determine_basal.js 13 KB

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