Skip to main content

NetIOB (netiob) Calculation and Blood Glucose Prediction Library

netiob is an advanced Python package for automated blood glucose prediction and insulin-on-board (IOB) calculation built upon the OpenAPS oref0 reference algorithm. This toolkit enables researchers, data scientists, and developers to preprocess diabetes management data, compute net IOB, forecast glucose, and visually analyze prediction scenarios.

Core Features

  • Blood Glucose (BG) Prediction: End-to-end pipeline using the OpenAPS oref0 determine-basal algorithm.
  • Net Insulin On Board (IOB): Robust IOB calculation incorporating basal rate variations, boluses, and autosensitivity analysis.
  • Data Preprocessing Utilities: Transform raw pump, CGM, and nutrition logs into SDTM-compliant, validated formats.
  • Multi-Source Data Adapter: Normalizes both tconnectsync (API/DataFrame) and Tandem pump CSV exports into a single canonical schema, so the preprocessing pipeline is source-agnostic.
  • Prediction Graphs: Inbuilt support (via Matplotlib/Plotly) for visualizing BG forecasting results and insulin activity.
  • Core Utilities: Comprehensive API bridge, datetime handling, profile assembly, autosensitivity computation, and more.

Requirements

  • Python >= 3.12, < 3.13
  • NumPy >= 1.22.0
  • Pandas >= 1.3.0
  • Requests >= 2.25.0
  • python-decouple >= 3.6
  • Plotly >= 5.9.0
  • A running OpenAPS oref0 HTTP API server (remote endpoint for the core IOB / determine-basal calculations)

The single source of truth for dependencies is pyproject.toml; resolved versions are pinned in uv.lock.

  • Runtime configuration (read by netiob/settings.py via python-decouple):

    • OREF0_API_SERVER_URL — base URL of the oref0 HTTP server (default http://localhost:3000).
    • MAX_WORKERS — thread-pool size for the parallel net-IOB calculator (default 4).
  • oref0 dependency: netiob does not implement the IOB / determine-basal math itself — it preprocesses data into oref0-compatible payloads and calls a running oref0 server, which performs the core JavaScript computations. A reachable oref0 server is therefore a hard runtime dependency. Get the oref0 repo here: https://github.com/openaps/oref0/tree/master

Installation

PyPI

pip install netiob

From source (with uv)

This project is managed with uv. Clone the repo and sync the managed virtualenv to uv.lock:

git clone https://gitlab.com/CeADARIreland/UCD/con/netiob-package.git
cd netiob
uv sync                            # create/update .venv to match uv.lock
uv run python -c "import netiob"   # run anything inside the managed env

From source (with pip)

git clone https://gitlab.com/CeADARIreland/UCD/con/netiob-package.git
cd netiob
pip install .

Makefile commands

The project ships a Makefile wrapping the common uv workflows.

Command Description
make setup-local Sync the managed virtualenv to uv.lock (uv sync).
make run-tests-all Run the full deterministic suite (unit + contract + cross-cutting). Integration tests are deselected so the run needs no external services.
make run-tests-integration Run only the integration tier against a live oref0 server. Tests self-skip if OREF0_API_SERVER_URL is unreachable.
make build-dist Bump the version (BUMP=patch by default) and build a wheel.
make build-dist-publish Clean dist/, rebuild, and upload to PyPI via twine.
make run-tests-all                 # fast, no network — use as the default gate
make run-tests-integration         # requires a reachable oref0 server
make build-dist BUMP=minor         # override the version bump segment

Test tiers and pass/fail criteria are described in tests/TEST_PLAN.md; worked input/output vectors for the computational core are in tests/TEST_DATA.md.

Import

# Core modules
from netiob.utils.coreutils import *
from netiob.utils.calculators import calculate_net_iob
from netiob.utils.openapsprediction import OpenapsPredictor
from netiob.utils.preprocessors import preprocess_basal_data, preprocess_bolus_data, preprocess_carbs_data, preprocess_cgm_data, preprocess_insulin_data
from netiob.utils.cgmdataprocessor import CGMDataProcessor
from netiob.utils.bgpredgraph import bg_prediction_graph
from netiob.utils.source_adapters import SourceDataAdapter

Functionalities

1. Core Utilities (coreutils.py)

  • API Communication: call_api(endpoint, payload)
  • Datetime Handling: parse_iso_utc, to_iso_z, etc.
  • Profile Construction: get_profile_inputs, get_profile_settings
  • Pump History Utilities: get_pump_history, get_carb_history
  • Autosensitivity Calculation: get_autosens
  • Data Serialization: make_json_serializable()

2. NetIOB Calculator (calculators.py)

  • Parallel net IOB calculation at 5-min intervals via OpenAPS oref0 API
  • Handles both bolus and basal variabilities (including temp basals vs. scheduled)
  • Example usage:
from netiob.utils.calculators import calculate_net_iob
iob_series = calculate_net_iob(basal_df, bolus_df, cgm_df, profile_df, autosens)
  • Returns a list of dicts for each time point, including keys: iob, activity, basaliob, bolusiob, time, lastTemp

3. Source Data Adapter (source_adapters.py)

  • SourceDataAdapter: Class-based normalization layer that unifies two independent data sources into the single canonical schema consumed by preprocessors.py:
    • tconnectsync — pulled from the tconnectsync API/library, provisioned as in-memory pandas DataFrames (never CSV files).
    • tandem — exported directly from the Tandem t:connect / t:slim X2 pump/CGM device as CSV files. Used as a fallback source whenever tconnectsync data is unavailable or incomplete.
  • Preference order is per data type, independently: for each of basal, bolus, carbs, and CGM, tconnectsync is used if supplied and non-empty; otherwise the corresponding tandem_* CSV path is adapted instead.
  • Canonical (tconnectsync-native) schema produced for every source, regardless of origin:
    • Basal → event_ts, commanded_basal_rate, base_basal_rate
    • Bolus → event_ts, bolus_id, bolus_delivery_status, requested_now, requested_later, extended_duration_requested, delivered_total, correction
    • Carbs → event_ts, carbs
    • CGM → event_ts, current_glucose_display_value
  • Tandem-specific adaptation notes:
    • adapt_tandem_bolus() expands each Tandem Bolus.csv row into one or more tconnectsync-style event rows. Standard/Auto boluses (no Bolex Insulin Delivered value) become a single "Bolus Completed" row; Extended/dual-wave boluses are expanded into cumulative 5-minute "Bolus Started" snapshots plus a terminal "Bolus Completed" row, mirroring tconnectsync's native multi-row-per-bolus_id shape. Correction Delivered is carried through to the correction field, and Duration (mins) is passed through unconverted (tconnectsync's extended_duration_requested is natively in minutes).
    • adapt_tandem_carbs() derives carb entries from the Tandem Bolus.csv's Carb Size column (Tandem has no dedicated carbs export).
    • Tandem's Hourly-basal-delivery.csv is used to validate/cross-check total basal delivery against the chunked Basal-doses.csv record.
  • Example usage:
from netiob.utils.source_adapters import SourceDataAdapter

adapter = SourceDataAdapter(
    tconnectsync_basal=tconnectsync_basal_df,   # DataFrame or None
    tconnectsync_bolus=tconnectsync_bolus_df,
    tconnectsync_carbs=tconnectsync_carbs_df,
    tconnectsync_cgm=tconnectsync_cgm_df,
    tconnectsync_profile=tconnectsync_profile_df,
    tandem_basal="tandem_Basal-doses.csv",
    tandem_bolus="tandem_Bolus.csv",
    tandem_cgm="tandem_CGM.csv",
    tandem_hourly_basal="tandem_Hourly-basal-delivery.csv",
    user_max_basal_rate=float(),    # Known user max basal rate
)
basal_df, bolus_df, carbs_df, cgm_df = adapter.load()

# adapter.source_used reports which source (tconnectsync vs tandem) was
# actually used per data type, e.g. {"basal": "tandem", "bolus": "tandem", ...}
print(adapter.source_used)

4. Preprocessors (preprocessors.py)

  • Preprocesses CGM, basal, bolus, and meal data into standardized DataFrames
  • Chunks long basal records; distributes extended boluses; aligns with OpenAPS SDTM data conventions
  • Entry points: preprocess_basal_data(basal_df), preprocess_bolus_data(bolus_df), preprocess_cgm_data(cgm_df), preprocess_carbs_data(carbs_df)
  • Entry point to process insulin data ready for netiob calculation and prediction: preprocess_insulin_data(processed_basal, processed_bolus)
  • Entry point to process and access all processed data at once: preprocess_user_data(basal_df, bolus_df, carbs_df, cgm_df). Returns a tuple of 5 (objects) processed data.
  • Note: preprocess_user_data() is source-agnostic — it expects the canonical schema described in the Source Data Adapter section above, whether that schema was populated from tconnectsync DataFrames or adapted from Tandem CSVs via SourceDataAdapter.

5. CGM Data Processor (cgmdataprocessor.py)

  • Orchestrates the transformation of raw user data into oref0-compatible input using the preprocessor.py
  • Access processed DataFrames and prediction-ready structures:
  • Pools and provides netiob and prediction required data as objects
processor = CGMDataProcessor(basal_df, bolus_df, carbs_df, cgm_df, profile_df)
processed_glucose_data = processor.glucose_data  # ready for API call
processed_basal = processor.proc_basal

6. Blood Glucose Prediction (openapsprediction.py)

  • OpenapsPredictor: Automated pipeline for forecasting BG, carbs-on-board (COB), IOB, insulin needs, and clinical recommendations using oref0 APIs
from netiob.utils.openapsprediction import OpenapsPredictor
predictor = OpenapsPredictor(basal_df, bolus_df, carbs_df, cgm_df, profile_df)
result = predictor.predict_bg(currenttemp, clock, simcarb)
  • Returns comprehensive prediction dict: eventualBG, predBGs, rate, reason, and more

7. Graph Plotting (bgpredgraph.py)

  • Plot BG prediction scenarios:
from netiob.utils.bgpredgraph import bg_prediction_graph
fig = bg_prediction_graph(result, scenario_label="BG Prediction", fig_show=True)
  • Generates interactive or static charts using Plotly/Matplotlib, highlighting:
    • IOB activity
    • COB/UAM scenarios
    • Target BG lines
    • Safest prediction curves

Example Pipeline Usage

  • Import and Load Dataframes
import pandas as pd
from netiob.utils.cgmdataprocessor import CGMDataProcessor
from netiob.utils.openapsprediction import OpenapsPredictor
from netiob.utils.bgpredgraph import bg_prediction_graph
from netiob.utils.calculators import calculate_net_iob
from netiob.utils.source_adapters import SourceDataAdapter

# Load user data into DataFrames
# Note: Data can be transformed from any data sources. Only ensure they are in DataFrame format
basal_df = pd.read_csv("basal.csv")
bolus_df = pd.read_csv("bolus.csv")
carbs_df = pd.read_csv("carbs.csv")
cgm_df = pd.read_csv("cgm.csv")
profile_df = pd.read_csv("profile.csv")
  • Preprocess
# Create an instance of CGMDataProcessor.
# See code file for full documentation on all objects of CGMDataProcessor
dataprocessor = CGMDataProcessor(basal_df, bolus_df, carbs_df, cgm_df, profile_df=profile)

# Get the objects of dataprocessor (Below are all the objects of CGMDataProcessor)
dataprocessor.proc_basal        # Processed basal data 
dataprocessor.proc_bolus        # Processed bolus data
dataprocessor.proc_carbs        # Processed carbs data
dataprocessor.proc_glucose      # Processed glucose data
dataprocessor.proc_insulin      # processed insulin data
dataprocessor.glucose_data      # Glucosed data structured in the required dict for OpenAPS prediction
dataprocessor.clock             # CGM last data event timestamp (for prediction)
dataprocessor.pumphistory       # Insulin data structured in the required dict (for netiob calculation and prediction)
dataprocessor.pump_clock        # Last insulin data event timestamp
dataprocessor.settings          # Useer settings in structured dict for prediction
dataprocessor.bg_targets        # BG target dict extracted from settings
dataprocessor.basal_profile     # 24-hours (hourly) baseline user basal profile dict extrapolated from user profile settings
dataprocessor.sensitivities     # Sensitivities data extracted from profile settings
dataprocessor.profile_carbs     # Carbs dict based on user profile
dataprocessor.profile           # Entire user profile structure dict needed for netiob calculation and prediction
datprocessor.autosens           # autosensitivity ratio dict calculated using oref0 API
  • Prediction
predictor = OpenapsPredictor(proc_basal, proc_bolus, proc_carbs, proc_cgm, profile_df)
prediction_result = predictor.predict_bg(currenttemp={}, clock="2025-11-07T16:00:00Z")

# Note: Synthetic carbs entry (in grams) can be simulated for prediction. In such case, pass (e.g., 5g) carbs as thus:
prediction_result = predictor.predict_bg(currenttemp={}, clock="2025-11-07T16:00:00Z", sim_carb=5)
  • Visualization
bg_prediction_graph(prediction_result, scenario_label="BG Prediction After Meal")
  • Calculate NetIOB
# Note, profile_df and autosens can be None. 
# In such case, a default baseline basal profile will be calculated based on insulin history and default auto sensitivity ratio will be used.
calculate_net_iob(basal_df, bolus_df, carbs_df, cgm_df, profile_df, austosens={})

Graph Output

  • The bg_prediction_graph function visualizes predicted curves (IOB, COB/UAM, ZT) and overlays "eventual BG" markers and target ranges.

Local Testing with Tandem CSVs (run_tandem_pipeline.py)

For local, offline validation of the Tandem CSV → SourceDataAdapter → preprocessors.py path (i.e. without a Django backend or live tconnectsync connection), the repo includes a standalone CLI harness: run_tandem_pipeline.py.

This script:

  1. Loads the four Tandem pump/CGM CSV exports (Basal-doses.csv, Bolus.csv, CGM.csv, Hourly-basal-delivery.csv).
  2. Runs them through SourceDataAdapter with tconnectsync_* inputs explicitly set to None, forcing every data type down the Tandem-CSV adaptation path (adapt_tandem_basal, adapt_tandem_bolus, adapt_tandem_carbs, adapt_tandem_cgm).
  3. Feeds the adapted DataFrames into preprocess_user_data().
  4. Writes both the adapter-only intermediates and the final processed outputs to disk, plus a validation summary that cross-checks processed totals against the raw CSV figures (e.g. total bolus units, total basal units).

Usage

python run_tandem_pipeline.py \
    --basal tandem-Basal-doses.csv \
    --bolus tandem-Bolus.csv \
    --cgm tandem-CGM.csv \
    --hourly-basal tandem-Hourly-basal-delivery.csv \
    --outdir ./output

Place source_adapters.py, preprocessors.py, and run_tandem_pipeline.py in the same directory (or ensure they're on PYTHONPATH) before running.

Outputs written to --outdir

File Description
adapted_basal.csv / adapted_bolus.csv / adapted_carbs.csv / adapted_cgm.csv Adapter-only output (canonical schema), before any preprocessors.py transformation — useful for structurally comparing against real tconnectsync DataFrames.
processed_basal.csv / processed_bolus.csv / processed_carbs.csv / processed_glucose.csv Final SDTM-style processed outputs from preprocess_user_data().
insulin_combined.csv Combined chronological basal + bolus insulin stream (netIOB-ready).

Programmatic use

run_tandem_pipeline.py also exposes run_pipeline(...) directly, so it can be imported and called from a notebook or test module instead of the CLI:

from run_tandem_pipeline import run_pipeline

result = run_pipeline(
    basal_csv="tandem-Basal-doses.csv",
    bolus_csv="tandem-Bolus.csv",
    cgm_csv="tandem-CGM.csv",
    hourly_basal_csv="tandem-Hourly-basal-delivery.csv",
    outdir="./output",
)

processed_bolus = result["processed_bolus"]
insulin_df = result["insulin_df"]

Contributing

  • Create issues or merge requests on GitLab for improvements.
  • Follow coding conventions and update docstrings.

License

This project is licensed under the Apache License 2.0. For more details, please see the LICENSE file in the repository.


Maintainers

CeADAR - Ireland's Centre for AI

Metadata

Release files for netiob 0.1.42

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for netiob 0.1.42
File Size Uploaded Provenance Actions
netiob-0.1.42.tar.gz 70.3 kB Without provenance Details for netiob-0.1.42.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for netiob 0.1.42
File Interpreter ABI Platform Actions
netiob-0.1.42-py3-none-any.whl Python 3 none any Details for netiob-0.1.42-py3-none-any.whl

Total release size: 139.7 kB

Release files / netiob-0.1.42.tar.gz

Download URL netiob-0.1.42.tar.gz
Size 70.3 kB
Tags Source
SHA-256 checksum
How to use checksums
42ff17b1b0ac6c1133b18ed7ea3d4ad51c63e67e3361ef9b8645f5a791b360e8
BLAKE2b-256 checksum
How to use checksums
495f2a593bcf508ce6ba110b09d03c122c4217757dcf2b1591713e1fe625c8b2
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.11.1

Release files / netiob-0.1.42-py3-none-any.whl

Download URL netiob-0.1.42-py3-none-any.whl
Size 69.4 kB
Tags Python 3
SHA-256 checksum
How to use checksums
853ece03531a27fddcd75511c82a91c0c7a8682aa7eec208dbe34ecf74bed7e7
BLAKE2b-256 checksum
How to use checksums
f0801fecde9ff227c623c0034b681523fe263e129dafa9400de6a8062343e6ff
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.11.1

Security for netiob 0.1.42

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.1.42 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page