repairgauge 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.
Files changed (40) hide show
  1. repairgauge-0.1.0/LICENSE +21 -0
  2. repairgauge-0.1.0/MANIFEST.in +4 -0
  3. repairgauge-0.1.0/PKG-INFO +166 -0
  4. repairgauge-0.1.0/README.md +143 -0
  5. repairgauge-0.1.0/docs/VALIDATION.md +115 -0
  6. repairgauge-0.1.0/pyproject.toml +41 -0
  7. repairgauge-0.1.0/repairgauge/__init__.py +3 -0
  8. repairgauge-0.1.0/repairgauge/backtest.py +148 -0
  9. repairgauge-0.1.0/repairgauge/cli.py +174 -0
  10. repairgauge-0.1.0/repairgauge/core.py +315 -0
  11. repairgauge-0.1.0/repairgauge/synth.py +168 -0
  12. repairgauge-0.1.0/repairgauge.egg-info/PKG-INFO +166 -0
  13. repairgauge-0.1.0/repairgauge.egg-info/SOURCES.txt +38 -0
  14. repairgauge-0.1.0/repairgauge.egg-info/dependency_links.txt +1 -0
  15. repairgauge-0.1.0/repairgauge.egg-info/entry_points.txt +2 -0
  16. repairgauge-0.1.0/repairgauge.egg-info/requires.txt +8 -0
  17. repairgauge-0.1.0/repairgauge.egg-info/top_level.txt +1 -0
  18. repairgauge-0.1.0/results/defaults_dev/candidates.csv +43 -0
  19. repairgauge-0.1.0/results/defaults_dev/per_lesion.csv +15121 -0
  20. repairgauge-0.1.0/results/phantom/by_deficit_recovery.csv +13 -0
  21. repairgauge-0.1.0/results/phantom/by_noise_recovery.csv +19 -0
  22. repairgauge-0.1.0/results/phantom/by_noise_size.csv +16 -0
  23. repairgauge-0.1.0/results/phantom/by_shift_vox_recovery.csv +25 -0
  24. repairgauge-0.1.0/results/phantom/by_shift_vox_size.csv +21 -0
  25. repairgauge-0.1.0/results/phantom/by_size_recovery.csv +31 -0
  26. repairgauge-0.1.0/results/phantom/headline.json +55 -0
  27. repairgauge-0.1.0/results/phantom/per_lesion.csv +3601 -0
  28. repairgauge-0.1.0/results/real_mirror/MTRmap/by_deficit_recovery.csv +13 -0
  29. repairgauge-0.1.0/results/real_mirror/MTRmap/by_size_recovery.csv +31 -0
  30. repairgauge-0.1.0/results/real_mirror/MTRmap/headline.json +60 -0
  31. repairgauge-0.1.0/results/real_mirror/MTRmap/nothing_planted_by_size.csv +6 -0
  32. repairgauge-0.1.0/results/real_mirror/MTRmap/per_lesion.csv +1627 -0
  33. repairgauge-0.1.0/results/real_mirror/ihMTR/by_deficit_recovery.csv +13 -0
  34. repairgauge-0.1.0/results/real_mirror/ihMTR/by_size_recovery.csv +31 -0
  35. repairgauge-0.1.0/results/real_mirror/ihMTR/headline.json +60 -0
  36. repairgauge-0.1.0/results/real_mirror/ihMTR/nothing_planted_by_size.csv +6 -0
  37. repairgauge-0.1.0/results/real_mirror/ihMTR/per_lesion.csv +1627 -0
  38. repairgauge-0.1.0/setup.cfg +4 -0
  39. repairgauge-0.1.0/tests/test_backtest.py +61 -0
  40. repairgauge-0.1.0/tests/test_core.py +121 -0
@@ -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,4 @@
1
+ include LICENSE README.md
2
+ graft docs
3
+ graft results
4
+ global-exclude *.pyc
@@ -0,0 +1,166 @@
1
+ Metadata-Version: 2.4
2
+ Name: repairgauge
3
+ Version: 0.1.0
4
+ Summary: Per-lesion recovery of a myelin-sensitive MRI value between two scans, with a known-answer backtest.
5
+ Author: Cedric Conday
6
+ License: MIT
7
+ Keywords: multiple sclerosis,MRI,lesion,remyelination,myelin,longitudinal,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
+ Provides-Extra: dev
20
+ Requires-Dist: pytest; extra == "dev"
21
+ Requires-Dist: ruff; extra == "dev"
22
+ Dynamic: license-file
23
+
24
+ # RepairGauge
25
+
26
+ RepairGauge measures, lesion by lesion, whether a myelin-sensitive MRI value recovered
27
+ between two scans of the same person. It also tests itself on known answers before you
28
+ trust it.
29
+
30
+ > **Nothing here is medical advice or evidence about multiple sclerosis.** It is research
31
+ > software. It has not been checked against histology or patient outcome.
32
+
33
+ ## Why
34
+
35
+ Open tools already compute myelin maps (qMRLab, QUIT, DECAES, hMRI), and open tools segment
36
+ lesions (LST-AI). I found no open tool that follows a myelin value inside each lesion over
37
+ time and comes with a known-answer test. That is what a myelin-repair trial needs to read
38
+ out. RepairGauge is that missing step. It does not make the maps and does not segment the
39
+ lesions; it takes both as inputs.
40
+
41
+ ## What it needs
42
+
43
+ * a baseline and a follow-up map of the same measure (MTR, MWF, ihMTR, T1w/T2w, R1, ...);
44
+ * a baseline lesion label image, or a binary mask, which is split into connected parts;
45
+ * a normal-appearing white matter (NAWM) mask, or a white matter mask. Lesions plus a 2 mm
46
+ margin and a 1 mm rim are then removed from it.
47
+
48
+ All inputs must already be on one grid. **RepairGauge does no registration.** If the grids
49
+ differ, it stops and says so.
50
+
51
+ ## What it measures
52
+
53
+ For every lesion:
54
+
55
+ 1. **Reference.** Each visit is divided by a local NAWM centre (Gaussian weight, 10 mm).
56
+ A global scale change or a smooth bias between visits cancels in that ratio. Values are
57
+ expressed in units of the baseline NAWM spread.
58
+ 2. **Deficit, change, recovery.** The deficit is how far the lesion sits below the reference
59
+ at baseline. The change is follow-up minus baseline. Recovery is change divided by deficit:
60
+ 1 means back to the reference, 0 means no change, a negative value means it got worse.
61
+ 3. **Noise floor.** The lesion's own shape is dropped at 1,000 random places in NAWM, and
62
+ the same change is measured there. This shows what "no change" looks like for a lesion
63
+ of this size and shape on this pair of scans. A small lesion therefore needs a bigger
64
+ change than a large one. A term for 0.3 mm of residual misalignment is added.
65
+ 4. **Label.** z = change against that floor. The label is repaired at z ≥ 2.5, worsened at
66
+ z ≤ −2.5, otherwise unchanged. A lesion is flagged `too_small` under 10 voxels, and
67
+ `shallow_deficit` when its deficit is under 3 NAWM spreads or under 4 noise floors.
68
+ Flagged lesions still get a label, but they are not "judged", and recovery is not quoted
69
+ for them.
70
+
71
+ Per person: counts per label, volume-weighted recovery, and the share of judged lesion
72
+ volume that was repaired. Outputs are `lesions.csv`, `summary.json`, `lesion_ids.nii.gz`
73
+ and `repair_labels.nii.gz` (1 repaired, 2 unchanged, 3 worsened, 4 undetermined).
74
+ Every threshold is in `repairgauge.core.Config` and on the command line.
75
+
76
+ ## Install and use
77
+
78
+ ```bash
79
+ pip install repairgauge
80
+ repairgauge run --baseline mtr_v1.nii.gz --followup mtr_v2.nii.gz \
81
+ --lesions lesions_v1.nii.gz --wm wm_v1.nii.gz --out out/
82
+ ```
83
+
84
+ Worked example on the built-in phantom (seed 0: 30 lesions, five sizes, six recovery
85
+ levels, deficit 25 %, follow-up with its own noise, a 5 % scale change, a bias field and
86
+ a 0.3 voxel shift):
87
+
88
+ ```bash
89
+ repairgauge phantom --out ph/
90
+ repairgauge run --baseline ph/baseline.nii.gz --followup ph/followup.nii.gz \
91
+ --lesions ph/lesions.nii.gz --wm ph/wm.nii.gz --out ph/out
92
+ # 30 lesions, 30 judged: 19 repaired, 6 unchanged, 5 worsened; volume-weighted recovery 0.33
93
+ ```
94
+
95
+ The 1,500 mm³ lesions in that run, true recovery against measured: −0.50 → −0.47
96
+ (worsened), 0 → 0.00 (unchanged), 0.25 → 0.27, 0.50 → 0.50, 0.75 → 0.75, 1.00 → 0.88
97
+ (all repaired). `ph/truth.csv` holds the answers for every lesion.
98
+
99
+ ## Known-answer results (2026-11-25, v0.1.0 defaults)
100
+
101
+ The defaults were fixed on development data first: phantom seeds 100–102, plus real pairs
102
+ from two subjects, sub-22449 and sub-24037. The numbers below come from seeds 0–4 and four
103
+ other subjects. The method is in `docs/VALIDATION.md`.
104
+
105
+ **Phantom**, 3,600 planted lesions (5 seeds × 3 noise levels × 4 shifts × 2 deficits × 30
106
+ lesions):
107
+
108
+ | | shift ≤ 0.5 voxel | shift 1 voxel |
109
+ |---|---:|---:|
110
+ | lesions judged | 95 % | 95 % |
111
+ | recovery error, judged lesions (mean absolute) | 0.07 | 0.14 |
112
+ | false "repaired" at zero recovery | **0 of 450** | 53 of 150 (35 %) |
113
+ | any recovery called repaired | 93 % | 97 % |
114
+ | 25 % recovery called repaired | 80 % | 92 % |
115
+ | worsening called worsened | 90 % | 70 % |
116
+
117
+ **Real noise.** MIRROR (OpenNeuro ds008825) is 22 healthy adults scanned twice on the same
118
+ day, so nothing changed between the two scans. The same lesions were planted into both
119
+ scans of sub-24762, sub-60476, sub-60501 and sub-60505: 15 % or 30 % deficit, five seeds,
120
+ 1,084 lesions per map. Regions where nothing was planted were scored as well (542).
121
+
122
+ | | MTR | ihMTR |
123
+ |---|---:|---:|
124
+ | planted lesions judged | 68 % | 9 % |
125
+ | recovery error, judged (mean absolute) | 0.11 | 0.25 |
126
+ | false "repaired" at zero recovery, judged | 0 | 0 |
127
+ | full recovery called repaired | 95 % | 68 % |
128
+ | any recovery called repaired | 73 % | 44 % |
129
+ | worsening called worsened | 78 % | 38 % |
130
+ | nothing planted: any change called | 3.5 % (19 of 542) | 1.8 % (10 of 542) |
131
+
132
+ On MTR, 30 % deficits are judged 92 % of the time and 15 % deficits 44 %. A 30 % deficit
133
+ that fully recovers is called repaired every time. ihMTR is too noisy at this resolution
134
+ to judge most lesions: 89 % are flagged `shallow_deficit`. The tool says so lesion by
135
+ lesion instead of guessing.
136
+
137
+ ## What this does not show
138
+
139
+ * **A planted change is not histology.** A lowered value that comes back is a test of the
140
+ arithmetic and the noise floor, not of myelin biology.
141
+ * **No patient data yet.** Real MS lesions have edges, rims and partial volume that the
142
+ planted ellipsoids do not.
143
+ * **Aligned inputs are assumed.** A one-voxel residual shift between visits turns 35 % of
144
+ unchanged phantom lesions into false "repaired" calls. Register well, or treat the
145
+ result as unreliable.
146
+ * **Large regions on real scans.** Where nothing was planted, regions of 1,500 mm³ were
147
+ called changed 15 % of the time on MTR and 10 % on ihMTR (11 and 7 of 72); smaller
148
+ regions stayed between 0 and 4 %. Real scan differences are spatially correlated in a
149
+ way the null does not fully capture at that size. The same size over-reads full
150
+ recovery on MTR (mean 1.29). Large lesions also often did not fit into the white matter
151
+ of these brains, so some cells have few lesions (as few as 4).
152
+ * Five sizes, two deficits, four subjects, two maps. MWF, R1 and T1w/T2w were not tested.
153
+
154
+ ## Next
155
+
156
+ The next known answer is the marmoset EAE dataset: serial 7 T MRI with histology for
157
+ remyelination per lesion (eLife, doi:10.7554/eLife.73786, CC0). It has not been started.
158
+
159
+ ## Credits
160
+
161
+ * MIRROR test-retest dataset, OpenNeuro ds008825 (CC0); code at github.com/PennLINC/mirror.
162
+ * NumPy, SciPy, pandas, nibabel.
163
+
164
+ ## Licence
165
+
166
+ MIT, © 2026 Cedric Conday.
@@ -0,0 +1,143 @@
1
+ # RepairGauge
2
+
3
+ RepairGauge measures, lesion by lesion, whether a myelin-sensitive MRI value recovered
4
+ between two scans of the same person. It also tests itself on known answers before you
5
+ trust it.
6
+
7
+ > **Nothing here is medical advice or evidence about multiple sclerosis.** It is research
8
+ > software. It has not been checked against histology or patient outcome.
9
+
10
+ ## Why
11
+
12
+ Open tools already compute myelin maps (qMRLab, QUIT, DECAES, hMRI), and open tools segment
13
+ lesions (LST-AI). I found no open tool that follows a myelin value inside each lesion over
14
+ time and comes with a known-answer test. That is what a myelin-repair trial needs to read
15
+ out. RepairGauge is that missing step. It does not make the maps and does not segment the
16
+ lesions; it takes both as inputs.
17
+
18
+ ## What it needs
19
+
20
+ * a baseline and a follow-up map of the same measure (MTR, MWF, ihMTR, T1w/T2w, R1, ...);
21
+ * a baseline lesion label image, or a binary mask, which is split into connected parts;
22
+ * a normal-appearing white matter (NAWM) mask, or a white matter mask. Lesions plus a 2 mm
23
+ margin and a 1 mm rim are then removed from it.
24
+
25
+ All inputs must already be on one grid. **RepairGauge does no registration.** If the grids
26
+ differ, it stops and says so.
27
+
28
+ ## What it measures
29
+
30
+ For every lesion:
31
+
32
+ 1. **Reference.** Each visit is divided by a local NAWM centre (Gaussian weight, 10 mm).
33
+ A global scale change or a smooth bias between visits cancels in that ratio. Values are
34
+ expressed in units of the baseline NAWM spread.
35
+ 2. **Deficit, change, recovery.** The deficit is how far the lesion sits below the reference
36
+ at baseline. The change is follow-up minus baseline. Recovery is change divided by deficit:
37
+ 1 means back to the reference, 0 means no change, a negative value means it got worse.
38
+ 3. **Noise floor.** The lesion's own shape is dropped at 1,000 random places in NAWM, and
39
+ the same change is measured there. This shows what "no change" looks like for a lesion
40
+ of this size and shape on this pair of scans. A small lesion therefore needs a bigger
41
+ change than a large one. A term for 0.3 mm of residual misalignment is added.
42
+ 4. **Label.** z = change against that floor. The label is repaired at z ≥ 2.5, worsened at
43
+ z ≤ −2.5, otherwise unchanged. A lesion is flagged `too_small` under 10 voxels, and
44
+ `shallow_deficit` when its deficit is under 3 NAWM spreads or under 4 noise floors.
45
+ Flagged lesions still get a label, but they are not "judged", and recovery is not quoted
46
+ for them.
47
+
48
+ Per person: counts per label, volume-weighted recovery, and the share of judged lesion
49
+ volume that was repaired. Outputs are `lesions.csv`, `summary.json`, `lesion_ids.nii.gz`
50
+ and `repair_labels.nii.gz` (1 repaired, 2 unchanged, 3 worsened, 4 undetermined).
51
+ Every threshold is in `repairgauge.core.Config` and on the command line.
52
+
53
+ ## Install and use
54
+
55
+ ```bash
56
+ pip install repairgauge
57
+ repairgauge run --baseline mtr_v1.nii.gz --followup mtr_v2.nii.gz \
58
+ --lesions lesions_v1.nii.gz --wm wm_v1.nii.gz --out out/
59
+ ```
60
+
61
+ Worked example on the built-in phantom (seed 0: 30 lesions, five sizes, six recovery
62
+ levels, deficit 25 %, follow-up with its own noise, a 5 % scale change, a bias field and
63
+ a 0.3 voxel shift):
64
+
65
+ ```bash
66
+ repairgauge phantom --out ph/
67
+ repairgauge run --baseline ph/baseline.nii.gz --followup ph/followup.nii.gz \
68
+ --lesions ph/lesions.nii.gz --wm ph/wm.nii.gz --out ph/out
69
+ # 30 lesions, 30 judged: 19 repaired, 6 unchanged, 5 worsened; volume-weighted recovery 0.33
70
+ ```
71
+
72
+ The 1,500 mm³ lesions in that run, true recovery against measured: −0.50 → −0.47
73
+ (worsened), 0 → 0.00 (unchanged), 0.25 → 0.27, 0.50 → 0.50, 0.75 → 0.75, 1.00 → 0.88
74
+ (all repaired). `ph/truth.csv` holds the answers for every lesion.
75
+
76
+ ## Known-answer results (2026-11-25, v0.1.0 defaults)
77
+
78
+ The defaults were fixed on development data first: phantom seeds 100–102, plus real pairs
79
+ from two subjects, sub-22449 and sub-24037. The numbers below come from seeds 0–4 and four
80
+ other subjects. The method is in `docs/VALIDATION.md`.
81
+
82
+ **Phantom**, 3,600 planted lesions (5 seeds × 3 noise levels × 4 shifts × 2 deficits × 30
83
+ lesions):
84
+
85
+ | | shift ≤ 0.5 voxel | shift 1 voxel |
86
+ |---|---:|---:|
87
+ | lesions judged | 95 % | 95 % |
88
+ | recovery error, judged lesions (mean absolute) | 0.07 | 0.14 |
89
+ | false "repaired" at zero recovery | **0 of 450** | 53 of 150 (35 %) |
90
+ | any recovery called repaired | 93 % | 97 % |
91
+ | 25 % recovery called repaired | 80 % | 92 % |
92
+ | worsening called worsened | 90 % | 70 % |
93
+
94
+ **Real noise.** MIRROR (OpenNeuro ds008825) is 22 healthy adults scanned twice on the same
95
+ day, so nothing changed between the two scans. The same lesions were planted into both
96
+ scans of sub-24762, sub-60476, sub-60501 and sub-60505: 15 % or 30 % deficit, five seeds,
97
+ 1,084 lesions per map. Regions where nothing was planted were scored as well (542).
98
+
99
+ | | MTR | ihMTR |
100
+ |---|---:|---:|
101
+ | planted lesions judged | 68 % | 9 % |
102
+ | recovery error, judged (mean absolute) | 0.11 | 0.25 |
103
+ | false "repaired" at zero recovery, judged | 0 | 0 |
104
+ | full recovery called repaired | 95 % | 68 % |
105
+ | any recovery called repaired | 73 % | 44 % |
106
+ | worsening called worsened | 78 % | 38 % |
107
+ | nothing planted: any change called | 3.5 % (19 of 542) | 1.8 % (10 of 542) |
108
+
109
+ On MTR, 30 % deficits are judged 92 % of the time and 15 % deficits 44 %. A 30 % deficit
110
+ that fully recovers is called repaired every time. ihMTR is too noisy at this resolution
111
+ to judge most lesions: 89 % are flagged `shallow_deficit`. The tool says so lesion by
112
+ lesion instead of guessing.
113
+
114
+ ## What this does not show
115
+
116
+ * **A planted change is not histology.** A lowered value that comes back is a test of the
117
+ arithmetic and the noise floor, not of myelin biology.
118
+ * **No patient data yet.** Real MS lesions have edges, rims and partial volume that the
119
+ planted ellipsoids do not.
120
+ * **Aligned inputs are assumed.** A one-voxel residual shift between visits turns 35 % of
121
+ unchanged phantom lesions into false "repaired" calls. Register well, or treat the
122
+ result as unreliable.
123
+ * **Large regions on real scans.** Where nothing was planted, regions of 1,500 mm³ were
124
+ called changed 15 % of the time on MTR and 10 % on ihMTR (11 and 7 of 72); smaller
125
+ regions stayed between 0 and 4 %. Real scan differences are spatially correlated in a
126
+ way the null does not fully capture at that size. The same size over-reads full
127
+ recovery on MTR (mean 1.29). Large lesions also often did not fit into the white matter
128
+ of these brains, so some cells have few lesions (as few as 4).
129
+ * Five sizes, two deficits, four subjects, two maps. MWF, R1 and T1w/T2w were not tested.
130
+
131
+ ## Next
132
+
133
+ The next known answer is the marmoset EAE dataset: serial 7 T MRI with histology for
134
+ remyelination per lesion (eLife, doi:10.7554/eLife.73786, CC0). It has not been started.
135
+
136
+ ## Credits
137
+
138
+ * MIRROR test-retest dataset, OpenNeuro ds008825 (CC0); code at github.com/PennLINC/mirror.
139
+ * NumPy, SciPy, pandas, nibabel.
140
+
141
+ ## Licence
142
+
143
+ MIT, © 2026 Cedric Conday.
@@ -0,0 +1,115 @@
1
+ # Validation record
2
+
3
+ All numbers are RepairGauge 0.1.0, run on 2026-11-25 on 4 CPU cores (arm64). The phantom
4
+ run takes 2 min 40 s, the real pairs 10 min.
5
+
6
+ ## How the defaults were fixed
7
+
8
+ The defaults were chosen on a development set and then frozen. The reported runs below use
9
+ other seeds and other subjects.
10
+
11
+ * **Phantom, seeds 100–102** (`scripts/fix_defaults.py --out results/defaults_dev --jobs 4`):
12
+ NAWM reference width 0 / 10 / 20 / 40 mm, alignment tolerance 0 / 0.15 / 0.3 / 0.5 mm,
13
+ z 2.0 / 2.5 / 3.0, over noise 2 / 4 / 8 %, shift 0–1 voxel and deficit 15 / 30 %. The
14
+ table is in `results/defaults_dev/candidates.csv`.
15
+ At tolerance 0.3 mm and z 2.5, false "repaired" at zero recovery was 0 for shifts up to
16
+ 0.5 voxel at every width, so the width was set by how many lesions it could judge.
17
+ * **Real pairs, sub-22449 and sub-24037, seeds 100–102**, width 0 / 10 / 20 mm. On MTR
18
+ 10 mm judged 68 % of planted lesions, against 46 % at 20 mm and 34 % with one global
19
+ value, with no false calls at zero recovery in any of the three. Logs:
20
+ `work/logs/dev_real_sigma*.log` (not in git).
21
+ * Frozen: width 10 mm, tolerance 0.3 mm, z 2.5, minimum 10 voxels, deficit at least
22
+ 3 NAWM spreads and 4 noise floors (commit 82a9a3d).
23
+
24
+ ## Phantom (seeds 0–4)
25
+
26
+ ```bash
27
+ repairgauge backtest --out results/phantom --jobs 4
28
+ ```
29
+
30
+ 112 × 112 × 80 at 1 mm, white matter texture. Per phantom: 30 lesions (15, 50, 150,
31
+ 500, 1,500 mm³ × recovery 0, 0.25, 0.5, 0.75, 1, −0.5). The follow-up gets its own noise,
32
+ a 5 % scale change, a 3 % bias field and a rigid shift. Grid: 5 seeds × noise 2 / 4 / 8 %
33
+ × shift 0 / 0.25 / 0.5 / 1 voxel × deficit 15 / 30 %, which is 3,600 lesions.
34
+
35
+ Headline (`results/phantom/headline.json`, all shifts pooled): judged 95 %; recovery error
36
+ on judged lesions 0.084 (bias +0.043); false "repaired" at zero recovery 8.8 %, all of it
37
+ at a 1 voxel shift (53 of 150; 0 of 450 at ≤ 0.5); sensitivity to any recovery 94 %, to
38
+ full recovery 99 %; specificity of "repaired" 96 %; sensitivity to worsening 85 %.
39
+
40
+ By shift (`results/phantom/by_shift_vox_recovery.csv`), the rate called repaired:
41
+
42
+ | shift (voxel) | recovery 0 | 0.25 | 0.5 | 1.0 | worsening called |
43
+ |---:|---:|---:|---:|---:|---:|
44
+ | 0 | 0.00 | 0.78 | 0.93 | 0.99 | 0.93 |
45
+ | 0.25 | 0.00 | 0.79 | 0.95 | 0.99 | 0.91 |
46
+ | 0.5 | 0.00 | 0.84 | 0.97 | 0.99 | 0.86 |
47
+ | 1.0 | **0.35** | 0.92 | 0.97 | 0.99 | 0.70 |
48
+
49
+ A one-voxel shift pushes recovery at zero to a mean of +0.15. A misaligned follow-up
50
+ smears the lesion edge into NAWM, and that reads as recovery. The alignment term covers
51
+ 0.3 mm, not 1 mm.
52
+
53
+ By size (`by_size_recovery.csv`): 15 mm³ lesions are the weak cell. Only 50–90 % are
54
+ judged, 25 % recovery is called 25 % of the time, worsening 40 %, and 10 % are falsely
55
+ called repaired at zero. From 50 mm³ up, any recovery of 25 % or more is called in 95–100 %
56
+ of cases. Large lesions (150–1,500 mm³) are falsely called repaired at zero 9–13 % of the
57
+ time, pooled over shifts. By noise (`by_noise_recovery.csv`): at 8 % voxel noise, 25 %
58
+ recovery is called 76 % of the time against 90 % at 2 %.
59
+
60
+ ## Real noise: MIRROR, OpenNeuro ds008825 (four held-out subjects, seeds 0–4)
61
+
62
+ ```bash
63
+ python scripts/fetch_mirror.py --out work/mirror --n 8 # about 30 MB per subject
64
+ python scripts/real_backtest.py --out results/real_mirror \
65
+ --subjects sub-24762 sub-60476 sub-60501 sub-60505 --seeds 0 1 2 3 4 --jobs 4
66
+ ```
67
+
68
+ These are the MTR and ihMTR maps of both same-day sessions in each subject's T1w space,
69
+ with that space's white matter mask from MP2RAGE. Six subjects were fetched, the first in
70
+ listing order. Two went to development; these four are the rest. Lesions are planted at
71
+ 15 % and 30 % deficit with the same sizes and recovery levels. A run with deficit 0 plants
72
+ nothing and scores the same regions, so any change called there is false.
73
+
74
+ | | MTR | ihMTR |
75
+ |---|---:|---:|
76
+ | planted lesions | 1,084 | 1,084 |
77
+ | judged | 68.3 % | 9.2 % |
78
+ | flagged shallow_deficit / too_small | 328 / 16 | 968 / 16 |
79
+ | recovery error, judged (mean absolute; bias) | 0.115 (+0.033) | 0.254 (−0.050) |
80
+ | false "repaired" at zero recovery: all / judged | 0.6 % / 0 | 0 / 0 |
81
+ | false "worsened" at zero recovery: all / judged | 0 / 0 | 0.6 % / 0 |
82
+ | full recovery called repaired | 94.9 % | 68.4 % |
83
+ | any recovery called repaired | 73.5 % | 43.5 % |
84
+ | specificity of "repaired" | 99.7 % | 100 % |
85
+ | worsening called worsened | 77.5 % | 37.5 % |
86
+ | nothing planted: repaired / worsened / any | 2.8 % / 0.7 % / 3.5 % | 0.2 % / 1.7 % / 1.8 % |
87
+
88
+ MTR by deficit (`results/real_mirror/MTRmap/by_deficit_recovery.csv`): at 30 %, 89–95 % are
89
+ judged, and recovery of 0.5 / 0.75 / 1 is called repaired 90 / 99 / 100 % of the time;
90
+ 25 % recovery only 41 %. At 15 %, a third to a half are judged, and 50 % recovery is called
91
+ 54 % of the time.
92
+
93
+ MTR by size (`by_size_recovery.csv`): 15 mm³ lesions are judged 33–40 % of the time and
94
+ 25 % recovery is never called. At 1,500 mm³, recovery is over-read (mean 1.14 at 0.75 and
95
+ 1.29 at 1.0), and only 4 of 40 zero-recovery lesions fitted into the white matter, so
96
+ false calls at that size are barely tested.
97
+
98
+ Nothing planted, by size (`nothing_planted_by_size.csv`), the rate of any change called:
99
+
100
+ | size (mm³) | 15 | 50 | 150 | 500 | 1,500 |
101
+ |---|---:|---:|---:|---:|---:|
102
+ | MTR | 0.017 | 0.000 | 0.042 | 0.009 | **0.153** |
103
+ | ihMTR | 0.008 | 0.008 | 0.000 | 0.009 | **0.097** |
104
+
105
+ Almost every unplanted region is flagged (MTR 99.8 %, ihMTR 97.6 %), because healthy white
106
+ matter has no deficit. The calls are reported anyway: they show that a large region on a
107
+ real pair moves more than the pseudo-lesion null predicts.
108
+
109
+ ## Unverified
110
+
111
+ * No patient scans, no histology. The marmoset EAE set (doi:10.7554/eLife.73786) is the
112
+ next known answer.
113
+ * MWF, R1 and T1w/T2w maps were not tested, and no field strength other than MIRROR's.
114
+ * The real pairs were scanned on the same day. Drift between visits months apart is
115
+ simulated only on the phantom (scale and bias).
@@ -0,0 +1,41 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "repairgauge"
7
+ version = "0.1.0"
8
+ description = "Per-lesion recovery of a myelin-sensitive MRI value between two scans, with a known-answer backtest."
9
+ readme = "README.md"
10
+ license = {text = "MIT"}
11
+ requires-python = ">=3.10"
12
+ authors = [{name = "Cedric Conday"}]
13
+ keywords = ["multiple sclerosis", "MRI", "lesion", "remyelination", "myelin", "longitudinal", "neuroimaging"]
14
+ classifiers = [
15
+ "Intended Audience :: Science/Research",
16
+ "License :: OSI Approved :: MIT License",
17
+ "Programming Language :: Python :: 3",
18
+ "Topic :: Scientific/Engineering :: Medical Science Apps.",
19
+ ]
20
+ dependencies = [
21
+ "numpy>=1.24",
22
+ "scipy>=1.10",
23
+ "nibabel>=5",
24
+ "pandas>=2",
25
+ ]
26
+
27
+ [project.optional-dependencies]
28
+ dev = ["pytest", "ruff"]
29
+
30
+ [project.scripts]
31
+ repairgauge = "repairgauge.cli:main"
32
+
33
+ [tool.setuptools.packages.find]
34
+ include = ["repairgauge*"]
35
+
36
+ [tool.ruff]
37
+ line-length = 110
38
+ target-version = "py310"
39
+
40
+ [tool.ruff.lint]
41
+ select = ["E", "F", "I", "B", "UP"]
@@ -0,0 +1,3 @@
1
+ """RepairGauge: did a myelin-sensitive MRI value recover, lesion by lesion."""
2
+
3
+ __version__ = "0.1.0"
@@ -0,0 +1,148 @@
1
+ """Run the tool on planted lesions and score it against the truth."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import itertools
6
+ import json
7
+ from dataclasses import asdict
8
+ from multiprocessing import Pool
9
+ from pathlib import Path
10
+
11
+ import numpy as np
12
+ import pandas as pd
13
+
14
+ from . import __version__
15
+ from .core import REPAIRED, WORSENED, Config, make_nawm, measure
16
+ from .synth import RECOVERIES, SIZES_MM3, Planted, make_phantom, plant_pair
17
+
18
+
19
+ def run_planted(planted: Planted, cfg: Config) -> pd.DataFrame:
20
+ """Measure a planted pair and join the result to the truth, one row per lesion."""
21
+ nawm = make_nawm(planted.wm, planted.lesions, planted.zooms, cfg.nawm_margin_mm, cfg.wm_erode_mm)
22
+ table, _, _ = measure(planted.baseline, planted.followup, planted.lesions, nawm,
23
+ planted.zooms, cfg)
24
+ return planted.truth.merge(table.drop(columns=["n_voxels"]), on="lesion_id", how="left")
25
+
26
+
27
+ def _rate(series: pd.Series) -> float:
28
+ return float(series.mean()) if len(series) else float("nan")
29
+
30
+
31
+ def score(rows: pd.DataFrame, by=("size_mm3", "recovery_true")) -> pd.DataFrame:
32
+ """Per cell: how many lesions, how many judged, recovery error, and label rates.
33
+
34
+ ``called_repaired`` and ``called_worsened`` count every lesion that got a z-score,
35
+ flagged or not. Where the truth is recovery > 0, ``called_repaired`` is the
36
+ sensitivity; at recovery 0 it is the false-positive rate; at recovery <= 0,
37
+ 1 - ``called_repaired`` is the specificity. The ``judged_*`` columns give the same
38
+ rates among unflagged lesions only.
39
+ """
40
+ out = []
41
+ for key, g in rows.groupby(list(by), sort=True):
42
+ key = key if isinstance(key, tuple) else (key,)
43
+ j = g[g["judged"].fillna(False).astype(bool)]
44
+ err = j["recovery"] - j["recovery_true"]
45
+ out.append({
46
+ **dict(zip(by, key, strict=True)),
47
+ "n": len(g),
48
+ "judged": _rate(g["judged"].fillna(False).astype(bool)),
49
+ "recovery_mean": float(j["recovery"].mean()) if len(j) else float("nan"),
50
+ "recovery_mae": float(err.abs().mean()) if len(j) else float("nan"),
51
+ "called_repaired": _rate(g["label"] == REPAIRED),
52
+ "called_worsened": _rate(g["label"] == WORSENED),
53
+ "judged_repaired": _rate(j["label"] == REPAIRED),
54
+ "judged_worsened": _rate(j["label"] == WORSENED),
55
+ })
56
+ return pd.DataFrame(out)
57
+
58
+
59
+ def headline(rows: pd.DataFrame) -> dict:
60
+ """The few numbers the README quotes. All lesions unless a key says ``judged``."""
61
+ judged = rows[rows["judged"].fillna(False).astype(bool)]
62
+ zero, pos, neg = (rows[rows["recovery_true"] == 0], rows[rows["recovery_true"] > 0],
63
+ rows[rows["recovery_true"] < 0])
64
+ full = rows[rows["recovery_true"] == 1.0]
65
+ err = judged["recovery"] - judged["recovery_true"]
66
+ jz = judged[judged["recovery_true"] == 0]
67
+ return {
68
+ "n_lesions": int(len(rows)),
69
+ "judged_share": _rate(rows["judged"].fillna(False).astype(bool)),
70
+ "recovery_mae_judged": float(err.abs().mean()) if len(judged) else float("nan"),
71
+ "recovery_bias_judged": float(err.mean()) if len(judged) else float("nan"),
72
+ "false_repaired_at_zero": _rate(zero["label"] == REPAIRED),
73
+ "false_worsened_at_zero": _rate(zero["label"] == WORSENED),
74
+ "false_repaired_at_zero_judged": _rate(jz["label"] == REPAIRED),
75
+ "false_worsened_at_zero_judged": _rate(jz["label"] == WORSENED),
76
+ "sensitivity_repaired_any_recovery": _rate(pos["label"] == REPAIRED),
77
+ "sensitivity_repaired_full_recovery": _rate(full["label"] == REPAIRED),
78
+ "specificity_repaired": 1.0 - _rate(pd.concat([zero, neg])["label"] == REPAIRED),
79
+ "sensitivity_worsened": _rate(neg["label"] == WORSENED),
80
+ }
81
+
82
+
83
+ def _one_phantom(job) -> pd.DataFrame:
84
+ seed, noise, shift, deficit, cfg = job
85
+ rows = run_planted(make_phantom(seed, noise=noise, shift_vox=shift, deficit=deficit), cfg)
86
+ return rows.assign(seed=seed, noise=noise, shift_vox=shift)
87
+
88
+
89
+ def run_synthetic(seeds, noises, shifts, deficits, cfg: Config | None = None,
90
+ jobs: int = 1) -> pd.DataFrame:
91
+ """One phantom per seed, noise level, shift and deficit; every lesion scored."""
92
+ cfg = cfg or Config()
93
+ grid = [(s, n, sh, d, cfg) for s, n, sh, d in itertools.product(seeds, noises, shifts, deficits)]
94
+ if jobs > 1:
95
+ with Pool(jobs) as pool:
96
+ parts = pool.map(_one_phantom, grid)
97
+ else:
98
+ parts = [_one_phantom(j) for j in grid]
99
+ return pd.concat(parts, ignore_index=True)
100
+
101
+
102
+ def run_real(baseline: np.ndarray, followup: np.ndarray, wm: np.ndarray, zooms, seeds,
103
+ deficits, cfg: Config | None = None, follow_shift_vox: float = 0.0,
104
+ sizes_mm3=SIZES_MM3, recoveries=RECOVERIES) -> pd.DataFrame:
105
+ """Plant into one real pair, once per seed and deficit. ``deficit`` 0 plants nothing."""
106
+ cfg = cfg or Config()
107
+ parts = []
108
+ for seed, deficit in itertools.product(seeds, deficits):
109
+ planted = plant_pair(baseline, followup, wm, zooms, seed, deficit=deficit,
110
+ sizes_mm3=sizes_mm3, recoveries=recoveries,
111
+ follow_shift_vox=follow_shift_vox)
112
+ parts.append(run_planted(planted, cfg).assign(seed=seed))
113
+ return pd.concat(parts, ignore_index=True)
114
+
115
+
116
+ def write_report(rows: pd.DataFrame, out: Path, cfg: Config, meta: dict) -> dict:
117
+ """Write per_lesion.csv, the score tables and headline.json into ``out``."""
118
+ out = Path(out)
119
+ out.mkdir(parents=True, exist_ok=True)
120
+ rows.to_csv(out / "per_lesion.csv", index=False, float_format="%.5g")
121
+ planted = rows[rows["deficit_true"] > 0]
122
+ result = {"version": __version__, **meta, "config": asdict(cfg)}
123
+ if len(planted):
124
+ score(planted).to_csv(out / "by_size_recovery.csv", index=False, float_format="%.4g")
125
+ score(planted, by=("deficit_true", "recovery_true")).to_csv(
126
+ out / "by_deficit_recovery.csv", index=False, float_format="%.4g")
127
+ for extra in ("noise", "shift_vox"):
128
+ if extra in rows:
129
+ score(planted, by=(extra, "size_mm3")).to_csv(
130
+ out / f"by_{extra}_size.csv", index=False, float_format="%.4g")
131
+ score(planted, by=(extra, "recovery_true")).to_csv(
132
+ out / f"by_{extra}_recovery.csv", index=False, float_format="%.4g")
133
+ result["planted"] = headline(planted)
134
+ blank = rows[rows["deficit_true"] == 0]
135
+ if len(blank):
136
+ called = blank["label"].isin([REPAIRED, WORSENED])
137
+ result["nothing_planted"] = {
138
+ "n_lesions": int(len(blank)),
139
+ "called_repaired": _rate(blank["label"] == REPAIRED),
140
+ "called_worsened": _rate(blank["label"] == WORSENED),
141
+ "called_any_change": _rate(called),
142
+ "flagged_share": 1.0 - _rate(blank["judged"].fillna(False).astype(bool)),
143
+ }
144
+ by_size = blank.assign(called=called).groupby("size_mm3")["called"].agg(["size", "mean"])
145
+ by_size.rename(columns={"size": "n", "mean": "called_any_change"}).to_csv(
146
+ out / "nothing_planted_by_size.csv", float_format="%.4g")
147
+ (out / "headline.json").write_text(json.dumps(result, indent=2) + "\n")
148
+ return result