lesiontrack 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Cedric Conday
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,256 @@
1
+ Metadata-Version: 2.4
2
+ Name: lesiontrack
3
+ Version: 0.1.0
4
+ Summary: Longitudinal multiple sclerosis lesion evolution: lesion tracking and slowly expanding lesion (SEL) detection with a synthetic backtest gate.
5
+ Author: Cedric Conday
6
+ License: MIT
7
+ Keywords: multiple sclerosis,MRI,lesion,longitudinal,slowly expanding lesions,neuroimaging
8
+ Classifier: Intended Audience :: Science/Research
9
+ Classifier: License :: OSI Approved :: MIT License
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Topic :: Scientific/Engineering :: Medical Science Apps.
12
+ Requires-Python: >=3.10
13
+ Description-Content-Type: text/markdown
14
+ License-File: LICENSE
15
+ Requires-Dist: numpy>=1.24
16
+ Requires-Dist: scipy>=1.10
17
+ Requires-Dist: nibabel>=5
18
+ Requires-Dist: pandas>=2
19
+ Requires-Dist: scikit-image>=0.21
20
+ Requires-Dist: picsl_greedy>=1.4
21
+ Requires-Dist: matplotlib>=3.7
22
+ Provides-Extra: dev
23
+ Requires-Dist: pytest; extra == "dev"
24
+ Requires-Dist: ruff; extra == "dev"
25
+ Dynamic: license-file
26
+
27
+ # lesiontrack
28
+
29
+ Longitudinal multiple sclerosis lesion evolution from two or more MRI timepoints:
30
+ which lesions are new, enlarging, shrinking, stable or resolved, and which are
31
+ **slowly expanding lesions (SELs)** by the Jacobian definition of Elliott et al. 2019,
32
+ with a **synthetic backtest gate** that has to pass before a real number is reported.
33
+
34
+ > **Nothing in this repository is evidence about multiple sclerosis.** It is research
35
+ > software. It is not a medical device, it has not been validated against histology or
36
+ > clinical outcome, and it makes no diagnostic claim.
37
+
38
+ ## Why this exists
39
+
40
+ Every MS clinic that pays for follow-up MRI analysis gets lesion-level change and, in
41
+ trials, SEL counts. In the open there was one SEL implementation, bound to a GUI, needing
42
+ FreeSurfer and ANTs, taking hours per subject and carrying its authors' own warning not
43
+ to use it. There is no public SEL ground truth, and the field's thresholds were set by
44
+ visual assessment. This package is the missing open engine, and the backtest is the
45
+ missing check.
46
+
47
+ * one dependency for registration: [greedy](https://github.com/pyushkevich/greedy),
48
+ installed as a wheel, x86-64 and arm64, CPU only
49
+ * minutes per subject pair, not hours
50
+ * every threshold in one file with its citation (`lesiontrack/config.py`)
51
+ * every output a plain NIfTI or TSV, on the baseline grid, ready for any viewer
52
+
53
+ ## Method
54
+
55
+ 1. **Halfway space.** Rigid registration of the follow-up T1w to the baseline T1w, then
56
+ the square root of that transform moves both scans into an unbiased midpoint space
57
+ (Nakamura et al.; Elliott et al. 2019).
58
+ 2. **Deformable registration** driven by T1w and FLAIR jointly (normalised cross
59
+ correlation, step 0.7, update smoothing 2 voxels), baseline fixed, follow-up moving.
60
+ 3. **Jacobian determinant** of the deformation field, converted to local percent volume
61
+ change per year: `(det J - 1) * 100 / years`.
62
+ 4. **SEL candidates** (Elliott 2019): voxels inside baseline lesions expanding at
63
+ >= 12.5 %/year seed 18-connected components; each seed grows by hysteresis into
64
+ neighbours expanding at >= 4 %/year, competing so distinct expansions stay distinct
65
+ (marker watershed on the expansion map); candidates under 10 voxels are dropped.
66
+ 5. **Scores** (Elliott 2019 as described by Vanden Bulcke et al. 2025): *concentricity*
67
+ is the robust slope of mean expansion per 1-voxel shell against depth from the
68
+ candidate edge; *constancy* is the normalised residual of a robust linear fit of
69
+ expansion over the intermediate timepoints (needs three or more scans). Both are
70
+ z-scored across the cohort; `S = z(concentricity) - z(constancy)`; `S >= 0` is a
71
+ definite SEL. Because the z-scores are cohort-relative, the definite/possible split
72
+ is a ranking within your cohort, not an absolute threshold; raw values are kept.
73
+ Candidates with no interior voxel have no concentricity and are marked unscorable.
74
+ 6. **Lesion tracking** from the binary masks: connected components at baseline and
75
+ follow-up are matched on the bipartite overlap graph, so merges and splits are
76
+ explicit. Volume change is annualised and classified as enlarging or shrinking beyond
77
+ +/-9 %/year, stable within +/-4 %/year, and trend_up / trend_down between (bands of
78
+ Vanden Bulcke et al. 2025). A follow-up component with no baseline overlap is *new* if
79
+ it clears the 1-voxel-dilated baseline mask and *adjacent_fragment* if it touches it;
80
+ a baseline component with no follow-up overlap is *resolved*.
81
+
82
+ ## The backtest gate
83
+
84
+ `lesiontrack backtest` takes a real baseline (T1w, FLAIR, lesion mask), picks lesions,
85
+ expands each by a known volume factor (1.15, 1.25, 1.40) with a smooth radial
86
+ deformation, perturbs the whole head rigidly, rescales intensities and adds noise, then
87
+ runs the full pipeline on the pair and reports:
88
+
89
+ * sensitivity: expanded lesions that receive a SEL candidate
90
+ * false positive rate: untouched lesions that receive one
91
+ * recovery fraction: robust slope of measured against true expansion (1.0 = exact)
92
+ * the noise floor inside untouched lesions and, per candidate, how well its mean rate
93
+ separates injected from spurious candidates
94
+
95
+ It is the only place the pipeline is checked against a known answer. Run it on your own
96
+ data before trusting a count. The numbers for MSLesSeg are in the section below.
97
+
98
+ ## Install
99
+
100
+ ```bash
101
+ pip install lesiontrack # once released; until then:
102
+ pip install git+https://github.com/CedricConday/lesiontrack
103
+ ```
104
+
105
+ Python 3.10+. Wheels for greedy exist for Linux x86-64 and arm64 and macOS.
106
+
107
+ ## Use
108
+
109
+ Write a tab-separated manifest, one row per scan, paths relative to the manifest:
110
+
111
+ ```
112
+ subject session time_years t1 flair mask brainmask
113
+ P1 T1 28.09 P1/T1/T1.nii.gz P1/T1/FLAIR.nii.gz P1/T1/MASK.nii.gz P1/T1/brain.nii.gz
114
+ P1 T2 28.51 P1/T2/T1.nii.gz P1/T2/FLAIR.nii.gz P1/T2/MASK.nii.gz
115
+ P1 T3 29.49 P1/T3/T1.nii.gz P1/T3/FLAIR.nii.gz P1/T3/MASK.nii.gz
116
+ ```
117
+
118
+ `time_years` is any consistent clock (age, or years since baseline). Masks come from
119
+ whatever segmenter you trust (LST-AI, SAMSEG, nnU-Net, manual); the brain mask is
120
+ optional and only restricts the registration metric.
121
+
122
+ ```bash
123
+ lesiontrack run manifest.tsv --out derivatives # every subject
124
+ lesiontrack run manifest.tsv --out derivatives --subject P1
125
+ lesiontrack cohort --out derivatives # z-scores and S across subjects
126
+ lesiontrack backtest --t1 T1.nii.gz --flair FLAIR.nii.gz --mask MASK.nii.gz --out backtest
127
+ ```
128
+
129
+ Per subject you get, on the baseline grid in halfway space:
130
+
131
+ | file | content |
132
+ |---|---|
133
+ | `expansion_<tp>_pct_per_year.nii.gz` | Jacobian-derived local volume change |
134
+ | `sel_candidates.nii.gz`, `sel_candidates.tsv` | candidate labels; size, peak and mean expansion, concentricity, constancy |
135
+ | `baseline_lesion_labels.nii.gz`, `lesion_labels_<tp>.nii.gz` | lesion components |
136
+ | `lesion_tracking.tsv` | one row per matched group with class, volumes, rate, merge/split flags |
137
+ | `new_or_enlarging_<tp>.nii.gz` | follow-up lesion voxels outside the dilated baseline |
138
+ | `overview_<tp>.png` | four axial slices: baseline, warped follow-up, expansion with SEL outlines |
139
+ | `summary.json` | counts, volumes, intervals, every parameter used |
140
+
141
+ `lesiontrack cohort` adds `sel_cohort.tsv` with `z_concentricity`, `z_constancy`,
142
+ `score_S` and `definite_sel`.
143
+
144
+ ## Results on public data
145
+
146
+ ### Backtest on MSLesSeg patient P1 (2026-09-26)
147
+
148
+ Three synthetic series (seeds 0, 1, 2), each with scans at 0, 0.5 and 1 year, eight of
149
+ eighteen lesions expanded by nominal factors 1.15 / 1.25 / 1.40 (analytic mean inside the
150
+ lesion 11 to 25 % because elongated lesions extend past the radial window), rigid
151
+ perturbation about 1 degree and 1 voxel per scan, intensity rescale 0.9 to 1.1, 2 % noise.
152
+ Default registration (greedy stationary-velocity, NCC 3x3x3, halfway space).
153
+
154
+ | quantity | value |
155
+ |---|---|
156
+ | recovery fraction (measured / true, robust slope) | **0.29** |
157
+ | recovery by lesion size: >= 500 / 100-500 / < 100 voxels | 0.57 / 0.27 / 0.29 |
158
+ | candidate sensitivity, Elliott thresholds | 0.88 |
159
+ | candidate false positive rate, Elliott thresholds | 0.47 (1.00 on untouched lesions >= 500 voxels) |
160
+ | definite SEL (S >= 0, z-scored within the run, so about half by construction): sensitivity / FPR | 0.42 / 0.30 |
161
+ | noise floor: 95th percentile of per-voxel expansion in untouched lesions | 5 to 10 %/yr |
162
+ | candidate mean expansion as a classifier, AUC | 0.91 to 0.96 |
163
+
164
+ Three conclusions the tool would not have earned without the gate:
165
+
166
+ 1. **The Jacobian under-reports by about 3x** on sub-voxel boundary shifts at 1 mm, and
167
+ more so for small lesions. SEL rates from any pipeline of this kind are lower bounds.
168
+ 2. **Elliott's candidate rule is noise-limited on confluent lesions.** A one-voxel peak
169
+ over 12.5 %/yr, grown by hysteresis to 4 %/yr, makes a 10-voxel candidate; large
170
+ lesions contain enough voxels to produce one by chance. Concentricity and constancy,
171
+ the published filters, were at chance here (AUC 0.54 and 0.40).
172
+ 3. **The candidate's mean rate is the filter that works** (AUC 0.90). It is exposed as
173
+ `min_mean_pct_per_year`, off by default. Trade-off on this registration (mean over
174
+ the three seeds):
175
+
176
+ | min mean (%/yr) | sensitivity | false positive rate |
177
+ |---|---|---|
178
+ | 0 (Elliott) | 0.88 | 0.47 |
179
+ | 8 | 0.67 | 0.10 |
180
+ | 10 | 0.38 | 0.00 |
181
+
182
+ Full record with the registration sweep: `docs/BACKTEST_NOTES.md`.
183
+
184
+ ### MSLesSeg cohort (24 patients, 2026-09-26)
185
+
186
+ All longitudinal MSLesSeg patients, baseline against their last scan (median interval
187
+ 1.5 years, range 0.16 to 6.0), default settings. One patient (P49) was refused by the
188
+ input gate: its follow-up T1 in the released dataset has 0.1 % nonzero voxels.
189
+
190
+ **Lesion tracking, all subjects, last follow-up** (baseline lesions 573, matched groups):
191
+ new 216, resolved 250, enlarging 127, shrinking 115, stable 36, trend 45. That churn is
192
+ real signal, not just segmentation noise: voxels the masks call new go from FLAIR z 0.73
193
+ at baseline to 1.49 at follow-up and only 6 % were already lesion-bright; resolved voxels
194
+ go from 1.45 to 0.87. But masks are segmented per timepoint in MSLesSeg, so "new" and
195
+ "resolved" also carry every difference between two segmentations.
196
+
197
+ **SEL candidates.** 530 candidates in 24 subjects, median 15 per subject (12.5 with mean
198
+ >= 8 %/yr); the literature reports about 2 to 4 SELs per patient over two years. On this
199
+ registration the Elliott rule is noise-dominated on real data as it was on the backtest.
200
+
201
+ **The Jacobian does not see what the masks see.** Per subject, mask-based total lesion
202
+ volume change and the Jacobian integrated over baseline lesions correlate at Spearman 0.10
203
+ (median magnitudes 21 % and 6 %). Per 1:1 matched lesion (n = 276) the correlation is 0.09;
204
+ 0.18 for lesions over 100 voxels. The largest mask growers (+100 to +680 %) have Jacobian
205
+ means near zero. A candidate is no more likely on a mask-enlarging lesion (42 %) than on a
206
+ shrinking one (45 %).
207
+
208
+ Read together with the backtest, the picture is consistent: a 1 mm deformable registration
209
+ recovers a fraction of true tissue displacement, and lesion growth that arrives as a change
210
+ of intensity at the boundary rather than as displacement is largely invisible to it. Whether
211
+ a stronger registration (ANTs SyN as in the original studies, or multi-resolution around
212
+ lesions) changes this is exactly the question the backtest lets anyone answer for their own
213
+ pipeline: inject, run, report recovery fraction and noise floor. We would like to see those
214
+ numbers for the pipelines behind published SEL counts.
215
+
216
+ Cohort tables: `derivatives/mslesseg/cohort_summary.tsv`, `sel_cohort.tsv`,
217
+ `check_volume_change_by_lesion.tsv`, `check_flair_consistency.tsv`
218
+ (`scripts/summarize_cohort.py`, `scripts/cohort_checks.py`).
219
+
220
+ ## Data used
221
+
222
+ * **MSLesSeg** (Guarnera et al. 2025, Sci Data 12:920, CC BY): 25 patients with 2 to 4
223
+ timepoints, already in MNI152 1 mm space with a lesion mask per timepoint.
224
+ `scripts/make_manifest_mslesseg.py` builds the manifest; intervals are age differences.
225
+ * **Lesjak et al. 2016** longitudinal database (CC BY): 20 patients, 2 timepoints, expert
226
+ masks of lesion change. Not yet used; it lacks baseline lesion masks.
227
+
228
+ ## Limitations, stated plainly
229
+
230
+ * The Jacobian sees any local volume change, including registration error at lesion
231
+ edges, atrophy, and interpolation. The backtest measures the pipeline's own noise floor
232
+ on untouched lesions; report it with your SEL counts.
233
+ * Two-timepoint studies cannot score constancy; S then rests on concentricity alone and
234
+ is labelled so.
235
+ * Thresholds are Elliott's, set by eye in 2019 on 3D scans resampled to 1x1x3 mm. Vanden
236
+ Bulcke et al. 2025 found only weak lesion-level agreement (Dice about 0.4) between SEL
237
+ masks from different segmenters or resolutions. Subject-level counts were stable;
238
+ lesion-level identity was not. Expect the same here.
239
+ * Masks are taken as given. A segmenter that hallucinates at follow-up will produce
240
+ "new" lesions; the tool does not second-guess it.
241
+
242
+ ## References
243
+
244
+ * Elliott C, et al. Slowly expanding/evolving lesions as a magnetic resonance imaging
245
+ marker of chronic active multiple sclerosis lesions. Mult Scler 2019;25:1915-1925.
246
+ * Vanden Bulcke C, et al. Do slowly expanding lesions correspond to chronic active
247
+ multiple sclerosis lesions? An integrated imaging analysis study. medRxiv 2025,
248
+ doi:10.64898/2025.12.03.25341192.
249
+ * Guarnera F, et al. MSLesSeg: baseline and benchmarking of a new Multiple Sclerosis
250
+ Lesion Segmentation dataset. Sci Data 2025;12:920.
251
+ * Yushkevich PA, et al. Fast automatic segmentation of hippocampal subfields and medial
252
+ temporal lobe subregions in 3 Tesla and 7 Tesla T2-weighted MRI (greedy). 2016.
253
+
254
+ ## License
255
+
256
+ MIT. Written by Cedric Conday with Claude (Anthropic) as coding partner.
@@ -0,0 +1,230 @@
1
+ # lesiontrack
2
+
3
+ Longitudinal multiple sclerosis lesion evolution from two or more MRI timepoints:
4
+ which lesions are new, enlarging, shrinking, stable or resolved, and which are
5
+ **slowly expanding lesions (SELs)** by the Jacobian definition of Elliott et al. 2019,
6
+ with a **synthetic backtest gate** that has to pass before a real number is reported.
7
+
8
+ > **Nothing in this repository is evidence about multiple sclerosis.** It is research
9
+ > software. It is not a medical device, it has not been validated against histology or
10
+ > clinical outcome, and it makes no diagnostic claim.
11
+
12
+ ## Why this exists
13
+
14
+ Every MS clinic that pays for follow-up MRI analysis gets lesion-level change and, in
15
+ trials, SEL counts. In the open there was one SEL implementation, bound to a GUI, needing
16
+ FreeSurfer and ANTs, taking hours per subject and carrying its authors' own warning not
17
+ to use it. There is no public SEL ground truth, and the field's thresholds were set by
18
+ visual assessment. This package is the missing open engine, and the backtest is the
19
+ missing check.
20
+
21
+ * one dependency for registration: [greedy](https://github.com/pyushkevich/greedy),
22
+ installed as a wheel, x86-64 and arm64, CPU only
23
+ * minutes per subject pair, not hours
24
+ * every threshold in one file with its citation (`lesiontrack/config.py`)
25
+ * every output a plain NIfTI or TSV, on the baseline grid, ready for any viewer
26
+
27
+ ## Method
28
+
29
+ 1. **Halfway space.** Rigid registration of the follow-up T1w to the baseline T1w, then
30
+ the square root of that transform moves both scans into an unbiased midpoint space
31
+ (Nakamura et al.; Elliott et al. 2019).
32
+ 2. **Deformable registration** driven by T1w and FLAIR jointly (normalised cross
33
+ correlation, step 0.7, update smoothing 2 voxels), baseline fixed, follow-up moving.
34
+ 3. **Jacobian determinant** of the deformation field, converted to local percent volume
35
+ change per year: `(det J - 1) * 100 / years`.
36
+ 4. **SEL candidates** (Elliott 2019): voxels inside baseline lesions expanding at
37
+ >= 12.5 %/year seed 18-connected components; each seed grows by hysteresis into
38
+ neighbours expanding at >= 4 %/year, competing so distinct expansions stay distinct
39
+ (marker watershed on the expansion map); candidates under 10 voxels are dropped.
40
+ 5. **Scores** (Elliott 2019 as described by Vanden Bulcke et al. 2025): *concentricity*
41
+ is the robust slope of mean expansion per 1-voxel shell against depth from the
42
+ candidate edge; *constancy* is the normalised residual of a robust linear fit of
43
+ expansion over the intermediate timepoints (needs three or more scans). Both are
44
+ z-scored across the cohort; `S = z(concentricity) - z(constancy)`; `S >= 0` is a
45
+ definite SEL. Because the z-scores are cohort-relative, the definite/possible split
46
+ is a ranking within your cohort, not an absolute threshold; raw values are kept.
47
+ Candidates with no interior voxel have no concentricity and are marked unscorable.
48
+ 6. **Lesion tracking** from the binary masks: connected components at baseline and
49
+ follow-up are matched on the bipartite overlap graph, so merges and splits are
50
+ explicit. Volume change is annualised and classified as enlarging or shrinking beyond
51
+ +/-9 %/year, stable within +/-4 %/year, and trend_up / trend_down between (bands of
52
+ Vanden Bulcke et al. 2025). A follow-up component with no baseline overlap is *new* if
53
+ it clears the 1-voxel-dilated baseline mask and *adjacent_fragment* if it touches it;
54
+ a baseline component with no follow-up overlap is *resolved*.
55
+
56
+ ## The backtest gate
57
+
58
+ `lesiontrack backtest` takes a real baseline (T1w, FLAIR, lesion mask), picks lesions,
59
+ expands each by a known volume factor (1.15, 1.25, 1.40) with a smooth radial
60
+ deformation, perturbs the whole head rigidly, rescales intensities and adds noise, then
61
+ runs the full pipeline on the pair and reports:
62
+
63
+ * sensitivity: expanded lesions that receive a SEL candidate
64
+ * false positive rate: untouched lesions that receive one
65
+ * recovery fraction: robust slope of measured against true expansion (1.0 = exact)
66
+ * the noise floor inside untouched lesions and, per candidate, how well its mean rate
67
+ separates injected from spurious candidates
68
+
69
+ It is the only place the pipeline is checked against a known answer. Run it on your own
70
+ data before trusting a count. The numbers for MSLesSeg are in the section below.
71
+
72
+ ## Install
73
+
74
+ ```bash
75
+ pip install lesiontrack # once released; until then:
76
+ pip install git+https://github.com/CedricConday/lesiontrack
77
+ ```
78
+
79
+ Python 3.10+. Wheels for greedy exist for Linux x86-64 and arm64 and macOS.
80
+
81
+ ## Use
82
+
83
+ Write a tab-separated manifest, one row per scan, paths relative to the manifest:
84
+
85
+ ```
86
+ subject session time_years t1 flair mask brainmask
87
+ P1 T1 28.09 P1/T1/T1.nii.gz P1/T1/FLAIR.nii.gz P1/T1/MASK.nii.gz P1/T1/brain.nii.gz
88
+ P1 T2 28.51 P1/T2/T1.nii.gz P1/T2/FLAIR.nii.gz P1/T2/MASK.nii.gz
89
+ P1 T3 29.49 P1/T3/T1.nii.gz P1/T3/FLAIR.nii.gz P1/T3/MASK.nii.gz
90
+ ```
91
+
92
+ `time_years` is any consistent clock (age, or years since baseline). Masks come from
93
+ whatever segmenter you trust (LST-AI, SAMSEG, nnU-Net, manual); the brain mask is
94
+ optional and only restricts the registration metric.
95
+
96
+ ```bash
97
+ lesiontrack run manifest.tsv --out derivatives # every subject
98
+ lesiontrack run manifest.tsv --out derivatives --subject P1
99
+ lesiontrack cohort --out derivatives # z-scores and S across subjects
100
+ lesiontrack backtest --t1 T1.nii.gz --flair FLAIR.nii.gz --mask MASK.nii.gz --out backtest
101
+ ```
102
+
103
+ Per subject you get, on the baseline grid in halfway space:
104
+
105
+ | file | content |
106
+ |---|---|
107
+ | `expansion_<tp>_pct_per_year.nii.gz` | Jacobian-derived local volume change |
108
+ | `sel_candidates.nii.gz`, `sel_candidates.tsv` | candidate labels; size, peak and mean expansion, concentricity, constancy |
109
+ | `baseline_lesion_labels.nii.gz`, `lesion_labels_<tp>.nii.gz` | lesion components |
110
+ | `lesion_tracking.tsv` | one row per matched group with class, volumes, rate, merge/split flags |
111
+ | `new_or_enlarging_<tp>.nii.gz` | follow-up lesion voxels outside the dilated baseline |
112
+ | `overview_<tp>.png` | four axial slices: baseline, warped follow-up, expansion with SEL outlines |
113
+ | `summary.json` | counts, volumes, intervals, every parameter used |
114
+
115
+ `lesiontrack cohort` adds `sel_cohort.tsv` with `z_concentricity`, `z_constancy`,
116
+ `score_S` and `definite_sel`.
117
+
118
+ ## Results on public data
119
+
120
+ ### Backtest on MSLesSeg patient P1 (2026-09-26)
121
+
122
+ Three synthetic series (seeds 0, 1, 2), each with scans at 0, 0.5 and 1 year, eight of
123
+ eighteen lesions expanded by nominal factors 1.15 / 1.25 / 1.40 (analytic mean inside the
124
+ lesion 11 to 25 % because elongated lesions extend past the radial window), rigid
125
+ perturbation about 1 degree and 1 voxel per scan, intensity rescale 0.9 to 1.1, 2 % noise.
126
+ Default registration (greedy stationary-velocity, NCC 3x3x3, halfway space).
127
+
128
+ | quantity | value |
129
+ |---|---|
130
+ | recovery fraction (measured / true, robust slope) | **0.29** |
131
+ | recovery by lesion size: >= 500 / 100-500 / < 100 voxels | 0.57 / 0.27 / 0.29 |
132
+ | candidate sensitivity, Elliott thresholds | 0.88 |
133
+ | candidate false positive rate, Elliott thresholds | 0.47 (1.00 on untouched lesions >= 500 voxels) |
134
+ | definite SEL (S >= 0, z-scored within the run, so about half by construction): sensitivity / FPR | 0.42 / 0.30 |
135
+ | noise floor: 95th percentile of per-voxel expansion in untouched lesions | 5 to 10 %/yr |
136
+ | candidate mean expansion as a classifier, AUC | 0.91 to 0.96 |
137
+
138
+ Three conclusions the tool would not have earned without the gate:
139
+
140
+ 1. **The Jacobian under-reports by about 3x** on sub-voxel boundary shifts at 1 mm, and
141
+ more so for small lesions. SEL rates from any pipeline of this kind are lower bounds.
142
+ 2. **Elliott's candidate rule is noise-limited on confluent lesions.** A one-voxel peak
143
+ over 12.5 %/yr, grown by hysteresis to 4 %/yr, makes a 10-voxel candidate; large
144
+ lesions contain enough voxels to produce one by chance. Concentricity and constancy,
145
+ the published filters, were at chance here (AUC 0.54 and 0.40).
146
+ 3. **The candidate's mean rate is the filter that works** (AUC 0.90). It is exposed as
147
+ `min_mean_pct_per_year`, off by default. Trade-off on this registration (mean over
148
+ the three seeds):
149
+
150
+ | min mean (%/yr) | sensitivity | false positive rate |
151
+ |---|---|---|
152
+ | 0 (Elliott) | 0.88 | 0.47 |
153
+ | 8 | 0.67 | 0.10 |
154
+ | 10 | 0.38 | 0.00 |
155
+
156
+ Full record with the registration sweep: `docs/BACKTEST_NOTES.md`.
157
+
158
+ ### MSLesSeg cohort (24 patients, 2026-09-26)
159
+
160
+ All longitudinal MSLesSeg patients, baseline against their last scan (median interval
161
+ 1.5 years, range 0.16 to 6.0), default settings. One patient (P49) was refused by the
162
+ input gate: its follow-up T1 in the released dataset has 0.1 % nonzero voxels.
163
+
164
+ **Lesion tracking, all subjects, last follow-up** (baseline lesions 573, matched groups):
165
+ new 216, resolved 250, enlarging 127, shrinking 115, stable 36, trend 45. That churn is
166
+ real signal, not just segmentation noise: voxels the masks call new go from FLAIR z 0.73
167
+ at baseline to 1.49 at follow-up and only 6 % were already lesion-bright; resolved voxels
168
+ go from 1.45 to 0.87. But masks are segmented per timepoint in MSLesSeg, so "new" and
169
+ "resolved" also carry every difference between two segmentations.
170
+
171
+ **SEL candidates.** 530 candidates in 24 subjects, median 15 per subject (12.5 with mean
172
+ >= 8 %/yr); the literature reports about 2 to 4 SELs per patient over two years. On this
173
+ registration the Elliott rule is noise-dominated on real data as it was on the backtest.
174
+
175
+ **The Jacobian does not see what the masks see.** Per subject, mask-based total lesion
176
+ volume change and the Jacobian integrated over baseline lesions correlate at Spearman 0.10
177
+ (median magnitudes 21 % and 6 %). Per 1:1 matched lesion (n = 276) the correlation is 0.09;
178
+ 0.18 for lesions over 100 voxels. The largest mask growers (+100 to +680 %) have Jacobian
179
+ means near zero. A candidate is no more likely on a mask-enlarging lesion (42 %) than on a
180
+ shrinking one (45 %).
181
+
182
+ Read together with the backtest, the picture is consistent: a 1 mm deformable registration
183
+ recovers a fraction of true tissue displacement, and lesion growth that arrives as a change
184
+ of intensity at the boundary rather than as displacement is largely invisible to it. Whether
185
+ a stronger registration (ANTs SyN as in the original studies, or multi-resolution around
186
+ lesions) changes this is exactly the question the backtest lets anyone answer for their own
187
+ pipeline: inject, run, report recovery fraction and noise floor. We would like to see those
188
+ numbers for the pipelines behind published SEL counts.
189
+
190
+ Cohort tables: `derivatives/mslesseg/cohort_summary.tsv`, `sel_cohort.tsv`,
191
+ `check_volume_change_by_lesion.tsv`, `check_flair_consistency.tsv`
192
+ (`scripts/summarize_cohort.py`, `scripts/cohort_checks.py`).
193
+
194
+ ## Data used
195
+
196
+ * **MSLesSeg** (Guarnera et al. 2025, Sci Data 12:920, CC BY): 25 patients with 2 to 4
197
+ timepoints, already in MNI152 1 mm space with a lesion mask per timepoint.
198
+ `scripts/make_manifest_mslesseg.py` builds the manifest; intervals are age differences.
199
+ * **Lesjak et al. 2016** longitudinal database (CC BY): 20 patients, 2 timepoints, expert
200
+ masks of lesion change. Not yet used; it lacks baseline lesion masks.
201
+
202
+ ## Limitations, stated plainly
203
+
204
+ * The Jacobian sees any local volume change, including registration error at lesion
205
+ edges, atrophy, and interpolation. The backtest measures the pipeline's own noise floor
206
+ on untouched lesions; report it with your SEL counts.
207
+ * Two-timepoint studies cannot score constancy; S then rests on concentricity alone and
208
+ is labelled so.
209
+ * Thresholds are Elliott's, set by eye in 2019 on 3D scans resampled to 1x1x3 mm. Vanden
210
+ Bulcke et al. 2025 found only weak lesion-level agreement (Dice about 0.4) between SEL
211
+ masks from different segmenters or resolutions. Subject-level counts were stable;
212
+ lesion-level identity was not. Expect the same here.
213
+ * Masks are taken as given. A segmenter that hallucinates at follow-up will produce
214
+ "new" lesions; the tool does not second-guess it.
215
+
216
+ ## References
217
+
218
+ * Elliott C, et al. Slowly expanding/evolving lesions as a magnetic resonance imaging
219
+ marker of chronic active multiple sclerosis lesions. Mult Scler 2019;25:1915-1925.
220
+ * Vanden Bulcke C, et al. Do slowly expanding lesions correspond to chronic active
221
+ multiple sclerosis lesions? An integrated imaging analysis study. medRxiv 2025,
222
+ doi:10.64898/2025.12.03.25341192.
223
+ * Guarnera F, et al. MSLesSeg: baseline and benchmarking of a new Multiple Sclerosis
224
+ Lesion Segmentation dataset. Sci Data 2025;12:920.
225
+ * Yushkevich PA, et al. Fast automatic segmentation of hippocampal subfields and medial
226
+ temporal lobe subregions in 3 Tesla and 7 Tesla T2-weighted MRI (greedy). 2016.
227
+
228
+ ## License
229
+
230
+ MIT. Written by Cedric Conday with Claude (Anthropic) as coding partner.
@@ -0,0 +1,7 @@
1
+ """lesiontrack: longitudinal MS lesion evolution and slowly expanding lesion detection.
2
+
3
+ Nothing in this package is evidence about multiple sclerosis. It is research
4
+ software; it is not a medical device and makes no diagnostic claim.
5
+ """
6
+
7
+ __version__ = "0.1.0"
@@ -0,0 +1,93 @@
1
+ """SEL candidates: contiguous expanding regions inside pre-existing T2 lesions.
2
+
3
+ Elliott et al. 2019, "SEL candidates":
4
+ 1. voxels inside baseline lesions with expansion >= JE1 (12.5 %/year);
5
+ 2. 18-connected components of those voxels seed the candidates;
6
+ 3. each seed grows into neighbouring voxels with expansion >= JE2 (4 %/year),
7
+ competing so that distinct expansions stay distinct even when connected;
8
+ 4. candidates under 10 voxels are discarded.
9
+
10
+ Step 3 is implemented as a marker-based watershed on the negated expansion
11
+ map, restricted to the JE2 region: each JE2 voxel joins the seed it is
12
+ reached from first along the steepest expansion path.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import numpy as np
18
+ import pandas as pd
19
+ from scipy import ndimage as ndi
20
+ from skimage.segmentation import watershed
21
+
22
+ from .config import SELParams
23
+
24
+
25
+ def structure(connectivity: int) -> np.ndarray:
26
+ return ndi.generate_binary_structure(3, connectivity)
27
+
28
+
29
+ def sel_candidates(expansion_pct_per_year: np.ndarray, lesion_mask: np.ndarray,
30
+ params: SELParams | None = None) -> np.ndarray:
31
+ """Label map of SEL candidates (0 = background), consecutively numbered."""
32
+ params = params or SELParams()
33
+ exp = np.asarray(expansion_pct_per_year, dtype=np.float32)
34
+ mask = np.asarray(lesion_mask) > 0
35
+ if exp.shape != mask.shape:
36
+ raise ValueError(f"shape mismatch {exp.shape} vs {mask.shape}")
37
+ st = structure(params.connectivity)
38
+
39
+ seeds = mask & (exp >= params.je1_pct_per_year)
40
+ seed_labels, n_seeds = ndi.label(seeds, structure=st)
41
+ if n_seeds == 0:
42
+ return np.zeros(mask.shape, dtype=np.int32)
43
+
44
+ grow = mask & (exp >= params.je2_pct_per_year)
45
+ labels = watershed(-exp, markers=seed_labels, mask=grow, connectivity=st)
46
+
47
+ # Reliability criterion: drop small candidates, then renumber consecutively.
48
+ counts = np.bincount(labels.ravel())
49
+ keep = np.flatnonzero(counts >= params.min_voxels)
50
+ keep = keep[keep != 0]
51
+ if params.min_mean_pct_per_year > 0 and keep.size:
52
+ sums = np.bincount(labels.ravel(), weights=exp.ravel(), minlength=counts.size)
53
+ means = sums[keep] / counts[keep]
54
+ keep = keep[means >= params.min_mean_pct_per_year]
55
+ lut = np.zeros(counts.size, dtype=np.int32)
56
+ lut[keep] = np.arange(1, keep.size + 1, dtype=np.int32)
57
+ return lut[labels]
58
+
59
+
60
+ def candidate_table(labels: np.ndarray, expansion_pct_per_year: np.ndarray,
61
+ lesion_labels: np.ndarray | None, voxel_mm3: float,
62
+ params: SELParams | None = None) -> pd.DataFrame:
63
+ """One row per candidate: size, expansion statistics, parent lesion, centroid."""
64
+ params = params or SELParams()
65
+ rows = []
66
+ n = int(labels.max())
67
+ if n == 0:
68
+ return pd.DataFrame(columns=[
69
+ "candidate_id", "n_voxels", "volume_mm3", "peak_pct_per_year",
70
+ "mean_pct_per_year", "seed_voxels", "parent_lesion_id", "cx", "cy", "cz",
71
+ ])
72
+ idx = np.arange(1, n + 1)
73
+ centroids = ndi.center_of_mass(labels > 0, labels, idx)
74
+ for k, (cx, cy, cz) in zip(idx, centroids):
75
+ sel = labels == k
76
+ vals = expansion_pct_per_year[sel]
77
+ parent = 0
78
+ if lesion_labels is not None:
79
+ parents = lesion_labels[sel]
80
+ parents = parents[parents > 0]
81
+ if parents.size:
82
+ parent = int(np.bincount(parents).argmax())
83
+ rows.append({
84
+ "candidate_id": int(k),
85
+ "n_voxels": int(sel.sum()),
86
+ "volume_mm3": float(sel.sum() * voxel_mm3),
87
+ "peak_pct_per_year": float(vals.max()),
88
+ "mean_pct_per_year": float(vals.mean()),
89
+ "seed_voxels": int((vals >= params.je1_pct_per_year).sum()),
90
+ "parent_lesion_id": parent,
91
+ "cx": float(cx), "cy": float(cy), "cz": float(cz),
92
+ })
93
+ return pd.DataFrame(rows)