Recovering breathing from ECG and MEG head coils with neuroresp
Shane Lindsay
This walkthrough covers recovering respiration from single-lead chest
ECG in MEG or EEG recordings (respiration_from_ecg) and using
continuous head-localisation coils (cHPI / HLC) in raw MEG.
Heart-rate estimators based solely on respiratory sinus arrhythmia (RSA)
weaken as vagal modulation declines with age. Mechanical chest expansion
still tilts the heart relative to the chest electrodes on every breath
(Moody et al., 1985), so neuroresp derives the 4 Hz respiratory
waveform from beat-by-beat R-wave amplitude and QRS area, combines
spectral evidence from morphology and RSA after two-pass 1/f whitening,
and uses RSA (Yasuma & Hayano, 2004) only to orient inhalation upward
and flag weak sign confidence.
from pathlib import Path
import urllib.request
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy.signal import welch
from neuroresp import clean_belt
from phrenic import simulate_respiration
from neuroresp.breaths import segment_breaths
from neuroresp.meg import respiration_from_ecg
plt.rcParams.update({
"axes.spines.top": False,
"axes.spines.right": False,
"figure.dpi": 140,
})
TEAL = "#086d70"
ORANGE = "#b45125"
SLATE = "#334155"
1. Low-RSA ECG, null-ECG screening, and rate transitions
Before moving to real human ECG, we test three cases with known ground
truth using simulate_respiration():
- Low RSA (
rsa_amp_bpm = 0.5): heart-rate modulation is weak while QRS amplitude still tracks lung expansion (qrs_mod_depth = 0.20). - Null ECG (
rsa_amp_bpm = 0,qrs_mod_depth = 0): no respiratory modulation at all; the physical modulation gate should reject it rather than passing normalised quantisation jitter. - Within-run rate shift (10 to 22 breaths/min): concatenating two 2-minute blocks checks that the slow block is not harmonic-doubled by a single whole-run bandpass filter.
# 1. Low-RSA simulated ECG at 14 bpm
sim_low_rsa = simulate_respiration(duration_s=180.0, rate_bpm=14.0, rate_sd_bpm=0.5,
ecg_fs=500.0, rsa_amp_bpm=0.5, qrs_mod_depth=0.20, seed=1)
res_low_rsa = respiration_from_ecg(sim_low_rsa["ecg"], fs=sim_low_rsa["ecg_fs"])
# 2. Unmodulated null ECG
sim_null = simulate_respiration(duration_s=120.0, rate_bpm=14.0, ecg_fs=500.0,
rsa_amp_bpm=0.0, qrs_mod_depth=0.0, noise_level=0.005, seed=2)
res_null = respiration_from_ecg(sim_null["ecg"], fs=sim_null["ecg_fs"])
# 3. Within-run rate shift: 10 bpm -> 22 bpm
s_slow = simulate_respiration(duration_s=120.0, rate_bpm=10.0, rate_sd_bpm=0.0, vt_cv=0.0, ecg_fs=500.0, seed=3)
s_fast = simulate_respiration(duration_s=120.0, rate_bpm=22.0, rate_sd_bpm=0.0, vt_cv=0.0, ecg_fs=500.0, seed=4)
res_shift = respiration_from_ecg(np.r_[s_slow["ecg"], s_fast["ecg"]], fs=500.0)
t_shift = np.arange(len(res_shift["wave"])) / 4.0
br_shift = segment_breaths(res_shift["wave"], t_shift, 4.0, observed=res_shift["valid"],
source="ecg", polarity_known="approximate")
slow_est = float(np.median(br_shift.loc[(br_shift.start_s > 15) & (br_shift.end_s < 105), "inst_rate_bpm"]))
fast_est = float(np.median(br_shift.loc[(br_shift.start_s > 135) & (br_shift.end_s < 225), "inst_rate_bpm"]))
pd.DataFrame({
"Low RSA (true 14 bpm)": {
"has_respiratory_modulation": res_low_rsa["has_respiratory_modulation"],
"estimated_bpm": round(res_low_rsa["f_resp"] * 60, 2),
"rate_nonstationary": res_low_rsa["rate_nonstationary"],
},
"Null ECG (no modulation)": {
"has_respiratory_modulation": res_null["has_respiratory_modulation"],
"estimated_bpm": None if not res_null["has_respiratory_modulation"] else round(res_null["f_resp"] * 60, 2),
"rate_nonstationary": res_null["rate_nonstationary"],
},
"Rate shift (10 -> 22 bpm)": {
"has_respiratory_modulation": res_shift["has_respiratory_modulation"],
"estimated_bpm": f"{slow_est:.1f} -> {fast_est:.1f}",
"rate_nonstationary": res_shift["rate_nonstationary"],
},
})
The low-RSA recording recovers 14.06 breaths/min, the unmodulated null
trace fails the modulation gate cleanly
(has_respiratory_modulation = False), and the two-block transition
tracks both 10 and 22 breaths/min while flagging
rate_nonstationary = True.
2. Real older-adult ECG against a physical chest belt
Next we load two 15-minute, 1 kHz resting recordings from older adults in the open-access Schumann dataset (ages 68 and 69; Schumann & Bär, 2022), which records single-lead chest ECG simultaneously with a physical respiratory belt. Each file is about 22 MB and downloads directly from Figshare if not already cached locally.
LOCAL_SCH = Path.home() / "projects/brain-body-cognition-data/schumann/raw"
CACHE_SCH = Path("/tmp/neuroresp_tutorial_schumann")
URLS = {
"04_1.txt": "https://ndownloader.figshare.com/files/49365466", # age 68
"12_1.txt": "https://ndownloader.figshare.com/files/49365439", # age 69 (weak RSA)
}
def load_schumann(fname):
local = LOCAL_SCH / fname
if local.is_file():
path = local
else:
path = CACHE_SCH / fname
if not path.is_file():
path.parent.mkdir(parents=True, exist_ok=True)
urllib.request.urlretrieve(URLS[fname], path)
arr = np.loadtxt(path)
return arr[:, 1].astype(float), arr[:, 2].astype(float)
ecg_68, belt_68 = load_schumann("04_1.txt")
ecg_69, belt_69 = load_schumann("12_1.txt")
res_68 = respiration_from_ecg(ecg_68, fs=1000.0)
resp_b68, _, sum_b68, _ = clean_belt(belt_68, fs=1000.0)
res_69 = respiration_from_ecg(ecg_69, fs=1000.0)
resp_b69, _, sum_b69, _ = clean_belt(belt_69, fs=1000.0)
def wave_corr(res_ecg, resp_belt):
t4 = np.arange(len(res_ecg["wave"])) / 4.0
b4 = np.interp(t4, resp_belt.time_s, resp_belt.respiration)
v = res_ecg["valid"] & np.isfinite(res_ecg["wave"]) & np.isfinite(b4)
return float(np.corrcoef(res_ecg["wave"][v], b4[v])[0, 1]), t4, b4
r68, t4_68, b4_68 = wave_corr(res_68, resp_b68)
r69, t4_69, b4_69 = wave_corr(res_69, resp_b69)
pd.DataFrame({
"Subject 04 (age 68, clear polarity)": {
"belt_rate_bpm": round(sum_b68["cycle_rate_median_bpm"], 2),
"ecg_rate_bpm": round(res_68["f_resp"] * 60, 2),
"waveform_r_vs_belt": round(r68, 3),
"polarity_confidence": round(res_68["polarity_confidence"], 3),
"polarity_ambiguous": res_68["polarity_ambiguous"],
},
"Subject 12 (age 69, weak RSA)": {
"belt_rate_bpm": round(sum_b69["cycle_rate_median_bpm"], 2),
"ecg_rate_bpm": round(res_69["f_resp"] * 60, 2),
"waveform_r_vs_belt": round(r69, 3),
"polarity_confidence": round(res_69["polarity_confidence"], 3),
"polarity_ambiguous": res_69["polarity_ambiguous"],
},
})
Comparing these two older adults illustrates both halves of
neuroresp meg. In Subject 04 (age 68), ECG-derived breathing matches
the physical chest belt closely in rate (12.19 vs. 11.63 breaths/min)
and signed waveform (r = +0.79, polarity_confidence = 0.68). In
Subject 12 (age 69), morphology still tracks breathing rate accurately
(8.44 vs. 9.09 breaths/min), while flat RSA triggers
polarity_ambiguous = True (polarity_confidence = 0.018), signalling
that inhalation-versus-exhalation orientation is uncertain even though
rate is usable.
def zscore(x):
return (x - np.nanmean(x)) / np.nanstd(x)
fig, axes = plt.subplots(2, 1, figsize=(10.5, 5.4), constrained_layout=True)
t0, t1 = 60.0, 120.0
m = (t4_68 >= t0) & (t4_68 <= t1)
axes[0].plot(t4_68[m] - t0, zscore(b4_68[m]), color=TEAL, lw=1.4, label="Physical chest belt")
axes[0].plot(t4_68[m] - t0, zscore(res_68["wave"][m]), color=ORANGE, lw=1.4, label=f"ECG-derived breathing (full-run r = {r68:+.2f})")
axes[0].set(xlim=(0, 60), ylim=(-2.8, 3.3), xlabel="Time in 60 s window (s)", ylabel="z-score",
title="Subject 04 (age 68): single-lead ECG recovery vs. physical chest belt")
axes[0].legend(frameon=False, ncol=2, loc="upper right")
b_clean = np.where(np.isfinite(b4_68), b4_68 - np.nanmean(b4_68), 0.0)
w_clean = np.where(np.isfinite(res_68["wave"]), res_68["wave"], 0.0)
f_b, p_b = welch(b_clean, fs=4.0, nperseg=256)
f_e, p_e = welch(w_clean - np.mean(w_clean), fs=4.0, nperseg=256)
mb = (f_b >= 0.05) & (f_b <= 0.50)
me = (f_e >= 0.05) & (f_e <= 0.50)
axes[1].plot(f_b[mb] * 60, p_b[mb] / p_b[mb].max(), color=TEAL, lw=1.5, label="Physical chest belt")
axes[1].plot(f_e[me] * 60, p_e[me] / p_e[me].max(), color=ORANGE, lw=1.5, ls="--", label="ECG-derived breathing")
axes[1].set(xlim=(3, 30), ylim=(0, 1.25), xlabel="Frequency (breaths/min)", ylabel="Normalised power",
title="Respiratory power spectrum (15-minute resting recording)")
axes[1].legend(frameon=False, ncol=2, loc="upper right")
plt.show()

3. Continuous MEG head-coil tracking (--source chpi and --source both)
Raw MEG recordings with continuous head localisation also carry
breathing through small nodding (pitch) and front-to-back (AP) head
movements. neuroresp supports both Elekta/MEGIN .fif recordings with
active cHPI coils and CTF .ds recordings with the nine continuous
HLC fiducial channels, converting both to a common anatomical
head-pose timeline.
Before extracting head-coil motion, neuroresp runs a preflight check
verifying active coil status, carrier power above local spectral
background, and sustained accepted pose coverage. Standalone head-coil
motion has an uncalibrated sign (polarity_known = false); passing
--source both exports both the mechanical head-coil trace and the
electrical ECG trace on the same recording clock, orienting the
head-coil sign approximately when ECG agreement passes its short-lag
correlation gate and writing an overlay_qc.png alignment plot.
# ECG-derived breathing from raw MEG or EEG (requires pip install 'neuroresp[meg]')
neuroresp meg sub-01_task-rest_meg.fif --ecg-ch ECG001 --out derivatives/neuroresp/sub-01/meg
# Continuous head-coil tracking alone (Elekta .fif or CTF .ds)
neuroresp meg sub-01_task-rest_meg.fif --source chpi --chpi-method pitch_ap --out derivatives/neuroresp/sub-01/chpi
# Paired head-coil + ECG extraction with convergent overlay QC
neuroresp meg sub-01_task-rest_meg.fif --source both --out derivatives/neuroresp/sub-01/meg_both
In Python with an already-open MNE Raw object:
from neuroresp.meg import extract_from_raw
result = extract_from_raw("sub-01_task-rest_meg.fif", source="both")
usable_phase = result["phase"][result["valid"]]
4. Summary
- Combine QRS morphology with whitened spectral fusion so ECG respiratory tracking holds up across adult ageing when heart-rate RSA fades.
- Check
has_respiratory_modulation,polarity_ambiguous, andrate_nonstationarybefore using an ECG waveform for breath-phase analyses; average rate often remains valid even when inspiratory polarity is ambiguous. - On pre-MaxFilter Elekta
.fifor CTF.dsMEG recordings with active coils,--source bothprovides an independent mechanical breathing channel alongside ECG.
References
- McNabb, C., Driver, I., Hyde, V., et al. (2025). WAND: A multi-modal dataset integrating advanced MRI, MEG, and TMS for multi-scale brain analysis. Scientific Data. https://doi.org/10.1038/s41597-024-04154-7
- Moody, G. B., Mark, R. G., Zoccola, A., & Mantero, S. (1985). Derivation of respiratory signals from multi-lead ECGs. Computers in Cardiology, 12, 113-116.
- 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
- Yasuma, F., & Hayano, J. (2004). Respiratory sinus arrhythmia: Why does the heartbeat synchronize with respiratory rhythm? Chest, 125(2), 683-690. https://doi.org/10.1378/chest.125.2.683