Typed Pipeline, Extensibility & Simulation-Based Inference
phrenic 0.2.0 organises forward simulation around four explicit seams so new sensors, biological mechanisms, priors, and inference backends compose cleanly without tangling physiology with measurement hardware.
flowchart LR
P["Physiology (θ)<br/>rhythm, mechanics, CO2 loop,<br/>cardiac & vascular coupling"] --> Core
PR["Protocol<br/>duration, sighs, holds,<br/>inhaled CO2 blocks, task cues"] --> Core
Core["Forward physics<br/>drive.py + mechanics.py + gas.py"] --> S["PhysiologicalState<br/>flow, volume, P_mus, PaCO2,<br/>beats, chest-wall volumes"]
H["Hardware (ν)<br/>selected sensors, TR, ECG fs,<br/>clipping, loose belt, ectopy"] --> R["SENSOR_REGISTRY<br/>render_sensors(state, hw, rng)"]
S --> R
R --> Out["Coupled sensor outputs"]
Out --> Inv["SimulationPosterior (inverse.py)<br/>or external neural SBI (to_training_arrays)"]
1. Typed forward runs and re-rendering hardware
simulate() takes three frozen dataclasses — Physiology, Protocol, and Hardware — and returns only the sensor channels listed in Hardware.sensors (or all registered sensors when sensors=None), together with the shared PhysiologicalState.
import numpy as np
from phrenic import Hardware, Physiology, Protocol, render_sensors, simulate
phys = Physiology.from_preset(
"quiet_rest",
rate_bpm=14.0,
chemo_gain=0.04, # opt-in two-pool CO2 chemoreflex loop
arterial_stiffness=1.3, # damps finger PPG respiratory pulse-height modulation
)
prot = Protocol(
duration_s=180.0,
fs=50.0,
inspired_co2_blocks_s=((60.0, 45.0, 28.0),), # (start_s, duration_s, mmHg rise)
)
hw = Hardware(sensors=("ac_belt", "capnogram", "mri_b0", "bold"), mri_tr_s=1.5)
sim = simulate(phys, prot, hw, seed=1)
# Re-render the exact same breathing trajectory under faster MRI and 250 Hz ECG
alt = render_sensors(
sim["state"],
Hardware(sensors=("ecg", "mri_b0", "bold"), ecg_fs=250.0, mri_tr_s=0.8),
np.random.default_rng(2),
)
2. Adding a custom sensor
Any callable matching (state: PhysiologicalState, hardware: Hardware, rng: np.random.Generator) -> dict can be registered without modifying core mechanics or gas code. Top-level functions also work across parallel simulate_batch(..., n_workers>1) workers.
from phrenic import Hardware, PhysiologicalState, register_sensor, simulate
def piezo_chest_band(state: PhysiologicalState, hw: Hardware, rng):
n = len(state.time_s)
sig = 1.4 * state.rip_chest[:n] + hw.noise_level * rng.standard_normal(n)
return {"piezo_chest": sig}
register_sensor("piezo_chest", piezo_chest_band)
sim = simulate(hardware=Hardware(sensors=("ac_belt", "piezo_chest")), seed=0)
3. Age-blind priors, demographic priors, and clinical deviants
Priors sit outside the forward physics in priors.py so validation stays leak-free:
BlindPrior: Wide, age-free prior for training and validating waveform-only inverse models without demographic leakage.NormativePrior(age, sex, height_cm, bmi): Empirical lifespan resting reference (ages 6–88, with paediatric stature scaling when height is omitted) for computing post-hoc normative z-scores and centiles.clinical_deviant(name, **overrides): Named clinical regimes (copd,ild,sleep_apnoea,rbd_autonomic,dysfunctional_breathing) expressed strictly asPhysiologyparameter deltas that can be overridden directly to sweep severity.
from phrenic import BlindPrior, NormativePrior, clinical_deviant
blind_bank = BlindPrior(include_closed_loop=True).sample_batch(200, seed=1)
ref_70f = NormativePrior(age=70, sex="female", height_cm=162, bmi=25)
mild_copd = clinical_deviant("copd", rate_bpm=17.5, resistance_cmh2o_s_l=7.5)
4. Simulation-Based Inference (SimulationPosterior)
SimulationPosterior provides a zero-bloat NumPy/SciPy local-linear ABC backend built for multi-sensor recordings with missing channels, plus clean array export for external neural posterior estimators (for example PyTorch/sbi).
import numpy as np
from scipy.signal import find_peaks
from phrenic import BlindPrior, Hardware, NormativePrior, Protocol, SimulationPosterior, simulate_batch
def summarize_belt(sim: dict) -> dict:
belt, fs = sim["ac_belt"], sim["fs"]
pks, _ = find_peaks(belt, distance=int(1.4 * fs), prominence=0.35 * float(np.std(belt)))
dt = np.diff(pks) / fs
return {
"obs_rate": float(60.0 / np.median(dt)) if len(dt) >= 5 else float("nan"),
"obs_dt_sd": float(np.std(dt, ddof=1)) if len(dt) >= 5 else float("nan"),
}
thetas, feats = simulate_batch(
BlindPrior().sample_batch(250, seed=0),
protocol=Protocol(duration_s=120.0, fs=40.0),
hardware=lambda rng: Hardware(sensors=("ac_belt",), noise_level=float(rng.uniform(0.005, 0.025))),
summarize=summarize_belt,
n_workers=4,
seed=0,
)
post = SimulationPosterior(n_neighbors=40).fit(feats, thetas[["rate_bpm", "ar1_phi", "vt_l"]])
est = post.predict({"obs_rate": 15.2, "obs_dt_sd": 0.45})
# Post-hoc normative centiles from the age-blind posterior
profile = post.deviation_profile({"obs_rate": 15.2, "obs_dt_sd": 0.45}, NormativePrior(age=45, sex="male"))
# Export aligned raw NumPy arrays for optional neural SBI backends
X, Theta, feature_names, target_names = post.to_training_arrays()
Key methods on SimulationPosterior:
predict_one()/predict(): Projects onto whichever observed features are finite, falling back to the unconditional prior when all features for a target are missing.sbc_check(val_feats, val_thetas, calibrate=True): Computes held-out coverage, Pearson r, MAE, and mean rank, calibrating per actually-observed sensor subset.fit_visit_variance()/predict_next_visit(): Combines within-scan posterior uncertainty with day-to-day biological state variance estimated from repeat visits.deviation_profile(obs, normative_prior): Places age-blind posterior estimates onto age/sex/BMI-conditioned normative centiles.to_training_arrays(): Exports aligned(X, Theta)arrays preserving exact boundary values (such as open-loopchemo_gain = 0.0) for neural SBI training.