@brainpilot/skills 0.0.12 → 0.0.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,392 @@
1
+ # Workflow Internals
2
+
3
+ The fMRIPrep pipeline is a Nipype workflow graph. This reference maps each
4
+ stage to its Python entry point (so you can read the source) and describes
5
+ the algorithms in enough depth to write a methods section or troubleshoot a
6
+ node failure.
7
+
8
+ Source root: `fmriprep/workflows/` — `base.py` (top-level), `bold/` (BOLD
9
+ per-run subworkflows). Anatomical workflows live in `smriprep` (sister package),
10
+ distortion-correction in `sdcflows`, common utilities in `niworkflows`.
11
+
12
+ ## Table of Contents
13
+ 1. [Top-level flow](#1-top-level-flow)
14
+ 2. [Anatomical pipeline](#2-anatomical-pipeline)
15
+ 3. [BOLD pipeline overview (fit vs apply)](#3-bold-pipeline-overview-fit-vs-apply)
16
+ 4. [BOLD reference-image estimation](#4-bold-reference-image-estimation)
17
+ 5. [Head-motion correction (HMC)](#5-head-motion-correction-hmc)
18
+ 6. [Slice-timing correction (STC)](#6-slice-timing-correction-stc)
19
+ 7. [Susceptibility distortion correction (SDC)](#7-susceptibility-distortion-correction-sdc)
20
+ 8. [Pre-processed BOLD in native space](#8-pre-processed-bold-in-native-space)
21
+ 9. [EPI-to-T1w registration (BBR)](#9-epi-to-t1w-registration-bbr)
22
+ 10. [Resampling to standard/native volumetric spaces](#10-resampling-to-standardnative-volumetric-spaces)
23
+ 11. [Surface sampling (FreeSurfer)](#11-surface-sampling-freesurfer)
24
+ 12. [HCP grayordinates / CIFTI-2](#12-hcp-grayordinates--cifti-2)
25
+ 13. [T2*-driven multi-echo combination](#13-t2-driven-multi-echo-combination)
26
+ 14. [Confounds estimation](#14-confounds-estimation)
27
+ 15. [Reports (nireports)](#15-reports-nireports)
28
+ 16. [Processing levels (`--level`)](#16-processing-levels---level)
29
+
30
+ ---
31
+
32
+ ## 1. Top-level flow
33
+
34
+ ```
35
+ init_fmriprep_wf (per-run entry)
36
+ └─ init_single_subject_wf (fmriprep/workflows/base.py)
37
+ ├─ init_anat_preproc_wf (smriprep.workflows.anatomical)
38
+ ├─ init_bold_wf (fmriprep/workflows/bold/base.py) ── one per BOLD run
39
+ │ ├─ init_bold_fit_wf (fmriprep/workflows/bold/fit.py)
40
+ │ ├─ init_bold_native_wf (fmriprep/workflows/bold/fit.py)
41
+ │ ├─ init_bold_volumetric_resample_wf (fmriprep/workflows/bold/apply.py)
42
+ │ ├─ init_bold_surf_wf (fmriprep/workflows/bold/resampling.py)
43
+ │ ├─ init_bold_fsLR_resampling_wf (fmriprep/workflows/bold/resampling.py)
44
+ │ └─ init_bold_confs_wf (fmriprep/workflows/bold/confounds.py)
45
+ └─ ds_report_* nodes → visual report reportlets
46
+ ```
47
+
48
+ Workflow naming conventions:
49
+ - Names end in `_wf`, built by `init_<name>_wf` functions.
50
+ - `inputnode` / `outputnode` = workflow "arguments"/"returns".
51
+ - `ds_*` nodes write to `<output_dir>/`; `ds_report_*` write reportlets.
52
+ - Node/label paths in the graph include `(module)` markers referencing where the
53
+ interface is defined (e.g. `about (reports)`).
54
+
55
+ ---
56
+
57
+ ## 2. Anatomical pipeline
58
+ *Entry: `smriprep.workflows.anatomical.init_anat_preproc_wf`*
59
+
60
+ Steps (in order):
61
+
62
+ 1. **Conform + average T1w** — reorient to RAS, resample to common voxel size,
63
+ optionally average (or unbiased-template) multiple T1w runs.
64
+ - `--subject-anatomical-reference first-lex` (default): register to first (lex) image.
65
+ - `--subject-anatomical-reference unbiased`: `mri_robust_template` unbiased template.
66
+ - `--subject-anatomical-reference sessionwise`: independent per session.
67
+
68
+ 2. **T2w merge/coregistration** — if T2w available, aligned to T1w space. Used
69
+ downstream by FreeSurfer for pial refinement.
70
+
71
+ 3. **N4 bias-field correction** — ANTs `N4BiasFieldCorrection`.
72
+
73
+ 4. **Skull-stripping** — Nipype implementation of `antsBrainExtraction.sh` on
74
+ OASIS30ANTs template (or `--skull-strip-template ...`).
75
+ - `--skull-strip-t1w force` (default) always strips.
76
+ - `--skull-strip-t1w auto` uses a heuristic to detect pre-stripped inputs.
77
+ - `--skull-strip-t1w skip` bypasses stripping entirely.
78
+
79
+ 5. **Tissue segmentation** — FSL `FAST` produces 3-class (CSF/GM/WM) probability
80
+ maps and a discrete segmentation.
81
+
82
+ 6. **Spatial normalization** — ANTs `antsRegistration` multi-scale mutual-info
83
+ nonlinear registration to every requested standard space
84
+ (`--output-spaces MNI152NLin2009cAsym`, etc.). Produces `.h5` composite
85
+ transforms both directions.
86
+
87
+ 7. **Optional lesion cost-function masking** — if
88
+ `sub-XX/anat/sub-XX_label-lesion_roi.nii.gz` exists, ANTs uses it to avoid
89
+ warping healthy tissue into damage (Brett et al. 2001).
90
+
91
+ 8. **Surface reconstruction** — FreeSurfer `recon-all`, three phases:
92
+ - Phase 1: `autorecon1 -noskullstrip` — brain mask from step 4 is injected.
93
+ - Phase 2: import brainmask.
94
+ - Phase 3: resume, using T2w/FLAIR for pial refinement when available.
95
+ - Submillimeter recon triggered automatically if voxels <1 mm, unless
96
+ `--no-submm-recon`. Disable entirely with `--fs-no-reconall`.
97
+ - Reused if outputs already exist in `<output>/sourcedata/freesurfer/sub-XX`.
98
+
99
+ 9. **MSMSulc surface registration** — Multimodal Surface Matching (MSM) using
100
+ sulcal depth to register subject spheres to `fsLR` (HCP convention).
101
+ Disable with `--no-msm`.
102
+
103
+ 10. **Brain-mask refinement** — When FreeSurfer runs, replace the ANTs-derived
104
+ mask with one derived from `mri/aseg.mgz` (better inclusion of deep-brain
105
+ structures).
106
+
107
+ 11. **Cortical thickness / curvature / sulcal-depth conversion** — GIFTI shape
108
+ files plus fsLR-32k CIFTI dscalar summaries.
109
+
110
+ 12. **Outputs** — see `references/outputs.md` for the full naming schema.
111
+
112
+ ---
113
+
114
+ ## 3. BOLD pipeline overview (fit vs apply)
115
+ *Entry: `fmriprep/workflows/bold/base.py :: init_bold_wf`*
116
+
117
+ Since 23.2.0 the BOLD workflow is split for clarity and to enable `--level`
118
+ partial runs:
119
+
120
+ ```
121
+ BOLD series ──▶ init_bold_fit_wf ──▶ init_bold_native_wf ──▶ init_bold_volumetric_resample_wf
122
+ └▶ init_bold_surf_wf
123
+ └▶ init_bold_fsLR_resampling_wf
124
+ └▶ init_bold_confs_wf
125
+ ```
126
+
127
+ - **`bold_fit_wf`** (`fit.py`) — resolves all transforms without saving heavy
128
+ intermediate BOLD data. Outputs reference images, HMC transforms, BBR transform,
129
+ and (when applicable) the fieldmap→BOLDref transform.
130
+ - **`bold_native_wf`** (`fit.py`) — applies STC and HMC/SDC in native BOLD space.
131
+ This is the input to all downstream resamplers.
132
+ - **`bold_volumetric_resample_wf`** (`apply.py`) — resamples native BOLD into
133
+ each `--output-spaces` template space.
134
+ - **`bold_surf_wf`** / **`bold_fsLR_resampling_wf`** — surface / CIFTI paths.
135
+ - **`bold_confs_wf`** (`confounds.py`) — confounds table.
136
+
137
+ At `--level minimal`, only transforms and refs are saved; the resamplers still
138
+ run internally when needed for QC plots but their outputs are discarded.
139
+
140
+ ---
141
+
142
+ ## 4. BOLD reference-image estimation
143
+ *Entry: `fmriprep/workflows/bold/reference.py :: init_raw_boldref_wf`*
144
+
145
+ Chooses a per-run reference volume:
146
+
147
+ - If T1-saturation "dummy scans" are detected (non-steady-state), they are
148
+ averaged (superior tissue contrast).
149
+ - Otherwise, median of a motion-corrected volume subset.
150
+
151
+ For BBR registration a distinct reference is used:
152
+ - Prefers a single-band reference (`sbref`) if the dataset provides one.
153
+ - Contrast-enhanced and skull-stripped via
154
+ `niworkflows.func.util.init_enhance_and_skullstrip_bold_wf`.
155
+ - If fieldmaps present, the stripped reference is SDC-corrected before BBR.
156
+
157
+ Number of non-steady-state volumes: auto-detected unless `--dummy-scans N`
158
+ forces it.
159
+
160
+ ---
161
+
162
+ ## 5. Head-motion correction (HMC)
163
+ *Entry: `fmriprep/workflows/bold/hmc.py :: init_bold_hmc_wf`*
164
+
165
+ - Tool: FSL `mcflirt`.
166
+ - Reference: BOLD reference from §4.
167
+ - Motion **parameters are estimated on the raw (un-STC) BOLD** so that
168
+ slice-timing interpolation does not alias motion into the estimates
169
+ (Power 2017 recommendation). The motion transforms are then applied jointly
170
+ with STC and SDC downstream (single-interpolation resampling).
171
+ - Emits:
172
+ - 6-parameter rigid transforms per volume (`trans_x/y/z`, `rot_x/y/z`).
173
+ - `framewise_displacement`, `rmsd` — pushed to the confounds workflow.
174
+ - `hmc_boldref` (aligned template) — pushed to BBR.
175
+
176
+ ---
177
+
178
+ ## 6. Slice-timing correction (STC)
179
+ *Entry: `fmriprep/workflows/bold/stc.py :: init_bold_stc_wf`*
180
+
181
+ - Tool: AFNI `3dTShift`.
182
+ - **Only runs** if `SliceTiming` metadata is present AND ≥5 usable (post-dummy)
183
+ volumes exist.
184
+ - Reference slice controlled by `--slice-time-ref` (default `0.5` = middle):
185
+ - `0` / `start` — TR onset (matches raw acquisition; no volume onset shift)
186
+ - `0.5` / `middle` — middle of TR (default; shifts volume onsets by 0.5 TR
187
+ — remember to adjust your first-level model)
188
+ - `1` — end of TR
189
+ - Disable with `--ignore slicetiming`.
190
+
191
+ STC is applied to the raw (validated) BOLD *before* HMC/SDC transforms are
192
+ applied — HMC/SDC transforms are then composed and applied together in a
193
+ single interpolation step (see §8 / §10). This ordering (STC on raw data →
194
+ HMC/SDC on STC-corrected data) is why HMC motion *parameters* are estimated
195
+ on the un-STC data in §5.
196
+
197
+ ---
198
+
199
+ ## 7. Susceptibility distortion correction (SDC)
200
+ *Delegated to the `sdcflows` package (`sdcflows.workflows.*`).*
201
+ See `references/sdc-fieldmaps.md` for user-facing SDC guidance.
202
+
203
+ Supported estimators (auto-selected from BIDS metadata):
204
+
205
+ | BIDS fieldmap type | Estimator | Notes |
206
+ |--------------------|-----------|-------|
207
+ | **PEPOLAR** (opposite phase-encoding EPI) | TOPUP-based | Preferred when available |
208
+ | **Phase-difference + magnitude** (`phasediff` or `phase1/phase2`) | PRELUDE→FUGUE | Requires 2 echo times in JSON |
209
+ | **Precomputed fieldmap** (`fieldmap` suffix) | FUGUE | User-supplied |
210
+ | **Fieldmap-less (SyN)** | ANTs SyN vs anatomical | Enabled by `--use-syn-sdc`, `--force syn-sdc` |
211
+
212
+ Fieldmap association (SDCFlows preference order):
213
+ 1. `B0FieldIdentifier` / `B0FieldSource` metadata (BIDS ≥1.6). **If present anywhere in the dataset, `IntendedFor` is ignored.**
214
+ 2. `IntendedFor` metadata on the fieldmap JSON.
215
+
216
+ Fieldmap Jacobian modulation is applied by default; disable with
217
+ `--ignore fmap-jacobian` (or force with `--force fmap-jacobian`).
218
+
219
+ ---
220
+
221
+ ## 8. Pre-processed BOLD in native space
222
+ *Entry: `fmriprep/workflows/bold/fit.py :: init_bold_native_wf`*
223
+
224
+ Applies HMC + (if any) SDC in **one interpolation step**, concatenating the
225
+ composed transforms to minimize resampling blur. The volumetric resampler is
226
+ `fmriprep.interfaces.resampling.ResampleSeries` (built on `nitransforms`),
227
+ default order-3 **cubic B-spline** interpolation with `grid-constant` boundary
228
+ mode (the default since 25.2.0). Output stays in the original BOLD grid.
229
+
230
+ Note: Lanczos-windowed sinc interpolation is used by fMRIPrep in some
231
+ non-volumetric places (e.g. `outputs.py` ANTs `ApplyTransforms` calls for
232
+ resampling anat images to output spaces) but the BOLD series itself is
233
+ resampled with cubic B-spline.
234
+
235
+ ---
236
+
237
+ ## 9. EPI-to-T1w registration (BBR)
238
+ *Entry: `fmriprep/workflows/bold/registration.py :: init_bbreg_wf` (FS on) or `init_fsl_bbr_wf` (FS off).*
239
+
240
+ With FreeSurfer enabled:
241
+ - `bbregister` aligns BOLD reference to the `?h.white` surfaces using
242
+ boundary-based registration.
243
+ - `--bold2anat-init` picks the initial reference: `auto` (T2w if available,
244
+ else T1w — default), `t1w`, `t2w`, or `header` (skip init reg).
245
+ - `--bold2anat-dof` picks DOF: 6 (rigid, default), 9, or 12.
246
+
247
+ Without FreeSurfer:
248
+ - FSL `flirt` with the BBR cost function (`bbr.sch`, ships in `fmriprep/data/flirtsch/`)
249
+ and the FAST WM segmentation as boundary.
250
+
251
+ **Fallback**: The BBR result is compared to the initial affine; excessive
252
+ deviation rejects BBR and uses the initial affine instead. Override with
253
+ `--force bbr` or `--force no-bbr`.
254
+
255
+ ---
256
+
257
+ ## 10. Resampling to standard/native volumetric spaces
258
+ *Entry: `fmriprep/workflows/bold/apply.py :: init_bold_volumetric_resample_wf`*
259
+
260
+ Concatenates: HMC ∘ SDC ∘ BBR ∘ T1w-to-standard, applied in a **single
261
+ cubic B-spline** interpolation (nitransforms `ResampleSeries`, order-3,
262
+ `grid-constant` boundary mode) for each `--output-spaces` entry. The boilerplate
263
+ records this as: "Gridded (volumetric) resamplings were performed using
264
+ nitransforms, configured with cubic B-spline interpolation."
265
+
266
+ `res-*` and other modifiers on `--output-spaces` control resampling grid; see
267
+ `references/spaces.md`.
268
+
269
+ Also produces the T1w brain mask resampled to each target space (using
270
+ ANTs `ApplyTransforms` with `MultiLabel` interpolation to preserve label integrity).
271
+
272
+ ---
273
+
274
+ ## 11. Surface sampling (FreeSurfer)
275
+ *Entry: `fmriprep/workflows/bold/resampling.py :: init_bold_surf_wf`*
276
+
277
+ Only runs when FreeSurfer is enabled and `fsnative`/`fsaverage*` is in
278
+ `--output-spaces` (or when `--cifti-output` is set).
279
+
280
+ - Samples cortical ribbon at 6 intervals normal to the white surface, extending
281
+ to the pial surface, and averages — one value per vertex per timepoint.
282
+ - Emits GIFTI (`.func.gii`) for both hemispheres.
283
+ - Native subject-mesh (`fsnative`), plus `fsaverage` and downsampled
284
+ `fsaverage6` (41k) / `fsaverage5` (10k, default).
285
+ - `--medial-surface-nan` replaces medial-wall vertices with NaN.
286
+ - `--project-goodvoxels` masks locally high-CoV voxels ("goodvoxels" heuristic).
287
+
288
+ ---
289
+
290
+ ## 12. HCP grayordinates / CIFTI-2
291
+ *Entry: `fmriprep/workflows/bold/resampling.py :: init_bold_fsLR_resampling_wf`*
292
+
293
+ When `--cifti-output` is set:
294
+ 1. Native BOLD → subject-native surface via §11.
295
+ 2. Dilate to fill sampling holes.
296
+ 3. Resample to `fsLR` mesh using Connectome Workbench (aligned L/R).
297
+ 4. Combine with volumetric subcortical time series (resampled to a
298
+ MNI152NLin6Asym grid) into a CIFTI-2 dense time series.
299
+
300
+ Resolutions:
301
+ - `--cifti-output 91k` — 91,282 grayordinates, 2 mm subcortical (default).
302
+ - `--cifti-output 170k` — 170,494 grayordinates, 1.6 mm subcortical.
303
+
304
+ Uses `wb_command` from Connectome Workbench (v1.5.0+).
305
+
306
+ ---
307
+
308
+ ## 13. T2*-driven multi-echo combination
309
+ *Entry: `fmriprep/workflows/bold/t2s.py :: init_bold_t2s_wf`*
310
+
311
+ For datasets with ≥3 echoes (`echo-N_bold`):
312
+ - Uses `tedana`'s `t2smap_workflow` to estimate adaptive T2* and S0 maps.
313
+ - Produces an **optimally combined** BOLD series that replaces the per-echo
314
+ data for all downstream steps.
315
+ - Method controlled by `--me-t2s-fit-method`:
316
+ - `curvefit` (default) — nonlinear regression; slower, more accurate.
317
+ - `loglin` — log-linear regression; faster.
318
+ - `--me-output-echos` also saves per-echo STC/HMC/SDC-corrected series for
319
+ downstream tedana denoising.
320
+
321
+ Two-echo data is **rejected** since 25.2.4 (tedana requires ≥3 echoes to fit T2*).
322
+
323
+ ---
324
+
325
+ ## 14. Confounds estimation
326
+ *Entry: `fmriprep/workflows/bold/confounds.py :: init_bold_confs_wf`*
327
+
328
+ Given motion-corrected BOLD, brain mask, HMC parameters, and tissue seg,
329
+ computes per-timepoint nuisance signals. See `references/confounds.md` for the
330
+ full column dictionary. Highlights:
331
+
332
+ - **Motion**: 6 rigid params (+ derivatives + squares → 24-parameter model).
333
+ - **Global signals**: `csf`, `white_matter`, `global_signal` (+ derivatives + squares).
334
+ - **Framewise displacement** (Power 2012), **RMSD** (Jenkinson 2002).
335
+ - **DVARS** / **std_dvars** (Power 2012).
336
+ - **CompCor**:
337
+ - `a_comp_cor_XX` — anatomical, **combined** WM ∪ CSF mask (Behzadi original).
338
+ - `c_comp_cor_XX` — anatomical, **CSF-only** mask (Muschelli refinement).
339
+ - `w_comp_cor_XX` — anatomical, **WM-only** mask (Muschelli refinement).
340
+ - `t_comp_cor_XX` — temporal, top-variance voxels.
341
+ - High-pass filter applied before decomposition; corresponding
342
+ `cosine_XX` DCT regressors are output — include them in your GLM if using
343
+ CompCor.
344
+ - **Non-steady-state outliers**: `non_steady_state_outlier_XX` (one column per detected outlier).
345
+ - **Motion spike regressors**: `motion_outlier_XX`, flagged when
346
+ FD > `--fd-spike-threshold` OR std-DVARS > `--dvars-spike-threshold`.
347
+ - **Edge / crown PCA**: `edge_comp_XX` — 24 components from an "outer brain
348
+ edge" (crown) mask, tagged in the JSON with `Method: EdgeRegressor`
349
+ (Patriat 2017 / Provins 2022).
350
+
351
+ By default, only components explaining the top 50% of ROI variance are
352
+ retained; `--return-all-components` keeps all (dropped ones are still tracked
353
+ in the JSON metadata).
354
+
355
+ ---
356
+
357
+ ## 15. Reports (nireports)
358
+
359
+ Each subject gets `<output>/sub-XX.html` (or split across sessions if
360
+ `--aggregate-session-reports` is exceeded).
361
+
362
+ Report structure defined by:
363
+ - `fmriprep/data/reports-spec.yml` (top-level)
364
+ - `fmriprep/data/reports-spec-anat.yml` (anatomical section)
365
+ - `fmriprep/data/reports-spec-func.yml` (per-run functional section)
366
+
367
+ Reportlets included (per subject / per BOLD run):
368
+ - Summary tables + BIDS validation warnings
369
+ - Anatomical conformation, skull-strip, tissue segmentation, MNI normalization animations
370
+ - FreeSurfer recon overlay
371
+ - Per-run BOLD validation, BBR alignment overlay, SDC before/after (if applicable)
372
+ - Carpetplot with FD/DVARS/GS strips (Power 2016)
373
+ - ROI overlay (tCompCor blue, aCompCor magenta)
374
+ - CompCor cumulative-variance curves
375
+ - Confound correlation matrix + global-signal correlation
376
+ - Multi-echo: T2*/S0 map, per-echo histogram, ICA_AROMA plot (legacy)
377
+ - Boilerplate citations (`CITATION.md/html/tex`)
378
+
379
+ Sample report: https://fmriprep.org/en/latest/_static/SampleReport/sample_report.html
380
+
381
+ ---
382
+
383
+ ## 16. Processing levels (`--level`)
384
+
385
+ | Level | What's saved | Use case |
386
+ |-------|--------------|----------|
387
+ | `minimal` | Transforms, references, brain masks. No resampled BOLD in outputs. All QC-relevant reportlets except carpetplot / confounds are still generated. | Large datasets, disk-constrained; also anatomical-only-adjacent flows. |
388
+ | `resampling` | + intermediate NIfTIs helpful for third-party resampling. If multi-echo, individual echos are saved after STC/HMC/SDC (like `--me-output-echos`). | You plan to do your own resampling downstream. |
389
+ | `full` (default) | + resampled BOLD in every `--output-spaces` target; CIFTI (if enabled); all confounds artifacts and carpetplots. | Standard use. |
390
+
391
+ Combine `--level minimal` with `--derivatives fmriprep=<path>` in a later run
392
+ to add outputs on demand.