Developers - API

The NiPreps community and contributing guidelines

PETPrep is a NiPreps application, and abides by the NiPreps Community guidelines. Please, make sure you have read and understood all the documentation provided in the NiPreps portal before you get started.

Setting up your development environment

We believe that PETPrep must be free to use, inspect, and critique. Correspondingly, you should be free to modify our software to improve it or adapt it to new use cases and we especially welcome contributions to improve it or its documentation.

We actively direct efforts into making the scrutiny and improvement processes as easy as possible. As part of such efforts, we maintain some tips and guidelines for developers to help minimize your burden if you want to modify the software.

Internal configuration system

A Python module to maintain unique, run-wide PETPrep settings.

This module implements the memory structures to keep a consistent, singleton config. Settings are passed across processes via filesystem, and a copy of the settings for each run and subject is left under <petprep_dir>/sub-<participant_id>/log/<run_unique_id>/petprep.toml. Settings are stored using ToML. The module has a to_filename() function to allow writing out the settings to hard disk in ToML format, which looks like:

Example file representation of PETPrep settings.
[environment]
cpu_count = 8
exec_env = "posix"
free_mem = 2.2
overcommit_policy = "heuristic"
overcommit_limit = "50%"
nipype_version = "1.5.0"
templateflow_version = "0.4.2"
version = "0.0.1"

[execution]
bids_dir = "pet/"
bids_description_hash = "5d42e27751bbc884eca87cb4e62b9a0cca0cd86f8e578747fe89b77e6c5b21e5"
boilerplate_only = false
fs_license_file = "/opt/freesurfer/license.txt"
fs_subjects_dir = "/opt/freesurfer/subjects"
log_dir = "/home/oesteban/tmp/petprep-ds005/out/petprep/logs"
log_level = 40
low_mem = false
md_only_boilerplate = false
notrack = true
output_dir = "/tmp"
output_spaces = "MNI152NLin2009cAsym:res-2 MNI152NLin2009cAsym:res-native fsaverage:den-10k fsaverage:den-30k"
reports_only = false
run_uuid = "20200306-105302_d365772b-fd60-4741-a722-372c2f558b50"
participant_label = [ "01",]
processing_groups = [ "sub-01",]
templateflow_home = "~/.cache/templateflow"
work_dir = "work/"
write_graph = false

[workflow]
anat_only = false
aroma_err_on_warn = false
aroma_melodic_dim = -200
pet2anat_dof = 6
pet2anat_init = "auto"
fmap_bspline = false
force = []
force_syn = false
hires = false
ignore = []
longitudinal = false
medial_surface_nan = false
project_goodvoxels = false
regressors_all_comps = false
regressors_dvars_th = 1.5
regressors_fd_th = 0.5
run_reconall = true
skull_strip_fixed_seed = false
skull_strip_template = "OASIS30ANTs"
subject_anatomical_reference = "first-lex"
t2s_coreg = false
use_aroma = false

[nipype]
crashfile_format = "txt"
get_linked_libs = false
memory_gb = 32
nprocs = 8
omp_nthreads = 8
plugin = "MultiProc"
resource_monitor = false
stop_on_first_crash = false

[nipype.plugin_args]
maxtasksperchild = 1
raise_insufficient = false

[execution.bids_filters.t1w]
reconstruction = "<Query.NONE: 1>"

[execution.bids_filters.t2w]
reconstruction = "<Query.NONE: 1>"

This config file is used to pass the settings across processes, using the load() function.

Configuration sections

class petprep.config.environment[source]

Read-only options regarding the platform and environment.

Crawls runtime descriptive settings (e.g., default FreeSurfer license, execution environment, nipype and PETPrep versions, etc.). The environment section is not loaded in from file, only written out when settings are exported. This config section is useful when reporting issues, and these variables are tracked whenever the user does not opt-out using the --notrack argument.

cpu_count = 2

Number of available CPUs.

exec_docker_version = None

Version of Docker Engine.

exec_env = 'posix'

A string representing the execution platform.

free_mem = 6.0

Free memory at start.

nipype_version = '1.11.0'

Nipype’s current version.

overcommit_limit = '50%'

Linux’s kernel virtual memory overcommit limits.

overcommit_policy = 'heuristic'

Linux’s kernel virtual memory overcommit policy.

templateflow_version = '25.1.2'

The TemplateFlow client version installed.

version = '0.0.8'

PETPrep’s version.

class petprep.config.execution[source]

Configure run-level settings.

aggr_ses_reports = None

Maximum number of sessions aggregated in one subject’s visual report.

bids_database_dir = None

Path to the directory containing SQLite database indices for the input BIDS dataset.

bids_description_hash = None

Checksum (SHA256) of the dataset_description.json of the BIDS dataset.

bids_dir = None

An existing path to the dataset, which must be BIDS-compliant.

bids_filters = None

A dictionary of BIDS selection filters.

boilerplate_only = False

Only generate a boilerplate.

combine_runs = False

Combine multiple runs for each PET series before preprocessing.

country_code = 'CAN'

Country ISO code used by carbon trackers.

A dictionary of dataset links to be used to track Sources in sidecars.

debug = []

Debug mode(s).

derivatives = {}

Path(s) to search for pre-computed derivatives

fs_license_file = None

An existing file containing a FreeSurfer license.

fs_subjects_dir = None

FreeSurfer’s subjects directory.

classmethod init()[source]

Create a new BIDS Layout accessible with layout.

layout = None

A BIDSLayout object, see init().

log_dir = None

The path to a directory that contains execution logs.

log_level = 25

Output verbosity.

low_mem = None

Utilize uncompressed NIfTIs and other tricks to minimize memory allocation.

md_only_boilerplate = False

Do not convert boilerplate from MarkDown to LaTex and HTML.

notrack = False

Do not collect telemetry information for PETPrep.

output_dir = None

Folder where derivatives will be stored.

output_layout = None

Layout of derivatives within output_dir.

output_spaces = None

List of (non)standard spaces designated (with the --output-spaces flag of the command line) as spatial references for outputs.

participant_label = None

List of participant identifiers that are to be preprocessed.

petprep_dir = None

Root of PETPrep BIDS Derivatives dataset. Depends on output_layout.

processing_groups = None

List of subject/session groups to preprocess.

rec_label = None

List of reconstruction identifiers that are to be preprocessed.

reports_only = False

Only build the reports, based on the reportlets found in a cached working directory.

run_label = None

List of run identifiers that are to be preprocessed.

run_uuid = '20260604-181806_31408c18-1996-4c67-ae00-d01987d7686f'

Unique identifier of this particular run.

session_label = None

List of session identifiers that are to be preprocessed.

sloppy = False

Run in sloppy mode (meaning, suboptimal parameters that minimize run-time).

task_id = None

Select a particular task from all available in the dataset.

templateflow_home = PosixPath('/home/docs/.cache/templateflow')[source]

The root folder of the TemplateFlow client.

tracer_label = None

List of tracer identifiers that are to be preprocessed.

track_carbon = False

Tracks power draws using CodeCarbon package.

work_dir = PosixPath('/home/docs/checkouts/readthedocs.org/user_builds/petprep/checkouts/latest/docs/work')[source]

Path to a working directory where intermediate results will be available.

write_graph = False

Write out the computational graph corresponding to the planned preprocessing.

class petprep.config.workflow[source]

Configure the particular execution graph of this workflow.

anat_only = False

Execute the anatomical preprocessing only.

anatref: str = 'auto'

Anatomical reference for PET-to-T1w registration ('t1w', 'nu', or 'auto').

cifti_output = None

Generate HCP Grayordinates, accepts either '91k' (default) or '170k'.

force = None

Force particular steps for PETPrep.

fs_no_resume = None

Adjust pipeline to reuse base template of existing longitudinal freesurfer

hires = False

Allow FreeSurfer recon-all to use the -hires flag for submillimeter T1w.

hmc_fix_frame: bool = False

Whether to fix the reference frame during head-motion estimation.

hmc_fwhm: float = 10.0

FWHM for Gaussian smoothing prior to head-motion estimation.

hmc_init_frame: int | str | None = 'auto'

Index of initial frame for head-motion estimation (‘auto’ selects highest uptake).

hmc_off: bool = False

Disable head-motion correction and keep data uncorrected.

hmc_start_time: float = 120.0

Time point (in seconds) at which head-motion estimation starts.

ignore = None

Ignore particular steps for PETPrep.

level = None

Level of preprocessing to complete. One of [‘minimal’, ‘resampling’, ‘full’].

longitudinal = False

Deprecated alias for subject_anatomical_reference == 'unbiased'.

medial_surface_nan = None

Fill medial surface with NaNs when sampling.

pet2anat_crop: bool = True

Crop the anatomical reference before PET-to-anatomical registration.

pet2anat_crop_fallback: bool = True

Try uncropped anatomical registration when auto-mode cropped registration scores poorly.

pet2anat_crop_fallback_threshold: float = -0.05

Similarity threshold for triggering uncropped anatomical registration fallback.

pet2anat_dof = None

Degrees of freedom of the PET-to-anatomical registration steps.

pet2anat_init = 'auto'

Initial transform for PET-to-anatomical registration.

pet2anat_method: str = 'auto'

PET-to-anatomical registration method (mri_coreg, robust, ants, or auto).

pet2anat_method_specified: bool = False

Flag indicating whether --pet2anat-method was explicitly provided.

petref: str = 'auto'

Strategy for building the PET reference ('template', 'twa', 'sum', 'first5min' or 'auto').

petref_specified: bool = False

Flag indicating whether --petref was explicitly provided.

project_goodvoxels = False

Exclude voxels with locally high coefficient of variation from sampling.

pvc_method: str | None = None

Algorithm used for partial volume correction.

pvc_psf: tuple | None = None

Point spread function (PSF) FWHM in mm for PVC.

pvc_tool: str | None = None

Tool used for partial volume correction.

ref_mask_index: tuple | None = None

Tuple of label indices used to build the reference mask.

ref_mask_name: str | None = None

Name of the reference region mask to generate.

regressors_all_comps = None

Return all CompCor components.

regressors_dvars_th = None

Threshold for DVARS.

regressors_fd_th = None

Threshold for FD.

run_msmsulc = True

Run Multimodal Surface Matching surface registration.

run_reconall = True

Run FreeSurfer’s surface reconstruction.

seg = 'gtm'

Segmentation approach (‘gtm’, ‘brainstem’, ‘thalamicNuclei’, ‘hippocampusAmygdala’, ‘wm’, ‘aparcaseg’, ‘raphe’, ‘limbic’).

skull_strip_fixed_seed = False

Fix a seed for skull-stripping.

skull_strip_t1w = 'force'

Skip brain extraction of the T1w image (default is force, meaning that PETPrep will run brain extraction of the T1w).

skull_strip_template = 'OASIS30ANTs'

Change default brain extraction template.

spaces = None

Keeps the SpatialReferences instance keeping standard and nonstandard spaces.

subject_anatomical_reference = 'first-lex'

Method to produce the subject anatomical reference.

class petprep.config.nipype[source]

Nipype settings.

crashfile_format = 'txt'

The file format for crashfiles, either text (txt) or pickle (pklz).

get_linked_libs = False

Run NiPype’s tool to enlist linked libraries for every interface.

classmethod get_plugin()[source]

Format a dictionary for Nipype consumption.

classmethod init()[source]

Set NiPype configurations.

memory_gb = None

Estimation in GB of the RAM this workflow can allocate at any given time.

nprocs = 2

Number of processes (compute tasks) that can be run in parallel (multiprocessing only).

omp_nthreads = None

Number of CPUs a single process can access for multithreaded execution.

plugin = 'MultiProc'

NiPype’s execution plugin.

plugin_args = {'maxtasksperchild': 1, 'raise_insufficient': False}

Settings for NiPype’s execution plugin.

remove_unnecessary_outputs = True

Clean up unused outputs after running

resource_monitor = False

Enable resource monitor.

stop_on_first_crash = True

Whether the workflow should stop or continue after the first error.

Usage

A config file is used to pass settings and collect information as the execution graph is built across processes.

from petprep import config
config_file = config.execution.work_dir / '.petprep.toml'
config.to_filename(config_file)
# Call build_workflow(config_file, retval) in a subprocess
with Manager() as mgr:
    from .workflow import build_workflow
    retval = mgr.dict()
    p = Process(target=build_workflow, args=(str(config_file), retval))
    p.start()
    p.join()
config.load(config_file)
# Access configs from any code section as:
value = config.section.setting

Logging

class petprep.config.loggers[source]

Keep loggers easily accessible (see init()).

cli = <Logger cli (WARNING)>[source]

Command-line interface logging.

default = <RootLogger root (WARNING)>[source]

The root logger.

classmethod init()[source]

Set the log level, initialize all loggers into loggers.

  • Add new logger levels (25: IMPORTANT, and 15: VERBOSE).

  • Add a new sub-logger (cli).

  • Logger configuration.

interface = <Logger nipype.interface (INFO)>[source]

NiPype’s interface logger.

utils = <Logger nipype.utils (INFO)>[source]

NiPype’s utils logger.

workflow = <Logger nipype.workflow (INFO)>[source]

NiPype’s workflow logger.

Other responsibilities

The config is responsible for other conveniency actions.

  • Switching Python’s multiprocessing to forkserver mode.

  • Set up a filter for warnings as early as possible.

  • Automated I/O magic operations. Some conversions need to happen in the store/load processes (e.g., from/to Path <-> str, BIDSLayout, etc.)

petprep.config.dumps()[source]

Format config into toml.

petprep.config.from_dict(settings, init=True, ignore=None)[source]

Read settings from a flat dictionary.

Parameters:
  • setting (dict) – Settings to apply to any configuration

  • init (bool or Container) – Initialize all, none, or a subset of configurations.

  • ignore (Container) – Collection of keys in setting to ignore

petprep.config.get(flat=False)[source]

Get config as a dict.

petprep.config.init_spaces(checkpoint=True)[source]

Initialize the spaces setting.

petprep.config.load(filename, skip=None, init=True)[source]

Load settings from file.

Parameters:
  • filename (os.PathLike) – TOML file containing PETPrep configuration.

  • skip (dict or None) – Sets of values to ignore during load, keyed by section name

  • init (bool or Container) – Initialize all, none, or a subset of configurations.

petprep.config.to_filename(filename)[source]

Write settings to file.

Workflows

PETPrep base processing workflows

petprep.workflows.base.init_petprep_wf()[source]

Build PETPrep’s pipeline.

This workflow organizes the execution of PETPREP, with a sub-workflow for each subject.

If FreeSurfer’s recon-all is to be run, a corresponding folder is created and populated with any needed template subjects under the derivatives folder.

Workflow Graph

(Source code)

petprep.workflows.base.init_single_subject_wf(subject_id: str, session_id: str | list[str] | None = None)[source]

Organize the preprocessing pipeline for a single subject.

It collects and reports information about the subject, and prepares sub-workflows to perform anatomical and PET preprocessing. Anatomical preprocessing is performed in a single workflow, regardless of the number of sessions. Functional preprocessing is performed using a separate workflow for each individual PET series.

Workflow Graph

(Source code)

Parameters:

subject_id (str) – Subject label for this single-subject workflow.

Inputs:

subjects_dir (str) – FreeSurfer’s $SUBJECTS_DIR.

Pre-processing PET workflows

Orchestrating the PET-preprocessing workflow

petprep.workflows.pet.base.init_pet_wf(*, pet_series: list[str], precomputed: dict = None) Workflow[source]

This workflow controls the PET preprocessing stages of PETPrep.

Workflow Graph

(Source code)

Parameters:
  • pet_series – List of paths to NIfTI files.

  • precomputed – Dictionary containing precomputed derivatives to reuse, if possible.

Inputs:
  • t1w_preproc – Bias-corrected structural template image

  • t1w_mask – Mask of the skull-stripped template image

  • t1w_dseg – Segmentation of preprocessed structural image, including gray-matter (GM), white-matter (WM) and cerebrospinal fluid (CSF)

  • t1w_tpms – List of tissue probability maps in T1w space

  • subjects_dir – FreeSurfer SUBJECTS_DIR

  • subject_id – FreeSurfer subject ID

  • fsnative2t1w_xfm – LTA-style affine matrix translating from FreeSurfer-conformed subject space to T1w

  • white – FreeSurfer white matter surfaces, in T1w space, collated left, then right

  • midthickness – FreeSurfer mid-thickness surfaces, in T1w space, collated left, then right

  • pial – FreeSurfer pial surfaces, in T1w space, collated left, then right

  • sphere_reg_fsLR – Registration spheres from fsnative to fsLR space, collated left, then right

  • anat_ribbon – Binary cortical ribbon mask in T1w space

  • segmentation – Segmentation file in T1w space

  • dseg_tsv – TSV with segmentation statistics

  • anat2std_xfm – Transform from anatomical space to standard space

  • std_t1w – T1w reference image in standard space

  • std_mask – Brain (binary) mask of the standard reference image

  • std_space – Value of space entity to be used in standard space output filenames

  • std_resolution – Value of resolution entity to be used in standard space output filenames

  • std_cohort – Value of cohort entity to be used in standard space output filenames

  • anat2mni6_xfm – Transform from anatomical space to MNI152NLin6Asym space

  • mni6_mask – Brain (binary) mask of the MNI152NLin6Asym reference image

  • mni2009c2anat_xfm – Transform from MNI152NLin2009cAsym to anatomical space

  • Note that ``anat2std_xfm``, ``std_space``, ``std_resolution``,

  • ``std_cohort``, ``std_t1w`` and ``std_mask`` are treated as single

  • inputs. In order to resample to multiple target spaces, connect

  • these fields to an iterable.

See also

petprep.workflows.pet.base.init_pet_fit_wf(*, pet_series: list[str], precomputed: dict = None, omp_nthreads: int = 1, name: str = 'pet_fit_wf') Workflow[source]

This workflow controls the fit-stage estimation steps for PET preprocessing.

Workflow Graph

(Source code)

Parameters:
  • pet_series – List of paths to NIfTI files

  • precomputed – Dictionary containing precomputed derivatives to reuse, if possible.

Inputs:
  • pet_file – PET series NIfTI file

  • t1w_preproc – Bias-corrected structural template image

  • t1w_mask – Mask of the skull-stripped template image

  • t1w_dseg – Segmentation of preprocessed structural image, including gray-matter (GM), white-matter (WM) and cerebrospinal fluid (CSF)

  • anat2std_xfm – List of transform files, collated with templates

  • subjects_dir – FreeSurfer SUBJECTS_DIR

  • subject_id – FreeSurfer subject ID

  • fsnative2t1w_xfm – LTA-style affine matrix translating from FreeSurfer-conformed subject space to T1w

  • segmentation – Segmentation file in T1w space

  • dseg_tsv – TSV with segmentation statistics

Outputs:
  • petref – PET reference image used for head motion correction.

  • pet_mask – Mask of petref.

  • motion_xfm – Affine transforms from each PET volume to petref, written as concatenated ITK affine transforms.

  • petref2anat_xfm – Affine transform mapping from PET reference space to the anatomical space.

  • registration_fallback – Whether the selected PET-to-anatomical registration used the uncropped anatomical fallback.

  • registration_anat_reference – Anatomical reference used by the selected PET-to-anatomical transform (cropped or uncropped).

See also

petprep.workflows.pet.base.init_pet_native_wf(*, pet_series: list[str], omp_nthreads: int = 1, name: str = 'pet_native_wf') Workflow[source]

Minimal resampling workflow.

This workflow resamples the PET series into PET reference space while applying the head-motion transforms estimated in the fit stage. It also selects the transforms needed to perform further resampling.

Workflow Graph

(Source code)

Parameters:

pet_series – List of paths to NIfTI files.

Inputs:
  • petref – PET reference file

  • pet_mask – Mask of pet reference file

  • motion_xfm – Affine transforms from each PET volume to petref, written as concatenated ITK affine transforms.

Outputs:
  • pet_minimal – PET series ready for further resampling.

  • pet_native – PET series resampled into PET reference space. Head motion correction will be applied to each file.

  • metadata – Metadata dictionary of PET series

  • motion_xfm – Motion correction transforms for further correcting pet_minimal.

Head-Motion Estimation and Correction (HMC) of PET images

petprep.workflows.pet.hmc.init_pet_hmc_wf(mem_gb: float, omp_nthreads: int, *, fwhm: float = 10.0, start_time: float = 120.0, frame_durations: Sequence[float] | None = None, frame_start_times: Sequence[float] | None = None, initial_frame: int | str | None = 'auto', fixed_frame: bool = False, name: str = 'pet_hmc_wf')[source]

Build a workflow to estimate head-motion parameters.

This workflow estimates the motion parameters to perform HMC over the input PET image.

Workflow Graph
_images/api-6.png

(Source code, png, svg, pdf)

Parameters:
  • mem_gb (float) – Size of PET file in GB

  • omp_nthreads (int) – Maximum number of threads an individual process may use

  • fwhm (float) – FWHM in millimeters for Gaussian smoothing prior to motion estimation

  • start_time (float) – Earliest time point (in seconds) used for motion estimation.

  • frame_durations (Sequence[float] or None) – Duration of each frame in seconds. If not provided, start-time clamping will be skipped.

  • frame_start_times (Sequence[float] or None) – Optional list of frame onset times used together with frame_durations to locate the start frame.

  • initial_frame (int, 'auto' or None) – 0-based index of the frame used to initialize motion correction. If 'auto' or None (default), the frame with the highest uptake is selected automatically. FreeSurfer’s initial_timepoint is 1-based; this workflow applies the required offset internally.

  • fixed_frame (bool) – Whether to keep the initial time point fixed during robust template estimation (fs.RobustTemplate’s fixtp parameter). If True, iterations are skipped to reduce runtime.

  • name (str) – Name of workflow (default: pet_hmc_wf)

Inputs:
  • pet_file – PET series NIfTI file

  • frame_durations – Duration of each PET frame, in seconds.

  • frame_start_times – Optional onset time of each PET frame.

Outputs:
  • xforms – ITKTransform file aligning each volume to ref_image

  • petref – PET reference image generated during motion estimation

Registration workflows

petprep.workflows.pet.registration.init_pet_reg_wf(*, pet2anat_dof: Literal[6, 9, 12], mem_gb: float, omp_nthreads: int, pet2anat_method: str = 'mri_coreg', crop_anat: bool = True, name: str = 'pet_reg_wf', sloppy: bool = False)[source]

Build a workflow to run same-subject, PET-to-anat image-registration.

Calculates the registration between a reference PET image and anat-space.

Workflow Graph
_images/api-7.png

(Source code, png, svg, pdf)

Parameters:
  • pet2anat_dof (6, 9 or 12) – Degrees-of-freedom for PET-anatomical registration

  • mem_gb (float) – Size of PET file in GB

  • omp_nthreads (int) – Maximum number of threads an individual process may use

  • pet2anat_method (str) – Method for PET-to-anatomical registration. Options are ‘mri_coreg’ (default FreeSurfer co-registration), ‘robust’ (uses FreeSurfer mri_robust_register with NMI, 6 DoF only), ‘ants’ (uses ANTs rigid registration, 6 DoF only), or ‘auto’ (runs FreeSurfer and ANTs in parallel, selecting the best-performing transform).

  • crop_anat (bool) – Crop the anatomical reference with FSL’s robustfov before registration.

  • name (str) – Name of workflow (default: pet_reg_wf)

Inputs:
  • ref_pet_brain – Reference image to which PET series is aligned If fieldwarp == True, ref_pet_brain should be unwarped

  • anat_preproc – Preprocessed anatomical image

  • anat_mask – Brainmask for anatomical image

Outputs:
  • itk_pet_to_anat – Affine transform from ref_pet_brain to anatomical space (ITK format)

  • itk_anat_to_pet – Affine transform from anatomical space to PET space (ITK format)

  • registration_winner – Name of the registration backend selected when pet2anat_method='auto'

  • registration_score – Similarity score for the selected registration transform.

  • fallback – Whether this workflow output came from an uncropped anatomical fallback registration.

  • anat_reference – Anatomical reference used for registration (cropped or uncropped).

Resampling workflows

petprep.workflows.pet.resampling.init_pet_surf_wf(*, mem_gb: float, surface_spaces: list[str], medial_surface_nan: bool, metadata: dict, output_dir: str, pvc_method: str | None = None, pvc_software_name: str | None = None, pvc_command_line: str | None = None, name: str = 'pet_surf_wf')[source]

Sample functional images to FreeSurfer surfaces.

For each vertex, the cortical ribbon is sampled at six points (spaced 20% of thickness apart) and averaged.

Outputs are in GIFTI format.

Workflow Graph
_images/api-8.png

(Source code, png, svg, pdf)

Parameters:
  • surface_spaces (list) – List of FreeSurfer surface-spaces (either fsaverage{3,4,5,6,} or fsnative) the functional images are to be resampled to. For fsnative, images will be resampled to the individual subject’s native surface.

  • medial_surface_nan (bool) – Replace medial wall values with NaNs on functional GIFTI files

  • pvc_method (str, optional) – Name of the PVC method, if applied. Used to set the pvc BIDS entity on derivative files.

Inputs:
  • source_file – Original PET series

  • sources – List of files used to create the output files.

  • pet_t1w – Motion-corrected PET series in T1 space

  • subjects_dir – FreeSurfer SUBJECTS_DIR

  • subject_id – FreeSurfer subject ID

  • fsnative2t1w_xfm – ITK-style affine matrix translating from FreeSurfer-conformed subject space to T1w

Outputs:

surfaces – PET series, resampled to FreeSurfer surfaces

petprep.workflows.pet.resampling.init_pet_fsLR_resampling_wf(grayord_density: Literal['91k', '170k'], omp_nthreads: int, mem_gb: float, name: str = 'pet_fsLR_resampling_wf')[source]

Resample PET time series to fsLR surface.

This workflow is derived heavily from three scripts within the DCAN-HCP pipelines scripts

Line numbers correspond to the locations of the code in the original scripts, found at: https://github.com/DCAN-Labs/DCAN-HCP/tree/9291324/

Workflow Graph
_images/api-9.png

(Source code, png, svg, pdf)

Parameters:
  • grayord_density (str) – Either "91k" or "170k", representing the total grayordinates.

  • omp_nthreads (int) – Maximum number of threads an individual process may use

  • mem_gb (float) – Size of PET file in GB

  • name (str) – Name of workflow (default: pet_fsLR_resampling_wf)

Inputs:
  • pet_file (str) – Path to PET file resampled into T1 space

  • white (list of str) – Path to left and right hemisphere white matter GIFTI surfaces.

  • pial (list of str) – Path to left and right hemisphere pial GIFTI surfaces.

  • midthickness (list of str) – Path to left and right hemisphere midthickness GIFTI surfaces.

  • midthickness_fsLR (list of str) – Path to left and right hemisphere midthickness GIFTI surfaces in fsLR space.

  • sphere_reg_fsLR (list of str) – Path to left and right hemisphere sphere.reg GIFTI surfaces, mapping from subject to fsLR

  • cortex_mask (list of str) – Path to left and right hemisphere cortical masks.

  • volume_roi (str or Undefined) – Pre-calculated mask. Not required.

Outputs:

pet_fsLR (list of str) – Path to PET series resampled as functional GIFTI files in fsLR space

petprep.workflows.pet.resampling.init_pet_grayords_wf(grayord_density: Literal['91k', '170k'], mem_gb: float, metadata: dict, name: str = 'pet_grayords_wf')[source]

Sample Grayordinates files onto the fsLR atlas.

Outputs are in CIFTI2 format.

Workflow Graph
_images/api-10.png

(Source code, png, svg, pdf)

Parameters:
  • grayord_density (str) – Either "91k" or "170k", representing the total grayordinates.

  • mem_gb (float) – Size of PET file in GB

  • metadata (dict) – BIDS metadata for PET file

  • name (str) – Unique name for the subworkflow (default: "pet_grayords_wf")

Inputs:
  • pet_fsLR (str) – List of paths to PET series resampled as functional GIFTI files in fsLR space

  • pet_std (str) – List of PET conversions to standard spaces.

  • spatial_reference (str) – List of unique identifiers corresponding to the PET standard-conversions.

Outputs:
  • cifti_pet (str) – PET CIFTI dtseries.

  • cifti_metadata (str) – BIDS metadata file corresponding to cifti_pet.

Calculate PET confounds

petprep.workflows.pet.confounds.init_pet_confs_wf(mem_gb: float, regressors_dvars_th: float, regressors_fd_th: float, freesurfer: bool = False, name: str = 'pet_confs_wf')[source]

Build a workflow to generate and write out confounding signals.

This workflow calculates confounds for a PET series, and aggregates them into a TSV file, for use as nuisance regressors in a GLM. The following confounds are calculated, with column headings in parentheses:

  1. Region-wise average signal (csf, white_matter, global_signal)

  2. DVARS - original and standardized variants (dvars, std_dvars)

  3. Framewise displacement, based on head-motion parameters (framewise_displacement)

  4. Cosine basis set for high-pass filtering w/ 0.008 Hz cut-off (cosine_XX)

  5. Non-steady-state volumes (non_steady_state_XX)

  6. Estimated head-motion parameters, in mm and rad (trans_x, trans_y, trans_z, rot_x, rot_y, rot_z)

Prior to estimating aCompCor and tCompCor, non-steady-state volumes are censored and high-pass filtered using a DCT basis. The cosine basis, as well as one regressor per censored volume, are included for convenience.

Workflow Graph
_images/api-11.png

(Source code, png, svg, pdf)

Parameters:
  • mem_gb (float) – Size of PET file in GB - please note that this size should be calculated after resamplings that may extend the FoV

  • name (str) – Name of workflow (default: pet_confs_wf)

  • regressors_dvars_th (float) – Criterion for flagging DVARS outliers

  • regressors_fd_th (float) – Criterion for flagging framewise displacement outliers

Inputs:
  • pet – PET image, after the prescribed corrections (STC, HMC and SDC) when available.

  • pet_mask – PET series mask

  • motion_xfm – ITK-formatted head motion transforms

  • t1w_mask – Mask of the skull-stripped template image

  • t1w_tpms – List of tissue probability maps in T1w space

  • petref2anat_xfm – Affine matrix that maps the PET reference space into alignment with the anatomical (T1w) space

Outputs:
  • confounds_file – TSV of all aggregated confounds

  • rois_report – Reportlet visualizing white-matter/CSF mask used for aCompCor, the ROI for tCompCor and the PET brain mask.

  • confounds_metadata – Confounds metadata dictionary.

  • crown_mask – Mask of brain edge voxels

Segmentation workflows.

Helpers for FreeSurfer gtmseg outputs.