determine_basal.js 18 KB

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