---
title: "Denoising fMRI and decensoring head motion with neuroresp"
subtitle: "Multiband Echo-1 extraction, post-tedana orthogonalisation, and framewise displacement"
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 the fMRI denoising and motion tools in `neuroresp`: extracting a 9 Hz breathing trace from the first echo of a multiband multi-echo scan, building volume-timed respiratory confounds, projecting motion and respiratory regressors orthogonal to rejected `tedana` ICA components, and removing respiratory pseudomotion from framewise displacement.

Two practical problems come up repeatedly when cleaning fMRI data. First, multi-echo ICA (`tedana`) removes focal motion cleanly but leaves fast and slow respiratory T2* variance inside accepted neural components (Power et al., 2018; DuPre et al., 2021). Second, regressing new nuisance columns out of a `tedana`-cleaned image by ordinary least squares reintroduces variance from components `tedana` already removed whenever the new regressors correlate with rejected components (Lindquist et al., 2019). Extracting breathing from the nearly BOLD-free first echo (`TE = 10.8 ms`) and projecting motion and respiratory confounds jointly orthogonal to the rejected ICA subspace avoids both issues.

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

from neuroresp.backends import run_extraction
from neuroresp.denoise import build_design, expand_motion_24, orthogonalise_matrix
from neuroresp.io import load_resp_csv, write_extraction_outputs
from neuroresp.motion import decensor
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. Multiband Echo-1 extraction on open multi-echo fMRI

We use a real 5-echo multiband scan (`sub-01`, `run-1`, `TR = 2.0 s`, `MB = 4`, `TE = 10.8 ms`) from OpenNeuro `ds004662` (CC0 licence; Reddy et al., 2023), paired with 20 Hz direct nasal CO2. The code downloads Echo 1 (175 MB) and its JSON/physio sidecars from OpenNeuro S3 into a temporary folder and caches the extracted CSV so re-runs are immediate (first extraction takes about 2 to 3 minutes on a laptop CPU).

```{python}
CACHE = Path("/tmp/neuroresp_tutorial_ds004662")
S3_BASE = "https://s3.amazonaws.com/openneuro.org/ds004662"
FILES = [
    "dataset_description.json",
    "sub-01/func/sub-01_task-handgrasp_run-1_echo-1_bold.json",
    "sub-01/func/sub-01_task-handgrasp_run-1_echo-1_bold.nii.gz",
    "sub-01/func/sub-01_task-handgrasp_run-1_physio.json",
    "sub-01/func/sub-01_task-handgrasp_run-1_physio.tsv.gz",
]

for rel in FILES:
    dest = CACHE / rel
    if not dest.is_file():
        dest.parent.mkdir(parents=True, exist_ok=True)
        urllib.request.urlretrieve(f"{S3_BASE}/{rel}", dest)

bold_path = CACHE / FILES[2]
phys_path = CACHE / FILES[4]
out_dir = CACHE / "extract_out"
if (out_dir / "respiration.csv").is_file() and (out_dir / "whole_volume.csv").is_file():
    resp_e1 = load_resp_csv(out_dir / "respiration.csv")
    wv_df = pd.read_csv(out_dir / "whole_volume.csv")
    meta_e1 = pd.read_json(out_dir / "metadata.json", typ="series")
    qc_e1 = meta_e1["qc"]
    tr_s = float(meta_e1["acquisition"]["tr_s"])
    n_frames = int(meta_e1["acquisition"]["n_frames"])
else:
    ext = run_extraction(bold_path, mode="auto", whole_volume=True, jobs=4)
    resp_e1 = process_extraction(ext)
    resp_e1.qc.update(compute_qc(resp_e1, ext))
    write_extraction_outputs(out_dir, ext, resp_e1, "sub-01_task-handgrasp_run-1")
    wv_df = ext.whole_volume
    qc_e1 = resp_e1.qc
    tr_s = ext.acquisition.tr_s
    n_frames = ext.acquisition.n_frames

pd.Series({
    "sampling_rate_hz": resp_e1.sampling_rate_hz,
    "tr_s": tr_s,
    "n_frames": n_frames,
    "dominant_rate_bpm": round(qc_e1["dominant_rate_bpm"], 2),
    "spectral_snr_db": round(qc_e1["spectral_snr_db"], 2),
    "fraction_power_above_volume_nyquist": round(qc_e1["fraction_power_above_volume_nyquist"], 3),
    "qc_status": qc_e1["status"],
})
```

Below we line up the 9 Hz Echo-1 trace and the once-per-volume trace against simultaneous nasal CO2 (allowing for the ~7.4 s gas-line transport delay) to see how multiband slice stacking resolves fast breathing at `TR = 2.0 s`.

```{python}
phys = pd.read_csv(phys_path, sep="\t", header=None, names=["trigger", "CO2", "right_grip", "left_grip"])
t_co2 = np.arange(len(phys)) / 20.0
co2_bp = sosfiltfilt(butter(4, (0.10, 0.50), btype="bandpass", fs=20.0, output="sos"),
                     phys["CO2"].to_numpy(float) - phys["CO2"].mean())

best_r, best_lag = 0.0, 0.0
for lag in np.arange(0.0, 12.01, 0.1):
    c_i = np.interp(resp_e1.time_s + lag, t_co2, co2_bp)
    v = np.isfinite(resp_e1.respiration) & (resp_e1.time_s + lag <= t_co2[-1]) & (resp_e1.time_s >= 10)
    r_val = float(np.corrcoef(resp_e1.respiration[v], c_i[v])[0, 1])
    if abs(r_val) > abs(best_r):
        best_r, best_lag = r_val, lag

sign = 1.0 if best_r >= 0 else -1.0
wv_t = wv_df["time_s"].to_numpy(float)
wv_pe = wv_df["pe_mm"].to_numpy(float) - wv_df["pe_mm"].mean()
c_wv = np.interp(wv_t + best_lag, t_co2, co2_bp)
v_wv = (wv_t + best_lag <= t_co2[-1]) & (wv_t >= 10)
r_wv = abs(float(np.corrcoef(wv_pe[v_wv], c_wv[v_wv])[0, 1]))

def zscore(x):
    return (x - np.nanmean(x)) / np.nanstd(x)

t0, t1 = 120.0, 180.0
m_e1 = (resp_e1.time_s >= t0) & (resp_e1.time_s <= t1)
m_wv = (wv_t >= t0) & (wv_t <= t1)
co2_aligned = np.interp(resp_e1.time_s[m_e1] + best_lag, t_co2, co2_bp)

fig, ax = plt.subplots(figsize=(10.5, 3.4), constrained_layout=True)
ax.plot(resp_e1.time_s[m_e1], zscore(co2_aligned), color=TEAL, lw=1.4, label=f"Nasal CO2 (lag-aligned {best_lag:.1f} s)")
ax.plot(resp_e1.time_s[m_e1], zscore(sign * resp_e1.respiration[m_e1]), color=ORANGE, lw=1.4, label=f"Echo-1 slice stack (9 Hz, |r| = {abs(best_r):.2f})")
ax.plot(wv_t[m_wv], zscore(sign * wv_pe[m_wv]), "--", color="#94a3b8", lw=1.1, label=f"Whole-volume Echo 1 (0.5 Hz, |r| = {r_wv:.2f})")
ax.set(xlim=(t0, t1), ylim=(-3.0, 3.6), xlabel="Scan time (s)", ylabel="z-score",
       title="ds004662 sub-01: 9 Hz Echo-1 slice stacking vs. direct nasal CO2")
ax.legend(frameon=False, ncol=3, loc="upper right", fontsize=8.5)
plt.show()
```

With 9 Hz multiband sampling, Echo 1 tracks individual breaths closely (`|r| = 0.87`) across the 2.0 s TR scan, whereas whole-volume motion (`|r| = 0.40`) misses peaks whenever breathing exceeds 15 breaths/min.

## 2. Building volume-timed confounds and honouring `StartTime`

`build_design()` builds second-order Glover rank-phase RETROICOR harmonics (`resp_sin1`, `resp_cos1`, `resp_sin2`, `resp_cos2`) together with the slow respiratory variation regressor (`resp_rv_rrf` and its temporal derivative; Birn et al., 2008; Chang & Glover, 2009). In midpoint mode, it checks `volume_offset_s`, then the target BOLD sidecar's `StartTime` (such as `0.0` or `0.75` s in `fMRIPrep` derivatives), and defaults to `TR / 2` only when neither is present.

```{python}
design = build_design(resp_e1, tr_s=tr_s, n_volumes=n_frames, include_slow=("rv",), sidecar_start_time_s=0.0)
print("Timing source:", design.metadata["TimingSource"], "| offset:", design.metadata["VolumeOffsetSec"], "s")
design.confounds.head().round(3)
```

A wrong volume offset leaves respiratory variance behind whenever breathing rate varies during a scan. On a synthetic BOLD voxel built from the real Echo-1 trace at `StartTime = 0.0 s`, a design built at `TR / 2` (`1.0 s`) leaves substantial variance behind, whereas the true `StartTime` removes it completely.

```{python}
d_true = build_design(resp_e1, tr_s=tr_s, n_volumes=n_frames, include_slow=(), sidecar_start_time_s=0.0)
d_wrong = build_design(resp_e1, tr_s=tr_s, n_volumes=n_frames, include_slow=(), sidecar_start_time_s=1.0)

y = 100.0 + 2.5 * d_true.confounds["resp_sin1"].to_numpy() + 1.5 * d_true.confounds["resp_cos1"].to_numpy()

def residual_fraction(y_vec, X_df):
    X = np.column_stack([np.ones(len(y_vec)), X_df.to_numpy()])
    beta, *_ = np.linalg.lstsq(X, y_vec, rcond=None)
    resid = y_vec - X @ beta
    return float(resid.var() / y_vec.var())

pd.Series({
    "Residual variance with mismatched TR/2 offset": round(residual_fraction(y, d_wrong.confounds), 4),
    "Residual variance with true StartTime = 0.0 s": round(residual_fraction(y, d_true.confounds), 12),
})
```

## 3. Joint orthogonalisation against rejected `tedana` components

When denoising an image that `tedana` has already cleaned, ordinary regression with motion and Echo-1 confounds can project variance from rejected ICA components back into the signal (Lindquist et al., 2019). Here we take the real 6 Echo-1 confound columns plus 24 expanded motion columns (`30` columns total), construct realistic rejected `tedana` components that share variance with motion and breathing, and compare naive regression against `orthogonalise_matrix()`.

```{python}
rng = np.random.default_rng(7)
# Six simulated rigid motion traces partially coupled to the real Echo-1 breathing trace
breath_vol = design.confounds["resp_sin1"].to_numpy()
raw_m6 = rng.normal(0, 0.05, size=(n_frames, 6))
raw_m6[:, 1] += 0.25 * breath_vol
motion_24 = expand_motion_24(raw_m6)
X_raw = np.column_stack([motion_24, design.confounds.to_numpy()])

# Five rejected tedana ICA components sharing motion/respiratory variance
rejected = np.column_stack([
    raw_m6[:, 1] + rng.normal(0, 0.05, n_frames),
    raw_m6[:, 3] + rng.normal(0, 0.05, n_frames),
    0.6 * breath_vol + rng.normal(0, 0.2, n_frames),
    rng.normal(0, 1.0, (n_frames, 2)),
])

# Simulate a tedana-cleaned voxel: already orthogonal to rejected components, but still containing surviving respiratory BOLD
q_rej, _ = np.linalg.qr(rejected - rejected.mean(axis=0))
neural = rng.normal(0, 1.0, n_frames)
resp_leak = 1.2 * design.confounds["resp_rv_rrf"].to_numpy() + 0.8 * design.confounds["resp_cos1"].to_numpy()
y_tedana = neural + resp_leak
y_tedana = y_tedana - y_tedana.mean()
y_tedana = y_tedana - q_rej @ (q_rej.T @ y_tedana)

def regress_and_check(y_in, X_mat):
    X_c = X_mat - X_mat.mean(axis=0)
    beta, *_ = np.linalg.lstsq(X_c, y_in, rcond=None)
    y_clean = y_in - X_c @ beta
    reintroduced_var = float(np.sum((q_rej.T @ y_clean) ** 2) / np.sum(y_in ** 2))
    return reintroduced_var

X_ortho = orthogonalise_matrix(X_raw, rejected)
pd.Series({
    "Rejected ICA variance before post-tedana cleanup": round(float(np.sum((q_rej.T @ y_tedana) ** 2) / np.sum(y_tedana ** 2)), 15),
    "Rejected ICA variance reintroduced by naive regression": round(regress_and_check(y_tedana, X_raw), 4),
    "Rejected ICA variance after orthogonalise_matrix()": round(regress_and_check(y_tedana, X_ortho), 15),
})
```

Naive regression reintroduces rejected ICA variance into a voxel that `tedana` had already cleaned to zero, whereas jointly orthogonalising all 30 motion and Echo-1 columns keeps rejected-component overlap at numerical zero.

## 4. Stripping respiratory shifts from framewise displacement (`decensor`)

On short-TR scans (`TR <= 0.8 s`, such as HCP 3T at `0.72 s`, which encodes LR/RL along column 0), respiratory B0 shifts show up directly inside the phase-encoding motion parameter and inflate framewise displacement (FD), causing heavy-breathing participants to lose frames unnecessarily (Power et al., 2019; Fair et al., 2020). For task or non-ICA pipelines where non-PE movement matters, filter only the PE axis (`method="pe_bandstop"`) or remove a reference-locked `field` fit; for ICA-denoised resting connectivity, six-axis `lowpass` (0.10 Hz) is effective when paired with a rescaled adjusted threshold (roughly 0.02 to 0.03 mm at TR = 0.72 s) and `raw_threshold_mm=0.20`. Here we construct a 160-volume fast-TR motion table (`TR = 0.72 s`) with continuous respiratory pseudomotion along the PE axis (column 0) plus one genuine 0.65 mm non-PE head jump at frame 80 (column 1), and apply `decensor(..., method="pe_bandstop", pe_axis=0)`.

```{python}
tr_fast = 0.72
n_fast = 160
t_fast = (np.arange(n_fast) + 0.5) * tr_fast
rng_m = np.random.default_rng(12)
m6 = rng_m.normal(0, 0.015, size=(n_fast, 6))
# Continuous respiratory pseudomotion (~18 bpm = 0.30 Hz) along the HCP 3T PE axis (col 0)
m6[:, 0] += 0.22 * np.sin(2 * np.pi * 0.30 * t_fast)
# One genuine non-PE head jump at frame 80 (col 1)
m6[80:, 1] += 0.65

fd_res = decensor(m6, tr_s=tr_fast, method="pe_bandstop", pe_axis=0, band_hz=(0.20, 0.45), threshold_mm=0.20)
f_idx = fd_res["frame"]
t_fd = (f_idx + 0.5) * tr_fast

fig, ax = plt.subplots(figsize=(10.5, 3.2), constrained_layout=True)
ax.plot(t_fd, fd_res["raw_fd_mm"], color="#94a3b8", lw=1.1, label=f"Raw FD ({fd_res['raw_censored'].sum()} frames > 0.2 mm)")
ax.plot(t_fd, fd_res["adjusted_fd_mm"], color=TEAL, lw=1.4, label=f"PE-bandstop FD ({fd_res['adjusted_censored'].sum()} frames > 0.2 mm)")
ax.axhline(0.20, color=ORANGE, lw=1.0, ls="--", label="0.20 mm censor threshold")
ax.set(xlim=(t_fd[0], t_fd[-1]), ylim=(0, 0.95), xlabel="Scan time (s)", ylabel="Framewise displacement (mm)",
       title="Removing respiratory pseudomotion from FD while retaining real head movement")
ax.legend(frameon=False, loc="upper right", ncol=3, fontsize=8.5)
plt.show()
```

PE-only bandstop filtering drops the respiratory ripples cleanly below the 0.20 mm censoring threshold while leaving the genuine 0.65 mm non-PE head jump completely untouched and flagged.

From the command line, the denoising and FD decensoring workflows are:

```sh
# Extract Echo-1 respiration
neuroresp extract sub-01_task-handgrasp_run-1_echo-1_bold.nii.gz --out echo1-rest

# Post-tedana cleanup with joint 24-motion + Echo-1 orthogonalisation
neuroresp denoise echo1-rest/respiration.csv \
  --nifti-in desc-denoised_bold.nii.gz --nifti-out desc-respclean_bold.nii.gz \
  --motion motion.1D --tedana-mixing desc-ICA_mixing.tsv --tedana-metrics desc-tedana_metrics.tsv \
  --out-confounds desc-resp_confounds.tsv

# PE-only bandstop FD decensoring (HCP 3T LR/RL PE is axis 0; task or non-ICA pipelines)
neuroresp motion decensor Movement_Regressors.txt --tr 0.72 --method pe_bandstop --pe-axis 0 --out fd-rest

# Low-pass FD decensoring (ICA-denoised rest, with rescaled threshold vs 0.20 mm raw FD)
neuroresp motion decensor Movement_Regressors.txt --tr 0.72 --method lowpass --threshold-mm 0.025 --raw-threshold-mm 0.20 --out fd-rest-lp
```

## 5. Summary

- On multiband multi-echo scans, Echo 1 (`TE ~ 10-14 ms`) gives a high-rate respiratory trace without circular BOLD weighting.
- Always check that the target BOLD sidecar's `StartTime` (or `--volume-offset`) matches how the preprocessed image was slice-time corrected.
- When cleaning `tedana` outputs, project motion and respiratory columns jointly orthogonal to rejected ICA components rather than running naive sequential regression.
- On short-TR scans, `neuroresp motion decensor` strips respiratory pseudomotion from FD while keeping genuine head jumps censored.

## References

- Birn, R. M., Smith, M. A., Jones, T. B., & Bandettini, P. A. (2008). The respiration response function: The temporal dynamics of fMRI signal fluctuations related to changes in respiration. *NeuroImage*, 40(2), 644-654. https://doi.org/10.1016/j.neuroimage.2007.11.059
- Chang, C., & Glover, G. H. (2009). Relationship between respiration, end-tidal CO2, and BOLD signals in resting-state fMRI. *NeuroImage*, 47(4), 1381-1393. https://doi.org/10.1016/j.neuroimage.2009.04.048
- DuPre, E., Salo, T., Ahmed, Z., et al. (2021). TE-dependent analysis of multi-echo fMRI with tedana. *Journal of Open Source Software*, 6(66), 3669. https://doi.org/10.21105/joss.03669
- Fair, D. A., Miranda-Dominguez, O., Snyder, A. Z., et al. (2020). Correction of respiratory artifacts in MRI head motion estimates. *NeuroImage*, 208, 116400. https://doi.org/10.1016/j.neuroimage.2019.116400
- Glover, G. H., Li, T. Q., & Ress, D. (2000). Image-based method for retrospective correction of physiological motion effects in fMRI: RETROICOR. *Magnetic Resonance in Medicine*, 44(1), 162-167.
- Lindquist, M. A., Geuter, S., Wager, T. D., & Caffo, B. S. (2019). Modular preprocessing pipelines can reintroduce artifacts into fMRI data. *Human Brain Mapping*, 40(8), 2358-2376. https://doi.org/10.1002/hbm.24528
- Power, J. D., Plitt, M., Gotts, S. J., et al. (2018). Ridding fMRI data of motion-related influences: Removal of signals with distinct spatial and physical bases in multiecho data. *PNAS*, 115(9), E2105-E2114.
- Power, J. D., Lynch, C. J., Silver, B. M., et al. (2019). Distinctions among real and apparent respiratory motions in human fMRI data. *NeuroImage*, 201, 116041.
- Reddy, N. A., Zvolanek, K. M., Moia, S., Caballero-Gaudes, C., & Bright, M. G. (2023). Denoising task-correlated head motion from motor-task fMRI data with multi-echo ICA. *bioRxiv*. https://doi.org/10.1101/2023.07.19.549746 *(OpenNeuro ds004662: https://doi.org/10.18112/openneuro.ds004662.v1.1.0)*
