determine_basal.js 18 KB

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