---
title: "Cross-sensor replay, clipped-belt waveform rescue, and two-pool CO₂"
subtitle: "Projecting one recorded sensor across the rest, fusing belt + MRI B0 + ECG, and modelling arterial CO₂"
author: "Shane Lindsay"
format:
  html:
    toc: true
    code-fold: false
    theme: cosmo
    embed-resources: true
execute:
  warning: false
  message: false
jupyter: python3
---

Most studies record only one or two breathing sensors. This walkthrough shows how to project a recorded signal across the remaining sensors with 5th–95th percentile intervals (`replay_sensor_array`), repair a clipped belt using simultaneous MRI B0 and ECG (`fuse_waveforms`), and propagate airflow through a two-pool CO₂ and BOLD model (`simulate_two_pool_co2`).

Every example uses open-access recordings downloaded into `/tmp/` on first run. Install `neuroresp` in Python 3.11 or newer with `python -m pip install neuroresp`.

```{python}
from pathlib import Path
import urllib.request
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy import signal

from neuroresp import fuse_waveforms, respiration_from_ecg
from phrenic import replay_sensor_array, simulate_respiration, simulate_two_pool_co2

plt.rcParams.update({
    "axes.spines.top": False,
    "axes.spines.right": False,
    "figure.dpi": 140,
})
TEAL = "#086d70"
ORANGE = "#b45125"
SLATE = "#334155"
BLUE = "#0284c7"
```

## 1. Projecting a real belt onto airflow, CO₂, and MRI B0

We start with one minute of quiet resting breathing from `Subject_11` in the open-access PhysioNet CPAP dataset (Guy et al., 2023), which records calibrated Venturi airflow alongside chest and abdominal straps at 100 Hz. First we hide the airflow trace, feed only the abdominal strap into `replay_sensor_array()`, and compare the predicted airflow interval against the held-out spirometer.

```{python}
cpap_cache = Path("/tmp/neuroresp_tutorial_cpap/Subject_11_0cmH20_norm_breaths.csv")
cpap_cache.parent.mkdir(parents=True, exist_ok=True)
if not cpap_cache.exists():
    urllib.request.urlretrieve(
        "https://physionet.org/files/pressure-flow-circum-cpap/1.0.0/"
        "processed-data/0cmH2O_norm/Subject_11_0cmH20_norm_breaths.csv",
        cpap_cache,
    )
df = pd.read_csv(cpap_cache)
fs = 50.0
flow_real = df["Flow [L/s]"].to_numpy(float)[::2]
chest = df["Chest [mm]"].to_numpy(float)[::2]
abd = df["Abd [mm]"].to_numpy(float)[::2]

# Age-blind replay from one abdominal strap vs dual straps with demographics
from_abd = replay_sensor_array(abd, fs, source="belt", n_draws=40, seed=1)
from_dual = replay_sensor_array(
    chest, fs, source="dual_rip", second_signal=abd,
    age=26, sex="M", height_cm=178, n_draws=40, seed=1,
)

t = from_abd["time_s"]
m = (t >= 5.0) & (t <= 45.0)
fig, axes = plt.subplots(3, 1, figsize=(9.5, 6.4), sharex=True)
for ax, out, title in [
    (axes[0], from_abd, "Single abdominal belt (age-blind) vs held-out real airflow"),
    (axes[1], from_dual, "Chest + abdomen straps with height/sex prior vs held-out real airflow"),
]:
    ax.fill_between(t[m], out["flow_l_s"]["p05"][m], out["flow_l_s"]["p95"][m], color=BLUE, alpha=0.22, label="90% interval")
    ax.plot(t[m], out["flow_l_s"]["median"][m], color=BLUE, lw=1.3, label="Model median")
    ax.plot(t[m], flow_real[m], color=ORANGE, lw=1.3, ls="--", label="Real Venturi airflow")
    ax.axhline(0, color="#999", lw=0.6)
    ax.set_ylabel("Flow (L/s)")
    ax.set_title(title, loc="left", fontweight="bold", fontsize=9.5)
    ax.legend(frameon=False, loc="upper right", ncol=3, fontsize=8)

axes[2].fill_between(t[m], from_dual["capnogram_mmhg"]["p05"][m], from_dual["capnogram_mmhg"]["p95"][m], color=TEAL, alpha=0.22)
axes[2].plot(t[m], from_dual["capnogram_mmhg"]["median"][m], color=TEAL, lw=1.3, label="Predicted CO₂ capnogram (90% interval)")
axes[2].set(ylabel="CO₂ (mmHg)", xlabel="Time (s)")
axes[2].legend(frameon=False, loc="upper right", fontsize=8)
fig.tight_layout()
plt.show()
```

Passing `age`, `sex`, and `height_cm` tightens the tidal-volume and cardiac priors while leaving channels the input sensor cannot constrain (such as baseline end-tidal CO₂) at realistic widths.

## 2. Repairing a clipped belt with MRI B0 and ECG (`fuse_waveforms`)

When a scanner belt saturates on deep breaths, `fuse_waveforms()` aligns any simultaneous auxiliary traces (MRI B0, ECG, or both) on the unclipped flanks, drops channels whose flank correlation falls below `min_aux_corr`, and combines usable sensors by inverse variance. Clean belt flanks stay untouched while uncertainty expands only across the repaired caps.

First we test three-sensor fusion on a simulated scan with belt clipping, MRI B0, ECG, and a corrupted dummy channel:

```{python}
sim = simulate_respiration(
    duration_s=90.0, fs=50.0, ecg_fs=500.0, preset="quiet_rest",
    sigh_times_s=(25.0, 62.0), belt_clip_quantile=0.86, rsa_amp_bpm=3.5, seed=3,
)
ecg_r = respiration_from_ecg(sim["ecg"], sim["ecg_fs"])
t_ecg = np.arange(len(ecg_r["wave"]), dtype=float) * (90.0 / len(ecg_r["wave"]))
rescued = fuse_waveforms(
    sim["time_s"], sim["ac_belt"], sim["belt_clip_mask"],
    {
        "mri": (sim["mri_subtr_time_s"], sim["mri_subtr_pe_mm"]),
        "ecg": (t_ecg, ecg_r["wave"]),
        "corrupt": (t_ecg, np.random.default_rng(0).standard_normal(len(t_ecg))),
    },
)
print("Aux weights:", {k: round(v, 3) for k, v in rescued["aux_weights"].items()})
print("Rescued fraction:", round(rescued["rescued_fraction"], 3))
```

Next we run the same rescue on a real 68-year-old adult (`04_1`) from the open-access Schumann & Bär (2022) dataset, clipping the top 15% of the chest belt and repairing the flat peaks from the simultaneous 1 kHz ECG:

```{python}
sch_cache = Path("/tmp/neuroresp_tutorial_schumann/04_1.txt")
sch_cache.parent.mkdir(parents=True, exist_ok=True)
if not sch_cache.exists():
    urllib.request.urlretrieve("https://ndownloader.figshare.com/files/49365466", sch_cache)
arr = np.loadtxt(sch_cache, max_rows=90000)
ecg_1k, belt_1k = arr[:, 1], arr[:, 2]
sos = signal.butter(2, (0.05, 1.0), btype="bandpass", fs=1000.0, output="sos")
belt_true = signal.sosfiltfilt(sos, belt_1k - np.mean(belt_1k))[::20]
t_b = np.arange(len(belt_true)) / 50.0
rail = float(np.quantile(belt_true, 0.85))
belt_clip = np.minimum(belt_true, rail)
clip_mask = belt_true >= rail

ecg_sch = respiration_from_ecg(ecg_1k, 1000.0)
t_e = np.arange(len(ecg_sch["wave"])) * (90.0 / len(ecg_sch["wave"]))
sch_rescued = fuse_waveforms(t_b, belt_clip, clip_mask, {"ecg": (t_e, ecg_sch["wave"])})

ms = (t_b >= 15.0) & (t_b <= 60.0)
fig, ax = plt.subplots(figsize=(9.5, 3.2))
ax.fill_between(t_b[ms], sch_rescued["fused_p05"][ms], sch_rescued["fused_p95"][ms], color=BLUE, alpha=0.25, label="90% interval")
ax.plot(t_b[ms], sch_rescued["fused"][ms], color=BLUE, lw=1.4, label="Clipped belt + ECG")
ax.plot(t_b[ms], belt_true[ms], color=ORANGE, lw=1.3, ls="--", label="Held-out true belt")
ax.set(xlabel="Time (s)", ylabel="Belt (a.u.)", title="Schumann 04_1 (age 68): rescuing clipped belt peaks with 1 kHz ECG")
ax.legend(frameon=False, loc="lower right", ncol=3, fontsize=8)
fig.tight_layout()
plt.show()
```

## 3. Two-pool CO₂ and BOLD kinetics (`simulate_two_pool_co2`)

A single deep sigh washes CO₂ out of the lungs and drives a delayed cortical BOLD dip roughly 12 seconds later. By contrast, breathing faster while taking shallower breaths spends more ventilation on anatomical dead space and leaves alveolar CO₂ nearly flat:

```{python}
base = simulate_respiration(duration_s=90, fs=50, rate_bpm=14, rate_sd_bpm=0, vt_l=0.50, vt_cv=0, noise_level=0, preset="quiet_rest", seed=1)
sigh = simulate_respiration(duration_s=90, fs=50, rate_bpm=14, rate_sd_bpm=0, vt_l=0.50, vt_cv=0, sigh_times_s=(25,), sigh_scale=2.2, noise_level=0, preset="quiet_rest", seed=1)
fast_fixed = simulate_respiration(duration_s=90, fs=50, rate_bpm=17, rate_sd_bpm=0, vt_l=0.50, vt_cv=0, noise_level=0, preset="quiet_rest", seed=1)
fast_shallow = simulate_respiration(duration_s=90, fs=50, rate_bpm=17, rate_sd_bpm=0, vt_l=0.43, vt_cv=0, noise_level=0, preset="quiet_rest", seed=1)

g_base = simulate_two_pool_co2(base["flow_l_s"], 50)
g_sigh = simulate_two_pool_co2(sigh["flow_l_s"], 50, vco2_l_min=g_base["vco2_l_min"])
g_ff = simulate_two_pool_co2(fast_fixed["flow_l_s"], 50, vco2_l_min=g_base["vco2_l_min"])
g_fs = simulate_two_pool_co2(fast_shallow["flow_l_s"], 50, vco2_l_min=g_base["vco2_l_min"])

fig, axes = plt.subplots(1, 2, figsize=(9.8, 3.2))
axes[0].plot(g_sigh["time_s"], g_sigh["paco2_mmhg"] - g_base["paco2_mmhg"], color=TEAL, lw=1.6, label="ΔPaCO₂ (mmHg)")
axes[0].plot(g_sigh["time_s"], g_sigh["bold_co2_pct"] - g_base["bold_co2_pct"], color=ORANGE, lw=1.6, ls="--", label="ΔBOLD (%)")
axes[0].axvline(25, color="#999", ls=":", lw=0.9)
axes[0].set(xlabel="Time (s)", title="Sigh at 25 s: fast CO₂ dip, delayed BOLD trough")
axes[0].legend(frameon=False, fontsize=8)

axes[1].plot(g_ff["time_s"], g_ff["paco2_mmhg"], color=ORANGE, lw=1.6, label="17 bpm, fixed 0.50 L")
axes[1].plot(g_fs["time_s"], g_fs["paco2_mmhg"], color=TEAL, lw=1.6, label="17 bpm, shallower 0.43 L")
axes[1].axhline(40.0, color="#999", ls=":", lw=0.9)
axes[1].set(xlabel="Time (s)", ylabel="PaCO₂ (mmHg)", title="Faster + shallower breathing preserves alveolar CO₂")
axes[1].legend(frameon=False, fontsize=8)
fig.tight_layout()
plt.show()
```

## References

- 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
- Schumann, A., & Bär, K.-J. (2022). Autonomic aging — A dataset to quantify changes of cardiovascular autonomic function during healthy aging. *Scientific Data*, 9, 95. https://doi.org/10.1038/s41597-022-01202-y
