Skip to content

csttool.preprocess

The preprocessing module exposes the high-level functions that the CLI preprocess command orchestrates. Use it directly when you want to script preprocessing from Python.

from csttool.preprocess import run_preprocessing

result = run_preprocessing(
    input_dir="./raw",          # directory holding sub-01.nii.gz + .bval/.bvec
    output_dir="./preproc",
    filename="sub-01",          # stem, without extension
    denoise_method="mppca",
    apply_motion_correction=True,
    external_correction="topup-eddy",   # declared, never verified
)

result["output_paths"]["data"]   # preprocessed NIfTI
result["bvecs_rotated"]          # True when motion correction rotated the gradients

csttool.preprocess

Preprocessing package for csttool.

Exports the main preprocessing orchestrator and module functions.

Functions:

run_preprocessing(input_dir, output_dir, filename, *, b0_threshold=DEFAULT_B0_THRESHOLD, external_correction=DEFAULT_EXTERNAL_CORRECTION, denoise_method=DEFAULT_DENOISE_METHOD, coil_count=4, apply_gibbs_correction=False, apply_motion_correction=False, target_voxel_size=None, save_visualizations=False, title_id=None, verbose=False)

Run the complete DWI preprocessing pipeline.

Steps: 1. Load dataset (NIfTI/DICOM + gradient table) 2. Reslice to target voxel size (optional) 3. Denoise (Patch2Self or NLMeans) 4. Brain masking (median Otsu on b0 volumes) 5. Gibbs unringing (optional) 6. Motion correction (optional) 7. Save outputs

Parameters:

Name Type Description Default
input_dir str or Path

Directory containing input NIfTI/DICOM and gradient files.

required
output_dir str or Path

Output directory for preprocessed files.

required
filename str

Base filename without extension (e.g., "sub01_dwi").

required
b0_threshold float

b-value at or below which a volume counts as a b0, in s/mm². The one authoritative threshold for this execution: it builds the gradient table, and the resulting gtab.b0s_mask is what brain masking and Patch2Self read.

50
external_correction str

User declaration of what correction was applied to the input before csttool received it. Recorded in the report as a declaration; never verified, and it changes no processing decision. See modules/external_declaration.py.

"unknown"
denoise_method str

Denoising method: "nlmeans", "patch2self", or "mppca". - "nlmeans" uses PIESNO for sigma estimation; requires coil_count. - "patch2self" requires bvals and >= 7 directions. - "mppca" (Marchenko-Pastur PCA) is self-adaptive; does not require coil_count or bvals — it exploits the 4D DWI redundancy directly. Best choice for modern multi-channel acquisitions where the effective coil count is unknown.

"mppca"
coil_count int

Number of scanner coils (for NLMeans noise estimation). Ignored when denoise_method is "patch2self" or "mppca".

4
apply_gibbs_correction bool

Apply Gibbs ringing correction.

False
apply_motion_correction bool

Apply between-volume motion correction.

False
target_voxel_size tuple[float, float, float] or None

Target voxel size in mm (x, y, z). If provided, data will be resliced to this voxel size. If None, no reslicing is performed.

None
save_visualizations bool

Save QC visualizations.

False
verbose bool

Print detailed processing information.

False

Returns:

Type Description
dict

Dictionary containing: - 'output_paths': Paths to saved files - 'brain_mask': The computed brain mask array - 'motion_correction_applied': Whether motion correction was applied - 'gtab': The gradient table

Source code in src/csttool/preprocess/preprocess.py
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
def run_preprocessing(
    input_dir: str | Path,
    output_dir: str | Path,
    filename: str,
    *,
    # Gradient handling
    b0_threshold: float = DEFAULT_B0_THRESHOLD,
    # Provenance
    external_correction: str = DEFAULT_EXTERNAL_CORRECTION,
    # Denoising options
    denoise_method: str = DEFAULT_DENOISE_METHOD,
    coil_count: int = 4,
    # Optional steps
    apply_gibbs_correction: bool = False,
    apply_motion_correction: bool = False,
    target_voxel_size: tuple[float, float, float] | None = None,
    # Visualization options
    save_visualizations: bool = False,
    title_id: str | None = None,
    verbose: bool = False,
) -> dict:
    """
    Run the complete DWI preprocessing pipeline.

    Steps:
        1. Load dataset (NIfTI/DICOM + gradient table)
        2. Reslice to target voxel size (optional)
        3. Denoise (Patch2Self or NLMeans)
        4. Brain masking (median Otsu on b0 volumes)
        5. Gibbs unringing (optional)
        6. Motion correction (optional)
        7. Save outputs

    Parameters
    ----------
    input_dir : str or Path
        Directory containing input NIfTI/DICOM and gradient files.
    output_dir : str or Path
        Output directory for preprocessed files.
    filename : str
        Base filename without extension (e.g., "sub01_dwi").
    b0_threshold : float, default=50
        b-value at or below which a volume counts as a b0, in s/mm². The one
        authoritative threshold for this execution: it builds the gradient
        table, and the resulting ``gtab.b0s_mask`` is what brain masking and
        Patch2Self read.
    external_correction : str, default="unknown"
        User declaration of what correction was applied to the input *before*
        csttool received it. Recorded in the report as a declaration; never
        verified, and it changes no processing decision. See
        ``modules/external_declaration.py``.
    denoise_method : str, default="mppca"
        Denoising method: "nlmeans", "patch2self", or "mppca".
        - "nlmeans" uses PIESNO for sigma estimation; requires coil_count.
        - "patch2self" requires bvals and >= 7 directions.
        - "mppca" (Marchenko-Pastur PCA) is self-adaptive; does not
          require coil_count or bvals — it exploits the 4D DWI redundancy
          directly. Best choice for modern multi-channel acquisitions
          where the effective coil count is unknown.
    coil_count : int, default=4
        Number of scanner coils (for NLMeans noise estimation).
        Ignored when denoise_method is "patch2self" or "mppca".
    apply_gibbs_correction : bool, default=False
        Apply Gibbs ringing correction.
    apply_motion_correction : bool, default=False
        Apply between-volume motion correction.
    target_voxel_size : tuple[float, float, float] or None, default=None
        Target voxel size in mm (x, y, z). If provided, data will be resliced
        to this voxel size. If None, no reslicing is performed.
    save_visualizations : bool, default=False
        Save QC visualizations.
    verbose : bool, default=False
        Print detailed processing information.

    Returns
    -------
    dict
        Dictionary containing:
        - 'output_paths': Paths to saved files
        - 'brain_mask': The computed brain mask array
        - 'motion_correction_applied': Whether motion correction was applied
        - 'gtab': The gradient table
    """
    input_dir = Path(input_dir)
    output_dir = Path(output_dir)
    output_dir.mkdir(parents=True, exist_ok=True)

    # The ledger is built as the run proceeds, so its order *is* the order
    # things happened. Externally declared work is prepended below, because it
    # happened before csttool ever saw the data.
    declaration = declaration_record(external_correction)
    stages: list[dict] = []
    if declares_external_work(declaration["declared"]):
        stages.append(_stage(
            "external_correction",
            performed_by="external",
            status="declared_external",
            requested=False,
            method=declaration["declared"],
            parameters=declaration,
            skip_reason=(
                "Performed outside csttool, before the data was received; "
                "recorded as a user declaration and not verified."
            ),
        ))

    # -------------------------------------------------------------------------
    # Step 1: Load dataset
    # -------------------------------------------------------------------------
    if verbose:
        print(f"Loading dataset from {input_dir}")

    nii, gtab, nifti_dir, metadata = load_dataset(
        str(input_dir), filename, b0_threshold=b0_threshold
    )
    data = np.asarray(nii.dataobj) if hasattr(nii, 'dataobj') else nii
    affine = nii.affine if hasattr(nii, 'affine') else np.eye(4)

    # Get current voxel size from the NIfTI header
    current_voxel_size = nii.header.get_zooms()[:3]
    print(f"PREPROCESSING: Loaded data with shape {data.shape}")
    print(f"PREPROCESSING: Current voxel size: {current_voxel_size} mm")

    loaded_geometry = _geometry(data, affine)
    # The DICOM branch converts with dicom2nifti and reorients the image *and*
    # its b-vectors to RAS together (AU21); the NIfTI branch touches neither.
    loaded_from_dicom = is_dicom_directory(input_dir)
    stages.append(_stage(
        "load",
        status="executed",
        method="dicom2nifti + validated gradient table" if loaded_from_dicom
        else "nibabel + validated gradient table",
        backend="csttool",
        parameters={
            "input_dir": str(input_dir),
            "filename": filename,
            "source": "dicom" if loaded_from_dicom else "nifti",
            "b0_threshold": b0_threshold,
            "n_volumes": int(len(gtab.bvals)),
            "n_b0": int(np.count_nonzero(gtab.b0s_mask)),
        },
        input_geometry=loaded_geometry,
        output_geometry=loaded_geometry,
        gradient_transform_status=(
            "reoriented_to_ras" if loaded_from_dicom else "none"
        ),
    ))

    # -------------------------------------------------------------------------
    # Step 2: Reslice to target voxel size (optional)
    # -------------------------------------------------------------------------
    reslice_input_geometry = _geometry(data, affine)
    if target_voxel_size is not None:
        print(f"PREPROCESSING: Reslicing to target voxel size: {target_voxel_size} mm")
        data, affine = reslice_voxels(
            data,
            affine,
            voxel_size=current_voxel_size,
            new_voxel_size=target_voxel_size
        )
        print(f"PREPROCESSING: Reslicing complete. New shape: {data.shape}")
    elif verbose:
        print("PREPROCESSING: Reslicing skipped")

    stages.append(_stage(
        "reslice",
        requested=target_voxel_size is not None,
        status="executed" if target_voxel_size is not None else "not_requested",
        method="trilinear resampling" if target_voxel_size is not None else None,
        backend="dipy" if target_voxel_size is not None else None,
        parameters={"target_voxel_size": list(target_voxel_size)}
        if target_voxel_size is not None else {},
        input_geometry=reslice_input_geometry,
        output_geometry=_geometry(data, affine),
        # Changing voxel size does not move the physical gradient frame.
        gradient_transform_status="not_required",
        skip_reason=None if target_voxel_size is not None
        else "No --target-voxel-size given",
    ))

    # -------------------------------------------------------------------------
    # Step 3: Denoise
    # -------------------------------------------------------------------------
    denoised = denoise(
        data,
        bvals=gtab.bvals,
        brain_mask=None,
        denoise_method=denoise_method,
        N=coil_count,
        b0_threshold=b0_threshold,
    )
    print(f"PREPROCESSING: Denoising complete ({denoise_method})")

    stages.append(_stage(
        "denoise",
        status="executed",
        method=denoise_method,
        backend="dipy",
        parameters={
            "coil_count": coil_count if denoise_method == "nlmeans" else None,
            "b0_threshold": b0_threshold,
        },
        input_geometry=_geometry(data, affine),
        output_geometry=_geometry(denoised, affine),
    ))

    # -------------------------------------------------------------------------
    # Step 4: Brain masking
    # -------------------------------------------------------------------------
    masked_data, brain_mask = background_segmentation(denoised, gtab)
    print("PREPROCESSING: Brain masking complete")

    stages.append(_stage(
        "mask",
        status="executed",
        method="median_otsu",
        backend="dipy",
        parameters={
            "median_radius": 2,
            "numpass": 1,
            "autocrop": False,
            "b0_volumes_used": int(np.count_nonzero(gtab.b0s_mask)),
        },
        input_geometry=_geometry(denoised, affine),
        output_geometry=_geometry(masked_data, affine),
    ))

    # -------------------------------------------------------------------------
    # Step 5: Gibbs unringing (optional)
    # -------------------------------------------------------------------------
    if apply_gibbs_correction:
        unringed = gibbs_unringing(masked_data)
        data_for_motion = unringed
        print("PREPROCESSING: Gibbs ringing correction complete")
    else:
        data_for_motion = masked_data
        if verbose:
            print("PREPROCESSING: Gibbs ringing correction skipped")

    stages.append(_stage(
        "gibbs",
        requested=apply_gibbs_correction,
        status="executed" if apply_gibbs_correction else "not_requested",
        method="gibbs_removal (local subvoxel-shift)" if apply_gibbs_correction else None,
        backend="dipy" if apply_gibbs_correction else None,
        input_geometry=_geometry(masked_data, affine),
        output_geometry=_geometry(data_for_motion, affine),
        skip_reason=None if apply_gibbs_correction else "--unring not given",
    ))

    # -------------------------------------------------------------------------
    # Step 6: Motion correction (optional)
    # -------------------------------------------------------------------------
    motion_correction_applied = False
    reg_affines = None
    rotated_bvecs = None
    max_rotation_deg = None
    warnings: list[str] = []

    if apply_motion_correction:
        try:
            preprocessed, reg_affines = perform_motion_correction(
                data_for_motion,
                gtab,
                affine,
                brain_mask=brain_mask
            )
            motion_correction_applied = True
            print("PREPROCESSING: Motion correction complete")

            # The volumes have been rotated onto the reference pose, so the
            # b-vectors must follow: a resampled volume paired with its
            # nominal gradient direction biases FA/MD and tilts V1 (Leemans &
            # Jones 2009). This sits inside the same try block on purpose — if
            # the rotation cannot be computed, the handler below discards the
            # motion-corrected data too, so what ships is always a mutually
            # consistent data/gradient pair rather than corrected volumes with
            # uncorrected gradients (the defect this milestone fixes).
            rotated_bvecs = rotate_bvecs_for_motion(
                gtab.bvals,
                gtab.bvecs,
                reg_affines,
                gtab.b0s_mask,
                affine,
                b0_threshold=b0_threshold,
            )
            max_rotation_deg = max_rotation_angle_deg(reg_affines)
            print(
                f"PREPROCESSING: b-vectors rotated "
                f"(max estimated head rotation {max_rotation_deg:.2f}°)"
            )
        except Exception as e:
            print(f"PREPROCESSING: Motion correction failed: {e}")
            print("   Continuing without motion correction")
            warnings.append(
                f"Motion correction was requested but failed ({type(e).__name__}: {e}); "
                "continued with uncorrected data and the original gradients."
            )
            motion_correction_applied = False
            reg_affines = None
            rotated_bvecs = None
            preprocessed = data_for_motion
    else:
        preprocessed = data_for_motion
        if verbose:
            print("PREPROCESSING: Motion correction skipped")

    n_dwi = int(np.count_nonzero(~gtab.b0s_mask))
    if not apply_motion_correction:
        motion_status = "not_requested"
    elif motion_correction_applied:
        motion_status = "executed"
    else:
        motion_status = "failed_continued"

    stages.append(_stage(
        "motion_correction",
        requested=apply_motion_correction,
        status=motion_status,
        method="register_dwi_series [center_of_mass, translation, rigid, affine]"
        if apply_motion_correction else None,
        backend="dipy" if apply_motion_correction else None,
        parameters={
            "scope": "between-volume affine motion correction only; no "
                     "eddy-current, outlier or susceptibility correction",
            "reference": "mean of registered b0 volumes",
        } if apply_motion_correction else {},
        input_geometry=_geometry(data_for_motion, affine),
        output_geometry=_geometry(preprocessed, affine),
        gradient_transform_status=(
            "bvecs_rotated" if rotated_bvecs is not None
            else "not_required" if not apply_motion_correction
            else "none"
        ),
        n_volumes_rotated=n_dwi if rotated_bvecs is not None else 0,
        max_rotation_deg=max_rotation_deg,
        warnings=warnings,
        skip_reason=None if apply_motion_correction
        else "--perform-motion-correction not given",
    ))

    # -------------------------------------------------------------------------
    # Step 7: Save outputs
    # -------------------------------------------------------------------------
    suffix = "_mc" if motion_correction_applied else "_nomc"
    output_stem = f"{filename}_dwi_preproc{suffix}"

    # Build gradient file paths
    bval_path = input_dir / f"{filename}.bval"
    if not bval_path.exists():
        bval_path = input_dir / f"{filename}.bvals"

    bvec_path = input_dir / f"{filename}.bvec"
    if not bvec_path.exists():
        bvec_path = input_dir / f"{filename}.bvecs"

    gradient_files = {}
    if bval_path.exists():
        gradient_files['bval'] = bval_path
    if bvec_path.exists():
        gradient_files['bvec'] = bvec_path

    final_geometry = _geometry(preprocessed, affine)
    stages.append(_stage(
        "save",
        status="executed",
        method="NIfTI + FSL-style gradient sidecars",
        backend="nibabel",
        parameters={
            "filename_stem": output_stem,
            "bvec_source": "rotated by csttool" if rotated_bvecs is not None
            else "copied from input",
            "bval_source": "copied from input",
        },
        input_geometry=final_geometry,
        output_geometry=final_geometry,
        gradient_transform_status=(
            "bvecs_rotated" if rotated_bvecs is not None else "none"
        ),
        n_volumes_rotated=n_dwi if rotated_bvecs is not None else 0,
        max_rotation_deg=max_rotation_deg,
    ))

    output_paths = save_preprocessed(
        data=preprocessed,
        affine=affine,
        output_dir=output_dir,
        filename_stem=output_stem,
        gradient_files=gradient_files if gradient_files else None,
        bvecs=rotated_bvecs,
        brain_mask=brain_mask,
        ledger=stages,
        provenance=get_provenance_dict(),
        processing_params={
            'denoise_method': denoise_method,
            'b0_threshold': b0_threshold,
            'external_correction': declaration_record(external_correction),
            'gibbs_correction': apply_gibbs_correction,
            # requested vs applied: a failed motion correction used to be
            # distinguishable only by the output filename suffix.
            'motion_correction_requested': apply_motion_correction,
            'motion_correction': motion_correction_applied,
            'bvecs_rotated': rotated_bvecs is not None,
            'max_rotation_deg': max_rotation_deg,
            'resliced': target_voxel_size is not None,
            'target_voxel_size': target_voxel_size if target_voxel_size else None,
            'warnings': warnings,
        }
    )
    print(f"PREPROCESSING: Saved outputs to {output_dir}")

    # -------------------------------------------------------------------------
    # Step 8: Visualizations (optional)
    # -------------------------------------------------------------------------
    if save_visualizations:
        try:
            from .modules.visualizations import save_all_preprocessing_visualizations
            # Pass the stage directory; save_all_preprocessing_visualizations appends
            # the single "visualizations/" subdir itself. Passing an already-"visualizations"
            # path here doubled it (…/visualizations/visualizations/) so the BIDS reorg,
            # which globs …/preprocessing/visualizations/*.png, never found the figures.
            save_all_preprocessing_visualizations(
                data_original=data,  # Raw data before any processing
                data_denoised=denoised,  # Denoised (same shape as original)
                data_masked=masked_data,  # After brain masking (cropped)
                data_unringed=unringed if apply_gibbs_correction else None,
                data_preprocessed=preprocessed,
                brain_mask=brain_mask,
                gtab=gtab,
                output_dir=output_dir,
                stem=filename,
                denoise_method=denoise_method,
                reg_affines=reg_affines,
                motion_correction_applied=motion_correction_applied,
                affine=affine,
                title_id=title_id,
            )
            print("PREPROCESSING: QC visualizations saved")
        except Exception as e:
            print(f"PREPROCESSING: Visualization saving failed: {e}")

    print(f"\nPREPROCESSING COMPLETED")

    return {
        'output_paths': output_paths,
        'brain_mask': brain_mask,
        'motion_correction_applied': motion_correction_applied,
        'bvecs_rotated': rotated_bvecs is not None,
        'max_rotation_deg': max_rotation_deg,
        'warnings': warnings,
        'gtab': gtab,
    }

load_dataset(dir_path, fname, *, b0_threshold=DEFAULT_B0_THRESHOLD)

Load dataset from DICOM directory or NIfTI file and build gradient table.

Parameters:

Name Type Description Default
dir_path str

Path to the directory containing the dataset.

required
fname str

Name of the file to load.

required
b0_threshold float

b-value at or below which a volume counts as a b0, in s/mm². This is the execution's single authoritative threshold (--b0-threshold); it decides gtab.b0s_mask, which in turn drives brain masking and Patch2Self.

DEFAULT_B0_THRESHOLD

Returns:

Name Type Description
nii Nifti1Image

NIfTI image.

bval str

Path to the bval file.

bvec str

Path to the bvec file.

gtab GradientTable

Gradient table.

Source code in src/csttool/preprocess/modules/load_dataset.py
def load_dataset(
    dir_path: str,
    fname: str,
    *,
    b0_threshold: float = DEFAULT_B0_THRESHOLD,
):
    """
    Load dataset from DICOM directory or NIfTI file and build gradient table.

    Parameters
    ----------
    dir_path : str
        Path to the directory containing the dataset.
    fname : str
        Name of the file to load.
    b0_threshold : float, optional
        b-value at or below which a volume counts as a b0, in s/mm². This is
        the execution's single authoritative threshold (``--b0-threshold``);
        it decides ``gtab.b0s_mask``, which in turn drives brain masking and
        Patch2Self.

    Returns
    -------
    nii : Nifti1Image
        NIfTI image.
    bval : str
        Path to the bval file.
    bvec : str
        Path to the bvec file.
    gtab : GradientTable
        Gradient table.
    """
    # Check if the directory exists
    dir_path = Path(dir_path)
    if not dir_path.is_dir():
        raise ValueError(f"Directory {dir_path} does not exist")

    # Check if DICOM directory
    if is_dicom_directory(dir_path):
        print(f"DICOM directory detected: {dir_path}")
        # Convert DICOM to NIfTI.
        # AU21: dicom2nifti's ``reorient_nifti=True`` reorients the *image* to
        # LAS but leaves the *bvecs* in the original scanner voxel space, so the
        # two become mutually inconsistent (a silent gradient flip that
        # corrupts the tensor fit). We therefore convert with
        # ``reorient_nifti=False`` (image + bvecs both in scanner voxel space,
        # consistent) and reorient *both* to RAS together below, matching the
        # dcm2niix primary path's convention.
        print(f"Converting DICOM to NIfTI...")
        nifti_dir = dir_path.parent / "nifti"
        nifti_dir.mkdir(parents=True, exist_ok=True)  # Create directory if it doesn't exist
        result = dicom2nifti.dicom_series_to_nifti(
            str(dir_path),
            str(nifti_dir / (fname + ".nii.gz")),
            reorient_nifti=False,
        )
        nii_path = result["NII_FILE"]
        bval_path = result.get("BVAL_FILE")
        bvec_path = result.get("BVEC_FILE")

        # Reorient image + bvecs to RAS together and rewrite the bvec sidecar so
        # every later stage (get_gtab_for_preproc reads these same files) sees a
        # consistent image/bvec pair. b-values are orientation-invariant, so the
        # .bval file is left untouched.
        raw_img = nib.load(nii_path)
        _bvals, raw_bvecs = read_bvals_bvecs(bval_path, bvec_path)
        # dicom2nifti's b-vectors are in a vendor-specific frame that is not the
        # voxel frame of the NIfTI it wrote (Siemens inverts the phase axis).
        # Undo that before reorienting, or the RAS pair is silently mirrored.
        from csttool.ingest.modules.convert_series import _read_manufacturer
        raw_bvecs, bvec_note = correct_dicom2nifti_bvecs(
            raw_bvecs, _read_manufacturer(dir_path)
        )
        print(f"  → gradients: {bvec_note}")
        ras_img, ras_bvecs = reorient_dwi_to_ras(raw_img, raw_bvecs)
        nib.save(ras_img, nii_path)
        # bvecs are stored transposed (3, N) per FSL/dicom2nifti convention.
        np.savetxt(bvec_path, ras_bvecs.T, fmt="%.8f")
        nii = ras_img
    else:
        print(f"NIfTI directory detected: {dir_path}")
        nifti_dir = dir_path
        nii_path = os.path.join(dir_path, fname + ".nii.gz")

        # Try .bval first, then .bvals for gradient files
        bval_path = os.path.join(dir_path, fname + ".bval")
        if not os.path.exists(bval_path):
            bval_path = os.path.join(dir_path, fname + ".bvals")

        bvec_path = os.path.join(dir_path, fname + ".bvec")
        if not os.path.exists(bvec_path):
            bvec_path = os.path.join(dir_path, fname + ".bvecs")

        nii = nib.load(nii_path)

    # Read bvalues and bvectors, build a validated gradient table.
    # AU21: validate at load (unit-norm DWI bvecs, non-negative bvals, b0>=1,
    # shape/count match) so a malformed table fails loudly instead of silently
    # corrupting the tensor fit.
    bvals, bvecs = read_bvals_bvecs(bval_path, bvec_path)
    gtab = validate_gradient_table(
        bvals, bvecs, b0_threshold=b0_threshold
    )
    num_of_gradients = len(gtab)

    # AU31: confirm the NIfTI data array is actually readable on disk. A
    # truncated .nii.gz loads its header fine (nib.load succeeds, shape looks
    # correct) but get_fdata()/dataobj raises EOFError deep in the pipeline.
    # Surface that here as a clear "file truncated" message naming the path.
    try:
        _ = nii.get_fdata(dtype=np.float32, caching="unchanged")
    except (EOFError, OSError) as e:
        raise ValueError(
            f"NIfTI file appears truncated or corrupt and could not be read: "
            f"{nii_path}\n  ({type(e).__name__}: {e})"
        ) from e


    # Try to load JSON sidecar
    metadata = {}
    json_path = nifti_dir / (fname + ".json")
    if not json_path.exists():
        # Try finding json with same name as nifti
        json_path = Path(nii_path).with_suffix('').with_suffix('.json')

    if json_path.exists():
        try:
            import json
            with open(json_path, 'r') as f:
                sidecar = json.load(f)

            # Extract standard BIDS fields
            metadata = {
                'MagneticFieldStrength': sidecar.get('MagneticFieldStrength'),
                'EchoTime': sidecar.get('EchoTime'),
                'RepetitionTime': sidecar.get('RepetitionTime'),
                'Manufacturer': sidecar.get('Manufacturer'),
                'DeviceSerialNumber': sidecar.get('DeviceSerialNumber'),
                'SoftwareVersions': sidecar.get('SoftwareVersions'),
                'dcm2niix_version': sidecar.get('ConversionSoftwareVersion'),
            }
            # Clean up None values
            metadata = {k: v for k, v in metadata.items() if v is not None}
            print(f"  → Loaded metadata from sidecar: {json_path}")
        except Exception as e:
            print(f"  ⚠️ Could not read JSON sidecar: {e}")

    # Add derived fields
    metadata.update({
        'VoxelSize': [float(x) for x in nii.header.get_zooms()[:3]],
        'Dimensions': [int(x) for x in nii.shape],
        'NumVolumes': nii.shape[3] if len(nii.shape) > 3 else 1,
        'NumDirections': len(gtab.bvals) if hasattr(gtab, 'bvals') else 0,
        'MaxBValue': float(gtab.bvals.max()) if hasattr(gtab, 'bvals') and len(gtab.bvals) > 0 else 0,
    })

    print(gtab.info)
    print(f"Number of gradients: {num_of_gradients}")
    print("\n" + "=" * 60)

    return nii, gtab, nifti_dir, metadata

denoise(data, bvals=None, brain_mask=None, denoise_method=DEFAULT_DENOISE_METHOD, N=4, patch_radius=2, b0_threshold=DEFAULT_B0_THRESHOLD)

Denoise DWI data.

Parameters:

Name Type Description Default
data ndarray

4D DWI data array.

required
bvals ndarray

1D array of b values. Required for Patch2Self; ignored for NLMeans and MPPCA.

None
brain_mask ndarray

3D brain mask array. Used by NLMeans (restricts denoise region; PIESNO fallback if None) and MPPCA (restricts PCA neighbourhood computation). Ignored for Patch2Self.

None
denoise_method str

Denoising method to use. One of:

  • "nlmeans" — Non-local means (Veraart et al. 2016). Requires N (coil count). Uses PIESNO for sigma estimation.
  • "patch2self" — Self-supervised denoising (Fadnavis et al. 2020). Requires bvals.
  • "mppca" — Marchenko-Pastur PCA (Veraart et al. 2016). Self-adaptive; does NOT require N or bvals.
DEFAULT_DENOISE_METHOD
N int

Number of scanner receiver coils. Used only by NLMeans for PIESNO noise estimation. Ignored by Patch2Self and MPPCA. Default: 4.

.. warning:: Must match the actual acquisition hardware. A wrong N biases sigma → biases NLMeans shrinkage → biases all downstream DTI metrics. For modern multi-channel head coils (e.g. 32/64-channel) with adaptive combine readout this parameter may not be meaningful; prefer MPPCA in that case.

4
patch_radius int

Patch radius for MPPCA local-PCA neighbourhood. Default 2 gives a 5×5×5 voxel patch (125 voxels) — DIPY sizes the patch as 2·radius+1 per side. Larger patches increase smoothing but reduce spatial specificity. Ignored by NLMeans and Patch2Self.

2
b0_threshold float

b-value at or below which a volume counts as a b0, in s/mm². Only used by Patch2Self, which partitions the series on it. Must be the same threshold the gradient table was built with.

DEFAULT_B0_THRESHOLD

Returns:

Name Type Description
denoised_data ndarray

4D denoised DWI data array.

References

.. [1] Veraart et al., "Denoising-based nonlinear averaging improves resolution limited diffusion MRI and DTI". NeuroImage 125, 873-886 (2016). [NLMeans] .. [2] Fadnavis et al., "Patch2Self: Denoising Diffusion MRI with Self-Supervised Learning". NeuroImage 223, 117389 (2020). .. [3] Veraart et al., "Denoising of diffusion MRI using random matrix theory". NeuroImage 134, 387-399 (2016). [MPPCA]

Source code in src/csttool/preprocess/modules/denoise.py
def denoise(
    data: np.ndarray,
    bvals: np.ndarray = None,
    brain_mask: np.ndarray = None,
    denoise_method: str = DEFAULT_DENOISE_METHOD,
    N: int = 4,
    patch_radius: int = 2,
    b0_threshold: float = DEFAULT_B0_THRESHOLD,
):
    """
    Denoise DWI data.

    Parameters
    ----------
    data : np.ndarray
        4D DWI data array.
    bvals : np.ndarray
        1D array of b values. Required for Patch2Self; ignored for
        NLMeans and MPPCA.
    brain_mask : np.ndarray
        3D brain mask array. Used by NLMeans (restricts denoise region;
        PIESNO fallback if None) and MPPCA (restricts PCA neighbourhood
        computation). Ignored for Patch2Self.
    denoise_method : str
        Denoising method to use. One of:

        - ``"nlmeans"`` — Non-local means (Veraart et al. 2016).
          Requires *N* (coil count). Uses PIESNO for sigma estimation.
        - ``"patch2self"`` — Self-supervised denoising (Fadnavis et al.
          2020). Requires *bvals*.
        - ``"mppca"`` — Marchenko-Pastur PCA (Veraart et al. 2016).
          Self-adaptive; does NOT require *N* or *bvals*.

    N : int
        Number of scanner receiver coils. Used only by NLMeans for PIESNO
        noise estimation. Ignored by Patch2Self and MPPCA.
        Default: 4.

        .. warning:: Must match the actual acquisition hardware. A wrong
           *N* biases sigma → biases NLMeans shrinkage → biases all
           downstream DTI metrics. For modern multi-channel head coils
           (e.g. 32/64-channel) with adaptive combine readout this
           parameter may not be meaningful; prefer MPPCA in that case.

    patch_radius : int
        Patch radius for MPPCA local-PCA neighbourhood. Default 2 gives
        a 5×5×5 voxel patch (125 voxels) — DIPY sizes the patch as
        2·radius+1 per side. Larger patches increase smoothing but reduce
        spatial specificity. Ignored by NLMeans and Patch2Self.

    b0_threshold : float
        b-value at or below which a volume counts as a b0, in s/mm². Only
        used by Patch2Self, which partitions the series on it. Must be the
        same threshold the gradient table was built with.

    Returns
    -------
    denoised_data : np.ndarray
        4D denoised DWI data array.

    References
    ----------
    .. [1] Veraart et al., "Denoising-based nonlinear averaging improves
       resolution limited diffusion MRI and DTI". NeuroImage 125, 873-886
       (2016). [NLMeans]
    .. [2] Fadnavis et al., "Patch2Self: Denoising Diffusion MRI with
       Self-Supervised Learning". NeuroImage 223, 117389 (2020).
    .. [3] Veraart et al., "Denoising of diffusion MRI using random matrix
       theory". NeuroImage 134, 387-399 (2016). [MPPCA]
    """

    available_methods = ["nlmeans", "patch2self", "mppca"]
    if denoise_method not in available_methods:
        raise ValueError(
            f"Invalid denoise method: {denoise_method}. "
            f"Available methods: {available_methods}"
        )

    # ==================================================================
    # NLMeans — Non-Local Means denoising
    # Requires : N (coil count for PIESNO sigma estimation)
    # Optional : brain_mask (restricts denoise region)
    # ==================================================================
    if denoise_method == "nlmeans":
        print("Denoising with NLM...")
        noise, noise_mask = piesno(data, N=N, return_mask=True)
        sigma = float(np.mean(noise))  # noise std deviation
        if brain_mask is None:
            print("  ⚠️  Brain mask is None, using noise mask as rudimentary brain mask")
            brain_mask = ~noise_mask
        denoised_data = nlmeans(
            data.astype(np.float32),
            sigma=sigma,
            mask=brain_mask,
            patch_radius=1,
            block_radius=2,
            rician=False,  # Assuming Gaussian noise
            num_threads=1,  # Multithreading introduces non-determinism; use single thread for reproducibility
        )

    # ==================================================================
    # Patch2Self — self-supervised denoising
    # Requires : bvals (uses diffusion signal redundancy across volumes)
    # ==================================================================
    elif denoise_method == "patch2self":
        if bvals is None:
            raise ValueError(
                "Patch2Self requires bvals. Pass the bvals array or use "
                "a different denoise method (nlmeans or mppca)."
            )
        print("Denoising with Patch2Self...")
        denoised_data = patch2self(
            data,
            bvals=bvals,
            model="ols",
            shift_intensity=True,
            clip_negative_vals=False,
            b0_threshold=b0_threshold,
        )

    # ==================================================================
    # MPPCA — Marchenko-Pastur PCA denoising
    # Self-adaptive: estimates the noise level from the eigenvalue
    # distribution of local-PCA patches, using the Marchenko-Pastur
    # distribution from random matrix theory.  Does NOT require the
    # number of coils (N) or bvals — it exploits the redundancy of the
    # multi-volume DWI directly.
    #
    # The mask parameter (if provided) limits which voxels are included
    # in the local PCA computation, reducing memory and runtime on
    # large volumes with mostly-background voxels.
    #
    # Reference: Veraart et al., "Denoising of diffusion MRI using
    # random matrix theory", NeuroImage 134, 387-399 (2016).
    # ==================================================================
    elif denoise_method == "mppca":
        from dipy.denoise.localpca import mppca as _mppca

        print(f"Denoising with MPPCA (patch_radius={patch_radius})...")

        if data.ndim != 4:
            raise ValueError(
                f"MPPCA requires 4D data, got {data.ndim}D"
            )

        denoised_data = _mppca(
            data,
            mask=brain_mask,
            patch_radius=patch_radius,
            pca_method="eig",  # Eigenvalue decomposition (faster than SVD for small patches)
            return_sigma=False,
        )

    return denoised_data

gibbs_unringing(data, slice_axis=2, n_points=3)

Remove Gibbs' ringing artifacts from DWI data.

Gibbs ringing artifacts appear as spurious oscillations near sharp edges in MR images due to truncation of k-space data.

Parameters:

Name Type Description Default
data ndarray

3D or 4D DWI data array.

required
slice_axis int

Axis along which slices were acquired (0, 1, or 2). Default is 2.

2
n_points int

Number of neighbor points to access local TV. Default is 3.

3

Returns:

Name Type Description
data_corrected ndarray

3D or 4D DWI data array with Gibbs ringing artifacts removed.

Source code in src/csttool/preprocess/modules/gibbs_unringing.py
def gibbs_unringing(
    data: np.ndarray,
    slice_axis: int = 2,
    n_points: int = 3
) -> np.ndarray:
    """
    Remove Gibbs' ringing artifacts from DWI data.

    Gibbs ringing artifacts appear as spurious oscillations near sharp edges
    in MR images due to truncation of k-space data.

    Parameters
    ----------
    data : np.ndarray
        3D or 4D DWI data array.
    slice_axis : int, optional
        Axis along which slices were acquired (0, 1, or 2). Default is 2.
    n_points : int, optional
        Number of neighbor points to access local TV. Default is 3.

    Returns
    -------
    data_corrected : np.ndarray
        3D or 4D DWI data array with Gibbs ringing artifacts removed.
    """
    if slice_axis not in [0, 1, 2]:
        raise ValueError(f"slice_axis must be 0, 1, or 2, got {slice_axis}")

    data_corrected = gibbs_removal(
        data,
        slice_axis=slice_axis,
        n_points=n_points,
        num_processes=1  # Use a single process to avoid non-determinism from parallel processing
    )
    return data_corrected

background_segmentation(data, gtab=None, median_radius=2, numpass=1, autocrop=False)

Estimate brain mask with median Otsu.

Parameters:

Name Type Description Default
data ndarray

4D DWI data array.

required
gtab GradientTable

Gradient table to identify b0 volumes. If provided, only the volumes marked by gtab.b0s_mask are used for mask computation. If None, only the first volume is used (for 4D input).

None
median_radius int

Radius of the median filter. Default is 2.

2
numpass int

Number of passes for the median filter. Default is 1.

1
autocrop bool

Whether to autocrop the data. Default is False.

False

Returns:

Name Type Description
masked_data ndarray

4D masked DWI data array.

mask ndarray

3D binary brain mask array.

Source code in src/csttool/preprocess/modules/background_segmentation.py
def background_segmentation(
    data: np.ndarray,
    gtab=None,
    median_radius: int = 2,
    numpass: int = 1,
    autocrop: bool = False
) -> tuple[np.ndarray, np.ndarray]:
    """
    Estimate brain mask with median Otsu.

    Parameters
    ----------
    data : np.ndarray
        4D DWI data array.
    gtab : GradientTable, optional
        Gradient table to identify b0 volumes. If provided, only the volumes
        marked by ``gtab.b0s_mask`` are used for mask computation. If None,
        only the first volume is used (for 4D input).
    median_radius : int, optional
        Radius of the median filter. Default is 2.
    numpass : int, optional
        Number of passes for the median filter. Default is 1.
    autocrop : bool, optional
        Whether to autocrop the data. Default is False.

    Returns
    -------
    masked_data : np.ndarray
        4D masked DWI data array.
    mask : np.ndarray
        3D binary brain mask array.
    """
    # Determine which volumes to use for mask computation
    vol_idx = None
    if gtab is not None:
        # Read the gradient table's own b0 partition rather than re-deriving it
        # from a module-level constant: the table was built with the b0
        # threshold this execution was given (--b0-threshold), so re-thresholding
        # here made masking disagree with the tensor fit whenever the threshold
        # was not the default. One table, one answer.
        b0_idx = np.where(gtab.b0s_mask)[0]
        if b0_idx.size > 0:
            vol_idx = b0_idx
    else:
        # If no gtab provided, default to using the first volume
        if data.ndim == 4:
            vol_idx = [0]

    masked_data, mask = median_otsu(
        data,
        vol_idx=vol_idx,
        median_radius=median_radius,
        numpass=numpass,
        autocrop=autocrop
    )

    return masked_data, mask

perform_motion_correction(data, gtab, affine, brain_mask=None)

Perform between-volume motion correction.

Parameters:

Name Type Description Default
data ndarray

4D DWI data array.

required
gtab GradientTable

Gradient table containing b-values and b-vectors.

required
affine ndarray

4x4 affine transformation matrix.

required
brain_mask ndarray or None

Binary brain mask to constrain registration. If provided, will be converted to uint8 and passed as static_mask.

None

Returns:

Name Type Description
data_corrected ndarray

4D DWI data array with motion correction applied.

reg_affines list

List of 4x4 registration affine matrices for each volume.

Source code in src/csttool/preprocess/modules/perform_motion_correction.py
def perform_motion_correction(
    data: np.ndarray,
    gtab,
    affine: np.ndarray,
    brain_mask: np.ndarray | None = None
) -> tuple[np.ndarray, list]:
    """
    Perform between-volume motion correction.

    Parameters
    ----------
    data : np.ndarray
        4D DWI data array.
    gtab : GradientTable
        Gradient table containing b-values and b-vectors.
    affine : np.ndarray
        4x4 affine transformation matrix.
    brain_mask : np.ndarray or None, optional
        Binary brain mask to constrain registration. If provided,
        will be converted to uint8 and passed as static_mask.

    Returns
    -------
    data_corrected : np.ndarray
        4D DWI data array with motion correction applied.
    reg_affines : list
        List of 4x4 registration affine matrices for each volume.
    """
    # Ensure mask is binary uint8 if provided
    if brain_mask is not None:
        brain_mask = brain_mask.astype(np.float64)
        data_corrected, reg_affines = motion_correction(
            data,
            gtab,
            affine=affine,
            static_mask=brain_mask
        )
    else:
        data_corrected, reg_affines = motion_correction(
            data,
            gtab,
            affine=affine
        )

    # dipy.align.motion_correction returns a Nifti1Image; extract the array
    if hasattr(data_corrected, 'get_fdata'):
        data_corrected = data_corrected.get_fdata(dtype=np.float32)

    return data_corrected, reg_affines

max_rotation_angle_deg(reg_affines)

Largest per-volume rotation magnitude in the stack, in degrees.

QC summary for the provenance ledger and the console: how much head rotation the registration thinks it removed.

Source code in src/csttool/preprocess/modules/reorient_gradients.py
def max_rotation_angle_deg(reg_affines) -> float:
    """Largest per-volume rotation magnitude in the stack, in degrees.

    QC summary for the provenance ledger and the console: how much head rotation
    the registration thinks it removed.
    """
    affines = _as_affine_stack(reg_affines)
    angles = []
    for i in range(affines.shape[-1]):
        rot = rotation_part(affines[..., i])
        # A rotation's trace fixes its angle: tr(R) = 1 + 2cos(theta).
        cos_theta = (np.trace(rot) - 1.0) / 2.0
        angles.append(np.degrees(np.arccos(np.clip(cos_theta, -1.0, 1.0))))
    return float(np.max(angles)) if angles else 0.0

rotate_bvecs_for_motion(bvals, bvecs, reg_affines, b0s_mask, image_affine, *, b0_threshold=50)

Apply motion-correction rotations to b-vectors.

Parameters:

Name Type Description Default
bvals (ndarray, shape(N))

b-values as carried by the gradient table used for motion correction.

required
bvecs (ndarray, shape(N, 3))

b-vectors in the image's voxel frame (the DIPY/FSL convention). b0 rows are all-zero.

required
reg_affines (ndarray, shape(4, 4, N) or (N, 4, 4))

Per-volume world-space transforms as returned by dipy.align.motion_correction — one for every volume, b0s included.

required
b0s_mask ndarray of bool, shape (N,)

Which volumes are b0. Used both to select the DWI affines and to keep b0 rows zero.

required
image_affine (ndarray, shape(4, 4))

The affine of the data that was registered. Only its orientation is used (see module docstring).

required
b0_threshold float

The execution's b0 threshold, needed to rebuild an equivalent gradient table in the world frame. Must be the one b0s_mask was derived with; a mismatch raises.

50

Returns:

Name Type Description
rotated_bvecs (ndarray, shape(N, 3))

b-vectors in the same voxel frame and volume order as the input. DWI rows are unit-norm; b0 rows are exactly zero.

Source code in src/csttool/preprocess/modules/reorient_gradients.py
def rotate_bvecs_for_motion(
    bvals: np.ndarray,
    bvecs: np.ndarray,
    reg_affines,
    b0s_mask: np.ndarray,
    image_affine: np.ndarray,
    *,
    b0_threshold: float = 50,
) -> np.ndarray:
    """Apply motion-correction rotations to b-vectors.

    Parameters
    ----------
    bvals : ndarray, shape (N,)
        b-values as carried by the gradient table used for motion correction.
    bvecs : ndarray, shape (N, 3)
        b-vectors in the image's **voxel** frame (the DIPY/FSL convention).
        b0 rows are all-zero.
    reg_affines : ndarray, shape (4, 4, N) or (N, 4, 4)
        Per-volume world-space transforms as returned by
        ``dipy.align.motion_correction`` — one for every volume, b0s included.
    b0s_mask : ndarray of bool, shape (N,)
        Which volumes are b0. Used both to select the DWI affines and to keep
        b0 rows zero.
    image_affine : ndarray, shape (4, 4)
        The affine of the data that was registered. Only its orientation is
        used (see module docstring).
    b0_threshold : float, optional
        The execution's b0 threshold, needed to rebuild an equivalent gradient
        table in the world frame. Must be the one ``b0s_mask`` was derived
        with; a mismatch raises.

    Returns
    -------
    rotated_bvecs : ndarray, shape (N, 3)
        b-vectors in the same voxel frame and volume order as the input. DWI
        rows are unit-norm; b0 rows are exactly zero.
    """
    from dipy.core.gradients import gradient_table_from_bvals_bvecs, reorient_bvecs

    bvals = np.asarray(bvals, dtype=float)
    bvecs = np.asarray(bvecs, dtype=float)
    b0s_mask = np.asarray(b0s_mask, dtype=bool)

    if bvecs.ndim != 2 or bvecs.shape[1] != 3:
        raise ValueError(f"bvecs must be (N, 3), got shape {bvecs.shape}")
    if bvals.shape[0] != bvecs.shape[0] or b0s_mask.shape[0] != bvecs.shape[0]:
        raise ValueError(
            "bvals, bvecs and b0s_mask must describe the same number of volumes"
        )

    affines = _as_affine_stack(reg_affines)
    if affines.shape[-1] != bvecs.shape[0]:
        raise ValueError(
            f"reg_affines covers {affines.shape[-1]} volumes but the gradient "
            f"table has {bvecs.shape[0]}"
        )

    dwi = ~b0s_mask
    if not dwi.any():
        # Nothing to rotate; hand back a copy so callers can always use the result.
        return bvecs.copy()

    # --- voxel frame -> world frame ---------------------------------------
    # Orthonormal, so norms are preserved exactly and the inverse is the
    # transpose (true for negative-determinant / sign-flipped orientations too).
    vox2world = rotation_part(image_affine)
    bvecs_world = bvecs @ vox2world.T

    gtab_world = gradient_table_from_bvals_bvecs(
        bvals, bvecs_world, b0_threshold=b0_threshold
    )
    if not np.array_equal(gtab_world.b0s_mask, b0s_mask):
        raise ValueError(
            "b0_threshold does not reproduce the supplied b0s_mask; the "
            "gradient table and the rotation would disagree about which "
            "volumes are b0"
        )

    # --- apply the inverse of each volume's rotation (DIPY's primitive) ----
    # Only the DWI affines, in the order reorient_bvecs expects.
    dwi_affines = affines[..., dwi]
    rotated_world = reorient_bvecs(gtab_world, dwi_affines).bvecs

    # --- world frame -> voxel frame ---------------------------------------
    rotated = rotated_world @ vox2world

    # Renormalise DWI rows to absorb floating-point drift; b0 rows stay zero.
    rotated[b0s_mask] = 0.0
    norms = np.linalg.norm(rotated[dwi], axis=1, keepdims=True)
    rotated[dwi] = rotated[dwi] / norms

    return rotated

save_preprocessed(data, affine, output_dir, filename_stem, *, gradient_files=None, bvecs=None, brain_mask=None, metadata=None, processing_params=None, ledger=None, provenance=None, create_report=True)

Save preprocessed DWI data with auxiliary files and metadata.

Parameters:

Name Type Description Default
data ndarray

Preprocessed 4D DWI data array (X, Y, Z, volumes).

required
affine ndarray

4x4 affine transformation matrix from NIfTI header.

required
output_dir str or Path

Output directory for all files (flat structure).

required
filename_stem str

Base filename without extension (e.g., "sub01_dwi_preproc").

required
gradient_files dict or None

Dictionary with keys 'bval' and 'bvec' pointing to source files. If provided, these will be copied to the output directory.

None
bvecs ndarray or None

Transformed b-vectors, shape (N, 3), in the DIPY voxel-frame convention. When given, the .bvec sidecar is written from this array (3xN on disk, the dcm2niix/FSL layout) instead of copied from gradient_files. Used after motion correction, whose per-volume rotations must be carried into the gradients. The .bval sidecar is always copied: b-values are unaffected by rotation, and copying keeps the file byte-identical rather than round-tripping through the gradient table (which rewrites sub-threshold b-values to 0).

None
brain_mask ndarray or None

3D binary brain mask to save alongside data.

None
metadata dict or None

Custom metadata to include in report (e.g., subject ID, session).

None
processing_params dict or None

Processing parameters used (e.g., denoising method, motion correction). Retained as a flat summary; the per-stage detail lives in ledger.

None
ledger list[dict] or None

Ordered per-stage provenance entries, chronological, with externally declared work first. Serialized under the top-level stages key together with a schema_version.

None
provenance dict or None

Output of get_provenance_dict() — git commit, Python and dependency versions, platform, hardware, thread environment. Serialized under provenance. Versions live here once rather than per stage.

None
create_report bool

Whether to generate a JSON processing report.

True

Returns:

Name Type Description
output_paths dict[str, Path]

Dictionary mapping output types to their absolute paths: - 'data': Path to saved preprocessed data - 'bval': Path to copied bval file (if provided) - 'bvec': Path to copied bvec file (if provided) - 'mask': Path to saved brain mask (if provided) - 'report': Path to processing report (if created)

Examples:

>>> paths = save_preprocessed(
...     data=preprocessed_data,
...     affine=affine,
...     output_dir="/data/preprocessed",
...     filename_stem="sub01_dwi_preproc",
...     gradient_files={"bval": "original.bval", "bvec": "original.bvec"},
...     brain_mask=mask,
...     processing_params={"denoise_method": "nlmeans", "motion_correction": True}
... )
Source code in src/csttool/preprocess/modules/save_preprocessed.py
def save_preprocessed(
    data: np.ndarray,
    affine: np.ndarray,
    output_dir: str | Path,
    filename_stem: str,
    *,
    gradient_files: dict[str, str | Path] | None = None,
    bvecs: np.ndarray | None = None,
    brain_mask: np.ndarray | None = None,
    metadata: dict | None = None,
    processing_params: dict | None = None,
    ledger: list[dict] | None = None,
    provenance: dict | None = None,
    create_report: bool = True,
) -> dict[str, Path]:
    """
    Save preprocessed DWI data with auxiliary files and metadata.

    Parameters
    ----------
    data : np.ndarray
        Preprocessed 4D DWI data array (X, Y, Z, volumes).
    affine : np.ndarray
        4x4 affine transformation matrix from NIfTI header.
    output_dir : str or Path
        Output directory for all files (flat structure).
    filename_stem : str
        Base filename without extension (e.g., "sub01_dwi_preproc").

    gradient_files : dict or None, optional
        Dictionary with keys 'bval' and 'bvec' pointing to source files.
        If provided, these will be copied to the output directory.
    bvecs : np.ndarray or None, optional
        Transformed b-vectors, shape (N, 3), in the DIPY voxel-frame
        convention. When given, the ``.bvec`` sidecar is *written* from this
        array (3xN on disk, the dcm2niix/FSL layout) instead of copied from
        ``gradient_files``. Used after motion correction, whose per-volume
        rotations must be carried into the gradients. The ``.bval`` sidecar is
        always copied: b-values are unaffected by rotation, and copying keeps
        the file byte-identical rather than round-tripping through the
        gradient table (which rewrites sub-threshold b-values to 0).
    brain_mask : np.ndarray or None, optional
        3D binary brain mask to save alongside data.
    metadata : dict or None, optional
        Custom metadata to include in report (e.g., subject ID, session).
    processing_params : dict or None, optional
        Processing parameters used (e.g., denoising method, motion correction).
        Retained as a flat summary; the per-stage detail lives in ``ledger``.
    ledger : list[dict] or None, optional
        Ordered per-stage provenance entries, chronological, with externally
        declared work first. Serialized under the top-level ``stages`` key
        together with a ``schema_version``.
    provenance : dict or None, optional
        Output of ``get_provenance_dict()`` — git commit, Python and dependency
        versions, platform, hardware, thread environment. Serialized under
        ``provenance``. Versions live here once rather than per stage.
    create_report : bool, default=True
        Whether to generate a JSON processing report.

    Returns
    -------
    output_paths : dict[str, Path]
        Dictionary mapping output types to their absolute paths:
        - 'data': Path to saved preprocessed data
        - 'bval': Path to copied bval file (if provided)
        - 'bvec': Path to copied bvec file (if provided)
        - 'mask': Path to saved brain mask (if provided)
        - 'report': Path to processing report (if created)

    Examples
    --------
    >>> paths = save_preprocessed(
    ...     data=preprocessed_data,
    ...     affine=affine,
    ...     output_dir="/data/preprocessed",
    ...     filename_stem="sub01_dwi_preproc",
    ...     gradient_files={"bval": "original.bval", "bvec": "original.bvec"},
    ...     brain_mask=mask,
    ...     processing_params={"denoise_method": "nlmeans", "motion_correction": True}
    ... )
    """
    # Validate inputs
    if not isinstance(data, np.ndarray):
        raise TypeError(f"data must be a numpy array, got {type(data)}")
    if affine.shape != (4, 4):
        raise ValueError(f"affine must be 4x4, got shape {affine.shape}")

    # Setup output directory
    output_dir = Path(output_dir)
    output_dir.mkdir(parents=True, exist_ok=True)

    output_paths = {}

    # Save preprocessed data
    data_path = output_dir / f"{filename_stem}.nii.gz"
    nib.save(nib.Nifti1Image(data, affine), data_path)
    output_paths['data'] = data_path
    print(f"  ✓ Saved preprocessed data: {data_path}")

    # Write transformed b-vectors, or copy the originals when untransformed
    if bvecs is not None:
        bvecs = np.asarray(bvecs, dtype=float)
        if bvecs.ndim != 2 or bvecs.shape[1] != 3:
            raise ValueError(f"bvecs must be (N, 3), got shape {bvecs.shape}")
        dest = output_dir / f"{filename_stem}.bvec"
        np.savetxt(dest, bvecs.T, fmt="%.8f")
        output_paths['bvec'] = dest
        print(f"  ✓ Wrote transformed bvec: {dest}")

    # Copy gradient files
    if gradient_files is not None:
        for grad_type in ['bval', 'bvec']:
            if grad_type == 'bvec' and bvecs is not None:
                continue  # already written above
            if grad_type in gradient_files:
                src = Path(gradient_files[grad_type])
                if src.exists():
                    dest = output_dir / f"{filename_stem}.{grad_type}"
                    shutil.copy2(src, dest)
                    output_paths[grad_type] = dest
                    print(f"  ✓ Copied {grad_type}: {dest}")
                else:
                    print(f"  ⚠️ {grad_type} file not found: {src}")

    # Save brain mask
    if brain_mask is not None:
        mask_path = output_dir / f"{filename_stem}_mask.nii.gz"
        nib.save(nib.Nifti1Image(brain_mask.astype(np.uint8), affine), mask_path)
        output_paths['mask'] = mask_path
        print(f"  ✓ Saved brain mask: {mask_path}")

    # Create processing report
    if create_report:
        report = {
            'timestamp': datetime.now().isoformat(),
            'filename_stem': filename_stem,
            'data_shape': list(data.shape),
            'data_dtype': str(data.dtype),
            'voxel_size': np.sqrt(np.sum(affine[:3, :3]**2, axis=0)).tolist(),
        }

        if processing_params is not None:
            report['processing_params'] = processing_params

        if metadata is not None:
            report['metadata'] = metadata

        # Additive: callers that pass neither get exactly the previous report.
        if ledger is not None:
            report['schema_version'] = 1
            report['stages'] = ledger

        if provenance is not None:
            report['provenance'] = provenance

        report_path = output_dir / f"{filename_stem}_report.json"
        with open(report_path, 'w') as f:
            json.dump(report, f, indent=2)
        output_paths['report'] = report_path
        print(f"  ✓ Saved processing report: {report_path}")

    return output_paths

plot_denoising_comparison(data_before, data_after, brain_mask, output_dir, stem, denoise_method, vol_idx=None, affine=None, title_id=None, verbose=True)

Create before/after denoising comparison figure.

Shows three orthogonal views comparing original and denoised data, plus per-voxel absolute-difference residuals highlighting removed noise.

Parameters:

Name Type Description Default
data_before ndarray

4D DWI data before denoising.

required
data_after ndarray

4D DWI data after denoising.

required
brain_mask ndarray

3D binary brain mask.

required
output_dir str or Path

Output directory for saving figure.

required
stem str

Subject/scan identifier for filename.

required
denoise_method str

Denoising method used.

required
vol_idx int

Volume index to visualize. Default picks a DWI volume (middle of 4th dim).

None
verbose bool

Print progress information.

True

Returns:

Name Type Description
fig_path Path

Path to saved figure.

Source code in src/csttool/preprocess/modules/visualizations.py
def plot_denoising_comparison(
    data_before,
    data_after,
    brain_mask,
    output_dir,
    stem,
    denoise_method,
    vol_idx=None,
    affine=None,
    title_id=None,
    verbose=True
):
    """
    Create before/after denoising comparison figure.

    Shows three orthogonal views comparing original and denoised data,
    plus per-voxel absolute-difference residuals highlighting removed noise.

    Parameters
    ----------
    data_before : ndarray
        4D DWI data before denoising.
    data_after : ndarray
        4D DWI data after denoising.
    brain_mask : ndarray
        3D binary brain mask.
    output_dir : str or Path
        Output directory for saving figure.
    stem : str
        Subject/scan identifier for filename.
    denoise_method : str
        Denoising method used. 
    vol_idx : int, optional
        Volume index to visualize. Default picks a DWI volume (middle of 4th dim).
    verbose : bool, optional
        Print progress information.

    Returns
    -------
    fig_path : Path
        Path to saved figure.
    """
    output_dir = Path(output_dir)
    viz_dir = output_dir / "visualizations"
    viz_dir.mkdir(parents=True, exist_ok=True)

    # Default to a DWI volume (middle of 4th dimension)
    if vol_idx is None:
        vol_idx = data_before.shape[3] // 2

    # Get middle slice indices for each orientation
    mid_ax = data_before.shape[2] // 2
    mid_cor = data_before.shape[1] // 2
    mid_sag = data_before.shape[0] // 2

    # Extract 3D volumes
    before = data_before[..., vol_idx]
    after = data_after[..., vol_idx]

    # Per-voxel absolute difference (removed signal). sqrt(x**2) == |x|; there is
    # no mean here, so this is |before - after|, not an RMS.
    abs_diff = np.abs(before.astype(np.float64) - after.astype(np.float64))
    if brain_mask is not None and brain_mask.shape == before.shape:
        abs_diff[~brain_mask] = 0

    # Define orthogonal views
    views = [
        ('Axial', before[:, :, mid_ax], after[:, :, mid_ax], abs_diff[:, :, mid_ax]),
        ('Coronal', before[:, mid_cor, :], after[:, mid_cor, :], abs_diff[:, mid_cor, :]),
        ('Sagittal', before[mid_sag, :, :], after[mid_sag, :, :], abs_diff[mid_sag, :, :]),
    ]

    # Shared |difference| scale across all three views so panels are comparable.
    res_pool = abs_diff[brain_mask] if (brain_mask is not None and brain_mask.shape == before.shape) else abs_diff
    res_vmax = np.percentile(res_pool, 99) if np.any(res_pool) else None

    # Create figure: 3 rows (views) × 3 columns (original, denoised, residuals)
    fig, axes = plt.subplots(3, 3, figsize=(12, 12),
                              subplot_kw={'xticks': [], 'yticks': []},
                              constrained_layout=True)
    fig.suptitle(f"Denoising using {denoise_method} - {title_id or stem} (Volume {vol_idx})", fontsize=14, fontweight='bold')

    # Column titles
    axes[0, 0].set_title('Original', fontsize=12)
    axes[0, 1].set_title('Denoised', fontsize=12)
    axes[0, 2].set_title('|Difference|', fontsize=12)

    res_im = None
    for row, (view_name, orig, den, res) in enumerate(views):
        # Original
        axes[row, 0].imshow(orig.T, cmap='gray', interpolation='none', origin='lower')
        axes[row, 0].set_ylabel(view_name, fontsize=12, fontweight='bold')

        # Denoised
        axes[row, 1].imshow(den.T, cmap='gray', interpolation='none', origin='lower')

        # Residuals (shared scale + perceptually-uniform residual colormap)
        res_im = axes[row, 2].imshow(res.T, cmap=_style.RESIDUAL_CMAP, interpolation='none',
                                     origin='lower', vmin=0, vmax=res_vmax)

        # Radiological orientation + L/R markers for all three panels of this view.
        if affine is not None:
            for c in range(3):
                _geo.finalize_image_view(axes[row, c], affine, view_name.lower())

    # Labelled colorbar for the shared |difference| column.
    if res_im is not None:
        _style.add_scalar_colorbar(fig, res_im, list(axes[:, 2]), 'Removed signal |Δ|')

    fig_path = viz_dir / f"{stem}_denoising_qc.png"
    _style.save_figure(fig, fig_path)
    plt.close(fig)

    if verbose:
        print(f"  ✓ Denoising QC: {fig_path}")

    return fig_path

plot_gibbs_unringing_comparison(data_before, data_after, brain_mask, output_dir, stem, vol_idx=None, affine=None, title_id=None, verbose=True)

Create before/after Gibbs unringing comparison figure.

Shows three orthogonal views comparing data before and after unringing, plus per-voxel absolute-difference residuals highlighting removed ringing artifacts.

Parameters:

Name Type Description Default
data_before ndarray

4D DWI data before Gibbs unringing.

required
data_after ndarray

4D DWI data after Gibbs unringing.

required
brain_mask ndarray

3D binary brain mask.

required
output_dir str or Path

Output directory for saving figure.

required
stem str

Subject/scan identifier for filename.

required
vol_idx int

Volume index to visualize. Default picks a DWI volume (middle of 4th dim).

None
verbose bool

Print progress information.

True

Returns:

Name Type Description
fig_path Path

Path to saved figure.

Source code in src/csttool/preprocess/modules/visualizations.py
def plot_gibbs_unringing_comparison(
    data_before,
    data_after,
    brain_mask,
    output_dir,
    stem,
    vol_idx=None,
    affine=None,
    title_id=None,
    verbose=True
):
    """
    Create before/after Gibbs unringing comparison figure.

    Shows three orthogonal views comparing data before and after
    unringing, plus per-voxel absolute-difference residuals highlighting removed ringing artifacts.

    Parameters
    ----------
    data_before : ndarray
        4D DWI data before Gibbs unringing.
    data_after : ndarray
        4D DWI data after Gibbs unringing.
    brain_mask : ndarray
        3D binary brain mask.
    output_dir : str or Path
        Output directory for saving figure.
    stem : str
        Subject/scan identifier for filename.
    vol_idx : int, optional
        Volume index to visualize. Default picks a DWI volume (middle of 4th dim).
    verbose : bool, optional
        Print progress information.

    Returns
    -------
    fig_path : Path
        Path to saved figure.
    """
    output_dir = Path(output_dir)
    viz_dir = output_dir / "visualizations"
    viz_dir.mkdir(parents=True, exist_ok=True)

    # Default to a DWI volume (middle of 4th dimension)
    if vol_idx is None:
        vol_idx = data_before.shape[3] // 2

    # Get middle slice indices for each orientation
    mid_ax = data_before.shape[2] // 2
    mid_cor = data_before.shape[1] // 2
    mid_sag = data_before.shape[0] // 2

    # Extract 3D volumes
    before = data_before[..., vol_idx]
    after = data_after[..., vol_idx]

    # Per-voxel absolute difference (removed ringing). sqrt(x**2) == |x|; there is
    # no mean here, so this is |before - after|, not an RMS.
    abs_diff = np.abs(before.astype(np.float64) - after.astype(np.float64))
    if brain_mask is not None and brain_mask.shape == before.shape:
        abs_diff[~brain_mask] = 0

    # Define orthogonal views
    views = [
        ('Axial', before[:, :, mid_ax], after[:, :, mid_ax], abs_diff[:, :, mid_ax]),
        ('Coronal', before[:, mid_cor, :], after[:, mid_cor, :], abs_diff[:, mid_cor, :]),
        ('Sagittal', before[mid_sag, :, :], after[mid_sag, :, :], abs_diff[mid_sag, :, :]),
    ]

    # Shared |difference| scale across all three views so panels are comparable.
    res_pool = abs_diff[brain_mask] if (brain_mask is not None and brain_mask.shape == before.shape) else abs_diff
    res_vmax = np.percentile(res_pool, 99) if np.any(res_pool) else None

    # Create figure: 3 rows (views) × 3 columns (before, after, residuals)
    fig, axes = plt.subplots(3, 3, figsize=(12, 12),
                              subplot_kw={'xticks': [], 'yticks': []},
                              constrained_layout=True)
    fig.suptitle(f"Gibbs Unringing - {title_id or stem} (Volume {vol_idx})", fontsize=14, fontweight='bold')

    # Column titles
    axes[0, 0].set_title('Before', fontsize=12)
    axes[0, 1].set_title('After', fontsize=12)
    axes[0, 2].set_title('|Difference|', fontsize=12)

    res_im = None
    for row, (view_name, bef, aft, res) in enumerate(views):
        # Before
        axes[row, 0].imshow(bef.T, cmap='gray', interpolation='none', origin='lower')
        axes[row, 0].set_ylabel(view_name, fontsize=12, fontweight='bold')

        # After
        axes[row, 1].imshow(aft.T, cmap='gray', interpolation='none', origin='lower')

        # Residuals (shared scale + perceptually-uniform residual colormap)
        res_im = axes[row, 2].imshow(res.T, cmap=_style.RESIDUAL_CMAP, interpolation='none',
                                     origin='lower', vmin=0, vmax=res_vmax)

        # Radiological orientation + L/R markers for all three panels of this view.
        if affine is not None:
            for c in range(3):
                _geo.finalize_image_view(axes[row, c], affine, view_name.lower())

    # Labelled colorbar for the shared |difference| column.
    if res_im is not None:
        _style.add_scalar_colorbar(fig, res_im, list(axes[:, 2]), 'Removed signal |Δ|')

    fig_path = viz_dir / f"{stem}_gibbs_unringing_qc.png"
    _style.save_figure(fig, fig_path)
    plt.close(fig)

    if verbose:
        print(f"  ✓ Gibbs unringing QC: {fig_path}")

    return fig_path

plot_brain_mask_overlay(data, brain_mask, gtab, output_dir, stem, affine=None, title_id=None, verbose=True)

Create brain mask overlay visualization.

Shows brain mask overlaid on b0 image in three orthogonal views, plus mask coverage statistics.

Parameters:

Name Type Description Default
data ndarray

4D DWI data (masked or unmasked).

required
brain_mask ndarray

3D binary brain mask.

required
gtab GradientTable

Gradient table to identify b0 volumes.

required
output_dir str or Path

Output directory for saving figure.

required
stem str

Subject/scan identifier for filename.

required
verbose bool

Print progress information.

True

Returns:

Name Type Description
fig_path Path

Path to saved figure.

Source code in src/csttool/preprocess/modules/visualizations.py
def plot_brain_mask_overlay(
    data,
    brain_mask,
    gtab,
    output_dir,
    stem,
    affine=None,
    title_id=None,
    verbose=True
):
    """
    Create brain mask overlay visualization.

    Shows brain mask overlaid on b0 image in three orthogonal views,
    plus mask coverage statistics.

    Parameters
    ----------
    data : ndarray
        4D DWI data (masked or unmasked).
    brain_mask : ndarray
        3D binary brain mask.
    gtab : GradientTable
        Gradient table to identify b0 volumes.
    output_dir : str or Path
        Output directory for saving figure.
    stem : str
        Subject/scan identifier for filename.
    verbose : bool, optional
        Print progress information.

    Returns
    -------
    fig_path : Path
        Path to saved figure.
    """
    output_dir = Path(output_dir)
    viz_dir = output_dir / "visualizations"
    viz_dir.mkdir(parents=True, exist_ok=True)

    # Get b0 volume
    from csttool.defaults import DEFAULT_B0_THRESHOLD
    b0_idx = np.where(gtab.bvals < DEFAULT_B0_THRESHOLD)[0]
    if len(b0_idx) == 0:
        b0_idx = [0]
    b0 = data[..., b0_idx[0]]

    # Get slice indices
    mid_ax = data.shape[2] // 2
    mid_cor = data.shape[1] // 2
    mid_sag = data.shape[0] // 2

    # Compute statistics
    total_voxels = brain_mask.size
    brain_voxels = brain_mask.sum()
    coverage = brain_voxels / total_voxels * 100

    # Create figure
    fig, axes = plt.subplots(2, 3, figsize=(15, 10), constrained_layout=True)
    fig.suptitle(f"Brain Mask QC - {title_id or stem}\n"
                 f"Coverage: {brain_voxels:,} voxels ({coverage:.1f}%)",
                 fontsize=14, fontweight='bold')

    vmax = np.percentile(b0[brain_mask], 99) if brain_mask.any() else np.percentile(b0, 99)

    views = [
        ('Axial', b0[:, :, mid_ax], brain_mask[:, :, mid_ax], f'z={mid_ax}'),
        ('Coronal', b0[:, mid_cor, :], brain_mask[:, mid_cor, :], f'y={mid_cor}'),
        ('Sagittal', b0[mid_sag, :, :], brain_mask[mid_sag, :, :], f'x={mid_sag}'),
    ]

    for col, (view_name, b0_slice, mask_slice, coord) in enumerate(views):
        # Row 0: b0 only
        axes[0, col].imshow(b0_slice.T, cmap='gray', origin='lower', vmin=0, vmax=vmax)
        axes[0, col].set_title(f'{view_name} ({coord})\nb0 image')
        axes[0, col].axis('off')

        # Row 1: b0 with mask overlay
        axes[1, col].imshow(b0_slice.T, cmap='gray', origin='lower', vmin=0, vmax=vmax)

        # Solid semi-transparent fill where the mask is set (a Reds colormap on a
        # constant array normalizes to near-white and is effectively invisible).
        overlay = np.zeros((*mask_slice.T.shape, 4))
        overlay[mask_slice.T > 0] = to_rgba('red', 0.30)
        axes[1, col].imshow(overlay, origin='lower')

        # Add contour
        axes[1, col].contour(mask_slice.T, levels=[0.5], colors='red', linewidths=1)
        axes[1, col].set_title(f'{view_name}\nwith brain mask')
        axes[1, col].axis('off')

        # Radiological orientation + L/R markers for both rows of this view.
        if affine is not None:
            _geo.finalize_image_view(axes[0, col], affine, view_name.lower())
            _geo.finalize_image_view(axes[1, col], affine, view_name.lower())

    fig_path = viz_dir / f"{stem}_brain_mask_qc.png"
    _style.save_figure(fig, fig_path)
    plt.close()

    if verbose:
        print(f"  ✓ Brain mask QC: {fig_path}")

    return fig_path

plot_motion_correction_summary(reg_affines, output_dir, stem, title_id=None, verbose=True)

Create motion correction summary visualization.

Shows translation and rotation parameters across volumes, highlighting any large motion events.

Parameters:

Name Type Description Default
reg_affines list of ndarray

List of 4x4 registration affine matrices (one per volume).

required
output_dir str or Path

Output directory for saving figure.

required
stem str

Subject/scan identifier for filename.

required
verbose bool

Print progress information.

True

Returns:

Name Type Description
fig_path Path

Path to saved figure.

Source code in src/csttool/preprocess/modules/visualizations.py
def plot_motion_correction_summary(
    reg_affines,
    output_dir,
    stem,
    title_id=None,
    verbose=True
):
    """
    Create motion correction summary visualization.

    Shows translation and rotation parameters across volumes,
    highlighting any large motion events.

    Parameters
    ----------
    reg_affines : list of ndarray
        List of 4x4 registration affine matrices (one per volume).
    output_dir : str or Path
        Output directory for saving figure.
    stem : str
        Subject/scan identifier for filename.
    verbose : bool, optional
        Print progress information.

    Returns
    -------
    fig_path : Path
        Path to saved figure.
    """
    output_dir = Path(output_dir)
    viz_dir = output_dir / "visualizations"
    viz_dir.mkdir(parents=True, exist_ok=True)

    # dipy.align.motion_correction returns a (4, 4, n_volumes) *array*, not a
    # list of 4x4 matrices. len() on that gives 4, and iterating it yields
    # (4, n) slices rather than affines — so every parameter plotted here used
    # to be a slice of a single matrix. On a 71-volume series that produced a
    # figure titled "4 volumes" reporting a 284° maximum rotation for a run
    # whose true maximum was 0.47°. Normalise the stack first.
    affines = _as_affine_stack(reg_affines)
    n_vols = affines.shape[-1]

    # Extract translation and rotation parameters
    translations = np.zeros((n_vols, 3))
    rotations = np.zeros((n_vols, 3))

    for i in range(n_vols):
        affine = affines[..., i]
        # Translation is in the last column
        translations[i] = affine[:3, 3]

        # Euler angles from the orthonormal rotation component. Polar
        # decomposition discards the scale/shear the affine stage picks up, so
        # the reported angles are rotations rather than a mix.
        R = rotation_part(affine)
        rotations[i, 0] = np.arctan2(R[2, 1], R[2, 2]) * 180 / np.pi  # Roll (x)
        rotations[i, 1] = np.arctan2(-R[2, 0], np.sqrt(R[2, 1]**2 + R[2, 2]**2)) * 180 / np.pi  # Pitch (y)
        rotations[i, 2] = np.arctan2(R[1, 0], R[0, 0]) * 180 / np.pi  # Yaw (z)

    # Compute relative motion (difference from first volume)
    translations_rel = translations - translations[0]
    rotations_rel = rotations - rotations[0]

    # Create figure
    fig, axes = plt.subplots(2, 2, figsize=(15, 10), constrained_layout=True)
    fig.suptitle(f"Motion Correction QC - {title_id or stem}\n{n_vols} volumes",
                 fontsize=14, fontweight='bold')

    volumes = np.arange(n_vols)

    # Translation (absolute)
    ax = axes[0, 0]
    ax.plot(volumes, translations[:, 0], 'r-', label='X', linewidth=1.5)
    ax.plot(volumes, translations[:, 1], 'g-', label='Y', linewidth=1.5)
    ax.plot(volumes, translations[:, 2], 'b-', label='Z', linewidth=1.5)
    ax.set_xlabel('Volume')
    ax.set_ylabel('Translation (mm)')
    ax.set_title('Absolute Translation')
    ax.legend(loc='upper right')
    ax.grid(True, alpha=0.3)

    # Translation (relative to first)
    ax = axes[0, 1]
    ax.plot(volumes, translations_rel[:, 0], 'r-', label='X', linewidth=1.5)
    ax.plot(volumes, translations_rel[:, 1], 'g-', label='Y', linewidth=1.5)
    ax.plot(volumes, translations_rel[:, 2], 'b-', label='Z', linewidth=1.5)
    ax.axhline(y=0, color='k', linestyle='--', linewidth=0.5)
    ax.set_xlabel('Volume')
    ax.set_ylabel('Translation (mm)')
    ax.set_title('Relative Translation (vs. volume 0)')
    ax.legend(loc='upper right')
    ax.grid(True, alpha=0.3)

    # Rotation (absolute)
    ax = axes[1, 0]
    ax.plot(volumes, rotations[:, 0], 'r-', label='Roll (X)', linewidth=1.5)
    ax.plot(volumes, rotations[:, 1], 'g-', label='Pitch (Y)', linewidth=1.5)
    ax.plot(volumes, rotations[:, 2], 'b-', label='Yaw (Z)', linewidth=1.5)
    ax.set_xlabel('Volume')
    ax.set_ylabel('Rotation (degrees)')
    ax.set_title('Absolute Rotation')
    ax.legend(loc='upper right')
    ax.grid(True, alpha=0.3)

    # Rotation (relative to first)
    ax = axes[1, 1]
    ax.plot(volumes, rotations_rel[:, 0], 'r-', label='Roll (X)', linewidth=1.5)
    ax.plot(volumes, rotations_rel[:, 1], 'g-', label='Pitch (Y)', linewidth=1.5)
    ax.plot(volumes, rotations_rel[:, 2], 'b-', label='Yaw (Z)', linewidth=1.5)
    ax.axhline(y=0, color='k', linestyle='--', linewidth=0.5)
    ax.set_xlabel('Volume')
    ax.set_ylabel('Rotation (degrees)')
    ax.set_title('Relative Rotation (vs. volume 0)')
    ax.legend(loc='upper right')
    ax.grid(True, alpha=0.3)

    # Add summary statistics. The rotation figure is the geodesic angle of each
    # volume's rotation, i.e. the same quantity the preprocessing report records
    # as `max_rotation_deg` — the two must not be able to disagree.
    max_trans = np.max(np.abs(translations_rel))
    max_rot = max_rotation_angle_deg(affines)

    fig.text(0.5, 0.02, 
             f"Max displacement: {max_trans:.2f} mm | Max rotation: {max_rot:.2f}°",
             ha='center', fontsize=11, style='italic')

    fig_path = viz_dir / f"{stem}_motion_qc.png"
    _style.save_figure(fig, fig_path)
    plt.close()

    if verbose:
        print(f"  ✓ Motion correction QC: {fig_path}")

    return fig_path

create_preprocessing_summary(data_original, data_preprocessed, brain_mask, gtab, output_dir, stem, motion_correction_applied=False, affine=None, title_id=None, verbose=True)

Create multi-panel preprocessing summary figure.

Combines key QC visualizations into a single summary figure for quick assessment of preprocessing quality.

Parameters:

Name Type Description Default
data_original ndarray

4D DWI data before preprocessing.

required
data_preprocessed ndarray

4D DWI data after preprocessing.

required
brain_mask ndarray

3D binary brain mask.

required
gtab GradientTable

Gradient table.

required
output_dir str or Path

Output directory for saving figure.

required
stem str

Subject/scan identifier for filename.

required
motion_correction_applied bool

Whether motion correction was applied.

False
verbose bool

Print progress information.

True

Returns:

Name Type Description
fig_path Path

Path to saved figure.

Source code in src/csttool/preprocess/modules/visualizations.py
def create_preprocessing_summary(
    data_original,
    data_preprocessed,
    brain_mask,
    gtab,
    output_dir,
    stem,
    motion_correction_applied=False,
    affine=None,
    title_id=None,
    verbose=True
):
    """
    Create multi-panel preprocessing summary figure.

    Combines key QC visualizations into a single summary figure
    for quick assessment of preprocessing quality.

    Parameters
    ----------
    data_original : ndarray
        4D DWI data before preprocessing.
    data_preprocessed : ndarray
        4D DWI data after preprocessing.
    brain_mask : ndarray
        3D binary brain mask.
    gtab : GradientTable
        Gradient table.
    output_dir : str or Path
        Output directory for saving figure.
    stem : str
        Subject/scan identifier for filename.
    motion_correction_applied : bool, optional
        Whether motion correction was applied.
    verbose : bool, optional
        Print progress information.

    Returns
    -------
    fig_path : Path
        Path to saved figure.
    """
    output_dir = Path(output_dir)
    viz_dir = output_dir / "visualizations"
    viz_dir.mkdir(parents=True, exist_ok=True)

    # Check if shapes are compatible
    orig_shape = data_original.shape[:3]
    proc_shape = data_preprocessed.shape[:3]
    mask_shape = brain_mask.shape

    # A true before/after in one slice grid needs matching shapes. Reslicing or
    # cropping changes the preprocessed grid, so the raw "original" is no longer
    # co-registered with it. Rather than silently substituting preprocessed data
    # while still labelling a panel "Original" (a misleading figure), record the
    # mismatch and annotate the affected panels honestly below.
    shapes_match = (orig_shape == proc_shape and orig_shape == mask_shape)
    if not shapes_match:
        data_original = data_preprocessed

    # Get b0 volume index
    from csttool.defaults import DEFAULT_B0_THRESHOLD
    b0_idx = np.where(gtab.bvals < DEFAULT_B0_THRESHOLD)[0]
    if len(b0_idx) == 0:
        b0_idx = [0]
    vol_idx = b0_idx[0]

    # Get slice indices
    mid_ax = data_original.shape[2] // 2

    # Extract data
    orig_b0 = data_original[:, :, mid_ax, vol_idx]
    proc_b0 = data_preprocessed[:, :, mid_ax, vol_idx]
    mask_slice = brain_mask[:, :, mid_ax]

    # Compute difference
    diff = np.abs(proc_b0.astype(np.float64) - orig_b0.astype(np.float64))
    diff[~mask_slice] = 0

    # Compute statistics
    brain_voxels = brain_mask.sum()
    coverage = brain_voxels / brain_mask.size * 100

    # Intensity statistics
    orig_mean = np.mean(data_original[brain_mask])
    proc_mean = np.mean(data_preprocessed[brain_mask])
    orig_std = np.std(data_original[brain_mask])
    proc_std = np.std(data_preprocessed[brain_mask])

    # Create figure with constrained_layout
    fig = plt.figure(figsize=(18, 10), constrained_layout=True)
    fig.suptitle(f"Preprocessing Summary - {title_id or stem}", fontsize=16, fontweight='bold')

    # Create grid. The stats row is text-only, so give it a much smaller height
    # than the two image rows to remove the empty band above the stats box (NEW-4).
    gs = fig.add_gridspec(3, 4, height_ratios=[1.0, 1.0, 0.35])

    vmax = np.percentile(orig_b0[mask_slice], 99) if mask_slice.any() else np.percentile(orig_b0, 99)
    diff_vmax = np.percentile(diff[mask_slice], 99) if diff[mask_slice].any() else 1

    # Row 0: Original, Preprocessed, Difference, Mask
    orig_title = 'Original b0' if shapes_match else 'Preprocessed b0\n(original grid differs)'
    diff_title = 'Difference (denoising)' if shapes_match else 'Difference N/A\n(shape changed)'

    ax1 = fig.add_subplot(gs[0, 0])
    ax1.imshow(orig_b0.T, cmap='gray', origin='lower', vmin=0, vmax=vmax)
    ax1.set_title(orig_title)
    ax1.axis('off')

    ax2 = fig.add_subplot(gs[0, 1])
    ax2.imshow(proc_b0.T, cmap='gray', origin='lower', vmin=0, vmax=vmax)
    ax2.set_title('Preprocessed b0')
    ax2.axis('off')

    ax3 = fig.add_subplot(gs[0, 2])
    diff_im = ax3.imshow(diff.T, cmap=_style.RESIDUAL_CMAP, origin='lower', vmin=0, vmax=diff_vmax)
    ax3.set_title(diff_title)
    ax3.axis('off')
    if shapes_match:
        # constrained_layout-compatible colorbar (no make_axes_locatable here).
        fig.colorbar(diff_im, ax=ax3, fraction=0.046, pad=0.04).ax.tick_params(labelsize=8)

    ax4 = fig.add_subplot(gs[0, 3])
    ax4.imshow(proc_b0.T, cmap='gray', origin='lower', vmin=0, vmax=vmax)
    ax4.contour(mask_slice.T, levels=[0.5], colors='red', linewidths=1.5)
    ax4.set_title(f'Brain Mask\n({brain_voxels:,} voxels)')
    ax4.axis('off')

    # Row 0 panels are all axial: radiological orientation + L/R markers.
    if affine is not None:
        for _ax in (ax1, ax2, ax3, ax4):
            _geo.finalize_image_view(_ax, affine, 'axial')

    # Row 1: Three orthogonal views with mask overlay
    views_data = [
        ('Sagittal', data_preprocessed[data_preprocessed.shape[0]//2, :, :, vol_idx],
         brain_mask[brain_mask.shape[0]//2, :, :]),
        ('Coronal', data_preprocessed[:, data_preprocessed.shape[1]//2, :, vol_idx],
         brain_mask[:, brain_mask.shape[1]//2, :]),
        ('Axial', data_preprocessed[:, :, data_preprocessed.shape[2]//2, vol_idx],
         brain_mask[:, :, brain_mask.shape[2]//2]),
    ]

    for i, (name, img, msk) in enumerate(views_data):
        ax = fig.add_subplot(gs[1, i])
        ax.imshow(img.T, cmap='gray', origin='lower')
        # Same contour colour as the dedicated Brain Mask panel (red) for consistency.
        ax.contour(msk.T, levels=[0.5], colors='red', linewidths=1)
        ax.set_title(name)
        ax.axis('off')
        if affine is not None:
            _geo.finalize_image_view(ax, affine, name.lower())

    # Row 1, col 3: Histogram comparison
    ax_hist = fig.add_subplot(gs[1, 3])

    orig_vals = data_original[brain_mask].flatten()
    proc_vals = data_preprocessed[brain_mask].flatten()

    # Subsample for efficiency (deterministic local RNG; no global-state mutation)
    if len(orig_vals) > 100000:
        idx = np.sort(viz_rng().choice(len(orig_vals), 100000, replace=False))
        orig_vals = orig_vals[idx]
        proc_vals = proc_vals[idx]

    ax_hist.hist(orig_vals, bins=100, alpha=0.5, label='Original', density=True)
    ax_hist.hist(proc_vals, bins=100, alpha=0.5, label='Preprocessed', density=True)
    ax_hist.set_xlabel('Intensity')
    ax_hist.set_ylabel('Density')
    ax_hist.set_title('Intensity Distribution')
    ax_hist.legend(fontsize=8)

    # Row 2: Statistics panel
    ax_stats = fig.add_subplot(gs[2, :])
    ax_stats.axis('off')

    mc_status = "Applied" if motion_correction_applied else "Not applied"
    bvalues = sorted({int(b) for b in gtab.bvals})  # plain ints (no numpy repr leak)
    grid_note = (
        "" if shapes_match
        else "\nNOTE: original grid differs from preprocessed (reslice/crop);\n"
             "      'Original' and 'Difference' panels are not directly comparable.\n"
    )

    stats_text = (
        f"{'─' * 80}\n"
        f"PREPROCESSING STATISTICS\n"
        f"{'─' * 80}\n\n"
        f"Data Shape:           {data_original.shape}\n"
        f"Voxel Dimensions:     {data_original.shape[:3]}\n"
        f"Number of Volumes:    {data_original.shape[3]}\n"
        f"B-values:             {bvalues}\n\n"
        f"Brain Mask Coverage:  {brain_voxels:,} voxels ({coverage:.1f}%)\n\n"
        f"Intensity (in brain):\n"
        f"  Original:           mean = {orig_mean:.1f}, std = {orig_std:.1f}\n"
        f"  Preprocessed:       mean = {proc_mean:.1f}, std = {proc_std:.1f}\n\n"
        f"Motion Correction:    {mc_status}\n"
        f"{grid_note}"
        f"{'─' * 80}"
    )

    ax_stats.text(0.5, 0.5, stats_text, transform=ax_stats.transAxes,
                  fontsize=10, fontfamily='monospace',
                  verticalalignment='center', horizontalalignment='center',
                  bbox=dict(boxstyle='round', facecolor='wheat', alpha=0.5))

    fig_path = viz_dir / f"{stem}_preprocessing_summary.png"
    _style.save_figure(fig, fig_path)
    plt.close()

    if verbose:
        print(f"  ✓ Preprocessing summary: {fig_path}")

    return fig_path

save_all_preprocessing_visualizations(data_original, data_denoised, data_masked, data_unringed, data_preprocessed, brain_mask, gtab, output_dir, stem, denoise_method, reg_affines=None, motion_correction_applied=False, affine=None, title_id=None, verbose=True)

Generate and save all preprocessing visualizations.

Convenience function that calls all visualization functions and returns paths to all generated figures.

Parameters:

Name Type Description Default
data_original ndarray

4D DWI data before any preprocessing.

required
data_denoised ndarray

4D DWI data after denoising (before masking).

required
data_masked ndarray

4D DWI data after brain masking (cropped).

required
data_unringed ndarray

4D DWI data after Gibbs unringing (cropped).

required
data_preprocessed ndarray

4D DWI data after full preprocessing.

required
brain_mask ndarray

3D binary brain mask.

required
gtab GradientTable

Gradient table.

required
output_dir str or Path

Output directory for saving figures.

required
stem str

Subject/scan identifier for filenames.

required
denoise_method str

Denoising method used.

required
reg_affines list of ndarray

Registration affines from motion correction.

None
motion_correction_applied bool

Whether motion correction was applied.

False
verbose bool

Print progress information.

True

Returns:

Name Type Description
viz_paths dict

Dictionary mapping visualization names to file paths.

Source code in src/csttool/preprocess/modules/visualizations.py
def save_all_preprocessing_visualizations(
    data_original,
    data_denoised,
    data_masked,
    data_unringed,
    data_preprocessed,
    brain_mask,
    gtab,
    output_dir,
    stem,
    denoise_method,
    reg_affines=None,
    motion_correction_applied=False,
    affine=None,
    title_id=None,
    verbose=True
):
    """
    Generate and save all preprocessing visualizations.

    Convenience function that calls all visualization functions
    and returns paths to all generated figures.

    Parameters
    ----------
    data_original : ndarray
        4D DWI data before any preprocessing.
    data_denoised : ndarray
        4D DWI data after denoising (before masking).
    data_masked : ndarray
        4D DWI data after brain masking (cropped).
    data_unringed : ndarray
        4D DWI data after Gibbs unringing (cropped).
    data_preprocessed : ndarray
        4D DWI data after full preprocessing.
    brain_mask : ndarray
        3D binary brain mask.
    gtab : GradientTable
        Gradient table.
    output_dir : str or Path
        Output directory for saving figures.
    stem : str
        Subject/scan identifier for filenames.
    denoise_method : str, optional
        Denoising method used.
    reg_affines : list of ndarray, optional
        Registration affines from motion correction.
    motion_correction_applied : bool, optional
        Whether motion correction was applied.
    verbose : bool, optional
        Print progress information.

    Returns
    -------
    viz_paths : dict
        Dictionary mapping visualization names to file paths.
    """
    _style.apply_house_style()  # shared typography/spines/DPI for this stage
    if verbose:
        print("\nGenerating preprocessing visualizations...")

    viz_paths = {}

    # Denoising comparison
    if data_denoised is not None:
        viz_paths['denoising_qc'] = plot_denoising_comparison(
            data_original, data_denoised, brain_mask,
            output_dir, stem, denoise_method, affine=affine,
            title_id=title_id, verbose=verbose
        )

    # Gibbs unringing comparison (both inputs are cropped/masked)
    if data_unringed is not None and data_masked is not None:
        viz_paths['gibbs_unringing_qc'] = plot_gibbs_unringing_comparison(
            data_masked, data_unringed, brain_mask,
            output_dir, stem, affine=affine, title_id=title_id, verbose=verbose
        )

    # Brain mask overlay
    viz_paths['brain_mask_qc'] = plot_brain_mask_overlay(
        data_preprocessed, brain_mask, gtab,
        output_dir, stem, affine=affine, title_id=title_id, verbose=verbose
    )

    # Motion correction (if applied)
    if motion_correction_applied and reg_affines is not None:
        viz_paths['motion_qc'] = plot_motion_correction_summary(
            reg_affines, output_dir, stem, title_id=title_id, verbose=verbose
        )

    # Summary figure
    viz_paths['summary'] = create_preprocessing_summary(
        data_original, data_preprocessed, brain_mask, gtab,
        output_dir, stem, motion_correction_applied, affine=affine,
        title_id=title_id, verbose=verbose
    )

    if verbose:
        print(f"  ✓ All preprocessing visualizations saved to: {Path(output_dir) / 'visualizations'}")

    return viz_paths