glucose-stats.js 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. const moment = require('moment');
  2. const log = console.error;
  3. /* eslint-disable-next-line no-unused-vars */
  4. const error = console.error;
  5. const debug = console.error;
  6. module.exports = {};
  7. const calcStatsExports = module.exports;
  8. // Calculate the sum of the distance of all points (sod)
  9. // Calculate the overall distance between the first and the last point (overallDistance)
  10. // Calculate the noise as the following formula: 1 - sod / overallDistance
  11. // Noise will get closer to zero as the sum of the individual lines are mostly
  12. // in a straight or straight moving curve
  13. // Noise will get closer to one as the sum of the distance of the individual lines get large
  14. // Also add multiplier to get more weight to the latest BG values
  15. // Also added weight for points where the delta shifts from pos to neg or neg to pos (peaks/valleys)
  16. // the more peaks and valleys, the more noise is amplified
  17. // Input:
  18. // [
  19. // {
  20. // real glucose -- glucose value in mg/dL
  21. // real readDate -- milliseconds since Epoch
  22. // },...
  23. // ]
  24. const calcNoise = (sgvArr) => {
  25. let noise = 0;
  26. const n = sgvArr.length;
  27. const firstSGV = sgvArr[0].glucose * 1000.0;
  28. const firstTime = sgvArr[0].readDate / 1000.0 * 30.0;
  29. const lastSGV = sgvArr[n - 1].glucose * 1000.0;
  30. const lastTime = sgvArr[n - 1].readDate / 1000.0 * 30.0;
  31. const xarr = [];
  32. for (let i = 0; i < n; i += 1) {
  33. xarr.push(sgvArr[i].readDate / 1000.0 * 30.0 - firstTime);
  34. }
  35. // sod = sum of distances
  36. let sod = 0;
  37. let lastDelta = 0;
  38. for (let i = 1; i < n; i += 1) {
  39. // y2y1Delta adds a multiplier that gives
  40. // higher priority to the latest BG's
  41. let y2y1Delta = (sgvArr[i].glucose - sgvArr[i - 1].glucose) * 1000.0 * (1 + i / (n * 3));
  42. const x2x1Delta = xarr[i] - xarr[i - 1];
  43. if ((lastDelta > 0) && (y2y1Delta < 0)) {
  44. // switched from positive delta to negative, increase noise impact
  45. y2y1Delta *= 1.1;
  46. } else if ((lastDelta < 0) && (y2y1Delta > 0)) {
  47. // switched from negative delta to positive, increase noise impact
  48. y2y1Delta *= 1.2;
  49. }
  50. lastDelta = y2y1Delta;
  51. sod += Math.sqrt(Math.pow(x2x1Delta, 2) + Math.pow(y2y1Delta, 2));
  52. }
  53. const overallsod = Math.sqrt(Math.pow(lastSGV - firstSGV, 2) + Math.pow(lastTime - firstTime, 2));
  54. if (sod === 0) {
  55. // protect from divide by 0
  56. noise = 0;
  57. } else {
  58. noise = 1 - (overallsod / sod);
  59. }
  60. return noise;
  61. };
  62. calcStatsExports.calcSensorNoise = (calcGlucose, glucoseHist, lastCal, sgv) => {
  63. const MAXRECORDS = 8;
  64. const MINRECORDS = 4;
  65. const sgvArr = [];
  66. const numRecords = Math.max(glucoseHist.length - MAXRECORDS, 0);
  67. for (let i = numRecords; i < glucoseHist.length; i += 1) {
  68. // Only use values that are > 30 to filter out invalid values.
  69. if (lastCal && (glucoseHist[i].glucose > 30) && ('unfiltered' in glucoseHist[i]) && (glucoseHist[i].unfiltered > 100)) {
  70. // use the unfiltered data with the most recent calculated calibration value
  71. // this will provide a noise calculation that is independent of calibration jumps
  72. sgvArr.push({
  73. glucose: calcGlucose(glucoseHist[i], lastCal),
  74. readDate: glucoseHist[i].readDateMills,
  75. });
  76. } else if (glucoseHist[i].glucose > 30) {
  77. // if raw data isn't available, use the transmitter calibrated glucose
  78. sgvArr.push({
  79. glucose: glucoseHist[i].glucose,
  80. readDate: glucoseHist[i].readDateMills,
  81. });
  82. }
  83. }
  84. if (sgv) {
  85. if (lastCal && 'unfiltered' in sgv && sgv.unfiltered > 100) {
  86. sgvArr.push({
  87. glucose: calcGlucose(sgv, lastCal),
  88. readDate: sgv.readDateMills,
  89. });
  90. } else {
  91. sgvArr.push({
  92. glucose: sgv.glucose,
  93. readDate: sgv.readDateMills,
  94. });
  95. }
  96. }
  97. if (sgvArr.length < MINRECORDS) {
  98. return 0;
  99. }
  100. return calcNoise(sgvArr);
  101. };
  102. // Return 10 minute trend total
  103. calcStatsExports.calcTrend = (calcGlucose, glucoseHist, lastCal, sgv) => {
  104. let sgvHist = null;
  105. let trend = 0;
  106. if (glucoseHist.length > 0) {
  107. let maxDate = null;
  108. let timeSpan = 0;
  109. let totalDelta = 0;
  110. const currentTime = sgv ? moment(sgv.readDateMills)
  111. : moment(glucoseHist[glucoseHist.length - 1].readDateMills);
  112. sgvHist = [];
  113. // delete any deltas > 16 minutes and any that don't have an unfiltered value (backfill records)
  114. let minDate = currentTime.valueOf() - 16 * 60 * 1000;
  115. for (let i = 0; i < glucoseHist.length; i += 1) {
  116. if (lastCal && (glucoseHist[i].readDateMills >= minDate) && ('unfiltered' in glucoseHist[i]) && (glucoseHist[i].unfiltered > 100)) {
  117. sgvHist.push({
  118. glucose: calcGlucose(glucoseHist[i], lastCal),
  119. readDate: glucoseHist[i].readDateMills,
  120. });
  121. } else if (glucoseHist[i].readDateMills >= minDate) {
  122. sgvHist.push({
  123. glucose: glucoseHist[i].glucose,
  124. readDate: glucoseHist[i].readDateMills,
  125. });
  126. }
  127. }
  128. if (sgv) {
  129. if (lastCal && ('unfiltered' in sgv) && (sgv.unfiltered > 100)) {
  130. sgvHist.push({
  131. glucose: calcGlucose(sgv, lastCal),
  132. readDate: sgv.readDateMills,
  133. });
  134. } else {
  135. sgvHist.push({
  136. glucose: sgv.glucose,
  137. readDate: sgv.readDateMills,
  138. });
  139. }
  140. }
  141. if (sgvHist.length > 1) {
  142. minDate = sgvHist[0].readDate;
  143. maxDate = sgvHist[sgvHist.length - 1].readDate;
  144. // Use the current calibration value to calculate the glucose from the
  145. // unfiltered data. This allows the trend calculation to be independent
  146. // of the calibration jumps
  147. totalDelta = sgvHist[sgvHist.length - 1].glucose - sgvHist[0].glucose;
  148. timeSpan = (maxDate - minDate) / 1000.0 / 60.0;
  149. trend = 10 * totalDelta / timeSpan;
  150. }
  151. } else {
  152. debug(`Not enough history for trend calculation: ${glucoseHist.length}`);
  153. }
  154. return trend;
  155. };
  156. // Return sensor noise
  157. calcStatsExports.calcNSNoise = (noise, glucoseHist) => {
  158. let nsNoise = 0; // Unknown
  159. const currSGV = glucoseHist[glucoseHist.length - 1];
  160. let deltaSGV = 0;
  161. if (glucoseHist.length > 1) {
  162. const priorSGV = glucoseHist[glucoseHist.length - 2];
  163. if ((currSGV.glucose > 30) && (priorSGV.glucose > 30)) {
  164. deltaSGV = currSGV.glucose - priorSGV.glucose;
  165. }
  166. }
  167. if (!currSGV) {
  168. nsNoise = 1;
  169. } else if (currSGV.glucose > 400) {
  170. log(`Glucose ${currSGV.glucose} > 400 - setting noise level Heavy`);
  171. nsNoise = 4;
  172. } else if (currSGV.glucose < 40) {
  173. log(`Glucose ${currSGV.glucose} < 40 - setting noise level Light`);
  174. nsNoise = 2;
  175. } else if (Math.abs(deltaSGV) > 30) {
  176. // This is OK even during a calibration jump because we don't want OpenAPS to be too
  177. // agressive with the "false" trend implied by a large positive jump
  178. log(`Glucose change ${deltaSGV} out of range [-30, 30] - setting noise level Heavy`);
  179. nsNoise = 4;
  180. } else if (noise < 0.35) {
  181. nsNoise = 1; // Clean
  182. } else if (noise < 0.5) {
  183. nsNoise = 2; // Light
  184. } else if (noise < 0.7) {
  185. nsNoise = 3; // Medium
  186. } else if (noise >= 0.7) {
  187. nsNoise = 4; // Heavy
  188. }
  189. return nsNoise;
  190. };
  191. calcStatsExports.NSNoiseString = (nsNoise) => {
  192. switch (nsNoise) {
  193. case 1:
  194. return 'Clean';
  195. case 2:
  196. return 'Light';
  197. case 3:
  198. return 'Medium';
  199. case 4:
  200. return 'Heavy';
  201. case 0:
  202. default:
  203. return 'Unknown';
  204. }
  205. };