Skip to content
Snippets Groups Projects
breath_plot.html 52.4 KiB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735
  <!--
Breath Plot: COVID-19 Respiration Analysis Software
    Copyright (C) 2020  Robert L. Read

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as
    published by the Free Software Foundation, either version 3 of the
    License, or (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
  -->
<!doctype html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">

	<!-- Load plotly.js into the DOM -->
  <script src='https://cdn.plot.ly/plotly-latest.min.js'></script>

    <title>Public Invention Respiration Analysis</title>

</head>
  <style>
#calcarea {
  flex-direction:column;
  background: AliceBlue;
}
.calcnum {
    color: blue;
    font-size: xx-large;
}
.fence {
width: 3em;
}
.value_and_fences {
  display: flex;
flex-direction: row;
justify-content: space-between;
}
.limit {
  display: flex;
  flex-direction: row;
}
.limit  label {
   width: 1em;
}

  .alarmred {
    background: red;
  }

</style>

<!-- Style for toggle switch -->
  <style>
  .switch {
  position: relative;
  display: inline-block;
  width: 60px;
  height: 34px;
}

.switch input {
  opacity: 0;
  width: 0;
  height: 0;
}

.slider {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #ccc;
  -webkit-transition: .4s;
  transition: .4s;
}

.slider:before {
  position: absolute;
  content: "";
  height: 26px;
  width: 26px;
  left: 4px;
  bottom: 4px;
  background-color: white;
  -webkit-transition: .4s;
  transition: .4s;
}

input:checked + .slider {
  background-color: #2196F3;
}

input:focus + .slider {
  box-shadow: 0 0 1px #2196F3;
}

input:checked + .slider:before {
  -webkit-transform: translateX(26px);
  -ms-transform: translateX(26px);
  transform: translateX(26px);
}

/* Rounded sliders */
.slider.round {
  border-radius: 34px;
}

.slider.round:before {
  border-radius: 50%;
}
</style>
  <body>

    <div class="container-fluid">

      <div class="jumbotron">
        <h1 class="display-4">VentMon Respiration Analysis</h1>
        <p class="lead">This is a work in progress of <a href="https://www.pubinv.org">Public Invention</a>. It can be attached to a data server to produce
an interactive or static analysis of a respiration. It&#39;s primary purpose is to test pandemic ventilators, but it is free software meant to be reused for other purposes.
        </p>
      </div>




      <div class="input-group mb-3">
        <div class="input-group-prepend">
          <span class="input-group-text" id="basic-addon3">PIRDS data server url:</span>
        </div>
        <input type="text" class="form-control" id="dserverurl" aria-describedby="basic-addon3">

        <div class="input-group-append">
          <a class="btn btn-outline-dark btn-sm" href="#" role="button" id="useofficial">Use Ventmon Data Lake: ventmon.coslabs.com</a>
        </div>
      </div>

      <div class="input-group mb-3">
        <div class="input-group-prepend">
          <span class="input-group-text" id="basic-addon3">Trace ID:</span>
        </div>
        <input type="text" class="form-control" id="traceid" aria-describedby="basic-addon3">
      </div>

      <div class="input-group mb-3">
        <div class="input-group-prepend">
  <span class="input-group-text" for="samples_to_plot">Number of Samples (~10s per 15000 samples):</span>
        </div>
        <input type="text" class="form-control" id="samples_to_plot" aria-describedby="samples_to_plot">
      </div>


  <label for="livetoggle">Plot Live:</label>
<label class="switch">
  <input type="checkbox" id="livetoggle" checked>
  <span class="slider round"></span>
</label>

  <div class="container-fluid">
    <div class="row">
          <div class="col-9">
            <div id='PFGraph'><!-- Pressure and Flow Graph --></div>
            <div id='EventsGraph'><!-- Events --></div>
          </div>
          <div class="col-3">
            <div class="alert alert-danger" role="alert" id="main_alert">
  Danger! Flow limits exceeded; volumes will be incorrect.
            </div>
            <div class="container" id="calcarea">
              <div>
                <label for="max">PIP (max): </label>
                  <div class="value_and_fences">
                    <div class="calcnum">
                      <label id="max"> </label>
                    </div>
                    <div class="vertical_alarms">
                    <div class="limit max">
                      <label for="max_h">H:</label>
                      <input class="fence" id="max_h" type='text'> </input>
                    </div>
                    <div class="limit min">
                      <label for="max_l">L:</label>
                      <input class="fence" id="max_l" type='text'> </input>
                    </div>
                    </div>
                  </div>
             </div>
             <div>
                <label for="avg">P. Mean: </label>
                  <div class="value_and_fences">
                    <div class="calcnum">
                      <label id="avg"> </label>
                    </div>
                    <div class="vertical_alarms">
                    <div class="limit max">
                      <label for="avg_h">H:</label>
                      <input class="fence" id="avg_h" type='text'> </input>
                    </div>
                    <div class="limit min">
                      <label for="avg_l">L:</label>
                      <input class="fence" id="avg_l" type='text'> </input>
                    </div>
                    </div>
                  </div>
             </div>
             <div>
                <label for="min">PEEP (min): </label>
                  <div class="value_and_fences">
                    <div class="calcnum">
                      <label id="min"> </label>
                    </div>
                    <div class="vertical_alarms">
                    <div class="limit max">
                      <label for="min_h">H:</label>
                      <input class="fence" id="min_h" type='text'> </input>
                    </div>
                    <div class="limit min">
                      <label for="min_l">L:</label>
                      <input class="fence" id="min_l" type='text'> </input>
                    </div>
                    </div>
                  </div>
             </div>
             <div>
                <label for="mv">MVs (l/min): </label>
                  <div class="value_and_fences">
                    <div class="calcnum">
                      <label id="mv"> </label>
                    </div>
                    <div class="vertical_alarms">
                    <div class="limit max">
                      <label for="mv_h">H:</label>
                      <input class="fence" id="mv_h" type='text'> </input>
                    </div>
                    <div class="limit min">
                      <label for="mv_l">L:</label>
                      <input class="fence" id="mv_l" type='text'> </input>
                    </div>
                    </div>
                  </div>
                </div>
              <div>
                <label for="bpm">RR: </label>
                  <div class="value_and_fences">
                    <div class="calcnum">
                      <label id="bpm"> </label>
                    </div>
                    <div class="vertical_alarms">
                    <div class="limit max">
                      <label for="bmp_h">H:</label>
                      <input class="fence" id="bpm_h" type='text'> </input>
                    </div>
                    <div class="limit min">
                      <label for="bpm_l">L:</label>
                      <input class="fence" id="bpm_l" type='text'> </input>
                    </div>
                    </div>
                  </div>
                </div>
                <div>
                  <label for="ier">I:E ratio: </label>
                  <div class="value_and_fences">
                    <div class="calcnum">
                      <label id="ier"> </label>
                    </div>
                    <div class="vertical_alarms">
                    <div class="limit max">
                      <label for="ier_h">H:</label>
                      <input class="fence" id="ier_h" type='text'> </input>
                    </div>
                    <div class="limit min">
                      <label for="ier_l">L:</label>
                      <input class="fence" id="ier_l" type='text'> </input>
                    </div>
                    </div>
                  </div>
              </div>
                <div>
                <label for="tv">VTd (ml): </label>
                  <div class="value_and_fences">
                    <div class="calcnum">
                      <label id="tv"> </label>
                    </div>
                    <div class="vertical_alarms">
                    <div class="limit max">
                      <label for="tv_h">H:</label>
                      <input class="fence" id="tv_h" type='text'> </input>
                    </div>
                    <div class="limit min">
                      <label for="tv_l">L:</label>
                      <input class="fence" id="tv_l" type='text'> </input>
                    </div>
                    </div>
                  </div>
              </div>
                <div>
                  <label for="fio2">FiO2 Mean (%): </label>
                  <div class="value_and_fences">
                    <div class="calcnum">
                      <label id="fio2"> </label>
                    </div>
                    <div class="vertical_alarms">
                      <div class="limit max">
                        <label for="fio2_h">H:</label>
                        <input class="fence" id="fio2_h" type='text'> </input>
                    </div>
                    <div class="limit min">
                      <label for="fio2_l">L:</label>
                      <input class="fence" id="fio2_l" type='text'> </input>
                    </div>
                  </div>
                </div>
                <div>
                  <label for="taip">TAIP (ms): </label>
                  <div class="value_and_fences">
                    <div class="calcnum">
                      <label id="taip"> </label>
                    </div>
                    <div class="vertical_alarms">
                      <div class="limit max">
                        <label for="taip_h">H:</label>
                        <input class="fence" id="taip_h" type='text'> </input>
                    </div>
                    <div class="limit min">
                      <label for="taip_l">L:</label>
                      <input class="fence" id="taip_l" type='text'> </input>
                    </div>
                  </div>
                </div>
              </div>
                <div>
                  <label for="taip">TRIP (ms): </label>
                  <div class="value_and_fences">
                    <div class="calcnum">
                      <label id="trip"> </label>
                    </div>
                    <div class="vertical_alarms">
                      <div class="limit max">
                        <label for="trip_h">H:</label>
                        <input class="fence" id="trip_h" type='text'> </input>
                    </div>
                    <div class="limit min">
                      <label for="trip_l">L:</label>
                      <input class="fence" id="trip_l" type='text'> </input>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div> <!-- end main area -->
  </div>

  <div>
  Parameters:
  <div>
        <label for="tarip_h">TAIP/TRIP High Pressure (cm H2O):</label>
  <input class="fence" id="tarip_h" type='text'> </input>
  </div>
  <div>
        <label for="tarip_l">TAIP/TRIP Low Pressure (cm H2O):</label>
  <input class="fence" id="tarip_l" type='text'> </input>
  </div>
</div>

<div>
  <button id="import">Import Trace</button>
  <button id="export">Export Trace</button>
</div>
<div>
  <textarea id="json_trace" rows="30" cols="80"></textarea>
</div>

<p>
  This is a work in progress of <a href="https://www.pubinv.org">Public Invention</a>.

<p>
  This is a tester tool for open-source ventilators.
  It uses the <a href="https://github.com/PubInv/respiration-data-standard">PIRDS data format</a>.

<p>
  The basic operation is receive data from web server specified in the URL above.
  Probably for now that will be the VentMon Python web server that
  listens on a serial port for the VentMon device or any other
  device that streams PIRDS events.

</div>
</body>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

  <script>

var TAIP_AND_TRIP_MIN = 2;
var TAIP_AND_TRIP_MAX = 8;

function getParameterByName(name, url) {
    if (!url) url = window.location.href;
    name = name.replace(/[\[\]]/g, '\\$&');
    var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, ' '));
}

// These are defined in PIRDS.h as "constant" key words of special meaning...
var FLOW_LIMITS_EXCEEDED = false;
const FLOW_TOO_HIGH = "FLOW OUT OF RANGE HIGH";
const FLOW_TOO_LOW = "FLOW OUT OF RANGE LOW";

const VENTMON_DATA_LAKE = "http://ventmon.coslabs.com";
const queryString = window.location.search;
const urlParams = new URLSearchParams(queryString);
var TRACE_ID = urlParams.get('i')
var DSERVER_URL = window.location.protocol + "//" + window.location.host;
var NUM_TO_READ = 500;

var DATA_RETRIEVAL_PERIOD = 50;

var RESPIRATION_RATE_WINDOW_SECONDS = 20;

var intervalID = null;


// This sould be better as time, but is easier
// to do as number of samples.
var MAX_SAMPLES_TO_STORE_S = 32000;
var samples = [];
var INITS_ONLY = true;

// This is just to get the party started!
function init_samples() {
    return [
	{
	    "event": "M",
	    "type": "P",
	    "ms": 19673310,
	    "loc": "A",
	    "num": "0",
	    "val": 10111
	},
	{
	    "event": "M",
	    "type": "D",
	    "ms": 19673310,
	    "loc": "A",
	    "num": "0",
	    "val": 4
	},
	{
	    "event": "M",
	    "type": "F",
	    "ms": 19673310,
	    "loc": "A",
	    "num": "0",
	    "val": 0
	},
	{
	    "event": "M",
	    "type": "P",
	    "ms": 19673376,
	    "loc": "A",
	    "num": "0",
	    "val": 10111
	},
	{
	    "event": "M",
	    "type": "D",
	    "ms": 19673376,
	    "loc": "A",
	    "num": "0",
	    "val": 4
	},
	{
	    "event": "M",
	    "type": "F",
	    "ms": 19673376,
	    "loc": "A",
	    "num": "0",
	    "val": 0
	},
	{
	    "event": "M",
	    "type": "P",
	    "ms": 19673442,
	    "loc": "A",
	    "num": "0",
	    "val": 10110
	},
	{
	    "event": "M",
	    "type": "D",
	    "ms": 19673442,
	    "loc": "A",
	    "num": "0",
	    "val": 3
	},
    ];
}



function unpack(rows, key) {
    return rows.map(function(row) { return row[key]; });
}

const CONVERT_PIRDS_TO_SLM = 1/1000;

// we have now changed this, there will be flow and
// pressure in the same samples, and we should filter.
// TODO: I need to add maximal start and end
// samples to equalize all the plots.
function samplesToLine(samples) {
    var flows = samples.filter(s => s.event == 'M' && s.type == 'F');

    // These are slm/1000, or ml/minute...
    // so we multiply by 1000 to get liters per minute
    var flow_values = unpack(flows,"val").map(v => v * CONVERT_PIRDS_TO_SLM);
    var fmillis = unpack(flows, 'ms');
    // Convert to seconds...
    var fmin = Math.min(...fmillis);
    var fzeroed = fmillis.map(m =>(m-fmin)/1000.0);

    var pressures = samples.filter(s => s.event == 'M' && s.type == 'D' && s.loc == 'A');

    var pmillis = unpack(pressures, 'ms');
    var pmin = Math.min(...pmillis);
    var pzeroed = pmillis.map(m =>(m-pmin)/1000.0);
    // the PIRDS standard is integral mm H2O, so we divide by 10
    var delta_p = unpack(pressures, 'val').map(p => p / 10);
    var diff_p = {type: "scatter", mode: "lines",
		  name: "pressure",
		  x: pzeroed,
		  y: delta_p,
		  line: {color: "#FF0000"}
		 };

  var flow = {type: "scatter", mode: "lines",
		name: "flow",
		x: fzeroed,
	      y: flow_values,
              xaxis: 'x2',
              yaxis: 'y2',
              fill: 'tozeroy',
		line: {color: '#0000FF'}
             };

  var max_flow = flow_values.reduce(
    function(a, b) {
      return Math.max(Math.abs(a), Math.abs(b));
    }
    ,0);
  var scaled_flow = flow_values.map(f => 100.0 * (f / max_flow));
  var flow_hollow = {type: "scatter", mode: "lines",
		name: "flow ghost",
		     x: fzeroed,
                     // Convert to a percentage
	             y: scaled_flow,
		line: {color: '#8888FF'}
               };
  return [diff_p,flow,flow_hollow];
}
function plot(samples, trans, breaths) {
  var new_data = samplesToLine(samples);
  var millis = unpack(samples, 'ms');
  var min = Math.min(...millis);
  var zeroed = millis.map(m =>(m-min)/1000.0);

  {
    var layout = {
      title: 'VentMon Breath Analysis',
      showlegend: false,
      xaxis: {domain: [0.0,1.0]},
      yaxis: {
        title: 'Airway P(cm H2O)',
        titlefont: {color: 'red'},
        tickfont: {color: 'red'},
      },
      xaxis2: {domain: [0.0,1.0]},
      yaxis2: {
        title: 'Flow l/minute',
        titlefont: {color: 'blue'},
        tickfont: {color: 'blue'}
      },
      grid: {
        rows: 2,
        columns: 1,
        pattern: 'independent',
        roworder: 'top to bottom'}
    }

    var double_plot = [new_data[0],new_data[1]];

    Plotly.newPlot('PFGraph', double_plot, layout);
  }

  // The Y-axis for the events will be percentage.
  // This is somewhat abstract; each trace has
  // a different meaning. In general it will be
  // % as a function of some known value, which
  // will be either a limit or a min or max.
  {
    var event_graph = [];
    if (trans) {
      // Transitions are simply scaled to 50%.
      var tmillis = unpack(trans, 'ms');
      var tzeroed = tmillis.map(m =>(m-min)/1000.0);
      var tstates = unpack(trans, 'state');
      var tstates_amped = tstates.map(m =>m*50);
      var transPlot = {type: "scatter",
                       mode: "lines+markers",
		       name: "trans",
		       x: tzeroed,
		       y: tstates_amped,
                       line: {shape: 'hv',
                              color: 'dkGreen'},
		      };
      // We add a hollow flow line to see in position..
      event_graph.push(new_data[2]);
      event_graph.push(transPlot);
    }

    if (breaths) {
      var bmillis = unpack(breaths, 'ms');
      var bzeroed = bmillis.map(m =>(m-min)/1000.0);
      // I'm goint to a add start and end transition to make the plot
      // come out right
      var ys = breaths.map( b => 0);
      var breathPlot = {type: "scatter", mode: "markers",
		        name: "Transitions",
		        x: bzeroed,
		        y: ys,
		        marker: { size: 8, color: "red",symbol: "diamond" },
                        textposition: 'bottom center',
                        text: bzeroed
		       };
      event_graph.push(breathPlot);
      // Now I attempt to extract volumes...
      // Our breaths mark the END of a breath..
      // so we want to draw the volumes that way.
      const volume_ht_factor = 20;
      var max_exh = unpack(breaths,'vol_e').reduce(
        function(a, b) {
          return Math.max(Math.abs(a), Math.abs(b));
        }
        ,0);
      var max_inh = unpack(breaths,'vol_i').reduce(
        function(a, b) {
          return Math.max(Math.abs(a), Math.abs(b));
        }
        ,0);
      var max_v = Math.max(max_inh,max_exh);

      var exh_v = unpack(breaths, 'vol_e').map(e => 100 * e / max_v);
      var t_exh_v =  unpack(breaths, 'vol_e').map(e => Math.round(e*1000.0)+"ml exh");
      var inh_v = unpack(breaths, 'vol_i').map(i => 100 * i / max_v);
      var t_inh_v = unpack(breaths, 'vol_i').map(e => Math.round(e*1000.0)+"ml inh");
      // now to graph properly, I must find the center of an inhalation.
      // I have packed these into the breaths...
      var inhale_centers = breaths.map(b => ((trans[b.trans_begin_inhale].ms + trans[b.trans_cross_zero].ms) - 2*min) / (2.0 * 1000.0));
      var exhale_centers = breaths.map(b => ((trans[b.trans_cross_zero].ms + trans[b.trans_end_exhale].ms) - 2*min) / (2.0 * 1000.0));

      var inhPlot = {type: "scatter", mode: "markers+text",
                     name: "Inh. ml",
                     textposition: 'bottom center',
                     x: inhale_centers,
                     y: inh_v,
                     text: t_inh_v,
                     marker: { size: 8,
                               color: 'black',
                               symbol: 'triangle-down'}
                    };
      var exhPlot = {type: "scatter", mode: "markers+text",
                     name: "Exh. ml",
                     textposition: 'top center',
                     marker : {
                       sizer: 12,
                       color: 'green',
                       symbol: 'triangle-up' },
                     x: exhale_centers,
                     y: exh_v,
                     text: t_exh_v,

                    };
      event_graph.push(inhPlot);
      event_graph.push(exhPlot);
    }

    // Now I will attempt to add other markers, such as Humidity, Altitude, and other events,
    // including possible warning events.

    function gen_graph_measurement(samples, name, color, textposition, tp, lc, vf, tf) {
      var selected = samples.filter(s => s.event == 'M' && s.type == tp && s.loc == lc);
      return gen_graph(selected, name, color, textposition, vf, tf);
    }
    function gen_graph(selected,name,color, textposition, vf, tf) {
      var millis = unpack(selected, 'ms');
      var zeroed = millis.map(m =>(m-min)/1000.0);
      var vs = selected.map(vf);
      var vs_t = vs.map(tf);
      var plot = {type: "scatter", mode: "markers+text",
                     name: name,
                     textposition: textposition,
                     x: zeroed,
                     y: vs,
                     text: vs_t,
                     marker: { size: 10, color: color }
                    };
      return plot;

    }
    function gen_message_events(samples,name,color, textposition) {
      var messages = samples.filter(s => s.event == 'E' && s.type == 'M');
      // Now I want to filter our all flow error messages...
      // There are two special ones, "FLOW OUT OF RANGE LOW" and
      // "FLOW OUT OF RANGE HIGH"
      // Basically, we will show only the first of these in a "run"
      // This is rather difficult; we will instead just use 200 ms
      // as a window.
      const time_windwow_ms = 200;

      var lows = [];
      var highs = [];
      var others = [];
      for(var i = 0; i < messages.length; i++) {
        var m = messages[i];
        if (m.buff == FLOW_TOO_LOW) {
          if ((lows.length == 0) || ((lows.length > 0) && (lows[lows.length-1].ms < (m.ms - 200))))
            lows.push(m);
        } else if (m.buff == FLOW_TOO_HIGH) {
          if ((highs.length == 0) || ((highs.length > 0) && (highs[highs.length-1].ms < (m.ms - 200))))
            highs.push(m);
        } else {
          others.push(m);
        }
      }
      if (lows.length > 0 || highs.length > 0) {
        set_flow_alert();
      } else {
        unset_flow_alert();
      }

      var lowsPlot = gen_graph(lows,"Low Range","blue",'top center',
                                    (s => -90.0),
                                    (v =>  "LOW"));
      var highsPlot = gen_graph(highs,"High Range","red",'bottom center',
                                    (s => 90.0),
                                    (v =>  "HIGH"));
      var othersPlot = gen_graph(others,"messages","Aqua",'top center',
                                    (s => -75.0),
                                 (v =>  v.buff));
      return [lowsPlot,highsPlot,othersPlot];
    }
    {
      var fio2AirwayPlot = gen_graph_measurement(samples,"FiO2 (%)","Black",'top center','O','A',
                              (s => s.val),
                              (v =>  "FiO2 (A): "+v.toFixed(1)+"%"));
      event_graph.push(fio2AirwayPlot);
    }

    {
      var humAirwayPlot = gen_graph_measurement(samples,"Hum (%)","Aqua",'top center','H','A',
                              (s => s.val/100.0),
                              (v =>  "H2O (A): "+v.toFixed(0)+"%"));
      event_graph.push(humAirwayPlot);
    }

    {
      var humAmbientPlot = gen_graph_measurement(samples,"Hum (%)","CornflowerBlue",'bottom center','H','B',
                              (s => -s.val/100.0),
                                      (v =>  "H2O (B): "+(-v).toFixed(0)+"%"));
      event_graph.push(humAmbientPlot);
    }

    {
      var tempAirwayPlot = gen_graph_measurement(samples,"Temp A","red",'bottom center','T','A',
                              (s => s.val/100.0),
                              (v =>  "T (A): "+v.toFixed(1)+"C"));
      event_graph.push(tempAirwayPlot);
    }

    {
      var tempAmbientPlot = gen_graph_measurement(samples,"Temp B","orange",'top center','T','B',
                              (s => -s.val/100.0),
                                      (v =>  "T (B): "+(-v).toFixed(1)+"C"));
      event_graph.push(tempAmbientPlot);
    }

    // Altitude is really just a check that the system is working
     {
      var altAmbientPlot = gen_graph_measurement(samples,"Altitude","purple",'right','A','B',
                              (s => s.val/20.0),
                                      (v =>  "Alt: "+(v*20.0).toFixed(0)+"m"));
      event_graph.push(altAmbientPlot);
     }

     {
       var [l,h,o] = gen_message_events(samples,"Message","red",'right');
       event_graph.push(l);
       event_graph.push(h);
       event_graph.push(o);
     }



    // The BME680 sensor detects VOC gases. I don't think has any clinical value
    // compared

    // {
    //   var gasAirwayPlot = gen_graph_measurement(samples,"Gas A","yellow",'bottom center','G','A',
    //                           (s => s.val/1000.0),
    //                                 (v =>  "G (A): "+(v*100).toFixed(1)+"Ohms"));
    //   event_graph.push(gasAirwayPlot);
    // }

    // {
    //   var gasAmbientPlot = gen_graph_measurement(samples,"Gas B","gold",'top center','G','B',
    //                           (s => -s.val/1000.0),
    //                                   (v =>  "G (B): "+(-v*100).toFixed(1)+"Ohms"));
    //   event_graph.push(gasAmbientPlot);
    // }



    // I'm going to try putting the pressure
    // in faintly to make the graphs match

    var event_layout = {
      title: 'Events',
      showlegend: false,
      xaxis: {domain: [0.0,1.0]},
      yaxis: {
        range: [-100.0, 100.0]
      },
    };
    Plotly.newPlot('EventsGraph', event_graph,event_layout);
  }
}

function set_flow_alert() {
  $("#main_alert").show();
}
function unset_flow_alert() {
  $("#main_alert").hide();
}

function check_alarms(limits,key,limit,val,f,ms) {
  var alarms = [];
  if (limits[key][limit] && (f(val,limits[key][limit]))) {
    alarms.push({param: key,
                 limit: limit,
                 val: val,
                 ms: ms});
  }
  return alarms;
}


// Return, [min,avg,max] pressures (no smoothing)!
function compute_pressures(secs,samples) {
  var pressures = samples.filter(s => s.event == 'M' && s.type == 'D' && s.loc == 'A');

  if (pressures.length == 0) {
    return [0,0,0,[]];
  } else {
    const recent_ms = pressures[pressures.length - 1].ms;
    var cur_ms = recent_ms;
    var cnt = 0.0;
    var i = pressures.length - 1;
    var cur_sample = pressures[i];

    var min = Number.MAX_VALUE;
    var max = Number.MIN_VALUE;
    var sum = 0;
    var alarms = [];
    while((i >=0) && (pressures[i].ms > (cur_ms - secs*1000))) {
      var p = pressures[i].val / 10.0;  // this is now cm H2O
      if (p < min ) {
        min = p;
      }
      if (p > max) {
        max = p;
      }
      sum += p;
      cnt++;
      alarms = alarms.concat(check_alarms(LIMITS,"max","h",p,(a,b) =>(a > b),pressures[i].ms));
      alarms = alarms.concat(check_alarms(LIMITS,"max","l",p,(a,b) =>(a < b),pressures[i].ms));
      i--;
    }
    return [min,sum/cnt,max,alarms];
  }
}

function compute_fio2_mean(secs,samples) {
  var oxygens = samples.filter(s => s.event == 'M' && s.type == 'O' && s.loc == 'A');

  if (oxygens.length == 0) {
    return null;
  } else {
    const recent_ms = oxygens[oxygens.length - 1].ms;
    var cur_ms = recent_ms;
    var cnt = 0.0;
    var i = oxygens.length - 1;

    var sum = 0;
    var alarms = [];
    while((i >=0) && (oxygens[i].ms > (cur_ms - secs*1000))) {
      var oxy = oxygens[i].val; // oxygen concentration as a percentage
      sum += oxy;
      cnt++;
      i--;
    }

    var fio2_avg = sum / cnt;

    return fio2_avg;
  }
}


function compute_respiration_rate(secs,samples,transitions,breaths) {
  // In order to compute the number of breaths
  // in the last s seconds, I compute those breaths
  // whose time stamp is s seconds from the most recent sample

  // We will compute respiration rate by counting breaths
  // and dividing (cnt - 1) by time the first and last inhalation
  var first_inhale_ms = -1;
  var last_inhale_ms = -1;
  if (breaths.length == 0) {
    return [0,0,0,"NA"];
  } else {
    const recent_ms = samples[samples.length - 1].ms;
    var cur_ms = recent_ms;
    var cnt = 0.0;
    var vol_i = 0.0;
    var vol_e = 0.0;
    var i = breaths.length - 1;
    var time_inh = 0;
    var time_exh = 0;
    // fully completed inhalation volume does not include the
    // most recent breath; we need it to be able to accurately
    // divide by the inhlation_duration.
    var vol_ci = 0.0;

    while((i >=0) && (breaths[i].ms > (cur_ms - secs*1000))) {
      cnt++;
      vol_i += breaths[i].vol_i;
      if (i < (breaths.length -1)) {
        vol_ci += breaths[i].vol_i;
      }
      vol_e += breaths[i].vol_e;

      const inh_ms = transitions[breaths[i].trans_begin_inhale].ms;
      // note i is counting down in this loop...
      if (last_inhale_ms < 0) last_inhale_ms = inh_ms;
      first_inhale_ms = inh_ms;
      const exh_ms = transitions[breaths[i].trans_end_exhale].ms;
      const zero_ms = transitions[breaths[i].trans_cross_zero].ms;
      time_inh += (zero_ms - inh_ms);
      time_exh += (exh_ms -  zero_ms);
      i--;
    }
    if ((cnt > 1) && (first_inhale_ms != last_inhale_ms)) {
      var inhalation_duration = last_inhale_ms - first_inhale_ms;
      var inhalation_duration_min = inhalation_duration / (60.0 * 1000.0);
      var rr = (cnt - 1) / inhalation_duration_min;
      var duration_minutes = secs / 60.0;

      // This is liters per minute. vol_ci is in liters.
      // inhalation_duration is in ms.
      var minute_volume =  vol_ci / inhalation_duration_min;

      var tidal_volume = 1000.0 * vol_i / cnt;

      var EIratio = (time_inh == 0) ? null : time_exh / time_inh;
      return  [
        rr,
        tidal_volume,
        minute_volume,
        EIratio];
    } else {
      return [0,0,0,"NA"];
    }