Cerebrovascular Reactivity Mapping with phys2cvr#
Abbreviations
CVR = Cerebrovascular Reactivity
ME = Multi-Echo
IC = Independent Component
ICA = Independent Component Analysis
\(P_{ET}CO_2\) = Pressure of End-Tidal Carbon Dioxide
Warning
This tutorial assumes you ran:
Important
The dataset used in this book has no \(CO_2\) recording, and its task is not a respiratory challenge.
So that every step below can run, the \(CO_2\) trace in this tutorial is simulated,
and the component classification comes from tedana’s automatic decision tree rather than from a manual revision.
The maps derived from the simulated trace show what phys2cvr produces, but they are not measurements of CVR.
The simulated trace will be replaced once a suitable public dataset is available.
Cerebrovascular Reactivity (CVR) Mapping can greatly benefit from multi-echo (ME) data acquisition and independent component analysis (ICA) denoising, especially when it is based on breath-holds, cued deep breaths, or resting-state.
While ME-ICA will greatly reduce motion-related noise (see Moia et al. [2021]), because CVR is an increase in blood flow triggered by vessel dilation, there is a component of signal that is proton-density related. For this reason, the default decision tree in tedana may categorize certain components that should (or at least could) be kept as noise, so it is strongly suggested to perform a manual revision of the automatic categorization and/or adapt the decision tree to accept a better suited set of components.
On top of that, in the context of breath-holds and cued deep breaths, attention should be paid in the denoising stage, as an aggressive approach will remove all sources of signal that inform CVR and the associated hemodynamic lag. Instead, a conservative denoising approach, where noise IC timeseries are orthogonalized to the (temporally shifted) \(P_{ET}CO_2\) and the non-noise IC timeseries, is to be preferred (Moia et al. [2021]).
Assuming that you are following the other tutorials in this book, once you obtained your optimally combined signal and your ICA decomposition that has been manually inspected (and corrected if needed), you will need to make sure you have:
a whole brain mask in functional space that will confine
phys2cvroperations within it - thedesc-adaptiveGoodSignal_mask.nii.gzoutput oftedanacan work fine, but if you have a different mask that is also ok;if you want, a ROI mask in functional space whose average signal will be used as reference to align the regressor (e.g. the \(CO_2\) trace) and whose average hemodynamic lag will be set as 0-lag - gray matter or cerebellum are commonly used as reference ROI;
if you want to run ICA denoising, the timeseries of rejected and accepted components from tedana in two different files.
Preparing the inputs#
We start from the outputs of the tedana tutorial.
import os
import matplotlib.pyplot as plt
import nibabel as nb
import nitransforms as nit
import numpy as np
import pandas as pd
from book_utils import glue_figure
from nilearn import image, plotting
data_path = os.path.abspath('../data')
prefix = "sub-24053_ses-1_task-rat_dir-PA_run-01"
func_dir = os.path.join(data_path, "ds006185/sub-24053/ses-1/func")
anat_dir = os.path.join(data_path, "ds006185/sub-24053/ses-1/anat")
ted_dir = os.path.join(data_path, "tedana")
out_dir = os.path.join(data_path, "cvr")
os.makedirs(out_dir, exist_ok=True)
# The optimally combined data and the brain mask written by tedana
optcom_file = os.path.join(ted_dir, f"{prefix}_desc-optcom_bold.nii.gz")
mask_file = os.path.join(ted_dir, f"{prefix}_desc-adaptiveGoodSignal_mask.nii.gz")
A reference ROI#
We use gray matter as the reference ROI.
fMRIPrep provides a tissue segmentation in the space of the T1w image (1 is gray matter),
so we resample it onto the grid of the functional data and keep the gray matter voxels that are inside the brain mask.
In addition to the files listed in Download Data, this needs the segmentation:
datalad get sub-24053/ses-1/anat/sub-24053_ses-1_dseg.nii.gz
datalad get sub-24053/ses-1/func/sub-24053_ses-1_task-rat_dir-PA_run-01_from-boldref_to-T1w_mode-image_desc-coreg_xfm.txt
# The transform moves images from the BOLD reference to the T1w image,
# so its inverse brings the segmentation into the space of the BOLD data.
xfm = nit.linear.load(
os.path.join(func_dir, f"{prefix}_from-boldref_to-T1w_mode-image_desc-coreg_xfm.txt"),
fmt="itk",
)
dseg_img = nit.resampling.apply(
~xfm,
os.path.join(anat_dir, "sub-24053_ses-1_dseg.nii.gz"),
reference=mask_file,
order=0,
)
mask_img = nb.load(mask_file)
roi = (dseg_img.get_fdata() == 1) & (mask_img.get_fdata() > 0)
roi_file = os.path.join(out_dir, "gm_mask.nii.gz")
nb.Nifti1Image(roi.astype(np.uint8), mask_img.affine).to_filename(roi_file)
print(f"{roi.sum()} gray matter voxels out of {(mask_img.get_fdata() > 0).sum()} voxels in the mask")
69440 gray matter voxels out of 211186 voxels in the mask
Accepted and rejected component timeseries#
The easiest way to obtain these is using the mixing matrix from tedana and a component classification with the help of pandas.
If you revised the classification with rica, read the manual_classification.tsv file you downloaded from it instead of the metrics table.
It has the same Component and classification columns.
# Read the component classification.
# Here it is the automatic one from tedana; with rica, read manual_classification.tsv instead.
classification = pd.read_table(os.path.join(ted_dir, f"{prefix}_desc-tedana_metrics.tsv"))
# Read the ICA mixing matrix
ica_mix = pd.read_table(os.path.join(ted_dir, f"{prefix}_desc-ICA_mixing.tsv"))
# Extract the list of rejected and accepted components
rej_comp = classification.loc[classification["classification"] == "rejected", "Component"].tolist()
acc_comp = classification.loc[classification["classification"] == "accepted", "Component"].tolist()
print(f"{len(acc_comp)} accepted and {len(rej_comp)} rejected components")
# Extract rejected vs accepted timeseries and save them
accepted_file = os.path.join(out_dir, "accepted_ic_timeseries.csv")
rejected_file = os.path.join(out_dir, "rejected_ic_timeseries.csv")
ica_mix[acc_comp].to_csv(accepted_file, index=False, header=False)
ica_mix[rej_comp].to_csv(rejected_file, index=False, header=False)
30 accepted and 43 rejected components
Other nuisance regressors#
Any other source of noise can be added as well. Here we take the motion parameters and their temporal derivatives from the fMRIPrep confounds.
confounds = pd.read_table(
os.path.join(func_dir, f"{prefix}_part-mag_desc-confounds_timeseries.tsv")
)
motion_columns = [
f"{kind}_{axis}{suffix}"
for kind in ("trans", "rot")
for axis in ("x", "y", "z")
for suffix in ("", "_derivative1")
]
motion_file = os.path.join(out_dir, "motion_params.csv")
# The first value of each derivative is undefined
confounds[motion_columns].fillna(0).to_csv(motion_file, index=False, header=False)
The phys2cvr workflow#
After installing phys2cvr, potentially with extra dependencies, we can import the main workflow of phys2cvr and call its help to see all available parameters (many).
from phys2cvr.workflows import phys2cvr as p2c
help(p2c)
Help on function phys2cvr in module phys2cvr.workflows:
phys2cvr(
fname_func,
fname_co2=None,
fname_pidx=None,
fname_roi=None,
fname_mask=None,
outdir=None,
freq=None,
tr=None,
trial_len=None,
n_trials=None,
abs_xcorr=False,
skip_xcorr=False,
highcut=0.04,
lowcut=0.02,
butter_order=9,
apply_filter=False,
run_regression=False,
lagged_regression=True,
r2model='full',
lag_max=None,
lag_step=None,
legacy=False,
l_degree=0,
denoise_matrix_file=None,
orthogonalised_matrix_file=None,
extra_matrix_file=None,
scale_factor=None,
lag_map=None,
regr_dir=None,
comp_endtidal=True,
response_function='hrf',
quiet=False,
debug=False
)
Run main workflow of phys2cvr.
Parameters
----------
fname_func : str or path
Filename of the functional input (nifti or txt)
fname_co2 : str or path, optional
Filename of the CO2 (physiological regressor) timeseries.
Can be either peakdet's output or a txt file.
If not declared, phys2cvr will consider the average temporal value
from the input.
Default: empty
fname_pidx : str or path, optional
Filename of the CO2 (physiological regressor) timeseries' PEAKS.
Required if CO2 file is a txt AND the convolution step is not skipped.
If not declared AND the convolution step is not skipped, raises an exception.
Default: empty
fname_roi : str or path, optional
Filename of the roi in a nifti volume.
If declared, phys2cvr will use these voxels .
If not, phys2cvr will use a mask, either the declared one or estimated
from the functional input.
Ignored if input is a txt file.
Default: empty
fname_mask : str or path, optional
Filename of the mask in a nifti volume.
If declared, phys2cvr will run only on these voxels.
If not, phys2cvr will estimate a mask from the functional input.
Ignored if input is a txt file.
Default: empty
outdir : str or path, optional
Output directory
Default: the directory where `fname_func` is.
freq : str, int, or float, optional
Sample frequency of the CO2 regressor. Required if CO2 input is TXT file.
If declared with peakdet file, it will overwrite the file frequency.
tr : str, int, or float, optional
TR of the timeseries. Required if input is TXT file.
If declared with nifti file, it will overwrite the file TR.
trial_len : str or int, optional
Length of each single trial for tasks that have more than one
(E.g. BreathHold, CO2 challenges, ...)
Used to improve cross correlation estimation.
Default: None
n_trials : str or int, optional
Number of trials in the task.
Default: None
abs_xcorr : bool, optional
If True, the cross correlation will consider max(abs(xcorr)).
If False, the cross correlation will consider max(xcorr).
Default: False
skip_xcorr : bool, optional
If True, skip the cross correlation step.
Default: False
highcut : str, int, or float, optional
High frequency limit for filter.
Required if applying a filter.
Default: 0.02
lowcut : str, int, or float, optional
Low frequency limit for filter.
Required if applying a filter.
Default: 0.04
butter_order : int, optional
Butterworth filter order.
Default: 9
apply_filter : bool, optional
Apply a Butterworth filter to the functional input.
Default: False
run_regression : bool, optional
Also run the regression step within phys2cvr.
By default, phys2cvr will only estimate the regressor(s) of interest.
Default: False
lagged_regression : bool, optional
Estimates regressors to run a lagged regression approach.
If `run_regression` is True, also run the lagged regression.
Can be turned off.
Default: True
r2model : {`full`, `partial`, `intercept`, `adj_full`, `adj_partial`, `adj_intercept`), optional
R^2 model the regression should return (and hence used for lag selection).
Potentially invariant if no orthogonalisation is introduced,
will change results with orthogonalisations.
See `stats.ols` help for more details.
Default: `full`
lag_max : int or float, optional
Limits (both positive and negative) of the temporal area to explore,
expressed in seconds (e.g. ±9 seconds). Caution: this is not a pythonic
range, but a real range, i.e. the upper limit is included (e.g. [-9, +9]).
Default: None
lag_step : int or float, optional
Step of the lag to take into account in seconds.
Default: None
legacy : bool, optional
If True, use pythonic ranges when creating the regressors, i.e. exclude
the upper range (e.g. [-9, +9) ).
Default: False
l_degree : int, optional
Only used if performing the regression step.
Highest order of the Legendre polynomial to add to the denoising matrix.
phys2cvr will add all polynomials up to the specified order
(e.g. if user specifies 3, orders 0, 1, 2, and 3 will be added).
Default is 0, which will model only the mean of the timeseries.
denoise_matrix_file : None, list of str(s) or path(s), optional
Add one or multiple denoising matrices to the regression model.
Ignored if not performing the regression step.
Default is None.
orthogonalised_matrix_file : None, list of str(s) or path(s), optional
Add one or multiple denoising matrices to the regression model,
AFTER orthogonalising them w.r.t. the task, the denoise matrix,
and the extra matrix.
Ignored if not performing the regression step.
Default is None.
extra_matrix_file : None, list of str(s) or path(s), optional
Add one or multiple extra matrices to use in the orthogonalisation step.
These matrices will not be added to the final regression model.
Ignored if not performing the regression step.
Default is None.
scale_factor : str, int, or float, optional
A scale factor to apply to the CVR map before exporting it.
Useful when using inputs recorded/stored in Volts that have a meaningful
unit of measurement otherwise, e.g. (CO2 traces in mmHg).
V->mmHg: CO2[mmHg] = (Patm-Pvap)[mmHg] * 10*CO2[V]/100[V]
Default: None
lag_map : str or path, optional
Filename of a lag map to get lags from.
Ignored if not running a lagged-GLM regression.
Default: None
regr_dir : str, optional
Directory containing pre-generated lagged regressors, useful
to (re-)run a GLM analysis.
Default: None
comp_endtidal : bool, optional
Compute the end-tidal interpolation of the CO2 signal.
response_function : {`hrf`, `rrf`, `crf`, `None`}, None, str, path, or 1D array-like, optional
Name of the response function to be used in the convolution of the regressor of
interest. Default is `hrf`.
If None, skips the convolution step.
If file, loads it.
For `rrf` and `crf`, `phys2denoise` must be installed (see extra installs).
See `signal.compute_petco2hrf` for details.
quiet : bool, optional
Return to screen only warnings and errors.
Default: False
debug : bool, optional
Return to screen more output.
Default: False
Raises
------
ValueError
- If the order of Legendre Polynomials is < 0.
- If a wrong R^2 model was specified.
- If functional nifti file is not at least 4D.
- If mask was specified but it has different dimensions than the
functional nifti file.
- If ROI was specified but it has different dimensions than the
functional nifti file.
- If a lag map was specified but it has different dimensions than the
functional nifti file.
- If a lag map was specified, lag_step was not, and the lag map seems
to have different lag_steps inside.
NotImplementedError
- If a file type is not supported yet.
NameError
- If functional timeseries is lacking TR and the latter was not specified.
- If physiological file is a txt file and no peaks were provided.
- If physiological file is lacking frequency and the latter was not specified.
You may notice many potential parameters. phys2cvr is meant to be very versatile, but fear not! Only a few of them are needed in different situations. For more info, check the workflow API page.
By default, phys2cvr takes anything given to it and creates lagged regressors of the interpolated end-tidal of a given trace (that is, the \(P_{ET}CO_2hrf\)) after aligning it with a reference signal and convolving it with a canonical HRF. However, you can run a lag regression internally.
Generally speaking, you may need these parameters - although only fname_func is mandatory:
fname_func=optcom_file, # The optimally combined data
fname_co2=co2_file, # The CO2 trace with peaks
fname_mask=mask_file, # A mask to limit the analysis to
fname_roi=roi_file, # A ROI to use as signal reference
outdir=os.path.join(out_dir, "co2"), # Output folder
run_regression=True, # Run the analysis!
lag_max=9, # Maximum lag to consider
lag_step=0.3, # Lag step to consider
l_degree=2, # Legendre polynomials degrees
You can also run a simple regression instead of a lagged one - in that case, remove lag_max and lag_step.
In terms of regressor for your CVR analysis, many options are supported:
\(CO_2\) traces (and their peak indices)
pre-made \(P_{ET}CO_2\) traces
task designs (timeseries)
BOLD signal averages from a ROI mask.
\(CO_2\) traces (and their peak indices)#
You can get \(CO_2\) traces (and their peak indices) with whatever program you want - simply run a very light lowpass filter (and maybe a downsampling), followed by peak detection.
A simulated \(CO_2\) recording#
Normally you would start from the file exported by your gas analyzer.
As explained at the top of this page, we have no such file for these data, so we simulate one:
a breathing rhythm of about 15 breaths per minute, in which each exhalation rises to an end-tidal value that drifts slowly around 38 mmHg.
The recording is 60 seconds longer than the functional run, as a real one usually starts before the run and stops after it.
Because the trace is simulated, there is no true alignment between the two;
phys2cvr simply picks the bulk shift with the highest cross-correlation.
Peak detection#
Here’s an example with Physiopy’s peakdet.
import peakdet as pk
data = np.genfromtxt(co2_path)
co2 = pk.Physio(data, fs=samp_freq)
# Interpolation (downsampling), then filtering.
co2 = pk.operations.interpolate_physio(co2, 40.0, kind='linear')
co2 = pk.operations.filter_physio(co2, 2, method='lowpass', order=7)
# Automatic peak detection, then manual editing
# If you see that not enough/too many peaks get selected,
# you might tune the threshold and distance.
co2 = pk.operations.peakfind_physio(co2, thresh=0.5, dist=120)
# edit_physio opens an interactive window to add or remove peaks by hand.
# It cannot run while this book is built, so it is commented out here.
# co2 = pk.operations.edit_physio(co2)
co2_file = pk.save_physio(os.path.join(out_dir, "co2.phys"), co2)
print(f"{co2.peaks.size} peaks detected")
172 peaks detected
If your file has several columns, select the one containing the \(CO_2\) data when creating the Physio object (e.g., data[:, channel]).
Fig. 60 The first two minutes of the simulated \(CO_2\) trace, after filtering, with the end-tidal peaks detected by peakdet.#
With this last output, we can run phys2cvr!
p2c(
fname_func=optcom_file, # The optimally combined data
fname_co2=co2_file, # The CO2 trace with peaks
fname_mask=mask_file, # A mask to limit the analysis to
fname_roi=roi_file, # A ROI to use as signal reference
outdir=os.path.join(out_dir, "co2"), # Output folder
run_regression=True, # Run the analysis!
lag_max=9, # Maximum lag to consider
lag_step=0.3, # Lag step to consider
l_degree=2, # Legendre polynomials degrees
denoise_matrix_file=[motion_file], # All the noise you want to add
orthogonalised_matrix_file=[rejected_file],
extra_matrix_file=[accepted_file],
scale_factor=None, # If CO2 trace is not in mmHg, you can scale the final map accordingly
)
If you didn’t use peakdet for your \(CO_2\) processing and peak detection, add the parameter fname_pidx='../co2_peak_indices' to the list.
phys2cvr will compute the \(P_{ET}CO_2hrf\) trace by linearly interpolating the end-tidal peaks of your \(CO_2\) trace and convolving the former with a canonical HRF. You can select another response function (as well as skipping the interpolation) using the parameter response_function.
Among other files, phys2cvr writes a CVR map, a lag map, and a t-statistic map to the output folder.
print("\n".join(sorted(f for f in os.listdir(os.path.join(out_dir, "co2")) if f.endswith(".nii.gz"))))
sub-24053_ses-1_task-rat_dir-PA_run-01_desc-optcom_bold_cvr.nii.gz
sub-24053_ses-1_task-rat_dir-PA_run-01_desc-optcom_bold_cvr_simple.nii.gz
sub-24053_ses-1_task-rat_dir-PA_run-01_desc-optcom_bold_lag.nii.gz
sub-24053_ses-1_task-rat_dir-PA_run-01_desc-optcom_bold_lag_mkrel.nii.gz
sub-24053_ses-1_task-rat_dir-PA_run-01_desc-optcom_bold_tstat.nii.gz
sub-24053_ses-1_task-rat_dir-PA_run-01_desc-optcom_bold_tstat_simple.nii.gz
/tmp/ipykernel_87409/1475869081.py:3: FutureWarning: From release 0.13.0 onwards, this function will, by default, copy the header of the input image to the output. Currently, the header is reset to the default Nifti1Header. To suppress this warning and use the new behavior, set `copy_header=True`.
bg_img = image.mean_img(optcom_file)
Fig. 61 CVR and lag maps estimated from the simulated \(CO_2\) trace. Because the trace is simulated, it is unrelated to the BOLD signal, and these maps only illustrate the outputs.#
Pre-made \(P_{ET}CO_2\) traces#
If you have a pre-made \(P_{ET}CO_2\) trace, simply skip the steps to make one.
To have such a trace for this example, we interpolate the end-tidal peaks detected above and save the result as a text file.
samples = np.arange(co2.data.size)
petco2 = np.interp(samples, co2.peaks, co2.data[co2.peaks])
petco2_file = os.path.join(out_dir, "petco2_trace.1D")
np.savetxt(petco2_file, petco2, fmt="%.4f")
Because a text file does not store its sampling frequency, we also need to declare it with freq.
p2c(
fname_func=optcom_file, # The optimally combined data
fname_co2=petco2_file, # The pre-made PetCO2 trace
freq=co2.fs, # The sampling frequency of the PetCO2 trace
fname_mask=mask_file, # A mask to limit the analysis to
fname_roi=roi_file, # A ROI to use as signal reference
outdir=os.path.join(out_dir, "petco2"), # Output folder
run_regression=True, # Run the analysis!
lag_max=9, # Maximum lag to consider
lag_step=0.3, # Lag step to consider
l_degree=2, # Legendre polynomials degrees
denoise_matrix_file=[motion_file], # All the noise you want to add
orthogonalised_matrix_file=[rejected_file],
extra_matrix_file=[accepted_file],
scale_factor=None, # If CO2 trace is not in mmHg, you can scale the final map accordingly
comp_endtidal=False, # DO NOT compute PetCO2 internally
response_function=None, # DO NOT interpolate the PetCO2 trace.
)
Task designs (timeseries)#
Simply use your task design as \(CO_2\) trace. You can interpolate it with an HRF or a respiratory response function internally, or do this beforehand.
The data used in this book were not acquired during a respiratory task, so this call is shown but not run.
p2c(
fname_func=optcom_file, # The optimally combined data
fname_co2='../task_design.1D', # The task design
freq=40, # The sampling frequency of the task design
fname_mask=mask_file, # A mask to limit the analysis to
fname_roi=roi_file, # A ROI to use as signal reference
outdir=os.path.join(out_dir, "task"), # Output folder
run_regression=True, # Run the analysis!
lag_max=9, # Maximum lag to consider
lag_step=0.3, # Lag step to consider
l_degree=2, # Legendre polynomials degrees
denoise_matrix_file=[motion_file], # All the noise you want to add
orthogonalised_matrix_file=[rejected_file],
extra_matrix_file=[accepted_file],
scale_factor=None, # If CO2 trace is not in mmHg, you can scale the final map accordingly
comp_endtidal=False, # DO NOT compute end-tidal trace
response_function='rrf', # Interpolate with RRF
)
BOLD signal averages from a ROI mask#
This is the simplest way to run phys2cvr, using the average BOLD signal from a desired ROI.
It needs no \(CO_2\) recording at all, so here nothing is simulated.
Note
The lagged regression is switched off in this call.
When the reference signal is the ROI average, its bulk shift relative to itself is zero,
and phys2cvr (at least up to version 0.28.4) then fails to build the lagged regressors.
This call therefore only produces the CVR map at the bulk shift.
p2c(
fname_func=optcom_file, # The optimally combined data
fname_mask=mask_file, # A mask to limit the analysis to
fname_roi=roi_file, # A ROI to use as signal reference
outdir=os.path.join(out_dir, "roi"), # Output folder
run_regression=True, # Run the analysis!
lagged_regression=False, # Only estimate CVR at the bulk shift (see the note above)
l_degree=2, # Legendre polynomials degrees
denoise_matrix_file=[motion_file], # All the noise you want to add
orthogonalised_matrix_file=[rejected_file],
extra_matrix_file=[accepted_file],
comp_endtidal=False, # DO NOT compute end-tidal trace
response_function=None, # DO NOT interpolate the trace
apply_filter=True, # Filter the average BOLD signal (optional)
highcut=0.04, # Lowpass frequency
lowcut=0.02, # Highpass frequency
butter_order=9, # Butterworth filter order
)
/tmp/ipykernel_87409/1475869081.py:3: FutureWarning: From release 0.13.0 onwards, this function will, by default, copy the header of the input image to the output. Currently, the header is reset to the default Nifti1Header. To suppress this warning and use the new behavior, set `copy_header=True`.
bg_img = image.mean_img(optcom_file)
Fig. 62 Map estimated from the average gray matter signal. These data were not acquired during a respiratory challenge, so this map illustrates the output of the call rather than a measurement of CVR.#
Final remarks#
Remember to cite the right papers and resources depending on the desired pipeline!
For more info about phys2cvr, as well as knowing what to cite in which case, check out its documentation.
Not a Python person? Prefer to run bash CLI commands? Not a problem.
phys2cvr is in fact primarily designed to be used via bash CLI.
phys2cvr --help
For more info about ME CVR, check out Moia et al. [2021], Cohen and Wang [2019], and Cohen et al. [2025].
If you want to contribute to phys2cvr, have requests, comments, or questions, feel free to open an issue!