Simulating lung mechanics and coupled breathing sensors with phrenic
Shane Lindsay
This walkthrough covers the respiratory mechanics simulator in
phrenic: how the quiet-rest lung and chest-wall core differs from
analytic waveforms, how individual physical parameters change breath
shape, how resting bronchoconstriction presets behave, and how to replay
real spirometry through the same sensor layer.
See Model & Calibration for the architecture and
equations, and the
README
for CLI flags. The analysis steps use the sister package neuroresp,
so install both in Python 3.11 or newer with
python -m pip install phrenic neuroresp.
from pathlib import Path
import urllib.request
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from neuroresp import analyse_airflow, clean_belt
from neuroresp.meg import respiration_from_ecg
from phrenic import simulate_respiration, simulate_sensors_from_flow
plt.rcParams.update({
"axes.spines.top": False,
"axes.spines.right": False,
"figure.dpi": 140,
})
TEAL = "#086d70"
AMBER = "#d97706"
ORANGE = "#b45125"
SLATE = "#334155"
BLUE = "#0284c7"
1. Analytic lobes versus quiet-rest lung mechanics
The default analytic mode builds each breath from volume-balanced
squared-sine lobes with exact zero-flow pauses. Passing
model="mechanics" (or a named preset such as preset="quiet_rest")
switches to a nonlinear resistance-compliance lung driven by smooth
inspiratory muscle effort, followed by post-inspiratory braking and
passive elastic recoil.
Here we generate 90-second recordings from both engines at 14 breaths/min with a sigh around 25 s, a 5 s peak hold at 55 s, and upper-rail belt clipping. The mechanics run also includes a brief resting swallow at 76 s.
s_ana = simulate_respiration(
duration_s=90.0, rate_bpm=14.0, rate_sd_bpm=0.8, vt_cv=0.06,
sigh_times_s=(25.0,), hold_intervals_s=((55.0, 5.0),), hold_phase="peak",
belt_clip_quantile=0.92, noise_level=0.005, seed=4,
)
s_mech = simulate_respiration(
duration_s=90.0, rate_bpm=14.0, rate_sd_bpm=0.8, vt_cv=0.06,
sigh_times_s=(25.0,), hold_intervals_s=((55.0, 5.0),), hold_phase="peak",
swallow_times_s=(76.0,), belt_clip_quantile=0.92, noise_level=0.005,
preset="quiet_rest", seed=4,
)
af_ana = analyse_airflow(s_ana["flow_l_s"], s_ana["fs"], calibrated=True)["summary"]
af_mech = analyse_airflow(s_mech["flow_l_s"], s_mech["fs"], calibrated=True)["summary"]
cols = [
"cycle_rate_median_bpm", "duty_cycle_median", "tptif_ti_median",
"tptef_te_median", "flatness_in_median", "exp_pause_frac_median", "vt_median_l",
]
pd.DataFrame({
"Analytic": {k: af_ana[k] for k in cols},
"Mechanics (quiet_rest)": {k: af_mech[k] for k in cols},
}).round(3)
Both runs match the target breathing rate and 0.50 L tidal volume, while
their breath shapes differ clearly. The analytic cycle peaks near the
middle of both phases (tptif_ti = 0.51, tptef_te = 0.47) with a
narrow inspiratory bell (flatness_in = 0.62). The mechanics cycle
rises briskly into a rounder inspiratory top (tptif_ti = 0.40,
flatness_in = 0.71) and peaks earlier in expiration (tptef_te =
0.34) before tapering passively to a quiet end-expiratory pause.
The 40-second window below covers the sigh, post-sigh recovery breath, and peak hold so you can compare the sensors directly.
t = s_mech["time_s"]
win = (t >= 20.0) & (t <= 64.0)
fig, axes = plt.subplots(2, 1, figsize=(10.0, 5.4), sharex=True, constrained_layout=True)
axes[0].axvspan(55.0, 60.0, color=TEAL, alpha=0.10)
axes[0].plot(t[win], s_ana["flow_l_s"][win], color="#94a3b8", lw=1.1, ls="--", label="Analytic lobes")
axes[0].plot(t[win], s_mech["flow_l_s"][win], color=TEAL, lw=1.4, label="Mechanics (quiet_rest)")
axes[0].axhline(0, color="#94a3b8", lw=0.7, ls=":")
axes[0].text(57.5, 0.88, "5 s peak hold", ha="center", fontsize=8.5, color=SLATE)
axes[0].set(ylabel="Flow (L/s)", title="Airway flow: analytic lobes vs quiet-rest mechanics")
axes[0].legend(frameon=False, loc="upper right", ncol=2)
axes[1].axvspan(55.0, 60.0, color=TEAL, alpha=0.10)
axes[1].plot(t[win], s_mech["rip_volume"][win], color=TEAL, lw=1.5, label="Dual RIP sum (V)")
axes[1].plot(t[win], s_mech["rip_chest_volume"][win], color=SLATE, lw=0.95, ls="--", label="Ribcage RIP")
axes[1].plot(t[win], s_mech["rip_abdomen_volume"][win], color=BLUE, lw=0.95, ls=":", label="Abdomen RIP")
ac_aligned = s_mech["ac_belt"][win] - np.median(s_mech["ac_belt"][win]) + np.median(s_mech["rip_volume"][win])
axes[1].plot(t[win], ac_aligned, color=ORANGE, lw=1.05, label="Clipped AC belt")
axes[1].set(xlabel="Time (s)", ylabel="Volume / belt (L)",
title="Mechanics chest-wall bands and clipped AC belt")
axes[1].legend(frameon=False, loc="upper right", ncol=2)
axes[1].set_xlim(20, 64)
plt.show()

In the top panel, releasing the glottic hold at 60 s produces a smooth elastic recoil peak followed by passive decay. In the bottom panel, the ribcage and abdomen bands sum exactly to total lung volume while the single AC belt clips on the sigh and decays toward baseline across the hold.
2. How mechanical parameters shape individual breaths
Holding breath rate regular (rate_sd_bpm=0, vt_cv=0) isolates how
four core parameters alter the waveform: linear airway resistance,
respiratory compliance, post-inspiratory braking, and ribcage-abdomen
phase lag.
fig, axes = plt.subplots(4, 1, figsize=(11.2, 8.8))
fig.subplots_adjust(left=0.08, right=0.72, top=0.95, bottom=0.06, hspace=0.55)
def win15(s, t0=12.0, t1=27.0):
m = (s["time_s"] >= t0) & (s["time_s"] <= t1)
return s["time_s"][m] - t0, m
def side_legend(ax):
ax.legend(frameon=False, fontsize=8.3, loc="center left", bbox_to_anchor=(1.02, 0.5))
# Row 1: Linear resistance at fixed inspiratory effort
ax = axes[0]
for r1, col, label in [(4.0, TEAL, "Healthy"), (10.0, AMBER, "Elevated"), (18.0, ORANGE, "High")]:
s = simulate_respiration(
duration_s=32, rate_bpm=14, rate_sd_bpm=0, vt_cv=0, noise_level=0,
model="mechanics", resistance_cmh2o_s_l=r1, peak_pmus_cmh2o=6.0, rc_ab_lag_s=0.0,
)
ts, m = win15(s)
vt = s["truth"]["vt_l"].iloc[2:].median()
ax.plot(ts, s["flow_l_s"][m], color=col, lw=1.5, label=f"{label}: R1={r1:.0f}\n Vt={vt:.2f} L")
ax.axhline(0, color="#94a3b8", lw=0.7, ls="--")
ax.set(ylabel="Flow (L/s)", xlim=(0, 15))
ax.set_title("1. Airway resistance R1 (fixed effort P_mus = 6 cmH2O)", loc="left", fontsize=10, fontweight="bold")
side_legend(ax)
# Row 2: Compliance at fixed inspiratory effort
ax = axes[1]
for comp, col, label in [(0.05, ORANGE, "Stiff"), (0.10, TEAL, "Normal"), (0.18, BLUE, "High C")]:
s = simulate_respiration(
duration_s=32, rate_bpm=14, rate_sd_bpm=0, vt_cv=0, noise_level=0,
model="mechanics", compliance_l_cmh2o=comp, peak_pmus_cmh2o=5.5, rc_ab_lag_s=0.0,
)
ts, m = win15(s)
vt = s["truth"]["vt_l"].iloc[2:].median()
ax.plot(ts, s["rip_volume"][m], color=col, lw=1.55, label=f"{label}: C={comp:.2f}\n Vt={vt:.2f} L")
ax.set(ylabel="Volume (L)", xlim=(0, 15))
ax.set_title("2. Respiratory compliance C (fixed effort P_mus = 5.5 cmH2O)", loc="left", fontsize=10, fontweight="bold")
side_legend(ax)
# Row 3: Post-inspiratory diaphragmatic braking
ax = axes[2]
for btau, col, label in [(0.0, ORANGE, "No braking"), (0.20, AMBER, "Light"), (0.44, TEAL, "Quiet rest")]:
s = simulate_respiration(
duration_s=32, rate_bpm=14, rate_sd_bpm=0, vt_cv=0, noise_level=0,
model="mechanics", braking_tau_s=btau, rc_ab_lag_s=0.0,
)
ts, m = win15(s)
tptef = s["truth"]["tptef_te"].iloc[2:].median()
ax.plot(ts, s["flow_l_s"][m], color=col, lw=1.5, label=f"{label}: tau={btau:.2f} s\n tPTEF/Te={tptef:.2f}")
ax.axhline(0, color="#94a3b8", lw=0.7, ls="--")
ax.set(ylabel="Flow (L/s)", xlim=(0, 15))
ax.set_title("3. Post-inspiratory diaphragmatic braking (braking_tau_s)", loc="left", fontsize=10, fontweight="bold")
side_legend(ax)
# Row 4: Konno-Mead chest-wall lag vs airway zero-flow peaks
ax = axes[3]
s_lag = simulate_respiration(
duration_s=32, rate_bpm=14, rate_sd_bpm=0, vt_cv=0, noise_level=0,
preset="quiet_rest", rc_fraction=0.50, rc_ab_lag_s=-0.22,
)
ts, m = win15(s_lag, 12.0, 22.0)
ax.plot(ts, s_lag["rip_volume"][m], color=TEAL, lw=1.7, label="Dual RIP sum V\n (airway peak)")
ax.plot(ts, s_lag["rip_chest_volume"][m] / 0.50, color=BLUE, lw=1.25, ls="--", label="Ribcage (scaled)\n (lags airway)")
ax.plot(ts, s_lag["rip_abdomen_volume"][m] / 0.50, color=ORANGE, lw=1.25, ls=":", label="Abdomen (scaled)\n (leads airway)")
for b in s_lag["truth"].itertuples():
tp = b.insp_end_s - 12.0
if 0.5 < tp < 9.5:
ax.axvline(tp, color=SLATE, lw=0.8, ls="-.", alpha=0.6)
ax.set(xlabel="Elapsed time (s)", ylabel="Scaled vol (L)", xlim=(0, 10))
ax.set_title("4. Konno-Mead chest-wall lag (rc_ab_lag_s = -0.22 s, abdomen leading)", loc="left", fontsize=10, fontweight="bold")
side_legend(ax)
plt.show()

Higher resistance blunts peak flow and stretches passive emptying; higher compliance increases volume excursion and lengthens recoil; post-inspiratory braking rounds the expiratory turnaround and moves peak expiratory flow away from the instant of reversal; and ribcage-abdomen phase lag shifts each single band relative to airway zero-flow while their sum aligns with the vertical zero-flow lines.
3. Resting bronchoconstriction presets and flow-volume loops
The four named presets cover supine quiet rest, seated quiet rest, and mild or moderate resting tidal bronchoconstriction (higher expiratory and low-volume resistance, with passive expiration). Comparing steady breaths across presets illustrates how bronchoconstriction reshapes tidal loops and chest-wall coordination even when minute ventilation is defended at 0.50 L per breath.
preset_list = [
("quiet_rest", "Quiet rest (supine)", TEAL),
("seated_rest", "Seated rest", BLUE),
("mild_bronchoconstriction", "Mild bronchoconstriction", AMBER),
("moderate_bronchoconstriction", "Moderate bronchoconstriction", ORANGE),
]
preset_sims = {}
rows = []
for name, _, _ in preset_list:
s = simulate_respiration(
duration_s=90.0, rate_bpm=14.0, rate_sd_bpm=0.0, vt_cv=0.0,
noise_level=0.0, preset=name,
)
preset_sims[name] = s
tr = s["truth"].iloc[3:]
rows.append({
"preset": name,
"vt_l": tr["vt_l"].median(),
"peak_pmus_cmh2o": tr["peak_pmus_cmh2o"].median(),
"tptef_te": tr["tptef_te"].median(),
"exp_pause_s": tr["exp_pause_s"].median(),
"end_exp_volume_l": tr["end_exp_volume_l"].median(),
"rc_ab_phase_deg": tr["rc_ab_phase_deg"].median(),
})
pd.DataFrame(rows).round(3)
As expiratory and low-volume resistance rises from quiet_rest to
moderate_bronchoconstriction, tptef_te drops from 0.27 to 0.12, the
natural end-expiratory pause shrinks from 0.26 s to 0.05 s,
end-expiratory lung volume climbs from 0.01 L to 0.24 L (dynamic
hyperinflation), and peak inspiratory muscle effort more than doubles
from 5.5 to 11.6 cmH2O to maintain the same 0.50 L tidal volume.
The tidal flow-volume loop and Konno-Mead chest-wall loop below illustrate both effects on a single steady breath.
fig, axes = plt.subplots(1, 2, figsize=(10.6, 4.3), constrained_layout=True)
for name, label, col in [
("quiet_rest", "Quiet rest (supine)", TEAL),
("mild_bronchoconstriction", "Mild bronchoconstriction", AMBER),
("moderate_bronchoconstriction", "Moderate bronchoconstriction", ORANGE),
]:
s = preset_sims[name]
b = s["truth"].iloc[6]
lo, hi = round(b.start_s * s["fs"]), round(b.end_s * s["fs"])
axes[0].plot(s["rip_volume"][lo:hi], s["flow_l_s"][lo:hi], color=col, lw=1.6,
label=f"{label} (Vee={b.end_exp_volume_l:.2f} L)")
rc = s["rip_chest_volume"][lo:hi] - np.min(s["rip_chest_volume"][lo:hi])
ab = s["rip_abdomen_volume"][lo:hi] - np.min(s["rip_abdomen_volume"][lo:hi])
axes[1].plot(ab, rc, color=col, lw=1.6, label=f"{label} ({b.rc_ab_phase_deg:+.1f} deg)")
axes[0].axhline(0, color="#94a3b8", lw=0.7, ls="--")
axes[0].set(xlabel="Lung volume above FRC (L)", ylabel="Flow (L/s)", ylim=(-0.54, 0.64),
title="Tidal flow-volume loops")
axes[0].legend(frameon=False, fontsize=8.2, loc="upper right")
axes[1].set(xlabel="Abdomen excursion (L)", ylabel="Ribcage excursion (L)",
title="Konno-Mead chest-wall loops")
axes[1].legend(frameon=False, fontsize=8.2, loc="upper left")
plt.show()

In the left panel, higher expiratory resistance shifts the loop rightward along the volume axis (air trapping) and scoops the expiratory limb inward. In the right panel, the loop opens wider and tilts upward as ribcage sharing and phase lag increase.
4. Driving the lung core directly (solve_lung_mechanics)
Because the lung and chest-wall solver sits in its own zero-neuroimaging
module, you can pass any custom or externally generated inspiratory
effort trace pmus directly into solve_lung_mechanics(). Below we
drive the lung with a smooth breathing-rate acceleration from 10 to 22
breaths/min under elevated resistance to show frequency-dependent
breath-stacking.
fs = 100.0
t_ext = np.arange(0.0, 40.0, 1.0 / fs)
inst_freq = np.linspace(10.0, 22.0, len(t_ext)) / 60.0
phase = 2.0 * np.pi * np.cumsum(inst_freq) / fs
pmus_ext = 9.0 * np.maximum(0.0, np.sin(phase)) ** 1.4
solved = solve_lung_mechanics(
pmus_ext, np.zeros(len(t_ext), dtype=bool), fs,
resistance_cmh2o_s_l=10.0, exp_resistance_ratio=1.4,
volume_resistance_slope=1.2, compliance_l_cmh2o=0.10,
)
fig, axes = plt.subplots(2, 1, figsize=(10.0, 4.4), sharex=True, constrained_layout=True)
axes[0].plot(t_ext, pmus_ext, color=SLATE, lw=1.2)
axes[0].set(ylabel="P_mus (cmH2O)", title="External inspiratory effort ramping from 10 to 22 breaths/min")
axes[1].plot(t_ext, solved["volume"], color=ORANGE, lw=1.4)
axes[1].set(xlabel="Time (s)", ylabel="Lung volume (L)",
title="Resulting lung volume: end-expiratory baseline climbs as breaths speed up")
axes[1].set_xlim(0, 40)
plt.show()

Even with constant peak effort (9 cmH2O), accelerating the breathing rate shortens the time available for passive emptying, causing end-expiratory lung volume to climb while tidal excursion shrinks.
5. Replaying real airflow through the sensor layer
The sensor adapters sit downstream of the physiological state, so any
calibrated airflow recording can drive them directly through
simulate_sensors_from_flow(). Here we download one minute of 100 Hz
quiet resting Venturi airflow from an adult (Subject_11, 0 cmH2O
normal breathing) in the open-access PhysioNet CPAP dataset (Guy et al.,
2023), compare its airflow metrics with our simulated quiet_rest run,
and pass it through a clipped AC belt, a 5 s loose-strap dropout, TR 2.0
s MRI shifts, low-RSA ECG, and finger PPG.
cache = Path("/tmp/neuroresp_tutorial_cpap/Subject_11_0cmH20_norm_breaths.csv")
cache.parent.mkdir(parents=True, exist_ok=True)
if not cache.exists():
url = (
"https://physionet.org/files/pressure-flow-circum-cpap/1.0.0/"
"processed-data/0cmH2O_norm/Subject_11_0cmH20_norm_breaths.csv"
)
urllib.request.urlretrieve(url, cache)
df_cpap = pd.read_csv(cache)
fs_cpap = round(1.0 / np.median(np.diff(df_cpap["Time [s]"])))
flow_real = df_cpap["Flow [L/s]"].to_numpy(float)
af_real = analyse_airflow(flow_real, fs_cpap, calibrated=True)["summary"]
pd.DataFrame({
"Real CPAP (Subject 11)": {k: af_real[k] for k in cols},
"Simulated quiet_rest": {k: af_mech[k] for k in cols},
}).round(3)
The simulated quiet_rest breath shape sits close to the real adult
recording across inspiratory peak timing (0.40 vs 0.39), inspiratory
flatness (0.71 vs 0.74), expiratory peak timing (0.34 vs 0.28), and
expiratory pause fraction (0.15 vs 0.16). Next we feed the real airflow
directly into simulate_sensors_from_flow() and verify how
clean_belt() and respiration_from_ecg() perform on the generated
sensors.
replayed = simulate_sensors_from_flow(
flow_real, fs_cpap,
rc_fraction=0.40, rc_ab_lag_s=-0.16,
belt_clip_quantile=0.92, loose_intervals_s=((40.0, 5.0),),
mri_tr_s=2.0, mri_shots_per_tr=8,
rsa_amp_bpm=1.0, seed=4,
)
_, _, sum_ac, _ = clean_belt(
replayed["ac_belt"], fs_cpap, upper_rail=replayed["belt_upper_rail"],
)
ecg_res = respiration_from_ecg(replayed["ecg"], replayed["ecg_fs"])
pd.Series({
"real_airflow_bpm": round(af_real["cycle_rate_median_bpm"], 2),
"clipped_belt_bpm": round(sum_ac["cycle_rate_median_bpm"], 2),
"belt_clip_fraction": round(sum_ac["clip_fraction"], 3),
"belt_loose_fraction": round(sum_ac["loose_fraction"], 3),
"belt_segments": sum_ac["n_segments"],
"low_rsa_ecg_bpm": round(ecg_res["f_resp"] * 60.0, 2),
})
real_airflow_bpm 12.100
clipped_belt_bpm 12.590
belt_clip_fraction 0.088
belt_loose_fraction 0.111
belt_segments 2.000
low_rsa_ecg_bpm 12.190
dtype: float64
Even with 8.8% belt clipping, a 5 s loose-strap dropout that splits the
belt into two segments, and low heart-rate RSA (1 beat/min), both
clean_belt() and respiration_from_ecg() stay close to the true 12.1
breaths/min airflow rate.
tr = replayed["time_s"]
fig, axes = plt.subplots(4, 1, figsize=(10.0, 7.2), sharex=True, constrained_layout=True)
axes[0].plot(tr, replayed["flow_l_s"], color=SLATE, lw=1.1)
axes[0].axhline(0, color="#94a3b8", lw=0.7, ls="--")
axes[0].set(ylabel="Flow (L/s)", title="Real calibrated airflow (PhysioNet CPAP Subject 11)")
ac_off = np.median(replayed["rip_volume"]) - np.median(replayed["ac_belt"])
axes[1].axvspan(40.0, 45.0, color="#64748b", alpha=0.16)
axes[1].plot(tr, replayed["rip_volume"], color=TEAL, lw=1.3, label="Integrated DC RIP sum")
axes[1].plot(tr, replayed["ac_belt"] + ac_off, color=ORANGE, lw=1.0, label="Clipped AC belt + loose strap")
axes[1].set(ylabel="Volume / belt", ylim=(-0.16, 0.74), title="Synthetic DC RIP and clipped AC belt from real breaths")
axes[1].legend(frameon=False, loc="upper right", ncol=2)
axes[2].plot(replayed["mri_subtr_time_s"], replayed["mri_subtr_pe_mm"], color=TEAL, lw=1.2, label="Sub-TR shots (4 Hz)")
axes[2].plot(replayed["mri_vol_time_s"], replayed["mri_vol_pe_mm"], "o--", color=ORANGE, ms=3, lw=0.9, label="Whole volume (TR 2.0 s)")
axes[2].set(ylabel="PE shift (mm)", title="MRI phase-encoding displacement on shot vs volume clocks")
axes[2].legend(frameon=False, loc="upper right", ncol=2)
axes[3].plot(tr, replayed["ppg"], color="#7c3aed", lw=0.85)
axes[3].set(xlabel="Time (s)", ylabel="PPG (a.u.)", title="Finger PPG on the shared cardiac beat clock", xlim=(0, float(tr[-1])))
plt.show()

6. Summary
- Use
model="analytic"when you want exact analytical zero-flow boundaries for unit tests and quickstarts, andmodel="mechanics"(or a preset) when passive emptying, breath-stacking, post-inspiratory braking, or ribcage-abdomen phase lag matter. - Keep resting elevated-resistance presets interpreted as mild-to-moderate tidal bronchoconstriction with passive expiration, separate from forced spirometry or closed-loop gas exchange.
- Use
solve_lung_mechanics()to test custom or externally generated inspiratory drive curves on the same mechanical lung. - Use
simulate_sensors_from_flow()to pair real human breathing irregularity with controlled belt clipping, loose straps, slow-TR MRI sampling, low-RSA ECG, and finger PPG.
References
- Albanese, A., Cheng, L., Ursino, M., & Chbat, N. W. (2016). An integrated mathematical model of the human cardiopulmonary system: model development. American Journal of Physiology-Heart and Circulatory Physiology, 310(7), H899-H921. https://doi.org/10.1152/ajpheart.00230.2014
- Bates, J. H. T. (2009). Lung Mechanics: An Inverse Modeling Approach. Cambridge University Press. https://doi.org/10.1017/CBO9780511627156
- Guy, E. F. S., Knopp, J., Lerios, T., & Chase, J. G. (2023). Pressure, flow, and dynamic thoraco-abdominal circumferences data for adults breathing under CPAP therapy (version 1.0.0). PhysioNet. https://doi.org/10.13026/25q9-y416
- Konno, K., & Mead, J. (1967). Measurement of the separate volume changes of rib cage and abdomen during breathing. Journal of Applied Physiology, 22(3), 407-422. https://doi.org/10.1152/jappl.1967.22.3.407