Skip to content
Snippets Groups Projects
breath_plot.html 46.1 KiB
Newer Older
  <!--
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>

Robert L. Read's avatar
Robert L. Read committed
  <script src='./js/respiration_math.js'></script>
    <title>Public Invention Respiration Analysis</title>

</head>
  <style>
#timetop {
  display: flex;
  flex-direction:row;
  justify-content: space-between;
  background: AliceBlue;
}
#leftjustify {
  display: flex;
  flex-direction:row;
  justify-content: flex-start;
}
button {
  margin-left: 10px;
  margin-right: 10px;
}
#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>

      <div id="control_area">
  <button id="control_area_button" type="button" class="btn btn-primary">START</button>
        </div>
  <label for="livetoggle">Plot Live:</label>
<label class="switch">
  <input type="checkbox" id="livetoggle" checked>
  <span class="slider round"></span>
  </label>
  <div id="leftjustify">
  <button type="button" class="btn btn-primary">5s</button>
  <button type="button" class="btn btn-primary">10s</button>
  <button type="button" class="btn btn-primary">15s</button>
  <button type="button" class="btn btn-primary">30s</button>
  <button type="button" class="btn btn-primary">60s</button>
  <button type="button" class="btn btn-primary">120s</button>
  <button type="button" class="btn btn-primary">180s</button>
  <button type="button" class="btn btn-primary">300s</button>
</div>
</div>

  <div class="container-fluid">
    <div class="row">
  <div class="col-9">
  <div id="timetop">
            <div class="alert alert-info" role="alert" id="time_start">
            Time of first sample
            </div>
            <div class="alert alert-info" role="alert" id="time_finish">
            Time of last sample
</div>
  </div>

            <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">Rise Time (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">Fall Time (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>
                  <label for="wob">W. of B. (J/L): </label>
                  <div class="value_and_fences">
                    <div class="calcnum">
                      <label id="wob"> </label>
                    </div>
                    <div class="vertical_alarms">
                      <div class="limit max">
                        <label for="wob_h">H:</label>
                        <input class="fence" id="wob_h" type='text'> </input>
                    </div>
                    <div class="limit min">
                      <label for="wob_l">L:</label>
                      <input class="fence" id="wob_l" type='text'> </input>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div> <!-- end main area -->
  </div>

  <div>
  Parameters:
  <div>
        <label for="tarip_h">Rise/Fall High Pressure (cm H2O):</label>
  <input class="fence" id="tarip_h" type='text'> </input>
  </div>
  <div>
        <label for="tarip_l">Rise/Fall 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>

// I want a function to print times without milliseconds!!!!

if (!Date.prototype.toISOStringSeconds) {
  (function() {

    function pad(number) {
      if (number < 10) {
        return '0' + number;
      }
      return number;
    }

    Date.prototype.toISOStringSeconds = function() {
      return this.getUTCFullYear() +
        '-' + pad(this.getUTCMonth() + 1) +
        '-' + pad(this.getUTCDate()) +
        'T' + pad(this.getUTCHours()) +
        ':' + pad(this.getUTCMinutes()) +
        ':' + pad(this.getUTCSeconds()) +
        'Z';
    };

  })();
}

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 SAMPLES_BETWEEN_FIO2_REPORTS = 30000;

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 = 500;
var RESPIRATION_RATE_WINDOW_SECONDS = 60;

var intervalID = null;


// This sould be better as time, but is easier
// to do as number of samples.
var MAX_SAMPLES_TO_STORE_S = 16000;
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' || s.loc == 'I'));

    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);

      // not sure why I have null work, have to understand.
      var max_work_per_liter = 0;
      var work_per_liter = [];
      for(var i = 0; i < breaths.length; i++) {
        var b = breaths[i];
        if (b.work != null) {
          var wpl = b.work / b.vol_i;
          if (wpl > max_work_per_liter)
            max_work_per_liter = wpl;
          var center = ((trans[b.trans_begin_inhale].ms + trans[b.trans_cross_zero].ms) - 2*min) / (2.0 * 1000.0);
          work_per_liter.push({ wpl: wpl, center: center });
        }
      }

      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");


      var work_v = work_per_liter.map(w => (1/3) * (100 * w.wpl / max_work_per_liter));
      var t_work = work_per_liter.map(w => w.wpl.toFixed(2)+"J/L");
      var work_centers = unpack(work_per_liter, 'center');

      // 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,

                    };
      var workPlot = {type: "scatter", mode: "markers+text",
                     name: "WoB J",
                     textposition: 'bottom center',
                     x: work_centers,
                     y: work_v,
                     text: t_work,
                     marker: { size: 8,
                               color: 'blue',
                               symbol: 'triangle-right'}
                     };
      event_graph.push(workPlot);
      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, lc0, lc1, vf, tf) {
      var selected = samples.filter(s => s.event == 'M' && s.type == tp && (s.loc == lc0 || s.loc == lc1));
      return gen_graph(selected, name, color, textposition, vf, tf);
    }
    function gen_graph_measurement_timed(samples, name, color, textposition, tp, lc0, lc1, vf, tf,time_window_ms) {
      var messages = samples.filter(s => s.event == 'M' && s.type == tp && (s.loc == lc0 || s.loc == lc1));
      var separated = [];
      for(var i = 0; i < messages.length; i++) {
        var m = messages[i];
        if ((separated.length == 0) || ((separated.length > 0) && (separated[separated.length-1].ms < (m.ms - time_window_ms))))
          separated.push(m);
      }
      return gen_graph_measurement(separated, name, color, textposition, tp, lc0, lc1, 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_WINDOW_MS = 400;

      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 - TIME_WINDOW_MS))))
            lows.push(m);
        } else if (m.buff == FLOW_TOO_HIGH) {
          if ((highs.length == 0) || ((highs.length > 0) && (highs[highs.length-1].ms < (m.ms - TIME_WINDOW_MS))))
            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_timed(samples,
                                                 "FiO2 (%)",
                                                       "Black",'top center','O','I','A',
                                                 (v =>  "FiO2 : "+v.toFixed(1)+"%"),
                                                 // O2 reported only once every 10 seconds
                                                SAMPLES_BETWEEN_FIO2_REPORTS);
      event_graph.push(fio2AirwayPlot);
    }

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

    {
      // "null" here will never be matched, which is correct
      var humAmbientPlot = gen_graph_measurement(samples,"Hum (%)","CornflowerBlue",'bottom center','H','B',null,
                              (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','I','A',
                              (s => s.val/100.0),
                              (v =>  "T (I): "+v.toFixed(1)+"C"));
      event_graph.push(tempAirwayPlot);
    }

    {
      var tempAmbientPlot = gen_graph_measurement(samples,"Temp B","orange",'top center','T','B',null,
                              (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','I','B',null,
                              (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);
     }


    // 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;
}


var LIMITS = {
  max: { h: 40,
         l: 0},
  avg: { h: 30,
         l: 0},
  min: { h: 10,
         l: -10},
  mv: { h: 10,
         l: 1},
  bpm: { h: 40,
         l: 5},