Artificial Pancreas PID Insulin Control Simulator Back
Medical Control

Artificial Pancreas PID Insulin Control Simulator

Design the PID closed-loop controller of an artificial pancreas (insulin pump for Type-1 diabetes). Adjust the target BG, carb ratio and PID gains and the post-meal glucose profile, Time-in-Range and hypoglycemia risk update in real time, giving the same first-cut feel as commercial hybrid loops like Medtronic 780G or Tandem Control-IQ.

Parameters
Target BG
mg/dL
CGM setpoint. 110 mg/dL is typical
Insulin sensitivity ISF
mg/dL/U
BG drop per unit of insulin
Carb ratio ICR
g/U
Grams of carbs covered by 1 unit of insulin
Basal insulin
U/h
Meal carbs
g
Carbohydrate content per meal
Proportional Kp
Integral Ki
1/h
Derivative Kd
h
Kd=0 is stable. Too large amplifies CGM noise
Results
Bolus insulin (U)
Total daily insulin (U/day)
Post-meal peak BG (mg/dL)
Estimated TIR (%)
Phase margin (deg)
Hypoglycemia risk
Glucose time series (last 6h) — insulin doses & meal markers

Blue line: BG. Green band: target range 70-180 mg/dL. Orange bars: insulin infusion. ▼: meal events. Real-time view of the closed-loop behaviour.

24h glucose profile — PID closed-loop vs open-loop
TIR (%) vs gain setting (Kp sweep)
Theory & Key Formulas

$$u(t) = K_p\,e(t) + K_i\!\int_0^t e(\tau)\,d\tau + K_d\,\frac{de}{dt},\quad e = BG_{\text{actual}} - BG_{\text{target}}$$

u: insulin infusion rate (U/h), e: glucose error (mg/dL), Kp/Ki/Kd: PID gains. Proportional + integral + derivative form a closed-loop dose controller.

$$\text{Bolus} = \frac{C_{\text{meal}}}{\text{ICR}},\qquad \Delta BG_{\text{insulin}} = U \cdot \text{ISF}$$

Bolus insulin from meal carbs C_meal divided by the carb ratio ICR. Insulin sensitivity ISF [mg/dL/U] is the BG drop per unit of insulin.

$$\text{TIR} = \frac{T_{70 \le BG \le 180}}{T_{\text{total}}}\times 100\,[\%]$$

TIR (Time in Range) is the fraction of time the BG stays between 70-180 mg/dL. International consensus targets TIR > 70% for adults with Type-1 diabetes.

Artificial Pancreas PID Insulin Control — Glucose Closed Loop

🙋
An "artificial pancreas" means a machine that delivers insulin in place of the pancreas, right? It's used by people with Type-1 diabetes — but how does it actually work?
🎓
Yes — more precisely it is usually called a "closed-loop insulin pump". It is made of three parts. First, a CGM (continuous glucose monitor) sits under the skin and measures BG every 5 minutes. Second, an insulin pump is connected to the body by a thin cannula and can deliver insulin in 0.025 U increments. Third, a controller in between decides "how much to deliver now" using a PID or MPC algorithm. The most successful commercial models worldwide are Medtronic 780G, Tandem Control-IQ and Insulet Omnipod 5.
🙋
Wait, PID — like the thing from the control class for motor speed? Can it really be used on a biological system like blood glucose?
🎓
Good catch — the underlying principle is the same. Take the error e(t) between the target (say 110 mg/dL) and the measured BG, and pick the dose as u(t) = Kp·e + Ki·∫e + Kd·de/dt. The crucial difference from motor control is the huge time delay: subcutaneous insulin takes 1-2 h to act, meals raise BG over 30-60 min, and the CGM reads interstitial fluid so it lags blood BG by 5-15 min. Plain PID with high gains will oscillate between hyper- and hypoglycemia. The phase margin and gain margin in this tool quantify that stability.
🙋
I see — so cranking Kp up to make it faster isn't the answer. I just pushed Kp to 2.0 and the phase margin collapsed and the verdict turned to a warning!
🎓
Exactly the classic failure mode. Once the phase margin drops below 30°, late-arriving insulin stacks on top of itself ("insulin stacking") and drives BG below target. If it happens at night the patient may not notice, slide into severe hypoglycemia (BG < 54 mg/dL) and lose consciousness. That is why commercial loops layer extra safety: IOB (Insulin On Board) compensation that subtracts the last 4 hours of dosing, and PLGS (predictive low-glucose suspend) that automatically stops the pump when a low is forecast.
🙋
Having to tell the pump "I'm about to eat 60 g of carbs" sounds annoying. Can't that be automated? I keep hearing the phrase "full closed loop".
🎓
Great question. Today's commercial loops are "hybrid closed loop" — only the meal bolus still has to be entered by the patient. Full closed loop (with automatic meal detection) is still in research. Approaches include detecting a meal from the CGM slope and dosing an automatic extra bolus, or using MPC (model predictive control) to look ahead. Closing the 30 min gap to the post-meal peak is genuinely hard, and it is a hot topic for the coming decade. The umbrella term is AID (Automated Insulin Delivery).
🙋
One more thing — the TIR on the left says 90%. Is that actually a great number?
🎓
Yes, that's outstanding. The international consensus target for adults with Type-1 is TIR > 70%, and before CGM was widespread the average for patients on multiple daily injections (MDI) sat around 50%. Modern hybrid closed loops like 780G push many patients to 75-80%, and each extra 10% of TIR is associated with roughly a 0.5% drop in HbA1c, which substantially cuts long-term complications. But TIR alone is not enough — keeping TBR (Time Below Range) < 4%, and severe TBR < 1%, matters just as much. Hyperglycemia is a multi-decade complication, hypoglycemia is a same-night emergency.

Frequently Asked Questions

An artificial pancreas (AP) is a closed-loop control system that uses a continuous glucose monitor (CGM) as feedback and decides the insulin infusion rate from an insulin pump automatically. PID control computes the dose u(t) from the error e(t) against the target BG as Kp·e + Ki·∫e dt + Kd·de/dt. Commercial hybrid closed-loop pumps such as Medtronic MiniMed 770G/780G, Tandem Control-IQ and Insulet Omnipod 5 are all built on this idea.
The carb ratio ICR is the grams of carbohydrate covered by one unit of insulin. With a 60 g meal and ICR = 12 g/U, the bolus is 60/12 = 5.0 U. ICR varies between people and over the day — usually smaller at breakfast (higher insulin resistance) and larger in the evening. Even with a closed loop, the patient or a meal-detection algorithm has to enter the meal bolus; fully automated meal handling (full closed loop) is still under research.
TIR is the fraction of time the BG sits between 70 and 180 mg/dL. ADA and international consensus targets TIR > 70% for adults with Type-1 diabetes, which roughly corresponds to HbA1c < 7% and meaningfully lowers the risk of microvascular complications such as retinopathy and nephropathy. Equally important is keeping time below 70 mg/dL under 4% and time below 54 mg/dL under 1% — preventing severe hypoglycemia matters more than pushing TIR a few extra points.
Subcutaneous insulin takes 1-2 hours to act, which adds a large dead time to the loop. Pushing Kp or Ki too high makes the controller react to a past high BG with too much insulin that lands late, undershoots the target and drives the patient into hypoglycemia (BG < 70 mg/dL). This tool surfaces that risk through the phase margin (>30°) and gain margin (>4 dB). Real implementations use insulin-on-board (IOB) compensation and predictive MPC to handle the delay.

Real-World Applications

Commercial hybrid closed-loop pumps (HCL): Medtronic MiniMed 780G, Tandem Control-IQ and Insulet Omnipod 5 are the leading examples. They communicate wirelessly with CGMs such as Dexcom G6/G7 or Medtronic Guardian 4 and make small adjustments every five minutes using a blend of model-predictive control and PID. In US, UK and EU trials they have raised average TIR from about 50% to 75% for adults with Type-1 diabetes, with HbA1c improvements of 0.5-1.0%. In Japan the 780G was approved in 2023 and reimbursement is widening.

Nocturnal basal adjustment (PLGS — Predictive Low-Glucose Suspend): To avoid severe overnight hypos, the pump automatically suspends delivery once the algorithm predicts BG will drop below 70 mg/dL within 30 minutes. It uses the CGM slope (de/dt), so it is one practical form of derivative control. It cuts nocturnal hypoglycemia time by 50-80% and slashes the risk of seizures or loss of consciousness during sleep. First commercialised in the Medtronic 670G, it is now standard in essentially every HCL.

Dynamic control during exercise and stress: Insulin sensitivity rises during exercise, so a fixed basal triggers hypos. Control-IQ raises the target to 140-160 mg/dL in "activity" mode, while Omnipod 5 re-estimates ISF dynamically from CGM history. Fully automating this requires integrating motion sensors, heart rate and cortisol estimates — Apple Watch / Fitbit integration is an active research path.

Glycemic control in neonates, perioperative care and the ICU: Beyond diabetes, closed-loop insulin control is applied to hyperglycemia in sepsis, post-cardiac-surgery and major surgery. CamAPS HX and research platforms based on the UVA/Padova simulator are used, and they support tight glycemic control in the ICU (since NICE-SUGAR, the target shifted to 140-180 mg/dL). In neonates, BG dynamics differ greatly from adults, so dedicated model calibration is required.

Common Misconceptions and Pitfalls

The biggest pitfall is treating "CGM value = blood glucose" as identical. The CGM measures interstitial fluid glucose electrochemically, and it lags blood glucose by 5-15 minutes. They agree well at steady state, but in rapidly rising post-meal phases or fast-falling exercise phases they can disagree by 20-40 mg/dL. That is why closed loops first denoise the CGM signal with a Kalman filter or IIR smoothing and lag-compensate the slope de/dt before feeding the PID. "My fingerstick and my CGM disagree!" is usually this lag, not a broken sensor.

Next, assuming "higher PID gains will flatten BG further". Subcutaneous insulin has a fixed 60-120 min absorption delay, so even higher Kp or Ki cannot make the loop bandwidth faster than that. Push the phase margin below 30° and you get a limit cycle: BG oscillates between 200 → 60 → 200 → 60 and TIR collapses. As Skyler et al. showed in Diabetes (2017), the safe zone for plain PID is roughly Ki = 0.05-0.15 /h and Kp = 0.3-0.7, combined with an IOB cap. The "gain margin > 4 dB" gauge in this tool maps to that envelope.

Finally, "a high TIR alone means good control" is not true. Consider TIR = 85% with TBR (< 70 mg/dL) = 8% and TAR = 7%: severe hypoglycemia risk is high and there are concerns about long-term cognitive decline. Compare it to TIR = 72% with TBR = 1% and TAR = 27% — that is clinically much safer. The international consensus (Battelino et al., Diabetes Care 2019) requires TIR > 70%, TBR < 4% and severe TBR < 1% all in parallel. The guiding rule of insulin therapy is "lower the BG only as far as you can without causing hypos", and PID gain design must respect that constraint first.

How to Use

  1. Set target glucose to 110–140 mg/dL (typical range for Type-1 diabetes management)
  2. Enter insulin sensitivity factor (ISF, e.g., 1 unit insulin lowers glucose ~40 mg/dL) and carb ratio (e.g., 1 unit per 10g carbs)
  3. Configure basal insulin rate (e.g., 0.8 U/hr) and adjust PID gains to achieve phase margin >40° for system stability
  4. Input meal carbohydrates and observe bolus calculation, post-meal peak glucose, and hypoglycemia risk in real time

Worked Example

Patient with Type-1 diabetes: target 120 mg/dL, ISF 1:40 (40 mg/dL per unit), carb ratio 1:12 (1 unit per 12g carbs), basal 0.9 U/hr. At breakfast with 48g carbs, simulator calculates bolus = 4.0 U (carb coverage). Current glucose 95 mg/dL triggers no correction dose. Post-meal peak reaches 156 mg/dL at +90 min. Total daily insulin estimate: 18.5 U/day. PID phase margin 52° indicates adequate stability; estimated time-in-range (TIR) 78%. Hypoglycemia risk score: 8% (low).

Practical Notes

  1. Increase PID proportional gain cautiously; excessive tuning causes oscillation and hypoglycemic episodes despite high TIR
  2. ISF varies diurnally—morning sensitivity (~1:35) differs from evening (~1:50); run separate profiles for accuracy
  3. Basal rate errors compound over 24 hours; verify via overnight fasting glucose stability before meal testing
  4. Phase margin below 30° signals risk of glucose overshoot; reduce derivative gain or lower target if margin drops
  5. Carb-counting error of ±5g shifts bolus by ~0.4–0.5 U; simulator flags high-carb meals (>60g) for split-dosing strategy