---
title: "Recovering breathing from fMRI and repairing clipped belts with neuroresp"
subtitle: "Sub-TR extraction, slow-TR aliasing, and belt-MRI fusion"
author: "Shane Lindsay"
format:
  html:
    toc: true
    code-fold: false
    theme: cosmo
    embed-resources: true
execute:
  warning: false
  message: false
jupyter: python3
---

This walkthrough covers recovering breathing directly from raw 4D fMRI images and combining those breaths with a clipped scanner belt from the same scan.

Every breath changes the amount of air in the lungs and shifts the magnetic field at the head, moving echo-planar images back and forth along the phase-encoding axis (Raj et al., 2001; Power et al., 2019). Standard motion correction estimates one shift per volume (`1 / TR`). When `TR` is 1.4 to 2.0 s, that volume sampling rate falls below twice the breathing frequency for faster breathers, so the respiratory peak folds down into lower frequencies (aliasing). Aligning slice groups at their native acquisition times samples the same field shift multiple times per TR (Hocke & Frederick, 2021), including across odd and even passes in legacy single-band scans.

We start with a simulated recording to inspect aliasing directly, then run `neuroresp` on a 56 MB open-access single-band resting fMRI scan (`TR = 2.0 s`) from OpenNeuro `ds003974` where the participant breathes above the volume Nyquist limit and the simultaneous 12-bit belt clips repeatedly at 4095.

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

from neuroresp import clean_belt
from phrenic import simulate_respiration
from neuroresp.backends import run_extraction
from neuroresp.breaths import segment_breaths, summarize_respiration
from neuroresp.fuse import clipped_cycles, fuse_cycles, summarize_fused
from neuroresp.qc import compute_qc
from neuroresp.signal import process_extraction

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

## 1. Slow-TR aliasing in simulated MRI displacement

At `TR = 2.0 s`, once-per-volume sampling (`0.5 Hz`) has a Nyquist limit of `0.25 Hz`, or 15 breaths/min. Any breathing faster than 15 breaths/min folds back below 15 breaths/min. Here we simulate regular breathing at 24 breaths/min (`0.40 Hz`) sampled both once per 2 s volume and at 8 slice-group shots per TR (`4 Hz`).

```{python}
sim = simulate_respiration(
    duration_s=120.0,
    rate_bpm=24.0,
    rate_sd_bpm=0.0,
    vt_cv=0.0,
    mri_tr_s=2.0,
    mri_shots_per_tr=8,
    noise_level=0.005,
    seed=0,
)

f_vol, p_vol = periodogram(sim["mri_vol_pe_mm"] - sim["mri_vol_pe_mm"].mean(), fs=0.5)
f_sub, p_sub = periodogram(sim["mri_subtr_pe_mm"] - sim["mri_subtr_pe_mm"].mean(), fs=4.0)

fig, axes = plt.subplots(1, 2, figsize=(10.5, 3.4), constrained_layout=True)

w_sub = sim["mri_subtr_time_s"] <= 20.0
w_vol = sim["mri_vol_time_s"] <= 20.0
axes[0].plot(sim["mri_subtr_time_s"][w_sub], sim["mri_subtr_pe_mm"][w_sub], color=TEAL, lw=1.4, label="Sub-TR shots (4 Hz)")
axes[0].plot(sim["mri_vol_time_s"][w_vol], sim["mri_vol_pe_mm"][w_vol], "o--", color=ORANGE, ms=4, lw=1.0, label="Once per volume (0.5 Hz)")
axes[0].set(xlim=(0, 20), ylim=(-0.05, 0.85), xlabel="Time (s)", ylabel="PE shift (mm)", title="24 breaths/min sampled at TR = 2.0 s")
axes[0].legend(frameon=False, loc="upper right")

axes[1].plot(f_sub * 60, p_sub / p_sub.max(), color=TEAL, lw=1.5, label="Sub-TR shots (peak: 24 bpm)")
axes[1].plot(f_vol * 60, p_vol / p_vol.max(), color=ORANGE, lw=1.5, ls="--", label="Once per volume (aliased: 6 bpm)")
axes[1].axvline(15.0, color=SLATE, lw=0.9, ls=":", label="Volume Nyquist (15 bpm)")
axes[1].set(xlim=(0, 35), ylim=(0, 1.38), xlabel="Frequency (breaths/min)", ylabel="Normalised power", title="Power spectrum")
axes[1].legend(frameon=False, loc="upper right", fontsize=8.5)
plt.show()
```

As can be seen in the right-hand panel, the once-per-volume trace places a clean peak at 6 breaths/min (`30 - 24`), whereas sub-TR sampling preserves the true 24 breaths/min peak.

## 2. Sub-TR extraction on real single-band fMRI

Next we use a real 5-minute resting scan (`sub-01`) from the Reading Brain L1 dataset on OpenNeuro (`ds003974`, CC0 licence; Li & Clariana, 2019; Follmer et al., 2018). The scan is a legacy single-band EPI (`TR = 2.0 s`, 34 interleaved slices, 150 volumes, 56 MB) paired with a 50 Hz respiratory belt. The helper below checks for a local copy first and otherwise downloads the three BIDS files from OpenNeuro S3 into a temporary cache folder.

```{python}
LOCAL_ROOT = Path.home() / "projects/brain-body-cognition-data/reading_brain_l1/raw"
CACHE_ROOT = Path("/tmp/neuroresp_tutorial_ds003974")
S3_BASE = "https://s3.amazonaws.com/openneuro.org/ds003974"

FILES = [
    "dataset_description.json",
    "task-rest_bold.json",
    "sub-01/func/sub-01_task-rest_acq-singleband_bold.nii.gz",
    "sub-01/func/sub-01_task-rest_acq-singleband_physio.tsv",
]

if (LOCAL_ROOT / FILES[2]).is_file():
    data_root = LOCAL_ROOT
else:
    data_root = CACHE_ROOT
    for rel in FILES:
        dest = data_root / rel
        if not dest.is_file():
            dest.parent.mkdir(parents=True, exist_ok=True)
            urllib.request.urlretrieve(f"{S3_BASE}/{rel}", dest)

bold_path = data_root / FILES[2]
phys_path = data_root / FILES[3]
print("Using:", bold_path)
```

We run `run_extraction()` with `mode="auto"` and `whole_volume=True` so we get both the sub-TR trace and the standard once-per-volume motion trace from the same run. `neuroresp` reads `SliceTiming` from the inherited root `task-rest_bold.json`, detects two interleaved passes (`odd` and `even` slices), and selects `interleaved_2pass` (1 Hz effective sampling, raising the Nyquist limit from 15 to 30 breaths/min).

```{python}
extraction = run_extraction(bold_path, mode="auto", whole_volume=True, jobs=4)
resp_mri = process_extraction(extraction)
resp_mri.qc.update(compute_qc(resp_mri, extraction))

acq = extraction.acquisition
pd.Series({
    "mode": acq.mode,
    "tr_s": acq.tr_s,
    "n_frames": acq.n_frames,
    "n_slices": acq.n_slices,
    "multiband_factor": acq.multiband_factor,
    "pass_offsets_s": tuple(round(x, 3) for x in acq.offsets_s),
    "dominant_rate_bpm": round(resp_mri.qc["dominant_rate_bpm"], 2),
    "fraction_power_above_volume_nyquist": round(resp_mri.qc["fraction_power_above_volume_nyquist"], 3),
    "coverage_frac": resp_mri.qc["coverage_frac"],
    "qc_status": resp_mri.qc["status"],
})
```

Over 70% of the respiratory-band power in this scan sits above the 15 breaths/min volume Nyquist limit (`dominant_rate_bpm = 20.63`). Notice that `qc_status` is `warn` because 1 Hz two-pass sampling slightly trims the top of the 0.50 Hz band (`0.10-0.475 Hz`) and single-band SNR is lower than fast multiband; checking the spectrum against the simultaneous 50 Hz belt shows how well it tracks.

## 3. Comparing whole-volume motion, 2-pass MRI, and the 50 Hz belt

The physio file contains three columns (scanner trigger, pulse oximetry, and the 12-bit respiratory belt in column 2, sampled at 50 Hz). We clean the belt with its known 12-bit rail limits (`0` and `4095`), then compare the spectra and a 60-second window of the raw belt against the 2-pass MRI trace.

```{python}
phys = pd.read_csv(phys_path, sep="\t", header=None)
raw_belt = phys.iloc[:, 2].to_numpy(float)
t_belt = np.arange(len(raw_belt)) / 50.0

resp_belt, breaths_belt, summary_belt, masks_belt = clean_belt(
    raw_belt, fs=50.0, lower_rail=0.0, upper_rail=4095.0
)

wv_pe = extraction.whole_volume["pe_mm"].to_numpy(float)
wv_pe = wv_pe - np.nanmean(wv_pe)
f_wv, p_wv = periodogram(wv_pe, fs=1.0 / acq.tr_s)
f_mri, p_mri = periodogram(resp_mri.raw_pe_mm - np.nanmean(resp_mri.raw_pe_mm), fs=resp_mri.sampling_rate_hz)
f_b, p_b = periodogram(raw_belt - np.mean(raw_belt), fs=50.0)

band_wv = (f_wv >= 0.05) & (f_wv <= 0.25)
wv_peak_bpm = float(f_wv[band_wv][np.argmax(p_wv[band_wv])] * 60)

belt_on_mri = np.interp(resp_mri.time_s, resp_belt.time_s, resp_belt.respiration)
valid = np.isfinite(resp_mri.respiration) & np.isfinite(belt_on_mri)
r_mri_belt = float(np.corrcoef(resp_mri.respiration[valid], belt_on_mri[valid])[0, 1])

pd.Series({
    "50 Hz belt median rate (bpm)": round(summary_belt["cycle_rate_median_bpm"], 2),
    "2-pass MRI dominant rate (bpm)": round(resp_mri.qc["dominant_rate_bpm"], 2),
    "Whole-volume MRI peak (bpm, aliased)": round(wv_peak_bpm, 2),
    "2-pass MRI vs belt correlation (r)": round(r_mri_belt, 3),
})
```

The whole-volume trace aliases to 11.2 breaths/min, whereas 2-pass extraction matches the 50 Hz belt closely (20.63 vs. 20.55 breaths/min, waveform `r = 0.65` across the full 5-minute run).

```{python}
fig, axes = plt.subplots(2, 1, figsize=(10.5, 5.8), constrained_layout=True)

def norm_psd(f, p, lo=0.05, hi=0.50):
    m = (f >= lo) & (f <= hi)
    return f[m] * 60, p[m] / p[m].max()

xb, yb = norm_psd(f_b, p_b)
xm, ym = norm_psd(f_mri, p_mri, 0.05, 0.475)
xw, yw = norm_psd(f_wv, p_wv, 0.05, 0.25)
axes[0].plot(xb, yb, color=SLATE, lw=1.4, label="50 Hz belt")
axes[0].plot(xm, ym, color=TEAL, lw=1.5, label="2-pass single-band MRI (1 Hz)")
axes[0].plot(xw, yw, color=ORANGE, lw=1.4, ls="--", label="Whole-volume MRI (0.5 Hz, aliased)")
axes[0].axvline(15.0, color="#64748b", lw=0.9, ls=":", label="Volume Nyquist (15 bpm)")
axes[0].set(xlim=(3, 30), ylim=(0, 1.25), xlabel="Frequency (breaths/min)", ylabel="Normalised power",
            title="ds003974 sub-01: power spectra")
axes[0].legend(frameon=False, ncol=2, loc="upper right", fontsize=8.5)

# 40-second overlay: raw unfiltered 12-bit belt (showing 4095 clipping) vs 2-pass MRI
t0, t1 = 150.0, 190.0
mb = (t_belt >= t0) & (t_belt <= t1)
mm = (resp_mri.time_s >= t0) & (resp_mri.time_s <= t1)
t_fine = np.linspace(t0, t1, 400)
mri_fine = CubicSpline(resp_mri.time_s, resp_mri.respiration)(t_fine)
ax_left = axes[1]
ax_right = ax_left.twinx()
ax_right.spines["top"].set_visible(False)
ax_left.plot(t_belt[mb], raw_belt[mb], color=SLATE, lw=1.1, label="Raw 50 Hz belt (ADC counts)")
ax_left.axhline(4095, color="#94a3b8", lw=0.8, ls=":")
ax_left.set(xlim=(t0, t1), ylim=(-100, 5100), xlabel="Time (s)", ylabel="Raw belt (ADC counts)",
            title="Raw 12-bit belt clipping at 4095 alongside 2-pass fMRI displacement")
ax_right.plot(t_fine, mri_fine, color=ORANGE, lw=1.4, label="2-pass fMRI (1 Hz, spline display)")
ax_right.scatter(resp_mri.time_s[mm], resp_mri.respiration[mm], color=ORANGE, s=14, zorder=3)
ax_right.set_ylabel("2-pass fMRI (mm)", color=ORANGE)
ax_right.tick_params(axis="y", colors=ORANGE)
h1, l1 = ax_left.get_legend_handles_labels()
h2, l2 = ax_right.get_legend_handles_labels()
ax_left.legend(h1 + h2, l1 + l2, frameon=False, loc="upper right", ncol=2, fontsize=8.5)
plt.show()
```

In the bottom panel, the raw belt repeatedly flattens at the 4095 digital ceiling across normal and deeper breaths, while the 2-pass fMRI trace continues tracking the breath cycles cleanly.

## 4. Repairing the clipped belt with fMRI (`fuse_cycles`)

Inspecting `summary_belt` confirms how severe the clipping is: 76 of the 100 belt breaths touch the 4095 rail (`clip_fraction = 0.089`), so `sigh_rate_censored` is `True` and `sigh_rate_per_min` is `None`.

We segment complete breaths from the 2-pass MRI trace (`polarity_known="false"` because MRI shift direction depends on phase-encoding polarity) and pass both cycle tables into `fuse_cycles()`. Clean belt cycles are kept, clipped belt cycles and their immediate neighbours are dropped, and complete MRI cycles fill the uncovered scan intervals with a new segment ID at every sensor switch.

```{python}
breaths_mri = segment_breaths(
    resp_mri.respiration,
    resp_mri.time_s,
    resp_mri.sampling_rate_hz,
    observed=np.isfinite(resp_mri.raw_pe_mm),
    source="mri",
    polarity_known="false",
)
summary_mri = summarize_respiration(breaths_mri)

sample_bad = masks_belt["rail_clipped"] | masks_belt["loose_belt"] | ~masks_belt["observed"]
bad_belt_cycles = clipped_cycles(breaths_belt, sample_bad, fs=50.0, start_time=0.0)
scan_window = (0.0, acq.n_frames * acq.tr_s)

fused = fuse_cycles(breaths_belt, breaths_mri, belt_bad=bad_belt_cycles, window=scan_window)
summary_fused = summarize_fused(
    fused,
    belt_clip_fraction=summary_belt["clip_fraction"],
    window=scan_window,
    belt_coverage_frac=summary_belt["coverage_frac"],
    mri_coverage_frac=resp_mri.qc["coverage_frac"],
    belt_sigh_censored=summary_belt["sigh_rate_censored"],
)

pd.DataFrame({
    "Belt only": {
        "n_breaths": summary_belt["n_breaths"],
        "n_clipped_cycles": summary_belt["n_clipped_cycles"],
        "rate_median_bpm": summary_belt["cycle_rate_median_bpm"],
        "depth_valid": summary_belt["depth_valid"],
        "sigh_rate_censored": summary_belt["sigh_rate_censored"],
    },
    "MRI 2-pass only": {
        "n_breaths": summary_mri["n_breaths"],
        "n_clipped_cycles": 0,
        "rate_median_bpm": summary_mri["cycle_rate_median_bpm"],
        "depth_valid": summary_mri["depth_valid"],
        "sigh_rate_censored": summary_mri["sigh_rate_censored"],
    },
    "Fused (belt + MRI)": {
        "n_breaths": summary_fused["n_breaths"],
        "n_clipped_cycles": 0,
        "rate_median_bpm": summary_fused["cycle_rate_median_bpm"],
        "depth_valid": summary_fused["depth_valid"],
        "sigh_rate_censored": summary_fused["sigh_rate_censored"],
    },
})
```

Fusion retains 93 complete cycles across 5 uninterrupted segments (`fused_coverage_frac = 0.951`), with 6.5% coming from unclipped belt intervals and 93.5% filled by MRI cycles. Because belt and MRI units do not mix and belt clipping occurred, `depth_valid` stays `False` and `sigh_rate_censored` stays `True`, while timing and rate summaries remain intact. Because two-pass single-band sampling provides one pass per second at `TR = 2.0 s`, individual MRI cycle durations fall on 1-second steps (15, 20, or 30 breaths/min), whereas multiband scans sample 8 to 20 times per second.

```{python}
fig, ax = plt.subplots(figsize=(10.5, 2.8), constrained_layout=True)
for src, colour, label in (("belt", TEAL, "Clean belt cycles"), ("mri", ORANGE, "MRI-rescued cycles")):
    sub = fused.loc[fused["source"] == src]
    ax.scatter((sub["start_s"] + sub["end_s"]) / 2, sub["inst_rate_bpm"], color=colour, s=18, label=label)
ax.set(xlim=(0, 300), ylim=(8, 35), xlabel="Scan time (s)", ylabel="Instantaneous rate (bpm)",
       title="Fused cycle timeline across the 5-minute scan (95.1% temporal-union coverage)")
ax.legend(frameon=False, loc="upper right", ncol=2)
plt.show()
```

From the command line, the same three-step workflow is:

```sh
neuroresp extract sub-01_task-rest_acq-singleband_bold.nii.gz --out mri-rest
neuroresp belt sub-01_task-rest_acq-singleband_physio.tsv --fs 50 --column 2 --lower-rail 0 --upper-rail 4095 --out belt-rest
neuroresp fuse belt-rest mri-rest --out fused-rest
```

## 5. Summary

- Check `fraction_power_above_volume_nyquist` whenever `TR` is 1.4 s or longer; standard volume motion aliases breathing above `30 / TR` breaths/min.
- `neuroresp extract` uses raw, unrealigned 4D EPI and BIDS `SliceTiming` to recover multiband slice stacks or two-pass interleaved single-band scans without external training data.
- MRI phase-encoding direction determines the sign of `pe_mm`, so standalone MRI traces give timing and rate (`polarity_known = false`) rather than absolute inhalation direction.
- `neuroresp fuse` replaces clipped or loose belt stretches with MRI cycles from the same scan while breaking segments at sensor switches and keeping mixed-unit depth and censored sigh rates explicit.

## References

- Follmer, J., Fang, S., Clariana, R., Meyer, B., & Li, P. (2018). What predicts adult readers' understanding of STEM texts? *Reading and Writing*, 31, 185-214. https://doi.org/10.1007/s11145-017-9781-x
- Hocke, L. M., & Frederick, B. D. (2021). Estimating cardiac and respiratory waveforms from multiband fMRI data using slice-sorted registration. *Magnetic Resonance in Medicine*, 85(1), 309-315. https://doi.org/10.1002/mrm.28416
- Li, P., & Clariana, R. (2019). Reading comprehension in L1 and L2: An integrative approach. *Journal of Neurolinguistics*, 50, 94-105. https://doi.org/10.1016/j.jneuroling.2018.03.005 *(OpenNeuro ds003974: https://doi.org/10.18112/openneuro.ds003974.v3.0.0)*
- Power, J. D., Lynch, C. J., Silver, B. M., Dubin, M. J., Martin, A., & Jones, R. M. (2019). Distinctions among real and apparent respiratory motions in human fMRI data. *NeuroImage*, 201, 116041. https://doi.org/10.1016/j.neuroimage.2019.116041
- Raj, D., Anderson, A. W., & Gore, J. C. (2001). Respiratory effects in human functional magnetic resonance imaging due to bulk susceptibility changes. *Physics in Medicine and Biology*, 46(12), 3331-3340. https://doi.org/10.1088/0031-9155/46/12/318
