determine-basal.js 31 KB

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