Skip to content

csttool.metrics

CST metric computation and PDF/HTML reporting. The CLI counterpart is metrics.

from csttool.metrics import compute_metrics

compute_metrics(
    cst_left="extract/cst_left.trk",
    cst_right="extract/cst_right.trk",
    fa="tracking/dti_FA.nii.gz",
    out="./metrics",
    generate_pdf=True,
)

csttool.metrics

CST Metrics Module

Modular metrics computation for bilateral CST analysis.

Structure: - modules/unilateral_analysis: Analyze individual hemispheres - modules/bilateral_analysis: Compare left vs right - modules/visualizations: Generate all plots

Functions:

analyze_cst_hemisphere(streamlines, fa_map=None, md_map=None, rd_map=None, ad_map=None, affine=None, hemisphere='unknown')

Complete analysis of a single CST hemisphere.

Parameters:

Name Type Description Default
streamlines Streamlines

Streamlines for one hemisphere (left OR right)

required
fa_map ndarray

3D fractional anisotropy map

None
md_map ndarray

3D mean diffusivity map

None
rd_map ndarray

3D radial diffusivity map

None
ad_map ndarray

3D axial diffusivity map

None
affine ndarray

4x4 affine transformation matrix

None
hemisphere str

'left' or 'right' for identification

'unknown'

Returns:

Name Type Description
metrics dict

Comprehensive metrics dictionary containing: - morphology: streamline count, length stats, volume - fa/md/rd/ad: per-scalar block with a length-unbiased headline (mean/std/median/min/max/n_streamlines, one vote per streamline), a preserved point-pool summary (mean_point_weighted … n_samples), and the along-tract profile with regional means (pontine/plic/precentral). See _compute_scalar_metrics. - hemisphere: identification string

Source code in src/csttool/metrics/modules/unilateral_analysis.py
def analyze_cst_hemisphere(
    streamlines,
    fa_map=None,
    md_map=None,
    rd_map=None,
    ad_map=None,
    affine=None,
    hemisphere='unknown'
):
    """
    Complete analysis of a single CST hemisphere.

    Parameters
    ----------
    streamlines : Streamlines
        Streamlines for one hemisphere (left OR right)
    fa_map : ndarray, optional
        3D fractional anisotropy map
    md_map : ndarray, optional
        3D mean diffusivity map
    rd_map : ndarray, optional
        3D radial diffusivity map
    ad_map : ndarray, optional
        3D axial diffusivity map
    affine : ndarray, optional
        4x4 affine transformation matrix
    hemisphere : str
        'left' or 'right' for identification

    Returns
    -------
    metrics : dict
        Comprehensive metrics dictionary containing:
        - morphology: streamline count, length stats, volume
        - fa/md/rd/ad: per-scalar block with a length-unbiased headline
          (mean/std/median/min/max/n_streamlines, one vote per streamline), a preserved
          point-pool summary (mean_point_weighted … n_samples), and the along-tract
          profile with regional means (pontine/plic/precentral). See
          `_compute_scalar_metrics`.
        - hemisphere: identification string
    """

    print(f"\nAnalyzing {hemisphere.upper()} CST...")

    metrics = {
        'hemisphere': hemisphere,
        'morphology': compute_morphology(streamlines, affine)
    }

    # Microstructural analysis requires affine. The per-scalar block is identical across
    # scalars, so it is built once in `_compute_scalar_metrics` — the single source of
    # truth for the headline / point-pool / profile key set (previously this block was
    # copied verbatim per scalar, so any key change was 4x).
    _scalar_inputs = [
        ('fa', fa_map, False),
        ('md', md_map, True),
        ('rd', rd_map, True),
        ('ad', ad_map, True),
    ]
    for _name, _map, _is_diffusivity in _scalar_inputs:
        if _map is not None and affine is not None:
            metrics[_name] = _compute_scalar_metrics(streamlines, _map, affine)
            if metrics[_name]['n_streamlines'] > 0:
                _fmt = '.3e' if _is_diffusivity else '.3f'
                print(f"  {_name.upper()}: {metrics[_name]['mean']:{_fmt}} "
                      f"± {metrics[_name]['std']:{_fmt}}")

    return metrics

compute_morphology(streamlines, affine)

Compute morphological properties of a streamline bundle.

Parameters:

Name Type Description Default
streamlines Streamlines

Input streamlines

required
affine ndarray

4x4 affine transformation matrix

required

Returns:

Name Type Description
morphology dict

Dictionary containing: - n_streamlines: number of streamlines - mean_length: average streamline length in mm - median_length: median streamline length in mm (additive descriptive stat; the length LI uses mean_length, not this) - std_length: standard deviation of lengths - min_length: minimum streamline length - max_length: maximum streamline length - tract_volume: volume in mm³ - bootstrap_se_length: bootstrap SE of mean_length, or None for an empty bundle. Length is a mean over a resamplable per-streamline population, so it carries an SE; tract_volume deliberately does not — it is a set-union voxel count, and bootstrapping it would estimate the variability of a coverage statistic while reading as an SE of a mean.

Source code in src/csttool/metrics/modules/unilateral_analysis.py
def compute_morphology(streamlines, affine):
    """
    Compute morphological properties of a streamline bundle.

    Parameters
    ----------
    streamlines : Streamlines
        Input streamlines
    affine : ndarray
        4x4 affine transformation matrix

    Returns
    -------
    morphology : dict
        Dictionary containing:
        - n_streamlines: number of streamlines
        - mean_length: average streamline length in mm
        - median_length: median streamline length in mm (additive descriptive stat;
          the length LI uses mean_length, not this)
        - std_length: standard deviation of lengths
        - min_length: minimum streamline length
        - max_length: maximum streamline length
        - tract_volume: volume in mm³
        - bootstrap_se_length: bootstrap SE of mean_length, or None for an empty
          bundle. Length is a mean over a resamplable per-streamline population,
          so it carries an SE; ``tract_volume`` deliberately does not — it is a
          set-union voxel count, and bootstrapping it would estimate the
          variability of a coverage statistic while reading as an SE of a mean.
    """

    if len(streamlines) == 0:
        return {
            'n_streamlines': 0,
            'mean_length': 0.0,
            'median_length': 0.0,
            'std_length': 0.0,
            'min_length': 0.0,
            'max_length': 0.0,
            'tract_volume': 0.0,
            'bootstrap_se_length': None,
        }

    # Compute streamline lengths
    lengths = np.array([length(s) for s in streamlines])

    # Compute tract volume by counting unique voxels
    # Get all points from all streamlines
    all_points = np.vstack(streamlines)

    # Transform to voxel coordinates using inverse affine
    inv_affine = np.linalg.inv(affine)
    all_points_hom = np.c_[all_points, np.ones(len(all_points))]
    voxel_coords = (inv_affine @ all_points_hom.T).T[:, :3]

    # Round to integer voxel indices
    voxel_indices = np.round(voxel_coords).astype(int)

    # Count unique voxels
    unique_voxels = np.unique(voxel_indices, axis=0)
    n_voxels = len(unique_voxels)

    # Compute voxel volume
    voxel_size = np.sqrt(np.sum(affine[:3, :3]**2, axis=0))
    voxel_volume = np.prod(voxel_size)

    # Total tract volume
    tract_volume = n_voxels * voxel_volume

    # median_length is an additive descriptive statistic paired with mean_length;
    # the length laterality index still uses mean_length (see bilateral_analysis),
    # so adding the median changes no existing metric value. See
    # docs/explanation/design-decisions.md.
    from . import qc_stats

    morphology = {
        'n_streamlines': len(streamlines),
        'mean_length': float(np.mean(lengths)),
        'median_length': float(np.median(lengths)),
        'std_length': float(np.std(lengths)),
        'min_length': float(np.min(lengths)),
        'max_length': float(np.max(lengths)),
        'tract_volume': float(tract_volume),
        'bootstrap_se_length': qc_stats.bootstrap_mean_se(lengths),
    }

    print(f"  Morphology: {morphology['n_streamlines']} streamlines, "
          f"{morphology['mean_length']:.1f} mm mean length, "
          f"{morphology['tract_volume']:.0f} mm³ volume")

    return morphology

sample_scalar_along_tract(streamlines, scalar_map, affine)

Sample scalar values at every point along all streamlines (point pool).

Every in-bounds point of every streamline is pooled into one flat array, so this is invariant to streamline orientation and to point order; it deliberately does not reorient (unlike compute_tract_profile). Summary statistics derived from it are therefore unaffected by AU9.

The pool is point-weighted: a streamline with twice as many points casts twice as many votes. When streamline length is correlated with the scalar (it is, weakly, on in-vivo CST data) this biases the mean. sample_scalar_per_streamline is the length-unbiased counterpart (one vote per streamline); the report's headline mean and the global laterality indices use that one, not this. This function is retained for QC, for the reproducibility stability tests, and as the basis of the preserved mean_point_weighted summary.

Parameters:

Name Type Description Default
streamlines Streamlines

Input streamlines in world coordinates (mm)

required
scalar_map ndarray

3D scalar map (e.g., FA or MD)

required
affine ndarray

4x4 affine transformation matrix

required

Returns:

Name Type Description
scalar_values ndarray

Array of all sampled scalar values (flattened across all streamlines)

Source code in src/csttool/metrics/modules/unilateral_analysis.py
def sample_scalar_along_tract(streamlines, scalar_map, affine):
    """Sample scalar values at every point along all streamlines (point pool).

    Every in-bounds point of every streamline is pooled into one flat array, so this is
    invariant to streamline orientation and to point order; it deliberately does not
    reorient (unlike `compute_tract_profile`). Summary statistics derived from it are
    therefore unaffected by AU9.

    The pool is **point-weighted**: a streamline with twice as many points casts twice
    as many votes. When streamline length is correlated with the scalar (it is, weakly,
    on in-vivo CST data) this biases the mean. `sample_scalar_per_streamline` is the
    length-unbiased counterpart (one vote per streamline); the report's headline mean and
    the global laterality indices use that one, not this. This function is retained for
    QC, for the reproducibility stability tests, and as the basis of the preserved
    ``mean_point_weighted`` summary.

    Parameters
    ----------
    streamlines : Streamlines
        Input streamlines in world coordinates (mm)
    scalar_map : ndarray
        3D scalar map (e.g., FA or MD)
    affine : ndarray
        4x4 affine transformation matrix

    Returns
    -------
    scalar_values : ndarray
        Array of all sampled scalar values (flattened across all streamlines)
    """
    if len(streamlines) == 0:
        return np.array([])

    all_values = []
    for streamline in streamlines:
        all_values.extend(_sample_streamline_values(streamline, scalar_map, affine))
    return np.array(all_values)

sample_scalar_per_streamline(streamlines, scalar_map, affine)

Mean scalar per streamline (one value per streamline, length-unbiased).

Each streamline that has at least one in-bounds point contributes exactly one value — the mean of its sampled points — regardless of how many points it has. Summary statistics derived from the returned array are therefore not weighted by streamline length, unlike sample_scalar_along_tract. This is the population the report's headline mean/std/median/min/max and the global laterality indices describe (audit finding AU10).

A streamline's point-mean is order-invariant, so this is unaffected by AU9 as well.

Parameters:

Name Type Description Default
streamlines Streamlines

Input streamlines in world coordinates (mm)

required
scalar_map ndarray

3D scalar map (e.g., FA or MD)

required
affine ndarray

4x4 affine transformation matrix

required

Returns:

Name Type Description
streamline_means ndarray

Mean scalar value for each streamline with at least one in-bounds point.

Source code in src/csttool/metrics/modules/unilateral_analysis.py
def sample_scalar_per_streamline(streamlines, scalar_map, affine):
    """Mean scalar per streamline (one value per streamline, length-unbiased).

    Each streamline that has at least one in-bounds point contributes exactly one value —
    the mean of its sampled points — regardless of how many points it has. Summary
    statistics derived from the returned array are therefore **not** weighted by
    streamline length, unlike `sample_scalar_along_tract`. This is the population the
    report's headline ``mean``/``std``/``median``/``min``/``max`` and the global
    laterality indices describe (audit finding AU10).

    A streamline's point-mean is order-invariant, so this is unaffected by AU9 as well.

    Parameters
    ----------
    streamlines : Streamlines
        Input streamlines in world coordinates (mm)
    scalar_map : ndarray
        3D scalar map (e.g., FA or MD)
    affine : ndarray
        4x4 affine transformation matrix

    Returns
    -------
    streamline_means : ndarray
        Mean scalar value for each streamline with at least one in-bounds point.
    """
    if len(streamlines) == 0:
        return np.array([])

    means = []
    for streamline in streamlines:
        vals = _sample_streamline_values(streamline, scalar_map, affine)
        if len(vals) > 0:
            means.append(float(np.mean(vals)))
    return np.array(means)

compute_tract_profile(streamlines, scalar_map, affine, n_points=20)

Compute normalized tract profile (average scalar along tract).

This function samples scalar values along each streamline, normalizes each streamline to the same number of points, and averages across all streamlines to create a representative profile.

Streamlines are reoriented inferior-to-superior first, so that point index i means the same anatomical position in every streamline (see orient_streamlines_inferior_to_superior). Without that step a mixed-orientation bundle averages one streamline's pontine end against another's precentral end. The input is not modified.

Parameters:

Name Type Description Default
streamlines Streamlines

Input streamlines in RASMM world coordinates (mm)

required
scalar_map ndarray

3D scalar map (FA or MD)

required
affine ndarray

4x4 affine transformation matrix

required
n_points int

Number of points in output profile (default: 20)

20

Returns:

Name Type Description
profile ndarray

Average scalar values at n_points positions along the tract, ordered from the inferior (pontine) end to the superior (precentral) end.

Source code in src/csttool/metrics/modules/unilateral_analysis.py
def compute_tract_profile(streamlines, scalar_map, affine, n_points=20):
    """
    Compute normalized tract profile (average scalar along tract).

    This function samples scalar values along each streamline, normalizes
    each streamline to the same number of points, and averages across all
    streamlines to create a representative profile.

    Streamlines are reoriented inferior-to-superior first, so that point index i means the
    same anatomical position in every streamline (see
    `orient_streamlines_inferior_to_superior`). Without that step a mixed-orientation
    bundle averages one streamline's pontine end against another's precentral end. The
    input is not modified.

    Parameters
    ----------
    streamlines : Streamlines
        Input streamlines in RASMM world coordinates (mm)
    scalar_map : ndarray
        3D scalar map (FA or MD)
    affine : ndarray
        4x4 affine transformation matrix
    n_points : int
        Number of points in output profile (default: 20)

    Returns
    -------
    profile : ndarray
        Average scalar values at n_points positions along the tract, ordered from the
        inferior (pontine) end to the superior (precentral) end.
    """

    if len(streamlines) == 0:
        return np.zeros(n_points)

    streamlines = orient_streamlines_inferior_to_superior(streamlines)

    all_profiles = []

    for streamline in streamlines:
        if len(streamline) < 2:
            continue

        # Sample scalar values at each point (shared per-point lookup)
        streamline_scalars = _sample_streamline_values(streamline, scalar_map, affine)

        if len(streamline_scalars) < 5:  # Need minimum points
            continue

        # Normalize to n_points
        if len(streamline_scalars) >= n_points:
            # Downsample
            indices = np.linspace(0, len(streamline_scalars)-1, n_points).astype(int)
            normalized_profile = np.array(streamline_scalars)[indices]
        else:
            # Upsample with interpolation
            x_original = np.linspace(0, 1, len(streamline_scalars))
            x_target = np.linspace(0, 1, n_points)
            normalized_profile = np.interp(x_target, x_original, streamline_scalars)

        all_profiles.append(normalized_profile)

    if len(all_profiles) == 0:
        return np.zeros(n_points)

    # Average across all streamlines
    final_profile = np.mean(all_profiles, axis=0)

    return final_profile.tolist()  # Convert to list for JSON serialization

orient_streamlines_inferior_to_superior(streamlines)

Flip streamlines so each runs from its inferior end to its superior end.

Tractography stores each streamline as [backward_from_seed][forward_from_seed], so a bundle mixes orientations. Averaging by point index across a mixed bundle aligns one streamline's pontine end with another's precentral end, biasing the tract profile and every regional metric derived from it (audit finding AU9).

Consumers assume index 0 is the inferior (pontine) end: compute_localized_metrics bins the profile by index, and the profile plots label position 0 "Pontine Level". So the ordering is anchored to anatomy rather than made merely self-consistent between streamlines, which would leave the whole bundle liable to being flipped as a unit.

Orientation is decided by comparing the mean Z of the first and last quartiles rather than the two endpoints alone. On healthy CST data the two rules agree on every streamline, but terminal points are the noisiest part of a streamline (that is where the stopping criterion fired) and the cortical end hooks laterally into the precentral gyrus, so the quartile mean is the more robust choice on the tortuous bundles this tool targets. It costs one extra mean per streamline and degrades to the endpoint rule for short streamlines.

Parameters:

Name Type Description Default
streamlines sequence of ndarray

Streamlines in RASMM world coordinates (as returned by load_tractogram(path, 'same')), where +Z is superior by the NIfTI standard. Because only the two ends of the same streamline are compared, the result is translation-invariant and therefore unaffected by the subject not being recentered (audit finding AU11).

required

Returns:

Name Type Description
oriented list of ndarray

A new list; the input streamlines are never modified in place.

Warns:

Type Description
UserWarning

If the bundle does not run predominantly superior-inferior, in which case "index 0 is the inferior end" is not anatomically meaningful.

Source code in src/csttool/metrics/modules/unilateral_analysis.py
def orient_streamlines_inferior_to_superior(streamlines):
    """
    Flip streamlines so each runs from its inferior end to its superior end.

    Tractography stores each streamline as ``[backward_from_seed][forward_from_seed]``, so a
    bundle mixes orientations. Averaging by point index across a mixed bundle aligns one
    streamline's pontine end with another's precentral end, biasing the tract profile and
    every regional metric derived from it (audit finding AU9).

    Consumers assume index 0 is the inferior (pontine) end: `compute_localized_metrics`
    bins the profile by index, and the profile plots label position 0 "Pontine Level". So
    the ordering is anchored to anatomy rather than made merely self-consistent between
    streamlines, which would leave the whole bundle liable to being flipped as a unit.

    Orientation is decided by comparing the mean Z of the first and last quartiles rather
    than the two endpoints alone. On healthy CST data the two rules agree on every
    streamline, but terminal points are the noisiest part of a streamline (that is where
    the stopping criterion fired) and the cortical end hooks laterally into the precentral
    gyrus, so the quartile mean is the more robust choice on the tortuous bundles this
    tool targets. It costs one extra mean per streamline and degrades to the endpoint rule
    for short streamlines.

    Parameters
    ----------
    streamlines : sequence of ndarray
        Streamlines in RASMM world coordinates (as returned by
        ``load_tractogram(path, 'same')``), where +Z is superior by the NIfTI standard.
        Because only the two ends of the same streamline are compared, the result is
        translation-invariant and therefore unaffected by the subject not being
        recentered (audit finding AU11).

    Returns
    -------
    oriented : list of ndarray
        A new list; the input streamlines are never modified in place.

    Warns
    -----
    UserWarning
        If the bundle does not run predominantly superior-inferior, in which case
        "index 0 is the inferior end" is not anatomically meaningful.
    """

    if len(streamlines) == 0:
        return []

    spans = np.array([
        np.abs(np.asarray(s)[-1] - np.asarray(s)[0])
        for s in streamlines if len(s) >= 2
    ])
    if len(spans) > 0:
        dominant = int(np.argmax(spans.mean(axis=0)))
        if dominant != 2:
            warnings.warn(
                f"Bundle runs predominantly along {'XYZ'[dominant]}, not Z: it is not a "
                "superior-inferior tract, so orienting it inferior-to-superior (and the "
                "pontine/precentral labels that assume it) is not meaningful.",
                UserWarning,
                stacklevel=2,
            )

    oriented = []
    for streamline in streamlines:
        points = np.asarray(streamline)
        if len(points) < 2:
            oriented.append(points)
            continue

        # Z decides. Ties fall through to Y then X, then keep the stored order, so the
        # result is deterministic and depends only on the streamline itself.
        for axis in (2, 1, 0):
            delta = _end_to_end_delta(points, axis)
            if delta != 0.0:
                oriented.append(points[::-1] if delta < 0 else points)
                break
        else:
            oriented.append(points)

    return oriented

print_hemisphere_summary(metrics)

Print human-readable summary of hemisphere metrics.

Parameters:

Name Type Description Default
metrics dict

Metrics dictionary from analyze_cst_hemisphere()

required
Source code in src/csttool/metrics/modules/unilateral_analysis.py
def print_hemisphere_summary(metrics):
    """
    Print human-readable summary of hemisphere metrics.

    Parameters
    ----------
    metrics : dict
        Metrics dictionary from analyze_cst_hemisphere()
    """

    hemisphere = metrics['hemisphere'].upper()
    print(f"\n{'='*60}")
    print(f"{hemisphere} CST ANALYSIS SUMMARY")
    print(f"{'='*60}")

    morph = metrics['morphology']
    print(f"Streamline Count: {morph['n_streamlines']}")
    print(f"Mean Length: {morph['mean_length']:.1f} ± {morph['std_length']:.1f} mm")
    print(f"Length Range: [{morph['min_length']:.1f}, {morph['max_length']:.1f}] mm")
    print(f"Tract Volume: {morph['tract_volume']:.0f} mm³")

    if 'fa' in metrics:
        fa = metrics['fa']
        print(f"\nFractional Anisotropy:")
        print(f"  Mean: {fa['mean']:.3f} ± {fa['std']:.3f} "
              f"(per-streamline, n={fa['n_streamlines']})")
        print(f"  Range: [{fa['min']:.3f}, {fa['max']:.3f}]")
        print(f"  Point-weighted: {fa['mean_point_weighted']:.3f} ± "
              f"{fa['std_point_weighted']:.3f} (n={fa['n_samples']} samples)")

    if 'md' in metrics:
        md = metrics['md']
        print(f"\nMean Diffusivity:")
        print(f"  Mean: {md['mean']:.3e} ± {md['std']:.3e} "
              f"(per-streamline, n={md['n_streamlines']})")
        print(f"  Range: [{md['min']:.3e}, {md['max']:.3e}]")
        print(f"  Point-weighted: {md['mean_point_weighted']:.3e} ± "
              f"{md['std_point_weighted']:.3e} (n={md['n_samples']} samples)")

    print(f"{'='*60}\n")

compare_bilateral_cst(left_metrics, right_metrics)

Compare left and right CST metrics and compute asymmetry measures.

Parameters:

Name Type Description Default
left_metrics dict

Metrics from analyze_cst_hemisphere() for left CST

required
right_metrics dict

Metrics from analyze_cst_hemisphere() for right CST

required

Returns:

Name Type Description
comparison dict

Comprehensive bilateral comparison containing: - left: complete left hemisphere metrics - right: complete right hemisphere metrics - asymmetry: laterality indices and differences

Source code in src/csttool/metrics/modules/bilateral_analysis.py
def compare_bilateral_cst(left_metrics, right_metrics):
    """
    Compare left and right CST metrics and compute asymmetry measures.

    Parameters
    ----------
    left_metrics : dict
        Metrics from analyze_cst_hemisphere() for left CST
    right_metrics : dict
        Metrics from analyze_cst_hemisphere() for right CST

    Returns
    -------
    comparison : dict
        Comprehensive bilateral comparison containing:
        - left: complete left hemisphere metrics
        - right: complete right hemisphere metrics
        - asymmetry: laterality indices and differences
    """

    print("\nComputing bilateral comparison...")

    comparison = {
        'left': left_metrics,
        'right': right_metrics,
        'asymmetry': compute_laterality_indices(left_metrics, right_metrics)
    }

    print_bilateral_summary(comparison)

    return comparison

compute_laterality_indices(left_metrics, right_metrics)

Compute laterality indices for all available metrics.

Laterality Index (LI) = (L - R) / (L + R)

LI interpretation: - LI > 0: Left hemisphere larger/higher - LI < 0: Right hemisphere larger/higher
- LI ≈ 0: Symmetric - |LI| > 0.1: Potentially significant asymmetry

Parameters:

Name Type Description Default
left_metrics dict

Left hemisphere metrics

required
right_metrics dict

Right hemisphere metrics

required

Returns:

Name Type Description
asymmetry dict

Laterality indices and absolute differences for: - volume - streamline count - mean length - mean FA (if available) - mean MD (if available) - mean RD (if available) - mean AD (if available)

Every index whose two hemisphere values carry a bootstrap SE also gets a
``laterality_index_se``, propagated by :func:`_attach_li_se`. Streamline
count and tract volume deliberately do not: a count *is* its own sample
size, and a volume is a set-union voxel count rather than a mean over a
resamplable population (plan §7.1).
Source code in src/csttool/metrics/modules/bilateral_analysis.py
def compute_laterality_indices(left_metrics, right_metrics):
    """
    Compute laterality indices for all available metrics.

    Laterality Index (LI) = (L - R) / (L + R)

    LI interpretation:
    - LI > 0: Left hemisphere larger/higher
    - LI < 0: Right hemisphere larger/higher  
    - LI ≈ 0: Symmetric
    - |LI| > 0.1: Potentially significant asymmetry

    Parameters
    ----------
    left_metrics : dict
        Left hemisphere metrics
    right_metrics : dict
        Right hemisphere metrics

    Returns
    -------
    asymmetry : dict
        Laterality indices and absolute differences for:
        - volume
        - streamline count
        - mean length
        - mean FA (if available)
        - mean MD (if available)
        - mean RD (if available)
        - mean AD (if available)

    Every index whose two hemisphere values carry a bootstrap SE also gets a
    ``laterality_index_se``, propagated by :func:`_attach_li_se`. Streamline
    count and tract volume deliberately do not: a count *is* its own sample
    size, and a volume is a set-union voxel count rather than a mean over a
    resamplable population (plan §7.1).
    """

    asymmetry = {}

    # Morphological asymmetry
    left_morph = left_metrics['morphology']
    right_morph = right_metrics['morphology']

    asymmetry['volume'] = compute_li(
        left_morph['tract_volume'],
        right_morph['tract_volume']
    )

    asymmetry['streamline_count'] = compute_li(
        left_morph['n_streamlines'],
        right_morph['n_streamlines']
    )

    asymmetry['mean_length'] = compute_li(
        left_morph['mean_length'],
        right_morph['mean_length']
    )
    _attach_li_se(
        asymmetry['mean_length'],
        left_morph['mean_length'], right_morph['mean_length'],
        left_morph.get('bootstrap_se_length'), right_morph.get('bootstrap_se_length'),
    )

    # Microstructural asymmetry (global).
    # The headline mean is per-streamline (length-unbiased, AU10), so the global LI is
    # computed on the same population the report tabulates - not the point-weighted
    # mean that longer streamlines dominate. The regional LIs below use the
    # profile-derived values, which are per-streamline-normalised by construction.
    for scalar in ('fa', 'md', 'rd', 'ad'):
        if scalar in left_metrics and scalar in right_metrics:
            asymmetry[scalar] = compute_li(
                left_metrics[scalar]['mean'],
                right_metrics[scalar]['mean']
            )
            _attach_li_se(
                asymmetry[scalar],
                left_metrics[scalar]['mean'], right_metrics[scalar]['mean'],
                left_metrics[scalar].get('bootstrap_se'),
                right_metrics[scalar].get('bootstrap_se'),
            )

    # Localized microstructural asymmetry (per region)
    regions = ['pontine', 'plic', 'precentral']
    scalars = ['fa', 'md', 'rd', 'ad']

    for scalar in scalars:
        if scalar in left_metrics and scalar in right_metrics:
            for region in regions:
                if region in left_metrics[scalar] and region in right_metrics[scalar]:
                    key = f'{scalar}_{region}'
                    asymmetry[key] = compute_li(
                        left_metrics[scalar][region],
                        right_metrics[scalar][region]
                    )
                    _attach_li_se(
                        asymmetry[key],
                        left_metrics[scalar][region], right_metrics[scalar][region],
                        left_metrics[scalar].get(f'{region}_se'),
                        right_metrics[scalar].get(f'{region}_se'),
                    )

    return asymmetry

compute_li(left_value, right_value)

Compute laterality index and absolute difference.

Parameters:

Name Type Description Default
left_value float

Metric value from left hemisphere

required
right_value float

Metric value from right hemisphere

required

Returns:

Name Type Description
li_info dict

Dictionary containing: - laterality_index: (L-R)/(L+R) - absolute_difference: |L-R| - percent_difference: 100 * |L-R| / mean(L,R) - interpretation: text description

Source code in src/csttool/metrics/modules/bilateral_analysis.py
def compute_li(left_value, right_value):
    """
    Compute laterality index and absolute difference.

    Parameters
    ----------
    left_value : float
        Metric value from left hemisphere
    right_value : float
        Metric value from right hemisphere

    Returns
    -------
    li_info : dict
        Dictionary containing:
        - laterality_index: (L-R)/(L+R)
        - absolute_difference: |L-R|
        - percent_difference: 100 * |L-R| / mean(L,R)
        - interpretation: text description
    """

    total = left_value + right_value

    if total == 0:
        return {
            'laterality_index': 0.0,
            'absolute_difference': 0.0,
            'percent_difference': 0.0,
            'interpretation': 'no data'
        }

    li = (left_value - right_value) / total
    abs_diff = abs(left_value - right_value)
    mean_value = (left_value + right_value) / 2
    pct_diff = 100 * abs_diff / mean_value if mean_value > 0 else 0.0

    # Interpret laterality
    from csttool.defaults import DEFAULT_LI_SYMMETRIC, DEFAULT_LI_MILD, DEFAULT_LI_MODERATE
    if abs(li) < DEFAULT_LI_SYMMETRIC:
        interpretation = 'symmetric'
    elif abs(li) < DEFAULT_LI_MILD:
        interpretation = 'mild asymmetry'
    elif abs(li) < DEFAULT_LI_MODERATE:
        interpretation = 'moderate asymmetry'
    else:
        interpretation = 'strong asymmetry'

    if li > 0:
        interpretation += ' (left > right)'
    elif li < 0:
        interpretation += ' (right > left)'

    return {
        'laterality_index': float(li),
        'absolute_difference': float(abs_diff),
        'percent_difference': float(pct_diff),
        'interpretation': interpretation,
        'left_value': float(left_value),
        'right_value': float(right_value)
    }

print_bilateral_summary(comparison)

Print human-readable bilateral comparison summary.

Parameters:

Name Type Description Default
comparison dict

Output from compare_bilateral_cst()

required
Source code in src/csttool/metrics/modules/bilateral_analysis.py
def print_bilateral_summary(comparison):
    """
    Print human-readable bilateral comparison summary.

    Parameters
    ----------
    comparison : dict
        Output from compare_bilateral_cst()
    """

    print("\n" + "=" * 60)
    print("BILATERAL CST COMPARISON")
    print("=" * 60)

    left = comparison['left']
    right = comparison['right']
    asym = comparison['asymmetry']

    # Morphology comparison
    print("\nMORPHOLOGY:")
    print(f"  Streamline Count:")
    print(f"    Left:  {left['morphology']['n_streamlines']}")
    print(f"    Right: {right['morphology']['n_streamlines']}")
    print(f"    LI:    {asym['streamline_count']['laterality_index']:+.3f} "
          f"({asym['streamline_count']['interpretation']})")

    print(f"\n  Tract Volume:")
    print(f"    Left:  {left['morphology']['tract_volume']:.0f} mm³")
    print(f"    Right: {right['morphology']['tract_volume']:.0f} mm³")
    print(f"    LI:    {asym['volume']['laterality_index']:+.3f} "
          f"({asym['volume']['interpretation']})")
    print(f"    Diff:  {asym['volume']['absolute_difference']:.0f} mm³ "
          f"({asym['volume']['percent_difference']:.1f}%)")

    print(f"\n  Mean Length:")
    print(f"    Left:  {left['morphology']['mean_length']:.1f} mm")
    print(f"    Right: {right['morphology']['mean_length']:.1f} mm")
    print(f"    LI:    {asym['mean_length']['laterality_index']:+.3f} "
          f"({asym['mean_length']['interpretation']})")

    # Microstructural comparison
    if 'fa' in asym:
        print(f"\nFRACTIONAL ANISOTROPY:")
        print(f"    Left:  {left['fa']['mean']:.3f} ± {left['fa']['std']:.3f}")
        print(f"    Right: {right['fa']['mean']:.3f} ± {right['fa']['std']:.3f}")
        print(f"    LI:    {asym['fa']['laterality_index']:+.3f} "
              f"({asym['fa']['interpretation']})")
        print(f"    Diff:  {asym['fa']['absolute_difference']:.3f} "
              f"({asym['fa']['percent_difference']:.1f}%)")

    if 'md' in asym:
        print(f"\nMEAN DIFFUSIVITY:")
        print(f"    Left:  {left['md']['mean']:.3e} ± {left['md']['std']:.3e}")
        print(f"    Right: {right['md']['mean']:.3e} ± {right['md']['std']:.3e}")
        print(f"    LI:    {asym['md']['laterality_index']:+.3f} "
              f"({asym['md']['interpretation']})")
        print(f"    Diff:  {asym['md']['absolute_difference']:.3e} "
              f"({asym['md']['percent_difference']:.1f}%)")

    print("=" * 60)

plot_tract_profiles(left_metrics, right_metrics, output_dir, subject_id, scalar='fa', anatomical_labels=True)

Plot along-tract profiles for bilateral comparison.

Creates a figure showing FA or MD profiles along normalized tract length for both left and right CST.

Parameters:

Name Type Description Default
left_metrics dict

Left hemisphere metrics with 'fa' or 'md' profile

required
right_metrics dict

Right hemisphere metrics with 'fa' or 'md' profile

required
output_dir str or Path

Output directory for saving figure

required
subject_id str

Subject identifier for filename

required
scalar str

'fa' or 'md' - which scalar to plot

'fa'
anatomical_labels bool

If True, add anatomical labels to x-axis (Pontine Level, PLIC, Precentral Gyrus)

True

Returns:

Name Type Description
fig_path Path

Path to saved figure

Source code in src/csttool/metrics/modules/visualizations.py
def plot_tract_profiles(
    left_metrics,
    right_metrics,
    output_dir,
    subject_id,
    scalar='fa',
    anatomical_labels=True
):
    """
    Plot along-tract profiles for bilateral comparison.

    Creates a figure showing FA or MD profiles along normalized tract length
    for both left and right CST.

    Parameters
    ----------
    left_metrics : dict
        Left hemisphere metrics with 'fa' or 'md' profile
    right_metrics : dict
        Right hemisphere metrics with 'fa' or 'md' profile
    output_dir : str or Path
        Output directory for saving figure
    subject_id : str
        Subject identifier for filename
    scalar : str
        'fa' or 'md' - which scalar to plot
    anatomical_labels : bool
        If True, add anatomical labels to x-axis (Pontine Level, PLIC, Precentral Gyrus)

    Returns
    -------
    fig_path : Path
        Path to saved figure
    """

    output_dir = Path(output_dir)
    output_dir.mkdir(parents=True, exist_ok=True)

    # Get profiles
    if scalar not in left_metrics or scalar not in right_metrics:
        print(f"Warning: {scalar.upper()} not available in metrics")
        return None

    # MD is stored in mm²/s (~8e-4); the axis is labelled ×10⁻³ mm²/s, so scale
    # the profile and mean lines by 1000 to match (same convention as
    # plot_stacked_profiles). FA is dimensionless and unscaled.
    scale = 1000.0 if scalar == 'md' else 1.0

    left_profile = np.array(left_metrics[scalar]['profile']) * scale
    right_profile = np.array(right_metrics[scalar]['profile']) * scale

    n_points = len(left_profile)
    x = np.linspace(0, 100, n_points)  # Normalized position (0-100%)

    # Create figure
    fig, ax = plt.subplots(figsize=(10, 6))

    # Plot profiles
    ax.plot(x, left_profile, color=_style.LEFT, linewidth=2, label='Left CST', marker='o', markersize=4)
    ax.plot(x, right_profile, color=_style.RIGHT, linewidth=2, label='Right CST', marker='s', markersize=4)

    # Add mean lines
    left_mean = left_metrics[scalar]['mean'] * scale
    right_mean = right_metrics[scalar]['mean'] * scale
    ax.axhline(left_mean, color=_style.LEFT, linestyle='--', alpha=0.5, label=f'Left mean: {left_mean:.3f}')
    ax.axhline(right_mean, color=_style.RIGHT, linestyle='--', alpha=0.5, label=f'Right mean: {right_mean:.3f}')

    # Labels and formatting
    scalar_label = 'Fractional Anisotropy' if scalar == 'fa' else 'Mean Diffusivity (×10⁻³ mm²/s)'

    # Set x-axis with anatomical labels
    if anatomical_labels:
        _shade_tract_regions(ax)
        _label_tract_regions(ax, y=-0.12)
        ax.set_xlabel('Normalized Tract Position', fontsize=12)
    else:
        ax.set_xlabel('Normalized Tract Position (%)', fontsize=12)

    ax.set_ylabel(scalar_label, fontsize=12)
    ax.set_title(f'{scalar_label.split(" (")[0]} Profile - {subject_id}', fontsize=14, fontweight='bold')
    ax.legend(loc='best', fontsize=10)
    ax.grid(True, alpha=0.3)

    plt.tight_layout()
    plt.subplots_adjust(bottom=0.15)  # Extra space for anatomical labels

    # Save figure
    fig_path = output_dir / f"{subject_id}_tract_profile_{scalar}.png"
    _style.save_figure(fig, fig_path)
    plt.close()

    print(f"✓ Tract profile saved: {fig_path}")
    return fig_path

plot_bilateral_comparison(comparison, output_dir, subject_id)

Create bar charts comparing left vs right CST metrics.

Parameters:

Name Type Description Default
comparison dict

Output from compare_bilateral_cst()

required
output_dir str or Path

Output directory for saving figure

required
subject_id str

Subject identifier

required

Returns:

Name Type Description
fig_path Path

Path to saved figure

Source code in src/csttool/metrics/modules/visualizations.py
def plot_bilateral_comparison(
    comparison,
    output_dir,
    subject_id
):
    """
    Create bar charts comparing left vs right CST metrics.

    Parameters
    ----------
    comparison : dict
        Output from compare_bilateral_cst()
    output_dir : str or Path
        Output directory for saving figure
    subject_id : str
        Subject identifier

    Returns
    -------
    fig_path : Path
        Path to saved figure
    """

    output_dir = Path(output_dir)
    output_dir.mkdir(parents=True, exist_ok=True)

    left = comparison['left']
    right = comparison['right']
    asym = comparison['asymmetry']

    # Prepare data for plotting
    metrics_to_plot = []

    # Morphology
    metrics_to_plot.append({
        'name': 'Streamline\nCount',
        'left': left['morphology']['n_streamlines'],
        'right': right['morphology']['n_streamlines'],
        'unit': '',
        'li': asym['streamline_count']['laterality_index']
    })

    metrics_to_plot.append({
        'name': 'Tract Volume\n(mm³)',
        'left': left['morphology']['tract_volume'],
        'right': right['morphology']['tract_volume'],
        'unit': 'mm³',
        'li': asym['volume']['laterality_index']
    })

    metrics_to_plot.append({
        'name': 'Mean Length\n(mm)',
        'left': left['morphology']['mean_length'],
        'right': right['morphology']['mean_length'],
        'unit': 'mm',
        'li': asym['mean_length']['laterality_index']
    })

    # Microstructure
    if 'fa' in left:
        metrics_to_plot.append({
            'name': 'Mean FA',
            'left': left['fa']['mean'],
            'right': right['fa']['mean'],
            'unit': '',
            'li': asym['fa']['laterality_index']
        })

    if 'md' in left:
        metrics_to_plot.append({
            'name': 'Mean MD\n(×10⁻³)',
            'left': left['md']['mean'] * 1000,  # Convert to 10^-3
            'right': right['md']['mean'] * 1000,
            'unit': '×10⁻³',
            'li': asym['md']['laterality_index']
        })

    # Create figure with subplots
    n_metrics = len(metrics_to_plot)
    fig, axes = plt.subplots(1, n_metrics, figsize=(4*n_metrics, 6))

    if n_metrics == 1:
        axes = [axes]

    # Plot each metric
    for ax, metric in zip(axes, metrics_to_plot):
        x_pos = [0, 1]
        values = [metric['left'], metric['right']]
        colors = [_style.LEFT, _style.RIGHT]  # Blue for left, red for right

        bars = ax.bar(x_pos, values, color=colors, alpha=0.7, edgecolor='black', linewidth=1.5)

        # Add value labels on bars
        for bar, val in zip(bars, values):
            height = bar.get_height()
            if 'FA' in metric['name']:
                label_text = f'{val:.3f}'
            elif 'MD' in metric['name']:
                label_text = f'{val:.2f}'
            else:
                label_text = f'{val:.0f}'

            ax.text(bar.get_x() + bar.get_width()/2., height,
                   label_text,
                   ha='center', va='bottom', fontsize=10, fontweight='bold')

        # Add laterality index
        li_text = f'LI = {metric["li"]:+.3f}'
        ax.text(0.5, ax.get_ylim()[1]*0.9, li_text,
               ha='center', va='top', fontsize=10,
               bbox=dict(boxstyle='round', facecolor='wheat', alpha=0.5))

        ax.set_xticks(x_pos)
        ax.set_xticklabels(['Left', 'Right'], fontsize=11)
        ax.set_ylabel(metric['unit'], fontsize=10)
        ax.set_title(metric['name'], fontsize=12, fontweight='bold')
        ax.grid(True, axis='y', alpha=0.3)

    plt.suptitle(f'Bilateral CST Comparison - {subject_id}', fontsize=14, fontweight='bold', y=1.02)
    plt.tight_layout()

    # Save figure
    fig_path = output_dir / f"{subject_id}_bilateral_comparison.png"
    _style.save_figure(fig, fig_path)
    plt.close()

    print(f"✓ Bilateral comparison saved: {fig_path}")
    return fig_path

create_summary_figure(comparison, streamlines_left, streamlines_right, fa_map, affine, output_dir, subject_id)

Create multi-panel summary figure with all key visualizations.

Parameters:

Name Type Description Default
comparison dict

Bilateral comparison metrics

required
streamlines_left Streamlines

Left CST streamlines

required
streamlines_right Streamlines

Right CST streamlines

required
fa_map ndarray

3D FA map

required
affine ndarray

4x4 affine transformation matrix

required
output_dir str or Path

Output directory

required
subject_id str

Subject identifier

required

Returns:

Name Type Description
fig_path Path

Path to saved summary figure

Source code in src/csttool/metrics/modules/visualizations.py
def create_summary_figure(
    comparison,
    streamlines_left,
    streamlines_right,
    fa_map,
    affine,
    output_dir,
    subject_id
):
    """
    Create multi-panel summary figure with all key visualizations.

    Parameters
    ----------
    comparison : dict
        Bilateral comparison metrics
    streamlines_left : Streamlines
        Left CST streamlines
    streamlines_right : Streamlines
        Right CST streamlines
    fa_map : ndarray
        3D FA map
    affine : ndarray
        4x4 affine transformation matrix
    output_dir : str or Path
        Output directory
    subject_id : str
        Subject identifier

    Returns
    -------
    fig_path : Path
        Path to saved summary figure
    """

    output_dir = Path(output_dir)
    output_dir.mkdir(parents=True, exist_ok=True)

    fig = plt.figure(figsize=(16, 10))

    # Create grid layout
    gs = fig.add_gridspec(3, 3, hspace=0.3, wspace=0.3)

    left = comparison['left']
    right = comparison['right']
    asym = comparison['asymmetry']

    # Panel 1: FA Tract Profile
    ax1 = fig.add_subplot(gs[0, :2])
    if 'fa' in left:
        left_profile = np.array(left['fa']['profile'])
        right_profile = np.array(right['fa']['profile'])
        x = np.linspace(0, 100, len(left_profile))

        ax1.plot(x, left_profile, color=_style.LEFT, linewidth=2, label='Left', marker='o', markersize=3)
        ax1.plot(x, right_profile, color=_style.RIGHT, linewidth=2, label='Right', marker='s', markersize=3)
        ax1.set_xlabel('Normalized Position (%)')
        ax1.set_ylabel('Fractional Anisotropy')
        ax1.set_title('FA Tract Profile', fontweight='bold')
        ax1.legend()
        ax1.grid(True, alpha=0.3)

    # Panel 2: Key Metrics Table
    ax2 = fig.add_subplot(gs[0, 2])
    ax2.axis('off')

    table_data = [
        ['Metric', 'Left', 'Right', 'LI'],
        ['Streamlines', f"{left['morphology']['n_streamlines']}", 
         f"{right['morphology']['n_streamlines']}", 
         f"{asym['streamline_count']['laterality_index']:+.2f}"],
        ['Volume (mm³)', f"{left['morphology']['tract_volume']:.0f}", 
         f"{right['morphology']['tract_volume']:.0f}", 
         f"{asym['volume']['laterality_index']:+.2f}"]
    ]

    if 'fa' in left:
        table_data.append(['Mean FA', f"{left['fa']['mean']:.3f}", 
                          f"{right['fa']['mean']:.3f}", 
                          f"{asym['fa']['laterality_index']:+.2f}"])

    table = ax2.table(cellText=table_data, cellLoc='center', loc='center',
                     colWidths=[0.3, 0.2, 0.2, 0.2])
    table.auto_set_font_size(False)
    table.set_fontsize(9)
    table.scale(1, 2)

    # Style header row
    for i in range(4):
        table[(0, i)].set_facecolor('#4CAF50')
        table[(0, i)].set_text_props(weight='bold', color='white')

    ax2.set_title('Summary Metrics', fontweight='bold', pad=20)

    # Panel 3: Streamline Count Comparison
    ax3 = fig.add_subplot(gs[1, 0])
    ax3.bar(['Left', 'Right'], 
           [left['morphology']['n_streamlines'], right['morphology']['n_streamlines']],
           color=[_style.LEFT, _style.RIGHT], alpha=0.7, edgecolor='black')
    ax3.set_ylabel('Count')
    ax3.set_title('Streamline Count', fontweight='bold')
    ax3.grid(True, axis='y', alpha=0.3)

    # Panel 4: Volume Comparison
    ax4 = fig.add_subplot(gs[1, 1])
    ax4.bar(['Left', 'Right'],
           [left['morphology']['tract_volume'], right['morphology']['tract_volume']],
           color=[_style.LEFT, _style.RIGHT], alpha=0.7, edgecolor='black')
    ax4.set_ylabel('Volume (mm³)')
    ax4.set_title('Tract Volume', fontweight='bold')
    ax4.grid(True, axis='y', alpha=0.3)

    # Panel 5: FA Comparison
    ax5 = fig.add_subplot(gs[1, 2])
    if 'fa' in left:
        ax5.bar(['Left', 'Right'],
               [left['fa']['mean'], right['fa']['mean']],
               color=[_style.LEFT, _style.RIGHT], alpha=0.7, edgecolor='black')
        ax5.set_ylabel('Mean FA')
        ax5.set_title('Fractional Anisotropy', fontweight='bold')
        ax5.grid(True, axis='y', alpha=0.3)

    # Panel 6: Laterality Indices
    ax6 = fig.add_subplot(gs[2, :])

    metrics_names = ['Volume', 'Streamlines', 'Length']
    li_values = [
        asym['volume']['laterality_index'],
        asym['streamline_count']['laterality_index'],
        asym['mean_length']['laterality_index']
    ]

    if 'fa' in asym:
        metrics_names.append('FA')
        li_values.append(asym['fa']['laterality_index'])

    if 'md' in asym:
        metrics_names.append('MD')
        li_values.append(asym['md']['laterality_index'])

    colors = [_style.LEFT if li > 0 else _style.RIGHT for li in li_values]
    ax6.barh(metrics_names, li_values, color=colors, alpha=0.7, edgecolor='black')
    ax6.axvline(0, color='black', linewidth=1)
    ax6.axvline(-0.1, color='gray', linestyle='--', alpha=0.5)
    ax6.axvline(0.1, color='gray', linestyle='--', alpha=0.5)
    ax6.set_xlabel('Laterality Index (LI)')
    ax6.set_title('Asymmetry Analysis', fontweight='bold')
    ax6.grid(True, axis='x', alpha=0.3)
    # Positive LI bars extend right (Left > Right); negative extend left
    # (Right > Left). Label each side where its bars actually point.
    ax6.text(0.98, 0.95, 'Left > Right', transform=ax6.transAxes, fontsize=9,
             color=_style.LEFT, ha='right', va='top')
    ax6.text(0.02, 0.95, 'Right > Left', transform=ax6.transAxes, fontsize=9,
             color=_style.RIGHT, ha='left', va='top')

    # Overall title
    plt.suptitle(f'CST Analysis Summary - {subject_id}', fontsize=16, fontweight='bold', y=0.98)

    # Save figure
    fig_path = output_dir / f"{subject_id}_summary.png"
    _style.save_figure(fig, fig_path)
    plt.close()

    print(f"✓ Summary figure saved: {fig_path}")
    return fig_path

plot_asymmetry_radar(asymmetry, output_dir, subject_id)

Create radar plot showing asymmetry across multiple metrics.

Parameters:

Name Type Description Default
asymmetry dict

Asymmetry metrics from bilateral comparison

required
output_dir str or Path

Output directory

required
subject_id str

Subject identifier

required

Returns:

Name Type Description
fig_path Path

Path to saved figure

Source code in src/csttool/metrics/modules/visualizations.py
def plot_asymmetry_radar(asymmetry, output_dir, subject_id):
    """
    Create radar plot showing asymmetry across multiple metrics.

    Parameters
    ----------
    asymmetry : dict
        Asymmetry metrics from bilateral comparison
    output_dir : str or Path
        Output directory
    subject_id : str
        Subject identifier

    Returns
    -------
    fig_path : Path
        Path to saved figure
    """

    output_dir = Path(output_dir)
    output_dir.mkdir(parents=True, exist_ok=True)

    # Prepare data
    metrics = []
    values = []

    if 'volume' in asymmetry:
        metrics.append('Volume')
        values.append(abs(asymmetry['volume']['laterality_index']))

    if 'streamline_count' in asymmetry:
        metrics.append('Streamline\nCount')
        values.append(abs(asymmetry['streamline_count']['laterality_index']))

    if 'fa' in asymmetry:
        metrics.append('FA')
        values.append(abs(asymmetry['fa']['laterality_index']))

    if 'md' in asymmetry:
        metrics.append('MD')
        values.append(abs(asymmetry['md']['laterality_index']))

    if len(metrics) < 3:
        print("Not enough metrics for radar plot")
        return None

    # Create radar plot
    angles = np.linspace(0, 2 * np.pi, len(metrics), endpoint=False).tolist()
    values += values[:1]  # Close the plot
    angles += angles[:1]

    fig, ax = plt.subplots(figsize=(8, 8), subplot_kw=dict(projection='polar'))
    ax.plot(angles, values, 'o-', linewidth=2, color=_style.LEFT)
    ax.fill(angles, values, alpha=0.25, color=_style.LEFT)

    # Add threshold circle
    threshold = [0.1] * (len(metrics) + 1)
    ax.plot(angles, threshold, '--', linewidth=1, color='red', alpha=0.5, label='Asymmetry threshold (0.1)')

    ax.set_xticks(angles[:-1])
    ax.set_xticklabels(metrics, fontsize=11)
    ax.set_ylim(0, max(0.3, max(values)))
    ax.set_title(f'Asymmetry Profile - {subject_id}', fontsize=14, fontweight='bold', pad=20)
    ax.legend(loc='upper right', bbox_to_anchor=(1.3, 1.1))
    ax.grid(True)

    # Save
    fig_path = output_dir / f"{subject_id}_asymmetry_radar.png"
    _style.save_figure(fig, fig_path)
    plt.close()

    print(f"✓ Asymmetry radar plot saved: {fig_path}")
    return fig_path

plot_stacked_profiles(left_metrics, right_metrics, output_dir, subject_id)

Create stacked FA, MD, RD, and AD profile plots for PDF report.

Creates a vertically stacked figure with 4 subplots (if data available): - FA profile - MD profile - RD profile - AD profile

All have shared x-axis (anatomical labels only on bottom).

Parameters:

Name Type Description Default
left_metrics dict

Left hemisphere metrics

required
right_metrics dict

Right hemisphere metrics

required
output_dir str or Path

Output directory

required
subject_id str

Subject identifier

required

Returns:

Name Type Description
fig_path Path

Path to saved figure

Source code in src/csttool/metrics/modules/visualizations.py
def plot_stacked_profiles(
    left_metrics,
    right_metrics,
    output_dir,
    subject_id
):
    """
    Create stacked FA, MD, RD, and AD profile plots for PDF report.

    Creates a vertically stacked figure with 4 subplots (if data available):
    - FA profile
    - MD profile
    - RD profile
    - AD profile

    All have shared x-axis (anatomical labels only on bottom).

    Parameters
    ----------
    left_metrics : dict
        Left hemisphere metrics
    right_metrics : dict
        Right hemisphere metrics
    output_dir : str or Path
        Output directory
    subject_id : str
        Subject identifier

    Returns
    -------
    fig_path : Path
        Path to saved figure
    """

    output_dir = Path(output_dir)
    output_dir.mkdir(parents=True, exist_ok=True)

    # Define metrics to plot in order
    metrics_config = [
        {'key': 'fa', 'title': 'Fractional Anisotropy', 'ylabel': 'FA', 'ylim': (0, 0.8), 'scale': 1},
        {'key': 'md', 'title': 'Mean Diffusivity', 'ylabel': 'MD (×10⁻³)', 'ylim': (0.5, 1.2), 'scale': 1000},
        {'key': 'rd', 'title': 'Radial Diffusivity', 'ylabel': 'RD (×10⁻³)', 'ylim': (0.3, 1.0), 'scale': 1000},
        {'key': 'ad', 'title': 'Axial Diffusivity', 'ylabel': 'AD (×10⁻³)', 'ylim': (0.8, 1.8), 'scale': 1000}
    ]

    # Filter available metrics
    available_metrics = []
    for m in metrics_config:
        if m['key'] in left_metrics and m['key'] in right_metrics:
            available_metrics.append(m)

    if not available_metrics:
        print("Warning: No profiles available for stacking")
        return None

    n_plots = len(available_metrics)
    # Fixed height per plot
    fig, axes = plt.subplots(n_plots, 1, figsize=(6, 2.2 * n_plots), sharex=True)

    if n_plots == 1:
        axes = [axes]

    for i, (ax, m) in enumerate(zip(axes, available_metrics)):
        key = m['key']
        scale = m['scale']

        left_profile = np.array(left_metrics[key]['profile']) * scale
        right_profile = np.array(right_metrics[key]['profile']) * scale
        n_points = len(left_profile)
        x = np.linspace(0, 100, n_points)

        ax.plot(x, left_profile, color=_style.LEFT, linewidth=2, label='Left CST', marker='o', markersize=3)
        ax.plot(x, right_profile, color=_style.RIGHT, linewidth=2, label='Right CST', marker='s', markersize=3)

        ax.set_ylabel(m['ylabel'], fontsize=10)
        # Auto stats for ylim might be better, but keeping fixed range as starting point logic
        # If 'ylim' is provided, use it, else auto
        if 'ylim' in m:
             # Basic check to see if data fits in default range, if not, auto-scale
             all_data = np.concatenate([left_profile, right_profile])
             if np.min(all_data) < m['ylim'][0] or np.max(all_data) > m['ylim'][1]:
                 # Auto scale with margin
                 margin = (np.max(all_data) - np.min(all_data)) * 0.1
                 ax.set_ylim(max(0, np.min(all_data) - margin), np.max(all_data) + margin)
             else:
                 ax.set_ylim(m['ylim'])

        ax.text(0.5, 0.9, m['title'], transform=ax.transAxes, fontsize=10, fontweight='bold', ha='center')

        # Bands go behind every panel; only the bottom one carries the labels.
        _shade_tract_regions(ax)

        ax.grid(True, alpha=0.3)

        # Only add legend to first plot
        if i == 0:
            ax.legend(loc='upper right', fontsize=9, framealpha=0.9)

    # Shared X-axis: labels go on the bottom plot only (shading is applied to every panel above)
    _label_tract_regions(axes[-1], y=-0.3, wrap=True)

    plt.tight_layout()
    # Increase bottom margin to prevent x-axis overlap
    plt.subplots_adjust(hspace=0.2, bottom=0.15)  # Minimize vertical space between plots

    fig_path = output_dir / f"{subject_id}_stacked_profiles.png"
    _style.save_figure(fig, fig_path)
    plt.close()

    print(f"✓ Stacked profiles saved: {fig_path}")
    return fig_path

plot_profile_matrix(left_metrics, right_metrics, output_dir, subject_id, *, size_mm=None, type_scale=1.0, show_band_note=True, filename=None)

2x2 along-tract profile matrix (FA / MD / RD / AD) for the PDF report.

The scientific centerpiece of the report. Generated at its exact final print size (:data:PROFILE_MATRIX_SIZE_MM, or size_mm when a caller typesets it on a different measure) and placed in the template at that same width, so 1 Matplotlib point = 1 printed point and the page budget is exact;

show_band_note draws the clause naming the IQR band. The report needs it on the figure - an HTML page has no caption to put it in. A document that does have one should say it there instead and pass False: the note is right-aligned on the axis-label line, so at a larger type_scale it grows into "Distance along tract (%)" and the two collide.

type_scale multiplies every point size. The report's scale is tuned against its own page, where the region labels and the band note are deliberately the smallest things on the figure; a document set in 12 pt with ~11 pt captions needs them larger, or they read as a different document. Because point sizes are absolute, shrinking the canvas does not shrink the type - so a caller on a narrower measure needs this rather than a smaller size_mm. Defaults to 1.0, which reproduces the report exactly. DPI only affects raster sharpness. the exact figure bbox is mandatory here — a "tight" bounding box would crop the canvas by an unpredictable amount and silently change the printed height.

Layout
  • One legend for the whole figure (Left CST / Right CST / the shaded bin), owned by Matplotlib so it can be placed against the subplot geometry. The HTML template deliberately carries no profile legend of its own.
  • One shared anatomical-region strip spanning both columns underneath the grid, carrying the region names centred over their TRACT_REGIONS intervals plus the shared position axis label. Per-panel landmark labels are not drawn: they used to collide with the x tick labels and were set in large italics that competed with the subplot titles.
  • Missing scalars degrade to an explicit N/A placeholder panel.
Dispersion

Each hemisphere's per-node interquartile range is filled behind its line, so a reader can tell a consensus from an average over dissent — two profiles whose means separate while their IQRs overlap everywhere do not support the difference the bare lines imply. The centre line stays the mean: the twelve regional values and their laterality indices are derived from this exact array, so switching it to the median would change every published regional metric. Where mean and IQR diverge visibly, that divergence is the finding.

A block without profile_p25 (legacy metrics JSON) or with profile_n == 0 (empty hemisphere) simply gets no band; the other hemisphere still gets one, and the figure is otherwise unchanged.

Source code in src/csttool/metrics/modules/visualizations.py
def plot_profile_matrix(
    left_metrics,
    right_metrics,
    output_dir,
    subject_id,
    *,
    size_mm=None,
    type_scale=1.0,
    show_band_note=True,
    filename=None,
):
    """2x2 along-tract profile matrix (FA / MD / RD / AD) for the PDF report.

    The scientific centerpiece of the report. Generated at its exact final print
    size (:data:`PROFILE_MATRIX_SIZE_MM`, or ``size_mm`` when a caller typesets
    it on a different measure) and placed in the template at that same
    width, so 1 Matplotlib point = 1 printed point and the page budget is exact;

    ``show_band_note`` draws the clause naming the IQR band. The report needs it
    on the figure - an HTML page has no caption to put it in. A document that
    does have one should say it there instead and pass ``False``: the note is
    right-aligned on the axis-label line, so at a larger ``type_scale`` it grows
    into "Distance along tract (%)" and the two collide.

    ``type_scale`` multiplies every point size. The report's scale is tuned
    against its own page, where the region labels and the band note are
    deliberately the smallest things on the figure; a document set in 12 pt with
    ~11 pt captions needs them larger, or they read as a different document.
    Because point sizes are absolute, shrinking the canvas does *not* shrink the
    type - so a caller on a narrower measure needs this rather than a smaller
    ``size_mm``. Defaults to 1.0, which reproduces the report exactly.
    DPI only affects raster sharpness. the exact figure bbox is mandatory
    here — a "tight" bounding box would crop the canvas by an unpredictable
    amount and silently change the printed height.

    Layout
    ------
    - One legend for the whole figure (Left CST / Right CST / the shaded bin),
      owned by Matplotlib so it can be placed against the subplot geometry. The
      HTML template deliberately carries no profile legend of its own.
    - One shared anatomical-region strip spanning both columns underneath the
      grid, carrying the region names centred over their ``TRACT_REGIONS``
      intervals plus the shared position axis label. Per-panel landmark labels
      are not drawn: they used to collide with the x tick labels and were set in
      large italics that competed with the subplot titles.
    - Missing scalars degrade to an explicit ``N/A`` placeholder panel.

    Dispersion
    ----------
    Each hemisphere's per-node interquartile range is filled behind its line, so
    a reader can tell a consensus from an average over dissent — two profiles
    whose means separate while their IQRs overlap everywhere do not support the
    difference the bare lines imply. The centre line stays the **mean**: the
    twelve regional values and their laterality indices are derived from this
    exact array, so switching it to the median would change every published
    regional metric. Where mean and IQR diverge visibly, that divergence is the
    finding.

    A block without ``profile_p25`` (legacy metrics JSON) or with
    ``profile_n == 0`` (empty hemisphere) simply gets no band; the other
    hemisphere still gets one, and the figure is otherwise unchanged.
    """
    from matplotlib.patches import Patch

    output_dir = Path(output_dir)
    output_dir.mkdir(parents=True, exist_ok=True)

    available = [
        m for m in _PROFILE_MATRIX_CONFIG
        if m['key'] in left_metrics and m['key'] in right_metrics
    ]
    if not available:
        print("Warning: no profiles available for the profile matrix")
        return None

    # ``size_mm`` lets a caller typeset the same matrix on a different measure -
    # a document whose text width is not the report's content width. It is a
    # physical dimension, passed in, not a second constant in this module: the
    # report owns its page, and nothing else's page belongs here. Everything
    # else about the figure is identical, so the two remain the same figure.
    size = PROFILE_MATRIX_SIZE_MM if size_mm is None else size_mm
    fig = _layout.figure_mm(size[0], size[1])
    # Margins are held constant in **millimetres**, not in figure fractions.
    # A fraction that leaves room for a tick label at 194 mm leaves less at
    # 160 mm, because the label's width is a point size and does not shrink with
    # the canvas - which is how the right-hand "100" tick came to overhang the
    # canvas edge and be clipped by the exact-bbox save. These constants
    # reproduce the reviewed 194 mm geometry exactly.
    _LEFT_MM, _RIGHT_MM, _BOTTOM_MM = 10.67, 2.91, 5.17
    left_frac = _LEFT_MM / size[0]
    right_frac = 1.0 - (_RIGHT_MM * type_scale) / size[0]
    bottom_frac = _BOTTOM_MM / size[1]
    # Two panel rows + a short shared region strip spanning both columns.
    gs = fig.add_gridspec(
        3, 2, height_ratios=[1.0, 1.0, 0.13],
        hspace=0.30, wspace=0.16,
        left=left_frac, right=right_frac, top=0.90, bottom=bottom_frac,
    )
    axes = [
        fig.add_subplot(gs[0, 0]), fig.add_subplot(gs[0, 1]),
        fig.add_subplot(gs[1, 0]), fig.add_subplot(gs[1, 1]),
    ]

    # The single profile legend for the report (see docstring).
    band_rgba = _blend_on_white(_style.REGION_BAND, _style.REGION_BAND_ALPHA)
    legend_handles = _style.hemisphere_legend_handles(
        left_label='Left CST', right_label='Right CST'
    ) + [Patch(facecolor=band_rgba, edgecolor='#b9c2cd', linewidth=0.5,
               label=f"{_REGION_DISPLAY_NAMES['plic']} bin")]
    fig.legend(
        handles=legend_handles, loc='upper center', ncol=3,
        fontsize=_RPT_LEGEND_PT * type_scale, frameon=False,
        bbox_to_anchor=(0.5, 1.005), handlelength=1.8, columnspacing=1.6,
        handletextpad=0.6, borderpad=0.0,
    )

    any_band = False
    for i, m in enumerate(available):
        ax = axes[i]
        key = m['key']
        scale = m['scale']
        left_profile = np.array(left_metrics[key]['profile']) * scale
        right_profile = np.array(right_metrics[key]['profile']) * scale
        n_points = len(left_profile)
        x = np.linspace(0, 100, n_points)

        # Bands first, and behind: the lines are the data and must stay legible
        # wherever the two hemispheres' bands overlap.
        alpha = m.get('band_alpha', _BAND_ALPHA)
        band_extents = [
            _draw_iqr_band(ax, x, left_metrics[key], _style.LEFT, scale, alpha),
            _draw_iqr_band(ax, x, right_metrics[key], _style.RIGHT, scale, alpha),
        ]
        any_band = any_band or any(e is not None for e in band_extents)

        ax.plot(x, left_profile, color=_style.LEFT, linewidth=1.4,
                label='Left CST', zorder=_Z_PROFILE_LINE)
        ax.plot(x, right_profile, color=_style.RIGHT, linewidth=1.4,
                label='Right CST', zorder=_Z_PROFILE_LINE)

        ax.set_ylabel(m['ylabel'], fontsize=_RPT_LABEL_PT * type_scale,
                      labelpad=2)

        # y-limits: existing fixed ranges with the existing auto-fallback, now
        # measured over the band extents as well as the lines. A band that
        # clipped at the axis edge would show a narrower spread than the bundle
        # has, which is the one thing this figure must not do.
        all_data = np.concatenate(
            [left_profile, right_profile]
            + [edge for extent in band_extents if extent for edge in extent]
        )
        if np.min(all_data) < m['ylim'][0] or np.max(all_data) > m['ylim'][1]:
            margin = (np.max(all_data) - np.min(all_data)) * 0.1
            ax.set_ylim(max(0, np.min(all_data) - margin), np.max(all_data) + margin)
        else:
            ax.set_ylim(m['ylim'])

        ax.set_title(m['title'], fontsize=_RPT_TITLE_PT * type_scale, pad=2.5)
        ax.tick_params(axis='both', labelsize=_RPT_TICK_PT * type_scale, pad=1.5,
                       length=2, width=0.6)
        ax.set_xlim(0, 100)
        # Bands behind every panel; the shared strip below names them once.
        _shade_tract_regions(ax, tick_suffix='')
        ax.grid(True, alpha=0.3, linewidth=0.5)
        if i < 2:  # top row: the position ticks are read off the bottom row
            plt.setp(ax.get_xticklabels(), visible=False)

    # Fill any unused panels (fewer than 4 scalars) with an explicit N/A marker.
    for j in range(len(available), 4):
        axes[j].axis('off')
        axes[j].text(0.5, 0.5, 'N/A', transform=axes[j].transAxes,
                     ha='center', va='center', fontsize=9, color='#888888')

    _draw_region_strip(fig.add_subplot(gs[2, :]),
                       band_note=any_band and show_band_note,
                       type_scale=type_scale)

    fig_path = output_dir / (filename or f"{subject_id}_profile_matrix.png")
    # Save the exact figure canvas: the house style's savefig.bbox="tight" would
    # crop-and-pad by an unpredictable amount and silently change the printed
    # height, breaking the page budget. ``save_figure_exact`` pins it.
    _style.save_figure_exact(fig, fig_path)
    plt.close(fig)
    _write_profile_matrix_sidecar(
        fig_path.with_suffix('.json'), subject_id, left_metrics, right_metrics,
        available, any_band,
    )
    print(f"✓ Profile matrix saved: {fig_path}")
    return fig_path

plot_report_qc_strip(fa_path, v1_path, density_path, roi_dseg_path, cst_left_path, cst_right_path, output_dir, subject_id, *, slab_mm=_geo.DEFAULT_SLAB_MM, max_streamlines=500, seed=None)

1x4 report QC strip: DEC-FA, CST density, extraction ROIs, CST over FA.

Replaces the 1x3 triptych, which showed the same information (streamlines over FA) from three angles. These four panels answer four different questions on one shared coronal slice:

  1. does the local diffusion field support the expected CST orientation?
  2. is the reconstructed bundle spatially coherent?
  3. were the intended anatomical constraints applied?
  4. is the final tract anatomically plausible?
One figure, one owner

The strip is a single PNG placed by CSS at :data:QC_STRIP_WIDTH_MM, so this function creates the Figure and the four Axes and draws into them with the csttool.viz.render primitives. It does not call the standalone qc_figures.plot_*_panel functions: each of those owns a Figure and saves it, which cannot be composed onto one canvas. The cost is four render calls per panel; the alternative — refactoring five reviewed standalone figures to accept an axes — is a larger change that would touch tested figures for no benefit here.

That ownership extends to every panel-level annotation: titles, the DEC direction key, the density colourbar, the ROI key and the hemisphere counts are all drawn here, and the HTML template contributes only the section heading. Only the Figure knows where the panels actually landed, so only the Figure can align a key to a panel column; and a key drawn from style.LEFT / style.BRAINSTEM / style.DENSITY_CMAP cannot drift from the marks it describes, which a CSS copy can. This is the same rule plot_profile_matrix already follows.

Layout

Four columns, each carrying — top to bottom — a 9 pt bold title, its image, and its own key. One shared caption spans the strip beneath them, carrying only what is true of all four panels: the plane, the rule that chose it, the display slab and the orientation convention. Panel-specific facts live in panel-specific keys, so no reader has to cross the figure to decode a mark.

Geometry is computed by :func:qc_strip_geometry from the displayed slice's aspect, which is what keeps the furniture bands meaningful — see that function for the defect this replaces.

One slice

The slice is chosen once, by :func:csttool.viz.geometry.select_qc_slice, and every panel gets it. The standalone panels each select their own, and two of them are called with density=None and so fall through to the level-4 anatomical fallback while a third gets level 1 — meaning the "shared slice" has never actually held outside a prototype driver. It holds here.

density_left / density_right are deliberately not plumbed. Level 2 (surviving_hemisphere) exists for the case where exactly one hemisphere is non-empty — but then the bilateral density volume is, by construction, identical to the surviving hemisphere's, so level 1 already selects the correct plane. Passing per-hemisphere volumes would add two persisted products to reach an unreachable branch. Please do not "fix" this.

Degradation

Every missing input degrades its own panel to a labelled grayscale-FA slot. The strip always renders four panels: it never reflows to three, because a reader must be able to see which question went unanswered.

Parameters:

Name Type Description Default
fa_path path

Required. Supplies the grid, the backgrounds and the level-4 slice fallback.

required
v1_path path or None

Optional persisted products, each on the FA grid. A volume that is present but on a different grid raises ValueError rather than being resampled silently.

required
density_path path or None

Optional persisted products, each on the FA grid. A volume that is present but on a different grid raises ValueError rather than being resampled silently.

required
roi_dseg_path path or None

Optional persisted products, each on the FA grid. A volume that is present but on a different grid raises ValueError rather than being resampled silently.

required
cst_left_path path or None

The two persisted tractograms.

required
cst_right_path path or None

The two persisted tractograms.

required
slab_mm float

Physical slab thickness for panels 3 and 4.

DEFAULT_SLAB_MM
max_streamlines int

Per-hemisphere subsample cap for panel 4.

500
seed int

Seed for that subsample. Defaults to :data:csttool.reproducibility.context.DEFAULT_SEED, which keeps this panel independent of figure subsampling. (viz.utils.VIZ_SEED was itself randomised per process until it moved to :func:~csttool.reproducibility.context.derive_seed, which made the legacy panel irreproducible across runs; both are stable now.)

None

Returns:

Type Description
Path

The saved PNG. A JSON sidecar beside it records the slice, the rule that chose it, the slab, the counts, the density maximum and the display cap that differs from it, the per-ROI slab voxel counts and which panels degraded.

Source code in src/csttool/metrics/modules/visualizations.py
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
def plot_report_qc_strip(
    fa_path,
    v1_path,
    density_path,
    roi_dseg_path,
    cst_left_path,
    cst_right_path,
    output_dir,
    subject_id,
    *,
    slab_mm=_geo.DEFAULT_SLAB_MM,
    max_streamlines=500,
    seed=None,
):
    """1x4 report QC strip: DEC-FA, CST density, extraction ROIs, CST over FA.

    Replaces the 1x3 triptych, which showed the same information (streamlines
    over FA) from three angles. These four panels answer four different
    questions on **one** shared coronal slice:

    1. does the local diffusion field support the expected CST orientation?
    2. is the reconstructed bundle spatially coherent?
    3. were the intended anatomical constraints applied?
    4. is the final tract anatomically plausible?

    One figure, one owner
    ---------------------
    The strip is a single PNG placed by CSS at :data:`QC_STRIP_WIDTH_MM`, so
    this function creates the Figure and the four Axes and draws into them with
    the ``csttool.viz.render`` primitives. It does **not** call the standalone
    ``qc_figures.plot_*_panel`` functions: each of those owns a Figure and saves
    it, which cannot be composed onto one canvas. The cost is four render calls
    per panel; the alternative — refactoring five reviewed standalone figures to
    accept an axes — is a larger change that would touch tested figures for no
    benefit here.

    That ownership extends to **every panel-level annotation**: titles, the DEC
    direction key, the density colourbar, the ROI key and the hemisphere counts
    are all drawn here, and the HTML template contributes only the section
    heading. Only the Figure knows where the panels actually landed, so only the
    Figure can align a key to a panel column; and a key drawn from
    ``style.LEFT`` / ``style.BRAINSTEM`` / ``style.DENSITY_CMAP`` cannot drift
    from the marks it describes, which a CSS copy can. This is the same rule
    ``plot_profile_matrix`` already follows.

    Layout
    ------
    Four columns, each carrying — top to bottom — a 9 pt bold title, its image,
    and its own key. One shared caption spans the strip beneath them, carrying
    only what is true of all four panels: the plane, the rule that chose it, the
    display slab and the orientation convention. Panel-specific facts live in
    panel-specific keys, so no reader has to cross the figure to decode a mark.

    Geometry is computed by :func:`qc_strip_geometry` from the displayed slice's
    aspect, which is what keeps the furniture bands meaningful — see that
    function for the defect this replaces.

    One slice
    ---------
    The slice is chosen **once**, by :func:`csttool.viz.geometry.select_qc_slice`,
    and every panel gets it. The standalone panels each select their own, and
    two of them are called with ``density=None`` and so fall through to the
    level-4 anatomical fallback while a third gets level 1 — meaning the
    "shared slice" has never actually held outside a prototype driver. It holds
    here.

    ``density_left`` / ``density_right`` are deliberately not plumbed. Level 2
    (``surviving_hemisphere``) exists for the case where exactly one hemisphere
    is non-empty — but then the *bilateral* density volume is, by construction,
    identical to the surviving hemisphere's, so level 1 already selects the
    correct plane. Passing per-hemisphere volumes would add two persisted
    products to reach an unreachable branch. Please do not "fix" this.

    Degradation
    -----------
    Every missing input degrades its own panel to a labelled grayscale-FA slot.
    The strip always renders four panels: it never reflows to three, because a
    reader must be able to see *which* question went unanswered.

    Parameters
    ----------
    fa_path : path
        Required. Supplies the grid, the backgrounds and the level-4 slice
        fallback.
    v1_path, density_path, roi_dseg_path : path or None
        Optional persisted products, each on the FA grid. A volume that is
        present but on a different grid raises ``ValueError`` rather than being
        resampled silently.
    cst_left_path, cst_right_path : path or None
        The two persisted tractograms.
    slab_mm : float
        Physical slab thickness for panels 3 and 4.
    max_streamlines : int
        Per-hemisphere subsample cap for panel 4.
    seed : int, optional
        Seed for that subsample. Defaults to
        :data:`csttool.reproducibility.context.DEFAULT_SEED`, which keeps this
        panel independent of figure subsampling. (``viz.utils.VIZ_SEED`` was
        itself randomised per process until it moved to
        :func:`~csttool.reproducibility.context.derive_seed`, which made the
        legacy panel irreproducible across runs; both are stable now.)

    Returns
    -------
    pathlib.Path
        The saved PNG. A JSON sidecar beside it records the slice, the rule that
        chose it, the slab, the counts, the density maximum and the display cap
        that differs from it, the per-ROI slab
        voxel counts and which panels degraded.
    """
    import json

    import nibabel as nib
    from dipy.io.streamline import load_tractogram

    from csttool.reproducibility.context import DEFAULT_SEED
    from csttool.viz import render as _render

    if seed is None:
        seed = DEFAULT_SEED

    output_dir = Path(output_dir)
    output_dir.mkdir(parents=True, exist_ok=True)

    fa_img = nib.load(str(fa_path))
    affine = fa_img.affine
    fa = fa_img.get_fdata().astype(np.float32)

    v1_img = _load_optional(v1_path, fa.shape, affine, "V1 field")
    density_img = _load_optional(density_path, fa.shape, affine, "CST density")
    dseg_img = _load_optional(roi_dseg_path, fa.shape, affine, "ROI segmentation")

    density = density_img.get_fdata().astype(np.float32) if density_img is not None else None
    dseg = np.asarray(dseg_img.dataobj) if dseg_img is not None else None

    def _load_streamlines(path):
        if path is None or not Path(path).exists():
            return []
        try:
            return list(load_tractogram(str(path), 'same').streamlines)
        except Exception:
            return []

    left = _load_streamlines(cst_left_path)
    right = _load_streamlines(cst_right_path)

    # One slice for all four panels. The ROI dseg feeds the level-3 fallback, so
    # a run whose extraction produced no streamlines at all is still shown at a
    # plane its own targets occupy.
    roi_masks = None
    if dseg is not None:
        roi_masks = [dseg == value for value in (1, 2, 3)]
    slice_index, provenance = _geo.select_qc_slice(
        density=density, roi_masks=roi_masks,
        brain_mask=(fa > 0).astype(np.uint8), affine=affine, view="coronal",
    )

    # ---- canvas ----------------------------------------------------------
    # Geometry first, from the displayed slice's shape: the image boxes are
    # computed rather than allocated, so apply_aspect never moves them and the
    # furniture bands below hold what they were measured for.
    canvas_h, canvas_w = _geo.slice_2d(fa, "coronal", slice_index).shape
    geom = qc_strip_geometry(canvas_w, canvas_h)
    width_mm, height_mm = geom["width_mm"], geom["height_mm"]
    panel_mm, image_mm = geom["panel_w_mm"], geom["image_h_mm"]
    fig = plt.figure(figsize=(width_mm / 25.4, height_mm / 25.4))

    axes = []
    for column in range(4):
        axes.append(fig.add_axes([
            geom["panel_x0_mm"][column] / width_mm,
            geom["image_y0_mm"] / height_mm,
            panel_mm / width_mm,
            image_mm / height_mm,
        ]))

    degraded = []

    def _background(ax):
        return _render.render_scalar_slice(
            ax, fa, affine, "coronal", slice_index,
            cmap=_style.ANATOMY_BG, norm=plt.Normalize(0, 1), markers=False,
        )

    def _title(ax, text):
        # 9 pt, matching the profile matrix's subplot titles. The pad is inside
        # _STRIP_TITLE_MM, which is the rendered height of this type plus it.
        ax.set_title(text, fontsize=_STRIP_TITLE_PT, fontweight='bold', pad=2.0)

    def _unavailable(ax, title, note):
        # The title names the panel; it never reports status. A reader must be
        # able to see which of the four questions went unanswered without the
        # heading row changing length from subject to subject.
        _background(ax)
        _title(ax, title)
        ax.text(0.5, 0.06, note, transform=ax.transAxes, ha='center', va='bottom',
                fontsize=_STRIP_NOTE_PT, style='italic', color='#dddddd')

    # ---- panel 1: DEC-FA -------------------------------------------------
    if v1_img is not None:
        v1 = v1_img.get_fdata(dtype=np.float32)
        if v1.ndim == 5:  # the stored product is (X, Y, Z, 1, 3)
            v1 = v1.squeeze(axis=3)
        # |V1_world| * clip(FA, 0, 1) — dipy.reconst.dti.color_fa's formula
        # applied to the already-rotated field. Calling color_fa directly would
        # re-apply its voxel-frame assumption. No gamma and no percentile
        # stretch: brightness *is* FA, so a dark panel is a real finding.
        dec = np.abs(v1) * np.clip(fa, 0, 1)[..., None]
        dec = np.clip(dec, 0.0, 1.0).astype(np.float32)
        _render.render_rgb_slice(axes[0], dec, affine, "coronal", slice_index,
                                 markers=False)
        # The direction key is drawn in this panel's column of the key band
        # below, not as an inset over the image. The arrow glyph it replaces was
        # a 6.1 x 6.1 mm opaque box covering ~3.5% of the panel, in the
        # inferior-lateral corner the CST descends through; its own docstring
        # concedes it cannot be shrunk below 0.22 in and stay legible, so it had
        # to leave the image rather than get smaller. render.add_direction_legend
        # stays in place for the standalone 90 mm panel, where 6 mm is
        # proportionate.
        _title(axes[0], "DEC-FA")
    else:
        _unavailable(axes[0], "DEC-FA", "world-frame V1 not produced")
        degraded.append("dec_fa")

    # ---- panel 2: CST density -------------------------------------------
    # Two different numbers, deliberately named apart. The *display* cap is a
    # presentation choice; the *true* maximum is a property of the data. The old
    # single ``vmax`` carried the first under a name that reads like the second,
    # which is exactly the confusion the endpoint label has to avoid.
    density_max_fraction = None      # the volume's real maximum, in [0, 1]
    density_display_vmax = None      # where the colour scale saturates
    density_display_clipped = False  # True when real values exceed that cap
    density_image = None
    if density is not None:
        nonzero = density[density > 0]
        # Subject-adaptive: a fixed [0, 1] scale renders real subjects nearly
        # uniformly dark, because the bilateral denominator puts even a fully
        # occupied unilateral voxel near 0.5 and real maxima far below that. No
        # log or power stretch: that would be a second normalization on top of
        # the persisted definition and would make two subjects incomparable.
        density_max_fraction = float(density.max()) if density.size else 0.0
        density_display_vmax = (
            float(np.percentile(nonzero, _DENSITY_DISPLAY_PERCENTILE))
            if nonzero.size else 1.0
        )
        # Saturation is a fact about this subject, not an assumption: on the
        # validation subject the true maximum is 1.9x the cap, so 71 voxels
        # share the top colour and a bare endpoint would misname the maximum.
        # Where the cap happens to reach the maximum, no "≥" is claimed.
        density_display_clipped = density_max_fraction > density_display_vmax
        _background(axes[1])
        density_image = _render.render_density_overlay(
            axes[1], density, affine, "coronal", slice_index,
            cmap=_style.DENSITY_CMAP, vmax=density_display_vmax,
        )
        _title(axes[1], "CST density")
    else:
        _unavailable(axes[1], "CST density", "density map not produced")
        degraded.append("density")

    # ---- panel 3: extraction ROIs ---------------------------------------
    roi_slab_voxels = {}
    if dseg is not None:
        _background(axes[2])
        roi_colors = (
            (1, "brainstem", _style.BRAINSTEM),
            (2, "motor_left", _style.MOTOR_LEFT),
            (3, "motor_right", _style.MOTOR_RIGHT),
        )
        for value, name, color in roi_colors:
            projected, n_voxels = _slab_projected_volume(
                dseg == value, affine, "coronal", slice_index, slab_mm
            )
            roi_slab_voxels[name] = n_voxels
            if n_voxels:
                # Contours, not fills: three opaque blobs on a 48 mm panel would
                # hide the anatomy they exist to be checked against.
                _render.render_mask_contour(
                    axes[2], projected, affine, "coronal", slice_index,
                    color=color, linewidth=_STRIP_ROI_LINEWIDTH,
                )
        _title(axes[2], "Extraction ROIs")
    else:
        _unavailable(axes[2], "Extraction ROIs", "ROI segmentation not produced")
        degraded.append("roi_dseg")

    # ---- panel 4: final CST over FA -------------------------------------
    _background(axes[3])
    rng = np.random.default_rng(seed)
    for streamlines, color in ((left, _style.LEFT), (right, _style.RIGHT)):
        _render.render_streamline_overlay(
            axes[3], streamlines, affine, "coronal", slice_index, color=color,
            thickness_mm=slab_mm, max_streamlines=max_streamlines, rng=rng,
        )
    _title(axes[3], "CST over FA")
    if not left and not right:
        degraded.append("streamlines")

    # ---- shared geometry -------------------------------------------------
    # Every panel is the same view of the same grid, so one canvas gives all
    # four identical world limits: 1 mm of brain is 1 mm of paper everywhere,
    # and the four are directly comparable by eye.
    #
    # When the image-height cap binds, the panel box is wider than the data, so
    # the common canvas is widened to the box's aspect and the difference prints
    # as the black letterbox this helper draws. Without this the box and the
    # data would disagree and apply_aspect would start moving boxes again.
    canvas_w_eff, canvas_h_eff = canvas_w, canvas_h
    if geom["box_aspect"] > geom["aspect"]:
        canvas_w_eff = canvas_h * geom["box_aspect"]
    elif geom["box_aspect"] < geom["aspect"]:
        canvas_h_eff = canvas_w / geom["box_aspect"]
    for ax in axes:
        _geo.pad_axes_to_canvas(ax, canvas_w_eff, canvas_h_eff)
        # Markers, not legends: a reader must not have to look at a neighbouring
        # panel to orient the one they are reading.
        _geo.add_lr_markers(ax, fontsize=_STRIP_MARKER_PT)

    # ---- per-panel key band ----------------------------------------------
    # One key column per panel, aligned to that panel's own computed x-extent,
    # so every legend sits under the data it describes. Draw once first: the
    # renderer is what _draw_key_row measures against, and by this point the
    # image boxes are final (they were computed, so apply_aspect changed
    # nothing).
    fig.canvas.draw()
    renderer = fig.canvas.get_renderer()

    def _key_axes(column):
        return fig.add_axes([
            geom["panel_x0_mm"][column] / width_mm,
            geom["key_y0_mm"] / height_mm,
            panel_mm / width_mm,
            _STRIP_KEY_MM / height_mm,
        ])

    key_axes = [_key_axes(column) for column in range(4)]
    for ax in key_axes:
        ax.set_axis_off()

    # Panel 1: which world axis each colour channel is. Not a legend — it is the
    # whole content of a DEC image.
    rows = [list(_DEC_AXIS_KEY) if v1_img is not None else []]

    # Panel 2's label row is measured as a single centred token so it takes part
    # in the common fit; its two numeric ticks flank the bar and are short.
    rows.append([(None, _DENSITY_CBAR_LABEL)] if density_image is not None else [])

    # Panel 3: the ROI colour key, beside the contours it names. An ROI the
    # display slab never reaches is greyed rather than dropped, so a zero count
    # is visible instead of silently absent.
    if dseg is not None:
        rows.append([
            (_style.BRAINSTEM if roi_slab_voxels.get("brainstem") else _STRIP_INK_MUTED,
             "brainstem",
             _STRIP_INK if roi_slab_voxels.get("brainstem") else _STRIP_INK_MUTED),
            (_style.MOTOR_LEFT if roi_slab_voxels.get("motor_left") else _STRIP_INK_MUTED,
             "motor L",
             _STRIP_INK if roi_slab_voxels.get("motor_left") else _STRIP_INK_MUTED),
            (_style.MOTOR_RIGHT if roi_slab_voxels.get("motor_right") else _STRIP_INK_MUTED,
             "motor R",
             _STRIP_INK if roi_slab_voxels.get("motor_right") else _STRIP_INK_MUTED),
        ])
    else:
        rows.append([])

    # Panel 4: the hemisphere counts, beside the trajectories they count.
    rows.append([
        (_style.LEFT, f"Left n={len(left)}"),
        (_style.RIGHT, f"Right n={len(right)}"),
    ])

    # One size for the whole band, set by whichever row is tightest.
    key_pt = _fit_key_fontsize(key_axes[0], renderer, rows, _STRIP_KEY_PT)

    # The label row is the alignment anchor for all four columns: swatches for
    # panels 1, 3 and 4, the quantity name for panel 2. One shared baseline,
    # placed so the cap heights meet the band's top pad, and derived from the
    # fitted type size rather than fixed so the row holds whatever the auto-fit
    # settles on.
    text_h_mm = key_pt * 25.4 / 72.0
    cap_mm = _STRIP_KEY_CAP_FRAC * text_h_mm
    label_baseline_mm = _STRIP_KEY_MM - _STRIP_KEY_TEXT_PAD_MM - cap_mm
    label_y = label_baseline_mm / _STRIP_KEY_MM

    _draw_key_row(key_axes[0], renderer, rows[0], key_pt, y=label_y)
    _draw_key_row(key_axes[2], renderer, rows[2], key_pt, y=label_y)
    _draw_key_row(key_axes[3], renderer, rows[3], key_pt, y=label_y)

    # Panel 2: a continuous scale is not a set of swatches, so this column gets
    # the colourbar. Its quantity name sits on the shared label row with the
    # other three keys and the bar hangs beneath it, so the four columns still
    # read as one row of legends. The name is static and the number is dynamic,
    # so they are set separately: as one string the label measured 47.45 mm
    # inside a 48.05 mm column and overflowed into the neighbouring panels as
    # soon as the endpoint reached two integer digits.
    if density_image is not None:
        key_ax = key_axes[1]
        key_ax.text(0.5, label_y, _DENSITY_CBAR_LABEL,
                    transform=key_ax.transAxes, ha='center', va='baseline',
                    fontsize=key_pt, color=_STRIP_INK)

        # Percentages, not raw fractions: the stored value is a fraction but a
        # reader should not have to convert 0.074 in their head. The upper tick
        # says "≥" whenever the scale saturates below the true maximum, so it
        # can never be misread as the maximum itself.
        #
        # The bar's width is what is left after the two end ticks have their
        # room, so an endpoint needing more digits narrows the bar instead of
        # pushing a number into panel 1 or panel 3.
        tick_texts = (
            format_density_percent(0.0),
            format_density_percent(density_display_vmax,
                                   saturated=density_display_clipped),
        )
        tick_w_mm = []
        for text in tick_texts:
            probe = key_ax.text(0, 0, text, fontsize=key_pt)
            tick_w_mm.append(probe.get_window_extent(renderer).width
                             / fig.dpi * 25.4)
            probe.remove()
        gap_mm = _STRIP_SWATCH_GAP_MM
        # The bar is centred in the column, so each tick has (panel - bar) / 2
        # to live in and the *wider* of the two is what binds — using their sum
        # lets the longer one hang past the column edge.
        allowed = (panel_mm - 2 * gap_mm - 2 * max(tick_w_mm)
                   - 2 * _STRIP_CBAR_EDGE_MM)
        bar_w = min(allowed, _STRIP_CBAR_MAX_FRAC * panel_mm)
        bar_w = max(bar_w, _STRIP_CBAR_MIN_FRAC * panel_mm)
        # An endpoint wide enough to fight the minimum takes the bar down with it
        # rather than clipping: a short bar is legible, a truncated number is not.
        bar_w = max(min(bar_w, allowed), 0.15 * panel_mm)

        bar_top_mm = label_baseline_mm - _STRIP_CBAR_GAP_MM
        bar_x0_mm = geom["panel_x0_mm"][1] + (panel_mm - bar_w) / 2.0
        cbar_ax = fig.add_axes([
            bar_x0_mm / width_mm,
            (geom["key_y0_mm"] + bar_top_mm - _STRIP_CBAR_MM) / height_mm,
            bar_w / width_mm,
            _STRIP_CBAR_MM / height_mm,
        ])
        cbar = fig.colorbar(density_image, cax=cbar_ax, orientation='horizontal',
                            ticks=[])
        cbar.outline.set_linewidth(0.4)

        # Ticks flank the bar, on a baseline set so their cap height straddles
        # the bar's middle, so bar and endpoints read as one object rather than
        # three stacked lines.
        bar_lo = (panel_mm - bar_w) / 2.0
        tick_baseline_mm = bar_top_mm - _STRIP_CBAR_MM / 2.0 - cap_mm / 2.0
        tick_y = tick_baseline_mm / _STRIP_KEY_MM
        for x_mm, text, align in (
            ((bar_lo - gap_mm) / panel_mm, tick_texts[0], 'right'),
            ((bar_lo + bar_w + gap_mm) / panel_mm, tick_texts[1], 'left'),
        ):
            key_ax.text(x_mm, tick_y, text, transform=key_ax.transAxes,
                        ha=align, va='baseline', fontsize=key_pt,
                        color=_STRIP_INK)

    # ---- shared caption --------------------------------------------------
    caption_ax = fig.add_axes([0.0, geom["caption_y0_mm"] / height_mm, 1.0,
                               _STRIP_CAPTION_MM / height_mm])
    caption_ax.set_axis_off()
    caption_text = _strip_caption_text(
        slice_index, provenance, slab_mm,
        density_scale_note=density_image is not None,
    )
    # Measured and shrunk if need be, exactly as the key rows are. The caption
    # grows with the slice index, the rule name, the slab and the density note,
    # and the figure is saved with its exact bbox, so an overlong line would be
    # silently cut off at the canvas edge rather than wrap.
    caption_pt = _fit_caption_fontsize(caption_ax, renderer, caption_text,
                                       _STRIP_CAPTION_PT)
    caption_ax.text(
        0.5, 0.5, caption_text,
        transform=caption_ax.transAxes, ha='center', va='center',
        fontsize=caption_pt, color=_STRIP_INK,
    )

    fig_path = output_dir / f"{subject_id}_report_qc_strip.png"
    # Exact canvas, not a tight bbox — see plot_profile_matrix.
    _style.save_figure_exact(fig, fig_path)
    plt.close(fig)

    sidecar = {
        "Subject": str(subject_id),
        "Panel": "report-qc-strip",
        "Panels": ["DEC-FA", "CST density", "Extraction ROIs", "CST over FA"],
        "SliceIndex": int(slice_index),
        "SliceSelectionRule": provenance.get("rule"),
        "SliceSelectionProvenance": provenance,
        "SlabThicknessMm": float(slab_mm),
        "StreamlineCounts": {"left": len(left), "right": len(right)},
        "StreamlinesDrawn": {"left": min(len(left), max_streamlines),
                             "right": min(len(right), max_streamlines)},
        # Three separate facts, because the old single "DensityVmax" held the
        # display cap under a name that reads like a data maximum.
        "DensityMaxFraction": density_max_fraction,
        "DensityDisplayVmax": density_display_vmax,
        "DensityDisplayPercentile": (_DENSITY_DISPLAY_PERCENTILE
                                     if density_display_vmax is not None else None),
        "DensityDisplayPercentileBasis": ("non-zero voxels"
                                          if density_display_vmax is not None else None),
        "DensityDisplayClipped": density_display_clipped,
        "RoiSlabVoxelCounts": roi_slab_voxels,
        "DegradedPanels": degraded,
        "Seed": int(seed),
        # The figure size is derived from the displayed slice's aspect, so it is
        # disclosed rather than assumed to be the module constant.
        "FigureSizeMm": [round(width_mm, 3), round(height_mm, 3)],
        "PanelAspect": round(geom["aspect"], 6),
    }
    fig_path.with_suffix('.json').write_text(
        json.dumps(sidecar, indent=2) + "\n", encoding='utf-8'
    )
    print(f"✓ Report QC strip saved: {fig_path}")
    return fig_path

plot_tractogram_qc_preview(streamlines_left, streamlines_right, background_image, affine, output_dir, subject_id, slice_type='axial', max_streamlines=500, set_title=True)

Create compact 3D tractogram QC preview (single view, standalone output).

Renders left (blue) and right (orange) CST streamlines overlaid on a brain slice at the internal-capsule level. Used for the standalone per-view QC PNGs written under --save-visualizations; the PDF report uses the composite :func:plot_tractogram_qc_triptych instead.

Source code in src/csttool/metrics/modules/visualizations.py
def plot_tractogram_qc_preview(
    streamlines_left,
    streamlines_right,
    background_image,
    affine,
    output_dir,
    subject_id,
    slice_type='axial',
    max_streamlines=500,
    set_title=True
):
    """
    Create compact 3D tractogram QC preview (single view, standalone output).

    Renders left (blue) and right (orange) CST streamlines overlaid on a brain
    slice at the internal-capsule level. Used for the standalone per-view QC
    PNGs written under ``--save-visualizations``; the PDF report uses the
    composite :func:`plot_tractogram_qc_triptych` instead.
    """
    output_dir = Path(output_dir)
    output_dir.mkdir(parents=True, exist_ok=True)

    rng = viz_rng()
    fig, ax = plt.subplots(figsize=(4, 4))
    _render_qc_slice(
        ax, streamlines_left, streamlines_right, background_image, affine,
        slice_type, max_streamlines=max_streamlines, rng=rng,
    )
    # Match the canvas aspect to the slice so the standalone PNG has minimal
    # whitespace (the slice is already drawn at correct pixel aspect via
    # aspect='equal').
    slice_idx = _qc_slice_index(background_image, slice_type)
    bg_slice = _geo.slice_2d(background_image, slice_type, slice_idx)
    data_ratio = bg_slice.shape[0] / bg_slice.shape[1]
    fig.set_size_inches(4, 4 * data_ratio)

    from matplotlib.lines import Line2D
    legend_elements = [
        Line2D([0], [0], color=_style.LEFT, linewidth=2, label='Left CST'),
        Line2D([0], [0], color=_style.RIGHT, linewidth=2, label='Right CST'),
    ]
    ax.legend(handles=legend_elements, loc='upper right', fontsize=8)

    if set_title:
        ax.set_title(f'CST Tractogram ({slice_type.title()})', fontsize=10, fontweight='bold')

    plt.tight_layout()
    fig_path = output_dir / f"{subject_id}_tractogram_qc_{slice_type}.png"
    _style.save_figure(fig, fig_path)
    plt.close()
    print(f"✓ Tractogram QC preview saved: {fig_path}")
    return fig_path

plot_tractogram_qc_triptych(streamlines_left, streamlines_right, background_image, affine, output_dir, subject_id, background_kind=None, max_streamlines=500, slice_indices=None)

Composite 1x3 tractogram QC figure.

.. deprecated:: Superseded in the PDF report by :func:plot_report_qc_strip, which answers four different questions on one shared slice instead of the same question (streamlines over FA) from three angles. This function is not removed: it stays exported and tested, and generate_complete_report still falls back to it for a caller that supplies no product paths. New code should use the strip.

Geometry

The three views come from different voxel planes and therefore have different source shapes (e.g. 72x96 sagittal/coronal vs 96x96 axial). Each image axis is given the same physical box and the same common data canvas — the union of the three slice extents, centred on each slice — so the panels are equally sized and equally scaled, with black letterboxing where a slice is smaller than the canvas. Nothing is stretched: the anatomical aspect ratio is preserved by aspect='equal'.

The colorbar lives on its own GridSpec column and is then snapped to the vertical extent of the image row, so it can never overlap an image (it used to be stolen out of the shared axes area and landed on top of the axial panel).

Scale

Sagittal / coronal / axial slices share a single grayscale FA scale (one matplotlib.colors.Normalize(vmin=0, vmax=1) instance) which is also the colorbar's, so the three views and the colorbar cannot drift apart by construction. The FA colorbar is rendered only when background_kind == "fa"; the caller must state what the background is (no boolean default) so an FA colorbar is never shown over a non-FA background.

Size

Generated at its exact final report size (:data:QC_TRIPTYCH_SIZE_MM) and saved with the exact figure bbox, so the printed height is the designed height and the one-page budget is exact.

Parameters:

Name Type Description Default
background_kind str or None

"fa" to render the FA colorbar; anything else (e.g. "other") suppresses it. No implicit default — the caller must declare it.

None
slice_indices dict

{'sagittal': i, 'coronal': j, 'axial': k} override; falls back to :func:_qc_slice_index (center slices).

None
Source code in src/csttool/metrics/modules/visualizations.py
def plot_tractogram_qc_triptych(
    streamlines_left,
    streamlines_right,
    background_image,
    affine,
    output_dir,
    subject_id,
    background_kind=None,
    max_streamlines=500,
    slice_indices=None,
):
    """
    Composite 1x3 tractogram QC figure.

    .. deprecated::
        Superseded in the PDF report by :func:`plot_report_qc_strip`, which
        answers four different questions on one shared slice instead of the same
        question (streamlines over FA) from three angles. This function is
        **not** removed: it stays exported and tested, and `generate_complete_report`
        still falls back to it for a caller that supplies no product paths. New
        code should use the strip.

    Geometry
    --------
    The three views come from different voxel planes and therefore have
    different source shapes (e.g. 72x96 sagittal/coronal vs 96x96 axial). Each
    image axis is given the *same* physical box and the *same* common data
    canvas — the union of the three slice extents, centred on each slice — so
    the panels are equally sized and equally scaled, with black letterboxing
    where a slice is smaller than the canvas. Nothing is stretched: the
    anatomical aspect ratio is preserved by ``aspect='equal'``.

    The colorbar lives on its own GridSpec column and is then snapped to the
    vertical extent of the image row, so it can never overlap an image (it used
    to be stolen out of the shared axes area and landed on top of the axial
    panel).

    Scale
    -----
    Sagittal / coronal / axial slices share a single grayscale FA scale (one
    ``matplotlib.colors.Normalize(vmin=0, vmax=1)`` instance) which is also the
    colorbar's, so the three views and the colorbar cannot drift apart by
    construction. The FA colorbar is rendered **only** when
    ``background_kind == "fa"``; the caller must state what the background is
    (no boolean default) so an FA colorbar is never shown over a non-FA
    background.

    Size
    ----
    Generated at its exact final report size (:data:`QC_TRIPTYCH_SIZE_MM`) and
    saved with the exact figure bbox, so the printed height is the designed
    height and the one-page budget is exact.

    Parameters
    ----------
    background_kind : str or None
        ``"fa"`` to render the FA colorbar; anything else (e.g. ``"other"``)
        suppresses it. No implicit default — the caller must declare it.
    slice_indices : dict, optional
        ``{'sagittal': i, 'coronal': j, 'axial': k}`` override; falls back to
        :func:`_qc_slice_index` (center slices).
    """
    from matplotlib.colors import Normalize

    output_dir = Path(output_dir)
    output_dir.mkdir(parents=True, exist_ok=True)

    show_colorbar = background_kind == "fa"
    # One Normalize instance shared by all three images and the colorbar.
    norm = Normalize(vmin=0.0, vmax=1.0) if show_colorbar else None
    rng = viz_rng()

    views = ('sagittal', 'coronal', 'axial')
    fig_width = QC_TRIPTYCH_SIZE_MM[0] / 25.4
    fig_height = QC_TRIPTYCH_SIZE_MM[1] / 25.4
    fig = plt.figure(figsize=(fig_width, fig_height))
    gs = fig.add_gridspec(
        1, 4, width_ratios=[1.0, 1.0, 1.0, 0.05], wspace=0.04,
        left=0.005, right=0.945, top=0.90, bottom=0.02,
    )
    axes = [fig.add_subplot(gs[0, i]) for i in range(3)]
    cax = fig.add_subplot(gs[0, 3])

    # Common display canvas: the largest slice extent across the three views, so
    # every panel covers the same number of voxels and is scaled identically.
    canvas_h, canvas_w = 0, 0
    for view in views:
        idx = (slice_indices or {}).get(view, _qc_slice_index(background_image, view))
        h, w = _geo.slice_2d(background_image, view, idx).shape
        canvas_h, canvas_w = max(canvas_h, h), max(canvas_w, w)

    last_im = None
    for ax, view in zip(axes, views):
        last_im = _render_qc_slice(
            ax, streamlines_left, streamlines_right, background_image, affine,
            view, max_streamlines=max_streamlines, norm=norm, rng=rng,
            slice_idx=(slice_indices or {}).get(view),
        )
        _geo.pad_axes_to_canvas(ax, canvas_w, canvas_h)
        ax.set_title(view.capitalize(), fontsize=_RPT_TICK_PT, pad=1.5)

    if show_colorbar and last_im is not None:
        cbar = fig.colorbar(
            last_im, cax=cax, orientation='vertical',
            ticks=[0.0, 0.25, 0.5, 0.75, 1.0],
        )
        # Label above the bar, not rotated beside it: a rotated y-label needs a
        # wide right margin that would come straight out of the panel widths.
        cax.set_title('FA', fontsize=6.5, pad=2)
        cbar.ax.tick_params(labelsize=6, length=1.5, width=0.5, pad=1)
        cbar.outline.set_linewidth(0.5)
        # Snap the colorbar to the image row's real vertical extent. The image
        # axes shrink to their data aspect only at draw time, so this has to
        # happen after a draw pass, and must read the *active* position.
        fig.canvas.draw()
        img_box = axes[0].get_position(original=False)
        cbar_box = cax.get_position()
        cax.set_position([cbar_box.x0, img_box.y0, cbar_box.width, img_box.height])
    else:
        cax.set_visible(False)

    fig_path = output_dir / f"{subject_id}_tractogram_qc_triptych.png"
    # Exact canvas, not a tight bbox — see plot_profile_matrix.
    _style.save_figure_exact(fig, fig_path)
    plt.close(fig)
    print(f"✓ Tractogram QC triptych saved: {fig_path}")
    return fig_path

save_json_report(comparison, output_dir, subject_id, metadata=None)

Save comprehensive metrics report as JSON.

Parameters:

Name Type Description Default
comparison dict

Output from compare_bilateral_cst()

required
output_dir str or Path

Output directory

required
subject_id str

Subject identifier

required
metadata dict

Additional metadata including: - acquisition: dict with protocol, b_values, n_directions, resolution - processing: dict with denoising_method, tracking_method, etc. - qc_thresholds: dict with fa_threshold, min_length, max_length - provenance: dict from get_provenance_dict() (git, deps, hardware, etc.)

None

Returns:

Name Type Description
json_path Path

Path to saved JSON file

Source code in src/csttool/metrics/modules/reports.py
def save_json_report(comparison, output_dir, subject_id, metadata=None):
    """
    Save comprehensive metrics report as JSON.

    Parameters
    ----------
    comparison : dict
        Output from compare_bilateral_cst()
    output_dir : str or Path
        Output directory
    subject_id : str
        Subject identifier
    metadata : dict, optional
        Additional metadata including:
        - acquisition: dict with protocol, b_values, n_directions, resolution
        - processing: dict with denoising_method, tracking_method, etc.
        - qc_thresholds: dict with fa_threshold, min_length, max_length
        - provenance: dict from get_provenance_dict() (git, deps, hardware, etc.)

    Returns
    -------
    json_path : Path
        Path to saved JSON file
    """

    output_dir = Path(output_dir)
    output_dir.mkdir(parents=True, exist_ok=True)

    # Initialize metadata if not provided
    if metadata is None:
        metadata = {}

    # Build report with extended schema. The uncertainty block is attached to the
    # serialised copy rather than mutating the caller's comparison dict, which is
    # also handed to the figure and HTML paths.
    metrics = dict(comparison)
    metrics['uncertainty'] = build_uncertainty_block()

    report = {
        'subject_id': subject_id,
        'processing_date': datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
        'csttool_version': __version__,
        'acquisition': metadata.get('acquisition', {}),
        'processing': metadata.get('processing', {}),
        'qc_thresholds': metadata.get('qc_thresholds', {}),
        'provenance': metadata.get('provenance', {}),
        'metrics': metrics
    }

    # Save JSON
    json_path = output_dir / f"{subject_id}_bilateral_metrics.json"
    with open(json_path, 'w') as f:
        json.dump(report, f, indent=2)

    print(f"  ✓ JSON report saved: {json_path}")
    return json_path

save_csv_summary(comparison, output_dir, subject_id)

Save metrics summary as CSV table.

Creates a flat CSV file with key metrics suitable for group analysis.

Parameters:

Name Type Description Default
comparison dict

Output from compare_bilateral_cst()

required
output_dir str or Path

Output directory

required
subject_id str

Subject identifier

required

Returns:

Name Type Description
csv_path Path

Path to saved CSV file

Source code in src/csttool/metrics/modules/reports.py
def save_csv_summary(comparison, output_dir, subject_id):
    """
    Save metrics summary as CSV table.

    Creates a flat CSV file with key metrics suitable for group analysis.

    Parameters
    ----------
    comparison : dict
        Output from compare_bilateral_cst()
    output_dir : str or Path
        Output directory
    subject_id : str
        Subject identifier

    Returns
    -------
    csv_path : Path
        Path to saved CSV file
    """

    output_dir = Path(output_dir)
    output_dir.mkdir(parents=True, exist_ok=True)

    left = comparison['left']
    right = comparison['right']
    asym = comparison['asymmetry']

    # Prepare data row
    data = {
        'subject_id': subject_id,
        'processing_date': datetime.now().strftime("%Y-%m-%d"),

        # Left morphology
        'left_n_streamlines': left['morphology']['n_streamlines'],
        'left_mean_length_mm': left['morphology']['mean_length'],
        'left_median_length_mm': left['morphology'].get('median_length', 0.0),
        'left_tract_volume_mm3': left['morphology']['tract_volume'],

        # Right morphology
        'right_n_streamlines': right['morphology']['n_streamlines'],
        'right_mean_length_mm': right['morphology']['mean_length'],
        'right_median_length_mm': right['morphology'].get('median_length', 0.0),
        'right_tract_volume_mm3': right['morphology']['tract_volume'],

        # Asymmetry
        'volume_laterality_index': asym['volume']['laterality_index'],
        'streamline_count_laterality_index': asym['streamline_count']['laterality_index'],
    }

    # Add FA if available
    if 'fa' in left:
        data.update({
            'left_fa_mean': left['fa']['mean'],
            'left_fa_std': left['fa']['std'],
            'right_fa_mean': right['fa']['mean'],
            'right_fa_std': right['fa']['std'],
            'fa_laterality_index': asym['fa']['laterality_index'],
            # Length-biased counterpart, preserved for bias auditing (AU10):
            'left_fa_mean_point_weighted': left['fa'].get('mean_point_weighted', 0.0),
            'right_fa_mean_point_weighted': right['fa'].get('mean_point_weighted', 0.0),
        })

    # Add MD if available
    if 'md' in left:
        data.update({
            'left_md_mean': left['md']['mean'],
            'left_md_std': left['md']['std'],
            'right_md_mean': right['md']['mean'],
            'right_md_std': right['md']['std'],
            'md_laterality_index': asym['md']['laterality_index'],
            'left_md_mean_point_weighted': left['md'].get('mean_point_weighted', 0.0),
            'right_md_mean_point_weighted': right['md'].get('mean_point_weighted', 0.0),
        })

    # Add RD if available
    if 'rd' in left:
        data.update({
            'left_rd_mean': left['rd']['mean'],
            'left_rd_std': left['rd']['std'],
            'right_rd_mean': right['rd']['mean'],
            'right_rd_std': right['rd']['std'],
            'rd_laterality_index': asym['rd']['laterality_index'],
            'left_rd_mean_point_weighted': left['rd'].get('mean_point_weighted', 0.0),
            'right_rd_mean_point_weighted': right['rd'].get('mean_point_weighted', 0.0),
        })

    # Add AD if available
    if 'ad' in left:
        data.update({
            'left_ad_mean': left['ad']['mean'],
            'left_ad_std': left['ad']['std'],
            'right_ad_mean': right['ad']['mean'],
            'right_ad_std': right['ad']['std'],
            'ad_laterality_index': asym['ad']['laterality_index'],
            'left_ad_mean_point_weighted': left['ad'].get('mean_point_weighted', 0.0),
            'right_ad_mean_point_weighted': right['ad'].get('mean_point_weighted', 0.0),
        })

    # Add localized metrics (inferior/central/superior bins) for each scalar
    regions = ['pontine', 'plic', 'precentral']
    scalars = ['fa', 'md', 'rd', 'ad']

    for scalar in scalars:
        if scalar in left and 'pontine' in left[scalar]:
            for region in regions:
                data[f'left_{scalar}_{region}'] = left[scalar].get(region, 0.0)
                data[f'right_{scalar}_{region}'] = right[scalar].get(region, 0.0)
                # Add LI for localized metric
                li_key = f'{scalar}_{region}'
                if li_key in asym:
                    data[f'{scalar}_{region}_laterality_index'] = asym[li_key]['laterality_index']

    # Bootstrap standard errors, appended at the end so a reader that indexes by
    # column position is unaffected. Regional SEs are deliberately not exported:
    # 24 more columns for a value the report does not display. A missing SE is an
    # empty cell, never 0.0 (see _se_cell).
    data['left_mean_length_se'] = _se_cell(left['morphology'].get('bootstrap_se_length'))
    data['right_mean_length_se'] = _se_cell(right['morphology'].get('bootstrap_se_length'))
    for scalar in scalars:
        if scalar in left and scalar in right:
            data[f'left_{scalar}_bootstrap_se'] = _se_cell(left[scalar].get('bootstrap_se'))
            data[f'right_{scalar}_bootstrap_se'] = _se_cell(right[scalar].get('bootstrap_se'))
            data[f'{scalar}_laterality_index_se'] = _se_cell(
                asym.get(scalar, {}).get('laterality_index_se')
            )

    # Node homology: the two headline scalars only. The 20-element per-node
    # difference arrays stay in the JSON — they have no place in a flat table.
    homology = comparison.get('node_homology') or {}
    data['node_homology_max_abs_z_diff_mm'] = _se_cell(
        homology.get('max_abs_z_difference_mm')
    )
    data['node_homology_length_diff_mm'] = _se_cell(
        homology.get('length_difference_mm')
    )

    # Save CSV
    csv_path = output_dir / f"{subject_id}_metrics_summary.csv"
    with open(csv_path, 'w', newline='') as f:
        writer = csv.DictWriter(f, fieldnames=data.keys())
        writer.writeheader()
        writer.writerow(data)

    print(f"  ✓ CSV summary saved: {csv_path}")
    return csv_path

save_html_report(comparison, visualization_paths, output_dir, subject_id, version=None, space='Native Space', metadata=None, fa_affine=None)

Generate HTML report using Jinja2 template.

Parameters:

Name Type Description Default
comparison dict

Output from compare_bilateral_cst()

required
visualization_paths dict

Paths to generated visualizations. Expected keys: profile_matrix (the 2x2 along-tract figure) and tractogram_qc_triptych (the 1x3 QC composite). Both are optional and render as placeholders if absent.

required
output_dir str or Path

Output directory

required
subject_id str

Subject identifier

required
version str

csttool version (defaults to package version)

None
space str

Space declaration (e.g., "Native Space")

'Native Space'
metadata dict

Acquisition, processing, and provenance metadata

None
fa_affine ndarray

FA-map affine used to compute the orientation code dynamically. When None, orientation renders as N/A.

None

Returns:

Name Type Description
html_path Path

Path to saved HTML file

Source code in src/csttool/metrics/modules/reports.py
def save_html_report(
    comparison,
    visualization_paths,
    output_dir,
    subject_id,
    version=None,
    space="Native Space",
    metadata=None,
    fa_affine=None,
):
    """
    Generate HTML report using Jinja2 template.

    Parameters
    ----------
    comparison : dict
        Output from compare_bilateral_cst()
    visualization_paths : dict
        Paths to generated visualizations. Expected keys: ``profile_matrix``
        (the 2x2 along-tract figure) and ``tractogram_qc_triptych`` (the 1x3
        QC composite). Both are optional and render as placeholders if absent.
    output_dir : str or Path
        Output directory
    subject_id : str
        Subject identifier
    version : str, optional
        csttool version (defaults to package version)
    space : str
        Space declaration (e.g., "Native Space")
    metadata : dict, optional
        Acquisition, processing, and provenance metadata
    fa_affine : ndarray, optional
        FA-map affine used to compute the orientation code dynamically. When
        None, orientation renders as ``N/A``.

    Returns
    -------
    html_path : Path
        Path to saved HTML file
    """
    if version is None:
        version = __version__

    if metadata is None:
        metadata = {}

    output_dir = Path(output_dir)
    output_dir.mkdir(parents=True, exist_ok=True)

    context = build_report_context(
        comparison=comparison,
        visualization_paths=visualization_paths,
        subject_id=subject_id,
        version=version,
        space=space,
        metadata=metadata,
        fa_affine=fa_affine,
    )

    # Load template and CSS
    template = _jinja_env.get_template("report.html.j2")
    css = (_TEMPLATE_DIR / "report.css").read_text()

    # Render template with context
    html_content = template.render(css=css, **context)

    html_path = output_dir / f"{subject_id}_report.html"
    html_path.write_text(html_content, encoding="utf-8")

    print(f"  ✓ HTML report saved: {html_path}")
    return html_path

save_pdf_report(comparison, visualization_paths, output_dir, subject_id, version=None, space='Native Space', html_path=None)

Generate PDF report by converting HTML report.

Source code in src/csttool/metrics/modules/reports.py
def save_pdf_report(
    comparison,
    visualization_paths,
    output_dir,
    subject_id,
    version=None,
    space="Native Space",
    html_path=None
):
    """
    Generate PDF report by converting HTML report.
    """
    output_dir = Path(output_dir)
    pdf_path = output_dir / f"{subject_id}_report.pdf"

    if html_path is None:
        # Fallback: try to find the standard HTML report
        possible_html = output_dir / f"{subject_id}_report.html"
        if possible_html.exists():
            html_path = possible_html
        else:
            print("⚠️ HTML report not found for PDF conversion. Generating temporary HTML...")
            # We would need to call save_html_report here, but let's rely on caller
            return None

    return html_to_pdf(html_path, pdf_path)

generate_complete_report(comparison, streamlines_left, streamlines_right, fa_map, affine, output_dir, subject_id, background_image=None, version=None, space='Native Space', metadata=None, fa_path=None, v1_path=None, density_path=None, roi_dseg_path=None, cst_left_path=None, cst_right_path=None)

Generate all report formats: JSON, CSV, and PDF with visualizations.

Parameters:

Name Type Description Default
comparison dict

Bilateral comparison metrics

required
streamlines_left Streamlines

Left CST streamlines

required
streamlines_right Streamlines

Right CST streamlines

required
fa_map ndarray

3D FA map

required
affine ndarray

4x4 affine transformation

required
output_dir str or Path

Output directory

required
subject_id str

Subject identifier

required
background_image ndarray

3D T1 or FA image for tractogram QC background (defaults to fa_map)

None
version str

csttool version string

None
fa_path

path, optional Persisted products for the 1x4 report QC strip, which reads from disk so the figure is reproducible from the products alone. fa_path and the two tractogram paths are the minimum; the rest degrade their own panel. With no fa_path the strip is skipped entirely and the report renders the legacy 1x3 triptych, which is what a caller that has not migrated gets.

None
v1_path

path, optional Persisted products for the 1x4 report QC strip, which reads from disk so the figure is reproducible from the products alone. fa_path and the two tractogram paths are the minimum; the rest degrade their own panel. With no fa_path the strip is skipped entirely and the report renders the legacy 1x3 triptych, which is what a caller that has not migrated gets.

None
density_path

path, optional Persisted products for the 1x4 report QC strip, which reads from disk so the figure is reproducible from the products alone. fa_path and the two tractogram paths are the minimum; the rest degrade their own panel. With no fa_path the strip is skipped entirely and the report renders the legacy 1x3 triptych, which is what a caller that has not migrated gets.

None
roi_dseg_path

path, optional Persisted products for the 1x4 report QC strip, which reads from disk so the figure is reproducible from the products alone. fa_path and the two tractogram paths are the minimum; the rest degrade their own panel. With no fa_path the strip is skipped entirely and the report renders the legacy 1x3 triptych, which is what a caller that has not migrated gets.

None
cst_left_path

path, optional Persisted products for the 1x4 report QC strip, which reads from disk so the figure is reproducible from the products alone. fa_path and the two tractogram paths are the minimum; the rest degrade their own panel. With no fa_path the strip is skipped entirely and the report renders the legacy 1x3 triptych, which is what a caller that has not migrated gets.

None
cst_right_path

path, optional Persisted products for the 1x4 report QC strip, which reads from disk so the figure is reproducible from the products alone. fa_path and the two tractogram paths are the minimum; the rest degrade their own panel. With no fa_path the strip is skipped entirely and the report renders the legacy 1x3 triptych, which is what a caller that has not migrated gets.

None

Returns:

Name Type Description
report_paths dict

Dictionary of all generated report file paths

Source code in src/csttool/metrics/modules/reports.py
def generate_complete_report(
    comparison,
    streamlines_left,
    streamlines_right,
    fa_map,
    affine,
    output_dir,
    subject_id,
    background_image=None,
    version=None,
    space="Native Space",
    metadata=None,
    fa_path=None,
    v1_path=None,
    density_path=None,
    roi_dseg_path=None,
    cst_left_path=None,
    cst_right_path=None,
):
    """
    Generate all report formats: JSON, CSV, and PDF with visualizations.

    Parameters
    ----------
    comparison : dict
        Bilateral comparison metrics
    streamlines_left : Streamlines
        Left CST streamlines
    streamlines_right : Streamlines
        Right CST streamlines
    fa_map : ndarray
        3D FA map
    affine : ndarray
        4x4 affine transformation
    output_dir : str or Path
        Output directory
    subject_id : str
        Subject identifier
    background_image : ndarray, optional
        3D T1 or FA image for tractogram QC background (defaults to fa_map)
    version : str
        csttool version string
    fa_path, v1_path, density_path, roi_dseg_path, cst_left_path, cst_right_path :
        path, optional
        Persisted products for the 1x4 report QC strip, which reads from disk so
        the figure is reproducible from the products alone. ``fa_path`` and the
        two tractogram paths are the minimum; the rest degrade their own panel.
        With no ``fa_path`` the strip is skipped entirely and the report renders
        the legacy 1x3 triptych, which is what a caller that has not migrated
        gets.

    Returns
    -------
    report_paths : dict
        Dictionary of all generated report file paths
    """

    from .visualizations import (
        plot_tract_profiles,
        plot_bilateral_comparison,
        create_summary_figure,
        plot_profile_matrix,
        plot_report_qc_strip,
        plot_tractogram_qc_triptych,
    )
    from csttool.viz import style as _style
    _style.apply_house_style()  # shared typography/spines/DPI for metrics figures

    # Use package version if not specified
    if version is None:
        version = __version__

    output_dir = Path(output_dir)
    viz_dir = output_dir / "visualizations"
    viz_dir.mkdir(parents=True, exist_ok=True)

    print("\nGenerating complete report package...")

    # Use FA map as background if no background image provided
    if background_image is None:
        background_image = fa_map

    # Generate the two composite figures used by the one-page PDF report.
    # The FA map is the QC background by default, so the grayscale FA colorbar is
    # scientifically valid (background_kind="fa").
    pdf_viz_paths = {
        'profile_matrix': plot_profile_matrix(
            comparison['left'], comparison['right'], viz_dir, subject_id
        ),
    }

    # The 1x4 strip replaces the triptych in the report. It reads persisted
    # products, so it needs paths rather than the in-memory arrays; a caller that
    # supplies none falls back to the triptych rather than losing the QC figure.
    if fa_path is not None:
        pdf_viz_paths['qc_strip'] = plot_report_qc_strip(
            fa_path=fa_path,
            v1_path=v1_path,
            density_path=density_path,
            roi_dseg_path=roi_dseg_path,
            cst_left_path=cst_left_path,
            cst_right_path=cst_right_path,
            output_dir=viz_dir,
            subject_id=subject_id,
        )
    else:
        pdf_viz_paths['tractogram_qc_triptych'] = plot_tractogram_qc_triptych(
            streamlines_left,
            streamlines_right,
            background_image,
            affine,
            viz_dir,
            subject_id,
            background_kind=("fa" if background_image is fa_map else "other"),
        )

    # Also generate individual plots for detailed analysis
    viz_paths = {}

    if 'fa' in comparison['left']:
        viz_paths['tract_profiles_fa'] = plot_tract_profiles(
            comparison['left'],
            comparison['right'],
            viz_dir,
            subject_id,
            scalar='fa'
        )

    if 'md' in comparison['left']:
        viz_paths['tract_profiles_md'] = plot_tract_profiles(
            comparison['left'],
            comparison['right'],
            viz_dir,
            subject_id,
            scalar='md'
        )

    viz_paths['bilateral_comparison'] = plot_bilateral_comparison(
        comparison,
        viz_dir,
        subject_id
    )

    viz_paths['summary'] = create_summary_figure(
        comparison,
        streamlines_left,
        streamlines_right,
        fa_map,
        affine,
        viz_dir,
        subject_id
    )

    # Merge all visualization paths
    viz_paths.update(pdf_viz_paths)

    # Generate reports
    # 1. HTML Report (critical as PDF is derived from it); pass the FA affine so
    #    the orientation code is computed dynamically.
    html_path = save_html_report(
        comparison, pdf_viz_paths, output_dir, subject_id, version, space,
        metadata, fa_affine=affine,
    )

    # 2. PDF Report (from HTML)
    pdf_path = save_pdf_report(comparison, pdf_viz_paths, output_dir, subject_id, version, space, html_path)

    report_paths = {
        'json': save_json_report(comparison, output_dir, subject_id, metadata=metadata),
        'csv': save_csv_summary(comparison, output_dir, subject_id),
        'html': html_path,
        'pdf': pdf_path,
        'visualizations': viz_paths
    }

    print("\n  ✓ Complete report package generated")
    return report_paths