determine_basal.js 13 KB

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