Skip to content

Commit

Permalink
Floating carbs / UAM (#452)
Browse files Browse the repository at this point in the history
* only do UAMpredBGs within DIA hours of a bolus

* enable bolus snooze if we don't have COB

* enableUAM after bolus or eating soon; enableSMB for COB too

* don't SMB when minPredBG is already below max_bg

* syntax

* print out IOB/COB/UAM predBG in reason field

* only calculate minDeviationSlope from maxDeviation to now

* only calculate minDeviationSlope from maxDeviation to now

* remove extra comma in reason field

* change back to 1h of data (45m of deviations) fo UAM

* use minAvgDelta for calculating predicted CI from UAM

* only display IOB/COB/UAM predBG when used

* only display each predBG if used

* only consider carbs from last DIA hours as a workaround for undead carbs

* predUCI debugging on

* let's try decaying predicted CI from UAM at minDeviationSlope/2

* spacing for pebble

* use the higher of minCOBPredBG or minUAMPredBG as minPredBG

* debugging

* spacing for pebble

* debugging

* debugging

* define minPredBG outside the if clause

* clean up old comments and whitespace

* ignore future temps and reduce predBG oscillation

* UAMduration off by 5m

* Project UAM impact out to DIA hours

Now that we're excluding future temps from predBGs, they're not as much
"up and to the right" when we have a long zero temp running.  So it should
be safter to extend UAM impact out up to DIA hours when we're at peak recent
deviations.  As soon as deviations start to come down that'll limit the UAM
impact predictions.

* undefined-check basalprofile_data[0]

* don't cancel low temps unless unneeded for naive_eventualBG too

* only enact after refresh_old_pumphistory in non-SMB mode

* debugging

* return maxDeviation

* return maxDeviation

* run autosens every 90m if edison-battery < 60%

* run autosens every 90m if edison-battery < 60%

* wait up to 5 minutes for new BG if rig battery low

* wait up to 5 minutes for new BG if rig battery low

* syntax

* syntax

* inline

* to -n or not to -n

* run low_battery_wait on regular pump-loop too

* run low_battery_wait on regular pump-loop too

* simplify break-out logic

* set mtime of glucose.json to time of most recent glucose value

* don't SMB for a trace of bolusiob due to a microbolus delivered when basal was higher

* run battery mode any time Edison isn't charged/charging

* if no monitor/temp_basal.json file, break

* check if monitor/edison-battery.json exists

* clarity

* don't print filename with ls

* copy-pasta

* to -n or not to -n

* 60-70% inclusive = charging

* allow high-temps 5mg/dL lower: at 70 instead of 75 when target is 100

* set Carb Impact high enough to absorb all meal carbs over 4 hours

* syntax

* formula was right originally; commented

* only killall if stuff really gets stuck

* wait longer for silence before giving up

* don't print filename with ls

* if we can't keep pumphistory refreshed, defer to other rigs

* if we can't keep pumphistory refreshed, defer to other rigs

* if we can't keep pumphistory refreshed, defer to other rigs

* wait longer for silence before giving up

* adjust the target ISF to be a weighted average of fullNewISF and pumpISF

* cap adjustedISF before applying 10%

* allow SMBs every 3 minutes

* don't use a minPredBG that's higher than any maxPredBG

* debugging

* fix formulas

* round meal_carbimpact

* meal_carbimpact * 2 since it linearly decays to zero

* use 6 hours for now, until we fix the TODO

* instead of profile.min_5m_carbimpact, assume all carbs absorb over 4h

* allow SMBs every 3 minutes

* totalCI can't be negative

* fix formulas

* generate COBpredBGs if remainingCI > 0; don't let ci be negative

* debugging

* stop adding remainingCI after 4h

* if UAM is enabled, use the higher of minCOBPredBG or minUAMPredBG

* need to allow negative CI to get good downward predictions

* truncate all BG predictions at 3 hours

* don't allow negative durations

* don't allow negative ci to mess up predCI

* don't use long_avgdelta for minDelta, to respond more quickly to upticks

* if naive_eventualBG < 40, set a 30m zero temp

* only use maxUAMPredBG if enableUAM; otherwise it's current bg

We don't need maxCOBPredBG here, because that is always >= minCOBPredBG, which we just used

* don't let maxUAMPredBG prevent high-temping for carbs

* cap remainingCarbs at 90g

* include 0m-ago data points in now

* chmod +x ./bin/*.py

* Allow wider BG target adjustment for autosens

* fix minPredBG logic for high-temping based on minIOBPredBG

* set minPredBG etc. regardless of ci

* re-add reset_spi_serial.py until oref0_init_pump_comms.py is fixed

* kill pump-loop after 5 minutes of not writing to pump-loop.log

* exclude the last 1/3 of carbs from remainingCarbs

* skip SMB stuff if No bolus needed (yet)

* syntax

* don't return false (it forces a retry)

* squelch stdout from enact/smb-suggested.json

* debugging

* newlines etc.

* newlines etc.

* wait on glucose data that is newer than last action

* spacing

* truncate all BG predictions at 3.5 hours

* only use data from the same device as the most recent BG data point

* set "charging" voltage at 58-68%

* only wait 4 minutes for new BG (pump-loop takes at least 1 minute)

* only wait 3 minutes for new BG (pump-loop takes at least 1 minute)

* require enableUAM: true in preferences.json to enable UAM

* go back to using minDeviationSlope to decay UAM CI

* adjust target BG if needed to safely bring down high BG faster without causing lows

* start at 85 for safety, which implies 100->130

* don't use adjustedTargetBG if it's above target_bg

* add adjust_targets_when_high preference (default true)

* fix variable name

* revert move of timestamp updating outside of oref0-pump-loop

* fix variable name

* fix variable name

* formula fix

* formula fix

* adjust min_bg and max_bg too

* adjust min_bg and max_bg too

* consolidate output onto single lines

* consolidate output onto single lines

* consolidate output onto single lines

* consolidate output onto single lines

* debugging

* debugging

* debugging

* debugging

* syntax

* debugging

* debugging

* debugging

* test 80 for minimum adjustedTargetBG

* debugging

* debugging

* debugging

* debugging

* debugging

* debugging

* debugging

* debugging

* wait 90m before setting minIOBPredBG and 60m before setting COB and UAM

* disable SMB/UAM except after a manual bolus for now

* only lower adjustedTarget to 80 when BG >~ 160, not >~140

* add preferences.json settings for enableSMB with bolus, COB, or temp targets

* revert autosens target range to 93-117 (for 100)

* Change name of preference value to adv_target_adjustments

* test 80 for minimum adjustedTargetBG

* only lower adjustedTarget to 80 when BG >~ 160, not >~140

* default adv_target_adjustments: false

* Call maxCOB var

* create maxCOB and defaults to 120 

create maxCOB and defaults to 120 because that's the most a typical body can absorb over 4 hours. (If someone enters more carbs or stacks more; OpenAPS will just truncate dosing based on 120. Essentially, this just limits AMA as a safety cap against weird COB calculations)

* comment

* un-revert the change that actually checks pump_loop_completed

* break if monitor/pump_loop_completed doesn't yet exist

* narrow the ranges for charged/charging

* consider pump_loop_completed even if no bolus needed

* wait 4 minutes for new BG now that we're doing it right

* always wait_for_bg regardless of battery level

* echo truthfully

* syntax

* comment out minutes_running code now that we're not incorporating future temps into eventualBG

* try also waiting for upto30s after radio reset before mmtuning

* whitespace

* grammar

* disable SMB when a high temptarget is set

* if both minUAMPredBG or minCOBPredBG are set, average them for now

* weighed average minUAMPredBG and minCOBPredBG based on how many carbs remain as COB

* wait for longer silence the weaker mmtune RSSI is

* grammar

* rounding and debugging

* grammar

* calculate minCOBPredBG if remainingCI > 0

* make sure minIOBPredBG is at least 40

* average the minIOBPredBG and minUAMPredBG for minPredBG

* we don't need to ignore low minPredBGs any more

* print basal and sens when unchanged

* include minPredBG in rT object

* update to smb_enact_temp based on pump_loop_completed

* add minPredBG to rT object

* syntax

* simplify and linearize rssi_wait

* comment

* remove unused code from autotune debugging

(3c34aa0)

* #447: if rewind_resets_autosens, use BG data since lastSiteChange

* only do padding in autosens mode, not COB calc mode

* cap all minPredBGs at 39 to avoid biasing averages

* differentiate autosens adjustments from adjust_targets_when_high ones

* allow temp rate within 0.025U/hr for decocare floating point math

* profile.adjust_targets_when_high renamed to adv_target_adjustments

* log when not Adjusting targets for high BG

* whitespace

* without COB, use max of minIOBPredBG,minUAMPredBG

* if carb_ratio is null buy we have a valid carb_ratios object, use that

* move carb_ratio null check to oref0-autotune-prep.js

* variable name

* if carb_ratio is null buy we have a valid carb_ratios object, use that

* if carb_ratio is null buy we have a valid carb_ratios object, use that

* if profile.json contains null carb_ratio use profile.pump.json

* Revert "if carb_ratio is null buy we have a valid carb_ratios object, use that"

This reverts commit 687edb8.

* Revert "if carb_ratio is null buy we have a valid carb_ratios object, use that"

This reverts commit 35d506e.

* check for carb_ratio==null if oref0-autotune-core fails

* don't do lastSiteChange stuff for oref0-meal

* wait for a full 30s silence before mmtuning

* grammar

* wait for a full 30s silence before mmtuning

* adv_target_adjustments comment

* allow setting of adjustmentFraction via preferences.json

* add remainingCarbsCap to preferences.json, defaulting to zero

* always run mocha in color mode

* don't set snoozeBG if minPredBG >= 400

* fix some tests; disable others

* use average of naive_eventualBG and minIOBPredBG to calculate worstCaseInsulinReq

this will allow it to stop zero temping sooner when it's not longer really needed.

* only mmtune 20% of the time now that we're waiting longer

* increase default min_5m_carbimpact to help avoid overestimating COB

* Update oref0-setup.sh (#454)

floating-carbs updated to allow comparison between NS and drip data and not update if values haven't changed.
  • Loading branch information
scottleibrand authored and danamlewis committed May 3, 2017
1 parent 0fc8151 commit 143879f
Show file tree
Hide file tree
Showing 17 changed files with 579 additions and 283 deletions.
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ all: test
report:
# report results to community
test:
./node_modules/.bin/mocha ${TESTS}
./node_modules/.bin/mocha -c ${TESTS}

travis:
${ISTANBUL} cover ${MOCHA} --include-all-sources true --report lcovonly -- -R tap ${TESTS}
Expand Down
2 changes: 1 addition & 1 deletion bin/oref0-determine-basal.js
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ if (!module.parent) {
if (autosens_input !== true && autosens_input.length) {
try {
autosens_data = JSON.parse(fs.readFileSync(autosens_input, 'utf8'));
console.error(JSON.stringify(autosens_data));
//console.error(JSON.stringify(autosens_data));
} catch (e) {
var msg = {
msg: "Optional feature Auto Sensitivity enabled. Could not find specified auto-sens: " + autosens_input
Expand Down
3 changes: 3 additions & 0 deletions bin/oref0-meal.js
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,9 @@ if (!module.parent) {
}
}

if (typeof basalprofile_data[0] == 'undefined') {
return console.error("Error: bad basalprofile_data:" + basalprofile_data);
}
if (typeof basalprofile_data[0].glucose != 'undefined') {
console.error("Warning: Argument order has changed: please update your oref0-meal device and meal.json report to place carbhistory.json after basalprofile.json");
var temp = carb_data;
Expand Down
192 changes: 112 additions & 80 deletions bin/oref0-pump-loop.sh

Large diffs are not rendered by default.

8 changes: 5 additions & 3 deletions bin/oref0-setup.sh
Original file line number Diff line number Diff line change
Expand Up @@ -732,7 +732,9 @@ if [[ $REPLY =~ ^[Yy]$ ]]; then
(crontab -l; crontab -l | grep -q "PATH=" || echo "PATH=$PATH" ) | crontab -
(crontab -l; crontab -l | grep -q "oref0-online $BT_MAC" || echo '* * * * * ps aux | grep -v grep | grep -q "oref0-online '$BT_MAC'" || oref0-online '$BT_MAC' >> /var/log/openaps/network.log' ) | crontab -
(crontab -l; crontab -l | grep -q "sudo wpa_cli scan" || echo '* * * * * sudo wpa_cli scan') | crontab -
(crontab -l; crontab -l | grep -q "killall -g --older-than 15m oref0" || echo '* * * * * ( killall -g --older-than 15m openaps; killall -g --older-than 15m oref0-pump-loop; killall -g --older-than 15m openaps-report )') | crontab -
(crontab -l; crontab -l | grep -q "killall -g --older-than 30m oref0" || echo '* * * * * ( killall -g --older-than 30m openaps; killall -g --older-than 30m oref0-pump-loop; killall -g --older-than 30m openaps-report )') | crontab -
# kill pump-loop after 5 minutes of not writing to pump-loop.log
(crontab -l; crontab -l | grep -q "killall -g --older-than 5m oref0" || echo '* * * * * find /var/log/openaps/pump-loop.log -mmin +5 | grep pump && ( killall -g --older-than 5m openaps; killall -g --older-than 5m oref0-pump-loop; killall -g --older-than 5m openaps-report )') | crontab -
# repair or reset git repository if it's corrupted or disk is full
(crontab -l; crontab -l | grep -q "cd $directory && oref0-reset-git" || echo "* * * * * cd $directory && oref0-reset-git") | crontab -
# truncate git history to 1000 commits if it has grown past 1500
Expand All @@ -744,8 +746,8 @@ if [[ $REPLY =~ ^[Yy]$ ]]; then
(crontab -l; crontab -l | grep -q "cd $directory-cgm-loop && oref0-truncate-git-history" || echo "* * * * * cd $directory-cgm-loop && oref0-truncate-git-history") | crontab -
(crontab -l; crontab -l | grep -q "cd $directory-cgm-loop && ps aux | grep -v grep | grep -q 'openaps monitor-cgm'" || echo "* * * * * cd $directory-cgm-loop && ps aux | grep -v grep | grep -q 'openaps monitor-cgm' || ( date; openaps monitor-cgm) | tee -a /var/log/openaps/cgm-loop.log; cp -up monitor/glucose-raw-merge.json $directory/cgm/glucose.json ; cp -up $directory/cgm/glucose.json $directory/monitor/glucose.json") | crontab -
elif [[ ${CGM,,} =~ "xdrip" ]]; then
(crontab -l; crontab -l | grep -q "cd $directory && ps aux | grep -v grep | grep -q 'openaps monitor-xdrip'" || echo "* * * * * cd $directory && ps aux | grep -v grep | grep -q 'openaps monitor-xdrip' || ( date; openaps monitor-xdrip) | tee -a /var/log/openaps/xdrip-loop.log; cp -up $directory/xdrip/glucose.json $directory/monitor/glucose.json") | crontab -
(crontab -l; crontab -l | grep -q "xDripAPS.py" || echo "@reboot python $HOME/.xDripAPS/xDripAPS.py") | crontab -
(crontab -l; crontab -l | grep -q "cd $directory && ps aux | grep -v grep | grep -q 'openaps monitor-xdrip'" || echo "* * * * * cd $directory && ps aux | grep -v grep | grep -q 'openaps monitor-xdrip' || ( date; cp -rf xdrip/glucose.json xdrip/last-glucose.json; openapsmonitor-xdrip) | tee -a /var/log/openaps/xdrip-loop.log; cmp --silent xdrip/glucose.json xdrip/last-glucose.json || cp -up $directory/xdrip/glucose.json $directory/monitor/glucose.json") | crontab -
(crontab -l; crontab -l | grep -q "xDripAPS.py" || echo "@reboot python $HOME/.xDripAPS/xDripAPS.py") | crontab -
elif [[ $ENABLE =~ dexusb ]]; then
(crontab -l; crontab -l | grep -q "@reboot .*dexusb-cgm" || echo "@reboot cd $directory && /usr/bin/python -u /usr/local/bin/oref0-dexusb-cgm-loop >> /var/log/openaps/cgm-dexusb-loop.log 2>&1" ) | crontab -
elif ! [[ ${CGM,,} =~ "mdt" ]]; then # use nightscout for cgm
Expand Down
Empty file modified bin/oref0_init_pump_comms.py
100644 → 100755
Empty file.
Empty file modified bin/oref0_subg_ww_radio_parameters.py
100644 → 100755
Empty file.
1 change: 0 additions & 1 deletion lib/autotune-prep/categorize.js
Original file line number Diff line number Diff line change
Expand Up @@ -184,7 +184,6 @@ function categorizeBGDatums(opts) {
glucoseDatum.deviation = deviation;



// Then, calculate carb absorption for that 5m interval using the deviation.
if ( mealCOB > 0 ) {
var profile = profileData;
Expand Down
24 changes: 21 additions & 3 deletions lib/autotune/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -177,9 +177,27 @@ function tuneAllTheThings (inputs) {
fullNewISF = ISF * p50ratios;
}
fullNewISF = Math.round( fullNewISF * 1000 ) / 1000;
// and apply 10% of that adjustment
var newISF = ( 0.9 * ISF ) + ( 0.1 * fullNewISF );
// adjust the target ISF to be a weighted average of fullNewISF and pumpISF
var adjustmentFraction;
if (pumpProfile.autotune_isf_adjustmentFraction) {
adjustmentFraction = pumpProfile.autotune_isf_adjustmentFraction;
} else {
adjustmentFraction = 0.5;
}
if (typeof(pumpISF) !== 'undefined') {
var adjustedISF = adjustmentFraction*fullNewISF + (1-adjustmentFraction)*pumpISF;
// cap adjustedISF before applying 10%
if (adjustedISF > maxISF) {
console.error("Limiting adjusted ISF of",adjustedISF.toFixed(2),"to",maxISF.toFixed(2),"(which is pump ISF of",pumpISF,"/",autotuneMin,")");
adjustedISF = maxISF;
} else if (adjustedISF < minISF) {
console.error("Limiting adjusted ISF of",adjustedISF.toFixed(2),"to",minISF.toFixed(2),"(which is pump ISF of",pumpISF,"/",autotuneMax,")");
adjustedISF = minISF;
}

// and apply 10% of that adjustment
var newISF = ( 0.9 * ISF ) + ( 0.1 * adjustedISF );

// low autosens ratio = high ISF
var maxISF = pumpISF / autotuneMin;
// high autosens ratio = low ISF
Expand All @@ -195,7 +213,7 @@ function tuneAllTheThings (inputs) {
newISF = Math.round( newISF * 1000 ) / 1000;
//console.error(avgRatio);
//console.error(newISF);
console.error("p50deviation:",p50deviation,"p50BGI",p50BGI,"p50ratios:",p50ratios,"Old ISF:",ISF,"fullNewISF:",fullNewISF,"newISF:",newISF);
console.error("p50deviation:",p50deviation,"p50BGI",p50BGI,"p50ratios:",p50ratios,"Old ISF:",ISF,"fullNewISF:",fullNewISF,"adjustedISF:",adjustedISF,"newISF:",newISF);

ISF = newISF;

Expand Down
30 changes: 29 additions & 1 deletion lib/determine-basal/cob-autosens.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,9 @@ function detectSensitivityandCarbAbsorption(inputs) {
basalprofile = inputs.basalprofile;
profile = inputs.iob_inputs.profile;
mealTime = new Date(inputs.mealTime);
ciTime = new Date(inputs.ciTime);

//console.error(mealTime);
//console.error(mealTime, ciTime);

// use last 24h worth of data by default
var lastSiteChange = new Date(new Date().getTime() - (24 * 60 * 60 * 1000));
Expand Down Expand Up @@ -66,6 +67,14 @@ function detectSensitivityandCarbAbsorption(inputs) {
continue;
}
}
// only consider last hour of data in CI mode
// this allows us to calculate deviations for the last ~45m
if (typeof ciTime) {
hoursAgo = (ciTime-bgTime)/(60*60*1000);
if (hoursAgo > 1 || hoursAgo < 0) {
continue;
}
}
// only consider BGs since lastSiteChange
if (lastSiteChange) {
hoursSinceSiteChange = (bgTime-lastSiteChange)/(60*60*1000);
Expand Down Expand Up @@ -104,6 +113,8 @@ function detectSensitivityandCarbAbsorption(inputs) {
}
}
var currentDeviation;
var minDeviationSlope = 0;
var maxDeviation = 0;
//console.error(bucketed_data);
for (var i=0; i < bucketed_data.length-3; ++i) {
var bgTime = new Date(bucketed_data[i].date);
Expand Down Expand Up @@ -140,9 +151,20 @@ function detectSensitivityandCarbAbsorption(inputs) {
// calculate the deviation right now, for use in min_5m
if (i==0) {
currentDeviation = Math.round((avgDelta-bgi)*1000)/1000;
if (ciTime > bgTime) {
//console.error("currentDeviation:",currentDeviation);
}
if (currentDeviation/2 > profile.min_5m_carbimpact) {
//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;
if (avgDeviation > maxDeviation) {
minDeviationSlope = Math.min(0, deviationSlope);
maxDeviation = avgDeviation;
}
//console.error("Deviations:",bgTime, avgDeviation, deviationSlope, minDeviationSlope);
}

// Exclude large positive deviations (carb absorption) from autosens
Expand Down Expand Up @@ -174,6 +196,9 @@ function detectSensitivityandCarbAbsorption(inputs) {
carbsAbsorbed += absorbed;
}
}
if(maxDeviation>0) {
//console.error("currentDeviation:",currentDeviation,"maxDeviation:",maxDeviation,"minDeviationSlope:",minDeviationSlope);
}
//console.error("");
inputs.mealTime || process.stderr.write(" ");
//console.log(JSON.stringify(avgDeltas));
Expand Down Expand Up @@ -234,6 +259,9 @@ function detectSensitivityandCarbAbsorption(inputs) {
var output = {
"ratio": ratio
, "carbsAbsorbed": carbsAbsorbed
, "currentDeviation": currentDeviation
, "maxDeviation": maxDeviation
, "minDeviationSlope": minDeviationSlope
}
return output;
}
Expand Down
Loading

0 comments on commit 143879f

Please sign in to comment.