From 4920176a4a8d162f6674e29c80c83d7105bf8f9c Mon Sep 17 00:00:00 2001 From: Thomas Emge Date: Wed, 5 Dec 2018 09:25:02 -0800 Subject: [PATCH] update (#2) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix remaining references to half_basal_target (#712) * fix remaining reference to half_basal_target * fix remaining reference to half_basal_target * raise SMB-disable threshold to > 20% of bg to catch fast carb rises (#717) * BlueZ update - min version 5.47 due (BlueBorne vulnerability fix) (#724) https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2017-1000250 http://www.bluez.org/release-of-bluez-5-47/ * fix logic fail for ! enableUAM case to set minGuardBG from COB (#721) * Upload entries from G5 to nightscout (#718) * Update packages.json Add the new script * oref0-upload-entries.json This script uploads new CGM entries to Nightscout. If the network connection is lost for a period of time the entries from the last time the upload was successful (stored in ``entries-last-date.json``) buffer in ``entries-upload.json`` until the next successful upload, at which point the file is deleted. This allows the device to be offline for any number of days and you get all the entries, not just the last 288, once it comes back online. * Rename oref0-upload-entries.json to oref0-upload-entries.sh * Update oref0-setup.sh to support "g5-upload" CGM type * Add the Bash indicator * Eliminate basal vs. bolus distinctions (#685) * remove all explicit references to basaliob * add enableSMB_always preference, but don't add to displayedDefaults yet * comment out all bolus snooze code * comment out bolus snooze / IOB code * comment out bolus snooze code * comment out bolus snooze code * comment out bolus snooze code * remove bolus snooze code * comment out bolus snooze code * comment out bolus snooze test * uncomment eventualBG < max_bg code and remove snoozeBG * comment out bolus snooze tests * rate <=0 * no more need to track hightempinsulin * no more need to track netbasalinsulin * no more need to track microBolus(IOB|Insulin) * remove one more bolus snooze reference * re-add basaliob and netbasalinsulin etc. * oref0-ns-loop (#713) * use IPv4 only to wget * add package-lock.json to .gitignore * match on spidev0.0 already in use too for Pi with Explorer HAT * first untested attempt at moving ns-loop aliases into oref0-ns-loop.sh * add oref0-ns-loop * syntax * fix get_ns_bg * change ns_temptargets back for now * improve logging * improve logging * return not exit * improve logging * improve logging * improve logging * improve logging * improve logging * improve logging * improve logging * improve logging * improve logging * improve logging * improve logging * install new oref0-ns-loop * revert to settings/temptargets.json for now * improve logging * don't wait for 40s twice on random failures * consistent messaging regardless of mmeowlink version * syntax * fix comment * killall bluetoothd again immediately before installing it (#726) * apply 20g/h carbAbsorptionRate to COB not total carbs (#715) * apply carbAbsorptionRate to COB not total carbs * round allDeviations array for readability * change initial carbAbsorptionRate assumption to 20g/h * fix broken safety checks with a single pump-loop type (#725) * consolidate down to a single pump-loop type * touch /tmp/pump_loop_completed even w/o SMB * in two more places * replace chained && with || fail * syntax * syntax * timeout ns-get curls after 30s (#728) * 0.6.0-dev2 * Fix pump-loop (#729) * install SMB aliases regardless for pump-loop to work * remove no-longer-applicable comments * chmod +x bin/*.sh * predBGs with zero temps (#714) * remove all explicit references to basaliob * add enableSMB_always preference, but don't add to displayedDefaults yet * comment out all bolus snooze code * comment out bolus snooze / IOB code * comment out bolus snooze code * comment out bolus snooze code * comment out bolus snooze code * remove bolus snooze code * comment out bolus snooze code * comment out bolus snooze test * uncomment eventualBG < max_bg code and remove snoozeBG * comment out bolus snooze tests * rate <=0 * no more need to track hightempinsulin * no more need to track netbasalinsulin * no more need to track microBolus(IOB|Insulin) * remove one more bolus snooze reference * re-add basaliob and netbasalinsulin etc. * add IOBWithZeroTemps * calculate iobWithZeroTemp * include the entire iobWithZeroTemp array * calculate ZTpredBGs * show all ZTpredBGs for now * use predZTBGI for ZTpredBGs * stop displaying ZTpredBGs once they're rising and above target * calculate and log minZTUAMPredBG * use minZTUAMPredBG to adjust dosing * debugging output * only show 30m of ZTpredBGs if rising above target * disable aCOB for now * use >= to make it more clear when ZTpredBGs have flattened out * fix logic Conflicts: lib/determine-basal/determine-basal.js * if avgPredBG is below minZTGuardBG, bring it up to that level * start the zero temp 1m in the future to avoid clock skew * if minZTGuardBG is between threshold and target, blend in the averaging * move minZTUAMPredBG outside of if (meal_data.carbs) * round minZTUAMPredBG for readability * round predCIs for readability * round remainingCIs for readability * align predCIs and remainingCIs * fix comment * copy old_preferences.json for reference * disable adv_target_adjustments and enableUAM by default * use old ns-loop for MDT CGM for now (#730) * Use autosens basal adjustments in IOB calculations (#705) * set exercise mode basal and ISF based on temptarget * adjust slightly less, and only if temptarget > 110 * for temptargets > 110, adjust sensitivityRatio and IOB * don't set neutral temp if carbsReq * make sure autosens doesn't use temptarget-adjusted insulin calculations * define var sensitivityRatio * define basal before bg < 39 check * allow exercise mode to be disabled in preferences.json * flag autosens IOB calculations to avoid feedback loops * make temptarget that generates 50% basal configurable * pass optional autosens data for IOB recalculation * pass optional autosens data for IOB recalculation * use new formula in calculating IOB too * actually update basal before calculating IOB * use autosens_data if defined * make it work * turns out we don't need this * pass autosens.json to calculate-iob * disable autosens_adjust_targets by default now * don't adjust carb_ratio with autosens * adjust remainingCATime (instead of CR) for autosens * stop excluding positive deviations as soon as mealCOB=0 if meal has been absorbing for >5h * add one neutral deviation per hour to help decay over long exclusion periods * use 0.5 cutoff for rounding * no more need for a gap now that we're paddng with hourly 0 deviations * clearer reporting of % negative vs. positive deviations * only add one neutral deviation every 2 hours * add negative deviations for high temp targets * add EdisonVoltage upload back in to oref0-ns-loop (#731) * add EdisonVoltage upload back in * no more need for edisonbattery aliases now that they're in oref0-ns-loop.sh * jq pretty colors * jq pretty colors * clarity * check preferences.json is valid json (#738) * check preferences.json is valid json * please go correct your typo * Only SMB every 3m; retry up to 2m (#744) * only SMB every 3m now that we retry * retry SMB if for up to 2m if waiting * adding cron start/stop aliases (#746) * adding cron stop/start aliases * typo fix * round insulinReq down to nearest 0.1U to safely allow eSMB on small basals (#732) * make sure all apt-get packages are up to date (#733) * Limit carb impact predictions to 30g/h (#740) * limit Carb Impact to 12 mg/dL per 5m * limit Carb Impact to 12 mg/dL per 5m before calculating CATime * limit carb impact based on maxCarbAbsorptionRate = 30 g/h * allow use of 39 (LOW) to calculate currentDeviation * disable SMB if either avgDelta is >20% too (#742) * pad up to 90m of zero deviations after site change (#743) * upgrade to mmeowlink v0.11.1 for clearer pump comms messaging (#534) * only use monitor/edison-battery.json if it exists (#750) * match on spidev5.1 to indicate explorer (for runagain); fix if syntax (#751) * optionally allow SMBs with activity mode (#734) * if disableSMB_with_temptarget: false, allow (smaller) SMBs with high targets * limit Carb Impact to 12 mg/dL per 5m * limit Carb Impact to 12 mg/dL per 5m before calculating CATime * limit carb impact based on maxCarbAbsorptionRate = 30 g/h * allow use of 39 (LOW) to calculate currentDeviation * go back to profile.sens to allow activity mode sensitivityRatio to adjust CR * always print old and new ISF * preflight after rssi_wait to make other rigs keep rssi_waiting * print CR * print CR * clarify disableSMB_with_temptarget: true to be allowSMB_with_temptarget: false * that should be allowSMB_with_high_temptarget not allowSMB_with_temptarget * more user-friendly output when there aren't any temptargets * remove "Excess" * check validity of iob.json and profile.json and refresh if invalid (#745) * check validity of iob.json and profile.json and refresh if invalid * bash doesn't like empty if clauses * specify which file was invalid * only check profile.json not iob.json in refresh_old_profile * don't proceed to a suggested.json if report invoke fails * call determine-basal directly, not via openaps * convert openaps get-settings to get_settings with error checking * just check validity, not contents * cleaner log output * convert settings/pumpprofile.json to direct, and get rid of No temptargets warning * Fix edisonbattery for MDT and xDrip. (#752) * Revert "add EdisonVoltage upload back in to oref0-ns-loop (#731)" This reverts commit a865517fcc575e118015c056ea565a3b4b8011f4. Conflicts: bin/oref0-setup.sh * revert * use old ns-loop for xdrip too * 0.6.0-dev3 * remove duplicate from merge conflict * Calculate UAM and eventualBG when insufficient data for COB (#747) * Optimize oref0-ns-loop.sh (#739) * don't get_ns_bg if fresh; only run every 5m if highload * fix glucose fresh check * json is slow: just check file age * use oref0_glucose_since directly; only get 24h of glucose every hour * syntax * use nightscout carb_history directly * set mtime of ns-glucose.json based on its last reading * update glucose-24h.json if not enough glucose to calculate COB * undefined check * on insufficient glucose data, only set COB to 0; still do UAM * A52 risk reduction (#749) * add A52_risk_enable setting in preferences.json * calculate and return nsCarbs vs. bwCarbs for A52 safety checks * don't need these * SMB not enabled for Bolus Wizard * don't enable SMB without A52_risk_enable if bolus wizard in use * print SMB disabled when ! microBolusAllowed * more/better SMB enabled logging * this is actually only 6h for now * comment out undefined/unused variable * press ESC three times on the pump to exit Bolus Wizard before SMBing, to help prevent A52 errors * clean up press_keys output * send all three esc in a row, and don't bolus unless successful * press ESC three times on the pump to exit Bolus Wizard before SMBing (#753) * press ESC three times on the pump to exit Bolus Wizard before SMBing, to help prevent A52 errors * clean up press_keys output * send all three esc in a row, and don't bolus unless successful * log what we're doing with ESC ESC ESC * don't treat suspended pump as a complete failure (#755) * 0.6.0-dev4 * change default curve to rapid-acting (#769) * Remove unnecessary verbose logging of the oref0-subg-ww-radio-paramet… (#763) * Remove unnecessary verbose logging of the oref0-subg-ww-radio-parameters. This logs every line being executed, which is probably overkill and fills the pump loop logs. * Commenting out set -x per @pietergit's recommendation * Offline local-only wifi hotspot (#716) * refactor oref0-online to use functions * start_hotspot if no connectivity; stop_hotspot if online via BT * refactor one more check_ip * pass MACs to function * pass MACs to function * pass MACs to function * stop/start backwards * check if hostapd is running before stop/start * stop_hotspot if running any time we have a public IP * logic * grep -q instead of checking pid * syntax * make variables global * ifup before hostapd; systemctl daemon-reload * ifdown/ifup wlan0 in stop_hotspot * stop_hotspot when we get BT * try ifdown later * stop udhcpd before starting dnsmasq * echo * no more need for sleep * install prerequisites and configs for local-only hotspot * only do local-only hotspot if BT configured * offline webapp * check if wlan0 is still in AP mode * pass MACs to start_hotspot * make sure hostapd and dnsmasq services are running if hotspot is up * only stop hotspot if we have internet * get ns-temptargets directly, then merge with any local-temptargets * print temptarget start time * untested set-local-temptarget.js * use current time if unspecified * oref0-set-local-temptarget * oref0-append-local-temptarget * oref0-append-local-temptarget * regenerate profile after refreshing temptargets * regenerate profile after merging temptargets * allow oref0-append-local-temptarget.sh to run oref0-set-local-temptarget * parse inputs as integers * remove spurious output * delete any local-temptarget files last modified more than 24h ago * make offline_hotspot a preference, false by default * per #716 it'd be better for xDrip to keep BT connected when offline * if no wifi and no BT, try cycling wlan0 * make sure all apt-get packages are up to date * Optimize oref0-ns-loop.sh (#739) * don't get_ns_bg if fresh; only run every 5m if highload * fix glucose fresh check * json is slow: just check file age * use oref0_glucose_since directly; only get 24h of glucose every hour * syntax * use nightscout carb_history directly * set mtime of ns-glucose.json based on its last reading * write profile.json.new and validate before mv'ing * don't trust awk exit status * cd to ~/myopenaps for oref0-online to read preferences.json * Create linux-bootup.sh Instructions for /etc/rc.local startup * Update oref0-setup.sh Stop automatic startup of hostapd & dnsmasq * Update oref0-setup.sh add linux-bootup.sh to /etc/rc.local * Update linux-bootup.sh check to see if .conf actually exists before overwriting with an empty file. * Update oref0-setup.sh Edit /etc/hostapd/hostapd.conf for Hostname and wpa * Update package.json add linux-bootup.sh * Delete linux-bootup.sh bad idea * Update package.json removed bad idea * Update oref0-setup.sh removed bad idea and writing to rc.local directly * Update oref0-setup.sh change hotspot name * Update oref0-setup.sh add wpa security for Hotspot with #OpenAPS * Update oref0-setup.sh add logic to rc.local * Update hostapd.conf add security to hotspot * Update oref0-setup.sh Changes for Hotspot setup * Update oref0-setup.sh change to setup for local-only hotspot * Update oref0-setup.sh changes for the different type of wpa-roam or wpa-conf * reverse logic so failure = not enabled * remove HostAPDIP if still configured after stop_hotspot * Update oref0-online.sh Changes to improve oref0-online * Update oref0-setup.sh changes to cron * syntax * if online via BT, cycle wlan0 * check for interfaces.ap; stop_hotspot if not enabled * reorder to always stop_hotspot if not enabled * don't release hotspot IP; reorder to stop_hotspot w/o BT MAC * add /tmp/disable_hotspot support * grammar capitalization etc. * logic * don't wait for 47 years if clock is mismatched * mv offline folder to www so it doesn't conflict with branch name * only release the wifi IP/route if it's from DHCP * whitepace * print Connected to Bluetooth with IP: * consistency * display wifi is not connected if no SSID * whitepace * consistency * whitepace * consistency * whitepace * print unassigned if no * reorder and print local wifi/BT IPs separately * syntax * print name of phone we're connected to with Bluetooth * only run check_ip once * print start/finish times * don't try to dhcp_renew when running hostapd * print when PUBLIC_IP not found * fix return code * don't renew wlan0 IP/route if it's failing * logging * syntax * don't wifi_dhcp_renew if bad_wifi * f we can't connect via BT, might as well try previously bad wifi networks again * remove extra -HotSpot from SSID * disconnect bnep0 even w/o an IP * temporarily disable hotspot for 1m every hour to allow it to try to connect via wifi again * download carbhistory to carbhistory.json.new and mv it over if valid * egrep quietly * download ns-temptargets to .new and mv it over if valid * escape $directory for crontab * let's play spot that syntax error * only retry SMB w/o waiting if it was <1 m wait * change default curve to rapid-acting * 0.6.0-dev5 * oref0-version (#759) * oref0-version.js Check and report current oref0 version as well as check for changes on remote. * adding oref0-version * Update oref0-version.js * Add oref0-version check every hour. * Language tweaks * Revert "Add oref0-version check every hour." This reverts commit 846b0f20857c89d320f7493a9dcd2f43d8dcb3b4. * check-for-updates after each successful pump-loop * replace backticks with quotes * chmod +x * port oref0-version.js to bash to avoid nodejs compatibility issues * switch to oref0-version.sh to avoid nodejs compatibility issues * rm oref0-version.js now that oref0-version.sh works * don't display git fetch output * revised text for master * remove extra newlines to save space * timeout git fetch after 30s if it hangs * grammar * tabs to spaces * only check-for-updates once an hour, outside of pump-loop * Removing "enable" requirement for SMB - use preferences only (#748) * remove extra SMB safety gates * remove remaining references * kill bluetoothd AFTER download in case WAN access is through bluetooth (#771) * Sensitivity and targets (#757) * replace autosens_adjust_targets with more detailed preferences * split autosens_adjust_targets to sensitivity_raises_target and resistance_lowers_target * add low_temptarget_lowers_sensitivity support * update comments to be correct * make high-temptarget added deviations half as strong * store/upload sensitivityRatio * adjust CSF for temptarget sensitivityRatio, but not for autosens * let 105-110 temp target trigger exercise mode * oref0-autosens-loop (#767) * refactor oref0-online to use functions * start_hotspot if no connectivity; stop_hotspot if online via BT * refactor one more check_ip * pass MACs to function * pass MACs to function * pass MACs to function * stop/start backwards * check if hostapd is running before stop/start * stop_hotspot if running any time we have a public IP * logic * grep -q instead of checking pid * syntax * make variables global * ifup before hostapd; systemctl daemon-reload * ifdown/ifup wlan0 in stop_hotspot * stop_hotspot when we get BT * try ifdown later * stop udhcpd before starting dnsmasq * echo * no more need for sleep * install prerequisites and configs for local-only hotspot * only do local-only hotspot if BT configured * offline webapp * check if wlan0 is still in AP mode * pass MACs to start_hotspot * make sure hostapd and dnsmasq services are running if hotspot is up * only stop hotspot if we have internet * get ns-temptargets directly, then merge with any local-temptargets * print temptarget start time * untested set-local-temptarget.js * use current time if unspecified * oref0-set-local-temptarget * oref0-append-local-temptarget * oref0-append-local-temptarget * regenerate profile after refreshing temptargets * regenerate profile after merging temptargets * allow oref0-append-local-temptarget.sh to run oref0-set-local-temptarget * parse inputs as integers * remove spurious output * delete any local-temptarget files last modified more than 24h ago * make offline_hotspot a preference, false by default * per #716 it'd be better for xDrip to keep BT connected when offline * if no wifi and no BT, try cycling wlan0 * make sure all apt-get packages are up to date * Optimize oref0-ns-loop.sh (#739) * don't get_ns_bg if fresh; only run every 5m if highload * fix glucose fresh check * json is slow: just check file age * use oref0_glucose_since directly; only get 24h of glucose every hour * syntax * use nightscout carb_history directly * set mtime of ns-glucose.json based on its last reading * write profile.json.new and validate before mv'ing * don't trust awk exit status * cd to ~/myopenaps for oref0-online to read preferences.json * Create linux-bootup.sh Instructions for /etc/rc.local startup * Update oref0-setup.sh Stop automatic startup of hostapd & dnsmasq * Update oref0-setup.sh add linux-bootup.sh to /etc/rc.local * Update linux-bootup.sh check to see if .conf actually exists before overwriting with an empty file. * Update oref0-setup.sh Edit /etc/hostapd/hostapd.conf for Hostname and wpa * Update package.json add linux-bootup.sh * Delete linux-bootup.sh bad idea * Update package.json removed bad idea * Update oref0-setup.sh removed bad idea and writing to rc.local directly * Update oref0-setup.sh change hotspot name * Update oref0-setup.sh add wpa security for Hotspot with #OpenAPS * Update oref0-setup.sh add logic to rc.local * Update hostapd.conf add security to hotspot * Update oref0-setup.sh Changes for Hotspot setup * Update oref0-setup.sh change to setup for local-only hotspot * Update oref0-setup.sh changes for the different type of wpa-roam or wpa-conf * reverse logic so failure = not enabled * remove HostAPDIP if still configured after stop_hotspot * Update oref0-online.sh Changes to improve oref0-online * Update oref0-setup.sh changes to cron * syntax * if online via BT, cycle wlan0 * check for interfaces.ap; stop_hotspot if not enabled * reorder to always stop_hotspot if not enabled * don't release hotspot IP; reorder to stop_hotspot w/o BT MAC * add /tmp/disable_hotspot support * grammar capitalization etc. * logic * don't wait for 47 years if clock is mismatched * mv offline folder to www so it doesn't conflict with branch name * only release the wifi IP/route if it's from DHCP * whitepace * print Connected to Bluetooth with IP: * consistency * display wifi is not connected if no SSID * whitepace * consistency * whitepace * consistency * whitepace * print unassigned if no * reorder and print local wifi/BT IPs separately * syntax * print name of phone we're connected to with Bluetooth * only run check_ip once * print start/finish times * don't try to dhcp_renew when running hostapd * print when PUBLIC_IP not found * fix return code * don't renew wlan0 IP/route if it's failing * logging * syntax * don't wifi_dhcp_renew if bad_wifi * f we can't connect via BT, might as well try previously bad wifi networks again * remove extra -HotSpot from SSID * disconnect bnep0 even w/o an IP * temporarily disable hotspot for 1m every hour to allow it to try to connect via wifi again * download carbhistory to carbhistory.json.new and mv it over if valid * egrep quietly * download ns-temptargets to .new and mv it over if valid * oref0-autosens-loop * log why we're running autosens twice * oref0-autosens-loop * Add a note with the latest calculated IOB after boluses. (#770) This is useful when multiple small micro boluses are being administered. The notes will be visible in the pushover notifications from nightscout. * Disable wide_bg_target_range by default (#768) * make wide_bg_target_range: false by default * log target range when using wide_bg_target_range * syntax * Update openaps-install.sh (#778) Add ntpdate * Fix oref0-autotune-recommends-report for DST (#779) * Build time_list array without using 'date' so it works with DST * leading zeros * only display API_SECRET not set warning if autotune fails (#774) * set >30m zero temps when needed for low minGuardBG (#783) * Optimize oref0-pump-loop, and bug fixes (#772) * standardize on openaps report invoke * not-yet-tested refactoring of monitor-pump, meal.json, etc. * more refactoring for speed * redirect output to the right files * don't display full traceback on time set errors * only run refresh_ commands if we don't have new glucose data yet * remove end-of-line whitespace * update pump_loop_completed before glucose-fresh checks * reset pump clock if >55s off; better error messaging * syntax * nest ifs so we quit immediately if fresh * hide red-herring 'date: invalid date ‘@’' message * don't redirect oref0-meal stderr to meal.json * more accurate log message * show monitor/status.json if it's bolusing * allow bolus and bolus wizard timestamps to differ by 1 second * boluswizard uses current.carb_input not current.carbs * warn if Treatment carbs unclassified * profile.A52_risk_enable variable reference * don't wait_for_bg after a Warning * replace () with { ;} * use try and retry functions * retry basal_profile.json pull if it fails * Couldn't * curly braces and clearer error * syntax * exclude .pyc files from git * lots more try, move suspended check to fail function * log when Reducing insulinReq for expectedDelta * try inside smb_suggest * grammar * wait_for_bg if too old; clarify error messages * not sure how that got removed * touch pump_loop_completed to wait for a new BG * newlines * check that profile has a valid current_basal * differentiate things we can continue from if they fail * "grep: enact/smb-suggested.json: No such file or directory" is not useful * rename refresh_pumphistory_and_meal for error clarity * continuing * "grep: enact/smb-suggested.json: No such file or directory" is not useful * install ntpdate * only show reason too old if it's recent * make sure status.json is fresh before checking if it says pump is suspended * use try_return to more clearly log when ESC or bolus fails * move calculate_iob into merge_pumphistory as it requires pumphistory-merged.json * syntax * 0.6.0-dev6 * if insulinReq > 0 but not enough for a microBolus, don't set an SMB zero temp (#786) * Add some missing units conversion in reason field. Some unit conversion were missing in the reason field, addede them. Also changed some of the console messages. * Add Carb ratio to reason field. This is useful as it allows to clearly see that what is really used for the calculation, and might avoid incorrectly thinking that the pump settings are used when autotune is active. * only add extra negative deviations if exercise mode is set (#790) * don't reduce insulinReq for expectedDelta (we have minGuardBG for that) (#793) * log when Reducing insulinReq for expectedDelta * don't reduce insulinReq for expectedDelta (we have minGuardBG for that now) * comment out tests for behavior being removed * run autotune 4am-4am instead of midnight-midnight (#794) * run autotune 4am-4am * run autotune at 4am instead of midnight * gzip old autotune json and log files to save space (#792) * gzip old autotune json and log files to save space * force gzip to overwrite if necessary * figure out how to not gzip the log we're currently writing to * only gzip autotune log files more than 2 days old * *** WARNING *** DO NOT USE enableSMB_always or enableSMB_after_carbs with xDrip+, Libre, or similar (#690) * Restore 512/712 support (#775) * standardize on openaps report invoke * not-yet-tested refactoring of monitor-pump, meal.json, etc. * more refactoring for speed * redirect output to the right files * don't display full traceback on time set errors * only run refresh_ commands if we don't have new glucose data yet * remove end-of-line whitespace * update pump_loop_completed before glucose-fresh checks * nest ifs so we quit immediately if fresh * hide red-herring 'date: invalid date ‘@’' message * don't redirect oref0-meal stderr to meal.json * more accurate log message * show monitor/status.json if it's bolusing * allow bolus and bolus wizard timestamps to differ by 1 second * boluswizard uses current.carb_input not current.carbs * warn if Treatment carbs unclassified * profile.A52_risk_enable variable reference * don't wait_for_bg after a Warning * don't run 512-incompatible currenttemp check w/o microBolusAllowed * run old_main for 512/712 pumps * fail preflight and quit main() if we detect an x12 pump * use die instead of fail to prevent mmtuning on x12 pumps * update openaps-install for Pi (#791) * make openaps-install work for Pi * more pi stuff * python-software-properties is now software-properties-common * use openaps-packages.sh * require a NS site when running interactively * ask for NS URL even if NIGHTSCOUT_HOST env var is set * clarify that tokenauth has to already be set up in NS * enumerate CGM options in detail * explain first, then use short prompts * require/reprompt for SN and API_SECRET * Cancel high temps and shorten long zero temps when we lose CGM data (#796) * put too-old-BG stuff together * move BG too old check in with CGM error checks; shorten long zero temps * use 12m for old BG threshold instead of 10m * 0.6.0-rc1 * merged pi-install to dev * oref0-pump-loop logging improvements (#800) * print when Retrying a command * remove duplicate old function monitor_pump * don't print traceback when Couldn't refresh pumpprofile * stringify status.json * wait 15-30s for boluses to finish * Fix "A52_risk_enable is not defined" error (#805) * only try to get bnep0 IP if bt-pan succeeds (#803) * only try to get bnep0 IP id bt-pan succeeds * disable_hotspot every 20m to check for wifi * if suggested temp is more than 20m shorter, enact it (#804) * Delete profile.carbratio_adjustmentratio (#798) This parameter is dangerous when used with autotune and doesn't have the expected or described results. Remove for now. (Docs will also need to be adjusted) * retry bad_wifi after an hour (#806) * print when Retrying a command * remove duplicate old function monitor_pump * don't print traceback when Couldn't refresh pumpprofile * stringify status.json * wait 15-30s for boluses to finish * install bash-completion * retry bad_wifi after an hour * fix logic error in maxDelta (#807) * fix basal schedule error checking (#808) * validate pumpprofile.json.new before using * fix current_basal check * don't print filename * show the right file * 0.6.0-rc2 * Convert threshold where appropriate in logging output (#811) * log-smb-disabled * require boolean true on enableSMB preferences (#812) * add MDT to oref0-ns-loop * add MDT to oref0-ns-loop * add logging data * Fix log error * 0.6.0 * 0.6.1-dev * don't re-install if we already have 0.6.1 * Check OREF0_SRC env for source code location. Check for being behind upstream. Only warn if repo is ahead of local (not local ahead of remote) (#822) * fix whitespace (convert tabs to spaces) and log messages * test small commit * js cleanup start changed splice/pop to array element cleaned up ns-status * splice pop format * changed var declaration * oref0-version fetch upstream (#825) * Check OREF0_SRC env for source code location. Check for being behind upstream. Only warn if repo is ahead of local (not local ahead of remote) * Need to actually git fetch upstream * Update oref0-version.sh Clarify error message * Process the Meal marker event from medtronic pump (#832) * Process the Meal marker event from medtronic pump (#810) * Changes * Process Meal Markers from pump * Undo changes * tabs to spaces to fix indentation * return journalCarbs * copy-pasta fix * indentation * Improve the oref0-pump-loop debuging options by adding a debug flag. (#826) * Improve the oref0-pump-loop debuginng options by adding a debug flag. * Grammar * commenting out unused and incorrect prepped_glucose code (#828) * commenting out unused and incorrect prepped_glucose code * remove second (yet) for consistency * remove second (yet) for consistency * not above means <= * use pumpbasalprofile for autotune IOB calculations (#818) * abort setup if we can't install bc etc. (#835) * Basal record search (#834) * Basal record search (#819) * Changes * Search through pump history for basal duration records * undoing some changes * Missed variable rename * Attempt to fix failing tests, they're referring to 'date' not 'timestamp' * loop over all of pumpHistory to find matching TempBasalDuration if it's not adjacent * fix whitespace (tabs and trailing spaces) * also edit settings.json and bg_targets_raw.json during setup (#815) * Simple Remote Access Scripts (#817) regenerate-index.sh creates a new file index.html every time it is run. This contains simple html formatting with example data for now (intent is to add additional parameter-value pairs for display after approval of proof of concept). setup-http.sh is intended to be called from oref0-setup.sh and adds cron entries to start SimpleHTTPServer at reboot and run regenerate-index.sh periodically. Both files should be in ~/myopenaps/enact directory. From a browser on any device, browse to http://[RIG_IP_ADDRESS]/index.html and the page will self-refresh periodically. * only calculate UAM deviations for the last ~30m (#829) * Fix typo in setup script for 512 files (#861) * Fix typo in setup script for 512 files Script currently saves 'bg_targets_raw.json' as 'bg_targets_raw.json,' Remove the errant comma at the end of the output file name. * Fix the other one too * don't require enableSMB to enableUAM (#831) * oref0-setup Explorer HAT support (#830) * ask about Explorer Board HAT * install explorer-hat branch of spi-serial for spidev0.0 * merged pi-install to dev * pi user * switch to decocare-clean * enable spidev ports on the Pi * try using packaged bluez with Rapsbian * force apt to use IPv4 for now * set bluetoothdminversion=5.43 to use packaged bluez with Rapsbian * Revert "switch to decocare-clean" This reverts commit 77dbd8a020534e30619c52316be836296832e190. * switch to oref0/master for bin/openaps-packages.sh * only use splitHistory internally: return un-split tempHistory (#836) * fix Edison batteryVoltage (#837) * refresh edison batteryVoltage * don't rely on openaps battery-status alias * don't require Explorer Board to use EdisonVoltage * Allow Custom OPENAPS_DIR (#858) * Allow Custom OPENAPS_DIR * Fixed the dev oref0-pump-loop script to drop x12-incompaitble reports… (#862) * Fixed the dev oref0-pump-loop script to drop x12-incompaitble reports IF an x12 pump is detected In previous versions of oref0, this action was done by manually implementing an alias-change (as documented in past versions of the oref0 code). Since the code here is not done via an alias anymore, but rather spelled out in the script, an if/then/else block is required to remove the offending reports when an incompatible pump is detected. Tested and verified against my 712. * Update oref0-pump-loop.sh Added -q to grep, we don't need to re-print the model num * Restore newline before comment. * Serve offline web page with flask (#843) * Automate the steps to install flask as a service (#839) Automate the steps to install flask as a service so can monitoring your rig OFFLINE with an Offline web page IPHONE USERS To access this from an iphone browser, enter something like the following: http://172.20.10:5000 ex : http://IP_address__rig:5000 * use port 8080 for flask to avoid conflicts * add meta refresh and title * should we add a flask.log? (#850) * added check for custom OPENAPSDIR enviornment var (#851) * added check for custom OPENAPSDIR enviornment var * change environment variable to OPENAPS_DIR * limit SMB zero temps to 60m (#844) * New monitoring page on port 80 (#863) * Automate the steps to install flask as a service Automate the steps to install flask as a service so can monitoring your rig OFFLINE with an Offline web page IPHONE USERS To access this from an iphone browser, enter something like the following: http://172.20.10:5000 ex : http://IP_address__rig:5000 * Automate the steps to install flask as a service (#839) Automate the steps to install flask as a service so can monitoring your rig OFFLINE with an Offline web page IPHONE USERS To access this from an iphone browser, enter something like the following: http://172.20.10:5000 ex : http://IP_address__rig:5000 * use port 8080 for flask to avoid conflicts * add meta refresh and title * Change the port of offline webpage to 5001 * Create new webpage offline to monitoring the rig. Change the port of FLASK to port 80. * Create new webpage offline to monitoring the rig. Change the port of FLASK to port 80. * should we add a flask.log? (#850) * added check for custom OPENAPSDIR enviornment var (#851) * added check for custom OPENAPSDIR enviornment var * change environment variable to OPENAPS_DIR * convert tabs to spaces * show Sensitivity Ratio in topbox instead of BASAL T * Add indexError.html to handle JSON Value error (#848) * do #849 manually * clearer error message * allow smartphones to zoom out to see the whole page un-scrunched * catch IOErrors too * make BG black * improve column layout * display 4h past and future * use suggested predBGs, not enacted * display Temp Targets * calculate and display BG delta * syntax * print BG delta correctly * shorter chart forecast legends * 70% scale; units * more readability improvements * Cancel temp on error and > 55m w/ skip_netural_temps (#842) * whitespace cleanup * don't ignore temp cancel requests * cancel temp on error rather than setting neutral * with skip_neutral_temps, cancel non-zero temps before the top of the hour * move cancel-temp logic outside of eventualBG < min_bg * smb_enact_temp if a 0 duration temp is requested * ignore lastTemp/currenttemp mismatches if we have <10m old lastTemp data * if currenttemp.duration is zero because temp is canceled it won't match lastTemp * Update oref0-ns-loop.sh (#870) Seems to fix issue #868 - fixes uploading with oref0-ns-loop on Pi * Better error message for self-resolving error on bad pump reads (#871) * raise BG target for noisy / raw CGM data (#833) * use raw_safety_multiplier=0.75 instead of max_raw * disable SMB on really big jumps for safety * raise SMB-disable threshold to delta > 15% of bg * 15% is too low * re-enable max_raw (applied after raw_safety_multiplier adjustment) * round insulinReq down to nearest 0.1U to safely allow eSMB on small basals * Treat xDrip noise >= 3 similar to Dexcom showing ??? * neutral temp only for bg <= 10 || bg == 38 * Propagate the noise field. (#820) Propagate the noise field of glucose data so it can be used by determine_basal. * define vars * pass noise to determine-basal; adjust target instead of BG * let's merge #735 instead * raw=noise; raise target 1.3x for noise; adjust maxraw accordingly * rename rawTargetMultiplier to noisyCGMTargetMultiplier * update unit tests * check noise and cancel/shorten temps if needed * fix test * comment out broken CURL_AUTH API_SECRET line (#838) * always enable autosens-loop (#841) * Display seconds in SMB wait time (#846) * Display seconds in SMB wait * Fix regex and indentation * Ignore records with 0 sgv (#865) * Display RMS deviation in autosens (#867) It can be difficult to evaluate whether changes to less-intuitive settings changes like insulin peak time/DIA are likely to be helpful. By calculating RMS deviation in autosens we have a metric measuring how well the current settings are predicting observed values. A change reducing RMS error will likely improve results and a change increasing RMS error will likely be unhelpful. * Allow Custom OPENAPS_DIR (#859) * Automate the steps to install flask as a service (#839) Automate the steps to install flask as a service so can monitoring your rig OFFLINE with an Offline web page IPHONE USERS To access this from an iphone browser, enter something like the following: http://172.20.10:5000 ex : http://IP_address__rig:5000 * use port 8080 for flask to avoid conflicts * add meta refresh and title * Allow Custom OPENAPS_DIR * Simplify environment variable check * use curly brackets consistently * removed merge indicators * fix direction calculation for negative trending (#885) * Speed up autotune and make it work in NS (#872) * declare vars * convert all lib references to relative for NS autotune compatibility * trim down IOBInputs.history to just the data for 6h prior to BGDate Conflicts: lib/autotune-prep/categorize.js * remove commented unused code * comment out some process.stderr.write * Autotune: avoid raising basals from UAM (#875) * exclude >6mg/dL deviations as UAM; only add lowest 50% of UAM deviations to basals * trim down IOBInputs.history to just the data for 6h prior to BGDate * remove commented unused code * remove duplicate function definitions (#892) * run bg_targets.json after bg_targets_raw.json * Upgrade bluez to 5.48, start bluetoothd if it's not running, remove experimental (#876) * - bugfix: also start bluetoothd in oref0-bluetoothup if it's not running - upgrade bluez to 5.48, changelog http://www.bluez.org/release-of-bluez-5-48/ - remove --experimental (finally) on bluetoothd startup and change it in /etc/rc.local if it's still there * fix grep statement * Explorer hat auto install (#897) * Update oref0-setup.sh * Update oref0-setup.sh * Update oref0-setup.sh * moving installer and code cleanup * Update oref0-setup.sh * indentation * auto-detect Explorer HAT * only generate edison-battery.json on edisons * support openaps-menu/scripts/getvoltage.sh * Remove external repo (#898) * grep quietly * Update logrotate.rsyslog (#901) * apt-get update, upgrade, and autoclean * re-do timerun stuff against dev (#896) * allow pumphistory pull to take 90s (for pi0w) * don't start oref0-pump-loop every 30s (#893) * Fixed autotune_isf_adjustmentFraction. (#905) * proceed to add battery-status if it doesn't exist yet * do not produce errors when iob_data.lastTemp doesn't exist (#883) * Pushover Priority to Urgent (#873) * Pushover Priority to Urgent Set Pushover Priority to urgent to ensure user sees the message. * Updated to provide pushover preferences Added preferences to allow user to configure pushover alerts' sound, priority, snooze, and only for options. * Date error with MDT CGM (#845) * Use proper date field in glucose-fresh for MDT CGM data * Fix Typo ($ to &) * In glucose-fresh Use display_time if present, otherwise use date * Forgot the filename in bin/oref0-pump-loop change * Format Autotune Output Profile (#900) * Format autotune output when copying it to settings. * Replaced json command calls with equivalent jq command calls. * Placed autotune profile format in a better place. * Added jq . -M back in for the grep for start command. * Reverted the cat with a redirect back to a cp command. * Removed unnecessary -M option to jq. * Format new autotune profile with json-stable-stringify so it is consistently arranged from one day to the next. * Autotune Command Line Option to Classify UAM as Basal (#904) * Added optional flag to oref0-autotune for manually telling categorize to include all of the UAM periods as basals. This is essentially telling autotune that the user faithfully entered all of the carb intakes for the time being processed. * Handled variable arguments better. * Prioritize categorize_uam_as_basal flag over the too many deviations categorizes as UAM check. * Offline monitoring page to show in mmol (#891) * Offline monitoring page to show in mmol * tabs to spaces * Fixed time zone problem. (#910) * Opened lsgaps time window from 5 to 6 to account for small variations (#915) greater than 5 minutes with G5 and xdrip-js. * print enact/smb-suggested.json if deliverAt check fails (#895) * Pushover glances (#856) * Adding watch complications - glances to pushover Pushover has a new powerful glances API that sends complications to an apple watch or small bits of data to a smart watch face. More information at the following web page: https://pushover.net/api/glances This change enhances the pushover notification script to optionally send information to the pushover glances API for watch face updates once every 10 minutes. It works well for apple watch complications. It has not yet been tested for android wear watchface updates yet. Note that apple limits the daily total number of complication updates to save watch battery, so we cannot update this glance data more often than every 10 minutes today. * Update oref0-pushover.sh * refactor for simplicity performance plus ifttt Refactored for simplicity and performance to just read from enact/smb-suggested.json Also, added another optional notification that will send an ifttt maker event "carbs-required" if additional carbs are required and if environment variable "MAKER_KEY" is set. This is the ifttt webhooks Maker key https://ifttt.com/maker_webhooks The "carbs-required" event can then be used with a ifttt recipe to perform an action based on carbs required. A good use case is to use the ifttt phone action to get a phone call with this event that will read out in human language the additional carbs and other vital facts. It will leave a voice mail if not answered * fix cut-n-paste error * fix bug with delta & tick to remove + * only use suggested.json - not smb-suggested.json * fixed problem with delta comparisons * fix delta comparisons * Language tweaks * exit if enact > 5 mins for safety and mult rigs * refactored to use glucose.json trend values * cut-n-paste error fixes I don't think cut-n-paste works in the github editor. Somehow it put 4 copies of my one code change throughout the file. I cleaned that up. * removed quotes from lastDirection value * fix syntax error * carbs-required repeat changed from 15 to 60 min Changed the carbs-required repeat check to send this maker notification no more than once per every 60 minutes. By that time, the user should have eaten and logged some carbs. IFTTT limits phone call triggers to 100 per month. * set positive deviations to zero if BG is below 80 (#902) * set positive deviations to zero if BG is below 80 (#903) * Fix iob calculation error (#878) * Fixed the calculation error where different DIAs are used when user has pump set to a value lower than 5 hours. * Fixed to use adjusted dia value instead of original profile setting. * Reordered calcIOB arguments. * Added explanatory comment. * Added unit test to ensure 5 hour minimum DIA is being correctly enforced for rapid acting insulin. * Fixed logic to move IOB test after profile DIA. * Enable IOB calc to recognize suspends (#879) * Added initial code to collect suspend and resume events. * Initial implementation of treating suspends as zero basals. * Added duration assignments back. * Declared splitEvents variable and removed some debug. * Used a similar structure to split suspends as with basals. * Made some whitespace match previous version. * Fixed call to splitAroundSuspends that was missing an argument. * Added profile setting to enable new feature. * Fixed incorrect comment description * Fixed logic error for when there were no suspends or resumes in the history. * Added test for iobcalc accounting for pump suspends. * Added a couple of new tests for pump suspend interaction. Split the test into multiple "it should.." test. * Added a note for an additional test that needs to be written * Modified code to add zero temps while pump is suspended. Modified test to account for corrected logic of zero temping while pump is suspended. Added remaining test. * Cleaned up some comments. * Clarified a comment. * Updated a comment. * #884: default remainingCATime to remainingCATimeMin if meal_data.carbs == 0 (#916) * Fix suspend zeros iob preference (#918) * Fixed suspend_zeros_iob preference. * Fixed preference name. * remove old commented code and corresponding usage entry * Fix a href (#926) * Changed suspend_zeros_iob default to true. (#922) * Fix handling of dates so that we are not comparing the time the pump-… (#924) * Fix handling of dates so that we are not comparing the time the pump-clock *was* set to, to the time it is when the test executes. Also, fix set-device-clocks so that it doesn't try and set the 'clock' on xdrip CGM. Reset author on new device. * Update oref0-pump-loop.sh * Update oref0-pump-loop.sh * Consistent use of `$HOME` instead of `~`. Make it possible to install oref0 in another directory than `myopenaps` and make it possible to start it from any directory (#886) * oref0-setup.sh installed myopenaps in the current directory instead of using $HOME/myopenaps also found missing instance where hardcoded ~/myopenaps was still used * use $HOME/ instead of ~/ * syntax fixes * Revert "syntax fixes" This reverts commit 3ff3b6c99efadff71b55c83aedf700e9cc1164c0. * Revert "Fix handling of dates so that we are not comparing the time the pump-… (#924)" This reverts commit 254757b7614cf977539594722ddba0d0e2b24db9. * Update oref0-setup.sh for the edgecase of failed wget (#909) * Update oref0-setup.sh remove existing `bluez-5.48.tar.gz` in case of failed wget so subsequent commands run. * Update oref0-setup.sh * Update oref0-setup.sh * Generate settings/bg_targets.json for x12 models (#920) settings/bg_targets.json is generated from settings/bg_targets_raw.json, adding the user-preferred units, and pulls no data from the pump. * Update offline monitoring page (#923) * Offline monitoring page to show in mmol * tabs to spaces * offline monitoring page * Read BG data till out of date range for chart * center data in BG pill * various fixes, move to all ajax calls * refactor calculate.js (#931) * remove error function (never used) from code * parallel coefficient order and precision * remove variable that is never used * remove references to biobContrib * remove incorrect comment * remove timeRef variable * remove unnecessary comment * parallel results syntax * improve readability of bilinear formulas * line spacing * round time since bolus for bilinear, similar to exponential calcs * rename vars, add comments * move function * remove unnecessary condition in iobCalcBilinear * create iobCalcExponential function * delete some blank lines * more line spacing tweaks * change td to end in exponential function * change tp to peak in exponential function * reverse logic for using custom peak time * calc minutes since bolus outside bilinear and exponential functions * reverse activityContrib and iobContrib vars * change 60*3 to end in bilinear function * flip logic for treatment.insulin condition * whoops. left a return statment in there. * reverse order of functions in file * set default dia, peak, and end as constants; add comments * comments and source for exponential formula * another comment * iobCalcBiLinear to iobCalcBilinear * delete line break in comment * parentheses for clarity * peak then end * Comments * comment tweaks * comments and more intuitive calcs for activityContrib in iobCalcBilinear function * narrow variable scope in iobCalcExponential * 35 and 120, inclusive * revert let back to var * Fix date routine, corrected/operational (#933) * Fix handling of dates so that we are not comparing the time the pump-clock *was* set to, to the time it is when the test executes. Also, fix set-device-clocks so that it doesn't try and set the 'clock' on xdrip CGM. Reset author on new device. * Update oref0-pump-loop.sh * Update oref0-pump-loop.sh * Update oref0-pump-loop.sh * Update oref0-pump-loop.sh * Fix syntax errors & unhandled errors in prior date-routine fix * Update oref0-pump-loop.sh * Update oref0-pump-loop.sh * only kill bluetoothd on edison * Revert "Fix date routine, corrected/operational (#933)" This reverts commit 5f29a885265d51fd2f6e17855dab84d5eff40090. * Don't loop on "stuck" CGM data (#942) * don't loop on 'stuck' CGM data * add reason field; fix var * make sure at least one avgdelta is non-zero * offline monitor - use xdrip bg data if more recent than monitor (#947) * Slightly refactor oref0 meal to read all the data before (#954) * Slightly refactor oref0 meal to read all the data before trying to match bolus wizard entries to corresponding bolus entries. This allows out of order bolus and bolus wizard entries to still work correctly. Before this change, when the bolus entry was after the bolusWizard entry, the carb was being skipped because no corresponding bolus was seen. * BolusWizard with matching bolus entry following it should not bet skipped. * eleborate "skipping bolus wizard entry" information (cherry picked from commit f628f49c11954d3672d7846e12b392b96cf1fd56) * remove extra spaces (cherry picked from commit eff86b5f55900bce428ee8b54480331e5cbca670) * one more space removed (cherry picked from commit fbcd8f23d65e071fb39c27671d19d7e6c7f94264) * Fix log rotate for those who don't use boostrap * Fix log rotate (dev PR) (#963) * Fix a href (#926) * Fix log rotate for those who don't use boostrap * rigs start at weekly by default * Change comment * backport carelink support by supressing mmtune execution (#964) * Support for x12 models in main() (#948) * Initial commit for x12 support in main() Deprecates old_main() and old functions that use it. Adds support for x12 pumps in smb loop (without using SMBs). ***Not tested.*** * Allow x12 models to use SMB loop * Remove redundant check and quiet grep * Readability Adds parentheses to x12 SMB warning. * Log clarity Changes based on comments in #948 * Fix log rotate for those who don't use boostrap (#962) * Change nano to vi for edit-wifi shortcut * Remove update_config=1 from bootstrap script * re-apply 7051259fc2fdb2fc3434f8c3a5d19130c01f8fba * avoid filling logs with DIA warning, since we override to 5h now anyway (#976) * Try three times to get a Bluetooth IP address When my phone is in and out of service several times in as many minutes (between subway stations, for example) it doesn't assign an IP address to the device when it tries to connect via Bluetooth. Once back in a more stable environment it takes a while before it tries to get on the Internet via Bluetooth again. This change, tested over several weeks, significantly reduces the time offline during and after using the subway. * Fix typo in filename of /tmp/autosens-completed (#990) Fix a typo that would cause completed_recently in oref0-autosens-loop.sh to always be false. This effectively disabled a feature that was supposed to make autosens recalculation happen less frequently when under high load. * Revert change (#991) Revert the outcome of this test to its original behavior. * don't error when HAT file doesn't exist * autoconfirm apt-get Add -y flags to the rest of the apt-get commands to bypass y/n prompts. * Don't error when HAT file doesn't exist (#993) Same issue as last, different location. * fix improper revert * if targets are < 20, assume for safety that they're intended to be mmol/L (#995) * make maxUAMSMBBasalMinutes a preference (#974) * Change invalid-IOB-curve behavor to match message (#1003) * 0.6.1 * tabs to spaces * add sgv.json?count=# route (#1001) * add sgv.json?count=# route support similar to xdrip+, for offline use with watchfaces, etc. * add units_hint to sgv.json * Trying to update the 'clock' on xdripaps causes an un-needed loop fail (#1002) Stop trying to set-device-clocks for CGM on xdripaps installs. When this command is executed, it results in a loop failure due to 'failure' to set the pump clock. Fixed by looking for the xdrip.ini file & skipping the CGM clock update if it is found. * Removing old to-do that's been taken care of * Remove seemingly unused comments * Add radio_type=carelink in pump.ini for carelink installs * Update index.js (#1012) * Update index.js Fix to warning message indicating Xdrip+ version is handling noisy data appropriately. * clarify * Fixed currentRate calculation when using autosens. (#1019) * fix syntax error (#1023) I was getting syntax errors running `openaps-setup` and I putting this `fi` back fixed it: https://github.com/openaps/oref0/commit/f92a01ead0e5186270920b27d61d2282d178569c#diff-704a2fd9a43fd79bf52037b1668c146d * adding duty cycle feature for carelink + mdt users (#1025) * adding duty cycle feature for carelink + mdt users * replace tab with 4 space * minor tweaks, mostly for clarity * update xDrip+ enableSMB warnings (#1017) * Update index.js Fix to warning message indicating Xdrip+ version is handling noisy data appropriately. * clarify * remove trailing spaces * remove trailing spaces * remove trailing spaces * Revert "Removing old to-do that's been taken care of" This reverts commit f92a01ead0e5186270920b27d61d2282d178569c. Conflicts: bin/oref0-setup.sh * only check_duty_cycle if "$DUTY_CYCLE" -gt "0" * xdrip.ini always exists: check for xdrip/ dir instead * Install MRAA on all kernel versions if it is needed. (#1015) * 0.6.2-dev * Adding links to documentation, and creating drop-down for readability * Fixing link to modern docs, and recommending others ways to contribute * Re-run apt-get update after dist-upgrade (#1034) Fixes an issue where openaps-install.sh cannot find packages on the pi after running a dist-upgrade. * rework release-master.sh * 0.6.2 * Update openaps-packages.sh (#1054) The latest node-js for raspbian deprecates the use of nodejs-legacy, which breaks this script on new pi installs. This will make it so that nodejs-legacy is only installed on the edison. * Update issue templates * Update issue templates * Update issue templates * Update issue templates * Update issue templates * Remove duplicate * Remove duplicate * Remove duplicate * Update --individual-troubleshooting-help.md --- .github/ISSUE_TEMPLATE/--bug-report.md | 32 + .github/ISSUE_TEMPLATE/--feature-request--.md | 17 + .../--individual-troubleshooting-help.md | 9 + .gitignore | 5 + .travis.yml | 2 +- CONTRIBUTING.md | 20 +- Makefile | 17 +- README.md | 35 +- bin/bt-pan | 228 + bin/mm-format-ns-glucose.sh | 27 +- bin/mm-format-ns-profile.sh | 25 +- bin/mm-format-ns-pump-history.sh | 25 +- bin/mm-format-ns-treatments.sh | 28 +- bin/mm-format-oref0-glucose.sh | 16 +- bin/mm-stick.sh | 2 +- bin/monitor-xdrip.sh | 13 + bin/nightscout.sh | 323 +- bin/ns-dedupe-treatments.sh | 10 +- bin/ns-get.sh | 55 +- bin/ns-status.js | 149 +- bin/ns-upload-entries.sh | 36 +- bin/ns-upload.sh | 46 +- bin/ns-uploader-setup.sh | 134 - bin/openaps-bootstrap.sh | 34 + bin/openaps-install.sh | 50 + bin/openaps-packages.sh | 16 + bin/openaps-src.sh | 44 + bin/oref0-append-local-temptarget.sh | 15 + bin/oref0-autosens-loop.sh | 57 + bin/oref0-autotune-core.js | 63 + bin/oref0-autotune-dayofweek.sh | 25 + bin/oref0-autotune-export-to-xlsx.py | 191 + bin/oref0-autotune-prep.js | 113 + bin/oref0-autotune-recommends-report.sh | 120 + bin/oref0-autotune.py | 252 + bin/oref0-autotune.sh | 271 + bin/oref0-bluetoothup.sh | 20 + bin/oref0-calculate-iob.js | 28 +- bin/oref0-conditional-run.sh | 38 + bin/oref0-copy-fresher | 37 + bin/oref0-delete-future-entries.sh | 22 + bin/oref0-detect-sensitivity.js | 172 + bin/oref0-determine-basal.js | 224 +- bin/oref0-dex-is-fresh.sh | 15 + bin/oref0-dex-time-since.sh | 6 + bin/oref0-dex-wait-until-expected.sh | 24 + bin/oref0-dexusb-cgm-loop.py | 167 + bin/oref0-find-insulin-uses.js | 15 +- bin/oref0-fix-git-corruption.sh | 79 + bin/oref0-get-profile.js | 214 +- bin/oref0-html.js | 181 + bin/oref0-ifttt-notify | 6 +- bin/oref0-log-shortcuts.sh | 32 + bin/oref0-mdt-trend.js | 129 + bin/oref0-meal.js | 107 + bin/oref0-mint-max-iob.sh | 44 - bin/oref0-normalize-temps.js | 17 +- bin/oref0-ns-loop.sh | 213 + bin/oref0-online.sh | 252 + bin/oref0-pebble.js | 59 +- bin/oref0-pump-loop.sh | 824 + bin/oref0-pushover.sh | 191 + bin/oref0-radio-reboot.sh | 25 + bin/oref0-raw.js | 62 + bin/oref0-reset-git.sh | 48 +- bin/oref0-reset-usb.sh | 20 +- ...clockset.sh => oref0-set-device-clocks.sh} | 41 +- bin/oref0-set-local-temptarget.js | 50 + bin/oref0-set-system-clock.sh | 51 + bin/oref0-setup.sh | 1129 + bin/oref0-subg-ww-radio-parameters.sh | 67 + bin/oref0-tail-log.sh | 3 + bin/oref0-tail-wifi.sh | 3 + bin/oref0-truncate-git-history.sh | 52 + bin/oref0-upload-entries.sh | 30 + bin/oref0-upload-profile.js | 280 + bin/oref0-version.sh | 48 + bin/oref0.sh | 40 +- bin/oref0_autotune_export_to_xlsx.py | 141 + bin/oref0_init_pump_comms.py | 70 + bin/oref0_nightscout_check.py | 123 + bin/oref0_subg_ww_radio_parameters.py | 123 + bin/peb-urchin-status.sh | 31 + bin/send-tempbasal-Azure.js | 76 - headless/headless.sh | 12 +- headless/hostapd.conf | 8 +- headless/install.sh | 5 +- lib/autotune-prep/categorize.js | 428 + lib/autotune-prep/dosed.js | 28 + lib/autotune-prep/index.js | 28 + lib/autotune/index.js | 463 + lib/basal-set-temp.js | 73 +- lib/bolus.js | 41 +- lib/determine-basal/autosens.js | 450 + lib/determine-basal/cob.js | 197 + lib/determine-basal/determine-basal.js | 1260 +- lib/glucose-get-last.js | 80 +- lib/iob/calculate.js | 142 +- lib/iob/history.js | 551 +- lib/iob/index.js | 83 +- lib/iob/total.js | 104 +- lib/meal/history.js | 141 + lib/meal/index.js | 24 + lib/meal/total.js | 137 + lib/oref0-setup/alias.json | 240 + lib/oref0-setup/autotune.json | 43 + lib/oref0-setup/basal_profile.json | 50 + lib/oref0-setup/bg_targets_raw.json | 30 + lib/oref0-setup/cgm-loop.json | 347 + lib/oref0-setup/device.json | 157 + lib/oref0-setup/dexcom.json | 11 + lib/oref0-setup/edisonbattery.json | 23 + lib/oref0-setup/mdt-cgm.json | 148 + lib/oref0-setup/pancreabble.json | 49 + lib/oref0-setup/pancreoptions.json | 7 + lib/oref0-setup/report.json | 393 + lib/oref0-setup/settings.json | 8 + lib/oref0-setup/shareble.json | 19 + lib/oref0-setup/supermicrobolus.json | 37 + lib/oref0-setup/vendor.json | 18 + lib/oref0-setup/xdrip-cgm.json | 41 + lib/profile/basal.js | 29 +- lib/profile/carbs.js | 41 +- lib/profile/index.js | 161 +- lib/profile/isf.js | 49 +- lib/profile/targets.js | 54 +- lib/pump.js | 11 +- lib/require-utils.js | 31 + lib/round-basal.js | 46 + lib/with-raw-glucose.js | 53 + logrotate.openaps | 2 +- logrotate.rsyslog | 10 +- package.json | 95 +- release-master.sh | 21 +- tests/basal.test.js | 36 + tests/bolus.test.js | 38 + tests/cobhistory.test.js | 44 + tests/determine-basal.test.js | 843 +- tests/get-last-glucose.test.js | 24 +- tests/iob.test.js | 1677 +- tests/profile.test.js | 115 + tests/set-temp-basal.test.js | 69 +- tests/with-raw-glucose.test.js | 59 + www/app.py | 120 + www/regenerate-index.sh | 23 + www/setup-http.sh | 2 + www/static/css/bootstrap.min.css | 7 + www/static/css/style.css | 30 + www/static/js/bootstrap.min.js | 7 + www/static/js/chart.js | 18609 ++++++++++++++++ www/static/js/direction.js | 16 + www/static/js/jquery.min.js | 4 + www/static/js/utils.js | 147 + www/templates/index.html | 768 + www/templates/indexError.html | 10 + 155 files changed, 35929 insertions(+), 1332 deletions(-) create mode 100644 .github/ISSUE_TEMPLATE/--bug-report.md create mode 100644 .github/ISSUE_TEMPLATE/--feature-request--.md create mode 100644 .github/ISSUE_TEMPLATE/--individual-troubleshooting-help.md create mode 100755 bin/bt-pan create mode 100755 bin/monitor-xdrip.sh delete mode 100755 bin/ns-uploader-setup.sh create mode 100755 bin/openaps-bootstrap.sh create mode 100755 bin/openaps-install.sh create mode 100755 bin/openaps-packages.sh create mode 100755 bin/openaps-src.sh create mode 100755 bin/oref0-append-local-temptarget.sh create mode 100755 bin/oref0-autosens-loop.sh create mode 100755 bin/oref0-autotune-core.js create mode 100755 bin/oref0-autotune-dayofweek.sh create mode 100755 bin/oref0-autotune-export-to-xlsx.py create mode 100755 bin/oref0-autotune-prep.js create mode 100755 bin/oref0-autotune-recommends-report.sh create mode 100755 bin/oref0-autotune.py create mode 100755 bin/oref0-autotune.sh create mode 100755 bin/oref0-bluetoothup.sh create mode 100755 bin/oref0-conditional-run.sh create mode 100755 bin/oref0-copy-fresher create mode 100755 bin/oref0-delete-future-entries.sh create mode 100755 bin/oref0-detect-sensitivity.js create mode 100755 bin/oref0-dex-is-fresh.sh create mode 100755 bin/oref0-dex-time-since.sh create mode 100755 bin/oref0-dex-wait-until-expected.sh create mode 100755 bin/oref0-dexusb-cgm-loop.py create mode 100755 bin/oref0-fix-git-corruption.sh create mode 100755 bin/oref0-html.js create mode 100755 bin/oref0-log-shortcuts.sh create mode 100755 bin/oref0-mdt-trend.js create mode 100755 bin/oref0-meal.js delete mode 100755 bin/oref0-mint-max-iob.sh create mode 100755 bin/oref0-ns-loop.sh create mode 100755 bin/oref0-online.sh create mode 100755 bin/oref0-pump-loop.sh create mode 100755 bin/oref0-pushover.sh create mode 100755 bin/oref0-radio-reboot.sh create mode 100755 bin/oref0-raw.js rename bin/{clockset.sh => oref0-set-device-clocks.sh} (51%) create mode 100755 bin/oref0-set-local-temptarget.js create mode 100755 bin/oref0-set-system-clock.sh create mode 100755 bin/oref0-setup.sh create mode 100755 bin/oref0-subg-ww-radio-parameters.sh create mode 100755 bin/oref0-tail-log.sh create mode 100755 bin/oref0-tail-wifi.sh create mode 100755 bin/oref0-truncate-git-history.sh create mode 100755 bin/oref0-upload-entries.sh create mode 100755 bin/oref0-upload-profile.js create mode 100755 bin/oref0-version.sh create mode 100755 bin/oref0_autotune_export_to_xlsx.py create mode 100755 bin/oref0_init_pump_comms.py create mode 100755 bin/oref0_nightscout_check.py create mode 100755 bin/oref0_subg_ww_radio_parameters.py create mode 100755 bin/peb-urchin-status.sh delete mode 100755 bin/send-tempbasal-Azure.js create mode 100644 lib/autotune-prep/categorize.js create mode 100644 lib/autotune-prep/dosed.js create mode 100644 lib/autotune-prep/index.js create mode 100644 lib/autotune/index.js create mode 100644 lib/determine-basal/autosens.js create mode 100644 lib/determine-basal/cob.js create mode 100644 lib/meal/history.js create mode 100644 lib/meal/index.js create mode 100644 lib/meal/total.js create mode 100644 lib/oref0-setup/alias.json create mode 100644 lib/oref0-setup/autotune.json create mode 100644 lib/oref0-setup/basal_profile.json create mode 100644 lib/oref0-setup/bg_targets_raw.json create mode 100644 lib/oref0-setup/cgm-loop.json create mode 100644 lib/oref0-setup/device.json create mode 100644 lib/oref0-setup/dexcom.json create mode 100644 lib/oref0-setup/edisonbattery.json create mode 100644 lib/oref0-setup/mdt-cgm.json create mode 100644 lib/oref0-setup/pancreabble.json create mode 100644 lib/oref0-setup/pancreoptions.json create mode 100644 lib/oref0-setup/report.json create mode 100644 lib/oref0-setup/settings.json create mode 100644 lib/oref0-setup/shareble.json create mode 100644 lib/oref0-setup/supermicrobolus.json create mode 100644 lib/oref0-setup/vendor.json create mode 100644 lib/oref0-setup/xdrip-cgm.json create mode 100644 lib/require-utils.js create mode 100644 lib/round-basal.js create mode 100644 lib/with-raw-glucose.js mode change 100644 => 100755 release-master.sh create mode 100644 tests/basal.test.js create mode 100644 tests/bolus.test.js create mode 100644 tests/cobhistory.test.js create mode 100644 tests/profile.test.js create mode 100644 tests/with-raw-glucose.test.js create mode 100644 www/app.py create mode 100644 www/regenerate-index.sh create mode 100644 www/setup-http.sh create mode 100644 www/static/css/bootstrap.min.css create mode 100644 www/static/css/style.css create mode 100644 www/static/js/bootstrap.min.js create mode 100644 www/static/js/chart.js create mode 100644 www/static/js/direction.js create mode 100644 www/static/js/jquery.min.js create mode 100644 www/static/js/utils.js create mode 100644 www/templates/index.html create mode 100644 www/templates/indexError.html diff --git a/.github/ISSUE_TEMPLATE/--bug-report.md b/.github/ISSUE_TEMPLATE/--bug-report.md new file mode 100644 index 000000000..13711b824 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/--bug-report.md @@ -0,0 +1,32 @@ +--- +name: "\U0001F41BBug report" +about: Create a report to help us fix things + +--- + +**Describe the bug** +A clear and concise description of what the bug is. + +**To Reproduce** +Steps to reproduce the behavior: +1. Go to '...' +2. Click on '....' +3. Scroll down to '....' +4. See error + +**Expected behavior** +A clear and concise description of what you expected to happen. + +**Screenshots** +If applicable, add screenshots to help explain your problem. + +**Smartphone (please complete the following information):** + +**Setup Information (please complete the following information):** +* Pump type (e.g. Medtronic 722, v. 2.4A firmware) +* CGM type (e.g. Dexcom G4 via xDrip+) +* Rig type (e.g. Edison/Explorer Board rig) +* oref0 version (e.g. oref0 0.6.2 master, or 0.7.0-dev) + +**Additional context** +Add any other context about the problem here. diff --git a/.github/ISSUE_TEMPLATE/--feature-request--.md b/.github/ISSUE_TEMPLATE/--feature-request--.md new file mode 100644 index 000000000..a94a261ab --- /dev/null +++ b/.github/ISSUE_TEMPLATE/--feature-request--.md @@ -0,0 +1,17 @@ +--- +name: "\U0001F4A1Feature request\U0001F4A1" +about: Suggest an idea for this project + +--- + +**Is your feature request related to a problem? Please describe.** +A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] + +**Describe the solution you'd like** +A clear and concise description of what you want to happen. + +**Describe alternatives you've considered** +A clear and concise description of any alternative solutions or features you've considered. + +**Additional context** +Add any other context or screenshots about the feature request here. diff --git a/.github/ISSUE_TEMPLATE/--individual-troubleshooting-help.md b/.github/ISSUE_TEMPLATE/--individual-troubleshooting-help.md new file mode 100644 index 000000000..ab64f15e3 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/--individual-troubleshooting-help.md @@ -0,0 +1,9 @@ +--- +name: "\U0001F198Individual troubleshooting help" +about: Getting help with your own individual setup - let's hop into Gitter at https://gitter.im/nightscout/intend-to-bolus + +--- + +Are you having an issue with your individual rig/setup? + +Please first go to Gitter (https://gitter.im/nightscout/intend-to-bolus) and post there, with details of your setup (pump/CGM/CGM data path/rig type/oref0 version) and the issue you're observing. diff --git a/.gitignore b/.gitignore index 4fcbc57e5..4638eb4bc 100644 --- a/.gitignore +++ b/.gitignore @@ -20,3 +20,8 @@ static/bower_components/ coverage/ npm-debug.log +bin/__pycache__ + +package-lock.json + +*.pyc diff --git a/.travis.yml b/.travis.yml index 65f5121d3..c296de757 100644 --- a/.travis.yml +++ b/.travis.yml @@ -3,5 +3,5 @@ sudo: false node_js: - "0.10" - "0.12" -script: make test +script: make travis after_script: make report diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 2ad2bacf1..d4706a25e 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -30,26 +30,10 @@ performance and quality of your system lies solely with you. Additionally, this community of contributors believes in "paying it forward", and individuals who are implementing these tools are asked to contribute by asking questions, helping improve documentation, and -contribute in other ways. +contribute in other ways. We always need testers for various pieces of works-in-progress; please do ask if you would like to help but aren't sure where to get started. Please submit issues and pull requests so that all users can share -knowledge. If you're unfamiliar with GitHub and/or coding, [check out these other ways to get involved with OpenAPS.](https://openaps.gitbooks.io/building-an-open-artificial-pancreas-system/content/docs/Overview/contribute.html) - -For hacking on openaps, here are some tips to help your patches reach -more people more quickly. The `master` branch is special, it should -be "production" ready code, tested and verified, and should match the -contents available in pypi. Basically that means the `master` branch -is never touched directly, but rather we use a variety of other -branches to do things, and then merge the work into the `master` -branch. Sometimes this is called -[git flow](http://nvie.com/posts/a-successful-git-branching-model/). -Here's few guidelines that might help: - - * target a `dev` branch for pull requests. The latest updated - branch, especially any recently updated branch with `dev` in the - name. - * Avoid editing `master` branch. - * test changes +knowledge. If you're unfamiliar with GitHub and/or coding, [check out these other ways to get involved with OpenAPS.](http://openaps.readthedocs.io/en/latest/docs/Give%20Back-Pay%20It%20Forward/contribute.html) See [OpenAPS.org](http://OpenAPS.org/) for background on the OpenAPS movement and project. diff --git a/Makefile b/Makefile index 21ad58f9f..339ddc79c 100644 --- a/Makefile +++ b/Makefile @@ -1,8 +1,23 @@ TESTS=tests/*.js +ISTANBUL=./node_modules/.bin/istanbul +MOCHA=./node_modules/mocha/bin/_mocha +ANALYZED=./coverage/lcov.info 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} + +report: + test -f ${ANALYZED} && \ + (npm install coveralls && cat ${ANALYZED} | \ + ./node_modules/.bin/coveralls) || echo "NO COVERAGE" + test -f ${ANALYZED} && \ + (npm install codacy-coverage && cat ${ANALYZED} | \ + YOURPACKAGE_COVERAGE=1 ./node_modules/codacy-coverage/bin/codacy-coverage.js) || echo "NO COVERAGE" + diff --git a/README.md b/README.md index c5e5aee11..8ede8f1db 100644 --- a/README.md +++ b/README.md @@ -1,18 +1,21 @@ # oref0 +Algorithm for OpenAPS implementations. To get started with OpenAPS, see the [OpenAPS documentation](http://openaps.readthedocs.org/en/latest/) -Javascript plugins for openaps - -## Installing +## Installing oref0 Install tools globally: -`sudo npm install -g oref0` +`npm run global-install` -## Usage +## Usage of oref0 ### `oref0` -The open reference implementation of the reference design. + +
+ The open reference implementation of the reference design. (click to expand for more usage details) +
+ ``` Usage: oref0 @@ -57,8 +60,6 @@ The result is suitable for sending to Nightscout's entries api, eg, using `ns-upload-entries`. ``` mm-format-ns-glucose - - ``` ### `mm-format-ns-pump-history` @@ -82,16 +83,13 @@ These can be defined in crontab, or in a simple file, eg ``` API_SECRET="..." NIGHTSCOUT_HOST=localhost:1337 ns-upload-entries - ``` -## Contributing - -See the [CONTRIBUTING document](CONTRIBUTING.md) ### Get the source ``` git clone git://github.com/openaps/oref0.git +cd oref0 git checkout dev git checkout -b wip/my-enhancement-fix-or-proposal ``` @@ -114,6 +112,11 @@ git push origin -u wip/my-enhancement-fix-or-proposal ``` Then target our `dev` branch for a pull request/peer review. +
+ +## Contributing + +See the [CONTRIBUTING document](CONTRIBUTING.md). PRs welcome! ## openaps @@ -132,11 +135,13 @@ contributors from liability. *Note:* This is intended to be a set of tools to support a self-driven DIY implementation and any person choosing to use these tools is solely responsible for testing and implement these tools independently or -together as a system. The [DIY part of OpenAPS is important] -(http://bit.ly/1NBbZtO). While formal training or experience as an +together as a system. The [DIY part of OpenAPS is important](http://bit.ly/1NBbZtO). +While formal training or experience as an engineer or a developer is not required, what *is* required is a growth mindset to learn what are essentially "building blocks" to implement an OpenAPS instance. This is not a "set and forget" system; it requires diligent and consistent testing and monitoring to ensure each piece of the system is monitoring, predicting, and performing as desired. The -performance and quality of your system lies solely with you. +performance and quality of your system lies solely with you. + +Read the [OpenAPS documentation](http://openaps.readthedocs.io/en/latest/) for more details. diff --git a/bin/bt-pan b/bin/bt-pan new file mode 100755 index 000000000..af1327d57 --- /dev/null +++ b/bin/bt-pan @@ -0,0 +1,228 @@ +#!/usr/bin/env python2 +from __future__ import absolute_import, print_function + +import os, sys, time, types, subprocess, signal + +import dbus + + +### ~bluezutils.py + +iface_base = 'org.bluez' +iface_dev = '{}.Device1'.format(iface_base) +iface_adapter = '{}.Adapter1'.format(iface_base) +iface_props = 'org.freedesktop.DBus.Properties' + +class BTError(Exception): pass + +def get_bus(): + bus = getattr(get_bus, 'cached_obj', None) + if not bus: bus = get_bus.cached_obj = dbus.SystemBus() + return bus + +def get_manager(): + manager = getattr(get_manager, 'cached_obj', None) + if not manager: + manager = get_manager.cached_obj = dbus.Interface( + get_bus().get_object(iface_base, '/'), + 'org.freedesktop.DBus.ObjectManager' ) + return manager + +def prop_get(obj, k, iface=None): + if iface is None: iface = obj.dbus_interface + return obj.Get(iface, k, dbus_interface=iface_props) +def prop_set(obj, k, v, iface=None): + if iface is None: iface = obj.dbus_interface + return obj.Set(iface, k, v, dbus_interface=iface_props) + +def find_adapter(pattern=None): + return find_adapter_in_objects(get_manager().GetManagedObjects(), pattern) + +def find_adapter_in_objects(objects, pattern=None): + bus, obj = get_bus(), None + for path, ifaces in objects.iteritems(): + adapter = ifaces.get(iface_adapter) + if adapter is None: continue + if not pattern or pattern == adapter['Address'] or path.endswith(pattern): + obj = bus.get_object(iface_base, path) + yield dbus.Interface(obj, iface_adapter) + if obj is None: + raise BTError('Bluetooth adapter not found') + +def find_device(device_address, adapter_pattern=None): + return find_device_in_objects(get_manager().GetManagedObjects(), device_address, adapter_pattern) + +def find_device_in_objects(objects, device_address, adapter_pattern=None): + bus = get_bus() + path_prefix = '' + if adapter_pattern: + if not isinstance(adapter_pattern, types.StringTypes): adapter = adapter_pattern + else: adapter = find_adapter_in_objects(objects, adapter_pattern) + path_prefix = adapter.object_path + for path, ifaces in objects.iteritems(): + device = ifaces.get(iface_dev) + if device is None: continue + if device['Address'] == device_address and path.startswith(path_prefix): + obj = bus.get_object(iface_base, path) + return dbus.Interface(obj, iface_dev) + raise BTError('Bluetooth device not found') + + +### bt-pan + +def main(args=None): + import argparse + parser = argparse.ArgumentParser( + description='BlueZ bluetooth PAN network server/client.') + + parser.add_argument('-i', '--device', metavar='local-addr/pattern', + help='Local device address/pattern to use (if not default).') + parser.add_argument('-a', '--device-all', action='store_true', + help='Use all local hci devices, not just default one.' + ' Only valid with "server" mode, mutually exclusive with --device option.') + parser.add_argument('-u', '--uuid', + metavar='uuid_or_shortcut', default='nap', + help='Service UUID to use. Can be either full UUID' + ' or one of the shortcuts: gn, panu, nap. Default: %(default)s.') + parser.add_argument('--systemd', action='store_true', + help='Use systemd service' + ' notification/watchdog mechanisms in daemon modes, if available.') + parser.add_argument('--debug', + action='store_true', help='Verbose operation mode.') + + cmds = parser.add_subparsers( dest='call', + title='Supported operations (have their own suboptions as well)' ) + + cmd = cmds.add_parser('server', help='Run infinitely as a NAP network server.') + cmd.add_argument('iface_name', + help='Bridge interface name to which each link will be added by bluez.' + ' It must be created and configured before starting the server.') + + cmd = cmds.add_parser('client', help='Connect to a PAN network.') + cmd.add_argument('remote_addr', help='Remote device address to connect to.') + cmd.add_argument('-d', '--disconnect', action='store_true', + help='Disconnect.') + cmd.add_argument('-w', '--wait', action='store_true', + help='Go into an endless wait-loop after connection, terminating it on exit.') + cmd.add_argument('-c', '--if-not-connected', action='store_true', + help='Dont raise error if connection is already established.') + cmd.add_argument('-r', '--reconnect', action='store_true', + help='Force reconnection if some connection is already established.') + + opts = parser.parse_args() + + global log + import logging + logging.basicConfig(level=logging.DEBUG if opts.debug else logging.WARNING) + log = logging.getLogger() + + if not opts.device_all: devs = [next(iter(find_adapter(opts.device)))] + else: + if opts.call != 'server': + parser.error('--device-all option is only valid with "server" mode.') + devs = list(find_adapter()) + devs = dict((prop_get(dev, 'Address'), dev) for dev in devs) + for dev_addr, dev in devs.viewitems(): + prop_set(dev, 'Powered', True) + log.debug('Using local device (addr: %s): %s', dev_addr, dev.object_path) + + wait_iter_noop = 3600 + if opts.systemd: + from systemd import daemon + def wait_iter(): + if not wait_iter.sd_ready: + daemon.notify('READY=1') + daemon.notify('STATUS=Running in {} mode...'.format(opts.call)) + wait_iter.sd_ready = True + time.sleep(wait_iter.timeout) + if wait_iter.sd_wdt: daemon.notify('WATCHDOG=1') + wd_pid, wd_usec = (os.environ.get(k) for k in ['WATCHDOG_PID', 'WATCHDOG_USEC']) + if wd_pid and wd_pid.isdigit() and int(wd_pid) == os.getpid(): + wd_interval = float(wd_usec) / 2e6 # half of interval in seconds + assert wd_interval > 0, wd_interval + else: wd_interval = None + if wd_interval: + log.debug('Initializing systemd watchdog pinger with interval: %ss', wd_interval) + wait_iter.sd_wdt, wait_iter.timeout = True, min(wd_interval, wait_iter_noop) + else: wait_iter.sd_wdt, wait_iter.timeout = False, wait_iter_noop + wait_iter.sd_ready = False + else: wait_iter = lambda: time.sleep(wait_iter_noop) + signal.signal(signal.SIGTERM, lambda sig,frm: sys.exit(0)) + + + if opts.call == 'server': + brctl = subprocess.Popen( + ['brctl', 'show', opts.iface_name], + stdout=open(os.devnull, 'wb'), stderr=subprocess.PIPE ) + brctl_stderr = brctl.stderr.read() + if brctl.wait() or brctl_stderr: + p = lambda fmt='',*a,**k: print(fmt.format(*a,**k), file=sys.stderr) + p('brctl check failed for interface: {}', opts.iface_name) + p() + p('Bridge interface must be added and configured before starting server, e.g. with:') + p(' brctl addbr bnep-bridge') + p(' brctl setfd bnep-bridge 0') + p(' brctl stp bnep-bridge off') + p(' ip addr add 10.101.225.84/24 dev bnep-bridge') + p(' ip link set bnep-bridge up') + return 1 + + servers = list() + try: + for dev_addr, dev in devs.viewitems(): + server = dbus.Interface(dev, 'org.bluez.NetworkServer1') + server.Unregister(opts.uuid) # in case already registered + server.Register(opts.uuid, opts.iface_name) + servers.append(server) + log.debug( 'Registered uuid %r with' + ' bridge/dev: %s / %s', opts.uuid, opts.iface_name, dev_addr ) + while True: wait_iter() + except KeyboardInterrupt: pass + finally: + if servers: + for server in servers: server.Unregister(opts.uuid) + log.debug('Unregistered server uuids') + + + elif opts.call == 'client': + dev_remote = find_device(opts.remote_addr, devs.values()[0]) + log.debug( 'Using remote device (addr: %s): %s', + prop_get(dev_remote, 'Address'), dev_remote.object_path ) + try: dev_remote.ConnectProfile(opts.uuid) + except: pass # no idea why it fails sometimes, but still creates dbus interface + + net = dbus.Interface(dev_remote, 'org.bluez.Network1') + for n in xrange(2): + try: iface = net.Connect(opts.uuid) + except dbus.exceptions.DBusException as err: + if err.get_dbus_name() != 'org.bluez.Error.Failed': raise + connected = prop_get(net, 'Connected') + if not connected: raise + if opts.disconnect: + net.Disconnect() + log.debug('Disconnected from network') + return + if opts.reconnect: + log.debug( 'Detected pre-established connection' + ' (iface: %s), reconnecting', prop_get(net, 'Interface') ) + net.Disconnect() + continue + if not opts.if_not_connected: raise + else: break + log.debug( + 'Connected to network (dev_remote: %s, addr: %s) uuid %r with iface: %s', + dev_remote.object_path, prop_get(dev_remote, 'Address'), opts.uuid, iface ) + + if opts.wait: + try: + while True: wait_iter() + except KeyboardInterrupt: pass + finally: + net.Disconnect() + log.debug('Disconnected from network') + + + else: raise ValueError(opts.call) + log.debug('Finished') + +if __name__ == '__main__': sys.exit(main()) diff --git a/bin/mm-format-ns-glucose.sh b/bin/mm-format-ns-glucose.sh index c8d511b0f..3dcd9c114 100755 --- a/bin/mm-format-ns-glucose.sh +++ b/bin/mm-format-ns-glucose.sh @@ -8,17 +8,32 @@ NSONLY="" test "$1" = "--oref0" && NSONLY="this.glucose = this.sgv" && shift +self=$(basename $0) +function usage ( ) { + +cat < +$self - Format Medtronic glucose data into something acceptable to Nightscout. +EOT +} + +case "$1" in + --help|-h|help) + usage + exit 0 +esac + HISTORY=${1-glucosehistory.json} OUTPUT=${2-/dev/fd/1} #TZ=${3-$(date +%z)} cat $HISTORY | \ - json -e "this.medtronic = this._type;" | \ - json -e "this.dateString = this.dateString ? this.dateString : (this.date + '$(date +%z)')" | \ - json -e "this.date = new Date(this.dateString).getTime();" | \ - json -e "this.type = (this.name == 'GlucoseSensorData') ? 'sgv' : 'pumpdata'" | \ - json -e "this.device = 'openaps://medtronic/pump/cgm'" | ( - json -e "$NSONLY" + json -E "this.medtronic = this._type;" | \ + json -E "this.dateString = this.dateString ? this.dateString : (this.date + '$(date +%z)')" | \ + json -E "this.date = new Date(this.dateString).getTime();" | \ + json -E "this.type = (this.name && this.name.indexOf('GlucoseSensorData') > -1) ? 'sgv' : 'pumpdata'" | \ + json -E "this.device = 'openaps://medtronic/pump/cgm'" | ( + json -E "$NSONLY" ) > $OUTPUT diff --git a/bin/mm-format-ns-profile.sh b/bin/mm-format-ns-profile.sh index 8e0e2f53a..718224ce6 100755 --- a/bin/mm-format-ns-profile.sh +++ b/bin/mm-format-ns-profile.sh @@ -2,18 +2,32 @@ # Author: Ben West +self=$(basename $0) SETTINGS=${1-monitor/settings.json} CARBS=${2-monitor/carb-ratios.json} BASALRATES=${3-monitor/active-basal-profile.json} SENSITIVITIES=${4-monitor/insulin-sensitivities.json} -TARGETS=${4-monitor/bg-targets.json} -OUTPUT=${2-/dev/fd/1} +TARGETS=${5-monitor/bg-targets.json} +OUTPUT=${6-/dev/fd/1} # DIA # CARBRATIO #TZ=${3-$(date +%z)} function usage ( ) { cat < +$self - Format Medtronic pump-history data into something acceptable to Nightscout. +EOT +} + +case "$1" in + --help|-h|help) + usage + exit 0 +esac + + HISTORY=${1-pumphistory.json} OUTPUT=${2-/dev/fd/1} #TZ=${3-$(date +%z)} cat $HISTORY | \ - json -e "this.medtronic = this._type;" | \ - #json -e "this.dateString = this.timestamp + '$(TZ=TZ date +%z)'" | \ - json -e "this.dateString = this.timestamp + '$(date +%z)'" | \ - json -e "this.type = 'medtronic'" | \ - json -e "this.date = this.date ? this.date : new Date(Date.parse(this.dateString)).getTime( )" \ + json -e "this.medtronic = this._type;" \ + -e "this.dateString = this.timestamp + '$(date +%z)'" \ + -e "this.type = 'medtronic'" \ + -e "this.date = this.date ? this.date : new Date(Date.parse(this.dateString)).getTime( )" \ > $OUTPUT diff --git a/bin/mm-format-ns-treatments.sh b/bin/mm-format-ns-treatments.sh index 1c976759e..fd10042a1 100755 --- a/bin/mm-format-ns-treatments.sh +++ b/bin/mm-format-ns-treatments.sh @@ -7,17 +7,31 @@ MODEL=${2-model.json} OUTPUT=${3-/dev/fd/1} #TZ=${3-$(date +%z)} self=$(basename $0) +function usage ( ) { + +cat < +$self - Format medtronic history data into Nightscout treatments data. +EOT +} + +case "$1" in + --help|-h|help) + usage + exit 0 +esac + # | json -e "this.type = 'mm://openaps/$self'" \ model=$(json -f $MODEL) oref0-normalize-temps $HISTORY \ | json -e "this.medtronic = 'mm://openaps/$self/' + (this._type || this.eventType);" \ - | json -e "this.created_at = this.created_at ? this.created_at : this.timestamp" \ - | json -e "this.enteredBy = 'openaps://medtronic/$model'" \ - | json -e "if (this.glucose && !this.glucoseType && this.glucose > 0) { this.glucoseType = this.enteredBy }" \ - | json -e "this.eventType = (this.eventType ? this.eventType : 'Note')" \ - | json -e "if (this.eventType == 'Note') { this.notes = this._type + ' $model ' + (this.notes ? this.notes : '')}" \ - | json > $OUTPUT - + -e "this.created_at = this.created_at ? this.created_at : this.timestamp" \ + -e "this.enteredBy = 'openaps://medtronic/$model'" \ + -e "if (this.glucose && !this.glucoseType && this.glucose > 0) { this.glucoseType = this.enteredBy }" \ + -e "this.eventType = (this.eventType ? this.eventType : 'Note')" \ + -e "if (this._type == 'AlarmSensor' && this.alarm_description) {this.notes = this.alarm_description}" \ + -e "if (this.eventType == 'Note' && !this.alarm_description) { this.notes = this._type + ' $model ' + (this.notes ? this.notes : '')}" \ + > $OUTPUT diff --git a/bin/mm-format-oref0-glucose.sh b/bin/mm-format-oref0-glucose.sh index 099b93373..f81650c5d 100755 --- a/bin/mm-format-oref0-glucose.sh +++ b/bin/mm-format-oref0-glucose.sh @@ -4,15 +4,29 @@ # Maintainer: @tghoward # Written for decocare v0.0.18. Will need updating the the decocare json format changes. +self=$(basename $0) HISTORY=${1-glucosehistory.json} OUTPUT=${2-/dev/fd/1} #TZ=${3-$(date +%z)} +function usage ( ) { + +cat < +$self - Format medtronic glucose data into oref0 format. +EOT +} + +case "$1" in + --help|-h|help) + usage + exit 0 +esac cat $HISTORY | \ json -e "this.medtronic = this._type;" | \ json -e "this.dateString = this.date + '$(date +%z)'" | \ json -e "this.date = new Date(this.dateString).getTime();" | \ - json -e "this.type = (this.name == 'GlucoseSensorData') ? 'sgv' : 'pumpdata'" | \ + json -E "this.type = (this.name && this.name.indexOf('GlucoseSensorData') > -1) ? 'sgv' : 'pumpdata'" | \ json -e "this.device = 'openaps://medtronic/pump/cgm'" \ > $OUTPUT diff --git a/bin/mm-stick.sh b/bin/mm-stick.sh index b4053ea7e..afb6c9123 100755 --- a/bin/mm-stick.sh +++ b/bin/mm-stick.sh @@ -109,7 +109,7 @@ case $OPERATION in print_fail $* exit 1 ;; - *|help) + *|help|--help|-h) print_help ;; esac diff --git a/bin/monitor-xdrip.sh b/bin/monitor-xdrip.sh new file mode 100755 index 000000000..e45ff9b3a --- /dev/null +++ b/bin/monitor-xdrip.sh @@ -0,0 +1,13 @@ +#!/bin/bash + +date +cp -rf xdrip/glucose.json xdrip/last-glucose.json +curl --compressed -s http://localhost:5000/api/v1/entries?count=288 | json -e "this.glucose = this.sgv" > xdrip/glucose.json +if ! cmp --silent xdrip/glucose.json xdrip/last-glucose.json; then + if cat xdrip/glucose.json | json -c "minAgo=(new Date()-new Date(this.dateString))/60/1000; return minAgo < 10 && minAgo > -5 && this.glucose > 38" | grep -q glucose; then + cp -up xdrip/glucose.json monitor/glucose.json + else + echo No recent glucose data downloaded from xDrip. + diff xdrip/glucose.json xdrip/last-glucose.json + fi +fi diff --git a/bin/nightscout.sh b/bin/nightscout.sh index 2b11237c0..d3fe79cec 100755 --- a/bin/nightscout.sh +++ b/bin/nightscout.sh @@ -6,27 +6,348 @@ NAME=${1-help} shift PROGRAM="ns-${NAME}" COMMAND=$(which $PROGRAM | head -n 1) +NIGHTSCOUT_DEBUG=${NIGHTSCOUT_DEBUG-0} function help_message ( ) { cat < +* latest-openaps-treatment +* cull-latest-openaps-treatments + +* get +* upload +* dedupe-treatments +* hash-api-secret +* status +* get-status +* upload-entries +* autoconfigure-device-crud + +EOF + +extra_ns_help + +} + +function extra_ns_help ( ) { + +cat < + +sets up: +openaps use ns shell get entries.json 'count=10' +openaps use ns shell upload treatments.json recently/combined-treatments.json + + + +EOF +extra_ns_help +} + +function ns_help ( ) { +cat < -1) ? 'sgv' : 'pumpdata'" | \ + json -E "this.device = 'openaps://medtronic/pump/cgm'" | ( + json -E "$NSONLY" + ) + ;; + format-recent-type) + ZONE=${1-'tz'} + TYPE=${2-'entries'} + FILE=${3-''} + # nightscout ns $NIGHTSCOUT_HOST $API_SECRET + test -z ${ZONE} && echo "Missing first argument, ZONE, usually is set to tz" && exit 1 + test -z ${TYPE} && echo "Missing second argument, TYPE, one of: entries, treatments, devicestatus, profiles." && exit 1 + test ! -e ${FILE} && echo "Third argument, contents to upload, FILE, does not exist" && exit 1 + test ! -r ${FILE} && echo "Third argument, contents to upload, FILE, not readable." && exit 1 + openaps use ns shell lsgaps ${ZONE} ${TYPE} \ + | openaps use ${ZONE} select --date dateString --current now --gaps - ${FILE} | json + ;; + latest-entries-time) + PREVIOUS_TIME=$(ns-get host $NIGHTSCOUT_HOST entries.json 'find[type]=sgv' | json 0) + test -z "${PREVIOUS_TIME}" && echo -n 0 || echo $PREVIOUS_TIME | json -j dateString + exit 0 + ;; + latest-treatment-time) + PREVIOUS_TIME=$(ns-get host $NIGHTSCOUT_HOST treatments.json'?find[enteredBy]=/openaps:\/\//&count=1' | json 0) + test -z "${PREVIOUS_TIME}" && echo -n 0 || echo $PREVIOUS_TIME | json -j created_at + exit 0 + # exec ns-get host $NIGHTSCOUT_HOST $* + ;; + format-recent-history-treatments) + HISTORY=$1 + MODEL=$2 + LAST_TIME=$(nightscout ns $NIGHTSCOUT_HOST $API_SECRET latest-treatment-time | json) + exec nightscout cull-latest-openaps-treatments $HISTORY $MODEL ${LAST_TIME} + exit 0 + + ;; + upload-non-empty-type) + TYPE=${1-entries.json} + FILE=$2 + test $(cat $FILE | json -a | wc -l) -lt 1 && echo "Nothing to upload." >&2 && cat $FILE && exit 0 + exec ns-upload $NIGHTSCOUT_HOST $API_SECRET $TYPE $FILE + ;; + upload-non-empty-treatments) + test $(cat $1 | json -a | wc -l) -lt 1 && echo "Nothing to upload." >&2 && cat $1 && exit 0 + exec ns-upload $NIGHTSCOUT_HOST $API_SECRET treatments.json $1 + + ;; + upload) + exec ns-upload $NIGHTSCOUT_HOST $API_SECRET $* + ;; + oref0_glucose) + zone=${1-'tz'} + shift + params=$* + params=${params-'count=10'} + exec ns-get host $NIGHTSCOUT_HOST entries/sgv.json $params \ + | json -e "this.glucose = this.sgv" \ + | openaps use $zone rezone --astimezone --date dateString - + ;; + oref0_glucose_without_zone) + params=$* + params=${params-'count=10'} + exec ns-get host $NIGHTSCOUT_HOST entries/sgv.json $params \ + | json -e "this.glucose = this.sgv" + ;; + oref0_glucose_since) + expr=$1 + zone=${2-'tz'} + count=${3-1000} + exec ns-get host $NIGHTSCOUT_HOST entries/sgv.json "find[date][\$gte]=$(date -d $expr +"%s%3N")&count=$count" \ + | json -e "this.glucose = this.sgv" \ + | openaps use $zone rezone --astimezone --date dateString - + ;; + temp_targets) + expr=${1--24hours} + exec ns-get host $NIGHTSCOUT_HOST treatments.json "find[created_at][\$gte]=$(date -d $expr -Iminutes -u)&find[eventType]=Temporary+Target" + ;; + carb_history) + expr=${1--24hours} + exec ns-get host $NIGHTSCOUT_HOST treatments.json "find[created_at][\$gte]=$(date -d $expr -Iminutes -u)&find[carbs][\$exists]=true" + ;; + *) + echo "Unknown request:" $OP + ns_help + exit 1; + ;; + esac + exit 0 + + ;; +hash-api-secret) + if [[ -z "$1" ]] ; then + echo "Missing plain Nightscout passphrase". + echo "Usage: $self hash-api-secret 'myverylongsecret'". + exit 1; + fi + API_SECRET=$(echo -n $1 | sha1sum | cut -d ' ' -f 1 | tr -d "\n") + echo $API_SECRET + ;; +autoconfigure-device-crud) + NIGHTSCOUT_HOST=$1 + PLAIN_NS_SECRET=$2 + if [[ "${PLAIN_NS_SECRET,,}" =~ "token=" ]]; then + API_SECRET=$2 # store token as API_SECRET + else + API_SECRET=$($self hash-api-secret $2) + fi + case $1 in + help|-h|--help) + setup_help + exit 0 + ;; + esac + # openaps device add ns-get host + test -z "$NIGHTSCOUT_HOST" && setup_help && exit 1; + test -z "$API_SECRET" && setup_help && exit 1; + openaps device add ns process --require "oper" nightscout ns "NIGHTSCOUT_HOST" "API_SECRET" + openaps device show ns --json | json \ + -e "this.extra.args = this.extra.args.replace(' NIGHTSCOUT_HOST ', ' $NIGHTSCOUT_HOST ')" \ + -e "this.extra.args = this.extra.args.replace(' API_SECRET', ' $API_SECRET')" \ + | openaps import + ;; cull-latest-openaps-treatments) INPUT=$1 MODEL=$2 LAST_TIME=$3 mm-format-ns-treatments $INPUT $MODEL | json -c "this.created_at > '$LAST_TIME'" ;; -help) +help|--help|-h) help_message + exit 0 ;; *) test -n "$COMMAND" && exec $COMMAND $* diff --git a/bin/ns-dedupe-treatments.sh b/bin/ns-dedupe-treatments.sh index 307513f5d..efde496d8 100755 --- a/bin/ns-dedupe-treatments.sh +++ b/bin/ns-dedupe-treatments.sh @@ -11,7 +11,7 @@ EOF } function fetch ( ) { - curl -s $ENDPOINT.json + curl --compressed -s -g $ENDPOINT.json } function flatten ( ) { @@ -22,7 +22,7 @@ function flatten ( ) { function find_dupes_on ( ) { count=$1 date=$2 - test $count -gt 1 && curl -g -s ${ENDPOINT}.json"?count=$(($count-1))&find[created_at]=$date" + test $count -gt 1 && curl --compressed -g -s ${ENDPOINT}.json"?count=$(($count-1))&find[created_at]=$date" } function debug_cmd ( ) { tid=$1 @@ -45,8 +45,8 @@ export NIGHTSCOUT_HOST ENDPOINT fetch | flatten | while read count date; do test $count -gt 1 && echo "{}" \ | json -e "this.count = $count" \ - | json -e "this.date = '$date'" \ - | json -e "this.created_at = '$date'" + -e "this.date = '$date'" \ + -e "this.created_at = '$date'" done | json -g } @@ -87,7 +87,7 @@ case "$1" in delete) main $2 delete_cmd ;; - *|help) + *|help|--help|-h) usage exit 1; ;; diff --git a/bin/ns-get.sh b/bin/ns-get.sh index d2d9366df..3d00b02aa 100755 --- a/bin/ns-get.sh +++ b/bin/ns-get.sh @@ -8,6 +8,11 @@ NIGHTSCOUT_HOST=${NIGHTSCOUT_HOST-${2-localhost:1337}} QUERY=${3} OUTPUT=${4-/dev/fd/1} +CURL_FLAGS="--compressed -g -s" +NIGHTSCOUT_FORMAT=${NIGHTSCOUT_FORMAT-jq .} +test "$NIGHTSCOUT_DEBUG" = "1" && CURL_FLAGS="${CURL_FLAGS} -iv" +test "$NIGHTSCOUT_DEBUG" = "1" && set -x + function usage ( ) { cat < [NIGHTSCOUT_HOST|localhost:1337] [QUERY] [stdout|-] @@ -15,46 +20,56 @@ Usage: $self [NIGHTSCOUT_HOST|localhost:1337] [QUERY] [stdout|-] $self type [QUERY] [stdout|-] -$self --config EOF } -REPORT_ENDPOINT=$NIGHTSCOUT_HOST/api/v1/${REPORT}'?'${QUERY} +CURL_AUTH="" + +# use token authentication if the user has a token set in their API_SECRET environment variable +if [[ "${API_SECRET}" =~ "token=" ]]; then + if [[ -z ${QUERY} ]]; then + REPORT_ENDPOINT=$NIGHTSCOUT_HOST/api/v1/${REPORT}'?'${API_SECRET} + else + REPORT_ENDPOINT=$NIGHTSCOUT_HOST/api/v1/${REPORT}'?'${API_SECRET}'&'${QUERY} + fi +else + REPORT_ENDPOINT=$NIGHTSCOUT_HOST/api/v1/${REPORT}'?'${QUERY} + #CURL_AUTH='-H "api-secret: ${API_SECRET}"' +fi + case $1 in - --config) - test -z $2 && echo "Device name missing." && usage && exit 1; - devicename=${2-${self}} - test -z $3 && echo "Type is missing" && usage && exit 1; - # echo openaps device add $2 process $self $3 - cat < -99; + }); + } + status.mmtune = mmtune; + } +} - return resolved; +function uploaderStatus (status) { + var uploader = require(cwd + uploader_input); + if (uploader) { + if (typeof uploader === 'number') { + status.uploader = { + battery: uploader + }; + } else { + status.uploader = uploader; + } + } } if (!module.parent) { - - var clock_input = process.argv.slice(2, 3).pop(); - var iob_input = process.argv.slice(3, 4).pop(); - var suggested_input = process.argv.slice(4, 5).pop(); - var enacted_input = process.argv.slice(5, 6).pop(); - var battery_input = process.argv.slice(6, 7).pop(); - var reservoir_input = process.argv.slice(7, 8).pop(); - var status_input = process.argv.slice(8, 9).pop(); + + var argv = require('yargs') + .usage("$0 [--uploader uploader.json] [mmtune.json]") + .option('uploader', { + alias: 'u', + describe: "Uploader battery status", + default: false + }) + .strict(true) + .help('help'); + + var params = argv.argv; + var inputs = params._; + var clock_input = inputs[0]; + var iob_input = inputs[1]; + var suggested_input = inputs[2]; + var enacted_input = inputs[3]; + var battery_input = inputs[4]; + var reservoir_input = inputs[5]; + var status_input = inputs[6]; + var mmtune_input = inputs[7]; + var uploader_input = params.uploader; + + if (inputs.length > 8) { + uploader_input = params.uploader ? inputs[7] : false; + mmtune_input = inputs[8]; + } if (!clock_input || !iob_input || !suggested_input || !enacted_input || !battery_input || !reservoir_input || !status_input) { - console.log('usage: ', process.argv.slice(0, 2), ' '); + console.log('usage: ', process.argv.slice(0, 2), ' [--uploader uploader.json] [mmtune.json]'); process.exit(1); } - - var cwd = process.cwd(); - - var status = { - openaps: { - iob: requireWithTimestamp(cwd + '/' + iob_input) - , suggested: requireWithTimestamp(cwd + '/' + suggested_input) - , enacted: requireWithTimestamp(cwd + '/' + enacted_input) - } - , pump: { - clock: require(cwd + '/' + clock_input) - , battery: require(cwd + '/' + battery_input) - , reservoir: require(cwd + '/' + reservoir_input) - , status: requireWithTimestamp(cwd + '/' + status_input) - } - }; - - console.log(JSON.stringify(status)); + + var cwd = process.cwd() + '/'; + + var hostname = 'unknown'; + try { + hostname = os.hostname(); + } catch (e) { + return console.error('Unable to get hostname to send with status', e); + } + + try { + var iob = null; + var iobArray = requireWithTimestamp(cwd + iob_input); + var suggested = requireWithTimestamp(cwd + suggested_input); + var enacted = requireWithTimestamp(cwd + enacted_input); + + if (iobArray && iobArray.length) { + iob = iobArray[0]; + iob.timestamp = iob.time; + delete iob.time; + } + + // we only need the most current predBGs + if (enacted && suggested) { + if (enacted.timestamp > suggested.timestamp) { + delete suggested.predBGs; + } else { + delete enacted.predBGs; + } + } + + var status = { + device: 'openaps://' + os.hostname(), + openaps: { + iob: iob, + suggested: suggested, + enacted: enacted + }, + pump: { + clock: safeRequire(cwd + clock_input), + battery: safeRequire(cwd + battery_input), + reservoir: safeRequire(cwd + reservoir_input), + status: requireWithTimestamp(cwd + status_input) + } + }; + + if (mmtune_input) { + mmtuneStatus(status); + } + + if (uploader_input) { + uploaderStatus(status); + } + + console.log(JSON.stringify(status)); + } catch (e) { + return console.error("Could not parse input data: ", e); + } } diff --git a/bin/ns-upload-entries.sh b/bin/ns-upload-entries.sh index 0bb0f56c5..26316b91a 100755 --- a/bin/ns-upload-entries.sh +++ b/bin/ns-upload-entries.sh @@ -3,17 +3,41 @@ # Author: Ben West # Maintainer: @cjo20, @scottleibrand +self=$(basename $0) ENTRIES=${1-entries.json} NIGHTSCOUT_HOST=${NIGHTSCOUT_HOST-localhost:1337} -#TZ=${3-$(date +%z)} OUTPUT=${2} +function usage ( ) { +cat < +$self - Upload entries (glucose data) to NS. +EOF +} + +case "$1" in + -h|--help|help) + usage + exit 0 + ;; +esac + export ENTRIES API_SECRET NIGHTSCOUT_HOST + +# use token authentication if the user has a token set in their API_SECRET environment variable +if [[ "${API_SECRET,,}" =~ "token=" ]]; then + API_SECRET_HEADER="" + REST_ENDPOINT="${NIGHTSCOUT_HOST}/api/v1/entries.json?${API_SECRET}" +else + REST_ENDPOINT="${NIGHTSCOUT_HOST}/api/v1/entries.json" + API_SECRET_HEADER='-H "API-SECRET: ${API_SECRET}"' +fi + + # requires API_SECRET and NIGHTSCOUT_HOST to be set in calling environment (i.e. in crontab) ( -curl -s -X POST --data-binary @$ENTRIES \ - -H "API-SECRET: $API_SECRET" \ - -H "content-type: application/json" \ - $NIGHTSCOUT_HOST/api/v1/entries.json -) && ( test -n "$OUTPUT" && touch $OUTPUT ; logger "Uploaded $ENTRIES to $NIGHTSCOUT_HOST" ) || logger "Unable to upload to $NIGHTSCOUT_HOST" +curl -m 30 -s -X POST --data-binary @${ENTRIES} \ + ${API_SECRET_HEADER} -H "content-type: application/json" \ + ${REST_ENDPOINT} +) && ( test -n "${OUTPUT}" && touch ${OUTPUT} ; logger "Uploaded ${ENTRIES} to ${NIGHTSCOUT_HOST}" ) || logger "Unable to upload to ${NIGHTSCOUT_HOST}" diff --git a/bin/ns-upload.sh b/bin/ns-upload.sh index ca45d303b..9876e6a70 100755 --- a/bin/ns-upload.sh +++ b/bin/ns-upload.sh @@ -7,7 +7,6 @@ NIGHTSCOUT_HOST=${NIGHTSCOUT_HOST-${1-localhost:1337}} API_SECRET=${2-${API_SECRET}} TYPE=${3-entries.json} ENTRIES=${4-entries.json} -#TZ=${3-$(date +%z)} OUTPUT=${5} REST_ENDPOINT="${NIGHTSCOUT_HOST}/api/v1/${TYPE}" @@ -16,32 +15,19 @@ function usage ( ) { cat < [API-TYPE|entries.json] [stdout|-] -$self --config output-report.json - $self help - This message. EOF } case $1 in - --config) - test -z $3 && usage && exit 1; - # echo openaps device add $2 process $self $3 -API_SECRET=$(echo -n $3 | sha1sum | cut -d ' ' -f 1 | tr -d "\n") - cat </dev/null >/dev/null || die "Usage: $self " -fi -directory=`mkdir -p $1; cd $1; pwd` -serial=$2 - -echo -n Setting up oref0 in $directory for pump $serial - -if [[ $# -gt 3 ]]; then - diyps_url=$4 - echo -n ", DIYPS URL $diyps_url" -fi -echo - -read -p "Continue? " -n 1 -r -echo -if [[ $REPLY =~ ^[Yy]$ ]]; then - -( ( cd $directory 2>/dev/null && git status ) || ( openaps init $directory ) ) || die "Can't init $directory" -cd $directory || die "Can't cd $directory" - -#sudo cp ~/src/oref0/logrotate.openaps /etc/logrotate.d/openaps -sudo bash -c "curl -s https://raw.githubusercontent.com/openaps/oref0/master/logrotate.openaps > /etc/logrotate.d/openaps" -#sudo cp ~/src/oref0/logrotate.rsyslog /etc/logrotate.d/rsyslog -sudo bash -c "curl -s https://raw.githubusercontent.com/openaps/oref0/master/logrotate.rsyslog > /etc/logrotate.d/rsyslog" - -test -d /var/log/openaps || sudo mkdir /var/log/openaps && sudo chown $USER /var/log/openaps - -openaps vendor add openapscontrib.timezones - -# don't re-create devices if they already exist -openaps device show 2>/dev/null > /tmp/openaps-devices - -# add devices -grep -q pump.ini .gitignore 2>/dev/null || echo pump.ini >> .gitignore -git add .gitignore -grep pump /tmp/openaps-devices || openaps device add pump medtronic $serial || die "Can't add pump" -grep cgm /tmp/openaps-devices || openaps device add cgm dexcom || die "Can't add CGM" -git add cgm.ini -grep ns-glucose /tmp/openaps-devices || openaps device add ns-glucose process 'bash -c "curl -s $NIGHTSCOUT_HOST/api/v1/entries/sgv.json | json -e \"this.glucose = this.sgv\""' || die "Can't add ns-glucose" -git add ns-glucose.ini -grep oref0 /tmp/openaps-devices || openaps device add oref0 process oref0 || die "Can't add oref0" -git add oref0.ini -grep iob /tmp/openaps-devices || openaps device add iob process --require "pumphistory profile clock" oref0 calculate-iob || die "Can't add iob" -git add iob.ini -grep tz /tmp/openaps-devices || openaps device add tz timezones || die "Can't add tz" -git add tz.ini -#grep latest-treatments /tmp/openaps-devices || openaps device add latest-treatments process nightscout 'latest-openaps-treatment $NIGHTSCOUT_HOST' || die "Can't add latest-treatments" -#git add latest-treatments.ini - -# don't re-create reports if they already exist -openaps report show 2>/dev/null > /tmp/openaps-reports - -# add reports for frequently-refreshed monitoring data -ls monitor 2>/dev/null >/dev/null || mkdir monitor || die "Can't mkdir monitor" -grep monitor/glucose.json /tmp/openaps-reports || openaps report add monitor/glucose.json JSON cgm iter_glucose 5 || die "Can't add glucose.json" -grep monitor/ns-glucose.json /tmp/openaps-reports || openaps report add monitor/ns-glucose.json text ns-glucose shell || die "Can't add ns-glucose.json" -grep settings/model.json /tmp/openaps-reports || openaps report add settings/model.json JSON pump model || die "Can't add model" -grep monitor/clock.json /tmp/openaps-reports || openaps report add monitor/clock.json JSON pump read_clock || die "Can't add clock.json" -grep monitor/clock-zoned.json /tmp/openaps-reports || openaps report add monitor/clock-zoned.json JSON tz clock monitor/clock.json || die "Can't add clock-zoned.json" -grep monitor/temp_basal.json /tmp/openaps-reports || openaps report add monitor/temp_basal.json JSON pump read_temp_basal || die "Can't add temp_basal.json" -grep monitor/reservoir.json /tmp/openaps-reports || openaps report add monitor/reservoir.json JSON pump reservoir || die "Can't add reservoir.json" -grep monitor/pumphistory.json /tmp/openaps-reports || openaps report add monitor/pumphistory.json JSON pump iter_pump_hours 4 || die "Can't add pumphistory.json" -grep monitor/pumphistory-zoned.json /tmp/openaps-reports || openaps report add monitor/pumphistory-zoned.json JSON tz rezone monitor/pumphistory.json || die "Can't add pumphistory-zoned.json" -grep monitor/iob.json /tmp/openaps-reports || openaps report add monitor/iob.json text iob shell monitor/pumphistory-zoned.json settings/profile.json monitor/clock-zoned.json || die "Can't add iob.json" - -# add reports for infrequently-refreshed settings data -ls settings 2>/dev/null >/dev/null || mkdir settings || die "Can't mkdir settings" -grep settings/bg_targets.json /tmp/openaps-reports || openaps report add settings/bg_targets.json JSON pump read_bg_targets || die "Can't add bg_targets.json" -grep settings/insulin_sensitivities.json /tmp/openaps-reports || openaps report add settings/insulin_sensitivities.json JSON pump read_insulin_sensitivities || die "Can't add insulin_sensitivities.json" -grep settings/basal_profile.json /tmp/openaps-reports || openaps report add settings/basal_profile.json JSON pump read_selected_basal_profile || die "Can't add basal_profile.json" -grep settings/settings.json /tmp/openaps-reports || openaps report add settings/settings.json JSON pump read_settings || die "Can't add settings.json" - -# add aliases to get data -openaps alias add invoke "report invoke" || die "Can't add invoke" -openaps alias add preflight '! bash -c "rm -f monitor/clock.json && openaps report invoke monitor/clock.json >/dev/null 2>/dev/null && grep -q T monitor/clock.json && echo PREFLIGHT OK || ( mm-stick warmup || sudo oref0-reset-usb; echo PREFLIGHT FAIL; sleep 120; exit 1 )"' || die "Can't add preflight" -openaps alias add monitor-cgm "report invoke monitor/glucose.json" || die "Can't add monitor-cgm" -openaps alias add get-ns-glucose "report invoke monitor/ns-glucose.json" || die "Can't add get-ns-glucose" -openaps alias add monitor-pump "report invoke monitor/clock.json monitor/temp_basal.json monitor/pumphistory.json monitor/pumphistory-zoned.json monitor/clock-zoned.json" || die "Can't add monitor-pump" -openaps alias add get-settings "report invoke settings/model.json settings/bg_targets.json settings/insulin_sensitivities.json settings/basal_profile.json settings/settings.json" || die "Can't add get-settings" -openaps alias add get-bg '! bash -c "openaps monitor-cgm 2>/dev/null || ( openaps get-ns-glucose && grep -q glucose monitor/ns-glucose.json && mv monitor/ns-glucose.json monitor/glucose.json )"' || die "Can't add get-bg" -openaps alias add gather '! bash -c "rm monitor/*; ( openaps get-bg && openaps get-settings >/dev/null && openaps monitor-pump ) 2>/dev/null"' || die "Can't add gather" -openaps alias add wait-for-bg '! bash -c "touch monitor/glucose.json; cp monitor/glucose.json monitor/last-glucose.json; while(diff -q monitor/last-glucose.json monitor/glucose.json); do echo -n .; sleep 10; openaps get-bg >/dev/null; done"' - -# upload treatments to nightscout -ls upload 2>/dev/null >/dev/null || mkdir upload || die "Can't mkdir upload" -openaps alias add latest-ns-treatment-time '! bash -c "nightscout latest-openaps-treatment $NIGHTSCOUT_HOST | json created_at"' || die "Can't add latest-ns-treatment-time" -openaps alias add format-latest-nightscout-treatments '! bash -c "nightscout cull-latest-openaps-treatments monitor/pumphistory-zoned.json settings/model.json $(openaps latest-ns-treatment-time) > upload/latest-treatments.json"' || die "Can't add format-latest-nightscout-treatments" -openaps alias add upload-recent-treatments '! bash -c "openaps format-latest-nightscout-treatments && test $(json -f upload/latest-treatments.json -a created_at eventType | wc -l ) -gt 0 && (ns-upload $NIGHTSCOUT_HOST $API_SECRET treatments.json upload/latest-treatments.json ) || echo \"No recent treatments to upload\""' || die "Can't add upload-recent-treatments" -openaps alias add upload '! bash -c "openaps preflight && ( openaps monitor-pump && openaps upload-recent-treatments && openaps get-settings) 2>/dev/null >/dev/null && echo -n \"Uploaded; most recent treatment event @ \" && openaps latest-ns-treatment-time || echo \"Error; could not upload\""' || die "Can't add upload" - -read -p "Schedule oref1 (openaps nightscout uploader) in cron? " -n 1 -r -echo -if [[ $REPLY =~ ^[Yy]$ ]]; then - read -p "Nightscout hostname? " - NIGHTSCOUT_HOST=$REPLY - read -p "Hashed API secret? " - API_SECRET=$REPLY - read -p "Upload to $NIGHTSCOUT_HOST using API secret $API_SECRET, correct? " -n 1 -r - if [[ $REPLY =~ ^[Yy]$ ]]; then - (crontab -l; echo NIGHTSCOUT_HOST=$NIGHTSCOUT_HOST) | crontab - - (crontab -l; echo API_SECRET=$API_SECRET) | crontab - - fi - # add crontab entries - (crontab -l; crontab -l | grep -q PATH || echo 'PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin') | crontab - - (crontab -l; crontab -l | grep -q killall || echo '* * * * * killall -g --older-than 10m openaps') | crontab - - (crontab -l; crontab -l | grep -q "reset-git" || echo "* * * * * cd $directory && oref0-reset-git") | crontab - - (crontab -l; crontab -l | grep -q uploader || echo "* * * * * cd $directory && ( ps aux | grep -v grep | grep -q 'openaps ' && echo OpenAPS already running || openaps upload ) 2>&1 | tee -a /var/log/openaps/uploader.log") | crontab - - crontab -l -fi - -fi diff --git a/bin/openaps-bootstrap.sh b/bin/openaps-bootstrap.sh new file mode 100755 index 000000000..610202fd1 --- /dev/null +++ b/bin/openaps-bootstrap.sh @@ -0,0 +1,34 @@ +#!/bin/bash +( +dmesg -D +echo Scanning for wifi networks: +ifup wlan0 +wpa_cli scan +echo -e "\nStrongest networks found:" +wpa_cli scan_res | sort -grk 3 | head | awk -F '\t' '{print $NF}' | uniq +set -e +echo -e /"\nWARNING: this script will back up and remove all of your current wifi configs." +read -p "Press Ctrl-C to cancel, or press Enter to continue:" -r +echo -e "\nNOTE: Spaces in your network name or password are ok. Do not add quotes." +read -p "Enter your network name: " -r +SSID=$REPLY +read -p "Enter your network password: " -r +PSK=$REPLY +cd /etc/network +cp interfaces interfaces.$(date +%s).bak +echo -e "auto lo\niface lo inet loopback\n\nauto usb0\niface usb0 inet static\n address 10.11.12.13\n netmask 255.255.255.0\n\nauto wlan0\niface wlan0 inet dhcp\n wpa-conf /etc/wpa_supplicant/wpa_supplicant.conf" > interfaces +echo -e "\n/etc/network/interfaces:\n" +cat interfaces +cd /etc/wpa_supplicant/ +cp wpa_supplicant.conf wpa_supplicant.conf.$(date +%s).bak +echo -e "ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev\nnetwork={\n ssid=\"$SSID\"\n psk=\"$PSK\"\n}" > wpa_supplicant.conf +echo -e "\n/etc/wpa_supplicant/wpa_supplicant.conf:\n" +cat wpa_supplicant.conf +echo -e "\nAttempting to bring up wlan0:\n" +ifdown wlan0; ifup wlan0 +sleep 10 +echo -ne "\nWifi SSID: "; iwgetid -r +sleep 5 +curl https://raw.githubusercontent.com/openaps/oref0/master/bin/openaps-install.sh > /tmp/openaps-install.sh +bash /tmp/openaps-install.sh +) diff --git a/bin/openaps-install.sh b/bin/openaps-install.sh new file mode 100755 index 000000000..e813fc731 --- /dev/null +++ b/bin/openaps-install.sh @@ -0,0 +1,50 @@ +#!/bin/bash +set -e + +read -p "Enter your rig's new hostname (this will be your rig's "name" in the future, so make sure to write it down): " -r +myrighostname=$REPLY +echo $myrighostname > /etc/hostname +sed -r -i"" "s/localhost( jubilinux)?$/localhost $myrighostname/" /etc/hosts +sed -r -i"" "s/127.0.1.1.*$/127.0.1.1 $myrighostname/" /etc/hosts + +# if passwords are old, force them to be changed at next login +passwd -S edison 2>/dev/null | grep 20[01][0-6] && passwd -e root +# automatically expire edison account if its password is not changed in 3 days +passwd -S edison 2>/dev/null | grep 20[01][0-6] && passwd -e edison -i 3 + +if [ -e /run/sshwarn ] ; then + echo Please select a secure password for ssh logins to your rig: + echo 'For the "root" account:' + passwd root + echo 'And for the "pi" account (same password is fine):' + passwd pi +fi + +grep "PermitRootLogin yes" /etc/ssh/sshd_config || echo "PermitRootLogin yes" > /etc/ssh/sshd_config + +# set timezone +dpkg-reconfigure tzdata + +#dpkg -P nodejs nodejs-dev +# TODO: remove the `-o Acquire::ForceIPv4=true` once Debian's mirrors work reliably over IPv6 +apt-get -o Acquire::ForceIPv4=true update && apt-get -o Acquire::ForceIPv4=true -y dist-upgrade && apt-get -o Acquire::ForceIPv4=true -y autoremove +apt-get -o Acquire::ForceIPv4=true update && apt-get -o Acquire::ForceIPv4=true install -y sudo strace tcpdump screen acpid vim python-pip locate ntpdate +#check if edison user exists before trying to add it to groups + +if getent passwd edison > /dev/null; then + echo "Adding edison to sudo users" + adduser edison sudo + echo "Adding edison to dialout users" + adduser edison dialout + # else + # echo "User edison does not exist. Apparently, you are runnning a non-edison setup." +fi + +sed -i "s/daily/hourly/g" /etc/logrotate.conf +sed -i "s/#compress/compress/g" /etc/logrotate.conf + +curl -s https://raw.githubusercontent.com/openaps/oref0/master/bin/openaps-packages.sh | bash - +mkdir -p ~/src; cd ~/src && git clone git://github.com/openaps/oref0.git || (cd oref0 && git checkout master && git pull) +echo "Press Enter to run oref0-setup with the current release (master branch) of oref0," +read -p "or press ctrl-c to cancel. " -r +cd && ~/src/oref0/bin/oref0-setup.sh diff --git a/bin/openaps-packages.sh b/bin/openaps-packages.sh new file mode 100755 index 000000000..a15ee53e2 --- /dev/null +++ b/bin/openaps-packages.sh @@ -0,0 +1,16 @@ +#!/bin/bash + +# TODO: remove the `-o Acquire::ForceIPv4=true` once Debian's mirrors work reliably over IPv6 +apt-get -o Acquire::ForceIPv4=true install -y sudo +sudo apt-get -o Acquire::ForceIPv4=true update && sudo apt-get -o Acquire::ForceIPv4=true -y upgrade +sudo apt-get -o Acquire::ForceIPv4=true install -y git python python-dev software-properties-common python-numpy python-pip npm watchdog strace tcpdump screen acpid vim locate jq lm-sensors && \ +if getent passwd edison > /dev/null; then sudo apt-get -o Acquire::ForceIPv4=true install -y nodejs-legacy; fi && \ +sudo pip install -U openaps && \ +sudo pip install -U openaps-contrib && \ +sudo openaps-install-udev-rules && \ +sudo activate-global-python-argcomplete && \ +sudo npm install -g json oref0 && \ +echo openaps installed && \ +openaps --version + + diff --git a/bin/openaps-src.sh b/bin/openaps-src.sh new file mode 100755 index 000000000..85753e17c --- /dev/null +++ b/bin/openaps-src.sh @@ -0,0 +1,44 @@ +#!/bin/bash + +apt-get install -y sudo +sudo apt-get update +sudo apt-get install -y git python python-dev python-software-properties python-numpy python-pip nodejs-legacy npm watchdog strace tcpdump screen acpid vim locate jq lm-sensors && \ +( curl -s https://bootstrap.pypa.io/ez_setup.py | sudo python ) && \ +sudo npm install -g json && \ +sudo easy_install -ZU setuptools && \ +mkdir ~/src +cd ~/src && \ +( + git clone -b dev git://github.com/openaps/decocare.git || \ + (cd decocare && git pull) + (cd decocare && \ + sudo python setup.py develop + ) + git clone git://github.com/openaps/dexcom_reader.git || \ + (cd dexcom_reader && git pull) + (cd dexcom_reader && \ + sudo python setup.py develop + ) + git clone -b dev git://github.com/openaps/openaps.git || \ + (cd openaps && git pull) + (cd openaps && \ + sudo python setup.py develop + ) + git clone git://github.com/openaps/openaps-contrib.git || \ + (cd openaps-contrib && git pull) + (cd openaps-contrib && \ + sudo python setup.py develop + ) + git clone -b dev git://github.com/openaps/oref0.git || \ + (cd oref0 && git pull) +) +test -d oref0 && \ +cd oref0 && \ +npm install && \ +sudo npm install -g && \ +sudo npm link && \ +sudo npm link oref0 + +sudo openaps-install-udev-rules && \ +sudo activate-global-python-argcomplete && \ +openaps --version diff --git a/bin/oref0-append-local-temptarget.sh b/bin/oref0-append-local-temptarget.sh new file mode 100755 index 000000000..fe78ba5d1 --- /dev/null +++ b/bin/oref0-append-local-temptarget.sh @@ -0,0 +1,15 @@ +#!/bin/bash + +if [[ ! -z "$2" ]]; then + input=$(oref0-set-local-temptarget $@) +elif [[ ! -z "$1" ]]; then + input=$(cat $1) +else + input=$(cat /dev/stdin) +fi +#cat "${1:-/dev/stdin}" \ +echo $input \ + | tee /tmp/temptarget.json \ + && jq -s '[.[0]] + .[1]' /tmp/temptarget.json settings/local-temptargets.json \ + | tee settings/local-temptargets.json.new \ + && mv settings/local-temptargets.json.new settings/local-temptargets.json diff --git a/bin/oref0-autosens-loop.sh b/bin/oref0-autosens-loop.sh new file mode 100755 index 000000000..c813d5785 --- /dev/null +++ b/bin/oref0-autosens-loop.sh @@ -0,0 +1,57 @@ +#!/bin/bash +main() { + echo + echo Starting oref0-autosens-loop at $(date): + overtemp && exit 1 + if highload && completed_recently; then + echo Load high at $(date): waiting up to 30m to continue + exit 2 + fi + + autosens 2>&1 + touch /tmp/autosens-completed + echo Completed oref0-autons-loop at $(date) +} + +function overtemp { + # check for CPU temperature above 85°C + sensors -u 2>/dev/null | awk '$NF > 85' | grep input \ + && echo Edison is too hot: waiting for it to cool down at $(date)\ + && echo Please ensure rig is properly ventilated +} + +function highload { + # check whether system load average is high + uptime | awk '$NF > 2' | grep load +} + +function completed_recently { + find /tmp/ -mmin -30 | egrep -q "autosens-completed" +} + +# find settings/ -newer settings/autosens.json | grep -q pumphistory-24h-zoned.json || find settings/ -size -5c | grep -q autosens.json || ! find settings/ | grep -q autosens || ! find settings/autosens.json +# openaps use detect-sensitivity shell monitor/glucose.json settings/pumphistory-24h-zoned.json settings/insulin_sensitivities.json settings/basal_profile.json settings/profile.json monitor/carbhistory.json settings/temptargets.json +function autosens { + # only run autosens if pumphistory-24h is newer than autosens + if find settings/ -newer settings/autosens.json | grep -q pumphistory-24h-zoned.json \ + || find settings/ -size -5c | grep -q autosens.json \ + || ! find settings/ | grep -q autosens \ + || ! find settings/autosens.json >/dev/null; then + if oref0-detect-sensitivity monitor/glucose.json settings/pumphistory-24h-zoned.json settings/insulin_sensitivities.json settings/basal_profile.json settings/profile.json monitor/carbhistory.json settings/temptargets.json > settings/autosens.json.new && cat settings/autosens.json.new | jq .ratio | grep -q [0-9]; then + mv settings/autosens.json.new settings/autosens.json + echo -n "Autosens refreshed: " + else + echo -n "Failed to refresh autosens: using old autosens.json: " + fi + else + echo -n "No need to refresh autosens yet: " + fi + cat settings/autosens.json | jq . -C -c +} + +die() { + echo "$@" + exit 1 +} + +main "$@" diff --git a/bin/oref0-autotune-core.js b/bin/oref0-autotune-core.js new file mode 100755 index 000000000..5a69de8ea --- /dev/null +++ b/bin/oref0-autotune-core.js @@ -0,0 +1,63 @@ +#!/usr/bin/env node + +/* + oref0 autotuning tool + + Uses the output of oref0-autotune-prep.js + + Calculates adjustments to basal schedule, ISF, and CSF + + Released under MIT license. See the accompanying LICENSE.txt file for + full terms and conditions + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + +*/ + +var autotune = require('oref0/lib/autotune'); +var stringify = require('json-stable-stringify'); +function usage ( ) { + console.error('usage: ', process.argv.slice(0, 2), ' '); +} + +if (!module.parent) { + var prepped_glucose_input = process.argv[2]; + if ([null, '--help', '-h', 'help'].indexOf(prepped_glucose_input) > 0) { + usage( ); + process.exit(0) + } + var previous_autotune_input = process.argv[3]; + var pumpprofile_input = process.argv[4]; + + if (!prepped_glucose_input || !previous_autotune_input || !pumpprofile_input ) { + usage( ); + console.log('{ "error": "Insufficient arguments" }'); + process.exit(1); + } + + var fs = require('fs'); + try { + var prepped_glucose_data = JSON.parse(fs.readFileSync(prepped_glucose_input, 'utf8')); + var previous_autotune_data = JSON.parse(fs.readFileSync(previous_autotune_input, 'utf8')); + var pumpprofile_data = JSON.parse(fs.readFileSync(pumpprofile_input, 'utf8')); + } catch (e) { + console.log('{ "error": "Could not parse input data" }'); + return console.error("Could not parse input data: ", e); + } + + var inputs = { + preppedGlucose: prepped_glucose_data + , previousAutotune: previous_autotune_data + , pumpProfile: pumpprofile_data + }; + + var autotune_output = autotune(inputs); + console.log(stringify(autotune_output, { space: ' '})); +} + diff --git a/bin/oref0-autotune-dayofweek.sh b/bin/oref0-autotune-dayofweek.sh new file mode 100755 index 000000000..6ee04648a --- /dev/null +++ b/bin/oref0-autotune-dayofweek.sh @@ -0,0 +1,25 @@ +#!/bin/bash + +# This script allows you to run autotune separately for each day of the week + +[ -z "$OPENAPS_DIR" ] && OPENAPS_DIR="$1" +myopenaps="$OPENAPS_DIR" +nsurl=$2 +DOW=$(date +%u) + +if [ -z $myopenaps ] || [ -z $nsurl ]; then + echo "Usage: $0 ~/myopenaps http://mynightscouthost.herokuapp.com" + exit +fi + +# if we have a day of week profile file, copy that over before autotuning +if [ -e $myopenaps/autotune/profile-day$DOW.json ]; then + cp $myopenaps/autotune/profile-day$DOW.json $myopenaps/autotune/profile.json +fi + +# do the regular autotune and update autotune.json, and then +# copy the updated profile.json back to the day of week profile file +oref0-autotune -d=$myopenaps -n=$nsurl \ +&& cat $myopenaps/autotune/profile.json | json | grep -q start \ +&& cp $myopenaps/autotune/profile.json $myopenaps/settings/autotune.json \ +&& cp $myopenaps/autotune/profile.json $myopenaps/autotune/profile-day$DOW.json diff --git a/bin/oref0-autotune-export-to-xlsx.py b/bin/oref0-autotune-export-to-xlsx.py new file mode 100755 index 000000000..8746c088b --- /dev/null +++ b/bin/oref0-autotune-export-to-xlsx.py @@ -0,0 +1,191 @@ +#!/usr/bin/python +# This script converts the json files in the autotune directory +# to a Microsoft Excel file +# +# Released under MIT license. See the accompanying LICENSE.txt file for +# full terms and conditions +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. + +import json +import glob, os, sys + +# +try: + import xlsxwriter +except: + print "This software requires XlsxWriter package. Install it with 'sudo pip install XlsxWriter', see http://xlsxwriter.readthedocs.io/" + sys.exit(1) + +import datetime +import argparse +import re + +def parseDateAndRun(filename): + m=re.match( r'.*profile.(?P[0-9]*).(?P20[0-9][0-9]-[01][0-9]-[0-3][0-9]).json', filename) + if m: + return (m.group('date'), m.group('run')) + else: # not found + return ('0','0') + +def calc_minutes(timestr): + # returns the number of minutes from midnight. seconds are ignored + # based on http://stackoverflow.com/questions/10663720/converting-a-time-string-to-seconds-in-python + ftr = [60,1,0] # ignore seconds, count minutes, and use 60 minutes per hour + return sum([a*b for a,b in zip(ftr, map(int,timestr.split(':')))]) + +def expandProfile(l, valueField, offsetField): + r=[] + minutes=0 + value=l[0][valueField] + for i in range(len(l)): + start1=l[i]['start'] + minutes1=calc_minutes(start1) + offset1=l[i][offsetField] + if minutes1!=offset1: + print "Error in JSON offSetField %s contains %s does not match start time %s (%d minutes). Please report this as a bug" % (offsetField, offset1, start1, minutes1) + sys.exit(1) + while (minutes [pumpprofile.json] [carbhistory.json] [--categorize_uam_as_basal]'); +} + +if (!module.parent) { + var pumphistory_input = process.argv[2]; + if ([null, '--help', '-h', 'help'].indexOf(pumphistory_input) > 0) { + usage( ); + process.exit(0); + } + var profile_input = process.argv[3]; + var glucose_input = process.argv[4]; + var pumpprofile_input = process.argv[5]; + var carb_input = process.argv[6]; + var categorize_uam_as_basal_arg = process.argv[7]; + + var categorize_uam_as_basal = false; + + if ( !pumphistory_input || !profile_input || !glucose_input ) { + usage( ); + console.log('{ "error": "Insufficient arguments" }'); + process.exit(1); + } + + if (carb_input === '--categorize_uam_as_basal') { + categorize_uam_as_basal = true; + carb_input = undefined; + } else if (categorize_uam_as_basal_arg === '--categorize_uam_as_basal') { + categorize_uam_as_basal = true; + } else if (typeof categorize_uam_as_basal_arg !== 'undefined') { + usage( ); + process.exit(1); + } + + var fs = require('fs'); + try { + var pumphistory_data = JSON.parse(fs.readFileSync(pumphistory_input, 'utf8')); + var profile_data = JSON.parse(fs.readFileSync(profile_input, 'utf8')); + } catch (e) { + console.log('{ "error": "Could not parse input data" }'); + return console.error("Could not parse input data: ", e); + } + + var pumpprofile_data = { }; + if (typeof pumpprofile_input != 'undefined') { + try { + pumpprofile_data = JSON.parse(fs.readFileSync(pumpprofile_input, 'utf8')); + } catch (e) { + console.error("Warning: could not parse "+pumpprofile_input); + } + } + + // disallow impossibly low carbRatios due to bad decoding + if ( typeof(profile_data.carb_ratio) == 'undefined' || profile_data.carb_ratio < 2 ) { + if ( typeof(pumpprofile_data.carb_ratio) == 'undefined' || pumpprofile_data.carb_ratio < 2 ) { + console.log('{ "carbs": 0, "mealCOB": 0, "reason": "carb_ratios ' + profile_data.carb_ratio + ' and ' + pumpprofile_data.carb_ratio + ' out of bounds" }'); + return console.error("Error: carb_ratios " + profile_data.carb_ratio + ' and ' + pumpprofile_data.carb_ratio + " out of bounds"); + } else { + profile_data.carb_ratio = pumpprofile_data.carb_ratio; + } + } + + try { + var glucose_data = JSON.parse(fs.readFileSync(glucose_input, 'utf8')); + } catch (e) { + console.error("Warning: could not parse "+glucose_input); + } + + var carb_data = { }; + if (typeof carb_input != 'undefined') { + try { + carb_data = JSON.parse(fs.readFileSync(carb_input, 'utf8')); + } catch (e) { + console.error("Warning: could not parse "+carb_input); + } + } + + var inputs = { + history: pumphistory_data + , profile: profile_data + , pumpprofile: pumpprofile_data + , carbs: carb_data + , glucose: glucose_data + , categorize_uam_as_basal: categorize_uam_as_basal + }; + + var prepped_glucose = generate(inputs); + console.log(JSON.stringify(prepped_glucose)); +} + diff --git a/bin/oref0-autotune-recommends-report.sh b/bin/oref0-autotune-recommends-report.sh new file mode 100755 index 000000000..95bc759e2 --- /dev/null +++ b/bin/oref0-autotune-recommends-report.sh @@ -0,0 +1,120 @@ +#!/bin/bash + +# This script creates a Summary Report of Autotune Recommendations. The report itself is +# structured in such a way intended to give the end user a quick look at what needs to change +# on their pump. Report is stored in the autotune sub-directory within the user's OpenAPS +# directory. +# +# Released under MIT license. See the accompanying LICENSE.txt file for +# full terms and conditions +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. +# +# Example usage: ~/src/oref0/bin/oref0-autotune-recommends-report.sh + +# fix problems with locales with printf output +LC_NUMERIC=en_US.UTF-8 + +die() { + echo "$@" + exit 1 +} + +# Use alternate date command if on OS X: +shopt -s expand_aliases + +if [[ `uname` == 'Darwin' ]] ; then + alias date='gdate' +fi + +if [ $# -ne 1 ]; then + echo "Usage: ./oref0-autotune-recommends-report.sh " + exit 1 +fi + +# OpenAPS Directory Input +directory=$1 + +# Set report filename and delete the old one if it exists +report_file=$directory/autotune/autotune_recommendations.log +[ -f $report_file ] && rm $report_file + +# Report Column Widths +parameter_width=15 +data_width=9 + +# Get current profile info +basal_minutes_current=( $(jq -r '.basalprofile[].minutes' $directory/autotune/profile.pump.json) ) +basal_rate_current=( $(jq -r '.basalprofile[].rate' $directory/autotune/profile.pump.json) ) +isf_current=$(cat $directory/autotune/profile.pump.json | jq '.isfProfile.sensitivities[0].sensitivity') +csf_current=$(cat $directory/autotune/profile.pump.json | jq '.csf') +carb_ratio_current=$(cat $directory/autotune/profile.pump.json | jq '.carb_ratio') + +# Get autotune profile info +basal_minutes_new=( $(jq -r '.basalprofile[].minutes' $directory/autotune/profile.json) ) +basal_rate_new=( $(jq -r '.basalprofile[].rate' $directory/autotune/profile.json) ) +isf_new=$(cat $directory/autotune/profile.json | jq '.isfProfile.sensitivities[0].sensitivity') +csf_new=$(cat $directory/autotune/profile.json | jq '.csf') +carb_ratio_new=$(cat $directory/autotune/profile.json | jq '.carb_ratio') + +# Print Header Info +printf "%-${parameter_width}s| %-${data_width}s| %-${data_width}s\n" "Parameter" "Pump" "Autotune" >> $report_file +printf "%s\n" "-------------------------------------" >> $report_file + +# Print ISF, CSF and Carb Ratio Recommendations +printf "%-${parameter_width}s| %-${data_width}.3f| %-${data_width}.3f\n" "ISF [mg/dL/U]" $isf_current $isf_new >> $report_file +# if [ $csf_current != null ]; then + # printf "%-${parameter_width}s| %-${data_width}.3f| %-${data_width}.3f\n" "CSF [mg/dL/g]" $csf_current $csf_new >> $report_file +# else + # printf "%-${parameter_width}s| %-${data_width}s| %-${data_width}.3f\n" "CSF [mg/dL/g]" "n/a" $csf_new >> $report_file +# fi +printf "%-${parameter_width}s| %-${data_width}.3f| %-${data_width}.3f\n" "Carb Ratio[g/U]" $carb_ratio_current $carb_ratio_new >> $report_file + +# Print Basal Profile Recommendations +printf "%-${parameter_width}s| %-${data_width}s|\n" "Basals [U/hr]" "-" >> $report_file + +# Build time_list array of H:M in 30 minute increments to mirror pump basal schedule +time_list=() +minutes_list=() +end_time=23:30 +time=00:00 +minutes=0 +for h in $(seq -w 0 23); do + for m in 00 30; do + time="$h:$m" + minutes=$(echo "60 * $h + $m" | bc) + #echo $time $minutes + time_list+=( "$time" ) + minutes_list+=( "$minutes" ) + done +done + +for (( i=0; i<${#minutes_list[@]}; i++ )) +do + # Check for current entry (account for 1-based index from grep) + basal_index_current=$(printf "%s\n" ${basal_minutes_current[@]}|grep -nw ${minutes_list[$i]} | sed 's/:.*//') + if [[ ${#basal_index_current} != 0 ]]; then + rate_current=${basal_rate_current[$(($basal_index_current - 1))]} + fi + # Check for autotune entry (account for 1-based index from grep) + basal_index_new=$(printf "%s\n" ${basal_minutes_new[@]}|grep -nw ${minutes_list[$i]} | sed 's/:.*//') + if [[ ${#basal_index_new} != 0 ]]; then + rate_new=${basal_rate_new[$((${basal_index_new} - 1))]} + fi + # Print this basal profile recommend based on data availability at this time + if [[ ${#basal_index_current} == 0 ]] && [[ ${#basal_index_new} == 0 ]]; then + printf " %-$(expr ${parameter_width} - 2)s| %-${data_width}s| %-${data_width}s\n" ${time_list[$i]} "" "" >> $report_file + elif [[ ${#basal_index_current} == 0 ]] && [[ ${#basal_index_new} != 0 ]]; then + printf " %-$(expr ${parameter_width} - 2)s| %-${data_width}s| %-${data_width}.3f\n" ${time_list[$i]} "" $rate_new >> $report_file + elif [[ ${#basal_index_current} != 0 ]] && [[ ${#basal_index_new} == 0 ]]; then + printf " %-$(expr ${parameter_width} - 2)s| %-${data_width}s| %-${data_width}s\n" ${time_list[$i]} $rate_current "" >> $report_file + else + printf " %-$(expr ${parameter_width} - 2)s| %-${data_width}.3f| %-${data_width}.3f\n" ${time_list[$i]} $rate_current $rate_new >> $report_file + fi +done diff --git a/bin/oref0-autotune.py b/bin/oref0-autotune.py new file mode 100755 index 000000000..5d901d039 --- /dev/null +++ b/bin/oref0-autotune.py @@ -0,0 +1,252 @@ +# Python version of oref0-autotune.sh +# Original bash code: scottleibrand, pietergit, beached, danamlewis + +# This script sets up an easy test environment for autotune, allowing the user to vary parameters +# like start/end date and number of runs. +# +# Required Inputs: +# DIR, (--dir=) +# NIGHTSCOUT_HOST, (--ns-host=) +# Optional Inputs: +# END_DATE, (--end-date=) +# if no end date supplied, assume we want a months worth or until day before current day +# NUMBER_OF_RUNS (--runs=) +# if no number of runs designated, then default to 5 +# EXPORT_EXCEL (--xlsx=) +# export to excel. Disabled by default +# TERMINAL_LOGGING (--log +# logs terminal output to autotune..log in the autotune directory, default to true + + +import argparse +import requests +import datetime +import os, errno +import logging +from subprocess import call +import shutil + + +DIR = '' +NIGHTSCOUT_HOST = '' +START_DATE = datetime.datetime.today() - datetime.timedelta(days=1) +END_DATE = datetime.datetime.today() +NUMBER_OF_RUNS = 1 +EXPORT_EXCEL = None +TERMINAL_LOGGING = True +RECOMMENDS_REPORT = True + +def get_input_arguments(): + parser = argparse.ArgumentParser(description='Autotune') + + # Required + # NOTE: As the code runs right now, this directory needs to exist and as well as the subfolders: autotune, settings + parser.add_argument('--dir', + '-d', + type=str, + required=True, + help='(--dir=)') + parser.add_argument('--ns-host', + '-n', + type=str, + required=True, + metavar='NIGHTSCOUT_HOST', + help='(--ns-host= ), output prepped glucose + # data or below + # oref0-autotune-prep ns-treatments.json profile.json ns-entries.$DATE.json > autotune.$RUN_NUMBER.$DATE.json + ns_treatments = os.path.join(autotune_directory, 'ns-treatments.json') + profile = os.path.join(autotune_directory, 'profile.json') + ns_entries = os.path.join(autotune_directory, 'ns-entries.{date}.json'.format(date=date.strftime("%Y-%m-%d"))) + autotune_prep = 'oref0-autotune-prep {ns_treatments} {profile} {ns_entries}'.format(ns_treatments=ns_treatments, profile=profile, ns_entries=ns_entries) + + # autotune.$RUN_NUMBER.$DATE.json + autotune_run_filename = os.path.join(autotune_directory, 'autotune.{run_number}.{date}.json' + .format(run_number=run_number, date=date.strftime("%Y-%m-%d"))) + with open(autotune_run_filename, "w+") as output: + logging.info('Running {script}'.format(script=autotune_prep)) + call(autotune_prep, stdout=output, shell=True) + logging.info('Writing output to {filename}'.format(filename=autotune_run_filename)) + + # Autotune (required args, ), + # output autotuned profile or what will be used as in the next iteration + # oref0-autotune-core autotune.$RUN_NUMBER.$DATE.json profile.json profile.pump.json > newprofile.$RUN_NUMBER.$DATE.json + + # oref0-autotune-core autotune.$run_number.$i.json profile.json profile.pump.json > newprofile.$RUN_NUMBER.$DATE.json + profile_pump = os.path.join(autotune_directory, 'profile.pump.json') + autotune_core = 'oref0-autotune-core {autotune_run} {profile} {profile_pump}'.format(profile=profile, profile_pump = profile_pump, autotune_run=autotune_run_filename) + + # newprofile.$RUN_NUMBER.$DATE.json + newprofile_run_filename = os.path.join(autotune_directory, 'newprofile.{run_number}.{date}.json' + .format(run_number=run_number, date=date.strftime("%Y-%m-%d"))) + with open(newprofile_run_filename, "w+") as output: + logging.info('Running {script}'.format(script=autotune_core)) + call(autotune_core, stdout=output, shell=True) + logging.info('Writing output to {filename}'.format(filename=autotune_run_filename)) + + # Copy tuned profile produced by autotune to profile.json for use with next day of data + # cp newprofile.$RUN_NUMBER.$DATE.json profile.json + shutil.copy(os.path.join(autotune_directory, 'newprofile.{run_number}.{date}.json'.format(run_number=run_number, date=date.strftime("%Y-%m-%d"))), + os.path.join(autotune_directory, 'profile.json')) + +def export_to_excel(output_directory, output_excel_filename): + autotune_export_to_xlsx = 'oref0-autotune-export-to-xlsx --dir {0} --output {1}'.format(output_directory, output_excel_filename) + call(autotune_export_to_xlsx, shell=True) + +def create_summary_report_and_display_results(output_directory): + print + print "Autotune pump profile recommendations:" + print "---------------------------------------------------------" + + report_file = os.path.join(output_directory, 'autotune', 'autotune_recommendations.log') + autotune_recommends_report = 'oref0-autotune-recommends-report {0}'.format(output_directory) + + call(autotune_recommends_report, shell=True) + print "Recommendations Log File: {0}".format(report_file) + + # Go ahead and echo autotune_recommendations.log to the terminal, minus blank lines + # cat $report_file | egrep -v "\| *\| *$" + call(['cat {0} | egrep -v "\| *\| *$"'.format(report_file)], shell=True) + +if __name__ == "__main__": + # Set log level for this app to DEBUG. + logging.basicConfig(level=logging.DEBUG) + # Supress non-essential logs (below WARNING) from requests module. + logging.getLogger("requests").setLevel(logging.WARNING) + + args = get_input_arguments() + assign_args_to_variables(args) + + # TODO: Convert Nightscout profile to OpenAPS profile format. + #get_nightscout_profile(NIGHTSCOUT_HOST) + + get_openaps_profile(DIR) + get_nightscout_carb_and_insulin_treatments(NIGHTSCOUT_HOST, START_DATE, END_DATE, DIR) + get_nightscout_bg_entries(NIGHTSCOUT_HOST, START_DATE, END_DATE, DIR) + run_autotune(START_DATE, END_DATE, NUMBER_OF_RUNS, DIR) + + if EXPORT_EXCEL: + export_to_excel(DIR, EXPORT_EXCEL) + + if RECOMMENDS_REPORT: + create_summary_report_and_display_results(DIR) diff --git a/bin/oref0-autotune.sh b/bin/oref0-autotune.sh new file mode 100755 index 000000000..dffb60e9c --- /dev/null +++ b/bin/oref0-autotune.sh @@ -0,0 +1,271 @@ +#!/bin/bash + +# This script sets up an easy test environment for autotune, allowing the user to vary parameters +# like start/end date. +# +# Required Inputs: +# DIR, (--dir=) +# NIGHTSCOUT_HOST, (--ns-host=) +# Optional Inputs: +# END_DATE, (--end-date=) +# if no end date supplied, assume we want a months worth or until day before current day +# EXPORT_EXCEL (--xlsx=) +# export to excel. Disabled by default +# TERMINAL_LOGGING (--log +# logs terminal output to autotune..log in the autotune directory, default to true +# +# Released under MIT license. See the accompanying LICENSE.txt file for +# full terms and conditions +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. + +die() { + if [[ -z "$API_SECRET" ]]; then + echo "Warning: API_SECRET is not set when calling oref0-autotune.sh" + echo "(this is only a problem if you have locked down read-only access to your NS)." + fi + + echo "$@" + exit 1 +} + +# defaults +CURL_FLAGS="--compressed" +DIR="" +NIGHTSCOUT_HOST="" +START_DATE="" +END_DATE="" +START_DAYS_AGO=1 # Default to yesterday if not otherwise specified +END_DAYS_AGO=1 # Default to yesterday if not otherwise specified +EXPORT_EXCEL="" # Default is to not export to Microsoft Excel +TERMINAL_LOGGING=true +CATEGORIZE_UAM_AS_BASAL=false +RECOMMENDS_REPORT=true +UNKNOWN_OPTION="" + +if [ -n "${API_SECRET_READ}" ]; then + echo "WARNING: API_SECRET_READ is deprecated starting with oref 0.6.x. The Nightscout authentication information is now used from the API_SECRET environment variable" +fi + +# If we are running OS X, we need to use a different version +# of the 'date' command; the built-in 'date' is BSD, which +# has fewer options than the linux version. So the user +# needs to install coreutils, which gives the GNU 'date' +# command as 'gdate': + +shopt -s expand_aliases + +if [[ `uname` == 'Darwin' ]] ; then + alias date='gdate' +fi + +# handle input arguments +for i in "$@" +do +case $i in + -d=*|--dir=*) + DIR="${i#*=}" + # ~/ paths have to be expanded manually + DIR="${DIR/#\~/$HOME}" + # If DIR is a symlink, get actual path: + if [[ -L $DIR ]] ; then + directory="$(readlink $DIR)" + else + directory="$DIR" + fi + shift # past argument=value + ;; + -n=*|--ns-host=*) + NIGHTSCOUT_HOST="${i#*=}" + shift # past argument=value + ;; + -s=*|--start-date=*) + START_DATE="${i#*=}" + START_DATE=`date --date="$START_DATE" +%Y-%m-%d` + shift # past argument=value + ;; + -e=*|--end-date=*) + END_DATE="${i#*=}" + END_DATE=`date --date="$END_DATE" +%Y-%m-%d` + shift # past argument=value + ;; + -t=*|--start-days-ago=*) + START_DAYS_AGO="${i#*=}" + shift # past argument=value + ;; + -d=*|--end-days-ago=*) + END_DAYS_AGO="${i#*=}" + shift # past argument=value + ;; + -x=*|--xlsx=*) + EXPORT_EXCEL="${i#*=}" + shift # past argument=value + ;; + -l=*|--log=*) + TERMINAL_LOGGING="${i#*=}" + shift + ;; + -c=*|--categorize-uam-as-basal=*) + CATEGORIZE_UAM_AS_BASAL="${i#*=}" + shift + ;; + *) + # unknown option + echo "Option ${i#*=} unknown" + UNKNOWN_OPTION="yes" + ;; +esac +done + +# remove any trailing / from NIGHTSCOUT_HOST +NIGHTSCOUT_HOST=$(echo $NIGHTSCOUT_HOST | sed 's/\/$//g') + +if [[ -z "$DIR" || -z "$NIGHTSCOUT_HOST" ]]; then + echo "Usage: oref0-autotune <--dir=myopenaps_directory> <--ns-host=https://mynightscout.azurewebsites.net> [--start-days-ago=number_of_days] [--end-days-ago=number_of_days] [--start-date=YYYY-MM-DD] [--end-date=YYYY-MM-DD] [--xlsx=autotune.xlsx] [--log=(true)|false] [--categorize-uam-as-basal=true|(false)]" +exit 1 +fi +if [[ -z "$START_DATE" ]]; then + # Default start date of yesterday + START_DATE=`date --date="$START_DAYS_AGO days ago" +%Y-%m-%d` +fi +if [[ -z "$END_DATE" ]]; then + # Default end-date as this morning at midnight in order to not get partial day samples for now + # (ISF/CSF adjustments are still single values across each day) + END_DATE=`date --date="$END_DAYS_AGO days ago" +%Y-%m-%d` +fi + +if [[ -z "$UNKNOWN_OPTION" ]] ; then # everything is ok + echo "Running oref0-autotune --dir=$DIR --ns-host=$NIGHTSCOUT_HOST --start-date=$START_DATE --end-date=$END_DATE --categorize-uam-as-basal=$CATEGORIZE_UAM_AS_BASAL" +else + echo "Unknown options. Exiting" + exit 1 +fi + +# Get profile for testing copied to home directory. +cd $directory && mkdir -p autotune +cp settings/pumpprofile.json autotune/profile.pump.json || die "Cannot copy settings/pumpprofile.json" +# This allows manual users to be able to run autotune by simply creating a settings/pumpprofile.json file. +if [[ `uname` == 'Darwin' ]] ; then + cp settings/pumpprofile.json settings/profile.json || die "Cannot copy settings/pumpprofile.json" +else + cp -up settings/pumpprofile.json settings/profile.json || die "Cannot copy settings/pumpprofile.json" +fi +# If a previous valid settings/autotune.json exists, use that; otherwise start from settings/profile.json +cp settings/autotune.json autotune/profile.json && cat autotune/profile.json | jq . | grep -q start || cp autotune/profile.pump.json autotune/profile.json +cd autotune + +# Turn on stderr logging, if enabled (default to true) +if [[ $TERMINAL_LOGGING = "true" ]]; then + # send stderr to a file as well as the terminal + exec &> >(tee -a autotune.$(date +%Y-%m-%d-%H%M%S).log) +fi + +# Build date list for autotune iteration +date_list=() +date=$START_DATE; +while : +do + date_list+=( "$date" ) + if [ $date != "$END_DATE" ]; then + date="$(date --date="$date + 1 days" +%Y-%m-%d)"; + else + break + fi +done + +echo "Compressing old json and log files to save space..." +gzip -f ns-*.json +gzip -f autotune*.json +# only gzip autotune log files more than 2 days old +find autotune.*.log -mtime +2 | while read file; do gzip -f $file; done +echo "Autotune disk usage:" +du -h . +echo "Overall disk used/avail:" +df -h . + +echo "Grabbing NIGHTSCOUT treatments.json and entries/sgv.json for date range..." + +# Get Nightscout BG (sgv.json) Entries +for i in "${date_list[@]}" +do + # pull CGM data from 4am-4am + query="find%5Bdate%5D%5B%24gte%5D=`(date -d "$i +4 hours " +%s | tr -d '\n'; echo 000)`&find%5Bdate%5D%5B%24lte%5D=`(date --date="$i +28 hours" +%s | tr -d '\n'; echo 000)`&count=1000" + echo Query: $NIGHTSCOUT_HOST $query + ns-get host $NIGHTSCOUT_HOST entries/sgv.json $query > ns-entries.$i.json || die "Couldn't download ns-entries.$i.json" + ls -la ns-entries.$i.json || die "No ns-entries.$i.json downloaded" + + # Get Nightscout carb and insulin Treatments + # echo $i $START_DATE; + #query="find%5Bdate%5D%5B%24gte%5D=`(date -d $i +%s | tr -d'\n'; echo 000)`&find%5Bdate%5D%5B%24lte%5D=`(date --date="$i +1 days" +%s | tr -d '\n'; echo 000)`&count=1000" + # to capture UTC-dated treatments, we need to capture an extra 12h on either side, plus the DIA lookback + # 18h = 12h for timezones + 6h for DIA; 40h = 28h for 4am + 12h for timezones + query="find%5Bcreated_at%5D%5B%24gte%5D=`date --date="$i -18 hours" -Iminutes`&find%5Bcreated_at%5D%5B%24lte%5D=`date --date="$i +42 hours" -Iminutes`" + echo Query: $NIGHTSCOUT_HOST/$query + ns-get host $NIGHTSCOUT_HOST treatments.json $query > ns-treatments.$i.json || die "Couldn't download ns-treatments.$i.json" + ls -la ns-treatments.$i.json || die "No ns-treatments.$i.json downloaded" + + + # Do iterative runs over date range, save autotune.json (prepped data) and input/output profile.json + cp profile.json profile.$i.json + # Autotune Prep (required args, ), output prepped glucose + # data or below + if [[ $CATEGORIZE_UAM_AS_BASAL = "true" ]]; then + CATEGORIZE_UAM_AS_BASAL_OPT="--categorize_uam_as_basal" + else + CATEGORIZE_UAM_AS_BASAL_OPT= + fi + echo "oref0-autotune-prep ns-treatments.$i.json profile.json ns-entries.$i.json profile.pump.json $CATEGORIZE_UAM_AS_BASAL_OPT > autotune.$i.json" + oref0-autotune-prep ns-treatments.$i.json profile.json ns-entries.$i.json profile.pump.json $CATEGORIZE_UAM_AS_BASAL_OPT > autotune.$i.json \ + || die "Could not run oref0-autotune-prep ns-treatments.$i.json profile.json ns-entries.$i.json" + + # Autotune (required args, ), + # output autotuned profile or what will be used as in the next iteration + echo "oref0-autotune-core autotune.$i.json profile.json profile.pump.json > newprofile.$i.json" + if ! oref0-autotune-core autotune.$i.json profile.json profile.pump.json > newprofile.$i.json; then + if cat profile.json | jq --exit-status .carb_ratio==null; then + echo "ERROR: profile.json contains null carb_ratio: using profile.pump.json" + cp profile.pump.json profile.json + exit + else + die "Could not run oref0-autotune-core autotune.$i.json profile.json profile.pump.json" + fi + else + # Copy tuned profile produced by autotune to profile.json for use with next day of data + cp newprofile.$i.json profile.json + fi + + + if ! [[ -z "$EXPORT_EXCEL" ]]; then + echo Exporting to $EXPORT_EXCEL + oref0-autotune-export-to-xlsx --dir $DIR --output $EXPORT_EXCEL + fi + + # Create Summary Report of Autotune Recommendations and display in the terminal + if [[ $RECOMMENDS_REPORT == "true" ]]; then + # Set the report file name, so we can let the user know where it is and cat + # it to the screen + report_file=$directory/autotune/autotune_recommendations.log + + echo + echo "Autotune pump profile recommendations:" + echo "---------------------------------------------------------" + + # Let the user know where the Autotune Recommendations are logged + echo "Recommendations Log File: $report_file" + echo + + # Run the Autotune Recommends Report + oref0-autotune-recommends-report $directory + + # Go ahead and echo autotune_recommendations.log to the terminal, minus blank lines + cat $report_file | egrep -v "\| *\| *$" + fi + +done # End Date Range Iteration diff --git a/bin/oref0-bluetoothup.sh b/bin/oref0-bluetoothup.sh new file mode 100755 index 000000000..0b74f8a1a --- /dev/null +++ b/bin/oref0-bluetoothup.sh @@ -0,0 +1,20 @@ +#!/bin/bash + +# start bluetoothd if bluetoothd is not running +if ! ( ps -fC bluetoothd ) ; then + sudo /usr/local/bin/bluetoothd & +fi + +if getent passwd edison && ! ( hciconfig -a | grep -q "PSCAN" ) ; then + sudo killall bluetoothd + sudo /usr/local/bin/bluetoothd & +fi + +if ( hciconfig -a | grep -q "DOWN" ) ; then + sudo hciconfig hci0 up + sudo /usr/local/bin/bluetoothd & +fi + +if !( hciconfig -a | grep -q $HOSTNAME ) ; then + sudo hciconfig hci0 name $HOSTNAME +fi diff --git a/bin/oref0-calculate-iob.js b/bin/oref0-calculate-iob.js index b0636063a..0cb29b6b9 100755 --- a/bin/oref0-calculate-iob.js +++ b/bin/oref0-calculate-iob.js @@ -19,14 +19,23 @@ */ var generate = require('oref0/lib/iob'); +function usage ( ) { + console.log('usage: ', process.argv.slice(0, 2), ' [autosens.json]'); + +} if (!module.parent) { - var pumphistory_input = process.argv.slice(2, 3).pop(); - var profile_input = process.argv.slice(3, 4).pop(); - var clock_input = process.argv.slice(4, 5).pop(); + var pumphistory_input = process.argv[2]; + if ([null, '--help', '-h', 'help'].indexOf(pumphistory_input) > 0) { + usage( ); + process.exit(0) + } + var profile_input = process.argv[3]; + var clock_input = process.argv[4]; + var autosens_input = process.argv[5]; if (!pumphistory_input || !profile_input) { - console.log('usage: ', process.argv.slice(0, 2), ' '); + usage( ); process.exit(1); } @@ -35,6 +44,14 @@ if (!module.parent) { var profile_data = require(cwd + '/' + profile_input); var clock_data = require(cwd + '/' + clock_input); + var autosens_data = null; + if (autosens_input) { + try { + var autosens_data = require(cwd + '/' + autosens_input); + } catch (e) {} + //console.error(autosens_input, JSON.stringify(autosens_data)); + } + // all_data.sort(function (a, b) { return a.date > b.date }); var inputs = { @@ -42,6 +59,9 @@ if (!module.parent) { , profile: profile_data , clock: clock_data }; + if ( autosens_data ) { + inputs.autosens = autosens_data; + } var iob = generate(inputs); console.log(JSON.stringify(iob)); diff --git a/bin/oref0-conditional-run.sh b/bin/oref0-conditional-run.sh new file mode 100755 index 000000000..b448b2df6 --- /dev/null +++ b/bin/oref0-conditional-run.sh @@ -0,0 +1,38 @@ +#!/bin/bash + +export GENERATE=false +export FILE=$1 +export FILE2=$2 +export COMMAND=$3 + +if test ! -n "$FILE"; then + echo "Usage: oref0-crun " + exit +fi + +if test ! -f $FILE; then + echo "$FILE not found, invoking report" + GENERATE=true +fi + +if test -n "$(find settings/ -size -5c | grep $FILE)"; then + echo "$FILE under 5 bytes, invoking report" + GENERATE=true +fi + +if test -n "$FILE2"; then + if test -n "$(find settings/ -newer $FILE | grep $FILE2)"; then + echo "$FILE older than $FILE2, invoking report" + GENERATE=true + fi +fi + +if [ "$GENERATE" = true ]; then + if test -n "$COMMAND"; then + openaps $COMMAND + else + openaps report invoke $FILE + fi +else + echo "$FILE exists and is new, skipping invoke" +fi \ No newline at end of file diff --git a/bin/oref0-copy-fresher b/bin/oref0-copy-fresher new file mode 100755 index 000000000..4d9f12081 --- /dev/null +++ b/bin/oref0-copy-fresher @@ -0,0 +1,37 @@ +#!/bin/bash +self=$(basename $0) +WITHIN=0 + +function usage ( ) { +cat <] [...] +cat files mentioned. +If --since seconds is specified, the file will only be cat'd if the files last +modification occurred within . +Default is 0, it will cat all files. +EOF +} +case $1 in + --help|-h|help) + usage + exit 0 + ;; + --since) + shift + WITHIN=$1 + shift + ;; +esac + + +for file in $* ; do + if [[ -f $file && ($WITHIN -eq 0 || $(expr $(date +%s) - $(date +%s -r $file)) -lt $WITHIN) ]] ; then + cat $file + fi +done + + + # 2783 test $(expr $(date +%s) - $(date +%s -r openaps.ini )) -gt 1000 && echo "OK" || echo "NOT" + # 2784 test $(expr $(date +%s) - $(date +%s -r openaps.ini )) -gt 1000000 && echo "OK" || echo "NOT" + # 2785 history | tail -n 3 > blah + diff --git a/bin/oref0-delete-future-entries.sh b/bin/oref0-delete-future-entries.sh new file mode 100755 index 000000000..da5335991 --- /dev/null +++ b/bin/oref0-delete-future-entries.sh @@ -0,0 +1,22 @@ +#!/bin/bash + +# Since the Edison does not have an internal clock +# after a reboot if you do not have the correct time your date will be older than +# the time on the CGM data in the monitor folder. +# Currently all the checks for time in the system is looking at data being older than current +# time +# This will delete all the data in the +# monitor directory. Allowing oref0 to gather all of the data again in pump-loop + +NEWTIME=$(date -d `(jq .[1].display_time monitor/glucose.json; echo ) | sed 's/"//g'` +%s) +TIME=$(date --date '5 minutes' +%s) + +echo $NEWTIME +echo $TIME + +if [ $NEWTIME -gt $TIME ]; then + echo CGM Time is newer than Edison Time$'\n'Deleting All Monitor Files + sudo rm -rf monitor/* +elif [ $NEWTIME -lt $TIME ]; then + echo "No Newer CGM Data found" +fi diff --git a/bin/oref0-detect-sensitivity.js b/bin/oref0-detect-sensitivity.js new file mode 100755 index 000000000..246a87393 --- /dev/null +++ b/bin/oref0-detect-sensitivity.js @@ -0,0 +1,172 @@ +#!/usr/bin/env node + +/* + Determine Basal + + Released under MIT license. See the accompanying LICENSE.txt file for + full terms and conditions + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ + +var basal = require('oref0/lib/profile/basal'); +var get_iob = require('oref0/lib/iob'); +var detect = require('oref0/lib/determine-basal/autosens'); + +if (!module.parent) { + var detectsensitivity = init(); + + var glucose_input = process.argv[2]; + var pumphistory_input = process.argv[3]; + var isf_input = process.argv[4] + var basalprofile_input = process.argv[5] + var profile_input = process.argv[6]; + var carb_input = process.argv[7] + var temptarget_input = process.argv[8] + + if (!glucose_input || !pumphistory_input || !profile_input) { + console.error('usage: ', process.argv.slice(0, 2), ' [carbhistory.json] [temptargets.json]'); + process.exit(1); + } + + var fs = require('fs'); + try { + var cwd = process.cwd(); + var glucose_data = require(cwd + '/' + glucose_input); + // require 6 hours of data to run autosens + if (glucose_data.length < 72) { + console.error("Optional feature autosens disabled: not enough glucose data to calculate sensitivity"); + return console.log('{ "ratio": 1, "reason": "not enough glucose data to calculate autosens" }'); + //process.exit(2); + } + + var pumphistory_data = require(cwd + '/' + pumphistory_input); + var profile = require(cwd + '/' + profile_input); + + var isf_data = require(cwd + '/' + isf_input); + if (isf_data.units !== 'mg/dL') { + if (isf_data.units == 'mmol/L') { + for (var i = 0, len = isf_data.sensitivities.length; i < len; i++) { + isf_data.sensitivities[i].sensitivity = isf_data.sensitivities[i].sensitivity * 18; + } + isf_data.units = 'mg/dL'; + } else { + console.log('ISF is expected to be expressed in mg/dL or mmol/L.' + , 'Found', isf_data.units, 'in', isf_input, '.'); + process.exit(2); + } + } + var basalprofile = require(cwd + '/' + basalprofile_input); + + var carb_data = { }; + if (typeof carb_input != 'undefined') { + try { + carb_data = JSON.parse(fs.readFileSync(carb_input, 'utf8')); + } catch (e) { + console.error("Warning: could not parse "+carb_input); + } + } + + var temptarget_data = { }; + if (typeof temptarget_input != 'undefined') { + try { + temptarget_data = JSON.parse(fs.readFileSync(temptarget_input, 'utf8')); + } catch (e) { + console.error("Warning: could not parse "+temptarget_input); + } + } + + var iob_inputs = { + history: pumphistory_data + , profile: profile + //, clock: clock_data + }; + } catch (e) { + return console.error("Could not parse input data: ", e); + } + + var detection_inputs = { + iob_inputs: iob_inputs + , carbs: carb_data + , glucose_data: glucose_data + , basalprofile: basalprofile + , temptargets: temptarget_data + //, clock: clock_data + }; + console.error("Calculating sensitivity using 8h of non-exluded data"); + detection_inputs.deviations = 96; + detect(detection_inputs); + ratio8h = ratio; + 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; + if ( ratio8h < ratio24h ) { + console.error("Using 8h autosens ratio of",ratio8h,"(ISF",newisf8h+")"); + } else { + console.error("Using 24h autosens ratio of",ratio24h,"(ISF",newisf24h+")"); + } + var lowestRatio = Math.min(ratio8h, ratio24h); + var sensAdj = { + "ratio": lowestRatio + } + return console.log(JSON.stringify(sensAdj)); + +} + +function init() { + + var detectsensitivity = { + name: 'detect-sensitivity' + , label: "OpenAPS Detect Sensitivity" + }; + + //detectsensitivity.getLastGlucose = require('../lib/glucose-get-last'); + //detectsensitivity.detect_sensitivity = require('../lib/determine-basal/determine-basal'); + return detectsensitivity; + +} +module.exports = init; + +// From https://gist.github.com/IceCreamYou/6ffa1b18c4c8f6aeaad2 +// Returns the value at a given percentile in a sorted numeric array. +// "Linear interpolation between closest ranks" method +function percentile(arr, p) { + if (arr.length === 0) return 0; + if (typeof p !== 'number') throw new TypeError('p must be a number'); + if (p <= 0) return arr[0]; + if (p >= 1) return arr[arr.length - 1]; + + var index = arr.length * p, + lower = Math.floor(index), + upper = lower + 1, + weight = index % 1; + + if (upper >= arr.length) return arr[lower]; + return arr[lower] * (1 - weight) + arr[upper] * weight; +} + +// Returns the percentile of the given value in a sorted numeric array. +function percentRank(arr, v) { + if (typeof v !== 'number') throw new TypeError('v must be a number'); + for (var i = 0, l = arr.length; i < l; i++) { + if (v <= arr[i]) { + while (i < l && v === arr[i]) i++; + if (i === 0) return 0; + if (v !== arr[i-1]) { + i += (v - arr[i-1]) / (arr[i] - arr[i-1]); + } + return i / l; + } + } + return 1; +} + diff --git a/bin/oref0-determine-basal.js b/bin/oref0-determine-basal.js index 02eabe258..ad193853a 100755 --- a/bin/oref0-determine-basal.js +++ b/bin/oref0-determine-basal.js @@ -14,52 +14,196 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ + /* istanbul ignore next */ if (!module.parent) { var determinebasal = init(); - var iob_input = process.argv.slice(2, 3).pop(); - var currenttemp_input = process.argv.slice(3, 4).pop(); - var glucose_input = process.argv.slice(4, 5).pop(); - var profile_input = process.argv.slice(5, 6).pop(); - var offline = process.argv.slice(6, 7).pop(); + var argv = require('yargs') + .usage("$0 iob.json currenttemp.json glucose.json profile.json [[--auto-sens] autosens.json] [meal.json] [--reservoir reservoir.json]") + .option('auto-sens', { + alias: 'a', + describe: "Auto-sensitivity configuration", + default: true + + }) + .option('reservoir', { + alias: 'r', + describe: "Reservoir status file for SuperMicroBolus mode (oref1)", + default: false + + }) + .option('meal', { + describe: "json doc describing meals", + default: true + + }) + .option('missing-auto-sens-ok', { + describe: "If auto-sens data is missing, try anyway.", + default: true + + }) + .option('missing-meal-ok', { + describe: "If meal data is missing, try anyway.", + default: true + + }) + .option('microbolus', { + describe: "Enable SuperMicroBolus mode (oref1)", + default: false + + }) + // error and show help if some other args given + .strict(true) + .help('help') + ; + function usage ( ) { + argv.showHelp( ); + } + + var params = argv.argv; + var errors = [ ]; + var warnings = [ ]; + + var iob_input = params._[0]; + if ([null, '--help', '-h', 'help'].indexOf(iob_input) > 0) { + + usage( ); + process.exit(0) + } + var currenttemp_input = params._[1]; + var glucose_input = params._[2]; + var profile_input = params._[3]; + var meal_input = params._[4]; + var autosens_input = params.autoSens; + if (params._.length > 5) { + autosens_input = params.autoSens ? params._[4] : false; + meal_input = params._[5]; + } + if (params.meal && params.meal !== true && !meal_input) { + meal_input = params.meal; + } + var reservoir_input = params.reservoir; if (!iob_input || !currenttemp_input || !glucose_input || !profile_input) { - console.error('usage: ', process.argv.slice(0, 2), ' [Offline]'); + usage( ); process.exit(1); } - - var cwd = process.cwd(); - var glucose_data = require(cwd + '/' + glucose_input); - var currenttemp = require(cwd + '/' + currenttemp_input); - var iob_data = require(cwd + '/' + iob_input); - var profile = require(cwd + '/' + profile_input); - var glucose_status = determinebasal.getLastGlucose(glucose_data); - - //if old reading from Dexcom do nothing - - var systemTime = new Date(); - var bgTime; - if (glucose_data[0].display_time) { - bgTime = new Date(glucose_data[0].display_time.replace('T', ' ')); - } else if (glucose_data[0].dateString) { - bgTime = new Date(glucose_data[0].dateString); - } else { console.error("Could not determine last BG time"); } - var minAgo = (systemTime - bgTime) / 60 / 1000; - - if (minAgo > 10 || minAgo < -5) { // Dexcom data is too old, or way in the future - var reason = "BG data is too old, or clock set incorrectly "+bgTime; - console.error(reason); - return 1; + + var fs = require('fs'); + try { + var cwd = process.cwd(); + var glucose_data = require(cwd + '/' + glucose_input); + var currenttemp = require(cwd + '/' + currenttemp_input); + var iob_data = require(cwd + '/' + iob_input); + var profile = require(cwd + '/' + profile_input); + var glucose_status = determinebasal.getLastGlucose(glucose_data); + } catch (e) { + return console.error("Could not parse input data: ", e); } + + //attempting to provide a check for autotune + //if autotune directory does not exist, SMB/oref1 should not be able to run + + // console.error("Printing this so you know it's getting to the check for autotune.") + + //printing microbolus before attempting check + //console.error("Microbolus var is currently set to: ",params['microbolus']); + + if (params['microbolus']) { + if (fs.existsSync("autotune")) { + console.error("Autotune exists! Hoorah! You can use microbolus-related features.") + } else { + console.error("Warning: Autotune has not been run. All microboluses will be disabled until you manually run autotune or add it to run nightly in your loop."); + params['microbolus'] = false; + //console.error("Microbolus var is currently set to: ",params['microbolus']); + } + } + + //console.log(carbratio_data); + var meal_data = { }; + //console.error("meal_input",meal_input); + if (meal_input && typeof meal_input != 'undefined') { + try { + meal_data = JSON.parse(fs.readFileSync(meal_input, 'utf8')); + console.error(JSON.stringify(meal_data)); + } catch (e) { + var msg = { + msg: "Optional feature Meal Assist enabled, but could not read required meal data." + , file: meal_input + , error: e + }; + console.error(msg.msg); + // console.log(JSON.stringify(msg)); + if (!params['missing-meal-ok']) { + warnings.push(msg); + } + // process.exit(1); + } + } + //if (meal_input) { meal_data = require(cwd + '/' + meal_input); } + + //console.error(autosens_input); + var autosens_data = null; + if (autosens_input) { + // { "ratio":1 }; + autosens_data = { "ratio": 1 }; + if (autosens_input !== true && autosens_input.length) { + try { + autosens_data = JSON.parse(fs.readFileSync(autosens_input, 'utf8')); + //console.error(JSON.stringify(autosens_data)); + } catch (e) { + var msg = { + msg: "Optional feature Auto Sensitivity enabled. Could not find specified auto-sens: " + autosens_input + , error: e + }; + console.error(msg.msg); + console.error(e); + // console.log(JSON.stringify(msg)); + if (!params['missing-auto-sens-ok']) { + errors.push(msg); + } + // process.exit(1); + } + } + } + var reservoir_data = null; + if (reservoir_input && typeof reservoir_input != 'undefined') { + try { + reservoir_data = fs.readFileSync(reservoir_input, 'utf8'); + //console.error(reservoir_data); + } catch (e) { + var msg = { + msg: "Warning: Could not read required reservoir data from "+reservoir_input+"." + , file: reservoir_input + , error: e + }; + console.error(msg.msg); + } + } + + if (warnings.length) { + console.error(JSON.stringify(warnings)); + } + + if (errors.length) { + console.log(JSON.stringify(errors)); + process.exit(1); + } + + if (typeof(iob_data.length) && iob_data.length > 1) { + console.error(JSON.stringify(iob_data[0])); + } else { + console.error(JSON.stringify(iob_data)); + } + console.error(JSON.stringify(glucose_status)); - console.error(JSON.stringify(currenttemp)); - console.error(JSON.stringify(iob_data)); - console.error(JSON.stringify(profile)); - - var setTempBasal = require('../lib/basal-set-temp'); - - rT = determinebasal.determine_basal(glucose_status, currenttemp, iob_data, profile, undefined, setTempBasal); + //console.error(JSON.stringify(currenttemp)); + //console.error(JSON.stringify(profile)); + + var tempBasalFunctions = require('oref0/lib/basal-set-temp'); + + rT = determinebasal.determine_basal(glucose_status, currenttemp, iob_data, profile, autosens_data, meal_data, tempBasalFunctions, params['microbolus'], reservoir_data); if(typeof rT.error === 'undefined') { console.log(JSON.stringify(rT)); @@ -68,16 +212,16 @@ if (!module.parent) { } } - + function init() { var determinebasal = { name: 'determine-basal' , label: "OpenAPS Determine Basal" }; - - determinebasal.getLastGlucose = require('../lib/glucose-get-last'); - determinebasal.determine_basal = require('../lib/determine-basal/determine-basal'); + + determinebasal.getLastGlucose = require('oref0/lib/glucose-get-last'); + determinebasal.determine_basal = require('oref0/lib/determine-basal/determine-basal'); return determinebasal; } diff --git a/bin/oref0-dex-is-fresh.sh b/bin/oref0-dex-is-fresh.sh new file mode 100755 index 000000000..fbd83d15e --- /dev/null +++ b/bin/oref0-dex-is-fresh.sh @@ -0,0 +1,15 @@ +#!/bin/bash + +GLUCOSE=$1 + +OLD=${2-5} +TIME_SINCE=$(oref0-dex-time-since $GLUCOSE) + +if (( $(bc <<< "$TIME_SINCE >= $OLD") )); then + echo "CGM Data $TIME_SINCE mins ago is old (>=$OLD)" + exit 1 +else + echo "CGM Data $TIME_SINCE mins ago is fresh (< $OLD)" + exit 0 +fi + diff --git a/bin/oref0-dex-time-since.sh b/bin/oref0-dex-time-since.sh new file mode 100755 index 000000000..1662b2c9c --- /dev/null +++ b/bin/oref0-dex-time-since.sh @@ -0,0 +1,6 @@ +#!/bin/bash + +GLUCOSE=$1 + +cat $GLUCOSE | json -e "this.minAgo=Math.round(100*(new Date()-new Date(this.dateString))/60/1000)/100" | json -a minAgo | head -n 1 + diff --git a/bin/oref0-dex-wait-until-expected.sh b/bin/oref0-dex-wait-until-expected.sh new file mode 100755 index 000000000..c9ea49b2f --- /dev/null +++ b/bin/oref0-dex-wait-until-expected.sh @@ -0,0 +1,24 @@ +#!/bin/bash + +GLUCOSE=$1 + +OLD=${2-5} +MAX_WAIT=${3-1} +TIME_SINCE=$(oref0-dex-time-since $GLUCOSE) + +if (( $(bc <<< "$TIME_SINCE >= $OLD") )); then + echo "CGM Data $TIME_SINCE mins ago is old (>=$OLD), not waiting" +else + WAIT_MINS=$(bc <<< "$OLD - $TIME_SINCE") + if (( $(bc <<< "$WAIT_MINS > 6") )); then + echo "Clock mismatch ($WAIT_MINS > 6); not waiting" + elif (( $(bc <<< "$WAIT_MINS >= $MAX_WAIT") )); then + echo "CGM Data $TIME_SINCE mins ago is fresh (< $OLD), $WAIT_MINS mins > max wait ($MAX_WAIT mins) waiting for next attempt" + exit 1 + else + echo "CGM Data $TIME_SINCE mins ago is fresh (< $OLD), waiting $WAIT_MINS mins for new data" + sleep ${WAIT_MINS}m + echo "finished waiting, let's get some CGM Data" + fi +fi + diff --git a/bin/oref0-dexusb-cgm-loop.py b/bin/oref0-dexusb-cgm-loop.py new file mode 100755 index 000000000..25023d967 --- /dev/null +++ b/bin/oref0-dexusb-cgm-loop.py @@ -0,0 +1,167 @@ +#!/usr/bin/python + +# This script will create a cgm-loop that will feed the cgm data +# to the OpenAPS environment and will rezone it and upload it to +# Nightscout +# Tested with Dexcom G4 non share +# +# Released under MIT license. See the accompanying LICENSE.txt file for +# full terms and conditions +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. + +from __future__ import print_function +import json +import time +import subprocess +import datetime +import dateutil.parser + +# How to integrate with openaps. +# Easiest way is to use oref0-setup.sh. This wil: +# Step 1. Add the following lines to your ~/.profile +# export NIGHTSCOUT_HOST="<>" +# export API_SECRET=<> +# Use a new shell, or use source ~/.profile +# +# Step 2. Edit your crontab with `crontab -e` and append the following line: +# @reboot cd /home/pi/openapsdir && python -u /usr/local/bin/oref0-dexusb-cgm-loop >> /var/log/openaps/cgm-loop2.log +# this will start this python script at reboot, and log to /var/log/openaps/cgm-loop2.log +# +# Step 3. Disable the default cgm loop in crontab, because this script will invoke openaps get-bg +# +# Step 4. Reboot + +HOURS=24 +CMD_GET_GLUCOSE="openaps use cgm oref0_glucose --hours %d --threshold 100" +CMD_DESCRIBE_CLOCKS="openaps use cgm DescribeClocks" +DEST="raw-cgm/raw-entries.json" +CMD_NS_UPLOAD_ENTRIES="ns-upload-entries %s" % DEST +CMD_OPENAPS_GET_BG="openaps get-bg" +WAIT=5*60+1 # wait 5 minutes and 1 second +CGMPER24H=288*2 # 24 hours = 288 * 5 minutes. For raw values multiply by 2 + +# limit the list to maxlen items +def limitlist(l,maxlen): + if len(l)24: + delta_hours=24 + return delta_hours + +def calculate_wait_until_next_cgm(dt): + if dt==-1: + return 60 + # will implement automatic waiting for next cgm reading later, for now check every minute + return 60 + +# First iteration: get a lot of egv data +iteration=1 +status=-1 +output="" +hours=HOURS +most_recent_cgm_display_time=-1 +most_recent_cgm_system_time=datetime.datetime.now() + +print("Starting loop") +while (status!=0): + (t, status, output) = gettimestatusoutput(CMD_GET_GLUCOSE % hours) + if status==0: + break + iteration=iteration+1 + print("Iteration: %d. Sleeping %d seconds" % (iteration, WAIT)) + time.sleep(WAIT) + +print("Writing output of '%s' to %s" % (CMD_GET_GLUCOSE, DEST)) +f = open(DEST, 'w') +f.write(output) +f.close() + +j1=json.loads(output) + +print("Rezoning and feeding to openaps") +(t,status, output) = gettimestatusoutput(CMD_OPENAPS_GET_BG) + +print("Uploading to nightscout") +(t,status, output) = gettimestatusoutput(CMD_NS_UPLOAD_ENTRIES) + +display_time_list=[] +for d in j1: + display_time_list.append(d["display_time"]) + len_j1=len(j1) + +print("Read %d records"% len_j1) +sliding24h=j1 +most_recent_cgm=display_time_list[0] +print("Most recent cgm display time: %s" % most_recent_cgm) + +while (True): + iteration=iteration+1 + wait=calculate_wait_until_next_cgm(most_recent_cgm) + print("Round: %d. Sleeping %d seconds" % (iteration, wait)) + time.sleep(wait) + new=[] + hours=hours_since(most_recent_cgm) + (t, status, output) = gettimestatusoutput(CMD_GET_GLUCOSE % hours) + if status==0: + j2=json.loads(output) + for d in j2: + dt=d["display_time"] + if not (dt in display_time_list): + print("New: %s" % dt) + display_time_list.append(dt) + new.append(d) + most_recent_cgm=dt + + if len(new)>0: # only do stuff if we have new cgm records + new=limitlist(new+sliding24h, CGMPER24H) # limit json to 24h of cgm values + sliding24h=new + f = open(DEST, 'w') + f.write(json.dumps(sliding24h, sort_keys=True, indent=4, separators=(',', ': '))) + f.close() + print("Rezoning and feeding to openaps") + (t,status, output) = gettimestatusoutput(CMD_OPENAPS_GET_BG) + + print("Uploading to nightscout") + (t,status, output) = gettimestatusoutput(CMD_NS_UPLOAD_ENTRIES) + + + diff --git a/bin/oref0-find-insulin-uses.js b/bin/oref0-find-insulin-uses.js index 813354c14..6cb3faf3d 100755 --- a/bin/oref0-find-insulin-uses.js +++ b/bin/oref0-find-insulin-uses.js @@ -19,14 +19,21 @@ */ var find_insulin = require('oref0/lib/iob/history'); +function usage ( ) { + console.log('usage: ', process.argv.slice(0, 2), ' '); +} if (!module.parent) { - var iob_input = process.argv.slice(2, 3).pop() - var profile_input = process.argv.slice(3, 4).pop() - var clock_input = process.argv.slice(4, 5).pop() + var iob_input = process.argv[2] + if ([null, '--help', '-h', 'help'].indexOf(iob_input) > 0) { + usage( ); + process.exit(0) + } + var profile_input = process.argv[3] + var clock_input = process.argv[4] if (!iob_input || !profile_input) { - console.log('usage: ', process.argv.slice(0, 2), ' '); + usage( ); process.exit(1); } diff --git a/bin/oref0-fix-git-corruption.sh b/bin/oref0-fix-git-corruption.sh new file mode 100755 index 000000000..715bf730c --- /dev/null +++ b/bin/oref0-fix-git-corruption.sh @@ -0,0 +1,79 @@ +#!/bin/bash + +# +# Author: Ben West +# +# +<&1 > /dev/null && return 1 || return 0 +} + +function ls_corrupt ( ) { + git status 2>&1 +} + +function find_last_branch_log ( ) { + # find last locally updated reflog, manually + find .git/logs/refs/heads/ -type f -printf "%T+ %p\n" | sort -r | head -n 1 | cut -f 2 -d' ' +} + +function find_last_valid_commit ( ) { + # last used branch + BRANCH=$(find_last_branch_log) + # Find second from last commit + if [ -z $BRANCH ]; then + exit 1 + fi + tail -n 2 $BRANCH | head -n 1 | cut -d' ' -f 2 +} + +if ! is_corrupt ; then + echo "Git repo does not appear to be corrupt." + exit 0 +fi + +# find previous commit before the corruption +VALID_COMMIT=$(find_last_valid_commit) + +if [ -z $VALID_COMMIT ]; then + echo "Error: Could not find last valid commit; aborting." + exit 1 +fi + +echo "Fixing, attempting to restore to $VALID_COMMIT" +while is_corrupt ; do + + # Each time the loop should run, remove any broken objects and attempt to + # restore the repo. + echo "Again" + # bunch of debugging + ls_corrupt + ls_corrupt > /tmp/corrupted + cat /tmp/corrupted | grep "error:.*file" + # Extract broken file objects from git error report. + cat /tmp/corrupted | grep "error:.*file" | sed -e "s/error:.*file \.git/\.git/g" | while read broken line ; do + echo $broken is corrupt + # Remove broken file. + rm -f $broken + # Attempt using git's repair tool. + git fsck --full + done + + # Attempt resetting HEAD to last known good commit. + git reset --hard $VALID_COMMIT + # If that works, quit the loop. + git status && break +done + +git status && echo "git repo repaired" + + diff --git a/bin/oref0-get-profile.js b/bin/oref0-get-profile.js index 8fedabcaf..29ba80b56 100755 --- a/bin/oref0-get-profile.js +++ b/bin/oref0-get-profile.js @@ -17,45 +17,219 @@ */ var generate = require('oref0/lib/profile/'); +function usage ( ) { + console.log('usage: ', process.argv.slice(0, 2), ' [] [] [] [--model model.json] [--autotune autotune.json]'); +} + +function exportDefaults () { + var defaults = generate.displayedDefaults(); + console.log(JSON.stringify(defaults, null, '\t')); +} + +function updatePreferences (prefs) { + var defaults = generate.displayedDefaults(); + + // check for any displayedDefaults missing from current prefs and add from defaults + + for (var pref in defaults) { + if (defaults.hasOwnProperty(pref) && !prefs.hasOwnProperty(pref)) { + prefs[pref] = defaults[pref]; + } + } + + console.log(JSON.stringify(prefs, null, '\t')); +} if (!module.parent) { - var pumpsettings_input = process.argv.slice(2, 3).pop() - var bgtargets_input = process.argv.slice(3, 4).pop() - var isf_input = process.argv.slice(4, 5).pop() - var basalprofile_input = process.argv.slice(5, 6).pop() - var maxiob_input = process.argv.slice(6, 7).pop() - + var argv = require('yargs') + .usage("$0 pump_settings.json bg_targets.json insulin_sensitivities.json basal_profile.json [preferences.json] [] [] [--model model.json] [--autotune autotune.json]") + .option('model', { + alias: 'm', + describe: "Pump model response", + default: false + }) + .option('autotune', { + alias: 'a', + describe: "Autotuned profile.json", + default: false + }) + .strict(true) + .help('help') + .option('exportDefaults', { + describe: "Show typically-adjusted default preference values", + default: false + }) + .option('updatePreferences', { + describe: "Check for any keys missing from current prefs and add from defaults", + default: false + }) + + var params = argv.argv; + var pumpsettings_input = params._[0] + if ([null, '--help', '-h', 'help'].indexOf(pumpsettings_input) > 0) { + usage( ); + process.exit(0); + } + if (params.exportDefaults) { + exportDefaults(); + process.exit(0); + } + if (params.updatePreferences) { + var preferences = {}; + var cwd = process.cwd() + preferences = require(cwd + '/' + params.updatePreferences); + updatePreferences(preferences); + process.exit(0); + } + + var bgtargets_input = params._[1] + var isf_input = params._[2] + var basalprofile_input = params._[3] + var preferences_input = params._[4] + var carbratio_input = params._[5] + var temptargets_input = params._[6] + var model_input = params.model; + var autotune_input = params.autotune; + if (!pumpsettings_input || !bgtargets_input || !isf_input || !basalprofile_input) { - console.log('usage: ', process.argv.slice(0, 2), ' []'); + usage( ); process.exit(1); } - + var cwd = process.cwd() var pumpsettings_data = require(cwd + '/' + pumpsettings_input); var bgtargets_data = require(cwd + '/' + bgtargets_input); if (bgtargets_data.units !== 'mg/dL') { - console.log('BG Target data is expected to be expressed in mg/dL.' + if (bgtargets_data.units == 'mmol/L') { + for (var i = 0, len = bgtargets_data.targets.length; i < len; i++) { + bgtargets_data.targets[i].high = bgtargets_data.targets[i].high * 18; + bgtargets_data.targets[i].low = bgtargets_data.targets[i].low * 18; + } + bgtargets_data.units = 'mg/dL'; + } else { + console.log('BG Target data is expected to be expressed in mg/dL or mmol/L.' , 'Found', bgtargets_data.units, 'in', bgtargets_input, '.'); - process.exit(2); + process.exit(2); + } } + var isf_data = require(cwd + '/' + isf_input); + if (isf_data.units !== 'mg/dL') { + if (isf_data.units == 'mmol/L') { + for (var i = 0, len = isf_data.sensitivities.length; i < len; i++) { + isf_data.sensitivities[i].sensitivity = isf_data.sensitivities[i].sensitivity * 18; + } + isf_data.units = 'mg/dL'; + } else { + console.log('ISF is expected to be expressed in mg/dL or mmol/L.' + , 'Found', isf_data.units, 'in', isf_input, '.'); + process.exit(2); + } + } var basalprofile_data = require(cwd + '/' + basalprofile_input); - var maxiob_data = { max_iob: 0 }; - if (typeof maxiob_input != 'undefined') { - maxiob_data = require(cwd + '/' + maxiob_input); + var preferences = {}; + if (typeof preferences_input != 'undefined') { + preferences = require(cwd + '/' + preferences_input); } - var inputs = { - settings: pumpsettings_data - , targets: bgtargets_data - , basals: basalprofile_data - , isf: isf_data - , max_iob: maxiob_data.max_iob || 0 + var fs = require('fs'); - }; + var model_data = { } + if (params.model) { + try { + 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}; + console.error(msg.msg); + console.log(JSON.stringify(msg)); + process.exit(1); + } + } + var autotune_data = { } + if (params.autotune) { + try { + autotune_data = JSON.parse(fs.readFileSync(autotune_input, 'utf8')); + + } catch (e) { + var 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)); + //process.exit(1); + } + } + + var carbratio_data = { }; + //console.log("carbratio_input",carbratio_input); + if (typeof carbratio_input != 'undefined') { + try { + 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 }; + console.error(msg.msg); + console.log(JSON.stringify(msg)); + process.exit(1); + } + var errors = [ ]; + + if (!(carbratio_data.schedule && carbratio_data.schedule[0].start && carbratio_data.schedule[0].ratio)) { + errors.push({msg: "Carb ratio data should have an array called schedule with a start and ratio fields.", file: carbratio_input, data: carbratio_data}); + } else { + } + if (carbratio_data.units != 'grams' && carbratio_data.units != 'exchanges') { + errors.push({msg: "Carb ratio should have units field set to 'grams' or 'exchanges'.", file: carbratio_input, data: carbratio_data}); + } + if (errors.length) { + + errors.forEach(function (msg) { + console.error(msg.msg); + }); + console.log(JSON.stringify(errors)); + process.exit(1); + } + } + var temptargets_data = { }; + if (typeof temptargets_input != 'undefined') { + try { + temptargets_data = JSON.parse(fs.readFileSync(temptargets_input, 'utf8')); + } catch (e) { + //console.error("Could not parse temptargets_data."); + } + } + + //console.log(carbratio_data); + var inputs = { }; + + //add all preferences to the inputs + for (var pref in preferences) { + if (preferences.hasOwnProperty(pref)) { + inputs[pref] = preferences[pref]; + } + } + + //make sure max_iob is set or default to 0 + inputs.max_iob = inputs.max_iob || 0; + + //set these after to make sure nothing happens if they are also set in preferences + inputs.settings = pumpsettings_data; + inputs.targets = bgtargets_data; + inputs.basals = basalprofile_data; + inputs.isf = isf_data; + inputs.carbratio = carbratio_data; + inputs.temptargets = temptargets_data; + inputs.model = model_data; + inputs.autotune = autotune_data; + + if (autotune_data) { + if (autotune_data.basalprofile) { inputs.basals = autotune_data.basalprofile; } + if (autotune_data.isfProfile) { inputs.isf = autotune_data.isfProfile; } + if (autotune_data.carb_ratio) { inputs.carbratio.schedule[0].ratio = autotune_data.carb_ratio; } + } var profile = generate(inputs); console.log(JSON.stringify(profile)); + } diff --git a/bin/oref0-html.js b/bin/oref0-html.js new file mode 100755 index 000000000..dfcf191c8 --- /dev/null +++ b/bin/oref0-html.js @@ -0,0 +1,181 @@ +#!/usr/bin/env node + +/* + Update Pebble Watch information + + Copyright (c) 2015 OpenAPS Contributors + + Released under MIT license. See the accompanying LICENSE.txt file for + full terms and conditions + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + +*/ + +function getTime(minutes) { + var baseTime = new Date(); + baseTime.setHours('00'); + baseTime.setMinutes('00'); + baseTime.setSeconds('00'); + + return baseTime.getTime() + minutes * 60 * 1000; + +} + +/* Return basal rate(U / hr) at the provided timeOfDay */ + +function basalLookup() { + var now = new Date(); + basalRate = Math.round(basalprofile_data[basalprofile_data.length-1].rate*100)/100 + + for (var i = 0; i < basalprofile_data.length - 1; i++) { + if ((now >= getTime(basalprofile_data[i].minutes)) && (now < getTime(basalprofile_data[i + 1].minutes))) { + basalRate = basalprofile_data[i].rate.toFixed(2); + break; + } + } +} + + + +function fileHM(file) { + var filedate = new Date(fs.statSync(file).mtime); + var HMS = filedate.toLocaleTimeString().split(":") + return HMS[0].concat(":", HMS[1]); +} + +if (!module.parent) { + + var fs = require('fs'); + + var glucose_input = process.argv[2] + var iob_input = process.argv[3] + var basalprofile_input = process.argv[4] + var currenttemp_input = process.argv[5] + var requestedtemp_input = process.argv[6] + var enactedtemp_input = process.argv[7] + var meal_input = process.argv[8] + + if (!glucose_input || !iob_input || !basalprofile_input || !currenttemp_input || !requestedtemp_input ) { + console.log('usage: ', process.argv.slice(0, 2), ' [meal.json]'); + process.exit(1); + } + + var cwd = process.cwd() + var file = cwd + '/' + glucose_input; + var glucose_data = require(file); + var bgTime = fileHM(file); + if (glucose_data[0].dateString) { + var bgDate = new Date(glucose_data[0].dateString); + var HMS = bgDate.toLocaleTimeString().split(":") + bgTime = HMS[0].concat(":", HMS[1]); + } + + var bgnow = glucose_data[0].glucose; + var delta = glucose_data[0].glucose - glucose_data[1].glucose; + var tick = delta; + if (delta >= 0) { tick = "+" + delta; } + var iob_data = require(cwd + '/' + iob_input); + iob = iob_data[0].iob.toFixed(1); + var basalprofile_data = require(cwd + '/' + basalprofile_input); + var basalRate; + basalLookup(); + file = cwd + '/' + currenttemp_input; + var temp = require(file); + var temp_time = fileHM(file); + var tempstring; + if (temp.duration < 1) { + tempstring = "No temp basal"; + } else { + tempstring = "Tmp: " + temp.duration + "m @ " + temp.rate.toFixed(1); + } + try { + var requestedtemp = require(cwd + '/' + requestedtemp_input); + } catch (e) { + return console.error("Could not parse requestedtemp: ", e); + } + var reqtempstring; + if (typeof requestedtemp.duration === 'undefined') { + reqtempstring = "None"; + } + else if (requestedtemp.duration < 1) { + reqtempstring = "Cancel"; + } else { + reqtempstring = requestedtemp.duration + "m@" + requestedtemp.rate.toFixed(1) + "U"; + } + //var enactedtemp = require(cwd + '/' + enactedtemp_input); + //if (enactedtemp.duration < 1) { + //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 mealCOB = "???"; + if (typeof meal_input != 'undefined') { + try { + 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; + } + } catch (e) { + //console.error("Optional feature Meal Assist not configured."); + } + } + +//console.log(""); + +console.log(""); + console.log(""); + console.log( bgnow + " " + tick + " at " + bgTime ); + console.log(""); + console.log(''); + console.log(''); +console.log(""); + +console.log(""); + + console.log("

"); + console.log( bgnow + " " + tick + " at " + bgTime ); + console.log("
"); + console.log( "IOB: " + iob + "U, eventually " + requestedtemp.eventualBG + " mg/dL" ); + console.log("
"); + //+ "Act: " + enactedstring + //+ " at " + enactedat + "\n" + console.log( tempstring ); + console.log( "U/hr at " + temp_time ); + console.log("

"); + console.log("
"); + console.log( "Req: " + reqtempstring ); + console.log("
"); + console.log( requestedtemp.reason ); + console.log("
"); + console.log( "Sched: " + basalRate + "U/hr" ); + console.log("
"); + console.log( "mealCOB: " + mealCOB + "g" ); + + +console.log(""); + + +} + diff --git a/bin/oref0-ifttt-notify b/bin/oref0-ifttt-notify index 17ea29b5f..a190932e3 100755 --- a/bin/oref0-ifttt-notify +++ b/bin/oref0-ifttt-notify @@ -25,7 +25,8 @@ if you wish. On the Maker channel there is a "how to trigger" link. Copy and paste the url for the example curl command, be sure to change the event name field. The URL, something like: -# https://maker.ifttt.com/trigger/{event}/with/key/MyKey + + https://maker.ifttt.com/trigger/{event}/with/key/MyKey You can pass the IFTTT_TRIGGER, which is the trigger URL as the first argument, or define it as an environment variable in your crontab. @@ -68,8 +69,9 @@ env) env exit ;; -help) +help|--help|-h) help_message + exit 0 ;; *) if [[ -z "$IFTTT_TRIGGER" || -z "$IFTTT_NOTIFY_USAGE" ]] ; then diff --git a/bin/oref0-log-shortcuts.sh b/bin/oref0-log-shortcuts.sh new file mode 100755 index 000000000..d481ae3b0 --- /dev/null +++ b/bin/oref0-log-shortcuts.sh @@ -0,0 +1,32 @@ +#!/bin/bash + +myopenaps=${OPENAPS_DIR:-"$HOME/myopenaps"} + +# add crontab entries +grep -q networklog $HOME/.bash_profile 2>/dev/null || echo "alias networklog="'"tail -n 100 -F /var/log/openaps/network.log"' >> $HOME/.bash_profile +grep -q xdrip-looplog $HOME/.bash_profile || echo "alias xdrip-looplog="'"tail -n 100 -F /var/log/openaps/xdrip-loop.log"' >> $HOME/.bash_profile +grep -q cgm-looplog $HOME/.bash_profile || echo "alias cgm-looplog="'"tail -n 100 -F /var/log/openaps/cgm-loop.log"' >> $HOME/.bash_profile +grep -q autosens-looplog $HOME/.bash_profile || echo "alias autosens-looplog="'"tail -n 100 -F /var/log/openaps/autosens-loop.log"' >> $HOME/.bash_profile +grep -q autotunelog $HOME/.bash_profile || echo "alias autotunelog="'"tail -n 100 -F /var/log/openaps/autotune.log"' >> $HOME/.bash_profile +grep -q pump-looplog $HOME/.bash_profile || echo "alias pump-looplog="'"tail -n 100 -F /var/log/openaps/pump-loop.log"' >> $HOME/.bash_profile +grep -q urchin-looplog $HOME/.bash_profile || echo "alias urchin-looplog="'"tail -n 100 -F /var/log/openaps/urchin-loop.log"' >> $HOME/.bash_profile +grep -q ns-looplog $HOME/.bash_profile || echo "alias ns-looplog="'"tail -n 100 -F /var/log/openaps/ns-loop.log"' >> $HOME/.bash_profile +grep -q cat-pref $HOME/.bash_profile || echo "alias cat-pref=\"cd ${myopenaps} && cat preferences.json\"" >> $HOME/.bash_profile +grep -q edit-pref $HOME/.bash_profile || echo "alias edit-pref=\"cd ${myopenaps} && nano preferences.json\"" >> $HOME/.bash_profile +grep -q cat-wifi $HOME/.bash_profile || echo "alias cat-wifi="'"cat /etc/wpa_supplicant/wpa_supplicant.conf"' >> $HOME/.bash_profile +grep -q edit-wifi $HOME/.bash_profile || echo "alias edit-wifi="'"vi /etc/wpa_supplicant/wpa_supplicant.conf"' >> $HOME/.bash_profile +grep -q cat-runagain $HOME/.bash_profile || echo "alias cat-runagain=\"cd ${myopenaps} && cat oref0-runagain.sh\"" >> $HOME/.bash_profile +grep -q edit-runagain $HOME/.bash_profile || echo "alias edit-runagain=\"cd ${myopenaps} && nano oref0-runagain.sh\"" >> $HOME/.bash_profile +grep -q cat-autotune $HOME/.bash_profile || echo "alias cat-autotune=\"cd ${myopenaps}/autotune && cat autotune_recommendations.log\"" >> $HOME/.bash_profile +grep -q git-branch $HOME/.bash_profile || echo "alias git-branch="'"cd $HOME/src/oref0 && git branch"' >> $HOME/.bash_profile +grep -q runagain $HOME/.bash_profile || echo "alias runagain=\"bash ${myopenaps}/oref0-runagain.sh\"" >> $HOME/.bash_profile +grep -q edison-battery $HOME/.bash_profile || echo "alias edison-battery=\"cd ${myopenaps}/monitor && cat edison-battery.json\"" >> $HOME/.bash_profile +grep -q cat-reservoir $HOME/.bash_profile || echo "alias cat-reservoir=\"cd ${myopenaps}/monitor && cat reservoir.json\"" >> $HOME/.bash_profile +grep -q stop-cron $HOME/.bash_profile || echo "alias stop-cron=\"cd ${myopenaps} && /etc/init.d/cron stop && killall -g oref0-pump-loop\"" >> $HOME/.bash_profile +grep -q start-cron $HOME/.bash_profile || echo "alias start-cron="'"/etc/init.d/cron start"' >> $HOME/.bash_profile + +# source default /etc/profile as well +grep -q /etc/skel/.profile $HOME/.bash_profile || echo ". /etc/skel/.profile" >> $HOME/.bash_profile + +# to enable shortcut aliases in $HOME/.bash_profile +source $HOME/.bash_profile diff --git a/bin/oref0-mdt-trend.js b/bin/oref0-mdt-trend.js new file mode 100755 index 000000000..30fb8b583 --- /dev/null +++ b/bin/oref0-mdt-trend.js @@ -0,0 +1,129 @@ +#!/usr/bin/env node + +function findRecord(arr, tell, date) { + for (var i = 0; i < arr.length; ++i) + { + if (arr[i]._tell == tell && arr[i].date == date) + { + return i; + } + } + return -1; +} + +function usage ( ) { + console.log('usage: ', process.argv.slice(0, 2), ''); + +} + +if (!module.parent) { + var glucose_input = process.argv[2]; + if ([null, '--help', '-h', 'help'].indexOf(glucose_input) > 0) { + usage( ); + process.exit(0) + } + + if (!glucose_input) { + usage( ); + process.exit(1); + } + + var cwd = process.cwd(); + var glucose_data = require(cwd + '/' + glucose_input); + glucose_data.sort(function (a, b) { return Date.parse(a.date) - Date.parse(b.date) }); + + filtered = glucose_data.filter(function(x) { return x.name == "GlucoseSensorData" }); + + var last_entries = []; + var last_entry_used = 0; + var window_mins = 15; + var max_entries = window_mins / 5; + var max_time = window_mins * 1000 * 60; + + var last_date = new Date(0); + var last_glucose = 0; + + for (var i = 0; i < filtered.length; ++i) { + var record = filtered[i]; + var output_record = glucose_data[findRecord(glucose_data, record._tell, record.date)]; + var current_date = Date.parse(record.date); + + var delta = 0; //record.sgv - last_glucose; + var delta_time = 0; + + if (record.name != "GlucoseSensorData") + { + continue; + } + + if (record.sgv == 0) + { + continue; + } + var used_records = 0; + for (var j = 0; j < max_entries; j++) + { + var past_record = last_entries[j]; + if (typeof past_record == "undefined" || past_record.sgv == 0) + { + continue; + } + var entry_delta_time = current_date - past_record.time; + + if (entry_delta_time <= max_time) + { + delta_time = entry_delta_time; + delta += ((record.sgv - past_record.sgv) * 1000 * 60) / delta_time; + used_records++; + } + } + delta /= used_records; + last_entries[last_entry_used] = {time: current_date, sgv: record.sgv}; + last_entry_used = (last_entry_used + 1 ) % max_entries; + if (current_date - last_date <= max_time) + { + + if (delta > 3) + { + output_record.trend_arrow = "DOUBLE_UP"; + output_record.direction = "DoubleUp"; + } + else if (delta > 2) + { + output_record.trend_arrow = "SINGLE_UP"; + output_record.direction = "SingleUp"; + } + else if (delta > 1) + { + output_record.trend_arrow = "45_UP"; + output_record.direction = "FortyFiveUp"; + } + else if (delta < -3) + { + output_record.trend_arrow = "DOUBLE_DOWN"; + output_record.direction = "DoubleDown"; + } + else if (delta < -2) + { + output_record.trend_arrow = "SINGLE_DOWN"; + output_record.direction = "SingleDown"; + } + else if (delta < -1) + { + output_record.trend_arrow = "45_DOWN"; + output_record.direction = "FortyFiveDown"; + } + else + { + output_record.trend_arrow = "FLAT"; + output_record.direction = "Flat"; + } + } + + last_glucose = record.sgv; + last_date = current_date; + } + + console.log(JSON.stringify(glucose_data)); +} + diff --git a/bin/oref0-meal.js b/bin/oref0-meal.js new file mode 100755 index 000000000..25a039aea --- /dev/null +++ b/bin/oref0-meal.js @@ -0,0 +1,107 @@ +#!/usr/bin/env node + +/* + oref0 meal data tool + + Collects meal data (carbs and boluses for last DIA hours) + for use in oref0 meal assist algorithm + + Released under MIT license. See the accompanying LICENSE.txt file for + full terms and conditions + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + +*/ + +var generate = require('oref0/lib/meal'); +function usage ( ) { + console.error('usage: ', process.argv.slice(0, 2), ' [carbhistory.json]'); +} + +if (!module.parent) { + var pumphistory_input = process.argv[2]; + if ([null, '--help', '-h', 'help'].indexOf(pumphistory_input) > 0) { + usage( ); + process.exit(0) + } + var profile_input = process.argv[3]; + var clock_input = process.argv[4]; + var glucose_input = process.argv[5]; + var basalprofile_input = process.argv[6]; + var carb_input = process.argv[7] + + if (!pumphistory_input || !profile_input || !clock_input || !glucose_input || !basalprofile_input) { + usage( ); + console.log('{ "carbs": 0, "reason": "Insufficient arguments" }'); + process.exit(1); + } + + var fs = require('fs'); + try { + var pumphistory_data = JSON.parse(fs.readFileSync(pumphistory_input, 'utf8')); + var profile_data = JSON.parse(fs.readFileSync(profile_input, 'utf8')); + var clock_data = JSON.parse(fs.readFileSync(clock_input, 'utf8')); + var basalprofile_data = JSON.parse(fs.readFileSync(basalprofile_input, 'utf8')); + } catch (e) { + console.log('{ "carbs": 0, "mealCOB": 0, "reason": "Could not parse input data" }'); + return console.error("Could not parse input data: ", e); + } + + // disallow impossibly low carbRatios due to bad decoding + if ( typeof(profile_data.carb_ratio) == 'undefined' || profile_data.carb_ratio < 3 ) { + console.log('{ "carbs": 0, "mealCOB": 0, "reason": "carb_ratio ' + profile_data.carb_ratio + ' out of bounds" }'); + return console.error("Error: carb_ratio " + profile_data.carb_ratio + " out of bounds"); + } + + try { + var glucose_data = JSON.parse(fs.readFileSync(glucose_input, 'utf8')); + } catch (e) { + console.error("Warning: could not parse "+glucose_input); + } + + var carb_data = { }; + if (typeof carb_input != 'undefined') { + try { + carb_data = JSON.parse(fs.readFileSync(carb_input, 'utf8')); + } catch (e) { + console.error("Warning: could not parse "+carb_input); + } + } + + 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; + carb_data = glucose_data; + glucose_data = basalprofile_data; + basalprofile_data = temp; + } + + var inputs = { + history: pumphistory_data + , profile: profile_data + , basalprofile: basalprofile_data + , clock: clock_data + , carbs: carb_data + , glucose: glucose_data + }; + + var recentCarbs = generate(inputs); + + if (glucose_data.length < 36) { + console.error("Not enough glucose data to calculate carb absorption; found:", glucose_data.length); + recentCarbs.mealCOB = 0; + recentCarbs.reason = "not enough glucose data to calculate carb absorption"; + } + + console.log(JSON.stringify(recentCarbs)); +} + diff --git a/bin/oref0-mint-max-iob.sh b/bin/oref0-mint-max-iob.sh deleted file mode 100755 index 8a1473cd7..000000000 --- a/bin/oref0-mint-max-iob.sh +++ /dev/null @@ -1,44 +0,0 @@ -#!/bin/bash - - -self=$(basename $0) -MAX_IOB=${1-} -OUTPUT=${2-/dev/fd/1} -shift - -function help_message ( ) { - cat < [max_iob.json] - -$self help - this message -Print a perfect max_iob.json. - - -Examples: -$ $self 2 -{ - "max_iob": 2 -} - -$ $self 2 foo.json -max_iob 2 saved in foo.json -bewest@hither:~/src/openaps/oref0$ - - -EOF -} - -case $MAX_IOB in -""| help) - help_message - ;; -*) - cat < $OUTPUT -{ "max_iob": $MAX_IOB } -EOF - test "$OUTPUT" != '/dev/fd/1' && echo "max_iob $MAX_IOB saved in $OUTPUT" - ;; -esac - - diff --git a/bin/oref0-normalize-temps.js b/bin/oref0-normalize-temps.js index b6b51cd86..6805ae38d 100755 --- a/bin/oref0-normalize-temps.js +++ b/bin/oref0-normalize-temps.js @@ -17,17 +17,28 @@ var find_insulin = require('oref0/lib/temps'); var find_bolus = require('oref0/lib/bolus'); var describe_pump = require('oref0/lib/pump'); +function usage ( ) { + console.log('usage: ', process.argv.slice(0, 2), ''); +} if (!module.parent) { - var iob_input = process.argv.slice(2, 3).pop() + var iob_input = process.argv[2]; + if ([null, '--help', '-h', 'help'].indexOf(iob_input) > 0) { + usage( ); + process.exit(0) + } if (!iob_input) { - console.log('usage: ', process.argv.slice(0, 2), ''); + usage( ) process.exit(1); } var cwd = process.cwd() - var all_data = require(cwd + '/' + iob_input); + try { + var all_data = require(cwd + '/' + iob_input); + } catch (e) { + return console.error("Could not parse pumphistory: ", e); + } var inputs = { history: all_data diff --git a/bin/oref0-ns-loop.sh b/bin/oref0-ns-loop.sh new file mode 100755 index 000000000..c4432ebb9 --- /dev/null +++ b/bin/oref0-ns-loop.sh @@ -0,0 +1,213 @@ +#!/bin/bash +# echo Starting ns-loop at $(date): && openaps get-ns-bg; sensors -u 2>/dev/null | awk '$NF > 85' | grep input || ( openaps ns-temptargets && echo -n Refreshed temptargets && openaps ns-meal-carbs && echo \\\" and meal-carbs\\\" && openaps upload ) +# echo Starting ns-loop at $(date): && openaps get-ns-bg; openaps ns-temptargets && echo -n Refreshed temptargets && openaps ns-meal-carbs && echo \\\" and meal-carbs\\\" && openaps battery-status; cat monitor/edison-battery.json; echo; openaps upload + +# main ns-loop +main() { + echo + echo Starting oref0-ns-loop at $(date): + if grep "MDT cgm" openaps.ini 2>&1 >/dev/null; then + check_mdt_upload + else + if glucose_fresh; then + echo Glucose file is fresh + cat cgm/ns-glucose.json | jq -c -C '.[0] | { glucose: .glucose, dateString: .dateString }' + else + get_ns_bg + fi + overtemp && exit 1 + if highload && completed_recently; then + echo Load high at $(date): waiting up to 5m to continue + exit 2 + fi + fi + + ns_temptargets || die "ns_temptargets failed" + ns_meal_carbs || die ", but ns_meal_carbs failed" + battery_status + upload + touch /tmp/ns-loop-completed + echo Completed oref0-ns-loop at $(date) +} + +function overtemp { + # check for CPU temperature above 85°C + sensors -u 2>/dev/null | awk '$NF > 85' | grep input \ + && echo Edison is too hot: waiting for it to cool down at $(date)\ + && echo Please ensure rig is properly ventilated +} + +function highload { + # check whether system load average is high + uptime | awk '$NF > 2' | grep load +} + + +#openaps get-ns-glucose && cat cgm/ns-glucose.json | json -c \\\"minAgo=(new Date()-new Date(this.dateString))/60/1000; return minAgo < 10 && minAgo > -5 && this.glucose > 38\\\" | grep -q glucose && cp -pu cgm/ns-glucose.json cgm/glucose.json; cp -pu cgm/glucose.json monitor/glucose.json +function get_ns_bg { + #openaps get-ns-glucose > /dev/null + # update 24h glucose file if it's 55m old or too small to calculate COB + if ! find cgm/ -mmin -54 | egrep -q cgm/ns-glucose-24h.json \ + || ! grep -c glucose cgm/ns-glucose-24h.json | jq -e '. > 36' >/dev/null; then + nightscout ns $NIGHTSCOUT_HOST $API_SECRET oref0_glucose_since -24hours > cgm/ns-glucose-24h.json + fi + nightscout ns $NIGHTSCOUT_HOST $API_SECRET oref0_glucose_since -1hour > cgm/ns-glucose-1h.json + jq -s '.[0] + .[1]|unique|sort_by(.date)|reverse' cgm/ns-glucose-24h.json cgm/ns-glucose-1h.json > cgm/ns-glucose.json + # if ns-glucose.json data is <10m old, no more than 5m in the future, and valid (>38), + # copy cgm/ns-glucose.json over to cgm/glucose.json if it's newer + valid_glucose=$(find_valid_ns_glucose) + if echo $valid_glucose | grep -q glucose; then + echo Found recent valid BG: + echo $valid_glucose | jq -c -C '.[0] | { glucose: .glucose, dateString: .dateString }' + cp -pu cgm/ns-glucose.json cgm/glucose.json + else + echo No recent valid BG found. Most recent: + cat cgm/ns-glucose.json | jq -c -C '.[0] | { glucose: .glucose, dateString: .dateString }' + fi + + # copy cgm/glucose.json over to monitor/glucose.json if it's newer + cp -pu cgm/glucose.json monitor/glucose.json +} + +function completed_recently { + find /tmp/ -mmin -5 | egrep -q "ns-loop-completed" +} + +function glucose_fresh { + # check whether ns-glucose.json is less than 5m old + touch -d "$(date -R -d @$(jq .[0].date/1000 cgm/ns-glucose.json))" cgm/ns-glucose.json + find cgm -mmin -5 | egrep -q "ns-glucose.json" +} + +function find_valid_ns_glucose { + # TODO: use jq for this if possible + cat cgm/ns-glucose.json | json -c "minAgo=(new Date()-new Date(this.dateString))/60/1000; return minAgo < 10 && minAgo > -5 && this.glucose > 38" +} + +function ns_temptargets { + #openaps report invoke settings/temptargets.json settings/profile.json >/dev/null + nightscout ns $NIGHTSCOUT_HOST $API_SECRET temp_targets > settings/ns-temptargets.json.new + cat settings/ns-temptargets.json.new | jq .[0].duration | egrep -q [0-9] && mv settings/ns-temptargets.json.new settings/ns-temptargets.json + # TODO: merge local-temptargets.json with ns-temptargets.json + #openaps report invoke settings/ns-temptargets.json settings/profile.json + echo -n "Latest NS temptargets: " + cat settings/ns-temptargets.json | jq -c -C '.[0] | { target: .targetBottom, duration: .duration, start: .created_at }' + # delete any local-temptarget files last modified more than 24h ago + find settings/local-temptarget* -mmin +1440 -exec rm {} \; + echo -n "Merging local temptargets: " + cat settings/local-temptargets.json | jq -c -C '.[0] | { target: .targetBottom, duration: .duration, start: .created_at }' + jq -s '.[0] + .[1]|unique|sort_by(.created_at)|reverse' settings/ns-temptargets.json settings/local-temptargets.json > settings/temptargets.json + echo -n "Temptargets merged: " + cat settings/temptargets.json | jq -c -C '.[0] | { target: .targetBottom, duration: .duration, start: .created_at }' + oref0-get-profile settings/settings.json settings/bg_targets.json settings/insulin_sensitivities.json settings/basal_profile.json preferences.json settings/carb_ratios.json settings/temptargets.json --model=settings/model.json --autotune settings/autotune.json | jq . > settings/profile.json.new || die "Couldn't refresh profile" + if cat settings/profile.json.new | jq . | grep -q basal; then + mv settings/profile.json.new settings/profile.json + else + die "Invalid profile.json.new after refresh" + fi +} + +# openaps report invoke monitor/carbhistory.json; oref0-meal monitor/pumphistory-merged.json settings/profile.json monitor/clock-zoned.json monitor/glucose.json settings/basal_profile.json monitor/carbhistory.json > monitor/meal.json.new; grep -q COB monitor/meal.json.new && mv monitor/meal.json.new monitor/meal.json; exit 0 +function ns_meal_carbs { + #openaps report invoke monitor/carbhistory.json >/dev/null + nightscout ns $NIGHTSCOUT_HOST $API_SECRET carb_history > monitor/carbhistory.json.new + cat monitor/carbhistory.json.new | jq .[0].carbs | egrep -q [0-9] && mv monitor/carbhistory.json.new monitor/carbhistory.json + oref0-meal monitor/pumphistory-merged.json settings/profile.json monitor/clock-zoned.json monitor/glucose.json settings/basal_profile.json monitor/carbhistory.json > monitor/meal.json.new + grep -q COB monitor/meal.json.new && mv monitor/meal.json.new monitor/meal.json + echo -n "Refreshed carbhistory; COB: " + grep COB monitor/meal.json | jq .mealCOB +} + +#sudo ~/src/EdisonVoltage/voltage json batteryVoltage battery > monitor/edison-battery.json +function battery_status { + if [ -e ~/src/EdisonVoltage/voltage ]; then + sudo ~/src/EdisonVoltage/voltage json batteryVoltage battery | tee monitor/edison-battery.json | jq -C -c . + elif [ -e /root/src/openaps-menu/scripts/getvoltage.sh ]; then + sudo /root/src/openaps-menu/scripts/getvoltage.sh | tee monitor/edison-battery.json | jq -C -c . + fi +} + +# echo -n Upload && ( openaps upload-ns-status; openaps upload-pumphistory-entries; openaps upload-recent-treatments ) 2>/dev/null >/dev/null && echo ed +function upload { + upload_ns_status + upload_recent_treatments || die "; NS treatments upload failed" +} + +# grep -q iob monitor/iob.json && find enact/ -mmin -5 -size +5c | grep -q suggested.json && openaps format-ns-status && grep -q iob upload/ns-status.json && ns-upload $NIGHTSCOUT_HOST $API_SECRET devicestatus.json upload/ns-status.json +function upload_ns_status { + #echo Uploading devicestatus + grep -q iob monitor/iob.json || die "IOB not found" + if ! find enact/ -mmin -5 -size +5c | grep -q suggested.json; then + echo -n "No recent suggested.json found; last updated " + ls -la enact/suggested.json | awk '{print $6,$7,$8}' + return 1 + fi + format_ns_status && grep -q iob upload/ns-status.json || die "Couldn't generate ns-status.json" + ns-upload $NIGHTSCOUT_HOST $API_SECRET devicestatus.json upload/ns-status.json | jq -C -c '.[0].openaps.suggested | {BG: .bg, IOB: .IOB, rate: .rate, duration: .duration, units: .units}' || die "Couldn't upload devicestatus to NS" +} + +#ns-status monitor/clock-zoned.json monitor/iob.json enact/suggested.json enact/enacted.json monitor/battery.json monitor/reservoir.json monitor/status.json > upload/ns-status.json +# ns-status monitor/clock-zoned.json monitor/iob.json enact/suggested.json enact/enacted.json monitor/battery.json monitor/reservoir.json monitor/status.json --uploader monitor/edison-battery.json > upload/ns-status.json +function format_ns_status { + if [ -s monitor/edison-battery.json ]; then + ns-status monitor/clock-zoned.json monitor/iob.json enact/suggested.json enact/enacted.json monitor/battery.json monitor/reservoir.json monitor/status.json --uploader monitor/edison-battery.json > upload/ns-status.json + else + ns-status monitor/clock-zoned.json monitor/iob.json enact/suggested.json enact/enacted.json monitor/battery.json monitor/reservoir.json monitor/status.json > upload/ns-status.json + fi +} + +#openaps format-latest-nightscout-treatments && test $(json -f upload/latest-treatments.json -a created_at eventType | wc -l ) -gt 0 && (ns-upload $NIGHTSCOUT_HOST $API_SECRET treatments.json upload/latest-treatments.json ) || echo \\\"No recent treatments to upload\\\" +function upload_recent_treatments { + #echo Uploading treatments + format_latest_nightscout_treatments || die "Couldn't format latest NS treatments" + if test $(json -f upload/latest-treatments.json -a created_at eventType | wc -l ) -gt 0; then + ns-upload $NIGHTSCOUT_HOST $API_SECRET treatments.json upload/latest-treatments.json | jq -C -c . || die "Couldn't upload latest treatments to NS" + else + echo "No new treatments to upload" + fi +} + +#nightscout cull-latest-openaps-treatments monitor/pumphistory-zoned.json settings/model.json $(openaps latest-ns-treatment-time) > upload/latest-treatments.json +function format_latest_nightscout_treatments { + nightscout cull-latest-openaps-treatments monitor/pumphistory-zoned.json settings/model.json $(openaps latest-ns-treatment-time) > upload/latest-treatments.json +} + +function check_mdt_upload { + if [ -f /tmp/mdt_cgm_uploaded ]; then + if [ $(date -d $(jq .[0].dateString nightscout/glucose.json | tr -d '"') +%s) -gt $(date -r /tmp/mdt_cgm_uploaded +%s) ];then + echo Found new MDT CGM data to upload: + echo "BG: $(jq .[0].glucose nightscout/glucose.json)" "at $(jq .[0].dateString nightscout/glucose.json | tr -d '"')" + mdt_upload_bg + else + echo No new MDT CGM data to upload + fi + elif [ -f nightscout/glucose.json ]; then + mdt_upload_bg + else + echo No cgm data available + fi +} + +function mdt_upload_bg { + echo Formating recent-missing-entries + openaps report invoke nightscout/recent-missing-entries.json 2>&1 >/dev/null + if grep "dateString" nightscout/recent-missing-entries.json 2>&1 >/dev/null; then + echo "$(jq '. | length' nightscout/recent-missing-entries.json) missing entires found, uploading" + openaps report invoke nightscout/uploaded-entries.json 2>&1 >/dev/null + touch -t $(date -d $(jq .[0].dateString nightscout/glucose.json | tr -d '"') +%Y%m%d%H%M.%S) /tmp/mdt_cgm_uploaded + echo "Uploaded $(jq '. | length' nightscout/uploaded-entries.json) missing entries" + echo MDT CGM data uploaded + else + echo No missing entries found + fi +} + + + + +die() { + echo "$@" + exit 1 +} + +main "$@" diff --git a/bin/oref0-online.sh b/bin/oref0-online.sh new file mode 100755 index 000000000..8240ad6cb --- /dev/null +++ b/bin/oref0-online.sh @@ -0,0 +1,252 @@ +#!/bin/bash + +main() { + MACs=$@ + HostAPDIP='10.29.29.1' + echo; echo Starting oref0-online at $(date). + # if we are connected to wifi but don't have an IP, try to get one + if iwgetid -r wlan0 | egrep -q "[A-Za-z0-9_]+"; then + if ! ip route | grep default | grep -q wlan0; then + if find /tmp/ -mmin -60 | grep bad_wifi && grep -q "$(iwgetid -r wlan0)" /tmp/bad_wifi; then + echo Not renewing wlan0 IP due to recent connectivity failure: + ls -la /tmp/bad_wifi + else + echo Attempting to renew wlan0 IP + sudo dhclient wlan0 + fi + fi + fi + if ifconfig | egrep -q "wlan0" >/dev/null; then + #if [[ $(ip -4 -o addr show dev wlan0 | awk '{split($4,a,"/");print a[1]}') = $(print_local_ip wlan0) ]]; then + print_wifi_name + echo -n "At $(date) my local wifi IP is: " + print_local_ip wlan0 + fi + if ifconfig | egrep -q "bnep0" >/dev/null; then + #if [[ $(ip -4 -o addr show dev bnep0 | awk '{split($4,a,"/");print a[1]}') = $(print_local_ip bnep0) ]]; then + print_bluetooth_name + #fi + echo -n "At $(date) my local Bluetooth IP is: " + print_local_ip bnep0 + else + echo "At $(date) my Bluetooth PAN is not connected" + fi + echo -n "At $(date) my public IP is: " + if check_ip; then + stop_hotspot + if has_ip wlan0 && has_ip bnep0; then + # if online via BT w/o a DHCP IP, cycle wifi + if print_local_ip wlan0 | grep $HostAPDIP || ! has_ip wlan0; then + ifdown wlan0; ifup wlan0 + fi + fi + # if online via wifi, disconnect BT + if has_ip wlan0 && ifconfig | egrep -q "bnep0" >/dev/null; then + bt_disconnect $MACs + #wifi_dhcp_renew + fi + else + echo + print_wifi_name + if ! has_ip wlan0; then + wifi_dhcp_renew + fi + if ! check_ip >/dev/null; then + bt_connect $MACs + fi + #print_wifi_name + if check_ip >/dev/null; then + # if we're online after activating bluetooth, shut down any local-access hotspot we're running + stop_hotspot + if ! print_local_ip wlan0 | egrep -q "[A-Za-z0-9_]+" >/dev/null; then + wifi_dhcp_renew + fi + else + # if we can't connect via BT, might as well try previously bad wifi networks again + rm /tmp/bad_wifi + # if we can't get online via wifi or bluetooth, start our own local-access hotspot + start_hotspot $@ + # don't disconnect bluetooth when starting local-only hotspot + fi + fi + echo Finished oref0-online at $(date). +} + +function print_bluetooth_name { + echo -n "At $(date) my Bluetooth is connected to " + grep Name /var/lib/bluetooth/*/*/info | awk -F = '{print $2}' + #echo ${MACs} +} + +function print_wifi_name { + SSID=$(iwgetid -r wlan0 | tr -d '\n') + if [[ ! -z $SSID ]]; then + echo "At $(date) my wifi network name is $SSID" + else + echo "At $(date) my wifi is not connected" + fi +} + +function print_local_ip { + LOCAL_IP=$(ip -4 -o addr show dev $1 | awk '{split($4,a,"/");print a[1]}') + if [[ -z $LOCAL_IP ]]; then + echo unassigned + else + echo $LOCAL_IP + fi +} + +function check_ip { + PUBLIC_IP=$(curl --compressed -4 -s -m 15 checkip.amazonaws.com | awk -F , '{print $NF}' | egrep "^[12]*[0-9]*[0-9]\.[12]*[0-9]*[0-9]\.[12]*[0-9]*[0-9]\.[12]*[0-9]*[0-9]$") + if [[ -z $PUBLIC_IP ]]; then + echo not found + return 1 + else + echo $PUBLIC_IP + fi +} + +function has_ip { + ifconfig | grep -A1 $1 | grep -q "inet addr" +} + +function bt_connect { + # loop over as many MACs as are provided as arguments + for MAC; do + #echo -n "At $(date) my public IP is: " + if ! check_ip >/dev/null; then + echo; echo "No Internet access detected, attempting to connect BT to $MAC" + oref0-bluetoothup + sudo bt-pan client $MAC -d + for i in {1..3} + do + sudo bt-pan client $MAC && sudo dhclient bnep0 + done + if ifconfig | egrep -q "bnep0" >/dev/null; then + echo -n "Connected to Bluetooth with IP: " + print_local_ip bnep0 + fi + # if we couldn't reach the Internet over wifi, but (now) have a bnep0 IP, release the wifi IP/route + if has_ip wlan0 && has_ip bnep0 && ! grep -q $HostAPDIP /etc/network/interfaces; then + # release the wifi IP/route but *don't* renew it, in case it's not working + sudo dhclient wlan0 -r + iwgetid -r wlan0 >> /tmp/bad_wifi + fi + #echo + fi + done +} + +function bt_disconnect { + echo "Disconnecting BT $MAC" + ifdown bnep0 + # loop over as many MACs as are provided as arguments + for MAC; do + sudo bt-pan client $MAC -d + done +} + +function wifi_dhcp_renew { + if find /tmp/ -mmin -60 | grep bad_wifi && grep -q "$(iwgetid -r wlan0)" /tmp/bad_wifi; then + echo Not renewing wlan0 IP due to recent connectivity failure: + ls -la /tmp/bad_wifi + else + echo; echo "Getting new wlan0 IP" + ps aux | grep -v grep | grep -q "dhclient wlan0" && sudo killall dhclient + sudo dhclient wlan0 -r + sudo dhclient wlan0 + fi +} + +function stop_hotspot { + if grep -q $HostAPDIP /etc/network/interfaces || iwconfig wlan0 | grep Mode:Master; then + echo "Shutting down local-only hotspot" + echo "Attempting to stop hostapd" + /etc/init.d/hostapd stop + echo "Attempting to stop dnsmasq" + /etc/init.d/dnsmasq stop + echo "Activating client config" + ifdown wlan0 + cp /etc/network/interfaces.client /etc/network/interfaces + ifup wlan0 + echo "Renewing IP Address for wlan0" + dhclient_restart + else + echo -n "At $(date) my local hotspot is not running" + if ! cat preferences.json | jq -e .offline_hotspot >/dev/null; then + echo " (and not enabled in preferences.json)" + else + echo + fi + fi +} + +function stop_cycle { + stop_hotspot + echo "Cycling wlan0" + ifdown wlan0; ifup wlan0 +} + + +function start_hotspot { + echo + if ls /tmp/disable_hotspot; then + stop_cycle + elif ! ls preferences.json 2>/dev/null >/dev/null \ + || ! cat preferences.json | jq -e .offline_hotspot >/dev/null; then + echo "Offline hotspot not enabled in preferences.json" + stop_cycle + elif [[ -z $1 ]]; then + echo "No BT MAC provided: not activating local-only hotspot" + echo "Cycling wlan0" + ifdown wlan0; ifup wlan0 + elif grep -q $HostAPDIP /etc/network/interfaces \ + && ifconfig wlan0 | grep -q $HostAPDIP; then + echo "Local hotspot is running." + service hostapd status > /dev/null || service hostapd restart + service dnsmasq status > /dev/null || service dnsmasq restart + elif ! ls /etc/network/interfaces.ap 2>/dev/null >/dev/null; then + echo "Local-only hotspot not configured" + stop_cycle + else + echo "Unable to connect via wifi or Bluetooth; activating local-only hotspot" + echo "Killing wpa_supplicant" + #killall wpa_supplicant + wpa_cli terminate + echo "Shutting down wlan0" + ifdown wlan0 + echo "Activating AP config" + cp /etc/network/interfaces.ap /etc/network/interfaces + ifup wlan0 + echo "Attempting to start hostapd" + /etc/init.d/hostapd start + echo "Attempting to start dnsmasq" + service udhcpd stop + /etc/init.d/dnsmasq start + systemctl daemon-reload + #echo "Stopping networking" + #/etc/init.d/networking stop + #echo "Starting networking" + #/etc/init.d/networking start + sleep 5 + echo "Setting IP Address for wlan0" + /sbin/ifconfig wlan0 $HostAPDIP netmask 255.255.255.0 up + fi +} + +function dhclient_restart { + ps aux | grep -v grep | grep -q "dhclient wlan0" && sudo killall dhclient + sudo dhclient wlan0 -r + sudo dhclient wlan0 +} + +function restart_networking { + echo; echo "Error, cycling networking " + sudo /etc/init.d/networking stop + sleep 5 + sudo /etc/init.d/networking start + echo "and getting new wlan0 IP" + dhclient_restart +} + +main "$@" diff --git a/bin/oref0-pebble.js b/bin/oref0-pebble.js index ffc70a81a..bf9b9df3a 100755 --- a/bin/oref0-pebble.js +++ b/bin/oref0-pebble.js @@ -50,19 +50,28 @@ function fileHM(file) { return HMS[0].concat(":", HMS[1]); } +function usage ( ) { + console.log('usage: ', process.argv.slice(0, 2), ' [meal.json]'); +} + if (!module.parent) { var fs = require('fs'); - var glucose_input = process.argv.slice(2, 3).pop() - var iob_input = process.argv.slice(3, 4).pop() - var basalprofile_input = process.argv.slice(4, 5).pop() - var currenttemp_input = process.argv.slice(5, 6).pop() - var requestedtemp_input = process.argv.slice(6, 7).pop() - var enactedtemp_input = process.argv.slice(7, 8).pop() + var glucose_input = process.argv[2] + if ([null, '--help', '-h', 'help'].indexOf(glucose_input) > 0) { + usage( ); + process.exit(0) + } + var iob_input = process.argv[3] + var basalprofile_input = process.argv[4] + var currenttemp_input = process.argv[5] + var requestedtemp_input = process.argv[6] + var enactedtemp_input = process.argv[7] + var meal_input = process.argv[8] if (!glucose_input || !iob_input || !basalprofile_input || !currenttemp_input || !requestedtemp_input || !enactedtemp_input) { - console.log('usage: ', process.argv.slice(0, 2), ' '); + usage( ); process.exit(1); } @@ -78,7 +87,7 @@ if (!module.parent) { var bgnow = glucose_data[0].glucose; var iob_data = require(cwd + '/' + iob_input); - iob = iob_data.iob.toFixed(1); + iob = iob_data[0].iob.toFixed(1); var basalprofile_data = require(cwd + '/' + basalprofile_input); var basalRate; basalLookup(); @@ -91,7 +100,11 @@ if (!module.parent) { } else { tempstring = "Tmp: " + temp.duration + "m@" + temp.rate.toFixed(1); } - var requestedtemp = require(cwd + '/' + requestedtemp_input); + try { + var requestedtemp = require(cwd + '/' + requestedtemp_input); + } catch (e) { + return console.error("Could not parse requestedtemp: ", e); + } var reqtempstring; if (typeof requestedtemp.duration === 'undefined') { reqtempstring = "None"; @@ -99,7 +112,7 @@ if (!module.parent) { else if (requestedtemp.duration < 1) { reqtempstring = "Cancel"; } else { - reqtempstring = requestedtemp.duration + "m@" + requestedtemp.rate.toFixed(1) + "U"; + reqtempstring = requestedtemp.duration + "m@" + requestedtemp.rate.toFixed(1); } var enactedtemp = require(cwd + '/' + enactedtemp_input); if (enactedtemp.duration < 1) { @@ -112,17 +125,35 @@ if (!module.parent) { enactedHMS = enactedDate.toLocaleTimeString().split(":") enactedat = enactedHMS[0].concat(":", enactedHMS[1]); + var mealCOB = "???"; + if (typeof meal_input != 'undefined') { + try { + 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; + } + } catch (e) { + //console.error("Optional feature Meal Assist not configured."); + } + } + + var os = require("os"); + var host = os.hostname(); var pebble = { "content" : "" + bgnow + requestedtemp.tick + " " + bgTime + "\n" - + iob + "U->" + requestedtemp.eventualBG + "-" + requestedtemp.snoozeBG + "\n" - + "Act: " + enactedstring - + " at " + enactedat + "\n" + //+ iob + "U->" + requestedtemp.eventualBG + "-" + requestedtemp.snoozeBG + "\n" + + iob + "U->" + requestedtemp.eventualBG + "\n" + //+ "Act: " + enactedstring + //+ " at " + enactedat + "\n" + tempstring + " at " + temp_time + "\n" + "Req: " + reqtempstring + "\n" + requestedtemp.reason + "\n" - + "Sched: " + basalRate + "U/hr\n", + + "Sched: " + basalRate + "U/hr\n" + + "mealCOB: " + mealCOB + "g\n" + + host + "\n", "refresh_frequency": 1 }; diff --git a/bin/oref0-pump-loop.sh b/bin/oref0-pump-loop.sh new file mode 100755 index 000000000..6d2cd06bd --- /dev/null +++ b/bin/oref0-pump-loop.sh @@ -0,0 +1,824 @@ +#!/bin/bash + +# OREF0_DEBUG makes this script much more verbose +# and allows it to print additional debug information. +# OREF0_DEBUG=1 generally means to print everything that usually +# goes to stderr. (It will will include stack traces in case +# of errors or exceptions in sub commands) +# OREF0_DEBUG=2 is for debugging only. It will print all commands +# being executed as well as all their output, (use with care as it +# might overflow your log files) +# The default value is 0. A silent mode could also be implemented, but +# it hasn't been done at this point. +# Note: for future changes: +# - when subcommand outputs are not needed in the main log file: +# - redirect the output to either fd >&3 or fd >&4 based on +# - when you want the output visible. +OREF0_DEBUG=${OREF0_DEBUG:-0} +if [[ "$OREF0_DEBUG" -ge 1 ]] ; then + exec 3>&1 +else + exec 3>/dev/null +fi +if [[ "$OREF0_DEBUG" -ge 2 ]] ; then + exec 4>&1 + set -x +else + exec 4>/dev/null +fi + +# main pump-loop +main() { + check_duty_cycle + prep + if ! overtemp; then + echo && echo "Starting oref0-pump-loop at $(date) with $upto30s second wait_for_silence:" + try_fail wait_for_bg + try_fail wait_for_silence $upto30s + retry_fail preflight + try_fail if_mdt_get_bg + try_fail refresh_old_pumphistory_24h + try_fail refresh_old_profile + try_fail touch /tmp/pump_loop_enacted -r monitor/glucose.json + if smb_check_everything; then + if ( grep -q '"units":' enact/smb-suggested.json 2>&3); then + if try_return smb_bolus; then + touch /tmp/pump_loop_completed -r /tmp/pump_loop_enacted + else + smb_old_temp && ( \ + echo "Falling back to basal-only pump-loop" \ + && refresh_temp_and_enact \ + && refresh_pumphistory_and_enact \ + && refresh_profile \ + && refresh_pumphistory_24h \ + && touch /tmp/pump_loop_success \ + && echo Completed pump-loop at $(date) \ + && echo \ + ) + fi + fi + touch /tmp/pump_loop_completed -r /tmp/pump_loop_enacted + if ! glucose-fresh; then + refresh_profile 15 + if ! glucose-fresh; then + refresh_pumphistory_24h + if ! glucose-fresh; then + refresh_after_bolus_or_enact + fi + fi + fi + cat /tmp/oref0-updates.txt 2>&3 + touch /tmp/pump_loop_success + echo Completed oref0-pump-loop at $(date) + echo + else + # pump-loop errored out for some reason + fail "$@" + fi + fi +} + +function timerun { + echo "$(date): running $@" >> /tmp/timefile.txt + { time $@ 2> /tmp/stderr ; } 2>> /tmp/timefile.txt + echo "$(date): completed $@" >> /tmp/timefile.txt + cat /tmp/stderr 1>&2 +} + +function fail { + echo -n "oref0-pump-loop failed. " + if find enact/ -mmin -5 | grep smb-suggested.json >&4 && grep "too old" enact/smb-suggested.json >&4; then + touch /tmp/pump_loop_completed + wait_for_bg + echo "Unsuccessful oref0-pump-loop (BG too old) at $(date)" + # don't treat suspended pump as a complete failure + elif find monitor/ -mmin -5 | grep status.json >&4 && grep -q '"suspended": true' monitor/status.json; then + refresh_profile 15; refresh_pumphistory_24h + refresh_after_bolus_or_enact + echo "Incomplete oref0-pump-loop (pump suspended) at $(date)" + else + maybe_mmtune + echo "If pump and rig are close enough, this error usually self-resolves. Stand by for the next loop." + echo Unsuccessful oref0-pump-loop at $(date) + fi + if grep -q "percent" monitor/temp_basal.json; then + echo "Error: pump is set to % basal type. The pump won’t accept temporary basal rates in this mode. Please change the pump to absolute u/hr so temporary basal rates will then be able to be set." + fi + if ! cat preferences.json | jq . >&4; then + echo Error: syntax error in preferences.json: please go correct your typo. + fi + echo + exit 1 +} + +# The function "check_duty_cycle" checks if the loop has to run and it returns 0 if so. +# It exits the script with code 0 otherwise. +# The desicion is based on the time since last *successful* loop. +# !Note duty cycle times are set in seconds. +# +# Additionally it may start an "emergency action" if enabled. +# Possible actions are usb power cycling or reboot the system. +# The EMERGENCY_ACTION variable sets the allowable time between successful loops. +# If no loop has completed in that time, it performs the enabled actions. +# !Note to enable a emergency action use 0 to enable and 1 to disable +# +# The intention is two fold: +# First the battery consumption is reduced (Pump and Pi) if the loop runs less often. +# This is most dramatic for Enlite CGM, where wait_for_bg can't be used. +# Secondly, if Carelink USB is used with Enlite, and wait_for_silence can't be used, this +# prevents the loop from disrupting the communication between the pump and enlite sensors. +# +# Use DUTY_CYCLE=0 (default) if you don't want to limit the loop +# +# Suggestion for Carelink USB users are +# DUTY_CYCLE=120 +# EMERGENCY_ACTION=900 +# REBOOT_ENABLE=0 #0=true +# USB_RESET_ENABLE=0 #0=true +# +# Default is DUTY_CYCLE=0 to disable this feature. +DUTY_CYCLE=${DUTY_CYCLE:-0} + +EMERGENCY_ACTION=${EMERGENCY_ACTION:-900} +REBOOT_ENABLE=${REBOOT_ENABLE:-1} #0=true +USB_RESET_ENABLE=${USB_RESET_ENABLE:-1} #0=true + +function check_duty_cycle { + if [ "$DUTY_CYCLE" -gt "0" ]; then + if [ -e /tmp/pump_loop_success ]; then + DIFF_SECONDS=$(expr $(date +%s) - $(stat -c %Y /tmp/pump_loop_success)) + + if ([ $USB_RESET_ENABLE ] || [ $REBOOT_ENABLE ]) && [ "$DIFF_SECONDS" -gt "$EMERGENCY_ACTION" ]; then + if [ $USB_RESET_ENABLE ]; then + USB_RESET_DIFF=$EMERGENCY_ACTION + if [ -e /tmp/usp_power_cycled ]; then + USB_RESET_DIFF=$(expr $(date +%s) - $(stat -c %Y /tmp/usp_power_cycled)) + fi + + if [ "$USB_RESET_DIFF" -gt "$EMERGENCY_ACTION" ]; then + # file is old --> power-cycling is long time ago (most probably not this round) --> power-cycling + echo -n "$DIFF_SECONDS (of $DUTY_CYCLE) since last run --> trying to reset USB... " + /usr/local/bin/oref0-reset-usb 2>&3 >&4 + touch /tmp/usp_power_cycled + echo " done. --> start new cycle." + return 0 #return to loop routine + fi + fi + # if usb reset doesn't help or is not enabled --> reboot system + if [ $REBOOT_ENABLE ]; then + echo "$DIFF_SECONDS (of $DUTY_CYCLE) since last run --> rebooting." + sudo shutdown -r now + exit 0 + fi + elif [ "$DIFF_SECONDS" -gt "$DUTY_CYCLE" ]; then + echo "$DIFF_SECONDS (of $DUTY_CYCLE) since last run --> start new cycle." + return 0 + else + echo "$DIFF_SECONDS (of $DUTY_CYCLE) since last run --> stop now." + exit 0 + fi + else + echo "/tmp/pump_loop_success does not exist; create it to start the loop duty cycle." + # if pump_loop_success does not exist, use the system uptime + touch -d "$(cat /proc/uptime | awk '{print $1}') seconds ago" /tmp/pump_loop_success + return 0 + fi + fi +} + + +function overtemp { + # check for CPU temperature above 85°C + sensors -u 2>&3 | awk '$NF > 85' | grep input \ + && echo Rig is too hot: not running pump-loop at $(date)\ + && echo Please ensure rig is properly ventilated +} + +function smb_reservoir_before { + # Refresh reservoir.json and pumphistory.json + try_fail refresh_pumphistory_and_meal + try_fail cp monitor/reservoir.json monitor/lastreservoir.json + try_fail timerun openaps report invoke monitor/clock.json monitor/clock-zoned.json 2>&3 >&4 | tail -1 + echo -n "Checking pump clock: " + (cat monitor/clock-zoned.json; echo) | tr -d '\n' + echo -n " is within 90s of current time: " && date + if (( $(bc <<< "$(date +%s -d $(cat monitor/clock-zoned.json | sed 's/"//g')) - $(date +%s)") < -55 )) || (( $(bc <<< "$(date +%s -d $(cat monitor/clock-zoned.json | sed 's/"//g')) - $(date +%s)") > 55 )); then + echo Pump clock is more than 55s off: attempting to reset it + timerun oref0-set-device-clocks + fi + (( $(bc <<< "$(date +%s -d $(cat monitor/clock-zoned.json | sed 's/"//g')) - $(date +%s)") > -90 )) \ + && (( $(bc <<< "$(date +%s -d $(cat monitor/clock-zoned.json | sed 's/"//g')) - $(date +%s)") < 90 )) || { echo "Error: pump clock refresh error / mismatch"; fail "$@"; } + find monitor/ -mmin -1 -size +5c | grep -q pumphistory || { echo "Error: pumphistory too old"; fail "$@"; } +} + +# check if the temp was read more than 5m ago, or has been running more than 10m +function smb_old_temp { + (find monitor/ -mmin +5 -size +5c | grep -q temp_basal && echo temp_basal.json more than 5m old) \ + || ( jq --exit-status "(.duration-1) % 30 < 20" monitor/temp_basal.json >&4 \ + && echo -n "Temp basal set more than 10m ago: " && jq .duration monitor/temp_basal.json + ) +} + +# make sure everything is in the right condition to SMB +function smb_check_everything { + try_fail smb_reservoir_before + try_fail smb_enact_temp + if (grep -q '"units":' enact/smb-suggested.json 2>&3); then + # wait_for_silence and retry if first attempt fails + ( smb_verify_suggested || smb_suggest ) \ + && echo -n "Listening for $upto10s s silence: " && wait_for_silence $upto10s \ + && smb_verify_reservoir \ + && smb_verify_status \ + || ( echo Retrying SMB checks + wait_for_silence 10 + smb_verify_status \ + && smb_reservoir_before \ + && smb_enact_temp \ + && ( smb_verify_suggested || smb_suggest ) \ + && smb_verify_reservoir \ + && smb_verify_status + ) + else + echo -n "No bolus needed. " + fi +} + +function smb_suggest { + rm -rf enact/smb-suggested.json + ls enact/smb-suggested.json 2>&3 >&4 && die "enact/suggested.json present" + # Run determine-basal + echo -n Temp refresh + try_fail timerun openaps report invoke monitor/temp_basal.json monitor/clock.json monitor/clock-zoned.json 2>&3 >&4 | tail -1 + try_fail calculate_iob && echo ed + try_fail determine_basal && cp -up enact/smb-suggested.json enact/suggested.json + try_fail smb_verify_suggested +} + +function determine_basal { + if ( grep -q 12 settings/model.json ); then + timerun oref0-determine-basal monitor/iob.json monitor/temp_basal.json monitor/glucose.json settings/profile.json settings/autosens.json monitor/meal.json --reservoir monitor/reservoir.json > enact/smb-suggested.json + else + timerun oref0-determine-basal monitor/iob.json monitor/temp_basal.json monitor/glucose.json settings/profile.json settings/autosens.json monitor/meal.json --microbolus --reservoir monitor/reservoir.json > enact/smb-suggested.json + fi +} + +# enact the appropriate temp before SMB'ing, (only if smb_verify_enacted fails or a 0 duration temp is requested) +function smb_enact_temp { + smb_suggest + if ( echo -n "enact/smb-suggested.json: " && cat enact/smb-suggested.json | jq -C -c . && grep -q duration enact/smb-suggested.json 2>&3 && ! smb_verify_enacted || jq --exit-status '.duration == 0' enact/smb-suggested.json >&4 ); then ( + rm enact/smb-enacted.json + timerun openaps report invoke enact/smb-enacted.json 2>&3 >&4 | tail -1 + grep -q duration enact/smb-enacted.json || timerun openaps report invoke enact/smb-enacted.json 2>&3 >&4 | tail -1 + cp -up enact/smb-enacted.json enact/enacted.json + echo -n "enact/smb-enacted.json: " && cat enact/smb-enacted.json | jq -C -c '. | "Rate: \(.rate) Duration: \(.duration)"' + ) 2>&1 | egrep -v "^ |subg_rfspy|handler" + else + echo -n "No smb_enact needed. " + fi + ( smb_verify_enacted || ( smb_verify_status; smb_verify_enacted) ) +} + +function smb_verify_enacted { + # Read the currently running temp and + # verify rate matches (within 0.03U/hr) and duration is no shorter than 5m less than smb-suggested.json + rm -rf monitor/temp_basal.json + ( echo -n Temp refresh \ + && ( timerun openaps report invoke monitor/temp_basal.json || timerun openaps report invoke monitor/temp_basal.json ) \ + 2>&3 >&4 | tail -1 && echo -n "ed: " \ + ) && echo -n "monitor/temp_basal.json: " && cat monitor/temp_basal.json | jq -C -c . \ + && jq --slurp --exit-status 'if .[1].rate then (.[0].rate > .[1].rate - 0.03 and .[0].rate < .[1].rate + 0.03 and .[0].duration > .[1].duration - 5 and .[0].duration < .[1].duration + 20) else true end' monitor/temp_basal.json enact/smb-suggested.json >&4 +} + +function smb_verify_reservoir { + # Read the pump reservoir volume and verify it is within 0.1U of the expected volume + rm -rf monitor/reservoir.json + echo -n "Checking reservoir: " \ + && (timerun openaps report invoke monitor/reservoir.json || timerun openaps report invoke monitor/reservoir.json) 2>&3 >&4 | tail -1 \ + && echo -n "reservoir level before: " \ + && cat monitor/lastreservoir.json \ + && echo -n ", suggested: " \ + && jq -r -C -c .reservoir enact/smb-suggested.json | tr -d '\n' \ + && echo -n " and after: " \ + && cat monitor/reservoir.json && echo \ + && (( $(bc <<< "$(< monitor/lastreservoir.json) - $(< monitor/reservoir.json) <= 0.1") )) \ + && (( $(bc <<< "$(< monitor/lastreservoir.json) - $(< monitor/reservoir.json) >= 0") )) \ + && (( $(bc <<< "$(jq -r .reservoir enact/smb-suggested.json | tr -d '\n') - $(< monitor/reservoir.json) <= 0.1") )) \ + && (( $(bc <<< "$(jq -r .reservoir enact/smb-suggested.json | tr -d '\n') - $(< monitor/reservoir.json) >= 0") )) +} + +function smb_verify_suggested { + if grep incorrectly enact/smb-suggested.json 2>&3; then + echo "Checking system clock against pump clock:" + timerun oref0-set-system-clock 2>&3 >&4 + fi + if jq -e -r .deliverAt enact/smb-suggested.json; then + echo -n "Checking deliverAt: " && jq -r .deliverAt enact/smb-suggested.json | tr -d '\n' \ + && echo -n " is within 1m of current time: " && date \ + && (( $(bc <<< "$(date +%s -d $(jq -r .deliverAt enact/smb-suggested.json | tr -d '\n')) - $(date +%s)") > -60 )) \ + && (( $(bc <<< "$(date +%s -d $(jq -r .deliverAt enact/smb-suggested.json | tr -d '\n')) - $(date +%s)") < 60 )) \ + && echo "and that smb-suggested.json is less than 1m old" \ + && (find enact/ -mmin -1 -size +5c | grep -q smb-suggested.json) + else + echo No deliverAt found. + cat enact/smb-suggested.json + false + fi +} + +function smb_verify_status { + # Read the pump status and verify it is not bolusing + rm -rf monitor/status.json + echo -n "Checking pump status (suspended/bolusing): " + ( timerun openaps report invoke monitor/status.json || timerun openaps report invoke monitor/status.json ) 2>&3 >&4 | tail -1 \ + && cat monitor/status.json | jq -C -c . \ + && grep -q '"status": "normal"' monitor/status.json \ + && grep -q '"bolusing": false' monitor/status.json \ + && if grep -q '"suspended": true' monitor/status.json; then + echo -n "Pump suspended; " + unsuspend_if_no_temp + refresh_pumphistory_and_meal + false + fi \ + && if grep -q 12 monitor/status.json; then + echo -n "x12 model detected." + true + fi +} + +function smb_bolus { + # Verify that the suggested.json is less than 5 minutes old + # and administer the supermicrobolus + find enact/ -mmin -5 | grep smb-suggested.json >&4 \ + && if (grep -q '"units":' enact/smb-suggested.json 2>&3); then + # press ESC three times on the pump to exit Bolus Wizard before SMBing, to help prevent A52 errors + echo -n "Sending ESC ESC ESC to exit any open menus before SMBing: " + try_return timerun openaps use pump press_keys esc esc esc | jq .completed | grep true \ + && try_return timerun openaps report invoke enact/bolused.json 2>&3 >&4 | tail -1 \ + && echo -n "enact/bolused.json: " && cat enact/bolused.json | jq -C -c . \ + && rm -rf enact/smb-suggested.json + else + echo -n "No bolus needed. " + fi +} + +function refresh_after_bolus_or_enact { + if (find enact/ -mmin -2 -size +5c | grep -q bolused.json || (cat monitor/temp_basal.json | json -c "this.duration > 28" | grep -q duration)); then + # refresh profile if >5m old to give SMB a chance to deliver + refresh_profile 3 + refresh_pumphistory_and_meal \ + || ( wait_for_silence 15 && refresh_pumphistory_and_meal ) \ + || ( wait_for_silence 30 && refresh_pumphistory_and_meal ) + calculate_iob && determine_basal 2>&3 >&4 \ + && cp -up enact/smb-suggested.json enact/suggested.json \ + && echo -n "IOB: " && cat enact/smb-suggested.json | jq .IOB + true + fi + +} + +function unsuspend_if_no_temp { + # If temp basal duration is zero, unsuspend pump + if (cat monitor/temp_basal.json | json -c "this.duration == 0" | grep -q duration); then + if (grep -iq '"unsuspend_if_no_temp": true' preferences.json); then + echo Temp basal has ended: unsuspending pump + timerun openaps use pump resume_pump + else + echo unsuspend_if_no_temp not enabled in preferences.json: leaving pump suspended + fi + else + # If temp basal duration is > zero, do nothing + echo Temp basal still running: leaving pump suspended + fi +} + +# calculate random sleep intervals, and get TTY port +function prep { + set -o pipefail + + upto10s=$[ ( $RANDOM / 3277 + 1) ] + upto20s=$[ ( $RANDOM / 1638 + 1) ] + upto30s=$[ ( $RANDOM / 1092 + 1) ] + # read tty port from pump.ini + eval $(grep port pump.ini | sed "s/ //g") + # if that fails, try the Explorer board default port + if [ -z $port ]; then + port=/dev/spidev5.1 + fi +} + +function if_mdt_get_bg { + echo -n + if grep "MDT cgm" openaps.ini 2>&3 >&4; then + echo \ + && echo Attempting to retrieve MDT CGM data from pump + #due to sometimes the pump is not in a state to give this command repeat until it completes + #"decocare.errors.DataTransferCorruptionError: Page size too short" + n=0 + until [ $n -ge 3 ]; do + timerun openaps report invoke monitor/cgm-mm-glucosedirty.json 2>&3 >&4 && break + echo + echo CGM data retrieval from pump disrupted, retrying in 5 seconds... + n=$[$n+1] + sleep 5; + echo Reattempting to retrieve MDT CGM data + done + if [ -f "monitor/cgm-mm-glucosedirty.json" ]; then + if [ -f "cgm/glucose.json" ]; then + if [ $(date -d $(jq .[1].date monitor/cgm-mm-glucosedirty.json | tr -d '"') +%s) == $(date -d $(jq .[0].display_time monitor/glucose.json | tr -d '"') +%s) ]; then + echo MDT CGM data retrieved \ + && echo No new MDT CGM data to reformat \ + && echo + # TODO: remove if still unused at next oref0 release + # if you want to wait for new bg uncomment next lines and add a backslash after echo above + #&& wait_for_mdt_get_bg \ + #&& mdt_get_bg + else + mdt_get_bg + fi + else + mdt_get_bg + fi + else + echo "Unable to get cgm data from pump" + fi + fi +} +# TODO: remove if still unused at next oref0 release +function wait_for_mdt_get_bg { + # This might not really be needed since very seldom does a loop take less time to run than CGM Data takes to refresh. + until [ $(date --date="@$(($(date -d $(jq .[1].date monitor/cgm-mm-glucosedirty.json| tr -d '"') +%s) + 300))" +%s) -lt $(date +%s) ]; do + CGMDIFFTIME=$(( $(date --date="@$(($(date -d $(jq .[1].date monitor/cgm-mm-glucosedirty.json| tr -d '"') +%s) + 300))" +%s) - $(date +%s) )) + echo "Last CGM Time was $(date -d $(jq .[1].date monitor/cgm-mm-glucosedirty.json| tr -d '"') +"%r") wait untill $(date --date="@$(($(date #-d $(jq .[1].date monitor/cgm-mm-glucosedirty.json| tr -d '"') +%s) + 300))" +"%r")to continue" + echo "waiting for $CGMDIFFTIME seconds before continuing" + sleep $CGMDIFFTIME + until timerun openaps report invoke monitor/cgm-mm-glucosedirty.json 2>&3 >&4; do + echo cgm data from pump disrupted, retrying in 5 seconds... + sleep 5; + echo -n MDT cgm data retrieve + done + done +} +function mdt_get_bg { + timerun openaps report invoke monitor/cgm-mm-glucosetrend.json 2>&3 >&4 \ + && timerun openaps report invoke cgm/cgm-glucose.json 2>&3 >&4 \ + && grep -q glucose cgm/cgm-glucose.json \ + && echo MDT CGM data retrieved \ + && cp -pu cgm/cgm-glucose.json cgm/glucose.json \ + && cp -pu cgm/glucose.json monitor/glucose-unzoned.json \ + && echo -n MDT New cgm data reformat \ + && timerun openaps report invoke monitor/glucose.json 2>&3 >&4 \ + && timerun openaps report invoke nightscout/glucose.json 2>&3 >&4 \ + && echo ted +} +# make sure we can talk to the pump and get a valid model number +function preflight { + echo -n "Preflight " + # only 515, 522, 523, 715, 722, 723, 554, and 754 pump models have been tested with SMB + ( timerun openaps report invoke settings/model.json || timerun openaps report invoke settings/model.json ) 2>&3 >&4 | tail -1 \ + && ( egrep -q "[57](15|22|23|54)" settings/model.json || (grep -q 12 settings/model.json && echo -n "(x12 models do not support SMB safety checks, SMB will not be available.) ") ) \ + && echo -n "OK. " \ + || ( echo -n "fail. "; false ) +} + +# reset radio, init world wide pump (if applicable), mmtune, and wait_for_silence 60 if no signal +function mmtune { + if grep "carelink" pump.ini 2>&1 >/dev/null; then + echo "using carelink; skipping mmtune" + return + fi + + # TODO: remove reset_spi_serial.py once oref0_init_pump_comms.py is fixed to do it correctly + if [[ $port == "/dev/spidev5.1" ]]; then + reset_spi_serial.py 2>&3 + fi + oref0_init_pump_comms.py + echo -n "Listening for 40s silence before mmtuning: " + for i in $(seq 1 800); do + echo -n . + any_pump_comms 40 2>&3 | egrep -v subg | egrep -q No \ + && echo "No interfering pump comms detected from other rigs (this is a good thing!)" \ + && break + done + echo {} > monitor/mmtune.json + echo -n "mmtune: " && timerun openaps report invoke monitor/mmtune.json 2>&3 >&4 | tail -1 + grep -v setFreq monitor/mmtune.json | grep -A2 $(json -a setFreq -f monitor/mmtune.json) | while read line + do echo -n "$line " + done + rssi_wait=$(grep -v setFreq monitor/mmtune.json | grep -A2 $(json -a setFreq -f monitor/mmtune.json) | tail -1 | awk '($1 < -60) {print -($1+60)*2}') + if [[ $rssi_wait > 1 ]]; then + echo "waiting for $rssi_wait second silence before continuing" + wait_for_silence $rssi_wait + preflight + echo "Done waiting for rigs with better signal." + else + echo "No wait required." + fi +} + +function maybe_mmtune { + if ( find /tmp/ -mmin -15 | egrep -q "pump_loop_completed" ); then + # mmtune ~ 25% of the time + [[ $(( ( RANDOM % 100 ) )) > 75 ]] \ + && mmtune + else + echo "pump_loop_completed more than 15m old; waiting for 40s silence before mmtuning" + wait_for_silence 40 + mmtune + fi +} + +function any_pump_comms { + mmeowlink-any-pump-comms.py --port $port --wait-for $1 +} + +# listen for $1 seconds of silence (no other rigs talking to pump) before continuing +function wait_for_silence { + if grep "carelink" pump.ini 2>&1 >/dev/null; then + echo "using carelink; not waiting for silence" + return + fi + if [ -z $1 ]; then + waitfor=40 + else + waitfor=$1 + fi + # check radio multiple times, and mmtune if all checks fail + ( ( out=$(any_pump_comms 1) ; echo $out | grep -qi comms || (echo $out; false) ) || \ + ( echo -n .; sleep 1; out=$(any_pump_comms 1) ; echo $out | grep -qi comms || (echo $out; false) ) || \ + ( echo -n .; sleep 2; out=$(any_pump_comms 1) ; echo $out | grep -qi comms || (echo $out; false) ) || \ + ( echo -n .; sleep 4; out=$(any_pump_comms 1) ; echo $out | grep -qi comms || (echo $out; false) ) || \ + ( echo -n .; sleep 8; out=$(any_pump_comms 1) ; echo $out | grep -qi comms || (echo $out; false) ) + ) 2>&1 | tail -2 \ + && echo -n "Radio ok. " || { echo -n "Radio check failed. "; any_pump_comms 1 2>&1 | tail -1; mmtune; } + echo -n "Listening: " + for i in $(seq 1 800); do + echo -n . + any_pump_comms $waitfor 2>&3 | egrep -v subg | egrep -q No \ + && echo "No interfering pump comms detected from other rigs (this is a good thing!)" \ + && break + done +} + +# Refresh pumphistory etc. +function refresh_pumphistory_and_meal { + retry_return timerun openaps report invoke monitor/status.json 2>&3 >&4 | tail -1 || return 1 + echo -n Ref + ( grep -q "model.*12" monitor/status.json || \ + test $(cat monitor/status.json | json suspended) == true || \ + test $(cat monitor/status.json | json bolusing) == false ) \ + || { echo; cat monitor/status.json | jq -c -C .; return 1; } + echo -n resh + retry_return monitor_pump || return 1 + echo -n ed + retry_return merge_pumphistory || return 1 + echo -n " pumphistory" + retry_return timerun oref0-meal monitor/pumphistory-merged.json settings/profile.json monitor/clock-zoned.json monitor/glucose.json settings/basal_profile.json monitor/carbhistory.json > monitor/meal.json || return 1 + echo " and meal.json" +} + +# monitor-pump report invoke monitor/clock.json monitor/temp_basal.json monitor/pumphistory.json monitor/pumphistory-zoned.json monitor/clock-zoned.json monitor/iob.json monitor/reservoir.json monitor/battery.json monitor/status.json +function monitor_pump { + retry_return invoke_pumphistory_etc || return 1 + retry_return invoke_reservoir_etc || return 1 +} + +function calculate_iob { + timerun oref0-calculate-iob monitor/pumphistory-merged.json settings/profile.json monitor/clock-zoned.json settings/autosens.json > monitor/iob.json || { echo; echo "Couldn't calculate IOB"; fail "$@"; } +} + +function invoke_pumphistory_etc { + timerun openaps report invoke monitor/clock.json monitor/temp_basal.json monitor/pumphistory.json monitor/pumphistory-zoned.json monitor/clock-zoned.json 2>&3 >&4 | tail -1 + test ${PIPESTATUS[0]} -eq 0 +} + +function invoke_reservoir_etc { + timerun openaps report invoke monitor/reservoir.json monitor/battery.json monitor/status.json 2>&3 >&4 | tail -1 + test ${PIPESTATUS[0]} -eq 0 +} + +function merge_pumphistory { + jq -s '.[0] + .[1]|unique|sort_by(.timestamp)|reverse' monitor/pumphistory-zoned.json settings/pumphistory-24h-zoned.json > monitor/pumphistory-merged.json + calculate_iob +} + +# Calculate new suggested temp basal and enact it +function enact { + rm enact/suggested.json + timerun openaps report invoke enact/suggested.json \ + && if (cat enact/suggested.json && grep -q duration enact/suggested.json); then ( + rm enact/enacted.json + timerun openaps report invoke enact/enacted.json 2>&3 >&4 | tail -1 + grep -q duration enact/enacted.json || timerun openaps report invoke enact/enacted.json ) 2>&1 | egrep -v "^ |subg_rfspy|handler" + fi + grep incorrectly enact/suggested.json && timerun oref0-set-system-clock 2>&3 + echo -n "enact/enacted.json: " && cat enact/enacted.json | jq -C -c . +} + +# refresh pumphistory if it's more than 30m old, but don't enact +function refresh_old_pumphistory { + find monitor/ -mmin -30 -size +100c | grep -q pumphistory-zoned \ + || ( echo -n "Old pumphistory, waiting for $upto30s seconds of silence: " && wait_for_silence $upto30s && refresh_pumphistory_and_meal ) +} + +# refresh pumphistory_24h if it's more than 2h old +function refresh_old_pumphistory_24h { + find settings/ -mmin -120 -size +100c | grep -q pumphistory-24h-zoned \ + || ( echo -n "Old pumphistory-24h, waiting for $upto30s seconds of silence: " && wait_for_silence $upto30s \ + && echo -n Old pumphistory-24h refresh \ + && timerun openaps report invoke settings/pumphistory-24h.json settings/pumphistory-24h-zoned.json 2>&3 >&4 | tail -1 && echo ed ) +} + +# refresh settings/profile if it's more than 1h old +function refresh_old_profile { + find settings/ -mmin -60 -size +5c | grep -q settings/profile.json && echo -n "Profile less than 60m old; " \ + || { echo -n "Old settings: " && get_settings; } + if ls settings/profile.json >&4 && cat settings/profile.json | jq -e .current_basal >&3; then + echo -n "Profile valid. " + else + echo -n "Profile invalid: " + ls -lart settings/profile.json + get_settings + fi +} + +# get-settings report invoke settings/model.json settings/bg_targets_raw.json settings/bg_targets.json settings/insulin_sensitivities_raw.json settings/insulin_sensitivities.json settings/basal_profile.json settings/settings.json settings/carb_ratios.json settings/pumpprofile.json settings/profile.json +function get_settings { + if grep -q 12 settings/model.json + then + # If we have a 512 or 712, then remove the incompatible reports, so the loop will work + # On the x12 pumps, these 'reports' are simulated by static json files created during the oref0-setup.sh run. + NON_X12_ITEMS="settings/bg_targets.json" + else + # On all other supported pumps, these reports work. + NON_X12_ITEMS="settings/bg_targets_raw.json settings/bg_targets.json settings/basal_profile.json settings/settings.json" + fi + retry_return timerun openaps report invoke settings/model.json settings/insulin_sensitivities_raw.json settings/insulin_sensitivities.json settings/carb_ratios.json $NON_X12_ITEMS 2>&3 >&4 | tail -1 || return 1 + # generate settings/pumpprofile.json without autotune + timerun oref0-get-profile settings/settings.json settings/bg_targets.json settings/insulin_sensitivities.json settings/basal_profile.json preferences.json settings/carb_ratios.json settings/temptargets.json --model=settings/model.json settings/autotune.json 2>&3 | jq . > settings/pumpprofile.json.new || { echo "Couldn't refresh pumpprofile"; fail "$@"; } + if ls settings/pumpprofile.json.new >&4 && cat settings/pumpprofile.json.new | jq -e .current_basal >&4; then + mv settings/pumpprofile.json.new settings/pumpprofile.json + echo -n "Pump profile refreshed; " + else + echo "Invalid pumpprofile.json.new after refresh" + ls -lart settings/pumpprofile.json.new + fi + # generate settings/profile.json.new with autotune + timerun oref0-get-profile settings/settings.json settings/bg_targets.json settings/insulin_sensitivities.json settings/basal_profile.json preferences.json settings/carb_ratios.json settings/temptargets.json --model=settings/model.json --autotune settings/autotune.json | jq . > settings/profile.json.new || { echo "Couldn't refresh profile"; fail "$@"; } + if ls settings/profile.json.new >&4 && cat settings/profile.json.new | jq -e .current_basal >&4; then + mv settings/profile.json.new settings/profile.json + echo -n "Settings refreshed; " + else + echo "Invalid profile.json.new after refresh" + ls -lart settings/profile.json.new + fi +} + +function refresh_smb_temp_and_enact { + # set mtime of monitor/glucose.json to the time of its most recent glucose value + setglucosetimestamp + # only smb_enact_temp if we haven't successfully completed a pump_loop recently + # (no point in enacting a temp that's going to get changed after we see our last SMB) + if (cat monitor/temp_basal.json | json -c "this.duration > 20" | grep -q duration); then + echo -n "Temp duration >20m. " + elif ( find /tmp/ -mmin +10 | grep -q /tmp/pump_loop_completed ); then + echo "pump_loop_completed more than 10m ago: setting temp before refreshing pumphistory. " + smb_enact_temp + else + echo -n "pump_loop_completed less than 10m ago. " + fi +} + +function refresh_temp_and_enact { + # set mtime of monitor/glucose.json to the time of its most recent glucose value + setglucosetimestamp + # TODO: use pump_loop_completed logic as in refresh_smb_temp_and_enact + if ( (find monitor/ -newer monitor/temp_basal.json | grep -q glucose.json && echo -n "glucose.json newer than temp_basal.json. " ) \ + || (! find monitor/ -mmin -5 -size +5c | grep -q temp_basal && echo "temp_basal.json more than 5m old. ")); then + echo -n Temp refresh + retry_fail invoke_temp_etc + echo ed + timerun oref0-calculate-iob monitor/pumphistory-merged.json settings/profile.json monitor/clock-zoned.json settings/autosens.json || { echo "Couldn't calculate IOB"; fail "$@"; } + if (cat monitor/temp_basal.json | json -c "this.duration < 27" | grep -q duration); then + enact; else echo Temp duration 27m or more + fi + else + echo -n "temp_basal.json less than 5m old. " + fi +} + +function invoke_temp_etc { + timerun openaps report invoke monitor/temp_basal.json monitor/clock.json monitor/clock-zoned.json 2>&3 >&4 | tail -1 + test ${PIPESTATUS[0]} -eq 0 + calculate_iob +} + +function refresh_pumphistory_and_enact { + # set mtime of monitor/glucose.json to the time of its most recent glucose value + setglucosetimestamp + if ((find monitor/ -newer monitor/pumphistory-zoned.json | grep -q glucose.json && echo -n "glucose.json newer than pumphistory. ") \ + || (find enact/ -newer monitor/pumphistory-zoned.json | grep -q enacted.json && echo -n "enacted.json newer than pumphistory. ") \ + || ((! find monitor/ -mmin -5 | grep -q pumphistory-zoned || ! find monitor/ -mmin +0 | grep -q pumphistory-zoned) && echo -n "pumphistory more than 5m old. ") ); then + { echo -n ": " && refresh_pumphistory_and_meal && enact; } + else + echo Pumphistory less than 5m old + fi +} + +function refresh_profile { + if [ -z $1 ]; then + profileage=10 + else + profileage=$1 + fi + find settings/ -mmin -$profileage -size +5c | grep -q settings.json && echo -n "Settings less than $profileage minutes old. " \ + || get_settings +} + +function wait_for_bg { + if grep "MDT cgm" openaps.ini 2>&3 >&4; then + echo "MDT CGM configured; not waiting" + elif egrep -q "Warning:" enact/smb-suggested.json 2>&3; then + echo "Retrying without waiting for new BG" + elif egrep -q "Waiting [0](\.[0-9])?m ([0-6]?[0-9]s )?to microbolus again." enact/smb-suggested.json 2>&3; then + echo "Retrying microbolus without waiting for new BG" + else + echo -n "Waiting up to 4 minutes for new BG: " + for i in `seq 1 24`; do + if glucose-fresh; then + break + else + echo -n .; sleep 10 + fi + done + fi +} + +function glucose-fresh { + # set mtime of monitor/glucose.json to the time of its most recent glucose value + if jq -e .[0].display_time monitor/glucose.json >/dev/null; then + touch -d $(jq -r .[0].display_time monitor/glucose.json) monitor/glucose.json 2>&3 + else + touch -d "$(date -R -d @$(jq .[0].date/1000 monitor/glucose.json))" monitor/glucose.json 2>&3 + fi + if (! ls /tmp/pump_loop_completed >&4 ); then + return 0; + elif (find monitor/ -newer /tmp/pump_loop_completed | grep -q glucose.json); then + echo glucose.json newer than pump_loop_completed + return 0; + else + return 1; + fi +} + +function refresh_pumphistory_24h { + if [ -e ~/src/EdisonVoltage/voltage ]; then + sudo ~/src/EdisonVoltage/voltage json batteryVoltage battery > monitor/edison-battery.json 2>&3 + elif [ -e /root/src/openaps-menu/scripts/getvoltage.sh ]; then + sudo /root/src/openaps-menu/scripts/getvoltage.sh > monitor/edison-battery.json 2>&3 + else + rm monitor/edison-battery.json 2>&3 + fi + if (! ls monitor/edison-battery.json 2>&3 >&4); then + echo -n "Edison battery level not found. " + autosens_freq=15 + elif (jq --exit-status ".battery >= 98 or (.battery <= 70 and .battery >= 60)" monitor/edison-battery.json >&4); then + echo -n "Edison battery at $(jq .battery monitor/edison-battery.json)% is charged (>= 98%) or likely charging (60-70%). " + autosens_freq=15 + elif (jq --exit-status ".battery < 98" monitor/edison-battery.json >&4); then + echo -n "Edison on battery: $(jq .battery monitor/edison-battery.json)%. " + autosens_freq=30 + else + echo -n "Edison battery level unknown. " + autosens_freq=15 + fi + find settings/ -mmin -$autosens_freq -size +100c | grep -q pumphistory-24h-zoned && echo "Pumphistory-24 < ${autosens_freq}m old" \ + || { echo -n pumphistory-24h refresh \ + && timerun openaps report invoke settings/pumphistory-24h.json settings/pumphistory-24h-zoned.json 2>&3 >&4 | tail -1 && echo ed; } +} + +function setglucosetimestamp { + if grep "MDT cgm" openaps.ini 2>&3 >&4; then + touch -d "$(date -R -d @$(jq .[0].date/1000 nightscout/glucose.json))" monitor/glucose.json + else + touch -d "$(date -R -d @$(jq .[0].date/1000 monitor/glucose.json))" monitor/glucose.json + fi +} + +retry_fail() { + "$@" || { echo Retrying $*; "$@"; } || { echo "Couldn't $*"; fail "$@"; } +} +retry_return() { + "$@" || { echo Retrying $*; "$@"; } || { echo "Couldn't $* - continuing"; return 1; } +} +try_fail() { + "$@" || { echo "Couldn't $*"; fail "$@"; } +} +try_return() { + "$@" || { echo "Couldn't $*" - continuing; return 1; } +} +die() { + echo "$@" + exit 1 +} + +main "$@" diff --git a/bin/oref0-pushover.sh b/bin/oref0-pushover.sh new file mode 100755 index 000000000..aa73b7e20 --- /dev/null +++ b/bin/oref0-pushover.sh @@ -0,0 +1,191 @@ +#!/bin/bash + +TOKEN=$1 +USER=$2 +FILE=${3-enact/suggested.json} +SOUND=${4-none} +SNOOZE=${5-15} +ONLYFOR=${6-carbs} +PRIORITY=0 +RETRY=60 +EXPIRE=600 + +PREF_FILE=preferences.json + +#echo "Running: $0 $TOKEN $USER $FILE $SOUND $SNOOZE" + +if [ -z $TOKEN ] || [ -z $USER ]; then + echo "Usage: $0 [enact/suggested.json] [none] [15] [carbs|insulin]" + exit +fi + +PREF_VALUE=$(cat $PREF_FILE | jq --raw-output -r .pushover_sound 2>/dev/null) + +if [ ! -z $PREF_VALUE ] && [ $PREF_VALUE != "null" ]; then + SOUND=$PREF_VALUE +fi + +PREF_VALUE=$(cat $PREF_FILE | jq .pushover_snooze 2>/dev/null) + +if [ ! -z $PREF_VALUE ] && [ $PREF_VALUE != "null" ] && [ "$PREF_VALUE" -eq "$PREF_VALUE" ]; then + SNOOZE=$PREF_VALUE +fi + +PREF_VALUE=$(cat $PREF_FILE | jq --raw-output -r .pushover_only 2>/dev/null) + +if [ ! -z $PREF_VALUE ] && [ $PREF_VALUE != "null" ]; then + ONLYFOR=$PREF_VALUE +fi + +PREF_VALUE=$(cat $PREF_FILE | jq .pushover_priority 2>/dev/null) + +if [ ! -z $PREF_VALUE ] && [ $PREF_VALUE != "null" ] && [ "$PREF_VALUE" -eq "$PREF_VALUE" ]; then + PRIORITY=$PREF_VALUE +fi + +PREF_VALUE=$(cat $PREF_FILE | jq .pushover_retry 2>/dev/null) + +if [ ! -z $PREF_VALUE ] && [ $PREF_VALUE != "null" ] && [ "$PREF_VALUE" -eq "$PREF_VALUE" ]; then + RETRY=$PREF_VALUE +fi + +PREF_VALUE=$(cat $PREF_FILE | jq .pushover_expire 2>/dev/null) + +if [ ! -z $PREF_VALUE ] && [ $PREF_VALUE != "null" ] && [ "$PREF_VALUE" -eq "$PREF_VALUE" ]; then + EXPIRE=$PREF_VALUE +fi + +if [ "$SOUND" = "default" ]; then + SOUND_OPTION="" +else + SOUND_OPTION="-F sound=$SOUND" +fi + +# Set priority to the default if it is an invalid value +if ((PRIORITY < -2)) || ((PRIORITY > 2)); then + PRIORITY=0 +fi + +if ((PRIORITY == 2)); then + PRIORITY_OPTIONS="-F retry=$RETRY -F expire=$EXPIRE" +else + PRIORITY_OPTIONS="" +fi + +date + +if find monitor/ -mmin -$SNOOZE | grep -q pushover-sent; then + echo "Last pushover sent less than $SNOOZE minutes ago." +elif ! find $FILE -mmin -5 | grep -q $FILE; then + echo "$FILE more than 5 minutes old" + exit +elif ! cat $FILE | egrep "add'l|maxBolus"; then + echo "No additional carbs or bolus required." +elif [[ $ONLYFOR =~ "carb" ]] && ! cat $FILE | egrep "add'l"; then + echo "No additional carbs required." +elif [[ $ONLYFOR =~ "insulin" ]] && ! cat $FILE | egrep "maxBolus"; then + echo "No additional insulin required." +else + curl -s -F token=$TOKEN -F user=$USER $SOUND_OPTION -F priority=$PRIORITY $PRIORITY_OPTIONS -F "message=$(jq -c "{bg, tick, carbsReq, insulinReq, reason}|del(.[] | nulls)" $FILE) - $(hostname)" https://api.pushover.net/1/messages.json && touch monitor/pushover-sent + echo +fi + +# Send to Pushover glances API +# For watch face updates once every 10 minutes +# Works for Apple Watch complications +# Not tested for Android Wear notifications yet + +# Use file to make sure we don't update glances more often than every 10 mins +# Apple watch disables any complication updates that happen more frequently + +source $HOME/.bash_profile +key=${MAKER_KEY:-"null"} +carbsReq=`jq .carbsReq ${FILE}` +tick=`jq .tick ${FILE}` +bgNow=`jq .bg ${FILE}` +delta=`echo "${tick}" | tr -d +` +delta="${delta%\"}" +delta="${delta#\"}" +cob=`jq .COB $FILE` +iob=`jq .IOB $FILE` + +#echo "carbsReq=${carbsReq} tick=${tick} bgNow=${bgNow} delta=${delta} cob=${cob} iob=${iob}" +pushoverGlances=$(cat preferences.json | jq -M '.pushoverGlances') + +if [ "${pushoverGlances}" == "null" -o "${pushoverGlances}" == "false" ]; then + echo "pushoverGlances not enabled in preferences.json" +else + GLANCES="monitor/last_glance" + GLUCOSE="monitor/glucose.json" + if [ ! -f $GLANCES ]; then + # First time through it will get created older than 10 minutes so it'll fire + touch $GLANCES && touch -r $GLANCES -d '-11 mins' $GLANCES + fi + + if test `find $GLANCES -mmin +10` + then + enactTime=$(ls -l --time-style=+"%l:%M" ${FILE} | awk '{printf ($6)}') + + lastDirection=`jq -M '.[0] .direction' $GLUCOSE` + lastDirection="${lastDirection%\"}" + lastDirection="${lastDirection#\"}" + + #echo lastDirection=$lastDirection + + if [ "${lastDirection}" == "SingleUp" ]; then + direction="+" + elif [ "${lastDirection}" == "FortyFiveUp" ]; then + direction="++" + elif [ "${lastDirection}" == "DoubleUp" ]; then + direction="+++" + elif [ "${lastDirection}" == "SingleDown" ]; then + direction="-" + elif [ "${lastDirection}" == "FortyFiveDown" ]; then + direction="--" + elif [ "${lastDirection}" == "DoubleDown" ]; then + direction="---" + else + direction="" # default for NONE or Flat + fi + + if [ test cat $FILE | egrep "add'l" ]; then + subtext="cr ${carbsReq}g" + else + subtext="e${enactTime}" + fi + text="${bgNow}${direction}" + title="cob ${cob}, iob ${iob}" + +# echo "pushover glance text=${text} subtext=${subtext} delta=${delta} title=${title} battery percent=${battery}" + curl -s -F "token=$TOKEN" -F "user=$USER" -F "text=${text}" -F "subtext=${subtext}" -F "count=$bgNow" -F "percent=${battery}" -F "title=${title}" https://api.pushover.net/1/glances.json + touch $GLANCES + fi +fi + +# Send IFTTT maker event "carbs-required" if additional carbs are required +# and if environment variable "MAKER_KEY" is set. This is the IFTTT webhooks Maker key +# https://ifttt.com/maker_webhooks +# The "carbs-required" event can then be used with a IFTTT recipe to perform an action +# based on carbs required. A good use case is to use the IFTTT phone action to get a phone +# call with this event that will read out in human language the additional carbs and other +# vital facts. It will leave a voice mail if not answered. + +if [[ "$MAKER_KEY" != "null" ]] && cat $FILE | egrep "add'l"; then + if find monitor/ -mmin -60 | grep -q ifttt-sent; then + echo "carbsReq=${carbsReq} but last IFTTT event sent less than 60 minutes ago." + else + message="Carbs required = ${carbsReq}. Glucose = $bgNow Insulin on board = $iob Carbs on board = $cob grams." + echo "posting message to carbs-required ... message=$message" + + ifttt="monitor/ifttt.json" + values="{ \"value1\":\"$message\" }" + + echo $values > $ifttt + + curl --request POST \ + --header 'Content-Type: application/json' \ + -d @$ifttt \ + https://maker.ifttt.com/trigger/carbs-required/with/key/${key} && touch monitor/ifttt-sent + fi +fi + diff --git a/bin/oref0-radio-reboot.sh b/bin/oref0-radio-reboot.sh new file mode 100755 index 000000000..3b9be78a8 --- /dev/null +++ b/bin/oref0-radio-reboot.sh @@ -0,0 +1,25 @@ +#!/bin/bash + +# There are 2 known conditions in which communication between rig and pump is not working and a reboot is required. +# 1) spidev5.1 already in use, see https://github.com/openaps/oref0/pull/411 (all pumps) +# 2) continuous 'retry 0' or hanging reset.py, see https://github.com/oskarpearson/mmeowlink/issues/60 (WW-pump users only) +# If one of those occur we will reboot the rig +# If it will restore within 5 minutes, then the reboot will be cancelled +# Note that this is a workaround, until we found the root cause of why the rig pump communication fails + +radio_errors=`tail --lines=20 /var/log/openaps/pump-loop.log | egrep "spidev.* already in use|retry 0|TimeoutExpired. Killing process"` +logfile=/var/log/openaps/pump-loop.log +if [ ! -z "$radio_errors" ]; then + if [ ! -e /run/nologin ]; then + echo >> $logfile + echo -n "Radio error found at " | tee -a $logfile + date >> $logfile + shutdown -r +5 "Rebooting to fix radio errors!" | tee -a $logfile + echo >> $logfile + fi +else + if [ -e /run/nologin ]; then + echo "No more radio errors; canceling reboot" | tee -a $logfile + shutdown -c | tee -a $logfile + fi +fi diff --git a/bin/oref0-raw.js b/bin/oref0-raw.js new file mode 100755 index 000000000..c46421f08 --- /dev/null +++ b/bin/oref0-raw.js @@ -0,0 +1,62 @@ +#!/usr/bin/env node +'use strict'; + +var fs = require('fs'); +var os = require("os"); + +var safeRequire = require('../lib/require-utils').safeRequire; +var getLastGlucose = require('../lib/glucose-get-last'); +var withRawGlucose = require('../lib/with-raw-glucose'); + +/* + Fills CGM data doesn't already contain an EVG, if we have unfiltered, filtered, and a cal + + Released under MIT license. See the accompanying LICENSE.txt file for + full terms and conditions + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + + */ + +function usage ( ) { + console.error('usage: ', process.argv.slice(0, 2), ' [max_raw]'); +} +if (!module.parent) { + var glucose_input = process.argv[2]; + if ([null, '--help', '-h', 'help'].indexOf(glucose_input) > 0) { + usage( ); + process.exit(0) + } + var cal_input = process.argv[3]; + + //limit to prevent high temping + var max_raw = process.argv[4]; + + if (!glucose_input || !cal_input) { + usage( ); + process.exit(1); + } + + try { + var cwd = process.cwd(); + var glucose_data = safeRequire(cwd + '/' + glucose_input); + var cals = safeRequire(cwd + '/' + cal_input); + + + glucose_data = glucose_data.map(function each (entry) { + return withRawGlucose(entry, cals, max_raw); + }); + + console.log(JSON.stringify(glucose_data)); + + } catch (e) { + return console.error("Could not parse input data: ", e); + } + +} diff --git a/bin/oref0-reset-git.sh b/bin/oref0-reset-git.sh index aa8a33629..dd1f5f2ee 100755 --- a/bin/oref0-reset-git.sh +++ b/bin/oref0-reset-git.sh @@ -1,4 +1,4 @@ -#!/bin/sh +#!/bin/bash # Delete git lock / history if necessary to recover from corrupted .git objects # @@ -14,7 +14,49 @@ # THE SOFTWARE. # must be run from within a git repo to do anything useful +self=$(basename $0) +BACKUP_AREA=${1-${BACKUP_AREA-/var/cache/openaps-ruination}} +function usage ( ) { + +cat </dev/null +find .git/index.lock -mmin +60 -exec rm {} \; 2>/dev/null +# first, try oref0-fix-git-corruption.sh to preserve git history up to last good commit +echo "Attempting to fix git corruption. Please wait 15s." +oref0-fix-git-corruption & +pid=$! +(sleep 15; killall oref0-fix-git-corruption) & +sleep_pid=$! +wait $pid + +status=$? +if [ $status -lt 128 ]; then + kill $sleep_pid +fi # if git repository is too corrupt to do anything, mv it to /tmp and start over. -git status > /dev/null || ( mv .git /tmp/.git-`date +%s` && openaps init . ) + +(git status && git diff && git symbolic-ref HEAD && ! df | grep 100% && ! df -i | grep 100%) > /dev/null || ( + echo Removing largest old git repo from $BACKUP_AREA + du -sh $BACKUP_AREA/git-1* | head -1 | awk '{print $2}' | while read line; do rm -rf $line; done + echo "Saving backup to: $BACKUP" > /dev/stderr + mv .git $BACKUP + rm -rf .git + openaps init . + ) + +#clean out any tmp_pack_ stuff from $BACKUP +find $BACKUP -name tmp_pack_* -exec rm {} \; diff --git a/bin/oref0-reset-usb.sh b/bin/oref0-reset-usb.sh index 82da00bd7..113731b35 100755 --- a/bin/oref0-reset-usb.sh +++ b/bin/oref0-reset-usb.sh @@ -1,4 +1,4 @@ -#!/bin/sh +#!/bin/bash # Power-cycle the Raspberry Pi USB bus to reset attached USB devices # @@ -13,6 +13,22 @@ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. +self=$(basename $0) +function usage ( ) { + +cat < $FILE sleep 1 diff --git a/bin/clockset.sh b/bin/oref0-set-device-clocks.sh similarity index 51% rename from bin/clockset.sh rename to bin/oref0-set-device-clocks.sh index 1da17db8c..278074101 100755 --- a/bin/clockset.sh +++ b/bin/oref0-set-device-clocks.sh @@ -18,15 +18,38 @@ PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin +CLOCK=${1-monitor/clock-zoned.json} +GLUCOSE=${2-monitor/glucose.json} +PUMP=${3-pump} +CGM=${4-cgm} + die() { echo "$@" ; exit 1; } +self=$(basename $0) +function usage ( ) { + +cat < fake-hwclock.data -grep : fake-hwclock.data && sudo cp fake-hwclock.data /etc/fake-hwclock.data -sudo fake-hwclock load -grep -q display_time glucose.json && grep display_time glucose.json | head -1 | awk '{print $2}' | sed "s/,//" | sed 's/"//g' | sed "s/$/`date +%z`/" | while read line; do date -u -d $line +"%F %R:%S"; done > fake-hwclock.data -grep -q dateString glucose.json && grep dateString glucose.json | head -1 | awk '{print $2}' | sed "s/,//" | sed 's/"//g' |while read line; do date -u -d $line +"%F %R:%S"; done > fake-hwclock.data -grep : fake-hwclock.data && sudo cp fake-hwclock.data /etc/fake-hwclock.data -sudo fake-hwclock load +if checkNTP; then + sudo ntpdate -s -b time.nist.gov + echo Setting pump time to $(date) + openaps use $PUMP set_clock --to now 2>&1 >/dev/null | tail -1 + # xdripaps CGM does not have a clock to set, so don't try. + if [ ! -d xdrip ]; then + echo Setting CGM time to $(date) + openaps use $CGM UpdateTime --to now 2>&1 >/dev/null | tail -1 + fi +fi diff --git a/bin/oref0-set-local-temptarget.js b/bin/oref0-set-local-temptarget.js new file mode 100755 index 000000000..8c2b20033 --- /dev/null +++ b/bin/oref0-set-local-temptarget.js @@ -0,0 +1,50 @@ +#!/usr/bin/env node + +/* + Released under MIT license. See the accompanying LICENSE.txt file for + full terms and conditions + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + +*/ + +function usage ( ) { + console.log('usage: ', process.argv[1], ' [starttime]'); + console.log('example: ', process.argv[1], '110 60'); + console.log('example: ', process.argv[1], '120 30 2017-10-18:00:15:00.000Z'); +} + +if (!module.parent) { + var target = process.argv[2]; + var duration = process.argv[3]; + var start = process.argv[4]; + + if ([null, '--help', '-h', 'help'].indexOf(target) > 0) { + usage( ); + process.exit(0) + } + if (!target || !duration) { + usage( ) + process.exit(1); + } + + var temptarget = {}; + temptarget.targetBottom = parseInt(target); + temptarget.targetTop = parseInt(target); + temptarget.duration = parseInt(duration); + if (start) { + temptarget.created_at = new Date(start); + } else { + temptarget.created_at = new Date(); + } + + + console.log(JSON.stringify(temptarget)); +} + diff --git a/bin/oref0-set-system-clock.sh b/bin/oref0-set-system-clock.sh new file mode 100755 index 000000000..4c9f752fb --- /dev/null +++ b/bin/oref0-set-system-clock.sh @@ -0,0 +1,51 @@ +#!/bin/bash + +# The Raspberry Pi doesn't contain a real hardware clock, so the time is lost on +# reboots. This updates the Raspberry Pi fake Hardware Clock so that it matches +# the meter time, and will be set to this value on reboot. This helps when there +# is no network connection +# +# Released under MIT license. See the accompanying LICENSE.txt file for +# full terms and conditions +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. + +PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin + +CLOCK=${1-monitor/clock-zoned.json} +GLUCOSE=${2-monitor/glucose.json} +PUMP=${3-pump} +CGM=${4-cgm} + +die() { echo "$@" ; exit 1; } +self=$(basename $0) +function usage ( ) { + +cat < <--serial=pump_serial_#> [--tty=/dev/ttySOMETHING] [--max_iob=0] [--ns-host=https://mynightscout.herokuapp.com] [--api-secret=[myplaintextapisecret|token=subjectname-plaintexthashsecret] [--cgm=(G4-upload|G4-local-only|shareble|G5|MDT|xdrip)] [--bleserial=SM123456] [--blemac=FE:DC:BA:98:76:54] [--btmac=AB:CD:EF:01:23:45] [--enable='autotune'] [--radio_locale=(WW|US)] [--ww_ti_usb_reset=(yes|no)]" + echo + read -p "Start interactive setup? [Y]/n " -r + if [[ $REPLY =~ ^[Nn]$ ]]; then + exit + fi + echo + if [[ -z $DIR ]]; then + DIR="$HOME/myopenaps" + fi + directory="$(readlink -m $DIR)" + echo + + read -p "What is your pump serial number (six digits, numbers only)? " -r + serial=$REPLY + while [[ -z $serial ]]; do + echo Pump serial number is required. + read -p "What is your pump serial number (six digits, numbers only)? " -r + serial=$REPLY + done + echocolor "Ok, $serial it is." + echo + + read -p "Do you have a 512 or 712 model pump? y/[N] " -r + if [[ $REPLY =~ ^[Yy]$ ]]; then + pumpmodel=x12 + echocolor "Ok, you'll be using a 512 or 712 pump. Got it. " + echo + else + echocolor "You're using a different model pump. Got it." + fi + + echo "What kind of CGM would you like to configure for offline use? Options are:" + echo "G4-upload: will use and upload BGs from a plugged in G4 receiver to Nightscout" + echo "G4-local-only: will use BGs from a plugged in G4, but will *not* upload them" + echo "G5: will use BGs from a plugged in G5, but will *not* upload them (the G5 app usually does that)" + echo "G5-upload: will use and upload BGs from a plugged in G5 receiver to Nightscout" + echo "MDT: will use and upload BGs from an Enlite sensor paired to your pump" + echo "xdrip: will work with an xDrip receiver app on your Android phone" + echo "Note: no matter which option you choose, CGM data will also be downloaded from NS when available." + echo + read -p "What kind of CGM would you like to configure?: " -r + CGM=$REPLY + echocolor "Ok, $CGM it is." + echo + if [[ ${CGM,,} =~ "shareble" ]]; then + read -p "What is your G4 Share Serial Number? (i.e. SM12345678) " -r + BLE_SERIAL=$REPLY + echo "$BLE_SERIAL? Got it." + echo + fi + + if grep -qa "Explorer HAT" /proc/device-tree/hat/product 2>/dev/null ; then + echocolor "Explorer Board HAT detected. " + ttyport=/dev/spidev0.0 + else + read -p "Are you using an Explorer Board? [Y]/n " -r + if [[ $REPLY =~ ^[Nn]$ ]]; then + echo 'Are you using mmeowlink (i.e. with a TI stick)? If not, press enter. If so, paste your full port address: it looks like "/dev/ttySOMETHING" without the quotes.' + read -p "What is your TTY port? " -r + ttyport=$REPLY + echocolor-n "Ok, " + if [[ -z "$ttyport" ]]; then + echo -n Carelink + else + echo -n TTY $ttyport + fi + echocolor " it is. " + echo + else + if getent passwd edison > /dev/null; then + echocolor "Yay! Configuring for Edison with Explorer Board. " + ttyport=/dev/spidev5.1 + else + echo "Hmm, you don't seem to be using an Edison." + read -p "What is your TTY port? (/dev/ttySOMETHING) " -r + ttyport=$REPLY + echocolor "Ok, we'll try TTY $ttyport then." + fi + echo + fi + fi + + + if [[ ! -z "${ttyport}" ]]; then + echo -e "\e[1mMedtronic pumps come in two types: WW (Worldwide) pumps, and NA (North America) pumps.\e[0m" + echo "Confusingly, North America pumps may also be used outside of North America." + echo + echo "USA pumps have a serial number / model number that has 'NA' in it." + echo "Non-USA pumps have a serial number / model number that 'WW' in it." + echo + echo "When using MMeowlink, we need to know which frequency we should use:" + echo -e "\e[1mAre you using a USA/North American pump? If so, just hit enter. Otherwise enter WW: \e[0m" + read -r + radio_locale=$REPLY + echo -n "Ok, " + # Force uppercase, just in case the user entered ww + radio_locale=${radio_locale^^} + + # check if user has a TI USB stick and a WorldWide pump and want's to reset the USB subsystem during mmtune if the TI USB fails + ww_ti_usb_reset="no" # assume you don't want it by default + if [[ $radio_locale =~ ^WW$ ]]; then + echo "If you have a TI USB stick and a WW pump and a Raspberry PI, you might want to reset the USB subsystem if it can't be found during a mmtune process. If so, enter Y. Otherwise just hit enter (default no):" + echo + read -p "Do you want to reset the USB system in case the TI USB stick can't be found during a mmtune proces? " -r + if [[ $REPLY =~ ^[Yy]$ ]]; then + ww_ti_usb_reset="yes" + else + ww_ti_usb_reset="no" + fi + fi + + if [[ -z "${radio_locale}" ]]; then + radio_locale='US' + fi + + echocolor "${radio_locale} it is" + echo + fi + + read -p "What is your Nightscout site? (i.e. https://mynightscout.herokuapp.com)? " -r + # remove any trailing / from NIGHTSCOUT_HOST + NIGHTSCOUT_HOST=$(echo $REPLY | sed 's/\/$//g') + while [[ -z $NIGHTSCOUT_HOST ]]; do + echo Nightscout is required for interactive setup. + read -p "What is your Nightscout site? (i.e. https://mynightscout.herokuapp.com)? " -r + # remove any trailing / from NIGHTSCOUT_HOST + NIGHTSCOUT_HOST=$(echo $REPLY | sed 's/\/$//g') + echo + done + echocolor "Ok, $NIGHTSCOUT_HOST it is." + echo + if [[ ! -z $NIGHTSCOUT_HOST ]]; then + echo "Starting with oref 0.5.0 you can use token based authentication to Nightscout. This makes it possible to deny anonymous access to your Nightscout instance. It's more secure than using your API_SECRET, but must first be configured in Nightscout." + read -p "Do you want to use token based authentication? y/[N] " -r + if [[ $REPLY =~ ^[Yy]$ ]]; then + read -p "What Nightscout access token (i.e. subjectname-hashof16characters) do you want to use for this rig? " -r + API_SECRET="token=${REPLY}" + echocolor "Ok, $API_SECRET it is." + echo + else + echocolor "Ok, you'll use API_SECRET instead." + echo + read -p "What is your Nightscout API_SECRET (i.e. myplaintextsecret; It should be at least 12 characters long)? " -r + API_SECRET=$REPLY + while [[ -z $API_SECRET ]]; do + echo API_SECRET is required for interactive setup. + read -p "What is your Nightscout API_SECRET (i.e. myplaintextsecret; It should be at least 12 characters long)? " -r + API_SECRET=$REPLY + done + echocolor "Ok, $API_SECRET it is." + echo + fi + fi + + read -p "Do you want to be able to set up BT tethering? y/[N] " -r + if [[ $REPLY =~ ^[Yy]$ ]]; then + read -p "What is your phone's BT MAC address (i.e. AA:BB:CC:DD:EE:FF)? " -r + BT_MAC=$REPLY + echo + echocolor "Ok, $BT_MAC it is. You will need to follow directions in docs to set-up BT tether after your rig is successfully looping." + echo + else + echo + echocolor "Ok, no BT installation at this time, you can run this script again later if you change your mind." + echo + fi + + + if [[ ! -z $BT_PEB ]]; then + read -p "For Pancreabble enter Pebble mac id (i.e. AA:BB:CC:DD:EE:FF) hit enter to skip " -r + BT_PEB=$REPLY + echocolor "Ok, $BT_PEB it is." + echo + fi + + echo + echo -e "\e[1mWhat value would you like to set for your max_IOB? Context: max_IOB is a safety setting\e[0m" + echo + echo -e "\e[3mIt limits how much insulin OpenAPS can give you in addition to your manual boluses and pre-set basal rates.\e[0m" + echo + echo -e 'max_IOB of 0 will make it so OpenAPS cannot provide positive IOB, and will function as "low glucose suspend" type mode.' + echo + echo -e "\e[4mIf you are unsure of what you would like max_IOB to be, we recommend starting with either 0 or one hour worth of basals.\e[0m" + echo + echo -e "\e[3mRead the docs for more tips on how to determine a max_IOB that is right for you. (You can come back and change this easily later).\e[0m" + echo + read -p "Type a whole number (without a decimal) [i.e. 0] and hit enter: " -r + if [[ $REPLY =~ [0-9] ]]; then + max_iob="$REPLY" + echocolor "Ok, $max_iob units will be set as your max_iob." + echo + else + max_iob=0 + echocolor "Ok, your max_iob will be set to 0 for now." + echo + fi + + read -p "Enable autotuning of basals and ratios? [Y]/n " -r + if [[ $REPLY =~ ^[Nn]$ ]]; then + echocolor "Ok, no autotune." + echo + else + ENABLE+=" autotune " + echocolor "Ok, autotune will be enabled. It will run around 4am." + echo + fi + + #always enabling AMA by default + #ENABLE+=" meal " + + read -p "Do you want to enable carbsReq Pushover alerts? y/[N] " -r + if [[ $REPLY =~ ^[Yy]$ ]]; then + read -p "If so, what is your Pushover API Token? " -r + PUSHOVER_TOKEN=$REPLY + echocolor "Ok, Pushover token $PUSHOVER_TOKEN it is." + echo + + read -p "And what is your Pushover User Key? " -r + PUSHOVER_USER=$REPLY + echocolor "Ok, Pushover User Key $PUSHOVER_USER it is." + echo + else + echocolor "Ok, no Pushover for you." + echo + fi + + echo + echo + echo + +else + if [[ $ww_ti_usb_reset =~ ^[Yy] ]]; then + ww_ti_usb_reset="yes" + else + ww_ti_usb_reset="no" + fi +fi + +echo -n "Setting up oref0 in $directory for pump $serial with $CGM CGM, " +if [[ ${CGM,,} =~ "shareble" ]]; then + echo -n "G4 Share serial $BLE_SERIAL, " +fi +echo +echo -n "NS host $NIGHTSCOUT_HOST, " +if [[ ${pumpmodel,,} =~ "x12" ]]; then + echo -n "x12 pump, " +fi + +if [[ -z "$ttyport" ]]; then + echo -n Carelink +else + echo -n TTY $ttyport +fi +if [[ "$max_iob" != "0" ]]; then + echo -n ", max_iob $max_iob"; +fi +if [[ ! -z "$max_daily_safety_multiplier" ]]; then + echo -n ", max_daily_safety_multiplier $max_daily_safety_multiplier"; +fi +if [[ ! -z "$current_basal_safety_multiplier" ]]; then + echo -n ", current_basal_safety_multiplier $current_basal_safety_multiplier"; +fi +#if [[ ! -z "$bolussnooze_dia_divisor" ]]; then + #echo -n ", bolussnooze_dia_divisor $bolussnooze_dia_divisor"; +#fi +if [[ ! -z "$min_5m_carbimpact" ]]; then + echo -n ", min_5m_carbimpact $min_5m_carbimpact"; +fi +if [[ ! -z "$ENABLE" ]]; then + echo -n ", advanced features $ENABLE"; +fi +echo +echo + +# This section is echoing (commenting) back the options you gave it during the interactive setup script. +# The "| tee -a /tmp/oref0-runagain.sh" part is also appending it to a file so you can run it again more easily in the future. + +# create temporary file for oref0-runagain.sh +OREF0_RUNAGAIN=`mktemp /tmp/oref0-runagain.XXXXXXXXXX` +echo "#!/bin/bash" > $OREF0_RUNAGAIN +echo "# To run again with these same options, use: " | tee $OREF0_RUNAGAIN +echo -n "oref0-setup --dir=$directory --serial=$serial --cgm=$CGM" | tee -a $OREF0_RUNAGAIN +if [[ ${CGM,,} =~ "shareble" ]]; then + echo -n " --bleserial=$BLE_SERIAL" | tee -a $OREF0_RUNAGAIN +fi +echo -n " --ns-host=$NIGHTSCOUT_HOST --api-secret=$API_SECRET" | tee -a $OREF0_RUNAGAIN +if [[ ! -z "$ttyport" ]]; then + echo -n " --tty=$ttyport" | tee -a $OREF0_RUNAGAIN +fi +if [[ ! -z "$pumpmodel" ]]; then + echo -n " --pumpmodel=$pumpmodel" | tee -a $OREF0_RUNAGAIN; +fi +echo -n " --max_iob=$max_iob" | tee -a $OREF0_RUNAGAIN; +if [[ ! -z "$max_daily_safety_multiplier" ]]; then + echo -n " --max_daily_safety_multiplier=$max_daily_safety_multiplier" | tee -a $OREF0_RUNAGAIN +fi +if [[ ! -z "$current_basal_safety_multiplier" ]]; then + echo -n " --current_basal_safety_multiplier=$current_basal_safety_multiplier" | tee -a $OREF0_RUNAGAIN +fi +#if [[ ! -z "$bolussnooze_dia_divisor" ]]; then + #echo -n " --bolussnooze_dia_divisor=$bolussnooze_dia_divisor" | tee -a $OREF0_RUNAGAIN +#fi +if [[ ! -z "$min_5m_carbimpact" ]]; then + echo -n " --min_5m_carbimpact=$min_5m_carbimpact" | tee -a $OREF0_RUNAGAIN +fi +if [[ ! -z "$ENABLE" ]]; then + echo -n " --enable='$ENABLE'" | tee -a $OREF0_RUNAGAIN +fi +if [[ ! -z "$radio_locale" ]]; then + echo -n " --radio_locale='$radio_locale'" | tee -a $OREF0_RUNAGAIN +fi +if [[ ${ww_ti_usb_reset,,} =~ "yes" ]]; then + echo -n " --ww_ti_usb_reset='$ww_ti_usb_reset'" | tee -a $OREF0_RUNAGAIN +fi +if [[ ! -z "$BLE_MAC" ]]; then + echo -n " --blemac='$BLE_MAC'" | tee -a $OREF0_RUNAGAIN +fi +if [[ ! -z "$BT_MAC" ]]; then + echo -n " --btmac='$BT_MAC'" | tee -a $OREF0_RUNAGAIN +fi +if [[ ! -z "$BT_PEB" ]]; then + echo -n " --btpeb='$BT_PEB'" | tee -a $OREF0_RUNAGAIN +fi +if [[ ! -z "$PUSHOVER_TOKEN" ]]; then + echo -n " --pushover_token='$PUSHOVER_TOKEN'" | tee -a $OREF0_RUNAGAIN +fi +if [[ ! -z "$PUSHOVER_USER" ]]; then + echo -n " --pushover_user='$PUSHOVER_USER'" | tee -a $OREF0_RUNAGAIN +fi +echo; echo | tee -a $OREF0_RUNAGAIN +chmod 755 $OREF0_RUNAGAIN + +echocolor-n "Continue? y/[N] " +read -r +if [[ $REPLY =~ ^[Yy]$ ]]; then + + # Attempting to remove git to make install --nogit by default for existing users + echo Removing any existing git in $directory/.git + rm -rf $directory/.git + echo Removed any existing git + + # TODO: delete this after openaps 0.2.1 release + echo Checking openaps 0.2.1 installation with --nogit support + if ! openaps --version 2>&1 | egrep "0.[2-9].[1-9]"; then + echo Installing latest openaps w/ nogit && sudo pip install git+https://github.com/openaps/openaps.git@nogit || die "Couldn't install openaps w/ nogit" + fi + + echo -n "Checking $directory: " + mkdir -p $directory + # if ( cd $directory && ls openaps.ini 2>/dev/null >/dev/null && openaps use -h >/dev/null ); then + # echo $directory already exists + if openaps init $directory --nogit; then + echo $directory initialized + else + die "Can't init $directory" + fi + cd $directory || die "Can't cd $directory" + + # Taking the oref0-runagain.sh from tmp to $directory + mv $OREF0_RUNAGAIN ./oref0-runagain.sh + + # Make sure it is executable afterwards + chmod +x ./oref0-runagain.sh + + mkdir -p monitor || die "Can't mkdir monitor" + mkdir -p raw-cgm || die "Can't mkdir raw-cgm" + mkdir -p cgm || die "Can't mkdir cgm" + mkdir -p settings || die "Can't mkdir settings" + mkdir -p enact || die "Can't mkdir enact" + mkdir -p upload || die "Can't mkdir upload" + if [[ ${CGM,,} =~ "xdrip" ]]; then + mkdir -p xdrip || die "Can't mkdir xdrip" + fi + + # check whether decocare-0.0.31 has been installed + if ! ls /usr/local/lib/python2.7/dist-packages/decocare-0.0.31-py2.7.egg/ 2>/dev/null >/dev/null; then + # install decocare with setuptools since 0.0.31 (with the 6.4U/h fix) isn't published properly to pypi + sudo easy_install -U decocare || die "Can't easy_install decocare" + fi + + mkdir -p $HOME/src/ + + # TODO: remove this and switch back to easy_install or pip once decocare 0.1.0 is released + if [ -d "$HOME/src/decocare/" ]; then + echo "$HOME/src/decocare/ already exists; pulling latest 0.1.0-dev" + (cd $HOME/src/decocare && git fetch && git checkout 0.1.0-dev && git pull) || die "Couldn't pull latest decocare 0.1.0-dev" + else + echo -n "Cloning decocare 0.1.0-dev: " + (cd $HOME/src && git clone -b 0.1.0-dev git://github.com/openaps/decocare.git) || die "Couldn't clone decocare 0.1.0-dev" + fi + echo Installing decocare 0.1.0-dev + cd $HOME/src/decocare + sudo python setup.py develop || die "Couldn't install decocare 0.1.0-dev" + + if [ -d "$HOME/src/oref0/" ]; then + echo "$HOME/src/oref0/ already exists; pulling latest" + (cd $HOME/src/oref0 && git fetch && git pull) || die "Couldn't pull latest oref0" + else + echo -n "Cloning oref0: " + (cd $HOME/src && git clone git://github.com/openaps/oref0.git) || die "Couldn't clone oref0" + fi + echo Checking oref0 installation + cd $HOME/src/oref0 + if git branch | grep "* master"; then + npm list -g oref0 | egrep oref0@0.6.[0] || (echo Installing latest oref0 package && sudo npm install -g oref0) + else + npm list -g oref0 | egrep oref0@0.6.[1-9] || (echo Installing latest oref0 from $HOME/src/oref0/ && cd $HOME/src/oref0/ && npm run global-install) + fi + + echo Checking mmeowlink installation +#if openaps vendor add --path . mmeowlink.vendors.mmeowlink 2>&1 | grep "No module"; then + pip show mmeowlink | egrep "Version: 0.11.1" || ( + echo Installing latest mmeowlink + sudo pip install -U mmeowlink || die "Couldn't install mmeowlink" + ) +#fi + + cd $directory || die "Can't cd $directory" + if [[ "$max_iob" == "0" && -z "$max_daily_safety_multiplier" && -z "$current_basal_safety_multiplier" && -z "$min_5m_carbimpact" ]]; then + cp preferences.json old_preferences.json + oref0-get-profile --exportDefaults > preferences.json || die "Could not run oref0-get-profile" + else + preferences_from_args=() + if [[ "$max_iob" != "0" ]]; then + preferences_from_args+="\"max_iob\":$max_iob " + fi + if [[ ! -z "$max_daily_safety_multiplier" ]]; then + preferences_from_args+="\"max_daily_safety_multiplier\":$max_daily_safety_multiplier " + fi + if [[ ! -z "$current_basal_safety_multiplier" ]]; then + preferences_from_args+="\"current_basal_safety_multiplier\":$current_basal_safety_multiplier " + fi + #if [[ ! -z "$bolussnooze_dia_divisor" ]]; then + #preferences_from_args+="\"bolussnooze_dia_divisor\":$bolussnooze_dia_divisor " + #fi + if [[ ! -z "$min_5m_carbimpact" ]]; then + preferences_from_args+="\"min_5m_carbimpact\":$min_5m_carbimpact " + fi + function join_by { local IFS="$1"; shift; echo "$*"; } + echo "{ $(join_by , ${preferences_from_args[@]}) }" > preferences_from_args.json + oref0-get-profile --updatePreferences preferences_from_args.json > preferences.json && rm preferences_from_args.json || die "Could not run oref0-get-profile" + fi + + cat preferences.json + + # fix log rotate file + sed -i "s/weekly/hourly/g" /etc/logrotate.conf + sed -i "s/daily/hourly/g" /etc/logrotate.conf + sed -i "s/#compress/compress/g" /etc/logrotate.conf + + # enable log rotation + sudo cp $HOME/src/oref0/logrotate.openaps /etc/logrotate.d/openaps || die "Could not cp /etc/logrotate.d/openaps" + sudo cp $HOME/src/oref0/logrotate.rsyslog /etc/logrotate.d/rsyslog || die "Could not cp /etc/logrotate.d/rsyslog" + + test -d /var/log/openaps || sudo mkdir /var/log/openaps && sudo chown $USER /var/log/openaps || die "Could not create /var/log/openaps" + + #TODO: remove this when IPv6 works reliably + echo 'Acquire::ForceIPv4 "true";' | sudo tee /etc/apt/apt.conf.d/99force-ipv4 + + # update, upgrade, and autoclean apt-get + echo Running apt-get update + sudo apt-get update + echo Running apt-get upgrade + sudo apt-get -y upgrade + echo Running apt-get autoclean + sudo apt-get autoclean + + # configure ns + if [[ ! -z "$NIGHTSCOUT_HOST" && ! -z "$API_SECRET" ]]; then + echo "Removing any existing ns device: " + ( killall -g openaps; killall -g oref0-pump-loop) 2>/dev/null; openaps device remove ns 2>/dev/null + echo "Running nightscout autoconfigure-device-crud $NIGHTSCOUT_HOST $API_SECRET" + nightscout autoconfigure-device-crud $NIGHTSCOUT_HOST $API_SECRET || die "Could not run nightscout autoconfigure-device-crud" + if [[ "${API_SECRET,,}" =~ "token=" ]]; then # install requirements for token based authentication + sudo apt-get -y install python3-pip + sudo pip3 install requests || die "Can't add pip3 requests - error installing" + oref0_nightscout_check || die "Error checking Nightscout permissions" + fi + fi + + # import template + for type in vendor device report alias; do + echo importing $type file + cat $HOME/src/oref0/lib/oref0-setup/$type.json | openaps import || die "Could not import $type.json" + done + echo Checking for BT Mac, BT Peb or Shareble + if [[ ! -z "$BT_PEB" || ! -z "$BT_MAC" || ${CGM,,} =~ "shareble" ]]; then + # Install Bluez for BT Tethering + echo Checking bluez installation + bluetoothdversion=$(bluetoothd --version || 0) + # use packaged bluez with Rapsbian + if getent passwd pi > /dev/null; then + bluetoothdminversion=5.43 + else + bluetoothdminversion=5.48 + fi + bluetoothdversioncompare=$(awk 'BEGIN{ print "'$bluetoothdversion'"<"'$bluetoothdminversion'" }') + if [ "$bluetoothdversioncompare" -eq 1 ]; then + cd $HOME/src/ && wget -c4 https://www.kernel.org/pub/linux/bluetooth/bluez-5.48.tar.gz && tar xvfz bluez-5.48.tar.gz || die "Couldn't download bluez" + killall bluetoothd &>/dev/null #Kill current running version if its out of date and we are updating it + cd $HOME/src/bluez-5.48 && ./configure --disable-systemd && make || die "Couldn't make bluez" + killall bluetoothd &>/dev/null #Kill current running version if its out of date and we are updating it + sudo make install || die "Couldn't make install bluez" + killall bluetoothd &>/dev/null #Kill current running version if its out of date and we are updating it + sudo cp ./src/bluetoothd /usr/local/bin/ || die "Couldn't install bluez" + oref0-bluetoothup + else + echo bluez version ${bluetoothdversion} already installed + fi + echo Installing prerequisites and configs for local-only hotspot + apt-get install -y hostapd dnsmasq || die "Couldn't install hostapd dnsmasq" + ls /etc/dnsmasq.conf.bak 2>/dev/null || mv /etc/dnsmasq.conf /etc/dnsmasq.conf.bak + cp $HOME/src/oref0/headless/dnsmasq.conf /etc/dnsmasq.conf || die "Couldn't copy dnsmasq.conf" + ls /etc/hostapd/hostapd.conf.bak 2>/dev/null || mv /etc/hostapd/hostapd.conf /etc/hostapd/hostapd.conf.bak + cp $HOME/src/oref0/headless/hostapd.conf /etc/hostapd/hostapd.conf || die "Couldn't copy hostapd.conf" + sed -i.bak -e "s|DAEMON_CONF=$|DAEMON_CONF=/etc/hostapd/hostapd.conf|g" /etc/init.d/hostapd + cp $HOME/src/oref0/headless/interfaces.ap /etc/network/ || die "Couldn't copy interfaces.ap" + cp /etc/network/interfaces /etc/network/interfaces.client || die "Couldn't copy interfaces.client" + #Stop automatic startup of hostapd & dnsmasq + update-rc.d -f hostapd remove + update-rc.d -f dnsmasq remove + # Edit /etc/hostapd/hostapd.conf for wifi using Hostname + sed -i.bak -e "s/ssid=OpenAPS/ssid=${HOSTNAME}/" /etc/hostapd/hostapd.conf + # Add Commands to /etc/rc.local + # Interrupt Kernel Messages + if ! grep -q 'sudo dmesg -n 1' /etc/rc.local; then + sed -i.bak -e '$ i sudo dmesg -n 1' /etc/rc.local + fi + # Add to /etc/rc.local to check if in hotspot mode and turn back to client mode during bootup + if ! grep -q 'cp /etc/network/interfaces.client /etc/network/interfaces' /etc/rc.local; then + sed -i.bak -e "$ i if [ -f /etc/network/interfaces.client ]; then\n\tif grep -q '#wpa-' /etc/network/interfaces; then\n\t\tsudo ifdown wlan0\n\t\tsudo cp /etc/network/interfaces.client /etc/network/interfaces\n\t\tsudo ifup wlan0\n\tfi\nfi" /etc/rc.local || die "Couldn't modify /etc/rc.local" + fi + fi + + # add/configure devices + if [[ ${CGM,,} =~ "g5" || ${CGM,,} =~ "g5-upload" ]]; then + openaps use cgm config --G5 + openaps report add raw-cgm/raw-entries.json JSON cgm oref0_glucose --hours "24.0" --threshold "100" --no-raw + elif [[ ${CGM,,} =~ "shareble" ]]; then + echo Checking Adafruit_BluefruitLE installation + if ! python -c "import Adafruit_BluefruitLE" 2>/dev/null; then + if [ -d "$HOME/src/Adafruit_Python_BluefruitLE/" ]; then + echo "$HOME/src/Adafruit_Python_BluefruitLE/ already exists; pulling latest master branch" + (cd $HOME/src/Adafruit_Python_BluefruitLE && git fetch && git checkout wip/bewest/custom-gatt-profile && git pull) || die "Couldn't pull latest Adafruit_Python_BluefruitLE wip/bewest/custom-gatt-profile" + else + echo -n "Cloning Adafruit_Python_BluefruitLE wip/bewest/custom-gatt-profile: " + # TODO: get this moved over to openaps and install with pip + (cd $HOME/src && git clone -b wip/bewest/custom-gatt-profile https://github.com/bewest/Adafruit_Python_BluefruitLE.git) || die "Couldn't clone Adafruit_Python_BluefruitLE wip/bewest/custom-gatt-profile" + fi + echo Installing Adafruit_BluefruitLE && cd $HOME/src/Adafruit_Python_BluefruitLE && sudo python setup.py develop || die "Couldn't install Adafruit_BluefruitLE" + fi + echo Checking openxshareble installation + if ! python -c "import openxshareble" 2>/dev/null; then + echo Installing openxshareble && sudo pip install git+https://github.com/openaps/openxshareble.git@dev || die "Couldn't install openxshareble" + fi + sudo apt-get update; sudo apt-get -y upgrade + sudo apt-get -y install bc jq libusb-dev libdbus-1-dev libglib2.0-dev libudev-dev libical-dev libreadline-dev python-dbus || die "Couldn't apt-get install: run 'sudo apt-get update' and try again?" + echo Checking bluez installation + # TODO: figure out if we need to do this for 5.44 as well + if bluetoothd --version | grep -q 5.37 2>/dev/null; then + sudo cp $HOME/src/openxshareble/bluetoothd.conf /etc/dbus-1/system.d/bluetooth.conf || die "Couldn't copy bluetoothd.conf" + fi + # start bluetoothd in /etc/rc.local if it is missing. + if ! grep -q '/usr/local/bin/bluetoothd &' /etc/rc.local; then + sed -i"" 's/^exit 0/\/usr\/local\/bin\/bluetoothd \&\n\nexit 0/' /etc/rc.local + fi + # starting with bluez 5.48 the --experimental command line option is not needed. remove the --experimental if it still exists in /etc/rc.local. this is for rigs with version 0.6.0 or earlier + if ! grep -q '/usr/local/bin/bluetoothd --experimental &' /etc/rc.local; then + sed -i"" 's/^\/usr\/local\/bin\/bluetoothd --experimental \&/\/usr\/local\/bin\/bluetoothd \&/' /etc/rc.local + fi + if ! grep -q 'bluetooth_rfkill_event >/dev/null 2>&1 &' /etc/rc.local; then + sed -i"" 's/^exit 0/bluetooth_rfkill_event >\/dev\/null 2>\&1 \&\n\nexit 0/' /etc/rc.local + fi + # comment out existing line if it exists and isn't already commented out + sed -i"" 's/^screen -S "brcm_patchram_plus" -d -m \/usr\/local\/sbin\/bluetooth_patchram.sh/# &/' /etc/rc.local + fi + + if [[ ${CGM,,} =~ "shareble" || ${CGM,,} =~ "g4-upload" ]]; then + mkdir -p $directory-cgm-loop + if ( cd $directory-cgm-loop && ls openaps.ini 2>/dev/null >/dev/null && openaps use -h >/dev/null ); then + echo $directory-cgm-loop already exists + elif openaps init $directory-cgm-loop --nogit; then + echo $directory-cgm-loop initialized + else + die "Can't init $directory-cgm-loop" + fi + cd $directory-cgm-loop || die "Can't cd $directory-cgm-loop" + mkdir -p monitor || die "Can't mkdir monitor" + mkdir -p nightscout || die "Can't mkdir nightscout" + + openaps device remove cgm 2>/dev/null + + # configure ns + if [[ ! -z "$NIGHTSCOUT_HOST" && ! -z "$API_SECRET" ]]; then + echo "Removing any existing ns device: " + ( killall -g openaps; killall -g oref0-pump-loop) 2>/dev/null; openaps device remove ns 2>/dev/null + echo "Running nightscout autoconfigure-device-crud $NIGHTSCOUT_HOST $API_SECRET" + nightscout autoconfigure-device-crud $NIGHTSCOUT_HOST $API_SECRET || die "Could not run nightscout autoconfigure-device-crud" + fi + + if [[ ${CGM,,} =~ "g4-upload" ]]; then + sudo apt-get -y install bc + openaps device add cgm dexcom || die "Can't add CGM" + for type in cgm-loop; do + echo importing $type file + cat $HOME/src/oref0/lib/oref0-setup/$type.json | openaps import || die "Could not import $type.json" + done + elif [[ ${CGM,,} =~ "shareble" ]]; then + # import shareble stuff + for type in shareble cgm-loop; do + echo importing $type file + cat $HOME/src/oref0/lib/oref0-setup/$type.json | openaps import || die "Could not import $type.json" + done + + if [[ -z "$BLE_MAC" ]]; then + read -p "Please go into your Dexcom's Share settings, forget any existing device, turn Share back on, and press Enter." + openaps use cgm list_dexcom + read -p "What is your G4 Share MAC address? (i.e. FE:DC:BA:98:78:54) " -r + BLE_MAC=$REPLY + echo "$BLE_MAC? Got it." + fi + echo openaps use cgm configure --serial $BLE_SERIAL --mac $BLE_MAC + openaps use cgm configure --serial $BLE_SERIAL --mac $BLE_MAC || die "Couldn't configure Share serial and MAC" + fi + + cd $directory || die "Can't cd $directory" + fi + + if [[ "$ttyport" =~ "spi" ]]; then + echo Checking kernel for spi_serial installation + if ! python -c "import spi_serial" 2>/dev/null; then + #if uname -r 2>&1 | egrep "^4.1[0-9]"; then # kernel >= 4.10+, use pietergit version of spi_serial (does not use mraa) + # echo Installing spi_serial && sudo pip install --upgrade git+https://github.com/pietergit/spi_serial.git || die "Couldn't install pietergit/spi_serial" + #else # kernel < 4.10, use scottleibrand version of spi_serial (requires mraa) + if [[ "$ttyport" =~ "spidev0.0" ]]; then + echo Installing spi_serial && sudo pip install --upgrade git+https://github.com/scottleibrand/spi_serial.git@explorer-hat || die "Couldn't install scottleibrand/spi_serial for explorer-hat" + sed -i.bak -e "s/#dtparam=spi=on/dtparam=spi=on/" /boot/config.txt + else + echo Installing spi_serial && sudo pip install --upgrade git+https://github.com/scottleibrand/spi_serial.git || die "Couldn't install scottleibrand/spi_serial" + fi + #fi + #echo Installing spi_serial && sudo pip install --upgrade git+https://github.com/EnhancedRadioDevices/spi_serial || die "Couldn't install spi_serial" + fi + + # from 0.5.0 the subg-ww-radio-parameters script will be run from oref0_init_pump_comms.py + # this will be called when mmtune is use with a WW pump. + # See https://github.com/oskarpearson/mmeowlink/issues/51 or https://github.com/oskarpearson/mmeowlink/wiki/Non-USA-pump-settings for details + # use --ww_ti_usb_reset=yes if using a TI USB stick and a WW pump. This will reset the USB subsystem if the TI USB device is not found. + # TODO: remove this workaround once https://github.com/oskarpearson/mmeowlink/issues/60 has been fixed + if [[ ${ww_ti_usb_reset,,} =~ "yes" ]]; then + openaps alias remove mmtune + openaps alias add mmtune "! bash -c \"oref0_init_pump_comms.py --ww_ti_usb_reset=yes -v; find monitor/ -size +5c | grep -q mmtune && cp monitor/mmtune.json mmtune_old.json; echo {} > monitor/mmtune.json; echo -n \"mmtune: \" && openaps report invoke monitor/mmtune.json; grep -v setFreq monitor/mmtune.json | grep -A2 $(cat monitor/mmtune.json | jq -r .setFreq) | while read line; do echo -n \"$line \"; done\"" + fi + echo Checking kernel for mraa installation + #if uname -r 2>&1 | egrep "^4.1[0-9]"; then # don't install mraa on 4.10+ kernels + # echo "Skipping mraa install for kernel 4.10+" + #else # check if mraa is installed + if ! ldconfig -p | grep -q mraa; then # if not installed, install it + echo Installing swig etc. + sudo apt-get install -y libpcre3-dev git cmake python-dev swig || die "Could not install swig etc." + # TODO: Due to mraa bug https://github.com/intel-iot-devkit/mraa/issues/771 we were not using the master branch of mraa on dev. + # TODO: After each oref0 release, check whether there is a new stable MRAA release that is of interest for the OpenAPS community + MRAA_RELEASE="v1.7.0" # GitHub hash 8ddbcde84e2d146bc0f9e38504d6c89c14291480 + if [ -d "$HOME/src/mraa/" ]; then + echo -n "$HOME/src/mraa/ already exists; " + #(echo "Pulling latest master branch" && cd ~/src/mraa && git fetch && git checkout master && git pull) || die "Couldn't pull latest mraa master" # used for oref0 dev + (echo "Updating mraa source to stable release ${MRAA_RELEASE}" && cd $HOME/src/mraa && git fetch && git checkout ${MRAA_RELEASE} && git pull) || die "Couldn't pull latest mraa ${MRAA_RELEASE} release" # used for oref0 master + else + echo -n "Cloning mraa " + #(echo -n "master branch. " && cd ~/src && git clone -b master https://github.com/intel-iot-devkit/mraa.git) || die "Couldn't clone mraa master" # used for oref0 dev + (echo -n "stable release ${MRAA_RELEASE}. " && cd $HOME/src && git clone -b ${MRAA_RELEASE} https://github.com/intel-iot-devkit/mraa.git) || die "Couldn't clone mraa release ${MRAA_RELEASE}" # used for oref0 master + fi + # build mraa from source + ( cd $HOME/src/ && mkdir -p mraa/build && cd $_ && cmake .. -DBUILDSWIGNODE=OFF && \ + make && sudo make install && echo && touch /tmp/reboot-required && echo mraa installed. Please reboot before using. && echo ) || die "Could not compile mraa" + sudo bash -c "grep -q i386-linux-gnu /etc/ld.so.conf || echo /usr/local/lib/i386-linux-gnu/ >> /etc/ld.so.conf && ldconfig" || die "Could not update /etc/ld.so.conf" + fi + #fi + fi + + echo Checking openaps dev installation + if ! openaps --version 2>&1 | egrep "0.[2-9].[0-9]"; then + # TODO: switch this back to master once https://github.com/openaps/openaps/pull/116 is merged/released + echo Installing latest openaps dev && sudo pip install git+https://github.com/openaps/openaps.git@dev || die "Couldn't install openaps" + fi + + cd $directory || die "Can't cd $directory" + echo "Removing any existing pump device:" + ( killall -g openaps; killall -g oref0-pump-loop) 2>/dev/null; openaps device remove pump 2>/dev/null + if [[ -z "$ttyport" ]]; then + openaps device add pump medtronic $serial || die "Can't add pump" + # add carelink to pump.ini + grep -q radio_type pump.ini || echo "radio_type=carelink" >> pump.ini + # carelinks can't listen for silence or mmtune, so just do a preflight check instead + openaps alias add wait-for-silence 'report invoke monitor/temp_basal.json' + openaps alias add wait-for-long-silence 'report invoke monitor/temp_basal.json' + openaps alias add mmtune 'report invoke monitor/temp_basal.json' + else + # radio_locale requires openaps 0.2.0-dev or later + openaps device add pump mmeowlink subg_rfspy $ttyport $serial $radio_locale || die "Can't add pump" + openaps alias add wait-for-silence '! bash -c "(mmeowlink-any-pump-comms.py --port '$ttyport' --wait-for 1 | grep -q comms && echo -n Radio ok, || openaps mmtune) && echo -n \" Listening: \"; for i in $(seq 1 100); do echo -n .; mmeowlink-any-pump-comms.py --port '$ttyport' --wait-for 30 2>/dev/null | egrep -v subg | egrep No && break; done"' + openaps alias add wait-for-long-silence '! bash -c "echo -n \"Listening: \"; for i in $(seq 1 200); do echo -n .; mmeowlink-any-pump-comms.py --port '$ttyport' --wait-for 45 2>/dev/null | egrep -v subg | egrep No && break; done"' + if [[ ${radio_locale,,} =~ "ww" ]]; then + if [ -d "$HOME/src/subg_rfspy/" ]; then + echo "$HOME/src/subg_rfspy/ already exists; pulling latest" + (cd $HOME/src/subg_rfspy && git fetch && git pull) || die "Couldn't pull latest subg_rfspy" + else + echo -n "Cloning subg_rfspy: " + (cd $HOME/src && git clone https://github.com/ps2/subg_rfspy) || die "Couldn't clone oref0" + fi + + # Hack to check if radio_locale has been set in pump.ini. + # It will remove empty line at the end of pump.ini and then append radio_locale if it's not there yet + grep -q radio_locale pump.ini || echo "$(< pump.ini)" > pump.ini ; echo "radio_locale=$radio_locale" >> pump.ini + fi + fi + + # Medtronic CGM + if [[ ${CGM,,} =~ "mdt" ]]; then + sudo pip install -U openapscontrib.glucosetools || die "Couldn't install glucosetools" + openaps device remove cgm 2>/dev/null + if [[ -z "$ttyport" ]]; then + openaps device add cgm medtronic $serial || die "Can't add cgm" + else + openaps device add cgm mmeowlink subg_rfspy $ttyport $serial $radio_locale || die "Can't add cgm" + fi + for type in mdt-cgm; do + echo importing $type file + cat $HOME/src/oref0/lib/oref0-setup/$type.json | openaps import || die "Could not import $type.json" + done + fi + + sudo pip install flask || die "Can't add xdrip cgm - error installing flask" + sudo pip install flask-restful || die "Can't add xdrip cgm - error installing flask-restful" + + # xdrip CGM (xDripAPS) + if [[ ${CGM,,} =~ "xdrip" ]]; then + echo xdrip selected as CGM, so configuring xDripAPS + sudo apt-get -y install sqlite3 || die "Can't add xdrip cgm - error installing sqlite3" + git clone https://github.com/colinlennon/xDripAPS.git $HOME/.xDripAPS + mkdir -p $HOME/.xDripAPS_data + for type in xdrip-cgm; do + echo importing $type file + cat $HOME/src/oref0/lib/oref0-setup/$type.json | openaps import || die "Could not import $type.json" + done + touch /tmp/reboot-required + fi + + # disable IPv6 + if ! grep -q 'net.ipv6.conf.all.disable_ipv6=1' /etc/sysctl.conf; then + sudo echo 'net.ipv6.conf.all.disable_ipv6=1' >> /etc/sysctl.conf + fi + if ! grep -q 'net.ipv6.conf.default.disable_ipv6=1' /etc/sysctl.conf; then + sudo echo 'net.ipv6.conf.default.disable_ipv6=1' >> /etc/sysctl.conf + fi + if ! grep -q 'net.ipv6.conf.lo.disable_ipv6=1' /etc/sysctl.conf; then + sudo echo 'net.ipv6.conf.lo.disable_ipv6=1' >> /etc/sysctl.conf + fi + sudo sysctl -p + + # Install EdisonVoltage + #if [[ "$ttyport" =~ "spidev5.1" ]]; then + if egrep -i "edison" /etc/passwd 2>/dev/null; then + echo "Checking if EdisonVoltage is already installed" + if [ -d "$HOME/src/EdisonVoltage/" ]; then + echo "EdisonVoltage already installed" + else + echo "Installing EdisonVoltage" + cd $HOME/src && git clone -b master git://github.com/cjo20/EdisonVoltage.git || (cd EdisonVoltage && git checkout master && git pull) + cd $HOME/src/EdisonVoltage + make voltage + fi + # Add module needed for EdisonVoltage to work on jubilinux 0.2.0 + grep iio_basincove_gpadc /etc/modules-load.d/modules.conf || echo iio_basincove_gpadc >> /etc/modules-load.d/modules.conf + fi + if [[ ${CGM,,} =~ "mdt" ]] || [[ ${CGM,,} =~ "xdrip" ]]; then # still need this for the old ns-loop for now + cd $directory || die "Can't cd $directory" + for type in edisonbattery; do + echo importing $type file + cat $HOME/src/oref0/lib/oref0-setup/$type.json | openaps import || die "Could not import $type.json" + done + fi + #fi + # Install Pancreabble + echo Checking for BT Pebble Mac + if [[ ! -z "$BT_PEB" ]]; then + sudo apt-get -y install jq + sudo pip install libpebble2 + sudo pip install --user git+git://github.com/mddub/pancreabble.git + oref0-bluetoothup + sudo rfcomm bind hci0 $BT_PEB + for type in pancreabble; do + echo importing $type file + cat $HOME/src/oref0/lib/oref0-setup/$type.json | openaps import || die "Could not import $type.json" + done + sudo cp $HOME/src/oref0/lib/oref0-setup/pancreoptions.json $directory/pancreoptions.json + fi + echo Running: openaps report add enact/suggested.json text determine-basal shell monitor/iob.json monitor/temp_basal.json monitor/glucose.json settings/profile.json settings/autosens.json monitor/meal.json + openaps report add enact/suggested.json text determine-basal shell monitor/iob.json monitor/temp_basal.json monitor/glucose.json settings/profile.json settings/autosens.json monitor/meal.json + + # configure autotune if enabled + if [[ $ENABLE =~ autotune ]]; then + sudo apt-get -y install jq + cd $directory || die "Can't cd $directory" + for type in autotune; do + echo importing $type file + cat $HOME/src/oref0/lib/oref0-setup/$type.json | openaps import || die "Could not import $type.json" + done + fi + + #Setup files for editing on the x12, and replace get-settings alias + if [[ ${pumpmodel,,} =~ "x12" ]]; then + echo "copying settings files for x12 pumps" + cp $HOME/src/oref0/lib/oref0-setup/bg_targets_raw.json $directory/settings/ && cp $HOME/src/oref0/lib/oref0-setup/basal_profile.json $directory/settings/ && cp $HOME/src/oref0/lib/oref0-setup/settings.json $directory/settings/ || die "Could not copy settings files for x12 pumps" + echo "getting ready to remove get-settings since this is an x12" + openaps alias remove get-settings || die "Could not remove get-settings" + echo "settings removed, getting ready to add x12 settings" + openaps alias add get-settings "report invoke settings/model.json settings/bg_targets.json settings/insulin_sensitivities_raw.json settings/insulin_sensitivities.json settings/carb_ratios.json settings/profile.json" || die "Could not add x12 settings" + fi + + #Moved this out of the conditional, so that x12 models will work with smb loops + sudo apt-get -y install bc jq ntpdate bash-completion || die "Couldn't install bc etc." + cd $directory || die "Can't cd $directory" + for type in supermicrobolus; do + echo importing $type file + cat $HOME/src/oref0/lib/oref0-setup/$type.json | openaps import || die "Could not import $type.json" + done + + echo "Adding OpenAPS log shortcuts" + oref0-log-shortcuts + + # Append NIGHTSCOUT_HOST and API_SECRET to $HOME/.bash_profile so that openaps commands can be executed from the command line + echo Add NIGHTSCOUT_HOST and API_SECRET to $HOME/.bash_profile + sed --in-place '/.*NIGHTSCOUT_HOST.*/d' $HOME/.bash_profile + (cat $HOME/.bash_profile | grep -q "NIGHTSCOUT_HOST" || echo export NIGHTSCOUT_HOST="$NIGHTSCOUT_HOST" >> $HOME/.bash_profile) + if [[ "${API_SECRET,,}" =~ "token=" ]]; then # install requirements for token based authentication + API_HASHED_SECRET=${API_SECRET} + else + API_HASHED_SECRET=$(nightscout hash-api-secret $API_SECRET) + fi + # Check if API_SECRET exists, if so remove all lines containing API_SECRET and add the new API_SECRET to the end of the file + sed --in-place '/.*API_SECRET.*/d' $HOME/.bash_profile + (cat $HOME/.profile | grep -q "API_SECRET" || echo export API_SECRET="$API_HASHED_SECRET" >> $HOME/.profile) + + # With 0.5.0 release we switched from ~/.profile to ~/.bash_profile for API_SECRET and NIGHTSCOUT_HOST, because a shell will look + # for ~/.bash_profile, ~/.bash_login, and ~/.profile, in that order, and reads and executes commands from + # the first one that exists and is readable. Remove API_SECRET and NIGHTSCOUT_HOST lines from ~/.profile if they exist + sed --in-place '/.*API_SECRET.*/d' .profile + sed --in-place '/.*NIGHTSCOUT_HOST.*/d' .profile + + # Then append the variables + echo NIGHTSCOUT_HOST="$NIGHTSCOUT_HOST" >> $HOME/.bash_profile + echo "export NIGHTSCOUT_HOST" >> $HOME/.bash_profile + echo API_SECRET="${API_HASHED_SECRET}" >> $HOME/.bash_profile + echo "export API_SECRET" >> $HOME/.bash_profile + + echo + + #Check to see if Explorer HAT is present, and install all necessary stuff + if grep -qa "Explorer HAT" /proc/device-tree/hat/product 2>/dev/null ; then + echo "Looks like you're using an Explorer HAT!" + echo "Making sure SPI is enabled..." + sed -i.bak -e "s/#dtparam=spi=on/dtparam=spi=on/" /boot/config.txt + echo "Enabling i2c device nodes..." + sed -i.bak -e "s/#dtparam=i2c_arm=on/dtparam=i2c_arm=on/" /boot/config.txt + egrep "^dtparam=i2c1=on" /boot/config.txt || echo "dtparam=i2c1=on,i2c1_baudrate=400000" >> /boot/config.txt + echo "i2c-dev" > /etc/modules-load.d/i2c.conf + echo "Installing socat..." + apt-get -y install socat + echo "Installing openaps-menu..." + cd $HOME/src && git clone git://github.com/openaps/openaps-menu.git || (cd openaps-menu && git checkout master && git pull) + cd $HOME/src/openaps-menu && sudo npm install + cp $HOME/src/openaps-menu/openaps-menu.service /etc/systemd/system/ && systemctl enable openaps-menu + cd $HOME/myopenaps && openaps alias remove battery-status; openaps alias add battery-status '! bash -c "sudo ~/src/openaps-menu/scripts/getvoltage.sh > monitor/edison-battery.json"' + fi + + if [[ "$ttyport" =~ "spi" ]]; then + echo Resetting spi_serial + reset_spi_serial.py + fi +# Commenting out the mmtune as attempt to stop the radio reboot errors that happen when re-setting up. +# echo Attempting to communicate with pump: +# ( killall -g openaps; killall -g oref0-pump-loop ) 2>/dev/null +# openaps mmtune +# echo + + read -p "Schedule openaps in cron? y/[N] " -r + if [[ $REPLY =~ ^[Yy]$ ]]; then + + echo Saving existing crontab to $HOME/crontab.txt: + crontab -l | tee $HOME/crontab.old.txt + read -p "Would you like to remove your existing crontab first? y/[N] " -r + if [[ $REPLY =~ ^[Yy]$ ]]; then + crontab -r + fi + + # add crontab entries + (crontab -l; crontab -l | grep -q "NIGHTSCOUT_HOST" || echo NIGHTSCOUT_HOST=$NIGHTSCOUT_HOST) | crontab - + (crontab -l; crontab -l | grep -q "API_SECRET=" || echo API_SECRET=$API_HASHED_SECRET) | crontab - + (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'" || cd '$directory' && oref0-online '$BT_MAC' 2>&1 >> /var/log/openaps/network.log' ) | crontab - + # temporarily disable hotspot for 1m every hour to allow it to try to connect via wifi again + (crontab -l; crontab -l | grep -q "touch /tmp/disable_hotspot" || echo '0,20,40 * * * * touch /tmp/disable_hotspot' ) | crontab - + (crontab -l; crontab -l | grep -q "rm /tmp/disable_hotspot" || echo '1,21,41 * * * * rm /tmp/disable_hotspot' ) | 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 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 - + if [[ ${CGM,,} =~ "g5-upload" ]]; then + (crontab -l; crontab -l | grep -q "oref0-upload-entries" || echo "* * * * * cd $directory && oref0-upload-entries" ) | crontab - + fi + if [[ ${CGM,,} =~ "shareble" || ${CGM,,} =~ "g4-upload" ]]; then + (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 'monitor-xdrip'" || echo "* * * * * cd $directory && ps aux | grep -v grep | grep -q 'monitor-xdrip' || monitor-xdrip | tee -a /var/log/openaps/xdrip-loop.log") | 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 + (crontab -l; crontab -l | grep -q "cd $directory && ps aux | grep -v grep | grep -q 'openaps get-bg'" || echo "* * * * * cd $directory && ps aux | grep -v grep | grep -q 'openaps get-bg' || ( date; openaps get-bg ; cat cgm/glucose.json | jq -r '.[] | \"\\(.sgv) \\(.dateString)\"' | head -1 ) | tee -a /var/log/openaps/cgm-loop.log") | crontab - + fi + if [[ ${CGM,,} =~ "xdrip" ]]; then # use old ns-loop for now + (crontab -l; crontab -l | grep -q "cd $directory && ps aux | grep -v grep | grep -q 'openaps ns-loop'" || echo "* * * * * cd $directory && ps aux | grep -v grep | grep -q 'openaps ns-loop' || openaps ns-loop | tee -a /var/log/openaps/ns-loop.log") | crontab - + else + (crontab -l; crontab -l | grep -q "cd $directory && ps aux | grep -v grep | grep -q 'oref0-ns-loop'" || echo "* * * * * cd $directory && ps aux | grep -v grep | grep -q 'oref0-ns-loop' || oref0-ns-loop | tee -a /var/log/openaps/ns-loop.log") | crontab - + fi + (crontab -l; crontab -l | grep -q "cd $directory && ps aux | grep -v grep | grep -q 'oref0-autosens-loop' || oref0-autosens-loop 2>&1" || echo "* * * * * cd $directory && ps aux | grep -v grep | grep -q 'oref0-autosens-loop' || oref0-autosens-loop 2>&1 | tee -a /var/log/openaps/autosens-loop.log") | crontab - + if [[ $ENABLE =~ autotune ]]; then + # autotune nightly at 4:05am using data from NS + (crontab -l; crontab -l | grep -q "oref0-autotune -d=$directory -n=$NIGHTSCOUT_HOST" || echo "5 4 * * * ( oref0-autotune -d=$directory -n=$NIGHTSCOUT_HOST && cat $directory/autotune/profile.json | jq . | grep -q start && cp $directory/autotune/profile.json $directory/settings/autotune.json) 2>&1 | tee -a /var/log/openaps/autotune.log") | crontab - + fi + if [[ "$ttyport" =~ "spi" ]]; then + (crontab -l; crontab -l | grep -q "reset_spi_serial.py" || echo "@reboot reset_spi_serial.py") | crontab - + (crontab -l; crontab -l | grep -q "oref0-radio-reboot" || echo "* * * * * oref0-radio-reboot") | crontab - + fi + (crontab -l; crontab -l | grep -q "cd $directory && ( ps aux | grep -v grep | grep bash | grep -q 'bin/oref0-pump-loop'" || echo "* * * * * cd $directory && ( ps aux | grep -v grep | grep bash | grep -q 'bin/oref0-pump-loop' || oref0-pump-loop ) 2>&1 | tee -a /var/log/openaps/pump-loop.log") | crontab - + if [[ ! -z "$BT_PEB" ]]; then + (crontab -l; crontab -l | grep -q "cd $directory && ( ps aux | grep -v grep | grep -q 'peb-urchin-status $BT_PEB '" || echo "* * * * * cd $directory && ( ps aux | grep -v grep | grep -q 'peb-urchin-status $BT_PEB' || peb-urchin-status $BT_PEB ) 2>&1 | tee -a /var/log/openaps/urchin-loop.log") | crontab - + fi + if [[ ! -z "$BT_PEB" || ! -z "$BT_MAC" ]]; then + (crontab -l; crontab -l | grep -q "oref0-bluetoothup" || echo '* * * * * ps aux | grep -v grep | grep -q "oref0-bluetoothup" || oref0-bluetoothup >> /var/log/openaps/network.log' ) | crontab - + fi + #if [[ "$ttyport" =~ "spidev5.1" ]]; then + # proper shutdown once the EdisonVoltage very low (< 3050mV; 2950 is dead) + if egrep -i "edison" /etc/passwd 2>/dev/null; then + (crontab -l; crontab -l | grep -q "cd $directory && sudo ~/src/EdisonVoltage/voltage" || echo "*/15 * * * * cd $directory && sudo ~/src/EdisonVoltage/voltage json batteryVoltage battery | jq .batteryVoltage | awk '{if (\$1<=3050)system(\"sudo shutdown -h now\")}'") | crontab - + #fi + fi + (crontab -l; crontab -l | grep -q "cd $directory && oref0-delete-future-entries" || echo "@reboot cd $directory && oref0-delete-future-entries") | crontab - + if [[ ! -z "$PUSHOVER_TOKEN" && ! -z "$PUSHOVER_USER" ]]; then + (crontab -l; crontab -l | grep -q "oref0-pushover" || echo "* * * * * cd $directory && oref0-pushover $PUSHOVER_TOKEN $PUSHOVER_USER 2>&1 >> /var/log/openaps/pushover.log" ) | crontab - + fi + (crontab -l; crontab -l | grep -q "cd $directory && oref0-version --check-for-updates" || echo "0 * * * * cd $directory && oref0-version --check-for-updates > /tmp/oref0-updates.txt") | crontab - + (crontab -l; crontab -l | grep -q "flask run" || echo "@reboot cd ~/src/oref0/www && export FLASK_APP=app.py && flask run -p 80 --host=0.0.0.0" | tee -a /var/log/openaps/flask.log) | crontab - + crontab -l | tee $HOME/crontab.txt + fi + + if [[ ${CGM,,} =~ "shareble" ]]; then + echo + echo "To pair your G4 Share receiver, open its Settings, select Share, Forget Device (if previously paired), then turn sharing On" + fi + + if [[ ${pumpmodel,,} =~ "x12" ]]; then + echo + echo To complete your x12 pump setup, you must edit your basal_profile.json, + echo and may want to edit your settings.json and bg_targets_raw.json as well. + read -p "Press enter to begin editing basal_profile.json, and then press Ctrl-X when done." + nano $directory/settings/basal_profile.json + read -p "Press enter to begin editing settings.json, and then press Ctrl-X when done." + nano $directory/settings/settings.json + read -p "Press enter to begin editing bg_targets_raw.json, and then press Ctrl-X when done." + nano $directory/settings/bg_targets_raw.json + echo To edit your basal_profile.json again in the future, run: nano $directory/settings/basal_profile.json + echo To edit your settings.json to set maxBasal or DIA, run: nano $directory/settings/settings.json + echo To edit your bg_targets_raw.json to set targets, run: nano $directory/settings/bg_targets_raw.json + fi + +fi # from 'read -p "Continue? y/[N] " -r' after interactive setup is complete + +if [ -e /tmp/reboot-required ]; then + read -p "Reboot required. Press enter to reboot or Ctrl-C to cancel" + sudo reboot +fi diff --git a/bin/oref0-subg-ww-radio-parameters.sh b/bin/oref0-subg-ww-radio-parameters.sh new file mode 100755 index 000000000..eeb6a511a --- /dev/null +++ b/bin/oref0-subg-ww-radio-parameters.sh @@ -0,0 +1,67 @@ +#!/bin/bash + +# set SERIAL_PORT from environment variable, or first argument, or default to /dev/mmeowlink +SERIAL_PORT=${SERIAL_PORT-${1-/dev/mmeowlink}} + +# It requires subg_rfspy in installed. This can be installated with +# cd ~/src +# git clone https://github.com/ps2/subg_rfspy.git +# Set SUBG_RFSPY_DIR to your subg_rfspy checkout +SUBG_RFSPY_DIR=$HOME/src/subg_rfspy + +# If you're on an ERF or TI USB, set this to 0: +#export RFSPY_RTSCTS=0 + +################################################################################ +set -e +# use set -x to debug oref0 ww pump communication errors +# set -x + +echo +echo The CC111x is located at $SERIAL_PORT + +# change to subg_rfspy tools directory +cd $SUBG_RFSPY_DIR/tools + +#Disabled killing openaps, because we want it to be able to use this with openaps mmtune +#echo -n "Killing running openaps processes... " +#killall -g openaps +#echo + +# Disabled by default, because it can hang the pump loop with TI USB stick +# The reset.py script will be called if this script is run with --resetpy as second parameter +# This is the default behaviour implemented in oref0_init_pump_comms.py +case "$2" in + --resetpy) + ./reset.py $SERIAL_PORT + sleep 2 + exit 0 + ;; +esac + +./change_setting.py $SERIAL_PORT 0x06 0x00 # CHANNR + +sleep 0.5 + +./change_setting.py $SERIAL_PORT 0x0C 0x59 # MDMCFG4 +sleep 0.5 +./change_setting.py $SERIAL_PORT 0x0D 0x66 # MDMCFG3 +sleep 0.5 +./change_setting.py $SERIAL_PORT 0x0E 0x33 # MDMCFG2 +sleep 0.5 +./change_setting.py $SERIAL_PORT 0x0F 0x62 # MDMCFG1 +sleep 0.5 +./change_setting.py $SERIAL_PORT 0x10 0x1A # MDMCFG0 +sleep 0.5 + +./change_setting.py $SERIAL_PORT 0x11 0x13 # DEVIATN +sleep 0.5 + +./change_setting.py $SERIAL_PORT 0x09 0x24 # FREQ2 +sleep 0.5 +./change_setting.py $SERIAL_PORT 0x0A 0x2E # FREQ1 +sleep 0.5 +./change_setting.py $SERIAL_PORT 0x0B 0x38 # FREQ0 +sleep 0.5 + +exit 0 diff --git a/bin/oref0-tail-log.sh b/bin/oref0-tail-log.sh new file mode 100755 index 000000000..a24448163 --- /dev/null +++ b/bin/oref0-tail-log.sh @@ -0,0 +1,3 @@ +#!/bin/bash + +tail -n 100 -F /var/log/openaps/pump-loop.log diff --git a/bin/oref0-tail-wifi.sh b/bin/oref0-tail-wifi.sh new file mode 100755 index 000000000..ff06f62a2 --- /dev/null +++ b/bin/oref0-tail-wifi.sh @@ -0,0 +1,3 @@ +#!/bin/bash + +tail -n 100 -F /var/log/openaps/network.log diff --git a/bin/oref0-truncate-git-history.sh b/bin/oref0-truncate-git-history.sh new file mode 100755 index 000000000..b0741e845 --- /dev/null +++ b/bin/oref0-truncate-git-history.sh @@ -0,0 +1,52 @@ +#!/bin/bash + +# Delete git lock / history if necessary to recover from corrupted .git objects +# +# Released under MIT license. See the accompanying LICENSE.txt file for +# full terms and conditions +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. + +# must be run from within a git repo to do anything useful +self=$(basename $0) +BACKUP_AREA=${1-${BACKUP_AREA-/var/cache/openaps-ruination}} +function usage ( ) { + +cat </dev/null +find .git/refs/heads/master.lock -mmin +60 -exec rm {} \; 2>/dev/null + +commits=$(git log | grep -c commit) +if (( $commits > 5000 )); then + echo "Found $commits commits; re-initializing .git" + echo "Saving backup to: $BACKUP" > /dev/stderr + mv .git $BACKUP + rm -rf .git + openaps init . +fi + +commits=$(git log | grep -c commit) +usage=$(du -sh .git | awk '{print $1}') +oldest=$(git log | grep Date | tail -1) +echo "$commits git commits using $usage since $oldest" diff --git a/bin/oref0-upload-entries.sh b/bin/oref0-upload-entries.sh new file mode 100755 index 000000000..d98d0ad5d --- /dev/null +++ b/bin/oref0-upload-entries.sh @@ -0,0 +1,30 @@ +#!/bin/bash + +echo "Checking entries-last-date.json..." +if [ -e upload/entries-last-date.json ]; then + LAST_TIME=$(jq -s ".[0].date" upload/entries-last-date.json) + echo "LAST_TIME is $LAST_TIME" + if [ "$LAST_TIME" == "null" ]; then + echo "Setting LAST_TIME to 0" + LAST_TIME=0 + fi +else + echo "Setting LAST_TIME to 0" + LAST_TIME=0 +fi + +echo "Merging cgm-glucose.json and entries-upload.json" +jq -s --unbuffered "[.[0][]] + [.[1][]]|unique|reverse" cgm/cgm-glucose.json upload/entries-upload.json > upload/entries-upload.new.json + +echo "Selecting only those records newer than $LAST_TIME" +jq -s --unbuffered --arg lasttime "$LAST_TIME" '.[0][] | select(.date > ("\($lasttime)" | tonumber))' upload/entries-upload.new.json > upload/entries-upload.array.json + +echo "Merging to an array and removing intermediate files" +jq -s --unbuffered "[.[]]" upload/entries-upload.array.json > upload/entries-upload.json +rm upload/entries-upload.new.json upload/entries-upload.array.json + +UPLOAD_COUNT=$(jq -s ".[]|length" upload/entries-upload.json) +echo "Entries to upload: $UPLOAD_COUNT" +if (( $UPLOAD_COUNT )); then + (ns-upload $NIGHTSCOUT_HOST $API_SECRET entries upload/entries-upload.json - && jq -s "{\"date\":.[0][0].date}" upload/entries-upload.json > upload/entries-last-date.json && rm upload/entries-upload.json) +fi diff --git a/bin/oref0-upload-profile.js b/bin/oref0-upload-profile.js new file mode 100755 index 000000000..2125a7697 --- /dev/null +++ b/bin/oref0-upload-profile.js @@ -0,0 +1,280 @@ +#!/usr/bin/env node + +/* + oref0 Nightscout profile update tool + + Checks the ISF / Basal profile in Nightscout and updates the profile if + necessary to match the profile collected by OpenAPS + + Released under MIT license. See the accompanying LICENSE.txt file for + full terms and conditions + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + +*/ + +var crypto = require('crypto'); +var request = require('request'); +var _ = require('lodash'); + +if (!module.parent) { + + var argv = require('yargs') + .usage("$0 profile.json NSURL api-secret [--preview]") + .option('preview', { + alias: 'p' + , describe: "Give a preview of the outcome without uploading" + , default: false + }) + .strict(true) + .help('help'); + + function usage() { + argv.showHelp(); + } + + var params = argv.argv; + var errors = []; + var warnings = []; + + var profile_input = params._[0]; + + if ([null, '--help', '-h', 'help'].indexOf(profile_input) > 0) { + usage(); + process.exit(0); + } + + var nsurl = params._[1]; + var apisecret = params._[2]; + + if (!profile_input || !nsurl || !apisecret) { + usage(); + process.exit(1); + } + + if (apisecret.length != 40) { + var shasum = crypto.createHash('sha1'); + shasum.update(String(apisecret)); + apisecret = shasum.digest('hex'); + }; + + try { + var cwd = process.cwd(); + var profiledata = require(cwd + '/' + profile_input); + + // Rudimentary check that the profile is valid + + if (!profiledata.dia + || profiledata.basalprofile.length < 1 + || profiledata.bg_targets.length < 1 + || profiledata.isfProfile.length < 1 ) + { throw "Profile JSON missing data"; } + + } catch (e) { + return console.error('Could not parse input data: ', e); + } + + + var options = { + uri: nsurl + '/api/v1/profile/current' + , json: true + , headers: { + 'api-secret': apisecret + } + }; + + request(options, function(error, res, data) { + if (error || res.statusCode != 200) { + console.log('Loading current profile from Nightscout failed'); + process.exit(1); + } + + var original_profile = data; + var new_profile = _.cloneDeep(data); + + if (!data.defaultProfile) { + console.error('Nightscout profile missing data'); + process.exit(1); + } + + var profile_id = data.defaultProfile; + var profile_store = new_profile.store[profile_id]; + + profile_store.dia = profiledata.dia; + + // Basals + + var new_basal = []; + + _.forEach(profiledata.basalprofile, function(basalentry) { + + var newEntry = { + time: '' + basalentry.start.substring(0, 5) + , value: '' + +(Math.round(basalentry.rate + 'e+3') + 'e-3') + , timeAsSeconds: '' + basalentry.minutes * 60 + }; + + new_basal.push(newEntry); + + }); + + profile_store.basal = new_basal; + + // BG Targets + + var new_target_low = []; + var new_target_high = []; + + _.forEach(profiledata.bg_targets.targets, function(target_entry) { + + var time = target_entry.start.substring(0, 5); + var seconds = parseInt(time.substring(0, 2)) * 60 * 60 + parseInt(time.substring(3, 5)) * 60; + var low_value = Math.round(target_entry.low); + var high_value = Math.round(target_entry.high); + + if (new_profile.units == 'mmol' && profiledata.bg_targets.units == 'mg/dL') { + low_value = +(Math.round(target_entry.low / 18 + 'e+1') + 'e-1'); + high_value = +(Math.round(target_entry.high / 18 + 'e+1') + 'e-1'); + } + + var new_low_entry = { + time: '' + time + , value: '' + low_value + , timeAsSeconds: '' + seconds + }; + + var new_high_entry = { + time: '' + time + , value: '' + high_value + , timeAsSeconds: '' + seconds + + }; + + new_target_low.push(new_low_entry); + new_target_high.push(new_high_entry); + }); + + profile_store.target_low = new_target_low; + profile_store.target_high = new_target_high; + + // ISF + + var new_sens = []; + + _.forEach(profiledata.isfProfile.sensitivities, function(isf_entry) { + + var value = Math.round(isf_entry.sensitivity); + + if (new_profile.units == 'mmol' && profiledata.isfProfile.units == 'mg/dL') { + value = +(Math.round(isf_entry.sensitivity / 18 + 'e+1') + 'e-1'); + } + + var new_isf_entry = { + time: isf_entry.start.substring(0, 5) + , value: '' + value + , timeAsSeconds: '' + isf_entry.offset * 60 + }; + + new_sens.push(new_isf_entry); + }); + + profile_store.sens = new_sens; + + // Carb ratios + + var new_carb_ratios = []; + + _.forEach(profiledata.carb_ratios.schedule, function(carb_entry) { + + var new_entry = { + time: carb_entry.start.substring(0, 5) + , value: '' + carb_entry.ratio + , timeAsSeconds: '' + carb_entry.offset * 60 + }; + + new_carb_ratios.push(new_entry); + }); + + profile_store.carbratio = new_carb_ratios; + + // change dates & remove Mongo ID from new profile to create a new object + // Inserts the new profile with name "OpenAPS Autosync" to not overwrite + // human-entered data + + var upload_profile; + + if (profile_id != 'OpenAPS Autosync') { + upload_profile = _.cloneDeep(data); + } else { + upload_profile = new_profile; + } + + var do_upload = !_.isEqual(original_profile, new_profile); + + if (do_upload) { + + var d = new Date(); + profile_store.startDate = d.toISOString(); + + if (profile_id != 'OpenAPS Autosync') { + upload_profile.defaultProfile = 'OpenAPS Autosync'; + upload_profile.store['OpenAPS Autosync'] = profile_store; + } + + delete upload_profile._id; + + upload_profile.startDate = profile_store.startDate; + upload_profile.created_at = profile_store.startDate; + upload_profile.mills = d.getTime(); + } + + // render preview + + if (params.preview) { + + if (_.isEqual(original_profile, new_profile)) { + console.log('Profile in Nightscout and OpenAPS are identical'); + } else { + console.log('Profile in Nightscout and OpenAPS differ'); + console.log('-------------- Nightscout Profile ----------------'); + console.log(JSON.stringify(original_profile, null, 2)); + console.log('-------------- New profile from OpenAPS data ----------------'); + console.log(JSON.stringify(upload_profile, null, 2)); + } + + process.exit(0); + } + + if (do_upload) { + + console.log('Profile changed, uploading to Nightscout'); + + options = { + uri: nsurl + '/api/v1/profile/' + , json: true + , method: 'POST' + , headers: { + 'api-secret': apisecret + } + , body: upload_profile + }; + + request(options, function(error, res, data) { + if (error || res.statusCode != 200) { + console.log(error); + console.log(res.body); + } else { + console.log('Profile uploaded to Nightscout'); + } + }); + } else { + console.log('Profiles match, no upload needed'); + } + }); +} diff --git a/bin/oref0-version.sh b/bin/oref0-version.sh new file mode 100755 index 000000000..87a7dd25d --- /dev/null +++ b/bin/oref0-version.sh @@ -0,0 +1,48 @@ +#!/bin/bash +source ~/.bash_profile +# Simple script to check current version / branch of oref0 installed and check for updates +location=${OREF0_SRC:-${HOME}/src/oref0} +branch=$(cd ${location} && git rev-parse --abbrev-ref HEAD) +version=$(jq .version "${location}/package.json" | sed 's/"//g') + +if [[ $1 =~ "update" ]]; then + cd ${location} && timeout 30 git fetch 2>/dev/null || echo git fetch failed # pull latest remote info + behind=$(cd ${location}/ && git rev-list --count --right-only ${branch}...origin/${branch}) + if (("$behind" > "0")); then + # we are out of date + echo "Your instance of oref0 [${version}, ${branch}] is out-of-date by ${behind} commits: you may want to consider updating." + if [ $branch != "master" ]; then + echo "You are currently running a development branch of oref0. Such branches change frequently." + echo "Please read the latest PR notes and update with the latest commits to dev before reporting any issues." + else + echo "Please make sure to read any new documentation and release notes that accompany the update." + fi + else + echo "Your instance of oref0 [${version}, ${branch}] is up-to-date." + fi + + + git remote -v | grep -q upstream + exit_status=$? + if [[ $exit_status -eq 0 ]]; then + timeout 30 git fetch upstream 2>/dev/null || echo git fetch upstream failed # pull latest remote info + behind=$(cd ${location}/ && git rev-list --count --right-only ${branch}...upstream/${branch}) + if (("$behind" > "0")); then + # we are out of date + echo "Your instance of oref0 [${version}, ${branch}] is out-of-date by ${behind} commits upstream: you may want to consider updating." + if [ $branch != "master" ]; then + echo "You are currently running a development branch of oref0. Such branches change frequently." + echo "Please read the latest PR notes and update with the latest commits to dev before reporting any issues." + else + echo "Please make sure to read any new documentation and release notes that accompany the update." + fi + else + echo "Your instance of oref0 [${version}, ${branch}] is up-to-date with upstream." + fi + fi + + +else + # simple version check and report. + echo "${version} [${branch}]" +fi diff --git a/bin/oref0.sh b/bin/oref0.sh index 44ffa5c9f..593f33525 100755 --- a/bin/oref0.sh +++ b/bin/oref0.sh @@ -12,29 +12,57 @@ function help_message ( ) { Usage: $self - ______ ______ ______ ______ 0 -/ | | \ | | | \ | | | | -| | | | | |__| | | |---- | |---- -\_|__|_/ |_| \_\ |_|____ |_| + ______ ______ ______ ______ 0 + / | | \ | | | \ | | | | + | | | | | |__| | | |---- | |---- + \_|__|_/ |_| \_\ |_|____ |_| Valid commands: - oref0 env - print information about environment. + oref0 device-helper - : create/template a device from bash commands easily + oref0 alias-helper - : create/template a alias from bash commands easily + oref0 env - print information about environment. oref0 pebble oref0 ifttt-notify oref0 get-profile oref0 calculate-iob + oref0 meal oref0 determine-basal + oref0 export-loop [backup-loop.json] - Print a backup json representation of + entire configuration. Optionally, if a + filename is specified, listing is + saved in the file instead. oref0 help - this message EOF } case $NAME in +device-helper) + name=$1 + shift + cat < $out + + exit + ;; +help|--help|-h) help_message ;; *) diff --git a/bin/oref0_autotune_export_to_xlsx.py b/bin/oref0_autotune_export_to_xlsx.py new file mode 100755 index 000000000..fb4acbde2 --- /dev/null +++ b/bin/oref0_autotune_export_to_xlsx.py @@ -0,0 +1,141 @@ +#!/usr/bin/python +# This script converts the json files in the autotune directory +# to a Microsoft Excel file +# +# Released under MIT license. See the accompanying LICENSE.txt file for +# full terms and conditions +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. + +import json +import glob, os, sys + +# +try: + import xlsxwriter +except: + print "This software requires XlsxWriter package. Install it with 'sudo pip install XlsxWriter', see http://xlsxwriter.readthedocs.io/" + sys.exit(1) + +import datetime +import argparse +import re + +def parseDateAndRun(filename): + m=re.match( r'profile.(?P.*).(?P20[0-9][0-9]-[01][0-9]-[0-3][0-9]).json', filename) + if m: + return (m.group('date'), m.group('run')) + else: # not found + return ('-','-') + +def calc_minutes(timestr): + # returns the number of minutes from midnight. seconds are ignored + # based on http://stackoverflow.com/questions/10663720/converting-a-time-string-to-seconds-in-python + ftr = [60,1,0] # ignore seconds, count minutes, and use 60 minutes per hour + return sum([a*b for a,b in zip(ftr, map(int,timestr.split(':')))]) + +def expandProfile(l, valueField, offsetField): + r=[] + minutes=0 + value=l[0][valueField] + for i in range(len(l)): + start1=l[i]['start'] + minutes1=calc_minutes(start1) + offset1=l[i][offsetField] + if minutes1!=offset1: + print "Error in JSON offSetField %s contains %s does not match start time %s (%d minutes). Please report this as a bug" % (offsetField, offset1, start1, minutes1) + sys.exit(1) + while (minutes0: + logging.error("The following permissions are missing in Nightscout: %s" % missing) + logging.error("Please follow instructions at https://openaps.readthedocs.io/en/master/docs/walkthrough/phase-1/nightscout-setup.md#switching-from-api_secret-to-token-based-authentication-for-your-rig") + sys.exit(1) + logging.info("All permissions in Nightscout are ok") + + +if __name__ == '__main__': + try: + parser = argparse.ArgumentParser(description='Checks permissions in Nightscout based on your ns.ini') + parser.add_argument('-v', '--verbose', action="store_true", help='increase output verbosity') + parser.add_argument('--nsini', type=str, help='Path to ns.ini' , default='./ns.ini') + args = parser.parse_args() + + init(args) + startup_checks(args) + check_permissions() + except Exception: + logging.exception("Exception in %s" % __name__) diff --git a/bin/oref0_subg_ww_radio_parameters.py b/bin/oref0_subg_ww_radio_parameters.py new file mode 100755 index 000000000..b789b9049 --- /dev/null +++ b/bin/oref0_subg_ww_radio_parameters.py @@ -0,0 +1,123 @@ +#!/usr/bin/env python3 + +# This script is a wrapper for the subg ww script +# It handles a timeout in case the subg ww script hangs (otherwise it would hold the pump-loop) +# It also resets the usb if --resetusb is set (recommended for TI USB stick) +# It also issues the reset.py script of if --resetpy is set (recommand for all others) + +import argparse +import configparser +import os +import sys +import logging +import subprocess +import time +import signal + +PORT_NOT_SET="port not set in pump.ini" +RADIO_LOCALE_NOT_SET="radio_locale not set in pump.ini" + +# get the port (device name) of the TI-chip from the pump.ini config file +def get_port_from_pump_ini(filename): + logging.debug("Parsing %s" % filename) + config = configparser.ConfigParser() + config.read(filename) + port=PORT_NOT_SET + radio_locale=RADIO_LOCALE_NOT_SET + for section in config.sections(): + if section=='device "pump"': + for option in config.options(section): + if option=='port': + port=config.get(section, option) + if option=='radio_locale': + radio_locale=config.get(section, option) + if radio_locale==RADIO_LOCALE_NOT_SET: + logging.debug("radio_locale is not set in pump.ini. Assuming US pump. No need to set WW parameters") + sys.exit(0) + elif str.lower(radio_locale)=='us': + logging.debug("radio_locale is set to %s. Skipping WW-pump initialization" % radio_locale) + sys.exit(0) + return port + + +# helper method to execute command cmd and return the returncode +# use a timeout of to, and wait w seconds after the command +def execute(cmd, cmdtimeout, wait): + try: + logging.debug("excuting %s" % cmd) + proc=subprocess.Popen(cmd, shell=False) + outs,errs=proc.communicate(timeout=cmdtimeout) + logging.debug("script exited with %s" % proc.returncode) + logging.debug("sleeping for %s seconds " % wait) + time.sleep(wait) + return proc.returncode + except subprocess.TimeoutExpired: + logging.error("TimeoutExpired. Killing process") + if proc.pid: + os.kill(int(proc.pid), signal.SIGKILL) + logging.debug("Exit with status code 1") + sys.exit(1) + +def main(args): + if args.verbose: + logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)s %(message)s') + else: + logging.basicConfig(level=logging.ERROR, format='%(asctime)s %(levelname)s %(message)s') + + try: + # step 1: get port device (pump device) from pump.ini. Exit if it's a US pump + pump_ini=os.path.join(args.dir, args.pump_ini) + pump_port=get_port_from_pump_ini(pump_ini) + logging.debug("Serial device (port) for pump is: %s" % pump_port) + + # step 2: check if port device file exists. If not reset USB if it's requested with the --resetusb parameter + if pump_port==PORT_NOT_SET: + logging.error("port is not set in pump.ini. Please set port to your serial device, e.g. /dev/mmeowlink") + sys.exit(1) + + # step 3: with a TI USB stick the device/symlink can disappear for unknown reasons. Restarting the USB subsystem seems to work + tries=0 + while (not os.path.exists(pump_port)) and tries<2: + logging.error("pump port %s does not exist" % pump_port) + if args.ww_ti_usb_reset=='yes': + exitcode=execute(["sudo", "oref0-reset-usb"], args.timeout, args.wait) + tries=tries+1 + else: # if not --ww_ti_usb_reset==yes then quit the loop + break + + # step 4: set environment variable + os.environ["RFSPY_RTSCTS"]=str(args.rfsypy_rtscts) + logging.debug("env RFSPY_RTSCTS=%s" % os.environ["RFSPY_RTSCTS"] ) + + # step 5: use reset.py + if args.ww_ti_usb_reset=='no': + cmd=["oref0-subg-ww-radio-parameters", str(pump_port), "--resetpy"] + exitcode=execute(cmd, args.timeout, args.wait) + + if not os.path.exists(pump_port): + logging.error("pump port %s does not exist. Exiting with status code 1" % pump_port) + sys.exit(1) + + # step 6: now set the subg ww radio parameters + exitcode=execute(['oref0-subg-ww-radio-parameters', pump_port], args.timeout, args.wait) + sys.exit(exitcode) # propagate exit code from oref0-subg-ww-radio-parameters + except Exception: + logging.exception("Exception in subg_ww_radio_parameters.py") + sys.exit(1) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser(description='Wrapper for setting World Wide radio parameters to a Medtronic pump for TI chip') + parser.add_argument('-d', '--dir', help='openaps dir', default='.') + parser.add_argument('-t', '--timeout', type=int, help='timeout value for script', default=30) + parser.add_argument('-w', '--wait', type=int, help='wait time after command', default=0.5) + parser.add_argument('--pump_ini', help='filename for pump config file', default='pump.ini') + parser.add_argument('--ww_ti_usb_reset', type=str, help='call oref0_reset_usb command or not. Use \'yes\' only for TI USB and WW-pump. Default: no' , default='no') + parser.add_argument('--rfsypy_rtscts', type=int, help='sets the RFSPY_RTSCTS environment variable (set to 0 for ERF and TI USB)', default=0) + parser.add_argument('-v', '--verbose', action="store_true", help='increase output verbosity') + parser.add_argument('--version', action='version', version='%(prog)s 0.0.1-dev') + args = parser.parse_args() + if str.lower(args.ww_ti_usb_reset) not in ['', 'yes', 'no']: + logging.fatal("Use --ww_ti_usb_reset with 'yes' or no'. You specified %s" % args.ww_ti_usb_reset) + sys.exit(1) + main(args) diff --git a/bin/peb-urchin-status.sh b/bin/peb-urchin-status.sh new file mode 100755 index 000000000..fd0a9f0a8 --- /dev/null +++ b/bin/peb-urchin-status.sh @@ -0,0 +1,31 @@ +#!/bin/bash +MAC=$1 + +if ! ( rfcomm show hci0 | grep -q $MAC ) ; then + sudo rfcomm bind hci0 $MAC +fi + +#Status for Pancreabble Urchin +if [[ $(jq .urchin_loop_status pancreoptions.json) = "true" ]]; then + echo {"\"message\": "\"loop status at "'$(date +%-I:%M%P)'": Running\"} > upload/urchin-status.json +fi +if [[ $(jq .urchin_iob pancreoptions.json) = "true" ]]; then + echo {"\"message\": "\""$(date +%R)": IOB: $(jq .openaps.iob.iob upload/ns-status.json)\"} > upload/urchin-status.json +fi +if [[ $(jq .urchin_temp_rate pancreoptions.json) = "true" ]]; then + echo {"\"message\": "\""$(date +%-I:%M%P)": Basal: $(jq .rate monitor/temp_basal.json) U/hr for $(jq .duration monitor/temp_basal.json) mins\"} > upload/urchin-status.json +fi + +#Notification Status +if [[ $(jq .notify_temp_basal pancreoptions.json) = "true" ]]; then + if [[ $(jq .rate enact/suggested.json) != null ]]; then + openaps use pbbl notify "Set Temp Basal" "at $(date +%-I:%M%P): $(jq .rate enact/suggested.json) for $(jq .duration enact/suggested.json) minutes" + fi +fi + + + +#decide to run urchin loop or not +if [[ $(jq .urchin_loop_on pancreoptions.json) = "true" ]]; then + openaps urchin-loop +fi diff --git a/bin/send-tempbasal-Azure.js b/bin/send-tempbasal-Azure.js deleted file mode 100755 index 32b60380d..000000000 --- a/bin/send-tempbasal-Azure.js +++ /dev/null @@ -1,76 +0,0 @@ -#!/usr/bin/env node - -/* - Send Temporary Basal to Azure - - Copyright (c) 2015 OpenAPS Contributors - - Released under MIT license. See the accompanying LICENSE.txt file for - full terms and conditions - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - -*/ -var http = require('https'); - -if (!module.parent) { - var iob_input = process.argv.slice(2, 3).pop() - var enacted_temps_input = process.argv.slice(3, 4).pop() - var glucose_input = process.argv.slice(4, 5).pop() - var webapi = process.argv.slice(5, 6).pop() - if (!iob_input || !enacted_temps_input || !glucose_input || !webapi) { - console.log('usage: ', process.argv.slice(0, 2), ' <[your_webapi].azurewebsites.net>'); - process.exit(1); - } -} - -var cwd = process.cwd(); -var glucose_data = require(cwd + '/' + glucose_input); -var enacted_temps = require(cwd + '/' + enacted_temps_input); -var iob_data = require(cwd + '/' + iob_input); - - - -var data = JSON.stringify({ - "Id": 3, - "temp": enacted_temps.temp, - "rate": enacted_temps.rate, - "duration": enacted_temps.duration, - "bg": glucose_data[0].glucose, - "iob": iob_data.iob, - "timestamp": enacted_temps.timestamp, - "received": enacted_temps.recieved -} -); - -var options = { - host: webapi, - port: '443', - path: '/api/openapstempbasals', - method: 'POST', - headers: { - 'Content-Type': 'application/json; charset=utf-8', - 'Content-Length': data.length - } -}; - -var req = http.request(options, function (res) { - var msg = ''; - - res.setEncoding('utf8'); - res.on('data', function (chunk) { - msg += chunk; - }); - res.on('end', function () { - console.log(JSON.parse(msg)); - }); -}); - -req.write(data); -req.end(); diff --git a/headless/headless.sh b/headless/headless.sh index d560e1f16..fc4ac8aa6 100755 --- a/headless/headless.sh +++ b/headless/headless.sh @@ -25,10 +25,10 @@ Interface='wlan0' HostAPDIP='10.29.29.1' echo "-----------------------------------" echo "Checking for DHCP leases" -clients=`cat /var/lib/misc/dnsmasq.leases | wc -l` +clients=$(cat /var/lib/misc/dnsmasq.leases | wc -l) echo "$clients DHCP clients found" if [[ $clients -eq 0 ]]; then - hostapd=`pidof hostapd` + hostapd=$(pidof hostapd) if [[ ! -z $hostapd ]]; then echo "Activating client config" cp /etc/network/interfaces.client /etc/network/interfaces @@ -40,7 +40,7 @@ if [[ $clients -eq 0 ]]; then /etc/init.d/networking stop echo "Starting networking" /etc/init.d/networking start - wpasup=`pidof wpa_supplicant` + wpasup=$(pidof wpa_supplicant) if [[ -z $wpasup ]]; then echo "Attempting to start wpa_supplicant" sudo wpa_supplicant -B -i wlan0 -c /etc/wpa_supplicant/wpa_supplicant.conf @@ -49,13 +49,13 @@ if [[ $clients -eq 0 ]]; then /sbin/dhclient wlan0 else echo "Checking connectivity of $Interface" - NetworkUp=`/sbin/ifconfig $Interface` - IP=`echo "$NetworkUp" | grep inet | wc -l` + NetworkUp=$(/sbin/ifconfig $Interface) + IP=$(echo "$NetworkUp" | grep inet | wc -l) if [[ $IP -eq 0 || $NetworkUp =~ $HostAPDIP ]]; then #if [[ $IP -eq 0 ]]; then #echo "Connection is down" - hostapd=`pidof hostapd` + hostapd=$(pidof hostapd) if [[ -z $hostapd ]]; then # If there are any more actions required when the interface goes down, add them here echo "Killing wpa_supplicant" diff --git a/headless/hostapd.conf b/headless/hostapd.conf index abe3a0a18..c76aad1e3 100644 --- a/headless/hostapd.conf +++ b/headless/hostapd.conf @@ -19,4 +19,10 @@ hw_mode=g channel=6 macaddr_acl=0 ignore_broadcast_ssid=0 -wpa=0 +wpa=2 +wpa_passphrase=#OpenAPS +wpa_key_mgmt=WPA-PSK +wpa_pairwise=CCMP +wpa_group_rekey=86400 +ieee80211n=1 +wme_enabled=1 diff --git a/headless/install.sh b/headless/install.sh index 86cd453a8..d7ba33874 100755 --- a/headless/install.sh +++ b/headless/install.sh @@ -15,5 +15,6 @@ cp ./dnsmasq.conf /etc/dnsmasq.conf ls /etc/hostapd/hostapd.conf.bak || mv /etc/hostapd/hostapd.conf /etc/hostapd/hostapd.conf.bak cp ./hostapd.conf /etc/hostapd/hostapd.conf sed -i.bak -e "s|DAEMON_CONF=|DAEMON_CONF=/etc/hostapd/hostapd.conf|g" /etc/init.d/hostapd -cp interfaces.* /etc/network/ -ls $PWD/headless.sh && ( grep -q headless /etc/crontab || echo "* * * * * root $PWD/headless.sh" ) >> /etc/crontab +cp interfaces.ap /etc/network/ +cp /etc/network/interfaces /etc/network/interfaces.client +#ls $PWD/headless.sh && ( grep -q headless /etc/crontab || echo "* * * * * root $PWD/headless.sh" ) >> /etc/crontab diff --git a/lib/autotune-prep/categorize.js b/lib/autotune-prep/categorize.js new file mode 100644 index 000000000..5bb8b69b9 --- /dev/null +++ b/lib/autotune-prep/categorize.js @@ -0,0 +1,428 @@ +var tz = require('moment-timezone'); +var basal = require('../profile/basal'); +var getIOB = require('../iob'); +var ISF = require('../profile/isf'); +var find_insulin = require('../iob/history'); +var dosed = require('./dosed'); + +// main function categorizeBGDatums. ;) categorize to ISF, CSF, or basals. + +function categorizeBGDatums(opts) { + var treatments = opts.treatments; + // this sorts the treatments collection in order. + treatments.sort(function (a, b) { + var aDate = new Date(tz(a.timestamp)); + var bDate = new Date(tz(b.timestamp)); + //console.error(aDate); + return bDate.getTime() - aDate.getTime(); + }); + var profileData = opts.profile; + if (typeof(opts.glucose) !== 'undefined') { + //var glucoseData = opts.glucose; + var glucoseData = opts.glucose.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; + }); + } + // this sorts the glucose collection in order. + glucoseData.sort(function (a, b) { + var aDate = new Date(tz(a.date)); + var bDate = new Date(tz(b.date)); + //console.error(aDate); + return bDate.getTime() - aDate.getTime(); + }); + // if (typeof(opts.preppedGlucose) !== 'undefined') { + // var preppedGlucoseData = opts.preppedGlucose; + // } + //starting variable at 0 + var boluses = 0; + var maxCarbs = 0; + //console.error(treatments); + if (!treatments) return {}; + + //console.error(glucoseData); + var IOBInputs = { + profile: profileData + , history: opts.pumpHistory + }; + var CSFGlucoseData = []; + var ISFGlucoseData = []; + var basalGlucoseData = []; + var UAMGlucoseData = []; + var CRData = []; + + var bucketedData = []; + bucketedData[0] = glucoseData[0]; + j=0; + //for loop to validate and bucket the data + for (var i=1; i < glucoseData.length; ++i) { + var BGTime; + var lastBGTime; + if (glucoseData[i].date) { + BGTime = new Date(glucoseData[i].date); + } else if (glucoseData[i].displayTime) { + BGTime = new Date(glucoseData[i].displayTime.replace('T', ' ')); + } else if (glucoseData[i].dateString) { + BGTime = new Date(glucoseData[i].dateString); + } else { console.error("Could not determine BG time"); } + if (glucoseData[i-1].date) { + lastBGTime = new Date(glucoseData[i-1].date); + } else if (glucoseData[i-1].displayTime) { + lastBGTime = new Date(glucoseData[i-1].displayTime.replace('T', ' ')); + } else if (glucoseData[i-1].dateString) { + lastBGTime = new Date(glucoseData[i-1].dateString); + } else { console.error("Could not determine last BG time"); } + if (glucoseData[i].glucose < 39 || glucoseData[i-1].glucose < 39) { + continue; + } + var elapsedMinutes = (BGTime - lastBGTime)/(60*1000); + if(Math.abs(elapsedMinutes) > 2) { + j++; + bucketedData[j]=glucoseData[i]; + bucketedData[j].date = BGTime.getTime(); + if (! bucketedData[j].dateString) { + bucketedData[j].dateString = BGTime.toISOString(); + } + } else { + // if duplicate, average the two + bucketedData[j].glucose = (bucketedData[j].glucose + glucoseData[i].glucose)/2; + } + } + //console.error(bucketedData); + //console.error(bucketedData[bucketedData.length-1]); + // go through the treatments and remove any that are older than the oldest glucose value + //console.error(treatments); + for (var i=treatments.length-1; i>0; --i) { + var treatment = treatments[i]; + //console.error(treatment); + if (treatment) { + var treatmentDate = new Date(tz(treatment.timestamp)); + var treatmentTime = treatmentDate.getTime(); + var glucoseDatum = bucketedData[bucketedData.length-1]; + //console.error(glucoseDatum); + var BGDate = new Date(glucoseDatum.date); + var BGTime = BGDate.getTime(); + if ( treatmentTime < BGTime ) { + treatments.splice(i,1); + } + } + } + //console.error(treatments); + var calculatingCR = false; + var absorbing = 0; + var uam = 0; // unannounced meal + var mealCOB = 0; + var mealCarbs = 0; + var CRCarbs = 0; + var type=""; + // main for loop + var fullHistory = IOBInputs.history; + for (var i=bucketedData.length-5; i > 0; --i) { + var glucoseDatum = bucketedData[i]; + //console.error(glucoseDatum); + var BGDate = new Date(glucoseDatum.date); + var 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]; + var myCarbs = 0; + if (treatment) { + var treatmentDate = new Date(tz(treatment.timestamp)); + var treatmentTime = treatmentDate.getTime(); + //console.error(treatmentDate); + if ( treatmentTime < BGTime ) { + if (treatment.carbs >= 1) { + mealCOB += parseFloat(treatment.carbs); + mealCarbs += parseFloat(treatment.carbs); + myCarbs = treatment.carbs; + } + treatments.pop(); + } + } + + var BG; + var avgDelta; + var delta; + // TODO: re-implement interpolation to avoid issues here with gaps + // calculate avgDelta as last 4 datapoints to better catch more rises after COB hits zero + if (typeof(bucketedData[i].glucose) != 'undefined' && typeof(bucketedData[i+4].glucose) != 'undefined') { + //console.error(bucketedData[i]); + BG = bucketedData[i].glucose; + if ( BG < 40 || bucketedData[i+4].glucose < 40) { + //process.stderr.write("!"); + continue; + } + avgDelta = (BG - bucketedData[i+4].glucose)/4; + delta = (BG - bucketedData[i+1].glucose); + } else { console.error("Could not find glucose data"); } + + avgDelta = avgDelta.toFixed(2); + glucoseDatum.avgDelta = avgDelta; + + //sens = ISF + var sens = ISF.isfLookup(IOBInputs.profile.isfProfile,BGDate); + IOBInputs.clock=BGDate.toISOString(); + // trim down IOBInputs.history to just the data for 6h prior to BGDate + //console.error(IOBInputs.history[0].created_at); + var newHistory = []; + for (h=0; h 0) { + //process.stderr.write("i"); + //console.error(hDate); + newHistory.push(fullHistory[h]); + } + } + IOBInputs.history = newHistory; + // process.stderr.write("" + newHistory.length + " "); + //console.error(newHistory[0].created_at,newHistory[newHistory.length-1].created_at,newHistory.length); + + + // 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 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); + + //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 + //console.log(JSON.stringify(IOBInputs.profile)); + // call iob since calculated elsewhere + var iob = getIOB(IOBInputs)[0]; + //console.error(JSON.stringify(iob)); + + // activity times ISF times 5 minutes is BGI + var BGI = Math.round(( -iob.activity * sens * 5 )*100)/100; + // datum = one glucose data point (being prepped to store in output) + glucoseDatum.BGI = BGI; + // calculating deviation + deviation = avgDelta-BGI; + + // set positive deviations to zero if BG is below 80 + if ( BG < 80 && deviation > 0 ) { + deviation = 0; + } + + // rounding and storing deviation + deviation = deviation.toFixed(2); + glucoseDatum.deviation = deviation; + + + // 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; + // Store the COB, and use it as the starting point for the next data point. + mealCOB = Math.max(0, mealCOB-absorbed); + } + + + // Calculate carb ratio (CR) independently of CSF and ISF + // Use the time period from meal bolus/carbs until COB is zero and IOB is < currentBasal/2 + // For now, if another meal IOB/COB stacks on top of it, consider them together + // Compare beginning and ending BGs, and calculate how much more/less insulin is needed to neutralize + // Use entered carbs vs. starting IOB + delivered insulin + needed-at-end insulin to directly calculate CR. + + if (mealCOB > 0 || calculatingCR ) { + // set initial values when we first see COB + CRCarbs += myCarbs; + if (!calculatingCR) { + CRInitialIOB = iob.iob; + CRInitialBG = glucoseDatum.glucose; + CRInitialCarbTime = new Date(glucoseDatum.date); + console.error("CRInitialIOB:",CRInitialIOB,"CRInitialBG:",CRInitialBG,"CRInitialCarbTime:",CRInitialCarbTime); + } + // keep calculatingCR as long as we have COB or enough IOB + if ( mealCOB > 0 && i>1 ) { + calculatingCR = true; + } else if ( iob.iob > currentBasal/2 && i>1 ) { + 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); + console.error("CREndIOB:",CREndIOB,"CREndBG:",CREndBG,"CREndTime:",CREndTime); + var CRDatum = { + CRInitialIOB: CRInitialIOB + , CRInitialBG: CRInitialBG + , CRInitialCarbTime: CRInitialCarbTime + , CREndIOB: CREndIOB + , CREndBG: CREndBG + , CREndTime: CREndTime + , CRCarbs: CRCarbs + }; + //console.error(CRDatum); + + var CRElapsedMinutes = Math.round((CREndTime - CRInitialCarbTime) / 1000 / 60); + //console.error(CREndTime - CRInitialCarbTime, CRElapsedMinutes); + if ( CRElapsedMinutes < 60 || ( i==1 && mealCOB > 0 ) ) { + console.error("Ignoring",CRElapsedMinutes,"m CR period."); + } else { + CRData.push(CRDatum); + } + + CRCarbs = 0; + calculatingCR = false; + } + } + + + // If mealCOB is zero but all deviations since hitting COB=0 are positive, assign those data points to CSFGlucoseData + // Once deviations go negative for at least one data point after COB=0, we can use the rest of the data to tune ISF or basals + if (mealCOB > 0 || absorbing || mealCarbs > 0) { + // if meal IOB has decayed, then end absorption after this data point unless COB > 0 + if ( iob.iob < currentBasal/2 ) { + absorbing = 0; + // otherwise, as long as deviations are positive, keep tracking carb deviations + } else if (deviation > 0) { + absorbing = 1; + } else { + absorbing = 0; + } + if ( ! absorbing && ! mealCOB ) { + mealCarbs = 0; + } + // check previous "type" value, and if it wasn't csf, set a mealAbsorption start flag + //console.error(type); + if ( type != "csf" ) { + glucoseDatum.mealAbsorption = "start"; + console.error(glucoseDatum.mealAbsorption,"carb absorption"); + } + type="csf"; + glucoseDatum.mealCarbs = mealCarbs; + //if (i == 0) { glucoseDatum.mealAbsorption = "end"; } + CSFGlucoseData.push(glucoseDatum); + } else { + // check previous "type" value, and if it was csf, set a mealAbsorption end flag + if ( type === "csf" ) { + CSFGlucoseData[CSFGlucoseData.length-1].mealAbsorption = "end"; + console.error(CSFGlucoseData[CSFGlucoseData.length-1].mealAbsorption,"carb absorption"); + } + + if ((iob.iob > currentBasal || deviation > 6 || uam) ) { + if (deviation > 0) { + uam = 1; + } else { + uam = 0; + } + if ( type != "uam" ) { + glucoseDatum.uamAbsorption = "start"; + console.error(glucoseDatum.uamAbsorption,"uannnounced meal absorption"); + } + type="uam"; + UAMGlucoseData.push(glucoseDatum); + } else { + if ( type === "uam" ) { + console.error("end unannounced meal absorption"); + } + + + // Go through the remaining time periods and divide them into periods where scheduled basal insulin activity dominates. This would be determined by calculating the BG impact of scheduled basal insulin (for example 1U/hr * 48 mg/dL/U ISF = 48 mg/dL/hr = 5 mg/dL/5m), and comparing that to BGI from bolus and net basal insulin activity. + // When BGI is positive (insulin activity is negative), we want to use that data to tune basals + // When BGI is smaller than about 1/4 of basalBGI, we want to use that data to tune basals + // When BGI is negative and more than about 1/4 of basalBGI, we can use that data to tune ISF, + // unless avgDelta is positive: then that's some sort of unexplained rise we don't want to use for ISF, so that means basals + if (basalBGI > -4 * BGI) { + type="basal"; + basalGlucoseData.push(glucoseDatum); + } else { + if ( avgDelta > 0 && avgDelta > -2*BGI ) { + //type="unknown" + type="basal" + basalGlucoseData.push(glucoseDatum); + } else { + type="ISF"; + ISFGlucoseData.push(glucoseDatum); + } + } + } + } + // debug line to print out all the things + 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 = { + profile: profileData + , history: opts.pumpHistory + }; + var treatments = find_insulin(IOBInputs); + CRData.forEach(function(CRDatum) { + var dosedOpts = { + treatments: treatments + , profile: opts.profile + , start: CRDatum.CRInitialCarbTime + , end: CRDatum.CREndTime + }; + var insulinDosed = dosed(dosedOpts); + CRDatum.CRInsulin = insulinDosed.insulin; + //console.error(CRDatum); + }); + + var CSFLength = CSFGlucoseData.length; + var ISFLength = ISFGlucoseData.length; + var UAMLength = UAMGlucoseData.length; + var basalLength = basalGlucoseData.length; + + if (opts.categorize_uam_as_basal) { + console.error("Categorizing all UAM data as basal."); + basalGlucoseData = basalGlucoseData.concat(UAMGlucoseData); + } else if (2*basalLength < UAMLength) { + //console.error(basalGlucoseData, UAMGlucoseData); + console.error("Warning: too many deviations categorized as UnAnnounced Meals"); + console.error("Adding",UAMLength,"UAM deviations to",basalLength,"basal ones"); + basalGlucoseData = basalGlucoseData.concat(UAMGlucoseData); + //console.error(basalGlucoseData); + // if too much data is excluded as UAM, add in the UAM deviations, but then discard the highest 50% + basalGlucoseData.sort(function (a, b) { + return a.deviation - b.deviation; + }); + var newBasalGlucose = basalGlucoseData.slice(0,basalGlucoseData.length/2); + //console.error(newBasalGlucose); + basalGlucoseData = newBasalGlucose; + console.error("and selecting the lowest 50%, leaving", basalGlucoseData.length, "basal+UAM ones"); + + console.error("Adding",UAMLength,"UAM deviations to",ISFLength,"ISF ones"); + ISFGlucoseData = ISFGlucoseData.concat(UAMGlucoseData); + //console.error(ISFGlucoseData.length, UAMLength); + } + var basalLength = basalGlucoseData.length; + var 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"); + //var basalGlucoseData = basalGlucoseData.concat(CSFGlucoseData); + console.error("Adding",CSFLength,"CSF deviations to",ISFLength,"ISF ones"); + ISFGlucoseData = ISFGlucoseData.concat(CSFGlucoseData); + CSFGlucoseData = []; + } + + + return { + CRData: CRData, + CSFGlucoseData: CSFGlucoseData, + ISFGlucoseData: ISFGlucoseData, + basalGlucoseData: basalGlucoseData + }; +} + +exports = module.exports = categorizeBGDatums; diff --git a/lib/autotune-prep/dosed.js b/lib/autotune-prep/dosed.js new file mode 100644 index 000000000..41c207ab3 --- /dev/null +++ b/lib/autotune-prep/dosed.js @@ -0,0 +1,28 @@ +function insulinDosed(opts) { + + var start = opts.start.getTime(); + var end = opts.end.getTime(); + var treatments = opts.treatments; + var profile_data = opts.profile; + var insulinDosed = 0; + if (!treatments) { + console.error("No treatments to process."); + return {}; + } + + treatments.forEach(function(treatment) { + //console.error(treatment); + if(treatment.insulin && treatment.date > start && treatment.date <= end) { + insulinDosed += treatment.insulin; + } + }); + //console.error(insulinDosed); + + var rval = { + insulin: Math.round( insulinDosed * 1000 ) / 1000 + }; + + return rval; +} + +exports = module.exports = insulinDosed; diff --git a/lib/autotune-prep/index.js b/lib/autotune-prep/index.js new file mode 100644 index 000000000..26a9c28a0 --- /dev/null +++ b/lib/autotune-prep/index.js @@ -0,0 +1,28 @@ + +// Prep step before autotune.js can run; pulls in meal (carb) data and calls categorize.js + +var tz = require('moment-timezone'); +var find_meals = require('../meal/history'); +var categorize = require('./categorize'); + +function generate (inputs) { + + //console.error(inputs); + var treatments = find_meals(inputs); + + var opts = { + treatments: treatments + , profile: inputs.profile + , pumpHistory: inputs.history + , glucose: inputs.glucose + //, prepped_glucose: inputs.prepped_glucose + , basalprofile: inputs.profile.basalprofile + , pumpbasalprofile: inputs.pumpprofile.basalprofile + , categorize_uam_as_basal: inputs.categorize_uam_as_basal + }; + + var autotune_prep_output = categorize(opts); + return autotune_prep_output; +} + +exports = module.exports = generate; diff --git a/lib/autotune/index.js b/lib/autotune/index.js new file mode 100644 index 000000000..2de190e0a --- /dev/null +++ b/lib/autotune/index.js @@ -0,0 +1,463 @@ +// does three things - tunes basals, ISF, and CSF + +function tuneAllTheThings (inputs) { + + var previousAutotune = inputs.previousAutotune; + //console.error(previousAutotune); + var pumpProfile = inputs.pumpProfile; + var pumpBasalProfile = pumpProfile.basalprofile; + //console.error(pumpBasalProfile); + var basalProfile = previousAutotune.basalprofile; + //console.error(basalProfile); + var isfProfile = previousAutotune.isfProfile; + //console.error(isfProfile); + var ISF = isfProfile.sensitivities[0].sensitivity; + //console.error(ISF); + var carbRatio = previousAutotune.carb_ratio; + //console.error(carbRatio); + var CSF = ISF / carbRatio; + // conditional on there being a pump profile; if not then skip + if (pumpProfile) { var pumpISFProfile = pumpProfile.isfProfile; } + if (pumpISFProfile && pumpISFProfile.sensitivities[0]) { + var pumpISF = pumpISFProfile.sensitivities[0].sensitivity; + var pumpCarbRatio = pumpProfile.carb_ratio; + var pumpCSF = pumpISF / pumpCarbRatio; + } + if (! carbRatio) { carbRatio = pumpCarbRatio; } + if (! CSF) { CSF = pumpCSF; } + if (! ISF) { ISF = pumpISF; } + //console.error(CSF); + var preppedGlucose = inputs.preppedGlucose; + var CSFGlucose = preppedGlucose.CSFGlucoseData; + //console.error(CSFGlucose[0]); + var ISFGlucose = preppedGlucose.ISFGlucoseData; + //console.error(ISFGlucose[0]); + var basalGlucose = preppedGlucose.basalGlucoseData; + //console.error(basalGlucose[0]); + var CRData = preppedGlucose.CRData; + //console.error(CRData); + + // Calculate carb ratio (CR) independently of CSF and ISF + // Use the time period from meal bolus/carbs until COB is zero and IOB is < currentBasal/2 + // For now, if another meal IOB/COB stacks on top of it, consider them together + // Compare beginning and ending BGs, and calculate how much more/less insulin is needed to neutralize + // Use entered carbs vs. starting IOB + delivered insulin + needed-at-end insulin to directly calculate CR. + + var CRTotalCarbs = 0; + var CRTotalInsulin = 0; + CRData.forEach(function(CRDatum) { + CRBGChange = CRDatum.CREndBG - CRDatum.CRInitialBG; + CRInsulinReq = CRBGChange / ISF; + 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; + //console.error(CRBGChange, CRInsulinReq, CRIOBChange, CRInsulinTotal); + //console.error("CRCarbs:",CRDatum.CRCarbs,"CRInsulin:",CRDatum.CRInsulinTotal,"CR:",CR); + if (CRDatum.CRInsulin > 0) { + CRTotalCarbs += CRDatum.CRCarbs; + CRTotalInsulin += CRDatum.CRInsulinTotal; + } + }); + CRTotalInsulin = Math.round(CRTotalInsulin*1000)/1000; + 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 + var hourlyBasalProfile = []; + var hourlyPumpProfile = []; + for (var i=0; i < 24; i++) { + // autotuned basal profile + for (var j=0; j < basalProfile.length; ++j) { + if (basalProfile[j].minutes <= i * 60) { + if (basalProfile[j].rate == 0) { + console.error("ERROR: bad basalProfile",basalProfile[j]); + return; + } + hourlyBasalProfile[i] = JSON.parse(JSON.stringify(basalProfile[j])); + } + } + hourlyBasalProfile[i].i=i; + hourlyBasalProfile[i].minutes=i*60; + var zeroPadHour = ("000"+i).slice(-2); + hourlyBasalProfile[i].start=zeroPadHour + ":00:00"; + 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) { + //console.error(pumpBasalProfile[j]); + if (pumpBasalProfile[j].rate == 0) { + console.error("ERROR: bad pumpBasalProfile",pumpBasalProfile[j]); + return; + } + if (pumpBasalProfile[j].minutes <= i * 60) { + hourlyPumpProfile[i] = JSON.parse(JSON.stringify(pumpBasalProfile[j])); + } + } + hourlyPumpProfile[i].i=i; + hourlyPumpProfile[i].minutes=i*60; + hourlyPumpProfile[i].rate=Math.round(hourlyPumpProfile[i].rate*1000)/1000 + } + } + //console.error(hourlyPumpProfile); + //console.error(hourlyBasalProfile); + var newHourlyBasalProfile = JSON.parse(JSON.stringify(hourlyBasalProfile)); + + // look at net deviations for each hour + for (var hour=0; hour < 24; hour++) { + var deviations = 0; + for (var i=0; i < basalGlucose.length; ++i) { + var BGTime; + + if (basalGlucose[i].date) { + BGTime = new Date(basalGlucose[i].date); + } else if (basalGlucose[i].displayTime) { + BGTime = new Date(basalGlucose[i].displayTime.replace('T', ' ')); + } else if (basalGuclose[i].dateString) { + BGTime = new Date(basalGlucose[i].dateString); + } else { + console.error("Could not determine last BG time"); + } + + var myHour = BGTime.getHours(); + if (hour == myHour) { + //console.error(basalGlucose[i].deviation); + deviations += parseFloat(basalGlucose[i].deviation); + } + } + deviations = Math.round( deviations * 1000 ) / 1000 + console.error("Hour",hour.toString(),"total deviations:",deviations,"mg/dL"); + // calculate how much less or additional basal insulin would have been required to eliminate the deviations + // only apply 20% of the needed adjustment to keep things relatively stable + var basalNeeded = 0.2 * deviations / ISF; + basalNeeded = Math.round( basalNeeded * 100 ) / 100 + // if basalNeeded is positive, adjust each of the 1-3 hour prior basals by 10% of the needed adjustment + console.error("Hour",hour,"basal adjustment needed:",basalNeeded,"U/hr"); + if (basalNeeded > 0 ) { + for (var offset=-3; offset < 0; offset++) { + var offsetHour = hour + offset; + if (offsetHour < 0) { offsetHour += 24; } + //console.error(offsetHour); + newHourlyBasalProfile[offsetHour].rate += basalNeeded / 3; + newHourlyBasalProfile[offsetHour].rate=Math.round(newHourlyBasalProfile[offsetHour].rate*1000)/1000 + } + // otherwise, figure out the percentage reduction required to the 1-3 hour prior basals + // and adjust all of them downward proportionally + } else if (basalNeeded < 0) { + var threeHourBasal = 0; + for (var 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++) { + offsetHour = hour + offset; + if (offsetHour < 0) { offsetHour += 24; } + newHourlyBasalProfile[offsetHour].rate = newHourlyBasalProfile[offsetHour].rate * adjustmentRatio; + newHourlyBasalProfile[offsetHour].rate=Math.round(newHourlyBasalProfile[offsetHour].rate*1000)/1000 + } + } + } + if (pumpBasalProfile && pumpBasalProfile[0]) { + for (var hour=0; hour < 24; hour++) { + //console.error(newHourlyBasalProfile[hour],hourlyPumpProfile[hour].rate*1.2); + // cap adjustments at autosens_max and autosens_min + var autotuneMax = pumpProfile.autosens_max; + var autotuneMin = pumpProfile.autosens_min; + var maxRate = hourlyPumpProfile[hour].rate * autotuneMax; + var minRate = hourlyPumpProfile[hour].rate * autotuneMin; + if (newHourlyBasalProfile[hour].rate > maxRate ) { + console.error("Limiting hour",hour,"basal to",maxRate.toFixed(2),"(which is",autotuneMax,"* pump basal of",hourlyPumpProfile[hour].rate,")"); + //console.error("Limiting hour",hour,"basal to",maxRate.toFixed(2),"(which is 20% above pump basal of",hourlyPumpProfile[hour].rate,")"); + newHourlyBasalProfile[hour].rate = maxRate; + } else if (newHourlyBasalProfile[hour].rate < minRate ) { + console.error("Limiting hour",hour,"basal to",minRate.toFixed(2),"(which is",autotuneMin,"* pump basal of",hourlyPumpProfile[hour].rate,")"); + //console.error("Limiting hour",hour,"basal to",minRate.toFixed(2),"(which is 20% below pump basal of",hourlyPumpProfile[hour].rate,")"); + newHourlyBasalProfile[hour].rate = minRate; + } + newHourlyBasalProfile[hour].rate = Math.round(newHourlyBasalProfile[hour].rate*1000)/1000; + } + } + + // some hours of the day rarely have data to tune basals due to meals. + // when no adjustments are needed to a particular hour, we should adjust it toward the average of the + // periods before and after it that do have data to be tuned + + var lastAdjustedHour = 0; + // scan through newHourlyBasalProfile and find hours where the rate is unchanged + for (var hour=0; hour < 24; hour++) { + if (hourlyBasalProfile[hour].rate === newHourlyBasalProfile[hour].rate) { + var nextAdjustedHour = 23; + for (var nextHour = hour; nextHour < 24; nextHour++) { + if (! (hourlyBasalProfile[nextHour].rate === newHourlyBasalProfile[nextHour].rate)) { + nextAdjustedHour = nextHour; + break; + //} else { + //console.error(nextHour, hourlyBasalProfile[nextHour].rate, newHourlyBasalProfile[nextHour].rate); + } + } + //console.error(hour, newHourlyBasalProfile); + newHourlyBasalProfile[hour].rate = Math.round( (0.8*hourlyBasalProfile[hour].rate + 0.1*newHourlyBasalProfile[lastAdjustedHour].rate + 0.1*newHourlyBasalProfile[nextAdjustedHour].rate)*1000 )/1000; + console.error("Adjusting hour",hour,"basal from",hourlyBasalProfile[hour].rate,"to",newHourlyBasalProfile[hour].rate,"based on hour",lastAdjustedHour,"=",newHourlyBasalProfile[lastAdjustedHour].rate,"and hour",nextAdjustedHour,"=",newHourlyBasalProfile[nextAdjustedHour].rate); + } else { + lastAdjustedHour = hour; + } + } + + console.error(newHourlyBasalProfile); + basalProfile = newHourlyBasalProfile; + + // Calculate carb ratio (CR) independently of CSF and ISF + // Use the time period from meal bolus/carbs until COB is zero and IOB is < currentBasal/2 + // For now, if another meal IOB/COB stacks on top of it, consider them together + // Compare beginning and ending BGs, and calculate how much more/less insulin is needed to neutralize + // Use entered carbs vs. starting IOB + delivered insulin + needed-at-end insulin to directly calculate CR. + + + + // calculate net deviations while carbs are absorbing + // measured from carb entry until COB and deviations both drop to zero + + var deviations = 0; + var mealCarbs = 0; + var totalMealCarbs = 0; + var totalDeviations = 0; + var fullNewCSF; + //console.error(CSFGlucose[0].mealAbsorption); + //console.error(CSFGlucose[0]); + for (var i=0; i < CSFGlucose.length; ++i) { + //console.error(CSFGlucose[i].mealAbsorption, i); + if ( CSFGlucose[i].mealAbsorption === "start" ) { + deviations = 0; + mealCarbs = parseInt(CSFGlucose[i].mealCarbs); + } else if (CSFGlucose[i].mealAbsorption === "end") { + deviations += parseFloat(CSFGlucose[i].deviation); + // compare the sum of deviations from start to end vs. current CSF * mealCarbs + //console.error(CSF,mealCarbs); + var csfRise = CSF * mealCarbs; + //console.error(deviations,ISF); + //console.error("csfRise:",csfRise,"deviations:",deviations); + totalMealCarbs += mealCarbs; + totalDeviations += deviations; + + } else { + deviations += Math.max(0*previousAutotune.min_5m_carbimpact,parseFloat(CSFGlucose[i].deviation)); + mealCarbs = Math.max(mealCarbs, parseInt(CSFGlucose[i].mealCarbs)); + } + } + // at midnight, write down the mealcarbs as total meal carbs (to prevent special case of when only one meal and it not finishing absorbing by midnight) + // TODO: figure out what to do with dinner carbs that don't finish absorbing by midnight + if (totalMealCarbs == 0) { totalMealCarbs += mealCarbs; } + if (totalDeviations == 0) { totalDeviations += deviations; } + //console.error(totalDeviations, totalMealCarbs); + if (totalMealCarbs == 0) { + // if no meals today, CSF is unchanged + fullNewCSF = CSF; + } else { + // how much change would be required to account for all of the deviations + fullNewCSF = Math.round( (totalDeviations / totalMealCarbs)*100 )/100; + } + // only adjust by 20% + var newCSF = ( 0.8 * CSF ) + ( 0.2 * fullNewCSF ); + // safety cap CSF + if (typeof(pumpCSF) !== 'undefined') { + var maxCSF = pumpCSF * autotuneMax; + var minCSF = pumpCSF * autotuneMin; + if (newCSF > maxCSF) { + console.error("Limiting CSF to",maxCSF.toFixed(2),"(which is",autotuneMax,"* pump CSF of",pumpCSF,")"); + newCSF = maxCSF; + } else if (newCSF < minCSF) { + console.error("Limiting CSF to",minCSF.toFixed(2),"(which is",autotuneMin,"* pump CSF of",pumpCSF,")"); + newCSF = minCSF; + } //else { console.error("newCSF",newCSF,"is close enough to",pumpCSF); } + } + 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); + // this is where CSF is set based on the outputs + if (newCSF) { + CSF = newCSF; + } + + if (totalCR == 0) { + // if no meals today, CR is unchanged + fullNewCR = carbRatio; + } else { + // how much change would be required to account for all of the deviations + fullNewCR = totalCR; + } + // safety cap fullNewCR + if (typeof(pumpCarbRatio) !== 'undefined') { + var maxCR = pumpCarbRatio * autotuneMax; + var minCR = pumpCarbRatio * autotuneMin; + if (fullNewCR > maxCR) { + console.error("Limiting fullNewCR from",fullNewCR,"to",maxCR.toFixed(2),"(which is",autotuneMax,"* pump CR of",pumpCarbRatio,")"); + fullNewCR = maxCR; + } else if (fullNewCR < minCR) { + console.error("Limiting fullNewCR from",fullNewCR,"to",minCR.toFixed(2),"(which is",autotuneMin,"* pump CR of",pumpCarbRatio,")"); + fullNewCR = minCR; + } //else { console.error("newCR",newCR,"is close enough to",pumpCarbRatio); } + } + // only adjust by 20% + newCR = ( 0.8 * carbRatio ) + ( 0.2 * fullNewCR ); + // safety cap newCR + if (typeof(pumpCarbRatio) !== 'undefined') { + var maxCR = pumpCarbRatio * autotuneMax; + var minCR = pumpCarbRatio * autotuneMin; + if (newCR > maxCR) { + console.error("Limiting CR to",maxCR.toFixed(2),"(which is",autotuneMax,"* pump CR of",pumpCarbRatio,")"); + newCR = maxCR; + } else if (newCR < minCR) { + console.error("Limiting CR to",minCR.toFixed(2),"(which is",autotuneMin,"* pump CR of",pumpCarbRatio,")"); + newCR = minCR; + } //else { console.error("newCR",newCR,"is close enough to",pumpCarbRatio); } + } + newCR = Math.round( newCR * 1000 ) / 1000; + console.error("oldCR:",carbRatio,"fullNewCR:",fullNewCR,"newCR:",newCR); + // this is where CR is set based on the outputs + //var ISFFromCRAndCSF = ISF; + if (newCR) { + carbRatio = newCR; + //ISFFromCRAndCSF = Math.round( carbRatio * CSF * 1000)/1000; + } + + + + // calculate median deviation and bgi in data attributable to ISF + var deviations = []; + var BGIs = []; + var avgDeltas = []; + var ratios = []; + var count = 0; + for (var i=0; i < ISFGlucose.length; ++i) { + deviation = parseFloat(ISFGlucose[i].deviation); + deviations.push(deviation); + var BGI = parseFloat(ISFGlucose[i].BGI); + BGIs.push(BGI); + var avgDelta = parseFloat(ISFGlucose[i].avgDelta); + avgDeltas.push(avgDelta); + var ratio = 1 + deviation / BGI; + //console.error("Deviation:",deviation,"BGI:",BGI,"avgDelta:",avgDelta,"ratio:",ratio); + ratios.push(ratio); + count++; + } + avgDeltas.sort(function(a, b){return a-b}); + BGIs.sort(function(a, b){return a-b}); + deviations.sort(function(a, b){return a-b}); + ratios.sort(function(a, b){return a-b}); + var p50deviation = percentile(deviations, 0.50); + var p50BGI = percentile(BGIs, 0.50); + var p50ratios = Math.round( percentile(ratios, 0.50) * 1000)/1000; + if (count < 10) { + // leave ISF unchanged if fewer than 5 ISF data points + var fullNewISF = ISF; + } else { + // calculate what adjustments to ISF would have been necessary to bring median deviation to zero + fullNewISF = ISF * p50ratios; + } + fullNewISF = Math.round( fullNewISF * 1000 ) / 1000; + // adjust the target ISF to be a weighted average of fullNewISF and pumpISF + var adjustmentFraction; + + if (typeof(pumpProfile.autotune_isf_adjustmentFraction) !== 'undefined') { + adjustmentFraction = pumpProfile.autotune_isf_adjustmentFraction; + } else { + adjustmentFraction = 1.0; + } + + // low autosens ratio = high ISF + var maxISF = pumpISF / autotuneMin; + // high autosens ratio = low ISF + var minISF = pumpISF / autotuneMax; + if (typeof(pumpISF) !== 'undefined') { + if ( fullNewISF < 0 ) { + var adjustedISF = ISF; + } else { + var adjustedISF = adjustmentFraction*fullNewISF + (1-adjustmentFraction)*pumpISF; + } + // cap adjustedISF before applying 10% + //console.error(adjustedISF, maxISF, minISF); + 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 20% of that adjustment + var newISF = ( 0.8 * ISF ) + ( 0.2 * adjustedISF ); + + if (newISF > maxISF) { + console.error("Limiting ISF of",newISF.toFixed(2),"to",maxISF.toFixed(2),"(which is pump ISF of",pumpISF,"/",autotuneMin,")"); + newISF = maxISF; + } else if (newISF < minISF) { + console.error("Limiting ISF of",newISF.toFixed(2),"to",minISF.toFixed(2),"(which is pump ISF of",pumpISF,"/",autotuneMax,")"); + newISF = minISF; + } + } + newISF = Math.round( newISF * 1000 ) / 1000; + //console.error(avgRatio); + //console.error(newISF); + p50deviation = Math.round( p50deviation * 1000 ) / 1000; + p50BGI = Math.round( p50BGI * 1000 ) / 1000; + adjustedISF = Math.round( adjustedISF * 1000 ) / 1000; + console.error("p50deviation:",p50deviation,"p50BGI",p50BGI,"p50ratios:",p50ratios,"Old ISF:",ISF,"fullNewISF:",fullNewISF,"adjustedISF:",adjustedISF,"newISF:",newISF); + + if (newISF) { + ISF = newISF; + } + + + // reconstruct updated version of previousAutotune as autotuneOutput + var autotuneOutput = previousAutotune; + autotuneOutput.basalprofile = basalProfile; + isfProfile.sensitivities[0].sensitivity = ISF; + autotuneOutput.isfProfile = isfProfile; + autotuneOutput.sens = ISF; + autotuneOutput.csf = CSF; + //carbRatio = ISF / CSF; + carbRatio = Math.round( carbRatio * 1000 ) / 1000; + autotuneOutput.carb_ratio = carbRatio; + + return autotuneOutput; +} + +exports = module.exports = tuneAllTheThings; + +// From https://gist.github.com/IceCreamYou/6ffa1b18c4c8f6aeaad2 +// Returns the value at a given percentile in a sorted numeric array. +// "Linear interpolation between closest ranks" method +function percentile(arr, p) { + if (arr.length === 0) return 0; + if (typeof p !== 'number') throw new TypeError('p must be a number'); + if (p <= 0) return arr[0]; + if (p >= 1) return arr[arr.length - 1]; + + var index = arr.length * p, + lower = Math.floor(index), + upper = lower + 1, + weight = index % 1; + + if (upper >= arr.length) return arr[lower]; + return arr[lower] * (1 - weight) + arr[upper] * weight; +} + +// Returns the percentile of the given value in a sorted numeric array. +function percentRank(arr, v) { + if (typeof v !== 'number') throw new TypeError('v must be a number'); + for (var i = 0, l = arr.length; i < l; i++) { + if (v <= arr[i]) { + while (i < l && v === arr[i]) i++; + if (i === 0) return 0; + if (v !== arr[i-1]) { + i += (v - arr[i-1]) / (arr[i] - arr[i-1]); + } + return i / l; + } + } + return 1; +} diff --git a/lib/basal-set-temp.js b/lib/basal-set-temp.js index daf70e4d5..04b00d178 100644 --- a/lib/basal-set-temp.js +++ b/lib/basal-set-temp.js @@ -1,23 +1,60 @@ -var setTempBasal = function (rate, duration, profile, rT, offline) { - maxSafeBasal = Math.min(profile.max_basal, 3 * profile.max_daily_basal, 4 * profile.current_basal); - - if (rate < 0) { - rate = 0; - } // if >30m @ 0 required, zero temp will be extended to 30m instead - else if (rate > maxSafeBasal) { - rate = maxSafeBasal; +'use strict'; + +function reason(rT, msg) { + rT.reason = (rT.reason ? rT.reason + '. ' : '') + msg; + console.error(msg); +} + +var tempBasalFunctions = {}; + +tempBasalFunctions.getMaxSafeBasal = function getMaxSafeBasal(profile) { + + var max_daily_safety_multiplier = (isNaN(profile.max_daily_safety_multiplier) || profile.max_daily_safety_multiplier == null) ? 3 : profile.max_daily_safety_multiplier; + var current_basal_safety_multiplier = (isNaN(profile.current_basal_safety_multiplier) || profile.current_basal_safety_multiplier == null) ? 4 : profile.current_basal_safety_multiplier; + + return Math.min(profile.max_basal, max_daily_safety_multiplier * profile.max_daily_basal, current_basal_safety_multiplier * profile.current_basal); +}; + +tempBasalFunctions.setTempBasal = function setTempBasal(rate, duration, profile, rT, currenttemp) { + //var maxSafeBasal = Math.min(profile.max_basal, 3 * profile.max_daily_basal, 4 * profile.current_basal); + + var maxSafeBasal = tempBasalFunctions.getMaxSafeBasal(profile); + var round_basal = require('./round-basal'); + + if (rate < 0) { + rate = 0; + } else if (rate > maxSafeBasal) { + rate = maxSafeBasal; } - - // rather than canceling temps, if Offline mode is set, always set the current basal as a 30m temp - // so we can see on the pump that openaps is working - if (duration == 0 && offline == 'Offline') { - rate = profile.current_basal; - duration = 30; + + var suggestedRate = round_basal(rate, profile); + if (typeof(currenttemp) !== 'undefined' && typeof(currenttemp.duration) !== 'undefined' && typeof(currenttemp.rate) !== 'undefined' && currenttemp.duration > (duration-10) && currenttemp.duration <= 120 && suggestedRate <= currenttemp.rate * 1.2 && suggestedRate >= currenttemp.rate * 0.8 && duration > 0 ) { + rT.reason += " "+currenttemp.duration+"m left and " + currenttemp.rate + " ~ req " + suggestedRate + "U/hr: no temp required"; + return rT; } - rT.duration = duration; - rT.rate = Math.round((Math.round(rate / 0.05) * 0.05)*100)/100; - return rT; + if (suggestedRate === profile.current_basal) { + if (profile.skip_neutral_temps) { + if (typeof(currenttemp) !== 'undefined' && typeof(currenttemp.duration) !== 'undefined' && currenttemp.duration > 0) { + reason(rT, 'Suggested rate is same as profile rate, a temp basal is active, canceling current temp'); + rT.duration = 0; + rT.rate = 0; + return rT; + } else { + reason(rT, 'Suggested rate is same as profile rate, no temp basal is active, doing nothing'); + return rT; + } + } else { + reason(rT, 'Setting neutral temp basal of ' + profile.current_basal + 'U/hr'); + rT.duration = duration; + rT.rate = suggestedRate; + return rT; + } + } else { + rT.duration = duration; + rT.rate = suggestedRate; + return rT; + } }; -module.exports = setTempBasal; \ No newline at end of file +module.exports = tempBasalFunctions; diff --git a/lib/bolus.js b/lib/bolus.js index 7e14e995a..c7845f7fa 100644 --- a/lib/bolus.js +++ b/lib/bolus.js @@ -5,11 +5,11 @@ function reduce (treatments) { var state = { }; var previous = [ ]; - + function in_previous (ev) { var found = false; previous.forEach(function (elem) { - if (elem.timestamp == ev.timestamp && ev._type == elem._type) { + if (elem.timestamp === ev.timestamp && ev._type === elem._type) { found = true; } }); @@ -23,14 +23,13 @@ function reduce (treatments) { var candidates = tail.slice( ).filter(function (elem) { var dt = Date.parse(elem.timestamp); return ts - dt <= ms; - }); return candidates; } function bolus (ev, remaining) { if (!ev) { console.error('XXX', ev, remaining); return; } - if (ev._type == 'BolusWizard') { + if (ev._type === 'BolusWizard') { state.carbs = ev.carb_input.toString( ); state.ratio = ev.carb_ratio.toString( ); if (ev.bg) { @@ -43,24 +42,26 @@ function reduce (treatments) { previous.push(ev); } - if (ev._type == 'Bolus') { + if (ev._type === 'Bolus') { state.duration = ev.duration.toString( ); // if (state.square || state.bolus) { } // state.insulin = (state.insulin ? state.insulin : 0) + ev.amount; if (ev.duration && ev.duration > 0) { state.square = ev; } else { - state.bolus = ev; + if (state.bolus) { + state.bolus.amount = state.bolus.amount + ev.amount; + } else + state.bolus = ev; } state.created_at = state.timestamp = ev.timestamp; previous.push(ev); } - if (remaining && remaining.length > 0) { if (state.bolus && state.wizard) { // skip to end - return bolus({}, []); + return bolus({}, []); } // keep recursing return bolus(remaining[0], remaining.slice(1)); @@ -69,8 +70,8 @@ function reduce (treatments) { // console.error("remaining", remaining); state.eventType = ''; - state.insulin = (state.square ? state.square.amount : 0) + - (state.bolus ? state.bolus.amount : 0); + state.insulin = (state.insulin ? state.insulin : 0) + (state.square ? state.square.amount : 0) + + (state.bolus ? state.bolus.amount : 0); var has_insulin = state.insulin && state.insulin > 0; var has_carbs = state.carbs && state.carbs > 0; var has_wizard = state.wizard ? true : false; @@ -88,6 +89,17 @@ function reduce (treatments) { annotate("Normal bolus (solo, no bolus wizard)."); } + if (has_insulin) { + var iobFile = "./monitor/iob.json"; + var fs = require('fs'); + if (fs.existsSync(iobFile)) { + var iob = JSON.parse(fs.readFileSync(iobFile)); + if (iob && Array.isArray(iob) && iob.length) { + annotate("Calculated IOB:", iob[0].iob); + } + } + } + if (state.bolus) { annotate("Programmed bolus", state.bolus.programmed); annotate("Delivered bolus", state.bolus.amount); @@ -113,7 +125,7 @@ function reduce (treatments) { // TODO: annotate prediction } } - if (state.carbs && state.insulin && state.bg) { + if (has_carbs && has_insulin) { state.eventType = 'Meal Bolus'; } else { if (has_carbs && !has_insulin) { @@ -151,9 +163,14 @@ function reduce (treatments) { switch (current._type) { case 'Bolus': case 'BolusWizard': - var tail = within_minutes_from(current, treatments.slice(index+1), 4); + var tail = within_minutes_from(current, treatments.slice(index+1), 2); bolus(current, tail); break; + case 'JournalEntryMealMarker': + current.carbs = current.carb_input; + current.eventType = 'Carb Correction'; + results.push(current); + break; default: results.push(current); break; diff --git a/lib/determine-basal/autosens.js b/lib/determine-basal/autosens.js new file mode 100644 index 000000000..6a18cd61f --- /dev/null +++ b/lib/determine-basal/autosens.js @@ -0,0 +1,450 @@ +var basal = require('../profile/basal'); +var get_iob = require('../iob'); +var find_insulin = require('../iob/history'); +var isf = require('../profile/isf'); +var find_meals = require('../meal/history'); +var tz = require('moment-timezone'); + +function detectSensitivity(inputs) { + + 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; + + // use last 24h worth of data by default + var lastSiteChange = new Date(new Date().getTime() - (24 * 60 * 60 * 1000)); + if (inputs.iob_inputs.profile.rewind_resets_autosens ) { + // scan through pumphistory and set lastSiteChange to the time of the last pump rewind event + // if not present, leave lastSiteChange unchanged at 24h ago. + var history = inputs.iob_inputs.history; + for (var h=1; h < history.length; ++h) { + if ( ! history[h]._type || history[h]._type != "Rewind" ) { + //process.stderr.write("-"); + continue; + } + if ( history[h].timestamp ) { + lastSiteChange = new Date( history[h].timestamp ); + console.error("Setting lastSiteChange to",lastSiteChange,"using timestamp",history[h].timestamp); + break; + } + } + } + + // get treatments from pumphistory once, not every time we get_iob() + var treatments = find_insulin(inputs.iob_inputs); + + var mealinputs = { + history: inputs.iob_inputs.history + , profile: profile + , carbs: inputs.carbs + , glucose: inputs.glucose_data + //, prepped_glucose: prepped_glucose_data + }; + var meals = find_meals(mealinputs); + meals.sort(function (a, b) { + var aDate = new Date(tz(a.timestamp)); + var bDate = new Date(tz(b.timestamp)); + //console.error(aDate); + return bDate.getTime() - aDate.getTime(); + }); + //console.error(meals); + + var avgDeltas = []; + var bgis = []; + var deviations = []; + var deviationSum = 0; + var bucketed_data = []; + glucose_data.reverse(); + bucketed_data[0] = glucose_data[0]; + 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) { + var bgTime; + var lastbgTime; + if (glucose_data[i].display_time) { + bgTime = new Date(glucose_data[i].display_time.replace('T', ' ')); + } else if (glucose_data[i].dateString) { + bgTime = new Date(glucose_data[i].dateString); + } else { console.error("Could not determine BG time"); } + if (glucose_data[i-1].display_time) { + lastbgTime = new Date(glucose_data[i-1].display_time.replace('T', ' ')); + } else if (glucose_data[i-1].dateString) { + lastbgTime = new Date(glucose_data[i-1].dateString); + } else if (bucketed_data[0].display_time) { + lastbgTime = new Date(bucketed_data[0].display_time.replace('T', ' ')); + } else { console.error("Could not determine last BG time"); } + if (glucose_data[i].glucose < 39 || glucose_data[i-1].glucose < 39) { +//console.error("skipping:",glucose_data[i].glucose,glucose_data[i-1].glucose); + continue; + } + // only consider BGs since lastSiteChange + if (lastSiteChange) { + hoursSinceSiteChange = (bgTime-lastSiteChange)/(60*60*1000); + if (hoursSinceSiteChange < 0) { + //console.error(hoursSinceSiteChange, bgTime, lastSiteChange); + continue; + } + } + var elapsed_minutes = (bgTime - lastbgTime)/(60*1000); + if(Math.abs(elapsed_minutes) > 2) { + j++; + bucketed_data[j]=glucose_data[i]; + bucketed_data[j].date = bgTime.getTime(); + //console.error(elapsed_minutes, bucketed_data[j].glucose, glucose_data[i].glucose); + } else { + bucketed_data[j].glucose = (bucketed_data[j].glucose + glucose_data[i].glucose)/2; + //console.error(bucketed_data[j].glucose, glucose_data[i].glucose); + } + } + bucketed_data.shift(); + for (var i=meals.length-1; i>0; --i) { + var treatment = meals[i]; + //console.error(treatment); + if (treatment) { + var treatmentDate = new Date(tz(treatment.timestamp)); + var treatmentTime = treatmentDate.getTime(); + var glucoseDatum = bucketed_data[0]; + //console.error(glucoseDatum); + var BGDate = new Date(glucoseDatum.date); + var BGTime = BGDate.getTime(); + if ( treatmentTime < BGTime ) { + //console.error("Removing old meal: ",treatmentDate); + meals.splice(i,1); + } + } + } + var absorbing = 0; + var uam = 0; // unannounced meal + var mealCOB = 0; + var mealCarbs = 0; + var mealStartCounter = 999; + var type=""; + //console.error(bucketed_data); + for (var i=3; i < bucketed_data.length; ++i) { + var bgTime = new Date(bucketed_data[i].date); + + var sens = isf.isfLookup(profile.isfProfile,bgTime); + + //console.error(bgTime , bucketed_data[i].glucose); + var bg; + var avgDelta; + var delta; + if (typeof(bucketed_data[i].glucose) != 'undefined') { + bg = bucketed_data[i].glucose; + if ( bg < 40 || bucketed_data[i-3].glucose < 40) { + process.stderr.write("!"); + continue; + } + avgDelta = (bg - bucketed_data[i-3].glucose)/3; + delta = (bg - bucketed_data[i-1].glucose); + } else { console.error("Could not find glucose data"); } + + avgDelta = avgDelta.toFixed(2); + iob_inputs.clock=bgTime; + iob_inputs.profile.current_basal = basal.basalLookup(basalprofile, bgTime); + // make sure autosens doesn't use temptarget-adjusted insulin calculations + iob_inputs.profile.temptargetSet = false; + //console.log(JSON.stringify(iob_inputs.profile)); + //console.error("Before: ", new Date().getTime()); + var iob = get_iob(iob_inputs, true, treatments)[0]; + //console.error("After: ", new Date().getTime()); + //console.log(JSON.stringify(iob)); + + var bgi = Math.round(( -iob.activity * sens * 5 )*100)/100; + bgi = bgi.toFixed(2); + //console.error(delta); + deviation = delta-bgi; + // set positive deviations to zero if BG is below 80 + if ( bg < 80 && deviation > 0 ) { + deviation = 0; + } + deviation = deviation.toFixed(2); + + var glucoseDatum = bucketed_data[i]; + //console.error(glucoseDatum); + var BGDate = new Date(glucoseDatum.date); + var 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]; + if (treatment) { + var treatmentDate = new Date(tz(treatment.timestamp)); + var 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); + process.stderr.write(displayCOB.toString()+"g"); + } + meals.pop(); + } + } + + // 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; + mealCOB = Math.max(0, mealCOB-absorbed); + } + + // If mealCOB is zero but all deviations since hitting COB=0 are positive, exclude from autosens + //console.error(mealCOB, absorbing, mealCarbs); + if (mealCOB > 0 || absorbing || mealCarbs > 0) { + if (deviation > 0 ) { + absorbing = 1; + } else { + absorbing = 0; + } + // stop excluding positive deviations as soon as mealCOB=0 if meal has been absorbing for >5h + if ( mealStartCounter > 60 && mealCOB < 0.5 ) { + displayCOB = Math.round(mealCOB); + process.stderr.write(displayCOB.toString()+"g"); + absorbing = 0; + } + if ( ! absorbing && mealCOB < 0.5 ) { + mealCarbs = 0; + } + // check previous "type" value, and if it wasn't csf, set a mealAbsorption start flag + //console.error(type); + if ( type != "csf" ) { + process.stderr.write("("); + mealStartCounter = 0; + //glucoseDatum.mealAbsorption = "start"; + //console.error(glucoseDatum.mealAbsorption,"carb absorption"); + } + mealStartCounter++; + type="csf"; + glucoseDatum.mealCarbs = mealCarbs; + //if (i == 0) { glucoseDatum.mealAbsorption = "end"; } + //CSFGlucoseData.push(glucoseDatum); + } else { + // check previous "type" value, and if it was csf, set a mealAbsorption end flag + if ( type === "csf" ) { + process.stderr.write(")"); + //CSFGlucoseData[CSFGlucoseData.length-1].mealAbsorption = "end"; + //console.error(CSFGlucoseData[CSFGlucoseData.length-1].mealAbsorption,"carb absorption"); + } + + currentBasal = iob_inputs.profile.current_basal; + // always exclude the first 45m after each carb entry + //if (iob.iob > currentBasal || uam ) { + if (iob.iob > 2 * currentBasal || uam || mealStartCounter < 9 ) { + mealStartCounter++; + if (deviation > 0) { + uam = 1; + } else { + uam = 0; + } + if ( type != "uam" ) { + process.stderr.write("u("); + //glucoseDatum.uamAbsorption = "start"; + //console.error(glucoseDatum.uamAbsorption,"uannnounced meal absorption"); + } + //console.error(mealStartCounter); + type="uam"; + } else { + if ( type === "uam" ) { + process.stderr.write(")"); + //console.error("end unannounced meal absorption"); + } + type = "non-meal" + } + } + + // Exclude meal-related deviations (carb absorption) from autosens + if ( type === "non-meal" ) { + if ( deviation > 0 ) { + //process.stderr.write(" "+bg.toString()); + process.stderr.write("+"); + } else if ( deviation == 0 ) { + process.stderr.write("="); + } else { + //process.stderr.write(" "+bg.toString()); + process.stderr.write("-"); + } + avgDeltas.push(avgDelta); + bgis.push(bgi); + deviations.push(deviation); + deviationSum += parseFloat(deviation); + } else { + process.stderr.write("x"); + } + // add an extra negative deviation if a high temptarget is running and exercise mode is set + if (profile.high_temptarget_raises_sensitivity || profile.exercise_mode) { + 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; + process.stderr.write("-"); + //console.error(tempDeviation) + deviations.push(tempDeviation); + } + } + + var minutes = bgTime.getMinutes(); + var hours = bgTime.getHours(); + if ( minutes >= 0 && minutes < 5 ) { + //console.error(bgTime); + process.stderr.write(hours.toString()+"h"); + // add one neutral deviation every 2 hours to help decay over long exclusion periods + if ( hours % 2 == 0 ) { + deviations.push(0); + process.stderr.write("="); + } + } + var lookback = inputs.deviations; + if (!lookback) { lookback = 96; } + // only keep the last 96 non-excluded data points (8h+ for any exclusions) + if (deviations.length > lookback) { + deviations.shift(); + } + } + //console.error(""); + process.stderr.write(" "); + //console.log(JSON.stringify(avgDeltas)); + //console.log(JSON.stringify(bgis)); + // when we have less than 8h worth of deviation data, add up to 90m of zero deviations + // this dampens any large sensitivity changes detected based on too little data, without ignoring them completely + console.error(""); + console.error("Using most recent",deviations.length,"deviations since",lastSiteChange); + if (deviations.length < 96) { + pad = Math.round((1 - deviations.length/96) * 18); + console.error("Adding",pad,"more zero deviations"); + for (var d=0; d 0.1; i = i - 0.01) { + //console.error("p="+i.toFixed(2)+": "+percentile(avgDeltas, i).toFixed(2)+", "+percentile(bgis, i).toFixed(2)+", "+percentile(deviations, i).toFixed(2)); + 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)); + 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); + console.error(greaterThanZero+"% of non-meal deviations positive (>50% = resistance)"); + } + } + pSensitive = percentile(deviations, 0.50); + pResistant = percentile(deviations, 0.50); + + 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); + console.error("RMS deviation: "+rmsDev.toFixed(2)); + + var basalOff = 0; + + if(pSensitive < 0) { // sensitive + basalOff = pSensitive * (60/5) / profile.sens; + process.stderr.write("Insulin sensitivity detected: "); + } else if (pResistant > 0) { // resistant + basalOff = pResistant * (60/5) / profile.sens; + process.stderr.write("Insulin resistance detected: "); + } else { + console.error("Sensitivity normal."); + } + ratio = 1 + (basalOff / profile.max_daily_basal); + + // don't adjust more than 1.2x by default (set in preferences.json) + var rawRatio = ratio; + ratio = Math.max(ratio, profile.autosens_min); + ratio = Math.min(ratio, profile.autosens_max); + + if (ratio !== rawRatio) { + console.error('Ratio limited from ' + rawRatio + ' to ' + ratio); + } + + ratio = Math.round(ratio*100)/100; + newisf = Math.round(profile.sens / ratio); + console.error("ISF adjusted from "+profile.sens+" to "+newisf); + //console.error("Basal adjustment "+basalOff.toFixed(2)+"U/hr"); + //console.error("Ratio: "+ratio*100+"%: new ISF: "+newisf.toFixed(1)+"mg/dL/U"); + var output = { + "ratio": ratio, + "newisf": newisf + } + return output; +} +module.exports = detectSensitivity; + +// From https://gist.github.com/IceCreamYou/6ffa1b18c4c8f6aeaad2 +// Returns the value at a given percentile in a sorted numeric array. +// "Linear interpolation between closest ranks" method +function percentile(arr, p) { + if (arr.length === 0) return 0; + if (typeof p !== 'number') throw new TypeError('p must be a number'); + if (p <= 0) return arr[0]; + if (p >= 1) return arr[arr.length - 1]; + + var index = arr.length * p, + lower = Math.floor(index), + upper = lower + 1, + weight = index % 1; + + if (upper >= arr.length) return arr[lower]; + return arr[lower] * (1 - weight) + arr[upper] * weight; +} + +// Returns the percentile of the given value in a sorted numeric array. +function percentRank(arr, v) { + if (typeof v !== 'number') throw new TypeError('v must be a number'); + for (var i = 0, l = arr.length; i < l; i++) { + if (v <= arr[i]) { + while (i < l && v === arr[i]) i++; + if (i === 0) return 0; + if (v !== arr[i-1]) { + i += (v - arr[i-1]) / (arr[i] - arr[i-1]); + } + return i / l; + } + } + return 1; +} + +function tempTargetRunning(temptargets_data, time) { + // sort tempTargets by date so we can process most recent first + try { + temptargets_data.sort(function (a, b) { return new Date(a.created_at) < new Date(b.created_at) }); + } catch (e) { + //console.error("Could not sort temptargets_data. Optional feature temporary targets disabled."); + } + //console.error(temptargets_data); + //console.error(time); + for (var i = 0; i < temptargets_data.length; i++) { + start = new Date(temptargets_data[i].created_at); + //console.error(start); + 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 + //console.error(temptargets_data[i]); + 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; + //console.error(tempTarget); + return tempTarget; + } + } +} diff --git a/lib/determine-basal/cob.js b/lib/determine-basal/cob.js new file mode 100644 index 000000000..39420b494 --- /dev/null +++ b/lib/determine-basal/cob.js @@ -0,0 +1,197 @@ +var basal = require('../profile/basal'); +var get_iob = require('../iob'); +var find_insulin = require('../iob/history'); +var isf = require('../profile/isf'); + +function detectCarbAbsorption(inputs) { + + 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); + + //console.error(mealTime, ciTime); + + // get treatments from pumphistory once, not every time we get_iob() + var treatments = find_insulin(inputs.iob_inputs); + + var avgDeltas = []; + var bgis = []; + var deviations = []; + var deviationSum = 0; + var carbsAbsorbed = 0; + var bucketed_data = []; + bucketed_data[0] = glucose_data[0]; + j=0; + var foundPreMealBG = false; + for (var i=1; i < glucose_data.length; ++i) { + var bgTime; + var lastbgTime; + if (glucose_data[i].display_time) { + bgTime = new Date(glucose_data[i].display_time.replace('T', ' ')); + } else if (glucose_data[i].dateString) { + bgTime = new Date(glucose_data[i].dateString); + } else { console.error("Could not determine BG time"); } + if (bucketed_data[bucketed_data.length-1].display_time) { + lastbgTime = new Date(bucketed_data[bucketed_data.length-1].display_time.replace('T', ' ')); + } else if (glucose_data[i-1].display_time) { + lastbgTime = new Date(glucose_data[i-1].display_time.replace('T', ' ')); + } else if (glucose_data[i-1].dateString) { + lastbgTime = new Date(glucose_data[i-1].dateString); + } else { console.error("Could not determine last BG time"); } + if (glucose_data[i].glucose < 39 || glucose_data[i-1].glucose < 39) { +//console.error("skipping:",glucose_data[i].glucose,glucose_data[i-1].glucose); + continue; + } + // only consider BGs for 6h after a meal for calculating COB + hoursAfterMeal = (bgTime-mealTime)/(60*60*1000); + if (hoursAfterMeal > 6 || foundPreMealBG) { + continue; + } else if (hoursAfterMeal < 0) { +//console.error("Found pre-meal BG:",glucose_data[i].glucose, bgTime, Math.round(hoursAfterMeal*100)/100); + foundPreMealBG = true; + } +//console.error(glucose_data[i].glucose, bgTime, Math.round(hoursAfterMeal*100)/100, bucketed_data[bucketed_data.length-1].display_time); + // only consider last ~45m of data in CI mode + // this allows us to calculate deviations for the last ~30m + if (typeof ciTime) { + hoursAgo = (ciTime-bgTime)/(45*60*1000); + if (hoursAgo > 1 || hoursAgo < 0) { + continue; + } + } + var elapsed_minutes = (bgTime - lastbgTime)/(60*1000); + //console.error(bgTime, lastbgTime, elapsed_minutes); + if(Math.abs(elapsed_minutes) > 8) { + // interpolate missing data points + lastbg = glucose_data[i-1].glucose; + elapsed_minutes = Math.abs(elapsed_minutes); + //console.error(elapsed_minutes); + while(elapsed_minutes > 5) { + previousbgTime = new Date(lastbgTime.getTime() - 5 * 60*1000); + j++; + bucketed_data[j] = []; + bucketed_data[j].date = previousbgTime.getTime(); + gapDelta = glucose_data[i].glucose - lastbg; + //console.error(gapDelta, lastbg, elapsed_minutes); + previousbg = lastbg + (5/elapsed_minutes * gapDelta); + bucketed_data[j].glucose = Math.round(previousbg); + //console.error("Interpolated", bucketed_data[j]); + + elapsed_minutes = elapsed_minutes - 5; + lastbg = previousbg; + lastbgTime = new Date(previousbgTime); + } + + } else if(Math.abs(elapsed_minutes) > 2) { + j++; + bucketed_data[j]=glucose_data[i]; + bucketed_data[j].date = bgTime.getTime(); + } else { + bucketed_data[j].glucose = (bucketed_data[j].glucose + glucose_data[i].glucose)/2; + } + //console.error(bucketed_data[j].date) + } + var currentDeviation; + var slopeFromMaxDeviation = 0; + var slopeFromMinDeviation = 999; + var maxDeviation = 0; + var minDeviation = 999; + var allDeviations = []; + //console.error(bucketed_data); + for (var i=0; i < bucketed_data.length-3; ++i) { + var bgTime = new Date(bucketed_data[i].date); + + var sens = isf.isfLookup(profile.isfProfile,bgTime); + + //console.error(bgTime , bucketed_data[i].glucose, bucketed_data[i].date); + var bg; + var avgDelta; + var delta; + if (typeof(bucketed_data[i].glucose) != 'undefined') { + bg = bucketed_data[i].glucose; + if ( bg < 39 || bucketed_data[i+3].glucose < 39) { + process.stderr.write("!"); + continue; + } + avgDelta = (bg - bucketed_data[i+3].glucose)/3; + delta = (bg - bucketed_data[i+1].glucose); + } else { console.error("Could not find glucose data"); } + + avgDelta = avgDelta.toFixed(2); + iob_inputs.clock=bgTime; + iob_inputs.profile.current_basal = basal.basalLookup(basalprofile, bgTime); + //console.log(JSON.stringify(iob_inputs.profile)); + //console.error("Before: ", new Date().getTime()); + var iob = get_iob(iob_inputs, true, treatments)[0]; + //console.error("After: ", new Date().getTime()); + //console.error(JSON.stringify(iob)); + + var bgi = Math.round(( -iob.activity * sens * 5 )*100)/100; + bgi = bgi.toFixed(2); + //console.error(delta); + 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 + if (i==0) { + currentDeviation = Math.round((avgDelta-bgi)*1000)/1000; + if (ciTime > bgTime) { + //console.error("currentDeviation:",currentDeviation,avgDelta,bgi); + allDeviations.push(Math.round(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; + //console.error(avgDeviation,currentDeviation,bgTime,ciTime) + if (avgDeviation > maxDeviation) { + slopeFromMaxDeviation = Math.min(0, deviationSlope); + maxDeviation = avgDeviation; + } + if (avgDeviation < minDeviation) { + slopeFromMinDeviation = Math.max(0, deviationSlope); + minDeviation = avgDeviation; + } + + //console.error("Deviations:",avgDeviation, avgDelta,bgi,bgTime); + allDeviations.push(Math.round(avgDeviation)); + //console.error(allDeviations); + } + + // if bgTime is more recent than mealTime + if(bgTime > mealTime) { + // 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; + // and add that to the running total carbsAbsorbed + //console.error("carbsAbsorbed:",carbsAbsorbed,"absorbed:",absorbed,"bgTime:",bgTime,"BG:",bucketed_data[i].glucose) + carbsAbsorbed += absorbed; + } + } + if(maxDeviation>0) { + //console.error("currentDeviation:",currentDeviation,"maxDeviation:",maxDeviation,"slopeFromMaxDeviation:",slopeFromMaxDeviation); + } + + var output = { + "carbsAbsorbed": carbsAbsorbed + , "currentDeviation": currentDeviation + , "maxDeviation": maxDeviation + , "minDeviation": minDeviation + , "slopeFromMaxDeviation": slopeFromMaxDeviation + , "slopeFromMinDeviation": slopeFromMinDeviation + , "allDeviations": allDeviations + } + return output; +} +module.exports = detectCarbAbsorption; diff --git a/lib/determine-basal/determine-basal.js b/lib/determine-basal/determine-basal.js index 52cb852fe..ce8213289 100644 --- a/lib/determine-basal/determine-basal.js +++ b/lib/determine-basal/determine-basal.js @@ -12,259 +12,1169 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -var determine_basal = function determine_basal(glucose_status, currenttemp, iob_data, profile, offline, setTempBasal) { - var rT = { //short for requestedTemp - }; + + +var round_basal = require('../round-basal') + +// Rounds value to 'digits' decimal places +function round(value, digits) +{ + if (! digits) { digits = 0; } + var scale = Math.pow(10, digits); + return Math.round(value * scale) / scale; +} + +// we expect BG to rise or fall at the rate of BGI, +// adjusted by the rate at which BG would need to rise / +// fall to get eventualBG to target over 2 hours +function calculate_expected_delta(target_bg, eventual_bg, bgi) { + // (hours * mins_per_hour) / 5 = how many 5 minute periods in 2h = 24 + var five_min_blocks = (2 * 60) / 5; + var target_delta = target_bg - eventual_bg; + var expectedDelta = round(bgi + (target_delta / five_min_blocks), 1); + return expectedDelta; +} + + +function convert_bg(value, profile) +{ + if (profile.out_units == "mmol/L") + { + return round(value / 18, 1).toFixed(1); + } + else + { + return Math.round(value); + } +} + +var determine_basal = function determine_basal(glucose_status, currenttemp, iob_data, profile, autosens_data, meal_data, tempBasalFunctions, microBolusAllowed, reservoir_data) { + var rT = {}; //short for requestedTemp + + var deliverAt = new Date(); if (typeof profile === 'undefined' || typeof profile.current_basal === 'undefined') { rT.error ='Error: could not get current basal rate'; return rT; } + var profile_current_basal = round_basal(profile.current_basal, profile); + var basal = profile_current_basal; + + var systemTime = new Date(); + var bgTime = new Date(glucose_status.date); + var minAgo = round( (systemTime - bgTime) / 60 / 1000 ,1); var bg = glucose_status.glucose; - if (bg < 30) { //Dexcom is in ??? mode or calibrating, do nothing. Asked @benwest for raw data in iter_glucose - rT.error = "CGM is calibrating or in ??? state"; - return rT; + var noise = glucose_status.noise; + // 38 is an xDrip error state that usually indicates sensor failure + // all other BG values between 11 and 37 mg/dL reflect non-error-code BG values, so we should zero temp for those + if (bg <= 10 || bg == 38 || noise >= 3) { //Dexcom is in ??? mode or calibrating, or xDrip reports high noise + rT.reason = "CGM is calibrating, in ??? state, or noise is high"; + } + if (minAgo > 12 || minAgo < -5) { // Dexcom data is too old, or way in the future + rT.reason = "If current system time "+systemTime+" is correct, then BG data is too old. The last BG data was read "+minAgo+"m ago at "+bgTime; + } + // if BG is too old/noisy, or is completely unchanging, cancel any high temps and shorten any long zero temps + if ( glucose_status.short_avgdelta == 0 && glucose_status.long_avgdelta == 0 ) { + rT.reason = "Error: CGM data is unchanged for the past ~45m"; + } + if (bg <= 10 || bg == 38 || noise >= 3 || minAgo > 12 || minAgo < -5 || ( glucose_status.short_avgdelta == 0 && glucose_status.long_avgdelta == 0 ) ) { + if (currenttemp.rate >= basal) { // high temp is running + rT.reason += ". Canceling high temp basal of "+currenttemp.rate; + rT.deliverAt = deliverAt; + rT.temp = 'absolute'; + rT.duration = 0; + rT.rate = 0; + return rT; + //return tempBasalFunctions.setTempBasal(basal, 30, profile, rT, currenttemp); + } else if ( currenttemp.rate == 0 && currenttemp.duration > 30 ) { //shorten long zero temps to 30m + rT.reason += ". Shortening " + currenttemp.duration + "m long zero temp to 30m. "; + rT.deliverAt = deliverAt; + rT.temp = 'absolute'; + rT.duration = 30; + rT.rate = 0; + return rT; + //return tempBasalFunctions.setTempBasal(0, 30, profile, rT, currenttemp); + } else { //do nothing. + rT.reason += ". Temp " + currenttemp.rate + " <= current basal " + basal + "U/hr; doing nothing. "; + return rT; + } } var max_iob = profile.max_iob; // maximum amount of non-bolus IOB OpenAPS will ever deliver - // if target_bg is set, great. otherwise, if min and max are set, then set target to their average + // if min and max are set, then set target to their average var target_bg; - if (typeof profile.target_bg !== 'undefined') { - target_bg = profile.target_bg; + var min_bg; + var max_bg; + if (typeof profile.min_bg !== 'undefined') { + min_bg = profile.min_bg; + } + if (typeof profile.max_bg !== 'undefined') { + max_bg = profile.max_bg; + } + if (typeof profile.min_bg !== 'undefined' && typeof profile.max_bg !== 'undefined') { + target_bg = (profile.min_bg + profile.max_bg) / 2; } else { - if (typeof profile.min_bg !== 'undefined' && typeof profile.max_bg !== 'undefined') { - target_bg = (profile.min_bg + profile.max_bg) / 2; + rT.error ='Error: could not determine target_bg. '; + return rT; + } + + var sensitivityRatio; + var high_temptarget_raises_sensitivity = profile.exercise_mode || profile.high_temptarget_raises_sensitivity; + var normalTarget = 100; // evaluate high/low temptarget against 100, not scheduled basal (which might change) + 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%) + // 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 + 10 + || profile.low_temptarget_lowers_sensitivity && profile.temptargetSet && target_bg < normalTarget ) { + // w/ target 100, temp target 110 = .89, 120 = 0.8, 140 = 0.67, 160 = .57, and 200 = .44 + // e.g.: Sensitivity ratio set to 0.8 based on temp target of 120; Adjusting basal from 1.65 to 1.35; ISF from 58.9 to 73.6 + //sensitivityRatio = 2/(2+(target_bg-normalTarget)/40); + var c = halfBasalTarget - normalTarget; + sensitivityRatio = c/(c+target_bg-normalTarget); + // limit sensitivityRatio to profile.autosens_max (1.2x by default) + sensitivityRatio = Math.min(sensitivityRatio, profile.autosens_max); + sensitivityRatio = round(sensitivityRatio,2); + process.stderr.write("Sensitivity ratio set to "+sensitivityRatio+" based on temp target of "+target_bg+"; "); + } else if (typeof autosens_data !== 'undefined' ) { + sensitivityRatio = autosens_data.ratio; + process.stderr.write("Autosens ratio: "+sensitivityRatio+"; "); + } + if (sensitivityRatio) { + basal = profile.current_basal * sensitivityRatio; + basal = round_basal(basal, profile); + if (basal != profile_current_basal) { + process.stderr.write("Adjusting basal from "+profile_current_basal+" to "+basal+"; "); } else { - rT.error ='Error: could not determine target_bg'; - return rT; + process.stderr.write("Basal unchanged: "+basal+"; "); } } - - + + // adjust min, max, and target BG for sensitivity, such that 50% increase in ISF raises target from 100 to 120 + if (profile.temptargetSet) { + //process.stderr.write("Temp Target set, not adjusting with autosens; "); + } else if (typeof autosens_data !== 'undefined' ) { + if ( profile.sensitivity_raises_target && autosens_data.ratio < 1 || profile.resistance_lowers_target && autosens_data.ratio > 1 ) { + // 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; + // don't allow target_bg below 80 + new_target_bg = Math.max(80, new_target_bg); + if (target_bg == new_target_bg) { + process.stderr.write("target_bg unchanged: "+new_target_bg+"; "); + } else { + process.stderr.write("target_bg from "+target_bg+" to "+new_target_bg+"; "); + } + target_bg = new_target_bg; + } + } + if (typeof iob_data === 'undefined' ) { - rT.error ='Error: iob_data undefined'; + rT.error ='Error: iob_data undefined. '; return rT; } - - if (typeof iob_data.activity === 'undefined' || typeof iob_data.iob === 'undefined' || typeof iob_data.activity === 'undefined') { - rT.error ='Error: iob_data missing some property'; + + var iobArray = iob_data; + if (typeof(iob_data.length) && iob_data.length > 1) { + iob_data = iobArray[0]; + //console.error(JSON.stringify(iob_data[0])); + } + + if (typeof iob_data.activity === 'undefined' || typeof iob_data.iob === 'undefined' ) { + rT.error ='Error: iob_data missing some property. '; return rT; } - + var tick; - - if (glucose_status.delta >= 0) { - tick = "+" + glucose_status.delta; - } else { - tick = glucose_status.delta; + + if (glucose_status.delta > -0.5) { + tick = "+" + round(glucose_status.delta,0); + } else { + tick = round(glucose_status.delta,0); + } + //var minDelta = Math.min(glucose_status.delta, glucose_status.short_avgdelta, glucose_status.long_avgdelta); + var minDelta = Math.min(glucose_status.delta, glucose_status.short_avgdelta); + var minAvgDelta = Math.min(glucose_status.short_avgdelta, glucose_status.long_avgdelta); + var maxDelta = Math.max(glucose_status.delta, glucose_status.short_avgdelta, glucose_status.long_avgdelta); + + var profile_sens = round(profile.sens,1) + var sens = profile.sens; + if (typeof autosens_data !== 'undefined' ) { + sens = profile.sens / sensitivityRatio; + sens = round(sens, 1); + if (sens != profile_sens) { + process.stderr.write("ISF from "+profile_sens+" to "+sens); + } else { + process.stderr.write("ISF unchanged: "+sens); + } + //process.stderr.write(" (autosens ratio "+sensitivityRatio+")"); + } + console.error("; CR:",profile.carb_ratio); + + // compare currenttemp to iob_data.lastTemp and cancel temp if they don't match + var lastTempAge; + if (typeof iob_data.lastTemp !== 'undefined' ) { + lastTempAge = round(( new Date().getTime() - iob_data.lastTemp.date ) / 60000); // in minutes + } else { + lastTempAge = 0; + } + //console.error("currenttemp:",currenttemp,"lastTemp:",JSON.stringify(iob_data.lastTemp),"lastTempAge:",lastTempAge,"m"); + tempModulus = (lastTempAge + currenttemp.duration) % 30; + console.error("currenttemp:",currenttemp,"lastTempAge:",lastTempAge,"m","tempModulus:",tempModulus,"m"); + rT.temp = 'absolute'; + rT.deliverAt = deliverAt; + if ( microBolusAllowed && currenttemp && iob_data.lastTemp && currenttemp.rate != iob_data.lastTemp.rate && lastTempAge > 10 && currenttemp.duration ) { + rT.reason = "Warning: currenttemp rate "+currenttemp.rate+" != lastTemp rate "+iob_data.lastTemp.rate+" from pumphistory; canceling temp"; + return tempBasalFunctions.setTempBasal(0, 0, profile, rT, currenttemp); + } + if ( currenttemp && iob_data.lastTemp && currenttemp.duration > 0 ) { + // TODO: fix this (lastTemp.duration is how long it has run; currenttemp.duration is time left + //if ( currenttemp.duration < iob_data.lastTemp.duration - 2) { + //rT.reason = "Warning: currenttemp duration "+currenttemp.duration+" << lastTemp duration "+round(iob_data.lastTemp.duration,1)+" from pumphistory; setting neutral temp of "+basal+"."; + //return tempBasalFunctions.setTempBasal(basal, 30, profile, rT, currenttemp); + //} + //console.error(lastTempAge, round(iob_data.lastTemp.duration,1), round(lastTempAge - iob_data.lastTemp.duration,1)); + var lastTempEnded = lastTempAge - iob_data.lastTemp.duration + if ( lastTempEnded > 5 && lastTempAge > 10 ) { + rT.reason = "Warning: currenttemp running but lastTemp from pumphistory ended "+lastTempEnded+"m ago; canceling temp"; + //console.error(currenttemp, round(iob_data.lastTemp,1), round(lastTempAge,1)); + return tempBasalFunctions.setTempBasal(0, 0, profile, rT, currenttemp); + } + // TODO: figure out a way to do this check that doesn't fail across basal schedule boundaries + //if ( tempModulus < 25 && tempModulus > 5 ) { + //rT.reason = "Warning: currenttemp duration "+currenttemp.duration+" + lastTempAge "+lastTempAge+" isn't a multiple of 30m; setting neutral temp of "+basal+"."; + //console.error(rT.reason); + //return tempBasalFunctions.setTempBasal(basal, 30, profile, rT, currenttemp); + //} } - var minDelta = Math.min(glucose_status.delta, glucose_status.avgdelta); - //var maxDelta = Math.max(glucose_status.delta, glucose_status.avgdelta); - //calculate BG impact: the amount BG "should" be rising or falling based on insulin activity alone - var bgi = Math.round(( -iob_data.activity * profile.sens * 5 )*100)/100; - // project deviation over next 15 minutes - var deviation = Math.round( 15 / 5 * ( glucose_status.avgdelta - bgi ) ); - //console.log("Avg.Delta: " + glucose_status.avgdelta.toFixed(1) + ", BGI: " + bgi.toFixed(1) + " 15m activity projection: " + deviation.toFixed(0)); - + var bgi = round(( -iob_data.activity * sens * 5 ), 2); + // project deviations for 30 minutes + var deviation = round( 30 / 5 * ( minDelta - bgi ) ); + // don't overreact to a big negative delta: use minAvgDelta if deviation is negative + if (deviation < 0) { + deviation = round( (30 / 5) * ( minAvgDelta - bgi ) ); + // and if deviation is still negative, use long_avgdelta + if (deviation < 0) { + deviation = round( (30 / 5) * ( glucose_status.long_avgdelta - bgi ) ); + } + } + // calculate the naive (bolus calculator math) eventual BG based on net IOB and sensitivity - var naive_eventualBG = Math.round( bg - (iob_data.iob * profile.sens) ); + 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) ) ); + } // and adjust it for the deviation above var eventualBG = naive_eventualBG + deviation; - // calculate what portion of that is due to bolusiob - var bolusContrib = iob_data.bolusiob * profile.sens; + // calculate what portion of that is due to bolussnooze + //var bolusContrib = iob_data.bolussnooze * sens; // and add it back in to get snoozeBG, plus another 50% to avoid low-temping at mealtime - var naive_snoozeBG = Math.round( naive_eventualBG + 1.5 * bolusContrib ); + //var naive_snoozeBG = round( naive_eventualBG + 1.5 * bolusContrib ); // adjust that for deviation like we did eventualBG - var snoozeBG = naive_snoozeBG + deviation; - - //console.log("BG: " + bg +"(" + tick + ","+glucose_status.avgdelta.toFixed(1)+")"+ " -> " + eventualBG + "-" + snoozeBG + " (Unadjusted: " + naive_eventualBG + "-" + naive_snoozeBG + "), BGI: " + bgi); + //var snoozeBG = naive_snoozeBG + deviation; - var expectedDelta = Math.round(( bgi + ( target_bg - eventualBG ) / ( profile.dia * 60 / 5 ) )*10)/10; - //console.log("expectedDelta: " + expectedDelta); + // raise target for noisy / raw CGM data + if (glucose_status.noise >= 2) { + // increase target at least 10% (default 30%) for raw / noisy data + var noisyCGMTargetMultiplier = Math.max( 1.1, profile.noisyCGMTargetMultiplier ); + // don't allow maxRaw above 250 + var maxRaw = Math.min( 250, profile.maxRaw ); + var adjustedMinBG = round(Math.min(200, min_bg * noisyCGMTargetMultiplier )); + var adjustedTargetBG = round(Math.min(200, target_bg * noisyCGMTargetMultiplier )); + var adjustedMaxBG = round(Math.min(200, max_bg * noisyCGMTargetMultiplier )); + process.stderr.write("Raising target_bg for noisy / raw CGM data, from "+target_bg+" to "+adjustedTargetBG+"; "); + min_bg = adjustedMinBG; + target_bg = adjustedTargetBG; + max_bg = adjustedMaxBG; + // 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); + // 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) { + process.stderr.write("Adjusting targets for high BG: min_bg from "+min_bg+" to "+adjustedMinBG+"; "); + min_bg = adjustedMinBG; + } else { + process.stderr.write("min_bg unchanged: "+min_bg+"; "); + } + // if eventualBG, naive_eventualBG, and target_bg aren't all above adjustedTargetBG, don’t use it + if (eventualBG > adjustedTargetBG && naive_eventualBG > adjustedTargetBG && target_bg > adjustedTargetBG) { + process.stderr.write("target_bg from "+target_bg+" to "+adjustedTargetBG+"; "); + target_bg = adjustedTargetBG; + } else { + process.stderr.write("target_bg unchanged: "+target_bg+"; "); + } + // if eventualBG, naive_eventualBG, and max_bg aren't all above adjustedMaxBG, don’t use it + if (eventualBG > adjustedMaxBG && naive_eventualBG > adjustedMaxBG && max_bg > adjustedMaxBG) { + console.error("max_bg from "+max_bg+" to "+adjustedMaxBG); + max_bg = adjustedMaxBG; + } else { + console.error("max_bg unchanged: "+max_bg); + } + } - if (typeof eventualBG === 'undefined' || isNaN(eventualBG)) { - rT.error ='Error: could not calculate eventualBG'; + var expectedDelta = calculate_expected_delta(target_bg, eventualBG, bgi); + if (typeof eventualBG === 'undefined' || isNaN(eventualBG)) { + rT.error ='Error: could not calculate eventualBG. '; return rT; } - - // min_bg of 90 -> threshold of 70, 110 -> 80, and 130 -> 90 - var threshold = profile.min_bg - 0.5*(profile.min_bg-50); - + + // min_bg of 90 -> threshold of 65, 100 -> 70 110 -> 75, and 130 -> 85 + var threshold = min_bg - 0.5*(min_bg-40); + + //console.error(reservoir_data); + rT = { 'temp': 'absolute' , 'bg': bg , 'tick': tick , 'eventualBG': eventualBG - , 'snoozeBG': snoozeBG + //, 'snoozeBG': snoozeBG + , 'insulinReq': 0 + , 'reservoir' : reservoir_data // The expected reservoir volume at which to deliver the microbolus (the reservoir volume from right before the last pumphistory run) + , 'deliverAt' : deliverAt // The time at which the microbolus should be delivered + , 'sensitivityRatio' : sensitivityRatio // autosens ratio (fraction of normal basal) }; - if (bg < threshold) { // low glucose suspend mode: BG is < ~80 - rT.reason = "BG " + bg + "<" + threshold; - if ((glucose_status.delta <= 0 && glucose_status.avgdelta <= 0) || (glucose_status.delta < expectedDelta && glucose_status.avgdelta < expectedDelta)) { - // BG is still falling / rising slower than predicted - return setTempBasal(0, 30, profile, rT, offline); - } - if (glucose_status.delta > glucose_status.avgdelta) { - rT.reason += ", delta " + glucose_status.delta + ">0"; + // generate predicted future BGs based on IOB, COB, and current absorption rate + + var COBpredBGs = []; + var aCOBpredBGs = []; + var IOBpredBGs = []; + var UAMpredBGs = []; + var ZTpredBGs = []; + COBpredBGs.push(bg); + aCOBpredBGs.push(bg); + IOBpredBGs.push(bg); + ZTpredBGs.push(bg); + UAMpredBGs.push(bg); + + // enable SMB whenever we have COB or UAM is enabled + // SMB is disabled by default, unless explicitly enabled in preferences.json + var enableSMB=false; + // disable SMB when a high temptarget is set + if (! microBolusAllowed) { + console.error("SMB disabled (!microBolusAllowed)") + } else if (! profile.allowSMB_with_high_temptarget && profile.temptargetSet && target_bg > 100) { + console.error("SMB disabled due to high temptarget of",target_bg); + enableSMB=false; + // enable SMB/UAM (if enabled in preferences) while we have COB + } else if (profile.enableSMB_with_COB === true && meal_data.mealCOB) { + if (meal_data.bwCarbs) { + if (profile.A52_risk_enable) { + console.error("Warning: SMB enabled with Bolus Wizard carbs: be sure to easy bolus 30s before using Bolus Wizard") + enableSMB=true; + } else { + console.error("SMB not enabled for Bolus Wizard COB"); + } } else { - rT.reason += ", avg delta " + glucose_status.avgdelta.toFixed(2) + ">0"; + console.error("SMB enabled for COB of",meal_data.mealCOB); + enableSMB=true; } - if (currenttemp.rate > profile.current_basal) { // if a high-temp is running - rT.reason += ", cancel high temp"; - return setTempBasal(0, 0, profile, rT, offline); // cancel high temp - } else if (currenttemp.duration && eventualBG > profile.max_bg) { // if low-temped and predicted to go high from negative IOB - rT.reason += ", cancel low temp"; - return setTempBasal(0, 0, profile, rT, offline); // cancel low temp + // enable SMB/UAM (if enabled in preferences) for a full 6 hours after any carb entry + // (6 hours is defined in carbWindow in lib/meal/total.js) + } else if (profile.enableSMB_after_carbs === true && meal_data.carbs ) { + if (meal_data.bwCarbs) { + if (profile.A52_risk_enable) { + console.error("Warning: SMB enabled with Bolus Wizard carbs: be sure to easy bolus 30s before using Bolus Wizard") + enableSMB=true; + } else { + console.error("SMB not enabled for Bolus Wizard carbs"); + } + } else { + console.error("SMB enabled for 6h after carb entry"); + enableSMB=true; } - rT.reason += "; no high-temp to cancel"; - return rT; - } - if (eventualBG < profile.min_bg) { // if eventual BG is below target: - rT.reason = "Eventual BG " + eventualBG + "<" + profile.min_bg; - if (minDelta > expectedDelta) { - if (minDelta > 0) { // if 5m or 15m avg BG is rising faster than expected delta - if (glucose_status.delta > glucose_status.avgdelta) { - rT.reason += ", but Delta " + tick + " > Exp. Delta " + expectedDelta; - } else { - rT.reason += ", but Avg. Delta " + glucose_status.avgdelta.toFixed(2) + " > Exp. Delta " + expectedDelta; - } - if (currenttemp.duration > 0) { // if there is currently any temp basal running - rT.reason = rT.reason += "; cancel"; - return setTempBasal(0, 0, profile, rT, offline); // cancel temp - } else { - rT.reason = rT.reason += "; no temp to cancel"; - return rT; - } + // enable SMB/UAM (if enabled in preferences) if a low temptarget is set + } else if (profile.enableSMB_with_temptarget === true && (profile.temptargetSet && target_bg < 100)) { + if (meal_data.bwFound) { + if (profile.A52_risk_enable) { + console.error("Warning: SMB enabled within 6h of using Bolus Wizard: be sure to easy bolus 30s before using Bolus Wizard") + enableSMB=true; + } else { + console.error("enableSMB_with_temptarget not supported within 6h of using Bolus Wizard"); } + } else { + console.error("SMB enabled for temptarget of",convert_bg(target_bg, profile)); + enableSMB=true; } - - // if this is just due to boluses, we can snooze until the bolus IOB decays (at double speed) - if (snoozeBG > profile.min_bg) { // if adding back in the bolus contribution BG would be above min - // if BG is falling and high-temped, or rising and low-temped, cancel - // compare against zero here, not BGI, because BGI will be highly negative from boluses and no carbs - if (glucose_status.delta < 0 && currenttemp.duration > 0 && currenttemp.rate > profile.current_basal) { - rT.reason += tick + ", and temp " + currenttemp.rate + " > basal " + profile.current_basal; - return setTempBasal(0, 0, profile, rT, offline); // cancel temp - } else if (glucose_status.delta > 0 && currenttemp.duration > 0 && currenttemp.rate < profile.current_basal) { - rT.reason += tick + ", and temp " + currenttemp.rate + " < basal " + profile.current_basal; - return setTempBasal(0, 0, profile, rT, offline); // cancel temp + // enable SMB/UAM if always-on (unless previously disabled for high temptarget) + } else if (profile.enableSMB_always === true) { + if (meal_data.bwFound) { + if (profile.A52_risk_enable === true) { + console.error("Warning: SMB enabled within 6h of using Bolus Wizard: be sure to easy bolus 30s before using Bolus Wizard") + enableSMB=true; + } else { + console.error("enableSMB_always not supported within 6h of using Bolus Wizard"); } - - rT.reason += "bolus snooze: eventual BG range " + eventualBG + "-" + snoozeBG; - return rT; } else { - // calculate 30m low-temp required to get projected BG up to target - // use snoozeBG instead of eventualBG to more gradually ramp in any counteraction of the user's boluses - var insulinReq = Math.min(0, (snoozeBG - target_bg) / profile.sens); - if (minDelta < 0 && minDelta > expectedDelta) { - // if we're barely falling, newinsulinReq should be barely negative - var newinsulinReq = Math.round(( insulinReq * (minDelta / expectedDelta) ) * 100)/100; - //console.log("Increasing insulinReq from " + insulinReq + " to " + newinsulinReq); - insulinReq = newinsulinReq; + console.error("SMB enabled due to enableSMB_always"); + enableSMB=true; + } + } else { + console.error("SMB disabled (no enableSMB preferences active)"); + } + // enable UAM (if enabled in preferences) + var enableUAM=(profile.enableUAM); + + + //console.error(meal_data); + // carb impact and duration are 0 unless changed below + var ci = 0; + var cid = 0; + // 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); + // 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 + var csf = profile.sens / profile.carb_ratio; + } 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; + } + 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) + if (ci > maxCI) { + console.error("Limiting carb impact from",ci,"to",maxCI,"mg/dL/5m (",maxCarbAbsorptionRate,"g/h )"); + ci = maxCI; + } + // set meal_carbimpact high enough to absorb all meal carbs over 6 hours + // total_impact (mg/dL) = CSF (mg/dL/g) * carbs (g) + //console.error(csf * meal_data.carbs); + // meal_carbimpact (mg/dL/5m) = CSF (mg/dL/g) * carbs (g) / 6 (h) * (1h/60m) * 5 (m/5m) * 2 (for linear decay) + //var meal_carbimpact = round((csf * meal_data.carbs / 6 / 60 * 5 * 2),1) + var remainingCATimeMin = 3; // h; before carb absorption starts + // adjust remainingCATime (instead of CR) for autosens + remainingCATimeMin = remainingCATimeMin / sensitivityRatio; + // 20 g/h means that anything <= 60g will get a remainingCATimeMin, 80g will get 4h, and 120g 6h + // when actual absorption ramps up it will take over from remainingCATime + var assumedCarbAbsorptionRate = 20; // g/h; maximum rate to assume carbs will absorb if no CI observed + var remainingCATime = remainingCATimeMin; + if (meal_data.carbs) { + // if carbs * assumedCarbAbsorptionRate > remainingCATimeMin, raise it + // so <= 90g is assumed to take 3h, and 120g=4h + remainingCATimeMin = Math.max(remainingCATimeMin, meal_data.mealCOB/assumedCarbAbsorptionRate); + var lastCarbAge = round(( new Date().getTime() - meal_data.lastCarbTime ) / 60000); + //console.error(meal_data.lastCarbTime, lastCarbAge); + + 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) + console.error("Last carbs",lastCarbAge,"minutes ago; remainingCATime:",remainingCATime,"hours;",round(fractionCOBAbsorbed*100)+"% carbs absorbed"); + } + + // calculate the number of carbs absorbed over remainingCATime hours at current CI + // CI (mg/dL/5m) * (5m)/5 (m) * 60 (min/hr) * 4 (h) / 2 (linear decay factor) = total carb impact (mg/dL) + var totalCI = Math.max(0, ci / 5 * 60 * remainingCATime / 2); + // totalCI (mg/dL) / CSF (mg/dL/g) = total carbs absorbed (g) + var totalCA = totalCI / csf; + var remainingCarbsCap = 90; // default to 90 + var remainingCarbsFraction = 1; + if (profile.remainingCarbsCap) { remainingCarbsCap = Math.min(90,profile.remainingCarbsCap); } + if (profile.remainingCarbsFraction) { remainingCarbsFraction = Math.min(1,profile.remainingCarbsFraction); } + var remainingCarbsIgnore = 1 - remainingCarbsFraction; + var remainingCarbs = Math.max(0, meal_data.mealCOB - totalCA - meal_data.carbs*remainingCarbsIgnore); + remainingCarbs = Math.min(remainingCarbsCap,remainingCarbs); + // assume remainingCarbs will absorb in a /\ shaped bilinear curve + // peaking at remainingCATime / 2 and ending at remainingCATime hours + // area of the /\ triangle is the same as a remainingCIpeak-height rectangle out to remainingCATime/2 + // remainingCIpeak (mg/dL/5m) = remainingCarbs (g) * CSF (mg/dL/g) * 5 (m/5m) * 1h/60m / (remainingCATime/2) (h) + var remainingCIpeak = remainingCarbs * csf * 5 / 60 / (remainingCATime/2); + //console.error(profile.min_5m_carbimpact,ci,totalCI,totalCA,remainingCarbs,remainingCI,remainingCATime); + //if (meal_data.mealCOB * 3 > meal_data.carbs) { } + + // calculate peak deviation in last hour, and slope from that to current deviation + var slopeFromMaxDeviation = round(meal_data.slopeFromMaxDeviation,2); + // calculate lowest deviation in last hour, and slope from that to current deviation + var slopeFromMinDeviation = round(meal_data.slopeFromMinDeviation,2); + // assume deviations will drop back down at least at 1/3 the rate they ramped up + var slopeFromDeviations = Math.min(slopeFromMaxDeviation,-slopeFromMinDeviation/3); + //console.error(slopeFromMaxDeviation); + + 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 + if (ci == 0) { + // avoid divide by zero + cid = 0; + } 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 ); + // 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"); + var minIOBPredBG = 999; + var minCOBPredBG = 999; + var minUAMPredBG = 999; + var minGuardBG = bg; + var minCOBGuardBG = 999; + var minUAMGuardBG = 999; + var minIOBGuardBG = 999; + var minZTGuardBG = 999; + var minPredBG; + var avgPredBG; + var IOBpredBG = eventualBG; + var maxIOBPredBG = bg; + var maxCOBPredBG = bg; + var maxUAMPredBG = bg; + //var maxPredBG = bg; + var eventualPredBG = bg; + var lastIOBpredBG; + var lastCOBpredBG; + var lastUAMpredBG; + var lastZTpredBG; + var UAMduration = 0; + var remainingCItotal = 0; + var remainingCIs = []; + var predCIs = []; + try { + iobArray.forEach(function(iobTick) { + //console.error(iobTick); + predBGI = round(( -iobTick.activity * sens * 5 ), 2); + 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)) ); + IOBpredBG = IOBpredBGs[IOBpredBGs.length-1] + predBGI + predDev; + // calculate predBGs with long zero temp without deviations + 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) ) ); + // 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) + var intervals = Math.min( COBpredBGs.length, (remainingCATime*12)-COBpredBGs.length ); + var remainingCI = Math.max(0, intervals / (remainingCATime/2*12) * remainingCIpeak ); + remainingCItotal += predCI+remainingCI; + 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; + // for UAMpredBGs, predicted carb impact drops at slopeFromDeviations + // calculate predicted CI from UAM based on slopeFromDeviations + 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) ) ); + //console.error(predUCIslope, predUCImax); + // predicted CI from UAM is the lesser of CI based on deviationSlope or DIA + predUCI = Math.min(predUCIslope, predUCImax); + if(predUCI>0) { + //console.error(UAMpredBGs.length,slopeFromDeviations, predUCI); + UAMduration=round((UAMpredBGs.length+1)*5/60,1); } - // rate required to deliver insulinReq less insulin over 30m: - var rate = profile.current_basal + (2 * insulinReq); - rate = Math.round( rate * 1000 ) / 1000; - // if required temp < existing temp basal - if (typeof currenttemp.rate !== 'undefined' && (currenttemp.duration > 0 && rate > currenttemp.rate - 0.1)) { - rT.reason += ", temp " + currenttemp.rate + " <~ req " + rate + "U/hr"; - return rT; - } else { - rT.reason += ", no temp, setting " + rate + "U/hr"; - return setTempBasal(rate, 30, profile, rT, offline); + 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); } + if ( COBpredBGs.length < 48) { COBpredBGs.push(COBpredBG); } + if ( aCOBpredBGs.length < 48) { aCOBpredBGs.push(aCOBpredBG); } + if ( UAMpredBGs.length < 48) { UAMpredBGs.push(UAMpredBG); } + if ( ZTpredBGs.length < 48) { ZTpredBGs.push(ZTpredBG); } + // calculate minGuardBGs without a wait from COB, UAM, IOB predBGs + if ( COBpredBG < minCOBGuardBG ) { minCOBGuardBG = round(COBpredBG); } + if ( UAMpredBG < minUAMGuardBG ) { minUAMGuardBG = round(UAMpredBG); } + if ( IOBpredBG < minIOBGuardBG ) { minIOBGuardBG = round(IOBpredBG); } + if ( ZTpredBG < minZTGuardBG ) { minZTGuardBG = round(ZTpredBG); } + + // set minPredBGs starting when currently-dosed insulin activity will peak + // look ahead 60m (regardless of insulin type) so as to be less aggressive on slower insulins + var insulinPeakTime = 60; + // add 30m to allow for insluin delivery (SMBs or temps) + insulinPeakTime = 90; + var insulinPeak5m = (insulinPeakTime/60)*12; + //console.error(insulinPeakTime, insulinPeak5m, profile.insulinPeakTime, profile.curve); + + // wait 90m before setting minIOBPredBG + if ( IOBpredBGs.length > insulinPeak5m && (IOBpredBG < minIOBPredBG) ) { minIOBPredBG = round(IOBpredBG); } + if ( IOBpredBG > maxIOBPredBG ) { maxIOBPredBG = IOBpredBG; } + // wait 85-105m before setting COB and 60m for UAM minPredBGs + if ( (cid || remainingCIpeak > 0) && COBpredBGs.length > insulinPeak5m && (COBpredBG < minCOBPredBG) ) { minCOBPredBG = round(COBpredBG); } + if ( (cid || remainingCIpeak > 0) && COBpredBG > maxIOBPredBG ) { maxCOBPredBG = COBpredBG; } + if ( enableUAM && UAMpredBGs.length > 12 && (UAMpredBG < minUAMPredBG) ) { minUAMPredBG = round(UAMpredBG); } + if ( enableUAM && UAMpredBG > maxIOBPredBG ) { maxUAMPredBG = UAMpredBG; } + }); + // set eventualBG to include effect of carbs + //console.error("PredBGs:",JSON.stringify(predBGs)); + } catch (e) { + console.error("Problem with iobArray. Optional feature Advanced Meal Assist disabled:",e); + } + if (meal_data.mealCOB) { + console.error("predCIs (mg/dL/5m):",predCIs.join(" ")); + console.error("remainingCIs: ",remainingCIs.join(" ")); + } + //,"totalCA:",round(totalCA,2),"remainingCItotal/csf+totalCA:",round(remainingCItotal/csf+totalCA,2)); + rT.predBGs = {}; + IOBpredBGs.forEach(function(p, i, theArray) { + theArray[i] = round(Math.min(401,Math.max(39,p))); + }); + for (var i=IOBpredBGs.length-1; i > 12; i--) { + if (IOBpredBGs[i-1] != IOBpredBGs[i]) { break; } + else { IOBpredBGs.pop(); } + } + rT.predBGs.IOB = IOBpredBGs; + lastIOBpredBG=round(IOBpredBGs[IOBpredBGs.length-1]); + ZTpredBGs.forEach(function(p, i, theArray) { + theArray[i] = round(Math.min(401,Math.max(39,p))); + }); + for (var i=ZTpredBGs.length-1; i > 6; i--) { + //if (ZTpredBGs[i-1] != ZTpredBGs[i]) { break; } + // stop displaying ZTpredBGs once they're rising and above target + if (ZTpredBGs[i-1] >= ZTpredBGs[i] || ZTpredBGs[i] <= target_bg) { break; } + else { ZTpredBGs.pop(); } + } + rT.predBGs.ZT = ZTpredBGs; + lastZTpredBG=round(ZTpredBGs[ZTpredBGs.length-1]); + if (meal_data.mealCOB > 0) { + aCOBpredBGs.forEach(function(p, i, theArray) { + theArray[i] = round(Math.min(401,Math.max(39,p))); + }); + for (var i=aCOBpredBGs.length-1; i > 12; i--) { + if (aCOBpredBGs[i-1] != aCOBpredBGs[i]) { break; } + else { aCOBpredBGs.pop(); } + } + // disable for now. may want to add a preference to re-enable + //rT.predBGs.aCOB = aCOBpredBGs; + } + if (meal_data.mealCOB > 0 && ( ci > 0 || remainingCIpeak > 0 )) { + COBpredBGs.forEach(function(p, i, theArray) { + theArray[i] = round(Math.min(401,Math.max(39,p))); + }); + for (var i=COBpredBGs.length-1; i > 12; i--) { + if (COBpredBGs[i-1] != COBpredBGs[i]) { break; } + else { COBpredBGs.pop(); } + } + rT.predBGs.COB = COBpredBGs; + lastCOBpredBG=round(COBpredBGs[COBpredBGs.length-1]); + eventualBG = Math.max(eventualBG, round(COBpredBGs[COBpredBGs.length-1]) ); + } + if (ci > 0 || remainingCIpeak > 0) { + if (enableUAM) { + UAMpredBGs.forEach(function(p, i, theArray) { + theArray[i] = round(Math.min(401,Math.max(39,p))); + }); + for (var i=UAMpredBGs.length-1; i > 12; i--) { + if (UAMpredBGs[i-1] != UAMpredBGs[i]) { break; } + else { UAMpredBGs.pop(); } + } + rT.predBGs.UAM = UAMpredBGs; + lastUAMpredBG=round(UAMpredBGs[UAMpredBGs.length-1]); + if (UAMpredBGs[UAMpredBGs.length-1]) { + eventualBG = Math.max(eventualBG, round(UAMpredBGs[UAMpredBGs.length-1]) ); } } + + // set eventualBG and snoozeBG based on COB or UAM predBGs + rT.eventualBG = eventualBG; } - - // if eventual BG is above min but BG is falling faster than expected Delta - if (minDelta < expectedDelta) { - if (glucose_status.delta < glucose_status.avgdelta) { - rT.reason = "Eventual BG " + eventualBG + ">" + profile.min_bg + " but Delta " + tick + " < Exp. Delta " + expectedDelta; + + console.error("UAM Impact:",uci,"mg/dL per 5m; UAM Duration:",UAMduration,"hours"); + + + minIOBPredBG = Math.max(39,minIOBPredBG); + minCOBPredBG = Math.max(39,minCOBPredBG); + minUAMPredBG = Math.max(39,minUAMPredBG); + minPredBG = round(minIOBPredBG); + + var fractionCarbsLeft = meal_data.mealCOB/meal_data.carbs; + // if we have COB and UAM is enabled, average both + if ( minUAMPredBG < 999 && minCOBPredBG < 999 ) { + // weight COBpredBG vs. UAMpredBG based on how many carbs remain as COB + avgPredBG = round( (1-fractionCarbsLeft)*UAMpredBG + fractionCarbsLeft*COBpredBG ); + // if UAM is disabled, average IOB and COB + } else if ( minCOBPredBG < 999 ) { + avgPredBG = round( (IOBpredBG + COBpredBG)/2 ); + // if we have UAM but no COB, average IOB and UAM + } else if ( minUAMPredBG < 999 ) { + avgPredBG = round( (IOBpredBG + UAMpredBG)/2 ); + } else { + avgPredBG = round( IOBpredBG ); + } + // if avgPredBG is below minZTGuardBG, bring it up to that level + if ( minZTGuardBG > avgPredBG ) { + avgPredBG = minZTGuardBG; + } + + // if we have both minCOBGuardBG and minUAMGuardBG, blend according to fractionCarbsLeft + if ( (cid || remainingCIpeak > 0) ) { + if ( enableUAM ) { + minGuardBG = fractionCarbsLeft*minCOBGuardBG + (1-fractionCarbsLeft)*minUAMGuardBG; } else { - rT.reason = "Eventual BG " + eventualBG + ">" + profile.min_bg + " but Avg. Delta " + glucose_status.avgdelta.toFixed(2) + " < Exp. Delta " + expectedDelta; + minGuardBG = minCOBGuardBG; } - if (currenttemp.duration > 0) { // if there is currently any temp basal running - rT.reason = rT.reason += "; cancel"; - return setTempBasal(0, 0, profile, rT, offline); // cancel temp + } else if ( enableUAM ) { + minGuardBG = minUAMGuardBG; + } else { + minGuardBG = minIOBGuardBG; + } + minGuardBG = round(minGuardBG); + //console.error(minCOBGuardBG, minUAMGuardBG, minIOBGuardBG, minGuardBG); + + var minZTUAMPredBG = minUAMPredBG; + // if minZTGuardBG is below threshold, bring down any super-high minUAMPredBG by averaging + // this helps prevent UAM from giving too much insulin in case absorption falls off suddenly + if ( minZTGuardBG < threshold ) { + minZTUAMPredBG = (minUAMPredBG + minZTGuardBG) / 2; + // if minZTGuardBG is between threshold and target, blend in the averaging + } else if ( minZTGuardBG < target_bg ) { + // target 100, threshold 70, minZTGuardBG 85 gives 50%: (85-70) / (100-70) + var blendPct = (minZTGuardBG-threshold) / (target_bg-threshold); + var blendedMinZTGuardBG = minUAMPredBG*blendPct + minZTGuardBG*(1-blendPct); + minZTUAMPredBG = (minUAMPredBG + blendedMinZTGuardBG) / 2; + //minZTUAMPredBG = minUAMPredBG - target_bg + minZTGuardBG; + // if minUAMPredBG is below minZTGuardBG, bring minUAMPredBG up by averaging + // this allows more insulin if lastUAMPredBG is below target, but minZTGuardBG is still high + } else if ( minZTGuardBG > minUAMPredBG ) { + minZTUAMPredBG = (minUAMPredBG + minZTGuardBG) / 2; + } + minZTUAMPredBG = round(minZTUAMPredBG); + //console.error("minUAMPredBG:",minUAMPredBG,"minZTGuardBG:",minZTGuardBG,"minZTUAMPredBG:",minZTUAMPredBG); + // if any carbs have been entered recently + if (meal_data.carbs) { + // average the minIOBPredBG and minUAMPredBG if available + /* + if ( minUAMPredBG < 999 ) { + avgMinPredBG = round( (minIOBPredBG+minUAMPredBG)/2 ); } else { - rT.reason = rT.reason += "; no temp to cancel"; - return rT; + avgMinPredBG = minIOBPredBG; } + */ + + // if UAM is disabled, use max of minIOBPredBG, minCOBPredBG + if ( ! enableUAM && minCOBPredBG < 999 ) { + minPredBG = round(Math.max(minIOBPredBG, minCOBPredBG)); + // 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)*minUAMPredBG; + 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 + } else { + //minPredBG = minUAMPredBG; + minPredBG = minZTUAMPredBG; + } + // in pure UAM mode, use the higher of minIOBPredBG,minUAMPredBG + } else if ( enableUAM ) { + //minPredBG = round(Math.max(minIOBPredBG,minUAMPredBG)); + minPredBG = round(Math.max(minIOBPredBG,minZTUAMPredBG)); + } + + // make sure minPredBG isn't higher than avgPredBG + minPredBG = Math.min( minPredBG, avgPredBG ); + + process.stderr.write("minPredBG: "+minPredBG+" minIOBPredBG: "+minIOBPredBG+" minZTGuardBG: "+minZTGuardBG); + if (minCOBPredBG < 999) { + process.stderr.write(" minCOBPredBG: "+minCOBPredBG); + } + if (minUAMPredBG < 999) { + process.stderr.write(" minUAMPredBG: "+minUAMPredBG); + } + console.error(" avgPredBG:",avgPredBG,"COB:",meal_data.mealCOB,"/",meal_data.carbs); + // But if the COB line falls off a cliff, don't trust UAM too much: + // use maxCOBPredBG if it's been set and lower than minPredBG + if ( maxCOBPredBG > bg ) { + minPredBG = Math.min(minPredBG, maxCOBPredBG); } - - if (eventualBG < profile.max_bg) { - rT.reason = eventualBG + " is in range. No temp required"; - if (currenttemp.duration > 0) { // if there is currently any temp basal running - rT.reason = rT.reason += "; cancel"; - return setTempBasal(0, 0, profile, rT, offline); // cancel temp + + rT.COB=meal_data.mealCOB; + rT.IOB=iob_data.iob; + rT.reason="COB: " + meal_data.mealCOB + ", Dev: " + convert_bg(deviation, profile) + ", BGI: " + convert_bg(bgi, profile) + ", ISF: " + convert_bg(sens, profile) + ", CR: " + round(profile.carb_ratio, 2) + ", Target: " + convert_bg(target_bg, profile) + ", minPredBG " + convert_bg(minPredBG, profile) + ", minGuardBG " + convert_bg(minGuardBG, profile) + ", IOBpredBG " + convert_bg(lastIOBpredBG, profile); + if (lastCOBpredBG > 0) { + rT.reason += ", COBpredBG " + convert_bg(lastCOBpredBG, profile); + } + if (lastUAMpredBG > 0) { + rT.reason += ", UAMpredBG " + convert_bg(lastUAMpredBG, profile) + } + rT.reason += "; "; + //var bgUndershoot = threshold - Math.min(minGuardBG, Math.max( naive_eventualBG, eventualBG )); + // use naive_eventualBG if above 40, but switch to minGuardBG if both eventualBGs hit floor of 39 + //var carbsReqBG = Math.max( naive_eventualBG, eventualBG ); + var carbsReqBG = naive_eventualBG; + if ( carbsReqBG < 40 ) { + carbsReqBG = Math.min( minGuardBG, carbsReqBG ); + } + var bgUndershoot = threshold - carbsReqBG; + // calculate how long until COB (or IOB) predBGs drop below min_bg + var minutesAboveMinBG = 240; + var minutesAboveThreshold = 240; + if (meal_data.mealCOB > 0 && ( ci > 0 || remainingCIpeak > 0 )) { + for (var i=0; i" + profile.max_bg + ", "; - if (basal_iob > max_iob) { - rT.reason = "basal_iob " + basal_iob + " > max_iob " + max_iob; - return setTempBasal(0, 0, profile, rT, offline); - } else { // otherwise, calculate 30m high-temp required to get projected BG down to target - - // insulinReq is the additional insulin required to get down to max bg: - var insulinReq = (eventualBG - target_bg) / profile.sens; + if (enableSMB && minGuardBG < threshold) { + console.error("minGuardBG",convert_bg(minGuardBG, profile),"projected below", convert_bg(threshold, profile) ,"- disabling SMB"); + //rT.reason += "minGuardBG "+minGuardBG+"<"+threshold+": SMB disabled; "; + enableSMB = false; + } + if ( maxDelta > 0.20 * bg ) { + console.error("maxDelta",convert_bg(maxDelta, profile),"> 20% of BG",convert_bg(bg, profile),"- disabling SMB"); + rT.reason += "maxDelta "+convert_bg(maxDelta, profile)+" > 20% of BG "+convert_bg(bg, profile)+": SMB disabled; "; + enableSMB = false; + } + + console.error("BG projected to remain above",convert_bg(min_bg, profile),"for",minutesAboveMinBG,"minutes"); + if ( minutesAboveThreshold < 240 || minutesAboveMinBG < 60 ) { + console.error("BG projected to remain above",convert_bg(threshold,profile),"for",minutesAboveThreshold,"minutes"); + } + // include at least minutesAboveMinBG worth of zero temps in calculating carbsReq + // always include at least 30m worth of zero temp (carbs to 80, low temp up to target) + //var zeroTempDuration = Math.max(30,minutesAboveMinBG); + var zeroTempDuration = minutesAboveThreshold; + // BG undershoot, minus effect of zero temps until hitting min_bg, converted to grams, minus COB + var zeroTempEffect = profile.current_basal*sens*zeroTempDuration/60; + // don't count the last 25% of COB against carbsReq + var COBforCarbsReq = Math.max(0, meal_data.mealCOB - 0.25*meal_data.carbs); + var carbsReq = (bgUndershoot - zeroTempEffect) / csf - COBforCarbsReq; + zeroTempEffect = round(zeroTempEffect); + carbsReq = round(carbsReq); + console.error("naive_eventualBG:",naive_eventualBG,"bgUndershoot:",bgUndershoot,"zeroTempDuration:",zeroTempDuration,"zeroTempEffect:",zeroTempEffect,"carbsReq:",carbsReq); + if ( carbsReq >= profile.carbsReqThreshold && minutesAboveThreshold <= 45 ) { + rT.carbsReq = carbsReq; + rT.reason += carbsReq + " add'l carbs req w/in " + minutesAboveThreshold + "m; "; + } + // don't low glucose suspend if IOB is already super negative and BG is rising faster than predicted + if (bg < threshold && iob_data.iob < -profile.current_basal*20/60 && minDelta > 0 && minDelta > expectedDelta) { + rT.reason += "IOB "+iob_data.iob+" < " + round(-profile.current_basal*20/60,2); + rT.reason += " and minDelta " + convert_bg(minDelta, profile) + " > " + "expectedDelta " + convert_bg(expectedDelta, profile) + "; "; + // 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; + var worstCaseInsulinReq = bgUndershoot / sens; + var durationReq = round(60*worstCaseInsulinReq / profile.current_basal); + durationReq = round(durationReq/30)*30; + // always set a 30-120m zero temp (oref0-pump-loop will let any longer SMB zero temp run) + durationReq = Math.min(120,Math.max(30,durationReq)); + return tempBasalFunctions.setTempBasal(0, durationReq, profile, rT, currenttemp); + } + + // if not in LGS mode, cancel temps before the top of the hour to reduce beeping/vibration + console.error(profile.skip_neutral_temps, rT.deliverAt.getMinutes()); + if ( profile.skip_neutral_temps && rT.deliverAt.getMinutes() >= 55 ) { + rT.reason += "; Canceling temp at " + rT.deliverAt.getMinutes() + "m past the hour. "; + return tempBasalFunctions.setTempBasal(0, 0, profile, rT, currenttemp); + } + + if (eventualBG < min_bg) { // if eventual BG is below target: + rT.reason += "Eventual BG " + convert_bg(eventualBG, profile) + " < " + convert_bg(min_bg, profile); + // if 5m or 30m avg BG is rising faster than expected delta + if ( minDelta > expectedDelta && minDelta > 0 && !carbsReq ) { + // if naive_eventualBG < 40, set a 30m zero temp (oref0-pump-loop will let any longer SMB zero temp run) + if (naive_eventualBG < 40) { + rT.reason += ", naive_eventualBG < 40. "; + return tempBasalFunctions.setTempBasal(0, 30, profile, rT, currenttemp); + } + if (glucose_status.delta > minDelta) { + rT.reason += ", but Delta " + convert_bg(tick, profile) + " > expectedDelta " + convert_bg(expectedDelta, profile); + } else { + rT.reason += ", but Min. Delta " + minDelta.toFixed(2) + " > Exp. Delta " + convert_bg(expectedDelta, profile); + } + if (currenttemp.duration > 15 && (round_basal(basal, profile) === round_basal(currenttemp.rate, profile))) { + rT.reason += ", temp " + currenttemp.rate + " ~ req " + basal + "U/hr. "; + return rT; + } else { + rT.reason += "; setting current basal of " + basal + " as temp. "; + return tempBasalFunctions.setTempBasal(basal, 30, profile, rT, currenttemp); + } + } + + // calculate 30m low-temp required to get projected BG up to target + // use snoozeBG to more gradually ramp in any counteraction of the user's boluses + // multiply by 2 to low-temp faster for increased hypo safety + //var insulinReq = 2 * Math.min(0, (snoozeBG - target_bg) / sens); + var insulinReq = 2 * Math.min(0, (eventualBG - target_bg) / sens); + insulinReq = round( insulinReq , 2); + // calculate naiveInsulinReq based on naive_eventualBG + var naiveInsulinReq = Math.min(0, (naive_eventualBG - target_bg) / sens); + naiveInsulinReq = round( naiveInsulinReq , 2); if (minDelta < 0 && minDelta > expectedDelta) { - var newinsulinReq = Math.round(( insulinReq * (1 - (minDelta / expectedDelta)) ) * 100)/100; - //console.log("Reducing insulinReq from " + insulinReq + " to " + newinsulinReq); + // if we're barely falling, newinsulinReq should be barely negative + //rT.reason += ", Snooze BG " + convert_bg(snoozeBG, profile); + var newinsulinReq = round(( insulinReq * (minDelta / expectedDelta) ), 2); + //console.error("Increasing insulinReq from " + insulinReq + " to " + newinsulinReq); insulinReq = newinsulinReq; } + // rate required to deliver insulinReq less insulin over 30m: + var rate = basal + (2 * insulinReq); + rate = round_basal(rate, profile); + + // if required temp < existing temp basal + var insulinScheduled = currenttemp.duration * (currenttemp.rate - basal) / 60; + // if current temp would deliver a lot (30% of basal) less than the required insulin, + // by both normal and naive calculations, then raise the rate + var minInsulinReq = Math.min(insulinReq,naiveInsulinReq); + if (insulinScheduled < minInsulinReq - basal*0.3) { + rT.reason += ", "+currenttemp.duration + "m@" + (currenttemp.rate).toFixed(2) + " is a lot less than needed. "; + return tempBasalFunctions.setTempBasal(rate, 30, profile, rT, currenttemp); + } + if (typeof currenttemp.rate !== 'undefined' && (currenttemp.duration > 5 && rate >= currenttemp.rate * 0.8)) { + rT.reason += ", temp " + currenttemp.rate + " ~< req " + rate + "U/hr. "; + return rT; + } 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); + if (durationReq < 0) { + durationReq = 0; + // don't set a temp longer than 120 minutes + } else { + durationReq = round(durationReq/30)*30; + durationReq = Math.min(120,Math.max(0,durationReq)); + } + //console.error(durationReq); + //rT.reason += "insulinReq " + insulinReq + "; " + if (durationReq > 0) { + rT.reason += ", setting " + durationReq + "m zero temp. "; + return tempBasalFunctions.setTempBasal(rate, durationReq, profile, rT, currenttemp); + } + } else { + rT.reason += ", setting " + rate + "U/hr. "; + } + return tempBasalFunctions.setTempBasal(rate, 30, profile, rT, currenttemp); + } + } + + // if eventual BG is above min but BG is falling faster than expected Delta + if (minDelta < expectedDelta) { + // if in SMB mode, don't cancel SMB zero temp + if (! (microBolusAllowed && enableSMB)) { + if (glucose_status.delta < minDelta) { + rT.reason += "Eventual BG " + convert_bg(eventualBG, profile) + " > " + convert_bg(min_bg, profile) + " but Delta " + convert_bg(tick, profile) + " < Exp. Delta " + convert_bg(expectedDelta, profile); + } else { + rT.reason += "Eventual BG " + convert_bg(eventualBG, profile) + " > " + convert_bg(min_bg, profile) + " but Min. Delta " + minDelta.toFixed(2) + " < Exp. Delta " + convert_bg(expectedDelta, profile); + } + if (currenttemp.duration > 15 && (round_basal(basal, profile) === round_basal(currenttemp.rate, profile))) { + rT.reason += ", temp " + currenttemp.rate + " ~ req " + basal + "U/hr. "; + return rT; + } else { + rT.reason += "; setting current basal of " + basal + " as temp. "; + return tempBasalFunctions.setTempBasal(basal, 30, profile, rT, currenttemp); + } + } + } + // eventualBG or minPredBG is below max_bg + if (Math.min(eventualBG,minPredBG) < max_bg) { + // if in SMB mode, don't cancel SMB zero temp + if (! (microBolusAllowed && enableSMB )) { + rT.reason += convert_bg(eventualBG, profile)+"-"+convert_bg(minPredBG, profile)+" in range: no temp required"; + if (currenttemp.duration > 15 && (round_basal(basal, profile) === round_basal(currenttemp.rate, profile))) { + rT.reason += ", temp " + currenttemp.rate + " ~ req " + basal + "U/hr. "; + return rT; + } else { + rT.reason += "; setting current basal of " + basal + " as temp. "; + return tempBasalFunctions.setTempBasal(basal, 30, profile, rT, currenttemp); + } + } + } + + // eventual BG is at/above target + // if iob is over max, just cancel any temps + // if we're not here because of SMB, eventual BG is at/above target + if (! (microBolusAllowed && rT.COB)) { + rT.reason += "Eventual BG " + convert_bg(eventualBG, profile) + " >= " + convert_bg(max_bg, profile) + ", "; + } + if (iob_data.iob > max_iob) { + rT.reason += "IOB " + round(iob_data.iob,2) + " > max_iob " + max_iob; + if (currenttemp.duration > 15 && (round_basal(basal, profile) === round_basal(currenttemp.rate, profile))) { + rT.reason += ", temp " + currenttemp.rate + " ~ req " + basal + "U/hr. "; + return rT; + } else { + rT.reason += "; setting current basal of " + basal + " as temp. "; + return tempBasalFunctions.setTempBasal(basal, 30, profile, rT, currenttemp); + } + } else { // otherwise, calculate 30m high-temp required to get projected BG down to target + + // 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); + var insulinReq = round( (Math.min(minPredBG,eventualBG) - target_bg) / sens, 2); + // when dropping, but not as fast as expected, reduce insulinReq proportionally + // to the what fraction of expectedDelta we're dropping at + //if (minDelta < 0 && minDelta > expectedDelta) { + //var newinsulinReq = round(( insulinReq * (1 - (minDelta / expectedDelta)) ), 2); + //console.error("Reducing insulinReq from " + insulinReq + " to " + newinsulinReq + " for minDelta " + minDelta + " vs. expectedDelta " + expectedDelta); + //insulinReq = newinsulinReq; + //} // if that would put us over max_iob, then reduce accordingly - if (insulinReq > max_iob-basal_iob) { - rT.reason = "max_iob " + max_iob + ", "; - insulinReq = max_iob-basal_iob; + if (insulinReq > max_iob-iob_data.iob) { + rT.reason += "max_iob " + max_iob + ", "; + insulinReq = max_iob-iob_data.iob; } // rate required to deliver insulinReq more insulin over 30m: - var rate = profile.current_basal + (2 * insulinReq); - rate = Math.round( rate * 1000 ) / 1000; + var rate = basal + (2 * insulinReq); + rate = round_basal(rate, profile); + insulinReq = round(insulinReq,3); + rT.insulinReq = insulinReq; + //console.error(iob_data.lastBolusTime); + // minutes since last bolus + var lastBolusAge = round(( new Date().getTime() - iob_data.lastBolusTime ) / 60000,1); + //console.error(lastBolusAge); + //console.error(profile.temptargetSet, target_bg, rT.COB); + // 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); + if (typeof profile.maxSMBBasalMinutes == 'undefined' ) { + 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 ) { + console.error("IOB",iob_data.iob,"> COB",meal_data.mealCOB+"; mealInsulinReq =",mealInsulinReq); + if (profile.maxUAMSMBBasalMinutes) { + console.error("profile.maxUAMSMBBasalMinutes:",profile.maxUAMSMBBasalMinutes,"profile.current_basal:",profile.current_basal); + maxBolus = round( profile.current_basal * profile.maxUAMSMBBasalMinutes / 60 ,1); + } else { + console.error("profile.maxUAMSMBBasalMinutes undefined: defaulting to 30m"); + maxBolus = round( profile.current_basal * 30 / 60 ,1); + } + } else { + console.error("profile.maxSMBBasalMinutes:",profile.maxSMBBasalMinutes,"profile.current_basal:",profile.current_basal); + maxBolus = round( profile.current_basal * profile.maxSMBBasalMinutes / 60 ,1); + } + // bolus 1/2 the insulinReq, up to maxBolus, rounding down to nearest 0.1U + microBolus = Math.floor(Math.min(insulinReq/2,maxBolus)*10)/10; + // 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); + + // if insulinReq > 0 but not enough for a microBolus, don't set an SMB zero temp + if (insulinReq > 0 && microBolus < 0.1) { + durationReq = 0; + } + + var smbLowTempReq = 0; + if (durationReq <= 0) { + durationReq = 0; + // don't set an SMB zero temp longer than 60 minutes + } else if (durationReq >= 30) { + durationReq = round(durationReq/30)*30; + durationReq = Math.min(60,Math.max(0,durationReq)); + } else { + // if SMB durationReq is less than 30m, set a nonzero low temp + smbLowTempReq = round( basal * durationReq/30 ,2); + durationReq = 30; + } + rT.reason += " insulinReq " + insulinReq; + if (microBolus >= maxBolus) { + rT.reason += "; maxBolus " + maxBolus; + } + if (durationReq > 0) { + rT.reason += "; setting " + durationReq + "m low temp of " + smbLowTempReq + "U/h"; + } + rT.reason += ". "; + + //allow SMBs every 3 minutes + var nextBolusMins = round(3-lastBolusAge,0); + var nextBolusSeconds = round((3 - lastBolusAge) * 60, 0) % 60; + //console.error(naive_eventualBG, insulinReq, worstCaseInsulinReq, durationReq); + console.error("naive_eventualBG",naive_eventualBG+",",durationReq+"m "+smbLowTempReq+"U/h temp needed; last bolus",lastBolusAge+"m ago; maxBolus: "+maxBolus); + if (lastBolusAge > 3) { + if (microBolus > 0) { + rT.units = microBolus; + rT.reason += "Microbolusing " + microBolus + "U. "; + } + } else { + rT.reason += "Waiting " + nextBolusMins + "m " + nextBolusSeconds + "s to microbolus again. "; + } + //rT.reason += ". "; + + // if no zero temp is required, don't return yet; allow later code to set a high temp + if (durationReq > 0) { + rT.rate = smbLowTempReq; + rT.duration = durationReq; + return rT; + } + + // if insulinReq is negative, snoozeBG > target_bg, and lastCOBpredBG > target_bg, set a neutral temp + //if (insulinReq < 0 && snoozeBG > target_bg && lastCOBpredBG > target_bg) { + //rT.reason += "; SMB bolus snooze: setting current basal of " + basal + " as temp. "; + //return tempBasalFunctions.setTempBasal(basal, 30, profile, rT, currenttemp); + //} + } + + var maxSafeBasal = tempBasalFunctions.getMaxSafeBasal(profile); - var maxSafeBasal = Math.min(profile.max_basal, 3 * profile.max_daily_basal, 4 * profile.current_basal); if (rate > maxSafeBasal) { - rT.reason += "adj. req. rate:"+rate.toFixed(1) +" to maxSafeBasal:"+maxSafeBasal.toFixed(1)+", "; - rate = maxSafeBasal; + rT.reason += "adj. req. rate: "+rate+" to maxSafeBasal: "+maxSafeBasal+", "; + rate = round_basal(maxSafeBasal, profile); } - - var insulinScheduled = currenttemp.duration * (currenttemp.rate - profile.current_basal) / 60; - if (insulinScheduled > insulinReq + 0.3) { // if current temp would deliver >0.3U more than the required insulin, lower the rate - rT.reason = currenttemp.duration + "mins @" + (currenttemp.rate - profile.current_basal).toFixed(3) + " = " + insulinScheduled.toFixed(3) + " > req " + insulinReq + "+0.3 U"; - return setTempBasal(rate, 30, profile, rT, offline); + + var 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); } - + if (typeof currenttemp.duration == 'undefined' || currenttemp.duration == 0) { // no temp is set - rT.reason += "no temp, setting " + rate + "U/hr"; - return setTempBasal(rate, 30, profile, rT, offline); + rT.reason += "no temp, setting " + rate + "U/hr. "; + return tempBasalFunctions.setTempBasal(rate, 30, profile, rT, currenttemp); } - - if (currenttemp.duration > 0 && rate < currenttemp.rate + 0.1) { // if required temp <~ existing temp basal - rT.reason += "temp " + currenttemp.rate + " >~ req " + rate + "U/hr"; + + if (currenttemp.duration > 5 && (round_basal(rate, profile) <= round_basal(currenttemp.rate, profile))) { // if required temp <~ existing temp basal + rT.reason += "temp " + currenttemp.rate + " >~ req " + rate + "U/hr. "; return rT; - } - + } + // required temp > existing temp basal - rT.reason += "temp " + currenttemp.rate + "<" + rate + "U/hr"; - return setTempBasal(rate, 30, profile, rT, offline); + rT.reason += "temp " + currenttemp.rate + "<" + rate + "U/hr. "; + return tempBasalFunctions.setTempBasal(rate, 30, profile, rT, currenttemp); } - + }; module.exports = determine_basal; diff --git a/lib/glucose-get-last.js b/lib/glucose-get-last.js index 7e6b5b0b4..e024ea19e 100644 --- a/lib/glucose-get-last.js +++ b/lib/glucose-get-last.js @@ -6,30 +6,70 @@ var getLastGlucose = function (data) { }); var now = data[0]; - var last = data[1]; - var minutes; + var now_date = now.date || Date.parse(now.display_time) || Date.parse(then.dateString); var change; - var avg; + var last_deltas = []; + var short_deltas = []; + var long_deltas = []; - //TODO: calculate average using system_time instead of assuming 1 data point every 5m - if (typeof data[3] !== 'undefined' && data[3].glucose > 30) { - minutes = 3*5; - change = now.glucose - data[3].glucose; - } else if (typeof data[2] !== 'undefined' && data[2].glucose > 30) { - minutes = 2*5; - change = now.glucose - data[2].glucose; - } else if (typeof last !== 'undefined' && last.glucose > 30) { - minutes = 5; - change = now.glucose - last.glucose; - } else { change = 0; } - // multiply by 5 to get the same units as delta, i.e. mg/dL/5m - avg = change/minutes * 5; + //console.error(now.glucose); + for (i=1; i < data.length; i++) { + // only use data from the same device as the most recent BG data point + if (typeof data[i] !== 'undefined' && data[i].glucose > 38 && data[i].device == now.device) { + var then = data[i]; + var then_date = then.date || Date.parse(then.display_time) || Date.parse(then.dateString); + var avgdelta = 0; + var minutesago; + if (typeof then_date !== 'undefined' && typeof now_date !== 'undefined') { + minutesago = Math.round( (now_date - then_date) / (1000 * 60) ); + // multiply by 5 to get the same units as delta, i.e. mg/dL/5m + change = now.glucose - then.glucose; + avgdelta = change/minutesago * 5; + } else { console.error("Error: date field not found: cannot calculate avgdelta"); } + //if (i < 5) { + //console.error(then.glucose, minutesago, avgdelta); + //} + // use the average of all data points in the last 2.5m for all further "now" calculations + if (-2 < minutesago && minutesago < 2.5) { + now.glucose = ( now.glucose + then.glucose ) / 2; + now_date = ( now_date + then_date ) / 2; + //console.error(then.glucose, now.glucose); + // short_deltas are calculated from everything ~5-15 minutes ago + } else if (2.5 < minutesago && minutesago < 17.5) { + //console.error(minutesago, avgdelta); + short_deltas.push(avgdelta); + // last_deltas are calculated from everything ~5 minutes ago + if (2.5 < minutesago && minutesago < 7.5) { + last_deltas.push(avgdelta); + } + //console.error(then.glucose, minutesago, avgdelta, last_deltas, short_deltas); + // long_deltas are calculated from everything ~20-40 minutes ago + } else if (17.5 < minutesago && minutesago < 42.5) { + long_deltas.push(avgdelta); + } + } + } + var last_delta = 0; + var short_avgdelta = 0; + var long_avgdelta = 0; + if (last_deltas.length > 0) { + last_delta = last_deltas.reduce(function(a, b) { return a + b; }) / last_deltas.length; + } + if (short_deltas.length > 0) { + short_avgdelta = short_deltas.reduce(function(a, b) { return a + b; }) / short_deltas.length; + } + if (long_deltas.length > 0) { + long_avgdelta = long_deltas.reduce(function(a, b) { return a + b; }) / long_deltas.length; + } return { - delta: now.glucose - last.glucose - , glucose: now.glucose - , avgdelta: avg + delta: Math.round( last_delta * 100 ) / 100 + , glucose: Math.round( now.glucose * 100 ) / 100 + , noise: Math.round(now.noise) + , short_avgdelta: Math.round( short_avgdelta * 100 ) / 100 + , long_avgdelta: Math.round( long_avgdelta * 100 ) / 100 + , date: now_date }; }; -module.exports = getLastGlucose; \ No newline at end of file +module.exports = getLastGlucose; diff --git a/lib/iob/calculate.js b/lib/iob/calculate.js index 00ff1358b..e459bb29c 100644 --- a/lib/iob/calculate.js +++ b/lib/iob/calculate.js @@ -1,40 +1,126 @@ +var _ = require('lodash'); -function iobCalc(treatment, time, dia) { - var diaratio = 3.0 / dia; - var peak = 75 ; - var end = 180 ; - //var sens = profile_data.sens; - if (typeof time === 'undefined') { - time = new Date(); - } - - var results = {}; +function iobCalc(treatment, time, curve, dia, peak, profile) { + // iobCalc returns two variables: + // activityContrib = units of treatment.insulin used in previous minute + // iobContrib = units of treatment.insulin still remaining at a given point in time + // ("Contrib" is used because these are the amounts contributed from pontentially multiple treatment.insulin dosages -- totals are calculated in total.js) + // + // Variables can be calculated using either: + // A bilinear insulin action curve (which only takes duration of insulin activity (dia) as an input parameter) or + // An exponential insulin action curve (which takes both a dia and a peak parameter) + // (which functional form to use is specified in the user's profile) if (treatment.insulin) { + + // Calc minutes since bolus (minsAgo) + if (typeof time === 'undefined') { + time = new Date(); + } var bolusTime = new Date(treatment.date); - var minAgo = diaratio * (time-bolusTime) / 1000 / 60; - var iobContrib = 0; - var activityContrib = 0; - - if (minAgo < peak) { - var x = (minAgo/5 + 1); - iobContrib = treatment.insulin * (1 - 0.001852 * x * x + 0.001852 * x); - //activityContrib=sens*treatment.insulin*(2/dia/60/peak)*minAgo; - activityContrib = treatment.insulin * (2 / dia / 60 / peak) * minAgo; - } else if (minAgo < end) { - var y = (minAgo-peak)/5; - iobContrib = treatment.insulin * (0.001323 * y * y - .054233 * y + .55556); - //activityContrib=sens*treatment.insulin*(2/dia/60-(minAgo-peak)*2/dia/60/(60*dia-peak)); - activityContrib = treatment.insulin * (2 / dia / 60 - (minAgo - peak) * 2 / dia / 60 / (60 * dia - peak)); + var minsAgo = Math.round((time - bolusTime) / 1000 / 60); + + + if (curve == 'bilinear') { + return iobCalcBilinear(treatment, minsAgo, dia); // no user-specified peak with this model + } else { + return iobCalcExponential(treatment, minsAgo, dia, peak, profile); } - results = { - iobContrib: iobContrib, - activityContrib: activityContrib - }; + } else { // empty return if (treatment.insulin) == False + return {}; + } +} + + +function iobCalcBilinear(treatment, minsAgo, dia) { + + const default_dia = 3.0 // assumed duration of insulin activity, in hours + const peak = 75; // assumed peak insulin activity, in minutes + const end = 180; // assumed end of insulin activity, in minutes + + // Scale minsAgo by the ratio of the default dia / the user's dia + // so the calculations for activityContrib and iobContrib work for + // other dia values (while using the constants specified above) + var timeScalar = default_dia / dia; + var scaled_minsAgo = timeScalar * minsAgo; + + + var activityContrib = 0; + var iobContrib = 0; + + // Calc percent of insulin activity at peak, and slopes up to and down from peak + // Based on area of triangle, because area under the insulin action "curve" must sum to 1 + // (length * height) / 2 = area of triangle (1), therefore height (activityPeak) = 2 / length (which in this case is dia, in minutes) + // activityPeak scales based on user's dia even though peak and end remain fixed + var activityPeak = 2 / (dia * 60) + var slopeUp = activityPeak / peak + var slopeDown = -1 * (activityPeak / (end - peak)) + + if (scaled_minsAgo < peak) { + + activityContrib = treatment.insulin * (slopeUp * scaled_minsAgo); + + var x1 = (scaled_minsAgo / 5) + 1; // scaled minutes since bolus, pre-peak; divided by 5 to work with coefficients estimated based on 5 minute increments + iobContrib = treatment.insulin * ( (-0.001852*x1*x1) + (0.001852*x1) + 1.000000 ); + + } else if (scaled_minsAgo < end) { + + var minsPastPeak = scaled_minsAgo - peak + activityContrib = treatment.insulin * (activityPeak + (slopeDown * minsPastPeak)); + + var x2 = ((scaled_minsAgo - peak) / 5); // scaled minutes past peak; divided by 5 to work with coefficients estimated based on 5 minute increments + iobContrib = treatment.insulin * ( (0.001323*x2*x2) + (-0.054233*x2) + 0.555560 ); + } + + var results = { + activityContrib: activityContrib, + iobContrib: iobContrib + }; + + return results; +} + + +function iobCalcExponential(treatment, minsAgo, dia, peak, profile) { + + // Use custom peak time (in minutes) if value is valid + if (profile.useCustomPeakTime && profile.insulinPeakTime !== undefined) { + if (profile.insulinPeakTime >= 35 && profile.insulinPeakTime <= 120) { + peak = profile.insulinPeakTime; + } else { + console.error('Insulin Peak Time is only supported for values between 35 to 120 minutes'); + } + } + var end = dia * 60; // end of insulin activity, in minutes + + + var activityContrib = 0; + var iobContrib = 0; + + if (minsAgo < end) { + + // Formula source: https://github.com/LoopKit/Loop/issues/388#issuecomment-317938473 + // Mapping of original source variable names to those used here: + // td = end + // tp = peak + // t = minsAgo + var tau = peak * (1 - peak / end) / (1 - 2 * peak / end); // time constant of exponential decay + var a = 2 * tau / end; // rise time factor + var S = 1 / (1 - a + (1 + a) * Math.exp(-end / tau)); // auxiliary scale factor + + activityContrib = treatment.insulin * (S / Math.pow(tau, 2)) * minsAgo * (1 - minsAgo / end) * Math.exp(-minsAgo / tau); + iobContrib = treatment.insulin * (1 - S * (1 - a) * ((Math.pow(minsAgo, 2) / (tau * end * (1 - a)) - minsAgo / tau - 1) * Math.exp(-minsAgo / tau) + 1)); + //console.error('DIA: ' + dia + ' minsAgo: ' + minsAgo + ' end: ' + end + ' peak: ' + peak + ' tau: ' + tau + ' a: ' + a + ' S: ' + S + ' activityContrib: ' + activityContrib + ' iobContrib: ' + iobContrib); } + var results = { + activityContrib: activityContrib, + iobContrib: iobContrib + }; + return results; } + exports = module.exports = iobCalc; diff --git a/lib/iob/history.js b/lib/iob/history.js index f7777eb9b..681f4d345 100644 --- a/lib/iob/history.js +++ b/lib/iob/history.js @@ -1,77 +1,538 @@ -var tz = require('timezone'); +var tz = require('moment-timezone'); +var basalprofile = require('../profile/basal.js'); +var _ = require('lodash'); +var moment = require('moment'); -function calcTempTreatments (inputs) { - var pumpHistory = inputs.history; - var profile_data = inputs.profile; +function splitTimespanWithOneSplitter(event,splitter) { + + var resultArray = [event]; + + if (splitter.type === 'recurring') { + + var startMinutes = event.started_at.getHours() * 60 + event.started_at.getMinutes(); + var endMinutes = startMinutes + event.duration; + + // 1440 = one day; no clean way to check if the event overlaps midnight + // so checking if end of event in minutes is past midnight + + if (event.duration > 30 || (startMinutes < splitter.minutes && endMinutes > splitter.minutes) || (endMinutes > 1440 && splitter.minutes < (endMinutes - 1440))) { + + var event1 = _.cloneDeep(event); + var event2 = _.cloneDeep(event); + + var event1Duration = 0; + + if (event.duration > 30) { + event1Duration = 30; + } else { + var splitPoint = splitter.minutes; + if (endMinutes > 1440) { splitPoint = 1440; } + event1Duration = splitPoint - startMinutes; + } + + var event1EndDate = moment(event.started_at).add(event1Duration,'minutes'); + + event1.duration = event1Duration; + + event2.duration = event.duration - event1Duration; + event2.timestamp = event1EndDate.format(); + event2.started_at = new Date(event2.timestamp); + event2.date = event2.started_at.getTime(); + + resultArray = [event1,event2]; + } + } + + return resultArray; +} + +function splitTimespan(event, splitterMoments) { + + var results = [event]; + + var splitFound = true; + + while(splitFound) { + + var resultArray = []; + splitFound = false; + + _.forEach(results,function split(o) { + _.forEach(splitterMoments,function split(p) { + var splitResult = splitTimespanWithOneSplitter(o,p); + if (splitResult.length > 1) { + resultArray = resultArray.concat(splitResult); + splitFound = true; + return false; + } + }); + + if (!splitFound) resultArray = resultArray.concat([o]); + + }); + + results = resultArray; + } + + return results; +} + +// Split currentEvent around any conflicting suspends +// by removing the time period from the event that +// overlaps with any suspend. +function splitAroundSuspends (currentEvent, pumpSuspends, firstResumeTime, suspendedPrior, lastSuspendTime, currentlySuspended) { + var events = []; + + var firstResumeStarted = new Date(firstResumeTime); + var firstResumeDate = firstResumeStarted.getTime() + + var lastSuspendStarted = new Date(lastSuspendTime); + var lastSuspendDate = lastSuspendStarted.getTime(); + + if (suspendedPrior && (currentEvent.date < firstResumeDate)) { + if ((currentEvent.date+currentEvent.duration*60*1000) < firstResumeDate) { + currentEvent.duration = 0; + } else { + currentEvent.duration = ((currentEvent.date+currentEvent.duration*60*1000)-firstResumeDate)/60/1000; + + currentEvent.started_at = new Date(tz(firstResumeTime)); + currentEvent.date = firstResumeDate + } + } + + if (currentlySuspended && ((currentEvent.date+currentEvent.duration*60*1000) > lastSuspendTime)) { + if (currentEvent.date > lastSuspendTime) { + currentEvent.duration = 0; + } else { + currentEvent.duration = (firstResumeDate - currentEvent.date)/60/1000; + } + } + + events.push(currentEvent); + + if (currentEvent.duration == 0) { + // bail out rather than wasting time going through the rest of the suspend events + return events; + } + + for (var i=0; i < pumpSuspends.length; i++) { + var suspend = pumpSuspends[i]; + + for (var j=0; j < events.length; j++) { + + if ((events[j].date <= suspend.date) && (events[j].date+events[j].duration*60*1000) > suspend.date) { + // event started before the suspend, but finished after the suspend started + + if ((events[j].date+events[j].duration*60*1000) > (suspend.date+suspend.duration*60*1000)) { + var event2 = _.cloneDeep(events[j]); + + var event2StartDate = moment(suspend.started_at).add(suspend.duration,'minutes'); + + event2.timestamp = event2StartDate.format(); + event2.started_at = new Date(tz(event2.timestamp)); + event2.date = suspend.date+suspend.duration*60*1000; + + event2.duration = ((events[j].date+events[j].duration*60*1000) - (suspend.date+suspend.duration*60*1000))/60/1000; + + events.push(event2); + } + + events[j].duration = (suspend.date-events[j].date)/60/1000; + + } else if ((suspend.date <= events[j].date) && (suspend.date+suspend.duration*60*1000 > events[j].date)) { + // suspend started before the event, but finished after the event started + + events[j].duration = ((events[j].date+events[j].duration*60*1000) - (suspend.date+suspend.duration*60*1000))/60/1000; + + var eventStartDate = moment(suspend.started_at).add(suspend.duration,'minutes'); + + events[j].timestamp = eventStartDate.format(); + events[j].started_at = new Date(tz(events[j].timestamp)); + events[j].date = suspend.date + suspend.duration*60*1000; + } + } + } + + return events; +} + +function calcTempTreatments (inputs, zeroTempDuration) { + var pumpHistory = inputs.history; + var profile_data = inputs.profile; + var autosens_data = inputs.autosens; var tempHistory = []; var tempBoluses = []; + var pumpSuspends = []; + var pumpResumes = []; + var suspendedPrior = false; + var firstResumeTime, lastSuspendTime; + var currentlySuspended = false; + var suspendError = false; + var now = new Date(); var timeZone = now.toString().match(/([-\+][0-9]+)\s/)[1]; + + // Gather the times the pump was suspended and resumed for (var i=0; i < pumpHistory.length; i++) { + var temp = {}; + var current = pumpHistory[i]; - //if(pumpHistory[i].date < time) { - if (pumpHistory[i]._type == "Bolus") { - //console.log(pumpHistory[i]); - var temp = {}; - temp.timestamp = current.timestamp; - //temp.started_at = new Date(current.date); - temp.started_at = new Date(tz(current.timestamp)); - //temp.date = current.date - temp.date = temp.started_at.getTime(); - temp.insulin = current.amount; - tempBoluses.push(temp); - } else if (pumpHistory[i]._type == "TempBasal") { - if (current.temp == 'percent') { - continue; + + if (current._type == "PumpSuspend") { + temp.timestamp = current.timestamp; + temp.started_at = new Date(tz(current.timestamp)); + temp.date = temp.started_at.getTime(); + pumpSuspends.push(temp); + } else if (current._type == "PumpResume") { + temp.timestamp = current.timestamp; + temp.started_at = new Date(tz(current.timestamp)); + temp.date = temp.started_at.getTime(); + pumpResumes.push(temp); + } + } + + pumpSuspends = _.sortBy(pumpSuspends, 'date'); + + pumpResumes = _.sortBy(pumpResumes, 'date'); + + if (pumpResumes.length > 0) { + firstResumeTime = pumpResumes[0].timestamp; + + // Check to see if our first resume was prior to our first suspend + // indicating suspend was prior to our first event. + if (pumpSuspends.length == 0 || (pumpResumes[0].date < pumpSuspends[0].date)) { + suspendedPrior = true; + } + + } + + var j=0; // matching pumpResumes entry; + + // Match the resumes with the suspends to get durations + for (var i=0; i < pumpSuspends.length; i++) { + for (; j < pumpResumes.length; j++) { + if (pumpResumes[j].date > pumpSuspends[i].date) { + break; + } + } + + if ((j >= pumpResumes.length) && !currentlySuspended) { + // even though it isn't the last suspend, we have reached + // the final suspend. Set resume last so the + // algorithm knows to suspend all the way + // through the last record beginning at the last suspend + // since we don't have a matching resume. + currentlySuspended = 1; + lastSuspendTime = pumpSuspends[i].timestamp; + + break; + } + + pumpSuspends[i].duration = (pumpResumes[j].date - pumpSuspends[i].date)/60/1000; + + } + + // These checks indicate something isn't quite aligned. + // Perhaps more resumes that suspends or vice versa... + if (!suspendedPrior && !currentlySuspended && (pumpResumes.length != pumpSuspends.length)) { + console.error("Mismatched number of resumes("+pumpResumes.length+") and suspends("+pumpSuspends.length+")!"); + } else if (suspendedPrior && !currentlySuspended && ((pumpResumes.length-1) != pumpSuspends.length)) { + console.error("Mismatched number of resumes("+pumpResumes.length+") and suspends("+pumpSuspends.length+") assuming suspended prior to history block!"); + } else if (!suspendedPrior && currentlySuspended && (pumpResumes.length != (pumpSuspends.length-1))) { + console.error("Mismatched number of resumes("+pumpResumes.length+") and suspends("+pumpSuspends.length+") assuming suspended past end of history block!"); + } else if (suspendedPrior && currentlySuspended && (pumpResumes.length != pumpSuspends.length)) { + console.error("Mismatched number of resumes("+pumpResumes.length+") and suspends("+pumpSuspends.length+") assuming suspended prior to and past end of history block!"); + } + + if (i < (pumpSuspends.length-1)) { + // truncate any extra suspends. if we had any extras + // the error checks above would have issued a error log message + pumpSuspends.splice(i+1, pumpSuspends.length-i-1); + } + + // Pick relevant events for processing and clean the data + + for (var i=0; i < pumpHistory.length; i++) { + var current = pumpHistory[i]; + if (current.bolus && current.bolus._type == "Bolus") { + var temp = current; + current = temp.bolus; + } + if (current._type == "Bolus") { + var temp = {}; + temp.timestamp = current.timestamp; + temp.started_at = new Date(tz(current.timestamp)); + temp.date = temp.started_at.getTime(); + temp.insulin = current.amount; + tempBoluses.push(temp); + } else if (current.eventType == "Meal Bolus" || current.eventType == "Correction Bolus" || current.eventType == "Snack Bolus" || current.eventType == "Bolus Wizard") { + //imports treatments entered through Nightscout Care Portal + //"Bolus Wizard" refers to the Nightscout Bolus Wizard, not the Medtronic Bolus Wizard + var temp = {}; + temp.timestamp = current.created_at; + temp.started_at = new Date(tz(temp.timestamp)); + temp.date = temp.started_at.getTime(); + temp.insulin = current.insulin; + tempBoluses.push(temp); + } else if (current.enteredBy == "xdrip") { + var temp = {}; + temp.timestamp = current.timestamp; + temp.started_at = new Date(tz(current.timestamp)); + temp.date = temp.started_at.getTime(); + temp.insulin = current.insulin; + tempBoluses.push(temp); + } else if (current.enteredBy =="HAPP_App" && current.insulin) { + var temp = {}; + temp.timestamp = current.created_at; + temp.started_at = new Date(tz(current.timestamp)); + temp.date = temp.started_at.getTime(); + temp.insulin = current.insulin; + tempBoluses.push(temp); + } else if (current.eventType == "Temp Basal" && current.enteredBy=="HAPP_App") { + var temp = {}; + temp.rate = current.absolute; + temp.duration = current.duration; + temp.timestamp = current.created_at; + temp.started_at = new Date(tz(temp.timestamp)); + temp.date = temp.started_at.getTime(); + temp.duration = current.duration; + tempHistory.push(temp); + } else if (current.eventType == "Temp Basal") { + var temp = {}; + temp.rate = current.rate; + temp.duration = current.duration; + temp.timestamp = current.timestamp; + temp.started_at = new Date(tz(temp.timestamp)); + temp.date = temp.started_at.getTime(); + temp.duration = current.duration; + tempHistory.push(temp); + } else if (current._type == "TempBasal") { + if (current.temp == 'percent') { + continue; + } + var rate = current.rate; + var timestamp = current.timestamp; + var duration; + if (i>0 && pumpHistory[i-1].timestamp == timestamp && pumpHistory[i-1]._type == "TempBasalDuration") { + duration = pumpHistory[i-1]['duration (min)']; + } else { + for (var iter=0; iter < pumpHistory.length; iter++) { + if (pumpHistory[iter].timestamp == timestamp && pumpHistory[iter]._type == "TempBasalDuration") { + duration = pumpHistory[iter]['duration (min)']; + break; + } + } + + if (duration == undefined) { + console.error("No duration found for "+rate+" U/hr basal "+timestamp, pumpHistory[i - 1], current, pumpHistory[i + 1]); } - var rate = pumpHistory[i].rate; - var date = pumpHistory[i].date; - if (i>0 && pumpHistory[i-1].date == date && pumpHistory[i-1]._type == "TempBasalDuration") { - var duration = pumpHistory[i-1]['duration (min)']; - } else if (i+1 b.date) { return 1 } if (a.date < b.date) { return -1; } return 0; }); + + // Check for overlapping events and adjust event lengths in case of overlap + + tempHistory = _.sortBy(tempHistory, 'date'); + for (var i=0; i+1 < tempHistory.length; i++) { if (tempHistory[i].date + tempHistory[i].duration*60*1000 > tempHistory[i+1].date) { tempHistory[i].duration = (tempHistory[i+1].date - tempHistory[i].date)/60/1000; } } + + // Create an array of moments to slit the temps by + // currently supports basal changes + + var splitterEvents = []; + + _.forEach(profile_data.basalprofile,function addSplitter(o) { + var splitterEvent = {}; + splitterEvent.type = 'recurring'; + splitterEvent.minutes = o.minutes; + splitterEvents.push(splitterEvent); + }); + + // iterate through the events and split at basal break points if needed + + var splitHistoryByBasal = []; + + _.forEach(tempHistory, function splitEvent(o) { + splitHistoryByBasal = splitHistoryByBasal.concat(splitTimespan(o,splitterEvents)); + }); + + tempHistory = _.sortBy(tempHistory, function(o) { return o.date; }); + + var suspend_zeros_iob = false; + + if (typeof profile_data.suspend_zeros_iob !== 'undefined') { + suspend_zeros_iob = profile_data.suspend_zeros_iob; + } + + if (suspend_zeros_iob) { + // iterate through the events and adjust their + // times as required to account for pump suspends + var splitHistory = []; + + _.forEach(splitHistoryByBasal, function splitSuspendEvent(o) { + var splitEvents = splitAroundSuspends(o, pumpSuspends, firstResumeTime, suspendedPrior, lastSuspendTime, currentlySuspended); + splitHistory = splitHistory.concat(splitEvents); + }); + + var zTempSuspendBasals = []; + + // Any existing temp basals during times the pump was suspended are now deleted + // Add 0 temp basals to negate the profile basal rates during times pump is suspended + _.forEach(pumpSuspends, function createTempBasal(o) { + var zTempBasal = [{ + _type: 'SuspendBasal', + rate: 0, + duration: o.duration, + date: o.date, + started_at: o.started_at + }]; + zTempSuspendBasals = zTempSuspendBasals.concat(zTempBasal); + }); + + // Add temp suspend basal for maximum DIA (8) up to the resume time + // if there is no matching suspend in the history before the first + // resume + var max_dia_ago = now.getTime() - 8*60*60*1000; + var firstResumeStarted = new Date(firstResumeTime); + var firstResumeDate = firstResumeStarted.getTime() + + // impact on IOB only matters if the resume occurred + // after DIA hours before now. + // otherwise, first resume date can be ignored. Whatever + // insulin is present prior to resume will be aged + // out due to DIA. + if (suspendedPrior && (max_dia_ago < firstResumeDate)) { + + var suspendStart = new Date(max_dia_ago); + var suspendStartDate = suspendStart.getTime() + var started_at = new Date(tz(suspendStart.toISOString())); + + var zTempBasal = [{ + // add _type to aid debugging. It isn't used + // anywhere. + _type: 'SuspendBasal', + rate: 0, + duration: (firstResumeDate - max_dia_ago)/60/1000, + date: suspendStartDate, + started_at: started_at + }]; + zTempSuspendBasals = zTempSuspendBasals.concat(zTempBasal); + } + + if (currentlySuspended) { + var suspendStart = new Date(lastSuspendTime); + var suspendStartDate = suspendStart.getTime() + var started_at = new Date(tz(suspendStart.toISOString())); + + var zTempBasal = [{ + _type: 'SuspendBasal', + rate: 0, + duration: (now - suspendStartDate)/60/1000, + date: suspendStartDate, + timestamp: lastSuspendTime, + started_at: started_at + }]; + zTempSuspendBasals = zTempSuspendBasals.concat(zTempBasal); + } + + // Add the new 0 temp basals to the splitHistory. + // We have to split the new zero temp basals by the profile + // basals just like the other temp basals. + _.forEach(zTempSuspendBasals, function splitEvent(o) { + splitHistory = splitHistory.concat(splitTimespan(o,splitterEvents)); + }); + } else { + splitHistory = splitHistoryByBasal; + } + + splitHistory = _.sortBy(splitHistory, function(o) { return o.date; }); + + // tempHistory = splitHistory; + + // iterate through the temp basals and create bolus events from temps that affect IOB + var tempBolusSize; - var now = new Date(); - var timeZone = now.toString().match(/([-\+][0-9]+)\s/)[1]; - for (var i=0; i < tempHistory.length; i++) { - if (tempHistory[i].duration > 0) { - var netBasalRate = tempHistory[i].rate-profile_data.current_basal; + + for (var i=0; i < splitHistory.length; i++) { + + var currentItem = splitHistory[i]; + + if (currentItem.duration > 0) { + + var currentRate = profile_data.current_basal; + if (!_.isEmpty(profile_data.basalprofile)) { + currentRate = basalprofile.basalLookup(profile_data.basalprofile,new Date(currentItem.timestamp)); + } + + if (typeof profile_data.min_bg !== 'undefined' && typeof profile_data.max_bg !== 'undefined') { + target_bg = (profile_data.min_bg + profile_data.max_bg) / 2; + } + //if (profile_data.temptargetSet && target_bg > 110) { + //sensitivityRatio = 2/(2+(target_bg-100)/40); + //currentRate = profile_data.current_basal * sensitivityRatio; + //} + var sensitivityRatio; + var profile = profile_data; + var normalTarget = 100; // evaluate high/low temptarget against 100, not scheduled basal (which might change) + 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%) + } + if ( profile.exercise_mode && profile.temptargetSet && target_bg >= normalTarget + 5 ) { + // w/ target 100, temp target 110 = .89, 120 = 0.8, 140 = 0.67, 160 = .57, and 200 = .44 + // e.g.: Sensitivity ratio set to 0.8 based on temp target of 120; Adjusting basal from 1.65 to 1.35; ISF from 58.9 to 73.6 + var c = halfBasalTarget - normalTarget; + sensitivityRatio = c/(c+target_bg-normalTarget); + } else if (typeof autosens_data !== 'undefined' ) { + sensitivityRatio = autosens_data.ratio; + //process.stderr.write("Autosens ratio: "+sensitivityRatio+"; "); + } + if ( sensitivityRatio ) { + currentRate = currentRate * sensitivityRatio; + } + + var netBasalRate = currentItem.rate - currentRate; if (netBasalRate < 0) { tempBolusSize = -0.05; } else { tempBolusSize = 0.05; } - var netBasalAmount = Math.round(netBasalRate*tempHistory[i].duration*10/6)/100 + var netBasalAmount = Math.round(netBasalRate*currentItem.duration*10/6)/100 var tempBolusCount = Math.round(netBasalAmount / tempBolusSize); - var tempBolusSpacing = tempHistory[i].duration / tempBolusCount; + var tempBolusSpacing = currentItem.duration / tempBolusCount; for (var j=0; j < tempBolusCount; j++) { var tempBolus = {}; tempBolus.insulin = tempBolusSize; - tempBolus.date = tempHistory[i].date + j * tempBolusSpacing*60*1000; + tempBolus.date = currentItem.date + j * tempBolusSpacing*60*1000; tempBolus.created_at = new Date(tempBolus.date); tempBoluses.push(tempBolus); } } } var all_data = [ ].concat(tempBoluses).concat(tempHistory); - all_data.sort(function (a, b) { return a.date > b.date }); + all_data = _.sortBy(all_data, 'date'); return all_data; } exports = module.exports = calcTempTreatments; diff --git a/lib/iob/index.js b/lib/iob/index.js index f8ac98cab..17078781b 100644 --- a/lib/iob/index.js +++ b/lib/iob/index.js @@ -1,23 +1,84 @@ -var tz = require('timezone'); +var tz = require('moment-timezone'); var find_insulin = require('./history'); var calculate = require('./calculate'); var sum = require('./total'); -function generate (inputs) { +function generate (inputs, currentIOBOnly, treatments) { - var treatments = find_insulin(inputs); + if (!treatments) { + var treatments = find_insulin(inputs); + // calculate IOB based on continuous future zero temping as well + var treatmentsWithZeroTemp = find_insulin(inputs, 240); + } else { + var treatmentsWithZeroTemp = []; + } + //console.error(treatments.length, treatmentsWithZeroTemp.length); + //console.error(treatments[treatments.length-1], treatmentsWithZeroTemp[treatmentsWithZeroTemp.length-1]) - var opts = { - treatments: treatments - , profile: inputs.profile - , calculate: calculate - }; + var opts = { + treatments: treatments + , profile: inputs.profile + , calculate: calculate + }; + if ( inputs.autosens ) { + opts.autosens = inputs.autosens; + } + var optsWithZeroTemp = { + treatments: treatmentsWithZeroTemp + , profile: inputs.profile + , calculate: calculate + }; - var clock = new Date(tz(inputs.clock)); + var iobArray = []; + //console.error(inputs.clock); + if (! /(Z|[+-][0-2][0-9]:?[034][05])+/.test(inputs.clock) ) { + console.error("Warning: clock input " + inputs.clock + " is unzoned; please pass clock-zoned.json instead"); + } + var clock = new Date(tz(inputs.clock)); - var iob = sum(opts, clock); - return iob; + var lastBolusTime = new Date(0).getTime(); //clock.getTime()); + var lastTemp = {}; + lastTemp.date = new Date(0).getTime(); //clock.getTime()); + //console.error(treatments[treatments.length-1]); + treatments.forEach(function(treatment) { + if (treatment.insulin && treatment.started_at) { + lastBolusTime = Math.max(lastBolusTime,treatment.started_at); + //console.error(treatment.insulin,treatment.started_at,lastBolusTime); + } else if (typeof(treatment.rate) === 'number' && treatment.duration ) { + if ( treatment.date > lastTemp.date ) { + lastTemp = treatment; + lastTemp.duration = Math.round(lastTemp.duration*100)/100; + } + + //console.error(treatment.rate, treatment.duration, treatment.started_at,lastTemp.started_at) + } + //console.error(treatment.rate, treatment.duration, treatment.started_at,lastTemp.started_at) + //if (treatment.insulin && treatment.started_at) { console.error(treatment.insulin,treatment.started_at,lastBolusTime); } + }); + var iStop; + if (currentIOBOnly) { + // for COB calculation, we only need the zeroth element of iobArray + iStop=1 + } else { + // predict IOB out to 4h, regardless of DIA + iStop=4*60; + } + for (i=0; i= 0.2 && treatment.started_at) { - //use half the dia for double speed bolus snooze - var bIOB = iobCalc(treatment, time, dia / 2); - //console.log(treatment); - //console.log(bIOB); - if (bIOB && bIOB.iobContrib) bolusiob += bIOB.iobContrib; + if( treatment.date <= now ) { + var dia_ago = now - dia*60*60*1000; + if( treatment.date > dia_ago ) { + // tIOB = total IOB + var tIOB = iobCalc(treatment, time, curve, dia, peak, profile_data); + if (tIOB && tIOB.iobContrib) { iob += tIOB.iobContrib; } + if (tIOB && tIOB.activityContrib) { activity += tIOB.activityContrib; } + // basals look like either of these: + // {"insulin":-0.05,"date":1507265512363.6365,"created_at":"2017-10-06T04:51:52.363Z"} + // {"insulin":0.05,"date":1507266530000,"created_at":"2017-10-06T05:08:50.000Z"} + // boluses look like: + // {"timestamp":"2017-10-05T22:06:31-07:00","started_at":"2017-10-06T05:06:31.000Z","date":1507266391000,"insulin":0.5} + if (treatment.insulin && tIOB && tIOB.iobContrib) { + if (treatment.insulin < 0.1) { + basaliob += tIOB.iobContrib; + netbasalinsulin += treatment.insulin; + } else { + bolusiob += tIOB.iobContrib; + bolusinsulin += treatment.insulin; + } + } + //console.error(JSON.stringify(treatment)); } - } + } // else { console.error("ignoring future treatment:",treatment); } }); - return { - iob: iob, - activity: activity, - bolusiob: bolusiob + var rval = { + iob: Math.round(iob * 1000) / 1000, + activity: Math.round(activity * 10000) / 10000, + basaliob: Math.round(basaliob * 1000) / 1000, + bolusiob: Math.round(bolusiob * 1000) / 1000, + netbasalinsulin: Math.round(netbasalinsulin * 1000) / 1000, + bolusinsulin: Math.round(bolusinsulin * 1000) / 1000, + time: time }; + + return rval; } exports = module.exports = iobTotal; - diff --git a/lib/meal/history.js b/lib/meal/history.js new file mode 100644 index 000000000..628a3e016 --- /dev/null +++ b/lib/meal/history.js @@ -0,0 +1,141 @@ + +var tz = require('moment-timezone'); + +function arrayHasElementWithSameTimestampAndProperty(array,t,propname) { + for (var j=0; j < array.length; j++) { + 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); + //console.error(tDate, tMin, tMax); + if (eDate > tMin && eDate < tMax) return true; + } + } + return false; +} + +function findMealInputs (inputs) { + var pumpHistory = inputs.history; + var carbHistory = inputs.carbs; + var profile_data = inputs.profile; + var mealInputs = []; + var bolusWizardInputs = []; + var duplicates = 0; + + for (var i=0; i < carbHistory.length; i++) { + var current = carbHistory[i]; + if (current.carbs && current.created_at) { + var temp = {}; + temp.timestamp = current.created_at; + temp.carbs = current.carbs; + temp.nsCarbs = current.carbs; + if (!arrayHasElementWithSameTimestampAndProperty(mealInputs,current.created_at,"carbs")) { + mealInputs.push(temp); + } else { + duplicates += 1; + } + } + } + + for (var i=0; i < pumpHistory.length; i++) { + var current = pumpHistory[i]; + if (current._type == "Bolus" && current.timestamp) { + //console.log(pumpHistory[i]); + var temp = {}; + temp.timestamp = current.timestamp; + temp.bolus = current.amount; + + if (!arrayHasElementWithSameTimestampAndProperty(mealInputs,current.timestamp,"bolus")) { + mealInputs.push(temp); + } else { + duplicates += 1; + } + } else if (current._type == "BolusWizard" && current.timestamp) { + // Delay process the BolusWizard entries to make sure we've seen all possible that correspond to the bolus wizard. + // More specifically, we need to make sure we process the corresponding bolus entry first. + bolusWizardInputs.push(current); + + } 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.timestamp = current.created_at; + temp.carbs = current.carbs; + temp.nsCarbs = current.carbs; + // don't enter the treatment if there's another treatment with the same exact timestamp + // to prevent duped carb entries from multiple sources + if (!arrayHasElementWithSameTimestampAndProperty(mealInputs,current.created_at,"carbs")) { + mealInputs.push(temp); + } else { + duplicates += 1; + } + } else if (current.enteredBy == "xdrip") { + var temp = {}; + temp.timestamp = current.created_at; + temp.carbs = current.carbs; + temp.nsCarbs = current.carbs; + temp.bolus = current.insulin; + if (!arrayHasElementWithSameTimestampAndProperty(mealInputs,current.timestamp,"carbs")) { + mealInputs.push(temp); + } else { + duplicates += 1; + } + } else if (current.carbs > 0) { + var temp = {}; + temp.carbs = current.carbs; + temp.nsCarbs = current.carbs; + temp.timestamp = current.created_at; + if (!arrayHasElementWithSameTimestampAndProperty(mealInputs,current.timestamp,"carbs")) { + mealInputs.push(temp); + } else { + duplicates += 1; + } + } else if (current._type == "JournalEntryMealMarker" && current.carb_input > 0 && current.timestamp) { + var temp = {}; + temp.timestamp = current.timestamp; + temp.carbs = current.carb_input; + temp.journalCarbs = current.carb_input; + if (!arrayHasElementWithSameTimestampAndProperty(mealInputs,current.timestamp,"carbs")) { + mealInputs.push(temp); + } else { + duplicates += 1; + } + } + } + + for(var i=0; i < bolusWizardInputs.length; i++) { + var current = bolusWizardInputs[i]; + //console.log(bolusWizardInputs[i]); + var temp = {}; + temp.timestamp = current.timestamp; + temp.carbs = current.carb_input; + temp.bwCarbs = current.carb_input; + + // don't enter the treatment if there's another treatment with the same exact timestamp + // to prevent duped carb entries from multiple sources + if (!arrayHasElementWithSameTimestampAndProperty(mealInputs,current.timestamp,"carbs")) { + if (arrayHasElementWithSameTimestampAndProperty(mealInputs,current.timestamp,"bolus")) { + mealInputs.push(temp); + //bwCarbs += temp.carbs; + } else { + console.error("Skipping bolus wizard entry", i, "in the pump history with",current.carb_input,"g carbs and no insulin."); + if (current.carb_input == 0) { + console.error("This is caused by a BolusWizard without carbs. If you specified insulin, it will be noted as a seperate Bolus"); + } + if (current.timestamp) { + console.error("Timestamp of bolus wizard:", current.timestamp); + } + } + } else { + duplicates += 1; + } + } + //if (duplicates > 0) console.error("Removed duplicate bolus/carb entries:" + duplicates); + + return mealInputs; +} + +exports = module.exports = findMealInputs; diff --git a/lib/meal/index.js b/lib/meal/index.js new file mode 100644 index 000000000..bca881e4a --- /dev/null +++ b/lib/meal/index.js @@ -0,0 +1,24 @@ + +var tz = require('moment-timezone'); +var find_meals = require('./history'); +var sum = require('./total'); + +function generate (inputs) { + + var treatments = find_meals(inputs); + + var opts = { + treatments: treatments + , profile: inputs.profile + , pumphistory: inputs.history + , glucose: inputs.glucose + , basalprofile: inputs.basalprofile + }; + + var clock = new Date(tz(inputs.clock)); + + var meal_data = sum(opts, clock); + return meal_data; +} + +exports = module.exports = generate; diff --git a/lib/meal/total.js b/lib/meal/total.js new file mode 100644 index 000000000..65981b00d --- /dev/null +++ b/lib/meal/total.js @@ -0,0 +1,137 @@ +var tz = require('moment-timezone'); +var calcMealCOB = require('../determine-basal/cob'); + +function recentCarbs(opts, time) { + var treatments = opts.treatments; + var profile_data = opts.profile; + if (typeof(opts.glucose) !== 'undefined') { + var glucose_data = opts.glucose; + } + var carbs = 0; + var nsCarbs = 0; + var bwCarbs = 0; + var journalCarbs = 0; + var bwFound = false; + var carbDelay = 20 * 60 * 1000; + var maxCarbs = 0; + var mealCarbTime = time.getTime(); + var lastCarbTime = 0; + if (!treatments) return {}; + + //console.error(glucose_data); + var iob_inputs = { + profile: profile_data + , history: opts.pumphistory + }; + var COB_inputs = { + glucose_data: glucose_data + , iob_inputs: iob_inputs + , basalprofile: opts.basalprofile + , mealTime: mealCarbTime + }; + var mealCOB = 0; + + // this sorts the treatments collection in order. + treatments.sort(function (a, b) { + var aDate = new Date(tz(a.timestamp)); + var bDate = new Date(tz(b.timestamp)); + //console.error(aDate); + return bDate.getTime() - aDate.getTime(); + }); + + var carbsToRemove = 0; + var nsCarbsToRemove = 0; + var bwCarbsToRemove = 0; + var journalCarbsToRemove = 0; + treatments.forEach(function(treatment) { + var now = time.getTime(); + // consider carbs from up to 6 hours ago in calculating COB + var carbWindow = now - 6 * 60*60*1000; + var treatmentDate = new Date(tz(treatment.timestamp)); + var treatmentTime = treatmentDate.getTime(); + if (treatmentTime > carbWindow && treatmentTime <= now) { + if (treatment.carbs >= 1) { + if (treatment.nsCarbs >= 1) { + nsCarbs += parseFloat(treatment.nsCarbs); + } else if (treatment.bwCarbs >= 1) { + bwCarbs += parseFloat(treatment.bwCarbs); + bwFound = true; + } else if (treatment.journalCarbs >= 1) { + journalCarbs += parseFloat(treatment.journalCarbs); + } else { + console.error("Treatment carbs unclassified:",treatment); + } + //console.error(treatment.carbs, maxCarbs, treatmentDate); + carbs += parseFloat(treatment.carbs); + COB_inputs.mealTime = treatmentTime; + lastCarbTime = Math.max(lastCarbTime,treatmentTime); + var myCarbsAbsorbed = calcMealCOB(COB_inputs).carbsAbsorbed; + var myMealCOB = Math.max(0, carbs - myCarbsAbsorbed); + mealCOB = Math.max(mealCOB, myMealCOB); + //console.error("myMealCOB:",myMealCOB, "mealCOB:",mealCOB, "carbs:",carbs,"myCarbsAbsorbed:",myCarbsAbsorbed); + if (myMealCOB < mealCOB) { + carbsToRemove += parseFloat(treatment.carbs); + if (treatment.nsCarbs >= 1) { + nsCarbsToRemove += parseFloat(treatment.nsCarbs); + } else if (treatment.bwCarbs >= 1) { + bwCarbsToRemove += parseFloat(treatment.bwCarbs); + } else if (treatment.journalCarbs >= 1) { + journalCarbsToRemove += parseFloat(treatment.journalCarbs); + } + } else { + carbsToRemove = 0; + nsCarbsToRemove = 0; + bwCarbsToRemove = 0; + } + //console.error(carbs, carbsToRemove); + //console.error("COB:",mealCOB); + } + } + }); + // only include carbs actually used in calculating COB + carbs -= carbsToRemove; + nsCarbs -= nsCarbsToRemove; + bwCarbs -= bwCarbsToRemove; + journalCarbs -= journalCarbsToRemove; + + // calculate the current deviation and steepest deviation downslope over the last hour + COB_inputs.ciTime = time.getTime(); + // set mealTime to 6h ago for Deviation calculations + COB_inputs.mealTime = time.getTime() - 6 * 60 * 60 * 1000; + var c = calcMealCOB(COB_inputs); + //console.error(c.currentDeviation, c.slopeFromMaxDeviation); + + // set a hard upper limit on COB to mitigate impact of erroneous or malicious carb entry + mealCOB = Math.min( profile.maxCOB, mealCOB ); + + // if currentDeviation is null or maxDeviation is 0, set mealCOB to 0 for zombie-carb safety + if (typeof(c.currentDeviation) === 'undefined' || c.currentDeviation === null) { + console.error(""); + console.error("Warning: setting mealCOB to 0 because currentDeviation is null/undefined"); + mealCOB = 0; + } + if (typeof(c.maxDeviation) === 'undefined' || c.maxDeviation === null) { + console.error(""); + console.error("Warning: setting mealCOB to 0 because maxDeviation is 0 or undefined"); + mealCOB = 0; + } + + return { + carbs: Math.round( carbs * 1000 ) / 1000 + , nsCarbs: Math.round( nsCarbs * 1000 ) / 1000 + , bwCarbs: Math.round( bwCarbs * 1000 ) / 1000 + , journalCarbs: Math.round( journalCarbs * 1000 ) / 1000 + , mealCOB: Math.round( mealCOB ) + , currentDeviation: Math.round( c.currentDeviation * 100 ) / 100 + , maxDeviation: Math.round( c.maxDeviation * 100 ) / 100 + , minDeviation: Math.round( c.minDeviation * 100 ) / 100 + , slopeFromMaxDeviation: Math.round( c.slopeFromMaxDeviation * 1000 ) / 1000 + , slopeFromMinDeviation: Math.round( c.slopeFromMinDeviation * 1000 ) / 1000 + , allDeviations: c.allDeviations + , lastCarbTime: lastCarbTime + , bwFound: bwFound + }; +} + +exports = module.exports = recentCarbs; + diff --git a/lib/oref0-setup/alias.json b/lib/oref0-setup/alias.json new file mode 100644 index 000000000..a86fde1e4 --- /dev/null +++ b/lib/oref0-setup/alias.json @@ -0,0 +1,240 @@ +[ + { + "type": "alias", + "name": "invoke", + "invoke": { + "command": "report invoke" + } + }, + { + "type": "alias", + "name": "mmtune", + "mmtune": { + "command": "! bash -c \"reset_spi_serial.py 2>/dev/null; oref0_init_pump_comms.py; find monitor/ -size +5c | grep -q mmtune && cp monitor/mmtune.json mmtune_old.json; echo {} > monitor/mmtune.json; echo -n \\\"mmtune: \\\" && openaps report invoke monitor/mmtune.json; grep -v setFreq monitor/mmtune.json | grep -A2 $(json -a setFreq -f monitor/mmtune.json) | while read line; do echo -n \\\"$line \\\"; done\"" + } + }, + { + "type": "alias", + "name": "wait-for-silence", + "wait-for-silence": { + "command": "report invoke monitor/temp_basal.json" + } + }, + { + "wait-for-long-silence": { + "command": "report invoke monitor/temp_basal.json" + }, + "type": "alias", + "name": "wait-for-long-silence" + }, + { + "type": "alias", + "name": "monitor-cgm", + "monitor-cgm": { + "command": "report invoke raw-cgm/raw-entries.json cgm/cgm-glucose.json" + } + }, + { + "type": "alias", + "name": "get-ns-glucose", + "get-ns-glucose": { + "command": "report invoke cgm/ns-glucose.json" + } + }, + { + "monitor-pump": { + "command": "report invoke monitor/clock.json monitor/temp_basal.json monitor/pumphistory.json monitor/pumphistory-zoned.json monitor/clock-zoned.json monitor/iob.json monitor/reservoir.json monitor/battery.json monitor/status.json" + }, + "type": "alias", + "name": "monitor-pump" + }, + { + "type": "alias", + "ns-temptargets": { + "command": "report invoke settings/temptargets.json settings/profile.json" + }, + "name": "ns-temptargets" + }, + { + "ns-meal-carbs": { + "command": "! bash -c \"openaps report invoke monitor/carbhistory.json; oref0-meal monitor/pumphistory-merged.json settings/profile.json monitor/clock-zoned.json monitor/glucose.json settings/basal_profile.json monitor/carbhistory.json > monitor/meal.json.new; grep -q COB monitor/meal.json.new && mv monitor/meal.json.new monitor/meal.json; exit 0\"" + }, + "type": "alias", + "name": "ns-meal-carbs" + }, + { + "type": "alias", + "name": "get-settings", + "get-settings": { + "command": "report invoke settings/model.json settings/bg_targets_raw.json settings/bg_targets.json settings/insulin_sensitivities_raw.json settings/insulin_sensitivities.json settings/basal_profile.json settings/settings.json settings/carb_ratios.json settings/profile.json" + } + }, + { + "type": "alias", + "name": "bg-fresh-check", + "bg-fresh-check": { + "command": "! bash -c \"cat cgm/glucose.json | json -c \\\"minAgo=(new Date()-new Date(this.dateString))/60/1000; return minAgo < 6 && minAgo > 0 && this.glucose > 38\\\" | grep -q glucose\"" + } + }, + { + "get-bg": { + "command": "! bash -c \"openaps monitor-cgm 2>&1 | tail -1 && grep -q glucose cgm/cgm-glucose.json && cp -pu cgm/cgm-glucose.json cgm/glucose.json; cp -pu cgm/glucose.json monitor/glucose.json\"" + }, + "type": "alias", + "name": "get-bg" + }, + { + "type": "alias", + "name": "get-ns-bg", + "get-ns-bg": { + "command": "! bash -c \"openaps get-ns-glucose && cat cgm/ns-glucose.json | json -c \\\"minAgo=(new Date()-new Date(this.dateString))/60/1000; return minAgo < 10 && minAgo > -5 && this.glucose > 38\\\" | grep -q glucose && cp -pu cgm/ns-glucose.json cgm/glucose.json; cp -pu cgm/glucose.json monitor/glucose.json\"" + } + }, + { + "gather": { + "command": "! bash -c \"openaps report invoke monitor/status.json 2>/dev/null >/dev/null && echo -n Ref && test $(cat monitor/status.json | json bolusing) == false && echo -n resh && ( openaps monitor-pump || openaps monitor-pump ) 2>/dev/null >/dev/null && echo ed pumphistory || (echo; exit 1) 2>/dev/null\"" + }, + "type": "alias", + "name": "gather" + }, + { + "type": "alias", + "autosens": { + "command": "! bash -c \"date; (find settings/ -newer settings/autosens.json | grep -q pumphistory-24h-zoned.json || find settings/ -size -5c | grep -q autosens.json || ! find settings/ | grep -q autosens || ! find settings/autosens.json) && openaps invoke settings/autosens.json\"" + }, + "name": "autosens" + }, + { + "type": "alias", + "name": "refresh-old-pumphistory", + "refresh-old-pumphistory": { + "command": "! bash -c \"find monitor/ -mmin -15 -size +100c | grep -q pumphistory-zoned || ( echo -n \\\"Old pumphistory: \\\" && openaps gather && openaps enact ) \"" + } + }, + { + "refresh-old-pumphistory-24h": { + "command": "! bash -c \"find settings/ -mmin -120 -size +100c | grep -q pumphistory-24h-zoned || (echo -n Old pumphistory-24h refresh && openaps report invoke settings/pumphistory-24h.json settings/pumphistory-24h-zoned.json 2>/dev/null >/dev/null && echo ed)\"" + }, + "type": "alias", + "name": "refresh-old-pumphistory-24h" + }, + { + "refresh-temp-and-enact": { + "command": "! bash -c \"if( (find monitor/ -newer monitor/temp_basal.json | grep -q glucose.json && echo glucose.json newer than temp_basal.json ) || (! find monitor/ -mmin -5 -size +5c | grep -q temp_basal && echo temp_basal.json more than 5m old)); then (echo -n Temp refresh && openaps report invoke monitor/temp_basal.json monitor/clock.json monitor/clock-zoned.json monitor/iob.json 2>/dev/null >/dev/null && echo ed && if(cat monitor/temp_basal.json | json -c \\\"this.duration < 27\\\" | grep -q duration); then openaps enact; else echo Temp duration 27m or more; fi); else echo temp_basal.json less than 5m old; fi\"" + }, + "type": "alias", + "name": "refresh-temp-and-enact" + }, + { + "type": "alias", + "name": "refresh-pumphistory-and-enact", + "refresh-pumphistory-and-enact": { + "command": "! bash -c \"if ((find monitor/ -newer monitor/pumphistory-zoned.json | grep -q glucose.json && echo -n glucose.json newer than pumphistory) || (find enact/ -newer monitor/pumphistory-zoned.json | grep -q enacted.json && echo -n enacted.json newer than pumphistory) || (! find monitor/ -mmin -5 | grep -q pumphistory-zoned && echo -n pumphistory more than 5m old) ); then (echo -n \\\": \\\" && openaps gather && openaps enact ); else echo Pumphistory less than 5m old; fi \"" + } + }, + { + "refresh-old-profile": { + "command": "! bash -c \"find settings/ -mmin -60 -size +5c | grep -q settings/profile.json && echo Profile less than 60m old || (echo -n Old settings refresh && openaps get-settings 2>/dev/null >/dev/null && echo ed )\"" + }, + "type": "alias", + "name": "refresh-old-profile" + }, + { + "refresh-profile": { + "command": "! bash -c \"find settings/ -mmin -10 -size +5c | grep -q settings.json && echo Settings less than 10m old || (echo -n Settings refresh && openaps get-settings 2>/dev/null >/dev/null && echo ed)\"" + }, + "type": "alias", + "name": "refresh-profile" + }, + { + "refresh-pumphistory-24h": { + "command": "! bash -c \"find settings/ -mmin -20 -size +100c | grep -q pumphistory-24h-zoned && echo Pumphistory-24 less than 20m old || (echo -n pumphistory-24h refresh && openaps report invoke settings/pumphistory-24h.json settings/pumphistory-24h-zoned.json 2>/dev/null >/dev/null && echo ed)\"" + }, + "type": "alias", + "name": "refresh-pumphistory-24h" + }, + { + "merge-pumphistory-long": { + "command": "! bash -c \"jq -s \\\".[0] + .[1]|unique|sort_by(.timestamp)|reverse\\\" settings/pumphistory-long.json monitor/pumphistory-zoned.json settings/pumphistory-24h-zoned.json > pumphistory-long.json.new && mv pumphistory-long.json.new settings/pumphistory-long.json\"" + }, + "type": "alias", + "name": "merge-pumphistory-long" + }, + { + "type": "alias", + "name": "enact", + "enact": { + "command": "! bash -c \"rm enact/suggested.json; openaps invoke enact/suggested.json && if (cat enact/suggested.json && grep -q duration enact/suggested.json); then ( rm enact/enacted.json; openaps invoke enact/enacted.json ; grep -q duration enact/enacted.json || openaps invoke enact/enacted.json ) 2>&1 | egrep -v \\\"^ |subg_rfspy|handler\\\"; fi; grep incorrectly enact/suggested.json && oref0-set-system-clock 2>/dev/null; cat enact/enacted.json | json -0\"" + } + }, + { + "type": "alias", + "name": "ns-loop", + "ns-loop": { + "command": "! bash -c \"echo Starting ns-loop at $(date): && openaps get-ns-bg; sensors -u 2>/dev/null | awk '$NF > 85' | grep input || ( openaps ns-temptargets && echo -n Refreshed temptargets && openaps ns-meal-carbs && echo \\\" and meal-carbs\\\" && openaps upload )\"" + } + }, + { + "pump-loop": { + "command": "! bash -c \"sleep $[ ( $RANDOM / 2048 ) ]s; until(echo Starting pump-loop at $(date): && openaps wait-for-silence && openaps refresh-old-pumphistory && openaps refresh-old-pumphistory-24h && openaps refresh-old-profile && openaps refresh-temp-and-enact && openaps refresh-pumphistory-and-enact && openaps refresh-profile && openaps refresh-pumphistory-24h && echo Completed pump-loop at $(date) && echo); do echo Error, retrying && [[ $RANDOM > 25000 ]] && openaps wait-for-long-silence && openaps mmtune; sleep 5; done\"" + }, + "type": "alias", + "name": "pump-loop" + }, + { + "pebble": { + "command": "! bash -c \"grep -q iob monitor/iob.json && grep -q absolute enact/suggested.json && openaps report invoke upload/pebble.json\"" + }, + "type": "alias", + "name": "pebble" + }, + { + "type": "alias", + "name": "latest-ns-treatment-time", + "latest-ns-treatment-time": { + "command": "! bash -c \"nightscout latest-openaps-treatment $NIGHTSCOUT_HOST | json created_at\"" + } + }, + { + "type": "alias", + "name": "format-latest-nightscout-treatments", + "format-latest-nightscout-treatments": { + "command": "! bash -c \"nightscout cull-latest-openaps-treatments monitor/pumphistory-zoned.json settings/model.json $(openaps latest-ns-treatment-time) > upload/latest-treatments.json\"" + } + }, + { + "type": "alias", + "name": "upload-recent-treatments", + "upload-recent-treatments": { + "command": "! bash -c \"openaps format-latest-nightscout-treatments && test $(json -f upload/latest-treatments.json -a created_at eventType | wc -l ) -gt 0 && (ns-upload $NIGHTSCOUT_HOST $API_SECRET treatments.json upload/latest-treatments.json ) || echo \\\"No recent treatments to upload\\\"\"" + } + }, + { + "type": "alias", + "name": "format-ns-status", + "format-ns-status": { + "command": "! bash -c \"ns-status monitor/clock-zoned.json monitor/iob.json enact/suggested.json enact/enacted.json monitor/battery.json monitor/reservoir.json monitor/status.json > upload/ns-status.json\"" + } + }, + { + "upload-ns-status": { + "command": "! bash -c \"grep -q iob monitor/iob.json && find enact/ -mmin -5 -size +5c | grep -q suggested.json && openaps format-ns-status && grep -q iob upload/ns-status.json && ns-upload $NIGHTSCOUT_HOST $API_SECRET devicestatus.json upload/ns-status.json\"" + }, + "type": "alias", + "name": "upload-ns-status" + }, + { + "type": "alias", + "name": "upload", + "upload": { + "command": "! bash -c \"echo -n Upload && ( openaps upload-ns-status; openaps upload-pumphistory-entries; openaps upload-recent-treatments ) 2>/dev/null >/dev/null && echo ed\"" + } + }, + { + "type": "alias", + "name": "monitor-xdrip", + "monitor-xdrip": { + "command": "report invoke xdrip/glucose.json" + } +} +] diff --git a/lib/oref0-setup/autotune.json b/lib/oref0-setup/autotune.json new file mode 100644 index 000000000..cd3c4ad45 --- /dev/null +++ b/lib/oref0-setup/autotune.json @@ -0,0 +1,43 @@ +[ + { + "settings/pumpprofile.json": { + "use": "shell", + "bg_targets": "settings/bg_targets.json", + "preferences": "preferences.json", + "settings": "settings/settings.json", + "basal_profile": "settings/basal_profile.json", + "reporter": "text", + "json_default": "True", + "carb_ratios": "settings/carb_ratios.json", + "device": "get-profile", + "remainder": "--model=settings/model.json", + "isf": "settings/insulin_sensitivities.json" + }, + "type": "report", + "name": "settings/pumpprofile.json" + }, + { + "settings/profile.json": { + "use": "shell", + "bg_targets": "settings/bg_targets.json", + "preferences": "preferences.json", + "settings": "settings/settings.json", + "basal_profile": "settings/basal_profile.json", + "reporter": "text", + "json_default": "True", + "carb_ratios": "settings/carb_ratios.json", + "device": "get-profile", + "remainder": "settings/temptargets.json --model=settings/model.json --autotune settings/autotune.json", + "isf": "settings/insulin_sensitivities.json" + }, + "type": "report", + "name": "settings/profile.json" + }, + { + "type": "alias", + "name": "get-settings", + "get-settings": { + "command": "report invoke settings/model.json settings/bg_targets_raw.json settings/bg_targets.json settings/insulin_sensitivities_raw.json settings/insulin_sensitivities.json settings/basal_profile.json settings/settings.json settings/carb_ratios.json settings/pumpprofile.json settings/profile.json" + } + } +] diff --git a/lib/oref0-setup/basal_profile.json b/lib/oref0-setup/basal_profile.json new file mode 100644 index 000000000..b9e18784e --- /dev/null +++ b/lib/oref0-setup/basal_profile.json @@ -0,0 +1,50 @@ +[ + { + "i": 0, + "start": "00:00:00", + "rate": 0, + "minutes": 0 + }, + { + "i": 1, + "start": "02:30:00", + "rate": 0, + "minutes": 150 + }, + { + "i": 2, + "start": "06:00:00", + "rate": 0, + "minutes": 360 + }, + { + "i": 3, + "start": "09:00:00", + "rate": 0, + "minutes": 600 + }, + { + "i": 4, + "start": "11:30:00", + "rate": 0, + "minutes": 690 + }, + { + "i": 5, + "start": "14:00:00", + "rate": 0, + "minutes": 840 + }, + { + "i": 6, + "start": "18:30:00", + "rate": 0, + "minutes": 1110 + }, + { + "i": 7, + "start": "23:00:00", + "rate": 0, + "minutes": 1380 + } +] diff --git a/lib/oref0-setup/bg_targets_raw.json b/lib/oref0-setup/bg_targets_raw.json new file mode 100644 index 000000000..b7c410929 --- /dev/null +++ b/lib/oref0-setup/bg_targets_raw.json @@ -0,0 +1,30 @@ +{ + "units": "mg/dL", + "targets": [ + { + "high": 120, + "start": "00:00:00", + "low": 110, + "offset": 0, + "i": 0, + "x": 0 + }, + { + "high": 110, + "start": "06:00:00", + "low": 110, + "offset": 360, + "i": 12, + "x": 1 + }, + { + "high": 120, + "start": "20:00:00", + "low": 110, + "offset": 1200, + "i": 40, + "x": 2 + } + ], + "first": 1 +} diff --git a/lib/oref0-setup/cgm-loop.json b/lib/oref0-setup/cgm-loop.json new file mode 100644 index 000000000..78c2c14c3 --- /dev/null +++ b/lib/oref0-setup/cgm-loop.json @@ -0,0 +1,347 @@ +[ + { + "openapscontrib.timezones": { + "path": ".", + "module": "openapscontrib.timezones" + }, + "type": "vendor", + "name": "openapscontrib.timezones" + }, + { + "type": "device", + "tz": { + "vendor": "openapscontrib.timezones", + "extra": "tz.ini" + }, + "name": "tz", + "extra": {} + }, + { + "extra": { + "fields": "", + "cmd": "oref0", + "args": "" + }, + "type": "device", + "name": "oref0", + "oref0": { + "vendor": "openaps.vendors.process", + "extra": "oref0.ini" + } + }, + { + "raw": { + "vendor": "openaps.vendors.process", + "extra": "raw.ini" + }, + "type": "device", + "name": "raw", + "extra": { + "fields": "glucose cal maxraw", + "cmd": "oref0", + "args": "raw" + } + }, + { + "merge": { + "vendor": "openaps.vendors.process", + "extra": "merge.ini" + }, + "type": "device", + "name": "merge", + "extra": { + "fields": "short long", + "cmd": "jq -s \".[0] + .[1]|unique|sort_by(.dateString)|reverse|.[0:288]\"", + "args": "" + } + }, + { + "extra": { + "fields": "file", + "cmd": "jq .[0:2]", + "args": "" + }, + "type": "device", + "name": "first", + "first": { + "vendor": "openaps.vendors.process", + "extra": "first.ini" + } + }, + { + "type": "report", + "name": "monitor/cal.json", + "monitor/cal.json": { + "count": "1", + "use": "nightscout_calibrations", + "reporter": "JSON", + "seconds": "", + "hours": "", + "device": "cgm", + "gaps": "", + "microseconds": "", + "date": "display_time", + "minutes": "" + } + }, + { + "monitor/cal-zoned.json": { + "use": "rezone", + "reporter": "JSON", + "astimezone": "False", + "date": "display_time system_time dateString", + "adjust": "missing", + "input": "monitor/cal.json", + "device": "tz", + "timezone": "" + }, + "type": "report", + "name": "monitor/cal-zoned.json" + }, + { + "monitor/glucose-oref0.json": { + "count": "", + "use": "oref0_glucose", + "no_raw": "False", + "reporter": "JSON", + "seconds": "", + "minutes": "30.0", + "hours": "", + "device": "cgm", + "gaps": "", + "microseconds": "", + "threshold": "100", + "sensor": "", + "date": "display_time", + "glucose": "" + }, + "type": "report", + "name": "monitor/glucose-oref0.json" + }, + { + "monitor/glucose-zoned.json": { + "use": "rezone", + "reporter": "JSON", + "astimezone": "False", + "date": "display_time system_time dateString", + "adjust": "missing", + "input": "monitor/glucose-oref0.json", + "device": "tz", + "timezone": "" + }, + "type": "report", + "name": "monitor/glucose-zoned.json" + }, + { + "monitor/glucose-raw.json": { + "use": "shell", + "reporter": "JSON", + "json_default": "True", + "cal": "monitor/cal.json", + "device": "raw", + "remainder": "", + "maxraw": "120", + "glucose": "monitor/glucose-zoned.json" + }, + "type": "report", + "name": "monitor/glucose-raw.json" + }, + { + "type": "report", + "nightscout/recent-missing-entries.json": { + "oper": "format-recent-type", + "use": "shell", + "reporter": "JSON", + "device": "ns", + "remainder": "tz entries monitor/glucose-zoned-merge.json", + "json_default": "True" + }, + "name": "nightscout/recent-missing-entries.json" + }, + { + "type": "report", + "nightscout/uploaded-entries.json": { + "oper": "upload", + "use": "shell", + "reporter": "JSON", + "device": "ns", + "remainder": "entries.json nightscout/recent-missing-entries.json", + "json_default": "True" + }, + "name": "nightscout/uploaded-entries.json" + }, + { + "nightscout/uploaded-cals.json": { + "oper": "upload", + "use": "shell", + "reporter": "JSON", + "device": "ns", + "remainder": "entries.json monitor/cal-zoned.json", + "json_default": "True" + }, + "type": "report", + "name": "nightscout/uploaded-cals.json" + }, + { + "monitor/glucose-oref0-long.json": { + "count": "", + "use": "oref0_glucose", + "no_raw": "False", + "reporter": "JSON", + "seconds": "", + "minutes": "", + "hours": "4.5", + "device": "cgm", + "gaps": "", + "microseconds": "", + "threshold": "100", + "sensor": "", + "date": "display_time", + "glucose": "" + }, + "type": "report", + "name": "monitor/glucose-oref0-long.json" + }, + { + "monitor/glucose-zoned-long.json": { + "use": "rezone", + "reporter": "JSON", + "astimezone": "False", + "date": "display_time system_time dateString", + "adjust": "missing", + "input": "monitor/glucose-oref0-long.json", + "device": "tz", + "timezone": "" + }, + "type": "report", + "name": "monitor/glucose-zoned-long.json" + }, + { + "monitor/glucose-zoned-merge.json": { + "use": "shell", + "short": "monitor/glucose-zoned.json", + "reporter": "JSON", + "device": "merge", + "remainder": "", + "json_default": "True", + "long": "monitor/glucose-zoned-merge.json" + }, + "type": "report", + "name": "monitor/glucose-zoned-merge.json" + }, + { + "type": "report", + "name": "monitor/glucose-raw-merge.json", + "monitor/glucose-raw-merge.json": { + "use": "shell", + "reporter": "JSON", + "json_default": "True", + "cal": "monitor/cal.json", + "device": "raw", + "remainder": "", + "maxraw": "200", + "glucose": "monitor/glucose-zoned-merge.json" + } + }, + { + "monitor/glucose-zoned-first.json": { + "use": "shell", + "file": "monitor/glucose-zoned-merge.json", + "reporter": "JSON", + "device": "first", + "remainder": "", + "json_default": "True" + }, + "type": "report", + "name": "monitor/glucose-zoned-first.json" + }, + { + "nightscout/uploaded-first.json": { + "oper": "upload", + "use": "shell", + "reporter": "JSON", + "device": "ns", + "remainder": "entries.json monitor/glucose-zoned-first.json", + "json_default": "True" + }, + "type": "report", + "name": "nightscout/uploaded-first.json" + }, + { + "wait-until-expected": { + "command": "! bash -c \"oref0-dex-wait-until-expected monitor/glucose-zoned.json 5.1\"" + }, + "type": "alias", + "name": "wait-until-expected" + }, + { + "type": "alias", + "name": "glucose", + "glucose": { + "command": "report invoke monitor/glucose-oref0.json monitor/glucose-zoned.json monitor/glucose-zoned-merge.json monitor/glucose-raw-merge.json" + } + }, + { + "echo-glucose": { + "command": "! bash -c \"echo \\\">>>>RESULTS<<<<\\\" && json -f monitor/glucose-raw-merge.json -a sgv raw dateString | head -n 3\"" + }, + "type": "alias", + "name": "echo-glucose" + }, + { + "extras": { + "command": "report invoke monitor/cal.json monitor/cal-zoned.json nightscout/uploaded-cals.json" + }, + "type": "alias", + "name": "extras" + }, + { + "maybe-extras": { + "command": "! bash -c \"if (oref0-dex-is-fresh monitor/glucose-zoned.json 3); then openaps extras; else echo \\\"Glucose is not fresh, not pulling extra data\\\"; fi\"" + }, + "type": "alias", + "name": "maybe-extras" + }, + { + "type": "alias", + "name": "upload", + "upload": { + "command": "report invoke nightscout/recent-missing-entries.json nightscout/uploaded-entries.json" + } + }, + { + "type": "alias", + "name": "monitor-cgm", + "monitor-cgm": { + "command": "! bash -c \"openaps wait-until-expected && time openaps glucose && openaps echo-glucose && (openaps upload-first || echo upload first failed) && (openaps upload || echo cgm upload failed) && (openaps maybe-extras || echo cgm extras failed)\"" + } + }, + { + "type": "alias", + "name": "glucose-long", + "glucose-long": { + "command": "report invoke monitor/glucose-oref0-long.json monitor/glucose-zoned-long.json" + } + }, + { + "type": "alias", + "name": "reset-glucose-merge", + "reset-glucose-merge": { + "command": "! bash -c \"openaps glucose-long && rm -f monitor/glucose-zoned-merge.json && cp monitor/glucose-zoned-long.json monitor/glucose-zoned-merge.json && openaps report invoke monitor/glucose-raw-merge.json\"" + } + }, + { + "upload-first": { + "command": "report invoke monitor/glucose-zoned-first.json nightscout/uploaded-first.json" + }, + "type": "alias", + "name": "upload-first" + }, + { + "type": "alias", + "name": "maybe-upload", + "maybe-upload": { + "command": "! bash -c \"if (is-fresh.sh monitor/glucose-zoned.json 4); then openaps upload; else echo \\\"Glucose is not fresh, not doing full upload\\\"; fi\"" + } + } +] diff --git a/lib/oref0-setup/device.json b/lib/oref0-setup/device.json new file mode 100644 index 000000000..ebff5a717 --- /dev/null +++ b/lib/oref0-setup/device.json @@ -0,0 +1,157 @@ +[ + { + "type": "device", + "cgm": { + "vendor": "openaps.vendors.dexcom", + "extra": "cgm.ini" + }, + "name": "cgm", + "extra": {} + }, + { + "ns-glucose": { + "vendor": "openaps.vendors.process", + "extra": "ns-glucose.ini" + }, + "type": "device", + "name": "ns-glucose", + "extra": { + "fields": "", + "cmd": "bash -c \"curl --compressed -m 30 -s $NIGHTSCOUT_HOST/api/v1/entries/sgv.json?count=1000 | json -e \\\"this.glucose = this.sgv\\\"\"", + "args": "" + } + }, + { + "extra": { + "fields": "", + "cmd": "oref0", + "args": "" + }, + "type": "device", + "name": "oref0", + "oref0": { + "vendor": "openaps.vendors.process", + "extra": "oref0.ini" + } + }, + { + "extra": { + "fields": "pumphistory profile clock", + "cmd": "oref0", + "args": "calculate-iob" + }, + "type": "device", + "name": "iob", + "iob": { + "vendor": "openaps.vendors.process", + "extra": "iob.ini" + } + }, + { + "extra": { + "fields": "pumphistory profile clock glucose basal carbs", + "cmd": "oref0", + "args": "meal" + }, + "type": "device", + "name": "meal", + "meal": { + "vendor": "openaps.vendors.process", + "extra": "meal.ini" + } + }, + { + "extra": { + "fields": "settings bg_targets isf basal_profile preferences carb_ratios", + "cmd": "oref0", + "args": "get-profile" + }, + "type": "device", + "name": "get-profile", + "get-profile": { + "vendor": "openaps.vendors.process", + "extra": "get-profile.ini" + } + }, + { + "extra": { + "fields": "glucose pumphistory isf basal_profile profile", + "cmd": "oref0", + "args": "detect-sensitivity" + }, + "type": "device", + "name": "detect-sensitivity", + "detect-sensitivity": { + "vendor": "openaps.vendors.process", + "extra": "detect-sensitivity.ini" + } + }, + { + "determine-basal": { + "vendor": "openaps.vendors.process", + "extra": "determine-basal.ini" + }, + "type": "device", + "name": "determine-basal", + "extra": { + "fields": "iob temp_basal glucose profile", + "cmd": "oref0", + "args": "determine-basal" + } + }, + { + "pebble": { + "vendor": "openaps.vendors.process", + "extra": "pebble.ini" + }, + "type": "device", + "name": "pebble", + "extra": { + "fields": "glucose iob basal_profile temp_basal suggested enacted meal", + "cmd": "oref0", + "args": "pebble" + } + }, + { + "type": "device", + "tz": { + "vendor": "openapscontrib.timezones", + "extra": "tz.ini" + }, + "name": "tz", + "extra": {} + }, + { + "pump": { + "vendor": "openaps.vendors.medtronic", + "extra": "pump.ini" + }, + "type": "device", + "name": "pump", + "extra": { + "serial": "123456" + } + }, + { + "units": { + "vendor": "openaps.vendors.units", + "extra": "units.ini" + }, + "type": "device", + "name": "units", + "extra": {} + }, + { + "xdrip": { + "vendor": "openaps.vendors.process", + "extra": "xdrip.ini" + }, + "type": "device", + "name": "xdrip", + "extra": { + "fields": "", + "cmd": "bash -c \"curl --compressed -s http://localhost:5000/api/v1/entries?count=288 | json -e \\\"this.glucose = this.sgv\\\"\"", + "args": "" + } + } +] diff --git a/lib/oref0-setup/dexcom.json b/lib/oref0-setup/dexcom.json new file mode 100644 index 000000000..9839974c4 --- /dev/null +++ b/lib/oref0-setup/dexcom.json @@ -0,0 +1,11 @@ +[ + { + "type": "device", + "cgm": { + "vendor": "openaps.vendors.dexcom", + "extra": "cgm.ini" + }, + "name": "cgm", + "extra": {} + } +] diff --git a/lib/oref0-setup/edisonbattery.json b/lib/oref0-setup/edisonbattery.json new file mode 100644 index 000000000..eb2c767c7 --- /dev/null +++ b/lib/oref0-setup/edisonbattery.json @@ -0,0 +1,23 @@ +[ +{ + "type": "alias", + "name": "format-ns-status", + "format-ns-status": { + "command": "! bash -c \"ns-status monitor/clock-zoned.json monitor/iob.json enact/suggested.json enact/enacted.json monitor/battery.json monitor/reservoir.json monitor/status.json --uploader monitor/edison-battery.json > upload/ns-status.json\"" + } +}, +{ + "type": "alias", + "name": "battery-status", + "battery-status": { + "command": "! bash -c \"sudo ~/src/EdisonVoltage/voltage json batteryVoltage battery > monitor/edison-battery.json\"" + } + }, + { + "type": "alias", + "name": "ns-loop", + "ns-loop": { + "command": "! bash -c \"echo Starting ns-loop at $(date): && openaps get-ns-bg; openaps ns-temptargets && echo -n Refreshed temptargets && openaps ns-meal-carbs && echo \\\" and meal-carbs\\\" && openaps battery-status; cat monitor/edison-battery.json; echo; openaps upload\"" + } + } +] diff --git a/lib/oref0-setup/mdt-cgm.json b/lib/oref0-setup/mdt-cgm.json new file mode 100644 index 000000000..989cb39c3 --- /dev/null +++ b/lib/oref0-setup/mdt-cgm.json @@ -0,0 +1,148 @@ +[ + { + "type": "vendor", + "name": "openapscontrib.glucosetools", + "openapscontrib.glucosetools": { + "path": ".", + "module": "openapscontrib.glucosetools" + } + }, + { + "extra": {}, + "type": "device", + "name": "glucose", + "glucose": { + "vendor": "openapscontrib.glucosetools", + "extra": "glucose.ini" + } + }, + { + "monitor/cgm-mm-glucosedirty.json": { + "hours": "24.0", + "device": "cgm", + "use": "iter_glucose_hours", + "reporter": "JSON" + }, + "type": "report", + "name": "monitor/cgm-mm-glucosedirty.json" + }, + { + "type": "report", + "name": "cgm/cgm-glucose.json", + "cgm/cgm-glucose.json": { + "use": "clean", + "reporter": "JSON", + "astimezone": "False", + "date": "display_time dateString", + "adjust": "missing", + "input": "raw-cgm/raw-entries.json", + "device": "glucose", + "timezone": "", + "infile": "monitor/cgm-mm-glucosetrend.json" + } + }, + { + "type": "report", + "name": "monitor/cgm-mm-glucosetrend.json", + "monitor/cgm-mm-glucosetrend.json": { + "device": "oref0", + "remainder": "mdt-trend monitor/cgm-mm-glucosedirty.json", + "use": "shell", + "json_default": "True", + "reporter": "JSON" + } + }, + { + "type": "alias", + "name": "monitor-cgm", + "monitor-cgm": { + "command": "report invoke monitor/cgm-mm-glucosedirty.json monitor/cgm-mm-glucosetrend.json cgm/cgm-glucose.json" + } + }, + { + "type": "alias", + "name": "ns-loop", + "ns-loop": { + "command": "! bash -c \"echo Starting ns-loop at $(date): && openaps ns-temptargets && echo -n Refreshed temptargets && openaps ns-meal-carbs && echo \\\" and meal-carbs\\\" && openaps upload\"" + } + }, + { + "pump-loop": { + "command": "! bash -c \"sleep $[ ( $RANDOM / 2048 ) ]s; until(echo Starting pump-loop at $(date): && openaps wait-for-silence && openaps get-bg && openaps refresh-old-pumphistory && openaps refresh-old-pumphistory-24h && openaps refresh-old-profile && openaps refresh-temp-and-enact && openaps refresh-pumphistory-and-enact && openaps refresh-profile && openaps refresh-pumphistory-24h && echo Completed pump-loop at $(date) && echo); do echo Error, retrying && [[ $RANDOM > 25000 ]] && ( openaps wait-for-long-silence ; openaps mmtune; sleep 5 ); done\"" + }, + "type": "alias", + "name": "pump-loop" + }, + { + "type": "report", + "name": "monitor/glucose.json", + "monitor/glucose.json": { + "use": "rezone", + "reporter": "JSON", + "astimezone": "False", + "date": "timestamp dateString start_at end_at created_at display_time", + "adjust": "missing", + "input": "monitor/glucose-unzoned.json", + "device": "tz", + "timezone": "" + } + }, + { + "type": "report", + "nightscout/recent-missing-entries.json": { + "oper": "format-recent-type", + "use": "shell", + "reporter": "JSON", + "device": "ns", + "remainder": "tz entries nightscout/glucose.json", + "json_default": "True" + }, + "name": "nightscout/recent-missing-entries.json" + }, + { + "type": "report", + "nightscout/uploaded-entries.json": { + "oper": "upload", + "use": "shell", + "reporter": "JSON", + "device": "ns", + "remainder": "entries.json nightscout/recent-missing-entries.json", + "json_default": "True" + }, + "name": "nightscout/uploaded-entries.json" + }, + { + "type": "report", + "nightscout/glucose.json": { + "oper": "mm-format-ns-glucose", + "use": "shell", + "reporter": "JSON", + "device": "ns", + "remainder": "monitor/glucose.json", + "json_default": "True" + }, + "name": "nightscout/glucose.json" + }, + { + "get-bg": { + "command": "! bash -c \" (echo -n MDT cgm data retrieve && openaps monitor-cgm 2>/dev/null >/dev/null && grep -q glucose cgm/cgm-glucose.json && echo d) && cp -pu cgm/cgm-glucose.json cgm/glucose.json && cp -pu cgm/glucose.json monitor/glucose-unzoned.json && (echo -n MDT cgm data reformat && openaps report invoke monitor/glucose.json nightscout/glucose.json 2>/dev/null >/dev/null && echo ted)\"" + }, + "type": "alias", + "name": "get-bg" + }, + { + "type": "alias", + "upload-bg": { + "command": "report invoke nightscout/recent-missing-entries.json nightscout/uploaded-entries.json" + }, + "name": "upload-bg" + }, + { + "type": "alias", + "name": "upload", + "upload": { + "command": "! bash -c \"echo -n Upload && ( openaps upload-bg; openaps upload-ns-status; openaps upload-recent-treatments ) 2>/dev/null >/dev/null && echo ed\"" + } + }, + {"type": "alias", "first-upload": {"command": "! bash -c \"cat nightscout/glucose.json | json 1 > nightscout/recent-missing-entries.json && openaps report invoke nightscout/uploaded-entries.json\""}, "name": "first-upload"} +] diff --git a/lib/oref0-setup/pancreabble.json b/lib/oref0-setup/pancreabble.json new file mode 100644 index 000000000..3724b7441 --- /dev/null +++ b/lib/oref0-setup/pancreabble.json @@ -0,0 +1,49 @@ +[ +{ + "pancreabble": { + "path": ".", + "module": "pancreabble" + }, + "type": "vendor", + "name": "pancreabble" + }, + { + "type": "device", + "pbbl": { + "vendor": "pancreabble", + "extra": "pbbl.ini" + }, + "name": "pbbl", + "extra": { + "port": "/dev/rfcomm0" + } + }, + { + "type": "report", + "name": "upload/urchin-data.json", + "upload/urchin-data.json": { + "use": "format_urchin_data", + "reporter": "JSON", + "cgm_clock": "monitor/clock.json", + "action": "add", + "device": "pbbl", + "glucose_history": "monitor/glucose-unzoned.json", + "status_text": "", + "status_json": "upload/urchin-status.json" + } + }, + { + "type": "alias", + "name": "upload-pbbl", + "upload-pbbl": { + "command": "! bash -c \"openaps use pbbl send_urchin_data upload/urchin-data.json\"" + } + }, + { + "urchin-loop": { + "command": "! bash -c \"openaps invoke upload/urchin-data.json && openaps upload-pbbl\"" + }, + "type": "alias", + "name": "urchin-loop" + } +] diff --git a/lib/oref0-setup/pancreoptions.json b/lib/oref0-setup/pancreoptions.json new file mode 100644 index 000000000..c15cb396f --- /dev/null +++ b/lib/oref0-setup/pancreoptions.json @@ -0,0 +1,7 @@ +{ + "urchin_loop_on": true, + "urchin_loop_status": false, + "urchin_iob": true, + "urchin_temp_rate": false, + "notify_temp_basal": false +} diff --git a/lib/oref0-setup/report.json b/lib/oref0-setup/report.json new file mode 100644 index 000000000..392829f9f --- /dev/null +++ b/lib/oref0-setup/report.json @@ -0,0 +1,393 @@ +[ + { + "type": "report", + "settings/temptargets.json": { + "oper": "temp_targets", + "use": "shell", + "reporter": "JSON", + "device": "ns", + "remainder": "-18hours", + "json_default": "True" + }, + "name": "settings/temptargets.json" + }, + { + "type": "report", + "monitor/carbhistory.json": { + "oper": "carb_history", + "use": "shell", + "reporter": "JSON", + "device": "ns", + "remainder": "-36hours", + "json_default": "True" + }, + "name": "monitor/carbhistory.json" + }, + { + "type": "report", + "name": "monitor/cgm-glucose.json", + "monitor/cgm-glucose.json": { + "hours": "25.0", + "device": "cgm", + "use": "iter_glucose_hours", + "reporter": "JSON" + } + }, + { + "type": "report", + "name": "raw-cgm/raw-entries.json", + "raw-cgm/raw-entries.json": { + "count": "", + "use": "oref0_glucose", + "reporter": "JSON", + "seconds": "", + "minutes": "", + "hours": "24", + "device": "cgm", + "gaps": "", + "microseconds": "", + "threshold": "100", + "sensor": "", + "date": "display_time", + "glucose": "" + } + }, + { + "cgm/ns-glucose.json": { + "oper": "oref0_glucose_since", + "use": "shell", + "reporter": "JSON", + "device": "ns", + "remainder": "-24hours", + "json_default": "True" + }, + "type": "report", + "name": "cgm/ns-glucose.json" + }, + { + "type": "report", + "monitor/mmtune.json": { + "device": "pump", + "use": "mmtune", + "reporter": "JSON" + }, + "name": "monitor/mmtune.json" + }, + { + "type": "report", + "settings/model.json": { + "device": "pump", + "use": "model", + "reporter": "JSON" + }, + "name": "settings/model.json" + }, + { + "monitor/clock.json": { + "device": "pump", + "use": "read_clock", + "reporter": "JSON" + }, + "type": "report", + "name": "monitor/clock.json" + }, + { + "type": "report", + "name": "cgm/cgm-glucose.json", + "cgm/cgm-glucose.json": { + "use": "rezone", + "reporter": "JSON", + "astimezone": "False", + "date": "display_time dateString", + "adjust": "missing", + "input": "raw-cgm/raw-entries.json", + "device": "tz", + "timezone": "" + } + }, + { + "monitor/clock-zoned.json": { + "use": "clock", + "reporter": "JSON", + "astimezone": "False", + "date": "None", + "adjust": "missing", + "input": "monitor/clock.json", + "device": "tz", + "timezone": "" + }, + "type": "report", + "name": "monitor/clock-zoned.json" + }, + { + "type": "report", + "name": "monitor/temp_basal.json", + "monitor/temp_basal.json": { + "device": "pump", + "use": "read_temp_basal", + "reporter": "JSON" + } + }, + { + "monitor/reservoir.json": { + "device": "pump", + "use": "reservoir", + "reporter": "JSON" + }, + "type": "report", + "name": "monitor/reservoir.json" + }, + { + "monitor/battery.json": { + "device": "pump", + "use": "read_battery_status", + "reporter": "JSON" + }, + "type": "report", + "name": "monitor/battery.json" + }, + { + "type": "report", + "name": "monitor/status.json", + "monitor/status.json": { + "device": "pump", + "use": "status", + "reporter": "JSON" + } + }, + { + "type": "report", + "name": "monitor/pumphistory.json", + "monitor/pumphistory.json": { + "hours": "2.0", + "device": "pump", + "use": "iter_pump_hours", + "reporter": "JSON" + } + }, + { + "settings/pumphistory-24h.json": { + "hours": "27.0", + "device": "pump", + "use": "iter_pump_hours", + "reporter": "JSON" + }, + "type": "report", + "name": "settings/pumphistory-24h.json" + }, + { + "monitor/pumphistory-zoned.json": { + "use": "rezone", + "reporter": "JSON", + "astimezone": "False", + "date": "timestamp dateString start_at end_at created_at", + "adjust": "missing", + "input": "monitor/pumphistory.json", + "device": "tz", + "timezone": "" + }, + "type": "report", + "name": "monitor/pumphistory-zoned.json" + }, + { + "type": "report", + "name": "settings/pumphistory-24h-zoned.json", + "settings/pumphistory-24h-zoned.json": { + "use": "rezone", + "reporter": "JSON", + "astimezone": "False", + "date": "timestamp dateString start_at end_at created_at", + "adjust": "missing", + "input": "settings/pumphistory-24h.json", + "device": "tz", + "timezone": "" + } + }, + { + "type": "report", + "name": "monitor/iob.json", + "monitor/iob.json": { + "profile": "settings/profile.json", + "use": "shell", + "clock": "monitor/clock-zoned.json", + "reporter": "text", + "json_default": "True", + "pumphistory": "monitor/pumphistory-merged.json", + "device": "iob", + "remainder": "settings/autosens.json" + } + }, + { + "type": "report", + "name": "monitor/meal.json", + "monitor/meal.json": { + "profile": "settings/profile.json", + "glucose": "monitor/glucose.json", + "clock": "monitor/clock-zoned.json", + "reporter": "text", + "json_default": "True", + "use": "shell", + "pumphistory": "monitor/pumphistory-merged.json", + "carbs": "monitor/carbhistory.json", + "device": "meal", + "remainder": "", + "basal": "settings/basal_profile.json" + } + }, + { + "type": "report", + "settings/autosens.json": { + "profile": "settings/profile.json", + "use": "shell", + "reporter": "text", + "basal_profile": "settings/basal_profile.json", + "json_default": "True", + "pumphistory": "settings/pumphistory-24h-zoned.json", + "device": "detect-sensitivity", + "remainder": "monitor/carbhistory.json settings/temptargets.json", + "isf": "settings/insulin_sensitivities.json", + "glucose": "monitor/glucose.json" + }, + "name": "settings/autosens.json" + }, + { + "type": "report", + "settings/bg_targets.json": { + "device": "units", + "to": "mg/dL", + "use": "bg_targets", + "input": "settings/bg_targets_raw.json", + "reporter": "JSON" + }, + "name": "settings/bg_targets.json" + }, + { + "settings/insulin_sensitivities.json": { + "device": "units", + "to": "mg/dL", + "use": "insulin_sensitivities", + "input": "settings/insulin_sensitivities_raw.json", + "reporter": "JSON" + }, + "type": "report", + "name": "settings/insulin_sensitivities.json" + }, + { + "settings/carb_ratios.json": { + "device": "pump", + "use": "read_carb_ratios", + "reporter": "JSON" + }, + "type": "report", + "name": "settings/carb_ratios.json" + }, + { + "settings/basal_profile.json": { + "device": "pump", + "use": "read_selected_basal_profile", + "reporter": "JSON" + }, + "type": "report", + "name": "settings/basal_profile.json" + }, + { + "settings/settings.json": { + "device": "pump", + "use": "read_settings", + "reporter": "JSON" + }, + "type": "report", + "name": "settings/settings.json" + }, + { + "settings/profile.json": { + "use": "shell", + "bg_targets": "settings/bg_targets.json", + "preferences": "preferences.json", + "settings": "settings/settings.json", + "basal_profile": "settings/basal_profile.json", + "reporter": "text", + "json_default": "True", + "carb_ratios": "settings/carb_ratios.json", + "device": "get-profile", + "remainder": "settings/temptargets.json --model=settings/model.json", + "isf": "settings/insulin_sensitivities.json" + }, + "type": "report", + "name": "settings/profile.json" + }, + { + "type": "report", + "name": "enact/suggested.json", + "enact/suggested.json": { + "profile": "settings/profile.json", + "use": "shell", + "temp_basal": "monitor/temp_basal.json", + "reporter": "text", + "json_default": "True", + "meal": "monitor/meal.json", + "autosens": "settings/autosens.json", + "device": "determine-basal", + "remainder": "", + "iob": "monitor/iob.json", + "glucose": "monitor/glucose.json" + } + }, + { + "type": "report", + "enact/enacted.json": { + "device": "pump", + "input": "enact/suggested.json", + "use": "set_temp_basal", + "reporter": "JSON" + }, + "name": "enact/enacted.json" + }, + { + "type": "report", + "upload/pebble.json": { + "suggested": "enact/suggested.json", + "use": "shell", + "temp_basal": "monitor/temp_basal.json", + "reporter": "text", + "basal_profile": "settings/basal_profile.json", + "json_default": "True", + "meal": "monitor/meal.json", + "device": "pebble", + "enacted": "enact/enacted.json", + "remainder": "", + "iob": "monitor/iob.json", + "glucose": "monitor/glucose.json" + }, + "name": "upload/pebble.json" + }, + { + "type": "report", + "name": "settings/bg_targets_raw.json", + "settings/bg_targets_raw.json": { + "device": "pump", + "use": "read_bg_targets", + "reporter": "JSON" + } + }, + { + "settings/insulin_sensitivities_raw.json": { + "device": "pump", + "use": "read_insulin_sensitivities", + "reporter": "JSON" + }, + "type": "report", + "name": "settings/insulin_sensitivities_raw.json" + }, + { + "type": "report", + "name": "xdrip/glucose.json", + "xdrip/glucose.json": { + "device": "xdrip", + "remainder": "", + "use": "shell", + "json_default": "True", + "reporter": "text" + } + } +] diff --git a/lib/oref0-setup/settings.json b/lib/oref0-setup/settings.json new file mode 100644 index 000000000..875328d7d --- /dev/null +++ b/lib/oref0-setup/settings.json @@ -0,0 +1,8 @@ +{ + "maxBasal": 1.5, + "temp_basal": { + "percent": 100, + "type": "Units/hour" + }, + "insulin_action_curve": 6 +} diff --git a/lib/oref0-setup/shareble.json b/lib/oref0-setup/shareble.json new file mode 100644 index 000000000..451b94eec --- /dev/null +++ b/lib/oref0-setup/shareble.json @@ -0,0 +1,19 @@ +[ + { + "type": "vendor", + "name": "openxshareble", + "openxshareble": { + "path": ".", + "module": "openxshareble" + } + }, + { + "type": "device", + "cgm": { + "vendor": "openxshareble", + "extra": "cgm.ini" + }, + "name": "cgm", + "extra": {} + } +] diff --git a/lib/oref0-setup/supermicrobolus.json b/lib/oref0-setup/supermicrobolus.json new file mode 100644 index 000000000..86d117ecc --- /dev/null +++ b/lib/oref0-setup/supermicrobolus.json @@ -0,0 +1,37 @@ +[ + { + "enact/smb-suggested.json": { + "profile": "settings/profile.json", + "use": "shell", + "temp_basal": "monitor/temp_basal.json", + "reporter": "JSON", + "json_default": "True", + "device": "determine-basal", + "remainder": "settings/autosens.json monitor/meal.json --microbolus --reservoir monitor/reservoir.json", + "iob": "monitor/iob.json", + "glucose": "monitor/glucose.json" + }, + "type": "report", + "name": "enact/smb-suggested.json" + }, + { + "enact/smb-enacted.json": { + "device": "pump", + "input": "enact/smb-suggested.json", + "use": "set_temp_basal", + "reporter": "JSON" + }, + "type": "report", + "name": "enact/smb-enacted.json" + }, + { + "enact/bolused.json": { + "device": "pump", + "input": "enact/smb-suggested.json", + "use": "bolus", + "reporter": "JSON" + }, + "type": "report", + "name": "enact/bolused.json" + } +] diff --git a/lib/oref0-setup/vendor.json b/lib/oref0-setup/vendor.json new file mode 100644 index 000000000..dc1364652 --- /dev/null +++ b/lib/oref0-setup/vendor.json @@ -0,0 +1,18 @@ +[ + { + "openapscontrib.timezones": { + "path": ".", + "module": "openapscontrib.timezones" + }, + "type": "vendor", + "name": "openapscontrib.timezones" + }, + { + "type": "vendor", + "name": "mmeowlink.vendors.mmeowlink", + "mmeowlink.vendors.mmeowlink": { + "path": ".", + "module": "mmeowlink.vendors.mmeowlink" + } + } +] diff --git a/lib/oref0-setup/xdrip-cgm.json b/lib/oref0-setup/xdrip-cgm.json new file mode 100644 index 000000000..92579d6bd --- /dev/null +++ b/lib/oref0-setup/xdrip-cgm.json @@ -0,0 +1,41 @@ +[ + { + "type": "report", + "nightscout/recent-missing-entries.json": { + "oper": "format-recent-type", + "use": "shell", + "reporter": "JSON", + "device": "ns", + "remainder": "tz entries monitor/glucose.json", + "json_default": "True" + }, + "name": "nightscout/recent-missing-entries.json" + }, + { + "type": "report", + "nightscout/uploaded-entries.json": { + "oper": "upload", + "use": "shell", + "reporter": "JSON", + "device": "ns", + "remainder": "entries.json nightscout/recent-missing-entries.json", + "json_default": "True" + }, + "name": "nightscout/uploaded-entries.json" + }, + { + "type": "alias", + "upload-bg": { + "command": "report invoke nightscout/recent-missing-entries.json nightscout/uploaded-entries.json" + }, + "name": "upload-bg" + }, + { + "type": "alias", + "name": "upload", + "upload": { + "command": "! bash -c \"echo -n Upload && ( openaps upload-bg; openaps upload-ns-status; openaps upload-pumphistory-entries; openaps upload-recent-treatments ) 2>/dev/null >/dev/null && echo ed\"" + } + }, + {"type": "alias", "first-upload": {"command": "! bash -c \"cat monitor/glucose.json | json 1 > nightscout/recent-missing-entries.json && openaps report invoke nightscout/uploaded-entries.json\""}, "name": "first-upload"} +] diff --git a/lib/profile/basal.js b/lib/profile/basal.js index 6cbda113f..9694d3203 100644 --- a/lib/profile/basal.js +++ b/lib/profile/basal.js @@ -1,14 +1,25 @@ -var getTime = require('../medtronic-clock'); +var _ = require('lodash'); /* Return basal rate(U / hr) at the provided timeOfDay */ -function basalLookup (schedules) { - var basalprofile_data = schedules; - var now = new Date(); +function basalLookup (schedules, now) { + + var nowDate = now; + + if (typeof(now) === 'undefined') { + nowDate = new Date(); + } + + var basalprofile_data = _.sortBy(schedules, function(o) { return o.i; }); var basalRate = basalprofile_data[basalprofile_data.length-1].rate - + if (basalRate == 0) { + console.error("ERROR: bad basal schedule",schedules); + return; + } + var nowMinutes = nowDate.getHours() * 60 + nowDate.getMinutes(); + for (var i = 0; i < basalprofile_data.length - 1; i++) { - if ((now >= getTime(basalprofile_data[i].minutes)) && (now < getTime(basalprofile_data[i + 1].minutes))) { + if ((nowMinutes >= basalprofile_data[i].minutes) && (nowMinutes < basalprofile_data[i + 1].minutes)) { basalRate = basalprofile_data[i].rate; break; } @@ -18,15 +29,13 @@ function basalLookup (schedules) { function maxDailyBasal (inputs) { - var basalprofile_data = inputs.basals; - basalprofile_data.sort(function (a, b) { if (a.rate < b.rate) { return 1 } if (a.rate > b.rate) { return -1; } return 0; }); - return Math.round( basalprofile_data[0].rate *1000)/1000; + var maxRate = _.maxBy(inputs.basals,function(o) { return Number(o.rate); }); + return (Number(maxRate.rate) *1000)/1000; } /*Return maximum daily basal rate(U / hr) from profile.basals */ function maxBasalLookup (inputs) { - return inputs.settings.maxBasal; } diff --git a/lib/profile/carbs.js b/lib/profile/carbs.js index 74cc503f4..31dfae6cc 100644 --- a/lib/profile/carbs.js +++ b/lib/profile/carbs.js @@ -1,20 +1,37 @@ var getTime = require('../medtronic-clock'); -function carbRatioLookup (inputs) { +function carbRatioLookup (inputs, profile) { var now = new Date(); - var carbratio_data = inputs.carbs; - //carbratio_data.schedule.sort(function (a, b) { return a.offset > b.offset }); - var carbRatio = carbratio_data.schedule[carbratio_data.schedule.length - 1] - - for (var i = 0; i < carbratio_data.schedule.length - 1; i++) { - if ((now >= getTime(carbratio_data.schedule[i].offset)) && (now < getTime(carbratio_data.schedule[i + 1].offset))) { - carbRatio = carbratio_data.schedule[i]; - break; + var carbratio_data = inputs.carbratio; + if (typeof(carbratio_data) != "undefined" && typeof(carbratio_data.schedule) != "undefined") { + var carbRatio; + if ((carbratio_data.units == "grams") || (carbratio_data.units == "exchanges")) { + //carbratio_data.schedule.sort(function (a, b) { return a.offset > b.offset }); + carbRatio = carbratio_data.schedule[carbratio_data.schedule.length - 1]; + + for (var i = 0; i < carbratio_data.schedule.length - 1; i++) { + if ((now >= getTime(carbratio_data.schedule[i].offset)) && (now < getTime(carbratio_data.schedule[i + 1].offset))) { + carbRatio = carbratio_data.schedule[i]; + // disallow impossibly high/low carbRatios due to bad decoding + if (carbRatio < 3 || carbRatio > 150) { + console.error("Error: carbRatio of " + carbRatio + " out of bounds."); + return; + } + break; + } + } + if (carbratio_data.units == "exchanges") { + carbRatio.ratio = 12 / carbRatio.ratio + } + return carbRatio.ratio; + } else { + console.error("Error: Unsupported carb_ratio units " + carbratio_data.units); + return; } - } - return carbRatio.ratio; - profile.carbratio = carbRatio.ratio; + //return carbRatio.ratio; + //profile.carbratio = carbRatio.ratio; + } else { return; } } carbRatioLookup.carbRatioLookup = carbRatioLookup; diff --git a/lib/profile/index.js b/lib/profile/index.js index c256729e8..5f347ca43 100644 --- a/lib/profile/index.js +++ b/lib/profile/index.js @@ -2,41 +2,174 @@ var basal = require('./basal'); var targets = require('./targets'); var isf = require('./isf'); +var carb_ratios = require('./carbs'); +var _ = require('lodash'); function defaults ( ) { - var profile = { - max_iob: 0 // if max_iob.json is not profided, never give more insulin than the pump would have - // , dia: pumpsettings_data.insulin_action_curve - , type: "current" - }; - return profile; + var profile = { + max_iob: 0 // if max_iob is not provided, will default to zero + , max_daily_safety_multiplier: 3 + , current_basal_safety_multiplier: 4 + , autosens_max: 1.2 + , autosens_min: 0.7 + , rewind_resets_autosens: true // reset autosensitivity to neutral for awhile after each pump rewind + // , autosens_adjust_targets: false // when autosens detects sensitivity/resistance, also adjust BG target accordingly + , high_temptarget_raises_sensitivity: false // raise sensitivity for temptargets >= 111. synonym for exercise_mode + , low_temptarget_lowers_sensitivity: false // lower sensitivity for temptargets <= 99. + , sensitivity_raises_target: true // raise BG target when autosens detects sensitivity + , resistance_lowers_target: false // lower BG target when autosens detects resistance + , adv_target_adjustments: false // lower target automatically when BG and eventualBG are high + , exercise_mode: false // when true, > 105 mg/dL high temp target adjusts sensitivityRatio for exercise_mode. This majorly changes the behavior of high temp targets from before. synonmym for high_temptarget_raises_sensitivity + , half_basal_exercise_target: 160 // when temptarget is 160 mg/dL *and* exercise_mode=true, run 50% basal at this level (120 = 75%; 140 = 60%) + // create maxCOB and default it 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/SMB as a safety cap against excessive COB entry) + , maxCOB: 120 + , wide_bg_target_range: false // by default use only the low end of the pump's BG target range as OpenAPS target + // by default the higher end of the target range is used only for avoiding bolus wizard overcorrections + // use wide_bg_target_range: true to force neutral temps over a wider range of eventualBGs + , skip_neutral_temps: false // if true, don't set neutral temps + , unsuspend_if_no_temp: false // if true, pump will un-suspend after a zero temp finishes + , bolussnooze_dia_divisor: 2 // bolus snooze decays after 1/2 of DIA + , min_5m_carbimpact: 8 // mg/dL per 5m (8 mg/dL/5m corresponds to 24g/hr at a CSF of 4 mg/dL/g (x/5*60/4)) + , autotune_isf_adjustmentFraction: 1.0 // keep autotune ISF closer to pump ISF via a weighted average of fullNewISF and pumpISF. 1.0 allows full adjustment, 0 is no adjustment from pump ISF. + , remainingCarbsFraction: 1.0 // fraction of carbs we'll assume will absorb over 4h if we don't yet see carb absorption + , remainingCarbsCap: 90 // max carbs we'll assume will absorb over 4h if we don't yet see carb absorption + // WARNING: use SMB with caution: it can and will automatically bolus up to max_iob worth of extra insulin + , enableUAM: true // enable detection of unannounced meal carb absorption + , A52_risk_enable: false + , enableSMB_with_COB: false // enable supermicrobolus while COB is positive + , enableSMB_with_temptarget: false // enable supermicrobolus for eating soon temp targets + // *** WARNING *** DO NOT USE enableSMB_always or enableSMB_after_carbs with Libre or similar + // LimiTTer, etc. do not properly filter out high-noise SGVs. xDrip+ builds greater than or equal to + // version number d8e-7097-2018-01-22 provide proper noise values, so that oref0 can ignore high noise + // readings, and can temporarily raise the BG target when sensor readings have medium noise, + // resulting in appropriate SMB behaviour. Older versions of xDrip+ should not be used with enableSMB_always. + // Using SMB overnight with such data sources risks causing a dangerous overdose of insulin + // if the CGM sensor reads falsely high and doesn't come down as actual BG does + , enableSMB_always: false // always enable supermicrobolus (unless disabled by high temptarget) + , enableSMB_after_carbs: false // enable supermicrobolus for 6h after carbs, even with 0 COB + // *** WARNING *** DO NOT USE enableSMB_always or enableSMB_after_carbs with Libre or similar. + , allowSMB_with_high_temptarget: false // allow supermicrobolus (if otherwise enabled) even with high temp targets + , maxSMBBasalMinutes: 30 // maximum minutes of basal that can be delivered as a single SMB with uncovered COB + , maxUAMSMBBasalMinutes: 30 // maximum minutes of basal that can be delivered as a single SMB when IOB exceeds COB + , curve: "rapid-acting" // change this to "ultra-rapid" for Fiasp, or "bilinear" for old curve + , useCustomPeakTime: false // allows changing insulinPeakTime + , insulinPeakTime: 75 // number of minutes after a bolus activity peaks. defaults to 55m for Fiasp if useCustomPeakTime: false + , carbsReqThreshold: 1 // grams of carbsReq to trigger a pushover + , offline_hotspot: false // enabled an offline-only local wifi hotspot if no Internet available + , noisyCGMTargetMultiplier: 1.3 // increase target by this amount when looping off raw/noisy CGM data + , suspend_zeros_iob: true // recognize pump suspends as non insulin delivery events + // TODO: make maxRaw a preference here usable by oref0-raw in myopenaps-cgm-loop + //, maxRaw: 200 // highest raw/noisy CGM value considered safe to use for looping + }; + return profile; +} + +function displayedDefaults () { + var allDefaults = defaults(); + var profile = { }; + + profile.max_iob = allDefaults.max_iob; + profile.max_daily_safety_multiplier = allDefaults.max_daily_safety_multiplier; + profile.current_basal_safety_multiplier= allDefaults.current_basal_safety_multiplier; + profile.autosens_max = allDefaults.autosens_max; + profile.autosens_min = allDefaults.autosens_min; + profile.rewind_resets_autosens = allDefaults.rewind_resets_autosens; + profile.adv_target_adjustments = allDefaults.adv_target_adjustments; + profile.exercise_mode = allDefaults.exercise_mode; + profile.wide_bg_target_range = allDefaults.wide_bg_target_range; + profile.sensitivity_raises_target = allDefaults.sensitivity_raises_target; + profile.unsuspend_if_no_temp = allDefaults.unsuspend_if_no_temp; + profile.enableSMB_with_COB = allDefaults.enableSMB_with_COB; + profile.enableSMB_with_temptarget = allDefaults.enableSMB_with_temptarget; + profile.enableUAM = allDefaults.enableUAM; + profile.curve = allDefaults.curve; + profile.offline_hotspot = allDefaults.offline_hotspot; + + console.error(profile); + return profile } function generate (inputs, opts) { var profile = opts && opts.type ? opts : defaults( ); + // check if inputs has overrides for any of the default prefs + // and apply if applicable + for (var pref in profile) { + if (inputs.hasOwnProperty(pref)) { + profile[pref] = inputs[pref]; + } + } + var pumpsettings_data = inputs.settings; - if (inputs.settings.insulin_action_curve) { + if (inputs.settings.insulin_action_curve > 1) { profile.dia = pumpsettings_data.insulin_action_curve; + } else { + console.error('DIA of', profile.dia, 'is not supported'); + return -1; } - if (inputs.max_iob) { - profile.max_iob = inputs.max_iob; + if (inputs.model) { + profile.model = inputs.model; } + profile.skip_neutral_temps = inputs.skip_neutral_temps; profile.current_basal = basal.basalLookup(inputs.basals); + profile.basalprofile = inputs.basals; + + _.forEach(profile.basalprofile, function(basalentry) { + basalentry.rate = +(Math.round(basalentry.rate + "e+3") + "e-3"); + }); + profile.max_daily_basal = basal.maxDailyBasal(inputs); profile.max_basal = basal.maxBasalLookup(inputs); + if (profile.current_basal === 0) { + console.error("current_basal of",profile.current_basal,"is not supported"); + return -1; + } + if (profile.max_daily_basal === 0) { + console.error("max_daily_basal of",profile.max_daily_basal,"is not supported"); + return -1; + } + if (profile.max_basal < 0.1) { + console.error("max_basal of",profile.max_basal,"is not supported"); + return -1; + } - var range = targets.bgTargetsLookup(inputs); - profile.min_bg = range.min_bg; - profile.max_bg = range.max_bg; - profile.sens = isf.isfLookup(inputs); - + var range = targets.bgTargetsLookup(inputs, profile); + profile.out_units = inputs.targets.user_preferred_units; + profile.min_bg = Math.round(range.min_bg); + profile.max_bg = Math.round(range.max_bg); + profile.bg_targets = inputs.targets; + + _.forEach(profile.bg_targets.targets, function(bg_entry) { + bg_entry.high = Math.round(bg_entry.high); + bg_entry.low = Math.round(bg_entry.low); + bg_entry.min_bg = Math.round(bg_entry.min_bg); + bg_entry.max_bg = Math.round(bg_entry.max_bg); + }); + + delete profile.bg_targets.raw; + + profile.temptargetSet = range.temptargetSet; + profile.sens = isf.isfLookup(inputs.isf); + profile.isfProfile = inputs.isf; + if (profile.sens < 5) { + console.error("ISF of",profile.sens,"is not supported"); + return -1; + } + if (typeof(inputs.carbratio) != "undefined") { + profile.carb_ratio = carb_ratios.carbRatioLookup(inputs, profile); + profile.carb_ratios = inputs.carbratio; + } else { + console.error("Profile wasn't given carb ratio data, cannot calculate carb_ratio"); + } return profile; } generate.defaults = defaults; +generate.displayedDefaults = displayedDefaults; exports = module.exports = generate; diff --git a/lib/profile/isf.js b/lib/profile/isf.js index e97504f88..9bb105007 100644 --- a/lib/profile/isf.js +++ b/lib/profile/isf.js @@ -1,18 +1,45 @@ -var getTime = require('../medtronic-clock'); - -function isfLookup (inputs) { - var now = new Date(); - var isf_data = inputs.isf; - //isf_data.sensitivities.sort(function (a, b) { return a.offset > b.offset }); - var isfSchedule = isf_data.sensitivities[isf_data.sensitivities.length - 1] - - for (var i = 0; i < isf_data.sensitivities.length - 1; i++) { - if ((now >= getTime(isf_data.sensitivities[i].offset)) && (now < getTime(isf_data.sensitivities[i + 1].offset))) { - isfSchedule = isf_data.sensitivities[i]; +var _ = require('lodash'); + +var lastResult = null; + +function isfLookup(isf_data, timestamp) { + + var nowDate = timestamp; + + if (typeof(timestamp) === 'undefined') { + nowDate = new Date(); + } + + var nowMinutes = nowDate.getHours() * 60 + nowDate.getMinutes(); + + if (lastResult && nowMinutes >= lastResult.offset && nowMinutes < lastResult.endOffset) { + return lastResult.sensitivity; + } + + isf_data = _.sortBy(isf_data.sensitivities, function(o) { return o.offset; }); + + var isfSchedule = isf_data[isf_data.length - 1]; + + if (isf_data[0].offset != 0 || isf_data[0].i != 0 || isf_data[0].x != 0 || isf_data[0].start != "00:00:00") { + return -1; + } + + var endMinutes = 1440; + + for (var i = 0; i < isf_data.length - 1; i++) { + var currentISF = isf_data[i]; + var nextISF = isf_data[i+1]; + if (nowMinutes >= currentISF.offset && nowMinutes < nextISF.offset) { + endMinutes = nextISF.offset; + isfSchedule = isf_data[i]; break; } } + + lastResult = isfSchedule; + lastResult.endOffset = endMinutes; + return isfSchedule.sensitivity; } diff --git a/lib/profile/targets.js b/lib/profile/targets.js index b3e7a2a4b..d2c7b8dbc 100644 --- a/lib/profile/targets.js +++ b/lib/profile/targets.js @@ -1,17 +1,18 @@ var getTime = require('../medtronic-clock'); -function bgTargetsLookup (inputs) { - return bound_target_range(lookup(inputs)); +function bgTargetsLookup (inputs, profile) { + return bound_target_range(lookup(inputs, profile)); } -function lookup (inputs) { +function lookup (inputs, profile) { var bgtargets_data = inputs.targets; + var temptargets_data = inputs.temptargets; var now = new Date(); //bgtargets_data.targets.sort(function (a, b) { return a.offset > b.offset }); - var bgTargets = bgtargets_data.targets[bgtargets_data.targets.length - 1] + var bgTargets = bgtargets_data.targets[bgtargets_data.targets.length - 1]; for (var i = 0; i < bgtargets_data.targets.length - 1; i++) { if ((now >= getTime(bgtargets_data.targets[i].offset)) && (now < getTime(bgtargets_data.targets[i + 1].offset))) { @@ -20,15 +21,56 @@ function lookup (inputs) { } } + if (profile.wide_bg_target_range) { + console.error('Allowing wide eventualBG target range: ' + bgTargets.low + ' - ' + bgTargets.high ); + } else { + bgTargets.high = bgTargets.low; + } + + var tempTargets = bgTargets; + + // sort tempTargets by date so we can process most recent first + try { + temptargets_data.sort(function (a, b) { return new Date(a.created_at) < new Date(b.created_at) }); + } catch (e) { + console.error("No temptargets found."); + } + //console.error(temptargets_data); + //console.error(now); + for (var i = 0; i < temptargets_data.length; i++) { + start = new Date(temptargets_data[i].created_at); + //console.error(start); + 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 + //console.error(temptargets_data[i]); + tempTargets = bgTargets; + break; + } else if (now >= new Date(temptargets_data[i].created_at) && now < expires ) { + //console.error(temptargets_data[i]); + tempTargets.high = temptargets_data[i].targetTop; + tempTargets.low = temptargets_data[i].targetBottom; + tempTargets.temptargetSet = true; + break; + } + } + bgTargets = tempTargets; + //console.error(bgTargets); + return bgTargets; } function bound_target_range (target) { + // if targets are < 20, assume for safety that they're intended to be mmol/L, and convert to mg/dL + if ( target.high < 20 ) { target.high = target.high * 18; } + if ( target.low < 20 ) { target.low = target.low * 18; } // hard-code lower bounds for min_bg and max_bg in case pump is set too low, or units are wrong - target.max_bg = Math.max(100, target.high); - target.min_bg = Math.max(90, target.low); + target.max_bg = Math.max(80, target.high); + target.min_bg = Math.max(80, target.low); // hard-code upper bound for min_bg in case pump is set too high target.min_bg = Math.min(200, target.min_bg); + target.max_bg = Math.min(200, target.max_bg); return target } diff --git a/lib/pump.js b/lib/pump.js index 3e02e5102..65b7539c4 100644 --- a/lib/pump.js +++ b/lib/pump.js @@ -7,10 +7,17 @@ function translate (treatments) { var invalid = false; switch (current._type) { case 'CalBGForPH': - current.eventType = ''; + current.eventType = 'BG Check'; current.glucose = current.amount; current.glucoseType = 'Finger'; - current.notes = "Pump received finger stick."; + break; + case 'BasalProfileStart': + case 'ResultDailyTotal': + case 'BGReceived': + case 'Sara6E': + case 'Model522ResultTotals': + case 'Model722ResultTotals': + invalid = true; break; default: break; diff --git a/lib/require-utils.js b/lib/require-utils.js new file mode 100644 index 000000000..6081e7e28 --- /dev/null +++ b/lib/require-utils.js @@ -0,0 +1,31 @@ +'use strict'; + +var fs = require('fs'); + +function safeRequire (path) { + var resolved; + + try { + resolved = require(path); + } catch (e) { + console.error("Could not require: " + path, e); + } + + return resolved; +} + +function requireWithTimestamp (path) { + var resolved = safeRequire(path); + + if (resolved) { + resolved.timestamp = fs.statSync(path).mtime; + } + + return resolved; +} + + +module.exports = { + safeRequire: safeRequire + , requireWithTimestamp: requireWithTimestamp +}; \ No newline at end of file diff --git a/lib/round-basal.js b/lib/round-basal.js new file mode 100644 index 000000000..39d286a53 --- /dev/null +++ b/lib/round-basal.js @@ -0,0 +1,46 @@ +var endsWith = function endsWith(text, val) { + return text.indexOf(val, text.length - val.length) !== -1; +} + +var round_basal = function round_basal(basal, profile) { + + /* x23 and x54 pumps change basal increment depending on how much basal is being delivered: + 0.025u for 0.025 < x < 0.975 + 0.05u for 1 < x < 9.95 + 0.1u for 10 < x + To round numbers nicely for the pump, use a scale factor of (1 / increment). */ + + var lowest_rate_scale = 20; + + // Has profile even been passed in? + if (typeof profile !== 'undefined') + { + // Make sure optional model has been set + if (typeof profile.model == 'string') + { + if (endsWith(profile.model, "54") || endsWith(profile.model, "23")) + { + lowest_rate_scale = 40; + } + } + } + + var rounded_result = basal; + // Shouldn't need to check against 0 as pumps can't deliver negative basal anyway? + if (basal < 1) + { + rounded_basal = Math.round(basal * lowest_rate_scale) / lowest_rate_scale; + } + else if (basal < 10) + { + rounded_basal = Math.round(basal * 20) / 20; + } + else + { + rounded_basal = Math.round(basal * 10) / 10; + } + + return rounded_basal; +} + +exports = module.exports = round_basal diff --git a/lib/with-raw-glucose.js b/lib/with-raw-glucose.js new file mode 100644 index 000000000..303e8d426 --- /dev/null +++ b/lib/with-raw-glucose.js @@ -0,0 +1,53 @@ +'use strict'; + +function cleanCal (cal) { + var clean = { + scale: parseFloat(cal.scale) || 0 + , intercept: parseFloat(cal.intercept) || 0 + , slope: parseFloat(cal.slope) || 0 + }; + + clean.valid = ! (clean.slope === 0 || clean.unfiltered === 0 || clean.scale === 0); + + return clean; +} + +module.exports = function withRawGlucose (entry, cals, maxRaw) { + var maxRaw = maxRaw || 200; + + var egv = entry.glucose || entry.sgv || 0; + + entry.unfiltered = parseInt(entry.unfiltered) || 0; + entry.filtered = parseInt(entry.filtered) || 0; + + //TODO: add time check, but how recent should it be? + //TODO: currently assuming the first is the best (and that there is probably just 1 cal) + var cal = cals && cals.length > 0 && cleanCal(cals[0]); + + if (cal && cal.valid) { + if (cal.filtered === 0 || egv < 40) { + entry.raw = Math.round(cal.scale * (entry.unfiltered - cal.intercept) / cal.slope); + } else { + var ratio = cal.scale * (entry.filtered - cal.intercept) / cal.slope / egv; + entry.raw = Math.round(cal.scale * (entry.unfiltered - cal.intercept) / cal.slope / ratio); + } + + if ( egv < 40 ) { + if (entry.raw) { + entry.glucose = entry.raw; + entry.fromRaw = true; + if (entry.raw <= maxRaw) { + entry.noise = 2; + } else { + entry.noise = 3; + } + } else { + entry.noise = 3; + } + } else if (! entry.noise) { + entry.noise = 0; + } + + } + return entry; +}; diff --git a/logrotate.openaps b/logrotate.openaps index ab14ff9d5..a83fd8041 100644 --- a/logrotate.openaps +++ b/logrotate.openaps @@ -14,7 +14,7 @@ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # -/var/log/openaps/loop.log { +/var/log/openaps/*.log { rotate 30 daily size 10M diff --git a/logrotate.rsyslog b/logrotate.rsyslog index 7088f2fc2..1c2c71a82 100644 --- a/logrotate.rsyslog +++ b/logrotate.rsyslog @@ -14,9 +14,8 @@ /var/log/syslog { - rotate 24 - daily - size 10M + rotate 3 + size 5M missingok notifempty delaycompress @@ -39,9 +38,8 @@ /var/log/debug /var/log/messages { - rotate 24 - daily - size 10M + rotate 3 + size 5M missingok notifempty compress diff --git a/package.json b/package.json index a9786ae4e..9356a1b17 100644 --- a/package.json +++ b/package.json @@ -1,9 +1,10 @@ { "name": "oref0", - "version": "0.1.2", + "version": "0.6.2", "description": "openaps oref0 reference implementation of the reference design", "scripts": { - "test": "make test" + "test": "make test", + "global-install": "npm install && sudo npm install -g && sudo npm link && sudo npm link oref0" }, "repository": { "type": "git", @@ -12,43 +13,95 @@ "keywords": [ "openaps" ], - "author": "Scott Leibrand, OpenAPS contributors", + "author": "Scott Leibrand, Dana Lewis, OpenAPS contributors", "license": "MIT", "bugs": { "url": "https://github.com/openaps/oref0/issues" }, "bin": { - "oref0-calculate-iob": "./bin/oref0-calculate-iob.js", - "oref0-find-insulin-uses": "./bin/oref0-find-insulin-uses.js", - "oref0-determine-basal": "./bin/oref0-determine-basal.js", - "oref0-normalize-temps": "./bin/oref0-normalize-temps.js", - "send-tempbasal-Azure": "./bin/send-tempbasal-Azure.js", - "oref0-get-profile": "./bin/oref0-get-profile.js", - "oref0-mint-max-iob": "./bin/oref0-mint-max-iob.sh", - "oref0-ifttt-notify": "./bin/oref0-ifttt-notify", - "oref0-reset-usb": "bin/oref0-reset-usb.sh", - "oref0-reset-git": "bin/oref0-reset-git.sh", + "bt-pan": "./bin/bt-pan", + "l": "./bin/oref0-tail-log.sh", "mm-format-ns-glucose": "./bin/mm-format-ns-glucose.sh", "mm-format-ns-profile": "./bin/mm-format-ns-profile.sh", - "mm-format-ns-treatments": "./bin/mm-format-ns-treatments.sh", "mm-format-ns-pump-history": "./bin/mm-format-ns-pump-history.sh", - "oref0": "./bin/oref0.sh", + "mm-format-ns-treatments": "./bin/mm-format-ns-treatments.sh", "mm-stick": "./bin/mm-stick.sh", - "ns-upload-entries": "./bin/ns-upload-entries.sh", - "ns-upload": "./bin/ns-upload.sh", - "ns-get": "./bin/ns-get.sh", - "ns-status": "./bin/ns-status.js", + "monitor-xdrip": "./bin/monitor-xdrip.sh", "nightscout": "./bin/nightscout.sh", "ns-dedupe-treatments": "./bin/ns-dedupe-treatments.sh", - "oref0-pebble": "./bin/oref0-pebble.js" + "ns-get": "./bin/ns-get.sh", + "ns-status": "./bin/ns-status.js", + "ns-upload": "./bin/ns-upload.sh", + "ns-upload-entries": "./bin/ns-upload-entries.sh", + "oref0": "./bin/oref0.sh", + "oref0-append-local-temptarget": "./bin/oref0-append-local-temptarget.sh", + "oref0-autosens-loop": "./bin/oref0-autosens-loop.sh", + "oref0-autotune": "./bin/oref0-autotune.sh", + "oref0-autotune-core": "./bin/oref0-autotune-core.js", + "oref0-autotune-export-to-xlsx": "./bin/oref0-autotune-export-to-xlsx.py", + "oref0-autotune-prep": "./bin/oref0-autotune-prep.js", + "oref0-autotune-recommends-report": "./bin/oref0-autotune-recommends-report.sh", + "oref0-bluetoothup": "./bin/oref0-bluetoothup.sh", + "oref0-calculate-iob": "./bin/oref0-calculate-iob.js", + "oref0-copy-fresher": "./bin/oref0-copy-fresher", + "oref0-crun": "./bin/oref0-conditional-run.sh", + "oref0-delete-future-entries": "./bin/oref0-delete-future-entries.sh", + "oref0-detect-sensitivity": "./bin/oref0-detect-sensitivity.js", + "oref0-determine-basal": "./bin/oref0-determine-basal.js", + "oref0-dexusb-cgm-loop": "./bin/oref0-dexusb-cgm-loop.py", + "oref0-dex-is-fresh": "./bin/oref0-dex-is-fresh.sh", + "oref0-dex-time-since": "./bin/oref0-dex-time-since.sh", + "oref0-dex-wait-until-expected": "./bin/oref0-dex-wait-until-expected.sh", + "oref0-find-insulin-uses": "./bin/oref0-find-insulin-uses.js", + "oref0-fix-git-corruption": "bin/oref0-fix-git-corruption.sh", + "oref0-get-profile": "./bin/oref0-get-profile.js", + "oref0-html": "./bin/oref0-html.js", + "oref0-ifttt-notify": "./bin/oref0-ifttt-notify", + "oref0_init_pump_comms.py": "./bin/oref0_init_pump_comms.py", + "oref0-log-shortcuts": "./bin/oref0-log-shortcuts.sh", + "oref0-mdt-trend": "./bin/oref0-mdt-trend.js", + "oref0-meal": "./bin/oref0-meal.js", + "oref0-ns-loop": "./bin/oref0-ns-loop.sh", + "oref0-normalize-temps": "./bin/oref0-normalize-temps.js", + "oref0_nightscout_check": "./bin/oref0_nightscout_check.py", + "oref0-online": "./bin/oref0-online.sh", + "oref0-pebble": "./bin/oref0-pebble.js", + "oref0-pump-loop": "./bin/oref0-pump-loop.sh", + "oref0-pushover": "./bin/oref0-pushover.sh", + "oref0-radio-reboot": "./bin/oref0-radio-reboot.sh", + "oref0-raw": "./bin/oref0-raw.js", + "oref0-reset-git": "bin/oref0-reset-git.sh", + "oref0-reset-usb": "bin/oref0-reset-usb.sh", + "oref0-set-device-clocks": "./bin/oref0-set-device-clocks.sh", + "oref0-set-system-clock": "./bin/oref0-set-system-clock.sh", + "oref0-set-local-temptarget": "./bin/oref0-set-local-temptarget.js", + "oref0-setup": "./bin/oref0-setup.sh", + "oref0-subg-ww-radio-parameters": "./bin/oref0-subg-ww-radio-parameters.sh", + "oref0_subg_ww_radio_parameters.py": "./bin/oref0_subg_ww_radio_parameters.py", + "oref0-truncate-git-history": "bin/oref0-truncate-git-history.sh", + "oref0-upload-entries": "./bin/oref0-upload-entries.sh", + "oref0-upload-profile": "./bin/oref0-upload-profile.js", + "oref0-version": "./bin/oref0-version.sh", + "peb-urchin-status": "./bin/peb-urchin-status.sh", + "wifi": "./bin/oref0-tail-wifi.sh" }, "homepage": "https://github.com/openaps/oref0", "dependencies": { + "crypto": "0.0.3", + "lodash": "^4.15.0", + "moment": "^2.14.1", + "request": "^2.79.0", "share2nightscout-bridge": "^0.1.5", - "timezone": "0.0.47" + "moment-timezone": "0.5.11", + "yargs": "~4.3.2", + "json": "~9.0.4", + "json-stable-stringify": "^1.0.1" }, "devDependencies": { + "coveralls": "^2.11.12", + "istanbul": "^0.4.4", "mocha": "^2.3.3", + "mocha-lcov-reporter": "^1.2.0", "should": "^7.1.0" }, "config": { diff --git a/release-master.sh b/release-master.sh old mode 100644 new mode 100755 index 7bf60e367..ffb0cd669 --- a/release-master.sh +++ b/release-master.sh @@ -1,6 +1,17 @@ -git checkout master && \ -git pull master && \ -npm version patch && \ -git tag -l && \ -npm publish && \ +#!/bin/bash + +# exit script immediately on any error +set -eu + +git checkout master +git pull origin master +echo "New version to be published in npm:" +npm version patch +echo "Publishing in 60s: Ctrl-C to cancel" +sleep 60 +echo "Running npm publish:" +npm publish +echo "Full list of git tags:" +git tag -l +echo "Pushing git tags to origin:" git push --tags origin master diff --git a/tests/basal.test.js b/tests/basal.test.js new file mode 100644 index 000000000..73ba0557a --- /dev/null +++ b/tests/basal.test.js @@ -0,0 +1,36 @@ +'use strict'; + +require('should'); + +var moment = require('moment'); + +describe('Basal', function ( ) { + + var basalprofile = [{'i': 0, 'start': '00:00:00', 'rate': 0, 'minutes': 0}, + {'i': 1, 'start': '00:15:00', 'rate': 2, 'minutes': 15 }, + {'i': 1, 'start': '00:45:00', 'rate': 0.5, 'minutes': 45 }]; + + it('should find the right max daily basal', function() { + + var inputs = {'basals': basalprofile}; + var basal = require('../lib/profile/basal'); + var maxBasal = basal.maxDailyBasal(inputs); + maxBasal.should.equal(2); + + }); + + + it('should find the right basal for a given moment', function() { + + var inputs = {'basals': basalprofile}; + var startingPoint = new Date(moment('2016-06-13 00:20:00.000').format()); + var startingPoint2 = new Date(moment('2016-06-13 01:00:00.000').format()); + var basal = require('../lib/profile/basal'); + var b = basal.basalLookup(basalprofile,startingPoint); + b.should.equal(2); + b = basal.basalLookup(basalprofile,startingPoint2); + b.should.equal(0.5); + + }); + +}); diff --git a/tests/bolus.test.js b/tests/bolus.test.js new file mode 100644 index 000000000..1e4f487a2 --- /dev/null +++ b/tests/bolus.test.js @@ -0,0 +1,38 @@ +'use strict'; + +var should = require('should'); + +describe('bolus', function () { + var bolushistory = [ + { + "_type": "Bolus", + "_description": "Bolus 2017-04-12T12:49:49 head[4], body[0] op[0x01]", + "timestamp": "2017-04-12T12:49:49-05:00", + "_body": "", + "programmed": 3.0, + "_head": "011e1e00", + "amount": 3.0, + "duration": 0, + "type": "normal", + "_date": "71314c0c11" + }, + { + "_type": "Bolus", + "_description": "Bolus 2017-04-12T12:47:53 head[4], body[0] op[0x01]", + "timestamp": "2017-04-12T12:47:53-05:00", + "_body": "", + "programmed": 0.2, + "_head": "01020200", + "amount": 0.2, + "duration": 0, + "type": "normal", + "_date": "752f4c4c11" + } + ]; + it('should not skip closely-timed boluses', function () { + var reduce_boluses = require('../lib/bolus'); + var vals = reduce_boluses(bolushistory); + vals.length.should.equal(1); + vals[0].insulin.should.equal('3.2'); + }) +}); \ No newline at end of file diff --git a/tests/cobhistory.test.js b/tests/cobhistory.test.js new file mode 100644 index 000000000..45536bc6d --- /dev/null +++ b/tests/cobhistory.test.js @@ -0,0 +1,44 @@ +'use strict'; + +var should = require('should'); + +describe('cobhistory', function ( ) { + var find_cob_iob_entries = require('../lib/meal/history'); + + var pumpHistory = [ + {"_type": "BolusWizard","timestamp": "2016-06-19T12:51:36-04:00","carb_input": 40}, + {"_type": "Bolus","timestamp": "2016-06-19T12:52:36-04:00","amount": 4.4}, + {"_type": "BolusWizard","timestamp": "2016-06-19T12:57:36-04:00","carb_input": 40}, + {"_type": "Bolus","timestamp": "2016-06-19T12:57:36-04:00","amount": 4.4}, + {"_type": "Bolus","timestamp": "2016-06-19T15:33:42-04:00","amount": 1.5}, + + {"_type": "BolusWizard","timestamp": "2016-06-19T12:59:36-04:00","carb_input": 40}, + {"_type": "Bolus","timestamp": "2016-06-19T12:59:36-04:00","amount": 4.4}, + {"_type": "BolusWizard","timestamp": "2016-06-19T12:59:36-04:00","carb_input": 40}, + {"_type": "Bolus","timestamp": "2016-06-19T12:59:36-04:00","amount": 4.4} + ]; + + var carbHistory = [ + {"_type": "BolusWizard","created_at": "2016-06-19T12:59:36-04:00","carbs": 40}, + {"_type": "Bolus","created_at": "2016-06-19T12:59:36-04:00","amount": 4.4}, + {"_type": "BolusWizard","created_at": "2016-06-19T12:59:36-04:00","carbs": 40}, + {"_type": "Bolus","created_at": "2016-06-19T12:59:36-04:00","amount": 4.4} + ]; + + //function determine_basal(glucose_status, currenttemp, iob_data, profile) + + it('should dedupe entries', function () { + var inputs = {}; + inputs.history = pumpHistory; + inputs.carbs = carbHistory; + inputs.profile = {}; + + var output = find_cob_iob_entries(inputs); + + console.log(output); + + // BolusWizard carb_input without a timestamp-matched Bolus will be ignored + output.length.should.equal(6); + }); + +}); diff --git a/tests/determine-basal.test.js b/tests/determine-basal.test.js index f050882db..c59b22fbc 100644 --- a/tests/determine-basal.test.js +++ b/tests/determine-basal.test.js @@ -1,434 +1,560 @@ 'use strict'; -require('should'); +var should = require('should'); +describe('round_basal', function ( ) { + var round_basal = require('../lib/round-basal'); + it('should round correctly without profile being passed in', function() { + var basal = 0.025; + var output = round_basal(basal); + output.should.equal(0.05); + }); + + var profile = {model: "522"}; + it('should round correctly with an old pump model', function() { + var basal = 0.025; + var output = round_basal(basal, profile); + output.should.equal(0.05); + }); + + + it('should round correctly with a new pump model', function() { + var basal = 0.025; + profile.model = "554"; + var output = round_basal(basal, profile); + output.should.equal(0.025); + //console.error(output); + }); + + it('should round correctly with an invalid pump model', function() { + var basal = 0.025; + profile.model = "HelloThisIsntAPumpModel"; + var output = round_basal(basal, profile); + output.should.equal(0.05); + }); + + it('should round basal rates properly (0.83 -> 0.825)', function() { + var basal = 0.83; + var output = round_basal(basal); + output.should.equal(0.85); + }); + + it('should round basal rates properly (0.86 -> 0.85)', function() { + var basal = 0.86; + var output = round_basal(basal); + output.should.equal(0.85); + }); + + it('should round basal rates properly: (1.83 -> 1.85)', function() { + var basal = 1.83; + var output = round_basal(basal); + output.should.equal(1.85); + }); + + it('should round basal rates properly: (1.86 -> 1.85)', function() { + var basal = 1.86; + var output = round_basal(basal); + output.should.equal(1.85); + }); + + it('should round basal rates properly: (10.83 -> 10.8)', function() { + var basal = 10.83; + var output = round_basal(basal); + output.should.equal(10.8); + }); + + it('should round basal rates properly: (10.86 -> 10.9)', function() { + var basal = 10.86; + var output = round_basal(basal); + output.should.equal(10.9); + }); +}); describe('determine-basal', function ( ) { var determine_basal = require('../lib/determine-basal/determine-basal'); - var setTempBasal = require('../lib/basal-set-temp'); + var tempBasalFunctions = require('../lib/basal-set-temp'); //function determine_basal(glucose_status, currenttemp, iob_data, profile) // standard initial conditions for all determine-basal test cases unless overridden - var glucose_status = {"delta":0,"glucose":115,"avgdelta":0}; + var glucose_status = {"delta":0,"glucose":115,"long_avgdelta":0.1,"short_avgdelta":0}; var currenttemp = {"duration":0,"rate":0,"temp":"absolute"}; - var iob_data = {"iob":0,"activity":0,"bolusiob":0}; - var profile = {"max_iob":1.5,"dia":3,"type":"current","current_basal":0.9,"max_daily_basal":1.3,"max_basal":3.5,"max_bg":120,"min_bg":110,"sens":40, "target_bg":110}; - - it('should do nothing when in range w/o IOB', function () { - var output = determine_basal(glucose_status, currenttemp, iob_data, profile, undefined,setTempBasal); - (typeof output.rate).should.equal('undefined'); - (typeof output.duration).should.equal('undefined'); - output.reason.should.match(/in range/); - }); - - it('should set current temp when in range w/o IOB with Offline set', function () { - var output = determine_basal(glucose_status, currenttemp, iob_data, profile, 'Offline',setTempBasal); + var iob_data = {"iob":0,"activity":0,"bolussnooze":0}; + var profile = {"max_iob":2.5,"dia":3,"type":"current","current_basal":0.9,"max_daily_basal":1.3,"max_basal":3.5,"max_bg":120,"min_bg":110,"sens":40,"carb_ratio":10}; + var meal_data = {}; + + it('should cancel high temp when in range w/o IOB', function () { + var currenttemp = {"duration":30,"rate":1.5,"temp":"absolute"}; + var output = determine_basal(glucose_status, currenttemp, iob_data, profile, undefined, meal_data, tempBasalFunctions); + //output.rate.should.equal(0); + //output.duration.should.equal(0); + //console.error(output); output.rate.should.equal(0.9); output.duration.should.equal(30); - output.reason.should.match(/in range.*setting current basal/); - }); - - it('should cancel any temp when in range w/o IOB', function () { - var currenttemp = {"duration":30,"rate":0,"temp":"absolute"}; - var output = determine_basal(glucose_status, currenttemp, iob_data, profile, undefined,setTempBasal); - output.rate.should.equal(0); - output.duration.should.equal(0); - output.reason.should.match(/in range.*cancel/); + //output.reason.should.match(/in range.*/); }); - + + //it('should let low temp run in range w/o IOB', function () { + //var currenttemp = {"duration":30,"rate":0,"temp":"absolute"}; + //var output = determine_basal(glucose_status, currenttemp, iob_data, profile, undefined, meal_data, tempBasalFunctions); + //console.error(output); + //(typeof output.rate).should.equal('undefined'); + //(typeof output.duration).should.equal('undefined'); + //output.reason.should.match(/.*letting low.*/); + //}); // low glucose suspend test cases it('should temp to 0 when low w/o IOB', function () { - var glucose_status = {"delta":-5,"glucose":75,"avgdelta":-5}; - var output = determine_basal(glucose_status, currenttemp, iob_data, profile, undefined,setTempBasal); + var glucose_status = {"delta":-5,"glucose":75,"long_avgdelta":-5,"short_avgdelta":-5}; + var output = determine_basal(glucose_status, currenttemp, iob_data, profile, undefined, meal_data, tempBasalFunctions); output.rate.should.equal(0); - output.duration.should.equal(30); - output.reason.should.match(/BG 75<80/); - }); - - it('should do nothing when low and rising w/o IOB', function () { - var glucose_status = {"delta":5,"glucose":75,"avgdelta":5}; - var output = determine_basal(glucose_status, currenttemp, iob_data, profile, undefined,setTempBasal); - (typeof output.rate).should.equal('undefined'); - (typeof output.duration).should.equal('undefined'); - output.reason.should.match(/75<80.*no high-temp/); + output.duration.should.be.above(29); + //output.reason.should.match(/BG 75<80/); }); - it('should do nothing when low and rising w/ negative IOB', function () { - var glucose_status = {"delta":5,"glucose":75,"avgdelta":5}; - var iob_data = {"iob":-1,"activity":-0.01,"bolusiob":0}; - var output = determine_basal(glucose_status, currenttemp, iob_data, profile, undefined,setTempBasal); + it('should not extend temp to 0 when <10m elapsed', function () { + var currenttemp = {"duration":57,"rate":0,"temp":"absolute"}; + var glucose_status = {"delta":-5,"glucose":75,"long_avgdelta":-5,"short_avgdelta":-5}; + var output = determine_basal(glucose_status, currenttemp, iob_data, profile, undefined, meal_data, tempBasalFunctions); + //console.log(output); (typeof output.rate).should.equal('undefined'); (typeof output.duration).should.equal('undefined'); - output.reason.should.match(/75<80.*no high-temp/); }); - it('should do nothing on large uptick even if avgdelta is still negative', function () { - var glucose_status = {"delta":2,"glucose":75,"avgdelta":-2}; - var output = determine_basal(glucose_status, currenttemp, iob_data, profile, undefined,setTempBasal); - (typeof output.rate).should.equal('undefined'); - (typeof output.duration).should.equal('undefined'); - output.reason.should.match(/BG 75<80/); + it('should do nothing when low and rising w/o IOB', function () { + var glucose_status = {"delta":5,"glucose":75,"long_avgdelta":5,"short_avgdelta":5}; + var output = determine_basal(glucose_status, currenttemp, iob_data, profile, undefined, meal_data, tempBasalFunctions); + output.rate.should.equal(0.9); + output.duration.should.equal(30); + //output.reason.should.match(/75<80.*setting current basal/); }); - it('should temp to 0 when rising slower than BGI', function () { - var glucose_status = {"delta":1,"glucose":75,"avgdelta":1}; - var iob_data = {"iob":-1,"activity":-0.01,"bolusiob":0}; - var output = determine_basal(glucose_status, currenttemp, iob_data, profile, undefined,setTempBasal); + //it('should do nothing when low and rising w/ negative IOB', function () { + //var glucose_status = {"delta":5,"glucose":75,"long_avgdelta":5,"short_avgdelta":5}; + //var iob_data = {"iob":-1,"activity":-0.01,"bolussnooze":0}; + //var output = determine_basal(glucose_status, currenttemp, iob_data, profile, undefined, meal_data, tempBasalFunctions); + //console.log(output); + //output.rate.should.equal(0.9); + //output.duration.should.equal(30); + //output.reason.should.match(/75<80.*setting current basal/); + //}); + + //it('should do nothing on large uptick even if avgdelta is still negative', function () { + //var glucose_status = {"delta":4,"glucose":75,"long_avgdelta":-2,"short_avgdelta":-2}; + //var output = determine_basal(glucose_status, currenttemp, iob_data, profile, undefined, meal_data, tempBasalFunctions); + //console.log(output); + //output.rate.should.equal(0.9); + //output.duration.should.equal(30); + //output.reason.should.match(/BG 75<80/); + //}); + + it('should temp to zero when rising slower than BGI', function () { + var glucose_status = {"delta":1,"glucose":75,"long_avgdelta":1,"short_avgdelta":1}; + var iob_data = {"iob":-0.5,"activity":-0.01,"bolussnooze":0}; + var output = determine_basal(glucose_status, currenttemp, iob_data, profile, undefined, meal_data, tempBasalFunctions); + //console.log(output); output.rate.should.equal(0); output.duration.should.equal(30); - output.reason.should.match(/BG 75<80/); + //output.reason.should.match(/BG 75<80/); }); it('should temp to 0 when low and falling, regardless of BGI', function () { - var glucose_status = {"delta":-1,"glucose":75,"avgdelta":-1}; - var iob_data = {"iob":1,"activity":0.01,"bolusiob":0.5}; - var output = determine_basal(glucose_status, currenttemp, iob_data, profile, undefined,setTempBasal); + var glucose_status = {"delta":-1,"glucose":75,"long_avgdelta":-1,"short_avgdelta":-1}; + var iob_data = {"iob":1,"activity":0.01,"bolussnooze":0.5}; + var output = determine_basal(glucose_status, currenttemp, iob_data, profile, undefined, meal_data, tempBasalFunctions); + //console.log(output); output.rate.should.equal(0); - output.duration.should.equal(30); - output.reason.should.match(/BG 75<80/); + output.duration.should.be.above(29); + //output.reason.should.match(/BG 75<80/); }); - it('should cancel high-temp when low and rising faster than BGI', function () { - var currenttemp = {"duration":20,"rate":2,"temp":"absolute"}; - var glucose_status = {"delta":5,"glucose":75,"avgdelta":5}; - var iob_data = {"iob":-1,"activity":-0.01,"bolusiob":0}; - var output = determine_basal(glucose_status, currenttemp, iob_data, profile, undefined,setTempBasal); - output.rate.should.equal(0); - output.duration.should.equal(0); - output.reason.should.match(/BG 75<80, avg delta .*, cancel high temp/); - }); - - it('should cancel low-temp eventualBG is higher then max_bg', function () { - var currenttemp = {"duration":20,"rate":0.9,"temp":"absolute"}; - var glucose_status = {"delta":5,"glucose":75,"avgdelta":5}; - var iob_data = {"iob":-1,"activity":-0.01,"bolusiob":0}; - var output = determine_basal(glucose_status, currenttemp, iob_data, profile, undefined,setTempBasal); - output.rate.should.equal(0); - output.duration.should.equal(0); - output.reason.should.match(/BG 75<80, avg delta .*, cancel low temp/); - }); + //it('should cancel high-temp when low and rising faster than BGI', function () { + //var currenttemp = {"duration":20,"rate":2,"temp":"absolute"}; + //var glucose_status = {"delta":5,"glucose":75,"long_avgdelta":5,"short_avgdelta":5}; + //var iob_data = {"iob":-1,"activity":-0.01,"bolussnooze":0}; + //var output = determine_basal(glucose_status, currenttemp, iob_data, profile, undefined, meal_data, tempBasalFunctions); + //console.log(output); + //output.rate.should.equal(0.9); + //output.duration.should.equal(30); + //output.reason.should.match(/BG 75<80, min delta .*/); + //}); + + //it('should cancel low-temp when eventualBG is higher then max_bg', function () { + //var currenttemp = {"duration":20,"rate":0,"temp":"absolute"}; + //var glucose_status = {"delta":5,"glucose":75,"long_avgdelta":5,"short_avgdelta":5}; + //var iob_data = {"iob":-1,"activity":-0.01,"bolussnooze":0}; + //var output = determine_basal(glucose_status, currenttemp, iob_data, profile, undefined, meal_data, tempBasalFunctions); + //console.log(output); + //output.rate.should.equal(0.9); + //output.duration.should.equal(30); + //output.reason.should.match(/BG 75<80, min delta .*/); + //}); it('should high-temp when > 80-ish and rising w/ lots of negative IOB', function () { - var glucose_status = {"delta":5,"glucose":85,"avgdelta":5}; - var iob_data = {"iob":-1,"activity":-0.01,"bolusiob":0}; - var output = determine_basal(glucose_status, currenttemp, iob_data, profile, undefined,setTempBasal); + var glucose_status = {"delta":5,"glucose":85,"long_avgdelta":5,"short_avgdelta":5}; + var iob_data = {"iob":-1,"activity":-0.01,"bolussnooze":0}; + var output = determine_basal(glucose_status, currenttemp, iob_data, profile, undefined, meal_data, tempBasalFunctions); output.rate.should.be.above(1); output.duration.should.equal(30); output.reason.should.match(/no temp, setting/); }); - - it('should high-temp when > 180-ish and rising but not more then maxSafeBasal', function () { - var glucose_status = {"delta":5,"glucose":185,"avgdelta":5}; - var iob_data = {"iob":0,"activity":-0.01,"bolusiob":0}; - var output = determine_basal(glucose_status, currenttemp, iob_data, profile, undefined,setTempBasal); - output.reason.should.match(/max_iob .*, adj. req. rate:.* to maxSafeBasal:.*, no temp, setting/); + it('should high-temp when > 180-ish and rising but not more then maxSafeBasal', function () { + var glucose_status = {"delta":5,"glucose":185,"long_avgdelta":5,"short_avgdelta":5}; + var iob_data = {"iob":0,"activity":-0.01,"bolussnooze":0}; + var output = determine_basal(glucose_status, currenttemp, iob_data, profile, undefined, meal_data, tempBasalFunctions); + output.reason.should.match(/.*, adj. req. rate:.* to maxSafeBasal:.*, no temp, setting/); }); - + it('should reduce high-temp when schedule would be above max', function () { - var glucose_status = {"delta":5,"glucose":145,"avgdelta":5}; + var glucose_status = {"delta":5,"glucose":145,"long_avgdelta":5,"short_avgdelta":5}; var currenttemp = {"duration":160,"rate":1.9,"temp":"absolute"}; - var iob_data = {"iob":0,"activity":-0.01,"bolusiob":0}; - var output = determine_basal(glucose_status, currenttemp, iob_data, profile, undefined,setTempBasal); + var iob_data = {"iob":0,"activity":-0.01,"bolussnooze":0}; + var output = determine_basal(glucose_status, currenttemp, iob_data, profile, undefined, meal_data, tempBasalFunctions); output.duration.should.equal(30); - output.reason.should.match(/.*mins .* = .* > req .*/); + output.reason.should.match(/.* > 2.*insulinReq. Setting temp.*/); }); - + it('should continue high-temp when required ~= temp running', function () { - var glucose_status = {"delta":5,"glucose":145,"avgdelta":5}; - var currenttemp = {"duration":30,"rate":3.1,"temp":"absolute"}; - var iob_data = {"iob":0,"activity":-0.01,"bolusiob":0}; - var output = determine_basal(glucose_status, currenttemp, iob_data, profile, undefined,setTempBasal); + var glucose_status = {"delta":5,"glucose":145,"long_avgdelta":5,"short_avgdelta":5}; + var currenttemp = {"duration":30,"rate":3.5,"temp":"absolute"}; + var iob_data = {"iob":0,"activity":-0.01,"bolussnooze":0}; + var output = determine_basal(glucose_status, currenttemp, iob_data, profile, undefined, meal_data, tempBasalFunctions); + //console.log(output); (typeof output.rate).should.equal('undefined'); (typeof output.duration).should.equal('undefined'); output.reason.should.match(/Eventual BG .*>.*, temp .* >~ req /); }); - + it('should set high-temp when required running temp is low', function () { - var glucose_status = {"delta":5,"glucose":145,"avgdelta":5}; + var glucose_status = {"delta":5,"glucose":145,"long_avgdelta":5,"short_avgdelta":5}; var currenttemp = {"duration":30,"rate":1.1,"temp":"absolute"}; - var iob_data = {"iob":0,"activity":-0.01,"bolusiob":0}; - var output = determine_basal(glucose_status, currenttemp, iob_data, profile, undefined,setTempBasal); + var iob_data = {"iob":0,"activity":-0.01,"bolussnooze":0}; + var output = determine_basal(glucose_status, currenttemp, iob_data, profile, undefined, meal_data, tempBasalFunctions); output.duration.should.equal(30); output.reason.should.match(/Eventual BG .*>.*, temp/); }); - + it('should stop high-temp when iob is near max_iob.', function () { - var glucose_status = {"delta":5,"glucose":485,"avgdelta":5}; - var iob_data = {"iob":3.5,"activity":0.05,"bolusiob":0}; - var output = determine_basal(glucose_status, currenttemp, iob_data, profile, undefined,setTempBasal); - output.rate.should.equal(0); - output.duration.should.equal(0); - output.reason.should.match(/basal_iob .* > max_iob .*/); + var glucose_status = {"delta":5,"glucose":485,"long_avgdelta":5,"short_avgdelta":5}; + var iob_data = {"iob":3.5,"activity":0.05,"bolussnooze":0}; + var output = determine_basal(glucose_status, currenttemp, iob_data, profile, undefined, meal_data, tempBasalFunctions); + output.rate.should.equal(0.9); + output.duration.should.equal(30); + output.reason.should.match(/IOB .* > max_iob .*/); }); it('should temp to 0 when LOW w/ positive IOB', function () { - var glucose_status = {"delta":0,"glucose":39,"avgdelta":0}; - var iob_data = {"iob":1,"activity":0.01,"bolusiob":0.5}; - var output = determine_basal(glucose_status, currenttemp, iob_data, profile, undefined,setTempBasal); + var glucose_status = {"delta":0,"glucose":39,"long_avgdelta":0.1,"short_avgdelta":0}; + var iob_data = {"iob":1,"activity":0.01,"bolussnooze":0.5}; + var output = determine_basal(glucose_status, currenttemp, iob_data, profile, undefined, meal_data, tempBasalFunctions); output.rate.should.equal(0); - output.duration.should.equal(30); - output.reason.should.match(/BG 39<80/); + output.duration.should.be.above(29); + //output.reason.should.match(/BG 39<80/); }); - it('should temp to 0 when LOW w/ negative IOB', function () { - var glucose_status = {"delta":0,"glucose":39,"avgdelta":0}; - var iob_data = {"iob":-2.5,"activity":-0.03,"bolusiob":0}; - var output = determine_basal(glucose_status, currenttemp, iob_data, profile, undefined,setTempBasal); - output.rate.should.equal(0); - output.duration.should.equal(30); - output.reason.should.match(/BG 39<80/); + it('should low temp when LOW w/ negative IOB', function () { + var glucose_status = {"delta":0,"glucose":39,"long_avgdelta":0.1,"short_avgdelta":0}; + var iob_data = {"iob":-2.5,"activity":-0.03,"bolussnooze":0}; + var output = determine_basal(glucose_status, currenttemp, iob_data, profile, undefined, meal_data, tempBasalFunctions); + output.rate.should.be.below(0.8); + output.duration.should.be.above(29); + //output.reason.should.match(/BG 39<80/); }); it('should temp to 0 when LOW w/ no IOB', function () { - var glucose_status = {"delta":0,"glucose":39,"avgdelta":0}; - var iob_data = {"iob":0,"activity":0,"bolusiob":0}; - var output = determine_basal(glucose_status, currenttemp, iob_data, profile, undefined,setTempBasal); + var glucose_status = {"delta":0,"glucose":39,"long_avgdelta":0.1,"short_avgdelta":0}; + var iob_data = {"iob":0,"activity":0,"bolussnooze":0}; + var output = determine_basal(glucose_status, currenttemp, iob_data, profile, undefined, meal_data, tempBasalFunctions); output.rate.should.equal(0); - output.duration.should.equal(30); - output.reason.should.match(/BG 39<80/); + output.duration.should.be.above(29); + //output.reason.should.match(/BG 39<80/); }); - + // low eventualBG it('should low-temp when eventualBG < min_bg', function () { - var glucose_status = {"delta":-3,"glucose":110,"avgdelta":-1}; - var output = determine_basal(glucose_status, currenttemp, iob_data, profile, undefined,setTempBasal); + var glucose_status = {"delta":-3,"glucose":110,"long_avgdelta":-1,"short_avgdelta":-1}; + var output = determine_basal(glucose_status, currenttemp, iob_data, profile, undefined, meal_data, tempBasalFunctions); + //console.log(output); output.rate.should.be.below(0.8); - output.duration.should.equal(30); - output.reason.should.match(/Eventual BG .*<110, no temp, setting .*/); + output.duration.should.be.above(29); + output.reason.should.match(/Eventual BG .*< 110.*/); }); - + it('should low-temp when eventualBG < min_bg with delta > exp. delta', function () { - var glucose_status = {"delta":-5,"glucose":115,"avgdelta":-6}; - var iob_data = {"iob":2,"activity":0.05,"bolusiob":0}; - var output = determine_basal(glucose_status, currenttemp, iob_data, profile, undefined,setTempBasal); + var glucose_status = {"delta":-5,"glucose":115,"long_avgdelta":-6,"short_avgdelta":-6}; + var iob_data = {"iob":2,"activity":0.05,"bolussnooze":0}; + var output = determine_basal(glucose_status, currenttemp, iob_data, profile, undefined, meal_data, tempBasalFunctions); //console.log(output); output.rate.should.be.below(0.2); - output.duration.should.equal(30); - output.reason.should.match(/Eventual BG .*<110, no temp, setting .*/); + output.duration.should.be.above(29); + //output.reason.should.match(/Eventual BG .*< 110.*setting .*/); }); - + it('should low-temp when eventualBG < min_bg with delta > exp. delta', function () { - var glucose_status = {"delta":-2,"glucose":156,"avgdelta":-1.33}; - var iob_data = {"iob":3.51,"activity":0.06,"bolusiob":0.08}; - var output = determine_basal(glucose_status, currenttemp, iob_data, profile, undefined,setTempBasal); - console.log(output); + var glucose_status = {"delta":-2,"glucose":156,"long_avgdelta":-1.33,"short_avgdelta":-1.33}; + var iob_data = {"iob":3.51,"activity":0.06,"bolussnooze":0.08}; + var output = determine_basal(glucose_status, currenttemp, iob_data, profile, undefined, meal_data, tempBasalFunctions); + //console.log(output); output.rate.should.be.below(0.8); output.duration.should.equal(30); - output.reason.should.match(/Eventual BG .*<110, no temp, setting .*/); + output.reason.should.match(/Eventual BG .*< 110.*setting .*/); }); it('should low-temp much less when eventualBG < min_bg with delta barely negative', function () { - var glucose_status = {"delta":-1,"glucose":115,"avgdelta":-1}; - var iob_data = {"iob":2,"activity":0.05,"bolusiob":0}; - var output = determine_basal(glucose_status, currenttemp, iob_data, profile, undefined,setTempBasal); - //console.log(output); - output.rate.should.be.above(0.5); + var glucose_status = {"delta":-1,"glucose":115,"long_avgdelta":-1,"short_avgdelta":-1}; + var iob_data = {"iob":2,"activity":0.05,"bolussnooze":0}; + var output = determine_basal(glucose_status, currenttemp, iob_data, profile, undefined, meal_data, tempBasalFunctions); + output.rate.should.be.above(0.3); output.rate.should.be.below(0.8); output.duration.should.equal(30); - output.reason.should.match(/Eventual BG .*<110, no temp, setting .*/); + output.reason.should.match(/Eventual BG .*< 110.*setting .*/); }); - it('should do nothing when eventualBG < min_bg but low temp in progress', function () { - var glucose_status = {"delta":-3,"glucose":110,"avgdelta":-1}; - var currenttemp = {"duration":20,"rate":0.0,"temp":"absolute"}; - var output = determine_basal(glucose_status, currenttemp, iob_data, profile, undefined,setTempBasal); - (typeof output.rate).should.equal('undefined'); - (typeof output.duration).should.equal('undefined'); - output.reason.should.match(/Eventual BG .*<110, temp .*/); - }); + //it('should do nothing when eventualBG < min_bg but appropriate low temp in progress', function () { + //var glucose_status = {"delta":-1,"glucose":110,"long_avgdelta":-1,"short_avgdelta":-1}; + //var currenttemp = {"duration":20,"rate":0.25,"temp":"absolute"}; + //var output = determine_basal(glucose_status, currenttemp, iob_data, profile, undefined, meal_data, tempBasalFunctions); + ////console.log(output); + //(typeof output.rate).should.equal('undefined'); + //(typeof output.duration).should.equal('undefined'); + //output.reason.should.match(/Eventual BG .*< 110, temp .*/); + //}); it('should cancel low-temp when lowish and avg.delta rising faster than BGI', function () { var currenttemp = {"duration":20,"rate":0.5,"temp":"absolute"}; - var glucose_status = {"delta":3,"glucose":85,"avgdelta":3}; - var iob_data = {"iob":-0.5,"activity":-0.01,"bolusiob":0}; - var output = determine_basal(glucose_status, currenttemp, iob_data, profile, undefined,setTempBasal); - output.rate.should.equal(0); - output.duration.should.equal(0); - output.reason.should.match(/Eventual BG.*<.*but Avg. Delta.*> Exp.*; cancel/); + var glucose_status = {"delta":3,"glucose":85,"long_avgdelta":3,"short_avgdelta":3}; + var iob_data = {"iob":-0.7,"activity":-0.01,"bolussnooze":0}; + var output = determine_basal(glucose_status, currenttemp, iob_data, profile, undefined, meal_data, tempBasalFunctions); + output.rate.should.be.above(0.8); + output.duration.should.equal(30); + //output.rate.should.equal(0); + //output.duration.should.equal(0); + //output.reason.should.match(/.*; cancel/); }); - + it('should cancel low-temp when lowish and delta rising faster than BGI', function () { var currenttemp = {"duration":20,"rate":0.5,"temp":"absolute"}; - var glucose_status = {"delta":3,"glucose":85,"avgdelta":3}; - var iob_data = {"iob":-0.5,"activity":-0.01,"bolusiob":0}; - var output = determine_basal(glucose_status, currenttemp, iob_data, profile, undefined,setTempBasal); - output.rate.should.equal(0); - output.duration.should.equal(0); - output.reason.should.match(/Eventual BG.*<.*but.*Delta.*> Exp.*; cancel/); + var glucose_status = {"delta":3,"glucose":85,"long_avgdelta":3,"short_avgdelta":3}; + var iob_data = {"iob":-0.7,"activity":-0.01,"bolussnooze":0}; + var output = determine_basal(glucose_status, currenttemp, iob_data, profile, undefined, meal_data, tempBasalFunctions); + console.log(output); + output.rate.should.be.above(0.8); + output.duration.should.equal(30); }); - - it('should do nothing when lowish and delta rising faster than BGI', function () { + + it('should set current basal as temp when lowish and delta rising faster than BGI', function () { var currenttemp = {"duration":0,"rate":0.5,"temp":"absolute"}; - var glucose_status = {"delta":3,"glucose":85,"avgdelta":3}; - var iob_data = {"iob":-0.5,"activity":-0.01,"bolusiob":0}; - var output = determine_basal(glucose_status, currenttemp, iob_data, profile, undefined,setTempBasal); - output.reason.should.match(/Eventual BG.*<.*but.*Delta.*> Exp.*; no temp to cancel/); + var glucose_status = {"delta":3,"glucose":85,"long_avgdelta":3,"short_avgdelta":3}; + var iob_data = {"iob":-0.7,"activity":-0.01,"bolussnooze":0}; + var output = determine_basal(glucose_status, currenttemp, iob_data, profile, undefined, meal_data, tempBasalFunctions); + //(typeof output.rate).should.equal('undefined'); + //(typeof output.duration).should.equal('undefined'); + console.log(profile, output); + output.rate.should.equal(0.9); + output.duration.should.equal(30); + output.reason.should.match(/in range.*setting current basal/); }); + it('should low-temp when low and rising slower than BGI', function () { - var glucose_status = {"delta":1,"glucose":85,"avgdelta":1}; - var iob_data = {"iob":-0.5,"activity":-0.01,"bolusiob":0}; - var output = determine_basal(glucose_status, currenttemp, iob_data, profile, undefined,setTempBasal); - //console.log(output); + var glucose_status = {"delta":1,"glucose":85,"long_avgdelta":1,"short_avgdelta":1}; + var iob_data = {"iob":-0.5,"activity":-0.01,"bolussnooze":0}; + var output = determine_basal(glucose_status, currenttemp, iob_data, profile, undefined, meal_data, tempBasalFunctions); output.rate.should.be.below(0.8); output.duration.should.equal(30); - output.reason.should.match(/no temp, setting/); + //output.reason.should.match(/setting/); }); // high eventualBG it('should high-temp when eventualBG > max_bg', function () { - var glucose_status = {"delta":+3,"glucose":120,"avgdelta":+1}; - var output = determine_basal(glucose_status, currenttemp, iob_data, profile, undefined,setTempBasal); + var glucose_status = {"delta":+3,"glucose":120,"long_avgdelta":0,"short_avgdelta":+1}; + var output = determine_basal(glucose_status, currenttemp, iob_data, profile, undefined, meal_data, tempBasalFunctions); output.rate.should.be.above(1); output.duration.should.equal(30); - output.reason.should.match(/Eventual BG .*>120/); + output.reason.should.match(/Eventual BG .*>= 120/); }); it('should cancel high-temp when high and avg. delta falling faster than BGI', function () { var currenttemp = {"duration":20,"rate":2,"temp":"absolute"}; - var glucose_status = {"delta":-5,"glucose":175,"avgdelta":-5}; - var iob_data = {"iob":1,"activity":0.01,"bolusiob":0}; - var output = determine_basal(glucose_status, currenttemp, iob_data, profile, undefined,setTempBasal); - output.rate.should.equal(0); - output.duration.should.equal(0); - output.reason.should.match(/Eventual BG.*>.*but Avg. Delta.*< Exp.*; cancel/); + var glucose_status = {"delta":-5,"glucose":175,"long_avgdelta":-5,"short_avgdelta":-5}; + var iob_data = {"iob":1,"activity":0.01,"bolussnooze":0}; + var output = determine_basal(glucose_status, currenttemp, iob_data, profile, undefined, meal_data, tempBasalFunctions); + output.rate.should.equal(0.9); + output.duration.should.equal(30); + //output.reason.should.match(/.*; cancel/); + //output.rate.should.equal(0); + //output.duration.should.equal(0); + output.reason.should.match(/Eventual BG.*>.*but Min. Delta.*< Exp.*/); }); - + it('should cancel high-temp when high and delta falling faster than BGI', function () { var currenttemp = {"duration":20,"rate":2,"temp":"absolute"}; - var glucose_status = {"delta":-5,"glucose":175,"avgdelta":-4}; - var iob_data = {"iob":1,"activity":0.01,"bolusiob":0}; - var output = determine_basal(glucose_status, currenttemp, iob_data, profile, undefined,setTempBasal); - output.rate.should.equal(0); - output.duration.should.equal(0); - output.reason.should.match(/Eventual BG.*>.*but.*Delta.*< Exp.*; cancel/); + var glucose_status = {"delta":-5,"glucose":175,"long_avgdelta":-4,"short_avgdelta":-4}; + var iob_data = {"iob":1,"activity":0.01,"bolussnooze":0}; + var output = determine_basal(glucose_status, currenttemp, iob_data, profile, undefined, meal_data, tempBasalFunctions); + output.rate.should.equal(0.9); + output.duration.should.equal(30); + output.reason.should.match(/Eventual BG.*>.*but.*Delta.*< Exp.*/); }); - - it('should do nothing when not temp and high and delta falling faster than BGI', function () { + + it('should do nothing when no temp and high and delta falling faster than BGI', function () { var currenttemp = {"duration":0,"rate":0,"temp":"absolute"}; - var glucose_status = {"delta":-5,"glucose":175,"avgdelta":-4}; - var iob_data = {"iob":1,"activity":0.01,"bolusiob":0}; - var output = determine_basal(glucose_status, currenttemp, iob_data, profile, undefined,setTempBasal); - (typeof output.rate).should.equal('undefined'); - (typeof output.duration).should.equal('undefined'); - output.reason.should.match(/Eventual BG.*>.*but.*Delta.*< Exp.*; no temp to cancel/); + var glucose_status = {"delta":-5,"glucose":175,"long_avgdelta":-4,"short_avgdelta":-4}; + var iob_data = {"iob":1,"activity":0.01,"bolussnooze":0}; + var output = determine_basal(glucose_status, currenttemp, iob_data, profile, undefined, meal_data, tempBasalFunctions); + //(typeof output.rate).should.equal('undefined'); + //(typeof output.duration).should.equal('undefined'); + output.rate.should.equal(0.9); + output.duration.should.equal(30); + output.reason.should.match(/Eventual BG.*>.*but.*Delta.*< Exp.*/); }); it('should high-temp when high and falling slower than BGI', function () { - var glucose_status = {"delta":-1,"glucose":175,"avgdelta":-1}; - var iob_data = {"iob":1,"activity":0.01,"bolusiob":0}; - var output = determine_basal(glucose_status, currenttemp, iob_data, profile, undefined,setTempBasal); + var glucose_status = {"delta":-1,"glucose":175,"long_avgdelta":-1,"short_avgdelta":-1}; + var iob_data = {"iob":1,"activity":0.01,"bolussnooze":0}; + var output = determine_basal(glucose_status, currenttemp, iob_data, profile, undefined, meal_data, tempBasalFunctions); output.rate.should.be.above(1); output.duration.should.equal(30); output.reason.should.match(/no temp, setting/); }); it('should high-temp when high and falling slowly with low insulin activity', function () { - var glucose_status = {"delta":-1,"glucose":300,"avgdelta":-1}; - var iob_data = {"iob":0.5,"activity":0.005,"bolusiob":0}; - var output = determine_basal(glucose_status, currenttemp, iob_data, profile, undefined,setTempBasal); + var glucose_status = {"delta":-1,"glucose":300,"long_avgdelta":-1,"short_avgdelta":-1}; + var iob_data = {"iob":0.5,"activity":0.005,"bolussnooze":0}; + var output = determine_basal(glucose_status, currenttemp, iob_data, profile, undefined, meal_data, tempBasalFunctions); output.rate.should.be.above(2.5); output.duration.should.equal(30); output.reason.should.match(/no temp, setting/); }); - it('should set lower high-temp when high and falling almost fast enough with low insulin activity', function () { - var glucose_status = {"delta":-5,"glucose":300,"avgdelta":-5}; - var iob_data = {"iob":0.5,"activity":0.005,"bolusiob":0}; - var output = determine_basal(glucose_status, currenttemp, iob_data, profile, undefined,setTempBasal); - //console.log(output); - output.rate.should.be.above(1); - output.rate.should.be.below(2); - output.duration.should.equal(30); - output.reason.should.match(/no temp, setting/); - }); - - it('should reduce high-temp when high and falling almost fast enough with low insulin activity', function () { - var glucose_status = {"delta":-5,"glucose":300,"avgdelta":-5}; - var iob_data = {"iob":0.5,"activity":0.005,"bolusiob":0}; - var currenttemp = {"duration":30,"rate":2.5,"temp":"absolute"}; - var output = determine_basal(glucose_status, currenttemp, iob_data, profile, undefined,setTempBasal); - output.rate.should.be.above(1); - output.rate.should.be.below(2); - output.duration.should.equal(30); - output.reason.should.match(/> req/); - }); + //it('should set lower high-temp when high and falling almost fast enough with low insulin activity', function () { + //var glucose_status = {"delta":-6,"glucose":300,"long_avgdelta":-5,"short_avgdelta":-5}; + //var iob_data = {"iob":0.5,"activity":0.005,"bolussnooze":0}; + //var output = determine_basal(glucose_status, currenttemp, iob_data, profile, undefined, meal_data, tempBasalFunctions); + //console.error(output); + //output.rate.should.be.above(1); + //output.rate.should.be.below(2); + //output.duration.should.equal(30); + //output.reason.should.match(/no temp, setting/); + //}); + + //it('should reduce high-temp when high and falling almost fast enough with low insulin activity', function () { + //var glucose_status = {"delta":-6,"glucose":300,"long_avgdelta":-5,"short_avgdelta":-5}; + //var iob_data = {"iob":0.5,"activity":0.005,"bolussnooze":0}; + //var currenttemp = {"duration":30,"rate":3.5,"temp":"absolute"}; + //var output = determine_basal(glucose_status, currenttemp, iob_data, profile, undefined, meal_data, tempBasalFunctions); + //console.error(output); + //output.rate.should.be.above(1); + //output.rate.should.be.below(2); + //output.duration.should.equal(30); + //output.reason.should.match(/.* > 2.*insulinReq. Setting temp.*/); + //}); it('should profile.current_basal be undefined return error', function () { var result = determine_basal(undefined,undefined,undefined,undefined); result.error.should.equal('Error: could not get current basal rate'); - }); + }); + + it('should let low-temp run when bg < 30 (Dexcom is in ???)', function () { + var currenttemp = {"duration":30,"rate":0,"temp":"absolute"}; + var output = determine_basal({glucose:10},currenttemp, iob_data, profile, undefined, meal_data, tempBasalFunctions); + //console.log(output); + (typeof output.rate).should.equal('undefined'); + output.reason.should.match(/CGM is calibrating/); + }); - it('should bg be < 30 (Dexcom is in ???) return error', function () { - var result = determine_basal({glucose:18},undefined, undefined, {"current_basal":0.0}, undefined,setTempBasal); - result.error.should.equal('CGM is calibrating or in ??? state'); - }); + it('should cancel high-temp when bg < 30 (Dexcom is in ???)', function () { + var currenttemp = {"duration":30,"rate":2,"temp":"absolute"}; + var output = determine_basal({glucose:10},currenttemp, iob_data, profile, undefined, meal_data, tempBasalFunctions); + //console.log(output); + output.rate.should.be.below(1); + output.reason.should.match(/Canceling high temp/); + }); - it('profile should contain min_bg,max_bg or target_bg', function () { - var result = determine_basal({glucose:100},undefined, undefined, {"current_basal":0.0}, undefined,setTempBasal); - result.error.should.equal('Error: could not determine target_bg'); - }); + it('profile should contain min_bg,max_bg', function () { + var result = determine_basal({glucose:100},undefined, undefined, {"current_basal":0.0}, undefined, meal_data, tempBasalFunctions); + result.error.should.equal('Error: could not determine target_bg. '); + }); it('iob_data should not be undefined', function () { - var result = determine_basal({glucose:100},undefined, undefined, {"current_basal":0.0, "target_bg":100}, undefined,setTempBasal); - result.error.should.equal('Error: iob_data undefined'); - }); + var result = determine_basal({glucose:100},undefined, undefined, {"current_basal":0.0, "max_bg":100,"min_bg":1100}, undefined, meal_data, tempBasalFunctions); + result.error.should.equal('Error: iob_data undefined. '); + }); - it('iob_data should contain activity, iob, bolusiob', function () { - var result = determine_basal({glucose:100}, undefined,{"activity":0}, {"current_basal":0.0, "target_bg":100}, undefined,setTempBasal); - result.error.should.equal('Error: iob_data missing some property'); - }); + //it('iob_data should contain activity, iob, bolussnooze', function () { + //var result = determine_basal({glucose:100}, undefined,{"activity":0}, {"current_basal":0.0, "max_bg":100,"min_bg":110}, undefined, meal_data, tempBasalFunctions); + //result.error.should.equal('Error: iob_data missing some property. '); + //}); /* it('should return error eventualBG if something went wrong', function () { - var result = determine_basal({glucose:100}, undefined,{"activity":0, "iob":0,"bolusiob":0}, {"current_basal":0.0, "target_bg":100, "sens":NaN}, undefined,setTempBasal); + var result = determine_basal({glucose:100}, undefined,{"activity":0, "iob":0,"bolussnooze":0}, {"current_basal":0.0, "sens":NaN}, undefined, meal_data, tempBasalFunctions); result.error.should.equal('Error: could not calculate eventualBG'); }); */ // meal assist / bolus snooze // right after 20g 1U meal bolus - it('should do nothing when low and rising after meal bolus', function () { - var glucose_status = {"delta":1,"glucose":80,"avgdelta":1}; - var iob_data = {"iob":0.5,"activity":-0.01,"bolusiob":1}; - var meal_data = {"dia_carbs":20,"dia_bolused":1}; - var output = determine_basal(glucose_status, currenttemp, iob_data, profile, undefined,setTempBasal); + //it('should set current basal as temp when low and rising after meal bolus', function () { + //var glucose_status = {"delta":1,"glucose":80,"long_avgdelta":1,"short_avgdelta":1}; + //var iob_data = {"iob":0.5,"activity":-0.01,"bolussnooze":1,"basaliob":-0.5}; + //var meal_data = {"carbs":20,"boluses":1, "mealCOB":20}; + //var output = determine_basal(glucose_status, currenttemp, iob_data, profile, undefined, meal_data, tempBasalFunctions); + //console.log(output); + //output.rate.should.equal(0.9); + //output.duration.should.equal(30); + //}); + + it('should do nothing when requested temp already running with >15m left', function () { + var glucose_status = {"delta":-2,"glucose":121,"long_avgdelta":-1.333,"short_avgdelta":-1.333}; + var iob_data = {"iob":3.983,"activity":0.0255,"bolussnooze":2.58,"basaliob":0.384,"netbasalinsulin":0.3,"hightempinsulin":0.7}; + var meal_data = {"carbs":65,"boluses":4, "mealCOB":65}; + var currenttemp = {"duration":29,"rate":1.3,"temp":"absolute"}; + var profile = {"max_iob":3,"type":"current","dia":3,"current_basal":1.3,"max_daily_basal":1.3,"max_basal":3.5,"min_bg":105,"max_bg ":105,"sens":40,"carb_ratio":10} + var output = determine_basal(glucose_status, currenttemp, iob_data, profile, undefined, meal_data, tempBasalFunctions); + //console.log(output); (typeof output.rate).should.equal('undefined'); (typeof output.duration).should.equal('undefined'); }); - - it('should cancel high temp when low and dropping after meal bolus', function () { - var glucose_status = {"delta":-1,"glucose":80,"avgdelta":1}; - var iob_data = {"iob":0.5,"activity":-0.01,"bolusiob":1}; - var currenttemp = {"duration":20,"rate":2,"temp":"absolute"}; - var output = determine_basal(glucose_status, currenttemp, iob_data, profile, undefined,setTempBasal); - output.rate.should.equal(0); - output.duration.should.equal(0); - }); - - it('should cancel low temp when low and rising after meal bolus', function () { - var glucose_status = {"delta":1,"glucose":80,"avgdelta":1}; - var iob_data = {"iob":0.5,"activity":-0.01,"bolusiob":1}; - var currenttemp = {"duration":20,"rate":0,"temp":"absolute"}; - var output = determine_basal(glucose_status, currenttemp, iob_data, profile, undefined,setTempBasal); - output.rate.should.equal(0); - output.duration.should.equal(0); - }); + //it('should cancel high temp when low and dropping after meal bolus', function () { + //var glucose_status = {"delta":-1,"glucose":80,"long_avgdelta":1,"short_avgdelta":1}; + //var iob_data = {"iob":0.5,"activity":-0.01,"bolussnooze":1,"basaliob":-0.5}; + //var currenttemp = {"duration":20,"rate":2,"temp":"absolute"}; + //var output = determine_basal(glucose_status, currenttemp, iob_data, profile, undefined, meal_data, tempBasalFunctions); + ////console.log(output); + ////output.rate.should.equal(0); + ////output.duration.should.equal(0); + //output.rate.should.be.below(1.0); + //output.duration.should.equal(30); + //}); + + //it('should cancel low temp when low and rising after meal bolus', function () { + //var glucose_status = {"delta":1,"glucose":80,"long_avgdelta":1,"short_avgdelta":1}; + //var iob_data = {"iob":0.5,"activity":-0.01,"bolussnooze":1,"basaliob":-0.5}; + //var currenttemp = {"duration":20,"rate":0,"temp":"absolute"}; + //var output = determine_basal(glucose_status, currenttemp, iob_data, profile, undefined, meal_data, tempBasalFunctions); + ////console.log(output); + //output.rate.should.equal(0.9); + //output.duration.should.equal(30); + ////output.rate.should.equal(0); + ////output.duration.should.equal(0); + //}); + + /* TODO: figure out how to do tests for advanced-meal-assist // 40m after 20g 1U meal bolus it('should high-temp aggressively when 120 and rising after meal bolus', function () { var glucose_status = {"delta":10,"glucose":120,"avgdelta":10}; - var iob_data = {"iob":0.4,"activity":0,"bolusiob":0.7}; - var meal_data = {"dia_carbs":20,"dia_bolused":1}; - var output = determine_basal(glucose_status, currenttemp, iob_data, profile, undefined,setTempBasal); + var iob_data = {"iob":0.4,"activity":0,"bolussnooze":0.7,"basaliob":-0.3}; + var meal_data = {"carbs":20,"boluses":1, "mealCOB":20}; + var output = determine_basal(glucose_status, currenttemp, iob_data, profile, undefined, meal_data, tempBasalFunctions); + console.log(output); output.rate.should.be.above(1.8); output.duration.should.equal(30); }); @@ -436,10 +562,11 @@ describe('determine-basal', function ( ) { // 60m after 20g 1U meal bolus it('should high-temp aggressively when 150 and rising after meal bolus', function () { var glucose_status = {"delta":3,"glucose":150,"avgdelta":5}; - var iob_data = {"iob":0.5,"activity":0.01,"bolusiob":0.6}; - var meal_data = {"dia_carbs":20,"dia_bolused":1}; + var iob_data = {"iob":0.5,"activity":0.01,"bolussnooze":0.6,"basaliob":-0.1}; + var meal_data = {"carbs":20,"boluses":1, "mealCOB":20}; var currenttemp = {"duration":10,"rate":2,"temp":"absolute"}; - var output = determine_basal(glucose_status, currenttemp, iob_data, profile, undefined,setTempBasal); + var output = determine_basal(glucose_status, currenttemp, iob_data, profile, undefined, meal_data, tempBasalFunctions); + console.log(output); output.rate.should.be.above(2.2); output.duration.should.equal(30); }); @@ -447,57 +574,173 @@ describe('determine-basal', function ( ) { // 75m after 20g 1U meal bolus it('should reduce high-temp when 160 and dropping slowly after meal bolus', function () { var glucose_status = {"delta":-3,"glucose":160,"avgdelta":0}; - var iob_data = {"iob":0.9,"activity":0.02,"bolusiob":0.5}; - var meal_data = {"dia_carbs":20,"dia_bolused":1}; + var iob_data = {"iob":0.9,"activity":0.02,"bolussnooze":0.5,"basaliob":0.4}; + var meal_data = {"carbs":20,"boluses":1, "mealCOB":20}; var currenttemp = {"duration":30,"rate":2.5,"temp":"absolute"}; - var output = determine_basal(glucose_status, currenttemp, iob_data, profile, undefined,setTempBasal); + var output = determine_basal(glucose_status, currenttemp, iob_data, profile, undefined, meal_data, tempBasalFunctions); output.rate.should.be.below(1.5); }); -/* // right after 120g 6U meal bolus it('should high-temp when 120 and rising after meal bolus', function () { - var glucose_status = {"delta":1,"glucose":120,"avgdelta":1}; - var iob_data = {"iob":6,"activity":0,"bolusiob":6}; - var meal_data = {"dia_carbs":120,"dia_bolused":6}; - var output = determine_basal(glucose_status, currenttemp, iob_data, profile, undefined,setTempBasal); + var glucose_status = {"delta":4,"glucose":120,"avgdelta":4}; + var iob_data = {"iob":6,"activity":0,"bolussnooze":6,"basaliob":0,"hightempinsulin":0}; + var meal_data = {"carbs":120,"boluses":6, "mealCOB":120}; + var output = determine_basal(glucose_status, currenttemp, iob_data, profile, undefined, meal_data, tempBasalFunctions); + console.log(output); output.rate.should.be.above(1); output.duration.should.equal(30); }); // after 120g 6U meal bolus it('should high-temp when 140 and rising after meal bolus', function () { - var glucose_status = {"delta":1,"glucose":140,"avgdelta":1}; - //TODO: figure out how to track basal_iob vs. net_iob - var iob_data = {"iob":6.5,"activity":0.01,"bolusiob":5.5}; - var meal_data = {"dia_carbs":120,"dia_bolused":6}; - var output = determine_basal(glucose_status, currenttemp, iob_data, profile, undefined,setTempBasal); + var glucose_status = {"delta":4,"glucose":140,"avgdelta":4}; + var iob_data = {"iob":6.5,"activity":0.01,"bolussnooze":5.5,"basaliob":1,"hightempinsulin":1}; + var meal_data = {"carbs":120,"boluses":6, "mealCOB":100}; + var output = determine_basal(glucose_status, currenttemp, iob_data, profile, undefined, meal_data, tempBasalFunctions); + console.log(output); output.rate.should.be.above(1); output.duration.should.equal(30); }); // after 120g 6U meal bolus it('should high-temp when 160 and rising after meal bolus', function () { - var glucose_status = {"delta":1,"glucose":160,"avgdelta":1}; - //TODO: figure out how to track basal_iob vs. net_iob - var iob_data = {"iob":7.0,"activity":0.02,"bolusiob":5}; - var meal_data = {"dia_carbs":120,"dia_bolused":6}; - var output = determine_basal(glucose_status, currenttemp, iob_data, profile, undefined,setTempBasal); + var glucose_status = {"delta":4,"glucose":160,"avgdelta":4}; + var iob_data = {"iob":7.0,"activity":0.02,"bolussnooze":5.0,"basaliob":2,"hightempinsulin":2}; + var meal_data = {"carbs":120,"boluses":6, "mealCOB":80}; + var output = determine_basal(glucose_status, currenttemp, iob_data, profile, undefined, meal_data, tempBasalFunctions); + console.log(output); output.rate.should.be.above(1); output.duration.should.equal(30); }); -*/ + + // after 120g 6U meal bolus + it('should not high-temp when 160 and rising slowly after meal bolus', function () { + var glucose_status = {"delta":1,"glucose":160,"avgdelta":1}; + var iob_data = {"iob":7.0,"activity":0.02,"bolussnooze":5.0,"basaliob":2}; + var meal_data = {"carbs":120,"boluses":6, "mealCOB":80}; + var output = determine_basal(glucose_status, currenttemp, iob_data, profile, undefined, meal_data, tempBasalFunctions); + console.log(output); + //should.not.exist(output.rate); + //should.not.exist(output.duration); + output.rate.should.equal(0.9); + output.duration.should.equal(30); + }); // after 120g 6U meal bolus it('should cancel temp when 160 and falling after meal bolus', function () { var glucose_status = {"delta":-1,"glucose":160,"avgdelta":-1}; - //TODO: figure out how to track basal_iob vs. net_iob - var iob_data = {"iob":7.0,"activity":0.03,"bolusiob":5}; - var meal_data = {"dia_carbs":120,"dia_bolused":6}; + var iob_data = {"iob":7.0,"activity":0.03,"bolussnooze":5.0,"basaliob":2}; + var meal_data = {"carbs":120,"boluses":6, "mealCOB":80}; var currenttemp = {"duration":15,"rate":2.5,"temp":"absolute"}; - var output = determine_basal(glucose_status, currenttemp, iob_data, profile, undefined,setTempBasal); + var output = determine_basal(glucose_status, currenttemp, iob_data, profile, undefined, meal_data, tempBasalFunctions); + output.rate.should.equal(0.9); + output.duration.should.equal(30); + //output.rate.should.equal(0); + //output.duration.should.equal(0); + }); + + it('should not set temp when boluses + basal IOB cover meal carbs', function () { + var glucose_status = {"delta":1,"glucose":160,"avgdelta":1}; + var iob_data = {"iob":7.0,"activity":0.02,"bolussnooze":4.0,"basaliob":3}; + var meal_data = {"carbs":120,"boluses":11, "mealCOB":80}; + var output = determine_basal(glucose_status, currenttemp, iob_data, profile, undefined, meal_data, tempBasalFunctions); + console.log(output); + output.rate.should.equal(0.9); + output.duration.should.equal(30); + //(typeof output.rate).should.equal('undefined'); + //(typeof output.duration).should.equal('undefined'); + }); + + it('should not set temp when boluses + basal IOB cover meal carbs', function () { + var meal_data = {"carbs":15,"boluses":2, "mealCOB":15} + var glucose_status = {"delta":3,"glucose":200,"avgdelta":8.667} + var currenttemp = {"duration":3,"rate":3.5,"temp":"absolute"} + var iob_data = {"iob":2.701,"activity":0.0107,"bolussnooze":0.866,"basaliob":1.013,"netbasalinsulin":1.1,"hightempinsulin":1.8} + var profile_data = {"max_iob":3,"type":"current","dia":3,"current_basal":0.9,"max_daily_basal":1.3,"max_basal":3.5,"min_bg":105,"max_bg":105,"sens":40,"carb_ratio":10} + var output = determine_basal(glucose_status, currenttemp, iob_data, profile, undefined, meal_data, tempBasalFunctions); + //console.log(output); + //output.rate.should.equal(0.9); + //output.duration.should.equal(30); + //(typeof output.rate).should.equal('undefined'); + //(typeof output.duration).should.equal('undefined'); + }); + */ + + it('should temp to zero with double sensitivity adjustment', function () { + //var glucose_status = {"delta":1,"glucose":160,"avgdelta":1}; + var iob_data = {"iob":0.5,"activity":0.001,"bolussnooze":0.0,"basaliob":0.5}; + var autosens_data = {"ratio":0.5}; + var output = determine_basal(glucose_status, currenttemp, iob_data, profile, autosens_data, meal_data, tempBasalFunctions); + //console.log(output); output.rate.should.equal(0); - output.duration.should.equal(0); + output.duration.should.equal(30); + }); + + it('maxSafeBasal current_basal_safety_multiplier of 1 should cause the current rate to be set, even if higher is needed', function () { + var glucose_status = {"delta":5,"glucose":185,"long_avgdelta":5,"short_avgdelta":5}; + var iob_data = {"iob":0,"activity":-0.01,"bolussnooze":0}; + profile.current_basal_safety_multiplier = 1; + var output = determine_basal(glucose_status, currenttemp, iob_data, profile, undefined, meal_data, tempBasalFunctions); + output.rate.should.equal(0.9); + output.reason.should.match(/.*, adj. req. rate:.* to maxSafeBasal:.*, no temp, setting/); + }); + + it('maxSafeBasal max_daily_safety_multiplier of 1 should cause the max daily rate to be set, even if higher is needed', function () { + var glucose_status = {"delta":5,"glucose":185,"long_avgdelta":5,"short_avgdelta":5}; + var iob_data = {"iob":0,"activity":-0.01,"bolussnooze":0}; + profile.current_basal_safety_multiplier = null; + profile.max_daily_safety_multiplier = 1; + var output = determine_basal(glucose_status, currenttemp, iob_data, profile, undefined, meal_data, tempBasalFunctions); + output.rate.should.equal(1.3); + output.reason.should.match(/.*, adj. req. rate:.* to maxSafeBasal:.*, no temp, setting/); + }); + + it('overriding maxSafeBasal multipliers to 10 should increase temp', function () { + var glucose_status = {"delta":5,"glucose":285,"long_avgdelta":5,"short_avgdelta":5}; + var iob_data = {"iob":0,"activity":-0.01,"bolussnooze":0}; + profile.max_basal = 5; + profile.current_basal_safety_multiplier = 10; + profile.max_daily_safety_multiplier = 10; + var output = determine_basal(glucose_status, currenttemp, iob_data, profile, undefined, meal_data, tempBasalFunctions); + output.rate.should.equal(5); + output.reason.should.match(/.*, adj. req. rate:.* to maxSafeBasal:.*, no temp, setting/); + }); + + it('should round appropriately for small basals when setting basal to maxSafeBasal ', function () { + var glucose_status = {"delta":5,"glucose":185,"long_avgdelta":5,"short_avgdelta":5}; + var profile2 = {"max_iob":2.5,"dia":3,"type":"current","current_basal":0.025,"max_daily_basal":1.3,"max_basal":.05,"max_bg":120,"min_bg":110,"sens":200,"model":"523"}; + var currenttemp = {"duration":0,"rate":0,"temp":"absolute"}; + var output = determine_basal(glucose_status, currenttemp, iob_data, profile2, undefined, meal_data, tempBasalFunctions); + output.rate.should.equal(0.05); + output.duration.should.equal(30); + output.reason.should.match(/.*, adj. req. rate:.* to maxSafeBasal: 0.05, no temp, setting 0.05/); + }); + + it('should match the basal rate precision available on a 523', function () { + //var currenttemp = {"duration":30,"rate":0,"temp":"absolute"}; + var currenttemp = {"duration":0,"rate":0,"temp":"absolute"}; + profile.current_basal = 0.825; + profile.model = "523"; + var output = determine_basal(glucose_status, currenttemp, iob_data, profile, undefined, meal_data, tempBasalFunctions); + //output.rate.should.equal(0); + //output.duration.should.equal(0); + output.rate.should.equal(0.825); + output.duration.should.equal(30); + output.reason.should.match(/in range.*/); + }); + + it('should match the basal rate precision available on a 522', function () { + //var currenttemp = {"duration":30,"rate":0,"temp":"absolute"}; + var currenttemp = {"duration":0,"rate":0,"temp":"absolute"}; + profile.current_basal = 0.875; + profile.model = "522"; + var output = determine_basal(glucose_status, currenttemp, iob_data, profile, undefined, meal_data, tempBasalFunctions); + //output.rate.should.equal(0); + //output.duration.should.equal(0); + output.rate.should.equal(0.9); + output.duration.should.equal(30); + output.reason.should.match(/in range.*/); }); }); diff --git a/tests/get-last-glucose.test.js b/tests/get-last-glucose.test.js index ea2894dce..d1a7430bd 100644 --- a/tests/get-last-glucose.test.js +++ b/tests/get-last-glucose.test.js @@ -7,9 +7,27 @@ describe('getLastGlucose', function ( ) { var getLastGlucose = require('../lib/glucose-get-last.js'); it('should handle NS sgv fields', function () { - var glucose_status = getLastGlucose([{sgv: 100}, {sgv: 95}, {sgv: 90}, {sgv: 70}]); + var glucose_status = getLastGlucose([{date: 1467942845000, sgv: 100}, {date: 1467942544500, sgv: 95}, {date: 1467942244000, sgv: 85}, {date: 1467941944000, sgv: 70}]); + //console.log(glucose_status); glucose_status.delta.should.equal(5); glucose_status.glucose.should.equal(100); - glucose_status.avgdelta.should.equal(10); + glucose_status.short_avgdelta.should.equal(7.5); + glucose_status.long_avgdelta.should.equal(0); }); -}); \ No newline at end of file + it('should handle two receivers 30s and 3 mg/dL offset', function () { + var glucose_status = getLastGlucose([{date: 1467942875000, sgv: 103}, {date: 1467942845000, sgv: 100}, {date: 1467942574500, sgv: 98}, {date: 1467942544500, sgv: 95}, {date: 1467942274000, sgv: 88}, {date: 1467942244000, sgv: 85}, {date: 1467941974000, sgv: 73}, {date: 1467941944000, sgv: 70}]); + //console.log(glucose_status); + glucose_status.delta.should.equal(5); + glucose_status.glucose.should.equal(101.5); + glucose_status.short_avgdelta.should.equal(7.5); + glucose_status.long_avgdelta.should.equal(0); + }); + it('should handle fields named glucose and calculate long_avgdelta', function () { + var glucose_status = getLastGlucose([{"date": 1469509700000, "glucose": 97}, {"date": 1469509400000, "glucose": 94}, {"date": 1469509100000, "glucose": 87}, {"date": 1469508800000, "glucose": 81}, {"date": 1469508500000, "glucose": 78}, {"date": 1469508200000, "glucose": 78}, {"date": 1469507900000, "glucose": 81}, {"date": 1469507600000, "glucose": 84}, {"date": 1469507300000, "glucose": 87}, {"date": 1469507000000, "glucose": 93}, {"date": 1469506700000, "glucose": 102}, {"date": 1469506400000, "glucose": 104}, {"date": 1469506100000, "glucose": 99}, {"date": 1469505800000, "glucose": 81}, {"date": 1469505500000, "glucose": 76}, {date: 1469509700000, glucose: 97}]); + //console.log(glucose_status); + glucose_status.delta.should.equal(3); + glucose_status.glucose.should.equal(97); + glucose_status.short_avgdelta.should.equal(4.44); + glucose_status.long_avgdelta.should.equal(2.86); + }); +}); diff --git a/tests/iob.test.js b/tests/iob.test.js index c5644c7ca..7a699e046 100644 --- a/tests/iob.test.js +++ b/tests/iob.test.js @@ -2,82 +2,1601 @@ require('should'); -describe('IOB', function ( ) { - - it('should calculate IOB', function() { - - var now = Date.now() - , timestamp = new Date(now).toISOString() - , inputs = { - clock: timestamp - , history: [{ - _type: 'Bolus' - , amount: 1 - , timestamp: timestamp - }] - , profile: { - dia: 3 - } - }; - - var rightAfterBolus = require('../lib/iob')(inputs); - rightAfterBolus.iob.should.equal(1); - rightAfterBolus.bolusiob.should.equal(1); - - var hourLaterInputs = inputs; - hourLaterInputs.clock = new Date(now + (60 * 60 * 1000)).toISOString(); - var hourLater = require('../lib/iob')(hourLaterInputs); - hourLater.iob.should.be.lessThan(1); - hourLater.bolusiob.should.be.lessThan(.5); - hourLater.iob.should.be.greaterThan(0); - - var afterDIAInputs = inputs; - afterDIAInputs.clock = new Date(now + (3 * 60 * 60 * 1000)).toISOString(); - var afterDIA = require('../lib/iob')(afterDIAInputs); - - afterDIA.iob.should.equal(0); - afterDIA.bolusiob.should.equal(0); - - }); - - it('should calculate IOB using a 4 hour duration', function() { - - var now = Date.now() - , timestamp = new Date(now).toISOString() - , inputs = { - clock: timestamp - , history: [{ - _type: 'Bolus' - , amount: 1 - , timestamp: timestamp - }] - , profile: { - dia: 4 - } - }; - - var rightAfterBolus = require('../lib/iob')(inputs); - rightAfterBolus.iob.should.equal(1); - rightAfterBolus.bolusiob.should.equal(1); - - var hourLaterInputs = inputs; - hourLaterInputs.clock = new Date(now + (60 * 60 * 1000)).toISOString(); - var hourLater = require('../lib/iob')(hourLaterInputs); - hourLater.iob.should.be.lessThan(1); - hourLater.bolusiob.should.be.lessThan(.5); - hourLater.iob.should.be.greaterThan(0); - - var after3hInputs = inputs; - after3hInputs.clock = new Date(now + (3 * 60 * 60 * 1000)).toISOString(); - var after3h = require('../lib/iob')(after3hInputs); - after3h.iob.should.be.greaterThan(0); - - var after4hInputs = inputs; - after4hInputs.clock = new Date(now + (4 * 60 * 60 * 1000)).toISOString(); - var after4h = require('../lib/iob')(after4hInputs); - after4h.iob.should.equal(0); - - }); - - -}); \ No newline at end of file +var moment = require('moment'); + +describe('IOB', function() { + + it('should calculate IOB', function() { + + var basalprofile = [{ + 'i': 0, + 'start': '00:00:00', + 'rate': 1, + 'minutes': 0 + }]; + + var now = Date.now(), + timestamp = new Date(now).toISOString(), + inputs = { + clock: timestamp, + history: [{ + _type: 'Bolus', + amount: 2, + timestamp: timestamp + }], + profile: { + dia: 3, + //bolussnooze_dia_divisor: 2, + basalprofile: basalprofile, + current_basal: 1, + max_daily_basal: 1 + } + + }; + + var rightAfterBolus = require('../lib/iob')(inputs)[0]; + rightAfterBolus.iob.should.equal(2); + //rightAfterBolus.bolussnooze.should.equal(2); + + var hourLaterInputs = inputs; + hourLaterInputs.clock = new Date(now + (60 * 60 * 1000)).toISOString(); + var hourLater = require('../lib/iob')(hourLaterInputs)[0]; + hourLater.iob.should.be.lessThan(1.45); + //hourLater.bolussnooze.should.be.lessThan(.5); + hourLater.iob.should.be.greaterThan(0); + hourLater.activity.should.be.greaterThan(0.01); + hourLater.activity.should.be.lessThan(0.02); + + var afterDIAInputs = inputs; + afterDIAInputs.clock = new Date(now + (3 * 60 * 60 * 1000)).toISOString(); + var afterDIA = require('../lib/iob')(afterDIAInputs)[0]; + + afterDIA.iob.should.equal(0); + //afterDIA.bolussnooze.should.equal(0); + }); + + it('should calculate IOB with Ultra-fast curve', function() { + + var basalprofile = [{ + 'i': 0, + 'start': '00:00:00', + 'rate': 1, + 'minutes': 0 + }]; + + var now = Date.now(), + timestamp = new Date(now).toISOString(), + inputs = { + clock: timestamp, + history: [{ + _type: 'Bolus', + amount: 2, + timestamp: timestamp + }], + profile: { + dia: 5, + //bolussnooze_dia_divisor: 2, + basalprofile: basalprofile, + current_basal: 1, + max_daily_basal: 1, + curve: 'ultra-rapid' + } + }; + + var rightAfterBolus = require('../lib/iob')(inputs)[0]; + + rightAfterBolus.iob.should.equal(2); + //rightAfterBolus.bolussnooze.should.equal(2); + + var hourLaterInputs = inputs; + hourLaterInputs.clock = new Date(now + (60 * 60 * 1000)).toISOString(); + var hourLater = require('../lib/iob')(hourLaterInputs)[0]; + hourLater.iob.should.be.lessThan(1.6); + hourLater.iob.should.be.greaterThan(1.3); + + //hourLater.bolussnooze.should.be.lessThan(1.7); + hourLater.iob.should.be.greaterThan(0); + hourLater.activity.should.be.greaterThan(0.006); + hourLater.activity.should.be.lessThan(0.015); + + var afterDIAInputs = inputs; + afterDIAInputs.clock = new Date(now + (5 * 60 * 60 * 1000)).toISOString(); + var afterDIA = require('../lib/iob')(afterDIAInputs)[0]; + afterDIA.iob.should.equal(0); + //afterDIA.bolussnooze.should.equal(0); + }); + + it('should calculate IOB with Ultra-fast peak setting of 55', function() { + + var basalprofile = [{ + 'i': 0, + 'start': '00:00:00', + 'rate': 1, + 'minutes': 0 + }]; + + var now = Date.now(), + timestamp = new Date(now).toISOString(), + inputs = { + clock: timestamp, + history: [{ + _type: 'Bolus', + amount: 1, + timestamp: timestamp + }], + profile: { + dia: 5, + insulinPeakTime: 55, + //bolussnooze_dia_divisor: 2, + basalprofile: basalprofile, + current_basal: 1, + max_daily_basal: 1, + curve: 'ultra-rapid' + } + }; + + var rightAfterBolus = require('../lib/iob')(inputs)[0]; + rightAfterBolus.iob.should.equal(1); + //rightAfterBolus.bolussnooze.should.equal(1); + + var hourLaterInputs = inputs; + hourLaterInputs.clock = new Date(now + (60 * 60 * 1000)).toISOString(); + var hourLater = require('../lib/iob')(hourLaterInputs)[0]; + hourLater.iob.should.be.lessThan(0.75); + //hourLater.bolussnooze.should.be.lessThan(0.75); + hourLater.iob.should.be.greaterThan(0); + hourLater.activity.should.be.greaterThan(0.0065); + hourLater.activity.should.be.lessThan(0.008); + + var afterDIAInputs = inputs; + afterDIAInputs.clock = new Date(now + (5 * 60 * 60 * 1000)).toISOString(); + var afterDIA = require('../lib/iob')(afterDIAInputs)[0]; + + afterDIA.iob.should.equal(0); + //afterDIA.bolussnooze.should.equal(0); + }); + + it('should calculate IOB with Ultra-fast curve peak setting of 65', function() { + + var basalprofile = [{ + 'i': 0, + 'start': '00:00:00', + 'rate': 1, + 'minutes': 0 + }]; + + var now = Date.now(), + timestamp = new Date(now).toISOString(), + inputs = { + clock: timestamp, + history: [{ + _type: 'Bolus', + amount: 1, + timestamp: timestamp + }], + profile: { + dia: 5, + insulinPeakTime: 65, + useCustomPeakTime: true, + //bolussnooze_dia_divisor: 2, + basalprofile: basalprofile, + current_basal: 1, + max_daily_basal: 1, + curve: 'ultra-rapid' + } + }; + + var rightAfterBolus = require('../lib/iob')(inputs)[0]; + rightAfterBolus.iob.should.equal(1); + //rightAfterBolus.bolussnooze.should.equal(1); + + var hourLaterInputs = inputs; + hourLaterInputs.clock = new Date(now + (60 * 60 * 1000)).toISOString(); + var hourLater = require('../lib/iob')(hourLaterInputs)[0]; + hourLater.iob.should.be.lessThan(0.77); + //hourLater.bolussnooze.should.be.lessThan(0.36); + hourLater.iob.should.be.greaterThan(0.72); + //hourLater.bolussnooze.should.be.greaterThan(0.354); + + hourLater.activity.should.be.greaterThan(0.0055); + hourLater.activity.should.be.lessThan(0.007); + + var afterDIAInputs = inputs; + afterDIAInputs.clock = new Date(now + (5 * 60 * 60 * 1000)).toISOString(); + var afterDIA = require('../lib/iob')(afterDIAInputs)[0]; + + afterDIA.iob.should.equal(0); + //afterDIA.bolussnooze.should.equal(0); + }); + + it('should calculate IOB with Ultra-rapid curve peak setting of 75', function() { + + var basalprofile = [{ + 'i': 0, + 'start': '00:00:00', + 'rate': 1, + 'minutes': 0 + }]; + + var now = Date.now(), + timestamp = new Date(now).toISOString(), + inputs = { + clock: timestamp, + history: [{ + _type: 'Bolus', + amount: 1, + timestamp: timestamp + }], + profile: { + dia: 5, + insulinPeakTime: 75, + useCustomPeakTime: true, + //bolussnooze_dia_divisor: 2, + basalprofile: basalprofile, + current_basal: 1, + max_daily_basal: 1, + curve: 'ultra-rapid' + } + }; + + var rightAfterBolus = require('../lib/iob')(inputs)[0]; + rightAfterBolus.iob.should.equal(1); + //rightAfterBolus.bolussnooze.should.equal(1); + + var hourLaterInputs = inputs; + hourLaterInputs.clock = new Date(now + (60 * 60 * 1000)).toISOString(); + var hourLater = require('../lib/iob')(hourLaterInputs)[0]; + hourLater.iob.should.be.lessThan(0.81); + //hourLater.bolussnooze.should.be.lessThan(0.5); + hourLater.iob.should.be.greaterThan(0.76); + //hourLater.bolussnooze.should.be.greaterThan(0.40); + + hourLater.iob.should.be.greaterThan(0); + hourLater.activity.should.be.greaterThan(0.0047); + hourLater.activity.should.be.lessThan(0.007); + + var afterDIAInputs = inputs; + afterDIAInputs.clock = new Date(now + (5 * 60 * 60 * 1000)).toISOString(); + var afterDIA = require('../lib/iob')(afterDIAInputs)[0]; + + afterDIA.iob.should.equal(0); + //afterDIA.bolussnooze.should.equal(0); + }); + + it('should calculate IOB with Ultra-rapid curve peak setting of 44 and DIA = 6', function() { + + var basalprofile = [{ + 'i': 0, + 'start': '00:00:00', + 'rate': 1, + 'minutes': 0 + }]; + + var now = Date.now(), + timestamp = new Date(now).toISOString(), + inputs = { + clock: timestamp, + history: [{ + _type: 'Bolus', + amount: 1, + timestamp: timestamp + }], + profile: { + dia: 6, + insulinPeakTime: 44, + useCustomPeakTime: true, + //bolussnooze_dia_divisor: 2, + basalprofile: basalprofile, + current_basal: 1, + max_daily_basal: 1, + curve: 'ultra-rapid' + } + }; + + var rightAfterBolus = require('../lib/iob')(inputs)[0]; + rightAfterBolus.iob.should.equal(1); + //rightAfterBolus.bolussnooze.should.equal(1); + + var hourLaterInputs = inputs; + hourLaterInputs.clock = new Date(now + (60 * 60 * 1000)).toISOString(); + var hourLater = require('../lib/iob')(hourLaterInputs)[0]; + hourLater.iob.should.be.lessThan(0.59); + //hourLater.bolussnooze.should.be.lessThan(0.23); + + hourLater.iob.should.be.greaterThan(0.57); + //hourLater.bolussnooze.should.be.greaterThan(0.21); + + hourLater.activity.should.be.greaterThan(0.007); + hourLater.activity.should.be.lessThan(0.0085); + + var afterDIAInputs = inputs; + afterDIAInputs.clock = new Date(now + (6 * 60 * 60 * 1000)).toISOString(); + var afterDIA = require('../lib/iob')(afterDIAInputs)[0]; + + afterDIA.iob.should.equal(0); + //afterDIA.bolussnooze.should.equal(0); + }); + + it('should calculate IOB with Rapid-acting', function() { + + var basalprofile = [{ + 'i': 0, + 'start': '00:00:00', + 'rate': 1, + 'minutes': 0 + }]; + + var now = Date.now(), + timestamp = new Date(now).toISOString(), + inputs = { + clock: timestamp, + history: [{ + _type: 'Bolus', + amount: 1, + timestamp: timestamp + }], + profile: { + dia: 5, + //bolussnooze_dia_divisor: 2, + basalprofile: basalprofile, + current_basal: 1, + max_daily_basal: 1, + curve: 'rapid-acting' + } + }; + + var rightAfterBolus = require('../lib/iob')(inputs)[0]; + rightAfterBolus.iob.should.equal(1); + //rightAfterBolus.bolussnooze.should.equal(1); + + var hourLaterInputs = inputs; + hourLaterInputs.clock = new Date(now + (60 * 60 * 1000)).toISOString(); + var hourLater = require('../lib/iob')(hourLaterInputs)[0]; + hourLater.iob.should.be.lessThan(0.8); + //hourLater.bolussnooze.should.be.lessThan(.8); + hourLater.iob.should.be.greaterThan(0); + + var afterDIAInputs = inputs; + afterDIAInputs.clock = new Date(now + (5 * 60 * 60 * 1000)).toISOString(); + var afterDIA = require('../lib/iob')(afterDIAInputs)[0]; + + afterDIA.iob.should.equal(0); + //afterDIA.bolussnooze.should.equal(0); + }); + + it('should force minimum 5 hour DIA with Rapid-acting', function() { + + var basalprofile = [{ + 'i': 0, + 'start': '00:00:00', + 'rate': 1, + 'minutes': 0 + }]; + + var now = Date.now(), + timestamp = new Date(now).toISOString(), + inputs = { + clock: timestamp, + history: [{ + _type: 'Bolus', + amount: 1, + timestamp: timestamp + }], + profile: { + dia: 5, + //bolussnooze_dia_divisor: 2, + basalprofile: basalprofile, + current_basal: 1, + max_daily_basal: 1, + curve: 'rapid-acting' + } + }; + + var hourLaterInputs = inputs; + hourLaterInputs.clock = new Date(now + (4 * 60 * 60 * 1000)).toISOString(); + + var hourLaterWith5 = require('../lib/iob')(hourLaterInputs)[0]; + + console.error(hourLaterWith5.iob); + + hourLaterInputs.profile.dia = 3; + + var hourLaterWith4 = require('../lib/iob')(hourLaterInputs)[0]; + + console.error(hourLaterWith4.iob); + + hourLaterWith4.iob.should.equal(hourLaterWith5.iob); + }); + + //it('should snooze fast if bolussnooze_dia_divisor is high', function() { + + //var now = Date.now(), + //timestamp = new Date(now).toISOString(), + //inputs = { + //clock: timestamp, + //history: [{ + //_type: 'Bolus', + //amount: 1, + //timestamp: timestamp + //}], + //profile: { + //dia: 3, + //bolussnooze_dia_divisor: 10 + //} + //}; + + //var snoozeInputs = inputs; + //snoozeInputs.clock = new Date(now + (20 * 60 * 1000)).toISOString(); + //var snooze = require('../lib/iob')(snoozeInputs)[0]; + //snooze.bolussnooze.should.equal(0); + //}); + + it('should calculate IOB with Temp Basals', function() { + + var basalprofile = [{ + 'i': 0, + 'start': '00:00:00', + 'rate': 1, + 'minutes': 0 + }]; + var now = Date.now(), + timestamp = new Date(now).toISOString(), + timestamp30mAgo = new Date(now - (30 * 60 * 1000)).toISOString(), + timestamp60mAgo = new Date(now - (60 * 60 * 1000)).toISOString(), + inputs = { + clock: timestamp, + history: [{ + _type: 'TempBasalDuration', + 'duration (min)': 30, + date: timestamp60mAgo, + timestamp: timestamp60mAgo + }, { + _type: 'TempBasal', + rate: 2, + date: timestamp60mAgo, + timestamp: timestamp60mAgo + }, { + _type: 'TempBasal', + rate: 2, + date: timestamp30mAgo, + timestamp: timestamp30mAgo + }, { + _type: 'TempBasalDuration', + 'duration (min)': 30, + date: timestamp, + timestamp: timestamp + }], + profile: { + dia: 3, + current_basal: 1, + max_daily_basal: 1, + //bolussnooze_dia_divisor: 2, + 'basalprofile': basalprofile + } + }; + + var iobInputs = inputs; + iobInputs.clock = timestamp + var iobNow = require('../lib/iob')(iobInputs)[0]; + + //console.log(iobNow); + iobNow.iob.should.be.lessThan(1); + iobNow.iob.should.be.greaterThan(0.5); + }); + + it('should calculate IOB with Temp Basals and a basal profile', function() { + + var startingPoint = moment('2016-06-13 01:00:00.000'); + var timestamp = startingPoint.format(); + var timestampEarly = startingPoint.subtract(30, 'minutes').format(); + + var basalprofile = [{ + 'i': 0, + 'start': '00:00:00', + 'rate': 2, + 'minutes': 0 + }, + { + 'i': 1, + 'start': '01:00:00', + 'rate': 1, + 'minutes': 60 + } + ]; + + var inputs = { + clock: timestamp, + history: [{ + _type: 'TempBasalDuration', + 'duration (min)': 30, + date: timestampEarly, + timestamp: timestampEarly, + }, { + _type: 'TempBasal', + rate: 2, + date: timestampEarly, + timestamp: timestampEarly + }, { + _type: 'TempBasal', + rate: 2, + date: timestamp, + timestamp: timestamp + }, { + _type: 'TempBasalDuration', + 'duration (min)': 30, + date: timestamp, + timestamp: timestamp, + }], + profile: { + dia: 3, + //bolussnooze_dia_divisor: 2, + basalprofile: basalprofile + } + }; + + var hourLaterInputs = inputs; + hourLaterInputs.clock = moment('2016-06-13 01:30:00.000'); + var hourLater = require('../lib/iob')(hourLaterInputs)[0]; + hourLater.iob.should.be.lessThan(0.5); + hourLater.iob.should.be.greaterThan(0.4); + }); + + it('should calculate IOB with Temp Basals that overlap midnight and a basal profile', function() { + + var basalprofile = [{ + 'i': 0, + 'start': '00:00:00', + 'rate': 2, + 'minutes': 0 + }, + { + 'i': 1, + 'start': '00:15:00', + 'rate': 1, + 'minutes': 15 + }, + { + 'i': 2, + 'start': '00:45:00', + 'rate': 0.5, + 'minutes': 45 + } + ]; + + var startingPoint = moment('2016-06-13 00:15:00.000'); + var timestamp = startingPoint.format(); + var timestampEarly = startingPoint.subtract(30, 'minutes').format(), + inputs = { + clock: timestamp, + history: [{ + _type: 'TempBasalDuration', + 'duration (min)': 30, + date: timestampEarly, + timestamp: timestampEarly + }, { + _type: 'TempBasal', + rate: 2, + date: timestampEarly, + timestamp: timestampEarly + }, { + _type: 'TempBasal', + rate: 2, + date: timestamp, + timestamp: timestamp + }, { + _type: 'TempBasalDuration', + 'duration (min)': 30, + date: timestamp, + timestamp: timestamp + }], + profile: { + dia: 3, + current_basal: 0.1, + max_daily_basal: 1, + //bolussnooze_dia_divisor: 2, + basalprofile: basalprofile + } + }; + + var hourLaterInputs = inputs; + hourLaterInputs.clock = moment('2016-06-13 00:45:00.000'); //new Date(now + (30 * 60 * 1000)).toISOString(); + var hourLater = require('../lib/iob')(hourLaterInputs)[0]; + + hourLater.iob.should.be.lessThan(0.8); + hourLater.iob.should.be.greaterThan(0.7); + }); + + it('should calculate IOB with Temp Basals that overlap each other', function() { + + var nowDate = new Date(); + var now = Date.now(); + + var basalprofile = [{ + 'i': 0, + 'start': '00:00:00', + 'rate': 1, + 'minutes': 0 + }]; + + var startingPoint = moment('2016-06-13 00:30:00.000'); + var timestampEarly = moment('2016-06-13 00:30:00.000').subtract(30, 'minutes'); + var timestampEarly2 = moment('2016-06-13 00:30:00.000').subtract(29, 'minutes'); + var timestampEarly3 = moment('2016-06-13 00:30:00.000').subtract(28, 'minutes'); + + var timestamp = startingPoint; + var inputs = { + clock: timestamp, + history: [{ + _type: 'TempBasalDuration', + 'duration (min)': 30, + date: timestampEarly.unix(), + timestamp: timestampEarly.format() + }, { + _type: 'TempBasal', + rate: 2, + date: timestampEarly.unix(), + timestamp: timestampEarly.format() + }, { + _type: 'TempBasalDuration', + 'duration (min)': 30, + date: timestampEarly2.unix(), + timestamp: timestampEarly2.format() + }, { + _type: 'TempBasal', + rate: 2, + date: timestampEarly2.unix(), + timestamp: timestampEarly2.format() + }, { + _type: 'TempBasalDuration', + 'duration (min)': 30, + date: timestampEarly3.unix(), + timestamp: timestampEarly3.format() + }, { + _type: 'TempBasal', + rate: 2, + date: timestampEarly3.unix(), + timestamp: timestampEarly3.format() + }, { + _type: 'TempBasal', + rate: 2, + date: timestamp.unix(), + timestamp: timestamp.format() + }, { + _type: 'TempBasalDuration', + 'duration (min)': 30, + date: timestamp.unix(), + timestamp: timestamp.format() + }], + profile: { + dia: 3, + current_basal: 0.1, + max_daily_basal: 1, + //bolussnooze_dia_divisor: 2, + basalprofile: basalprofile + } + }; + + var hourLaterInputs = inputs; + hourLaterInputs.clock = moment('2016-06-13 00:30:00.000'); //new Date(now + (30 * 60 * 1000)).toISOString(); + var hourLater = require('../lib/iob')(hourLaterInputs)[0]; + + hourLater.iob.should.be.lessThan(0.5); + hourLater.iob.should.be.greaterThan(0.45); + }); + + it('should calculate IOB with Temp Basals that overlap midnight and a basal profile, part deux', function() { + + var nowDate = new Date(); + var now = Date.now(); + + var basalprofile = [{ + 'i': 0, + 'start': '00:00:00', + 'rate': 2, + 'minutes': 0 + }, + { + 'i': 1, + 'start': '00:15:00', + 'rate': 0.1, + 'minutes': 15 + }, + { + 'i': 1, + 'start': '00:30:00', + 'rate': 2, + 'minutes': 30 + }, + { + 'i': 1, + 'start': '00:45:00', + 'rate': 0.1, + 'minutes': 45 + } + ]; + + var startingPoint = moment('2016-06-13 23:45:00.000'); + var timestamp = startingPoint.format(); + var timestampEarly = startingPoint.subtract(30, 'minutes').format(), + inputs = { + clock: timestamp, + history: [{ + _type: 'TempBasalDuration', + 'duration (min)': 60, + date: timestamp, + timestamp: timestamp + }, { + _type: 'TempBasal', + rate: 2, + date: timestamp, + timestamp: timestamp + }], + profile: { + dia: 3, + current_basal: 0.1, + max_daily_basal: 1, + //bolussnooze_dia_divisor: 2, + basalprofile: basalprofile + } + }; + + var hourLaterInputs = inputs; + hourLaterInputs.clock = moment('2016-06-14 00:45:00.000'); //new Date(now + (30 * 60 * 1000)).toISOString(); + var hourLater = require('../lib/iob')(hourLaterInputs)[0]; + + hourLater.iob.should.be.lessThan(1); + hourLater.iob.should.be.greaterThan(0.8); + }); + + it('should calculate IOB without counting time pump suspended at end of basal', function() { + + var basalprofile = [{ + 'i': 0, + 'start': '00:00:00', + 'rate': 1, + 'minutes': 0 + }]; + var now = Date.now(), + timestamp = new Date(now).toISOString(), + timestamp15mAgo = new Date(now - (15 * 60 * 1000)).toISOString(), + timestamp30mAgo = new Date(now - (30 * 60 * 1000)).toISOString(), + timestamp45mAgo = new Date(now - (45 * 60 * 1000)).toISOString(), + timestamp60mAgo = new Date(now - (60 * 60 * 1000)).toISOString(), + timestamp75mAgo = new Date(now - (75 * 60 * 1000)).toISOString(), + + inputs = { + clock: timestamp, + history: [{ + _type: 'TempBasalDuration', + 'duration (min)': 15, + date: timestamp60mAgo, + timestamp: timestamp60mAgo + }, { + _type: 'TempBasal', + rate: 2, + date: timestamp60mAgo, + timestamp: timestamp60mAgo + }, { + _type: 'TempBasalDuration', + 'duration (min)': 15, + date: timestamp45mAgo, + timestamp: timestamp45mAgo + }, { + _type: 'TempBasal', + rate: 0, + date: timestamp45mAgo, + timestamp: timestamp45mAgo + }], + profile: { + dia: 3, + current_basal: 1, + suspend_zeros_iob: true, + max_daily_basal: 1, + //bolussnooze_dia_divisor: 2, + 'basalprofile': basalprofile + } + }; + + var iobInputs = inputs; + + // Calculate IOB with inputs that will be the same as + var iobNowWithoutSuspend = require('../lib/iob')(iobInputs)[0]; + + inputs = { + clock: timestamp, + history: [{ + _type: 'TempBasalDuration', + 'duration (min)': 30, + date: timestamp60mAgo, + timestamp: timestamp60mAgo + }, { + _type: 'TempBasal', + rate: 2, + date: timestamp60mAgo, + timestamp: timestamp60mAgo + }, { + _type: 'PumpSuspend', + date: timestamp45mAgo, + timestamp: timestamp45mAgo + }, { + _type: 'PumpResume', + date: timestamp30mAgo, + timestamp: timestamp30mAgo + }], + profile: { + dia: 3, + current_basal: 1, + suspend_zeros_iob: true, + max_daily_basal: 1, + //bolussnooze_dia_divisor: 2, + 'basalprofile': basalprofile + } + }; + + iobInputs = inputs; + + var iobNowWithSuspend = require('../lib/iob')(iobInputs)[0]; + + iobNowWithSuspend.iob.should.equal(iobNowWithoutSuspend.iob); + }); + + it('should calculate IOB without counting time pump suspended in middle of basal', function() { + + var basalprofile = [{ + 'i': 0, + 'start': '00:00:00', + 'rate': 1, + 'minutes': 0 + }]; + var now = Date.now(), + timestamp = new Date(now).toISOString(), + timestamp15mAgo = new Date(now - (15 * 60 * 1000)).toISOString(), + timestamp30mAgo = new Date(now - (30 * 60 * 1000)).toISOString(), + timestamp45mAgo = new Date(now - (45 * 60 * 1000)).toISOString(), + timestamp60mAgo = new Date(now - (60 * 60 * 1000)).toISOString(), + timestamp75mAgo = new Date(now - (75 * 60 * 1000)).toISOString(), + + inputs = { + clock: timestamp, + history: [{ + _type: 'TempBasalDuration', + 'duration (min)': 15, + date: timestamp60mAgo, + timestamp: timestamp60mAgo + }, { + _type: 'TempBasal', + rate: 2, + date: timestamp60mAgo, + timestamp: timestamp60mAgo + }, { + _type: 'TempBasalDuration', + 'duration (min)': 15, + date: timestamp45mAgo, + timestamp: timestamp45mAgo + }, { + _type: 'TempBasal', + rate: 0, + date: timestamp45mAgo, + timestamp: timestamp45mAgo + }, { + _type: 'TempBasalDuration', + 'duration (min)': 15, + date: timestamp30mAgo, + timestamp: timestamp30mAgo + }, { + _type: 'TempBasal', + rate: 2, + date: timestamp30mAgo, + timestamp: timestamp30mAgo + }], + profile: { + dia: 3, + current_basal: 1, + suspend_zeros_iob: true, + max_daily_basal: 1, + //bolussnooze_dia_divisor: 2, + 'basalprofile': basalprofile + } + }; + + var iobInputs = inputs; + + var iobNowWithoutSuspend = require('../lib/iob')(iobInputs)[0]; + + inputs = { + clock: timestamp, + history: [{ + _type: 'TempBasalDuration', + 'duration (min)': 45, + date: timestamp60mAgo, + timestamp: timestamp60mAgo + }, { + _type: 'TempBasal', + rate: 2, + date: timestamp60mAgo, + timestamp: timestamp60mAgo + }, { + _type: 'PumpSuspend', + date: timestamp45mAgo, + timestamp: timestamp45mAgo + }, { + _type: 'PumpResume', + date: timestamp30mAgo, + timestamp: timestamp30mAgo + }], + profile: { + dia: 3, + current_basal: 1, + suspend_zeros_iob: true, + max_daily_basal: 1, + //bolussnooze_dia_divisor: 2, + 'basalprofile': basalprofile + } + }; + + iobInputs = inputs; + + var iobNowWithSuspend = require('../lib/iob')(iobInputs)[0]; + + iobNowWithSuspend.iob.should.equal(iobNowWithoutSuspend.iob); + }); + + it('should calculate IOB without counting time pump suspended surrounding a basal', function() { + + var basalprofile = [{ + 'i': 0, + 'start': '00:00:00', + 'rate': 1, + 'minutes': 0 + }]; + var now = Date.now(), + timestamp = new Date(now).toISOString(), + timestamp15mAgo = new Date(now - (15 * 60 * 1000)).toISOString(), + timestamp30mAgo = new Date(now - (30 * 60 * 1000)).toISOString(), + timestamp45mAgo = new Date(now - (45 * 60 * 1000)).toISOString(), + timestamp60mAgo = new Date(now - (60 * 60 * 1000)).toISOString(), + timestamp75mAgo = new Date(now - (75 * 60 * 1000)).toISOString(), + timestamp90mAgo = new Date(now - (90 * 60 * 1000)).toISOString(), + + inputs = { + clock: timestamp, + history: [{ + _type: 'TempBasalDuration', + 'duration (min)': 15, + date: timestamp90mAgo, + timestamp: timestamp90mAgo + }, { + _type: 'TempBasal', + rate: 2, + date: timestamp90mAgo, + timestamp: timestamp90mAgo + }, { + _type: 'TempBasalDuration', + 'duration (min)': 45, + date: timestamp75mAgo, + timestamp: timestamp75mAgo + }, { + _type: 'TempBasal', + rate: 0, + date: timestamp75mAgo, + timestamp: timestamp75mAgo + }, { + _type: 'TempBasalDuration', + 'duration (min)': 15, + date: timestamp30mAgo, + timestamp: timestamp30mAgo + }, { + _type: 'TempBasal', + rate: 2, + date: timestamp30mAgo, + timestamp: timestamp30mAgo + }], + profile: { + dia: 3, + current_basal: 1, + suspend_zeros_iob: true, + max_daily_basal: 1, + //bolussnooze_dia_divisor: 2, + 'basalprofile': basalprofile + } + }; + + var iobInputs = inputs; + + var iobNowWithoutSuspend = require('../lib/iob')(iobInputs)[0]; + + inputs = { + clock: timestamp, + history: [{ + _type: 'TempBasalDuration', + 'duration (min)': 30, + date: timestamp90mAgo, + timestamp: timestamp90mAgo + }, { + _type: 'TempBasal', + rate: 2, + date: timestamp90mAgo, + timestamp: timestamp90mAgo + }, { + _type: 'PumpSuspend', + date: timestamp75mAgo, + timestamp: timestamp75mAgo + }, { + _type: 'TempBasalDuration', + 'duration (min)': 15, + date: timestamp60mAgo, + timestamp: timestamp60mAgo + }, { + _type: 'TempBasal', + rate: 2, + date: timestamp60mAgo, + timestamp: timestamp60mAgo + }, { + _type: 'TempBasalDuration', + 'duration (min)': 30, + date: timestamp45mAgo, + timestamp: timestamp45mAgo + }, { + _type: 'TempBasal', + rate: 2, + date: timestamp45mAgo, + timestamp: timestamp45mAgo + }, { + _type: 'PumpResume', + date: timestamp30mAgo, + timestamp: timestamp30mAgo + }], + profile: { + dia: 3, + current_basal: 1, + suspend_zeros_iob: true, + max_daily_basal: 1, + //bolussnooze_dia_divisor: 2, + 'basalprofile': basalprofile + } + }; + + iobInputs = inputs; + + var iobNowWithSuspend = require('../lib/iob')(iobInputs)[0]; + + iobNowWithSuspend.iob.should.equal(iobNowWithoutSuspend.iob); + }); + + it('should calculate IOB without counting time pump suspended at beginning of basal', function() { + + var basalprofile = [{ + 'i': 0, + 'start': '00:00:00', + 'rate': 1, + 'minutes': 0 + }]; + var now = Date.now(), + timestamp = new Date(now).toISOString(), + timestamp15mAgo = new Date(now - (15 * 60 * 1000)).toISOString(), + timestamp30mAgo = new Date(now - (30 * 60 * 1000)).toISOString(), + timestamp45mAgo = new Date(now - (45 * 60 * 1000)).toISOString(), + timestamp60mAgo = new Date(now - (60 * 60 * 1000)).toISOString(), + timestamp75mAgo = new Date(now - (75 * 60 * 1000)).toISOString(), + + inputs = { + clock: timestamp, + history: [{ + _type: 'TempBasalDuration', + 'duration (min)': 15, + date: timestamp45mAgo, + timestamp: timestamp45mAgo + }, { + _type: 'TempBasal', + rate: 0, + date: timestamp45mAgo, + timestamp: timestamp45mAgo + }, { + _type: 'TempBasalDuration', + 'duration (min)': 15, + date: timestamp30mAgo, + timestamp: timestamp30mAgo + }, { + _type: 'TempBasal', + rate: 2, + date: timestamp30mAgo, + timestamp: timestamp30mAgo + }], + profile: { + dia: 3, + current_basal: 1, + suspend_zeros_iob: true, + max_daily_basal: 1, + //bolussnooze_dia_divisor: 2, + 'basalprofile': basalprofile + } + }; + + var iobInputs = inputs; + + var iobNowWithoutSuspend = require('../lib/iob')(iobInputs)[0]; + + inputs = { + clock: timestamp, + history: [{ + _type: 'PumpSuspend', + date: timestamp45mAgo, + timestamp: timestamp45mAgo + }, { + _type: 'TempBasalDuration', + 'duration (min)': 30, + date: timestamp45mAgo, + timestamp: timestamp45mAgo + }, { + _type: 'TempBasal', + rate: 2, + date: timestamp45mAgo, + timestamp: timestamp45mAgo + }, { + _type: 'PumpResume', + date: timestamp30mAgo, + timestamp: timestamp30mAgo + }], + profile: { + dia: 3, + current_basal: 1, + suspend_zeros_iob: true, + max_daily_basal: 1, + 'basalprofile': basalprofile + } + }; + + var iobInputs = inputs; + + var iobNowWithSuspend = require('../lib/iob')(iobInputs)[0]; + + iobNowWithSuspend.iob.should.equal(iobNowWithoutSuspend.iob); + }); + + it('should calculate IOB without counting time pump suspended when pump suspend prior to history start', function() { + + var basalprofile = [{ + 'i': 0, + 'start': '00:00:00', + 'rate': 1, + 'minutes': 0 + }]; + var now = Date.now(), + timestamp = new Date(now).toISOString(), + timestamp15mAgo = new Date(now - (15 * 60 * 1000)).toISOString(), + timestamp30mAgo = new Date(now - (30 * 60 * 1000)).toISOString(), + timestamp45mAgo = new Date(now - (45 * 60 * 1000)).toISOString(), + timestamp60mAgo = new Date(now - (60 * 60 * 1000)).toISOString(), + timestamp75mAgo = new Date(now - (75 * 60 * 1000)).toISOString(), + timestamp480mAgo = new Date(now - (480 * 60 * 1000)).toISOString(), + + inputs = { + clock: timestamp, + history: [{ + _type: 'TempBasalDuration', + 'duration (min)': 435, + date: timestamp480mAgo, + timestamp: timestamp480mAgo + }, { + _type: 'TempBasal', + rate: 0, + date: timestamp480mAgo, + timestamp: timestamp480mAgo + }, { + _type: 'TempBasalDuration', + 'duration (min)': 15, + date: timestamp45mAgo, + timestamp: timestamp45mAgo + }, { + _type: 'TempBasal', + rate: 2, + date: timestamp45mAgo, + timestamp: timestamp45mAgo + }], + profile: { + dia: 3, + current_basal: 1, + suspend_zeros_iob: true, + max_daily_basal: 1, + //bolussnooze_dia_divisor: 2, + 'basalprofile': basalprofile + } + }; + + var iobInputs = inputs; + + var iobNowWithoutSuspend = require('../lib/iob')(iobInputs)[0]; + + inputs = { + clock: timestamp, + history: [{ + _type: 'TempBasalDuration', + 'duration (min)': 30, + date: timestamp60mAgo, + timestamp: timestamp60mAgo + }, { + _type: 'TempBasal', + rate: 2, + date: timestamp60mAgo, + timestamp: timestamp60mAgo + }, { + _type: 'PumpResume', + date: timestamp45mAgo, + timestamp: timestamp45mAgo + }], + profile: { + dia: 3, + current_basal: 1, + suspend_zeros_iob: true, + max_daily_basal: 1, + //bolussnooze_dia_divisor: 2, + 'basalprofile': basalprofile + } + }; + + iobInputs = inputs; + + var iobNowWithSuspend = require('../lib/iob')(iobInputs)[0]; + + iobNowWithSuspend.iob.should.equal(iobNowWithoutSuspend.iob); + }); + + it('should calculate IOB without counting time pump suspended when pump is currently suspended', function() { + + var basalprofile = [{ + 'i': 0, + 'start': '00:00:00', + 'rate': 1, + 'minutes': 0 + }]; + var now = Date.now(), + timestamp = new Date(now).toISOString(), + timestamp15mAgo = new Date(now - (15 * 60 * 1000)).toISOString(), + timestamp30mAgo = new Date(now - (30 * 60 * 1000)).toISOString(), + timestamp45mAgo = new Date(now - (45 * 60 * 1000)).toISOString(), + timestamp60mAgo = new Date(now - (60 * 60 * 1000)).toISOString(), + timestamp75mAgo = new Date(now - (75 * 60 * 1000)).toISOString(), + + inputs = { + clock: timestamp, + history: [{ + _type: 'TempBasalDuration', + 'duration (min)': 15, + date: timestamp45mAgo, + timestamp: timestamp45mAgo + }, { + _type: 'TempBasal', + rate: 2, + date: timestamp45mAgo, + timestamp: timestamp45mAgo + }, { + _type: 'TempBasalDuration', + 'duration (min)': 30, + date: timestamp30mAgo, + timestamp: timestamp30mAgo + }, { + _type: 'TempBasal', + rate: 2, + date: timestamp30mAgo, + timestamp: timestamp30mAgo + }], + profile: { + dia: 3, + current_basal: 1, + suspend_zeros_iob: true, + max_daily_basal: 1, + //bolussnooze_dia_divisor: 2, + 'basalprofile': basalprofile + } + }; + + var iobInputs = inputs; + + var iobNowWithoutSuspend = require('../lib/iob')(iobInputs)[0]; + + inputs = { + clock: timestamp, + history: [{ + _type: 'TempBasalDuration', + 'duration (min)': 30, + date: timestamp45mAgo, + timestamp: timestamp45mAgo + }, { + _type: 'TempBasal', + rate: 2, + date: timestamp45mAgo, + timestamp: timestamp45mAgo + }, { + _type: 'PumpSuspend', + date: timestamp30mAgo, + timestamp: timestamp30mAgo + }], + profile: { + dia: 3, + current_basal: 1, + suspend_zeros_iob: true, + max_daily_basal: 1, + //bolussnooze_dia_divisor: 2, + 'basalprofile': basalprofile + } + }; + + var iobNowWithSuspend = require('../lib/iob')(iobInputs)[0]; + + iobNowWithSuspend.iob.should.equal(iobNowWithoutSuspend.iob); + }); + + it('should not report negative IOB with Temp Basals and a basal profile with drastic changes', function() { + + var basalprofile = [{ + 'i': 0, + 'start': '00:00:00', + 'rate': 0.1, + 'minutes': 0 + }, + { + 'i': 1, + 'start': '00:30:00', + 'rate': 2, + 'minutes': 30 + } + ]; + + var startingPoint = new Date('2016-06-13 00:00:00.000'); + var startingPoint2 = new Date('2016-06-13 00:30:00.000'); + var endPoint = new Date('2016-06-13 01:00:00.000'); + + var inputs = { + clock: endPoint, + history: [{ + _type: 'TempBasalDuration', + 'duration (min)': 30, + date: startingPoint + }, { + _type: 'TempBasal', + rate: 0.1, + date: startingPoint, + timestamp: startingPoint + }, { + _type: 'TempBasal', + rate: 2, + date: startingPoint2, + timestamp: startingPoint2 + }, { + _type: 'TempBasalDuration', + 'duration (min)': 30, + date: startingPoint2 + }], + profile: { + dia: 3, + current_basal: 2, + max_daily_basal: 2, + //bolussnooze_dia_divisor: 2, + 'basalprofile': basalprofile + } + }; + + var hourLaterInputs = inputs; + var hourLater = require('../lib/iob')(hourLaterInputs)[0]; + hourLater.iob.should.equal(0); + }); + + it('should calculate IOB with Temp Basal events that overlap', function() { + + var basalprofile = [{ + 'i': 0, + 'start': '00:00:00', + 'rate': 1, + 'minutes': 0 + }]; + + var now = Date.now(), + timestamp30mAgo = new Date(now - (30 * 60 * 1000)).toISOString(), + timestamp31mAgo = new Date(now - (31 * 60 * 1000)).toISOString(), + inputs = { + clock: timestamp30mAgo, + history: [{ + _type: 'TempBasalDuration', + 'duration (min)': 30, + date: timestamp31mAgo, + timestamp: timestamp31mAgo + }, { + _type: 'TempBasal', + rate: 2, + date: timestamp31mAgo, + timestamp: timestamp31mAgo + }, { + _type: 'TempBasal', + rate: 2, + date: timestamp30mAgo, + timestamp: timestamp30mAgo + }, { + _type: 'TempBasalDuration', + 'duration (min)': 30, + date: timestamp30mAgo, + timestamp: timestamp30mAgo + }], + profile: { + dia: 3, + current_basal: 1, + max_daily_basal: 1, + 'basalprofile': basalprofile + } + }; + + var hourLaterInputs = inputs; + hourLaterInputs.clock = new Date(now + (60 * 60 * 1000)).toISOString(); + var hourLater = require('../lib/iob')(hourLaterInputs)[0]; + + hourLater.iob.should.be.lessThan(1); + hourLater.iob.should.be.greaterThan(0); + }); + + it('should calculate IOB with Temp Basals that are lower than base rate', function() { + + var basalprofile = [{ + 'i': 0, + 'start': '00:00:00', + 'rate': 2, + 'minutes': 0 + }]; + + var now = Date.now(), + timestamp = new Date(now).toISOString(), + timestampEarly = new Date(now - (30 * 60 * 1000)).toISOString(), + inputs = { + clock: timestamp, + history: [{ + _type: 'TempBasalDuration', + 'duration (min)': 30, + date: timestampEarly, + timestamp: timestampEarly + }, { + _type: 'TempBasal', + rate: 1, + date: timestampEarly, + timestamp: timestampEarly + }, { + _type: 'TempBasal', + rate: 1, + date: timestamp, + timestamp: timestamp + }, { + _type: 'TempBasalDuration', + 'duration (min)': 30, + date: timestamp, + timestamp: timestamp + }], + profile: { + dia: 3, + current_basal: 2, + max_daily_basal: 2, + //bolussnooze_dia_divisor: 2, + 'basalprofile': basalprofile + } + }; + + var hourLaterInputs = inputs; + hourLaterInputs.clock = new Date(now + (60 * 60 * 1000)).toISOString(); + var hourLater = require('../lib/iob')(hourLaterInputs)[0]; + + hourLater.iob.should.be.lessThan(0); + hourLater.iob.should.be.greaterThan(-1); + }); + + it('should show 0 IOB with Temp Basals if duration is not found', function() { + + var now = Date.now(), + timestamp = new Date(now).toISOString(), + timestampEarly = new Date(now - (60 * 60 * 1000)).toISOString(), + inputs = { + clock: timestamp, + history: [{ + _type: 'TempBasal', + rate: 2, + date: timestamp, + timestamp: timestamp + }], + profile: { + dia: 3, + current_basal: 1, + max_daily_basal: 1, + //bolussnooze_dia_divisor: 2 + } + }; + + var hourLaterInputs = inputs; + hourLaterInputs.clock = new Date(now + (60 * 60 * 1000)).toISOString(); + var hourLater = require('../lib/iob')(hourLaterInputs)[0]; + + hourLater.iob.should.equal(0); + }); + + it('should show 0 IOB with Temp Basals if basal is percentage based', function() { + + var now = Date.now(), + timestamp = new Date(now).toISOString(), + timestampEarly = new Date(now - (60 * 60 * 1000)).toISOString(), + inputs = { + clock: timestamp, + history: [{ + _type: 'TempBasal', + temp: 'percent', + rate: 2, + date: timestamp, + timestamp: timestamp + }, + { + _type: 'TempBasalDuration', + 'duration (min)': 30, + date: timestamp + } + ], + profile: { + dia: 3, + current_basal: 1, + max_daily_basal: 1, + //bolussnooze_dia_divisor: 2 + } + }; + + + var hourLaterInputs = inputs; + hourLaterInputs.clock = new Date(now + (60 * 60 * 1000)).toISOString(); + var hourLater = require('../lib/iob')(hourLaterInputs)[0]; + + hourLater.iob.should.equal(0); + }); + + it('should calculate IOB using a 4 hour duration', function() { + + var basalprofile = [{ + 'i': 0, + 'start': '00:00:00', + 'rate': 1, + 'minutes': 0 + }]; + + var now = Date.now(), + timestamp = new Date(now).toISOString(), + inputs = { + clock: timestamp, + history: [{ + _type: 'Bolus', + amount: 1, + timestamp: timestamp + }], + profile: { + dia: 4, + //bolussnooze_dia_divisor: 2, + basalprofile: basalprofile, + current_basal: 1, + max_daily_basal: 1 + } + + }; + + var rightAfterBolus = require('../lib/iob')(inputs)[0]; + rightAfterBolus.iob.should.equal(1); + //rightAfterBolus.bolussnooze.should.equal(1); + + var hourLaterInputs = inputs; + hourLaterInputs.clock = new Date(now + (60 * 60 * 1000)).toISOString(); + var hourLater = require('../lib/iob')(hourLaterInputs)[0]; + hourLater.iob.should.be.lessThan(1); + //hourLater.bolussnooze.should.be.lessThan(.5); + hourLater.iob.should.be.greaterThan(0); + + var after3hInputs = inputs; + after3hInputs.clock = new Date(now + (3 * 60 * 60 * 1000)).toISOString(); + var after3h = require('../lib/iob')(after3hInputs)[0]; + after3h.iob.should.be.greaterThan(0); + + var after4hInputs = inputs; + after4hInputs.clock = new Date(now + (4 * 60 * 60 * 1000)).toISOString(); + var after4h = require('../lib/iob')(after4hInputs)[0]; + after4h.iob.should.equal(0); + }); + + +}); diff --git a/tests/profile.test.js b/tests/profile.test.js new file mode 100644 index 000000000..d608388c8 --- /dev/null +++ b/tests/profile.test.js @@ -0,0 +1,115 @@ +'use strict'; + +require('should'); +var _ = require('lodash'); + +describe('Profile', function ( ) { + + var baseInputs = { + settings: { + insulin_action_curve: 3 + } + , basals: [ + {minutes: 0, rate: 1} + ] + , targets: { + targets: [ + { offset: 0, high: 120, low: 100 } + ] + } + , temptargets: [ + ] + , isf: { + sensitivities: [ + { offset: 0, i: 0, x: 0, start: '00:00:00', sensitivity: 100 } + ] + } + , carbratio: { + units: 'grams' + , schedule: [ + { offset: 0, ratio: 20 } + ] + } + }; + + it('should should create a profile from inputs', function () { + var profile = require('../lib/profile')(baseInputs); + profile.max_iob.should.equal(0); + profile.dia.should.equal(3); + profile.sens.should.equal(100); + profile.current_basal.should.equal(1); + profile.max_bg.should.equal(100); + profile.min_bg.should.equal(100); + profile.carb_ratio.should.equal(20); + }); + + it('should should honour wide_bg_target_range', function () { + var profile = require('../lib/profile')(_.merge({}, baseInputs, {wide_bg_target_range: true})); + profile.max_iob.should.equal(0); + profile.dia.should.equal(3); + profile.sens.should.equal(100); + profile.current_basal.should.equal(1); + profile.max_bg.should.equal(100); + profile.min_bg.should.equal(100); + profile.carb_ratio.should.equal(20); + }); + + + var currentTime = new Date(); + var creationDate = new Date(currentTime.getTime() - (5 * 60 * 1000)); + + it('should create a profile with temptarget set', function() { + var profile = require('../lib/profile')(_.merge({}, baseInputs, { temptargets: [{'eventType':'Temporary Target', 'reason':'Eating Soon', 'targetTop':80, 'targetBottom':80, 'duration':20, 'created_at': creationDate}]})); + profile.max_iob.should.equal(0); + profile.dia.should.equal(3); + profile.sens.should.equal(100); + profile.current_basal.should.equal(1); + profile.max_bg.should.equal(80); + profile.min_bg.should.equal(80); + profile.carb_ratio.should.equal(20); + profile.temptargetSet.should.equal(true); + }); + + + var pastDate = new Date(currentTime.getTime() - 90*60*1000); + it('should create a profile ignoring an out of date temptarget', function() { + var profile = require('../lib/profile')(_.merge({}, baseInputs, { temptargets: [{'eventType':'Temporary Target', 'reason':'Eating Soon', 'targetTop':80, 'targetBottom':80, 'duration':20, 'created_at': pastDate}]})); + profile.max_iob.should.equal(0); + profile.dia.should.equal(3); + profile.sens.should.equal(100); + profile.current_basal.should.equal(1); + profile.max_bg.should.equal(100); + profile.min_bg.should.equal(100); + profile.carb_ratio.should.equal(20); + }); + + it('should create a profile ignoring a temptarget with 0 duration', function() { + var profile = require('../lib/profile')(_.merge({}, baseInputs, { temptargets: [{'eventType':'Temporary Target', 'reason':'Eating Soon', 'targetTop':80, 'targetBottom':80, 'duration':0, 'created_at': creationDate}]})); + profile.max_iob.should.equal(0); + profile.dia.should.equal(3); + profile.sens.should.equal(100); + profile.current_basal.should.equal(1); + profile.max_bg.should.equal(100); + profile.min_bg.should.equal(100); + profile.carb_ratio.should.equal(20); + }); + + + it('should error with invalid DIA', function () { + var profile = require('../lib/profile')(_.merge({}, baseInputs, {settings: {insulin_action_curve: 1}})); + profile.should.equal(-1); + }); + + it('should error with a current basal of 0', function () { + var profile = require('../lib/profile')(_.merge({}, baseInputs, {basals: [{minutes: 0, rate: 0}]})); + profile.should.equal(-1); + }); + + + it('should set the profile model from input', function () { + var profile = require('../lib/profile')(_.merge({}, baseInputs, {model: 554})); + profile.model.should.equal(554); + }); + + +}); diff --git a/tests/set-temp-basal.test.js b/tests/set-temp-basal.test.js index 3f8cd7413..171d7337b 100644 --- a/tests/set-temp-basal.test.js +++ b/tests/set-temp-basal.test.js @@ -3,61 +3,96 @@ require('should'); -describe('setTempBasal', function ( ) { - var setTempBasal = require('../lib/basal-set-temp'); +describe('tempBasalFunctions.setTempBasal', function ( ) { + var tempBasalFunctions = require('../lib/basal-set-temp'); - //function setTempBasal(rate, duration, profile, requestedTemp) + //function tempBasalFunctions.setTempBasal(rate, duration, profile, requestedTemp) var profile = { "current_basal":0.8,"max_daily_basal":1.3,"max_basal":3.0 }; var rt = {}; it('should cancel temp', function () { - var requestedTemp = setTempBasal(0, 0, profile, rt); + var requestedTemp = tempBasalFunctions.setTempBasal(0, 0, profile, rt); requestedTemp.rate.should.equal(0); requestedTemp.duration.should.equal(0); }); it('should set zero temp', function () { - var requestedTemp = setTempBasal(0, 30, profile, rt); + var requestedTemp = tempBasalFunctions.setTempBasal(0, 30, profile, rt); requestedTemp.rate.should.equal(0); requestedTemp.duration.should.equal(30); }); it('should set high temp', function () { - var requestedTemp = setTempBasal(2, 30, profile, rt); + var requestedTemp = tempBasalFunctions.setTempBasal(2, 30, profile, rt); requestedTemp.rate.should.equal(2); requestedTemp.duration.should.equal(30); }); - it('should limit high temp to max_basal', function () { - var requestedTemp = setTempBasal(4, 30, profile, rt); - requestedTemp.rate.should.equal(3); - requestedTemp.duration.should.equal(30); + it('should not set basal on skip neutral mode', function () { + profile.skip_neutral_temps = true; + var rt2 = {}; + var current = {duration: 10}; + var requestedTemp = tempBasalFunctions.setTempBasal(0.8, 30, profile, rt2, current); + requestedTemp.duration.should.equal(0); + var requestedTemp = tempBasalFunctions.setTempBasal(0.8, 30, profile, {}); + requestedTemp.reason.should.equal('Suggested rate is same as profile rate, no temp basal is active, doing nothing'); }); - it('should set current_basal as temp on requestedTemp if offline', function () { - var requestedTemp = setTempBasal(0, 0, profile, rt, "Offline"); - requestedTemp.rate.should.equal(0.8); + it('should limit high temp to max_basal', function () { + var requestedTemp = tempBasalFunctions.setTempBasal(4, 30, profile, rt); + requestedTemp.rate.should.equal(3); requestedTemp.duration.should.equal(30); }); it('should limit high temp to 3 * max_daily_basal', function () { var profile = { "current_basal":1.0,"max_daily_basal":1.3,"max_basal":10.0 }; - var requestedTemp = setTempBasal(6, 30, profile, rt); + var requestedTemp = tempBasalFunctions.setTempBasal(6, 30, profile, rt); requestedTemp.rate.should.equal(3.9); requestedTemp.duration.should.equal(30); }); it('should limit high temp to 4 * current_basal', function () { var profile = { "current_basal":0.7,"max_daily_basal":1.3,"max_basal":10.0 }; - var requestedTemp = setTempBasal(6, 30, profile, rt); + var requestedTemp = tempBasalFunctions.setTempBasal(6, 30, profile, rt); requestedTemp.rate.should.equal(2.8); requestedTemp.duration.should.equal(30); }); + it('should temp to 0 when requested rate is less then 0 * current_basal', function () { var profile = { "current_basal":0.7,"max_daily_basal":1.3,"max_basal":10.0 }; - var requestedTemp = setTempBasal(-1, 30, profile, rt); + var requestedTemp = tempBasalFunctions.setTempBasal(-1, 30, profile, rt); requestedTemp.rate.should.equal(0); requestedTemp.duration.should.equal(30); }); -}); \ No newline at end of file + it('should limit high temp to 4 * max_daily_basal when overridden', function () { + var profile = { "current_basal":2.0,"max_daily_basal":1.3,"max_basal":10.0, "max_daily_safety_multiplier": 4}; + var requestedTemp = tempBasalFunctions.setTempBasal(6, 30, profile, rt); + requestedTemp.rate.should.equal(5.2); + requestedTemp.duration.should.equal(30); + }); + + it('should limit high temp to 5 * current_basal when overridden', function () { + var profile = { "current_basal":0.7,"max_daily_basal":1.3,"max_basal":10.0, "current_basal_safety_multiplier": 5}; + var requestedTemp = tempBasalFunctions.setTempBasal(6, 30, profile, rt); + requestedTemp.rate.should.equal(3.5); + requestedTemp.duration.should.equal(30); + }); + + it('should allow small basal change when current temp is also small', function () { + var rt = {} + var profile = { "current_basal":0.075,"max_daily_basal":1.3,"max_basal":10.0, "current_basal_safety_multiplier": 5, "model": "523"}; + var currentTemp = { "rate": 0.025, "duration": 24}; + var requestedTemp = tempBasalFunctions.setTempBasal(0, 30, profile, rt, currentTemp); + requestedTemp.rate.should.equal(0); + requestedTemp.duration.should.equal(30); + }); + + it('should not allow small basal change when current temp is large', function () { + var rt = {} + var profile = { "current_basal":10.075,"max_daily_basal":11.3,"max_basal":50.0, "current_basal_safety_multiplier": 5, "model": "523"}; + var currentTemp = { "rate": 10.1, "duration": 24}; + var requestedTemp = tempBasalFunctions.setTempBasal(10.125, 30, profile, rt, currentTemp); + //requestedTemp.reason.should.equal("undefined, but 24m left and 10.1 ~ req 10.1U/hr: no action required"); + }); +}); diff --git a/tests/with-raw-glucose.test.js b/tests/with-raw-glucose.test.js new file mode 100644 index 000000000..98b95d213 --- /dev/null +++ b/tests/with-raw-glucose.test.js @@ -0,0 +1,59 @@ +'use strict'; + +var should = require('should'); +var withRawGlucose = require('../lib/with-raw-glucose'); + +var cals = [{ + scale: 1 + , intercept: 25717.82377004309 + , slope: 766.895601715918 +}]; + +describe('IOB', function ( ) { + it('should add raw glucose and not mess with real glucose', function ( ) { + var entry = {unfiltered: 113680, filtered: 111232, glucose: 110, noise: 1}; + withRawGlucose(entry, cals); + + entry.glucose.should.equal(110); + entry.raw.should.equal(113); + entry.noise.should.equal(1); + }); + + it('should add raw glucose and not mess with sgv from NS', function ( ) { + var entry = {unfiltered: 113680, filtered: 111232, sgv: 110, noise: 1}; + withRawGlucose(entry, cals); + + should.not.exist(entry.glucose); + entry.sgv.should.equal(110); + entry.raw.should.equal(113); + entry.noise.should.equal(1); + }); + + it('should add raw glucose and set missing glucose', function ( ) { + var entry = {unfiltered: 113680, filtered: 111232, noise: 1}; + withRawGlucose(entry, cals); + + entry.glucose.should.equal(115); + entry.raw.should.equal(115); + entry.noise.should.equal(2); + }); + + it('should add raw glucose, but set set noise to 3 when glucose above maxRaw', function ( ) { + var entry = {unfiltered: 143680, filtered: 141232, noise: 1}; + withRawGlucose(entry, cals, 150); + + //should.not.exist(entry.glucose); + entry.raw.should.equal(154); + entry.noise.should.equal(3); + }); + + it('should add raw glucose, and set missing glucose when maxRaw is higher', function ( ) { + var entry = {unfiltered: 143680, filtered: 141232, noise: 1}; + withRawGlucose(entry, cals, 250); + + entry.glucose.should.equal(154); + entry.raw.should.equal(154); + entry.noise.should.equal(2); + }); + +}); diff --git a/www/app.py b/www/app.py new file mode 100644 index 000000000..add4199f7 --- /dev/null +++ b/www/app.py @@ -0,0 +1,120 @@ +import os +import socket + +from flask import Flask, render_template, url_for, json, jsonify, request +from datetime import datetime +import pytz + +app = Flask(__name__) + +@app.route("/") +def index(): + try: + myopenaps_dir = os.environ['OPENAPS_DIR'] + except KeyError: + myopenaps_dir = "/root/myopenaps/" + data=dict() + try: + error_text = "getHost" + data['hostname']=socket.gethostname() + error_text = "pump_loop_success" + if os.path.isfile("/tmp/pump_loop_success"): + data['loop_completed']=datetime.fromtimestamp(os.path.getmtime("/tmp/pump_loop_success"), pytz.utc) + else: + data['loop_completed']="" + + except ValueError: + return render_template('indexError.html', data=data, error_text=error_text ) + except IOError: + return render_template('indexError.html', data=data, error_text=error_text ) + else: + return render_template('index.html', data=data ) + +@app.route("/suggested") +def suggested(): + json_url = os.path.join("/root/myopenaps/enact/suggested.json") + data = json.load(open(json_url)) + return jsonify(data) + +@app.route("/enacted") +def enacted(): + json_url = os.path.join("/root/myopenaps/enact/enacted.json") + data = json.load(open(json_url)) + return jsonify(data) + +@app.route("/glucose") +def glucose(): + if os.path.getmtime("/root/myopenaps/xdrip/glucose.json") > os.path.getmtime("/root/myopenaps/monitor/glucose.json"): + json_url = os.path.join("/root/myopenaps/xdrip/glucose.json") + else: + json_url = os.path.join("/root/myopenaps/monitor/glucose.json") + data = json.load(open(json_url)) + return jsonify(data) + +@app.route("/sgv.json") +def sgvjson(): + json_url = os.path.join("/root/myopenaps/settings/profile.json") + data = json.load(open(json_url)) + units = data['out_units'] + count = request.args.get('count', default = 10, type = int) + if os.path.getmtime("/root/myopenaps/xdrip/glucose.json") > os.path.getmtime("/root/myopenaps/monitor/glucose.json"): + json_url = os.path.join("/root/myopenaps/xdrip/glucose.json") + else: + json_url = os.path.join("/root/myopenaps/monitor/glucose.json") + data = json.load(open(json_url)) + if units == "mg/dL": + data[0]['units_hint'] = "mgdl" + else: + data[0]['units_hint'] = "mmol" + return jsonify(data[0:count]) + +@app.route("/temptargets") +def temptargets(): + json_url = os.path.join("/root/myopenaps/settings/temptargets.json") + data = json.load(open(json_url)) + return jsonify(data) + +@app.route("/profile") +def profile(): + json_url = os.path.join("/root/myopenaps/settings/profile.json") + data = json.load(open(json_url)) + return jsonify(data) + +@app.route("/pumphistory") +def pumphistory(): + json_url = os.path.join("/root/myopenaps/monitor/pumphistory-merged.json") + data = json.load(open(json_url)) + return jsonify(data) + +@app.route("/iob") +def iob(): + json_url = os.path.join("/root/myopenaps/monitor/iob.json") + data = json.load(open(json_url)) + return jsonify(data) + +@app.route("/pump_battery") +def pump_battery(): + json_url = os.path.join("/root/myopenaps/monitor/battery.json") + data = json.load(open(json_url)) + return jsonify(data) + +@app.route("/edison_battery") +def edison_battery(): + json_url = os.path.join("/root/myopenaps/monitor/edison-battery.json") + data = json.load(open(json_url)) + return jsonify(data) + +@app.route("/meal") +def meal(): + json_url = os.path.join("/root/myopenaps/monitor/meal.json") + data = json.load(open(json_url)) + return jsonify(data) + +@app.route("/temp_basal") +def temp_basal(): + json_url = os.path.join("/root/myopenaps/monitor/temp_basal.json") + data = json.load(open(json_url)) + return jsonify(data) + +if __name__ == '__main__': + app.run(debug=True, host='0.0.0.0') diff --git a/www/regenerate-index.sh b/www/regenerate-index.sh new file mode 100644 index 000000000..4d47cc804 --- /dev/null +++ b/www/regenerate-index.sh @@ -0,0 +1,23 @@ +rm ~/myopenaps/enact/index.html +(echo '') > ~/myopenaps/enact/index.html +(echo '') >> ~/myopenaps/enact/index.html +(echo '') >> ~/myopenaps/enact/index.html +(echo '') >> ~/myopenaps/enact/index.html +(echo '') >> ~/myopenaps/enact/index.html +(echo '') >> ~/myopenaps/enact/index.html +(echo '') >> ~/myopenaps/enact/index.html +(echo '') >> ~/myopenaps/enact/index.html + +(echo '') >> ~/myopenaps/enact/index.html +(echo -n '') >> ~/myopenaps/enact/index.html + +(echo '') >> ~/myopenaps/enact/index.html +(echo -n '') >> ~/myopenaps/enact/index.html + +(echo '
ParameterValue
Page updated') >> ~/myopenaps/enact/index.html +date >> ~/myopenaps/enact/index.html +(echo '
Edison Battery' +cat ~/myopenaps/monitor/edison-battery.json | jq -r .battery | tr '\n' ' ' && echo '%') >> ~/myopenaps/enact/index.html +(echo '
') >> ~/myopenaps/enact/index.html +(echo '') >> ~/myopenaps/enact/index.html +(echo '') >> ~/myopenaps/enact/index.html diff --git a/www/setup-http.sh b/www/setup-http.sh new file mode 100644 index 000000000..f24876c39 --- /dev/null +++ b/www/setup-http.sh @@ -0,0 +1,2 @@ +(crontab -l; crontab -l | grep -q "SimpleHTTPServer" || echo '@reboot cd /root/myopenaps/enact && python -m SimpleHTTPServer 1337 > /dev/null 2>&1') | crontab - +(crontab -l; crontab -l | grep -q "regenerate-index" || echo '*/1 * * * * (bash /root/myopenaps/enact/regenerate-index.sh) 2>&1 | tee -a /var/log/openaps/http.log') | crontab - diff --git a/www/static/css/bootstrap.min.css b/www/static/css/bootstrap.min.css new file mode 100644 index 000000000..ad65b4ed3 --- /dev/null +++ b/www/static/css/bootstrap.min.css @@ -0,0 +1,7 @@ +/*! + * Bootstrap v4.0.0-beta.2 (https://getbootstrap.com) + * Copyright 2011-2017 The Bootstrap Authors + * Copyright 2011-2017 Twitter, Inc. + * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) + */:root{--blue:#007bff;--indigo:#6610f2;--purple:#6f42c1;--pink:#e83e8c;--red:#dc3545;--orange:#fd7e14;--yellow:#ffc107;--green:#28a745;--teal:#20c997;--cyan:#17a2b8;--white:#fff;--gray:#868e96;--gray-dark:#343a40;--primary:#007bff;--secondary:#868e96;--success:#28a745;--info:#17a2b8;--warning:#ffc107;--danger:#dc3545;--light:#f8f9fa;--dark:#343a40;--breakpoint-xs:0;--breakpoint-sm:576px;--breakpoint-md:768px;--breakpoint-lg:992px;--breakpoint-xl:1200px;--font-family-sans-serif:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol";--font-family-monospace:"SFMono-Regular",Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace}@media print{*,::after,::before{text-shadow:none!important;box-shadow:none!important}a,a:visited{text-decoration:underline}abbr[title]::after{content:" (" attr(title) ")"}pre{white-space:pre-wrap!important}blockquote,pre{border:1px solid #999;page-break-inside:avoid}thead{display:table-header-group}img,tr{page-break-inside:avoid}h2,h3,p{orphans:3;widows:3}h2,h3{page-break-after:avoid}.navbar{display:none}.badge{border:1px solid #000}.table{border-collapse:collapse!important}.table td,.table th{background-color:#fff!important}.table-bordered td,.table-bordered th{border:1px solid #ddd!important}}*,::after,::before{box-sizing:border-box}html{font-family:sans-serif;line-height:1.15;-webkit-text-size-adjust:100%;-ms-text-size-adjust:100%;-ms-overflow-style:scrollbar;-webkit-tap-highlight-color:transparent}@-ms-viewport{width:device-width}article,aside,dialog,figcaption,figure,footer,header,hgroup,main,nav,section{display:block}body{margin:0;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol";font-size:1rem;font-weight:400;line-height:1.5;color:#212529;text-align:left;background-color:#fff}[tabindex="-1"]:focus{outline:0!important}hr{box-sizing:content-box;height:0;overflow:visible}h1,h2,h3,h4,h5,h6{margin-top:0;margin-bottom:.5rem}p{margin-top:0;margin-bottom:1rem}abbr[data-original-title],abbr[title]{text-decoration:underline;-webkit-text-decoration:underline dotted;text-decoration:underline dotted;cursor:help;border-bottom:0}address{margin-bottom:1rem;font-style:normal;line-height:inherit}dl,ol,ul{margin-top:0;margin-bottom:1rem}ol ol,ol ul,ul ol,ul ul{margin-bottom:0}dt{font-weight:700}dd{margin-bottom:.5rem;margin-left:0}blockquote{margin:0 0 1rem}dfn{font-style:italic}b,strong{font-weight:bolder}small{font-size:80%}sub,sup{position:relative;font-size:75%;line-height:0;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}a{color:#007bff;text-decoration:none;background-color:transparent;-webkit-text-decoration-skip:objects}a:hover{color:#0056b3;text-decoration:underline}a:not([href]):not([tabindex]){color:inherit;text-decoration:none}a:not([href]):not([tabindex]):focus,a:not([href]):not([tabindex]):hover{color:inherit;text-decoration:none}a:not([href]):not([tabindex]):focus{outline:0}code,kbd,pre,samp{font-family:monospace,monospace;font-size:1em}pre{margin-top:0;margin-bottom:1rem;overflow:auto;-ms-overflow-style:scrollbar}figure{margin:0 0 1rem}img{vertical-align:middle;border-style:none}svg:not(:root){overflow:hidden}[role=button],a,area,button,input:not([type=range]),label,select,summary,textarea{-ms-touch-action:manipulation;touch-action:manipulation}table{border-collapse:collapse}caption{padding-top:.75rem;padding-bottom:.75rem;color:#868e96;text-align:left;caption-side:bottom}th{text-align:inherit}label{display:inline-block;margin-bottom:.5rem}button{border-radius:0}button:focus{outline:1px dotted;outline:5px auto -webkit-focus-ring-color}button,input,optgroup,select,textarea{margin:0;font-family:inherit;font-size:inherit;line-height:inherit}button,input{overflow:visible}button,select{text-transform:none}[type=reset],[type=submit],button,html [type=button]{-webkit-appearance:button}[type=button]::-moz-focus-inner,[type=reset]::-moz-focus-inner,[type=submit]::-moz-focus-inner,button::-moz-focus-inner{padding:0;border-style:none}input[type=checkbox],input[type=radio]{box-sizing:border-box;padding:0}input[type=date],input[type=datetime-local],input[type=month],input[type=time]{-webkit-appearance:listbox}textarea{overflow:auto;resize:vertical}fieldset{min-width:0;padding:0;margin:0;border:0}legend{display:block;width:100%;max-width:100%;padding:0;margin-bottom:.5rem;font-size:1.5rem;line-height:inherit;color:inherit;white-space:normal}progress{vertical-align:baseline}[type=number]::-webkit-inner-spin-button,[type=number]::-webkit-outer-spin-button{height:auto}[type=search]{outline-offset:-2px;-webkit-appearance:none}[type=search]::-webkit-search-cancel-button,[type=search]::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{font:inherit;-webkit-appearance:button}output{display:inline-block}summary{display:list-item}template{display:none}[hidden]{display:none!important}.h1,.h2,.h3,.h4,.h5,.h6,h1,h2,h3,h4,h5,h6{margin-bottom:.5rem;font-family:inherit;font-weight:500;line-height:1.2;color:inherit}.h1,h1{font-size:2.5rem}.h2,h2{font-size:2rem}.h3,h3{font-size:1.75rem}.h4,h4{font-size:1.5rem}.h5,h5{font-size:1.25rem}.h6,h6{font-size:1rem}.lead{font-size:1.25rem;font-weight:300}.display-1{font-size:6rem;font-weight:300;line-height:1.2}.display-2{font-size:5.5rem;font-weight:300;line-height:1.2}.display-3{font-size:4.5rem;font-weight:300;line-height:1.2}.display-4{font-size:3.5rem;font-weight:300;line-height:1.2}hr{margin-top:1rem;margin-bottom:1rem;border:0;border-top:1px solid rgba(0,0,0,.1)}.small,small{font-size:80%;font-weight:400}.mark,mark{padding:.2em;background-color:#fcf8e3}.list-unstyled{padding-left:0;list-style:none}.list-inline{padding-left:0;list-style:none}.list-inline-item{display:inline-block}.list-inline-item:not(:last-child){margin-right:5px}.initialism{font-size:90%;text-transform:uppercase}.blockquote{margin-bottom:1rem;font-size:1.25rem}.blockquote-footer{display:block;font-size:80%;color:#868e96}.blockquote-footer::before{content:"\2014 \00A0"}.img-fluid{max-width:100%;height:auto}.img-thumbnail{padding:.25rem;background-color:#fff;border:1px solid #ddd;border-radius:.25rem;transition:all .2s ease-in-out;max-width:100%;height:auto}.figure{display:inline-block}.figure-img{margin-bottom:.5rem;line-height:1}.figure-caption{font-size:90%;color:#868e96}code,kbd,pre,samp{font-family:SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace}code{padding:.2rem .4rem;font-size:90%;color:#bd4147;background-color:#f8f9fa;border-radius:.25rem}a>code{padding:0;color:inherit;background-color:inherit}kbd{padding:.2rem .4rem;font-size:90%;color:#fff;background-color:#212529;border-radius:.2rem}kbd kbd{padding:0;font-size:100%;font-weight:700}pre{display:block;margin-top:0;margin-bottom:1rem;font-size:90%;color:#212529}pre code{padding:0;font-size:inherit;color:inherit;background-color:transparent;border-radius:0}.pre-scrollable{max-height:340px;overflow-y:scroll}.container{width:100%;padding-right:15px;padding-left:15px;margin-right:auto;margin-left:auto}@media (min-width:576px){.container{max-width:540px}}@media (min-width:768px){.container{max-width:720px}}@media (min-width:992px){.container{max-width:960px}}@media (min-width:1200px){.container{max-width:1140px}}.container-fluid{width:100%;padding-right:15px;padding-left:15px;margin-right:auto;margin-left:auto}.row{display:-ms-flexbox;display:flex;-ms-flex-wrap:wrap;flex-wrap:wrap;margin-right:-15px;margin-left:-15px}.no-gutters{margin-right:0;margin-left:0}.no-gutters>.col,.no-gutters>[class*=col-]{padding-right:0;padding-left:0}.col,.col-1,.col-10,.col-11,.col-12,.col-2,.col-3,.col-4,.col-5,.col-6,.col-7,.col-8,.col-9,.col-auto,.col-lg,.col-lg-1,.col-lg-10,.col-lg-11,.col-lg-12,.col-lg-2,.col-lg-3,.col-lg-4,.col-lg-5,.col-lg-6,.col-lg-7,.col-lg-8,.col-lg-9,.col-lg-auto,.col-md,.col-md-1,.col-md-10,.col-md-11,.col-md-12,.col-md-2,.col-md-3,.col-md-4,.col-md-5,.col-md-6,.col-md-7,.col-md-8,.col-md-9,.col-md-auto,.col-sm,.col-sm-1,.col-sm-10,.col-sm-11,.col-sm-12,.col-sm-2,.col-sm-3,.col-sm-4,.col-sm-5,.col-sm-6,.col-sm-7,.col-sm-8,.col-sm-9,.col-sm-auto,.col-xl,.col-xl-1,.col-xl-10,.col-xl-11,.col-xl-12,.col-xl-2,.col-xl-3,.col-xl-4,.col-xl-5,.col-xl-6,.col-xl-7,.col-xl-8,.col-xl-9,.col-xl-auto{position:relative;width:100%;min-height:1px;padding-right:15px;padding-left:15px}.col{-ms-flex-preferred-size:0;flex-basis:0;-ms-flex-positive:1;flex-grow:1;max-width:100%}.col-auto{-ms-flex:0 0 auto;flex:0 0 auto;width:auto;max-width:none}.col-1{-ms-flex:0 0 8.333333%;flex:0 0 8.333333%;max-width:8.333333%}.col-2{-ms-flex:0 0 16.666667%;flex:0 0 16.666667%;max-width:16.666667%}.col-3{-ms-flex:0 0 25%;flex:0 0 25%;max-width:25%}.col-4{-ms-flex:0 0 33.333333%;flex:0 0 33.333333%;max-width:33.333333%}.col-5{-ms-flex:0 0 41.666667%;flex:0 0 41.666667%;max-width:41.666667%}.col-6{-ms-flex:0 0 50%;flex:0 0 50%;max-width:50%}.col-7{-ms-flex:0 0 58.333333%;flex:0 0 58.333333%;max-width:58.333333%}.col-8{-ms-flex:0 0 66.666667%;flex:0 0 66.666667%;max-width:66.666667%}.col-9{-ms-flex:0 0 75%;flex:0 0 75%;max-width:75%}.col-10{-ms-flex:0 0 83.333333%;flex:0 0 83.333333%;max-width:83.333333%}.col-11{-ms-flex:0 0 91.666667%;flex:0 0 91.666667%;max-width:91.666667%}.col-12{-ms-flex:0 0 100%;flex:0 0 100%;max-width:100%}.order-first{-ms-flex-order:-1;order:-1}.order-1{-ms-flex-order:1;order:1}.order-2{-ms-flex-order:2;order:2}.order-3{-ms-flex-order:3;order:3}.order-4{-ms-flex-order:4;order:4}.order-5{-ms-flex-order:5;order:5}.order-6{-ms-flex-order:6;order:6}.order-7{-ms-flex-order:7;order:7}.order-8{-ms-flex-order:8;order:8}.order-9{-ms-flex-order:9;order:9}.order-10{-ms-flex-order:10;order:10}.order-11{-ms-flex-order:11;order:11}.order-12{-ms-flex-order:12;order:12}.offset-1{margin-left:8.333333%}.offset-2{margin-left:16.666667%}.offset-3{margin-left:25%}.offset-4{margin-left:33.333333%}.offset-5{margin-left:41.666667%}.offset-6{margin-left:50%}.offset-7{margin-left:58.333333%}.offset-8{margin-left:66.666667%}.offset-9{margin-left:75%}.offset-10{margin-left:83.333333%}.offset-11{margin-left:91.666667%}@media (min-width:576px){.col-sm{-ms-flex-preferred-size:0;flex-basis:0;-ms-flex-positive:1;flex-grow:1;max-width:100%}.col-sm-auto{-ms-flex:0 0 auto;flex:0 0 auto;width:auto;max-width:none}.col-sm-1{-ms-flex:0 0 8.333333%;flex:0 0 8.333333%;max-width:8.333333%}.col-sm-2{-ms-flex:0 0 16.666667%;flex:0 0 16.666667%;max-width:16.666667%}.col-sm-3{-ms-flex:0 0 25%;flex:0 0 25%;max-width:25%}.col-sm-4{-ms-flex:0 0 33.333333%;flex:0 0 33.333333%;max-width:33.333333%}.col-sm-5{-ms-flex:0 0 41.666667%;flex:0 0 41.666667%;max-width:41.666667%}.col-sm-6{-ms-flex:0 0 50%;flex:0 0 50%;max-width:50%}.col-sm-7{-ms-flex:0 0 58.333333%;flex:0 0 58.333333%;max-width:58.333333%}.col-sm-8{-ms-flex:0 0 66.666667%;flex:0 0 66.666667%;max-width:66.666667%}.col-sm-9{-ms-flex:0 0 75%;flex:0 0 75%;max-width:75%}.col-sm-10{-ms-flex:0 0 83.333333%;flex:0 0 83.333333%;max-width:83.333333%}.col-sm-11{-ms-flex:0 0 91.666667%;flex:0 0 91.666667%;max-width:91.666667%}.col-sm-12{-ms-flex:0 0 100%;flex:0 0 100%;max-width:100%}.order-sm-first{-ms-flex-order:-1;order:-1}.order-sm-1{-ms-flex-order:1;order:1}.order-sm-2{-ms-flex-order:2;order:2}.order-sm-3{-ms-flex-order:3;order:3}.order-sm-4{-ms-flex-order:4;order:4}.order-sm-5{-ms-flex-order:5;order:5}.order-sm-6{-ms-flex-order:6;order:6}.order-sm-7{-ms-flex-order:7;order:7}.order-sm-8{-ms-flex-order:8;order:8}.order-sm-9{-ms-flex-order:9;order:9}.order-sm-10{-ms-flex-order:10;order:10}.order-sm-11{-ms-flex-order:11;order:11}.order-sm-12{-ms-flex-order:12;order:12}.offset-sm-0{margin-left:0}.offset-sm-1{margin-left:8.333333%}.offset-sm-2{margin-left:16.666667%}.offset-sm-3{margin-left:25%}.offset-sm-4{margin-left:33.333333%}.offset-sm-5{margin-left:41.666667%}.offset-sm-6{margin-left:50%}.offset-sm-7{margin-left:58.333333%}.offset-sm-8{margin-left:66.666667%}.offset-sm-9{margin-left:75%}.offset-sm-10{margin-left:83.333333%}.offset-sm-11{margin-left:91.666667%}}@media (min-width:768px){.col-md{-ms-flex-preferred-size:0;flex-basis:0;-ms-flex-positive:1;flex-grow:1;max-width:100%}.col-md-auto{-ms-flex:0 0 auto;flex:0 0 auto;width:auto;max-width:none}.col-md-1{-ms-flex:0 0 8.333333%;flex:0 0 8.333333%;max-width:8.333333%}.col-md-2{-ms-flex:0 0 16.666667%;flex:0 0 16.666667%;max-width:16.666667%}.col-md-3{-ms-flex:0 0 25%;flex:0 0 25%;max-width:25%}.col-md-4{-ms-flex:0 0 33.333333%;flex:0 0 33.333333%;max-width:33.333333%}.col-md-5{-ms-flex:0 0 41.666667%;flex:0 0 41.666667%;max-width:41.666667%}.col-md-6{-ms-flex:0 0 50%;flex:0 0 50%;max-width:50%}.col-md-7{-ms-flex:0 0 58.333333%;flex:0 0 58.333333%;max-width:58.333333%}.col-md-8{-ms-flex:0 0 66.666667%;flex:0 0 66.666667%;max-width:66.666667%}.col-md-9{-ms-flex:0 0 75%;flex:0 0 75%;max-width:75%}.col-md-10{-ms-flex:0 0 83.333333%;flex:0 0 83.333333%;max-width:83.333333%}.col-md-11{-ms-flex:0 0 91.666667%;flex:0 0 91.666667%;max-width:91.666667%}.col-md-12{-ms-flex:0 0 100%;flex:0 0 100%;max-width:100%}.order-md-first{-ms-flex-order:-1;order:-1}.order-md-1{-ms-flex-order:1;order:1}.order-md-2{-ms-flex-order:2;order:2}.order-md-3{-ms-flex-order:3;order:3}.order-md-4{-ms-flex-order:4;order:4}.order-md-5{-ms-flex-order:5;order:5}.order-md-6{-ms-flex-order:6;order:6}.order-md-7{-ms-flex-order:7;order:7}.order-md-8{-ms-flex-order:8;order:8}.order-md-9{-ms-flex-order:9;order:9}.order-md-10{-ms-flex-order:10;order:10}.order-md-11{-ms-flex-order:11;order:11}.order-md-12{-ms-flex-order:12;order:12}.offset-md-0{margin-left:0}.offset-md-1{margin-left:8.333333%}.offset-md-2{margin-left:16.666667%}.offset-md-3{margin-left:25%}.offset-md-4{margin-left:33.333333%}.offset-md-5{margin-left:41.666667%}.offset-md-6{margin-left:50%}.offset-md-7{margin-left:58.333333%}.offset-md-8{margin-left:66.666667%}.offset-md-9{margin-left:75%}.offset-md-10{margin-left:83.333333%}.offset-md-11{margin-left:91.666667%}}@media (min-width:992px){.col-lg{-ms-flex-preferred-size:0;flex-basis:0;-ms-flex-positive:1;flex-grow:1;max-width:100%}.col-lg-auto{-ms-flex:0 0 auto;flex:0 0 auto;width:auto;max-width:none}.col-lg-1{-ms-flex:0 0 8.333333%;flex:0 0 8.333333%;max-width:8.333333%}.col-lg-2{-ms-flex:0 0 16.666667%;flex:0 0 16.666667%;max-width:16.666667%}.col-lg-3{-ms-flex:0 0 25%;flex:0 0 25%;max-width:25%}.col-lg-4{-ms-flex:0 0 33.333333%;flex:0 0 33.333333%;max-width:33.333333%}.col-lg-5{-ms-flex:0 0 41.666667%;flex:0 0 41.666667%;max-width:41.666667%}.col-lg-6{-ms-flex:0 0 50%;flex:0 0 50%;max-width:50%}.col-lg-7{-ms-flex:0 0 58.333333%;flex:0 0 58.333333%;max-width:58.333333%}.col-lg-8{-ms-flex:0 0 66.666667%;flex:0 0 66.666667%;max-width:66.666667%}.col-lg-9{-ms-flex:0 0 75%;flex:0 0 75%;max-width:75%}.col-lg-10{-ms-flex:0 0 83.333333%;flex:0 0 83.333333%;max-width:83.333333%}.col-lg-11{-ms-flex:0 0 91.666667%;flex:0 0 91.666667%;max-width:91.666667%}.col-lg-12{-ms-flex:0 0 100%;flex:0 0 100%;max-width:100%}.order-lg-first{-ms-flex-order:-1;order:-1}.order-lg-1{-ms-flex-order:1;order:1}.order-lg-2{-ms-flex-order:2;order:2}.order-lg-3{-ms-flex-order:3;order:3}.order-lg-4{-ms-flex-order:4;order:4}.order-lg-5{-ms-flex-order:5;order:5}.order-lg-6{-ms-flex-order:6;order:6}.order-lg-7{-ms-flex-order:7;order:7}.order-lg-8{-ms-flex-order:8;order:8}.order-lg-9{-ms-flex-order:9;order:9}.order-lg-10{-ms-flex-order:10;order:10}.order-lg-11{-ms-flex-order:11;order:11}.order-lg-12{-ms-flex-order:12;order:12}.offset-lg-0{margin-left:0}.offset-lg-1{margin-left:8.333333%}.offset-lg-2{margin-left:16.666667%}.offset-lg-3{margin-left:25%}.offset-lg-4{margin-left:33.333333%}.offset-lg-5{margin-left:41.666667%}.offset-lg-6{margin-left:50%}.offset-lg-7{margin-left:58.333333%}.offset-lg-8{margin-left:66.666667%}.offset-lg-9{margin-left:75%}.offset-lg-10{margin-left:83.333333%}.offset-lg-11{margin-left:91.666667%}}@media (min-width:1200px){.col-xl{-ms-flex-preferred-size:0;flex-basis:0;-ms-flex-positive:1;flex-grow:1;max-width:100%}.col-xl-auto{-ms-flex:0 0 auto;flex:0 0 auto;width:auto;max-width:none}.col-xl-1{-ms-flex:0 0 8.333333%;flex:0 0 8.333333%;max-width:8.333333%}.col-xl-2{-ms-flex:0 0 16.666667%;flex:0 0 16.666667%;max-width:16.666667%}.col-xl-3{-ms-flex:0 0 25%;flex:0 0 25%;max-width:25%}.col-xl-4{-ms-flex:0 0 33.333333%;flex:0 0 33.333333%;max-width:33.333333%}.col-xl-5{-ms-flex:0 0 41.666667%;flex:0 0 41.666667%;max-width:41.666667%}.col-xl-6{-ms-flex:0 0 50%;flex:0 0 50%;max-width:50%}.col-xl-7{-ms-flex:0 0 58.333333%;flex:0 0 58.333333%;max-width:58.333333%}.col-xl-8{-ms-flex:0 0 66.666667%;flex:0 0 66.666667%;max-width:66.666667%}.col-xl-9{-ms-flex:0 0 75%;flex:0 0 75%;max-width:75%}.col-xl-10{-ms-flex:0 0 83.333333%;flex:0 0 83.333333%;max-width:83.333333%}.col-xl-11{-ms-flex:0 0 91.666667%;flex:0 0 91.666667%;max-width:91.666667%}.col-xl-12{-ms-flex:0 0 100%;flex:0 0 100%;max-width:100%}.order-xl-first{-ms-flex-order:-1;order:-1}.order-xl-1{-ms-flex-order:1;order:1}.order-xl-2{-ms-flex-order:2;order:2}.order-xl-3{-ms-flex-order:3;order:3}.order-xl-4{-ms-flex-order:4;order:4}.order-xl-5{-ms-flex-order:5;order:5}.order-xl-6{-ms-flex-order:6;order:6}.order-xl-7{-ms-flex-order:7;order:7}.order-xl-8{-ms-flex-order:8;order:8}.order-xl-9{-ms-flex-order:9;order:9}.order-xl-10{-ms-flex-order:10;order:10}.order-xl-11{-ms-flex-order:11;order:11}.order-xl-12{-ms-flex-order:12;order:12}.offset-xl-0{margin-left:0}.offset-xl-1{margin-left:8.333333%}.offset-xl-2{margin-left:16.666667%}.offset-xl-3{margin-left:25%}.offset-xl-4{margin-left:33.333333%}.offset-xl-5{margin-left:41.666667%}.offset-xl-6{margin-left:50%}.offset-xl-7{margin-left:58.333333%}.offset-xl-8{margin-left:66.666667%}.offset-xl-9{margin-left:75%}.offset-xl-10{margin-left:83.333333%}.offset-xl-11{margin-left:91.666667%}}.table{width:100%;max-width:100%;margin-bottom:1rem;background-color:transparent}.table td,.table th{padding:.75rem;vertical-align:top;border-top:1px solid #e9ecef}.table thead th{vertical-align:bottom;border-bottom:2px solid #e9ecef}.table tbody+tbody{border-top:2px solid #e9ecef}.table .table{background-color:#fff}.table-sm td,.table-sm th{padding:.3rem}.table-bordered{border:1px solid #e9ecef}.table-bordered td,.table-bordered th{border:1px solid #e9ecef}.table-bordered thead td,.table-bordered thead th{border-bottom-width:2px}.table-striped tbody tr:nth-of-type(odd){background-color:rgba(0,0,0,.05)}.table-hover tbody tr:hover{background-color:rgba(0,0,0,.075)}.table-primary,.table-primary>td,.table-primary>th{background-color:#b8daff}.table-hover .table-primary:hover{background-color:#9fcdff}.table-hover .table-primary:hover>td,.table-hover .table-primary:hover>th{background-color:#9fcdff}.table-secondary,.table-secondary>td,.table-secondary>th{background-color:#dddfe2}.table-hover .table-secondary:hover{background-color:#cfd2d6}.table-hover .table-secondary:hover>td,.table-hover .table-secondary:hover>th{background-color:#cfd2d6}.table-success,.table-success>td,.table-success>th{background-color:#c3e6cb}.table-hover .table-success:hover{background-color:#b1dfbb}.table-hover .table-success:hover>td,.table-hover .table-success:hover>th{background-color:#b1dfbb}.table-info,.table-info>td,.table-info>th{background-color:#bee5eb}.table-hover .table-info:hover{background-color:#abdde5}.table-hover .table-info:hover>td,.table-hover .table-info:hover>th{background-color:#abdde5}.table-warning,.table-warning>td,.table-warning>th{background-color:#ffeeba}.table-hover .table-warning:hover{background-color:#ffe8a1}.table-hover .table-warning:hover>td,.table-hover .table-warning:hover>th{background-color:#ffe8a1}.table-danger,.table-danger>td,.table-danger>th{background-color:#f5c6cb}.table-hover .table-danger:hover{background-color:#f1b0b7}.table-hover .table-danger:hover>td,.table-hover .table-danger:hover>th{background-color:#f1b0b7}.table-light,.table-light>td,.table-light>th{background-color:#fdfdfe}.table-hover .table-light:hover{background-color:#ececf6}.table-hover .table-light:hover>td,.table-hover .table-light:hover>th{background-color:#ececf6}.table-dark,.table-dark>td,.table-dark>th{background-color:#c6c8ca}.table-hover .table-dark:hover{background-color:#b9bbbe}.table-hover .table-dark:hover>td,.table-hover .table-dark:hover>th{background-color:#b9bbbe}.table-active,.table-active>td,.table-active>th{background-color:rgba(0,0,0,.075)}.table-hover .table-active:hover{background-color:rgba(0,0,0,.075)}.table-hover .table-active:hover>td,.table-hover .table-active:hover>th{background-color:rgba(0,0,0,.075)}.table .thead-dark th{color:#fff;background-color:#212529;border-color:#32383e}.table .thead-light th{color:#495057;background-color:#e9ecef;border-color:#e9ecef}.table-dark{color:#fff;background-color:#212529}.table-dark td,.table-dark th,.table-dark thead th{border-color:#32383e}.table-dark.table-bordered{border:0}.table-dark.table-striped tbody tr:nth-of-type(odd){background-color:rgba(255,255,255,.05)}.table-dark.table-hover tbody tr:hover{background-color:rgba(255,255,255,.075)}@media (max-width:575px){.table-responsive-sm{display:block;width:100%;overflow-x:auto;-webkit-overflow-scrolling:touch;-ms-overflow-style:-ms-autohiding-scrollbar}.table-responsive-sm.table-bordered{border:0}}@media (max-width:767px){.table-responsive-md{display:block;width:100%;overflow-x:auto;-webkit-overflow-scrolling:touch;-ms-overflow-style:-ms-autohiding-scrollbar}.table-responsive-md.table-bordered{border:0}}@media (max-width:991px){.table-responsive-lg{display:block;width:100%;overflow-x:auto;-webkit-overflow-scrolling:touch;-ms-overflow-style:-ms-autohiding-scrollbar}.table-responsive-lg.table-bordered{border:0}}@media (max-width:1199px){.table-responsive-xl{display:block;width:100%;overflow-x:auto;-webkit-overflow-scrolling:touch;-ms-overflow-style:-ms-autohiding-scrollbar}.table-responsive-xl.table-bordered{border:0}}.table-responsive{display:block;width:100%;overflow-x:auto;-webkit-overflow-scrolling:touch;-ms-overflow-style:-ms-autohiding-scrollbar}.table-responsive.table-bordered{border:0}.form-control{display:block;width:100%;padding:.375rem .75rem;font-size:1rem;line-height:1.5;color:#495057;background-color:#fff;background-image:none;background-clip:padding-box;border:1px solid #ced4da;border-radius:.25rem;transition:border-color ease-in-out .15s,box-shadow ease-in-out .15s}.form-control::-ms-expand{background-color:transparent;border:0}.form-control:focus{color:#495057;background-color:#fff;border-color:#80bdff;outline:0;box-shadow:0 0 0 .2rem rgba(0,123,255,.25)}.form-control::-webkit-input-placeholder{color:#868e96;opacity:1}.form-control:-ms-input-placeholder{color:#868e96;opacity:1}.form-control::-ms-input-placeholder{color:#868e96;opacity:1}.form-control::placeholder{color:#868e96;opacity:1}.form-control:disabled,.form-control[readonly]{background-color:#e9ecef;opacity:1}select.form-control:not([size]):not([multiple]){height:calc(2.25rem + 2px)}select.form-control:focus::-ms-value{color:#495057;background-color:#fff}.form-control-file,.form-control-range{display:block}.col-form-label{padding-top:calc(.375rem + 1px);padding-bottom:calc(.375rem + 1px);margin-bottom:0;line-height:1.5}.col-form-label-lg{padding-top:calc(.5rem + 1px);padding-bottom:calc(.5rem + 1px);font-size:1.25rem;line-height:1.5}.col-form-label-sm{padding-top:calc(.25rem + 1px);padding-bottom:calc(.25rem + 1px);font-size:.875rem;line-height:1.5}.col-form-legend{padding-top:.375rem;padding-bottom:.375rem;margin-bottom:0;font-size:1rem}.form-control-plaintext{padding-top:.375rem;padding-bottom:.375rem;margin-bottom:0;line-height:1.5;background-color:transparent;border:solid transparent;border-width:1px 0}.form-control-plaintext.form-control-lg,.form-control-plaintext.form-control-sm,.input-group-lg>.form-control-plaintext.form-control,.input-group-lg>.form-control-plaintext.input-group-addon,.input-group-lg>.input-group-btn>.form-control-plaintext.btn,.input-group-sm>.form-control-plaintext.form-control,.input-group-sm>.form-control-plaintext.input-group-addon,.input-group-sm>.input-group-btn>.form-control-plaintext.btn{padding-right:0;padding-left:0}.form-control-sm,.input-group-sm>.form-control,.input-group-sm>.input-group-addon,.input-group-sm>.input-group-btn>.btn{padding:.25rem .5rem;font-size:.875rem;line-height:1.5;border-radius:.2rem}.input-group-sm>.input-group-btn>select.btn:not([size]):not([multiple]),.input-group-sm>select.form-control:not([size]):not([multiple]),.input-group-sm>select.input-group-addon:not([size]):not([multiple]),select.form-control-sm:not([size]):not([multiple]){height:calc(1.8125rem + 2px)}.form-control-lg,.input-group-lg>.form-control,.input-group-lg>.input-group-addon,.input-group-lg>.input-group-btn>.btn{padding:.5rem 1rem;font-size:1.25rem;line-height:1.5;border-radius:.3rem}.input-group-lg>.input-group-btn>select.btn:not([size]):not([multiple]),.input-group-lg>select.form-control:not([size]):not([multiple]),.input-group-lg>select.input-group-addon:not([size]):not([multiple]),select.form-control-lg:not([size]):not([multiple]){height:calc(2.875rem + 2px)}.form-group{margin-bottom:1rem}.form-text{display:block;margin-top:.25rem}.form-row{display:-ms-flexbox;display:flex;-ms-flex-wrap:wrap;flex-wrap:wrap;margin-right:-5px;margin-left:-5px}.form-row>.col,.form-row>[class*=col-]{padding-right:5px;padding-left:5px}.form-check{position:relative;display:block;margin-bottom:.5rem}.form-check.disabled .form-check-label{color:#868e96}.form-check-label{padding-left:1.25rem;margin-bottom:0}.form-check-input{position:absolute;margin-top:.25rem;margin-left:-1.25rem}.form-check-inline{display:inline-block;margin-right:.75rem}.form-check-inline .form-check-label{vertical-align:middle}.valid-feedback{display:none;margin-top:.25rem;font-size:.875rem;color:#28a745}.valid-tooltip{position:absolute;top:100%;z-index:5;display:none;width:250px;padding:.5rem;margin-top:.1rem;font-size:.875rem;line-height:1;color:#fff;background-color:rgba(40,167,69,.8);border-radius:.2rem}.custom-select.is-valid,.form-control.is-valid,.was-validated .custom-select:valid,.was-validated .form-control:valid{border-color:#28a745}.custom-select.is-valid:focus,.form-control.is-valid:focus,.was-validated .custom-select:valid:focus,.was-validated .form-control:valid:focus{box-shadow:0 0 0 .2rem rgba(40,167,69,.25)}.custom-select.is-valid~.valid-feedback,.custom-select.is-valid~.valid-tooltip,.form-control.is-valid~.valid-feedback,.form-control.is-valid~.valid-tooltip,.was-validated .custom-select:valid~.valid-feedback,.was-validated .custom-select:valid~.valid-tooltip,.was-validated .form-control:valid~.valid-feedback,.was-validated .form-control:valid~.valid-tooltip{display:block}.form-check-input.is-valid+.form-check-label,.was-validated .form-check-input:valid+.form-check-label{color:#28a745}.custom-control-input.is-valid~.custom-control-indicator,.was-validated .custom-control-input:valid~.custom-control-indicator{background-color:rgba(40,167,69,.25)}.custom-control-input.is-valid~.custom-control-description,.was-validated .custom-control-input:valid~.custom-control-description{color:#28a745}.custom-file-input.is-valid~.custom-file-control,.was-validated .custom-file-input:valid~.custom-file-control{border-color:#28a745}.custom-file-input.is-valid~.custom-file-control::before,.was-validated .custom-file-input:valid~.custom-file-control::before{border-color:inherit}.custom-file-input.is-valid:focus,.was-validated .custom-file-input:valid:focus{box-shadow:0 0 0 .2rem rgba(40,167,69,.25)}.invalid-feedback{display:none;margin-top:.25rem;font-size:.875rem;color:#dc3545}.invalid-tooltip{position:absolute;top:100%;z-index:5;display:none;width:250px;padding:.5rem;margin-top:.1rem;font-size:.875rem;line-height:1;color:#fff;background-color:rgba(220,53,69,.8);border-radius:.2rem}.custom-select.is-invalid,.form-control.is-invalid,.was-validated .custom-select:invalid,.was-validated .form-control:invalid{border-color:#dc3545}.custom-select.is-invalid:focus,.form-control.is-invalid:focus,.was-validated .custom-select:invalid:focus,.was-validated .form-control:invalid:focus{box-shadow:0 0 0 .2rem rgba(220,53,69,.25)}.custom-select.is-invalid~.invalid-feedback,.custom-select.is-invalid~.invalid-tooltip,.form-control.is-invalid~.invalid-feedback,.form-control.is-invalid~.invalid-tooltip,.was-validated .custom-select:invalid~.invalid-feedback,.was-validated .custom-select:invalid~.invalid-tooltip,.was-validated .form-control:invalid~.invalid-feedback,.was-validated .form-control:invalid~.invalid-tooltip{display:block}.form-check-input.is-invalid+.form-check-label,.was-validated .form-check-input:invalid+.form-check-label{color:#dc3545}.custom-control-input.is-invalid~.custom-control-indicator,.was-validated .custom-control-input:invalid~.custom-control-indicator{background-color:rgba(220,53,69,.25)}.custom-control-input.is-invalid~.custom-control-description,.was-validated .custom-control-input:invalid~.custom-control-description{color:#dc3545}.custom-file-input.is-invalid~.custom-file-control,.was-validated .custom-file-input:invalid~.custom-file-control{border-color:#dc3545}.custom-file-input.is-invalid~.custom-file-control::before,.was-validated .custom-file-input:invalid~.custom-file-control::before{border-color:inherit}.custom-file-input.is-invalid:focus,.was-validated .custom-file-input:invalid:focus{box-shadow:0 0 0 .2rem rgba(220,53,69,.25)}.form-inline{display:-ms-flexbox;display:flex;-ms-flex-flow:row wrap;flex-flow:row wrap;-ms-flex-align:center;align-items:center}.form-inline .form-check{width:100%}@media (min-width:576px){.form-inline label{display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center;-ms-flex-pack:center;justify-content:center;margin-bottom:0}.form-inline .form-group{display:-ms-flexbox;display:flex;-ms-flex:0 0 auto;flex:0 0 auto;-ms-flex-flow:row wrap;flex-flow:row wrap;-ms-flex-align:center;align-items:center;margin-bottom:0}.form-inline .form-control{display:inline-block;width:auto;vertical-align:middle}.form-inline .form-control-plaintext{display:inline-block}.form-inline .input-group{width:auto}.form-inline .form-check{display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center;-ms-flex-pack:center;justify-content:center;width:auto;margin-top:0;margin-bottom:0}.form-inline .form-check-label{padding-left:0}.form-inline .form-check-input{position:relative;margin-top:0;margin-right:.25rem;margin-left:0}.form-inline .custom-control{display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center;-ms-flex-pack:center;justify-content:center;padding-left:0}.form-inline .custom-control-indicator{position:static;display:inline-block;margin-right:.25rem;vertical-align:text-bottom}.form-inline .has-feedback .form-control-feedback{top:0}}.btn{display:inline-block;font-weight:400;text-align:center;white-space:nowrap;vertical-align:middle;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;border:1px solid transparent;padding:.375rem .75rem;font-size:1rem;line-height:1.5;border-radius:.25rem;transition:background-color .15s ease-in-out,border-color .15s ease-in-out,box-shadow .15s ease-in-out}.btn:focus,.btn:hover{text-decoration:none}.btn.focus,.btn:focus{outline:0;box-shadow:0 0 0 .2rem rgba(0,123,255,.25)}.btn.disabled,.btn:disabled{opacity:.65}.btn:not([disabled]):not(.disabled).active,.btn:not([disabled]):not(.disabled):active{background-image:none}a.btn.disabled,fieldset[disabled] a.btn{pointer-events:none}.btn-primary{color:#fff;background-color:#007bff;border-color:#007bff}.btn-primary:hover{color:#fff;background-color:#0069d9;border-color:#0062cc}.btn-primary.focus,.btn-primary:focus{box-shadow:0 0 0 .2rem rgba(0,123,255,.5)}.btn-primary.disabled,.btn-primary:disabled{background-color:#007bff;border-color:#007bff}.btn-primary:not([disabled]):not(.disabled).active,.btn-primary:not([disabled]):not(.disabled):active,.show>.btn-primary.dropdown-toggle{color:#fff;background-color:#0062cc;border-color:#005cbf;box-shadow:0 0 0 .2rem rgba(0,123,255,.5)}.btn-secondary{color:#fff;background-color:#868e96;border-color:#868e96}.btn-secondary:hover{color:#fff;background-color:#727b84;border-color:#6c757d}.btn-secondary.focus,.btn-secondary:focus{box-shadow:0 0 0 .2rem rgba(134,142,150,.5)}.btn-secondary.disabled,.btn-secondary:disabled{background-color:#868e96;border-color:#868e96}.btn-secondary:not([disabled]):not(.disabled).active,.btn-secondary:not([disabled]):not(.disabled):active,.show>.btn-secondary.dropdown-toggle{color:#fff;background-color:#6c757d;border-color:#666e76;box-shadow:0 0 0 .2rem rgba(134,142,150,.5)}.btn-success{color:#fff;background-color:#28a745;border-color:#28a745}.btn-success:hover{color:#fff;background-color:#218838;border-color:#1e7e34}.btn-success.focus,.btn-success:focus{box-shadow:0 0 0 .2rem rgba(40,167,69,.5)}.btn-success.disabled,.btn-success:disabled{background-color:#28a745;border-color:#28a745}.btn-success:not([disabled]):not(.disabled).active,.btn-success:not([disabled]):not(.disabled):active,.show>.btn-success.dropdown-toggle{color:#fff;background-color:#1e7e34;border-color:#1c7430;box-shadow:0 0 0 .2rem rgba(40,167,69,.5)}.btn-info{color:#fff;background-color:#17a2b8;border-color:#17a2b8}.btn-info:hover{color:#fff;background-color:#138496;border-color:#117a8b}.btn-info.focus,.btn-info:focus{box-shadow:0 0 0 .2rem rgba(23,162,184,.5)}.btn-info.disabled,.btn-info:disabled{background-color:#17a2b8;border-color:#17a2b8}.btn-info:not([disabled]):not(.disabled).active,.btn-info:not([disabled]):not(.disabled):active,.show>.btn-info.dropdown-toggle{color:#fff;background-color:#117a8b;border-color:#10707f;box-shadow:0 0 0 .2rem rgba(23,162,184,.5)}.btn-warning{color:#111;background-color:#ffc107;border-color:#ffc107}.btn-warning:hover{color:#111;background-color:#e0a800;border-color:#d39e00}.btn-warning.focus,.btn-warning:focus{box-shadow:0 0 0 .2rem rgba(255,193,7,.5)}.btn-warning.disabled,.btn-warning:disabled{background-color:#ffc107;border-color:#ffc107}.btn-warning:not([disabled]):not(.disabled).active,.btn-warning:not([disabled]):not(.disabled):active,.show>.btn-warning.dropdown-toggle{color:#111;background-color:#d39e00;border-color:#c69500;box-shadow:0 0 0 .2rem rgba(255,193,7,.5)}.btn-danger{color:#fff;background-color:#dc3545;border-color:#dc3545}.btn-danger:hover{color:#fff;background-color:#c82333;border-color:#bd2130}.btn-danger.focus,.btn-danger:focus{box-shadow:0 0 0 .2rem rgba(220,53,69,.5)}.btn-danger.disabled,.btn-danger:disabled{background-color:#dc3545;border-color:#dc3545}.btn-danger:not([disabled]):not(.disabled).active,.btn-danger:not([disabled]):not(.disabled):active,.show>.btn-danger.dropdown-toggle{color:#fff;background-color:#bd2130;border-color:#b21f2d;box-shadow:0 0 0 .2rem rgba(220,53,69,.5)}.btn-light{color:#111;background-color:#f8f9fa;border-color:#f8f9fa}.btn-light:hover{color:#111;background-color:#e2e6ea;border-color:#dae0e5}.btn-light.focus,.btn-light:focus{box-shadow:0 0 0 .2rem rgba(248,249,250,.5)}.btn-light.disabled,.btn-light:disabled{background-color:#f8f9fa;border-color:#f8f9fa}.btn-light:not([disabled]):not(.disabled).active,.btn-light:not([disabled]):not(.disabled):active,.show>.btn-light.dropdown-toggle{color:#111;background-color:#dae0e5;border-color:#d3d9df;box-shadow:0 0 0 .2rem rgba(248,249,250,.5)}.btn-dark{color:#fff;background-color:#343a40;border-color:#343a40}.btn-dark:hover{color:#fff;background-color:#23272b;border-color:#1d2124}.btn-dark.focus,.btn-dark:focus{box-shadow:0 0 0 .2rem rgba(52,58,64,.5)}.btn-dark.disabled,.btn-dark:disabled{background-color:#343a40;border-color:#343a40}.btn-dark:not([disabled]):not(.disabled).active,.btn-dark:not([disabled]):not(.disabled):active,.show>.btn-dark.dropdown-toggle{color:#fff;background-color:#1d2124;border-color:#171a1d;box-shadow:0 0 0 .2rem rgba(52,58,64,.5)}.btn-outline-primary{color:#007bff;background-color:transparent;background-image:none;border-color:#007bff}.btn-outline-primary:hover{color:#fff;background-color:#007bff;border-color:#007bff}.btn-outline-primary.focus,.btn-outline-primary:focus{box-shadow:0 0 0 .2rem rgba(0,123,255,.5)}.btn-outline-primary.disabled,.btn-outline-primary:disabled{color:#007bff;background-color:transparent}.btn-outline-primary:not([disabled]):not(.disabled).active,.btn-outline-primary:not([disabled]):not(.disabled):active,.show>.btn-outline-primary.dropdown-toggle{color:#fff;background-color:#007bff;border-color:#007bff;box-shadow:0 0 0 .2rem rgba(0,123,255,.5)}.btn-outline-secondary{color:#868e96;background-color:transparent;background-image:none;border-color:#868e96}.btn-outline-secondary:hover{color:#fff;background-color:#868e96;border-color:#868e96}.btn-outline-secondary.focus,.btn-outline-secondary:focus{box-shadow:0 0 0 .2rem rgba(134,142,150,.5)}.btn-outline-secondary.disabled,.btn-outline-secondary:disabled{color:#868e96;background-color:transparent}.btn-outline-secondary:not([disabled]):not(.disabled).active,.btn-outline-secondary:not([disabled]):not(.disabled):active,.show>.btn-outline-secondary.dropdown-toggle{color:#fff;background-color:#868e96;border-color:#868e96;box-shadow:0 0 0 .2rem rgba(134,142,150,.5)}.btn-outline-success{color:#28a745;background-color:transparent;background-image:none;border-color:#28a745}.btn-outline-success:hover{color:#fff;background-color:#28a745;border-color:#28a745}.btn-outline-success.focus,.btn-outline-success:focus{box-shadow:0 0 0 .2rem rgba(40,167,69,.5)}.btn-outline-success.disabled,.btn-outline-success:disabled{color:#28a745;background-color:transparent}.btn-outline-success:not([disabled]):not(.disabled).active,.btn-outline-success:not([disabled]):not(.disabled):active,.show>.btn-outline-success.dropdown-toggle{color:#fff;background-color:#28a745;border-color:#28a745;box-shadow:0 0 0 .2rem rgba(40,167,69,.5)}.btn-outline-info{color:#17a2b8;background-color:transparent;background-image:none;border-color:#17a2b8}.btn-outline-info:hover{color:#fff;background-color:#17a2b8;border-color:#17a2b8}.btn-outline-info.focus,.btn-outline-info:focus{box-shadow:0 0 0 .2rem rgba(23,162,184,.5)}.btn-outline-info.disabled,.btn-outline-info:disabled{color:#17a2b8;background-color:transparent}.btn-outline-info:not([disabled]):not(.disabled).active,.btn-outline-info:not([disabled]):not(.disabled):active,.show>.btn-outline-info.dropdown-toggle{color:#fff;background-color:#17a2b8;border-color:#17a2b8;box-shadow:0 0 0 .2rem rgba(23,162,184,.5)}.btn-outline-warning{color:#ffc107;background-color:transparent;background-image:none;border-color:#ffc107}.btn-outline-warning:hover{color:#fff;background-color:#ffc107;border-color:#ffc107}.btn-outline-warning.focus,.btn-outline-warning:focus{box-shadow:0 0 0 .2rem rgba(255,193,7,.5)}.btn-outline-warning.disabled,.btn-outline-warning:disabled{color:#ffc107;background-color:transparent}.btn-outline-warning:not([disabled]):not(.disabled).active,.btn-outline-warning:not([disabled]):not(.disabled):active,.show>.btn-outline-warning.dropdown-toggle{color:#fff;background-color:#ffc107;border-color:#ffc107;box-shadow:0 0 0 .2rem rgba(255,193,7,.5)}.btn-outline-danger{color:#dc3545;background-color:transparent;background-image:none;border-color:#dc3545}.btn-outline-danger:hover{color:#fff;background-color:#dc3545;border-color:#dc3545}.btn-outline-danger.focus,.btn-outline-danger:focus{box-shadow:0 0 0 .2rem rgba(220,53,69,.5)}.btn-outline-danger.disabled,.btn-outline-danger:disabled{color:#dc3545;background-color:transparent}.btn-outline-danger:not([disabled]):not(.disabled).active,.btn-outline-danger:not([disabled]):not(.disabled):active,.show>.btn-outline-danger.dropdown-toggle{color:#fff;background-color:#dc3545;border-color:#dc3545;box-shadow:0 0 0 .2rem rgba(220,53,69,.5)}.btn-outline-light{color:#f8f9fa;background-color:transparent;background-image:none;border-color:#f8f9fa}.btn-outline-light:hover{color:#212529;background-color:#f8f9fa;border-color:#f8f9fa}.btn-outline-light.focus,.btn-outline-light:focus{box-shadow:0 0 0 .2rem rgba(248,249,250,.5)}.btn-outline-light.disabled,.btn-outline-light:disabled{color:#f8f9fa;background-color:transparent}.btn-outline-light:not([disabled]):not(.disabled).active,.btn-outline-light:not([disabled]):not(.disabled):active,.show>.btn-outline-light.dropdown-toggle{color:#212529;background-color:#f8f9fa;border-color:#f8f9fa;box-shadow:0 0 0 .2rem rgba(248,249,250,.5)}.btn-outline-dark{color:#343a40;background-color:transparent;background-image:none;border-color:#343a40}.btn-outline-dark:hover{color:#fff;background-color:#343a40;border-color:#343a40}.btn-outline-dark.focus,.btn-outline-dark:focus{box-shadow:0 0 0 .2rem rgba(52,58,64,.5)}.btn-outline-dark.disabled,.btn-outline-dark:disabled{color:#343a40;background-color:transparent}.btn-outline-dark:not([disabled]):not(.disabled).active,.btn-outline-dark:not([disabled]):not(.disabled):active,.show>.btn-outline-dark.dropdown-toggle{color:#fff;background-color:#343a40;border-color:#343a40;box-shadow:0 0 0 .2rem rgba(52,58,64,.5)}.btn-link{font-weight:400;color:#007bff;background-color:transparent}.btn-link:hover{color:#0056b3;text-decoration:underline;background-color:transparent;border-color:transparent}.btn-link.focus,.btn-link:focus{border-color:transparent;box-shadow:none}.btn-link.disabled,.btn-link:disabled{color:#868e96}.btn-group-lg>.btn,.btn-lg{padding:.5rem 1rem;font-size:1.25rem;line-height:1.5;border-radius:.3rem}.btn-group-sm>.btn,.btn-sm{padding:.25rem .5rem;font-size:.875rem;line-height:1.5;border-radius:.2rem}.btn-block{display:block;width:100%}.btn-block+.btn-block{margin-top:.5rem}input[type=button].btn-block,input[type=reset].btn-block,input[type=submit].btn-block{width:100%}.fade{opacity:0;transition:opacity .15s linear}.fade.show{opacity:1}.collapse{display:none}.collapse.show{display:block}tr.collapse.show{display:table-row}tbody.collapse.show{display:table-row-group}.collapsing{position:relative;height:0;overflow:hidden;transition:height .35s ease}.dropdown,.dropup{position:relative}.dropdown-toggle::after{display:inline-block;width:0;height:0;margin-left:.255em;vertical-align:.255em;content:"";border-top:.3em solid;border-right:.3em solid transparent;border-bottom:0;border-left:.3em solid transparent}.dropdown-toggle:empty::after{margin-left:0}.dropdown-menu{position:absolute;top:100%;left:0;z-index:1000;display:none;float:left;min-width:10rem;padding:.5rem 0;margin:.125rem 0 0;font-size:1rem;color:#212529;text-align:left;list-style:none;background-color:#fff;background-clip:padding-box;border:1px solid rgba(0,0,0,.15);border-radius:.25rem}.dropup .dropdown-menu{margin-top:0;margin-bottom:.125rem}.dropup .dropdown-toggle::after{display:inline-block;width:0;height:0;margin-left:.255em;vertical-align:.255em;content:"";border-top:0;border-right:.3em solid transparent;border-bottom:.3em solid;border-left:.3em solid transparent}.dropup .dropdown-toggle:empty::after{margin-left:0}.dropdown-divider{height:0;margin:.5rem 0;overflow:hidden;border-top:1px solid #e9ecef}.dropdown-item{display:block;width:100%;padding:.25rem 1.5rem;clear:both;font-weight:400;color:#212529;text-align:inherit;white-space:nowrap;background:0 0;border:0}.dropdown-item:focus,.dropdown-item:hover{color:#16181b;text-decoration:none;background-color:#f8f9fa}.dropdown-item.active,.dropdown-item:active{color:#fff;text-decoration:none;background-color:#007bff}.dropdown-item.disabled,.dropdown-item:disabled{color:#868e96;background-color:transparent}.dropdown-menu.show{display:block}.dropdown-header{display:block;padding:.5rem 1.5rem;margin-bottom:0;font-size:.875rem;color:#868e96;white-space:nowrap}.btn-group,.btn-group-vertical{position:relative;display:-ms-inline-flexbox;display:inline-flex;vertical-align:middle}.btn-group-vertical>.btn,.btn-group>.btn{position:relative;-ms-flex:0 1 auto;flex:0 1 auto}.btn-group-vertical>.btn:hover,.btn-group>.btn:hover{z-index:2}.btn-group-vertical>.btn.active,.btn-group-vertical>.btn:active,.btn-group-vertical>.btn:focus,.btn-group>.btn.active,.btn-group>.btn:active,.btn-group>.btn:focus{z-index:2}.btn-group .btn+.btn,.btn-group .btn+.btn-group,.btn-group .btn-group+.btn,.btn-group .btn-group+.btn-group,.btn-group-vertical .btn+.btn,.btn-group-vertical .btn+.btn-group,.btn-group-vertical .btn-group+.btn,.btn-group-vertical .btn-group+.btn-group{margin-left:-1px}.btn-toolbar{display:-ms-flexbox;display:flex;-ms-flex-wrap:wrap;flex-wrap:wrap;-ms-flex-pack:start;justify-content:flex-start}.btn-toolbar .input-group{width:auto}.btn-group>.btn:not(:first-child):not(:last-child):not(.dropdown-toggle){border-radius:0}.btn-group>.btn:first-child{margin-left:0}.btn-group>.btn:first-child:not(:last-child):not(.dropdown-toggle){border-top-right-radius:0;border-bottom-right-radius:0}.btn-group>.btn:last-child:not(:first-child),.btn-group>.dropdown-toggle:not(:first-child){border-top-left-radius:0;border-bottom-left-radius:0}.btn-group>.btn-group{float:left}.btn-group>.btn-group:not(:first-child):not(:last-child)>.btn{border-radius:0}.btn-group>.btn-group:first-child:not(:last-child)>.btn:last-child,.btn-group>.btn-group:first-child:not(:last-child)>.dropdown-toggle{border-top-right-radius:0;border-bottom-right-radius:0}.btn-group>.btn-group:last-child:not(:first-child)>.btn:first-child{border-top-left-radius:0;border-bottom-left-radius:0}.btn+.dropdown-toggle-split{padding-right:.5625rem;padding-left:.5625rem}.btn+.dropdown-toggle-split::after{margin-left:0}.btn-group-sm>.btn+.dropdown-toggle-split,.btn-sm+.dropdown-toggle-split{padding-right:.375rem;padding-left:.375rem}.btn-group-lg>.btn+.dropdown-toggle-split,.btn-lg+.dropdown-toggle-split{padding-right:.75rem;padding-left:.75rem}.btn-group-vertical{-ms-flex-direction:column;flex-direction:column;-ms-flex-align:start;align-items:flex-start;-ms-flex-pack:center;justify-content:center}.btn-group-vertical .btn,.btn-group-vertical .btn-group{width:100%}.btn-group-vertical>.btn+.btn,.btn-group-vertical>.btn+.btn-group,.btn-group-vertical>.btn-group+.btn,.btn-group-vertical>.btn-group+.btn-group{margin-top:-1px;margin-left:0}.btn-group-vertical>.btn:not(:first-child):not(:last-child){border-radius:0}.btn-group-vertical>.btn:first-child:not(:last-child){border-bottom-right-radius:0;border-bottom-left-radius:0}.btn-group-vertical>.btn:last-child:not(:first-child){border-top-left-radius:0;border-top-right-radius:0}.btn-group-vertical>.btn-group:not(:first-child):not(:last-child)>.btn{border-radius:0}.btn-group-vertical>.btn-group:first-child:not(:last-child)>.btn:last-child,.btn-group-vertical>.btn-group:first-child:not(:last-child)>.dropdown-toggle{border-bottom-right-radius:0;border-bottom-left-radius:0}.btn-group-vertical>.btn-group:last-child:not(:first-child)>.btn:first-child{border-top-left-radius:0;border-top-right-radius:0}[data-toggle=buttons]>.btn input[type=checkbox],[data-toggle=buttons]>.btn input[type=radio],[data-toggle=buttons]>.btn-group>.btn input[type=checkbox],[data-toggle=buttons]>.btn-group>.btn input[type=radio]{position:absolute;clip:rect(0,0,0,0);pointer-events:none}.input-group{position:relative;display:-ms-flexbox;display:flex;-ms-flex-align:stretch;align-items:stretch;width:100%}.input-group .form-control{position:relative;z-index:2;-ms-flex:1 1 auto;flex:1 1 auto;width:1%;margin-bottom:0}.input-group .form-control:active,.input-group .form-control:focus,.input-group .form-control:hover{z-index:3}.input-group .form-control,.input-group-addon,.input-group-btn{display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center}.input-group .form-control:not(:first-child):not(:last-child),.input-group-addon:not(:first-child):not(:last-child),.input-group-btn:not(:first-child):not(:last-child){border-radius:0}.input-group-addon,.input-group-btn{white-space:nowrap}.input-group-addon{padding:.375rem .75rem;margin-bottom:0;font-size:1rem;font-weight:400;line-height:1.5;color:#495057;text-align:center;background-color:#e9ecef;border:1px solid #ced4da;border-radius:.25rem}.input-group-addon.form-control-sm,.input-group-sm>.input-group-addon,.input-group-sm>.input-group-btn>.input-group-addon.btn{padding:.25rem .5rem;font-size:.875rem;border-radius:.2rem}.input-group-addon.form-control-lg,.input-group-lg>.input-group-addon,.input-group-lg>.input-group-btn>.input-group-addon.btn{padding:.5rem 1rem;font-size:1.25rem;border-radius:.3rem}.input-group-addon input[type=checkbox],.input-group-addon input[type=radio]{margin-top:0}.input-group .form-control:not(:last-child),.input-group-addon:not(:last-child),.input-group-btn:not(:first-child)>.btn-group:not(:last-child)>.btn,.input-group-btn:not(:first-child)>.btn:not(:last-child):not(.dropdown-toggle),.input-group-btn:not(:last-child)>.btn,.input-group-btn:not(:last-child)>.btn-group>.btn,.input-group-btn:not(:last-child)>.dropdown-toggle{border-top-right-radius:0;border-bottom-right-radius:0}.input-group-addon:not(:last-child){border-right:0}.input-group .form-control:not(:first-child),.input-group-addon:not(:first-child),.input-group-btn:not(:first-child)>.btn,.input-group-btn:not(:first-child)>.btn-group>.btn,.input-group-btn:not(:first-child)>.dropdown-toggle,.input-group-btn:not(:last-child)>.btn-group:not(:first-child)>.btn,.input-group-btn:not(:last-child)>.btn:not(:first-child){border-top-left-radius:0;border-bottom-left-radius:0}.form-control+.input-group-addon:not(:first-child){border-left:0}.input-group-btn{position:relative;-ms-flex-align:stretch;align-items:stretch;font-size:0;white-space:nowrap}.input-group-btn>.btn{position:relative}.input-group-btn>.btn+.btn{margin-left:-1px}.input-group-btn>.btn:active,.input-group-btn>.btn:focus,.input-group-btn>.btn:hover{z-index:3}.input-group-btn:first-child>.btn+.btn{margin-left:0}.input-group-btn:not(:last-child)>.btn,.input-group-btn:not(:last-child)>.btn-group{margin-right:-1px}.input-group-btn:not(:first-child)>.btn,.input-group-btn:not(:first-child)>.btn-group{z-index:2;margin-left:0}.input-group-btn:not(:first-child)>.btn-group:first-child,.input-group-btn:not(:first-child)>.btn:first-child{margin-left:-1px}.input-group-btn:not(:first-child)>.btn-group:active,.input-group-btn:not(:first-child)>.btn-group:focus,.input-group-btn:not(:first-child)>.btn-group:hover,.input-group-btn:not(:first-child)>.btn:active,.input-group-btn:not(:first-child)>.btn:focus,.input-group-btn:not(:first-child)>.btn:hover{z-index:3}.custom-control{position:relative;display:-ms-inline-flexbox;display:inline-flex;min-height:1.5rem;padding-left:1.5rem;margin-right:1rem}.custom-control-input{position:absolute;z-index:-1;opacity:0}.custom-control-input:checked~.custom-control-indicator{color:#fff;background-color:#007bff}.custom-control-input:focus~.custom-control-indicator{box-shadow:0 0 0 1px #fff,0 0 0 .2rem rgba(0,123,255,.25)}.custom-control-input:active~.custom-control-indicator{color:#fff;background-color:#b3d7ff}.custom-control-input:disabled~.custom-control-indicator{background-color:#e9ecef}.custom-control-input:disabled~.custom-control-description{color:#868e96}.custom-control-indicator{position:absolute;top:.25rem;left:0;display:block;width:1rem;height:1rem;pointer-events:none;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;background-color:#ddd;background-repeat:no-repeat;background-position:center center;background-size:50% 50%}.custom-checkbox .custom-control-indicator{border-radius:.25rem}.custom-checkbox .custom-control-input:checked~.custom-control-indicator{background-image:url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 8 8'%3E%3Cpath fill='%23fff' d='M6.564.75l-3.59 3.612-1.538-1.55L0 4.26 2.974 7.25 8 2.193z'/%3E%3C/svg%3E")}.custom-checkbox .custom-control-input:indeterminate~.custom-control-indicator{background-color:#007bff;background-image:url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 4 4'%3E%3Cpath stroke='%23fff' d='M0 2h4'/%3E%3C/svg%3E")}.custom-radio .custom-control-indicator{border-radius:50%}.custom-radio .custom-control-input:checked~.custom-control-indicator{background-image:url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='-4 -4 8 8'%3E%3Ccircle r='3' fill='%23fff'/%3E%3C/svg%3E")}.custom-controls-stacked{display:-ms-flexbox;display:flex;-ms-flex-direction:column;flex-direction:column}.custom-controls-stacked .custom-control{margin-bottom:.25rem}.custom-controls-stacked .custom-control+.custom-control{margin-left:0}.custom-select{display:inline-block;max-width:100%;height:calc(2.25rem + 2px);padding:.375rem 1.75rem .375rem .75rem;line-height:1.5;color:#495057;vertical-align:middle;background:#fff url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 4 5'%3E%3Cpath fill='%23333' d='M2 0L0 2h4zm0 5L0 3h4z'/%3E%3C/svg%3E") no-repeat right .75rem center;background-size:8px 10px;border:1px solid #ced4da;border-radius:.25rem;-webkit-appearance:none;-moz-appearance:none;appearance:none}.custom-select:focus{border-color:#80bdff;outline:0}.custom-select:focus::-ms-value{color:#495057;background-color:#fff}.custom-select[multiple]{height:auto;background-image:none}.custom-select:disabled{color:#868e96;background-color:#e9ecef}.custom-select::-ms-expand{opacity:0}.custom-select-sm{height:calc(1.8125rem + 2px);padding-top:.375rem;padding-bottom:.375rem;font-size:75%}.custom-file{position:relative;display:inline-block;max-width:100%;height:calc(2.25rem + 2px);margin-bottom:0}.custom-file-input{min-width:14rem;max-width:100%;height:calc(2.25rem + 2px);margin:0;opacity:0}.custom-file-input:focus~.custom-file-control{box-shadow:0 0 0 .075rem #fff,0 0 0 .2rem #007bff}.custom-file-control{position:absolute;top:0;right:0;left:0;z-index:5;height:calc(2.25rem + 2px);padding:.375rem .75rem;line-height:1.5;color:#495057;pointer-events:none;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;background-color:#fff;border:1px solid #ced4da;border-radius:.25rem}.custom-file-control:lang(en):empty::after{content:"Choose file..."}.custom-file-control::before{position:absolute;top:-1px;right:-1px;bottom:-1px;z-index:6;display:block;height:calc(2.25rem + 2px);padding:.375rem .75rem;line-height:1.5;color:#495057;background-color:#e9ecef;border:1px solid #ced4da;border-radius:0 .25rem .25rem 0}.custom-file-control:lang(en)::before{content:"Browse"}.nav{display:-ms-flexbox;display:flex;-ms-flex-wrap:wrap;flex-wrap:wrap;padding-left:0;margin-bottom:0;list-style:none}.nav-link{display:block;padding:.5rem 1rem}.nav-link:focus,.nav-link:hover{text-decoration:none}.nav-link.disabled{color:#868e96}.nav-tabs{border-bottom:1px solid #ddd}.nav-tabs .nav-item{margin-bottom:-1px}.nav-tabs .nav-link{border:1px solid transparent;border-top-left-radius:.25rem;border-top-right-radius:.25rem}.nav-tabs .nav-link:focus,.nav-tabs .nav-link:hover{border-color:#e9ecef #e9ecef #ddd}.nav-tabs .nav-link.disabled{color:#868e96;background-color:transparent;border-color:transparent}.nav-tabs .nav-item.show .nav-link,.nav-tabs .nav-link.active{color:#495057;background-color:#fff;border-color:#ddd #ddd #fff}.nav-tabs .dropdown-menu{margin-top:-1px;border-top-left-radius:0;border-top-right-radius:0}.nav-pills .nav-link{border-radius:.25rem}.nav-pills .nav-link.active,.nav-pills .show>.nav-link{color:#fff;background-color:#007bff}.nav-fill .nav-item{-ms-flex:1 1 auto;flex:1 1 auto;text-align:center}.nav-justified .nav-item{-ms-flex-preferred-size:0;flex-basis:0;-ms-flex-positive:1;flex-grow:1;text-align:center}.tab-content>.tab-pane{display:none}.tab-content>.active{display:block}.navbar{position:relative;display:-ms-flexbox;display:flex;-ms-flex-wrap:wrap;flex-wrap:wrap;-ms-flex-align:center;align-items:center;-ms-flex-pack:justify;justify-content:space-between;padding:.5rem 1rem}.navbar>.container,.navbar>.container-fluid{display:-ms-flexbox;display:flex;-ms-flex-wrap:wrap;flex-wrap:wrap;-ms-flex-align:center;align-items:center;-ms-flex-pack:justify;justify-content:space-between}.navbar-brand{display:inline-block;padding-top:.3125rem;padding-bottom:.3125rem;margin-right:1rem;font-size:1.25rem;line-height:inherit;white-space:nowrap}.navbar-brand:focus,.navbar-brand:hover{text-decoration:none}.navbar-nav{display:-ms-flexbox;display:flex;-ms-flex-direction:column;flex-direction:column;padding-left:0;margin-bottom:0;list-style:none}.navbar-nav .nav-link{padding-right:0;padding-left:0}.navbar-nav .dropdown-menu{position:static;float:none}.navbar-text{display:inline-block;padding-top:.5rem;padding-bottom:.5rem}.navbar-collapse{-ms-flex-preferred-size:100%;flex-basis:100%;-ms-flex-positive:1;flex-grow:1;-ms-flex-align:center;align-items:center}.navbar-toggler{padding:.25rem .75rem;font-size:1.25rem;line-height:1;background:0 0;border:1px solid transparent;border-radius:.25rem}.navbar-toggler:focus,.navbar-toggler:hover{text-decoration:none}.navbar-toggler-icon{display:inline-block;width:1.5em;height:1.5em;vertical-align:middle;content:"";background:no-repeat center center;background-size:100% 100%}@media (max-width:575px){.navbar-expand-sm>.container,.navbar-expand-sm>.container-fluid{padding-right:0;padding-left:0}}@media (min-width:576px){.navbar-expand-sm{-ms-flex-flow:row nowrap;flex-flow:row nowrap;-ms-flex-pack:start;justify-content:flex-start}.navbar-expand-sm .navbar-nav{-ms-flex-direction:row;flex-direction:row}.navbar-expand-sm .navbar-nav .dropdown-menu{position:absolute}.navbar-expand-sm .navbar-nav .dropdown-menu-right{right:0;left:auto}.navbar-expand-sm .navbar-nav .nav-link{padding-right:.5rem;padding-left:.5rem}.navbar-expand-sm>.container,.navbar-expand-sm>.container-fluid{-ms-flex-wrap:nowrap;flex-wrap:nowrap}.navbar-expand-sm .navbar-collapse{display:-ms-flexbox!important;display:flex!important;-ms-flex-preferred-size:auto;flex-basis:auto}.navbar-expand-sm .navbar-toggler{display:none}.navbar-expand-sm .dropup .dropdown-menu{top:auto;bottom:100%}}@media (max-width:767px){.navbar-expand-md>.container,.navbar-expand-md>.container-fluid{padding-right:0;padding-left:0}}@media (min-width:768px){.navbar-expand-md{-ms-flex-flow:row nowrap;flex-flow:row nowrap;-ms-flex-pack:start;justify-content:flex-start}.navbar-expand-md .navbar-nav{-ms-flex-direction:row;flex-direction:row}.navbar-expand-md .navbar-nav .dropdown-menu{position:absolute}.navbar-expand-md .navbar-nav .dropdown-menu-right{right:0;left:auto}.navbar-expand-md .navbar-nav .nav-link{padding-right:.5rem;padding-left:.5rem}.navbar-expand-md>.container,.navbar-expand-md>.container-fluid{-ms-flex-wrap:nowrap;flex-wrap:nowrap}.navbar-expand-md .navbar-collapse{display:-ms-flexbox!important;display:flex!important;-ms-flex-preferred-size:auto;flex-basis:auto}.navbar-expand-md .navbar-toggler{display:none}.navbar-expand-md .dropup .dropdown-menu{top:auto;bottom:100%}}@media (max-width:991px){.navbar-expand-lg>.container,.navbar-expand-lg>.container-fluid{padding-right:0;padding-left:0}}@media (min-width:992px){.navbar-expand-lg{-ms-flex-flow:row nowrap;flex-flow:row nowrap;-ms-flex-pack:start;justify-content:flex-start}.navbar-expand-lg .navbar-nav{-ms-flex-direction:row;flex-direction:row}.navbar-expand-lg .navbar-nav .dropdown-menu{position:absolute}.navbar-expand-lg .navbar-nav .dropdown-menu-right{right:0;left:auto}.navbar-expand-lg .navbar-nav .nav-link{padding-right:.5rem;padding-left:.5rem}.navbar-expand-lg>.container,.navbar-expand-lg>.container-fluid{-ms-flex-wrap:nowrap;flex-wrap:nowrap}.navbar-expand-lg .navbar-collapse{display:-ms-flexbox!important;display:flex!important;-ms-flex-preferred-size:auto;flex-basis:auto}.navbar-expand-lg .navbar-toggler{display:none}.navbar-expand-lg .dropup .dropdown-menu{top:auto;bottom:100%}}@media (max-width:1199px){.navbar-expand-xl>.container,.navbar-expand-xl>.container-fluid{padding-right:0;padding-left:0}}@media (min-width:1200px){.navbar-expand-xl{-ms-flex-flow:row nowrap;flex-flow:row nowrap;-ms-flex-pack:start;justify-content:flex-start}.navbar-expand-xl .navbar-nav{-ms-flex-direction:row;flex-direction:row}.navbar-expand-xl .navbar-nav .dropdown-menu{position:absolute}.navbar-expand-xl .navbar-nav .dropdown-menu-right{right:0;left:auto}.navbar-expand-xl .navbar-nav .nav-link{padding-right:.5rem;padding-left:.5rem}.navbar-expand-xl>.container,.navbar-expand-xl>.container-fluid{-ms-flex-wrap:nowrap;flex-wrap:nowrap}.navbar-expand-xl .navbar-collapse{display:-ms-flexbox!important;display:flex!important;-ms-flex-preferred-size:auto;flex-basis:auto}.navbar-expand-xl .navbar-toggler{display:none}.navbar-expand-xl .dropup .dropdown-menu{top:auto;bottom:100%}}.navbar-expand{-ms-flex-flow:row nowrap;flex-flow:row nowrap;-ms-flex-pack:start;justify-content:flex-start}.navbar-expand>.container,.navbar-expand>.container-fluid{padding-right:0;padding-left:0}.navbar-expand .navbar-nav{-ms-flex-direction:row;flex-direction:row}.navbar-expand .navbar-nav .dropdown-menu{position:absolute}.navbar-expand .navbar-nav .dropdown-menu-right{right:0;left:auto}.navbar-expand .navbar-nav .nav-link{padding-right:.5rem;padding-left:.5rem}.navbar-expand>.container,.navbar-expand>.container-fluid{-ms-flex-wrap:nowrap;flex-wrap:nowrap}.navbar-expand .navbar-collapse{display:-ms-flexbox!important;display:flex!important;-ms-flex-preferred-size:auto;flex-basis:auto}.navbar-expand .navbar-toggler{display:none}.navbar-expand .dropup .dropdown-menu{top:auto;bottom:100%}.navbar-light .navbar-brand{color:rgba(0,0,0,.9)}.navbar-light .navbar-brand:focus,.navbar-light .navbar-brand:hover{color:rgba(0,0,0,.9)}.navbar-light .navbar-nav .nav-link{color:rgba(0,0,0,.5)}.navbar-light .navbar-nav .nav-link:focus,.navbar-light .navbar-nav .nav-link:hover{color:rgba(0,0,0,.7)}.navbar-light .navbar-nav .nav-link.disabled{color:rgba(0,0,0,.3)}.navbar-light .navbar-nav .active>.nav-link,.navbar-light .navbar-nav .nav-link.active,.navbar-light .navbar-nav .nav-link.show,.navbar-light .navbar-nav .show>.nav-link{color:rgba(0,0,0,.9)}.navbar-light .navbar-toggler{color:rgba(0,0,0,.5);border-color:rgba(0,0,0,.1)}.navbar-light .navbar-toggler-icon{background-image:url("data:image/svg+xml;charset=utf8,%3Csvg viewBox='0 0 30 30' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath stroke='rgba(0, 0, 0, 0.5)' stroke-width='2' stroke-linecap='round' stroke-miterlimit='10' d='M4 7h22M4 15h22M4 23h22'/%3E%3C/svg%3E")}.navbar-light .navbar-text{color:rgba(0,0,0,.5)}.navbar-light .navbar-text a{color:rgba(0,0,0,.9)}.navbar-light .navbar-text a:focus,.navbar-light .navbar-text a:hover{color:rgba(0,0,0,.9)}.navbar-dark .navbar-brand{color:#fff}.navbar-dark .navbar-brand:focus,.navbar-dark .navbar-brand:hover{color:#fff}.navbar-dark .navbar-nav .nav-link{color:rgba(255,255,255,.5)}.navbar-dark .navbar-nav .nav-link:focus,.navbar-dark .navbar-nav .nav-link:hover{color:rgba(255,255,255,.75)}.navbar-dark .navbar-nav .nav-link.disabled{color:rgba(255,255,255,.25)}.navbar-dark .navbar-nav .active>.nav-link,.navbar-dark .navbar-nav .nav-link.active,.navbar-dark .navbar-nav .nav-link.show,.navbar-dark .navbar-nav .show>.nav-link{color:#fff}.navbar-dark .navbar-toggler{color:rgba(255,255,255,.5);border-color:rgba(255,255,255,.1)}.navbar-dark .navbar-toggler-icon{background-image:url("data:image/svg+xml;charset=utf8,%3Csvg viewBox='0 0 30 30' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath stroke='rgba(255, 255, 255, 0.5)' stroke-width='2' stroke-linecap='round' stroke-miterlimit='10' d='M4 7h22M4 15h22M4 23h22'/%3E%3C/svg%3E")}.navbar-dark .navbar-text{color:rgba(255,255,255,.5)}.navbar-dark .navbar-text a{color:#fff}.navbar-dark .navbar-text a:focus,.navbar-dark .navbar-text a:hover{color:#fff}.card{position:relative;display:-ms-flexbox;display:flex;-ms-flex-direction:column;flex-direction:column;min-width:0;word-wrap:break-word;background-color:#fff;background-clip:border-box;border:1px solid rgba(0,0,0,.125);border-radius:.25rem}.card>hr{margin-right:0;margin-left:0}.card>.list-group:first-child .list-group-item:first-child{border-top-left-radius:.25rem;border-top-right-radius:.25rem}.card>.list-group:last-child .list-group-item:last-child{border-bottom-right-radius:.25rem;border-bottom-left-radius:.25rem}.card-body{-ms-flex:1 1 auto;flex:1 1 auto;padding:1.25rem}.card-title{margin-bottom:.75rem}.card-subtitle{margin-top:-.375rem;margin-bottom:0}.card-text:last-child{margin-bottom:0}.card-link:hover{text-decoration:none}.card-link+.card-link{margin-left:1.25rem}.card-header{padding:.75rem 1.25rem;margin-bottom:0;background-color:rgba(0,0,0,.03);border-bottom:1px solid rgba(0,0,0,.125)}.card-header:first-child{border-radius:calc(.25rem - 1px) calc(.25rem - 1px) 0 0}.card-header+.list-group .list-group-item:first-child{border-top:0}.card-footer{padding:.75rem 1.25rem;background-color:rgba(0,0,0,.03);border-top:1px solid rgba(0,0,0,.125)}.card-footer:last-child{border-radius:0 0 calc(.25rem - 1px) calc(.25rem - 1px)}.card-header-tabs{margin-right:-.625rem;margin-bottom:-.75rem;margin-left:-.625rem;border-bottom:0}.card-header-pills{margin-right:-.625rem;margin-left:-.625rem}.card-img-overlay{position:absolute;top:0;right:0;bottom:0;left:0;padding:1.25rem}.card-img{width:100%;border-radius:calc(.25rem - 1px)}.card-img-top{width:100%;border-top-left-radius:calc(.25rem - 1px);border-top-right-radius:calc(.25rem - 1px)}.card-img-bottom{width:100%;border-bottom-right-radius:calc(.25rem - 1px);border-bottom-left-radius:calc(.25rem - 1px)}.card-deck{display:-ms-flexbox;display:flex;-ms-flex-direction:column;flex-direction:column}.card-deck .card{margin-bottom:15px}@media (min-width:576px){.card-deck{-ms-flex-flow:row wrap;flex-flow:row wrap;margin-right:-15px;margin-left:-15px}.card-deck .card{display:-ms-flexbox;display:flex;-ms-flex:1 0 0%;flex:1 0 0%;-ms-flex-direction:column;flex-direction:column;margin-right:15px;margin-bottom:0;margin-left:15px}}.card-group{display:-ms-flexbox;display:flex;-ms-flex-direction:column;flex-direction:column}.card-group .card{margin-bottom:15px}@media (min-width:576px){.card-group{-ms-flex-flow:row wrap;flex-flow:row wrap}.card-group .card{-ms-flex:1 0 0%;flex:1 0 0%;margin-bottom:0}.card-group .card+.card{margin-left:0;border-left:0}.card-group .card:first-child{border-top-right-radius:0;border-bottom-right-radius:0}.card-group .card:first-child .card-img-top{border-top-right-radius:0}.card-group .card:first-child .card-img-bottom{border-bottom-right-radius:0}.card-group .card:last-child{border-top-left-radius:0;border-bottom-left-radius:0}.card-group .card:last-child .card-img-top{border-top-left-radius:0}.card-group .card:last-child .card-img-bottom{border-bottom-left-radius:0}.card-group .card:only-child{border-radius:.25rem}.card-group .card:only-child .card-img-top{border-top-left-radius:.25rem;border-top-right-radius:.25rem}.card-group .card:only-child .card-img-bottom{border-bottom-right-radius:.25rem;border-bottom-left-radius:.25rem}.card-group .card:not(:first-child):not(:last-child):not(:only-child){border-radius:0}.card-group .card:not(:first-child):not(:last-child):not(:only-child) .card-img-bottom,.card-group .card:not(:first-child):not(:last-child):not(:only-child) .card-img-top{border-radius:0}}.card-columns .card{margin-bottom:.75rem}@media (min-width:576px){.card-columns{-webkit-column-count:3;column-count:3;-webkit-column-gap:1.25rem;column-gap:1.25rem}.card-columns .card{display:inline-block;width:100%}}.breadcrumb{display:-ms-flexbox;display:flex;-ms-flex-wrap:wrap;flex-wrap:wrap;padding:.75rem 1rem;margin-bottom:1rem;list-style:none;background-color:#e9ecef;border-radius:.25rem}.breadcrumb-item+.breadcrumb-item::before{display:inline-block;padding-right:.5rem;padding-left:.5rem;color:#868e96;content:"/"}.breadcrumb-item+.breadcrumb-item:hover::before{text-decoration:underline}.breadcrumb-item+.breadcrumb-item:hover::before{text-decoration:none}.breadcrumb-item.active{color:#868e96}.pagination{display:-ms-flexbox;display:flex;padding-left:0;list-style:none;border-radius:.25rem}.page-item:first-child .page-link{margin-left:0;border-top-left-radius:.25rem;border-bottom-left-radius:.25rem}.page-item:last-child .page-link{border-top-right-radius:.25rem;border-bottom-right-radius:.25rem}.page-item.active .page-link{z-index:2;color:#fff;background-color:#007bff;border-color:#007bff}.page-item.disabled .page-link{color:#868e96;pointer-events:none;background-color:#fff;border-color:#ddd}.page-link{position:relative;display:block;padding:.5rem .75rem;margin-left:-1px;line-height:1.25;color:#007bff;background-color:#fff;border:1px solid #ddd}.page-link:focus,.page-link:hover{color:#0056b3;text-decoration:none;background-color:#e9ecef;border-color:#ddd}.pagination-lg .page-link{padding:.75rem 1.5rem;font-size:1.25rem;line-height:1.5}.pagination-lg .page-item:first-child .page-link{border-top-left-radius:.3rem;border-bottom-left-radius:.3rem}.pagination-lg .page-item:last-child .page-link{border-top-right-radius:.3rem;border-bottom-right-radius:.3rem}.pagination-sm .page-link{padding:.25rem .5rem;font-size:.875rem;line-height:1.5}.pagination-sm .page-item:first-child .page-link{border-top-left-radius:.2rem;border-bottom-left-radius:.2rem}.pagination-sm .page-item:last-child .page-link{border-top-right-radius:.2rem;border-bottom-right-radius:.2rem}.badge{display:inline-block;padding:.25em .4em;font-size:75%;font-weight:700;line-height:1;text-align:center;white-space:nowrap;vertical-align:baseline;border-radius:.25rem}.badge:empty{display:none}.btn .badge{position:relative;top:-1px}.badge-pill{padding-right:.6em;padding-left:.6em;border-radius:10rem}.badge-primary{color:#fff;background-color:#007bff}.badge-primary[href]:focus,.badge-primary[href]:hover{color:#fff;text-decoration:none;background-color:#0062cc}.badge-secondary{color:#fff;background-color:#868e96}.badge-secondary[href]:focus,.badge-secondary[href]:hover{color:#fff;text-decoration:none;background-color:#6c757d}.badge-success{color:#fff;background-color:#28a745}.badge-success[href]:focus,.badge-success[href]:hover{color:#fff;text-decoration:none;background-color:#1e7e34}.badge-info{color:#fff;background-color:#17a2b8}.badge-info[href]:focus,.badge-info[href]:hover{color:#fff;text-decoration:none;background-color:#117a8b}.badge-warning{color:#111;background-color:#ffc107}.badge-warning[href]:focus,.badge-warning[href]:hover{color:#111;text-decoration:none;background-color:#d39e00}.badge-danger{color:#fff;background-color:#dc3545}.badge-danger[href]:focus,.badge-danger[href]:hover{color:#fff;text-decoration:none;background-color:#bd2130}.badge-light{color:#111;background-color:#f8f9fa}.badge-light[href]:focus,.badge-light[href]:hover{color:#111;text-decoration:none;background-color:#dae0e5}.badge-dark{color:#fff;background-color:#343a40}.badge-dark[href]:focus,.badge-dark[href]:hover{color:#fff;text-decoration:none;background-color:#1d2124}.jumbotron{padding:2rem 1rem;margin-bottom:2rem;background-color:#e9ecef;border-radius:.3rem}@media (min-width:576px){.jumbotron{padding:4rem 2rem}}.jumbotron-fluid{padding-right:0;padding-left:0;border-radius:0}.alert{position:relative;padding:.75rem 1.25rem;margin-bottom:1rem;border:1px solid transparent;border-radius:.25rem}.alert-heading{color:inherit}.alert-link{font-weight:700}.alert-dismissible .close{position:absolute;top:0;right:0;padding:.75rem 1.25rem;color:inherit}.alert-primary{color:#004085;background-color:#cce5ff;border-color:#b8daff}.alert-primary hr{border-top-color:#9fcdff}.alert-primary .alert-link{color:#002752}.alert-secondary{color:#464a4e;background-color:#e7e8ea;border-color:#dddfe2}.alert-secondary hr{border-top-color:#cfd2d6}.alert-secondary .alert-link{color:#2e3133}.alert-success{color:#155724;background-color:#d4edda;border-color:#c3e6cb}.alert-success hr{border-top-color:#b1dfbb}.alert-success .alert-link{color:#0b2e13}.alert-info{color:#0c5460;background-color:#d1ecf1;border-color:#bee5eb}.alert-info hr{border-top-color:#abdde5}.alert-info .alert-link{color:#062c33}.alert-warning{color:#856404;background-color:#fff3cd;border-color:#ffeeba}.alert-warning hr{border-top-color:#ffe8a1}.alert-warning .alert-link{color:#533f03}.alert-danger{color:#721c24;background-color:#f8d7da;border-color:#f5c6cb}.alert-danger hr{border-top-color:#f1b0b7}.alert-danger .alert-link{color:#491217}.alert-light{color:#818182;background-color:#fefefe;border-color:#fdfdfe}.alert-light hr{border-top-color:#ececf6}.alert-light .alert-link{color:#686868}.alert-dark{color:#1b1e21;background-color:#d6d8d9;border-color:#c6c8ca}.alert-dark hr{border-top-color:#b9bbbe}.alert-dark .alert-link{color:#040505}@-webkit-keyframes progress-bar-stripes{from{background-position:1rem 0}to{background-position:0 0}}@keyframes progress-bar-stripes{from{background-position:1rem 0}to{background-position:0 0}}.progress{display:-ms-flexbox;display:flex;height:1rem;overflow:hidden;font-size:.75rem;background-color:#e9ecef;border-radius:.25rem}.progress-bar{display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center;-ms-flex-pack:center;justify-content:center;color:#fff;background-color:#007bff}.progress-bar-striped{background-image:linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-size:1rem 1rem}.progress-bar-animated{-webkit-animation:progress-bar-stripes 1s linear infinite;animation:progress-bar-stripes 1s linear infinite}.media{display:-ms-flexbox;display:flex;-ms-flex-align:start;align-items:flex-start}.media-body{-ms-flex:1;flex:1}.list-group{display:-ms-flexbox;display:flex;-ms-flex-direction:column;flex-direction:column;padding-left:0;margin-bottom:0}.list-group-item-action{width:100%;color:#495057;text-align:inherit}.list-group-item-action:focus,.list-group-item-action:hover{color:#495057;text-decoration:none;background-color:#f8f9fa}.list-group-item-action:active{color:#212529;background-color:#e9ecef}.list-group-item{position:relative;display:block;padding:.75rem 1.25rem;margin-bottom:-1px;background-color:#fff;border:1px solid rgba(0,0,0,.125)}.list-group-item:first-child{border-top-left-radius:.25rem;border-top-right-radius:.25rem}.list-group-item:last-child{margin-bottom:0;border-bottom-right-radius:.25rem;border-bottom-left-radius:.25rem}.list-group-item:focus,.list-group-item:hover{text-decoration:none}.list-group-item.disabled,.list-group-item:disabled{color:#868e96;background-color:#fff}.list-group-item.active{z-index:2;color:#fff;background-color:#007bff;border-color:#007bff}.list-group-flush .list-group-item{border-right:0;border-left:0;border-radius:0}.list-group-flush:first-child .list-group-item:first-child{border-top:0}.list-group-flush:last-child .list-group-item:last-child{border-bottom:0}.list-group-item-primary{color:#004085;background-color:#b8daff}a.list-group-item-primary,button.list-group-item-primary{color:#004085}a.list-group-item-primary:focus,a.list-group-item-primary:hover,button.list-group-item-primary:focus,button.list-group-item-primary:hover{color:#004085;background-color:#9fcdff}a.list-group-item-primary.active,button.list-group-item-primary.active{color:#fff;background-color:#004085;border-color:#004085}.list-group-item-secondary{color:#464a4e;background-color:#dddfe2}a.list-group-item-secondary,button.list-group-item-secondary{color:#464a4e}a.list-group-item-secondary:focus,a.list-group-item-secondary:hover,button.list-group-item-secondary:focus,button.list-group-item-secondary:hover{color:#464a4e;background-color:#cfd2d6}a.list-group-item-secondary.active,button.list-group-item-secondary.active{color:#fff;background-color:#464a4e;border-color:#464a4e}.list-group-item-success{color:#155724;background-color:#c3e6cb}a.list-group-item-success,button.list-group-item-success{color:#155724}a.list-group-item-success:focus,a.list-group-item-success:hover,button.list-group-item-success:focus,button.list-group-item-success:hover{color:#155724;background-color:#b1dfbb}a.list-group-item-success.active,button.list-group-item-success.active{color:#fff;background-color:#155724;border-color:#155724}.list-group-item-info{color:#0c5460;background-color:#bee5eb}a.list-group-item-info,button.list-group-item-info{color:#0c5460}a.list-group-item-info:focus,a.list-group-item-info:hover,button.list-group-item-info:focus,button.list-group-item-info:hover{color:#0c5460;background-color:#abdde5}a.list-group-item-info.active,button.list-group-item-info.active{color:#fff;background-color:#0c5460;border-color:#0c5460}.list-group-item-warning{color:#856404;background-color:#ffeeba}a.list-group-item-warning,button.list-group-item-warning{color:#856404}a.list-group-item-warning:focus,a.list-group-item-warning:hover,button.list-group-item-warning:focus,button.list-group-item-warning:hover{color:#856404;background-color:#ffe8a1}a.list-group-item-warning.active,button.list-group-item-warning.active{color:#fff;background-color:#856404;border-color:#856404}.list-group-item-danger{color:#721c24;background-color:#f5c6cb}a.list-group-item-danger,button.list-group-item-danger{color:#721c24}a.list-group-item-danger:focus,a.list-group-item-danger:hover,button.list-group-item-danger:focus,button.list-group-item-danger:hover{color:#721c24;background-color:#f1b0b7}a.list-group-item-danger.active,button.list-group-item-danger.active{color:#fff;background-color:#721c24;border-color:#721c24}.list-group-item-light{color:#818182;background-color:#fdfdfe}a.list-group-item-light,button.list-group-item-light{color:#818182}a.list-group-item-light:focus,a.list-group-item-light:hover,button.list-group-item-light:focus,button.list-group-item-light:hover{color:#818182;background-color:#ececf6}a.list-group-item-light.active,button.list-group-item-light.active{color:#fff;background-color:#818182;border-color:#818182}.list-group-item-dark{color:#1b1e21;background-color:#c6c8ca}a.list-group-item-dark,button.list-group-item-dark{color:#1b1e21}a.list-group-item-dark:focus,a.list-group-item-dark:hover,button.list-group-item-dark:focus,button.list-group-item-dark:hover{color:#1b1e21;background-color:#b9bbbe}a.list-group-item-dark.active,button.list-group-item-dark.active{color:#fff;background-color:#1b1e21;border-color:#1b1e21}.close{float:right;font-size:1.5rem;font-weight:700;line-height:1;color:#000;text-shadow:0 1px 0 #fff;opacity:.5}.close:focus,.close:hover{color:#000;text-decoration:none;opacity:.75}button.close{padding:0;background:0 0;border:0;-webkit-appearance:none}.modal-open{overflow:hidden}.modal{position:fixed;top:0;right:0;bottom:0;left:0;z-index:1050;display:none;overflow:hidden;outline:0}.modal.fade .modal-dialog{transition:-webkit-transform .3s ease-out;transition:transform .3s ease-out;transition:transform .3s ease-out,-webkit-transform .3s ease-out;-webkit-transform:translate(0,-25%);transform:translate(0,-25%)}.modal.show .modal-dialog{-webkit-transform:translate(0,0);transform:translate(0,0)}.modal-open .modal{overflow-x:hidden;overflow-y:auto}.modal-dialog{position:relative;width:auto;margin:10px;pointer-events:none}.modal-content{position:relative;display:-ms-flexbox;display:flex;-ms-flex-direction:column;flex-direction:column;pointer-events:auto;background-color:#fff;background-clip:padding-box;border:1px solid rgba(0,0,0,.2);border-radius:.3rem;outline:0}.modal-backdrop{position:fixed;top:0;right:0;bottom:0;left:0;z-index:1040;background-color:#000}.modal-backdrop.fade{opacity:0}.modal-backdrop.show{opacity:.5}.modal-header{display:-ms-flexbox;display:flex;-ms-flex-align:start;align-items:flex-start;-ms-flex-pack:justify;justify-content:space-between;padding:15px;border-bottom:1px solid #e9ecef;border-top-left-radius:.3rem;border-top-right-radius:.3rem}.modal-header .close{padding:15px;margin:-15px -15px -15px auto}.modal-title{margin-bottom:0;line-height:1.5}.modal-body{position:relative;-ms-flex:1 1 auto;flex:1 1 auto;padding:15px}.modal-footer{display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center;-ms-flex-pack:end;justify-content:flex-end;padding:15px;border-top:1px solid #e9ecef}.modal-footer>:not(:first-child){margin-left:.25rem}.modal-footer>:not(:last-child){margin-right:.25rem}.modal-scrollbar-measure{position:absolute;top:-9999px;width:50px;height:50px;overflow:scroll}@media (min-width:576px){.modal-dialog{max-width:500px;margin:30px auto}.modal-sm{max-width:300px}}@media (min-width:992px){.modal-lg{max-width:800px}}.tooltip{position:absolute;z-index:1070;display:block;margin:0;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol";font-style:normal;font-weight:400;line-height:1.5;text-align:left;text-align:start;text-decoration:none;text-shadow:none;text-transform:none;letter-spacing:normal;word-break:normal;word-spacing:normal;white-space:normal;line-break:auto;font-size:.875rem;word-wrap:break-word;opacity:0}.tooltip.show{opacity:.9}.tooltip .arrow{position:absolute;display:block;width:5px;height:5px}.tooltip .arrow::before{position:absolute;border-color:transparent;border-style:solid}.tooltip.bs-tooltip-auto[x-placement^=top],.tooltip.bs-tooltip-top{padding:5px 0}.tooltip.bs-tooltip-auto[x-placement^=top] .arrow,.tooltip.bs-tooltip-top .arrow{bottom:0}.tooltip.bs-tooltip-auto[x-placement^=top] .arrow::before,.tooltip.bs-tooltip-top .arrow::before{margin-left:-3px;content:"";border-width:5px 5px 0;border-top-color:#000}.tooltip.bs-tooltip-auto[x-placement^=right],.tooltip.bs-tooltip-right{padding:0 5px}.tooltip.bs-tooltip-auto[x-placement^=right] .arrow,.tooltip.bs-tooltip-right .arrow{left:0}.tooltip.bs-tooltip-auto[x-placement^=right] .arrow::before,.tooltip.bs-tooltip-right .arrow::before{margin-top:-3px;content:"";border-width:5px 5px 5px 0;border-right-color:#000}.tooltip.bs-tooltip-auto[x-placement^=bottom],.tooltip.bs-tooltip-bottom{padding:5px 0}.tooltip.bs-tooltip-auto[x-placement^=bottom] .arrow,.tooltip.bs-tooltip-bottom .arrow{top:0}.tooltip.bs-tooltip-auto[x-placement^=bottom] .arrow::before,.tooltip.bs-tooltip-bottom .arrow::before{margin-left:-3px;content:"";border-width:0 5px 5px;border-bottom-color:#000}.tooltip.bs-tooltip-auto[x-placement^=left],.tooltip.bs-tooltip-left{padding:0 5px}.tooltip.bs-tooltip-auto[x-placement^=left] .arrow,.tooltip.bs-tooltip-left .arrow{right:0}.tooltip.bs-tooltip-auto[x-placement^=left] .arrow::before,.tooltip.bs-tooltip-left .arrow::before{right:0;margin-top:-3px;content:"";border-width:5px 0 5px 5px;border-left-color:#000}.tooltip-inner{max-width:200px;padding:3px 8px;color:#fff;text-align:center;background-color:#000;border-radius:.25rem}.popover{position:absolute;top:0;left:0;z-index:1060;display:block;max-width:276px;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol";font-style:normal;font-weight:400;line-height:1.5;text-align:left;text-align:start;text-decoration:none;text-shadow:none;text-transform:none;letter-spacing:normal;word-break:normal;word-spacing:normal;white-space:normal;line-break:auto;font-size:.875rem;word-wrap:break-word;background-color:#fff;background-clip:padding-box;border:1px solid rgba(0,0,0,.2);border-radius:.3rem}.popover .arrow{position:absolute;display:block;width:.8rem;height:.4rem}.popover .arrow::after,.popover .arrow::before{position:absolute;display:block;border-color:transparent;border-style:solid}.popover .arrow::before{content:"";border-width:.8rem}.popover .arrow::after{content:"";border-width:.8rem}.popover.bs-popover-auto[x-placement^=top],.popover.bs-popover-top{margin-bottom:.8rem}.popover.bs-popover-auto[x-placement^=top] .arrow,.popover.bs-popover-top .arrow{bottom:0}.popover.bs-popover-auto[x-placement^=top] .arrow::after,.popover.bs-popover-auto[x-placement^=top] .arrow::before,.popover.bs-popover-top .arrow::after,.popover.bs-popover-top .arrow::before{border-bottom-width:0}.popover.bs-popover-auto[x-placement^=top] .arrow::before,.popover.bs-popover-top .arrow::before{bottom:-.8rem;margin-left:-.8rem;border-top-color:rgba(0,0,0,.25)}.popover.bs-popover-auto[x-placement^=top] .arrow::after,.popover.bs-popover-top .arrow::after{bottom:calc((.8rem - 1px) * -1);margin-left:-.8rem;border-top-color:#fff}.popover.bs-popover-auto[x-placement^=right],.popover.bs-popover-right{margin-left:.8rem}.popover.bs-popover-auto[x-placement^=right] .arrow,.popover.bs-popover-right .arrow{left:0}.popover.bs-popover-auto[x-placement^=right] .arrow::after,.popover.bs-popover-auto[x-placement^=right] .arrow::before,.popover.bs-popover-right .arrow::after,.popover.bs-popover-right .arrow::before{margin-top:-.8rem;border-left-width:0}.popover.bs-popover-auto[x-placement^=right] .arrow::before,.popover.bs-popover-right .arrow::before{left:-.8rem;border-right-color:rgba(0,0,0,.25)}.popover.bs-popover-auto[x-placement^=right] .arrow::after,.popover.bs-popover-right .arrow::after{left:calc((.8rem - 1px) * -1);border-right-color:#fff}.popover.bs-popover-auto[x-placement^=bottom],.popover.bs-popover-bottom{margin-top:.8rem}.popover.bs-popover-auto[x-placement^=bottom] .arrow,.popover.bs-popover-bottom .arrow{top:0}.popover.bs-popover-auto[x-placement^=bottom] .arrow::after,.popover.bs-popover-auto[x-placement^=bottom] .arrow::before,.popover.bs-popover-bottom .arrow::after,.popover.bs-popover-bottom .arrow::before{margin-left:-.8rem;border-top-width:0}.popover.bs-popover-auto[x-placement^=bottom] .arrow::before,.popover.bs-popover-bottom .arrow::before{top:-.8rem;border-bottom-color:rgba(0,0,0,.25)}.popover.bs-popover-auto[x-placement^=bottom] .arrow::after,.popover.bs-popover-bottom .arrow::after{top:calc((.8rem - 1px) * -1);border-bottom-color:#fff}.popover.bs-popover-auto[x-placement^=bottom] .popover-header::before,.popover.bs-popover-bottom .popover-header::before{position:absolute;top:0;left:50%;display:block;width:20px;margin-left:-10px;content:"";border-bottom:1px solid #f7f7f7}.popover.bs-popover-auto[x-placement^=left],.popover.bs-popover-left{margin-right:.8rem}.popover.bs-popover-auto[x-placement^=left] .arrow,.popover.bs-popover-left .arrow{right:0}.popover.bs-popover-auto[x-placement^=left] .arrow::after,.popover.bs-popover-auto[x-placement^=left] .arrow::before,.popover.bs-popover-left .arrow::after,.popover.bs-popover-left .arrow::before{margin-top:-.8rem;border-right-width:0}.popover.bs-popover-auto[x-placement^=left] .arrow::before,.popover.bs-popover-left .arrow::before{right:-.8rem;border-left-color:rgba(0,0,0,.25)}.popover.bs-popover-auto[x-placement^=left] .arrow::after,.popover.bs-popover-left .arrow::after{right:calc((.8rem - 1px) * -1);border-left-color:#fff}.popover-header{padding:.5rem .75rem;margin-bottom:0;font-size:1rem;color:inherit;background-color:#f7f7f7;border-bottom:1px solid #ebebeb;border-top-left-radius:calc(.3rem - 1px);border-top-right-radius:calc(.3rem - 1px)}.popover-header:empty{display:none}.popover-body{padding:.5rem .75rem;color:#212529}.carousel{position:relative}.carousel-inner{position:relative;width:100%;overflow:hidden}.carousel-item{position:relative;display:none;-ms-flex-align:center;align-items:center;width:100%;transition:-webkit-transform .6s ease;transition:transform .6s ease;transition:transform .6s ease,-webkit-transform .6s ease;-webkit-backface-visibility:hidden;backface-visibility:hidden;-webkit-perspective:1000px;perspective:1000px}.carousel-item-next,.carousel-item-prev,.carousel-item.active{display:block}.carousel-item-next,.carousel-item-prev{position:absolute;top:0}.carousel-item-next.carousel-item-left,.carousel-item-prev.carousel-item-right{-webkit-transform:translateX(0);transform:translateX(0)}@supports ((-webkit-transform-style:preserve-3d) or (transform-style:preserve-3d)){.carousel-item-next.carousel-item-left,.carousel-item-prev.carousel-item-right{-webkit-transform:translate3d(0,0,0);transform:translate3d(0,0,0)}}.active.carousel-item-right,.carousel-item-next{-webkit-transform:translateX(100%);transform:translateX(100%)}@supports ((-webkit-transform-style:preserve-3d) or (transform-style:preserve-3d)){.active.carousel-item-right,.carousel-item-next{-webkit-transform:translate3d(100%,0,0);transform:translate3d(100%,0,0)}}.active.carousel-item-left,.carousel-item-prev{-webkit-transform:translateX(-100%);transform:translateX(-100%)}@supports ((-webkit-transform-style:preserve-3d) or (transform-style:preserve-3d)){.active.carousel-item-left,.carousel-item-prev{-webkit-transform:translate3d(-100%,0,0);transform:translate3d(-100%,0,0)}}.carousel-control-next,.carousel-control-prev{position:absolute;top:0;bottom:0;display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center;-ms-flex-pack:center;justify-content:center;width:15%;color:#fff;text-align:center;opacity:.5}.carousel-control-next:focus,.carousel-control-next:hover,.carousel-control-prev:focus,.carousel-control-prev:hover{color:#fff;text-decoration:none;outline:0;opacity:.9}.carousel-control-prev{left:0}.carousel-control-next{right:0}.carousel-control-next-icon,.carousel-control-prev-icon{display:inline-block;width:20px;height:20px;background:transparent no-repeat center center;background-size:100% 100%}.carousel-control-prev-icon{background-image:url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='%23fff' viewBox='0 0 8 8'%3E%3Cpath d='M5.25 0l-4 4 4 4 1.5-1.5-2.5-2.5 2.5-2.5-1.5-1.5z'/%3E%3C/svg%3E")}.carousel-control-next-icon{background-image:url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='%23fff' viewBox='0 0 8 8'%3E%3Cpath d='M2.75 0l-1.5 1.5 2.5 2.5-2.5 2.5 1.5 1.5 4-4-4-4z'/%3E%3C/svg%3E")}.carousel-indicators{position:absolute;right:0;bottom:10px;left:0;z-index:15;display:-ms-flexbox;display:flex;-ms-flex-pack:center;justify-content:center;padding-left:0;margin-right:15%;margin-left:15%;list-style:none}.carousel-indicators li{position:relative;-ms-flex:0 1 auto;flex:0 1 auto;width:30px;height:3px;margin-right:3px;margin-left:3px;text-indent:-999px;background-color:rgba(255,255,255,.5)}.carousel-indicators li::before{position:absolute;top:-10px;left:0;display:inline-block;width:100%;height:10px;content:""}.carousel-indicators li::after{position:absolute;bottom:-10px;left:0;display:inline-block;width:100%;height:10px;content:""}.carousel-indicators .active{background-color:#fff}.carousel-caption{position:absolute;right:15%;bottom:20px;left:15%;z-index:10;padding-top:20px;padding-bottom:20px;color:#fff;text-align:center}.align-baseline{vertical-align:baseline!important}.align-top{vertical-align:top!important}.align-middle{vertical-align:middle!important}.align-bottom{vertical-align:bottom!important}.align-text-bottom{vertical-align:text-bottom!important}.align-text-top{vertical-align:text-top!important}.bg-primary{background-color:#007bff!important}a.bg-primary:focus,a.bg-primary:hover{background-color:#0062cc!important}.bg-secondary{background-color:#868e96!important}a.bg-secondary:focus,a.bg-secondary:hover{background-color:#6c757d!important}.bg-success{background-color:#28a745!important}a.bg-success:focus,a.bg-success:hover{background-color:#1e7e34!important}.bg-info{background-color:#17a2b8!important}a.bg-info:focus,a.bg-info:hover{background-color:#117a8b!important}.bg-warning{background-color:#ffc107!important}a.bg-warning:focus,a.bg-warning:hover{background-color:#d39e00!important}.bg-danger{background-color:#dc3545!important}a.bg-danger:focus,a.bg-danger:hover{background-color:#bd2130!important}.bg-light{background-color:#f8f9fa!important}a.bg-light:focus,a.bg-light:hover{background-color:#dae0e5!important}.bg-dark{background-color:#343a40!important}a.bg-dark:focus,a.bg-dark:hover{background-color:#1d2124!important}.bg-white{background-color:#fff!important}.bg-transparent{background-color:transparent!important}.border{border:1px solid #e9ecef!important}.border-0{border:0!important}.border-top-0{border-top:0!important}.border-right-0{border-right:0!important}.border-bottom-0{border-bottom:0!important}.border-left-0{border-left:0!important}.border-primary{border-color:#007bff!important}.border-secondary{border-color:#868e96!important}.border-success{border-color:#28a745!important}.border-info{border-color:#17a2b8!important}.border-warning{border-color:#ffc107!important}.border-danger{border-color:#dc3545!important}.border-light{border-color:#f8f9fa!important}.border-dark{border-color:#343a40!important}.border-white{border-color:#fff!important}.rounded{border-radius:.25rem!important}.rounded-top{border-top-left-radius:.25rem!important;border-top-right-radius:.25rem!important}.rounded-right{border-top-right-radius:.25rem!important;border-bottom-right-radius:.25rem!important}.rounded-bottom{border-bottom-right-radius:.25rem!important;border-bottom-left-radius:.25rem!important}.rounded-left{border-top-left-radius:.25rem!important;border-bottom-left-radius:.25rem!important}.rounded-circle{border-radius:50%!important}.rounded-0{border-radius:0!important}.clearfix::after{display:block;clear:both;content:""}.d-none{display:none!important}.d-inline{display:inline!important}.d-inline-block{display:inline-block!important}.d-block{display:block!important}.d-table{display:table!important}.d-table-row{display:table-row!important}.d-table-cell{display:table-cell!important}.d-flex{display:-ms-flexbox!important;display:flex!important}.d-inline-flex{display:-ms-inline-flexbox!important;display:inline-flex!important}@media (min-width:576px){.d-sm-none{display:none!important}.d-sm-inline{display:inline!important}.d-sm-inline-block{display:inline-block!important}.d-sm-block{display:block!important}.d-sm-table{display:table!important}.d-sm-table-row{display:table-row!important}.d-sm-table-cell{display:table-cell!important}.d-sm-flex{display:-ms-flexbox!important;display:flex!important}.d-sm-inline-flex{display:-ms-inline-flexbox!important;display:inline-flex!important}}@media (min-width:768px){.d-md-none{display:none!important}.d-md-inline{display:inline!important}.d-md-inline-block{display:inline-block!important}.d-md-block{display:block!important}.d-md-table{display:table!important}.d-md-table-row{display:table-row!important}.d-md-table-cell{display:table-cell!important}.d-md-flex{display:-ms-flexbox!important;display:flex!important}.d-md-inline-flex{display:-ms-inline-flexbox!important;display:inline-flex!important}}@media (min-width:992px){.d-lg-none{display:none!important}.d-lg-inline{display:inline!important}.d-lg-inline-block{display:inline-block!important}.d-lg-block{display:block!important}.d-lg-table{display:table!important}.d-lg-table-row{display:table-row!important}.d-lg-table-cell{display:table-cell!important}.d-lg-flex{display:-ms-flexbox!important;display:flex!important}.d-lg-inline-flex{display:-ms-inline-flexbox!important;display:inline-flex!important}}@media (min-width:1200px){.d-xl-none{display:none!important}.d-xl-inline{display:inline!important}.d-xl-inline-block{display:inline-block!important}.d-xl-block{display:block!important}.d-xl-table{display:table!important}.d-xl-table-row{display:table-row!important}.d-xl-table-cell{display:table-cell!important}.d-xl-flex{display:-ms-flexbox!important;display:flex!important}.d-xl-inline-flex{display:-ms-inline-flexbox!important;display:inline-flex!important}}.d-print-block{display:none!important}@media print{.d-print-block{display:block!important}}.d-print-inline{display:none!important}@media print{.d-print-inline{display:inline!important}}.d-print-inline-block{display:none!important}@media print{.d-print-inline-block{display:inline-block!important}}@media print{.d-print-none{display:none!important}}.embed-responsive{position:relative;display:block;width:100%;padding:0;overflow:hidden}.embed-responsive::before{display:block;content:""}.embed-responsive .embed-responsive-item,.embed-responsive embed,.embed-responsive iframe,.embed-responsive object,.embed-responsive video{position:absolute;top:0;bottom:0;left:0;width:100%;height:100%;border:0}.embed-responsive-21by9::before{padding-top:42.857143%}.embed-responsive-16by9::before{padding-top:56.25%}.embed-responsive-4by3::before{padding-top:75%}.embed-responsive-1by1::before{padding-top:100%}.flex-row{-ms-flex-direction:row!important;flex-direction:row!important}.flex-column{-ms-flex-direction:column!important;flex-direction:column!important}.flex-row-reverse{-ms-flex-direction:row-reverse!important;flex-direction:row-reverse!important}.flex-column-reverse{-ms-flex-direction:column-reverse!important;flex-direction:column-reverse!important}.flex-wrap{-ms-flex-wrap:wrap!important;flex-wrap:wrap!important}.flex-nowrap{-ms-flex-wrap:nowrap!important;flex-wrap:nowrap!important}.flex-wrap-reverse{-ms-flex-wrap:wrap-reverse!important;flex-wrap:wrap-reverse!important}.justify-content-start{-ms-flex-pack:start!important;justify-content:flex-start!important}.justify-content-end{-ms-flex-pack:end!important;justify-content:flex-end!important}.justify-content-center{-ms-flex-pack:center!important;justify-content:center!important}.justify-content-between{-ms-flex-pack:justify!important;justify-content:space-between!important}.justify-content-around{-ms-flex-pack:distribute!important;justify-content:space-around!important}.align-items-start{-ms-flex-align:start!important;align-items:flex-start!important}.align-items-end{-ms-flex-align:end!important;align-items:flex-end!important}.align-items-center{-ms-flex-align:center!important;align-items:center!important}.align-items-baseline{-ms-flex-align:baseline!important;align-items:baseline!important}.align-items-stretch{-ms-flex-align:stretch!important;align-items:stretch!important}.align-content-start{-ms-flex-line-pack:start!important;align-content:flex-start!important}.align-content-end{-ms-flex-line-pack:end!important;align-content:flex-end!important}.align-content-center{-ms-flex-line-pack:center!important;align-content:center!important}.align-content-between{-ms-flex-line-pack:justify!important;align-content:space-between!important}.align-content-around{-ms-flex-line-pack:distribute!important;align-content:space-around!important}.align-content-stretch{-ms-flex-line-pack:stretch!important;align-content:stretch!important}.align-self-auto{-ms-flex-item-align:auto!important;align-self:auto!important}.align-self-start{-ms-flex-item-align:start!important;align-self:flex-start!important}.align-self-end{-ms-flex-item-align:end!important;align-self:flex-end!important}.align-self-center{-ms-flex-item-align:center!important;align-self:center!important}.align-self-baseline{-ms-flex-item-align:baseline!important;align-self:baseline!important}.align-self-stretch{-ms-flex-item-align:stretch!important;align-self:stretch!important}@media (min-width:576px){.flex-sm-row{-ms-flex-direction:row!important;flex-direction:row!important}.flex-sm-column{-ms-flex-direction:column!important;flex-direction:column!important}.flex-sm-row-reverse{-ms-flex-direction:row-reverse!important;flex-direction:row-reverse!important}.flex-sm-column-reverse{-ms-flex-direction:column-reverse!important;flex-direction:column-reverse!important}.flex-sm-wrap{-ms-flex-wrap:wrap!important;flex-wrap:wrap!important}.flex-sm-nowrap{-ms-flex-wrap:nowrap!important;flex-wrap:nowrap!important}.flex-sm-wrap-reverse{-ms-flex-wrap:wrap-reverse!important;flex-wrap:wrap-reverse!important}.justify-content-sm-start{-ms-flex-pack:start!important;justify-content:flex-start!important}.justify-content-sm-end{-ms-flex-pack:end!important;justify-content:flex-end!important}.justify-content-sm-center{-ms-flex-pack:center!important;justify-content:center!important}.justify-content-sm-between{-ms-flex-pack:justify!important;justify-content:space-between!important}.justify-content-sm-around{-ms-flex-pack:distribute!important;justify-content:space-around!important}.align-items-sm-start{-ms-flex-align:start!important;align-items:flex-start!important}.align-items-sm-end{-ms-flex-align:end!important;align-items:flex-end!important}.align-items-sm-center{-ms-flex-align:center!important;align-items:center!important}.align-items-sm-baseline{-ms-flex-align:baseline!important;align-items:baseline!important}.align-items-sm-stretch{-ms-flex-align:stretch!important;align-items:stretch!important}.align-content-sm-start{-ms-flex-line-pack:start!important;align-content:flex-start!important}.align-content-sm-end{-ms-flex-line-pack:end!important;align-content:flex-end!important}.align-content-sm-center{-ms-flex-line-pack:center!important;align-content:center!important}.align-content-sm-between{-ms-flex-line-pack:justify!important;align-content:space-between!important}.align-content-sm-around{-ms-flex-line-pack:distribute!important;align-content:space-around!important}.align-content-sm-stretch{-ms-flex-line-pack:stretch!important;align-content:stretch!important}.align-self-sm-auto{-ms-flex-item-align:auto!important;align-self:auto!important}.align-self-sm-start{-ms-flex-item-align:start!important;align-self:flex-start!important}.align-self-sm-end{-ms-flex-item-align:end!important;align-self:flex-end!important}.align-self-sm-center{-ms-flex-item-align:center!important;align-self:center!important}.align-self-sm-baseline{-ms-flex-item-align:baseline!important;align-self:baseline!important}.align-self-sm-stretch{-ms-flex-item-align:stretch!important;align-self:stretch!important}}@media (min-width:768px){.flex-md-row{-ms-flex-direction:row!important;flex-direction:row!important}.flex-md-column{-ms-flex-direction:column!important;flex-direction:column!important}.flex-md-row-reverse{-ms-flex-direction:row-reverse!important;flex-direction:row-reverse!important}.flex-md-column-reverse{-ms-flex-direction:column-reverse!important;flex-direction:column-reverse!important}.flex-md-wrap{-ms-flex-wrap:wrap!important;flex-wrap:wrap!important}.flex-md-nowrap{-ms-flex-wrap:nowrap!important;flex-wrap:nowrap!important}.flex-md-wrap-reverse{-ms-flex-wrap:wrap-reverse!important;flex-wrap:wrap-reverse!important}.justify-content-md-start{-ms-flex-pack:start!important;justify-content:flex-start!important}.justify-content-md-end{-ms-flex-pack:end!important;justify-content:flex-end!important}.justify-content-md-center{-ms-flex-pack:center!important;justify-content:center!important}.justify-content-md-between{-ms-flex-pack:justify!important;justify-content:space-between!important}.justify-content-md-around{-ms-flex-pack:distribute!important;justify-content:space-around!important}.align-items-md-start{-ms-flex-align:start!important;align-items:flex-start!important}.align-items-md-end{-ms-flex-align:end!important;align-items:flex-end!important}.align-items-md-center{-ms-flex-align:center!important;align-items:center!important}.align-items-md-baseline{-ms-flex-align:baseline!important;align-items:baseline!important}.align-items-md-stretch{-ms-flex-align:stretch!important;align-items:stretch!important}.align-content-md-start{-ms-flex-line-pack:start!important;align-content:flex-start!important}.align-content-md-end{-ms-flex-line-pack:end!important;align-content:flex-end!important}.align-content-md-center{-ms-flex-line-pack:center!important;align-content:center!important}.align-content-md-between{-ms-flex-line-pack:justify!important;align-content:space-between!important}.align-content-md-around{-ms-flex-line-pack:distribute!important;align-content:space-around!important}.align-content-md-stretch{-ms-flex-line-pack:stretch!important;align-content:stretch!important}.align-self-md-auto{-ms-flex-item-align:auto!important;align-self:auto!important}.align-self-md-start{-ms-flex-item-align:start!important;align-self:flex-start!important}.align-self-md-end{-ms-flex-item-align:end!important;align-self:flex-end!important}.align-self-md-center{-ms-flex-item-align:center!important;align-self:center!important}.align-self-md-baseline{-ms-flex-item-align:baseline!important;align-self:baseline!important}.align-self-md-stretch{-ms-flex-item-align:stretch!important;align-self:stretch!important}}@media (min-width:992px){.flex-lg-row{-ms-flex-direction:row!important;flex-direction:row!important}.flex-lg-column{-ms-flex-direction:column!important;flex-direction:column!important}.flex-lg-row-reverse{-ms-flex-direction:row-reverse!important;flex-direction:row-reverse!important}.flex-lg-column-reverse{-ms-flex-direction:column-reverse!important;flex-direction:column-reverse!important}.flex-lg-wrap{-ms-flex-wrap:wrap!important;flex-wrap:wrap!important}.flex-lg-nowrap{-ms-flex-wrap:nowrap!important;flex-wrap:nowrap!important}.flex-lg-wrap-reverse{-ms-flex-wrap:wrap-reverse!important;flex-wrap:wrap-reverse!important}.justify-content-lg-start{-ms-flex-pack:start!important;justify-content:flex-start!important}.justify-content-lg-end{-ms-flex-pack:end!important;justify-content:flex-end!important}.justify-content-lg-center{-ms-flex-pack:center!important;justify-content:center!important}.justify-content-lg-between{-ms-flex-pack:justify!important;justify-content:space-between!important}.justify-content-lg-around{-ms-flex-pack:distribute!important;justify-content:space-around!important}.align-items-lg-start{-ms-flex-align:start!important;align-items:flex-start!important}.align-items-lg-end{-ms-flex-align:end!important;align-items:flex-end!important}.align-items-lg-center{-ms-flex-align:center!important;align-items:center!important}.align-items-lg-baseline{-ms-flex-align:baseline!important;align-items:baseline!important}.align-items-lg-stretch{-ms-flex-align:stretch!important;align-items:stretch!important}.align-content-lg-start{-ms-flex-line-pack:start!important;align-content:flex-start!important}.align-content-lg-end{-ms-flex-line-pack:end!important;align-content:flex-end!important}.align-content-lg-center{-ms-flex-line-pack:center!important;align-content:center!important}.align-content-lg-between{-ms-flex-line-pack:justify!important;align-content:space-between!important}.align-content-lg-around{-ms-flex-line-pack:distribute!important;align-content:space-around!important}.align-content-lg-stretch{-ms-flex-line-pack:stretch!important;align-content:stretch!important}.align-self-lg-auto{-ms-flex-item-align:auto!important;align-self:auto!important}.align-self-lg-start{-ms-flex-item-align:start!important;align-self:flex-start!important}.align-self-lg-end{-ms-flex-item-align:end!important;align-self:flex-end!important}.align-self-lg-center{-ms-flex-item-align:center!important;align-self:center!important}.align-self-lg-baseline{-ms-flex-item-align:baseline!important;align-self:baseline!important}.align-self-lg-stretch{-ms-flex-item-align:stretch!important;align-self:stretch!important}}@media (min-width:1200px){.flex-xl-row{-ms-flex-direction:row!important;flex-direction:row!important}.flex-xl-column{-ms-flex-direction:column!important;flex-direction:column!important}.flex-xl-row-reverse{-ms-flex-direction:row-reverse!important;flex-direction:row-reverse!important}.flex-xl-column-reverse{-ms-flex-direction:column-reverse!important;flex-direction:column-reverse!important}.flex-xl-wrap{-ms-flex-wrap:wrap!important;flex-wrap:wrap!important}.flex-xl-nowrap{-ms-flex-wrap:nowrap!important;flex-wrap:nowrap!important}.flex-xl-wrap-reverse{-ms-flex-wrap:wrap-reverse!important;flex-wrap:wrap-reverse!important}.justify-content-xl-start{-ms-flex-pack:start!important;justify-content:flex-start!important}.justify-content-xl-end{-ms-flex-pack:end!important;justify-content:flex-end!important}.justify-content-xl-center{-ms-flex-pack:center!important;justify-content:center!important}.justify-content-xl-between{-ms-flex-pack:justify!important;justify-content:space-between!important}.justify-content-xl-around{-ms-flex-pack:distribute!important;justify-content:space-around!important}.align-items-xl-start{-ms-flex-align:start!important;align-items:flex-start!important}.align-items-xl-end{-ms-flex-align:end!important;align-items:flex-end!important}.align-items-xl-center{-ms-flex-align:center!important;align-items:center!important}.align-items-xl-baseline{-ms-flex-align:baseline!important;align-items:baseline!important}.align-items-xl-stretch{-ms-flex-align:stretch!important;align-items:stretch!important}.align-content-xl-start{-ms-flex-line-pack:start!important;align-content:flex-start!important}.align-content-xl-end{-ms-flex-line-pack:end!important;align-content:flex-end!important}.align-content-xl-center{-ms-flex-line-pack:center!important;align-content:center!important}.align-content-xl-between{-ms-flex-line-pack:justify!important;align-content:space-between!important}.align-content-xl-around{-ms-flex-line-pack:distribute!important;align-content:space-around!important}.align-content-xl-stretch{-ms-flex-line-pack:stretch!important;align-content:stretch!important}.align-self-xl-auto{-ms-flex-item-align:auto!important;align-self:auto!important}.align-self-xl-start{-ms-flex-item-align:start!important;align-self:flex-start!important}.align-self-xl-end{-ms-flex-item-align:end!important;align-self:flex-end!important}.align-self-xl-center{-ms-flex-item-align:center!important;align-self:center!important}.align-self-xl-baseline{-ms-flex-item-align:baseline!important;align-self:baseline!important}.align-self-xl-stretch{-ms-flex-item-align:stretch!important;align-self:stretch!important}}.float-left{float:left!important}.float-right{float:right!important}.float-none{float:none!important}@media (min-width:576px){.float-sm-left{float:left!important}.float-sm-right{float:right!important}.float-sm-none{float:none!important}}@media (min-width:768px){.float-md-left{float:left!important}.float-md-right{float:right!important}.float-md-none{float:none!important}}@media (min-width:992px){.float-lg-left{float:left!important}.float-lg-right{float:right!important}.float-lg-none{float:none!important}}@media (min-width:1200px){.float-xl-left{float:left!important}.float-xl-right{float:right!important}.float-xl-none{float:none!important}}.position-static{position:static!important}.position-relative{position:relative!important}.position-absolute{position:absolute!important}.position-fixed{position:fixed!important}.position-sticky{position:-webkit-sticky!important;position:sticky!important}.fixed-top{position:fixed;top:0;right:0;left:0;z-index:1030}.fixed-bottom{position:fixed;right:0;bottom:0;left:0;z-index:1030}@supports ((position:-webkit-sticky) or (position:sticky)){.sticky-top{position:-webkit-sticky;position:sticky;top:0;z-index:1020}}.sr-only{position:absolute;width:1px;height:1px;padding:0;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;-webkit-clip-path:inset(50%);clip-path:inset(50%);border:0}.sr-only-focusable:active,.sr-only-focusable:focus{position:static;width:auto;height:auto;overflow:visible;clip:auto;white-space:normal;-webkit-clip-path:none;clip-path:none}.w-25{width:25%!important}.w-50{width:50%!important}.w-75{width:75%!important}.w-100{width:100%!important}.h-25{height:25%!important}.h-50{height:50%!important}.h-75{height:75%!important}.h-100{height:100%!important}.mw-100{max-width:100%!important}.mh-100{max-height:100%!important}.m-0{margin:0!important}.mt-0,.my-0{margin-top:0!important}.mr-0,.mx-0{margin-right:0!important}.mb-0,.my-0{margin-bottom:0!important}.ml-0,.mx-0{margin-left:0!important}.m-1{margin:.25rem!important}.mt-1,.my-1{margin-top:.25rem!important}.mr-1,.mx-1{margin-right:.25rem!important}.mb-1,.my-1{margin-bottom:.25rem!important}.ml-1,.mx-1{margin-left:.25rem!important}.m-2{margin:.5rem!important}.mt-2,.my-2{margin-top:.5rem!important}.mr-2,.mx-2{margin-right:.5rem!important}.mb-2,.my-2{margin-bottom:.5rem!important}.ml-2,.mx-2{margin-left:.5rem!important}.m-3{margin:1rem!important}.mt-3,.my-3{margin-top:1rem!important}.mr-3,.mx-3{margin-right:1rem!important}.mb-3,.my-3{margin-bottom:1rem!important}.ml-3,.mx-3{margin-left:1rem!important}.m-4{margin:1.5rem!important}.mt-4,.my-4{margin-top:1.5rem!important}.mr-4,.mx-4{margin-right:1.5rem!important}.mb-4,.my-4{margin-bottom:1.5rem!important}.ml-4,.mx-4{margin-left:1.5rem!important}.m-5{margin:3rem!important}.mt-5,.my-5{margin-top:3rem!important}.mr-5,.mx-5{margin-right:3rem!important}.mb-5,.my-5{margin-bottom:3rem!important}.ml-5,.mx-5{margin-left:3rem!important}.p-0{padding:0!important}.pt-0,.py-0{padding-top:0!important}.pr-0,.px-0{padding-right:0!important}.pb-0,.py-0{padding-bottom:0!important}.pl-0,.px-0{padding-left:0!important}.p-1{padding:.25rem!important}.pt-1,.py-1{padding-top:.25rem!important}.pr-1,.px-1{padding-right:.25rem!important}.pb-1,.py-1{padding-bottom:.25rem!important}.pl-1,.px-1{padding-left:.25rem!important}.p-2{padding:.5rem!important}.pt-2,.py-2{padding-top:.5rem!important}.pr-2,.px-2{padding-right:.5rem!important}.pb-2,.py-2{padding-bottom:.5rem!important}.pl-2,.px-2{padding-left:.5rem!important}.p-3{padding:1rem!important}.pt-3,.py-3{padding-top:1rem!important}.pr-3,.px-3{padding-right:1rem!important}.pb-3,.py-3{padding-bottom:1rem!important}.pl-3,.px-3{padding-left:1rem!important}.p-4{padding:1.5rem!important}.pt-4,.py-4{padding-top:1.5rem!important}.pr-4,.px-4{padding-right:1.5rem!important}.pb-4,.py-4{padding-bottom:1.5rem!important}.pl-4,.px-4{padding-left:1.5rem!important}.p-5{padding:3rem!important}.pt-5,.py-5{padding-top:3rem!important}.pr-5,.px-5{padding-right:3rem!important}.pb-5,.py-5{padding-bottom:3rem!important}.pl-5,.px-5{padding-left:3rem!important}.m-auto{margin:auto!important}.mt-auto,.my-auto{margin-top:auto!important}.mr-auto,.mx-auto{margin-right:auto!important}.mb-auto,.my-auto{margin-bottom:auto!important}.ml-auto,.mx-auto{margin-left:auto!important}@media (min-width:576px){.m-sm-0{margin:0!important}.mt-sm-0,.my-sm-0{margin-top:0!important}.mr-sm-0,.mx-sm-0{margin-right:0!important}.mb-sm-0,.my-sm-0{margin-bottom:0!important}.ml-sm-0,.mx-sm-0{margin-left:0!important}.m-sm-1{margin:.25rem!important}.mt-sm-1,.my-sm-1{margin-top:.25rem!important}.mr-sm-1,.mx-sm-1{margin-right:.25rem!important}.mb-sm-1,.my-sm-1{margin-bottom:.25rem!important}.ml-sm-1,.mx-sm-1{margin-left:.25rem!important}.m-sm-2{margin:.5rem!important}.mt-sm-2,.my-sm-2{margin-top:.5rem!important}.mr-sm-2,.mx-sm-2{margin-right:.5rem!important}.mb-sm-2,.my-sm-2{margin-bottom:.5rem!important}.ml-sm-2,.mx-sm-2{margin-left:.5rem!important}.m-sm-3{margin:1rem!important}.mt-sm-3,.my-sm-3{margin-top:1rem!important}.mr-sm-3,.mx-sm-3{margin-right:1rem!important}.mb-sm-3,.my-sm-3{margin-bottom:1rem!important}.ml-sm-3,.mx-sm-3{margin-left:1rem!important}.m-sm-4{margin:1.5rem!important}.mt-sm-4,.my-sm-4{margin-top:1.5rem!important}.mr-sm-4,.mx-sm-4{margin-right:1.5rem!important}.mb-sm-4,.my-sm-4{margin-bottom:1.5rem!important}.ml-sm-4,.mx-sm-4{margin-left:1.5rem!important}.m-sm-5{margin:3rem!important}.mt-sm-5,.my-sm-5{margin-top:3rem!important}.mr-sm-5,.mx-sm-5{margin-right:3rem!important}.mb-sm-5,.my-sm-5{margin-bottom:3rem!important}.ml-sm-5,.mx-sm-5{margin-left:3rem!important}.p-sm-0{padding:0!important}.pt-sm-0,.py-sm-0{padding-top:0!important}.pr-sm-0,.px-sm-0{padding-right:0!important}.pb-sm-0,.py-sm-0{padding-bottom:0!important}.pl-sm-0,.px-sm-0{padding-left:0!important}.p-sm-1{padding:.25rem!important}.pt-sm-1,.py-sm-1{padding-top:.25rem!important}.pr-sm-1,.px-sm-1{padding-right:.25rem!important}.pb-sm-1,.py-sm-1{padding-bottom:.25rem!important}.pl-sm-1,.px-sm-1{padding-left:.25rem!important}.p-sm-2{padding:.5rem!important}.pt-sm-2,.py-sm-2{padding-top:.5rem!important}.pr-sm-2,.px-sm-2{padding-right:.5rem!important}.pb-sm-2,.py-sm-2{padding-bottom:.5rem!important}.pl-sm-2,.px-sm-2{padding-left:.5rem!important}.p-sm-3{padding:1rem!important}.pt-sm-3,.py-sm-3{padding-top:1rem!important}.pr-sm-3,.px-sm-3{padding-right:1rem!important}.pb-sm-3,.py-sm-3{padding-bottom:1rem!important}.pl-sm-3,.px-sm-3{padding-left:1rem!important}.p-sm-4{padding:1.5rem!important}.pt-sm-4,.py-sm-4{padding-top:1.5rem!important}.pr-sm-4,.px-sm-4{padding-right:1.5rem!important}.pb-sm-4,.py-sm-4{padding-bottom:1.5rem!important}.pl-sm-4,.px-sm-4{padding-left:1.5rem!important}.p-sm-5{padding:3rem!important}.pt-sm-5,.py-sm-5{padding-top:3rem!important}.pr-sm-5,.px-sm-5{padding-right:3rem!important}.pb-sm-5,.py-sm-5{padding-bottom:3rem!important}.pl-sm-5,.px-sm-5{padding-left:3rem!important}.m-sm-auto{margin:auto!important}.mt-sm-auto,.my-sm-auto{margin-top:auto!important}.mr-sm-auto,.mx-sm-auto{margin-right:auto!important}.mb-sm-auto,.my-sm-auto{margin-bottom:auto!important}.ml-sm-auto,.mx-sm-auto{margin-left:auto!important}}@media (min-width:768px){.m-md-0{margin:0!important}.mt-md-0,.my-md-0{margin-top:0!important}.mr-md-0,.mx-md-0{margin-right:0!important}.mb-md-0,.my-md-0{margin-bottom:0!important}.ml-md-0,.mx-md-0{margin-left:0!important}.m-md-1{margin:.25rem!important}.mt-md-1,.my-md-1{margin-top:.25rem!important}.mr-md-1,.mx-md-1{margin-right:.25rem!important}.mb-md-1,.my-md-1{margin-bottom:.25rem!important}.ml-md-1,.mx-md-1{margin-left:.25rem!important}.m-md-2{margin:.5rem!important}.mt-md-2,.my-md-2{margin-top:.5rem!important}.mr-md-2,.mx-md-2{margin-right:.5rem!important}.mb-md-2,.my-md-2{margin-bottom:.5rem!important}.ml-md-2,.mx-md-2{margin-left:.5rem!important}.m-md-3{margin:1rem!important}.mt-md-3,.my-md-3{margin-top:1rem!important}.mr-md-3,.mx-md-3{margin-right:1rem!important}.mb-md-3,.my-md-3{margin-bottom:1rem!important}.ml-md-3,.mx-md-3{margin-left:1rem!important}.m-md-4{margin:1.5rem!important}.mt-md-4,.my-md-4{margin-top:1.5rem!important}.mr-md-4,.mx-md-4{margin-right:1.5rem!important}.mb-md-4,.my-md-4{margin-bottom:1.5rem!important}.ml-md-4,.mx-md-4{margin-left:1.5rem!important}.m-md-5{margin:3rem!important}.mt-md-5,.my-md-5{margin-top:3rem!important}.mr-md-5,.mx-md-5{margin-right:3rem!important}.mb-md-5,.my-md-5{margin-bottom:3rem!important}.ml-md-5,.mx-md-5{margin-left:3rem!important}.p-md-0{padding:0!important}.pt-md-0,.py-md-0{padding-top:0!important}.pr-md-0,.px-md-0{padding-right:0!important}.pb-md-0,.py-md-0{padding-bottom:0!important}.pl-md-0,.px-md-0{padding-left:0!important}.p-md-1{padding:.25rem!important}.pt-md-1,.py-md-1{padding-top:.25rem!important}.pr-md-1,.px-md-1{padding-right:.25rem!important}.pb-md-1,.py-md-1{padding-bottom:.25rem!important}.pl-md-1,.px-md-1{padding-left:.25rem!important}.p-md-2{padding:.5rem!important}.pt-md-2,.py-md-2{padding-top:.5rem!important}.pr-md-2,.px-md-2{padding-right:.5rem!important}.pb-md-2,.py-md-2{padding-bottom:.5rem!important}.pl-md-2,.px-md-2{padding-left:.5rem!important}.p-md-3{padding:1rem!important}.pt-md-3,.py-md-3{padding-top:1rem!important}.pr-md-3,.px-md-3{padding-right:1rem!important}.pb-md-3,.py-md-3{padding-bottom:1rem!important}.pl-md-3,.px-md-3{padding-left:1rem!important}.p-md-4{padding:1.5rem!important}.pt-md-4,.py-md-4{padding-top:1.5rem!important}.pr-md-4,.px-md-4{padding-right:1.5rem!important}.pb-md-4,.py-md-4{padding-bottom:1.5rem!important}.pl-md-4,.px-md-4{padding-left:1.5rem!important}.p-md-5{padding:3rem!important}.pt-md-5,.py-md-5{padding-top:3rem!important}.pr-md-5,.px-md-5{padding-right:3rem!important}.pb-md-5,.py-md-5{padding-bottom:3rem!important}.pl-md-5,.px-md-5{padding-left:3rem!important}.m-md-auto{margin:auto!important}.mt-md-auto,.my-md-auto{margin-top:auto!important}.mr-md-auto,.mx-md-auto{margin-right:auto!important}.mb-md-auto,.my-md-auto{margin-bottom:auto!important}.ml-md-auto,.mx-md-auto{margin-left:auto!important}}@media (min-width:992px){.m-lg-0{margin:0!important}.mt-lg-0,.my-lg-0{margin-top:0!important}.mr-lg-0,.mx-lg-0{margin-right:0!important}.mb-lg-0,.my-lg-0{margin-bottom:0!important}.ml-lg-0,.mx-lg-0{margin-left:0!important}.m-lg-1{margin:.25rem!important}.mt-lg-1,.my-lg-1{margin-top:.25rem!important}.mr-lg-1,.mx-lg-1{margin-right:.25rem!important}.mb-lg-1,.my-lg-1{margin-bottom:.25rem!important}.ml-lg-1,.mx-lg-1{margin-left:.25rem!important}.m-lg-2{margin:.5rem!important}.mt-lg-2,.my-lg-2{margin-top:.5rem!important}.mr-lg-2,.mx-lg-2{margin-right:.5rem!important}.mb-lg-2,.my-lg-2{margin-bottom:.5rem!important}.ml-lg-2,.mx-lg-2{margin-left:.5rem!important}.m-lg-3{margin:1rem!important}.mt-lg-3,.my-lg-3{margin-top:1rem!important}.mr-lg-3,.mx-lg-3{margin-right:1rem!important}.mb-lg-3,.my-lg-3{margin-bottom:1rem!important}.ml-lg-3,.mx-lg-3{margin-left:1rem!important}.m-lg-4{margin:1.5rem!important}.mt-lg-4,.my-lg-4{margin-top:1.5rem!important}.mr-lg-4,.mx-lg-4{margin-right:1.5rem!important}.mb-lg-4,.my-lg-4{margin-bottom:1.5rem!important}.ml-lg-4,.mx-lg-4{margin-left:1.5rem!important}.m-lg-5{margin:3rem!important}.mt-lg-5,.my-lg-5{margin-top:3rem!important}.mr-lg-5,.mx-lg-5{margin-right:3rem!important}.mb-lg-5,.my-lg-5{margin-bottom:3rem!important}.ml-lg-5,.mx-lg-5{margin-left:3rem!important}.p-lg-0{padding:0!important}.pt-lg-0,.py-lg-0{padding-top:0!important}.pr-lg-0,.px-lg-0{padding-right:0!important}.pb-lg-0,.py-lg-0{padding-bottom:0!important}.pl-lg-0,.px-lg-0{padding-left:0!important}.p-lg-1{padding:.25rem!important}.pt-lg-1,.py-lg-1{padding-top:.25rem!important}.pr-lg-1,.px-lg-1{padding-right:.25rem!important}.pb-lg-1,.py-lg-1{padding-bottom:.25rem!important}.pl-lg-1,.px-lg-1{padding-left:.25rem!important}.p-lg-2{padding:.5rem!important}.pt-lg-2,.py-lg-2{padding-top:.5rem!important}.pr-lg-2,.px-lg-2{padding-right:.5rem!important}.pb-lg-2,.py-lg-2{padding-bottom:.5rem!important}.pl-lg-2,.px-lg-2{padding-left:.5rem!important}.p-lg-3{padding:1rem!important}.pt-lg-3,.py-lg-3{padding-top:1rem!important}.pr-lg-3,.px-lg-3{padding-right:1rem!important}.pb-lg-3,.py-lg-3{padding-bottom:1rem!important}.pl-lg-3,.px-lg-3{padding-left:1rem!important}.p-lg-4{padding:1.5rem!important}.pt-lg-4,.py-lg-4{padding-top:1.5rem!important}.pr-lg-4,.px-lg-4{padding-right:1.5rem!important}.pb-lg-4,.py-lg-4{padding-bottom:1.5rem!important}.pl-lg-4,.px-lg-4{padding-left:1.5rem!important}.p-lg-5{padding:3rem!important}.pt-lg-5,.py-lg-5{padding-top:3rem!important}.pr-lg-5,.px-lg-5{padding-right:3rem!important}.pb-lg-5,.py-lg-5{padding-bottom:3rem!important}.pl-lg-5,.px-lg-5{padding-left:3rem!important}.m-lg-auto{margin:auto!important}.mt-lg-auto,.my-lg-auto{margin-top:auto!important}.mr-lg-auto,.mx-lg-auto{margin-right:auto!important}.mb-lg-auto,.my-lg-auto{margin-bottom:auto!important}.ml-lg-auto,.mx-lg-auto{margin-left:auto!important}}@media (min-width:1200px){.m-xl-0{margin:0!important}.mt-xl-0,.my-xl-0{margin-top:0!important}.mr-xl-0,.mx-xl-0{margin-right:0!important}.mb-xl-0,.my-xl-0{margin-bottom:0!important}.ml-xl-0,.mx-xl-0{margin-left:0!important}.m-xl-1{margin:.25rem!important}.mt-xl-1,.my-xl-1{margin-top:.25rem!important}.mr-xl-1,.mx-xl-1{margin-right:.25rem!important}.mb-xl-1,.my-xl-1{margin-bottom:.25rem!important}.ml-xl-1,.mx-xl-1{margin-left:.25rem!important}.m-xl-2{margin:.5rem!important}.mt-xl-2,.my-xl-2{margin-top:.5rem!important}.mr-xl-2,.mx-xl-2{margin-right:.5rem!important}.mb-xl-2,.my-xl-2{margin-bottom:.5rem!important}.ml-xl-2,.mx-xl-2{margin-left:.5rem!important}.m-xl-3{margin:1rem!important}.mt-xl-3,.my-xl-3{margin-top:1rem!important}.mr-xl-3,.mx-xl-3{margin-right:1rem!important}.mb-xl-3,.my-xl-3{margin-bottom:1rem!important}.ml-xl-3,.mx-xl-3{margin-left:1rem!important}.m-xl-4{margin:1.5rem!important}.mt-xl-4,.my-xl-4{margin-top:1.5rem!important}.mr-xl-4,.mx-xl-4{margin-right:1.5rem!important}.mb-xl-4,.my-xl-4{margin-bottom:1.5rem!important}.ml-xl-4,.mx-xl-4{margin-left:1.5rem!important}.m-xl-5{margin:3rem!important}.mt-xl-5,.my-xl-5{margin-top:3rem!important}.mr-xl-5,.mx-xl-5{margin-right:3rem!important}.mb-xl-5,.my-xl-5{margin-bottom:3rem!important}.ml-xl-5,.mx-xl-5{margin-left:3rem!important}.p-xl-0{padding:0!important}.pt-xl-0,.py-xl-0{padding-top:0!important}.pr-xl-0,.px-xl-0{padding-right:0!important}.pb-xl-0,.py-xl-0{padding-bottom:0!important}.pl-xl-0,.px-xl-0{padding-left:0!important}.p-xl-1{padding:.25rem!important}.pt-xl-1,.py-xl-1{padding-top:.25rem!important}.pr-xl-1,.px-xl-1{padding-right:.25rem!important}.pb-xl-1,.py-xl-1{padding-bottom:.25rem!important}.pl-xl-1,.px-xl-1{padding-left:.25rem!important}.p-xl-2{padding:.5rem!important}.pt-xl-2,.py-xl-2{padding-top:.5rem!important}.pr-xl-2,.px-xl-2{padding-right:.5rem!important}.pb-xl-2,.py-xl-2{padding-bottom:.5rem!important}.pl-xl-2,.px-xl-2{padding-left:.5rem!important}.p-xl-3{padding:1rem!important}.pt-xl-3,.py-xl-3{padding-top:1rem!important}.pr-xl-3,.px-xl-3{padding-right:1rem!important}.pb-xl-3,.py-xl-3{padding-bottom:1rem!important}.pl-xl-3,.px-xl-3{padding-left:1rem!important}.p-xl-4{padding:1.5rem!important}.pt-xl-4,.py-xl-4{padding-top:1.5rem!important}.pr-xl-4,.px-xl-4{padding-right:1.5rem!important}.pb-xl-4,.py-xl-4{padding-bottom:1.5rem!important}.pl-xl-4,.px-xl-4{padding-left:1.5rem!important}.p-xl-5{padding:3rem!important}.pt-xl-5,.py-xl-5{padding-top:3rem!important}.pr-xl-5,.px-xl-5{padding-right:3rem!important}.pb-xl-5,.py-xl-5{padding-bottom:3rem!important}.pl-xl-5,.px-xl-5{padding-left:3rem!important}.m-xl-auto{margin:auto!important}.mt-xl-auto,.my-xl-auto{margin-top:auto!important}.mr-xl-auto,.mx-xl-auto{margin-right:auto!important}.mb-xl-auto,.my-xl-auto{margin-bottom:auto!important}.ml-xl-auto,.mx-xl-auto{margin-left:auto!important}}.text-justify{text-align:justify!important}.text-nowrap{white-space:nowrap!important}.text-truncate{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.text-left{text-align:left!important}.text-right{text-align:right!important}.text-center{text-align:center!important}@media (min-width:576px){.text-sm-left{text-align:left!important}.text-sm-right{text-align:right!important}.text-sm-center{text-align:center!important}}@media (min-width:768px){.text-md-left{text-align:left!important}.text-md-right{text-align:right!important}.text-md-center{text-align:center!important}}@media (min-width:992px){.text-lg-left{text-align:left!important}.text-lg-right{text-align:right!important}.text-lg-center{text-align:center!important}}@media (min-width:1200px){.text-xl-left{text-align:left!important}.text-xl-right{text-align:right!important}.text-xl-center{text-align:center!important}}.text-lowercase{text-transform:lowercase!important}.text-uppercase{text-transform:uppercase!important}.text-capitalize{text-transform:capitalize!important}.font-weight-light{font-weight:300!important}.font-weight-normal{font-weight:400!important}.font-weight-bold{font-weight:700!important}.font-italic{font-style:italic!important}.text-white{color:#fff!important}.text-primary{color:#007bff!important}a.text-primary:focus,a.text-primary:hover{color:#0062cc!important}.text-secondary{color:#868e96!important}a.text-secondary:focus,a.text-secondary:hover{color:#6c757d!important}.text-success{color:#28a745!important}a.text-success:focus,a.text-success:hover{color:#1e7e34!important}.text-info{color:#17a2b8!important}a.text-info:focus,a.text-info:hover{color:#117a8b!important}.text-warning{color:#ffc107!important}a.text-warning:focus,a.text-warning:hover{color:#d39e00!important}.text-danger{color:#dc3545!important}a.text-danger:focus,a.text-danger:hover{color:#bd2130!important}.text-light{color:#f8f9fa!important}a.text-light:focus,a.text-light:hover{color:#dae0e5!important}.text-dark{color:#343a40!important}a.text-dark:focus,a.text-dark:hover{color:#1d2124!important}.text-muted{color:#868e96!important}.text-hide{font:0/0 a;color:transparent;text-shadow:none;background-color:transparent;border:0}.visible{visibility:visible!important}.invisible{visibility:hidden!important} +/*# sourceMappingURL=bootstrap.min.css.map */ \ No newline at end of file diff --git a/www/static/css/style.css b/www/static/css/style.css new file mode 100644 index 000000000..186883d1c --- /dev/null +++ b/www/static/css/style.css @@ -0,0 +1,30 @@ +body { + background: white; + color: black; +} +.row{margin: 10px} +.bg{font-size:40px;font-weight:bold} +.delta,.timeago-bg{font-size:14px;} + +.topbox{ + font-size:20px; + background-color:#cccccc; + border-radius:8px; + margin: 13px 0 10px; +} + +.box2{ + background-color:#cccccc; + border-radius:8px; + margin:0px 10px; +} + +.delta-box{ + padding:30px 0 0 0; +} + +@media (max-device-width:768px) { + .delta-box{ + padding:0; + } +} diff --git a/www/static/js/bootstrap.min.js b/www/static/js/bootstrap.min.js new file mode 100644 index 000000000..3ef837607 --- /dev/null +++ b/www/static/js/bootstrap.min.js @@ -0,0 +1,7 @@ +/*! + * Bootstrap v4.0.0-beta.3 (https://getbootstrap.com) + * Copyright 2011-2017 The Bootstrap Authors (https://github.com/twbs/bootstrap/graphs/contributors) + * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) + */ +!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports,require("jquery"),require("popper.js")):"function"==typeof define&&define.amd?define(["exports","jquery","popper.js"],e):e(t.bootstrap={},t.jQuery,t.Popper)}(this,function(t,e,n){"use strict";function i(t,e){for(var n=0;n0?n:null}catch(t){return null}},reflow:function(t){return t.offsetHeight},triggerTransitionEnd:function(e){t(e).trigger(i.end)},supportsTransitionEnd:function(){return Boolean(i)},isElement:function(t){return(t[0]||t).nodeType},typeCheckConfig:function(t,n,i){for(var r in i)if(Object.prototype.hasOwnProperty.call(i,r)){var o=i[r],a=n[r],l=a&&s.isElement(a)?"element":e(a);if(!new RegExp(o).test(l))throw new Error(t.toUpperCase()+': Option "'+r+'" provided type "'+l+'" but expected type "'+o+'".')}}};return i=!window.QUnit&&{end:"transitionend"},t.fn.emulateTransitionEnd=n,s.supportsTransitionEnd()&&(t.event.special[s.TRANSITION_END]={bindType:i.end,delegateType:i.end,handle:function(e){if(t(e.target).is(this))return e.handleObj.handler.apply(this,arguments)}}),s}(e),a=function(t){var e="alert",n="bs.alert",i="."+n,r=t.fn[e],a={CLOSE:"close"+i,CLOSED:"closed"+i,CLICK_DATA_API:"click"+i+".data-api"},l="alert",h="fade",c="show",u=function(){function e(t){this._element=t}var i=e.prototype;return i.close=function(t){t=t||this._element;var e=this._getRootElement(t);this._triggerCloseEvent(e).isDefaultPrevented()||this._removeElement(e)},i.dispose=function(){t.removeData(this._element,n),this._element=null},i._getRootElement=function(e){var n=o.getSelectorFromElement(e),i=!1;return n&&(i=t(n)[0]),i||(i=t(e).closest("."+l)[0]),i},i._triggerCloseEvent=function(e){var n=t.Event(a.CLOSE);return t(e).trigger(n),n},i._removeElement=function(e){var n=this;t(e).removeClass(c),o.supportsTransitionEnd()&&t(e).hasClass(h)?t(e).one(o.TRANSITION_END,function(t){return n._destroyElement(e,t)}).emulateTransitionEnd(150):this._destroyElement(e)},i._destroyElement=function(e){t(e).detach().trigger(a.CLOSED).remove()},e._jQueryInterface=function(i){return this.each(function(){var s=t(this),r=s.data(n);r||(r=new e(this),s.data(n,r)),"close"===i&&r[i](this)})},e._handleDismiss=function(t){return function(e){e&&e.preventDefault(),t.close(this)}},s(e,null,[{key:"VERSION",get:function(){return"4.0.0-beta.3"}}]),e}();return t(document).on(a.CLICK_DATA_API,'[data-dismiss="alert"]',u._handleDismiss(new u)),t.fn[e]=u._jQueryInterface,t.fn[e].Constructor=u,t.fn[e].noConflict=function(){return t.fn[e]=r,u._jQueryInterface},u}(e),l=function(t){var e="button",n="bs.button",i="."+n,r=".data-api",o=t.fn[e],a="active",l="btn",h="focus",c='[data-toggle^="button"]',u='[data-toggle="buttons"]',f="input",d=".active",_=".btn",g={CLICK_DATA_API:"click"+i+r,FOCUS_BLUR_DATA_API:"focus"+i+r+" blur"+i+r},m=function(){function e(t){this._element=t}var i=e.prototype;return i.toggle=function(){var e=!0,n=!0,i=t(this._element).closest(u)[0];if(i){var s=t(this._element).find(f)[0];if(s){if("radio"===s.type)if(s.checked&&t(this._element).hasClass(a))e=!1;else{var r=t(i).find(d)[0];r&&t(r).removeClass(a)}if(e){if(s.hasAttribute("disabled")||i.hasAttribute("disabled")||s.classList.contains("disabled")||i.classList.contains("disabled"))return;s.checked=!t(this._element).hasClass(a),t(s).trigger("change")}s.focus(),n=!1}}n&&this._element.setAttribute("aria-pressed",!t(this._element).hasClass(a)),e&&t(this._element).toggleClass(a)},i.dispose=function(){t.removeData(this._element,n),this._element=null},e._jQueryInterface=function(i){return this.each(function(){var s=t(this).data(n);s||(s=new e(this),t(this).data(n,s)),"toggle"===i&&s[i]()})},s(e,null,[{key:"VERSION",get:function(){return"4.0.0-beta.3"}}]),e}();return t(document).on(g.CLICK_DATA_API,c,function(e){e.preventDefault();var n=e.target;t(n).hasClass(l)||(n=t(n).closest(_)),m._jQueryInterface.call(t(n),"toggle")}).on(g.FOCUS_BLUR_DATA_API,c,function(e){var n=t(e.target).closest(_)[0];t(n).toggleClass(h,/^focus(in)?$/.test(e.type))}),t.fn[e]=m._jQueryInterface,t.fn[e].Constructor=m,t.fn[e].noConflict=function(){return t.fn[e]=o,m._jQueryInterface},m}(e),h=function(t){var e="carousel",n="bs.carousel",i="."+n,a=t.fn[e],l={interval:5e3,keyboard:!0,slide:!1,pause:"hover",wrap:!0},h={interval:"(number|boolean)",keyboard:"boolean",slide:"(boolean|string)",pause:"(string|boolean)",wrap:"boolean"},c="next",u="prev",f="left",d="right",_={SLIDE:"slide"+i,SLID:"slid"+i,KEYDOWN:"keydown"+i,MOUSEENTER:"mouseenter"+i,MOUSELEAVE:"mouseleave"+i,TOUCHEND:"touchend"+i,LOAD_DATA_API:"load"+i+".data-api",CLICK_DATA_API:"click"+i+".data-api"},g="carousel",m="active",p="slide",v="carousel-item-right",E="carousel-item-left",T="carousel-item-next",y="carousel-item-prev",C={ACTIVE:".active",ACTIVE_ITEM:".active.carousel-item",ITEM:".carousel-item",NEXT_PREV:".carousel-item-next, .carousel-item-prev",INDICATORS:".carousel-indicators",DATA_SLIDE:"[data-slide], [data-slide-to]",DATA_RIDE:'[data-ride="carousel"]'},I=function(){function a(e,n){this._items=null,this._interval=null,this._activeElement=null,this._isPaused=!1,this._isSliding=!1,this.touchTimeout=null,this._config=this._getConfig(n),this._element=t(e)[0],this._indicatorsElement=t(this._element).find(C.INDICATORS)[0],this._addEventListeners()}var I=a.prototype;return I.next=function(){this._isSliding||this._slide(c)},I.nextWhenVisible=function(){!document.hidden&&t(this._element).is(":visible")&&"hidden"!==t(this._element).css("visibility")&&this.next()},I.prev=function(){this._isSliding||this._slide(u)},I.pause=function(e){e||(this._isPaused=!0),t(this._element).find(C.NEXT_PREV)[0]&&o.supportsTransitionEnd()&&(o.triggerTransitionEnd(this._element),this.cycle(!0)),clearInterval(this._interval),this._interval=null},I.cycle=function(t){t||(this._isPaused=!1),this._interval&&(clearInterval(this._interval),this._interval=null),this._config.interval&&!this._isPaused&&(this._interval=setInterval((document.visibilityState?this.nextWhenVisible:this.next).bind(this),this._config.interval))},I.to=function(e){var n=this;this._activeElement=t(this._element).find(C.ACTIVE_ITEM)[0];var i=this._getItemIndex(this._activeElement);if(!(e>this._items.length-1||e<0))if(this._isSliding)t(this._element).one(_.SLID,function(){return n.to(e)});else{if(i===e)return this.pause(),void this.cycle();var s=e>i?c:u;this._slide(s,this._items[e])}},I.dispose=function(){t(this._element).off(i),t.removeData(this._element,n),this._items=null,this._config=null,this._element=null,this._interval=null,this._isPaused=null,this._isSliding=null,this._activeElement=null,this._indicatorsElement=null},I._getConfig=function(t){return t=r({},l,t),o.typeCheckConfig(e,t,h),t},I._addEventListeners=function(){var e=this;this._config.keyboard&&t(this._element).on(_.KEYDOWN,function(t){return e._keydown(t)}),"hover"===this._config.pause&&(t(this._element).on(_.MOUSEENTER,function(t){return e.pause(t)}).on(_.MOUSELEAVE,function(t){return e.cycle(t)}),"ontouchstart"in document.documentElement&&t(this._element).on(_.TOUCHEND,function(){e.pause(),e.touchTimeout&&clearTimeout(e.touchTimeout),e.touchTimeout=setTimeout(function(t){return e.cycle(t)},500+e._config.interval)}))},I._keydown=function(t){if(!/input|textarea/i.test(t.target.tagName))switch(t.which){case 37:t.preventDefault(),this.prev();break;case 39:t.preventDefault(),this.next();break;default:return}},I._getItemIndex=function(e){return this._items=t.makeArray(t(e).parent().find(C.ITEM)),this._items.indexOf(e)},I._getItemByDirection=function(t,e){var n=t===c,i=t===u,s=this._getItemIndex(e),r=this._items.length-1;if((i&&0===s||n&&s===r)&&!this._config.wrap)return e;var o=(s+(t===u?-1:1))%this._items.length;return-1===o?this._items[this._items.length-1]:this._items[o]},I._triggerSlideEvent=function(e,n){var i=this._getItemIndex(e),s=this._getItemIndex(t(this._element).find(C.ACTIVE_ITEM)[0]),r=t.Event(_.SLIDE,{relatedTarget:e,direction:n,from:s,to:i});return t(this._element).trigger(r),r},I._setActiveIndicatorElement=function(e){if(this._indicatorsElement){t(this._indicatorsElement).find(C.ACTIVE).removeClass(m);var n=this._indicatorsElement.children[this._getItemIndex(e)];n&&t(n).addClass(m)}},I._slide=function(e,n){var i,s,r,a=this,l=t(this._element).find(C.ACTIVE_ITEM)[0],h=this._getItemIndex(l),u=n||l&&this._getItemByDirection(e,l),g=this._getItemIndex(u),I=Boolean(this._interval);if(e===c?(i=E,s=T,r=f):(i=v,s=y,r=d),u&&t(u).hasClass(m))this._isSliding=!1;else{if(!this._triggerSlideEvent(u,r).isDefaultPrevented()&&l&&u){this._isSliding=!0,I&&this.pause(),this._setActiveIndicatorElement(u);var A=t.Event(_.SLID,{relatedTarget:u,direction:r,from:h,to:g});o.supportsTransitionEnd()&&t(this._element).hasClass(p)?(t(u).addClass(s),o.reflow(u),t(l).addClass(i),t(u).addClass(i),t(l).one(o.TRANSITION_END,function(){t(u).removeClass(i+" "+s).addClass(m),t(l).removeClass(m+" "+s+" "+i),a._isSliding=!1,setTimeout(function(){return t(a._element).trigger(A)},0)}).emulateTransitionEnd(600)):(t(l).removeClass(m),t(u).addClass(m),this._isSliding=!1,t(this._element).trigger(A)),I&&this.cycle()}}},a._jQueryInterface=function(e){return this.each(function(){var i=t(this).data(n),s=r({},l,t(this).data());"object"==typeof e&&(s=r({},s,e));var o="string"==typeof e?e:s.slide;if(i||(i=new a(this,s),t(this).data(n,i)),"number"==typeof e)i.to(e);else if("string"==typeof o){if("undefined"==typeof i[o])throw new Error('No method named "'+o+'"');i[o]()}else s.interval&&(i.pause(),i.cycle())})},a._dataApiClickHandler=function(e){var i=o.getSelectorFromElement(this);if(i){var s=t(i)[0];if(s&&t(s).hasClass(g)){var l=r({},t(s).data(),t(this).data()),h=this.getAttribute("data-slide-to");h&&(l.interval=!1),a._jQueryInterface.call(t(s),l),h&&t(s).data(n).to(h),e.preventDefault()}}},s(a,null,[{key:"VERSION",get:function(){return"4.0.0-beta.3"}},{key:"Default",get:function(){return l}}]),a}();return t(document).on(_.CLICK_DATA_API,C.DATA_SLIDE,I._dataApiClickHandler),t(window).on(_.LOAD_DATA_API,function(){t(C.DATA_RIDE).each(function(){var e=t(this);I._jQueryInterface.call(e,e.data())})}),t.fn[e]=I._jQueryInterface,t.fn[e].Constructor=I,t.fn[e].noConflict=function(){return t.fn[e]=a,I._jQueryInterface},I}(e),c=function(t){var e="collapse",n="bs.collapse",i="."+n,a=t.fn[e],l={toggle:!0,parent:""},h={toggle:"boolean",parent:"(string|element)"},c={SHOW:"show"+i,SHOWN:"shown"+i,HIDE:"hide"+i,HIDDEN:"hidden"+i,CLICK_DATA_API:"click"+i+".data-api"},u="show",f="collapse",d="collapsing",_="collapsed",g="width",m="height",p={ACTIVES:".show, .collapsing",DATA_TOGGLE:'[data-toggle="collapse"]'},v=function(){function i(e,n){this._isTransitioning=!1,this._element=e,this._config=this._getConfig(n),this._triggerArray=t.makeArray(t('[data-toggle="collapse"][href="#'+e.id+'"],[data-toggle="collapse"][data-target="#'+e.id+'"]'));for(var i=t(p.DATA_TOGGLE),s=0;s0&&this._triggerArray.push(r)}this._parent=this._config.parent?this._getParent():null,this._config.parent||this._addAriaAndCollapsedClass(this._element,this._triggerArray),this._config.toggle&&this.toggle()}var a=i.prototype;return a.toggle=function(){t(this._element).hasClass(u)?this.hide():this.show()},a.show=function(){var e=this;if(!this._isTransitioning&&!t(this._element).hasClass(u)){var s,r;if(this._parent&&((s=t.makeArray(t(this._parent).children().children(p.ACTIVES))).length||(s=null)),!(s&&(r=t(s).data(n))&&r._isTransitioning)){var a=t.Event(c.SHOW);if(t(this._element).trigger(a),!a.isDefaultPrevented()){s&&(i._jQueryInterface.call(t(s),"hide"),r||t(s).data(n,null));var l=this._getDimension();t(this._element).removeClass(f).addClass(d),this._element.style[l]=0,this._triggerArray.length&&t(this._triggerArray).removeClass(_).attr("aria-expanded",!0),this.setTransitioning(!0);var h=function(){t(e._element).removeClass(d).addClass(f).addClass(u),e._element.style[l]="",e.setTransitioning(!1),t(e._element).trigger(c.SHOWN)};if(o.supportsTransitionEnd()){var g="scroll"+(l[0].toUpperCase()+l.slice(1));t(this._element).one(o.TRANSITION_END,h).emulateTransitionEnd(600),this._element.style[l]=this._element[g]+"px"}else h()}}}},a.hide=function(){var e=this;if(!this._isTransitioning&&t(this._element).hasClass(u)){var n=t.Event(c.HIDE);if(t(this._element).trigger(n),!n.isDefaultPrevented()){var i=this._getDimension();if(this._element.style[i]=this._element.getBoundingClientRect()[i]+"px",o.reflow(this._element),t(this._element).addClass(d).removeClass(f).removeClass(u),this._triggerArray.length)for(var s=0;s0},h._getPopperConfig=function(){var t=this,e={};"function"==typeof this._config.offset?e.fn=function(e){return e.offsets=r({},e.offsets,t._config.offset(e.offsets)||{}),e}:e.offset=this._config.offset;return{placement:this._getPlacement(),modifiers:{offset:e,flip:{enabled:this._config.flip},preventOverflow:{boundariesElement:this._config.boundary}}}},l._jQueryInterface=function(e){return this.each(function(){var n=t(this).data(i);if(n||(n=new l(this,"object"==typeof e?e:null),t(this).data(i,n)),"string"==typeof e){if("undefined"==typeof n[e])throw new Error('No method named "'+e+'"');n[e]()}})},l._clearMenus=function(e){if(!e||3!==e.which&&("keyup"!==e.type||9===e.which))for(var n=t.makeArray(t(T)),s=0;s0&&r--,40===e.which&&rdocument.documentElement.clientHeight;!this._isBodyOverflowing&&t&&(this._element.style.paddingLeft=this._scrollbarWidth+"px"),this._isBodyOverflowing&&!t&&(this._element.style.paddingRight=this._scrollbarWidth+"px")},p._resetAdjustments=function(){this._element.style.paddingLeft="",this._element.style.paddingRight=""},p._checkScrollbar=function(){var t=document.body.getBoundingClientRect();this._isBodyOverflowing=t.left+t.right
',trigger:"hover focus",title:"",delay:0,html:!1,selector:!1,placement:"top",offset:0,container:!1,fallbackPlacement:"flip",boundary:"scrollParent"},d="show",_="out",g={HIDE:"hide"+a,HIDDEN:"hidden"+a,SHOW:"show"+a,SHOWN:"shown"+a,INSERTED:"inserted"+a,CLICK:"click"+a,FOCUSIN:"focusin"+a,FOCUSOUT:"focusout"+a,MOUSEENTER:"mouseenter"+a,MOUSELEAVE:"mouseleave"+a},m="fade",p="show",v=".tooltip-inner",E=".arrow",T="hover",y="focus",C="click",I="manual",A=function(){function l(t,e){if("undefined"==typeof n)throw new Error("Bootstrap tooltips require Popper.js (https://popper.js.org)");this._isEnabled=!0,this._timeout=0,this._hoverState="",this._activeTrigger={},this._popper=null,this.element=t,this.config=this._getConfig(e),this.tip=null,this._setListeners()}var A=l.prototype;return A.enable=function(){this._isEnabled=!0},A.disable=function(){this._isEnabled=!1},A.toggleEnabled=function(){this._isEnabled=!this._isEnabled},A.toggle=function(e){if(this._isEnabled)if(e){var n=this.constructor.DATA_KEY,i=t(e.currentTarget).data(n);i||(i=new this.constructor(e.currentTarget,this._getDelegateConfig()),t(e.currentTarget).data(n,i)),i._activeTrigger.click=!i._activeTrigger.click,i._isWithActiveTrigger()?i._enter(null,i):i._leave(null,i)}else{if(t(this.getTipElement()).hasClass(p))return void this._leave(null,this);this._enter(null,this)}},A.dispose=function(){clearTimeout(this._timeout),t.removeData(this.element,this.constructor.DATA_KEY),t(this.element).off(this.constructor.EVENT_KEY),t(this.element).closest(".modal").off("hide.bs.modal"),this.tip&&t(this.tip).remove(),this._isEnabled=null,this._timeout=null,this._hoverState=null,this._activeTrigger=null,null!==this._popper&&this._popper.destroy(),this._popper=null,this.element=null,this.config=null,this.tip=null},A.show=function(){var e=this;if("none"===t(this.element).css("display"))throw new Error("Please use show on visible elements");var i=t.Event(this.constructor.Event.SHOW);if(this.isWithContent()&&this._isEnabled){t(this.element).trigger(i);var s=t.contains(this.element.ownerDocument.documentElement,this.element);if(i.isDefaultPrevented()||!s)return;var r=this.getTipElement(),a=o.getUID(this.constructor.NAME);r.setAttribute("id",a),this.element.setAttribute("aria-describedby",a),this.setContent(),this.config.animation&&t(r).addClass(m);var h="function"==typeof this.config.placement?this.config.placement.call(this,r,this.element):this.config.placement,c=this._getAttachment(h);this.addAttachmentClass(c);var u=!1===this.config.container?document.body:t(this.config.container);t(r).data(this.constructor.DATA_KEY,this),t.contains(this.element.ownerDocument.documentElement,this.tip)||t(r).appendTo(u),t(this.element).trigger(this.constructor.Event.INSERTED),this._popper=new n(this.element,r,{placement:c,modifiers:{offset:{offset:this.config.offset},flip:{behavior:this.config.fallbackPlacement},arrow:{element:E},preventOverflow:{boundariesElement:this.config.boundary}},onCreate:function(t){t.originalPlacement!==t.placement&&e._handlePopperPlacementChange(t)},onUpdate:function(t){e._handlePopperPlacementChange(t)}}),t(r).addClass(p),"ontouchstart"in document.documentElement&&t("body").children().on("mouseover",null,t.noop);var f=function(){e.config.animation&&e._fixTransition();var n=e._hoverState;e._hoverState=null,t(e.element).trigger(e.constructor.Event.SHOWN),n===_&&e._leave(null,e)};o.supportsTransitionEnd()&&t(this.tip).hasClass(m)?t(this.tip).one(o.TRANSITION_END,f).emulateTransitionEnd(l._TRANSITION_DURATION):f()}},A.hide=function(e){var n=this,i=this.getTipElement(),s=t.Event(this.constructor.Event.HIDE),r=function(){n._hoverState!==d&&i.parentNode&&i.parentNode.removeChild(i),n._cleanTipClass(),n.element.removeAttribute("aria-describedby"),t(n.element).trigger(n.constructor.Event.HIDDEN),null!==n._popper&&n._popper.destroy(),e&&e()};t(this.element).trigger(s),s.isDefaultPrevented()||(t(i).removeClass(p),"ontouchstart"in document.documentElement&&t("body").children().off("mouseover",null,t.noop),this._activeTrigger[C]=!1,this._activeTrigger[y]=!1,this._activeTrigger[T]=!1,o.supportsTransitionEnd()&&t(this.tip).hasClass(m)?t(i).one(o.TRANSITION_END,r).emulateTransitionEnd(150):r(),this._hoverState="")},A.update=function(){null!==this._popper&&this._popper.scheduleUpdate()},A.isWithContent=function(){return Boolean(this.getTitle())},A.addAttachmentClass=function(e){t(this.getTipElement()).addClass("bs-tooltip-"+e)},A.getTipElement=function(){return this.tip=this.tip||t(this.config.template)[0],this.tip},A.setContent=function(){var e=t(this.getTipElement());this.setElementContent(e.find(v),this.getTitle()),e.removeClass(m+" "+p)},A.setElementContent=function(e,n){var i=this.config.html;"object"==typeof n&&(n.nodeType||n.jquery)?i?t(n).parent().is(e)||e.empty().append(n):e.text(t(n).text()):e[i?"html":"text"](n)},A.getTitle=function(){var t=this.element.getAttribute("data-original-title");return t||(t="function"==typeof this.config.title?this.config.title.call(this.element):this.config.title),t},A._getAttachment=function(t){return u[t.toUpperCase()]},A._setListeners=function(){var e=this;this.config.trigger.split(" ").forEach(function(n){if("click"===n)t(e.element).on(e.constructor.Event.CLICK,e.config.selector,function(t){return e.toggle(t)});else if(n!==I){var i=n===T?e.constructor.Event.MOUSEENTER:e.constructor.Event.FOCUSIN,s=n===T?e.constructor.Event.MOUSELEAVE:e.constructor.Event.FOCUSOUT;t(e.element).on(i,e.config.selector,function(t){return e._enter(t)}).on(s,e.config.selector,function(t){return e._leave(t)})}t(e.element).closest(".modal").on("hide.bs.modal",function(){return e.hide()})}),this.config.selector?this.config=r({},this.config,{trigger:"manual",selector:""}):this._fixTitle()},A._fixTitle=function(){var t=typeof this.element.getAttribute("data-original-title");(this.element.getAttribute("title")||"string"!==t)&&(this.element.setAttribute("data-original-title",this.element.getAttribute("title")||""),this.element.setAttribute("title",""))},A._enter=function(e,n){var i=this.constructor.DATA_KEY;(n=n||t(e.currentTarget).data(i))||(n=new this.constructor(e.currentTarget,this._getDelegateConfig()),t(e.currentTarget).data(i,n)),e&&(n._activeTrigger["focusin"===e.type?y:T]=!0),t(n.getTipElement()).hasClass(p)||n._hoverState===d?n._hoverState=d:(clearTimeout(n._timeout),n._hoverState=d,n.config.delay&&n.config.delay.show?n._timeout=setTimeout(function(){n._hoverState===d&&n.show()},n.config.delay.show):n.show())},A._leave=function(e,n){var i=this.constructor.DATA_KEY;(n=n||t(e.currentTarget).data(i))||(n=new this.constructor(e.currentTarget,this._getDelegateConfig()),t(e.currentTarget).data(i,n)),e&&(n._activeTrigger["focusout"===e.type?y:T]=!1),n._isWithActiveTrigger()||(clearTimeout(n._timeout),n._hoverState=_,n.config.delay&&n.config.delay.hide?n._timeout=setTimeout(function(){n._hoverState===_&&n.hide()},n.config.delay.hide):n.hide())},A._isWithActiveTrigger=function(){for(var t in this._activeTrigger)if(this._activeTrigger[t])return!0;return!1},A._getConfig=function(n){return"number"==typeof(n=r({},this.constructor.Default,t(this.element).data(),n)).delay&&(n.delay={show:n.delay,hide:n.delay}),"number"==typeof n.title&&(n.title=n.title.toString()),"number"==typeof n.content&&(n.content=n.content.toString()),o.typeCheckConfig(e,n,this.constructor.DefaultType),n},A._getDelegateConfig=function(){var t={};if(this.config)for(var e in this.config)this.constructor.Default[e]!==this.config[e]&&(t[e]=this.config[e]);return t},A._cleanTipClass=function(){var e=t(this.getTipElement()),n=e.attr("class").match(h);null!==n&&n.length>0&&e.removeClass(n.join(""))},A._handlePopperPlacementChange=function(t){this._cleanTipClass(),this.addAttachmentClass(this._getAttachment(t.placement))},A._fixTransition=function(){var e=this.getTipElement(),n=this.config.animation;null===e.getAttribute("x-placement")&&(t(e).removeClass(m),this.config.animation=!1,this.hide(),this.show(),this.config.animation=n)},l._jQueryInterface=function(e){return this.each(function(){var n=t(this).data(i),s="object"==typeof e&&e;if((n||!/dispose|hide/.test(e))&&(n||(n=new l(this,s),t(this).data(i,n)),"string"==typeof e)){if("undefined"==typeof n[e])throw new Error('No method named "'+e+'"');n[e]()}})},s(l,null,[{key:"VERSION",get:function(){return"4.0.0-beta.3"}},{key:"Default",get:function(){return f}},{key:"NAME",get:function(){return e}},{key:"DATA_KEY",get:function(){return i}},{key:"Event",get:function(){return g}},{key:"EVENT_KEY",get:function(){return a}},{key:"DefaultType",get:function(){return c}}]),l}();return t.fn[e]=A._jQueryInterface,t.fn[e].Constructor=A,t.fn[e].noConflict=function(){return t.fn[e]=l,A._jQueryInterface},A}(e),_=function(t){var e="popover",n="bs.popover",i="."+n,o=t.fn[e],a=new RegExp("(^|\\s)bs-popover\\S+","g"),l=r({},d.Default,{placement:"right",trigger:"click",content:"",template:''}),h=r({},d.DefaultType,{content:"(string|element|function)"}),c="fade",u="show",f=".popover-header",_=".popover-body",g={HIDE:"hide"+i,HIDDEN:"hidden"+i,SHOW:"show"+i,SHOWN:"shown"+i,INSERTED:"inserted"+i,CLICK:"click"+i,FOCUSIN:"focusin"+i,FOCUSOUT:"focusout"+i,MOUSEENTER:"mouseenter"+i,MOUSELEAVE:"mouseleave"+i},m=function(r){function o(){return r.apply(this,arguments)||this}!function(t,e){t.prototype=Object.create(e.prototype),t.prototype.constructor=t,t.__proto__=e}(o,r);var d=o.prototype;return d.isWithContent=function(){return this.getTitle()||this._getContent()},d.addAttachmentClass=function(e){t(this.getTipElement()).addClass("bs-popover-"+e)},d.getTipElement=function(){return this.tip=this.tip||t(this.config.template)[0],this.tip},d.setContent=function(){var e=t(this.getTipElement());this.setElementContent(e.find(f),this.getTitle());var n=this._getContent();"function"==typeof n&&(n=n.call(this.element)),this.setElementContent(e.find(_),n),e.removeClass(c+" "+u)},d._getContent=function(){return this.element.getAttribute("data-content")||this.config.content},d._cleanTipClass=function(){var e=t(this.getTipElement()),n=e.attr("class").match(a);null!==n&&n.length>0&&e.removeClass(n.join(""))},o._jQueryInterface=function(e){return this.each(function(){var i=t(this).data(n),s="object"==typeof e?e:null;if((i||!/destroy|hide/.test(e))&&(i||(i=new o(this,s),t(this).data(n,i)),"string"==typeof e)){if("undefined"==typeof i[e])throw new Error('No method named "'+e+'"');i[e]()}})},s(o,null,[{key:"VERSION",get:function(){return"4.0.0-beta.3"}},{key:"Default",get:function(){return l}},{key:"NAME",get:function(){return e}},{key:"DATA_KEY",get:function(){return n}},{key:"Event",get:function(){return g}},{key:"EVENT_KEY",get:function(){return i}},{key:"DefaultType",get:function(){return h}}]),o}(d);return t.fn[e]=m._jQueryInterface,t.fn[e].Constructor=m,t.fn[e].noConflict=function(){return t.fn[e]=o,m._jQueryInterface},m}(e),g=function(t){var e="scrollspy",n="bs.scrollspy",i="."+n,a=t.fn[e],l={offset:10,method:"auto",target:""},h={offset:"number",method:"string",target:"(string|element)"},c={ACTIVATE:"activate"+i,SCROLL:"scroll"+i,LOAD_DATA_API:"load"+i+".data-api"},u="dropdown-item",f="active",d={DATA_SPY:'[data-spy="scroll"]',ACTIVE:".active",NAV_LIST_GROUP:".nav, .list-group",NAV_LINKS:".nav-link",NAV_ITEMS:".nav-item",LIST_ITEMS:".list-group-item",DROPDOWN:".dropdown",DROPDOWN_ITEMS:".dropdown-item",DROPDOWN_TOGGLE:".dropdown-toggle"},_="offset",g="position",m=function(){function a(e,n){var i=this;this._element=e,this._scrollElement="BODY"===e.tagName?window:e,this._config=this._getConfig(n),this._selector=this._config.target+" "+d.NAV_LINKS+","+this._config.target+" "+d.LIST_ITEMS+","+this._config.target+" "+d.DROPDOWN_ITEMS,this._offsets=[],this._targets=[],this._activeTarget=null,this._scrollHeight=0,t(this._scrollElement).on(c.SCROLL,function(t){return i._process(t)}),this.refresh(),this._process()}var m=a.prototype;return m.refresh=function(){var e=this,n=this._scrollElement!==this._scrollElement.window?g:_,i="auto"===this._config.method?n:this._config.method,s=i===g?this._getScrollTop():0;this._offsets=[],this._targets=[],this._scrollHeight=this._getScrollHeight();t.makeArray(t(this._selector)).map(function(e){var n,r=o.getSelectorFromElement(e);if(r&&(n=t(r)[0]),n){var a=n.getBoundingClientRect();if(a.width||a.height)return[t(n)[i]().top+s,r]}return null}).filter(function(t){return t}).sort(function(t,e){return t[0]-e[0]}).forEach(function(t){e._offsets.push(t[0]),e._targets.push(t[1])})},m.dispose=function(){t.removeData(this._element,n),t(this._scrollElement).off(i),this._element=null,this._scrollElement=null,this._config=null,this._selector=null,this._offsets=null,this._targets=null,this._activeTarget=null,this._scrollHeight=null},m._getConfig=function(n){if("string"!=typeof(n=r({},l,n)).target){var i=t(n.target).attr("id");i||(i=o.getUID(e),t(n.target).attr("id",i)),n.target="#"+i}return o.typeCheckConfig(e,n,h),n},m._getScrollTop=function(){return this._scrollElement===window?this._scrollElement.pageYOffset:this._scrollElement.scrollTop},m._getScrollHeight=function(){return this._scrollElement.scrollHeight||Math.max(document.body.scrollHeight,document.documentElement.scrollHeight)},m._getOffsetHeight=function(){return this._scrollElement===window?window.innerHeight:this._scrollElement.getBoundingClientRect().height},m._process=function(){var t=this._getScrollTop()+this._config.offset,e=this._getScrollHeight(),n=this._config.offset+e-this._getOffsetHeight();if(this._scrollHeight!==e&&this.refresh(),t>=n){var i=this._targets[this._targets.length-1];this._activeTarget!==i&&this._activate(i)}else{if(this._activeTarget&&t0)return this._activeTarget=null,void this._clear();for(var s=this._offsets.length;s--;){this._activeTarget!==this._targets[s]&&t>=this._offsets[s]&&("undefined"==typeof this._offsets[s+1]||t=4)throw new Error("Bootstrap's JavaScript requires at least jQuery v1.9.1 but less than v4.0.0")}(e),t.Util=o,t.Alert=a,t.Button=l,t.Carousel=h,t.Collapse=c,t.Dropdown=u,t.Modal=f,t.Popover=_,t.Scrollspy=g,t.Tab=m,t.Tooltip=d,Object.defineProperty(t,"__esModule",{value:!0})}); +//# sourceMappingURL=bootstrap.min.js.map \ No newline at end of file diff --git a/www/static/js/chart.js b/www/static/js/chart.js new file mode 100644 index 000000000..45c2ff06d --- /dev/null +++ b/www/static/js/chart.js @@ -0,0 +1,18609 @@ + +/*! + * Chart.js + * http://chartjs.org/ + * Version: 2.7.1 + * + * Copyright 2017 Nick Downie + * Released under the MIT license + * https://github.com/chartjs/Chart.js/blob/master/LICENSE.md + */ +(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.Chart = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o lum2) { + return (lum1 + 0.05) / (lum2 + 0.05); + } + return (lum2 + 0.05) / (lum1 + 0.05); + }, + + level: function (color2) { + var contrastRatio = this.contrast(color2); + if (contrastRatio >= 7.1) { + return 'AAA'; + } + + return (contrastRatio >= 4.5) ? 'AA' : ''; + }, + + dark: function () { + // YIQ equation from http://24ways.org/2010/calculating-color-contrast + var rgb = this.values.rgb; + var yiq = (rgb[0] * 299 + rgb[1] * 587 + rgb[2] * 114) / 1000; + return yiq < 128; + }, + + light: function () { + return !this.dark(); + }, + + negate: function () { + var rgb = []; + for (var i = 0; i < 3; i++) { + rgb[i] = 255 - this.values.rgb[i]; + } + this.setValues('rgb', rgb); + return this; + }, + + lighten: function (ratio) { + var hsl = this.values.hsl; + hsl[2] += hsl[2] * ratio; + this.setValues('hsl', hsl); + return this; + }, + + darken: function (ratio) { + var hsl = this.values.hsl; + hsl[2] -= hsl[2] * ratio; + this.setValues('hsl', hsl); + return this; + }, + + saturate: function (ratio) { + var hsl = this.values.hsl; + hsl[1] += hsl[1] * ratio; + this.setValues('hsl', hsl); + return this; + }, + + desaturate: function (ratio) { + var hsl = this.values.hsl; + hsl[1] -= hsl[1] * ratio; + this.setValues('hsl', hsl); + return this; + }, + + whiten: function (ratio) { + var hwb = this.values.hwb; + hwb[1] += hwb[1] * ratio; + this.setValues('hwb', hwb); + return this; + }, + + blacken: function (ratio) { + var hwb = this.values.hwb; + hwb[2] += hwb[2] * ratio; + this.setValues('hwb', hwb); + return this; + }, + + greyscale: function () { + var rgb = this.values.rgb; + // http://en.wikipedia.org/wiki/Grayscale#Converting_color_to_grayscale + var val = rgb[0] * 0.3 + rgb[1] * 0.59 + rgb[2] * 0.11; + this.setValues('rgb', [val, val, val]); + return this; + }, + + clearer: function (ratio) { + var alpha = this.values.alpha; + this.setValues('alpha', alpha - (alpha * ratio)); + return this; + }, + + opaquer: function (ratio) { + var alpha = this.values.alpha; + this.setValues('alpha', alpha + (alpha * ratio)); + return this; + }, + + rotate: function (degrees) { + var hsl = this.values.hsl; + var hue = (hsl[0] + degrees) % 360; + hsl[0] = hue < 0 ? 360 + hue : hue; + this.setValues('hsl', hsl); + return this; + }, + + /** + * Ported from sass implementation in C + * https://github.com/sass/libsass/blob/0e6b4a2850092356aa3ece07c6b249f0221caced/functions.cpp#L209 + */ + mix: function (mixinColor, weight) { + var color1 = this; + var color2 = mixinColor; + var p = weight === undefined ? 0.5 : weight; + + var w = 2 * p - 1; + var a = color1.alpha() - color2.alpha(); + + var w1 = (((w * a === -1) ? w : (w + a) / (1 + w * a)) + 1) / 2.0; + var w2 = 1 - w1; + + return this + .rgb( + w1 * color1.red() + w2 * color2.red(), + w1 * color1.green() + w2 * color2.green(), + w1 * color1.blue() + w2 * color2.blue() + ) + .alpha(color1.alpha() * p + color2.alpha() * (1 - p)); + }, + + toJSON: function () { + return this.rgb(); + }, + + clone: function () { + // NOTE(SB): using node-clone creates a dependency to Buffer when using browserify, + // making the final build way to big to embed in Chart.js. So let's do it manually, + // assuming that values to clone are 1 dimension arrays containing only numbers, + // except 'alpha' which is a number. + var result = new Color(); + var source = this.values; + var target = result.values; + var value, type; + + for (var prop in source) { + if (source.hasOwnProperty(prop)) { + value = source[prop]; + type = ({}).toString.call(value); + if (type === '[object Array]') { + target[prop] = value.slice(0); + } else if (type === '[object Number]') { + target[prop] = value; + } else { + console.error('unexpected color value:', value); + } + } + } + + return result; + } +}; + +Color.prototype.spaces = { + rgb: ['red', 'green', 'blue'], + hsl: ['hue', 'saturation', 'lightness'], + hsv: ['hue', 'saturation', 'value'], + hwb: ['hue', 'whiteness', 'blackness'], + cmyk: ['cyan', 'magenta', 'yellow', 'black'] +}; + +Color.prototype.maxes = { + rgb: [255, 255, 255], + hsl: [360, 100, 100], + hsv: [360, 100, 100], + hwb: [360, 100, 100], + cmyk: [100, 100, 100, 100] +}; + +Color.prototype.getValues = function (space) { + var values = this.values; + var vals = {}; + + for (var i = 0; i < space.length; i++) { + vals[space.charAt(i)] = values[space][i]; + } + + if (values.alpha !== 1) { + vals.a = values.alpha; + } + + // {r: 255, g: 255, b: 255, a: 0.4} + return vals; +}; + +Color.prototype.setValues = function (space, vals) { + var values = this.values; + var spaces = this.spaces; + var maxes = this.maxes; + var alpha = 1; + var i; + + this.valid = true; + + if (space === 'alpha') { + alpha = vals; + } else if (vals.length) { + // [10, 10, 10] + values[space] = vals.slice(0, space.length); + alpha = vals[space.length]; + } else if (vals[space.charAt(0)] !== undefined) { + // {r: 10, g: 10, b: 10} + for (i = 0; i < space.length; i++) { + values[space][i] = vals[space.charAt(i)]; + } + + alpha = vals.a; + } else if (vals[spaces[space][0]] !== undefined) { + // {red: 10, green: 10, blue: 10} + var chans = spaces[space]; + + for (i = 0; i < space.length; i++) { + values[space][i] = vals[chans[i]]; + } + + alpha = vals.alpha; + } + + values.alpha = Math.max(0, Math.min(1, (alpha === undefined ? values.alpha : alpha))); + + if (space === 'alpha') { + return false; + } + + var capped; + + // cap values of the space prior converting all values + for (i = 0; i < space.length; i++) { + capped = Math.max(0, Math.min(maxes[space][i], values[space][i])); + values[space][i] = Math.round(capped); + } + + // convert to all the other color spaces + for (var sname in spaces) { + if (sname !== space) { + values[sname] = convert[space][sname](values[space]); + } + } + + return true; +}; + +Color.prototype.setSpace = function (space, args) { + var vals = args[0]; + + if (vals === undefined) { + // color.rgb() + return this.getValues(space); + } + + // color.rgb(10, 10, 10) + if (typeof vals === 'number') { + vals = Array.prototype.slice.call(args); + } + + this.setValues(space, vals); + return this; +}; + +Color.prototype.setChannel = function (space, index, val) { + var svalues = this.values[space]; + if (val === undefined) { + // color.red() + return svalues[index]; + } else if (val === svalues[index]) { + // color.red(color.red()) + return this; + } + + // color.red(100) + svalues[index] = val; + this.setValues(space, svalues); + + return this; +}; + +if (typeof window !== 'undefined') { + window.Color = Color; +} + +module.exports = Color; + +},{"1":1,"4":4}],3:[function(require,module,exports){ +/* MIT license */ + +module.exports = { + rgb2hsl: rgb2hsl, + rgb2hsv: rgb2hsv, + rgb2hwb: rgb2hwb, + rgb2cmyk: rgb2cmyk, + rgb2keyword: rgb2keyword, + rgb2xyz: rgb2xyz, + rgb2lab: rgb2lab, + rgb2lch: rgb2lch, + + hsl2rgb: hsl2rgb, + hsl2hsv: hsl2hsv, + hsl2hwb: hsl2hwb, + hsl2cmyk: hsl2cmyk, + hsl2keyword: hsl2keyword, + + hsv2rgb: hsv2rgb, + hsv2hsl: hsv2hsl, + hsv2hwb: hsv2hwb, + hsv2cmyk: hsv2cmyk, + hsv2keyword: hsv2keyword, + + hwb2rgb: hwb2rgb, + hwb2hsl: hwb2hsl, + hwb2hsv: hwb2hsv, + hwb2cmyk: hwb2cmyk, + hwb2keyword: hwb2keyword, + + cmyk2rgb: cmyk2rgb, + cmyk2hsl: cmyk2hsl, + cmyk2hsv: cmyk2hsv, + cmyk2hwb: cmyk2hwb, + cmyk2keyword: cmyk2keyword, + + keyword2rgb: keyword2rgb, + keyword2hsl: keyword2hsl, + keyword2hsv: keyword2hsv, + keyword2hwb: keyword2hwb, + keyword2cmyk: keyword2cmyk, + keyword2lab: keyword2lab, + keyword2xyz: keyword2xyz, + + xyz2rgb: xyz2rgb, + xyz2lab: xyz2lab, + xyz2lch: xyz2lch, + + lab2xyz: lab2xyz, + lab2rgb: lab2rgb, + lab2lch: lab2lch, + + lch2lab: lch2lab, + lch2xyz: lch2xyz, + lch2rgb: lch2rgb +} + + +function rgb2hsl(rgb) { + var r = rgb[0]/255, + g = rgb[1]/255, + b = rgb[2]/255, + min = Math.min(r, g, b), + max = Math.max(r, g, b), + delta = max - min, + h, s, l; + + if (max == min) + h = 0; + else if (r == max) + h = (g - b) / delta; + else if (g == max) + h = 2 + (b - r) / delta; + else if (b == max) + h = 4 + (r - g)/ delta; + + h = Math.min(h * 60, 360); + + if (h < 0) + h += 360; + + l = (min + max) / 2; + + if (max == min) + s = 0; + else if (l <= 0.5) + s = delta / (max + min); + else + s = delta / (2 - max - min); + + return [h, s * 100, l * 100]; +} + +function rgb2hsv(rgb) { + var r = rgb[0], + g = rgb[1], + b = rgb[2], + min = Math.min(r, g, b), + max = Math.max(r, g, b), + delta = max - min, + h, s, v; + + if (max == 0) + s = 0; + else + s = (delta/max * 1000)/10; + + if (max == min) + h = 0; + else if (r == max) + h = (g - b) / delta; + else if (g == max) + h = 2 + (b - r) / delta; + else if (b == max) + h = 4 + (r - g) / delta; + + h = Math.min(h * 60, 360); + + if (h < 0) + h += 360; + + v = ((max / 255) * 1000) / 10; + + return [h, s, v]; +} + +function rgb2hwb(rgb) { + var r = rgb[0], + g = rgb[1], + b = rgb[2], + h = rgb2hsl(rgb)[0], + w = 1/255 * Math.min(r, Math.min(g, b)), + b = 1 - 1/255 * Math.max(r, Math.max(g, b)); + + return [h, w * 100, b * 100]; +} + +function rgb2cmyk(rgb) { + var r = rgb[0] / 255, + g = rgb[1] / 255, + b = rgb[2] / 255, + c, m, y, k; + + k = Math.min(1 - r, 1 - g, 1 - b); + c = (1 - r - k) / (1 - k) || 0; + m = (1 - g - k) / (1 - k) || 0; + y = (1 - b - k) / (1 - k) || 0; + return [c * 100, m * 100, y * 100, k * 100]; +} + +function rgb2keyword(rgb) { + return reverseKeywords[JSON.stringify(rgb)]; +} + +function rgb2xyz(rgb) { + var r = rgb[0] / 255, + g = rgb[1] / 255, + b = rgb[2] / 255; + + // assume sRGB + r = r > 0.04045 ? Math.pow(((r + 0.055) / 1.055), 2.4) : (r / 12.92); + g = g > 0.04045 ? Math.pow(((g + 0.055) / 1.055), 2.4) : (g / 12.92); + b = b > 0.04045 ? Math.pow(((b + 0.055) / 1.055), 2.4) : (b / 12.92); + + var x = (r * 0.4124) + (g * 0.3576) + (b * 0.1805); + var y = (r * 0.2126) + (g * 0.7152) + (b * 0.0722); + var z = (r * 0.0193) + (g * 0.1192) + (b * 0.9505); + + return [x * 100, y *100, z * 100]; +} + +function rgb2lab(rgb) { + var xyz = rgb2xyz(rgb), + x = xyz[0], + y = xyz[1], + z = xyz[2], + l, a, b; + + x /= 95.047; + y /= 100; + z /= 108.883; + + x = x > 0.008856 ? Math.pow(x, 1/3) : (7.787 * x) + (16 / 116); + y = y > 0.008856 ? Math.pow(y, 1/3) : (7.787 * y) + (16 / 116); + z = z > 0.008856 ? Math.pow(z, 1/3) : (7.787 * z) + (16 / 116); + + l = (116 * y) - 16; + a = 500 * (x - y); + b = 200 * (y - z); + + return [l, a, b]; +} + +function rgb2lch(args) { + return lab2lch(rgb2lab(args)); +} + +function hsl2rgb(hsl) { + var h = hsl[0] / 360, + s = hsl[1] / 100, + l = hsl[2] / 100, + t1, t2, t3, rgb, val; + + if (s == 0) { + val = l * 255; + return [val, val, val]; + } + + if (l < 0.5) + t2 = l * (1 + s); + else + t2 = l + s - l * s; + t1 = 2 * l - t2; + + rgb = [0, 0, 0]; + for (var i = 0; i < 3; i++) { + t3 = h + 1 / 3 * - (i - 1); + t3 < 0 && t3++; + t3 > 1 && t3--; + + if (6 * t3 < 1) + val = t1 + (t2 - t1) * 6 * t3; + else if (2 * t3 < 1) + val = t2; + else if (3 * t3 < 2) + val = t1 + (t2 - t1) * (2 / 3 - t3) * 6; + else + val = t1; + + rgb[i] = val * 255; + } + + return rgb; +} + +function hsl2hsv(hsl) { + var h = hsl[0], + s = hsl[1] / 100, + l = hsl[2] / 100, + sv, v; + + if(l === 0) { + // no need to do calc on black + // also avoids divide by 0 error + return [0, 0, 0]; + } + + l *= 2; + s *= (l <= 1) ? l : 2 - l; + v = (l + s) / 2; + sv = (2 * s) / (l + s); + return [h, sv * 100, v * 100]; +} + +function hsl2hwb(args) { + return rgb2hwb(hsl2rgb(args)); +} + +function hsl2cmyk(args) { + return rgb2cmyk(hsl2rgb(args)); +} + +function hsl2keyword(args) { + return rgb2keyword(hsl2rgb(args)); +} + + +function hsv2rgb(hsv) { + var h = hsv[0] / 60, + s = hsv[1] / 100, + v = hsv[2] / 100, + hi = Math.floor(h) % 6; + + var f = h - Math.floor(h), + p = 255 * v * (1 - s), + q = 255 * v * (1 - (s * f)), + t = 255 * v * (1 - (s * (1 - f))), + v = 255 * v; + + switch(hi) { + case 0: + return [v, t, p]; + case 1: + return [q, v, p]; + case 2: + return [p, v, t]; + case 3: + return [p, q, v]; + case 4: + return [t, p, v]; + case 5: + return [v, p, q]; + } +} + +function hsv2hsl(hsv) { + var h = hsv[0], + s = hsv[1] / 100, + v = hsv[2] / 100, + sl, l; + + l = (2 - s) * v; + sl = s * v; + sl /= (l <= 1) ? l : 2 - l; + sl = sl || 0; + l /= 2; + return [h, sl * 100, l * 100]; +} + +function hsv2hwb(args) { + return rgb2hwb(hsv2rgb(args)) +} + +function hsv2cmyk(args) { + return rgb2cmyk(hsv2rgb(args)); +} + +function hsv2keyword(args) { + return rgb2keyword(hsv2rgb(args)); +} + +// http://dev.w3.org/csswg/css-color/#hwb-to-rgb +function hwb2rgb(hwb) { + var h = hwb[0] / 360, + wh = hwb[1] / 100, + bl = hwb[2] / 100, + ratio = wh + bl, + i, v, f, n; + + // wh + bl cant be > 1 + if (ratio > 1) { + wh /= ratio; + bl /= ratio; + } + + i = Math.floor(6 * h); + v = 1 - bl; + f = 6 * h - i; + if ((i & 0x01) != 0) { + f = 1 - f; + } + n = wh + f * (v - wh); // linear interpolation + + switch (i) { + default: + case 6: + case 0: r = v; g = n; b = wh; break; + case 1: r = n; g = v; b = wh; break; + case 2: r = wh; g = v; b = n; break; + case 3: r = wh; g = n; b = v; break; + case 4: r = n; g = wh; b = v; break; + case 5: r = v; g = wh; b = n; break; + } + + return [r * 255, g * 255, b * 255]; +} + +function hwb2hsl(args) { + return rgb2hsl(hwb2rgb(args)); +} + +function hwb2hsv(args) { + return rgb2hsv(hwb2rgb(args)); +} + +function hwb2cmyk(args) { + return rgb2cmyk(hwb2rgb(args)); +} + +function hwb2keyword(args) { + return rgb2keyword(hwb2rgb(args)); +} + +function cmyk2rgb(cmyk) { + var c = cmyk[0] / 100, + m = cmyk[1] / 100, + y = cmyk[2] / 100, + k = cmyk[3] / 100, + r, g, b; + + r = 1 - Math.min(1, c * (1 - k) + k); + g = 1 - Math.min(1, m * (1 - k) + k); + b = 1 - Math.min(1, y * (1 - k) + k); + return [r * 255, g * 255, b * 255]; +} + +function cmyk2hsl(args) { + return rgb2hsl(cmyk2rgb(args)); +} + +function cmyk2hsv(args) { + return rgb2hsv(cmyk2rgb(args)); +} + +function cmyk2hwb(args) { + return rgb2hwb(cmyk2rgb(args)); +} + +function cmyk2keyword(args) { + return rgb2keyword(cmyk2rgb(args)); +} + + +function xyz2rgb(xyz) { + var x = xyz[0] / 100, + y = xyz[1] / 100, + z = xyz[2] / 100, + r, g, b; + + r = (x * 3.2406) + (y * -1.5372) + (z * -0.4986); + g = (x * -0.9689) + (y * 1.8758) + (z * 0.0415); + b = (x * 0.0557) + (y * -0.2040) + (z * 1.0570); + + // assume sRGB + r = r > 0.0031308 ? ((1.055 * Math.pow(r, 1.0 / 2.4)) - 0.055) + : r = (r * 12.92); + + g = g > 0.0031308 ? ((1.055 * Math.pow(g, 1.0 / 2.4)) - 0.055) + : g = (g * 12.92); + + b = b > 0.0031308 ? ((1.055 * Math.pow(b, 1.0 / 2.4)) - 0.055) + : b = (b * 12.92); + + r = Math.min(Math.max(0, r), 1); + g = Math.min(Math.max(0, g), 1); + b = Math.min(Math.max(0, b), 1); + + return [r * 255, g * 255, b * 255]; +} + +function xyz2lab(xyz) { + var x = xyz[0], + y = xyz[1], + z = xyz[2], + l, a, b; + + x /= 95.047; + y /= 100; + z /= 108.883; + + x = x > 0.008856 ? Math.pow(x, 1/3) : (7.787 * x) + (16 / 116); + y = y > 0.008856 ? Math.pow(y, 1/3) : (7.787 * y) + (16 / 116); + z = z > 0.008856 ? Math.pow(z, 1/3) : (7.787 * z) + (16 / 116); + + l = (116 * y) - 16; + a = 500 * (x - y); + b = 200 * (y - z); + + return [l, a, b]; +} + +function xyz2lch(args) { + return lab2lch(xyz2lab(args)); +} + +function lab2xyz(lab) { + var l = lab[0], + a = lab[1], + b = lab[2], + x, y, z, y2; + + if (l <= 8) { + y = (l * 100) / 903.3; + y2 = (7.787 * (y / 100)) + (16 / 116); + } else { + y = 100 * Math.pow((l + 16) / 116, 3); + y2 = Math.pow(y / 100, 1/3); + } + + x = x / 95.047 <= 0.008856 ? x = (95.047 * ((a / 500) + y2 - (16 / 116))) / 7.787 : 95.047 * Math.pow((a / 500) + y2, 3); + + z = z / 108.883 <= 0.008859 ? z = (108.883 * (y2 - (b / 200) - (16 / 116))) / 7.787 : 108.883 * Math.pow(y2 - (b / 200), 3); + + return [x, y, z]; +} + +function lab2lch(lab) { + var l = lab[0], + a = lab[1], + b = lab[2], + hr, h, c; + + hr = Math.atan2(b, a); + h = hr * 360 / 2 / Math.PI; + if (h < 0) { + h += 360; + } + c = Math.sqrt(a * a + b * b); + return [l, c, h]; +} + +function lab2rgb(args) { + return xyz2rgb(lab2xyz(args)); +} + +function lch2lab(lch) { + var l = lch[0], + c = lch[1], + h = lch[2], + a, b, hr; + + hr = h / 360 * 2 * Math.PI; + a = c * Math.cos(hr); + b = c * Math.sin(hr); + return [l, a, b]; +} + +function lch2xyz(args) { + return lab2xyz(lch2lab(args)); +} + +function lch2rgb(args) { + return lab2rgb(lch2lab(args)); +} + +function keyword2rgb(keyword) { + return cssKeywords[keyword]; +} + +function keyword2hsl(args) { + return rgb2hsl(keyword2rgb(args)); +} + +function keyword2hsv(args) { + return rgb2hsv(keyword2rgb(args)); +} + +function keyword2hwb(args) { + return rgb2hwb(keyword2rgb(args)); +} + +function keyword2cmyk(args) { + return rgb2cmyk(keyword2rgb(args)); +} + +function keyword2lab(args) { + return rgb2lab(keyword2rgb(args)); +} + +function keyword2xyz(args) { + return rgb2xyz(keyword2rgb(args)); +} + +var cssKeywords = { + aliceblue: [240,248,255], + antiquewhite: [250,235,215], + aqua: [0,255,255], + aquamarine: [127,255,212], + azure: [240,255,255], + beige: [245,245,220], + bisque: [255,228,196], + black: [0,0,0], + blanchedalmond: [255,235,205], + blue: [0,0,255], + blueviolet: [138,43,226], + brown: [165,42,42], + burlywood: [222,184,135], + cadetblue: [95,158,160], + chartreuse: [127,255,0], + chocolate: [210,105,30], + coral: [255,127,80], + cornflowerblue: [100,149,237], + cornsilk: [255,248,220], + crimson: [220,20,60], + cyan: [0,255,255], + darkblue: [0,0,139], + darkcyan: [0,139,139], + darkgoldenrod: [184,134,11], + darkgray: [169,169,169], + darkgreen: [0,100,0], + darkgrey: [169,169,169], + darkkhaki: [189,183,107], + darkmagenta: [139,0,139], + darkolivegreen: [85,107,47], + darkorange: [255,140,0], + darkorchid: [153,50,204], + darkred: [139,0,0], + darksalmon: [233,150,122], + darkseagreen: [143,188,143], + darkslateblue: [72,61,139], + darkslategray: [47,79,79], + darkslategrey: [47,79,79], + darkturquoise: [0,206,209], + darkviolet: [148,0,211], + deeppink: [255,20,147], + deepskyblue: [0,191,255], + dimgray: [105,105,105], + dimgrey: [105,105,105], + dodgerblue: [30,144,255], + firebrick: [178,34,34], + floralwhite: [255,250,240], + forestgreen: [34,139,34], + fuchsia: [255,0,255], + gainsboro: [220,220,220], + ghostwhite: [248,248,255], + gold: [255,215,0], + goldenrod: [218,165,32], + gray: [128,128,128], + green: [0,128,0], + greenyellow: [173,255,47], + grey: [128,128,128], + honeydew: [240,255,240], + hotpink: [255,105,180], + indianred: [205,92,92], + indigo: [75,0,130], + ivory: [255,255,240], + khaki: [240,230,140], + lavender: [230,230,250], + lavenderblush: [255,240,245], + lawngreen: [124,252,0], + lemonchiffon: [255,250,205], + lightblue: [173,216,230], + lightcoral: [240,128,128], + lightcyan: [224,255,255], + lightgoldenrodyellow: [250,250,210], + lightgray: [211,211,211], + lightgreen: [144,238,144], + lightgrey: [211,211,211], + lightpink: [255,182,193], + lightsalmon: [255,160,122], + lightseagreen: [32,178,170], + lightskyblue: [135,206,250], + lightslategray: [119,136,153], + lightslategrey: [119,136,153], + lightsteelblue: [176,196,222], + lightyellow: [255,255,224], + lime: [0,255,0], + limegreen: [50,205,50], + linen: [250,240,230], + magenta: [255,0,255], + maroon: [128,0,0], + mediumaquamarine: [102,205,170], + mediumblue: [0,0,205], + mediumorchid: [186,85,211], + mediumpurple: [147,112,219], + mediumseagreen: [60,179,113], + mediumslateblue: [123,104,238], + mediumspringgreen: [0,250,154], + mediumturquoise: [72,209,204], + mediumvioletred: [199,21,133], + midnightblue: [25,25,112], + mintcream: [245,255,250], + mistyrose: [255,228,225], + moccasin: [255,228,181], + navajowhite: [255,222,173], + navy: [0,0,128], + oldlace: [253,245,230], + olive: [128,128,0], + olivedrab: [107,142,35], + orange: [255,165,0], + orangered: [255,69,0], + orchid: [218,112,214], + palegoldenrod: [238,232,170], + palegreen: [152,251,152], + paleturquoise: [175,238,238], + palevioletred: [219,112,147], + papayawhip: [255,239,213], + peachpuff: [255,218,185], + peru: [205,133,63], + pink: [255,192,203], + plum: [221,160,221], + powderblue: [176,224,230], + purple: [128,0,128], + rebeccapurple: [102, 51, 153], + red: [255,0,0], + rosybrown: [188,143,143], + royalblue: [65,105,225], + saddlebrown: [139,69,19], + salmon: [250,128,114], + sandybrown: [244,164,96], + seagreen: [46,139,87], + seashell: [255,245,238], + sienna: [160,82,45], + silver: [192,192,192], + skyblue: [135,206,235], + slateblue: [106,90,205], + slategray: [112,128,144], + slategrey: [112,128,144], + snow: [255,250,250], + springgreen: [0,255,127], + steelblue: [70,130,180], + tan: [210,180,140], + teal: [0,128,128], + thistle: [216,191,216], + tomato: [255,99,71], + turquoise: [64,224,208], + violet: [238,130,238], + wheat: [245,222,179], + white: [255,255,255], + whitesmoke: [245,245,245], + yellow: [255,255,0], + yellowgreen: [154,205,50] +}; + +var reverseKeywords = {}; +for (var key in cssKeywords) { + reverseKeywords[JSON.stringify(cssKeywords[key])] = key; +} + +},{}],4:[function(require,module,exports){ +var conversions = require(3); + +var convert = function() { + return new Converter(); +} + +for (var func in conversions) { + // export Raw versions + convert[func + "Raw"] = (function(func) { + // accept array or plain args + return function(arg) { + if (typeof arg == "number") + arg = Array.prototype.slice.call(arguments); + return conversions[func](arg); + } + })(func); + + var pair = /(\w+)2(\w+)/.exec(func), + from = pair[1], + to = pair[2]; + + // export rgb2hsl and ["rgb"]["hsl"] + convert[from] = convert[from] || {}; + + convert[from][to] = convert[func] = (function(func) { + return function(arg) { + if (typeof arg == "number") + arg = Array.prototype.slice.call(arguments); + + var val = conversions[func](arg); + if (typeof val == "string" || val === undefined) + return val; // keyword + + for (var i = 0; i < val.length; i++) + val[i] = Math.round(val[i]); + return val; + } + })(func); +} + + +/* Converter does lazy conversion and caching */ +var Converter = function() { + this.convs = {}; +}; + +/* Either get the values for a space or + set the values for a space, depending on args */ +Converter.prototype.routeSpace = function(space, args) { + var values = args[0]; + if (values === undefined) { + // color.rgb() + return this.getValues(space); + } + // color.rgb(10, 10, 10) + if (typeof values == "number") { + values = Array.prototype.slice.call(args); + } + + return this.setValues(space, values); +}; + +/* Set the values for a space, invalidating cache */ +Converter.prototype.setValues = function(space, values) { + this.space = space; + this.convs = {}; + this.convs[space] = values; + return this; +}; + +/* Get the values for a space. If there's already + a conversion for the space, fetch it, otherwise + compute it */ +Converter.prototype.getValues = function(space) { + var vals = this.convs[space]; + if (!vals) { + var fspace = this.space, + from = this.convs[fspace]; + vals = convert[fspace][space](from); + + this.convs[space] = vals; + } + return vals; +}; + +["rgb", "hsl", "hsv", "cmyk", "keyword"].forEach(function(space) { + Converter.prototype[space] = function(vals) { + return this.routeSpace(space, arguments); + } +}); + +module.exports = convert; +},{"3":3}],5:[function(require,module,exports){ +'use strict' + +module.exports = { + "aliceblue": [240, 248, 255], + "antiquewhite": [250, 235, 215], + "aqua": [0, 255, 255], + "aquamarine": [127, 255, 212], + "azure": [240, 255, 255], + "beige": [245, 245, 220], + "bisque": [255, 228, 196], + "black": [0, 0, 0], + "blanchedalmond": [255, 235, 205], + "blue": [0, 0, 255], + "blueviolet": [138, 43, 226], + "brown": [165, 42, 42], + "burlywood": [222, 184, 135], + "cadetblue": [95, 158, 160], + "chartreuse": [127, 255, 0], + "chocolate": [210, 105, 30], + "coral": [255, 127, 80], + "cornflowerblue": [100, 149, 237], + "cornsilk": [255, 248, 220], + "crimson": [220, 20, 60], + "cyan": [0, 255, 255], + "darkblue": [0, 0, 139], + "darkcyan": [0, 139, 139], + "darkgoldenrod": [184, 134, 11], + "darkgray": [169, 169, 169], + "darkgreen": [0, 100, 0], + "darkgrey": [169, 169, 169], + "darkkhaki": [189, 183, 107], + "darkmagenta": [139, 0, 139], + "darkolivegreen": [85, 107, 47], + "darkorange": [255, 140, 0], + "darkorchid": [153, 50, 204], + "darkred": [139, 0, 0], + "darksalmon": [233, 150, 122], + "darkseagreen": [143, 188, 143], + "darkslateblue": [72, 61, 139], + "darkslategray": [47, 79, 79], + "darkslategrey": [47, 79, 79], + "darkturquoise": [0, 206, 209], + "darkviolet": [148, 0, 211], + "deeppink": [255, 20, 147], + "deepskyblue": [0, 191, 255], + "dimgray": [105, 105, 105], + "dimgrey": [105, 105, 105], + "dodgerblue": [30, 144, 255], + "firebrick": [178, 34, 34], + "floralwhite": [255, 250, 240], + "forestgreen": [34, 139, 34], + "fuchsia": [255, 0, 255], + "gainsboro": [220, 220, 220], + "ghostwhite": [248, 248, 255], + "gold": [255, 215, 0], + "goldenrod": [218, 165, 32], + "gray": [128, 128, 128], + "green": [0, 128, 0], + "greenyellow": [173, 255, 47], + "grey": [128, 128, 128], + "honeydew": [240, 255, 240], + "hotpink": [255, 105, 180], + "indianred": [205, 92, 92], + "indigo": [75, 0, 130], + "ivory": [255, 255, 240], + "khaki": [240, 230, 140], + "lavender": [230, 230, 250], + "lavenderblush": [255, 240, 245], + "lawngreen": [124, 252, 0], + "lemonchiffon": [255, 250, 205], + "lightblue": [173, 216, 230], + "lightcoral": [240, 128, 128], + "lightcyan": [224, 255, 255], + "lightgoldenrodyellow": [250, 250, 210], + "lightgray": [211, 211, 211], + "lightgreen": [144, 238, 144], + "lightgrey": [211, 211, 211], + "lightpink": [255, 182, 193], + "lightsalmon": [255, 160, 122], + "lightseagreen": [32, 178, 170], + "lightskyblue": [135, 206, 250], + "lightslategray": [119, 136, 153], + "lightslategrey": [119, 136, 153], + "lightsteelblue": [176, 196, 222], + "lightyellow": [255, 255, 224], + "lime": [0, 255, 0], + "limegreen": [50, 205, 50], + "linen": [250, 240, 230], + "magenta": [255, 0, 255], + "maroon": [128, 0, 0], + "mediumaquamarine": [102, 205, 170], + "mediumblue": [0, 0, 205], + "mediumorchid": [186, 85, 211], + "mediumpurple": [147, 112, 219], + "mediumseagreen": [60, 179, 113], + "mediumslateblue": [123, 104, 238], + "mediumspringgreen": [0, 250, 154], + "mediumturquoise": [72, 209, 204], + "mediumvioletred": [199, 21, 133], + "midnightblue": [25, 25, 112], + "mintcream": [245, 255, 250], + "mistyrose": [255, 228, 225], + "moccasin": [255, 228, 181], + "navajowhite": [255, 222, 173], + "navy": [0, 0, 128], + "oldlace": [253, 245, 230], + "olive": [128, 128, 0], + "olivedrab": [107, 142, 35], + "orange": [255, 165, 0], + "orangered": [255, 69, 0], + "orchid": [218, 112, 214], + "palegoldenrod": [238, 232, 170], + "palegreen": [152, 251, 152], + "paleturquoise": [175, 238, 238], + "palevioletred": [219, 112, 147], + "papayawhip": [255, 239, 213], + "peachpuff": [255, 218, 185], + "peru": [205, 133, 63], + "pink": [255, 192, 203], + "plum": [221, 160, 221], + "powderblue": [176, 224, 230], + "purple": [128, 0, 128], + "rebeccapurple": [102, 51, 153], + "red": [255, 0, 0], + "rosybrown": [188, 143, 143], + "royalblue": [65, 105, 225], + "saddlebrown": [139, 69, 19], + "salmon": [250, 128, 114], + "sandybrown": [244, 164, 96], + "seagreen": [46, 139, 87], + "seashell": [255, 245, 238], + "sienna": [160, 82, 45], + "silver": [192, 192, 192], + "skyblue": [135, 206, 235], + "slateblue": [106, 90, 205], + "slategray": [112, 128, 144], + "slategrey": [112, 128, 144], + "snow": [255, 250, 250], + "springgreen": [0, 255, 127], + "steelblue": [70, 130, 180], + "tan": [210, 180, 140], + "teal": [0, 128, 128], + "thistle": [216, 191, 216], + "tomato": [255, 99, 71], + "turquoise": [64, 224, 208], + "violet": [238, 130, 238], + "wheat": [245, 222, 179], + "white": [255, 255, 255], + "whitesmoke": [245, 245, 245], + "yellow": [255, 255, 0], + "yellowgreen": [154, 205, 50] +}; + +},{}],6:[function(require,module,exports){ +//! moment.js +//! version : 2.18.1 +//! authors : Tim Wood, Iskren Chernev, Moment.js contributors +//! license : MIT +//! momentjs.com + +;(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : + typeof define === 'function' && define.amd ? define(factory) : + global.moment = factory() +}(this, (function () { 'use strict'; + +var hookCallback; + +function hooks () { + return hookCallback.apply(null, arguments); +} + +// This is done to register the method called with moment() +// without creating circular dependencies. +function setHookCallback (callback) { + hookCallback = callback; +} + +function isArray(input) { + return input instanceof Array || Object.prototype.toString.call(input) === '[object Array]'; +} + +function isObject(input) { + // IE8 will treat undefined and null as object if it wasn't for + // input != null + return input != null && Object.prototype.toString.call(input) === '[object Object]'; +} + +function isObjectEmpty(obj) { + var k; + for (k in obj) { + // even if its not own property I'd still call it non-empty + return false; + } + return true; +} + +function isUndefined(input) { + return input === void 0; +} + +function isNumber(input) { + return typeof input === 'number' || Object.prototype.toString.call(input) === '[object Number]'; +} + +function isDate(input) { + return input instanceof Date || Object.prototype.toString.call(input) === '[object Date]'; +} + +function map(arr, fn) { + var res = [], i; + for (i = 0; i < arr.length; ++i) { + res.push(fn(arr[i], i)); + } + return res; +} + +function hasOwnProp(a, b) { + return Object.prototype.hasOwnProperty.call(a, b); +} + +function extend(a, b) { + for (var i in b) { + if (hasOwnProp(b, i)) { + a[i] = b[i]; + } + } + + if (hasOwnProp(b, 'toString')) { + a.toString = b.toString; + } + + if (hasOwnProp(b, 'valueOf')) { + a.valueOf = b.valueOf; + } + + return a; +} + +function createUTC (input, format, locale, strict) { + return createLocalOrUTC(input, format, locale, strict, true).utc(); +} + +function defaultParsingFlags() { + // We need to deep clone this object. + return { + empty : false, + unusedTokens : [], + unusedInput : [], + overflow : -2, + charsLeftOver : 0, + nullInput : false, + invalidMonth : null, + invalidFormat : false, + userInvalidated : false, + iso : false, + parsedDateParts : [], + meridiem : null, + rfc2822 : false, + weekdayMismatch : false + }; +} + +function getParsingFlags(m) { + if (m._pf == null) { + m._pf = defaultParsingFlags(); + } + return m._pf; +} + +var some; +if (Array.prototype.some) { + some = Array.prototype.some; +} else { + some = function (fun) { + var t = Object(this); + var len = t.length >>> 0; + + for (var i = 0; i < len; i++) { + if (i in t && fun.call(this, t[i], i, t)) { + return true; + } + } + + return false; + }; +} + +var some$1 = some; + +function isValid(m) { + if (m._isValid == null) { + var flags = getParsingFlags(m); + var parsedParts = some$1.call(flags.parsedDateParts, function (i) { + return i != null; + }); + var isNowValid = !isNaN(m._d.getTime()) && + flags.overflow < 0 && + !flags.empty && + !flags.invalidMonth && + !flags.invalidWeekday && + !flags.nullInput && + !flags.invalidFormat && + !flags.userInvalidated && + (!flags.meridiem || (flags.meridiem && parsedParts)); + + if (m._strict) { + isNowValid = isNowValid && + flags.charsLeftOver === 0 && + flags.unusedTokens.length === 0 && + flags.bigHour === undefined; + } + + if (Object.isFrozen == null || !Object.isFrozen(m)) { + m._isValid = isNowValid; + } + else { + return isNowValid; + } + } + return m._isValid; +} + +function createInvalid (flags) { + var m = createUTC(NaN); + if (flags != null) { + extend(getParsingFlags(m), flags); + } + else { + getParsingFlags(m).userInvalidated = true; + } + + return m; +} + +// Plugins that add properties should also add the key here (null value), +// so we can properly clone ourselves. +var momentProperties = hooks.momentProperties = []; + +function copyConfig(to, from) { + var i, prop, val; + + if (!isUndefined(from._isAMomentObject)) { + to._isAMomentObject = from._isAMomentObject; + } + if (!isUndefined(from._i)) { + to._i = from._i; + } + if (!isUndefined(from._f)) { + to._f = from._f; + } + if (!isUndefined(from._l)) { + to._l = from._l; + } + if (!isUndefined(from._strict)) { + to._strict = from._strict; + } + if (!isUndefined(from._tzm)) { + to._tzm = from._tzm; + } + if (!isUndefined(from._isUTC)) { + to._isUTC = from._isUTC; + } + if (!isUndefined(from._offset)) { + to._offset = from._offset; + } + if (!isUndefined(from._pf)) { + to._pf = getParsingFlags(from); + } + if (!isUndefined(from._locale)) { + to._locale = from._locale; + } + + if (momentProperties.length > 0) { + for (i = 0; i < momentProperties.length; i++) { + prop = momentProperties[i]; + val = from[prop]; + if (!isUndefined(val)) { + to[prop] = val; + } + } + } + + return to; +} + +var updateInProgress = false; + +// Moment prototype object +function Moment(config) { + copyConfig(this, config); + this._d = new Date(config._d != null ? config._d.getTime() : NaN); + if (!this.isValid()) { + this._d = new Date(NaN); + } + // Prevent infinite loop in case updateOffset creates new moment + // objects. + if (updateInProgress === false) { + updateInProgress = true; + hooks.updateOffset(this); + updateInProgress = false; + } +} + +function isMoment (obj) { + return obj instanceof Moment || (obj != null && obj._isAMomentObject != null); +} + +function absFloor (number) { + if (number < 0) { + // -0 -> 0 + return Math.ceil(number) || 0; + } else { + return Math.floor(number); + } +} + +function toInt(argumentForCoercion) { + var coercedNumber = +argumentForCoercion, + value = 0; + + if (coercedNumber !== 0 && isFinite(coercedNumber)) { + value = absFloor(coercedNumber); + } + + return value; +} + +// compare two arrays, return the number of differences +function compareArrays(array1, array2, dontConvert) { + var len = Math.min(array1.length, array2.length), + lengthDiff = Math.abs(array1.length - array2.length), + diffs = 0, + i; + for (i = 0; i < len; i++) { + if ((dontConvert && array1[i] !== array2[i]) || + (!dontConvert && toInt(array1[i]) !== toInt(array2[i]))) { + diffs++; + } + } + return diffs + lengthDiff; +} + +function warn(msg) { + if (hooks.suppressDeprecationWarnings === false && + (typeof console !== 'undefined') && console.warn) { + console.warn('Deprecation warning: ' + msg); + } +} + +function deprecate(msg, fn) { + var firstTime = true; + + return extend(function () { + if (hooks.deprecationHandler != null) { + hooks.deprecationHandler(null, msg); + } + if (firstTime) { + var args = []; + var arg; + for (var i = 0; i < arguments.length; i++) { + arg = ''; + if (typeof arguments[i] === 'object') { + arg += '\n[' + i + '] '; + for (var key in arguments[0]) { + arg += key + ': ' + arguments[0][key] + ', '; + } + arg = arg.slice(0, -2); // Remove trailing comma and space + } else { + arg = arguments[i]; + } + args.push(arg); + } + warn(msg + '\nArguments: ' + Array.prototype.slice.call(args).join('') + '\n' + (new Error()).stack); + firstTime = false; + } + return fn.apply(this, arguments); + }, fn); +} + +var deprecations = {}; + +function deprecateSimple(name, msg) { + if (hooks.deprecationHandler != null) { + hooks.deprecationHandler(name, msg); + } + if (!deprecations[name]) { + warn(msg); + deprecations[name] = true; + } +} + +hooks.suppressDeprecationWarnings = false; +hooks.deprecationHandler = null; + +function isFunction(input) { + return input instanceof Function || Object.prototype.toString.call(input) === '[object Function]'; +} + +function set (config) { + var prop, i; + for (i in config) { + prop = config[i]; + if (isFunction(prop)) { + this[i] = prop; + } else { + this['_' + i] = prop; + } + } + this._config = config; + // Lenient ordinal parsing accepts just a number in addition to + // number + (possibly) stuff coming from _dayOfMonthOrdinalParse. + // TODO: Remove "ordinalParse" fallback in next major release. + this._dayOfMonthOrdinalParseLenient = new RegExp( + (this._dayOfMonthOrdinalParse.source || this._ordinalParse.source) + + '|' + (/\d{1,2}/).source); +} + +function mergeConfigs(parentConfig, childConfig) { + var res = extend({}, parentConfig), prop; + for (prop in childConfig) { + if (hasOwnProp(childConfig, prop)) { + if (isObject(parentConfig[prop]) && isObject(childConfig[prop])) { + res[prop] = {}; + extend(res[prop], parentConfig[prop]); + extend(res[prop], childConfig[prop]); + } else if (childConfig[prop] != null) { + res[prop] = childConfig[prop]; + } else { + delete res[prop]; + } + } + } + for (prop in parentConfig) { + if (hasOwnProp(parentConfig, prop) && + !hasOwnProp(childConfig, prop) && + isObject(parentConfig[prop])) { + // make sure changes to properties don't modify parent config + res[prop] = extend({}, res[prop]); + } + } + return res; +} + +function Locale(config) { + if (config != null) { + this.set(config); + } +} + +var keys; + +if (Object.keys) { + keys = Object.keys; +} else { + keys = function (obj) { + var i, res = []; + for (i in obj) { + if (hasOwnProp(obj, i)) { + res.push(i); + } + } + return res; + }; +} + +var keys$1 = keys; + +var defaultCalendar = { + sameDay : '[Today at] LT', + nextDay : '[Tomorrow at] LT', + nextWeek : 'dddd [at] LT', + lastDay : '[Yesterday at] LT', + lastWeek : '[Last] dddd [at] LT', + sameElse : 'L' +}; + +function calendar (key, mom, now) { + var output = this._calendar[key] || this._calendar['sameElse']; + return isFunction(output) ? output.call(mom, now) : output; +} + +var defaultLongDateFormat = { + LTS : 'h:mm:ss A', + LT : 'h:mm A', + L : 'MM/DD/YYYY', + LL : 'MMMM D, YYYY', + LLL : 'MMMM D, YYYY h:mm A', + LLLL : 'dddd, MMMM D, YYYY h:mm A' +}; + +function longDateFormat (key) { + var format = this._longDateFormat[key], + formatUpper = this._longDateFormat[key.toUpperCase()]; + + if (format || !formatUpper) { + return format; + } + + this._longDateFormat[key] = formatUpper.replace(/MMMM|MM|DD|dddd/g, function (val) { + return val.slice(1); + }); + + return this._longDateFormat[key]; +} + +var defaultInvalidDate = 'Invalid date'; + +function invalidDate () { + return this._invalidDate; +} + +var defaultOrdinal = '%d'; +var defaultDayOfMonthOrdinalParse = /\d{1,2}/; + +function ordinal (number) { + return this._ordinal.replace('%d', number); +} + +var defaultRelativeTime = { + future : 'in %s', + past : '%s ago', + s : 'a few seconds', + ss : '%d seconds', + m : 'a minute', + mm : '%d minutes', + h : 'an hour', + hh : '%d hours', + d : 'a day', + dd : '%d days', + M : 'a month', + MM : '%d months', + y : 'a year', + yy : '%d years' +}; + +function relativeTime (number, withoutSuffix, string, isFuture) { + var output = this._relativeTime[string]; + return (isFunction(output)) ? + output(number, withoutSuffix, string, isFuture) : + output.replace(/%d/i, number); +} + +function pastFuture (diff, output) { + var format = this._relativeTime[diff > 0 ? 'future' : 'past']; + return isFunction(format) ? format(output) : format.replace(/%s/i, output); +} + +var aliases = {}; + +function addUnitAlias (unit, shorthand) { + var lowerCase = unit.toLowerCase(); + aliases[lowerCase] = aliases[lowerCase + 's'] = aliases[shorthand] = unit; +} + +function normalizeUnits(units) { + return typeof units === 'string' ? aliases[units] || aliases[units.toLowerCase()] : undefined; +} + +function normalizeObjectUnits(inputObject) { + var normalizedInput = {}, + normalizedProp, + prop; + + for (prop in inputObject) { + if (hasOwnProp(inputObject, prop)) { + normalizedProp = normalizeUnits(prop); + if (normalizedProp) { + normalizedInput[normalizedProp] = inputObject[prop]; + } + } + } + + return normalizedInput; +} + +var priorities = {}; + +function addUnitPriority(unit, priority) { + priorities[unit] = priority; +} + +function getPrioritizedUnits(unitsObj) { + var units = []; + for (var u in unitsObj) { + units.push({unit: u, priority: priorities[u]}); + } + units.sort(function (a, b) { + return a.priority - b.priority; + }); + return units; +} + +function makeGetSet (unit, keepTime) { + return function (value) { + if (value != null) { + set$1(this, unit, value); + hooks.updateOffset(this, keepTime); + return this; + } else { + return get(this, unit); + } + }; +} + +function get (mom, unit) { + return mom.isValid() ? + mom._d['get' + (mom._isUTC ? 'UTC' : '') + unit]() : NaN; +} + +function set$1 (mom, unit, value) { + if (mom.isValid()) { + mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value); + } +} + +// MOMENTS + +function stringGet (units) { + units = normalizeUnits(units); + if (isFunction(this[units])) { + return this[units](); + } + return this; +} + + +function stringSet (units, value) { + if (typeof units === 'object') { + units = normalizeObjectUnits(units); + var prioritized = getPrioritizedUnits(units); + for (var i = 0; i < prioritized.length; i++) { + this[prioritized[i].unit](units[prioritized[i].unit]); + } + } else { + units = normalizeUnits(units); + if (isFunction(this[units])) { + return this[units](value); + } + } + return this; +} + +function zeroFill(number, targetLength, forceSign) { + var absNumber = '' + Math.abs(number), + zerosToFill = targetLength - absNumber.length, + sign = number >= 0; + return (sign ? (forceSign ? '+' : '') : '-') + + Math.pow(10, Math.max(0, zerosToFill)).toString().substr(1) + absNumber; +} + +var formattingTokens = /(\[[^\[]*\])|(\\)?([Hh]mm(ss)?|Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Qo?|YYYYYY|YYYYY|YYYY|YY|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|kk?|mm?|ss?|S{1,9}|x|X|zz?|ZZ?|.)/g; + +var localFormattingTokens = /(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g; + +var formatFunctions = {}; + +var formatTokenFunctions = {}; + +// token: 'M' +// padded: ['MM', 2] +// ordinal: 'Mo' +// callback: function () { this.month() + 1 } +function addFormatToken (token, padded, ordinal, callback) { + var func = callback; + if (typeof callback === 'string') { + func = function () { + return this[callback](); + }; + } + if (token) { + formatTokenFunctions[token] = func; + } + if (padded) { + formatTokenFunctions[padded[0]] = function () { + return zeroFill(func.apply(this, arguments), padded[1], padded[2]); + }; + } + if (ordinal) { + formatTokenFunctions[ordinal] = function () { + return this.localeData().ordinal(func.apply(this, arguments), token); + }; + } +} + +function removeFormattingTokens(input) { + if (input.match(/\[[\s\S]/)) { + return input.replace(/^\[|\]$/g, ''); + } + return input.replace(/\\/g, ''); +} + +function makeFormatFunction(format) { + var array = format.match(formattingTokens), i, length; + + for (i = 0, length = array.length; i < length; i++) { + if (formatTokenFunctions[array[i]]) { + array[i] = formatTokenFunctions[array[i]]; + } else { + array[i] = removeFormattingTokens(array[i]); + } + } + + return function (mom) { + var output = '', i; + for (i = 0; i < length; i++) { + output += isFunction(array[i]) ? array[i].call(mom, format) : array[i]; + } + return output; + }; +} + +// format date using native date object +function formatMoment(m, format) { + if (!m.isValid()) { + return m.localeData().invalidDate(); + } + + format = expandFormat(format, m.localeData()); + formatFunctions[format] = formatFunctions[format] || makeFormatFunction(format); + + return formatFunctions[format](m); +} + +function expandFormat(format, locale) { + var i = 5; + + function replaceLongDateFormatTokens(input) { + return locale.longDateFormat(input) || input; + } + + localFormattingTokens.lastIndex = 0; + while (i >= 0 && localFormattingTokens.test(format)) { + format = format.replace(localFormattingTokens, replaceLongDateFormatTokens); + localFormattingTokens.lastIndex = 0; + i -= 1; + } + + return format; +} + +var match1 = /\d/; // 0 - 9 +var match2 = /\d\d/; // 00 - 99 +var match3 = /\d{3}/; // 000 - 999 +var match4 = /\d{4}/; // 0000 - 9999 +var match6 = /[+-]?\d{6}/; // -999999 - 999999 +var match1to2 = /\d\d?/; // 0 - 99 +var match3to4 = /\d\d\d\d?/; // 999 - 9999 +var match5to6 = /\d\d\d\d\d\d?/; // 99999 - 999999 +var match1to3 = /\d{1,3}/; // 0 - 999 +var match1to4 = /\d{1,4}/; // 0 - 9999 +var match1to6 = /[+-]?\d{1,6}/; // -999999 - 999999 + +var matchUnsigned = /\d+/; // 0 - inf +var matchSigned = /[+-]?\d+/; // -inf - inf + +var matchOffset = /Z|[+-]\d\d:?\d\d/gi; // +00:00 -00:00 +0000 -0000 or Z +var matchShortOffset = /Z|[+-]\d\d(?::?\d\d)?/gi; // +00 -00 +00:00 -00:00 +0000 -0000 or Z + +var matchTimestamp = /[+-]?\d+(\.\d{1,3})?/; // 123456789 123456789.123 + +// any word (or two) characters or numbers including two/three word month in arabic. +// includes scottish gaelic two word and hyphenated months +var matchWord = /[0-9]*['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+|[\u0600-\u06FF\/]+(\s*?[\u0600-\u06FF]+){1,2}/i; + + +var regexes = {}; + +function addRegexToken (token, regex, strictRegex) { + regexes[token] = isFunction(regex) ? regex : function (isStrict, localeData) { + return (isStrict && strictRegex) ? strictRegex : regex; + }; +} + +function getParseRegexForToken (token, config) { + if (!hasOwnProp(regexes, token)) { + return new RegExp(unescapeFormat(token)); + } + + return regexes[token](config._strict, config._locale); +} + +// Code from http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript +function unescapeFormat(s) { + return regexEscape(s.replace('\\', '').replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g, function (matched, p1, p2, p3, p4) { + return p1 || p2 || p3 || p4; + })); +} + +function regexEscape(s) { + return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'); +} + +var tokens = {}; + +function addParseToken (token, callback) { + var i, func = callback; + if (typeof token === 'string') { + token = [token]; + } + if (isNumber(callback)) { + func = function (input, array) { + array[callback] = toInt(input); + }; + } + for (i = 0; i < token.length; i++) { + tokens[token[i]] = func; + } +} + +function addWeekParseToken (token, callback) { + addParseToken(token, function (input, array, config, token) { + config._w = config._w || {}; + callback(input, config._w, config, token); + }); +} + +function addTimeToArrayFromToken(token, input, config) { + if (input != null && hasOwnProp(tokens, token)) { + tokens[token](input, config._a, config, token); + } +} + +var YEAR = 0; +var MONTH = 1; +var DATE = 2; +var HOUR = 3; +var MINUTE = 4; +var SECOND = 5; +var MILLISECOND = 6; +var WEEK = 7; +var WEEKDAY = 8; + +var indexOf; + +if (Array.prototype.indexOf) { + indexOf = Array.prototype.indexOf; +} else { + indexOf = function (o) { + // I know + var i; + for (i = 0; i < this.length; ++i) { + if (this[i] === o) { + return i; + } + } + return -1; + }; +} + +var indexOf$1 = indexOf; + +function daysInMonth(year, month) { + return new Date(Date.UTC(year, month + 1, 0)).getUTCDate(); +} + +// FORMATTING + +addFormatToken('M', ['MM', 2], 'Mo', function () { + return this.month() + 1; +}); + +addFormatToken('MMM', 0, 0, function (format) { + return this.localeData().monthsShort(this, format); +}); + +addFormatToken('MMMM', 0, 0, function (format) { + return this.localeData().months(this, format); +}); + +// ALIASES + +addUnitAlias('month', 'M'); + +// PRIORITY + +addUnitPriority('month', 8); + +// PARSING + +addRegexToken('M', match1to2); +addRegexToken('MM', match1to2, match2); +addRegexToken('MMM', function (isStrict, locale) { + return locale.monthsShortRegex(isStrict); +}); +addRegexToken('MMMM', function (isStrict, locale) { + return locale.monthsRegex(isStrict); +}); + +addParseToken(['M', 'MM'], function (input, array) { + array[MONTH] = toInt(input) - 1; +}); + +addParseToken(['MMM', 'MMMM'], function (input, array, config, token) { + var month = config._locale.monthsParse(input, token, config._strict); + // if we didn't find a month name, mark the date as invalid. + if (month != null) { + array[MONTH] = month; + } else { + getParsingFlags(config).invalidMonth = input; + } +}); + +// LOCALES + +var MONTHS_IN_FORMAT = /D[oD]?(\[[^\[\]]*\]|\s)+MMMM?/; +var defaultLocaleMonths = 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_'); +function localeMonths (m, format) { + if (!m) { + return isArray(this._months) ? this._months : + this._months['standalone']; + } + return isArray(this._months) ? this._months[m.month()] : + this._months[(this._months.isFormat || MONTHS_IN_FORMAT).test(format) ? 'format' : 'standalone'][m.month()]; +} + +var defaultLocaleMonthsShort = 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'); +function localeMonthsShort (m, format) { + if (!m) { + return isArray(this._monthsShort) ? this._monthsShort : + this._monthsShort['standalone']; + } + return isArray(this._monthsShort) ? this._monthsShort[m.month()] : + this._monthsShort[MONTHS_IN_FORMAT.test(format) ? 'format' : 'standalone'][m.month()]; +} + +function handleStrictParse(monthName, format, strict) { + var i, ii, mom, llc = monthName.toLocaleLowerCase(); + if (!this._monthsParse) { + // this is not used + this._monthsParse = []; + this._longMonthsParse = []; + this._shortMonthsParse = []; + for (i = 0; i < 12; ++i) { + mom = createUTC([2000, i]); + this._shortMonthsParse[i] = this.monthsShort(mom, '').toLocaleLowerCase(); + this._longMonthsParse[i] = this.months(mom, '').toLocaleLowerCase(); + } + } + + if (strict) { + if (format === 'MMM') { + ii = indexOf$1.call(this._shortMonthsParse, llc); + return ii !== -1 ? ii : null; + } else { + ii = indexOf$1.call(this._longMonthsParse, llc); + return ii !== -1 ? ii : null; + } + } else { + if (format === 'MMM') { + ii = indexOf$1.call(this._shortMonthsParse, llc); + if (ii !== -1) { + return ii; + } + ii = indexOf$1.call(this._longMonthsParse, llc); + return ii !== -1 ? ii : null; + } else { + ii = indexOf$1.call(this._longMonthsParse, llc); + if (ii !== -1) { + return ii; + } + ii = indexOf$1.call(this._shortMonthsParse, llc); + return ii !== -1 ? ii : null; + } + } +} + +function localeMonthsParse (monthName, format, strict) { + var i, mom, regex; + + if (this._monthsParseExact) { + return handleStrictParse.call(this, monthName, format, strict); + } + + if (!this._monthsParse) { + this._monthsParse = []; + this._longMonthsParse = []; + this._shortMonthsParse = []; + } + + // TODO: add sorting + // Sorting makes sure if one month (or abbr) is a prefix of another + // see sorting in computeMonthsParse + for (i = 0; i < 12; i++) { + // make the regex if we don't have it already + mom = createUTC([2000, i]); + if (strict && !this._longMonthsParse[i]) { + this._longMonthsParse[i] = new RegExp('^' + this.months(mom, '').replace('.', '') + '$', 'i'); + this._shortMonthsParse[i] = new RegExp('^' + this.monthsShort(mom, '').replace('.', '') + '$', 'i'); + } + if (!strict && !this._monthsParse[i]) { + regex = '^' + this.months(mom, '') + '|^' + this.monthsShort(mom, ''); + this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i'); + } + // test the regex + if (strict && format === 'MMMM' && this._longMonthsParse[i].test(monthName)) { + return i; + } else if (strict && format === 'MMM' && this._shortMonthsParse[i].test(monthName)) { + return i; + } else if (!strict && this._monthsParse[i].test(monthName)) { + return i; + } + } +} + +// MOMENTS + +function setMonth (mom, value) { + var dayOfMonth; + + if (!mom.isValid()) { + // No op + return mom; + } + + if (typeof value === 'string') { + if (/^\d+$/.test(value)) { + value = toInt(value); + } else { + value = mom.localeData().monthsParse(value); + // TODO: Another silent failure? + if (!isNumber(value)) { + return mom; + } + } + } + + dayOfMonth = Math.min(mom.date(), daysInMonth(mom.year(), value)); + mom._d['set' + (mom._isUTC ? 'UTC' : '') + 'Month'](value, dayOfMonth); + return mom; +} + +function getSetMonth (value) { + if (value != null) { + setMonth(this, value); + hooks.updateOffset(this, true); + return this; + } else { + return get(this, 'Month'); + } +} + +function getDaysInMonth () { + return daysInMonth(this.year(), this.month()); +} + +var defaultMonthsShortRegex = matchWord; +function monthsShortRegex (isStrict) { + if (this._monthsParseExact) { + if (!hasOwnProp(this, '_monthsRegex')) { + computeMonthsParse.call(this); + } + if (isStrict) { + return this._monthsShortStrictRegex; + } else { + return this._monthsShortRegex; + } + } else { + if (!hasOwnProp(this, '_monthsShortRegex')) { + this._monthsShortRegex = defaultMonthsShortRegex; + } + return this._monthsShortStrictRegex && isStrict ? + this._monthsShortStrictRegex : this._monthsShortRegex; + } +} + +var defaultMonthsRegex = matchWord; +function monthsRegex (isStrict) { + if (this._monthsParseExact) { + if (!hasOwnProp(this, '_monthsRegex')) { + computeMonthsParse.call(this); + } + if (isStrict) { + return this._monthsStrictRegex; + } else { + return this._monthsRegex; + } + } else { + if (!hasOwnProp(this, '_monthsRegex')) { + this._monthsRegex = defaultMonthsRegex; + } + return this._monthsStrictRegex && isStrict ? + this._monthsStrictRegex : this._monthsRegex; + } +} + +function computeMonthsParse () { + function cmpLenRev(a, b) { + return b.length - a.length; + } + + var shortPieces = [], longPieces = [], mixedPieces = [], + i, mom; + for (i = 0; i < 12; i++) { + // make the regex if we don't have it already + mom = createUTC([2000, i]); + shortPieces.push(this.monthsShort(mom, '')); + longPieces.push(this.months(mom, '')); + mixedPieces.push(this.months(mom, '')); + mixedPieces.push(this.monthsShort(mom, '')); + } + // Sorting makes sure if one month (or abbr) is a prefix of another it + // will match the longer piece. + shortPieces.sort(cmpLenRev); + longPieces.sort(cmpLenRev); + mixedPieces.sort(cmpLenRev); + for (i = 0; i < 12; i++) { + shortPieces[i] = regexEscape(shortPieces[i]); + longPieces[i] = regexEscape(longPieces[i]); + } + for (i = 0; i < 24; i++) { + mixedPieces[i] = regexEscape(mixedPieces[i]); + } + + this._monthsRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i'); + this._monthsShortRegex = this._monthsRegex; + this._monthsStrictRegex = new RegExp('^(' + longPieces.join('|') + ')', 'i'); + this._monthsShortStrictRegex = new RegExp('^(' + shortPieces.join('|') + ')', 'i'); +} + +// FORMATTING + +addFormatToken('Y', 0, 0, function () { + var y = this.year(); + return y <= 9999 ? '' + y : '+' + y; +}); + +addFormatToken(0, ['YY', 2], 0, function () { + return this.year() % 100; +}); + +addFormatToken(0, ['YYYY', 4], 0, 'year'); +addFormatToken(0, ['YYYYY', 5], 0, 'year'); +addFormatToken(0, ['YYYYYY', 6, true], 0, 'year'); + +// ALIASES + +addUnitAlias('year', 'y'); + +// PRIORITIES + +addUnitPriority('year', 1); + +// PARSING + +addRegexToken('Y', matchSigned); +addRegexToken('YY', match1to2, match2); +addRegexToken('YYYY', match1to4, match4); +addRegexToken('YYYYY', match1to6, match6); +addRegexToken('YYYYYY', match1to6, match6); + +addParseToken(['YYYYY', 'YYYYYY'], YEAR); +addParseToken('YYYY', function (input, array) { + array[YEAR] = input.length === 2 ? hooks.parseTwoDigitYear(input) : toInt(input); +}); +addParseToken('YY', function (input, array) { + array[YEAR] = hooks.parseTwoDigitYear(input); +}); +addParseToken('Y', function (input, array) { + array[YEAR] = parseInt(input, 10); +}); + +// HELPERS + +function daysInYear(year) { + return isLeapYear(year) ? 366 : 365; +} + +function isLeapYear(year) { + return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0; +} + +// HOOKS + +hooks.parseTwoDigitYear = function (input) { + return toInt(input) + (toInt(input) > 68 ? 1900 : 2000); +}; + +// MOMENTS + +var getSetYear = makeGetSet('FullYear', true); + +function getIsLeapYear () { + return isLeapYear(this.year()); +} + +function createDate (y, m, d, h, M, s, ms) { + // can't just apply() to create a date: + // https://stackoverflow.com/q/181348 + var date = new Date(y, m, d, h, M, s, ms); + + // the date constructor remaps years 0-99 to 1900-1999 + if (y < 100 && y >= 0 && isFinite(date.getFullYear())) { + date.setFullYear(y); + } + return date; +} + +function createUTCDate (y) { + var date = new Date(Date.UTC.apply(null, arguments)); + + // the Date.UTC function remaps years 0-99 to 1900-1999 + if (y < 100 && y >= 0 && isFinite(date.getUTCFullYear())) { + date.setUTCFullYear(y); + } + return date; +} + +// start-of-first-week - start-of-year +function firstWeekOffset(year, dow, doy) { + var // first-week day -- which january is always in the first week (4 for iso, 1 for other) + fwd = 7 + dow - doy, + // first-week day local weekday -- which local weekday is fwd + fwdlw = (7 + createUTCDate(year, 0, fwd).getUTCDay() - dow) % 7; + + return -fwdlw + fwd - 1; +} + +// https://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year.2C_week_number_and_weekday +function dayOfYearFromWeeks(year, week, weekday, dow, doy) { + var localWeekday = (7 + weekday - dow) % 7, + weekOffset = firstWeekOffset(year, dow, doy), + dayOfYear = 1 + 7 * (week - 1) + localWeekday + weekOffset, + resYear, resDayOfYear; + + if (dayOfYear <= 0) { + resYear = year - 1; + resDayOfYear = daysInYear(resYear) + dayOfYear; + } else if (dayOfYear > daysInYear(year)) { + resYear = year + 1; + resDayOfYear = dayOfYear - daysInYear(year); + } else { + resYear = year; + resDayOfYear = dayOfYear; + } + + return { + year: resYear, + dayOfYear: resDayOfYear + }; +} + +function weekOfYear(mom, dow, doy) { + var weekOffset = firstWeekOffset(mom.year(), dow, doy), + week = Math.floor((mom.dayOfYear() - weekOffset - 1) / 7) + 1, + resWeek, resYear; + + if (week < 1) { + resYear = mom.year() - 1; + resWeek = week + weeksInYear(resYear, dow, doy); + } else if (week > weeksInYear(mom.year(), dow, doy)) { + resWeek = week - weeksInYear(mom.year(), dow, doy); + resYear = mom.year() + 1; + } else { + resYear = mom.year(); + resWeek = week; + } + + return { + week: resWeek, + year: resYear + }; +} + +function weeksInYear(year, dow, doy) { + var weekOffset = firstWeekOffset(year, dow, doy), + weekOffsetNext = firstWeekOffset(year + 1, dow, doy); + return (daysInYear(year) - weekOffset + weekOffsetNext) / 7; +} + +// FORMATTING + +addFormatToken('w', ['ww', 2], 'wo', 'week'); +addFormatToken('W', ['WW', 2], 'Wo', 'isoWeek'); + +// ALIASES + +addUnitAlias('week', 'w'); +addUnitAlias('isoWeek', 'W'); + +// PRIORITIES + +addUnitPriority('week', 5); +addUnitPriority('isoWeek', 5); + +// PARSING + +addRegexToken('w', match1to2); +addRegexToken('ww', match1to2, match2); +addRegexToken('W', match1to2); +addRegexToken('WW', match1to2, match2); + +addWeekParseToken(['w', 'ww', 'W', 'WW'], function (input, week, config, token) { + week[token.substr(0, 1)] = toInt(input); +}); + +// HELPERS + +// LOCALES + +function localeWeek (mom) { + return weekOfYear(mom, this._week.dow, this._week.doy).week; +} + +var defaultLocaleWeek = { + dow : 0, // Sunday is the first day of the week. + doy : 6 // The week that contains Jan 1st is the first week of the year. +}; + +function localeFirstDayOfWeek () { + return this._week.dow; +} + +function localeFirstDayOfYear () { + return this._week.doy; +} + +// MOMENTS + +function getSetWeek (input) { + var week = this.localeData().week(this); + return input == null ? week : this.add((input - week) * 7, 'd'); +} + +function getSetISOWeek (input) { + var week = weekOfYear(this, 1, 4).week; + return input == null ? week : this.add((input - week) * 7, 'd'); +} + +// FORMATTING + +addFormatToken('d', 0, 'do', 'day'); + +addFormatToken('dd', 0, 0, function (format) { + return this.localeData().weekdaysMin(this, format); +}); + +addFormatToken('ddd', 0, 0, function (format) { + return this.localeData().weekdaysShort(this, format); +}); + +addFormatToken('dddd', 0, 0, function (format) { + return this.localeData().weekdays(this, format); +}); + +addFormatToken('e', 0, 0, 'weekday'); +addFormatToken('E', 0, 0, 'isoWeekday'); + +// ALIASES + +addUnitAlias('day', 'd'); +addUnitAlias('weekday', 'e'); +addUnitAlias('isoWeekday', 'E'); + +// PRIORITY +addUnitPriority('day', 11); +addUnitPriority('weekday', 11); +addUnitPriority('isoWeekday', 11); + +// PARSING + +addRegexToken('d', match1to2); +addRegexToken('e', match1to2); +addRegexToken('E', match1to2); +addRegexToken('dd', function (isStrict, locale) { + return locale.weekdaysMinRegex(isStrict); +}); +addRegexToken('ddd', function (isStrict, locale) { + return locale.weekdaysShortRegex(isStrict); +}); +addRegexToken('dddd', function (isStrict, locale) { + return locale.weekdaysRegex(isStrict); +}); + +addWeekParseToken(['dd', 'ddd', 'dddd'], function (input, week, config, token) { + var weekday = config._locale.weekdaysParse(input, token, config._strict); + // if we didn't get a weekday name, mark the date as invalid + if (weekday != null) { + week.d = weekday; + } else { + getParsingFlags(config).invalidWeekday = input; + } +}); + +addWeekParseToken(['d', 'e', 'E'], function (input, week, config, token) { + week[token] = toInt(input); +}); + +// HELPERS + +function parseWeekday(input, locale) { + if (typeof input !== 'string') { + return input; + } + + if (!isNaN(input)) { + return parseInt(input, 10); + } + + input = locale.weekdaysParse(input); + if (typeof input === 'number') { + return input; + } + + return null; +} + +function parseIsoWeekday(input, locale) { + if (typeof input === 'string') { + return locale.weekdaysParse(input) % 7 || 7; + } + return isNaN(input) ? null : input; +} + +// LOCALES + +var defaultLocaleWeekdays = 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_'); +function localeWeekdays (m, format) { + if (!m) { + return isArray(this._weekdays) ? this._weekdays : + this._weekdays['standalone']; + } + return isArray(this._weekdays) ? this._weekdays[m.day()] : + this._weekdays[this._weekdays.isFormat.test(format) ? 'format' : 'standalone'][m.day()]; +} + +var defaultLocaleWeekdaysShort = 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'); +function localeWeekdaysShort (m) { + return (m) ? this._weekdaysShort[m.day()] : this._weekdaysShort; +} + +var defaultLocaleWeekdaysMin = 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'); +function localeWeekdaysMin (m) { + return (m) ? this._weekdaysMin[m.day()] : this._weekdaysMin; +} + +function handleStrictParse$1(weekdayName, format, strict) { + var i, ii, mom, llc = weekdayName.toLocaleLowerCase(); + if (!this._weekdaysParse) { + this._weekdaysParse = []; + this._shortWeekdaysParse = []; + this._minWeekdaysParse = []; + + for (i = 0; i < 7; ++i) { + mom = createUTC([2000, 1]).day(i); + this._minWeekdaysParse[i] = this.weekdaysMin(mom, '').toLocaleLowerCase(); + this._shortWeekdaysParse[i] = this.weekdaysShort(mom, '').toLocaleLowerCase(); + this._weekdaysParse[i] = this.weekdays(mom, '').toLocaleLowerCase(); + } + } + + if (strict) { + if (format === 'dddd') { + ii = indexOf$1.call(this._weekdaysParse, llc); + return ii !== -1 ? ii : null; + } else if (format === 'ddd') { + ii = indexOf$1.call(this._shortWeekdaysParse, llc); + return ii !== -1 ? ii : null; + } else { + ii = indexOf$1.call(this._minWeekdaysParse, llc); + return ii !== -1 ? ii : null; + } + } else { + if (format === 'dddd') { + ii = indexOf$1.call(this._weekdaysParse, llc); + if (ii !== -1) { + return ii; + } + ii = indexOf$1.call(this._shortWeekdaysParse, llc); + if (ii !== -1) { + return ii; + } + ii = indexOf$1.call(this._minWeekdaysParse, llc); + return ii !== -1 ? ii : null; + } else if (format === 'ddd') { + ii = indexOf$1.call(this._shortWeekdaysParse, llc); + if (ii !== -1) { + return ii; + } + ii = indexOf$1.call(this._weekdaysParse, llc); + if (ii !== -1) { + return ii; + } + ii = indexOf$1.call(this._minWeekdaysParse, llc); + return ii !== -1 ? ii : null; + } else { + ii = indexOf$1.call(this._minWeekdaysParse, llc); + if (ii !== -1) { + return ii; + } + ii = indexOf$1.call(this._weekdaysParse, llc); + if (ii !== -1) { + return ii; + } + ii = indexOf$1.call(this._shortWeekdaysParse, llc); + return ii !== -1 ? ii : null; + } + } +} + +function localeWeekdaysParse (weekdayName, format, strict) { + var i, mom, regex; + + if (this._weekdaysParseExact) { + return handleStrictParse$1.call(this, weekdayName, format, strict); + } + + if (!this._weekdaysParse) { + this._weekdaysParse = []; + this._minWeekdaysParse = []; + this._shortWeekdaysParse = []; + this._fullWeekdaysParse = []; + } + + for (i = 0; i < 7; i++) { + // make the regex if we don't have it already + + mom = createUTC([2000, 1]).day(i); + if (strict && !this._fullWeekdaysParse[i]) { + this._fullWeekdaysParse[i] = new RegExp('^' + this.weekdays(mom, '').replace('.', '\.?') + '$', 'i'); + this._shortWeekdaysParse[i] = new RegExp('^' + this.weekdaysShort(mom, '').replace('.', '\.?') + '$', 'i'); + this._minWeekdaysParse[i] = new RegExp('^' + this.weekdaysMin(mom, '').replace('.', '\.?') + '$', 'i'); + } + if (!this._weekdaysParse[i]) { + regex = '^' + this.weekdays(mom, '') + '|^' + this.weekdaysShort(mom, '') + '|^' + this.weekdaysMin(mom, ''); + this._weekdaysParse[i] = new RegExp(regex.replace('.', ''), 'i'); + } + // test the regex + if (strict && format === 'dddd' && this._fullWeekdaysParse[i].test(weekdayName)) { + return i; + } else if (strict && format === 'ddd' && this._shortWeekdaysParse[i].test(weekdayName)) { + return i; + } else if (strict && format === 'dd' && this._minWeekdaysParse[i].test(weekdayName)) { + return i; + } else if (!strict && this._weekdaysParse[i].test(weekdayName)) { + return i; + } + } +} + +// MOMENTS + +function getSetDayOfWeek (input) { + if (!this.isValid()) { + return input != null ? this : NaN; + } + var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay(); + if (input != null) { + input = parseWeekday(input, this.localeData()); + return this.add(input - day, 'd'); + } else { + return day; + } +} + +function getSetLocaleDayOfWeek (input) { + if (!this.isValid()) { + return input != null ? this : NaN; + } + var weekday = (this.day() + 7 - this.localeData()._week.dow) % 7; + return input == null ? weekday : this.add(input - weekday, 'd'); +} + +function getSetISODayOfWeek (input) { + if (!this.isValid()) { + return input != null ? this : NaN; + } + + // behaves the same as moment#day except + // as a getter, returns 7 instead of 0 (1-7 range instead of 0-6) + // as a setter, sunday should belong to the previous week. + + if (input != null) { + var weekday = parseIsoWeekday(input, this.localeData()); + return this.day(this.day() % 7 ? weekday : weekday - 7); + } else { + return this.day() || 7; + } +} + +var defaultWeekdaysRegex = matchWord; +function weekdaysRegex (isStrict) { + if (this._weekdaysParseExact) { + if (!hasOwnProp(this, '_weekdaysRegex')) { + computeWeekdaysParse.call(this); + } + if (isStrict) { + return this._weekdaysStrictRegex; + } else { + return this._weekdaysRegex; + } + } else { + if (!hasOwnProp(this, '_weekdaysRegex')) { + this._weekdaysRegex = defaultWeekdaysRegex; + } + return this._weekdaysStrictRegex && isStrict ? + this._weekdaysStrictRegex : this._weekdaysRegex; + } +} + +var defaultWeekdaysShortRegex = matchWord; +function weekdaysShortRegex (isStrict) { + if (this._weekdaysParseExact) { + if (!hasOwnProp(this, '_weekdaysRegex')) { + computeWeekdaysParse.call(this); + } + if (isStrict) { + return this._weekdaysShortStrictRegex; + } else { + return this._weekdaysShortRegex; + } + } else { + if (!hasOwnProp(this, '_weekdaysShortRegex')) { + this._weekdaysShortRegex = defaultWeekdaysShortRegex; + } + return this._weekdaysShortStrictRegex && isStrict ? + this._weekdaysShortStrictRegex : this._weekdaysShortRegex; + } +} + +var defaultWeekdaysMinRegex = matchWord; +function weekdaysMinRegex (isStrict) { + if (this._weekdaysParseExact) { + if (!hasOwnProp(this, '_weekdaysRegex')) { + computeWeekdaysParse.call(this); + } + if (isStrict) { + return this._weekdaysMinStrictRegex; + } else { + return this._weekdaysMinRegex; + } + } else { + if (!hasOwnProp(this, '_weekdaysMinRegex')) { + this._weekdaysMinRegex = defaultWeekdaysMinRegex; + } + return this._weekdaysMinStrictRegex && isStrict ? + this._weekdaysMinStrictRegex : this._weekdaysMinRegex; + } +} + + +function computeWeekdaysParse () { + function cmpLenRev(a, b) { + return b.length - a.length; + } + + var minPieces = [], shortPieces = [], longPieces = [], mixedPieces = [], + i, mom, minp, shortp, longp; + for (i = 0; i < 7; i++) { + // make the regex if we don't have it already + mom = createUTC([2000, 1]).day(i); + minp = this.weekdaysMin(mom, ''); + shortp = this.weekdaysShort(mom, ''); + longp = this.weekdays(mom, ''); + minPieces.push(minp); + shortPieces.push(shortp); + longPieces.push(longp); + mixedPieces.push(minp); + mixedPieces.push(shortp); + mixedPieces.push(longp); + } + // Sorting makes sure if one weekday (or abbr) is a prefix of another it + // will match the longer piece. + minPieces.sort(cmpLenRev); + shortPieces.sort(cmpLenRev); + longPieces.sort(cmpLenRev); + mixedPieces.sort(cmpLenRev); + for (i = 0; i < 7; i++) { + shortPieces[i] = regexEscape(shortPieces[i]); + longPieces[i] = regexEscape(longPieces[i]); + mixedPieces[i] = regexEscape(mixedPieces[i]); + } + + this._weekdaysRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i'); + this._weekdaysShortRegex = this._weekdaysRegex; + this._weekdaysMinRegex = this._weekdaysRegex; + + this._weekdaysStrictRegex = new RegExp('^(' + longPieces.join('|') + ')', 'i'); + this._weekdaysShortStrictRegex = new RegExp('^(' + shortPieces.join('|') + ')', 'i'); + this._weekdaysMinStrictRegex = new RegExp('^(' + minPieces.join('|') + ')', 'i'); +} + +// FORMATTING + +function hFormat() { + return this.hours() % 12 || 12; +} + +function kFormat() { + return this.hours() || 24; +} + +addFormatToken('H', ['HH', 2], 0, 'hour'); +addFormatToken('h', ['hh', 2], 0, hFormat); +addFormatToken('k', ['kk', 2], 0, kFormat); + +addFormatToken('hmm', 0, 0, function () { + return '' + hFormat.apply(this) + zeroFill(this.minutes(), 2); +}); + +addFormatToken('hmmss', 0, 0, function () { + return '' + hFormat.apply(this) + zeroFill(this.minutes(), 2) + + zeroFill(this.seconds(), 2); +}); + +addFormatToken('Hmm', 0, 0, function () { + return '' + this.hours() + zeroFill(this.minutes(), 2); +}); + +addFormatToken('Hmmss', 0, 0, function () { + return '' + this.hours() + zeroFill(this.minutes(), 2) + + zeroFill(this.seconds(), 2); +}); + +function meridiem (token, lowercase) { + addFormatToken(token, 0, 0, function () { + return this.localeData().meridiem(this.hours(), this.minutes(), lowercase); + }); +} + +meridiem('a', true); +meridiem('A', false); + +// ALIASES + +addUnitAlias('hour', 'h'); + +// PRIORITY +addUnitPriority('hour', 13); + +// PARSING + +function matchMeridiem (isStrict, locale) { + return locale._meridiemParse; +} + +addRegexToken('a', matchMeridiem); +addRegexToken('A', matchMeridiem); +addRegexToken('H', match1to2); +addRegexToken('h', match1to2); +addRegexToken('k', match1to2); +addRegexToken('HH', match1to2, match2); +addRegexToken('hh', match1to2, match2); +addRegexToken('kk', match1to2, match2); + +addRegexToken('hmm', match3to4); +addRegexToken('hmmss', match5to6); +addRegexToken('Hmm', match3to4); +addRegexToken('Hmmss', match5to6); + +addParseToken(['H', 'HH'], HOUR); +addParseToken(['k', 'kk'], function (input, array, config) { + var kInput = toInt(input); + array[HOUR] = kInput === 24 ? 0 : kInput; +}); +addParseToken(['a', 'A'], function (input, array, config) { + config._isPm = config._locale.isPM(input); + config._meridiem = input; +}); +addParseToken(['h', 'hh'], function (input, array, config) { + array[HOUR] = toInt(input); + getParsingFlags(config).bigHour = true; +}); +addParseToken('hmm', function (input, array, config) { + var pos = input.length - 2; + array[HOUR] = toInt(input.substr(0, pos)); + array[MINUTE] = toInt(input.substr(pos)); + getParsingFlags(config).bigHour = true; +}); +addParseToken('hmmss', function (input, array, config) { + var pos1 = input.length - 4; + var pos2 = input.length - 2; + array[HOUR] = toInt(input.substr(0, pos1)); + array[MINUTE] = toInt(input.substr(pos1, 2)); + array[SECOND] = toInt(input.substr(pos2)); + getParsingFlags(config).bigHour = true; +}); +addParseToken('Hmm', function (input, array, config) { + var pos = input.length - 2; + array[HOUR] = toInt(input.substr(0, pos)); + array[MINUTE] = toInt(input.substr(pos)); +}); +addParseToken('Hmmss', function (input, array, config) { + var pos1 = input.length - 4; + var pos2 = input.length - 2; + array[HOUR] = toInt(input.substr(0, pos1)); + array[MINUTE] = toInt(input.substr(pos1, 2)); + array[SECOND] = toInt(input.substr(pos2)); +}); + +// LOCALES + +function localeIsPM (input) { + // IE8 Quirks Mode & IE7 Standards Mode do not allow accessing strings like arrays + // Using charAt should be more compatible. + return ((input + '').toLowerCase().charAt(0) === 'p'); +} + +var defaultLocaleMeridiemParse = /[ap]\.?m?\.?/i; +function localeMeridiem (hours, minutes, isLower) { + if (hours > 11) { + return isLower ? 'pm' : 'PM'; + } else { + return isLower ? 'am' : 'AM'; + } +} + + +// MOMENTS + +// Setting the hour should keep the time, because the user explicitly +// specified which hour he wants. So trying to maintain the same hour (in +// a new timezone) makes sense. Adding/subtracting hours does not follow +// this rule. +var getSetHour = makeGetSet('Hours', true); + +// months +// week +// weekdays +// meridiem +var baseConfig = { + calendar: defaultCalendar, + longDateFormat: defaultLongDateFormat, + invalidDate: defaultInvalidDate, + ordinal: defaultOrdinal, + dayOfMonthOrdinalParse: defaultDayOfMonthOrdinalParse, + relativeTime: defaultRelativeTime, + + months: defaultLocaleMonths, + monthsShort: defaultLocaleMonthsShort, + + week: defaultLocaleWeek, + + weekdays: defaultLocaleWeekdays, + weekdaysMin: defaultLocaleWeekdaysMin, + weekdaysShort: defaultLocaleWeekdaysShort, + + meridiemParse: defaultLocaleMeridiemParse +}; + +// internal storage for locale config files +var locales = {}; +var localeFamilies = {}; +var globalLocale; + +function normalizeLocale(key) { + return key ? key.toLowerCase().replace('_', '-') : key; +} + +// pick the locale from the array +// try ['en-au', 'en-gb'] as 'en-au', 'en-gb', 'en', as in move through the list trying each +// substring from most specific to least, but move to the next array item if it's a more specific variant than the current root +function chooseLocale(names) { + var i = 0, j, next, locale, split; + + while (i < names.length) { + split = normalizeLocale(names[i]).split('-'); + j = split.length; + next = normalizeLocale(names[i + 1]); + next = next ? next.split('-') : null; + while (j > 0) { + locale = loadLocale(split.slice(0, j).join('-')); + if (locale) { + return locale; + } + if (next && next.length >= j && compareArrays(split, next, true) >= j - 1) { + //the next array item is better than a shallower substring of this one + break; + } + j--; + } + i++; + } + return null; +} + +function loadLocale(name) { + var oldLocale = null; + // TODO: Find a better way to register and load all the locales in Node + if (!locales[name] && (typeof module !== 'undefined') && + module && module.exports) { + try { + oldLocale = globalLocale._abbr; + require('./locale/' + name); + // because defineLocale currently also sets the global locale, we + // want to undo that for lazy loaded locales + getSetGlobalLocale(oldLocale); + } catch (e) { } + } + return locales[name]; +} + +// This function will load locale and then set the global locale. If +// no arguments are passed in, it will simply return the current global +// locale key. +function getSetGlobalLocale (key, values) { + var data; + if (key) { + if (isUndefined(values)) { + data = getLocale(key); + } + else { + data = defineLocale(key, values); + } + + if (data) { + // moment.duration._locale = moment._locale = data; + globalLocale = data; + } + } + + return globalLocale._abbr; +} + +function defineLocale (name, config) { + if (config !== null) { + var parentConfig = baseConfig; + config.abbr = name; + if (locales[name] != null) { + deprecateSimple('defineLocaleOverride', + 'use moment.updateLocale(localeName, config) to change ' + + 'an existing locale. moment.defineLocale(localeName, ' + + 'config) should only be used for creating a new locale ' + + 'See http://momentjs.com/guides/#/warnings/define-locale/ for more info.'); + parentConfig = locales[name]._config; + } else if (config.parentLocale != null) { + if (locales[config.parentLocale] != null) { + parentConfig = locales[config.parentLocale]._config; + } else { + if (!localeFamilies[config.parentLocale]) { + localeFamilies[config.parentLocale] = []; + } + localeFamilies[config.parentLocale].push({ + name: name, + config: config + }); + return null; + } + } + locales[name] = new Locale(mergeConfigs(parentConfig, config)); + + if (localeFamilies[name]) { + localeFamilies[name].forEach(function (x) { + defineLocale(x.name, x.config); + }); + } + + // backwards compat for now: also set the locale + // make sure we set the locale AFTER all child locales have been + // created, so we won't end up with the child locale set. + getSetGlobalLocale(name); + + + return locales[name]; + } else { + // useful for testing + delete locales[name]; + return null; + } +} + +function updateLocale(name, config) { + if (config != null) { + var locale, parentConfig = baseConfig; + // MERGE + if (locales[name] != null) { + parentConfig = locales[name]._config; + } + config = mergeConfigs(parentConfig, config); + locale = new Locale(config); + locale.parentLocale = locales[name]; + locales[name] = locale; + + // backwards compat for now: also set the locale + getSetGlobalLocale(name); + } else { + // pass null for config to unupdate, useful for tests + if (locales[name] != null) { + if (locales[name].parentLocale != null) { + locales[name] = locales[name].parentLocale; + } else if (locales[name] != null) { + delete locales[name]; + } + } + } + return locales[name]; +} + +// returns locale data +function getLocale (key) { + var locale; + + if (key && key._locale && key._locale._abbr) { + key = key._locale._abbr; + } + + if (!key) { + return globalLocale; + } + + if (!isArray(key)) { + //short-circuit everything else + locale = loadLocale(key); + if (locale) { + return locale; + } + key = [key]; + } + + return chooseLocale(key); +} + +function listLocales() { + return keys$1(locales); +} + +function checkOverflow (m) { + var overflow; + var a = m._a; + + if (a && getParsingFlags(m).overflow === -2) { + overflow = + a[MONTH] < 0 || a[MONTH] > 11 ? MONTH : + a[DATE] < 1 || a[DATE] > daysInMonth(a[YEAR], a[MONTH]) ? DATE : + a[HOUR] < 0 || a[HOUR] > 24 || (a[HOUR] === 24 && (a[MINUTE] !== 0 || a[SECOND] !== 0 || a[MILLISECOND] !== 0)) ? HOUR : + a[MINUTE] < 0 || a[MINUTE] > 59 ? MINUTE : + a[SECOND] < 0 || a[SECOND] > 59 ? SECOND : + a[MILLISECOND] < 0 || a[MILLISECOND] > 999 ? MILLISECOND : + -1; + + if (getParsingFlags(m)._overflowDayOfYear && (overflow < YEAR || overflow > DATE)) { + overflow = DATE; + } + if (getParsingFlags(m)._overflowWeeks && overflow === -1) { + overflow = WEEK; + } + if (getParsingFlags(m)._overflowWeekday && overflow === -1) { + overflow = WEEKDAY; + } + + getParsingFlags(m).overflow = overflow; + } + + return m; +} + +// iso 8601 regex +// 0000-00-00 0000-W00 or 0000-W00-0 + T + 00 or 00:00 or 00:00:00 or 00:00:00.000 + +00:00 or +0000 or +00) +var extendedIsoRegex = /^\s*((?:[+-]\d{6}|\d{4})-(?:\d\d-\d\d|W\d\d-\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?::\d\d(?::\d\d(?:[.,]\d+)?)?)?)([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/; +var basicIsoRegex = /^\s*((?:[+-]\d{6}|\d{4})(?:\d\d\d\d|W\d\d\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?:\d\d(?:\d\d(?:[.,]\d+)?)?)?)([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/; + +var tzRegex = /Z|[+-]\d\d(?::?\d\d)?/; + +var isoDates = [ + ['YYYYYY-MM-DD', /[+-]\d{6}-\d\d-\d\d/], + ['YYYY-MM-DD', /\d{4}-\d\d-\d\d/], + ['GGGG-[W]WW-E', /\d{4}-W\d\d-\d/], + ['GGGG-[W]WW', /\d{4}-W\d\d/, false], + ['YYYY-DDD', /\d{4}-\d{3}/], + ['YYYY-MM', /\d{4}-\d\d/, false], + ['YYYYYYMMDD', /[+-]\d{10}/], + ['YYYYMMDD', /\d{8}/], + // YYYYMM is NOT allowed by the standard + ['GGGG[W]WWE', /\d{4}W\d{3}/], + ['GGGG[W]WW', /\d{4}W\d{2}/, false], + ['YYYYDDD', /\d{7}/] +]; + +// iso time formats and regexes +var isoTimes = [ + ['HH:mm:ss.SSSS', /\d\d:\d\d:\d\d\.\d+/], + ['HH:mm:ss,SSSS', /\d\d:\d\d:\d\d,\d+/], + ['HH:mm:ss', /\d\d:\d\d:\d\d/], + ['HH:mm', /\d\d:\d\d/], + ['HHmmss.SSSS', /\d\d\d\d\d\d\.\d+/], + ['HHmmss,SSSS', /\d\d\d\d\d\d,\d+/], + ['HHmmss', /\d\d\d\d\d\d/], + ['HHmm', /\d\d\d\d/], + ['HH', /\d\d/] +]; + +var aspNetJsonRegex = /^\/?Date\((\-?\d+)/i; + +// date from iso format +function configFromISO(config) { + var i, l, + string = config._i, + match = extendedIsoRegex.exec(string) || basicIsoRegex.exec(string), + allowTime, dateFormat, timeFormat, tzFormat; + + if (match) { + getParsingFlags(config).iso = true; + + for (i = 0, l = isoDates.length; i < l; i++) { + if (isoDates[i][1].exec(match[1])) { + dateFormat = isoDates[i][0]; + allowTime = isoDates[i][2] !== false; + break; + } + } + if (dateFormat == null) { + config._isValid = false; + return; + } + if (match[3]) { + for (i = 0, l = isoTimes.length; i < l; i++) { + if (isoTimes[i][1].exec(match[3])) { + // match[2] should be 'T' or space + timeFormat = (match[2] || ' ') + isoTimes[i][0]; + break; + } + } + if (timeFormat == null) { + config._isValid = false; + return; + } + } + if (!allowTime && timeFormat != null) { + config._isValid = false; + return; + } + if (match[4]) { + if (tzRegex.exec(match[4])) { + tzFormat = 'Z'; + } else { + config._isValid = false; + return; + } + } + config._f = dateFormat + (timeFormat || '') + (tzFormat || ''); + configFromStringAndFormat(config); + } else { + config._isValid = false; + } +} + +// RFC 2822 regex: For details see https://tools.ietf.org/html/rfc2822#section-3.3 +var basicRfcRegex = /^((?:Mon|Tue|Wed|Thu|Fri|Sat|Sun),?\s)?(\d?\d\s(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(?:\d\d)?\d\d\s)(\d\d:\d\d)(\:\d\d)?(\s(?:UT|GMT|[ECMP][SD]T|[A-IK-Za-ik-z]|[+-]\d{4}))$/; + +// date and time from ref 2822 format +function configFromRFC2822(config) { + var string, match, dayFormat, + dateFormat, timeFormat, tzFormat; + var timezones = { + ' GMT': ' +0000', + ' EDT': ' -0400', + ' EST': ' -0500', + ' CDT': ' -0500', + ' CST': ' -0600', + ' MDT': ' -0600', + ' MST': ' -0700', + ' PDT': ' -0700', + ' PST': ' -0800' + }; + var military = 'YXWVUTSRQPONZABCDEFGHIKLM'; + var timezone, timezoneIndex; + + string = config._i + .replace(/\([^\)]*\)|[\n\t]/g, ' ') // Remove comments and folding whitespace + .replace(/(\s\s+)/g, ' ') // Replace multiple-spaces with a single space + .replace(/^\s|\s$/g, ''); // Remove leading and trailing spaces + match = basicRfcRegex.exec(string); + + if (match) { + dayFormat = match[1] ? 'ddd' + ((match[1].length === 5) ? ', ' : ' ') : ''; + dateFormat = 'D MMM ' + ((match[2].length > 10) ? 'YYYY ' : 'YY '); + timeFormat = 'HH:mm' + (match[4] ? ':ss' : ''); + + // TODO: Replace the vanilla JS Date object with an indepentent day-of-week check. + if (match[1]) { // day of week given + var momentDate = new Date(match[2]); + var momentDay = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'][momentDate.getDay()]; + + if (match[1].substr(0,3) !== momentDay) { + getParsingFlags(config).weekdayMismatch = true; + config._isValid = false; + return; + } + } + + switch (match[5].length) { + case 2: // military + if (timezoneIndex === 0) { + timezone = ' +0000'; + } else { + timezoneIndex = military.indexOf(match[5][1].toUpperCase()) - 12; + timezone = ((timezoneIndex < 0) ? ' -' : ' +') + + (('' + timezoneIndex).replace(/^-?/, '0')).match(/..$/)[0] + '00'; + } + break; + case 4: // Zone + timezone = timezones[match[5]]; + break; + default: // UT or +/-9999 + timezone = timezones[' GMT']; + } + match[5] = timezone; + config._i = match.splice(1).join(''); + tzFormat = ' ZZ'; + config._f = dayFormat + dateFormat + timeFormat + tzFormat; + configFromStringAndFormat(config); + getParsingFlags(config).rfc2822 = true; + } else { + config._isValid = false; + } +} + +// date from iso format or fallback +function configFromString(config) { + var matched = aspNetJsonRegex.exec(config._i); + + if (matched !== null) { + config._d = new Date(+matched[1]); + return; + } + + configFromISO(config); + if (config._isValid === false) { + delete config._isValid; + } else { + return; + } + + configFromRFC2822(config); + if (config._isValid === false) { + delete config._isValid; + } else { + return; + } + + // Final attempt, use Input Fallback + hooks.createFromInputFallback(config); +} + +hooks.createFromInputFallback = deprecate( + 'value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), ' + + 'which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are ' + + 'discouraged and will be removed in an upcoming major release. Please refer to ' + + 'http://momentjs.com/guides/#/warnings/js-date/ for more info.', + function (config) { + config._d = new Date(config._i + (config._useUTC ? ' UTC' : '')); + } +); + +// Pick the first defined of two or three arguments. +function defaults(a, b, c) { + if (a != null) { + return a; + } + if (b != null) { + return b; + } + return c; +} + +function currentDateArray(config) { + // hooks is actually the exported moment object + var nowValue = new Date(hooks.now()); + if (config._useUTC) { + return [nowValue.getUTCFullYear(), nowValue.getUTCMonth(), nowValue.getUTCDate()]; + } + return [nowValue.getFullYear(), nowValue.getMonth(), nowValue.getDate()]; +} + +// convert an array to a date. +// the array should mirror the parameters below +// note: all values past the year are optional and will default to the lowest possible value. +// [year, month, day , hour, minute, second, millisecond] +function configFromArray (config) { + var i, date, input = [], currentDate, yearToUse; + + if (config._d) { + return; + } + + currentDate = currentDateArray(config); + + //compute day of the year from weeks and weekdays + if (config._w && config._a[DATE] == null && config._a[MONTH] == null) { + dayOfYearFromWeekInfo(config); + } + + //if the day of the year is set, figure out what it is + if (config._dayOfYear != null) { + yearToUse = defaults(config._a[YEAR], currentDate[YEAR]); + + if (config._dayOfYear > daysInYear(yearToUse) || config._dayOfYear === 0) { + getParsingFlags(config)._overflowDayOfYear = true; + } + + date = createUTCDate(yearToUse, 0, config._dayOfYear); + config._a[MONTH] = date.getUTCMonth(); + config._a[DATE] = date.getUTCDate(); + } + + // Default to current date. + // * if no year, month, day of month are given, default to today + // * if day of month is given, default month and year + // * if month is given, default only year + // * if year is given, don't default anything + for (i = 0; i < 3 && config._a[i] == null; ++i) { + config._a[i] = input[i] = currentDate[i]; + } + + // Zero out whatever was not defaulted, including time + for (; i < 7; i++) { + config._a[i] = input[i] = (config._a[i] == null) ? (i === 2 ? 1 : 0) : config._a[i]; + } + + // Check for 24:00:00.000 + if (config._a[HOUR] === 24 && + config._a[MINUTE] === 0 && + config._a[SECOND] === 0 && + config._a[MILLISECOND] === 0) { + config._nextDay = true; + config._a[HOUR] = 0; + } + + config._d = (config._useUTC ? createUTCDate : createDate).apply(null, input); + // Apply timezone offset from input. The actual utcOffset can be changed + // with parseZone. + if (config._tzm != null) { + config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm); + } + + if (config._nextDay) { + config._a[HOUR] = 24; + } +} + +function dayOfYearFromWeekInfo(config) { + var w, weekYear, week, weekday, dow, doy, temp, weekdayOverflow; + + w = config._w; + if (w.GG != null || w.W != null || w.E != null) { + dow = 1; + doy = 4; + + // TODO: We need to take the current isoWeekYear, but that depends on + // how we interpret now (local, utc, fixed offset). So create + // a now version of current config (take local/utc/offset flags, and + // create now). + weekYear = defaults(w.GG, config._a[YEAR], weekOfYear(createLocal(), 1, 4).year); + week = defaults(w.W, 1); + weekday = defaults(w.E, 1); + if (weekday < 1 || weekday > 7) { + weekdayOverflow = true; + } + } else { + dow = config._locale._week.dow; + doy = config._locale._week.doy; + + var curWeek = weekOfYear(createLocal(), dow, doy); + + weekYear = defaults(w.gg, config._a[YEAR], curWeek.year); + + // Default to current week. + week = defaults(w.w, curWeek.week); + + if (w.d != null) { + // weekday -- low day numbers are considered next week + weekday = w.d; + if (weekday < 0 || weekday > 6) { + weekdayOverflow = true; + } + } else if (w.e != null) { + // local weekday -- counting starts from begining of week + weekday = w.e + dow; + if (w.e < 0 || w.e > 6) { + weekdayOverflow = true; + } + } else { + // default to begining of week + weekday = dow; + } + } + if (week < 1 || week > weeksInYear(weekYear, dow, doy)) { + getParsingFlags(config)._overflowWeeks = true; + } else if (weekdayOverflow != null) { + getParsingFlags(config)._overflowWeekday = true; + } else { + temp = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy); + config._a[YEAR] = temp.year; + config._dayOfYear = temp.dayOfYear; + } +} + +// constant that refers to the ISO standard +hooks.ISO_8601 = function () {}; + +// constant that refers to the RFC 2822 form +hooks.RFC_2822 = function () {}; + +// date from string and format string +function configFromStringAndFormat(config) { + // TODO: Move this to another part of the creation flow to prevent circular deps + if (config._f === hooks.ISO_8601) { + configFromISO(config); + return; + } + if (config._f === hooks.RFC_2822) { + configFromRFC2822(config); + return; + } + config._a = []; + getParsingFlags(config).empty = true; + + // This array is used to make a Date, either with `new Date` or `Date.UTC` + var string = '' + config._i, + i, parsedInput, tokens, token, skipped, + stringLength = string.length, + totalParsedInputLength = 0; + + tokens = expandFormat(config._f, config._locale).match(formattingTokens) || []; + + for (i = 0; i < tokens.length; i++) { + token = tokens[i]; + parsedInput = (string.match(getParseRegexForToken(token, config)) || [])[0]; + // console.log('token', token, 'parsedInput', parsedInput, + // 'regex', getParseRegexForToken(token, config)); + if (parsedInput) { + skipped = string.substr(0, string.indexOf(parsedInput)); + if (skipped.length > 0) { + getParsingFlags(config).unusedInput.push(skipped); + } + string = string.slice(string.indexOf(parsedInput) + parsedInput.length); + totalParsedInputLength += parsedInput.length; + } + // don't parse if it's not a known token + if (formatTokenFunctions[token]) { + if (parsedInput) { + getParsingFlags(config).empty = false; + } + else { + getParsingFlags(config).unusedTokens.push(token); + } + addTimeToArrayFromToken(token, parsedInput, config); + } + else if (config._strict && !parsedInput) { + getParsingFlags(config).unusedTokens.push(token); + } + } + + // add remaining unparsed input length to the string + getParsingFlags(config).charsLeftOver = stringLength - totalParsedInputLength; + if (string.length > 0) { + getParsingFlags(config).unusedInput.push(string); + } + + // clear _12h flag if hour is <= 12 + if (config._a[HOUR] <= 12 && + getParsingFlags(config).bigHour === true && + config._a[HOUR] > 0) { + getParsingFlags(config).bigHour = undefined; + } + + getParsingFlags(config).parsedDateParts = config._a.slice(0); + getParsingFlags(config).meridiem = config._meridiem; + // handle meridiem + config._a[HOUR] = meridiemFixWrap(config._locale, config._a[HOUR], config._meridiem); + + configFromArray(config); + checkOverflow(config); +} + + +function meridiemFixWrap (locale, hour, meridiem) { + var isPm; + + if (meridiem == null) { + // nothing to do + return hour; + } + if (locale.meridiemHour != null) { + return locale.meridiemHour(hour, meridiem); + } else if (locale.isPM != null) { + // Fallback + isPm = locale.isPM(meridiem); + if (isPm && hour < 12) { + hour += 12; + } + if (!isPm && hour === 12) { + hour = 0; + } + return hour; + } else { + // this is not supposed to happen + return hour; + } +} + +// date from string and array of format strings +function configFromStringAndArray(config) { + var tempConfig, + bestMoment, + + scoreToBeat, + i, + currentScore; + + if (config._f.length === 0) { + getParsingFlags(config).invalidFormat = true; + config._d = new Date(NaN); + return; + } + + for (i = 0; i < config._f.length; i++) { + currentScore = 0; + tempConfig = copyConfig({}, config); + if (config._useUTC != null) { + tempConfig._useUTC = config._useUTC; + } + tempConfig._f = config._f[i]; + configFromStringAndFormat(tempConfig); + + if (!isValid(tempConfig)) { + continue; + } + + // if there is any input that was not parsed add a penalty for that format + currentScore += getParsingFlags(tempConfig).charsLeftOver; + + //or tokens + currentScore += getParsingFlags(tempConfig).unusedTokens.length * 10; + + getParsingFlags(tempConfig).score = currentScore; + + if (scoreToBeat == null || currentScore < scoreToBeat) { + scoreToBeat = currentScore; + bestMoment = tempConfig; + } + } + + extend(config, bestMoment || tempConfig); +} + +function configFromObject(config) { + if (config._d) { + return; + } + + var i = normalizeObjectUnits(config._i); + config._a = map([i.year, i.month, i.day || i.date, i.hour, i.minute, i.second, i.millisecond], function (obj) { + return obj && parseInt(obj, 10); + }); + + configFromArray(config); +} + +function createFromConfig (config) { + var res = new Moment(checkOverflow(prepareConfig(config))); + if (res._nextDay) { + // Adding is smart enough around DST + res.add(1, 'd'); + res._nextDay = undefined; + } + + return res; +} + +function prepareConfig (config) { + var input = config._i, + format = config._f; + + config._locale = config._locale || getLocale(config._l); + + if (input === null || (format === undefined && input === '')) { + return createInvalid({nullInput: true}); + } + + if (typeof input === 'string') { + config._i = input = config._locale.preparse(input); + } + + if (isMoment(input)) { + return new Moment(checkOverflow(input)); + } else if (isDate(input)) { + config._d = input; + } else if (isArray(format)) { + configFromStringAndArray(config); + } else if (format) { + configFromStringAndFormat(config); + } else { + configFromInput(config); + } + + if (!isValid(config)) { + config._d = null; + } + + return config; +} + +function configFromInput(config) { + var input = config._i; + if (isUndefined(input)) { + config._d = new Date(hooks.now()); + } else if (isDate(input)) { + config._d = new Date(input.valueOf()); + } else if (typeof input === 'string') { + configFromString(config); + } else if (isArray(input)) { + config._a = map(input.slice(0), function (obj) { + return parseInt(obj, 10); + }); + configFromArray(config); + } else if (isObject(input)) { + configFromObject(config); + } else if (isNumber(input)) { + // from milliseconds + config._d = new Date(input); + } else { + hooks.createFromInputFallback(config); + } +} + +function createLocalOrUTC (input, format, locale, strict, isUTC) { + var c = {}; + + if (locale === true || locale === false) { + strict = locale; + locale = undefined; + } + + if ((isObject(input) && isObjectEmpty(input)) || + (isArray(input) && input.length === 0)) { + input = undefined; + } + // object construction must be done this way. + // https://github.com/moment/moment/issues/1423 + c._isAMomentObject = true; + c._useUTC = c._isUTC = isUTC; + c._l = locale; + c._i = input; + c._f = format; + c._strict = strict; + + return createFromConfig(c); +} + +function createLocal (input, format, locale, strict) { + return createLocalOrUTC(input, format, locale, strict, false); +} + +var prototypeMin = deprecate( + 'moment().min is deprecated, use moment.max instead. http://momentjs.com/guides/#/warnings/min-max/', + function () { + var other = createLocal.apply(null, arguments); + if (this.isValid() && other.isValid()) { + return other < this ? this : other; + } else { + return createInvalid(); + } + } +); + +var prototypeMax = deprecate( + 'moment().max is deprecated, use moment.min instead. http://momentjs.com/guides/#/warnings/min-max/', + function () { + var other = createLocal.apply(null, arguments); + if (this.isValid() && other.isValid()) { + return other > this ? this : other; + } else { + return createInvalid(); + } + } +); + +// Pick a moment m from moments so that m[fn](other) is true for all +// other. This relies on the function fn to be transitive. +// +// moments should either be an array of moment objects or an array, whose +// first element is an array of moment objects. +function pickBy(fn, moments) { + var res, i; + if (moments.length === 1 && isArray(moments[0])) { + moments = moments[0]; + } + if (!moments.length) { + return createLocal(); + } + res = moments[0]; + for (i = 1; i < moments.length; ++i) { + if (!moments[i].isValid() || moments[i][fn](res)) { + res = moments[i]; + } + } + return res; +} + +// TODO: Use [].sort instead? +function min () { + var args = [].slice.call(arguments, 0); + + return pickBy('isBefore', args); +} + +function max () { + var args = [].slice.call(arguments, 0); + + return pickBy('isAfter', args); +} + +var now = function () { + return Date.now ? Date.now() : +(new Date()); +}; + +var ordering = ['year', 'quarter', 'month', 'week', 'day', 'hour', 'minute', 'second', 'millisecond']; + +function isDurationValid(m) { + for (var key in m) { + if (!(ordering.indexOf(key) !== -1 && (m[key] == null || !isNaN(m[key])))) { + return false; + } + } + + var unitHasDecimal = false; + for (var i = 0; i < ordering.length; ++i) { + if (m[ordering[i]]) { + if (unitHasDecimal) { + return false; // only allow non-integers for smallest unit + } + if (parseFloat(m[ordering[i]]) !== toInt(m[ordering[i]])) { + unitHasDecimal = true; + } + } + } + + return true; +} + +function isValid$1() { + return this._isValid; +} + +function createInvalid$1() { + return createDuration(NaN); +} + +function Duration (duration) { + var normalizedInput = normalizeObjectUnits(duration), + years = normalizedInput.year || 0, + quarters = normalizedInput.quarter || 0, + months = normalizedInput.month || 0, + weeks = normalizedInput.week || 0, + days = normalizedInput.day || 0, + hours = normalizedInput.hour || 0, + minutes = normalizedInput.minute || 0, + seconds = normalizedInput.second || 0, + milliseconds = normalizedInput.millisecond || 0; + + this._isValid = isDurationValid(normalizedInput); + + // representation for dateAddRemove + this._milliseconds = +milliseconds + + seconds * 1e3 + // 1000 + minutes * 6e4 + // 1000 * 60 + hours * 1000 * 60 * 60; //using 1000 * 60 * 60 instead of 36e5 to avoid floating point rounding errors https://github.com/moment/moment/issues/2978 + // Because of dateAddRemove treats 24 hours as different from a + // day when working around DST, we need to store them separately + this._days = +days + + weeks * 7; + // It is impossible translate months into days without knowing + // which months you are are talking about, so we have to store + // it separately. + this._months = +months + + quarters * 3 + + years * 12; + + this._data = {}; + + this._locale = getLocale(); + + this._bubble(); +} + +function isDuration (obj) { + return obj instanceof Duration; +} + +function absRound (number) { + if (number < 0) { + return Math.round(-1 * number) * -1; + } else { + return Math.round(number); + } +} + +// FORMATTING + +function offset (token, separator) { + addFormatToken(token, 0, 0, function () { + var offset = this.utcOffset(); + var sign = '+'; + if (offset < 0) { + offset = -offset; + sign = '-'; + } + return sign + zeroFill(~~(offset / 60), 2) + separator + zeroFill(~~(offset) % 60, 2); + }); +} + +offset('Z', ':'); +offset('ZZ', ''); + +// PARSING + +addRegexToken('Z', matchShortOffset); +addRegexToken('ZZ', matchShortOffset); +addParseToken(['Z', 'ZZ'], function (input, array, config) { + config._useUTC = true; + config._tzm = offsetFromString(matchShortOffset, input); +}); + +// HELPERS + +// timezone chunker +// '+10:00' > ['10', '00'] +// '-1530' > ['-15', '30'] +var chunkOffset = /([\+\-]|\d\d)/gi; + +function offsetFromString(matcher, string) { + var matches = (string || '').match(matcher); + + if (matches === null) { + return null; + } + + var chunk = matches[matches.length - 1] || []; + var parts = (chunk + '').match(chunkOffset) || ['-', 0, 0]; + var minutes = +(parts[1] * 60) + toInt(parts[2]); + + return minutes === 0 ? + 0 : + parts[0] === '+' ? minutes : -minutes; +} + +// Return a moment from input, that is local/utc/zone equivalent to model. +function cloneWithOffset(input, model) { + var res, diff; + if (model._isUTC) { + res = model.clone(); + diff = (isMoment(input) || isDate(input) ? input.valueOf() : createLocal(input).valueOf()) - res.valueOf(); + // Use low-level api, because this fn is low-level api. + res._d.setTime(res._d.valueOf() + diff); + hooks.updateOffset(res, false); + return res; + } else { + return createLocal(input).local(); + } +} + +function getDateOffset (m) { + // On Firefox.24 Date#getTimezoneOffset returns a floating point. + // https://github.com/moment/moment/pull/1871 + return -Math.round(m._d.getTimezoneOffset() / 15) * 15; +} + +// HOOKS + +// This function will be called whenever a moment is mutated. +// It is intended to keep the offset in sync with the timezone. +hooks.updateOffset = function () {}; + +// MOMENTS + +// keepLocalTime = true means only change the timezone, without +// affecting the local hour. So 5:31:26 +0300 --[utcOffset(2, true)]--> +// 5:31:26 +0200 It is possible that 5:31:26 doesn't exist with offset +// +0200, so we adjust the time as needed, to be valid. +// +// Keeping the time actually adds/subtracts (one hour) +// from the actual represented time. That is why we call updateOffset +// a second time. In case it wants us to change the offset again +// _changeInProgress == true case, then we have to adjust, because +// there is no such time in the given timezone. +function getSetOffset (input, keepLocalTime, keepMinutes) { + var offset = this._offset || 0, + localAdjust; + if (!this.isValid()) { + return input != null ? this : NaN; + } + if (input != null) { + if (typeof input === 'string') { + input = offsetFromString(matchShortOffset, input); + if (input === null) { + return this; + } + } else if (Math.abs(input) < 16 && !keepMinutes) { + input = input * 60; + } + if (!this._isUTC && keepLocalTime) { + localAdjust = getDateOffset(this); + } + this._offset = input; + this._isUTC = true; + if (localAdjust != null) { + this.add(localAdjust, 'm'); + } + if (offset !== input) { + if (!keepLocalTime || this._changeInProgress) { + addSubtract(this, createDuration(input - offset, 'm'), 1, false); + } else if (!this._changeInProgress) { + this._changeInProgress = true; + hooks.updateOffset(this, true); + this._changeInProgress = null; + } + } + return this; + } else { + return this._isUTC ? offset : getDateOffset(this); + } +} + +function getSetZone (input, keepLocalTime) { + if (input != null) { + if (typeof input !== 'string') { + input = -input; + } + + this.utcOffset(input, keepLocalTime); + + return this; + } else { + return -this.utcOffset(); + } +} + +function setOffsetToUTC (keepLocalTime) { + return this.utcOffset(0, keepLocalTime); +} + +function setOffsetToLocal (keepLocalTime) { + if (this._isUTC) { + this.utcOffset(0, keepLocalTime); + this._isUTC = false; + + if (keepLocalTime) { + this.subtract(getDateOffset(this), 'm'); + } + } + return this; +} + +function setOffsetToParsedOffset () { + if (this._tzm != null) { + this.utcOffset(this._tzm, false, true); + } else if (typeof this._i === 'string') { + var tZone = offsetFromString(matchOffset, this._i); + if (tZone != null) { + this.utcOffset(tZone); + } + else { + this.utcOffset(0, true); + } + } + return this; +} + +function hasAlignedHourOffset (input) { + if (!this.isValid()) { + return false; + } + input = input ? createLocal(input).utcOffset() : 0; + + return (this.utcOffset() - input) % 60 === 0; +} + +function isDaylightSavingTime () { + return ( + this.utcOffset() > this.clone().month(0).utcOffset() || + this.utcOffset() > this.clone().month(5).utcOffset() + ); +} + +function isDaylightSavingTimeShifted () { + if (!isUndefined(this._isDSTShifted)) { + return this._isDSTShifted; + } + + var c = {}; + + copyConfig(c, this); + c = prepareConfig(c); + + if (c._a) { + var other = c._isUTC ? createUTC(c._a) : createLocal(c._a); + this._isDSTShifted = this.isValid() && + compareArrays(c._a, other.toArray()) > 0; + } else { + this._isDSTShifted = false; + } + + return this._isDSTShifted; +} + +function isLocal () { + return this.isValid() ? !this._isUTC : false; +} + +function isUtcOffset () { + return this.isValid() ? this._isUTC : false; +} + +function isUtc () { + return this.isValid() ? this._isUTC && this._offset === 0 : false; +} + +// ASP.NET json date format regex +var aspNetRegex = /^(\-)?(?:(\d*)[. ])?(\d+)\:(\d+)(?:\:(\d+)(\.\d*)?)?$/; + +// from http://docs.closure-library.googlecode.com/git/closure_goog_date_date.js.source.html +// somewhat more in line with 4.4.3.2 2004 spec, but allows decimal anywhere +// and further modified to allow for strings containing both week and day +var isoRegex = /^(-)?P(?:(-?[0-9,.]*)Y)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)W)?(?:(-?[0-9,.]*)D)?(?:T(?:(-?[0-9,.]*)H)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)S)?)?$/; + +function createDuration (input, key) { + var duration = input, + // matching against regexp is expensive, do it on demand + match = null, + sign, + ret, + diffRes; + + if (isDuration(input)) { + duration = { + ms : input._milliseconds, + d : input._days, + M : input._months + }; + } else if (isNumber(input)) { + duration = {}; + if (key) { + duration[key] = input; + } else { + duration.milliseconds = input; + } + } else if (!!(match = aspNetRegex.exec(input))) { + sign = (match[1] === '-') ? -1 : 1; + duration = { + y : 0, + d : toInt(match[DATE]) * sign, + h : toInt(match[HOUR]) * sign, + m : toInt(match[MINUTE]) * sign, + s : toInt(match[SECOND]) * sign, + ms : toInt(absRound(match[MILLISECOND] * 1000)) * sign // the millisecond decimal point is included in the match + }; + } else if (!!(match = isoRegex.exec(input))) { + sign = (match[1] === '-') ? -1 : 1; + duration = { + y : parseIso(match[2], sign), + M : parseIso(match[3], sign), + w : parseIso(match[4], sign), + d : parseIso(match[5], sign), + h : parseIso(match[6], sign), + m : parseIso(match[7], sign), + s : parseIso(match[8], sign) + }; + } else if (duration == null) {// checks for null or undefined + duration = {}; + } else if (typeof duration === 'object' && ('from' in duration || 'to' in duration)) { + diffRes = momentsDifference(createLocal(duration.from), createLocal(duration.to)); + + duration = {}; + duration.ms = diffRes.milliseconds; + duration.M = diffRes.months; + } + + ret = new Duration(duration); + + if (isDuration(input) && hasOwnProp(input, '_locale')) { + ret._locale = input._locale; + } + + return ret; +} + +createDuration.fn = Duration.prototype; +createDuration.invalid = createInvalid$1; + +function parseIso (inp, sign) { + // We'd normally use ~~inp for this, but unfortunately it also + // converts floats to ints. + // inp may be undefined, so careful calling replace on it. + var res = inp && parseFloat(inp.replace(',', '.')); + // apply sign while we're at it + return (isNaN(res) ? 0 : res) * sign; +} + +function positiveMomentsDifference(base, other) { + var res = {milliseconds: 0, months: 0}; + + res.months = other.month() - base.month() + + (other.year() - base.year()) * 12; + if (base.clone().add(res.months, 'M').isAfter(other)) { + --res.months; + } + + res.milliseconds = +other - +(base.clone().add(res.months, 'M')); + + return res; +} + +function momentsDifference(base, other) { + var res; + if (!(base.isValid() && other.isValid())) { + return {milliseconds: 0, months: 0}; + } + + other = cloneWithOffset(other, base); + if (base.isBefore(other)) { + res = positiveMomentsDifference(base, other); + } else { + res = positiveMomentsDifference(other, base); + res.milliseconds = -res.milliseconds; + res.months = -res.months; + } + + return res; +} + +// TODO: remove 'name' arg after deprecation is removed +function createAdder(direction, name) { + return function (val, period) { + var dur, tmp; + //invert the arguments, but complain about it + if (period !== null && !isNaN(+period)) { + deprecateSimple(name, 'moment().' + name + '(period, number) is deprecated. Please use moment().' + name + '(number, period). ' + + 'See http://momentjs.com/guides/#/warnings/add-inverted-param/ for more info.'); + tmp = val; val = period; period = tmp; + } + + val = typeof val === 'string' ? +val : val; + dur = createDuration(val, period); + addSubtract(this, dur, direction); + return this; + }; +} + +function addSubtract (mom, duration, isAdding, updateOffset) { + var milliseconds = duration._milliseconds, + days = absRound(duration._days), + months = absRound(duration._months); + + if (!mom.isValid()) { + // No op + return; + } + + updateOffset = updateOffset == null ? true : updateOffset; + + if (milliseconds) { + mom._d.setTime(mom._d.valueOf() + milliseconds * isAdding); + } + if (days) { + set$1(mom, 'Date', get(mom, 'Date') + days * isAdding); + } + if (months) { + setMonth(mom, get(mom, 'Month') + months * isAdding); + } + if (updateOffset) { + hooks.updateOffset(mom, days || months); + } +} + +var add = createAdder(1, 'add'); +var subtract = createAdder(-1, 'subtract'); + +function getCalendarFormat(myMoment, now) { + var diff = myMoment.diff(now, 'days', true); + return diff < -6 ? 'sameElse' : + diff < -1 ? 'lastWeek' : + diff < 0 ? 'lastDay' : + diff < 1 ? 'sameDay' : + diff < 2 ? 'nextDay' : + diff < 7 ? 'nextWeek' : 'sameElse'; +} + +function calendar$1 (time, formats) { + // We want to compare the start of today, vs this. + // Getting start-of-today depends on whether we're local/utc/offset or not. + var now = time || createLocal(), + sod = cloneWithOffset(now, this).startOf('day'), + format = hooks.calendarFormat(this, sod) || 'sameElse'; + + var output = formats && (isFunction(formats[format]) ? formats[format].call(this, now) : formats[format]); + + return this.format(output || this.localeData().calendar(format, this, createLocal(now))); +} + +function clone () { + return new Moment(this); +} + +function isAfter (input, units) { + var localInput = isMoment(input) ? input : createLocal(input); + if (!(this.isValid() && localInput.isValid())) { + return false; + } + units = normalizeUnits(!isUndefined(units) ? units : 'millisecond'); + if (units === 'millisecond') { + return this.valueOf() > localInput.valueOf(); + } else { + return localInput.valueOf() < this.clone().startOf(units).valueOf(); + } +} + +function isBefore (input, units) { + var localInput = isMoment(input) ? input : createLocal(input); + if (!(this.isValid() && localInput.isValid())) { + return false; + } + units = normalizeUnits(!isUndefined(units) ? units : 'millisecond'); + if (units === 'millisecond') { + return this.valueOf() < localInput.valueOf(); + } else { + return this.clone().endOf(units).valueOf() < localInput.valueOf(); + } +} + +function isBetween (from, to, units, inclusivity) { + inclusivity = inclusivity || '()'; + return (inclusivity[0] === '(' ? this.isAfter(from, units) : !this.isBefore(from, units)) && + (inclusivity[1] === ')' ? this.isBefore(to, units) : !this.isAfter(to, units)); +} + +function isSame (input, units) { + var localInput = isMoment(input) ? input : createLocal(input), + inputMs; + if (!(this.isValid() && localInput.isValid())) { + return false; + } + units = normalizeUnits(units || 'millisecond'); + if (units === 'millisecond') { + return this.valueOf() === localInput.valueOf(); + } else { + inputMs = localInput.valueOf(); + return this.clone().startOf(units).valueOf() <= inputMs && inputMs <= this.clone().endOf(units).valueOf(); + } +} + +function isSameOrAfter (input, units) { + return this.isSame(input, units) || this.isAfter(input,units); +} + +function isSameOrBefore (input, units) { + return this.isSame(input, units) || this.isBefore(input,units); +} + +function diff (input, units, asFloat) { + var that, + zoneDelta, + delta, output; + + if (!this.isValid()) { + return NaN; + } + + that = cloneWithOffset(input, this); + + if (!that.isValid()) { + return NaN; + } + + zoneDelta = (that.utcOffset() - this.utcOffset()) * 6e4; + + units = normalizeUnits(units); + + if (units === 'year' || units === 'month' || units === 'quarter') { + output = monthDiff(this, that); + if (units === 'quarter') { + output = output / 3; + } else if (units === 'year') { + output = output / 12; + } + } else { + delta = this - that; + output = units === 'second' ? delta / 1e3 : // 1000 + units === 'minute' ? delta / 6e4 : // 1000 * 60 + units === 'hour' ? delta / 36e5 : // 1000 * 60 * 60 + units === 'day' ? (delta - zoneDelta) / 864e5 : // 1000 * 60 * 60 * 24, negate dst + units === 'week' ? (delta - zoneDelta) / 6048e5 : // 1000 * 60 * 60 * 24 * 7, negate dst + delta; + } + return asFloat ? output : absFloor(output); +} + +function monthDiff (a, b) { + // difference in months + var wholeMonthDiff = ((b.year() - a.year()) * 12) + (b.month() - a.month()), + // b is in (anchor - 1 month, anchor + 1 month) + anchor = a.clone().add(wholeMonthDiff, 'months'), + anchor2, adjust; + + if (b - anchor < 0) { + anchor2 = a.clone().add(wholeMonthDiff - 1, 'months'); + // linear across the month + adjust = (b - anchor) / (anchor - anchor2); + } else { + anchor2 = a.clone().add(wholeMonthDiff + 1, 'months'); + // linear across the month + adjust = (b - anchor) / (anchor2 - anchor); + } + + //check for negative zero, return zero if negative zero + return -(wholeMonthDiff + adjust) || 0; +} + +hooks.defaultFormat = 'YYYY-MM-DDTHH:mm:ssZ'; +hooks.defaultFormatUtc = 'YYYY-MM-DDTHH:mm:ss[Z]'; + +function toString () { + return this.clone().locale('en').format('ddd MMM DD YYYY HH:mm:ss [GMT]ZZ'); +} + +function toISOString() { + if (!this.isValid()) { + return null; + } + var m = this.clone().utc(); + if (m.year() < 0 || m.year() > 9999) { + return formatMoment(m, 'YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]'); + } + if (isFunction(Date.prototype.toISOString)) { + // native implementation is ~50x faster, use it when we can + return this.toDate().toISOString(); + } + return formatMoment(m, 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]'); +} + +/** + * Return a human readable representation of a moment that can + * also be evaluated to get a new moment which is the same + * + * @link https://nodejs.org/dist/latest/docs/api/util.html#util_custom_inspect_function_on_objects + */ +function inspect () { + if (!this.isValid()) { + return 'moment.invalid(/* ' + this._i + ' */)'; + } + var func = 'moment'; + var zone = ''; + if (!this.isLocal()) { + func = this.utcOffset() === 0 ? 'moment.utc' : 'moment.parseZone'; + zone = 'Z'; + } + var prefix = '[' + func + '("]'; + var year = (0 <= this.year() && this.year() <= 9999) ? 'YYYY' : 'YYYYYY'; + var datetime = '-MM-DD[T]HH:mm:ss.SSS'; + var suffix = zone + '[")]'; + + return this.format(prefix + year + datetime + suffix); +} + +function format (inputString) { + if (!inputString) { + inputString = this.isUtc() ? hooks.defaultFormatUtc : hooks.defaultFormat; + } + var output = formatMoment(this, inputString); + return this.localeData().postformat(output); +} + +function from (time, withoutSuffix) { + if (this.isValid() && + ((isMoment(time) && time.isValid()) || + createLocal(time).isValid())) { + return createDuration({to: this, from: time}).locale(this.locale()).humanize(!withoutSuffix); + } else { + return this.localeData().invalidDate(); + } +} + +function fromNow (withoutSuffix) { + return this.from(createLocal(), withoutSuffix); +} + +function to (time, withoutSuffix) { + if (this.isValid() && + ((isMoment(time) && time.isValid()) || + createLocal(time).isValid())) { + return createDuration({from: this, to: time}).locale(this.locale()).humanize(!withoutSuffix); + } else { + return this.localeData().invalidDate(); + } +} + +function toNow (withoutSuffix) { + return this.to(createLocal(), withoutSuffix); +} + +// If passed a locale key, it will set the locale for this +// instance. Otherwise, it will return the locale configuration +// variables for this instance. +function locale (key) { + var newLocaleData; + + if (key === undefined) { + return this._locale._abbr; + } else { + newLocaleData = getLocale(key); + if (newLocaleData != null) { + this._locale = newLocaleData; + } + return this; + } +} + +var lang = deprecate( + 'moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.', + function (key) { + if (key === undefined) { + return this.localeData(); + } else { + return this.locale(key); + } + } +); + +function localeData () { + return this._locale; +} + +function startOf (units) { + units = normalizeUnits(units); + // the following switch intentionally omits break keywords + // to utilize falling through the cases. + switch (units) { + case 'year': + this.month(0); + /* falls through */ + case 'quarter': + case 'month': + this.date(1); + /* falls through */ + case 'week': + case 'isoWeek': + case 'day': + case 'date': + this.hours(0); + /* falls through */ + case 'hour': + this.minutes(0); + /* falls through */ + case 'minute': + this.seconds(0); + /* falls through */ + case 'second': + this.milliseconds(0); + } + + // weeks are a special case + if (units === 'week') { + this.weekday(0); + } + if (units === 'isoWeek') { + this.isoWeekday(1); + } + + // quarters are also special + if (units === 'quarter') { + this.month(Math.floor(this.month() / 3) * 3); + } + + return this; +} + +function endOf (units) { + units = normalizeUnits(units); + if (units === undefined || units === 'millisecond') { + return this; + } + + // 'date' is an alias for 'day', so it should be considered as such. + if (units === 'date') { + units = 'day'; + } + + return this.startOf(units).add(1, (units === 'isoWeek' ? 'week' : units)).subtract(1, 'ms'); +} + +function valueOf () { + return this._d.valueOf() - ((this._offset || 0) * 60000); +} + +function unix () { + return Math.floor(this.valueOf() / 1000); +} + +function toDate () { + return new Date(this.valueOf()); +} + +function toArray () { + var m = this; + return [m.year(), m.month(), m.date(), m.hour(), m.minute(), m.second(), m.millisecond()]; +} + +function toObject () { + var m = this; + return { + years: m.year(), + months: m.month(), + date: m.date(), + hours: m.hours(), + minutes: m.minutes(), + seconds: m.seconds(), + milliseconds: m.milliseconds() + }; +} + +function toJSON () { + // new Date(NaN).toJSON() === null + return this.isValid() ? this.toISOString() : null; +} + +function isValid$2 () { + return isValid(this); +} + +function parsingFlags () { + return extend({}, getParsingFlags(this)); +} + +function invalidAt () { + return getParsingFlags(this).overflow; +} + +function creationData() { + return { + input: this._i, + format: this._f, + locale: this._locale, + isUTC: this._isUTC, + strict: this._strict + }; +} + +// FORMATTING + +addFormatToken(0, ['gg', 2], 0, function () { + return this.weekYear() % 100; +}); + +addFormatToken(0, ['GG', 2], 0, function () { + return this.isoWeekYear() % 100; +}); + +function addWeekYearFormatToken (token, getter) { + addFormatToken(0, [token, token.length], 0, getter); +} + +addWeekYearFormatToken('gggg', 'weekYear'); +addWeekYearFormatToken('ggggg', 'weekYear'); +addWeekYearFormatToken('GGGG', 'isoWeekYear'); +addWeekYearFormatToken('GGGGG', 'isoWeekYear'); + +// ALIASES + +addUnitAlias('weekYear', 'gg'); +addUnitAlias('isoWeekYear', 'GG'); + +// PRIORITY + +addUnitPriority('weekYear', 1); +addUnitPriority('isoWeekYear', 1); + + +// PARSING + +addRegexToken('G', matchSigned); +addRegexToken('g', matchSigned); +addRegexToken('GG', match1to2, match2); +addRegexToken('gg', match1to2, match2); +addRegexToken('GGGG', match1to4, match4); +addRegexToken('gggg', match1to4, match4); +addRegexToken('GGGGG', match1to6, match6); +addRegexToken('ggggg', match1to6, match6); + +addWeekParseToken(['gggg', 'ggggg', 'GGGG', 'GGGGG'], function (input, week, config, token) { + week[token.substr(0, 2)] = toInt(input); +}); + +addWeekParseToken(['gg', 'GG'], function (input, week, config, token) { + week[token] = hooks.parseTwoDigitYear(input); +}); + +// MOMENTS + +function getSetWeekYear (input) { + return getSetWeekYearHelper.call(this, + input, + this.week(), + this.weekday(), + this.localeData()._week.dow, + this.localeData()._week.doy); +} + +function getSetISOWeekYear (input) { + return getSetWeekYearHelper.call(this, + input, this.isoWeek(), this.isoWeekday(), 1, 4); +} + +function getISOWeeksInYear () { + return weeksInYear(this.year(), 1, 4); +} + +function getWeeksInYear () { + var weekInfo = this.localeData()._week; + return weeksInYear(this.year(), weekInfo.dow, weekInfo.doy); +} + +function getSetWeekYearHelper(input, week, weekday, dow, doy) { + var weeksTarget; + if (input == null) { + return weekOfYear(this, dow, doy).year; + } else { + weeksTarget = weeksInYear(input, dow, doy); + if (week > weeksTarget) { + week = weeksTarget; + } + return setWeekAll.call(this, input, week, weekday, dow, doy); + } +} + +function setWeekAll(weekYear, week, weekday, dow, doy) { + var dayOfYearData = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy), + date = createUTCDate(dayOfYearData.year, 0, dayOfYearData.dayOfYear); + + this.year(date.getUTCFullYear()); + this.month(date.getUTCMonth()); + this.date(date.getUTCDate()); + return this; +} + +// FORMATTING + +addFormatToken('Q', 0, 'Qo', 'quarter'); + +// ALIASES + +addUnitAlias('quarter', 'Q'); + +// PRIORITY + +addUnitPriority('quarter', 7); + +// PARSING + +addRegexToken('Q', match1); +addParseToken('Q', function (input, array) { + array[MONTH] = (toInt(input) - 1) * 3; +}); + +// MOMENTS + +function getSetQuarter (input) { + return input == null ? Math.ceil((this.month() + 1) / 3) : this.month((input - 1) * 3 + this.month() % 3); +} + +// FORMATTING + +addFormatToken('D', ['DD', 2], 'Do', 'date'); + +// ALIASES + +addUnitAlias('date', 'D'); + +// PRIOROITY +addUnitPriority('date', 9); + +// PARSING + +addRegexToken('D', match1to2); +addRegexToken('DD', match1to2, match2); +addRegexToken('Do', function (isStrict, locale) { + // TODO: Remove "ordinalParse" fallback in next major release. + return isStrict ? + (locale._dayOfMonthOrdinalParse || locale._ordinalParse) : + locale._dayOfMonthOrdinalParseLenient; +}); + +addParseToken(['D', 'DD'], DATE); +addParseToken('Do', function (input, array) { + array[DATE] = toInt(input.match(match1to2)[0], 10); +}); + +// MOMENTS + +var getSetDayOfMonth = makeGetSet('Date', true); + +// FORMATTING + +addFormatToken('DDD', ['DDDD', 3], 'DDDo', 'dayOfYear'); + +// ALIASES + +addUnitAlias('dayOfYear', 'DDD'); + +// PRIORITY +addUnitPriority('dayOfYear', 4); + +// PARSING + +addRegexToken('DDD', match1to3); +addRegexToken('DDDD', match3); +addParseToken(['DDD', 'DDDD'], function (input, array, config) { + config._dayOfYear = toInt(input); +}); + +// HELPERS + +// MOMENTS + +function getSetDayOfYear (input) { + var dayOfYear = Math.round((this.clone().startOf('day') - this.clone().startOf('year')) / 864e5) + 1; + return input == null ? dayOfYear : this.add((input - dayOfYear), 'd'); +} + +// FORMATTING + +addFormatToken('m', ['mm', 2], 0, 'minute'); + +// ALIASES + +addUnitAlias('minute', 'm'); + +// PRIORITY + +addUnitPriority('minute', 14); + +// PARSING + +addRegexToken('m', match1to2); +addRegexToken('mm', match1to2, match2); +addParseToken(['m', 'mm'], MINUTE); + +// MOMENTS + +var getSetMinute = makeGetSet('Minutes', false); + +// FORMATTING + +addFormatToken('s', ['ss', 2], 0, 'second'); + +// ALIASES + +addUnitAlias('second', 's'); + +// PRIORITY + +addUnitPriority('second', 15); + +// PARSING + +addRegexToken('s', match1to2); +addRegexToken('ss', match1to2, match2); +addParseToken(['s', 'ss'], SECOND); + +// MOMENTS + +var getSetSecond = makeGetSet('Seconds', false); + +// FORMATTING + +addFormatToken('S', 0, 0, function () { + return ~~(this.millisecond() / 100); +}); + +addFormatToken(0, ['SS', 2], 0, function () { + return ~~(this.millisecond() / 10); +}); + +addFormatToken(0, ['SSS', 3], 0, 'millisecond'); +addFormatToken(0, ['SSSS', 4], 0, function () { + return this.millisecond() * 10; +}); +addFormatToken(0, ['SSSSS', 5], 0, function () { + return this.millisecond() * 100; +}); +addFormatToken(0, ['SSSSSS', 6], 0, function () { + return this.millisecond() * 1000; +}); +addFormatToken(0, ['SSSSSSS', 7], 0, function () { + return this.millisecond() * 10000; +}); +addFormatToken(0, ['SSSSSSSS', 8], 0, function () { + return this.millisecond() * 100000; +}); +addFormatToken(0, ['SSSSSSSSS', 9], 0, function () { + return this.millisecond() * 1000000; +}); + + +// ALIASES + +addUnitAlias('millisecond', 'ms'); + +// PRIORITY + +addUnitPriority('millisecond', 16); + +// PARSING + +addRegexToken('S', match1to3, match1); +addRegexToken('SS', match1to3, match2); +addRegexToken('SSS', match1to3, match3); + +var token; +for (token = 'SSSS'; token.length <= 9; token += 'S') { + addRegexToken(token, matchUnsigned); +} + +function parseMs(input, array) { + array[MILLISECOND] = toInt(('0.' + input) * 1000); +} + +for (token = 'S'; token.length <= 9; token += 'S') { + addParseToken(token, parseMs); +} +// MOMENTS + +var getSetMillisecond = makeGetSet('Milliseconds', false); + +// FORMATTING + +addFormatToken('z', 0, 0, 'zoneAbbr'); +addFormatToken('zz', 0, 0, 'zoneName'); + +// MOMENTS + +function getZoneAbbr () { + return this._isUTC ? 'UTC' : ''; +} + +function getZoneName () { + return this._isUTC ? 'Coordinated Universal Time' : ''; +} + +var proto = Moment.prototype; + +proto.add = add; +proto.calendar = calendar$1; +proto.clone = clone; +proto.diff = diff; +proto.endOf = endOf; +proto.format = format; +proto.from = from; +proto.fromNow = fromNow; +proto.to = to; +proto.toNow = toNow; +proto.get = stringGet; +proto.invalidAt = invalidAt; +proto.isAfter = isAfter; +proto.isBefore = isBefore; +proto.isBetween = isBetween; +proto.isSame = isSame; +proto.isSameOrAfter = isSameOrAfter; +proto.isSameOrBefore = isSameOrBefore; +proto.isValid = isValid$2; +proto.lang = lang; +proto.locale = locale; +proto.localeData = localeData; +proto.max = prototypeMax; +proto.min = prototypeMin; +proto.parsingFlags = parsingFlags; +proto.set = stringSet; +proto.startOf = startOf; +proto.subtract = subtract; +proto.toArray = toArray; +proto.toObject = toObject; +proto.toDate = toDate; +proto.toISOString = toISOString; +proto.inspect = inspect; +proto.toJSON = toJSON; +proto.toString = toString; +proto.unix = unix; +proto.valueOf = valueOf; +proto.creationData = creationData; + +// Year +proto.year = getSetYear; +proto.isLeapYear = getIsLeapYear; + +// Week Year +proto.weekYear = getSetWeekYear; +proto.isoWeekYear = getSetISOWeekYear; + +// Quarter +proto.quarter = proto.quarters = getSetQuarter; + +// Month +proto.month = getSetMonth; +proto.daysInMonth = getDaysInMonth; + +// Week +proto.week = proto.weeks = getSetWeek; +proto.isoWeek = proto.isoWeeks = getSetISOWeek; +proto.weeksInYear = getWeeksInYear; +proto.isoWeeksInYear = getISOWeeksInYear; + +// Day +proto.date = getSetDayOfMonth; +proto.day = proto.days = getSetDayOfWeek; +proto.weekday = getSetLocaleDayOfWeek; +proto.isoWeekday = getSetISODayOfWeek; +proto.dayOfYear = getSetDayOfYear; + +// Hour +proto.hour = proto.hours = getSetHour; + +// Minute +proto.minute = proto.minutes = getSetMinute; + +// Second +proto.second = proto.seconds = getSetSecond; + +// Millisecond +proto.millisecond = proto.milliseconds = getSetMillisecond; + +// Offset +proto.utcOffset = getSetOffset; +proto.utc = setOffsetToUTC; +proto.local = setOffsetToLocal; +proto.parseZone = setOffsetToParsedOffset; +proto.hasAlignedHourOffset = hasAlignedHourOffset; +proto.isDST = isDaylightSavingTime; +proto.isLocal = isLocal; +proto.isUtcOffset = isUtcOffset; +proto.isUtc = isUtc; +proto.isUTC = isUtc; + +// Timezone +proto.zoneAbbr = getZoneAbbr; +proto.zoneName = getZoneName; + +// Deprecations +proto.dates = deprecate('dates accessor is deprecated. Use date instead.', getSetDayOfMonth); +proto.months = deprecate('months accessor is deprecated. Use month instead', getSetMonth); +proto.years = deprecate('years accessor is deprecated. Use year instead', getSetYear); +proto.zone = deprecate('moment().zone is deprecated, use moment().utcOffset instead. http://momentjs.com/guides/#/warnings/zone/', getSetZone); +proto.isDSTShifted = deprecate('isDSTShifted is deprecated. See http://momentjs.com/guides/#/warnings/dst-shifted/ for more information', isDaylightSavingTimeShifted); + +function createUnix (input) { + return createLocal(input * 1000); +} + +function createInZone () { + return createLocal.apply(null, arguments).parseZone(); +} + +function preParsePostFormat (string) { + return string; +} + +var proto$1 = Locale.prototype; + +proto$1.calendar = calendar; +proto$1.longDateFormat = longDateFormat; +proto$1.invalidDate = invalidDate; +proto$1.ordinal = ordinal; +proto$1.preparse = preParsePostFormat; +proto$1.postformat = preParsePostFormat; +proto$1.relativeTime = relativeTime; +proto$1.pastFuture = pastFuture; +proto$1.set = set; + +// Month +proto$1.months = localeMonths; +proto$1.monthsShort = localeMonthsShort; +proto$1.monthsParse = localeMonthsParse; +proto$1.monthsRegex = monthsRegex; +proto$1.monthsShortRegex = monthsShortRegex; + +// Week +proto$1.week = localeWeek; +proto$1.firstDayOfYear = localeFirstDayOfYear; +proto$1.firstDayOfWeek = localeFirstDayOfWeek; + +// Day of Week +proto$1.weekdays = localeWeekdays; +proto$1.weekdaysMin = localeWeekdaysMin; +proto$1.weekdaysShort = localeWeekdaysShort; +proto$1.weekdaysParse = localeWeekdaysParse; + +proto$1.weekdaysRegex = weekdaysRegex; +proto$1.weekdaysShortRegex = weekdaysShortRegex; +proto$1.weekdaysMinRegex = weekdaysMinRegex; + +// Hours +proto$1.isPM = localeIsPM; +proto$1.meridiem = localeMeridiem; + +function get$1 (format, index, field, setter) { + var locale = getLocale(); + var utc = createUTC().set(setter, index); + return locale[field](utc, format); +} + +function listMonthsImpl (format, index, field) { + if (isNumber(format)) { + index = format; + format = undefined; + } + + format = format || ''; + + if (index != null) { + return get$1(format, index, field, 'month'); + } + + var i; + var out = []; + for (i = 0; i < 12; i++) { + out[i] = get$1(format, i, field, 'month'); + } + return out; +} + +// () +// (5) +// (fmt, 5) +// (fmt) +// (true) +// (true, 5) +// (true, fmt, 5) +// (true, fmt) +function listWeekdaysImpl (localeSorted, format, index, field) { + if (typeof localeSorted === 'boolean') { + if (isNumber(format)) { + index = format; + format = undefined; + } + + format = format || ''; + } else { + format = localeSorted; + index = format; + localeSorted = false; + + if (isNumber(format)) { + index = format; + format = undefined; + } + + format = format || ''; + } + + var locale = getLocale(), + shift = localeSorted ? locale._week.dow : 0; + + if (index != null) { + return get$1(format, (index + shift) % 7, field, 'day'); + } + + var i; + var out = []; + for (i = 0; i < 7; i++) { + out[i] = get$1(format, (i + shift) % 7, field, 'day'); + } + return out; +} + +function listMonths (format, index) { + return listMonthsImpl(format, index, 'months'); +} + +function listMonthsShort (format, index) { + return listMonthsImpl(format, index, 'monthsShort'); +} + +function listWeekdays (localeSorted, format, index) { + return listWeekdaysImpl(localeSorted, format, index, 'weekdays'); +} + +function listWeekdaysShort (localeSorted, format, index) { + return listWeekdaysImpl(localeSorted, format, index, 'weekdaysShort'); +} + +function listWeekdaysMin (localeSorted, format, index) { + return listWeekdaysImpl(localeSorted, format, index, 'weekdaysMin'); +} + +getSetGlobalLocale('en', { + dayOfMonthOrdinalParse: /\d{1,2}(th|st|nd|rd)/, + ordinal : function (number) { + var b = number % 10, + output = (toInt(number % 100 / 10) === 1) ? 'th' : + (b === 1) ? 'st' : + (b === 2) ? 'nd' : + (b === 3) ? 'rd' : 'th'; + return number + output; + } +}); + +// Side effect imports +hooks.lang = deprecate('moment.lang is deprecated. Use moment.locale instead.', getSetGlobalLocale); +hooks.langData = deprecate('moment.langData is deprecated. Use moment.localeData instead.', getLocale); + +var mathAbs = Math.abs; + +function abs () { + var data = this._data; + + this._milliseconds = mathAbs(this._milliseconds); + this._days = mathAbs(this._days); + this._months = mathAbs(this._months); + + data.milliseconds = mathAbs(data.milliseconds); + data.seconds = mathAbs(data.seconds); + data.minutes = mathAbs(data.minutes); + data.hours = mathAbs(data.hours); + data.months = mathAbs(data.months); + data.years = mathAbs(data.years); + + return this; +} + +function addSubtract$1 (duration, input, value, direction) { + var other = createDuration(input, value); + + duration._milliseconds += direction * other._milliseconds; + duration._days += direction * other._days; + duration._months += direction * other._months; + + return duration._bubble(); +} + +// supports only 2.0-style add(1, 's') or add(duration) +function add$1 (input, value) { + return addSubtract$1(this, input, value, 1); +} + +// supports only 2.0-style subtract(1, 's') or subtract(duration) +function subtract$1 (input, value) { + return addSubtract$1(this, input, value, -1); +} + +function absCeil (number) { + if (number < 0) { + return Math.floor(number); + } else { + return Math.ceil(number); + } +} + +function bubble () { + var milliseconds = this._milliseconds; + var days = this._days; + var months = this._months; + var data = this._data; + var seconds, minutes, hours, years, monthsFromDays; + + // if we have a mix of positive and negative values, bubble down first + // check: https://github.com/moment/moment/issues/2166 + if (!((milliseconds >= 0 && days >= 0 && months >= 0) || + (milliseconds <= 0 && days <= 0 && months <= 0))) { + milliseconds += absCeil(monthsToDays(months) + days) * 864e5; + days = 0; + months = 0; + } + + // The following code bubbles up values, see the tests for + // examples of what that means. + data.milliseconds = milliseconds % 1000; + + seconds = absFloor(milliseconds / 1000); + data.seconds = seconds % 60; + + minutes = absFloor(seconds / 60); + data.minutes = minutes % 60; + + hours = absFloor(minutes / 60); + data.hours = hours % 24; + + days += absFloor(hours / 24); + + // convert days to months + monthsFromDays = absFloor(daysToMonths(days)); + months += monthsFromDays; + days -= absCeil(monthsToDays(monthsFromDays)); + + // 12 months -> 1 year + years = absFloor(months / 12); + months %= 12; + + data.days = days; + data.months = months; + data.years = years; + + return this; +} + +function daysToMonths (days) { + // 400 years have 146097 days (taking into account leap year rules) + // 400 years have 12 months === 4800 + return days * 4800 / 146097; +} + +function monthsToDays (months) { + // the reverse of daysToMonths + return months * 146097 / 4800; +} + +function as (units) { + if (!this.isValid()) { + return NaN; + } + var days; + var months; + var milliseconds = this._milliseconds; + + units = normalizeUnits(units); + + if (units === 'month' || units === 'year') { + days = this._days + milliseconds / 864e5; + months = this._months + daysToMonths(days); + return units === 'month' ? months : months / 12; + } else { + // handle milliseconds separately because of floating point math errors (issue #1867) + days = this._days + Math.round(monthsToDays(this._months)); + switch (units) { + case 'week' : return days / 7 + milliseconds / 6048e5; + case 'day' : return days + milliseconds / 864e5; + case 'hour' : return days * 24 + milliseconds / 36e5; + case 'minute' : return days * 1440 + milliseconds / 6e4; + case 'second' : return days * 86400 + milliseconds / 1000; + // Math.floor prevents floating point math errors here + case 'millisecond': return Math.floor(days * 864e5) + milliseconds; + default: throw new Error('Unknown unit ' + units); + } + } +} + +// TODO: Use this.as('ms')? +function valueOf$1 () { + if (!this.isValid()) { + return NaN; + } + return ( + this._milliseconds + + this._days * 864e5 + + (this._months % 12) * 2592e6 + + toInt(this._months / 12) * 31536e6 + ); +} + +function makeAs (alias) { + return function () { + return this.as(alias); + }; +} + +var asMilliseconds = makeAs('ms'); +var asSeconds = makeAs('s'); +var asMinutes = makeAs('m'); +var asHours = makeAs('h'); +var asDays = makeAs('d'); +var asWeeks = makeAs('w'); +var asMonths = makeAs('M'); +var asYears = makeAs('y'); + +function get$2 (units) { + units = normalizeUnits(units); + return this.isValid() ? this[units + 's']() : NaN; +} + +function makeGetter(name) { + return function () { + return this.isValid() ? this._data[name] : NaN; + }; +} + +var milliseconds = makeGetter('milliseconds'); +var seconds = makeGetter('seconds'); +var minutes = makeGetter('minutes'); +var hours = makeGetter('hours'); +var days = makeGetter('days'); +var months = makeGetter('months'); +var years = makeGetter('years'); + +function weeks () { + return absFloor(this.days() / 7); +} + +var round = Math.round; +var thresholds = { + ss: 44, // a few seconds to seconds + s : 45, // seconds to minute + m : 45, // minutes to hour + h : 22, // hours to day + d : 26, // days to month + M : 11 // months to year +}; + +// helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize +function substituteTimeAgo(string, number, withoutSuffix, isFuture, locale) { + return locale.relativeTime(number || 1, !!withoutSuffix, string, isFuture); +} + +function relativeTime$1 (posNegDuration, withoutSuffix, locale) { + var duration = createDuration(posNegDuration).abs(); + var seconds = round(duration.as('s')); + var minutes = round(duration.as('m')); + var hours = round(duration.as('h')); + var days = round(duration.as('d')); + var months = round(duration.as('M')); + var years = round(duration.as('y')); + + var a = seconds <= thresholds.ss && ['s', seconds] || + seconds < thresholds.s && ['ss', seconds] || + minutes <= 1 && ['m'] || + minutes < thresholds.m && ['mm', minutes] || + hours <= 1 && ['h'] || + hours < thresholds.h && ['hh', hours] || + days <= 1 && ['d'] || + days < thresholds.d && ['dd', days] || + months <= 1 && ['M'] || + months < thresholds.M && ['MM', months] || + years <= 1 && ['y'] || ['yy', years]; + + a[2] = withoutSuffix; + a[3] = +posNegDuration > 0; + a[4] = locale; + return substituteTimeAgo.apply(null, a); +} + +// This function allows you to set the rounding function for relative time strings +function getSetRelativeTimeRounding (roundingFunction) { + if (roundingFunction === undefined) { + return round; + } + if (typeof(roundingFunction) === 'function') { + round = roundingFunction; + return true; + } + return false; +} + +// This function allows you to set a threshold for relative time strings +function getSetRelativeTimeThreshold (threshold, limit) { + if (thresholds[threshold] === undefined) { + return false; + } + if (limit === undefined) { + return thresholds[threshold]; + } + thresholds[threshold] = limit; + if (threshold === 's') { + thresholds.ss = limit - 1; + } + return true; +} + +function humanize (withSuffix) { + if (!this.isValid()) { + return this.localeData().invalidDate(); + } + + var locale = this.localeData(); + var output = relativeTime$1(this, !withSuffix, locale); + + if (withSuffix) { + output = locale.pastFuture(+this, output); + } + + return locale.postformat(output); +} + +var abs$1 = Math.abs; + +function toISOString$1() { + // for ISO strings we do not use the normal bubbling rules: + // * milliseconds bubble up until they become hours + // * days do not bubble at all + // * months bubble up until they become years + // This is because there is no context-free conversion between hours and days + // (think of clock changes) + // and also not between days and months (28-31 days per month) + if (!this.isValid()) { + return this.localeData().invalidDate(); + } + + var seconds = abs$1(this._milliseconds) / 1000; + var days = abs$1(this._days); + var months = abs$1(this._months); + var minutes, hours, years; + + // 3600 seconds -> 60 minutes -> 1 hour + minutes = absFloor(seconds / 60); + hours = absFloor(minutes / 60); + seconds %= 60; + minutes %= 60; + + // 12 months -> 1 year + years = absFloor(months / 12); + months %= 12; + + + // inspired by https://github.com/dordille/moment-isoduration/blob/master/moment.isoduration.js + var Y = years; + var M = months; + var D = days; + var h = hours; + var m = minutes; + var s = seconds; + var total = this.asSeconds(); + + if (!total) { + // this is the same as C#'s (Noda) and python (isodate)... + // but not other JS (goog.date) + return 'P0D'; + } + + return (total < 0 ? '-' : '') + + 'P' + + (Y ? Y + 'Y' : '') + + (M ? M + 'M' : '') + + (D ? D + 'D' : '') + + ((h || m || s) ? 'T' : '') + + (h ? h + 'H' : '') + + (m ? m + 'M' : '') + + (s ? s + 'S' : ''); +} + +var proto$2 = Duration.prototype; + +proto$2.isValid = isValid$1; +proto$2.abs = abs; +proto$2.add = add$1; +proto$2.subtract = subtract$1; +proto$2.as = as; +proto$2.asMilliseconds = asMilliseconds; +proto$2.asSeconds = asSeconds; +proto$2.asMinutes = asMinutes; +proto$2.asHours = asHours; +proto$2.asDays = asDays; +proto$2.asWeeks = asWeeks; +proto$2.asMonths = asMonths; +proto$2.asYears = asYears; +proto$2.valueOf = valueOf$1; +proto$2._bubble = bubble; +proto$2.get = get$2; +proto$2.milliseconds = milliseconds; +proto$2.seconds = seconds; +proto$2.minutes = minutes; +proto$2.hours = hours; +proto$2.days = days; +proto$2.weeks = weeks; +proto$2.months = months; +proto$2.years = years; +proto$2.humanize = humanize; +proto$2.toISOString = toISOString$1; +proto$2.toString = toISOString$1; +proto$2.toJSON = toISOString$1; +proto$2.locale = locale; +proto$2.localeData = localeData; + +// Deprecations +proto$2.toIsoString = deprecate('toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)', toISOString$1); +proto$2.lang = lang; + +// Side effect imports + +// FORMATTING + +addFormatToken('X', 0, 0, 'unix'); +addFormatToken('x', 0, 0, 'valueOf'); + +// PARSING + +addRegexToken('x', matchSigned); +addRegexToken('X', matchTimestamp); +addParseToken('X', function (input, array, config) { + config._d = new Date(parseFloat(input, 10) * 1000); +}); +addParseToken('x', function (input, array, config) { + config._d = new Date(toInt(input)); +}); + +// Side effect imports + + +hooks.version = '2.18.1'; + +setHookCallback(createLocal); + +hooks.fn = proto; +hooks.min = min; +hooks.max = max; +hooks.now = now; +hooks.utc = createUTC; +hooks.unix = createUnix; +hooks.months = listMonths; +hooks.isDate = isDate; +hooks.locale = getSetGlobalLocale; +hooks.invalid = createInvalid; +hooks.duration = createDuration; +hooks.isMoment = isMoment; +hooks.weekdays = listWeekdays; +hooks.parseZone = createInZone; +hooks.localeData = getLocale; +hooks.isDuration = isDuration; +hooks.monthsShort = listMonthsShort; +hooks.weekdaysMin = listWeekdaysMin; +hooks.defineLocale = defineLocale; +hooks.updateLocale = updateLocale; +hooks.locales = listLocales; +hooks.weekdaysShort = listWeekdaysShort; +hooks.normalizeUnits = normalizeUnits; +hooks.relativeTimeRounding = getSetRelativeTimeRounding; +hooks.relativeTimeThreshold = getSetRelativeTimeThreshold; +hooks.calendarFormat = getCalendarFormat; +hooks.prototype = proto; + +return hooks; + +}))); + +},{}],7:[function(require,module,exports){ +/** + * @namespace Chart + */ +var Chart = require(29)(); + +Chart.helpers = require(45); + +// @todo dispatch these helpers into appropriated helpers/helpers.* file and write unit tests! +require(27)(Chart); + +Chart.defaults = require(25); +Chart.Element = require(26); +Chart.elements = require(40); +Chart.Interaction = require(28); +Chart.platform = require(48); + +require(31)(Chart); +require(22)(Chart); +require(23)(Chart); +require(24)(Chart); +require(30)(Chart); +require(33)(Chart); +require(32)(Chart); +require(35)(Chart); + +require(54)(Chart); +require(52)(Chart); +require(53)(Chart); +require(55)(Chart); +require(56)(Chart); +require(57)(Chart); + +// Controllers must be loaded after elements +// See Chart.core.datasetController.dataElementType +require(15)(Chart); +require(16)(Chart); +require(17)(Chart); +require(18)(Chart); +require(19)(Chart); +require(20)(Chart); +require(21)(Chart); + +require(8)(Chart); +require(9)(Chart); +require(10)(Chart); +require(11)(Chart); +require(12)(Chart); +require(13)(Chart); +require(14)(Chart); + +// Loading built-it plugins +var plugins = []; + +plugins.push( + require(49)(Chart), + require(50)(Chart), + require(51)(Chart) +); + +Chart.plugins.register(plugins); + +Chart.platform.initialize(); + +module.exports = Chart; +if (typeof window !== 'undefined') { + window.Chart = Chart; +} + +// DEPRECATIONS + +/** + * Provided for backward compatibility, use Chart.helpers.canvas instead. + * @namespace Chart.canvasHelpers + * @deprecated since version 2.6.0 + * @todo remove at version 3 + * @private + */ +Chart.canvasHelpers = Chart.helpers.canvas; + +},{"10":10,"11":11,"12":12,"13":13,"14":14,"15":15,"16":16,"17":17,"18":18,"19":19,"20":20,"21":21,"22":22,"23":23,"24":24,"25":25,"26":26,"27":27,"28":28,"29":29,"30":30,"31":31,"32":32,"33":33,"35":35,"40":40,"45":45,"48":48,"49":49,"50":50,"51":51,"52":52,"53":53,"54":54,"55":55,"56":56,"57":57,"8":8,"9":9}],8:[function(require,module,exports){ +'use strict'; + +module.exports = function(Chart) { + + Chart.Bar = function(context, config) { + config.type = 'bar'; + + return new Chart(context, config); + }; + +}; + +},{}],9:[function(require,module,exports){ +'use strict'; + +module.exports = function(Chart) { + + Chart.Bubble = function(context, config) { + config.type = 'bubble'; + return new Chart(context, config); + }; + +}; + +},{}],10:[function(require,module,exports){ +'use strict'; + +module.exports = function(Chart) { + + Chart.Doughnut = function(context, config) { + config.type = 'doughnut'; + + return new Chart(context, config); + }; + +}; + +},{}],11:[function(require,module,exports){ +'use strict'; + +module.exports = function(Chart) { + + Chart.Line = function(context, config) { + config.type = 'line'; + + return new Chart(context, config); + }; + +}; + +},{}],12:[function(require,module,exports){ +'use strict'; + +module.exports = function(Chart) { + + Chart.PolarArea = function(context, config) { + config.type = 'polarArea'; + + return new Chart(context, config); + }; + +}; + +},{}],13:[function(require,module,exports){ +'use strict'; + +module.exports = function(Chart) { + + Chart.Radar = function(context, config) { + config.type = 'radar'; + + return new Chart(context, config); + }; + +}; + +},{}],14:[function(require,module,exports){ +'use strict'; + +module.exports = function(Chart) { + Chart.Scatter = function(context, config) { + config.type = 'scatter'; + return new Chart(context, config); + }; +}; + +},{}],15:[function(require,module,exports){ +'use strict'; + +var defaults = require(25); +var elements = require(40); +var helpers = require(45); + +defaults._set('bar', { + hover: { + mode: 'label' + }, + + scales: { + xAxes: [{ + type: 'category', + + // Specific to Bar Controller + categoryPercentage: 0.8, + barPercentage: 0.9, + + // offset settings + offset: true, + + // grid line settings + gridLines: { + offsetGridLines: true + } + }], + + yAxes: [{ + type: 'linear' + }] + } +}); + +defaults._set('horizontalBar', { + hover: { + mode: 'index', + axis: 'y' + }, + + scales: { + xAxes: [{ + type: 'linear', + position: 'bottom' + }], + + yAxes: [{ + position: 'left', + type: 'category', + + // Specific to Horizontal Bar Controller + categoryPercentage: 0.8, + barPercentage: 0.9, + + // offset settings + offset: true, + + // grid line settings + gridLines: { + offsetGridLines: true + } + }] + }, + + elements: { + rectangle: { + borderSkipped: 'left' + } + }, + + tooltips: { + callbacks: { + title: function(item, data) { + // Pick first xLabel for now + var title = ''; + + if (item.length > 0) { + if (item[0].yLabel) { + title = item[0].yLabel; + } else if (data.labels.length > 0 && item[0].index < data.labels.length) { + title = data.labels[item[0].index]; + } + } + + return title; + }, + + label: function(item, data) { + var datasetLabel = data.datasets[item.datasetIndex].label || ''; + return datasetLabel + ': ' + item.xLabel; + } + }, + mode: 'index', + axis: 'y' + } +}); + +module.exports = function(Chart) { + + Chart.controllers.bar = Chart.DatasetController.extend({ + + dataElementType: elements.Rectangle, + + initialize: function() { + var me = this; + var meta; + + Chart.DatasetController.prototype.initialize.apply(me, arguments); + + meta = me.getMeta(); + meta.stack = me.getDataset().stack; + meta.bar = true; + }, + + update: function(reset) { + var me = this; + var rects = me.getMeta().data; + var i, ilen; + + me._ruler = me.getRuler(); + + for (i = 0, ilen = rects.length; i < ilen; ++i) { + me.updateElement(rects[i], i, reset); + } + }, + + updateElement: function(rectangle, index, reset) { + var me = this; + var chart = me.chart; + var meta = me.getMeta(); + var dataset = me.getDataset(); + var custom = rectangle.custom || {}; + var rectangleOptions = chart.options.elements.rectangle; + + rectangle._xScale = me.getScaleForId(meta.xAxisID); + rectangle._yScale = me.getScaleForId(meta.yAxisID); + rectangle._datasetIndex = me.index; + rectangle._index = index; + + rectangle._model = { + datasetLabel: dataset.label, + label: chart.data.labels[index], + borderSkipped: custom.borderSkipped ? custom.borderSkipped : rectangleOptions.borderSkipped, + backgroundColor: custom.backgroundColor ? custom.backgroundColor : helpers.valueAtIndexOrDefault(dataset.backgroundColor, index, rectangleOptions.backgroundColor), + borderColor: custom.borderColor ? custom.borderColor : helpers.valueAtIndexOrDefault(dataset.borderColor, index, rectangleOptions.borderColor), + borderWidth: custom.borderWidth ? custom.borderWidth : helpers.valueAtIndexOrDefault(dataset.borderWidth, index, rectangleOptions.borderWidth) + }; + + me.updateElementGeometry(rectangle, index, reset); + + rectangle.pivot(); + }, + + /** + * @private + */ + updateElementGeometry: function(rectangle, index, reset) { + var me = this; + var model = rectangle._model; + var vscale = me.getValueScale(); + var base = vscale.getBasePixel(); + var horizontal = vscale.isHorizontal(); + var ruler = me._ruler || me.getRuler(); + var vpixels = me.calculateBarValuePixels(me.index, index); + var ipixels = me.calculateBarIndexPixels(me.index, index, ruler); + + model.horizontal = horizontal; + model.base = reset ? base : vpixels.base; + model.x = horizontal ? reset ? base : vpixels.head : ipixels.center; + model.y = horizontal ? ipixels.center : reset ? base : vpixels.head; + model.height = horizontal ? ipixels.size : undefined; + model.width = horizontal ? undefined : ipixels.size; + }, + + /** + * @private + */ + getValueScaleId: function() { + return this.getMeta().yAxisID; + }, + + /** + * @private + */ + getIndexScaleId: function() { + return this.getMeta().xAxisID; + }, + + /** + * @private + */ + getValueScale: function() { + return this.getScaleForId(this.getValueScaleId()); + }, + + /** + * @private + */ + getIndexScale: function() { + return this.getScaleForId(this.getIndexScaleId()); + }, + + /** + * Returns the effective number of stacks based on groups and bar visibility. + * @private + */ + getStackCount: function(last) { + var me = this; + var chart = me.chart; + var scale = me.getIndexScale(); + var stacked = scale.options.stacked; + var ilen = last === undefined ? chart.data.datasets.length : last + 1; + var stacks = []; + var i, meta; + + for (i = 0; i < ilen; ++i) { + meta = chart.getDatasetMeta(i); + if (meta.bar && chart.isDatasetVisible(i) && + (stacked === false || + (stacked === true && stacks.indexOf(meta.stack) === -1) || + (stacked === undefined && (meta.stack === undefined || stacks.indexOf(meta.stack) === -1)))) { + stacks.push(meta.stack); + } + } + + return stacks.length; + }, + + /** + * Returns the stack index for the given dataset based on groups and bar visibility. + * @private + */ + getStackIndex: function(datasetIndex) { + return this.getStackCount(datasetIndex) - 1; + }, + + /** + * @private + */ + getRuler: function() { + var me = this; + var scale = me.getIndexScale(); + var stackCount = me.getStackCount(); + var datasetIndex = me.index; + var pixels = []; + var isHorizontal = scale.isHorizontal(); + var start = isHorizontal ? scale.left : scale.top; + var end = start + (isHorizontal ? scale.width : scale.height); + var i, ilen; + + for (i = 0, ilen = me.getMeta().data.length; i < ilen; ++i) { + pixels.push(scale.getPixelForValue(null, i, datasetIndex)); + } + + return { + pixels: pixels, + start: start, + end: end, + stackCount: stackCount, + scale: scale + }; + }, + + /** + * Note: pixel values are not clamped to the scale area. + * @private + */ + calculateBarValuePixels: function(datasetIndex, index) { + var me = this; + var chart = me.chart; + var meta = me.getMeta(); + var scale = me.getValueScale(); + var datasets = chart.data.datasets; + var value = scale.getRightValue(datasets[datasetIndex].data[index]); + var stacked = scale.options.stacked; + var stack = meta.stack; + var start = 0; + var i, imeta, ivalue, base, head, size; + + if (stacked || (stacked === undefined && stack !== undefined)) { + for (i = 0; i < datasetIndex; ++i) { + imeta = chart.getDatasetMeta(i); + + if (imeta.bar && + imeta.stack === stack && + imeta.controller.getValueScaleId() === scale.id && + chart.isDatasetVisible(i)) { + + ivalue = scale.getRightValue(datasets[i].data[index]); + if ((value < 0 && ivalue < 0) || (value >= 0 && ivalue > 0)) { + start += ivalue; + } + } + } + } + + base = scale.getPixelForValue(start); + head = scale.getPixelForValue(start + value); + size = (head - base) / 2; + + return { + size: size, + base: base, + head: head, + center: head + size / 2 + }; + }, + + /** + * @private + */ + calculateBarIndexPixels: function(datasetIndex, index, ruler) { + var me = this; + var options = ruler.scale.options; + var stackIndex = me.getStackIndex(datasetIndex); + var pixels = ruler.pixels; + var base = pixels[index]; + var length = pixels.length; + var start = ruler.start; + var end = ruler.end; + var leftSampleSize, rightSampleSize, leftCategorySize, rightCategorySize, fullBarSize, size; + + if (length === 1) { + leftSampleSize = base > start ? base - start : end - base; + rightSampleSize = base < end ? end - base : base - start; + } else { + if (index > 0) { + leftSampleSize = (base - pixels[index - 1]) / 2; + if (index === length - 1) { + rightSampleSize = leftSampleSize; + } + } + if (index < length - 1) { + rightSampleSize = (pixels[index + 1] - base) / 2; + if (index === 0) { + leftSampleSize = rightSampleSize; + } + } + } + + leftCategorySize = leftSampleSize * options.categoryPercentage; + rightCategorySize = rightSampleSize * options.categoryPercentage; + fullBarSize = (leftCategorySize + rightCategorySize) / ruler.stackCount; + size = fullBarSize * options.barPercentage; + + size = Math.min( + helpers.valueOrDefault(options.barThickness, size), + helpers.valueOrDefault(options.maxBarThickness, Infinity)); + + base -= leftCategorySize; + base += fullBarSize * stackIndex; + base += (fullBarSize - size) / 2; + + return { + size: size, + base: base, + head: base + size, + center: base + size / 2 + }; + }, + + draw: function() { + var me = this; + var chart = me.chart; + var scale = me.getValueScale(); + var rects = me.getMeta().data; + var dataset = me.getDataset(); + var ilen = rects.length; + var i = 0; + + helpers.canvas.clipArea(chart.ctx, chart.chartArea); + + for (; i < ilen; ++i) { + if (!isNaN(scale.getRightValue(dataset.data[i]))) { + rects[i].draw(); + } + } + + helpers.canvas.unclipArea(chart.ctx); + }, + + setHoverStyle: function(rectangle) { + var dataset = this.chart.data.datasets[rectangle._datasetIndex]; + var index = rectangle._index; + var custom = rectangle.custom || {}; + var model = rectangle._model; + + model.backgroundColor = custom.hoverBackgroundColor ? custom.hoverBackgroundColor : helpers.valueAtIndexOrDefault(dataset.hoverBackgroundColor, index, helpers.getHoverColor(model.backgroundColor)); + model.borderColor = custom.hoverBorderColor ? custom.hoverBorderColor : helpers.valueAtIndexOrDefault(dataset.hoverBorderColor, index, helpers.getHoverColor(model.borderColor)); + model.borderWidth = custom.hoverBorderWidth ? custom.hoverBorderWidth : helpers.valueAtIndexOrDefault(dataset.hoverBorderWidth, index, model.borderWidth); + }, + + removeHoverStyle: function(rectangle) { + var dataset = this.chart.data.datasets[rectangle._datasetIndex]; + var index = rectangle._index; + var custom = rectangle.custom || {}; + var model = rectangle._model; + var rectangleElementOptions = this.chart.options.elements.rectangle; + + model.backgroundColor = custom.backgroundColor ? custom.backgroundColor : helpers.valueAtIndexOrDefault(dataset.backgroundColor, index, rectangleElementOptions.backgroundColor); + model.borderColor = custom.borderColor ? custom.borderColor : helpers.valueAtIndexOrDefault(dataset.borderColor, index, rectangleElementOptions.borderColor); + model.borderWidth = custom.borderWidth ? custom.borderWidth : helpers.valueAtIndexOrDefault(dataset.borderWidth, index, rectangleElementOptions.borderWidth); + } + }); + + Chart.controllers.horizontalBar = Chart.controllers.bar.extend({ + /** + * @private + */ + getValueScaleId: function() { + return this.getMeta().xAxisID; + }, + + /** + * @private + */ + getIndexScaleId: function() { + return this.getMeta().yAxisID; + } + }); +}; + +},{"25":25,"40":40,"45":45}],16:[function(require,module,exports){ +'use strict'; + +var defaults = require(25); +var elements = require(40); +var helpers = require(45); + +defaults._set('bubble', { + hover: { + mode: 'single' + }, + + scales: { + xAxes: [{ + type: 'linear', // bubble should probably use a linear scale by default + position: 'bottom', + id: 'x-axis-0' // need an ID so datasets can reference the scale + }], + yAxes: [{ + type: 'linear', + position: 'left', + id: 'y-axis-0' + }] + }, + + tooltips: { + callbacks: { + title: function() { + // Title doesn't make sense for scatter since we format the data as a point + return ''; + }, + label: function(item, data) { + var datasetLabel = data.datasets[item.datasetIndex].label || ''; + var dataPoint = data.datasets[item.datasetIndex].data[item.index]; + return datasetLabel + ': (' + item.xLabel + ', ' + item.yLabel + ', ' + dataPoint.r + ')'; + } + } + } +}); + + +module.exports = function(Chart) { + + Chart.controllers.bubble = Chart.DatasetController.extend({ + /** + * @protected + */ + dataElementType: elements.Point, + + /** + * @protected + */ + update: function(reset) { + var me = this; + var meta = me.getMeta(); + var points = meta.data; + + // Update Points + helpers.each(points, function(point, index) { + me.updateElement(point, index, reset); + }); + }, + + /** + * @protected + */ + updateElement: function(point, index, reset) { + var me = this; + var meta = me.getMeta(); + var custom = point.custom || {}; + var xScale = me.getScaleForId(meta.xAxisID); + var yScale = me.getScaleForId(meta.yAxisID); + var options = me._resolveElementOptions(point, index); + var data = me.getDataset().data[index]; + var dsIndex = me.index; + + var x = reset ? xScale.getPixelForDecimal(0.5) : xScale.getPixelForValue(typeof data === 'object' ? data : NaN, index, dsIndex); + var y = reset ? yScale.getBasePixel() : yScale.getPixelForValue(data, index, dsIndex); + + point._xScale = xScale; + point._yScale = yScale; + point._options = options; + point._datasetIndex = dsIndex; + point._index = index; + point._model = { + backgroundColor: options.backgroundColor, + borderColor: options.borderColor, + borderWidth: options.borderWidth, + hitRadius: options.hitRadius, + pointStyle: options.pointStyle, + radius: reset ? 0 : options.radius, + skip: custom.skip || isNaN(x) || isNaN(y), + x: x, + y: y, + }; + + point.pivot(); + }, + + /** + * @protected + */ + setHoverStyle: function(point) { + var model = point._model; + var options = point._options; + + model.backgroundColor = helpers.valueOrDefault(options.hoverBackgroundColor, helpers.getHoverColor(options.backgroundColor)); + model.borderColor = helpers.valueOrDefault(options.hoverBorderColor, helpers.getHoverColor(options.borderColor)); + model.borderWidth = helpers.valueOrDefault(options.hoverBorderWidth, options.borderWidth); + model.radius = options.radius + options.hoverRadius; + }, + + /** + * @protected + */ + removeHoverStyle: function(point) { + var model = point._model; + var options = point._options; + + model.backgroundColor = options.backgroundColor; + model.borderColor = options.borderColor; + model.borderWidth = options.borderWidth; + model.radius = options.radius; + }, + + /** + * @private + */ + _resolveElementOptions: function(point, index) { + var me = this; + var chart = me.chart; + var datasets = chart.data.datasets; + var dataset = datasets[me.index]; + var custom = point.custom || {}; + var options = chart.options.elements.point; + var resolve = helpers.options.resolve; + var data = dataset.data[index]; + var values = {}; + var i, ilen, key; + + // Scriptable options + var context = { + chart: chart, + dataIndex: index, + dataset: dataset, + datasetIndex: me.index + }; + + var keys = [ + 'backgroundColor', + 'borderColor', + 'borderWidth', + 'hoverBackgroundColor', + 'hoverBorderColor', + 'hoverBorderWidth', + 'hoverRadius', + 'hitRadius', + 'pointStyle' + ]; + + for (i = 0, ilen = keys.length; i < ilen; ++i) { + key = keys[i]; + values[key] = resolve([ + custom[key], + dataset[key], + options[key] + ], context, index); + } + + // Custom radius resolution + values.radius = resolve([ + custom.radius, + data ? data.r : undefined, + dataset.radius, + options.radius + ], context, index); + + return values; + } + }); +}; + +},{"25":25,"40":40,"45":45}],17:[function(require,module,exports){ +'use strict'; + +var defaults = require(25); +var elements = require(40); +var helpers = require(45); + +defaults._set('doughnut', { + animation: { + // Boolean - Whether we animate the rotation of the Doughnut + animateRotate: true, + // Boolean - Whether we animate scaling the Doughnut from the centre + animateScale: false + }, + hover: { + mode: 'single' + }, + legendCallback: function(chart) { + var text = []; + text.push('
    '); + + var data = chart.data; + var datasets = data.datasets; + var labels = data.labels; + + if (datasets.length) { + for (var i = 0; i < datasets[0].data.length; ++i) { + text.push('
  • '); + if (labels[i]) { + text.push(labels[i]); + } + text.push('
  • '); + } + } + + text.push('
'); + return text.join(''); + }, + legend: { + labels: { + generateLabels: function(chart) { + var data = chart.data; + if (data.labels.length && data.datasets.length) { + return data.labels.map(function(label, i) { + var meta = chart.getDatasetMeta(0); + var ds = data.datasets[0]; + var arc = meta.data[i]; + var custom = arc && arc.custom || {}; + var valueAtIndexOrDefault = helpers.valueAtIndexOrDefault; + var arcOpts = chart.options.elements.arc; + var fill = custom.backgroundColor ? custom.backgroundColor : valueAtIndexOrDefault(ds.backgroundColor, i, arcOpts.backgroundColor); + var stroke = custom.borderColor ? custom.borderColor : valueAtIndexOrDefault(ds.borderColor, i, arcOpts.borderColor); + var bw = custom.borderWidth ? custom.borderWidth : valueAtIndexOrDefault(ds.borderWidth, i, arcOpts.borderWidth); + + return { + text: label, + fillStyle: fill, + strokeStyle: stroke, + lineWidth: bw, + hidden: isNaN(ds.data[i]) || meta.data[i].hidden, + + // Extra data used for toggling the correct item + index: i + }; + }); + } + return []; + } + }, + + onClick: function(e, legendItem) { + var index = legendItem.index; + var chart = this.chart; + var i, ilen, meta; + + for (i = 0, ilen = (chart.data.datasets || []).length; i < ilen; ++i) { + meta = chart.getDatasetMeta(i); + // toggle visibility of index if exists + if (meta.data[index]) { + meta.data[index].hidden = !meta.data[index].hidden; + } + } + + chart.update(); + } + }, + + // The percentage of the chart that we cut out of the middle. + cutoutPercentage: 50, + + // The rotation of the chart, where the first data arc begins. + rotation: Math.PI * -0.5, + + // The total circumference of the chart. + circumference: Math.PI * 2.0, + + // Need to override these to give a nice default + tooltips: { + callbacks: { + title: function() { + return ''; + }, + label: function(tooltipItem, data) { + var dataLabel = data.labels[tooltipItem.index]; + var value = ': ' + data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index]; + + if (helpers.isArray(dataLabel)) { + // show value on first line of multiline label + // need to clone because we are changing the value + dataLabel = dataLabel.slice(); + dataLabel[0] += value; + } else { + dataLabel += value; + } + + return dataLabel; + } + } + } +}); + +defaults._set('pie', helpers.clone(defaults.doughnut)); +defaults._set('pie', { + cutoutPercentage: 0 +}); + +module.exports = function(Chart) { + + Chart.controllers.doughnut = Chart.controllers.pie = Chart.DatasetController.extend({ + + dataElementType: elements.Arc, + + linkScales: helpers.noop, + + // Get index of the dataset in relation to the visible datasets. This allows determining the inner and outer radius correctly + getRingIndex: function(datasetIndex) { + var ringIndex = 0; + + for (var j = 0; j < datasetIndex; ++j) { + if (this.chart.isDatasetVisible(j)) { + ++ringIndex; + } + } + + return ringIndex; + }, + + update: function(reset) { + var me = this; + var chart = me.chart; + var chartArea = chart.chartArea; + var opts = chart.options; + var arcOpts = opts.elements.arc; + var availableWidth = chartArea.right - chartArea.left - arcOpts.borderWidth; + var availableHeight = chartArea.bottom - chartArea.top - arcOpts.borderWidth; + var minSize = Math.min(availableWidth, availableHeight); + var offset = {x: 0, y: 0}; + var meta = me.getMeta(); + var cutoutPercentage = opts.cutoutPercentage; + var circumference = opts.circumference; + + // If the chart's circumference isn't a full circle, calculate minSize as a ratio of the width/height of the arc + if (circumference < Math.PI * 2.0) { + var startAngle = opts.rotation % (Math.PI * 2.0); + startAngle += Math.PI * 2.0 * (startAngle >= Math.PI ? -1 : startAngle < -Math.PI ? 1 : 0); + var endAngle = startAngle + circumference; + var start = {x: Math.cos(startAngle), y: Math.sin(startAngle)}; + var end = {x: Math.cos(endAngle), y: Math.sin(endAngle)}; + var contains0 = (startAngle <= 0 && endAngle >= 0) || (startAngle <= Math.PI * 2.0 && Math.PI * 2.0 <= endAngle); + var contains90 = (startAngle <= Math.PI * 0.5 && Math.PI * 0.5 <= endAngle) || (startAngle <= Math.PI * 2.5 && Math.PI * 2.5 <= endAngle); + var contains180 = (startAngle <= -Math.PI && -Math.PI <= endAngle) || (startAngle <= Math.PI && Math.PI <= endAngle); + var contains270 = (startAngle <= -Math.PI * 0.5 && -Math.PI * 0.5 <= endAngle) || (startAngle <= Math.PI * 1.5 && Math.PI * 1.5 <= endAngle); + var cutout = cutoutPercentage / 100.0; + var min = {x: contains180 ? -1 : Math.min(start.x * (start.x < 0 ? 1 : cutout), end.x * (end.x < 0 ? 1 : cutout)), y: contains270 ? -1 : Math.min(start.y * (start.y < 0 ? 1 : cutout), end.y * (end.y < 0 ? 1 : cutout))}; + var max = {x: contains0 ? 1 : Math.max(start.x * (start.x > 0 ? 1 : cutout), end.x * (end.x > 0 ? 1 : cutout)), y: contains90 ? 1 : Math.max(start.y * (start.y > 0 ? 1 : cutout), end.y * (end.y > 0 ? 1 : cutout))}; + var size = {width: (max.x - min.x) * 0.5, height: (max.y - min.y) * 0.5}; + minSize = Math.min(availableWidth / size.width, availableHeight / size.height); + offset = {x: (max.x + min.x) * -0.5, y: (max.y + min.y) * -0.5}; + } + + chart.borderWidth = me.getMaxBorderWidth(meta.data); + chart.outerRadius = Math.max((minSize - chart.borderWidth) / 2, 0); + chart.innerRadius = Math.max(cutoutPercentage ? (chart.outerRadius / 100) * (cutoutPercentage) : 0, 0); + chart.radiusLength = (chart.outerRadius - chart.innerRadius) / chart.getVisibleDatasetCount(); + chart.offsetX = offset.x * chart.outerRadius; + chart.offsetY = offset.y * chart.outerRadius; + + meta.total = me.calculateTotal(); + + me.outerRadius = chart.outerRadius - (chart.radiusLength * me.getRingIndex(me.index)); + me.innerRadius = Math.max(me.outerRadius - chart.radiusLength, 0); + + helpers.each(meta.data, function(arc, index) { + me.updateElement(arc, index, reset); + }); + }, + + updateElement: function(arc, index, reset) { + var me = this; + var chart = me.chart; + var chartArea = chart.chartArea; + var opts = chart.options; + var animationOpts = opts.animation; + var centerX = (chartArea.left + chartArea.right) / 2; + var centerY = (chartArea.top + chartArea.bottom) / 2; + var startAngle = opts.rotation; // non reset case handled later + var endAngle = opts.rotation; // non reset case handled later + var dataset = me.getDataset(); + var circumference = reset && animationOpts.animateRotate ? 0 : arc.hidden ? 0 : me.calculateCircumference(dataset.data[index]) * (opts.circumference / (2.0 * Math.PI)); + var innerRadius = reset && animationOpts.animateScale ? 0 : me.innerRadius; + var outerRadius = reset && animationOpts.animateScale ? 0 : me.outerRadius; + var valueAtIndexOrDefault = helpers.valueAtIndexOrDefault; + + helpers.extend(arc, { + // Utility + _datasetIndex: me.index, + _index: index, + + // Desired view properties + _model: { + x: centerX + chart.offsetX, + y: centerY + chart.offsetY, + startAngle: startAngle, + endAngle: endAngle, + circumference: circumference, + outerRadius: outerRadius, + innerRadius: innerRadius, + label: valueAtIndexOrDefault(dataset.label, index, chart.data.labels[index]) + } + }); + + var model = arc._model; + // Resets the visual styles + this.removeHoverStyle(arc); + + // Set correct angles if not resetting + if (!reset || !animationOpts.animateRotate) { + if (index === 0) { + model.startAngle = opts.rotation; + } else { + model.startAngle = me.getMeta().data[index - 1]._model.endAngle; + } + + model.endAngle = model.startAngle + model.circumference; + } + + arc.pivot(); + }, + + removeHoverStyle: function(arc) { + Chart.DatasetController.prototype.removeHoverStyle.call(this, arc, this.chart.options.elements.arc); + }, + + calculateTotal: function() { + var dataset = this.getDataset(); + var meta = this.getMeta(); + var total = 0; + var value; + + helpers.each(meta.data, function(element, index) { + value = dataset.data[index]; + if (!isNaN(value) && !element.hidden) { + total += Math.abs(value); + } + }); + + /* if (total === 0) { + total = NaN; + }*/ + + return total; + }, + + calculateCircumference: function(value) { + var total = this.getMeta().total; + if (total > 0 && !isNaN(value)) { + return (Math.PI * 2.0) * (value / total); + } + return 0; + }, + + // gets the max border or hover width to properly scale pie charts + getMaxBorderWidth: function(arcs) { + var max = 0; + var index = this.index; + var length = arcs.length; + var borderWidth; + var hoverWidth; + + for (var i = 0; i < length; i++) { + borderWidth = arcs[i]._model ? arcs[i]._model.borderWidth : 0; + hoverWidth = arcs[i]._chart ? arcs[i]._chart.config.data.datasets[index].hoverBorderWidth : 0; + + max = borderWidth > max ? borderWidth : max; + max = hoverWidth > max ? hoverWidth : max; + } + return max; + } + }); +}; + +},{"25":25,"40":40,"45":45}],18:[function(require,module,exports){ +'use strict'; + +var defaults = require(25); +var elements = require(40); +var helpers = require(45); + +defaults._set('line', { + showLines: true, + spanGaps: false, + + hover: { + mode: 'label' + }, + + scales: { + xAxes: [{ + type: 'category', + id: 'x-axis-0' + }], + yAxes: [{ + type: 'linear', + id: 'y-axis-0' + }] + } +}); + +module.exports = function(Chart) { + + function lineEnabled(dataset, options) { + return helpers.valueOrDefault(dataset.showLine, options.showLines); + } + + Chart.controllers.line = Chart.DatasetController.extend({ + + datasetElementType: elements.Line, + + dataElementType: elements.Point, + + update: function(reset) { + var me = this; + var meta = me.getMeta(); + var line = meta.dataset; + var points = meta.data || []; + var options = me.chart.options; + var lineElementOptions = options.elements.line; + var scale = me.getScaleForId(meta.yAxisID); + var i, ilen, custom; + var dataset = me.getDataset(); + var showLine = lineEnabled(dataset, options); + + // Update Line + if (showLine) { + custom = line.custom || {}; + + // Compatibility: If the properties are defined with only the old name, use those values + if ((dataset.tension !== undefined) && (dataset.lineTension === undefined)) { + dataset.lineTension = dataset.tension; + } + + // Utility + line._scale = scale; + line._datasetIndex = me.index; + // Data + line._children = points; + // Model + line._model = { + // Appearance + // The default behavior of lines is to break at null values, according + // to https://github.com/chartjs/Chart.js/issues/2435#issuecomment-216718158 + // This option gives lines the ability to span gaps + spanGaps: dataset.spanGaps ? dataset.spanGaps : options.spanGaps, + tension: custom.tension ? custom.tension : helpers.valueOrDefault(dataset.lineTension, lineElementOptions.tension), + backgroundColor: custom.backgroundColor ? custom.backgroundColor : (dataset.backgroundColor || lineElementOptions.backgroundColor), + borderWidth: custom.borderWidth ? custom.borderWidth : (dataset.borderWidth || lineElementOptions.borderWidth), + borderColor: custom.borderColor ? custom.borderColor : (dataset.borderColor || lineElementOptions.borderColor), + borderCapStyle: custom.borderCapStyle ? custom.borderCapStyle : (dataset.borderCapStyle || lineElementOptions.borderCapStyle), + borderDash: custom.borderDash ? custom.borderDash : (dataset.borderDash || lineElementOptions.borderDash), + borderDashOffset: custom.borderDashOffset ? custom.borderDashOffset : (dataset.borderDashOffset || lineElementOptions.borderDashOffset), + borderJoinStyle: custom.borderJoinStyle ? custom.borderJoinStyle : (dataset.borderJoinStyle || lineElementOptions.borderJoinStyle), + fill: custom.fill ? custom.fill : (dataset.fill !== undefined ? dataset.fill : lineElementOptions.fill), + steppedLine: custom.steppedLine ? custom.steppedLine : helpers.valueOrDefault(dataset.steppedLine, lineElementOptions.stepped), + cubicInterpolationMode: custom.cubicInterpolationMode ? custom.cubicInterpolationMode : helpers.valueOrDefault(dataset.cubicInterpolationMode, lineElementOptions.cubicInterpolationMode), + }; + + line.pivot(); + } + + // Update Points + for (i = 0, ilen = points.length; i < ilen; ++i) { + me.updateElement(points[i], i, reset); + } + + if (showLine && line._model.tension !== 0) { + me.updateBezierControlPoints(); + } + + // Now pivot the point for animation + for (i = 0, ilen = points.length; i < ilen; ++i) { + points[i].pivot(); + } + }, + + getPointBackgroundColor: function(point, index) { + var backgroundColor = this.chart.options.elements.point.backgroundColor; + var dataset = this.getDataset(); + var custom = point.custom || {}; + + if (custom.backgroundColor) { + backgroundColor = custom.backgroundColor; + } else if (dataset.pointBackgroundColor) { + backgroundColor = helpers.valueAtIndexOrDefault(dataset.pointBackgroundColor, index, backgroundColor); + } else if (dataset.backgroundColor) { + backgroundColor = dataset.backgroundColor; + } + + return backgroundColor; + }, + + getPointBorderColor: function(point, index) { + var borderColor = this.chart.options.elements.point.borderColor; + var dataset = this.getDataset(); + var custom = point.custom || {}; + + if (custom.borderColor) { + borderColor = custom.borderColor; + } else if (dataset.pointBorderColor) { + borderColor = helpers.valueAtIndexOrDefault(dataset.pointBorderColor, index, borderColor); + } else if (dataset.borderColor) { + borderColor = dataset.borderColor; + } + + return borderColor; + }, + + getPointBorderWidth: function(point, index) { + var borderWidth = this.chart.options.elements.point.borderWidth; + var dataset = this.getDataset(); + var custom = point.custom || {}; + + if (!isNaN(custom.borderWidth)) { + borderWidth = custom.borderWidth; + } else if (!isNaN(dataset.pointBorderWidth) || helpers.isArray(dataset.pointBorderWidth)) { + borderWidth = helpers.valueAtIndexOrDefault(dataset.pointBorderWidth, index, borderWidth); + } else if (!isNaN(dataset.borderWidth)) { + borderWidth = dataset.borderWidth; + } + + return borderWidth; + }, + + updateElement: function(point, index, reset) { + var me = this; + var meta = me.getMeta(); + var custom = point.custom || {}; + var dataset = me.getDataset(); + var datasetIndex = me.index; + var value = dataset.data[index]; + var yScale = me.getScaleForId(meta.yAxisID); + var xScale = me.getScaleForId(meta.xAxisID); + var pointOptions = me.chart.options.elements.point; + var x, y; + + // Compatibility: If the properties are defined with only the old name, use those values + if ((dataset.radius !== undefined) && (dataset.pointRadius === undefined)) { + dataset.pointRadius = dataset.radius; + } + if ((dataset.hitRadius !== undefined) && (dataset.pointHitRadius === undefined)) { + dataset.pointHitRadius = dataset.hitRadius; + } + + x = xScale.getPixelForValue(typeof value === 'object' ? value : NaN, index, datasetIndex); + y = reset ? yScale.getBasePixel() : me.calculatePointY(value, index, datasetIndex); + + // Utility + point._xScale = xScale; + point._yScale = yScale; + point._datasetIndex = datasetIndex; + point._index = index; + + // Desired view properties + point._model = { + x: x, + y: y, + skip: custom.skip || isNaN(x) || isNaN(y), + // Appearance + radius: custom.radius || helpers.valueAtIndexOrDefault(dataset.pointRadius, index, pointOptions.radius), + pointStyle: custom.pointStyle || helpers.valueAtIndexOrDefault(dataset.pointStyle, index, pointOptions.pointStyle), + backgroundColor: me.getPointBackgroundColor(point, index), + borderColor: me.getPointBorderColor(point, index), + borderWidth: me.getPointBorderWidth(point, index), + tension: meta.dataset._model ? meta.dataset._model.tension : 0, + steppedLine: meta.dataset._model ? meta.dataset._model.steppedLine : false, + // Tooltip + hitRadius: custom.hitRadius || helpers.valueAtIndexOrDefault(dataset.pointHitRadius, index, pointOptions.hitRadius) + }; + }, + + calculatePointY: function(value, index, datasetIndex) { + var me = this; + var chart = me.chart; + var meta = me.getMeta(); + var yScale = me.getScaleForId(meta.yAxisID); + var sumPos = 0; + var sumNeg = 0; + var i, ds, dsMeta; + + if (yScale.options.stacked) { + for (i = 0; i < datasetIndex; i++) { + ds = chart.data.datasets[i]; + dsMeta = chart.getDatasetMeta(i); + if (dsMeta.type === 'line' && dsMeta.yAxisID === yScale.id && chart.isDatasetVisible(i)) { + var stackedRightValue = Number(yScale.getRightValue(ds.data[index])); + if (stackedRightValue < 0) { + sumNeg += stackedRightValue || 0; + } else { + sumPos += stackedRightValue || 0; + } + } + } + + var rightValue = Number(yScale.getRightValue(value)); + if (rightValue < 0) { + return yScale.getPixelForValue(sumNeg + rightValue); + } + return yScale.getPixelForValue(sumPos + rightValue); + } + + return yScale.getPixelForValue(value); + }, + + updateBezierControlPoints: function() { + var me = this; + var meta = me.getMeta(); + var area = me.chart.chartArea; + var points = (meta.data || []); + var i, ilen, point, model, controlPoints; + + // Only consider points that are drawn in case the spanGaps option is used + if (meta.dataset._model.spanGaps) { + points = points.filter(function(pt) { + return !pt._model.skip; + }); + } + + function capControlPoint(pt, min, max) { + return Math.max(Math.min(pt, max), min); + } + + if (meta.dataset._model.cubicInterpolationMode === 'monotone') { + helpers.splineCurveMonotone(points); + } else { + for (i = 0, ilen = points.length; i < ilen; ++i) { + point = points[i]; + model = point._model; + controlPoints = helpers.splineCurve( + helpers.previousItem(points, i)._model, + model, + helpers.nextItem(points, i)._model, + meta.dataset._model.tension + ); + model.controlPointPreviousX = controlPoints.previous.x; + model.controlPointPreviousY = controlPoints.previous.y; + model.controlPointNextX = controlPoints.next.x; + model.controlPointNextY = controlPoints.next.y; + } + } + + if (me.chart.options.elements.line.capBezierPoints) { + for (i = 0, ilen = points.length; i < ilen; ++i) { + model = points[i]._model; + model.controlPointPreviousX = capControlPoint(model.controlPointPreviousX, area.left, area.right); + model.controlPointPreviousY = capControlPoint(model.controlPointPreviousY, area.top, area.bottom); + model.controlPointNextX = capControlPoint(model.controlPointNextX, area.left, area.right); + model.controlPointNextY = capControlPoint(model.controlPointNextY, area.top, area.bottom); + } + } + }, + + draw: function() { + var me = this; + var chart = me.chart; + var meta = me.getMeta(); + var points = meta.data || []; + var area = chart.chartArea; + var ilen = points.length; + var i = 0; + + helpers.canvas.clipArea(chart.ctx, area); + + if (lineEnabled(me.getDataset(), chart.options)) { + meta.dataset.draw(); + } + + helpers.canvas.unclipArea(chart.ctx); + + // Draw the points + for (; i < ilen; ++i) { + points[i].draw(area); + } + }, + + setHoverStyle: function(point) { + // Point + var dataset = this.chart.data.datasets[point._datasetIndex]; + var index = point._index; + var custom = point.custom || {}; + var model = point._model; + + model.radius = custom.hoverRadius || helpers.valueAtIndexOrDefault(dataset.pointHoverRadius, index, this.chart.options.elements.point.hoverRadius); + model.backgroundColor = custom.hoverBackgroundColor || helpers.valueAtIndexOrDefault(dataset.pointHoverBackgroundColor, index, helpers.getHoverColor(model.backgroundColor)); + model.borderColor = custom.hoverBorderColor || helpers.valueAtIndexOrDefault(dataset.pointHoverBorderColor, index, helpers.getHoverColor(model.borderColor)); + model.borderWidth = custom.hoverBorderWidth || helpers.valueAtIndexOrDefault(dataset.pointHoverBorderWidth, index, model.borderWidth); + }, + + removeHoverStyle: function(point) { + var me = this; + var dataset = me.chart.data.datasets[point._datasetIndex]; + var index = point._index; + var custom = point.custom || {}; + var model = point._model; + + // Compatibility: If the properties are defined with only the old name, use those values + if ((dataset.radius !== undefined) && (dataset.pointRadius === undefined)) { + dataset.pointRadius = dataset.radius; + } + + model.radius = custom.radius || helpers.valueAtIndexOrDefault(dataset.pointRadius, index, me.chart.options.elements.point.radius); + model.backgroundColor = me.getPointBackgroundColor(point, index); + model.borderColor = me.getPointBorderColor(point, index); + model.borderWidth = me.getPointBorderWidth(point, index); + } + }); +}; + +},{"25":25,"40":40,"45":45}],19:[function(require,module,exports){ +'use strict'; + +var defaults = require(25); +var elements = require(40); +var helpers = require(45); + +defaults._set('polarArea', { + scale: { + type: 'radialLinear', + angleLines: { + display: false + }, + gridLines: { + circular: true + }, + pointLabels: { + display: false + }, + ticks: { + beginAtZero: true + } + }, + + // Boolean - Whether to animate the rotation of the chart + animation: { + animateRotate: true, + animateScale: true + }, + + startAngle: -0.5 * Math.PI, + legendCallback: function(chart) { + var text = []; + text.push('
    '); + + var data = chart.data; + var datasets = data.datasets; + var labels = data.labels; + + if (datasets.length) { + for (var i = 0; i < datasets[0].data.length; ++i) { + text.push('
  • '); + if (labels[i]) { + text.push(labels[i]); + } + text.push('
  • '); + } + } + + text.push('
'); + return text.join(''); + }, + legend: { + labels: { + generateLabels: function(chart) { + var data = chart.data; + if (data.labels.length && data.datasets.length) { + return data.labels.map(function(label, i) { + var meta = chart.getDatasetMeta(0); + var ds = data.datasets[0]; + var arc = meta.data[i]; + var custom = arc.custom || {}; + var valueAtIndexOrDefault = helpers.valueAtIndexOrDefault; + var arcOpts = chart.options.elements.arc; + var fill = custom.backgroundColor ? custom.backgroundColor : valueAtIndexOrDefault(ds.backgroundColor, i, arcOpts.backgroundColor); + var stroke = custom.borderColor ? custom.borderColor : valueAtIndexOrDefault(ds.borderColor, i, arcOpts.borderColor); + var bw = custom.borderWidth ? custom.borderWidth : valueAtIndexOrDefault(ds.borderWidth, i, arcOpts.borderWidth); + + return { + text: label, + fillStyle: fill, + strokeStyle: stroke, + lineWidth: bw, + hidden: isNaN(ds.data[i]) || meta.data[i].hidden, + + // Extra data used for toggling the correct item + index: i + }; + }); + } + return []; + } + }, + + onClick: function(e, legendItem) { + var index = legendItem.index; + var chart = this.chart; + var i, ilen, meta; + + for (i = 0, ilen = (chart.data.datasets || []).length; i < ilen; ++i) { + meta = chart.getDatasetMeta(i); + meta.data[index].hidden = !meta.data[index].hidden; + } + + chart.update(); + } + }, + + // Need to override these to give a nice default + tooltips: { + callbacks: { + title: function() { + return ''; + }, + label: function(item, data) { + return data.labels[item.index] + ': ' + item.yLabel; + } + } + } +}); + +module.exports = function(Chart) { + + Chart.controllers.polarArea = Chart.DatasetController.extend({ + + dataElementType: elements.Arc, + + linkScales: helpers.noop, + + update: function(reset) { + var me = this; + var chart = me.chart; + var chartArea = chart.chartArea; + var meta = me.getMeta(); + var opts = chart.options; + var arcOpts = opts.elements.arc; + var minSize = Math.min(chartArea.right - chartArea.left, chartArea.bottom - chartArea.top); + chart.outerRadius = Math.max((minSize - arcOpts.borderWidth / 2) / 2, 0); + chart.innerRadius = Math.max(opts.cutoutPercentage ? (chart.outerRadius / 100) * (opts.cutoutPercentage) : 1, 0); + chart.radiusLength = (chart.outerRadius - chart.innerRadius) / chart.getVisibleDatasetCount(); + + me.outerRadius = chart.outerRadius - (chart.radiusLength * me.index); + me.innerRadius = me.outerRadius - chart.radiusLength; + + meta.count = me.countVisibleElements(); + + helpers.each(meta.data, function(arc, index) { + me.updateElement(arc, index, reset); + }); + }, + + updateElement: function(arc, index, reset) { + var me = this; + var chart = me.chart; + var dataset = me.getDataset(); + var opts = chart.options; + var animationOpts = opts.animation; + var scale = chart.scale; + var labels = chart.data.labels; + + var circumference = me.calculateCircumference(dataset.data[index]); + var centerX = scale.xCenter; + var centerY = scale.yCenter; + + // If there is NaN data before us, we need to calculate the starting angle correctly. + // We could be way more efficient here, but its unlikely that the polar area chart will have a lot of data + var visibleCount = 0; + var meta = me.getMeta(); + for (var i = 0; i < index; ++i) { + if (!isNaN(dataset.data[i]) && !meta.data[i].hidden) { + ++visibleCount; + } + } + + // var negHalfPI = -0.5 * Math.PI; + var datasetStartAngle = opts.startAngle; + var distance = arc.hidden ? 0 : scale.getDistanceFromCenterForValue(dataset.data[index]); + var startAngle = datasetStartAngle + (circumference * visibleCount); + var endAngle = startAngle + (arc.hidden ? 0 : circumference); + + var resetRadius = animationOpts.animateScale ? 0 : scale.getDistanceFromCenterForValue(dataset.data[index]); + + helpers.extend(arc, { + // Utility + _datasetIndex: me.index, + _index: index, + _scale: scale, + + // Desired view properties + _model: { + x: centerX, + y: centerY, + innerRadius: 0, + outerRadius: reset ? resetRadius : distance, + startAngle: reset && animationOpts.animateRotate ? datasetStartAngle : startAngle, + endAngle: reset && animationOpts.animateRotate ? datasetStartAngle : endAngle, + label: helpers.valueAtIndexOrDefault(labels, index, labels[index]) + } + }); + + // Apply border and fill style + me.removeHoverStyle(arc); + + arc.pivot(); + }, + + removeHoverStyle: function(arc) { + Chart.DatasetController.prototype.removeHoverStyle.call(this, arc, this.chart.options.elements.arc); + }, + + countVisibleElements: function() { + var dataset = this.getDataset(); + var meta = this.getMeta(); + var count = 0; + + helpers.each(meta.data, function(element, index) { + if (!isNaN(dataset.data[index]) && !element.hidden) { + count++; + } + }); + + return count; + }, + + calculateCircumference: function(value) { + var count = this.getMeta().count; + if (count > 0 && !isNaN(value)) { + return (2 * Math.PI) / count; + } + return 0; + } + }); +}; + +},{"25":25,"40":40,"45":45}],20:[function(require,module,exports){ +'use strict'; + +var defaults = require(25); +var elements = require(40); +var helpers = require(45); + +defaults._set('radar', { + scale: { + type: 'radialLinear' + }, + elements: { + line: { + tension: 0 // no bezier in radar + } + } +}); + +module.exports = function(Chart) { + + Chart.controllers.radar = Chart.DatasetController.extend({ + + datasetElementType: elements.Line, + + dataElementType: elements.Point, + + linkScales: helpers.noop, + + update: function(reset) { + var me = this; + var meta = me.getMeta(); + var line = meta.dataset; + var points = meta.data; + var custom = line.custom || {}; + var dataset = me.getDataset(); + var lineElementOptions = me.chart.options.elements.line; + var scale = me.chart.scale; + + // Compatibility: If the properties are defined with only the old name, use those values + if ((dataset.tension !== undefined) && (dataset.lineTension === undefined)) { + dataset.lineTension = dataset.tension; + } + + helpers.extend(meta.dataset, { + // Utility + _datasetIndex: me.index, + _scale: scale, + // Data + _children: points, + _loop: true, + // Model + _model: { + // Appearance + tension: custom.tension ? custom.tension : helpers.valueOrDefault(dataset.lineTension, lineElementOptions.tension), + backgroundColor: custom.backgroundColor ? custom.backgroundColor : (dataset.backgroundColor || lineElementOptions.backgroundColor), + borderWidth: custom.borderWidth ? custom.borderWidth : (dataset.borderWidth || lineElementOptions.borderWidth), + borderColor: custom.borderColor ? custom.borderColor : (dataset.borderColor || lineElementOptions.borderColor), + fill: custom.fill ? custom.fill : (dataset.fill !== undefined ? dataset.fill : lineElementOptions.fill), + borderCapStyle: custom.borderCapStyle ? custom.borderCapStyle : (dataset.borderCapStyle || lineElementOptions.borderCapStyle), + borderDash: custom.borderDash ? custom.borderDash : (dataset.borderDash || lineElementOptions.borderDash), + borderDashOffset: custom.borderDashOffset ? custom.borderDashOffset : (dataset.borderDashOffset || lineElementOptions.borderDashOffset), + borderJoinStyle: custom.borderJoinStyle ? custom.borderJoinStyle : (dataset.borderJoinStyle || lineElementOptions.borderJoinStyle), + } + }); + + meta.dataset.pivot(); + + // Update Points + helpers.each(points, function(point, index) { + me.updateElement(point, index, reset); + }, me); + + // Update bezier control points + me.updateBezierControlPoints(); + }, + updateElement: function(point, index, reset) { + var me = this; + var custom = point.custom || {}; + var dataset = me.getDataset(); + var scale = me.chart.scale; + var pointElementOptions = me.chart.options.elements.point; + var pointPosition = scale.getPointPositionForValue(index, dataset.data[index]); + + // Compatibility: If the properties are defined with only the old name, use those values + if ((dataset.radius !== undefined) && (dataset.pointRadius === undefined)) { + dataset.pointRadius = dataset.radius; + } + if ((dataset.hitRadius !== undefined) && (dataset.pointHitRadius === undefined)) { + dataset.pointHitRadius = dataset.hitRadius; + } + + helpers.extend(point, { + // Utility + _datasetIndex: me.index, + _index: index, + _scale: scale, + + // Desired view properties + _model: { + x: reset ? scale.xCenter : pointPosition.x, // value not used in dataset scale, but we want a consistent API between scales + y: reset ? scale.yCenter : pointPosition.y, + + // Appearance + tension: custom.tension ? custom.tension : helpers.valueOrDefault(dataset.lineTension, me.chart.options.elements.line.tension), + radius: custom.radius ? custom.radius : helpers.valueAtIndexOrDefault(dataset.pointRadius, index, pointElementOptions.radius), + backgroundColor: custom.backgroundColor ? custom.backgroundColor : helpers.valueAtIndexOrDefault(dataset.pointBackgroundColor, index, pointElementOptions.backgroundColor), + borderColor: custom.borderColor ? custom.borderColor : helpers.valueAtIndexOrDefault(dataset.pointBorderColor, index, pointElementOptions.borderColor), + borderWidth: custom.borderWidth ? custom.borderWidth : helpers.valueAtIndexOrDefault(dataset.pointBorderWidth, index, pointElementOptions.borderWidth), + pointStyle: custom.pointStyle ? custom.pointStyle : helpers.valueAtIndexOrDefault(dataset.pointStyle, index, pointElementOptions.pointStyle), + + // Tooltip + hitRadius: custom.hitRadius ? custom.hitRadius : helpers.valueAtIndexOrDefault(dataset.pointHitRadius, index, pointElementOptions.hitRadius) + } + }); + + point._model.skip = custom.skip ? custom.skip : (isNaN(point._model.x) || isNaN(point._model.y)); + }, + updateBezierControlPoints: function() { + var chartArea = this.chart.chartArea; + var meta = this.getMeta(); + + helpers.each(meta.data, function(point, index) { + var model = point._model; + var controlPoints = helpers.splineCurve( + helpers.previousItem(meta.data, index, true)._model, + model, + helpers.nextItem(meta.data, index, true)._model, + model.tension + ); + + // Prevent the bezier going outside of the bounds of the graph + model.controlPointPreviousX = Math.max(Math.min(controlPoints.previous.x, chartArea.right), chartArea.left); + model.controlPointPreviousY = Math.max(Math.min(controlPoints.previous.y, chartArea.bottom), chartArea.top); + + model.controlPointNextX = Math.max(Math.min(controlPoints.next.x, chartArea.right), chartArea.left); + model.controlPointNextY = Math.max(Math.min(controlPoints.next.y, chartArea.bottom), chartArea.top); + + // Now pivot the point for animation + point.pivot(); + }); + }, + + setHoverStyle: function(point) { + // Point + var dataset = this.chart.data.datasets[point._datasetIndex]; + var custom = point.custom || {}; + var index = point._index; + var model = point._model; + + model.radius = custom.hoverRadius ? custom.hoverRadius : helpers.valueAtIndexOrDefault(dataset.pointHoverRadius, index, this.chart.options.elements.point.hoverRadius); + model.backgroundColor = custom.hoverBackgroundColor ? custom.hoverBackgroundColor : helpers.valueAtIndexOrDefault(dataset.pointHoverBackgroundColor, index, helpers.getHoverColor(model.backgroundColor)); + model.borderColor = custom.hoverBorderColor ? custom.hoverBorderColor : helpers.valueAtIndexOrDefault(dataset.pointHoverBorderColor, index, helpers.getHoverColor(model.borderColor)); + model.borderWidth = custom.hoverBorderWidth ? custom.hoverBorderWidth : helpers.valueAtIndexOrDefault(dataset.pointHoverBorderWidth, index, model.borderWidth); + }, + + removeHoverStyle: function(point) { + var dataset = this.chart.data.datasets[point._datasetIndex]; + var custom = point.custom || {}; + var index = point._index; + var model = point._model; + var pointElementOptions = this.chart.options.elements.point; + + model.radius = custom.radius ? custom.radius : helpers.valueAtIndexOrDefault(dataset.pointRadius, index, pointElementOptions.radius); + model.backgroundColor = custom.backgroundColor ? custom.backgroundColor : helpers.valueAtIndexOrDefault(dataset.pointBackgroundColor, index, pointElementOptions.backgroundColor); + model.borderColor = custom.borderColor ? custom.borderColor : helpers.valueAtIndexOrDefault(dataset.pointBorderColor, index, pointElementOptions.borderColor); + model.borderWidth = custom.borderWidth ? custom.borderWidth : helpers.valueAtIndexOrDefault(dataset.pointBorderWidth, index, pointElementOptions.borderWidth); + } + }); +}; + +},{"25":25,"40":40,"45":45}],21:[function(require,module,exports){ +'use strict'; + +var defaults = require(25); + +defaults._set('scatter', { + hover: { + mode: 'single' + }, + + scales: { + xAxes: [{ + id: 'x-axis-1', // need an ID so datasets can reference the scale + type: 'linear', // scatter should not use a category axis + position: 'bottom' + }], + yAxes: [{ + id: 'y-axis-1', + type: 'linear', + position: 'left' + }] + }, + + showLines: false, + + tooltips: { + callbacks: { + title: function() { + return ''; // doesn't make sense for scatter since data are formatted as a point + }, + label: function(item) { + return '(' + item.xLabel + ', ' + item.yLabel + ')'; + } + } + } +}); + +module.exports = function(Chart) { + + // Scatter charts use line controllers + Chart.controllers.scatter = Chart.controllers.line; + +}; + +},{"25":25}],22:[function(require,module,exports){ +/* global window: false */ +'use strict'; + +var defaults = require(25); +var Element = require(26); +var helpers = require(45); + +defaults._set('global', { + animation: { + duration: 1000, + easing: 'easeOutQuart', + onProgress: helpers.noop, + onComplete: helpers.noop + } +}); + +module.exports = function(Chart) { + + Chart.Animation = Element.extend({ + chart: null, // the animation associated chart instance + currentStep: 0, // the current animation step + numSteps: 60, // default number of steps + easing: '', // the easing to use for this animation + render: null, // render function used by the animation service + + onAnimationProgress: null, // user specified callback to fire on each step of the animation + onAnimationComplete: null, // user specified callback to fire when the animation finishes + }); + + Chart.animationService = { + frameDuration: 17, + animations: [], + dropFrames: 0, + request: null, + + /** + * @param {Chart} chart - The chart to animate. + * @param {Chart.Animation} animation - The animation that we will animate. + * @param {Number} duration - The animation duration in ms. + * @param {Boolean} lazy - if true, the chart is not marked as animating to enable more responsive interactions + */ + addAnimation: function(chart, animation, duration, lazy) { + var animations = this.animations; + var i, ilen; + + animation.chart = chart; + + if (!lazy) { + chart.animating = true; + } + + for (i = 0, ilen = animations.length; i < ilen; ++i) { + if (animations[i].chart === chart) { + animations[i] = animation; + return; + } + } + + animations.push(animation); + + // If there are no animations queued, manually kickstart a digest, for lack of a better word + if (animations.length === 1) { + this.requestAnimationFrame(); + } + }, + + cancelAnimation: function(chart) { + var index = helpers.findIndex(this.animations, function(animation) { + return animation.chart === chart; + }); + + if (index !== -1) { + this.animations.splice(index, 1); + chart.animating = false; + } + }, + + requestAnimationFrame: function() { + var me = this; + if (me.request === null) { + // Skip animation frame requests until the active one is executed. + // This can happen when processing mouse events, e.g. 'mousemove' + // and 'mouseout' events will trigger multiple renders. + me.request = helpers.requestAnimFrame.call(window, function() { + me.request = null; + me.startDigest(); + }); + } + }, + + /** + * @private + */ + startDigest: function() { + var me = this; + var startTime = Date.now(); + var framesToDrop = 0; + + if (me.dropFrames > 1) { + framesToDrop = Math.floor(me.dropFrames); + me.dropFrames = me.dropFrames % 1; + } + + me.advance(1 + framesToDrop); + + var endTime = Date.now(); + + me.dropFrames += (endTime - startTime) / me.frameDuration; + + // Do we have more stuff to animate? + if (me.animations.length > 0) { + me.requestAnimationFrame(); + } + }, + + /** + * @private + */ + advance: function(count) { + var animations = this.animations; + var animation, chart; + var i = 0; + + while (i < animations.length) { + animation = animations[i]; + chart = animation.chart; + + animation.currentStep = (animation.currentStep || 0) + count; + animation.currentStep = Math.min(animation.currentStep, animation.numSteps); + + helpers.callback(animation.render, [chart, animation], chart); + helpers.callback(animation.onAnimationProgress, [animation], chart); + + if (animation.currentStep >= animation.numSteps) { + helpers.callback(animation.onAnimationComplete, [animation], chart); + chart.animating = false; + animations.splice(i, 1); + } else { + ++i; + } + } + } + }; + + /** + * Provided for backward compatibility, use Chart.Animation instead + * @prop Chart.Animation#animationObject + * @deprecated since version 2.6.0 + * @todo remove at version 3 + */ + Object.defineProperty(Chart.Animation.prototype, 'animationObject', { + get: function() { + return this; + } + }); + + /** + * Provided for backward compatibility, use Chart.Animation#chart instead + * @prop Chart.Animation#chartInstance + * @deprecated since version 2.6.0 + * @todo remove at version 3 + */ + Object.defineProperty(Chart.Animation.prototype, 'chartInstance', { + get: function() { + return this.chart; + }, + set: function(value) { + this.chart = value; + } + }); + +}; + +},{"25":25,"26":26,"45":45}],23:[function(require,module,exports){ +'use strict'; + +var defaults = require(25); +var helpers = require(45); +var Interaction = require(28); +var platform = require(48); + +module.exports = function(Chart) { + var plugins = Chart.plugins; + + // Create a dictionary of chart types, to allow for extension of existing types + Chart.types = {}; + + // Store a reference to each instance - allowing us to globally resize chart instances on window resize. + // Destroy method on the chart will remove the instance of the chart from this reference. + Chart.instances = {}; + + // Controllers available for dataset visualization eg. bar, line, slice, etc. + Chart.controllers = {}; + + /** + * Initializes the given config with global and chart default values. + */ + function initConfig(config) { + config = config || {}; + + // Do NOT use configMerge() for the data object because this method merges arrays + // and so would change references to labels and datasets, preventing data updates. + var data = config.data = config.data || {}; + data.datasets = data.datasets || []; + data.labels = data.labels || []; + + config.options = helpers.configMerge( + defaults.global, + defaults[config.type], + config.options || {}); + + return config; + } + + /** + * Updates the config of the chart + * @param chart {Chart} chart to update the options for + */ + function updateConfig(chart) { + var newOptions = chart.options; + + // Update Scale(s) with options + if (newOptions.scale) { + chart.scale.options = newOptions.scale; + } else if (newOptions.scales) { + newOptions.scales.xAxes.concat(newOptions.scales.yAxes).forEach(function(scaleOptions) { + chart.scales[scaleOptions.id].options = scaleOptions; + }); + } + + // Tooltip + chart.tooltip._options = newOptions.tooltips; + } + + function positionIsHorizontal(position) { + return position === 'top' || position === 'bottom'; + } + + helpers.extend(Chart.prototype, /** @lends Chart */ { + /** + * @private + */ + construct: function(item, config) { + var me = this; + + config = initConfig(config); + + var context = platform.acquireContext(item, config); + var canvas = context && context.canvas; + var height = canvas && canvas.height; + var width = canvas && canvas.width; + + me.id = helpers.uid(); + me.ctx = context; + me.canvas = canvas; + me.config = config; + me.width = width; + me.height = height; + me.aspectRatio = height ? width / height : null; + me.options = config.options; + me._bufferedRender = false; + + /** + * Provided for backward compatibility, Chart and Chart.Controller have been merged, + * the "instance" still need to be defined since it might be called from plugins. + * @prop Chart#chart + * @deprecated since version 2.6.0 + * @todo remove at version 3 + * @private + */ + me.chart = me; + me.controller = me; // chart.chart.controller #inception + + // Add the chart instance to the global namespace + Chart.instances[me.id] = me; + + // Define alias to the config data: `chart.data === chart.config.data` + Object.defineProperty(me, 'data', { + get: function() { + return me.config.data; + }, + set: function(value) { + me.config.data = value; + } + }); + + if (!context || !canvas) { + // The given item is not a compatible context2d element, let's return before finalizing + // the chart initialization but after setting basic chart / controller properties that + // can help to figure out that the chart is not valid (e.g chart.canvas !== null); + // https://github.com/chartjs/Chart.js/issues/2807 + console.error("Failed to create chart: can't acquire context from the given item"); + return; + } + + me.initialize(); + me.update(); + }, + + /** + * @private + */ + initialize: function() { + var me = this; + + // Before init plugin notification + plugins.notify(me, 'beforeInit'); + + helpers.retinaScale(me, me.options.devicePixelRatio); + + me.bindEvents(); + + if (me.options.responsive) { + // Initial resize before chart draws (must be silent to preserve initial animations). + me.resize(true); + } + + // Make sure scales have IDs and are built before we build any controllers. + me.ensureScalesHaveIDs(); + me.buildScales(); + me.initToolTip(); + + // After init plugin notification + plugins.notify(me, 'afterInit'); + + return me; + }, + + clear: function() { + helpers.canvas.clear(this); + return this; + }, + + stop: function() { + // Stops any current animation loop occurring + Chart.animationService.cancelAnimation(this); + return this; + }, + + resize: function(silent) { + var me = this; + var options = me.options; + var canvas = me.canvas; + var aspectRatio = (options.maintainAspectRatio && me.aspectRatio) || null; + + // the canvas render width and height will be casted to integers so make sure that + // the canvas display style uses the same integer values to avoid blurring effect. + + // Set to 0 instead of canvas.size because the size defaults to 300x150 if the element is collased + var newWidth = Math.max(0, Math.floor(helpers.getMaximumWidth(canvas))); + var newHeight = Math.max(0, Math.floor(aspectRatio ? newWidth / aspectRatio : helpers.getMaximumHeight(canvas))); + + if (me.width === newWidth && me.height === newHeight) { + return; + } + + canvas.width = me.width = newWidth; + canvas.height = me.height = newHeight; + canvas.style.width = newWidth + 'px'; + canvas.style.height = newHeight + 'px'; + + helpers.retinaScale(me, options.devicePixelRatio); + + if (!silent) { + // Notify any plugins about the resize + var newSize = {width: newWidth, height: newHeight}; + plugins.notify(me, 'resize', [newSize]); + + // Notify of resize + if (me.options.onResize) { + me.options.onResize(me, newSize); + } + + me.stop(); + me.update(me.options.responsiveAnimationDuration); + } + }, + + ensureScalesHaveIDs: function() { + var options = this.options; + var scalesOptions = options.scales || {}; + var scaleOptions = options.scale; + + helpers.each(scalesOptions.xAxes, function(xAxisOptions, index) { + xAxisOptions.id = xAxisOptions.id || ('x-axis-' + index); + }); + + helpers.each(scalesOptions.yAxes, function(yAxisOptions, index) { + yAxisOptions.id = yAxisOptions.id || ('y-axis-' + index); + }); + + if (scaleOptions) { + scaleOptions.id = scaleOptions.id || 'scale'; + } + }, + + /** + * Builds a map of scale ID to scale object for future lookup. + */ + buildScales: function() { + var me = this; + var options = me.options; + var scales = me.scales = {}; + var items = []; + + if (options.scales) { + items = items.concat( + (options.scales.xAxes || []).map(function(xAxisOptions) { + return {options: xAxisOptions, dtype: 'category', dposition: 'bottom'}; + }), + (options.scales.yAxes || []).map(function(yAxisOptions) { + return {options: yAxisOptions, dtype: 'linear', dposition: 'left'}; + }) + ); + } + + if (options.scale) { + items.push({ + options: options.scale, + dtype: 'radialLinear', + isDefault: true, + dposition: 'chartArea' + }); + } + + helpers.each(items, function(item) { + var scaleOptions = item.options; + var scaleType = helpers.valueOrDefault(scaleOptions.type, item.dtype); + var scaleClass = Chart.scaleService.getScaleConstructor(scaleType); + if (!scaleClass) { + return; + } + + if (positionIsHorizontal(scaleOptions.position) !== positionIsHorizontal(item.dposition)) { + scaleOptions.position = item.dposition; + } + + var scale = new scaleClass({ + id: scaleOptions.id, + options: scaleOptions, + ctx: me.ctx, + chart: me + }); + + scales[scale.id] = scale; + scale.mergeTicksOptions(); + + // TODO(SB): I think we should be able to remove this custom case (options.scale) + // and consider it as a regular scale part of the "scales"" map only! This would + // make the logic easier and remove some useless? custom code. + if (item.isDefault) { + me.scale = scale; + } + }); + + Chart.scaleService.addScalesToLayout(this); + }, + + buildOrUpdateControllers: function() { + var me = this; + var types = []; + var newControllers = []; + + helpers.each(me.data.datasets, function(dataset, datasetIndex) { + var meta = me.getDatasetMeta(datasetIndex); + var type = dataset.type || me.config.type; + + if (meta.type && meta.type !== type) { + me.destroyDatasetMeta(datasetIndex); + meta = me.getDatasetMeta(datasetIndex); + } + meta.type = type; + + types.push(meta.type); + + if (meta.controller) { + meta.controller.updateIndex(datasetIndex); + } else { + var ControllerClass = Chart.controllers[meta.type]; + if (ControllerClass === undefined) { + throw new Error('"' + meta.type + '" is not a chart type.'); + } + + meta.controller = new ControllerClass(me, datasetIndex); + newControllers.push(meta.controller); + } + }, me); + + return newControllers; + }, + + /** + * Reset the elements of all datasets + * @private + */ + resetElements: function() { + var me = this; + helpers.each(me.data.datasets, function(dataset, datasetIndex) { + me.getDatasetMeta(datasetIndex).controller.reset(); + }, me); + }, + + /** + * Resets the chart back to it's state before the initial animation + */ + reset: function() { + this.resetElements(); + this.tooltip.initialize(); + }, + + update: function(config) { + var me = this; + + if (!config || typeof config !== 'object') { + // backwards compatibility + config = { + duration: config, + lazy: arguments[1] + }; + } + + updateConfig(me); + + if (plugins.notify(me, 'beforeUpdate') === false) { + return; + } + + // In case the entire data object changed + me.tooltip._data = me.data; + + // Make sure dataset controllers are updated and new controllers are reset + var newControllers = me.buildOrUpdateControllers(); + + // Make sure all dataset controllers have correct meta data counts + helpers.each(me.data.datasets, function(dataset, datasetIndex) { + me.getDatasetMeta(datasetIndex).controller.buildOrUpdateElements(); + }, me); + + me.updateLayout(); + + // Can only reset the new controllers after the scales have been updated + helpers.each(newControllers, function(controller) { + controller.reset(); + }); + + me.updateDatasets(); + + // Need to reset tooltip in case it is displayed with elements that are removed + // after update. + me.tooltip.initialize(); + + // Last active contains items that were previously in the tooltip. + // When we reset the tooltip, we need to clear it + me.lastActive = []; + + // Do this before render so that any plugins that need final scale updates can use it + plugins.notify(me, 'afterUpdate'); + + if (me._bufferedRender) { + me._bufferedRequest = { + duration: config.duration, + easing: config.easing, + lazy: config.lazy + }; + } else { + me.render(config); + } + }, + + /** + * Updates the chart layout unless a plugin returns `false` to the `beforeLayout` + * hook, in which case, plugins will not be called on `afterLayout`. + * @private + */ + updateLayout: function() { + var me = this; + + if (plugins.notify(me, 'beforeLayout') === false) { + return; + } + + Chart.layoutService.update(this, this.width, this.height); + + /** + * Provided for backward compatibility, use `afterLayout` instead. + * @method IPlugin#afterScaleUpdate + * @deprecated since version 2.5.0 + * @todo remove at version 3 + * @private + */ + plugins.notify(me, 'afterScaleUpdate'); + plugins.notify(me, 'afterLayout'); + }, + + /** + * Updates all datasets unless a plugin returns `false` to the `beforeDatasetsUpdate` + * hook, in which case, plugins will not be called on `afterDatasetsUpdate`. + * @private + */ + updateDatasets: function() { + var me = this; + + if (plugins.notify(me, 'beforeDatasetsUpdate') === false) { + return; + } + + for (var i = 0, ilen = me.data.datasets.length; i < ilen; ++i) { + me.updateDataset(i); + } + + plugins.notify(me, 'afterDatasetsUpdate'); + }, + + /** + * Updates dataset at index unless a plugin returns `false` to the `beforeDatasetUpdate` + * hook, in which case, plugins will not be called on `afterDatasetUpdate`. + * @private + */ + updateDataset: function(index) { + var me = this; + var meta = me.getDatasetMeta(index); + var args = { + meta: meta, + index: index + }; + + if (plugins.notify(me, 'beforeDatasetUpdate', [args]) === false) { + return; + } + + meta.controller.update(); + + plugins.notify(me, 'afterDatasetUpdate', [args]); + }, + + render: function(config) { + var me = this; + + if (!config || typeof config !== 'object') { + // backwards compatibility + config = { + duration: config, + lazy: arguments[1] + }; + } + + var duration = config.duration; + var lazy = config.lazy; + + if (plugins.notify(me, 'beforeRender') === false) { + return; + } + + var animationOptions = me.options.animation; + var onComplete = function(animation) { + plugins.notify(me, 'afterRender'); + helpers.callback(animationOptions && animationOptions.onComplete, [animation], me); + }; + + if (animationOptions && ((typeof duration !== 'undefined' && duration !== 0) || (typeof duration === 'undefined' && animationOptions.duration !== 0))) { + var animation = new Chart.Animation({ + numSteps: (duration || animationOptions.duration) / 16.66, // 60 fps + easing: config.easing || animationOptions.easing, + + render: function(chart, animationObject) { + var easingFunction = helpers.easing.effects[animationObject.easing]; + var currentStep = animationObject.currentStep; + var stepDecimal = currentStep / animationObject.numSteps; + + chart.draw(easingFunction(stepDecimal), stepDecimal, currentStep); + }, + + onAnimationProgress: animationOptions.onProgress, + onAnimationComplete: onComplete + }); + + Chart.animationService.addAnimation(me, animation, duration, lazy); + } else { + me.draw(); + + // See https://github.com/chartjs/Chart.js/issues/3781 + onComplete(new Chart.Animation({numSteps: 0, chart: me})); + } + + return me; + }, + + draw: function(easingValue) { + var me = this; + + me.clear(); + + if (helpers.isNullOrUndef(easingValue)) { + easingValue = 1; + } + + me.transition(easingValue); + + if (plugins.notify(me, 'beforeDraw', [easingValue]) === false) { + return; + } + + // Draw all the scales + helpers.each(me.boxes, function(box) { + box.draw(me.chartArea); + }, me); + + if (me.scale) { + me.scale.draw(); + } + + me.drawDatasets(easingValue); + me._drawTooltip(easingValue); + + plugins.notify(me, 'afterDraw', [easingValue]); + }, + + /** + * @private + */ + transition: function(easingValue) { + var me = this; + + for (var i = 0, ilen = (me.data.datasets || []).length; i < ilen; ++i) { + if (me.isDatasetVisible(i)) { + me.getDatasetMeta(i).controller.transition(easingValue); + } + } + + me.tooltip.transition(easingValue); + }, + + /** + * Draws all datasets unless a plugin returns `false` to the `beforeDatasetsDraw` + * hook, in which case, plugins will not be called on `afterDatasetsDraw`. + * @private + */ + drawDatasets: function(easingValue) { + var me = this; + + if (plugins.notify(me, 'beforeDatasetsDraw', [easingValue]) === false) { + return; + } + + // Draw datasets reversed to support proper line stacking + for (var i = (me.data.datasets || []).length - 1; i >= 0; --i) { + if (me.isDatasetVisible(i)) { + me.drawDataset(i, easingValue); + } + } + + plugins.notify(me, 'afterDatasetsDraw', [easingValue]); + }, + + /** + * Draws dataset at index unless a plugin returns `false` to the `beforeDatasetDraw` + * hook, in which case, plugins will not be called on `afterDatasetDraw`. + * @private + */ + drawDataset: function(index, easingValue) { + var me = this; + var meta = me.getDatasetMeta(index); + var args = { + meta: meta, + index: index, + easingValue: easingValue + }; + + if (plugins.notify(me, 'beforeDatasetDraw', [args]) === false) { + return; + } + + meta.controller.draw(easingValue); + + plugins.notify(me, 'afterDatasetDraw', [args]); + }, + + /** + * Draws tooltip unless a plugin returns `false` to the `beforeTooltipDraw` + * hook, in which case, plugins will not be called on `afterTooltipDraw`. + * @private + */ + _drawTooltip: function(easingValue) { + var me = this; + var tooltip = me.tooltip; + var args = { + tooltip: tooltip, + easingValue: easingValue + }; + + if (plugins.notify(me, 'beforeTooltipDraw', [args]) === false) { + return; + } + + tooltip.draw(); + + plugins.notify(me, 'afterTooltipDraw', [args]); + }, + + // Get the single element that was clicked on + // @return : An object containing the dataset index and element index of the matching element. Also contains the rectangle that was draw + getElementAtEvent: function(e) { + return Interaction.modes.single(this, e); + }, + + getElementsAtEvent: function(e) { + return Interaction.modes.label(this, e, {intersect: true}); + }, + + getElementsAtXAxis: function(e) { + return Interaction.modes['x-axis'](this, e, {intersect: true}); + }, + + getElementsAtEventForMode: function(e, mode, options) { + var method = Interaction.modes[mode]; + if (typeof method === 'function') { + return method(this, e, options); + } + + return []; + }, + + getDatasetAtEvent: function(e) { + return Interaction.modes.dataset(this, e, {intersect: true}); + }, + + getDatasetMeta: function(datasetIndex) { + var me = this; + var dataset = me.data.datasets[datasetIndex]; + if (!dataset._meta) { + dataset._meta = {}; + } + + var meta = dataset._meta[me.id]; + if (!meta) { + meta = dataset._meta[me.id] = { + type: null, + data: [], + dataset: null, + controller: null, + hidden: null, // See isDatasetVisible() comment + xAxisID: null, + yAxisID: null + }; + } + + return meta; + }, + + getVisibleDatasetCount: function() { + var count = 0; + for (var i = 0, ilen = this.data.datasets.length; i < ilen; ++i) { + if (this.isDatasetVisible(i)) { + count++; + } + } + return count; + }, + + isDatasetVisible: function(datasetIndex) { + var meta = this.getDatasetMeta(datasetIndex); + + // meta.hidden is a per chart dataset hidden flag override with 3 states: if true or false, + // the dataset.hidden value is ignored, else if null, the dataset hidden state is returned. + return typeof meta.hidden === 'boolean' ? !meta.hidden : !this.data.datasets[datasetIndex].hidden; + }, + + generateLegend: function() { + return this.options.legendCallback(this); + }, + + /** + * @private + */ + destroyDatasetMeta: function(datasetIndex) { + var id = this.id; + var dataset = this.data.datasets[datasetIndex]; + var meta = dataset._meta && dataset._meta[id]; + + if (meta) { + meta.controller.destroy(); + delete dataset._meta[id]; + } + }, + + destroy: function() { + var me = this; + var canvas = me.canvas; + var i, ilen; + + me.stop(); + + // dataset controllers need to cleanup associated data + for (i = 0, ilen = me.data.datasets.length; i < ilen; ++i) { + me.destroyDatasetMeta(i); + } + + if (canvas) { + me.unbindEvents(); + helpers.canvas.clear(me); + platform.releaseContext(me.ctx); + me.canvas = null; + me.ctx = null; + } + + plugins.notify(me, 'destroy'); + + delete Chart.instances[me.id]; + }, + + toBase64Image: function() { + return this.canvas.toDataURL.apply(this.canvas, arguments); + }, + + initToolTip: function() { + var me = this; + me.tooltip = new Chart.Tooltip({ + _chart: me, + _chartInstance: me, // deprecated, backward compatibility + _data: me.data, + _options: me.options.tooltips + }, me); + }, + + /** + * @private + */ + bindEvents: function() { + var me = this; + var listeners = me._listeners = {}; + var listener = function() { + me.eventHandler.apply(me, arguments); + }; + + helpers.each(me.options.events, function(type) { + platform.addEventListener(me, type, listener); + listeners[type] = listener; + }); + + // Elements used to detect size change should not be injected for non responsive charts. + // See https://github.com/chartjs/Chart.js/issues/2210 + if (me.options.responsive) { + listener = function() { + me.resize(); + }; + + platform.addEventListener(me, 'resize', listener); + listeners.resize = listener; + } + }, + + /** + * @private + */ + unbindEvents: function() { + var me = this; + var listeners = me._listeners; + if (!listeners) { + return; + } + + delete me._listeners; + helpers.each(listeners, function(listener, type) { + platform.removeEventListener(me, type, listener); + }); + }, + + updateHoverStyle: function(elements, mode, enabled) { + var method = enabled ? 'setHoverStyle' : 'removeHoverStyle'; + var element, i, ilen; + + for (i = 0, ilen = elements.length; i < ilen; ++i) { + element = elements[i]; + if (element) { + this.getDatasetMeta(element._datasetIndex).controller[method](element); + } + } + }, + + /** + * @private + */ + eventHandler: function(e) { + var me = this; + var tooltip = me.tooltip; + + if (plugins.notify(me, 'beforeEvent', [e]) === false) { + return; + } + + // Buffer any update calls so that renders do not occur + me._bufferedRender = true; + me._bufferedRequest = null; + + var changed = me.handleEvent(e); + changed |= tooltip && tooltip.handleEvent(e); + + plugins.notify(me, 'afterEvent', [e]); + + var bufferedRequest = me._bufferedRequest; + if (bufferedRequest) { + // If we have an update that was triggered, we need to do a normal render + me.render(bufferedRequest); + } else if (changed && !me.animating) { + // If entering, leaving, or changing elements, animate the change via pivot + me.stop(); + + // We only need to render at this point. Updating will cause scales to be + // recomputed generating flicker & using more memory than necessary. + me.render(me.options.hover.animationDuration, true); + } + + me._bufferedRender = false; + me._bufferedRequest = null; + + return me; + }, + + /** + * Handle an event + * @private + * @param {IEvent} event the event to handle + * @return {Boolean} true if the chart needs to re-render + */ + handleEvent: function(e) { + var me = this; + var options = me.options || {}; + var hoverOptions = options.hover; + var changed = false; + + me.lastActive = me.lastActive || []; + + // Find Active Elements for hover and tooltips + if (e.type === 'mouseout') { + me.active = []; + } else { + me.active = me.getElementsAtEventForMode(e, hoverOptions.mode, hoverOptions); + } + + // Invoke onHover hook + // Need to call with native event here to not break backwards compatibility + helpers.callback(options.onHover || options.hover.onHover, [e.native, me.active], me); + + if (e.type === 'mouseup' || e.type === 'click') { + if (options.onClick) { + // Use e.native here for backwards compatibility + options.onClick.call(me, e.native, me.active); + } + } + + // Remove styling for last active (even if it may still be active) + if (me.lastActive.length) { + me.updateHoverStyle(me.lastActive, hoverOptions.mode, false); + } + + // Built in hover styling + if (me.active.length && hoverOptions.mode) { + me.updateHoverStyle(me.active, hoverOptions.mode, true); + } + + changed = !helpers.arrayEquals(me.active, me.lastActive); + + // Remember Last Actives + me.lastActive = me.active; + + return changed; + } + }); + + /** + * Provided for backward compatibility, use Chart instead. + * @class Chart.Controller + * @deprecated since version 2.6.0 + * @todo remove at version 3 + * @private + */ + Chart.Controller = Chart; +}; + +},{"25":25,"28":28,"45":45,"48":48}],24:[function(require,module,exports){ +'use strict'; + +var helpers = require(45); + +module.exports = function(Chart) { + + var arrayEvents = ['push', 'pop', 'shift', 'splice', 'unshift']; + + /** + * Hooks the array methods that add or remove values ('push', pop', 'shift', 'splice', + * 'unshift') and notify the listener AFTER the array has been altered. Listeners are + * called on the 'onData*' callbacks (e.g. onDataPush, etc.) with same arguments. + */ + function listenArrayEvents(array, listener) { + if (array._chartjs) { + array._chartjs.listeners.push(listener); + return; + } + + Object.defineProperty(array, '_chartjs', { + configurable: true, + enumerable: false, + value: { + listeners: [listener] + } + }); + + arrayEvents.forEach(function(key) { + var method = 'onData' + key.charAt(0).toUpperCase() + key.slice(1); + var base = array[key]; + + Object.defineProperty(array, key, { + configurable: true, + enumerable: false, + value: function() { + var args = Array.prototype.slice.call(arguments); + var res = base.apply(this, args); + + helpers.each(array._chartjs.listeners, function(object) { + if (typeof object[method] === 'function') { + object[method].apply(object, args); + } + }); + + return res; + } + }); + }); + } + + /** + * Removes the given array event listener and cleanup extra attached properties (such as + * the _chartjs stub and overridden methods) if array doesn't have any more listeners. + */ + function unlistenArrayEvents(array, listener) { + var stub = array._chartjs; + if (!stub) { + return; + } + + var listeners = stub.listeners; + var index = listeners.indexOf(listener); + if (index !== -1) { + listeners.splice(index, 1); + } + + if (listeners.length > 0) { + return; + } + + arrayEvents.forEach(function(key) { + delete array[key]; + }); + + delete array._chartjs; + } + + // Base class for all dataset controllers (line, bar, etc) + Chart.DatasetController = function(chart, datasetIndex) { + this.initialize(chart, datasetIndex); + }; + + helpers.extend(Chart.DatasetController.prototype, { + + /** + * Element type used to generate a meta dataset (e.g. Chart.element.Line). + * @type {Chart.core.element} + */ + datasetElementType: null, + + /** + * Element type used to generate a meta data (e.g. Chart.element.Point). + * @type {Chart.core.element} + */ + dataElementType: null, + + initialize: function(chart, datasetIndex) { + var me = this; + me.chart = chart; + me.index = datasetIndex; + me.linkScales(); + me.addElements(); + }, + + updateIndex: function(datasetIndex) { + this.index = datasetIndex; + }, + + linkScales: function() { + var me = this; + var meta = me.getMeta(); + var dataset = me.getDataset(); + + if (meta.xAxisID === null) { + meta.xAxisID = dataset.xAxisID || me.chart.options.scales.xAxes[0].id; + } + if (meta.yAxisID === null) { + meta.yAxisID = dataset.yAxisID || me.chart.options.scales.yAxes[0].id; + } + }, + + getDataset: function() { + return this.chart.data.datasets[this.index]; + }, + + getMeta: function() { + return this.chart.getDatasetMeta(this.index); + }, + + getScaleForId: function(scaleID) { + return this.chart.scales[scaleID]; + }, + + reset: function() { + this.update(true); + }, + + /** + * @private + */ + destroy: function() { + if (this._data) { + unlistenArrayEvents(this._data, this); + } + }, + + createMetaDataset: function() { + var me = this; + var type = me.datasetElementType; + return type && new type({ + _chart: me.chart, + _datasetIndex: me.index + }); + }, + + createMetaData: function(index) { + var me = this; + var type = me.dataElementType; + return type && new type({ + _chart: me.chart, + _datasetIndex: me.index, + _index: index + }); + }, + + addElements: function() { + var me = this; + var meta = me.getMeta(); + var data = me.getDataset().data || []; + var metaData = meta.data; + var i, ilen; + + for (i = 0, ilen = data.length; i < ilen; ++i) { + metaData[i] = metaData[i] || me.createMetaData(i); + } + + meta.dataset = meta.dataset || me.createMetaDataset(); + }, + + addElementAndReset: function(index) { + var element = this.createMetaData(index); + this.getMeta().data.splice(index, 0, element); + this.updateElement(element, index, true); + }, + + buildOrUpdateElements: function() { + var me = this; + var dataset = me.getDataset(); + var data = dataset.data || (dataset.data = []); + + // In order to correctly handle data addition/deletion animation (an thus simulate + // real-time charts), we need to monitor these data modifications and synchronize + // the internal meta data accordingly. + if (me._data !== data) { + if (me._data) { + // This case happens when the user replaced the data array instance. + unlistenArrayEvents(me._data, me); + } + + listenArrayEvents(data, me); + me._data = data; + } + + // Re-sync meta data in case the user replaced the data array or if we missed + // any updates and so make sure that we handle number of datapoints changing. + me.resyncElements(); + }, + + update: helpers.noop, + + transition: function(easingValue) { + var meta = this.getMeta(); + var elements = meta.data || []; + var ilen = elements.length; + var i = 0; + + for (; i < ilen; ++i) { + elements[i].transition(easingValue); + } + + if (meta.dataset) { + meta.dataset.transition(easingValue); + } + }, + + draw: function() { + var meta = this.getMeta(); + var elements = meta.data || []; + var ilen = elements.length; + var i = 0; + + if (meta.dataset) { + meta.dataset.draw(); + } + + for (; i < ilen; ++i) { + elements[i].draw(); + } + }, + + removeHoverStyle: function(element, elementOpts) { + var dataset = this.chart.data.datasets[element._datasetIndex]; + var index = element._index; + var custom = element.custom || {}; + var valueOrDefault = helpers.valueAtIndexOrDefault; + var model = element._model; + + model.backgroundColor = custom.backgroundColor ? custom.backgroundColor : valueOrDefault(dataset.backgroundColor, index, elementOpts.backgroundColor); + model.borderColor = custom.borderColor ? custom.borderColor : valueOrDefault(dataset.borderColor, index, elementOpts.borderColor); + model.borderWidth = custom.borderWidth ? custom.borderWidth : valueOrDefault(dataset.borderWidth, index, elementOpts.borderWidth); + }, + + setHoverStyle: function(element) { + var dataset = this.chart.data.datasets[element._datasetIndex]; + var index = element._index; + var custom = element.custom || {}; + var valueOrDefault = helpers.valueAtIndexOrDefault; + var getHoverColor = helpers.getHoverColor; + var model = element._model; + + model.backgroundColor = custom.hoverBackgroundColor ? custom.hoverBackgroundColor : valueOrDefault(dataset.hoverBackgroundColor, index, getHoverColor(model.backgroundColor)); + model.borderColor = custom.hoverBorderColor ? custom.hoverBorderColor : valueOrDefault(dataset.hoverBorderColor, index, getHoverColor(model.borderColor)); + model.borderWidth = custom.hoverBorderWidth ? custom.hoverBorderWidth : valueOrDefault(dataset.hoverBorderWidth, index, model.borderWidth); + }, + + /** + * @private + */ + resyncElements: function() { + var me = this; + var meta = me.getMeta(); + var data = me.getDataset().data; + var numMeta = meta.data.length; + var numData = data.length; + + if (numData < numMeta) { + meta.data.splice(numData, numMeta - numData); + } else if (numData > numMeta) { + me.insertElements(numMeta, numData - numMeta); + } + }, + + /** + * @private + */ + insertElements: function(start, count) { + for (var i = 0; i < count; ++i) { + this.addElementAndReset(start + i); + } + }, + + /** + * @private + */ + onDataPush: function() { + this.insertElements(this.getDataset().data.length - 1, arguments.length); + }, + + /** + * @private + */ + onDataPop: function() { + this.getMeta().data.pop(); + }, + + /** + * @private + */ + onDataShift: function() { + this.getMeta().data.shift(); + }, + + /** + * @private + */ + onDataSplice: function(start, count) { + this.getMeta().data.splice(start, count); + this.insertElements(start, arguments.length - 2); + }, + + /** + * @private + */ + onDataUnshift: function() { + this.insertElements(0, arguments.length); + } + }); + + Chart.DatasetController.extend = helpers.inherits; +}; + +},{"45":45}],25:[function(require,module,exports){ +'use strict'; + +var helpers = require(45); + +module.exports = { + /** + * @private + */ + _set: function(scope, values) { + return helpers.merge(this[scope] || (this[scope] = {}), values); + } +}; + +},{"45":45}],26:[function(require,module,exports){ +'use strict'; + +var color = require(2); +var helpers = require(45); + +function interpolate(start, view, model, ease) { + var keys = Object.keys(model); + var i, ilen, key, actual, origin, target, type, c0, c1; + + for (i = 0, ilen = keys.length; i < ilen; ++i) { + key = keys[i]; + + target = model[key]; + + // if a value is added to the model after pivot() has been called, the view + // doesn't contain it, so let's initialize the view to the target value. + if (!view.hasOwnProperty(key)) { + view[key] = target; + } + + actual = view[key]; + + if (actual === target || key[0] === '_') { + continue; + } + + if (!start.hasOwnProperty(key)) { + start[key] = actual; + } + + origin = start[key]; + + type = typeof target; + + if (type === typeof origin) { + if (type === 'string') { + c0 = color(origin); + if (c0.valid) { + c1 = color(target); + if (c1.valid) { + view[key] = c1.mix(c0, ease).rgbString(); + continue; + } + } + } else if (type === 'number' && isFinite(origin) && isFinite(target)) { + view[key] = origin + (target - origin) * ease; + continue; + } + } + + view[key] = target; + } +} + +var Element = function(configuration) { + helpers.extend(this, configuration); + this.initialize.apply(this, arguments); +}; + +helpers.extend(Element.prototype, { + + initialize: function() { + this.hidden = false; + }, + + pivot: function() { + var me = this; + if (!me._view) { + me._view = helpers.clone(me._model); + } + me._start = {}; + return me; + }, + + transition: function(ease) { + var me = this; + var model = me._model; + var start = me._start; + var view = me._view; + + // No animation -> No Transition + if (!model || ease === 1) { + me._view = model; + me._start = null; + return me; + } + + if (!view) { + view = me._view = {}; + } + + if (!start) { + start = me._start = {}; + } + + interpolate(start, view, model, ease); + + return me; + }, + + tooltipPosition: function() { + return { + x: this._model.x, + y: this._model.y + }; + }, + + hasValue: function() { + return helpers.isNumber(this._model.x) && helpers.isNumber(this._model.y); + } +}); + +Element.extend = helpers.inherits; + +module.exports = Element; + +},{"2":2,"45":45}],27:[function(require,module,exports){ +/* global window: false */ +/* global document: false */ +'use strict'; + +var color = require(2); +var defaults = require(25); +var helpers = require(45); + +module.exports = function(Chart) { + + // -- Basic js utility methods + + helpers.configMerge = function(/* objects ... */) { + return helpers.merge(helpers.clone(arguments[0]), [].slice.call(arguments, 1), { + merger: function(key, target, source, options) { + var tval = target[key] || {}; + var sval = source[key]; + + if (key === 'scales') { + // scale config merging is complex. Add our own function here for that + target[key] = helpers.scaleMerge(tval, sval); + } else if (key === 'scale') { + // used in polar area & radar charts since there is only one scale + target[key] = helpers.merge(tval, [Chart.scaleService.getScaleDefaults(sval.type), sval]); + } else { + helpers._merger(key, target, source, options); + } + } + }); + }; + + helpers.scaleMerge = function(/* objects ... */) { + return helpers.merge(helpers.clone(arguments[0]), [].slice.call(arguments, 1), { + merger: function(key, target, source, options) { + if (key === 'xAxes' || key === 'yAxes') { + var slen = source[key].length; + var i, type, scale; + + if (!target[key]) { + target[key] = []; + } + + for (i = 0; i < slen; ++i) { + scale = source[key][i]; + type = helpers.valueOrDefault(scale.type, key === 'xAxes' ? 'category' : 'linear'); + + if (i >= target[key].length) { + target[key].push({}); + } + + if (!target[key][i].type || (scale.type && scale.type !== target[key][i].type)) { + // new/untyped scale or type changed: let's apply the new defaults + // then merge source scale to correctly overwrite the defaults. + helpers.merge(target[key][i], [Chart.scaleService.getScaleDefaults(type), scale]); + } else { + // scales type are the same + helpers.merge(target[key][i], scale); + } + } + } else { + helpers._merger(key, target, source, options); + } + } + }); + }; + + helpers.where = function(collection, filterCallback) { + if (helpers.isArray(collection) && Array.prototype.filter) { + return collection.filter(filterCallback); + } + var filtered = []; + + helpers.each(collection, function(item) { + if (filterCallback(item)) { + filtered.push(item); + } + }); + + return filtered; + }; + helpers.findIndex = Array.prototype.findIndex ? + function(array, callback, scope) { + return array.findIndex(callback, scope); + } : + function(array, callback, scope) { + scope = scope === undefined ? array : scope; + for (var i = 0, ilen = array.length; i < ilen; ++i) { + if (callback.call(scope, array[i], i, array)) { + return i; + } + } + return -1; + }; + helpers.findNextWhere = function(arrayToSearch, filterCallback, startIndex) { + // Default to start of the array + if (helpers.isNullOrUndef(startIndex)) { + startIndex = -1; + } + for (var i = startIndex + 1; i < arrayToSearch.length; i++) { + var currentItem = arrayToSearch[i]; + if (filterCallback(currentItem)) { + return currentItem; + } + } + }; + helpers.findPreviousWhere = function(arrayToSearch, filterCallback, startIndex) { + // Default to end of the array + if (helpers.isNullOrUndef(startIndex)) { + startIndex = arrayToSearch.length; + } + for (var i = startIndex - 1; i >= 0; i--) { + var currentItem = arrayToSearch[i]; + if (filterCallback(currentItem)) { + return currentItem; + } + } + }; + + // -- Math methods + helpers.isNumber = function(n) { + return !isNaN(parseFloat(n)) && isFinite(n); + }; + helpers.almostEquals = function(x, y, epsilon) { + return Math.abs(x - y) < epsilon; + }; + helpers.almostWhole = function(x, epsilon) { + var rounded = Math.round(x); + return (((rounded - epsilon) < x) && ((rounded + epsilon) > x)); + }; + helpers.max = function(array) { + return array.reduce(function(max, value) { + if (!isNaN(value)) { + return Math.max(max, value); + } + return max; + }, Number.NEGATIVE_INFINITY); + }; + helpers.min = function(array) { + return array.reduce(function(min, value) { + if (!isNaN(value)) { + return Math.min(min, value); + } + return min; + }, Number.POSITIVE_INFINITY); + }; + helpers.sign = Math.sign ? + function(x) { + return Math.sign(x); + } : + function(x) { + x = +x; // convert to a number + if (x === 0 || isNaN(x)) { + return x; + } + return x > 0 ? 1 : -1; + }; + helpers.log10 = Math.log10 ? + function(x) { + return Math.log10(x); + } : + function(x) { + return Math.log(x) / Math.LN10; + }; + helpers.toRadians = function(degrees) { + return degrees * (Math.PI / 180); + }; + helpers.toDegrees = function(radians) { + return radians * (180 / Math.PI); + }; + // Gets the angle from vertical upright to the point about a centre. + helpers.getAngleFromPoint = function(centrePoint, anglePoint) { + var distanceFromXCenter = anglePoint.x - centrePoint.x; + var distanceFromYCenter = anglePoint.y - centrePoint.y; + var radialDistanceFromCenter = Math.sqrt(distanceFromXCenter * distanceFromXCenter + distanceFromYCenter * distanceFromYCenter); + + var angle = Math.atan2(distanceFromYCenter, distanceFromXCenter); + + if (angle < (-0.5 * Math.PI)) { + angle += 2.0 * Math.PI; // make sure the returned angle is in the range of (-PI/2, 3PI/2] + } + + return { + angle: angle, + distance: radialDistanceFromCenter + }; + }; + helpers.distanceBetweenPoints = function(pt1, pt2) { + return Math.sqrt(Math.pow(pt2.x - pt1.x, 2) + Math.pow(pt2.y - pt1.y, 2)); + }; + helpers.aliasPixel = function(pixelWidth) { + return (pixelWidth % 2 === 0) ? 0 : 0.5; + }; + helpers.splineCurve = function(firstPoint, middlePoint, afterPoint, t) { + // Props to Rob Spencer at scaled innovation for his post on splining between points + // http://scaledinnovation.com/analytics/splines/aboutSplines.html + + // This function must also respect "skipped" points + + var previous = firstPoint.skip ? middlePoint : firstPoint; + var current = middlePoint; + var next = afterPoint.skip ? middlePoint : afterPoint; + + var d01 = Math.sqrt(Math.pow(current.x - previous.x, 2) + Math.pow(current.y - previous.y, 2)); + var d12 = Math.sqrt(Math.pow(next.x - current.x, 2) + Math.pow(next.y - current.y, 2)); + + var s01 = d01 / (d01 + d12); + var s12 = d12 / (d01 + d12); + + // If all points are the same, s01 & s02 will be inf + s01 = isNaN(s01) ? 0 : s01; + s12 = isNaN(s12) ? 0 : s12; + + var fa = t * s01; // scaling factor for triangle Ta + var fb = t * s12; + + return { + previous: { + x: current.x - fa * (next.x - previous.x), + y: current.y - fa * (next.y - previous.y) + }, + next: { + x: current.x + fb * (next.x - previous.x), + y: current.y + fb * (next.y - previous.y) + } + }; + }; + helpers.EPSILON = Number.EPSILON || 1e-14; + helpers.splineCurveMonotone = function(points) { + // This function calculates Bézier control points in a similar way than |splineCurve|, + // but preserves monotonicity of the provided data and ensures no local extremums are added + // between the dataset discrete points due to the interpolation. + // See : https://en.wikipedia.org/wiki/Monotone_cubic_interpolation + + var pointsWithTangents = (points || []).map(function(point) { + return { + model: point._model, + deltaK: 0, + mK: 0 + }; + }); + + // Calculate slopes (deltaK) and initialize tangents (mK) + var pointsLen = pointsWithTangents.length; + var i, pointBefore, pointCurrent, pointAfter; + for (i = 0; i < pointsLen; ++i) { + pointCurrent = pointsWithTangents[i]; + if (pointCurrent.model.skip) { + continue; + } + + pointBefore = i > 0 ? pointsWithTangents[i - 1] : null; + pointAfter = i < pointsLen - 1 ? pointsWithTangents[i + 1] : null; + if (pointAfter && !pointAfter.model.skip) { + var slopeDeltaX = (pointAfter.model.x - pointCurrent.model.x); + + // In the case of two points that appear at the same x pixel, slopeDeltaX is 0 + pointCurrent.deltaK = slopeDeltaX !== 0 ? (pointAfter.model.y - pointCurrent.model.y) / slopeDeltaX : 0; + } + + if (!pointBefore || pointBefore.model.skip) { + pointCurrent.mK = pointCurrent.deltaK; + } else if (!pointAfter || pointAfter.model.skip) { + pointCurrent.mK = pointBefore.deltaK; + } else if (this.sign(pointBefore.deltaK) !== this.sign(pointCurrent.deltaK)) { + pointCurrent.mK = 0; + } else { + pointCurrent.mK = (pointBefore.deltaK + pointCurrent.deltaK) / 2; + } + } + + // Adjust tangents to ensure monotonic properties + var alphaK, betaK, tauK, squaredMagnitude; + for (i = 0; i < pointsLen - 1; ++i) { + pointCurrent = pointsWithTangents[i]; + pointAfter = pointsWithTangents[i + 1]; + if (pointCurrent.model.skip || pointAfter.model.skip) { + continue; + } + + if (helpers.almostEquals(pointCurrent.deltaK, 0, this.EPSILON)) { + pointCurrent.mK = pointAfter.mK = 0; + continue; + } + + alphaK = pointCurrent.mK / pointCurrent.deltaK; + betaK = pointAfter.mK / pointCurrent.deltaK; + squaredMagnitude = Math.pow(alphaK, 2) + Math.pow(betaK, 2); + if (squaredMagnitude <= 9) { + continue; + } + + tauK = 3 / Math.sqrt(squaredMagnitude); + pointCurrent.mK = alphaK * tauK * pointCurrent.deltaK; + pointAfter.mK = betaK * tauK * pointCurrent.deltaK; + } + + // Compute control points + var deltaX; + for (i = 0; i < pointsLen; ++i) { + pointCurrent = pointsWithTangents[i]; + if (pointCurrent.model.skip) { + continue; + } + + pointBefore = i > 0 ? pointsWithTangents[i - 1] : null; + pointAfter = i < pointsLen - 1 ? pointsWithTangents[i + 1] : null; + if (pointBefore && !pointBefore.model.skip) { + deltaX = (pointCurrent.model.x - pointBefore.model.x) / 3; + pointCurrent.model.controlPointPreviousX = pointCurrent.model.x - deltaX; + pointCurrent.model.controlPointPreviousY = pointCurrent.model.y - deltaX * pointCurrent.mK; + } + if (pointAfter && !pointAfter.model.skip) { + deltaX = (pointAfter.model.x - pointCurrent.model.x) / 3; + pointCurrent.model.controlPointNextX = pointCurrent.model.x + deltaX; + pointCurrent.model.controlPointNextY = pointCurrent.model.y + deltaX * pointCurrent.mK; + } + } + }; + helpers.nextItem = function(collection, index, loop) { + if (loop) { + return index >= collection.length - 1 ? collection[0] : collection[index + 1]; + } + return index >= collection.length - 1 ? collection[collection.length - 1] : collection[index + 1]; + }; + helpers.previousItem = function(collection, index, loop) { + if (loop) { + return index <= 0 ? collection[collection.length - 1] : collection[index - 1]; + } + return index <= 0 ? collection[0] : collection[index - 1]; + }; + // Implementation of the nice number algorithm used in determining where axis labels will go + helpers.niceNum = function(range, round) { + var exponent = Math.floor(helpers.log10(range)); + var fraction = range / Math.pow(10, exponent); + var niceFraction; + + if (round) { + if (fraction < 1.5) { + niceFraction = 1; + } else if (fraction < 3) { + niceFraction = 2; + } else if (fraction < 7) { + niceFraction = 5; + } else { + niceFraction = 10; + } + } else if (fraction <= 1.0) { + niceFraction = 1; + } else if (fraction <= 2) { + niceFraction = 2; + } else if (fraction <= 5) { + niceFraction = 5; + } else { + niceFraction = 10; + } + + return niceFraction * Math.pow(10, exponent); + }; + // Request animation polyfill - http://www.paulirish.com/2011/requestanimationframe-for-smart-animating/ + helpers.requestAnimFrame = (function() { + if (typeof window === 'undefined') { + return function(callback) { + callback(); + }; + } + return window.requestAnimationFrame || + window.webkitRequestAnimationFrame || + window.mozRequestAnimationFrame || + window.oRequestAnimationFrame || + window.msRequestAnimationFrame || + function(callback) { + return window.setTimeout(callback, 1000 / 60); + }; + }()); + // -- DOM methods + helpers.getRelativePosition = function(evt, chart) { + var mouseX, mouseY; + var e = evt.originalEvent || evt; + var canvas = evt.currentTarget || evt.srcElement; + var boundingRect = canvas.getBoundingClientRect(); + + var touches = e.touches; + if (touches && touches.length > 0) { + mouseX = touches[0].clientX; + mouseY = touches[0].clientY; + + } else { + mouseX = e.clientX; + mouseY = e.clientY; + } + + // Scale mouse coordinates into canvas coordinates + // by following the pattern laid out by 'jerryj' in the comments of + // http://www.html5canvastutorials.com/advanced/html5-canvas-mouse-coordinates/ + var paddingLeft = parseFloat(helpers.getStyle(canvas, 'padding-left')); + var paddingTop = parseFloat(helpers.getStyle(canvas, 'padding-top')); + var paddingRight = parseFloat(helpers.getStyle(canvas, 'padding-right')); + var paddingBottom = parseFloat(helpers.getStyle(canvas, 'padding-bottom')); + var width = boundingRect.right - boundingRect.left - paddingLeft - paddingRight; + var height = boundingRect.bottom - boundingRect.top - paddingTop - paddingBottom; + + // We divide by the current device pixel ratio, because the canvas is scaled up by that amount in each direction. However + // the backend model is in unscaled coordinates. Since we are going to deal with our model coordinates, we go back here + mouseX = Math.round((mouseX - boundingRect.left - paddingLeft) / (width) * canvas.width / chart.currentDevicePixelRatio); + mouseY = Math.round((mouseY - boundingRect.top - paddingTop) / (height) * canvas.height / chart.currentDevicePixelRatio); + + return { + x: mouseX, + y: mouseY + }; + + }; + + // Private helper function to convert max-width/max-height values that may be percentages into a number + function parseMaxStyle(styleValue, node, parentProperty) { + var valueInPixels; + if (typeof styleValue === 'string') { + valueInPixels = parseInt(styleValue, 10); + + if (styleValue.indexOf('%') !== -1) { + // percentage * size in dimension + valueInPixels = valueInPixels / 100 * node.parentNode[parentProperty]; + } + } else { + valueInPixels = styleValue; + } + + return valueInPixels; + } + + /** + * Returns if the given value contains an effective constraint. + * @private + */ + function isConstrainedValue(value) { + return value !== undefined && value !== null && value !== 'none'; + } + + // Private helper to get a constraint dimension + // @param domNode : the node to check the constraint on + // @param maxStyle : the style that defines the maximum for the direction we are using (maxWidth / maxHeight) + // @param percentageProperty : property of parent to use when calculating width as a percentage + // @see http://www.nathanaeljones.com/blog/2013/reading-max-width-cross-browser + function getConstraintDimension(domNode, maxStyle, percentageProperty) { + var view = document.defaultView; + var parentNode = domNode.parentNode; + var constrainedNode = view.getComputedStyle(domNode)[maxStyle]; + var constrainedContainer = view.getComputedStyle(parentNode)[maxStyle]; + var hasCNode = isConstrainedValue(constrainedNode); + var hasCContainer = isConstrainedValue(constrainedContainer); + var infinity = Number.POSITIVE_INFINITY; + + if (hasCNode || hasCContainer) { + return Math.min( + hasCNode ? parseMaxStyle(constrainedNode, domNode, percentageProperty) : infinity, + hasCContainer ? parseMaxStyle(constrainedContainer, parentNode, percentageProperty) : infinity); + } + + return 'none'; + } + // returns Number or undefined if no constraint + helpers.getConstraintWidth = function(domNode) { + return getConstraintDimension(domNode, 'max-width', 'clientWidth'); + }; + // returns Number or undefined if no constraint + helpers.getConstraintHeight = function(domNode) { + return getConstraintDimension(domNode, 'max-height', 'clientHeight'); + }; + helpers.getMaximumWidth = function(domNode) { + var container = domNode.parentNode; + if (!container) { + return domNode.clientWidth; + } + + var paddingLeft = parseInt(helpers.getStyle(container, 'padding-left'), 10); + var paddingRight = parseInt(helpers.getStyle(container, 'padding-right'), 10); + var w = container.clientWidth - paddingLeft - paddingRight; + var cw = helpers.getConstraintWidth(domNode); + return isNaN(cw) ? w : Math.min(w, cw); + }; + helpers.getMaximumHeight = function(domNode) { + var container = domNode.parentNode; + if (!container) { + return domNode.clientHeight; + } + + var paddingTop = parseInt(helpers.getStyle(container, 'padding-top'), 10); + var paddingBottom = parseInt(helpers.getStyle(container, 'padding-bottom'), 10); + var h = container.clientHeight - paddingTop - paddingBottom; + var ch = helpers.getConstraintHeight(domNode); + return isNaN(ch) ? h : Math.min(h, ch); + }; + helpers.getStyle = function(el, property) { + return el.currentStyle ? + el.currentStyle[property] : + document.defaultView.getComputedStyle(el, null).getPropertyValue(property); + }; + helpers.retinaScale = function(chart, forceRatio) { + var pixelRatio = chart.currentDevicePixelRatio = forceRatio || window.devicePixelRatio || 1; + if (pixelRatio === 1) { + return; + } + + var canvas = chart.canvas; + var height = chart.height; + var width = chart.width; + + canvas.height = height * pixelRatio; + canvas.width = width * pixelRatio; + chart.ctx.scale(pixelRatio, pixelRatio); + + // If no style has been set on the canvas, the render size is used as display size, + // making the chart visually bigger, so let's enforce it to the "correct" values. + // See https://github.com/chartjs/Chart.js/issues/3575 + canvas.style.height = height + 'px'; + canvas.style.width = width + 'px'; + }; + // -- Canvas methods + helpers.fontString = function(pixelSize, fontStyle, fontFamily) { + return fontStyle + ' ' + pixelSize + 'px ' + fontFamily; + }; + helpers.longestText = function(ctx, font, arrayOfThings, cache) { + cache = cache || {}; + var data = cache.data = cache.data || {}; + var gc = cache.garbageCollect = cache.garbageCollect || []; + + if (cache.font !== font) { + data = cache.data = {}; + gc = cache.garbageCollect = []; + cache.font = font; + } + + ctx.font = font; + var longest = 0; + helpers.each(arrayOfThings, function(thing) { + // Undefined strings and arrays should not be measured + if (thing !== undefined && thing !== null && helpers.isArray(thing) !== true) { + longest = helpers.measureText(ctx, data, gc, longest, thing); + } else if (helpers.isArray(thing)) { + // if it is an array lets measure each element + // to do maybe simplify this function a bit so we can do this more recursively? + helpers.each(thing, function(nestedThing) { + // Undefined strings and arrays should not be measured + if (nestedThing !== undefined && nestedThing !== null && !helpers.isArray(nestedThing)) { + longest = helpers.measureText(ctx, data, gc, longest, nestedThing); + } + }); + } + }); + + var gcLen = gc.length / 2; + if (gcLen > arrayOfThings.length) { + for (var i = 0; i < gcLen; i++) { + delete data[gc[i]]; + } + gc.splice(0, gcLen); + } + return longest; + }; + helpers.measureText = function(ctx, data, gc, longest, string) { + var textWidth = data[string]; + if (!textWidth) { + textWidth = data[string] = ctx.measureText(string).width; + gc.push(string); + } + if (textWidth > longest) { + longest = textWidth; + } + return longest; + }; + helpers.numberOfLabelLines = function(arrayOfThings) { + var numberOfLines = 1; + helpers.each(arrayOfThings, function(thing) { + if (helpers.isArray(thing)) { + if (thing.length > numberOfLines) { + numberOfLines = thing.length; + } + } + }); + return numberOfLines; + }; + + helpers.color = !color ? + function(value) { + console.error('Color.js not found!'); + return value; + } : + function(value) { + /* global CanvasGradient */ + if (value instanceof CanvasGradient) { + value = defaults.global.defaultColor; + } + + return color(value); + }; + + helpers.getHoverColor = function(colorValue) { + /* global CanvasPattern */ + return (colorValue instanceof CanvasPattern) ? + colorValue : + helpers.color(colorValue).saturate(0.5).darken(0.1).rgbString(); + }; +}; + +},{"2":2,"25":25,"45":45}],28:[function(require,module,exports){ +'use strict'; + +var helpers = require(45); + +/** + * Helper function to get relative position for an event + * @param {Event|IEvent} event - The event to get the position for + * @param {Chart} chart - The chart + * @returns {Point} the event position + */ +function getRelativePosition(e, chart) { + if (e.native) { + return { + x: e.x, + y: e.y + }; + } + + return helpers.getRelativePosition(e, chart); +} + +/** + * Helper function to traverse all of the visible elements in the chart + * @param chart {chart} the chart + * @param handler {Function} the callback to execute for each visible item + */ +function parseVisibleItems(chart, handler) { + var datasets = chart.data.datasets; + var meta, i, j, ilen, jlen; + + for (i = 0, ilen = datasets.length; i < ilen; ++i) { + if (!chart.isDatasetVisible(i)) { + continue; + } + + meta = chart.getDatasetMeta(i); + for (j = 0, jlen = meta.data.length; j < jlen; ++j) { + var element = meta.data[j]; + if (!element._view.skip) { + handler(element); + } + } + } +} + +/** + * Helper function to get the items that intersect the event position + * @param items {ChartElement[]} elements to filter + * @param position {Point} the point to be nearest to + * @return {ChartElement[]} the nearest items + */ +function getIntersectItems(chart, position) { + var elements = []; + + parseVisibleItems(chart, function(element) { + if (element.inRange(position.x, position.y)) { + elements.push(element); + } + }); + + return elements; +} + +/** + * Helper function to get the items nearest to the event position considering all visible items in teh chart + * @param chart {Chart} the chart to look at elements from + * @param position {Point} the point to be nearest to + * @param intersect {Boolean} if true, only consider items that intersect the position + * @param distanceMetric {Function} function to provide the distance between points + * @return {ChartElement[]} the nearest items + */ +function getNearestItems(chart, position, intersect, distanceMetric) { + var minDistance = Number.POSITIVE_INFINITY; + var nearestItems = []; + + parseVisibleItems(chart, function(element) { + if (intersect && !element.inRange(position.x, position.y)) { + return; + } + + var center = element.getCenterPoint(); + var distance = distanceMetric(position, center); + + if (distance < minDistance) { + nearestItems = [element]; + minDistance = distance; + } else if (distance === minDistance) { + // Can have multiple items at the same distance in which case we sort by size + nearestItems.push(element); + } + }); + + return nearestItems; +} + +/** + * Get a distance metric function for two points based on the + * axis mode setting + * @param {String} axis the axis mode. x|y|xy + */ +function getDistanceMetricForAxis(axis) { + var useX = axis.indexOf('x') !== -1; + var useY = axis.indexOf('y') !== -1; + + return function(pt1, pt2) { + var deltaX = useX ? Math.abs(pt1.x - pt2.x) : 0; + var deltaY = useY ? Math.abs(pt1.y - pt2.y) : 0; + return Math.sqrt(Math.pow(deltaX, 2) + Math.pow(deltaY, 2)); + }; +} + +function indexMode(chart, e, options) { + var position = getRelativePosition(e, chart); + // Default axis for index mode is 'x' to match old behaviour + options.axis = options.axis || 'x'; + var distanceMetric = getDistanceMetricForAxis(options.axis); + var items = options.intersect ? getIntersectItems(chart, position) : getNearestItems(chart, position, false, distanceMetric); + var elements = []; + + if (!items.length) { + return []; + } + + chart.data.datasets.forEach(function(dataset, datasetIndex) { + if (chart.isDatasetVisible(datasetIndex)) { + var meta = chart.getDatasetMeta(datasetIndex); + var element = meta.data[items[0]._index]; + + // don't count items that are skipped (null data) + if (element && !element._view.skip) { + elements.push(element); + } + } + }); + + return elements; +} + +/** + * @interface IInteractionOptions + */ +/** + * If true, only consider items that intersect the point + * @name IInterfaceOptions#boolean + * @type Boolean + */ + +/** + * Contains interaction related functions + * @namespace Chart.Interaction + */ +module.exports = { + // Helper function for different modes + modes: { + single: function(chart, e) { + var position = getRelativePosition(e, chart); + var elements = []; + + parseVisibleItems(chart, function(element) { + if (element.inRange(position.x, position.y)) { + elements.push(element); + return elements; + } + }); + + return elements.slice(0, 1); + }, + + /** + * @function Chart.Interaction.modes.label + * @deprecated since version 2.4.0 + * @todo remove at version 3 + * @private + */ + label: indexMode, + + /** + * Returns items at the same index. If the options.intersect parameter is true, we only return items if we intersect something + * If the options.intersect mode is false, we find the nearest item and return the items at the same index as that item + * @function Chart.Interaction.modes.index + * @since v2.4.0 + * @param chart {chart} the chart we are returning items from + * @param e {Event} the event we are find things at + * @param options {IInteractionOptions} options to use during interaction + * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned + */ + index: indexMode, + + /** + * Returns items in the same dataset. If the options.intersect parameter is true, we only return items if we intersect something + * If the options.intersect is false, we find the nearest item and return the items in that dataset + * @function Chart.Interaction.modes.dataset + * @param chart {chart} the chart we are returning items from + * @param e {Event} the event we are find things at + * @param options {IInteractionOptions} options to use during interaction + * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned + */ + dataset: function(chart, e, options) { + var position = getRelativePosition(e, chart); + options.axis = options.axis || 'xy'; + var distanceMetric = getDistanceMetricForAxis(options.axis); + var items = options.intersect ? getIntersectItems(chart, position) : getNearestItems(chart, position, false, distanceMetric); + + if (items.length > 0) { + items = chart.getDatasetMeta(items[0]._datasetIndex).data; + } + + return items; + }, + + /** + * @function Chart.Interaction.modes.x-axis + * @deprecated since version 2.4.0. Use index mode and intersect == true + * @todo remove at version 3 + * @private + */ + 'x-axis': function(chart, e) { + return indexMode(chart, e, {intersect: false}); + }, + + /** + * Point mode returns all elements that hit test based on the event position + * of the event + * @function Chart.Interaction.modes.intersect + * @param chart {chart} the chart we are returning items from + * @param e {Event} the event we are find things at + * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned + */ + point: function(chart, e) { + var position = getRelativePosition(e, chart); + return getIntersectItems(chart, position); + }, + + /** + * nearest mode returns the element closest to the point + * @function Chart.Interaction.modes.intersect + * @param chart {chart} the chart we are returning items from + * @param e {Event} the event we are find things at + * @param options {IInteractionOptions} options to use + * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned + */ + nearest: function(chart, e, options) { + var position = getRelativePosition(e, chart); + options.axis = options.axis || 'xy'; + var distanceMetric = getDistanceMetricForAxis(options.axis); + var nearestItems = getNearestItems(chart, position, options.intersect, distanceMetric); + + // We have multiple items at the same distance from the event. Now sort by smallest + if (nearestItems.length > 1) { + nearestItems.sort(function(a, b) { + var sizeA = a.getArea(); + var sizeB = b.getArea(); + var ret = sizeA - sizeB; + + if (ret === 0) { + // if equal sort by dataset index + ret = a._datasetIndex - b._datasetIndex; + } + + return ret; + }); + } + + // Return only 1 item + return nearestItems.slice(0, 1); + }, + + /** + * x mode returns the elements that hit-test at the current x coordinate + * @function Chart.Interaction.modes.x + * @param chart {chart} the chart we are returning items from + * @param e {Event} the event we are find things at + * @param options {IInteractionOptions} options to use + * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned + */ + x: function(chart, e, options) { + var position = getRelativePosition(e, chart); + var items = []; + var intersectsItem = false; + + parseVisibleItems(chart, function(element) { + if (element.inXRange(position.x)) { + items.push(element); + } + + if (element.inRange(position.x, position.y)) { + intersectsItem = true; + } + }); + + // If we want to trigger on an intersect and we don't have any items + // that intersect the position, return nothing + if (options.intersect && !intersectsItem) { + items = []; + } + return items; + }, + + /** + * y mode returns the elements that hit-test at the current y coordinate + * @function Chart.Interaction.modes.y + * @param chart {chart} the chart we are returning items from + * @param e {Event} the event we are find things at + * @param options {IInteractionOptions} options to use + * @return {Chart.Element[]} Array of elements that are under the point. If none are found, an empty array is returned + */ + y: function(chart, e, options) { + var position = getRelativePosition(e, chart); + var items = []; + var intersectsItem = false; + + parseVisibleItems(chart, function(element) { + if (element.inYRange(position.y)) { + items.push(element); + } + + if (element.inRange(position.x, position.y)) { + intersectsItem = true; + } + }); + + // If we want to trigger on an intersect and we don't have any items + // that intersect the position, return nothing + if (options.intersect && !intersectsItem) { + items = []; + } + return items; + } + } +}; + +},{"45":45}],29:[function(require,module,exports){ +'use strict'; + +var defaults = require(25); + +defaults._set('global', { + responsive: true, + responsiveAnimationDuration: 0, + maintainAspectRatio: true, + events: ['mousemove', 'mouseout', 'click', 'touchstart', 'touchmove'], + hover: { + onHover: null, + mode: 'nearest', + intersect: true, + animationDuration: 400 + }, + onClick: null, + defaultColor: 'rgba(0,0,0,0.1)', + defaultFontColor: '#666', + defaultFontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif", + defaultFontSize: 12, + defaultFontStyle: 'normal', + showLines: true, + + // Element defaults defined in element extensions + elements: {}, + + // Layout options such as padding + layout: { + padding: { + top: 0, + right: 0, + bottom: 0, + left: 0 + } + } +}); + +module.exports = function() { + + // Occupy the global variable of Chart, and create a simple base class + var Chart = function(item, config) { + this.construct(item, config); + return this; + }; + + Chart.Chart = Chart; + + return Chart; +}; + +},{"25":25}],30:[function(require,module,exports){ +'use strict'; + +var helpers = require(45); + +module.exports = function(Chart) { + + function filterByPosition(array, position) { + return helpers.where(array, function(v) { + return v.position === position; + }); + } + + function sortByWeight(array, reverse) { + array.forEach(function(v, i) { + v._tmpIndex_ = i; + return v; + }); + array.sort(function(a, b) { + var v0 = reverse ? b : a; + var v1 = reverse ? a : b; + return v0.weight === v1.weight ? + v0._tmpIndex_ - v1._tmpIndex_ : + v0.weight - v1.weight; + }); + array.forEach(function(v) { + delete v._tmpIndex_; + }); + } + + /** + * @interface ILayoutItem + * @prop {String} position - The position of the item in the chart layout. Possible values are + * 'left', 'top', 'right', 'bottom', and 'chartArea' + * @prop {Number} weight - The weight used to sort the item. Higher weights are further away from the chart area + * @prop {Boolean} fullWidth - if true, and the item is horizontal, then push vertical boxes down + * @prop {Function} isHorizontal - returns true if the layout item is horizontal (ie. top or bottom) + * @prop {Function} update - Takes two parameters: width and height. Returns size of item + * @prop {Function} getPadding - Returns an object with padding on the edges + * @prop {Number} width - Width of item. Must be valid after update() + * @prop {Number} height - Height of item. Must be valid after update() + * @prop {Number} left - Left edge of the item. Set by layout system and cannot be used in update + * @prop {Number} top - Top edge of the item. Set by layout system and cannot be used in update + * @prop {Number} right - Right edge of the item. Set by layout system and cannot be used in update + * @prop {Number} bottom - Bottom edge of the item. Set by layout system and cannot be used in update + */ + + // The layout service is very self explanatory. It's responsible for the layout within a chart. + // Scales, Legends and Plugins all rely on the layout service and can easily register to be placed anywhere they need + // It is this service's responsibility of carrying out that layout. + Chart.layoutService = { + defaults: {}, + + /** + * Register a box to a chart. + * A box is simply a reference to an object that requires layout. eg. Scales, Legend, Title. + * @param {Chart} chart - the chart to use + * @param {ILayoutItem} item - the item to add to be layed out + */ + addBox: function(chart, item) { + if (!chart.boxes) { + chart.boxes = []; + } + + // initialize item with default values + item.fullWidth = item.fullWidth || false; + item.position = item.position || 'top'; + item.weight = item.weight || 0; + + chart.boxes.push(item); + }, + + /** + * Remove a layoutItem from a chart + * @param {Chart} chart - the chart to remove the box from + * @param {Object} layoutItem - the item to remove from the layout + */ + removeBox: function(chart, layoutItem) { + var index = chart.boxes ? chart.boxes.indexOf(layoutItem) : -1; + if (index !== -1) { + chart.boxes.splice(index, 1); + } + }, + + /** + * Sets (or updates) options on the given `item`. + * @param {Chart} chart - the chart in which the item lives (or will be added to) + * @param {Object} item - the item to configure with the given options + * @param {Object} options - the new item options. + */ + configure: function(chart, item, options) { + var props = ['fullWidth', 'position', 'weight']; + var ilen = props.length; + var i = 0; + var prop; + + for (; i < ilen; ++i) { + prop = props[i]; + if (options.hasOwnProperty(prop)) { + item[prop] = options[prop]; + } + } + }, + + /** + * Fits boxes of the given chart into the given size by having each box measure itself + * then running a fitting algorithm + * @param {Chart} chart - the chart + * @param {Number} width - the width to fit into + * @param {Number} height - the height to fit into + */ + update: function(chart, width, height) { + if (!chart) { + return; + } + + var layoutOptions = chart.options.layout || {}; + var padding = helpers.options.toPadding(layoutOptions.padding); + var leftPadding = padding.left; + var rightPadding = padding.right; + var topPadding = padding.top; + var bottomPadding = padding.bottom; + + var leftBoxes = filterByPosition(chart.boxes, 'left'); + var rightBoxes = filterByPosition(chart.boxes, 'right'); + var topBoxes = filterByPosition(chart.boxes, 'top'); + var bottomBoxes = filterByPosition(chart.boxes, 'bottom'); + var chartAreaBoxes = filterByPosition(chart.boxes, 'chartArea'); + + // Sort boxes by weight. A higher weight is further away from the chart area + sortByWeight(leftBoxes, true); + sortByWeight(rightBoxes, false); + sortByWeight(topBoxes, true); + sortByWeight(bottomBoxes, false); + + // Essentially we now have any number of boxes on each of the 4 sides. + // Our canvas looks like the following. + // The areas L1 and L2 are the left axes. R1 is the right axis, T1 is the top axis and + // B1 is the bottom axis + // There are also 4 quadrant-like locations (left to right instead of clockwise) reserved for chart overlays + // These locations are single-box locations only, when trying to register a chartArea location that is already taken, + // an error will be thrown. + // + // |----------------------------------------------------| + // | T1 (Full Width) | + // |----------------------------------------------------| + // | | | T2 | | + // | |----|-------------------------------------|----| + // | | | C1 | | C2 | | + // | | |----| |----| | + // | | | | | + // | L1 | L2 | ChartArea (C0) | R1 | + // | | | | | + // | | |----| |----| | + // | | | C3 | | C4 | | + // | |----|-------------------------------------|----| + // | | | B1 | | + // |----------------------------------------------------| + // | B2 (Full Width) | + // |----------------------------------------------------| + // + // What we do to find the best sizing, we do the following + // 1. Determine the minimum size of the chart area. + // 2. Split the remaining width equally between each vertical axis + // 3. Split the remaining height equally between each horizontal axis + // 4. Give each layout the maximum size it can be. The layout will return it's minimum size + // 5. Adjust the sizes of each axis based on it's minimum reported size. + // 6. Refit each axis + // 7. Position each axis in the final location + // 8. Tell the chart the final location of the chart area + // 9. Tell any axes that overlay the chart area the positions of the chart area + + // Step 1 + var chartWidth = width - leftPadding - rightPadding; + var chartHeight = height - topPadding - bottomPadding; + var chartAreaWidth = chartWidth / 2; // min 50% + var chartAreaHeight = chartHeight / 2; // min 50% + + // Step 2 + var verticalBoxWidth = (width - chartAreaWidth) / (leftBoxes.length + rightBoxes.length); + + // Step 3 + var horizontalBoxHeight = (height - chartAreaHeight) / (topBoxes.length + bottomBoxes.length); + + // Step 4 + var maxChartAreaWidth = chartWidth; + var maxChartAreaHeight = chartHeight; + var minBoxSizes = []; + + function getMinimumBoxSize(box) { + var minSize; + var isHorizontal = box.isHorizontal(); + + if (isHorizontal) { + minSize = box.update(box.fullWidth ? chartWidth : maxChartAreaWidth, horizontalBoxHeight); + maxChartAreaHeight -= minSize.height; + } else { + minSize = box.update(verticalBoxWidth, chartAreaHeight); + maxChartAreaWidth -= minSize.width; + } + + minBoxSizes.push({ + horizontal: isHorizontal, + minSize: minSize, + box: box, + }); + } + + helpers.each(leftBoxes.concat(rightBoxes, topBoxes, bottomBoxes), getMinimumBoxSize); + + // If a horizontal box has padding, we move the left boxes over to avoid ugly charts (see issue #2478) + var maxHorizontalLeftPadding = 0; + var maxHorizontalRightPadding = 0; + var maxVerticalTopPadding = 0; + var maxVerticalBottomPadding = 0; + + helpers.each(topBoxes.concat(bottomBoxes), function(horizontalBox) { + if (horizontalBox.getPadding) { + var boxPadding = horizontalBox.getPadding(); + maxHorizontalLeftPadding = Math.max(maxHorizontalLeftPadding, boxPadding.left); + maxHorizontalRightPadding = Math.max(maxHorizontalRightPadding, boxPadding.right); + } + }); + + helpers.each(leftBoxes.concat(rightBoxes), function(verticalBox) { + if (verticalBox.getPadding) { + var boxPadding = verticalBox.getPadding(); + maxVerticalTopPadding = Math.max(maxVerticalTopPadding, boxPadding.top); + maxVerticalBottomPadding = Math.max(maxVerticalBottomPadding, boxPadding.bottom); + } + }); + + // At this point, maxChartAreaHeight and maxChartAreaWidth are the size the chart area could + // be if the axes are drawn at their minimum sizes. + // Steps 5 & 6 + var totalLeftBoxesWidth = leftPadding; + var totalRightBoxesWidth = rightPadding; + var totalTopBoxesHeight = topPadding; + var totalBottomBoxesHeight = bottomPadding; + + // Function to fit a box + function fitBox(box) { + var minBoxSize = helpers.findNextWhere(minBoxSizes, function(minBox) { + return minBox.box === box; + }); + + if (minBoxSize) { + if (box.isHorizontal()) { + var scaleMargin = { + left: Math.max(totalLeftBoxesWidth, maxHorizontalLeftPadding), + right: Math.max(totalRightBoxesWidth, maxHorizontalRightPadding), + top: 0, + bottom: 0 + }; + + // Don't use min size here because of label rotation. When the labels are rotated, their rotation highly depends + // on the margin. Sometimes they need to increase in size slightly + box.update(box.fullWidth ? chartWidth : maxChartAreaWidth, chartHeight / 2, scaleMargin); + } else { + box.update(minBoxSize.minSize.width, maxChartAreaHeight); + } + } + } + + // Update, and calculate the left and right margins for the horizontal boxes + helpers.each(leftBoxes.concat(rightBoxes), fitBox); + + helpers.each(leftBoxes, function(box) { + totalLeftBoxesWidth += box.width; + }); + + helpers.each(rightBoxes, function(box) { + totalRightBoxesWidth += box.width; + }); + + // Set the Left and Right margins for the horizontal boxes + helpers.each(topBoxes.concat(bottomBoxes), fitBox); + + // Figure out how much margin is on the top and bottom of the vertical boxes + helpers.each(topBoxes, function(box) { + totalTopBoxesHeight += box.height; + }); + + helpers.each(bottomBoxes, function(box) { + totalBottomBoxesHeight += box.height; + }); + + function finalFitVerticalBox(box) { + var minBoxSize = helpers.findNextWhere(minBoxSizes, function(minSize) { + return minSize.box === box; + }); + + var scaleMargin = { + left: 0, + right: 0, + top: totalTopBoxesHeight, + bottom: totalBottomBoxesHeight + }; + + if (minBoxSize) { + box.update(minBoxSize.minSize.width, maxChartAreaHeight, scaleMargin); + } + } + + // Let the left layout know the final margin + helpers.each(leftBoxes.concat(rightBoxes), finalFitVerticalBox); + + // Recalculate because the size of each layout might have changed slightly due to the margins (label rotation for instance) + totalLeftBoxesWidth = leftPadding; + totalRightBoxesWidth = rightPadding; + totalTopBoxesHeight = topPadding; + totalBottomBoxesHeight = bottomPadding; + + helpers.each(leftBoxes, function(box) { + totalLeftBoxesWidth += box.width; + }); + + helpers.each(rightBoxes, function(box) { + totalRightBoxesWidth += box.width; + }); + + helpers.each(topBoxes, function(box) { + totalTopBoxesHeight += box.height; + }); + helpers.each(bottomBoxes, function(box) { + totalBottomBoxesHeight += box.height; + }); + + // We may be adding some padding to account for rotated x axis labels + var leftPaddingAddition = Math.max(maxHorizontalLeftPadding - totalLeftBoxesWidth, 0); + totalLeftBoxesWidth += leftPaddingAddition; + totalRightBoxesWidth += Math.max(maxHorizontalRightPadding - totalRightBoxesWidth, 0); + + var topPaddingAddition = Math.max(maxVerticalTopPadding - totalTopBoxesHeight, 0); + totalTopBoxesHeight += topPaddingAddition; + totalBottomBoxesHeight += Math.max(maxVerticalBottomPadding - totalBottomBoxesHeight, 0); + + // Figure out if our chart area changed. This would occur if the dataset layout label rotation + // changed due to the application of the margins in step 6. Since we can only get bigger, this is safe to do + // without calling `fit` again + var newMaxChartAreaHeight = height - totalTopBoxesHeight - totalBottomBoxesHeight; + var newMaxChartAreaWidth = width - totalLeftBoxesWidth - totalRightBoxesWidth; + + if (newMaxChartAreaWidth !== maxChartAreaWidth || newMaxChartAreaHeight !== maxChartAreaHeight) { + helpers.each(leftBoxes, function(box) { + box.height = newMaxChartAreaHeight; + }); + + helpers.each(rightBoxes, function(box) { + box.height = newMaxChartAreaHeight; + }); + + helpers.each(topBoxes, function(box) { + if (!box.fullWidth) { + box.width = newMaxChartAreaWidth; + } + }); + + helpers.each(bottomBoxes, function(box) { + if (!box.fullWidth) { + box.width = newMaxChartAreaWidth; + } + }); + + maxChartAreaHeight = newMaxChartAreaHeight; + maxChartAreaWidth = newMaxChartAreaWidth; + } + + // Step 7 - Position the boxes + var left = leftPadding + leftPaddingAddition; + var top = topPadding + topPaddingAddition; + + function placeBox(box) { + if (box.isHorizontal()) { + box.left = box.fullWidth ? leftPadding : totalLeftBoxesWidth; + box.right = box.fullWidth ? width - rightPadding : totalLeftBoxesWidth + maxChartAreaWidth; + box.top = top; + box.bottom = top + box.height; + + // Move to next point + top = box.bottom; + + } else { + + box.left = left; + box.right = left + box.width; + box.top = totalTopBoxesHeight; + box.bottom = totalTopBoxesHeight + maxChartAreaHeight; + + // Move to next point + left = box.right; + } + } + + helpers.each(leftBoxes.concat(topBoxes), placeBox); + + // Account for chart width and height + left += maxChartAreaWidth; + top += maxChartAreaHeight; + + helpers.each(rightBoxes, placeBox); + helpers.each(bottomBoxes, placeBox); + + // Step 8 + chart.chartArea = { + left: totalLeftBoxesWidth, + top: totalTopBoxesHeight, + right: totalLeftBoxesWidth + maxChartAreaWidth, + bottom: totalTopBoxesHeight + maxChartAreaHeight + }; + + // Step 9 + helpers.each(chartAreaBoxes, function(box) { + box.left = chart.chartArea.left; + box.top = chart.chartArea.top; + box.right = chart.chartArea.right; + box.bottom = chart.chartArea.bottom; + + box.update(maxChartAreaWidth, maxChartAreaHeight); + }); + } + }; +}; + +},{"45":45}],31:[function(require,module,exports){ +'use strict'; + +var defaults = require(25); +var Element = require(26); +var helpers = require(45); + +defaults._set('global', { + plugins: {} +}); + +module.exports = function(Chart) { + + /** + * The plugin service singleton + * @namespace Chart.plugins + * @since 2.1.0 + */ + Chart.plugins = { + /** + * Globally registered plugins. + * @private + */ + _plugins: [], + + /** + * This identifier is used to invalidate the descriptors cache attached to each chart + * when a global plugin is registered or unregistered. In this case, the cache ID is + * incremented and descriptors are regenerated during following API calls. + * @private + */ + _cacheId: 0, + + /** + * Registers the given plugin(s) if not already registered. + * @param {Array|Object} plugins plugin instance(s). + */ + register: function(plugins) { + var p = this._plugins; + ([]).concat(plugins).forEach(function(plugin) { + if (p.indexOf(plugin) === -1) { + p.push(plugin); + } + }); + + this._cacheId++; + }, + + /** + * Unregisters the given plugin(s) only if registered. + * @param {Array|Object} plugins plugin instance(s). + */ + unregister: function(plugins) { + var p = this._plugins; + ([]).concat(plugins).forEach(function(plugin) { + var idx = p.indexOf(plugin); + if (idx !== -1) { + p.splice(idx, 1); + } + }); + + this._cacheId++; + }, + + /** + * Remove all registered plugins. + * @since 2.1.5 + */ + clear: function() { + this._plugins = []; + this._cacheId++; + }, + + /** + * Returns the number of registered plugins? + * @returns {Number} + * @since 2.1.5 + */ + count: function() { + return this._plugins.length; + }, + + /** + * Returns all registered plugin instances. + * @returns {Array} array of plugin objects. + * @since 2.1.5 + */ + getAll: function() { + return this._plugins; + }, + + /** + * Calls enabled plugins for `chart` on the specified hook and with the given args. + * This method immediately returns as soon as a plugin explicitly returns false. The + * returned value can be used, for instance, to interrupt the current action. + * @param {Object} chart - The chart instance for which plugins should be called. + * @param {String} hook - The name of the plugin method to call (e.g. 'beforeUpdate'). + * @param {Array} [args] - Extra arguments to apply to the hook call. + * @returns {Boolean} false if any of the plugins return false, else returns true. + */ + notify: function(chart, hook, args) { + var descriptors = this.descriptors(chart); + var ilen = descriptors.length; + var i, descriptor, plugin, params, method; + + for (i = 0; i < ilen; ++i) { + descriptor = descriptors[i]; + plugin = descriptor.plugin; + method = plugin[hook]; + if (typeof method === 'function') { + params = [chart].concat(args || []); + params.push(descriptor.options); + if (method.apply(plugin, params) === false) { + return false; + } + } + } + + return true; + }, + + /** + * Returns descriptors of enabled plugins for the given chart. + * @returns {Array} [{ plugin, options }] + * @private + */ + descriptors: function(chart) { + var cache = chart._plugins || (chart._plugins = {}); + if (cache.id === this._cacheId) { + return cache.descriptors; + } + + var plugins = []; + var descriptors = []; + var config = (chart && chart.config) || {}; + var options = (config.options && config.options.plugins) || {}; + + this._plugins.concat(config.plugins || []).forEach(function(plugin) { + var idx = plugins.indexOf(plugin); + if (idx !== -1) { + return; + } + + var id = plugin.id; + var opts = options[id]; + if (opts === false) { + return; + } + + if (opts === true) { + opts = helpers.clone(defaults.global.plugins[id]); + } + + plugins.push(plugin); + descriptors.push({ + plugin: plugin, + options: opts || {} + }); + }); + + cache.descriptors = descriptors; + cache.id = this._cacheId; + return descriptors; + } + }; + + /** + * Plugin extension hooks. + * @interface IPlugin + * @since 2.1.0 + */ + /** + * @method IPlugin#beforeInit + * @desc Called before initializing `chart`. + * @param {Chart.Controller} chart - The chart instance. + * @param {Object} options - The plugin options. + */ + /** + * @method IPlugin#afterInit + * @desc Called after `chart` has been initialized and before the first update. + * @param {Chart.Controller} chart - The chart instance. + * @param {Object} options - The plugin options. + */ + /** + * @method IPlugin#beforeUpdate + * @desc Called before updating `chart`. If any plugin returns `false`, the update + * is cancelled (and thus subsequent render(s)) until another `update` is triggered. + * @param {Chart.Controller} chart - The chart instance. + * @param {Object} options - The plugin options. + * @returns {Boolean} `false` to cancel the chart update. + */ + /** + * @method IPlugin#afterUpdate + * @desc Called after `chart` has been updated and before rendering. Note that this + * hook will not be called if the chart update has been previously cancelled. + * @param {Chart.Controller} chart - The chart instance. + * @param {Object} options - The plugin options. + */ + /** + * @method IPlugin#beforeDatasetsUpdate + * @desc Called before updating the `chart` datasets. If any plugin returns `false`, + * the datasets update is cancelled until another `update` is triggered. + * @param {Chart.Controller} chart - The chart instance. + * @param {Object} options - The plugin options. + * @returns {Boolean} false to cancel the datasets update. + * @since version 2.1.5 + */ + /** + * @method IPlugin#afterDatasetsUpdate + * @desc Called after the `chart` datasets have been updated. Note that this hook + * will not be called if the datasets update has been previously cancelled. + * @param {Chart.Controller} chart - The chart instance. + * @param {Object} options - The plugin options. + * @since version 2.1.5 + */ + /** + * @method IPlugin#beforeDatasetUpdate + * @desc Called before updating the `chart` dataset at the given `args.index`. If any plugin + * returns `false`, the datasets update is cancelled until another `update` is triggered. + * @param {Chart} chart - The chart instance. + * @param {Object} args - The call arguments. + * @param {Number} args.index - The dataset index. + * @param {Object} args.meta - The dataset metadata. + * @param {Object} options - The plugin options. + * @returns {Boolean} `false` to cancel the chart datasets drawing. + */ + /** + * @method IPlugin#afterDatasetUpdate + * @desc Called after the `chart` datasets at the given `args.index` has been updated. Note + * that this hook will not be called if the datasets update has been previously cancelled. + * @param {Chart} chart - The chart instance. + * @param {Object} args - The call arguments. + * @param {Number} args.index - The dataset index. + * @param {Object} args.meta - The dataset metadata. + * @param {Object} options - The plugin options. + */ + /** + * @method IPlugin#beforeLayout + * @desc Called before laying out `chart`. If any plugin returns `false`, + * the layout update is cancelled until another `update` is triggered. + * @param {Chart.Controller} chart - The chart instance. + * @param {Object} options - The plugin options. + * @returns {Boolean} `false` to cancel the chart layout. + */ + /** + * @method IPlugin#afterLayout + * @desc Called after the `chart` has been layed out. Note that this hook will not + * be called if the layout update has been previously cancelled. + * @param {Chart.Controller} chart - The chart instance. + * @param {Object} options - The plugin options. + */ + /** + * @method IPlugin#beforeRender + * @desc Called before rendering `chart`. If any plugin returns `false`, + * the rendering is cancelled until another `render` is triggered. + * @param {Chart.Controller} chart - The chart instance. + * @param {Object} options - The plugin options. + * @returns {Boolean} `false` to cancel the chart rendering. + */ + /** + * @method IPlugin#afterRender + * @desc Called after the `chart` has been fully rendered (and animation completed). Note + * that this hook will not be called if the rendering has been previously cancelled. + * @param {Chart.Controller} chart - The chart instance. + * @param {Object} options - The plugin options. + */ + /** + * @method IPlugin#beforeDraw + * @desc Called before drawing `chart` at every animation frame specified by the given + * easing value. If any plugin returns `false`, the frame drawing is cancelled until + * another `render` is triggered. + * @param {Chart.Controller} chart - The chart instance. + * @param {Number} easingValue - The current animation value, between 0.0 and 1.0. + * @param {Object} options - The plugin options. + * @returns {Boolean} `false` to cancel the chart drawing. + */ + /** + * @method IPlugin#afterDraw + * @desc Called after the `chart` has been drawn for the specific easing value. Note + * that this hook will not be called if the drawing has been previously cancelled. + * @param {Chart.Controller} chart - The chart instance. + * @param {Number} easingValue - The current animation value, between 0.0 and 1.0. + * @param {Object} options - The plugin options. + */ + /** + * @method IPlugin#beforeDatasetsDraw + * @desc Called before drawing the `chart` datasets. If any plugin returns `false`, + * the datasets drawing is cancelled until another `render` is triggered. + * @param {Chart.Controller} chart - The chart instance. + * @param {Number} easingValue - The current animation value, between 0.0 and 1.0. + * @param {Object} options - The plugin options. + * @returns {Boolean} `false` to cancel the chart datasets drawing. + */ + /** + * @method IPlugin#afterDatasetsDraw + * @desc Called after the `chart` datasets have been drawn. Note that this hook + * will not be called if the datasets drawing has been previously cancelled. + * @param {Chart.Controller} chart - The chart instance. + * @param {Number} easingValue - The current animation value, between 0.0 and 1.0. + * @param {Object} options - The plugin options. + */ + /** + * @method IPlugin#beforeDatasetDraw + * @desc Called before drawing the `chart` dataset at the given `args.index` (datasets + * are drawn in the reverse order). If any plugin returns `false`, the datasets drawing + * is cancelled until another `render` is triggered. + * @param {Chart} chart - The chart instance. + * @param {Object} args - The call arguments. + * @param {Number} args.index - The dataset index. + * @param {Object} args.meta - The dataset metadata. + * @param {Number} args.easingValue - The current animation value, between 0.0 and 1.0. + * @param {Object} options - The plugin options. + * @returns {Boolean} `false` to cancel the chart datasets drawing. + */ + /** + * @method IPlugin#afterDatasetDraw + * @desc Called after the `chart` datasets at the given `args.index` have been drawn + * (datasets are drawn in the reverse order). Note that this hook will not be called + * if the datasets drawing has been previously cancelled. + * @param {Chart} chart - The chart instance. + * @param {Object} args - The call arguments. + * @param {Number} args.index - The dataset index. + * @param {Object} args.meta - The dataset metadata. + * @param {Number} args.easingValue - The current animation value, between 0.0 and 1.0. + * @param {Object} options - The plugin options. + */ + /** + * @method IPlugin#beforeTooltipDraw + * @desc Called before drawing the `tooltip`. If any plugin returns `false`, + * the tooltip drawing is cancelled until another `render` is triggered. + * @param {Chart} chart - The chart instance. + * @param {Object} args - The call arguments. + * @param {Object} args.tooltip - The tooltip. + * @param {Number} args.easingValue - The current animation value, between 0.0 and 1.0. + * @param {Object} options - The plugin options. + * @returns {Boolean} `false` to cancel the chart tooltip drawing. + */ + /** + * @method IPlugin#afterTooltipDraw + * @desc Called after drawing the `tooltip`. Note that this hook will not + * be called if the tooltip drawing has been previously cancelled. + * @param {Chart} chart - The chart instance. + * @param {Object} args - The call arguments. + * @param {Object} args.tooltip - The tooltip. + * @param {Number} args.easingValue - The current animation value, between 0.0 and 1.0. + * @param {Object} options - The plugin options. + */ + /** + * @method IPlugin#beforeEvent + * @desc Called before processing the specified `event`. If any plugin returns `false`, + * the event will be discarded. + * @param {Chart.Controller} chart - The chart instance. + * @param {IEvent} event - The event object. + * @param {Object} options - The plugin options. + */ + /** + * @method IPlugin#afterEvent + * @desc Called after the `event` has been consumed. Note that this hook + * will not be called if the `event` has been previously discarded. + * @param {Chart.Controller} chart - The chart instance. + * @param {IEvent} event - The event object. + * @param {Object} options - The plugin options. + */ + /** + * @method IPlugin#resize + * @desc Called after the chart as been resized. + * @param {Chart.Controller} chart - The chart instance. + * @param {Number} size - The new canvas display size (eq. canvas.style width & height). + * @param {Object} options - The plugin options. + */ + /** + * @method IPlugin#destroy + * @desc Called after the chart as been destroyed. + * @param {Chart.Controller} chart - The chart instance. + * @param {Object} options - The plugin options. + */ + + /** + * Provided for backward compatibility, use Chart.plugins instead + * @namespace Chart.pluginService + * @deprecated since version 2.1.5 + * @todo remove at version 3 + * @private + */ + Chart.pluginService = Chart.plugins; + + /** + * Provided for backward compatibility, inheriting from Chart.PlugingBase has no + * effect, instead simply create/register plugins via plain JavaScript objects. + * @interface Chart.PluginBase + * @deprecated since version 2.5.0 + * @todo remove at version 3 + * @private + */ + Chart.PluginBase = Element.extend({}); +}; + +},{"25":25,"26":26,"45":45}],32:[function(require,module,exports){ +'use strict'; + +var defaults = require(25); +var Element = require(26); +var helpers = require(45); +var Ticks = require(34); + +defaults._set('scale', { + display: true, + position: 'left', + offset: false, + + // grid line settings + gridLines: { + display: true, + color: 'rgba(0, 0, 0, 0.1)', + lineWidth: 1, + drawBorder: true, + drawOnChartArea: true, + drawTicks: true, + tickMarkLength: 10, + zeroLineWidth: 1, + zeroLineColor: 'rgba(0,0,0,0.25)', + zeroLineBorderDash: [], + zeroLineBorderDashOffset: 0.0, + offsetGridLines: false, + borderDash: [], + borderDashOffset: 0.0 + }, + + // scale label + scaleLabel: { + // display property + display: false, + + // actual label + labelString: '', + + // line height + lineHeight: 1.2, + + // top/bottom padding + padding: { + top: 4, + bottom: 4 + } + }, + + // label settings + ticks: { + beginAtZero: false, + minRotation: 0, + maxRotation: 50, + mirror: false, + padding: 0, + reverse: false, + display: true, + autoSkip: true, + autoSkipPadding: 0, + labelOffset: 0, + // We pass through arrays to be rendered as multiline labels, we convert Others to strings here. + callback: Ticks.formatters.values, + minor: {}, + major: {} + } +}); + +function labelsFromTicks(ticks) { + var labels = []; + var i, ilen; + + for (i = 0, ilen = ticks.length; i < ilen; ++i) { + labels.push(ticks[i].label); + } + + return labels; +} + +function getLineValue(scale, index, offsetGridLines) { + var lineValue = scale.getPixelForTick(index); + + if (offsetGridLines) { + if (index === 0) { + lineValue -= (scale.getPixelForTick(1) - lineValue) / 2; + } else { + lineValue -= (lineValue - scale.getPixelForTick(index - 1)) / 2; + } + } + return lineValue; +} + +module.exports = function(Chart) { + + function computeTextSize(context, tick, font) { + return helpers.isArray(tick) ? + helpers.longestText(context, font, tick) : + context.measureText(tick).width; + } + + function parseFontOptions(options) { + var valueOrDefault = helpers.valueOrDefault; + var globalDefaults = defaults.global; + var size = valueOrDefault(options.fontSize, globalDefaults.defaultFontSize); + var style = valueOrDefault(options.fontStyle, globalDefaults.defaultFontStyle); + var family = valueOrDefault(options.fontFamily, globalDefaults.defaultFontFamily); + + return { + size: size, + style: style, + family: family, + font: helpers.fontString(size, style, family) + }; + } + + function parseLineHeight(options) { + return helpers.options.toLineHeight( + helpers.valueOrDefault(options.lineHeight, 1.2), + helpers.valueOrDefault(options.fontSize, defaults.global.defaultFontSize)); + } + + Chart.Scale = Element.extend({ + /** + * Get the padding needed for the scale + * @method getPadding + * @private + * @returns {Padding} the necessary padding + */ + getPadding: function() { + var me = this; + return { + left: me.paddingLeft || 0, + top: me.paddingTop || 0, + right: me.paddingRight || 0, + bottom: me.paddingBottom || 0 + }; + }, + + /** + * Returns the scale tick objects ({label, major}) + * @since 2.7 + */ + getTicks: function() { + return this._ticks; + }, + + // These methods are ordered by lifecyle. Utilities then follow. + // Any function defined here is inherited by all scale types. + // Any function can be extended by the scale type + + mergeTicksOptions: function() { + var ticks = this.options.ticks; + if (ticks.minor === false) { + ticks.minor = { + display: false + }; + } + if (ticks.major === false) { + ticks.major = { + display: false + }; + } + for (var key in ticks) { + if (key !== 'major' && key !== 'minor') { + if (typeof ticks.minor[key] === 'undefined') { + ticks.minor[key] = ticks[key]; + } + if (typeof ticks.major[key] === 'undefined') { + ticks.major[key] = ticks[key]; + } + } + } + }, + beforeUpdate: function() { + helpers.callback(this.options.beforeUpdate, [this]); + }, + update: function(maxWidth, maxHeight, margins) { + var me = this; + var i, ilen, labels, label, ticks, tick; + + // Update Lifecycle - Probably don't want to ever extend or overwrite this function ;) + me.beforeUpdate(); + + // Absorb the master measurements + me.maxWidth = maxWidth; + me.maxHeight = maxHeight; + me.margins = helpers.extend({ + left: 0, + right: 0, + top: 0, + bottom: 0 + }, margins); + me.longestTextCache = me.longestTextCache || {}; + + // Dimensions + me.beforeSetDimensions(); + me.setDimensions(); + me.afterSetDimensions(); + + // Data min/max + me.beforeDataLimits(); + me.determineDataLimits(); + me.afterDataLimits(); + + // Ticks - `this.ticks` is now DEPRECATED! + // Internal ticks are now stored as objects in the PRIVATE `this._ticks` member + // and must not be accessed directly from outside this class. `this.ticks` being + // around for long time and not marked as private, we can't change its structure + // without unexpected breaking changes. If you need to access the scale ticks, + // use scale.getTicks() instead. + + me.beforeBuildTicks(); + + // New implementations should return an array of objects but for BACKWARD COMPAT, + // we still support no return (`this.ticks` internally set by calling this method). + ticks = me.buildTicks() || []; + + me.afterBuildTicks(); + + me.beforeTickToLabelConversion(); + + // New implementations should return the formatted tick labels but for BACKWARD + // COMPAT, we still support no return (`this.ticks` internally changed by calling + // this method and supposed to contain only string values). + labels = me.convertTicksToLabels(ticks) || me.ticks; + + me.afterTickToLabelConversion(); + + me.ticks = labels; // BACKWARD COMPATIBILITY + + // IMPORTANT: from this point, we consider that `this.ticks` will NEVER change! + + // BACKWARD COMPAT: synchronize `_ticks` with labels (so potentially `this.ticks`) + for (i = 0, ilen = labels.length; i < ilen; ++i) { + label = labels[i]; + tick = ticks[i]; + if (!tick) { + ticks.push(tick = { + label: label, + major: false + }); + } else { + tick.label = label; + } + } + + me._ticks = ticks; + + // Tick Rotation + me.beforeCalculateTickRotation(); + me.calculateTickRotation(); + me.afterCalculateTickRotation(); + // Fit + me.beforeFit(); + me.fit(); + me.afterFit(); + // + me.afterUpdate(); + + return me.minSize; + + }, + afterUpdate: function() { + helpers.callback(this.options.afterUpdate, [this]); + }, + + // + + beforeSetDimensions: function() { + helpers.callback(this.options.beforeSetDimensions, [this]); + }, + setDimensions: function() { + var me = this; + // Set the unconstrained dimension before label rotation + if (me.isHorizontal()) { + // Reset position before calculating rotation + me.width = me.maxWidth; + me.left = 0; + me.right = me.width; + } else { + me.height = me.maxHeight; + + // Reset position before calculating rotation + me.top = 0; + me.bottom = me.height; + } + + // Reset padding + me.paddingLeft = 0; + me.paddingTop = 0; + me.paddingRight = 0; + me.paddingBottom = 0; + }, + afterSetDimensions: function() { + helpers.callback(this.options.afterSetDimensions, [this]); + }, + + // Data limits + beforeDataLimits: function() { + helpers.callback(this.options.beforeDataLimits, [this]); + }, + determineDataLimits: helpers.noop, + afterDataLimits: function() { + helpers.callback(this.options.afterDataLimits, [this]); + }, + + // + beforeBuildTicks: function() { + helpers.callback(this.options.beforeBuildTicks, [this]); + }, + buildTicks: helpers.noop, + afterBuildTicks: function() { + helpers.callback(this.options.afterBuildTicks, [this]); + }, + + beforeTickToLabelConversion: function() { + helpers.callback(this.options.beforeTickToLabelConversion, [this]); + }, + convertTicksToLabels: function() { + var me = this; + // Convert ticks to strings + var tickOpts = me.options.ticks; + me.ticks = me.ticks.map(tickOpts.userCallback || tickOpts.callback, this); + }, + afterTickToLabelConversion: function() { + helpers.callback(this.options.afterTickToLabelConversion, [this]); + }, + + // + + beforeCalculateTickRotation: function() { + helpers.callback(this.options.beforeCalculateTickRotation, [this]); + }, + calculateTickRotation: function() { + var me = this; + var context = me.ctx; + var tickOpts = me.options.ticks; + var labels = labelsFromTicks(me._ticks); + + // Get the width of each grid by calculating the difference + // between x offsets between 0 and 1. + var tickFont = parseFontOptions(tickOpts); + context.font = tickFont.font; + + var labelRotation = tickOpts.minRotation || 0; + + if (labels.length && me.options.display && me.isHorizontal()) { + var originalLabelWidth = helpers.longestText(context, tickFont.font, labels, me.longestTextCache); + var labelWidth = originalLabelWidth; + var cosRotation, sinRotation; + + // Allow 3 pixels x2 padding either side for label readability + var tickWidth = me.getPixelForTick(1) - me.getPixelForTick(0) - 6; + + // Max label rotation can be set or default to 90 - also act as a loop counter + while (labelWidth > tickWidth && labelRotation < tickOpts.maxRotation) { + var angleRadians = helpers.toRadians(labelRotation); + cosRotation = Math.cos(angleRadians); + sinRotation = Math.sin(angleRadians); + + if (sinRotation * originalLabelWidth > me.maxHeight) { + // go back one step + labelRotation--; + break; + } + + labelRotation++; + labelWidth = cosRotation * originalLabelWidth; + } + } + + me.labelRotation = labelRotation; + }, + afterCalculateTickRotation: function() { + helpers.callback(this.options.afterCalculateTickRotation, [this]); + }, + + // + + beforeFit: function() { + helpers.callback(this.options.beforeFit, [this]); + }, + fit: function() { + var me = this; + // Reset + var minSize = me.minSize = { + width: 0, + height: 0 + }; + + var labels = labelsFromTicks(me._ticks); + + var opts = me.options; + var tickOpts = opts.ticks; + var scaleLabelOpts = opts.scaleLabel; + var gridLineOpts = opts.gridLines; + var display = opts.display; + var isHorizontal = me.isHorizontal(); + + var tickFont = parseFontOptions(tickOpts); + var tickMarkLength = opts.gridLines.tickMarkLength; + + // Width + if (isHorizontal) { + // subtract the margins to line up with the chartArea if we are a full width scale + minSize.width = me.isFullWidth() ? me.maxWidth - me.margins.left - me.margins.right : me.maxWidth; + } else { + minSize.width = display && gridLineOpts.drawTicks ? tickMarkLength : 0; + } + + // height + if (isHorizontal) { + minSize.height = display && gridLineOpts.drawTicks ? tickMarkLength : 0; + } else { + minSize.height = me.maxHeight; // fill all the height + } + + // Are we showing a title for the scale? + if (scaleLabelOpts.display && display) { + var scaleLabelLineHeight = parseLineHeight(scaleLabelOpts); + var scaleLabelPadding = helpers.options.toPadding(scaleLabelOpts.padding); + var deltaHeight = scaleLabelLineHeight + scaleLabelPadding.height; + + if (isHorizontal) { + minSize.height += deltaHeight; + } else { + minSize.width += deltaHeight; + } + } + + // Don't bother fitting the ticks if we are not showing them + if (tickOpts.display && display) { + var largestTextWidth = helpers.longestText(me.ctx, tickFont.font, labels, me.longestTextCache); + var tallestLabelHeightInLines = helpers.numberOfLabelLines(labels); + var lineSpace = tickFont.size * 0.5; + var tickPadding = me.options.ticks.padding; + + if (isHorizontal) { + // A horizontal axis is more constrained by the height. + me.longestLabelWidth = largestTextWidth; + + var angleRadians = helpers.toRadians(me.labelRotation); + var cosRotation = Math.cos(angleRadians); + var sinRotation = Math.sin(angleRadians); + + // TODO - improve this calculation + var labelHeight = (sinRotation * largestTextWidth) + + (tickFont.size * tallestLabelHeightInLines) + + (lineSpace * (tallestLabelHeightInLines - 1)) + + lineSpace; // padding + + minSize.height = Math.min(me.maxHeight, minSize.height + labelHeight + tickPadding); + + me.ctx.font = tickFont.font; + var firstLabelWidth = computeTextSize(me.ctx, labels[0], tickFont.font); + var lastLabelWidth = computeTextSize(me.ctx, labels[labels.length - 1], tickFont.font); + + // Ensure that our ticks are always inside the canvas. When rotated, ticks are right aligned + // which means that the right padding is dominated by the font height + if (me.labelRotation !== 0) { + me.paddingLeft = opts.position === 'bottom' ? (cosRotation * firstLabelWidth) + 3 : (cosRotation * lineSpace) + 3; // add 3 px to move away from canvas edges + me.paddingRight = opts.position === 'bottom' ? (cosRotation * lineSpace) + 3 : (cosRotation * lastLabelWidth) + 3; + } else { + me.paddingLeft = firstLabelWidth / 2 + 3; // add 3 px to move away from canvas edges + me.paddingRight = lastLabelWidth / 2 + 3; + } + } else { + // A vertical axis is more constrained by the width. Labels are the + // dominant factor here, so get that length first and account for padding + if (tickOpts.mirror) { + largestTextWidth = 0; + } else { + // use lineSpace for consistency with horizontal axis + // tickPadding is not implemented for horizontal + largestTextWidth += tickPadding + lineSpace; + } + + minSize.width = Math.min(me.maxWidth, minSize.width + largestTextWidth); + + me.paddingTop = tickFont.size / 2; + me.paddingBottom = tickFont.size / 2; + } + } + + me.handleMargins(); + + me.width = minSize.width; + me.height = minSize.height; + }, + + /** + * Handle margins and padding interactions + * @private + */ + handleMargins: function() { + var me = this; + if (me.margins) { + me.paddingLeft = Math.max(me.paddingLeft - me.margins.left, 0); + me.paddingTop = Math.max(me.paddingTop - me.margins.top, 0); + me.paddingRight = Math.max(me.paddingRight - me.margins.right, 0); + me.paddingBottom = Math.max(me.paddingBottom - me.margins.bottom, 0); + } + }, + + afterFit: function() { + helpers.callback(this.options.afterFit, [this]); + }, + + // Shared Methods + isHorizontal: function() { + return this.options.position === 'top' || this.options.position === 'bottom'; + }, + isFullWidth: function() { + return (this.options.fullWidth); + }, + + // Get the correct value. NaN bad inputs, If the value type is object get the x or y based on whether we are horizontal or not + getRightValue: function(rawValue) { + // Null and undefined values first + if (helpers.isNullOrUndef(rawValue)) { + return NaN; + } + // isNaN(object) returns true, so make sure NaN is checking for a number; Discard Infinite values + if (typeof rawValue === 'number' && !isFinite(rawValue)) { + return NaN; + } + // If it is in fact an object, dive in one more level + if (rawValue) { + if (this.isHorizontal()) { + if (rawValue.x !== undefined) { + return this.getRightValue(rawValue.x); + } + } else if (rawValue.y !== undefined) { + return this.getRightValue(rawValue.y); + } + } + + // Value is good, return it + return rawValue; + }, + + /** + * Used to get the value to display in the tooltip for the data at the given index + * @param index + * @param datasetIndex + */ + getLabelForIndex: helpers.noop, + + /** + * Returns the location of the given data point. Value can either be an index or a numerical value + * The coordinate (0, 0) is at the upper-left corner of the canvas + * @param value + * @param index + * @param datasetIndex + */ + getPixelForValue: helpers.noop, + + /** + * Used to get the data value from a given pixel. This is the inverse of getPixelForValue + * The coordinate (0, 0) is at the upper-left corner of the canvas + * @param pixel + */ + getValueForPixel: helpers.noop, + + /** + * Returns the location of the tick at the given index + * The coordinate (0, 0) is at the upper-left corner of the canvas + */ + getPixelForTick: function(index) { + var me = this; + var offset = me.options.offset; + if (me.isHorizontal()) { + var innerWidth = me.width - (me.paddingLeft + me.paddingRight); + var tickWidth = innerWidth / Math.max((me._ticks.length - (offset ? 0 : 1)), 1); + var pixel = (tickWidth * index) + me.paddingLeft; + + if (offset) { + pixel += tickWidth / 2; + } + + var finalVal = me.left + Math.round(pixel); + finalVal += me.isFullWidth() ? me.margins.left : 0; + return finalVal; + } + var innerHeight = me.height - (me.paddingTop + me.paddingBottom); + return me.top + (index * (innerHeight / (me._ticks.length - 1))); + }, + + /** + * Utility for getting the pixel location of a percentage of scale + * The coordinate (0, 0) is at the upper-left corner of the canvas + */ + getPixelForDecimal: function(decimal) { + var me = this; + if (me.isHorizontal()) { + var innerWidth = me.width - (me.paddingLeft + me.paddingRight); + var valueOffset = (innerWidth * decimal) + me.paddingLeft; + + var finalVal = me.left + Math.round(valueOffset); + finalVal += me.isFullWidth() ? me.margins.left : 0; + return finalVal; + } + return me.top + (decimal * me.height); + }, + + /** + * Returns the pixel for the minimum chart value + * The coordinate (0, 0) is at the upper-left corner of the canvas + */ + getBasePixel: function() { + return this.getPixelForValue(this.getBaseValue()); + }, + + getBaseValue: function() { + var me = this; + var min = me.min; + var max = me.max; + + return me.beginAtZero ? 0 : + min < 0 && max < 0 ? max : + min > 0 && max > 0 ? min : + 0; + }, + + /** + * Returns a subset of ticks to be plotted to avoid overlapping labels. + * @private + */ + _autoSkip: function(ticks) { + var skipRatio; + var me = this; + var isHorizontal = me.isHorizontal(); + var optionTicks = me.options.ticks.minor; + var tickCount = ticks.length; + var labelRotationRadians = helpers.toRadians(me.labelRotation); + var cosRotation = Math.cos(labelRotationRadians); + var longestRotatedLabel = me.longestLabelWidth * cosRotation; + var result = []; + var i, tick, shouldSkip; + + // figure out the maximum number of gridlines to show + var maxTicks; + if (optionTicks.maxTicksLimit) { + maxTicks = optionTicks.maxTicksLimit; + } + + if (isHorizontal) { + skipRatio = false; + + if ((longestRotatedLabel + optionTicks.autoSkipPadding) * tickCount > (me.width - (me.paddingLeft + me.paddingRight))) { + skipRatio = 1 + Math.floor(((longestRotatedLabel + optionTicks.autoSkipPadding) * tickCount) / (me.width - (me.paddingLeft + me.paddingRight))); + } + + // if they defined a max number of optionTicks, + // increase skipRatio until that number is met + if (maxTicks && tickCount > maxTicks) { + skipRatio = Math.max(skipRatio, Math.floor(tickCount / maxTicks)); + } + } + + for (i = 0; i < tickCount; i++) { + tick = ticks[i]; + + // Since we always show the last tick,we need may need to hide the last shown one before + shouldSkip = (skipRatio > 1 && i % skipRatio > 0) || (i % skipRatio === 0 && i + skipRatio >= tickCount); + if (shouldSkip && i !== tickCount - 1) { + // leave tick in place but make sure it's not displayed (#4635) + delete tick.label; + } + result.push(tick); + } + return result; + }, + + // Actually draw the scale on the canvas + // @param {rectangle} chartArea : the area of the chart to draw full grid lines on + draw: function(chartArea) { + var me = this; + var options = me.options; + if (!options.display) { + return; + } + + var context = me.ctx; + var globalDefaults = defaults.global; + var optionTicks = options.ticks.minor; + var optionMajorTicks = options.ticks.major || optionTicks; + var gridLines = options.gridLines; + var scaleLabel = options.scaleLabel; + + var isRotated = me.labelRotation !== 0; + var isHorizontal = me.isHorizontal(); + + var ticks = optionTicks.autoSkip ? me._autoSkip(me.getTicks()) : me.getTicks(); + var tickFontColor = helpers.valueOrDefault(optionTicks.fontColor, globalDefaults.defaultFontColor); + var tickFont = parseFontOptions(optionTicks); + var majorTickFontColor = helpers.valueOrDefault(optionMajorTicks.fontColor, globalDefaults.defaultFontColor); + var majorTickFont = parseFontOptions(optionMajorTicks); + + var tl = gridLines.drawTicks ? gridLines.tickMarkLength : 0; + + var scaleLabelFontColor = helpers.valueOrDefault(scaleLabel.fontColor, globalDefaults.defaultFontColor); + var scaleLabelFont = parseFontOptions(scaleLabel); + var scaleLabelPadding = helpers.options.toPadding(scaleLabel.padding); + var labelRotationRadians = helpers.toRadians(me.labelRotation); + + var itemsToDraw = []; + + var xTickStart = options.position === 'right' ? me.left : me.right - tl; + var xTickEnd = options.position === 'right' ? me.left + tl : me.right; + var yTickStart = options.position === 'bottom' ? me.top : me.bottom - tl; + var yTickEnd = options.position === 'bottom' ? me.top + tl : me.bottom; + + helpers.each(ticks, function(tick, index) { + // autoskipper skipped this tick (#4635) + if (helpers.isNullOrUndef(tick.label)) { + return; + } + + var label = tick.label; + var lineWidth, lineColor, borderDash, borderDashOffset; + if (index === me.zeroLineIndex && options.offset === gridLines.offsetGridLines) { + // Draw the first index specially + lineWidth = gridLines.zeroLineWidth; + lineColor = gridLines.zeroLineColor; + borderDash = gridLines.zeroLineBorderDash; + borderDashOffset = gridLines.zeroLineBorderDashOffset; + } else { + lineWidth = helpers.valueAtIndexOrDefault(gridLines.lineWidth, index); + lineColor = helpers.valueAtIndexOrDefault(gridLines.color, index); + borderDash = helpers.valueOrDefault(gridLines.borderDash, globalDefaults.borderDash); + borderDashOffset = helpers.valueOrDefault(gridLines.borderDashOffset, globalDefaults.borderDashOffset); + } + + // Common properties + var tx1, ty1, tx2, ty2, x1, y1, x2, y2, labelX, labelY; + var textAlign = 'middle'; + var textBaseline = 'middle'; + var tickPadding = optionTicks.padding; + + if (isHorizontal) { + var labelYOffset = tl + tickPadding; + + if (options.position === 'bottom') { + // bottom + textBaseline = !isRotated ? 'top' : 'middle'; + textAlign = !isRotated ? 'center' : 'right'; + labelY = me.top + labelYOffset; + } else { + // top + textBaseline = !isRotated ? 'bottom' : 'middle'; + textAlign = !isRotated ? 'center' : 'left'; + labelY = me.bottom - labelYOffset; + } + + var xLineValue = getLineValue(me, index, gridLines.offsetGridLines && ticks.length > 1); + if (xLineValue < me.left) { + lineColor = 'rgba(0,0,0,0)'; + } + xLineValue += helpers.aliasPixel(lineWidth); + + labelX = me.getPixelForTick(index) + optionTicks.labelOffset; // x values for optionTicks (need to consider offsetLabel option) + + tx1 = tx2 = x1 = x2 = xLineValue; + ty1 = yTickStart; + ty2 = yTickEnd; + y1 = chartArea.top; + y2 = chartArea.bottom; + } else { + var isLeft = options.position === 'left'; + var labelXOffset; + + if (optionTicks.mirror) { + textAlign = isLeft ? 'left' : 'right'; + labelXOffset = tickPadding; + } else { + textAlign = isLeft ? 'right' : 'left'; + labelXOffset = tl + tickPadding; + } + + labelX = isLeft ? me.right - labelXOffset : me.left + labelXOffset; + + var yLineValue = getLineValue(me, index, gridLines.offsetGridLines && ticks.length > 1); + if (yLineValue < me.top) { + lineColor = 'rgba(0,0,0,0)'; + } + yLineValue += helpers.aliasPixel(lineWidth); + + labelY = me.getPixelForTick(index) + optionTicks.labelOffset; + + tx1 = xTickStart; + tx2 = xTickEnd; + x1 = chartArea.left; + x2 = chartArea.right; + ty1 = ty2 = y1 = y2 = yLineValue; + } + + itemsToDraw.push({ + tx1: tx1, + ty1: ty1, + tx2: tx2, + ty2: ty2, + x1: x1, + y1: y1, + x2: x2, + y2: y2, + labelX: labelX, + labelY: labelY, + glWidth: lineWidth, + glColor: lineColor, + glBorderDash: borderDash, + glBorderDashOffset: borderDashOffset, + rotation: -1 * labelRotationRadians, + label: label, + major: tick.major, + textBaseline: textBaseline, + textAlign: textAlign + }); + }); + + // Draw all of the tick labels, tick marks, and grid lines at the correct places + helpers.each(itemsToDraw, function(itemToDraw) { + if (gridLines.display) { + context.save(); + context.lineWidth = itemToDraw.glWidth; + context.strokeStyle = itemToDraw.glColor; + if (context.setLineDash) { + context.setLineDash(itemToDraw.glBorderDash); + context.lineDashOffset = itemToDraw.glBorderDashOffset; + } + + context.beginPath(); + + if (gridLines.drawTicks) { + context.moveTo(itemToDraw.tx1, itemToDraw.ty1); + context.lineTo(itemToDraw.tx2, itemToDraw.ty2); + } + + if (gridLines.drawOnChartArea) { + context.moveTo(itemToDraw.x1, itemToDraw.y1); + context.lineTo(itemToDraw.x2, itemToDraw.y2); + } + + context.stroke(); + context.restore(); + } + + if (optionTicks.display) { + // Make sure we draw text in the correct color and font + context.save(); + context.translate(itemToDraw.labelX, itemToDraw.labelY); + context.rotate(itemToDraw.rotation); + context.font = itemToDraw.major ? majorTickFont.font : tickFont.font; + context.fillStyle = itemToDraw.major ? majorTickFontColor : tickFontColor; + context.textBaseline = itemToDraw.textBaseline; + context.textAlign = itemToDraw.textAlign; + + var label = itemToDraw.label; + if (helpers.isArray(label)) { + for (var i = 0, y = 0; i < label.length; ++i) { + // We just make sure the multiline element is a string here.. + context.fillText('' + label[i], 0, y); + // apply same lineSpacing as calculated @ L#320 + y += (tickFont.size * 1.5); + } + } else { + context.fillText(label, 0, 0); + } + context.restore(); + } + }); + + if (scaleLabel.display) { + // Draw the scale label + var scaleLabelX; + var scaleLabelY; + var rotation = 0; + var halfLineHeight = parseLineHeight(scaleLabel) / 2; + + if (isHorizontal) { + scaleLabelX = me.left + ((me.right - me.left) / 2); // midpoint of the width + scaleLabelY = options.position === 'bottom' + ? me.bottom - halfLineHeight - scaleLabelPadding.bottom + : me.top + halfLineHeight + scaleLabelPadding.top; + } else { + var isLeft = options.position === 'left'; + scaleLabelX = isLeft + ? me.left + halfLineHeight + scaleLabelPadding.top + : me.right - halfLineHeight - scaleLabelPadding.top; + scaleLabelY = me.top + ((me.bottom - me.top) / 2); + rotation = isLeft ? -0.5 * Math.PI : 0.5 * Math.PI; + } + + context.save(); + context.translate(scaleLabelX, scaleLabelY); + context.rotate(rotation); + context.textAlign = 'center'; + context.textBaseline = 'middle'; + context.fillStyle = scaleLabelFontColor; // render in correct colour + context.font = scaleLabelFont.font; + context.fillText(scaleLabel.labelString, 0, 0); + context.restore(); + } + + if (gridLines.drawBorder) { + // Draw the line at the edge of the axis + context.lineWidth = helpers.valueAtIndexOrDefault(gridLines.lineWidth, 0); + context.strokeStyle = helpers.valueAtIndexOrDefault(gridLines.color, 0); + var x1 = me.left; + var x2 = me.right; + var y1 = me.top; + var y2 = me.bottom; + + var aliasPixel = helpers.aliasPixel(context.lineWidth); + if (isHorizontal) { + y1 = y2 = options.position === 'top' ? me.bottom : me.top; + y1 += aliasPixel; + y2 += aliasPixel; + } else { + x1 = x2 = options.position === 'left' ? me.right : me.left; + x1 += aliasPixel; + x2 += aliasPixel; + } + + context.beginPath(); + context.moveTo(x1, y1); + context.lineTo(x2, y2); + context.stroke(); + } + } + }); +}; + +},{"25":25,"26":26,"34":34,"45":45}],33:[function(require,module,exports){ +'use strict'; + +var defaults = require(25); +var helpers = require(45); + +module.exports = function(Chart) { + + Chart.scaleService = { + // Scale registration object. Extensions can register new scale types (such as log or DB scales) and then + // use the new chart options to grab the correct scale + constructors: {}, + // Use a registration function so that we can move to an ES6 map when we no longer need to support + // old browsers + + // Scale config defaults + defaults: {}, + registerScaleType: function(type, scaleConstructor, scaleDefaults) { + this.constructors[type] = scaleConstructor; + this.defaults[type] = helpers.clone(scaleDefaults); + }, + getScaleConstructor: function(type) { + return this.constructors.hasOwnProperty(type) ? this.constructors[type] : undefined; + }, + getScaleDefaults: function(type) { + // Return the scale defaults merged with the global settings so that we always use the latest ones + return this.defaults.hasOwnProperty(type) ? helpers.merge({}, [defaults.scale, this.defaults[type]]) : {}; + }, + updateScaleDefaults: function(type, additions) { + var me = this; + if (me.defaults.hasOwnProperty(type)) { + me.defaults[type] = helpers.extend(me.defaults[type], additions); + } + }, + addScalesToLayout: function(chart) { + // Adds each scale to the chart.boxes array to be sized accordingly + helpers.each(chart.scales, function(scale) { + // Set ILayoutItem parameters for backwards compatibility + scale.fullWidth = scale.options.fullWidth; + scale.position = scale.options.position; + scale.weight = scale.options.weight; + Chart.layoutService.addBox(chart, scale); + }); + } + }; +}; + +},{"25":25,"45":45}],34:[function(require,module,exports){ +'use strict'; + +var helpers = require(45); + +/** + * Namespace to hold static tick generation functions + * @namespace Chart.Ticks + */ +module.exports = { + /** + * Namespace to hold generators for different types of ticks + * @namespace Chart.Ticks.generators + */ + generators: { + /** + * Interface for the options provided to the numeric tick generator + * @interface INumericTickGenerationOptions + */ + /** + * The maximum number of ticks to display + * @name INumericTickGenerationOptions#maxTicks + * @type Number + */ + /** + * The distance between each tick. + * @name INumericTickGenerationOptions#stepSize + * @type Number + * @optional + */ + /** + * Forced minimum for the ticks. If not specified, the minimum of the data range is used to calculate the tick minimum + * @name INumericTickGenerationOptions#min + * @type Number + * @optional + */ + /** + * The maximum value of the ticks. If not specified, the maximum of the data range is used to calculate the tick maximum + * @name INumericTickGenerationOptions#max + * @type Number + * @optional + */ + + /** + * Generate a set of linear ticks + * @method Chart.Ticks.generators.linear + * @param generationOptions {INumericTickGenerationOptions} the options used to generate the ticks + * @param dataRange {IRange} the range of the data + * @returns {Array} array of tick values + */ + linear: function(generationOptions, dataRange) { + var ticks = []; + // To get a "nice" value for the tick spacing, we will use the appropriately named + // "nice number" algorithm. See http://stackoverflow.com/questions/8506881/nice-label-algorithm-for-charts-with-minimum-ticks + // for details. + + var spacing; + if (generationOptions.stepSize && generationOptions.stepSize > 0) { + spacing = generationOptions.stepSize; + } else { + var niceRange = helpers.niceNum(dataRange.max - dataRange.min, false); + spacing = helpers.niceNum(niceRange / (generationOptions.maxTicks - 1), true); + } + var niceMin = Math.floor(dataRange.min / spacing) * spacing; + var niceMax = Math.ceil(dataRange.max / spacing) * spacing; + + // If min, max and stepSize is set and they make an evenly spaced scale use it. + if (generationOptions.min && generationOptions.max && generationOptions.stepSize) { + // If very close to our whole number, use it. + if (helpers.almostWhole((generationOptions.max - generationOptions.min) / generationOptions.stepSize, spacing / 1000)) { + niceMin = generationOptions.min; + niceMax = generationOptions.max; + } + } + + var numSpaces = (niceMax - niceMin) / spacing; + // If very close to our rounded value, use it. + if (helpers.almostEquals(numSpaces, Math.round(numSpaces), spacing / 1000)) { + numSpaces = Math.round(numSpaces); + } else { + numSpaces = Math.ceil(numSpaces); + } + + // Put the values into the ticks array + ticks.push(generationOptions.min !== undefined ? generationOptions.min : niceMin); + for (var j = 1; j < numSpaces; ++j) { + ticks.push(niceMin + (j * spacing)); + } + ticks.push(generationOptions.max !== undefined ? generationOptions.max : niceMax); + + return ticks; + }, + + /** + * Generate a set of logarithmic ticks + * @method Chart.Ticks.generators.logarithmic + * @param generationOptions {INumericTickGenerationOptions} the options used to generate the ticks + * @param dataRange {IRange} the range of the data + * @returns {Array} array of tick values + */ + logarithmic: function(generationOptions, dataRange) { + var ticks = []; + var valueOrDefault = helpers.valueOrDefault; + + // Figure out what the max number of ticks we can support it is based on the size of + // the axis area. For now, we say that the minimum tick spacing in pixels must be 50 + // We also limit the maximum number of ticks to 11 which gives a nice 10 squares on + // the graph + var tickVal = valueOrDefault(generationOptions.min, Math.pow(10, Math.floor(helpers.log10(dataRange.min)))); + + var endExp = Math.floor(helpers.log10(dataRange.max)); + var endSignificand = Math.ceil(dataRange.max / Math.pow(10, endExp)); + var exp, significand; + + if (tickVal === 0) { + exp = Math.floor(helpers.log10(dataRange.minNotZero)); + significand = Math.floor(dataRange.minNotZero / Math.pow(10, exp)); + + ticks.push(tickVal); + tickVal = significand * Math.pow(10, exp); + } else { + exp = Math.floor(helpers.log10(tickVal)); + significand = Math.floor(tickVal / Math.pow(10, exp)); + } + + do { + ticks.push(tickVal); + + ++significand; + if (significand === 10) { + significand = 1; + ++exp; + } + + tickVal = significand * Math.pow(10, exp); + } while (exp < endExp || (exp === endExp && significand < endSignificand)); + + var lastTick = valueOrDefault(generationOptions.max, tickVal); + ticks.push(lastTick); + + return ticks; + } + }, + + /** + * Namespace to hold formatters for different types of ticks + * @namespace Chart.Ticks.formatters + */ + formatters: { + /** + * Formatter for value labels + * @method Chart.Ticks.formatters.values + * @param value the value to display + * @return {String|Array} the label to display + */ + values: function(value) { + return helpers.isArray(value) ? value : '' + value; + }, + + /** + * Formatter for linear numeric ticks + * @method Chart.Ticks.formatters.linear + * @param tickValue {Number} the value to be formatted + * @param index {Number} the position of the tickValue parameter in the ticks array + * @param ticks {Array} the list of ticks being converted + * @return {String} string representation of the tickValue parameter + */ + linear: function(tickValue, index, ticks) { + // If we have lots of ticks, don't use the ones + var delta = ticks.length > 3 ? ticks[2] - ticks[1] : ticks[1] - ticks[0]; + + // If we have a number like 2.5 as the delta, figure out how many decimal places we need + if (Math.abs(delta) > 1) { + if (tickValue !== Math.floor(tickValue)) { + // not an integer + delta = tickValue - Math.floor(tickValue); + } + } + + var logDelta = helpers.log10(Math.abs(delta)); + var tickString = ''; + + if (tickValue !== 0) { + var numDecimal = -1 * Math.floor(logDelta); + numDecimal = Math.max(Math.min(numDecimal, 20), 0); // toFixed has a max of 20 decimal places + tickString = tickValue.toFixed(numDecimal); + } else { + tickString = '0'; // never show decimal places for 0 + } + + return tickString; + }, + + logarithmic: function(tickValue, index, ticks) { + var remain = tickValue / (Math.pow(10, Math.floor(helpers.log10(tickValue)))); + + if (tickValue === 0) { + return '0'; + } else if (remain === 1 || remain === 2 || remain === 5 || index === 0 || index === ticks.length - 1) { + return tickValue.toExponential(); + } + return ''; + } + } +}; + +},{"45":45}],35:[function(require,module,exports){ +'use strict'; + +var defaults = require(25); +var Element = require(26); +var helpers = require(45); + +defaults._set('global', { + tooltips: { + enabled: true, + custom: null, + mode: 'nearest', + position: 'average', + intersect: true, + backgroundColor: 'rgba(0,0,0,0.8)', + titleFontStyle: 'bold', + titleSpacing: 2, + titleMarginBottom: 6, + titleFontColor: '#fff', + titleAlign: 'left', + bodySpacing: 2, + bodyFontColor: '#fff', + bodyAlign: 'left', + footerFontStyle: 'bold', + footerSpacing: 2, + footerMarginTop: 6, + footerFontColor: '#fff', + footerAlign: 'left', + yPadding: 6, + xPadding: 6, + caretPadding: 2, + caretSize: 5, + cornerRadius: 6, + multiKeyBackground: '#fff', + displayColors: true, + borderColor: 'rgba(0,0,0,0)', + borderWidth: 0, + callbacks: { + // Args are: (tooltipItems, data) + beforeTitle: helpers.noop, + title: function(tooltipItems, data) { + // Pick first xLabel for now + var title = ''; + var labels = data.labels; + var labelCount = labels ? labels.length : 0; + + if (tooltipItems.length > 0) { + var item = tooltipItems[0]; + + if (item.xLabel) { + title = item.xLabel; + } else if (labelCount > 0 && item.index < labelCount) { + title = labels[item.index]; + } + } + + return title; + }, + afterTitle: helpers.noop, + + // Args are: (tooltipItems, data) + beforeBody: helpers.noop, + + // Args are: (tooltipItem, data) + beforeLabel: helpers.noop, + label: function(tooltipItem, data) { + var label = data.datasets[tooltipItem.datasetIndex].label || ''; + + if (label) { + label += ': '; + } + label += tooltipItem.yLabel; + return label; + }, + labelColor: function(tooltipItem, chart) { + var meta = chart.getDatasetMeta(tooltipItem.datasetIndex); + var activeElement = meta.data[tooltipItem.index]; + var view = activeElement._view; + return { + borderColor: view.borderColor, + backgroundColor: view.backgroundColor + }; + }, + labelTextColor: function() { + return this._options.bodyFontColor; + }, + afterLabel: helpers.noop, + + // Args are: (tooltipItems, data) + afterBody: helpers.noop, + + // Args are: (tooltipItems, data) + beforeFooter: helpers.noop, + footer: helpers.noop, + afterFooter: helpers.noop + } + } +}); + +module.exports = function(Chart) { + + /** + * Helper method to merge the opacity into a color + */ + function mergeOpacity(colorString, opacity) { + var color = helpers.color(colorString); + return color.alpha(opacity * color.alpha()).rgbaString(); + } + + // Helper to push or concat based on if the 2nd parameter is an array or not + function pushOrConcat(base, toPush) { + if (toPush) { + if (helpers.isArray(toPush)) { + // base = base.concat(toPush); + Array.prototype.push.apply(base, toPush); + } else { + base.push(toPush); + } + } + + return base; + } + + // Private helper to create a tooltip item model + // @param element : the chart element (point, arc, bar) to create the tooltip item for + // @return : new tooltip item + function createTooltipItem(element) { + var xScale = element._xScale; + var yScale = element._yScale || element._scale; // handle radar || polarArea charts + var index = element._index; + var datasetIndex = element._datasetIndex; + + return { + xLabel: xScale ? xScale.getLabelForIndex(index, datasetIndex) : '', + yLabel: yScale ? yScale.getLabelForIndex(index, datasetIndex) : '', + index: index, + datasetIndex: datasetIndex, + x: element._model.x, + y: element._model.y + }; + } + + /** + * Helper to get the reset model for the tooltip + * @param tooltipOpts {Object} the tooltip options + */ + function getBaseModel(tooltipOpts) { + var globalDefaults = defaults.global; + var valueOrDefault = helpers.valueOrDefault; + + return { + // Positioning + xPadding: tooltipOpts.xPadding, + yPadding: tooltipOpts.yPadding, + xAlign: tooltipOpts.xAlign, + yAlign: tooltipOpts.yAlign, + + // Body + bodyFontColor: tooltipOpts.bodyFontColor, + _bodyFontFamily: valueOrDefault(tooltipOpts.bodyFontFamily, globalDefaults.defaultFontFamily), + _bodyFontStyle: valueOrDefault(tooltipOpts.bodyFontStyle, globalDefaults.defaultFontStyle), + _bodyAlign: tooltipOpts.bodyAlign, + bodyFontSize: valueOrDefault(tooltipOpts.bodyFontSize, globalDefaults.defaultFontSize), + bodySpacing: tooltipOpts.bodySpacing, + + // Title + titleFontColor: tooltipOpts.titleFontColor, + _titleFontFamily: valueOrDefault(tooltipOpts.titleFontFamily, globalDefaults.defaultFontFamily), + _titleFontStyle: valueOrDefault(tooltipOpts.titleFontStyle, globalDefaults.defaultFontStyle), + titleFontSize: valueOrDefault(tooltipOpts.titleFontSize, globalDefaults.defaultFontSize), + _titleAlign: tooltipOpts.titleAlign, + titleSpacing: tooltipOpts.titleSpacing, + titleMarginBottom: tooltipOpts.titleMarginBottom, + + // Footer + footerFontColor: tooltipOpts.footerFontColor, + _footerFontFamily: valueOrDefault(tooltipOpts.footerFontFamily, globalDefaults.defaultFontFamily), + _footerFontStyle: valueOrDefault(tooltipOpts.footerFontStyle, globalDefaults.defaultFontStyle), + footerFontSize: valueOrDefault(tooltipOpts.footerFontSize, globalDefaults.defaultFontSize), + _footerAlign: tooltipOpts.footerAlign, + footerSpacing: tooltipOpts.footerSpacing, + footerMarginTop: tooltipOpts.footerMarginTop, + + // Appearance + caretSize: tooltipOpts.caretSize, + cornerRadius: tooltipOpts.cornerRadius, + backgroundColor: tooltipOpts.backgroundColor, + opacity: 0, + legendColorBackground: tooltipOpts.multiKeyBackground, + displayColors: tooltipOpts.displayColors, + borderColor: tooltipOpts.borderColor, + borderWidth: tooltipOpts.borderWidth + }; + } + + /** + * Get the size of the tooltip + */ + function getTooltipSize(tooltip, model) { + var ctx = tooltip._chart.ctx; + + var height = model.yPadding * 2; // Tooltip Padding + var width = 0; + + // Count of all lines in the body + var body = model.body; + var combinedBodyLength = body.reduce(function(count, bodyItem) { + return count + bodyItem.before.length + bodyItem.lines.length + bodyItem.after.length; + }, 0); + combinedBodyLength += model.beforeBody.length + model.afterBody.length; + + var titleLineCount = model.title.length; + var footerLineCount = model.footer.length; + var titleFontSize = model.titleFontSize; + var bodyFontSize = model.bodyFontSize; + var footerFontSize = model.footerFontSize; + + height += titleLineCount * titleFontSize; // Title Lines + height += titleLineCount ? (titleLineCount - 1) * model.titleSpacing : 0; // Title Line Spacing + height += titleLineCount ? model.titleMarginBottom : 0; // Title's bottom Margin + height += combinedBodyLength * bodyFontSize; // Body Lines + height += combinedBodyLength ? (combinedBodyLength - 1) * model.bodySpacing : 0; // Body Line Spacing + height += footerLineCount ? model.footerMarginTop : 0; // Footer Margin + height += footerLineCount * (footerFontSize); // Footer Lines + height += footerLineCount ? (footerLineCount - 1) * model.footerSpacing : 0; // Footer Line Spacing + + // Title width + var widthPadding = 0; + var maxLineWidth = function(line) { + width = Math.max(width, ctx.measureText(line).width + widthPadding); + }; + + ctx.font = helpers.fontString(titleFontSize, model._titleFontStyle, model._titleFontFamily); + helpers.each(model.title, maxLineWidth); + + // Body width + ctx.font = helpers.fontString(bodyFontSize, model._bodyFontStyle, model._bodyFontFamily); + helpers.each(model.beforeBody.concat(model.afterBody), maxLineWidth); + + // Body lines may include some extra width due to the color box + widthPadding = model.displayColors ? (bodyFontSize + 2) : 0; + helpers.each(body, function(bodyItem) { + helpers.each(bodyItem.before, maxLineWidth); + helpers.each(bodyItem.lines, maxLineWidth); + helpers.each(bodyItem.after, maxLineWidth); + }); + + // Reset back to 0 + widthPadding = 0; + + // Footer width + ctx.font = helpers.fontString(footerFontSize, model._footerFontStyle, model._footerFontFamily); + helpers.each(model.footer, maxLineWidth); + + // Add padding + width += 2 * model.xPadding; + + return { + width: width, + height: height + }; + } + + /** + * Helper to get the alignment of a tooltip given the size + */ + function determineAlignment(tooltip, size) { + var model = tooltip._model; + var chart = tooltip._chart; + var chartArea = tooltip._chart.chartArea; + var xAlign = 'center'; + var yAlign = 'center'; + + if (model.y < size.height) { + yAlign = 'top'; + } else if (model.y > (chart.height - size.height)) { + yAlign = 'bottom'; + } + + var lf, rf; // functions to determine left, right alignment + var olf, orf; // functions to determine if left/right alignment causes tooltip to go outside chart + var yf; // function to get the y alignment if the tooltip goes outside of the left or right edges + var midX = (chartArea.left + chartArea.right) / 2; + var midY = (chartArea.top + chartArea.bottom) / 2; + + if (yAlign === 'center') { + lf = function(x) { + return x <= midX; + }; + rf = function(x) { + return x > midX; + }; + } else { + lf = function(x) { + return x <= (size.width / 2); + }; + rf = function(x) { + return x >= (chart.width - (size.width / 2)); + }; + } + + olf = function(x) { + return x + size.width > chart.width; + }; + orf = function(x) { + return x - size.width < 0; + }; + yf = function(y) { + return y <= midY ? 'top' : 'bottom'; + }; + + if (lf(model.x)) { + xAlign = 'left'; + + // Is tooltip too wide and goes over the right side of the chart.? + if (olf(model.x)) { + xAlign = 'center'; + yAlign = yf(model.y); + } + } else if (rf(model.x)) { + xAlign = 'right'; + + // Is tooltip too wide and goes outside left edge of canvas? + if (orf(model.x)) { + xAlign = 'center'; + yAlign = yf(model.y); + } + } + + var opts = tooltip._options; + return { + xAlign: opts.xAlign ? opts.xAlign : xAlign, + yAlign: opts.yAlign ? opts.yAlign : yAlign + }; + } + + /** + * @Helper to get the location a tooltip needs to be placed at given the initial position (via the vm) and the size and alignment + */ + function getBackgroundPoint(vm, size, alignment) { + // Background Position + var x = vm.x; + var y = vm.y; + + var caretSize = vm.caretSize; + var caretPadding = vm.caretPadding; + var cornerRadius = vm.cornerRadius; + var xAlign = alignment.xAlign; + var yAlign = alignment.yAlign; + var paddingAndSize = caretSize + caretPadding; + var radiusAndPadding = cornerRadius + caretPadding; + + if (xAlign === 'right') { + x -= size.width; + } else if (xAlign === 'center') { + x -= (size.width / 2); + } + + if (yAlign === 'top') { + y += paddingAndSize; + } else if (yAlign === 'bottom') { + y -= size.height + paddingAndSize; + } else { + y -= (size.height / 2); + } + + if (yAlign === 'center') { + if (xAlign === 'left') { + x += paddingAndSize; + } else if (xAlign === 'right') { + x -= paddingAndSize; + } + } else if (xAlign === 'left') { + x -= radiusAndPadding; + } else if (xAlign === 'right') { + x += radiusAndPadding; + } + + return { + x: x, + y: y + }; + } + + Chart.Tooltip = Element.extend({ + initialize: function() { + this._model = getBaseModel(this._options); + this._lastActive = []; + }, + + // Get the title + // Args are: (tooltipItem, data) + getTitle: function() { + var me = this; + var opts = me._options; + var callbacks = opts.callbacks; + + var beforeTitle = callbacks.beforeTitle.apply(me, arguments); + var title = callbacks.title.apply(me, arguments); + var afterTitle = callbacks.afterTitle.apply(me, arguments); + + var lines = []; + lines = pushOrConcat(lines, beforeTitle); + lines = pushOrConcat(lines, title); + lines = pushOrConcat(lines, afterTitle); + + return lines; + }, + + // Args are: (tooltipItem, data) + getBeforeBody: function() { + var lines = this._options.callbacks.beforeBody.apply(this, arguments); + return helpers.isArray(lines) ? lines : lines !== undefined ? [lines] : []; + }, + + // Args are: (tooltipItem, data) + getBody: function(tooltipItems, data) { + var me = this; + var callbacks = me._options.callbacks; + var bodyItems = []; + + helpers.each(tooltipItems, function(tooltipItem) { + var bodyItem = { + before: [], + lines: [], + after: [] + }; + pushOrConcat(bodyItem.before, callbacks.beforeLabel.call(me, tooltipItem, data)); + pushOrConcat(bodyItem.lines, callbacks.label.call(me, tooltipItem, data)); + pushOrConcat(bodyItem.after, callbacks.afterLabel.call(me, tooltipItem, data)); + + bodyItems.push(bodyItem); + }); + + return bodyItems; + }, + + // Args are: (tooltipItem, data) + getAfterBody: function() { + var lines = this._options.callbacks.afterBody.apply(this, arguments); + return helpers.isArray(lines) ? lines : lines !== undefined ? [lines] : []; + }, + + // Get the footer and beforeFooter and afterFooter lines + // Args are: (tooltipItem, data) + getFooter: function() { + var me = this; + var callbacks = me._options.callbacks; + + var beforeFooter = callbacks.beforeFooter.apply(me, arguments); + var footer = callbacks.footer.apply(me, arguments); + var afterFooter = callbacks.afterFooter.apply(me, arguments); + + var lines = []; + lines = pushOrConcat(lines, beforeFooter); + lines = pushOrConcat(lines, footer); + lines = pushOrConcat(lines, afterFooter); + + return lines; + }, + + update: function(changed) { + var me = this; + var opts = me._options; + + // Need to regenerate the model because its faster than using extend and it is necessary due to the optimization in Chart.Element.transition + // that does _view = _model if ease === 1. This causes the 2nd tooltip update to set properties in both the view and model at the same time + // which breaks any animations. + var existingModel = me._model; + var model = me._model = getBaseModel(opts); + var active = me._active; + + var data = me._data; + + // In the case where active.length === 0 we need to keep these at existing values for good animations + var alignment = { + xAlign: existingModel.xAlign, + yAlign: existingModel.yAlign + }; + var backgroundPoint = { + x: existingModel.x, + y: existingModel.y + }; + var tooltipSize = { + width: existingModel.width, + height: existingModel.height + }; + var tooltipPosition = { + x: existingModel.caretX, + y: existingModel.caretY + }; + + var i, len; + + if (active.length) { + model.opacity = 1; + + var labelColors = []; + var labelTextColors = []; + tooltipPosition = Chart.Tooltip.positioners[opts.position].call(me, active, me._eventPosition); + + var tooltipItems = []; + for (i = 0, len = active.length; i < len; ++i) { + tooltipItems.push(createTooltipItem(active[i])); + } + + // If the user provided a filter function, use it to modify the tooltip items + if (opts.filter) { + tooltipItems = tooltipItems.filter(function(a) { + return opts.filter(a, data); + }); + } + + // If the user provided a sorting function, use it to modify the tooltip items + if (opts.itemSort) { + tooltipItems = tooltipItems.sort(function(a, b) { + return opts.itemSort(a, b, data); + }); + } + + // Determine colors for boxes + helpers.each(tooltipItems, function(tooltipItem) { + labelColors.push(opts.callbacks.labelColor.call(me, tooltipItem, me._chart)); + labelTextColors.push(opts.callbacks.labelTextColor.call(me, tooltipItem, me._chart)); + }); + + + // Build the Text Lines + model.title = me.getTitle(tooltipItems, data); + model.beforeBody = me.getBeforeBody(tooltipItems, data); + model.body = me.getBody(tooltipItems, data); + model.afterBody = me.getAfterBody(tooltipItems, data); + model.footer = me.getFooter(tooltipItems, data); + + // Initial positioning and colors + model.x = Math.round(tooltipPosition.x); + model.y = Math.round(tooltipPosition.y); + model.caretPadding = opts.caretPadding; + model.labelColors = labelColors; + model.labelTextColors = labelTextColors; + + // data points + model.dataPoints = tooltipItems; + + // We need to determine alignment of the tooltip + tooltipSize = getTooltipSize(this, model); + alignment = determineAlignment(this, tooltipSize); + // Final Size and Position + backgroundPoint = getBackgroundPoint(model, tooltipSize, alignment); + } else { + model.opacity = 0; + } + + model.xAlign = alignment.xAlign; + model.yAlign = alignment.yAlign; + model.x = backgroundPoint.x; + model.y = backgroundPoint.y; + model.width = tooltipSize.width; + model.height = tooltipSize.height; + + // Point where the caret on the tooltip points to + model.caretX = tooltipPosition.x; + model.caretY = tooltipPosition.y; + + me._model = model; + + if (changed && opts.custom) { + opts.custom.call(me, model); + } + + return me; + }, + drawCaret: function(tooltipPoint, size) { + var ctx = this._chart.ctx; + var vm = this._view; + var caretPosition = this.getCaretPosition(tooltipPoint, size, vm); + + ctx.lineTo(caretPosition.x1, caretPosition.y1); + ctx.lineTo(caretPosition.x2, caretPosition.y2); + ctx.lineTo(caretPosition.x3, caretPosition.y3); + }, + getCaretPosition: function(tooltipPoint, size, vm) { + var x1, x2, x3, y1, y2, y3; + var caretSize = vm.caretSize; + var cornerRadius = vm.cornerRadius; + var xAlign = vm.xAlign; + var yAlign = vm.yAlign; + var ptX = tooltipPoint.x; + var ptY = tooltipPoint.y; + var width = size.width; + var height = size.height; + + if (yAlign === 'center') { + y2 = ptY + (height / 2); + + if (xAlign === 'left') { + x1 = ptX; + x2 = x1 - caretSize; + x3 = x1; + + y1 = y2 + caretSize; + y3 = y2 - caretSize; + } else { + x1 = ptX + width; + x2 = x1 + caretSize; + x3 = x1; + + y1 = y2 - caretSize; + y3 = y2 + caretSize; + } + } else { + if (xAlign === 'left') { + x2 = ptX + cornerRadius + (caretSize); + x1 = x2 - caretSize; + x3 = x2 + caretSize; + } else if (xAlign === 'right') { + x2 = ptX + width - cornerRadius - caretSize; + x1 = x2 - caretSize; + x3 = x2 + caretSize; + } else { + x2 = ptX + (width / 2); + x1 = x2 - caretSize; + x3 = x2 + caretSize; + } + if (yAlign === 'top') { + y1 = ptY; + y2 = y1 - caretSize; + y3 = y1; + } else { + y1 = ptY + height; + y2 = y1 + caretSize; + y3 = y1; + // invert drawing order + var tmp = x3; + x3 = x1; + x1 = tmp; + } + } + return {x1: x1, x2: x2, x3: x3, y1: y1, y2: y2, y3: y3}; + }, + drawTitle: function(pt, vm, ctx, opacity) { + var title = vm.title; + + if (title.length) { + ctx.textAlign = vm._titleAlign; + ctx.textBaseline = 'top'; + + var titleFontSize = vm.titleFontSize; + var titleSpacing = vm.titleSpacing; + + ctx.fillStyle = mergeOpacity(vm.titleFontColor, opacity); + ctx.font = helpers.fontString(titleFontSize, vm._titleFontStyle, vm._titleFontFamily); + + var i, len; + for (i = 0, len = title.length; i < len; ++i) { + ctx.fillText(title[i], pt.x, pt.y); + pt.y += titleFontSize + titleSpacing; // Line Height and spacing + + if (i + 1 === title.length) { + pt.y += vm.titleMarginBottom - titleSpacing; // If Last, add margin, remove spacing + } + } + } + }, + drawBody: function(pt, vm, ctx, opacity) { + var bodyFontSize = vm.bodyFontSize; + var bodySpacing = vm.bodySpacing; + var body = vm.body; + + ctx.textAlign = vm._bodyAlign; + ctx.textBaseline = 'top'; + ctx.font = helpers.fontString(bodyFontSize, vm._bodyFontStyle, vm._bodyFontFamily); + + // Before Body + var xLinePadding = 0; + var fillLineOfText = function(line) { + ctx.fillText(line, pt.x + xLinePadding, pt.y); + pt.y += bodyFontSize + bodySpacing; + }; + + // Before body lines + ctx.fillStyle = mergeOpacity(vm.bodyFontColor, opacity); + helpers.each(vm.beforeBody, fillLineOfText); + + var drawColorBoxes = vm.displayColors; + xLinePadding = drawColorBoxes ? (bodyFontSize + 2) : 0; + + // Draw body lines now + helpers.each(body, function(bodyItem, i) { + var textColor = mergeOpacity(vm.labelTextColors[i], opacity); + ctx.fillStyle = textColor; + helpers.each(bodyItem.before, fillLineOfText); + + helpers.each(bodyItem.lines, function(line) { + // Draw Legend-like boxes if needed + if (drawColorBoxes) { + // Fill a white rect so that colours merge nicely if the opacity is < 1 + ctx.fillStyle = mergeOpacity(vm.legendColorBackground, opacity); + ctx.fillRect(pt.x, pt.y, bodyFontSize, bodyFontSize); + + // Border + ctx.lineWidth = 1; + ctx.strokeStyle = mergeOpacity(vm.labelColors[i].borderColor, opacity); + ctx.strokeRect(pt.x, pt.y, bodyFontSize, bodyFontSize); + + // Inner square + ctx.fillStyle = mergeOpacity(vm.labelColors[i].backgroundColor, opacity); + ctx.fillRect(pt.x + 1, pt.y + 1, bodyFontSize - 2, bodyFontSize - 2); + ctx.fillStyle = textColor; + } + + fillLineOfText(line); + }); + + helpers.each(bodyItem.after, fillLineOfText); + }); + + // Reset back to 0 for after body + xLinePadding = 0; + + // After body lines + helpers.each(vm.afterBody, fillLineOfText); + pt.y -= bodySpacing; // Remove last body spacing + }, + drawFooter: function(pt, vm, ctx, opacity) { + var footer = vm.footer; + + if (footer.length) { + pt.y += vm.footerMarginTop; + + ctx.textAlign = vm._footerAlign; + ctx.textBaseline = 'top'; + + ctx.fillStyle = mergeOpacity(vm.footerFontColor, opacity); + ctx.font = helpers.fontString(vm.footerFontSize, vm._footerFontStyle, vm._footerFontFamily); + + helpers.each(footer, function(line) { + ctx.fillText(line, pt.x, pt.y); + pt.y += vm.footerFontSize + vm.footerSpacing; + }); + } + }, + drawBackground: function(pt, vm, ctx, tooltipSize, opacity) { + ctx.fillStyle = mergeOpacity(vm.backgroundColor, opacity); + ctx.strokeStyle = mergeOpacity(vm.borderColor, opacity); + ctx.lineWidth = vm.borderWidth; + var xAlign = vm.xAlign; + var yAlign = vm.yAlign; + var x = pt.x; + var y = pt.y; + var width = tooltipSize.width; + var height = tooltipSize.height; + var radius = vm.cornerRadius; + + ctx.beginPath(); + ctx.moveTo(x + radius, y); + if (yAlign === 'top') { + this.drawCaret(pt, tooltipSize); + } + ctx.lineTo(x + width - radius, y); + ctx.quadraticCurveTo(x + width, y, x + width, y + radius); + if (yAlign === 'center' && xAlign === 'right') { + this.drawCaret(pt, tooltipSize); + } + ctx.lineTo(x + width, y + height - radius); + ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height); + if (yAlign === 'bottom') { + this.drawCaret(pt, tooltipSize); + } + ctx.lineTo(x + radius, y + height); + ctx.quadraticCurveTo(x, y + height, x, y + height - radius); + if (yAlign === 'center' && xAlign === 'left') { + this.drawCaret(pt, tooltipSize); + } + ctx.lineTo(x, y + radius); + ctx.quadraticCurveTo(x, y, x + radius, y); + ctx.closePath(); + + ctx.fill(); + + if (vm.borderWidth > 0) { + ctx.stroke(); + } + }, + draw: function() { + var ctx = this._chart.ctx; + var vm = this._view; + + if (vm.opacity === 0) { + return; + } + + var tooltipSize = { + width: vm.width, + height: vm.height + }; + var pt = { + x: vm.x, + y: vm.y + }; + + // IE11/Edge does not like very small opacities, so snap to 0 + var opacity = Math.abs(vm.opacity < 1e-3) ? 0 : vm.opacity; + + // Truthy/falsey value for empty tooltip + var hasTooltipContent = vm.title.length || vm.beforeBody.length || vm.body.length || vm.afterBody.length || vm.footer.length; + + if (this._options.enabled && hasTooltipContent) { + // Draw Background + this.drawBackground(pt, vm, ctx, tooltipSize, opacity); + + // Draw Title, Body, and Footer + pt.x += vm.xPadding; + pt.y += vm.yPadding; + + // Titles + this.drawTitle(pt, vm, ctx, opacity); + + // Body + this.drawBody(pt, vm, ctx, opacity); + + // Footer + this.drawFooter(pt, vm, ctx, opacity); + } + }, + + /** + * Handle an event + * @private + * @param {IEvent} event - The event to handle + * @returns {Boolean} true if the tooltip changed + */ + handleEvent: function(e) { + var me = this; + var options = me._options; + var changed = false; + + me._lastActive = me._lastActive || []; + + // Find Active Elements for tooltips + if (e.type === 'mouseout') { + me._active = []; + } else { + me._active = me._chart.getElementsAtEventForMode(e, options.mode, options); + } + + // Remember Last Actives + changed = !helpers.arrayEquals(me._active, me._lastActive); + + // If tooltip didn't change, do not handle the target event + if (!changed) { + return false; + } + + me._lastActive = me._active; + + if (options.enabled || options.custom) { + me._eventPosition = { + x: e.x, + y: e.y + }; + + var model = me._model; + me.update(true); + me.pivot(); + + // See if our tooltip position changed + changed |= (model.x !== me._model.x) || (model.y !== me._model.y); + } + + return changed; + } + }); + + /** + * @namespace Chart.Tooltip.positioners + */ + Chart.Tooltip.positioners = { + /** + * Average mode places the tooltip at the average position of the elements shown + * @function Chart.Tooltip.positioners.average + * @param elements {ChartElement[]} the elements being displayed in the tooltip + * @returns {Point} tooltip position + */ + average: function(elements) { + if (!elements.length) { + return false; + } + + var i, len; + var x = 0; + var y = 0; + var count = 0; + + for (i = 0, len = elements.length; i < len; ++i) { + var el = elements[i]; + if (el && el.hasValue()) { + var pos = el.tooltipPosition(); + x += pos.x; + y += pos.y; + ++count; + } + } + + return { + x: Math.round(x / count), + y: Math.round(y / count) + }; + }, + + /** + * Gets the tooltip position nearest of the item nearest to the event position + * @function Chart.Tooltip.positioners.nearest + * @param elements {Chart.Element[]} the tooltip elements + * @param eventPosition {Point} the position of the event in canvas coordinates + * @returns {Point} the tooltip position + */ + nearest: function(elements, eventPosition) { + var x = eventPosition.x; + var y = eventPosition.y; + var minDistance = Number.POSITIVE_INFINITY; + var i, len, nearestElement; + + for (i = 0, len = elements.length; i < len; ++i) { + var el = elements[i]; + if (el && el.hasValue()) { + var center = el.getCenterPoint(); + var d = helpers.distanceBetweenPoints(eventPosition, center); + + if (d < minDistance) { + minDistance = d; + nearestElement = el; + } + } + } + + if (nearestElement) { + var tp = nearestElement.tooltipPosition(); + x = tp.x; + y = tp.y; + } + + return { + x: x, + y: y + }; + } + }; +}; + +},{"25":25,"26":26,"45":45}],36:[function(require,module,exports){ +'use strict'; + +var defaults = require(25); +var Element = require(26); +var helpers = require(45); + +defaults._set('global', { + elements: { + arc: { + backgroundColor: defaults.global.defaultColor, + borderColor: '#fff', + borderWidth: 2 + } + } +}); + +module.exports = Element.extend({ + inLabelRange: function(mouseX) { + var vm = this._view; + + if (vm) { + return (Math.pow(mouseX - vm.x, 2) < Math.pow(vm.radius + vm.hoverRadius, 2)); + } + return false; + }, + + inRange: function(chartX, chartY) { + var vm = this._view; + + if (vm) { + var pointRelativePosition = helpers.getAngleFromPoint(vm, {x: chartX, y: chartY}); + var angle = pointRelativePosition.angle; + var distance = pointRelativePosition.distance; + + // Sanitise angle range + var startAngle = vm.startAngle; + var endAngle = vm.endAngle; + while (endAngle < startAngle) { + endAngle += 2.0 * Math.PI; + } + while (angle > endAngle) { + angle -= 2.0 * Math.PI; + } + while (angle < startAngle) { + angle += 2.0 * Math.PI; + } + + // Check if within the range of the open/close angle + var betweenAngles = (angle >= startAngle && angle <= endAngle); + var withinRadius = (distance >= vm.innerRadius && distance <= vm.outerRadius); + + return (betweenAngles && withinRadius); + } + return false; + }, + + getCenterPoint: function() { + var vm = this._view; + var halfAngle = (vm.startAngle + vm.endAngle) / 2; + var halfRadius = (vm.innerRadius + vm.outerRadius) / 2; + return { + x: vm.x + Math.cos(halfAngle) * halfRadius, + y: vm.y + Math.sin(halfAngle) * halfRadius + }; + }, + + getArea: function() { + var vm = this._view; + return Math.PI * ((vm.endAngle - vm.startAngle) / (2 * Math.PI)) * (Math.pow(vm.outerRadius, 2) - Math.pow(vm.innerRadius, 2)); + }, + + tooltipPosition: function() { + var vm = this._view; + var centreAngle = vm.startAngle + ((vm.endAngle - vm.startAngle) / 2); + var rangeFromCentre = (vm.outerRadius - vm.innerRadius) / 2 + vm.innerRadius; + + return { + x: vm.x + (Math.cos(centreAngle) * rangeFromCentre), + y: vm.y + (Math.sin(centreAngle) * rangeFromCentre) + }; + }, + + draw: function() { + var ctx = this._chart.ctx; + var vm = this._view; + var sA = vm.startAngle; + var eA = vm.endAngle; + + ctx.beginPath(); + + ctx.arc(vm.x, vm.y, vm.outerRadius, sA, eA); + ctx.arc(vm.x, vm.y, vm.innerRadius, eA, sA, true); + + ctx.closePath(); + ctx.strokeStyle = vm.borderColor; + ctx.lineWidth = vm.borderWidth; + + ctx.fillStyle = vm.backgroundColor; + + ctx.fill(); + ctx.lineJoin = 'bevel'; + + if (vm.borderWidth) { + ctx.stroke(); + } + } +}); + +},{"25":25,"26":26,"45":45}],37:[function(require,module,exports){ +'use strict'; + +var defaults = require(25); +var Element = require(26); +var helpers = require(45); + +var globalDefaults = defaults.global; + +defaults._set('global', { + elements: { + line: { + tension: 0.4, + backgroundColor: globalDefaults.defaultColor, + borderWidth: 3, + borderColor: globalDefaults.defaultColor, + borderCapStyle: 'butt', + borderDash: [], + borderDashOffset: 0.0, + borderJoinStyle: 'miter', + capBezierPoints: true, + fill: true, // do we fill in the area between the line and its base axis + } + } +}); + +module.exports = Element.extend({ + draw: function() { + var me = this; + var vm = me._view; + var ctx = me._chart.ctx; + var spanGaps = vm.spanGaps; + var points = me._children.slice(); // clone array + var globalOptionLineElements = globalDefaults.elements.line; + var lastDrawnIndex = -1; + var index, current, previous, currentVM; + + // If we are looping, adding the first point again + if (me._loop && points.length) { + points.push(points[0]); + } + + ctx.save(); + + // Stroke Line Options + ctx.lineCap = vm.borderCapStyle || globalOptionLineElements.borderCapStyle; + + // IE 9 and 10 do not support line dash + if (ctx.setLineDash) { + ctx.setLineDash(vm.borderDash || globalOptionLineElements.borderDash); + } + + ctx.lineDashOffset = vm.borderDashOffset || globalOptionLineElements.borderDashOffset; + ctx.lineJoin = vm.borderJoinStyle || globalOptionLineElements.borderJoinStyle; + ctx.lineWidth = vm.borderWidth || globalOptionLineElements.borderWidth; + ctx.strokeStyle = vm.borderColor || globalDefaults.defaultColor; + + // Stroke Line + ctx.beginPath(); + lastDrawnIndex = -1; + + for (index = 0; index < points.length; ++index) { + current = points[index]; + previous = helpers.previousItem(points, index); + currentVM = current._view; + + // First point moves to it's starting position no matter what + if (index === 0) { + if (!currentVM.skip) { + ctx.moveTo(currentVM.x, currentVM.y); + lastDrawnIndex = index; + } + } else { + previous = lastDrawnIndex === -1 ? previous : points[lastDrawnIndex]; + + if (!currentVM.skip) { + if ((lastDrawnIndex !== (index - 1) && !spanGaps) || lastDrawnIndex === -1) { + // There was a gap and this is the first point after the gap + ctx.moveTo(currentVM.x, currentVM.y); + } else { + // Line to next point + helpers.canvas.lineTo(ctx, previous._view, current._view); + } + lastDrawnIndex = index; + } + } + } + + ctx.stroke(); + ctx.restore(); + } +}); + +},{"25":25,"26":26,"45":45}],38:[function(require,module,exports){ +'use strict'; + +var defaults = require(25); +var Element = require(26); +var helpers = require(45); + +var defaultColor = defaults.global.defaultColor; + +defaults._set('global', { + elements: { + point: { + radius: 3, + pointStyle: 'circle', + backgroundColor: defaultColor, + borderColor: defaultColor, + borderWidth: 1, + // Hover + hitRadius: 1, + hoverRadius: 4, + hoverBorderWidth: 1 + } + } +}); + +function xRange(mouseX) { + var vm = this._view; + return vm ? (Math.pow(mouseX - vm.x, 2) < Math.pow(vm.radius + vm.hitRadius, 2)) : false; +} + +function yRange(mouseY) { + var vm = this._view; + return vm ? (Math.pow(mouseY - vm.y, 2) < Math.pow(vm.radius + vm.hitRadius, 2)) : false; +} + +module.exports = Element.extend({ + inRange: function(mouseX, mouseY) { + var vm = this._view; + return vm ? ((Math.pow(mouseX - vm.x, 2) + Math.pow(mouseY - vm.y, 2)) < Math.pow(vm.hitRadius + vm.radius, 2)) : false; + }, + + inLabelRange: xRange, + inXRange: xRange, + inYRange: yRange, + + getCenterPoint: function() { + var vm = this._view; + return { + x: vm.x, + y: vm.y + }; + }, + + getArea: function() { + return Math.PI * Math.pow(this._view.radius, 2); + }, + + tooltipPosition: function() { + var vm = this._view; + return { + x: vm.x, + y: vm.y, + padding: vm.radius + vm.borderWidth + }; + }, + + draw: function(chartArea) { + var vm = this._view; + var model = this._model; + var ctx = this._chart.ctx; + var pointStyle = vm.pointStyle; + var radius = vm.radius; + var x = vm.x; + var y = vm.y; + var color = helpers.color; + var errMargin = 1.01; // 1.01 is margin for Accumulated error. (Especially Edge, IE.) + var ratio = 0; + + if (vm.skip) { + return; + } + + ctx.strokeStyle = vm.borderColor || defaultColor; + ctx.lineWidth = helpers.valueOrDefault(vm.borderWidth, defaults.global.elements.point.borderWidth); + ctx.fillStyle = vm.backgroundColor || defaultColor; + + // Cliping for Points. + // going out from inner charArea? + if ((chartArea !== undefined) && ((model.x < chartArea.left) || (chartArea.right * errMargin < model.x) || (model.y < chartArea.top) || (chartArea.bottom * errMargin < model.y))) { + // Point fade out + if (model.x < chartArea.left) { + ratio = (x - model.x) / (chartArea.left - model.x); + } else if (chartArea.right * errMargin < model.x) { + ratio = (model.x - x) / (model.x - chartArea.right); + } else if (model.y < chartArea.top) { + ratio = (y - model.y) / (chartArea.top - model.y); + } else if (chartArea.bottom * errMargin < model.y) { + ratio = (model.y - y) / (model.y - chartArea.bottom); + } + ratio = Math.round(ratio * 100) / 100; + ctx.strokeStyle = color(ctx.strokeStyle).alpha(ratio).rgbString(); + ctx.fillStyle = color(ctx.fillStyle).alpha(ratio).rgbString(); + } + + helpers.canvas.drawPoint(ctx, pointStyle, radius, x, y); + } +}); + +},{"25":25,"26":26,"45":45}],39:[function(require,module,exports){ +'use strict'; + +var defaults = require(25); +var Element = require(26); + +defaults._set('global', { + elements: { + rectangle: { + backgroundColor: defaults.global.defaultColor, + borderColor: defaults.global.defaultColor, + borderSkipped: 'bottom', + borderWidth: 0 + } + } +}); + +function isVertical(bar) { + return bar._view.width !== undefined; +} + +/** + * Helper function to get the bounds of the bar regardless of the orientation + * @param bar {Chart.Element.Rectangle} the bar + * @return {Bounds} bounds of the bar + * @private + */ +function getBarBounds(bar) { + var vm = bar._view; + var x1, x2, y1, y2; + + if (isVertical(bar)) { + // vertical + var halfWidth = vm.width / 2; + x1 = vm.x - halfWidth; + x2 = vm.x + halfWidth; + y1 = Math.min(vm.y, vm.base); + y2 = Math.max(vm.y, vm.base); + } else { + // horizontal bar + var halfHeight = vm.height / 2; + x1 = Math.min(vm.x, vm.base); + x2 = Math.max(vm.x, vm.base); + y1 = vm.y - halfHeight; + y2 = vm.y + halfHeight; + } + + return { + left: x1, + top: y1, + right: x2, + bottom: y2 + }; +} + +module.exports = Element.extend({ + draw: function() { + var ctx = this._chart.ctx; + var vm = this._view; + var left, right, top, bottom, signX, signY, borderSkipped; + var borderWidth = vm.borderWidth; + + if (!vm.horizontal) { + // bar + left = vm.x - vm.width / 2; + right = vm.x + vm.width / 2; + top = vm.y; + bottom = vm.base; + signX = 1; + signY = bottom > top ? 1 : -1; + borderSkipped = vm.borderSkipped || 'bottom'; + } else { + // horizontal bar + left = vm.base; + right = vm.x; + top = vm.y - vm.height / 2; + bottom = vm.y + vm.height / 2; + signX = right > left ? 1 : -1; + signY = 1; + borderSkipped = vm.borderSkipped || 'left'; + } + + // Canvas doesn't allow us to stroke inside the width so we can + // adjust the sizes to fit if we're setting a stroke on the line + if (borderWidth) { + // borderWidth shold be less than bar width and bar height. + var barSize = Math.min(Math.abs(left - right), Math.abs(top - bottom)); + borderWidth = borderWidth > barSize ? barSize : borderWidth; + var halfStroke = borderWidth / 2; + // Adjust borderWidth when bar top position is near vm.base(zero). + var borderLeft = left + (borderSkipped !== 'left' ? halfStroke * signX : 0); + var borderRight = right + (borderSkipped !== 'right' ? -halfStroke * signX : 0); + var borderTop = top + (borderSkipped !== 'top' ? halfStroke * signY : 0); + var borderBottom = bottom + (borderSkipped !== 'bottom' ? -halfStroke * signY : 0); + // not become a vertical line? + if (borderLeft !== borderRight) { + top = borderTop; + bottom = borderBottom; + } + // not become a horizontal line? + if (borderTop !== borderBottom) { + left = borderLeft; + right = borderRight; + } + } + + ctx.beginPath(); + ctx.fillStyle = vm.backgroundColor; + ctx.strokeStyle = vm.borderColor; + ctx.lineWidth = borderWidth; + + // Corner points, from bottom-left to bottom-right clockwise + // | 1 2 | + // | 0 3 | + var corners = [ + [left, bottom], + [left, top], + [right, top], + [right, bottom] + ]; + + // Find first (starting) corner with fallback to 'bottom' + var borders = ['bottom', 'left', 'top', 'right']; + var startCorner = borders.indexOf(borderSkipped, 0); + if (startCorner === -1) { + startCorner = 0; + } + + function cornerAt(index) { + return corners[(startCorner + index) % 4]; + } + + // Draw rectangle from 'startCorner' + var corner = cornerAt(0); + ctx.moveTo(corner[0], corner[1]); + + for (var i = 1; i < 4; i++) { + corner = cornerAt(i); + ctx.lineTo(corner[0], corner[1]); + } + + ctx.fill(); + if (borderWidth) { + ctx.stroke(); + } + }, + + height: function() { + var vm = this._view; + return vm.base - vm.y; + }, + + inRange: function(mouseX, mouseY) { + var inRange = false; + + if (this._view) { + var bounds = getBarBounds(this); + inRange = mouseX >= bounds.left && mouseX <= bounds.right && mouseY >= bounds.top && mouseY <= bounds.bottom; + } + + return inRange; + }, + + inLabelRange: function(mouseX, mouseY) { + var me = this; + if (!me._view) { + return false; + } + + var inRange = false; + var bounds = getBarBounds(me); + + if (isVertical(me)) { + inRange = mouseX >= bounds.left && mouseX <= bounds.right; + } else { + inRange = mouseY >= bounds.top && mouseY <= bounds.bottom; + } + + return inRange; + }, + + inXRange: function(mouseX) { + var bounds = getBarBounds(this); + return mouseX >= bounds.left && mouseX <= bounds.right; + }, + + inYRange: function(mouseY) { + var bounds = getBarBounds(this); + return mouseY >= bounds.top && mouseY <= bounds.bottom; + }, + + getCenterPoint: function() { + var vm = this._view; + var x, y; + if (isVertical(this)) { + x = vm.x; + y = (vm.y + vm.base) / 2; + } else { + x = (vm.x + vm.base) / 2; + y = vm.y; + } + + return {x: x, y: y}; + }, + + getArea: function() { + var vm = this._view; + return vm.width * Math.abs(vm.y - vm.base); + }, + + tooltipPosition: function() { + var vm = this._view; + return { + x: vm.x, + y: vm.y + }; + } +}); + +},{"25":25,"26":26}],40:[function(require,module,exports){ +'use strict'; + +module.exports = {}; +module.exports.Arc = require(36); +module.exports.Line = require(37); +module.exports.Point = require(38); +module.exports.Rectangle = require(39); + +},{"36":36,"37":37,"38":38,"39":39}],41:[function(require,module,exports){ +'use strict'; + +var helpers = require(42); + +/** + * @namespace Chart.helpers.canvas + */ +var exports = module.exports = { + /** + * Clears the entire canvas associated to the given `chart`. + * @param {Chart} chart - The chart for which to clear the canvas. + */ + clear: function(chart) { + chart.ctx.clearRect(0, 0, chart.width, chart.height); + }, + + /** + * Creates a "path" for a rectangle with rounded corners at position (x, y) with a + * given size (width, height) and the same `radius` for all corners. + * @param {CanvasRenderingContext2D} ctx - The canvas 2D Context. + * @param {Number} x - The x axis of the coordinate for the rectangle starting point. + * @param {Number} y - The y axis of the coordinate for the rectangle starting point. + * @param {Number} width - The rectangle's width. + * @param {Number} height - The rectangle's height. + * @param {Number} radius - The rounded amount (in pixels) for the four corners. + * @todo handle `radius` as top-left, top-right, bottom-right, bottom-left array/object? + */ + roundedRect: function(ctx, x, y, width, height, radius) { + if (radius) { + var rx = Math.min(radius, width / 2); + var ry = Math.min(radius, height / 2); + + ctx.moveTo(x + rx, y); + ctx.lineTo(x + width - rx, y); + ctx.quadraticCurveTo(x + width, y, x + width, y + ry); + ctx.lineTo(x + width, y + height - ry); + ctx.quadraticCurveTo(x + width, y + height, x + width - rx, y + height); + ctx.lineTo(x + rx, y + height); + ctx.quadraticCurveTo(x, y + height, x, y + height - ry); + ctx.lineTo(x, y + ry); + ctx.quadraticCurveTo(x, y, x + rx, y); + } else { + ctx.rect(x, y, width, height); + } + }, + + drawPoint: function(ctx, style, radius, x, y) { + var type, edgeLength, xOffset, yOffset, height, size; + + if (style && typeof style === 'object') { + type = style.toString(); + if (type === '[object HTMLImageElement]' || type === '[object HTMLCanvasElement]') { + ctx.drawImage(style, x - style.width / 2, y - style.height / 2, style.width, style.height); + return; + } + } + + if (isNaN(radius) || radius <= 0) { + return; + } + + switch (style) { + // Default includes circle + default: + ctx.beginPath(); + ctx.arc(x, y, radius, 0, Math.PI * 2); + ctx.closePath(); + ctx.fill(); + break; + case 'triangle': + ctx.beginPath(); + edgeLength = 3 * radius / Math.sqrt(3); + height = edgeLength * Math.sqrt(3) / 2; + ctx.moveTo(x - edgeLength / 2, y + height / 3); + ctx.lineTo(x + edgeLength / 2, y + height / 3); + ctx.lineTo(x, y - 2 * height / 3); + ctx.closePath(); + ctx.fill(); + break; + case 'rect': + size = 1 / Math.SQRT2 * radius; + ctx.beginPath(); + ctx.fillRect(x - size, y - size, 2 * size, 2 * size); + ctx.strokeRect(x - size, y - size, 2 * size, 2 * size); + break; + case 'rectRounded': + var offset = radius / Math.SQRT2; + var leftX = x - offset; + var topY = y - offset; + var sideSize = Math.SQRT2 * radius; + ctx.beginPath(); + this.roundedRect(ctx, leftX, topY, sideSize, sideSize, radius / 2); + ctx.closePath(); + ctx.fill(); + break; + case 'rectRot': + size = 1 / Math.SQRT2 * radius; + ctx.beginPath(); + ctx.moveTo(x - size, y); + ctx.lineTo(x, y + size); + ctx.lineTo(x + size, y); + ctx.lineTo(x, y - size); + ctx.closePath(); + ctx.fill(); + break; + case 'cross': + ctx.beginPath(); + ctx.moveTo(x, y + radius); + ctx.lineTo(x, y - radius); + ctx.moveTo(x - radius, y); + ctx.lineTo(x + radius, y); + ctx.closePath(); + break; + case 'crossRot': + ctx.beginPath(); + xOffset = Math.cos(Math.PI / 4) * radius; + yOffset = Math.sin(Math.PI / 4) * radius; + ctx.moveTo(x - xOffset, y - yOffset); + ctx.lineTo(x + xOffset, y + yOffset); + ctx.moveTo(x - xOffset, y + yOffset); + ctx.lineTo(x + xOffset, y - yOffset); + ctx.closePath(); + break; + case 'star': + ctx.beginPath(); + ctx.moveTo(x, y + radius); + ctx.lineTo(x, y - radius); + ctx.moveTo(x - radius, y); + ctx.lineTo(x + radius, y); + xOffset = Math.cos(Math.PI / 4) * radius; + yOffset = Math.sin(Math.PI / 4) * radius; + ctx.moveTo(x - xOffset, y - yOffset); + ctx.lineTo(x + xOffset, y + yOffset); + ctx.moveTo(x - xOffset, y + yOffset); + ctx.lineTo(x + xOffset, y - yOffset); + ctx.closePath(); + break; + case 'line': + ctx.beginPath(); + ctx.moveTo(x - radius, y); + ctx.lineTo(x + radius, y); + ctx.closePath(); + break; + case 'dash': + ctx.beginPath(); + ctx.moveTo(x, y); + ctx.lineTo(x + radius, y); + ctx.closePath(); + break; + } + + ctx.stroke(); + }, + + clipArea: function(ctx, area) { + ctx.save(); + ctx.beginPath(); + ctx.rect(area.left, area.top, area.right - area.left, area.bottom - area.top); + ctx.clip(); + }, + + unclipArea: function(ctx) { + ctx.restore(); + }, + + lineTo: function(ctx, previous, target, flip) { + if (target.steppedLine) { + if ((target.steppedLine === 'after' && !flip) || (target.steppedLine !== 'after' && flip)) { + ctx.lineTo(previous.x, target.y); + } else { + ctx.lineTo(target.x, previous.y); + } + ctx.lineTo(target.x, target.y); + return; + } + + if (!target.tension) { + ctx.lineTo(target.x, target.y); + return; + } + + ctx.bezierCurveTo( + flip ? previous.controlPointPreviousX : previous.controlPointNextX, + flip ? previous.controlPointPreviousY : previous.controlPointNextY, + flip ? target.controlPointNextX : target.controlPointPreviousX, + flip ? target.controlPointNextY : target.controlPointPreviousY, + target.x, + target.y); + } +}; + +// DEPRECATIONS + +/** + * Provided for backward compatibility, use Chart.helpers.canvas.clear instead. + * @namespace Chart.helpers.clear + * @deprecated since version 2.7.0 + * @todo remove at version 3 + * @private + */ +helpers.clear = exports.clear; + +/** + * Provided for backward compatibility, use Chart.helpers.canvas.roundedRect instead. + * @namespace Chart.helpers.drawRoundedRectangle + * @deprecated since version 2.7.0 + * @todo remove at version 3 + * @private + */ +helpers.drawRoundedRectangle = function(ctx) { + ctx.beginPath(); + exports.roundedRect.apply(exports, arguments); + ctx.closePath(); +}; + +},{"42":42}],42:[function(require,module,exports){ +'use strict'; + +/** + * @namespace Chart.helpers + */ +var helpers = { + /** + * An empty function that can be used, for example, for optional callback. + */ + noop: function() {}, + + /** + * Returns a unique id, sequentially generated from a global variable. + * @returns {Number} + * @function + */ + uid: (function() { + var id = 0; + return function() { + return id++; + }; + }()), + + /** + * Returns true if `value` is neither null nor undefined, else returns false. + * @param {*} value - The value to test. + * @returns {Boolean} + * @since 2.7.0 + */ + isNullOrUndef: function(value) { + return value === null || typeof value === 'undefined'; + }, + + /** + * Returns true if `value` is an array, else returns false. + * @param {*} value - The value to test. + * @returns {Boolean} + * @function + */ + isArray: Array.isArray ? Array.isArray : function(value) { + return Object.prototype.toString.call(value) === '[object Array]'; + }, + + /** + * Returns true if `value` is an object (excluding null), else returns false. + * @param {*} value - The value to test. + * @returns {Boolean} + * @since 2.7.0 + */ + isObject: function(value) { + return value !== null && Object.prototype.toString.call(value) === '[object Object]'; + }, + + /** + * Returns `value` if defined, else returns `defaultValue`. + * @param {*} value - The value to return if defined. + * @param {*} defaultValue - The value to return if `value` is undefined. + * @returns {*} + */ + valueOrDefault: function(value, defaultValue) { + return typeof value === 'undefined' ? defaultValue : value; + }, + + /** + * Returns value at the given `index` in array if defined, else returns `defaultValue`. + * @param {Array} value - The array to lookup for value at `index`. + * @param {Number} index - The index in `value` to lookup for value. + * @param {*} defaultValue - The value to return if `value[index]` is undefined. + * @returns {*} + */ + valueAtIndexOrDefault: function(value, index, defaultValue) { + return helpers.valueOrDefault(helpers.isArray(value) ? value[index] : value, defaultValue); + }, + + /** + * Calls `fn` with the given `args` in the scope defined by `thisArg` and returns the + * value returned by `fn`. If `fn` is not a function, this method returns undefined. + * @param {Function} fn - The function to call. + * @param {Array|undefined|null} args - The arguments with which `fn` should be called. + * @param {Object} [thisArg] - The value of `this` provided for the call to `fn`. + * @returns {*} + */ + callback: function(fn, args, thisArg) { + if (fn && typeof fn.call === 'function') { + return fn.apply(thisArg, args); + } + }, + + /** + * Note(SB) for performance sake, this method should only be used when loopable type + * is unknown or in none intensive code (not called often and small loopable). Else + * it's preferable to use a regular for() loop and save extra function calls. + * @param {Object|Array} loopable - The object or array to be iterated. + * @param {Function} fn - The function to call for each item. + * @param {Object} [thisArg] - The value of `this` provided for the call to `fn`. + * @param {Boolean} [reverse] - If true, iterates backward on the loopable. + */ + each: function(loopable, fn, thisArg, reverse) { + var i, len, keys; + if (helpers.isArray(loopable)) { + len = loopable.length; + if (reverse) { + for (i = len - 1; i >= 0; i--) { + fn.call(thisArg, loopable[i], i); + } + } else { + for (i = 0; i < len; i++) { + fn.call(thisArg, loopable[i], i); + } + } + } else if (helpers.isObject(loopable)) { + keys = Object.keys(loopable); + len = keys.length; + for (i = 0; i < len; i++) { + fn.call(thisArg, loopable[keys[i]], keys[i]); + } + } + }, + + /** + * Returns true if the `a0` and `a1` arrays have the same content, else returns false. + * @see http://stackoverflow.com/a/14853974 + * @param {Array} a0 - The array to compare + * @param {Array} a1 - The array to compare + * @returns {Boolean} + */ + arrayEquals: function(a0, a1) { + var i, ilen, v0, v1; + + if (!a0 || !a1 || a0.length !== a1.length) { + return false; + } + + for (i = 0, ilen = a0.length; i < ilen; ++i) { + v0 = a0[i]; + v1 = a1[i]; + + if (v0 instanceof Array && v1 instanceof Array) { + if (!helpers.arrayEquals(v0, v1)) { + return false; + } + } else if (v0 !== v1) { + // NOTE: two different object instances will never be equal: {x:20} != {x:20} + return false; + } + } + + return true; + }, + + /** + * Returns a deep copy of `source` without keeping references on objects and arrays. + * @param {*} source - The value to clone. + * @returns {*} + */ + clone: function(source) { + if (helpers.isArray(source)) { + return source.map(helpers.clone); + } + + if (helpers.isObject(source)) { + var target = {}; + var keys = Object.keys(source); + var klen = keys.length; + var k = 0; + + for (; k < klen; ++k) { + target[keys[k]] = helpers.clone(source[keys[k]]); + } + + return target; + } + + return source; + }, + + /** + * The default merger when Chart.helpers.merge is called without merger option. + * Note(SB): this method is also used by configMerge and scaleMerge as fallback. + * @private + */ + _merger: function(key, target, source, options) { + var tval = target[key]; + var sval = source[key]; + + if (helpers.isObject(tval) && helpers.isObject(sval)) { + helpers.merge(tval, sval, options); + } else { + target[key] = helpers.clone(sval); + } + }, + + /** + * Merges source[key] in target[key] only if target[key] is undefined. + * @private + */ + _mergerIf: function(key, target, source) { + var tval = target[key]; + var sval = source[key]; + + if (helpers.isObject(tval) && helpers.isObject(sval)) { + helpers.mergeIf(tval, sval); + } else if (!target.hasOwnProperty(key)) { + target[key] = helpers.clone(sval); + } + }, + + /** + * Recursively deep copies `source` properties into `target` with the given `options`. + * IMPORTANT: `target` is not cloned and will be updated with `source` properties. + * @param {Object} target - The target object in which all sources are merged into. + * @param {Object|Array(Object)} source - Object(s) to merge into `target`. + * @param {Object} [options] - Merging options: + * @param {Function} [options.merger] - The merge method (key, target, source, options) + * @returns {Object} The `target` object. + */ + merge: function(target, source, options) { + var sources = helpers.isArray(source) ? source : [source]; + var ilen = sources.length; + var merge, i, keys, klen, k; + + if (!helpers.isObject(target)) { + return target; + } + + options = options || {}; + merge = options.merger || helpers._merger; + + for (i = 0; i < ilen; ++i) { + source = sources[i]; + if (!helpers.isObject(source)) { + continue; + } + + keys = Object.keys(source); + for (k = 0, klen = keys.length; k < klen; ++k) { + merge(keys[k], target, source, options); + } + } + + return target; + }, + + /** + * Recursively deep copies `source` properties into `target` *only* if not defined in target. + * IMPORTANT: `target` is not cloned and will be updated with `source` properties. + * @param {Object} target - The target object in which all sources are merged into. + * @param {Object|Array(Object)} source - Object(s) to merge into `target`. + * @returns {Object} The `target` object. + */ + mergeIf: function(target, source) { + return helpers.merge(target, source, {merger: helpers._mergerIf}); + }, + + /** + * Applies the contents of two or more objects together into the first object. + * @param {Object} target - The target object in which all objects are merged into. + * @param {Object} arg1 - Object containing additional properties to merge in target. + * @param {Object} argN - Additional objects containing properties to merge in target. + * @returns {Object} The `target` object. + */ + extend: function(target) { + var setFn = function(value, key) { + target[key] = value; + }; + for (var i = 1, ilen = arguments.length; i < ilen; ++i) { + helpers.each(arguments[i], setFn); + } + return target; + }, + + /** + * Basic javascript inheritance based on the model created in Backbone.js + */ + inherits: function(extensions) { + var me = this; + var ChartElement = (extensions && extensions.hasOwnProperty('constructor')) ? extensions.constructor : function() { + return me.apply(this, arguments); + }; + + var Surrogate = function() { + this.constructor = ChartElement; + }; + + Surrogate.prototype = me.prototype; + ChartElement.prototype = new Surrogate(); + ChartElement.extend = helpers.inherits; + + if (extensions) { + helpers.extend(ChartElement.prototype, extensions); + } + + ChartElement.__super__ = me.prototype; + return ChartElement; + } +}; + +module.exports = helpers; + +// DEPRECATIONS + +/** + * Provided for backward compatibility, use Chart.helpers.callback instead. + * @function Chart.helpers.callCallback + * @deprecated since version 2.6.0 + * @todo remove at version 3 + * @private + */ +helpers.callCallback = helpers.callback; + +/** + * Provided for backward compatibility, use Array.prototype.indexOf instead. + * Array.prototype.indexOf compatibility: Chrome, Opera, Safari, FF1.5+, IE9+ + * @function Chart.helpers.indexOf + * @deprecated since version 2.7.0 + * @todo remove at version 3 + * @private + */ +helpers.indexOf = function(array, item, fromIndex) { + return Array.prototype.indexOf.call(array, item, fromIndex); +}; + +/** + * Provided for backward compatibility, use Chart.helpers.valueOrDefault instead. + * @function Chart.helpers.getValueOrDefault + * @deprecated since version 2.7.0 + * @todo remove at version 3 + * @private + */ +helpers.getValueOrDefault = helpers.valueOrDefault; + +/** + * Provided for backward compatibility, use Chart.helpers.valueAtIndexOrDefault instead. + * @function Chart.helpers.getValueAtIndexOrDefault + * @deprecated since version 2.7.0 + * @todo remove at version 3 + * @private + */ +helpers.getValueAtIndexOrDefault = helpers.valueAtIndexOrDefault; + +},{}],43:[function(require,module,exports){ +'use strict'; + +var helpers = require(42); + +/** + * Easing functions adapted from Robert Penner's easing equations. + * @namespace Chart.helpers.easingEffects + * @see http://www.robertpenner.com/easing/ + */ +var effects = { + linear: function(t) { + return t; + }, + + easeInQuad: function(t) { + return t * t; + }, + + easeOutQuad: function(t) { + return -t * (t - 2); + }, + + easeInOutQuad: function(t) { + if ((t /= 0.5) < 1) { + return 0.5 * t * t; + } + return -0.5 * ((--t) * (t - 2) - 1); + }, + + easeInCubic: function(t) { + return t * t * t; + }, + + easeOutCubic: function(t) { + return (t = t - 1) * t * t + 1; + }, + + easeInOutCubic: function(t) { + if ((t /= 0.5) < 1) { + return 0.5 * t * t * t; + } + return 0.5 * ((t -= 2) * t * t + 2); + }, + + easeInQuart: function(t) { + return t * t * t * t; + }, + + easeOutQuart: function(t) { + return -((t = t - 1) * t * t * t - 1); + }, + + easeInOutQuart: function(t) { + if ((t /= 0.5) < 1) { + return 0.5 * t * t * t * t; + } + return -0.5 * ((t -= 2) * t * t * t - 2); + }, + + easeInQuint: function(t) { + return t * t * t * t * t; + }, + + easeOutQuint: function(t) { + return (t = t - 1) * t * t * t * t + 1; + }, + + easeInOutQuint: function(t) { + if ((t /= 0.5) < 1) { + return 0.5 * t * t * t * t * t; + } + return 0.5 * ((t -= 2) * t * t * t * t + 2); + }, + + easeInSine: function(t) { + return -Math.cos(t * (Math.PI / 2)) + 1; + }, + + easeOutSine: function(t) { + return Math.sin(t * (Math.PI / 2)); + }, + + easeInOutSine: function(t) { + return -0.5 * (Math.cos(Math.PI * t) - 1); + }, + + easeInExpo: function(t) { + return (t === 0) ? 0 : Math.pow(2, 10 * (t - 1)); + }, + + easeOutExpo: function(t) { + return (t === 1) ? 1 : -Math.pow(2, -10 * t) + 1; + }, + + easeInOutExpo: function(t) { + if (t === 0) { + return 0; + } + if (t === 1) { + return 1; + } + if ((t /= 0.5) < 1) { + return 0.5 * Math.pow(2, 10 * (t - 1)); + } + return 0.5 * (-Math.pow(2, -10 * --t) + 2); + }, + + easeInCirc: function(t) { + if (t >= 1) { + return t; + } + return -(Math.sqrt(1 - t * t) - 1); + }, + + easeOutCirc: function(t) { + return Math.sqrt(1 - (t = t - 1) * t); + }, + + easeInOutCirc: function(t) { + if ((t /= 0.5) < 1) { + return -0.5 * (Math.sqrt(1 - t * t) - 1); + } + return 0.5 * (Math.sqrt(1 - (t -= 2) * t) + 1); + }, + + easeInElastic: function(t) { + var s = 1.70158; + var p = 0; + var a = 1; + if (t === 0) { + return 0; + } + if (t === 1) { + return 1; + } + if (!p) { + p = 0.3; + } + if (a < 1) { + a = 1; + s = p / 4; + } else { + s = p / (2 * Math.PI) * Math.asin(1 / a); + } + return -(a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t - s) * (2 * Math.PI) / p)); + }, + + easeOutElastic: function(t) { + var s = 1.70158; + var p = 0; + var a = 1; + if (t === 0) { + return 0; + } + if (t === 1) { + return 1; + } + if (!p) { + p = 0.3; + } + if (a < 1) { + a = 1; + s = p / 4; + } else { + s = p / (2 * Math.PI) * Math.asin(1 / a); + } + return a * Math.pow(2, -10 * t) * Math.sin((t - s) * (2 * Math.PI) / p) + 1; + }, + + easeInOutElastic: function(t) { + var s = 1.70158; + var p = 0; + var a = 1; + if (t === 0) { + return 0; + } + if ((t /= 0.5) === 2) { + return 1; + } + if (!p) { + p = 0.45; + } + if (a < 1) { + a = 1; + s = p / 4; + } else { + s = p / (2 * Math.PI) * Math.asin(1 / a); + } + if (t < 1) { + return -0.5 * (a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t - s) * (2 * Math.PI) / p)); + } + return a * Math.pow(2, -10 * (t -= 1)) * Math.sin((t - s) * (2 * Math.PI) / p) * 0.5 + 1; + }, + easeInBack: function(t) { + var s = 1.70158; + return t * t * ((s + 1) * t - s); + }, + + easeOutBack: function(t) { + var s = 1.70158; + return (t = t - 1) * t * ((s + 1) * t + s) + 1; + }, + + easeInOutBack: function(t) { + var s = 1.70158; + if ((t /= 0.5) < 1) { + return 0.5 * (t * t * (((s *= (1.525)) + 1) * t - s)); + } + return 0.5 * ((t -= 2) * t * (((s *= (1.525)) + 1) * t + s) + 2); + }, + + easeInBounce: function(t) { + return 1 - effects.easeOutBounce(1 - t); + }, + + easeOutBounce: function(t) { + if (t < (1 / 2.75)) { + return 7.5625 * t * t; + } + if (t < (2 / 2.75)) { + return 7.5625 * (t -= (1.5 / 2.75)) * t + 0.75; + } + if (t < (2.5 / 2.75)) { + return 7.5625 * (t -= (2.25 / 2.75)) * t + 0.9375; + } + return 7.5625 * (t -= (2.625 / 2.75)) * t + 0.984375; + }, + + easeInOutBounce: function(t) { + if (t < 0.5) { + return effects.easeInBounce(t * 2) * 0.5; + } + return effects.easeOutBounce(t * 2 - 1) * 0.5 + 0.5; + } +}; + +module.exports = { + effects: effects +}; + +// DEPRECATIONS + +/** + * Provided for backward compatibility, use Chart.helpers.easing.effects instead. + * @function Chart.helpers.easingEffects + * @deprecated since version 2.7.0 + * @todo remove at version 3 + * @private + */ +helpers.easingEffects = effects; + +},{"42":42}],44:[function(require,module,exports){ +'use strict'; + +var helpers = require(42); + +/** + * @alias Chart.helpers.options + * @namespace + */ +module.exports = { + /** + * Converts the given line height `value` in pixels for a specific font `size`. + * @param {Number|String} value - The lineHeight to parse (eg. 1.6, '14px', '75%', '1.6em'). + * @param {Number} size - The font size (in pixels) used to resolve relative `value`. + * @returns {Number} The effective line height in pixels (size * 1.2 if value is invalid). + * @see https://developer.mozilla.org/en-US/docs/Web/CSS/line-height + * @since 2.7.0 + */ + toLineHeight: function(value, size) { + var matches = ('' + value).match(/^(normal|(\d+(?:\.\d+)?)(px|em|%)?)$/); + if (!matches || matches[1] === 'normal') { + return size * 1.2; + } + + value = +matches[2]; + + switch (matches[3]) { + case 'px': + return value; + case '%': + value /= 100; + break; + default: + break; + } + + return size * value; + }, + + /** + * Converts the given value into a padding object with pre-computed width/height. + * @param {Number|Object} value - If a number, set the value to all TRBL component, + * else, if and object, use defined properties and sets undefined ones to 0. + * @returns {Object} The padding values (top, right, bottom, left, width, height) + * @since 2.7.0 + */ + toPadding: function(value) { + var t, r, b, l; + + if (helpers.isObject(value)) { + t = +value.top || 0; + r = +value.right || 0; + b = +value.bottom || 0; + l = +value.left || 0; + } else { + t = r = b = l = +value || 0; + } + + return { + top: t, + right: r, + bottom: b, + left: l, + height: t + b, + width: l + r + }; + }, + + /** + * Evaluates the given `inputs` sequentially and returns the first defined value. + * @param {Array[]} inputs - An array of values, falling back to the last value. + * @param {Object} [context] - If defined and the current value is a function, the value + * is called with `context` as first argument and the result becomes the new input. + * @param {Number} [index] - If defined and the current value is an array, the value + * at `index` become the new input. + * @since 2.7.0 + */ + resolve: function(inputs, context, index) { + var i, ilen, value; + + for (i = 0, ilen = inputs.length; i < ilen; ++i) { + value = inputs[i]; + if (value === undefined) { + continue; + } + if (context !== undefined && typeof value === 'function') { + value = value(context); + } + if (index !== undefined && helpers.isArray(value)) { + value = value[index]; + } + if (value !== undefined) { + return value; + } + } + } +}; + +},{"42":42}],45:[function(require,module,exports){ +'use strict'; + +module.exports = require(42); +module.exports.easing = require(43); +module.exports.canvas = require(41); +module.exports.options = require(44); + +},{"41":41,"42":42,"43":43,"44":44}],46:[function(require,module,exports){ +/** + * Platform fallback implementation (minimal). + * @see https://github.com/chartjs/Chart.js/pull/4591#issuecomment-319575939 + */ + +module.exports = { + acquireContext: function(item) { + if (item && item.canvas) { + // Support for any object associated to a canvas (including a context2d) + item = item.canvas; + } + + return item && item.getContext('2d') || null; + } +}; + +},{}],47:[function(require,module,exports){ +/** + * Chart.Platform implementation for targeting a web browser + */ + +'use strict'; + +var helpers = require(45); + +var EXPANDO_KEY = '$chartjs'; +var CSS_PREFIX = 'chartjs-'; +var CSS_RENDER_MONITOR = CSS_PREFIX + 'render-monitor'; +var CSS_RENDER_ANIMATION = CSS_PREFIX + 'render-animation'; +var ANIMATION_START_EVENTS = ['animationstart', 'webkitAnimationStart']; + +/** + * DOM event types -> Chart.js event types. + * Note: only events with different types are mapped. + * @see https://developer.mozilla.org/en-US/docs/Web/Events + */ +var EVENT_TYPES = { + touchstart: 'mousedown', + touchmove: 'mousemove', + touchend: 'mouseup', + pointerenter: 'mouseenter', + pointerdown: 'mousedown', + pointermove: 'mousemove', + pointerup: 'mouseup', + pointerleave: 'mouseout', + pointerout: 'mouseout' +}; + +/** + * The "used" size is the final value of a dimension property after all calculations have + * been performed. This method uses the computed style of `element` but returns undefined + * if the computed style is not expressed in pixels. That can happen in some cases where + * `element` has a size relative to its parent and this last one is not yet displayed, + * for example because of `display: none` on a parent node. + * @see https://developer.mozilla.org/en-US/docs/Web/CSS/used_value + * @returns {Number} Size in pixels or undefined if unknown. + */ +function readUsedSize(element, property) { + var value = helpers.getStyle(element, property); + var matches = value && value.match(/^(\d+)(\.\d+)?px$/); + return matches ? Number(matches[1]) : undefined; +} + +/** + * Initializes the canvas style and render size without modifying the canvas display size, + * since responsiveness is handled by the controller.resize() method. The config is used + * to determine the aspect ratio to apply in case no explicit height has been specified. + */ +function initCanvas(canvas, config) { + var style = canvas.style; + + // NOTE(SB) canvas.getAttribute('width') !== canvas.width: in the first case it + // returns null or '' if no explicit value has been set to the canvas attribute. + var renderHeight = canvas.getAttribute('height'); + var renderWidth = canvas.getAttribute('width'); + + // Chart.js modifies some canvas values that we want to restore on destroy + canvas[EXPANDO_KEY] = { + initial: { + height: renderHeight, + width: renderWidth, + style: { + display: style.display, + height: style.height, + width: style.width + } + } + }; + + // Force canvas to display as block to avoid extra space caused by inline + // elements, which would interfere with the responsive resize process. + // https://github.com/chartjs/Chart.js/issues/2538 + style.display = style.display || 'block'; + + if (renderWidth === null || renderWidth === '') { + var displayWidth = readUsedSize(canvas, 'width'); + if (displayWidth !== undefined) { + canvas.width = displayWidth; + } + } + + if (renderHeight === null || renderHeight === '') { + if (canvas.style.height === '') { + // If no explicit render height and style height, let's apply the aspect ratio, + // which one can be specified by the user but also by charts as default option + // (i.e. options.aspectRatio). If not specified, use canvas aspect ratio of 2. + canvas.height = canvas.width / (config.options.aspectRatio || 2); + } else { + var displayHeight = readUsedSize(canvas, 'height'); + if (displayWidth !== undefined) { + canvas.height = displayHeight; + } + } + } + + return canvas; +} + +/** + * Detects support for options object argument in addEventListener. + * https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#Safely_detecting_option_support + * @private + */ +var supportsEventListenerOptions = (function() { + var supports = false; + try { + var options = Object.defineProperty({}, 'passive', { + get: function() { + supports = true; + } + }); + window.addEventListener('e', null, options); + } catch (e) { + // continue regardless of error + } + return supports; +}()); + +// Default passive to true as expected by Chrome for 'touchstart' and 'touchend' events. +// https://github.com/chartjs/Chart.js/issues/4287 +var eventListenerOptions = supportsEventListenerOptions ? {passive: true} : false; + +function addEventListener(node, type, listener) { + node.addEventListener(type, listener, eventListenerOptions); +} + +function removeEventListener(node, type, listener) { + node.removeEventListener(type, listener, eventListenerOptions); +} + +function createEvent(type, chart, x, y, nativeEvent) { + return { + type: type, + chart: chart, + native: nativeEvent || null, + x: x !== undefined ? x : null, + y: y !== undefined ? y : null, + }; +} + +function fromNativeEvent(event, chart) { + var type = EVENT_TYPES[event.type] || event.type; + var pos = helpers.getRelativePosition(event, chart); + return createEvent(type, chart, pos.x, pos.y, event); +} + +function throttled(fn, thisArg) { + var ticking = false; + var args = []; + + return function() { + args = Array.prototype.slice.call(arguments); + thisArg = thisArg || this; + + if (!ticking) { + ticking = true; + helpers.requestAnimFrame.call(window, function() { + ticking = false; + fn.apply(thisArg, args); + }); + } + }; +} + +// Implementation based on https://github.com/marcj/css-element-queries +function createResizer(handler) { + var resizer = document.createElement('div'); + var cls = CSS_PREFIX + 'size-monitor'; + var maxSize = 1000000; + var style = + 'position:absolute;' + + 'left:0;' + + 'top:0;' + + 'right:0;' + + 'bottom:0;' + + 'overflow:hidden;' + + 'pointer-events:none;' + + 'visibility:hidden;' + + 'z-index:-1;'; + + resizer.style.cssText = style; + resizer.className = cls; + resizer.innerHTML = + '
' + + '
' + + '
' + + '
' + + '
' + + '
' + + '
' + + '
'; + + var expand = resizer.childNodes[0]; + var shrink = resizer.childNodes[1]; + + resizer._reset = function() { + expand.scrollLeft = maxSize; + expand.scrollTop = maxSize; + shrink.scrollLeft = maxSize; + shrink.scrollTop = maxSize; + }; + var onScroll = function() { + resizer._reset(); + handler(); + }; + + addEventListener(expand, 'scroll', onScroll.bind(expand, 'expand')); + addEventListener(shrink, 'scroll', onScroll.bind(shrink, 'shrink')); + + return resizer; +} + +// https://davidwalsh.name/detect-node-insertion +function watchForRender(node, handler) { + var expando = node[EXPANDO_KEY] || (node[EXPANDO_KEY] = {}); + var proxy = expando.renderProxy = function(e) { + if (e.animationName === CSS_RENDER_ANIMATION) { + handler(); + } + }; + + helpers.each(ANIMATION_START_EVENTS, function(type) { + addEventListener(node, type, proxy); + }); + + // #4737: Chrome might skip the CSS animation when the CSS_RENDER_MONITOR class + // is removed then added back immediately (same animation frame?). Accessing the + // `offsetParent` property will force a reflow and re-evaluate the CSS animation. + // https://gist.github.com/paulirish/5d52fb081b3570c81e3a#box-metrics + // https://github.com/chartjs/Chart.js/issues/4737 + expando.reflow = !!node.offsetParent; + + node.classList.add(CSS_RENDER_MONITOR); +} + +function unwatchForRender(node) { + var expando = node[EXPANDO_KEY] || {}; + var proxy = expando.renderProxy; + + if (proxy) { + helpers.each(ANIMATION_START_EVENTS, function(type) { + removeEventListener(node, type, proxy); + }); + + delete expando.renderProxy; + } + + node.classList.remove(CSS_RENDER_MONITOR); +} + +function addResizeListener(node, listener, chart) { + var expando = node[EXPANDO_KEY] || (node[EXPANDO_KEY] = {}); + + // Let's keep track of this added resizer and thus avoid DOM query when removing it. + var resizer = expando.resizer = createResizer(throttled(function() { + if (expando.resizer) { + return listener(createEvent('resize', chart)); + } + })); + + // The resizer needs to be attached to the node parent, so we first need to be + // sure that `node` is attached to the DOM before injecting the resizer element. + watchForRender(node, function() { + if (expando.resizer) { + var container = node.parentNode; + if (container && container !== resizer.parentNode) { + container.insertBefore(resizer, container.firstChild); + } + + // The container size might have changed, let's reset the resizer state. + resizer._reset(); + } + }); +} + +function removeResizeListener(node) { + var expando = node[EXPANDO_KEY] || {}; + var resizer = expando.resizer; + + delete expando.resizer; + unwatchForRender(node); + + if (resizer && resizer.parentNode) { + resizer.parentNode.removeChild(resizer); + } +} + +function injectCSS(platform, css) { + // http://stackoverflow.com/q/3922139 + var style = platform._style || document.createElement('style'); + if (!platform._style) { + platform._style = style; + css = '/* Chart.js */\n' + css; + style.setAttribute('type', 'text/css'); + document.getElementsByTagName('head')[0].appendChild(style); + } + + style.appendChild(document.createTextNode(css)); +} + +module.exports = { + /** + * This property holds whether this platform is enabled for the current environment. + * Currently used by platform.js to select the proper implementation. + * @private + */ + _enabled: typeof window !== 'undefined' && typeof document !== 'undefined', + + initialize: function() { + var keyframes = 'from{opacity:0.99}to{opacity:1}'; + + injectCSS(this, + // DOM rendering detection + // https://davidwalsh.name/detect-node-insertion + '@-webkit-keyframes ' + CSS_RENDER_ANIMATION + '{' + keyframes + '}' + + '@keyframes ' + CSS_RENDER_ANIMATION + '{' + keyframes + '}' + + '.' + CSS_RENDER_MONITOR + '{' + + '-webkit-animation:' + CSS_RENDER_ANIMATION + ' 0.001s;' + + 'animation:' + CSS_RENDER_ANIMATION + ' 0.001s;' + + '}' + ); + }, + + acquireContext: function(item, config) { + if (typeof item === 'string') { + item = document.getElementById(item); + } else if (item.length) { + // Support for array based queries (such as jQuery) + item = item[0]; + } + + if (item && item.canvas) { + // Support for any object associated to a canvas (including a context2d) + item = item.canvas; + } + + // To prevent canvas fingerprinting, some add-ons undefine the getContext + // method, for example: https://github.com/kkapsner/CanvasBlocker + // https://github.com/chartjs/Chart.js/issues/2807 + var context = item && item.getContext && item.getContext('2d'); + + // `instanceof HTMLCanvasElement/CanvasRenderingContext2D` fails when the item is + // inside an iframe or when running in a protected environment. We could guess the + // types from their toString() value but let's keep things flexible and assume it's + // a sufficient condition if the item has a context2D which has item as `canvas`. + // https://github.com/chartjs/Chart.js/issues/3887 + // https://github.com/chartjs/Chart.js/issues/4102 + // https://github.com/chartjs/Chart.js/issues/4152 + if (context && context.canvas === item) { + initCanvas(item, config); + return context; + } + + return null; + }, + + releaseContext: function(context) { + var canvas = context.canvas; + if (!canvas[EXPANDO_KEY]) { + return; + } + + var initial = canvas[EXPANDO_KEY].initial; + ['height', 'width'].forEach(function(prop) { + var value = initial[prop]; + if (helpers.isNullOrUndef(value)) { + canvas.removeAttribute(prop); + } else { + canvas.setAttribute(prop, value); + } + }); + + helpers.each(initial.style || {}, function(value, key) { + canvas.style[key] = value; + }); + + // The canvas render size might have been changed (and thus the state stack discarded), + // we can't use save() and restore() to restore the initial state. So make sure that at + // least the canvas context is reset to the default state by setting the canvas width. + // https://www.w3.org/TR/2011/WD-html5-20110525/the-canvas-element.html + canvas.width = canvas.width; + + delete canvas[EXPANDO_KEY]; + }, + + addEventListener: function(chart, type, listener) { + var canvas = chart.canvas; + if (type === 'resize') { + // Note: the resize event is not supported on all browsers. + addResizeListener(canvas, listener, chart); + return; + } + + var expando = listener[EXPANDO_KEY] || (listener[EXPANDO_KEY] = {}); + var proxies = expando.proxies || (expando.proxies = {}); + var proxy = proxies[chart.id + '_' + type] = function(event) { + listener(fromNativeEvent(event, chart)); + }; + + addEventListener(canvas, type, proxy); + }, + + removeEventListener: function(chart, type, listener) { + var canvas = chart.canvas; + if (type === 'resize') { + // Note: the resize event is not supported on all browsers. + removeResizeListener(canvas, listener); + return; + } + + var expando = listener[EXPANDO_KEY] || {}; + var proxies = expando.proxies || {}; + var proxy = proxies[chart.id + '_' + type]; + if (!proxy) { + return; + } + + removeEventListener(canvas, type, proxy); + } +}; + +// DEPRECATIONS + +/** + * Provided for backward compatibility, use EventTarget.addEventListener instead. + * EventTarget.addEventListener compatibility: Chrome, Opera 7, Safari, FF1.5+, IE9+ + * @see https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener + * @function Chart.helpers.addEvent + * @deprecated since version 2.7.0 + * @todo remove at version 3 + * @private + */ +helpers.addEvent = addEventListener; + +/** + * Provided for backward compatibility, use EventTarget.removeEventListener instead. + * EventTarget.removeEventListener compatibility: Chrome, Opera 7, Safari, FF1.5+, IE9+ + * @see https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/removeEventListener + * @function Chart.helpers.removeEvent + * @deprecated since version 2.7.0 + * @todo remove at version 3 + * @private + */ +helpers.removeEvent = removeEventListener; + +},{"45":45}],48:[function(require,module,exports){ +'use strict'; + +var helpers = require(45); +var basic = require(46); +var dom = require(47); + +// @TODO Make possible to select another platform at build time. +var implementation = dom._enabled ? dom : basic; + +/** + * @namespace Chart.platform + * @see https://chartjs.gitbooks.io/proposals/content/Platform.html + * @since 2.4.0 + */ +module.exports = helpers.extend({ + /** + * @since 2.7.0 + */ + initialize: function() {}, + + /** + * Called at chart construction time, returns a context2d instance implementing + * the [W3C Canvas 2D Context API standard]{@link https://www.w3.org/TR/2dcontext/}. + * @param {*} item - The native item from which to acquire context (platform specific) + * @param {Object} options - The chart options + * @returns {CanvasRenderingContext2D} context2d instance + */ + acquireContext: function() {}, + + /** + * Called at chart destruction time, releases any resources associated to the context + * previously returned by the acquireContext() method. + * @param {CanvasRenderingContext2D} context - The context2d instance + * @returns {Boolean} true if the method succeeded, else false + */ + releaseContext: function() {}, + + /** + * Registers the specified listener on the given chart. + * @param {Chart} chart - Chart from which to listen for event + * @param {String} type - The ({@link IEvent}) type to listen for + * @param {Function} listener - Receives a notification (an object that implements + * the {@link IEvent} interface) when an event of the specified type occurs. + */ + addEventListener: function() {}, + + /** + * Removes the specified listener previously registered with addEventListener. + * @param {Chart} chart -Chart from which to remove the listener + * @param {String} type - The ({@link IEvent}) type to remove + * @param {Function} listener - The listener function to remove from the event target. + */ + removeEventListener: function() {} + +}, implementation); + +/** + * @interface IPlatform + * Allows abstracting platform dependencies away from the chart + * @borrows Chart.platform.acquireContext as acquireContext + * @borrows Chart.platform.releaseContext as releaseContext + * @borrows Chart.platform.addEventListener as addEventListener + * @borrows Chart.platform.removeEventListener as removeEventListener + */ + +/** + * @interface IEvent + * @prop {String} type - The event type name, possible values are: + * 'contextmenu', 'mouseenter', 'mousedown', 'mousemove', 'mouseup', 'mouseout', + * 'click', 'dblclick', 'keydown', 'keypress', 'keyup' and 'resize' + * @prop {*} native - The original native event (null for emulated events, e.g. 'resize') + * @prop {Number} x - The mouse x position, relative to the canvas (null for incompatible events) + * @prop {Number} y - The mouse y position, relative to the canvas (null for incompatible events) + */ + +},{"45":45,"46":46,"47":47}],49:[function(require,module,exports){ +/** + * Plugin based on discussion from the following Chart.js issues: + * @see https://github.com/chartjs/Chart.js/issues/2380#issuecomment-279961569 + * @see https://github.com/chartjs/Chart.js/issues/2440#issuecomment-256461897 + */ + +'use strict'; + +var defaults = require(25); +var elements = require(40); +var helpers = require(45); + +defaults._set('global', { + plugins: { + filler: { + propagate: true + } + } +}); + +module.exports = function() { + + var mappers = { + dataset: function(source) { + var index = source.fill; + var chart = source.chart; + var meta = chart.getDatasetMeta(index); + var visible = meta && chart.isDatasetVisible(index); + var points = (visible && meta.dataset._children) || []; + var length = points.length || 0; + + return !length ? null : function(point, i) { + return (i < length && points[i]._view) || null; + }; + }, + + boundary: function(source) { + var boundary = source.boundary; + var x = boundary ? boundary.x : null; + var y = boundary ? boundary.y : null; + + return function(point) { + return { + x: x === null ? point.x : x, + y: y === null ? point.y : y, + }; + }; + } + }; + + // @todo if (fill[0] === '#') + function decodeFill(el, index, count) { + var model = el._model || {}; + var fill = model.fill; + var target; + + if (fill === undefined) { + fill = !!model.backgroundColor; + } + + if (fill === false || fill === null) { + return false; + } + + if (fill === true) { + return 'origin'; + } + + target = parseFloat(fill, 10); + if (isFinite(target) && Math.floor(target) === target) { + if (fill[0] === '-' || fill[0] === '+') { + target = index + target; + } + + if (target === index || target < 0 || target >= count) { + return false; + } + + return target; + } + + switch (fill) { + // compatibility + case 'bottom': + return 'start'; + case 'top': + return 'end'; + case 'zero': + return 'origin'; + // supported boundaries + case 'origin': + case 'start': + case 'end': + return fill; + // invalid fill values + default: + return false; + } + } + + function computeBoundary(source) { + var model = source.el._model || {}; + var scale = source.el._scale || {}; + var fill = source.fill; + var target = null; + var horizontal; + + if (isFinite(fill)) { + return null; + } + + // Backward compatibility: until v3, we still need to support boundary values set on + // the model (scaleTop, scaleBottom and scaleZero) because some external plugins and + // controllers might still use it (e.g. the Smith chart). + + if (fill === 'start') { + target = model.scaleBottom === undefined ? scale.bottom : model.scaleBottom; + } else if (fill === 'end') { + target = model.scaleTop === undefined ? scale.top : model.scaleTop; + } else if (model.scaleZero !== undefined) { + target = model.scaleZero; + } else if (scale.getBasePosition) { + target = scale.getBasePosition(); + } else if (scale.getBasePixel) { + target = scale.getBasePixel(); + } + + if (target !== undefined && target !== null) { + if (target.x !== undefined && target.y !== undefined) { + return target; + } + + if (typeof target === 'number' && isFinite(target)) { + horizontal = scale.isHorizontal(); + return { + x: horizontal ? target : null, + y: horizontal ? null : target + }; + } + } + + return null; + } + + function resolveTarget(sources, index, propagate) { + var source = sources[index]; + var fill = source.fill; + var visited = [index]; + var target; + + if (!propagate) { + return fill; + } + + while (fill !== false && visited.indexOf(fill) === -1) { + if (!isFinite(fill)) { + return fill; + } + + target = sources[fill]; + if (!target) { + return false; + } + + if (target.visible) { + return fill; + } + + visited.push(fill); + fill = target.fill; + } + + return false; + } + + function createMapper(source) { + var fill = source.fill; + var type = 'dataset'; + + if (fill === false) { + return null; + } + + if (!isFinite(fill)) { + type = 'boundary'; + } + + return mappers[type](source); + } + + function isDrawable(point) { + return point && !point.skip; + } + + function drawArea(ctx, curve0, curve1, len0, len1) { + var i; + + if (!len0 || !len1) { + return; + } + + // building first area curve (normal) + ctx.moveTo(curve0[0].x, curve0[0].y); + for (i = 1; i < len0; ++i) { + helpers.canvas.lineTo(ctx, curve0[i - 1], curve0[i]); + } + + // joining the two area curves + ctx.lineTo(curve1[len1 - 1].x, curve1[len1 - 1].y); + + // building opposite area curve (reverse) + for (i = len1 - 1; i > 0; --i) { + helpers.canvas.lineTo(ctx, curve1[i], curve1[i - 1], true); + } + } + + function doFill(ctx, points, mapper, view, color, loop) { + var count = points.length; + var span = view.spanGaps; + var curve0 = []; + var curve1 = []; + var len0 = 0; + var len1 = 0; + var i, ilen, index, p0, p1, d0, d1; + + ctx.beginPath(); + + for (i = 0, ilen = (count + !!loop); i < ilen; ++i) { + index = i % count; + p0 = points[index]._view; + p1 = mapper(p0, index, view); + d0 = isDrawable(p0); + d1 = isDrawable(p1); + + if (d0 && d1) { + len0 = curve0.push(p0); + len1 = curve1.push(p1); + } else if (len0 && len1) { + if (!span) { + drawArea(ctx, curve0, curve1, len0, len1); + len0 = len1 = 0; + curve0 = []; + curve1 = []; + } else { + if (d0) { + curve0.push(p0); + } + if (d1) { + curve1.push(p1); + } + } + } + } + + drawArea(ctx, curve0, curve1, len0, len1); + + ctx.closePath(); + ctx.fillStyle = color; + ctx.fill(); + } + + return { + id: 'filler', + + afterDatasetsUpdate: function(chart, options) { + var count = (chart.data.datasets || []).length; + var propagate = options.propagate; + var sources = []; + var meta, i, el, source; + + for (i = 0; i < count; ++i) { + meta = chart.getDatasetMeta(i); + el = meta.dataset; + source = null; + + if (el && el._model && el instanceof elements.Line) { + source = { + visible: chart.isDatasetVisible(i), + fill: decodeFill(el, i, count), + chart: chart, + el: el + }; + } + + meta.$filler = source; + sources.push(source); + } + + for (i = 0; i < count; ++i) { + source = sources[i]; + if (!source) { + continue; + } + + source.fill = resolveTarget(sources, i, propagate); + source.boundary = computeBoundary(source); + source.mapper = createMapper(source); + } + }, + + beforeDatasetDraw: function(chart, args) { + var meta = args.meta.$filler; + if (!meta) { + return; + } + + var ctx = chart.ctx; + var el = meta.el; + var view = el._view; + var points = el._children || []; + var mapper = meta.mapper; + var color = view.backgroundColor || defaults.global.defaultColor; + + if (mapper && color && points.length) { + helpers.canvas.clipArea(ctx, chart.chartArea); + doFill(ctx, points, mapper, view, color, el._loop); + helpers.canvas.unclipArea(ctx); + } + } + }; +}; + +},{"25":25,"40":40,"45":45}],50:[function(require,module,exports){ +'use strict'; + +var defaults = require(25); +var Element = require(26); +var helpers = require(45); + +defaults._set('global', { + legend: { + display: true, + position: 'top', + fullWidth: true, + reverse: false, + weight: 1000, + + // a callback that will handle + onClick: function(e, legendItem) { + var index = legendItem.datasetIndex; + var ci = this.chart; + var meta = ci.getDatasetMeta(index); + + // See controller.isDatasetVisible comment + meta.hidden = meta.hidden === null ? !ci.data.datasets[index].hidden : null; + + // We hid a dataset ... rerender the chart + ci.update(); + }, + + onHover: null, + + labels: { + boxWidth: 40, + padding: 10, + // Generates labels shown in the legend + // Valid properties to return: + // text : text to display + // fillStyle : fill of coloured box + // strokeStyle: stroke of coloured box + // hidden : if this legend item refers to a hidden item + // lineCap : cap style for line + // lineDash + // lineDashOffset : + // lineJoin : + // lineWidth : + generateLabels: function(chart) { + var data = chart.data; + return helpers.isArray(data.datasets) ? data.datasets.map(function(dataset, i) { + return { + text: dataset.label, + fillStyle: (!helpers.isArray(dataset.backgroundColor) ? dataset.backgroundColor : dataset.backgroundColor[0]), + hidden: !chart.isDatasetVisible(i), + lineCap: dataset.borderCapStyle, + lineDash: dataset.borderDash, + lineDashOffset: dataset.borderDashOffset, + lineJoin: dataset.borderJoinStyle, + lineWidth: dataset.borderWidth, + strokeStyle: dataset.borderColor, + pointStyle: dataset.pointStyle, + + // Below is extra data used for toggling the datasets + datasetIndex: i + }; + }, this) : []; + } + } + }, + + legendCallback: function(chart) { + var text = []; + text.push('
    '); + for (var i = 0; i < chart.data.datasets.length; i++) { + text.push('
  • '); + if (chart.data.datasets[i].label) { + text.push(chart.data.datasets[i].label); + } + text.push('
  • '); + } + text.push('
'); + return text.join(''); + } +}); + +module.exports = function(Chart) { + + var layout = Chart.layoutService; + var noop = helpers.noop; + + /** + * Helper function to get the box width based on the usePointStyle option + * @param labelopts {Object} the label options on the legend + * @param fontSize {Number} the label font size + * @return {Number} width of the color box area + */ + function getBoxWidth(labelOpts, fontSize) { + return labelOpts.usePointStyle ? + fontSize * Math.SQRT2 : + labelOpts.boxWidth; + } + + Chart.Legend = Element.extend({ + + initialize: function(config) { + helpers.extend(this, config); + + // Contains hit boxes for each dataset (in dataset order) + this.legendHitBoxes = []; + + // Are we in doughnut mode which has a different data type + this.doughnutMode = false; + }, + + // These methods are ordered by lifecycle. Utilities then follow. + // Any function defined here is inherited by all legend types. + // Any function can be extended by the legend type + + beforeUpdate: noop, + update: function(maxWidth, maxHeight, margins) { + var me = this; + + // Update Lifecycle - Probably don't want to ever extend or overwrite this function ;) + me.beforeUpdate(); + + // Absorb the master measurements + me.maxWidth = maxWidth; + me.maxHeight = maxHeight; + me.margins = margins; + + // Dimensions + me.beforeSetDimensions(); + me.setDimensions(); + me.afterSetDimensions(); + // Labels + me.beforeBuildLabels(); + me.buildLabels(); + me.afterBuildLabels(); + + // Fit + me.beforeFit(); + me.fit(); + me.afterFit(); + // + me.afterUpdate(); + + return me.minSize; + }, + afterUpdate: noop, + + // + + beforeSetDimensions: noop, + setDimensions: function() { + var me = this; + // Set the unconstrained dimension before label rotation + if (me.isHorizontal()) { + // Reset position before calculating rotation + me.width = me.maxWidth; + me.left = 0; + me.right = me.width; + } else { + me.height = me.maxHeight; + + // Reset position before calculating rotation + me.top = 0; + me.bottom = me.height; + } + + // Reset padding + me.paddingLeft = 0; + me.paddingTop = 0; + me.paddingRight = 0; + me.paddingBottom = 0; + + // Reset minSize + me.minSize = { + width: 0, + height: 0 + }; + }, + afterSetDimensions: noop, + + // + + beforeBuildLabels: noop, + buildLabels: function() { + var me = this; + var labelOpts = me.options.labels || {}; + var legendItems = helpers.callback(labelOpts.generateLabels, [me.chart], me) || []; + + if (labelOpts.filter) { + legendItems = legendItems.filter(function(item) { + return labelOpts.filter(item, me.chart.data); + }); + } + + if (me.options.reverse) { + legendItems.reverse(); + } + + me.legendItems = legendItems; + }, + afterBuildLabels: noop, + + // + + beforeFit: noop, + fit: function() { + var me = this; + var opts = me.options; + var labelOpts = opts.labels; + var display = opts.display; + + var ctx = me.ctx; + + var globalDefault = defaults.global; + var valueOrDefault = helpers.valueOrDefault; + var fontSize = valueOrDefault(labelOpts.fontSize, globalDefault.defaultFontSize); + var fontStyle = valueOrDefault(labelOpts.fontStyle, globalDefault.defaultFontStyle); + var fontFamily = valueOrDefault(labelOpts.fontFamily, globalDefault.defaultFontFamily); + var labelFont = helpers.fontString(fontSize, fontStyle, fontFamily); + + // Reset hit boxes + var hitboxes = me.legendHitBoxes = []; + + var minSize = me.minSize; + var isHorizontal = me.isHorizontal(); + + if (isHorizontal) { + minSize.width = me.maxWidth; // fill all the width + minSize.height = display ? 10 : 0; + } else { + minSize.width = display ? 10 : 0; + minSize.height = me.maxHeight; // fill all the height + } + + // Increase sizes here + if (display) { + ctx.font = labelFont; + + if (isHorizontal) { + // Labels + + // Width of each line of legend boxes. Labels wrap onto multiple lines when there are too many to fit on one + var lineWidths = me.lineWidths = [0]; + var totalHeight = me.legendItems.length ? fontSize + (labelOpts.padding) : 0; + + ctx.textAlign = 'left'; + ctx.textBaseline = 'top'; + + helpers.each(me.legendItems, function(legendItem, i) { + var boxWidth = getBoxWidth(labelOpts, fontSize); + var width = boxWidth + (fontSize / 2) + ctx.measureText(legendItem.text).width; + + if (lineWidths[lineWidths.length - 1] + width + labelOpts.padding >= me.width) { + totalHeight += fontSize + (labelOpts.padding); + lineWidths[lineWidths.length] = me.left; + } + + // Store the hitbox width and height here. Final position will be updated in `draw` + hitboxes[i] = { + left: 0, + top: 0, + width: width, + height: fontSize + }; + + lineWidths[lineWidths.length - 1] += width + labelOpts.padding; + }); + + minSize.height += totalHeight; + + } else { + var vPadding = labelOpts.padding; + var columnWidths = me.columnWidths = []; + var totalWidth = labelOpts.padding; + var currentColWidth = 0; + var currentColHeight = 0; + var itemHeight = fontSize + vPadding; + + helpers.each(me.legendItems, function(legendItem, i) { + var boxWidth = getBoxWidth(labelOpts, fontSize); + var itemWidth = boxWidth + (fontSize / 2) + ctx.measureText(legendItem.text).width; + + // If too tall, go to new column + if (currentColHeight + itemHeight > minSize.height) { + totalWidth += currentColWidth + labelOpts.padding; + columnWidths.push(currentColWidth); // previous column width + + currentColWidth = 0; + currentColHeight = 0; + } + + // Get max width + currentColWidth = Math.max(currentColWidth, itemWidth); + currentColHeight += itemHeight; + + // Store the hitbox width and height here. Final position will be updated in `draw` + hitboxes[i] = { + left: 0, + top: 0, + width: itemWidth, + height: fontSize + }; + }); + + totalWidth += currentColWidth; + columnWidths.push(currentColWidth); + minSize.width += totalWidth; + } + } + + me.width = minSize.width; + me.height = minSize.height; + }, + afterFit: noop, + + // Shared Methods + isHorizontal: function() { + return this.options.position === 'top' || this.options.position === 'bottom'; + }, + + // Actually draw the legend on the canvas + draw: function() { + var me = this; + var opts = me.options; + var labelOpts = opts.labels; + var globalDefault = defaults.global; + var lineDefault = globalDefault.elements.line; + var legendWidth = me.width; + var lineWidths = me.lineWidths; + + if (opts.display) { + var ctx = me.ctx; + var valueOrDefault = helpers.valueOrDefault; + var fontColor = valueOrDefault(labelOpts.fontColor, globalDefault.defaultFontColor); + var fontSize = valueOrDefault(labelOpts.fontSize, globalDefault.defaultFontSize); + var fontStyle = valueOrDefault(labelOpts.fontStyle, globalDefault.defaultFontStyle); + var fontFamily = valueOrDefault(labelOpts.fontFamily, globalDefault.defaultFontFamily); + var labelFont = helpers.fontString(fontSize, fontStyle, fontFamily); + var cursor; + + // Canvas setup + ctx.textAlign = 'left'; + ctx.textBaseline = 'middle'; + ctx.lineWidth = 0.5; + ctx.strokeStyle = fontColor; // for strikethrough effect + ctx.fillStyle = fontColor; // render in correct colour + ctx.font = labelFont; + + var boxWidth = getBoxWidth(labelOpts, fontSize); + var hitboxes = me.legendHitBoxes; + + // current position + var drawLegendBox = function(x, y, legendItem) { + if (isNaN(boxWidth) || boxWidth <= 0) { + return; + } + + // Set the ctx for the box + ctx.save(); + + ctx.fillStyle = valueOrDefault(legendItem.fillStyle, globalDefault.defaultColor); + ctx.lineCap = valueOrDefault(legendItem.lineCap, lineDefault.borderCapStyle); + ctx.lineDashOffset = valueOrDefault(legendItem.lineDashOffset, lineDefault.borderDashOffset); + ctx.lineJoin = valueOrDefault(legendItem.lineJoin, lineDefault.borderJoinStyle); + ctx.lineWidth = valueOrDefault(legendItem.lineWidth, lineDefault.borderWidth); + ctx.strokeStyle = valueOrDefault(legendItem.strokeStyle, globalDefault.defaultColor); + var isLineWidthZero = (valueOrDefault(legendItem.lineWidth, lineDefault.borderWidth) === 0); + + if (ctx.setLineDash) { + // IE 9 and 10 do not support line dash + ctx.setLineDash(valueOrDefault(legendItem.lineDash, lineDefault.borderDash)); + } + + if (opts.labels && opts.labels.usePointStyle) { + // Recalculate x and y for drawPoint() because its expecting + // x and y to be center of figure (instead of top left) + var radius = fontSize * Math.SQRT2 / 2; + var offSet = radius / Math.SQRT2; + var centerX = x + offSet; + var centerY = y + offSet; + + // Draw pointStyle as legend symbol + helpers.canvas.drawPoint(ctx, legendItem.pointStyle, radius, centerX, centerY); + } else { + // Draw box as legend symbol + if (!isLineWidthZero) { + ctx.strokeRect(x, y, boxWidth, fontSize); + } + ctx.fillRect(x, y, boxWidth, fontSize); + } + + ctx.restore(); + }; + var fillText = function(x, y, legendItem, textWidth) { + var halfFontSize = fontSize / 2; + var xLeft = boxWidth + halfFontSize + x; + var yMiddle = y + halfFontSize; + + ctx.fillText(legendItem.text, xLeft, yMiddle); + + if (legendItem.hidden) { + // Strikethrough the text if hidden + ctx.beginPath(); + ctx.lineWidth = 2; + ctx.moveTo(xLeft, yMiddle); + ctx.lineTo(xLeft + textWidth, yMiddle); + ctx.stroke(); + } + }; + + // Horizontal + var isHorizontal = me.isHorizontal(); + if (isHorizontal) { + cursor = { + x: me.left + ((legendWidth - lineWidths[0]) / 2), + y: me.top + labelOpts.padding, + line: 0 + }; + } else { + cursor = { + x: me.left + labelOpts.padding, + y: me.top + labelOpts.padding, + line: 0 + }; + } + + var itemHeight = fontSize + labelOpts.padding; + helpers.each(me.legendItems, function(legendItem, i) { + var textWidth = ctx.measureText(legendItem.text).width; + var width = boxWidth + (fontSize / 2) + textWidth; + var x = cursor.x; + var y = cursor.y; + + if (isHorizontal) { + if (x + width >= legendWidth) { + y = cursor.y += itemHeight; + cursor.line++; + x = cursor.x = me.left + ((legendWidth - lineWidths[cursor.line]) / 2); + } + } else if (y + itemHeight > me.bottom) { + x = cursor.x = x + me.columnWidths[cursor.line] + labelOpts.padding; + y = cursor.y = me.top + labelOpts.padding; + cursor.line++; + } + + drawLegendBox(x, y, legendItem); + + hitboxes[i].left = x; + hitboxes[i].top = y; + + // Fill the actual label + fillText(x, y, legendItem, textWidth); + + if (isHorizontal) { + cursor.x += width + (labelOpts.padding); + } else { + cursor.y += itemHeight; + } + + }); + } + }, + + /** + * Handle an event + * @private + * @param {IEvent} event - The event to handle + * @return {Boolean} true if a change occured + */ + handleEvent: function(e) { + var me = this; + var opts = me.options; + var type = e.type === 'mouseup' ? 'click' : e.type; + var changed = false; + + if (type === 'mousemove') { + if (!opts.onHover) { + return; + } + } else if (type === 'click') { + if (!opts.onClick) { + return; + } + } else { + return; + } + + // Chart event already has relative position in it + var x = e.x; + var y = e.y; + + if (x >= me.left && x <= me.right && y >= me.top && y <= me.bottom) { + // See if we are touching one of the dataset boxes + var lh = me.legendHitBoxes; + for (var i = 0; i < lh.length; ++i) { + var hitBox = lh[i]; + + if (x >= hitBox.left && x <= hitBox.left + hitBox.width && y >= hitBox.top && y <= hitBox.top + hitBox.height) { + // Touching an element + if (type === 'click') { + // use e.native for backwards compatibility + opts.onClick.call(me, e.native, me.legendItems[i]); + changed = true; + break; + } else if (type === 'mousemove') { + // use e.native for backwards compatibility + opts.onHover.call(me, e.native, me.legendItems[i]); + changed = true; + break; + } + } + } + } + + return changed; + } + }); + + function createNewLegendAndAttach(chart, legendOpts) { + var legend = new Chart.Legend({ + ctx: chart.ctx, + options: legendOpts, + chart: chart + }); + + layout.configure(chart, legend, legendOpts); + layout.addBox(chart, legend); + chart.legend = legend; + } + + return { + id: 'legend', + + beforeInit: function(chart) { + var legendOpts = chart.options.legend; + + if (legendOpts) { + createNewLegendAndAttach(chart, legendOpts); + } + }, + + beforeUpdate: function(chart) { + var legendOpts = chart.options.legend; + var legend = chart.legend; + + if (legendOpts) { + helpers.mergeIf(legendOpts, defaults.global.legend); + + if (legend) { + layout.configure(chart, legend, legendOpts); + legend.options = legendOpts; + } else { + createNewLegendAndAttach(chart, legendOpts); + } + } else if (legend) { + layout.removeBox(chart, legend); + delete chart.legend; + } + }, + + afterEvent: function(chart, e) { + var legend = chart.legend; + if (legend) { + legend.handleEvent(e); + } + } + }; +}; + +},{"25":25,"26":26,"45":45}],51:[function(require,module,exports){ +'use strict'; + +var defaults = require(25); +var Element = require(26); +var helpers = require(45); + +defaults._set('global', { + title: { + display: false, + fontStyle: 'bold', + fullWidth: true, + lineHeight: 1.2, + padding: 10, + position: 'top', + text: '', + weight: 2000 // by default greater than legend (1000) to be above + } +}); + +module.exports = function(Chart) { + + var layout = Chart.layoutService; + var noop = helpers.noop; + + Chart.Title = Element.extend({ + initialize: function(config) { + var me = this; + helpers.extend(me, config); + + // Contains hit boxes for each dataset (in dataset order) + me.legendHitBoxes = []; + }, + + // These methods are ordered by lifecycle. Utilities then follow. + + beforeUpdate: noop, + update: function(maxWidth, maxHeight, margins) { + var me = this; + + // Update Lifecycle - Probably don't want to ever extend or overwrite this function ;) + me.beforeUpdate(); + + // Absorb the master measurements + me.maxWidth = maxWidth; + me.maxHeight = maxHeight; + me.margins = margins; + + // Dimensions + me.beforeSetDimensions(); + me.setDimensions(); + me.afterSetDimensions(); + // Labels + me.beforeBuildLabels(); + me.buildLabels(); + me.afterBuildLabels(); + + // Fit + me.beforeFit(); + me.fit(); + me.afterFit(); + // + me.afterUpdate(); + + return me.minSize; + + }, + afterUpdate: noop, + + // + + beforeSetDimensions: noop, + setDimensions: function() { + var me = this; + // Set the unconstrained dimension before label rotation + if (me.isHorizontal()) { + // Reset position before calculating rotation + me.width = me.maxWidth; + me.left = 0; + me.right = me.width; + } else { + me.height = me.maxHeight; + + // Reset position before calculating rotation + me.top = 0; + me.bottom = me.height; + } + + // Reset padding + me.paddingLeft = 0; + me.paddingTop = 0; + me.paddingRight = 0; + me.paddingBottom = 0; + + // Reset minSize + me.minSize = { + width: 0, + height: 0 + }; + }, + afterSetDimensions: noop, + + // + + beforeBuildLabels: noop, + buildLabels: noop, + afterBuildLabels: noop, + + // + + beforeFit: noop, + fit: function() { + var me = this; + var valueOrDefault = helpers.valueOrDefault; + var opts = me.options; + var display = opts.display; + var fontSize = valueOrDefault(opts.fontSize, defaults.global.defaultFontSize); + var minSize = me.minSize; + var lineCount = helpers.isArray(opts.text) ? opts.text.length : 1; + var lineHeight = helpers.options.toLineHeight(opts.lineHeight, fontSize); + var textSize = display ? (lineCount * lineHeight) + (opts.padding * 2) : 0; + + if (me.isHorizontal()) { + minSize.width = me.maxWidth; // fill all the width + minSize.height = textSize; + } else { + minSize.width = textSize; + minSize.height = me.maxHeight; // fill all the height + } + + me.width = minSize.width; + me.height = minSize.height; + + }, + afterFit: noop, + + // Shared Methods + isHorizontal: function() { + var pos = this.options.position; + return pos === 'top' || pos === 'bottom'; + }, + + // Actually draw the title block on the canvas + draw: function() { + var me = this; + var ctx = me.ctx; + var valueOrDefault = helpers.valueOrDefault; + var opts = me.options; + var globalDefaults = defaults.global; + + if (opts.display) { + var fontSize = valueOrDefault(opts.fontSize, globalDefaults.defaultFontSize); + var fontStyle = valueOrDefault(opts.fontStyle, globalDefaults.defaultFontStyle); + var fontFamily = valueOrDefault(opts.fontFamily, globalDefaults.defaultFontFamily); + var titleFont = helpers.fontString(fontSize, fontStyle, fontFamily); + var lineHeight = helpers.options.toLineHeight(opts.lineHeight, fontSize); + var offset = lineHeight / 2 + opts.padding; + var rotation = 0; + var top = me.top; + var left = me.left; + var bottom = me.bottom; + var right = me.right; + var maxWidth, titleX, titleY; + + ctx.fillStyle = valueOrDefault(opts.fontColor, globalDefaults.defaultFontColor); // render in correct colour + ctx.font = titleFont; + + // Horizontal + if (me.isHorizontal()) { + titleX = left + ((right - left) / 2); // midpoint of the width + titleY = top + offset; + maxWidth = right - left; + } else { + titleX = opts.position === 'left' ? left + offset : right - offset; + titleY = top + ((bottom - top) / 2); + maxWidth = bottom - top; + rotation = Math.PI * (opts.position === 'left' ? -0.5 : 0.5); + } + + ctx.save(); + ctx.translate(titleX, titleY); + ctx.rotate(rotation); + ctx.textAlign = 'center'; + ctx.textBaseline = 'middle'; + + var text = opts.text; + if (helpers.isArray(text)) { + var y = 0; + for (var i = 0; i < text.length; ++i) { + ctx.fillText(text[i], 0, y, maxWidth); + y += lineHeight; + } + } else { + ctx.fillText(text, 0, 0, maxWidth); + } + + ctx.restore(); + } + } + }); + + function createNewTitleBlockAndAttach(chart, titleOpts) { + var title = new Chart.Title({ + ctx: chart.ctx, + options: titleOpts, + chart: chart + }); + + layout.configure(chart, title, titleOpts); + layout.addBox(chart, title); + chart.titleBlock = title; + } + + return { + id: 'title', + + beforeInit: function(chart) { + var titleOpts = chart.options.title; + + if (titleOpts) { + createNewTitleBlockAndAttach(chart, titleOpts); + } + }, + + beforeUpdate: function(chart) { + var titleOpts = chart.options.title; + var titleBlock = chart.titleBlock; + + if (titleOpts) { + helpers.mergeIf(titleOpts, defaults.global.title); + + if (titleBlock) { + layout.configure(chart, titleBlock, titleOpts); + titleBlock.options = titleOpts; + } else { + createNewTitleBlockAndAttach(chart, titleOpts); + } + } else if (titleBlock) { + Chart.layoutService.removeBox(chart, titleBlock); + delete chart.titleBlock; + } + } + }; +}; + +},{"25":25,"26":26,"45":45}],52:[function(require,module,exports){ +'use strict'; + +module.exports = function(Chart) { + + // Default config for a category scale + var defaultConfig = { + position: 'bottom' + }; + + var DatasetScale = Chart.Scale.extend({ + /** + * Internal function to get the correct labels. If data.xLabels or data.yLabels are defined, use those + * else fall back to data.labels + * @private + */ + getLabels: function() { + var data = this.chart.data; + return this.options.labels || (this.isHorizontal() ? data.xLabels : data.yLabels) || data.labels; + }, + + determineDataLimits: function() { + var me = this; + var labels = me.getLabels(); + me.minIndex = 0; + me.maxIndex = labels.length - 1; + var findIndex; + + if (me.options.ticks.min !== undefined) { + // user specified min value + findIndex = labels.indexOf(me.options.ticks.min); + me.minIndex = findIndex !== -1 ? findIndex : me.minIndex; + } + + if (me.options.ticks.max !== undefined) { + // user specified max value + findIndex = labels.indexOf(me.options.ticks.max); + me.maxIndex = findIndex !== -1 ? findIndex : me.maxIndex; + } + + me.min = labels[me.minIndex]; + me.max = labels[me.maxIndex]; + }, + + buildTicks: function() { + var me = this; + var labels = me.getLabels(); + // If we are viewing some subset of labels, slice the original array + me.ticks = (me.minIndex === 0 && me.maxIndex === labels.length - 1) ? labels : labels.slice(me.minIndex, me.maxIndex + 1); + }, + + getLabelForIndex: function(index, datasetIndex) { + var me = this; + var data = me.chart.data; + var isHorizontal = me.isHorizontal(); + + if (data.yLabels && !isHorizontal) { + return me.getRightValue(data.datasets[datasetIndex].data[index]); + } + return me.ticks[index - me.minIndex]; + }, + + // Used to get data value locations. Value can either be an index or a numerical value + getPixelForValue: function(value, index) { + var me = this; + var offset = me.options.offset; + // 1 is added because we need the length but we have the indexes + var offsetAmt = Math.max((me.maxIndex + 1 - me.minIndex - (offset ? 0 : 1)), 1); + + // If value is a data object, then index is the index in the data array, + // not the index of the scale. We need to change that. + var valueCategory; + if (value !== undefined && value !== null) { + valueCategory = me.isHorizontal() ? value.x : value.y; + } + if (valueCategory !== undefined || (value !== undefined && isNaN(index))) { + var labels = me.getLabels(); + value = valueCategory || value; + var idx = labels.indexOf(value); + index = idx !== -1 ? idx : index; + } + + if (me.isHorizontal()) { + var valueWidth = me.width / offsetAmt; + var widthOffset = (valueWidth * (index - me.minIndex)); + + if (offset) { + widthOffset += (valueWidth / 2); + } + + return me.left + Math.round(widthOffset); + } + var valueHeight = me.height / offsetAmt; + var heightOffset = (valueHeight * (index - me.minIndex)); + + if (offset) { + heightOffset += (valueHeight / 2); + } + + return me.top + Math.round(heightOffset); + }, + getPixelForTick: function(index) { + return this.getPixelForValue(this.ticks[index], index + this.minIndex, null); + }, + getValueForPixel: function(pixel) { + var me = this; + var offset = me.options.offset; + var value; + var offsetAmt = Math.max((me._ticks.length - (offset ? 0 : 1)), 1); + var horz = me.isHorizontal(); + var valueDimension = (horz ? me.width : me.height) / offsetAmt; + + pixel -= horz ? me.left : me.top; + + if (offset) { + pixel -= (valueDimension / 2); + } + + if (pixel <= 0) { + value = 0; + } else { + value = Math.round(pixel / valueDimension); + } + + return value + me.minIndex; + }, + getBasePixel: function() { + return this.bottom; + } + }); + + Chart.scaleService.registerScaleType('category', DatasetScale, defaultConfig); + +}; + +},{}],53:[function(require,module,exports){ +'use strict'; + +var defaults = require(25); +var helpers = require(45); +var Ticks = require(34); + +module.exports = function(Chart) { + + var defaultConfig = { + position: 'left', + ticks: { + callback: Ticks.formatters.linear + } + }; + + var LinearScale = Chart.LinearScaleBase.extend({ + + determineDataLimits: function() { + var me = this; + var opts = me.options; + var chart = me.chart; + var data = chart.data; + var datasets = data.datasets; + var isHorizontal = me.isHorizontal(); + var DEFAULT_MIN = 0; + var DEFAULT_MAX = 1; + + function IDMatches(meta) { + return isHorizontal ? meta.xAxisID === me.id : meta.yAxisID === me.id; + } + + // First Calculate the range + me.min = null; + me.max = null; + + var hasStacks = opts.stacked; + if (hasStacks === undefined) { + helpers.each(datasets, function(dataset, datasetIndex) { + if (hasStacks) { + return; + } + + var meta = chart.getDatasetMeta(datasetIndex); + if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta) && + meta.stack !== undefined) { + hasStacks = true; + } + }); + } + + if (opts.stacked || hasStacks) { + var valuesPerStack = {}; + + helpers.each(datasets, function(dataset, datasetIndex) { + var meta = chart.getDatasetMeta(datasetIndex); + var key = [ + meta.type, + // we have a separate stack for stack=undefined datasets when the opts.stacked is undefined + ((opts.stacked === undefined && meta.stack === undefined) ? datasetIndex : ''), + meta.stack + ].join('.'); + + if (valuesPerStack[key] === undefined) { + valuesPerStack[key] = { + positiveValues: [], + negativeValues: [] + }; + } + + // Store these per type + var positiveValues = valuesPerStack[key].positiveValues; + var negativeValues = valuesPerStack[key].negativeValues; + + if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta)) { + helpers.each(dataset.data, function(rawValue, index) { + var value = +me.getRightValue(rawValue); + if (isNaN(value) || meta.data[index].hidden) { + return; + } + + positiveValues[index] = positiveValues[index] || 0; + negativeValues[index] = negativeValues[index] || 0; + + if (opts.relativePoints) { + positiveValues[index] = 100; + } else if (value < 0) { + negativeValues[index] += value; + } else { + positiveValues[index] += value; + } + }); + } + }); + + helpers.each(valuesPerStack, function(valuesForType) { + var values = valuesForType.positiveValues.concat(valuesForType.negativeValues); + var minVal = helpers.min(values); + var maxVal = helpers.max(values); + me.min = me.min === null ? minVal : Math.min(me.min, minVal); + me.max = me.max === null ? maxVal : Math.max(me.max, maxVal); + }); + + } else { + helpers.each(datasets, function(dataset, datasetIndex) { + var meta = chart.getDatasetMeta(datasetIndex); + if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta)) { + helpers.each(dataset.data, function(rawValue, index) { + var value = +me.getRightValue(rawValue); + if (isNaN(value) || meta.data[index].hidden) { + return; + } + + if (me.min === null) { + me.min = value; + } else if (value < me.min) { + me.min = value; + } + + if (me.max === null) { + me.max = value; + } else if (value > me.max) { + me.max = value; + } + }); + } + }); + } + + me.min = isFinite(me.min) && !isNaN(me.min) ? me.min : DEFAULT_MIN; + me.max = isFinite(me.max) && !isNaN(me.max) ? me.max : DEFAULT_MAX; + + // Common base implementation to handle ticks.min, ticks.max, ticks.beginAtZero + this.handleTickRangeOptions(); + }, + getTickLimit: function() { + var maxTicks; + var me = this; + var tickOpts = me.options.ticks; + + if (me.isHorizontal()) { + maxTicks = Math.min(tickOpts.maxTicksLimit ? tickOpts.maxTicksLimit : 11, Math.ceil(me.width / 50)); + } else { + // The factor of 2 used to scale the font size has been experimentally determined. + var tickFontSize = helpers.valueOrDefault(tickOpts.fontSize, defaults.global.defaultFontSize); + maxTicks = Math.min(tickOpts.maxTicksLimit ? tickOpts.maxTicksLimit : 11, Math.ceil(me.height / (2 * tickFontSize))); + } + + return maxTicks; + }, + // Called after the ticks are built. We need + handleDirectionalChanges: function() { + if (!this.isHorizontal()) { + // We are in a vertical orientation. The top value is the highest. So reverse the array + this.ticks.reverse(); + } + }, + getLabelForIndex: function(index, datasetIndex) { + return +this.getRightValue(this.chart.data.datasets[datasetIndex].data[index]); + }, + // Utils + getPixelForValue: function(value) { + // This must be called after fit has been run so that + // this.left, this.top, this.right, and this.bottom have been defined + var me = this; + var start = me.start; + + var rightValue = +me.getRightValue(value); + var pixel; + var range = me.end - start; + + if (me.isHorizontal()) { + pixel = me.left + (me.width / range * (rightValue - start)); + return Math.round(pixel); + } + + pixel = me.bottom - (me.height / range * (rightValue - start)); + return Math.round(pixel); + }, + getValueForPixel: function(pixel) { + var me = this; + var isHorizontal = me.isHorizontal(); + var innerDimension = isHorizontal ? me.width : me.height; + var offset = (isHorizontal ? pixel - me.left : me.bottom - pixel) / innerDimension; + return me.start + ((me.end - me.start) * offset); + }, + getPixelForTick: function(index) { + return this.getPixelForValue(this.ticksAsNumbers[index]); + } + }); + Chart.scaleService.registerScaleType('linear', LinearScale, defaultConfig); + +}; + +},{"25":25,"34":34,"45":45}],54:[function(require,module,exports){ +'use strict'; + +var helpers = require(45); +var Ticks = require(34); + +module.exports = function(Chart) { + + var noop = helpers.noop; + + Chart.LinearScaleBase = Chart.Scale.extend({ + getRightValue: function(value) { + if (typeof value === 'string') { + return +value; + } + return Chart.Scale.prototype.getRightValue.call(this, value); + }, + + handleTickRangeOptions: function() { + var me = this; + var opts = me.options; + var tickOpts = opts.ticks; + + // If we are forcing it to begin at 0, but 0 will already be rendered on the chart, + // do nothing since that would make the chart weird. If the user really wants a weird chart + // axis, they can manually override it + if (tickOpts.beginAtZero) { + var minSign = helpers.sign(me.min); + var maxSign = helpers.sign(me.max); + + if (minSign < 0 && maxSign < 0) { + // move the top up to 0 + me.max = 0; + } else if (minSign > 0 && maxSign > 0) { + // move the bottom down to 0 + me.min = 0; + } + } + + var setMin = tickOpts.min !== undefined || tickOpts.suggestedMin !== undefined; + var setMax = tickOpts.max !== undefined || tickOpts.suggestedMax !== undefined; + + if (tickOpts.min !== undefined) { + me.min = tickOpts.min; + } else if (tickOpts.suggestedMin !== undefined) { + if (me.min === null) { + me.min = tickOpts.suggestedMin; + } else { + me.min = Math.min(me.min, tickOpts.suggestedMin); + } + } + + if (tickOpts.max !== undefined) { + me.max = tickOpts.max; + } else if (tickOpts.suggestedMax !== undefined) { + if (me.max === null) { + me.max = tickOpts.suggestedMax; + } else { + me.max = Math.max(me.max, tickOpts.suggestedMax); + } + } + + if (setMin !== setMax) { + // We set the min or the max but not both. + // So ensure that our range is good + // Inverted or 0 length range can happen when + // ticks.min is set, and no datasets are visible + if (me.min >= me.max) { + if (setMin) { + me.max = me.min + 1; + } else { + me.min = me.max - 1; + } + } + } + + if (me.min === me.max) { + me.max++; + + if (!tickOpts.beginAtZero) { + me.min--; + } + } + }, + getTickLimit: noop, + handleDirectionalChanges: noop, + + buildTicks: function() { + var me = this; + var opts = me.options; + var tickOpts = opts.ticks; + + // Figure out what the max number of ticks we can support it is based on the size of + // the axis area. For now, we say that the minimum tick spacing in pixels must be 50 + // We also limit the maximum number of ticks to 11 which gives a nice 10 squares on + // the graph. Make sure we always have at least 2 ticks + var maxTicks = me.getTickLimit(); + maxTicks = Math.max(2, maxTicks); + + var numericGeneratorOptions = { + maxTicks: maxTicks, + min: tickOpts.min, + max: tickOpts.max, + stepSize: helpers.valueOrDefault(tickOpts.fixedStepSize, tickOpts.stepSize) + }; + var ticks = me.ticks = Ticks.generators.linear(numericGeneratorOptions, me); + + me.handleDirectionalChanges(); + + // At this point, we need to update our max and min given the tick values since we have expanded the + // range of the scale + me.max = helpers.max(ticks); + me.min = helpers.min(ticks); + + if (tickOpts.reverse) { + ticks.reverse(); + + me.start = me.max; + me.end = me.min; + } else { + me.start = me.min; + me.end = me.max; + } + }, + convertTicksToLabels: function() { + var me = this; + me.ticksAsNumbers = me.ticks.slice(); + me.zeroLineIndex = me.ticks.indexOf(0); + + Chart.Scale.prototype.convertTicksToLabels.call(me); + } + }); +}; + +},{"34":34,"45":45}],55:[function(require,module,exports){ +'use strict'; + +var helpers = require(45); +var Ticks = require(34); + +module.exports = function(Chart) { + + var defaultConfig = { + position: 'left', + + // label settings + ticks: { + callback: Ticks.formatters.logarithmic + } + }; + + var LogarithmicScale = Chart.Scale.extend({ + determineDataLimits: function() { + var me = this; + var opts = me.options; + var tickOpts = opts.ticks; + var chart = me.chart; + var data = chart.data; + var datasets = data.datasets; + var valueOrDefault = helpers.valueOrDefault; + var isHorizontal = me.isHorizontal(); + function IDMatches(meta) { + return isHorizontal ? meta.xAxisID === me.id : meta.yAxisID === me.id; + } + + // Calculate Range + me.min = null; + me.max = null; + me.minNotZero = null; + + var hasStacks = opts.stacked; + if (hasStacks === undefined) { + helpers.each(datasets, function(dataset, datasetIndex) { + if (hasStacks) { + return; + } + + var meta = chart.getDatasetMeta(datasetIndex); + if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta) && + meta.stack !== undefined) { + hasStacks = true; + } + }); + } + + if (opts.stacked || hasStacks) { + var valuesPerStack = {}; + + helpers.each(datasets, function(dataset, datasetIndex) { + var meta = chart.getDatasetMeta(datasetIndex); + var key = [ + meta.type, + // we have a separate stack for stack=undefined datasets when the opts.stacked is undefined + ((opts.stacked === undefined && meta.stack === undefined) ? datasetIndex : ''), + meta.stack + ].join('.'); + + if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta)) { + if (valuesPerStack[key] === undefined) { + valuesPerStack[key] = []; + } + + helpers.each(dataset.data, function(rawValue, index) { + var values = valuesPerStack[key]; + var value = +me.getRightValue(rawValue); + if (isNaN(value) || meta.data[index].hidden) { + return; + } + + values[index] = values[index] || 0; + + if (opts.relativePoints) { + values[index] = 100; + } else { + // Don't need to split positive and negative since the log scale can't handle a 0 crossing + values[index] += value; + } + }); + } + }); + + helpers.each(valuesPerStack, function(valuesForType) { + var minVal = helpers.min(valuesForType); + var maxVal = helpers.max(valuesForType); + me.min = me.min === null ? minVal : Math.min(me.min, minVal); + me.max = me.max === null ? maxVal : Math.max(me.max, maxVal); + }); + + } else { + helpers.each(datasets, function(dataset, datasetIndex) { + var meta = chart.getDatasetMeta(datasetIndex); + if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta)) { + helpers.each(dataset.data, function(rawValue, index) { + var value = +me.getRightValue(rawValue); + if (isNaN(value) || meta.data[index].hidden) { + return; + } + + if (me.min === null) { + me.min = value; + } else if (value < me.min) { + me.min = value; + } + + if (me.max === null) { + me.max = value; + } else if (value > me.max) { + me.max = value; + } + + if (value !== 0 && (me.minNotZero === null || value < me.minNotZero)) { + me.minNotZero = value; + } + }); + } + }); + } + + me.min = valueOrDefault(tickOpts.min, me.min); + me.max = valueOrDefault(tickOpts.max, me.max); + + if (me.min === me.max) { + if (me.min !== 0 && me.min !== null) { + me.min = Math.pow(10, Math.floor(helpers.log10(me.min)) - 1); + me.max = Math.pow(10, Math.floor(helpers.log10(me.max)) + 1); + } else { + me.min = 1; + me.max = 10; + } + } + }, + buildTicks: function() { + var me = this; + var opts = me.options; + var tickOpts = opts.ticks; + + var generationOptions = { + min: tickOpts.min, + max: tickOpts.max + }; + var ticks = me.ticks = Ticks.generators.logarithmic(generationOptions, me); + + if (!me.isHorizontal()) { + // We are in a vertical orientation. The top value is the highest. So reverse the array + ticks.reverse(); + } + + // At this point, we need to update our max and min given the tick values since we have expanded the + // range of the scale + me.max = helpers.max(ticks); + me.min = helpers.min(ticks); + + if (tickOpts.reverse) { + ticks.reverse(); + + me.start = me.max; + me.end = me.min; + } else { + me.start = me.min; + me.end = me.max; + } + }, + convertTicksToLabels: function() { + this.tickValues = this.ticks.slice(); + + Chart.Scale.prototype.convertTicksToLabels.call(this); + }, + // Get the correct tooltip label + getLabelForIndex: function(index, datasetIndex) { + return +this.getRightValue(this.chart.data.datasets[datasetIndex].data[index]); + }, + getPixelForTick: function(index) { + return this.getPixelForValue(this.tickValues[index]); + }, + getPixelForValue: function(value) { + var me = this; + var start = me.start; + var newVal = +me.getRightValue(value); + var opts = me.options; + var tickOpts = opts.ticks; + var innerDimension, pixel, range; + + if (me.isHorizontal()) { + range = helpers.log10(me.end) - helpers.log10(start); // todo: if start === 0 + if (newVal === 0) { + pixel = me.left; + } else { + innerDimension = me.width; + pixel = me.left + (innerDimension / range * (helpers.log10(newVal) - helpers.log10(start))); + } + } else { + // Bottom - top since pixels increase downward on a screen + innerDimension = me.height; + if (start === 0 && !tickOpts.reverse) { + range = helpers.log10(me.end) - helpers.log10(me.minNotZero); + if (newVal === start) { + pixel = me.bottom; + } else if (newVal === me.minNotZero) { + pixel = me.bottom - innerDimension * 0.02; + } else { + pixel = me.bottom - innerDimension * 0.02 - (innerDimension * 0.98 / range * (helpers.log10(newVal) - helpers.log10(me.minNotZero))); + } + } else if (me.end === 0 && tickOpts.reverse) { + range = helpers.log10(me.start) - helpers.log10(me.minNotZero); + if (newVal === me.end) { + pixel = me.top; + } else if (newVal === me.minNotZero) { + pixel = me.top + innerDimension * 0.02; + } else { + pixel = me.top + innerDimension * 0.02 + (innerDimension * 0.98 / range * (helpers.log10(newVal) - helpers.log10(me.minNotZero))); + } + } else if (newVal === 0) { + pixel = tickOpts.reverse ? me.top : me.bottom; + } else { + range = helpers.log10(me.end) - helpers.log10(start); + innerDimension = me.height; + pixel = me.bottom - (innerDimension / range * (helpers.log10(newVal) - helpers.log10(start))); + } + } + return pixel; + }, + getValueForPixel: function(pixel) { + var me = this; + var range = helpers.log10(me.end) - helpers.log10(me.start); + var value, innerDimension; + + if (me.isHorizontal()) { + innerDimension = me.width; + value = me.start * Math.pow(10, (pixel - me.left) * range / innerDimension); + } else { // todo: if start === 0 + innerDimension = me.height; + value = Math.pow(10, (me.bottom - pixel) * range / innerDimension) / me.start; + } + return value; + } + }); + Chart.scaleService.registerScaleType('logarithmic', LogarithmicScale, defaultConfig); + +}; + +},{"34":34,"45":45}],56:[function(require,module,exports){ +'use strict'; + +var defaults = require(25); +var helpers = require(45); +var Ticks = require(34); + +module.exports = function(Chart) { + + var globalDefaults = defaults.global; + + var defaultConfig = { + display: true, + + // Boolean - Whether to animate scaling the chart from the centre + animate: true, + position: 'chartArea', + + angleLines: { + display: true, + color: 'rgba(0, 0, 0, 0.1)', + lineWidth: 1 + }, + + gridLines: { + circular: false + }, + + // label settings + ticks: { + // Boolean - Show a backdrop to the scale label + showLabelBackdrop: true, + + // String - The colour of the label backdrop + backdropColor: 'rgba(255,255,255,0.75)', + + // Number - The backdrop padding above & below the label in pixels + backdropPaddingY: 2, + + // Number - The backdrop padding to the side of the label in pixels + backdropPaddingX: 2, + + callback: Ticks.formatters.linear + }, + + pointLabels: { + // Boolean - if true, show point labels + display: true, + + // Number - Point label font size in pixels + fontSize: 10, + + // Function - Used to convert point labels + callback: function(label) { + return label; + } + } + }; + + function getValueCount(scale) { + var opts = scale.options; + return opts.angleLines.display || opts.pointLabels.display ? scale.chart.data.labels.length : 0; + } + + function getPointLabelFontOptions(scale) { + var pointLabelOptions = scale.options.pointLabels; + var fontSize = helpers.valueOrDefault(pointLabelOptions.fontSize, globalDefaults.defaultFontSize); + var fontStyle = helpers.valueOrDefault(pointLabelOptions.fontStyle, globalDefaults.defaultFontStyle); + var fontFamily = helpers.valueOrDefault(pointLabelOptions.fontFamily, globalDefaults.defaultFontFamily); + var font = helpers.fontString(fontSize, fontStyle, fontFamily); + + return { + size: fontSize, + style: fontStyle, + family: fontFamily, + font: font + }; + } + + function measureLabelSize(ctx, fontSize, label) { + if (helpers.isArray(label)) { + return { + w: helpers.longestText(ctx, ctx.font, label), + h: (label.length * fontSize) + ((label.length - 1) * 1.5 * fontSize) + }; + } + + return { + w: ctx.measureText(label).width, + h: fontSize + }; + } + + function determineLimits(angle, pos, size, min, max) { + if (angle === min || angle === max) { + return { + start: pos - (size / 2), + end: pos + (size / 2) + }; + } else if (angle < min || angle > max) { + return { + start: pos - size - 5, + end: pos + }; + } + + return { + start: pos, + end: pos + size + 5 + }; + } + + /** + * Helper function to fit a radial linear scale with point labels + */ + function fitWithPointLabels(scale) { + /* + * Right, this is really confusing and there is a lot of maths going on here + * The gist of the problem is here: https://gist.github.com/nnnick/696cc9c55f4b0beb8fe9 + * + * Reaction: https://dl.dropboxusercontent.com/u/34601363/toomuchscience.gif + * + * Solution: + * + * We assume the radius of the polygon is half the size of the canvas at first + * at each index we check if the text overlaps. + * + * Where it does, we store that angle and that index. + * + * After finding the largest index and angle we calculate how much we need to remove + * from the shape radius to move the point inwards by that x. + * + * We average the left and right distances to get the maximum shape radius that can fit in the box + * along with labels. + * + * Once we have that, we can find the centre point for the chart, by taking the x text protrusion + * on each side, removing that from the size, halving it and adding the left x protrusion width. + * + * This will mean we have a shape fitted to the canvas, as large as it can be with the labels + * and position it in the most space efficient manner + * + * https://dl.dropboxusercontent.com/u/34601363/yeahscience.gif + */ + + var plFont = getPointLabelFontOptions(scale); + + // Get maximum radius of the polygon. Either half the height (minus the text width) or half the width. + // Use this to calculate the offset + change. - Make sure L/R protrusion is at least 0 to stop issues with centre points + var largestPossibleRadius = Math.min(scale.height / 2, scale.width / 2); + var furthestLimits = { + r: scale.width, + l: 0, + t: scale.height, + b: 0 + }; + var furthestAngles = {}; + var i, textSize, pointPosition; + + scale.ctx.font = plFont.font; + scale._pointLabelSizes = []; + + var valueCount = getValueCount(scale); + for (i = 0; i < valueCount; i++) { + pointPosition = scale.getPointPosition(i, largestPossibleRadius); + textSize = measureLabelSize(scale.ctx, plFont.size, scale.pointLabels[i] || ''); + scale._pointLabelSizes[i] = textSize; + + // Add quarter circle to make degree 0 mean top of circle + var angleRadians = scale.getIndexAngle(i); + var angle = helpers.toDegrees(angleRadians) % 360; + var hLimits = determineLimits(angle, pointPosition.x, textSize.w, 0, 180); + var vLimits = determineLimits(angle, pointPosition.y, textSize.h, 90, 270); + + if (hLimits.start < furthestLimits.l) { + furthestLimits.l = hLimits.start; + furthestAngles.l = angleRadians; + } + + if (hLimits.end > furthestLimits.r) { + furthestLimits.r = hLimits.end; + furthestAngles.r = angleRadians; + } + + if (vLimits.start < furthestLimits.t) { + furthestLimits.t = vLimits.start; + furthestAngles.t = angleRadians; + } + + if (vLimits.end > furthestLimits.b) { + furthestLimits.b = vLimits.end; + furthestAngles.b = angleRadians; + } + } + + scale.setReductions(largestPossibleRadius, furthestLimits, furthestAngles); + } + + /** + * Helper function to fit a radial linear scale with no point labels + */ + function fit(scale) { + var largestPossibleRadius = Math.min(scale.height / 2, scale.width / 2); + scale.drawingArea = Math.round(largestPossibleRadius); + scale.setCenterPoint(0, 0, 0, 0); + } + + function getTextAlignForAngle(angle) { + if (angle === 0 || angle === 180) { + return 'center'; + } else if (angle < 180) { + return 'left'; + } + + return 'right'; + } + + function fillText(ctx, text, position, fontSize) { + if (helpers.isArray(text)) { + var y = position.y; + var spacing = 1.5 * fontSize; + + for (var i = 0; i < text.length; ++i) { + ctx.fillText(text[i], position.x, y); + y += spacing; + } + } else { + ctx.fillText(text, position.x, position.y); + } + } + + function adjustPointPositionForLabelHeight(angle, textSize, position) { + if (angle === 90 || angle === 270) { + position.y -= (textSize.h / 2); + } else if (angle > 270 || angle < 90) { + position.y -= textSize.h; + } + } + + function drawPointLabels(scale) { + var ctx = scale.ctx; + var valueOrDefault = helpers.valueOrDefault; + var opts = scale.options; + var angleLineOpts = opts.angleLines; + var pointLabelOpts = opts.pointLabels; + + ctx.lineWidth = angleLineOpts.lineWidth; + ctx.strokeStyle = angleLineOpts.color; + + var outerDistance = scale.getDistanceFromCenterForValue(opts.ticks.reverse ? scale.min : scale.max); + + // Point Label Font + var plFont = getPointLabelFontOptions(scale); + + ctx.textBaseline = 'top'; + + for (var i = getValueCount(scale) - 1; i >= 0; i--) { + if (angleLineOpts.display) { + var outerPosition = scale.getPointPosition(i, outerDistance); + ctx.beginPath(); + ctx.moveTo(scale.xCenter, scale.yCenter); + ctx.lineTo(outerPosition.x, outerPosition.y); + ctx.stroke(); + ctx.closePath(); + } + + if (pointLabelOpts.display) { + // Extra 3px out for some label spacing + var pointLabelPosition = scale.getPointPosition(i, outerDistance + 5); + + // Keep this in loop since we may support array properties here + var pointLabelFontColor = valueOrDefault(pointLabelOpts.fontColor, globalDefaults.defaultFontColor); + ctx.font = plFont.font; + ctx.fillStyle = pointLabelFontColor; + + var angleRadians = scale.getIndexAngle(i); + var angle = helpers.toDegrees(angleRadians); + ctx.textAlign = getTextAlignForAngle(angle); + adjustPointPositionForLabelHeight(angle, scale._pointLabelSizes[i], pointLabelPosition); + fillText(ctx, scale.pointLabels[i] || '', pointLabelPosition, plFont.size); + } + } + } + + function drawRadiusLine(scale, gridLineOpts, radius, index) { + var ctx = scale.ctx; + ctx.strokeStyle = helpers.valueAtIndexOrDefault(gridLineOpts.color, index - 1); + ctx.lineWidth = helpers.valueAtIndexOrDefault(gridLineOpts.lineWidth, index - 1); + + if (scale.options.gridLines.circular) { + // Draw circular arcs between the points + ctx.beginPath(); + ctx.arc(scale.xCenter, scale.yCenter, radius, 0, Math.PI * 2); + ctx.closePath(); + ctx.stroke(); + } else { + // Draw straight lines connecting each index + var valueCount = getValueCount(scale); + + if (valueCount === 0) { + return; + } + + ctx.beginPath(); + var pointPosition = scale.getPointPosition(0, radius); + ctx.moveTo(pointPosition.x, pointPosition.y); + + for (var i = 1; i < valueCount; i++) { + pointPosition = scale.getPointPosition(i, radius); + ctx.lineTo(pointPosition.x, pointPosition.y); + } + + ctx.closePath(); + ctx.stroke(); + } + } + + function numberOrZero(param) { + return helpers.isNumber(param) ? param : 0; + } + + var LinearRadialScale = Chart.LinearScaleBase.extend({ + setDimensions: function() { + var me = this; + var opts = me.options; + var tickOpts = opts.ticks; + // Set the unconstrained dimension before label rotation + me.width = me.maxWidth; + me.height = me.maxHeight; + me.xCenter = Math.round(me.width / 2); + me.yCenter = Math.round(me.height / 2); + + var minSize = helpers.min([me.height, me.width]); + var tickFontSize = helpers.valueOrDefault(tickOpts.fontSize, globalDefaults.defaultFontSize); + me.drawingArea = opts.display ? (minSize / 2) - (tickFontSize / 2 + tickOpts.backdropPaddingY) : (minSize / 2); + }, + determineDataLimits: function() { + var me = this; + var chart = me.chart; + var min = Number.POSITIVE_INFINITY; + var max = Number.NEGATIVE_INFINITY; + + helpers.each(chart.data.datasets, function(dataset, datasetIndex) { + if (chart.isDatasetVisible(datasetIndex)) { + var meta = chart.getDatasetMeta(datasetIndex); + + helpers.each(dataset.data, function(rawValue, index) { + var value = +me.getRightValue(rawValue); + if (isNaN(value) || meta.data[index].hidden) { + return; + } + + min = Math.min(value, min); + max = Math.max(value, max); + }); + } + }); + + me.min = (min === Number.POSITIVE_INFINITY ? 0 : min); + me.max = (max === Number.NEGATIVE_INFINITY ? 0 : max); + + // Common base implementation to handle ticks.min, ticks.max, ticks.beginAtZero + me.handleTickRangeOptions(); + }, + getTickLimit: function() { + var tickOpts = this.options.ticks; + var tickFontSize = helpers.valueOrDefault(tickOpts.fontSize, globalDefaults.defaultFontSize); + return Math.min(tickOpts.maxTicksLimit ? tickOpts.maxTicksLimit : 11, Math.ceil(this.drawingArea / (1.5 * tickFontSize))); + }, + convertTicksToLabels: function() { + var me = this; + + Chart.LinearScaleBase.prototype.convertTicksToLabels.call(me); + + // Point labels + me.pointLabels = me.chart.data.labels.map(me.options.pointLabels.callback, me); + }, + getLabelForIndex: function(index, datasetIndex) { + return +this.getRightValue(this.chart.data.datasets[datasetIndex].data[index]); + }, + fit: function() { + if (this.options.pointLabels.display) { + fitWithPointLabels(this); + } else { + fit(this); + } + }, + /** + * Set radius reductions and determine new radius and center point + * @private + */ + setReductions: function(largestPossibleRadius, furthestLimits, furthestAngles) { + var me = this; + var radiusReductionLeft = furthestLimits.l / Math.sin(furthestAngles.l); + var radiusReductionRight = Math.max(furthestLimits.r - me.width, 0) / Math.sin(furthestAngles.r); + var radiusReductionTop = -furthestLimits.t / Math.cos(furthestAngles.t); + var radiusReductionBottom = -Math.max(furthestLimits.b - me.height, 0) / Math.cos(furthestAngles.b); + + radiusReductionLeft = numberOrZero(radiusReductionLeft); + radiusReductionRight = numberOrZero(radiusReductionRight); + radiusReductionTop = numberOrZero(radiusReductionTop); + radiusReductionBottom = numberOrZero(radiusReductionBottom); + + me.drawingArea = Math.min( + Math.round(largestPossibleRadius - (radiusReductionLeft + radiusReductionRight) / 2), + Math.round(largestPossibleRadius - (radiusReductionTop + radiusReductionBottom) / 2)); + me.setCenterPoint(radiusReductionLeft, radiusReductionRight, radiusReductionTop, radiusReductionBottom); + }, + setCenterPoint: function(leftMovement, rightMovement, topMovement, bottomMovement) { + var me = this; + var maxRight = me.width - rightMovement - me.drawingArea; + var maxLeft = leftMovement + me.drawingArea; + var maxTop = topMovement + me.drawingArea; + var maxBottom = me.height - bottomMovement - me.drawingArea; + + me.xCenter = Math.round(((maxLeft + maxRight) / 2) + me.left); + me.yCenter = Math.round(((maxTop + maxBottom) / 2) + me.top); + }, + + getIndexAngle: function(index) { + var angleMultiplier = (Math.PI * 2) / getValueCount(this); + var startAngle = this.chart.options && this.chart.options.startAngle ? + this.chart.options.startAngle : + 0; + + var startAngleRadians = startAngle * Math.PI * 2 / 360; + + // Start from the top instead of right, so remove a quarter of the circle + return index * angleMultiplier + startAngleRadians; + }, + getDistanceFromCenterForValue: function(value) { + var me = this; + + if (value === null) { + return 0; // null always in center + } + + // Take into account half font size + the yPadding of the top value + var scalingFactor = me.drawingArea / (me.max - me.min); + if (me.options.ticks.reverse) { + return (me.max - value) * scalingFactor; + } + return (value - me.min) * scalingFactor; + }, + getPointPosition: function(index, distanceFromCenter) { + var me = this; + var thisAngle = me.getIndexAngle(index) - (Math.PI / 2); + return { + x: Math.round(Math.cos(thisAngle) * distanceFromCenter) + me.xCenter, + y: Math.round(Math.sin(thisAngle) * distanceFromCenter) + me.yCenter + }; + }, + getPointPositionForValue: function(index, value) { + return this.getPointPosition(index, this.getDistanceFromCenterForValue(value)); + }, + + getBasePosition: function() { + var me = this; + var min = me.min; + var max = me.max; + + return me.getPointPositionForValue(0, + me.beginAtZero ? 0 : + min < 0 && max < 0 ? max : + min > 0 && max > 0 ? min : + 0); + }, + + draw: function() { + var me = this; + var opts = me.options; + var gridLineOpts = opts.gridLines; + var tickOpts = opts.ticks; + var valueOrDefault = helpers.valueOrDefault; + + if (opts.display) { + var ctx = me.ctx; + var startAngle = this.getIndexAngle(0); + + // Tick Font + var tickFontSize = valueOrDefault(tickOpts.fontSize, globalDefaults.defaultFontSize); + var tickFontStyle = valueOrDefault(tickOpts.fontStyle, globalDefaults.defaultFontStyle); + var tickFontFamily = valueOrDefault(tickOpts.fontFamily, globalDefaults.defaultFontFamily); + var tickLabelFont = helpers.fontString(tickFontSize, tickFontStyle, tickFontFamily); + + helpers.each(me.ticks, function(label, index) { + // Don't draw a centre value (if it is minimum) + if (index > 0 || tickOpts.reverse) { + var yCenterOffset = me.getDistanceFromCenterForValue(me.ticksAsNumbers[index]); + + // Draw circular lines around the scale + if (gridLineOpts.display && index !== 0) { + drawRadiusLine(me, gridLineOpts, yCenterOffset, index); + } + + if (tickOpts.display) { + var tickFontColor = valueOrDefault(tickOpts.fontColor, globalDefaults.defaultFontColor); + ctx.font = tickLabelFont; + + ctx.save(); + ctx.translate(me.xCenter, me.yCenter); + ctx.rotate(startAngle); + + if (tickOpts.showLabelBackdrop) { + var labelWidth = ctx.measureText(label).width; + ctx.fillStyle = tickOpts.backdropColor; + ctx.fillRect( + -labelWidth / 2 - tickOpts.backdropPaddingX, + -yCenterOffset - tickFontSize / 2 - tickOpts.backdropPaddingY, + labelWidth + tickOpts.backdropPaddingX * 2, + tickFontSize + tickOpts.backdropPaddingY * 2 + ); + } + + ctx.textAlign = 'center'; + ctx.textBaseline = 'middle'; + ctx.fillStyle = tickFontColor; + ctx.fillText(label, 0, -yCenterOffset); + ctx.restore(); + } + } + }); + + if (opts.angleLines.display || opts.pointLabels.display) { + drawPointLabels(me); + } + } + } + }); + Chart.scaleService.registerScaleType('radialLinear', LinearRadialScale, defaultConfig); + +}; + +},{"25":25,"34":34,"45":45}],57:[function(require,module,exports){ +/* global window: false */ +'use strict'; + +var moment = require(6); +moment = typeof moment === 'function' ? moment : window.moment; + +var defaults = require(25); +var helpers = require(45); + +// Integer constants are from the ES6 spec. +var MIN_INTEGER = Number.MIN_SAFE_INTEGER || -9007199254740991; +var MAX_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991; + +var INTERVALS = { + millisecond: { + common: true, + size: 1, + steps: [1, 2, 5, 10, 20, 50, 100, 250, 500] + }, + second: { + common: true, + size: 1000, + steps: [1, 2, 5, 10, 30] + }, + minute: { + common: true, + size: 60000, + steps: [1, 2, 5, 10, 30] + }, + hour: { + common: true, + size: 3600000, + steps: [1, 2, 3, 6, 12] + }, + day: { + common: true, + size: 86400000, + steps: [1, 2, 5] + }, + week: { + common: false, + size: 604800000, + steps: [1, 2, 3, 4] + }, + month: { + common: true, + size: 2.628e9, + steps: [1, 2, 3] + }, + quarter: { + common: false, + size: 7.884e9, + steps: [1, 2, 3, 4] + }, + year: { + common: true, + size: 3.154e10 + } +}; + +var UNITS = Object.keys(INTERVALS); + +function sorter(a, b) { + return a - b; +} + +function arrayUnique(items) { + var hash = {}; + var out = []; + var i, ilen, item; + + for (i = 0, ilen = items.length; i < ilen; ++i) { + item = items[i]; + if (!hash[item]) { + hash[item] = true; + out.push(item); + } + } + + return out; +} + +/** + * Returns an array of {time, pos} objects used to interpolate a specific `time` or position + * (`pos`) on the scale, by searching entries before and after the requested value. `pos` is + * a decimal between 0 and 1: 0 being the start of the scale (left or top) and 1 the other + * extremity (left + width or top + height). Note that it would be more optimized to directly + * store pre-computed pixels, but the scale dimensions are not guaranteed at the time we need + * to create the lookup table. The table ALWAYS contains at least two items: min and max. + * + * @param {Number[]} timestamps - timestamps sorted from lowest to highest. + * @param {String} distribution - If 'linear', timestamps will be spread linearly along the min + * and max range, so basically, the table will contains only two items: {min, 0} and {max, 1}. + * If 'series', timestamps will be positioned at the same distance from each other. In this + * case, only timestamps that break the time linearity are registered, meaning that in the + * best case, all timestamps are linear, the table contains only min and max. + */ +function buildLookupTable(timestamps, min, max, distribution) { + if (distribution === 'linear' || !timestamps.length) { + return [ + {time: min, pos: 0}, + {time: max, pos: 1} + ]; + } + + var table = []; + var items = [min]; + var i, ilen, prev, curr, next; + + for (i = 0, ilen = timestamps.length; i < ilen; ++i) { + curr = timestamps[i]; + if (curr > min && curr < max) { + items.push(curr); + } + } + + items.push(max); + + for (i = 0, ilen = items.length; i < ilen; ++i) { + next = items[i + 1]; + prev = items[i - 1]; + curr = items[i]; + + // only add points that breaks the scale linearity + if (prev === undefined || next === undefined || Math.round((next + prev) / 2) !== curr) { + table.push({time: curr, pos: i / (ilen - 1)}); + } + } + + return table; +} + +// @see adapted from http://www.anujgakhar.com/2014/03/01/binary-search-in-javascript/ +function lookup(table, key, value) { + var lo = 0; + var hi = table.length - 1; + var mid, i0, i1; + + while (lo >= 0 && lo <= hi) { + mid = (lo + hi) >> 1; + i0 = table[mid - 1] || null; + i1 = table[mid]; + + if (!i0) { + // given value is outside table (before first item) + return {lo: null, hi: i1}; + } else if (i1[key] < value) { + lo = mid + 1; + } else if (i0[key] > value) { + hi = mid - 1; + } else { + return {lo: i0, hi: i1}; + } + } + + // given value is outside table (after last item) + return {lo: i1, hi: null}; +} + +/** + * Linearly interpolates the given source `value` using the table items `skey` values and + * returns the associated `tkey` value. For example, interpolate(table, 'time', 42, 'pos') + * returns the position for a timestamp equal to 42. If value is out of bounds, values at + * index [0, 1] or [n - 1, n] are used for the interpolation. + */ +function interpolate(table, skey, sval, tkey) { + var range = lookup(table, skey, sval); + + // Note: the lookup table ALWAYS contains at least 2 items (min and max) + var prev = !range.lo ? table[0] : !range.hi ? table[table.length - 2] : range.lo; + var next = !range.lo ? table[1] : !range.hi ? table[table.length - 1] : range.hi; + + var span = next[skey] - prev[skey]; + var ratio = span ? (sval - prev[skey]) / span : 0; + var offset = (next[tkey] - prev[tkey]) * ratio; + + return prev[tkey] + offset; +} + +/** + * Convert the given value to a moment object using the given time options. + * @see http://momentjs.com/docs/#/parsing/ + */ +function momentify(value, options) { + var parser = options.parser; + var format = options.parser || options.format; + + if (typeof parser === 'function') { + return parser(value); + } + + if (typeof value === 'string' && typeof format === 'string') { + return moment(value, format); + } + + if (!(value instanceof moment)) { + value = moment(value); + } + + if (value.isValid()) { + return value; + } + + // Labels are in an incompatible moment format and no `parser` has been provided. + // The user might still use the deprecated `format` option to convert his inputs. + if (typeof format === 'function') { + return format(value); + } + + return value; +} + +function parse(input, scale) { + if (helpers.isNullOrUndef(input)) { + return null; + } + + var options = scale.options.time; + var value = momentify(scale.getRightValue(input), options); + if (!value.isValid()) { + return null; + } + + if (options.round) { + value.startOf(options.round); + } + + return value.valueOf(); +} + +/** + * Returns the number of unit to skip to be able to display up to `capacity` number of ticks + * in `unit` for the given `min` / `max` range and respecting the interval steps constraints. + */ +function determineStepSize(min, max, unit, capacity) { + var range = max - min; + var interval = INTERVALS[unit]; + var milliseconds = interval.size; + var steps = interval.steps; + var i, ilen, factor; + + if (!steps) { + return Math.ceil(range / ((capacity || 1) * milliseconds)); + } + + for (i = 0, ilen = steps.length; i < ilen; ++i) { + factor = steps[i]; + if (Math.ceil(range / (milliseconds * factor)) <= capacity) { + break; + } + } + + return factor; +} + +/** + * Figures out what unit results in an appropriate number of auto-generated ticks + */ +function determineUnitForAutoTicks(minUnit, min, max, capacity) { + var ilen = UNITS.length; + var i, interval, factor; + + for (i = UNITS.indexOf(minUnit); i < ilen - 1; ++i) { + interval = INTERVALS[UNITS[i]]; + factor = interval.steps ? interval.steps[interval.steps.length - 1] : MAX_INTEGER; + + if (interval.common && Math.ceil((max - min) / (factor * interval.size)) <= capacity) { + return UNITS[i]; + } + } + + return UNITS[ilen - 1]; +} + +/** + * Figures out what unit to format a set of ticks with + */ +function determineUnitForFormatting(ticks, minUnit, min, max) { + var duration = moment.duration(moment(max).diff(moment(min))); + var ilen = UNITS.length; + var i, unit; + + for (i = ilen - 1; i >= UNITS.indexOf(minUnit); i--) { + unit = UNITS[i]; + if (INTERVALS[unit].common && duration.as(unit) >= ticks.length) { + return unit; + } + } + + return UNITS[minUnit ? UNITS.indexOf(minUnit) : 0]; +} + +function determineMajorUnit(unit) { + for (var i = UNITS.indexOf(unit) + 1, ilen = UNITS.length; i < ilen; ++i) { + if (INTERVALS[UNITS[i]].common) { + return UNITS[i]; + } + } +} + +/** + * Generates a maximum of `capacity` timestamps between min and max, rounded to the + * `minor` unit, aligned on the `major` unit and using the given scale time `options`. + * Important: this method can return ticks outside the min and max range, it's the + * responsibility of the calling code to clamp values if needed. + */ +function generate(min, max, capacity, options) { + var timeOpts = options.time; + var minor = timeOpts.unit || determineUnitForAutoTicks(timeOpts.minUnit, min, max, capacity); + var major = determineMajorUnit(minor); + var stepSize = helpers.valueOrDefault(timeOpts.stepSize, timeOpts.unitStepSize); + var weekday = minor === 'week' ? timeOpts.isoWeekday : false; + var majorTicksEnabled = options.ticks.major.enabled; + var interval = INTERVALS[minor]; + var first = moment(min); + var last = moment(max); + var ticks = []; + var time; + + if (!stepSize) { + stepSize = determineStepSize(min, max, minor, capacity); + } + + // For 'week' unit, handle the first day of week option + if (weekday) { + first = first.isoWeekday(weekday); + last = last.isoWeekday(weekday); + } + + // Align first/last ticks on unit + first = first.startOf(weekday ? 'day' : minor); + last = last.startOf(weekday ? 'day' : minor); + + // Make sure that the last tick include max + if (last < max) { + last.add(1, minor); + } + + time = moment(first); + + if (majorTicksEnabled && major && !weekday && !timeOpts.round) { + // Align the first tick on the previous `minor` unit aligned on the `major` unit: + // we first aligned time on the previous `major` unit then add the number of full + // stepSize there is between first and the previous major time. + time.startOf(major); + time.add(~~((first - time) / (interval.size * stepSize)) * stepSize, minor); + } + + for (; time < last; time.add(stepSize, minor)) { + ticks.push(+time); + } + + ticks.push(+time); + + return ticks; +} + +/** + * Returns the right and left offsets from edges in the form of {left, right}. + * Offsets are added when the `offset` option is true. + */ +function computeOffsets(table, ticks, min, max, options) { + var left = 0; + var right = 0; + var upper, lower; + + if (options.offset && ticks.length) { + if (!options.time.min) { + upper = ticks.length > 1 ? ticks[1] : max; + lower = ticks[0]; + left = ( + interpolate(table, 'time', upper, 'pos') - + interpolate(table, 'time', lower, 'pos') + ) / 2; + } + if (!options.time.max) { + upper = ticks[ticks.length - 1]; + lower = ticks.length > 1 ? ticks[ticks.length - 2] : min; + right = ( + interpolate(table, 'time', upper, 'pos') - + interpolate(table, 'time', lower, 'pos') + ) / 2; + } + } + + return {left: left, right: right}; +} + +function ticksFromTimestamps(values, majorUnit) { + var ticks = []; + var i, ilen, value, major; + + for (i = 0, ilen = values.length; i < ilen; ++i) { + value = values[i]; + major = majorUnit ? value === +moment(value).startOf(majorUnit) : false; + + ticks.push({ + value: value, + major: major + }); + } + + return ticks; +} + +module.exports = function(Chart) { + + var defaultConfig = { + position: 'bottom', + + /** + * Data distribution along the scale: + * - 'linear': data are spread according to their time (distances can vary), + * - 'series': data are spread at the same distance from each other. + * @see https://github.com/chartjs/Chart.js/pull/4507 + * @since 2.7.0 + */ + distribution: 'linear', + + /** + * Scale boundary strategy (bypassed by min/max time options) + * - `data`: make sure data are fully visible, ticks outside are removed + * - `ticks`: make sure ticks are fully visible, data outside are truncated + * @see https://github.com/chartjs/Chart.js/pull/4556 + * @since 2.7.0 + */ + bounds: 'data', + + time: { + parser: false, // false == a pattern string from http://momentjs.com/docs/#/parsing/string-format/ or a custom callback that converts its argument to a moment + format: false, // DEPRECATED false == date objects, moment object, callback or a pattern string from http://momentjs.com/docs/#/parsing/string-format/ + unit: false, // false == automatic or override with week, month, year, etc. + round: false, // none, or override with week, month, year, etc. + displayFormat: false, // DEPRECATED + isoWeekday: false, // override week start day - see http://momentjs.com/docs/#/get-set/iso-weekday/ + minUnit: 'millisecond', + + // defaults to unit's corresponding unitFormat below or override using pattern string from http://momentjs.com/docs/#/displaying/format/ + displayFormats: { + millisecond: 'h:mm:ss.SSS a', // 11:20:01.123 AM, + second: 'h:mm:ss a', // 11:20:01 AM + minute: 'h:mm a', // 11:20 AM + hour: 'hA', // 5PM + day: 'MMM D', // Sep 4 + week: 'll', // Week 46, or maybe "[W]WW - YYYY" ? + month: 'MMM YYYY', // Sept 2015 + quarter: '[Q]Q - YYYY', // Q3 + year: 'YYYY' // 2015 + }, + }, + ticks: { + autoSkip: false, + + /** + * Ticks generation input values: + * - 'auto': generates "optimal" ticks based on scale size and time options. + * - 'data': generates ticks from data (including labels from data {t|x|y} objects). + * - 'labels': generates ticks from user given `data.labels` values ONLY. + * @see https://github.com/chartjs/Chart.js/pull/4507 + * @since 2.7.0 + */ + source: 'auto', + + major: { + enabled: false + } + } + }; + + var TimeScale = Chart.Scale.extend({ + initialize: function() { + if (!moment) { + throw new Error('Chart.js - Moment.js could not be found! You must include it before Chart.js to use the time scale. Download at https://momentjs.com'); + } + + this.mergeTicksOptions(); + + Chart.Scale.prototype.initialize.call(this); + }, + + update: function() { + var me = this; + var options = me.options; + + // DEPRECATIONS: output a message only one time per update + if (options.time && options.time.format) { + console.warn('options.time.format is deprecated and replaced by options.time.parser.'); + } + + return Chart.Scale.prototype.update.apply(me, arguments); + }, + + /** + * Allows data to be referenced via 't' attribute + */ + getRightValue: function(rawValue) { + if (rawValue && rawValue.t !== undefined) { + rawValue = rawValue.t; + } + return Chart.Scale.prototype.getRightValue.call(this, rawValue); + }, + + determineDataLimits: function() { + var me = this; + var chart = me.chart; + var timeOpts = me.options.time; + var min = MAX_INTEGER; + var max = MIN_INTEGER; + var timestamps = []; + var datasets = []; + var labels = []; + var i, j, ilen, jlen, data, timestamp; + + // Convert labels to timestamps + for (i = 0, ilen = chart.data.labels.length; i < ilen; ++i) { + labels.push(parse(chart.data.labels[i], me)); + } + + // Convert data to timestamps + for (i = 0, ilen = (chart.data.datasets || []).length; i < ilen; ++i) { + if (chart.isDatasetVisible(i)) { + data = chart.data.datasets[i].data; + + // Let's consider that all data have the same format. + if (helpers.isObject(data[0])) { + datasets[i] = []; + + for (j = 0, jlen = data.length; j < jlen; ++j) { + timestamp = parse(data[j], me); + timestamps.push(timestamp); + datasets[i][j] = timestamp; + } + } else { + timestamps.push.apply(timestamps, labels); + datasets[i] = labels.slice(0); + } + } else { + datasets[i] = []; + } + } + + if (labels.length) { + // Sort labels **after** data have been converted + labels = arrayUnique(labels).sort(sorter); + min = Math.min(min, labels[0]); + max = Math.max(max, labels[labels.length - 1]); + } + + if (timestamps.length) { + timestamps = arrayUnique(timestamps).sort(sorter); + min = Math.min(min, timestamps[0]); + max = Math.max(max, timestamps[timestamps.length - 1]); + } + + min = parse(timeOpts.min, me) || min; + max = parse(timeOpts.max, me) || max; + + // In case there is no valid min/max, let's use today limits + min = min === MAX_INTEGER ? +moment().startOf('day') : min; + max = max === MIN_INTEGER ? +moment().endOf('day') + 1 : max; + + // Make sure that max is strictly higher than min (required by the lookup table) + me.min = Math.min(min, max); + me.max = Math.max(min + 1, max); + + // PRIVATE + me._horizontal = me.isHorizontal(); + me._table = []; + me._timestamps = { + data: timestamps, + datasets: datasets, + labels: labels + }; + }, + + buildTicks: function() { + var me = this; + var min = me.min; + var max = me.max; + var options = me.options; + var timeOpts = options.time; + var timestamps = []; + var ticks = []; + var i, ilen, timestamp; + + switch (options.ticks.source) { + case 'data': + timestamps = me._timestamps.data; + break; + case 'labels': + timestamps = me._timestamps.labels; + break; + case 'auto': + default: + timestamps = generate(min, max, me.getLabelCapacity(min), options); + } + + if (options.bounds === 'ticks' && timestamps.length) { + min = timestamps[0]; + max = timestamps[timestamps.length - 1]; + } + + // Enforce limits with user min/max options + min = parse(timeOpts.min, me) || min; + max = parse(timeOpts.max, me) || max; + + // Remove ticks outside the min/max range + for (i = 0, ilen = timestamps.length; i < ilen; ++i) { + timestamp = timestamps[i]; + if (timestamp >= min && timestamp <= max) { + ticks.push(timestamp); + } + } + + me.min = min; + me.max = max; + + // PRIVATE + me._unit = timeOpts.unit || determineUnitForFormatting(ticks, timeOpts.minUnit, me.min, me.max); + me._majorUnit = determineMajorUnit(me._unit); + me._table = buildLookupTable(me._timestamps.data, min, max, options.distribution); + me._offsets = computeOffsets(me._table, ticks, min, max, options); + + return ticksFromTimestamps(ticks, me._majorUnit); + }, + + getLabelForIndex: function(index, datasetIndex) { + var me = this; + var data = me.chart.data; + var timeOpts = me.options.time; + var label = data.labels && index < data.labels.length ? data.labels[index] : ''; + var value = data.datasets[datasetIndex].data[index]; + + if (helpers.isObject(value)) { + label = me.getRightValue(value); + } + if (timeOpts.tooltipFormat) { + label = momentify(label, timeOpts).format(timeOpts.tooltipFormat); + } + + return label; + }, + + /** + * Function to format an individual tick mark + * @private + */ + tickFormatFunction: function(tick, index, ticks, formatOverride) { + var me = this; + var options = me.options; + var time = tick.valueOf(); + var formats = options.time.displayFormats; + var minorFormat = formats[me._unit]; + var majorUnit = me._majorUnit; + var majorFormat = formats[majorUnit]; + var majorTime = tick.clone().startOf(majorUnit).valueOf(); + var majorTickOpts = options.ticks.major; + var major = majorTickOpts.enabled && majorUnit && majorFormat && time === majorTime; + var label = tick.format(formatOverride ? formatOverride : major ? majorFormat : minorFormat); + var tickOpts = major ? majorTickOpts : options.ticks.minor; + var formatter = helpers.valueOrDefault(tickOpts.callback, tickOpts.userCallback); + + return formatter ? formatter(label, index, ticks) : label; + }, + + convertTicksToLabels: function(ticks) { + var labels = []; + var i, ilen; + + for (i = 0, ilen = ticks.length; i < ilen; ++i) { + labels.push(this.tickFormatFunction(moment(ticks[i].value), i, ticks)); + } + + return labels; + }, + + /** + * @private + */ + getPixelForOffset: function(time) { + var me = this; + var size = me._horizontal ? me.width : me.height; + var start = me._horizontal ? me.left : me.top; + var pos = interpolate(me._table, 'time', time, 'pos'); + + return start + size * (me._offsets.left + pos) / (me._offsets.left + 1 + me._offsets.right); + }, + + getPixelForValue: function(value, index, datasetIndex) { + var me = this; + var time = null; + + if (index !== undefined && datasetIndex !== undefined) { + time = me._timestamps.datasets[datasetIndex][index]; + } + + if (time === null) { + time = parse(value, me); + } + + if (time !== null) { + return me.getPixelForOffset(time); + } + }, + + getPixelForTick: function(index) { + var ticks = this.getTicks(); + return index >= 0 && index < ticks.length ? + this.getPixelForOffset(ticks[index].value) : + null; + }, + + getValueForPixel: function(pixel) { + var me = this; + var size = me._horizontal ? me.width : me.height; + var start = me._horizontal ? me.left : me.top; + var pos = (size ? (pixel - start) / size : 0) * (me._offsets.left + 1 + me._offsets.left) - me._offsets.right; + var time = interpolate(me._table, 'pos', pos, 'time'); + + return moment(time); + }, + + /** + * Crude approximation of what the label width might be + * @private + */ + getLabelWidth: function(label) { + var me = this; + var ticksOpts = me.options.ticks; + var tickLabelWidth = me.ctx.measureText(label).width; + var angle = helpers.toRadians(ticksOpts.maxRotation); + var cosRotation = Math.cos(angle); + var sinRotation = Math.sin(angle); + var tickFontSize = helpers.valueOrDefault(ticksOpts.fontSize, defaults.global.defaultFontSize); + + return (tickLabelWidth * cosRotation) + (tickFontSize * sinRotation); + }, + + /** + * @private + */ + getLabelCapacity: function(exampleTime) { + var me = this; + + var formatOverride = me.options.time.displayFormats.millisecond; // Pick the longest format for guestimation + + var exampleLabel = me.tickFormatFunction(moment(exampleTime), 0, [], formatOverride); + var tickLabelWidth = me.getLabelWidth(exampleLabel); + var innerWidth = me.isHorizontal() ? me.width : me.height; + + return Math.floor(innerWidth / tickLabelWidth); + } + }); + + Chart.scaleService.registerScaleType('time', TimeScale, defaultConfig); +}; + +},{"25":25,"45":45,"6":6}]},{},[7])(7) +}); \ No newline at end of file diff --git a/www/static/js/direction.js b/www/static/js/direction.js new file mode 100644 index 000000000..eb02c4d8d --- /dev/null +++ b/www/static/js/direction.js @@ -0,0 +1,16 @@ +var dir2Char = { + NONE: '⇼' + , DoubleUp: '⇈' + , SingleUp: '↑' + , FortyFiveUp: '↗' + , Flat: '→' + , FortyFiveDown: '↘' + , SingleDown: '↓' + , DoubleDown: '⇊' + , 'NOT COMPUTABLE': '-' + , 'RATE OUT OF RANGE': '⇕' +}; + +function directionToChar(direction) { + return dir2Char[direction] || '-'; +} \ No newline at end of file diff --git a/www/static/js/jquery.min.js b/www/static/js/jquery.min.js new file mode 100644 index 000000000..bcd3956c8 --- /dev/null +++ b/www/static/js/jquery.min.js @@ -0,0 +1,4 @@ +/*! jQuery v3.2.1 | (c) JS Foundation and other contributors | jquery.org/license */ +!function(a,b){"use strict";"object"==typeof module&&"object"==typeof module.exports?module.exports=a.document?b(a,!0):function(a){if(!a.document)throw new Error("jQuery requires a window with a document");return b(a)}:b(a)}("undefined"!=typeof window?window:this,function(a,b){"use strict";var c=[],d=a.document,e=Object.getPrototypeOf,f=c.slice,g=c.concat,h=c.push,i=c.indexOf,j={},k=j.toString,l=j.hasOwnProperty,m=l.toString,n=m.call(Object),o={};function p(a,b){b=b||d;var c=b.createElement("script");c.text=a,b.head.appendChild(c).parentNode.removeChild(c)}var q="3.2.1",r=function(a,b){return new r.fn.init(a,b)},s=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,t=/^-ms-/,u=/-([a-z])/g,v=function(a,b){return b.toUpperCase()};r.fn=r.prototype={jquery:q,constructor:r,length:0,toArray:function(){return f.call(this)},get:function(a){return null==a?f.call(this):a<0?this[a+this.length]:this[a]},pushStack:function(a){var b=r.merge(this.constructor(),a);return b.prevObject=this,b},each:function(a){return r.each(this,a)},map:function(a){return this.pushStack(r.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return this.pushStack(f.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(a){var b=this.length,c=+a+(a<0?b:0);return this.pushStack(c>=0&&c0&&b-1 in a)}var x=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u="sizzle"+1*new Date,v=a.document,w=0,x=0,y=ha(),z=ha(),A=ha(),B=function(a,b){return a===b&&(l=!0),0},C={}.hasOwnProperty,D=[],E=D.pop,F=D.push,G=D.push,H=D.slice,I=function(a,b){for(var c=0,d=a.length;c+~]|"+K+")"+K+"*"),S=new RegExp("="+K+"*([^\\]'\"]*?)"+K+"*\\]","g"),T=new RegExp(N),U=new RegExp("^"+L+"$"),V={ID:new RegExp("^#("+L+")"),CLASS:new RegExp("^\\.("+L+")"),TAG:new RegExp("^("+L+"|[*])"),ATTR:new RegExp("^"+M),PSEUDO:new RegExp("^"+N),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+K+"*(even|odd|(([+-]|)(\\d*)n|)"+K+"*(?:([+-]|)"+K+"*(\\d+)|))"+K+"*\\)|)","i"),bool:new RegExp("^(?:"+J+")$","i"),needsContext:new RegExp("^"+K+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+K+"*((?:-\\d)?\\d*)"+K+"*\\)|)(?=[^-]|$)","i")},W=/^(?:input|select|textarea|button)$/i,X=/^h\d$/i,Y=/^[^{]+\{\s*\[native \w/,Z=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,$=/[+~]/,_=new RegExp("\\\\([\\da-f]{1,6}"+K+"?|("+K+")|.)","ig"),aa=function(a,b,c){var d="0x"+b-65536;return d!==d||c?b:d<0?String.fromCharCode(d+65536):String.fromCharCode(d>>10|55296,1023&d|56320)},ba=/([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g,ca=function(a,b){return b?"\0"===a?"\ufffd":a.slice(0,-1)+"\\"+a.charCodeAt(a.length-1).toString(16)+" ":"\\"+a},da=function(){m()},ea=ta(function(a){return a.disabled===!0&&("form"in a||"label"in a)},{dir:"parentNode",next:"legend"});try{G.apply(D=H.call(v.childNodes),v.childNodes),D[v.childNodes.length].nodeType}catch(fa){G={apply:D.length?function(a,b){F.apply(a,H.call(b))}:function(a,b){var c=a.length,d=0;while(a[c++]=b[d++]);a.length=c-1}}}function ga(a,b,d,e){var f,h,j,k,l,o,r,s=b&&b.ownerDocument,w=b?b.nodeType:9;if(d=d||[],"string"!=typeof a||!a||1!==w&&9!==w&&11!==w)return d;if(!e&&((b?b.ownerDocument||b:v)!==n&&m(b),b=b||n,p)){if(11!==w&&(l=Z.exec(a)))if(f=l[1]){if(9===w){if(!(j=b.getElementById(f)))return d;if(j.id===f)return d.push(j),d}else if(s&&(j=s.getElementById(f))&&t(b,j)&&j.id===f)return d.push(j),d}else{if(l[2])return G.apply(d,b.getElementsByTagName(a)),d;if((f=l[3])&&c.getElementsByClassName&&b.getElementsByClassName)return G.apply(d,b.getElementsByClassName(f)),d}if(c.qsa&&!A[a+" "]&&(!q||!q.test(a))){if(1!==w)s=b,r=a;else if("object"!==b.nodeName.toLowerCase()){(k=b.getAttribute("id"))?k=k.replace(ba,ca):b.setAttribute("id",k=u),o=g(a),h=o.length;while(h--)o[h]="#"+k+" "+sa(o[h]);r=o.join(","),s=$.test(a)&&qa(b.parentNode)||b}if(r)try{return G.apply(d,s.querySelectorAll(r)),d}catch(x){}finally{k===u&&b.removeAttribute("id")}}}return i(a.replace(P,"$1"),b,d,e)}function ha(){var a=[];function b(c,e){return a.push(c+" ")>d.cacheLength&&delete b[a.shift()],b[c+" "]=e}return b}function ia(a){return a[u]=!0,a}function ja(a){var b=n.createElement("fieldset");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function ka(a,b){var c=a.split("|"),e=c.length;while(e--)d.attrHandle[c[e]]=b}function la(a,b){var c=b&&a,d=c&&1===a.nodeType&&1===b.nodeType&&a.sourceIndex-b.sourceIndex;if(d)return d;if(c)while(c=c.nextSibling)if(c===b)return-1;return a?1:-1}function ma(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function na(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function oa(a){return function(b){return"form"in b?b.parentNode&&b.disabled===!1?"label"in b?"label"in b.parentNode?b.parentNode.disabled===a:b.disabled===a:b.isDisabled===a||b.isDisabled!==!a&&ea(b)===a:b.disabled===a:"label"in b&&b.disabled===a}}function pa(a){return ia(function(b){return b=+b,ia(function(c,d){var e,f=a([],c.length,b),g=f.length;while(g--)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function qa(a){return a&&"undefined"!=typeof a.getElementsByTagName&&a}c=ga.support={},f=ga.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return!!b&&"HTML"!==b.nodeName},m=ga.setDocument=function(a){var b,e,g=a?a.ownerDocument||a:v;return g!==n&&9===g.nodeType&&g.documentElement?(n=g,o=n.documentElement,p=!f(n),v!==n&&(e=n.defaultView)&&e.top!==e&&(e.addEventListener?e.addEventListener("unload",da,!1):e.attachEvent&&e.attachEvent("onunload",da)),c.attributes=ja(function(a){return a.className="i",!a.getAttribute("className")}),c.getElementsByTagName=ja(function(a){return a.appendChild(n.createComment("")),!a.getElementsByTagName("*").length}),c.getElementsByClassName=Y.test(n.getElementsByClassName),c.getById=ja(function(a){return o.appendChild(a).id=u,!n.getElementsByName||!n.getElementsByName(u).length}),c.getById?(d.filter.ID=function(a){var b=a.replace(_,aa);return function(a){return a.getAttribute("id")===b}},d.find.ID=function(a,b){if("undefined"!=typeof b.getElementById&&p){var c=b.getElementById(a);return c?[c]:[]}}):(d.filter.ID=function(a){var b=a.replace(_,aa);return function(a){var c="undefined"!=typeof a.getAttributeNode&&a.getAttributeNode("id");return c&&c.value===b}},d.find.ID=function(a,b){if("undefined"!=typeof b.getElementById&&p){var c,d,e,f=b.getElementById(a);if(f){if(c=f.getAttributeNode("id"),c&&c.value===a)return[f];e=b.getElementsByName(a),d=0;while(f=e[d++])if(c=f.getAttributeNode("id"),c&&c.value===a)return[f]}return[]}}),d.find.TAG=c.getElementsByTagName?function(a,b){return"undefined"!=typeof b.getElementsByTagName?b.getElementsByTagName(a):c.qsa?b.querySelectorAll(a):void 0}:function(a,b){var c,d=[],e=0,f=b.getElementsByTagName(a);if("*"===a){while(c=f[e++])1===c.nodeType&&d.push(c);return d}return f},d.find.CLASS=c.getElementsByClassName&&function(a,b){if("undefined"!=typeof b.getElementsByClassName&&p)return b.getElementsByClassName(a)},r=[],q=[],(c.qsa=Y.test(n.querySelectorAll))&&(ja(function(a){o.appendChild(a).innerHTML="",a.querySelectorAll("[msallowcapture^='']").length&&q.push("[*^$]="+K+"*(?:''|\"\")"),a.querySelectorAll("[selected]").length||q.push("\\["+K+"*(?:value|"+J+")"),a.querySelectorAll("[id~="+u+"-]").length||q.push("~="),a.querySelectorAll(":checked").length||q.push(":checked"),a.querySelectorAll("a#"+u+"+*").length||q.push(".#.+[+~]")}),ja(function(a){a.innerHTML="";var b=n.createElement("input");b.setAttribute("type","hidden"),a.appendChild(b).setAttribute("name","D"),a.querySelectorAll("[name=d]").length&&q.push("name"+K+"*[*^$|!~]?="),2!==a.querySelectorAll(":enabled").length&&q.push(":enabled",":disabled"),o.appendChild(a).disabled=!0,2!==a.querySelectorAll(":disabled").length&&q.push(":enabled",":disabled"),a.querySelectorAll("*,:x"),q.push(",.*:")})),(c.matchesSelector=Y.test(s=o.matches||o.webkitMatchesSelector||o.mozMatchesSelector||o.oMatchesSelector||o.msMatchesSelector))&&ja(function(a){c.disconnectedMatch=s.call(a,"*"),s.call(a,"[s!='']:x"),r.push("!=",N)}),q=q.length&&new RegExp(q.join("|")),r=r.length&&new RegExp(r.join("|")),b=Y.test(o.compareDocumentPosition),t=b||Y.test(o.contains)?function(a,b){var c=9===a.nodeType?a.documentElement:a,d=b&&b.parentNode;return a===d||!(!d||1!==d.nodeType||!(c.contains?c.contains(d):a.compareDocumentPosition&&16&a.compareDocumentPosition(d)))}:function(a,b){if(b)while(b=b.parentNode)if(b===a)return!0;return!1},B=b?function(a,b){if(a===b)return l=!0,0;var d=!a.compareDocumentPosition-!b.compareDocumentPosition;return d?d:(d=(a.ownerDocument||a)===(b.ownerDocument||b)?a.compareDocumentPosition(b):1,1&d||!c.sortDetached&&b.compareDocumentPosition(a)===d?a===n||a.ownerDocument===v&&t(v,a)?-1:b===n||b.ownerDocument===v&&t(v,b)?1:k?I(k,a)-I(k,b):0:4&d?-1:1)}:function(a,b){if(a===b)return l=!0,0;var c,d=0,e=a.parentNode,f=b.parentNode,g=[a],h=[b];if(!e||!f)return a===n?-1:b===n?1:e?-1:f?1:k?I(k,a)-I(k,b):0;if(e===f)return la(a,b);c=a;while(c=c.parentNode)g.unshift(c);c=b;while(c=c.parentNode)h.unshift(c);while(g[d]===h[d])d++;return d?la(g[d],h[d]):g[d]===v?-1:h[d]===v?1:0},n):n},ga.matches=function(a,b){return ga(a,null,null,b)},ga.matchesSelector=function(a,b){if((a.ownerDocument||a)!==n&&m(a),b=b.replace(S,"='$1']"),c.matchesSelector&&p&&!A[b+" "]&&(!r||!r.test(b))&&(!q||!q.test(b)))try{var d=s.call(a,b);if(d||c.disconnectedMatch||a.document&&11!==a.document.nodeType)return d}catch(e){}return ga(b,n,null,[a]).length>0},ga.contains=function(a,b){return(a.ownerDocument||a)!==n&&m(a),t(a,b)},ga.attr=function(a,b){(a.ownerDocument||a)!==n&&m(a);var e=d.attrHandle[b.toLowerCase()],f=e&&C.call(d.attrHandle,b.toLowerCase())?e(a,b,!p):void 0;return void 0!==f?f:c.attributes||!p?a.getAttribute(b):(f=a.getAttributeNode(b))&&f.specified?f.value:null},ga.escape=function(a){return(a+"").replace(ba,ca)},ga.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},ga.uniqueSort=function(a){var b,d=[],e=0,f=0;if(l=!c.detectDuplicates,k=!c.sortStable&&a.slice(0),a.sort(B),l){while(b=a[f++])b===a[f]&&(e=d.push(f));while(e--)a.splice(d[e],1)}return k=null,a},e=ga.getText=function(a){var b,c="",d=0,f=a.nodeType;if(f){if(1===f||9===f||11===f){if("string"==typeof a.textContent)return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=e(a)}else if(3===f||4===f)return a.nodeValue}else while(b=a[d++])c+=e(b);return c},d=ga.selectors={cacheLength:50,createPseudo:ia,match:V,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(_,aa),a[3]=(a[3]||a[4]||a[5]||"").replace(_,aa),"~="===a[2]&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),"nth"===a[1].slice(0,3)?(a[3]||ga.error(a[0]),a[4]=+(a[4]?a[5]+(a[6]||1):2*("even"===a[3]||"odd"===a[3])),a[5]=+(a[7]+a[8]||"odd"===a[3])):a[3]&&ga.error(a[0]),a},PSEUDO:function(a){var b,c=!a[6]&&a[2];return V.CHILD.test(a[0])?null:(a[3]?a[2]=a[4]||a[5]||"":c&&T.test(c)&&(b=g(c,!0))&&(b=c.indexOf(")",c.length-b)-c.length)&&(a[0]=a[0].slice(0,b),a[2]=c.slice(0,b)),a.slice(0,3))}},filter:{TAG:function(a){var b=a.replace(_,aa).toLowerCase();return"*"===a?function(){return!0}:function(a){return a.nodeName&&a.nodeName.toLowerCase()===b}},CLASS:function(a){var b=y[a+" "];return b||(b=new RegExp("(^|"+K+")"+a+"("+K+"|$)"))&&y(a,function(a){return b.test("string"==typeof a.className&&a.className||"undefined"!=typeof a.getAttribute&&a.getAttribute("class")||"")})},ATTR:function(a,b,c){return function(d){var e=ga.attr(d,a);return null==e?"!="===b:!b||(e+="","="===b?e===c:"!="===b?e!==c:"^="===b?c&&0===e.indexOf(c):"*="===b?c&&e.indexOf(c)>-1:"$="===b?c&&e.slice(-c.length)===c:"~="===b?(" "+e.replace(O," ")+" ").indexOf(c)>-1:"|="===b&&(e===c||e.slice(0,c.length+1)===c+"-"))}},CHILD:function(a,b,c,d,e){var f="nth"!==a.slice(0,3),g="last"!==a.slice(-4),h="of-type"===b;return 1===d&&0===e?function(a){return!!a.parentNode}:function(b,c,i){var j,k,l,m,n,o,p=f!==g?"nextSibling":"previousSibling",q=b.parentNode,r=h&&b.nodeName.toLowerCase(),s=!i&&!h,t=!1;if(q){if(f){while(p){m=b;while(m=m[p])if(h?m.nodeName.toLowerCase()===r:1===m.nodeType)return!1;o=p="only"===a&&!o&&"nextSibling"}return!0}if(o=[g?q.firstChild:q.lastChild],g&&s){m=q,l=m[u]||(m[u]={}),k=l[m.uniqueID]||(l[m.uniqueID]={}),j=k[a]||[],n=j[0]===w&&j[1],t=n&&j[2],m=n&&q.childNodes[n];while(m=++n&&m&&m[p]||(t=n=0)||o.pop())if(1===m.nodeType&&++t&&m===b){k[a]=[w,n,t];break}}else if(s&&(m=b,l=m[u]||(m[u]={}),k=l[m.uniqueID]||(l[m.uniqueID]={}),j=k[a]||[],n=j[0]===w&&j[1],t=n),t===!1)while(m=++n&&m&&m[p]||(t=n=0)||o.pop())if((h?m.nodeName.toLowerCase()===r:1===m.nodeType)&&++t&&(s&&(l=m[u]||(m[u]={}),k=l[m.uniqueID]||(l[m.uniqueID]={}),k[a]=[w,t]),m===b))break;return t-=e,t===d||t%d===0&&t/d>=0}}},PSEUDO:function(a,b){var c,e=d.pseudos[a]||d.setFilters[a.toLowerCase()]||ga.error("unsupported pseudo: "+a);return e[u]?e(b):e.length>1?(c=[a,a,"",b],d.setFilters.hasOwnProperty(a.toLowerCase())?ia(function(a,c){var d,f=e(a,b),g=f.length;while(g--)d=I(a,f[g]),a[d]=!(c[d]=f[g])}):function(a){return e(a,0,c)}):e}},pseudos:{not:ia(function(a){var b=[],c=[],d=h(a.replace(P,"$1"));return d[u]?ia(function(a,b,c,e){var f,g=d(a,null,e,[]),h=a.length;while(h--)(f=g[h])&&(a[h]=!(b[h]=f))}):function(a,e,f){return b[0]=a,d(b,null,f,c),b[0]=null,!c.pop()}}),has:ia(function(a){return function(b){return ga(a,b).length>0}}),contains:ia(function(a){return a=a.replace(_,aa),function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:ia(function(a){return U.test(a||"")||ga.error("unsupported lang: "+a),a=a.replace(_,aa).toLowerCase(),function(b){var c;do if(c=p?b.lang:b.getAttribute("xml:lang")||b.getAttribute("lang"))return c=c.toLowerCase(),c===a||0===c.indexOf(a+"-");while((b=b.parentNode)&&1===b.nodeType);return!1}}),target:function(b){var c=a.location&&a.location.hash;return c&&c.slice(1)===b.id},root:function(a){return a===o},focus:function(a){return a===n.activeElement&&(!n.hasFocus||n.hasFocus())&&!!(a.type||a.href||~a.tabIndex)},enabled:oa(!1),disabled:oa(!0),checked:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&!!a.checked||"option"===b&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},empty:function(a){for(a=a.firstChild;a;a=a.nextSibling)if(a.nodeType<6)return!1;return!0},parent:function(a){return!d.pseudos.empty(a)},header:function(a){return X.test(a.nodeName)},input:function(a){return W.test(a.nodeName)},button:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&"button"===a.type||"button"===b},text:function(a){var b;return"input"===a.nodeName.toLowerCase()&&"text"===a.type&&(null==(b=a.getAttribute("type"))||"text"===b.toLowerCase())},first:pa(function(){return[0]}),last:pa(function(a,b){return[b-1]}),eq:pa(function(a,b,c){return[c<0?c+b:c]}),even:pa(function(a,b){for(var c=0;c=0;)a.push(d);return a}),gt:pa(function(a,b,c){for(var d=c<0?c+b:c;++d1?function(b,c,d){var e=a.length;while(e--)if(!a[e](b,c,d))return!1;return!0}:a[0]}function va(a,b,c){for(var d=0,e=b.length;d-1&&(f[j]=!(g[j]=l))}}else r=wa(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):G.apply(g,r)})}function ya(a){for(var b,c,e,f=a.length,g=d.relative[a[0].type],h=g||d.relative[" "],i=g?1:0,k=ta(function(a){return a===b},h,!0),l=ta(function(a){return I(b,a)>-1},h,!0),m=[function(a,c,d){var e=!g&&(d||c!==j)||((b=c).nodeType?k(a,c,d):l(a,c,d));return b=null,e}];i1&&ua(m),i>1&&sa(a.slice(0,i-1).concat({value:" "===a[i-2].type?"*":""})).replace(P,"$1"),c,i0,e=a.length>0,f=function(f,g,h,i,k){var l,o,q,r=0,s="0",t=f&&[],u=[],v=j,x=f||e&&d.find.TAG("*",k),y=w+=null==v?1:Math.random()||.1,z=x.length;for(k&&(j=g===n||g||k);s!==z&&null!=(l=x[s]);s++){if(e&&l){o=0,g||l.ownerDocument===n||(m(l),h=!p);while(q=a[o++])if(q(l,g||n,h)){i.push(l);break}k&&(w=y)}c&&((l=!q&&l)&&r--,f&&t.push(l))}if(r+=s,c&&s!==r){o=0;while(q=b[o++])q(t,u,g,h);if(f){if(r>0)while(s--)t[s]||u[s]||(u[s]=E.call(i));u=wa(u)}G.apply(i,u),k&&!f&&u.length>0&&r+b.length>1&&ga.uniqueSort(i)}return k&&(w=y,j=v),t};return c?ia(f):f}return h=ga.compile=function(a,b){var c,d=[],e=[],f=A[a+" "];if(!f){b||(b=g(a)),c=b.length;while(c--)f=ya(b[c]),f[u]?d.push(f):e.push(f);f=A(a,za(e,d)),f.selector=a}return f},i=ga.select=function(a,b,c,e){var f,i,j,k,l,m="function"==typeof a&&a,n=!e&&g(a=m.selector||a);if(c=c||[],1===n.length){if(i=n[0]=n[0].slice(0),i.length>2&&"ID"===(j=i[0]).type&&9===b.nodeType&&p&&d.relative[i[1].type]){if(b=(d.find.ID(j.matches[0].replace(_,aa),b)||[])[0],!b)return c;m&&(b=b.parentNode),a=a.slice(i.shift().value.length)}f=V.needsContext.test(a)?0:i.length;while(f--){if(j=i[f],d.relative[k=j.type])break;if((l=d.find[k])&&(e=l(j.matches[0].replace(_,aa),$.test(i[0].type)&&qa(b.parentNode)||b))){if(i.splice(f,1),a=e.length&&sa(i),!a)return G.apply(c,e),c;break}}}return(m||h(a,n))(e,b,!p,c,!b||$.test(a)&&qa(b.parentNode)||b),c},c.sortStable=u.split("").sort(B).join("")===u,c.detectDuplicates=!!l,m(),c.sortDetached=ja(function(a){return 1&a.compareDocumentPosition(n.createElement("fieldset"))}),ja(function(a){return a.innerHTML="","#"===a.firstChild.getAttribute("href")})||ka("type|href|height|width",function(a,b,c){if(!c)return a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),c.attributes&&ja(function(a){return a.innerHTML="",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||ka("value",function(a,b,c){if(!c&&"input"===a.nodeName.toLowerCase())return a.defaultValue}),ja(function(a){return null==a.getAttribute("disabled")})||ka(J,function(a,b,c){var d;if(!c)return a[b]===!0?b.toLowerCase():(d=a.getAttributeNode(b))&&d.specified?d.value:null}),ga}(a);r.find=x,r.expr=x.selectors,r.expr[":"]=r.expr.pseudos,r.uniqueSort=r.unique=x.uniqueSort,r.text=x.getText,r.isXMLDoc=x.isXML,r.contains=x.contains,r.escapeSelector=x.escape;var y=function(a,b,c){var d=[],e=void 0!==c;while((a=a[b])&&9!==a.nodeType)if(1===a.nodeType){if(e&&r(a).is(c))break;d.push(a)}return d},z=function(a,b){for(var c=[];a;a=a.nextSibling)1===a.nodeType&&a!==b&&c.push(a);return c},A=r.expr.match.needsContext;function B(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()}var C=/^<([a-z][^\/\0>:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i,D=/^.[^:#\[\.,]*$/;function E(a,b,c){return r.isFunction(b)?r.grep(a,function(a,d){return!!b.call(a,d,a)!==c}):b.nodeType?r.grep(a,function(a){return a===b!==c}):"string"!=typeof b?r.grep(a,function(a){return i.call(b,a)>-1!==c}):D.test(b)?r.filter(b,a,c):(b=r.filter(b,a),r.grep(a,function(a){return i.call(b,a)>-1!==c&&1===a.nodeType}))}r.filter=function(a,b,c){var d=b[0];return c&&(a=":not("+a+")"),1===b.length&&1===d.nodeType?r.find.matchesSelector(d,a)?[d]:[]:r.find.matches(a,r.grep(b,function(a){return 1===a.nodeType}))},r.fn.extend({find:function(a){var b,c,d=this.length,e=this;if("string"!=typeof a)return this.pushStack(r(a).filter(function(){for(b=0;b1?r.uniqueSort(c):c},filter:function(a){return this.pushStack(E(this,a||[],!1))},not:function(a){return this.pushStack(E(this,a||[],!0))},is:function(a){return!!E(this,"string"==typeof a&&A.test(a)?r(a):a||[],!1).length}});var F,G=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]+))$/,H=r.fn.init=function(a,b,c){var e,f;if(!a)return this;if(c=c||F,"string"==typeof a){if(e="<"===a[0]&&">"===a[a.length-1]&&a.length>=3?[null,a,null]:G.exec(a),!e||!e[1]&&b)return!b||b.jquery?(b||c).find(a):this.constructor(b).find(a);if(e[1]){if(b=b instanceof r?b[0]:b,r.merge(this,r.parseHTML(e[1],b&&b.nodeType?b.ownerDocument||b:d,!0)),C.test(e[1])&&r.isPlainObject(b))for(e in b)r.isFunction(this[e])?this[e](b[e]):this.attr(e,b[e]);return this}return f=d.getElementById(e[2]),f&&(this[0]=f,this.length=1),this}return a.nodeType?(this[0]=a,this.length=1,this):r.isFunction(a)?void 0!==c.ready?c.ready(a):a(r):r.makeArray(a,this)};H.prototype=r.fn,F=r(d);var I=/^(?:parents|prev(?:Until|All))/,J={children:!0,contents:!0,next:!0,prev:!0};r.fn.extend({has:function(a){var b=r(a,this),c=b.length;return this.filter(function(){for(var a=0;a-1:1===c.nodeType&&r.find.matchesSelector(c,a))){f.push(c);break}return this.pushStack(f.length>1?r.uniqueSort(f):f)},index:function(a){return a?"string"==typeof a?i.call(r(a),this[0]):i.call(this,a.jquery?a[0]:a):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){return this.pushStack(r.uniqueSort(r.merge(this.get(),r(a,b))))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}});function K(a,b){while((a=a[b])&&1!==a.nodeType);return a}r.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return y(a,"parentNode")},parentsUntil:function(a,b,c){return y(a,"parentNode",c)},next:function(a){return K(a,"nextSibling")},prev:function(a){return K(a,"previousSibling")},nextAll:function(a){return y(a,"nextSibling")},prevAll:function(a){return y(a,"previousSibling")},nextUntil:function(a,b,c){return y(a,"nextSibling",c)},prevUntil:function(a,b,c){return y(a,"previousSibling",c)},siblings:function(a){return z((a.parentNode||{}).firstChild,a)},children:function(a){return z(a.firstChild)},contents:function(a){return B(a,"iframe")?a.contentDocument:(B(a,"template")&&(a=a.content||a),r.merge([],a.childNodes))}},function(a,b){r.fn[a]=function(c,d){var e=r.map(this,b,c);return"Until"!==a.slice(-5)&&(d=c),d&&"string"==typeof d&&(e=r.filter(d,e)),this.length>1&&(J[a]||r.uniqueSort(e),I.test(a)&&e.reverse()),this.pushStack(e)}});var L=/[^\x20\t\r\n\f]+/g;function M(a){var b={};return r.each(a.match(L)||[],function(a,c){b[c]=!0}),b}r.Callbacks=function(a){a="string"==typeof a?M(a):r.extend({},a);var b,c,d,e,f=[],g=[],h=-1,i=function(){for(e=e||a.once,d=b=!0;g.length;h=-1){c=g.shift();while(++h-1)f.splice(c,1),c<=h&&h--}),this},has:function(a){return a?r.inArray(a,f)>-1:f.length>0},empty:function(){return f&&(f=[]),this},disable:function(){return e=g=[],f=c="",this},disabled:function(){return!f},lock:function(){return e=g=[],c||b||(f=c=""),this},locked:function(){return!!e},fireWith:function(a,c){return e||(c=c||[],c=[a,c.slice?c.slice():c],g.push(c),b||i()),this},fire:function(){return j.fireWith(this,arguments),this},fired:function(){return!!d}};return j};function N(a){return a}function O(a){throw a}function P(a,b,c,d){var e;try{a&&r.isFunction(e=a.promise)?e.call(a).done(b).fail(c):a&&r.isFunction(e=a.then)?e.call(a,b,c):b.apply(void 0,[a].slice(d))}catch(a){c.apply(void 0,[a])}}r.extend({Deferred:function(b){var c=[["notify","progress",r.Callbacks("memory"),r.Callbacks("memory"),2],["resolve","done",r.Callbacks("once memory"),r.Callbacks("once memory"),0,"resolved"],["reject","fail",r.Callbacks("once memory"),r.Callbacks("once memory"),1,"rejected"]],d="pending",e={state:function(){return d},always:function(){return f.done(arguments).fail(arguments),this},"catch":function(a){return e.then(null,a)},pipe:function(){var a=arguments;return r.Deferred(function(b){r.each(c,function(c,d){var e=r.isFunction(a[d[4]])&&a[d[4]];f[d[1]](function(){var a=e&&e.apply(this,arguments);a&&r.isFunction(a.promise)?a.promise().progress(b.notify).done(b.resolve).fail(b.reject):b[d[0]+"With"](this,e?[a]:arguments)})}),a=null}).promise()},then:function(b,d,e){var f=0;function g(b,c,d,e){return function(){var h=this,i=arguments,j=function(){var a,j;if(!(b=f&&(d!==O&&(h=void 0,i=[a]),c.rejectWith(h,i))}};b?k():(r.Deferred.getStackHook&&(k.stackTrace=r.Deferred.getStackHook()),a.setTimeout(k))}}return r.Deferred(function(a){c[0][3].add(g(0,a,r.isFunction(e)?e:N,a.notifyWith)),c[1][3].add(g(0,a,r.isFunction(b)?b:N)),c[2][3].add(g(0,a,r.isFunction(d)?d:O))}).promise()},promise:function(a){return null!=a?r.extend(a,e):e}},f={};return r.each(c,function(a,b){var g=b[2],h=b[5];e[b[1]]=g.add,h&&g.add(function(){d=h},c[3-a][2].disable,c[0][2].lock),g.add(b[3].fire),f[b[0]]=function(){return f[b[0]+"With"](this===f?void 0:this,arguments),this},f[b[0]+"With"]=g.fireWith}),e.promise(f),b&&b.call(f,f),f},when:function(a){var b=arguments.length,c=b,d=Array(c),e=f.call(arguments),g=r.Deferred(),h=function(a){return function(c){d[a]=this,e[a]=arguments.length>1?f.call(arguments):c,--b||g.resolveWith(d,e)}};if(b<=1&&(P(a,g.done(h(c)).resolve,g.reject,!b),"pending"===g.state()||r.isFunction(e[c]&&e[c].then)))return g.then();while(c--)P(e[c],h(c),g.reject);return g.promise()}});var Q=/^(Eval|Internal|Range|Reference|Syntax|Type|URI)Error$/;r.Deferred.exceptionHook=function(b,c){a.console&&a.console.warn&&b&&Q.test(b.name)&&a.console.warn("jQuery.Deferred exception: "+b.message,b.stack,c)},r.readyException=function(b){a.setTimeout(function(){throw b})};var R=r.Deferred();r.fn.ready=function(a){return R.then(a)["catch"](function(a){r.readyException(a)}),this},r.extend({isReady:!1,readyWait:1,ready:function(a){(a===!0?--r.readyWait:r.isReady)||(r.isReady=!0,a!==!0&&--r.readyWait>0||R.resolveWith(d,[r]))}}),r.ready.then=R.then;function S(){d.removeEventListener("DOMContentLoaded",S), +a.removeEventListener("load",S),r.ready()}"complete"===d.readyState||"loading"!==d.readyState&&!d.documentElement.doScroll?a.setTimeout(r.ready):(d.addEventListener("DOMContentLoaded",S),a.addEventListener("load",S));var T=function(a,b,c,d,e,f,g){var h=0,i=a.length,j=null==c;if("object"===r.type(c)){e=!0;for(h in c)T(a,b,h,c[h],!0,f,g)}else if(void 0!==d&&(e=!0,r.isFunction(d)||(g=!0),j&&(g?(b.call(a,d),b=null):(j=b,b=function(a,b,c){return j.call(r(a),c)})),b))for(;h1,null,!0)},removeData:function(a){return this.each(function(){X.remove(this,a)})}}),r.extend({queue:function(a,b,c){var d;if(a)return b=(b||"fx")+"queue",d=W.get(a,b),c&&(!d||Array.isArray(c)?d=W.access(a,b,r.makeArray(c)):d.push(c)),d||[]},dequeue:function(a,b){b=b||"fx";var c=r.queue(a,b),d=c.length,e=c.shift(),f=r._queueHooks(a,b),g=function(){r.dequeue(a,b)};"inprogress"===e&&(e=c.shift(),d--),e&&("fx"===b&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return W.get(a,c)||W.access(a,c,{empty:r.Callbacks("once memory").add(function(){W.remove(a,[b+"queue",c])})})}}),r.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.length\x20\t\r\n\f]+)/i,la=/^$|\/(?:java|ecma)script/i,ma={option:[1,""],thead:[1,"","
"],col:[2,"","
"],tr:[2,"","
"],td:[3,"","
"],_default:[0,"",""]};ma.optgroup=ma.option,ma.tbody=ma.tfoot=ma.colgroup=ma.caption=ma.thead,ma.th=ma.td;function na(a,b){var c;return c="undefined"!=typeof a.getElementsByTagName?a.getElementsByTagName(b||"*"):"undefined"!=typeof a.querySelectorAll?a.querySelectorAll(b||"*"):[],void 0===b||b&&B(a,b)?r.merge([a],c):c}function oa(a,b){for(var c=0,d=a.length;c-1)e&&e.push(f);else if(j=r.contains(f.ownerDocument,f),g=na(l.appendChild(f),"script"),j&&oa(g),c){k=0;while(f=g[k++])la.test(f.type||"")&&c.push(f)}return l}!function(){var a=d.createDocumentFragment(),b=a.appendChild(d.createElement("div")),c=d.createElement("input");c.setAttribute("type","radio"),c.setAttribute("checked","checked"),c.setAttribute("name","t"),b.appendChild(c),o.checkClone=b.cloneNode(!0).cloneNode(!0).lastChild.checked,b.innerHTML="",o.noCloneChecked=!!b.cloneNode(!0).lastChild.defaultValue}();var ra=d.documentElement,sa=/^key/,ta=/^(?:mouse|pointer|contextmenu|drag|drop)|click/,ua=/^([^.]*)(?:\.(.+)|)/;function va(){return!0}function wa(){return!1}function xa(){try{return d.activeElement}catch(a){}}function ya(a,b,c,d,e,f){var g,h;if("object"==typeof b){"string"!=typeof c&&(d=d||c,c=void 0);for(h in b)ya(a,h,c,d,b[h],f);return a}if(null==d&&null==e?(e=c,d=c=void 0):null==e&&("string"==typeof c?(e=d,d=void 0):(e=d,d=c,c=void 0)),e===!1)e=wa;else if(!e)return a;return 1===f&&(g=e,e=function(a){return r().off(a),g.apply(this,arguments)},e.guid=g.guid||(g.guid=r.guid++)),a.each(function(){r.event.add(this,b,e,d,c)})}r.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,n,o,p,q=W.get(a);if(q){c.handler&&(f=c,c=f.handler,e=f.selector),e&&r.find.matchesSelector(ra,e),c.guid||(c.guid=r.guid++),(i=q.events)||(i=q.events={}),(g=q.handle)||(g=q.handle=function(b){return"undefined"!=typeof r&&r.event.triggered!==b.type?r.event.dispatch.apply(a,arguments):void 0}),b=(b||"").match(L)||[""],j=b.length;while(j--)h=ua.exec(b[j])||[],n=p=h[1],o=(h[2]||"").split(".").sort(),n&&(l=r.event.special[n]||{},n=(e?l.delegateType:l.bindType)||n,l=r.event.special[n]||{},k=r.extend({type:n,origType:p,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&r.expr.match.needsContext.test(e),namespace:o.join(".")},f),(m=i[n])||(m=i[n]=[],m.delegateCount=0,l.setup&&l.setup.call(a,d,o,g)!==!1||a.addEventListener&&a.addEventListener(n,g)),l.add&&(l.add.call(a,k),k.handler.guid||(k.handler.guid=c.guid)),e?m.splice(m.delegateCount++,0,k):m.push(k),r.event.global[n]=!0)}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,n,o,p,q=W.hasData(a)&&W.get(a);if(q&&(i=q.events)){b=(b||"").match(L)||[""],j=b.length;while(j--)if(h=ua.exec(b[j])||[],n=p=h[1],o=(h[2]||"").split(".").sort(),n){l=r.event.special[n]||{},n=(d?l.delegateType:l.bindType)||n,m=i[n]||[],h=h[2]&&new RegExp("(^|\\.)"+o.join("\\.(?:.*\\.|)")+"(\\.|$)"),g=f=m.length;while(f--)k=m[f],!e&&p!==k.origType||c&&c.guid!==k.guid||h&&!h.test(k.namespace)||d&&d!==k.selector&&("**"!==d||!k.selector)||(m.splice(f,1),k.selector&&m.delegateCount--,l.remove&&l.remove.call(a,k));g&&!m.length&&(l.teardown&&l.teardown.call(a,o,q.handle)!==!1||r.removeEvent(a,n,q.handle),delete i[n])}else for(n in i)r.event.remove(a,n+b[j],c,d,!0);r.isEmptyObject(i)&&W.remove(a,"handle events")}},dispatch:function(a){var b=r.event.fix(a),c,d,e,f,g,h,i=new Array(arguments.length),j=(W.get(this,"events")||{})[b.type]||[],k=r.event.special[b.type]||{};for(i[0]=b,c=1;c=1))for(;j!==this;j=j.parentNode||this)if(1===j.nodeType&&("click"!==a.type||j.disabled!==!0)){for(f=[],g={},c=0;c-1:r.find(e,this,null,[j]).length),g[e]&&f.push(d);f.length&&h.push({elem:j,handlers:f})}return j=this,i\x20\t\r\n\f]*)[^>]*)\/>/gi,Aa=/\s*$/g;function Ea(a,b){return B(a,"table")&&B(11!==b.nodeType?b:b.firstChild,"tr")?r(">tbody",a)[0]||a:a}function Fa(a){return a.type=(null!==a.getAttribute("type"))+"/"+a.type,a}function Ga(a){var b=Ca.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function Ha(a,b){var c,d,e,f,g,h,i,j;if(1===b.nodeType){if(W.hasData(a)&&(f=W.access(a),g=W.set(b,f),j=f.events)){delete g.handle,g.events={};for(e in j)for(c=0,d=j[e].length;c1&&"string"==typeof q&&!o.checkClone&&Ba.test(q))return a.each(function(e){var f=a.eq(e);s&&(b[0]=q.call(this,e,f.html())),Ja(f,b,c,d)});if(m&&(e=qa(b,a[0].ownerDocument,!1,a,d),f=e.firstChild,1===e.childNodes.length&&(e=f),f||d)){for(h=r.map(na(e,"script"),Fa),i=h.length;l")},clone:function(a,b,c){var d,e,f,g,h=a.cloneNode(!0),i=r.contains(a.ownerDocument,a);if(!(o.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||r.isXMLDoc(a)))for(g=na(h),f=na(a),d=0,e=f.length;d0&&oa(g,!i&&na(a,"script")),h},cleanData:function(a){for(var b,c,d,e=r.event.special,f=0;void 0!==(c=a[f]);f++)if(U(c)){if(b=c[W.expando]){if(b.events)for(d in b.events)e[d]?r.event.remove(c,d):r.removeEvent(c,d,b.handle);c[W.expando]=void 0}c[X.expando]&&(c[X.expando]=void 0)}}}),r.fn.extend({detach:function(a){return Ka(this,a,!0)},remove:function(a){return Ka(this,a)},text:function(a){return T(this,function(a){return void 0===a?r.text(this):this.empty().each(function(){1!==this.nodeType&&11!==this.nodeType&&9!==this.nodeType||(this.textContent=a)})},null,a,arguments.length)},append:function(){return Ja(this,arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=Ea(this,a);b.appendChild(a)}})},prepend:function(){return Ja(this,arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=Ea(this,a);b.insertBefore(a,b.firstChild)}})},before:function(){return Ja(this,arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this)})},after:function(){return Ja(this,arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this.nextSibling)})},empty:function(){for(var a,b=0;null!=(a=this[b]);b++)1===a.nodeType&&(r.cleanData(na(a,!1)),a.textContent="");return this},clone:function(a,b){return a=null!=a&&a,b=null==b?a:b,this.map(function(){return r.clone(this,a,b)})},html:function(a){return T(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a&&1===b.nodeType)return b.innerHTML;if("string"==typeof a&&!Aa.test(a)&&!ma[(ka.exec(a)||["",""])[1].toLowerCase()]){a=r.htmlPrefilter(a);try{for(;c1)}});function _a(a,b,c,d,e){return new _a.prototype.init(a,b,c,d,e)}r.Tween=_a,_a.prototype={constructor:_a,init:function(a,b,c,d,e,f){this.elem=a,this.prop=c,this.easing=e||r.easing._default,this.options=b,this.start=this.now=this.cur(),this.end=d,this.unit=f||(r.cssNumber[c]?"":"px")},cur:function(){var a=_a.propHooks[this.prop];return a&&a.get?a.get(this):_a.propHooks._default.get(this)},run:function(a){var b,c=_a.propHooks[this.prop];return this.options.duration?this.pos=b=r.easing[this.easing](a,this.options.duration*a,0,1,this.options.duration):this.pos=b=a,this.now=(this.end-this.start)*b+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),c&&c.set?c.set(this):_a.propHooks._default.set(this),this}},_a.prototype.init.prototype=_a.prototype,_a.propHooks={_default:{get:function(a){var b;return 1!==a.elem.nodeType||null!=a.elem[a.prop]&&null==a.elem.style[a.prop]?a.elem[a.prop]:(b=r.css(a.elem,a.prop,""),b&&"auto"!==b?b:0)},set:function(a){r.fx.step[a.prop]?r.fx.step[a.prop](a):1!==a.elem.nodeType||null==a.elem.style[r.cssProps[a.prop]]&&!r.cssHooks[a.prop]?a.elem[a.prop]=a.now:r.style(a.elem,a.prop,a.now+a.unit)}}},_a.propHooks.scrollTop=_a.propHooks.scrollLeft={set:function(a){a.elem.nodeType&&a.elem.parentNode&&(a.elem[a.prop]=a.now)}},r.easing={linear:function(a){return a},swing:function(a){return.5-Math.cos(a*Math.PI)/2},_default:"swing"},r.fx=_a.prototype.init,r.fx.step={};var ab,bb,cb=/^(?:toggle|show|hide)$/,db=/queueHooks$/;function eb(){bb&&(d.hidden===!1&&a.requestAnimationFrame?a.requestAnimationFrame(eb):a.setTimeout(eb,r.fx.interval),r.fx.tick())}function fb(){return a.setTimeout(function(){ab=void 0}),ab=r.now()}function gb(a,b){var c,d=0,e={height:a};for(b=b?1:0;d<4;d+=2-b)c=ca[d],e["margin"+c]=e["padding"+c]=a;return b&&(e.opacity=e.width=a),e}function hb(a,b,c){for(var d,e=(kb.tweeners[b]||[]).concat(kb.tweeners["*"]),f=0,g=e.length;f1)},removeAttr:function(a){return this.each(function(){r.removeAttr(this,a)})}}),r.extend({attr:function(a,b,c){var d,e,f=a.nodeType;if(3!==f&&8!==f&&2!==f)return"undefined"==typeof a.getAttribute?r.prop(a,b,c):(1===f&&r.isXMLDoc(a)||(e=r.attrHooks[b.toLowerCase()]||(r.expr.match.bool.test(b)?lb:void 0)),void 0!==c?null===c?void r.removeAttr(a,b):e&&"set"in e&&void 0!==(d=e.set(a,c,b))?d:(a.setAttribute(b,c+""),c):e&&"get"in e&&null!==(d=e.get(a,b))?d:(d=r.find.attr(a,b), +null==d?void 0:d))},attrHooks:{type:{set:function(a,b){if(!o.radioValue&&"radio"===b&&B(a,"input")){var c=a.value;return a.setAttribute("type",b),c&&(a.value=c),b}}}},removeAttr:function(a,b){var c,d=0,e=b&&b.match(L);if(e&&1===a.nodeType)while(c=e[d++])a.removeAttribute(c)}}),lb={set:function(a,b,c){return b===!1?r.removeAttr(a,c):a.setAttribute(c,c),c}},r.each(r.expr.match.bool.source.match(/\w+/g),function(a,b){var c=mb[b]||r.find.attr;mb[b]=function(a,b,d){var e,f,g=b.toLowerCase();return d||(f=mb[g],mb[g]=e,e=null!=c(a,b,d)?g:null,mb[g]=f),e}});var nb=/^(?:input|select|textarea|button)$/i,ob=/^(?:a|area)$/i;r.fn.extend({prop:function(a,b){return T(this,r.prop,a,b,arguments.length>1)},removeProp:function(a){return this.each(function(){delete this[r.propFix[a]||a]})}}),r.extend({prop:function(a,b,c){var d,e,f=a.nodeType;if(3!==f&&8!==f&&2!==f)return 1===f&&r.isXMLDoc(a)||(b=r.propFix[b]||b,e=r.propHooks[b]),void 0!==c?e&&"set"in e&&void 0!==(d=e.set(a,c,b))?d:a[b]=c:e&&"get"in e&&null!==(d=e.get(a,b))?d:a[b]},propHooks:{tabIndex:{get:function(a){var b=r.find.attr(a,"tabindex");return b?parseInt(b,10):nb.test(a.nodeName)||ob.test(a.nodeName)&&a.href?0:-1}}},propFix:{"for":"htmlFor","class":"className"}}),o.optSelected||(r.propHooks.selected={get:function(a){var b=a.parentNode;return b&&b.parentNode&&b.parentNode.selectedIndex,null},set:function(a){var b=a.parentNode;b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex)}}),r.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){r.propFix[this.toLowerCase()]=this});function pb(a){var b=a.match(L)||[];return b.join(" ")}function qb(a){return a.getAttribute&&a.getAttribute("class")||""}r.fn.extend({addClass:function(a){var b,c,d,e,f,g,h,i=0;if(r.isFunction(a))return this.each(function(b){r(this).addClass(a.call(this,b,qb(this)))});if("string"==typeof a&&a){b=a.match(L)||[];while(c=this[i++])if(e=qb(c),d=1===c.nodeType&&" "+pb(e)+" "){g=0;while(f=b[g++])d.indexOf(" "+f+" ")<0&&(d+=f+" ");h=pb(d),e!==h&&c.setAttribute("class",h)}}return this},removeClass:function(a){var b,c,d,e,f,g,h,i=0;if(r.isFunction(a))return this.each(function(b){r(this).removeClass(a.call(this,b,qb(this)))});if(!arguments.length)return this.attr("class","");if("string"==typeof a&&a){b=a.match(L)||[];while(c=this[i++])if(e=qb(c),d=1===c.nodeType&&" "+pb(e)+" "){g=0;while(f=b[g++])while(d.indexOf(" "+f+" ")>-1)d=d.replace(" "+f+" "," ");h=pb(d),e!==h&&c.setAttribute("class",h)}}return this},toggleClass:function(a,b){var c=typeof a;return"boolean"==typeof b&&"string"===c?b?this.addClass(a):this.removeClass(a):r.isFunction(a)?this.each(function(c){r(this).toggleClass(a.call(this,c,qb(this),b),b)}):this.each(function(){var b,d,e,f;if("string"===c){d=0,e=r(this),f=a.match(L)||[];while(b=f[d++])e.hasClass(b)?e.removeClass(b):e.addClass(b)}else void 0!==a&&"boolean"!==c||(b=qb(this),b&&W.set(this,"__className__",b),this.setAttribute&&this.setAttribute("class",b||a===!1?"":W.get(this,"__className__")||""))})},hasClass:function(a){var b,c,d=0;b=" "+a+" ";while(c=this[d++])if(1===c.nodeType&&(" "+pb(qb(c))+" ").indexOf(b)>-1)return!0;return!1}});var rb=/\r/g;r.fn.extend({val:function(a){var b,c,d,e=this[0];{if(arguments.length)return d=r.isFunction(a),this.each(function(c){var e;1===this.nodeType&&(e=d?a.call(this,c,r(this).val()):a,null==e?e="":"number"==typeof e?e+="":Array.isArray(e)&&(e=r.map(e,function(a){return null==a?"":a+""})),b=r.valHooks[this.type]||r.valHooks[this.nodeName.toLowerCase()],b&&"set"in b&&void 0!==b.set(this,e,"value")||(this.value=e))});if(e)return b=r.valHooks[e.type]||r.valHooks[e.nodeName.toLowerCase()],b&&"get"in b&&void 0!==(c=b.get(e,"value"))?c:(c=e.value,"string"==typeof c?c.replace(rb,""):null==c?"":c)}}}),r.extend({valHooks:{option:{get:function(a){var b=r.find.attr(a,"value");return null!=b?b:pb(r.text(a))}},select:{get:function(a){var b,c,d,e=a.options,f=a.selectedIndex,g="select-one"===a.type,h=g?null:[],i=g?f+1:e.length;for(d=f<0?i:g?f:0;d-1)&&(c=!0);return c||(a.selectedIndex=-1),f}}}}),r.each(["radio","checkbox"],function(){r.valHooks[this]={set:function(a,b){if(Array.isArray(b))return a.checked=r.inArray(r(a).val(),b)>-1}},o.checkOn||(r.valHooks[this].get=function(a){return null===a.getAttribute("value")?"on":a.value})});var sb=/^(?:focusinfocus|focusoutblur)$/;r.extend(r.event,{trigger:function(b,c,e,f){var g,h,i,j,k,m,n,o=[e||d],p=l.call(b,"type")?b.type:b,q=l.call(b,"namespace")?b.namespace.split("."):[];if(h=i=e=e||d,3!==e.nodeType&&8!==e.nodeType&&!sb.test(p+r.event.triggered)&&(p.indexOf(".")>-1&&(q=p.split("."),p=q.shift(),q.sort()),k=p.indexOf(":")<0&&"on"+p,b=b[r.expando]?b:new r.Event(p,"object"==typeof b&&b),b.isTrigger=f?2:3,b.namespace=q.join("."),b.rnamespace=b.namespace?new RegExp("(^|\\.)"+q.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,b.result=void 0,b.target||(b.target=e),c=null==c?[b]:r.makeArray(c,[b]),n=r.event.special[p]||{},f||!n.trigger||n.trigger.apply(e,c)!==!1)){if(!f&&!n.noBubble&&!r.isWindow(e)){for(j=n.delegateType||p,sb.test(j+p)||(h=h.parentNode);h;h=h.parentNode)o.push(h),i=h;i===(e.ownerDocument||d)&&o.push(i.defaultView||i.parentWindow||a)}g=0;while((h=o[g++])&&!b.isPropagationStopped())b.type=g>1?j:n.bindType||p,m=(W.get(h,"events")||{})[b.type]&&W.get(h,"handle"),m&&m.apply(h,c),m=k&&h[k],m&&m.apply&&U(h)&&(b.result=m.apply(h,c),b.result===!1&&b.preventDefault());return b.type=p,f||b.isDefaultPrevented()||n._default&&n._default.apply(o.pop(),c)!==!1||!U(e)||k&&r.isFunction(e[p])&&!r.isWindow(e)&&(i=e[k],i&&(e[k]=null),r.event.triggered=p,e[p](),r.event.triggered=void 0,i&&(e[k]=i)),b.result}},simulate:function(a,b,c){var d=r.extend(new r.Event,c,{type:a,isSimulated:!0});r.event.trigger(d,null,b)}}),r.fn.extend({trigger:function(a,b){return this.each(function(){r.event.trigger(a,b,this)})},triggerHandler:function(a,b){var c=this[0];if(c)return r.event.trigger(a,b,c,!0)}}),r.each("blur focus focusin focusout resize scroll click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup contextmenu".split(" "),function(a,b){r.fn[b]=function(a,c){return arguments.length>0?this.on(b,null,a,c):this.trigger(b)}}),r.fn.extend({hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)}}),o.focusin="onfocusin"in a,o.focusin||r.each({focus:"focusin",blur:"focusout"},function(a,b){var c=function(a){r.event.simulate(b,a.target,r.event.fix(a))};r.event.special[b]={setup:function(){var d=this.ownerDocument||this,e=W.access(d,b);e||d.addEventListener(a,c,!0),W.access(d,b,(e||0)+1)},teardown:function(){var d=this.ownerDocument||this,e=W.access(d,b)-1;e?W.access(d,b,e):(d.removeEventListener(a,c,!0),W.remove(d,b))}}});var tb=a.location,ub=r.now(),vb=/\?/;r.parseXML=function(b){var c;if(!b||"string"!=typeof b)return null;try{c=(new a.DOMParser).parseFromString(b,"text/xml")}catch(d){c=void 0}return c&&!c.getElementsByTagName("parsererror").length||r.error("Invalid XML: "+b),c};var wb=/\[\]$/,xb=/\r?\n/g,yb=/^(?:submit|button|image|reset|file)$/i,zb=/^(?:input|select|textarea|keygen)/i;function Ab(a,b,c,d){var e;if(Array.isArray(b))r.each(b,function(b,e){c||wb.test(a)?d(a,e):Ab(a+"["+("object"==typeof e&&null!=e?b:"")+"]",e,c,d)});else if(c||"object"!==r.type(b))d(a,b);else for(e in b)Ab(a+"["+e+"]",b[e],c,d)}r.param=function(a,b){var c,d=[],e=function(a,b){var c=r.isFunction(b)?b():b;d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(null==c?"":c)};if(Array.isArray(a)||a.jquery&&!r.isPlainObject(a))r.each(a,function(){e(this.name,this.value)});else for(c in a)Ab(c,a[c],b,e);return d.join("&")},r.fn.extend({serialize:function(){return r.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var a=r.prop(this,"elements");return a?r.makeArray(a):this}).filter(function(){var a=this.type;return this.name&&!r(this).is(":disabled")&&zb.test(this.nodeName)&&!yb.test(a)&&(this.checked||!ja.test(a))}).map(function(a,b){var c=r(this).val();return null==c?null:Array.isArray(c)?r.map(c,function(a){return{name:b.name,value:a.replace(xb,"\r\n")}}):{name:b.name,value:c.replace(xb,"\r\n")}}).get()}});var Bb=/%20/g,Cb=/#.*$/,Db=/([?&])_=[^&]*/,Eb=/^(.*?):[ \t]*([^\r\n]*)$/gm,Fb=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Gb=/^(?:GET|HEAD)$/,Hb=/^\/\//,Ib={},Jb={},Kb="*/".concat("*"),Lb=d.createElement("a");Lb.href=tb.href;function Mb(a){return function(b,c){"string"!=typeof b&&(c=b,b="*");var d,e=0,f=b.toLowerCase().match(L)||[];if(r.isFunction(c))while(d=f[e++])"+"===d[0]?(d=d.slice(1)||"*",(a[d]=a[d]||[]).unshift(c)):(a[d]=a[d]||[]).push(c)}}function Nb(a,b,c,d){var e={},f=a===Jb;function g(h){var i;return e[h]=!0,r.each(a[h]||[],function(a,h){var j=h(b,c,d);return"string"!=typeof j||f||e[j]?f?!(i=j):void 0:(b.dataTypes.unshift(j),g(j),!1)}),i}return g(b.dataTypes[0])||!e["*"]&&g("*")}function Ob(a,b){var c,d,e=r.ajaxSettings.flatOptions||{};for(c in b)void 0!==b[c]&&((e[c]?a:d||(d={}))[c]=b[c]);return d&&r.extend(!0,a,d),a}function Pb(a,b,c){var d,e,f,g,h=a.contents,i=a.dataTypes;while("*"===i[0])i.shift(),void 0===d&&(d=a.mimeType||b.getResponseHeader("Content-Type"));if(d)for(e in h)if(h[e]&&h[e].test(d)){i.unshift(e);break}if(i[0]in c)f=i[0];else{for(e in c){if(!i[0]||a.converters[e+" "+i[0]]){f=e;break}g||(g=e)}f=f||g}if(f)return f!==i[0]&&i.unshift(f),c[f]}function Qb(a,b,c,d){var e,f,g,h,i,j={},k=a.dataTypes.slice();if(k[1])for(g in a.converters)j[g.toLowerCase()]=a.converters[g];f=k.shift();while(f)if(a.responseFields[f]&&(c[a.responseFields[f]]=b),!i&&d&&a.dataFilter&&(b=a.dataFilter(b,a.dataType)),i=f,f=k.shift())if("*"===f)f=i;else if("*"!==i&&i!==f){if(g=j[i+" "+f]||j["* "+f],!g)for(e in j)if(h=e.split(" "),h[1]===f&&(g=j[i+" "+h[0]]||j["* "+h[0]])){g===!0?g=j[e]:j[e]!==!0&&(f=h[0],k.unshift(h[1]));break}if(g!==!0)if(g&&a["throws"])b=g(b);else try{b=g(b)}catch(l){return{state:"parsererror",error:g?l:"No conversion from "+i+" to "+f}}}return{state:"success",data:b}}r.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:tb.href,type:"GET",isLocal:Fb.test(tb.protocol),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Kb,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/\bxml\b/,html:/\bhtml/,json:/\bjson\b/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":JSON.parse,"text xml":r.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(a,b){return b?Ob(Ob(a,r.ajaxSettings),b):Ob(r.ajaxSettings,a)},ajaxPrefilter:Mb(Ib),ajaxTransport:Mb(Jb),ajax:function(b,c){"object"==typeof b&&(c=b,b=void 0),c=c||{};var e,f,g,h,i,j,k,l,m,n,o=r.ajaxSetup({},c),p=o.context||o,q=o.context&&(p.nodeType||p.jquery)?r(p):r.event,s=r.Deferred(),t=r.Callbacks("once memory"),u=o.statusCode||{},v={},w={},x="canceled",y={readyState:0,getResponseHeader:function(a){var b;if(k){if(!h){h={};while(b=Eb.exec(g))h[b[1].toLowerCase()]=b[2]}b=h[a.toLowerCase()]}return null==b?null:b},getAllResponseHeaders:function(){return k?g:null},setRequestHeader:function(a,b){return null==k&&(a=w[a.toLowerCase()]=w[a.toLowerCase()]||a,v[a]=b),this},overrideMimeType:function(a){return null==k&&(o.mimeType=a),this},statusCode:function(a){var b;if(a)if(k)y.always(a[y.status]);else for(b in a)u[b]=[u[b],a[b]];return this},abort:function(a){var b=a||x;return e&&e.abort(b),A(0,b),this}};if(s.promise(y),o.url=((b||o.url||tb.href)+"").replace(Hb,tb.protocol+"//"),o.type=c.method||c.type||o.method||o.type,o.dataTypes=(o.dataType||"*").toLowerCase().match(L)||[""],null==o.crossDomain){j=d.createElement("a");try{j.href=o.url,j.href=j.href,o.crossDomain=Lb.protocol+"//"+Lb.host!=j.protocol+"//"+j.host}catch(z){o.crossDomain=!0}}if(o.data&&o.processData&&"string"!=typeof o.data&&(o.data=r.param(o.data,o.traditional)),Nb(Ib,o,c,y),k)return y;l=r.event&&o.global,l&&0===r.active++&&r.event.trigger("ajaxStart"),o.type=o.type.toUpperCase(),o.hasContent=!Gb.test(o.type),f=o.url.replace(Cb,""),o.hasContent?o.data&&o.processData&&0===(o.contentType||"").indexOf("application/x-www-form-urlencoded")&&(o.data=o.data.replace(Bb,"+")):(n=o.url.slice(f.length),o.data&&(f+=(vb.test(f)?"&":"?")+o.data,delete o.data),o.cache===!1&&(f=f.replace(Db,"$1"),n=(vb.test(f)?"&":"?")+"_="+ub++ +n),o.url=f+n),o.ifModified&&(r.lastModified[f]&&y.setRequestHeader("If-Modified-Since",r.lastModified[f]),r.etag[f]&&y.setRequestHeader("If-None-Match",r.etag[f])),(o.data&&o.hasContent&&o.contentType!==!1||c.contentType)&&y.setRequestHeader("Content-Type",o.contentType),y.setRequestHeader("Accept",o.dataTypes[0]&&o.accepts[o.dataTypes[0]]?o.accepts[o.dataTypes[0]]+("*"!==o.dataTypes[0]?", "+Kb+"; q=0.01":""):o.accepts["*"]);for(m in o.headers)y.setRequestHeader(m,o.headers[m]);if(o.beforeSend&&(o.beforeSend.call(p,y,o)===!1||k))return y.abort();if(x="abort",t.add(o.complete),y.done(o.success),y.fail(o.error),e=Nb(Jb,o,c,y)){if(y.readyState=1,l&&q.trigger("ajaxSend",[y,o]),k)return y;o.async&&o.timeout>0&&(i=a.setTimeout(function(){y.abort("timeout")},o.timeout));try{k=!1,e.send(v,A)}catch(z){if(k)throw z;A(-1,z)}}else A(-1,"No Transport");function A(b,c,d,h){var j,m,n,v,w,x=c;k||(k=!0,i&&a.clearTimeout(i),e=void 0,g=h||"",y.readyState=b>0?4:0,j=b>=200&&b<300||304===b,d&&(v=Pb(o,y,d)),v=Qb(o,v,y,j),j?(o.ifModified&&(w=y.getResponseHeader("Last-Modified"),w&&(r.lastModified[f]=w),w=y.getResponseHeader("etag"),w&&(r.etag[f]=w)),204===b||"HEAD"===o.type?x="nocontent":304===b?x="notmodified":(x=v.state,m=v.data,n=v.error,j=!n)):(n=x,!b&&x||(x="error",b<0&&(b=0))),y.status=b,y.statusText=(c||x)+"",j?s.resolveWith(p,[m,x,y]):s.rejectWith(p,[y,x,n]),y.statusCode(u),u=void 0,l&&q.trigger(j?"ajaxSuccess":"ajaxError",[y,o,j?m:n]),t.fireWith(p,[y,x]),l&&(q.trigger("ajaxComplete",[y,o]),--r.active||r.event.trigger("ajaxStop")))}return y},getJSON:function(a,b,c){return r.get(a,b,c,"json")},getScript:function(a,b){return r.get(a,void 0,b,"script")}}),r.each(["get","post"],function(a,b){r[b]=function(a,c,d,e){return r.isFunction(c)&&(e=e||d,d=c,c=void 0),r.ajax(r.extend({url:a,type:b,dataType:e,data:c,success:d},r.isPlainObject(a)&&a))}}),r._evalUrl=function(a){return r.ajax({url:a,type:"GET",dataType:"script",cache:!0,async:!1,global:!1,"throws":!0})},r.fn.extend({wrapAll:function(a){var b;return this[0]&&(r.isFunction(a)&&(a=a.call(this[0])),b=r(a,this[0].ownerDocument).eq(0).clone(!0),this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstElementChild)a=a.firstElementChild;return a}).append(this)),this},wrapInner:function(a){return r.isFunction(a)?this.each(function(b){r(this).wrapInner(a.call(this,b))}):this.each(function(){var b=r(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=r.isFunction(a);return this.each(function(c){r(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(a){return this.parent(a).not("body").each(function(){r(this).replaceWith(this.childNodes)}),this}}),r.expr.pseudos.hidden=function(a){return!r.expr.pseudos.visible(a)},r.expr.pseudos.visible=function(a){return!!(a.offsetWidth||a.offsetHeight||a.getClientRects().length)},r.ajaxSettings.xhr=function(){try{return new a.XMLHttpRequest}catch(b){}};var Rb={0:200,1223:204},Sb=r.ajaxSettings.xhr();o.cors=!!Sb&&"withCredentials"in Sb,o.ajax=Sb=!!Sb,r.ajaxTransport(function(b){var c,d;if(o.cors||Sb&&!b.crossDomain)return{send:function(e,f){var g,h=b.xhr();if(h.open(b.type,b.url,b.async,b.username,b.password),b.xhrFields)for(g in b.xhrFields)h[g]=b.xhrFields[g];b.mimeType&&h.overrideMimeType&&h.overrideMimeType(b.mimeType),b.crossDomain||e["X-Requested-With"]||(e["X-Requested-With"]="XMLHttpRequest");for(g in e)h.setRequestHeader(g,e[g]);c=function(a){return function(){c&&(c=d=h.onload=h.onerror=h.onabort=h.onreadystatechange=null,"abort"===a?h.abort():"error"===a?"number"!=typeof h.status?f(0,"error"):f(h.status,h.statusText):f(Rb[h.status]||h.status,h.statusText,"text"!==(h.responseType||"text")||"string"!=typeof h.responseText?{binary:h.response}:{text:h.responseText},h.getAllResponseHeaders()))}},h.onload=c(),d=h.onerror=c("error"),void 0!==h.onabort?h.onabort=d:h.onreadystatechange=function(){4===h.readyState&&a.setTimeout(function(){c&&d()})},c=c("abort");try{h.send(b.hasContent&&b.data||null)}catch(i){if(c)throw i}},abort:function(){c&&c()}}}),r.ajaxPrefilter(function(a){a.crossDomain&&(a.contents.script=!1)}),r.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/\b(?:java|ecma)script\b/},converters:{"text script":function(a){return r.globalEval(a),a}}}),r.ajaxPrefilter("script",function(a){void 0===a.cache&&(a.cache=!1),a.crossDomain&&(a.type="GET")}),r.ajaxTransport("script",function(a){if(a.crossDomain){var b,c;return{send:function(e,f){b=r(" + + + + + + + + + + +
+
+
+
+
+
+
+
+
BG
+
Looped
+
+
+
+ +
+
IOB: U
+
COB: g
+
Enacted: for min + SMB U
+
+ +
+ +
+
+
+
+
+ +
+
Temp basal: for min
+
Sensitivity Ratio:
+
+
+
Insulin Req: U
+
Eventual BG:
+
+
+
Pump: U, v,
+
{{ data.hostname }}: %, v
+
+ + +
+ + diff --git a/www/templates/indexError.html b/www/templates/indexError.html new file mode 100644 index 000000000..9877034de --- /dev/null +++ b/www/templates/indexError.html @@ -0,0 +1,10 @@ + + + + + + +

OpenAPS

+

Temporary JSON Value Error ({{ error_text }}). Refreshing automatically in 5 seconds

+ +