determine-basal.js 32 KB

1
  1. var freeaps_determineBasal;(()=>{var e={2982:(e,t,r)=>{var a=r(3531);function n(e,t){t||(t=0);var r=Math.pow(10,t);return Math.round(e*r)/r}function o(e,t){return"mmol/L"===t.out_units?n(.0555*e,1):Math.round(e)}e.exports=function(e,t,r,i,s,l,u,d,m,c,g,h,p,v,B){var f=i.min_bg,b=v.overrideTarget;0!=b&&6!=b&&v.useOverride&&!i.temptargetSet&&(f=b);const M=v.smbIsOff,_=v.advancedSettings,y=v.isfAndCr,x=v.isf,S=v.cr;v.smbIsScheduledOff,v.start,v.end;const D=v.smbMinutes,w=v.uamMinutes;var G=h.useNewFormula,C=0,T=f,U=new Date;c&&(U=new Date(c));var O=0,A="",R="",I="",F="",j="",P="",E=0,q=0,W=0,k=0,L=0,z=0;const N=v.weightedAverage;var H=1,Z=i.sens,$=i.carb_ratio;v.useOverride&&(H=v.overridePercentage/100,y?(Z/=H,$/=H):(S&&($/=H),x&&(Z/=H)));const J=i.weightPercentage,K=v.average_total_data;function Q(e,t){var r=e.getTime();return new Date(r+36e5*t)}function V(e){var t=i.bolus_increment;.1!=t&&(t=.05);var r=e/t;return r>=1?n(Math.floor(r)*t,5):0}function X(e){function t(e){return e<10&&(e="0"+e),e}return t(e.getHours())+":"+t(e.getMinutes())+":00"}function Y(e,t){var r=new Date("1/1/1999 "+e),a=new Date("1/1/1999 "+t);return(r.getTime()-a.getTime())/36e5}const ee=Math.min(i.autosens_min,i.autosens_max),te=Math.max(i.autosens_min,i.autosens_max);function re(e,t){var r=0,a=t,n=(e-t)/36e5,o=0,i=n,s=0;do{if(n>0){var l=X(a),u=p[0].rate;for(let e=0;e<p.length;e++){var d=p[e].start;if(l==d){if(e+1<p.length)n>=(s=Y(p[e+1].start,p[e].start))?o=s:n<s&&(o=n);else if(e+1==p.length){let t=p[0].start;n>=(s=24-Y(p[e].start,t))?o=s:n<s&&(o=n)}r+=V((u=p[e].rate)*o),n-=o,console.log("Dynamic ratios log: scheduled insulin added: "+V(u*o)+" U. Bas duration: "+o.toPrecision(3)+" h. Base Rate: "+u+" U/h. Time :"+l),a=Q(a,o)}else if(l>d)if(e+1<p.length){var m=p[e+1].start;l<m&&(n>=(s=Y(m,l))?o=s:n<s&&(o=n),r+=V((u=p[e].rate)*o),n-=o,console.log("Dynamic ratios log: scheduled insulin added: "+V(u*o)+" U. Bas duration: "+o.toPrecision(3)+" h. Base Rate: "+u+" U/h. Time :"+l),a=Q(a,o))}else e==p.length-1&&(n>=(s=Y("23:59:59",l))?o=s:n<s&&(o=n),r+=V((u=p[e].rate)*o),n-=o,console.log("Dynamic ratios log: scheduled insulin added: "+V(u*o)+" U. Bas duration: "+o.toPrecision(3)+" h. Base Rate: "+u+" U/h. Time :"+l),a=Q(a,o))}}}while(n>0&&n<i);return r}if((te==ee||te<1||ee>1)&&(G=!1,console.log("Dynamic ISF disabled due to current autosens settings")),g.length){let e=g.length-1;var ae=new Date(g[e].timestamp),ne=new Date(g[0].timestamp);"TempBasalDuration"==g[0]._type&&(ne=new Date),(O=(ne-ae)/36e5)<23.9&&O>21?(L=re(ae,(oe=24-O,ie=ae.getTime(),new Date(ie-36e5*oe))),F="24 hours of data is required for an accurate tdd calculation. Currently only "+O.toPrecision(3)+" hours of pump history data are available. Using your pump scheduled basals to fill in the missing hours. Scheduled basals added: "+L.toPrecision(5)+" U. "):O<21?(G=!1,enableDynamicCR=!1):F=""}else console.log("Pumphistory is empty!"),G=!1,enableDynamicCR=!1;var oe,ie;for(let e=0;e<g.length;e++)"Bolus"==g[e]._type&&(k+=g[e].amount);for(let e=1;e<g.length;e++)if("TempBasal"==g[e]._type&&g[e].rate>0){E=e,z=g[e].rate;var se=g[e-1]["duration (min)"]/60,le=se,ue=new Date(g[e-1].timestamp),de=new Date(ue),me=0;do{if(e--,0==e){de=new Date;break}if("TempBasal"==g[e]._type||"PumpSuspend"==g[e]._type){de=new Date(g[e].timestamp);break}var ce=e-2;if(ce>=0&&"Rewind"==g[ce]._type){let e=g[ce].timestamp;for(;ce-1>=0&&"Prime"==g[ce-=1]._type;)me=(g[ce].timestamp-e)/36e5;me>=se&&(de=new Date(e),me=0)}}while(e>0);var ge=(de-ue)/36e5;ge<le&&(se=ge),W+=V(z*(se-me)),e=E}for(let e=0;e<g.length;e++)if(0==g[e]["duration (min)"]||"PumpResume"==g[e]._type){let t=new Date(g[e].timestamp),r=new Date(t),a=e;do{if(a>0&&(--a,"TempBasal"==g[a]._type)){r=new Date(g[a].timestamp);break}}while(a>0);(r-t)/36e5>0&&(L+=re(r,t))}for(let e=g.length-1;e>0;e--)if("TempBasalDuration"==g[e]._type){let t=g[e]["duration (min)"]/60,r=new Date(g[e].timestamp);var he=new Date(r);let a=e;do{if(--a,a>=0&&("TempBasal"==g[a]._type||"PumpSuspend"==g[a]._type)){he=new Date(g[a].timestamp);break}}while(a>0);0==e&&"TempBasalDuration"==g[0]._type&&(he=new Date,t=g[e]["duration (min)"]/60),(he-r)/36e5-t>0&&(L+=re(he,Q(r,t)))}var pe,ve={TDD:n(q=k+W+L,5),bolus:n(k,5),temp_basal:n(W,5),scheduled_basal:n(L,5)};O>21?(R=". Bolus insulin: "+k.toPrecision(5)+" U",I=". Temporary basal insulin: "+W.toPrecision(5)+" U",A=". Insulin with scheduled basal rate: "+L.toPrecision(5)+" U",j=F+" TDD past 24h is: "+q.toPrecision(5)+" U"+R+I+A,P=", TDD: "+n(q,2)+" U, "+n(k/q*100,0)+"% Bolus "+n((W+L)/q*100,0)+"% Basal"):P=", TDD: Not enough pumpData (< 21h)";const Be=e.glucose,fe=h.enableDynamicCR,be=h.adjustmentFactor,Me=h.adjustmentFactorSigmoid,_e=h.sigmoid,ye=f;var xe,Se=!1,De="",we=1;K>0&&(we=N/K),we>1?(we=n(we=Math.min(we,i.autosens_max),2),i.autosens_max):we<1&&(we=n(we=Math.max(we,i.autosens_min),2),i.autosens_min),xe=", Basal ratio: "+we,(i.high_temptarget_raises_sensitivity||i.exercise_mode)&&(Se=!0),ye>=118&&Se&&(G=!1,De="Dynamic ISF temporarily off due to a high temp target/exercising. Current min target: "+ye);var Ge=", Dynamic ratios log: ",Ce=", AF: "+(_e?Me:be),Te="BG: "+Be+" mg/dl ("+(.0555*Be).toPrecision(2)+" mmol/l)",Ue="",Oe="";const Ae=h.curve,Re=i.insulinPeakTime,Ie=h.useCustomPeakTime;var Fe=55,je=65;switch(Ae){case"rapid-acting":je=65;break;case"ultra-rapid":je=50}Ie?(Fe=120-Re,console.log("Custom insulinpeakTime set to :"+Re+", insulinFactor: "+Fe)):(Fe=120-je,console.log("insulinFactor set to : "+Fe)),pe=q,J<1&&N>1&&(q=N,console.log("Using weighted TDD average: "+n(q,2)+" U, instead of past 24 h ("+n(pe,2)+" U), weight: "+J),Oe=", Weighted TDD: "+n(q,2)+" U");var Pe="";if(G)if(_e){const e=ee,t=te-e;var Ee=te-1;1==te&&(Ee=te+.01-1);const r=.0555*(Be-f)*Me*we+Math.log10(1/Ee-e/Ee)/Math.log10(Math.E);qe=t/(1+Math.exp(-r))+e,Ue=", Sigmoid function"}else{var qe=Z*be*q*Math.log(Be/Fe+1)/1800;Ue=", Logarithmic formula"}var We=$;const ke=n($,1);var Le="",ze="";if(G&&q>0){if(Le=", Dynamic ISF/CR: On/",qe>te?(De=", Dynamic ISF limited by autosens_max setting: "+te+" ("+n(qe,2)+"), ",ze=", Autosens/Dynamic Limit: "+te+" ("+n(qe,2)+")",qe=te):qe<ee&&(De=", Dynamic ISF limited by autosens_min setting: "+ee+" ("+n(qe,2)+"). ",ze=", Autosens/Dynamic Limit: "+ee+" ("+n(qe,2)+")",qe=ee),fe){Le+="On";var Ne=". New Dynamic CR: "+n($/=qe,1)+" g/U"}else Ne=" CR: "+We+" g/U",Le+="Off";const e=Z/qe;s.ratio=qe,Pe=". Using Sigmoid function, the autosens ratio has been adjusted with sigmoid factor to: "+n(s.ratio,2)+". New ISF = "+n(e,2)+" mg/dl ("+n(.0555*e,2)+" (mmol/l). CR adjusted from "+n(ke,2)+" to "+n($,2),j+=Ge+Te+Ce+Ue+(De+=_e?Pe:", Dynamic autosens.ratio set to "+n(qe,2)+" with ISF: "+e.toPrecision(3)+" mg/dl/U ("+(.0555*e).toPrecision(3)+" mmol/l/U)")+Le+Ne+Oe}else j+=Ge+"Dynamic Settings disabled";console.log(j),G||fe?G&&i.tddAdjBasal?P+=Le+Ue+ze+Ce+xe:G&&!i.tddAdjBasal&&(P+=Le+Ue+ze+Ce):P+="",.5!==i.smb_delivery_ratio&&(P+=", SMB Ratio: "+Math.min(i.smb_delivery_ratio,1)),""!==B&&"Nothing changed"!==B&&(P+=", Middleware: "+B);var He={},Ze=new Date(U);if(void 0===i||void 0===i.current_basal)return He.error="Error: could not get current basal rate",He;var $e=a(i.current_basal,i)*H,Je=$e;v.useOverride&&(0==v.duration?console.log("Profile Override is active. Override "+n(100*H,0)+"%. Override Duration: Enabled indefinitely"):console.log("Profile Override is active. Override "+n(100*H,0)+"%. Override Expires in: "+v.duration+" min."));var Ke,Qe=new Date(e.date),Ve=n((U-Qe)/60/1e3,1),Xe=e.glucose,Ye=e.noise;Ke=e.delta>-.5?"+"+n(e.delta,0):n(e.delta,0);var et=Math.min(e.delta,e.short_avgdelta),tt=Math.min(e.short_avgdelta,e.long_avgdelta),rt=Math.max(e.delta,e.short_avgdelta,e.long_avgdelta);if((Xe<=10||38===Xe||Ye>=3)&&(He.reason="CGM is calibrating, in ??? state, or noise is high"),Xe>60&&0==e.delta&&e.short_avgdelta>-1&&e.short_avgdelta<1&&e.long_avgdelta>-1&&e.long_avgdelta<1&&400!=Xe&&"fakecgm"==e.device&&(console.error("CGM data is unchanged ("+o(Xe,i)+"+"+o(e.delta,i)+") for 5m w/ "+o(e.short_avgdelta,i)+" mg/dL ~15m change & "+o(e.long_avgdelta,2)+" mg/dL ~45m change"),console.error("Simulator mode detected ("+e.device+"): continuing anyway")),Ve>12||Ve<-5?He.reason="If current system time "+U+" is correct, then BG data is too old. The last BG data was read "+Ve+"m ago at "+Qe:0===e.short_avgdelta&&0===e.long_avgdelta&&400!=Xe&&(e.last_cal&&e.last_cal<3?He.reason="CGM was just calibrated":He.reason="CGM data is unchanged ("+o(Xe,i)+"+"+o(e.delta,i)+") for 5m w/ "+o(e.short_avgdelta,i)+" mg/dL ~15m change & "+o(e.long_avgdelta,i)+" mg/dL ~45m change"),400!=Xe&&(Xe<=10||38===Xe||Ye>=3||Ve>12||Ve<-5||0===e.short_avgdelta&&0===e.long_avgdelta))return t.rate>=Je?(He.reason+=". Canceling high temp basal of "+t.rate,He.deliverAt=Ze,He.temp="absolute",He.duration=0,He.rate=0,He):0===t.rate&&t.duration>30?(He.reason+=". Shortening "+t.duration+"m long zero temp to 30m. ",He.deliverAt=Ze,He.temp="absolute",He.duration=30,He.rate=0,He):(He.reason+=". Temp "+t.rate+" <= current basal "+Je+"U/hr; doing nothing. ",He);var at,nt,ot,it,st=i.max_iob;if(void 0!==f&&(nt=f),void 0!==i.max_bg&&(ot=f),void 0!==i.enableSMB_high_bg_target&&(it=i.enableSMB_high_bg_target),void 0===f)return He.error="Error: could not determine target_bg. ",He;at=f;var lt,ut=i.exercise_mode||i.high_temptarget_raises_sensitivity,dt=100;if(lt=i.half_basal_exercise_target,ut&&i.temptargetSet&&at>dt||i.low_temptarget_lowers_sensitivity&&i.temptargetSet&&at<dt){var mt=lt-dt;sensitivityRatio=mt*(mt+at-dt)<=0?i.autosens_max:mt/(mt+at-dt),sensitivityRatio=Math.min(sensitivityRatio,i.autosens_max),sensitivityRatio=n(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||6===b||b===i.min_bg||i.temptargetSet||(at=b,console.log("Current Override Profile Target: "+o(b,i)+" "+i.out_units)),process.stderr.write("Autosens ratio: "+sensitivityRatio+"; "));if(i.temptargetSet&&at<dt&&G&&Be>=at&&sensitivityRatio<qe&&(s.ratio=qe*(dt/at),s.ratio=Math.min(s.ratio,i.autosens_max),sensitivityRatio=n(s.ratio,2),console.log("Dynamic ratio increased from "+n(qe,2)+" to "+n(s.ratio,2)+" due to a low temp target ("+at+").")),sensitivityRatio&&!G?(Je=i.current_basal*H*sensitivityRatio,(Je=a(Je,i))!==$e?process.stderr.write("Adjusting basal from "+$e+" to "+Je+"; "):process.stderr.write("Basal unchanged: "+Je+"; ")):G&&i.tddAdjBasal&&(Je=i.current_basal*we*H,Je=a(Je,i),K>0&&(process.stderr.write("TDD-adjustment of basals activated, using tdd24h_14d_Ratio "+n(we,2)+", TDD 24h = "+n(pe,2)+"U, Weighted average TDD = "+n(N,2)+"U, (Weight percentage = "+J+"), Total data of TDDs (up to 14 days) average = "+n(K,2)+"U. "),Je!==$e*H?process.stderr.write("Adjusting basal from "+$e*H+" U/h to "+Je+" U/h; "):process.stderr.write("Basal unchanged: "+Je+" U/h; "))),i.temptargetSet);else if(void 0!==s&&s&&(i.sensitivity_raises_target&&s.ratio<1||i.resistance_lowers_target&&s.ratio>1)){nt=n((nt-60)/s.ratio)+60,ot=n((ot-60)/s.ratio)+60;var ct=n((at-60)/s.ratio)+60;at===(ct=Math.max(80,ct))?process.stderr.write("target_bg unchanged: "+o(ct,i)+"; "):process.stderr.write("target_bg from "+o(ct,i)+" to "+o(ct,i)+"; "),at=ct}var gt=o(at,i);at!=f&&(gt=0!==b&&6!==b&&b!==at?o(f,i)+"→"+o(b,i)+"→"+o(at,i):o(f,i)+"→"+o(at,i));var ht=200,pt=200,vt=200;if(e.noise>=2){var Bt=Math.max(1.1,i.noisyCGMTargetMultiplier);Math.min(250,i.maxRaw),ht=n(Math.min(200,nt*Bt)),pt=n(Math.min(200,at*Bt)),vt=n(Math.min(200,ot*Bt)),process.stderr.write("Raising target_bg for noisy / raw CGM data, from "+o(ct,i)+" to "+o(pt,i)+"; "),nt=ht,at=pt,ot=vt}T=nt-.5*(nt-40),T=Math.min(Math.max(i.threshold_setting,T,60),120),console.error(`Threshold set to ${o(T,i)}`);var ft="",bt=(n(Z,1),Z);if(void 0!==s&&s&&((bt=n(bt=Z/sensitivityRatio,1))!==Z?process.stderr.write("ISF from "+o(Z,i)+" to "+o(bt,i)):process.stderr.write("ISF unchanged: "+o(bt,i)),ft+="Autosens ratio: "+n(sensitivityRatio,2)+", ISF: "+o(Z,i)+"→"+o(bt,i)),console.error("CR:"+$),void 0===r)return He.error="Error: iob_data undefined. ",He;var Mt,_t=r;if(r.length,r.length>1&&(r=_t[0]),void 0===r.activity||void 0===r.iob)return He.error="Error: iob_data missing some property. ",He;var yt=((Mt=void 0!==r.lastTemp?n((new Date(U).getTime()-r.lastTemp.date)/6e4):0)+t.duration)%30;if(console.error("currenttemp:"+t.rate+" lastTempAge:"+Mt+"m, tempModulus:"+yt+"m"),He.temp="absolute",He.deliverAt=Ze,d&&t&&r.lastTemp&&t.rate!==r.lastTemp.rate&&Mt>10&&t.duration)return He.reason="Warning: currenttemp rate "+t.rate+" != lastTemp rate "+r.lastTemp.rate+" from pumphistory; canceling temp",u.setTempBasal(0,0,i,He,t);if(t&&r.lastTemp&&t.duration>0){var xt=Mt-r.lastTemp.duration;if(xt>5&&Mt>10)return He.reason="Warning: currenttemp running but lastTemp from pumphistory ended "+xt+"m ago; canceling temp",u.setTempBasal(0,0,i,He,t)}var St=n(-r.activity*bt*5,2),Dt=n(6*(et-St));Dt<0&&(Dt=n(6*(tt-St)))<0&&(Dt=n(6*(e.long_avgdelta-St)));var wt,Gt=(wt=r.iob>0?n(Xe-r.iob*bt):n(Xe-r.iob*Math.min(bt,Z)))+Dt;if(void 0===Gt||isNaN(Gt))return He.error="Error: could not calculate eventualBG. Sensitivity: "+bt+" Deviation: "+Dt,He;var Ct,Tt,Ut=function(e,t,r){return n(r+(e-t)/24,1)}(at,Gt,St);He={temp:"absolute",bg:Xe,tick:Ke,eventualBG:Gt,insulinReq:0,reservoir:m,deliverAt:Ze,sensitivityRatio,CR:n($,1),TDD:pe,insulin:ve,current_target:at,insulinForManualBolus:C,manualBolusErrorString:0,minDelta:et,expectedDelta:Ut,minGuardBG:Tt,minPredBG:Ct,threshold:o(T,i)};var Ot=[],At=[],Rt=[],It=[];Ot.push(Xe),At.push(Xe),It.push(Xe),Rt.push(Xe);let Ft=!1;M?(console.error("SMBs are always off."),Ft=!1):Ft=function(e,t,r,a,n,i,s,l){if(s.smbIsScheduledOff){let e=new Date(l.getHours()),t=s.start,r=s.end;if(t<r&&e>=t&&e<r)return console.error("SMB disabled: current time is in SMB disabled scheduled"),!1;if(t>r&&(e>=t||e<r))return console.error("SMB disabled: current time is in SMB disabled scheduled"),!1;if(0==t&&0==r)return console.error("SMB disabled: current time is in SMB disabled scheduled"),!1;if(t==r&&e==t)return console.error("SMB disabled: current time is in SMB disabled scheduled"),!1}return t?!e.allowSMB_with_high_temptarget&&e.temptargetSet&&n>100?(console.error("SMB disabled due to high temptarget of "+n),!1):!0===r.bwFound&&!1===e.A52_risk_enable?(console.error("SMB disabled due to Bolus Wizard activity in the last 6 hours."),!1):400==a?(console.error("Invalid CGM (HIGH). SMBs disabled."),!1):!0===e.enableSMB_always?(r.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&&r.mealCOB?(r.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 "+r.mealCOB),!0):!0===e.enableSMB_after_carbs&&r.carbs?(r.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&&n<100?(r.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 "+o(n,e)),!0):!0===e.enableSMB_high_bg&&null!==i&&a>=i?(console.error("Checking BG to see if High for SMB enablement."),console.error("Current BG",a," | High BG ",i),r.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,d,l,Xe,at,it,v,U);var jt,Pt=i.enableUAM,Et=0;Et=n(et-St,1);var qt=n(et-St,1);csf=bt/$,console.error("profile.sens:"+o(Z,i)+", sens:"+o(bt,i)+", CSF:"+n(csf,1));var Wt=n(30*csf*5/60,1);Et>Wt&&(console.error("Limiting carb impact from "+Et+" to "+Wt+"mg/dL/5m (30g/h)"),Et=Wt);var kt=3;sensitivityRatio&&(kt/=sensitivityRatio);var Lt=kt;if(l.carbs){kt=Math.max(kt,l.mealCOB/20);var zt=n((new Date(U).getTime()-l.lastCarbTime)/6e4),Nt=(l.carbs-l.mealCOB)/l.carbs;Lt=n(Lt=kt+1.5*zt/60,1),console.error("Last carbs "+zt+" minutes ago; remainingCATime:"+Lt+"hours; "+n(100*Nt,1)+"% carbs absorbed")}var Ht=Math.max(0,Et/5*60*Lt/2)/csf,Zt=90,$t=1;i.remainingCarbsCap&&(Zt=Math.min(90,i.remainingCarbsCap)),i.remainingCarbsFraction&&($t=Math.min(1,i.remainingCarbsFraction));var Jt=1-$t,Kt=Math.max(0,l.mealCOB-Ht-l.carbs*Jt),Qt=(Kt=Math.min(Zt,Kt))*csf*5/60/(Lt/2),Vt=n(l.slopeFromMaxDeviation,2),Xt=n(l.slopeFromMinDeviation,2),Yt=Math.min(Vt,-Xt/3);jt=0===Et?0:Math.min(60*Lt/5/2,Math.max(0,l.mealCOB*csf/Et)),console.error("Carb Impact:"+Et+"mg/dL per 5m; CI Duration:"+n(5*jt/60*2,1)+"hours; remaining CI ("+Lt/2+"h peak):"+n(Qt,1)+"mg/dL per 5m");var er,tr,rr,ar,nr=999,or=999,ir=999,sr=999,lr=999,ur=999,dr=999,mr=Gt,cr=Xe,gr=Xe,hr=0,pr=[],vr=[];try{_t.forEach((function(e){var t=n(-e.activity*bt*5,2),r=n(-e.iobWithZeroTemp.activity*bt*5,2),a=wt,o=Et*(1-Math.min(1,At.length/12));!0===(G&&!_e)?(mr=At[At.length-1]+n(-e.activity*(1800/(q*be*Math.log(Math.max(At[At.length-1],39)/Fe+1)))*5,2)+o,a=It[It.length-1]+n(-e.iobWithZeroTemp.activity*(1800/(q*be*Math.log(Math.max(It[It.length-1],39)/Fe+1)))*5,2),console.log("Dynamic ISF (Logarithmic Formula) )adjusted predictions for IOB and ZT: IOBpredBG: "+n(mr,2)+" , ZTpredBG: "+n(a,2))):(mr=At[At.length-1]+t+o,a=It[It.length-1]+r);var i=Math.max(0,Math.max(0,Et)*(1-Ot.length/Math.max(2*jt,1))),s=Math.min(Ot.length,12*Lt-Ot.length),l=Math.max(0,s/(Lt/2*12)*Qt);pr.push(n(l,0)),vr.push(n(i,0)),COBpredBG=Ot[Ot.length-1]+t+Math.min(0,o)+i+l;var u=Math.max(0,qt+Rt.length*Yt),d=Math.max(0,qt*(1-Rt.length/Math.max(36,1))),m=Math.min(u,d);m>0&&(hr=n(5*(Rt.length+1)/60,1)),!0===(G&&!_e)?(UAMpredBG=Rt[Rt.length-1]+n(-e.activity*(1800/(q*be*Math.log(Math.max(Rt[Rt.length-1],39)/Fe+1)))*5,2)+Math.min(0,o)+m,console.log("Dynamic ISF (Logarithmic Formula) adjusted prediction for UAM: UAMpredBG: "+n(UAMpredBG,2))):UAMpredBG=Rt[Rt.length-1]+t+Math.min(0,o)+m,At.length<48&&At.push(mr),Ot.length<48&&Ot.push(COBpredBG),Rt.length<48&&Rt.push(UAMpredBG),It.length<48&&It.push(a),COBpredBG<sr&&(sr=n(COBpredBG)),UAMpredBG<lr&&(lr=n(UAMpredBG)),mr<ur&&(ur=n(mr)),a<dr&&(dr=n(a)),At.length>18&&mr<nr&&(nr=n(mr)),mr>cr&&(cr=mr),(jt||Qt>0)&&Ot.length>18&&COBpredBG<or&&(or=n(COBpredBG)),(jt||Qt>0)&&COBpredBG>cr&&(gr=COBpredBG),Pt&&Rt.length>12&&UAMpredBG<ir&&(ir=n(UAMpredBG)),Pt&&UAMpredBG>cr&&UAMpredBG}))}catch(e){console.error("Problem with iobArray. Optional feature Advanced Meal Assist disabled")}l.mealCOB&&(console.error("predCIs (mg/dL/5m):"+vr.join(" ")),console.error("remainingCIs: "+pr.join(" "))),He.predBGs={},At.forEach((function(e,t,r){r[t]=n(Math.min(401,Math.max(39,e)))}));for(var Br=At.length-1;Br>12&&At[Br-1]===At[Br];Br--)At.pop();for(He.predBGs.IOB=At,tr=n(At[At.length-1]),It.forEach((function(e,t,r){r[t]=n(Math.min(401,Math.max(39,e)))})),Br=It.length-1;Br>6&&!(It[Br-1]>=It[Br]||It[Br]<=at);Br--)It.pop();if(He.predBGs.ZT=It,n(It[It.length-1]),l.mealCOB>0&&(Et>0||Qt>0)){for(Ot.forEach((function(e,t,r){r[t]=n(Math.min(1500,Math.max(39,e)))})),Br=Ot.length-1;Br>12&&Ot[Br-1]===Ot[Br];Br--)Ot.pop();He.predBGs.COB=Ot,rr=n(Ot[Ot.length-1]),Gt=Math.max(Gt,n(Ot[Ot.length-1])),console.error("COBpredBG: "+n(Ot[Ot.length-1]))}if(Et>0||Qt>0){if(Pt){for(Rt.forEach((function(e,t,r){r[t]=n(Math.min(401,Math.max(39,e)))})),Br=Rt.length-1;Br>12&&Rt[Br-1]===Rt[Br];Br--)Rt.pop();He.predBGs.UAM=Rt,ar=n(Rt[Rt.length-1]),Rt[Rt.length-1]&&(Gt=Math.max(Gt,n(Rt[Rt.length-1])))}He.eventualBG=Gt}console.error("UAM Impact:"+qt+"mg/dL per 5m; UAM Duration:"+hr+"hours"),nr=Math.max(39,nr),or=Math.max(39,or),ir=Math.max(39,ir),Ct=n(nr);var fr=l.mealCOB/l.carbs;er=n(ir<999&&or<999?(1-fr)*UAMpredBG+fr*COBpredBG:or<999?(mr+COBpredBG)/2:ir<999?(mr+UAMpredBG)/2:mr),dr>er&&(er=dr),Tt=n(Tt=jt||Qt>0?Pt?fr*sr+(1-fr)*lr:sr:Pt?lr:ur);var br=ir;if(dr<T)br=(ir+dr)/2;else if(dr<at){var Mr=(dr-T)/(at-T);br=(ir+(ir*Mr+dr*(1-Mr)))/2}else dr>ir&&(br=(ir+dr)/2);if(br=n(br),l.carbs)if(!Pt&&or<999)Ct=n(Math.max(nr,or));else if(or<999){var _r=fr*or+(1-fr)*br;Ct=n(Math.max(nr,or,_r))}else Ct=Pt?br:Tt;else Pt&&(Ct=n(Math.max(nr,br)));Ct=Math.min(Ct,er),process.stderr.write("minPredBG: "+Ct+" minIOBPredBG: "+nr+" minZTGuardBG: "+dr),or<999&&process.stderr.write(" minCOBPredBG: "+or),ir<999&&process.stderr.write(" minUAMPredBG: "+ir),console.error(" avgPredBG:"+er+" COB/Carbs:"+l.mealCOB+"/"+l.carbs),gr>Xe&&(Ct=Math.min(Ct,gr)),He.COB=l.mealCOB,He.IOB=r.iob,He.BGI=o(St,i),He.deviation=o(Dt,i),He.ISF=o(bt,i),He.CR=n($,1),He.target_bg=o(at,i),He.TDD=n(pe,2),He.current_target=n(at,0);var yr=He.CR;ke!=He.CR&&(yr=ke+"→"+He.CR),He.reason=ft+", COB: "+He.COB+", Dev: "+He.deviation+", BGI: "+He.BGI+", CR: "+yr+", Target: "+gt+", minPredBG "+o(Ct,i)+", minGuardBG "+o(Tt,i)+", IOBpredBG "+o(tr,i),rr>0&&(He.reason+=", COBpredBG "+o(rr,i)),ar>0&&(He.reason+=", UAMpredBG "+o(ar,i)),He.reason+=P,He.reason+="; ";var xr=wt;xr<40&&(xr=Math.min(Tt,xr));var Sr,Dr=T-xr,wr=240,Gr=240;if(l.mealCOB>0&&(Et>0||Qt>0)){for(Br=0;Br<Ot.length;Br++)if(Ot[Br]<nt){wr=5*Br;break}for(Br=0;Br<Ot.length;Br++)if(Ot[Br]<T){Gr=5*Br;break}}else{for(Br=0;Br<At.length;Br++)if(At[Br]<nt){wr=5*Br;break}for(Br=0;Br<At.length;Br++)if(At[Br]<T){Gr=5*Br;break}}Ft&&Tt<T&&(console.error("minGuardBG "+o(Tt,i)+" projected below "+o(T,i)+" - disabling SMB"),He.manualBolusErrorString=1,He.minGuardBG=Tt,He.insulinForManualBolus=n((He.eventualBG-He.target_bg)/bt,2),Ft=!1),void 0===i.maxDelta_bg_threshold&&(Sr=.2),void 0!==i.maxDelta_bg_threshold&&(Sr=Math.min(i.maxDelta_bg_threshold,.4)),rt>Sr*Xe&&(console.error("maxDelta "+o(rt,i)+" > "+100*Sr+"% of BG "+o(Xe,i)+" - disabling SMB"),He.reason+="maxDelta "+o(rt,i)+" > "+100*Sr+"% of BG "+o(Xe,i)+" - SMB disabled!, ",Ft=!1),console.error("BG projected to remain above "+o(nt,i)+" for "+wr+"minutes"),(Gr<240||wr<60)&&console.error("BG projected to remain above "+o(T,i)+" for "+Gr+"minutes");var Cr=Gr,Tr=i.current_basal*H*bt*Cr/60,Ur=Math.max(0,l.mealCOB-.25*l.carbs),Or=(Dr-Tr)/csf-Ur;Tr=n(Tr),Or=n(Or),console.error("naive_eventualBG:",wt,"bgUndershoot:",Dr,"zeroTempDuration:",Cr,"zeroTempEffect:",Tr,"carbsReq:",Or),"Could not parse clock data"==l.reason?console.error("carbsReq unknown: Could not parse clock data"):Or>=i.carbsReqThreshold&&Gr<=45&&(He.carbsReq=Or,He.reason+=Or+" add'l carbs req w/in "+Gr+"m; ");var Ar=0;if(Xe<T&&r.iob<-i.current_basal*H*20/60&&et>0&&et>Ut)He.reason+="IOB "+r.iob+" < "+n(-i.current_basal*H*20/60,2),He.reason+=" and minDelta "+o(et,i)+" > expectedDelta "+o(Ut,i)+"; ";else if(Xe<T||Tt<T)return He.reason+="minGuardBG "+o(Tt,i)+"<"+o(T,i),Dr=at-Tt,Tt<T&&(He.manualBolusErrorString=2,He.minGuardBG=Tt),He.insulinForManualBolus=n((Gt-at)/bt,2),Ar=n(Dr/bt*60/i.current_basal*H),Ar=30*n(Ar/30),Ar=Math.min(120,Math.max(30,Ar)),u.setTempBasal(0,Ar,i,He,t);if(i.skip_neutral_temps&&He.deliverAt.getMinutes()>=55){if(!Ft)return He.reason+="; Canceling temp at "+(60-He.deliverAt.getMinutes())+"min before turn of the hour to avoid beeping of MDT. SMB are disabled anyways.",u.setTempBasal(0,0,i,He,t);console.error(60-He.deliverAt.getMinutes()+"min before turn of the hour, but SMB's are enabled - not skipping neutral temps.")}var Rr=0,Ir=Je,Fr=0;if(Gt<nt){if(He.reason+="Eventual BG "+o(Gt,i)+" < "+o(nt,i),et>Ut&&et>0&&!Or)return wt<40?(He.reason+=", naive_eventualBG < 40. ",u.setTempBasal(0,30,i,He,t)):(e.delta>et?He.reason+=", but Delta "+o(Ke,i)+" > expectedDelta "+o(Ut,i):He.reason+=", but Min. Delta "+et.toFixed(2)+" > Exp. Delta "+o(Ut,i),t.duration>15&&a(Je,i)===a(t.rate,i)?(He.reason+=", temp "+t.rate+" ~ req "+Je+"U/hr. ",He):(He.reason+="; setting current basal of "+Je+" as temp. ",u.setTempBasal(Je,30,i,He,t)));Rr=n(Rr=2*Math.min(0,(Gt-at)/bt),2);var jr=Math.min(0,(wt-at)/bt);jr=n(jr,2),et<0&&et>Ut&&(Rr=n(Rr*(et/Ut),2)),Ir=a(Ir=Je+2*Rr,i),Fr=t.duration*(t.rate-Je)/60;var Pr=Math.min(Rr,jr);if(console.log("naiveInsulinReq:"+jr),Fr<Pr-.3*Je)return He.reason+=", "+t.duration+"m@"+t.rate.toFixed(2)+" is a lot less than needed. ",u.setTempBasal(Ir,30,i,He,t);if(void 0!==t.rate&&t.duration>5&&Ir>=.8*t.rate)return He.reason+=", temp "+t.rate+" ~< req "+Ir+"U/hr. ",He;if(Ir<=0){if((Ar=n((Dr=at-wt)/bt*60/i.current_basal*H))<0?Ar=0:(Ar=30*n(Ar/30),Ar=Math.min(120,Math.max(0,Ar))),Ar>0)return He.reason+=", setting "+Ar+"m zero temp. ",u.setTempBasal(Ir,Ar,i,He,t)}else He.reason+=", setting "+Ir+"U/hr. ";return u.setTempBasal(Ir,30,i,He,t)}if(et<Ut&&(He.minDelta=et,He.expectedDelta=Ut,(Ut-et>=2||Ut+-1*et>=2)&&(He.manualBolusErrorString=et>=0&&Ut>0?3:et<0&&Ut<=0||et<0&&Ut>=0?4:5),He.insulinForManualBolus=n((He.eventualBG-He.target_bg)/bt,2),!d||!Ft))return e.delta<et?He.reason+="Eventual BG "+o(Gt,i)+" > "+o(nt,i)+" but Delta "+o(Ke,i)+" < Exp. Delta "+o(Ut,i):He.reason+="Eventual BG "+o(Gt,i)+" > "+o(nt,i)+" but Min. Delta "+et.toFixed(2)+" < Exp. Delta "+o(Ut,i),t.duration>15&&a(Je,i)===a(t.rate,i)?(He.reason+=", temp "+t.rate+" ~ req "+Je+"U/hr. ",He):(He.reason+="; setting current basal of "+Je+" as temp. ",u.setTempBasal(Je,30,i,He,t));if(Math.min(Gt,Ct)<ot&&(Ct<nt&&Gt>nt&&(He.manualBolusErrorString=6,He.insulinForManualBolus=n((He.eventualBG-He.target_bg)/bt,2),He.minPredBG=Ct),!d||!Ft))return He.reason+=o(Gt,i)+"-"+o(Ct,i)+" in range: no temp required",t.duration>15&&a(Je,i)===a(t.rate,i)?(He.reason+=", temp "+t.rate+" ~ req "+Je+"U/hr. ",He):(He.reason+="; setting current basal of "+Je+" as temp. ",u.setTempBasal(Je,30,i,He,t));if(Gt>=ot&&(He.reason+="Eventual BG "+o(Gt,i)+" >= "+o(ot,i)+", ",Gt>ot&&(He.insulinForManualBolus=n((Gt-at)/bt,2))),r.iob>st)return He.reason+="IOB "+n(r.iob,2)+" > max_iob "+st,t.duration>15&&a(Je,i)===a(t.rate,i)?(He.reason+=", temp "+t.rate+" ~ req "+Je+"U/hr. ",He):(He.reason+="; setting current basal of "+Je+" as temp. ",u.setTempBasal(Je,30,i,He,t));Rr=n((Math.min(Ct,Gt)-at)/bt,2),C=n((Gt-at)/bt,2),Rr>st-r.iob?(console.error("SMB limited by maxIOB: "+st-r.iob+" (. insulinReq: "+Rr+" U)"),He.reason+="max_iob "+st+", ",Rr=st-r.iob):console.error("SMB not limited by maxIOB ( insulinReq: "+Rr+" U)."),C>st-r.iob?(console.error("Ev. Bolus limited by maxIOB: "+st-r.iob+" (. insulinForManualBolus: "+C+" U)"),He.reason+="max_iob "+st+", "):console.error("Ev. Bolus would not be limited by maxIOB ( insulinForManualBolus: "+C+" U)."),Ir=a(Ir=Je+2*Rr,i),Rr=n(Rr,3),He.insulinReq=Rr;var Er=n((new Date(U).getTime()-r.lastBolusTime)/6e4,1);if(d&&Ft&&Xe>T){var qr=30;void 0!==i.maxSMBBasalMinutes&&(qr=i.maxSMBBasalMinutes);var Wr=30;void 0!==i.maxUAMSMBBasalMinutes&&(Wr=i.maxUAMSMBBasalMinutes),v.useOverride&&_&&D!==qr&&(console.error("SMB Max Minutes - setting overriden from "+qr+" to "+D),qr=D),v.useOverride&&_&&w!==Wr&&(console.error("UAM Max Minutes - setting overriden from "+Wr+" to "+w),Wr=w);var kr=n(l.mealCOB/$,3),Lr=0;void 0===qr?(Lr=n(i.current_basal*H*30/60,1),console.error("smbMinutesSetting undefined: defaulting to 30m"),Rr>Lr&&console.error("SMB limited by maxBolus: "+Lr+" ( "+Rr+" U)")):r.iob>kr&&r.iob>0?(console.error("IOB"+r.iob+"> COB"+l.mealCOB+"; mealInsulinReq ="+kr),Wr?(console.error("maxUAMSMBBasalMinutes: "+Wr+", profile.current_basal: "+i.current_basal*H),Lr=n(i.current_basal*H*Wr/60,1)):(console.error("maxUAMSMBBasalMinutes undefined: defaulting to 30m"),Lr=n(i.current_basal*H*30/60,1)),Rr>Lr?console.error("SMB limited by maxUAMSMBBasalMinutes [ "+Wr+"m ]: "+Lr+"U ( "+Rr+"U )"):console.error("SMB is not limited by maxUAMSMBBasalMinutes. ( insulinReq: "+Rr+"U )")):(console.error(".maxSMBBasalMinutes: "+qr+", profile.current_basal: "+i.current_basal*H),Rr>(Lr=n(i.current_basal*H*qr/60,1))?console.error("SMB limited by maxSMBBasalMinutes: "+qr+"m ]: "+Lr+"U ( insulinReq: "+Rr+"U )"):console.error("SMB is not limited by maxSMBBasalMinutes. ( insulinReq: "+Rr+"U )"));var zr=i.bolus_increment,Nr=1/zr,Hr=Math.min(i.smb_delivery_ratio,1);.5!=Hr&&console.error("SMB Delivery Ratio changed from default 0.5 to "+n(Hr,2));var Zr=Math.min(Rr*Hr,Lr);Zr=Math.floor(Zr*Nr)/Nr,Ar=n((at-(wt+nr)/2)/bt*60/i.current_basal*H),Rr>0&&Zr<zr&&(Ar=0);var $r=0;Ar<=0?Ar=0:Ar>=30?(Ar=30*n(Ar/30),Ar=Math.min(60,Math.max(0,Ar))):($r=n(Je*Ar/30,2),Ar=30),He.reason+=" insulinReq "+Rr,Zr>=Lr&&(He.reason+="; maxBolus "+Lr),Ar>0&&(He.reason+="; setting "+Ar+"m low temp of "+$r+"U/h"),He.reason+=". ";var Jr=3;i.SMBInterval&&(Jr=Math.min(10,Math.max(1,i.SMBInterval)));var Kr=n(Jr-Er,0),Qr=n(60*(Jr-Er),0)%60;if(console.error("naive_eventualBG "+wt+","+Ar+"m "+$r+"U/h temp needed; last bolus "+Er+"m ago; maxBolus: "+Lr),Er>Jr?Zr>0&&(He.units=Zr,He.reason+="Microbolusing "+Zr+"U. "):He.reason+="Waiting "+Kr+"m "+Qr+"s to microbolus again. ",Ar>0)return He.rate=$r,He.duration=Ar,He}var Vr=u.getMaxSafeBasal(i);return 400==Xe?u.setTempBasal(i.current_basal,30,i,He,t):(Ir>Vr&&(He.reason+="adj. req. rate: "+Ir+" to maxSafeBasal: "+n(Vr,2)+", ",Ir=a(Vr,i)),(Fr=t.duration*(t.rate-Je)/60)>=2*Rr?(He.reason+=t.duration+"m@"+t.rate.toFixed(2)+" > 2 * insulinReq. Setting temp basal of "+Ir+"U/hr. ",u.setTempBasal(Ir,30,i,He,t)):void 0===t.duration||0===t.duration?(He.reason+="no temp, setting "+Ir+"U/hr. ",u.setTempBasal(Ir,30,i,He,t)):t.duration>5&&a(Ir,i)<=a(t.rate,i)?(He.reason+="temp "+t.rate+" >~ req "+Ir+"U/hr. ",He):(He.reason+="temp "+t.rate+"<"+Ir+"U/hr. ",u.setTempBasal(Ir,30,i,He,t)))}},3531:(e,t,r)=>{var a=r(2296);e.exports=function(e,t){var r=20;return void 0!==t&&"string"==typeof t.model&&(a(t.model,"54")||a(t.model,"23"))&&(r=40),e<1?Math.round(e*r)/r:e<10?Math.round(20*e)/20:Math.round(10*e)/10}},1873:(e,t,r)=>{var a=r(9325).Symbol;e.exports=a},4932:e=>{e.exports=function(e,t){for(var r=-1,a=null==e?0:e.length,n=Array(a);++r<a;)n[r]=t(e[r],r,e);return n}},7133:e=>{e.exports=function(e,t,r){return e==e&&(void 0!==r&&(e=e<=r?e:r),void 0!==t&&(e=e>=t?e:t)),e}},2552:(e,t,r)=>{var a=r(1873),n=r(659),o=r(9350),i=a?a.toStringTag:void 0;e.exports=function(e){return null==e?void 0===e?"[object Undefined]":"[object Null]":i&&i in Object(e)?n(e):o(e)}},7556:(e,t,r)=>{var a=r(1873),n=r(4932),o=r(6449),i=r(4394),s=a?a.prototype:void 0,l=s?s.toString:void 0;e.exports=function e(t){if("string"==typeof t)return t;if(o(t))return n(t,e)+"";if(i(t))return l?l.call(t):"";var r=t+"";return"0"==r&&1/t==-1/0?"-0":r}},4128:(e,t,r)=>{var a=r(1800),n=/^\s+/;e.exports=function(e){return e?e.slice(0,a(e)+1).replace(n,""):e}},4840:(e,t,r)=>{var a="object"==typeof r.g&&r.g&&r.g.Object===Object&&r.g;e.exports=a},659:(e,t,r)=>{var a=r(1873),n=Object.prototype,o=n.hasOwnProperty,i=n.toString,s=a?a.toStringTag:void 0;e.exports=function(e){var t=o.call(e,s),r=e[s];try{e[s]=void 0;var a=!0}catch(e){}var n=i.call(e);return a&&(t?e[s]=r:delete e[s]),n}},9350:e=>{var t=Object.prototype.toString;e.exports=function(e){return t.call(e)}},9325:(e,t,r)=>{var a=r(4840),n="object"==typeof self&&self&&self.Object===Object&&self,o=a||n||Function("return this")();e.exports=o},1800:e=>{var t=/\s/;e.exports=function(e){for(var r=e.length;r--&&t.test(e.charAt(r)););return r}},2296:(e,t,r)=>{var a=r(7133),n=r(7556),o=r(1489),i=r(3222);e.exports=function(e,t,r){e=i(e),t=n(t);var s=e.length,l=r=void 0===r?s:a(o(r),0,s);return(r-=t.length)>=0&&e.slice(r,l)==t}},6449:e=>{var t=Array.isArray;e.exports=t},3805:e=>{e.exports=function(e){var t=typeof e;return null!=e&&("object"==t||"function"==t)}},346:e=>{e.exports=function(e){return null!=e&&"object"==typeof e}},4394:(e,t,r)=>{var a=r(2552),n=r(346);e.exports=function(e){return"symbol"==typeof e||n(e)&&"[object Symbol]"==a(e)}},7400:(e,t,r)=>{var a=r(6993),n=1/0;e.exports=function(e){return e?(e=a(e))===n||e===-1/0?17976931348623157e292*(e<0?-1:1):e==e?e:0:0===e?e:0}},1489:(e,t,r)=>{var a=r(7400);e.exports=function(e){var t=a(e),r=t%1;return t==t?r?t-r:t:0}},6993:(e,t,r)=>{var a=r(4128),n=r(3805),o=r(4394),i=/^[-+]0x[0-9a-f]+$/i,s=/^0b[01]+$/i,l=/^0o[0-7]+$/i,u=parseInt;e.exports=function(e){if("number"==typeof e)return e;if(o(e))return NaN;if(n(e)){var t="function"==typeof e.valueOf?e.valueOf():e;e=n(t)?t+"":t}if("string"!=typeof e)return 0===e?e:+e;e=a(e);var r=s.test(e);return r||l.test(e)?u(e.slice(2),r?2:8):i.test(e)?NaN:+e}},3222:(e,t,r)=>{var a=r(7556);e.exports=function(e){return null==e?"":a(e)}}},t={};function r(a){var n=t[a];if(void 0!==n)return n.exports;var o=t[a]={exports:{}};return e[a](o,o.exports,r),o.exports}r.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}();var a=r(2982);freeaps_determineBasal=a})();