determine_basal.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  1. function middleware(iob, currenttemp, glucose, profile, autosens, meal, reservoir, clock, pumphistory, preferences, basalProfile) {
  2. // This middleware works with my "bdb" branch.
  3. const BG = glucose[0].glucose;
  4. var chrisFormula = preferences.enableChris;
  5. var useDynamicCR = preferences.enableDynamicCR;
  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 pumpData = 0;
  12. var log = "";
  13. var logTDD = "";
  14. var logBasal = "";
  15. var logBolus = "";
  16. var logTempBasal = "";
  17. var dataLog = "";
  18. var logOutPut = "";
  19. var current = 0;
  20. var TDD = 0;
  21. var insulin = 0;
  22. var tempInsulin = 0;
  23. var bolusInsulin = 0;
  24. var scheduledBasalInsulin = 0;
  25. var quota = 0;
  26. function round(value, precision) {
  27. var multiplier = Math.pow(10, precision || 0);
  28. return Math.round(value * multiplier) / multiplier;
  29. }
  30. function addTimeToDate(objDate, _hours) {
  31. var ms = objDate.getTime();
  32. var add_ms = _hours * 36e5;
  33. var newDateObj = new Date(ms + add_ms);
  34. return newDateObj;
  35. }
  36. function subtractTimeFromDate(date, hours_) {
  37. var ms_ = date.getTime();
  38. var add_ms_ = hours_ * 36e5;
  39. var new_date = new Date(ms_ - add_ms_);
  40. return new_date;
  41. }
  42. function accountForIncrements(insulin) {
  43. // If you have not set this to 0.05 in FAX settings (Omnipod), this will be set to 0.1 (Medtronic) in code.
  44. var minimalDose = profile.bolus_increment;
  45. if (minimalDose != 0.05) {
  46. minimalDose = 0.1;
  47. }
  48. var incrementsRaw = insulin / minimalDose;
  49. if (incrementsRaw >= 1) {
  50. var incrementsRounded = Math.floor(incrementsRaw);
  51. return round(incrementsRounded * minimalDose, 5);
  52. } else { return 0; }
  53. }
  54. function makeBaseString(base_timeStamp) {
  55. function addZero(i) {
  56. if (i < 10) {i = "0" + i}
  57. return i;
  58. }
  59. let hour = addZero(base_timeStamp.getHours());
  60. let minutes = addZero(base_timeStamp.getMinutes());
  61. let seconds = "00";
  62. let string = hour + ":" + minutes + ":" + seconds;
  63. return string;
  64. }
  65. function timeDifferenceOfString(string1, string2) {
  66. //Base time strings are in "00:00:00" format
  67. var time1 = new Date("1/1/1999 " + string1);
  68. var time2 = new Date("1/1/1999 " + string2);
  69. var ms1 = time1.getTime();
  70. var ms2 = time2.getTime();
  71. var difference = (ms1 - ms2) / 36e5;
  72. return difference;
  73. }
  74. function calcScheduledBasalInsulin(lastRealTempTime, addedLastTempTime) {
  75. var totalInsulin = 0;
  76. var old = addedLastTempTime;
  77. var totalDuration = (lastRealTempTime - addedLastTempTime) / 36e5;
  78. var basDuration = 0;
  79. var totalDurationCheck = totalDuration;
  80. var durationCurrentSchedule = 0;
  81. do {
  82. if (totalDuration > 0) {
  83. var baseTime_ = makeBaseString(old);
  84. //Default basalrate in case none is found...
  85. var basalScheduledRate_ = basalProfile[0].start;
  86. for (let m = 0; m < basalProfile.length; m++) {
  87. var timeToTest = basalProfile[m].start;
  88. if (baseTime_ == timeToTest) {
  89. if (m + 1 < basalProfile.length) {
  90. let end = basalProfile[m+1].start;
  91. let start = basalProfile[m].start;
  92. durationCurrentSchedule = timeDifferenceOfString(end, start);
  93. if (totalDuration >= durationCurrentSchedule) {
  94. basDuration = durationCurrentSchedule;
  95. } else if (totalDuration < durationCurrentSchedule) {
  96. basDuration = totalDuration;
  97. }
  98. }
  99. else if (m + 1 == basalProfile.length) {
  100. let end = basalProfile[0].start;
  101. let start = basalProfile[m].start;
  102. // First schedule is 00:00:00. Changed places of start and end here.
  103. durationCurrentSchedule = 24 - (timeDifferenceOfString(start, end));
  104. if (totalDuration >= durationCurrentSchedule) {
  105. basDuration = durationCurrentSchedule;
  106. } else if (totalDuration < durationCurrentSchedule) {
  107. basDuration = totalDuration;
  108. }
  109. }
  110. basalScheduledRate_ = basalProfile[m].rate;
  111. totalInsulin += accountForIncrements(basalScheduledRate_ * basDuration);
  112. totalDuration -= basDuration;
  113. console.log("Dynamic ratios log: scheduled insulin added: " + accountForIncrements(basalScheduledRate_ * basDuration) + " U. Bas duration: " + basDuration.toPrecision(3) + " h. Base Rate: " + basalScheduledRate_ + " U/h" + ". Time :" + baseTime_);
  114. // Move clock to new date
  115. old = addTimeToDate(old, basDuration);
  116. }
  117. else if (baseTime_ > timeToTest) {
  118. if (m + 1 < basalProfile.length) {
  119. var timeToTest2 = basalProfile[m+1].start
  120. if (baseTime_ < timeToTest2) {
  121. // durationCurrentSchedule = timeDifferenceOfString(end, start);
  122. durationCurrentSchedule = timeDifferenceOfString(timeToTest2, baseTime_);
  123. if (totalDuration >= durationCurrentSchedule) {
  124. basDuration = durationCurrentSchedule;
  125. } else if (totalDuration < durationCurrentSchedule) {
  126. basDuration = totalDuration;
  127. }
  128. basalScheduledRate_ = basalProfile[m].rate;
  129. totalInsulin += accountForIncrements(basalScheduledRate_ * basDuration);
  130. totalDuration -= basDuration;
  131. console.log("Dynamic ratios log: scheduled insulin added: " + accountForIncrements(basalScheduledRate_ * basDuration) + " U. Bas duration: " + basDuration.toPrecision(3) + " h. Base Rate: " + basalScheduledRate_ + " U/h" + ". Time :" + baseTime_);
  132. // Move clock to new date
  133. old = addTimeToDate(old, basDuration);
  134. }
  135. }
  136. else if (m == basalProfile.length - 1) {
  137. // let start = basalProfile[m].start;
  138. let start = baseTime_;
  139. // First schedule is 00:00:00. Changed places of start and end here.
  140. durationCurrentSchedule = timeDifferenceOfString("23:59:59", start);
  141. if (totalDuration >= durationCurrentSchedule) {
  142. basDuration = durationCurrentSchedule;
  143. } else if (totalDuration < durationCurrentSchedule) {
  144. basDuration = totalDuration;
  145. }
  146. basalScheduledRate_ = basalProfile[m].rate;
  147. totalInsulin += accountForIncrements(basalScheduledRate_ * basDuration);
  148. totalDuration -= basDuration;
  149. console.log("Dynamic ratios log: scheduled insulin added: " + accountForIncrements(basalScheduledRate_ * basDuration) + " U. Bas duration: " + basDuration.toPrecision(3) + " h. Base Rate: " + basalScheduledRate_ + " U/h" + ". Time :" + baseTime_);
  150. // Move clock to new date
  151. old = addTimeToDate(old, basDuration);
  152. }
  153. }
  154. }
  155. }
  156. //totalDurationCheck to avoid infinite loop
  157. } while (totalDuration > 0 && totalDuration < totalDurationCheck);
  158. // amount of insulin according to pump basal rate schedules
  159. return totalInsulin;
  160. }
  161. //------------- End of added functions ----------------------------------------------------
  162. if (profile.high_temptarget_raises_sensitivity == true || profile.exercise_mode == true) {
  163. exerciseSetting = true;
  164. }
  165. // Turns off Auto-ISF when using Dynamic ISF.
  166. if (profile.use_autoisf == true && chrisFormula == true) {
  167. profile.use_autoisf = false;
  168. }
  169. // Turn off Chris' formula (and AutoISF) when using a temp target >= 118 (6.5 mol/l) and if an exercise setting is enabled.
  170. if (currentMinTarget >= 118 && exerciseSetting == true) {
  171. profile.use_autoisf = false;
  172. chrisFormula = false;
  173. log = "Dynamic ISF temporarily off due to a high temp target/exercising. Current min target: " + currentMinTarget;
  174. }
  175. // Check that there is enough pump history data (>23.5 hours) for TDD calculation, else estimate a TDD using using missing hours with scheduled basal rates.
  176. if (chrisFormula == true) {
  177. let ph_length = pumphistory.length;
  178. var endDate = new Date(pumphistory[ph_length-1].timestamp);
  179. var startDate = new Date(pumphistory[0].timestamp);
  180. // If latest pump event is a temp basal
  181. if (pumphistory[0]._type == "TempBasalDuration") {
  182. startDate = new Date();
  183. }
  184. pumpData = (startDate - endDate) / 36e5;
  185. if (pumpData < 23.5) {
  186. var missingHours = 24 - pumpData;
  187. // Makes new end date for a total time duration of exakt 24 hour.
  188. var endDate_ = subtractTimeFromDate(endDate, missingHours);
  189. // endDate - endDate_ = missingHours
  190. scheduledBasalInsulin = calcScheduledBasalInsulin(endDate, endDate_);
  191. dataLog = "24 hours of data is required for an accurate TDD calculation. Currently only " + pumpData.toPrecision(3) + " hours of pump history data are available. Using your pump scheduled basals to fill in the missing hours. Scheduled basals added: " + scheduledBasalInsulin.toPrecision(5) + " U. ";
  192. } else { dataLog = ""; }
  193. }
  194. // Calculate TDD --------------------------------------
  195. //Bolus:
  196. for (let i = 0; i < pumphistory.length; i++) {
  197. if (pumphistory[i]._type == "Bolus") {
  198. bolusInsulin += pumphistory[i].amount;
  199. }
  200. }
  201. // Temp basals:
  202. for (let j = 1; j < pumphistory.length; j++) {
  203. if (pumphistory[j]._type == "TempBasal" && pumphistory[j].rate > 0) {
  204. current = j;
  205. quota = pumphistory[j].rate;
  206. var duration = pumphistory[j-1]['duration (min)'] / 60;
  207. var origDur = duration;
  208. var pastTime = new Date(pumphistory[j-1].timestamp);
  209. // If temp basal hasn't yet ended, use now as end date for calculation
  210. do {
  211. j--;
  212. if (j <= 0) {
  213. morePresentTime = new Date();
  214. break;
  215. } else if (pumphistory[j]._type == "TempBasal" || pumphistory[j]._type == "PumpSuspend") {
  216. morePresentTime = new Date(pumphistory[j].timestamp);
  217. break;
  218. }
  219. }
  220. while (j >= 0);
  221. var diff = (morePresentTime - pastTime) / 36e5;
  222. if (diff < origDur) {
  223. duration = diff;
  224. }
  225. insulin = quota * duration;
  226. tempInsulin += accountForIncrements(insulin);
  227. j = current;
  228. }
  229. }
  230. // Check and count for when basals are delivered with a scheduled basal rate or an Autotuned basal rate.
  231. // 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.
  232. // 2. Check for temp basals that completes. This is for when disconnected from link/iphone, or when in open loop.
  233. // 3. Account for a punp suspension. This is for when pod screams or when MDT or pod is manually suspended.
  234. // 4. Account for a pump resume (in case pump/cgm is disconnected before next loop).
  235. // To do: are there more circumstances when scheduled basal rates are used?
  236. //
  237. for (let k = 0; k < pumphistory.length; k++) {
  238. // Check for 0 temp basals with 0 min duration.
  239. insulin = 0;
  240. if (pumphistory[k]['duration (min)'] == 0 || pumphistory[k]._type == "PumpResume") {
  241. let time1 = new Date(pumphistory[k].timestamp);
  242. let time2 = time1;
  243. let l = k;
  244. do {
  245. --l;
  246. if (pumphistory[l]._type == "TempBasal" && l >= 0) {
  247. time2 = new Date(pumphistory[l].timestamp);
  248. break;
  249. }
  250. } while (l > 0);
  251. // duration of current scheduled basal in h
  252. let basDuration = (time2 - time1) / 36e5;
  253. if (basDuration > 0) {
  254. scheduledBasalInsulin += calcScheduledBasalInsulin(time2, time1);
  255. }
  256. }
  257. }
  258. // Check for temp basals that completes
  259. for (let n = pumphistory.length -1; n > 0; n--) {
  260. if (pumphistory[n]._type == "TempBasalDuration") {
  261. // duration in hours
  262. let oldBasalDuration = pumphistory[n]['duration (min)'] / 60;
  263. // time of old temp basal
  264. let oldTime = new Date(pumphistory[n].timestamp);
  265. var newTime = oldTime;
  266. let o = n;
  267. do {
  268. --o;
  269. if (o >= 0) {
  270. if (pumphistory[o]._type == "TempBasal" || pumphistory[o]._type == "PumpSuspend") {
  271. // time of next (new) temp basal or a pump suspension
  272. newTime = new Date(pumphistory[o].timestamp);
  273. break;
  274. }
  275. }
  276. } while (o > 0);
  277. // When latest temp basal is index 0 in pump history
  278. if (n == 0 && pumphistory[0]._type == "TempBasalDuration") {
  279. newTime = new Date();
  280. oldBasalDuration = pumphistory[n]['duration (min)'] / 60;
  281. }
  282. let tempBasalTimeDifference = (newTime - oldTime) / 36e5;
  283. let timeOfbasal = tempBasalTimeDifference - oldBasalDuration;
  284. // if duration of scheduled basal is more than 0
  285. if (timeOfbasal > 0) {
  286. // Timestamp after completed temp basal
  287. let timeOfScheduledBasal = addTimeToDate(oldTime, oldBasalDuration);
  288. scheduledBasalInsulin += calcScheduledBasalInsulin(newTime, timeOfScheduledBasal);
  289. }
  290. }
  291. }
  292. // ----------------------------------------------------
  293. TDD = bolusInsulin + tempInsulin + scheduledBasalInsulin;
  294. logBolus = ". Bolus insulin: " + bolusInsulin.toPrecision(5) + " U";
  295. logTempBasal = ". Temporary basal insulin: " + tempInsulin.toPrecision(5) + " U";
  296. logBasal = ". Insulin with scheduled basal rate: " + scheduledBasalInsulin.toPrecision(5) + " U";
  297. logTDD = ". TDD past 24h is: " + TDD.toPrecision(5) + " U";
  298. var startLog = "Dynamic ratios log: ";
  299. var afLog = "AF: " + adjustmentFactor + ". ";
  300. var bgLog = "BG: " + BG + " mg/dl (" + (BG * 0.0555).toPrecision(2) + " mmol/l). ";
  301. var formula = "";
  302. // Insulin curve
  303. const curve = preferences.curve;
  304. const ipt = preferences.insulinPeakTime;
  305. const ucpk = preferences.useCustomPeakTime;
  306. var insulinFactor = 55;
  307. switch (curve) {
  308. case "rapid-acting":
  309. insulinFactor = 55;
  310. break;
  311. case "ultra-rapid":
  312. if (ipt < 75 && ucpk == true) {
  313. insulinFactor = 120 - ipt;
  314. } else { insulinFactor = 70; }
  315. break;
  316. }
  317. // Modified Chris Wilson's' formula with added adjustmentFactor for tuning and use instead of autosens:
  318. // var newRatio = profile.sens * adjustmentFactor * TDD * BG / 277700;
  319. //
  320. // New logarithmic formula : var newRatio = profile.sens * adjustmentFactor * TDD * ln(( BG/insulinFactor) + 1 )) / 1800
  321. //
  322. if (preferences.useNewFormula == true) {
  323. var newRatio = profile.sens * adjustmentFactor * TDD * Math.log(BG/insulinFactor+1) / 1800;
  324. formula = "Logarithmic formula. InsulinFactor: " + insulinFactor + ". ";
  325. }
  326. else {
  327. var newRatio = profile.sens * adjustmentFactor * TDD * BG / 277700;
  328. formula = "Original formula. ";
  329. }
  330. var isf = profile.sens / newRatio;
  331. // Dynamic CR (Test)
  332. var cr = profile.carb_ratio;
  333. if (useDynamicCR == true) {
  334. cr = round(profile.carb_ratio/newRatio, 2);
  335. profile.carb_ratio = cr;
  336. }
  337. if (chrisFormula == true && TDD > 0) {
  338. log = "Dynamic autosens.ratio set to " + newRatio.toPrecision(3) + " with ISF: " + isf.toPrecision(3) + " mg/dl/U (" + (isf * 0.0555).toPrecision(3) + " mmol/l/U) and CR: " + cr + " g/U";
  339. // Respect autosens.max and autosens.min limits
  340. if (newRatio > maxLimitChris) {
  341. log = "Dynamic ISF hit limit by autosens_max setting: " + maxLimitChris + " (" + newRatio.toPrecision(3) + ")" + ". ISF: " + (profile.sens / maxLimitChris).toPrecision(3) + " mg/dl/U (" + ((profile.sens / maxLimitChris) * 0.0555).toPrecision(3) + " mmol/l/U) and CR: " + cr + " g/U";
  342. newRatio = maxLimitChris;
  343. } else if (newRatio < minLimitChris) {
  344. log = "Dynamic ISF hit limit by autosens_min setting: " + minLimitChris + " (" + newRatio.toPrecision(3) + ")" + ". ISF: " + (profile.sens / minLimitChris).toPrecision(3) + " mg/dl/U (" + ((profile.sens / minLimitChris) * 0.0555).toPrecision(3) + " mmol/l/U) and CR: " + cr + " g/U";
  345. newRatio = minLimitChris;
  346. }
  347. // Set the new ratio
  348. autosens.ratio = round(newRatio, 2);
  349. logOutPut = startLog + dataLog + bgLog + afLog + formula + log + logTDD + logBolus + logTempBasal + logBasal;
  350. } else if (chrisFormula == false && useDynamicCR == true) {
  351. logOutPut = startLog + bgLog + afLog + formula + "Dynamic ISF is off. Dynamic CR: " + cr + " g/U.";
  352. } else {
  353. logOutPut = startLog + "Dynamic ISF is off. Dynamic CR is off." ;
  354. }
  355. return logOutPut;
  356. }