determine_basal.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. function middleware(iob, currenttemp, glucose, profile, autosens, meal, reservoir, clock, pumphistory, preferences) {
  2. // This middleware only works if you have added pumphistory and preferences to middleware in FreeAPS X code (my mw_preferences branch).
  3. const BG = glucose[0].glucose;
  4. // Change to false to turn off Chris Wilson's formula
  5. var chrisFormula = preferences.enableChris;
  6. const minLimitChris = profile.autosens_min;
  7. const maxLimitChris = profile.autosens_max;
  8. const adjustmentFactor = preferences.adjustmentFactor;
  9. const currentMinTarget = profile.min_bg;
  10. var exerciseSetting = false;
  11. var enoughData = false;
  12. var pumpData = 0;
  13. var log = "";
  14. var logTDD = "";
  15. var logBasal = "";
  16. var logBolus = "";
  17. var logTempBasal = "";
  18. var current = 0;
  19. // If you have not set this to 0.05 in FAX settings (Omnipod), this will be set to 0.1 in code.
  20. var minimalDose = profile.bolus_increment;
  21. var TDD = 0;
  22. var insulin = 0;
  23. var tempInsulin = 0;
  24. var bolusInsulin = 0;
  25. var scheduledBasalInsulin = 0;
  26. var incrementsRaw = 0;
  27. var incrementsRounded = 0;
  28. var quota = 0;
  29. if (profile.high_temptarget_raises_sensitivity == true || profile.exercise_mode == true) {
  30. exerciseSetting = true;
  31. }
  32. // Turn off Chris' formula (and AutoISF) when using a temp target >= 118 (6.5 mol/l) and if an exercise setting is enabled.
  33. // If using AutoISF uncomment the profile.use_autoisf = false
  34. if (currentMinTarget >= 118 && exerciseSetting == true) {
  35. // profile.use_autoisf = false;
  36. chrisFormula = false;
  37. log = "Dynamic ISF temporarily off due to a high temp target/exercising. Current min target: " + currentMinTarget;
  38. }
  39. // Check that there is enough pump history data (>23 hours) for TDD calculation, else end this middleware.
  40. if (chrisFormula == true) {
  41. let ph_length = pumphistory.length;
  42. let endDate = new Date(pumphistory[ph_length-1].timestamp);
  43. let startDate = new Date(pumphistory[0].timestamp);
  44. // If latest pump event is a temp basal
  45. if (pumphistory[0]._type == "TempBasalDuration") {
  46. startDate = new Date();
  47. }
  48. // > 23 hours
  49. pumpData = (startDate - endDate) / 36e5;
  50. if (pumpData >= 23) {
  51. enoughData = true;
  52. } else {
  53. chrisFormula = false;
  54. return "Dynamic ISF is temporarily off. 24 hours of data is required for a correct TDD calculation. Currently only " + pumpData.toPrecision(3) + " hours of pump history data available.";
  55. }
  56. }
  57. // Calculate TDD --------------------------------------
  58. //Bolus:
  59. for (let i = 0; i < pumphistory.length; i++) {
  60. if (pumphistory[i]._type == "Bolus") {
  61. bolusInsulin += pumphistory[i].amount;
  62. }
  63. }
  64. // Temp basals:
  65. if (minimalDose != 0.05) {
  66. minimalDose = 0.1;
  67. }
  68. for (let j = 1; j < pumphistory.length; j++) {
  69. if (pumphistory[j]._type == "TempBasal" && pumphistory[j].rate > 0) {
  70. current = j;
  71. quota = pumphistory[j].rate;
  72. var duration = pumphistory[j-1]['duration (min)'] / 60;
  73. var origDur = duration;
  74. var pastTime = new Date(pumphistory[j-1].timestamp);
  75. // If temp basal hasn't yet ended, use now as end date for calculation
  76. do {
  77. j--;
  78. if (j <= 0) {
  79. morePresentTime = new Date();
  80. break;
  81. } else if (pumphistory[j]._type == "TempBasal" || pumphistory[j]._type == "PumpSuspend") {
  82. morePresentTime = new Date(pumphistory[j].timestamp);
  83. break;
  84. }
  85. }
  86. while (j >= 0);
  87. var diff = (morePresentTime - pastTime) / 36e5;
  88. if (diff < origDur) {
  89. duration = diff;
  90. }
  91. insulin = quota * duration;
  92. // Account for smallest possible pump dosage
  93. incrementsRaw = insulin / minimalDose;
  94. if (incrementsRaw >= 1) {
  95. incrementsRounded = Math.floor(incrementsRaw);
  96. insulin = incrementsRounded * minimalDose;
  97. tempInsulin += insulin;
  98. } else { insulin = 0}
  99. j = current;
  100. }
  101. }
  102. // Check and count for when basals are delivered with a scheduled basal rate or an Autotuned basal rate.
  103. // 1. Check for 0 temp basals with 0 min duration. This is for when ending a manual temp basal and (perhaps) continuing in open loop for a while.
  104. // 2. Check for temp basals that completes. This is for when disconected from link/iphone, or when in open loop.
  105. // To do: need to check for more circumstances when scheduled basal rates are used.
  106. //
  107. for (let k = 0; k < pumphistory.length; k++) {
  108. // Check for 0 temp basals with 0 min duration.
  109. insulin = 0;
  110. if (pumphistory[k]['duration (min)'] == 0) {
  111. let time1 = new Date(pumphistory[k].timestamp);
  112. let time2 = time1;
  113. let l = k;
  114. do {
  115. --l;
  116. if (pumphistory[l]._type == "TempBasal" && l >= 0) {
  117. time2 = new Date(pumphistory[l].timestamp);
  118. break;
  119. }
  120. } while (l > 0);
  121. // duration of current scheduled basal in h
  122. let basDuration = (time2 - time1) / 36e5;
  123. if (basDuration > 0) {
  124. let hour = time1.getHours();
  125. let minutes = time1.getMinutes();
  126. let seconds = "00";
  127. let string = "" + hour + ":" + minutes + ":" + seconds;
  128. let baseTime = new Date(string);
  129. let basalScheduledRate = profile.basalprofile[0].start;
  130. for (let m = 0; m < profile.basalprofile.length; m++) {
  131. if (profile.basalprofile[m].start == baseTime) {
  132. basalScheduledRate = profile.basalprofile[m].rate;
  133. insulin = basalScheduledRate * basDuration;
  134. break;
  135. }
  136. else if (m + 1 < profile.basalprofile.length) {
  137. if (profile.basalprofile[m].start < baseTime && profile.basalprofile[m+1].start > baseTime) {
  138. basalScheduledRate = profile.basalprofile[m].rate;
  139. insulin = basalScheduledRate * basDuration;
  140. break;
  141. }
  142. }
  143. else if (m == profile.basalprofile.length - 1) {
  144. basalScheduledRate = profile.basalprofile[m].rate;
  145. insulin = basalScheduledRate * basDuration;
  146. break;
  147. }
  148. }
  149. // Account for smallest possible pump dosage
  150. incrementsRaw = insulin / minimalDose;
  151. if (incrementsRaw >= 1) {
  152. incrementsRounded = Math.floor(incrementsRaw);
  153. insulin = incrementsRounded * minimalDose;
  154. scheduledBasalInsulin += insulin;
  155. } else { insulin = 0;
  156. }
  157. }
  158. }
  159. }
  160. // Check for temp basals that completes
  161. for (let n = pumphistory.length -1; n > 0; n--) {
  162. if (pumphistory[n]._type == "TempBasalDuration") {
  163. // duration in hours
  164. let oldBasalDuration = pumphistory[n]['duration (min)'] / 60;
  165. // time of old temp basal
  166. let oldTime = new Date(pumphistory[n].timestamp);
  167. let newTime = oldTime;
  168. let o = n;
  169. do {
  170. --o;
  171. if (o >= 0) {
  172. if (pumphistory[o]._type == "TempBasal") {
  173. // time of next (new) temp basal
  174. newTime = new Date(pumphistory[o].timestamp);
  175. break;
  176. }
  177. }
  178. } while (o > 0);
  179. // When latest temp basal is index 0 in pump history
  180. if (n == 0 && pumphistory[0]._type == "TempBasalDuration") {
  181. newTime = new Date();
  182. oldBasalDuration = pumphistory[n]['duration (min)'] / 60;
  183. }
  184. // Time difference in hours, new - old
  185. let tempBasalTimeDifference = (newTime - oldTime) / 36e5;
  186. let timeOfbasal = tempBasalTimeDifference - oldBasalDuration;
  187. // if duration of scheduled basal is more than 0
  188. if (timeOfbasal > 0) {
  189. // Timestamp after completed temp basal
  190. let timeOfScheduledBasal = new Date(oldTime.getTime() + oldBasalDuration*36e5);
  191. let hour = timeOfScheduledBasal.getHours();
  192. let minutes = timeOfScheduledBasal.getMinutes();
  193. let seconds = "00";
  194. // "hour:minutes:00"
  195. let baseTime = "" + hour + ":" + minutes + ":" + seconds;
  196. // Default if correct basal schedule rate not found
  197. let basalScheduledRate = profile.basalprofile[0].rate;
  198. for (let p = 0; p < profile.basalprofile.length; ++p) {
  199. let basalRateTime = new Date(profile.basalprofile[p].start);
  200. if (basalRateTime == baseTime) {
  201. basalScheduledRate = profile.basalprofile[p].rate;
  202. break;
  203. }
  204. else if (p+1 < profile.basalprofile.length) {
  205. let nextBasalRateTime = new Date(profile.basalprofile[p+1].start);
  206. if (basalRateTime < baseTime && nextBasalRateTime > baseTime) {
  207. basalScheduledRate = profile.basalprofile[p].rate;
  208. break;
  209. }
  210. }
  211. else if (p == (profile.basalprofile.length - 1)) {
  212. basalScheduledRate = profile.basalprofile[p].rate;
  213. break;
  214. }
  215. }
  216. insulin = basalScheduledRate * timeOfbasal;
  217. // Account for smallest possible pump dosage
  218. incrementsRaw = insulin / minimalDose;
  219. if (incrementsRaw >= 1) {
  220. incrementsRounded = Math.floor(incrementsRaw);
  221. scheduledBasalInsulin += incrementsRounded * minimalDose;
  222. } else { insulin = 0}
  223. }
  224. }
  225. }
  226. TDD = bolusInsulin + tempInsulin + scheduledBasalInsulin;
  227. logBolus = ". Bolus insulin: " + bolusInsulin.toPrecision(5) + " U";
  228. logTempBasal = ". Temporary basal insulin: " + tempInsulin.toPrecision(5) + " U";
  229. logBasal = ". Delivered scheduled basal insulin: " + scheduledBasalInsulin.toPrecision(5) + " U";
  230. logTDD = ". TDD past 24h is: " + TDD.toPrecision(5) + " U";
  231. // ----------------------------------------------------
  232. // Chris' formula with added adjustmentFactor for tuning:
  233. if (chrisFormula == true && TDD > 0) {
  234. var newRatio = profile.sens / (277700 / (adjustmentFactor * TDD * BG));
  235. log = "New ratio using Dynamic ISF is " + newRatio.toPrecision(3) + " with ISF: " + (profile.sens / newRatio).toPrecision(3) + " (" + ((profile.sens / newRatio) * 0.0555).toPrecision(3) + " mmol/l/U)";
  236. // Respect autosens.max and autosens.min limits
  237. if (newRatio > maxLimitChris) {
  238. log = "Dynamic ISF hit limit by autosens_max setting: " + maxLimitChris + " (" + newRatio.toPrecision(3) + ")" + ". ISF: " + (profile.sens / maxLimitChris).toPrecision(3) + " (" + ((profile.sens / maxLimitChris) * 0.0555).toPrecision(3) + " mmol/l/U)";
  239. newRatio = maxLimitChris;
  240. } else if (newRatio < minLimitChris) {
  241. log = "Dynamic ISF hit limit by autosens_min setting: " + minLimitChris + " (" + newRatio.toPrecision(3) + ")" + ". ISF: " + (profile.sens / minLimitChris).toPrecision(3) + " (" + ((profile.sens / minLimitChris) * 0.0555).toPrecision(3) + " mmol/l/U)";
  242. newRatio = minLimitChris;
  243. }
  244. function round(value, precision) {
  245. var multiplier = Math.pow(10, precision || 0);
  246. return Math.round(value * multiplier) / multiplier;
  247. }
  248. // Set the new ratio
  249. autosens.ratio = round(newRatio, 2);
  250. // Print to log
  251. return log + logTDD + logBolus + logTempBasal + logBasal;
  252. } else { return "Dynamic ISF is off." }
  253. }