External Regressors in tedana Decision Trees#
Abbreviations
CSF = CerebroSpinal Fluid
FD = Framewise Displacement
IC = Independent Component
ROI = Region of Interest
RETROICOR = RETROspective Image CORrection
RV = Respiration Variation
HR = Heart Rate
tedana classifies ICA components mostly from how their signal depends on echo time (TE).
Sometimes we also know what a noise source or the signal of interest looks like over time:
a recording of the participant’s breathing, the head motion estimated during preprocessing,
the average signal in a region, or the timing of the task.
Decision trees can compare each component’s time series to such external regressors,
and use the fit to reject components that look like noise or to keep components that look like the task.
This page builds the four kinds of external regressors listed in ME-ICA/multi-echo-data-analysis#94:
physiological regressors computed from cardiac and respiratory recordings,
average time series from ROIs (see ME-ICA/tedana#1175),
confounds estimated by fMRIPrep, and
task regressors.
It then runs tedana with a decision tree that uses them, and compares the result with a tree that does not.
The data#
We use one run of the localizer task from the Dense Investigation of Variability of Affect (DIVA) dataset (see the preprint). The participant alternated between 14-second blocks of finger tapping (motor) and of watching a flickering checkerboard (visual), separated by 14 seconds of rest. In half of the blocks, music played at the same time (auditory). The run was acquired with four echoes, and cardiac (ECG) and respiratory (belt) signals were recorded during the scan. The echoes were preprocessed with fMRIPrep and stay in the space of the run’s BOLD reference image. See Download Data for the list of files.
import json
import os
import shutil
import matplotlib.pyplot as plt
import nibabel as nb
import numpy as np
import pandas as pd
from book_utils import atlas_mask, glue_figure, load_diva, warp_mni_roi_to_run
from nilearn import datasets, masking, plotting
from nilearn.glm.first_level import make_first_level_design_matrix
from scipy import signal
from tedana import workflows
data_path = os.path.abspath("../data")
data = load_diva(data_path)
prefix = data["prefix"]
out_dir = os.path.join(data_path, "external-regressors")
os.makedirs(out_dir, exist_ok=True)
/mnt/c/Users/tsalo/Documents/ME-ICA/multi-echo-data-analysis/meda/lib/python3.14/site-packages/tqdm/auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html
from .autonotebook import tqdm as notebook_tqdm
Every regressor needs one value per volume, so we start with the timing of the volumes.
fMRIPrep corrected the data for slice timing, and its sidecar records, in StartTime,
the time within each volume that the corrected data represent.
That is when we sample every regressor.
fMRIPrep also flags the first volumes, acquired before the signal reached a steady state, as non-steady-state outliers.
We will drop them in tedana with dummy_scans, which drops the same rows from the external regressors.
with open(data["optcom_json"], "r") as fo:
bold_metadata = json.load(fo)
t_r = bold_metadata["RepetitionTime"]
n_vols = nb.load(data["optcom"]).shape[3]
frame_times = np.arange(n_vols) * t_r + bold_metadata["StartTime"]
confounds = pd.read_table(data["confounds"])
dummy_scans = confounds.filter(like="non_steady_state_outlier").any(axis=1).to_numpy()
n_dummy = int(np.argmin(dummy_scans)) if dummy_scans.any() else 0
# dummy_scans only removes volumes at the start of the run
assert dummy_scans[:n_dummy].all() and not dummy_scans[n_dummy:].any()
# The times of the volumes that tedana keeps
volume_times = frame_times[n_dummy:]
print(f"{n_vols} volumes, TR = {t_r} s, {n_dummy} non-steady-state volume(s)")
300 volumes, TR = 1.5 s, 1 non-steady-state volume(s)
1. Physiological regressors#
The physiological recording is a BIDS _physio.tsv.gz file, with its sampling frequency, columns and start time in its sidecar.
with open(data["physio_json"], "r") as fo:
physio_metadata = json.load(fo)
print(json.dumps(physio_metadata, indent=4))
physio = pd.read_table(data["physio"], header=None, names=physio_metadata["Columns"])
samp_freq = physio_metadata["SamplingFrequency"]
Aligning the recording with the scan#
According to BIDS, StartTime is the time of the first sample relative to the first volume,
so a positive value means that the recording started after the scan.
That is not the case here: the recording starts before the scan, and the sign of StartTime is flipped.
The trigger channel settles the question.
It is high while the scanner acquires volumes, so its first high sample marks the start of the first volume,
and the length of the high period should match the duration of the run.
scan_on = physio["trigger"].to_numpy() > (physio["trigger"].max() / 2)
start_time = -np.argmax(scan_on) / samp_freq
physio_times = np.arange(physio.shape[0]) / samp_freq + start_time
print(f"StartTime in the sidecar: {physio_metadata['StartTime']} s")
print(f"StartTime from the trigger: {start_time:.3f} s")
print(f"The trigger is high for {scan_on.sum() / samp_freq:.2f} s; the run lasts {n_vols * t_r:.2f} s")
StartTime in the sidecar: 9.0 s
StartTime from the trigger: -9.065 s
The trigger is high for 450.01 s; the run lasts 450.00 s
From now on, physio_times holds the time of each sample relative to the start of the scan.
Cardiac and respiratory peaks#
The ECG was recorded during the scan, so it carries a gradient artifact at the rate at which the scanner acquires slices.
With 48 slices acquired with a multiband factor of three, there are 16 shots per 1.5-second volume,
so the artifact sits at 10.7 Hz and its harmonics.
A band-pass filter below that frequency leaves the R peaks, which scipy can find.
The respiratory belt is slow, so a low-pass filter is enough.
sos = signal.butter(4, [0.5, 8], btype="bandpass", fs=samp_freq, output="sos")
cardiac = signal.sosfiltfilt(sos, physio["cardiac"].to_numpy())
# R peaks are at least 0.6 s apart (heart rate < 100 bpm) and stand out from the rest of the trace
card_peaks, _ = signal.find_peaks(cardiac, distance=int(0.6 * samp_freq), prominence=np.std(cardiac))
# Drop the occasional T wave that passes the first criteria
card_peaks = card_peaks[cardiac[card_peaks] > 0.5 * np.median(cardiac[card_peaks])]
beat_times = physio_times[card_peaks][1:]
heart_rate = 60 / np.diff(physio_times[card_peaks])
sos = signal.butter(4, 1, btype="lowpass", fs=samp_freq, output="sos")
respiration = signal.sosfiltfilt(sos, physio["respiration"].to_numpy())
resp_peaks, _ = signal.find_peaks(respiration, distance=int(2 * samp_freq), prominence=0.5 * np.std(respiration))
Fig. 63 Top: 15 seconds of the ECG before and after filtering, with the detected R peaks. The sharp spikes in the raw trace are the gradient artifact. Middle: heart rate over the whole recording. Bottom: one minute of the filtered respiratory trace, with the detected peaks.#
RETROICOR#
RETROICOR [Glover et al., 2000] models the effect of the cardiac and respiratory cycles on the signal as a Fourier series of their phase at the time each volume was acquired. The cardiac phase goes from 0 to \(2\pi\) between consecutive R peaks. The respiratory phase also accounts for the depth of the breath: its magnitude comes from the amplitude of the respiratory trace relative to its histogram, and its sign from whether the participant is breathing in or out. The functions below compute both phases and their Fourier series.
We sample each phase at the volume times and expand it to the second order, which gives eight regressors. The respiratory phase jumps from \(\pi\) to \(-\pi\) at the top of each breath, so we take the value of the nearest sample instead of interpolating across the jump.
card_phase = cardiac_phase(frame_times, physio_times[card_peaks])
resp_phase_all = respiratory_phase(respiration)
nearest_sample = np.clip(np.round((frame_times - physio_times[0]) * samp_freq).astype(int), 0, physio_times.size - 1)
resp_phase = resp_phase_all[nearest_sample]
retroicor = pd.concat(
[
fourier_expansion(card_phase, 2, "physio_card"),
fourier_expansion(resp_phase, 2, "physio_resp"),
],
axis=1,
)
Fig. 64 Top: 30 seconds of the cardiac and respiratory phases, with their values at the volume times (black). Bottom: the eight RETROICOR regressors over the whole run. The heart beats faster than the volumes are acquired, so the cardiac regressors are aliased and look like noise; that is expected, since the cardiac noise in the data is aliased in the same way.#
Respiration variation and heart rate#
Slower changes in the depth of breathing and in heart rate change arterial \(CO_2\) and blood flow, and they affect the BOLD signal over several seconds. Following Chang et al. [2009], we compute the respiration variation (RV), the standard deviation of the respiratory trace in a 6-second window, and the heart rate averaged over the same window. They are then convolved with the respiration response function [Birn et al., 2008] and the cardiac response function [Chang et al., 2009], respectively. We do this on a fine time grid that starts with the recording, so that the seconds recorded before the scan contribute to the first volumes, and then sample the result at the volume times.
grid_step = 0.1
grid = np.arange(physio_times[0], physio_times[-1], grid_step)
window_length = round(6 / grid_step) + 1
rv = pd.Series(np.interp(grid, physio_times, respiration)).rolling(window_length, center=True, min_periods=1).std().to_numpy()
hr = pd.Series(np.interp(grid, beat_times, heart_rate)).rolling(window_length, center=True, min_periods=1).mean().to_numpy()
kernel_times = np.arange(0, 40, grid_step)
rrf = respiration_response_function(kernel_times)
crf = cardiac_response_function(kernel_times)
rv_conv = np.convolve(rv - rv.mean(), rrf)[: grid.size]
hr_conv = np.convolve(hr - hr.mean(), crf)[: grid.size]
physio_slow = pd.DataFrame(
{
"physio_rv": np.interp(frame_times, grid, rv_conv),
"physio_hr": np.interp(frame_times, grid, hr_conv),
}
)
physio_regressors = pd.concat([retroicor, physio_slow], axis=1)
Fig. 65 Left: the response functions. Right: RV and HR in 6-second windows (gray), and the regressors after convolution, sampled at the volume times (color), each scaled to unit variance. The recording starts about 9 seconds before the first volume, so the convolution already has a history at the first volume; the plot shows the run only.#
2. ROI time series#
tedana takes a table of time series, so the average signal in an ROI has to be computed before tedana runs
(ME-ICA/tedana#1175).
As an example, we use the lateral ventricles from the Harvard-Oxford subcortical atlas, as a CSF ROI.
Important
This ROI is here to show how an ROI time series can be used in a decision tree, not to recommend this particular ROI.
fMRIPrep already writes a similar regressor, the csf column of its confounds file,
which is the average signal in an eroded CSF mask from the participant’s own segmentation.
An ROI that fMRIPrep does not provide, such as a draining vein or a region with a known artifact, is where this approach is most useful.
The ROI is in a standard space, so we warp it into the space of the BOLD data with the transforms that fMRIPrep wrote:
_from-MNI152NLin2009cAsym_to-T1w_mode-image_xfm.h5 (a nonlinear transform between the template and the participant’s T1w image)
and _from-run_to-T1w_mode-image_desc-coreg_xfm.txt (a rigid transform between the run’s BOLD reference and the T1w image).
warp_mni_roi_to_run chains them with NiTransforms and resamples the ROI onto the BOLD reference.
harvard_oxford = datasets.fetch_atlas_harvard_oxford("sub-maxprob-thr25-2mm")
ventricles_mni = atlas_mask(harvard_oxford, ["Left Lateral Ventricle", "Right Lateral Ventricle"])
ventricles = warp_mni_roi_to_run(ventricles_mni, data)
ventricles_file = os.path.join(out_dir, f"{prefix}_space-run_desc-ventricles_mask.nii.gz")
ventricles.to_filename(ventricles_file)
Note
The atlases distributed with FSL (and fetched by nilearn) are in the MNI152NLin6Asym template,
while fMRIPrep’s transform starts from MNI152NLin2009cAsym.
The two templates differ by a few millimeters, which matters little for large ROIs.
For precise work, add the transform between the two templates from TemplateFlow to the chain.
Fig. 66 The lateral ventricle ROI after warping it to the space of the BOLD data, on top of the BOLD reference image.#
We average the optimally combined echoes that fMRIPrep writes (_desc-preproc_bold.nii.gz without an echo entity) in the ROI.
tedana’s own optimal combination would be slightly different, but this is close enough to describe a noise source.
ventricle_timeseries = masking.apply_mask(data["optcom"], ventricles_file).mean(axis=1)
Fig. 67 The average signal in the ventricle ROI and fMRIPrep’s csf regressor, after the non-steady-state volume, each scaled to unit variance.
They are similar but not identical, because the masks differ.#
3. fMRIPrep confounds#
fMRIPrep writes many candidate confounds. Here we use the six head motion parameters and their temporal derivatives.
motion_columns = [f"{kind}_{axis}{suffix}" for kind in ("trans", "rot") for axis in ("x", "y", "z") for suffix in ("", "_derivative1")]
# The first value of each derivative is undefined
motion = confounds[motion_columns].fillna(0)
Fig. 68 The translation and rotation parameters estimated by fMRIPrep, and the framewise displacement that summarizes them. The regressors are the six parameters and their derivatives; framewise displacement is shown only for reference.#
4. Task regressors#
The localizer has three conditions.
A block that combines tapping and music counts as both a motor and an auditory block,
so we split each trial_type into its parts and model each condition separately.
nilearn convolves the blocks with a hemodynamic response function and samples them at the volume times.
events = pd.read_table(data["events"])
events = events.assign(trial_type=events["trial_type"].str.split("/")).explode("trial_type")
events = events[["onset", "duration", "trial_type"]].sort_values("onset").reset_index(drop=True)
task_design = make_first_level_design_matrix(frame_times, events, hrf_model="spm", drift_model=None)
task_regressors = task_design[["motor", "visual", "auditory"]].reset_index(drop=True)
Fig. 69 The blocks of each condition (shaded) and the task regressors.#
Putting the regressors together#
tedana reads external regressors from a tab-separated file with one column per regressor and one row per volume, including the dummy scans.
The names of the columns are how the decision tree refers to the regressors, so we give each kind a prefix.
external = pd.concat(
[
physio_regressors,
pd.DataFrame({"csf_ventricles": ventricle_timeseries}),
motion.add_prefix("mot_"),
task_regressors.add_prefix("task_"),
],
axis=1,
)
assert external.shape[0] == n_vols
assert not external.isna().any().any()
external_file = os.path.join(out_dir, f"{prefix}_desc-external_regressors.tsv")
external.to_csv(external_file, sep="\t", index=False)
Fig. 70 All external regressors, each scaled to unit variance.#
A decision tree that uses external regressors#
A decision tree is a JSON file.
It declares how to fit the external regressors in its external_regressor_config,
and then uses the resulting metrics in its nodes.
tedana comes with demonstration trees that do this.
Our tree, decision_trees/external_regressors_tree.json,
is tedana’s demo_external_regressors_motion_task_models tree, edited in three places:
the regular expressions that select the regressors match our column names,
the nuisance model has a partial model for the physiological regressors,
and a node tags the components that the physiological regressors fit.
Here is its external_regressor_config:
"external_regressor_config": [
{
"regress_ID": "nuisance",
"info": "Fits all external nuisance regressors to a single model using an F statistic",
"report": "External nuisance regressors that fit to components using a linear model were rejected.",
"detrend": true,
"statistic": "F",
"regressors": ["^mot_.*$", "^csf_.*$", "^physio_.*$"],
"partial_models": {
"Motion": ["^mot_.*$"],
"CSF": ["^csf_.*$"],
"Physio": ["^physio_.*$"]
}
},
{
"regress_ID": "task",
"info": "Fits all task regressors to a single model using an F statistic",
"report": "Task regressors that fit to components using a linear model and have some T2* weighting were accepted even if they would have been rejected based on other criteria.",
"detrend": true,
"statistic": "F",
"regressors": ["^task_.*$"]
}
],
It fits two models to each component’s time series:
a nuisance model, an F-test of all the nuisance regressors together, with partial models that test subsets of them;
a task model, an F-test of the task regressors.
"detrend": true adds Legendre polynomials to both models, to absorb slow drifts.
The F-tests compare each model with a model that has only the polynomials,
and \(R^2\) is the fraction of the variance left after detrending that the regressors explain.
A partial model is tested by comparing the full model with the full model minus that subset of regressors.
tedana selects the regressors by matching the column names to the regular expressions.
The nodes that use these models are near the end of the tree. First, a component is provisionally rejected if the nuisance model fits it significantly (p < 0.05) and explains more than half of its variance (\(R^2\) > 0.5):
{
"functionname": "dec_left_op_right",
"parameters": {
"if_true": "provisionalreject",
"if_false": "nochange",
"decide_comps": "all",
"op": "<",
"left": "pval nuisance model",
"right": 0.05
},
"kwargs": {
"op2": ">",
"left2": "R2stat nuisance model",
"right2": 0.5,
"log_extra_info": "If external regressors fit with p<0.05 and model R2>0.5 of the variance, then reject.",
"tag_if_true": "External regressors"
},
"_comment": "Provisionally rejecting components that fit to the external regressor noise model"
},
Three nodes that change nothing then tag the rejected components whose fit is driven by motion, CSF or physiological regressors. This is the one we added for the physiological regressors:
{
"functionname": "dec_left_op_right",
"parameters": {
"if_true": "nochange",
"if_false": "nochange",
"decide_comps": "provisionalreject",
"op": "<",
"left": "pval nuisance model",
"right": 0.05
},
"kwargs": {
"op2": ">",
"left2": "R2stat nuisance model",
"right2": 0.5,
"op3": "<",
"left3": "pval nuisance Physio partial model",
"right3": 0.05,
"tag_if_true": "Fits physiological external regressors"
},
"_comment": "Identical to the one above, & not changing classifications, but tagging if fits to physiological regressors"
},
Finally, a component that was going to be rejected is accepted instead if the task model fits it in the same way and it has enough TE-dependence (kappa above the kappa elbow):
{
"functionname": "dec_left_op_right",
"parameters": {
"if_true": "accepted",
"if_false": "nochange",
"decide_comps": ["provisionalreject"],
"op": "<",
"left": "pval task model",
"right": 0.05
},
"kwargs": {
"op2": ">",
"left2": "R2stat task model",
"right2": 0.5,
"op3": ">=",
"left3": "kappa",
"right3": "kappa_elbow_kundu",
"tag_if_true": "Fits task"
},
"_comment": "Keep if it fits task regressors and contains T2* signal, as defined by kappa>elbow"
},
The whole tree
{
"tree_id": "external_regressors_physio_motion_csf_task",
"info": "The demo_external_regressors_motion_task_models tree from tedana, with the regressors of the Multi-Echo fMRI Data Analysis book and a partial model for physiological regressors.",
"report": "This is based on the minimal criteria of the original MEICA decision tree \\citep{kundu2013integrated} without the more aggressive noise removal steps \\citep{dupre2021te}.",
"necessary_metrics": [
"kappa",
"rho",
"countsigFS0",
"countsigFT2",
"dice_FS0",
"dice_FT2",
"signal-noise_t",
"variance explained",
"pval nuisance model",
"pval task model",
"pval nuisance Motion partial model",
"pval nuisance CSF partial model",
"pval nuisance Physio partial model",
"R2stat nuisance model",
"R2stat task model"
],
"intermediate_classifications": ["provisionalaccept", "provisionalreject"],
"classification_tags": [
"Likely BOLD",
"Unlikely BOLD",
"Low variance",
"External regressors",
"Fits motion external regressors",
"Fits CSF external regressors",
"Fits physiological external regressors",
"Fits task"
],
"external_regressor_config": [
{
"regress_ID": "nuisance",
"info": "Fits all external nuisance regressors to a single model using an F statistic",
"report": "External nuisance regressors that fit to components using a linear model were rejected.",
"detrend": true,
"statistic": "F",
"regressors": ["^mot_.*$", "^csf_.*$", "^physio_.*$"],
"partial_models": {
"Motion": ["^mot_.*$"],
"CSF": ["^csf_.*$"],
"Physio": ["^physio_.*$"]
}
},
{
"regress_ID": "task",
"info": "Fits all task regressors to a single model using an F statistic",
"report": "Task regressors that fit to components using a linear model and have some T2* weighting were accepted even if they would have been rejected based on other criteria.",
"detrend": true,
"statistic": "F",
"regressors": ["^task_.*$"]
}
],
"nodes": [
{
"functionname": "manual_classify",
"parameters": {"new_classification": "unclassified", "decide_comps": "all"},
"kwargs": {"clear_classification_tags": true, "dont_warn_reclassify": true}
},
{
"functionname": "dec_left_op_right",
"parameters": {
"if_true": "provisionalreject",
"if_false": "nochange",
"decide_comps": "all",
"op": ">",
"left": "rho",
"right": "kappa"
},
"kwargs": {"tag_if_true": "Unlikely BOLD"}
},
{
"functionname": "dec_left_op_right",
"parameters": {
"if_true": "provisionalreject",
"if_false": "nochange",
"decide_comps": "all",
"op": ">",
"left": "countsigFS0",
"right": "countsigFT2"
},
"kwargs": {
"left2": "countsigFT2",
"op2": ">",
"right2": 0,
"tag_if_true": "Unlikely BOLD"
}
},
{
"functionname": "calc_median",
"parameters": {
"decide_comps": "all",
"metric_name": "variance explained",
"median_label": "varex"
}
},
{
"functionname": "dec_left_op_right",
"parameters": {
"if_true": "provisionalreject",
"if_false": "nochange",
"decide_comps": "all",
"op": ">",
"left": "dice_FS0",
"right": "dice_FT2"
},
"kwargs": {
"left2": "variance explained",
"op2": ">",
"right2": "median_varex",
"tag_if_true": "Unlikely BOLD"
}
},
{
"functionname": "dec_left_op_right",
"parameters": {
"if_true": "provisionalreject",
"if_false": "nochange",
"decide_comps": "all",
"op": ">",
"left": 0,
"right": "signal-noise_t"
},
"kwargs": {
"left2": "variance explained",
"op2": ">",
"right2": "median_varex",
"tag_if_true": "Unlikely BOLD"
}
},
{
"functionname": "calc_kappa_elbow",
"parameters": {"decide_comps": "all"}
},
{
"functionname": "calc_rho_elbow",
"parameters": {"decide_comps": "all"},
"kwargs": {
"subset_decide_comps": "unclassified",
"rho_elbow_type": "liberal"
}
},
{
"functionname": "dec_left_op_right",
"parameters": {
"if_true": "provisionalaccept",
"if_false": "provisionalreject",
"decide_comps": "unclassified",
"op": ">=",
"left": "kappa",
"right": "kappa_elbow_kundu"
},
"kwargs": {
"log_extra_info": "If kappa> kappa elbow and rho<rho elbow, provisional accept. Otherwise provisional reject",
"op2": "<",
"left2": "rho",
"right2": "rho_elbow_liberal",
"tag_if_true": "Likely BOLD"
}
},
{
"functionname": "dec_left_op_right",
"parameters": {
"if_true": "provisionalaccept",
"if_false": "nochange",
"decide_comps": "provisionalreject",
"op": ">",
"left": "kappa",
"right": "rho"
},
"kwargs": {
"log_extra_info": "If kappa>elbow and kappa>2*rho accept even if rho>elbow",
"right_scale": 2,
"op2": ">",
"left2": "kappa",
"right2": "kappa_elbow_kundu",
"tag_if_true": "Likely BOLD",
"tag_if_false": "Unlikely BOLD"
}
},
{
"functionname": "dec_left_op_right",
"parameters": {
"if_true": "provisionalreject",
"if_false": "nochange",
"decide_comps": "all",
"op": "<",
"left": "pval nuisance model",
"right": 0.05
},
"kwargs": {
"op2": ">",
"left2": "R2stat nuisance model",
"right2": 0.5,
"log_extra_info": "If external regressors fit with p<0.05 and model R2>0.5 of the variance, then reject.",
"tag_if_true": "External regressors"
},
"_comment": "Provisionally rejecting components that fit to the external regressor noise model"
},
{
"functionname": "dec_left_op_right",
"parameters": {
"if_true": "nochange",
"if_false": "nochange",
"decide_comps": "provisionalreject",
"op": "<",
"left": "pval nuisance model",
"right": 0.05
},
"kwargs": {
"op2": ">",
"left2": "R2stat nuisance model",
"right2": 0.5,
"op3": "<",
"left3": "pval nuisance Motion partial model",
"right3": 0.05,
"tag_if_true": "Fits motion external regressors"
},
"_comment": "Identical to the one above, & not changing classifications, but tagging if fits to motion regressors"
},
{
"functionname": "dec_left_op_right",
"parameters": {
"if_true": "nochange",
"if_false": "nochange",
"decide_comps": "provisionalreject",
"op": "<",
"left": "pval nuisance model",
"right": 0.05
},
"kwargs": {
"op2": ">",
"left2": "R2stat nuisance model",
"right2": 0.5,
"op3": "<",
"left3": "pval nuisance CSF partial model",
"right3": 0.05,
"tag_if_true": "Fits CSF external regressors"
},
"_comment": "Identical to the one above, & not changing classifications, but tagging if fits to CSF regressors"
},
{
"functionname": "dec_left_op_right",
"parameters": {
"if_true": "nochange",
"if_false": "nochange",
"decide_comps": "provisionalreject",
"op": "<",
"left": "pval nuisance model",
"right": 0.05
},
"kwargs": {
"op2": ">",
"left2": "R2stat nuisance model",
"right2": 0.5,
"op3": "<",
"left3": "pval nuisance Physio partial model",
"right3": 0.05,
"tag_if_true": "Fits physiological external regressors"
},
"_comment": "Identical to the one above, & not changing classifications, but tagging if fits to physiological regressors"
},
{
"functionname": "dec_left_op_right",
"parameters": {
"if_true": "accepted",
"if_false": "nochange",
"decide_comps": ["provisionalreject"],
"op": "<",
"left": "pval task model",
"right": 0.05
},
"kwargs": {
"op2": ">",
"left2": "R2stat task model",
"right2": 0.5,
"op3": ">=",
"left3": "kappa",
"right3": "kappa_elbow_kundu",
"tag_if_true": "Fits task"
},
"_comment": "Keep if it fits task regressors and contains T2* signal, as defined by kappa>elbow"
},
{
"functionname": "dec_variance_lessthan_thresholds",
"parameters": {
"if_true": "accepted",
"if_false": "nochange",
"decide_comps": "provisionalreject"
},
"kwargs": {
"var_metric": "variance explained",
"single_comp_threshold": 0.1,
"all_comp_threshold": 1.0,
"tag_if_true": "Low variance"
}
},
{
"functionname": "manual_classify",
"parameters": {"new_classification": "accepted", "decide_comps": "provisionalaccept"},
"kwargs": {"tag": "Likely BOLD"}
},
{
"functionname": "manual_classify",
"parameters": {
"new_classification": "rejected",
"decide_comps": ["provisionalreject", "unclassified"]
},
"kwargs": {"tag": "Unlikely BOLD"}
}
]
}
Running tedana#
To see what the external regressors change, we need a tree that does everything else the same way.
The demonstration tree is not simply the minimal tree with extra nodes:
its early nodes only provisionally reject components, and it can rescue components with high kappa.
So the baseline, decision_trees/baseline_tree.json,
is our tree without the external_regressor_config, the five nodes that use it, and the metrics and tags that only those nodes need.
The baseline tree
{
"tree_id": "external_regressors_physio_motion_csf_task_without_external",
"info": "The external_regressors_physio_motion_csf_task tree, without the external regressor models and the nodes that use them.",
"report": "This is based on the minimal criteria of the original MEICA decision tree \\citep{kundu2013integrated} without the more aggressive noise removal steps \\citep{dupre2021te}.",
"necessary_metrics": [
"kappa",
"rho",
"countsigFS0",
"countsigFT2",
"dice_FS0",
"dice_FT2",
"signal-noise_t",
"variance explained"
],
"intermediate_classifications": ["provisionalaccept", "provisionalreject"],
"classification_tags": [
"Likely BOLD",
"Unlikely BOLD",
"Low variance"
],
"nodes": [
{
"functionname": "manual_classify",
"parameters": {"new_classification": "unclassified", "decide_comps": "all"},
"kwargs": {"clear_classification_tags": true, "dont_warn_reclassify": true}
},
{
"functionname": "dec_left_op_right",
"parameters": {
"if_true": "provisionalreject",
"if_false": "nochange",
"decide_comps": "all",
"op": ">",
"left": "rho",
"right": "kappa"
},
"kwargs": {"tag_if_true": "Unlikely BOLD"}
},
{
"functionname": "dec_left_op_right",
"parameters": {
"if_true": "provisionalreject",
"if_false": "nochange",
"decide_comps": "all",
"op": ">",
"left": "countsigFS0",
"right": "countsigFT2"
},
"kwargs": {
"left2": "countsigFT2",
"op2": ">",
"right2": 0,
"tag_if_true": "Unlikely BOLD"
}
},
{
"functionname": "calc_median",
"parameters": {
"decide_comps": "all",
"metric_name": "variance explained",
"median_label": "varex"
}
},
{
"functionname": "dec_left_op_right",
"parameters": {
"if_true": "provisionalreject",
"if_false": "nochange",
"decide_comps": "all",
"op": ">",
"left": "dice_FS0",
"right": "dice_FT2"
},
"kwargs": {
"left2": "variance explained",
"op2": ">",
"right2": "median_varex",
"tag_if_true": "Unlikely BOLD"
}
},
{
"functionname": "dec_left_op_right",
"parameters": {
"if_true": "provisionalreject",
"if_false": "nochange",
"decide_comps": "all",
"op": ">",
"left": 0,
"right": "signal-noise_t"
},
"kwargs": {
"left2": "variance explained",
"op2": ">",
"right2": "median_varex",
"tag_if_true": "Unlikely BOLD"
}
},
{
"functionname": "calc_kappa_elbow",
"parameters": {"decide_comps": "all"}
},
{
"functionname": "calc_rho_elbow",
"parameters": {"decide_comps": "all"},
"kwargs": {
"subset_decide_comps": "unclassified",
"rho_elbow_type": "liberal"
}
},
{
"functionname": "dec_left_op_right",
"parameters": {
"if_true": "provisionalaccept",
"if_false": "provisionalreject",
"decide_comps": "unclassified",
"op": ">=",
"left": "kappa",
"right": "kappa_elbow_kundu"
},
"kwargs": {
"log_extra_info": "If kappa> kappa elbow and rho<rho elbow, provisional accept. Otherwise provisional reject",
"op2": "<",
"left2": "rho",
"right2": "rho_elbow_liberal",
"tag_if_true": "Likely BOLD"
}
},
{
"functionname": "dec_left_op_right",
"parameters": {
"if_true": "provisionalaccept",
"if_false": "nochange",
"decide_comps": "provisionalreject",
"op": ">",
"left": "kappa",
"right": "rho"
},
"kwargs": {
"log_extra_info": "If kappa>elbow and kappa>2*rho accept even if rho>elbow",
"right_scale": 2,
"op2": ">",
"left2": "kappa",
"right2": "kappa_elbow_kundu",
"tag_if_true": "Likely BOLD",
"tag_if_false": "Unlikely BOLD"
}
},
{
"functionname": "dec_variance_lessthan_thresholds",
"parameters": {
"if_true": "accepted",
"if_false": "nochange",
"decide_comps": "provisionalreject"
},
"kwargs": {
"var_metric": "variance explained",
"single_comp_threshold": 0.1,
"all_comp_threshold": 1.0,
"tag_if_true": "Low variance"
}
},
{
"functionname": "manual_classify",
"parameters": {"new_classification": "accepted", "decide_comps": "provisionalaccept"},
"kwargs": {"tag": "Likely BOLD"}
},
{
"functionname": "manual_classify",
"parameters": {
"new_classification": "rejected",
"decide_comps": ["provisionalreject", "unclassified"]
},
"kwargs": {"tag": "Unlikely BOLD"}
}
]
}
We run tedana with the baseline tree first.
tedana keeps the logs and reports of earlier runs in its output folder, so we start each run from an empty folder.
baseline_dir = os.path.join(out_dir, "tedana-baseline")
if os.path.isdir(baseline_dir):
shutil.rmtree(baseline_dir)
workflows.tedana_workflow(
data["echo_files"],
data["echo_times"],
out_dir=baseline_dir,
mask=data["mask"],
prefix=prefix,
dummy_scans=n_dummy,
tedpca="mdl",
tree=os.path.abspath("decision_trees/baseline_tree.json"),
fixed_seed=42,
overwrite=True,
)
Then we run it again with our tree and the external regressors.
To compare the two classifications, we reuse the ICA decomposition of the first run with mixing_file, so both trees classify the same components.
external_dir = os.path.join(out_dir, "tedana-external")
if os.path.isdir(external_dir):
shutil.rmtree(external_dir)
workflows.tedana_workflow(
data["echo_files"],
data["echo_times"],
out_dir=external_dir,
mask=data["mask"],
prefix=prefix,
dummy_scans=n_dummy,
tree=os.path.abspath("decision_trees/external_regressors_tree.json"),
external_regressors=external_file,
mixing_file=os.path.join(baseline_dir, f"{prefix}_desc-ICA_mixing.tsv"),
fixed_seed=42,
overwrite=True,
)
Comparing the classifications#
The metrics table now has a column for each statistic of each model.
metrics_baseline = pd.read_table(os.path.join(baseline_dir, f"{prefix}_desc-tedana_metrics.tsv"), index_col="Component")
metrics_external = pd.read_table(os.path.join(external_dir, f"{prefix}_desc-tedana_metrics.tsv"), index_col="Component")
print("\n".join(c for c in metrics_external.columns if c not in metrics_baseline.columns))
Fstat nuisance model
Fstat nuisance Motion partial model
Fstat nuisance CSF partial model
Fstat nuisance Physio partial model
pval nuisance model
pval nuisance Motion partial model
pval nuisance CSF partial model
pval nuisance Physio partial model
R2stat nuisance model
R2stat nuisance Motion partial model
R2stat nuisance CSF partial model
R2stat nuisance Physio partial model
Fstat task model
pval task model
R2stat task model
external regressor correlation physio_card_cos1
external regressor correlation physio_card_sin1
external regressor correlation physio_card_cos2
external regressor correlation physio_card_sin2
external regressor correlation physio_resp_cos1
external regressor correlation physio_resp_sin1
external regressor correlation physio_resp_cos2
external regressor correlation physio_resp_sin2
external regressor correlation physio_rv
external regressor correlation physio_hr
external regressor correlation csf_ventricles
external regressor correlation mot_trans_x
external regressor correlation mot_trans_x_derivative1
external regressor correlation mot_trans_y
external regressor correlation mot_trans_y_derivative1
external regressor correlation mot_trans_z
external regressor correlation mot_trans_z_derivative1
external regressor correlation mot_rot_x
external regressor correlation mot_rot_x_derivative1
external regressor correlation mot_rot_y
external regressor correlation mot_rot_y_derivative1
external regressor correlation mot_rot_z
external regressor correlation mot_rot_z_derivative1
external regressor correlation task_motor
external regressor correlation task_visual
external regressor correlation task_auditory
| without external regressors | external regressors | |
|---|---|---|
| accepted components | 25.0 | 21.0 |
| rejected components | 32.0 | 36.0 |
| variance explained by rejected components (%) | 54.4 | 77.0 |
These components changed classification:
| without external regressors | external regressors | tags | kappa | rho | variance explained | R2 nuisance | R2 task | |
|---|---|---|---|---|---|---|---|---|
| Component | ||||||||
| ICA_00 | accepted | rejected | External regressors,Fits physiological externa... | 31.157 | 16.391 | 0.203 | 0.507 | 0.065 |
| ICA_08 | accepted | rejected | Fits motion external regressors,External regre... | 49.821 | 19.640 | 1.732 | 0.722 | 0.055 |
| ICA_25 | accepted | rejected | Fits motion external regressors,External regre... | 43.156 | 18.452 | 18.744 | 0.974 | 0.101 |
| ICA_32 | accepted | rejected | Fits motion external regressors,External regre... | 43.399 | 15.520 | 1.962 | 0.568 | 0.051 |
The tags show why the external regressors mattered for each rejected component:
classification_tags
Unlikely BOLD 37
External regressors 26
Likely BOLD 25
Fits physiological external regressors 25
Fits motion external regressors 22
Fits CSF external regressors 13
Name: components, dtype: int64
Fig. 71 Each component’s fit to the nuisance and task models. The size of each point is the variance the component explains, and the dashed lines are the \(R^2\) thresholds used by the tree.#
Finally, we look at the time series of some components next to the regressors that fit them:
the components that the nuisance model changed, and, for comparison, the three accepted components that the task model fits best.
To match what tedana tests, we remove the Legendre polynomials from both the component and the regressors before fitting.
Fig. 72 Time series of the components whose classification changed (with the fit of the nuisance model, red) and of the three accepted components that the task model fits best (with the fit of the task model, green), after removing the Legendre polynomials.#
Final remarks#
Each external regressor adds a degree of freedom to the F-tests, and a model with many regressors fits noise by chance. The \(R^2\) threshold in the tree protects against this, but keep the models small and the regressors meaningful.
The partial-model tags only require p < 0.05 for a subset of regressors, on top of a full model that already fits well. With ten physiological regressors, that is an easy bar to clear, so read the tags as hints rather than diagnoses.
Slow regressors, like the motion parameters themselves, can fit slow fluctuations that remain after detrending. Using only the derivatives of the motion parameters, or a higher detrending order (an integer for
"detrend"), makes the nuisance model more specific.Regressors that are correlated with the task, like head motion during tapping, will make the nuisance model fit task-related components. The task model in this tree is there to rescue those components, as long as they are TE-dependent.
The thresholds in the demonstration trees are not validated. Look at the components the external regressors change, as we did above, before you rely on a tree.
For more about decision trees and external regressors, see the
tedana documentation on building decision trees.
The denoised data from the second run are used in Task Analysis of Multi-Echo Data.