ROI
This file contains functions and classes related to the extraction of timecourses.
- class fmriproc.roi.DateTimeEncoder(*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)[source]
Bases:
JSONEncoder- default(obj)[source]
Implement this method in a subclass such that it returns a serializable object for
o, or calls the base implementation (to raise aTypeError).For example, to support arbitrary iterators, you could implement default like this:
def default(self, o): try: iterable = iter(o) except TypeError: pass else: return list(iterable) # Let the base class default method raise the TypeError return super().default(o)
- class fmriproc.roi.ExtractFromROIs[source]
Bases:
objectExtract timecourses given a list of ROIs from functional files. Assumes the ROI and functional files are in the same space, e.g., both in native functional space (in case of single-subject processing), or all in MNI-space (in which case multi- subject processing is permitted). If the ROIs represent float data (e.g., zstat/tstat), it will extract the 15 highest voxels within that ROI. If ROI is binary, all voxels will be used. See also
fmriproc.roi.ExtractFromROIs.extract_data().- Parameters:
func (str, nibabel.Nifti1Image, nibabel.GiftiImage, np.ndarray) – Input functional data, either a string representing a path, a nibabel.Nifti1Image-object, a nibabel.GiftiImage-object, or a numpy array
rois (list, str, optional) – List of ROIs, either strings representing a path, nibabel.Nifti1Image-objects, or a numpy arrays or a directory con- taining a bunch of ROIs. Use the “filters=”-flag to further specify the input.
filters (str, list, optional) – additional filters to search for ROI files. For instance, you have specified a directory with “–rois /path/to/ROIs”, but that directory contains a bunch of ROIs that you’re not necessarily interested in. If you’re only interested in the files starting with “conv-*”, you can specify that here.
roi_names – If empty, we will try to derive the ROI name from the filename (if they are strings). E.g., from “bin.thr.ACC_L.nii.gz”, it would extract the last elements after “.”, so “ACC_L”. If the inputs are not strings, we will default to “roi_{}”, so it’s highly encouraged to use the roi_names-input for non-string functional files.
list – If empty, we will try to derive the ROI name from the filename (if they are strings). E.g., from “bin.thr.ACC_L.nii.gz”, it would extract the last elements after “.”, so “ACC_L”. If the inputs are not strings, we will default to “roi_{}”, so it’s highly encouraged to use the roi_names-input for non-string functional files.
str – If empty, we will try to derive the ROI name from the filename (if they are strings). E.g., from “bin.thr.ACC_L.nii.gz”, it would extract the last elements after “.”, so “ACC_L”. If the inputs are not strings, we will default to “roi_{}”, so it’s highly encouraged to use the roi_names-input for non-string functional files.
optional – If empty, we will try to derive the ROI name from the filename (if they are strings). E.g., from “bin.thr.ACC_L.nii.gz”, it would extract the last elements after “.”, so “ACC_L”. If the inputs are not strings, we will default to “roi_{}”, so it’s highly encouraged to use the roi_names-input for non-string functional files.
ses (int, optional) – Specify session ID; will be read from filename if possible using
lazyfmri.utils.split_bids_components()task (str, optional) – Specify task ID; will be read from filename if possible using
lazyfmri.utils.split_bids_components()TR (int, optional) – Repetition time to use for the dataframe formation, by default 2
subject (int, optional) – Subject ID to use for the dataframe formation, by default 1
verbose (bool, optional) – Make some noise, by default False
**kwargs (dict) – Same as
fmriproc.roi.ExtractFromROIs.extract_data()
Example
from fmriproc import roi obj = roi.ExtractFromROIs( "/path/to/fmriprep/sub-01/ses-1/func/sub-01_ses-1_task-task1_space-MNI152NLin6Asym_bold.nii.gz", rois=[ "/path/to/rois/bin.thr.space-MNI152NLin6Asym.ACC_L.nii.gz, "/path/to/rois/bin.thr.space-MNI152NLin6Asym.ACC_R.nii.gz "/path/to/rois/bin.thr.space-MNI152NLin6Asym.PCC_L.nii.gz "/path/to/rois/bin.thr.space-MNI152NLin6Asym.PCC_R.nii.gz ], TR=1.5, subject="01" )
- static extract_data()[source]
Extractor function depending on ROI input. If the ROI represents a zstat/tstat file (or file with float) values, we will select by default the 15 highest values within the roi. To select the 15 lowest, set highest=False. To change the number of voxels to extract, use the nr-input.
- Parameters:
func (np.ndarray) – 2D timeseries representing the functional data (voxels, time)
roi (np.ndarray) – int/float np.ndarray representing the ROI data (voxels,)
nr (int, optional) – number of voxels to extract from data in case the input is float, by default 15. if the input is binary, we will take the entire ROI.
bsl (int, optional) – amount of time to use to calculate baseline for percent signal change conversion, by default 15s.
highest (bool, optional) – If True, we select nr HIGHEST voxels from roi. If False, we select the nr LOWEST. By default True
psc (bool, optional) – Normalize to percent signal change. Default is True.
zscore (bool, optional) – Normalize using z-scoring. Default = False
- Returns:
extracted data (either normalized or not)
- Return type:
np.ndarray
- static load_file(file)[source]
Load file based on whether it is a string, numpy array, or nibabel.Nifti1Image object
- main_extractor(sep='_', **kwargs)[source]
Loop through functional files to extract data using
fmriproc.roi.ExtractFromROIs.extract_data()
- class fmriproc.roi.ExtractSubjects[source]
Bases:
ExtractFromROIsLoop through all subjects in a FEAT-directory to extract timecourses from a set of ROIs using
fmriproc.roi.ExtractFromROIs().- Parameters:
ft_dir (str) – path to 1st level FEAT, fMRIprep, or Pybest directory. For FEAT, We’re explicitly searching for the “filtered_func_data” files; for fMRIprep, we will look for “*desc-preproc_bold.nii.gz” using the native functional files as default. Use e.g., space=MNI152NLin6Asym to select FSL’s MNI files. For Pybest, we will either look in the “unzscored”-folder if you want surface-based files (e.g., ‘fsnative’ or ‘fsaverage’) for “*desc-denoised_bold.npy”. For volumetric files, we will look in the “masked” folder for “*desc-denoised_bold.nii.gz”. For both fMRIprep and Pybest, you can select specific tasks with task=[“task1”, “task3”]. Otherwise all files will be considered. This can be particularly problematic for surface-based files from Pybest, as there’s extra files being outputted by Pybest that make selection using these criteria difficult. For instance, if you have multiple runs, it saves out an average without “run”-identifier. However, it outputs the same file if you only have a single runs..
func (str, list, optional) – Reuse existing csv-file (<output_dir>/<base_name>/<base_name>_desc-tcs.csv)
excl_subjs (list, optional) – Exclude particular subjects present in the ft_dir, by default None
incl_subjs (str, optional) – Include particular subjects present in the ft_dir, by default None
n_jobs (int, optional) – Number of jobs to use for the extraction, by default set to the number of subjects present
verbose (bool, optional) – Make some noise, by default False
in_file (str, optional) – Directly specify a 4D file to extract timecourses from, rather than looking in predefined folders such as fMRIPrep, FEAT, or Pybest..
**kwargs (dict) – Same as
fmriproc.roi.ExtractFromROIs.extract_data()
- extract_single_subject(files, **kwargs)[source]
Wrapper around
fmriproc.roi.ExtractFromROIsto extract data from a single subject
- extract_subjects(**kwargs)[source]
Wrapper around
fmriproc.roi.ExtractSubjects.extract_single_subject()to loop through subjects
- class fmriproc.roi.FullExtractionPipeline[source]
Bases:
ExtractSubjectsGiven a list of ROIs, extract the timecourses from all subjects’ preprocessed data in a level1 feat folder. If these ROIs are binary, the timecourses will be averaged across this entire area. If the ROIs are values (e.g., z-stat values), the n (default = 15) highest (default) /lowest (–lowest) values will be selected and averaged. These timecourses are entered in a deconvolution model using the canonical HRF and its derivatives as basis sets (default). From this model, parameters are extracted from the individual basis sets as well as the full HRF. Results are plotted and stored in a figure where the rows denote EVs (stimulus conditions. There’s a couple of default settings that you can generally leave alone, but there’s flags to changed them nonetheless.
- Parameters:
proj_dir (str, optional) – Root of the project folder, defaults to os.environ.get(“DIR_DATA_HOME”). Mainly necessary for fetching onset files.
order (list, optional) – If performing deconvolution, a plot can be generated. This flag sets the order (rows). By default, we’ll take the order in the onset dataframe (unsorted).
peak (int, optional) – Deconvolution can sometimes cause exotic HRF shapes. This flag specifically tells the algorithm to select the first peak while extracting parameters.
dec_kws (dict, optional) –
Extra parameters for the deconvolution, by default:
dec_defaults = { "interval": [-2,25], "basis_sets": "canonical_hrf_with_time_derivative_dispersion", "TR": 2 }
The format should be as follows (different parameters comma-separated, and parameter-value pair separated by ‘=’): “–dec <parameter1>=<value1>,<parameter2>=<value2>,<parameterX>=<valueX>” In case you want to change the interval over which the profiles are deconvolved, use “interval=t1>t2” (separated by ‘>’).
plot_kws (dict, optional) –
Set parameters for plotting. The idea is similar to the “–dec” flag. The defaults are set to:
plot_defaults = { "line_width": 3, # thickness of the lines of profiles "y_dec": 2, # number of decimals on y-axes (ensures correct spacing) "add_hline": 0, # horizontal line at 0 "sns_offset": 4, # distance between y-axis and first bar in bar plot "error": "se", # error type (standard error of mean) for bar plot "cmap": "Set1" # colormap Set1 }
output_dir (str, optional) – path to output directory (default = $DIR_DATA_DERIV/roi_extract)
output_base (str, optional) – basename for output. Will also be used to create a subfolder in <output_dir>. “_desc-<description>” will be appended automatically. Defaults to “roi_extract” (very insightful, I know..)
verbose (bool, optional) – print progress to the terminal
pos_neg (bool, optional) – Switch to different plotting function, by default False.
do_fit (bool, optional) – If False, we’ll only extract the data and will not perform deconvolution, by default True
- generate_plot(include_pars=['magnitude', 'time_to_peak', '1st_deriv_time_to_peak', '2nd_deriv_time_to_peak', 'rise_slope', 'positive_area'], time_col='time', write_files=True, cdict={}, subjects=False, fc=1, **kwargs)[source]
- class fmriproc.roi.ROI[source]
Bases:
objectGenerate a mask from FreeSurfer atlases or Label-files. The input can be a string/list of strings representing ROIs present in FreeSurfer’s aparc-files or in the ‘label’ folder. In case the input should be read from the segmentation files, set mask_type=”aparc” (default). If they are label-files, set mask_type=”surf”. The class rests on functions from the cxutils-toolbox, and will through an error if it is not installed.
- Parameters:
roi (str, list) – String or list of strings representing ROIs in the aparc-files or files from the label-folder as per the output of FreeSurfer. For instance, V1_exvivo.thresh. By default, both hemispheres will be considered, so ?h. can be omit- ted.
mask_type (str, optional) – Type of segmentation to use, by default “aparc”. “aparc” represents the volumetric segmentations, whereas “surf” will represent the surface based ROIs (e.g., files in ‘labels’-folder)
subject (str, optional) – FreeSurfer-subject to use, by default “fsaverage”
- Returns:
The actual masks will be stored as attribute “self.roi_mask”, which can be accesss with
fmriproc.image.ROI.return_mask()- Return type:
np.ndarray
Example
# get motor cortex from FSAverage from fmriproc import roi some_roi = roi.ROI( "precentral", mask_type="surf", subject="fsaverage" ).return_mask()
# get V1 from sub-01 from fmriproc import roi some_roi = roi.ROI( "V1_exvivo.thresh", mask_type="surf", subject="sub-01" ).return_mask()
# get precuneus from sub-01 from fmriproc import roi some_roi = roi.ROI( "inferiorparietal", mask_type="aparc", subject="sub-01" ).return_mask()
- aparc_mask()[source]
Generate mask from label-file using
fmriproc.roi.ROI.make_roi_mask()