Usage
neuroresp provides eight CLI subcommands (extract, denoise, belt, airflow, motion, fuse, meg, and batch) together with Python functions for scripts and cluster jobs. See Outputs and Quality Control for column definitions, Scientific Approach for the underlying models, and the sister package phrenic for mechanistic multi-sensor simulation (phrenic simulate outputs plug straight into neuroresp airflow, neuroresp belt, and neuroresp meg).
Extract breathing from raw fMRI
Run neuroresp extract on one raw unrealigned 4D BOLD NIfTI per output folder. During very regular paced breathing, check near_tr_harmonic_lock: a rhythm near k/TR can be distorted by stack centring even when a plausible waveform is returned. Adjacent or root BIDS JSON sidecars are found automatically, and Echo 1 is chosen automatically when given a multi-echo run prefix.
neuroresp extract sub-01_ses-01_task-rest_echo-1_bold.nii.gz \
--out derivatives/neuroresp/sub-01/ses-01/rest \
--backend python2d \
--mode auto \
--reference median \
--skip-initial 5 \
--jobs 4
| Option | Default | Description |
|---|---|---|
--sidecar PATH |
Auto BIDS lookup | Explicit BIDS JSON sidecar path |
--backend {python2d,afni} |
python2d |
Pure Python 2D Gauss-Newton solver or external AFNI 3dvolreg |
--mode {auto,multiband_stack,interleaved_2pass,single_band_2d,whole_volume} |
auto |
Uses multiband_stack when MB ≥ 2, interleaved_2pass on odd/even MB = 1 passes, single_band_2d on other MB = 1 slice timings, and whole_volume without SliceTiming |
--reference {median,frame0} |
median |
Temporal median after --skip-initial frames, or frame 0 |
--skip-initial INT |
5 |
Leading frames omitted from the median reference (kept on the output clock) |
--whole-volume |
False |
Also write whole_volume.csv at the mean slice offset |
--no-plot |
False |
Skip saving qc.png |
--jobs INT |
4 |
Worker threads across slice groups |
Build confounds for fMRIPrep and nilearn
The default --timing midpoint mode outputs one row per retained volume. It uses the target BOLD JSON sidecar’s StartTime when present, otherwise the middle of the TR. Pass --volume-offset SECONDS to override either value (the offset must be within the TR); --sidecar explicitly selects the target JSON. Set --discarded to the number of leading volumes physically removed from the target NIfTI since extraction, leaving it at zero if the target retains all frames. The sidecar records the timing source and the extent of slow-predictor imputation; inspect these when physiology is missing (see Outputs and Quality Control).
neuroresp denoise derivatives/neuroresp/sub-01/ses-01/rest/respiration.csv \
--nifti-in derivatives/fmriprep/sub-01/ses-01/func/sub-01_ses-01_task-rest_space-MNI152NLin2009cAsym_desc-preproc_bold.nii.gz \
--motion derivatives/fmriprep/sub-01/ses-01/func/sub-01_ses-01_task-rest_desc-confounds_timeseries.tsv \
--motion-expansion 24 \
--slow rv \
--out-confounds derivatives/neuroresp/sub-01/ses-01/rest/sub-01_ses-01_task-rest_desc-resp_confounds.tsv
Pass the exported TSV (with any aligned fMRIPrep cosine drift columns) to nilearn. If removing the first five volumes at this stage, trim the image and confounds together:
import pandas as pd
from nilearn.image import clean_img, index_img
confounds = pd.read_csv("sub-01_ses-01_task-rest_desc-resp_confounds.tsv", sep="\t")
bold = index_img(
"sub-01_ses-01_task-rest_space-MNI152NLin2009cAsym_desc-preproc_bold.nii.gz",
slice(5, None),
)
cleaned = clean_img(
bold,
confounds=confounds.iloc[5:],
t_r=1.8,
detrend=True,
standardize="psc",
)
Clean tedana outputs with joint orthogonalisation
Supply desc-ICA_mixing.tsv, desc-tedana_metrics.tsv, and the aligned motion parameters (--motion). With --motion-expansion auto, six rigid parameters expand to 24 columns (parameters, backward first differences with zero in row 0, and squares of both), an existing 24-column table passes through unchanged, and fMRIPrep TSVs select rigid motion columns by name (6, 24, and none are also supported). All 30 motion and Echo-1 columns are projected orthogonal to tedana rejected ICA time courses before regression.
neuroresp denoise derivatives/neuroresp/sub-01/rest/respiration.csv \
--discarded 8 \
--motion motion.1D \
--motion-expansion auto \
--slow rv \
--tedana-mixing derivatives/tedana/sub-01/rest/desc-ICA_mixing.tsv \
--tedana-metrics derivatives/tedana/sub-01/rest/desc-tedana_metrics.tsv \
--nifti-in derivatives/tedana/sub-01/rest/desc-denoised_bold.nii.gz \
--nifti-out derivatives/tedana/sub-01/rest/desc-respclean_bold.nii.gz \
--out-confounds derivatives/tedana/sub-01/rest/desc-resp_confounds.tsv
For native echoes before slice timing interpolation, add --sidecar and --timing slice-exact to sample and regress each native slice at its own SliceTiming offset.
Measure direct airway flow
Use airflow with signed flow from a spirometer or pneumotachograph, or signed pressure from a nasal cannula (positive inspiration by default, or pass --inspiration-negative). BIDS physio sidecars supply the sampling rate, start time, and channel names automatically; for plain CSV or TSV files, pass --fs and pick the airway channel by name or zero-based index with --column.
neuroresp airflow sub-01_task-rest_physio.tsv.gz --column flow --calibrated --out flow-rest
neuroresp airflow cannula.csv --fs 6 --column pressure --sensor nasal_pressure \
--inspiration-negative --out nasal-rest
neuroresp denoise nasal-rest/respiration.csv --tr 2 --n-volumes 120 --out-confounds confounds.tsv
By default (--baseline auto), calibrated linear flow keeps its hardware zero. Uncalibrated flow and nasal pressure use balanced drift removal, choosing a local 60-second offset so inspired and expired volumes average to zero (for nasal pressure, after signed square-root linearisation). You can override this with --baseline none when zero is already known, or --baseline median for explicit rolling-median subtraction, bearing in mind that asymmetric breathing can have a nonzero median even when volumes match.
Before finding landmarks, the extractor builds a 2 Hz guide contour, lightly smooths high-rate nasal pressure so noise near zero does not inflate under the square root, and uses shape-preserving cubic interpolation whenever the native rate is below 60 Hz. Clipping is flagged only against explicit --lower-rail and --upper-rail bounds in input units so quantised peaks and sighs stay intact. Missing samples and sustained off-zero flatlines (4 s or longer) split the recording into separate segments, while genuine near-zero breath holds remain observed.
Add --calibrated when you want absolute tidal volume and minute ventilation. BIDS linear flow in mL/s, L/min, or mL/min is converted to L/s automatically, whereas plain files without unit metadata must already be in L/s. Uncalibrated nasal cannulas still return full relative motor-shape metrics. The exported BIDS respiratory channel stores linearised flow, while respiration.csv stores the integrated lung-volume proxy expected by neuroresp denoise. Pass --no-plot to skip the QC figure. The ventilation summaries distinguish accepted complete-cycle exposure from total observed time, including holds; an additional flow-integral estimate includes partial cycles. Rail loss can remove a breath altogether from the complete-cycle table and censors the sigh rate; see Direct airway outputs. Keep derivatives in a separate directory. The airflow and belt commands reject output paths that would overwrite the input recording or an explicitly supplied sidecar.
from neuroresp import analyse_airflow
result = analyse_airflow(flow_l_s, fs=100, calibrated=True)
breaths = result["breaths"]
median_vt = result["summary"]["vt_median_l"]
Clean belts and motion logs and hybrid runs
Hardware belts
neuroresp belt cleans a BIDS belt recording over a 0.05–1.00 Hz timing band (covering slow breathers down to 3 breaths/min while preserving breath harmonics without filter ringing), flags rail saturation and loose straps, and writes respiration.csv, breaths.tsv, and summary.json. Strap orientation defaults to --polarity-known unknown; pass --polarity-known true when an increasing signal is verified to represent expansion. Because chest-wall belt hysteresis shifts turnarounds relative to true airway zero-flow, belt rise fraction and I:E are withheld by default; pass compute_shape=True and polarity_known="true" to clean_belt in Python if you explicitly want chest-wall rise/fall asymmetry.
neuroresp belt sub-01_task-rest_physio.tsv.gz --out derivatives/neuroresp/sub-01/belt
For calibrated DC-coupled bands with known expansion polarity, --states adds four-state chest-wall segmentation on the un-high-passed displacement contour, separating active expansion and recoil from flat dwells at the top and bottom of each cycle. For paired chest and abdomen RIP bands in matching units, pass --second-column to sum both centred channels over their jointly finite samples (a correlation below −0.2 flags a likely inverted strap).
neuroresp belt rip.csv --fs 100 --column chest --second-column abdomen \
--states --dc-coupled --polarity-known true --out rip-states
Pass --dc-coupled so clipping checks use only explicit --lower-rail and --upper-rail limits (applied to the centred sum for dual bands) rather than flagging genuine top-of-breath holds at empirical extrema. Because loose-strap detection defaults to 4 seconds of low excursion, raise --loose-min-s above your expected hold length in breath-hold studies, or pass 0 to disable loose-strap masking. The state estimator has a 0.3 s minimum flat-run duration and roughly 0.2–0.3 s boundary erosion, even on the 10 Hz state grid; true half-second dwells may be missed. See Chest-wall movement versus airway timing for when belt dwell supports within-person comparisons versus when direct airflow is required. Clipped belt cycles may still contribute timing, but their depths are excluded from summaries and the run’s sigh rate is censored.
from neuroresp import clean_belt, segment_belt_states
resp, breaths, summary, masks = clean_belt(chest, fs=100, dc_coupled=True, states=True, polarity_known="true")
cycles = resp.belt_states.cycles
# Or segment an already quality-masked belt directly.
states = segment_belt_states(chest, fs=100, observed=observed)
In Python, BeltStateSegmentation.signal and cleaned are oriented by BeltStateConfig.polarity (set to -1 for inverted straps), after anti-alias low-pass filtering onto the 10 Hz state grid.
Motion tracking and FD decensoring
The motion subcommands accept --format {auto,afni_1d,hcp,fmriprep,spm,plain_6}. Auto detects named fMRIPrep rigid-body columns (mm, radians), HCP Movement_Regressors.txt (the first six of 12 columns, mm and degrees), indexed AFNI files, and six-column SPM rp_*.txt files (translations in mm followed by rotations in radians). Six-column .1D files are interpreted in AFNI roll, pitch, yaw, superior, left, posterior order; other six-column files default to x, y, z translation followed by x, y, z rotation (mm and degrees). Specify the format explicitly for ambiguous files and use --rotation-units {auto,deg,rad} to override the rotation convention. The loader returns translations in mm followed by rotations in degrees, retaining physical axis signs; --pe-axis is zero-based in translation order. Paired runs must use the same physical axes and signs.
# HCP 3T (TR = 0.72 s) encodes LR/RL along x (--pe-axis 0); AP/PA scans such as HCP 7T use --pe-axis 1.
neuroresp motion track Movement_Regressors.txt --tr 0.72 --pe-axis 0 --out derivatives/neuroresp/sub-01/motion_track
# Task or non-ICA pipelines: filter the phase-encoding axis only so non-PE head movement stays intact.
neuroresp motion decensor Movement_Regressors.txt --tr 0.72 --method pe_bandstop --pe-axis 0 --out derivatives/neuroresp/sub-01/motion_fd
# ICA-denoised resting connectivity: 0.10 Hz low-pass FD with a rescaled threshold against 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 derivatives/neuroresp/sub-01/motion_fd_lp
Choose the decensoring method to match the downstream pipeline. For task fMRI or non-ICA pipelines where non-PE movement matters, use pe_bandstop (passing --pe-axis) or a reference-locked field fit so respiratory filtering leaves non-PE axes untouched. For ICA-denoised resting-state connectivity, six-axis lowpass (0.10 Hz default) works well, but low-pass filtering compresses framewise displacement by roughly an order of magnitude at short TR (for example from a median of 0.153 mm to 0.017 mm at TR = 0.72 s in HCP); lower --threshold-mm accordingly (such as 0.02 to 0.03 mm) and pass --raw-threshold-mm 0.20 to compare against standard 0.20 mm raw censoring. Reference-locked fits (pe, field) trim 10 boundary volumes by default; filter-only methods keep all volumes (--edge 0) so censor masks cover the full run, and passing --edge 10 trims filter boundary transients from evaluation.
Hybrid belt and MRI cycle fusion
Keeps clean belt cycles (excluding cycles touching flagged samples and their immediate neighbours within a bout) and fills uncovered stretches with complete MRI cycles from the same run, starting a new segment at every sensor switch or gap greater than 0.20 s. When source respiration.csv traces exist, neuroresp fuse also writes fused_respiration.csv with a continuous repaired waveform and 5th–95th percentile intervals across clipped or dropped belt stretches. Pass --ecg (a neuroresp meg output directory or respiration CSV) to include ECG alongside belt and MRI B0.
neuroresp fuse derivatives/neuroresp/sub-01/belt derivatives/neuroresp/sub-01/rest \
--ecg derivatives/neuroresp/sub-01/meg \
--out derivatives/neuroresp/sub-01/fused
In Python, call fuse_waveforms directly to repair clipped or dropped belt stretches using MRI B0, ECG, or both together:
from neuroresp import fuse_waveforms
rescued = fuse_waveforms(
belt_time_s, belt_signal, clip_mask,
{"mri": (mri_time_s, mri_pe_mm), "ecg": (ecg_time_s, ecg_wave)},
)
Recover breathing from MEG and EEG
neuroresp meg sub-01_task-rest_meg.fif \
--ecg-ch ECG003 \
--out derivatives/neuroresp/sub-01/meg \
--prefix sub-01_task-rest
Install the MEG extra with python -m pip install "neuroresp[meg]" (or python -m pip install ".[meg]" from a local checkout) to read raw recordings. Use a separate output directory per recording.
--source |
Output |
|---|---|
auto (default) |
Exports one tracker. Prefers ECG and tries cHPI if ECG is unavailable, fails QC or has ambiguous polarity. If ECG was extracted and cHPI is unavailable or fails QC, exports ECG with the cHPI diagnostic. |
ecg |
Forces a single ECG-derived tracker. Accepts raw M/EEG or an NPZ with ecg and scalar fs_ecg. |
chpi |
Forces a single head-motion tracker. A usable simultaneous ECG can orient its sign. |
both |
Requires both sources. Writes the cHPI tracker at the output root and the ECG tracker in ecg/. With plotting enabled, overlapping valid spans yield overlay_qc.png. |
For active continuous head-position indicator (cHPI) coils, use a pre-MaxFilter raw MEG recording. The preflight checks coil-status bits, carrier power above the local spectral background and sustained head-pose sampling. At least three strong carriers must be active together. The QC JSON records the checks so a configured but inactive coil set can be identified.
neuroresp meg sub-01_task-rest_meg.fif --source chpi --chpi-method pitch_ap --out derivatives/neuroresp/sub-01/chpi
Select the motion waveform with --chpi-method {pitch_ap,z_trans,pc1}. The anatomical pitch_ap estimate combines head pitch and front-to-back translation after quiet-interval standard-deviation scaling and sign alignment. Run rate uses the median of the two axis-specific cycle rates when they are available, agree within 3 breaths/min and the combined rate is valid. Discordant axes fail the rate check. The alternatives use z translation or the first principal component of the motion features. Use --skip-start SECONDS to exclude startup time from cHPI tracking while retaining recording-relative timestamps.
CTF recordings work the same way. Pass the .ds directory, and neuroresp reads the nine continuous HLC fiducial channels in place of fitting coil fields. Any recording whose channels include HLC0011–HLC0033 takes this route. The CTF gate checks that all nine channels exist and move, that the fiducial triangle is plausible and that at least 60 s of glitch-free head positions remain. A failure names the failed check.
neuroresp meg sub-01_ses-01_task-resting_meg.ds --source both --out derivatives/neuroresp/sub-01/meg
Already extracted HLC traces can be passed as an NPZ with hlc (samples × 9 in metres, ordered nasion, left ear, right ear, each as x, y, z) and scalar fs_hlc, through --chpi-pos or as the input file.
Standalone cHPI has an uncalibrated sign. An ECG that passes the polarity and quality gates can orient it approximately using the head-coil polarity gate, without shifting the waveform in time. ECG tracking itself checks for actual beat-to-beat respiratory modulation (null or weak modulation fails QC); changing rates widen the tracking band and raise rate_nonstationary for review.
Use --ecg-ch NAME to select an ECG stored as an auxiliary channel or to choose among multiple ECGs. A cHPI gate failure in chpi or both mode exits with the failed check before writing a trace. The motion and ECG series share recording time zero even when tracking starts late.
from neuroresp.meg import extract_from_raw
motion = extract_from_raw("sub-01_task-rest_meg.fif", source="both")
ecg = motion["ecg"]
usable_phase = motion["phase"][motion["valid"]]
For an already open MNE Raw object, neuroresp.respiration_from_chpi(raw) returns the standalone motion estimate. Its qc entry includes the gate measurements and the polarity convention.
For a CTF Raw object, or an array of HLC positions with its sampling rate, use neuroresp.respiration_from_hlc(raw) or respiration_from_hlc(hlc, fs). neuroresp.preflight_ctf_hlc runs the gate alone and returns its measurements without raising.
In Python without mne installed, call respiration_from_ecg directly on a 1D NumPy array.
from neuroresp.meg import respiration_from_ecg, write_meg_physio_bids
res = respiration_from_ecg(ecg_1khz, fs=1000.0)
write_meg_physio_bids("derivatives/neuroresp/sub-01/meg", res, prefix="sub-01_task-rest")
Batch processing and Slurm arrays
Plan a cohort once to inspect the selected images and belt recordings. The output paths in manifest.tsv are relative to the batch output root. Participant, session, task, acquisition and run filters accept multiple values. Labels retain leading zeroes.
neuroresp batch plan /data/bids --out /data/derivatives/neuroresp --task rest \
--workflow extract-fuse --write-slurm /data/rest.sbatch
neuroresp batch run /data/derivatives/neuroresp/manifest.tsv --out /data/derivatives/neuroresp \
--workers 4 --jobs 2 --skip-existing
Choose extract for native MRI trackers, belt for physiological recordings including belt-only runs, extract-fuse for hybrid cycles with MRI-only output when a belt is absent, or denoise for a tracker and midpoint confounds. Use a separate output root for each workflow to retain distinct results. A denoise run can reuse a completed extraction in the same root with --skip-existing. For local execution, --workers controls concurrent runs and --jobs controls registration workers within each run.
For Slurm, submit the generated script with sbatch /data/rest.sbatch from the environment containing neuroresp. Each array task processes one zero-based manifest row. After the array finishes, run neuroresp batch aggregate /data/derivatives/neuroresp. A local batch aggregates automatically unless --no-aggregate is supplied. Failed runs record their error and the batch command returns a nonzero exit code after processing the selected rows. Correct the input and repeat with --skip-existing to retry failed runs. Batch creates a BIDS 1.11.2 derivative dataset_description.json when absent. Reuse is existence-based: the successful status, selected inputs, backend, mode, workflow and required output files must match, but changed file contents, inherited sidecars, processing defaults or software versions are not checked. Omit --skip-existing to recompute after such changes.