HomeType 1 Diabetes Insulin Pump ManagementContinuous Glucose Monitor Closed-Loop Algorithm Simulator

💉 Continuous Glucose Monitor Closed-Loop Algorithm Simulator

The simulator models a closed-loop algorithm for artificial pancreas systems to manage insulin delivery and glucose levels in patients with diabetes.

Type 1 Diabetes Insulin Pump Management2DModerate60 FPS
cgm-closed-loop-algorithm ↗ Open standalone

CGM Sensor Data Acquisition & Signal Conditioning

Every closed-loop insulin system starts with a single noisy analog signal: the tiny electrochemical current generated when glucose oxidase on a subcutaneous filament reacts with interstitial glucose. Turning that current into a trustworthy, clinically actionable number every five minutes — reliably, for ten straight days — is a harder engineering problem than most people realize.

  • 5 min: Sampling interval (raw current sampled continuously)
  • 1–2 hr: Sensor warm-up (before first reliable reading)
  • 5–10 min: Interstitial lag vs. blood (physiological diffusion delay)
  • 10–15 days: Sensor wear duration (Dexcom G6/G7, Libre 3)

From electrochemical current to a glucose number

A CGM filament is coated with glucose oxidase, an enzyme that converts glucose + oxygen into gluconolactone + hydrogen peroxide. The hydrogen peroxide is oxidized at a platinum electrode, producing a current proportional to local interstitial glucose concentration — typically a few nanoamps per mg/dL.

That raw current is extremely noisy: it drifts with sensor age, local tissue reaction, hydration, temperature, and compression (lying on the sensor). Firmware inside the transmitter applies a chain of corrections before a number ever reaches the algorithm:

• Calibration — factory-calibrated sensors (Dexcom G6/G7, Libre) use a manufacturing-lot-specific current-to-glucose curve; older-generation sensors required 1–2 daily fingerstick calibrations • Temperature compensation — an onboard thermistor corrects for the fact that enzyme kinetics are temperature-dependent • Kalman/exponential filtering — raw 1-minute samples are smoothed to suppress electrical noise before the reported 5-minute value is generated • Compression artifact detection — sudden implausible drops (e.g. from sleeping on the sensor) are flagged and suppressed rather than acted on

Why interstitial glucose lags blood glucose

CGM sensors sit in the interstitial fluid of the subcutaneous layer, not in a blood vessel. Glucose must diffuse from capillaries into that interstitial space before the sensor ever "sees" it. During stable periods this lag is negligible, but when blood glucose is changing rapidly (after a meal, after a bolus, during exercise) the interstitial reading can trail true blood glucose by 5–10 minutes, and occasionally longer during vigorous exercise where blood flow redistributes.

This lag is not just a nuisance — it is the single biggest reason a closed-loop algorithm cannot simply react to the current CGM value. If the algorithm waited for interstitial glucose to visibly rise before delivering insulin, and then waited again for injected insulin to act (10–20 more minutes for rapid-acting analogs), total system lag could exceed 30 minutes — long enough to miss a rapid excursion in both directions.

This is precisely why hybrid closed-loop systems are built around prediction rather than reaction. Compensating computationally for a lag that cannot be removed physically is the founding design principle of every modern automated insulin delivery (AID) system.

Signal quality gating before the algorithm ever sees a value

Modern transmitters (Dexcom G7, Libre 3, Medtronic Guardian 4) run on-device sensor-fusion logic before the Bluetooth packet is even sent to the pump or phone:

• Rate-of-change gating: readings that imply a physiologically impossible rate (>10 mg/dL/min sustained) are flagged as noise • Confidence scoring: each 5-minute value ships with an internal reliability estimate; low-confidence values reduce algorithm aggressiveness automatically • Signal loss handling: if Bluetooth connectivity drops for multiple cycles, the closed-loop algorithm reverts to a safe pre-programmed basal rate rather than acting on stale data • Session-start caution: for roughly the first 12–24 hours of a new sensor, accuracy is lower (MARD often 2–4 points worse), so algorithms are intentionally more conservative

Predictive Glucose Modeling with Model Predictive Control (MPC)

The intellectual core of a hybrid closed-loop system is not the sensor or the pump — it is the forecasting engine sitting between them. Model predictive control (MPC) takes the recent glucose trend and a physiological model of how insulin and carbohydrates move through the body, and projects the glucose curve forward 30 to 60 minutes, converting a reactive pump into a genuinely anticipatory one.

  • 30–60 min: Forecast horizon (rolling prediction window)
  • Every 5 min: Recompute frequency (new CGM value → new forecast)
  • ~4 hr: Insulin action modeled (IOB decay curve, rapid-acting analog)
  • MPC: Core algorithm class (model predictive control)

What the model actually predicts

MPC treats the body as a control system with known (if imperfect) dynamics. Two compartments matter most:

• Insulin-on-board (IOB): every unit of insulin already delivered continues acting for hours. Rapid-acting analogs (aspart, lispro) peak around 60–90 minutes and have a duration of action of roughly 4 hours. The algorithm tracks a decay curve for every micro-dose so it never "double counts" insulin that has not finished acting yet. • Carbohydrates-on-board (COB), where meal announcements are used: carbohydrate absorption is modeled with a similar time-delayed curve, since digested glucose does not hit the bloodstream instantly.

Combining current glucose, its recent rate-of-change (derivative over the last 3–4 CGM points), IOB, and COB, the model numerically integrates forward in 5-minute steps to produce a projected glucose curve — not a single number but a full trajectory, typically evaluated at the 30-minute and 60-minute marks.

Why prediction beats simple reaction

A naive "reactive" algorithm — increase insulin when glucose is high, decrease when low — performs poorly because of the compounded lag discussed in Stage 1: interstitial delay plus insulin action delay. By the time a reactive system detects a rise and delivers more insulin, that insulin will not peak for another hour, by which point the rise may already have reversed on its own — causing an unwanted late-onset low.

MPC instead asks a different question every 5 minutes: "given everything currently in motion (existing IOB, current trend, recent meals), where will glucose be in 30 minutes if I do nothing more?" It then computes the minimal basal adjustment needed today so that the predicted curve stays inside target range, rather than waiting to observe the excursion directly. This is the same control-theory principle used in cruise control and thermostats — except tuned for a system (human metabolism) that is far noisier and less linear than a car or a room.

Tandem's Control-IQ and Omnipod 5's SmartAdjust both re-run their prediction model at every single 5-minute CGM cycle — meaning the insulin dose you receive right now was chosen based on a rolling 30–60 minute look-ahead, recomputed roughly 288 times per day.

Handling model uncertainty safely

No physiological model is perfect — insulin sensitivity varies with stress, illness, hormones, and time of day, and the model's parameters are only estimates. Closed-loop systems handle this uncertainty by design rather than by pretending it does not exist:

• Conservative default parameters: population-average insulin sensitivity and carb ratios are used unless the clinician tunes them • Bounded aggressiveness: maximum basal multipliers (commonly capped around 200–280% of programmed basal) prevent the model from ever making an extreme single-cycle correction • Continuous re-estimation: every new 5-minute CGM value updates the forecast, so a wrong prediction is corrected within minutes rather than being trusted for the full hour • Fallback to safe basal: if CGM data is missing or the model becomes unreliable, the system reverts to the user's pre-programmed manual basal rate

Automated Micro-Bolus & Basal Modulation Every Five Minutes

Once the predicted trajectory is in hand, the algorithm has to translate a forecast into an actual insulin command — a basal rate multiplier, or in the most advanced hybrid closed-loop systems, a small automatic correction bolus. This happens continuously, in tiny increments, roughly 288 times a day, replacing the coarse manual adjustments a person would otherwise have to make by hand.

  • 5 min: Adjustment cycle (basal re-evaluated every cycle)
  • ~200–280%: Max basal multiplier (system-dependent safety ceiling)
  • Omnipod 5: Auto-correction bolus (micro-boluses for predicted highs)
  • ~288: Daily basal decisions (one per 5-minute CGM cycle)

From forecast to a basal rate multiplier

The predicted 30–60 minute trajectory is compared against the target range (commonly 112.5–160 mg/dL as an internal control target, distinct from the 70–180 mg/dL reporting range). The algorithm then selects a basal multiplier for the next 5-minute cycle:

• Predicted glucose trending well above target → basal increased, sometimes up to the system maximum (e.g. Control-IQ can deliver up to 280% of programmed basal) • Predicted glucose tracking near target → basal held near 100% (the user's normal programmed rate) • Predicted glucose trending below target → basal reduced below 100%, tapering toward a full suspend as the predicted low approaches (formalized in Stage 4)

Because this decision is remade every 5 minutes from a fresh forecast, the system behaves less like a single large correction and more like thousands of tiny nudges throughout the day — smoothing out the glucose curve instead of over-correcting and inducing a rebound.

Automatic correction micro-boluses

Basal modulation alone can only move insulin delivery within a fairly narrow band, since it is limited to a multiple of the user's baseline rate. For genuinely high, meal-driven excursions, some systems go a step further and deliver small automatic correction boluses on top of basal — a capability that distinguishes "advanced hybrid closed-loop" (AHCL) systems from earlier "hybrid closed-loop" designs:

• Omnipod 5 (SmartAdjust) can deliver automatic correction micro-boluses roughly once per hour when the predicted glucose exceeds target, in addition to continuous basal modulation • Control-IQ delivers an automatic correction bolus specifically when glucose is predicted to exceed 180 mg/dL in 30 minutes, capped at 60% of the user's normal meal-bolus correction dose • These micro-boluses are intentionally conservative — a fraction of what a person would manually dose — because the system is still blind to whether a meal has actually been announced, and would rather slightly under-correct than risk stacking insulin

Automatic correction boluses only ever act to lower predicted highs — no commercial hybrid closed-loop system currently auto-boluses for a predicted low; the low-glucose side of the loop is handled exclusively by reducing or suspending basal (Stage 4).

Commercial hybrid closed-loop systems compared

ProductIndicationTrial DesignKey Result
Tandem Control-IQBasal modulation + correction bolusMPC forecast at every 5-min CGM reading; auto-bolus above predicted 180 mg/dLWidely studied; strong pediatric trial base
Omnipod 5 (SmartAdjust)Basal modulation + hourly micro-bolusTubeless pod; on-pod MPC algorithm, no phone requiredFully automated micro-bolusing, adapts per-user targets
Medtronic MiniMed 780GBasal modulation + auto-correction q5minSmartGuard algorithm targets as low as 100 mg/dLMost aggressive correction-bolus frequency (every 5 min)
CamAPS FXBasal modulation onlyFully adaptive MPC, learns insulin sensitivity over timeApproved for pregnancy and very young children

Predictive Low-Glucose Suspend — The Core Safety Feature

If model-predictive dosing is the intelligence of a closed-loop system, predictive low-glucose suspend (PLGS) is its conscience. Rather than waiting for a hypoglycemic event to happen and then reacting, the algorithm halts insulin delivery pre-emptively the moment its own forecast shows a low arriving within the next 30 minutes — and resumes automatically, without any user input, once the trend reverses.

  • ≤30 min: Suspend trigger window (predicted low glucose horizon)
  • <70 mg/dL: Hypoglycemia threshold (ADA consensus low-glucose cutoff)
  • Trend reversal: Auto-resume condition (basal restarts without user action)
  • ~75–80%: Nocturnal hypo reduction (vs. sensor-augmented pump alone)

How predictive suspend differs from threshold suspend

Earlier-generation systems (e.g. the 2013 Medtronic MiniMed 530G) used threshold suspend: insulin delivery stopped only after CGM glucose actually crossed a low threshold. That is reactive, and given the interstitial lag from Stage 1, it is already late — blood glucose may have been low for several minutes before the sensor caught up.

Predictive low-glucose suspend inverts the logic entirely. Using the same MPC forecast from Stage 2, the algorithm asks each cycle: "does the projected trajectory cross 70 mg/dL — or a user-configurable higher threshold — within the next 30 minutes?" If yes, basal insulin is suspended immediately, before glucose has actually dropped, giving existing insulin-on-board time to finish acting without any additional insulin compounding the fall.

Graduated response, not an on/off switch

In practice, most systems do not treat suspension as a binary event but as the extreme end of a graduated response curve that starts well above the hypoglycemia threshold:

• Predicted glucose approaching target floor (~110–130 mg/dL) → basal gradually tapered below 100% • Predicted glucose trending toward 80–90 mg/dL within the forecast horizon → basal reduced further, often toward 0–20% • Predicted glucose trending below 70 mg/dL within 30 minutes → full basal suspend • Predicted glucose already low and falling → suspend continues; some systems (Control-IQ) also suspend if current glucose is below 70 mg/dL and falling, independent of the forward forecast, as a reactive backstop

This graduated behavior avoids abrupt on/off insulin cycling, which itself can cause glucose oscillation, while still reaching full suspension fast enough to matter when a real low is imminent.

Automatic resume — closing the loop safely

A suspend that never lifts is just as dangerous as one that never triggers — prolonged basal suspension risks rebound hyperglycemia and, in extreme cases, ketosis. Closed-loop systems therefore resume basal delivery automatically, without requiring the user to intervene, as soon as the forecast trend reverses:

• The algorithm continues recomputing the 30-minute forecast every 5 minutes during a suspend, exactly as it does at any other time • Once the predicted trajectory shows glucose climbing back above the low threshold with margin, basal delivery resumes — typically starting conservatively rather than snapping back to full rate • Maximum suspend duration safeguards exist in most systems: if glucose does not respond as expected, delivery resumes at a minimal safe rate after a bounded interval to prevent unbounded periods with zero insulin

Randomized trials of PLGS-equipped systems (ASPIRE In-Home, and subsequent hybrid closed-loop trials) found roughly a 75–80% reduction in nocturnal hypoglycemic events compared with sensor-augmented pump therapy without predictive suspend — the single largest safety gain of any component in the closed-loop stack.

Performance Evaluation — Time in Range, GMI, and Real-World Trial Results

Closed-loop systems are ultimately judged not by algorithm elegance but by standardized glycemic outcome metrics that clinicians and regulators agree on. Time-in-range has emerged as the primary real-world outcome measure, supplementing — and in day-to-day clinical use often superseding — the traditional quarterly HbA1c blood draw.

  • >70%: Time-in-Range target (70–180 mg/dL, ADA/ATTD consensus)
  • <4%: Time-Below-Range target (<70 mg/dL threshold)
  • ~10–15%: Pediatric TIR improvement (closed-loop vs. standard pump)
  • HbA1c proxy: GMI (derived from mean CGM glucose)

Time-in-range as the primary consensus outcome

International consensus guidelines (Battelino et al. 2019, endorsed by ADA and ATTD) define standardized CGM metrics over a minimum 14-day, ≥70%-active-time data window:

• Time-in-Range (TIR): percent of readings between 70–180 mg/dL — target >70% for most adults and children with type 1 diabetes • Time-Below-Range (TBR): percent of readings <70 mg/dL (target <4%) and <54 mg/dL (target <1%, level 2 hypoglycemia) • Time-Above-Range (TAR): percent of readings >180 mg/dL (target <25%) and >250 mg/dL (target <5%) • Coefficient of variation (CV): glucose variability measure, target ≤36%

Each 1% improvement in TIR corresponds to roughly 14 minutes per day spent in target range — a granular, immediately actionable number in a way HbA1c, averaged over 3 months, can never be.

Glucose Management Indicator (GMI) as an HbA1c proxy

GMI converts mean CGM glucose over a monitoring period into an estimated HbA1c-equivalent percentage using a regression formula derived from large CGM-vs-lab-HbA1c datasets:

GMI (%) = 3.31 + 0.02392 × (mean glucose in mg/dL)

GMI is not identical to laboratory HbA1c — the two can diverge for a given individual due to red blood cell lifespan variation, hemoglobinopathies, and the fact that GMI reflects only the CGM-wear period rather than a full ~3-month red cell average — but it gives clinicians and patients a same-day estimate rather than waiting for a lab draw, and correlates strongly with hybrid closed-loop TIR improvements at a population level.

Real-world and pediatric trial outcomes

Randomized and real-world evidence for hybrid closed-loop systems has been consistently positive, particularly in the pediatric population where achieving target control is historically hardest:

• Control-IQ pivotal trial (Brown et al., NEJM 2019): TIR increased from 61% to 71% over 6 months (adults and adolescents combined) versus sensor-augmented pump therapy • Pediatric-focused trials (ages 6–13) have reported roughly 10–15 percentage-point TIR improvements versus standard pump therapy, alongside significant reductions in nighttime hypoglycemia and caregiver-reported burden • Omnipod 5 pivotal trial: mean TIR improved from 65% to 74% in children/adolescents, with GMI improving by roughly 0.3–0.4 percentage points • Real-world registry data (not just trial settings) show similar gains, with the largest benefit consistently observed overnight, when predictive low-glucose suspend has the most uninterrupted time to act

Across pediatric hybrid closed-loop trials, the ~10–15% absolute TIR improvement over standard pump therapy corresponds to roughly 1.5–2.5 additional hours per day spent in the 70–180 mg/dL target range — without any additional conscious effort from the child or caregiver.
⚙ Under the hood

The simulator models a closed-loop algorithm for artificial pancreas systems to manage insulin delivery and glucose levels in patients with diabetes.

CanvasBiomedicine

2D · HTML5 Canvas 2D · 60 FPS target · runs fully client-side, no install

What did you find?

Add reproduction steps (optional)