determine_basal.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  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. // 3. Account for a punp suspension.
  110. // 4. Account for a pump resume (in case pump/cgm is disconnected before next loop).
  111. // To do: are there more circumstances when scheduled basal rates are used?
  112. //
  113. for (let k = 0; k < pumphistory.length; k++) {
  114. // Check for 0 temp basals with 0 min duration.
  115. insulin = 0;
  116. if (pumphistory[k]['duration (min)'] == 0 || pumphistory[k]._type == "PumpResume") {
  117. let time1 = new Date(pumphistory[k].timestamp);
  118. let time2 = time1;
  119. let l = k;
  120. do {
  121. --l;
  122. if (pumphistory[l]._type == "TempBasal" && l >= 0) {
  123. time2 = new Date(pumphistory[l].timestamp);
  124. break;
  125. }
  126. } while (l > 0);
  127. // duration of current scheduled basal in h
  128. let basDuration = (time2 - time1) / 36e5;
  129. if (basDuration > 0) {
  130. let hour = time1.getHours();
  131. let minutes = time1.getMinutes();
  132. let seconds = "00";
  133. let string = "" + hour + ":" + minutes + ":" + seconds;
  134. let baseTime = new Date(string);
  135. let basalScheduledRate = profile.basalprofile[0].start;
  136. for (let m = 0; m < profile.basalprofile.length; m++) {
  137. if (profile.basalprofile[m].start == baseTime) {
  138. basalScheduledRate = profile.basalprofile[m].rate;
  139. insulin = basalScheduledRate * basDuration;
  140. break;
  141. }
  142. else if (m + 1 < profile.basalprofile.length) {
  143. if (profile.basalprofile[m].start < baseTime && profile.basalprofile[m+1].start > baseTime) {
  144. basalScheduledRate = profile.basalprofile[m].rate;
  145. insulin = basalScheduledRate * basDuration;
  146. break;
  147. }
  148. }
  149. else if (m == profile.basalprofile.length - 1) {
  150. basalScheduledRate = profile.basalprofile[m].rate;
  151. insulin = basalScheduledRate * basDuration;
  152. break;
  153. }
  154. }
  155. // Account for smallest possible pump dosage
  156. incrementsRaw = insulin / minimalDose;
  157. if (incrementsRaw >= 1) {
  158. incrementsRounded = Math.floor(incrementsRaw);
  159. insulin = incrementsRounded * minimalDose;
  160. scheduledBasalInsulin += insulin;
  161. } else { insulin = 0;
  162. }
  163. }
  164. }
  165. }
  166. // Check for temp basals that completes
  167. for (let n = pumphistory.length -1; n > 0; n--) {
  168. if (pumphistory[n]._type == "TempBasalDuration") {
  169. // duration in hours
  170. let oldBasalDuration = pumphistory[n]['duration (min)'] / 60;
  171. // time of old temp basal
  172. let oldTime = new Date(pumphistory[n].timestamp);
  173. let newTime = oldTime;
  174. let o = n;
  175. do {
  176. --o;
  177. if (o >= 0) {
  178. if (pumphistory[o]._type == "TempBasal" || pumphistory[o]._type == "PumpSuspend") {
  179. // time of next (new) temp basal or a pump suspension
  180. newTime = new Date(pumphistory[o].timestamp);
  181. break;
  182. }
  183. }
  184. } while (o > 0);
  185. // When latest temp basal is index 0 in pump history
  186. if (n == 0 && pumphistory[0]._type == "TempBasalDuration") {
  187. newTime = new Date();
  188. oldBasalDuration = pumphistory[n]['duration (min)'] / 60;
  189. }
  190. // Time difference in hours, new - old
  191. let tempBasalTimeDifference = (newTime - oldTime) / 36e5;
  192. let timeOfbasal = tempBasalTimeDifference - oldBasalDuration;
  193. // if duration of scheduled basal is more than 0
  194. if (timeOfbasal > 0) {
  195. // Timestamp after completed temp basal
  196. let timeOfScheduledBasal = new Date(oldTime.getTime() + oldBasalDuration*36e5);
  197. let hour = timeOfScheduledBasal.getHours();
  198. let minutes = timeOfScheduledBasal.getMinutes();
  199. let seconds = "00";
  200. // "hour:minutes:00"
  201. let baseTime = "" + hour + ":" + minutes + ":" + seconds;
  202. // Default if correct basal schedule rate not found
  203. let basalScheduledRate = profile.basalprofile[0].rate;
  204. for (let p = 0; p < profile.basalprofile.length; ++p) {
  205. let basalRateTime = new Date(profile.basalprofile[p].start);
  206. if (basalRateTime == baseTime) {
  207. basalScheduledRate = profile.basalprofile[p].rate;
  208. break;
  209. }
  210. else if (p+1 < profile.basalprofile.length) {
  211. let nextBasalRateTime = new Date(profile.basalprofile[p+1].start);
  212. if (basalRateTime < baseTime && nextBasalRateTime > baseTime) {
  213. basalScheduledRate = profile.basalprofile[p].rate;
  214. break;
  215. }
  216. }
  217. else if (p == (profile.basalprofile.length - 1)) {
  218. basalScheduledRate = profile.basalprofile[p].rate;
  219. break;
  220. }
  221. }
  222. insulin = basalScheduledRate * timeOfbasal;
  223. // Account for smallest possible pump dosage
  224. incrementsRaw = insulin / minimalDose;
  225. if (incrementsRaw >= 1) {
  226. incrementsRounded = Math.floor(incrementsRaw);
  227. scheduledBasalInsulin += incrementsRounded * minimalDose;
  228. } else { insulin = 0}
  229. }
  230. }
  231. }
  232. TDD = bolusInsulin + tempInsulin + scheduledBasalInsulin;
  233. logBolus = ". Bolus insulin: " + bolusInsulin.toPrecision(5) + " U";
  234. logTempBasal = ". Temporary basal insulin: " + tempInsulin.toPrecision(5) + " U";
  235. logBasal = ". Delivered scheduled basal insulin: " + scheduledBasalInsulin.toPrecision(5) + " U";
  236. logTDD = ". TDD past 24h is: " + TDD.toPrecision(5) + " U";
  237. // ----------------------------------------------------
  238. // Chris' formula with added adjustmentFactor for tuning:
  239. if (chrisFormula == true && TDD > 0) {
  240. var newRatio = profile.sens / (277700 / (adjustmentFactor * TDD * BG));
  241. 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)";
  242. // Respect autosens.max and autosens.min limits
  243. if (newRatio > maxLimitChris) {
  244. 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)";
  245. newRatio = maxLimitChris;
  246. } else if (newRatio < minLimitChris) {
  247. 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)";
  248. newRatio = minLimitChris;
  249. }
  250. function round(value, precision) {
  251. var multiplier = Math.pow(10, precision || 0);
  252. return Math.round(value * multiplier) / multiplier;
  253. }
  254. // Set the new ratio
  255. autosens.ratio = round(newRatio, 2);
  256. // Set the new Dynamic CR (Test)
  257. if (useDynamicCR == true) {
  258. profile.carb_ratio = round(profile.carb_ratio/newRatio, 2);
  259. }
  260. // Print to log
  261. return log + logTDD + logBolus + logTempBasal + logBasal;
  262. } else { return "Dynamic ISF is off." }
  263. }