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
|
Source code in src/csttool/metrics/modules/unilateral_analysis.py
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; |
Source code in src/csttool/metrics/modules/unilateral_analysis.py
223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 | |
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
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
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
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
|
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
415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 | |
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
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
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
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 | |
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
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
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
83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 | |
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
1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 | |
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
1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 | |
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
2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 | |
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
178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 | |
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_REGIONSintervals 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/Aplaceholder 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
663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 | |
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:
- does the local diffusion field support the expected CST orientation?
- is the reconstructed bundle spatially coherent?
- were the intended anatomical constraints applied?
- 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 |
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 |
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 |
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: |
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 | |
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
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
|
|
None
|
slice_indices
|
dict
|
|
None
|
Source code in src/csttool/metrics/modules/visualizations.py
1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 | |
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
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
628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 | |
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: |
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 |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
html_path |
Path
|
Path to saved HTML file |
Source code in src/csttool/metrics/modules/reports.py
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
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. |
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. |
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. |
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. |
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. |
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. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
report_paths |
dict
|
Dictionary of all generated report file paths |
Source code in src/csttool/metrics/modules/reports.py
924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 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 | |