determine-basal.js 29 KB

1
  1. var freeaps_determineBasal;(()=>{var e={5546:(e,t,a)=>{var r=a(6880);function o(e,t){t||(t=0);var a=Math.pow(10,t);return Math.round(e*a)/a}function n(e,t){return"mmol/L"===t.out_units?o(.0555*e,1):Math.round(e)}e.exports=function(e,t,a,i,s,l,m,u,d,c,g,h,p,f,b){var v=i.min_bg,B=0,M="",_="",y="",x="",D="",w=0,S=(f=0,0),T=0,U=0,C=0;const G=b.weightedAverage,O=i.weightPercentage,A=b.average_total_data;function R(e,t){var a=e.getTime();return new Date(a+36e5*t)}function I(e){var t=i.bolus_increment;.05!=t&&(t=.1);var a=e/t;return a>=1?o(Math.floor(a)*t,5):0}function j(e){function t(e){return e<10&&(e="0"+e),e}return t(e.getHours())+":"+t(e.getMinutes())+":00"}function F(e,t){var a=new Date("1/1/1999 "+e),r=new Date("1/1/1999 "+t);return(a.getTime()-r.getTime())/36e5}function P(e,t){var a=0,r=t,o=(e-t)/36e5,n=0,i=o,s=0;do{if(o>0){var l=j(r),m=p[0].rate;for(let e=0;e<p.length;e++){var u=p[e].start;if(l==u){if(e+1<p.length){o>=(s=F(p[e+1].start,p[e].start))?n=s:o<s&&(n=o)}else if(e+1==p.length){let t=p[0].start;o>=(s=24-F(p[e].start,t))?n=s:o<s&&(n=o)}a+=I((m=p[e].rate)*n),o-=n,console.log("Dynamic ratios log: scheduled insulin added: "+I(m*n)+" U. Bas duration: "+n.toPrecision(3)+" h. Base Rate: "+m+" U/h. Time :"+l),r=R(r,n)}else if(l>u)if(e+1<p.length){var d=p[e+1].start;l<d&&(o>=(s=F(d,l))?n=s:o<s&&(n=o),a+=I((m=p[e].rate)*n),o-=n,console.log("Dynamic ratios log: scheduled insulin added: "+I(m*n)+" U. Bas duration: "+n.toPrecision(3)+" h. Base Rate: "+m+" U/h. Time :"+l),r=R(r,n))}else if(e==p.length-1){o>=(s=F("23:59:59",l))?n=s:o<s&&(n=o),a+=I((m=p[e].rate)*n),o-=n,console.log("Dynamic ratios log: scheduled insulin added: "+I(m*n)+" U. Bas duration: "+n.toPrecision(3)+" h. Base Rate: "+m+" U/h. Time :"+l),r=R(r,n)}}}}while(o>0&&o<i);return a}if(g.length){let e=g.length-1;var W=new Date(g[e].timestamp),q=new Date(g[0].timestamp);if("TempBasalDuration"==g[0]._type&&(q=new Date),(B=(q-W)/36e5)<23.9&&B>21)U=P(W,(k=24-B,E=W.getTime(),new Date(E-36e5*k))),x="24 hours of data is required for an accurate tdd calculation. Currently only "+B.toPrecision(3)+" hours of pump history data are available. Using your pump scheduled basals to fill in the missing hours. Scheduled basals added: "+U.toPrecision(5)+" U. ";else B<21?(V=!1,enableDynamicCR=!1):x=""}else console.log("Pumphistory is empty!"),V=!1,enableDynamicCR=!1;var k,E;for(let e=0;e<g.length;e++)"Bolus"==g[e]._type&&(T+=g[e].amount);for(let e=1;e<g.length;e++)if("TempBasal"==g[e]._type&&g[e].rate>0){w=e,C=g[e].rate;var L=g[e-1]["duration (min)"]/60,z=L,N=new Date(g[e-1].timestamp),Z=N;do{if(e--,0==e){Z=new Date;break}if("TempBasal"==g[e]._type||"PumpSuspend"==g[e]._type){Z=new Date(g[e].timestamp);break}}while(e>0);var H=(Z-N)/36e5;H<z&&(L=H),S+=I(C*L),e=w}for(let e=0;e<g.length;e++)if(0,0==g[e]["duration (min)"]||"PumpResume"==g[e]._type){let t=new Date(g[e].timestamp),a=t,r=e;do{if(r>0&&(--r,"TempBasal"==g[r]._type)){a=new Date(g[r].timestamp);break}}while(r>0);(a-t)/36e5>0&&(U+=P(a,t))}for(let e=g.length-1;e>0;e--)if("TempBasalDuration"==g[e]._type){let t=g[e]["duration (min)"]/60,a=new Date(g[e].timestamp);var $=a;let r=e;do{if(--r,r>=0&&("TempBasal"==g[r]._type||"PumpSuspend"==g[r]._type)){$=new Date(g[r].timestamp);break}}while(r>0);if(0==e&&"TempBasalDuration"==g[0]._type&&($=new Date,t=g[e]["duration (min)"]/60),($-a)/36e5-t>0){U+=P($,R(a,t))}}var J,K={TDD:o(f=T+S+U,5),bolus:o(T,5),temp_basal:o(S,5),scheduled_basal:o(U,5)};B>21?(_=". Bolus insulin: "+T.toPrecision(5)+" U",y=". Temporary basal insulin: "+S.toPrecision(5)+" U",M=". Insulin with scheduled basal rate: "+U.toPrecision(5)+" U",D=x+(" TDD past 24h is: "+f.toPrecision(5)+" U")+_+y+M,tddReason=G>0&&A>0?", TDD: "+o(f,1)+" U, Weighted avg: "+o(G,1)+" U, Total data avg: "+o(A,1)+" U":", TDD: "+o(f,2)):tddReason=", TDD: Not enough pumpData (< 21h)";const Q=e.glucose;var V=h.useNewFormula;const X=h.enableDynamicCR,Y=Math.min(i.autosens_min,i.autosens_max),ee=Math.max(i.autosens_min,i.autosens_max),te=h.adjustmentFactor,ae=i.min_bg;var re=!1,oe="",ne=1,ie="";A>0&&(ne=G/A),ie=ne>1?"Basal adjustment with a 24 hour to total average (up to 14 days of data) TDD ratio (limited by Autosens max setting). Basal Ratio: "+(ne=o(ne=Math.min(ne,i.autosens_max),2))+". Upper limit = Autosens max ("+i.autosens_max+")":ne<1?"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: "+(ne=o(ne=Math.max(ne,i.autosens_min),2))+". Lower limit = Autosens min ("+i.autosens_min+")":"Basal adjusted with a 24 hour to total average (up to 14 days of data) TDD ratio: "+ne,ie=", Basal ratio: "+ne,(i.high_temptarget_raises_sensitivity||i.exercise_mode)&&(re=!0),ae>=118&&re&&(V=!1,oe="Dynamic ISF temporarily off due to a high temp target/exercising. Current min target: "+ae);var se=", Dynamic ratios log: ",le=", AF: "+te,me="BG: "+Q+" mg/dl ("+(.0555*Q).toPrecision(2)+" mmol/l)",ue="",de="";const ce=h.curve,ge=h.insulinPeakTime,he=h.useCustomPeakTime;var pe=55,fe=65;switch(ce){case"rapid-acting":fe=65;break;case"ultra-rapid":fe=50}he?(pe=120-ge,console.log("Custom insulinpeakTime set to :"+ge+", insulinFactor: "+pe)):(pe=120-fe,console.log("insulinFactor set to : "+pe)),J=f,O<1&&G>0&&(f=G,console.log("Using weighted TDD average: "+o(f,2)+" U, instead of past 24 h ("+o(J,2)+" U), weight: "+O),de=", Weighted TDD: "+o(f,2)+" U");const be=h.sigmoid;var ve="";if(V){var Be=i.sens*te*f*Math.log(Q/pe+1)/1800;ue=", Logarithmic formula"}var Me="";if(V&&be){const e=Y,t=ee-e,a=.0555*(Q-i.min_bg);var _e=ne;Me=", tdd_factor: "+o(_e,1);const r=ee-1,n=Math.log10(1/r-e/r)/Math.log10(Math.E),s=a*te*_e+n;Be=t/(1+Math.exp(-s))+e,ue=", Sigmoid function"}var ye=i.carb_ratio,xe="",De="";if(V&&f>0){if(xe=", Dynamic ISF/CR: On/",Be>ee?(oe=", Dynamic ISF limited by autosens_max setting: "+ee+" ("+o(Be,2)+"), ",De=", Autosens/Dynamic Limit: "+ee+" ("+o(Be,2)+")",Be=ee):Be<Y&&(oe=", Dynamic ISF limjted by autosens_min setting: "+Y+" ("+o(Be,2)+"). ",De=", Autosens/Dynamic Limit: "+Y+" ("+o(Be,2)+")",Be=Y),X){xe+="On";var we=Be;Be>1&&(we=(Be-1)/2+1);var Se=" CR: "+(ye=o(ye/we,2))+" g/U";i.carb_ratio=ye}else Se=" CR: "+ye+" g/U",xe+="Off";const e=i.sens/Be;ve=". Using Sigmoid function, the autosens ratio has been adjusted with sigmoid factor to: "+o(s.ratio,2)+". New ISF = "+o(e,2)+" mg/dl ("+o(.0555*e,2)+" (mmol/l). CR adjusted from "+o(ye,2)+" to "+o(i.carb_ratio,2)+" ("+o(.0555*i.carb_ratio,2)+" mmol/l).",oe+=be?ve:", Dynamic autosens.ratio set to "+o(Be,2)+" with ISF: "+e.toPrecision(3)+" mg/dl/U ("+(.0555*e).toPrecision(3)+" mmol/l/U)",s.ratio=Be,D+=se+me+le+ue+oe+xe+Se+de}else D+=se+"Dynamic Settings disabled";console.log(D),V||X?V&&i.tddAdjBasal?tddReason+=xe+ue+De+le+ie:V&&!i.tddAdjBasal&&(tddReason+=xe+ue+De+le):tddReason+="";var Te={},Ue=new Date;if(c&&(Ue=c),void 0===i||void 0===i.current_basal)return Te.error="Error: could not get current basal rate",Te;var Ce=r(i.current_basal,i),Ge=Ce,Oe=new Date;c&&(Oe=c);var Ae,Re=new Date(e.date),Ie=o((Oe-Re)/60/1e3,1),je=e.glucose,Fe=e.noise;Ae=e.delta>-.5?"+"+o(e.delta,0):o(e.delta,0);var Pe=Math.min(e.delta,e.short_avgdelta),We=Math.min(e.short_avgdelta,e.long_avgdelta),qe=Math.max(e.delta,e.short_avgdelta,e.long_avgdelta);(je<=10||38===je||Fe>=3)&&(Te.reason="CGM is calibrating, in ??? state, or noise is high");if(je>60&&0==e.delta&&e.short_avgdelta>-1&&e.short_avgdelta<1&&e.long_avgdelta>-1&&e.long_avgdelta<1&&("fakecgm"==e.device?(console.error("CGM data is unchanged ("+n(je,i)+"+"+n(e.delta,i)+") for 5m w/ "+n(e.short_avgdelta,i)+" mg/dL ~15m change & "+n(e.long_avgdelta,2)+" mg/dL ~45m change"),console.error("Simulator mode detected ("+e.device+"): continuing anyway")):!0),Ie>12||Ie<-5?Te.reason="If current system time "+Oe+" is correct, then BG data is too old. The last BG data was read "+Ie+"m ago at "+Re:0===e.short_avgdelta&&0===e.long_avgdelta&&(e.last_cal&&e.last_cal<3?Te.reason="CGM was just calibrated":Te.reason="CGM data is unchanged ("+n(je,i)+"+"+n(e.delta,i)+") for 5m w/ "+n(e.short_avgdelta,i)+" mg/dL ~15m change & "+n(e.long_avgdelta,i)+" mg/dL ~45m change"),je<=10||38===je||Fe>=3||Ie>12||Ie<-5||0===e.short_avgdelta&&0===e.long_avgdelta)return t.rate>=Ge?(Te.reason+=". Canceling high temp basal of "+t.rate,Te.deliverAt=Ue,Te.temp="absolute",Te.duration=0,Te.rate=0,Te):0===t.rate&&t.duration>30?(Te.reason+=". Shortening "+t.duration+"m long zero temp to 30m. ",Te.deliverAt=Ue,Te.temp="absolute",Te.duration=30,Te.rate=0,Te):(Te.reason+=". Temp "+t.rate+" <= current basal "+Ge+"U/hr; doing nothing. ",Te);var ke,Ee,Le,ze,Ne=i.max_iob;if(void 0!==i.min_bg&&(Ee=i.min_bg),void 0!==i.max_bg&&(Le=i.max_bg),void 0!==i.enableSMB_high_bg_target&&(ze=i.enableSMB_high_bg_target),void 0===i.min_bg||void 0===i.max_bg)return Te.error="Error: could not determine target_bg. ",Te;ke=(i.min_bg+i.max_bg)/2;var Ze=i.exercise_mode||i.high_temptarget_raises_sensitivity,He=100,$e=160;if(i.half_basal_exercise_target&&($e=i.half_basal_exercise_target),Ze&&i.temptargetSet&&ke>He||i.low_temptarget_lowers_sensitivity&&i.temptargetSet&&ke<He){var Je=$e-He;sensitivityRatio=Je*(Je+ke-He)<=0?i.autosens_max:Je/(Je+ke-He),sensitivityRatio=Math.min(sensitivityRatio,i.autosens_max),sensitivityRatio=o(sensitivityRatio,2),process.stderr.write("Sensitivity ratio set to "+sensitivityRatio+" based on temp target of "+ke+"; ")}else void 0!==s&&s&&(sensitivityRatio=s.ratio,process.stderr.write("Autosens ratio: "+sensitivityRatio+"; "));if(i.temptargetSet&&ke<He&&V&&Q>=ke&&sensitivityRatio<Be&&(s.ratio=Be*(He/ke),s.ratio=Math.min(s.ratio,i.autosens_max),sensitivityRatio=o(s.ratio,2),console.log("Dynamic ratio increased from "+o(Be,2)+" to "+o(s.ratio,2)+" due to a low temp target ("+ke+").")),sensitivityRatio&&!V?(Ge=i.current_basal*sensitivityRatio,Ge=r(Ge,i)):V&&i.tddAdjBasal&&(Ge=i.current_basal*ne,Ge=r(Ge,i),process.stderr.write("TDD-adjustment of basals activated, using tdd24h_14d_Ratio "+o(ne,2)+", TDD 24h = "+o(J,2)+"U, Weighted average TDD = "+o(G,2)+"U, (Weight percentage = "+O+"), Total data of TDDs (up to 14 days) average = "+o(A,2)+"U. "),Ge!==Ce?process.stderr.write("Adjusting basal from "+Ce+" U/h to "+Ge+" U/h; "):process.stderr.write("Basal unchanged: "+Ge+" U/h; ")),i.temptargetSet);else if(void 0!==s&&s&&(i.sensitivity_raises_target&&s.ratio<1||i.resistance_lowers_target&&s.ratio>1)){Ee=o((Ee-60)/s.ratio)+60,Le=o((Le-60)/s.ratio)+60;var Ke=o((ke-60)/s.ratio)+60;ke===(Ke=Math.max(80,Ke))?process.stderr.write("target_bg unchanged: "+Ke+"; "):process.stderr.write("target_bg from "+ke+" to "+Ke+"; "),ke=Ke}var Qe=200,Ve=200,Xe=200;if(e.noise>=2){var Ye=Math.max(1.1,i.noisyCGMTargetMultiplier);Math.min(250,i.maxRaw);Qe=o(Math.min(200,Ee*Ye)),Ve=o(Math.min(200,ke*Ye)),Xe=o(Math.min(200,Le*Ye)),process.stderr.write("Raising target_bg for noisy / raw CGM data, from "+ke+" to "+Ve+"; "),Ee=Qe,ke=Ve,Le=Xe}var et=Ee-.5*(Ee-40),tt=i.threshold_setting;tt>et&&tt<=120&&tt>=65?(console.error("Threshold changed in settings from "+n(et,i)+" to "+n(tt,i)+". "),et=tt):console.error("Current threshold: "+n(et,i));var at="",rt=o(i.sens,1),ot=i.sens;if(void 0!==s&&s&&((ot=o(ot=i.sens/sensitivityRatio,1))!==rt?process.stderr.write("ISF from "+n(rt,i)+" to "+n(ot,i)):process.stderr.write("ISF unchanged: "+n(ot,i)),at+="Autosens ratio: "+o(sensitivityRatio,2)+", ISF: "+n(rt,i)+"→"+n(ot,i)),console.error("CR:"+i.carb_ratio),void 0===a)return Te.error="Error: iob_data undefined. ",Te;var nt,it=a;if(a.length,a.length>1&&J>0&&(a=it[0]),void 0===a.activity||void 0===a.iob)return Te.error="Error: iob_data missing some property. ",Te;var st=((nt=void 0!==a.lastTemp?o((new Date(Oe).getTime()-a.lastTemp.date)/6e4):0)+t.duration)%30;if(console.error("currenttemp:"+t.rate+" lastTempAge:"+nt+"m, tempModulus:"+st+"m"),Te.temp="absolute",Te.deliverAt=Ue,u&&t&&a.lastTemp&&t.rate!==a.lastTemp.rate&&nt>10&&t.duration)return Te.reason="Warning: currenttemp rate "+t.rate+" != lastTemp rate "+a.lastTemp.rate+" from pumphistory; canceling temp",m.setTempBasal(0,0,i,Te,t);if(t&&a.lastTemp&&t.duration>0){var lt=nt-a.lastTemp.duration;if(lt>5&&nt>10)return Te.reason="Warning: currenttemp running but lastTemp from pumphistory ended "+lt+"m ago; canceling temp",m.setTempBasal(0,0,i,Te,t)}var mt=o(-a.activity*ot*5,2),ut=o(6*(Pe-mt));ut<0&&(ut=o(6*(We-mt)))<0&&(ut=o(6*(e.long_avgdelta-mt)));var dt=je,ct=(dt=a.iob>0?o(je-a.iob*ot):o(je-a.iob*Math.min(ot,i.sens)))+ut;if(void 0===ct||isNaN(ct))return Te.error="Error: could not calculate eventualBG. Sensitivity: "+ot+" Deviation: "+ut,Te;var gt=function(e,t,a){return o(a+(e-t)/24,1)}(ke,ct,mt);Te={temp:"absolute",bg:je,tick:Ae,eventualBG:ct,insulinReq:0,reservoir:d,deliverAt:Ue,sensitivityRatio,TDD:J,insulin:K};var ht=[],pt=[],ft=[],bt=[];ht.push(je),pt.push(je),bt.push(je),ft.push(je);var vt=function(e,t,a,r,o,i){return t?!e.allowSMB_with_high_temptarget&&e.temptargetSet&&o>100?(console.error("SMB disabled due to high temptarget of "+o),!1):!0===a.bwFound&&!1===e.A52_risk_enable?(console.error("SMB disabled due to Bolus Wizard activity in the last 6 hours."),!1):!0===e.enableSMB_always?(a.bwFound?console.error("Warning: SMB enabled within 6h of using Bolus Wizard: be sure to easy bolus 30s before using Bolus Wizard"):console.error("SMB enabled due to enableSMB_always"),!0):!0===e.enableSMB_with_COB&&a.mealCOB?(a.bwCarbs?console.error("Warning: SMB enabled with Bolus Wizard carbs: be sure to easy bolus 30s before using Bolus Wizard"):console.error("SMB enabled for COB of "+a.mealCOB),!0):!0===e.enableSMB_after_carbs&&a.carbs?(a.bwCarbs?console.error("Warning: SMB enabled with Bolus Wizard carbs: be sure to easy bolus 30s before using Bolus Wizard"):console.error("SMB enabled for 6h after carb entry"),!0):!0===e.enableSMB_with_temptarget&&e.temptargetSet&&o<100?(a.bwFound?console.error("Warning: SMB enabled within 6h of using Bolus Wizard: be sure to easy bolus 30s before using Bolus Wizard"):console.error("SMB enabled for temptarget of "+n(o,e)),!0):!0===e.enableSMB_high_bg&&null!==i&&r>=i?(console.error("Checking BG to see if High for SMB enablement."),console.error("Current BG",r," | High BG ",i),a.bwFound?console.error("Warning: High BG SMB enabled within 6h of using Bolus Wizard: be sure to easy bolus 30s before using Bolus Wizard"):console.error("High BG detected. Enabling SMB."),!0):(console.error("SMB disabled (no enableSMB preferences active or no condition satisfied)"),!1):(console.error("SMB disabled (!microBolusAllowed)"),!1)}(i,u,l,je,ke,ze),Bt=i.enableUAM,Mt=0,_t=0;Mt=o(Pe-mt,1);var yt=o(Pe-mt,1);csf=ot/i.carb_ratio,console.error("profile.sens:"+n(i.sens,i)+", sens:"+n(ot,i)+", CSF:"+o(csf,1));var xt=o(30*csf*5/60,1);Mt>xt&&(console.error("Limiting carb impact from "+Mt+" to "+xt+"mg/dL/5m (30g/h)"),Mt=xt);var Dt=3;sensitivityRatio&&(Dt/=sensitivityRatio);var wt=Dt;if(l.carbs){Dt=Math.max(Dt,l.mealCOB/20);var St=o((new Date(Oe).getTime()-l.lastCarbTime)/6e4),Tt=(l.carbs-l.mealCOB)/l.carbs;wt=o(wt=Dt+1.5*St/60,1),console.error("Last carbs "+St+" minutes ago; remainingCATime:"+wt+"hours; "+o(100*Tt,1)+"% carbs absorbed")}var Ut=Math.max(0,Mt/5*60*wt/2)/csf,Ct=90,Gt=1;i.remainingCarbsCap&&(Ct=Math.min(90,i.remainingCarbsCap)),i.remainingCarbsFraction&&(Gt=Math.min(1,i.remainingCarbsFraction));var Ot=1-Gt,At=Math.max(0,l.mealCOB-Ut-l.carbs*Ot),Rt=(At=Math.min(Ct,At))*csf*5/60/(wt/2),It=o(l.slopeFromMaxDeviation,2),jt=o(l.slopeFromMinDeviation,2),Ft=Math.min(It,-jt/3);_t=0===Mt?0:Math.min(60*wt/5/2,Math.max(0,l.mealCOB*csf/Mt)),console.error("Carb Impact:"+Mt+"mg/dL per 5m; CI Duration:"+o(5*_t/60*2,1)+"hours; remaining CI ("+wt/2+"h peak):"+o(Rt,1)+"mg/dL per 5m");var Pt,Wt,qt,kt,Et,Lt=999,zt=999,Nt=999,Zt=je,Ht=999,$t=999,Jt=999,Kt=999,Qt=ct,Vt=je,Xt=je,Yt=0,ea=[],ta=[];try{it.forEach((function(e){var t=o(-e.activity*ot*5,2),a=o(-e.iobWithZeroTemp.activity*ot*5,2),r=dt,n=Mt*(1-Math.min(1,pt.length/12));if(!0===(V&&!be))Qt=pt[pt.length-1]+o(-e.activity*(1800/(f*te*Math.log(Math.max(pt[pt.length-1],39)/pe+1)))*5,2)+n,r=bt[bt.length-1]+o(-e.iobWithZeroTemp.activity*(1800/(f*te*Math.log(Math.max(bt[bt.length-1],39)/pe+1)))*5,2),console.log("Dynamic ISF (Logarithmic Formula) )adjusted predictions for IOB and ZT: IOBpredBG: "+o(Qt,2)+" , ZTpredBG: "+o(r,2));else Qt=pt[pt.length-1]+t+n,r=bt[bt.length-1]+a;var i=Math.max(0,Math.max(0,Mt)*(1-ht.length/Math.max(2*_t,1))),s=Math.min(ht.length,12*wt-ht.length),l=Math.max(0,s/(wt/2*12)*Rt);i+l,ea.push(o(l,0)),ta.push(o(i,0)),COBpredBG=ht[ht.length-1]+t+Math.min(0,n)+i+l;var m=Math.max(0,yt+ft.length*Ft),u=Math.max(0,yt*(1-ft.length/Math.max(36,1))),d=Math.min(m,u);if(d>0&&(Yt=o(5*(ft.length+1)/60,1)),!0===(V&&!be))UAMpredBG=ft[ft.length-1]+o(-e.activity*(1800/(f*te*Math.log(Math.max(ft[ft.length-1],39)/pe+1)))*5,2)+Math.min(0,n)+d,console.log("Dynamic ISF (Logarithmic Formula) adjusted prediction for UAM: UAMpredBG: "+o(UAMpredBG,2));else UAMpredBG=ft[ft.length-1]+t+Math.min(0,n)+d;pt.length<48&&pt.push(Qt),ht.length<48&&ht.push(COBpredBG),ft.length<48&&ft.push(UAMpredBG),bt.length<48&&bt.push(r),COBpredBG<Ht&&(Ht=o(COBpredBG)),UAMpredBG<$t&&($t=o(UAMpredBG)),Qt<Jt&&(Jt=o(Qt)),r<Kt&&(Kt=o(r));pt.length>18&&Qt<Lt&&(Lt=o(Qt)),Qt>Vt&&(Vt=Qt),(_t||Rt>0)&&ht.length>18&&COBpredBG<zt&&(zt=o(COBpredBG)),(_t||Rt>0)&&COBpredBG>Vt&&(Xt=COBpredBG),Bt&&ft.length>12&&UAMpredBG<Nt&&(Nt=o(UAMpredBG)),Bt&&UAMpredBG>Vt&&UAMpredBG}))}catch(e){console.error("Problem with iobArray. Optional feature Advanced Meal Assist disabled")}l.mealCOB&&(console.error("predCIs (mg/dL/5m):"+ta.join(" ")),console.error("remainingCIs: "+ea.join(" "))),Te.predBGs={},pt.forEach((function(e,t,a){a[t]=o(Math.min(401,Math.max(39,e)))}));for(var aa=pt.length-1;aa>12&&pt[aa-1]===pt[aa];aa--)pt.pop();for(Te.predBGs.IOB=pt,qt=o(pt[pt.length-1]),bt.forEach((function(e,t,a){a[t]=o(Math.min(401,Math.max(39,e)))})),aa=bt.length-1;aa>6&&!(bt[aa-1]>=bt[aa]||bt[aa]<=ke);aa--)bt.pop();if(Te.predBGs.ZT=bt,o(bt[bt.length-1]),l.mealCOB>0&&(Mt>0||Rt>0)){for(ht.forEach((function(e,t,a){a[t]=o(Math.min(401,Math.max(39,e)))})),aa=ht.length-1;aa>12&&ht[aa-1]===ht[aa];aa--)ht.pop();Te.predBGs.COB=ht,kt=o(ht[ht.length-1]),ct=Math.max(ct,o(ht[ht.length-1]))}if(Mt>0||Rt>0){if(Bt){for(ft.forEach((function(e,t,a){a[t]=o(Math.min(401,Math.max(39,e)))})),aa=ft.length-1;aa>12&&ft[aa-1]===ft[aa];aa--)ft.pop();Te.predBGs.UAM=ft,Et=o(ft[ft.length-1]),ft[ft.length-1]&&(ct=Math.max(ct,o(ft[ft.length-1])))}Te.eventualBG=ct}console.error("UAM Impact:"+yt+"mg/dL per 5m; UAM Duration:"+Yt+"hours"),Lt=Math.max(39,Lt),zt=Math.max(39,zt),Nt=Math.max(39,Nt),Pt=o(Lt);var ra=l.mealCOB/l.carbs;Wt=o(Nt<999&&zt<999?(1-ra)*UAMpredBG+ra*COBpredBG:zt<999?(Qt+COBpredBG)/2:Nt<999?(Qt+UAMpredBG)/2:Qt),Kt>Wt&&(Wt=Kt),Zt=o(Zt=_t||Rt>0?Bt?ra*Ht+(1-ra)*$t:Ht:Bt?$t:Jt);var oa=Nt;if(Kt<et)oa=(Nt+Kt)/2;else if(Kt<ke){var na=(Kt-et)/(ke-et);oa=(Nt+(Nt*na+Kt*(1-na)))/2}else Kt>Nt&&(oa=(Nt+Kt)/2);if(oa=o(oa),l.carbs)if(!Bt&&zt<999)Pt=o(Math.max(Lt,zt));else if(zt<999){var ia=ra*zt+(1-ra)*oa;Pt=o(Math.max(Lt,zt,ia))}else Pt=Bt?oa:Zt;else Bt&&(Pt=o(Math.max(Lt,oa)));Pt=Math.min(Pt,Wt),process.stderr.write("minPredBG: "+Pt+" minIOBPredBG: "+Lt+" minZTGuardBG: "+Kt),zt<999&&process.stderr.write(" minCOBPredBG: "+zt),Nt<999&&process.stderr.write(" minUAMPredBG: "+Nt),console.error(" avgPredBG:"+Wt+" COB/Carbs:"+l.mealCOB+"/"+l.carbs),Xt>je&&(Pt=Math.min(Pt,Xt)),Te.COB=l.mealCOB,Te.IOB=a.iob,Te.BGI=n(mt,i),Te.deviation=n(ut,i),Te.ISF=n(ot,i),Te.CR=o(i.carb_ratio,2),Te.target_bg=n(ke,i),Te.TDD=o(J,2);var sa=Te.target_bg;ke!=v&&(sa=n(v,i)+"→"+Te.target_bg),Te.reason=at+", COB: "+Te.COB+", Dev: "+Te.deviation+", BGI: "+Te.BGI+", CR: "+Te.CR+", Target: "+sa+", minPredBG "+n(Pt,i)+", minGuardBG "+n(Zt,i)+", IOBpredBG "+n(qt,i),kt>0&&(Te.reason+=", COBpredBG "+n(kt,i)),Et>0&&(Te.reason+=", UAMpredBG "+n(Et,i)),Te.reason+=tddReason+Me,Te.reason+="; ";var la=dt;la<40&&(la=Math.min(Zt,la));var ma,ua=et-la,da=240,ca=240;if(l.mealCOB>0&&(Mt>0||Rt>0)){for(aa=0;aa<ht.length;aa++)if(ht[aa]<Ee){da=5*aa;break}for(aa=0;aa<ht.length;aa++)if(ht[aa]<et){ca=5*aa;break}}else{for(aa=0;aa<pt.length;aa++)if(pt[aa]<Ee){da=5*aa;break}for(aa=0;aa<pt.length;aa++)if(pt[aa]<et){ca=5*aa;break}}vt&&Zt<et&&(console.error("minGuardBG "+n(Zt,i)+" projected below "+n(et,i)+" - disabling SMB"),vt=!1),void 0===i.maxDelta_bg_threshold&&(ma=.2),void 0!==i.maxDelta_bg_threshold&&(ma=Math.min(i.maxDelta_bg_threshold,.4)),qe>ma*je&&(console.error("maxDelta "+n(qe,i)+" > "+100*ma+"% of BG "+n(je,i)+" - disabling SMB"),Te.reason+="maxDelta "+n(qe,i)+" > "+100*ma+"% of BG "+n(je,i)+" - SMB disabled!, ",vt=!1),console.error("BG projected to remain above "+n(Ee,i)+" for "+da+"minutes"),(ca<240||da<60)&&console.error("BG projected to remain above "+n(et,i)+" for "+ca+"minutes");var ga=ca,ha=i.current_basal*ot*ga/60,pa=Math.max(0,l.mealCOB-.25*l.carbs),fa=(ua-ha)/csf-pa;ha=o(ha),fa=o(fa),console.error("naive_eventualBG:",dt,"bgUndershoot:",ua,"zeroTempDuration:",ga,"zeroTempEffect:",ha,"carbsReq:",fa),"Could not parse clock data"==l.reason?console.error("carbsReq unknown: Could not parse clock data"):fa>=i.carbsReqThreshold&&ca<=45&&(Te.carbsReq=fa,Te.reason+=fa+" add'l carbs req w/in "+ca+"m; ");var ba=0;if(je<et&&a.iob<20*-i.current_basal/60&&Pe>0&&Pe>gt)Te.reason+="IOB "+a.iob+" < "+o(20*-i.current_basal/60,2),Te.reason+=" and minDelta "+n(Pe,i)+" > expectedDelta "+n(gt,i)+"; ";else if(je<et||Zt<et)return Te.reason+="minGuardBG "+n(Zt,i)+"<"+n(et,i),ba=o(60*((ua=ke-Zt)/ot)/i.current_basal),ba=30*o(ba/30),ba=Math.min(120,Math.max(30,ba)),m.setTempBasal(0,ba,i,Te,t);if(i.skip_neutral_temps&&Te.deliverAt.getMinutes()>=55)return Te.reason+="; Canceling temp at "+Te.deliverAt.getMinutes()+"m past the hour. ",m.setTempBasal(0,0,i,Te,t);var va=0,Ba=Ge;if(ct<Ee){if(Te.reason+="Eventual BG "+n(ct,i)+" < "+n(Ee,i),Pe>gt&&Pe>0&&!fa)return dt<40?(Te.reason+=", naive_eventualBG < 40. ",m.setTempBasal(0,30,i,Te,t)):(e.delta>Pe?Te.reason+=", but Delta "+n(Ae,i)+" > expectedDelta "+n(gt,i):Te.reason+=", but Min. Delta "+Pe.toFixed(2)+" > Exp. Delta "+n(gt,i),t.duration>15&&r(Ge,i)===r(t.rate,i)?(Te.reason+=", temp "+t.rate+" ~ req "+Ge+"U/hr. ",Te):(Te.reason+="; setting current basal of "+Ge+" as temp. ",m.setTempBasal(Ge,30,i,Te,t)));va=o(va=2*Math.min(0,(ct-ke)/ot),2);var Ma=Math.min(0,(dt-ke)/ot);if(Ma=o(Ma,2),Pe<0&&Pe>gt)va=o(va*(Pe/gt),2);if(Ba=r(Ba=Ge+2*va,i),t.duration*(t.rate-Ge)/60<Math.min(va,Ma)-.3*Ge)return Te.reason+=", "+t.duration+"m@"+t.rate.toFixed(2)+" is a lot less than needed. ",m.setTempBasal(Ba,30,i,Te,t);if(void 0!==t.rate&&t.duration>5&&Ba>=.8*t.rate)return Te.reason+=", temp "+t.rate+" ~< req "+Ba+"U/hr. ",Te;if(Ba<=0){if((ba=o(60*((ua=ke-dt)/ot)/i.current_basal))<0?ba=0:(ba=30*o(ba/30),ba=Math.min(120,Math.max(0,ba))),ba>0)return Te.reason+=", setting "+ba+"m zero temp. ",m.setTempBasal(Ba,ba,i,Te,t)}else Te.reason+=", setting "+Ba+"U/hr. ";return m.setTempBasal(Ba,30,i,Te,t)}if(Pe<gt&&(!u||!vt))return e.delta<Pe?Te.reason+="Eventual BG "+n(ct,i)+" > "+n(Ee,i)+" but Delta "+n(Ae,i)+" < Exp. Delta "+n(gt,i):Te.reason+="Eventual BG "+n(ct,i)+" > "+n(Ee,i)+" but Min. Delta "+Pe.toFixed(2)+" < Exp. Delta "+n(gt,i),t.duration>15&&r(Ge,i)===r(t.rate,i)?(Te.reason+=", temp "+t.rate+" ~ req "+Ge+"U/hr. ",Te):(Te.reason+="; setting current basal of "+Ge+" as temp. ",m.setTempBasal(Ge,30,i,Te,t));if(Math.min(ct,Pt)<Le&&(!u||!vt))return Te.reason+=n(ct,i)+"-"+n(Pt,i)+" in range: no temp required",t.duration>15&&r(Ge,i)===r(t.rate,i)?(Te.reason+=", temp "+t.rate+" ~ req "+Ge+"U/hr. ",Te):(Te.reason+="; setting current basal of "+Ge+" as temp. ",m.setTempBasal(Ge,30,i,Te,t));if(ct>=Le&&(Te.reason+="Eventual BG "+n(ct,i)+" >= "+n(Le,i)+", "),a.iob>Ne)return Te.reason+="IOB "+o(a.iob,2)+" > max_iob "+Ne,t.duration>15&&r(Ge,i)===r(t.rate,i)?(Te.reason+=", temp "+t.rate+" ~ req "+Ge+"U/hr. ",Te):(Te.reason+="; setting current basal of "+Ge+" as temp. ",m.setTempBasal(Ge,30,i,Te,t));(va=o((Math.min(Pt,ct)-ke)/ot,2))>Ne-a.iob?(console.error("SMB limited by maxIOB: "+Ne-a.iob+" (. insulinReq: "+va+" U)"),Te.reason+="max_iob "+Ne+", ",va=Ne-a.iob):console.error("SMB not limited by maxIOB ( insulinReq: "+va+" U)."),Ba=r(Ba=Ge+2*va,i),va=o(va,3),Te.insulinReq=va;var _a=o((new Date(Oe).getTime()-a.lastBolusTime)/6e4,1);if(u&&vt&&je>et){var ya=o(l.mealCOB/i.carb_ratio,3),xa=0;void 0===i.maxSMBBasalMinutes?(xa=o(30*i.current_basal/60,1),console.error("profile.maxSMBBasalMinutes undefined: defaulting to 30m"),va>xa&&console.error("SMB limited by maxBolus: "+xa+" ( "+va+" U)")):a.iob>ya&&a.iob>0?(console.error("IOB"+a.iob+"> COB"+l.mealCOB+"; mealInsulinReq ="+ya),i.maxUAMSMBBasalMinutes?(console.error("profile.maxUAMSMBBasalMinutes: "+i.maxUAMSMBBasalMinutes+", profile.current_basal: "+i.current_basal),xa=o(i.current_basal*i.maxUAMSMBBasalMinutes/60,1)):(console.error("profile.maxUAMSMBBasalMinutes undefined: defaulting to 30m"),xa=o(30*i.current_basal/60,1)),va>xa?console.error("SMB limited by maxUAMSMBBasalMinutes [ "+i.maxUAMSMBBasalMinutes+"m ]: "+xa+"U ( "+va+"U )"):console.error("SMB is not limited by maxUAMSMBBasalMinutes. ( insulinReq: "+va+"U )")):(console.error("profile.maxSMBBasalMinutes: "+i.maxSMBBasalMinutes+", profile.current_basal: "+i.current_basal),va>(xa=o(i.current_basal*i.maxSMBBasalMinutes/60,1))?console.error("SMB limited by maxSMBBasalMinutes: "+i.maxSMBBasalMinutes+"m ]: "+xa+"U ( insulinReq: "+va+"U )"):console.error("SMB is not limited by maxSMBBasalMinutes. ( insulinReq: "+va+"U )"));var Da=i.bolus_increment,wa=1/Da,Sa=i.smb_delivery_ratio;Sa>.5&&console.error("SMB Delivery Ratio increased from default 0.5 to "+o(Sa,2));var Ta=Math.min(va*Sa,xa);Ta=Math.floor(Ta*wa)/wa,ba=o(60*((ke-(dt+Lt)/2)/ot)/i.current_basal),va>0&&Ta<Da&&(ba=0);var Ua=0;ba<=0?ba=0:ba>=30?(ba=30*o(ba/30),ba=Math.min(60,Math.max(0,ba))):(Ua=o(Ge*ba/30,2),ba=30),Te.reason+=" insulinReq "+va,Ta>=xa&&(Te.reason+="; maxBolus "+xa),ba>0&&(Te.reason+="; setting "+ba+"m low temp of "+Ua+"U/h"),Te.reason+=". ";var Ca=3;i.SMBInterval&&(Ca=Math.min(10,Math.max(1,i.SMBInterval)));var Ga=o(Ca-_a,0),Oa=o(60*(Ca-_a),0)%60;if(console.error("naive_eventualBG "+dt+","+ba+"m "+Ua+"U/h temp needed; last bolus "+_a+"m ago; maxBolus: "+xa),_a>Ca?Ta>0&&(Te.units=Ta,Te.reason+="Microbolusing "+Ta+"U. "):Te.reason+="Waiting "+Ga+"m "+Oa+"s to microbolus again. ",ba>0)return Te.rate=Ua,Te.duration=ba,Te}var Aa=m.getMaxSafeBasal(i);return Ba>Aa&&(Te.reason+="adj. req. rate: "+Ba+" to maxSafeBasal: "+o(Aa,2)+", ",Ba=r(Aa,i)),t.duration*(t.rate-Ge)/60>=2*va?(Te.reason+=t.duration+"m@"+t.rate.toFixed(2)+" > 2 * insulinReq. Setting temp basal of "+Ba+"U/hr. ",m.setTempBasal(Ba,30,i,Te,t)):void 0===t.duration||0===t.duration?(Te.reason+="no temp, setting "+Ba+"U/hr. ",m.setTempBasal(Ba,30,i,Te,t)):t.duration>5&&r(Ba,i)<=r(t.rate,i)?(Te.reason+="temp "+t.rate+" >~ req "+Ba+"U/hr. ",Te):(Te.reason+="temp "+t.rate+"<"+Ba+"U/hr. ",m.setTempBasal(Ba,30,i,Te,t))}},6880:(e,t,a)=>{var r=a(6654);e.exports=function(e,t){var a=20;void 0!==t&&"string"==typeof t.model&&(r(t.model,"54")||r(t.model,"23"))&&(a=40);return e<1?Math.round(e*a)/a:e<10?Math.round(20*e)/20:Math.round(10*e)/10}},2705:(e,t,a)=>{var r=a(5639).Symbol;e.exports=r},9932:e=>{e.exports=function(e,t){for(var a=-1,r=null==e?0:e.length,o=Array(r);++a<r;)o[a]=t(e[a],a,e);return o}},9750:e=>{e.exports=function(e,t,a){return e==e&&(void 0!==a&&(e=e<=a?e:a),void 0!==t&&(e=e>=t?e:t)),e}},4239:(e,t,a)=>{var r=a(2705),o=a(9607),n=a(2333),i=r?r.toStringTag:void 0;e.exports=function(e){return null==e?void 0===e?"[object Undefined]":"[object Null]":i&&i in Object(e)?o(e):n(e)}},531:(e,t,a)=>{var r=a(2705),o=a(9932),n=a(1469),i=a(3448),s=r?r.prototype:void 0,l=s?s.toString:void 0;e.exports=function e(t){if("string"==typeof t)return t;if(n(t))return o(t,e)+"";if(i(t))return l?l.call(t):"";var a=t+"";return"0"==a&&1/t==-Infinity?"-0":a}},7561:(e,t,a)=>{var r=a(7990),o=/^\s+/;e.exports=function(e){return e?e.slice(0,r(e)+1).replace(o,""):e}},1957:(e,t,a)=>{var r="object"==typeof a.g&&a.g&&a.g.Object===Object&&a.g;e.exports=r},9607:(e,t,a)=>{var r=a(2705),o=Object.prototype,n=o.hasOwnProperty,i=o.toString,s=r?r.toStringTag:void 0;e.exports=function(e){var t=n.call(e,s),a=e[s];try{e[s]=void 0;var r=!0}catch(e){}var o=i.call(e);return r&&(t?e[s]=a:delete e[s]),o}},2333:e=>{var t=Object.prototype.toString;e.exports=function(e){return t.call(e)}},5639:(e,t,a)=>{var r=a(1957),o="object"==typeof self&&self&&self.Object===Object&&self,n=r||o||Function("return this")();e.exports=n},7990:e=>{var t=/\s/;e.exports=function(e){for(var a=e.length;a--&&t.test(e.charAt(a)););return a}},6654:(e,t,a)=>{var r=a(9750),o=a(531),n=a(554),i=a(9833);e.exports=function(e,t,a){e=i(e),t=o(t);var s=e.length,l=a=void 0===a?s:r(n(a),0,s);return(a-=t.length)>=0&&e.slice(a,l)==t}},1469:e=>{var t=Array.isArray;e.exports=t},3218:e=>{e.exports=function(e){var t=typeof e;return null!=e&&("object"==t||"function"==t)}},7005:e=>{e.exports=function(e){return null!=e&&"object"==typeof e}},3448:(e,t,a)=>{var r=a(4239),o=a(7005);e.exports=function(e){return"symbol"==typeof e||o(e)&&"[object Symbol]"==r(e)}},8601:(e,t,a)=>{var r=a(4841),o=1/0;e.exports=function(e){return e?(e=r(e))===o||e===-1/0?17976931348623157e292*(e<0?-1:1):e==e?e:0:0===e?e:0}},554:(e,t,a)=>{var r=a(8601);e.exports=function(e){var t=r(e),a=t%1;return t==t?a?t-a:t:0}},4841:(e,t,a)=>{var r=a(7561),o=a(3218),n=a(3448),i=/^[-+]0x[0-9a-f]+$/i,s=/^0b[01]+$/i,l=/^0o[0-7]+$/i,m=parseInt;e.exports=function(e){if("number"==typeof e)return e;if(n(e))return NaN;if(o(e)){var t="function"==typeof e.valueOf?e.valueOf():e;e=o(t)?t+"":t}if("string"!=typeof e)return 0===e?e:+e;e=r(e);var a=s.test(e);return a||l.test(e)?m(e.slice(2),a?2:8):i.test(e)?NaN:+e}},9833:(e,t,a)=>{var r=a(531);e.exports=function(e){return null==e?"":r(e)}}},t={};function a(r){var o=t[r];if(void 0!==o)return o.exports;var n=t[r]={exports:{}};return e[r](n,n.exports,a),n.exports}a.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}();var r=a(5546);freeaps_determineBasal=r})();