diff --git a/bin/oref0-autosens-history.js b/bin/oref0-autosens-history.js index 6dc645fff..a2df748e7 100755 --- a/bin/oref0-autosens-history.js +++ b/bin/oref0-autosens-history.js @@ -59,8 +59,8 @@ if (!module.parent) { if (typeof profile.isfProfile === "undefined") { - for (prop in profile[0].store) { - profilename = prop; + for (var prop in profile[0].store) { + var profilename = prop; } //console.error(profilename); //console.error(profile[0].store[profilename].basal); @@ -89,7 +89,7 @@ if (!module.parent) { "autosens_max": 2.0, "autosens_min": 0.5 }; - var inputs = { "basals": profile.basalprofile }; + inputs = { "basals": profile.basalprofile }; profile.max_daily_basal = basal.maxDailyBasal(inputs); //console.error(profile); } diff --git a/bin/oref0-autotune-core.js b/bin/oref0-autotune-core.js index ee924c4a8..2d566571f 100755 --- a/bin/oref0-autotune-core.js +++ b/bin/oref0-autotune-core.js @@ -55,7 +55,7 @@ if (!module.parent) { previous_autotune_data.insulinPeakTime = pumpprofile_data.insulinPeakTime; } - var inputs = { + inputs = { preppedGlucose: prepped_glucose_data , previousAutotune: previous_autotune_data , pumpProfile: pumpprofile_data diff --git a/bin/oref0-autotune-prep.js b/bin/oref0-autotune-prep.js index ed9189c21..f79bc81a6 100755 --- a/bin/oref0-autotune-prep.js +++ b/bin/oref0-autotune-prep.js @@ -110,7 +110,7 @@ if (!module.parent) { } } - var inputs = { + inputs = { history: pumphistory_data , profile: profile_data , pumpprofile: pumpprofile_data diff --git a/bin/oref0-calculate-iob.js b/bin/oref0-calculate-iob.js index f6cae0ac1..b64d2464f 100755 --- a/bin/oref0-calculate-iob.js +++ b/bin/oref0-calculate-iob.js @@ -53,20 +53,20 @@ if (!module.parent) { var autosens_data = null; if (autosens_input) { try { - var autosens_data = require(cwd + '/' + autosens_input); + autosens_data = require(cwd + '/' + autosens_input); } catch (e) {} //console.error(autosens_input, JSON.stringify(autosens_data)); } var pumphistory_24_data = null; if (pumphistory_24_input) { try { - var pumphistory_24_data = require(cwd + '/' + pumphistory_24_input); + pumphistory_24_data = require(cwd + '/' + pumphistory_24_input); } catch (e) {} } // pumphistory_data.sort(function (a, b) { return a.date > b.date }); - var inputs = { + inputs = { history: pumphistory_data , history24: pumphistory_24_data , profile: profile_data diff --git a/bin/oref0-detect-sensitivity.js b/bin/oref0-detect-sensitivity.js index 0c8ec5a24..3146afeb9 100755 --- a/bin/oref0-detect-sensitivity.js +++ b/bin/oref0-detect-sensitivity.js @@ -106,13 +106,13 @@ if (!module.parent) { console.error("Calculating sensitivity using 8h of non-exluded data"); detection_inputs.deviations = 96; detect(detection_inputs); - ratio8h = ratio; - newisf8h = newisf; + var ratio8h = ratio; + var newisf8h = newisf; console.error("Calculating sensitivity using all non-exluded data (up to 24h)"); detection_inputs.deviations = 288; detect(detection_inputs); - ratio24h = ratio; - newisf24h = newisf; + var ratio24h = ratio; + var newisf24h = newisf; if ( ratio8h < ratio24h ) { console.error("Using 8h autosens ratio of",ratio8h,"(ISF",newisf8h+")"); } else { diff --git a/bin/oref0-determine-basal.js b/bin/oref0-determine-basal.js index f8fa832f2..d6c93ee7d 100755 --- a/bin/oref0-determine-basal.js +++ b/bin/oref0-determine-basal.js @@ -148,7 +148,7 @@ if (!module.parent) { autosens_data = JSON.parse(fs.readFileSync(autosens_input, 'utf8')); //console.error(JSON.stringify(autosens_data)); } catch (e) { - var msg = { + msg = { msg: "Optional feature Auto Sensitivity enabled. Could not find specified auto-sens: " + autosens_input , error: e }; @@ -168,7 +168,7 @@ if (!module.parent) { reservoir_data = fs.readFileSync(reservoir_input, 'utf8'); //console.error(reservoir_data); } catch (e) { - var msg = { + msg = { msg: "Warning: Could not read required reservoir data from "+reservoir_input+"." , file: reservoir_input , error: e @@ -183,7 +183,7 @@ if (!module.parent) { currentTime = new Date(currentTime_input); console.error(currentTime); } catch (e) { - var msg = { + msg = { msg: "Warning: Could not parse current time: "+currentTime_input+"." , error: e }; @@ -212,7 +212,7 @@ if (!module.parent) { var tempBasalFunctions = require('../lib/basal-set-temp'); - rT = determine_basal(glucose_status, currenttemp, iob_data, profile, autosens_data, meal_data, tempBasalFunctions, params['microbolus'], reservoir_data, currentTime); + var rT = determine_basal(glucose_status, currenttemp, iob_data, profile, autosens_data, meal_data, tempBasalFunctions, params['microbolus'], reservoir_data, currentTime); if(typeof rT.error === 'undefined') { console.log(JSON.stringify(rT)); diff --git a/bin/oref0-get-profile.js b/bin/oref0-get-profile.js index 96dcf0ddf..96a247fda 100755 --- a/bin/oref0-get-profile.js +++ b/bin/oref0-get-profile.js @@ -98,7 +98,7 @@ if (!module.parent) { var model_input = params.model; var autotune_input = params.autotune; - var cwd = process.cwd() + cwd = process.cwd() var pumpsettings_data = require(cwd + '/' + pumpsettings_input); var bgtargets_data = require(cwd + '/' + bgtargets_input); if (bgtargets_data.units !== 'mg/dL') { @@ -130,7 +130,7 @@ if (!module.parent) { } var basalprofile_data = require(cwd + '/' + basalprofile_input); - var preferences = {}; + preferences = {}; if (typeof preferences_input !== 'undefined') { preferences = require(cwd + '/' + preferences_input); } @@ -139,7 +139,7 @@ if (!module.parent) { var model_data = { } if (params.model) { try { - model_string = fs.readFileSync(model_input, 'utf8'); + var model_string = fs.readFileSync(model_input, 'utf8'); model_data = model_string.replace(/"/gi, ''); } catch (e) { var msg = { error: e, msg: "Could not parse model_data", file: model_input}; @@ -154,7 +154,7 @@ if (!module.parent) { autotune_data = JSON.parse(fs.readFileSync(autotune_input, 'utf8')); } catch (e) { - var msg = { error: e, msg: "Could not parse autotune_data", file: autotune_input}; + msg = { error: e, msg: "Could not parse autotune_data", file: autotune_input}; console.error(msg.msg); // Continue and output a non-autotuned profile if we don't have autotune_data //console.log(JSON.stringify(msg)); @@ -169,7 +169,7 @@ if (!module.parent) { carbratio_data = JSON.parse(fs.readFileSync(carbratio_input, 'utf8')); } catch (e) { - var msg = { error: e, msg: "Could not parse carbratio_data. Feature Meal Assist enabled but cannot find required carb_ratios.", file: carbratio_input }; + msg = { error: e, msg: "Could not parse carbratio_data. Feature Meal Assist enabled but cannot find required carb_ratios.", file: carbratio_input }; console.error(msg.msg); console.log(JSON.stringify(msg)); process.exit(1); diff --git a/bin/oref0-html.js b/bin/oref0-html.js index e19c269ba..8f8ac7ae1 100755 --- a/bin/oref0-html.js +++ b/bin/oref0-html.js @@ -91,7 +91,7 @@ if (!module.parent) { var tick = delta; if (delta >= 0) { tick = "+" + delta; } var iob_data = require(cwd + '/' + iob_input); - iob = iob_data[0].iob.toFixed(1); + var iob = iob_data[0].iob.toFixed(1); var basalprofile_data = require(cwd + '/' + basalprofile_input); var basalRate; basalLookup(); @@ -124,7 +124,7 @@ if (!module.parent) { //} else { //enactedstring = enactedtemp.duration + "m@" + enactedtemp.rate.toFixed(1) + "U"; //} - tz = new Date().toString().match(/([-+][0-9]+)\s/)[1] + var tz = new Date().toString().match(/([-+][0-9]+)\s/)[1] //enactedDate = new Date(enactedtemp.timestamp.concat(tz)); //enactedHMS = enactedDate.toLocaleTimeString().split(":") //enactedat = enactedHMS[0].concat(":", enactedHMS[1]); @@ -132,7 +132,7 @@ if (!module.parent) { var mealCOB = "???"; if (typeof meal_input !== 'undefined') { try { - meal_data = JSON.parse(fs.readFileSync(meal_input, 'utf8')); + var meal_data = JSON.parse(fs.readFileSync(meal_input, 'utf8')); //console.error(JSON.stringify(meal_data)); if (typeof meal_data.mealCOB !== 'undefined') { mealCOB = meal_data.mealCOB; diff --git a/bin/oref0-meal.js b/bin/oref0-meal.js index 84a3ae942..00ed186da 100755 --- a/bin/oref0-meal.js +++ b/bin/oref0-meal.js @@ -87,7 +87,7 @@ if (!module.parent) { basalprofile_data = temp; } - var inputs = { + inputs = { history: pumphistory_data , profile: profile_data , basalprofile: basalprofile_data diff --git a/bin/oref0-pebble.js b/bin/oref0-pebble.js index b9b2ad3a6..069d26d2b 100755 --- a/bin/oref0-pebble.js +++ b/bin/oref0-pebble.js @@ -87,7 +87,7 @@ if (!module.parent) { var bgnow = glucose_data[0].glucose; var iob_data = require(cwd + '/' + iob_input); - iob = iob_data[0].iob.toFixed(1); + var iob = iob_data[0].iob.toFixed(1); var basalprofile_data = require(cwd + '/' + basalprofile_input); var basalRate; basalLookup(); @@ -116,19 +116,19 @@ if (!module.parent) { } var enactedtemp = require(cwd + '/' + enactedtemp_input); if (enactedtemp.duration < 1) { - enactedstring = "Cancel"; + var enactedstring = "Cancel"; } else { enactedstring = enactedtemp.duration + "m@" + enactedtemp.rate.toFixed(1) + "U"; } - tz = new Date().toString().match(/([-+][0-9]+)\s/)[1] - enactedDate = new Date(enactedtemp.timestamp.concat(tz)); - enactedHMS = enactedDate.toLocaleTimeString().split(":") - enactedat = enactedHMS[0].concat(":", enactedHMS[1]); + var tz = new Date().toString().match(/([-+][0-9]+)\s/)[1] + var enactedDate = new Date(enactedtemp.timestamp.concat(tz)); + var enactedHMS = enactedDate.toLocaleTimeString().split(":") + var enactedat = enactedHMS[0].concat(":", enactedHMS[1]); var mealCOB = "???"; if (typeof meal_input !== 'undefined') { try { - meal_data = JSON.parse(fs.readFileSync(meal_input, 'utf8')); + var meal_data = JSON.parse(fs.readFileSync(meal_input, 'utf8')); //console.error(JSON.stringify(meal_data)); if (typeof meal_data.mealCOB !== 'undefined') { mealCOB = meal_data.mealCOB; diff --git a/lib/autotune-prep/categorize.js b/lib/autotune-prep/categorize.js index ec2a1a6a1..a0ca93544 100644 --- a/lib/autotune-prep/categorize.js +++ b/lib/autotune-prep/categorize.js @@ -54,7 +54,7 @@ function categorizeBGDatums(opts) { var bucketedData = []; bucketedData[0] = glucoseData[0]; - j=0; + var j=0; //for loop to validate and bucket the data for (var i=1; i < glucoseData.length; ++i) { var BGTime; @@ -107,7 +107,7 @@ function categorizeBGDatums(opts) { //console.error(glucoseDatum); if (glucoseDatum) { var BGDate = new Date(glucoseDatum.date); - var BGTime = BGDate.getTime(); + BGTime = BGDate.getTime(); if ( treatmentTime < BGTime ) { treatments.splice(i,1); } @@ -125,17 +125,17 @@ function categorizeBGDatums(opts) { // main for loop var fullHistory = IOBInputs.history; for (i=bucketedData.length-5; i > 0; --i) { - var glucoseDatum = bucketedData[i]; + glucoseDatum = bucketedData[i]; //console.error(glucoseDatum); - var BGDate = new Date(glucoseDatum.date); - var BGTime = BGDate.getTime(); + BGDate = new Date(glucoseDatum.date); + BGTime = BGDate.getTime(); // As we're processing each data point, go through the treatment.carbs and see if any of them are older than // the current BG data point. If so, add those carbs to COB. - var treatment = treatments[treatments.length-1]; + treatment = treatments[treatments.length-1]; var myCarbs = 0; if (treatment) { - var treatmentDate = new Date(tz(treatment.timestamp)); - var treatmentTime = treatmentDate.getTime(); + treatmentDate = new Date(tz(treatment.timestamp)); + treatmentTime = treatmentDate.getTime(); //console.error(treatmentDate); if ( treatmentTime < BGTime ) { if (treatment.carbs >= 1) { @@ -192,22 +192,22 @@ function categorizeBGDatums(opts) { // for IOB calculations, use the average of the last 4 hours' basals to help convergence; // this helps since the basal this hour could be different from previous, especially if with autotune they start to diverge. // use the pumpbasalprofile to properly calculate IOB during periods where no temp basal is set - currentPumpBasal = basal.basalLookup(opts.pumpbasalprofile, BGDate); - BGDate1hAgo = new Date(BGTime-1*60*60*1000); - BGDate2hAgo = new Date(BGTime-2*60*60*1000); - BGDate3hAgo = new Date(BGTime-3*60*60*1000); - basal1hAgo = basal.basalLookup(opts.pumpbasalprofile, BGDate1hAgo); - basal2hAgo = basal.basalLookup(opts.pumpbasalprofile, BGDate2hAgo); - basal3hAgo = basal.basalLookup(opts.pumpbasalprofile, BGDate3hAgo); + var currentPumpBasal = basal.basalLookup(opts.pumpbasalprofile, BGDate); + var BGDate1hAgo = new Date(BGTime-1*60*60*1000); + var BGDate2hAgo = new Date(BGTime-2*60*60*1000); + var BGDate3hAgo = new Date(BGTime-3*60*60*1000); + var basal1hAgo = basal.basalLookup(opts.pumpbasalprofile, BGDate1hAgo); + var basal2hAgo = basal.basalLookup(opts.pumpbasalprofile, BGDate2hAgo); + var basal3hAgo = basal.basalLookup(opts.pumpbasalprofile, BGDate3hAgo); var sum = [currentPumpBasal,basal1hAgo,basal2hAgo,basal3hAgo].reduce(function(a, b) { return a + b; }); IOBInputs.profile.currentBasal = Math.round((sum/4)*1000)/1000; // this is the current autotuned basal, used for everything else besides IOB calculations - currentBasal = basal.basalLookup(opts.basalprofile, BGDate); + var currentBasal = basal.basalLookup(opts.basalprofile, BGDate); //console.error(currentBasal,basal1hAgo,basal2hAgo,basal3hAgo,IOBInputs.profile.currentBasal); // basalBGI is BGI of basal insulin activity. - basalBGI = Math.round(( currentBasal * sens / 60 * 5 )*100)/100; // U/hr * mg/dL/U * 1 hr / 60 minutes * 5 = mg/dL/5m + var basalBGI = Math.round(( currentBasal * sens / 60 * 5 )*100)/100; // U/hr * mg/dL/U * 1 hr / 60 minutes * 5 = mg/dL/5m //console.log(JSON.stringify(IOBInputs.profile)); // call iob since calculated elsewhere var iob = getIOB(IOBInputs)[0]; @@ -218,7 +218,7 @@ function categorizeBGDatums(opts) { // datum = one glucose data point (being prepped to store in output) glucoseDatum.BGI = BGI; // calculating deviation - deviation = avgDelta-BGI; + var deviation = avgDelta-BGI; //console.error(deviation,avgDelta,BG,bucketedData[i].glucose); // set positive deviations to zero if BG is below 80 @@ -234,8 +234,8 @@ function categorizeBGDatums(opts) { // Then, calculate carb absorption for that 5m interval using the deviation. if ( mealCOB > 0 ) { var profile = profileData; - ci = Math.max(deviation, profile.min_5m_carbimpact); - absorbed = ci * profile.carb_ratio / sens; + var ci = Math.max(deviation, profile.min_5m_carbimpact); + var absorbed = ci * profile.carb_ratio / sens; // Store the COB, and use it as the starting point for the next data point. mealCOB = Math.max(0, mealCOB-absorbed); } @@ -251,9 +251,9 @@ function categorizeBGDatums(opts) { // set initial values when we first see COB CRCarbs += myCarbs; if (!calculatingCR) { - CRInitialIOB = iob.iob; - CRInitialBG = glucoseDatum.glucose; - CRInitialCarbTime = new Date(glucoseDatum.date); + var CRInitialIOB = iob.iob; + var CRInitialBG = glucoseDatum.glucose; + var CRInitialCarbTime = new Date(glucoseDatum.date); console.error("CRInitialIOB:",CRInitialIOB,"CRInitialBG:",CRInitialBG,"CRInitialCarbTime:",CRInitialCarbTime); } // keep calculatingCR as long as we have COB or enough IOB @@ -263,9 +263,9 @@ function categorizeBGDatums(opts) { calculatingCR = true; // when COB=0 and IOB drops low enough, record end values and be done calculatingCR } else { - CREndIOB = iob.iob; - CREndBG = glucoseDatum.glucose; - CREndTime = new Date(glucoseDatum.date); + var CREndIOB = iob.iob; + var CREndBG = glucoseDatum.glucose; + var CREndTime = new Date(glucoseDatum.date); console.error("CREndIOB:",CREndIOB,"CREndBG:",CREndBG,"CREndTime:",CREndTime); var CRDatum = { CRInitialIOB: CRInitialIOB @@ -363,16 +363,16 @@ function categorizeBGDatums(opts) { } } // debug line to print out all the things - BGDateArray = BGDate.toString().split(" "); + var BGDateArray = BGDate.toString().split(" "); BGTime = BGDateArray[4]; console.error(absorbing.toString(),"mealCOB:",mealCOB.toFixed(1),"mealCarbs:",mealCarbs,"basalBGI:",basalBGI.toFixed(1),"BGI:",BGI.toFixed(1),"IOB:",iob.iob.toFixed(1),"at",BGTime,"dev:",deviation,"avgDelta:",avgDelta,type); } - var IOBInputs = { + IOBInputs = { profile: profileData , history: opts.pumpHistory }; - var treatments = find_insulin(IOBInputs); + treatments = find_insulin(IOBInputs); CRData.forEach(function(CRDatum) { var dosedOpts = { treatments: treatments @@ -424,8 +424,8 @@ function categorizeBGDatums(opts) { //console.error(ISFGlucoseData.length, UAMLength); } } - var basalLength = basalGlucoseData.length; - var ISFLength = ISFGlucoseData.length; + basalLength = basalGlucoseData.length; + ISFLength = ISFGlucoseData.length; if ( 4*basalLength + ISFLength < CSFLength && ISFLength < 10 ) { console.error("Warning: too many deviations categorized as meals"); //console.error("Adding",CSFLength,"CSF deviations to",basalLength,"basal ones"); diff --git a/lib/autotune-prep/index.js b/lib/autotune-prep/index.js index 24899c3ed..122f780ff 100644 --- a/lib/autotune-prep/index.js +++ b/lib/autotune-prep/index.js @@ -109,20 +109,18 @@ function generate (inputs) { var startPeak=opts.profile.insulinPeakTime - 10; var endPeak=opts.profile.insulinPeakTime + 10; for (var peak=startPeak; peak <= endPeak; peak=(peak+5)) { - var sqrtDeviations = 0; - var deviations = 0; - var deviationsSq = 0; + sqrtDeviations = 0; + deviations = 0; + deviationsSq = 0; opts.profile.insulinPeakTime = peak; - var curve_output = categorize(opts); - var basalGlucose = curve_output.basalGlucoseData; + curve_output = categorize(opts); + basalGlucose = curve_output.basalGlucoseData; for (hour=0; hour < 24; ++hour) { for (i=0; i < basalGlucose.length; ++i) { - var BGTime; - if (basalGlucose[i].date) { BGTime = new Date(basalGlucose[i].date); } else if (basalGlucose[i].displayTime) { @@ -133,7 +131,7 @@ function generate (inputs) { consoleError("Could not determine last BG time"); } - var myHour = BGTime.getHours(); + myHour = BGTime.getHours(); if (hour === myHour) { //console.error(basalGlucose[i].deviation); sqrtDeviations += Math.pow(parseFloat(Math.abs(basalGlucose[i].deviation)), 0.5); @@ -144,9 +142,9 @@ function generate (inputs) { } console.error(deviationsSq); - var meanDeviation = Math.round(deviations/basalGlucose.length*1000)/1000; - var SMRDeviation = Math.round(Math.pow(sqrtDeviations/basalGlucose.length,2)*1000)/1000; - var RMSDeviation = Math.round(Math.pow(deviationsSq/basalGlucose.length,0.5)*1000)/1000; + meanDeviation = Math.round(deviations/basalGlucose.length*1000)/1000; + SMRDeviation = Math.round(Math.pow(sqrtDeviations/basalGlucose.length,2)*1000)/1000; + RMSDeviation = Math.round(Math.pow(deviationsSq/basalGlucose.length,0.5)*1000)/1000; consoleError('insulinPeakTime', peak, 'meanDeviation:', meanDeviation, 'SMRDeviation:', SMRDeviation, 'RMSDeviation:',RMSDeviation, '(mg/dL)'); peakDeviations.push({ peak: peak, diff --git a/lib/autotune/index.js b/lib/autotune/index.js index 0119e94b0..57e5d3f6c 100644 --- a/lib/autotune/index.js +++ b/lib/autotune/index.js @@ -69,11 +69,11 @@ function tuneAllTheThings (inputs) { var RMSDeviations = diaDeviations[i].RMSDeviation; if (meanDeviations < minMeanDeviations) { minMeanDeviations = Math.round(meanDeviations*1000)/1000; - var meanBest = i; + meanBest = i; } if (RMSDeviations < minRMSDeviations) { minRMSDeviations = Math.round(RMSDeviations*1000)/1000; - var RMSBest = i; + RMSBest = i; } } console.error("Best insulinEndTime for meanDeviations:",diaDeviations[meanBest].dia,"hours"); @@ -104,20 +104,20 @@ function tuneAllTheThings (inputs) { var currentPeakMeanDev = peakDeviations[2].meanDeviation; var currentPeakRMSDev = peakDeviations[2].RMSDeviation; //console.error(currentPeakMeanDev); - var minMeanDeviations = 1000000; - var minRMSDeviations = 1000000; - var meanBest = 2; - var RMSBest = 2; + minMeanDeviations = 1000000; + minRMSDeviations = 1000000; + meanBest = 2; + RMSBest = 2; for (i=0; i < peakDeviations.length; i++) { - var meanDeviations = peakDeviations[i].meanDeviation; - var RMSDeviations = peakDeviations[i].RMSDeviation; + meanDeviations = peakDeviations[i].meanDeviation; + RMSDeviations = peakDeviations[i].RMSDeviation; if (meanDeviations < minMeanDeviations) { minMeanDeviations = Math.round(meanDeviations*1000)/1000; - var meanBest = i; + meanBest = i; } if (RMSDeviations < minRMSDeviations) { minRMSDeviations = Math.round(RMSDeviations*1000)/1000; - var RMSBest = i; + RMSBest = i; } } console.error("Best insulinPeakTime for meanDeviations:",peakDeviations[meanBest].peak,"minutes"); @@ -149,12 +149,12 @@ function tuneAllTheThings (inputs) { var CRTotalCarbs = 0; var CRTotalInsulin = 0; CRData.forEach(function(CRDatum) { - CRBGChange = CRDatum.CREndBG - CRDatum.CRInitialBG; - CRInsulinReq = CRBGChange / ISF; - CRIOBChange = CRDatum.CREndIOB - CRDatum.CRInitialIOB; + var CRBGChange = CRDatum.CREndBG - CRDatum.CRInitialBG; + var CRInsulinReq = CRBGChange / ISF; + var CRIOBChange = CRDatum.CREndIOB - CRDatum.CRInitialIOB; CRDatum.CRInsulinTotal = CRDatum.CRInitialIOB + CRDatum.CRInsulin + CRInsulinReq; //console.error(CRDatum.CRInitialIOB, CRDatum.CRInsulin, CRInsulinReq, CRInsulinTotal); - CR = Math.round( CRDatum.CRCarbs / CRDatum.CRInsulinTotal * 1000 )/1000; + var CR = Math.round( CRDatum.CRCarbs / CRDatum.CRInsulinTotal * 1000 )/1000; //console.error(CRBGChange, CRInsulinReq, CRIOBChange, CRInsulinTotal); //console.error("CRCarbs:",CRDatum.CRCarbs,"CRInsulin:",CRDatum.CRInsulinTotal,"CR:",CR); if (CRDatum.CRInsulin > 0) { @@ -163,7 +163,7 @@ function tuneAllTheThings (inputs) { } }); CRTotalInsulin = Math.round(CRTotalInsulin*1000)/1000; - totalCR = Math.round( CRTotalCarbs / CRTotalInsulin * 1000 )/1000; + var totalCR = Math.round( CRTotalCarbs / CRTotalInsulin * 1000 )/1000; console.error("CRTotalCarbs:",CRTotalCarbs,"CRTotalInsulin:",CRTotalInsulin,"totalCR:",totalCR); // convert the basal profile to hourly if it isn't already @@ -187,7 +187,7 @@ function tuneAllTheThings (inputs) { hourlyBasalProfile[i].rate=Math.round(hourlyBasalProfile[i].rate*1000)/1000 // pump basal profile if (pumpBasalProfile && pumpBasalProfile[0]) { - for (var j=0; j < pumpBasalProfile.length; ++j) { + for (j=0; j < pumpBasalProfile.length; ++j) { //console.error(pumpBasalProfile[j]); if (pumpBasalProfile[j].rate === 0) { console.error("ERROR: bad pumpBasalProfile",pumpBasalProfile[j]); @@ -248,14 +248,14 @@ function tuneAllTheThings (inputs) { // and adjust all of them downward proportionally } else if (basalNeeded < 0) { var threeHourBasal = 0; - for (var offset=-3; offset < 0; offset++) { + for (offset=-3; offset < 0; offset++) { offsetHour = hour + offset; if (offsetHour < 0) { offsetHour += 24; } threeHourBasal += newHourlyBasalProfile[offsetHour].rate; } var adjustmentRatio = 1.0 + basalNeeded / threeHourBasal; //console.error(adjustmentRatio); - for (var offset=-3; offset < 0; offset++) { + for (offset=-3; offset < 0; offset++) { offsetHour = hour + offset; if (offsetHour < 0) { offsetHour += 24; } newHourlyBasalProfile[offsetHour].rate = newHourlyBasalProfile[offsetHour].rate * adjustmentRatio; @@ -380,7 +380,7 @@ function tuneAllTheThings (inputs) { newCSF = minCSF; } //else { console.error("newCSF",newCSF,"is close enough to",pumpCSF); } } - oldCSF = Math.round( CSF * 1000 ) / 1000; + var oldCSF = Math.round( CSF * 1000 ) / 1000; newCSF = Math.round( newCSF * 1000 ) / 1000; totalDeviations = Math.round ( totalDeviations * 1000 )/1000; console.error("totalMealCarbs:",totalMealCarbs,"totalDeviations:",totalDeviations,"oldCSF",oldCSF,"fullNewCSF:",fullNewCSF,"newCSF:",newCSF); @@ -391,7 +391,7 @@ function tuneAllTheThings (inputs) { if (totalCR === 0) { // if no meals today, CR is unchanged - fullNewCR = carbRatio; + var fullNewCR = carbRatio; } else { // how much change would be required to account for all of the deviations fullNewCR = totalCR; @@ -412,7 +412,7 @@ function tuneAllTheThings (inputs) { } //else { console.error("newCR",newCR,"is close enough to",pumpCarbRatio); } } // only adjust by 20% - newCR = ( 0.8 * carbRatio ) + ( 0.2 * fullNewCR ); + var newCR = ( 0.8 * carbRatio ) + ( 0.2 * fullNewCR ); // safety cap newCR if (typeof(pumpCarbRatio) !== 'undefined') { if (newCR > maxCR) { @@ -484,7 +484,7 @@ function tuneAllTheThings (inputs) { if ( fullNewISF < 0 ) { var adjustedISF = ISF; } else { - var adjustedISF = adjustmentFraction*fullNewISF + (1-adjustmentFraction)*pumpISF; + adjustedISF = adjustmentFraction*fullNewISF + (1-adjustmentFraction)*pumpISF; } // cap adjustedISF before applying 10% //console.error(adjustedISF, maxISF, minISF); diff --git a/lib/determine-basal/autosens.js b/lib/determine-basal/autosens.js index 64ce6c595..db2c86834 100644 --- a/lib/determine-basal/autosens.js +++ b/lib/determine-basal/autosens.js @@ -9,22 +9,22 @@ var percentile = require('../percentile'); function detectSensitivity(inputs) { //console.error(inputs.glucose_data[0]); - glucose_data = inputs.glucose_data.map(function prepGlucose (obj) { + var glucose_data = inputs.glucose_data.map(function prepGlucose (obj) { //Support the NS sgv field to avoid having to convert in a custom way obj.glucose = obj.glucose || obj.sgv; return obj; }); //console.error(glucose_data[0]); - iob_inputs = inputs.iob_inputs; - basalprofile = inputs.basalprofile; - profile = inputs.iob_inputs.profile; + var iob_inputs = inputs.iob_inputs; + var basalprofile = inputs.basalprofile; + var profile = inputs.iob_inputs.profile; // use last 24h worth of data by default if (inputs.retrospective) { //console.error(glucose_data[0]); var lastSiteChange = new Date(new Date(glucose_data[0].date).getTime() - (24 * 60 * 60 * 1000)); } else { - var lastSiteChange = new Date(new Date().getTime() - (24 * 60 * 60 * 1000)); + lastSiteChange = new Date(new Date().getTime() - (24 * 60 * 60 * 1000)); } if (inputs.iob_inputs.profile.rewind_resets_autosens === true ) { // scan through pumphistory and set lastSiteChange to the time of the last pump rewind event @@ -70,7 +70,7 @@ function detectSensitivity(inputs) { glucose_data.reverse(); bucketed_data[0] = glucose_data[0]; //console.error(bucketed_data[0]); - j=0; + var j=0; // go through the meal treatments and remove any that are older than the oldest glucose value //console.error(meals); for (var i=1; i < glucose_data.length; ++i) { @@ -98,7 +98,7 @@ function detectSensitivity(inputs) { } // only consider BGs since lastSiteChange if (lastSiteChange) { - hoursSinceSiteChange = (bgTime-lastSiteChange)/(60*60*1000); + var hoursSinceSiteChange = (bgTime-lastSiteChange)/(60*60*1000); if (hoursSinceSiteChange < 0) { //console.error(hoursSinceSiteChange, bgTime, lastSiteChange); continue; @@ -145,7 +145,7 @@ function detectSensitivity(inputs) { var type=""; //console.error(bucketed_data); for (i=3; i < bucketed_data.length; ++i) { - var bgTime = new Date(bucketed_data[i].date); + bgTime = new Date(bucketed_data[i].date); var sens = isf.isfLookup(profile.isfProfile,bgTime); @@ -155,8 +155,8 @@ function detectSensitivity(inputs) { var delta; if (typeof(bucketed_data[i].glucose) !== 'undefined') { bg = bucketed_data[i].glucose; - last_bg = bucketed_data[i-1].glucose; - old_bg = bucketed_data[i-3].glucose; + var last_bg = bucketed_data[i-1].glucose; + var old_bg = bucketed_data[i-3].glucose; if ( isNaN(bg) || !bg || bg < 40 || isNaN(old_bg) || !old_bg || old_bg < 40 || isNaN(last_bg) || !last_bg || last_bg < 40) { process.stderr.write("!"); continue; @@ -195,22 +195,22 @@ function detectSensitivity(inputs) { } deviation = deviation.toFixed(2); - var glucoseDatum = bucketed_data[i]; + glucoseDatum = bucketed_data[i]; //console.error(glucoseDatum); - var BGDate = new Date(glucoseDatum.date); - var BGTime = BGDate.getTime(); + BGDate = new Date(glucoseDatum.date); + BGTime = BGDate.getTime(); // As we're processing each data point, go through the treatment.carbs and see if any of them are older than // the current BG data point. If so, add those carbs to COB. - var treatment = meals[meals.length-1]; + treatment = meals[meals.length-1]; if (treatment) { - var treatmentDate = new Date(tz(treatment.timestamp)); - var treatmentTime = treatmentDate.getTime(); + treatmentDate = new Date(tz(treatment.timestamp)); + treatmentTime = treatmentDate.getTime(); if ( treatmentTime < BGTime ) { if (treatment.carbs >= 1) { //console.error(treatmentDate, treatmentTime, BGTime, BGTime-treatmentTime); mealCOB += parseFloat(treatment.carbs); mealCarbs += parseFloat(treatment.carbs); - displayCOB = Math.round(mealCOB); + var displayCOB = Math.round(mealCOB); //console.error(displayCOB, mealCOB, treatment.carbs); process.stderr.write(displayCOB.toString()+"g"); } @@ -221,8 +221,8 @@ function detectSensitivity(inputs) { // calculate carb absorption for that 5m interval using the deviation. if ( mealCOB > 0 ) { //var profile = profileData; - ci = Math.max(deviation, profile.min_5m_carbimpact); - absorbed = ci * profile.carb_ratio / sens; + var ci = Math.max(deviation, profile.min_5m_carbimpact); + var absorbed = ci * profile.carb_ratio / sens; if (absorbed) { mealCOB = Math.max(0, mealCOB-absorbed); } else { @@ -268,7 +268,7 @@ function detectSensitivity(inputs) { //console.error(CSFGlucoseData[CSFGlucoseData.length-1].mealAbsorption,"carb absorption"); } - currentBasal = iob_inputs.profile.current_basal; + var currentBasal = iob_inputs.profile.current_basal; // always exclude the first 45m after each carb entry using mealStartCounter //if (iob.iob > currentBasal || uam ) { if ((!inputs.retrospective && iob.iob > 2 * currentBasal) || uam || mealStartCounter < 9 ) { @@ -314,13 +314,13 @@ function detectSensitivity(inputs) { } // add an extra negative deviation if a high temptarget is running and exercise mode is set if (profile.high_temptarget_raises_sensitivity === true || profile.exercise_mode === true) { - tempTarget = tempTargetRunning(inputs.temptargets, bgTime) + var tempTarget = tempTargetRunning(inputs.temptargets, bgTime) if (tempTarget) { //console.error(tempTarget) } if ( tempTarget > 100 ) { // for a 110 temptarget, add a -0.5 deviation, for 160 add -3 - tempDeviation=-(tempTarget-100)/20; + var tempDeviation=-(tempTarget-100)/20; process.stderr.write("-"); //console.error(tempDeviation) deviations.push(tempDeviation); @@ -354,7 +354,7 @@ function detectSensitivity(inputs) { console.error(""); console.error("Using most recent",deviations.length,"deviations since",lastSiteChange); if (deviations.length < 96) { - pad = Math.round((1 - deviations.length/96) * 18); + var pad = Math.round((1 - deviations.length/96) * 18); console.error("Adding",pad,"more zero deviations"); for (var d=0; d= 0 && percentile(deviations, i) < 0 ) { //console.error("p="+i.toFixed(2)+": "+percentile(avgDeltas, i).toFixed(2)+", "+percentile(bgis, i).toFixed(2)+", "+percentile(deviations, i).toFixed(2)); - lessThanZero = Math.round(100*i); + var lessThanZero = Math.round(100*i); console.error(lessThanZero+"% of non-meal deviations negative (>50% = sensitivity)"); } if ( percentile(deviations, (i+0.01)) > 0 && percentile(deviations, i) <= 0 ) { //console.error("p="+i.toFixed(2)+": "+percentile(avgDeltas, i).toFixed(2)+", "+percentile(bgis, i).toFixed(2)+", "+percentile(deviations, i).toFixed(2)); - greaterThanZero = 100-Math.round(100*i); + var greaterThanZero = 100-Math.round(100*i); console.error(greaterThanZero+"% of non-meal deviations positive (>50% = resistance)"); } } - pSensitive = percentile(deviations, 0.50); - pResistant = percentile(deviations, 0.50); + var pSensitive = percentile(deviations, 0.50); + var pResistant = percentile(deviations, 0.50); - average = deviationSum / deviations.length; + var average = deviationSum / deviations.length; //console.error("Mean deviation: "+average.toFixed(2)); - squareDeviations = deviations.reduce(function(acc, dev){dev_f = parseFloat(dev); return acc + dev_f * dev_f}, 0); - rmsDev = Math.sqrt(squareDeviations / deviations.length); + var squareDeviations = deviations.reduce(function(acc, dev){var dev_f = parseFloat(dev); return acc + dev_f * dev_f}, 0); + var rmsDev = Math.sqrt(squareDeviations / deviations.length); console.error("RMS deviation: "+rmsDev.toFixed(2)); var basalOff = 0; @@ -433,9 +433,9 @@ function tempTargetRunning(temptargets_data, time) { //console.error(temptargets_data); //console.error(time); for (var i = 0; i < temptargets_data.length; i++) { - start = new Date(temptargets_data[i].created_at); + var start = new Date(temptargets_data[i].created_at); //console.error(start); - expires = new Date(start.getTime() + temptargets_data[i].duration * 60 * 1000); + var expires = new Date(start.getTime() + temptargets_data[i].duration * 60 * 1000); //console.error(expires); if (time >= new Date(temptargets_data[i].created_at) && temptargets_data[i].duration === 0) { // cancel temp targets @@ -443,7 +443,7 @@ function tempTargetRunning(temptargets_data, time) { return 0; } else if (time >= new Date(temptargets_data[i].created_at) && time < expires ) { //console.error(temptargets_data[i]); - tempTarget = ( temptargets_data[i].targetTop + temptargets_data[i].targetBottom ) / 2; + var tempTarget = ( temptargets_data[i].targetTop + temptargets_data[i].targetBottom ) / 2; //console.error(tempTarget); return tempTarget; } diff --git a/lib/determine-basal/cob.js b/lib/determine-basal/cob.js index b6ad7d03d..85f0522b9 100644 --- a/lib/determine-basal/cob.js +++ b/lib/determine-basal/cob.js @@ -5,16 +5,16 @@ var isf = require('../profile/isf'); function detectCarbAbsorption(inputs) { - glucose_data = inputs.glucose_data.map(function prepGlucose (obj) { + var glucose_data = inputs.glucose_data.map(function prepGlucose (obj) { //Support the NS sgv field to avoid having to convert in a custom way obj.glucose = obj.glucose || obj.sgv; return obj; }); - iob_inputs = inputs.iob_inputs; - basalprofile = inputs.basalprofile; - profile = inputs.iob_inputs.profile; - mealTime = new Date(inputs.mealTime); - ciTime = new Date(inputs.ciTime); + var iob_inputs = inputs.iob_inputs; + var basalprofile = inputs.basalprofile; + /* TODO why does declaring profile break tests-command-behavior.tests.sh? */ profile = inputs.iob_inputs.profile; + var mealTime = new Date(inputs.mealTime); + var ciTime = new Date(inputs.ciTime); //console.error(mealTime, ciTime); @@ -28,7 +28,7 @@ function detectCarbAbsorption(inputs) { var carbsAbsorbed = 0; var bucketed_data = []; bucketed_data[0] = glucose_data[0]; - j=0; + var j=0; var foundPreMealBG = false; var lastbgi = 0; @@ -49,7 +49,7 @@ function detectCarbAbsorption(inputs) { continue; } // only consider BGs for 6h after a meal for calculating COB - hoursAfterMeal = (bgTime-mealTime)/(60*60*1000); + var hoursAfterMeal = (bgTime-mealTime)/(60*60*1000); if (hoursAfterMeal > 6 || foundPreMealBG) { continue; } else if (hoursAfterMeal < 0) { @@ -60,7 +60,7 @@ function detectCarbAbsorption(inputs) { // only consider last ~45m of data in CI mode // this allows us to calculate deviations for the last ~30m if (typeof ciTime !== 'undefined') { - hoursAgo = (ciTime-bgTime)/(45*60*1000); + var hoursAgo = (ciTime-bgTime)/(45*60*1000); if (hoursAgo > 1 || hoursAgo < 0) { continue; } @@ -76,18 +76,18 @@ function detectCarbAbsorption(inputs) { //console.error(bgTime, lastbgTime, elapsed_minutes); if(Math.abs(elapsed_minutes) > 8) { // interpolate missing data points - lastbg = glucose_data[lastbgi].glucose; + var lastbg = glucose_data[lastbgi].glucose; // cap interpolation at a maximum of 4h elapsed_minutes = Math.min(240,Math.abs(elapsed_minutes)); //console.error(elapsed_minutes); while(elapsed_minutes > 5) { - previousbgTime = new Date(lastbgTime.getTime() - 5 * 60*1000); + var previousbgTime = new Date(lastbgTime.getTime() - 5 * 60*1000); j++; bucketed_data[j] = []; bucketed_data[j].date = previousbgTime.getTime(); - gapDelta = glucose_data[i].glucose - lastbg; + var gapDelta = glucose_data[i].glucose - lastbg; //console.error(gapDelta, lastbg, elapsed_minutes); - previousbg = lastbg + (5/elapsed_minutes * gapDelta); + var previousbg = lastbg + (5/elapsed_minutes * gapDelta); bucketed_data[j].glucose = Math.round(previousbg); //console.error("Interpolated", bucketed_data[j]); @@ -115,7 +115,7 @@ function detectCarbAbsorption(inputs) { var allDeviations = []; //console.error(bucketed_data); for (i=0; i < bucketed_data.length-3; ++i) { - var bgTime = new Date(bucketed_data[i].date); + bgTime = new Date(bucketed_data[i].date); var sens = isf.isfLookup(profile.isfProfile,bgTime); @@ -145,7 +145,7 @@ function detectCarbAbsorption(inputs) { var bgi = Math.round(( -iob.activity * sens * 5 )*100)/100; bgi = bgi.toFixed(2); //console.error(delta); - deviation = delta-bgi; + var deviation = delta-bgi; deviation = deviation.toFixed(2); //if (deviation < 0 && deviation > -2) { console.error("BG: "+bg+", avgDelta: "+avgDelta+", BGI: "+bgi+", deviation: "+deviation); } // calculate the deviation right now, for use in min_5m @@ -159,8 +159,8 @@ function detectCarbAbsorption(inputs) { //console.error("currentDeviation",currentDeviation,"/2 > min_5m_carbimpact",profile.min_5m_carbimpact); } } else if (ciTime > bgTime) { - avgDeviation = Math.round((avgDelta-bgi)*1000)/1000; - deviationSlope = (avgDeviation-currentDeviation)/(bgTime-ciTime)*1000*60*5; + var avgDeviation = Math.round((avgDelta-bgi)*1000)/1000; + var deviationSlope = (avgDeviation-currentDeviation)/(bgTime-ciTime)*1000*60*5; //console.error(avgDeviation,currentDeviation,bgTime,ciTime) if (avgDeviation > maxDeviation) { slopeFromMaxDeviation = Math.min(0, deviationSlope); @@ -181,8 +181,8 @@ function detectCarbAbsorption(inputs) { // figure out how many carbs that represents // if currentDeviation is > 2 * min_5m_carbimpact, assume currentDeviation/2 worth of carbs were absorbed // but always assume at least profile.min_5m_carbimpact (3mg/dL/5m by default) absorption - ci = Math.max(deviation, currentDeviation/2, profile.min_5m_carbimpact); - absorbed = ci * profile.carb_ratio / sens; + var ci = Math.max(deviation, currentDeviation/2, profile.min_5m_carbimpact); + var absorbed = ci * profile.carb_ratio / sens; // and add that to the running total carbsAbsorbed //console.error("carbsAbsorbed:",carbsAbsorbed,"absorbed:",absorbed,"bgTime:",bgTime,"BG:",bucketed_data[i].glucose) carbsAbsorbed += absorbed; diff --git a/lib/determine-basal/determine-basal.js b/lib/determine-basal/determine-basal.js index 547f1d06a..52bc7be82 100644 --- a/lib/determine-basal/determine-basal.js +++ b/lib/determine-basal/determine-basal.js @@ -134,7 +134,7 @@ var determine_basal = function determine_basal(glucose_status, currenttemp, iob_ if ( profile.half_basal_exercise_target ) { var halfBasalTarget = profile.half_basal_exercise_target; } else { - var halfBasalTarget = 160; // when temptarget is 160 mg/dL, run 50% basal (120 = 75%; 140 = 60%) + halfBasalTarget = 160; // when temptarget is 160 mg/dL, run 50% basal (120 = 75%; 140 = 60%) // 80 mg/dL with low_temptarget_lowers_sensitivity would give 1.5x basal, but is limited to autosens_max (1.2x by default) } if ( high_temptarget_raises_sensitivity && profile.temptargetSet && target_bg > normalTarget @@ -170,7 +170,7 @@ var determine_basal = function determine_basal(glucose_status, currenttemp, iob_ // with a target of 100, default 0.7-1.2 autosens min/max range would allow a 93-117 target range min_bg = round((min_bg - 60) / autosens_data.ratio) + 60; max_bg = round((max_bg - 60) / autosens_data.ratio) + 60; - new_target_bg = round((target_bg - 60) / autosens_data.ratio) + 60; + var new_target_bg = round((target_bg - 60) / autosens_data.ratio) + 60; // don't allow target_bg below 80 new_target_bg = Math.max(80, new_target_bg); if (target_bg === new_target_bg) { @@ -232,7 +232,7 @@ var determine_basal = function determine_basal(glucose_status, currenttemp, iob_ lastTempAge = 0; } //console.error("currenttemp:",currenttemp,"lastTemp:",JSON.stringify(iob_data.lastTemp),"lastTempAge:",lastTempAge,"m"); - tempModulus = (lastTempAge + currenttemp.duration) % 30; + var tempModulus = (lastTempAge + currenttemp.duration) % 30; console.error("currenttemp:",currenttemp,"lastTempAge:",lastTempAge,"m","tempModulus:",tempModulus,"m"); rT.temp = 'absolute'; rT.deliverAt = deliverAt; @@ -278,7 +278,7 @@ var determine_basal = function determine_basal(glucose_status, currenttemp, iob_ if (iob_data.iob > 0) { var naive_eventualBG = round( bg - (iob_data.iob * sens) ); } else { // if IOB is negative, be more conservative and use the lower of sens, profile.sens - var naive_eventualBG = round( bg - (iob_data.iob * Math.min(sens, profile.sens) ) ); + naive_eventualBG = round( bg - (iob_data.iob * Math.min(sens, profile.sens) ) ); } // and adjust it for the deviation above var eventualBG = naive_eventualBG + deviation; @@ -299,9 +299,9 @@ var determine_basal = function determine_basal(glucose_status, currenttemp, iob_ // adjust target BG range if configured to bring down high BG faster } else if ( bg > max_bg && profile.adv_target_adjustments && ! profile.temptargetSet ) { // with target=100, as BG rises from 100 to 160, adjustedTarget drops from 100 to 80 - var adjustedMinBG = round(Math.max(80, min_bg - (bg - min_bg)/3 ),0); - var adjustedTargetBG =round( Math.max(80, target_bg - (bg - target_bg)/3 ),0); - var adjustedMaxBG = round(Math.max(80, max_bg - (bg - max_bg)/3 ),0); + adjustedMinBG = round(Math.max(80, min_bg - (bg - min_bg)/3 ),0); + adjustedTargetBG =round( Math.max(80, target_bg - (bg - target_bg)/3 ),0); + adjustedMaxBG = round(Math.max(80, max_bg - (bg - max_bg)/3 ),0); // if eventualBG, naive_eventualBG, and target_bg aren't all above adjustedMinBG, don’t use it //console.error("naive_eventualBG:",naive_eventualBG+", eventualBG:",eventualBG); if (eventualBG > adjustedMinBG && naive_eventualBG > adjustedMinBG && min_bg > adjustedMinBG) { @@ -437,7 +437,7 @@ var determine_basal = function determine_basal(glucose_status, currenttemp, iob_ // calculate current carb absorption rate, and how long to absorb all carbs // CI = current carb impact on BG in mg/dL/5m ci = round((minDelta - bgi),1); - uci = round((minDelta - bgi),1); + var uci = round((minDelta - bgi),1); // ISF (mg/dL/U) / CR (g/U) = CSF (mg/dL/g) if (profile.temptargetSet) { // if temptargetSet, use unadjusted profile.sens to allow activity mode sensitivityRatio to adjust CR @@ -445,11 +445,11 @@ var determine_basal = function determine_basal(glucose_status, currenttemp, iob_ } else { // otherwise, use autosens-adjusted sens to counteract autosens meal insulin dosing adjustments // so that autotuned CR is still in effect even when basals and ISF are being adjusted by autosens - var csf = sens / profile.carb_ratio; + csf = sens / profile.carb_ratio; } var maxCarbAbsorptionRate = 30; // g/h; maximum rate to assume carbs will absorb if no CI observed // limit Carb Impact to maxCarbAbsorptionRate * csf in mg/dL per 5m - maxCI = round(maxCarbAbsorptionRate*csf*5/60,1) + var maxCI = round(maxCarbAbsorptionRate*csf*5/60,1) if (ci > maxCI) { console.error("Limiting carb impact from",ci,"to",maxCI,"mg/dL/5m (",maxCarbAbsorptionRate,"g/h )"); ci = maxCI; @@ -470,7 +470,7 @@ var determine_basal = function determine_basal(glucose_status, currenttemp, iob_ var lastCarbAge = round(( new Date(systemTime).getTime() - meal_data.lastCarbTime ) / 60000); //console.error(meal_data.lastCarbTime, lastCarbAge); - fractionCOBAbsorbed = ( meal_data.carbs - meal_data.mealCOB ) / meal_data.carbs; + var fractionCOBAbsorbed = ( meal_data.carbs - meal_data.mealCOB ) / meal_data.carbs; remainingCATime = remainingCATimeMin + 1.5 * lastCarbAge/60; remainingCATime = round(remainingCATime,1); //console.error(fractionCOBAbsorbed, remainingCATimeAdjustment, remainingCATime) @@ -504,7 +504,7 @@ var determine_basal = function determine_basal(glucose_status, currenttemp, iob_ var slopeFromDeviations = Math.min(slopeFromMaxDeviation,-slopeFromMinDeviation/3); //console.error(slopeFromMaxDeviation); - aci = 10; + var aci = 10; //5m data points = g * (1U/10g) * (40mg/dL/1U) / (mg/dL/5m) // duration (in 5m data points) = COB (g) * CSF (mg/dL/g) / ci (mg/dL/5m) // limit cid to remainingCATime hours: the reset goes to remainingCI @@ -514,7 +514,7 @@ var determine_basal = function determine_basal(glucose_status, currenttemp, iob_ } else { cid = Math.min(remainingCATime*60/5/2,Math.max(0, meal_data.mealCOB * csf / ci )); } - acid = Math.max(0, meal_data.mealCOB * csf / aci ); + var acid = Math.max(0, meal_data.mealCOB * csf / aci ); // duration (hours) = duration (5m) * 5 / 60 * 2 (to account for linear decay) console.error("Carb Impact:",ci,"mg/dL per 5m; CI Duration:",round(cid*5/60*2,1),"hours; remaining CI (~2h peak):",round(remainingCIpeak,1),"mg/dL per 5m"); //console.error("Accel. Carb Impact:",aci,"mg/dL per 5m; ACI Duration:",round(acid*5/60*2,1),"hours"); @@ -545,18 +545,18 @@ var determine_basal = function determine_basal(glucose_status, currenttemp, iob_ try { iobArray.forEach(function(iobTick) { //console.error(iobTick); - predBGI = round(( -iobTick.activity * sens * 5 ), 2); - predZTBGI = round(( -iobTick.iobWithZeroTemp.activity * sens * 5 ), 2); + var predBGI = round(( -iobTick.activity * sens * 5 ), 2); + var predZTBGI = round(( -iobTick.iobWithZeroTemp.activity * sens * 5 ), 2); // for IOBpredBGs, predicted deviation impact drops linearly from current deviation down to zero // over 60 minutes (data points every 5m) - predDev = ci * ( 1 - Math.min(1,IOBpredBGs.length/(60/5)) ); + var predDev = ci * ( 1 - Math.min(1,IOBpredBGs.length/(60/5)) ); IOBpredBG = IOBpredBGs[IOBpredBGs.length-1] + predBGI + predDev; // calculate predBGs with long zero temp without deviations - ZTpredBG = ZTpredBGs[ZTpredBGs.length-1] + predZTBGI; + var ZTpredBG = ZTpredBGs[ZTpredBGs.length-1] + predZTBGI; // for COBpredBGs, predicted carb impact drops linearly from current carb impact down to zero // eventually accounting for all carbs (if they can be absorbed over DIA) - predCI = Math.max(0, Math.max(0,ci) * ( 1 - COBpredBGs.length/Math.max(cid*2,1) ) ); - predACI = Math.max(0, Math.max(0,aci) * ( 1 - COBpredBGs.length/Math.max(acid*2,1) ) ); + var predCI = Math.max(0, Math.max(0,ci) * ( 1 - COBpredBGs.length/Math.max(cid*2,1) ) ); + var predACI = Math.max(0, Math.max(0,aci) * ( 1 - COBpredBGs.length/Math.max(acid*2,1) ) ); // if any carbs aren't absorbed after remainingCATime hours, assume they'll absorb in a /\ shaped // bilinear curve peaking at remainingCIpeak at remainingCATime/2 hours (remainingCATime/2*12 * 5m) // and ending at remainingCATime h (remainingCATime*12 * 5m intervals) @@ -566,22 +566,22 @@ var determine_basal = function determine_basal(glucose_status, currenttemp, iob_ remainingCIs.push(round(remainingCI,0)); predCIs.push(round(predCI,0)); //process.stderr.write(round(predCI,1)+"+"+round(remainingCI,1)+" "); - COBpredBG = COBpredBGs[COBpredBGs.length-1] + predBGI + Math.min(0,predDev) + predCI + remainingCI; - aCOBpredBG = aCOBpredBGs[aCOBpredBGs.length-1] + predBGI + Math.min(0,predDev) + predACI; + var COBpredBG = COBpredBGs[COBpredBGs.length-1] + predBGI + Math.min(0,predDev) + predCI + remainingCI; + var aCOBpredBG = aCOBpredBGs[aCOBpredBGs.length-1] + predBGI + Math.min(0,predDev) + predACI; // for UAMpredBGs, predicted carb impact drops at slopeFromDeviations // calculate predicted CI from UAM based on slopeFromDeviations - predUCIslope = Math.max(0, uci + ( UAMpredBGs.length*slopeFromDeviations ) ); + var predUCIslope = Math.max(0, uci + ( UAMpredBGs.length*slopeFromDeviations ) ); // if slopeFromDeviations is too flat, predicted deviation impact drops linearly from // current deviation down to zero over 3h (data points every 5m) - predUCImax = Math.max(0, uci * ( 1 - UAMpredBGs.length/Math.max(3*60/5,1) ) ); + var predUCImax = Math.max(0, uci * ( 1 - UAMpredBGs.length/Math.max(3*60/5,1) ) ); //console.error(predUCIslope, predUCImax); // predicted CI from UAM is the lesser of CI based on deviationSlope or DIA - predUCI = Math.min(predUCIslope, predUCImax); + var predUCI = Math.min(predUCIslope, predUCImax); if(predUCI>0) { //console.error(UAMpredBGs.length,slopeFromDeviations, predUCI); UAMduration=round((UAMpredBGs.length+1)*5/60,1); } - UAMpredBG = UAMpredBGs[UAMpredBGs.length-1] + predBGI + Math.min(0, predDev) + predUCI; + var UAMpredBG = UAMpredBGs[UAMpredBGs.length-1] + predBGI + Math.min(0, predDev) + predUCI; //console.error(predBGI, predCI, predUCI); // truncate all BG predictions at 4 hours if ( IOBpredBGs.length < 48) { IOBpredBGs.push(IOBpredBG); } @@ -752,7 +752,7 @@ var determine_basal = function determine_basal(glucose_status, currenttemp, iob_ // if we have COB, use minCOBPredBG, or blendedMinPredBG if it's higher } else if ( minCOBPredBG < 999 ) { // calculate blendedMinPredBG based on how many carbs remain as COB - blendedMinPredBG = fractionCarbsLeft*minCOBPredBG + (1-fractionCarbsLeft)*minZTUAMPredBG; + var blendedMinPredBG = fractionCarbsLeft*minCOBPredBG + (1-fractionCarbsLeft)*minZTUAMPredBG; // if blendedMinPredBG > minCOBPredBG, use that instead minPredBG = round(Math.max(minIOBPredBG, minCOBPredBG, blendedMinPredBG)); // if carbs have been entered, but have expired, use minUAMPredBG @@ -869,7 +869,7 @@ var determine_basal = function determine_basal(glucose_status, currenttemp, iob_ // predictive low glucose suspend mode: BG is / is projected to be < threshold } else if ( bg < threshold || minGuardBG < threshold ) { rT.reason += "minGuardBG " + convert_bg(minGuardBG, profile) + "<" + convert_bg(threshold, profile); - var bgUndershoot = target_bg - minGuardBG; + bgUndershoot = target_bg - minGuardBG; var worstCaseInsulinReq = bgUndershoot / sens; var durationReq = round(60*worstCaseInsulinReq / profile.current_basal); durationReq = round(durationReq/30)*30; @@ -940,9 +940,9 @@ var determine_basal = function determine_basal(glucose_status, currenttemp, iob_ } else { // calculate a long enough zero temp to eventually correct back up to target if ( rate <=0 ) { - var bgUndershoot = target_bg - naive_eventualBG; - var worstCaseInsulinReq = bgUndershoot / sens; - var durationReq = round(60*worstCaseInsulinReq / profile.current_basal); + bgUndershoot = target_bg - naive_eventualBG; + worstCaseInsulinReq = bgUndershoot / sens; + durationReq = round(60*worstCaseInsulinReq / profile.current_basal); if (durationReq < 0) { durationReq = 0; // don't set a temp longer than 120 minutes @@ -1013,7 +1013,7 @@ var determine_basal = function determine_basal(glucose_status, currenttemp, iob_ // insulinReq is the additional insulin required to get minPredBG down to target_bg //console.error(minPredBG,eventualBG); - var insulinReq = round( (Math.min(minPredBG,eventualBG) - target_bg) / sens, 2); + insulinReq = round( (Math.min(minPredBG,eventualBG) - target_bg) / sens, 2); // if that would put us over max_iob, then reduce accordingly if (insulinReq > max_iob-iob_data.iob) { rT.reason += "max_iob " + max_iob + ", "; @@ -1021,7 +1021,7 @@ var determine_basal = function determine_basal(glucose_status, currenttemp, iob_ } // rate required to deliver insulinReq more insulin over 30m: - var rate = basal + (2 * insulinReq); + rate = basal + (2 * insulinReq); rate = round_basal(rate, profile); insulinReq = round(insulinReq,3); rT.insulinReq = insulinReq; @@ -1033,9 +1033,9 @@ var determine_basal = function determine_basal(glucose_status, currenttemp, iob_ // only allow microboluses with COB or low temp targets, or within DIA hours of a bolus if (microBolusAllowed && enableSMB && bg > threshold) { // never bolus more than maxSMBBasalMinutes worth of basal - mealInsulinReq = round( meal_data.mealCOB / profile.carb_ratio ,3); + var mealInsulinReq = round( meal_data.mealCOB / profile.carb_ratio ,3); if (typeof profile.maxSMBBasalMinutes === 'undefined' ) { - maxBolus = round( profile.current_basal * 30 / 60 ,1); + var maxBolus = round( profile.current_basal * 30 / 60 ,1); console.error("profile.maxSMBBasalMinutes undefined: defaulting to 30m"); // if IOB covers more than COB, limit maxBolus to 30m of basal } else if ( iob_data.iob > mealInsulinReq && iob_data.iob > 0 ) { @@ -1053,11 +1053,11 @@ var determine_basal = function determine_basal(glucose_status, currenttemp, iob_ } // bolus 1/2 the insulinReq, up to maxBolus, rounding down to nearest bolus increment var roundSMBTo = 1 / profile.bolus_increment; - microBolus = Math.floor(Math.min(insulinReq/2,maxBolus)*roundSMBTo)/roundSMBTo; + var microBolus = Math.floor(Math.min(insulinReq/2,maxBolus)*roundSMBTo)/roundSMBTo; // calculate a long enough zero temp to eventually correct back up to target var smbTarget = target_bg; - var worstCaseInsulinReq = (smbTarget - (naive_eventualBG + minIOBPredBG)/2 ) / sens; - var durationReq = round(60*worstCaseInsulinReq / profile.current_basal); + worstCaseInsulinReq = (smbTarget - (naive_eventualBG + minIOBPredBG)/2 ) / sens; + durationReq = round(60*worstCaseInsulinReq / profile.current_basal); // if insulinReq > 0 but not enough for a microBolus, don't set an SMB zero temp if (insulinReq > 0 && microBolus < profile.bolus_increment) { @@ -1121,7 +1121,7 @@ var determine_basal = function determine_basal(glucose_status, currenttemp, iob_ rate = round_basal(maxSafeBasal, profile); } - var insulinScheduled = currenttemp.duration * (currenttemp.rate - basal) / 60; + insulinScheduled = currenttemp.duration * (currenttemp.rate - basal) / 60; if (insulinScheduled >= insulinReq * 2) { // if current temp would deliver >2x more than the required insulin, lower the rate rT.reason += currenttemp.duration + "m@" + (currenttemp.rate).toFixed(2) + " > 2 * insulinReq. Setting temp basal of " + rate + "U/hr. "; return tempBasalFunctions.setTempBasal(rate, 30, profile, rT, currenttemp); diff --git a/lib/meal/history.js b/lib/meal/history.js index 35c1b65c1..33d2247d0 100644 --- a/lib/meal/history.js +++ b/lib/meal/history.js @@ -3,10 +3,10 @@ function arrayHasElementWithSameTimestampAndProperty(array,t,propname) { var element = array[j]; if (element.timestamp === t && element[propname] !== undefined) return true; if ( element[propname] !== undefined ) { - eDate = new Date(element.timestamp); - tDate = new Date(t); - tMin = new Date(tDate.getTime() - 2000); - tMax = new Date(tDate.getTime() + 2000); + var eDate = new Date(element.timestamp); + var tDate = new Date(t); + var tMin = new Date(tDate.getTime() - 2000); + var tMax = new Date(tDate.getTime() + 2000); //console.error(tDate, tMin, tMax); if (eDate > tMin && eDate < tMax) return true; } @@ -38,10 +38,10 @@ function findMealInputs (inputs) { } for (i=0; i < pumpHistory.length; i++) { - var current = pumpHistory[i]; + current = pumpHistory[i]; if (current._type === "Bolus" && current.timestamp) { //console.log(pumpHistory[i]); - var temp = {}; + temp = {}; temp.timestamp = current.timestamp; temp.bolus = current.amount; @@ -58,7 +58,7 @@ function findMealInputs (inputs) { } else if ((current._type === "Meal Bolus" || current._type === "Correction Bolus" || current._type === "Snack Bolus" || current._type === "Bolus Wizard" || current._type === "Carb Correction") && current.created_at) { //imports carbs entered through Nightscout Care Portal //"Bolus Wizard" refers to the Nightscout Bolus Wizard, not the Medtronic Bolus Wizard - var temp = {}; + temp = {}; temp.timestamp = current.created_at; temp.carbs = current.carbs; temp.nsCarbs = current.carbs; @@ -70,7 +70,7 @@ function findMealInputs (inputs) { duplicates += 1; } } else if (current.enteredBy === "xdrip") { - var temp = {}; + temp = {}; temp.timestamp = current.created_at; temp.carbs = current.carbs; temp.nsCarbs = current.carbs; @@ -81,7 +81,7 @@ function findMealInputs (inputs) { duplicates += 1; } } else if (current.carbs > 0) { - var temp = {}; + temp = {}; temp.carbs = current.carbs; temp.nsCarbs = current.carbs; temp.timestamp = current.created_at; @@ -92,7 +92,7 @@ function findMealInputs (inputs) { duplicates += 1; } } else if (current._type === "JournalEntryMealMarker" && current.carb_input > 0 && current.timestamp) { - var temp = {}; + temp = {}; temp.timestamp = current.timestamp; temp.carbs = current.carb_input; temp.journalCarbs = current.carb_input; @@ -105,9 +105,9 @@ function findMealInputs (inputs) { } for(i=0; i < bolusWizardInputs.length; i++) { - var current = bolusWizardInputs[i]; + current = bolusWizardInputs[i]; //console.log(bolusWizardInputs[i]); - var temp = {}; + temp = {}; temp.timestamp = current.timestamp; temp.carbs = current.carb_input; temp.bwCarbs = current.carb_input; diff --git a/lib/profile/targets.js b/lib/profile/targets.js index 51c605249..a2322ac4f 100644 --- a/lib/profile/targets.js +++ b/lib/profile/targets.js @@ -38,9 +38,9 @@ function lookup (inputs, profile) { //console.error(temptargets_data); //console.error(now); for (i = 0; i < temptargets_data.length; i++) { - start = new Date(temptargets_data[i].created_at); + var start = new Date(temptargets_data[i].created_at); //console.error(start); - expires = new Date(start.getTime() + temptargets_data[i].duration * 60 * 1000); + var expires = new Date(start.getTime() + temptargets_data[i].duration * 60 * 1000); //console.error(expires); if (now >= new Date(temptargets_data[i].created_at) && temptargets_data[i].duration === 0) { // cancel temp targets