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