determine-basal.js 83 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658
  1. /*
  2. Determine Basal
  3. Released under MIT license. See the accompanying LICENSE.txt file for
  4. full terms and conditions
  5. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  6. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  7. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  8. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  9. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  10. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  11. THE SOFTWARE.
  12. */
  13. // Define various functions used later on, in the main function determine_basal() below
  14. var round_basal = require('../round-basal');
  15. // Rounds value to 'digits' decimal places
  16. function round(value, digits) {
  17. if (! digits) { digits = 0; }
  18. var scale = Math.pow(10, digits);
  19. return Math.round(value * scale) / scale;
  20. }
  21. // we expect BG to rise or fall at the rate of BGI,
  22. // adjusted by the rate at which BG would need to rise /
  23. // fall to get eventualBG to target over 2 hours
  24. function calculate_expected_delta(target_bg, eventual_bg, bgi) {
  25. // (hours * mins_per_hour) / 5 = how many 5 minute periods in 2h = 24
  26. var five_min_blocks = (2 * 60) / 5;
  27. var target_delta = target_bg - eventual_bg;
  28. return /* expectedDelta */ round(bgi + (target_delta / five_min_blocks), 1);
  29. }
  30. function convert_bg(value, profile)
  31. {
  32. if (profile.out_units === "mmol/L")
  33. {
  34. return round(value * 0.0555,1);
  35. }
  36. else
  37. {
  38. return Math.round(value);
  39. }
  40. }
  41. function enable_smb(profile, microBolusAllowed, meal_data, bg, target_bg, high_bg, oref_variables, time) {
  42. if (oref_variables.smbIsScheduledOff){
  43. /* Below logic is related to profile overrides which can disable SMBs or disable them for a scheduled window.
  44. * SMBs will be disabled from [start, end), such that if an SMB is scheduled to be disabled from 10 AM to 2 PM,
  45. * an SMB will not be allowed from 10:00:00 until 1:59:59.
  46. */
  47. let currentHour = new Date(time.getHours());
  48. let startTime = oref_variables.start;
  49. let endTime = oref_variables.end;
  50. if (startTime < endTime && (currentHour >= startTime && currentHour < endTime)) {
  51. console.error("SMB disabled: current time is in SMB disabled scheduled")
  52. return false
  53. } else if (startTime > endTime && (currentHour >= startTime || currentHour < endTime)) {
  54. console.error("SMB disabled: current time is in SMB disabled scheduled")
  55. return false
  56. } else if (startTime == 0 && endTime == 0) {
  57. console.error("SMB disabled: current time is in SMB disabled scheduled")
  58. return false;
  59. } else if (startTime == endTime && currentHour == startTime) {
  60. console.error("SMB disabled: current time is in SMB disabled scheduled")
  61. return false;
  62. }
  63. }
  64. // disable SMB when a high temptarget is set
  65. if (! microBolusAllowed) {
  66. console.error("SMB disabled (!microBolusAllowed)");
  67. return false;
  68. } else if (! profile.allowSMB_with_high_temptarget && profile.temptargetSet && target_bg > 100) {
  69. console.error("SMB disabled due to high temptarget of " + target_bg);
  70. return false;
  71. } else if (meal_data.bwFound === true && profile.A52_risk_enable === false) {
  72. console.error("SMB disabled due to Bolus Wizard activity in the last 6 hours.");
  73. return false;
  74. // Disable if invalid CGM reading (HIGH)
  75. } else if (bg == 400) {
  76. console.error("Invalid CGM (HIGH). SMBs disabled.");
  77. return false;
  78. }
  79. // enable SMB/UAM if always-on (unless previously disabled for high temptarget)
  80. if (profile.enableSMB_always === true) {
  81. if (meal_data.bwFound) {
  82. console.error("Warning: SMB enabled within 6h of using Bolus Wizard: be sure to easy bolus 30s before using Bolus Wizard");
  83. } else {
  84. console.error("SMB enabled due to enableSMB_always");
  85. }
  86. return true;
  87. }
  88. // enable SMB/UAM (if enabled in preferences) while we have COB
  89. if (profile.enableSMB_with_COB === true && meal_data.mealCOB) {
  90. if (meal_data.bwCarbs) {
  91. console.error("Warning: SMB enabled with Bolus Wizard carbs: be sure to easy bolus 30s before using Bolus Wizard");
  92. } else {
  93. console.error("SMB enabled for COB of " + meal_data.mealCOB);
  94. }
  95. return true;
  96. }
  97. // enable SMB/UAM (if enabled in preferences) for a full 6 hours after any carb entry
  98. // (6 hours is defined in carbWindow in lib/meal/total.js)
  99. if (profile.enableSMB_after_carbs === true && meal_data.carbs ) {
  100. if (meal_data.bwCarbs) {
  101. console.error("Warning: SMB enabled with Bolus Wizard carbs: be sure to easy bolus 30s before using Bolus Wizard");
  102. } else {
  103. console.error("SMB enabled for 6h after carb entry");
  104. }
  105. return true;
  106. }
  107. // enable SMB/UAM (if enabled in preferences) if a low temptarget is set
  108. if (profile.enableSMB_with_temptarget === true && (profile.temptargetSet && target_bg < 100)) {
  109. if (meal_data.bwFound) {
  110. console.error("Warning: SMB enabled within 6h of using Bolus Wizard: be sure to easy bolus 30s before using Bolus Wizard");
  111. } else {
  112. console.error("SMB enabled for temptarget of " + convert_bg(target_bg, profile));
  113. }
  114. return true;
  115. }
  116. // enable SMB if high bg is found
  117. if (profile.enableSMB_high_bg === true && high_bg !== null && bg >= high_bg) {
  118. console.error("Checking BG to see if High for SMB enablement.");
  119. console.error("Current BG", bg, " | High BG ", high_bg);
  120. if (meal_data.bwFound) {
  121. console.error("Warning: High BG SMB enabled within 6h of using Bolus Wizard: be sure to easy bolus 30s before using Bolus Wizard");
  122. } else {
  123. console.error("High BG detected. Enabling SMB.");
  124. }
  125. return true;
  126. }
  127. console.error("SMB disabled (no enableSMB preferences active or no condition satisfied)");
  128. return false;
  129. }
  130. var determine_basal = function determine_basal(glucose_status, currenttemp, iob_data, profile, autosens_data, meal_data, tempBasalFunctions, microBolusAllowed, reservoir_data, currentTime, pumphistory, preferences, basalprofile, oref2_variables, middleWare) {
  131. var profileTarget = profile.min_bg;
  132. var overrideTarget = oref2_variables.overrideTarget;
  133. if (overrideTarget != 0 && overrideTarget != 6 && oref2_variables.useOverride && !profile.temptargetSet) {
  134. profileTarget = overrideTarget;
  135. }
  136. const smbIsOff = oref2_variables.smbIsOff;
  137. const advancedSettings = oref2_variables.advancedSettings;
  138. const isfAndCr = oref2_variables.isfAndCr;
  139. const isf = oref2_variables.isf;
  140. const cr_ = oref2_variables.cr;
  141. const smbMinutes = oref2_variables.smbMinutes;
  142. const uamMinutes = oref2_variables.uamMinutes;
  143. // tdd past 24 hour
  144. let tdd = oref2_variables.currentTDD;
  145. var logOutPut = "";
  146. var tddReason = "";
  147. var dynISFenabled = preferences.useNewFormula
  148. var insulinForManualBolus = 0;
  149. var manualBolusErrorString = 0;
  150. var threshold = profileTarget;
  151. var systemTime = new Date();
  152. if (currentTime) {
  153. systemTime = new Date(currentTime);
  154. }
  155. const weightedAverage = oref2_variables.weightedAverage;
  156. var overrideFactor = 1;
  157. var sensitivity = profile.sens;
  158. var carbRatio = profile.carb_ratio;
  159. if (oref2_variables.useOverride) {
  160. overrideFactor = oref2_variables.overridePercentage / 100;
  161. if (isfAndCr) {
  162. sensitivity /= overrideFactor;
  163. carbRatio /= overrideFactor;
  164. } else {
  165. if (cr_) { carbRatio /= overrideFactor; }
  166. if (isf) { sensitivity /= overrideFactor; }
  167. }
  168. }
  169. const weightPercentage = profile.weightPercentage;
  170. const average_total_data = oref2_variables.average_total_data;
  171. // In case the autosens.min/max limits are reversed:
  172. const minLimitChris = Math.min(profile.autosens_min, profile.autosens_max);
  173. const maxLimitChris = Math.max(profile.autosens_min, profile.autosens_max);
  174. // Turn off when autosens.min = autosens.max
  175. if (maxLimitChris == minLimitChris || maxLimitChris < 1 || minLimitChris > 1) {
  176. dynISFenabled = false;
  177. console.log("Dynamic ISF disabled due to current autosens settings");
  178. }
  179. // Dynamic ratios
  180. const BG = glucose_status.glucose;
  181. const adjustmentFactor = preferences.adjustmentFactor;
  182. const adjustmentFactorSigmoid = preferences.adjustmentFactorSigmoid;
  183. const enable_sigmoid = preferences.sigmoid;
  184. const currentMinTarget = profileTarget;
  185. var exerciseSetting = false;
  186. var log = "";
  187. var tdd24h_14d_Ratio = 1;
  188. var basal_ratio_log = "";
  189. if (average_total_data > 0) {
  190. tdd24h_14d_Ratio = weightedAverage / average_total_data;
  191. }
  192. // respect autosens_max/min for tdd24h_14d_Ratio, used to adjust basal similarly as autosens
  193. if (tdd24h_14d_Ratio > 1) {
  194. tdd24h_14d_Ratio = Math.min(tdd24h_14d_Ratio, profile.autosens_max);
  195. tdd24h_14d_Ratio = round(tdd24h_14d_Ratio,2);
  196. basal_ratio_log = "Basal adjustment with a 24 hour to total average (up to 14 days of data) TDD ratio (limited by Autosens max setting). Basal Ratio: " + tdd24h_14d_Ratio + ". Upper limit = Autosens max (" + profile.autosens_max + ")";
  197. }
  198. else if (tdd24h_14d_Ratio < 1) {
  199. tdd24h_14d_Ratio = Math.max(tdd24h_14d_Ratio, profile.autosens_min);
  200. tdd24h_14d_Ratio = round(tdd24h_14d_Ratio,2);
  201. basal_ratio_log = "Basal adjustment with a 24 hour to to total average (up to 14 days of data) TDD ratio (limited by Autosens min setting). Basal Ratio: " + tdd24h_14d_Ratio + ". Lower limit = Autosens min (" + profile.autosens_min + ")";
  202. }
  203. else {
  204. basal_ratio_log = "Basal adjusted with a 24 hour to total average (up to 14 days of data) TDD ratio: " + tdd24h_14d_Ratio;
  205. }
  206. basal_ratio_log = ", Basal ratio: " + tdd24h_14d_Ratio;
  207. // One of two exercise settings (they share the same purpose)
  208. if (profile.high_temptarget_raises_sensitivity || profile.exercise_mode) {
  209. exerciseSetting = true;
  210. }
  211. // Turn off Chris' formula when using a temp target >= 118 (6.5 mol/l) and if an exercise setting is enabled.
  212. if (currentMinTarget >= 118 && exerciseSetting) {
  213. dynISFenabled = false;
  214. log = "Dynamic ISF temporarily off due to a high temp target/exercising. Current min target: " + currentMinTarget;
  215. }
  216. var startLog = ", Dynamic ratios log: ";
  217. var afLog = ", AF: " + (enable_sigmoid ? adjustmentFactorSigmoid : adjustmentFactor);
  218. var bgLog = "BG: " + BG + " mg/dl (" + (BG * 0.0555).toPrecision(2) + " mmol/l)";
  219. var formula = "";
  220. var weightLog = "";
  221. // Insulin curve
  222. const curve = preferences.curve;
  223. const ipt = profile.insulinPeakTime;
  224. const ucpk = preferences.useCustomPeakTime;
  225. var insulinFactor = 55; // deafult (120-65)
  226. var insulinPA = 65; // default (Novorapid/Novolog)
  227. switch (curve) {
  228. case "rapid-acting":
  229. insulinPA = 65;
  230. break;
  231. case "ultra-rapid":
  232. insulinPA = 50;
  233. break;
  234. }
  235. if (ucpk) {
  236. insulinFactor = 120 - ipt;
  237. console.log("Custom insulinpeakTime set to :" + ipt + ", insulinFactor: " + insulinFactor);
  238. } else {
  239. insulinFactor = 120 - insulinPA;
  240. console.log("insulinFactor set to : " + insulinFactor);
  241. }
  242. // Use weighted TDD average
  243. tdd_before = tdd;
  244. if (weightPercentage < 1 && weightedAverage > 1) {
  245. tdd = weightedAverage;
  246. console.log("Using weighted TDD average: " + round(tdd,2) + " U, instead of past 24 h (" + round(tdd_before,2) + " U), weight: " + weightPercentage);
  247. weightLog = ", Weighted TDD: " + round(tdd,2) + " U";
  248. }
  249. // Modified Chris Wilson's' formula with added adjustmentFactor for tuning and use of the autosens.ratio:
  250. // var newRatio = profile.sens * adjustmentFactor * tdd * BG / 277700;
  251. //
  252. // New logarithmic formula : var newRatio = profile.sens * adjustmentFactor * tdd * ln(( BG/insulinFactor) + 1 )) / 1800
  253. //
  254. var sigmoidLog = ""
  255. if (dynISFenabled) {
  256. // Logarithmic
  257. if (!enable_sigmoid) {
  258. var newRatio = sensitivity * adjustmentFactor * tdd * Math.log(BG/insulinFactor+1) / 1800;
  259. formula = ", Logarithmic formula";
  260. }
  261. // Sigmoid
  262. else {
  263. const as_min = minLimitChris;
  264. const autosens_interval = maxLimitChris - as_min;
  265. //Blood glucose deviation from set target (the lower BG target) converted to mmol/l to fit current formula.
  266. const bg_dev = (BG - profileTarget) * 0.0555;
  267. // Account for TDD of insulin. Compare last 2 hours with total data (up to 14 days)
  268. var tdd_factor = tdd24h_14d_Ratio; // weighted average TDD / total data average TDD
  269. var max_minus_one = maxLimitChris - 1;
  270. // Avoid division by 0
  271. if (maxLimitChris == 1) {
  272. max_minus_one = maxLimitChris + 0.01 - 1;
  273. }
  274. //Makes sigmoid factor(y) = 1 when BG deviation(x) = 0.
  275. const fix_offset = (Math.log10(1/max_minus_one-as_min/max_minus_one) / Math.log10(Math.E));
  276. //Exponent used in sigmoid formula
  277. const exponent = bg_dev * adjustmentFactorSigmoid * tdd_factor + fix_offset;
  278. // The sigmoid function
  279. const sigmoid_factor = autosens_interval / (1 + Math.exp(-exponent)) + as_min;
  280. newRatio = sigmoid_factor;
  281. formula = ", Sigmoid function";
  282. }
  283. }
  284. var dynamicISFLog = "";
  285. var limitLog = "";
  286. if (dynISFenabled && tdd > 0) {
  287. dynamicISFLog = ", Dynamic ISF: On";
  288. // Respect autosens.max and autosens.min limitLogs
  289. if (newRatio > maxLimitChris) {
  290. log = ", Dynamic ISF limited by autosens_max setting: " + maxLimitChris + " (" + round(newRatio,2) + "), ";
  291. limitLog = ", Autosens/Dynamic Limit: " + maxLimitChris + " (" + round(newRatio,2) + ")";
  292. newRatio = maxLimitChris;
  293. } else if (newRatio < minLimitChris) {
  294. log = ", Dynamic ISF limited by autosens_min setting: " + minLimitChris + " (" + round(newRatio,2) + "). ";
  295. limitLog = ", Autosens/Dynamic Limit: " + minLimitChris + " (" + round(newRatio,2) + ")";
  296. newRatio = minLimitChris;
  297. }
  298. const isf = sensitivity / newRatio;
  299. // Set the new ratio
  300. autosens_data.ratio = newRatio;
  301. sigmoidLog = ". Using Sigmoid function, the autosens ratio has been adjusted with sigmoid factor to: " + round(autosens_data.ratio, 2) + ". New ISF = " + round(isf, 2) + " mg/dl (" + round(0.0555 * isf, 2) + " (mmol/l).";
  302. if (!enable_sigmoid) {
  303. log += ", Dynamic autosens.ratio set to " + round(newRatio,2) + " with ISF: " + isf.toPrecision(3) + " mg/dl/U (" + (isf * 0.0555).toPrecision(3) + " mmol/l/U)";
  304. } else { log += sigmoidLog }
  305. logOutPut += startLog + bgLog + afLog + formula + log + dynamicISFLog + weightLog;
  306. } else { logOutPut += startLog + "Dynamic Settings disabled"; }
  307. console.log(logOutPut);
  308. if (!dynISFenabled) {
  309. tddReason += "";
  310. } else if (dynISFenabled && profile.tddAdjBasal) {
  311. tddReason += dynamicISFLog + formula + limitLog + afLog + basal_ratio_log;
  312. }
  313. else if (dynISFenabled && !profile.tddAdjBasal) { tddReason += dynamicISFLog + formula + limitLog + afLog; }
  314. if (0.5 !== profile.smb_delivery_ratio) {
  315. tddReason += ", SMB Ratio: " + Math.min(profile.smb_delivery_ratio, 1);
  316. }
  317. // Not confident but something like this in iAPS v3.0.3
  318. if (middleWare !== "" && middleWare !== "Nothing changed"){
  319. tddReason += ", Middleware: " + middleWare;
  320. }
  321. // --------------- END OF DYNAMIC RATIOS CALCULATION ------ A FEW LINES ADDED ALSO AT LINE NR 1136 and 1178 ------------------------------------------------
  322. // Set variables required for evaluating error conditions
  323. var rT = {}; //short for requestedTemp
  324. var deliverAt = new Date(systemTime);
  325. if (typeof profile === 'undefined' || typeof profile.current_basal === 'undefined') {
  326. rT.error ='Error: could not get current basal rate';
  327. return rT;
  328. }
  329. var profile_current_basal = round_basal(profile.current_basal, profile) * overrideFactor;
  330. var basal = profile_current_basal;
  331. // Print Current Override factor, if any
  332. if (oref2_variables.useOverride) {
  333. if (oref2_variables.duration == 0) {
  334. console.log("Profile Override is active. Override " + round(overrideFactor * 100, 0) + "%. Override Duration: " + "Enabled indefinitely");
  335. } else
  336. console.log("Profile Override is active. Override " + round(overrideFactor * 100, 0) + "%. Override Expires in: " + oref2_variables.duration + " min.");
  337. }
  338. var bgTime = new Date(glucose_status.date);
  339. var minAgo = round( (systemTime - bgTime) / 60 / 1000 ,1);
  340. var bg = glucose_status.glucose;
  341. var noise = glucose_status.noise;
  342. // Prep various delta variables.
  343. var tick;
  344. if (glucose_status.delta > -0.5) {
  345. tick = "+" + round(glucose_status.delta,0);
  346. } else {
  347. tick = round(glucose_status.delta,0);
  348. }
  349. //var minDelta = Math.min(glucose_status.delta, glucose_status.short_avgdelta, glucose_status.long_avgdelta);
  350. var minDelta = Math.min(glucose_status.delta, glucose_status.short_avgdelta);
  351. var minAvgDelta = Math.min(glucose_status.short_avgdelta, glucose_status.long_avgdelta);
  352. var maxDelta = Math.max(glucose_status.delta, glucose_status.short_avgdelta, glucose_status.long_avgdelta);
  353. // Cancel high temps (and replace with neutral) or shorten long zero temps for various error conditions
  354. // 38 is an xDrip error state that usually indicates sensor failure
  355. // all other BG values between 11 and 37 mg/dL reflect non-error-code BG values, so we should zero temp for those
  356. // First, print out different explanations for each different error condition
  357. if (bg <= 10 || bg === 38 || noise >= 3) { //Dexcom is in ??? mode or calibrating, or xDrip reports high noise
  358. rT.reason = "CGM is calibrating, in ??? state, or noise is high";
  359. }
  360. var tooflat=false;
  361. if (bg > 60 && glucose_status.delta == 0 && glucose_status.short_avgdelta > -1 && glucose_status.short_avgdelta < 1 && glucose_status.long_avgdelta > -1 && glucose_status.long_avgdelta < 1 && bg != 400) {
  362. if (glucose_status.device == "fakecgm") {
  363. console.error("CGM data is unchanged (" + convert_bg(bg,profile) + "+" + convert_bg(glucose_status.delta,profile)+ ") for 5m w/ " + convert_bg(glucose_status.short_avgdelta,profile) + " mg/dL ~15m change & " + convert_bg(glucose_status.long_avgdelta,2) + " mg/dL ~45m change");
  364. console.error("Simulator mode detected (" + glucose_status.device + "): continuing anyway");
  365. } else if (bg != 400) {
  366. tooflat=true;
  367. }
  368. }
  369. if (minAgo > 12 || minAgo < -5) { // Dexcom data is too old, or way in the future
  370. rT.reason = "If current system time " + systemTime + " is correct, then BG data is too old. The last BG data was read "+minAgo+"m ago at "+bgTime;
  371. // if BG is too old/noisy, or is completely unchanging, cancel any high temps and shorten any long zero temps
  372. } else if ( glucose_status.short_avgdelta === 0 && glucose_status.long_avgdelta === 0 && bg != 400 ) {
  373. if ( glucose_status.last_cal && glucose_status.last_cal < 3 ) {
  374. rT.reason = "CGM was just calibrated";
  375. } else {
  376. rT.reason = "CGM data is unchanged (" + convert_bg(bg,profile) + "+" + convert_bg(glucose_status.delta,profile) + ") for 5m w/ " + convert_bg(glucose_status.short_avgdelta,profile) + " mg/dL ~15m change & " + convert_bg(glucose_status.long_avgdelta,profile) + " mg/dL ~45m change";
  377. }
  378. }
  379. if (bg != 400) {
  380. if (bg <= 10 || bg === 38 || noise >= 3 || minAgo > 12 || minAgo < -5 || ( glucose_status.short_avgdelta === 0 && glucose_status.long_avgdelta === 0 ) ) {
  381. if (currenttemp.rate >= basal) { // high temp is running
  382. rT.reason += ". Canceling high temp basal of " + currenttemp.rate;
  383. rT.deliverAt = deliverAt;
  384. rT.temp = 'absolute';
  385. rT.duration = 0;
  386. rT.rate = 0;
  387. return rT;
  388. // don't use setTempBasal(), as it has logic that allows <120% high temps to continue running
  389. //return tempBasalFunctions.setTempBasal(basal, 30, profile, rT, currenttemp);
  390. } else if ( currenttemp.rate === 0 && currenttemp.duration > 30 ) { //shorten long zero temps to 30m
  391. rT.reason += ". Shortening " + currenttemp.duration + "m long zero temp to 30m. ";
  392. rT.deliverAt = deliverAt;
  393. rT.temp = 'absolute';
  394. rT.duration = 30;
  395. rT.rate = 0;
  396. return rT;
  397. // don't use setTempBasal(), as it has logic that allows long zero temps to continue running
  398. //return tempBasalFunctions.setTempBasal(0, 30, profile, rT, currenttemp);
  399. } else { //do nothing.
  400. rT.reason += ". Temp " + currenttemp.rate + " <= current basal " + basal + "U/hr; doing nothing. ";
  401. return rT;
  402. }
  403. }
  404. }
  405. // Get configured target, and return if unable to do so.
  406. // This should occur after checking that we're not in one of the CGM-data-related error conditions handled above,
  407. // and before using target_bg to adjust sensitivityRatio below.
  408. var max_iob = profile.max_iob; // maximum amount of non-bolus IOB OpenAPS will ever deliver
  409. // if min and max are set, then set target to their average
  410. var target_bg;
  411. var min_bg;
  412. var max_bg;
  413. var high_bg;
  414. if (typeof profileTarget !== 'undefined') {
  415. min_bg = profileTarget;
  416. }
  417. if (typeof profile.max_bg !== 'undefined') {
  418. max_bg = profileTarget;
  419. }
  420. if (typeof profile.enableSMB_high_bg_target !== 'undefined') {
  421. high_bg = profile.enableSMB_high_bg_target;
  422. }
  423. if (typeof profileTarget !== 'undefined') {
  424. target_bg = profileTarget;
  425. } else {
  426. rT.error ='Error: could not determine target_bg. ';
  427. return rT;
  428. }
  429. // Calculate sensitivityRatio based on temp targets, if applicable, or using the value calculated by autosens
  430. // var sensitivityRatio;
  431. var high_temptarget_raises_sensitivity = profile.exercise_mode || profile.high_temptarget_raises_sensitivity;
  432. var normalTarget = 100; // evaluate high/low temptarget against 100, not scheduled target (which might change)
  433. var halfBasalTarget = 160; // when temptarget is 160 mg/dL, run 50% basal (120 = 75%; 140 = 60%)
  434. // 80 mg/dL with low_temptarget_lowers_sensitivity would give 1.5x basal, but is limitLoged to autosens_max (1.2x by default)
  435. //if ( profile.half_basal_exercise_target ) {
  436. halfBasalTarget = profile.half_basal_exercise_target;
  437. //}
  438. if ( high_temptarget_raises_sensitivity && profile.temptargetSet && target_bg > normalTarget ||
  439. profile.low_temptarget_lowers_sensitivity && profile.temptargetSet && target_bg < normalTarget ) {
  440. // w/ target 100, temp target 110 = .89, 120 = 0.8, 140 = 0.67, 160 = .57, and 200 = .44
  441. // e.g.: Sensitivity ratio set to 0.8 based on temp target of 120; Adjusting basal from 1.65 to 1.35; ISF from 58.9 to 73.6
  442. //sensitivityRatio = 2/(2+(target_bg-normalTarget)/40);
  443. var c = halfBasalTarget - normalTarget;
  444. // getting multiplication less or equal to 0 means that we have a really low target with a really low halfBasalTarget
  445. // with low TT and lowTTlowersSensitivity we need autosens_max as a value
  446. // we use multiplication instead of the division to avoid "division by zero error"
  447. if (c * (c + target_bg-normalTarget) <= 0.0) {
  448. sensitivityRatio = profile.autosens_max;
  449. }
  450. else {
  451. sensitivityRatio = c/(c+target_bg-normalTarget);
  452. }
  453. // limit sensitivityRatio to profile.autosens_max (1.2x by default)
  454. sensitivityRatio = Math.min(sensitivityRatio, profile.autosens_max);
  455. sensitivityRatio = round(sensitivityRatio,2);
  456. process.stderr.write("Sensitivity ratio set to "+sensitivityRatio+" based on temp target of "+target_bg+"; ");
  457. }
  458. else if (typeof autosens_data !== 'undefined' && autosens_data) {
  459. sensitivityRatio = autosens_data.ratio;
  460. // Override Profile.Target
  461. if (overrideTarget !== 0 && overrideTarget !== 6 && overrideTarget !== profile.min_bg && !profile.temptargetSet) {
  462. target_bg = overrideTarget;
  463. console.log("Current Override Profile Target: " + convert_bg(overrideTarget, profile) + " " + profile.out_units);
  464. }
  465. process.stderr.write("Autosens ratio: "+sensitivityRatio+"; ");
  466. }
  467. // Increase the dynamic ratio when using a low temp target
  468. if (profile.temptargetSet && target_bg < normalTarget && dynISFenabled && BG >= target_bg) {
  469. if (sensitivityRatio < newRatio) {
  470. autosens_data.ratio = newRatio * (normalTarget/target_bg);
  471. //Use autosesns.max limit
  472. autosens_data.ratio = Math.min(autosens_data.ratio, profile.autosens_max);
  473. sensitivityRatio = round(autosens_data.ratio, 2);
  474. console.log("Dynamic ratio increased from " + round(newRatio, 2) + " to " + round(autosens_data.ratio,2) + " due to a low temp target (" + target_bg + ").");
  475. }
  476. }
  477. if (sensitivityRatio && !dynISFenabled) { // Only enable adjustment of basal by sensitivityRatio when not using dISF
  478. basal = profile.current_basal * overrideFactor * sensitivityRatio;
  479. basal = round_basal(basal, profile);
  480. if (basal !== profile_current_basal) {
  481. process.stderr.write("Adjusting basal from "+profile_current_basal+" to "+basal+"; ");
  482. } else {
  483. process.stderr.write("Basal unchanged: "+basal+"; ");
  484. }
  485. }
  486. else if (dynISFenabled && profile.tddAdjBasal) {
  487. basal = profile.current_basal * tdd24h_14d_Ratio * overrideFactor;
  488. basal = round_basal(basal, profile);
  489. if (average_total_data > 0) {
  490. process.stderr.write("TDD-adjustment of basals activated, using tdd24h_14d_Ratio " + round(tdd24h_14d_Ratio,2) + ", TDD 24h = " + round(tdd_before,2) + "U, Weighted average TDD = " + round(weightedAverage,2) + "U, (Weight percentage = " + weightPercentage + "), Total data of TDDs (up to 14 days) average = " + round(average_total_data,2) + "U. " );
  491. if (basal !== profile_current_basal * overrideFactor) {
  492. process.stderr.write("Adjusting basal from " + profile_current_basal * overrideFactor + " U/h to " + basal + " U/h; ");
  493. } else { process.stderr.write("Basal unchanged: " + basal + " U/h; "); }
  494. }
  495. }
  496. // Conversely, adjust BG target based on autosens ratio if no temp target is running
  497. // adjust min, max, and target BG for sensitivity, such that 50% increase in ISF raises target from 100 to 120
  498. if (profile.temptargetSet) {
  499. //process.stderr.write("Temp Target set, not adjusting with autosens; ");
  500. } else if (typeof autosens_data !== 'undefined' && autosens_data) {
  501. if ( profile.sensitivity_raises_target && autosens_data.ratio < 1 || profile.resistance_lowers_target && autosens_data.ratio > 1 ) {
  502. // with a target of 100, default 0.7-1.2 autosens min/max range would allow a 93-117 target range
  503. min_bg = round((min_bg - 60) / autosens_data.ratio) + 60;
  504. max_bg = round((max_bg - 60) / autosens_data.ratio) + 60;
  505. var new_target_bg = round((target_bg - 60) / autosens_data.ratio) + 60;
  506. // don't allow target_bg below 80
  507. new_target_bg = Math.max(80, new_target_bg);
  508. if (target_bg === new_target_bg) {
  509. process.stderr.write("target_bg unchanged: " + convert_bg(new_target_bg, profile) + "; ");
  510. } else {
  511. process.stderr.write("target_bg from "+ convert_bg(new_target_bg, profile) + " to " + convert_bg(new_target_bg, profile) + "; ");
  512. }
  513. target_bg = new_target_bg;
  514. }
  515. }
  516. // Display if differing in enacted box
  517. var targetLog = convert_bg(target_bg, profile);
  518. if (target_bg != profileTarget) {
  519. if (overrideTarget !== 0 && overrideTarget !== 6 && overrideTarget !== target_bg) {
  520. targetLog = convert_bg(profileTarget, profile) + "\u2192" + convert_bg(overrideTarget, profile) + "\u2192" + convert_bg(target_bg, profile);
  521. } else {
  522. targetLog = convert_bg(profileTarget, profile) + "\u2192" + convert_bg(target_bg, profile);
  523. }
  524. }
  525. // Raise target for noisy / raw CGM data.
  526. var adjustedMinBG = 200;
  527. var adjustedTargetBG = 200;
  528. var adjustedMaxBG = 200;
  529. if (glucose_status.noise >= 2) {
  530. // increase target at least 10% (default 30%) for raw / noisy data
  531. var noisyCGMTargetMultiplier = Math.max( 1.1, profile.noisyCGMTargetMultiplier );
  532. // don't allow maxRaw above 250
  533. var maxRaw = Math.min( 250, profile.maxRaw );
  534. adjustedMinBG = round(Math.min(200, min_bg * noisyCGMTargetMultiplier ));
  535. adjustedTargetBG = round(Math.min(200, target_bg * noisyCGMTargetMultiplier ));
  536. adjustedMaxBG = round(Math.min(200, max_bg * noisyCGMTargetMultiplier ));
  537. process.stderr.write("Raising target_bg for noisy / raw CGM data, from " + convert_bg(new_target_bg, profile) + " to " + convert_bg(adjustedTargetBG, profile) + "; ");
  538. min_bg = adjustedMinBG;
  539. target_bg = adjustedTargetBG;
  540. max_bg = adjustedMaxBG;
  541. }
  542. // min_bg thresholds: 80->60, 90->65, 100->70, 110->75, 120->80
  543. threshold = min_bg - 0.5*(min_bg-40);
  544. // Set threshold to the user's setting, as long as it's between 60-120 and above the default calculated threshold
  545. threshold = Math.min(Math.max(profile.threshold_setting, threshold, 60), 120);
  546. console.error(`Threshold set to ${convert_bg(threshold, profile)}`);
  547. // If iob_data or its required properties are missing, return.
  548. // This has to be checked after checking that we're not in one of the CGM-data-related error conditions handled above,
  549. // and before attempting to use iob_data below.
  550. // Adjust ISF based on sensitivityRatio
  551. var isfreason = ""
  552. var profile_sens = round(sensitivity,1);
  553. var sens = sensitivity;
  554. if (typeof autosens_data !== 'undefined' && autosens_data) {
  555. sens = sensitivity / sensitivityRatio;
  556. sens = round(sens, 1);
  557. if (sens !== sensitivity) {
  558. process.stderr.write("ISF from "+ convert_bg(sensitivity,profile) +" to " + convert_bg(sens,profile));
  559. } else {
  560. process.stderr.write("ISF unchanged: "+ convert_bg(sens,profile));
  561. }
  562. //process.stderr.write(" (autosens ratio "+sensitivityRatio+")");
  563. isfreason += "Autosens ratio: " + round(sensitivityRatio, 2) + ", ISF: " + convert_bg(sensitivity,profile) + "\u2192" + convert_bg(sens,profile);
  564. }
  565. console.error("CR:" + carbRatio);
  566. if (typeof iob_data === 'undefined' ) {
  567. rT.error ='Error: iob_data undefined. ';
  568. return rT;
  569. }
  570. var iobArray = iob_data;
  571. if (typeof(iob_data.length) && iob_data.length > 1) {
  572. iob_data = iobArray[0];
  573. }
  574. if (typeof iob_data.activity === 'undefined' || typeof iob_data.iob === 'undefined' ) {
  575. rT.error ='Error: iob_data missing some property. ';
  576. return rT;
  577. }
  578. // Compare currenttemp to iob_data.lastTemp and cancel temp if they don't match, as a safety check
  579. // This should occur after checking that we're not in one of the CGM-data-related error conditions handled above,
  580. // and before returning (doing nothing) below if eventualBG is undefined.
  581. var lastTempAge;
  582. if (typeof iob_data.lastTemp !== 'undefined' ) {
  583. lastTempAge = round(( new Date(systemTime).getTime() - iob_data.lastTemp.date ) / 60000); // in minutes
  584. } else {
  585. lastTempAge = 0;
  586. }
  587. //console.error("currenttemp:",currenttemp,"lastTemp:",JSON.stringify(iob_data.lastTemp),"lastTempAge:",lastTempAge,"m");
  588. var tempModulus = (lastTempAge + currenttemp.duration) % 30;
  589. console.error("currenttemp:" + currenttemp.rate + " lastTempAge:" + lastTempAge + "m, tempModulus:" + tempModulus + "m");
  590. rT.temp = 'absolute';
  591. rT.deliverAt = deliverAt;
  592. if ( microBolusAllowed && currenttemp && iob_data.lastTemp && currenttemp.rate !== iob_data.lastTemp.rate && lastTempAge > 10 && currenttemp.duration ) {
  593. rT.reason = "Warning: currenttemp rate " + currenttemp.rate + " != lastTemp rate " + iob_data.lastTemp.rate + " from pumphistory; canceling temp"; // reason.conclusion started
  594. return tempBasalFunctions.setTempBasal(0, 0, profile, rT, currenttemp);
  595. }
  596. if ( currenttemp && iob_data.lastTemp && currenttemp.duration > 0 ) {
  597. //console.error(lastTempAge, round(iob_data.lastTemp.duration,1), round(lastTempAge - iob_data.lastTemp.duration,1));
  598. var lastTempEnded = lastTempAge - iob_data.lastTemp.duration;
  599. if ( lastTempEnded > 5 && lastTempAge > 10 ) {
  600. rT.reason = "Warning: currenttemp running but lastTemp from pumphistory ended " + lastTempEnded + "m ago; canceling temp"; // reason.conclusion started
  601. //console.error(currenttemp, round(iob_data.lastTemp,1), round(lastTempAge,1));
  602. return tempBasalFunctions.setTempBasal(0, 0, profile, rT, currenttemp);
  603. }
  604. }
  605. // Calculate BGI, deviation, and eventualBG.
  606. // This has to happen after we obtain iob_data
  607. //calculate BG impact: the amount BG "should" be rising or falling based on insulin activity alone
  608. var bgi = round(( -iob_data.activity * sens * 5 ), 2);
  609. // project deviations for 30 minutes
  610. var deviation = round( 30 / 5 * ( minDelta - bgi ) );
  611. // don't overreact to a big negative delta: use minAvgDelta if deviation is negative
  612. if (deviation < 0) {
  613. deviation = round( (30 / 5) * ( minAvgDelta - bgi ) );
  614. // and if deviation is still negative, use long_avgdelta
  615. if (deviation < 0) {
  616. deviation = round( (30 / 5) * ( glucose_status.long_avgdelta - bgi ) );
  617. }
  618. }
  619. // calculate the naive (bolus calculator math) eventual BG based on net IOB and sensitivity
  620. var naive_eventualBG = bg;
  621. if (iob_data.iob > 0) {
  622. naive_eventualBG = round( bg - (iob_data.iob * sens) );
  623. } else { // if IOB is negative, be more conservative and use the lower of sens, profile.sens
  624. naive_eventualBG = round( bg - (iob_data.iob * Math.min(sens, sensitivity) ) );
  625. }
  626. // and adjust it for the deviation above
  627. var eventualBG = naive_eventualBG + deviation;
  628. if (typeof eventualBG === 'undefined' || isNaN(eventualBG)) {
  629. rT.error ='Error: could not calculate eventualBG. Sensitivity: ' + sens + ' Deviation: ' + deviation;
  630. return rT;
  631. }
  632. var expectedDelta = calculate_expected_delta(target_bg, eventualBG, bgi);
  633. var minPredBG;
  634. var minGuardBG;
  635. //console.error(reservoir_data);
  636. // Initialize rT (requestedTemp) object. Has to be done after eventualBG is calculated.
  637. rT = {
  638. 'temp': 'absolute'
  639. , 'bg': bg
  640. , 'tick': tick
  641. , 'eventualBG': eventualBG
  642. , 'insulinReq': 0
  643. , 'reservoir' : reservoir_data // The expected reservoir volume at which to deliver the microbolus (the reservoir volume from right before the last pumphistory run)
  644. , 'deliverAt' : deliverAt // The time at which the microbolus should be delivered
  645. , 'sensitivityRatio' : sensitivityRatio
  646. , 'CR' : round(carbRatio, 1)
  647. , 'current_target': target_bg
  648. , 'insulinForManualBolus': insulinForManualBolus
  649. , 'manualBolusErrorString': manualBolusErrorString
  650. , 'minDelta': minDelta
  651. , 'expectedDelta': expectedDelta
  652. , 'minGuardBG': minGuardBG
  653. , 'minPredBG': minPredBG
  654. , 'threshold': convert_bg(threshold, profile)
  655. };
  656. // Generate predicted future BGs based on IOB, COB, and current absorption rate
  657. // Initialize and calculate variables used for predicting BGs
  658. var COBpredBGs = [];
  659. var IOBpredBGs = [];
  660. var UAMpredBGs = [];
  661. var ZTpredBGs = [];
  662. COBpredBGs.push(bg);
  663. IOBpredBGs.push(bg);
  664. ZTpredBGs.push(bg);
  665. UAMpredBGs.push(bg);
  666. let enableSMB = false;
  667. // If SMB is always off, don't bother checking if we should enable SMBs
  668. if (smbIsOff) {
  669. console.error("SMBs are always off.");
  670. enableSMB = false;
  671. } else {
  672. enableSMB = enable_smb(
  673. profile,
  674. microBolusAllowed,
  675. meal_data,
  676. bg,
  677. target_bg,
  678. high_bg,
  679. oref2_variables,
  680. systemTime
  681. );
  682. }
  683. var enableUAM = (profile.enableUAM);
  684. //console.error(meal_data);
  685. // carb impact and duration are 0 unless changed below
  686. var ci = 0;
  687. var cid = 0;
  688. // calculate current carb absorption rate, and how long to absorb all carbs
  689. // CI = current carb impact on BG in mg/dL/5m
  690. ci = round((minDelta - bgi),1);
  691. var uci = round((minDelta - bgi),1);
  692. // ISF (mg/dL/U) / CR (g/U) = CSF (mg/dL/g)
  693. // use autosens-adjusted sens to counteract autosens meal insulin dosing adjustments so that
  694. // autotuned CR is still in effect even when basals and ISF are being adjusted by TT or autosens
  695. // this avoids overdosing insulin for large meals when low temp targets are active
  696. csf = sens / carbRatio;
  697. console.error("profile.sens:" + convert_bg(sensitivity,profile) + ", sens:" + convert_bg(sens,profile) + ", CSF:" + round(csf,1));
  698. var maxCarbAbsorptionRate = 30; // g/h; maximum rate to assume carbs will absorb if no CI observed
  699. // limitLog Carb Impact to maxCarbAbsorptionRate * csf in mg/dL per 5m
  700. var maxCI = round(maxCarbAbsorptionRate*csf*5/60,1);
  701. if (ci > maxCI) {
  702. console.error("Limiting carb impact from " + ci + " to " + maxCI + "mg/dL/5m (" + maxCarbAbsorptionRate + "g/h)");
  703. ci = maxCI;
  704. }
  705. var remainingCATimeMin = 3; // h; minimum duration of expected not-yet-observed carb absorption
  706. // adjust remainingCATime (instead of CR) for autosens if sensitivityRatio defined
  707. if (sensitivityRatio) {
  708. remainingCATimeMin = remainingCATimeMin / sensitivityRatio;
  709. }
  710. // 20 g/h means that anything <= 60g will get a remainingCATimeMin, 80g will get 4h, and 120g 6h
  711. // when actual absorption ramps up it will take over from remainingCATime
  712. var assumedCarbAbsorptionRate = 20; // g/h; maximum rate to assume carbs will absorb if no CI observed
  713. var remainingCATime = remainingCATimeMin;
  714. if (meal_data.carbs) {
  715. // if carbs * assumedCarbAbsorptionRate > remainingCATimeMin, raise it
  716. // so <= 90g is assumed to take 3h, and 120g=4h
  717. remainingCATimeMin = Math.max(remainingCATimeMin, meal_data.mealCOB/assumedCarbAbsorptionRate);
  718. var lastCarbAge = round(( new Date(systemTime).getTime() - meal_data.lastCarbTime ) / 60000);
  719. //console.error(meal_data.lastCarbTime, lastCarbAge);
  720. var fractionCOBAbsorbed = ( meal_data.carbs - meal_data.mealCOB ) / meal_data.carbs;
  721. // if the lastCarbTime was 1h ago, increase remainingCATime by 1.5 hours
  722. remainingCATime = remainingCATimeMin + 1.5 * lastCarbAge/60;
  723. remainingCATime = round(remainingCATime,1);
  724. //console.error(fractionCOBAbsorbed, remainingCATimeAdjustment, remainingCATime)
  725. console.error("Last carbs " + lastCarbAge + " minutes ago; remainingCATime:" + remainingCATime + "hours; " + round(fractionCOBAbsorbed*100, 1) + "% carbs absorbed");
  726. }
  727. // calculate the number of carbs absorbed over remainingCATime hours at current CI
  728. // CI (mg/dL/5m) * (5m)/5 (m) * 60 (min/hr) * 4 (h) / 2 (linear decay factor) = total carb impact (mg/dL)
  729. var totalCI = Math.max(0, ci / 5 * 60 * remainingCATime / 2);
  730. // totalCI (mg/dL) / CSF (mg/dL/g) = total carbs absorbed (g)
  731. var totalCA = totalCI / csf;
  732. var remainingCarbsCap = 90; // default to 90
  733. var remainingCarbsFraction = 1;
  734. if (profile.remainingCarbsCap) { remainingCarbsCap = Math.min(90,profile.remainingCarbsCap); }
  735. if (profile.remainingCarbsFraction) { remainingCarbsFraction = Math.min(1,profile.remainingCarbsFraction); }
  736. var remainingCarbsIgnore = 1 - remainingCarbsFraction;
  737. var remainingCarbs = Math.max(0, meal_data.mealCOB - totalCA - meal_data.carbs*remainingCarbsIgnore);
  738. remainingCarbs = Math.min(remainingCarbsCap,remainingCarbs);
  739. // assume remainingCarbs will absorb in a /\ shaped bilinear curve
  740. // peaking at remainingCATime / 2 and ending at remainingCATime hours
  741. // area of the /\ triangle is the same as a remainingCIpeak-height rectangle out to remainingCATime/2
  742. // remainingCIpeak (mg/dL/5m) = remainingCarbs (g) * CSF (mg/dL/g) * 5 (m/5m) * 1h/60m / (remainingCATime/2) (h)
  743. var remainingCIpeak = remainingCarbs * csf * 5 / 60 / (remainingCATime/2);
  744. //console.error(profile.min_5m_carbimpact,ci,totalCI,totalCA,remainingCarbs,remainingCI,remainingCATime);
  745. // calculate peak deviation in last hour, and slope from that to current deviation
  746. var slopeFromMaxDeviation = round(meal_data.slopeFromMaxDeviation,2);
  747. // calculate lowest deviation in last hour, and slope from that to current deviation
  748. var slopeFromMinDeviation = round(meal_data.slopeFromMinDeviation,2);
  749. // assume deviations will drop back down at least at 1/3 the rate they ramped up
  750. var slopeFromDeviations = Math.min(slopeFromMaxDeviation,-slopeFromMinDeviation/3);
  751. //console.error(slopeFromMaxDeviation);
  752. //5m data points = g * (1U/10g) * (40mg/dL/1U) / (mg/dL/5m)
  753. // duration (in 5m data points) = COB (g) * CSF (mg/dL/g) / ci (mg/dL/5m)
  754. // limitLog cid to remainingCATime hours: the reset goes to remainingCI
  755. var nfcid = 0;
  756. if (ci === 0) {
  757. // avoid divide by zero
  758. cid = 0;
  759. } else { cid = Math.min(remainingCATime*60/5/2,Math.max(0, meal_data.mealCOB * csf / ci )); }
  760. // duration (hours) = duration (5m) * 5 / 60 * 2 (to account for linear decay)
  761. console.error("Carb Impact:" + ci + "mg/dL per 5m; CI Duration:" + round(cid*5/60*2,1) + "hours; remaining CI (" + remainingCATime/2 + "h peak):" + round(remainingCIpeak,1) + "mg/dL per 5m");
  762. var minIOBPredBG = 999;
  763. var minCOBPredBG = 999;
  764. var minUAMPredBG = 999;
  765. //minGuardBG = bg;
  766. var minCOBGuardBG = 999;
  767. var minUAMGuardBG = 999;
  768. var minIOBGuardBG = 999;
  769. var minZTGuardBG = 999;
  770. var minPredBG;
  771. var avgPredBG;
  772. var IOBpredBG = eventualBG;
  773. var maxIOBPredBG = bg;
  774. var maxCOBPredBG = bg;
  775. var maxUAMPredBG = bg;
  776. var eventualPredBG = bg;
  777. var lastIOBpredBG;
  778. var lastCOBpredBG;
  779. var lastUAMpredBG;
  780. var lastZTpredBG;
  781. var UAMduration = 0;
  782. var remainingCItotal = 0;
  783. var remainingCIs = [];
  784. var predCIs = [];
  785. try {
  786. iobArray.forEach(function(iobTick) {
  787. //console.error(iobTick);
  788. var predBGI = round(( -iobTick.activity * sens * 5 ), 2);
  789. var predZTBGI = round(( -iobTick.iobWithZeroTemp.activity * sens * 5 ), 2);
  790. var ZTpredBG = naive_eventualBG;
  791. // for IOBpredBGs, predicted deviation impact drops linearly from current deviation down to zero
  792. // over 60 minutes (data points every 5m)
  793. var predDev = ci * ( 1 - Math.min(1,IOBpredBGs.length/(60/5)) );
  794. // Adding dynamic ISF in predictions for ZT and IOB. Modification from Tim Street's AAPS but with default as off:
  795. switch(true) {
  796. case dynISFenabled && !enable_sigmoid:
  797. //IOBpredBG = IOBpredBGs[IOBpredBGs.length-1] + predBGI + predDev; // Adding dynamic ISF in predictions for UAM, ZT and IOB:
  798. IOBpredBG = IOBpredBGs[IOBpredBGs.length-1] + (round(( -iobTick.activity * (1800 / ( tdd * adjustmentFactor * (Math.log((Math.max( IOBpredBGs[IOBpredBGs.length-1],39) / insulinFactor ) + 1 ) ) )) * 5 ),2)) + predDev;
  799. //var ZTpredBG = ZTpredBGs[ZTpredBGs.length-1] + predZTBGI; // Adding dynamic ISF in predictions for UAM, ZT and IOB:
  800. ZTpredBG = ZTpredBGs[ZTpredBGs.length-1] + (round(( -iobTick.iobWithZeroTemp.activity * (1800 / ( tdd * adjustmentFactor * (Math.log(( Math.max(ZTpredBGs[ZTpredBGs.length-1],39) / insulinFactor ) + 1 ) ) )) * 5 ), 2));
  801. console.log("Dynamic ISF (Logarithmic Formula) )adjusted predictions for IOB and ZT: IOBpredBG: " + round(IOBpredBG,2) + " , ZTpredBG: " + round(ZTpredBG,2));
  802. break;
  803. default:
  804. IOBpredBG = IOBpredBGs[IOBpredBGs.length-1] + predBGI + predDev;
  805. // calculate predBGs with long zero temp without deviations
  806. ZTpredBG = ZTpredBGs[ZTpredBGs.length-1] + predZTBGI;
  807. }
  808. // for COBpredBGs, predicted carb impact drops linearly from current carb impact down to zero
  809. // eventually accounting for all carbs (if they can be absorbed over DIA)
  810. var predCI = Math.max(0, Math.max(0,ci) * ( 1 - COBpredBGs.length/Math.max(cid*2,1) ) );
  811. // if any carbs aren't absorbed after remainingCATime hours, assume they'll absorb in a /\ shaped
  812. // bilinear curve peaking at remainingCIpeak at remainingCATime/2 hours (remainingCATime/2*12 * 5m)
  813. // and ending at remainingCATime h (remainingCATime*12 * 5m intervals)
  814. var intervals = Math.min( COBpredBGs.length, (remainingCATime*12)-COBpredBGs.length );
  815. var remainingCI = Math.max(0, intervals / (remainingCATime/2*12) * remainingCIpeak );
  816. remainingCItotal += predCI+remainingCI;
  817. remainingCIs.push(round(remainingCI,0));
  818. predCIs.push(round(predCI,0));
  819. //process.stderr.write(round(predCI,1)+"+"+round(remainingCI,1)+" ");
  820. COBpredBG = COBpredBGs[COBpredBGs.length-1] + predBGI + Math.min(0,predDev) + predCI + remainingCI;
  821. // for UAMpredBGs, predicted carb impact drops at slopeFromDeviations
  822. // calculate predicted CI from UAM based on slopeFromDeviations
  823. var predUCIslope = Math.max(0, uci + ( UAMpredBGs.length*slopeFromDeviations ) );
  824. // if slopeFromDeviations is too flat, predicted deviation impact drops linearly from
  825. // current deviation down to zero over 3h (data points every 5m)
  826. var predUCImax = Math.max(0, uci * ( 1 - UAMpredBGs.length/Math.max(3*60/5,1) ) );
  827. //console.error(predUCIslope, predUCImax);
  828. // predicted CI from UAM is the lesser of CI based on deviationSlope or DIA
  829. var predUCI = Math.min(predUCIslope, predUCImax);
  830. if(predUCI>0) {
  831. //console.error(UAMpredBGs.length,slopeFromDeviations, predUCI);
  832. UAMduration=round((UAMpredBGs.length+1)*5/60,1);
  833. }
  834. // Adding dynamic ISF in predictions for UAM. Modification from Tim Street's AAPS but with default as off:
  835. switch(true) {
  836. case dynISFenabled && !enable_sigmoid:
  837. //UAMpredBG = UAMpredBGs[UAMpredBGs.length-1] + predBGI + Math.min(0, predDev) + predUCI; // Adding dynamic ISF in predictions for UAM:
  838. UAMpredBG = UAMpredBGs[UAMpredBGs.length-1] + (round(( -iobTick.activity * (1800 / ( tdd * adjustmentFactor * (Math.log(( Math.max(UAMpredBGs[UAMpredBGs.length-1],39) / insulinFactor ) + 1 ) ) )) * 5 ),2)) + Math.min(0, predDev) + predUCI;
  839. console.log("Dynamic ISF (Logarithmic Formula) adjusted prediction for UAM: UAMpredBG: " + round(UAMpredBG,2));
  840. break;
  841. default:
  842. UAMpredBG = UAMpredBGs[UAMpredBGs.length-1] + predBGI + Math.min(0, predDev) + predUCI;
  843. }
  844. //console.error(predBGI, predCI, predUCI);
  845. // truncate all BG predictions at 4 hours
  846. if ( IOBpredBGs.length < 48 ) { IOBpredBGs.push(IOBpredBG); }
  847. if ( COBpredBGs.length < 48 ) { COBpredBGs.push(COBpredBG); }
  848. if ( UAMpredBGs.length < 48 ) { UAMpredBGs.push(UAMpredBG); }
  849. if ( ZTpredBGs.length < 48 ) { ZTpredBGs.push(ZTpredBG); }
  850. // calculate minGuardBGs without a wait from COB, UAM, IOB predBGs
  851. if ( COBpredBG < minCOBGuardBG ) { minCOBGuardBG = round(COBpredBG); }
  852. if ( UAMpredBG < minUAMGuardBG ) { minUAMGuardBG = round(UAMpredBG); }
  853. if ( IOBpredBG < minIOBGuardBG ) { minIOBGuardBG = round(IOBpredBG); }
  854. if ( ZTpredBG < minZTGuardBG ) { minZTGuardBG = round(ZTpredBG); }
  855. // set minPredBGs starting when currently-dosed insulin activity will peak
  856. // look ahead 60m (regardless of insulin type) so as to be less aggressive on slower insulins
  857. var insulinPeakTime = 60;
  858. // add 30m to allow for insulin delivery (SMBs or temps)
  859. insulinPeakTime = 90;
  860. var insulinPeak5m = (insulinPeakTime/60)*12;
  861. //console.error(insulinPeakTime, insulinPeak5m, profile.insulinPeakTime, profile.curve);
  862. // wait 90m before setting minIOBPredBG
  863. if ( IOBpredBGs.length > insulinPeak5m && (IOBpredBG < minIOBPredBG) ) { minIOBPredBG = round(IOBpredBG); }
  864. if ( IOBpredBG > maxIOBPredBG ) { maxIOBPredBG = IOBpredBG; }
  865. // wait 85-105m before setting COB and 60m for UAM minPredBGs
  866. if ( (cid || remainingCIpeak > 0) && COBpredBGs.length > insulinPeak5m && (COBpredBG < minCOBPredBG) ) { minCOBPredBG = round(COBpredBG); }
  867. if ( (cid || remainingCIpeak > 0) && COBpredBG > maxIOBPredBG ) { maxCOBPredBG = COBpredBG; }
  868. if ( enableUAM && UAMpredBGs.length > 12 && (UAMpredBG < minUAMPredBG) ) { minUAMPredBG = round(UAMpredBG); }
  869. if ( enableUAM && UAMpredBG > maxIOBPredBG ) { maxUAMPredBG = UAMpredBG; }
  870. });
  871. // set eventualBG to include effect of carbs
  872. //console.error("PredBGs:",JSON.stringify(predBGs));
  873. } catch (e) {
  874. console.error("Problem with iobArray. Optional feature Advanced Meal Assist disabled");
  875. }
  876. if (meal_data.mealCOB) {
  877. console.error("predCIs (mg/dL/5m):" + predCIs.join(" "));
  878. console.error("remainingCIs: " + remainingCIs.join(" "));
  879. }
  880. rT.predBGs = {};
  881. IOBpredBGs.forEach(function(p, i, theArray) {
  882. theArray[i] = round(Math.min(401,Math.max(39,p)));
  883. });
  884. for (var i=IOBpredBGs.length-1; i > 12; i--) {
  885. if (IOBpredBGs[i-1] !== IOBpredBGs[i]) { break; }
  886. else { IOBpredBGs.pop(); }
  887. }
  888. rT.predBGs.IOB = IOBpredBGs;
  889. lastIOBpredBG=round(IOBpredBGs[IOBpredBGs.length-1]);
  890. ZTpredBGs.forEach(function(p, i, theArray) {
  891. theArray[i] = round(Math.min(401,Math.max(39,p)));
  892. });
  893. for (i=ZTpredBGs.length-1; i > 6; i--) {
  894. // stop displaying ZTpredBGs once they're rising and above target
  895. if (ZTpredBGs[i-1] >= ZTpredBGs[i] || ZTpredBGs[i] <= target_bg) { break; }
  896. else { ZTpredBGs.pop(); }
  897. }
  898. rT.predBGs.ZT = ZTpredBGs;
  899. lastZTpredBG=round(ZTpredBGs[ZTpredBGs.length-1]);
  900. if (meal_data.mealCOB > 0 && ( ci > 0 || remainingCIpeak > 0 )) {
  901. COBpredBGs.forEach(function(p, i, theArray) {
  902. theArray[i] = round(Math.min(1500,Math.max(39,p)));
  903. });
  904. for (i=COBpredBGs.length-1; i > 12; i--) {
  905. if (COBpredBGs[i-1] !== COBpredBGs[i]) { break; }
  906. else { COBpredBGs.pop(); }
  907. }
  908. rT.predBGs.COB = COBpredBGs;
  909. lastCOBpredBG=round(COBpredBGs[COBpredBGs.length-1]);
  910. eventualBG = Math.max(eventualBG, round(COBpredBGs[COBpredBGs.length-1]));
  911. console.error("COBpredBG: " + round(COBpredBGs[COBpredBGs.length-1]) );
  912. }
  913. if (ci > 0 || remainingCIpeak > 0) {
  914. if (enableUAM) {
  915. UAMpredBGs.forEach(function(p, i, theArray) {
  916. theArray[i] = round(Math.min(401,Math.max(39,p)));
  917. });
  918. for (i=UAMpredBGs.length-1; i > 12; i--) {
  919. if (UAMpredBGs[i-1] !== UAMpredBGs[i]) { break; }
  920. else { UAMpredBGs.pop(); }
  921. }
  922. rT.predBGs.UAM = UAMpredBGs;
  923. lastUAMpredBG=round(UAMpredBGs[UAMpredBGs.length-1]);
  924. if (UAMpredBGs[UAMpredBGs.length-1]) {
  925. eventualBG = Math.max(eventualBG, round(UAMpredBGs[UAMpredBGs.length-1]) );
  926. }
  927. }
  928. // set eventualBG based on COB or UAM predBGs
  929. rT.eventualBG = eventualBG;
  930. }
  931. console.error("UAM Impact:" + uci + "mg/dL per 5m; UAM Duration:" + UAMduration + "hours");
  932. minIOBPredBG = Math.max(39,minIOBPredBG);
  933. minCOBPredBG = Math.max(39,minCOBPredBG);
  934. minUAMPredBG = Math.max(39,minUAMPredBG);
  935. minPredBG = round(minIOBPredBG);
  936. var fractionCarbsLeft = meal_data.mealCOB/meal_data.carbs;
  937. // if we have COB and UAM is enabled, average both
  938. if ( minUAMPredBG < 999 && minCOBPredBG < 999 ) {
  939. // weight COBpredBG vs. UAMpredBG based on how many carbs remain as COB
  940. avgPredBG = round( (1-fractionCarbsLeft)*UAMpredBG + fractionCarbsLeft*COBpredBG );
  941. // if UAM is disabled, average IOB and COB
  942. } else if ( minCOBPredBG < 999 ) {
  943. avgPredBG = round( (IOBpredBG + COBpredBG)/2 );
  944. // if we have UAM but no COB, average IOB and UAM
  945. } else if ( minUAMPredBG < 999 ) {
  946. avgPredBG = round( (IOBpredBG + UAMpredBG)/2 );
  947. } else {
  948. avgPredBG = round( IOBpredBG );
  949. }
  950. // if avgPredBG is below minZTGuardBG, bring it up to that level
  951. if ( minZTGuardBG > avgPredBG ) {
  952. avgPredBG = minZTGuardBG;
  953. }
  954. // if we have both minCOBGuardBG and minUAMGuardBG, blend according to fractionCarbsLeft
  955. if ( (cid || remainingCIpeak > 0) ) {
  956. if ( enableUAM ) {
  957. minGuardBG = fractionCarbsLeft*minCOBGuardBG + (1-fractionCarbsLeft)*minUAMGuardBG;
  958. } else {
  959. minGuardBG = minCOBGuardBG;
  960. }
  961. } else if ( enableUAM ) {
  962. minGuardBG = minUAMGuardBG;
  963. } else {
  964. minGuardBG = minIOBGuardBG;
  965. }
  966. minGuardBG = round(minGuardBG);
  967. //console.error(minCOBGuardBG, minUAMGuardBG, minIOBGuardBG, minGuardBG);
  968. var minZTUAMPredBG = minUAMPredBG;
  969. // if minZTGuardBG is below threshold, bring down any super-high minUAMPredBG by averaging
  970. // this helps prevent UAM from giving too much insulin in case absorption falls off suddenly
  971. if ( minZTGuardBG < threshold ) {
  972. minZTUAMPredBG = (minUAMPredBG + minZTGuardBG) / 2;
  973. // if minZTGuardBG is between threshold and target, blend in the averaging
  974. } else if ( minZTGuardBG < target_bg ) {
  975. // target 100, threshold 70, minZTGuardBG 85 gives 50%: (85-70) / (100-70)
  976. var blendPct = (minZTGuardBG-threshold) / (target_bg-threshold);
  977. var blendedMinZTGuardBG = minUAMPredBG*blendPct + minZTGuardBG*(1-blendPct);
  978. minZTUAMPredBG = (minUAMPredBG + blendedMinZTGuardBG) / 2;
  979. //minZTUAMPredBG = minUAMPredBG - target_bg + minZTGuardBG;
  980. // if minUAMPredBG is below minZTGuardBG, bring minUAMPredBG up by averaging
  981. // this allows more insulin if lastUAMPredBG is below target, but minZTGuardBG is still high
  982. } else if ( minZTGuardBG > minUAMPredBG ) {
  983. minZTUAMPredBG = (minUAMPredBG + minZTGuardBG) / 2;
  984. }
  985. minZTUAMPredBG = round(minZTUAMPredBG);
  986. //console.error("minUAMPredBG:",minUAMPredBG,"minZTGuardBG:",minZTGuardBG,"minZTUAMPredBG:",minZTUAMPredBG);
  987. // if any carbs have been entered recently
  988. if (meal_data.carbs) {
  989. // if UAM is disabled, use max of minIOBPredBG, minCOBPredBG
  990. if ( ! enableUAM && minCOBPredBG < 999 ) {
  991. minPredBG = round(Math.max(minIOBPredBG, minCOBPredBG));
  992. // if we have COB, use minCOBPredBG, or blendedMinPredBG if it's higher
  993. } else if ( minCOBPredBG < 999 ) {
  994. // calculate blendedMinPredBG based on how many carbs remain as COB
  995. var blendedMinPredBG = fractionCarbsLeft*minCOBPredBG + (1-fractionCarbsLeft)*minZTUAMPredBG;
  996. // if blendedMinPredBG > minCOBPredBG, use that instead
  997. minPredBG = round(Math.max(minIOBPredBG, minCOBPredBG, blendedMinPredBG));
  998. // if carbs have been entered, but have expired, use minUAMPredBG
  999. } else if ( enableUAM ) {
  1000. minPredBG = minZTUAMPredBG;
  1001. } else {
  1002. minPredBG = minGuardBG;
  1003. }
  1004. // in pure UAM mode, use the higher of minIOBPredBG,minUAMPredBG
  1005. } else if ( enableUAM ) {
  1006. minPredBG = round(Math.max(minIOBPredBG,minZTUAMPredBG));
  1007. }
  1008. // make sure minPredBG isn't higher than avgPredBG
  1009. minPredBG = Math.min( minPredBG, avgPredBG );
  1010. // Print summary variables based on predBGs etc.
  1011. process.stderr.write("minPredBG: "+minPredBG+" minIOBPredBG: "+minIOBPredBG+" minZTGuardBG: "+minZTGuardBG);
  1012. if (minCOBPredBG < 999) {
  1013. process.stderr.write(" minCOBPredBG: "+minCOBPredBG);
  1014. }
  1015. if (minUAMPredBG < 999) {
  1016. process.stderr.write(" minUAMPredBG: "+minUAMPredBG);
  1017. }
  1018. console.error(" avgPredBG:" + avgPredBG + " COB/Carbs:" + meal_data.mealCOB + "/" + meal_data.carbs);
  1019. // But if the COB line falls off a cliff, don't trust UAM too much:
  1020. // use maxCOBPredBG if it's been set and lower than minPredBG
  1021. if ( maxCOBPredBG > bg ) {
  1022. minPredBG = Math.min(minPredBG, maxCOBPredBG);
  1023. }
  1024. rT.COB=meal_data.mealCOB;
  1025. rT.IOB=iob_data.iob;
  1026. rT.BGI=convert_bg(bgi,profile);
  1027. rT.deviation=convert_bg(deviation, profile);
  1028. rT.ISF=convert_bg(sens, profile);
  1029. rT.CR=round(carbRatio, 1);
  1030. rT.target_bg=convert_bg(target_bg, profile);
  1031. rT.current_target=round(target_bg, 0);
  1032. rT.reason = isfreason + ", COB: " + rT.COB + ", Dev: " + rT.deviation + ", BGI: " + rT.BGI + ", CR: " + rT.CR + ", Target: " + targetLog + ", minPredBG " + convert_bg(minPredBG, profile) + ", minGuardBG " + convert_bg(minGuardBG, profile) + ", IOBpredBG " + convert_bg(lastIOBpredBG, profile);
  1033. if (lastCOBpredBG > 0) {
  1034. rT.reason += ", COBpredBG " + convert_bg(lastCOBpredBG, profile);
  1035. }
  1036. if (lastUAMpredBG > 0) {
  1037. rT.reason += ", UAMpredBG " + convert_bg(lastUAMpredBG, profile);
  1038. }
  1039. rT.reason += tddReason;
  1040. rT.reason += "; "; // reason.conclusion started
  1041. // Use minGuardBG to prevent overdosing in hypo-risk situations
  1042. // use naive_eventualBG if above 40, but switch to minGuardBG if both eventualBGs hit floor of 39
  1043. var carbsReqBG = naive_eventualBG;
  1044. if ( carbsReqBG < 40 ) {
  1045. carbsReqBG = Math.min( minGuardBG, carbsReqBG );
  1046. }
  1047. var bgUndershoot = threshold - carbsReqBG;
  1048. // calculate how long until COB (or IOB) predBGs drop below min_bg
  1049. var minutesAboveMinBG = 240;
  1050. var minutesAboveThreshold = 240;
  1051. if (meal_data.mealCOB > 0 && ( ci > 0 || remainingCIpeak > 0 )) {
  1052. for (i=0; i<COBpredBGs.length; i++) {
  1053. if ( COBpredBGs[i] < min_bg ) {
  1054. minutesAboveMinBG = 5*i;
  1055. break;
  1056. }
  1057. }
  1058. for (i=0; i<COBpredBGs.length; i++) {
  1059. if ( COBpredBGs[i] < threshold ) {
  1060. minutesAboveThreshold = 5*i;
  1061. break;
  1062. }
  1063. }
  1064. }
  1065. else {
  1066. for (i=0; i<IOBpredBGs.length; i++) {
  1067. //console.error(IOBpredBGs[i], min_bg);
  1068. if ( IOBpredBGs[i] < min_bg ) {
  1069. minutesAboveMinBG = 5*i;
  1070. break;
  1071. }
  1072. }
  1073. for (i=0; i<IOBpredBGs.length; i++) {
  1074. //console.error(IOBpredBGs[i], threshold);
  1075. if ( IOBpredBGs[i] < threshold ) {
  1076. minutesAboveThreshold = 5*i;
  1077. break;
  1078. }
  1079. }
  1080. }
  1081. if (enableSMB && minGuardBG < threshold) {
  1082. console.error("minGuardBG " + convert_bg(minGuardBG, profile) + " projected below " + convert_bg(threshold, profile) + " - disabling SMB");
  1083. rT.manualBolusErrorString = 1;
  1084. rT.minGuardBG = minGuardBG;
  1085. rT.insulinForManualBolus = round((rT.eventualBG - rT.target_bg) / sens, 2);
  1086. //rT.reason += "minGuardBG "+minGuardBG+"<"+threshold+": SMB disabled; ";
  1087. enableSMB = false;
  1088. }
  1089. // Disable SMB for sudden rises (often caused by calibrations or activation/deactivation of Dexcom's noise-filtering algorithm)
  1090. // Added maxDelta_bg_threshold as a hidden preference and included a cap at 0.4 as a safety limitLog
  1091. var maxDelta_bg_threshold;
  1092. if (typeof profile.maxDelta_bg_threshold === 'undefined') {
  1093. maxDelta_bg_threshold = 0.2;
  1094. }
  1095. if (typeof profile.maxDelta_bg_threshold !== 'undefined') {
  1096. maxDelta_bg_threshold = Math.min(profile.maxDelta_bg_threshold, 0.4);
  1097. }
  1098. if ( maxDelta > maxDelta_bg_threshold * bg ) {
  1099. console.error("maxDelta " + convert_bg(maxDelta, profile)+ " > " + 100 * maxDelta_bg_threshold + "% of BG " + convert_bg(bg, profile) + " - disabling SMB");
  1100. rT.reason += "maxDelta " + convert_bg(maxDelta, profile) + " > " + 100 * maxDelta_bg_threshold + "% of BG " + convert_bg(bg, profile) + " - SMB disabled!, ";
  1101. enableSMB = false;
  1102. }
  1103. // Calculate carbsReq (carbs required to avoid a hypo)
  1104. console.error("BG projected to remain above " + convert_bg(min_bg, profile) + " for " + minutesAboveMinBG + "minutes");
  1105. if ( minutesAboveThreshold < 240 || minutesAboveMinBG < 60 ) {
  1106. console.error("BG projected to remain above " + convert_bg(threshold,profile) + " for " + minutesAboveThreshold + "minutes");
  1107. }
  1108. // include at least minutesAboveThreshold worth of zero temps in calculating carbsReq
  1109. // always include at least 30m worth of zero temp (carbs to 80, low temp up to target)
  1110. var zeroTempDuration = minutesAboveThreshold;
  1111. // BG undershoot, minus effect of zero temps until hitting min_bg, converted to grams, minus COB
  1112. var zeroTempEffect = profile.current_basal*overrideFactor*sens*zeroTempDuration/60;
  1113. // don't count the last 25% of COB against carbsReq
  1114. var COBforCarbsReq = Math.max(0, meal_data.mealCOB - 0.25*meal_data.carbs);
  1115. var carbsReq = (bgUndershoot - zeroTempEffect) / csf - COBforCarbsReq;
  1116. zeroTempEffect = round(zeroTempEffect);
  1117. carbsReq = round(carbsReq);
  1118. console.error("naive_eventualBG:",naive_eventualBG,"bgUndershoot:",bgUndershoot,"zeroTempDuration:",zeroTempDuration,"zeroTempEffect:",zeroTempEffect,"carbsReq:",carbsReq);
  1119. if ( meal_data.reason == "Could not parse clock data" ) {
  1120. console.error("carbsReq unknown: Could not parse clock data");
  1121. } else if ( carbsReq >= profile.carbsReqThreshold && minutesAboveThreshold <= 45 ) {
  1122. rT.carbsReq = carbsReq;
  1123. rT.reason += carbsReq + " add'l carbs req w/in " + minutesAboveThreshold + "m; ";
  1124. }
  1125. // Begin core dosing logic: check for situations requiring low or high temps, and return appropriate temp after first match
  1126. // don't low glucose suspend if IOB is already super negative and BG is rising faster than predicted
  1127. var worstCaseInsulinReq = 0;
  1128. var durationReq = 0;
  1129. if (bg < threshold && iob_data.iob < -profile.current_basal*overrideFactor*20/60 && minDelta > 0 && minDelta > expectedDelta) {
  1130. rT.reason += "IOB "+iob_data.iob+" < " + round(-profile.current_basal*overrideFactor*20/60,2);
  1131. rT.reason += " and minDelta " + convert_bg(minDelta, profile) + " > " + "expectedDelta " + convert_bg(expectedDelta, profile) + "; ";
  1132. // predictive low glucose suspend mode: BG is / is projected to be < threshold
  1133. } else if ( bg < threshold || minGuardBG < threshold ) {
  1134. rT.reason += "minGuardBG " + convert_bg(minGuardBG, profile) + "<" + convert_bg(threshold, profile);
  1135. bgUndershoot = target_bg - minGuardBG;
  1136. if (minGuardBG < threshold) {
  1137. rT.manualBolusErrorString = 2;
  1138. rT.minGuardBG = minGuardBG;
  1139. }
  1140. rT.insulinForManualBolus = round((eventualBG - target_bg) / sens, 2);
  1141. worstCaseInsulinReq = bgUndershoot / sens;
  1142. durationReq = round(60*worstCaseInsulinReq / profile.current_basal*overrideFactor);
  1143. durationReq = round(durationReq/30)*30;
  1144. // always set a 30-120m zero temp (oref0-pump-loop will let any longer SMB zero temp run)
  1145. durationReq = Math.min(120,Math.max(30,durationReq));
  1146. return tempBasalFunctions.setTempBasal(0, durationReq, profile, rT, currenttemp);
  1147. }
  1148. // if not in LGS mode, cancel temps before the top of the hour to reduce beeping/vibration
  1149. // console.error(profile.skip_neutral_temps, rT.deliverAt.getMinutes());
  1150. if ( profile.skip_neutral_temps && rT.deliverAt.getMinutes() >= 55 ) {
  1151. if (!enableSMB) {
  1152. rT.reason += "; Canceling temp at " + (60 - rT.deliverAt.getMinutes()) + "min before turn of the hour to avoid beeping of MDT. SMB are disabled anyways.";
  1153. return tempBasalFunctions.setTempBasal(0, 0, profile, rT, currenttemp);
  1154. } else {
  1155. console.error((60 - rT.deliverAt.getMinutes()) + "min before turn of the hour, but SMB's are enabled - not skipping neutral temps.")
  1156. }
  1157. }
  1158. var insulinReq = 0;
  1159. var rate = basal;
  1160. var insulinScheduled = 0;
  1161. if (eventualBG < min_bg) { // if eventual BG is below target:
  1162. rT.reason += "Eventual BG " + convert_bg(eventualBG, profile) + " < " + convert_bg(min_bg, profile);
  1163. // if 5m or 30m avg BG is rising faster than expected delta
  1164. if ( minDelta > expectedDelta && minDelta > 0 && !carbsReq ) {
  1165. // if naive_eventualBG < 40, set a 30m zero temp (oref0-pump-loop will let any longer SMB zero temp run)
  1166. if (naive_eventualBG < 40) {
  1167. rT.reason += ", naive_eventualBG < 40. ";
  1168. return tempBasalFunctions.setTempBasal(0, 30, profile, rT, currenttemp);
  1169. }
  1170. if (glucose_status.delta > minDelta) {
  1171. rT.reason += ", but Delta " + convert_bg(tick, profile) + " > expectedDelta " + convert_bg(expectedDelta, profile);
  1172. } else {
  1173. rT.reason += ", but Min. Delta " + minDelta.toFixed(2) + " > Exp. Delta " + convert_bg(expectedDelta, profile);
  1174. }
  1175. if (currenttemp.duration > 15 && (round_basal(basal, profile) === round_basal(currenttemp.rate, profile))) {
  1176. rT.reason += ", temp " + currenttemp.rate + " ~ req " + basal + "U/hr. ";
  1177. return rT;
  1178. } else {
  1179. rT.reason += "; setting current basal of " + basal + " as temp. ";
  1180. return tempBasalFunctions.setTempBasal(basal, 30, profile, rT, currenttemp);
  1181. }
  1182. }
  1183. // calculate 30m low-temp required to get projected BG up to target
  1184. // multiply by 2 to low-temp faster for increased hypo safety
  1185. insulinReq = 2 * Math.min(0, (eventualBG - target_bg) / sens);
  1186. insulinReq = round( insulinReq , 2);
  1187. // calculate naiveInsulinReq based on naive_eventualBG
  1188. var naiveInsulinReq = Math.min(0, (naive_eventualBG - target_bg) / sens);
  1189. naiveInsulinReq = round( naiveInsulinReq , 2);
  1190. if (minDelta < 0 && minDelta > expectedDelta) {
  1191. // if we're barely falling, newinsulinReq should be barely negative
  1192. var newinsulinReq = round(( insulinReq * (minDelta / expectedDelta) ), 2);
  1193. //console.error("Increasing insulinReq from " + insulinReq + " to " + newinsulinReq);
  1194. insulinReq = newinsulinReq;
  1195. }
  1196. // rate required to deliver insulinReq less insulin over 30m:
  1197. rate = basal + (2 * insulinReq);
  1198. rate = round_basal(rate, profile);
  1199. // if required temp < existing temp basal
  1200. insulinScheduled = currenttemp.duration * (currenttemp.rate - basal) / 60;
  1201. // if current temp would deliver a lot (30% of basal) less than the required insulin,
  1202. // by both normal and naive calculations, then raise the rate
  1203. var minInsulinReq = Math.min(insulinReq,naiveInsulinReq);
  1204. console.log("naiveInsulinReq:" + naiveInsulinReq);
  1205. if (insulinScheduled < minInsulinReq - basal*0.3) {
  1206. rT.reason += ", " + currenttemp.duration + "m@" + (currenttemp.rate).toFixed(2) + " is a lot less than needed. ";
  1207. return tempBasalFunctions.setTempBasal(rate, 30, profile, rT, currenttemp);
  1208. }
  1209. if (typeof currenttemp.rate !== 'undefined' && (currenttemp.duration > 5 && rate >= currenttemp.rate * 0.8)) {
  1210. rT.reason += ", temp " + currenttemp.rate + " ~< req " + rate + "U/hr. ";
  1211. return rT;
  1212. }
  1213. else {
  1214. // calculate a long enough zero temp to eventually correct back up to target
  1215. if ( rate <=0 ) {
  1216. bgUndershoot = target_bg - naive_eventualBG;
  1217. worstCaseInsulinReq = bgUndershoot / sens;
  1218. durationReq = round(60*worstCaseInsulinReq / profile.current_basal * overrideFactor);
  1219. if (durationReq < 0) {
  1220. durationReq = 0;
  1221. // don't set a temp longer than 120 minutes
  1222. } else {
  1223. durationReq = round(durationReq/30)*30;
  1224. durationReq = Math.min(120,Math.max(0,durationReq));
  1225. }
  1226. //console.error(durationReq);
  1227. if (durationReq > 0) {
  1228. rT.reason += ", setting " + durationReq + "m zero temp. ";
  1229. return tempBasalFunctions.setTempBasal(rate, durationReq, profile, rT, currenttemp);
  1230. }
  1231. }
  1232. else {
  1233. rT.reason += ", setting " + rate + "U/hr. ";
  1234. }
  1235. return tempBasalFunctions.setTempBasal(rate, 30, profile, rT, currenttemp);
  1236. }
  1237. }
  1238. // if eventual BG is above min_bg but BG is falling faster than expected Delta
  1239. if (minDelta < expectedDelta) {
  1240. rT.minDelta = minDelta;
  1241. rT.expectedDelta = expectedDelta;
  1242. //Describe how the glucose is changing
  1243. if (expectedDelta - minDelta >= 2 || (expectedDelta + (-1 * minDelta) >= 2)) {
  1244. if (minDelta >= 0 && expectedDelta > 0) {
  1245. rT.manualBolusErrorString = 3;
  1246. }
  1247. else if ((minDelta < 0 && expectedDelta <= 0) || (minDelta < 0 && expectedDelta >= 0)) {
  1248. rT.manualBolusErrorString = 4;
  1249. }
  1250. else {
  1251. rT.manualBolusErrorString = 5;
  1252. }
  1253. }
  1254. rT.insulinForManualBolus = round((rT.eventualBG - rT.target_bg) / sens, 2);
  1255. // if in SMB mode, don't cancel SMB zero temp
  1256. if (! (microBolusAllowed && enableSMB)) {
  1257. if (glucose_status.delta < minDelta) {
  1258. rT.reason += "Eventual BG " + convert_bg(eventualBG, profile) + " > " + convert_bg(min_bg, profile) + " but Delta " + convert_bg(tick, profile) + " < Exp. Delta " + convert_bg(expectedDelta, profile);
  1259. } else {
  1260. rT.reason += "Eventual BG " + convert_bg(eventualBG, profile) + " > " + convert_bg(min_bg, profile) + " but Min. Delta " + minDelta.toFixed(2) + " < Exp. Delta " + convert_bg(expectedDelta, profile);
  1261. }
  1262. if (currenttemp.duration > 15 && (round_basal(basal, profile) === round_basal(currenttemp.rate, profile))) {
  1263. rT.reason += ", temp " + currenttemp.rate + " ~ req " + basal + "U/hr. ";
  1264. return rT;
  1265. } else {
  1266. rT.reason += "; setting current basal of " + basal + " as temp. ";
  1267. return tempBasalFunctions.setTempBasal(basal, 30, profile, rT, currenttemp);
  1268. }
  1269. }
  1270. }
  1271. // eventualBG or minPredBG is below max_bg
  1272. if (Math.min(eventualBG,minPredBG) < max_bg) {
  1273. if (minPredBG < min_bg && eventualBG > min_bg) {
  1274. rT.manualBolusErrorString = 6;
  1275. rT.insulinForManualBolus = round((rT.eventualBG - rT.target_bg) / sens, 2);
  1276. }
  1277. // Moving this out of the if condition in L1429, so that minPredBG is becomes always available in rT object (aka Trio's determination)
  1278. rT.minPredBG = minPredBG;
  1279. // if in SMB mode, don't cancel SMB zero temp
  1280. if (! (microBolusAllowed && enableSMB )) {
  1281. rT.reason += convert_bg(eventualBG, profile)+ "-" + convert_bg(minPredBG, profile) + " in range: no temp required";
  1282. if (currenttemp.duration > 15 && (round_basal(basal, profile) === round_basal(currenttemp.rate, profile))) {
  1283. rT.reason += ", temp " + currenttemp.rate + " ~ req " + basal + "U/hr. ";
  1284. return rT;
  1285. } else {
  1286. rT.reason += "; setting current basal of " + basal + " as temp. ";
  1287. return tempBasalFunctions.setTempBasal(basal, 30, profile, rT, currenttemp);
  1288. }
  1289. }
  1290. }
  1291. // eventual BG is at/above target
  1292. // if iob is over max, just cancel any temps
  1293. if ( eventualBG >= max_bg ) {
  1294. rT.reason += "Eventual BG " + convert_bg(eventualBG, profile) + " >= " + convert_bg(max_bg, profile) + ", ";
  1295. if (eventualBG > max_bg) {
  1296. rT.insulinForManualBolus = round((eventualBG - target_bg) / sens, 2);
  1297. }
  1298. }
  1299. if (iob_data.iob > max_iob) {
  1300. rT.reason += "IOB " + round(iob_data.iob,2) + " > max_iob " + max_iob;
  1301. if (currenttemp.duration > 15 && (round_basal(basal, profile) === round_basal(currenttemp.rate, profile))) {
  1302. rT.reason += ", temp " + currenttemp.rate + " ~ req " + basal + "U/hr. ";
  1303. return rT;
  1304. } else {
  1305. rT.reason += "; setting current basal of " + basal + " as temp. ";
  1306. return tempBasalFunctions.setTempBasal(basal, 30, profile, rT, currenttemp);
  1307. }
  1308. }
  1309. else { // otherwise, calculate 30m high-temp required to get projected BG down to target
  1310. // insulinReq is the additional insulin required to get minPredBG down to target_bg
  1311. //console.error(minPredBG,eventualBG);
  1312. insulinReq = round( (Math.min(minPredBG,eventualBG) - target_bg) / sens, 2);
  1313. insulinForManualBolus = round((eventualBG - target_bg) / sens, 2);
  1314. // if that would put us over max_iob, then reduce accordingly
  1315. if (insulinReq > max_iob-iob_data.iob) {
  1316. console.error("SMB limited by maxIOB: " + max_iob-iob_data.iob + " (. insulinReq: " + insulinReq + " U)");
  1317. rT.reason += "max_iob " + max_iob + ", ";
  1318. insulinReq = max_iob-iob_data.iob;
  1319. } else { console.error("SMB not limited by maxIOB ( insulinReq: " + insulinReq + " U).");}
  1320. if (insulinForManualBolus > max_iob-iob_data.iob) {
  1321. console.error("Ev. Bolus limited by maxIOB: " + max_iob-iob_data.iob + " (. insulinForManualBolus: " + insulinForManualBolus + " U)");
  1322. rT.reason += "max_iob " + max_iob + ", ";
  1323. } else { console.error("Ev. Bolus would not be limited by maxIOB ( insulinForManualBolus: " + insulinForManualBolus + " U).");}
  1324. // rate required to deliver insulinReq more insulin over 30m:
  1325. rate = basal + (2 * insulinReq);
  1326. rate = round_basal(rate, profile);
  1327. insulinReq = round(insulinReq,3);
  1328. rT.insulinReq = insulinReq;
  1329. //console.error(iob_data.lastBolusTime);
  1330. // minutes since last bolus
  1331. var lastBolusAge = round(( new Date(systemTime).getTime() - iob_data.lastBolusTime ) / 60000,1);
  1332. //console.error(lastBolusAge);
  1333. //console.error(profile.temptargetSet, target_bg, rT.COB);
  1334. // only allow microboluses with COB or low temp targets, or within DIA hours of a bolus
  1335. if (microBolusAllowed && enableSMB && bg > threshold) {
  1336. // never bolus more than maxSMBBasalMinutes worth of basal
  1337. var smbMinutesSetting = 30;
  1338. if (typeof profile.maxSMBBasalMinutes !== 'undefined') {
  1339. smbMinutesSetting = profile.maxSMBBasalMinutes;
  1340. }
  1341. var uamMinutesSetting = 30;
  1342. if (typeof profile.maxUAMSMBBasalMinutes !== 'undefined') {
  1343. uamMinutesSetting = profile.maxUAMSMBBasalMinutes;
  1344. }
  1345. if (oref2_variables.useOverride && advancedSettings && smbMinutes !== smbMinutesSetting) {
  1346. console.error("SMB Max Minutes - setting overriden from " + smbMinutesSetting + " to " + smbMinutes);
  1347. smbMinutesSetting = smbMinutes;
  1348. }
  1349. if (oref2_variables.useOverride && advancedSettings && uamMinutes !== uamMinutesSetting) {
  1350. console.error("UAM Max Minutes - setting overriden from " + uamMinutesSetting + " to " + uamMinutes);
  1351. uamMinutesSetting = uamMinutes;
  1352. }
  1353. var mealInsulinReq = round( meal_data.mealCOB / carbRatio ,3);
  1354. var maxBolus = 0;
  1355. if (typeof smbMinutesSetting === 'undefined' ) {
  1356. maxBolus = round(profile.current_basal *overrideFactor * 30 / 60 ,1);
  1357. console.error("smbMinutesSetting undefined: defaulting to 30m");
  1358. if( insulinReq > maxBolus ) {
  1359. console.error("SMB limited by maxBolus: " + maxBolus + " ( " + insulinReq + " U)");
  1360. }
  1361. } else if ( iob_data.iob > mealInsulinReq && iob_data.iob > 0 ) {
  1362. console.error("IOB" + iob_data.iob + "> COB" + meal_data.mealCOB + "; mealInsulinReq =" + mealInsulinReq);
  1363. if (uamMinutesSetting) {
  1364. console.error("maxUAMSMBBasalMinutes: " + uamMinutesSetting + ", profile.current_basal: " + profile.current_basal * overrideFactor);
  1365. maxBolus = round(profile.current_basal * overrideFactor * uamMinutesSetting / 60 ,1);
  1366. } else {
  1367. console.error("maxUAMSMBBasalMinutes undefined: defaulting to 30m");
  1368. maxBolus = round( profile.current_basal * overrideFactor * 30 / 60 ,1);
  1369. }
  1370. if( insulinReq > maxBolus ) {
  1371. console.error("SMB limited by maxUAMSMBBasalMinutes [ " + uamMinutesSetting + "m ]: " + maxBolus + "U ( " + insulinReq + "U )");
  1372. } else { console.error("SMB is not limited by maxUAMSMBBasalMinutes. ( insulinReq: " + insulinReq + "U )"); }
  1373. } else {
  1374. console.error(".maxSMBBasalMinutes: " + smbMinutesSetting + ", profile.current_basal: " + profile.current_basal * overrideFactor);
  1375. maxBolus = round(profile.current_basal * overrideFactor * smbMinutesSetting / 60 ,1);
  1376. if( insulinReq > maxBolus ) {
  1377. console.error("SMB limited by maxSMBBasalMinutes: " + smbMinutesSetting + "m ]: " + maxBolus + "U ( insulinReq: " + insulinReq + "U )");
  1378. } else { console.error("SMB is not limited by maxSMBBasalMinutes. ( insulinReq: " + insulinReq + "U )"); }
  1379. }
  1380. // bolus 1/2 the insulinReq, up to maxBolus, rounding down to nearest bolus increment
  1381. var bolusIncrement = profile.bolus_increment;
  1382. //if (profile.bolus_increment) { bolusIncrement=profile.bolus_increment };
  1383. var roundSMBTo = 1 / bolusIncrement;
  1384. var smb_ratio = Math.min(profile.smb_delivery_ratio, 1);
  1385. if (smb_ratio != 0.5) {
  1386. console.error("SMB Delivery Ratio changed from default 0.5 to " + round(smb_ratio,2))
  1387. }
  1388. var microBolus = Math.min(insulinReq*smb_ratio, maxBolus);
  1389. microBolus = Math.floor(microBolus*roundSMBTo)/roundSMBTo;
  1390. // calculate a long enough zero temp to eventually correct back up to target
  1391. var smbTarget = target_bg;
  1392. worstCaseInsulinReq = (smbTarget - (naive_eventualBG + minIOBPredBG)/2 ) / sens;
  1393. durationReq = round(60*worstCaseInsulinReq / profile.current_basal * overrideFactor);
  1394. // if insulinReq > 0 but not enough for a microBolus, don't set an SMB zero temp
  1395. if (insulinReq > 0 && microBolus < bolusIncrement) {
  1396. durationReq = 0;
  1397. }
  1398. var smbLowTempReq = 0;
  1399. if (durationReq <= 0) {
  1400. durationReq = 0;
  1401. // don't set an SMB zero temp longer than 60 minutes
  1402. } else if (durationReq >= 30) {
  1403. durationReq = round(durationReq/30)*30;
  1404. durationReq = Math.min(60,Math.max(0,durationReq));
  1405. } else {
  1406. // if SMB durationReq is less than 30m, set a nonzero low temp
  1407. smbLowTempReq = round( basal * durationReq/30 ,2);
  1408. durationReq = 30;
  1409. }
  1410. rT.reason += " insulinReq " + insulinReq;
  1411. if (microBolus >= maxBolus) {
  1412. rT.reason += "; maxBolus " + maxBolus;
  1413. }
  1414. if (durationReq > 0) {
  1415. rT.reason += "; setting " + durationReq + "m low temp of " + smbLowTempReq + "U/h";
  1416. }
  1417. rT.reason += ". ";
  1418. //allow SMBs every 3 minutes by default
  1419. var SMBInterval = 3;
  1420. if (profile.SMBInterval) {
  1421. // allow SMBIntervals between 1 and 10 minutes
  1422. SMBInterval = Math.min(10,Math.max(1,profile.SMBInterval));
  1423. }
  1424. var nextBolusMins = round(SMBInterval-lastBolusAge,0);
  1425. var nextBolusSeconds = round((SMBInterval - lastBolusAge) * 60, 0) % 60;
  1426. //console.error(naive_eventualBG, insulinReq, worstCaseInsulinReq, durationReq);
  1427. console.error("naive_eventualBG " + naive_eventualBG + "," + durationReq + "m " + smbLowTempReq + "U/h temp needed; last bolus " + lastBolusAge +"m ago; maxBolus: " + maxBolus);
  1428. if (lastBolusAge > SMBInterval) {
  1429. if (microBolus > 0) {
  1430. rT.units = microBolus;
  1431. rT.reason += "Microbolusing " + microBolus + "U. ";
  1432. }
  1433. } else {
  1434. rT.reason += "Waiting " + nextBolusMins + "m " + nextBolusSeconds + "s to microbolus again. ";
  1435. }
  1436. //rT.reason += ". ";
  1437. // if no zero temp is required, don't return yet; allow later code to set a high temp
  1438. if (durationReq > 0) {
  1439. rT.rate = smbLowTempReq;
  1440. rT.duration = durationReq;
  1441. return rT;
  1442. }
  1443. }
  1444. var maxSafeBasal = tempBasalFunctions.getMaxSafeBasal(profile);
  1445. if (bg == 400) {
  1446. return tempBasalFunctions.setTempBasal(profile.current_basal, 30, profile, rT, currenttemp);
  1447. }
  1448. if (rate > maxSafeBasal) {
  1449. rT.reason += "adj. req. rate: " + rate + " to maxSafeBasal: " + round(maxSafeBasal,2) + ", ";
  1450. rate = round_basal(maxSafeBasal, profile);
  1451. }
  1452. insulinScheduled = currenttemp.duration * (currenttemp.rate - basal) / 60;
  1453. if (insulinScheduled >= insulinReq * 2) { // if current temp would deliver >2x more than the required insulin, lower the rate
  1454. rT.reason += currenttemp.duration + "m@" + (currenttemp.rate).toFixed(2) + " > 2 * insulinReq. Setting temp basal of " + rate + "U/hr. ";
  1455. return tempBasalFunctions.setTempBasal(rate, 30, profile, rT, currenttemp);
  1456. }
  1457. if (typeof currenttemp.duration === 'undefined' || currenttemp.duration === 0) { // no temp is set
  1458. rT.reason += "no temp, setting " + rate + "U/hr. ";
  1459. return tempBasalFunctions.setTempBasal(rate, 30, profile, rT, currenttemp);
  1460. }
  1461. if (currenttemp.duration > 5 && (round_basal(rate, profile) <= round_basal(currenttemp.rate, profile))) { // if required temp <~ existing temp basal
  1462. rT.reason += "temp " + currenttemp.rate + " >~ req " + rate + "U/hr. ";
  1463. return rT;
  1464. }
  1465. // required temp > existing temp basal
  1466. rT.reason += "temp " + currenttemp.rate + "<" + rate + "U/hr. ";
  1467. return tempBasalFunctions.setTempBasal(rate, 30, profile, rT, currenttemp);
  1468. }
  1469. };
  1470. module.exports = determine_basal;