mscard 0.1.0__py3-none-any.whl
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.
- mscard/__init__.py +3 -0
- mscard/calibrate.py +441 -0
- mscard/cli.py +138 -0
- mscard/config.py +51 -0
- mscard/figures.py +66 -0
- mscard/measure.py +184 -0
- mscard/report.py +259 -0
- mscard/segment.py +90 -0
- mscard/spec.py +151 -0
- mscard-0.1.0.dist-info/METADATA +217 -0
- mscard-0.1.0.dist-info/RECORD +15 -0
- mscard-0.1.0.dist-info/WHEEL +5 -0
- mscard-0.1.0.dist-info/entry_points.txt +2 -0
- mscard-0.1.0.dist-info/licenses/LICENSE +21 -0
- mscard-0.1.0.dist-info/top_level.txt +1 -0
mscard/__init__.py
ADDED
mscard/calibrate.py
ADDED
|
@@ -0,0 +1,441 @@
|
|
|
1
|
+
"""Calibration: a synthetic follow-up with known truth, the same pipeline, and a grade.
|
|
2
|
+
|
|
3
|
+
The synthetic follow-up is the subject's own baseline scan, one modelled year
|
|
4
|
+
later: the whole brain contracted by a known factor (bidsgate inject-atrophy),
|
|
5
|
+
a known set of new lesions placed away from the existing ones (bidsgate
|
|
6
|
+
inject-lesions), a small rigid repositioning, a gain change and noise. Every
|
|
7
|
+
baseline lesion is otherwise unchanged, so the truth for each report line is
|
|
8
|
+
known: which follow-up lesions are new, that no baseline lesion enlarged,
|
|
9
|
+
shrank, resolved or expanded slowly, and the brain volume change.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import json
|
|
15
|
+
import shutil
|
|
16
|
+
import zlib
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
|
|
19
|
+
import nibabel as nib
|
|
20
|
+
import numpy as np
|
|
21
|
+
import pandas as pd
|
|
22
|
+
from scipy import ndimage as ndi
|
|
23
|
+
|
|
24
|
+
from .config import Bands, SyntheticParams
|
|
25
|
+
from .spec import Scan
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def label_lesions(mask: np.ndarray, connectivity: int = 2) -> np.ndarray:
|
|
29
|
+
from lesiontrack.tracking import label_lesions as _ll
|
|
30
|
+
|
|
31
|
+
return _ll(mask, connectivity)
|
|
32
|
+
|
|
33
|
+
SESSION = "SYN"
|
|
34
|
+
TRUTH_FORMAT = 2 # bump when the synthetic construction or the truth record changes; old caches are rebuilt
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _save(arr: np.ndarray, like: nib.Nifti1Image, path: Path, dtype=None) -> Path:
|
|
38
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
39
|
+
nib.save(nib.Nifti1Image(arr.astype(dtype) if dtype is not None else arr, like.affine), path)
|
|
40
|
+
return path
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def make_synthetic(baseline: Scan, out_dir: Path, sp: SyntheticParams, log: list[str] | None = None) -> tuple[Scan, dict]:
|
|
44
|
+
"""Write the synthetic follow-up of ``baseline`` under ``out_dir`` and return (scan, truth)."""
|
|
45
|
+
from bidsgate.inject_atrophy import _warp, displacement
|
|
46
|
+
from bidsgate.inject_lesions import LesionSpec, inject
|
|
47
|
+
from lesiontrack.synth import _rigid_field
|
|
48
|
+
|
|
49
|
+
out_dir = Path(out_dir)
|
|
50
|
+
truth_json = out_dir / "truth.json"
|
|
51
|
+
t1_p, fl_p = out_dir / "T1w.nii.gz", out_dir / "FLAIR.nii.gz"
|
|
52
|
+
mask_p, brain_p, new_p = out_dir / "mask.nii.gz", out_dir / "brainmask.nii.gz", out_dir / "newlesions_truth.nii.gz"
|
|
53
|
+
params_json = json.loads(json.dumps(sp.__dict__)) # tuples become lists, as in the stored truth
|
|
54
|
+
if truth_json.exists() and all(p.exists() for p in (t1_p, fl_p, mask_p, brain_p, new_p)):
|
|
55
|
+
truth = json.loads(truth_json.read_text())
|
|
56
|
+
if truth.get("format") == TRUTH_FORMAT and truth.get("params") == params_json and truth.get("source") == _source(baseline):
|
|
57
|
+
truth["rewritten"] = False
|
|
58
|
+
return _scan(baseline, out_dir, sp), truth
|
|
59
|
+
if baseline.mask is None or baseline.brainmask is None:
|
|
60
|
+
raise ValueError("make_synthetic needs a baseline with a lesion mask and a brain mask")
|
|
61
|
+
# A stale synthetic invalidates every downstream cache (lesiontrack keys its registration
|
|
62
|
+
# cache on parameters only, not on the input files).
|
|
63
|
+
for stale in (out_dir.parent / "measure", out_dir.parent / "lst-ai", out_dir.parent / "grade.json",
|
|
64
|
+
out_dir.parent / "newlesions_truth_halfway.nii.gz"):
|
|
65
|
+
if stale.is_dir():
|
|
66
|
+
shutil.rmtree(stale)
|
|
67
|
+
elif stale.exists():
|
|
68
|
+
stale.unlink()
|
|
69
|
+
seed = (sp.seed * 1_000_003 + zlib.crc32(baseline.subject.encode())) % (2**32)
|
|
70
|
+
rng = np.random.default_rng(seed)
|
|
71
|
+
img = nib.load(baseline.t1)
|
|
72
|
+
zooms = tuple(float(z) for z in img.header.get_zooms()[:3])
|
|
73
|
+
if max(zooms) / min(zooms) > 1.05:
|
|
74
|
+
raise ValueError(f"make_synthetic needs isotropic voxels (got {zooms}); the rigid perturbation is built in "
|
|
75
|
+
"index space and would add a strain of the size of the injected atrophy on anisotropic data. "
|
|
76
|
+
"Resample to isotropic first.")
|
|
77
|
+
t1 = np.asarray(img.dataobj, dtype=np.float32)
|
|
78
|
+
fl = np.asarray(nib.load(baseline.flair).dataobj, dtype=np.float32)
|
|
79
|
+
mask = np.asarray(nib.load(baseline.mask).dataobj) > 0
|
|
80
|
+
brain = np.asarray(nib.load(baseline.brainmask).dataobj) > 0
|
|
81
|
+
|
|
82
|
+
# 1. Whole-brain contraction by a known factor; every image and mask follows the same field.
|
|
83
|
+
disp = displacement(t1.shape, zooms, brain, sp.volume_factor, sp.falloff_mm)
|
|
84
|
+
t1a = _warp(t1, disp, 1)
|
|
85
|
+
fla = _warp(fl, disp, 1)
|
|
86
|
+
# Masks follow the field as the zero level set of their signed distance: nearest-neighbour
|
|
87
|
+
# keeps the old boundary, and a 0.5 threshold on an interpolated binary mask erodes small
|
|
88
|
+
# lesions; the signed distance moves the boundary by the field and nothing else.
|
|
89
|
+
lab_bl = label_lesions(mask, 2)
|
|
90
|
+
laba = _warp_labels(lab_bl, disp, zooms)
|
|
91
|
+
maska = laba > 0
|
|
92
|
+
braina = _warp_mask(brain, disp, zooms)
|
|
93
|
+
del disp
|
|
94
|
+
|
|
95
|
+
# 2. New lesions, placed by bidsgate inside a brain mask that excludes a margin around every
|
|
96
|
+
# baseline lesion, so each injected lesion is truly new rather than an enlargement.
|
|
97
|
+
tmp = out_dir / "tmp"
|
|
98
|
+
tmp.mkdir(parents=True, exist_ok=True)
|
|
99
|
+
it = round(sp.exclusion_mm / min(zooms))
|
|
100
|
+
excl = ndi.binary_dilation(maska, structure=ndi.generate_binary_structure(3, 2), iterations=max(1, it))
|
|
101
|
+
place = _save((braina & ~excl).astype(np.uint8), img, tmp / "placement.nii.gz")
|
|
102
|
+
_save(t1a, img, tmp / "T1w_atrophied.nii.gz")
|
|
103
|
+
_save(fla, img, tmp / "FLAIR_atrophied.nii.gz")
|
|
104
|
+
new_json = out_dir / "newlesions_truth.json"
|
|
105
|
+
spec = LesionSpec(n=sp.n_new, seed=int(rng.integers(0, 2**31 - 1)))
|
|
106
|
+
inject(tmp / "T1w_atrophied.nii.gz", tmp / "FLAIR_atrophied.nii.gz", tmp / "T1w_injected.nii.gz",
|
|
107
|
+
tmp / "FLAIR_injected.nii.gz", tmp / "newlesions.nii.gz", new_json, spec, mask_path=place)
|
|
108
|
+
t1b = np.asarray(nib.load(tmp / "T1w_injected.nii.gz").dataobj, dtype=np.float32)
|
|
109
|
+
flb = np.asarray(nib.load(tmp / "FLAIR_injected.nii.gz").dataobj, dtype=np.float32)
|
|
110
|
+
newb = np.asarray(nib.load(tmp / "newlesions.nii.gz").dataobj).astype(np.int32)
|
|
111
|
+
new_truth = json.loads(new_json.read_text())
|
|
112
|
+
|
|
113
|
+
# 3. Rigid repositioning, gain, noise: what a second visit adds even when nothing changed.
|
|
114
|
+
rot = rng.uniform(-1, 1, 3) * sp.rigid_rot_deg
|
|
115
|
+
trans = rng.uniform(-1, 1, 3) * sp.rigid_trans_vox
|
|
116
|
+
rig = _rigid_field(t1.shape, rot, trans)
|
|
117
|
+
t1c = _warp(t1b, rig, 1)
|
|
118
|
+
flc = _warp(flb, rig, 1)
|
|
119
|
+
labc = _warp_labels(laba, rig, zooms)
|
|
120
|
+
newc = _warp_labels(newb, rig, zooms)
|
|
121
|
+
maskc = (labc > 0) | (newc > 0)
|
|
122
|
+
brainc = _warp_mask(braina, rig, zooms)
|
|
123
|
+
del rig
|
|
124
|
+
vox = float(np.prod(zooms))
|
|
125
|
+
vb, va = np.bincount(lab_bl.ravel()), np.bincount(labc.ravel(), minlength=lab_bl.max() + 1)
|
|
126
|
+
baseline_lesions = [{"id": int(i), "volume_before_mm3": float(vb[i] * vox), "volume_after_mm3": float(va[i] * vox)}
|
|
127
|
+
for i in range(1, lab_bl.max() + 1)]
|
|
128
|
+
gains = rng.uniform(*sp.intensity_scale, 2)
|
|
129
|
+
head = t1c > 0
|
|
130
|
+
for arr, g in ((t1c, gains[0]), (flc, gains[1])):
|
|
131
|
+
arr *= g
|
|
132
|
+
sd = sp.noise_frac * float(np.percentile(arr[head], 99)) if head.any() else 0.0
|
|
133
|
+
arr[head] += rng.normal(0, sd, int(head.sum())).astype(np.float32)
|
|
134
|
+
np.maximum(arr, 0, out=arr)
|
|
135
|
+
_save(t1c, img, t1_p)
|
|
136
|
+
_save(flc, img, fl_p)
|
|
137
|
+
_save(maskc, img, mask_p, np.uint8)
|
|
138
|
+
_save(brainc, img, brain_p, np.uint8)
|
|
139
|
+
_save(newc, img, new_p, np.int32)
|
|
140
|
+
_save(labc, img, out_dir / "baselinelesions_truth.nii.gz", np.int32)
|
|
141
|
+
for p in tmp.glob("*"):
|
|
142
|
+
p.unlink()
|
|
143
|
+
tmp.rmdir()
|
|
144
|
+
truth = {
|
|
145
|
+
"rewritten": True,
|
|
146
|
+
"format": TRUTH_FORMAT,
|
|
147
|
+
"kind": "mscard synthetic follow-up",
|
|
148
|
+
"session": SESSION,
|
|
149
|
+
"dt_years": sp.dt_years,
|
|
150
|
+
"volume_factor": sp.volume_factor,
|
|
151
|
+
"injected_brain_change_pct": (sp.volume_factor - 1) * 100,
|
|
152
|
+
"n_new": sp.n_new,
|
|
153
|
+
"new_lesions": new_truth["lesions"],
|
|
154
|
+
"new_lesion_volume_mm3": new_truth["total_volume_mm3"],
|
|
155
|
+
"baseline_lesion_count_truth": int(lab_bl.max()),
|
|
156
|
+
"baseline_lesion_volume_mm3": float(mask.sum() * vox),
|
|
157
|
+
"baseline_lesion_volume_after_mm3": float((labc > 0).sum() * vox),
|
|
158
|
+
"baseline_lesions": baseline_lesions,
|
|
159
|
+
"rigid": {"rot_deg": rot.tolist(), "trans_vox": trans.tolist()},
|
|
160
|
+
"gains": gains.tolist(),
|
|
161
|
+
"seed": seed,
|
|
162
|
+
"params": sp.__dict__,
|
|
163
|
+
"source": _source(baseline),
|
|
164
|
+
"truth_per_line": {
|
|
165
|
+
"new": "exactly the injected lesions; any other follow-up-only component is false",
|
|
166
|
+
"enlarging/shrinking/resolved": "per lesion in baseline_lesions: volume_after_mm3 against volume_before_mm3 "
|
|
167
|
+
"(the global factor plus voxel quantisation of the moved boundary); no lesion resolves",
|
|
168
|
+
"sel": "none; no lesion expands",
|
|
169
|
+
"brain_volume_change_pct": (sp.volume_factor - 1) * 100,
|
|
170
|
+
},
|
|
171
|
+
}
|
|
172
|
+
truth_json.write_text(json.dumps(scrub(truth), indent=2, allow_nan=False))
|
|
173
|
+
if log is not None:
|
|
174
|
+
log.append(f"{baseline.subject}: synthetic follow-up, factor {sp.volume_factor}, {sp.n_new} new lesions, seed {seed}")
|
|
175
|
+
return _scan(baseline, out_dir, sp), truth
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def _source(baseline: Scan) -> dict:
|
|
179
|
+
"""The inputs the synthetic was built from, with size and mtime so a changed mask is noticed."""
|
|
180
|
+
rec = {}
|
|
181
|
+
for what in ("t1", "flair", "mask", "brainmask"):
|
|
182
|
+
q = getattr(baseline, what)
|
|
183
|
+
st = Path(q).stat() if q is not None else None
|
|
184
|
+
rec[what] = None if q is None else {"path": str(q), "size": st.st_size, "mtime": int(st.st_mtime)}
|
|
185
|
+
return rec
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def _warp_mask(mask: np.ndarray, disp: np.ndarray, zooms: tuple) -> np.ndarray:
|
|
189
|
+
"""Move a binary mask by a sampling field as the zero level set of its signed distance (mm)."""
|
|
190
|
+
from bidsgate.inject_atrophy import _warp
|
|
191
|
+
|
|
192
|
+
sd = (ndi.distance_transform_edt(~mask, sampling=zooms) - ndi.distance_transform_edt(mask, sampling=zooms)).astype(np.float32)
|
|
193
|
+
return _warp(sd, disp, 1, cval=1e3) <= 0
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def _warp_labels(labels: np.ndarray, disp: np.ndarray, zooms: tuple) -> np.ndarray:
|
|
197
|
+
"""Warp an integer label map: the support as a level set, labels by nearest neighbour then nearest fill."""
|
|
198
|
+
from bidsgate.inject_atrophy import _warp
|
|
199
|
+
|
|
200
|
+
support = _warp_mask(labels > 0, disp, zooms)
|
|
201
|
+
nn = _warp(labels, disp, 0)
|
|
202
|
+
missing = support & (nn == 0)
|
|
203
|
+
if missing.any():
|
|
204
|
+
idx = ndi.distance_transform_edt(nn == 0, return_distances=False, return_indices=True)
|
|
205
|
+
nn = np.where(missing, nn[tuple(idx)], nn)
|
|
206
|
+
return np.where(support, nn, 0).astype(np.int32)
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def _scan(baseline: Scan, out_dir: Path, sp: SyntheticParams) -> Scan:
|
|
210
|
+
return Scan(subject=baseline.subject, session=SESSION, time_years=baseline.time_years + sp.dt_years,
|
|
211
|
+
t1=out_dir / "T1w.nii.gz", flair=out_dir / "FLAIR.nii.gz", mask=out_dir / "mask.nii.gz",
|
|
212
|
+
brainmask=out_dir / "brainmask.nii.gz", date="synthetic", scanner=baseline.scanner)
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def _ids(v) -> list[int]:
|
|
216
|
+
if v is None or (isinstance(v, float) and np.isnan(v)):
|
|
217
|
+
return []
|
|
218
|
+
# pandas reads an all-single-id column as float ("1.0"); a multi-id cell is "1,3"
|
|
219
|
+
return [int(float(x)) for x in str(v).replace(";", ",").split(",") if str(x).strip()]
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def light(value, green, amber, kind: str) -> str:
|
|
223
|
+
"""kind: 'min' (higher is better), 'max' (lower is better), 'range' (inside is better)."""
|
|
224
|
+
if value is None or (isinstance(value, float) and np.isnan(value)):
|
|
225
|
+
return "none"
|
|
226
|
+
if kind == "min":
|
|
227
|
+
return "green" if value >= green else "amber" if value >= amber else "red"
|
|
228
|
+
if kind == "max":
|
|
229
|
+
return "green" if value <= green else "amber" if value <= amber else "red"
|
|
230
|
+
lo, hi = green
|
|
231
|
+
alo, ahi = amber
|
|
232
|
+
return "green" if lo <= value <= hi else "amber" if alo <= value <= ahi else "red"
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
def grade(baseline: Scan, syn: Scan, cal_dir: Path, measurement: dict, truth: dict, segmenter: str,
|
|
236
|
+
bands: Bands, threads: int = 4, reference_mask: Path | None = None) -> dict:
|
|
237
|
+
"""Compare the calibration measurement with the injected truth, line by line."""
|
|
238
|
+
from lesiontrack.registration import run_greedy
|
|
239
|
+
|
|
240
|
+
cal_dir = Path(cal_dir)
|
|
241
|
+
lt = cal_dir / "measure" / "lesiontrack"
|
|
242
|
+
fu = measurement["follow_up"]
|
|
243
|
+
if len(measurement["follow_ups"]) != 1:
|
|
244
|
+
raise ValueError("grade expects the calibration measurement to hold exactly one follow-up")
|
|
245
|
+
# Single pair: lesiontrack resliced the follow-up mask with its own halfway matrix (frame=None).
|
|
246
|
+
half = lt / "reg" / f"{fu}_halfway.mat"
|
|
247
|
+
truth_half = cal_dir / "newlesions_truth_halfway.nii.gz"
|
|
248
|
+
run_greedy(f"-d 3 -threads {threads} -rf {baseline.t1} -ri NN -rt short -rm {syn.t1.parent / 'newlesions_truth.nii.gz'} "
|
|
249
|
+
f"{truth_half} -r {half}", cal_dir / "reslice.log")
|
|
250
|
+
tn = np.asarray(nib.load(truth_half).dataobj).astype(np.int32)
|
|
251
|
+
fl = np.asarray(nib.load(lt / f"lesion_labels_{fu}.nii.gz").dataobj).astype(np.int32)
|
|
252
|
+
table = pd.read_csv(lt / "lesion_tracking.tsv", sep="\t", dtype={"baseline_ids": str, "followup_ids": str, "follow_up": str})
|
|
253
|
+
table = table[table["follow_up"].astype(str) == fu]
|
|
254
|
+
new_ids = [i for _, r in table[table["class"] == "new"].iterrows() for i in _ids(r["followup_ids"])]
|
|
255
|
+
frag_ids = [i for _, r in table[table["class"] == "adjacent_fragment"].iterrows() for i in _ids(r["followup_ids"])]
|
|
256
|
+
pred_new = np.isin(fl, new_ids)
|
|
257
|
+
pred_frag = np.isin(fl, frag_ids)
|
|
258
|
+
seg = fl > 0
|
|
259
|
+
per = []
|
|
260
|
+
for les in truth["new_lesions"]:
|
|
261
|
+
sel = tn == les["id"]
|
|
262
|
+
n = int(sel.sum())
|
|
263
|
+
per.append({
|
|
264
|
+
"id": les["id"], "volume_mm3": les["volume_mm3"], "voxels_halfway": n,
|
|
265
|
+
"segmented": bool(seg[sel].any()) if n else False,
|
|
266
|
+
"reported_new": bool(pred_new[sel].any()) if n else False,
|
|
267
|
+
"reported_fragment": bool(pred_frag[sel].any()) if n else False,
|
|
268
|
+
})
|
|
269
|
+
dfp = pd.DataFrame(per, columns=["id", "volume_mm3", "voxels_halfway", "segmented", "reported_new", "reported_fragment"])
|
|
270
|
+
dfp["reported"] = dfp["reported_new"].astype(bool) | dfp["reported_fragment"].astype(bool)
|
|
271
|
+
tn_near = ndi.binary_dilation(tn > 0, structure=ndi.generate_binary_structure(3, 2), iterations=1)
|
|
272
|
+
false_new = [i for i in new_ids if not tn_near[fl == i].any()]
|
|
273
|
+
false_frag = [i for i in frag_ids if not tn_near[fl == i].any()]
|
|
274
|
+
by_size = {}
|
|
275
|
+
for lo, hi, name in ((0, 50, "<50"), (50, 150, "50-150"), (150, 400, "150-400"), (400, 1e9, ">=400")):
|
|
276
|
+
s = dfp[(dfp["volume_mm3"] >= lo) & (dfp["volume_mm3"] < hi)]
|
|
277
|
+
if len(s):
|
|
278
|
+
by_size[name] = {"n": len(s), "reported": int(s["reported"].sum()), "segmented": int(s["segmented"].sum())}
|
|
279
|
+
|
|
280
|
+
# Baseline lesions: the truth for each is its own volume in the synthetic mask (the global
|
|
281
|
+
# factor plus the voxel quantisation of a moved boundary), so a call is judged against the
|
|
282
|
+
# class that truth rate falls in, with lesiontrack's own bands.
|
|
283
|
+
from lesiontrack.config import TrackParams
|
|
284
|
+
from lesiontrack.tracking import classify_rate
|
|
285
|
+
|
|
286
|
+
bl_truth_half = cal_dir / "baselinelesions_truth_halfway.nii.gz"
|
|
287
|
+
run_greedy(f"-d 3 -threads {threads} -rf {baseline.t1} -ri NN -rt short -rm {syn.t1.parent / 'baselinelesions_truth.nii.gz'} "
|
|
288
|
+
f"{bl_truth_half} -r {half}", cal_dir / "reslice.log")
|
|
289
|
+
tb = np.asarray(nib.load(bl_truth_half).dataobj).astype(np.int32)
|
|
290
|
+
lb = np.asarray(nib.load(lt / "baseline_lesion_labels.nii.gz").dataobj).astype(np.int32)
|
|
291
|
+
tinfo = {x["id"]: x for x in truth.get("baseline_lesions", [])}
|
|
292
|
+
dt = truth["dt_years"]
|
|
293
|
+
vox = measurement["voxel_mm3"]
|
|
294
|
+
tp = TrackParams()
|
|
295
|
+
base = table[table["n_baseline"] > 0]
|
|
296
|
+
judged = []
|
|
297
|
+
for _, r in base.iterrows():
|
|
298
|
+
sel = np.isin(lb, _ids(r["baseline_ids"]))
|
|
299
|
+
ids = [int(i) for i in np.unique(tb[sel]) if i > 0 and int(i) in tinfo]
|
|
300
|
+
if not ids:
|
|
301
|
+
continue
|
|
302
|
+
before = sum(tinfo[i]["volume_before_mm3"] for i in ids)
|
|
303
|
+
after = sum(tinfo[i]["volume_after_mm3"] for i in ids)
|
|
304
|
+
if after <= 0:
|
|
305
|
+
t_cls, t_rate = "resolved", -100.0 / dt
|
|
306
|
+
else:
|
|
307
|
+
t_rate = (after - before) / before * 100.0 / dt
|
|
308
|
+
t_cls = classify_rate(t_rate, round((after - before) / vox), tp)
|
|
309
|
+
judged.append({"group_id": int(r["group_id"]), "predicted": str(r["class"]), "truth": t_cls,
|
|
310
|
+
"truth_rate_pct_per_year": t_rate, "predicted_rate_pct_per_year": None if r["class"] == "resolved" else float(r["pct_per_year"]),
|
|
311
|
+
"n_lesions": len(ids)})
|
|
312
|
+
n_base = sum(j["n_lesions"] for j in judged)
|
|
313
|
+
cls = {}
|
|
314
|
+
for j in judged:
|
|
315
|
+
cls[j["predicted"]] = cls.get(j["predicted"], 0) + 1
|
|
316
|
+
changed = {"enlarging", "shrinking"}
|
|
317
|
+
false_change = sum(1 for j in judged if j["predicted"] in changed and j["truth"] not in changed)
|
|
318
|
+
missed_change = sum(1 for j in judged if j["truth"] in changed and j["predicted"] not in changed and j["predicted"] != "resolved")
|
|
319
|
+
false_trend = sum(1 for j in judged if j["predicted"] in ("trend_up", "trend_down") and j["truth"] == "stable")
|
|
320
|
+
false_resolved = sum(1 for j in judged if j["predicted"] == "resolved" and j["truth"] != "resolved")
|
|
321
|
+
agree = sum(1 for j in judged if j["predicted"] == j["truth"])
|
|
322
|
+
truth_changed = sum(1 for j in judged if j["truth"] in changed)
|
|
323
|
+
|
|
324
|
+
inj = truth["injected_brain_change_pct"]
|
|
325
|
+
jac = measurement["brain"]["jacobian"]["change_pct"]
|
|
326
|
+
mr = measurement["brain"]["mask_ratio"]["change_pct"] if measurement["brain"].get("mask_ratio") else None
|
|
327
|
+
n_cand = measurement["sel"]["candidates"]
|
|
328
|
+
base_count = measurement["lesions"]["baseline_count"] or 1
|
|
329
|
+
|
|
330
|
+
seg_grade = None
|
|
331
|
+
if segmenter == "lst-ai":
|
|
332
|
+
seg_grade = _segmentation_grade(baseline, syn, cal_dir, truth, reference_mask)
|
|
333
|
+
|
|
334
|
+
b = bands
|
|
335
|
+
g = {
|
|
336
|
+
"segmenter": segmenter,
|
|
337
|
+
"truth": {k: truth[k] for k in ("volume_factor", "injected_brain_change_pct", "n_new", "new_lesion_volume_mm3", "rigid", "gains", "seed")},
|
|
338
|
+
"new_lesions": {
|
|
339
|
+
"injected": len(dfp),
|
|
340
|
+
"reported_as_new": int(dfp["reported_new"].sum()),
|
|
341
|
+
"reported_as_fragment": int(dfp["reported_fragment"].sum()),
|
|
342
|
+
"reported": int(dfp["reported"].sum()),
|
|
343
|
+
"segmented": int(dfp["segmented"].sum()),
|
|
344
|
+
"sensitivity": float(dfp["reported"].mean()) if len(dfp) else None,
|
|
345
|
+
"smallest_reported_mm3": float(dfp[dfp["reported"]]["volume_mm3"].min()) if dfp["reported"].any() else None,
|
|
346
|
+
"largest_missed_mm3": float(dfp[~dfp["reported"]]["volume_mm3"].max()) if (~dfp["reported"]).any() else None,
|
|
347
|
+
"false_new": len(false_new),
|
|
348
|
+
"false_fragment": len(false_frag),
|
|
349
|
+
"by_size": by_size,
|
|
350
|
+
"per_lesion": per,
|
|
351
|
+
},
|
|
352
|
+
"unchanged_lesions": {
|
|
353
|
+
"n": n_base,
|
|
354
|
+
"groups": len(judged),
|
|
355
|
+
"called_enlarging_or_shrinking": false_change,
|
|
356
|
+
"missed_enlarging_or_shrinking": missed_change,
|
|
357
|
+
"truth_enlarging_or_shrinking": truth_changed,
|
|
358
|
+
"called_trend": false_trend,
|
|
359
|
+
"called_resolved": false_resolved,
|
|
360
|
+
"class_agreement": agree / len(judged) if judged else None,
|
|
361
|
+
"false_change_rate": false_change / len(judged) if judged else None,
|
|
362
|
+
"false_resolved_rate": false_resolved / len(judged) if judged else None,
|
|
363
|
+
"classes": {k: int(v) for k, v in cls.items()},
|
|
364
|
+
"per_group": judged,
|
|
365
|
+
"note": "truth per baseline lesion is its own volume in the synthetic mask; a call is false when it lands "
|
|
366
|
+
"in the enlarging/shrinking band while the truth rate does not, and resolved is false when the lesion is still there",
|
|
367
|
+
},
|
|
368
|
+
"sel": {"candidates": n_cand, "per_baseline_lesion": n_cand / base_count, "truth": 0},
|
|
369
|
+
"brain": {
|
|
370
|
+
"injected_change_pct": inj,
|
|
371
|
+
"jacobian_change_pct": jac,
|
|
372
|
+
"jacobian_recovery": jac / inj if inj else None,
|
|
373
|
+
"mask_ratio_change_pct": mr,
|
|
374
|
+
"mask_ratio_recovery": (mr / inj) if (mr is not None and inj) else None,
|
|
375
|
+
},
|
|
376
|
+
"segmentation": seg_grade,
|
|
377
|
+
}
|
|
378
|
+
# With supplied masks the synthetic follow-up mask contains the injected lesions by construction,
|
|
379
|
+
# so their detection is the annotator's, not the pipeline's: those two lights are not awarded.
|
|
380
|
+
detection_graded = segmenter != "given"
|
|
381
|
+
g["lights"] = {
|
|
382
|
+
"new_sensitivity": light(g["new_lesions"]["sensitivity"], *b.new_sensitivity_min, "min") if detection_graded else "none",
|
|
383
|
+
"false_new": light(g["new_lesions"]["false_new"], *b.false_new_max, "max") if detection_graded else "none",
|
|
384
|
+
"atrophy_recovery": light(g["brain"]["jacobian_recovery"], *b.atrophy_recovery_range, "range"),
|
|
385
|
+
"false_change_rate": light(g["unchanged_lesions"]["false_change_rate"], *b.false_change_rate_max, "max"),
|
|
386
|
+
"false_resolved_rate": light(g["unchanged_lesions"]["false_resolved_rate"], *b.false_resolved_rate_max, "max"),
|
|
387
|
+
"sel_candidates_per_lesion": light(g["sel"]["per_baseline_lesion"], *b.sel_candidates_per_lesion_max, "max"),
|
|
388
|
+
"seg_sensitivity": light(seg_grade["sensitivity"] if seg_grade else None, *b.seg_sensitivity_min, "min"),
|
|
389
|
+
"seg_false_positives": light(seg_grade["false_positive_components"] if seg_grade else None, *b.seg_false_positive_max, "max"),
|
|
390
|
+
}
|
|
391
|
+
g["detection_graded"] = detection_graded
|
|
392
|
+
g["bands"] = bands.__dict__
|
|
393
|
+
with open(cal_dir / "grade.json", "w") as fh:
|
|
394
|
+
json.dump(scrub(g), fh, indent=2, allow_nan=False)
|
|
395
|
+
return g
|
|
396
|
+
|
|
397
|
+
|
|
398
|
+
def scrub(o):
|
|
399
|
+
"""JSON-safe copy: numpy scalars to Python, NaN to None, Paths to str."""
|
|
400
|
+
if isinstance(o, dict):
|
|
401
|
+
return {str(k): scrub(v) for k, v in o.items()}
|
|
402
|
+
if isinstance(o, (list, tuple)):
|
|
403
|
+
return [scrub(v) for v in o]
|
|
404
|
+
if isinstance(o, (np.integer,)):
|
|
405
|
+
return int(o)
|
|
406
|
+
if isinstance(o, (np.floating, float)):
|
|
407
|
+
return None if np.isnan(o) else float(o)
|
|
408
|
+
if isinstance(o, np.bool_):
|
|
409
|
+
return bool(o)
|
|
410
|
+
if isinstance(o, Path):
|
|
411
|
+
return str(o)
|
|
412
|
+
return o
|
|
413
|
+
|
|
414
|
+
|
|
415
|
+
def _segmentation_grade(baseline: Scan, syn: Scan, cal_dir: Path, truth: dict, reference_mask: Path | None) -> dict:
|
|
416
|
+
"""LST-AI on the synthetic follow-up against the injected lesions, old lesions masked out."""
|
|
417
|
+
from bidsgate.score import score_lesions
|
|
418
|
+
|
|
419
|
+
new_truth = syn.t1.parent / "newlesions_truth.nii.gz"
|
|
420
|
+
old = np.asarray(nib.load(syn.t1.parent / "mask.nii.gz").dataobj) > 0
|
|
421
|
+
newl = np.asarray(nib.load(new_truth).dataobj) > 0
|
|
422
|
+
old_only = old & ~newl
|
|
423
|
+
img = nib.load(syn.mask)
|
|
424
|
+
pred = np.asarray(img.dataobj) > 0
|
|
425
|
+
zooms = img.header.get_zooms()[:3]
|
|
426
|
+
near_old = ndi.distance_transform_edt(~old_only, sampling=zooms) <= 2.0
|
|
427
|
+
pred_new_only = pred & ~near_old
|
|
428
|
+
p = cal_dir / "lstai_pred_newonly.nii.gz"
|
|
429
|
+
nib.save(nib.Nifti1Image(pred_new_only.astype(np.uint8), img.affine), p)
|
|
430
|
+
sc = score_lesions(syn.t1.parent / "newlesions_truth.json", new_truth, p)
|
|
431
|
+
out = {k: sc[k] for k in ("dice", "sensitivity", "lesions", "detected", "false_positive_components",
|
|
432
|
+
"false_positive_volume_mm3", "by_size", "volume_ratio")}
|
|
433
|
+
out["note"] = "LST-AI mask of the synthetic follow-up scored against the injected lesions only; " \
|
|
434
|
+
"predicted voxels within 2 mm of a baseline lesion are excluded first"
|
|
435
|
+
if reference_mask is not None and baseline.mask is not None:
|
|
436
|
+
a = np.asarray(nib.load(reference_mask).dataobj) > 0
|
|
437
|
+
b = np.asarray(nib.load(baseline.mask).dataobj) > 0
|
|
438
|
+
out["baseline_reference_dice"] = float(2 * (a & b).sum() / (a.sum() + b.sum())) if (a.sum() + b.sum()) else None
|
|
439
|
+
out["baseline_reference_mask"] = str(reference_mask)
|
|
440
|
+
return out
|
|
441
|
+
|
mscard/cli.py
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
"""mscard command line: run (measure + calibrate + report), calibrate, report."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import json
|
|
7
|
+
import sys
|
|
8
|
+
import traceback
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
from . import __version__
|
|
12
|
+
from .config import Bands, Params, SyntheticParams
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def _params(a: argparse.Namespace) -> Params:
|
|
16
|
+
sp = SyntheticParams()
|
|
17
|
+
over = {k: getattr(a, k) for k in ("volume_factor", "n_new", "seed", "dt_years") if getattr(a, k, None) is not None}
|
|
18
|
+
if over:
|
|
19
|
+
sp = SyntheticParams(**{**sp.__dict__, **over})
|
|
20
|
+
return Params(synthetic=sp, bands=Bands(), threads=a.threads, engine=a.engine)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def run_subject(subject: str, scans: list, out: Path, segmenter: str, params: Params, do_measure: bool,
|
|
24
|
+
do_calibrate: bool, reference_mask: Path | None = None) -> dict:
|
|
25
|
+
from .calibrate import grade, make_synthetic
|
|
26
|
+
from .measure import measure
|
|
27
|
+
from .segment import ensure_masks, lst_ai
|
|
28
|
+
from .spec import ensure_brainmask
|
|
29
|
+
|
|
30
|
+
sub = out / subject
|
|
31
|
+
sub.mkdir(parents=True, exist_ok=True)
|
|
32
|
+
log: list[str] = []
|
|
33
|
+
given_baseline_mask = scans[0].mask
|
|
34
|
+
scans = ensure_masks(scans, segmenter, sub / "segment", params.threads, log)
|
|
35
|
+
status = {"subject": subject}
|
|
36
|
+
if do_measure:
|
|
37
|
+
m = measure(subject, scans, sub / "measure", params.threads, params.engine, log, segmenter)
|
|
38
|
+
status["measure"] = "ok"
|
|
39
|
+
status["interval_years"] = m["interval_years"]
|
|
40
|
+
if do_calibrate:
|
|
41
|
+
baseline = ensure_brainmask(scans[0], sub / "measure" / "brainmask" / f"{scans[0].session}_brainmask.nii.gz", log)
|
|
42
|
+
cal = sub / "calibration"
|
|
43
|
+
syn, truth = make_synthetic(baseline, cal / "synthetic", params.synthetic, log)
|
|
44
|
+
if segmenter == "lst-ai":
|
|
45
|
+
syn = syn.with_mask(lst_ai(syn, cal / "lst-ai", threads=params.threads))
|
|
46
|
+
m2 = measure(subject, [baseline, syn], cal / "measure", params.threads, params.engine, log, segmenter)
|
|
47
|
+
ref = given_baseline_mask if (segmenter == "lst-ai" and given_baseline_mask is not None) else None
|
|
48
|
+
g = grade(baseline, syn, cal, m2, truth, segmenter, params.bands, params.threads, reference_mask=ref)
|
|
49
|
+
status["calibrate"] = "ok"
|
|
50
|
+
status["lights"] = g["lights"]
|
|
51
|
+
(sub / "mscard.log").write_text("\n".join(log) + "\n")
|
|
52
|
+
return status
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def cmd_run(a: argparse.Namespace, do_measure: bool = True, do_calibrate: bool = True) -> int:
|
|
56
|
+
from .report import gallery, render
|
|
57
|
+
from .spec import read_manifest
|
|
58
|
+
|
|
59
|
+
subjects = read_manifest(Path(a.manifest))
|
|
60
|
+
if a.subject:
|
|
61
|
+
want = set(a.subject)
|
|
62
|
+
missing = want - set(subjects)
|
|
63
|
+
if missing:
|
|
64
|
+
raise SystemExit(f"not in manifest: {sorted(missing)}")
|
|
65
|
+
subjects = {k: v for k, v in subjects.items() if k in want}
|
|
66
|
+
if do_calibrate and not do_measure:
|
|
67
|
+
subjects = {k: v[:1] for k, v in subjects.items()}
|
|
68
|
+
out = Path(a.out)
|
|
69
|
+
params = _params(a)
|
|
70
|
+
failed = 0
|
|
71
|
+
for name, scans in subjects.items():
|
|
72
|
+
try:
|
|
73
|
+
st = run_subject(name, scans, out, a.segmenter, params, do_measure, do_calibrate and not a.no_calibrate)
|
|
74
|
+
render(out / name)
|
|
75
|
+
print(f"{name}: {json.dumps(st.get('lights', st))}")
|
|
76
|
+
except Exception as e: # noqa: BLE001 - one subject must not stop the cohort
|
|
77
|
+
failed += 1
|
|
78
|
+
(out / name).mkdir(parents=True, exist_ok=True)
|
|
79
|
+
(out / name / "FAILED.txt").write_text("".join(traceback.format_exception(e)))
|
|
80
|
+
print(f"{name}: FAILED: {e}", file=sys.stderr)
|
|
81
|
+
gallery(out)
|
|
82
|
+
return 1 if failed else 0
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def cmd_report(a: argparse.Namespace) -> int:
|
|
86
|
+
from .report import gallery, render
|
|
87
|
+
|
|
88
|
+
out = Path(a.out)
|
|
89
|
+
subs = [p for p in sorted(out.iterdir()) if (p / "measure" / "mscard.json").exists() or (p / "calibration" / "grade.json").exists()]
|
|
90
|
+
if a.subject:
|
|
91
|
+
subs = [p for p in subs if p.name in set(a.subject)]
|
|
92
|
+
for p in subs:
|
|
93
|
+
render(p)
|
|
94
|
+
print(f"{p.name}: {p / 'report.html'}")
|
|
95
|
+
gallery(out)
|
|
96
|
+
print(f"gallery: {out / 'index.html'}")
|
|
97
|
+
return 0
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def _common(p: argparse.ArgumentParser) -> None:
|
|
101
|
+
p.add_argument("manifest", help="TSV: subject, session, time_years, t1, flair [, mask, brainmask, date, scanner]")
|
|
102
|
+
p.add_argument("--out", required=True)
|
|
103
|
+
p.add_argument("--subject", action="append", help="restrict to these subjects (repeatable)")
|
|
104
|
+
p.add_argument("--segmenter", choices=("given", "lst-ai"), default="given",
|
|
105
|
+
help="'given' uses the manifest's masks; 'lst-ai' runs LST-AI v2 in docker for every scan")
|
|
106
|
+
p.add_argument("--threads", type=int, default=4)
|
|
107
|
+
p.add_argument("--engine", choices=("greedy", "ants"), default="greedy", help="deformable engine (lesiontrack)")
|
|
108
|
+
p.add_argument("--volume-factor", type=float, dest="volume_factor", help="calibration: injected brain volume factor (default 0.98)")
|
|
109
|
+
p.add_argument("--n-new", type=int, dest="n_new", help="calibration: injected new lesions (default 12)")
|
|
110
|
+
p.add_argument("--seed", type=int, help="calibration seed (default 0), mixed with the subject name")
|
|
111
|
+
p.add_argument("--dt-years", type=float, dest="dt_years", help="calibration: modelled interval (default 1.0)")
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def main(argv: list[str] | None = None) -> int:
|
|
115
|
+
ap = argparse.ArgumentParser(prog="mscard", description="The longitudinal MS MRI report that grades itself.")
|
|
116
|
+
ap.add_argument("--version", action="version", version=f"mscard {__version__}")
|
|
117
|
+
sub = ap.add_subparsers(dest="cmd", required=True)
|
|
118
|
+
|
|
119
|
+
r = sub.add_parser("run", help="measure every subject, calibrate the pipeline on each baseline, write reports")
|
|
120
|
+
_common(r)
|
|
121
|
+
r.add_argument("--no-calibrate", action="store_true", help="measure and report without the calibration")
|
|
122
|
+
r.set_defaults(func=lambda a: cmd_run(a, True, True))
|
|
123
|
+
|
|
124
|
+
c = sub.add_parser("calibrate", help="calibration only: synthetic follow-up of each baseline, grade")
|
|
125
|
+
_common(c)
|
|
126
|
+
c.set_defaults(func=lambda a: cmd_run(a, False, True), no_calibrate=False)
|
|
127
|
+
|
|
128
|
+
p = sub.add_parser("report", help="re-render report.html for every subject in an output tree, and the gallery")
|
|
129
|
+
p.add_argument("out")
|
|
130
|
+
p.add_argument("--subject", action="append")
|
|
131
|
+
p.set_defaults(func=cmd_report)
|
|
132
|
+
|
|
133
|
+
a = ap.parse_args(argv)
|
|
134
|
+
return a.func(a)
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
if __name__ == "__main__":
|
|
138
|
+
sys.exit(main())
|
mscard/config.py
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
"""Every threshold mscard uses, in one place, with its origin.
|
|
2
|
+
|
|
3
|
+
The traffic-light bands below are mscard's own working bands for reading a
|
|
4
|
+
calibration. They are not a clinical standard and no standard exists yet for
|
|
5
|
+
"how good must a longitudinal MS pipeline be"; they are stated so the reader
|
|
6
|
+
can disagree with them. Green means the pipeline recovered the injected truth
|
|
7
|
+
well enough that the corresponding number in the report can be read at face
|
|
8
|
+
value; amber means read it with the calibration next to it; red means the
|
|
9
|
+
number is not trustworthy on this scan with this pipeline.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from dataclasses import dataclass, field
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@dataclass(frozen=True)
|
|
16
|
+
class SyntheticParams:
|
|
17
|
+
volume_factor: float = 0.98 # whole-brain volume factor over the synthetic year, -2 %
|
|
18
|
+
falloff_mm: float = 12.0 # bidsgate default: the contraction fades over this distance outside the brain
|
|
19
|
+
n_new: int = 12 # new lesions injected, bidsgate's size cycle 30/80/200/600/1500 mm3
|
|
20
|
+
exclusion_mm: float = 6.0 # new lesions are placed at least this far from every baseline lesion
|
|
21
|
+
rigid_rot_deg: float = 1.0 # small head repositioning between visits (lesiontrack.synth defaults)
|
|
22
|
+
rigid_trans_vox: float = 1.0
|
|
23
|
+
intensity_scale: tuple = (0.9, 1.1) # per-image gain drawn uniformly, models scanner drift
|
|
24
|
+
noise_frac: float = 0.02 # Gaussian noise, fraction of the 99th percentile, inside the head only
|
|
25
|
+
dt_years: float = 1.0
|
|
26
|
+
seed: int = 0
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@dataclass(frozen=True)
|
|
30
|
+
class Bands:
|
|
31
|
+
"""(green_at_least_or_at_most, amber_...) per grade; direction is in the name."""
|
|
32
|
+
|
|
33
|
+
new_sensitivity_min: tuple = (0.90, 0.70)
|
|
34
|
+
false_new_max: tuple = (1, 3)
|
|
35
|
+
atrophy_recovery_range: tuple = ((0.8, 1.2), (0.5, 1.5))
|
|
36
|
+
false_change_rate_max: tuple = (0.05, 0.15) # baseline lesions called enlarging or shrinking when unchanged
|
|
37
|
+
false_resolved_rate_max: tuple = (0.0, 0.05)
|
|
38
|
+
sel_candidates_per_lesion_max: tuple = (0.2, 0.5)
|
|
39
|
+
seg_sensitivity_min: tuple = (0.80, 0.60) # only when mscard ran the segmenter itself
|
|
40
|
+
seg_false_positive_max: tuple = (3, 8)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
@dataclass(frozen=True)
|
|
44
|
+
class Params:
|
|
45
|
+
synthetic: SyntheticParams = field(default_factory=SyntheticParams)
|
|
46
|
+
bands: Bands = field(default_factory=Bands)
|
|
47
|
+
threads: int = 4
|
|
48
|
+
engine: str = "greedy"
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
LST_AI_IMAGE = "jqmcginnis/lst-ai:v2.0.0rc1-cpu"
|