determine_basal.js 13 KB

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