Spaces:
Sleeping
Sleeping
Commit ·
6bc44d6
0
Parent(s):
Squash history: one commit holding the current files
Browse files- .gitattributes +36 -0
- README.md +104 -0
- app.py +92 -0
- data/DiSCo_Connectivity_Matrix_Cross-Sectional_Area.txt +16 -0
- data/DiSCo_Connectivity_Matrix_Strands_Count.txt +16 -0
- data/DiSCo_ROIs.nii.gz +3 -0
- data/DiSCo_Strands_Diameters.txt +0 -0
- data/DiSCo_Strands_Trajectories.tck +3 -0
- data/DiSCo_gradients.bvals +1 -0
- data/DiSCo_gradients_dipy.bvecs +3 -0
- data/DiSCo_mask.nii.gz +3 -0
- data/SOURCE.md +16 -0
- pyproject.toml +3 -0
- requirements.txt +23 -0
- space/__init__.py +1 -0
- space/app.py +748 -0
- space/brain.toml +175 -0
- space/config.toml +132 -0
- space/limits.py +63 -0
- space/pipeline.py +1171 -0
- space/sources/__init__.py +24 -0
- space/sources/brain.py +1475 -0
- space/sources/disco.py +590 -0
- space/viewers.py +320 -0
- tests/test_acceptance.py +107 -0
- tests/test_app.py +285 -0
- tests/test_brain.py +820 -0
- tests/test_build_brain_asset.py +222 -0
- tests/test_build_parcellation.py +76 -0
- tests/test_limits.py +37 -0
- tests/test_no_private_identifiers.py +48 -0
- tests/test_pipeline.py +380 -0
- tests/test_viewers.py +81 -0
- tools/build_brain_asset.py +370 -0
- tools/build_brain_fixture.py +139 -0
- tools/build_parcellation.py +233 -0
- tools/deploy.py +106 -0
- tools/gate_job.py +50 -0
- tools/live.py +69 -0
- tools/measure_brain.py +184 -0
- tools/measure_scanners.py +73 -0
- tools/scanner_brain_bmap.py +60 -0
- tools/scanner_disco_effects.py +54 -0
- tools/scanner_disco_terms.py +36 -0
- tools/stamp_disco_background.py +30 -0
.gitattributes
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
*.7z filter=lfs diff=lfs merge=lfs -text
|
| 2 |
+
*.arrow filter=lfs diff=lfs merge=lfs -text
|
| 3 |
+
*.bin filter=lfs diff=lfs merge=lfs -text
|
| 4 |
+
*.bz2 filter=lfs diff=lfs merge=lfs -text
|
| 5 |
+
*.ckpt filter=lfs diff=lfs merge=lfs -text
|
| 6 |
+
*.ftz filter=lfs diff=lfs merge=lfs -text
|
| 7 |
+
*.gz filter=lfs diff=lfs merge=lfs -text
|
| 8 |
+
*.h5 filter=lfs diff=lfs merge=lfs -text
|
| 9 |
+
*.joblib filter=lfs diff=lfs merge=lfs -text
|
| 10 |
+
*.lfs.* filter=lfs diff=lfs merge=lfs -text
|
| 11 |
+
*.mlmodel filter=lfs diff=lfs merge=lfs -text
|
| 12 |
+
*.model filter=lfs diff=lfs merge=lfs -text
|
| 13 |
+
*.msgpack filter=lfs diff=lfs merge=lfs -text
|
| 14 |
+
*.npy filter=lfs diff=lfs merge=lfs -text
|
| 15 |
+
*.npz filter=lfs diff=lfs merge=lfs -text
|
| 16 |
+
*.onnx filter=lfs diff=lfs merge=lfs -text
|
| 17 |
+
*.ot filter=lfs diff=lfs merge=lfs -text
|
| 18 |
+
*.parquet filter=lfs diff=lfs merge=lfs -text
|
| 19 |
+
*.pb filter=lfs diff=lfs merge=lfs -text
|
| 20 |
+
*.pickle filter=lfs diff=lfs merge=lfs -text
|
| 21 |
+
*.pkl filter=lfs diff=lfs merge=lfs -text
|
| 22 |
+
*.pt filter=lfs diff=lfs merge=lfs -text
|
| 23 |
+
*.pth filter=lfs diff=lfs merge=lfs -text
|
| 24 |
+
*.rar filter=lfs diff=lfs merge=lfs -text
|
| 25 |
+
*.safetensors filter=lfs diff=lfs merge=lfs -text
|
| 26 |
+
saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
| 27 |
+
*.tar.* filter=lfs diff=lfs merge=lfs -text
|
| 28 |
+
*.tar filter=lfs diff=lfs merge=lfs -text
|
| 29 |
+
*.tflite filter=lfs diff=lfs merge=lfs -text
|
| 30 |
+
*.tgz filter=lfs diff=lfs merge=lfs -text
|
| 31 |
+
*.wasm filter=lfs diff=lfs merge=lfs -text
|
| 32 |
+
*.xz filter=lfs diff=lfs merge=lfs -text
|
| 33 |
+
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
+
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
+
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 36 |
+
data/DiSCo_Strands_Trajectories.tck filter=lfs diff=lfs merge=lfs -text
|
README.md
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
title: "Brain replay: MASiVar"
|
| 3 |
+
emoji: 🧠
|
| 4 |
+
colorFrom: indigo
|
| 5 |
+
colorTo: blue
|
| 6 |
+
sdk: gradio
|
| 7 |
+
sdk_version: 6.28.0
|
| 8 |
+
app_file: app.py
|
| 9 |
+
pinned: false
|
| 10 |
+
startup_duration_timeout: 1h
|
| 11 |
+
license: mit
|
| 12 |
+
short_description: A real brain replayed from packs, to an 84-region connectome
|
| 13 |
+
---
|
| 14 |
+
|
| 15 |
+
# The brain Space on ZeroGPU
|
| 16 |
+
|
| 17 |
+
The same application as `rfick/disco-zero` (dmrai-lab/disco-space), serving `space/brain.toml` (`DISCO_CONFIG`):
|
| 18 |
+
a real brain as a compositional replay phantom. The input is the multi-tissue CSD of one scan, MASiVar `sub-cIs1`
|
| 19 |
+
(OpenNeuro ds003416, Cai et al. MRM 2021, CC0): its white-matter FOD field, its WM / GM / CSF fractions and an
|
| 20 |
+
84-region parcellation, made once offline and published as the dataset `SubstrateCommons/masivar-brain`. Each run
|
| 21 |
+
composes every brain voxel from two replay packs (CACTUS axons for WM, packed spheres for GM; free water in closed
|
| 22 |
+
form for CSF) at the chosen acquisition, tissue and scanner, adds Rician noise, estimates the tissue responses from
|
| 23 |
+
the replayed data, fits CSD, tracks from the white matter and scores the 84 x 84 connectome (and its 14 lobar groups)
|
| 24 |
+
against the connectome of the input FOD tracked with the same tracker, settings, seeds and key. Source and pins:
|
| 25 |
+
https://github.com/dmrai-lab/disco-space (`requirements-zero.txt`, `app.py`, `space/sources/brain.py`).
|
| 26 |
+
|
| 27 |
+
**The scanner.** The menu holds the ideal scanner and two catalogued machines, the Siemens Prisma 3 T and Terra 7 T,
|
| 28 |
+
each played at every voxel as it delivers there with the head centre at isocentre (voxels binned into encoding
|
| 29 |
+
classes at 1 % of b). The Hyperfine Swoop 64 mT is not on this menu, and the page says why under it: its own gradient
|
| 30 |
+
is exact in dmipy-sim's closed form, but it bins this head into 9,752 classes at 2-3 minutes each
|
| 31 |
+
(`docs/scanner.md`). The DiSCo Spaces play it exactly.
|
| 32 |
+
|
| 33 |
+
**Where the work runs.** The packs' pose responses (the only physics that depends on the tissue and the field) are
|
| 34 |
+
computed on the CPU and kept in the page's process for the container's lifetime per pack, protocol, tissue and field:
|
| 35 |
+
for every preset (with its ladder) and the scan's protocol at every field preset when the container starts, for any
|
| 36 |
+
other run inside its GPU call (the page only looks its cache up before the call, so the call follows the request at
|
| 37 |
+
once; ZeroGPU's proxy token expires when the call comes late), after which the page keeps them too. Inside the call,
|
| 38 |
+
torch contracts them with
|
| 39 |
+
every voxel's FOD, fractions and proton densities (voxels x measurements x 45), then the noise, the reconstruction
|
| 40 |
+
(dmipy-fit), the tracking and the truth's tracking (dmipy-tract), the scoring. Deterministic algorithms are on and
|
| 41 |
+
TF32 off inside the call.
|
| 42 |
+
|
| 43 |
+
## GPU quota per visitor
|
| 44 |
+
|
| 45 |
+
Every run reserves the GPU for the seconds the page shows under the run button. ZeroGPU charges that reservation
|
| 46 |
+
against the *visitor's* daily quota, not the Space's: 2 minutes logged out, 5 with a free Hugging Face account, 40
|
| 47 |
+
with PRO; a single request above the visitor's quota is refused before it starts, and a run that outlives its
|
| 48 |
+
reservation is killed. Only the device part of a run holds the GPU, with the packs' responses the page has not
|
| 49 |
+
cached (part of the reservation shown, which falls once a run has cached them); the page's files and figures after
|
| 50 |
+
it do not.
|
| 51 |
+
|
| 52 |
+
Not re-measured at the current pins (dmipy-sim 1b79d2e; the tables below name their own). Measured on an L40S with the BATMAN development fixture (96 x 96 x 60 at 2.5 mm, 90,205 brain voxels, 36,605 in the
|
| 53 |
+
WM stop mask; dmipy-sim 7f6f1fa, dmipy-fit 0c7dde8 with the single-tissue reconstruction, dmipy-tract 7da22c3;
|
| 54 |
+
`tools/measure_brain.py`, 2026-09-30), steady state, seconds:
|
| 55 |
+
|
| 56 |
+
| stage | 113 measurements | 495 measurements (five shells x 96) |
|
| 57 |
+
|---|---|---|
|
| 58 |
+
| the packs' responses, every tier, on the host CPU (not charged) | 4.9-6.1 (8 threads) | 7.5-7.9 (8 threads) |
|
| 59 |
+
| the replay (the contraction on the device) | 0.04 | 0.17 |
|
| 60 |
+
| noise | 0.35 | 1.4 |
|
| 61 |
+
| reconstruction (single-tissue: tournier07 response + CSD) | 3.7 | 8.0 |
|
| 62 |
+
| the round trip against the input FOD | 0.85 | 0.85 |
|
| 63 |
+
| tracking, density 1 / 2 / 4 (36,605 / 292,840 / 2,342,720 seeds) | 0.7 / 1.9 / 13.6 | 0.7 / 1.9 / 13.6-16.4 |
|
| 64 |
+
| the truth's tracking, density 1 / 2 / 4 | 0.8 / 2.1 / 14.8 | 0.7 / 2.1 / 23.2 |
|
| 65 |
+
| the ladder (three rungs of contraction) | 0.07 | 0.5 |
|
| 66 |
+
|
| 67 |
+
The reservation (`space/brain.toml`, `[budget]`) is each device stage x 1.5 for the pool, 12 s for the worker's
|
| 68 |
+
start and the handoff, times 1.3: at the default density 2 and 495 measurements, A alone 49 s, A with the ladder 50
|
| 69 |
+
s, A + B + ladder 79 s, so every default configuration with one B fits a logged-out visitor's 2 minutes; density 4
|
| 70 |
+
reserves 131 s for A alone and is for logged-in visitors.
|
| 71 |
+
|
| 72 |
+
**Measured on the pool** (`tools/live.py rfick/brain-zero --config brain.toml`, 2026-10-01, the MASiVar asset at
|
| 73 |
+
revision 2 unless the row says revision 3: 71,052 brain voxels, the scan's own protocol of 485 measurements, density 2, 3 T along the bore, every
|
| 74 |
+
tier, SNR 30 at M0 = 1, the multi-tissue reconstruction; the packs' responses cached on the page):
|
| 75 |
+
|
| 76 |
+
| run | reserved | device held | handoff to the page | wall through the API | connectome Pearson log(1 + count) vs the input's |
|
| 77 |
+
|---|---|---|---|---|---|
|
| 78 |
+
| A + ladder | 50 s | 13.6 s | 4.5 s | 103 s | 0.903 (lobar 0.980), 228,760 streamlines |
|
| 79 |
+
| A + B (field → 7 T) + ladder | 78 s | 22.1 s | 6.6 s | 149 s | A 0.903, B 0.889, A vs B 0.962 |
|
| 80 |
+
| A + ladder, the windowed WM pack (`single_bundle_1s_c3_seg125ms`, window 0 of 8; 2026-10-01 13:10, logged out) | 50 s | 13.9 s | 4.7 s | 96 s | 0.893 (lobar 0.975); the container served after 22 s, its warm-up in a process beside the page |
|
| 81 |
+
| A + B (every shell's pulse timing → long-TE δ 30 / Δ 120 ms, TE 160 ms: two windows of both packs) + ladder (2026-10-01 14:55, logged out, the responses cached by the warm-up) | 78 s | 22.8 s | 6.8 s | 362 s (the pool's queue included) | A 0.893, B 0.839 (lobar 0.949; the median voxel's b = 0 SNR falls from 7.0 to 3.7 at TE 160 ms), A vs B 0.943 |
|
| 82 |
+
| A + ladder on **revision 3** of the asset (the responses from the eroded mask, Tournier 2013; 2026-10-01 16:20, with an account token: a logged-out address has two runs a day) | 50 s | 13.4 s | 4.5 s | 81 s | 0.932 (lobar 0.981); the FOD round trip against the new truth: principal peak 46.5° median, AFD r 0.826 (the truth now holds 5,498 two-peak WM voxels against 2,272) |
|
| 83 |
+
| A + ladder on **revision 2 of the WM pack** (built from the kept walks, each window's own contact channel, no contact envelope; dmipy-sim#528; 2026-10-02 00:03, account token, the page's cache warm) | 50 s | 22.9 s of compute | — | 96 s | 0.930 (lobar 0.983), the same to the third digit as on the resegmented cut |
|
| 84 |
+
|
| 85 |
+
**The warm-up's timeline** (Space commit 44fa8da7, 2026-10-01 18:06 UTC: 32 entries, one per response; the container
|
| 86 |
+
has 192 CPUs visible and a cgroup quota of 16, 104 GB; RSS 4-15 GB): the default run's responses 42 s after the process
|
| 87 |
+
started, every preset with its ladder by 2.5 min, the one-window knobs by 7 min, the first two-window class at 9 min
|
| 88 |
+
(112 s: its band's coupling tables are built once per container), the second at 9.5 min, then the field presets in
|
| 89 |
+
ascending field. Until an entry is cached, a run asking for it computes it inside its own reservation at the cold
|
| 90 |
+
price; a logged-out visitor's 120 s then holds the default run from the first minute, a two-window class once the
|
| 91 |
+
warm-up reaches it, and another field once that field is cached. Before dmipy-sim#532 the first two-window entry took
|
| 92 |
+
1292 s on this pool (1217 s of it page faults in the field factor's numpy route) and the 11.7 T band 936 s.
|
| 93 |
+
|
| 94 |
+
Device stages of A at 485 measurements on the pool: replay 0.3 s, noise 1.7, the three-tissue responses 1.2,
|
| 95 |
+
MT-CSD 3.1, the round trip 1.2, tracking 2.5, the truth's tracking 2.3 (B reuses A's). The page then spends 9-17 s
|
| 96 |
+
writing files and 4-6 s on states and figures, outside the reservation.
|
| 97 |
+
|
| 98 |
+
The payload that crosses from the GPU worker back to the page is one Result per run (the DWI before and after the
|
| 99 |
+
noise in float32 on the brain's bounding box, the FOD field, the streamlines): 1.5 GB per run at 495 measurements and
|
| 100 |
+
density 2 (0.27 GB of it streamlines; 3.4 GB at density 4), plus the ladder's rungs; the pool hands it off in 4.5 s
|
| 101 |
+
for A alone and 6.6 s for A + B.
|
| 102 |
+
|
| 103 |
+
The truth connectome is reproducible bit for bit at one key; between two keys at the same density its Pearson of
|
| 104 |
+
log(1 + count) over the 3,486 region pairs is 0.834 / 0.945 / 0.982 at density 1 / 2 / 4, the floor of the score.
|
app.py
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""The ZeroGPU entry (disco-space#2): the same page as ``space/app.py`` on Hugging Face's shared GPU pool, which runs
|
| 2 |
+
PyTorch only and gives a GPU to a call decorated with ``spaces.GPU`` for its duration: here the compute alone (with
|
| 3 |
+
the source's share a run needs that the page has not cached, a brain's pack responses, so the call is entered as soon
|
| 4 |
+
as the request arrives); the cache lookup before it and the page's drawing and files after it stay in this process
|
| 5 |
+
(disco-space#7). The configuration is ``DISCO_CONFIG`` (``space/config.toml``, the DiSCo Space, unless the
|
| 6 |
+
Space sets another: ``brain.toml`` for the brain Space). The compute backend is torch (``DISCO_BACKEND=torch``), the
|
| 7 |
+
layout's tiles are rebuilt on the device inside every call (``resident = false``: nothing survives between calls),
|
| 8 |
+
deterministic algorithms are on and TF32 off inside the call. The source's data come from the Hub at the config's
|
| 9 |
+
revision, downloaded once when the container starts (the parent process loads it before the page serves; the forked
|
| 10 |
+
GPU worker inherits it). ``spaces`` must be imported before torch."""
|
| 11 |
+
import os
|
| 12 |
+
|
| 13 |
+
os.environ.setdefault("DISCO_BACKEND", "torch")
|
| 14 |
+
os.environ.setdefault("DISCO_RESIDENT", "0") # the pool drops the device between calls: tiles rebuilt per call
|
| 15 |
+
os.environ.setdefault("JAX_PLATFORMS", "cpu") # jax is a library dependency here; it never sees the GPU
|
| 16 |
+
|
| 17 |
+
from space.limits import cap_threads, cap_affinity # noqa: E402 (no numpy behind it)
|
| 18 |
+
cap_threads() # BLAS / OpenMP threads = the cgroup's CPU quota, not the 192 CPUs the pool shows
|
| 19 |
+
cap_affinity() # and the CPUs the process may run on, which sizes XLA's and torch's pools
|
| 20 |
+
|
| 21 |
+
import spaces # noqa: E402 (before torch, as ZeroGPU requires)
|
| 22 |
+
import torch # noqa: E402
|
| 23 |
+
|
| 24 |
+
from space import app as A # noqa: E402
|
| 25 |
+
|
| 26 |
+
def gpu_runner(fn):
|
| 27 |
+
"""``fn`` (:func:`space.app.compute`) under the GPU for the seconds :func:`space.app.estimated_seconds` reads off
|
| 28 |
+
the inputs (``DISCO_GPU_SECONDS`` overrides with a fixed number), deterministic, full precision. Its first
|
| 29 |
+
argument is the source's share of the run the page has cached (:func:`space.app.prepare_runs`, a lookup), the
|
| 30 |
+
page's inputs follow. A generator: its stage texts and its payload cross from the worker to the page's process,
|
| 31 |
+
where the page draws and writes files after the device is released."""
|
| 32 |
+
fixed = os.environ.get("DISCO_GPU_SECONDS")
|
| 33 |
+
duration = (lambda *args, **kw: int(fixed)) if fixed else (lambda prepared, *args, **kw: A.estimated_seconds(*args))
|
| 34 |
+
|
| 35 |
+
@spaces.GPU(duration=duration)
|
| 36 |
+
def run(*args):
|
| 37 |
+
torch.use_deterministic_algorithms(True)
|
| 38 |
+
torch.backends.cuda.matmul.allow_tf32 = False
|
| 39 |
+
torch.backends.cudnn.allow_tf32 = False
|
| 40 |
+
yield from fn(*args)
|
| 41 |
+
return run
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
@spaces.GPU(duration=60)
|
| 45 |
+
def probe():
|
| 46 |
+
"""What the GPU worker sees: the device, the memory, the layout's files and how fast they read (an API endpoint
|
| 47 |
+
for the deployment check, `/probe`)."""
|
| 48 |
+
import glob, json, time
|
| 49 |
+
import numpy as np
|
| 50 |
+
st = A._load(); src = st["source"]; where = getattr(getattr(src, "moments", None), "path", "")
|
| 51 |
+
out = dict(torch=torch.__version__, cuda=torch.cuda.is_available(), device=torch.cuda.get_device_name(0) if torch.cuda.is_available() else None,
|
| 52 |
+
gpu_memory_gb=round(torch.cuda.get_device_properties(0).total_memory / 1e9, 1) if torch.cuda.is_available() else None,
|
| 53 |
+
layout=where, data=sorted(os.path.basename(p) for p in glob.glob(os.path.join(where, "*")))[:12], backend=os.environ.get("DISCO_BACKEND"),
|
| 54 |
+
resident=os.environ.get("DISCO_RESIDENT"), load_seconds=round(st.get("load_seconds", float("nan")), 1), error=st.get("error"),
|
| 55 |
+
cpus=len(os.sched_getaffinity(0)), cpu_count=os.cpu_count())
|
| 56 |
+
try:
|
| 57 |
+
with open("/proc/meminfo") as f:
|
| 58 |
+
mem = dict(l.split(":") for l in f.read().splitlines() if ":" in l)
|
| 59 |
+
out["host_ram_total_gb"] = round(int(mem["MemTotal"].split()[0]) / 1e6, 1); out["host_ram_available_gb"] = round(int(mem["MemAvailable"].split()[0]) / 1e6, 1)
|
| 60 |
+
except Exception as e:
|
| 61 |
+
out["meminfo"] = repr(e)[:100]
|
| 62 |
+
files = sorted(glob.glob(os.path.join(where, "m_*.npy")))
|
| 63 |
+
if files:
|
| 64 |
+
t0 = time.perf_counter(); m = np.load(files[0], mmap_mode="r"); chunk = np.array(m[:100000]); dt = time.perf_counter() - t0
|
| 65 |
+
out["read_mb"] = round(chunk.nbytes / 1e6, 1); out["read_mb_per_s"] = round(chunk.nbytes / 1e6 / dt, 1)
|
| 66 |
+
t0 = time.perf_counter(); torch.as_tensor(chunk, device="cuda"); torch.cuda.synchronize(); out["upload_mb_per_s"] = round(chunk.nbytes / 1e6 / (time.perf_counter() - t0), 1)
|
| 67 |
+
# the moment image inside this worker: the first compiled call, a second one (the kernel alone), the eager kernel
|
| 68 |
+
try:
|
| 69 |
+
from dmipy_sim.replay import shape_moments as SM
|
| 70 |
+
kernel = dict(SM._TORCH_KERNEL)
|
| 71 |
+
b = np.full(184, 1e9); u = np.tile([0.6, 0.0, 0.8], (184, 1)); name = "d10.2-D16.7"
|
| 72 |
+
try:
|
| 73 |
+
t0 = time.perf_counter(); src.moments.image(name, b, u, backend="torch", resident=True); torch.cuda.synchronize(); out["image_first_compiled_s"] = round(time.perf_counter() - t0, 2)
|
| 74 |
+
t0 = time.perf_counter(); src.moments.image(name, b, u, backend="torch", resident=True); torch.cuda.synchronize(); out["image_second_compiled_s"] = round(time.perf_counter() - t0, 2)
|
| 75 |
+
SM._TORCH_KERNEL["fn"] = SM._tile_sums_torch
|
| 76 |
+
t0 = time.perf_counter(); src.moments.image(name, b, u, backend="torch", resident=True); torch.cuda.synchronize(); out["image_eager_s"] = round(time.perf_counter() - t0, 2)
|
| 77 |
+
t0 = time.perf_counter(); src.moments.image(name, b, u, backend="torch", resident=False); torch.cuda.synchronize(); out["image_eager_nonresident_s"] = round(time.perf_counter() - t0, 2)
|
| 78 |
+
finally:
|
| 79 |
+
SM._TORCH_KERNEL.update(kernel) # the probe leaves the kernel as it found it
|
| 80 |
+
except Exception as e:
|
| 81 |
+
out["image_probe_error"] = repr(e)[:300]
|
| 82 |
+
return json.dumps(out)
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
if __name__ == "__main__":
|
| 86 |
+
import gradio as gr
|
| 87 |
+
A._load() # the layout from the Hub, once per container, on the CPU side
|
| 88 |
+
demo = A.build(runner=gpu_runner)
|
| 89 |
+
with demo:
|
| 90 |
+
probe_out = gr.Textbox(visible=False)
|
| 91 |
+
gr.Button("probe", visible=False).click(probe, outputs=probe_out, api_name="probe")
|
| 92 |
+
demo.queue(max_size=16).launch()
|
data/DiSCo_Connectivity_Matrix_Cross-Sectional_Area.txt
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 2.162871270396190052e-03 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 2.189675997158816757e-03
|
| 2 |
+
0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.997585422976351933e-03 0.000000000000000000e+00 7.175606107097754014e-04 0.000000000000000000e+00 1.655100351998834872e-03 2.387440308015482265e-03 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00
|
| 3 |
+
0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.924395670360410813e-03 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 2.654596172406068107e-03 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00
|
| 4 |
+
2.162871270396190052e-03 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 2.628305165746386285e-03 0.000000000000000000e+00 0.000000000000000000e+00 2.635616648843574703e-03 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.886968137806108257e-03 0.000000000000000000e+00
|
| 5 |
+
0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 2.534360857737260383e-03 2.374712365275239920e-03 1.137071191188254162e-03 0.000000000000000000e+00 9.664784118105288185e-04 0.000000000000000000e+00 1.700001026067903291e-03 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00
|
| 6 |
+
0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 2.534360857737260383e-03 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.729937622254859586e-03 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 2.033450045316130637e-03 1.732738504881186714e-03 0.000000000000000000e+00 0.000000000000000000e+00
|
| 7 |
+
0.000000000000000000e+00 1.997585422976351933e-03 0.000000000000000000e+00 2.628305165746386285e-03 2.374712365275239920e-03 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00
|
| 8 |
+
0.000000000000000000e+00 0.000000000000000000e+00 1.924395670360410813e-03 0.000000000000000000e+00 1.137071191188254162e-03 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00
|
| 9 |
+
0.000000000000000000e+00 7.175606107097754014e-04 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.729937622254859586e-03 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.824011182415068676e-03 0.000000000000000000e+00 0.000000000000000000e+00 3.198598066436200379e-04 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00
|
| 10 |
+
0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 2.635616648843574703e-03 9.664784118105288185e-04 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.824011182415068676e-03 0.000000000000000000e+00 0.000000000000000000e+00 2.515545329756637034e-03 0.000000000000000000e+00 1.331434494278619166e-03 0.000000000000000000e+00 0.000000000000000000e+00
|
| 11 |
+
0.000000000000000000e+00 1.655100351998834872e-03 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.339352492098972499e-03 0.000000000000000000e+00
|
| 12 |
+
0.000000000000000000e+00 2.387440308015482265e-03 0.000000000000000000e+00 0.000000000000000000e+00 1.700001026067903291e-03 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 2.515545329756637034e-03 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00
|
| 13 |
+
0.000000000000000000e+00 0.000000000000000000e+00 2.654596172406068107e-03 0.000000000000000000e+00 0.000000000000000000e+00 2.033450045316130637e-03 0.000000000000000000e+00 0.000000000000000000e+00 3.198598066436200379e-04 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.635685597106705663e-03
|
| 14 |
+
0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.732738504881186714e-03 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.331434494278619166e-03 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00
|
| 15 |
+
0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.886968137806108257e-03 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.339352492098972499e-03 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00
|
| 16 |
+
2.189675997158816757e-03 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.635685597106705663e-03 0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00
|
data/DiSCo_Connectivity_Matrix_Strands_Count.txt
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
0 0 0 535 0 0 0 0 0 0 0 0 0 0 0 579
|
| 2 |
+
0 0 0 0 0 0 537 0 198 0 431 625 0 0 0 0
|
| 3 |
+
0 0 0 0 0 0 0 539 0 0 0 0 711 0 0 0
|
| 4 |
+
535 0 0 0 0 0 733 0 0 669 0 0 0 0 490 0
|
| 5 |
+
0 0 0 0 0 672 640 298 0 259 0 417 0 0 0 0
|
| 6 |
+
0 0 0 0 672 0 0 0 465 0 0 0 546 479 0 0
|
| 7 |
+
0 537 0 733 640 0 0 0 0 0 0 0 0 0 0 0
|
| 8 |
+
0 0 539 0 298 0 0 0 0 0 0 0 0 0 0 0
|
| 9 |
+
0 198 0 0 0 465 0 0 0 472 0 0 88 0 0 0
|
| 10 |
+
0 0 0 669 259 0 0 0 472 0 0 660 0 349 0 0
|
| 11 |
+
0 431 0 0 0 0 0 0 0 0 0 0 0 0 355 0
|
| 12 |
+
0 625 0 0 417 0 0 0 0 660 0 0 0 0 0 0
|
| 13 |
+
0 0 711 0 0 546 0 0 88 0 0 0 0 0 0 449
|
| 14 |
+
0 0 0 0 0 479 0 0 0 349 0 0 0 0 0 0
|
| 15 |
+
0 0 0 490 0 0 0 0 0 0 355 0 0 0 0 0
|
| 16 |
+
579 0 0 0 0 0 0 0 0 0 0 0 449 0 0 0
|
data/DiSCo_ROIs.nii.gz
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:c01ad8a759a83bff332d08ce0455fb13082cc6bbc036ae9eb2dd8329cd2fc5a4
|
| 3 |
+
size 3565
|
data/DiSCo_Strands_Diameters.txt
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
data/DiSCo_Strands_Trajectories.tck
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:92176064b9170a2e252ddc39f91d6c45b6cb82acfb6996d56c7191e4df5085df
|
| 3 |
+
size 7936217
|
data/DiSCo_gradients.bvals
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
0.000 13191.533 13191.533 13191.533 13191.533 13191.533 13191.533 13191.533 13191.533 13191.533 13191.533 13191.533 13191.533 13191.533 13191.533 13191.533 13191.533 13191.533 13191.533 13191.533 13191.533 13191.533 13191.533 13191.533 13191.533 13191.533 13191.533 13191.533 13191.533 13191.533 13191.533 13191.533 13191.533 13191.533 13191.533 13191.533 13191.533 13191.533 13191.533 13191.533 13191.533 13191.533 13191.533 13191.533 13191.533 13191.533 13191.533 13191.533 13191.533 13191.533 13191.533 13191.533 13191.533 13191.533 13191.533 13191.533 13191.533 13191.533 13191.533 13191.533 13191.533 13191.533 13191.533 13191.533 13191.533 13191.533 13191.533 13191.533 13191.533 13191.533 13191.533 13191.533 13191.533 13191.533 13191.533 13191.533 13191.533 13191.533 13191.533 13191.533 13191.533 13191.533 13191.533 13191.533 13191.533 13191.533 13191.533 13191.533 13191.533 13191.533 13191.533 0.000 1925.435 1925.435 1925.435 1925.435 1925.435 1925.435 1925.435 1925.435 1925.435 1925.435 1925.435 1925.435 1925.435 1925.435 1925.435 1925.435 1925.435 1925.435 1925.435 1925.435 1925.435 1925.435 1925.435 1925.435 1925.435 1925.435 1925.435 1925.435 1925.435 1925.435 1925.435 1925.435 1925.435 1925.435 1925.435 1925.435 1925.435 1925.435 1925.435 1925.435 1925.435 1925.435 1925.435 1925.435 1925.435 1925.435 1925.435 1925.435 1925.435 1925.435 1925.435 1925.435 1925.435 1925.435 1925.435 1925.435 1925.435 1925.435 1925.435 1925.435 1925.435 1925.435 1925.435 1925.435 1925.435 1925.435 1925.435 1925.435 1925.435 1925.435 1925.435 1925.435 1925.435 1925.435 1925.435 1925.435 1925.435 1925.435 1925.435 1925.435 1925.435 1925.435 1925.435 1925.435 1925.435 1925.435 1925.435 1925.435 1925.435 1925.435 0.000 3093.884 3093.884 3093.884 3093.884 3093.884 3093.884 3093.884 3093.884 3093.884 3093.884 3093.884 3093.884 3093.884 3093.884 3093.884 3093.884 3093.884 3093.884 3093.884 3093.884 3093.884 3093.884 3093.884 3093.884 3093.884 3093.884 3093.884 3093.884 3093.884 3093.884 3093.884 3093.884 3093.884 3093.884 3093.884 3093.884 3093.884 3093.884 3093.884 3093.884 3093.884 3093.884 3093.884 3093.884 3093.884 3093.884 3093.884 3093.884 3093.884 3093.884 3093.884 3093.884 3093.884 3093.884 3093.884 3093.884 3093.884 3093.884 3093.884 3093.884 3093.884 3093.884 3093.884 3093.884 3093.884 3093.884 3093.884 3093.884 3093.884 3093.884 3093.884 3093.884 3093.884 3093.884 3093.884 3093.884 3093.884 3093.884 3093.884 3093.884 3093.884 3093.884 3093.884 3093.884 3093.884 3093.884 3093.884 3093.884 3093.884 3093.884 0.000 1000.011 1000.011 1000.011 1000.011 1000.011 1000.011 1000.011 1000.011 1000.011 1000.011 1000.011 1000.011 1000.011 1000.011 1000.011 1000.011 1000.011 1000.011 1000.011 1000.011 1000.011 1000.011 1000.011 1000.011 1000.011 1000.011 1000.011 1000.011 1000.011 1000.011 1000.011 1000.011 1000.011 1000.011 1000.011 1000.011 1000.011 1000.011 1000.011 1000.011 1000.011 1000.011 1000.011 1000.011 1000.011 1000.011 1000.011 1000.011 1000.011 1000.011 1000.011 1000.011 1000.011 1000.011 1000.011 1000.011 1000.011 1000.011 1000.011 1000.011 1000.011 1000.011 1000.011 1000.011 1000.011 1000.011 1000.011 1000.011 1000.011 1000.011 1000.011 1000.011 1000.011 1000.011 1000.011 1000.011 1000.011 1000.011 1000.011 1000.011 1000.011 1000.011 1000.011 1000.011 1000.011 1000.011 1000.011 1000.011 1000.011 1000.011
|
data/DiSCo_gradients_dipy.bvecs
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
0.000000000000000000e+00 8.763600000000000279e-01 2.554899999999999949e-01 1.436999999999999944e-01 -1.044500000000000012e-01 1.660800000000000054e-01 -1.897699999999999942e-01 -9.580100000000000282e-01 1.473000000000000004e-02 -1.668999999999999997e-02 -6.403600000000000403e-01 5.072499999999999787e-01 0.000000000000000000e+00 7.738500000000000378e-01 -6.163300000000000445e-01 2.732200000000000184e-01 -9.652300000000000324e-01 8.527799999999999825e-01 3.767999999999999822e-02 -3.469499999999999806e-01 2.078999999999999945e-02 -9.899999999999999946e-04 2.936000000000000276e-01 9.355499999999999927e-01 5.789699999999999847e-01 -9.423599999999999755e-01 -5.744700000000000362e-01 4.970200000000000173e-01 6.388200000000000545e-01 7.791400000000000547e-01 -8.034599999999999520e-01 1.489000000000000046e-01 -1.682800000000000129e-01 -2.739900000000000113e-01 -7.120300000000000518e-01 9.616799999999999793e-01 5.369999999999999774e-02 4.046399999999999997e-01 -3.968800000000000106e-01 -7.353600000000000136e-01 8.756199999999999539e-01 9.047600000000000087e-01 7.475000000000000533e-01 -1.119900000000000062e-01 8.377200000000000202e-01 -4.818299999999999805e-01 6.925299999999999789e-01 -6.893000000000000238e-01 8.754199999999999759e-01 6.798800000000000399e-01 -4.628099999999999992e-01 -6.679500000000000437e-01 -2.014600000000000002e-01 8.018699999999999717e-01 6.428599999999999870e-01 -5.543000000000000149e-01 -3.600000000000000227e-04 -4.664400000000000213e-01 -4.293699999999999739e-01 5.249599999999999822e-01 5.171999999999999931e-01 9.977000000000000313e-01 2.693900000000000183e-01 4.888199999999999767e-01 -2.557599999999999874e-01 -4.751099999999999768e-01 3.420900000000000052e-01 -6.850399999999999823e-01 8.578799999999999759e-01 4.605099999999999749e-01 -9.126300000000000523e-01 -2.148299999999999932e-01 4.853299999999999836e-01 4.202099999999999724e-01 2.668300000000000116e-01 7.628999999999999670e-02 7.220699999999999896e-01 2.918499999999999983e-01 -8.437700000000000200e-01 -4.988500000000000156e-01 2.720199999999999840e-01 -5.802699999999999525e-01 3.233800000000000008e-01 -2.323399999999999910e-01 7.338599999999999568e-01 9.777900000000000480e-01 -6.776600000000000401e-01 -2.306900000000000062e-01 8.320899999999999963e-01 -3.628299999999999859e-01 -2.347599999999999965e-01 0.000000000000000000e+00 8.763600000000000279e-01 2.554899999999999949e-01 1.436999999999999944e-01 -1.044500000000000012e-01 1.660800000000000054e-01 -1.897699999999999942e-01 -9.580100000000000282e-01 1.473000000000000004e-02 -1.668999999999999997e-02 -6.403600000000000403e-01 5.072499999999999787e-01 0.000000000000000000e+00 7.738500000000000378e-01 -6.163300000000000445e-01 2.732200000000000184e-01 -9.652300000000000324e-01 8.527799999999999825e-01 3.767999999999999822e-02 -3.469499999999999806e-01 2.078999999999999945e-02 -9.899999999999999946e-04 2.936000000000000276e-01 9.355499999999999927e-01 5.789699999999999847e-01 -9.423599999999999755e-01 -5.744700000000000362e-01 4.970200000000000173e-01 6.388200000000000545e-01 7.791400000000000547e-01 -8.034599999999999520e-01 1.489000000000000046e-01 -1.682800000000000129e-01 -2.739900000000000113e-01 -7.120300000000000518e-01 9.616799999999999793e-01 5.369999999999999774e-02 4.046399999999999997e-01 -3.968800000000000106e-01 -7.353600000000000136e-01 8.756199999999999539e-01 9.047600000000000087e-01 7.475000000000000533e-01 -1.119900000000000062e-01 8.377200000000000202e-01 -4.818299999999999805e-01 6.925299999999999789e-01 -6.893000000000000238e-01 8.754199999999999759e-01 6.798800000000000399e-01 -4.628099999999999992e-01 -6.679500000000000437e-01 -2.014600000000000002e-01 8.018699999999999717e-01 6.428599999999999870e-01 -5.543000000000000149e-01 -3.600000000000000227e-04 -4.664400000000000213e-01 -4.293699999999999739e-01 5.249599999999999822e-01 5.171999999999999931e-01 9.977000000000000313e-01 2.693900000000000183e-01 4.888199999999999767e-01 -2.557599999999999874e-01 -4.751099999999999768e-01 3.420900000000000052e-01 -6.850399999999999823e-01 8.578799999999999759e-01 4.605099999999999749e-01 -9.126300000000000523e-01 -2.148299999999999932e-01 4.853299999999999836e-01 4.202099999999999724e-01 2.668300000000000116e-01 7.628999999999999670e-02 7.220699999999999896e-01 2.918499999999999983e-01 -8.437700000000000200e-01 -4.988500000000000156e-01 2.720199999999999840e-01 -5.802699999999999525e-01 3.233800000000000008e-01 -2.323399999999999910e-01 7.338599999999999568e-01 9.777900000000000480e-01 -6.776600000000000401e-01 -2.306900000000000062e-01 8.320899999999999963e-01 -3.628299999999999859e-01 -2.347599999999999965e-01 0.000000000000000000e+00 8.763600000000000279e-01 2.554899999999999949e-01 1.436999999999999944e-01 -1.044500000000000012e-01 1.660800000000000054e-01 -1.897699999999999942e-01 -9.580100000000000282e-01 1.473000000000000004e-02 -1.668999999999999997e-02 -6.403600000000000403e-01 5.072499999999999787e-01 0.000000000000000000e+00 7.738500000000000378e-01 -6.163300000000000445e-01 2.732200000000000184e-01 -9.652300000000000324e-01 8.527799999999999825e-01 3.767999999999999822e-02 -3.469499999999999806e-01 2.078999999999999945e-02 -9.899999999999999946e-04 2.936000000000000276e-01 9.355499999999999927e-01 5.789699999999999847e-01 -9.423599999999999755e-01 -5.744700000000000362e-01 4.970200000000000173e-01 6.388200000000000545e-01 7.791400000000000547e-01 -8.034599999999999520e-01 1.489000000000000046e-01 -1.682800000000000129e-01 -2.739900000000000113e-01 -7.120300000000000518e-01 9.616799999999999793e-01 5.369999999999999774e-02 4.046399999999999997e-01 -3.968800000000000106e-01 -7.353600000000000136e-01 8.756199999999999539e-01 9.047600000000000087e-01 7.475000000000000533e-01 -1.119900000000000062e-01 8.377200000000000202e-01 -4.818299999999999805e-01 6.925299999999999789e-01 -6.893000000000000238e-01 8.754199999999999759e-01 6.798800000000000399e-01 -4.628099999999999992e-01 -6.679500000000000437e-01 -2.014600000000000002e-01 8.018699999999999717e-01 6.428599999999999870e-01 -5.543000000000000149e-01 -3.499999999999999964e-04 -4.664400000000000213e-01 -4.293699999999999739e-01 5.249599999999999822e-01 5.171999999999999931e-01 9.977000000000000313e-01 2.693900000000000183e-01 4.888199999999999767e-01 -2.557599999999999874e-01 -4.751099999999999768e-01 3.420900000000000052e-01 -6.850399999999999823e-01 8.578799999999999759e-01 4.605099999999999749e-01 -9.126300000000000523e-01 -2.148299999999999932e-01 4.853299999999999836e-01 4.202099999999999724e-01 2.668300000000000116e-01 7.628999999999999670e-02 7.220699999999999896e-01 2.918499999999999983e-01 -8.437700000000000200e-01 -4.988500000000000156e-01 2.720199999999999840e-01 -5.802699999999999525e-01 3.233800000000000008e-01 -2.323399999999999910e-01 7.338599999999999568e-01 9.777900000000000480e-01 -6.776600000000000401e-01 -2.306900000000000062e-01 8.320899999999999963e-01 -3.628299999999999859e-01 -2.347599999999999965e-01 0.000000000000000000e+00 8.763600000000000279e-01 2.554899999999999949e-01 1.436999999999999944e-01 -1.044500000000000012e-01 1.660800000000000054e-01 -1.897699999999999942e-01 -9.580100000000000282e-01 1.473000000000000004e-02 -1.668999999999999997e-02 -6.403600000000000403e-01 5.072499999999999787e-01 0.000000000000000000e+00 7.738500000000000378e-01 -6.163300000000000445e-01 2.732200000000000184e-01 -9.652300000000000324e-01 8.527799999999999825e-01 3.767999999999999822e-02 -3.469499999999999806e-01 2.078999999999999945e-02 -9.899999999999999946e-04 2.936000000000000276e-01 9.355499999999999927e-01 5.789699999999999847e-01 -9.423599999999999755e-01 -5.744700000000000362e-01 4.970200000000000173e-01 6.388200000000000545e-01 7.791400000000000547e-01 -8.034599999999999520e-01 1.489000000000000046e-01 -1.682800000000000129e-01 -2.739900000000000113e-01 -7.120300000000000518e-01 9.616799999999999793e-01 5.369999999999999774e-02 4.046399999999999997e-01 -3.968800000000000106e-01 -7.353600000000000136e-01 8.756199999999999539e-01 9.047600000000000087e-01 7.475000000000000533e-01 -1.119900000000000062e-01 8.377200000000000202e-01 -4.818299999999999805e-01 6.925299999999999789e-01 -6.893000000000000238e-01 8.754199999999999759e-01 6.798800000000000399e-01 -4.628099999999999992e-01 -6.679500000000000437e-01 -2.014600000000000002e-01 8.018699999999999717e-01 6.428599999999999870e-01 -5.543000000000000149e-01 -3.499999999999999964e-04 -4.664400000000000213e-01 -4.293699999999999739e-01 5.249599999999999822e-01 5.171999999999999931e-01 9.977000000000000313e-01 2.693900000000000183e-01 4.888199999999999767e-01 -2.557599999999999874e-01 -4.751099999999999768e-01 3.420900000000000052e-01 -6.850399999999999823e-01 8.578799999999999759e-01 4.605099999999999749e-01 -9.126300000000000523e-01 -2.148299999999999932e-01 4.853299999999999836e-01 4.202099999999999724e-01 2.668300000000000116e-01 7.628999999999999670e-02 7.220699999999999896e-01 2.918499999999999983e-01 -8.437700000000000200e-01 -4.988500000000000156e-01 2.720199999999999840e-01 -5.802699999999999525e-01 3.233800000000000008e-01 -2.323399999999999910e-01 7.338599999999999568e-01 9.777900000000000480e-01 -6.776600000000000401e-01 -2.306900000000000062e-01 8.320899999999999963e-01 -3.628299999999999859e-01 -2.347599999999999965e-01
|
| 2 |
+
0.000000000000000000e+00 -1.992299999999999904e-01 -6.112000000000000072e-02 -2.180499999999999938e-01 -9.930499999999999883e-01 8.334300000000000042e-01 -9.454200000000000381e-01 -1.767900000000000027e-01 -8.922999999999999821e-01 7.327599999999999669e-01 -6.879199999999999759e-01 8.470800000000000551e-01 0.000000000000000000e+00 6.134100000000000108e-01 3.085999999999999854e-02 -5.705999999999999961e-01 1.829000000000000070e-02 1.892600000000000116e-01 -2.772700000000000164e-01 -9.366999999999999771e-01 -5.218099999999999961e-01 4.615500000000000158e-01 -8.873199999999999976e-01 -6.237999999999999795e-02 5.644500000000000073e-01 2.839900000000000202e-01 7.387399999999999523e-01 -1.174700000000000050e-01 1.032399999999999984e-01 4.735500000000000265e-01 5.700999999999999818e-02 2.300300000000000122e-01 9.780100000000000460e-01 4.232000000000000206e-01 1.554300000000000126e-01 -2.468500000000000139e-01 -9.854300000000000281e-01 1.655899999999999872e-01 7.317299999999999915e-01 -3.010599999999999943e-01 -4.829300000000000259e-01 2.330800000000000094e-01 -6.452599999999999447e-01 8.232000000000000428e-01 4.914999999999999925e-02 5.251700000000000257e-01 -7.137700000000000156e-01 3.032500000000000195e-01 4.538499999999999757e-01 -6.075199999999999489e-01 -6.678100000000000147e-01 5.420099999999999918e-01 6.446899999999999853e-01 -5.315800000000000525e-01 6.635699999999999932e-01 8.221399999999999819e-01 -9.438100000000000378e-01 -2.006499999999999950e-01 -8.377000000000000002e-01 -3.770200000000000218e-01 3.765600000000000058e-01 -4.014000000000000207e-02 9.269899999999999807e-01 -2.728400000000000269e-01 9.043600000000000527e-01 -4.501499999999999946e-01 6.470399999999999485e-01 -2.196700000000000041e-01 -4.225700000000000012e-01 -8.761600000000000499e-01 -3.990400000000000058e-01 -1.503599999999999937e-01 -7.836499999999999577e-01 7.878399999999999848e-01 -7.680500000000000105e-01 6.727600000000000247e-01 -3.972200000000000175e-01 -3.320899999999999963e-01 3.110100000000000087e-01 6.056599999999999762e-01 4.501999999999999891e-01 -8.063200000000000367e-01 -9.421100000000000030e-01 -4.025599999999999734e-01 6.725100000000000522e-01 1.923199999999999910e-01 -4.597399999999999820e-01 -8.152500000000000302e-01 4.231699999999999906e-01 6.468000000000000138e-02 -6.296599999999999975e-01 0.000000000000000000e+00 -1.992299999999999904e-01 -6.112000000000000072e-02 -2.180499999999999938e-01 -9.930499999999999883e-01 8.334300000000000042e-01 -9.454200000000000381e-01 -1.767900000000000027e-01 -8.922999999999999821e-01 7.327599999999999669e-01 -6.879199999999999759e-01 8.470800000000000551e-01 0.000000000000000000e+00 6.134100000000000108e-01 3.085999999999999854e-02 -5.705999999999999961e-01 1.829000000000000070e-02 1.892600000000000116e-01 -2.772700000000000164e-01 -9.366999999999999771e-01 -5.218099999999999961e-01 4.615500000000000158e-01 -8.873199999999999976e-01 -6.237999999999999795e-02 5.644500000000000073e-01 2.839900000000000202e-01 7.387399999999999523e-01 -1.174700000000000050e-01 1.032399999999999984e-01 4.735500000000000265e-01 5.700999999999999818e-02 2.300300000000000122e-01 9.780100000000000460e-01 4.232000000000000206e-01 1.554300000000000126e-01 -2.468500000000000139e-01 -9.854300000000000281e-01 1.655899999999999872e-01 7.317299999999999915e-01 -3.010599999999999943e-01 -4.829300000000000259e-01 2.330800000000000094e-01 -6.452599999999999447e-01 8.232000000000000428e-01 4.914999999999999925e-02 5.251700000000000257e-01 -7.137700000000000156e-01 3.032500000000000195e-01 4.538499999999999757e-01 -6.075199999999999489e-01 -6.678100000000000147e-01 5.420099999999999918e-01 6.446899999999999853e-01 -5.315800000000000525e-01 6.635699999999999932e-01 8.221399999999999819e-01 -9.438100000000000378e-01 -2.006499999999999950e-01 -8.377000000000000002e-01 -3.770200000000000218e-01 3.765600000000000058e-01 -4.014000000000000207e-02 9.269899999999999807e-01 -2.728400000000000269e-01 9.043600000000000527e-01 -4.501499999999999946e-01 6.470399999999999485e-01 -2.196700000000000041e-01 -4.225700000000000012e-01 -8.761600000000000499e-01 -3.990400000000000058e-01 -1.503599999999999937e-01 -7.836499999999999577e-01 7.878399999999999848e-01 -7.680500000000000105e-01 6.727600000000000247e-01 -3.972200000000000175e-01 -3.320899999999999963e-01 3.110100000000000087e-01 6.056599999999999762e-01 4.501999999999999891e-01 -8.063200000000000367e-01 -9.421100000000000030e-01 -4.025599999999999734e-01 6.725100000000000522e-01 1.923199999999999910e-01 -4.597399999999999820e-01 -8.152500000000000302e-01 4.231699999999999906e-01 6.468000000000000138e-02 -6.296599999999999975e-01 0.000000000000000000e+00 -1.992299999999999904e-01 -6.112000000000000072e-02 -2.180499999999999938e-01 -9.930499999999999883e-01 8.334300000000000042e-01 -9.454200000000000381e-01 -1.767900000000000027e-01 -8.922999999999999821e-01 7.327599999999999669e-01 -6.879199999999999759e-01 8.470800000000000551e-01 0.000000000000000000e+00 6.134100000000000108e-01 3.085999999999999854e-02 -5.705999999999999961e-01 1.829000000000000070e-02 1.892600000000000116e-01 -2.772700000000000164e-01 -9.366999999999999771e-01 -5.218099999999999961e-01 4.615500000000000158e-01 -8.873199999999999976e-01 -6.237999999999999795e-02 5.644500000000000073e-01 2.839900000000000202e-01 7.387399999999999523e-01 -1.174700000000000050e-01 1.032399999999999984e-01 4.735500000000000265e-01 5.700999999999999818e-02 2.300300000000000122e-01 9.780100000000000460e-01 4.232000000000000206e-01 1.554300000000000126e-01 -2.468500000000000139e-01 -9.854300000000000281e-01 1.655899999999999872e-01 7.317299999999999915e-01 -3.010599999999999943e-01 -4.829300000000000259e-01 2.330800000000000094e-01 -6.452599999999999447e-01 8.232000000000000428e-01 4.914999999999999925e-02 5.251700000000000257e-01 -7.137700000000000156e-01 3.032500000000000195e-01 4.538499999999999757e-01 -6.075199999999999489e-01 -6.678100000000000147e-01 5.420099999999999918e-01 6.446899999999999853e-01 -5.315800000000000525e-01 6.635699999999999932e-01 8.221399999999999819e-01 -9.438100000000000378e-01 -2.006499999999999950e-01 -8.377000000000000002e-01 -3.770200000000000218e-01 3.765600000000000058e-01 -4.014000000000000207e-02 9.269899999999999807e-01 -2.728400000000000269e-01 9.043600000000000527e-01 -4.501499999999999946e-01 6.470399999999999485e-01 -2.196700000000000041e-01 -4.225700000000000012e-01 -8.761600000000000499e-01 -3.990400000000000058e-01 -1.503599999999999937e-01 -7.836499999999999577e-01 7.878399999999999848e-01 -7.680500000000000105e-01 6.727600000000000247e-01 -3.972200000000000175e-01 -3.320899999999999963e-01 3.110100000000000087e-01 6.056599999999999762e-01 4.501999999999999891e-01 -8.063200000000000367e-01 -9.421100000000000030e-01 -4.025599999999999734e-01 6.725100000000000522e-01 1.923199999999999910e-01 -4.597399999999999820e-01 -8.152500000000000302e-01 4.231699999999999906e-01 6.468000000000000138e-02 -6.296599999999999975e-01 0.000000000000000000e+00 -1.992299999999999904e-01 -6.112000000000000072e-02 -2.180499999999999938e-01 -9.930499999999999883e-01 8.334300000000000042e-01 -9.454200000000000381e-01 -1.767900000000000027e-01 -8.922999999999999821e-01 7.327599999999999669e-01 -6.879199999999999759e-01 8.470800000000000551e-01 0.000000000000000000e+00 6.134100000000000108e-01 3.085999999999999854e-02 -5.705999999999999961e-01 1.829000000000000070e-02 1.892600000000000116e-01 -2.772700000000000164e-01 -9.366999999999999771e-01 -5.218099999999999961e-01 4.615500000000000158e-01 -8.873199999999999976e-01 -6.237999999999999795e-02 5.644500000000000073e-01 2.839900000000000202e-01 7.387399999999999523e-01 -1.174700000000000050e-01 1.032399999999999984e-01 4.735500000000000265e-01 5.700999999999999818e-02 2.300300000000000122e-01 9.780100000000000460e-01 4.232000000000000206e-01 1.554300000000000126e-01 -2.468500000000000139e-01 -9.854300000000000281e-01 1.655899999999999872e-01 7.317299999999999915e-01 -3.010599999999999943e-01 -4.829300000000000259e-01 2.330800000000000094e-01 -6.452599999999999447e-01 8.232000000000000428e-01 4.914999999999999925e-02 5.251700000000000257e-01 -7.137700000000000156e-01 3.032500000000000195e-01 4.538499999999999757e-01 -6.075199999999999489e-01 -6.678100000000000147e-01 5.420099999999999918e-01 6.446899999999999853e-01 -5.315800000000000525e-01 6.635699999999999932e-01 8.221399999999999819e-01 -9.438100000000000378e-01 -2.006499999999999950e-01 -8.377000000000000002e-01 -3.770200000000000218e-01 3.765600000000000058e-01 -4.014000000000000207e-02 9.269899999999999807e-01 -2.728400000000000269e-01 9.043600000000000527e-01 -4.501499999999999946e-01 6.470399999999999485e-01 -2.196700000000000041e-01 -4.225700000000000012e-01 -8.761600000000000499e-01 -3.990400000000000058e-01 -1.503599999999999937e-01 -7.836499999999999577e-01 7.878399999999999848e-01 -7.680500000000000105e-01 6.727600000000000247e-01 -3.972200000000000175e-01 -3.320899999999999963e-01 3.110100000000000087e-01 6.056599999999999762e-01 4.501999999999999891e-01 -8.063200000000000367e-01 -9.421100000000000030e-01 -4.025599999999999734e-01 6.725100000000000522e-01 1.923199999999999910e-01 -4.597399999999999820e-01 -8.152500000000000302e-01 4.231699999999999906e-01 6.468000000000000138e-02 -6.296599999999999975e-01
|
| 3 |
+
0.000000000000000000e+00 4.385299999999999754e-01 9.648799999999999599e-01 -9.653000000000000469e-01 -5.430000000000000104e-02 5.270799999999999930e-01 2.648800000000000043e-01 2.257599999999999885e-01 4.511999999999999900e-01 -6.802799999999999958e-01 -3.416299999999999892e-01 1.586100000000000010e-01 1.000000000000000000e+00 -1.577600000000000113e-01 7.868899999999999784e-01 7.744400000000000173e-01 -2.607499999999999818e-01 -4.867799999999999905e-01 9.600499999999999590e-01 4.701000000000000317e-02 8.528099999999999570e-01 8.871200000000000196e-01 -3.556099999999999817e-01 -3.476400000000000046e-01 5.883800000000000141e-01 1.769300000000000039e-01 3.524900000000000255e-01 8.597500000000000142e-01 7.623999999999999666e-01 4.107199999999999740e-01 5.926200000000000356e-01 9.617200000000000193e-01 1.232199999999999962e-01 8.636200000000000543e-01 -6.847299999999999498e-01 1.193499999999999978e-01 1.613799999999999957e-01 8.993600000000000483e-01 5.541300000000000114e-01 -6.071199999999999930e-01 -8.009999999999999759e-03 3.564800000000000191e-01 1.577600000000000113e-01 5.565999999999999837e-01 5.438800000000000301e-01 7.014599999999999724e-01 -1.046099999999999947e-01 6.579599999999999893e-01 1.663000000000000034e-01 4.107199999999999740e-01 5.829600000000000337e-01 5.099799999999999889e-01 7.374199999999999644e-01 -2.728200000000000069e-01 -3.826300000000000257e-01 -1.297399999999999942e-01 -3.304799999999999960e-01 8.615000000000000435e-01 3.375000000000000222e-01 7.630700000000000260e-01 7.685699999999999754e-01 -5.460000000000000270e-02 2.609799999999999898e-01 -8.286299999999999777e-01 -3.416299999999999892e-01 7.560599999999999543e-01 6.814099999999999602e-01 6.945900000000000407e-01 2.923700000000000188e-01 -1.423999999999999988e-01 8.867999999999999494e-02 9.650100000000000344e-01 3.877599999999999936e-01 4.502499999999999836e-01 5.821499999999999453e-01 7.359200000000000186e-01 5.664099999999999691e-01 8.969599999999999795e-01 4.374000000000000110e-01 -6.199400000000000466e-01 8.504899999999999682e-01 1.145899999999999974e-01 8.867999999999999494e-02 8.854199999999999848e-01 9.582999999999999852e-02 8.328000000000000680e-02 5.739499999999999602e-01 5.311799999999999855e-01 -3.585400000000000253e-01 9.296100000000000474e-01 7.405500000000000416e-01 0.000000000000000000e+00 4.385299999999999754e-01 9.648799999999999599e-01 -9.653000000000000469e-01 -5.430000000000000104e-02 5.270799999999999930e-01 2.648800000000000043e-01 2.257599999999999885e-01 4.511999999999999900e-01 -6.802799999999999958e-01 -3.416299999999999892e-01 1.586100000000000010e-01 1.000000000000000000e+00 -1.577600000000000113e-01 7.868899999999999784e-01 7.744400000000000173e-01 -2.607499999999999818e-01 -4.867799999999999905e-01 9.600499999999999590e-01 4.701000000000000317e-02 8.528099999999999570e-01 8.871200000000000196e-01 -3.556099999999999817e-01 -3.476400000000000046e-01 5.883800000000000141e-01 1.769300000000000039e-01 3.524900000000000255e-01 8.597500000000000142e-01 7.623999999999999666e-01 4.107199999999999740e-01 5.926200000000000356e-01 9.617200000000000193e-01 1.232199999999999962e-01 8.636200000000000543e-01 -6.847299999999999498e-01 1.193499999999999978e-01 1.613799999999999957e-01 8.993600000000000483e-01 5.541300000000000114e-01 -6.071199999999999930e-01 -8.009999999999999759e-03 3.564800000000000191e-01 1.577600000000000113e-01 5.565999999999999837e-01 5.438800000000000301e-01 7.014599999999999724e-01 -1.046099999999999947e-01 6.579599999999999893e-01 1.663000000000000034e-01 4.107199999999999740e-01 5.829600000000000337e-01 5.099799999999999889e-01 7.374199999999999644e-01 -2.728200000000000069e-01 -3.826300000000000257e-01 -1.297399999999999942e-01 -3.304799999999999960e-01 8.615000000000000435e-01 3.375000000000000222e-01 7.630700000000000260e-01 7.685699999999999754e-01 -5.460000000000000270e-02 2.609799999999999898e-01 -8.286299999999999777e-01 -3.416299999999999892e-01 7.560599999999999543e-01 6.814099999999999602e-01 6.945900000000000407e-01 2.923700000000000188e-01 -1.423999999999999988e-01 8.867999999999999494e-02 9.650100000000000344e-01 3.877599999999999936e-01 4.502499999999999836e-01 5.821499999999999453e-01 7.359200000000000186e-01 5.664099999999999691e-01 8.969599999999999795e-01 4.374000000000000110e-01 -6.199400000000000466e-01 8.504899999999999682e-01 1.145899999999999974e-01 8.867999999999999494e-02 8.854199999999999848e-01 9.582999999999999852e-02 8.328000000000000680e-02 5.739499999999999602e-01 5.311799999999999855e-01 -3.585400000000000253e-01 9.296100000000000474e-01 7.405500000000000416e-01 0.000000000000000000e+00 4.385299999999999754e-01 9.648799999999999599e-01 -9.653000000000000469e-01 -5.430000000000000104e-02 5.270799999999999930e-01 2.648800000000000043e-01 2.257599999999999885e-01 4.511999999999999900e-01 -6.802799999999999958e-01 -3.416299999999999892e-01 1.586100000000000010e-01 1.000000000000000000e+00 -1.577600000000000113e-01 7.868899999999999784e-01 7.744400000000000173e-01 -2.607499999999999818e-01 -4.867799999999999905e-01 9.600499999999999590e-01 4.701000000000000317e-02 8.528099999999999570e-01 8.871200000000000196e-01 -3.556099999999999817e-01 -3.476400000000000046e-01 5.883800000000000141e-01 1.769300000000000039e-01 3.524900000000000255e-01 8.597500000000000142e-01 7.623999999999999666e-01 4.107199999999999740e-01 5.926200000000000356e-01 9.617200000000000193e-01 1.232199999999999962e-01 8.636200000000000543e-01 -6.847299999999999498e-01 1.193499999999999978e-01 1.613799999999999957e-01 8.993600000000000483e-01 5.541300000000000114e-01 -6.071199999999999930e-01 -8.009999999999999759e-03 3.564800000000000191e-01 1.577600000000000113e-01 5.565999999999999837e-01 5.438800000000000301e-01 7.014599999999999724e-01 -1.046099999999999947e-01 6.579599999999999893e-01 1.663000000000000034e-01 4.107199999999999740e-01 5.829600000000000337e-01 5.099799999999999889e-01 7.374199999999999644e-01 -2.728200000000000069e-01 -3.826300000000000257e-01 -1.297399999999999942e-01 -3.304799999999999960e-01 8.615000000000000435e-01 3.375000000000000222e-01 7.630700000000000260e-01 7.685699999999999754e-01 -5.460000000000000270e-02 2.609799999999999898e-01 -8.286299999999999777e-01 -3.416299999999999892e-01 7.560599999999999543e-01 6.814099999999999602e-01 6.945900000000000407e-01 2.923700000000000188e-01 -1.423999999999999988e-01 8.867999999999999494e-02 9.650100000000000344e-01 3.877599999999999936e-01 4.502499999999999836e-01 5.821499999999999453e-01 7.359200000000000186e-01 5.664099999999999691e-01 8.969599999999999795e-01 4.374000000000000110e-01 -6.199400000000000466e-01 8.504899999999999682e-01 1.145899999999999974e-01 8.867999999999999494e-02 8.854199999999999848e-01 9.582999999999999852e-02 8.328000000000000680e-02 5.739499999999999602e-01 5.311799999999999855e-01 -3.585400000000000253e-01 9.296100000000000474e-01 7.405500000000000416e-01 0.000000000000000000e+00 4.385299999999999754e-01 9.648799999999999599e-01 -9.653000000000000469e-01 -5.430000000000000104e-02 5.270799999999999930e-01 2.648800000000000043e-01 2.257599999999999885e-01 4.511999999999999900e-01 -6.802799999999999958e-01 -3.416299999999999892e-01 1.586100000000000010e-01 1.000000000000000000e+00 -1.577600000000000113e-01 7.868899999999999784e-01 7.744400000000000173e-01 -2.607499999999999818e-01 -4.867799999999999905e-01 9.600499999999999590e-01 4.701000000000000317e-02 8.528099999999999570e-01 8.871200000000000196e-01 -3.556099999999999817e-01 -3.476400000000000046e-01 5.883800000000000141e-01 1.769300000000000039e-01 3.524900000000000255e-01 8.597500000000000142e-01 7.623999999999999666e-01 4.107199999999999740e-01 5.926200000000000356e-01 9.617200000000000193e-01 1.232199999999999962e-01 8.636200000000000543e-01 -6.847299999999999498e-01 1.193499999999999978e-01 1.613799999999999957e-01 8.993600000000000483e-01 5.541300000000000114e-01 -6.071199999999999930e-01 -8.009999999999999759e-03 3.564800000000000191e-01 1.577600000000000113e-01 5.565999999999999837e-01 5.438800000000000301e-01 7.014599999999999724e-01 -1.046099999999999947e-01 6.579599999999999893e-01 1.663000000000000034e-01 4.107199999999999740e-01 5.829600000000000337e-01 5.099799999999999889e-01 7.374199999999999644e-01 -2.728200000000000069e-01 -3.826300000000000257e-01 -1.297399999999999942e-01 -3.304799999999999960e-01 8.615000000000000435e-01 3.375000000000000222e-01 7.630700000000000260e-01 7.685699999999999754e-01 -5.460000000000000270e-02 2.609799999999999898e-01 -8.286299999999999777e-01 -3.416299999999999892e-01 7.560599999999999543e-01 6.814099999999999602e-01 6.945900000000000407e-01 2.923700000000000188e-01 -1.423999999999999988e-01 8.867999999999999494e-02 9.650100000000000344e-01 3.877599999999999936e-01 4.502499999999999836e-01 5.821499999999999453e-01 7.359200000000000186e-01 5.664099999999999691e-01 8.969599999999999795e-01 4.374000000000000110e-01 -6.199400000000000466e-01 8.504899999999999682e-01 1.145899999999999974e-01 8.867999999999999494e-02 8.854199999999999848e-01 9.582999999999999852e-02 8.328000000000000680e-02 5.739499999999999602e-01 5.311799999999999855e-01 -3.585400000000000253e-01 9.296100000000000474e-01 7.405500000000000416e-01
|
data/DiSCo_mask.nii.gz
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:f81c639103795a1e6a4163305c418a061b54224a73fcc99a09459dc7ab561b50
|
| 3 |
+
size 10881
|
data/SOURCE.md
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# DiSCo reference files
|
| 2 |
+
|
| 3 |
+
From the Diffusion-Simulated Connectivity (DiSCo) dataset, Rafael-Patino J., Girard G., Truffet R., Pizzolato M.,
|
| 4 |
+
Caruyer E., Thiran J.-P., "The Diffusion-Simulated Connectivity (DiSCo) dataset", Data in Brief 38 (2021) 107429,
|
| 5 |
+
https://doi.org/10.1016/j.dib.2021.107429; data at https://doi.org/10.5281/zenodo.4634234. Licence CC BY 4.0.
|
| 6 |
+
|
| 7 |
+
| file | what |
|
| 8 |
+
|---|---|
|
| 9 |
+
| `DiSCo_mask.nii.gz` | the 40³ mask of the phantom's voxels (the tracking domain) |
|
| 10 |
+
| `DiSCo_ROIs.nii.gz` | the sixteen end regions, labels 1 to 16 (seeds and connectome endpoints) |
|
| 11 |
+
| `DiSCo_gradients.bvals`, `DiSCo_gradients_dipy.bvecs` | the dataset's 364-measurement gradient table (b in s/mm²), the "DiSCo 364" acquisition |
|
| 12 |
+
| `DiSCo_Connectivity_Matrix_Strands_Count.txt` | ground truth: strands per region pair |
|
| 13 |
+
| `DiSCo_Connectivity_Matrix_Cross-Sectional_Area.txt` | ground truth: total cross-sectional area per region pair |
|
| 14 |
+
| `DiSCo_Strands_Trajectories.tck`, `DiSCo_Strands_Diameters.txt` | the 12,196 strands' centerlines (in units of the 25 µm voxel, i.e. the image grid) and inner diameters (mm): the ground-truth view |
|
| 15 |
+
|
| 16 |
+
Unmodified copies of the dataset's DiSCo1 files, redistributed here under CC BY 4.0 so the Space is self-contained.
|
pyproject.toml
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[tool.pytest.ini_options]
|
| 2 |
+
pythonpath = ["."]
|
| 3 |
+
testpaths = ["tests"]
|
requirements.txt
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# The ZeroGPU (Gradio SDK) deployment: PyTorch on the shared pool; jax stays as a CPU library dependency of dmipy-sim
|
| 2 |
+
# and never touches the GPU. The dmipy packages by commit (the torch backends: dmipy-sim#511, dmipy-fit#38,
|
| 3 |
+
# dmipy-tract#5).
|
| 4 |
+
torch>=2.4
|
| 5 |
+
tomli; python_version < "3.11" # the ZeroGPU image is Python 3.10 (its README python_version is ignored)
|
| 6 |
+
spaces>=0.30
|
| 7 |
+
gradio==6.28.0
|
| 8 |
+
jax>=0.4.30
|
| 9 |
+
jaxopt==0.8.5
|
| 10 |
+
numpy>=1.26,<3
|
| 11 |
+
scipy>=1.11
|
| 12 |
+
nibabel==5.4.2
|
| 13 |
+
safetensors>=0.4
|
| 14 |
+
huggingface_hub>=0.30
|
| 15 |
+
requests>=2.31
|
| 16 |
+
matplotlib>=3.8
|
| 17 |
+
plotly>=5.20
|
| 18 |
+
pillow>=10
|
| 19 |
+
dipy>=1.9
|
| 20 |
+
# dmipy-sim: main at the merge of dmipy-sim#598 (the field declared by the spec's pools)
|
| 21 |
+
dmipy-sim @ git+https://github.com/dmrai-lab/dmipy-sim@1b79d2e06a958578bc523c84bacf54bae86fbb95
|
| 22 |
+
dmipy-fit @ git+https://github.com/dmrai-lab/dmipy-fit@c3dcc546595cbde8e8e7c7bb2ff4e87f099d5dab
|
| 23 |
+
dmipy-tract @ git+https://github.com/dmrai-lab/dmipy-tract@7da22c3a9473c50a08cc7c6246ec16b68a64d877
|
space/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
"""The DiSCo Space: ``pipeline`` (replay -> CSD -> tracking -> score) and ``app`` (the Gradio page over it)."""
|
space/app.py
ADDED
|
@@ -0,0 +1,748 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""The Spaces' page, four tabs over :mod:`space.pipeline` and the configured source (:mod:`space.sources`).
|
| 2 |
+
|
| 3 |
+
The acquisition tab: a preset (the source's), custom shells (on a stored pulse timing; at their own δ / Δ / TE, or
|
| 4 |
+
from an uploaded Camino scheme, in DiSCo's full mode); the source's tissue-and-scanner panel; the noise; the
|
| 5 |
+
tracker; the scanner (ideal, or a catalogued machine whose every catalogued term the replay applies at the phantom's
|
| 6 |
+
place in the bore, and whose gradient limit refuses a shell it cannot play; docs/scanner.md); B, the same run with one
|
| 7 |
+
knob changed; N
|
| 8 |
+
tracker keys for the tractogram's own spread; the run button, whose progress names the stage it is in. The truth
|
| 9 |
+
tab: the source's input and ground truth. The Replay DWI Explorer: the ingredient maps of the tiers, the noise-free
|
| 10 |
+
layers (the tier ladder, A, B) and their differences in the DWI or in MD / FA, per shell, and the estimated against
|
| 11 |
+
the true responses where the source has them. The results tab: a DWI slice with the FODs' principal directions,
|
| 12 |
+
the tractograms and connectomes of A and B against the source's truth, the spread over keys, the accuracy and round
|
| 13 |
+
trip tables, the timings, the downloads.
|
| 14 |
+
|
| 15 |
+
The page is built from the source's class (:meth:`space.pipeline.Source.describe`, ``presets``, ``panel``,
|
| 16 |
+
``knobs``, ``estimated_seconds``) before any data loads; a run is :func:`prepare_runs` on the host (a lookup of the
|
| 17 |
+
source's share that needs no device, in the page's cache), :func:`compute` on the device (which computes the share
|
| 18 |
+
the page had not cached first, so the GPU call is entered as soon as the request arrives), :func:`present` back on
|
| 19 |
+
the host. Nothing scientific lives here: every number comes from the pipeline or the source, every figure from
|
| 20 |
+
:mod:`space.viewers`."""
|
| 21 |
+
from __future__ import annotations
|
| 22 |
+
|
| 23 |
+
import os
|
| 24 |
+
import shutil
|
| 25 |
+
import tempfile
|
| 26 |
+
import threading
|
| 27 |
+
import time
|
| 28 |
+
|
| 29 |
+
import numpy as np
|
| 30 |
+
from dataclasses import replace
|
| 31 |
+
|
| 32 |
+
from . import pipeline as P
|
| 33 |
+
from . import sources
|
| 34 |
+
from . import viewers as V
|
| 35 |
+
|
| 36 |
+
MAX_SHELLS = 4
|
| 37 |
+
CUSTOM = "custom shells"
|
| 38 |
+
UPLOADED = "uploaded scheme"
|
| 39 |
+
PER_SHELL = 7 # on, timing class, b, directions, delta, Delta, TE
|
| 40 |
+
NO_KNOB = P.NO_KNOB
|
| 41 |
+
IDEAL = P.IDEAL
|
| 42 |
+
RESPONSES_ROW = "worker · the packs' responses not cached on the page" # the timings row tools/live.py prints
|
| 43 |
+
SAMPLE = 10_000 # streamlines kept in the page's state and in the sample .tck
|
| 44 |
+
OUTPUTS = ("result", "headline", "dwi_view", "tract_view", "mats", "timings", "tck", "volumes", "z_slider", "m_slider",
|
| 45 |
+
"tract_view_b", "mats_b", "b_row", "floor_view", "accuracy", "spread_view",
|
| 46 |
+
"explore_view", "metric_view", "ingredient_pool", "ingredient_contact", "ingredient_field", "layer_table", "layer_choice",
|
| 47 |
+
"ez_slider", "em_slider", "truth_view", "fractions_view", "lobar_view", "roundtrip", "response_view") # the run button's outputs, in order
|
| 48 |
+
EXPLORE_MODES = ("signal", "minus the previous layer", "B − A", "(B − A) ÷ floor")
|
| 49 |
+
METRICS = ("DWI", "MD (µm²/ms)", "FA")
|
| 50 |
+
_state = {"source": None, "error": None}
|
| 51 |
+
_lock = threading.Lock()
|
| 52 |
+
_RUNS = tempfile.mkdtemp(prefix="disco-runs-") # one directory per run tag, replaced on every run
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def _load():
|
| 56 |
+
"""The source, loaded once per process (a failed load is retried on the next call)."""
|
| 57 |
+
with _lock:
|
| 58 |
+
if _state["source"] is None:
|
| 59 |
+
try:
|
| 60 |
+
t0 = time.perf_counter()
|
| 61 |
+
cfg = P.config()
|
| 62 |
+
src = sources.source(cfg)
|
| 63 |
+
_state["warm"] = src.warm_in_background() # the brain's warm-up runs beside the serving page
|
| 64 |
+
_state["regions"] = V.region_markers(src.regions)
|
| 65 |
+
_state["gt_views"] = None
|
| 66 |
+
_state["source"] = src; _state["cfg"] = cfg; _state["load_seconds"] = time.perf_counter() - t0; _state["error"] = None
|
| 67 |
+
except Exception as e: # shown on the page instead of a dead Space; the next call tries again
|
| 68 |
+
_state["error"] = repr(e)
|
| 69 |
+
return _state
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def _protocol_from_inputs(S, cfg, preset, n_b0, *shell_inputs, scheme=None, full=False):
|
| 73 |
+
"""The acquisition the page asks for: a preset of the source class ``S``, the shell rows (in full mode each with
|
| 74 |
+
its own delta / Delta / TE in ms, else on a stored timing class), or in full mode an uploaded Camino scheme."""
|
| 75 |
+
if preset == UPLOADED:
|
| 76 |
+
if not full:
|
| 77 |
+
raise ValueError("a scheme upload needs full mode (DISCO_MODE=full with the columnar pack)")
|
| 78 |
+
if not scheme:
|
| 79 |
+
raise ValueError("upload a Camino .scheme file")
|
| 80 |
+
return P.protocol_from_scheme(scheme)
|
| 81 |
+
if preset in S.presets(cfg):
|
| 82 |
+
return S.protocol(cfg, preset)
|
| 83 |
+
if preset != CUSTOM:
|
| 84 |
+
raise ValueError(f"unknown acquisition {preset!r}")
|
| 85 |
+
shells = []
|
| 86 |
+
for k in range(MAX_SHELLS):
|
| 87 |
+
on, shape, b, n, delta, Delta, TE = shell_inputs[PER_SHELL * k: PER_SHELL * (k + 1)]
|
| 88 |
+
if on and full:
|
| 89 |
+
shells.append(P.Shell.free(float(b), int(n), float(delta) * 1e-3, float(Delta) * 1e-3, float(TE) * 1e-3))
|
| 90 |
+
elif on:
|
| 91 |
+
shells.append(P.Shell(str(shape), float(b), int(n)))
|
| 92 |
+
return P.Protocol(tuple(shells), n_b0=int(n_b0), name=CUSTOM)
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def physics_values(S, cfg, *values):
|
| 96 |
+
"""The panel's inputs as a dict by the source class ``S``'s :attr:`~space.pipeline.Panel.fields`."""
|
| 97 |
+
fields = S.panel(cfg).fields
|
| 98 |
+
if len(values) != len(fields):
|
| 99 |
+
raise ValueError(f"the physics panel has {len(fields)} inputs, got {len(values)}")
|
| 100 |
+
return dict(zip(fields, values))
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def gradient_text(cfg, protocol, shapes, scanner):
|
| 104 |
+
"""The per-shell gradient table as Markdown, and whether every shell is playable on the menu's ``scanner``."""
|
| 105 |
+
rows = P.playable(protocol, shapes, P.machine(cfg, scanner))
|
| 106 |
+
lines = ["| shell | b (s/mm²) | timing | needs | limit |", "|---|---|---|---|---|"]
|
| 107 |
+
for name, b, delta, Delta, G, G_max, ok in rows:
|
| 108 |
+
limit = "any" if G_max is None else f"{G_max * 1e3:.0f} mT/m {'✓' if ok else '✗ cannot play'}"
|
| 109 |
+
lines.append(f"| {name} | {b:g} | δ {delta * 1e3:g} / Δ {Delta * 1e3:g} ms | {G * 1e3:.0f} mT/m | {limit} |")
|
| 110 |
+
return "\n".join(lines), all(r[-1] for r in rows)
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def plan_runs(cfg, source, preset, n_b0, snr_on, snr, scheme_file, knob, scanner, values, shell_inputs):
|
| 114 |
+
"""The runs the button asks for, validated before any work: ``[(tag, protocol, snr_on, snr, physics)]`` for A
|
| 115 |
+
and, with a knob, B; refused with the reason when the scanner cannot play a shell or the source cannot do the
|
| 116 |
+
run."""
|
| 117 |
+
S = type(source)
|
| 118 |
+
full = source.mode == "full"
|
| 119 |
+
protocol = _protocol_from_inputs(S, cfg, preset, n_b0, *shell_inputs, scheme=scheme_file, full=full)
|
| 120 |
+
key = P.machine(cfg, scanner)
|
| 121 |
+
runs = [("A", protocol, snr_on, snr, S.physics_from(cfg, values, scanner=key))]
|
| 122 |
+
knobs = S.knobs(cfg)
|
| 123 |
+
if knob not in knobs:
|
| 124 |
+
raise ValueError(f"unknown knob {knob!r}")
|
| 125 |
+
change = knobs[knob]
|
| 126 |
+
if change is not None:
|
| 127 |
+
if key is not None and change[0] in ("field", "b0"):
|
| 128 |
+
raise ValueError(f"the {scanner} fixes the field and its direction: the knob {knob!r} would make B the same run; "
|
| 129 |
+
"choose the ideal scanner to vary them")
|
| 130 |
+
pb, on_b, snr_b, vb = S.apply_knob(cfg, change, protocol, snr_on, snr, values)
|
| 131 |
+
runs.append(("B", pb, on_b, snr_b, S.physics_from(cfg, vb, scanner=key)))
|
| 132 |
+
for tag, prot, _, _, physics in runs:
|
| 133 |
+
table, ok = gradient_text(cfg, prot, source.shapes, scanner)
|
| 134 |
+
if not ok:
|
| 135 |
+
raise ValueError(f"{scanner} cannot play run {tag}'s shells (square pulses):\n\n{table}")
|
| 136 |
+
source.validate(prot, physics)
|
| 137 |
+
return runs
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def _split(S, cfg, rest):
|
| 141 |
+
"""The run signature's tail: the physics panel's values (a dict) and the shell rows."""
|
| 142 |
+
n = len(S.panel(cfg).fields)
|
| 143 |
+
return physics_values(S, cfg, *rest[:n]), rest[n:]
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
def response_entries(source, runs, ladder_on):
|
| 147 |
+
"""The :meth:`~space.pipeline.Source.prepare` entries of :func:`plan_runs`'s ``runs``: ``[(slot, meas, physics)]``
|
| 148 |
+
for A, B and, with the ladder, A's rungs; ``slot`` is ``("runs", tag)`` or ``("ladder", i)``."""
|
| 149 |
+
out = [(("runs", tag), P.measurements(prot, source.shapes), ph) for tag, prot, _, _, ph in runs]
|
| 150 |
+
if ladder_on:
|
| 151 |
+
meas_a = out[0][1]
|
| 152 |
+
out += [(("ladder", i), meas_a, ph) for i, (_, ph) in enumerate(source.ladder_steps(runs[0][4]))]
|
| 153 |
+
return out
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
def prepare_runs(preset, n_b0, snr_on, snr, density, max_angle, step_mm, key, scheme_file, knob, scanner, n_keys, ladder_on, *rest):
|
| 157 |
+
"""The source's share of the runs the inputs ask for as the page's process has it cached
|
| 158 |
+
(:meth:`~space.pipeline.Source.cached`), looked up and never computed, so the GPU call follows the request at
|
| 159 |
+
once: ``{"runs": {tag: ...}, "ladder": [...] or None}``, None for an entry not cached (or a source with nothing
|
| 160 |
+
to prepare); :func:`compute` computes the missing ones."""
|
| 161 |
+
state = _load()
|
| 162 |
+
if state["error"]:
|
| 163 |
+
raise ValueError(f"the source did not load: {state['error']}")
|
| 164 |
+
source, cfg = state["source"], state["cfg"]
|
| 165 |
+
values, shell_inputs = _split(type(source), cfg, rest)
|
| 166 |
+
runs = plan_runs(cfg, source, preset, n_b0, snr_on, snr, scheme_file, knob, scanner, values, shell_inputs)
|
| 167 |
+
out = dict(runs={}, ladder=[] if ladder_on else None)
|
| 168 |
+
for (where, k), meas, ph in response_entries(source, runs, ladder_on):
|
| 169 |
+
hit = source.cached(meas, ph)
|
| 170 |
+
if where == "runs":
|
| 171 |
+
out["runs"][k] = hit
|
| 172 |
+
else:
|
| 173 |
+
out["ladder"].append(hit)
|
| 174 |
+
return out
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def _fill(source, runs, ladder_on, prepared):
|
| 178 |
+
""":func:`prepare_runs`'s entries the page had not cached, computed here (inside the GPU call), a generator: a
|
| 179 |
+
stage text when there are any, then returns ``(prepared, {response_key: result}, seconds)``: the entries
|
| 180 |
+
complete, the ones computed here by key, the time (None for a source with nothing to prepare)."""
|
| 181 |
+
entries = [(slot, meas, ph) for slot, meas, ph in response_entries(source, runs, ladder_on) if source.response_key(meas, ph) is not None]
|
| 182 |
+
if not entries:
|
| 183 |
+
return prepared, {}, None
|
| 184 |
+
out = dict(runs=dict(prepared["runs"]), ladder=None if prepared["ladder"] is None else list(prepared["ladder"]))
|
| 185 |
+
missing = [(slot, meas, ph) for slot, meas, ph in entries if out[slot[0]][slot[1]] is None]
|
| 186 |
+
if missing:
|
| 187 |
+
yield (f"**computing the packs' responses on the worker: not cached on the page** ({len(missing)} of {len(entries)}) …", 0.0)
|
| 188 |
+
t0 = time.perf_counter()
|
| 189 |
+
computed = {}
|
| 190 |
+
for (where, k), meas, ph in missing:
|
| 191 |
+
r = source.cached(meas, ph) # an earlier entry of this run with the same key (B = A but its M0)
|
| 192 |
+
if r is None:
|
| 193 |
+
r = source.prepare(meas, ph)
|
| 194 |
+
computed[source.response_key(meas, ph)] = r
|
| 195 |
+
out[where][k] = r
|
| 196 |
+
return out, computed, time.perf_counter() - t0
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
def _result_state(res, sample, load_seconds):
|
| 200 |
+
"""What the results tab needs, kept per session: float32 volumes, the peaks, the streamline sample, the numbers."""
|
| 201 |
+
pk, amp = P.peaks(res.sh)
|
| 202 |
+
fr = res.extras.get("fractions")
|
| 203 |
+
return dict(dwi=res.dwi.astype(np.float32), floor=res.floor.astype(np.float32), floor_median=P.floor_stats(res)["median"], meas=res.meas,
|
| 204 |
+
peaks=pk.astype(np.float32), peak_amp=amp.astype(np.float32), matrix=res.matrix, score=res.score, seconds=res.seconds,
|
| 205 |
+
load_seconds=load_seconds, tractogram=sample, n_streamlines=len(res.tractogram), shape=res.dwi.shape[:3], name=res.protocol.name,
|
| 206 |
+
extras=dict(fractions=None if fr is None else fr.astype(np.float16)))
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
def _layer_labels(physics, knob):
|
| 210 |
+
"""The explorer's names for A and B: A is the ladder's top rung, named by every tier it has on; B is A with the
|
| 211 |
+
knob."""
|
| 212 |
+
tiers = [q for q in ("relaxation", "contact", "field") if physics and getattr(physics, q)]
|
| 213 |
+
a = "A = bare" + "".join(f" + {q}" for q in tiers) if tiers else "A = bare diffusion"
|
| 214 |
+
return a, f"B = A with {knob}"
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
def _explorer_state(results, ladder, ingredients, knob, source):
|
| 218 |
+
"""What the Replay DWI Explorer keeps per session: the noise-free layers (the ladder, then A, then B) as float16
|
| 219 |
+
volumes with their tensor maps, the replay floor, the ingredient images' layers, the per-shell layer differences."""
|
| 220 |
+
ra = results["A"]; mask = np.isfinite(ra.clean[..., 0])
|
| 221 |
+
name_a, name_b = _layer_labels(ra.physics, knob)
|
| 222 |
+
layers = list(ladder) + [(name_a, ra.clean)] + ([(name_b, results["B"].clean)] if "B" in results else [])
|
| 223 |
+
metrics = {}
|
| 224 |
+
for label, vol in layers:
|
| 225 |
+
try:
|
| 226 |
+
md, fa = P.dti(vol, ra.meas, mask)
|
| 227 |
+
except ValueError: # too few low-b rows for a tensor: no metric maps
|
| 228 |
+
md = fa = None
|
| 229 |
+
metrics[label] = (None if md is None else md.astype(np.float16), None if fa is None else fa.astype(np.float16))
|
| 230 |
+
return dict(layers=[(label, vol.astype(np.float16)) for label, vol in layers], metrics=metrics, floor=ra.floor.astype(np.float32),
|
| 231 |
+
meas=ra.meas, mask=mask, ingredients=source.ingredient_layers(ingredients), differences=P.layer_differences(layers, ra.meas, mask),
|
| 232 |
+
snr=ra.snr, physics=ra.physics)
|
| 233 |
+
|
| 234 |
+
|
| 235 |
+
def _status(text):
|
| 236 |
+
import gradio as gr
|
| 237 |
+
keep = gr.update()
|
| 238 |
+
return (keep, text) + (keep,) * (len(OUTPUTS) - 2)
|
| 239 |
+
|
| 240 |
+
|
| 241 |
+
def _one_run(tag, source, protocol, snr_on, snr, tracking, physics, prepared, t0):
|
| 242 |
+
"""One pipeline run as a generator of ``(text, fraction)`` stage updates, then the :class:`Result` last: ``tag``
|
| 243 |
+
is A or B in the stage text."""
|
| 244 |
+
texts = source.describe(source.cfg)["stages"]
|
| 245 |
+
for item in P.run_stages(source, protocol, snr=(float(snr) if snr_on else None), tracking=tracking, physics=physics, prepared=prepared):
|
| 246 |
+
if isinstance(item, P.Result):
|
| 247 |
+
yield item
|
| 248 |
+
return
|
| 249 |
+
stage, k, n = item
|
| 250 |
+
yield (f"**{tag} · {k + 1}/{n} {texts[stage]}** … ({protocol.n_meas} measurements, {time.perf_counter() - t0:.0f} s so far)", (k + 0.5) / (n + 1))
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
def _write_files(tag, res, source):
|
| 254 |
+
"""The run's files under its tag (the previous run's under the same tag replaced): the full tractogram and a
|
| 255 |
+
sample as .tck, the DWI and FOD volumes, the source's own files; ``(sample, {"tck": [...], "volumes": [...]})``."""
|
| 256 |
+
out = os.path.join(_RUNS, tag); shutil.rmtree(out, ignore_errors=True); os.makedirs(out)
|
| 257 |
+
stem = f"{source.describe(source.cfg)['files']}_{tag}_{res.protocol.name.replace(' ', '_')}"
|
| 258 |
+
tck = os.path.join(out, f"{stem}.tck"); res.tractogram.to_tck(tck)
|
| 259 |
+
sample = P.sample_tractogram(res.tractogram, SAMPLE)
|
| 260 |
+
sample_path = os.path.join(out, f"{stem}_sample{SAMPLE // 1000}k.tck"); sample.to_tck(sample_path)
|
| 261 |
+
vols = P.write_volumes(res, out, prefix=stem, affine=source.affine)
|
| 262 |
+
return sample, dict(tck=[tck, sample_path], volumes=[vols["dwi"], vols["bvals"], vols["bvecs"], vols["fod"]] + source.extra_files(res, out, stem))
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
def explore(ex, layer, mode, metric, z, m):
|
| 266 |
+
"""The explorer's map: ``layer`` of the state's layers, in ``mode`` (the signal, its difference to the previous
|
| 267 |
+
layer, B minus A, or that over the replay floor), as the DWI at measurement ``m`` or a tensor metric, slice ``z``."""
|
| 268 |
+
if not ex:
|
| 269 |
+
return None
|
| 270 |
+
labels = [l for l, _ in ex["layers"]]; vols = dict(ex["layers"])
|
| 271 |
+
if layer not in vols:
|
| 272 |
+
layer = labels[-1]
|
| 273 |
+
z = int(z); m = min(int(m), len(ex["meas"].bvals) - 1)
|
| 274 |
+
k = METRICS.index(metric) if metric in METRICS else 0
|
| 275 |
+
|
| 276 |
+
def field(label):
|
| 277 |
+
if k == 0:
|
| 278 |
+
return np.asarray(vols[label], np.float32)[..., m]
|
| 279 |
+
md, fa = ex["metrics"][label]
|
| 280 |
+
v = md if k == 1 else fa
|
| 281 |
+
return None if v is None else np.asarray(v, np.float32)
|
| 282 |
+
what = f"{metric} of {layer}" if k else f"{layer}: b = {ex['meas'].bvals[m]:g} s/mm², measurement {m}"
|
| 283 |
+
x = field(layer)
|
| 284 |
+
if x is None:
|
| 285 |
+
return None
|
| 286 |
+
if mode == "signal":
|
| 287 |
+
return V.map_slice(x, z, f"{what}, slice z = {z}", cmap="gray" if k == 0 else "viridis", vmin=0 if k == 0 else None, vmax=1 if k != 1 else None)
|
| 288 |
+
if mode == "minus the previous layer":
|
| 289 |
+
i = labels.index(layer)
|
| 290 |
+
if i == 0:
|
| 291 |
+
return V.map_slice(x, z, f"{layer} is the first layer: its signal, slice z = {z}", cmap="gray", vmin=0, vmax=1)
|
| 292 |
+
prev = field(labels[i - 1])
|
| 293 |
+
return V.map_slice(x - prev, z, f"{what} minus {labels[i - 1]}, slice z = {z}", symmetric=True)
|
| 294 |
+
a_label = next((l for l in labels if l.startswith("A")), None); b_label = next((l for l in labels if l.startswith("B")), None)
|
| 295 |
+
if a_label is None or b_label is None:
|
| 296 |
+
return V.map_slice(x, z, f"no B in this run (choose a knob in the acquisition tab): {what}, slice z = {z}", cmap="gray" if k == 0 else "viridis")
|
| 297 |
+
d = field(b_label) - field(a_label)
|
| 298 |
+
if mode == "B − A":
|
| 299 |
+
return V.map_slice(d, z, f"B − A, {metric} at measurement {m}" if k == 0 else f"B − A, {metric}", symmetric=True)
|
| 300 |
+
if not np.any(ex["floor"] > 0):
|
| 301 |
+
return V.map_slice(d, z, "this source has no per-voxel replay floor: B − A, " + (f"{metric} at measurement {m}" if k == 0 else metric), symmetric=True)
|
| 302 |
+
return V.map_slice(d / np.where(ex["floor"] > 0, ex["floor"], np.nan), z, f"(B − A) ÷ replay floor, {metric}" + (f" at measurement {m}" if k == 0 else ""), symmetric=True)
|
| 303 |
+
|
| 304 |
+
|
| 305 |
+
def ingredient_views(ex, z):
|
| 306 |
+
"""The explorer's three ingredient images at slice ``z``, from the source's layers of the run's ingredients."""
|
| 307 |
+
layers = (ex or {}).get("ingredients") or [None, None, None]
|
| 308 |
+
z = int(z)
|
| 309 |
+
return tuple(None if item is None or item[1] is None else V.map_slice(item[1], z, f"{item[0]}, z = {z}", **item[2]) for item in layers)
|
| 310 |
+
|
| 311 |
+
|
| 312 |
+
def layer_table(ex):
|
| 313 |
+
rows = [[a, b, f"{sh:g}", f"{med:.4f}", f"{p99:.4f}"] for a, b, sh, med, p99 in ex["differences"]] if ex else []
|
| 314 |
+
if ex and np.any(ex["floor"] > 0):
|
| 315 |
+
f = ex["floor"][ex["mask"]]
|
| 316 |
+
rows.append(["replay floor", "", "", f"{np.median(f):.4f}", f"{np.quantile(f, 0.99):.4f}"])
|
| 317 |
+
return rows
|
| 318 |
+
|
| 319 |
+
|
| 320 |
+
def compute(prepared, preset, n_b0, snr_on, snr, density, max_angle, step_mm, key, scheme_file, knob, scanner, n_keys, ladder_on, *rest):
|
| 321 |
+
"""Everything a run needs the device for, a generator: ``(text, fraction)`` stage updates while it works, then
|
| 322 |
+
the payload last, a dict of plain data (:class:`P.Result` per tag, the explorer's ladder and ingredient maps, the
|
| 323 |
+
tracker-key spread, the seconds of each step, the source's share the page had not cached as computed here by key
|
| 324 |
+
and its seconds, the clock at the handoff). ``prepared`` is :func:`prepare_runs`'s, ``rest`` the physics panel
|
| 325 |
+
then the shell rows. On a shared GPU pool this runs in the forked worker and its yields cross to the page's
|
| 326 |
+
process; nothing here draws or writes a file, so the device is held for the compute alone."""
|
| 327 |
+
state = _load()
|
| 328 |
+
if state["error"]:
|
| 329 |
+
raise ValueError(f"the source did not load: {state['error']}")
|
| 330 |
+
source, cfg = state["source"], state["cfg"]
|
| 331 |
+
S = type(source)
|
| 332 |
+
values, shell_inputs = _split(S, cfg, rest)
|
| 333 |
+
runs = plan_runs(cfg, source, preset, n_b0, snr_on, snr, scheme_file, knob, scanner, values, shell_inputs)
|
| 334 |
+
for tag, prot, _, _, physics in runs: # full mode: what each run reads, before any byte moves
|
| 335 |
+
plan = source.plan(P.measurements(prot, source.shapes), physics)
|
| 336 |
+
if plan:
|
| 337 |
+
yield (f"**{tag}: full replay of {plan['rows']:,} rows, {plan['bytes'] / 1e9:.1f} GB to read, about "
|
| 338 |
+
f"{plan['estimated_seconds'] / 60:.0f} min** (bands {plan['K']}, field modes {plan['modes']})", 0.0)
|
| 339 |
+
t0 = time.perf_counter()
|
| 340 |
+
prepared, kernels, response_seconds = yield from _fill(source, runs, ladder_on, prepared)
|
| 341 |
+
tracking = S.tracking(cfg, density=density, max_angle=max_angle, step=step_mm, key=key)
|
| 342 |
+
results = {}; seconds = {}
|
| 343 |
+
try:
|
| 344 |
+
for tag, prot, on, s_, ph in runs:
|
| 345 |
+
for item in _one_run(tag, source, prot, on, s_, tracking, ph, prepared["runs"][tag], t0):
|
| 346 |
+
if isinstance(item, P.Result):
|
| 347 |
+
results[tag] = item
|
| 348 |
+
else:
|
| 349 |
+
yield item
|
| 350 |
+
meas_a = results["A"].meas; physics_a = runs[0][4]
|
| 351 |
+
ladder = []
|
| 352 |
+
if ladder_on and physics_a is not None and not physics_a.bare:
|
| 353 |
+
yield (f"**Replay DWI Explorer · the tier ladder of A, noise-free** … ({time.perf_counter() - t0:.0f} s so far)", 0.8)
|
| 354 |
+
t = time.perf_counter(); ladder = source.ladder(meas_a, physics_a, prepared["ladder"]); seconds["explorer · ladder"] = time.perf_counter() - t
|
| 355 |
+
yield (f"**Replay DWI Explorer · the ingredient maps** … ({time.perf_counter() - t0:.0f} s so far)", 0.85)
|
| 356 |
+
t = time.perf_counter(); ingredients = source.ingredients(meas_a, physics_a, prepared["runs"]["A"]); seconds["explorer · ingredients"] = time.perf_counter() - t
|
| 357 |
+
spread = None
|
| 358 |
+
if int(n_keys) > 1: # A's tracking repeated over further keys: the tractogram's own spread
|
| 359 |
+
keys = [int(key) + 1 + i for i in range(int(n_keys) - 1)]
|
| 360 |
+
mats = [results["A"].matrix]; scores = [results["A"].score]
|
| 361 |
+
for i, (k, M, sc, secs) in enumerate(P.repeat_tracking(results["A"], source, tracking, keys)):
|
| 362 |
+
mats.append(M); scores.append(sc)
|
| 363 |
+
yield (f"**A · tracking again with key {k} ({i + 2}/{int(n_keys)})** … ({time.perf_counter() - t0:.0f} s so far)", 0.9)
|
| 364 |
+
spread = P.pair_spread(mats, scores, key=source.score_key())
|
| 365 |
+
finally:
|
| 366 |
+
source.release()
|
| 367 |
+
yield dict(results={tag: _light(r) for tag, r in results.items()}, ladder=[(label, vol.astype(np.float32)) for label, vol in ladder],
|
| 368 |
+
ingredients=ingredients, spread=spread, knob=knob, seconds=seconds, kernels=kernels, response_seconds=response_seconds,
|
| 369 |
+
compute_seconds=time.perf_counter() - t0, handed_off_at=time.time())
|
| 370 |
+
|
| 371 |
+
|
| 372 |
+
def _light(res):
|
| 373 |
+
"""``res`` with its DWI volumes in float32 for the handoff: what the page keeps, draws, fits and writes is float32
|
| 374 |
+
or narrower, so the payload carries half the bytes and the compute's own arithmetic is untouched."""
|
| 375 |
+
return replace(res, dwi=res.dwi.astype(np.float32), clean=None if res.clean is None else res.clean.astype(np.float32))
|
| 376 |
+
|
| 377 |
+
|
| 378 |
+
def present(payload, state):
|
| 379 |
+
"""The page's outputs (:data:`OUTPUTS`, in order) from a compute payload: the files, the per-session states, the
|
| 380 |
+
headline and the figures (A's source share from the page's cache, which holds it after :func:`run_pipeline`).
|
| 381 |
+
Runs where the page runs, never on the device."""
|
| 382 |
+
import gradio as gr
|
| 383 |
+
received = time.time()
|
| 384 |
+
source = state["source"]; load_seconds = state["load_seconds"]; regions = state["regions"]
|
| 385 |
+
results = payload["results"]; ladder = payload["ladder"]; ingredients = payload["ingredients"]; spread = payload["spread"]; knob = payload["knob"]
|
| 386 |
+
post = {}
|
| 387 |
+
if payload.get("response_seconds") is not None:
|
| 388 |
+
post[RESPONSES_ROW] = payload["response_seconds"]
|
| 389 |
+
post.update(payload["seconds"])
|
| 390 |
+
t = time.perf_counter()
|
| 391 |
+
samples = {}; files = {}
|
| 392 |
+
for tag, r in results.items():
|
| 393 |
+
samples[tag], files[tag] = _write_files(tag, r, source)
|
| 394 |
+
post["page · files"] = time.perf_counter() - t; t = time.perf_counter()
|
| 395 |
+
rs = {tag: _result_state(r, samples[tag], load_seconds) for tag, r in results.items()}
|
| 396 |
+
ex = _explorer_state(results, ladder, ingredients, knob, source)
|
| 397 |
+
post["page · states"] = time.perf_counter() - t; t = time.perf_counter()
|
| 398 |
+
labels = [l for l, _ in ex["layers"]]; name_a = labels[-2] if "B" in results else labels[-1]
|
| 399 |
+
ra = rs["A"]; rb = rs.get("B")
|
| 400 |
+
headline = source.score_text("A", results["A"])
|
| 401 |
+
if rb:
|
| 402 |
+
headline += "<br>" + source.score_text("B", results["B"]) + "<br>" + source.compare_text(source.compare(results["A"], results["B"]), knob)
|
| 403 |
+
if spread:
|
| 404 |
+
headline += (f"<br>**A over {spread['n']} tracker keys: {spread['key']} {spread['pearson_mean']:.3f} ± {spread['pearson_std']:.3f}**, "
|
| 405 |
+
f"median pair count CV {spread['cv_median']:.2f}, {spread['pairs_always']} pairs in every run, {spread['pairs_any']} in any.")
|
| 406 |
+
d = source.describe(source.cfg)
|
| 407 |
+
headline += " The Replay DWI Explorer is the third tab, the results the fourth."
|
| 408 |
+
z0 = ra["dwi"].shape[2] // 2
|
| 409 |
+
m0 = int(np.flatnonzero(~ra["meas"].b0)[0]) if (~ra["meas"].b0).any() else 0
|
| 410 |
+
timings = [[f"{tag} · {r}", t_] for tag in rs for r, t_ in V.timings_rows(rs[tag]["seconds"], rs[tag]["load_seconds"])] if rb else V.timings_rows(ra["seconds"], ra["load_seconds"])
|
| 411 |
+
timings += [["device held (compute)", f"{payload['compute_seconds']:.2f}"], ["handoff to the page", f"{received - payload['handed_off_at']:.2f}"]]
|
| 412 |
+
timings += [[k, f"{v:.2f}"] for k, v in post.items()]
|
| 413 |
+
rs["explorer"] = ex # the page state: A, B and the explorer's layers
|
| 414 |
+
box = V.grid_box(ra["shape"], source.affine) if d["views"]["truth"] else ra["shape"]
|
| 415 |
+
pa = source.cached(results["A"].meas, results["A"].physics)
|
| 416 |
+
out = (rs, headline, V.dwi_slice(ra["dwi"], ra["meas"], z0, m0, peaks=ra["peaks"], peak_amp=ra["peak_amp"], overlay=True, label="A: "),
|
| 417 |
+
V.tractogram3d(ra["tractogram"], regions, box, total=ra["n_streamlines"]),
|
| 418 |
+
source.matrices(results["A"].matrix, results["A"].score, results["A"].reference),
|
| 419 |
+
timings, [t_ for f in files.values() for t_ in f["tck"]], [v for f in files.values() for v in f["volumes"]],
|
| 420 |
+
_slider_update(z0, ra["dwi"].shape[2] - 1), _slider_update(m0, results["A"].protocol.n_meas - 1),
|
| 421 |
+
V.tractogram3d(rb["tractogram"], regions, box, total=rb["n_streamlines"]) if rb else None,
|
| 422 |
+
source.matrices(results["B"].matrix, results["B"].score, results["B"].reference) if rb else None,
|
| 423 |
+
gr.update(visible=rb is not None),
|
| 424 |
+
V.floor_slice(ra["floor"], z0, ra["floor_median"], label="A: ") if d["views"]["floor"] else None, source.accuracy(results["A"]),
|
| 425 |
+
V.spread_matrices(spread) if spread else None,
|
| 426 |
+
explore(ex, name_a, "minus the previous layer" if len(labels) > 1 else "signal", METRICS[0], z0, m0),
|
| 427 |
+
explore(ex, name_a, "signal", METRICS[2], z0, m0), *ingredient_views(ex, z0), layer_table(ex),
|
| 428 |
+
gr.update(choices=labels, value=name_a), _slider_update(z0, ra["dwi"].shape[2] - 1), _slider_update(m0, results["A"].protocol.n_meas - 1),
|
| 429 |
+
source.truth_view(ra["dwi"], ra["meas"], z0, m0), source.fractions_view(ra["extras"], z0),
|
| 430 |
+
source.lobar(results["A"].matrix, results["A"].score, results["A"].reference), source.roundtrip_rows(results["A"]),
|
| 431 |
+
source.response_view(pa, results["A"].extras))
|
| 432 |
+
timings.append(["page · figures", f"{time.perf_counter() - t:.2f}"])
|
| 433 |
+
return out
|
| 434 |
+
|
| 435 |
+
|
| 436 |
+
def run_pipeline(compute_fn, *args, progress=None):
|
| 437 |
+
"""The run button, a generator: the source's share of the runs the page has cached (:func:`prepare_runs`, a
|
| 438 |
+
lookup), then the stage texts of ``compute_fn`` (:func:`compute`, or it wrapped for a GPU pool) into the headline
|
| 439 |
+
as they arrive (the other outputs untouched, the progress bar following), then the share the call computed kept
|
| 440 |
+
in the page's cache and the page's outputs from its payload (:func:`present`)."""
|
| 441 |
+
import gradio as gr
|
| 442 |
+
state = _load()
|
| 443 |
+
if state["error"]:
|
| 444 |
+
raise gr.Error(f"the source did not load: {state['error']}")
|
| 445 |
+
if progress:
|
| 446 |
+
progress(0.0, desc="starting")
|
| 447 |
+
payload = None
|
| 448 |
+
try:
|
| 449 |
+
yield _status("**starting the run** (the packs' responses looked up on the page) …")
|
| 450 |
+
prepared = prepare_runs(*args)
|
| 451 |
+
for item in compute_fn(prepared, *args):
|
| 452 |
+
if isinstance(item, dict):
|
| 453 |
+
payload = item
|
| 454 |
+
else:
|
| 455 |
+
text, fraction = item
|
| 456 |
+
if progress:
|
| 457 |
+
progress(fraction, desc=text.split("**")[1] if "**" in text else text)
|
| 458 |
+
yield _status(text)
|
| 459 |
+
except (ValueError, KeyError) as e:
|
| 460 |
+
raise gr.Error(str(e))
|
| 461 |
+
if payload.get("kernels"):
|
| 462 |
+
state["source"].keep(payload["kernels"])
|
| 463 |
+
yield _status(f"**drawing** … (device held {payload['compute_seconds']:.0f} s)")
|
| 464 |
+
yield present(payload, state)
|
| 465 |
+
|
| 466 |
+
|
| 467 |
+
GPU_TIERS = (("logged out", 120), ("free account", 300), ("PRO", 2400)) # ZeroGPU's daily quota per visitor tier, seconds
|
| 468 |
+
|
| 469 |
+
|
| 470 |
+
def estimated_seconds(preset, n_b0, snr_on, snr, density, max_angle, step_mm, key, scheme_file, knob, scanner, n_keys, ladder_on, *rest):
|
| 471 |
+
"""The GPU seconds a run reserves on the shared pool, from its inputs (the same positional inputs as
|
| 472 |
+
:func:`run_pipeline`): the configured source's measured cost model
|
| 473 |
+
(:meth:`~space.pipeline.Source.estimated_seconds`) with the source's share the call computes because the page has
|
| 474 |
+
it not cached (:func:`uncached_responses`). The pool refuses a request above the visitor's daily quota
|
| 475 |
+
(:data:`GPU_TIERS`) and kills a run that outlives its reservation, so this is the measured cost with its margin,
|
| 476 |
+
not a generous one; 480 when the inputs make no protocol."""
|
| 477 |
+
try:
|
| 478 |
+
cfg = P.config()
|
| 479 |
+
S = sources.source_class(cfg)
|
| 480 |
+
n = len(S.panel(cfg).fields)
|
| 481 |
+
protocol = _protocol_from_inputs(S, cfg, preset, n_b0, *rest[n:], scheme=scheme_file, full=S.mode == "full")
|
| 482 |
+
except Exception:
|
| 483 |
+
return 480
|
| 484 |
+
responses = uncached_responses(preset, n_b0, snr_on, snr, density, max_angle, step_mm, key, scheme_file, knob, scanner, n_keys, ladder_on, *rest)
|
| 485 |
+
try:
|
| 486 |
+
machine = P.machine(cfg, scanner)
|
| 487 |
+
except ValueError:
|
| 488 |
+
return 480
|
| 489 |
+
return S.estimated_seconds(cfg, protocol, density=density, knob=knob, n_keys=n_keys, ladder=ladder_on, responses=responses, scanner=machine)
|
| 490 |
+
|
| 491 |
+
|
| 492 |
+
def uncached_responses(preset, n_b0, snr_on, snr, density, max_angle, step_mm, key, scheme_file, knob, scanner, n_keys, ladder_on, *rest):
|
| 493 |
+
"""``(state, n_meas, saves)`` per entry of the source's share of the run the inputs ask for that the page's
|
| 494 |
+
process has not cached (:meth:`~space.pipeline.Source.responses`): what the GPU call computes before its replay. Empty when
|
| 495 |
+
the source is not loaded in this process (the pool's entry loads it before the page serves) or refuses the run
|
| 496 |
+
(it is refused before the GPU call)."""
|
| 497 |
+
source = _state["source"]
|
| 498 |
+
if source is None:
|
| 499 |
+
return []
|
| 500 |
+
cfg = _state["cfg"]
|
| 501 |
+
try:
|
| 502 |
+
values, shell_inputs = _split(type(source), cfg, rest)
|
| 503 |
+
runs = plan_runs(cfg, source, preset, n_b0, snr_on, snr, scheme_file, knob, scanner, values, shell_inputs)
|
| 504 |
+
except (ValueError, KeyError):
|
| 505 |
+
return []
|
| 506 |
+
return source.responses([(meas, ph) for _, meas, ph in response_entries(source, runs, ladder_on)])
|
| 507 |
+
|
| 508 |
+
|
| 509 |
+
def gpu_seconds_text(*args):
|
| 510 |
+
"""The readout under the run button on the pool: the seconds this run reserves against the tiers' quotas, and
|
| 511 |
+
which tiers can run it (a request above a visitor's daily quota is refused by the pool before it starts)."""
|
| 512 |
+
secs = estimated_seconds(*args)
|
| 513 |
+
fits = [name for name, cap in GPU_TIERS if secs <= cap]
|
| 514 |
+
who = ("a visitor " + ", ".join(fits)) if fits else "no tier: split the run (drop B, the ladder or the extra keys)"
|
| 515 |
+
caps = ", ".join(f"{name} {cap // 60} min" for name, cap in GPU_TIERS)
|
| 516 |
+
return (f"**This run reserves {secs} s of GPU.** ZeroGPU grants each visitor a daily quota ({caps}) and refuses a "
|
| 517 |
+
f"single request above it (\"larger than the maximum allowed\"): this run can be started by {who}. "
|
| 518 |
+
f"Log in to Hugging Face in this browser to use your own quota.")
|
| 519 |
+
|
| 520 |
+
|
| 521 |
+
def _slider_update(value, maximum):
|
| 522 |
+
import gradio as gr
|
| 523 |
+
return gr.update(value=int(value), maximum=int(maximum))
|
| 524 |
+
|
| 525 |
+
|
| 526 |
+
def redraw_explorer(rs, layer, mode, metric, z, m):
|
| 527 |
+
ex = rs and rs.get("explorer")
|
| 528 |
+
return (explore(ex, layer, mode, metric, z, m), explore(ex, layer, mode, METRICS[2] if metric == METRICS[0] else metric, z, m), *ingredient_views(ex, z))
|
| 529 |
+
|
| 530 |
+
|
| 531 |
+
def redraw_slice(rs, z, m, overlay, which):
|
| 532 |
+
if not rs or which not in rs:
|
| 533 |
+
return None, None, None, None
|
| 534 |
+
r = rs[which]; source = _load()["source"]
|
| 535 |
+
views = source.describe(source.cfg)["views"]
|
| 536 |
+
return (V.dwi_slice(r["dwi"], r["meas"], int(z), int(m), peaks=r["peaks"], peak_amp=r["peak_amp"], overlay=bool(overlay), label=f"{which}: "),
|
| 537 |
+
V.floor_slice(r["floor"], int(z), r["floor_median"], label=f"{which}: ") if views["floor"] else None,
|
| 538 |
+
source.truth_view(r["dwi"], r["meas"], int(z), int(m)), source.fractions_view(r["extras"], int(z)))
|
| 539 |
+
|
| 540 |
+
|
| 541 |
+
def ground_truth_views():
|
| 542 |
+
"""The truth tab's views, drawn once per process."""
|
| 543 |
+
state = _load()
|
| 544 |
+
if state["error"]:
|
| 545 |
+
return None, None
|
| 546 |
+
if state["gt_views"] is None:
|
| 547 |
+
state["gt_views"] = state["source"].truth_views()
|
| 548 |
+
return state["gt_views"]
|
| 549 |
+
|
| 550 |
+
|
| 551 |
+
def _widget(c):
|
| 552 |
+
"""The Gradio component of a panel :class:`~space.pipeline.Control` (an input kind)."""
|
| 553 |
+
import gradio as gr
|
| 554 |
+
common = dict(label=c.label, visible=c.visible, interactive=c.interactive)
|
| 555 |
+
if c.kind == "checkbox":
|
| 556 |
+
return gr.Checkbox(value=bool(c.value), **common)
|
| 557 |
+
if c.kind == "number":
|
| 558 |
+
return gr.Number(value=c.value, **common)
|
| 559 |
+
if c.kind == "slider":
|
| 560 |
+
return gr.Slider(c.minimum, c.maximum, value=c.value, step=c.step, **common)
|
| 561 |
+
if c.kind == "dropdown":
|
| 562 |
+
return gr.Dropdown(list(c.choices), value=c.value, **common)
|
| 563 |
+
raise ValueError(f"unknown control kind {c.kind!r}")
|
| 564 |
+
|
| 565 |
+
|
| 566 |
+
def build(runner=None, cfg=None):
|
| 567 |
+
"""The Blocks of the configured source (``cfg``, else :func:`space.pipeline.config`). ``runner`` wraps
|
| 568 |
+
:func:`compute` for the run button (the ZeroGPU entry passes ``spaces.GPU(...)``): the device part of a run; the
|
| 569 |
+
page looks up its cache before it and draws from its payload after it, in this process."""
|
| 570 |
+
import gradio as gr
|
| 571 |
+
cfg = cfg or P.config()
|
| 572 |
+
S = sources.source_class(cfg)
|
| 573 |
+
d = S.describe(cfg)
|
| 574 |
+
full = S.mode == "full"
|
| 575 |
+
shapes = S.shapes_of(cfg); presets = S.presets(cfg) + [CUSTOM] + ([UPLOADED] if full else [])
|
| 576 |
+
shape_names = [n for n in shapes]
|
| 577 |
+
panel = S.panel(cfg); tc = S.tracking_controls(cfg)
|
| 578 |
+
with gr.Blocks(title=d["title"], delete_cache=(3600, 3600)) as demo:
|
| 579 |
+
gr.Markdown(
|
| 580 |
+
d["heading"]
|
| 581 |
+
+ ("\n\n**Before you press run:** the GPU time of a run is charged to *your* Hugging Face quota, not the Space's: "
|
| 582 |
+
"2 minutes a day logged out, 5 with a free account, 40 with PRO. The line under the run button says how many "
|
| 583 |
+
"seconds the configured run reserves and which of those can start it; a request above your quota is refused "
|
| 584 |
+
"before it starts, so log in to Hugging Face in this browser if you want more than one run a day." if runner is not None else "")
|
| 585 |
+
+ "\n\n**Fixed here:** " + "; ".join(d["fixed"]) + ".")
|
| 586 |
+
result = gr.State(None)
|
| 587 |
+
with gr.Tabs():
|
| 588 |
+
with gr.Tab("1 · acquisition, tissue and scanner"):
|
| 589 |
+
with gr.Row():
|
| 590 |
+
with gr.Column(scale=1):
|
| 591 |
+
preset = gr.Dropdown(presets, value=presets[0], label="acquisition")
|
| 592 |
+
n_b0 = gr.Slider(1, 10, value=1, step=1, label="b = 0 measurements (custom shells)")
|
| 593 |
+
shell_inputs = []
|
| 594 |
+
for k in range(MAX_SHELLS):
|
| 595 |
+
with gr.Row():
|
| 596 |
+
on = gr.Checkbox(value=(k == 0), label=f"shell {k + 1}")
|
| 597 |
+
shape = gr.Dropdown(shape_names, value=shape_names[0], label="pulse timing δ / Δ", visible=not full)
|
| 598 |
+
b = gr.Number(value=[1000, 2000, 3000, 6000][k], label="b (s/mm²)")
|
| 599 |
+
n = gr.Slider(6, 128, value=[30, 60, 90, 60][k], step=1, label="directions")
|
| 600 |
+
delta = gr.Number(value=10.2, label="δ (ms)", visible=full)
|
| 601 |
+
Delta = gr.Number(value=16.7, label="Δ (ms)", visible=full)
|
| 602 |
+
TE = gr.Number(value=53.5, label="TE (ms)", visible=full)
|
| 603 |
+
shell_inputs += [on, shape, b, n, delta, Delta, TE]
|
| 604 |
+
gr.Markdown(d["acquisition"])
|
| 605 |
+
scheme_file = gr.File(label="uploaded scheme: Camino STEJSKALTANNER (.scheme)", file_count="single", type="filepath", visible=full)
|
| 606 |
+
with gr.Column(scale=1):
|
| 607 |
+
field_presets = {f"{f:g} T": float(f) for f in panel.field_presets}
|
| 608 |
+
widgets = {}; catalogue_note = reset = field_preset = None
|
| 609 |
+
with gr.Accordion("tissue and scanner: the physics tiers", open=True):
|
| 610 |
+
for row in panel.rows:
|
| 611 |
+
with gr.Row():
|
| 612 |
+
for c in row:
|
| 613 |
+
if c.kind == "field_preset":
|
| 614 |
+
field_preset = gr.Dropdown(list(c.choices), value=c.value, label=c.label)
|
| 615 |
+
elif c.kind == "catalogue_note":
|
| 616 |
+
catalogue_note = gr.Markdown(c.value)
|
| 617 |
+
elif c.kind == "reset":
|
| 618 |
+
reset = gr.Button(c.label, size="sm")
|
| 619 |
+
elif c.kind == "markdown":
|
| 620 |
+
gr.Markdown(c.value)
|
| 621 |
+
else:
|
| 622 |
+
widgets[c.name] = _widget(c)
|
| 623 |
+
gr.Markdown(d["tissue"])
|
| 624 |
+
physics_inputs = [widgets[name] for name in panel.fields]
|
| 625 |
+
with gr.Row():
|
| 626 |
+
snr_on = gr.Checkbox(value=True, label="add Rician noise")
|
| 627 |
+
snr = gr.Slider(5, 100, value=30, step=1, label="SNR at M0 (a full water voxel before relaxation; each voxel's b = 0 SNR follows its tissue)")
|
| 628 |
+
density = gr.Slider(tc["density"][0], tc["density"][1], value=tc["density"][2], step=tc["density"][3], label=tc["density"][4])
|
| 629 |
+
max_angle = gr.Slider(tc["max_angle"][0], tc["max_angle"][1], value=tc["max_angle"][2], step=tc["max_angle"][3], label=tc["max_angle"][4])
|
| 630 |
+
step_mm = gr.Slider(tc["step"][0], tc["step"][1], value=tc["step"][2], step=tc["step"][3], label=tc["step"][4])
|
| 631 |
+
key = gr.Number(value=0, precision=0, label="random key")
|
| 632 |
+
knob = gr.Dropdown(list(S.knobs(cfg)), value=NO_KNOB, label="B: the same run with one knob changed")
|
| 633 |
+
scanner = gr.Dropdown([IDEAL] + list(P.machines(cfg)), value=IDEAL,
|
| 634 |
+
label="scanner: a catalogued machine sets the field and its direction, plays every term "
|
| 635 |
+
"its catalogue entry carries, and refuses a shell beyond its gradient limit")
|
| 636 |
+
scanner_terms = gr.Markdown(P.scanner_text(cfg, IDEAL, S.refused_machines(cfg)))
|
| 637 |
+
gradients = gr.Markdown()
|
| 638 |
+
n_keys = gr.Slider(1, 8, value=1, step=1, label="repeat A's tracking over N keys (the tractogram's own spread)")
|
| 639 |
+
ladder_on = gr.Checkbox(value=not full, visible=not full, label=d["ladder"])
|
| 640 |
+
go = gr.Button(d["run_label"], variant="primary")
|
| 641 |
+
gpu_text = gr.Markdown(visible=runner is not None)
|
| 642 |
+
headline = gr.Markdown()
|
| 643 |
+
with gr.Tab(d["truth_tab"]) as gt_tab:
|
| 644 |
+
strands_view = gr.Plot(label=d["truth_labels"][0])
|
| 645 |
+
gt_matrix = gr.Image(label=d["truth_labels"][1], type="pil")
|
| 646 |
+
gr.Markdown(f"**The truth:** {d['truth']}.")
|
| 647 |
+
with gr.Tab("3 · Replay DWI Explorer"):
|
| 648 |
+
gr.Markdown(d["explorer"])
|
| 649 |
+
with gr.Row():
|
| 650 |
+
ingredient_pool = gr.Image(label=d["ingredients"][0], type="pil")
|
| 651 |
+
ingredient_contact = gr.Image(label=d["ingredients"][1], type="pil")
|
| 652 |
+
ingredient_field = gr.Image(label=d["ingredients"][2], type="pil")
|
| 653 |
+
with gr.Row():
|
| 654 |
+
layer_choice = gr.Dropdown(["A"], value="A", label="layer")
|
| 655 |
+
mode = gr.Radio(list(EXPLORE_MODES), value=EXPLORE_MODES[0], label="show")
|
| 656 |
+
metric = gr.Radio(list(METRICS), value=METRICS[0], label="quantity")
|
| 657 |
+
with gr.Row():
|
| 658 |
+
ez_slider = gr.Slider(0, 39, value=20, step=1, label="axial slice z")
|
| 659 |
+
em_slider = gr.Slider(0, 363, value=0, step=1, label="measurement (DWI only)")
|
| 660 |
+
with gr.Row():
|
| 661 |
+
explore_view = gr.Image(label="the chosen layer and mode", type="pil")
|
| 662 |
+
metric_view = gr.Image(label="the same for FA (or the chosen metric)", type="pil")
|
| 663 |
+
layer_tbl = gr.Dataframe(headers=["from", "to", "b (s/mm²)", "median |ΔS|", "99 % |ΔS|"], label="layer differences per shell, and the replay floor", interactive=False)
|
| 664 |
+
response_view = gr.Image(label="estimated vs true response per tissue", type="pil", visible=d["views"]["response"])
|
| 665 |
+
with gr.Tab(d["results_tab"]):
|
| 666 |
+
with gr.Row():
|
| 667 |
+
with gr.Column(scale=1):
|
| 668 |
+
dwi_view = gr.Image(label="DWI slice", type="pil")
|
| 669 |
+
with gr.Row():
|
| 670 |
+
z_slider = gr.Slider(0, 39, value=20, step=1, label="axial slice z")
|
| 671 |
+
m_slider = gr.Slider(0, 363, value=0, step=1, label="measurement")
|
| 672 |
+
overlay = gr.Checkbox(value=True, label="FOD principal directions")
|
| 673 |
+
which = gr.Radio(["A", "B"], value="A", label="run")
|
| 674 |
+
with gr.Column(scale=1, visible=d["views"]["truth"]):
|
| 675 |
+
truth_view = gr.Image(label="the same slice with the input FOD's principal directions", type="pil")
|
| 676 |
+
with gr.Column(scale=1):
|
| 677 |
+
tract_view = gr.Plot(label="tractogram A")
|
| 678 |
+
fractions_view = gr.Image(label="recovered vs input fractions", type="pil", visible=d["views"]["fractions"])
|
| 679 |
+
mats = gr.Image(label="connectome A vs its truth", type="pil")
|
| 680 |
+
lobar_view = gr.Image(label="connectome A vs its truth over the lobar groups", type="pil", visible=d["views"]["lobar"])
|
| 681 |
+
with gr.Row(visible=False) as b_row:
|
| 682 |
+
tract_view_b = gr.Plot(label="tractogram B")
|
| 683 |
+
mats_b = gr.Image(label="connectome B vs its truth", type="pil")
|
| 684 |
+
spread_view = gr.Image(label="A over N tracker keys: mean and spread per pair", type="pil")
|
| 685 |
+
roundtrip = gr.Dataframe(headers=["what", "value"], label="the round trip: the reconstruction and the connectome against the input",
|
| 686 |
+
interactive=False, wrap=True, visible=d["views"]["roundtrip"])
|
| 687 |
+
with gr.Accordion("accuracy: what this replay is an approximation of", open=False):
|
| 688 |
+
gr.Markdown(d["accuracy"])
|
| 689 |
+
with gr.Row():
|
| 690 |
+
floor_view = gr.Image(label="split-half floor (this run, the slice above)", type="pil", visible=d["views"]["floor"])
|
| 691 |
+
accuracy = gr.Dataframe(headers=["what", "value"], label="the source and this run", interactive=False, wrap=True)
|
| 692 |
+
with gr.Row():
|
| 693 |
+
timings = gr.Dataframe(headers=["stage", "seconds"], label="timings", interactive=False)
|
| 694 |
+
with gr.Column():
|
| 695 |
+
tck = gr.File(label="tractograms (.tck, MRtrix): every streamline, and a 10k sample", file_count="multiple")
|
| 696 |
+
volumes = gr.File(label=d["volumes_label"], file_count="multiple")
|
| 697 |
+
compute_fn = compute if runner is None else runner(compute) # the device part alone runs under a pool's GPU
|
| 698 |
+
|
| 699 |
+
def run_with_progress(*args, progress=gr.Progress()):
|
| 700 |
+
yield from run_pipeline(compute_fn, *args, progress=progress)
|
| 701 |
+
tissue_numbers = [widgets[name] for name in panel.catalogue] + [catalogue_note]
|
| 702 |
+
field_preset.change(lambda name: [field_presets[name]] + S.catalogue_numbers(cfg, field_presets[name]), inputs=field_preset,
|
| 703 |
+
outputs=[widgets["field_T"]] + tissue_numbers, show_progress="hidden")
|
| 704 |
+
reset.click(lambda f: S.catalogue_numbers(cfg, f), inputs=widgets["field_T"], outputs=tissue_numbers, show_progress="hidden")
|
| 705 |
+
|
| 706 |
+
def show_gradients(preset_, n_b0_, scanner_, scheme_, *shells_):
|
| 707 |
+
try:
|
| 708 |
+
prot = _protocol_from_inputs(S, cfg, preset_, n_b0_, *shells_, scheme=scheme_, full=full)
|
| 709 |
+
except (ValueError, KeyError) as e:
|
| 710 |
+
return f"({e})"
|
| 711 |
+
return gradient_text(cfg, prot, shapes, scanner_)[0]
|
| 712 |
+
|
| 713 |
+
def choose_scanner(label, field_now):
|
| 714 |
+
"""The menu's machine: its term table, its field on the slider and the catalogue's tissue at it (the ideal
|
| 715 |
+
scanner keeps the field as set)."""
|
| 716 |
+
key = P.machine(cfg, label)
|
| 717 |
+
f = float(field_now) if key is None else float(P.limits(key).field_T)
|
| 718 |
+
return [P.scanner_text(cfg, label, S.refused_machines(cfg)), f] + (S.catalogue_numbers(cfg, f) if key is not None else [gr.update()] * len(tissue_numbers))
|
| 719 |
+
scanner.change(choose_scanner, inputs=[scanner, widgets["field_T"]], outputs=[scanner_terms, widgets["field_T"]] + tissue_numbers,
|
| 720 |
+
show_progress="hidden")
|
| 721 |
+
for ctl in (preset, scanner, scheme_file, *shell_inputs):
|
| 722 |
+
ctl.change(show_gradients, inputs=[preset, n_b0, scanner, scheme_file, *shell_inputs], outputs=gradients, show_progress="hidden")
|
| 723 |
+
outputs = dict(result=result, headline=headline, dwi_view=dwi_view, tract_view=tract_view, mats=mats, timings=timings, tck=tck,
|
| 724 |
+
volumes=volumes, z_slider=z_slider, m_slider=m_slider, tract_view_b=tract_view_b, mats_b=mats_b, b_row=b_row,
|
| 725 |
+
floor_view=floor_view, accuracy=accuracy, spread_view=spread_view, explore_view=explore_view, metric_view=metric_view,
|
| 726 |
+
ingredient_pool=ingredient_pool, ingredient_contact=ingredient_contact, ingredient_field=ingredient_field,
|
| 727 |
+
layer_table=layer_tbl, layer_choice=layer_choice, ez_slider=ez_slider, em_slider=em_slider, truth_view=truth_view,
|
| 728 |
+
fractions_view=fractions_view, lobar_view=lobar_view, roundtrip=roundtrip, response_view=response_view)
|
| 729 |
+
for ctl in (layer_choice, mode, metric, ez_slider, em_slider):
|
| 730 |
+
ctl.change(redraw_explorer, inputs=[result, layer_choice, mode, metric, ez_slider, em_slider],
|
| 731 |
+
outputs=[explore_view, metric_view, ingredient_pool, ingredient_contact, ingredient_field], show_progress="hidden")
|
| 732 |
+
run_inputs = [preset, n_b0, snr_on, snr, density, max_angle, step_mm, key, scheme_file, knob, scanner, n_keys, ladder_on, *physics_inputs, *shell_inputs]
|
| 733 |
+
if runner is not None: # the pool: what the run reserves, live as the inputs change
|
| 734 |
+
gr.on([c.change for c in run_inputs] + [demo.load], gpu_seconds_text, inputs=run_inputs, outputs=gpu_text, show_progress="hidden")
|
| 735 |
+
run_event = go.click(run_with_progress, inputs=run_inputs,
|
| 736 |
+
outputs=[outputs[name] for name in OUTPUTS], concurrency_limit=1, api_name="run_pipeline") # the endpoint tools/live.py drives
|
| 737 |
+
if runner is not None: # the run's responses are now cached on the page: the reservation falls
|
| 738 |
+
run_event.then(gpu_seconds_text, inputs=run_inputs, outputs=gpu_text, show_progress="hidden")
|
| 739 |
+
for ctl in (z_slider, m_slider, overlay, which):
|
| 740 |
+
ctl.change(redraw_slice, inputs=[result, z_slider, m_slider, overlay, which], outputs=[dwi_view, floor_view, truth_view, fractions_view], show_progress="hidden")
|
| 741 |
+
gt_tab.select(ground_truth_views, outputs=[strands_view, gt_matrix])
|
| 742 |
+
demo.load(lambda: (_load().get("error") and f"**the source did not load:** {_load()['error']}") or "", outputs=headline)
|
| 743 |
+
return demo
|
| 744 |
+
|
| 745 |
+
|
| 746 |
+
if __name__ == "__main__":
|
| 747 |
+
threading.Thread(target=_load, daemon=True).start() # download and warm while the page comes up
|
| 748 |
+
build().queue(max_size=8).launch(server_name="0.0.0.0", server_port=int(os.environ.get("PORT", 7860)))
|
space/brain.toml
ADDED
|
@@ -0,0 +1,175 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# The brain Space: what is pinned. Every number the app shows comes from pipeline.py and sources/brain.py on this
|
| 2 |
+
# configuration. DISCO_CONFIG=brain.toml selects it (the entry app.py, tools/deploy.py --config, tools/live.py --config).
|
| 3 |
+
|
| 4 |
+
source = "brain" # space/sources/brain.py
|
| 5 |
+
|
| 6 |
+
# The asset: the multi-tissue CSD of the subject's scan (WM FOD, WM/GM/CSF fractions, mask), its parcellation
|
| 7 |
+
# (labels, regions.json, stop mask) and a mean b = 0, made once offline (disco-space#8 steps 2-4). A public Hub
|
| 8 |
+
# dataset at a revision, downloaded into the Hub cache when the container starts; `local = "/dir"` (or
|
| 9 |
+
# DISCO_BRAIN_ASSET in the environment) reads a directory instead.
|
| 10 |
+
[asset]
|
| 11 |
+
hub = "SubstrateCommons/masivar-brain"
|
| 12 |
+
revision = "7556d3900adfe73f2b78b34fffb74902354775e9" # MASiVar sub-cIs1 ses-s1Ax1, dmipy-fit 11294e9 (mask eroded 3, tournier13) csd_msmt_torch, 2026-10-01 (revision 3)
|
| 13 |
+
|
| 14 |
+
[describe]
|
| 15 |
+
title = "Brain replay: MASiVar"
|
| 16 |
+
subject = "MASiVar sub-cIs1 (OpenNeuro ds003416, Cai et al. MRM 2021, CC0)"
|
| 17 |
+
heading = """A real brain as a compositional replay phantom: the multi-tissue CSD of one scan (its white-matter FOD field and \
|
| 18 |
+
WM / GM / CSF fractions) composed with replay packs, one Monte-Carlo walk per tissue. Choose an acquisition, the tissue and the \
|
| 19 |
+
scanner; the Space replays every brain voxel from the packs' responses, adds noise, estimates the tissue responses from the \
|
| 20 |
+
replayed data, fits multi-tissue CSD, tracks from the white matter and scores the 84-region connectome against the connectome of \
|
| 21 |
+
the input FOD tracked the same way. The progress bar names each stage."""
|
| 22 |
+
scan_preset = "the scan's own protocol"
|
| 23 |
+
|
| 24 |
+
# The pulse timing the scan's own protocol plays when the asset's manifest states none (MASiVar's sidecars carry no
|
| 25 |
+
# EchoTime, delta or Delta): the BATMAN capstone's square pulses, which the 100 ms packs play; the page says it is assumed.
|
| 26 |
+
[scan]
|
| 27 |
+
delta = 0.025
|
| 28 |
+
Delta = 0.055
|
| 29 |
+
TE = 0.100
|
| 30 |
+
|
| 31 |
+
# The timing classes a shell plays (square pulses; delta / Delta / TE in seconds, kind = "pgste" a stimulated echo
|
| 32 |
+
# storing for TM = Delta - delta, whose TE = 2 t_store + TM includes the storage). A pack is its walk in windows
|
| 33 |
+
# (RPK.md 4.3; 125 ms for the menu's windowed packs); a class reads the windows its acquisition reaches
|
| 34 |
+
# (Brain.windows_reached: the classes up to TE 100 ms window 0), and a class beyond a pack's walk or its declared windows is refused by name. The scan's own class
|
| 35 |
+
# (`scan`) comes from the asset's manifest.
|
| 36 |
+
[shapes."d12-D24"]
|
| 37 |
+
label = "clinical δ 12 / Δ 24 ms, TE 60 ms"
|
| 38 |
+
delta = 0.012
|
| 39 |
+
Delta = 0.024
|
| 40 |
+
TE = 0.060
|
| 41 |
+
[shapes."d17-D30"]
|
| 42 |
+
label = "research δ 17 / Δ 30 ms, TE 70 ms"
|
| 43 |
+
delta = 0.017
|
| 44 |
+
Delta = 0.030
|
| 45 |
+
TE = 0.070
|
| 46 |
+
[shapes."d25-D55"]
|
| 47 |
+
label = "long δ 25 / Δ 55 ms, TE 100 ms (the BATMAN capstone's)"
|
| 48 |
+
delta = 0.025
|
| 49 |
+
Delta = 0.055
|
| 50 |
+
TE = 0.100
|
| 51 |
+
[shapes."ste-d12-TM36"]
|
| 52 |
+
label = "stimulated echo δ 12 / TM 36 ms (Δ 48 ms), TE 70 ms"
|
| 53 |
+
delta = 0.012
|
| 54 |
+
Delta = 0.048
|
| 55 |
+
TE = 0.070
|
| 56 |
+
kind = "pgste"
|
| 57 |
+
# The classes only a walk longer than 100 ms plays (two windows of the 1 s pack); a 100 ms pack refuses them by name.
|
| 58 |
+
[shapes."ste-d12-TM150"]
|
| 59 |
+
label = "long stimulated echo δ 12 / TM 150 ms (Δ 162 ms), TE 184 ms: a walk beyond 100 ms (two windows)"
|
| 60 |
+
delta = 0.012
|
| 61 |
+
Delta = 0.162
|
| 62 |
+
TE = 0.184
|
| 63 |
+
kind = "pgste"
|
| 64 |
+
[shapes."long-TE-d30-D120"]
|
| 65 |
+
label = "long-TE δ 30 / Δ 120 ms, TE 160 ms: a walk beyond 100 ms (two windows)"
|
| 66 |
+
delta = 0.030
|
| 67 |
+
Delta = 0.120
|
| 68 |
+
TE = 0.160
|
| 69 |
+
|
| 70 |
+
# Presets besides the scan's own protocol (which comes from the asset). b in s/mm^2.
|
| 71 |
+
[presets."clinical b1000 x 30"]
|
| 72 |
+
n_b0 = 1
|
| 73 |
+
shells = [{ shape = "d12-D24", b = 1000, n_dirs = 30 }]
|
| 74 |
+
[presets."research 3-shell x 90"]
|
| 75 |
+
n_b0 = 3
|
| 76 |
+
shells = [
|
| 77 |
+
{ shape = "d17-D30", b = 1000, n_dirs = 90 },
|
| 78 |
+
{ shape = "d17-D30", b = 2000, n_dirs = 90 },
|
| 79 |
+
{ shape = "d17-D30", b = 3000, n_dirs = 90 },
|
| 80 |
+
]
|
| 81 |
+
|
| 82 |
+
# The tissue and the scanner: the field presets (T), the default field, whether a run starts with the tiers on, and
|
| 83 |
+
# the values the "M0 of GM" knob offers B. The tissue's numbers come from dmipy-sim's biophysical constants by key.
|
| 84 |
+
[physics]
|
| 85 |
+
fields = [0.064, 1.5, 3.0, 7.0, 11.7]
|
| 86 |
+
default_field = 3.0
|
| 87 |
+
default_on = true
|
| 88 |
+
m0_gm_knob = [0.7, 1.0]
|
| 89 |
+
|
| 90 |
+
# The scanner menu after "ideal": catalogue machines whose every catalogued term the brain applies, the head centre at
|
| 91 |
+
# isocentre (docs/scanner.md). Each voxel is binned into an encoding class by what the machine delivers there, to
|
| 92 |
+
# `tolerance` of b (dmipy_sim.phantom.bore.encoding_classes), and every class's played acquisition is expanded by the
|
| 93 |
+
# packs. `refused` are the machines kept off the menu, each shown under it with the reason (Brain.refused_machines):
|
| 94 |
+
# the Swoop, whose own gradient makes the head thousands of encoding classes (docs/scanner.md).
|
| 95 |
+
[scanners]
|
| 96 |
+
machines = [
|
| 97 |
+
{ label = "Siemens Prisma 3 T", key = "siemens_magnetom_prisma_3T" },
|
| 98 |
+
{ label = "Siemens Terra 7 T", key = "siemens_magnetom_terra_7T" },
|
| 99 |
+
]
|
| 100 |
+
refused = [
|
| 101 |
+
{ label = "Hyperfine Swoop 64 mT", key = "hyperfine_swoop_64mT" },
|
| 102 |
+
]
|
| 103 |
+
tolerance = 0.01
|
| 104 |
+
|
| 105 |
+
# The pack menu per tissue (the first is the default): a label and a pack URI (hf:// or a local path, as
|
| 106 |
+
# dmipy_sim.phantom.PackSubstrate resolves it). A Hub pack declaring several windows loads the windows a run reaches
|
| 107 |
+
# (Brain.pack); a local path or a one-window pack loads whole. SubstrateCommons family records feed this later (disco-space#8, decision 5).
|
| 108 |
+
[packs]
|
| 109 |
+
wm = [
|
| 110 |
+
{ label = "CACTUS single bundle, 1 s walk in 125 ms windows (1280 Hz)", uri = "hf://SubstrateCommons/cactus-axons/packs/single_bundle_1s_c3_seg125ms.rpk" },
|
| 111 |
+
{ label = "canonical cylinder, 2 µm, 100 ms", uri = "hf://SubstrateCommons/canonical-pores/packs/cylinder/d02.00um.rpk" },
|
| 112 |
+
]
|
| 113 |
+
gm = [
|
| 114 |
+
{ label = "grey-matter spheres, 250 ms in 125 ms windows (240 Hz)", uri = "hf://SubstrateCommons/grey-matter-spheres/packs/packed_spheres_leaky_250ms_c2_seg125ms.rpk" },
|
| 115 |
+
{ label = "grey-matter spheres, 100 ms", uri = "hf://SubstrateCommons/grey-matter-spheres/packs/gm_spheres_100ms.rpk" },
|
| 116 |
+
]
|
| 117 |
+
|
| 118 |
+
# The compute backend: the brain's replay contraction is torch on the device; the CSD solver and the tracker follow
|
| 119 |
+
# this backend. DISCO_BACKEND overrides.
|
| 120 |
+
[compute]
|
| 121 |
+
backend = "torch"
|
| 122 |
+
resident = false
|
| 123 |
+
|
| 124 |
+
# The reconstruction: msmt (three-tissue responses from the data + multi-shell multi-tissue CSD, dmipy-fit#39) or
|
| 125 |
+
# tournier07 (single-fibre response + single-tissue CSD). DISCO_RECONSTRUCTION overrides.
|
| 126 |
+
[reconstruction]
|
| 127 |
+
method = "msmt"
|
| 128 |
+
|
| 129 |
+
[tracking]
|
| 130 |
+
density = 2 # seeds per WM voxel = density^3
|
| 131 |
+
step_mm = 1.25
|
| 132 |
+
max_angle = 45.0
|
| 133 |
+
|
| 134 |
+
# The GPU reservation model (Brain.estimated_seconds): a run = fixed + per_meas x n + track[d] (A's tracking), plus
|
| 135 |
+
# track[d] for the truth (the input FOD tracked the same way, shared by B), per_meas_ladder x n for the ladder, B = a
|
| 136 |
+
# run without the worker's start, track[d] per extra key; times margin. Refit from tools/measure_brain.py on an L40S
|
| 137 |
+
# with the BATMAN fixture (90,205 voxels, 36,605 WM seeds per density^3; README-brain-zero.md has the table), each
|
| 138 |
+
# device stage x 1.5 for the pool (DiSCo's CSD and tracking ran 1.1-1.3x slower on the pool than on an L40S), the
|
| 139 |
+
# worker's start and a multi-GB payload's handoff 12 s. The single-tissue reconstruction's cost is in per_meas
|
| 140 |
+
# (8.0 s at 495 measurements); refit when dmipy-fit#39's multi-tissue path runs. Seconds.
|
| 141 |
+
[budget]
|
| 142 |
+
worker = 12.0 # the worker's start and the payload's handoff
|
| 143 |
+
fixed = 16.0 # worker + noise, the round trip, the scoring and the explorer's maps (L40S 2.5 s x 1.5)
|
| 144 |
+
per_meas = 0.03 # the contraction and the reconstruction per measurement (L40S 8.9 s at 495 x 1.5 / 495)
|
| 145 |
+
ladder_per_meas = 0.002 # the ladder's rungs of contraction (L40S 0.5 s at 495 x 1.5 / 495)
|
| 146 |
+
margin = 1.3
|
| 147 |
+
# The packs' pose responses the GPU worker computes when the page has them not cached (Brain.responses), JAX on
|
| 148 |
+
# the CPU: fixed + per_meas x n per entry, bounding every measurement on a CPU host (8 threads; the pool's worker has
|
| 149 |
+
# 192 CPUs, taken as x 1.0) over the scan (113), clinical (31) and two 4 x 128 + 10 custom protocols (522; TE 100 ms
|
| 150 |
+
# alone and four mixed classes), fields 0.064-12 T. cold: a field band not compiled in this process (the scan at
|
| 151 |
+
# 11.7 T 16.6 s, at 11.7 T with chi x 1.1 29.4 s, 4 x 128 at TE 100 ms and 12 T 49.9 s); warm: a compiled band at
|
| 152 |
+
# another tissue or field direction (2.3 / 6.8 / 14.7 s at 31 / 113 / 522); no_field: the field tier off, nothing
|
| 153 |
+
# compiles (0.7 / 1.7 / 3.3 s). An entry is priced fixed + per_meas x n_meas + per_save x saves, where saves is the
|
| 154 |
+
# number of the WM pack's saves the entry's acquisition spans, k (n_t - 1) + 1 for the k windows of n_t saves it
|
| 155 |
+
# reaches (Brain.windows_needed, Brain.saves_spanned; a one-window pack's n_t): per_save is seconds per save spanned,
|
| 156 |
+
# priced independent of the measurement count: the slope of prepare's seconds over the saves at one protocol, the 485
|
| 157 |
+
# measurements of MASiVar's (the measurements' share stays in per_meas). Measured on a CPU host (4 threads,
|
| 158 |
+
# tools/measure_brain.py --saves): prepare on the 100 ms legacy pack (1,002 saves) and the 1 s Swoop pack's prefixes
|
| 159 |
+
# of 100 / 204 ms (ReplayPack.prefix per shard: 1,303 / 2,656 saves), three runs, the third adding the 85 ms prefix
|
| 160 |
+
# (1,107 saves) and playing the d17-D30 class instead of the scan's. With the field
|
| 161 |
+
# tier off the slope is 0.0008-0.0016 s per save; the field states' slopes (-0.0015 to +0.0062) are within the
|
| 162 |
+
# shared box's noise, and their save-dependent work is the same expansion, so the three take the largest no_field
|
| 163 |
+
# slope. fixed and per_meas were fit on the 1,002-save pack, so its saves are priced twice: 1.6 s of margin.
|
| 164 |
+
response_cold = { fixed = 22.0, per_meas = 0.07, per_save = 0.0016 }
|
| 165 |
+
response_warm = { fixed = 2.5, per_meas = 0.04, per_save = 0.0016 }
|
| 166 |
+
response_no_field = { fixed = 0.5, per_meas = 0.012, per_save = 0.0016 }
|
| 167 |
+
# On a machine every encoding class's rows play their own amplitude, so its shells no longer share the expansion's
|
| 168 |
+
# bodies: a class of the scan's 485 measurements on the 100 ms CACTUS pack at 3 T with every tier took 25 s against
|
| 169 |
+
# 4.5 s for the commanded protocol (a CPU host, 8 threads, the Prisma at 6 cm, its slew), so an entry's rows count
|
| 170 |
+
# once per class times this (Brain.responses).
|
| 171 |
+
response_per_class = 5.6
|
| 172 |
+
[budget.track] # one tracking of the WM at density d, the run's or the truth's (L40S steady x 1.5)
|
| 173 |
+
1 = 1.5 # 36,605 seeds: 0.7 s
|
| 174 |
+
2 = 3.5 # 292,840 seeds: 1.9-2.1 s
|
| 175 |
+
4 = 35.0 # 2,342,720 seeds: 13.6-23.2 s
|
space/config.toml
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# The DiSCo Space: what is pinned. Every number the app shows comes from pipeline.py on this configuration.
|
| 2 |
+
|
| 3 |
+
source = "disco" # space/sources/disco.py: the DiSCo phantom (demo: its layout, full: its columnar pack)
|
| 4 |
+
|
| 5 |
+
[data]
|
| 6 |
+
repo = "SubstrateCommons/disco-replay" # the public replay dataset
|
| 7 |
+
moments = "disco/moments" # the shape-moment layout written by dmipy-sim's write_shape_moments
|
| 8 |
+
revision = "2db4e7839bc21c52c49d2aa7d399dde13be4cca7" # the dataset revision the layout is read at (with the background moments, disco-space#29)
|
| 9 |
+
source_manifest_sha256 = "499e411b7f7412ffa72a8885ee22a7bed9198e992a517b81c273ceeaeafd629e" # the columnar manifest the layout was contracted from (its manifest.json names it)
|
| 10 |
+
|
| 11 |
+
# The timing classes ("shapes") the layout holds: square pulses (slew_rate = inf) at TE = 53.5 ms, PGSE unless
|
| 12 |
+
# kind = "pgste" (a stimulated echo storing for TM = Delta - delta). delta / Delta / TE in seconds, the same numbers the
|
| 13 |
+
# layout's manifest records (checked at load); label is what the app shows.
|
| 14 |
+
[shapes."d10.2-D16.7"]
|
| 15 |
+
label = "DiSCo δ 10.2 / Δ 16.7 ms (shells b = 0, 1000, 1925)"
|
| 16 |
+
delta = 0.0102
|
| 17 |
+
Delta = 0.0167
|
| 18 |
+
TE = 0.0535
|
| 19 |
+
[shapes."d7.6-D45.9"]
|
| 20 |
+
label = "DiSCo δ 7.6 / Δ 45.9 ms (shell b = 3091)"
|
| 21 |
+
delta = 0.0076
|
| 22 |
+
Delta = 0.0459
|
| 23 |
+
TE = 0.0535
|
| 24 |
+
[shapes."d17.7-D35.8"]
|
| 25 |
+
label = "DiSCo δ 17.7 / Δ 35.8 ms (shell b = 13183)"
|
| 26 |
+
delta = 0.0177
|
| 27 |
+
Delta = 0.0358
|
| 28 |
+
TE = 0.0535
|
| 29 |
+
[shapes."d12-D24"]
|
| 30 |
+
label = "clinical δ 12 / Δ 24 ms"
|
| 31 |
+
delta = 0.012
|
| 32 |
+
Delta = 0.024
|
| 33 |
+
TE = 0.0535
|
| 34 |
+
[shapes."d17-D30"]
|
| 35 |
+
label = "research δ 17 / Δ 30 ms"
|
| 36 |
+
delta = 0.017
|
| 37 |
+
Delta = 0.030
|
| 38 |
+
TE = 0.0535
|
| 39 |
+
[shapes."d8-D20"]
|
| 40 |
+
label = "Connectome 2.0 δ 8 / Δ 20 ms"
|
| 41 |
+
delta = 0.008
|
| 42 |
+
Delta = 0.020
|
| 43 |
+
TE = 0.0535
|
| 44 |
+
# The stimulated echo matched to DiSCo's b = 3091 shell: the same diffusion time (Delta = delta + TM = 45.9 ms) with
|
| 45 |
+
# the magnetisation stored along z for TM, so susceptibility dephasing (and T2) act only during the two deltas.
|
| 46 |
+
[shapes."ste-d7.6-TM38.3"]
|
| 47 |
+
label = "stimulated echo δ 7.6 / TM 38.3 ms (Δ 45.9 ms, the PGSTE twin of the b = 3091 class)"
|
| 48 |
+
delta = 0.0076
|
| 49 |
+
Delta = 0.0459
|
| 50 |
+
TE = 0.0535
|
| 51 |
+
kind = "pgste"
|
| 52 |
+
|
| 53 |
+
# DiSCo's own protocol: which timing class each shell of the dataset's gradient table plays (b in s/mm^2, the
|
| 54 |
+
# table's rows are assigned to the nearest b here).
|
| 55 |
+
[disco]
|
| 56 |
+
shells = [
|
| 57 |
+
{ b = 0, shape = "d10.2-D16.7" },
|
| 58 |
+
{ b = 1000, shape = "d10.2-D16.7" },
|
| 59 |
+
{ b = 1925, shape = "d10.2-D16.7" },
|
| 60 |
+
{ b = 3091, shape = "d7.6-D45.9" },
|
| 61 |
+
{ b = 13183, shape = "d17.7-D35.8" },
|
| 62 |
+
]
|
| 63 |
+
|
| 64 |
+
# Presets the app offers besides "DiSCo 364" (which comes from the dataset's table). b in s/mm^2.
|
| 65 |
+
[presets."clinical b1000 x 30"]
|
| 66 |
+
n_b0 = 1
|
| 67 |
+
shells = [{ shape = "d12-D24", b = 1000, n_dirs = 30 }]
|
| 68 |
+
[presets."research 3-shell x 90"]
|
| 69 |
+
n_b0 = 3
|
| 70 |
+
shells = [
|
| 71 |
+
{ shape = "d17-D30", b = 1000, n_dirs = 90 },
|
| 72 |
+
{ shape = "d17-D30", b = 2000, n_dirs = 90 },
|
| 73 |
+
{ shape = "d17-D30", b = 3000, n_dirs = 90 },
|
| 74 |
+
]
|
| 75 |
+
[presets."Connectome 2.0 b6000 x 60"]
|
| 76 |
+
n_b0 = 2
|
| 77 |
+
shells = [{ shape = "d8-D20", b = 6000, n_dirs = 60 }]
|
| 78 |
+
|
| 79 |
+
# The tissue and the scanner: the field presets the page offers (T), the default field,
|
| 80 |
+
# and whether a run starts with the tiers on. Tissue defaults come from dmipy-sim's white-matter catalogue at the
|
| 81 |
+
# nearest cited field (1.5 / 3 / 7 T) and are editable on the page.
|
| 82 |
+
[physics]
|
| 83 |
+
fields = [0.064, 1.5, 3.0, 7.0, 11.7]
|
| 84 |
+
default_field = 3.0
|
| 85 |
+
default_on = true
|
| 86 |
+
pools = ["intra", "extra"] # the pack's seeded pools (its spec also names a myelin pool nobody was seeded in)
|
| 87 |
+
|
| 88 |
+
# The scanner menu after "ideal": catalogue machines of dmipy-sim (ScannerLimits.of(key)), each applied with every term
|
| 89 |
+
# its entry carries (docs/scanner.md); the phantom sits at a distance from isocentre along a scanner axis (the panel's
|
| 90 |
+
# placement, at most 7.9 cm: the whole 1 mm cube inside the Swoop's 8 cm anchor). The Swoop's own gradient needs the
|
| 91 |
+
# layout's background moments (shape_moments.stamp_background); a layout without them refuses it by name.
|
| 92 |
+
[scanners]
|
| 93 |
+
machines = [
|
| 94 |
+
{ label = "Hyperfine Swoop 64 mT (permanent magnet, field across the patient)", key = "hyperfine_swoop_64mT" },
|
| 95 |
+
{ label = "Siemens Prisma 3 T", key = "siemens_magnetom_prisma_3T" },
|
| 96 |
+
{ label = "Siemens Terra 7 T", key = "siemens_magnetom_terra_7T" },
|
| 97 |
+
]
|
| 98 |
+
default_offset_cm = 7.9
|
| 99 |
+
max_offset_cm = 7.9
|
| 100 |
+
delivery_per_meas = 0.0036 # s per measurement per replay: bore.delivered_moments over DiSCo's 31,802 live voxels, 1.3 s at 364 (a CPU host)
|
| 101 |
+
|
| 102 |
+
# The mode: demo = the prebaked shape-moment layout (the hosted Spaces; seconds; the stored pulse
|
| 103 |
+
# timings), full = the columnar replay pack itself (minutes per volume; any timing; the scheme upload), read from
|
| 104 |
+
# DISCO_COLUMNS (a directory with the columns, or the Hub at 45 MB/s). DISCO_MODE in the environment overrides.
|
| 105 |
+
[mode]
|
| 106 |
+
mode = "demo"
|
| 107 |
+
columns = "hf://SubstrateCommons/disco-replay/disco"
|
| 108 |
+
workers = 16
|
| 109 |
+
|
| 110 |
+
# The compute backend: jax (the reference; the Docker Space) or torch (Hugging Face's shared GPU pool, disco-space#2);
|
| 111 |
+
# DISCO_BACKEND in the environment overrides. resident = false rebuilds the layout's device tensors on every call
|
| 112 |
+
# (a pool that drops the device between calls).
|
| 113 |
+
[compute]
|
| 114 |
+
backend = "jax"
|
| 115 |
+
resident = true
|
| 116 |
+
|
| 117 |
+
[tracking]
|
| 118 |
+
density = 4 # seeds per region voxel = density^3 (4 -> 659,840 seeds, the DiSCo score's setting)
|
| 119 |
+
step_mm = 0.5
|
| 120 |
+
max_angle = 30.0
|
| 121 |
+
max_steps = 500
|
| 122 |
+
|
| 123 |
+
# The acceptance gate (tests/test_acceptance.py) on the DiSCo 364 protocol, noiseless.
|
| 124 |
+
[gate]
|
| 125 |
+
pearson_count_min = 0.90
|
| 126 |
+
missed_pairs_max = 0
|
| 127 |
+
reference_max_abs_diff = 1e-3 # the replay of DiSCo 364 against disco/reference/disco_replay_bare.nii.gz
|
| 128 |
+
|
| 129 |
+
# The reconstruction: DiSCo is single-fibre white matter, so its CSD is the single-tissue Tournier 2007 one on the
|
| 130 |
+
# response white_matter_response_tournier07 estimates from the volume. DISCO_RECONSTRUCTION in the environment overrides.
|
| 131 |
+
[reconstruction]
|
| 132 |
+
method = "tournier07"
|
space/limits.py
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""The container's CPU quota, read from its cgroup, and the BLAS thread cap derived from it.
|
| 2 |
+
|
| 3 |
+
A Space's container sees the host's CPUs (192 on the ZeroGPU pool) while its cgroup grants a few; numpy's BLAS and
|
| 4 |
+
OpenMP pools size themselves on the visible count unless told otherwise, and XLA's CPU pool (jax, the pose expansion's
|
| 5 |
+
field factor) on the CPUs the process may run on, which no variable changes: measured 247 threads at 72 CPUs, 73 at
|
| 6 |
+
16, 25 at 4. A heavy contraction then runs on far more threads than it has cores, throttled by the quota: the pool's
|
| 7 |
+
first two-window warm entry spent 1217 s of 1292 s in that one jax phase against 24 s on an 8-thread box. This module
|
| 8 |
+
has no numpy import, so the entry can call it first."""
|
| 9 |
+
import math
|
| 10 |
+
import os
|
| 11 |
+
|
| 12 |
+
THREAD_VARS = ("OMP_NUM_THREADS", "OPENBLAS_NUM_THREADS", "MKL_NUM_THREADS")
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def cpu_quota_from(text):
|
| 16 |
+
"""The CPUs a cgroup v2 ``cpu.max`` line grants: ``'<quota> <period>'`` -> ``ceil(quota / period)`` (at least 1),
|
| 17 |
+
``'max <period>'`` -> None (no quota)."""
|
| 18 |
+
quota, period = text.split()[:2]
|
| 19 |
+
if quota == "max":
|
| 20 |
+
return None
|
| 21 |
+
return max(1, math.ceil(int(quota) / int(period)))
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def cpu_quota():
|
| 25 |
+
"""The CPUs this container's cgroup grants (v2 ``cpu.max``, else v1 ``cpu.cfs_quota_us`` / ``cpu.cfs_period_us``),
|
| 26 |
+
None when unlimited or unknown."""
|
| 27 |
+
try:
|
| 28 |
+
with open("/sys/fs/cgroup/cpu.max") as f:
|
| 29 |
+
return cpu_quota_from(f.read())
|
| 30 |
+
except (OSError, ValueError):
|
| 31 |
+
pass
|
| 32 |
+
try:
|
| 33 |
+
with open("/sys/fs/cgroup/cpu/cpu.cfs_quota_us") as f, open("/sys/fs/cgroup/cpu/cpu.cfs_period_us") as g:
|
| 34 |
+
q, p = int(f.read()), int(g.read())
|
| 35 |
+
return None if q < 0 else cpu_quota_from(f"{q} {p}")
|
| 36 |
+
except (OSError, ValueError):
|
| 37 |
+
return None
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def cap_threads(quota=None):
|
| 41 |
+
"""Sets the BLAS / OpenMP thread variables (:data:`THREAD_VARS`) that are not already set to the cgroup's CPU
|
| 42 |
+
quota (``quota`` overrides the read), before numpy is imported; returns the cap applied, None when there is no
|
| 43 |
+
quota to apply. A variable the environment already sets stays as it is."""
|
| 44 |
+
n = cpu_quota() if quota is None else quota
|
| 45 |
+
if n is None:
|
| 46 |
+
return None
|
| 47 |
+
for var in THREAD_VARS:
|
| 48 |
+
os.environ.setdefault(var, str(n))
|
| 49 |
+
return n
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def cap_affinity(quota=None):
|
| 53 |
+
"""Restricts this process to the first ``quota`` CPUs it may run on (``os.sched_setaffinity``; ``quota`` overrides
|
| 54 |
+
the cgroup read), so that every pool that sizes itself on the schedulable CPUs (XLA's, and torch's) matches the
|
| 55 |
+
quota; returns the CPUs it now runs on, or None when there is no quota or the process already runs on no more
|
| 56 |
+
than it. Children (the warm-up's process, the forked GPU worker) inherit it."""
|
| 57 |
+
n = cpu_quota() if quota is None else quota
|
| 58 |
+
allowed = sorted(os.sched_getaffinity(0))
|
| 59 |
+
if n is None or len(allowed) <= n:
|
| 60 |
+
return None
|
| 61 |
+
cpus = set(allowed[:n])
|
| 62 |
+
os.sched_setaffinity(0, cpus)
|
| 63 |
+
return cpus
|
space/pipeline.py
ADDED
|
@@ -0,0 +1,1171 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""The Spaces' pipeline: an acquisition on a replay source -> the DWI of the source's grid -> noise -> the
|
| 2 |
+
reconstruction -> probabilistic tracking -> the connectome of the source's regions against the source's truth. Plain
|
| 3 |
+
functions with their timings; nothing here draws or reads a widget.
|
| 4 |
+
|
| 5 |
+
The source is what the configuration names (:mod:`space.sources`): DiSCo's replay layout or columnar pack
|
| 6 |
+
(:mod:`space.sources.disco`), or a brain composed from an FOD field, tissue fractions and replay packs
|
| 7 |
+
(:mod:`space.sources.brain`). Everything a page needs from a source -- its texts, presets, tissue panel, regions,
|
| 8 |
+
truth, reconstruction and GPU budget -- is the :class:`Source` interface, so one page serves both. The CSD is
|
| 9 |
+
dmipy-fit's, the tracker dmipy-tract's ``track``, the connectome dmipy-tract's ``connectivity`` over the source's
|
| 10 |
+
label image.
|
| 11 |
+
"""
|
| 12 |
+
from __future__ import annotations
|
| 13 |
+
|
| 14 |
+
import os
|
| 15 |
+
import time
|
| 16 |
+
try:
|
| 17 |
+
import tomllib # 3.11+
|
| 18 |
+
except ModuleNotFoundError: # the ZeroGPU image is Python 3.10
|
| 19 |
+
import tomli as tomllib
|
| 20 |
+
from dataclasses import dataclass, field, replace
|
| 21 |
+
from typing import Optional
|
| 22 |
+
|
| 23 |
+
import numpy as np
|
| 24 |
+
|
| 25 |
+
HERE = os.path.dirname(os.path.abspath(__file__))
|
| 26 |
+
ROOT = os.path.dirname(HERE)
|
| 27 |
+
DEFAULT_CONFIG = os.path.join(HERE, "config.toml")
|
| 28 |
+
DATA_DIR = os.path.join(ROOT, "data")
|
| 29 |
+
SH_ORDER = 8
|
| 30 |
+
B0_MAX = 50.0 # s/mm^2: a row below it is a b = 0 measurement, everywhere in the pipeline
|
| 31 |
+
BAND_TOL = 0.005 # the band tolerance (x the pack's floor) of the layout and of a full replay
|
| 32 |
+
BACKENDS = ("jax", "torch")
|
| 33 |
+
MODES = ("demo", "full")
|
| 34 |
+
RECONSTRUCTIONS = ("msmt", "tournier07")
|
| 35 |
+
NO_KNOB = "none: run A only" # the knob that makes no B
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def config_path():
|
| 39 |
+
"""The configuration this process serves: ``DISCO_CONFIG`` in the environment (a path, or a name in
|
| 40 |
+
``space/`` such as ``brain.toml``), else ``space/config.toml`` (the DiSCo Space)."""
|
| 41 |
+
p = os.environ.get("DISCO_CONFIG") or DEFAULT_CONFIG
|
| 42 |
+
return p if os.path.isabs(p) or os.path.exists(p) else os.path.join(HERE, p)
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def config(path=None):
|
| 46 |
+
"""The configuration at ``path``, else at :func:`config_path`."""
|
| 47 |
+
with open(path or config_path(), "rb") as f:
|
| 48 |
+
return tomllib.load(f)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def reconstruction(cfg):
|
| 52 |
+
"""The reconstruction a run fits: ``msmt`` (three-tissue responses estimated from the data and multi-shell
|
| 53 |
+
multi-tissue CSD) or ``tournier07`` (the single-fibre response and single-tissue CSD): ``DISCO_RECONSTRUCTION``
|
| 54 |
+
in the environment, else ``[reconstruction] method``."""
|
| 55 |
+
r = os.environ.get("DISCO_RECONSTRUCTION") or cfg["reconstruction"]["method"]
|
| 56 |
+
if r not in RECONSTRUCTIONS:
|
| 57 |
+
raise ValueError(f"reconstruction must be one of {RECONSTRUCTIONS}, got {r!r}")
|
| 58 |
+
return r
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def mode(cfg):
|
| 62 |
+
"""``demo``: the shape-moment layout (seconds; the stored pulse timings). ``full``: the columnar replay pack
|
| 63 |
+
(minutes per volume; any timing). ``DISCO_MODE`` in the environment, else ``[mode] mode``."""
|
| 64 |
+
m = os.environ.get("DISCO_MODE") or cfg["mode"]["mode"]
|
| 65 |
+
if m not in MODES:
|
| 66 |
+
raise ValueError(f"mode must be one of {MODES}, got {m!r}")
|
| 67 |
+
return m
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def columns_uri(cfg):
|
| 71 |
+
"""Where full mode reads the columnar pack: ``DISCO_COLUMNS`` (a directory, or ``hf://owner/name/prefix``), else
|
| 72 |
+
``[mode] columns``."""
|
| 73 |
+
return os.environ.get("DISCO_COLUMNS") or cfg["mode"]["columns"]
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def resident(cfg):
|
| 77 |
+
"""Whether the layout's device tensors stay across calls: ``DISCO_RESIDENT`` (``0``/``false`` for a pool that
|
| 78 |
+
drops the device between calls) else ``[compute] resident``."""
|
| 79 |
+
env = os.environ.get("DISCO_RESIDENT")
|
| 80 |
+
if env is not None:
|
| 81 |
+
return env.strip().lower() not in ("0", "false", "no")
|
| 82 |
+
return bool(cfg["compute"]["resident"])
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def backend(cfg):
|
| 86 |
+
"""The compute backend, ``jax`` or ``torch`` (a host that runs PyTorch only: the layout image, the CSD solver
|
| 87 |
+
and the tracker switch together): ``DISCO_BACKEND`` in the environment, else ``[compute] backend``."""
|
| 88 |
+
b = os.environ.get("DISCO_BACKEND") or cfg["compute"]["backend"]
|
| 89 |
+
if b not in BACKENDS:
|
| 90 |
+
raise ValueError(f"backend must be one of {BACKENDS}, got {b!r}")
|
| 91 |
+
return b
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
# ---- the acquisition -------------------------------------------------------------------------------------------
|
| 95 |
+
|
| 96 |
+
@dataclass(frozen=True)
|
| 97 |
+
class Shell:
|
| 98 |
+
"""One shell: the timing class it plays, its b-value (s/mm^2) and its direction count. A shell made by
|
| 99 |
+
:meth:`free` carries its own pulse timing (``delta``, ``Delta``, ``TE`` in seconds) instead of a stored class,
|
| 100 |
+
and ``shape`` names it."""
|
| 101 |
+
shape: str
|
| 102 |
+
b: float
|
| 103 |
+
n_dirs: int
|
| 104 |
+
delta: Optional[float] = None
|
| 105 |
+
Delta: Optional[float] = None
|
| 106 |
+
TE: Optional[float] = None
|
| 107 |
+
|
| 108 |
+
@classmethod
|
| 109 |
+
def free(cls, b, n_dirs, delta, Delta, TE):
|
| 110 |
+
"""A shell at its own square-pulse timing (seconds), named ``d<delta>-D<Delta>-TE<TE>`` in ms."""
|
| 111 |
+
if not (0 < delta < Delta < TE):
|
| 112 |
+
raise ValueError(f"a free pulse timing needs 0 < delta < Delta < TE, got {delta}, {Delta}, {TE}")
|
| 113 |
+
return cls(f"d{delta * 1e3:g}-D{Delta * 1e3:g}-TE{TE * 1e3:g}", float(b), int(n_dirs), float(delta), float(Delta), float(TE))
|
| 114 |
+
|
| 115 |
+
@property
|
| 116 |
+
def free_timing(self):
|
| 117 |
+
return self.delta is not None
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
@dataclass(frozen=True)
|
| 121 |
+
class Protocol:
|
| 122 |
+
"""The measurements of one acquisition: ``n_b0`` b = 0 rows on the first shell's timing, then every shell's
|
| 123 |
+
directions (a Fibonacci hemisphere of ``n_dirs`` unless ``directions`` gives each row's own; ``bvals`` likewise
|
| 124 |
+
gives each row's own b-value in place of the shells')."""
|
| 125 |
+
shells: tuple
|
| 126 |
+
n_b0: int = 1
|
| 127 |
+
directions: Optional[np.ndarray] = None
|
| 128 |
+
bvals: Optional[np.ndarray] = None
|
| 129 |
+
name: str = "custom"
|
| 130 |
+
|
| 131 |
+
def __post_init__(self):
|
| 132 |
+
if not self.shells:
|
| 133 |
+
raise ValueError("a protocol has at least one shell")
|
| 134 |
+
if self.n_b0 < 1:
|
| 135 |
+
raise ValueError("a protocol has at least one b = 0 measurement (the DWI is normalised by it)")
|
| 136 |
+
for s in self.shells:
|
| 137 |
+
if s.b <= 0 or s.n_dirs < 1:
|
| 138 |
+
raise ValueError(f"a shell has b > 0 and at least one direction, got {s}")
|
| 139 |
+
if self.directions is not None and self.directions.shape != (self.n_meas, 3):
|
| 140 |
+
raise ValueError(f"directions must be ({self.n_meas}, 3), got {self.directions.shape}")
|
| 141 |
+
if self.bvals is not None and self.bvals.shape != (self.n_meas,):
|
| 142 |
+
raise ValueError(f"bvals must be ({self.n_meas},), got {self.bvals.shape}")
|
| 143 |
+
|
| 144 |
+
@property
|
| 145 |
+
def n_meas(self):
|
| 146 |
+
return self.n_b0 + sum(s.n_dirs for s in self.shells)
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
@dataclass(frozen=True)
|
| 150 |
+
class Measurements:
|
| 151 |
+
"""Per row: b (s/mm^2), unit direction, timing-class name, delta / Delta / TE (s)."""
|
| 152 |
+
bvals: np.ndarray
|
| 153 |
+
dirs: np.ndarray
|
| 154 |
+
shape: np.ndarray
|
| 155 |
+
delta: np.ndarray
|
| 156 |
+
Delta: np.ndarray
|
| 157 |
+
TE: np.ndarray
|
| 158 |
+
|
| 159 |
+
@property
|
| 160 |
+
def b0(self):
|
| 161 |
+
return self.bvals < B0_MAX
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
def measurements(protocol, shapes):
|
| 165 |
+
"""The rows of ``protocol`` with the timings of ``shapes`` (the config's ``[shapes]`` table) or the shells' own."""
|
| 166 |
+
timing = {}
|
| 167 |
+
for s in protocol.shells:
|
| 168 |
+
if s.free_timing:
|
| 169 |
+
timing[s.shape] = dict(delta=s.delta, Delta=s.Delta, TE=s.TE)
|
| 170 |
+
elif s.shape not in shapes:
|
| 171 |
+
raise KeyError(f"no timing class {s.shape!r}; the layout holds {sorted(shapes)}")
|
| 172 |
+
else:
|
| 173 |
+
timing[s.shape] = shapes[s.shape]
|
| 174 |
+
names = [protocol.shells[0].shape] * protocol.n_b0
|
| 175 |
+
for s in protocol.shells:
|
| 176 |
+
names += [s.shape] * s.n_dirs
|
| 177 |
+
if protocol.directions is None:
|
| 178 |
+
from dmipy_tract import hemisphere
|
| 179 |
+
dirs = np.concatenate([np.tile([0.0, 0.0, 1.0], (protocol.n_b0, 1))] + [hemisphere(s.n_dirs) for s in protocol.shells])
|
| 180 |
+
else:
|
| 181 |
+
dirs = np.asarray(protocol.directions, np.float64)
|
| 182 |
+
if protocol.bvals is None:
|
| 183 |
+
b = np.asarray([0.0] * protocol.n_b0 + [s.b for s in protocol.shells for _ in range(s.n_dirs)], np.float64)
|
| 184 |
+
else:
|
| 185 |
+
b = np.asarray(protocol.bvals, np.float64)
|
| 186 |
+
delta = np.array([timing[n]["delta"] for n in names]); Delta = np.array([timing[n]["Delta"] for n in names])
|
| 187 |
+
TE = np.array([timing[n]["TE"] for n in names])
|
| 188 |
+
return Measurements(b, dirs, np.asarray(names), delta, Delta, TE)
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
def protocol_from_rows(bvals, dirs, group, make_shell, *, name):
|
| 192 |
+
"""A Protocol from a table of rows (``bvals`` in s/mm^2, ``dirs`` (N, 3) in any norm, ``group`` an integer per
|
| 193 |
+
row saying which shell it belongs to) and ``make_shell(group, rows) -> Shell``: the b = 0 rows first (their
|
| 194 |
+
direction set to z), then every group's rows in ascending group order, each row's own b-value and unit
|
| 195 |
+
direction. Returns the protocol and ``idx``, the table rows in the protocol's order."""
|
| 196 |
+
bvals = np.asarray(bvals, np.float64).ravel(); dirs = np.asarray(dirs, np.float64); group = np.asarray(group)
|
| 197 |
+
if dirs.ndim != 2 or dirs.shape != (len(bvals), 3):
|
| 198 |
+
raise ValueError(f"dirs must be ({len(bvals)}, 3), got {dirs.shape}")
|
| 199 |
+
if np.any(bvals < 0) or not np.all(np.isfinite(bvals)) or not np.all(np.isfinite(dirs)):
|
| 200 |
+
raise ValueError("the table has a negative or non-finite entry")
|
| 201 |
+
b0 = bvals < B0_MAX
|
| 202 |
+
if not b0.any():
|
| 203 |
+
raise ValueError("the table needs a b = 0 row (the DWI is normalised by it)")
|
| 204 |
+
norm = np.linalg.norm(dirs, axis=1)
|
| 205 |
+
if np.any(norm[~b0] == 0):
|
| 206 |
+
raise ValueError("a b > 0 row has a zero direction")
|
| 207 |
+
dirs = np.where(b0[:, None], np.array([0.0, 0.0, 1.0]), dirs / np.where(norm > 0, norm, 1.0)[:, None])
|
| 208 |
+
idx = [np.flatnonzero(b0)]; shells = []
|
| 209 |
+
for g in np.unique(group[~b0]):
|
| 210 |
+
rows = np.flatnonzero((group == g) & ~b0)
|
| 211 |
+
idx.append(rows); shells.append(make_shell(g, rows))
|
| 212 |
+
idx = np.concatenate(idx)
|
| 213 |
+
return Protocol(tuple(shells), n_b0=int(b0.sum()), directions=dirs[idx], bvals=bvals[idx], name=name), idx
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
def protocol_from_scheme(path, *, name="uploaded scheme"):
|
| 217 |
+
"""A Camino ``STEJSKALTANNER`` scheme file (``gx gy gz |G| Delta delta TE`` per row, SI units) as a Protocol
|
| 218 |
+
with every row's own b-value, direction and pulse timing, for full mode: one free shell per distinct
|
| 219 |
+
(b, delta, Delta, TE) in that order, the b = 0 rows first. Read by :func:`dmipy_sim.io.mcdc.read_scheme`, the
|
| 220 |
+
one reader of that format."""
|
| 221 |
+
from dmipy_sim.io.mcdc import read_scheme
|
| 222 |
+
enc = read_scheme(path).encoding
|
| 223 |
+
b = np.asarray(enc.bvalues, np.float64) / 1e6
|
| 224 |
+
delta = np.asarray(enc.delta, np.float64); Delta = np.asarray(enc.Delta, np.float64); TE = np.asarray(enc.TE, np.float64)
|
| 225 |
+
keys = np.stack([np.round(b), np.round(delta * 1e6), np.round(Delta * 1e6), np.round(TE * 1e6)], 1)
|
| 226 |
+
_, group = np.unique(keys, axis=0, return_inverse=True)
|
| 227 |
+
def make_shell(g, rows):
|
| 228 |
+
r = rows[0]
|
| 229 |
+
return Shell.free(keys[r, 0], len(rows), delta[r], Delta[r], TE[r])
|
| 230 |
+
return protocol_from_rows(b, np.asarray(enc.gradient_directions, np.float64), group.ravel(), make_shell, name=name)[0]
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
def preset_protocol(cfg, name):
|
| 234 |
+
"""A ``[presets]`` entry of the config as a Protocol."""
|
| 235 |
+
p = cfg["presets"][name]
|
| 236 |
+
return Protocol(tuple(Shell(s["shape"], float(s["b"]), int(s["n_dirs"])) for s in p["shells"]), n_b0=int(p["n_b0"]), name=name)
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
def retime(protocol, shape):
|
| 240 |
+
"""``protocol`` with every shell on the timing class ``shape`` (b-values, directions and counts kept): the A/B
|
| 241 |
+
knob that swaps a PGSE class for its stimulated-echo twin, or one δ / Δ for another."""
|
| 242 |
+
return Protocol(tuple(Shell(shape, s.b, s.n_dirs) for s in protocol.shells), n_b0=protocol.n_b0,
|
| 243 |
+
directions=protocol.directions, bvals=protocol.bvals, name=f"{protocol.name} on {shape}")
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
def write_volumes(res, out_dir, *, prefix, affine):
|
| 247 |
+
"""The result's DWI as NIfTI (float32 on ``affine``, NaN as 0) with its bvals (s/mm^2) and bvecs (3 x N), and
|
| 248 |
+
the FOD SH field as NIfTI (tournier07 basis, order 8); returns the four paths."""
|
| 249 |
+
import nibabel as nib
|
| 250 |
+
os.makedirs(out_dir, exist_ok=True)
|
| 251 |
+
paths = {}
|
| 252 |
+
dwi = os.path.join(out_dir, f"{prefix}_dwi.nii.gz")
|
| 253 |
+
nib.save(nib.Nifti1Image(np.nan_to_num(res.dwi).astype(np.float32), np.asarray(affine, np.float64)), dwi); paths["dwi"] = dwi
|
| 254 |
+
bvals = os.path.join(out_dir, f"{prefix}.bvals"); np.savetxt(bvals, res.meas.bvals[None, :], fmt="%.1f"); paths["bvals"] = bvals
|
| 255 |
+
bvecs = os.path.join(out_dir, f"{prefix}.bvecs"); np.savetxt(bvecs, res.meas.dirs.T, fmt="%.8f"); paths["bvecs"] = bvecs
|
| 256 |
+
fod = os.path.join(out_dir, f"{prefix}_fod_sh.nii.gz")
|
| 257 |
+
nib.save(nib.Nifti1Image(np.nan_to_num(res.sh).astype(np.float32), np.asarray(affine, np.float64)), fod); paths["fod"] = fod
|
| 258 |
+
return paths
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
# ---- the physics: tissue and scanner --------------------------------------------------------------------------------
|
| 262 |
+
CATALOGUE_FIELDS = (1.5, 3.0, 7.0) # where dmipy-sim's white-matter catalogue has cited relaxation
|
| 263 |
+
CATALOGUE_POOLS = ("intra", "extra", "myelin") # the pools the catalogue has T2 and T1 for
|
| 264 |
+
B0_ALONG_Z = (0.0, 0.0, 1.0)
|
| 265 |
+
B0_TRANSVERSE = (1.0, 0.0, 0.0)
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
def catalogue(field_T, pools=CATALOGUE_POOLS):
|
| 269 |
+
"""dmipy-sim's canonical white matter at the catalogue field nearest ``field_T`` (in log distance): ``T2`` and
|
| 270 |
+
``T1`` per pool of ``pools`` (s), ``rho2`` (m/s), the sheath's ``chi_iso`` and ``chi_aniso`` (SI), and
|
| 271 |
+
``catalogue_field``, the field the numbers were cited at (the page says so when it is not the chosen one)."""
|
| 272 |
+
import warnings
|
| 273 |
+
from dmipy_sim.substrate.biophysical_constants import canonical_white_matter
|
| 274 |
+
if not float(field_T) > 0:
|
| 275 |
+
raise ValueError(f"the field is in tesla, got {field_T}")
|
| 276 |
+
near = min(CATALOGUE_FIELDS, key=lambda f: abs(np.log(f / float(field_T))))
|
| 277 |
+
with warnings.catch_warnings():
|
| 278 |
+
warnings.simplefilter("ignore")
|
| 279 |
+
w = canonical_white_matter(field_T=near)
|
| 280 |
+
unknown = [q for q in pools if q not in CATALOGUE_POOLS]
|
| 281 |
+
if unknown:
|
| 282 |
+
raise ValueError(f"the catalogue has no relaxation for the pools {unknown}; it knows {CATALOGUE_POOLS}")
|
| 283 |
+
return dict(catalogue_field=near, T2={q: float(w[f"T2_{q}"]) for q in pools}, T1={q: float(w[f"T1_{q}"]) for q in pools},
|
| 284 |
+
rho2=float(w["rho2"]), chi_iso=float(w["chi_iso_myelin"]), chi_aniso=float(w["delta_chi_a"]))
|
| 285 |
+
|
| 286 |
+
|
| 287 |
+
def b0_direction(theta_deg, phi_deg):
|
| 288 |
+
"""The unit field direction at polar angle ``theta`` from z and azimuth ``phi`` from x (degrees)."""
|
| 289 |
+
t, f = np.radians(float(theta_deg)), np.radians(float(phi_deg))
|
| 290 |
+
return (float(np.sin(t) * np.cos(f)), float(np.sin(t) * np.sin(f)), float(np.cos(t)))
|
| 291 |
+
|
| 292 |
+
|
| 293 |
+
@dataclass(frozen=True)
|
| 294 |
+
class Physics:
|
| 295 |
+
"""The tissue and the scanner a replay is evaluated at: the field (T) and its direction in the substrate frame,
|
| 296 |
+
T2 and T1 per seeded pool (s), the walls' surface relaxivity ``rho2`` (m/s), the sheath's ``chi_iso`` and
|
| 297 |
+
``chi_aniso`` (SI, the field source); ``relaxation`` / ``contact`` / ``field`` switch the three tiers, so a tier
|
| 298 |
+
is a knob the page can turn off one at a time. :meth:`tissue` is the :class:`dmipy_sim.spec.tissue.Tissue` for
|
| 299 |
+
the replay (None when every tier is off: bare diffusion). ``scanner`` is the machine (a catalogue key; None: the
|
| 300 |
+
ideal scanner), whose field the physics is at, and ``offset_m`` where the phantom's centre sits from isocentre
|
| 301 |
+
(metres, the scanner's frame): together they say what gradient every voxel is delivered (docs/scanner.md)."""
|
| 302 |
+
field_T: float
|
| 303 |
+
T2: dict
|
| 304 |
+
T1: dict
|
| 305 |
+
rho2: float
|
| 306 |
+
chi_iso: float
|
| 307 |
+
chi_aniso: float
|
| 308 |
+
b0_direction: tuple = B0_ALONG_Z
|
| 309 |
+
relaxation: bool = True
|
| 310 |
+
contact: bool = True
|
| 311 |
+
field: bool = True
|
| 312 |
+
scanner: Optional[str] = None
|
| 313 |
+
offset_m: tuple = (0.0, 0.0, 0.0)
|
| 314 |
+
|
| 315 |
+
def __post_init__(self):
|
| 316 |
+
if self.scanner is not None:
|
| 317 |
+
L = limits(self.scanner)
|
| 318 |
+
if abs(float(L.field_T) - float(self.field_T)) > 1e-9:
|
| 319 |
+
raise ValueError(f"{self.scanner} is a {L.field_T:g} T magnet; the physics says {self.field_T:g} T")
|
| 320 |
+
if np.shape(self.offset_m) != (3,):
|
| 321 |
+
raise ValueError("offset_m is the phantom centre's displacement from isocentre, three lengths in metres")
|
| 322 |
+
if not (0 < self.field_T < 30):
|
| 323 |
+
raise ValueError(f"the field is in tesla, got {self.field_T}")
|
| 324 |
+
if not self.T2 or set(self.T1) != set(self.T2):
|
| 325 |
+
raise ValueError(f"T2 and T1 are seconds over the same pools, got {self.T2} and {self.T1}")
|
| 326 |
+
for what, m in (("T2", self.T2), ("T1", self.T1)):
|
| 327 |
+
if any(not (0 < float(v) < 100) for v in m.values()):
|
| 328 |
+
raise ValueError(f"{what} is seconds per pool, got {m}")
|
| 329 |
+
if self.rho2 < 0:
|
| 330 |
+
raise ValueError("the surface relaxivity is non-negative")
|
| 331 |
+
u = np.asarray(self.b0_direction, np.float64)
|
| 332 |
+
if u.shape != (3,) or not np.isclose(np.linalg.norm(u), 1.0, atol=1e-6):
|
| 333 |
+
raise ValueError("b0_direction is a unit vector")
|
| 334 |
+
|
| 335 |
+
@classmethod
|
| 336 |
+
def at(cls, field_T, *, pools=("intra", "extra"), b0_direction=B0_ALONG_Z, **overrides):
|
| 337 |
+
"""The catalogue's white matter at ``field_T`` over ``pools`` with ``overrides`` (any field of the class)."""
|
| 338 |
+
c = catalogue(field_T, pools); c.pop("catalogue_field")
|
| 339 |
+
return cls(field_T=float(field_T), b0_direction=tuple(float(x) for x in b0_direction), **{**c, **overrides})
|
| 340 |
+
|
| 341 |
+
@property
|
| 342 |
+
def bare(self):
|
| 343 |
+
return not (self.relaxation or self.contact or self.field)
|
| 344 |
+
|
| 345 |
+
@property
|
| 346 |
+
def along_z(self):
|
| 347 |
+
return bool(np.allclose(self.b0_direction, B0_ALONG_Z))
|
| 348 |
+
|
| 349 |
+
@property
|
| 350 |
+
def pools(self):
|
| 351 |
+
return tuple(self.T2)
|
| 352 |
+
|
| 353 |
+
def tissue(self, unseeded=()):
|
| 354 |
+
"""The Tissue for the replay; ``unseeded`` names the substrate's pools no walker was seeded in, which the
|
| 355 |
+
library's mapping still wants a value for: they take the first seeded pool's (nothing reads it)."""
|
| 356 |
+
from dmipy_sim.spec.tissue import Tissue
|
| 357 |
+
if self.bare:
|
| 358 |
+
return None
|
| 359 |
+
first = self.pools[0]
|
| 360 |
+
T2 = {**self.T2, **{q: self.T2[first] for q in unseeded}}; T1 = {**self.T1, **{q: self.T1[first] for q in unseeded}}
|
| 361 |
+
return Tissue(T2=T2 if self.relaxation else None, T1=T1 if self.relaxation else None,
|
| 362 |
+
rho2=self.rho2 if self.contact else None, chi_iso=self.chi_iso if self.field else None,
|
| 363 |
+
chi_aniso=self.chi_aniso if self.field else 0.0)
|
| 364 |
+
|
| 365 |
+
def label(self):
|
| 366 |
+
where = "" if self.scanner is None else f" on the {self.scanner} at ({', '.join(f'{x * 100:.1f}' for x in self.offset_m)}) cm"
|
| 367 |
+
if self.bare:
|
| 368 |
+
return "bare diffusion" + where
|
| 369 |
+
tiers = [n for n, on in (("relaxation", self.relaxation), ("contact", self.contact), ("field", self.field)) if on]
|
| 370 |
+
u = self.b0_direction
|
| 371 |
+
return f"{self.field_T:g} T along ({u[0]:.2f}, {u[1]:.2f}, {u[2]:.2f}), tiers {'+'.join(tiers)}" + where
|
| 372 |
+
|
| 373 |
+
|
| 374 |
+
def tissue_and_scanner(physics, unseeded=()):
|
| 375 |
+
"""``(tissue, scanner)`` for a replay at ``physics``: ``(None, None)`` for bare diffusion; the scanner's field
|
| 376 |
+
goes with the field tier only (relaxation at a field is already in the tissue's T2 and T1)."""
|
| 377 |
+
tissue = physics.tissue(unseeded) if physics else None
|
| 378 |
+
return tissue, (physics.field_T if tissue is not None and physics.field else None)
|
| 379 |
+
|
| 380 |
+
|
| 381 |
+
# ---- the sources: what replays, what is tracked, what is scored ------------------------------------------------------
|
| 382 |
+
|
| 383 |
+
@dataclass(frozen=True)
|
| 384 |
+
class Control:
|
| 385 |
+
"""One widget of a source's tissue-and-scanner panel: ``kind`` is an input (``checkbox``, ``number``, ``slider``,
|
| 386 |
+
``dropdown``) or a piece of the panel's machinery (``field_preset``: the field presets that fill the catalogue's
|
| 387 |
+
numbers, ``catalogue_note`` and ``reset``: the note saying where the numbers came from and the button that
|
| 388 |
+
restores them, ``markdown``: text). ``value`` is the default; ``interactive`` False shows it fixed."""
|
| 389 |
+
name: str
|
| 390 |
+
kind: str
|
| 391 |
+
label: str = ""
|
| 392 |
+
value: object = None
|
| 393 |
+
choices: tuple = ()
|
| 394 |
+
minimum: Optional[float] = None
|
| 395 |
+
maximum: Optional[float] = None
|
| 396 |
+
step: Optional[float] = None
|
| 397 |
+
visible: bool = True
|
| 398 |
+
interactive: bool = True
|
| 399 |
+
|
| 400 |
+
|
| 401 |
+
@dataclass(frozen=True)
|
| 402 |
+
class Panel:
|
| 403 |
+
"""A source's tissue-and-scanner panel: ``rows`` of :class:`Control` in the order drawn, ``fields`` the inputs'
|
| 404 |
+
names in the order the run signature carries them, ``catalogue`` the names the catalogue fills in (in the order
|
| 405 |
+
:meth:`Source.catalogue_numbers` returns them, a note last), ``field_presets`` the fields (T) offered."""
|
| 406 |
+
rows: tuple
|
| 407 |
+
fields: tuple
|
| 408 |
+
catalogue: tuple
|
| 409 |
+
field_presets: tuple
|
| 410 |
+
|
| 411 |
+
def controls(self):
|
| 412 |
+
return {c.name: c for row in self.rows for c in row}
|
| 413 |
+
|
| 414 |
+
|
| 415 |
+
@dataclass(frozen=True)
|
| 416 |
+
class Regions:
|
| 417 |
+
"""The regions a connectome is counted between: ``labels`` an integer image (0 = no region, 1..n the regions),
|
| 418 |
+
``affine`` its voxel-to-tracking-frame map in millimetres, ``names`` one per region, ``groups`` the coarser view
|
| 419 |
+
as ``((name, (label, ...)), ...)`` (empty when the source has none)."""
|
| 420 |
+
labels: np.ndarray
|
| 421 |
+
affine: np.ndarray
|
| 422 |
+
names: tuple
|
| 423 |
+
groups: tuple = ()
|
| 424 |
+
|
| 425 |
+
@property
|
| 426 |
+
def n(self):
|
| 427 |
+
return len(self.names)
|
| 428 |
+
|
| 429 |
+
@property
|
| 430 |
+
def pairs(self):
|
| 431 |
+
"""The region pairs, the upper triangle without the diagonal."""
|
| 432 |
+
return np.triu_indices(self.n, 1)
|
| 433 |
+
|
| 434 |
+
def matrix(self, tg):
|
| 435 |
+
"""The symmetrised ``n x n`` streamline-count matrix of ``tg`` between the regions (no self-connections):
|
| 436 |
+
dmipy-tract's ``connectivity`` over the label image, row 0 (no region) dropped."""
|
| 437 |
+
from dmipy_tract import connectivity
|
| 438 |
+
counts, _ = connectivity(tg, self.labels, self.affine)
|
| 439 |
+
M = np.zeros((self.n + 1, self.n + 1))
|
| 440 |
+
k = min(counts.shape[0], self.n + 1)
|
| 441 |
+
M[:k, :k] = counts[:k, :k]
|
| 442 |
+
M = M[1:, 1:]
|
| 443 |
+
M = M + M.T
|
| 444 |
+
np.fill_diagonal(M, 0)
|
| 445 |
+
return M
|
| 446 |
+
|
| 447 |
+
def grouped(self, M):
|
| 448 |
+
"""``M`` summed over the groups: ``(G, G)``, the off-diagonal entries the counts between two groups, the
|
| 449 |
+
diagonal the count within a group (each pair once)."""
|
| 450 |
+
A = np.zeros((self.n, len(self.groups)))
|
| 451 |
+
for g, (_, ids) in enumerate(self.groups):
|
| 452 |
+
A[np.asarray(ids, int) - 1, g] = 1.0
|
| 453 |
+
G = A.T @ np.asarray(M, np.float64) @ A
|
| 454 |
+
G[np.diag_indices_from(G)] /= 2.0
|
| 455 |
+
return G
|
| 456 |
+
|
| 457 |
+
|
| 458 |
+
class Source:
|
| 459 |
+
"""A replay source: what the page shows and asks for (class-level, from the configuration alone, so the page is
|
| 460 |
+
built before any data loads) and what a run does with the data (the instance).
|
| 461 |
+
|
| 462 |
+
The page's side: :meth:`describe` (the title and every text that names the source), :meth:`presets` and
|
| 463 |
+
:meth:`protocol` (the acquisitions offered), :meth:`panel` (the tissue-and-scanner inputs),
|
| 464 |
+
:meth:`catalogue_numbers`, :meth:`physics_from`, :meth:`knobs` and :meth:`apply_knob` (B, one knob away from A),
|
| 465 |
+
:meth:`refused_machines` (the catalogued machines kept off the scanner menu, and why),
|
| 466 |
+
:meth:`tracking_controls` and :meth:`estimated_seconds` (the GPU seconds a run reserves on a shared pool).
|
| 467 |
+
|
| 468 |
+
The run's side: :attr:`regions` and :attr:`affine`, :meth:`validate`, :meth:`prepare` (the share of a replay
|
| 469 |
+
that needs no device, kept per process: :meth:`response_key`, :meth:`cached`, :meth:`keep`,
|
| 470 |
+
:meth:`responses`), :meth:`replay`, :meth:`reconstruct`, :meth:`tracking_inputs`,
|
| 471 |
+
:meth:`reference` and :meth:`score` (the truth the connectome is scored against), :meth:`compare` (A against
|
| 472 |
+
B), :meth:`ladder`, :meth:`ingredients`, :meth:`accuracy`."""
|
| 473 |
+
mode = ""
|
| 474 |
+
STAGES = ("replay", "noise", "csd", "track", "score")
|
| 475 |
+
TIERS = () # the physics tiers a ladder switches on one at a time
|
| 476 |
+
unseeded = () # the substrate's pools no walker was seeded in
|
| 477 |
+
|
| 478 |
+
def __init__(self, cfg):
|
| 479 |
+
self.cfg = cfg
|
| 480 |
+
self.shapes = cfg["shapes"]
|
| 481 |
+
self.backend = backend(cfg)
|
| 482 |
+
|
| 483 |
+
# ---- the page's side: from the configuration alone ----
|
| 484 |
+
|
| 485 |
+
@classmethod
|
| 486 |
+
def refused_machines(cls, cfg):
|
| 487 |
+
"""``{label: reason}``: the catalogued machines this source keeps off its scanner menu, each with the reason the
|
| 488 |
+
page shows under the menu. None here."""
|
| 489 |
+
return {}
|
| 490 |
+
|
| 491 |
+
@classmethod
|
| 492 |
+
def describe(cls, cfg):
|
| 493 |
+
"""The texts that name the source: ``title``, ``heading`` (the page's first paragraph), ``acquisition``
|
| 494 |
+
(under the shell rows), ``tissue`` (under the panel), ``explorer`` (the explorer's paragraph), ``results_tab``,
|
| 495 |
+
``truth_tab`` (the tab of the input and its truth), ``stages`` (the progress text per stage), ``fixed`` (what a
|
| 496 |
+
visitor cannot change, one line each), ``accuracy`` (the accuracy accordion's paragraph), ``ingredients``
|
| 497 |
+
(the three ingredient images' labels), ``truth`` (what the connectome is scored against, and how),
|
| 498 |
+
``files`` (the download files' prefix)."""
|
| 499 |
+
raise NotImplementedError
|
| 500 |
+
|
| 501 |
+
@classmethod
|
| 502 |
+
def presets(cls, cfg):
|
| 503 |
+
"""The acquisitions the page offers besides custom shells, the default first."""
|
| 504 |
+
raise NotImplementedError
|
| 505 |
+
|
| 506 |
+
@classmethod
|
| 507 |
+
def shapes_of(cls, cfg):
|
| 508 |
+
"""The timing classes a shell can play: ``{name: {label, delta, Delta, TE[, kind]}}``."""
|
| 509 |
+
return cfg["shapes"]
|
| 510 |
+
|
| 511 |
+
@classmethod
|
| 512 |
+
def protocol(cls, cfg, name):
|
| 513 |
+
"""The preset ``name`` as a :class:`Protocol`."""
|
| 514 |
+
raise NotImplementedError
|
| 515 |
+
|
| 516 |
+
@classmethod
|
| 517 |
+
def panel(cls, cfg):
|
| 518 |
+
"""The tissue-and-scanner :class:`Panel`."""
|
| 519 |
+
raise NotImplementedError
|
| 520 |
+
|
| 521 |
+
@classmethod
|
| 522 |
+
def catalogue_numbers(cls, cfg, field_T):
|
| 523 |
+
"""The panel's :attr:`Panel.catalogue` numbers at ``field_T`` in the page's units, a note last."""
|
| 524 |
+
raise NotImplementedError
|
| 525 |
+
|
| 526 |
+
#: Whether the source plays its pulses at the page's scanner gradient class's slew (:meth:`physics_from` takes
|
| 527 |
+
#: ``gradient``); a source that does not plays ideal pulses and the class only checks what it can play.
|
| 528 |
+
plays_slew = False
|
| 529 |
+
|
| 530 |
+
@classmethod
|
| 531 |
+
def physics_from(cls, cfg, values, gradient=None):
|
| 532 |
+
"""The panel (a dict by :attr:`Panel.fields`, page units) as the source's physics, or None when it is off;
|
| 533 |
+
``gradient`` the page's scanner gradient class (a catalogue name) for a source with :attr:`plays_slew`, None
|
| 534 |
+
for ideal pulses."""
|
| 535 |
+
raise NotImplementedError
|
| 536 |
+
|
| 537 |
+
@classmethod
|
| 538 |
+
def knobs(cls, cfg):
|
| 539 |
+
"""The one-knob changes B can make to A, ``{label: (kind, value)}`` (None for no B)."""
|
| 540 |
+
raise NotImplementedError
|
| 541 |
+
|
| 542 |
+
@classmethod
|
| 543 |
+
def apply_knob(cls, cfg, change, protocol, snr_on, snr, values):
|
| 544 |
+
"""B's settings: A's with ``change`` applied; ``(protocol, snr_on, snr, values)``."""
|
| 545 |
+
raise NotImplementedError
|
| 546 |
+
|
| 547 |
+
@classmethod
|
| 548 |
+
def tracking_controls(cls, cfg):
|
| 549 |
+
"""The tracker's inputs: ``{name: (minimum, maximum, value, step, label)}`` for ``density``,
|
| 550 |
+
``max_angle`` and ``step``."""
|
| 551 |
+
raise NotImplementedError
|
| 552 |
+
|
| 553 |
+
@classmethod
|
| 554 |
+
def tracking(cls, cfg, *, density, max_angle, step, key):
|
| 555 |
+
"""The tracker's :class:`Tracking` from the page's inputs."""
|
| 556 |
+
raise NotImplementedError
|
| 557 |
+
|
| 558 |
+
@classmethod
|
| 559 |
+
def estimated_seconds(cls, cfg, protocol, *, density, knob, n_keys, ladder, responses=(), scanner=None):
|
| 560 |
+
"""The GPU seconds a run of ``protocol`` reserves on a shared pool, from the measured cost model;
|
| 561 |
+
``responses`` the ``(state, n_meas, saves)`` of each :meth:`prepare` the call computes (:meth:`responses`),
|
| 562 |
+
``scanner`` the machine (a catalogue key; None: the ideal scanner)."""
|
| 563 |
+
raise NotImplementedError
|
| 564 |
+
|
| 565 |
+
# ---- the run's side ----
|
| 566 |
+
@classmethod
|
| 567 |
+
def load(cls, cfg, *, local=None):
|
| 568 |
+
"""The source of ``cfg`` with its data loaded (``local``: a local copy instead of the Hub's)."""
|
| 569 |
+
return cls(cfg)
|
| 570 |
+
|
| 571 |
+
def validate(self, protocol, physics):
|
| 572 |
+
"""Refuses, before any work, a run this source cannot do; returns its measurements."""
|
| 573 |
+
return measurements(protocol, self.shapes)
|
| 574 |
+
|
| 575 |
+
def response_key(self, meas, physics=None):
|
| 576 |
+
"""The key of :meth:`prepare`'s result in this process's cache; None for a source with nothing to prepare."""
|
| 577 |
+
return None
|
| 578 |
+
|
| 579 |
+
def cached(self, meas, physics=None):
|
| 580 |
+
""":meth:`prepare`'s result for ``meas`` at ``physics`` when this process has it, else None."""
|
| 581 |
+
return None
|
| 582 |
+
|
| 583 |
+
def keep(self, prepared):
|
| 584 |
+
"""``{response_key: result}`` of :meth:`prepare` computed in another process kept in this one's cache."""
|
| 585 |
+
return
|
| 586 |
+
|
| 587 |
+
def responses(self, entries):
|
| 588 |
+
"""``(state, n_meas, saves)`` for each :meth:`prepare` of a run's ``entries`` ``[(meas, physics)]`` that a
|
| 589 |
+
process forked from this one would compute, ``state`` a ``[budget]`` key, ``saves`` the pack saves it spans;
|
| 590 |
+
empty for a source with nothing to prepare."""
|
| 591 |
+
return []
|
| 592 |
+
|
| 593 |
+
def prepare(self, meas, physics=None):
|
| 594 |
+
"""The share of a replay of ``meas`` at ``physics`` that needs no device, computed and kept in this process's
|
| 595 |
+
cache (None for a source that has none); :meth:`replay` takes it as ``prepared``. A run looks it up on the page
|
| 596 |
+
(:meth:`cached`) and computes what is missing inside the GPU call."""
|
| 597 |
+
return None
|
| 598 |
+
|
| 599 |
+
def replay(self, meas, physics=None, prepared=None):
|
| 600 |
+
"""``(dwi, floor, s0_factor, seconds)``: the S0-normalised signal of every voxel per measurement (NaN
|
| 601 |
+
outside the source's voxels), the split-half floor per voxel (zero where the source has none), the voxel's
|
| 602 |
+
raw b = 0 signal as a fraction of M0 (what relaxation, contact and the field took, 1 when the source cannot
|
| 603 |
+
tell), and the time; at ``physics`` else bare diffusion; ``prepared`` is :meth:`prepare`'s."""
|
| 604 |
+
raise NotImplementedError
|
| 605 |
+
|
| 606 |
+
def reconstruct(self, dwi, s0_factor, meas, mask):
|
| 607 |
+
"""``(sh, seconds, extras)``: the FOD field from the DWI, the time of each step, and whatever else the
|
| 608 |
+
reconstruction estimated (``fractions`` on the multi-tissue path): the configuration's
|
| 609 |
+
:func:`reconstruction`, the single-fibre response and dmipy-fit's batched Tournier 2007 CSD (:func:`csd`, one
|
| 610 |
+
step ``csd``) or three-tissue responses and multi-tissue CSD on the signal in M0 units (:func:`csd_msmt`)."""
|
| 611 |
+
if reconstruction(self.cfg) == "tournier07":
|
| 612 |
+
sh, t, _ = csd(dwi, meas, mask, backend=self.backend)
|
| 613 |
+
return sh, {"csd": t}, {}
|
| 614 |
+
sh, fractions, _, (t_resp, t_fit) = csd_msmt(dwi * s0_factor[..., None], meas, mask, backend=self.backend)
|
| 615 |
+
return sh, {"responses (dhollander16)": t_resp, f"MT-CSD (csd_msmt_{self.backend})": t_fit}, dict(fractions=fractions)
|
| 616 |
+
|
| 617 |
+
def tracking_inputs(self, sh, density):
|
| 618 |
+
"""``(field, seeds)``: the FOD field on the tracking domain and the seeds at ``density``."""
|
| 619 |
+
raise NotImplementedError
|
| 620 |
+
|
| 621 |
+
def reference(self, tracking, seeds):
|
| 622 |
+
"""``(reference, seconds)``: what the connectome is scored against at ``tracking`` from ``seeds``."""
|
| 623 |
+
raise NotImplementedError
|
| 624 |
+
|
| 625 |
+
def score(self, M, reference):
|
| 626 |
+
"""The connectome ``M`` against ``reference``: a dict of numbers."""
|
| 627 |
+
raise NotImplementedError
|
| 628 |
+
|
| 629 |
+
def compare(self, a, b):
|
| 630 |
+
"""Run A against run B (two :class:`Result`): a dict of numbers."""
|
| 631 |
+
raise NotImplementedError
|
| 632 |
+
|
| 633 |
+
def plan(self, meas, physics=None):
|
| 634 |
+
"""What a replay reads before any byte moves (None when the source has nothing to plan)."""
|
| 635 |
+
return None
|
| 636 |
+
|
| 637 |
+
def warm(self):
|
| 638 |
+
"""Whatever the first run would otherwise pay (nothing for a source that reads per run)."""
|
| 639 |
+
return
|
| 640 |
+
|
| 641 |
+
def warm_in_background(self):
|
| 642 |
+
""":meth:`warm` while the page serves, for a source whose warm-up is long enough to matter; this one's is
|
| 643 |
+
:meth:`warm` itself, done before the page serves. Returns the handle the caller may join, or None."""
|
| 644 |
+
self.warm()
|
| 645 |
+
return None
|
| 646 |
+
|
| 647 |
+
def release(self):
|
| 648 |
+
"""Whatever a run kept on the device that must not survive it (nothing for a source that reads per run)."""
|
| 649 |
+
return
|
| 650 |
+
|
| 651 |
+
def ingredients(self, meas, physics=None, prepared=None):
|
| 652 |
+
"""The per-voxel maps of what each tier multiplies into the sum (None for a source without them)."""
|
| 653 |
+
return None
|
| 654 |
+
|
| 655 |
+
def ladder_steps(self, physics):
|
| 656 |
+
"""The rungs below ``physics``: ``[(label, physics)]`` from bare diffusion (None) with the source's
|
| 657 |
+
:attr:`TIERS` switched on one at a time, up to (not including) ``physics`` itself; empty for bare physics."""
|
| 658 |
+
if physics is None or physics.bare:
|
| 659 |
+
return []
|
| 660 |
+
steps = [("bare diffusion", None)]
|
| 661 |
+
on = []
|
| 662 |
+
wanted = [q for q in self.TIERS if getattr(physics, q)]
|
| 663 |
+
for tier in wanted[:-1]:
|
| 664 |
+
on.append(tier)
|
| 665 |
+
steps.append(("+ " + " + ".join(on), replace(physics, **{q: q in on for q in self.TIERS})))
|
| 666 |
+
return steps
|
| 667 |
+
|
| 668 |
+
def ladder(self, meas, physics, prepared=None):
|
| 669 |
+
"""The noise-free replays of :meth:`ladder_steps`, ``[(label, dwi)]``; ``prepared`` is one :meth:`prepare`
|
| 670 |
+
per rung, in order (None for a source that has none)."""
|
| 671 |
+
steps = self.ladder_steps(physics)
|
| 672 |
+
prepared = prepared if prepared is not None else [None] * len(steps)
|
| 673 |
+
return [(label, self.replay(meas, ph, pr)[0]) for (label, ph), pr in zip(steps, prepared)]
|
| 674 |
+
|
| 675 |
+
# ---- what the page draws from a run (None where the source has no such view) ----
|
| 676 |
+
def score_key(self):
|
| 677 |
+
"""The score's headline number, by its key in :meth:`score`'s dict."""
|
| 678 |
+
raise NotImplementedError
|
| 679 |
+
|
| 680 |
+
def score_text(self, tag, res):
|
| 681 |
+
"""The headline of run ``tag`` (Markdown)."""
|
| 682 |
+
raise NotImplementedError
|
| 683 |
+
|
| 684 |
+
def compare_text(self, c, knob):
|
| 685 |
+
"""The headline line of A against B (:meth:`compare`'s dict)."""
|
| 686 |
+
raise NotImplementedError
|
| 687 |
+
|
| 688 |
+
def matrices(self, M, score, reference):
|
| 689 |
+
"""The connectome beside what it is scored against (an image)."""
|
| 690 |
+
raise NotImplementedError
|
| 691 |
+
|
| 692 |
+
def truth_views(self):
|
| 693 |
+
"""The truth tab's two views (a 3-D figure, an image), drawn once per process."""
|
| 694 |
+
raise NotImplementedError
|
| 695 |
+
|
| 696 |
+
@staticmethod
|
| 697 |
+
def ingredient_layers(ingredients):
|
| 698 |
+
"""The explorer's three ingredient images as ``[(title, map, style)]`` (``style`` the keywords of
|
| 699 |
+
:func:`space.viewers.map_slice`, ``map`` None for an image with nothing to show)."""
|
| 700 |
+
return [None, None, None]
|
| 701 |
+
|
| 702 |
+
def lobar(self, M, score, reference):
|
| 703 |
+
"""The connectome over the regions' groups beside the reference's (an image), None without groups."""
|
| 704 |
+
return None
|
| 705 |
+
|
| 706 |
+
def truth_view(self, dwi, meas, z, m):
|
| 707 |
+
"""A DWI slice with the input's FOD peaks over it, None for a source whose input is not an FOD."""
|
| 708 |
+
return None
|
| 709 |
+
|
| 710 |
+
def fractions_view(self, extras, z):
|
| 711 |
+
"""The recovered tissue fractions against the input's at slice ``z``, None for a source without them."""
|
| 712 |
+
return None
|
| 713 |
+
|
| 714 |
+
def roundtrip_rows(self, res):
|
| 715 |
+
"""Rows ``(what, value)`` of the reconstruction against the input; empty for a source without one."""
|
| 716 |
+
return []
|
| 717 |
+
|
| 718 |
+
def response_view(self, prepared, extras):
|
| 719 |
+
"""The estimated responses against the true ones (an image), None for a source without them."""
|
| 720 |
+
return None
|
| 721 |
+
|
| 722 |
+
def extra_files(self, res, out_dir, stem):
|
| 723 |
+
"""Files beside the tractograms and volumes (paths)."""
|
| 724 |
+
return []
|
| 725 |
+
|
| 726 |
+
def accuracy(self, res=None):
|
| 727 |
+
"""Rows ``(what, value)`` saying what this source's replay is an approximation of, and ``res``'s own floor."""
|
| 728 |
+
rows = []
|
| 729 |
+
if res is not None:
|
| 730 |
+
if np.any(res.floor > 0):
|
| 731 |
+
f = floor_stats(res)
|
| 732 |
+
rows.append(["this run's floor: median / 99 % / max over voxels with signal", f"{f['median']:.4f} / {f['p99']:.4f} / {f['max']:.4f}"])
|
| 733 |
+
sf = res.s0_factor[np.isfinite(res.dwi[..., 0])]
|
| 734 |
+
rows.append(["this run's b = 0 signal over M0: min / median / max", f"{np.nanmin(sf):.3f} / {np.nanmedian(sf):.3f} / {np.nanmax(sf):.3f}"])
|
| 735 |
+
snr = b0_snr(res)
|
| 736 |
+
if snr:
|
| 737 |
+
rows.append([f"b = 0 SNR at SNR {res.snr:g} at M0: min / median / max", f"{snr['min']:.1f} / {snr['median']:.1f} / {snr['max']:.1f}"])
|
| 738 |
+
return rows
|
| 739 |
+
|
| 740 |
+
|
| 741 |
+
def s0_normalised(S, b0, M0=None):
|
| 742 |
+
"""``(S / S0, S0 / M0_max)``: every voxel's signal over its own b = 0 mean, and that b = 0 mean over the largest
|
| 743 |
+
M0 (the bare signal of the fullest water voxel: ``M0`` is the bare b = 0 map, None gives a factor of 1)."""
|
| 744 |
+
S0 = np.nanmean(S[..., b0], axis=-1)
|
| 745 |
+
factor = S0 / np.nanmax(M0) if M0 is not None else np.where(np.isfinite(S0), 1.0, np.nan)
|
| 746 |
+
return S / S0[..., None], factor
|
| 747 |
+
|
| 748 |
+
|
| 749 |
+
|
| 750 |
+
# ---- the stages -------------------------------------------------------------------------------------------------
|
| 751 |
+
|
| 752 |
+
def add_noise(dwi, snr, s0_factor=None, seed=0, backend="jax"):
|
| 753 |
+
"""Rician noise at ``snr`` defined at M0, the bare signal of the fullest water voxel: sigma is M0 / snr in
|
| 754 |
+
absolute units, so on the S0-normalised DWI it is ``1 / (snr * s0_factor)`` per voxel (``s0_factor`` the voxel's
|
| 755 |
+
raw b = 0 over M0; None means 1 everywhere, the b = 0 SNR itself). ``None`` for ``snr`` leaves the signal
|
| 756 |
+
noiseless. NaN voxels stay NaN. The draw comes from JAX's generator on the jax backend and from numpy's on the
|
| 757 |
+
torch backend (a forked GPU worker must not touch JAX); the two streams differ, the distribution is the same."""
|
| 758 |
+
if snr is None:
|
| 759 |
+
return dwi
|
| 760 |
+
if snr <= 0:
|
| 761 |
+
raise ValueError("SNR is positive, or None for no noise")
|
| 762 |
+
from dmipy_sim.acquisition.noise import add_rician_noise
|
| 763 |
+
valid = np.isfinite(dwi)
|
| 764 |
+
factor = np.ones(dwi.shape[:-1]) if s0_factor is None else np.asarray(s0_factor, np.float64)
|
| 765 |
+
if factor.shape != dwi.shape[:-1] or np.any(factor[np.isfinite(factor)] <= 0):
|
| 766 |
+
raise ValueError("s0_factor is a positive map over the DWI's voxels")
|
| 767 |
+
sigma = np.broadcast_to((1.0 / (snr * factor))[..., None], dwi.shape)[valid]
|
| 768 |
+
out = np.array(dwi) # Rice(nu, sigma) = sigma * Rice(nu / sigma, 1): one unit-sigma draw
|
| 769 |
+
out[valid] = sigma * np.asarray(add_rician_noise(dwi[valid] / sigma, 1.0, seed=seed, rng="numpy" if backend == "torch" else "jax"))
|
| 770 |
+
return out
|
| 771 |
+
|
| 772 |
+
|
| 773 |
+
def scheme(meas):
|
| 774 |
+
"""The measurements as dmipy-fit's acquisition scheme (SI b-values, the same b = 0 threshold as the pipeline)."""
|
| 775 |
+
from dmipy_fit.core.acquisition_scheme import acquisition_scheme_from_bvalues
|
| 776 |
+
return acquisition_scheme_from_bvalues(meas.bvals * 1e6, meas.dirs, delta=meas.delta, Delta=meas.Delta, TE=meas.TE, b0_threshold=B0_MAX * 1e6)
|
| 777 |
+
|
| 778 |
+
|
| 779 |
+
def csd(dwi, meas, mask, backend="jax"):
|
| 780 |
+
"""``(sh, seconds, response)``: the FOD field ``(X, Y, Z, 45)`` in the tournier07 basis, dmipy-fit's batched
|
| 781 |
+
Tournier 2007 solver on ``backend`` with the response ``white_matter_response_tournier07`` estimates from the
|
| 782 |
+
masked voxels (``response`` is its ``(S0, model)``), fitted on ``mask`` (the voxels with signal)."""
|
| 783 |
+
from dmipy_fit.core.modeling_framework import MultiCompartmentSphericalHarmonicsModel
|
| 784 |
+
from dmipy_fit.tissue_response.white_matter_response import white_matter_response_tournier07
|
| 785 |
+
t0 = time.perf_counter()
|
| 786 |
+
data = np.nan_to_num(dwi, nan=0.0)
|
| 787 |
+
sch = scheme(meas)
|
| 788 |
+
S0, response, _ = white_matter_response_tournier07(sch, data[mask])
|
| 789 |
+
mc = MultiCompartmentSphericalHarmonicsModel(models=[response], sh_order=SH_ORDER)
|
| 790 |
+
fitted = mc.fit(sch, data, mask=mask, solver=f"csd_tournier07_{backend}", verbose=False)
|
| 791 |
+
return np.asarray(fitted.fitted_parameters["sh_coeff"], np.float64), time.perf_counter() - t0, (S0, response)
|
| 792 |
+
|
| 793 |
+
|
| 794 |
+
MSMT_ISSUE = "dmrai-lab/dmipy-fit#39"
|
| 795 |
+
|
| 796 |
+
|
| 797 |
+
def csd_msmt(data, meas, mask, backend="torch"):
|
| 798 |
+
"""``(sh, fractions, responses, seconds)``: three-tissue responses estimated from the data (Dhollander 2016,
|
| 799 |
+
``three_tissue_response_dhollander16`` with ``mask=``; the white-matter response by Tournier 2007's FA selection,
|
| 800 |
+
the single-tissue path's, since Tournier 2013's iteration does not converge on a replayed brain in its five
|
| 801 |
+
iterations and costs 5 s where this costs 0.2 s) and multi-shell multi-tissue CSD (Jeurissen 2014,
|
| 802 |
+
``solver='csd_msmt_<backend>'``), dmipy-fit's batched solvers of dmipy-fit#39. ``data`` is the signal in M0 units
|
| 803 |
+
(not S0-normalised: the tissues' b = 0 signals are what separates them); ``sh`` the WM FOD ``(X, Y, Z, 45)``,
|
| 804 |
+
``fractions`` the fitted WM / GM / CSF volume fractions ``(X, Y, Z, 3)``, ``responses`` ``(S0s, models)`` as
|
| 805 |
+
estimated, ``seconds`` ``(responses, fit)``. Refuses by name, before any work, a dmipy-fit without them."""
|
| 806 |
+
import inspect
|
| 807 |
+
from dmipy_fit.core.modeling_framework import MultiCompartmentSphericalHarmonicsModel
|
| 808 |
+
from dmipy_fit.tissue_response.three_tissue_response import three_tissue_response_dhollander16
|
| 809 |
+
params = inspect.signature(three_tissue_response_dhollander16).parameters
|
| 810 |
+
if "mask" not in params or "backend" not in params:
|
| 811 |
+
raise RuntimeError(f"this dmipy-fit has no batched dhollander16 (three_tissue_response_dhollander16(scheme, data, mask=, backend=)): "
|
| 812 |
+
f"the multi-tissue reconstruction is {MSMT_ISSUE}; until it merges, DISCO_RECONSTRUCTION=tournier07 "
|
| 813 |
+
f"runs the single-tissue Tournier 2007 CSD instead")
|
| 814 |
+
t0 = time.perf_counter()
|
| 815 |
+
data = np.nan_to_num(np.asarray(data, np.float64), nan=0.0)
|
| 816 |
+
sch = scheme(meas)
|
| 817 |
+
S0s, models, _ = three_tissue_response_dhollander16(sch, data, mask=mask, backend=backend, wm_algorithm="tournier07")
|
| 818 |
+
t_resp = time.perf_counter() - t0; t0 = time.perf_counter()
|
| 819 |
+
mc = MultiCompartmentSphericalHarmonicsModel(models=list(models), S0_tissue_responses=list(S0s), sh_order=SH_ORDER)
|
| 820 |
+
try:
|
| 821 |
+
fitted = mc.fit(sch, data, mask=mask, solver=f"csd_msmt_{backend}", verbose=False)
|
| 822 |
+
except ValueError as e:
|
| 823 |
+
if "Unknown solver" in str(e):
|
| 824 |
+
raise RuntimeError(f"this dmipy-fit has no solver csd_msmt_{backend}: the multi-tissue CSD is {MSMT_ISSUE}") from e
|
| 825 |
+
raise
|
| 826 |
+
fp = fitted.fitted_parameters
|
| 827 |
+
fractions = np.stack([np.asarray(fp[name], np.float64) for name in mc.partial_volume_names], -1)
|
| 828 |
+
return np.asarray(fp["sh_coeff"], np.float64), fractions, (list(S0s), list(models)), (t_resp, time.perf_counter() - t0)
|
| 829 |
+
|
| 830 |
+
|
| 831 |
+
@dataclass(frozen=True)
|
| 832 |
+
class Tracking:
|
| 833 |
+
"""The tracker's settings: dipy's defaults for the DiSCo score."""
|
| 834 |
+
density: int = 4
|
| 835 |
+
step_mm: float = 0.5
|
| 836 |
+
max_angle: float = 30.0
|
| 837 |
+
max_steps: int = 500
|
| 838 |
+
relative_threshold: float = 0.1
|
| 839 |
+
key: int = 0
|
| 840 |
+
|
| 841 |
+
|
| 842 |
+
def track(field, seeds, settings, backend):
|
| 843 |
+
"""``(tractogram, seconds)``: probabilistic streamlines from ``seeds`` on ``field``."""
|
| 844 |
+
from dmipy_tract import track as _track
|
| 845 |
+
t0 = time.perf_counter()
|
| 846 |
+
tg = _track(field, seeds, rule="probabilistic", step_mm=settings.step_mm, max_angle=settings.max_angle,
|
| 847 |
+
max_steps=settings.max_steps, relative_threshold=settings.relative_threshold, key=settings.key, backend=backend)
|
| 848 |
+
return tg, time.perf_counter() - t0
|
| 849 |
+
|
| 850 |
+
|
| 851 |
+
def peaks(sh, n_dirs=362):
|
| 852 |
+
"""The principal direction of every voxel's FOD, ``(X, Y, Z, 3)`` unit vectors, and its amplitude ``(X, Y, Z)``:
|
| 853 |
+
the largest FOD value over the tracker's hemisphere (zero where the FOD is zero or NaN)."""
|
| 854 |
+
from dmipy_tract import hemisphere, sh_matrix
|
| 855 |
+
dirs = hemisphere(n_dirs)
|
| 856 |
+
B = sh_matrix(SH_ORDER, dirs) # (n_dirs, n_coef)
|
| 857 |
+
coef = np.nan_to_num(np.asarray(sh, np.float64)).reshape(-1, sh.shape[-1])
|
| 858 |
+
amp = coef @ B.T
|
| 859 |
+
k = np.argmax(amp, axis=1)
|
| 860 |
+
peak = np.take_along_axis(amp, k[:, None], axis=1)[:, 0]
|
| 861 |
+
d = np.where(peak[:, None] > 0, dirs[k], 0.0)
|
| 862 |
+
return d.reshape(sh.shape[:-1] + (3,)), np.clip(peak, 0, None).reshape(sh.shape[:-1])
|
| 863 |
+
|
| 864 |
+
|
| 865 |
+
def fod_peaks(sh, n_max=3, *, relative=0.1, separation_deg=25.0, n_dirs=362, chunk=20000):
|
| 866 |
+
"""The FOD's peaks per voxel of ``sh (..., n_coef)``: ``(dirs (..., n_max, 3), amps (..., n_max), count (...))``,
|
| 867 |
+
the local maxima of the FOD on the tracker's hemisphere (antipodes identified, a direction's neighbours those
|
| 868 |
+
within 12 degrees) above ``relative`` of the voxel's largest value, strongest first, a weaker one within
|
| 869 |
+
``separation_deg`` of a stronger one dropped; zero rows beyond ``count``. The first is :func:`peaks`'s."""
|
| 870 |
+
from dmipy_tract import hemisphere, sh_matrix
|
| 871 |
+
V = hemisphere(n_dirs)
|
| 872 |
+
B = sh_matrix(SH_ORDER, V)
|
| 873 |
+
c = np.abs(V @ V.T)
|
| 874 |
+
nbr = [np.flatnonzero((c[i] > np.cos(np.radians(12.0))) & (np.arange(n_dirs) != i)) for i in range(n_dirs)]
|
| 875 |
+
width = max(len(x) for x in nbr)
|
| 876 |
+
table = np.array([np.pad(x, (0, width - len(x)), constant_values=i) for i, x in enumerate(nbr)])
|
| 877 |
+
coef = np.nan_to_num(np.asarray(sh, np.float64)).reshape(-1, np.shape(sh)[-1])
|
| 878 |
+
n = coef.shape[0]
|
| 879 |
+
dirs = np.zeros((n, n_max, 3)); amps = np.zeros((n, n_max)); count = np.zeros(n, np.int64)
|
| 880 |
+
cos_sep = np.cos(np.radians(separation_deg))
|
| 881 |
+
for s0 in range(0, n, chunk):
|
| 882 |
+
A = coef[s0:s0 + chunk] @ B.T # (m, n_dirs)
|
| 883 |
+
top = A.max(1, keepdims=True)
|
| 884 |
+
is_max = (A >= A[:, table].max(2)) & (A > relative * top) & (top > 0)
|
| 885 |
+
cand = np.where(is_max, A, -np.inf)
|
| 886 |
+
order = np.argsort(-cand, axis=1)[:, :n_max + 3] # a few spare candidates for the separation rule
|
| 887 |
+
kept = np.zeros((len(A), n_max), np.int64); nk = np.zeros(len(A), np.int64)
|
| 888 |
+
for j in range(order.shape[1]):
|
| 889 |
+
idx = order[:, j]
|
| 890 |
+
ok = np.isfinite(cand[np.arange(len(A)), idx]) & (nk < n_max)
|
| 891 |
+
for q in range(n_max): # not within separation of a kept one
|
| 892 |
+
prev = kept[:, q]
|
| 893 |
+
close = (q < nk) & (np.abs(np.einsum("ij,ij->i", V[idx], V[prev])) > cos_sep)
|
| 894 |
+
ok &= ~close
|
| 895 |
+
kept[ok, nk[ok]] = idx[ok]; nk[ok] += 1
|
| 896 |
+
rows = np.arange(len(A))[:, None]
|
| 897 |
+
valid = np.arange(n_max)[None, :] < nk[:, None]
|
| 898 |
+
dirs[s0:s0 + chunk] = np.where(valid[..., None], V[kept], 0.0)
|
| 899 |
+
amps[s0:s0 + chunk] = np.where(valid, A[rows, kept], 0.0)
|
| 900 |
+
count[s0:s0 + chunk] = nk
|
| 901 |
+
lead = np.shape(sh)[:-1]
|
| 902 |
+
return dirs.reshape(lead + (n_max, 3)), amps.reshape(lead + (n_max,)), count.reshape(lead)
|
| 903 |
+
|
| 904 |
+
|
| 905 |
+
def pearson(a, b):
|
| 906 |
+
"""The Pearson correlation of two vectors, NaN when either is constant."""
|
| 907 |
+
a = np.asarray(a, np.float64); b = np.asarray(b, np.float64)
|
| 908 |
+
if a.std() == 0 or b.std() == 0:
|
| 909 |
+
return float("nan")
|
| 910 |
+
return float(np.corrcoef(a, b)[0, 1])
|
| 911 |
+
|
| 912 |
+
|
| 913 |
+
def connected_pairs(M):
|
| 914 |
+
"""How many region pairs (the upper triangle of ``M`` without the diagonal) ``M`` connects."""
|
| 915 |
+
return int((np.asarray(M)[np.triu_indices(len(M), 1)] > 0).sum())
|
| 916 |
+
|
| 917 |
+
|
| 918 |
+
def pair_spread(matrices, scores, *, key):
|
| 919 |
+
"""Over repeated runs: the streamline-count mean and standard deviation per region pair, the mean and standard
|
| 920 |
+
deviation of the score ``key``, and the median coefficient of variation over the pairs that any run connected."""
|
| 921 |
+
M = np.stack(matrices).astype(np.float64)
|
| 922 |
+
pairs = np.triu_indices(M.shape[1], 1)
|
| 923 |
+
mean = M.mean(0); std = M.std(0, ddof=1) if len(M) > 1 else np.zeros_like(mean)
|
| 924 |
+
any_ = mean[pairs] > 0
|
| 925 |
+
cv = std[pairs][any_] / mean[pairs][any_]
|
| 926 |
+
pc = np.array([s[key] for s in scores])
|
| 927 |
+
return dict(mean=mean, std=std, n=len(M), key=key, pearson_mean=float(pc.mean()), pearson_std=float(pc.std(ddof=1)) if len(pc) > 1 else 0.0,
|
| 928 |
+
cv_median=float(np.median(cv)) if cv.size else float("nan"), pairs_any=int(any_.sum()),
|
| 929 |
+
pairs_always=int((M[:, pairs[0], pairs[1]] > 0).all(0).sum()))
|
| 930 |
+
|
| 931 |
+
|
| 932 |
+
def dti(dwi, meas, mask, *, b_max=1500.0):
|
| 933 |
+
"""``(md, fa)`` grids from a log-linear tensor fit on the rows with b <= ``b_max`` s/mm^2 (the b = 0 rows
|
| 934 |
+
included): mean diffusivity in um^2/ms and fractional anisotropy, NaN outside ``mask``."""
|
| 935 |
+
rows = meas.bvals <= b_max
|
| 936 |
+
if rows.sum() < 7 or meas.b0[rows].sum() < 1 or (~meas.b0[rows]).sum() < 6:
|
| 937 |
+
raise ValueError("a tensor fit needs a b = 0 row and six or more directions at b <= b_max")
|
| 938 |
+
g = meas.dirs[rows]; b = meas.bvals[rows] / 1e3 # ms/um^2, so D comes out in um^2/ms
|
| 939 |
+
X = np.column_stack([np.ones(rows.sum()), -b * g[:, 0] ** 2, -b * g[:, 1] ** 2, -b * g[:, 2] ** 2,
|
| 940 |
+
-2 * b * g[:, 0] * g[:, 1], -2 * b * g[:, 0] * g[:, 2], -2 * b * g[:, 1] * g[:, 2]])
|
| 941 |
+
S = np.clip(np.nan_to_num(dwi[mask][:, rows], nan=1e-6), 1e-6, None)
|
| 942 |
+
beta = np.linalg.pinv(X) @ np.log(S).T # (7, n_vox)
|
| 943 |
+
D = np.empty((beta.shape[1], 3, 3))
|
| 944 |
+
D[:, 0, 0] = beta[1]; D[:, 1, 1] = beta[2]; D[:, 2, 2] = beta[3]
|
| 945 |
+
D[:, 0, 1] = D[:, 1, 0] = beta[4]; D[:, 0, 2] = D[:, 2, 0] = beta[5]; D[:, 1, 2] = D[:, 2, 1] = beta[6]
|
| 946 |
+
ev = np.linalg.eigvalsh(D)
|
| 947 |
+
md = ev.mean(1)
|
| 948 |
+
fa = np.sqrt(1.5 * ((ev - md[:, None]) ** 2).sum(1) / np.maximum((ev ** 2).sum(1), 1e-30))
|
| 949 |
+
MD = np.full(mask.shape, np.nan); FA = np.full(mask.shape, np.nan)
|
| 950 |
+
MD[mask] = md; FA[mask] = fa
|
| 951 |
+
return MD, FA
|
| 952 |
+
|
| 953 |
+
|
| 954 |
+
def layer_differences(layers, meas, mask):
|
| 955 |
+
"""Between consecutive layers ``[(label, dwi)]``, per shell: the median and 99th percentile of |dS| over the
|
| 956 |
+
voxels of ``mask``; rows ``(from, to, b, median, p99)``."""
|
| 957 |
+
rows = []
|
| 958 |
+
shells = np.unique(np.round(meas.bvals[~meas.b0]))
|
| 959 |
+
for (la, a), (lb, b) in zip(layers[:-1], layers[1:]):
|
| 960 |
+
d = np.abs(b - a)[mask]
|
| 961 |
+
for sh in shells:
|
| 962 |
+
cols = np.round(meas.bvals) == sh
|
| 963 |
+
v = d[:, cols][np.isfinite(d[:, cols])]
|
| 964 |
+
rows.append((la, lb, float(sh), float(np.median(v)) if v.size else float("nan"), float(np.quantile(v, 0.99)) if v.size else float("nan")))
|
| 965 |
+
return rows
|
| 966 |
+
|
| 967 |
+
|
| 968 |
+
def floor_stats(res):
|
| 969 |
+
"""The run's split-half floor over the voxels with signal: ``median``, ``p99``, ``max`` and the voxel count."""
|
| 970 |
+
f = res.floor[np.isfinite(res.dwi[..., 0])]
|
| 971 |
+
return dict(median=float(np.median(f)), p99=float(np.quantile(f, 0.99)), max=float(f.max()), n=int(f.size))
|
| 972 |
+
|
| 973 |
+
|
| 974 |
+
def b0_snr(res):
|
| 975 |
+
"""The b = 0 SNR of the run's voxels with signal (``snr`` at M0 times each voxel's S0 factor): ``median``,
|
| 976 |
+
``min``, ``max``; None for a noiseless run."""
|
| 977 |
+
if res.snr is None:
|
| 978 |
+
return None
|
| 979 |
+
f = res.s0_factor[np.isfinite(res.dwi[..., 0])] * res.snr
|
| 980 |
+
return dict(median=float(np.nanmedian(f)), min=float(np.nanmin(f)), max=float(np.nanmax(f)))
|
| 981 |
+
|
| 982 |
+
|
| 983 |
+
def gradient_needed(b, delta, Delta):
|
| 984 |
+
"""The square-pulse PGSE amplitude (T/m) that gives ``b`` (s/mm^2) at ``delta`` / ``Delta`` (s):
|
| 985 |
+
b = γ² G² δ² (Δ − δ/3)."""
|
| 986 |
+
from dmipy_sim.acquisition.scanners import GAMMA
|
| 987 |
+
return float(np.sqrt(b * 1e6 / (GAMMA ** 2 * delta ** 2 * (Delta - delta / 3.0))))
|
| 988 |
+
|
| 989 |
+
|
| 990 |
+
IDEAL = "ideal: no scanner terms, any gradient amplitude"
|
| 991 |
+
|
| 992 |
+
|
| 993 |
+
def machines(cfg):
|
| 994 |
+
"""The configuration's scanner menu after :data:`IDEAL`: ``{label: catalogue key}`` (``[scanners] machines``), each a
|
| 995 |
+
machine of dmipy-sim's catalogue whose every catalogued term the page applies (docs/scanner.md)."""
|
| 996 |
+
return {m["label"]: m["key"] for m in (cfg.get("scanners") or {}).get("machines", [])}
|
| 997 |
+
|
| 998 |
+
|
| 999 |
+
def machine(cfg, label):
|
| 1000 |
+
"""The catalogue key of the menu's ``label``, None for :data:`IDEAL`; an unknown label is refused by name."""
|
| 1001 |
+
if label in (None, IDEAL):
|
| 1002 |
+
return None
|
| 1003 |
+
menu = machines(cfg)
|
| 1004 |
+
if label not in menu:
|
| 1005 |
+
raise ValueError(f"no scanner {label!r}; the menu is {[IDEAL] + list(menu)}")
|
| 1006 |
+
return menu[label]
|
| 1007 |
+
|
| 1008 |
+
|
| 1009 |
+
def limits(key):
|
| 1010 |
+
"""The :class:`dmipy_sim.acquisition.scanners.ScannerLimits` of a catalogue key."""
|
| 1011 |
+
from dmipy_sim.acquisition.scanners import ScannerLimits
|
| 1012 |
+
return ScannerLimits.of(key)
|
| 1013 |
+
|
| 1014 |
+
|
| 1015 |
+
def playable(protocol, shapes, scanner=None):
|
| 1016 |
+
"""Per shell, the gradient it needs and whether ``scanner`` (a catalogue key, or None for no limit) can play it:
|
| 1017 |
+
rows of ``(shell, b, delta, Delta, G_needed, G_max or None, ok)`` in SI. A stimulated-echo class needs the same
|
| 1018 |
+
amplitude as its PGSE twin (the same δ and diffusion time)."""
|
| 1019 |
+
G_max = float(limits(scanner).G_max) if scanner else None
|
| 1020 |
+
rows = []
|
| 1021 |
+
for s in protocol.shells:
|
| 1022 |
+
t = dict(delta=s.delta, Delta=s.Delta) if s.free_timing else shapes[s.shape]
|
| 1023 |
+
delta, Delta = float(t["delta"]), float(t["Delta"])
|
| 1024 |
+
G = gradient_needed(s.b, delta, Delta)
|
| 1025 |
+
rows.append((s.shape, s.b, delta, Delta, G, G_max, G_max is None or G <= G_max))
|
| 1026 |
+
return rows
|
| 1027 |
+
|
| 1028 |
+
|
| 1029 |
+
#: how the page names a catalogue leaf's confidence
|
| 1030 |
+
CONFIDENCE = {"cited": "measured", "widely-quoted": "measured", "derived": "derived from a measurement",
|
| 1031 |
+
"inferred": "inferred from the class"}
|
| 1032 |
+
#: the scanner terms and the catalogue leaves each is read from (section, leaf), in the page's order
|
| 1033 |
+
TERMS = (("field strength and direction", (("frame", "b0_axis"),)),
|
| 1034 |
+
("field law: its gradient g0 (and its value, a phase per voxel)", (("homogeneity", "b0_harmonic_Z2"), ("homogeneity", "b0_harmonic_Z2X"))),
|
| 1035 |
+
("gradient nonlinearity L", (("gradient_nonlinearity", "d_scale_y_dx"), ("gradient_nonlinearity", "b_error_quadratic_axial"))),
|
| 1036 |
+
("Maxwell (concomitant) gradient", ()),
|
| 1037 |
+
("transmit scale B1", (("rf", "b1_axial_falloff"), ("rf", "b1_calibration_offset"))))
|
| 1038 |
+
|
| 1039 |
+
|
| 1040 |
+
def scanner_terms(key):
|
| 1041 |
+
"""The rows of a machine's term table: ``(term, applied, where the number comes from)``. ``applied`` is whether
|
| 1042 |
+
the catalogue carries the term (the page applies every one it carries); the source is the catalogue leaves'
|
| 1043 |
+
confidence as the page names it (:data:`CONFIDENCE`) with their citation keys, or why the term is absent."""
|
| 1044 |
+
from dmipy_sim.acquisition import scanner_constants as scc
|
| 1045 |
+
L = limits(key)
|
| 1046 |
+
_key, entry, _kind = scc.resolve(key)
|
| 1047 |
+
rows = []
|
| 1048 |
+
have = {"field strength and direction": L.field_T is not None,
|
| 1049 |
+
"field law: its gradient g0 (and its value, a phase per voxel)": L.has_field_law,
|
| 1050 |
+
"gradient nonlinearity L": L.has_gradient_nonlinearity,
|
| 1051 |
+
"Maxwell (concomitant) gradient": L.field_T is not None,
|
| 1052 |
+
"transmit scale B1": L.has_transmit_profile}
|
| 1053 |
+
for term, leaves in TERMS:
|
| 1054 |
+
got = []
|
| 1055 |
+
for sec, leaf in leaves:
|
| 1056 |
+
rec = (entry.get(sec) or {}).get(leaf)
|
| 1057 |
+
if isinstance(rec, dict) and rec.get("value") not in (None, "None") and rec.get("confidence") in CONFIDENCE:
|
| 1058 |
+
got.append(f"{CONFIDENCE[rec['confidence']]} ({rec.get('source_key')})")
|
| 1059 |
+
if term == "Maxwell (concomitant) gradient":
|
| 1060 |
+
src = f"exact from the field strength ({L.field_T:g} T) and the coils' linear field: Maxwell's equations, no fit"
|
| 1061 |
+
elif term == "field strength and direction":
|
| 1062 |
+
u = L.b0_axis or (0.0, 0.0, 1.0)
|
| 1063 |
+
src = f"{L.field_T:g} T along ({u[0]:g}, {u[1]:g}, {u[2]:g}) (R, A, S); " + "; ".join(dict.fromkeys(got))
|
| 1064 |
+
elif have[term]:
|
| 1065 |
+
src = "; ".join(dict.fromkeys(got))
|
| 1066 |
+
elif term == "transmit scale B1" and L.b1_brain_range:
|
| 1067 |
+
src = f"absent: the catalogue holds a range over a brain ({L.b1_brain_range[0]:g}-{L.b1_brain_range[1]:g}), no map"
|
| 1068 |
+
else:
|
| 1069 |
+
src = "absent: the catalogue publishes no such law for this machine"
|
| 1070 |
+
rows.append((term, bool(have[term]), src))
|
| 1071 |
+
return rows
|
| 1072 |
+
|
| 1073 |
+
|
| 1074 |
+
def scanner_text(cfg, label, refused=None):
|
| 1075 |
+
"""The menu entry's term table as Markdown (the page shows it under the menu), followed by each machine the source
|
| 1076 |
+
keeps off its menu and why (``refused``: ``{label: reason}``, :meth:`Source.refused_machines`)."""
|
| 1077 |
+
key = machine(cfg, label)
|
| 1078 |
+
if key is None:
|
| 1079 |
+
lines = ["**ideal:** the commanded gradient everywhere, the field preset and its direction as set; no transmit scale."]
|
| 1080 |
+
else:
|
| 1081 |
+
lines = [f"**{label}** (`{key}`): every term its catalogue entry carries, at the phantom's place in the bore.",
|
| 1082 |
+
"", "| term | applied | from |", "|---|---|---|"]
|
| 1083 |
+
for term, on, src in scanner_terms(key):
|
| 1084 |
+
lines.append(f"| {term} | {'yes' if on else 'no'} | {src} |")
|
| 1085 |
+
for name, why in (refused or {}).items():
|
| 1086 |
+
lines += ["", f"**Not on this menu: {name}.** {why}"]
|
| 1087 |
+
return "\n".join(lines)
|
| 1088 |
+
|
| 1089 |
+
|
| 1090 |
+
def sample_tractogram(tg, n, *, seed=0):
|
| 1091 |
+
"""``n`` streamlines drawn without replacement from ``tg`` (``tg`` itself when it has no more), in their
|
| 1092 |
+
original order: what the page keeps and draws while the full tractogram goes to the .tck file."""
|
| 1093 |
+
if len(tg) <= n:
|
| 1094 |
+
return tg
|
| 1095 |
+
return tg.select(np.sort(np.random.default_rng(seed).choice(len(tg), n, replace=False)))
|
| 1096 |
+
|
| 1097 |
+
|
| 1098 |
+
@dataclass
|
| 1099 |
+
class Result:
|
| 1100 |
+
"""One run: the protocol and its rows, the DWI the reconstruction saw (noisy when ``snr`` is set), the replay floor
|
| 1101 |
+
per voxel, the voxel's b = 0 signal over M0 (what the physics took, the b = 0 SNR is ``snr`` times it), the FOD SH
|
| 1102 |
+
field, the tractogram and its seeds, the connectome and its score, the stage times, the physics (None for bare
|
| 1103 |
+
diffusion), ``clean`` (the replay before the noise), ``reference`` (what the connectome was scored against) and
|
| 1104 |
+
``extras`` (what the source's reconstruction and scoring estimated beside the FOD, by name)."""
|
| 1105 |
+
protocol: Protocol
|
| 1106 |
+
meas: Measurements
|
| 1107 |
+
dwi: np.ndarray
|
| 1108 |
+
floor: np.ndarray
|
| 1109 |
+
s0_factor: np.ndarray
|
| 1110 |
+
sh: np.ndarray
|
| 1111 |
+
tractogram: object
|
| 1112 |
+
seeds: np.ndarray
|
| 1113 |
+
matrix: np.ndarray
|
| 1114 |
+
score: dict
|
| 1115 |
+
seconds: dict = field(default_factory=dict)
|
| 1116 |
+
clean: Optional[np.ndarray] = None
|
| 1117 |
+
snr: Optional[float] = None
|
| 1118 |
+
physics: Optional[object] = None
|
| 1119 |
+
reference: Optional[object] = None
|
| 1120 |
+
extras: dict = field(default_factory=dict)
|
| 1121 |
+
|
| 1122 |
+
|
| 1123 |
+
def run_stages(source, protocol, *, snr=None, tracking=Tracking(), noise_seed=0, physics=None, prepared=None):
|
| 1124 |
+
"""The pipeline as a generator: before each of the source's ``STAGES`` it yields ``(stage, k, n)`` (so a page
|
| 1125 |
+
can show where the run is, from inside any worker), and last the :class:`Result`. ``physics`` is the tissue and
|
| 1126 |
+
scanner the replay is evaluated at (None: bare diffusion); ``prepared`` is the source's :meth:`Source.prepare`
|
| 1127 |
+
for it, done on the host before."""
|
| 1128 |
+
t_run = time.perf_counter()
|
| 1129 |
+
stages = source.STAGES
|
| 1130 |
+
|
| 1131 |
+
def at(stage):
|
| 1132 |
+
print(f"[pipeline] {stage} at +{time.perf_counter() - t_run:.1f} s", flush=True) # the server log shows where a run is
|
| 1133 |
+
return stage, stages.index(stage), len(stages)
|
| 1134 |
+
meas = source.validate(protocol, physics)
|
| 1135 |
+
yield at("replay"); dwi, floor, s0_factor, t_replay = source.replay(meas, physics, prepared)
|
| 1136 |
+
yield at("noise"); t0 = time.perf_counter(); noisy = add_noise(dwi, snr, s0_factor, seed=noise_seed, backend=source.backend); t_noise = time.perf_counter() - t0
|
| 1137 |
+
signal = np.isfinite(dwi[..., 0])
|
| 1138 |
+
yield at("csd"); sh, t_csd, extras = source.reconstruct(noisy, s0_factor, meas, signal)
|
| 1139 |
+
yield at("track"); t0 = time.perf_counter(); fld, seeds = source.tracking_inputs(sh, tracking.density); tg, _ = track(fld, seeds, tracking, source.backend); t_track = time.perf_counter() - t0
|
| 1140 |
+
seconds = dict(replay=t_replay, noise=t_noise, **t_csd, track=t_track)
|
| 1141 |
+
if "truth" in stages:
|
| 1142 |
+
yield at("truth")
|
| 1143 |
+
reference, t_ref = source.reference(tracking, seeds)
|
| 1144 |
+
if "truth" in stages:
|
| 1145 |
+
seconds["truth"] = t_ref
|
| 1146 |
+
yield at("score"); t0 = time.perf_counter(); M = source.regions.matrix(tg); s = source.score(M, reference); seconds["score"] = time.perf_counter() - t0
|
| 1147 |
+
seconds["total"] = sum(seconds.values())
|
| 1148 |
+
yield Result(protocol, meas, noisy, floor, s0_factor, sh, tg, seeds, M, s, snr=snr, physics=physics, clean=dwi,
|
| 1149 |
+
seconds=seconds, reference=reference, extras=extras)
|
| 1150 |
+
|
| 1151 |
+
|
| 1152 |
+
def run(source, protocol, *, snr=None, tracking=Tracking(), noise_seed=0, physics=None, prepared=None, progress=None):
|
| 1153 |
+
"""The whole pipeline for one protocol: every stage's output and time. ``progress(stage, k, n)`` is called as
|
| 1154 |
+
each stage begins."""
|
| 1155 |
+
for item in run_stages(source, protocol, snr=snr, tracking=tracking, noise_seed=noise_seed, physics=physics, prepared=prepared):
|
| 1156 |
+
if isinstance(item, Result):
|
| 1157 |
+
return item
|
| 1158 |
+
if progress:
|
| 1159 |
+
progress(*item)
|
| 1160 |
+
|
| 1161 |
+
|
| 1162 |
+
def repeat_tracking(res, source, tracking, keys):
|
| 1163 |
+
"""The tractography of ``res`` (its FOD field, the seeds built once) repeated over tracker ``keys``: a generator
|
| 1164 |
+
of ``(key, matrix, score, seconds)`` scored against ``res``'s own reference; the replay, noise and
|
| 1165 |
+
reconstruction are kept, only the tracker's randomness varies."""
|
| 1166 |
+
fld, seeds = source.tracking_inputs(res.sh, tracking.density)
|
| 1167 |
+
for k in keys:
|
| 1168 |
+
t0 = time.perf_counter()
|
| 1169 |
+
tg, _ = track(fld, seeds, replace(tracking, key=int(k)), source.backend)
|
| 1170 |
+
M = source.regions.matrix(tg)
|
| 1171 |
+
yield int(k), M, source.score(M, res.reference), time.perf_counter() - t0
|
space/sources/__init__.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""The replay sources a Space serves, chosen by the configuration's ``source``: ``disco`` (the DiSCo phantom, a
|
| 2 |
+
:class:`~space.sources.disco.Layout` in demo mode or :class:`~space.sources.disco.Columns` in full mode) or ``brain``
|
| 3 |
+
(:class:`~space.sources.brain.Brain`, a brain composed from an FOD field, tissue fractions and replay packs)."""
|
| 4 |
+
from .. import pipeline as P
|
| 5 |
+
|
| 6 |
+
SOURCES = ("disco", "brain")
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def source_class(cfg):
|
| 10 |
+
"""The :class:`space.pipeline.Source` subclass the configuration names; its class methods are what the page is
|
| 11 |
+
built from before any data loads."""
|
| 12 |
+
name = cfg["source"]
|
| 13 |
+
if name not in SOURCES:
|
| 14 |
+
raise ValueError(f"source must be one of {SOURCES}, got {name!r}")
|
| 15 |
+
if name == "brain":
|
| 16 |
+
from .brain import Brain
|
| 17 |
+
return Brain
|
| 18 |
+
from .disco import Columns, Layout
|
| 19 |
+
return Columns if P.mode(cfg) == "full" else Layout
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def source(cfg, *, local=None):
|
| 23 |
+
"""The source the configuration names, loaded (``local``: a local copy of its data instead of the Hub's)."""
|
| 24 |
+
return source_class(cfg).load(cfg, local=local)
|
space/sources/brain.py
ADDED
|
@@ -0,0 +1,1475 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""The brain source: a brain composed, voxel by voxel, from a white-matter FOD field, WM / GM / CSF fractions and
|
| 2 |
+
replay packs, replayed on the device, reconstructed, tracked and scored against the connectome of its own input.
|
| 3 |
+
|
| 4 |
+
The input is an **asset** (the directory layout of ``SubstrateCommons/masivar-brain``: ``manifest.json``,
|
| 5 |
+
``fod_wm.npy``, ``fractions.npy``, ``mask.npy``, ``labels.npy``, ``regions.json``, ``stop_mask.npy``,
|
| 6 |
+
``mean_b0.npy``): the multi-tissue CSD of a real scan, made once offline, with its parcellation. The replay is the
|
| 7 |
+
kernel route of dmipy-sim's phantom (RPH.md 6): per voxel and measurement
|
| 8 |
+
|
| 9 |
+
S = | f_wm m0_wm FOD . C_wm + f_gm m0_gm E_gm + f_csf m0_csf E_csf |
|
| 10 |
+
|
| 11 |
+
where ``C_wm`` is the WM pack's pose response contracted to the FOD's harmonics
|
| 12 |
+
(:meth:`dmipy_sim.replay.ReplayPack.pose_responses` at ``keep=(8, 0)`` through :func:`dmipy_sim.replay.so3.axis_density_coeffs`),
|
| 13 |
+
``E_gm`` the GM pack's response to an isotropic orientation distribution, ``E_csf`` free water in closed form
|
| 14 |
+
(:class:`dmipy_sim.phantom.FreeWater`), each at the run's tissue (T2 / T1 per pool at the echo, the WM walls' surface
|
| 15 |
+
relaxivity, the myelin sheath's susceptibility at the scanner's field and its direction), and ``m0`` the proton
|
| 16 |
+
density per tissue. The pose responses (:meth:`Brain.prepare`: seconds on the CPU) are cached in the page's process per
|
| 17 |
+
pack, protocol, tissue and field; a run looks them up on the page and computes the missing ones inside the GPU call,
|
| 18 |
+
so the call is entered as soon as the request arrives. The contraction over voxels x
|
| 19 |
+
measurements x 45 runs in torch on the device. It is exactly what ``Phantom.compose(...).replay(seq, pose=...)``
|
| 20 |
+
computes, which the tests check. The acquisition is in the image frame; the field's direction is given in the
|
| 21 |
+
scanner frame and reaches the packs through the specimen's pose (:func:`specimen_pose`).
|
| 22 |
+
"""
|
| 23 |
+
from __future__ import annotations
|
| 24 |
+
|
| 25 |
+
import functools
|
| 26 |
+
import json
|
| 27 |
+
import os
|
| 28 |
+
import time
|
| 29 |
+
from dataclasses import dataclass, replace
|
| 30 |
+
from typing import Optional
|
| 31 |
+
|
| 32 |
+
import numpy as np
|
| 33 |
+
|
| 34 |
+
from .. import pipeline as P
|
| 35 |
+
|
| 36 |
+
ASSET_FILES = ("manifest.json", "fod_wm.npy", "fractions.npy", "mask.npy", "labels.npy", "regions.json", "stop_mask.npy", "mean_b0.npy")
|
| 37 |
+
TISSUES = ("wm", "gm", "csf")
|
| 38 |
+
WM_POOLS = ("intra", "extra", "myelin") # the catalogue's white-matter pools, by the packs' pool names
|
| 39 |
+
M0_KEYS = {"wm": "proton_density_white_matter", "gm": "proton_density_grey_matter", "csf": "proton_density_csf"}
|
| 40 |
+
RELAXATION_KEYS = {"gm": ("T2_grey_matter", "T1_grey_matter"), "csf": ("T2_csf", "T1_csf")}
|
| 41 |
+
SCAN = "scan" # the timing class of the asset's own protocol
|
| 42 |
+
B0_MODES = {"along the bore (z)": P.B0_ALONG_Z, "transverse (x): 90° from the bore, as in a biplanar magnet like the Swoop": P.B0_TRANSVERSE}
|
| 43 |
+
FREE_B0 = "free (polar and azimuth angles below)"
|
| 44 |
+
LMAX = 8
|
| 45 |
+
N_COEF = 45
|
| 46 |
+
REACH_MM = 250.0 # the longest streamline the tracker must be able to reach
|
| 47 |
+
PROFILE_ANGLES = np.linspace(0.0, 90.0, 19) # degrees between the gradient and a fibre, for the response plot
|
| 48 |
+
C00 = 1.0 / (2.0 * np.sqrt(np.pi)) # the l = 0 coefficient of a unit-integral density
|
| 49 |
+
#: why a magnet with its own gradient (a field law: the Swoop) is not on the brain's scanner menu, as the page says it
|
| 50 |
+
FIELD_LAW_REFUSAL = ("Its own gradient (the permanent magnet's field law, 1.4 mT/m at 8 cm) is on through every pulse and dead "
|
| 51 |
+
"time, so every voxel plays a two-direction waveform of its own. dmipy-sim's closed form expands that "
|
| 52 |
+
"waveform exactly; the cost keeps it off this menu. Binned to the menu's 1 % of b, this head needs 9,752 "
|
| 53 |
+
"encoding classes for the scan's protocol (665 at 3 %), and one class's pose responses take 2-3 minutes "
|
| 54 |
+
"(WM 104-166 s, GM 4-21 s at 485 measurements on a GH200), so one protocol at one tissue and field is about "
|
| 55 |
+
"two weeks of one device. The DiSCo Space plays the Swoop exactly.")
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
# ---- the asset ---------------------------------------------------------------------------------------------------------
|
| 59 |
+
|
| 60 |
+
def asset_location(cfg):
|
| 61 |
+
"""Where the asset is: ``DISCO_BRAIN_ASSET`` in the environment (a local directory), else the configuration's
|
| 62 |
+
``[asset]``: ``local`` (a directory) or ``hub`` + ``revision`` (a public dataset downloaded into the Hub cache)."""
|
| 63 |
+
env = os.environ.get("DISCO_BRAIN_ASSET")
|
| 64 |
+
if env:
|
| 65 |
+
return env
|
| 66 |
+
a = cfg["asset"]
|
| 67 |
+
return a["local"] if a.get("local") else f"hf://{a['hub']}@{a['revision']}"
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def asset_dir(where):
|
| 71 |
+
"""The asset's local directory: ``where`` itself, or the dataset ``hf://repo@revision`` downloaded (once per
|
| 72 |
+
container: the Hub cache holds it)."""
|
| 73 |
+
if not where.startswith("hf://"):
|
| 74 |
+
return where
|
| 75 |
+
from huggingface_hub import snapshot_download
|
| 76 |
+
repo, _, rev = where[len("hf://"):].partition("@")
|
| 77 |
+
return snapshot_download(repo, repo_type="dataset", revision=rev or None, allow_patterns=list(ASSET_FILES))
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
@functools.lru_cache(maxsize=4)
|
| 81 |
+
def manifest(where):
|
| 82 |
+
"""The asset's ``manifest.json`` (downloaded alone for a Hub asset)."""
|
| 83 |
+
if where.startswith("hf://"):
|
| 84 |
+
from huggingface_hub import hf_hub_download
|
| 85 |
+
repo, _, rev = where[len("hf://"):].partition("@")
|
| 86 |
+
path = hf_hub_download(repo, "manifest.json", repo_type="dataset", revision=rev or None)
|
| 87 |
+
else:
|
| 88 |
+
path = os.path.join(where, "manifest.json")
|
| 89 |
+
with open(path) as f:
|
| 90 |
+
return json.load(f)
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
@functools.lru_cache(maxsize=16)
|
| 94 |
+
def declared_segments(uri):
|
| 95 |
+
"""The segment table ``{n, n_t, T}`` (RPK.md 4.3) a pack declares, read without its arrays: a Hub pack's
|
| 96 |
+
record in its dataset's ``manifest.json`` (``hf://owner/name/path``), a local pack's header."""
|
| 97 |
+
from dmipy_sim.replay.publish import MANIFEST, header_of, is_hub_uri, parse_uri
|
| 98 |
+
if is_hub_uri(uri):
|
| 99 |
+
from huggingface_hub import hf_hub_download
|
| 100 |
+
repo, path = parse_uri(uri)
|
| 101 |
+
with open(hf_hub_download(repo, MANIFEST, repo_type="dataset")) as f:
|
| 102 |
+
rows = [r for r in json.load(f).get("packs") or [] if r.get("path") == path]
|
| 103 |
+
if not rows:
|
| 104 |
+
raise ValueError(f"{uri}: the dataset {repo} holds no record of this pack (its manifest.json)")
|
| 105 |
+
seg = rows[0].get("segments")
|
| 106 |
+
else:
|
| 107 |
+
seg = header_of(uri)["walk_params"].get("segments")
|
| 108 |
+
if not seg:
|
| 109 |
+
raise ValueError(f"{uri}: no declared segment table (walk_params.segments, RPK.md 4.3) in its "
|
| 110 |
+
f"{'record' if is_hub_uri(uri) else 'header'}")
|
| 111 |
+
return dict(n=int(seg["n"]), n_t=int(seg["n_t"]), T=float(seg["T"]))
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def image_rotation(man):
|
| 115 |
+
"""``R`` (image -> scanner) of the asset's grid (:meth:`dmipy_sim.phantom.Grid.from_oblique_affine`)."""
|
| 116 |
+
from dmipy_sim.phantom import Grid
|
| 117 |
+
_, R = Grid.from_oblique_affine(np.asarray(man["grid"]["affine"], np.float64), tuple(man["grid"]["shape"]))
|
| 118 |
+
return np.asarray(R, np.float64)
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def read_regions(path):
|
| 122 |
+
"""``(regions, groups)`` from ``regions.json``: the regions ``[{id, name, hemisphere, lobe}]`` (a list, or the
|
| 123 |
+
``regions`` of an object) sorted by id, and the lobar groups ``((name, (id, ...)), ...)`` made from each region's
|
| 124 |
+
hemisphere and lobe in order of first appearance; an object's ``groups`` must agree with them."""
|
| 125 |
+
with open(path) as f:
|
| 126 |
+
doc = json.load(f)
|
| 127 |
+
regions = sorted(doc["regions"] if isinstance(doc, dict) else doc, key=lambda r: int(r["id"]))
|
| 128 |
+
groups = {}
|
| 129 |
+
for r in regions:
|
| 130 |
+
groups.setdefault(f"{str(r['hemisphere'])[0].upper()} {r['lobe']}", []).append(int(r["id"]))
|
| 131 |
+
groups = tuple((name, tuple(ids)) for name, ids in groups.items())
|
| 132 |
+
if isinstance(doc, dict) and doc.get("groups"):
|
| 133 |
+
stated = {tuple(sorted(int(i) for i in g["ids"])) for g in doc["groups"]}
|
| 134 |
+
if stated != {tuple(sorted(ids)) for _, ids in groups}:
|
| 135 |
+
raise ValueError("regions.json: its groups are not the regions' hemisphere x lobe")
|
| 136 |
+
return regions, groups
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
@dataclass
|
| 140 |
+
class Asset:
|
| 141 |
+
"""The asset, cropped to the brain's bounding box (one voxel of margin): ``fod`` ``(X, Y, Z, 45)`` in the image
|
| 142 |
+
frame, ``fractions`` ``(X, Y, Z, 3)`` WM / GM / CSF (a voxel whose fractions sum above one is divided by its sum, a
|
| 143 |
+
WM fraction without an FOD is not replayed; ``notes`` counts both), ``mask``, ``labels``, ``stop``, ``b0``, ``affine`` the
|
| 144 |
+
cropped grid's voxel -> scanner mm, ``R`` image -> scanner, ``regions`` / ``groups`` from ``regions.json``,
|
| 145 |
+
``manifest``, ``crop`` the slices into the full grid."""
|
| 146 |
+
manifest: dict
|
| 147 |
+
fod: np.ndarray
|
| 148 |
+
fractions: np.ndarray
|
| 149 |
+
mask: np.ndarray
|
| 150 |
+
labels: np.ndarray
|
| 151 |
+
stop: np.ndarray
|
| 152 |
+
b0: np.ndarray
|
| 153 |
+
affine: np.ndarray
|
| 154 |
+
R: np.ndarray
|
| 155 |
+
regions: list
|
| 156 |
+
groups: tuple
|
| 157 |
+
crop: tuple
|
| 158 |
+
notes: tuple = ()
|
| 159 |
+
|
| 160 |
+
@classmethod
|
| 161 |
+
def load(cls, where):
|
| 162 |
+
d = asset_dir(where)
|
| 163 |
+
missing = [f for f in ASSET_FILES if not os.path.exists(os.path.join(d, f))]
|
| 164 |
+
if missing:
|
| 165 |
+
raise FileNotFoundError(f"the brain asset at {where} lacks {missing}")
|
| 166 |
+
man = manifest(where)
|
| 167 |
+
shape = tuple(man["grid"]["shape"])
|
| 168 |
+
fod = np.load(os.path.join(d, "fod_wm.npy"), mmap_mode="r")
|
| 169 |
+
mask = np.load(os.path.join(d, "mask.npy")).astype(bool)
|
| 170 |
+
if fod.shape != shape + (N_COEF,) or mask.shape != shape:
|
| 171 |
+
raise ValueError(f"the asset's FOD {fod.shape} and mask {mask.shape} are not on its grid {shape} with {N_COEF} coefficients")
|
| 172 |
+
from dmipy_sim.phantom.orientation import SH_BASES
|
| 173 |
+
basis = str(man["fod"]["basis"]).split()[0]
|
| 174 |
+
if SH_BASES.get(basis) != ("tournier07", False) or int(man["fod"]["lmax"]) != LMAX or man["fod"]["frame"] != "image":
|
| 175 |
+
raise ValueError(f"the asset's FOD is {man['fod']}: this source reads dmipy-sim's required basis (a basis whose "
|
| 176 |
+
f"name, the first word, dmipy_sim.phantom.orientation.SH_BASES maps to orthonormal tournier07: "
|
| 177 |
+
f"tournier07, mrtrix3, dmipy-fit) at lmax {LMAX} in the image frame")
|
| 178 |
+
if list(man["fractions"]) != list(TISSUES):
|
| 179 |
+
raise ValueError(f"the asset's fractions are {man['fractions']}, this source reads {list(TISSUES)}")
|
| 180 |
+
ijk = np.argwhere(mask)
|
| 181 |
+
lo = np.maximum(ijk.min(0) - 1, 0); hi = np.minimum(ijk.max(0) + 2, shape)
|
| 182 |
+
crop = tuple(slice(int(a), int(b)) for a, b in zip(lo, hi))
|
| 183 |
+
affine = np.asarray(man["grid"]["affine"], np.float64).copy()
|
| 184 |
+
affine[:3, 3] = affine[:3, :3] @ lo + affine[:3, 3]
|
| 185 |
+
regions, groups = read_regions(os.path.join(d, "regions.json"))
|
| 186 |
+
labels = np.load(os.path.join(d, "labels.npy"))[crop].astype(np.int32)
|
| 187 |
+
n = int(man["parcellation"]["n_regions"])
|
| 188 |
+
if [int(r["id"]) for r in regions] != list(range(1, n + 1)) or labels.min() < 0 or labels.max() > n:
|
| 189 |
+
raise ValueError(f"the asset's regions are not 1..{n} (regions.json ids {[r['id'] for r in regions][:5]}..., labels up to {labels.max()})")
|
| 190 |
+
m = mask[crop]
|
| 191 |
+
fodc = np.asarray(fod[crop], np.float32) * m[..., None]
|
| 192 |
+
fr = np.clip(np.load(os.path.join(d, "fractions.npy"))[crop].astype(np.float32), 0.0, None) * m[..., None]
|
| 193 |
+
notes = []
|
| 194 |
+
no_fod = (fr[..., 0] > 0) & ~(fodc[..., 0] > 0)
|
| 195 |
+
if no_fod.any(): # a WM fraction needs an orientation to compose with
|
| 196 |
+
notes.append(("voxels with a WM fraction and no FOD (their WM fraction is not replayed)",
|
| 197 |
+
f"{int(no_fod.sum()):,}, WM fraction up to {float(fr[..., 0][no_fod].max()):.3f}"))
|
| 198 |
+
fr[..., 0] = np.where(no_fod, 0.0, fr[..., 0])
|
| 199 |
+
total = fr.sum(-1, keepdims=True)
|
| 200 |
+
over = total[..., 0] > 1.0
|
| 201 |
+
if over.any(): # shares of a voxel's volume: float16 rounding, an unconstrained fit
|
| 202 |
+
notes.append(("voxels whose fractions sum above one (divided by their sum)", f"{int(over.sum()):,}, largest sum {float(total.max()):.3f}"))
|
| 203 |
+
fr = fr / np.maximum(total, 1.0)
|
| 204 |
+
return cls(man, fodc, fr, m, labels, np.load(os.path.join(d, "stop_mask.npy"))[crop].astype(bool) & m,
|
| 205 |
+
np.load(os.path.join(d, "mean_b0.npy"))[crop].astype(np.float32), affine, image_rotation(man), regions, groups, crop, tuple(notes))
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
def scan_protocol(man, *, name):
|
| 209 |
+
"""The asset's own protocol: its rows' b-values (s/mm^2) and directions turned into the image frame (the frame
|
| 210 |
+
of the FOD the replay composes), one shell per b rounded to 50 s/mm^2, on the timing class :data:`SCAN`."""
|
| 211 |
+
b = np.asarray(man["protocol"]["bvals_s_mm2"], np.float64)
|
| 212 |
+
g = np.asarray(man["protocol"]["bvecs"], np.float64)
|
| 213 |
+
if g.shape == (3, len(b)):
|
| 214 |
+
g = g.T
|
| 215 |
+
frame = man["protocol"]["bvec_frame"]
|
| 216 |
+
if frame not in ("image", "scanner"):
|
| 217 |
+
raise ValueError(f"bvec_frame is 'image' or 'scanner', got {frame!r}")
|
| 218 |
+
if frame == "scanner":
|
| 219 |
+
g = g @ image_rotation(man) # R.T g per row
|
| 220 |
+
group = np.round(b / 50.0).astype(int)
|
| 221 |
+
return P.protocol_from_rows(b, g, group, lambda k, rows: P.Shell(SCAN, float(np.round(b[rows].mean())), int(len(rows))), name=name)[0]
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
# ---- the physics --------------------------------------------------------------------------------------------------------
|
| 225 |
+
|
| 226 |
+
@dataclass(frozen=True)
|
| 227 |
+
class BrainPhysics:
|
| 228 |
+
"""The tissue and scanner a brain replay is evaluated at: ``field_T`` (the scanner's field, T; the catalogue's
|
| 229 |
+
relaxation is cited at the nearest of 1.5 / 3 / 7 T), ``b0_direction`` (its unit direction in the scanner frame),
|
| 230 |
+
``T2`` / ``T1`` as ``{"wm": {pool: s}, "gm": s, "csf": s}``, ``rho2`` the WM walls' surface relaxivity (m/s),
|
| 231 |
+
``chi_iso`` / ``chi_aniso`` the myelin sheath's susceptibility (SI, the WM pack's field source), ``D_csf`` free
|
| 232 |
+
water's diffusivity (m^2/s), ``m0`` the proton density per tissue relative to CSF, ``wm_pack`` / ``gm_pack`` the
|
| 233 |
+
packs by their configuration label; ``relaxation``, ``contact`` and ``field`` switch the three tiers; ``scanner``
|
| 234 |
+
the machine (a key of dmipy-sim's catalogue): its slew rate shapes every pulse's ramps, its field and direction are
|
| 235 |
+
the physics', and every voxel is played the gradient it delivers there with the head centre at isocentre
|
| 236 |
+
(:meth:`Brain.prepare`); None is the ideal scanner, ideal pulses with vertical ramps. All off is bare diffusion at
|
| 237 |
+
the same proton densities and packs."""
|
| 238 |
+
field_T: float
|
| 239 |
+
T2: dict
|
| 240 |
+
T1: dict
|
| 241 |
+
rho2: float
|
| 242 |
+
chi_iso: float
|
| 243 |
+
chi_aniso: float
|
| 244 |
+
D_csf: float
|
| 245 |
+
m0: dict
|
| 246 |
+
wm_pack: str
|
| 247 |
+
gm_pack: str
|
| 248 |
+
b0_direction: tuple = P.B0_ALONG_Z
|
| 249 |
+
relaxation: bool = True
|
| 250 |
+
contact: bool = True
|
| 251 |
+
field: bool = True
|
| 252 |
+
scanner: Optional[str] = None
|
| 253 |
+
|
| 254 |
+
def __post_init__(self):
|
| 255 |
+
if self.scanner is not None:
|
| 256 |
+
L = P.limits(self.scanner)
|
| 257 |
+
if abs(float(L.field_T) - float(self.field_T)) > 1e-9:
|
| 258 |
+
raise ValueError(f"{self.scanner} is a {L.field_T:g} T magnet; the physics says {self.field_T:g} T")
|
| 259 |
+
if L.has_field_law:
|
| 260 |
+
raise ValueError(f"{self.scanner} is not on the brain's scanner menu. {FIELD_LAW_REFUSAL}")
|
| 261 |
+
if not (0 < self.field_T < 30):
|
| 262 |
+
raise ValueError(f"the field is in tesla, got {self.field_T}")
|
| 263 |
+
if set(self.m0) != set(TISSUES) or any(float(v) < 0 for v in self.m0.values()):
|
| 264 |
+
raise ValueError(f"m0 is a non-negative proton density per tissue {TISSUES}, got {self.m0}")
|
| 265 |
+
if self.rho2 < 0:
|
| 266 |
+
raise ValueError("the surface relaxivity is non-negative")
|
| 267 |
+
u = np.asarray(self.b0_direction, np.float64)
|
| 268 |
+
if u.shape != (3,) or not np.isclose(np.linalg.norm(u), 1.0, atol=1e-6):
|
| 269 |
+
raise ValueError("b0_direction is a unit vector")
|
| 270 |
+
|
| 271 |
+
@property
|
| 272 |
+
def bare(self):
|
| 273 |
+
return not (self.relaxation or self.contact or self.field)
|
| 274 |
+
|
| 275 |
+
@property
|
| 276 |
+
def scanner_field(self):
|
| 277 |
+
"""The replay's ``scanner=``: the field in tesla with the field tier, else None (relaxation at a field is
|
| 278 |
+
already in T2 and T1)."""
|
| 279 |
+
return self.field_T if self.field else None
|
| 280 |
+
|
| 281 |
+
@property
|
| 282 |
+
def slew_rate(self):
|
| 283 |
+
"""The slew rate every pulse's ramps are played at (T/m/s): the catalogue class's ``slew_max``, infinite
|
| 284 |
+
(vertical ramps) on the ideal scanner."""
|
| 285 |
+
if self.scanner is None:
|
| 286 |
+
return np.inf
|
| 287 |
+
from dmipy_sim.acquisition.scanners import ScannerLimits
|
| 288 |
+
return float(ScannerLimits.of(self.scanner).slew_max)
|
| 289 |
+
|
| 290 |
+
def label(self):
|
| 291 |
+
if self.bare:
|
| 292 |
+
return "bare diffusion" + (f" on the {self.scanner}" if self.scanner else "")
|
| 293 |
+
tiers = "+".join(t for t in ("relaxation", "contact", "field") if getattr(self, t))
|
| 294 |
+
u = self.b0_direction
|
| 295 |
+
grad = f", on the {self.scanner} (its slew {self.slew_rate:g} T/m/s and every catalogued term, head centre at isocentre)" if self.scanner else ""
|
| 296 |
+
return f"{self.field_T:g} T along ({u[0]:.2f}, {u[1]:.2f}, {u[2]:.2f}), tiers {tiers}{grad}"
|
| 297 |
+
|
| 298 |
+
def tissues(self, wm_pack, gm_pack):
|
| 299 |
+
"""``(wm, gm, csf)`` :class:`dmipy_sim.spec.Tissue` for the packs ``wm_pack`` and ``gm_pack``: the WM pack's
|
| 300 |
+
pools with their T2 / T1, the walls' rho2 and, on a WM pack whose spec declares its susceptibility field
|
| 301 |
+
present (a magnetic myelin pool), the sheath's susceptibility; the GM pack's pools at grey matter's T2 / T1;
|
| 302 |
+
free water's D, T2 and T1. A tier off leaves its values out (``None`` for a pack with nothing on: its bare
|
| 303 |
+
diffusion). A WM pack whose field is absent has no sheath, so its tissue carries no susceptibility and its
|
| 304 |
+
field tier is zero at any field."""
|
| 305 |
+
from dmipy_sim.spec import Tissue
|
| 306 |
+
wm_pools, gm_pools = Brain.pools(wm_pack), Brain.pools(gm_pack)
|
| 307 |
+
relax, contact = self.relaxation, self.contact
|
| 308 |
+
field = self.field and wm_pack.susceptibility_field == "present"
|
| 309 |
+
wm = Tissue(T2={p: self.T2["wm"][p] for p in wm_pools} if relax else None, T1={p: self.T1["wm"][p] for p in wm_pools} if relax else None,
|
| 310 |
+
rho2=self.rho2 if contact else None, chi_iso=self.chi_iso if field else None,
|
| 311 |
+
chi_aniso=self.chi_aniso if field else 0.0) if (relax or contact or field) else None
|
| 312 |
+
gm = Tissue(T2={p: self.T2["gm"] for p in gm_pools}, T1={p: self.T1["gm"] for p in gm_pools}) if relax else None
|
| 313 |
+
csf = Tissue(D=self.D_csf, T2=self.T2["csf"] if relax else None, T1=self.T1["csf"] if relax else None)
|
| 314 |
+
return wm, gm, csf
|
| 315 |
+
|
| 316 |
+
|
| 317 |
+
def catalogue(field_T):
|
| 318 |
+
"""The catalogue at the cited field nearest ``field_T`` (in log distance): the white matter's pools
|
| 319 |
+
(:func:`space.pipeline.catalogue`), grey matter's and CSF's T2 and T1, free water's diffusivity, the proton
|
| 320 |
+
densities, all from ``dmipy_sim.substrate.biophysical_constants`` by key; ``catalogue_field`` says which field."""
|
| 321 |
+
import warnings
|
| 322 |
+
from dmipy_sim.substrate.biophysical_constants import get_value
|
| 323 |
+
wm = P.catalogue(field_T, WM_POOLS)
|
| 324 |
+
near = wm["catalogue_field"]
|
| 325 |
+
with warnings.catch_warnings():
|
| 326 |
+
warnings.simplefilter("ignore")
|
| 327 |
+
T2 = {"wm": wm["T2"], **{t: float(get_value(k[0], near, allow_nearest=True)) for t, k in RELAXATION_KEYS.items()}}
|
| 328 |
+
T1 = {"wm": wm["T1"], **{t: float(get_value(k[1], near, allow_nearest=True)) for t, k in RELAXATION_KEYS.items()}}
|
| 329 |
+
return dict(catalogue_field=near, T2=T2, T1=T1, rho2=wm["rho2"], chi_iso=wm["chi_iso"], chi_aniso=wm["chi_aniso"],
|
| 330 |
+
D_csf=float(get_value("D_csf")), m0={t: float(get_value(k)) for t, k in M0_KEYS.items()})
|
| 331 |
+
|
| 332 |
+
|
| 333 |
+
def specimen_pose(R, b0_direction):
|
| 334 |
+
"""The specimen's pose in the bore for a replay whose acquisition is in the image frame: ``W R`` with ``R`` the
|
| 335 |
+
image -> scanner rotation and ``W`` the rotation taking the field's scanner-frame direction onto z (the bore's
|
| 336 |
+
field axis), so the packs see the field at ``R.T b0_direction`` in the image frame. A sequence composed at this
|
| 337 |
+
pose carries the gradients ``pose @ g`` (:meth:`Brain.sequence`)."""
|
| 338 |
+
from dmipy_sim.replay.so3 import rotation_of
|
| 339 |
+
return rotation_of(np.asarray(b0_direction, np.float64)).T @ np.asarray(R, np.float64)
|
| 340 |
+
|
| 341 |
+
|
| 342 |
+
@dataclass
|
| 343 |
+
class Kernels:
|
| 344 |
+
"""A replay's pose responses (:meth:`Brain.prepare`): per encoding class and measurement, the WM response contracted
|
| 345 |
+
to the FOD's harmonics ``wm`` ``(n_classes, n_meas, 45)`` complex, the GM response to an isotropic distribution ``gm``
|
| 346 |
+
and free water's ``csf`` ``(n_classes, n_meas)`` complex (a class fills the rows of its timing class), ``classes``
|
| 347 |
+
``(n_voxels, n_timing)`` each voxel's class per timing class and ``timing_rows`` the measurement rows of each timing
|
| 348 |
+
class (the ideal scanner: one class per timing class, every voxel in it), the proton densities ``m0``, the packs'
|
| 349 |
+
certified floors, the seconds it took;
|
| 350 |
+
``profile`` the true response curves at the run's shells (``b``, ``wm`` ``(n_shells, n_angles)``, ``gm``, ``csf``
|
| 351 |
+
``(n_shells,)``, each over its b = 0 value), ``b0`` the b = 0 signal per tissue under each tier alone, and
|
| 352 |
+
``stages`` the seconds of each stage of :meth:`Brain.prepare` (``load_wm``, ``load_gm``, ``pose_wm``, ``pose_gm``,
|
| 353 |
+
``weights``)."""
|
| 354 |
+
wm: np.ndarray
|
| 355 |
+
gm: np.ndarray
|
| 356 |
+
csf: np.ndarray
|
| 357 |
+
classes: np.ndarray
|
| 358 |
+
timing_rows: tuple
|
| 359 |
+
m0: dict
|
| 360 |
+
floors: dict
|
| 361 |
+
seconds: float
|
| 362 |
+
profile: Optional[dict] = None
|
| 363 |
+
b0: Optional[dict] = None
|
| 364 |
+
stages: Optional[dict] = None
|
| 365 |
+
|
| 366 |
+
|
| 367 |
+
# ---- the source ---------------------------------------------------------------------------------------------------------
|
| 368 |
+
|
| 369 |
+
class Brain(P.Source):
|
| 370 |
+
"""A brain from its asset: the regions of its parcellation, the tracker seeded in its white matter and stopped
|
| 371 |
+
where the white matter and the regions end, the connectome scored against the connectome of the asset's own FOD
|
| 372 |
+
tracked with the same settings, seeds and key."""
|
| 373 |
+
plays_slew = True
|
| 374 |
+
TIERS = ("relaxation", "contact", "field")
|
| 375 |
+
STAGES = ("replay", "noise", "csd", "track", "truth", "score")
|
| 376 |
+
|
| 377 |
+
def __init__(self, cfg, *, asset=None):
|
| 378 |
+
super().__init__(cfg)
|
| 379 |
+
self.where = asset or asset_location(cfg)
|
| 380 |
+
self.asset = a = Asset.load(self.where)
|
| 381 |
+
self.shapes = self.shape_table(cfg, self.where)
|
| 382 |
+
self.affine = a.affine
|
| 383 |
+
self.mask = a.mask
|
| 384 |
+
self.regions = P.Regions(a.labels, a.affine, tuple(r["name"] for r in a.regions), a.groups)
|
| 385 |
+
self.vox = np.argwhere(a.mask) # the replayed voxels
|
| 386 |
+
f = a.fractions[a.mask].astype(np.float64)
|
| 387 |
+
c0 = a.fod[a.mask][:, 0].astype(np.float64)
|
| 388 |
+
unit = np.where((c0 > 0)[:, None], a.fod[a.mask] * (C00 / np.where(c0 > 0, c0, 1.0))[:, None], 0.0)
|
| 389 |
+
self.fod_unit = unit.astype(np.float32) # every voxel's FOD as a unit-integral density
|
| 390 |
+
self.f = f.astype(np.float32)
|
| 391 |
+
self.packs = {}
|
| 392 |
+
self._reference = {}
|
| 393 |
+
self._kernels = {} # prepare()'s results, by response_key
|
| 394 |
+
self._compiled = set() # the _band()s prepare() ran in this process
|
| 395 |
+
self._encodings = {} # encoding()'s results, by machine and rows
|
| 396 |
+
|
| 397 |
+
@classmethod
|
| 398 |
+
def load(cls, cfg, *, local=None):
|
| 399 |
+
return cls(cfg, asset=local)
|
| 400 |
+
|
| 401 |
+
def warm_entries(self):
|
| 402 |
+
"""The ``(meas, physics)`` a run can ask for without a custom acquisition, one per response key, in the order
|
| 403 |
+
the warm-up computes them: every preset at the panel's defaults with its ladder rungs, then B of every knob
|
| 404 |
+
on the default protocol, the field presets last in ascending field along both B0 directions (the band to
|
| 405 |
+
compile grows with the field: 7 T and 11.7 T cost minutes each, so they follow everything cheaper, the
|
| 406 |
+
pulse-timing classes among it), with the scan's protocol on each machine of the scanner menu that can play it,
|
| 407 |
+
at the system's field, with its slew and its delivered gradient, before the field presets. A knob that leaves the response unchanged (noise, M0, the default pack
|
| 408 |
+
or direction) repeats no entry; an entry the packs cannot play is left out (a run asking for it is refused
|
| 409 |
+
by name)."""
|
| 410 |
+
cfg = self.cfg
|
| 411 |
+
panel = self.panel(cfg)
|
| 412 |
+
values = {c.name: c.value for row in panel.rows for c in row if c.name in panel.fields}
|
| 413 |
+
physics = self.physics_from(cfg, values)
|
| 414 |
+
entries = []
|
| 415 |
+
for name in self.presets(cfg):
|
| 416 |
+
prot = self.protocol(cfg, name)
|
| 417 |
+
entries += [(prot, physics)] + [(prot, rung) for _, rung in self.ladder_steps(physics)]
|
| 418 |
+
scan = self.protocol(cfg, self.presets(cfg)[0])
|
| 419 |
+
knobs = [c for c in self.knobs(cfg).values() if c is not None]
|
| 420 |
+
fields = sorted((c for c in knobs if c[0] == "field"), key=lambda c: c[1])
|
| 421 |
+
def knob_entries(changes):
|
| 422 |
+
out = []
|
| 423 |
+
for change in changes:
|
| 424 |
+
prot, _, _, v = self.apply_knob(cfg, change, scan, True, None, values)
|
| 425 |
+
modes = list(B0_MODES) if change[0] == "field" else [v["b0_mode"]]
|
| 426 |
+
out += [(prot, self.physics_from(cfg, {**v, "b0_mode": mode})) for mode in modes]
|
| 427 |
+
return out
|
| 428 |
+
entries += knob_entries([c for c in knobs if c[0] != "field"])
|
| 429 |
+
for key in P.machines(cfg).values(): # the machines that can play the scan, at their field
|
| 430 |
+
if not all(r[-1] for r in P.playable(scan, self.shapes, key)):
|
| 431 |
+
continue
|
| 432 |
+
_, _, _, v = self.apply_knob(cfg, ("field", float(P.limits(key).field_T)), scan, True, None, values)
|
| 433 |
+
entries.append((scan, self.physics_from(cfg, v, scanner=key)))
|
| 434 |
+
entries += knob_entries(fields)
|
| 435 |
+
out = []; keys = set()
|
| 436 |
+
for prot, ph in entries:
|
| 437 |
+
try:
|
| 438 |
+
meas = self.validate(prot, ph)
|
| 439 |
+
except ValueError:
|
| 440 |
+
continue
|
| 441 |
+
key = self.response_key(meas, ph)
|
| 442 |
+
if key not in keys:
|
| 443 |
+
keys.add(key)
|
| 444 |
+
out.append((meas, ph))
|
| 445 |
+
return out
|
| 446 |
+
|
| 447 |
+
def warm_in_background(self):
|
| 448 |
+
""":meth:`warm` in a process of its own while this one serves: the entries' responses arrive one by one and
|
| 449 |
+
are kept here (:meth:`keep`), so a run finds the cache filling from the first entry on and pays, inside its
|
| 450 |
+
reservation, only for an entry not yet there. A spawned process, not a thread: the GPU worker is a fork of
|
| 451 |
+
this process, and a fork taken while a thread runs JAX can deadlock the child; the spawned process compiles
|
| 452 |
+
its own bands, so an entry of a band this process never compiled is priced cold (:meth:`responses`) until a
|
| 453 |
+
run computes it here. Returns the thread that drains the results; the packs are loaded here first (the
|
| 454 |
+
windows the entries reach), so a run arriving before the warm-up ends has them. Both sides print their
|
| 455 |
+
progress to stdout (the Space's run log): the process its start (CPUs, memory limit), each entry with its
|
| 456 |
+
seconds and RSS; this side each entry kept and the process's exit code when it ends, with or without its
|
| 457 |
+
end marker (a process killed by the container's memory limit sends none)."""
|
| 458 |
+
import multiprocessing as mp
|
| 459 |
+
import threading
|
| 460 |
+
from queue import Empty
|
| 461 |
+
entries = self.warm_entries()
|
| 462 |
+
for meas, ph in entries:
|
| 463 |
+
for tissue, label in (("wm", ph.wm_pack), ("gm", ph.gm_pack)):
|
| 464 |
+
self.pack(tissue, label, self.windows_needed(tissue, label, meas))
|
| 465 |
+
ctx = mp.get_context("spawn")
|
| 466 |
+
queue = ctx.Queue()
|
| 467 |
+
proc = ctx.Process(target=_warm_worker, args=(self.cfg, self.where, entries, queue), daemon=True, name="brain-warm")
|
| 468 |
+
proc.start()
|
| 469 |
+
|
| 470 |
+
def drain():
|
| 471 |
+
n = 0
|
| 472 |
+
while True:
|
| 473 |
+
try:
|
| 474 |
+
item = queue.get(timeout=30)
|
| 475 |
+
except Empty:
|
| 476 |
+
if proc.is_alive():
|
| 477 |
+
continue
|
| 478 |
+
print(f"warm-up: the process ended with exit code {proc.exitcode} after {n} of {len(entries)} entries, "
|
| 479 |
+
"without its end marker", flush=True)
|
| 480 |
+
return
|
| 481 |
+
if item is None:
|
| 482 |
+
break
|
| 483 |
+
key, kernels = item
|
| 484 |
+
self.keep({key: kernels})
|
| 485 |
+
n += 1
|
| 486 |
+
print(f"warm-up: the page keeps entry {n}/{len(entries)}", flush=True)
|
| 487 |
+
proc.join()
|
| 488 |
+
print(f"warm-up: the process ended with exit code {proc.exitcode} after {n} of {len(entries)} entries", flush=True)
|
| 489 |
+
|
| 490 |
+
t = threading.Thread(target=drain, daemon=True, name="brain-warm-drain")
|
| 491 |
+
t.start()
|
| 492 |
+
return t
|
| 493 |
+
|
| 494 |
+
# ---- the packs ----
|
| 495 |
+
@classmethod
|
| 496 |
+
def refused_machines(cls, cfg):
|
| 497 |
+
"""``{label: reason}`` for ``[scanners] refused`` of the configuration: each a catalogued magnet with its own
|
| 498 |
+
gradient, kept off the menu for :data:`FIELD_LAW_REFUSAL`."""
|
| 499 |
+
out = {}
|
| 500 |
+
for m in (cfg.get("scanners") or {}).get("refused", []):
|
| 501 |
+
if not P.limits(m["key"]).has_field_law:
|
| 502 |
+
raise ValueError(f"[scanners] refused names {m['key']!r}, which has no field law: the brain plays it, so it belongs on the menu")
|
| 503 |
+
out[m["label"]] = FIELD_LAW_REFUSAL
|
| 504 |
+
return out
|
| 505 |
+
|
| 506 |
+
@classmethod
|
| 507 |
+
def pack_menu(cls, cfg, tissue):
|
| 508 |
+
"""The configuration's packs for ``tissue`` (``wm`` / ``gm``): ``{label: uri}`` in the menu's order."""
|
| 509 |
+
return {p["label"]: p["uri"] for p in cfg["packs"][tissue]}
|
| 510 |
+
|
| 511 |
+
def segments(self, tissue, label):
|
| 512 |
+
"""The declared segment table ``{n, n_t, T}`` of the pack ``label`` of ``tissue``'s menu
|
| 513 |
+
(:func:`declared_segments`: read without the pack's arrays)."""
|
| 514 |
+
menu = self.pack_menu(self.cfg, tissue)
|
| 515 |
+
if label not in menu:
|
| 516 |
+
raise ValueError(f"no {tissue.upper()} pack {label!r}; the menu is {list(menu)}")
|
| 517 |
+
return declared_segments(menu[label])
|
| 518 |
+
|
| 519 |
+
def windows_reached(self, segments, meas):
|
| 520 |
+
"""``{class: k}``: per timing class of ``meas``, the number of the pack's windows its acquisition reaches.
|
| 521 |
+
``segments`` is a declared table ``{n, n_t, T}`` (:func:`declared_segments`) or a pack's meta (its
|
| 522 |
+
``walk_params.segments``). The acquisition lasts ``T_acq = (G.shape[1] - 1) dt`` of the class's sequence,
|
| 523 |
+
as :meth:`dmipy_sim.replay.ReplayPack._compile` reads it, and window ``i`` starts at ``i T``; a window whose
|
| 524 |
+
first save sits at or beyond ``T_acq`` is not reached, so the save at a window's end belongs to that window
|
| 525 |
+
alone. A pack of one window (``n = 1``) is reached as one window whatever the class; ``k``
|
| 526 |
+
above ``n`` is an acquisition beyond the walk (:meth:`windows_needed` refuses it)."""
|
| 527 |
+
seg = (segments.get("walk_params") or {}).get("segments") if "walk_params" in segments else segments
|
| 528 |
+
out = {}
|
| 529 |
+
for name in map(str, np.unique(meas.shape)):
|
| 530 |
+
if int(seg["n"]) <= 1:
|
| 531 |
+
out[name] = 1
|
| 532 |
+
continue
|
| 533 |
+
s = self._b0_sequence(name, np.eye(3))
|
| 534 |
+
T_acq = (np.shape(s.G)[1] - 1) * float(s.dt)
|
| 535 |
+
out[name] = max(1, int(np.ceil(T_acq * (1.0 - 1e-12) / float(seg["T"]))))
|
| 536 |
+
return out
|
| 537 |
+
|
| 538 |
+
def windows_needed(self, tissue, label, meas):
|
| 539 |
+
"""The windows of the pack ``label`` of ``tissue``'s menu the classes of ``meas`` reach (the largest
|
| 540 |
+
:meth:`windows_reached`), refused by name for a class that reaches beyond the windows the pack declares."""
|
| 541 |
+
seg = self.segments(tissue, label)
|
| 542 |
+
reach = self.windows_reached(seg, meas)
|
| 543 |
+
for name, k in reach.items():
|
| 544 |
+
if k > int(seg["n"]):
|
| 545 |
+
raise ValueError(f"the {tissue.upper()} pack {label!r} declares {seg['n']} window(s) of {float(seg['T']) * 1e3:g} ms: "
|
| 546 |
+
f"the class {name!r} (TE {float(self.shapes[name]['TE']) * 1e3:g} ms) reaches window {k - 1}")
|
| 547 |
+
return max(reach.values())
|
| 548 |
+
|
| 549 |
+
@staticmethod
|
| 550 |
+
def saves_spanned(segments, k):
|
| 551 |
+
"""The saves of the first ``k`` windows of a declared table: ``k (n_t - 1) + 1`` (consecutive windows share
|
| 552 |
+
their boundary save; one window is its ``n_t``)."""
|
| 553 |
+
return int(k) * (int(segments["n_t"]) - 1) + 1
|
| 554 |
+
|
| 555 |
+
def pack(self, tissue, label, k):
|
| 556 |
+
"""The pack ``label`` of ``tissue``'s menu holding at least its first ``k`` windows: a Hub URI whose
|
| 557 |
+
declared table has ``n > 1`` loads ``windows=range(k)`` (:class:`dmipy_sim.phantom.PackSubstrate`; the pack
|
| 558 |
+
records them as ``windows_present``); a local path or a one-window pack loads whole. A later request for
|
| 559 |
+
more windows than it holds reloads with the larger range (the library fetches only the new ranges) and
|
| 560 |
+
replaces the cached pack."""
|
| 561 |
+
from dmipy_sim.phantom import PackSubstrate
|
| 562 |
+
from dmipy_sim.replay.publish import is_hub_uri
|
| 563 |
+
key = (tissue, label)
|
| 564 |
+
seg = self.segments(tissue, label)
|
| 565 |
+
if key in self.packs and self.windows_held(self.packs[key], seg) >= int(k):
|
| 566 |
+
return self.packs[key]
|
| 567 |
+
uri = self.pack_menu(self.cfg, tissue)[label]
|
| 568 |
+
windows = {"windows": range(int(k))} if is_hub_uri(uri) and int(seg["n"]) > 1 else {}
|
| 569 |
+
self.packs[key] = PackSubstrate(uri, m0=1.0, name=f"{tissue}:{label}", **windows).pack
|
| 570 |
+
return self.packs[key]
|
| 571 |
+
|
| 572 |
+
@staticmethod
|
| 573 |
+
def windows_held(pack, segments):
|
| 574 |
+
"""The windows ``pack`` holds: its ``windows_present`` when loaded by window, else every window ``segments``
|
| 575 |
+
declares."""
|
| 576 |
+
return int(segments["n"]) if pack.windows_present is None else int(pack.windows_present)
|
| 577 |
+
|
| 578 |
+
@staticmethod
|
| 579 |
+
def pools(pack):
|
| 580 |
+
"""The pack's pool names (its embedded spec), or None for a pack without a spec."""
|
| 581 |
+
spec = pack.substrate
|
| 582 |
+
return None if spec is None else tuple(p.name for p in spec.pools)
|
| 583 |
+
|
| 584 |
+
@staticmethod
|
| 585 |
+
def walk_seconds(pack):
|
| 586 |
+
return float(pack.meta["walk_params"]["T_max"])
|
| 587 |
+
|
| 588 |
+
# ---- the page's side ----
|
| 589 |
+
@classmethod
|
| 590 |
+
def shape_table(cls, cfg, where=None):
|
| 591 |
+
"""The timing classes: the configuration's ``[shapes]`` and :data:`SCAN`, the scan's own pulse timing from the
|
| 592 |
+
asset's manifest, or the configuration's ``[scan]`` timing when the manifest states none (the label says
|
| 593 |
+
which)."""
|
| 594 |
+
pr = manifest(where or asset_location(cfg))["protocol"]
|
| 595 |
+
stated = all(pr.get(k) is not None for k in ("delta_s", "Delta_s", "TE_s"))
|
| 596 |
+
t = dict(delta=float(pr["delta_s"]), Delta=float(pr["Delta_s"]), TE=float(pr["TE_s"])) if stated else \
|
| 597 |
+
{k: float(cfg["scan"][k]) for k in ("delta", "Delta", "TE")}
|
| 598 |
+
why = "the scan's own timing" if stated else "the scan's b-values and directions at the configuration's timing (the asset states none)"
|
| 599 |
+
return {**cfg["shapes"], SCAN: dict(label=f"{why}: δ {t['delta'] * 1e3:g} / Δ {t['Delta'] * 1e3:g} ms, TE {t['TE'] * 1e3:g} ms", **t)}
|
| 600 |
+
|
| 601 |
+
@classmethod
|
| 602 |
+
def describe(cls, cfg):
|
| 603 |
+
d = cfg["describe"]
|
| 604 |
+
return dict(
|
| 605 |
+
title=d["title"],
|
| 606 |
+
heading=(f"# {d['title']}\n" + d["heading"]),
|
| 607 |
+
acquisition=("A shell's **pulse timing** (δ, Δ, TE; square pulses) is one of the classes below, each played by the packs' "
|
| 608 |
+
"walks, stored in windows (125 ms for the windowed packs): a class reads the windows its acquisition reaches, and a timing beyond the "
|
| 609 |
+
"walk is refused by name; the b-values, the directions and their number, the "
|
| 610 |
+
"tissue, the proton densities, the packs, the SNR and the tracker are free. The first preset is the scan's own "
|
| 611 |
+
"protocol, its directions turned into the image frame. Timing classes: "
|
| 612 |
+
+ "; ".join(f"`{n}` = {t['label']}" for n, t in cls.shape_table(cfg).items()) + "."),
|
| 613 |
+
tissue=("The replay composes three tissues per voxel: the WM pack contracted with the voxel's FOD, the GM pack as an "
|
| 614 |
+
"isotropic distribution, free water in closed form, each weighted by its fraction and proton density M0 "
|
| 615 |
+
"(relative to CSF). **SNR is defined at M0 = 1**, the b = 0 signal of a pure-CSF voxel before relaxation, so "
|
| 616 |
+
"lowering a tissue's M0 lowers its SNR. The **field** tier is the WM pack's myelin-sheath susceptibility at the "
|
| 617 |
+
"scanner's field and direction (given in the scanner frame; the head's own susceptibility is not modelled); the "
|
| 618 |
+
"GM pack and free water carry no field source. The packs' responses to the presets and the field presets are "
|
| 619 |
+
"computed once when the Space starts; any other (a custom protocol, a field or tissue not seen before) is "
|
| 620 |
+
"computed inside the GPU call and is part of what the run reserves. The pack menu is the "
|
| 621 |
+
"configuration's list; the WM pack's contact tier uses the catalogue's white-matter ρ₂, the GM pack's walls take "
|
| 622 |
+
"none (no cited value)."),
|
| 623 |
+
explorer=("What the replay made, before the noise and the tractography. **A** is the run you configured (its replay "
|
| 624 |
+
"before the noise); **B** is the same run with the one knob you chose changed. **Ingredients**: the proton-density "
|
| 625 |
+
"map Σ f·M0, the relaxation weight of every voxel's b = 0 signal at the echo, and the contact tier's survival "
|
| 626 |
+
"(the field tier's effect is its rung of the ladder). "
|
| 627 |
+
"**Layers**: A replayed with its tiers switched on one at a time (bare → + relaxation → + contact → + field), then B, as the "
|
| 628 |
+
"DWI or the tensor's MD and FA. **Estimated vs true response**: the responses the reconstruction estimated from the "
|
| 629 |
+
"replayed data against the packs' exact response at the run's tissue, per shell: what the response heuristic "
|
| 630 |
+
"gets right is itself a result. There is no per-voxel split-half floor here: the accuracy is the packs' "
|
| 631 |
+
"certified floors (the accuracy table)."),
|
| 632 |
+
results_tab="4 · brain results",
|
| 633 |
+
truth_tab="2 · the input",
|
| 634 |
+
truth_labels=("the regions (centroids, by lobe)", "the input: WM FOD peaks, fractions and regions"),
|
| 635 |
+
stages={"replay": "replaying the brain from the packs' responses", "noise": "adding Rician noise",
|
| 636 |
+
"csd": "estimating the responses and fitting CSD", "track": "tracking from the white matter",
|
| 637 |
+
"truth": "tracking the input FOD with the same settings (the truth)", "score": "scoring the connectome"},
|
| 638 |
+
fixed=[f"the subject: {d['subject']}; its FOD field, fractions and parcellation (made once, offline)",
|
| 639 |
+
"one pack per tissue class per run, from the configuration's menu (Hub records later)",
|
| 640 |
+
"the head's own susceptibility and RF effects are not modelled",
|
| 641 |
+
"the head centre at the scanner's isocentre (a machine of the scanner menu plays every voxel the gradient it delivers there; docs/scanner.md)",
|
| 642 |
+
"no per-voxel split-half floor: the packs' certified floors are the accuracy"],
|
| 643 |
+
accuracy=("A brain replay is exact composition (the tests check it against dmipy-sim's own `Phantom.compose(...).replay`) of "
|
| 644 |
+
"the packs' responses, so its accuracy is the packs' certified Monte-Carlo floors; there is no per-voxel split-half "
|
| 645 |
+
"floor, because every voxel reads the same two walks."),
|
| 646 |
+
ingredients=("proton density: Σ f·M0 (relative to CSF)", "relaxation: the b = 0 signal's T2 / T1 weight at the echo",
|
| 647 |
+
"contact: the WM walls' surface-relaxivity survival at b = 0"),
|
| 648 |
+
truth=("the connectome of the input FOD tracked directly with the same tracker, settings, seeds and key: Pearson of "
|
| 649 |
+
"log(1 + count) over the region pairs, the pairs connected in one only, and the same on the lobar groups"),
|
| 650 |
+
ladder="Replay DWI Explorer: replay A's tier ladder too (bare, + relaxation, + contact; noise-free; a few seconds of GPU time)",
|
| 651 |
+
views=dict(truth=True, fractions=True, lobar=True, roundtrip=True, response=True, floor=False),
|
| 652 |
+
files="brain", step_unit="mm",
|
| 653 |
+
volumes_label="DWI (.nii.gz, bvecs in the image frame) with bvals/bvecs, the FOD SH field (tournier07 order 8), the connectome (.csv)",
|
| 654 |
+
run_label="replay → responses + CSD → track → connectome")
|
| 655 |
+
|
| 656 |
+
@classmethod
|
| 657 |
+
def presets(cls, cfg):
|
| 658 |
+
return [cfg["describe"]["scan_preset"]] + list(cfg["presets"])
|
| 659 |
+
|
| 660 |
+
@classmethod
|
| 661 |
+
def protocol(cls, cfg, name):
|
| 662 |
+
if name == cfg["describe"]["scan_preset"]:
|
| 663 |
+
return scan_protocol(manifest(asset_location(cfg)), name=name)
|
| 664 |
+
return P.preset_protocol(cfg, name)
|
| 665 |
+
|
| 666 |
+
@classmethod
|
| 667 |
+
def panel(cls, cfg):
|
| 668 |
+
phys = cfg["physics"]; f0 = float(phys["default_field"]); c0 = cls.catalogue_numbers(cfg, f0)
|
| 669 |
+
cat = catalogue(f0)
|
| 670 |
+
C = P.Control
|
| 671 |
+
wm_menu = list(cls.pack_menu(cfg, "wm")); gm_menu = list(cls.pack_menu(cfg, "gm"))
|
| 672 |
+
rows = (
|
| 673 |
+
(C("on", "checkbox", "evaluate in tissue (off: bare diffusion at the same proton densities)", bool(phys["default_on"])),),
|
| 674 |
+
(C("field_preset", "field_preset", "field preset", f"{f0:g} T", tuple(f"{float(f):g} T" for f in phys["fields"])),
|
| 675 |
+
C("field_T", "slider", "B0 (T)", f0, minimum=0.05, maximum=12.0, step=0.001)),
|
| 676 |
+
(C("b0_mode", "dropdown", "B0 direction (scanner frame)", list(B0_MODES)[0], tuple(B0_MODES) + (FREE_B0,)),
|
| 677 |
+
C("theta", "slider", "polar angle from z (°)", 0, minimum=0, maximum=180, step=1),
|
| 678 |
+
C("phi", "slider", "azimuth from x (°)", 0, minimum=0, maximum=360, step=1)),
|
| 679 |
+
(C("relaxation", "checkbox", "relaxation (T2, T1 per tissue)", True), C("contact", "checkbox", "contact (the WM walls' ρ₂)", True),
|
| 680 |
+
C("field", "checkbox", "field (the myelin sheath's susceptibility)", True)),
|
| 681 |
+
tuple(C(f"T2_wm_{p}", "number", f"T2 WM {p} (ms)", c0[k]) for k, p in enumerate(WM_POOLS)),
|
| 682 |
+
(C("T2_gm", "number", "T2 GM (ms)", c0[3]), C("T2_csf", "number", "T2 CSF (ms)", c0[4])),
|
| 683 |
+
(C("rho2", "number", "ρ₂ of the WM walls, transverse (µm/s)", c0[5]), C("chi_iso", "number", "χ_iso of the sheath (ppm)", c0[6]),
|
| 684 |
+
C("chi_aniso", "number", "Δχ_a of the sheath (ppm)", c0[7])),
|
| 685 |
+
(C("m0_wm", "slider", "M0 WM (relative to CSF)", cat["m0"]["wm"], minimum=0.0, maximum=1.0, step=0.01),
|
| 686 |
+
C("m0_gm", "slider", "M0 GM", cat["m0"]["gm"], minimum=0.0, maximum=1.0, step=0.01),
|
| 687 |
+
C("m0_csf", "slider", "M0 CSF", cat["m0"]["csf"], minimum=0.0, maximum=1.0, step=0.01)),
|
| 688 |
+
(C("wm_pack", "dropdown", "WM pack", wm_menu[0], tuple(wm_menu)), C("gm_pack", "dropdown", "GM pack", gm_menu[0], tuple(gm_menu))),
|
| 689 |
+
(C("catalogue_note", "catalogue_note", value=c0[-1]), C("reset", "reset", "reset to the catalogue at this field")),
|
| 690 |
+
)
|
| 691 |
+
fields = ("on", "field_T", "b0_mode", "theta", "phi", "relaxation", "contact", "field", *[f"T2_wm_{p}" for p in WM_POOLS], "T2_gm", "T2_csf",
|
| 692 |
+
"rho2", "chi_iso", "chi_aniso", "m0_wm", "m0_gm", "m0_csf", "wm_pack", "gm_pack")
|
| 693 |
+
return P.Panel(rows, fields, (*[f"T2_wm_{p}" for p in WM_POOLS], "T2_gm", "T2_csf", "rho2", "chi_iso", "chi_aniso"),
|
| 694 |
+
tuple(float(f) for f in phys["fields"]))
|
| 695 |
+
|
| 696 |
+
@classmethod
|
| 697 |
+
def catalogue_numbers(cls, cfg, field_T):
|
| 698 |
+
"""The catalogue's T2 per WM pool, GM and CSF (ms), the WM walls' rho2 (µm/s) and the sheath's susceptibility
|
| 699 |
+
(ppm) at ``field_T``, and the note saying which cited field they came from."""
|
| 700 |
+
c = catalogue(float(field_T))
|
| 701 |
+
note = (f"catalogue values at {c['catalogue_field']:g} T" if abs(c["catalogue_field"] - float(field_T)) < 1e-9
|
| 702 |
+
else f"the catalogue has no cited relaxation at {float(field_T):g} T: nearest is {c['catalogue_field']:g} T, edit as you see fit")
|
| 703 |
+
return [c["T2"]["wm"][p] * 1e3 for p in WM_POOLS] + [c["T2"]["gm"] * 1e3, c["T2"]["csf"] * 1e3, c["rho2"] * 1e6,
|
| 704 |
+
c["chi_iso"] * 1e6, c["chi_aniso"] * 1e6, note]
|
| 705 |
+
|
| 706 |
+
@classmethod
|
| 707 |
+
def physics_from(cls, cfg, values, scanner=None):
|
| 708 |
+
"""The panel (page units: ms, µm/s, ppm) as a :class:`BrainPhysics`: T1 and free water's D from the catalogue at
|
| 709 |
+
the physics' field, the tiers off (bare diffusion at the same M0 and packs) when the panel is off; ``scanner``
|
| 710 |
+
the machine of the page's menu (a catalogue key; None: the ideal scanner), whose field and direction replace
|
| 711 |
+
the panel's and whose slew shapes every pulse."""
|
| 712 |
+
on = bool(values["on"])
|
| 713 |
+
field_T = float(values["field_T"])
|
| 714 |
+
u = B0_MODES[values["b0_mode"]] if values["b0_mode"] in B0_MODES else P.b0_direction(values["theta"], values["phi"])
|
| 715 |
+
if scanner is not None:
|
| 716 |
+
L = P.limits(scanner)
|
| 717 |
+
field_T, u = float(L.field_T), tuple(float(x) for x in (L.b0_axis or P.B0_ALONG_Z))
|
| 718 |
+
c = catalogue(field_T)
|
| 719 |
+
return BrainPhysics(field_T=field_T, b0_direction=tuple(float(x) for x in u),
|
| 720 |
+
T2={"wm": {p: float(values[f"T2_wm_{p}"]) * 1e-3 for p in WM_POOLS}, "gm": float(values["T2_gm"]) * 1e-3, "csf": float(values["T2_csf"]) * 1e-3},
|
| 721 |
+
T1=c["T1"], rho2=float(values["rho2"]) * 1e-6, chi_iso=float(values["chi_iso"]) * 1e-6, chi_aniso=float(values["chi_aniso"]) * 1e-6,
|
| 722 |
+
D_csf=c["D_csf"], m0={t: float(values[f"m0_{t}"]) for t in TISSUES}, wm_pack=str(values["wm_pack"]), gm_pack=str(values["gm_pack"]),
|
| 723 |
+
relaxation=on and bool(values["relaxation"]), contact=on and bool(values["contact"]), field=on and bool(values["field"]),
|
| 724 |
+
scanner=scanner)
|
| 725 |
+
|
| 726 |
+
@classmethod
|
| 727 |
+
def knobs(cls, cfg):
|
| 728 |
+
"""B = A with one change: the field (with the catalogue's tissue at it), the field's direction, a tier off, the
|
| 729 |
+
tissue off, the WM or GM pack, grey matter's M0, the noise, or every shell's pulse timing (a stimulated echo
|
| 730 |
+
among them)."""
|
| 731 |
+
out = {P.NO_KNOB: None}
|
| 732 |
+
for f in cfg["physics"]["fields"]:
|
| 733 |
+
out[f"field → {float(f):g} T (catalogue tissue at that field)"] = ("field", float(f))
|
| 734 |
+
for label in B0_MODES:
|
| 735 |
+
out[f"B0 direction → {label}"] = ("b0", label)
|
| 736 |
+
for tier in cls.TIERS:
|
| 737 |
+
out[f"{tier} tier → off"] = ("tier", tier)
|
| 738 |
+
out["tissue → off (bare diffusion)"] = ("bare", None)
|
| 739 |
+
for tissue in ("wm", "gm"):
|
| 740 |
+
for label in cls.pack_menu(cfg, tissue):
|
| 741 |
+
out[f"{tissue.upper()} pack → {label}"] = ("pack", (tissue, label))
|
| 742 |
+
for v in cfg["physics"]["m0_gm_knob"]:
|
| 743 |
+
out[f"M0 of GM → {float(v):g}"] = ("m0_gm", float(v))
|
| 744 |
+
for v in (10, 100):
|
| 745 |
+
out[f"SNR → {v}"] = ("snr", float(v))
|
| 746 |
+
out["noise → off"] = ("snr", None)
|
| 747 |
+
for name, sh in cfg["shapes"].items():
|
| 748 |
+
out[f"every shell's pulse timing → {name} ({sh['label']})"] = ("shape", name)
|
| 749 |
+
return out
|
| 750 |
+
|
| 751 |
+
@classmethod
|
| 752 |
+
def apply_knob(cls, cfg, change, protocol, snr_on, snr, values):
|
| 753 |
+
kind, value = change
|
| 754 |
+
v = dict(values)
|
| 755 |
+
if kind in ("field", "b0", "tier") and not v["on"]:
|
| 756 |
+
raise ValueError(f"the knob {kind!r} changes the tissue panel, which is off for A: switch it on, or choose another knob")
|
| 757 |
+
if kind == "field":
|
| 758 |
+
v["field_T"] = value; v.update(zip(cls.panel(cfg).catalogue, cls.catalogue_numbers(cfg, value)))
|
| 759 |
+
elif kind == "b0":
|
| 760 |
+
v["b0_mode"] = value
|
| 761 |
+
elif kind == "tier":
|
| 762 |
+
v[value] = False
|
| 763 |
+
elif kind == "bare":
|
| 764 |
+
v["on"] = False
|
| 765 |
+
elif kind == "pack":
|
| 766 |
+
v[f"{value[0]}_pack"] = value[1]
|
| 767 |
+
elif kind == "m0_gm":
|
| 768 |
+
v["m0_gm"] = value
|
| 769 |
+
elif kind == "snr":
|
| 770 |
+
snr_on = value is not None; snr = value if value is not None else snr
|
| 771 |
+
elif kind == "shape":
|
| 772 |
+
protocol = P.retime(protocol, value)
|
| 773 |
+
else:
|
| 774 |
+
raise ValueError(f"unknown knob {kind!r}")
|
| 775 |
+
return protocol, snr_on, snr, v
|
| 776 |
+
|
| 777 |
+
@classmethod
|
| 778 |
+
def tracking_controls(cls, cfg):
|
| 779 |
+
t = cfg["tracking"]
|
| 780 |
+
return dict(density=(1, 4, t["density"], 1, "seeds per WM voxel (density³)"), max_angle=(10, 60, t["max_angle"], 1, "max angle (°)"),
|
| 781 |
+
step=(0.5, 2.5, t["step_mm"], 0.05, "step (mm)"))
|
| 782 |
+
|
| 783 |
+
@classmethod
|
| 784 |
+
def tracking(cls, cfg, *, density, max_angle, step, key):
|
| 785 |
+
"""The tracker with :meth:`max_steps` for the step: a streamline can reach :data:`REACH_MM`."""
|
| 786 |
+
return P.Tracking(density=int(density), step_mm=float(step), max_angle=float(max_angle), max_steps=cls.max_steps(step), key=int(key))
|
| 787 |
+
|
| 788 |
+
@classmethod
|
| 789 |
+
def shapes_of(cls, cfg):
|
| 790 |
+
return cls.shape_table(cfg)
|
| 791 |
+
|
| 792 |
+
@classmethod
|
| 793 |
+
def max_steps(cls, step_mm):
|
| 794 |
+
"""Points per half-streamline such that :data:`REACH_MM` is reachable from a seed at either end."""
|
| 795 |
+
return int(np.ceil(REACH_MM / float(step_mm))) + 1
|
| 796 |
+
|
| 797 |
+
@classmethod
|
| 798 |
+
def estimated_seconds(cls, cfg, protocol, *, density, knob, n_keys, ladder, responses=(), scanner=None):
|
| 799 |
+
"""The GPU seconds a run reserves: ``[budget]`` of the configuration, measured on an L40S with the BATMAN
|
| 800 |
+
fixture (tools/measure_brain.py): a fixed part (the worker's start, noise, the reconstruction's fixed cost, the
|
| 801 |
+
handoff), a part per measurement (the contraction and the reconstruction scale with the rows), the tracking
|
| 802 |
+
and the truth's tracking per density, the ladder's two rungs of contraction, B (a second run whose truth is A's),
|
| 803 |
+
each further tracker key, and the pose responses the worker computes because the page has them not cached
|
| 804 |
+
(``responses``: ``(state, n_meas, saves)`` per entry, :meth:`responses`, each priced ``fixed + per_meas x n_meas +
|
| 805 |
+
per_save x saves``; a machine's encoding classes are in ``n_meas``); times the margin, within 30 and 480 s."""
|
| 806 |
+
b = cfg["budget"]
|
| 807 |
+
n = protocol.n_meas; d = str(int(density))
|
| 808 |
+
track = float(b["track"][d])
|
| 809 |
+
run = b["fixed"] + b["per_meas"] * n + track
|
| 810 |
+
secs = run + track + (b["ladder_per_meas"] * n if ladder else 0.0) + ((run - b["worker"]) if knob != P.NO_KNOB else 0.0) + track * (int(n_keys) - 1)
|
| 811 |
+
secs += sum(b[f"response_{state}"]["fixed"] + b[f"response_{state}"]["per_meas"] * m + b[f"response_{state}"]["per_save"] * saves
|
| 812 |
+
for state, m, saves in responses)
|
| 813 |
+
return int(min(480, max(30, b["margin"] * secs)))
|
| 814 |
+
|
| 815 |
+
# ---- the run's side ----
|
| 816 |
+
def validate(self, protocol, physics):
|
| 817 |
+
"""The measurements, refused by name when a class reaches beyond the windows a pack declares
|
| 818 |
+
(:meth:`windows_needed`, from the declared table, loaded or not), when a class's echo lies beyond a loaded
|
| 819 |
+
pack's walk (:meth:`prepare` loads the chosen ones), or when a loaded pack's embedded spec does not declare its
|
| 820 |
+
susceptibility field (a pack without a spec, or whose magnetic pools, field tier and stored field disagree)."""
|
| 821 |
+
meas = P.measurements(protocol, self.shapes)
|
| 822 |
+
if physics is None:
|
| 823 |
+
raise ValueError("a brain replay needs its physics (the proton densities and the packs), even for bare diffusion")
|
| 824 |
+
for tissue, label in (("wm", physics.wm_pack), ("gm", physics.gm_pack)):
|
| 825 |
+
self.windows_needed(tissue, label, meas)
|
| 826 |
+
pk = self.packs.get((tissue, label))
|
| 827 |
+
if pk is None:
|
| 828 |
+
continue
|
| 829 |
+
T = self.walk_seconds(pk)
|
| 830 |
+
for name in map(str, np.unique(meas.shape)):
|
| 831 |
+
TE = float(self.shapes[name]["TE"])
|
| 832 |
+
if TE > T * (1 + 1e-9):
|
| 833 |
+
raise ValueError(f"the {tissue.upper()} pack {label!r} is a {T * 1e3:g} ms walk: it cannot play the class {name!r} "
|
| 834 |
+
f"at TE {TE * 1e3:g} ms")
|
| 835 |
+
pk.susceptibility_field # refuses a pack whose embedded spec does not declare its field, by name
|
| 836 |
+
return meas
|
| 837 |
+
|
| 838 |
+
def sequence(self, meas, rows, pose, slew_rate=np.inf):
|
| 839 |
+
"""The ScannerSequence of the measurement rows ``rows`` (one timing class) played at the specimen's ``pose``:
|
| 840 |
+
the image-frame directions turned by ``pose``, trapezoid pulses at the class's delta / Delta / TE with ramps at
|
| 841 |
+
``slew_rate`` (vertical at the default, infinite), a stimulated echo storing for TM = Delta - delta when the
|
| 842 |
+
class is one."""
|
| 843 |
+
import dmipy_sim as d
|
| 844 |
+
names = np.unique(meas.shape[rows])
|
| 845 |
+
if len(names) != 1:
|
| 846 |
+
raise ValueError(f"one timing class per sequence, got {list(names)}")
|
| 847 |
+
t = self.shapes[str(names[0])]
|
| 848 |
+
dirs = (meas.dirs[rows] @ np.asarray(pose).T).tolist(); b = meas.bvals[rows] * 1e6
|
| 849 |
+
if t.get("kind", "pgse") == "pgste":
|
| 850 |
+
return d.pgste(dirs, float(t["delta"]), float(t["Delta"]) - float(t["delta"]), bvalues=b, TE=float(t["TE"]), n_t=1000,
|
| 851 |
+
slew_rate=float(slew_rate), ste_flip_angles=(90.0, 90.0, 90.0))
|
| 852 |
+
return d.pgse(dirs, float(t["delta"]), float(t["Delta"]), bvalues=b, TE=float(t["TE"]), n_t=1000, slew_rate=float(slew_rate))
|
| 853 |
+
|
| 854 |
+
def _b0_sequence(self, name, pose, slew_rate=np.inf):
|
| 855 |
+
"""The class ``name``'s b = 0 measurement as a sequence at ``pose`` (:meth:`sequence`): what the b = 0 signal
|
| 856 |
+
and the acquisition's duration are read from."""
|
| 857 |
+
one = P.Measurements(np.zeros(1), np.array([[0.0, 0.0, 1.0]]), np.array([name]), np.zeros(1), np.zeros(1), np.zeros(1))
|
| 858 |
+
return self.sequence(one, np.arange(1), pose, slew_rate)
|
| 859 |
+
|
| 860 |
+
def response_key(self, meas, physics=None):
|
| 861 |
+
"""The key of :meth:`prepare`'s result in this process's cache: the measurements (b-values, directions,
|
| 862 |
+
timing classes) and the physics but its proton densities, which the device applies."""
|
| 863 |
+
import hashlib
|
| 864 |
+
h = hashlib.sha256()
|
| 865 |
+
for x in (meas.bvals, meas.dirs, meas.shape.astype(str)):
|
| 866 |
+
h.update(np.ascontiguousarray(x).tobytes())
|
| 867 |
+
return h.hexdigest(), repr(replace(physics, m0={t: 0.0 for t in TISSUES}))
|
| 868 |
+
|
| 869 |
+
@staticmethod
|
| 870 |
+
def _band(meas, physics):
|
| 871 |
+
"""What the pose route compiles for: the packs, the rows per timing class and, with the field tier, the field
|
| 872 |
+
and the sheath's susceptibility (the phase amplitude sets the expansion's band, whose shapes compile; measured:
|
| 873 |
+
a new tissue or field direction at a compiled band costs no compilation, a run without the field tier none
|
| 874 |
+
at all)."""
|
| 875 |
+
names, counts = np.unique(meas.shape.astype(str), return_counts=True)
|
| 876 |
+
field = (physics.field_T, physics.chi_iso, physics.chi_aniso) if physics.field else None
|
| 877 |
+
return physics.wm_pack, physics.gm_pack, tuple(zip(names.tolist(), counts.tolist())), field
|
| 878 |
+
|
| 879 |
+
def cached(self, meas, physics=None):
|
| 880 |
+
""":meth:`prepare`'s result for ``meas`` at ``physics`` when this process has it (at ``physics``'s proton
|
| 881 |
+
densities, zero seconds), else None."""
|
| 882 |
+
k = self._kernels.get(self.response_key(meas, physics))
|
| 883 |
+
return None if k is None else replace(k, m0=dict(physics.m0), seconds=0.0)
|
| 884 |
+
|
| 885 |
+
def keep(self, kernels):
|
| 886 |
+
"""``{response_key: Kernels}`` computed in another process (the GPU worker) kept in this one's cache."""
|
| 887 |
+
for key, k in kernels.items():
|
| 888 |
+
self._store(key, k)
|
| 889 |
+
|
| 890 |
+
def _store(self, key, k):
|
| 891 |
+
self._kernels[key] = k
|
| 892 |
+
while len(self._kernels) > 128: # a bounded memory: the oldest goes first
|
| 893 |
+
self._kernels.pop(next(iter(self._kernels)))
|
| 894 |
+
|
| 895 |
+
@functools.cached_property
|
| 896 |
+
def bore_grid(self):
|
| 897 |
+
"""``(grid, index)``: the brain's voxels as they sit in the bore, the head centre (the mask's centroid) at
|
| 898 |
+
isocentre: :meth:`dmipy_sim.phantom.Grid.from_oblique_affine` of the cropped asset's affine, whose rotation
|
| 899 |
+
is :attr:`Asset.R` (the frame the page composes in), and ``index`` the brain voxels' own indices, each at
|
| 900 |
+
``affine @ [ijk, 1]`` in the scanner for a left- or right-handed affine."""
|
| 901 |
+
from dmipy_sim.phantom import Grid
|
| 902 |
+
A = np.asarray(self.affine, np.float64)
|
| 903 |
+
centre = (A[:3, :3] @ self.vox.mean(0) + A[:3, 3]) * 1e-3
|
| 904 |
+
grid, R = Grid.from_oblique_affine(A, self.mask.shape, isocenter_m=centre)
|
| 905 |
+
if not np.allclose(R, self.asset.R, atol=1e-6):
|
| 906 |
+
raise ValueError("the asset's rotation is not its affine's: the bore placement would be wrong")
|
| 907 |
+
return grid, self.vox.copy()
|
| 908 |
+
|
| 909 |
+
def encoding(self, meas, physics, rows):
|
| 910 |
+
"""``(class_of_voxel, played)``: the timing class ``rows`` of ``meas`` as the run's machine plays it at every brain
|
| 911 |
+
voxel, binned to ``[scanners] tolerance`` of b (:func:`dmipy_sim.phantom.bore.encoding_classes` on
|
| 912 |
+
:attr:`bore_grid`), the played acquisitions in the image frame; computed once per machine, slew and rows."""
|
| 913 |
+
from dmipy_sim.phantom.bore import encoding_classes
|
| 914 |
+
import hashlib
|
| 915 |
+
h = hashlib.sha256()
|
| 916 |
+
for x in (meas.bvals[rows], meas.dirs[rows], meas.shape[rows].astype(str)):
|
| 917 |
+
h.update(np.ascontiguousarray(x).tobytes())
|
| 918 |
+
key = (physics.scanner, physics.slew_rate, h.hexdigest())
|
| 919 |
+
if key not in self._encodings:
|
| 920 |
+
grid, idx = self.bore_grid
|
| 921 |
+
tol = float(self.cfg["scanners"]["tolerance"])
|
| 922 |
+
seq = self.sequence(meas, rows, np.eye(3), physics.slew_rate)
|
| 923 |
+
out = encoding_classes(P.limits(physics.scanner), grid, seq, idx, tolerance=tol)
|
| 924 |
+
if out is None:
|
| 925 |
+
out = (np.zeros(len(idx), int), [seq])
|
| 926 |
+
self._encodings[key] = (np.asarray(out[0], int), list(out[1]))
|
| 927 |
+
while len(self._encodings) > 16:
|
| 928 |
+
self._encodings.pop(next(iter(self._encodings)))
|
| 929 |
+
return self._encodings[key]
|
| 930 |
+
|
| 931 |
+
def n_classes(self, meas, physics):
|
| 932 |
+
"""The encoding classes the run's acquisition needs over its timing classes (one per timing class on the ideal
|
| 933 |
+
scanner): what its pose responses cost, in units of the commanded acquisition."""
|
| 934 |
+
groups = [np.flatnonzero(meas.shape == name) for name in np.unique(meas.shape)]
|
| 935 |
+
if physics is None or physics.scanner is None:
|
| 936 |
+
return 1
|
| 937 |
+
return max(len(self.encoding(meas, physics, rows)[1]) for rows in groups)
|
| 938 |
+
|
| 939 |
+
def responses(self, entries):
|
| 940 |
+
"""What :meth:`prepare` costs for a run's ``entries`` ``[(meas, physics)]`` in a process forked from this one,
|
| 941 |
+
in order: ``(state, n_meas, saves)`` for each entry not cached here, once per key; ``state`` is ``no_field``
|
| 942 |
+
(the field tier off: nothing to compile), ``warm`` (a band compiled here, or by an earlier entry of the run)
|
| 943 |
+
or ``cold`` (a band to compile first); ``saves`` the WM pack's saves the entry's classes span
|
| 944 |
+
(:meth:`saves_spanned` of :meth:`windows_needed`). ``[budget]`` prices them (``response_<state>``); on a machine
|
| 945 |
+
an entry counts its rows once per encoding class times ``response_per_class`` (a class's rows each play their own
|
| 946 |
+
amplitude, so the shells no longer share the expansion's bodies)."""
|
| 947 |
+
out = []; keys = set(); bands = set(self._compiled)
|
| 948 |
+
for meas, ph in entries:
|
| 949 |
+
key = self.response_key(meas, ph)
|
| 950 |
+
if key in self._kernels or key in keys:
|
| 951 |
+
continue
|
| 952 |
+
keys.add(key)
|
| 953 |
+
band = self._band(meas, ph)
|
| 954 |
+
saves = self.saves_spanned(self.segments("wm", ph.wm_pack), self.windows_needed("wm", ph.wm_pack, meas))
|
| 955 |
+
n = len(meas.bvals)
|
| 956 |
+
if ph.scanner is not None: # every class's rows are their own bodies
|
| 957 |
+
n = int(np.ceil(n * self.n_classes(meas, ph) * float(self.cfg["budget"]["response_per_class"])))
|
| 958 |
+
out.append(("no_field" if not ph.field else "warm" if band in bands else "cold", n, saves))
|
| 959 |
+
bands.add(band)
|
| 960 |
+
return out
|
| 961 |
+
|
| 962 |
+
def prepare(self, meas, physics=None):
|
| 963 |
+
"""The pose responses of a replay, on the CPU: per timing class of ``meas``, the WM and GM packs' pose
|
| 964 |
+
responses at the run's tissue, field and specimen pose (dmipy-sim's closed form) contracted to the FOD's
|
| 965 |
+
harmonics, free water's closed form; the true response curves for the explorer and the b = 0 weight of each
|
| 966 |
+
tier alone (both at the first class's shells, within the windows ``meas`` reaches). Loads the windows of the
|
| 967 |
+
chosen packs the classes reach (:meth:`windows_needed`, :meth:`pack`); computed every call and kept in this
|
| 968 |
+
process's cache under :meth:`response_key` (:meth:`cached` reads it)."""
|
| 969 |
+
from dmipy_sim.phantom import FreeWater
|
| 970 |
+
from dmipy_sim.replay import so3
|
| 971 |
+
t0 = time.perf_counter(); stages = {}
|
| 972 |
+
wm_pack = self.pack("wm", physics.wm_pack, self.windows_needed("wm", physics.wm_pack, meas))
|
| 973 |
+
stages["load_wm"] = time.perf_counter() - t0
|
| 974 |
+
gm_pack = self.pack("gm", physics.gm_pack, self.windows_needed("gm", physics.gm_pack, meas))
|
| 975 |
+
stages["load_gm"] = time.perf_counter() - t0 - stages["load_wm"]
|
| 976 |
+
for name in np.unique(meas.shape): # the walks and the WM pack's tiers, now loaded
|
| 977 |
+
self.validate(P.Protocol((P.Shell(str(name), 1.0, 1),), name="check"), physics)
|
| 978 |
+
t_wm, t_gm, t_csf = physics.tissues(wm_pack, gm_pack)
|
| 979 |
+
pose = specimen_pose(self.asset.R, physics.b0_direction)
|
| 980 |
+
A = axis_map()
|
| 981 |
+
n = len(meas.bvals)
|
| 982 |
+
classes = [np.flatnonzero(meas.shape == name) for name in np.unique(meas.shape)]
|
| 983 |
+
# per timing class, the acquisitions the voxels are played: the commanded one, or one per encoding class of the
|
| 984 |
+
# machine (its delivered gradient, in the image frame, turned to the specimen's pose)
|
| 985 |
+
plan, seqs = [], []
|
| 986 |
+
from dmipy_sim.acquisition.waveforms import rotate_waveform
|
| 987 |
+
for rows in classes:
|
| 988 |
+
if physics.scanner is None:
|
| 989 |
+
cls, played = np.zeros(len(self.vox), int), [self.sequence(meas, rows, pose, physics.slew_rate)]
|
| 990 |
+
else:
|
| 991 |
+
cls, img = self.encoding(meas, physics, rows)
|
| 992 |
+
played = [rotate_waveform(q, pose) for q in img]
|
| 993 |
+
plan.append((rows, cls, len(seqs))); seqs += played
|
| 994 |
+
prof = self._profile_sequence(meas, classes[0], pose, physics.slew_rate) # the explorer's curves ride in the same pass
|
| 995 |
+
batch = seqs + ([prof[0]] if prof is not None else [])
|
| 996 |
+
t = time.perf_counter()
|
| 997 |
+
r_wm = wm_pack.pose_responses(batch, tissue=t_wm, scanner=physics.scanner_field, pose=pose, keep=(LMAX, 0))
|
| 998 |
+
stages["pose_wm"] = time.perf_counter() - t; t = time.perf_counter()
|
| 999 |
+
r_gm = gm_pack.pose_responses(batch, tissue=t_gm, scanner=physics.scanner_field, pose=pose, keep=(0, 0))
|
| 1000 |
+
stages["pose_gm"] = time.perf_counter() - t
|
| 1001 |
+
free = FreeWater(m0=1.0, tissue=t_csf)
|
| 1002 |
+
K = len(seqs)
|
| 1003 |
+
C_wm = np.zeros((K, n, N_COEF), np.complex128); e_gm = np.zeros((K, n), np.complex128); e_csf = np.zeros((K, n), np.complex128)
|
| 1004 |
+
voxel_class = np.zeros((len(self.vox), len(classes)), np.int32)
|
| 1005 |
+
for t_, (rows, cls, off) in enumerate(plan):
|
| 1006 |
+
for j in range(int(cls.max()) + 1):
|
| 1007 |
+
k_ = off + j
|
| 1008 |
+
C_wm[k_, rows] = r_wm[k_].retained(LMAX, 0) @ A
|
| 1009 |
+
e_gm[k_, rows] = r_gm[k_].retained(0, 0)[:, 0] * A[0, 0] * C00
|
| 1010 |
+
e_csf[k_, rows] = free.response(seqs[k_])
|
| 1011 |
+
voxel_class[:, t_] = off + cls
|
| 1012 |
+
profile = None
|
| 1013 |
+
if prof is not None:
|
| 1014 |
+
seq, shells = prof
|
| 1015 |
+
axis = so3.Distribution.axis((0.0, 0.0, 1.0), lmax=LMAX, nmax=0)
|
| 1016 |
+
wm = np.abs(r_wm[-1].compose(axis)); gm = np.abs(r_gm[-1].retained(0, 0)[:, 0]); csf = np.abs(free.response(seq))
|
| 1017 |
+
k_ = len(PROFILE_ANGLES)
|
| 1018 |
+
profile = dict(b=shells, angles=PROFILE_ANGLES, wm=(wm[1:] / wm[0]).reshape(len(shells), k_),
|
| 1019 |
+
gm=(gm[1:] / gm[0]).reshape(len(shells), k_)[:, 0], csf=(csf[1:] / csf[0]).reshape(len(shells), k_)[:, 0])
|
| 1020 |
+
t = time.perf_counter()
|
| 1021 |
+
b0 = self._tier_weights(meas, physics, wm_pack, gm_pack, pose, classes[0])
|
| 1022 |
+
stages["weights"] = time.perf_counter() - t
|
| 1023 |
+
floors = {"wm": _floor(wm_pack), "gm": _floor(gm_pack)}
|
| 1024 |
+
k = Kernels(C_wm, e_gm, e_csf, voxel_class, tuple(classes), dict(physics.m0), floors, time.perf_counter() - t0, profile, b0, stages)
|
| 1025 |
+
self._store(self.response_key(meas, physics), k)
|
| 1026 |
+
self._compiled.add(self._band(meas, physics))
|
| 1027 |
+
return k
|
| 1028 |
+
|
| 1029 |
+
def _profile_sequence(self, meas, rows, pose, slew_rate=np.inf):
|
| 1030 |
+
"""``(seq, shells)``: the explorer's profile at the shells of ``meas``'s first class (``rows``): b = 0, then
|
| 1031 |
+
per shell a gradient at each of :data:`PROFILE_ANGLES` from the image's z, where the profile's fibre lies; None
|
| 1032 |
+
without a diffusion-weighted shell."""
|
| 1033 |
+
shells = np.unique(np.round(meas.bvals[rows][~meas.b0[rows]]))
|
| 1034 |
+
if not shells.size:
|
| 1035 |
+
return None
|
| 1036 |
+
th = np.radians(PROFILE_ANGLES)
|
| 1037 |
+
dirs = np.stack([np.sin(th), np.zeros_like(th), np.cos(th)], 1)
|
| 1038 |
+
b = np.concatenate([[0.0], np.repeat(shells, len(th))])
|
| 1039 |
+
g = np.concatenate([[[0.0, 0.0, 1.0]], np.tile(dirs, (len(shells), 1))])
|
| 1040 |
+
prof = P.Measurements(b, g, np.full(len(b), meas.shape[rows[0]]), np.zeros(len(b)), np.zeros(len(b)), np.zeros(len(b)))
|
| 1041 |
+
return self.sequence(prof, np.arange(len(b)), pose, slew_rate), shells
|
| 1042 |
+
|
| 1043 |
+
def _tier_weights(self, meas, physics, wm_pack, gm_pack, pose, rows):
|
| 1044 |
+
"""The b = 0 signal per tissue with each tier alone, over bare: ``relaxation`` (T2 at the echo, T1 over a
|
| 1045 |
+
stimulated echo's storage) per tissue, ``contact`` (the WM walls' survival) for WM; a tier that is off is
|
| 1046 |
+
absent. The b = 0 signal has no orientation, so one pose of the pack answers it."""
|
| 1047 |
+
from dmipy_sim.phantom import FreeWater
|
| 1048 |
+
seq = self._b0_sequence(str(meas.shape[rows[0]]), pose, physics.slew_rate)
|
| 1049 |
+
out = {}
|
| 1050 |
+
alone = dict(relaxation=False, contact=False, field=False)
|
| 1051 |
+
if physics.relaxation:
|
| 1052 |
+
t_wm, t_gm, t_csf = replace(physics, **{**alone, "relaxation": True}).tissues(wm_pack, gm_pack)
|
| 1053 |
+
out["relaxation"] = {"wm": float(np.abs(wm_pack.replay(seq, tissue=t_wm))[0]), "gm": float(np.abs(gm_pack.replay(seq, tissue=t_gm))[0]),
|
| 1054 |
+
"csf": float(np.abs(FreeWater(m0=1.0, tissue=t_csf).response(seq))[0])}
|
| 1055 |
+
if physics.contact:
|
| 1056 |
+
t_wm, _, _ = replace(physics, **{**alone, "contact": True}).tissues(wm_pack, gm_pack)
|
| 1057 |
+
out["contact"] = {"wm": float(np.abs(wm_pack.replay(seq, tissue=t_wm))[0])}
|
| 1058 |
+
return out
|
| 1059 |
+
|
| 1060 |
+
def replay(self, meas, physics=None, prepared=None):
|
| 1061 |
+
"""The kernel route on the device: per timing class and encoding class, ``S = |F_wm C_wm^T + f_gm m0_gm e_gm +
|
| 1062 |
+
f_csf m0_csf e_csf|`` over the class's voxels in float32 torch (the device's GPU when there is one),
|
| 1063 |
+
S0-normalised; ``s0_factor`` is every voxel's b = 0 signal in M0 units (M0 = 1: pure CSF before relaxation);
|
| 1064 |
+
the floor is zero (the packs' floors are the accuracy)."""
|
| 1065 |
+
import torch
|
| 1066 |
+
if prepared is None:
|
| 1067 |
+
raise ValueError("a brain replay needs its pose responses: Brain.prepare(meas, physics) first")
|
| 1068 |
+
t0 = time.perf_counter()
|
| 1069 |
+
dev = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 1070 |
+
k = prepared
|
| 1071 |
+
m0 = k.m0
|
| 1072 |
+
f = torch.as_tensor(self.f, device=dev)
|
| 1073 |
+
F = torch.as_tensor(self.fod_unit, device=dev) * (f[:, 0] * m0["wm"])[:, None]
|
| 1074 |
+
g = (f[:, 1] * m0["gm"])[:, None]; c = (f[:, 2] * m0["csf"])[:, None]
|
| 1075 |
+
n_vox, n = F.shape[0], len(meas.bvals)
|
| 1076 |
+
Sr = torch.zeros((n_vox, n), dtype=torch.float32, device=dev); Si = torch.zeros_like(Sr)
|
| 1077 |
+
for t_, rows in enumerate(k.timing_rows):
|
| 1078 |
+
r = torch.as_tensor(np.asarray(rows), device=dev)
|
| 1079 |
+
for cls in np.unique(k.classes[:, t_]):
|
| 1080 |
+
sel = np.flatnonzero(k.classes[:, t_] == cls)
|
| 1081 |
+
v = torch.as_tensor(sel, device=dev) if len(sel) < n_vox else None
|
| 1082 |
+
C = k.wm[cls][rows]
|
| 1083 |
+
Cr = torch.as_tensor(C.real.astype(np.float32), device=dev); Ci = torch.as_tensor(C.imag.astype(np.float32), device=dev)
|
| 1084 |
+
eg = torch.as_tensor(np.stack([k.gm[cls][rows].real, k.gm[cls][rows].imag]).astype(np.float32), device=dev)
|
| 1085 |
+
ec = torch.as_tensor(np.stack([k.csf[cls][rows].real, k.csf[cls][rows].imag]).astype(np.float32), device=dev)
|
| 1086 |
+
Fv, gv, cv = (F, g, c) if v is None else (F[v], g[v], c[v])
|
| 1087 |
+
re = Fv @ Cr.T + gv * eg[0][None, :] + cv * ec[0][None, :]
|
| 1088 |
+
im = Fv @ Ci.T + gv * eg[1][None, :] + cv * ec[1][None, :]
|
| 1089 |
+
if v is None:
|
| 1090 |
+
Sr[:, r] = re; Si[:, r] = im
|
| 1091 |
+
else:
|
| 1092 |
+
Sr[v[:, None], r[None, :]] = re; Si[v[:, None], r[None, :]] = im
|
| 1093 |
+
S = torch.sqrt(Sr * Sr + Si * Si)
|
| 1094 |
+
S0 = S[:, torch.as_tensor(meas.b0, device=dev)].mean(1)
|
| 1095 |
+
live = S0 > 0
|
| 1096 |
+
dwi = torch.where(live[:, None], S / torch.where(live, S0, 1.0)[:, None], torch.nan)
|
| 1097 |
+
out = np.full(self.mask.shape + (len(meas.bvals),), np.nan, np.float32)
|
| 1098 |
+
out[self.mask] = dwi.cpu().numpy()
|
| 1099 |
+
factor = np.full(self.mask.shape, np.nan, np.float32)
|
| 1100 |
+
factor[self.mask] = torch.where(live, S0, torch.nan).cpu().numpy()
|
| 1101 |
+
return out, np.zeros(self.mask.shape, np.float32), factor, time.perf_counter() - t0
|
| 1102 |
+
|
| 1103 |
+
def reconstruct(self, dwi, s0_factor, meas, mask):
|
| 1104 |
+
"""The configuration's reconstruction (:func:`space.pipeline.reconstruction`) and the round trip against the
|
| 1105 |
+
asset: ``msmt``, three-tissue responses and multi-tissue CSD on the signal in M0 units, or ``tournier07``,
|
| 1106 |
+
the single-fibre response and single-tissue CSD on the S0-normalised signal; each step's time under a name
|
| 1107 |
+
that says which ran. ``extras``: the path, the recovered fractions (multi-tissue only), the estimated response
|
| 1108 |
+
curves at the explorer's profile, and the round-trip numbers (:meth:`roundtrip`)."""
|
| 1109 |
+
method = P.reconstruction(self.cfg)
|
| 1110 |
+
if method == "tournier07":
|
| 1111 |
+
sh, t, (S0, model) = P.csd(dwi, meas, mask, backend=self.backend)
|
| 1112 |
+
seconds = {f"csd · single-tissue: tournier07 response + csd_tournier07_{self.backend}": t}
|
| 1113 |
+
responses = {"wm": (S0, model)}; fractions = None
|
| 1114 |
+
path = f"single-tissue Tournier 2007 (DISCO_RECONSTRUCTION=tournier07): white_matter_response_tournier07 + csd_tournier07_{self.backend}"
|
| 1115 |
+
else:
|
| 1116 |
+
sh, fractions, (S0s, models), (t_resp, t_fit) = P.csd_msmt(dwi * s0_factor[..., None], meas, mask, backend=self.backend)
|
| 1117 |
+
seconds = {"csd · responses: three_tissue_response_dhollander16": t_resp, f"csd · MT-CSD: csd_msmt_{self.backend}": t_fit}
|
| 1118 |
+
responses = dict(zip(TISSUES, zip(S0s, models))); path = f"multi-tissue: three_tissue_response_dhollander16 + csd_msmt_{self.backend}"
|
| 1119 |
+
t0 = time.perf_counter()
|
| 1120 |
+
extras = dict(reconstruction=path, fractions=None if fractions is None else fractions.astype(np.float32),
|
| 1121 |
+
responses=estimated_profile(responses, meas), roundtrip=self.roundtrip(sh, fractions))
|
| 1122 |
+
seconds["round trip · the FOD and fractions against the input"] = time.perf_counter() - t0
|
| 1123 |
+
return sh, seconds, extras
|
| 1124 |
+
|
| 1125 |
+
def roundtrip(self, sh, fractions):
|
| 1126 |
+
"""The recovered FOD against the asset's in the WM (the stop mask's voxels): the principal peaks' angle
|
| 1127 |
+
(median, 95 %), the Pearson of the l = 0 coefficient (the apparent fibre density), the share of voxels whose
|
| 1128 |
+
peak count (up to three) agrees; with fractions, their Pearson per tissue and median absolute difference
|
| 1129 |
+
over the brain."""
|
| 1130 |
+
wm = self.asset.stop
|
| 1131 |
+
rec = P.fod_peaks(np.asarray(sh)[wm]); ref = P.fod_peaks(self.asset.fod[wm])
|
| 1132 |
+
cosang = np.abs(np.einsum("ij,ij->i", rec[0][:, 0], ref[0][:, 0]))
|
| 1133 |
+
both = (rec[1][:, 0] > 0) & (ref[1][:, 0] > 0)
|
| 1134 |
+
ang = np.degrees(np.arccos(np.clip(cosang[both], 0, 1)))
|
| 1135 |
+
afd_rec = np.asarray(sh)[wm][:, 0] * (1.0 if fractions is None else fractions[wm][:, 0]) # the WM signal's l = 0 amplitude
|
| 1136 |
+
afd_in = self.asset.fod[wm][:, 0] * self.asset.fractions[wm][:, 0]
|
| 1137 |
+
out = dict(peak_angle_median=float(np.median(ang)) if ang.size else float("nan"), peak_angle_p95=float(np.quantile(ang, 0.95)) if ang.size else float("nan"),
|
| 1138 |
+
afd_pearson=P.pearson(afd_rec, afd_in),
|
| 1139 |
+
peak_count_agreement=float(np.mean(rec[2] == ref[2])), n_wm=int(wm.sum()),
|
| 1140 |
+
peak_counts_recovered=np.bincount(rec[2], minlength=4)[:4].tolist(), peak_counts_input=np.bincount(ref[2], minlength=4)[:4].tolist())
|
| 1141 |
+
if fractions is not None:
|
| 1142 |
+
m = self.mask
|
| 1143 |
+
for k, t in enumerate(TISSUES):
|
| 1144 |
+
out[f"fraction_{t}_pearson"] = P.pearson(fractions[m][:, k], self.asset.fractions[m][:, k])
|
| 1145 |
+
out[f"fraction_{t}_mad"] = float(np.median(np.abs(fractions[m][:, k] - self.asset.fractions[m][:, k])))
|
| 1146 |
+
return out
|
| 1147 |
+
|
| 1148 |
+
def tracking_inputs(self, sh, density):
|
| 1149 |
+
"""``(field, seeds)``: the FOD turned from the image frame into the scanner frame on the asset's affine, the
|
| 1150 |
+
domain the white matter and the regions (leaving it ends a streamline), ``density^3`` seeds per WM voxel."""
|
| 1151 |
+
from dmipy_sim.replay.so3 import rotate_sh
|
| 1152 |
+
from dmipy_tract import FODField, seeds_from_mask
|
| 1153 |
+
a = self.asset
|
| 1154 |
+
world = np.zeros(np.shape(sh), np.float32)
|
| 1155 |
+
world[self.mask] = rotate_sh(np.asarray(sh)[self.mask], a.R).astype(np.float32)
|
| 1156 |
+
return FODField(world, a.affine, a.stop | (a.labels > 0)), seeds_from_mask(a.stop, a.affine, density=density)
|
| 1157 |
+
|
| 1158 |
+
def reference(self, tracking, seeds):
|
| 1159 |
+
"""The truth: the asset's own FOD tracked with ``tracking`` from ``seeds`` (the same tracker, settings, seeds
|
| 1160 |
+
and key as the run), its connectome and lobar sum; computed once per (settings, seeds) and reused (B shares
|
| 1161 |
+
A's)."""
|
| 1162 |
+
key = (tracking, len(seeds), float(np.asarray(seeds).sum()))
|
| 1163 |
+
if key in self._reference:
|
| 1164 |
+
return self._reference[key], 0.0
|
| 1165 |
+
t0 = time.perf_counter()
|
| 1166 |
+
fld, _ = self.tracking_inputs(self.asset.fod, tracking.density)
|
| 1167 |
+
tg, _ = P.track(fld, seeds, tracking, self.backend)
|
| 1168 |
+
M = self.regions.matrix(tg)
|
| 1169 |
+
ref = dict(matrix=M, lobar=self.regions.grouped(M), streamlines=len(tg))
|
| 1170 |
+
self._reference = {key: ref}
|
| 1171 |
+
return ref, time.perf_counter() - t0
|
| 1172 |
+
|
| 1173 |
+
def score(self, M, reference):
|
| 1174 |
+
"""Against the truth's connectome: Pearson of log(1 + count) over the region pairs (``pearson_log``), the
|
| 1175 |
+
pairs connected in the run only and in the truth only, and the same Pearson over the lobar groups' upper
|
| 1176 |
+
triangle with the diagonal (the within-group counts)."""
|
| 1177 |
+
T = reference["matrix"]; pairs = self.regions.pairs
|
| 1178 |
+
a, b = M[pairs], T[pairs]
|
| 1179 |
+
G, Gt = self.regions.grouped(M), reference["lobar"]
|
| 1180 |
+
gp = np.triu_indices(len(G))
|
| 1181 |
+
return dict(pearson_log=P.pearson(np.log1p(a), np.log1p(b)), connected_pairs=int((a > 0).sum()), truth_pairs=int((b > 0).sum()),
|
| 1182 |
+
only_run=int(((a > 0) & (b == 0)).sum()), only_truth=int(((a == 0) & (b > 0)).sum()),
|
| 1183 |
+
lobar_pearson_log=P.pearson(np.log1p(G[gp]), np.log1p(Gt[gp])), n_pairs=len(pairs[0]))
|
| 1184 |
+
|
| 1185 |
+
def compare(self, a, b):
|
| 1186 |
+
"""A against B over the region pairs: the Pearson of log(1 + count) between the two, the pairs connected in
|
| 1187 |
+
one only, and B's score minus A's."""
|
| 1188 |
+
pairs = self.regions.pairs
|
| 1189 |
+
ma, mb = a.matrix[pairs], b.matrix[pairs]
|
| 1190 |
+
return dict(pearson_ab=P.pearson(np.log1p(ma), np.log1p(mb)), only_a=int(((ma > 0) & (mb == 0)).sum()),
|
| 1191 |
+
only_b=int(((mb > 0) & (ma == 0)).sum()), delta_log=b.score["pearson_log"] - a.score["pearson_log"])
|
| 1192 |
+
|
| 1193 |
+
def score_key(self):
|
| 1194 |
+
return "pearson_log"
|
| 1195 |
+
|
| 1196 |
+
def ladder_steps(self, physics):
|
| 1197 |
+
"""The rungs below ``physics``: bare diffusion (the tiers off, the same proton densities and packs), then the
|
| 1198 |
+
tiers on one at a time."""
|
| 1199 |
+
if physics is None or physics.bare:
|
| 1200 |
+
return []
|
| 1201 |
+
steps = [("bare diffusion", replace(physics, **{q: False for q in self.TIERS}))]
|
| 1202 |
+
wanted = [q for q in self.TIERS if getattr(physics, q)]
|
| 1203 |
+
on = []
|
| 1204 |
+
for tier in wanted[:-1]:
|
| 1205 |
+
on.append(tier)
|
| 1206 |
+
steps.append(("+ " + " + ".join(on), replace(physics, **{q: q in on for q in self.TIERS})))
|
| 1207 |
+
return steps
|
| 1208 |
+
|
| 1209 |
+
def ingredients(self, meas, physics=None, prepared=None):
|
| 1210 |
+
"""The per-voxel maps of what the tissue multiplies into the b = 0 signal: ``m0`` (Σ f·M0), ``relaxation``
|
| 1211 |
+
(the voxel's b = 0 weight from T2 / T1 alone), ``contact`` (the share the WM walls' surface relaxivity leaves
|
| 1212 |
+
of it), and ``tiers``, the per-tissue weights they are made of."""
|
| 1213 |
+
if prepared is None:
|
| 1214 |
+
return None
|
| 1215 |
+
f = self.asset.fractions; m0 = prepared.m0
|
| 1216 |
+
w = {t: f[..., k] * m0[t] for k, t in enumerate(TISSUES)}
|
| 1217 |
+
total = sum(w.values())
|
| 1218 |
+
out = dict(m0=np.where(self.mask, total, np.nan).astype(np.float32), relaxation=None, contact=None, tiers=prepared.b0)
|
| 1219 |
+
with np.errstate(invalid="ignore", divide="ignore"):
|
| 1220 |
+
if "relaxation" in (prepared.b0 or {}):
|
| 1221 |
+
r = prepared.b0["relaxation"]
|
| 1222 |
+
relaxed = sum(w[t] * r[t] for t in TISSUES)
|
| 1223 |
+
out["relaxation"] = np.where(self.mask & (total > 0), relaxed / total, np.nan).astype(np.float32)
|
| 1224 |
+
if "contact" in (prepared.b0 or {}):
|
| 1225 |
+
c = prepared.b0["contact"]["wm"]
|
| 1226 |
+
out["contact"] = np.where(self.mask & (total > 0), (w["wm"] * c + w["gm"] + w["csf"]) / total, np.nan).astype(np.float32)
|
| 1227 |
+
return out
|
| 1228 |
+
|
| 1229 |
+
def accuracy(self, res=None):
|
| 1230 |
+
a = self.asset.manifest
|
| 1231 |
+
rows = [["subject", str(a["subject"])], ["source", f"{a['source'].get('dataset')} ({a['source'].get('license')})"],
|
| 1232 |
+
["asset", self.where], ["grid (cropped to the brain)", f"{self.mask.shape}, {int(self.mask.sum()):,} voxels, "
|
| 1233 |
+
f"{int(self.asset.stop.sum()):,} in the WM stop mask"],
|
| 1234 |
+
["regions", f"{self.regions.n} ({len(self.regions.groups)} lobar groups)"],
|
| 1235 |
+
["the scan's timing class", self.shapes[SCAN]["label"]],
|
| 1236 |
+
*[list(n) for n in self.asset.notes],
|
| 1237 |
+
["replay", "exact composition of the packs' pose responses (dmipy-sim's phantom route), float32 on the device"],
|
| 1238 |
+
["per-voxel split-half floor", "none: every voxel reads the same two walks; the packs' certified floors below are the accuracy"]]
|
| 1239 |
+
for (tissue, label), pk in self.packs.items():
|
| 1240 |
+
seg = self.segments(tissue, label); held = self.windows_held(pk, seg)
|
| 1241 |
+
rows.append([f"{tissue.upper()} pack {label}", f"{pk.meta.get('id')}, {pk.n_walkers:,} walkers, {self.walk_seconds(pk) * 1e3:g} ms walk, "
|
| 1242 |
+
f"windows held / declared {held} / {seg['n']} of {float(seg['T']) * 1e3:g} ms "
|
| 1243 |
+
f"({self.saves_spanned(seg, held):,} of {self.saves_spanned(seg, seg['n']):,} saves at "
|
| 1244 |
+
f"{float(seg['T']) / (int(seg['n_t']) - 1) * 1e6:.4g} µs), certified floor (max) {_floor(pk):.4g}"])
|
| 1245 |
+
return rows + super().accuracy(res)
|
| 1246 |
+
|
| 1247 |
+
def score_text(self, tag, res):
|
| 1248 |
+
s = res.score; physics = res.physics; rt = res.extras.get("roundtrip") or {}
|
| 1249 |
+
snr = P.b0_snr(res)
|
| 1250 |
+
noise = "" if snr is None else f", SNR {res.snr:g} at M0 = 1 ({snr['median']:.1f} at b = 0 in the median voxel)"
|
| 1251 |
+
return (f"**{tag}: connectome vs the input's, Pearson log(1 + count) {s['pearson_log']:.3f}** (lobar {s['lobar_pearson_log']:.3f}; "
|
| 1252 |
+
f"{s['only_run']} pairs in the run only, {s['only_truth']} in the input's only); FOD round trip: principal peak "
|
| 1253 |
+
f"{rt.get('peak_angle_median', float('nan')):.1f}° median / {rt.get('peak_angle_p95', float('nan')):.1f}° 95 %, AFD r "
|
| 1254 |
+
f"{rt.get('afd_pearson', float('nan')):.3f} ({res.protocol.n_meas} measurements, {physics.label() if physics else 'bare'}{noise}, "
|
| 1255 |
+
f"{len(res.tractogram):,} streamlines, {res.seconds['total']:.1f} s; {res.extras.get('reconstruction', '')})")
|
| 1256 |
+
|
| 1257 |
+
def compare_text(self, c, knob):
|
| 1258 |
+
return (f"**A vs B: connectome Pearson log(1 + count) {c['pearson_ab']:.3f}**, {c['only_a']} pairs in A only, {c['only_b']} in B only, "
|
| 1259 |
+
f"B − A {c['delta_log']:+.3f} vs the input's connectome; B = A with {knob}.")
|
| 1260 |
+
|
| 1261 |
+
def matrices(self, M, score, reference):
|
| 1262 |
+
from .. import viewers as V
|
| 1263 |
+
return V.pair_panel([(f"this run (Pearson log {score['pearson_log']:.3f})", M), ("the input FOD tracked the same way", reference["matrix"])],
|
| 1264 |
+
f"{score['connected_pairs']} of {score['n_pairs']} pairs connected, the input's {score['truth_pairs']}; "
|
| 1265 |
+
f"{score['only_run']} in the run only, {score['only_truth']} in the input's only", names=self.regions.names)
|
| 1266 |
+
|
| 1267 |
+
def lobar(self, M, score, reference):
|
| 1268 |
+
from .. import viewers as V
|
| 1269 |
+
return V.pair_panel([(f"lobar groups, this run (Pearson log {score['lobar_pearson_log']:.3f})", self.regions.grouped(M)),
|
| 1270 |
+
("lobar groups, the input", reference["lobar"])], "the connectome summed over the lobar groups",
|
| 1271 |
+
names=tuple(n for n, _ in self.regions.groups))
|
| 1272 |
+
|
| 1273 |
+
@staticmethod
|
| 1274 |
+
def ingredient_layers(ing):
|
| 1275 |
+
if not ing:
|
| 1276 |
+
return [None, None, None]
|
| 1277 |
+
return [("proton density Σ f·M0 (relative to CSF)", ing["m0"], dict(vmin=0, vmax=1)),
|
| 1278 |
+
("relaxation: the voxel's b = 0 weight from T2 / T1 at the echo", ing["relaxation"], dict(cmap="magma", vmin=0, vmax=1)) if ing.get("relaxation") is not None else None,
|
| 1279 |
+
("contact: the share of the b = 0 signal the WM walls' ρ₂ leaves", ing["contact"], dict(cmap="magma", vmax=1)) if ing.get("contact") is not None else None]
|
| 1280 |
+
|
| 1281 |
+
@functools.cached_property
|
| 1282 |
+
def input_peaks(self):
|
| 1283 |
+
"""The asset's WM FOD principal peaks and amplitudes (image frame), for the slices."""
|
| 1284 |
+
return P.peaks(self.asset.fod)
|
| 1285 |
+
|
| 1286 |
+
def truth_view(self, dwi, meas, z, m):
|
| 1287 |
+
from .. import viewers as V
|
| 1288 |
+
pk, amp = self.input_peaks
|
| 1289 |
+
return V.dwi_slice(dwi, meas, z, m, peaks=pk, peak_amp=amp, overlay=True, label="the input FOD's peaks · ")
|
| 1290 |
+
|
| 1291 |
+
def fractions_view(self, extras, z):
|
| 1292 |
+
from .. import viewers as V
|
| 1293 |
+
return V.fractions_pair(extras.get("fractions"), self.asset.fractions, z)
|
| 1294 |
+
|
| 1295 |
+
def roundtrip_rows(self, res):
|
| 1296 |
+
rt = res.extras.get("roundtrip") or {}
|
| 1297 |
+
rows = [["reconstruction", res.extras.get("reconstruction", "")],
|
| 1298 |
+
["principal peak vs the input's, WM voxels: median / 95 % (°)", f"{rt.get('peak_angle_median', float('nan')):.2f} / {rt.get('peak_angle_p95', float('nan')):.2f}"],
|
| 1299 |
+
["AFD (the WM signal's l = 0 amplitude: the FOD's, times the WM fraction where one is fitted) Pearson, WM voxels", f"{rt.get('afd_pearson', float('nan')):.4f}"],
|
| 1300 |
+
["peak count agreement (up to 3), WM voxels", f"{100 * rt.get('peak_count_agreement', float('nan')):.1f} % of {rt.get('n_wm', 0):,}"],
|
| 1301 |
+
["voxels with 0 / 1 / 2 / 3 peaks: recovered", " / ".join(str(x) for x in rt.get("peak_counts_recovered", []))],
|
| 1302 |
+
["voxels with 0 / 1 / 2 / 3 peaks: input", " / ".join(str(x) for x in rt.get("peak_counts_input", []))]]
|
| 1303 |
+
for t in TISSUES:
|
| 1304 |
+
if f"fraction_{t}_pearson" in rt:
|
| 1305 |
+
rows.append([f"{t.upper()} fraction vs the input's: Pearson / median |Δ|", f"{rt[f'fraction_{t}_pearson']:.4f} / {rt[f'fraction_{t}_mad']:.4f}"])
|
| 1306 |
+
if "fraction_wm_pearson" not in rt:
|
| 1307 |
+
rows.append(["fractions", "not estimated by the single-tissue reconstruction"])
|
| 1308 |
+
s = res.score
|
| 1309 |
+
rows += [["connectome vs the input's: Pearson log(1 + count), region pairs", f"{s['pearson_log']:.4f}"],
|
| 1310 |
+
["the same over the lobar groups", f"{s['lobar_pearson_log']:.4f}"],
|
| 1311 |
+
["pairs connected: run / input / run only / input only", f"{s['connected_pairs']} / {s['truth_pairs']} / {s['only_run']} / {s['only_truth']} of {s['n_pairs']}"],
|
| 1312 |
+
["streamlines: run / input", f"{len(res.tractogram):,} / {res.reference['streamlines']:,}"]]
|
| 1313 |
+
return rows
|
| 1314 |
+
|
| 1315 |
+
def response_view(self, prepared, extras):
|
| 1316 |
+
from .. import viewers as V
|
| 1317 |
+
est = extras.get("responses")
|
| 1318 |
+
note = "" if est is not None and est.get("gm") is not None else "estimated: WM only, the single-tissue reconstruction"
|
| 1319 |
+
return V.response_curves(prepared.profile if prepared is not None else None, est, note=note)
|
| 1320 |
+
|
| 1321 |
+
def extra_files(self, res, out_dir, stem):
|
| 1322 |
+
"""The connectome and its lobar sum as CSV, the regions' names as the header."""
|
| 1323 |
+
import csv
|
| 1324 |
+
paths = []
|
| 1325 |
+
for what, M, names in (("connectome", res.matrix, self.regions.names), ("lobar", self.regions.grouped(res.matrix), tuple(n for n, _ in self.regions.groups))):
|
| 1326 |
+
path = os.path.join(out_dir, f"{stem}_{what}.csv")
|
| 1327 |
+
with open(path, "w", newline="") as f:
|
| 1328 |
+
w = csv.writer(f); w.writerow([""] + list(names))
|
| 1329 |
+
for name, row in zip(names, M):
|
| 1330 |
+
w.writerow([name] + [f"{v:g}" for v in row])
|
| 1331 |
+
paths.append(path)
|
| 1332 |
+
return paths
|
| 1333 |
+
|
| 1334 |
+
def truth_views(self):
|
| 1335 |
+
"""The input tab: the region centroids in 3-D coloured by lobe, and a slice of the input (the WM FOD's principal
|
| 1336 |
+
peaks over the mean b = 0, the fractions, the labels)."""
|
| 1337 |
+
from .. import viewers as V
|
| 1338 |
+
a = self.asset
|
| 1339 |
+
pk, amp = P.peaks(a.fod)
|
| 1340 |
+
z = self.mask.shape[2] // 2
|
| 1341 |
+
return (V.regions3d(self.regions, self.mask.shape), V.input_slices(a.b0, pk, amp, a.fractions, a.labels, z))
|
| 1342 |
+
|
| 1343 |
+
|
| 1344 |
+
def _warm_worker(cfg, where, entries, queue):
|
| 1345 |
+
"""The warm-up's process (:meth:`Brain.warm_in_background`): its own :class:`Brain` on the same configuration
|
| 1346 |
+
and asset, every ``(meas, physics)`` of ``entries`` computed on the CPU and put on ``queue`` as
|
| 1347 |
+
``(response_key, Kernels)``, then ``None``. One line per entry on stdout (the Space's run log) with its index,
|
| 1348 |
+
the seconds it took, :attr:`Kernels.stages`, the pose expansion's phases (dmipy-sim's run record, which the
|
| 1349 |
+
expansion joins), the process's user and system CPU seconds and page faults over the entry (a system-bound entry
|
| 1350 |
+
is paying the kernel, for pages or I/O, not computing) and the seconds since the start."""
|
| 1351 |
+
os.environ.setdefault("JAX_PLATFORMS", "cpu")
|
| 1352 |
+
t0 = time.perf_counter()
|
| 1353 |
+
from ..limits import cpu_quota, THREAD_VARS
|
| 1354 |
+
print(f"warm-up: process {os.getpid()} starts on {len(entries)} entries, {len(os.sched_getaffinity(0))} CPUs visible, "
|
| 1355 |
+
f"cgroup CPU quota {cpu_quota()}, cpuset {_cgroup_cpuset()}, threads {os.environ.get(THREAD_VARS[0], 'unset')}, "
|
| 1356 |
+
f"memory limit {_cgroup_memory_limit()}, memory.high {_cgroup_memory_high()}, memory.events {_cgroup_memory_events()}", flush=True)
|
| 1357 |
+
try:
|
| 1358 |
+
src = Brain(cfg, asset=where)
|
| 1359 |
+
print(f"warm-up: the source loaded, RSS {_rss_gb():.1f} GB ({time.perf_counter() - t0:.0f} s since the start)", flush=True)
|
| 1360 |
+
from dmipy_sim.run import Run
|
| 1361 |
+
import resource
|
| 1362 |
+
for i, (meas, ph) in enumerate(entries, 1):
|
| 1363 |
+
t = time.perf_counter(); r0 = resource.getrusage(resource.RUSAGE_SELF)
|
| 1364 |
+
with Run("brain-warm", params=dict(entry=i)) as run: # the pose expansion's phases join this record
|
| 1365 |
+
kernels = src.prepare(meas, ph)
|
| 1366 |
+
r1 = resource.getrusage(resource.RUSAGE_SELF)
|
| 1367 |
+
phases = ", ".join(f"{n} {v:.1f}" for n, v in run.phase_seconds().items())
|
| 1368 |
+
usage = (f"user {r1.ru_utime - r0.ru_utime:.0f} s, system {r1.ru_stime - r0.ru_stime:.0f} s, "
|
| 1369 |
+
f"minor faults {r1.ru_minflt - r0.ru_minflt}, major faults {r1.ru_majflt - r0.ru_majflt}")
|
| 1370 |
+
queue.put((src.response_key(meas, ph), kernels))
|
| 1371 |
+
windows = {t: src.windows_needed(t, label, meas) for t, label in (("wm", ph.wm_pack), ("gm", ph.gm_pack))}
|
| 1372 |
+
print(f"warm-up {i}/{len(entries)}: {len(meas.bvals)} measurements, WM {ph.wm_pack!r} ({windows['wm']} window(s)), "
|
| 1373 |
+
f"GM {ph.gm_pack!r} ({windows['gm']} window(s)), {ph.field_T:g} T along {ph.b0_direction}, "
|
| 1374 |
+
f"tiers {'on' if ph.field else 'off'}: {time.perf_counter() - t:.1f} s "
|
| 1375 |
+
f"({', '.join(f'{n} {v:.1f}' for n, v in (kernels.stages or {}).items())}; phases {phases}; {usage}), RSS {_rss_gb():.1f} GB, "
|
| 1376 |
+
f"memory.events {_cgroup_memory_events()} ({time.perf_counter() - t0:.0f} s since the start)", flush=True)
|
| 1377 |
+
finally:
|
| 1378 |
+
queue.put(None)
|
| 1379 |
+
|
| 1380 |
+
|
| 1381 |
+
def _rss_gb():
|
| 1382 |
+
"""This process's resident set in GB (VmRSS of /proc/self/status; nan where there is no procfs)."""
|
| 1383 |
+
try:
|
| 1384 |
+
with open("/proc/self/status") as f:
|
| 1385 |
+
for line in f:
|
| 1386 |
+
if line.startswith("VmRSS:"):
|
| 1387 |
+
return int(line.split()[1]) / 1e6
|
| 1388 |
+
except OSError:
|
| 1389 |
+
pass
|
| 1390 |
+
return float("nan")
|
| 1391 |
+
|
| 1392 |
+
|
| 1393 |
+
def _cgroup_cpuset():
|
| 1394 |
+
"""The CPUs the container may run on as its cgroup states them (v2 ``cpuset.cpus.effective``), ``'unknown'``
|
| 1395 |
+
where the file does not exist."""
|
| 1396 |
+
try:
|
| 1397 |
+
with open("/sys/fs/cgroup/cpuset.cpus.effective") as f:
|
| 1398 |
+
return f.read().strip() or "unknown"
|
| 1399 |
+
except OSError:
|
| 1400 |
+
return "unknown"
|
| 1401 |
+
|
| 1402 |
+
|
| 1403 |
+
def _cgroup_memory_high():
|
| 1404 |
+
"""The cgroup's memory.high (v2), the throttling threshold below memory.max: ``'max'`` when unset, in GB
|
| 1405 |
+
otherwise, ``'unknown'`` where the file does not exist."""
|
| 1406 |
+
try:
|
| 1407 |
+
with open("/sys/fs/cgroup/memory.high") as f:
|
| 1408 |
+
v = f.read().strip()
|
| 1409 |
+
return v if v == "max" else f"{int(v) / 1e9:.1f} GB"
|
| 1410 |
+
except OSError:
|
| 1411 |
+
return "unknown"
|
| 1412 |
+
|
| 1413 |
+
|
| 1414 |
+
def _cgroup_memory_events():
|
| 1415 |
+
"""The cgroup's memory.events (v2) as ``{name: count}`` (``high`` counts the times memory.high throttled the
|
| 1416 |
+
group, ``max`` the times memory.max was hit); empty where the file does not exist."""
|
| 1417 |
+
try:
|
| 1418 |
+
with open("/sys/fs/cgroup/memory.events") as f:
|
| 1419 |
+
return {k: int(v) for k, v in (line.split() for line in f if line.strip())}
|
| 1420 |
+
except OSError:
|
| 1421 |
+
return {}
|
| 1422 |
+
|
| 1423 |
+
|
| 1424 |
+
def _cgroup_memory_limit():
|
| 1425 |
+
"""The container's memory limit as the cgroup states it (v2 ``memory.max``, v1 ``memory.limit_in_bytes``), in GB,
|
| 1426 |
+
``'max'`` when unlimited, ``'unknown'`` where neither file exists."""
|
| 1427 |
+
for path in ("/sys/fs/cgroup/memory.max", "/sys/fs/cgroup/memory/memory.limit_in_bytes"):
|
| 1428 |
+
try:
|
| 1429 |
+
with open(path) as f:
|
| 1430 |
+
v = f.read().strip()
|
| 1431 |
+
except OSError:
|
| 1432 |
+
continue
|
| 1433 |
+
return v if v == "max" else f"{int(v) / 1e9:.1f} GB"
|
| 1434 |
+
return "unknown"
|
| 1435 |
+
|
| 1436 |
+
|
| 1437 |
+
def _floor(pack):
|
| 1438 |
+
return float((pack.meta.get("fidelity") or {}).get("floor_max") or float("nan"))
|
| 1439 |
+
|
| 1440 |
+
|
| 1441 |
+
@functools.lru_cache(maxsize=1)
|
| 1442 |
+
def axis_map():
|
| 1443 |
+
"""``(n_so3(8, 0), 45)``: a compact even-order density's harmonics to its SO(3) coefficients
|
| 1444 |
+
(:func:`dmipy_sim.replay.so3.axis_density_coeffs`, which is linear), so ``resp.retained(8, 0) @ axis_map()`` is the
|
| 1445 |
+
response contracted to the FOD's harmonics."""
|
| 1446 |
+
from dmipy_sim.replay import so3
|
| 1447 |
+
return np.stack([so3.axis_density_coeffs(e, LMAX, 0) for e in np.eye(N_COEF)], 1)
|
| 1448 |
+
|
| 1449 |
+
|
| 1450 |
+
def estimated_profile(responses, meas):
|
| 1451 |
+
"""The estimated response curves at the explorer's profile (the shells of ``meas``, :data:`PROFILE_ANGLES`): the
|
| 1452 |
+
WM response a fibre along z gives each gradient angle, GM's and CSF's isotropic signal, each over its b = 0
|
| 1453 |
+
value, from the models the reconstruction estimated (``{tissue: (S0, model)}``); ``None`` for a tissue it did not
|
| 1454 |
+
estimate."""
|
| 1455 |
+
from dmipy_fit.core.acquisition_scheme import acquisition_scheme_from_bvalues
|
| 1456 |
+
rows = meas.shape == meas.shape[0]
|
| 1457 |
+
shells = np.unique(np.round(meas.bvals[rows & ~meas.b0]))
|
| 1458 |
+
if not shells.size:
|
| 1459 |
+
return None
|
| 1460 |
+
th = np.radians(PROFILE_ANGLES)
|
| 1461 |
+
dirs = np.stack([np.sin(th), np.zeros_like(th), np.cos(th)], 1)
|
| 1462 |
+
b = np.concatenate([[0.0], np.repeat(shells, len(th))]); g = np.concatenate([[[0.0, 0.0, 1.0]], np.tile(dirs, (len(shells), 1))])
|
| 1463 |
+
i = int(np.flatnonzero(rows)[0])
|
| 1464 |
+
sch = acquisition_scheme_from_bvalues(b * 1e6, g, delta=np.full(len(b), meas.delta[i]), Delta=np.full(len(b), meas.Delta[i]),
|
| 1465 |
+
TE=np.full(len(b), meas.TE[i]), b0_threshold=P.B0_MAX * 1e6)
|
| 1466 |
+
out = dict(b=shells, angles=PROFILE_ANGLES)
|
| 1467 |
+
for t in TISSUES:
|
| 1468 |
+
if t not in responses:
|
| 1469 |
+
out[t] = None
|
| 1470 |
+
continue
|
| 1471 |
+
_, model = responses[t]
|
| 1472 |
+
E = np.asarray(model(sch, mu=[0.0, 0.0]) if t == "wm" else model(sch), np.float64)
|
| 1473 |
+
E = (E[1:] / E[0]).reshape(len(shells), len(th))
|
| 1474 |
+
out[t] = E if t == "wm" else E[:, 0]
|
| 1475 |
+
return out
|
space/sources/disco.py
ADDED
|
@@ -0,0 +1,590 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""The DiSCo source: the DiSCo phantom's 40^3 grid replayed from its stored walk, tracked from the sixteen regions
|
| 2 |
+
and scored against the dataset's strand-count and cross-sectional-area matrices (CC BY 4.0, ``data/SOURCE.md``).
|
| 3 |
+
|
| 4 |
+
Two sources replay the same walk. :class:`Layout` (demo mode) is dmipy-sim's shape-moment layout: the DiSCo replay
|
| 5 |
+
pack contracted once per stored pulse timing ("class"), so a protocol on those classes at any b-values, directions,
|
| 6 |
+
tissue and field is an elementwise kernel on device-resident rows, in seconds. :class:`Columns` (full mode) is the
|
| 7 |
+
columnar replay pack itself, read once per run for any pulse timing, in minutes. Both are a :class:`Disco`: the
|
| 8 |
+
page's texts, the tissue panel of the white-matter catalogue, the regions, the ground truth and the GPU budget.
|
| 9 |
+
"""
|
| 10 |
+
from __future__ import annotations
|
| 11 |
+
|
| 12 |
+
import os
|
| 13 |
+
import time
|
| 14 |
+
|
| 15 |
+
import numpy as np
|
| 16 |
+
|
| 17 |
+
from .. import pipeline as P
|
| 18 |
+
|
| 19 |
+
N_REGIONS = 16
|
| 20 |
+
VOXEL_M = 25e-6 # DiSCo's voxel; the strands' coordinate unit
|
| 21 |
+
B0_MODES = {"along z (the strands' frame)": P.B0_ALONG_Z, "transverse (x): 90° from z, as in a biplanar magnet like the Swoop": P.B0_TRANSVERSE}
|
| 22 |
+
#: the scanner axes the phantom can be moved along from isocentre (the strands' frame is the scanner's: R, A, S)
|
| 23 |
+
OFFSET_AXES = {"R-L (x)": (1.0, 0.0, 0.0), "A-P (y)": (0.0, 1.0, 0.0), "S-I (z)": (0.0, 0.0, 1.0)}
|
| 24 |
+
FREE_B0 = "free (polar and azimuth angles below)"
|
| 25 |
+
DISCO_364 = "DiSCo 364"
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def disco_protocol(cfg):
|
| 29 |
+
"""DiSCo's own 364-measurement protocol (its gradient table, its per-shell timing classes from ``[disco]``) as
|
| 30 |
+
a Protocol with every row's own direction and b-value: the acquisition the reference volumes were replayed with.
|
| 31 |
+
Returns it and the table rows in the protocol's order (the reference volumes follow the table's)."""
|
| 32 |
+
bv = np.loadtxt(os.path.join(P.DATA_DIR, "DiSCo_gradients.bvals")).ravel()
|
| 33 |
+
dirs = np.loadtxt(os.path.join(P.DATA_DIR, "DiSCo_gradients_dipy.bvecs"))
|
| 34 |
+
if dirs.shape[0] == 3:
|
| 35 |
+
dirs = dirs.T
|
| 36 |
+
shells = cfg["disco"]["shells"] # [{b, shape}] in the table's row order
|
| 37 |
+
centres = np.array([s["b"] for s in shells])
|
| 38 |
+
which = np.argmin(np.abs(bv[:, None] - centres[None, :]), axis=1)
|
| 39 |
+
return P.protocol_from_rows(bv, dirs, which, lambda k, rows: P.Shell(shells[k]["shape"], float(np.round(bv[rows].mean())), int(len(rows))),
|
| 40 |
+
name=DISCO_364)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def pools(cfg):
|
| 44 |
+
"""The seeded pools the panel offers T2 and T1 for."""
|
| 45 |
+
return tuple(cfg["physics"]["pools"])
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def physics_fields(cfg):
|
| 49 |
+
"""The panel's inputs, in the run signature's order."""
|
| 50 |
+
q = pools(cfg)
|
| 51 |
+
return ("on", "field_T", "b0_mode", "theta", "phi", *[f"T2_{p}" for p in q], *[f"T1_{p}" for p in q],
|
| 52 |
+
"rho2", "chi_iso", "chi_aniso", "relaxation", "contact", "field", "offset_cm", "offset_axis")
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def tissue_numbers(cfg):
|
| 56 |
+
"""The panel's inputs the catalogue fills in: ms, ms, µm/s, ppm on the page."""
|
| 57 |
+
q = pools(cfg)
|
| 58 |
+
return (*[f"T2_{p}" for p in q], *[f"T1_{p}" for p in q], "rho2", "chi_iso", "chi_aniso")
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
class Disco(P.Source):
|
| 62 |
+
"""What a DiSCo replay source has beside its replay data: the DiSCo mask, the sixteen regions, the two
|
| 63 |
+
ground-truth matrices, the config's timing classes and seeded pools, the compute backend; the page's DiSCo texts,
|
| 64 |
+
presets, tissue panel and knobs; the tracker seeded in the regions on the voxel grid (the millimetre frame is
|
| 65 |
+
the voxel frame); the score against the strand count and the cross-sectional area."""
|
| 66 |
+
TIERS = ("relaxation", "contact", "field")
|
| 67 |
+
|
| 68 |
+
def __init__(self, cfg):
|
| 69 |
+
import nibabel as nib
|
| 70 |
+
super().__init__(cfg)
|
| 71 |
+
self.pools = pools(cfg)
|
| 72 |
+
self.mask = np.asarray(nib.load(os.path.join(P.DATA_DIR, "DiSCo_mask.nii.gz")).dataobj) > 0
|
| 73 |
+
self.rois = np.asarray(nib.load(os.path.join(P.DATA_DIR, "DiSCo_ROIs.nii.gz")).dataobj).astype(np.int32)
|
| 74 |
+
self.gt_count = np.loadtxt(os.path.join(P.DATA_DIR, "DiSCo_Connectivity_Matrix_Strands_Count.txt"))
|
| 75 |
+
self.gt_area = np.loadtxt(os.path.join(P.DATA_DIR, "DiSCo_Connectivity_Matrix_Cross-Sectional_Area.txt"))
|
| 76 |
+
self.affine = np.eye(4)
|
| 77 |
+
self.regions = P.Regions(self.rois, self.affine, tuple(str(k) for k in range(1, N_REGIONS + 1)))
|
| 78 |
+
|
| 79 |
+
def check_grid(self, grid_shape, what):
|
| 80 |
+
if tuple(grid_shape) != self.mask.shape:
|
| 81 |
+
raise ValueError(f"{what}'s grid {tuple(grid_shape)} is not the mask's {self.mask.shape}")
|
| 82 |
+
|
| 83 |
+
# ---- the page's side ----
|
| 84 |
+
@classmethod
|
| 85 |
+
def describe(cls, cfg):
|
| 86 |
+
full = P.mode(cfg) == "full"
|
| 87 |
+
shapes = cfg["shapes"]
|
| 88 |
+
return dict(
|
| 89 |
+
title="DiSCo replay to tractogram",
|
| 90 |
+
heading=("# DiSCo: one Monte-Carlo walk, any acquisition, a connectome\n"
|
| 91 |
+
"The DiSCo phantom's walkers were simulated once (SubstrateCommons/disco-replay). Choose an acquisition; the Space "
|
| 92 |
+
"replays the whole 40³ grid from the stored walk, adds noise, fits constrained spherical deconvolution, tracks from "
|
| 93 |
+
"the sixteen regions and scores the connectome against the ground truth. The progress bar names each stage."),
|
| 94 |
+
acquisition=("**Full mode**: the columnar replay pack is read for every run, so a shell's δ / Δ / TE are free "
|
| 95 |
+
"(one TE and one pulse kind per run, square pulses, the field along z) and a Camino `.scheme` file "
|
| 96 |
+
"can be uploaded; a run takes minutes, the plan shown first says how many.") if full else
|
| 97 |
+
("**Demo mode**: a shell's **pulse timing** (δ, Δ; TE 53.5 ms, square pulses) is one of the stored classes, "
|
| 98 |
+
"because the layout holds each walker's response to that pulse shape; the b-value, the directions and their "
|
| 99 |
+
"number, the tissue, the field, the SNR and the tracker are free. Stored: " + "; ".join(f"`{n}` = {shapes[n]['label']}" for n in shapes)
|
| 100 |
+
+ ". The same image beside the columnar pack (`DISCO_MODE=full`) replays any timing, in minutes."),
|
| 101 |
+
tissue=("**The scanner** (the menu beside the run button): a catalogued machine sets the field and its direction and plays "
|
| 102 |
+
"every term its catalogue entry carries -- the coils' nonlinearity, their Maxwell gradient, the magnet's own gradient, "
|
| 103 |
+
"the transmit scale -- at the phantom's place in the bore (the distance below; every term vanishes at isocentre), per "
|
| 104 |
+
"voxel and exactly on the layout (docs/scanner.md). "
|
| 105 |
+
"The pack's walkers live in the intra- and extra-axonal pools (its spec names a myelin pool nobody was seeded "
|
| 106 |
+
"in). On this phantom the field's **direction** and the **stimulated echo** move the signal most; 3 T against "
|
| 107 |
+
"7 T on a PGSE is small (the 180° refocuses the static dephasing), and at 7 T the catalogue's two T2 coincide."),
|
| 108 |
+
explorer=("What the replay made, before the noise and the tractography. **A** is the run you configured in the first tab "
|
| 109 |
+
"(its replay before the noise); **B** is the same run with the one knob you chose there changed, and exists only "
|
| 110 |
+
"when a knob is set. **Ingredients**: what each tier multiplies into every walker's term, reduced per voxel. "
|
| 111 |
+
"**Layers**: A's walk replayed with A's tiers switched on one at a time, ending at A itself, then B; look at a "
|
| 112 |
+
"layer, its difference to the previous one, or B minus A, in the DWI itself or in the tensor's MD and FA from the "
|
| 113 |
+
"b ≤ 1500 shells; divide by the replay floor to see where a difference means something. A null result is a "
|
| 114 |
+
"result: 7 T against 3 T at the catalogue's tissue moves the median voxel by 0.005 (99 % of voxels under 0.02), under "
|
| 115 |
+
"the replay floor of about 0.01: the catalogue gives both seeded pools the same T2 at 7 T (47 ms), so the "
|
| 116 |
+
"relaxation tier re-weights nothing between them, the contact tier does not depend on the field, and the sheath "
|
| 117 |
+
"field's dephasing, though it grows from 0.10 to 0.24 rad of spread, moves the magnitude by 0.004 in the median voxel."),
|
| 118 |
+
results_tab="4 · DiSCo results",
|
| 119 |
+
truth_tab="2 · ground truth",
|
| 120 |
+
truth_labels=("the strands", "the ground-truth matrices"),
|
| 121 |
+
stages={"replay": "replaying the grid from the stored walk", "noise": "adding Rician noise", "csd": "fitting CSD (order 8)",
|
| 122 |
+
"track": "tracking from the sixteen regions", "score": "scoring the connectome"},
|
| 123 |
+
fixed=["the DiSCo phantom's geometry and its one stored walk", "the sixteen regions and the ground-truth matrices",
|
| 124 |
+
"the pulse timing classes of the layout (demo mode)"],
|
| 125 |
+
accuracy=("A replay is a measured approximation of the stored walk, not a rendering: the walk's two halves are replayed "
|
| 126 |
+
"separately and their disagreement per voxel is the **floor** below which a signal difference means nothing; "
|
| 127 |
+
"the layout keeps K temporal bands of each walker's path and the **band error** is what the dropped bands "
|
| 128 |
+
"would have added at the built gradient amplitude."),
|
| 129 |
+
ingredients=("relaxation tier: intra-axonal weight fraction", "contact tier: the walkers' wall contact", "field tier: dephasing phase spread at the echo"),
|
| 130 |
+
truth="the dataset's strand-count and cross-sectional-area matrices: Pearson over the 120 region pairs",
|
| 131 |
+
ladder=("Replay DWI Explorer: replay A's tier ladder too (bare, +relaxation, +contact; noise-free; about 30 s more of GPU time at DiSCo 364)"),
|
| 132 |
+
views=dict(truth=False, fractions=False, lobar=False, roundtrip=False, response=False, floor=True),
|
| 133 |
+
files="disco", step_unit="voxels; the grid is the mm frame",
|
| 134 |
+
volumes_label="DWI (.nii.gz) with bvals/bvecs, and the FOD SH field (.nii.gz, tournier07 order 8)",
|
| 135 |
+
run_label="replay → CSD → track → score")
|
| 136 |
+
|
| 137 |
+
@classmethod
|
| 138 |
+
def presets(cls, cfg):
|
| 139 |
+
return [DISCO_364] + list(cfg["presets"])
|
| 140 |
+
|
| 141 |
+
@classmethod
|
| 142 |
+
def protocol(cls, cfg, name):
|
| 143 |
+
if name == DISCO_364:
|
| 144 |
+
return disco_protocol(cfg)[0]
|
| 145 |
+
return P.preset_protocol(cfg, name)
|
| 146 |
+
|
| 147 |
+
@classmethod
|
| 148 |
+
def panel(cls, cfg):
|
| 149 |
+
phys = cfg["physics"]; f0 = float(phys["default_field"]); c0 = cls.catalogue_numbers(cfg, f0); q = pools(cfg); n = len(q)
|
| 150 |
+
C = P.Control
|
| 151 |
+
rows = (
|
| 152 |
+
(C("on", "checkbox", "evaluate the walk in tissue at a field (off: bare diffusion)", bool(phys["default_on"])),),
|
| 153 |
+
(C("field_preset", "field_preset", "field preset", f"{f0:g} T", tuple(f"{float(f):g} T" for f in phys["fields"])),
|
| 154 |
+
C("field_T", "slider", "B0 (T)", f0, minimum=0.05, maximum=12.0, step=0.001)),
|
| 155 |
+
(C("b0_mode", "dropdown", "B0 direction", list(B0_MODES)[0], tuple(B0_MODES) + (FREE_B0,)),
|
| 156 |
+
C("theta", "slider", "polar angle from z (°)", 0, minimum=0, maximum=180, step=1),
|
| 157 |
+
C("phi", "slider", "azimuth from x (°)", 0, minimum=0, maximum=360, step=1)),
|
| 158 |
+
(C("relaxation", "checkbox", "relaxation (T2, T1)", True), C("contact", "checkbox", "contact (surface relaxivity ρ₂)", True),
|
| 159 |
+
C("field", "checkbox", "field (myelin susceptibility)", True)),
|
| 160 |
+
tuple(C(f"T2_{p}", "number", f"T2 {p} (ms)", c0[k]) for k, p in enumerate(q)),
|
| 161 |
+
tuple(C(f"T1_{p}", "number", f"T1 {p} (ms)", c0[n + k]) for k, p in enumerate(q)),
|
| 162 |
+
(C("rho2", "number", "ρ₂, the walls' transverse surface relaxivity (µm/s)", c0[2 * n]), C("chi_iso", "number", "χ_iso of the sheath, the field source (ppm)", c0[2 * n + 1]),
|
| 163 |
+
C("chi_aniso", "number", "Δχ_a of the sheath (ppm)", c0[2 * n + 2])),
|
| 164 |
+
(C("catalogue_note", "catalogue_note", value=c0[-1]), C("reset", "reset", "reset to the catalogue at this field")),
|
| 165 |
+
(C("offset_cm", "slider", "the phantom's distance from isocentre (cm; a scanner's terms vanish at 0)",
|
| 166 |
+
float(cfg["scanners"]["default_offset_cm"]), minimum=0.0, maximum=float(cfg["scanners"]["max_offset_cm"]), step=0.1),
|
| 167 |
+
C("offset_axis", "dropdown", "along the scanner axis", list(OFFSET_AXES)[0], tuple(OFFSET_AXES))),
|
| 168 |
+
)
|
| 169 |
+
return P.Panel(rows, physics_fields(cfg), tissue_numbers(cfg), tuple(float(f) for f in phys["fields"]))
|
| 170 |
+
|
| 171 |
+
@classmethod
|
| 172 |
+
def catalogue_numbers(cls, cfg, field_T):
|
| 173 |
+
"""The catalogue's white matter at ``field_T`` in the page's units (ms, µm/s, ppm), in :func:`tissue_numbers`
|
| 174 |
+
order, plus the note that says which cited field it came from: what the reset button and the field presets
|
| 175 |
+
fill in."""
|
| 176 |
+
q = pools(cfg)
|
| 177 |
+
c = P.catalogue(float(field_T), q)
|
| 178 |
+
note = (f"catalogue values at {c['catalogue_field']:g} T" if abs(c["catalogue_field"] - float(field_T)) < 1e-9
|
| 179 |
+
else f"the catalogue has no cited relaxation at {float(field_T):g} T: nearest is {c['catalogue_field']:g} T, edit as you see fit")
|
| 180 |
+
return ([c["T2"][p] * 1e3 for p in q] + [c["T1"][p] * 1e3 for p in q]
|
| 181 |
+
+ [c["rho2"] * 1e6, c["chi_iso"] * 1e6, c["chi_aniso"] * 1e6, note])
|
| 182 |
+
|
| 183 |
+
@classmethod
|
| 184 |
+
def physics_from(cls, cfg, values, scanner=None):
|
| 185 |
+
"""The panel (page units: ms, µm/s, ppm, cm) as a :class:`space.pipeline.Physics` in SI, or None when it is off
|
| 186 |
+
and no machine is chosen. ``scanner`` is the machine (a catalogue key; None: the ideal scanner): it sets the
|
| 187 |
+
field and its direction (the strands' frame is the scanner's), the panel's placement puts the phantom's
|
| 188 |
+
centre ``offset_cm`` along ``offset_axis`` from isocentre, and with the tissue off the physics is the bare
|
| 189 |
+
diffusion on that machine. The layout plays square pulses: a machine's slew is not played here."""
|
| 190 |
+
q = pools(cfg)
|
| 191 |
+
u = B0_MODES[values["b0_mode"]] if values["b0_mode"] in B0_MODES else P.b0_direction(values["theta"], values["phi"])
|
| 192 |
+
field_T = float(values["field_T"])
|
| 193 |
+
offset = (0.0, 0.0, 0.0)
|
| 194 |
+
if scanner is not None:
|
| 195 |
+
L = P.limits(scanner)
|
| 196 |
+
field_T, u = float(L.field_T), tuple(float(x) for x in (L.b0_axis or P.B0_ALONG_Z))
|
| 197 |
+
if values["offset_axis"] not in OFFSET_AXES:
|
| 198 |
+
raise ValueError(f"the phantom moves along one of {list(OFFSET_AXES)}, not {values['offset_axis']!r}")
|
| 199 |
+
offset = tuple(float(values["offset_cm"]) * 1e-2 * a for a in OFFSET_AXES[values["offset_axis"]])
|
| 200 |
+
if not values["on"]:
|
| 201 |
+
return None if scanner is None else P.Physics.at(field_T, pools=q, b0_direction=u, relaxation=False, contact=False,
|
| 202 |
+
field=False, scanner=scanner, offset_m=offset)
|
| 203 |
+
return P.Physics(field_T=field_T, b0_direction=u,
|
| 204 |
+
T2={p: float(values[f"T2_{p}"]) * 1e-3 for p in q}, T1={p: float(values[f"T1_{p}"]) * 1e-3 for p in q},
|
| 205 |
+
rho2=float(values["rho2"]) * 1e-6, chi_iso=float(values["chi_iso"]) * 1e-6, chi_aniso=float(values["chi_aniso"]) * 1e-6,
|
| 206 |
+
relaxation=bool(values["relaxation"]), contact=bool(values["contact"]), field=bool(values["field"]),
|
| 207 |
+
scanner=scanner, offset_m=offset)
|
| 208 |
+
|
| 209 |
+
@classmethod
|
| 210 |
+
def knobs(cls, cfg):
|
| 211 |
+
"""The one-knob changes B can make to A: the field (with the catalogue's tissue at it), the field's direction,
|
| 212 |
+
a tier off, the tissue off, the noise, or every shell's pulse timing; ``{label: (kind, value)}``."""
|
| 213 |
+
out = {P.NO_KNOB: None}
|
| 214 |
+
for f in cfg["physics"]["fields"]:
|
| 215 |
+
out[f"field → {float(f):g} T (catalogue tissue at that field)"] = ("field", float(f))
|
| 216 |
+
for label in B0_MODES:
|
| 217 |
+
out[f"B0 direction → {label}"] = ("b0", label)
|
| 218 |
+
for tier in cls.TIERS:
|
| 219 |
+
out[f"{tier} tier → off"] = ("tier", tier)
|
| 220 |
+
out["tissue → off (bare diffusion)"] = ("bare", None)
|
| 221 |
+
for v in (10, 100):
|
| 222 |
+
out[f"SNR → {v}"] = ("snr", float(v))
|
| 223 |
+
out["noise → off"] = ("snr", None)
|
| 224 |
+
for name, sh in cfg["shapes"].items():
|
| 225 |
+
out[f"every shell's pulse timing → {name} ({sh['label']})"] = ("shape", name)
|
| 226 |
+
return out
|
| 227 |
+
|
| 228 |
+
@classmethod
|
| 229 |
+
def apply_knob(cls, cfg, change, protocol, snr_on, snr, values):
|
| 230 |
+
"""B's settings: A's with ``change`` (a value of :meth:`knobs`) applied; ``(protocol, snr_on, snr, values)``.
|
| 231 |
+
A knob that changes the tissue panel needs A's panel on, so that B differs from A in that one thing."""
|
| 232 |
+
kind, value = change
|
| 233 |
+
v = dict(values)
|
| 234 |
+
if kind in ("field", "b0", "tier") and not v["on"]:
|
| 235 |
+
raise ValueError(f"the knob {kind!r} changes the tissue panel, which is off for A: switch it on, or choose another knob")
|
| 236 |
+
if kind == "field":
|
| 237 |
+
v["field_T"] = value; v.update(zip(tissue_numbers(cfg), cls.catalogue_numbers(cfg, value)))
|
| 238 |
+
elif kind == "b0":
|
| 239 |
+
v["b0_mode"] = value
|
| 240 |
+
elif kind == "tier":
|
| 241 |
+
v[value] = False
|
| 242 |
+
elif kind == "bare":
|
| 243 |
+
v["on"] = False
|
| 244 |
+
elif kind == "snr":
|
| 245 |
+
snr_on = value is not None; snr = value if value is not None else snr
|
| 246 |
+
elif kind == "shape":
|
| 247 |
+
protocol = P.retime(protocol, value)
|
| 248 |
+
else:
|
| 249 |
+
raise ValueError(f"unknown knob {kind!r}")
|
| 250 |
+
return protocol, snr_on, snr, v
|
| 251 |
+
|
| 252 |
+
@classmethod
|
| 253 |
+
def tracking_controls(cls, cfg):
|
| 254 |
+
t = cfg["tracking"]
|
| 255 |
+
return dict(density=(1, 4, t["density"], 1, "seeds per region voxel (density³)"),
|
| 256 |
+
max_angle=(10, 60, t["max_angle"], 1, "max angle (°)"),
|
| 257 |
+
step=(0.25, 1.0, t["step_mm"], 0.05, "step (voxels; the grid is the mm frame)"))
|
| 258 |
+
|
| 259 |
+
@classmethod
|
| 260 |
+
def tracking(cls, cfg, *, density, max_angle, step, key):
|
| 261 |
+
return P.Tracking(density=int(density), step_mm=float(step), max_angle=float(max_angle), max_steps=int(cfg["tracking"]["max_steps"]), key=int(key))
|
| 262 |
+
|
| 263 |
+
@classmethod
|
| 264 |
+
def estimated_seconds(cls, cfg, protocol, *, density, knob, n_keys, ladder, responses=(), scanner=None):
|
| 265 |
+
"""Measured on the pool at DiSCo 364 with every tier (#7, dmipy-sim#522/#523): the worker's start and the
|
| 266 |
+
payload's handoff 8 s, noise to scoring 8 s, the first replay 0.045 s per measurement (the tiles uploaded
|
| 267 |
+
inside the call), each further replay on the resident tiles 0.032 s per measurement (the ladder is three, B
|
| 268 |
+
one plus its 8 s of stages, a new field direction included), 10 s per extra tracker key; on a machine every
|
| 269 |
+
replay adds its delivery, ``[scanners] delivery_per_meas`` s per measurement (the delivered vectors of the
|
| 270 |
+
layout's live voxels on the host and their upload); times 1.3, within 30 and 480 s. DiSCo prepares nothing,
|
| 271 |
+
so ``responses`` is empty."""
|
| 272 |
+
n = protocol.n_meas
|
| 273 |
+
replays = 1 + (3 if ladder else 0) + (1 if knob != P.NO_KNOB else 0)
|
| 274 |
+
secs = 16 + 0.045 * n + (3 * 0.032 * n if ladder else 0) + ((8 + 0.032 * n) if knob != P.NO_KNOB else 0) + 10 * (int(n_keys) - 1)
|
| 275 |
+
if scanner is not None:
|
| 276 |
+
secs += replays * float(cfg["scanners"]["delivery_per_meas"]) * n
|
| 277 |
+
return int(min(480, max(30, 1.3 * secs)))
|
| 278 |
+
|
| 279 |
+
# ---- the run's side ----
|
| 280 |
+
def tracking_inputs(self, sh, density):
|
| 281 |
+
"""``(field, seeds)``: the FOD field on the mask and the ``density^3`` seeds per region voxel, built once for
|
| 282 |
+
however many tracker keys run on them."""
|
| 283 |
+
from dmipy_tract import FODField, seeds_from_mask
|
| 284 |
+
return FODField(sh, self.affine, self.mask | (self.rois > 0)), seeds_from_mask(self.rois > 0, self.affine, density=density)
|
| 285 |
+
|
| 286 |
+
def reference(self, tracking, seeds):
|
| 287 |
+
"""The ground-truth matrices, the same for every run."""
|
| 288 |
+
return dict(count=self.gt_count, area=self.gt_area), 0.0
|
| 289 |
+
|
| 290 |
+
def score(self, M, reference):
|
| 291 |
+
"""Pearson correlations over the 120 region pairs with the strand-count and area matrices, and the pair
|
| 292 |
+
bookkeeping (connected, ground-truth, false, missed)."""
|
| 293 |
+
return score(M, reference["count"], reference["area"])
|
| 294 |
+
|
| 295 |
+
def compare(self, a, b):
|
| 296 |
+
return compare(a, b)
|
| 297 |
+
|
| 298 |
+
def truth_views(self):
|
| 299 |
+
"""The ground truth tab: a sample of the strands in 3-D with the region markers, and the two matrices."""
|
| 300 |
+
from dmipy_sim.io.strands import read_tck, read_diameters
|
| 301 |
+
from .. import viewers as V
|
| 302 |
+
strands = read_tck(os.path.join(P.DATA_DIR, "DiSCo_Strands_Trajectories.tck"), coordinate_unit_m=VOXEL_M)
|
| 303 |
+
diameters = read_diameters(os.path.join(P.DATA_DIR, "DiSCo_Strands_Diameters.txt"), diameter_unit_m=1e-3)
|
| 304 |
+
return (V.strands3d([s / VOXEL_M for s in strands], diameters, V.region_markers(self.regions), self.mask.shape),
|
| 305 |
+
V.ground_truth_matrix(self.gt_count, self.gt_area, P.connected_pairs(self.gt_count)))
|
| 306 |
+
|
| 307 |
+
def score_text(self, tag, res):
|
| 308 |
+
s = res.score; physics = res.physics
|
| 309 |
+
snr = P.b0_snr(res)
|
| 310 |
+
noise = "" if snr is None else f", SNR {res.snr:g} at M0 = {snr['median']:.1f} at b = 0 in the median voxel"
|
| 311 |
+
return (f"**{tag}: Pearson vs strand count {s['pearson_count']:.3f}, vs area {s['pearson_area']:.3f}** "
|
| 312 |
+
f"({res.protocol.n_meas} measurements, {physics.label() if physics else 'bare diffusion'}"
|
| 313 |
+
f"{noise}, {len(res.tractogram):,} streamlines, {res.seconds['total']:.1f} s; "
|
| 314 |
+
f"replay floor median {P.floor_stats(res)['median']:.4f})")
|
| 315 |
+
|
| 316 |
+
def compare_text(self, c, knob):
|
| 317 |
+
return (f"**A vs B: connectome Pearson {c['pearson_ab']:.3f}**, {c['only_a']} pairs in A only, {c['only_b']} in B only, "
|
| 318 |
+
f"B − A {c['delta_count']:+.3f} vs count, {c['delta_area']:+.3f} vs area; B = A with {knob}.")
|
| 319 |
+
|
| 320 |
+
def matrices(self, M, score, reference):
|
| 321 |
+
"""The connectome beside the strand-count ground truth."""
|
| 322 |
+
from .. import viewers as V
|
| 323 |
+
return V.matrices(M, score, reference["count"])
|
| 324 |
+
|
| 325 |
+
def score_key(self):
|
| 326 |
+
return "pearson_count"
|
| 327 |
+
|
| 328 |
+
@staticmethod
|
| 329 |
+
def ingredient_layers(ing):
|
| 330 |
+
"""The intra-axonal weight fraction, the walls' contact (the survival at the run's rho2 with the contact tier,
|
| 331 |
+
else the boundary local time), the field's dephasing spread."""
|
| 332 |
+
if not ing:
|
| 333 |
+
return [None, None, None]
|
| 334 |
+
pool = ("intra-axonal weight fraction (relaxation tier re-weights it)", ing["intra_fraction"], dict(vmin=0, vmax=1))
|
| 335 |
+
if ing.get("contact_survival") is not None:
|
| 336 |
+
contact = ("contact survival exp(−ρ₂ ℓ / D) at the run's ρ₂ (ℓ the walkers' wall contact)", ing["contact_survival"], dict(cmap="magma", vmax=1))
|
| 337 |
+
elif ing.get("wall_contact_um") is not None:
|
| 338 |
+
contact = ("walkers' wall contact ℓ (boundary local time, µm)", ing["wall_contact_um"], dict(cmap="magma", unit="µm"))
|
| 339 |
+
else:
|
| 340 |
+
contact = None
|
| 341 |
+
fld = (("spread over the voxel's walkers of the sheath field's dephasing phase at the echo (rad)", ing["field_rad"], dict(cmap="inferno", unit="rad"))
|
| 342 |
+
if ing.get("field_rad") is not None else None)
|
| 343 |
+
return [pool, contact, fld]
|
| 344 |
+
|
| 345 |
+
|
| 346 |
+
PAIRS = np.triu_indices(N_REGIONS, 1) # the 120 region pairs
|
| 347 |
+
|
| 348 |
+
|
| 349 |
+
def score(M, gt_count, gt_area):
|
| 350 |
+
"""Pearson correlations over the 120 region pairs with the strand-count and area matrices, and the pair
|
| 351 |
+
bookkeeping (connected, ground-truth, false, missed)."""
|
| 352 |
+
return dict(pearson_count=P.pearson(M[PAIRS], gt_count[PAIRS]), pearson_area=P.pearson(M[PAIRS], gt_area[PAIRS]),
|
| 353 |
+
connected_pairs=P.connected_pairs(M), gt_pairs=P.connected_pairs(gt_count),
|
| 354 |
+
false_pairs=int(((M[PAIRS] > 0) & (gt_count[PAIRS] == 0)).sum()), missed_pairs=int(((M[PAIRS] == 0) & (gt_count[PAIRS] > 0)).sum()))
|
| 355 |
+
|
| 356 |
+
|
| 357 |
+
def compare(a, b):
|
| 358 |
+
"""A against B over the 120 region pairs: the Pearson between the two streamline-count matrices, the pairs
|
| 359 |
+
connected in one only, and B's score minus A's."""
|
| 360 |
+
ma, mb = a.matrix[PAIRS], b.matrix[PAIRS]
|
| 361 |
+
return dict(pearson_ab=P.pearson(ma, mb), only_a=int(((ma > 0) & (mb == 0)).sum()), only_b=int(((mb > 0) & (ma == 0)).sum()),
|
| 362 |
+
delta_count=b.score["pearson_count"] - a.score["pearson_count"], delta_area=b.score["pearson_area"] - a.score["pearson_area"])
|
| 363 |
+
|
| 364 |
+
|
| 365 |
+
class Layout(Disco):
|
| 366 |
+
"""Demo mode: dmipy-sim's shape-moment layout (``dmipy_sim.replay.shape_moments``) at the config's dataset
|
| 367 |
+
revision, or a local copy; every stored class's timing is the config's, and a tissue needs the layout's tiers."""
|
| 368 |
+
mode = "demo"
|
| 369 |
+
|
| 370 |
+
@classmethod
|
| 371 |
+
def load(cls, cfg, *, local=None):
|
| 372 |
+
"""The layout at ``local``, ``DISCO_MOMENTS``, or the config's dataset revision on the Hub."""
|
| 373 |
+
return cls(cfg, local=local or os.environ.get("DISCO_MOMENTS"))
|
| 374 |
+
|
| 375 |
+
def __init__(self, cfg, *, local=None):
|
| 376 |
+
from dmipy_sim.replay.shape_moments import ShapeMoments
|
| 377 |
+
super().__init__(cfg)
|
| 378 |
+
d = cfg["data"]
|
| 379 |
+
uri = local or f"hf://{d['repo']}/{d['moments']}"
|
| 380 |
+
self.moments = ShapeMoments.open(uri, revision=d.get("revision") or None) if uri.startswith("hf://") else ShapeMoments(uri)
|
| 381 |
+
self.resident = P.resident(cfg)
|
| 382 |
+
want = d.get("source_manifest_sha256")
|
| 383 |
+
got = self.moments.manifest["source"]["manifest_sha256"]
|
| 384 |
+
if want and got != want:
|
| 385 |
+
raise ValueError(f"the layout at {uri} was contracted from columnar manifest {got[:12]}, the config pins {want[:12]}")
|
| 386 |
+
missing = [s for s in self.shapes if s not in self.moments.shapes]
|
| 387 |
+
if missing:
|
| 388 |
+
raise ValueError(f"the layout at {uri} lacks the timing classes {missing}; it holds {self.moments.shapes}")
|
| 389 |
+
for name, t in self.shapes.items():
|
| 390 |
+
enc = self.moments.manifest["shapes"][name].get("encoding") or {}
|
| 391 |
+
for k in ("delta", "Delta", "TE"):
|
| 392 |
+
v = enc.get(k)
|
| 393 |
+
v = v[0] if isinstance(v, list) and v else v
|
| 394 |
+
if v is not None and abs(float(v) - float(t[k])) > 1e-9:
|
| 395 |
+
raise ValueError(f"class {name}: the layout's {k} is {v} s, the config's {t[k]} s")
|
| 396 |
+
self.tiers = bool(self.moments.manifest.get("tiers"))
|
| 397 |
+
self.M0 = None # the bare b = 0 map (every voxel's walker weight): set by warm()
|
| 398 |
+
if self.tiers: # the pools with walkers are the spec's first n_pools ids
|
| 399 |
+
t = self.moments.manifest["tiers"]
|
| 400 |
+
spec_pools = sorted(t["substrate"]["pools"], key=lambda q: q["id"]) if t.get("substrate") else []
|
| 401 |
+
seeded = tuple(q["name"] for q in spec_pools[:int(t["pools"])])
|
| 402 |
+
if set(seeded) != set(self.pools):
|
| 403 |
+
raise ValueError(f"the layout's seeded pools are {seeded}, the config's [physics] pools {self.pools}")
|
| 404 |
+
self.unseeded = tuple(q["name"] for q in spec_pools[int(t["pools"]):])
|
| 405 |
+
self.check_grid(self.moments.grid.shape, "the layout")
|
| 406 |
+
|
| 407 |
+
def validate(self, protocol, physics):
|
| 408 |
+
meas = P.measurements(protocol, self.shapes)
|
| 409 |
+
if physics and not physics.bare and not self.tiers:
|
| 410 |
+
raise ValueError("this layout holds bare diffusion only: switch the tissue panel off")
|
| 411 |
+
if physics and set(physics.pools) != set(self.pools):
|
| 412 |
+
raise ValueError(f"the tissue names the pools {physics.pools}; this layout's are {self.pools}")
|
| 413 |
+
if physics and physics.scanner is not None:
|
| 414 |
+
L = P.limits(physics.scanner)
|
| 415 |
+
if L.has_field_law and not self.moments.background:
|
| 416 |
+
raise ValueError(f"the {physics.scanner}'s own gradient needs the layout's background moments, and this layout has "
|
| 417 |
+
"none (dmipy_sim.replay.shape_moments.stamp_background adds them in one pass)")
|
| 418 |
+
if L.has_transmit_profile and any("rf" not in self.moments.manifest["shapes"][n] for n in np.unique(meas.shape)):
|
| 419 |
+
raise ValueError(f"the {physics.scanner}'s transmit scale needs the classes' RF schedules, which this layout does not "
|
| 420 |
+
"record (stamp_background records them)")
|
| 421 |
+
return meas
|
| 422 |
+
|
| 423 |
+
def delivered(self, name, bvals, dirs, physics):
|
| 424 |
+
"""What the run's machine delivers at every voxel with rows for the class ``name`` at ``bvals`` (s/m^2) along
|
| 425 |
+
``dirs``: the layout's :meth:`~dmipy_sim.replay.shape_moments.ShapeMoments.delivery` with the grid's centre at
|
| 426 |
+
the physics' offset; None on the ideal scanner."""
|
| 427 |
+
if physics is None or physics.scanner is None:
|
| 428 |
+
return None
|
| 429 |
+
return self.moments.delivery(name, bvals, dirs, P.limits(physics.scanner), self.moments.grid.centred_at(physics.offset_m))
|
| 430 |
+
|
| 431 |
+
def replay(self, meas, physics=None, prepared=None):
|
| 432 |
+
t0 = time.perf_counter()
|
| 433 |
+
S = np.full(self.mask.shape + (len(meas.bvals),), np.nan)
|
| 434 |
+
floor = np.zeros(self.mask.shape)
|
| 435 |
+
tissue, scanner = P.tissue_and_scanner(physics, self.unseeded)
|
| 436 |
+
b0 = physics.b0_direction if physics else P.B0_ALONG_Z
|
| 437 |
+
for name in np.unique(meas.shape):
|
| 438 |
+
rows = meas.shape == name
|
| 439 |
+
S[..., rows], f = self.moments.image(name, meas.bvals[rows] * 1e6, meas.dirs[rows], backend=self.backend,
|
| 440 |
+
resident=True, tissue=tissue, scanner=scanner, b0_direction=b0,
|
| 441 |
+
delivered=self.delivered(name, meas.bvals[rows] * 1e6, meas.dirs[rows], physics))
|
| 442 |
+
floor = np.fmax(floor, f) # resident within a run: release() drops the device copies after it
|
| 443 |
+
if self.M0 is None: # the bare b = 0 map: the walker weight of every voxel
|
| 444 |
+
self.M0 = self.moments.image(meas.shape[0], np.zeros(1), np.array([P.B0_ALONG_Z]), backend=self.backend, resident=True)[0][..., 0]
|
| 445 |
+
dwi, factor = P.s0_normalised(S, meas.b0, self.M0)
|
| 446 |
+
return dwi, floor, factor, time.perf_counter() - t0
|
| 447 |
+
|
| 448 |
+
def release(self):
|
| 449 |
+
if not self.resident:
|
| 450 |
+
self.moments.release()
|
| 451 |
+
|
| 452 |
+
def ingredients(self, meas, physics=None, prepared=None):
|
| 453 |
+
"""What each tier multiplies into the sum, per voxel, for the run's first class (the layout's
|
| 454 |
+
:meth:`~dmipy_sim.replay.shape_moments.ShapeMoments.tier_maps` on the device columns the replay left
|
| 455 |
+
resident): ``intra_fraction`` (the walker weight in the intra-axonal pool over the voxel's),
|
| 456 |
+
``wall_contact_um`` (the walkers' boundary local time l under the class's gate, a length; the layout stores
|
| 457 |
+
it signed as the exponent's term, -l, so the contact tier's weight is exp(rho2 c / D) = exp(-rho2 l / D)),
|
| 458 |
+
``contact_survival`` (that factor at the run's rho2, None without the contact tier), ``field_rad`` (the spread
|
| 459 |
+
over the voxel's walkers of the dephasing phase the sheath's field gives them by the echo at the run's field
|
| 460 |
+
and direction, the exact per-walker phase the kernel applies, in radians; None without the field tier), and
|
| 461 |
+
``D_walk`` (m^2/s)."""
|
| 462 |
+
if not self.tiers:
|
| 463 |
+
return None
|
| 464 |
+
tissue, scanner = P.tissue_and_scanner(physics, self.unseeded)
|
| 465 |
+
b0 = physics.b0_direction if physics else P.B0_ALONG_Z
|
| 466 |
+
maps = self.moments.tier_maps(str(meas.shape[0]), tissue, scanner, backend=self.backend, resident=True, b0_direction=b0)
|
| 467 |
+
contact = maps["contact"]
|
| 468 |
+
return dict(D_walk=float(self.moments.manifest["tiers"]["D_walk"]), intra_fraction=maps["pool"]["intra"],
|
| 469 |
+
wall_contact_um=None if contact is None else -contact * 1e6,
|
| 470 |
+
contact_survival=maps["contact_weight"] if (physics and physics.contact) else None,
|
| 471 |
+
field_rad=maps["phase_std"] if (physics and physics.field) else None)
|
| 472 |
+
|
| 473 |
+
def default_physics(self):
|
| 474 |
+
"""The tissue panel's default (``[physics]``), or None when it starts off or the layout has no tiers."""
|
| 475 |
+
p = self.cfg["physics"]
|
| 476 |
+
return P.Physics.at(float(p["default_field"]), pools=self.pools) if (p["default_on"] and self.tiers) else None
|
| 477 |
+
|
| 478 |
+
def warm(self):
|
| 479 |
+
"""DiSCo's own protocol replayed once at the default physics (every class it plays compiled at the row
|
| 480 |
+
counts the default run uses), then one direction on every other class (its tier group's terms contracted
|
| 481 |
+
and on the device). When the tiles are not kept resident (a pool that drops the device between calls), the
|
| 482 |
+
padded host arrays are loaded into this process instead, so a forked worker inherits them and pays the
|
| 483 |
+
transfer alone."""
|
| 484 |
+
if not self.resident:
|
| 485 |
+
self.moments.preload(list(self.shapes))
|
| 486 |
+
return
|
| 487 |
+
physics = self.default_physics()
|
| 488 |
+
disco = disco_protocol(self.cfg)[0]
|
| 489 |
+
self.replay(P.measurements(disco, self.shapes), physics)
|
| 490 |
+
rest = [name for name in self.shapes if name not in {s.shape for s in disco.shells}]
|
| 491 |
+
if rest:
|
| 492 |
+
self.replay(P.measurements(P.Protocol(tuple(P.Shell(name, 1000.0, 1) for name in rest), n_b0=1, name="warm"), self.shapes), physics)
|
| 493 |
+
|
| 494 |
+
def accuracy(self, res=None):
|
| 495 |
+
m = self.moments.manifest; src = m["source"]
|
| 496 |
+
rows = [["temporal bands kept (K)", str(m["K"])],
|
| 497 |
+
["band error at the built amplitude (worst class)", f"{m['band_error']:.2e}"],
|
| 498 |
+
["band tolerance (× the pack's floor)", f"{m['tol']:g}"],
|
| 499 |
+
["source pack", str(src.get("pack"))],
|
| 500 |
+
["source pack's certified median floor", f"{src['floor']:.4g}"],
|
| 501 |
+
["source manifest sha256", src["manifest_sha256"][:16]],
|
| 502 |
+
["layout written by", f"{m.get('code', {}).get('commit', '?')[:12]} on {m.get('created', '?')}"],
|
| 503 |
+
["pulses", "square (slew rate ∞), one TE per class"],
|
| 504 |
+
["tiers stored", "pool, contact, field" if self.tiers else "none (bare diffusion only)"],
|
| 505 |
+
["background moments (a magnet's own gradient)", "stored, certified to {:g} mT/m".format(self.moments.background["amplitude"] * 1e3)
|
| 506 |
+
if self.moments.background else "not stored: a machine with its own gradient is refused"]]
|
| 507 |
+
if res is not None and res.physics is not None and res.physics.scanner is not None:
|
| 508 |
+
rows.append(["scanner", f"{res.physics.scanner}, the phantom's centre at "
|
| 509 |
+
f"({', '.join(f'{x * 100:.1f}' for x in res.physics.offset_m)}) cm from isocentre: every catalogued term "
|
| 510 |
+
"per voxel, exact on the layout (docs/scanner.md)"])
|
| 511 |
+
rows += super().accuracy(res)
|
| 512 |
+
if res is not None:
|
| 513 |
+
for name in np.unique(res.meas.shape):
|
| 514 |
+
sh = m["shapes"][name]; enc = sh.get("encoding") or {}
|
| 515 |
+
first = {k: (v[0] if isinstance(v, list) and v else v) for k, v in enc.items()}
|
| 516 |
+
rows.append([f"class {name}", f"δ {first.get('delta')} / Δ {first.get('Delta')} / TE {first.get('TE')} s, "
|
| 517 |
+
f"built at {float(sh.get('amplitude_built') or 0) * 1e3:.0f} mT/m, pathway amplitude {sh.get('pathway') or 1}"])
|
| 518 |
+
return rows
|
| 519 |
+
|
| 520 |
+
|
| 521 |
+
class Columns(Disco):
|
| 522 |
+
"""Full mode: the columnar replay pack (:class:`dmipy_sim.replay.columnar.ColumnarPack`) at
|
| 523 |
+
:func:`space.pipeline.columns_uri`, read once per run: one ScannerSequence per run (one echo time, one pulse kind, square
|
| 524 |
+
pulses), the tissue and field of the run, the field along the pack's z."""
|
| 525 |
+
mode = "full"
|
| 526 |
+
RATE = {True: 45e6, False: 500e6} # bytes/s read from the Hub, from a local disk
|
| 527 |
+
|
| 528 |
+
def __init__(self, cfg, *, uri=None):
|
| 529 |
+
from dmipy_sim.replay.columnar import ColumnarPack
|
| 530 |
+
super().__init__(cfg)
|
| 531 |
+
self.uri = uri or P.columns_uri(cfg)
|
| 532 |
+
self.pack = ColumnarPack(self.uri, workers=int(cfg["mode"]["workers"]))
|
| 533 |
+
self.check_grid(self.pack.grid.shape, "the pack")
|
| 534 |
+
self.remote = self.uri.startswith("hf://")
|
| 535 |
+
|
| 536 |
+
def kinds(self, meas):
|
| 537 |
+
"""The pulse kinds (``pgse`` / ``pgste``) of the classes the rows play; a free timing is PGSE."""
|
| 538 |
+
return sorted({self.shapes[n].get("kind", "pgse") if n in self.shapes else "pgse" for n in np.unique(meas.shape)})
|
| 539 |
+
|
| 540 |
+
def validate(self, protocol, physics):
|
| 541 |
+
meas = P.measurements(protocol, self.shapes)
|
| 542 |
+
if len(np.unique(np.round(meas.TE, 9))) != 1:
|
| 543 |
+
raise ValueError("full mode replays one echo time per run")
|
| 544 |
+
if len(self.kinds(meas)) != 1:
|
| 545 |
+
raise ValueError("full mode replays one pulse kind (PGSE or stimulated echo) per run")
|
| 546 |
+
if physics and not physics.along_z:
|
| 547 |
+
raise ValueError("full mode replays the field along z only")
|
| 548 |
+
if physics and physics.scanner is not None:
|
| 549 |
+
raise ValueError("full mode replays the commanded acquisition on the whole grid; a machine's per-voxel delivery is demo "
|
| 550 |
+
"mode's (the layout), so choose the ideal scanner here")
|
| 551 |
+
return meas
|
| 552 |
+
|
| 553 |
+
def sequence(self, meas):
|
| 554 |
+
"""The one ScannerSequence of the measurements: square pulses, every row's own delta / Delta at the rows'
|
| 555 |
+
common TE; a stimulated echo stores for TM = Delta - delta between 90° pulses."""
|
| 556 |
+
import dmipy_sim as d
|
| 557 |
+
TE = float(np.unique(np.round(meas.TE, 9))[0])
|
| 558 |
+
kind, = self.kinds(meas)
|
| 559 |
+
if kind == "pgste":
|
| 560 |
+
return d.pgste(meas.dirs.tolist(), meas.delta, meas.Delta - meas.delta, bvalues=meas.bvals * 1e6, n_t=1000,
|
| 561 |
+
slew_rate=np.inf, ste_flip_angles=(90.0, 90.0, 90.0))
|
| 562 |
+
return d.pgse(meas.dirs.tolist(), meas.delta, meas.Delta, bvalues=meas.bvals * 1e6, TE=TE, n_t=1000, slew_rate=np.inf)
|
| 563 |
+
|
| 564 |
+
def plan(self, meas, physics=None):
|
| 565 |
+
"""What the replay will read (the pack's plan: bands, modes, tiers, rows, bytes) and ``estimated_seconds``
|
| 566 |
+
at the source's read rate."""
|
| 567 |
+
tissue, scanner = P.tissue_and_scanner(physics, self.unseeded)
|
| 568 |
+
plan = self.pack.plan(self.sequence(meas), tissue=tissue, scanner=scanner, tol=P.BAND_TOL)
|
| 569 |
+
plan["estimated_seconds"] = plan["bytes"] / self.RATE[self.remote]
|
| 570 |
+
return plan
|
| 571 |
+
|
| 572 |
+
def replay(self, meas, physics=None, prepared=None, *, progress=None):
|
| 573 |
+
from dmipy_sim.replay.study import Study, Protocol as SProtocol, Acquisition
|
| 574 |
+
t0 = time.perf_counter()
|
| 575 |
+
tissue, scanner = P.tissue_and_scanner(physics, self.unseeded)
|
| 576 |
+
study = Study(SProtocol([Acquisition(self.sequence(meas), name="run")]), tissues=[tissue], scanners=[scanner])
|
| 577 |
+
S, floor, plan = self.pack.image_study(study, tol=P.BAND_TOL, chunk_rows=1_000_000, progress=progress)
|
| 578 |
+
self.last_plan = plan
|
| 579 |
+
dwi, factor = P.s0_normalised(S[0], meas.b0) # the pack's bare weights are not read here: the factor is 1
|
| 580 |
+
return dwi, floor[0], factor, time.perf_counter() - t0
|
| 581 |
+
|
| 582 |
+
def accuracy(self, res=None):
|
| 583 |
+
m = self.pack.meta
|
| 584 |
+
rows = [["source pack", str(m.get("id"))], ["source pack's certified median floor", f"{self.pack.floor:.4g}"],
|
| 585 |
+
["bands kept", str(self.pack.K)], ["band tolerance (× the pack's floor)", f"{P.BAND_TOL:g}"],
|
| 586 |
+
["pulses", "square (slew rate ∞), one TE and one pulse kind per run"]]
|
| 587 |
+
plan = getattr(self, "last_plan", None)
|
| 588 |
+
if plan:
|
| 589 |
+
rows.append(["last replay read", f"{plan.get('rows', 0):,} rows, {plan.get('bytes', 0) / 1e9:.1f} GB, bands {plan.get('K')}, modes {plan.get('modes')}"])
|
| 590 |
+
return rows + super().accuracy(res)
|
space/viewers.py
ADDED
|
@@ -0,0 +1,320 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""The page's views: a DWI slice with the FODs' principal directions drawn over it, the replay floor slice, scalar and
|
| 2 |
+
fraction maps, the tractogram and the ground-truth strands as rotatable 3-D figures with the region markers, the
|
| 3 |
+
connectome beside its truth for any number of regions, the spread over repeated runs, the response curves, the
|
| 4 |
+
timings. Matplotlib for the slices and matrices (PIL images), Plotly for the 3-D views (figures the page rotates).
|
| 5 |
+
Every number drawn comes in from :mod:`space.pipeline`, a source or the page."""
|
| 6 |
+
from __future__ import annotations
|
| 7 |
+
|
| 8 |
+
import io
|
| 9 |
+
|
| 10 |
+
import numpy as np
|
| 11 |
+
|
| 12 |
+
REGION_COLOURS = ["#e6194b", "#3cb44b", "#ffe119", "#4363d8", "#f58231", "#911eb4", "#46f0f0", "#f032e6",
|
| 13 |
+
"#bcf60c", "#fabebe", "#008080", "#e6beff", "#9a6324", "#fffac8", "#800000", "#aaffc3"]
|
| 14 |
+
AXIS_COLOURS = ("#d62728", "#2ca02c", "#1f77b4") # paths that mostly follow x, y, z
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def _image(fig):
|
| 18 |
+
import matplotlib.pyplot as plt
|
| 19 |
+
buf = io.BytesIO()
|
| 20 |
+
fig.savefig(buf, format="png", dpi=110, bbox_inches="tight")
|
| 21 |
+
plt.close(fig)
|
| 22 |
+
buf.seek(0)
|
| 23 |
+
from PIL import Image
|
| 24 |
+
return Image.open(buf)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def _mpl():
|
| 28 |
+
import matplotlib
|
| 29 |
+
matplotlib.use("Agg")
|
| 30 |
+
import matplotlib.pyplot as plt
|
| 31 |
+
return plt
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def _slice_axes(title):
|
| 35 |
+
"""One square axial-slice figure without ticks; ``(fig, ax)``."""
|
| 36 |
+
plt = _mpl()
|
| 37 |
+
fig, ax = plt.subplots(figsize=(5.2, 5.2))
|
| 38 |
+
ax.set_title(title, fontsize=9)
|
| 39 |
+
ax.set_xticks([]); ax.set_yticks([])
|
| 40 |
+
return fig, ax
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
NAMED_TICKS = 20 # up to this many regions the ticks carry the names
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def pair_panel(panels, suptitle, *, vmin=1.0, names=None):
|
| 47 |
+
"""Square matrices side by side on a log colour scale (zeros blank): ``panels`` is ``[(title, M), ...]``. The
|
| 48 |
+
ticks are the regions' names when ``names`` has at most :data:`NAMED_TICKS`, else every region number at a
|
| 49 |
+
stride that keeps about ten ticks."""
|
| 50 |
+
plt = _mpl()
|
| 51 |
+
from matplotlib.colors import LogNorm
|
| 52 |
+
n = len(panels[0][1])
|
| 53 |
+
big = n > 16
|
| 54 |
+
fig, axes = plt.subplots(1, len(panels), figsize=((6.2 if big else 4) * len(panels), 5.8 if big else 3.8))
|
| 55 |
+
labelled = names is not None and len(names) <= NAMED_TICKS
|
| 56 |
+
ticks = range(n) if labelled else range(0, n, max(1, int(np.ceil(n / 10))) if big else 3)
|
| 57 |
+
for ax, (title, A) in zip(np.atleast_1d(axes), panels):
|
| 58 |
+
A = np.asarray(A, np.float64)
|
| 59 |
+
top = max(float(A.max()), vmin * 2)
|
| 60 |
+
im = ax.imshow(np.where(A > 0, A, np.nan), norm=LogNorm(vmin=vmin, vmax=top), cmap="viridis")
|
| 61 |
+
ax.set_title(title, fontsize=9); ax.set_xticks(list(ticks)); ax.set_yticks(list(ticks))
|
| 62 |
+
if labelled:
|
| 63 |
+
ax.set_xticklabels(names, rotation=90, fontsize=6); ax.set_yticklabels(names, fontsize=6)
|
| 64 |
+
else:
|
| 65 |
+
ax.set_xticklabels([t + 1 for t in ticks], fontsize=7); ax.set_yticklabels([t + 1 for t in ticks], fontsize=7)
|
| 66 |
+
fig.colorbar(im, ax=ax, fraction=0.046)
|
| 67 |
+
fig.suptitle(suptitle, fontsize=9)
|
| 68 |
+
return _image(fig)
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def dwi_slice(dwi, meas, z, m, *, peaks=None, peak_amp=None, overlay=False, label=""):
|
| 73 |
+
"""Axial slice ``z`` of measurement ``m`` (S0-normalised, grey 0..1); with ``overlay`` the principal FOD direction
|
| 74 |
+
of every voxel as a short line coloured by |direction| (x, y, z -> r, g, b), scaled by its amplitude."""
|
| 75 |
+
b = meas.bvals[m]
|
| 76 |
+
fig, ax = _slice_axes(f"{label}slice z = {z}, measurement {m}: b = {b:g} s/mm², {meas.shape[m]}" + (", FOD peaks" if overlay else ""))
|
| 77 |
+
sl = np.nan_to_num(dwi[:, :, z, m])
|
| 78 |
+
ax.imshow(sl.T, origin="lower", cmap="gray", vmin=0, vmax=1, extent=(-0.5, dwi.shape[0] - 0.5, -0.5, dwi.shape[1] - 0.5))
|
| 79 |
+
if overlay and peaks is not None:
|
| 80 |
+
d = peaks[:, :, z]; a = peak_amp[:, :, z]
|
| 81 |
+
ii, jj = np.nonzero(a > 0)
|
| 82 |
+
if len(ii):
|
| 83 |
+
L = 0.45 * a[ii, jj] / a[ii, jj].max()
|
| 84 |
+
x0 = ii - L * d[ii, jj, 0]; x1 = ii + L * d[ii, jj, 0]; y0 = jj - L * d[ii, jj, 1]; y1 = jj + L * d[ii, jj, 1]
|
| 85 |
+
from matplotlib.collections import LineCollection
|
| 86 |
+
ax.add_collection(LineCollection(np.stack([np.stack([x0, y0], 1), np.stack([x1, y1], 1)], 1),
|
| 87 |
+
colors=np.abs(d[ii, jj]), linewidths=1.2))
|
| 88 |
+
return _image(fig)
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def floor_slice(floor, z, median, *, label=""):
|
| 92 |
+
"""Axial slice ``z`` of the replay's split-half floor per voxel (the disagreement of the two walker halves,
|
| 93 |
+
the largest over the classes played), ``median`` the run's median floor for the title."""
|
| 94 |
+
fig, ax = _slice_axes(f"{label}split-half floor, slice z = {z} (median {median:.4f})")
|
| 95 |
+
sl = floor[:, :, z]
|
| 96 |
+
im = ax.imshow(np.where(sl > 0, sl, np.nan).T, origin="lower", cmap="magma", vmin=0, vmax=max(float(np.nanmax(floor)), 1e-6))
|
| 97 |
+
fig.colorbar(im, ax=ax, fraction=0.046)
|
| 98 |
+
return _image(fig)
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def _lines3d(paths, colours, *, name, width=2.0, opacity=0.7):
|
| 102 |
+
"""One Plotly trace per colour group: the group's points concatenated with a NaN row between paths (a gap)."""
|
| 103 |
+
import plotly.graph_objects as go
|
| 104 |
+
traces = []
|
| 105 |
+
for colour, group in zip(colours, paths):
|
| 106 |
+
if not group:
|
| 107 |
+
continue
|
| 108 |
+
pts = np.concatenate(group).astype(np.float64)
|
| 109 |
+
ends = np.cumsum([len(p) for p in group])
|
| 110 |
+
pts = np.insert(pts, ends, np.nan, axis=0)
|
| 111 |
+
traces.append(go.Scatter3d(x=pts[:, 0], y=pts[:, 1], z=pts[:, 2], mode="lines", line=dict(color=colour, width=width),
|
| 112 |
+
opacity=opacity, name=name, showlegend=False, hoverinfo="skip", connectgaps=False))
|
| 113 |
+
return traces
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def _by_dominant_axis(paths):
|
| 117 |
+
"""Paths split by the axis their end-to-end vector mostly follows (x, y, z): the colour groups."""
|
| 118 |
+
groups = [[], [], []]
|
| 119 |
+
for pts in paths:
|
| 120 |
+
v = np.abs(pts[-1] - pts[0])
|
| 121 |
+
groups[int(np.argmax(v)) if v.max() > 0 else 0].append(pts)
|
| 122 |
+
return groups
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def region_markers(regions):
|
| 126 |
+
"""The region centroids as Plotly markers (built once per source; the 3-D views take it): ``regions`` a
|
| 127 |
+
:class:`space.pipeline.Regions` (centroids through its affine, into the tracking frame) or a label image (voxel
|
| 128 |
+
coordinates); numbered while there are at most :data:`NAMED_TICKS` regions, else coloured by their group with the
|
| 129 |
+
name on hover."""
|
| 130 |
+
import plotly.graph_objects as go
|
| 131 |
+
labels = getattr(regions, "labels", regions)
|
| 132 |
+
affine = np.asarray(getattr(regions, "affine", np.eye(4)), np.float64)
|
| 133 |
+
names = getattr(regions, "names", None)
|
| 134 |
+
n = len(names) if names is not None else int(np.max(labels))
|
| 135 |
+
group_of = {}
|
| 136 |
+
for g, (_, ids) in enumerate(getattr(regions, "groups", ()) or ()):
|
| 137 |
+
for i in ids:
|
| 138 |
+
group_of[int(i)] = g
|
| 139 |
+
cs = []
|
| 140 |
+
for k in range(1, n + 1):
|
| 141 |
+
ijk = np.argwhere(labels == k)
|
| 142 |
+
if len(ijk):
|
| 143 |
+
cs.append((k, ijk.mean(0) @ affine[:3, :3].T + affine[:3, 3]))
|
| 144 |
+
few = n <= NAMED_TICKS
|
| 145 |
+
colour = [REGION_COLOURS[(group_of.get(c[0], c[0] - 1)) % len(REGION_COLOURS)] for c in cs]
|
| 146 |
+
return go.Scatter3d(x=[c[1][0] for c in cs], y=[c[1][1] for c in cs], z=[c[1][2] for c in cs], mode="markers+text" if few else "markers",
|
| 147 |
+
text=[str(c[0]) if few or names is None else names[c[0] - 1] for c in cs], textposition="top center",
|
| 148 |
+
hoverinfo="text", marker=dict(size=5 if few else 3, color=colour), name="regions", showlegend=False)
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def _figure3d(paths, regions, shape, title, *, name, width, opacity):
|
| 152 |
+
"""Paths coloured by dominant axis with the region markers: in a cube of ``shape`` voxels, or in the box
|
| 153 |
+
``shape = ((x0, x1), (y0, y1), (z0, z1))`` in millimetres."""
|
| 154 |
+
import plotly.graph_objects as go
|
| 155 |
+
box = np.asarray(shape, np.float64)
|
| 156 |
+
ranges, unit, aspect = (box, "mm", "data") if box.ndim == 2 else (np.stack([np.zeros(3), box], 1), "voxels", "cube")
|
| 157 |
+
fig = go.Figure(data=_lines3d(_by_dominant_axis(paths), AXIS_COLOURS, name=name, width=width, opacity=opacity) + [regions])
|
| 158 |
+
fig.update_layout(scene=dict(xaxis=dict(range=list(ranges[0]), title=f"x ({unit})"), yaxis=dict(range=list(ranges[1]), title="y"),
|
| 159 |
+
zaxis=dict(range=list(ranges[2]), title="z"), aspectmode=aspect),
|
| 160 |
+
margin=dict(l=0, r=0, t=30, b=0), height=560, title=dict(text=title, font=dict(size=13)))
|
| 161 |
+
return fig
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
def _sample(items, n, seed):
|
| 165 |
+
pick = np.random.default_rng(seed).choice(len(items), min(n, len(items)), replace=False)
|
| 166 |
+
return [np.asarray(items[i]) for i in pick]
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
def tractogram3d(tg, regions, shape, *, n=1500, seed=0, total=None):
|
| 170 |
+
"""A random sample of ``n`` streamlines in 3-D, coloured by dominant axis (x red, y green, z blue), the region
|
| 171 |
+
markers; ``total`` is the run's streamline count when ``tg`` is already a sample."""
|
| 172 |
+
paths = [p for p in _sample(tg, n, seed) if len(p) > 1]
|
| 173 |
+
return _figure3d(paths, regions, shape, f"{len(paths):,} of {total or len(tg):,} streamlines (drag to rotate)", name="streamlines", width=2.0, opacity=0.7)
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
def strands3d(strands, diameters_m, regions, shape, *, n=800, seed=0):
|
| 177 |
+
"""A random sample of ``n`` ground-truth strands (centerlines in voxel units, one line width) coloured by
|
| 178 |
+
dominant axis, the region markers; the diameters' range (metres in, µm in the title)."""
|
| 179 |
+
paths = _sample(strands, n, seed)
|
| 180 |
+
return _figure3d(paths, regions, shape, f"{len(paths):,} of {len(strands):,} ground-truth strands, diameters "
|
| 181 |
+
f"{1e6 * diameters_m.min():.1f}-{1e6 * diameters_m.max():.1f} µm (drag to rotate)", name="strands", width=1.5, opacity=0.6)
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
def matrices(M, score, gt_count):
|
| 185 |
+
"""Ours beside the strand-count ground truth on a log colour scale, with the score's numbers."""
|
| 186 |
+
return pair_panel([(f"streamline counts (Pearson {score['pearson_count']:.3f} vs count, {score['pearson_area']:.3f} vs area)", M),
|
| 187 |
+
("ground truth: strand count", gt_count)],
|
| 188 |
+
f"{score['connected_pairs']} of {len(M) * (len(M) - 1) // 2} pairs connected, ground truth {score['gt_pairs']}; "
|
| 189 |
+
f"{score['false_pairs']} false, {score['missed_pairs']} missed")
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
def ground_truth_matrix(gt_count, gt_area, n_pairs):
|
| 193 |
+
"""The two ground-truth matrices; ``n_pairs`` is how many of the 120 pairs the strands connect."""
|
| 194 |
+
return pair_panel([("strand count", gt_count), ("cross-sectional area", gt_area)],
|
| 195 |
+
f"the ground truth: {n_pairs} connected pairs of {len(gt_count) * (len(gt_count) - 1) // 2}", vmin=max(float(gt_area[gt_area > 0].min()), 1e-3))
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
def spread_matrices(spread):
|
| 199 |
+
"""The mean streamline count per pair beside its standard deviation over the repeated runs."""
|
| 200 |
+
return pair_panel([(f"mean count over {spread['n']} keys", spread["mean"]), ("standard deviation over the keys", spread["std"])],
|
| 201 |
+
f"{spread['key']} {spread['pearson_mean']:.3f} ± {spread['pearson_std']:.3f}; median pair CV {spread['cv_median']:.2f}; "
|
| 202 |
+
f"{spread['pairs_always']} pairs in every run, {spread['pairs_any']} in any")
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
def timings_rows(seconds, load_seconds):
|
| 206 |
+
"""The stage times as table rows, the source's load time (once per process) first."""
|
| 207 |
+
rows = [["source loaded (once per process; a long warm-up runs beside the page)", f"{load_seconds:.1f}"]]
|
| 208 |
+
return rows + [[k, f"{v:.2f}"] for k, v in seconds.items()]
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
def map_slice(vol, z, title, *, cmap="viridis", symmetric=False, vmin=None, vmax=None, unit=""):
|
| 212 |
+
"""Axial slice ``z`` of a scalar map (NaN blank): a diverging scale around zero when ``symmetric`` (the
|
| 213 |
+
difference maps), else the map's own range unless ``vmin`` / ``vmax`` fix it."""
|
| 214 |
+
fig, ax = _slice_axes(title)
|
| 215 |
+
sl = np.asarray(vol[:, :, z], np.float64)
|
| 216 |
+
finite = sl[np.isfinite(sl)]
|
| 217 |
+
if symmetric:
|
| 218 |
+
top = float(np.max(np.abs(finite))) if finite.size else 1.0
|
| 219 |
+
top = top or 1.0
|
| 220 |
+
im = ax.imshow(sl.T, origin="lower", cmap="RdBu_r", vmin=-top, vmax=top)
|
| 221 |
+
else:
|
| 222 |
+
lo = float(np.min(finite)) if (vmin is None and finite.size) else (vmin or 0.0)
|
| 223 |
+
hi = float(np.max(finite)) if (vmax is None and finite.size) else (vmax if vmax is not None else 1.0)
|
| 224 |
+
im = ax.imshow(sl.T, origin="lower", cmap=cmap, vmin=lo, vmax=hi if hi > lo else lo + 1e-9)
|
| 225 |
+
fig.colorbar(im, ax=ax, fraction=0.046, label=unit)
|
| 226 |
+
return _image(fig)
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
def grid_box(shape, affine):
|
| 230 |
+
"""The millimetre box ``((x0, x1), (y0, y1), (z0, z1))`` the grid of ``shape`` covers under ``affine``: the 3-D
|
| 231 |
+
views' extent for a source whose tracking frame is not its voxel frame."""
|
| 232 |
+
corners = np.array(np.meshgrid(*[[-0.5, n - 0.5] for n in shape[:3]], indexing="ij")).reshape(3, -1).T
|
| 233 |
+
w = corners @ np.asarray(affine)[:3, :3].T + np.asarray(affine)[:3, 3]
|
| 234 |
+
return tuple((float(a), float(b)) for a, b in zip(w.min(0), w.max(0)))
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
def regions3d(regions, shape):
|
| 238 |
+
"""The regions' centroids alone in 3-D, coloured by group, in the tracking frame's box."""
|
| 239 |
+
return _figure3d([], region_markers(regions), grid_box(shape, regions.affine), f"{regions.n} regions (hover for the name; colour: lobar group)",
|
| 240 |
+
name="regions", width=1.0, opacity=1.0)
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
def _rgb(fractions, z):
|
| 244 |
+
"""An axial slice of three fractions as red / green / blue."""
|
| 245 |
+
return np.clip(np.nan_to_num(np.asarray(fractions, np.float64)[:, :, z, :3]), 0, 1).transpose(1, 0, 2)
|
| 246 |
+
|
| 247 |
+
|
| 248 |
+
def fractions_pair(recovered, truth, z):
|
| 249 |
+
"""The recovered fractions beside the input's at slice ``z`` (WM red, GM green, CSF blue), and their difference
|
| 250 |
+
per tissue; the recovered side says so when the reconstruction estimated none."""
|
| 251 |
+
plt = _mpl()
|
| 252 |
+
fig, axes = plt.subplots(1, 5 if recovered is not None else 1, figsize=(15 if recovered is not None else 4, 3.4))
|
| 253 |
+
axes = np.atleast_1d(axes)
|
| 254 |
+
axes[0].imshow(_rgb(truth, z), origin="lower"); axes[0].set_title(f"input fractions, z = {z} (WM r, GM g, CSF b)", fontsize=8)
|
| 255 |
+
if recovered is not None:
|
| 256 |
+
axes[1].imshow(_rgb(recovered, z), origin="lower"); axes[1].set_title("recovered (multi-tissue CSD)", fontsize=8)
|
| 257 |
+
for k, t in enumerate(("WM", "GM", "CSF")):
|
| 258 |
+
d = np.asarray(recovered, np.float64)[:, :, z, k] - np.asarray(truth, np.float64)[:, :, z, k]
|
| 259 |
+
im = axes[2 + k].imshow(d.T, origin="lower", cmap="RdBu_r", vmin=-0.5, vmax=0.5)
|
| 260 |
+
axes[2 + k].set_title(f"{t}: recovered − input", fontsize=8)
|
| 261 |
+
fig.colorbar(im, ax=axes[-1], fraction=0.046)
|
| 262 |
+
else:
|
| 263 |
+
axes[0].set_title(f"input fractions, z = {z}: the single-tissue reconstruction estimates none", fontsize=8)
|
| 264 |
+
for ax in axes:
|
| 265 |
+
ax.set_xticks([]); ax.set_yticks([])
|
| 266 |
+
return _image(fig)
|
| 267 |
+
|
| 268 |
+
|
| 269 |
+
def input_slices(b0, peaks, amp, fractions, labels, z):
|
| 270 |
+
"""The input at slice ``z``: the mean b = 0 with the WM FOD's principal peaks, the fractions (WM r, GM g, CSF b),
|
| 271 |
+
the parcellation."""
|
| 272 |
+
plt = _mpl()
|
| 273 |
+
from matplotlib.collections import LineCollection
|
| 274 |
+
fig, axes = plt.subplots(1, 3, figsize=(13, 4.4))
|
| 275 |
+
sl = np.nan_to_num(np.asarray(b0, np.float64)[:, :, z])
|
| 276 |
+
axes[0].imshow(sl.T, origin="lower", cmap="gray", vmin=0, vmax=float(np.quantile(sl[sl > 0], 0.99)) if (sl > 0).any() else 1)
|
| 277 |
+
d = peaks[:, :, z]; a = amp[:, :, z]
|
| 278 |
+
ii, jj = np.nonzero(a > 0)
|
| 279 |
+
if len(ii):
|
| 280 |
+
L = 0.45 * a[ii, jj] / a[ii, jj].max()
|
| 281 |
+
seg = np.stack([np.stack([ii - L * d[ii, jj, 0], jj - L * d[ii, jj, 1]], 1), np.stack([ii + L * d[ii, jj, 0], jj + L * d[ii, jj, 1]], 1)], 1)
|
| 282 |
+
axes[0].add_collection(LineCollection(seg, colors=np.abs(d[ii, jj]), linewidths=0.8))
|
| 283 |
+
axes[0].set_title(f"mean b = 0 and the WM FOD's principal peaks, z = {z}", fontsize=8)
|
| 284 |
+
axes[1].imshow(_rgb(fractions, z), origin="lower"); axes[1].set_title("fractions (WM r, GM g, CSF b)", fontsize=8)
|
| 285 |
+
lab = np.asarray(labels)[:, :, z].astype(float)
|
| 286 |
+
axes[2].imshow(np.where(lab > 0, lab, np.nan).T, origin="lower", cmap="tab20", interpolation="nearest")
|
| 287 |
+
axes[2].set_title(f"regions ({int(np.max(labels))})", fontsize=8)
|
| 288 |
+
for ax in axes:
|
| 289 |
+
ax.set_xticks([]); ax.set_yticks([])
|
| 290 |
+
return _image(fig)
|
| 291 |
+
|
| 292 |
+
|
| 293 |
+
def response_curves(true, estimated, note=""):
|
| 294 |
+
"""The packs' exact response at the run's tissue (solid) against the reconstruction's estimate from the replayed
|
| 295 |
+
data (dashed): the WM response of a fibre against the gradient's angle per shell, and GM's and CSF's signal per
|
| 296 |
+
shell, each over its b = 0 value; a tissue the reconstruction did not estimate is drawn true only."""
|
| 297 |
+
plt = _mpl()
|
| 298 |
+
fig, axes = plt.subplots(1, 2, figsize=(10, 3.6))
|
| 299 |
+
if true is None:
|
| 300 |
+
for ax in axes:
|
| 301 |
+
ax.set_axis_off()
|
| 302 |
+
axes[0].set_title("no diffusion-weighted shell: no response to draw", fontsize=9)
|
| 303 |
+
return _image(fig)
|
| 304 |
+
cmap = plt.get_cmap("viridis")
|
| 305 |
+
b = np.asarray(true["b"], np.float64)
|
| 306 |
+
for k, bb in enumerate(b):
|
| 307 |
+
col = cmap(k / max(len(b) - 1, 1))
|
| 308 |
+
axes[0].plot(true["angles"], true["wm"][k], "-", color=col, label=f"b = {bb:g}")
|
| 309 |
+
if estimated is not None and estimated.get("wm") is not None:
|
| 310 |
+
axes[0].plot(estimated["angles"], estimated["wm"][k], "--", color=col)
|
| 311 |
+
axes[0].set_xlabel("angle between the gradient and the fibre (°)"); axes[0].set_ylabel("S / S(b = 0)")
|
| 312 |
+
axes[0].set_title("WM: the pack's exact response (solid) vs the estimate (dashed)", fontsize=9); axes[0].legend(fontsize=7)
|
| 313 |
+
for t, marker in (("gm", "o"), ("csf", "s")):
|
| 314 |
+
axes[1].plot(b, true[t], "-" + marker, label=f"{t.upper()} exact")
|
| 315 |
+
if estimated is not None and estimated.get(t) is not None:
|
| 316 |
+
axes[1].plot(b, estimated[t], "--" + marker, mfc="none", label=f"{t.upper()} estimated")
|
| 317 |
+
axes[1].set_yscale("log"); axes[1].set_xlabel("b (s/mm²)"); axes[1].set_ylabel("S / S(b = 0)")
|
| 318 |
+
axes[1].set_title("GM and CSF" + (f" ({note})" if note else ""), fontsize=9); axes[1].legend(fontsize=7)
|
| 319 |
+
fig.tight_layout()
|
| 320 |
+
return _image(fig)
|
tests/test_acceptance.py
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""The gate: on a GPU with the layout reachable, DiSCo's own protocol replayed from the layout equals the published
|
| 2 |
+
bare reference volume, and the noiseless pipeline scores the connectome within the reference's band with no ground-
|
| 3 |
+
truth pair missed. Prints the per-stage timings (first call and steady) and writes them to ``gate.json``.
|
| 4 |
+
|
| 5 |
+
JAX_PLATFORMS=cuda XLA_FLAGS=--xla_gpu_deterministic_ops=true pytest tests/test_acceptance.py -s
|
| 6 |
+
DISCO_MOMENTS=/local/dir pytest ... # a local copy of the layout instead of the Hub
|
| 7 |
+
"""
|
| 8 |
+
import json
|
| 9 |
+
import os
|
| 10 |
+
import time
|
| 11 |
+
|
| 12 |
+
import numpy as np
|
| 13 |
+
import pytest
|
| 14 |
+
|
| 15 |
+
from space import pipeline as P
|
| 16 |
+
from space import sources
|
| 17 |
+
from space.sources import disco as D
|
| 18 |
+
|
| 19 |
+
CFG = P.config()
|
| 20 |
+
OUT = os.environ.get("GATE_OUT", os.path.join(P.ROOT, "gate.json"))
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
@pytest.fixture(scope="module")
|
| 24 |
+
def layout():
|
| 25 |
+
import jax
|
| 26 |
+
if jax.devices()[0].platform != "gpu":
|
| 27 |
+
pytest.skip("the gate runs on a GPU")
|
| 28 |
+
pytest.importorskip("huggingface_hub")
|
| 29 |
+
t0 = time.perf_counter()
|
| 30 |
+
lay = sources.source(CFG)
|
| 31 |
+
lay.warm()
|
| 32 |
+
lay.load_seconds = time.perf_counter() - t0
|
| 33 |
+
return lay
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
@pytest.mark.parametrize("run", ["bare", "3T", "7T"])
|
| 37 |
+
def test_discos_protocol_from_the_layout_is_the_published_reference_volume(layout, run):
|
| 38 |
+
"""S0-normalised, on every voxel the reference has signal: the replay through the moments is the replay the
|
| 39 |
+
reference was made with, to the float32 arithmetic of the layout; bare, and in the catalogue's white matter at
|
| 40 |
+
3 T and 7 T with every tier on and the field along z (the references' setting)."""
|
| 41 |
+
import nibabel as nib
|
| 42 |
+
from huggingface_hub import hf_hub_download
|
| 43 |
+
p, order = D.disco_protocol(CFG) # order: the table's rows in the protocol's order
|
| 44 |
+
physics = None if run == "bare" else P.Physics.at(float(run[:-1]))
|
| 45 |
+
m = layout.validate(p, physics)
|
| 46 |
+
dwi, floor, factor, secs = layout.replay(m, physics)
|
| 47 |
+
ref_path = hf_hub_download(CFG["data"]["repo"], f"disco/reference/disco_replay_{run}.nii.gz", repo_type="dataset", revision=CFG["data"]["revision"])
|
| 48 |
+
ref = np.asarray(nib.load(ref_path).dataobj, np.float64)[..., order]
|
| 49 |
+
both = np.isfinite(dwi) & (ref != 0)
|
| 50 |
+
d = np.abs(dwi - ref)[both]
|
| 51 |
+
print(f"\nreference check {run}: max |dS| {d.max():.2e}, 99.9 % {np.quantile(d, 0.999):.2e}, median {np.median(d):.2e} "
|
| 52 |
+
f"over {both.any(-1).sum()} voxels; replay {secs:.2f} s")
|
| 53 |
+
assert (~np.isfinite(dwi) & (ref != 0)).any(-1).sum() == 0, "voxels the reference has signal in and the layout has no rows"
|
| 54 |
+
assert d.max() < CFG["gate"]["reference_max_abs_diff"]
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def test_the_noiseless_pipeline_scores_within_the_references_band(layout):
|
| 58 |
+
"""Pearson vs strand count at or above the gate's floor (the replay reference's band is 0.912 +- 0.003; the
|
| 59 |
+
tracker on the reference volume measured 0.927) and no ground-truth pair missed; the timings recorded."""
|
| 60 |
+
p, _ = D.disco_protocol(CFG)
|
| 61 |
+
tr = P.Tracking(**{k: CFG["tracking"][k] for k in ("density", "step_mm", "max_angle", "max_steps")})
|
| 62 |
+
first = P.run(layout, p, snr=None, tracking=tr) # includes every compile
|
| 63 |
+
steady = P.run(layout, p, snr=None, tracking=tr)
|
| 64 |
+
s = steady.score
|
| 65 |
+
table = dict(device=str(__import__("jax").devices()[0]), layout_load_seconds=layout.load_seconds,
|
| 66 |
+
first_call=first.seconds, steady=steady.seconds, score=s, streamlines=len(steady.tractogram),
|
| 67 |
+
seeds=int(len(steady.seeds)), n_meas=p.n_meas)
|
| 68 |
+
print("\ngate: " + json.dumps(table, indent=1))
|
| 69 |
+
with open(OUT, "w") as f:
|
| 70 |
+
json.dump(table, f, indent=1)
|
| 71 |
+
assert s["pearson_count"] >= CFG["gate"]["pearson_count_min"], s
|
| 72 |
+
assert s["missed_pairs"] <= CFG["gate"]["missed_pairs_max"], s
|
| 73 |
+
assert first.score["pearson_count"] == s["pearson_count"] # the same key: the same tractogram (deterministic XLA ops)
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
@pytest.mark.parametrize("machine", [m["key"] for m in CFG["scanners"]["machines"]])
|
| 77 |
+
def test_a_machine_on_discos_protocol_moves_the_image_and_is_timed(layout, machine):
|
| 78 |
+
"""Each machine of the menu at 7.9 cm from isocentre along R-L on DiSCo's own protocol (none of them can play it:
|
| 79 |
+
the gradient limit is the page's, the replay's cost is measured here at the gate's protocol), against the ideal
|
| 80 |
+
scanner at the machine's field and direction: the delivered image is finite where the ideal one is and moves it;
|
| 81 |
+
the first and steady replay seconds of both go to ``gate_scanners.json`` beside ``gate.json``. A machine with its
|
| 82 |
+
own gradient needs the layout's background moments and is skipped by name on a layout without them."""
|
| 83 |
+
from dataclasses import replace
|
| 84 |
+
L = P.limits(machine)
|
| 85 |
+
if L.has_field_law and not layout.moments.background:
|
| 86 |
+
pytest.skip(f"{machine}'s own gradient needs the layout's background moments (shape_moments.stamp_background)")
|
| 87 |
+
p, _ = D.disco_protocol(CFG)
|
| 88 |
+
ideal = P.Physics.at(float(L.field_T), b0_direction=tuple(L.b0_axis or (0.0, 0.0, 1.0)))
|
| 89 |
+
far = replace(ideal, scanner=machine, offset_m=(0.079, 0.0, 0.0))
|
| 90 |
+
m = layout.validate(p, far)
|
| 91 |
+
secs = {}
|
| 92 |
+
for tag, ph in (("ideal", ideal), ("machine", far)):
|
| 93 |
+
for k in ("first", "steady"):
|
| 94 |
+
dwi, _, factor, s = layout.replay(m, ph)
|
| 95 |
+
secs[f"{tag}_{k}"] = s
|
| 96 |
+
if tag == "ideal":
|
| 97 |
+
ref = dwi
|
| 98 |
+
both = np.isfinite(ref)
|
| 99 |
+
assert (np.isfinite(dwi) == both).all()
|
| 100 |
+
moved = float(np.max(np.abs(dwi - ref)[both]))
|
| 101 |
+
print(f"\n{machine} at 7.9 cm on DiSCo 364: max |dS| vs ideal {moved:.3e}; seconds {json.dumps(secs)}")
|
| 102 |
+
assert moved > 1e-3
|
| 103 |
+
path = os.path.join(os.path.dirname(OUT), "gate_scanners.json")
|
| 104 |
+
table = json.load(open(path)) if os.path.exists(path) else {}
|
| 105 |
+
table[machine] = dict(seconds=secs, max_abs_dS=moved, n_meas=p.n_meas, offset_m=list(far.offset_m), device=str(__import__("jax").devices()[0]))
|
| 106 |
+
with open(path, "w") as f:
|
| 107 |
+
json.dump(table, f, indent=1)
|
tests/test_app.py
ADDED
|
@@ -0,0 +1,285 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""The page's acquisition choice without a browser: DiSCo's table, a config preset, the shell rows (a stored class in
|
| 2 |
+
demo mode, the row's own delta / Delta / TE in full mode), a scheme upload only in full mode; an unknown choice
|
| 3 |
+
refused (no Gradio needed: the mapping lives beside the page, not in a widget)."""
|
| 4 |
+
import types
|
| 5 |
+
|
| 6 |
+
import numpy as np
|
| 7 |
+
import pytest
|
| 8 |
+
|
| 9 |
+
from space import app as A
|
| 10 |
+
from space import pipeline as P
|
| 11 |
+
from space.sources import disco as D
|
| 12 |
+
|
| 13 |
+
CFG = P.config()
|
| 14 |
+
S = D.Disco
|
| 15 |
+
ROWS = [True, "d12-D24", 1000, 30, 10.0, 20.0, 60.0, True, "d8-D20", 3000, 45, 8.0, 20.0, 60.0,
|
| 16 |
+
False, "d17-D30", 3000, 90, 17.0, 30.0, 60.0, False, "d17-D30", 6000, 60, 17.0, 30.0, 60.0]
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def test_the_three_kinds_of_acquisition():
|
| 20 |
+
disco = A._protocol_from_inputs(S, CFG, "DiSCo 364", 5, *ROWS)
|
| 21 |
+
assert disco.name == "DiSCo 364" and disco.n_meas == 364 and disco.n_b0 == 4 # the table's own, not the slider's
|
| 22 |
+
name = next(iter(CFG["presets"]))
|
| 23 |
+
preset = A._protocol_from_inputs(S, CFG, name, 5, *ROWS)
|
| 24 |
+
assert preset.name == name and preset.n_b0 == CFG["presets"][name]["n_b0"]
|
| 25 |
+
assert [s.shape for s in preset.shells] == [s["shape"] for s in CFG["presets"][name]["shells"]]
|
| 26 |
+
custom = A._protocol_from_inputs(S, CFG, A.CUSTOM, 2, *ROWS)
|
| 27 |
+
assert custom.n_b0 == 2 and [(s.shape, s.b, s.n_dirs) for s in custom.shells] == [("d12-D24", 1000.0, 30), ("d8-D20", 3000.0, 45)]
|
| 28 |
+
assert not any(s.free_timing for s in custom.shells)
|
| 29 |
+
with pytest.raises(ValueError, match="unknown acquisition"):
|
| 30 |
+
A._protocol_from_inputs(S, CFG, "something else", 2, *ROWS)
|
| 31 |
+
with pytest.raises(ValueError, match="at least one shell"):
|
| 32 |
+
A._protocol_from_inputs(S, CFG, A.CUSTOM, 2, *([False] + ROWS[1:7] + [False] + ROWS[8:14] + ROWS[14:]))
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def test_full_mode_takes_the_rows_own_timing_and_demo_mode_refuses_the_upload():
|
| 36 |
+
full = A._protocol_from_inputs(S, CFG, A.CUSTOM, 2, *ROWS, full=True)
|
| 37 |
+
assert all(s.free_timing for s in full.shells)
|
| 38 |
+
assert [(s.delta, s.Delta, s.TE) for s in full.shells] == [(0.010, 0.020, 0.060), (0.008, 0.020, 0.060)]
|
| 39 |
+
with pytest.raises(ValueError, match="full mode"):
|
| 40 |
+
A._protocol_from_inputs(S, CFG, A.UPLOADED, 2, *ROWS, scheme="x.scheme")
|
| 41 |
+
with pytest.raises(ValueError, match="upload"):
|
| 42 |
+
A._protocol_from_inputs(S, CFG, A.UPLOADED, 2, *ROWS, scheme=None, full=True)
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def _values(on=True, field_T=3.0, **over):
|
| 46 |
+
nums = S.catalogue_numbers(CFG, field_T)[:-1]
|
| 47 |
+
v = dict(zip(D.physics_fields(CFG), [on, field_T, next(iter(D.B0_MODES)), 0, 0] + nums + [True, True, True, 7.9, next(iter(D.OFFSET_AXES))]))
|
| 48 |
+
v.update(over)
|
| 49 |
+
return v
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def test_the_physics_panel_is_a_physics_in_si_or_none_when_off():
|
| 53 |
+
nums = S.catalogue_numbers(CFG, 3.0)
|
| 54 |
+
assert nums[-1].startswith("catalogue values at 3 T") and S.catalogue_numbers(CFG, 0.064)[-1].startswith("the catalogue has no cited")
|
| 55 |
+
ph = S.physics_from(CFG, _values(field=False))
|
| 56 |
+
assert ph.field_T == 3.0 and ph.T2["intra"] == nums[0] * 1e-3 and ph.rho2 == nums[4] * 1e-6 and not ph.field and ph.relaxation and ph.pools == D.pools(CFG)
|
| 57 |
+
assert S.physics_from(CFG, _values(on=False)) is None
|
| 58 |
+
free = S.physics_from(CFG, _values(field_T=7.0, b0_mode=D.FREE_B0, theta=90, phi=90))
|
| 59 |
+
assert abs(free.b0_direction[1] - 1.0) < 1e-12
|
| 60 |
+
with pytest.raises(ValueError, match="17 inputs"):
|
| 61 |
+
A.physics_values(S, CFG, 1, 2, 3)
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def test_a_knob_changes_one_thing_of_a():
|
| 65 |
+
"""Every knob maps to B = A with that one change: the field takes the catalogue tissue with it, a tier goes off,
|
| 66 |
+
the tissue goes off, the noise changes, every shell is retimed; A's other settings survive; a panel knob on an
|
| 67 |
+
A whose panel is off is refused (B would differ in two things)."""
|
| 68 |
+
v = _values()
|
| 69 |
+
prot = A._protocol_from_inputs(S, CFG, A.CUSTOM, 2, *ROWS)
|
| 70 |
+
ks = S.knobs(CFG)
|
| 71 |
+
assert ks[A.NO_KNOB] is None and len(ks) == 1 + 5 + 2 + 3 + 1 + 3 + len(CFG["shapes"])
|
| 72 |
+
for name, change in ks.items():
|
| 73 |
+
if change is None:
|
| 74 |
+
continue
|
| 75 |
+
pb, on, snr, vb = S.apply_knob(CFG, change, prot, True, 30.0, v)
|
| 76 |
+
diffs = [k for k in D.physics_fields(CFG) if vb[k] != v[k]]
|
| 77 |
+
kind = change[0]
|
| 78 |
+
if kind == "field":
|
| 79 |
+
assert vb["field_T"] == change[1] and [vb[k] for k in D.tissue_numbers(CFG)] == S.catalogue_numbers(CFG, change[1])[:-1] and pb is prot
|
| 80 |
+
elif kind == "b0":
|
| 81 |
+
assert diffs == ["b0_mode"] or (diffs == [] and change[1] == v["b0_mode"])
|
| 82 |
+
elif kind == "tier":
|
| 83 |
+
assert diffs == [change[1]] and vb[change[1]] is False
|
| 84 |
+
elif kind == "bare":
|
| 85 |
+
assert diffs == ["on"] and S.physics_from(CFG, vb) is None
|
| 86 |
+
elif kind == "snr":
|
| 87 |
+
assert diffs == [] and (on, snr) == ((False, 30.0) if change[1] is None else (True, change[1]))
|
| 88 |
+
elif kind == "shape":
|
| 89 |
+
assert diffs == [] and all(s.shape == change[1] for s in pb.shells) and [s.b for s in pb.shells] == [s.b for s in prot.shells]
|
| 90 |
+
if kind in ("field", "b0", "tier"):
|
| 91 |
+
with pytest.raises(ValueError, match="which is off for A"):
|
| 92 |
+
S.apply_knob(CFG, change, prot, True, 30.0, _values(on=False))
|
| 93 |
+
with pytest.raises(ValueError, match="unknown knob"):
|
| 94 |
+
S.apply_knob(CFG, ("what", 1), prot, True, 30.0, v)
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def test_compare_is_symmetric_in_its_pairs_and_zero_for_the_same_run():
|
| 98 |
+
M = np.zeros((16, 16)); M[0, 1] = M[1, 0] = 5; M[2, 3] = M[3, 2] = 2
|
| 99 |
+
N = M.copy(); N[4, 5] = N[5, 4] = 1; N[2, 3] = N[3, 2] = 0
|
| 100 |
+
a = types.SimpleNamespace(matrix=M, score=dict(pearson_count=0.9, pearson_area=0.8))
|
| 101 |
+
b = types.SimpleNamespace(matrix=N, score=dict(pearson_count=0.85, pearson_area=0.8))
|
| 102 |
+
c = D.compare(a, b)
|
| 103 |
+
assert c["only_a"] == 1 and c["only_b"] == 1 and abs(c["delta_count"] + 0.05) < 1e-12 and c["delta_area"] == 0
|
| 104 |
+
same = D.compare(a, a)
|
| 105 |
+
assert same["only_a"] == 0 and same["pearson_ab"] == 1.0
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
PRISMA = "Siemens Prisma 3 T"
|
| 109 |
+
SWOOP = next(k for k in P.machines(CFG) if k.startswith("Hyperfine Swoop"))
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def test_the_gradient_table_names_the_shell_the_scanner_cannot_play():
|
| 113 |
+
prot = A._protocol_from_inputs(S, CFG, A.CUSTOM, 2, *ROWS)
|
| 114 |
+
table, ok = A.gradient_text(CFG, prot, CFG["shapes"], PRISMA)
|
| 115 |
+
assert "70 mT/m" in table and "194 mT/m" in table and "cannot play" in table and not ok # shell 2: b 3000 at δ 8 / Δ 20
|
| 116 |
+
assert A.gradient_text(CFG, prot, CFG["shapes"], A.IDEAL)[1]
|
| 117 |
+
with pytest.raises(ValueError, match="no scanner"):
|
| 118 |
+
A.gradient_text(CFG, prot, CFG["shapes"], "a magnet nobody built")
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def test_the_scanner_menu_names_every_term_and_where_it_comes_from():
|
| 122 |
+
"""The term table of each machine: the Swoop applies every term (its field law measured, its nonlinearity's
|
| 123 |
+
diagonal derived from a measurement), the cylinders their class-model nonlinearity and the Maxwell term, with
|
| 124 |
+
their own gradient and transmit map absent and said so; the ideal scanner none."""
|
| 125 |
+
assert list(P.machines(CFG).values()) == ["hyperfine_swoop_64mT", "siemens_magnetom_prisma_3T", "siemens_magnetom_terra_7T"]
|
| 126 |
+
sw = {t: (on, src) for t, on, src in P.scanner_terms("hyperfine_swoop_64mT")}
|
| 127 |
+
assert all(on for on, _ in sw.values()) and "0.064 T along (0, 1, 0)" in sw["field strength and direction"][1]
|
| 128 |
+
assert "measured" in sw["transmit scale B1"][1] and "derived from a measurement" in sw["gradient nonlinearity L"][1]
|
| 129 |
+
pr = {t: (on, src) for t, on, src in P.scanner_terms("siemens_magnetom_prisma_3T")}
|
| 130 |
+
assert pr["gradient nonlinearity L"][0] and "inferred from the class" in pr["gradient nonlinearity L"][1]
|
| 131 |
+
assert not pr["field law: its gradient g0 (and its value, a phase per voxel)"][0] and "absent" in pr["field law: its gradient g0 (and its value, a phase per voxel)"][1]
|
| 132 |
+
assert not pr["transmit scale B1"][0] and "0.7-1.2" in pr["transmit scale B1"][1] and pr["Maxwell (concomitant) gradient"][0]
|
| 133 |
+
assert "ideal" in P.scanner_text(CFG, A.IDEAL) and "| transmit scale B1 | no |" in P.scanner_text(CFG, PRISMA)
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def test_a_machine_sets_the_field_its_direction_and_the_placement():
|
| 137 |
+
"""DiSCo's physics on a machine: the machine's field and direction whatever the panel says, the phantom's centre at
|
| 138 |
+
the panel's distance along its axis, the bare diffusion on the machine when the tissue is off; the ideal scanner
|
| 139 |
+
keeps the panel's field and no placement."""
|
| 140 |
+
v = dict(_values(), field_T=1.5, offset_cm=7.9, offset_axis="A-P (y)")
|
| 141 |
+
ph = S.physics_from(CFG, v, scanner="hyperfine_swoop_64mT")
|
| 142 |
+
assert ph.field_T == 0.064 and ph.b0_direction == (0.0, 1.0, 0.0) and np.allclose(ph.offset_m, (0.0, 0.079, 0.0))
|
| 143 |
+
assert ph.scanner == "hyperfine_swoop_64mT" and "hyperfine_swoop_64mT" in ph.label()
|
| 144 |
+
off = S.physics_from(CFG, dict(v, on=False), scanner="siemens_magnetom_prisma_3T")
|
| 145 |
+
assert off.bare and off.scanner == "siemens_magnetom_prisma_3T" and off.field_T == 3.0
|
| 146 |
+
assert S.physics_from(CFG, dict(v, on=False)) is None
|
| 147 |
+
ideal = S.physics_from(CFG, v)
|
| 148 |
+
assert ideal.field_T == 1.5 and ideal.scanner is None and ideal.offset_m == (0.0, 0.0, 0.0)
|
| 149 |
+
with pytest.raises(ValueError, match="T magnet"):
|
| 150 |
+
P.Physics.at(3.0, scanner="hyperfine_swoop_64mT")
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
class _Demo(D.Disco):
|
| 154 |
+
"""A demo source without replay data: validates as a tiered layout would."""
|
| 155 |
+
mode = "demo"
|
| 156 |
+
tiers = True
|
| 157 |
+
|
| 158 |
+
def validate(self, protocol, physics):
|
| 159 |
+
if physics and not physics.bare and not self.tiers:
|
| 160 |
+
raise ValueError("bare only")
|
| 161 |
+
if physics and set(physics.pools) != set(self.pools):
|
| 162 |
+
raise ValueError("pools")
|
| 163 |
+
return P.measurements(protocol, self.shapes)
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
def test_the_runs_are_planned_and_refused_before_any_work():
|
| 167 |
+
"""plan_runs: A alone, A + B with a knob, the scanner's refusal naming the run, the source's refusal, and the
|
| 168 |
+
upload refused in demo mode."""
|
| 169 |
+
src = _Demo(CFG)
|
| 170 |
+
v = _values()
|
| 171 |
+
runs = A.plan_runs(CFG, src, A.CUSTOM, 2, True, 30.0, None, A.NO_KNOB, A.IDEAL, v, ROWS)
|
| 172 |
+
assert [r[0] for r in runs] == ["A"] and runs[0][4].field_T == 3.0
|
| 173 |
+
runs = A.plan_runs(CFG, src, A.CUSTOM, 2, True, 30.0, None, "SNR → 10", A.IDEAL, v, ROWS)
|
| 174 |
+
assert [r[0] for r in runs] == ["A", "B"] and runs[1][3] == 10.0 and runs[1][1] is runs[0][1]
|
| 175 |
+
with pytest.raises(ValueError, match="cannot play run A"):
|
| 176 |
+
A.plan_runs(CFG, src, A.CUSTOM, 2, True, 30.0, None, A.NO_KNOB, SWOOP, v, ROWS)
|
| 177 |
+
with pytest.raises(ValueError, match="cannot play run B"):
|
| 178 |
+
A.plan_runs(CFG, src, "clinical b1000 x 30", 1, True, 30.0, None, "every shell's pulse timing → d8-D20 (Connectome 2.0 δ 8 / Δ 20 ms)", PRISMA, v, ROWS)
|
| 179 |
+
with pytest.raises(ValueError, match="fixes the field"):
|
| 180 |
+
A.plan_runs(CFG, src, "clinical b1000 x 30", 1, True, 30.0, None, "field → 7 T (catalogue tissue at that field)", PRISMA, v, ROWS)
|
| 181 |
+
runs = A.plan_runs(CFG, src, "clinical b1000 x 30", 1, True, 30.0, None, A.NO_KNOB, PRISMA, v, ROWS)
|
| 182 |
+
assert runs[0][4].scanner == "siemens_magnetom_prisma_3T" and runs[0][4].field_T == 3.0
|
| 183 |
+
src.tiers = False
|
| 184 |
+
with pytest.raises(ValueError, match="bare only"):
|
| 185 |
+
A.plan_runs(CFG, src, A.CUSTOM, 2, True, 30.0, None, A.NO_KNOB, A.IDEAL, v, ROWS)
|
| 186 |
+
with pytest.raises(ValueError, match="full mode"):
|
| 187 |
+
A.plan_runs(CFG, src, A.UPLOADED, 2, True, 30.0, "x.scheme", A.NO_KNOB, A.IDEAL, _values(on=False), ROWS)
|
| 188 |
+
with pytest.raises(ValueError, match="unknown knob"):
|
| 189 |
+
A.plan_runs(CFG, src, A.CUSTOM, 2, True, 30.0, None, "twist", A.IDEAL, v, ROWS)
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
def test_disco_prepares_nothing_so_the_lookup_and_the_worker_have_nothing_to_do(monkeypatch):
|
| 193 |
+
"""DiSCo has no share outside the device: prepare_runs gives None for every entry, the worker computes nothing and
|
| 194 |
+
says nothing, the payload has no response seconds and the reservation has no response part."""
|
| 195 |
+
src = _Demo(CFG)
|
| 196 |
+
monkeypatch.setattr(A, "_load", lambda: dict(error=None, source=src, cfg=CFG))
|
| 197 |
+
v = _values()
|
| 198 |
+
args = [A.CUSTOM, 2, True, 30.0, 2, 30.0, 0.5, 0, None, "SNR → 10", A.IDEAL, 1, True, *v.values(), *ROWS]
|
| 199 |
+
prepared = A.prepare_runs(*args)
|
| 200 |
+
assert prepared["runs"] == {"A": None, "B": None} and all(p is None for p in prepared["ladder"])
|
| 201 |
+
runs = A.plan_runs(CFG, src, A.CUSTOM, 2, True, 30.0, None, "SNR → 10", A.IDEAL, v, ROWS)
|
| 202 |
+
gen = A._fill(src, runs, True, prepared)
|
| 203 |
+
with pytest.raises(StopIteration) as stop:
|
| 204 |
+
next(gen)
|
| 205 |
+
assert stop.value.value == (prepared, {}, None)
|
| 206 |
+
assert src.responses([(m, ph) for _, m, ph in A.response_entries(src, runs, True)]) == []
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
def test_the_estimated_seconds_grow_with_the_run_and_stay_in_the_pools_window():
|
| 210 |
+
v = list(_values().values())
|
| 211 |
+
one = A.estimated_seconds("DiSCo 364", 1, True, 30, 2, 30.0, 0.5, 0, None, A.NO_KNOB, A.IDEAL, 1, False, *v, *ROWS)
|
| 212 |
+
two = A.estimated_seconds("DiSCo 364", 1, True, 30, 2, 30.0, 0.5, 0, None, "SNR → 10", A.IDEAL, 1, False, *v, *ROWS)
|
| 213 |
+
keys = A.estimated_seconds("DiSCo 364", 1, True, 30, 2, 30.0, 0.5, 0, None, A.NO_KNOB, A.IDEAL, 8, False, *v, *ROWS)
|
| 214 |
+
ladder = A.estimated_seconds("DiSCo 364", 1, True, 30, 2, 30.0, 0.5, 0, None, A.NO_KNOB, A.IDEAL, 1, True, *v, *ROWS)
|
| 215 |
+
small = A.estimated_seconds("clinical b1000 x 30", 1, True, 30, 2, 30.0, 0.5, 0, None, A.NO_KNOB, A.IDEAL, 1, False, *v, *ROWS)
|
| 216 |
+
assert 30 <= small < one < two <= 480 and one < keys <= 480 and one < ladder <= 480
|
| 217 |
+
both = A.estimated_seconds("DiSCo 364", 1, True, 30, 2, 30.0, 0.5, 0, None, "SNR → 10", A.IDEAL, 1, True, *v, *ROWS)
|
| 218 |
+
assert one < ladder < both <= 120 # DiSCo alone, with the ladder, and A + B + ladder all fit a logged-out visitor's quota
|
| 219 |
+
assert A.estimated_seconds("nonsense", 1, True, 30, 2, 30.0, 0.5, 0, None, A.NO_KNOB, A.IDEAL, 1, True, *v, *ROWS) == 480
|
| 220 |
+
text = A.gpu_seconds_text("DiSCo 364", 1, True, 30, 2, 30.0, 0.5, 0, None, A.NO_KNOB, A.IDEAL, 1, True, *v, *ROWS)
|
| 221 |
+
assert f"reserves {ladder} s" in text and "logged out" in text.split("started by")[1].split(".")[0]
|
| 222 |
+
assert len(A.OUTPUTS) == 30
|
| 223 |
+
|
| 224 |
+
|
| 225 |
+
def test_the_explorer_draws_layers_differences_and_metrics_from_its_state():
|
| 226 |
+
"""A two-layer explorer state (bare, A) with B: every mode and quantity returns an image; the table has one row
|
| 227 |
+
per layer step per shell plus the floor; an empty state draws nothing."""
|
| 228 |
+
p = P.Protocol((P.Shell("d12-D24", 1000, 12),), n_b0=1)
|
| 229 |
+
m = P.measurements(p, CFG["shapes"])
|
| 230 |
+
rng = np.random.default_rng(0)
|
| 231 |
+
bare = rng.uniform(0.3, 1.0, (4, 4, 2, 13)).astype(np.float16); a = (bare * 0.98).astype(np.float16); b = (bare * 0.97).astype(np.float16)
|
| 232 |
+
md = rng.random((4, 4, 2)).astype(np.float16); fa = rng.random((4, 4, 2)).astype(np.float16)
|
| 233 |
+
ex = dict(layers=[("bare diffusion", bare), ("A = bare + field", a), ("B = A with field → 7 T", b)], metrics={k: (md, fa) for k in ("bare diffusion", "A = bare + field", "B = A with field → 7 T")},
|
| 234 |
+
floor=np.full((4, 4, 2), 0.01, np.float32), meas=m, mask=np.ones((4, 4, 2), bool),
|
| 235 |
+
ingredients=S.ingredient_layers(dict(intra_fraction=rng.random((4, 4, 2)), wall_contact_um=rng.random((4, 4, 2)), contact_survival=None, field_rad=None, D_walk=6e-10)),
|
| 236 |
+
differences=P.layer_differences([("bare diffusion", bare.astype(np.float32)), ("A", a.astype(np.float32)), ("B", b.astype(np.float32))], m, np.ones((4, 4, 2), bool)),
|
| 237 |
+
snr=None, physics=None)
|
| 238 |
+
for mode in A.EXPLORE_MODES:
|
| 239 |
+
for metric in A.METRICS:
|
| 240 |
+
img = A.explore(ex, "A = bare + field", mode, metric, 1, 5)
|
| 241 |
+
assert img is not None and img.size[0] > 100, (mode, metric)
|
| 242 |
+
assert A.explore(ex, "bare diffusion", "minus the previous layer", A.METRICS[0], 0, 0) is not None
|
| 243 |
+
pool, contact, fld = A.ingredient_views(ex, 1)
|
| 244 |
+
assert pool is not None and contact is not None and fld is None
|
| 245 |
+
rows = A.layer_table(ex)
|
| 246 |
+
assert len(rows) == 2 + 1 and rows[-1][0] == "replay floor"
|
| 247 |
+
assert A._layer_labels(P.Physics.at(3.0, contact=False), "SNR → 10") == ("A = bare + relaxation + field", "B = A with SNR → 10")
|
| 248 |
+
assert A._layer_labels(None, A.NO_KNOB)[0] == "A = bare diffusion"
|
| 249 |
+
assert A.explore(None, "A", "signal", A.METRICS[0], 0, 0) is None and A.ingredient_views(None, 0) == (None, None, None) and A.layer_table(None) == []
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
def test_the_run_button_chains_the_devices_texts_into_the_headline_then_the_pages_outputs(monkeypatch):
|
| 253 |
+
"""run_pipeline: every (text, fraction) of the compute function becomes a headline-only update (the progress bar
|
| 254 |
+
following), the payload goes to present once the device part has ended, and its outputs are the last yield."""
|
| 255 |
+
pytest.importorskip("gradio")
|
| 256 |
+
kept = []
|
| 257 |
+
source = types.SimpleNamespace(keep=kept.append)
|
| 258 |
+
monkeypatch.setattr(A, "_load", lambda: dict(error=None, load_seconds=1.0, regions=None, source=source))
|
| 259 |
+
monkeypatch.setattr(A, "prepare_runs", lambda *args: dict(runs={"A": args}, ladder=None))
|
| 260 |
+
seen = []
|
| 261 |
+
monkeypatch.setattr(A, "present", lambda payload, state: seen.append(payload) or ("drawn",) * len(A.OUTPUTS))
|
| 262 |
+
|
| 263 |
+
def fake_compute(prepared, *args):
|
| 264 |
+
assert prepared["runs"]["A"] == args
|
| 265 |
+
yield ("**A · 1/5 replay** …", 0.1)
|
| 266 |
+
yield ("**A · 2/5 noise** …", 0.3)
|
| 267 |
+
yield dict(results={}, compute_seconds=12.0, kernels={"key": "computed on the worker"})
|
| 268 |
+
bars = []
|
| 269 |
+
out = list(A.run_pipeline(fake_compute, "x", 1, progress=lambda f, desc: bars.append((f, desc))))
|
| 270 |
+
assert "starting" in out[0][1] and [o[1] for o in out[1:3]] == ["**A · 1/5 replay** …", "**A · 2/5 noise** …"] and all(len(o) == len(A.OUTPUTS) for o in out[:4])
|
| 271 |
+
assert "drawing" in out[3][1] and out[4] == ("drawn",) * len(A.OUTPUTS)
|
| 272 |
+
assert bars == [(0.0, "starting"), (0.1, "A · 1/5 replay"), (0.3, "A · 2/5 noise")] and seen[0]["compute_seconds"] == 12.0
|
| 273 |
+
assert kept == [{"key": "computed on the worker"}] # the page keeps what the worker computed, before drawing
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
def test_the_payload_carries_float32_volumes():
|
| 277 |
+
"""_light: the DWI and the clean replay cross the fork as float32, everything else of the result as it was."""
|
| 278 |
+
p = P.Protocol((P.Shell("d12-D24", 1000, 6),), n_b0=1)
|
| 279 |
+
m = P.measurements(p, CFG["shapes"])
|
| 280 |
+
dwi = np.random.default_rng(0).random((2, 2, 2, 7)); floor = np.zeros((2, 2, 2))
|
| 281 |
+
res = P.Result(p, m, dwi, floor, np.ones((2, 2, 2)), np.zeros((2, 2, 2, 45)), None, None, np.zeros((16, 16)), {}, clean=dwi * 0.5, snr=30.0)
|
| 282 |
+
light = A._light(res)
|
| 283 |
+
assert light.dwi.dtype == np.float32 and light.clean.dtype == np.float32 and res.dwi.dtype == np.float64
|
| 284 |
+
np.testing.assert_allclose(light.dwi, dwi, rtol=1e-6); assert light.snr == 30.0 and light.meas is m
|
| 285 |
+
assert A._light(P.Result(p, m, dwi, floor, None, None, None, None, None, {})).clean is None
|
tests/test_brain.py
ADDED
|
@@ -0,0 +1,820 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""The brain source: the asset's layout (the BATMAN fixture of ``tools/build_brain_fixture.py``, local only), the
|
| 2 |
+
kernel-route replay against dmipy-sim's own ``Phantom.compose(...).replay`` (the oracle), the connectome of a known
|
| 3 |
+
tractogram, the reservation model, the panel and its knobs, the refusals, and the page's chain on a small crop of the
|
| 4 |
+
fixture. Skipped where the fixture or the packs are not on this machine; ``DISCO_BRAIN_FIXTURE`` and
|
| 5 |
+
``DISCO_BRAIN_PACKS`` point at them."""
|
| 6 |
+
import json
|
| 7 |
+
import os
|
| 8 |
+
|
| 9 |
+
import numpy as np
|
| 10 |
+
import pytest
|
| 11 |
+
|
| 12 |
+
from space import pipeline as P
|
| 13 |
+
from space.sources import brain as B
|
| 14 |
+
|
| 15 |
+
FIXTURE = os.environ.get("DISCO_BRAIN_FIXTURE", os.path.expanduser("~/dmrai-ws/data/batman/brain_fixture"))
|
| 16 |
+
PACKS = os.environ.get("DISCO_BRAIN_PACKS", os.path.expanduser("~/dmrai-ws/packs"))
|
| 17 |
+
WM_PACK = os.path.join(PACKS, "single_bundle_1s_c3_seg125ms.rpk")
|
| 18 |
+
GM_PACK = os.path.join(PACKS, "gm_spheres_100ms.rpk")
|
| 19 |
+
has_fixture = pytest.mark.skipif(not os.path.exists(os.path.join(FIXTURE, "manifest.json")), reason="the BATMAN brain fixture is not on this machine")
|
| 20 |
+
has_packs = pytest.mark.skipif(not (os.path.exists(WM_PACK) and os.path.exists(GM_PACK)), reason="the WM and GM packs are not on this machine")
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def brain_cfg(asset=FIXTURE):
|
| 24 |
+
"""brain.toml with the asset and the packs local (the tests never touch the network)."""
|
| 25 |
+
cfg = P.config(os.path.join(P.HERE, "brain.toml"))
|
| 26 |
+
cfg["asset"] = {"local": asset}
|
| 27 |
+
cfg["packs"] = {"wm": [{"label": "CACTUS single bundle, 1 s in 125 ms windows", "uri": WM_PACK}],
|
| 28 |
+
"gm": [{"label": "grey-matter spheres, 100 ms", "uri": GM_PACK}]}
|
| 29 |
+
return cfg
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def default_values(cfg):
|
| 33 |
+
panel = B.Brain.panel(cfg)
|
| 34 |
+
return {c.name: c.value for row in panel.rows for c in row if c.name in panel.fields}
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
@pytest.fixture(scope="module")
|
| 38 |
+
def brain():
|
| 39 |
+
if not os.path.exists(os.path.join(FIXTURE, "manifest.json")):
|
| 40 |
+
pytest.skip("the BATMAN brain fixture is not on this machine")
|
| 41 |
+
return B.Brain(brain_cfg())
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
@has_fixture
|
| 45 |
+
def test_the_fixture_loads_in_the_assets_layout(brain):
|
| 46 |
+
"""Every file of the contract, cropped to the brain with its affine shifted, 84 regions in 14 lobar groups, the
|
| 47 |
+
FOD a unit-integral density per voxel, the fractions shares of a voxel, the scan's protocol in the image frame."""
|
| 48 |
+
a = brain.asset
|
| 49 |
+
man = a.manifest
|
| 50 |
+
assert a.fod.shape == a.mask.shape + (45,) and a.fractions.shape == a.mask.shape + (3,) and a.labels.shape == a.mask.shape
|
| 51 |
+
assert all(s < n for s, n in zip(a.mask.shape, man["grid"]["shape"])) and int(a.mask.sum()) == 90205
|
| 52 |
+
lo = np.array([c.start for c in a.crop])
|
| 53 |
+
np.testing.assert_allclose(a.affine[:3, 3], np.asarray(man["grid"]["affine"])[:3, :3] @ lo + np.asarray(man["grid"]["affine"])[:3, 3])
|
| 54 |
+
assert brain.regions.n == 84 and len(brain.regions.groups) == 14 and sorted(i for _, ids in brain.regions.groups for i in ids) == list(range(1, 85))
|
| 55 |
+
np.testing.assert_allclose(brain.fod_unit[brain.f[:, 0] > 0][:, 0], B.C00, rtol=1e-5)
|
| 56 |
+
assert (a.fractions.sum(-1) <= 1 + 1e-6).all() and (a.stop <= a.mask).all()
|
| 57 |
+
prot = B.Brain.protocol(brain.cfg, B.Brain.presets(brain.cfg)[0])
|
| 58 |
+
assert prot.n_meas == len(man["protocol"]["bvals_s_mm2"]) and {s.shape for s in prot.shells} == {B.SCAN}
|
| 59 |
+
g = np.asarray(man["protocol"]["bvecs"], float); b = np.asarray(man["protocol"]["bvals_s_mm2"], float)
|
| 60 |
+
first = g[b > 50][0] / np.linalg.norm(g[b > 50][0])
|
| 61 |
+
assert np.allclose(prot.directions[prot.n_b0:][0], a.R.T @ first) or np.isclose(np.abs(prot.directions[prot.n_b0:] @ (a.R.T @ first)).max(), 1.0)
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def compose_reference(brain, meas, ph, *, scanner, n=200):
|
| 65 |
+
"""``(got, ref)`` on ``n`` voxels drawn with seed 0, in M0 units: the page's contraction (:meth:`Brain.prepare`,
|
| 66 |
+
:meth:`Brain.replay`) and dmipy-sim's ``Phantom.compose(...).replay(seq, scanner=scanner, pose=...)`` of the
|
| 67 |
+
same packs as loaded, tissue, fractions and FODs, NaN where a voxel carries no signal."""
|
| 68 |
+
from dmipy_sim.phantom import FreeWater, Grid, Inert, ODF, PackSubstrate, Phantom
|
| 69 |
+
dwi, floor, factor, _ = brain.replay(meas, ph, brain.prepare(meas, ph))
|
| 70 |
+
assert floor.max() == 0 and np.nanmax(dwi) <= 1 + 1e-5
|
| 71 |
+
pick = np.sort(np.random.default_rng(0).choice(len(brain.vox), n, replace=False))
|
| 72 |
+
ijk = brain.vox[pick]
|
| 73 |
+
fr = brain.asset.fractions[tuple(ijk.T)].astype(np.float64); fod = brain.asset.fod[tuple(ijk.T)].astype(np.float64)
|
| 74 |
+
wm_pack, gm_pack = brain.pack("wm", ph.wm_pack, 1), brain.pack("gm", ph.gm_pack, 1)
|
| 75 |
+
t_wm, t_gm, t_csf = ph.tissues(wm_pack, gm_pack)
|
| 76 |
+
wm = PackSubstrate(wm_pack, m0=ph.m0["wm"], name="wm", tissue=t_wm)
|
| 77 |
+
gm = PackSubstrate(gm_pack, m0=ph.m0["gm"], name="gm", tissue=t_gm)
|
| 78 |
+
csf = FreeWater(m0=ph.m0["csf"], tissue=t_csf)
|
| 79 |
+
iso = np.zeros((n, 45)); iso[:, 0] = B.C00
|
| 80 |
+
grid = Grid(shape=(n, 1, 1), voxel_size_m=(2.5e-3,) * 3)
|
| 81 |
+
phantom = Phantom.compose(grid, fractions={wm: fr[:, 0].reshape(n, 1, 1), gm: fr[:, 1].reshape(n, 1, 1), csf: fr[:, 2].reshape(n, 1, 1)},
|
| 82 |
+
remainder=Inert(), orientation={wm: ODF(fod.reshape(n, 1, 1, 45), basis="tournier07"),
|
| 83 |
+
gm: ODF(iso.reshape(n, 1, 1, 45), basis="tournier07")})
|
| 84 |
+
pose = B.specimen_pose(brain.asset.R, ph.b0_direction)
|
| 85 |
+
ref = phantom.replay(brain.sequence(meas, np.arange(len(meas.bvals)), pose), scanner=scanner, pose=pose)[:, 0, 0, :]
|
| 86 |
+
got = (dwi * factor[..., None])[tuple(ijk.T)]
|
| 87 |
+
assert (np.isfinite(got[:, 0]) == np.isfinite(ref[:, 0])).all()
|
| 88 |
+
return got, ref
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
@has_fixture
|
| 92 |
+
@has_packs
|
| 93 |
+
def test_the_replay_is_dmipy_sims_phantom_composition(brain):
|
| 94 |
+
"""At the scan's protocol, 3 T with every tier on (relaxation, contact, the sheath's field along the bore), noise
|
| 95 |
+
off: the Space's float32 contraction over 200 voxels equals ``Phantom.compose(...).replay(seq, pose=...)`` of the
|
| 96 |
+
same packs, tissue, fractions and FODs to 1e-5 in M0 units, the field given as ``scanner=ph.scanner_field``."""
|
| 97 |
+
cfg = brain.cfg
|
| 98 |
+
ph = B.Brain.physics_from(cfg, default_values(cfg))
|
| 99 |
+
assert ph.relaxation and ph.contact and ph.field and ph.field_T == 3.0
|
| 100 |
+
meas = brain.validate(B.Brain.protocol(cfg, B.Brain.presets(cfg)[0]), ph)
|
| 101 |
+
got, ref = compose_reference(brain, meas, ph, scanner=ph.scanner_field)
|
| 102 |
+
live = np.isfinite(ref[:, 0])
|
| 103 |
+
assert live.sum() > 150
|
| 104 |
+
assert np.max(np.abs(got[live] - ref[live])) < 1e-5
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
@pytest.mark.skipif(not os.environ.get("DISCO_HUB_TESTS"), reason="reads the Hub: set DISCO_HUB_TESTS=1")
|
| 108 |
+
@has_fixture
|
| 109 |
+
def test_a_windowed_multi_seed_pack_replays_as_dmipy_sims_phantom_composition():
|
| 110 |
+
"""The page's default packs (brain.toml's first menu entries: the WM walk of 1 s in 125 ms windows from several
|
| 111 |
+
seeded walks, the GM walk of 250 ms in 125 ms windows), read from the Hub by window, every tier on at 3 T: a
|
| 112 |
+
class within window 0 loads ``windows=range(1)`` and the page's contraction over 200 voxels equals
|
| 113 |
+
``Phantom.compose(...).replay`` of the same packs to float precision (1e-6 in M0 units; measured 7e-8). The
|
| 114 |
+
sheath's field is the composition's ``scanner=ph.scanner_field``; the same composition without it
|
| 115 |
+
(``scanner=None``, the ideal machine's key ``ph.scanner``) is refused by dmipy-sim, since the tissue's
|
| 116 |
+
susceptibility needs a field to act in (disco-space#36)."""
|
| 117 |
+
cfg = P.config(os.path.join(P.HERE, "brain.toml"))
|
| 118 |
+
cfg["asset"] = {"local": FIXTURE}
|
| 119 |
+
brain = B.Brain(cfg)
|
| 120 |
+
ph = B.Brain.physics_from(cfg, default_values(cfg))
|
| 121 |
+
assert ph.relaxation and ph.contact and ph.field and ph.field_T == 3.0 and ph.scanner is None
|
| 122 |
+
meas = brain.validate(P.Protocol((P.Shell(B.SCAN, 1000, 6), P.Shell(B.SCAN, 2500, 6)), n_b0=1), ph)
|
| 123 |
+
got, ref = compose_reference(brain, meas, ph, scanner=ph.scanner_field)
|
| 124 |
+
wm = brain.pack("wm", ph.wm_pack, 1)
|
| 125 |
+
walks = wm.segments["walks"]
|
| 126 |
+
assert wm.windows_present == 1 and wm.n_segments > 1 and len(walks) == 1 and len(walks[0]["seed"]) > 1
|
| 127 |
+
live = np.isfinite(ref[:, 0])
|
| 128 |
+
assert live.sum() > 150
|
| 129 |
+
assert np.max(np.abs(got[live] - ref[live])) < 1e-6
|
| 130 |
+
with pytest.raises(ValueError, match="no scanner field"):
|
| 131 |
+
compose_reference(brain, meas, ph, scanner=ph.scanner)
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
@has_fixture
|
| 135 |
+
@has_packs
|
| 136 |
+
def test_prepare_is_kept_per_tissue_and_field_and_the_m0_is_the_devices(brain):
|
| 137 |
+
"""The pose responses are kept per (packs, protocol, tissue, field): the cache has them for other proton densities
|
| 138 |
+
(zero seconds), not for another tissue, and the replay follows the new M0 linearly per tissue."""
|
| 139 |
+
cfg = brain.cfg
|
| 140 |
+
v = default_values(cfg)
|
| 141 |
+
ph = B.Brain.physics_from(cfg, v)
|
| 142 |
+
meas = brain.validate(P.preset_protocol(cfg, "clinical b1000 x 30"), ph)
|
| 143 |
+
k1 = brain.prepare(meas, ph)
|
| 144 |
+
k2 = brain.cached(meas, B.Brain.physics_from(cfg, {**v, "m0_gm": 0.5}))
|
| 145 |
+
assert k2.seconds == 0.0 and k2.m0["gm"] == 0.5 and k1.m0["gm"] == v["m0_gm"] and k2.wm is k1.wm
|
| 146 |
+
assert brain.cached(meas, B.Brain.physics_from(cfg, {**v, "rho2": 2 * v["rho2"]})) is None
|
| 147 |
+
only_gm = {**v, "m0_wm": 0.0, "m0_csf": 0.0}
|
| 148 |
+
a = brain.replay(meas, B.Brain.physics_from(cfg, only_gm), brain.cached(meas, B.Brain.physics_from(cfg, only_gm)))
|
| 149 |
+
b = brain.replay(meas, B.Brain.physics_from(cfg, {**only_gm, "m0_gm": 0.5 * v["m0_gm"]}), brain.cached(meas, B.Brain.physics_from(cfg, {**only_gm, "m0_gm": 0.5 * v["m0_gm"]})))
|
| 150 |
+
ok = np.isfinite(a[2])
|
| 151 |
+
np.testing.assert_allclose(b[2][ok], 0.5 * a[2][ok], rtol=1e-5) # the b = 0 signal halves
|
| 152 |
+
np.testing.assert_allclose(b[0][ok], a[0][ok], atol=1e-5) # the normalised signal does not move
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
def _regions():
|
| 156 |
+
labels = np.zeros((6, 2, 2), np.int32); labels[0] = 1; labels[2] = 2; labels[4] = 3; labels[5] = 4
|
| 157 |
+
return P.Regions(labels, np.diag([2.0, 2.0, 2.0, 1.0]), ("a", "b", "c", "d"), (("L x", (1, 2)), ("R x", (3, 4))))
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
def test_the_connectome_of_a_known_tractogram():
|
| 161 |
+
"""Four streamlines with known endpoint regions (mm through the affine): the symmetrised count, no diagonal, a
|
| 162 |
+
streamline ending in no region uncounted, and the group sums (the diagonal the within-group count, once)."""
|
| 163 |
+
from dmipy_tract import Tractogram
|
| 164 |
+
reg = _regions()
|
| 165 |
+
x = lambda i: np.array([2.0 * i, 0.0, 0.0])
|
| 166 |
+
paths = [np.stack([x(0), x(2)]), np.stack([x(2), x(0)]), np.stack([x(0), x(4)]), np.stack([x(4), x(5)]), np.stack([x(1), x(5)])]
|
| 167 |
+
pts = np.concatenate(paths).astype(np.float32); off = np.r_[0, np.cumsum([len(p) for p in paths])]
|
| 168 |
+
tg = Tractogram(pts, off, np.arange(len(paths)), np.zeros((len(paths), 2), np.int8))
|
| 169 |
+
M = reg.matrix(tg)
|
| 170 |
+
expect = np.zeros((4, 4)); expect[0, 1] = expect[1, 0] = 2; expect[0, 2] = expect[2, 0] = 1; expect[2, 3] = expect[3, 2] = 1
|
| 171 |
+
np.testing.assert_array_equal(M, expect)
|
| 172 |
+
G = reg.grouped(M)
|
| 173 |
+
np.testing.assert_array_equal(G, [[2, 1], [1, 1]])
|
| 174 |
+
assert P.connected_pairs(M) == 3 and len(reg.pairs[0]) == 6
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
@has_fixture
|
| 178 |
+
def test_the_score_is_against_the_inputs_connectome(brain):
|
| 179 |
+
"""Pearson of log(1 + count): one for the truth itself, the pairs connected in one only counted, the lobar view;
|
| 180 |
+
B against A the same numbers between two runs."""
|
| 181 |
+
import types
|
| 182 |
+
n = brain.regions.n
|
| 183 |
+
rng = np.random.default_rng(0)
|
| 184 |
+
T = np.triu(rng.poisson(3.0, (n, n)), 1).astype(float); T = T + T.T
|
| 185 |
+
ref = dict(matrix=T, lobar=brain.regions.grouped(T), streamlines=100)
|
| 186 |
+
s = brain.score(T, ref)
|
| 187 |
+
assert s["pearson_log"] == pytest.approx(1.0) and s["only_run"] == 0 == s["only_truth"] and s["lobar_pearson_log"] == pytest.approx(1.0)
|
| 188 |
+
M = T.copy(); M[0, 1] = M[1, 0] = 0; M[2, 3] = M[3, 2] = T[2, 3] + 5
|
| 189 |
+
s2 = brain.score(M, ref)
|
| 190 |
+
assert s2["only_truth"] == int(T[0, 1] > 0) and s2["pearson_log"] < 1
|
| 191 |
+
a = types.SimpleNamespace(matrix=T, score=s); b = types.SimpleNamespace(matrix=M, score=s2)
|
| 192 |
+
c = brain.compare(a, b)
|
| 193 |
+
assert c["only_a"] == int(T[0, 1] > 0) and c["only_b"] == 0 and c["delta_log"] == pytest.approx(s2["pearson_log"] - 1.0)
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
def test_the_reservation_grows_with_the_run_and_the_default_fits_a_logged_out_visitor():
|
| 197 |
+
"""The brain's model from ``[budget]``: more measurements, the ladder, B, a denser seeding and more keys each
|
| 198 |
+
cost more; the default acquisition with A + B + ladder at the default density reserves at most 120 s."""
|
| 199 |
+
cfg = P.config(os.path.join(P.HERE, "brain.toml"))
|
| 200 |
+
small = P.preset_protocol(cfg, "clinical b1000 x 30"); big = P.preset_protocol(cfg, "research 3-shell x 90")
|
| 201 |
+
est = lambda prot, **kw: B.Brain.estimated_seconds(cfg, prot, **{**dict(density=cfg["tracking"]["density"], knob=P.NO_KNOB, n_keys=1, ladder=False), **kw})
|
| 202 |
+
knob = "SNR → 10"
|
| 203 |
+
assert 30 <= est(small) < est(big) < est(big, ladder=True) < est(big, ladder=True, knob=knob) <= 480
|
| 204 |
+
assert est(big, density=1) < est(big, density=2) < est(big, density=4) and est(big) < est(big, n_keys=3)
|
| 205 |
+
scan_like = P.Protocol((P.Shell(B.SCAN, 1000, 96), P.Shell(B.SCAN, 1500, 96), P.Shell(B.SCAN, 2000, 96), P.Shell(B.SCAN, 2500, 96), P.Shell(B.SCAN, 3000, 96)), n_b0=15)
|
| 206 |
+
assert est(scan_like, ladder=True, knob=knob) <= 120 # MASiVar's five shells x 96 at the default density, A + B + ladder
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
@has_fixture
|
| 210 |
+
def test_the_panel_is_a_brain_physics_and_every_knob_changes_one_thing(brain):
|
| 211 |
+
cfg = brain.cfg
|
| 212 |
+
panel = B.Brain.panel(cfg)
|
| 213 |
+
assert set(panel.fields) <= set(panel.controls()) and set(panel.catalogue) <= set(panel.fields)
|
| 214 |
+
v = default_values(cfg)
|
| 215 |
+
ph = B.Brain.physics_from(cfg, v)
|
| 216 |
+
assert ph.m0 == {"wm": 0.7, "gm": 0.85, "csf": 1.0} and ph.T2["wm"]["intra"] == pytest.approx(0.05) and ph.scanner_field == 3.0
|
| 217 |
+
off = B.Brain.physics_from(cfg, {**v, "on": False})
|
| 218 |
+
assert off.bare and off.m0 == ph.m0 and off.scanner_field is None and off.wm_pack == ph.wm_pack
|
| 219 |
+
prot = P.preset_protocol(cfg, "clinical b1000 x 30")
|
| 220 |
+
for label, change in B.Brain.knobs(cfg).items():
|
| 221 |
+
if change is None:
|
| 222 |
+
continue
|
| 223 |
+
pb, on, snr, vb = B.Brain.apply_knob(cfg, change, prot, True, 30.0, v)
|
| 224 |
+
diffs = [k for k in panel.fields if vb[k] != v[k]]
|
| 225 |
+
kind = change[0]
|
| 226 |
+
if kind == "field":
|
| 227 |
+
assert "field_T" in diffs or change[1] == v["field_T"]
|
| 228 |
+
elif kind in ("tier", "bare", "b0", "m0_gm", "pack"):
|
| 229 |
+
assert len(diffs) <= 1, (label, diffs)
|
| 230 |
+
elif kind in ("snr", "shape"):
|
| 231 |
+
assert diffs == []
|
| 232 |
+
steps = brain.ladder_steps(ph)
|
| 233 |
+
assert [l for l, _ in steps] == ["bare diffusion", "+ relaxation", "+ relaxation + contact"] and steps[0][1].bare and steps[0][1].m0 == ph.m0
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
@has_fixture
|
| 237 |
+
@has_packs
|
| 238 |
+
def test_the_refusals_name_what_the_packs_cannot_play(brain):
|
| 239 |
+
"""A class whose echo lies beyond the 100 ms walk (the configuration's classes for a longer walk among them), and
|
| 240 |
+
the multi-tissue reconstruction on a dmipy-fit without it."""
|
| 241 |
+
cfg = brain.cfg
|
| 242 |
+
ph = B.Brain.physics_from(cfg, default_values(cfg))
|
| 243 |
+
brain.pack("wm", ph.wm_pack, 1); brain.pack("gm", ph.gm_pack, 1)
|
| 244 |
+
brain.shapes = {**brain.shapes, "long": dict(label="long", delta=0.03, Delta=0.06, TE=0.12)}
|
| 245 |
+
with pytest.raises(ValueError, match="100 ms walk: it cannot play the class 'long'"):
|
| 246 |
+
brain.validate(P.Protocol((P.Shell("long", 1000, 6),)), ph)
|
| 247 |
+
for name in ("ste-d12-TM150", "long-TE-d30-D120"):
|
| 248 |
+
with pytest.raises(ValueError, match=f"100 ms walk: it cannot play the class '{name}'"):
|
| 249 |
+
brain.validate(P.Protocol((P.Shell(name, 1000, 6),)), ph)
|
| 250 |
+
import inspect
|
| 251 |
+
from dmipy_fit.tissue_response.three_tissue_response import three_tissue_response_dhollander16
|
| 252 |
+
if "mask" not in inspect.signature(three_tissue_response_dhollander16).parameters:
|
| 253 |
+
with pytest.raises(RuntimeError, match="dmipy-fit#39"):
|
| 254 |
+
P.csd_msmt(np.ones((2, 1, 1, 7)), P.measurements(P.Protocol((P.Shell("d12-D24", 1000, 6),)), cfg["shapes"]), np.ones((2, 1, 1), bool), backend="torch")
|
| 255 |
+
|
| 256 |
+
|
| 257 |
+
def mini_asset(tmp_path, size=(18, 18, 10)):
|
| 258 |
+
"""A crop of the fixture around the brain's centre, in the asset's layout (every region name kept)."""
|
| 259 |
+
d = tmp_path / "asset"; d.mkdir()
|
| 260 |
+
man = json.load(open(os.path.join(FIXTURE, "manifest.json")))
|
| 261 |
+
mask = np.load(os.path.join(FIXTURE, "mask.npy"))
|
| 262 |
+
c = np.argwhere(mask).mean(0).astype(int)
|
| 263 |
+
sl = tuple(slice(int(ci - s // 2), int(ci - s // 2 + s)) for ci, s in zip(c, size))
|
| 264 |
+
for f in ("fod_wm.npy", "fractions.npy", "mask.npy", "labels.npy", "stop_mask.npy", "mean_b0.npy"):
|
| 265 |
+
np.save(d / f, np.load(os.path.join(FIXTURE, f))[sl])
|
| 266 |
+
A = np.asarray(man["grid"]["affine"]); A[:3, 3] = A[:3, :3] @ np.array([s.start for s in sl]) + A[:3, 3]
|
| 267 |
+
man["grid"] = dict(shape=list(size), voxel_size_mm=man["grid"]["voxel_size_mm"], affine=A.tolist())
|
| 268 |
+
json.dump(man, open(d / "manifest.json", "w"))
|
| 269 |
+
import shutil
|
| 270 |
+
shutil.copy(os.path.join(FIXTURE, "regions.json"), d / "regions.json")
|
| 271 |
+
return str(d)
|
| 272 |
+
|
| 273 |
+
|
| 274 |
+
@has_fixture
|
| 275 |
+
@has_packs
|
| 276 |
+
def test_the_brain_page_runs_a_to_b_on_a_small_crop(tmp_path, monkeypatch):
|
| 277 |
+
"""The page's chain on a crop of the fixture (single-tissue reconstruction, the torch backend on the CPU): the cache
|
| 278 |
+
lookup, the device part (the packs' responses, A, B = A with the field off, the ladder), the drawing; every output there, the headline
|
| 279 |
+
against the input's connectome, the round trip and the timings naming the reconstruction path, the files."""
|
| 280 |
+
pytest.importorskip("gradio")
|
| 281 |
+
from space import app as A
|
| 282 |
+
monkeypatch.setenv("DISCO_RECONSTRUCTION", "tournier07")
|
| 283 |
+
asset = mini_asset(tmp_path)
|
| 284 |
+
monkeypatch.setenv("DISCO_CONFIG", "brain.toml"); monkeypatch.setenv("DISCO_BRAIN_ASSET", asset) # what estimated_seconds reads
|
| 285 |
+
cfg = brain_cfg(asset)
|
| 286 |
+
src = B.Brain(cfg)
|
| 287 |
+
state = dict(error=None, source=src, cfg=cfg, load_seconds=0.1, regions=__import__("space.viewers", fromlist=["x"]).region_markers(src.regions), gt_views=None)
|
| 288 |
+
monkeypatch.setattr(A, "_load", lambda: state)
|
| 289 |
+
panel = B.Brain.panel(cfg)
|
| 290 |
+
physics = [default_values(cfg)[k] for k in panel.fields]
|
| 291 |
+
shells = [True, "d12-D24", 1000, 12, 10.0, 20.0, 60.0] + [False, "d12-D24", 2000, 12, 10.0, 20.0, 60.0] * 3
|
| 292 |
+
args = ["research 3-shell x 90", 1, True, 30, 1, 45.0, 1.25, 0, None, "field tier → off", A.IDEAL, 2, True, *physics, *shells]
|
| 293 |
+
out = list(A.run_pipeline(A.compute, *args))
|
| 294 |
+
final = out[-1]
|
| 295 |
+
assert len(final) == len(A.OUTPUTS)
|
| 296 |
+
named = dict(zip(A.OUTPUTS, final))
|
| 297 |
+
assert "connectome vs the input's" in named["headline"] and "A vs B" in named["headline"] and "tracker keys" in named["headline"]
|
| 298 |
+
rows = dict((r[0], r[1]) for r in named["timings"])
|
| 299 |
+
assert any("tournier07" in k for k in rows) and any(k.startswith("A · truth") for k in rows) and float(rows[A.RESPONSES_ROW]) > 0
|
| 300 |
+
assert any(r[0] == "reconstruction" and "tournier07" in r[1] for r in named["roundtrip"])
|
| 301 |
+
for key in ("dwi_view", "mats", "lobar_view", "truth_view", "fractions_view", "response_view", "ingredient_pool", "explore_view"):
|
| 302 |
+
assert named[key] is not None, key
|
| 303 |
+
assert any(p.endswith("_connectome.csv") for p in named["volumes"]) and all(os.path.exists(p) for p in named["tck"])
|
| 304 |
+
labels = named["layer_choice"]["choices"]
|
| 305 |
+
assert [l if isinstance(l, str) else l[0] for l in labels][:3] == ["bare diffusion", "+ relaxation", "+ relaxation + contact"]
|
| 306 |
+
assert A.estimated_seconds(*args) >= 30
|
| 307 |
+
fig, img = src.truth_views() # the input tab
|
| 308 |
+
assert len(fig.data) == 1 and img.size[0] > 100
|
| 309 |
+
demo = A.build(cfg=cfg) # the page itself builds from the brain's class alone
|
| 310 |
+
assert demo.title == cfg["describe"]["title"]
|
| 311 |
+
|
| 312 |
+
|
| 313 |
+
@has_fixture
|
| 314 |
+
@has_packs
|
| 315 |
+
def test_the_worker_computes_what_the_page_has_not_cached_and_the_page_keeps_it(monkeypatch):
|
| 316 |
+
"""prepare_runs is a lookup: None for every entry the page has not cached (A, B, the ladder's rungs). The worker
|
| 317 |
+
(another process: here another Brain) computes exactly those inside the call, says so in a stage text, and hands
|
| 318 |
+
them over by key; the page keeps them, after which the same run finds every entry cached and equal."""
|
| 319 |
+
pytest.importorskip("gradio")
|
| 320 |
+
from space import app as A
|
| 321 |
+
cfg = brain_cfg()
|
| 322 |
+
page, worker = B.Brain(cfg), B.Brain(cfg)
|
| 323 |
+
monkeypatch.setattr(A, "_load", lambda: dict(error=None, source=page, cfg=cfg))
|
| 324 |
+
v = default_values(cfg)
|
| 325 |
+
physics = [v[k] for k in B.Brain.panel(cfg).fields]
|
| 326 |
+
args = ["clinical b1000 x 30", 1, True, 30, 1, 45.0, 1.25, 0, None, "B0 direction → " + list(B.B0_MODES)[1], A.IDEAL, 1, True, *physics] + [False] * 28
|
| 327 |
+
prepared = A.prepare_runs(*args)
|
| 328 |
+
assert set(prepared["runs"]) == {"A", "B"} and all(k is None for k in [*prepared["runs"].values(), *prepared["ladder"]]) and len(prepared["ladder"]) == 3
|
| 329 |
+
runs = A.plan_runs(cfg, page, *args[:4], args[8], args[9], args[10], v, [False] * 28)
|
| 330 |
+
gen = A._fill(worker, runs, True, prepared)
|
| 331 |
+
texts = []
|
| 332 |
+
try:
|
| 333 |
+
while True:
|
| 334 |
+
texts.append(next(gen))
|
| 335 |
+
except StopIteration as stop:
|
| 336 |
+
filled, computed, seconds = stop.value
|
| 337 |
+
assert len(texts) == 1 and "computing the packs' responses on the worker" in texts[0][0] and seconds > 0
|
| 338 |
+
assert len(computed) == 5 and all(k is not None for k in [*filled["runs"].values(), *filled["ladder"]])
|
| 339 |
+
assert page.cached(P.measurements(runs[0][1], page.shapes), runs[0][4]) is None # the worker's work is not the page's yet
|
| 340 |
+
page.keep(computed)
|
| 341 |
+
again = A.prepare_runs(*args)
|
| 342 |
+
for got, want in zip([*again["runs"].values(), *again["ladder"]], [*filled["runs"].values(), *filled["ladder"]]):
|
| 343 |
+
assert got.seconds == 0.0 and np.array_equal(got.wm, want.wm) and np.array_equal(got.csf, want.csf)
|
| 344 |
+
gen = A._fill(worker, runs, True, again) # nothing missing: no stage text, nothing computed
|
| 345 |
+
try:
|
| 346 |
+
next(gen); raise AssertionError("a stage text with nothing to compute")
|
| 347 |
+
except StopIteration as stop:
|
| 348 |
+
assert stop.value[1] == {} and stop.value[2] < 0.01
|
| 349 |
+
|
| 350 |
+
|
| 351 |
+
@has_fixture
|
| 352 |
+
@has_packs
|
| 353 |
+
def test_the_reservation_prices_the_responses_the_page_has_not_cached(monkeypatch):
|
| 354 |
+
"""Nothing cached: A is a band to compile (cold), the ladder's rungs compile nothing (no field tier). With A's
|
| 355 |
+
entries cached on the page, B's knob decides the extra: a new field is a band to compile (cold), a new field
|
| 356 |
+
direction at A's band is warm, the field tier off is the ladder's top rung, cached; the reservation rises by the priced
|
| 357 |
+
entry and falls back once the page keeps B's responses (as after a run). Another band compiled by an earlier
|
| 358 |
+
entry of the same run is warm."""
|
| 359 |
+
from space import app as A
|
| 360 |
+
cfg = brain_cfg()
|
| 361 |
+
page = B.Brain(cfg)
|
| 362 |
+
monkeypatch.setitem(A._state, "source", page); monkeypatch.setitem(A._state, "cfg", cfg)
|
| 363 |
+
monkeypatch.setattr(A, "_load", lambda: dict(error=None, source=page, cfg=cfg))
|
| 364 |
+
monkeypatch.setattr(A.P, "config", lambda path=None: cfg)
|
| 365 |
+
v = default_values(cfg)
|
| 366 |
+
physics = [v[k] for k in B.Brain.panel(cfg).fields]
|
| 367 |
+
args = lambda knob, ladder=True: ["clinical b1000 x 30", 1, True, 30, 1, 45.0, 1.25, 0, None, knob, A.IDEAL, 1, ladder, *physics] + [False] * 28
|
| 368 |
+
seven = "field → 7 T (catalogue tissue at that field)"
|
| 369 |
+
cold = A.uncached_responses(*args(P.NO_KNOB))
|
| 370 |
+
saves = B.Brain.saves_spanned(B.declared_segments(WM_PACK), 1) # the WM pack's first window
|
| 371 |
+
assert cold == [("cold", 31, saves), ("no_field", 31, saves), ("no_field", 31, saves), ("no_field", 31, saves)]
|
| 372 |
+
prot = P.preset_protocol(cfg, "clinical b1000 x 30")
|
| 373 |
+
for (_, meas, ph) in A.response_entries(page, A.plan_runs(cfg, page, *args(P.NO_KNOB)[:4], None, P.NO_KNOB, A.IDEAL, v, [False] * 28), True):
|
| 374 |
+
page.prepare(meas, ph)
|
| 375 |
+
assert A.uncached_responses(*args(P.NO_KNOB)) == []
|
| 376 |
+
assert A.uncached_responses(*args(seven)) == [("cold", 31, saves)]
|
| 377 |
+
assert A.uncached_responses(*args("B0 direction → " + list(B.B0_MODES)[1])) == [("warm", 31, saves)]
|
| 378 |
+
assert A.uncached_responses(*args("field tier → off")) == [] # A's top rung of the ladder
|
| 379 |
+
b = cfg["budget"]
|
| 380 |
+
base = B.Brain.estimated_seconds(cfg, prot, density=1, knob=seven, n_keys=1, ladder=True)
|
| 381 |
+
before = A.estimated_seconds(*args(seven))
|
| 382 |
+
cold_price = b["response_cold"]["fixed"] + 31 * b["response_cold"]["per_meas"] + saves * b["response_cold"]["per_save"]
|
| 383 |
+
assert abs((before - base) - b["margin"] * cold_price) <= 1
|
| 384 |
+
runs = A.plan_runs(cfg, page, *args(seven)[:4], None, seven, A.IDEAL, v, [False] * 28)
|
| 385 |
+
meas_b, ph_b = A.response_entries(page, runs, False)[1][1:]
|
| 386 |
+
worker = B.Brain(cfg)
|
| 387 |
+
page.keep({page.response_key(meas_b, ph_b): worker.prepare(meas_b, ph_b)})
|
| 388 |
+
assert A.uncached_responses(*args(seven)) == [] and A.estimated_seconds(*args(seven)) == base < before
|
| 389 |
+
seven_both = dict(v, field_T=7.0) # A at 7 T (cold), B its other direction: warm after A
|
| 390 |
+
physics7 = [seven_both[k] for k in B.Brain.panel(cfg).fields]
|
| 391 |
+
a7 = ["clinical b1000 x 30", 1, True, 30, 1, 45.0, 1.25, 0, None, "B0 direction → " + list(B.B0_MODES)[1], A.IDEAL, 1, False, *physics7] + [False] * 28
|
| 392 |
+
assert A.uncached_responses(*a7) == [("cold", 31, saves), ("warm", 31, saves)]
|
| 393 |
+
|
| 394 |
+
|
| 395 |
+
@has_fixture
|
| 396 |
+
def test_the_asset_as_the_masivar_build_writes_it_loads(tmp_path):
|
| 397 |
+
"""The MASiVar build's spellings (tools/build_brain_asset.py, build_parcellation.py): the basis named
|
| 398 |
+
``dmipy-fit ...``, the pulse timing null (the sidecars carry none), regions.json with ``lobes`` names instead of
|
| 399 |
+
groups, fractions of an unconstrained fit summing above one, a WM fraction where the FOD is zero: it loads, the
|
| 400 |
+
scan's class takes the configuration's timing and says so, and the two corrections are counted."""
|
| 401 |
+
d = mini_asset(tmp_path)
|
| 402 |
+
man = json.load(open(os.path.join(d, "manifest.json")))
|
| 403 |
+
man["fod"]["basis"] = "dmipy-fit tournier07 (dipy real_sh_tournier real-SH ordering)"
|
| 404 |
+
man["protocol"].update(TE_s=None, delta_s=None, Delta_s=None)
|
| 405 |
+
json.dump(man, open(os.path.join(d, "manifest.json"), "w"))
|
| 406 |
+
regions = json.load(open(os.path.join(d, "regions.json")))["regions"]
|
| 407 |
+
json.dump(dict(convention="fixture", regions=regions, lobes=[f"{r['lobe']}-{r['hemisphere']}" for r in regions]), open(os.path.join(d, "regions.json"), "w"))
|
| 408 |
+
fr = np.load(os.path.join(d, "fractions.npy")).astype(np.float32); fod = np.load(os.path.join(d, "fod_wm.npy")); mask = np.load(os.path.join(d, "mask.npy"))
|
| 409 |
+
i, j, k = np.argwhere(mask & (fr[..., 0] > 0.3))[0]
|
| 410 |
+
fr[i, j, k] = [0.8, 0.3, 0.1]
|
| 411 |
+
i2, j2, k2 = np.argwhere(mask & (fr[..., 0] > 0.3))[1]
|
| 412 |
+
fod[i2, j2, k2] = 0.0
|
| 413 |
+
np.save(os.path.join(d, "fractions.npy"), fr.astype(np.float16)); np.save(os.path.join(d, "fod_wm.npy"), fod)
|
| 414 |
+
B.manifest.cache_clear()
|
| 415 |
+
src = B.Brain(brain_cfg(d))
|
| 416 |
+
assert "configuration's timing" in src.shapes[B.SCAN]["label"] and src.shapes[B.SCAN]["TE"] == src.cfg["scan"]["TE"]
|
| 417 |
+
notes = dict(src.asset.notes)
|
| 418 |
+
assert any("sum above one" in n for n in notes) and any("no FOD" in n for n in notes)
|
| 419 |
+
assert (src.asset.fractions.sum(-1) <= 1 + 1e-6).all() and len(src.regions.groups) == 14
|
| 420 |
+
wrong = dict(man, fod=dict(man["fod"], basis="descoteaux07"))
|
| 421 |
+
json.dump(wrong, open(os.path.join(d, "manifest.json"), "w")); B.manifest.cache_clear()
|
| 422 |
+
with pytest.raises(ValueError, match="required basis"):
|
| 423 |
+
B.Brain(brain_cfg(d))
|
| 424 |
+
B.manifest.cache_clear()
|
| 425 |
+
|
| 426 |
+
|
| 427 |
+
# ---- the pack's windows (RPK.md 4.3): a run holds the windows its acquisition reaches ----
|
| 428 |
+
|
| 429 |
+
@pytest.fixture(scope="module")
|
| 430 |
+
def two_windows(tmp_path_factory):
|
| 431 |
+
"""A cylinder walk of 200 ms stored in two 100 ms windows (300 walkers, every tier, built with the bank) and
|
| 432 |
+
the same pack truncated to its first window (no re-encode), both on disk: ``(two, one)`` paths."""
|
| 433 |
+
import dmipy_sim as d
|
| 434 |
+
from dmipy_sim.replay import read_rpk
|
| 435 |
+
from dmipy_sim.replay.bank import build_replay_pack
|
| 436 |
+
out = tmp_path_factory.mktemp("windows")
|
| 437 |
+
walk = d.simulate_trajectories(300, 2e-9, d.Cylinder(radius=3e-6, orientation=(0.0, 0.0, 1.0)), 0.2, 2e-4, seed=0, require_gpu=False)
|
| 438 |
+
two = str(out / "two.rpk"); one = str(out / "one.rpk")
|
| 439 |
+
build_replay_pack(walk, id="test/two-windows", license="x", citation="x", K=48, out_path=two, segment_T=0.1)
|
| 440 |
+
read_rpk(two).truncate(1, out_path=one)
|
| 441 |
+
return two, one
|
| 442 |
+
|
| 443 |
+
|
| 444 |
+
@pytest.fixture(scope="module")
|
| 445 |
+
def windowed(two_windows):
|
| 446 |
+
"""A brain whose packs are the two-window fixture (``two``) and its first window (``one``), for WM and GM."""
|
| 447 |
+
if not os.path.exists(os.path.join(FIXTURE, "manifest.json")):
|
| 448 |
+
pytest.skip("the BATMAN brain fixture is not on this machine")
|
| 449 |
+
two, one = two_windows
|
| 450 |
+
cfg = brain_cfg()
|
| 451 |
+
menu = [{"label": "two", "uri": two}, {"label": "one", "uri": one}]
|
| 452 |
+
cfg["packs"] = {"wm": list(menu), "gm": list(menu)}
|
| 453 |
+
return B.Brain(cfg)
|
| 454 |
+
|
| 455 |
+
|
| 456 |
+
def _class(name, n=6, b=1000):
|
| 457 |
+
return P.Protocol((P.Shell(name, b, n),), n_b0=1)
|
| 458 |
+
|
| 459 |
+
|
| 460 |
+
@has_fixture
|
| 461 |
+
def test_the_windows_a_class_reaches(windowed):
|
| 462 |
+
"""On a pack of two 100 ms windows: the 60 / 70 ms classes and the 100 ms class reach window 0 alone (the save at
|
| 463 |
+
100 ms ends window 0, window 1 starts there), the 160 ms PGSE and the 184 ms stimulated echo reach both; the table
|
| 464 |
+
reads the same from the pack's header and from the loaded pack's meta; the first window alone is one window
|
| 465 |
+
whatever the class."""
|
| 466 |
+
two = windowed.segments("wm", "two")
|
| 467 |
+
assert two == dict(n=2, n_t=501, T=pytest.approx(0.1))
|
| 468 |
+
for name, k in (("d12-D24", 1), ("ste-d12-TM36", 1), ("d25-D55", 1), ("long-TE-d30-D120", 2), ("ste-d12-TM150", 2)):
|
| 469 |
+
meas = P.measurements(_class(name), windowed.shapes)
|
| 470 |
+
assert windowed.windows_reached(two, meas) == {name: k}, name
|
| 471 |
+
assert windowed.windows_needed("wm", "two", meas) == k
|
| 472 |
+
assert windowed.windows_needed("wm", "one", meas) == 1
|
| 473 |
+
both = P.measurements(P.Protocol((P.Shell("d12-D24", 1000, 6), P.Shell("long-TE-d30-D120", 2000, 6)), n_b0=1), windowed.shapes)
|
| 474 |
+
assert windowed.windows_reached(two, both) == {"d12-D24": 1, "long-TE-d30-D120": 2}
|
| 475 |
+
pk = windowed.pack("wm", "two", 1)
|
| 476 |
+
assert windowed.windows_reached(pk.meta, both) == windowed.windows_reached(two, both)
|
| 477 |
+
assert B.Brain.saves_spanned(two, 1) == 501 and B.Brain.saves_spanned(two, 2) == 1001
|
| 478 |
+
|
| 479 |
+
|
| 480 |
+
@has_fixture
|
| 481 |
+
def test_a_class_beyond_the_declared_windows_is_refused_by_name(windowed):
|
| 482 |
+
"""A 250 ms echo on the 200 ms pack of two windows reaches window 2: refused by name before anything loads."""
|
| 483 |
+
cfg = windowed.cfg
|
| 484 |
+
ph = B.Brain.physics_from(cfg, {**default_values(cfg), "wm_pack": "two", "gm_pack": "two"})
|
| 485 |
+
windowed.shapes = {**windowed.shapes, "beyond": dict(label="beyond", delta=0.03, Delta=0.12, TE=0.25)}
|
| 486 |
+
with pytest.raises(ValueError, match=r"'two' declares 2 window\(s\) of 100 ms: the class 'beyond' \(TE 250 ms\) reaches window 2"):
|
| 487 |
+
windowed.validate(_class("beyond"), ph)
|
| 488 |
+
meas = windowed.validate(_class("long-TE-d30-D120"), ph)
|
| 489 |
+
assert len(meas.bvals) == 7
|
| 490 |
+
|
| 491 |
+
|
| 492 |
+
@has_fixture
|
| 493 |
+
def test_a_hub_pack_loads_the_windows_reached_and_reloads_for_more(windowed, two_windows, monkeypatch):
|
| 494 |
+
"""A Hub pack declaring two windows: the first request loads ``windows=range(1)``, a request within what is held
|
| 495 |
+
loads nothing, a request for two reloads with ``range(2)`` and replaces the cached pack; a local path loads whole.
|
| 496 |
+
(The library's window-ranged read is stood in for by the fixture stamped with the windows asked for;
|
| 497 |
+
``test_the_hub_fixture_loads_by_window`` reads the Hub.)"""
|
| 498 |
+
import dmipy_sim.phantom as phantom
|
| 499 |
+
from dmipy_sim.replay import read_rpk
|
| 500 |
+
two, _ = two_windows
|
| 501 |
+
uri = "hf://SubstrateCommons/test/packs/two.rpk"
|
| 502 |
+
calls = []
|
| 503 |
+
|
| 504 |
+
class Windowed:
|
| 505 |
+
def __init__(self, pack, *, m0, name=None, windows=None):
|
| 506 |
+
calls.append((pack, None if windows is None else list(windows)))
|
| 507 |
+
self.pack = read_rpk(two)
|
| 508 |
+
if windows is not None:
|
| 509 |
+
self.pack.meta["windows_present"] = len(windows)
|
| 510 |
+
|
| 511 |
+
real = B.declared_segments
|
| 512 |
+
monkeypatch.setattr(B, "declared_segments", lambda u: real(two) if u == uri else real(u))
|
| 513 |
+
monkeypatch.setattr(phantom, "PackSubstrate", Windowed)
|
| 514 |
+
src = B.Brain.__new__(B.Brain)
|
| 515 |
+
src.cfg = {**windowed.cfg, "packs": {"wm": [{"label": "hub", "uri": uri}, {"label": "local", "uri": two}], "gm": []}}
|
| 516 |
+
src.packs = {}
|
| 517 |
+
seg = src.segments("wm", "hub")
|
| 518 |
+
a = src.pack("wm", "hub", 1)
|
| 519 |
+
assert calls == [(uri, [0])] and src.windows_held(a, seg) == 1
|
| 520 |
+
assert src.pack("wm", "hub", 1) is a and len(calls) == 1
|
| 521 |
+
b = src.pack("wm", "hub", 2)
|
| 522 |
+
assert calls[-1] == (uri, [0, 1]) and src.packs[("wm", "hub")] is b and src.windows_held(b, seg) == 2
|
| 523 |
+
assert src.pack("wm", "hub", 1) is b and len(calls) == 2
|
| 524 |
+
whole = src.pack("wm", "local", 1)
|
| 525 |
+
assert calls[-1] == (two, None) and src.windows_held(whole, seg) == 2
|
| 526 |
+
|
| 527 |
+
|
| 528 |
+
@pytest.mark.skipif(not os.environ.get("DISCO_HUB_TESTS"), reason="reads the Hub: set DISCO_HUB_TESTS=1")
|
| 529 |
+
@has_fixture
|
| 530 |
+
def test_a_hub_pack_loads_by_window(windowed, tmp_path, monkeypatch):
|
| 531 |
+
"""brain.toml's default GM pack on the Hub (a walk in two windows, its table from its dataset's record), read by
|
| 532 |
+
byte range into an empty Hub cache (the library keeps a window read there and serves a later, smaller request
|
| 533 |
+
from it): ``windows=range(1)`` for a class within window 0, then ``range(2)`` when a class reaching window 1 asks,
|
| 534 |
+
which replaces the cached pack."""
|
| 535 |
+
import huggingface_hub.constants
|
| 536 |
+
monkeypatch.setattr(huggingface_hub.constants, "HF_HUB_CACHE", str(tmp_path))
|
| 537 |
+
cfg = P.config(os.path.join(P.HERE, "brain.toml"))
|
| 538 |
+
label, uri = next(iter(B.Brain.pack_menu(cfg, "gm").items()))
|
| 539 |
+
src = B.Brain.__new__(B.Brain)
|
| 540 |
+
src.cfg = {**windowed.cfg, "packs": {"wm": [], "gm": [{"label": label, "uri": uri}]}}
|
| 541 |
+
src.packs = {}; src.shapes = windowed.shapes
|
| 542 |
+
seg = src.segments("gm", label)
|
| 543 |
+
assert seg["n"] == 2
|
| 544 |
+
T = float(seg["T"]) # classes whose echo sits in window 0, then in window 1
|
| 545 |
+
src.shapes = {**src.shapes, "w0": dict(label="w0", delta=0.2 * T, Delta=0.5 * T, TE=T), "w1": dict(label="w1", delta=0.3 * T, Delta=0.75 * T, TE=1.5 * T)}
|
| 546 |
+
short, long = P.measurements(_class("w0"), src.shapes), P.measurements(_class("w1"), src.shapes)
|
| 547 |
+
assert src.windows_needed("gm", label, short) == 1
|
| 548 |
+
assert src.windows_needed("gm", label, long) == 2
|
| 549 |
+
one = src.pack("gm", label, 1)
|
| 550 |
+
assert one.windows_present == 1 and one.n_segments == 2
|
| 551 |
+
two = src.pack("gm", label, 2)
|
| 552 |
+
assert two.windows_present == 2 and src.packs[("gm", label)] is two
|
| 553 |
+
|
| 554 |
+
|
| 555 |
+
@has_fixture
|
| 556 |
+
def test_the_reservation_rises_with_the_windows_reached(windowed):
|
| 557 |
+
"""A class within the first window and one reaching the second: the WM pack's saves spanned (501, then 1001);
|
| 558 |
+
the reservation of the responses the page has not cached rises by ``per_save`` x the saves a second window adds."""
|
| 559 |
+
cfg = windowed.cfg
|
| 560 |
+
ph = B.Brain.physics_from(cfg, {**default_values(cfg), "wm_pack": "two", "gm_pack": "two"})
|
| 561 |
+
short = windowed.validate(_class("d17-D30"), ph); long = windowed.validate(_class("long-TE-d30-D120"), ph)
|
| 562 |
+
assert windowed.responses([(short, ph)]) == [("cold", 7, 501)] and windowed.responses([(long, ph)]) == [("cold", 7, 1001)]
|
| 563 |
+
prot = P.preset_protocol(cfg, "research 3-shell x 90") # above the 30 s floor
|
| 564 |
+
swoop = dict(n=10, n_t=1302, T=0.09995) # the 1 s pack's windows: 1,302 and 2,603 saves
|
| 565 |
+
one, both = B.Brain.saves_spanned(swoop, 1), B.Brain.saves_spanned(swoop, 2)
|
| 566 |
+
est = lambda r: B.Brain.estimated_seconds(cfg, prot, density=2, knob=P.NO_KNOB, n_keys=1, ladder=False, responses=r)
|
| 567 |
+
b = cfg["budget"]
|
| 568 |
+
for state in ("cold", "warm", "no_field"):
|
| 569 |
+
per_save = b[f"response_{state}"]["per_save"]
|
| 570 |
+
lo, hi = est([(state, prot.n_meas, one)]), est([(state, prot.n_meas, both)])
|
| 571 |
+
assert per_save > 0 and lo < hi and abs((hi - lo) - b["margin"] * (both - one) * per_save) <= 1, state
|
| 572 |
+
|
| 573 |
+
|
| 574 |
+
@has_fixture
|
| 575 |
+
def test_a_one_window_class_on_two_windows_is_the_first_window_bit_for_bit(windowed):
|
| 576 |
+
"""Every tier on, a class within the first window: the pose responses of the two-window pack equal those of the
|
| 577 |
+
pack truncated to its first window to the bit (the replay reads window 0 alone), the explorer's curves and the
|
| 578 |
+
tiers' b = 0 weights too; the accuracy table says the windows each holds."""
|
| 579 |
+
cfg = windowed.cfg
|
| 580 |
+
v = default_values(cfg)
|
| 581 |
+
ph_two = B.Brain.physics_from(cfg, {**v, "wm_pack": "two", "gm_pack": "two"})
|
| 582 |
+
ph_one = B.Brain.physics_from(cfg, {**v, "wm_pack": "one", "gm_pack": "one"})
|
| 583 |
+
assert ph_two.relaxation and ph_two.contact and ph_two.field
|
| 584 |
+
prot = P.Protocol((P.Shell("d17-D30", 1000, 12), P.Shell("d17-D30", 2500, 12)), n_b0=2)
|
| 585 |
+
k2 = windowed.prepare(windowed.validate(prot, ph_two), ph_two)
|
| 586 |
+
k1 = windowed.prepare(windowed.validate(prot, ph_one), ph_one)
|
| 587 |
+
for x in ("wm", "gm", "csf"):
|
| 588 |
+
assert np.array_equal(getattr(k2, x), getattr(k1, x)), x
|
| 589 |
+
for x in ("wm", "gm", "csf"):
|
| 590 |
+
assert np.array_equal(k2.profile[x], k1.profile[x]), x
|
| 591 |
+
assert k2.b0 == k1.b0 and windowed.windows_held(windowed.packs[("wm", "two")], windowed.segments("wm", "two")) == 2
|
| 592 |
+
rows = dict(windowed.accuracy())
|
| 593 |
+
assert "windows held / declared 2 / 2 of 100 ms (1,001 of 1,001 saves at 200 µs)" in rows["WM pack two"]
|
| 594 |
+
assert "windows held / declared 1 / 1 of 100 ms (501 of 501 saves" in rows["WM pack one"]
|
| 595 |
+
|
| 596 |
+
|
| 597 |
+
@has_fixture
|
| 598 |
+
@has_packs
|
| 599 |
+
def test_the_warm_up_runs_in_its_own_process_and_the_page_keeps_what_arrives(monkeypatch):
|
| 600 |
+
"""``Brain.warm_in_background`` loads the packs here, spawns the worker on ``warm_entries`` and keeps every
|
| 601 |
+
``(key, Kernels)`` the worker sends; the page then finds the entries cached and equal to its own ``prepare``.
|
| 602 |
+
Two entries stand for the set."""
|
| 603 |
+
cfg = brain_cfg()
|
| 604 |
+
full = B.Brain(cfg, asset=FIXTURE)
|
| 605 |
+
two = full.warm_entries()[:2]
|
| 606 |
+
assert len(two) == 2
|
| 607 |
+
monkeypatch.setattr(B.Brain, "warm_entries", lambda self: two)
|
| 608 |
+
page = B.Brain(cfg, asset=FIXTURE)
|
| 609 |
+
assert all(page.cached(m, ph) is None for m, ph in two)
|
| 610 |
+
drain = page.warm_in_background()
|
| 611 |
+
assert ("wm", two[0][1].wm_pack) in page.packs and ("gm", two[0][1].gm_pack) in page.packs # loaded here, before the worker
|
| 612 |
+
drain.join(timeout=600)
|
| 613 |
+
assert not drain.is_alive(), "the warm-up did not finish in time"
|
| 614 |
+
for m, ph in two:
|
| 615 |
+
got = page.cached(m, ph)
|
| 616 |
+
assert got is not None and np.array_equal(got.wm, full.prepare(m, ph).wm)
|
| 617 |
+
assert P.Source.warm_in_background(P.Source.__new__(P.Source)) is None # the base: warm() itself, nothing to join
|
| 618 |
+
|
| 619 |
+
|
| 620 |
+
@has_fixture
|
| 621 |
+
@has_packs
|
| 622 |
+
def test_the_warm_set_has_one_entry_per_response_and_the_high_fields_last():
|
| 623 |
+
"""``Brain.warm_entries``: no two entries share a response key (the noise, M0, default-pack and default-direction
|
| 624 |
+
knobs repeat the default run's response), the first entry is the scan's protocol at the panel's defaults, and
|
| 625 |
+
the field presets close the set in ascending field, so the minutes 7 T and 11.7 T cost come after everything
|
| 626 |
+
cheaper, the pulse-timing classes among it."""
|
| 627 |
+
cfg = brain_cfg()
|
| 628 |
+
src = B.Brain(cfg, asset=FIXTURE)
|
| 629 |
+
entries = src.warm_entries()
|
| 630 |
+
keys = [src.response_key(m, ph) for m, ph in entries]
|
| 631 |
+
assert len(keys) == len(set(keys))
|
| 632 |
+
assert len(entries) < sum(1 for c in B.Brain.knobs(cfg).values() if c is not None) + 3 * 4
|
| 633 |
+
first_meas, first_ph = entries[0]
|
| 634 |
+
assert set(first_meas.shape.tolist()) == {"scan"} and first_ph == B.Brain.physics_from(cfg, default_values(cfg))
|
| 635 |
+
fields = [ph.field_T for m, ph in entries]
|
| 636 |
+
catalogue_fields = sorted(float(f) for f in cfg["physics"]["fields"])
|
| 637 |
+
high = [f for f in fields if f > 3.0]
|
| 638 |
+
assert high == sorted(high) and fields[-2:] == [catalogue_fields[-1]] * 2
|
| 639 |
+
shapes = [i for i, (m, ph) in enumerate(entries) if set(m.shape.tolist()) != {"scan"} and len(m.bvals) == len(entries[0][0].bvals)]
|
| 640 |
+
assert shapes and max(shapes) < min(i for i, f in enumerate(fields) if f > 3.0)
|
| 641 |
+
|
| 642 |
+
|
| 643 |
+
@has_fixture
|
| 644 |
+
@has_packs
|
| 645 |
+
def test_a_machine_plays_every_pulse_at_its_slew_and_field():
|
| 646 |
+
"""``BrainPhysics.scanner`` names a machine of dmipy-sim's catalogue: the pulses are trapezoids with ramps at its
|
| 647 |
+
slew (the same b), its field and direction replace the panel's, the response key tells the machines apart, the label
|
| 648 |
+
names it, a magnet with its own gradient (the Swoop) is refused by name, and a name outside the catalogue too."""
|
| 649 |
+
cfg = brain_cfg()
|
| 650 |
+
src = B.Brain(cfg, asset=FIXTURE)
|
| 651 |
+
values = default_values(cfg)
|
| 652 |
+
ideal = B.Brain.physics_from(cfg, values)
|
| 653 |
+
real = B.Brain.physics_from(cfg, dict(values, field_T=1.5), scanner="siemens_magnetom_terra_7T")
|
| 654 |
+
assert ideal.scanner is None and np.isinf(ideal.slew_rate)
|
| 655 |
+
assert real.scanner == "siemens_magnetom_terra_7T" and real.slew_rate == pytest.approx(200.0) and real.field_T == 7.0
|
| 656 |
+
assert real.b0_direction == (0.0, 0.0, 1.0) and "on the siemens_magnetom_terra_7T" in real.label() and "on the" not in ideal.label()
|
| 657 |
+
with pytest.raises(ValueError, match="not on the brain's scanner menu"):
|
| 658 |
+
B.Brain.physics_from(cfg, values, scanner="hyperfine_swoop_64mT")
|
| 659 |
+
with pytest.raises(Exception):
|
| 660 |
+
B.Brain.physics_from(cfg, values, scanner="a magnet nobody built")
|
| 661 |
+
prot = src.protocol(cfg, src.presets(cfg)[0])
|
| 662 |
+
meas = P.measurements(prot, src.shapes)
|
| 663 |
+
rows = np.flatnonzero(meas.shape == meas.shape[0])
|
| 664 |
+
square = src.sequence(meas, rows, np.eye(3), ideal.slew_rate)
|
| 665 |
+
trap = src.sequence(meas, rows, np.eye(3), real.slew_rate)
|
| 666 |
+
assert np.max(square.encoding.ramp_time) == 0.0 and np.max(trap.encoding.ramp_time) > 0.0
|
| 667 |
+
np.testing.assert_allclose(trap.b(), square.b(), rtol=1e-6) # measured 1.8e-7: the trapezoid sampled on the 1000-sample grid
|
| 668 |
+
assert src.response_key(meas, real) != src.response_key(meas, ideal)
|
| 669 |
+
|
| 670 |
+
|
| 671 |
+
def test_the_swoop_is_off_the_brains_menu_and_the_page_says_why():
|
| 672 |
+
"""brain.toml's ``[scanners] refused`` keeps the Swoop off the menu; the text under the menu, for the ideal scanner
|
| 673 |
+
and for each machine, names it with the reason (the closed form is exact, the classes are the cost), and the
|
| 674 |
+
DiSCo page refuses nothing."""
|
| 675 |
+
from space.sources import disco as D
|
| 676 |
+
cfg = P.config(os.path.join(P.HERE, "brain.toml"))
|
| 677 |
+
refused = B.Brain.refused_machines(cfg)
|
| 678 |
+
assert list(refused) == ["Hyperfine Swoop 64 mT"] and "hyperfine_swoop_64mT" not in P.machines(cfg).values()
|
| 679 |
+
for label in [P.IDEAL] + list(P.machines(cfg)):
|
| 680 |
+
text = P.scanner_text(cfg, label, refused)
|
| 681 |
+
assert "**Not on this menu: Hyperfine Swoop 64 mT.**" in text and "exactly" in text and "encoding classes" in text
|
| 682 |
+
assert D.Disco.refused_machines(P.config()) == {}
|
| 683 |
+
bad = {**cfg, "scanners": {**cfg["scanners"], "refused": [{"label": "Prisma", "key": "siemens_magnetom_prisma_3T"}]}}
|
| 684 |
+
with pytest.raises(ValueError, match="no field law"):
|
| 685 |
+
B.Brain.refused_machines(bad)
|
| 686 |
+
|
| 687 |
+
|
| 688 |
+
def left_handed_asset(tmp_path):
|
| 689 |
+
"""The fixture as a left-handed image: every array's third axis reversed and the affine's third column negated
|
| 690 |
+
with its origin at the old last slice, so every voxel holds the same tissue at the same scanner position."""
|
| 691 |
+
d = tmp_path / "left"; d.mkdir()
|
| 692 |
+
man = json.load(open(os.path.join(FIXTURE, "manifest.json")))
|
| 693 |
+
for f in ("fod_wm.npy", "fractions.npy", "mask.npy", "labels.npy", "stop_mask.npy", "mean_b0.npy"):
|
| 694 |
+
np.save(d / f, np.ascontiguousarray(np.load(os.path.join(FIXTURE, f))[:, :, ::-1]))
|
| 695 |
+
A = np.asarray(man["grid"]["affine"], np.float64)
|
| 696 |
+
n = int(man["grid"]["shape"][2])
|
| 697 |
+
A[:3, 3] = A[:3, 3] + A[:3, 2] * (n - 1); A[:3, 2] = -A[:3, 2]
|
| 698 |
+
man["grid"]["affine"] = A.tolist()
|
| 699 |
+
json.dump(man, open(d / "manifest.json", "w"))
|
| 700 |
+
import shutil
|
| 701 |
+
shutil.copy(os.path.join(FIXTURE, "regions.json"), d / "regions.json")
|
| 702 |
+
return str(d)
|
| 703 |
+
|
| 704 |
+
|
| 705 |
+
@has_fixture
|
| 706 |
+
@pytest.mark.parametrize("handed", ["right", "left"])
|
| 707 |
+
def test_the_head_sits_at_isocentre_at_its_physical_offsets(tmp_path, handed):
|
| 708 |
+
"""The bore grid puts every brain voxel at its affine's place relative to the head centre, for the fixture's
|
| 709 |
+
right-handed affine and its left-handed copy, on the voxels' own indices."""
|
| 710 |
+
asset = FIXTURE if handed == "right" else left_handed_asset(tmp_path)
|
| 711 |
+
src = B.Brain(brain_cfg(asset), asset=asset)
|
| 712 |
+
assert (np.linalg.det(src.affine[:3, :3]) < 0) == (handed == "left")
|
| 713 |
+
grid, idx = src.bore_grid
|
| 714 |
+
np.testing.assert_array_equal(idx, src.vox)
|
| 715 |
+
A = src.affine
|
| 716 |
+
truth = (A[:3, :3] @ src.vox.T).T * 1e-3 + A[:3, 3] * 1e-3
|
| 717 |
+
np.testing.assert_allclose(grid.offset_m(idx) @ np.asarray(grid.to_scanner).T, truth - truth.mean(0), atol=1e-12)
|
| 718 |
+
|
| 719 |
+
|
| 720 |
+
@has_fixture
|
| 721 |
+
def test_a_left_handed_brains_bore_maps_are_the_catalogues_field_at_its_affines_place(tmp_path):
|
| 722 |
+
"""On the fixture's left-handed copy, the bore maps the machines' terms are read from -- the Swoop's field offset,
|
| 723 |
+
its transmit scale and its own gradient, the Prisma's gradient nonlinearity -- at every sampled brain voxel equal
|
| 724 |
+
the catalogue's law at ``affine @ [ijk, 1]`` from the head centre, on both sides of the midline (a mirrored head
|
| 725 |
+
would read the law at the wrong side's places); its left-handed and right-handed copies give every voxel the same values."""
|
| 726 |
+
from dmipy_sim.phantom.bore import b0_offset_map, b1_scale_map, background_gradient_map, gradient_tensor_map
|
| 727 |
+
asset = left_handed_asset(tmp_path)
|
| 728 |
+
left = B.Brain(brain_cfg(asset), asset=asset)
|
| 729 |
+
right = B.Brain(brain_cfg(), asset=FIXTURE)
|
| 730 |
+
assert np.linalg.det(left.affine[:3, :3]) < 0
|
| 731 |
+
grid, idx = left.bore_grid
|
| 732 |
+
A = left.affine
|
| 733 |
+
at = (A[:3, :3] @ idx.T).T * 1e-3 + A[:3, 3] * 1e-3
|
| 734 |
+
d = at - at.mean(0) # scanner-frame displacement from the head centre
|
| 735 |
+
near = np.linalg.norm(d, axis=1) < 0.07 # inside the Swoop's 8 cm anchor with room
|
| 736 |
+
rng = np.random.default_rng(3)
|
| 737 |
+
sides = [np.flatnonzero(near & (d[:, 0] > 0.02)), np.flatnonzero(near & (d[:, 0] < -0.02))]
|
| 738 |
+
pick = np.concatenate([rng.choice(s, 50, replace=False) for s in sides])
|
| 739 |
+
pos = grid.positions_m(idx[pick])
|
| 740 |
+
swoop, prisma = P.limits("hyperfine_swoop_64mT"), P.limits("siemens_magnetom_prisma_3T")
|
| 741 |
+
b0 = b0_offset_map(swoop, grid)(pos)
|
| 742 |
+
np.testing.assert_allclose(b0, swoop.b0_offset(d[pick]), rtol=1e-12, atol=1e-15)
|
| 743 |
+
np.testing.assert_allclose(b1_scale_map(swoop, grid)(pos), swoop.b1_scale(d[pick]), rtol=1e-12)
|
| 744 |
+
np.testing.assert_allclose(background_gradient_map(swoop, grid)(pos) @ np.asarray(grid.to_scanner).T,
|
| 745 |
+
swoop.b0_gradient(d[pick]), rtol=1e-10, atol=1e-15)
|
| 746 |
+
R = np.asarray(grid.to_scanner)
|
| 747 |
+
L_grid = gradient_tensor_map(prisma, grid)(pos)
|
| 748 |
+
np.testing.assert_allclose(R @ L_grid @ R.T, prisma.gradient_tensor(d[pick]), rtol=1e-10, atol=1e-12)
|
| 749 |
+
g_r, i_r = right.bore_grid
|
| 750 |
+
order = np.lexsort(right.vox.T[::-1]); order_l = np.lexsort((left.vox * [1, 1, -1]).T[::-1])
|
| 751 |
+
inside = near[order_l] # the same voxels, in the same order, on both
|
| 752 |
+
np.testing.assert_allclose(b0_offset_map(swoop, g_r)(g_r.positions_m(i_r[order][inside])),
|
| 753 |
+
b0_offset_map(swoop, grid)(grid.positions_m(idx[order_l][inside])), rtol=1e-10, atol=1e-15)
|
| 754 |
+
|
| 755 |
+
|
| 756 |
+
@has_fixture
|
| 757 |
+
@has_packs
|
| 758 |
+
def test_a_machine_plays_each_voxel_its_encoding_class_and_a_representative_exactly():
|
| 759 |
+
"""On the Prisma, the clinical preset: every voxel is played its encoding class (the delivered b of every member
|
| 760 |
+
within the configured tolerance of its class's), and a class's first member -- the voxel whose exact values the
|
| 761 |
+
class was composed from -- gets exactly what its own delivered acquisition, expanded by the packs and composed with
|
| 762 |
+
its FOD and fractions, gives: the replay to 1e-5 in M0 units; the machine moves the image off the ideal scanner's."""
|
| 763 |
+
from dmipy_sim.phantom import FreeWater
|
| 764 |
+
from dmipy_sim.phantom.bore import encoding_classes
|
| 765 |
+
from dmipy_sim.acquisition.waveforms import rotate_waveform
|
| 766 |
+
cfg = brain_cfg()
|
| 767 |
+
src = B.Brain(cfg, asset=FIXTURE)
|
| 768 |
+
values = default_values(cfg)
|
| 769 |
+
ph = B.Brain.physics_from(cfg, values, scanner="siemens_magnetom_prisma_3T")
|
| 770 |
+
ideal = B.Brain.physics_from(cfg, values)
|
| 771 |
+
prot = B.Brain.protocol(cfg, "clinical b1000 x 30")
|
| 772 |
+
meas = src.validate(prot, ph)
|
| 773 |
+
k = src.prepare(meas, ph)
|
| 774 |
+
dwi, _, factor, _ = src.replay(meas, ph, k)
|
| 775 |
+
dwi0, _, factor0, _ = src.replay(meas, ideal, src.prepare(meas, ideal))
|
| 776 |
+
rows = np.flatnonzero(meas.shape == meas.shape[0])
|
| 777 |
+
cls, played = src.encoding(meas, ph, rows)
|
| 778 |
+
assert 1 < len(played) < 50 and k.wm.shape[0] == len(played)
|
| 779 |
+
b_class = np.array([p.b() for p in played]) # (n_classes, n_meas)
|
| 780 |
+
grid, idx = src.bore_grid
|
| 781 |
+
tol = float(cfg["scanners"]["tolerance"])
|
| 782 |
+
rng = np.random.default_rng(1)
|
| 783 |
+
for v in rng.choice(len(idx), 40, replace=False):
|
| 784 |
+
_, own = encoding_classes(P.limits(ph.scanner), grid, src.sequence(meas, rows, np.eye(3), ph.slew_rate), idx[v:v + 1], tolerance=None)
|
| 785 |
+
b = own[0].b(); nz = meas.bvals[rows] > 50
|
| 786 |
+
assert np.max(np.abs(b[nz] / b_class[cls[v]][nz] - 1)) < 2 * tol
|
| 787 |
+
pose = B.specimen_pose(src.asset.R, ph.b0_direction)
|
| 788 |
+
wm_pack, gm_pack = src.pack("wm", ph.wm_pack, 1), src.pack("gm", ph.gm_pack, 1)
|
| 789 |
+
t_wm, t_gm, t_csf = ph.tissues(wm_pack, gm_pack)
|
| 790 |
+
reps = [int(np.flatnonzero(cls == c)[0]) for c in range(len(played))]
|
| 791 |
+
reps = [v for v in reps if np.isfinite(factor[tuple(src.vox[v])])][:4] # a class's first member may hold no signal
|
| 792 |
+
assert reps
|
| 793 |
+
for v in reps:
|
| 794 |
+
_, own = encoding_classes(P.limits(ph.scanner), grid, src.sequence(meas, rows, np.eye(3), ph.slew_rate), idx[v:v + 1], tolerance=None)
|
| 795 |
+
seq = rotate_waveform(own[0], pose)
|
| 796 |
+
Cw = wm_pack.pose_responses([seq], tissue=t_wm, scanner=ph.scanner_field, pose=pose, keep=(B.LMAX, 0))[0].retained(B.LMAX, 0) @ B.axis_map()
|
| 797 |
+
eg = gm_pack.pose_responses([seq], tissue=t_gm, scanner=ph.scanner_field, pose=pose, keep=(0, 0))[0].retained(0, 0)[:, 0] * B.axis_map()[0, 0] * B.C00
|
| 798 |
+
ec = FreeWater(m0=1.0, tissue=t_csf).response(seq)
|
| 799 |
+
f = src.f[v].astype(np.float64); m0 = ph.m0
|
| 800 |
+
ref = np.abs(f[0] * m0["wm"] * (src.fod_unit[v].astype(np.float64) @ Cw.T) + f[1] * m0["gm"] * eg + f[2] * m0["csf"] * ec)
|
| 801 |
+
got = (dwi * factor[..., None])[tuple(src.vox[v])][rows]
|
| 802 |
+
assert np.max(np.abs(got - ref)) < 1e-5, (v, np.max(np.abs(got - ref)))
|
| 803 |
+
moved = np.nanmax(np.abs(dwi * factor[..., None] - dwi0 * factor0[..., None]))
|
| 804 |
+
assert moved > 1e-3
|
| 805 |
+
|
| 806 |
+
|
| 807 |
+
@has_fixture
|
| 808 |
+
@has_packs
|
| 809 |
+
def test_the_warm_set_holds_the_scan_on_every_machine_that_can_play_it():
|
| 810 |
+
"""After the knobs, ``warm_entries`` adds the scan's protocol on each machine of the menu that can play its
|
| 811 |
+
shells, at the machine's field with its slew; a machine that cannot play the scan is left out."""
|
| 812 |
+
cfg = brain_cfg()
|
| 813 |
+
src = B.Brain(cfg, asset=FIXTURE)
|
| 814 |
+
scan = src.protocol(cfg, src.presets(cfg)[0])
|
| 815 |
+
menu = P.machines(cfg).values()
|
| 816 |
+
can = {key for key in menu if all(r[-1] for r in P.playable(scan, src.shapes, key))}
|
| 817 |
+
got = {ph.scanner: ph for m, ph in src.warm_entries() if ph.scanner is not None}
|
| 818 |
+
assert set(got) == can and can
|
| 819 |
+
for key, ph in got.items():
|
| 820 |
+
assert ph.field_T == pytest.approx(P.limits(key).field_T) and ph.slew_rate == pytest.approx(P.limits(key).slew_max)
|
tests/test_build_brain_asset.py
ADDED
|
@@ -0,0 +1,222 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""``build_brain_asset.py``'s pieces, on tiny synthetic data: merging shells, the mean b=0, the manifest payload and
|
| 2 |
+
the checks sample are pure numpy/nibabel and run in every CI; the dmipy-fit MSMT-CSD fit itself needs cvxpy and is
|
| 3 |
+
skipped when it is not installed (the offline build's own venv; not part of the Space's requirements.txt)."""
|
| 4 |
+
import json
|
| 5 |
+
import os
|
| 6 |
+
|
| 7 |
+
import nibabel as nib
|
| 8 |
+
import numpy as np
|
| 9 |
+
import pytest
|
| 10 |
+
|
| 11 |
+
from tools import build_brain_asset as BA
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def _write_shell(tmp_path, stem, shape, bval, n_dirs, affine, seed):
|
| 15 |
+
rng = np.random.default_rng(seed)
|
| 16 |
+
n = n_dirs + 1
|
| 17 |
+
data = rng.random(shape + (n,)).astype(np.float32) + 1.0
|
| 18 |
+
nib.Nifti1Image(data, affine).to_filename(os.path.join(tmp_path, stem + ".nii.gz"))
|
| 19 |
+
bvals = np.r_[np.full(n_dirs, float(bval)), 0.0]
|
| 20 |
+
dirs = rng.normal(size=(n_dirs, 3))
|
| 21 |
+
dirs /= np.linalg.norm(dirs, axis=1, keepdims=True)
|
| 22 |
+
bvecs = np.vstack([dirs, [[0.0, 0.0, 0.0]]])
|
| 23 |
+
np.savetxt(os.path.join(tmp_path, stem + ".bval"), bvals[None, :], fmt="%g")
|
| 24 |
+
np.savetxt(os.path.join(tmp_path, stem + ".bvec"), bvecs.T, fmt="%g")
|
| 25 |
+
return data, bvals, bvecs
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def test_merge_shells_concatenates_and_orders(tmp_path):
|
| 29 |
+
affine = np.diag([2.5, 2.5, 2.5, 1.0])
|
| 30 |
+
shape = (4, 4, 3)
|
| 31 |
+
d1, bv1, vec1 = _write_shell(tmp_path, "a_b1000n4_dwi", shape, 1000, 4, affine, seed=0)
|
| 32 |
+
d2, bv2, vec2 = _write_shell(tmp_path, "b_b2000n6_dwi", shape, 2000, 6, affine, seed=1)
|
| 33 |
+
|
| 34 |
+
data, bvals, bvecs, aff, shells = BA.merge_shells(str(tmp_path))
|
| 35 |
+
|
| 36 |
+
assert data.shape == shape + (5 + 7,)
|
| 37 |
+
assert bvals.shape == (12,)
|
| 38 |
+
assert bvecs.shape == (12, 3)
|
| 39 |
+
np.testing.assert_allclose(aff, affine)
|
| 40 |
+
assert shells == [(1000.0, 4), (2000.0, 6)]
|
| 41 |
+
# every file's own b0 (last column) survives the concatenation
|
| 42 |
+
assert np.sum(bvals < BA.B0_THRESHOLD_S_MM2) == 2
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def test_merge_shells_rejects_a_mismatched_grid(tmp_path):
|
| 46 |
+
affine = np.diag([2.5, 2.5, 2.5, 1.0])
|
| 47 |
+
_write_shell(tmp_path, "a_b1000n2_dwi", (4, 4, 3), 1000, 2, affine, seed=0)
|
| 48 |
+
_write_shell(tmp_path, "b_b2000n2_dwi", (5, 4, 3), 2000, 2, affine, seed=1)
|
| 49 |
+
with pytest.raises(ValueError):
|
| 50 |
+
BA.merge_shells(str(tmp_path))
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def test_mean_b0_averages_only_the_b0_volumes():
|
| 54 |
+
bvals = np.array([0.0, 1000.0, 1000.0, 10.0])
|
| 55 |
+
data = np.zeros((2, 2, 2, 4), dtype=np.float32)
|
| 56 |
+
data[..., 0] = 2.0
|
| 57 |
+
data[..., 3] = 4.0
|
| 58 |
+
data[..., 1] = 999.0
|
| 59 |
+
data[..., 2] = 999.0
|
| 60 |
+
out = BA.mean_b0(data, bvals)
|
| 61 |
+
assert out.shape == (2, 2, 2)
|
| 62 |
+
np.testing.assert_allclose(out, 3.0)
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def test_mean_b0_raises_without_a_b0():
|
| 66 |
+
with pytest.raises(ValueError):
|
| 67 |
+
BA.mean_b0(np.zeros((2, 2, 2, 3)), np.array([1000.0, 1000.0, 1000.0]))
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def test_build_manifest_schema():
|
| 71 |
+
m = BA.build_manifest(
|
| 72 |
+
subject="s", scan="sc", source_doi="10.x/y", grid_shape=(2, 3, 4), voxel_size_mm=(2.5, 2.5, 2.5),
|
| 73 |
+
affine=np.eye(4), bvals=np.array([0.0, 1000.0]), bvecs=np.zeros((2, 3)), te_s=None, delta_s=None,
|
| 74 |
+
delta_cap_s=None, dmipy_fit_commit="abc123", disco_space_commit="def456", solver="csd_cvxpy", n_regions=84)
|
| 75 |
+
json.dumps(m) # every field must be JSON-serialisable
|
| 76 |
+
assert m["source"]["dataset"] == "OpenNeuro ds003416"
|
| 77 |
+
assert m["source"]["paper_doi"] == "10.1002/mrm.28926"
|
| 78 |
+
assert m["source"]["license"] == "CC0"
|
| 79 |
+
assert m["grid"]["shape"] == [2, 3, 4]
|
| 80 |
+
assert m["fod"]["lmax"] == BA.SH_ORDER
|
| 81 |
+
assert m["fractions"] == ["wm", "gm", "csf"]
|
| 82 |
+
assert m["reconstruction"]["tool"] == "dmipy-fit"
|
| 83 |
+
assert m["reconstruction"]["commit"] == "abc123"
|
| 84 |
+
assert "eroded 3 passes" in m["reconstruction"]["responses"] and "tournier13" in m["reconstruction"]["responses"]
|
| 85 |
+
assert m["parcellation"]["n_regions"] == 84
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def test_save_checks_sample_is_reproducible(tmp_path):
|
| 89 |
+
rng = np.random.default_rng(0)
|
| 90 |
+
data = rng.random((5, 5, 5, 7)).astype(np.float32)
|
| 91 |
+
sh = rng.random((5, 5, 5, 45)).astype(np.float32)
|
| 92 |
+
fractions = rng.random((5, 5, 5, 3)).astype(np.float32)
|
| 93 |
+
mask = np.zeros((5, 5, 5), dtype=bool)
|
| 94 |
+
mask[1:4, 1:4, 1:4] = True
|
| 95 |
+
bvals = np.linspace(0, 3000, 7)
|
| 96 |
+
|
| 97 |
+
BA.save_checks_sample(str(tmp_path), data, bvals, sh, fractions, mask, n_sample=10, seed=0)
|
| 98 |
+
out = np.load(os.path.join(tmp_path, "checks", "msmt_sample.npz"))
|
| 99 |
+
assert out["voxel_index"].shape == (10, 3)
|
| 100 |
+
assert out["signal"].shape == (10, 7)
|
| 101 |
+
assert out["sh_coeff"].shape == (10, 45)
|
| 102 |
+
assert out["fractions"].shape == (10, 3)
|
| 103 |
+
for idx, sig in zip(out["voxel_index"], out["signal"]):
|
| 104 |
+
assert mask[tuple(idx)]
|
| 105 |
+
np.testing.assert_allclose(sig, data[tuple(idx)])
|
| 106 |
+
|
| 107 |
+
BA.save_checks_sample(str(tmp_path), data, bvals, sh, fractions, mask, n_sample=10, seed=0)
|
| 108 |
+
out2 = np.load(os.path.join(tmp_path, "checks", "msmt_sample.npz"))
|
| 109 |
+
np.testing.assert_array_equal(out["voxel_index"], out2["voxel_index"])
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def test_fraction_sanity():
|
| 113 |
+
fractions = np.zeros((2, 2, 1, 3), dtype=np.float32)
|
| 114 |
+
fractions[0, 0, 0] = [0.7, 0.2, 0.1] # sum 1.0, WM > 0.5
|
| 115 |
+
fractions[0, 1, 0] = [0.3, 0.3, 0.3] # sum 0.9, WM not > 0.5
|
| 116 |
+
fractions[1, 0, 0] = [0.9, 0.05, 0.05] # sum 1.0, WM > 0.5
|
| 117 |
+
mask = np.zeros((2, 2, 1), dtype=bool)
|
| 118 |
+
mask[0, 0, 0] = mask[0, 1, 0] = mask[1, 0, 0] = True # (1, 1, 0) left out of the mask on purpose
|
| 119 |
+
|
| 120 |
+
out = BA.fraction_sanity(fractions, mask)
|
| 121 |
+
assert out["n_mask"] == 3
|
| 122 |
+
assert out["n_wm_gt_half"] == 2
|
| 123 |
+
assert out["sum_median"] == pytest.approx(1.0)
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def _pure_direction_sh(sh_order, direction):
|
| 127 |
+
"""The real-SH coefficients of a single delta-like lobe along ``direction`` (dipy's own ``sf_to_sh`` on a
|
| 128 |
+
one-hot signal at a fine sphere, so the test does not depend on dmipy-fit's basis machinery)."""
|
| 129 |
+
from dipy.data import get_sphere
|
| 130 |
+
from dipy.reconst.shm import sf_to_sh
|
| 131 |
+
sphere = get_sphere(name="repulsion724")
|
| 132 |
+
cos_angle = sphere.vertices @ np.asarray(direction) / np.linalg.norm(direction)
|
| 133 |
+
sf = np.clip(cos_angle, 0, None) ** 16 # a sharp lobe peaked at `direction`
|
| 134 |
+
return sf_to_sh(sf, sphere, sh_order_max=sh_order, basis_type="tournier07")
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
def test_fod_peak_counts_single_vs_crossing():
|
| 138 |
+
sh_order = 8
|
| 139 |
+
single = _pure_direction_sh(sh_order, (0, 0, 1))
|
| 140 |
+
crossing = _pure_direction_sh(sh_order, (1, 0, 0)) + _pure_direction_sh(sh_order, (0, 1, 0))
|
| 141 |
+
sh = np.stack([single, crossing]).reshape(1, 2, 1, -1).astype(np.float32)
|
| 142 |
+
wm_mask = np.ones((1, 2, 1), dtype=bool)
|
| 143 |
+
|
| 144 |
+
counts = BA.fod_peak_counts(sh, wm_mask, sh_order=sh_order)
|
| 145 |
+
assert sum(counts.values()) == 2
|
| 146 |
+
assert counts.get(1, 0) >= 1 # the single lobe
|
| 147 |
+
assert counts.get(2, 0) >= 1 # the two well-separated lobes
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
def test_save_mean_b0_fod_png_writes_a_file(tmp_path):
|
| 151 |
+
shape = (4, 4, 2)
|
| 152 |
+
mean_b0_volume = np.random.default_rng(0).random(shape).astype(np.float32)
|
| 153 |
+
sh = np.zeros(shape + (45,), dtype=np.float32)
|
| 154 |
+
sh[..., 0] = 1.0 # an isotropic (but non-zero) FOD everywhere: a valid, if uninteresting, principal direction
|
| 155 |
+
wm_mask = np.ones(shape, dtype=bool)
|
| 156 |
+
out_path = os.path.join(tmp_path, "slice.png")
|
| 157 |
+
|
| 158 |
+
BA.save_mean_b0_fod_png(out_path, mean_b0_volume, sh, wm_mask, z=0)
|
| 159 |
+
assert os.path.exists(out_path) and os.path.getsize(out_path) > 0
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
def _single_tensor_attenuation(bvals_s_mm2, bvecs, eigenvalues_mm2_s, axis):
|
| 163 |
+
"""A closed-form single-tensor signal attenuation ``exp(-b g^T D g)``, no dmipy-sim/jax needed: ``D`` has its
|
| 164 |
+
principal eigenvector along ``axis`` (unit vector) with ``eigenvalues_mm2_s = (lambda_par, lambda_perp)``."""
|
| 165 |
+
axis = np.asarray(axis, dtype=np.float64)
|
| 166 |
+
axis = axis / np.linalg.norm(axis)
|
| 167 |
+
lambda_par, lambda_perp = eigenvalues_mm2_s
|
| 168 |
+
d_par_perp = lambda_par - lambda_perp
|
| 169 |
+
cos2 = (bvecs @ axis) ** 2
|
| 170 |
+
return np.exp(-bvals_s_mm2 * (lambda_perp + d_par_perp * cos2))
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
def test_fit_msmt_csd_end_to_end_on_a_tiny_synthetic_volume():
|
| 174 |
+
"""A smoke test of the dmipy-fit call itself (skipped if cvxpy is not installed): a few voxels of a synthetic
|
| 175 |
+
single-tensor-plus-isotropic signal (plain numpy, no dmipy-sim), checking only shapes and that the fractions
|
| 176 |
+
come out non-negative."""
|
| 177 |
+
pytest.importorskip("cvxpy")
|
| 178 |
+
|
| 179 |
+
rng = np.random.default_rng(0)
|
| 180 |
+
n_dirs = 30
|
| 181 |
+
dirs = rng.normal(size=(n_dirs, 3))
|
| 182 |
+
dirs /= np.linalg.norm(dirs, axis=1, keepdims=True)
|
| 183 |
+
bvals_shell = np.repeat([1000.0, 2000.0], n_dirs)
|
| 184 |
+
bvecs_shell = np.tile(dirs, (2, 1))
|
| 185 |
+
bvals = np.r_[0.0, 0.0, bvals_shell]
|
| 186 |
+
bvecs = np.vstack([[0, 0, 0], [0, 0, 0], bvecs_shell])
|
| 187 |
+
|
| 188 |
+
# dhollander16 classifies every voxel by FA and a signal-decay metric, then takes small percentiles (2 %, 10 %)
|
| 189 |
+
# of the GM-like / CSF-like populations as its candidates: a few discrete classes risk one of those percentiles
|
| 190 |
+
# rounding to an empty set (a NaN response, poisoning the CSD kernel), so the volume instead has a continuum of
|
| 191 |
+
# randomly oriented, randomly scaled tensors spanning WM-like (high FA) through GM-like to CSF-like (isotropic,
|
| 192 |
+
# high diffusivity) -- much closer to what real brain data actually looks like to this heuristic.
|
| 193 |
+
# every side 6 voxels longer than the 3-pass erosion of the response selection removes from it
|
| 194 |
+
shape = (16, 16, 12)
|
| 195 |
+
n_voxels = int(np.prod(shape))
|
| 196 |
+
fa_like = rng.uniform(0.0, 1.0, size=n_voxels) # 0 = isotropic, 1 = maximally anisotropic
|
| 197 |
+
mean_d = np.where(fa_like < 0.5, rng.uniform(0.7e-3, 1.0e-3, n_voxels), # GM/WM-ish mean diffusivity
|
| 198 |
+
rng.uniform(1.0e-3, 1.4e-3, n_voxels))
|
| 199 |
+
is_csf = rng.uniform(0, 1, n_voxels) < 0.15
|
| 200 |
+
mean_d = np.where(is_csf, rng.uniform(2.8e-3, 3.2e-3, n_voxels), mean_d)
|
| 201 |
+
fa_like = np.where(is_csf, 0.0, fa_like)
|
| 202 |
+
lambda_perp = mean_d * (1.0 - 0.6 * fa_like)
|
| 203 |
+
lambda_par = mean_d * (1.0 + 1.2 * fa_like)
|
| 204 |
+
axes = rng.normal(size=(n_voxels, 3))
|
| 205 |
+
|
| 206 |
+
mask = np.ones(shape, dtype=bool)
|
| 207 |
+
data = np.empty((n_voxels, len(bvals)), dtype=np.float64)
|
| 208 |
+
for i in range(n_voxels):
|
| 209 |
+
data[i] = _single_tensor_attenuation(bvals, bvecs, (lambda_par[i], lambda_perp[i]), axis=axes[i])
|
| 210 |
+
data *= 1.0 + 0.01 * rng.standard_normal(data.shape)
|
| 211 |
+
data = data.reshape(shape + (len(bvals),))
|
| 212 |
+
|
| 213 |
+
voxel_positions = np.zeros(shape, dtype=bool)
|
| 214 |
+
voxel_positions[0, 0, 0] = voxel_positions[1, 0, 0] = voxel_positions[2, 0, 0] = voxel_positions[3, 0, 0] = True
|
| 215 |
+
|
| 216 |
+
sh, fractions, responses, out_scheme = BA.fit_msmt_csd(
|
| 217 |
+
data, bvals, bvecs, mask, sh_order=4, voxel_positions=voxel_positions)
|
| 218 |
+
assert sh.shape == shape + (15,) # lmax = 4 -> 15 real-SH coefficients
|
| 219 |
+
assert fractions.shape == shape + (3,)
|
| 220 |
+
assert responses["n_voxels_fit"] == voxel_positions.sum() == 4
|
| 221 |
+
assert np.all(fractions[voxel_positions] >= -1e-4) # non-negative to the QP solver's feasibility tolerance
|
| 222 |
+
assert np.all(fractions[~voxel_positions] == 0) # only the requested voxels were fit
|
tests/test_build_parcellation.py
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""The parcellation's pure-numpy pieces: the node table (84 nodes, 14 lobar groups), the majority vote and the
|
| 2 |
+
derived labels / stop mask. No SynthSeg, no TensorFlow, no download -- everything here is synthetic and fast."""
|
| 3 |
+
import numpy as np
|
| 4 |
+
import pytest
|
| 5 |
+
|
| 6 |
+
from tools import build_parcellation as BP
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def test_node_table_has_84_nodes_and_14_lobar_groups():
|
| 10 |
+
nodes = BP.node_table()
|
| 11 |
+
assert len(nodes) == 84
|
| 12 |
+
assert len(set(n["id"] for n in nodes)) == 84
|
| 13 |
+
assert set(n["id"] for n in nodes) == set(range(1, 85))
|
| 14 |
+
left = [n for n in nodes if n["hemisphere"] == "left"]
|
| 15 |
+
right = [n for n in nodes if n["hemisphere"] == "right"]
|
| 16 |
+
assert len(left) == 42 and len(right) == 42
|
| 17 |
+
cortical = [n for n in nodes if n["lobe"] != "subcortical"]
|
| 18 |
+
subcortical = [n for n in nodes if n["lobe"] == "subcortical"]
|
| 19 |
+
assert len(cortical) == 68 and len(subcortical) == 16
|
| 20 |
+
regions = BP.regions_payload()
|
| 21 |
+
groups = regions["lobes"]
|
| 22 |
+
assert len(groups) == 14 and len(set(groups)) == 14
|
| 23 |
+
for lobe in BP.LOBES:
|
| 24 |
+
assert f"{lobe}-left" in groups and f"{lobe}-right" in groups
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def test_node_table_ids_are_unique_per_fs_label_and_hemisphere():
|
| 28 |
+
nodes = BP.node_table()
|
| 29 |
+
keys = [(n["fs_label"], n["hemisphere"]) for n in nodes]
|
| 30 |
+
assert len(set(keys)) == len(keys)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def test_supersampled_affine_centres_subvoxels_within_the_parent_voxel():
|
| 34 |
+
ref_affine = np.array([[2.5, 0, 0, 10.0], [0, 2.5, 0, -5.0], [0, 0, 2.5, 3.0], [0, 0, 0, 1]])
|
| 35 |
+
for factor in (1, 2, 4, 5):
|
| 36 |
+
sup = BP._supersampled_affine(ref_affine, factor)
|
| 37 |
+
# the mean of the factor**3 sub-voxel centres of parent voxel (2, 1, 0) must equal that parent's own centre
|
| 38 |
+
idx = np.arange(factor)
|
| 39 |
+
grid = np.stack(np.meshgrid(idx, idx, idx, indexing="ij"), axis=-1).reshape(-1, 3)
|
| 40 |
+
sub_index = np.array([2, 1, 0]) * factor + grid
|
| 41 |
+
world = sub_index @ sup[:3, :3].T + sup[:3, 3]
|
| 42 |
+
parent_world = ref_affine[:3, :3] @ [2, 1, 0] + ref_affine[:3, 3]
|
| 43 |
+
np.testing.assert_allclose(world.mean(axis=0), parent_world, atol=1e-9)
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def test_majority_vote_picks_the_plurality_label_under_identity_registration():
|
| 47 |
+
# a tiny "T1" label volume at 1 mm, two blocks of 3x3x3 mostly-9 voxels with a 2-voxel minority, at the origin;
|
| 48 |
+
# the "diffusion" grid is 3x coarser (3 mm) and exactly covers one combined super-voxel.
|
| 49 |
+
seg = np.full((3, 3, 3), 9, dtype=np.int32)
|
| 50 |
+
seg[0, 0, 0] = 5
|
| 51 |
+
seg[0, 0, 1] = 5
|
| 52 |
+
seg_affine = np.eye(4)
|
| 53 |
+
ref_affine = np.diag([3.0, 3.0, 3.0, 1.0])
|
| 54 |
+
ref_affine[:3, 3] = 1.0 # the single ref voxel's centre sits at the seg block's centre
|
| 55 |
+
majority = BP.majority_vote(seg, seg_affine, (1, 1, 1), ref_affine, np.eye(4), factor=3)
|
| 56 |
+
assert majority.shape == (1, 1, 1)
|
| 57 |
+
assert majority[0, 0, 0] == 9 # 25 votes for 9 against 2 for 5
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def test_labels_and_stop_mask_from_majority_labels():
|
| 61 |
+
majority = np.array([[[0, 2, 1001]]]) # background, left cerebral WM, left bankssts
|
| 62 |
+
labels, stop = BP.labels_and_stop_mask(majority)
|
| 63 |
+
assert labels[0, 0, 0] == 0
|
| 64 |
+
assert labels[0, 0, 2] == 1 # bankssts is fs id 1001, the first (lowest) left-hemisphere node
|
| 65 |
+
assert stop.tolist() == [[[False, True, False]]]
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def test_label_volumes_mm3():
|
| 69 |
+
labels = np.array([0, 0, 1, 1, 1, 2], dtype=np.int16)
|
| 70 |
+
vols = BP.label_volumes_mm3(labels, voxel_volume_mm3=8.0)
|
| 71 |
+
assert vols == {1: 24.0, 2: 8.0}
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def test_every_cortical_name_has_a_lobe():
|
| 75 |
+
assert set(BP.LOBE_OF_CORTICAL) == set(BP.CORTICAL_NAMES.values())
|
| 76 |
+
assert set(BP.LOBE_OF_CORTICAL.values()) <= set(BP.LOBES)
|
tests/test_limits.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""space.limits: the cgroup CPU quota and the thread cap derived from it."""
|
| 2 |
+
import os
|
| 3 |
+
|
| 4 |
+
import pytest
|
| 5 |
+
|
| 6 |
+
from space import limits as L
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def test_the_quota_is_the_ceiling_of_quota_over_period():
|
| 10 |
+
assert L.cpu_quota_from("100000 100000") == 1
|
| 11 |
+
assert L.cpu_quota_from("150000 100000") == 2
|
| 12 |
+
assert L.cpu_quota_from("800000 100000\n") == 8
|
| 13 |
+
assert L.cpu_quota_from("50000 100000") == 1
|
| 14 |
+
assert L.cpu_quota_from("max 100000") is None
|
| 15 |
+
with pytest.raises(ValueError):
|
| 16 |
+
L.cpu_quota_from("")
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def test_the_cap_sets_only_the_unset_variables(monkeypatch):
|
| 20 |
+
for var in L.THREAD_VARS:
|
| 21 |
+
monkeypatch.delenv(var, raising=False)
|
| 22 |
+
monkeypatch.setenv("MKL_NUM_THREADS", "3")
|
| 23 |
+
assert L.cap_threads(quota=6) == 6
|
| 24 |
+
assert os.environ["OMP_NUM_THREADS"] == "6" and os.environ["OPENBLAS_NUM_THREADS"] == "6"
|
| 25 |
+
assert os.environ["MKL_NUM_THREADS"] == "3"
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def test_the_affinity_cap_keeps_the_first_cpus_of_the_allowed_set():
|
| 29 |
+
before = os.sched_getaffinity(0)
|
| 30 |
+
try:
|
| 31 |
+
assert L.cap_affinity(quota=len(before)) is None # no more than the quota: untouched
|
| 32 |
+
assert os.sched_getaffinity(0) == before
|
| 33 |
+
if len(before) > 1:
|
| 34 |
+
got = L.cap_affinity(quota=1)
|
| 35 |
+
assert got == {min(before)} and os.sched_getaffinity(0) == got
|
| 36 |
+
finally:
|
| 37 |
+
os.sched_setaffinity(0, before)
|
tests/test_no_private_identifiers.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""This repository is public: nothing tracked names a private machine. A benchmark note says what hardware
|
| 2 |
+
CLASS a measurement ran on (a CPU host, a GH200, an L40S -- all fine to name) and never which machine.
|
| 3 |
+
|
| 4 |
+
The forbidden tokens themselves are never written here, in a comment, in a commit message or in test output:
|
| 5 |
+
publishing a byte-exact list of "the names we must not say" defeats the point. Instead this holds salted
|
| 6 |
+
SHA-256 digests of the (lowercased) tokens; a file is flagged by tokenising it on ``[A-Za-z0-9-]+`` and hashing
|
| 7 |
+
each token the same way. A failure reports which FILE matched, never which word."""
|
| 8 |
+
import hashlib
|
| 9 |
+
import os
|
| 10 |
+
import re
|
| 11 |
+
import subprocess
|
| 12 |
+
|
| 13 |
+
SALT = "dmrai-lab/disco-space:no-private-identifiers:v1"
|
| 14 |
+
|
| 15 |
+
#: salted sha256(SALT + token.lower()) of each forbidden token -- never the token itself
|
| 16 |
+
FORBIDDEN_DIGESTS = frozenset((
|
| 17 |
+
"332482b751888461b8dd6f0f6b988fa3524fb79cdf9cbdacb4177c9ed7ffa77d",
|
| 18 |
+
"8acbc150f613da285bda4dfe2c932e5d64d6d5b6f130fdbe8c6d0d6350d642bf",
|
| 19 |
+
"90964afc5e136e5912547b5bb0a9d3c6d235aa4f7e3defbbda5cd8f8fe20a1b2",
|
| 20 |
+
))
|
| 21 |
+
|
| 22 |
+
TOKEN_RE = re.compile(r"[A-Za-z0-9-]+")
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def _digest(token):
|
| 26 |
+
return hashlib.sha256((SALT + token.lower()).encode()).hexdigest()
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def tracked_files():
|
| 30 |
+
root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
| 31 |
+
out = subprocess.run(["git", "-C", root, "ls-files"], capture_output=True, text=True, check=True)
|
| 32 |
+
return [os.path.join(root, p) for p in out.stdout.splitlines() if p]
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def test_no_tracked_file_names_a_private_machine():
|
| 36 |
+
hits = []
|
| 37 |
+
for path in tracked_files():
|
| 38 |
+
if os.path.abspath(path) == os.path.abspath(__file__):
|
| 39 |
+
continue # this file's own digest table
|
| 40 |
+
try:
|
| 41 |
+
with open(path, encoding="utf-8") as f:
|
| 42 |
+
text = f.read()
|
| 43 |
+
except (UnicodeDecodeError, IsADirectoryError):
|
| 44 |
+
continue # a binary asset (data/*.nii.gz, images, ...)
|
| 45 |
+
if any(_digest(tok) in FORBIDDEN_DIGESTS for tok in TOKEN_RE.findall(text)):
|
| 46 |
+
hits.append(path)
|
| 47 |
+
# the message names the FILE only -- never the matched word, which stays undisclosed even on failure
|
| 48 |
+
assert not hits, f"{len(hits)} tracked file(s) name a forbidden private machine: {hits}"
|
tests/test_pipeline.py
ADDED
|
@@ -0,0 +1,380 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""The pipeline's pieces that need no GPU and no layout: protocols and their measurements, DiSCo's own table as
|
| 2 |
+
a protocol, the noise, the score on the ground truth itself, the config's consistency."""
|
| 3 |
+
import numpy as np
|
| 4 |
+
import pytest
|
| 5 |
+
|
| 6 |
+
from space import pipeline as P
|
| 7 |
+
from space.sources import disco as D
|
| 8 |
+
|
| 9 |
+
CFG = P.config()
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def test_the_config_names_every_shell_and_preset_shape():
|
| 13 |
+
shapes = set(CFG["shapes"])
|
| 14 |
+
assert {s["shape"] for s in CFG["disco"]["shells"]} <= shapes
|
| 15 |
+
for name, preset in CFG["presets"].items():
|
| 16 |
+
assert {s["shape"] for s in preset["shells"]} <= shapes, name
|
| 17 |
+
assert P.preset_protocol(CFG, name).name == name
|
| 18 |
+
for s in CFG["shapes"].values():
|
| 19 |
+
assert 0 < s["delta"] < s["Delta"] < s["TE"]
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def test_a_protocols_measurements_are_its_rows_in_order():
|
| 23 |
+
p = P.Protocol((P.Shell("d12-D24", 1000, 30), P.Shell("d8-D20", 6000, 12)), n_b0=2)
|
| 24 |
+
m = P.measurements(p, CFG["shapes"])
|
| 25 |
+
assert p.n_meas == 44 and m.bvals.shape == (44,) and m.dirs.shape == (44, 3)
|
| 26 |
+
assert m.b0.sum() == 2 and list(m.shape[:2]) == ["d12-D24"] * 2 # the b = 0 rows take the first shell's timing
|
| 27 |
+
assert (m.bvals[2:32] == 1000).all() and (m.bvals[32:] == 6000).all()
|
| 28 |
+
np.testing.assert_allclose(np.linalg.norm(m.dirs, axis=1), 1.0, atol=1e-12)
|
| 29 |
+
assert (m.dirs[2:, 2] > 0).all() # a hemisphere: no antipodal pairs
|
| 30 |
+
np.testing.assert_allclose(m.delta[32:], CFG["shapes"]["d8-D20"]["delta"])
|
| 31 |
+
np.testing.assert_allclose(m.Delta[:32], CFG["shapes"]["d12-D24"]["Delta"])
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def test_protocol_refusals():
|
| 35 |
+
with pytest.raises(ValueError, match="at least one shell"):
|
| 36 |
+
P.Protocol(())
|
| 37 |
+
with pytest.raises(ValueError, match="b = 0"):
|
| 38 |
+
P.Protocol((P.Shell("d12-D24", 1000, 30),), n_b0=0)
|
| 39 |
+
with pytest.raises(ValueError, match="b > 0"):
|
| 40 |
+
P.Protocol((P.Shell("d12-D24", 0, 30),))
|
| 41 |
+
with pytest.raises(ValueError, match="directions must be"):
|
| 42 |
+
P.Protocol((P.Shell("d12-D24", 1000, 3),), directions=np.zeros((2, 3)))
|
| 43 |
+
with pytest.raises(KeyError, match="no timing class"):
|
| 44 |
+
P.measurements(P.Protocol((P.Shell("d99-D99", 1000, 3),)), CFG["shapes"])
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def test_discos_table_is_a_protocol_of_its_own_rows():
|
| 48 |
+
"""The dataset's 364 rows: 4 shells on 3 timing classes, every row's direction its own, b = 0 rows first, the
|
| 49 |
+
rows' b-values those of the table."""
|
| 50 |
+
p, idx = D.disco_protocol(CFG)
|
| 51 |
+
m = P.measurements(p, CFG["shapes"])
|
| 52 |
+
bv = np.loadtxt(P.DATA_DIR + "/DiSCo_gradients.bvals").ravel()[idx] # the table's rows in the protocol's order
|
| 53 |
+
assert p.name == "DiSCo 364" and p.n_meas == 364 == len(idx) and sorted(idx) == list(range(364))
|
| 54 |
+
assert [s.b for s in p.shells] == [1000, 1925, 3094, 13192] # the table's shells, rounded means
|
| 55 |
+
assert [s.shape for s in p.shells] == ["d10.2-D16.7", "d10.2-D16.7", "d7.6-D45.9", "d17.7-D35.8"]
|
| 56 |
+
assert m.b0.sum() == p.n_b0 == 4 and m.b0[:p.n_b0].all()
|
| 57 |
+
np.testing.assert_array_equal(m.bvals, bv) # every row's own b-value, exactly
|
| 58 |
+
assert sorted(np.unique(np.round(bv)).tolist()) == [0, 1000, 1925, 3094, 13192]
|
| 59 |
+
np.testing.assert_allclose(np.linalg.norm(m.dirs, axis=1), 1.0, atol=1e-6)
|
| 60 |
+
np.testing.assert_allclose(m.delta[m.shape == "d7.6-D45.9"], 7.6e-3)
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def test_noise_is_rician_at_the_given_snr_and_leaves_nan_alone():
|
| 64 |
+
dwi = np.full((5, 5, 5, 40), 0.5); dwi[0, 0, 0] = np.nan
|
| 65 |
+
out = P.add_noise(dwi, 20.0, seed=1)
|
| 66 |
+
assert np.isnan(out[0, 0, 0]).all() and np.isfinite(out[1:]).all()
|
| 67 |
+
assert abs(out[1:].std() - 0.05) < 0.005 and (out[1:] >= 0).all() # sigma = 1 / SNR, a magnitude
|
| 68 |
+
assert P.add_noise(dwi, None) is dwi
|
| 69 |
+
with pytest.raises(ValueError, match="positive"):
|
| 70 |
+
P.add_noise(dwi, 0.0)
|
| 71 |
+
out_t = P.add_noise(dwi, 20.0, seed=1, backend="torch") # numpy's stream: same distribution, another realisation
|
| 72 |
+
assert np.isnan(out_t[0, 0, 0]).all() and abs(out_t[1:].std() - 0.05) < 0.005 and not np.array_equal(out_t[1:], out[1:])
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def test_the_snr_is_at_m0_and_each_voxels_b0_snr_follows_its_s0_factor():
|
| 76 |
+
"""A voxel whose b = 0 signal is half of M0 gets twice the sigma on its normalised signal (SNR 20 at M0 is SNR 10
|
| 77 |
+
there); the factor map must cover the voxels and be positive; the b = 0 SNR summary reads it back."""
|
| 78 |
+
dwi = np.full((2, 1, 1, 4000), 0.5); factor = np.array([[[1.0]], [[0.5]]])
|
| 79 |
+
out = P.add_noise(dwi, 20.0, factor, seed=3)
|
| 80 |
+
assert abs(out[0].std() - 0.05) < 0.004 and abs(out[1].std() - 0.10) < 0.008
|
| 81 |
+
with pytest.raises(ValueError, match="positive map"):
|
| 82 |
+
P.add_noise(dwi, 20.0, np.array([[[1.0]], [[0.0]]]))
|
| 83 |
+
with pytest.raises(ValueError, match="positive map"):
|
| 84 |
+
P.add_noise(dwi, 20.0, np.ones((3, 1, 1)))
|
| 85 |
+
S = np.ones((2, 1, 1, 3)); S[1] *= 0.4; M0 = np.array([[[1.0]], [[1.0]]])
|
| 86 |
+
norm, f = P.s0_normalised(S, np.array([True, False, False]), M0)
|
| 87 |
+
np.testing.assert_allclose(norm, 1.0); np.testing.assert_allclose(f.ravel(), [1.0, 0.4])
|
| 88 |
+
res = P.Result(None, None, norm, None, f, None, None, None, None, {}, snr=30.0)
|
| 89 |
+
assert P.b0_snr(res) == dict(median=21.0, min=12.0, max=30.0)
|
| 90 |
+
assert P.b0_snr(P.Result(None, None, norm, None, f, None, None, None, None, {})) is None
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
class _Source(D.Disco):
|
| 94 |
+
"""The ground truth and the config without any replay data (D.Disco loads the files, nothing else)."""
|
| 95 |
+
mode = "test"
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def test_the_score_of_the_ground_truth_is_one_and_the_pairs_add_up():
|
| 99 |
+
gt = _Source(CFG)
|
| 100 |
+
s = gt.score(gt.gt_count, gt.reference(None, None)[0])
|
| 101 |
+
assert s["pearson_count"] == pytest.approx(1.0) and s["false_pairs"] == 0 == s["missed_pairs"]
|
| 102 |
+
assert s["connected_pairs"] == s["gt_pairs"] == 25 == P.connected_pairs(gt.gt_count)
|
| 103 |
+
empty = gt.score(np.zeros((16, 16)), gt.reference(None, None)[0])
|
| 104 |
+
assert empty["missed_pairs"] == 25 and empty["connected_pairs"] == 0 and np.isnan(empty["pearson_count"]) # a constant matrix: NaN, no warning
|
| 105 |
+
assert np.isnan(P.pearson([1, 1, 1], [1, 2, 3])) and P.pearson([1, 2, 3], [2, 4, 6]) == pytest.approx(1.0)
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def test_the_volumes_round_trip(tmp_path):
|
| 109 |
+
"""The DWI and FOD written as NIfTI read back with the table beside them."""
|
| 110 |
+
import nibabel as nib
|
| 111 |
+
p = P.Protocol((P.Shell("d12-D24", 1000, 6),), n_b0=1)
|
| 112 |
+
m = P.measurements(p, CFG["shapes"])
|
| 113 |
+
dwi = np.random.default_rng(0).random((4, 4, 4, 7)); dwi[0, 0, 0] = np.nan
|
| 114 |
+
sh = np.random.default_rng(1).random((4, 4, 4, 45))
|
| 115 |
+
res = P.Result(p, m, dwi, np.zeros((4, 4, 4)), np.ones((4, 4, 4)), sh, None, None, None, {}, {})
|
| 116 |
+
paths = P.write_volumes(res, str(tmp_path), prefix="t", affine=np.eye(4))
|
| 117 |
+
back = np.asarray(nib.load(paths["dwi"]).dataobj)
|
| 118 |
+
np.testing.assert_allclose(back, np.nan_to_num(dwi).astype(np.float32))
|
| 119 |
+
np.testing.assert_allclose(np.loadtxt(paths["bvals"]), m.bvals); np.testing.assert_allclose(np.loadtxt(paths["bvecs"]).T, m.dirs, atol=1e-8)
|
| 120 |
+
assert np.asarray(nib.load(paths["fod"]).dataobj).shape == (4, 4, 4, 45)
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def test_the_backend_and_residency_come_from_the_config_or_the_environment(monkeypatch):
|
| 124 |
+
monkeypatch.delenv("DISCO_BACKEND", raising=False); monkeypatch.delenv("DISCO_RESIDENT", raising=False)
|
| 125 |
+
assert P.backend(CFG) == CFG["compute"]["backend"] == "jax" and P.resident(CFG) is True
|
| 126 |
+
monkeypatch.setenv("DISCO_BACKEND", "torch"); monkeypatch.setenv("DISCO_RESIDENT", "0")
|
| 127 |
+
assert P.backend(CFG) == "torch" and P.resident(CFG) is False
|
| 128 |
+
monkeypatch.setenv("DISCO_BACKEND", "numpy")
|
| 129 |
+
with pytest.raises(ValueError, match="backend"):
|
| 130 |
+
P.backend(CFG)
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def test_the_mode_and_the_columns_come_from_the_config_or_the_environment(monkeypatch):
|
| 134 |
+
monkeypatch.delenv("DISCO_MODE", raising=False); monkeypatch.delenv("DISCO_COLUMNS", raising=False)
|
| 135 |
+
assert P.mode(CFG) == "demo" and P.columns_uri(CFG).startswith("hf://")
|
| 136 |
+
monkeypatch.setenv("DISCO_MODE", "full"); monkeypatch.setenv("DISCO_COLUMNS", "/columns")
|
| 137 |
+
assert P.mode(CFG) == "full" and P.columns_uri(CFG) == "/columns"
|
| 138 |
+
monkeypatch.setenv("DISCO_MODE", "fast")
|
| 139 |
+
with pytest.raises(ValueError, match="mode"):
|
| 140 |
+
P.mode(CFG)
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def test_a_free_pulse_timing_is_the_shells_own_in_full_mode():
|
| 144 |
+
p = P.Protocol((P.Shell.free(2000, 12, 0.02, 0.05, 0.09),), n_b0=1)
|
| 145 |
+
assert p.shells[0].shape == "d20-D50-TE90" and p.shells[0].free_timing
|
| 146 |
+
m = P.measurements(p, CFG["shapes"])
|
| 147 |
+
np.testing.assert_allclose(m.delta, 0.02); np.testing.assert_allclose(m.Delta, 0.05); np.testing.assert_allclose(m.TE, 0.09)
|
| 148 |
+
with pytest.raises(ValueError, match="delta < Delta < TE"):
|
| 149 |
+
P.Shell.free(2000, 12, 0.06, 0.05, 0.09)
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def test_a_table_of_rows_becomes_a_protocol_b0_first_then_each_group_in_order():
|
| 153 |
+
"""protocol_from_rows: the one row-grouping used by DiSCo's table and by an uploaded scheme; its refusals."""
|
| 154 |
+
b = np.array([1000, 0, 2000, 1000, 0]); dirs = np.array([[1, 0, 0], [0, 0, 0], [0, 2, 0], [0, 0, 1], [0, 0, 0]], float)
|
| 155 |
+
group = np.array([0, 0, 1, 0, 0])
|
| 156 |
+
p, idx = P.protocol_from_rows(b, dirs, group, lambda g, rows: P.Shell("d12-D24", float(b[rows[0]]), len(rows)), name="t")
|
| 157 |
+
assert list(idx) == [1, 4, 0, 3, 2] and p.n_b0 == 2 and [(s.b, s.n_dirs) for s in p.shells] == [(1000.0, 2), (2000.0, 1)]
|
| 158 |
+
np.testing.assert_allclose(np.linalg.norm(p.directions, axis=1), 1.0)
|
| 159 |
+
np.testing.assert_array_equal(p.directions[:2], [[0, 0, 1], [0, 0, 1]])
|
| 160 |
+
with pytest.raises(ValueError, match="b = 0"):
|
| 161 |
+
P.protocol_from_rows(b[[0, 2]], dirs[[0, 2]], group[[0, 2]], None, name="t")
|
| 162 |
+
with pytest.raises(ValueError, match="zero direction"):
|
| 163 |
+
P.protocol_from_rows(b, np.zeros((5, 3)), group, None, name="t")
|
| 164 |
+
with pytest.raises(ValueError, match="dirs must be"):
|
| 165 |
+
P.protocol_from_rows(b, dirs[:3], group, None, name="t")
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
def test_a_camino_scheme_becomes_a_protocol_with_every_rows_timing(tmp_path):
|
| 169 |
+
"""Two shells with their own delta / Delta at one TE plus a b = 0 row, written as Camino STEJSKALTANNER rows
|
| 170 |
+
(|G| in T/m, times in s): one free shell per distinct timing, the rows' own b-values and directions, b = 0 first."""
|
| 171 |
+
rows = ["VERSION: STEJSKALTANNER"]
|
| 172 |
+
rng = np.random.default_rng(0)
|
| 173 |
+
rows.append("0 0 0 0 0.0300 0.0100 0.0800")
|
| 174 |
+
for delta, Delta, G in ((0.0100, 0.0300, 0.0400), (0.0150, 0.0400, 0.0500)):
|
| 175 |
+
for _ in range(4):
|
| 176 |
+
u = rng.normal(size=3); u /= np.linalg.norm(u)
|
| 177 |
+
rows.append(f"{u[0]:.6f} {u[1]:.6f} {u[2]:.6f} {G:.4f} {Delta:.4f} {delta:.4f} 0.0800")
|
| 178 |
+
path = tmp_path / "t.scheme"; path.write_text("\n".join(rows) + "\n")
|
| 179 |
+
p = P.protocol_from_scheme(str(path))
|
| 180 |
+
assert p.n_meas == 9 and p.n_b0 == 1 and len(p.shells) == 2 and all(s.free_timing for s in p.shells)
|
| 181 |
+
m = P.measurements(p, CFG["shapes"])
|
| 182 |
+
assert m.b0[0] and (m.delta[1:5] == 0.0100).all() and (m.delta[5:] == 0.0150).all() and np.allclose(m.TE, 0.08)
|
| 183 |
+
assert np.allclose(np.linalg.norm(m.dirs, axis=1), 1.0)
|
| 184 |
+
np.testing.assert_allclose(sorted(s.b for s in p.shells), [305, 1409], atol=1) # Stejskal-Tanner b of 40 and 50 mT/m
|
| 185 |
+
assert p.shells[0].shape == "d10-D30-TE80"
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
def test_the_physics_is_the_catalogue_at_the_nearest_field_with_the_tiers_as_switches():
|
| 189 |
+
"""3 T is cited; 0.064 T and 11.7 T take the nearest cited field (1.5 T, 7 T) and say so; a tier off leaves that
|
| 190 |
+
part out of the tissue; all off is bare (no tissue); the refusals."""
|
| 191 |
+
c3 = P.catalogue(3.0); assert c3["catalogue_field"] == 3.0 and set(c3["T2"]) == set(P.CATALOGUE_POOLS) and c3["T2"]["myelin"] < c3["T2"]["intra"]
|
| 192 |
+
two = P.catalogue(3.0, ("intra", "extra")); assert set(two["T2"]) == {"intra", "extra"}
|
| 193 |
+
with pytest.raises(ValueError, match="no relaxation for the pools"):
|
| 194 |
+
P.catalogue(3.0, ("intra", "csf"))
|
| 195 |
+
assert P.catalogue(0.064)["catalogue_field"] == 1.5 and P.catalogue(11.7)["catalogue_field"] == 7.0
|
| 196 |
+
ph = P.Physics.at(3.0)
|
| 197 |
+
assert ph.pools == ("intra", "extra")
|
| 198 |
+
tis = ph.tissue()
|
| 199 |
+
assert tis.T2 == two["T2"] and tis.T1 == two["T1"] and tis.rho2 == c3["rho2"] and tis.chi_iso == c3["chi_iso"] and tis.chi_aniso == c3["chi_aniso"]
|
| 200 |
+
filled = ph.tissue(unseeded=("myelin",)) # the unseeded spec pool takes the first pool's value
|
| 201 |
+
assert set(filled.T2) == {"intra", "extra", "myelin"} and filled.T2["myelin"] == two["T2"]["intra"]
|
| 202 |
+
assert not ph.bare and "relaxation+contact+field" in ph.label()
|
| 203 |
+
no_field = P.Physics.at(7.0, field=False, b0_direction=P.b0_direction(90, 0))
|
| 204 |
+
assert no_field.tissue().chi_iso is None and no_field.tissue().chi_aniso == 0.0 and no_field.tissue().rho2 == c3["rho2"]
|
| 205 |
+
np.testing.assert_allclose(no_field.b0_direction, (1, 0, 0), atol=1e-12)
|
| 206 |
+
bare = P.Physics.at(3.0, relaxation=False, contact=False, field=False)
|
| 207 |
+
assert bare.bare and bare.tissue() is None and bare.label() == "bare diffusion"
|
| 208 |
+
assert P.tissue_and_scanner(bare) == (None, None) and P.tissue_and_scanner(None) == (None, None)
|
| 209 |
+
assert P.tissue_and_scanner(no_field)[1] is None and P.tissue_and_scanner(ph)[1] == 3.0 # the field goes with the field tier
|
| 210 |
+
only_relax = P.Physics.at(3.0, contact=False, field=False, T2={"intra": 0.08, "extra": 0.08})
|
| 211 |
+
assert only_relax.tissue().T2["intra"] == 0.08 and only_relax.tissue().rho2 is None
|
| 212 |
+
with pytest.raises(ValueError, match="tesla"):
|
| 213 |
+
P.Physics.at(3000.0)
|
| 214 |
+
with pytest.raises(ValueError, match="same pools"):
|
| 215 |
+
P.Physics.at(3.0, T2={"intra": 0.05})
|
| 216 |
+
with pytest.raises(ValueError, match="per pool"):
|
| 217 |
+
P.Physics.at(3.0, T2={"intra": -0.05, "extra": 0.05})
|
| 218 |
+
with pytest.raises(ValueError, match="unit vector"):
|
| 219 |
+
P.Physics.at(3.0, b0_direction=(0, 0, 2))
|
| 220 |
+
np.testing.assert_allclose(np.linalg.norm(P.B0_TRANSVERSE), 1.0)
|
| 221 |
+
assert P.Physics.at(3.0).along_z and not no_field.along_z
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
def test_a_tractogram_sample_keeps_whole_streamlines_in_order():
|
| 225 |
+
from dmipy_tract.tractogram import Tractogram
|
| 226 |
+
rng = np.random.default_rng(1)
|
| 227 |
+
counts = rng.integers(2, 6, size=50)
|
| 228 |
+
tg = Tractogram(rng.normal(size=(counts.sum(), 3)), np.concatenate([[0], np.cumsum(counts)]), np.arange(50), np.zeros((50, 2), np.int8))
|
| 229 |
+
s = P.sample_tractogram(tg, 10, seed=0)
|
| 230 |
+
assert len(s) == 10 and np.all(np.diff(s.seed_index) > 0)
|
| 231 |
+
for k, i in enumerate(s.seed_index):
|
| 232 |
+
np.testing.assert_array_equal(s[k], tg[int(i)])
|
| 233 |
+
assert P.sample_tractogram(tg, 100) is tg
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
def test_the_gradient_a_shell_needs_and_the_scanners_that_can_play_it():
|
| 237 |
+
"""b = 1000 at δ 12 / Δ 24 ms needs 70 mT/m (γ² G² δ² (Δ − δ/3)); the Prisma (80 mT/m) plays it, the Swoop (23
|
| 238 |
+
mT/m) does not; DiSCo's b = 13183 shell needs more than either; None means no limit."""
|
| 239 |
+
G = P.gradient_needed(1000, 0.012, 0.024)
|
| 240 |
+
assert 0.069 < G < 0.071
|
| 241 |
+
assert P.limits("siemens_magnetom_prisma_3T").G_max == 0.08 and P.limits("hyperfine_swoop_64mT").G_max < 0.03
|
| 242 |
+
p = P.Protocol((P.Shell("d12-D24", 1000, 30),), n_b0=1)
|
| 243 |
+
assert P.playable(p, CFG["shapes"], "siemens_magnetom_prisma_3T")[0][-1] and not P.playable(p, CFG["shapes"], "hyperfine_swoop_64mT")[0][-1]
|
| 244 |
+
assert P.playable(p, CFG["shapes"], None)[0][5] is None and P.playable(p, CFG["shapes"], None)[0][-1]
|
| 245 |
+
disco, _ = D.disco_protocol(CFG)
|
| 246 |
+
assert all(r[-1] for r in P.playable(disco, CFG["shapes"], None))
|
| 247 |
+
assert not all(r[-1] for r in P.playable(disco, CFG["shapes"], "siemens_magnetom_prisma_3T"))
|
| 248 |
+
free = P.Protocol((P.Shell.free(1000, 30, 0.012, 0.024, 0.06),), n_b0=1)
|
| 249 |
+
assert abs(P.playable(free, CFG["shapes"], None)[0][4] - G) < 1e-12
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
def test_the_pair_spread_over_repeated_runs():
|
| 253 |
+
M1 = np.zeros((16, 16)); M1[0, 1] = M1[1, 0] = 10; M1[2, 3] = M1[3, 2] = 4
|
| 254 |
+
M2 = M1.copy(); M2[0, 1] = M2[1, 0] = 14; M2[2, 3] = M2[3, 2] = 0; M2[4, 5] = M2[5, 4] = 2
|
| 255 |
+
sp = P.pair_spread([M1, M2], [dict(pearson_count=0.8), dict(pearson_count=0.9)], key="pearson_count")
|
| 256 |
+
assert sp["n"] == 2 and abs(sp["pearson_mean"] - 0.85) < 1e-12 and abs(sp["pearson_std"] - np.std([0.8, 0.9], ddof=1)) < 1e-12
|
| 257 |
+
assert sp["pairs_any"] == 3 and sp["pairs_always"] == 1 and sp["mean"][0, 1] == 12 and abs(sp["std"][0, 1] - np.std([10, 14], ddof=1)) < 1e-12
|
| 258 |
+
one = P.pair_spread([M1], [dict(pearson_count=0.8)], key="pearson_count")
|
| 259 |
+
assert one["pearson_std"] == 0.0 and one["std"].max() == 0.0
|
| 260 |
+
|
| 261 |
+
|
| 262 |
+
def test_floor_stats_are_over_the_voxels_with_signal():
|
| 263 |
+
dwi = np.ones((3, 3, 3, 2)); dwi[0, 0, 0] = np.nan
|
| 264 |
+
floor = np.arange(27, dtype=float).reshape(3, 3, 3) / 27
|
| 265 |
+
res = P.Result(None, None, dwi, floor, None, None, None, None, None, {})
|
| 266 |
+
f = P.floor_stats(res)
|
| 267 |
+
assert f["n"] == 26 and f["max"] == floor[2, 2, 2] and f["median"] == np.median(floor.ravel()[1:])
|
| 268 |
+
|
| 269 |
+
|
| 270 |
+
def test_the_layout_at_the_pinned_revision_holds_the_configs_classes_and_tiers():
|
| 271 |
+
"""The manifest the Space will download: every [shapes] class with the config's timing, and the tiers when the
|
| 272 |
+
tissue panel starts on (needs the Hub; skipped offline)."""
|
| 273 |
+
import json
|
| 274 |
+
hf = pytest.importorskip("huggingface_hub")
|
| 275 |
+
d = CFG["data"]
|
| 276 |
+
import requests
|
| 277 |
+
from huggingface_hub.errors import HfHubHTTPError, LocalEntryNotFoundError, OfflineModeIsEnabled
|
| 278 |
+
try:
|
| 279 |
+
path = hf.hf_hub_download(d["repo"], f"{d['moments']}/manifest.json", repo_type="dataset", revision=d["revision"])
|
| 280 |
+
except (requests.ConnectionError, HfHubHTTPError, LocalEntryNotFoundError, OfflineModeIsEnabled) as e: # offline, or the Hub unreachable
|
| 281 |
+
pytest.skip(f"the Hub is not reachable: {e!r}"[:120])
|
| 282 |
+
with open(path) as f:
|
| 283 |
+
m = json.load(f)
|
| 284 |
+
assert m["source"]["manifest_sha256"] == d["source_manifest_sha256"]
|
| 285 |
+
missing = [c for c in CFG["shapes"] if c not in m["columns"]]
|
| 286 |
+
assert not missing, f"the layout at {d['revision'][:12]} lacks {missing}"
|
| 287 |
+
for name, t in CFG["shapes"].items():
|
| 288 |
+
enc = m["shapes"][name].get("encoding") or {}
|
| 289 |
+
for k in ("delta", "Delta", "TE"):
|
| 290 |
+
v = enc.get(k); v = v[0] if isinstance(v, list) else v
|
| 291 |
+
if v is not None:
|
| 292 |
+
assert abs(v - t[k]) < 1e-9, (name, k, v, t[k])
|
| 293 |
+
if CFG["physics"]["default_on"]:
|
| 294 |
+
assert m.get("tiers"), "the tissue panel starts on but the layout has no tiers"
|
| 295 |
+
|
| 296 |
+
|
| 297 |
+
def test_the_tensor_fit_recovers_a_synthetic_tensor_and_refuses_too_few_rows():
|
| 298 |
+
"""A voxel with D = diag(1.7, 0.3, 0.3) um^2/ms at b = 0 and 1000 over 30 directions: MD 0.767, FA 0.799; a voxel
|
| 299 |
+
outside the mask is NaN; fewer than six directions below b_max refuse."""
|
| 300 |
+
p = P.Protocol((P.Shell("d12-D24", 1000, 30), P.Shell("d8-D20", 3000, 12)), n_b0=1)
|
| 301 |
+
m = P.measurements(p, CFG["shapes"])
|
| 302 |
+
D = np.diag([1.7e-3, 0.3e-3, 0.3e-3])
|
| 303 |
+
S = np.exp(-m.bvals * np.einsum("ni,ij,nj->n", m.dirs, D, m.dirs))
|
| 304 |
+
dwi = np.tile(S, (2, 2, 1, 1)); mask = np.ones((2, 2, 1), bool); mask[0, 0, 0] = False
|
| 305 |
+
md, fa = P.dti(dwi, m, mask)
|
| 306 |
+
assert np.isnan(md[0, 0, 0]) and abs(md[1, 1, 0] - 0.7667) < 1e-3 and abs(fa[1, 1, 0] - 0.7990) < 1e-3
|
| 307 |
+
with pytest.raises(ValueError, match="six or more"):
|
| 308 |
+
P.dti(dwi, m, mask, b_max=500)
|
| 309 |
+
|
| 310 |
+
|
| 311 |
+
def test_layer_differences_are_per_shell_between_consecutive_layers():
|
| 312 |
+
p = P.Protocol((P.Shell("d12-D24", 1000, 6), P.Shell("d8-D20", 3000, 6)), n_b0=1)
|
| 313 |
+
m = P.measurements(p, CFG["shapes"])
|
| 314 |
+
a = np.ones((2, 1, 1, 13)); b = a.copy(); b[..., 1:7] += 0.01; b[..., 7:] += 0.05; c = b.copy(); c[..., 7:] -= 0.02
|
| 315 |
+
rows = P.layer_differences([("bare", a), ("+ relaxation", b), ("A", c)], m, np.ones((2, 1, 1), bool))
|
| 316 |
+
assert [(r[0], r[1], r[2]) for r in rows] == [("bare", "+ relaxation", 1000.0), ("bare", "+ relaxation", 3000.0), ("+ relaxation", "A", 1000.0), ("+ relaxation", "A", 3000.0)]
|
| 317 |
+
np.testing.assert_allclose([r[3] for r in rows], [0.01, 0.05, 0.0, 0.02], atol=1e-12)
|
| 318 |
+
|
| 319 |
+
|
| 320 |
+
def test_the_ingredients_are_the_layouts_tier_maps_in_the_pages_units():
|
| 321 |
+
"""The ingredient maps on a stand-in layout: the intra fraction as is, the wall contact as +l in micrometres from
|
| 322 |
+
the stored -l, the survival and the field spread only with their tiers on, the maps asked at the run's tissue,
|
| 323 |
+
field and direction on the layout's backend."""
|
| 324 |
+
calls = []
|
| 325 |
+
class _M:
|
| 326 |
+
manifest = {"tiers": {"D_walk": 6e-10}}
|
| 327 |
+
def tier_maps(self, shape, tissue=None, scanner=None, *, backend, resident, b0_direction):
|
| 328 |
+
calls.append((shape, tissue is not None, scanner, backend, resident, tuple(b0_direction)))
|
| 329 |
+
return dict(pool={"intra": np.full((2, 1, 1), 0.4), "extra": np.full((2, 1, 1), 0.6)}, contact=np.array([[[-2e-5]], [[np.nan]]]),
|
| 330 |
+
contact_weight=np.full((2, 1, 1), 0.9), phase=np.zeros((2, 1, 1)), phase_std=np.full((2, 1, 1), 0.1))
|
| 331 |
+
lay = D.Layout.__new__(D.Layout); lay.moments = _M(); lay.tiers = True; lay.backend = "torch"; lay.unseeded = ("myelin",)
|
| 332 |
+
meas = P.measurements(P.Protocol((P.Shell("d12-D24", 1000, 6),), n_b0=1), P.config()["shapes"])
|
| 333 |
+
ph = P.Physics.at(3.0)
|
| 334 |
+
out = D.Layout.ingredients(lay, meas, ph)
|
| 335 |
+
assert out["D_walk"] == 6e-10 and out["intra_fraction"][0, 0, 0] == 0.4
|
| 336 |
+
np.testing.assert_allclose(out["wall_contact_um"].ravel(), [20.0, np.nan])
|
| 337 |
+
assert out["contact_survival"][0, 0, 0] == 0.9 and out["field_rad"][0, 0, 0] == 0.1
|
| 338 |
+
assert calls[-1] == ("d12-D24", True, 3.0, "torch", True, (0.0, 0.0, 1.0))
|
| 339 |
+
bare = D.Layout.ingredients(lay, meas, None)
|
| 340 |
+
assert bare["contact_survival"] is None and bare["field_rad"] is None and bare["wall_contact_um"][0, 0, 0] == 20.0
|
| 341 |
+
assert calls[-1][1:3] == (False, None)
|
| 342 |
+
lay.tiers = False
|
| 343 |
+
assert D.Layout.ingredients(lay, meas, ph) is None
|
| 344 |
+
|
| 345 |
+
|
| 346 |
+
def test_a_machine_reaches_the_layout_as_a_delivery_at_the_placement():
|
| 347 |
+
"""On a stand-in layout: the ideal scanner asks the image for the commanded acquisition (no delivery); a machine
|
| 348 |
+
asks the layout's delivery for every class at the machine's catalogue entry and the grid centred at the physics'
|
| 349 |
+
offset, and hands it to that class's image; a machine with its own gradient on a layout without background moments,
|
| 350 |
+
and with a transmit law on one without RF schedules, is refused by name."""
|
| 351 |
+
from dmipy_sim.phantom import Grid
|
| 352 |
+
seen = []
|
| 353 |
+
class _M:
|
| 354 |
+
grid = Grid(shape=(2, 1, 1), voxel_size_m=(25e-6,) * 3, origin_m=(0.0, 0.0, 0.0))
|
| 355 |
+
background = None
|
| 356 |
+
manifest = {"shapes": {"d12-D24": {}, "d8-D20": {}}}
|
| 357 |
+
def delivery(self, shape, b, dirs, scanner, grid):
|
| 358 |
+
seen.append(("delivery", shape, scanner.name, tuple(np.round(np.asarray(grid.isocenter_m) - np.asarray(self.grid.isocenter_m), 6))))
|
| 359 |
+
return ("delivered", shape)
|
| 360 |
+
def image(self, shape, b, dirs, *, backend, resident, tissue, scanner, b0_direction, delivered=None):
|
| 361 |
+
seen.append(("image", shape, delivered, scanner, tuple(b0_direction)))
|
| 362 |
+
return np.ones((2, 1, 1, len(b))), np.zeros((2, 1, 1))
|
| 363 |
+
lay = D.Layout.__new__(D.Layout); lay.moments = _M(); lay.tiers = True; lay.backend = "jax"; lay.unseeded = ("myelin",)
|
| 364 |
+
lay.M0 = np.ones((2, 1, 1)); lay.mask = np.ones((2, 1, 1), bool); lay.pools = ("intra", "extra"); lay.shapes = CFG["shapes"]
|
| 365 |
+
meas = P.measurements(P.Protocol((P.Shell("d12-D24", 1000, 3), P.Shell("d8-D20", 2000, 3)), n_b0=1), CFG["shapes"])
|
| 366 |
+
D.Layout.replay(lay, meas, P.Physics.at(3.0))
|
| 367 |
+
assert [s[2] for s in seen if s[0] == "image"] == [None, None]
|
| 368 |
+
seen.clear()
|
| 369 |
+
ph = P.Physics.at(3.0, scanner="siemens_magnetom_prisma_3T", offset_m=(0.0, 0.0, 0.05))
|
| 370 |
+
D.Layout.validate(lay, P.Protocol((P.Shell("d12-D24", 1000, 3),), n_b0=1), ph)
|
| 371 |
+
D.Layout.replay(lay, meas, ph)
|
| 372 |
+
assert [s for s in seen if s[0] == "delivery"] == [("delivery", "d12-D24", "siemens_magnetom_prisma_3T", (0.0, 0.0, -0.05)),
|
| 373 |
+
("delivery", "d8-D20", "siemens_magnetom_prisma_3T", (0.0, 0.0, -0.05))]
|
| 374 |
+
assert [s[2] for s in seen if s[0] == "image"] == [("delivered", "d12-D24"), ("delivered", "d8-D20")]
|
| 375 |
+
swoop = P.Physics.at(0.064, scanner="hyperfine_swoop_64mT", b0_direction=(0.0, 1.0, 0.0))
|
| 376 |
+
with pytest.raises(ValueError, match="background moments"):
|
| 377 |
+
D.Layout.validate(lay, P.Protocol((P.Shell("d12-D24", 100, 3),), n_b0=1), swoop)
|
| 378 |
+
lay.moments.background = {"amplitude": 5e-3}
|
| 379 |
+
with pytest.raises(ValueError, match="RF schedules"):
|
| 380 |
+
D.Layout.validate(lay, P.Protocol((P.Shell("d12-D24", 100, 3),), n_b0=1), swoop)
|
tests/test_viewers.py
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""The page's views on constructed inputs (no GPU, no layout): the FOD peaks of a delta FOD are its direction, the slice
|
| 2 |
+
viewer draws with and without the overlay, the 3-D views hold the sample they say, the timings rows are the stages."""
|
| 3 |
+
import numpy as np
|
| 4 |
+
|
| 5 |
+
from space import pipeline as P
|
| 6 |
+
from space import viewers as V
|
| 7 |
+
|
| 8 |
+
CFG = P.config()
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def test_the_peak_of_a_delta_fod_is_its_direction():
|
| 12 |
+
from dmipy_tract import sh_matrix
|
| 13 |
+
d = np.array([[0.6, 0.0, 0.8], [0.0, 1.0, 0.0]])
|
| 14 |
+
sh = np.zeros((2, 1, 1, 45)); sh[0, 0, 0] = sh_matrix(8, d[:1])[0]; sh[1, 0, 0] = sh_matrix(8, d[1:])[0]
|
| 15 |
+
peaks, amp = P.peaks(sh)
|
| 16 |
+
assert peaks.shape == (2, 1, 1, 3) and (amp > 0).all()
|
| 17 |
+
for k in range(2):
|
| 18 |
+
assert abs(abs(peaks[k, 0, 0] @ d[k]) - 1.0) < 0.01 # within the hemisphere's angular resolution
|
| 19 |
+
zero = np.zeros((1, 1, 1, 45)); zero[..., 0] = np.nan
|
| 20 |
+
p0, a0 = P.peaks(zero)
|
| 21 |
+
assert (p0 == 0).all() and (a0 == 0).all()
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def _result():
|
| 25 |
+
p = P.Protocol((P.Shell("d12-D24", 1000, 6),), n_b0=1)
|
| 26 |
+
m = P.measurements(p, CFG["shapes"])
|
| 27 |
+
rng = np.random.default_rng(0)
|
| 28 |
+
dwi = rng.random((6, 6, 6, 7)).astype(np.float32); dwi[0, 0] = np.nan
|
| 29 |
+
sh = np.zeros((6, 6, 6, 45)); sh[..., 0] = 1.0
|
| 30 |
+
peaks, amp = P.peaks(sh)
|
| 31 |
+
return dwi, m, peaks, amp
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def test_the_slice_viewer_draws_with_and_without_the_overlay():
|
| 35 |
+
dwi, m, peaks, amp = _result()
|
| 36 |
+
a = V.dwi_slice(dwi, m, 3, 2, peaks=peaks, peak_amp=amp, overlay=True)
|
| 37 |
+
b = V.dwi_slice(dwi, m, 3, 0)
|
| 38 |
+
assert a.size[0] > 100 and b.size[0] > 100
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def test_the_3d_views_hold_their_sample():
|
| 42 |
+
import nibabel as nib
|
| 43 |
+
import os
|
| 44 |
+
rois = np.asarray(nib.load(os.path.join(P.DATA_DIR, "DiSCo_ROIs.nii.gz")).dataobj).astype(np.int32)
|
| 45 |
+
strands = [np.cumsum(np.random.default_rng(i).normal(size=(20, 3)), 0) + 20 for i in range(50)]
|
| 46 |
+
regions = V.region_markers(rois)
|
| 47 |
+
assert regions.mode == "markers+text" and len(regions.x) == 16
|
| 48 |
+
fig = V.strands3d(strands, np.full(50, 2e-6), regions, rois.shape, n=30)
|
| 49 |
+
lines = [t for t in fig.data if t.mode == "lines"]
|
| 50 |
+
assert sum(int(np.isnan(np.asarray(t.x, float)).sum()) for t in lines) == 30 # one NaN gap per path
|
| 51 |
+
assert "2.0-2.0 µm" in fig.layout.title.text
|
| 52 |
+
from dmipy_tract import Tractogram
|
| 53 |
+
pts = np.concatenate(strands[:10]).astype(np.float32); offsets = np.r_[0, np.cumsum([len(s) for s in strands[:10]])]
|
| 54 |
+
tg = Tractogram(pts, offsets, np.arange(10), np.zeros((10, 2), np.int8))
|
| 55 |
+
fig2 = V.tractogram3d(tg, regions, rois.shape, n=4, total=12345)
|
| 56 |
+
assert sum(int(np.isnan(np.asarray(t.x, float)).sum()) for t in fig2.data if t.mode == "lines") == 4
|
| 57 |
+
assert "4 of 12,345" in fig2.layout.title.text
|
| 58 |
+
assert V.ground_truth_matrix(np.eye(16) * 0 + np.triu(np.ones((16, 16)), 1), np.triu(np.ones((16, 16)), 1) * 0.5, 120).size[0] > 100
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def test_the_timings_rows_are_the_stages():
|
| 62 |
+
rows = V.timings_rows(dict(replay=1.0, csd=2.0, total=3.0), 10.0)
|
| 63 |
+
assert rows[0][0].startswith("source") and [r[0] for r in rows[1:]] == ["replay", "csd", "total"]
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def test_the_floor_slice_draws_the_positive_voxels():
|
| 67 |
+
floor = np.zeros((8, 8, 4), np.float32); floor[2:6, 2:6, :] = 0.01; floor[3, 3, 1] = 0.05
|
| 68 |
+
img = V.floor_slice(floor, 1, 0.01, label="A: ")
|
| 69 |
+
assert img.size[0] > 100 and img.size[1] > 100
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def test_the_spread_matrices_draw():
|
| 73 |
+
M = np.zeros((16, 16)); M[0, 1] = M[1, 0] = 10
|
| 74 |
+
sp = P.pair_spread([M, M * 1.2], [dict(pearson_count=0.8), dict(pearson_count=0.82)], key="pearson_count")
|
| 75 |
+
assert V.spread_matrices(sp).size[0] > 100
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def test_the_map_slice_draws_plain_and_diverging():
|
| 79 |
+
vol = np.random.default_rng(0).normal(size=(6, 6, 3)); vol[0, 0] = np.nan
|
| 80 |
+
assert V.map_slice(vol, 1, "t").size[0] > 100 and V.map_slice(vol, 1, "d", symmetric=True).size[0] > 100
|
| 81 |
+
assert V.map_slice(np.full((6, 6, 3), np.nan), 1, "empty", symmetric=True).size[0] > 100
|
tools/build_brain_asset.py
ADDED
|
@@ -0,0 +1,370 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""The brain Space's asset (disco-space#8 step 4): a MASiVar scan's multi-shell DWI, reconstructed by dmipy-fit
|
| 2 |
+
*alone* (three-tissue responses, Dhollander 2016; multi-shell multi-tissue CSD, Jeurissen 2014, ``CsdCvxpyOptimizer``)
|
| 3 |
+
into a WM FOD field and WM/GM/CSF fractions, plus the parcellation of ``build_parcellation.py``, written to an asset
|
| 4 |
+
directory the Space's ``Brain`` source reads. The FOD and the fractions are dmipy-fit's
|
| 5 |
+
``MultiCompartmentSphericalHarmonicsModel`` end to end; MRtrix appears nowhere. dipy is used by this offline tool for
|
| 6 |
+
what is not reconstruction: the median-Otsu brain mask and the peak count of the sanity check (and inside dmipy-fit's
|
| 7 |
+
own tissue-response estimator until dmipy-fit#39 replaces it). Nothing here runs in the Space.
|
| 8 |
+
|
| 9 |
+
OMP_NUM_THREADS=4 MKL_NUM_THREADS=4 python tools/build_brain_asset.py --dwi-dir DIR --parcellation-dir PARC_DIR \\
|
| 10 |
+
--out-dir OUT [--n-test-voxels 200] [--solver csd_cvxpy]
|
| 11 |
+
|
| 12 |
+
``--dwi-dir`` holds the PreQual-preprocessed single-shell NIfTI + bval + bvec triples of one scan (the derivative
|
| 13 |
+
keeps every shell separate; this script is what merges them into one multi-shell volume). ``--parcellation-dir`` is
|
| 14 |
+
``build_parcellation.py``'s output (``labels.npy``, ``stop_mask.npy``, ``regions.json``); it is resampled here onto
|
| 15 |
+
the DWI's own grid only if its own grid differs (it does not, by construction: both scripts are handed the same
|
| 16 |
+
mean b=0 as the reference grid).
|
| 17 |
+
|
| 18 |
+
With ``--n-test-voxels`` set (no ``--out-dir`` write of the whole-brain arrays), fits only a random subset of masked
|
| 19 |
+
voxels and reports the measured per-voxel time and the whole-brain extrapolation, for a dry run before the (long)
|
| 20 |
+
full fit.
|
| 21 |
+
"""
|
| 22 |
+
from __future__ import annotations
|
| 23 |
+
|
| 24 |
+
import argparse
|
| 25 |
+
import glob
|
| 26 |
+
import json
|
| 27 |
+
import os
|
| 28 |
+
import subprocess
|
| 29 |
+
import time
|
| 30 |
+
|
| 31 |
+
import numpy as np
|
| 32 |
+
|
| 33 |
+
SH_ORDER = 8
|
| 34 |
+
B0_THRESHOLD_S_MM2 = 50.0 # a row below this b-value (s/mm^2) is a b = 0 measurement
|
| 35 |
+
RESPONSE_ERODE = 3 # erosion passes of the brain mask the responses are selected from
|
| 36 |
+
RESPONSES = ("three_tissue_response_dhollander16 (mask eroded 3 passes, as MRtrix dwi2response dhollander -erode 3; "
|
| 37 |
+
"white-matter selection tournier13)")
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def merge_shells(dwi_dir):
|
| 41 |
+
"""The PreQual per-shell NIfTI + bval + bvec triples of ``dwi_dir`` (one file per shell, each already carrying
|
| 42 |
+
its own b = 0 volume), concatenated into one multi-shell acquisition: ``(data, bvals, bvecs, affine, shells)``.
|
| 43 |
+
``data`` is ``(X, Y, Z, N)`` float32, ``bvals`` (s/mm^2) and ``bvecs`` (image-frame unit vectors, BIDS/FSL
|
| 44 |
+
convention) are ``(N,)`` / ``(N, 3)``; ``shells`` lists ``(b_value, n_directions)`` as found, ascending."""
|
| 45 |
+
import nibabel as nib
|
| 46 |
+
|
| 47 |
+
niis = sorted(glob.glob(os.path.join(dwi_dir, "*_dwi.nii.gz")))
|
| 48 |
+
if not niis:
|
| 49 |
+
raise FileNotFoundError(f"no *_dwi.nii.gz in {dwi_dir}")
|
| 50 |
+
datas, bvals, bvecs, shells, affine, ref_shape = [], [], [], [], None, None
|
| 51 |
+
for f in niis:
|
| 52 |
+
stem = f[: -len(".nii.gz")]
|
| 53 |
+
im = nib.load(f)
|
| 54 |
+
if affine is None:
|
| 55 |
+
affine, ref_shape = im.affine, im.shape[:3]
|
| 56 |
+
elif not np.allclose(im.affine, affine, atol=1e-4) or im.shape[:3] != ref_shape:
|
| 57 |
+
raise ValueError(f"{f} is not on the other shells' grid")
|
| 58 |
+
d = np.asarray(im.dataobj, dtype=np.float32)
|
| 59 |
+
bv = np.loadtxt(stem + ".bval")
|
| 60 |
+
vec = np.loadtxt(stem + ".bvec").T
|
| 61 |
+
datas.append(d)
|
| 62 |
+
bvals.append(bv)
|
| 63 |
+
bvecs.append(vec)
|
| 64 |
+
n_dwi = int((bv >= B0_THRESHOLD_S_MM2).sum())
|
| 65 |
+
if n_dwi:
|
| 66 |
+
shells.append((float(np.median(bv[bv >= B0_THRESHOLD_S_MM2])), n_dwi))
|
| 67 |
+
data = np.concatenate(datas, axis=-1)
|
| 68 |
+
bvals = np.concatenate(bvals)
|
| 69 |
+
bvecs = np.concatenate(bvecs, axis=0)
|
| 70 |
+
shells = sorted(shells)
|
| 71 |
+
return data, bvals, bvecs, affine, shells
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def mean_b0(data, bvals):
|
| 75 |
+
"""The mean of every b = 0 volume (``bvals < B0_THRESHOLD_S_MM2``), ``(X, Y, Z)`` float32."""
|
| 76 |
+
b0 = bvals < B0_THRESHOLD_S_MM2
|
| 77 |
+
if not np.any(b0):
|
| 78 |
+
raise ValueError("no b = 0 measurement in this acquisition")
|
| 79 |
+
return data[..., b0].mean(axis=-1).astype(np.float32)
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def brain_mask(mean_b0_volume):
|
| 83 |
+
"""The brain mask from the mean b = 0 image (dipy's median-Otsu, the standard tool; not dmipy-fit's job)."""
|
| 84 |
+
from dipy.segment.mask import median_otsu
|
| 85 |
+
_, mask = median_otsu(mean_b0_volume, median_radius=4, numpass=4)
|
| 86 |
+
return mask.astype(bool)
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def fit_msmt_csd(data, bvals, bvecs, mask, sh_order=SH_ORDER, solver="csd_cvxpy", voxel_positions=None):
|
| 90 |
+
"""dmipy-fit end to end: :func:`three_tissue_response_dhollander16` estimates the WM / GM / CSF response
|
| 91 |
+
kernels from the data itself (selected from ``mask`` eroded by ``RESPONSE_ERODE`` passes, the WM by tournier13),
|
| 92 |
+
then ``MultiCompartmentSphericalHarmonicsModel`` (``S0_tissue_responses`` set, volume fractions free) fits every voxel of ``mask`` with ``solver`` (``CsdCvxpyOptimizer`` for
|
| 93 |
+
``'csd_cvxpy'``). If ``voxel_positions`` is given (a ``(mask.sum(),)``-shaped boolean subset, for a dry run) only
|
| 94 |
+
those voxels are fit; the rest of ``mask`` is still used to estimate the responses.
|
| 95 |
+
|
| 96 |
+
Always fits serially (``use_parallel_processing=False``): dmipy-fit's parallel path forks a
|
| 97 |
+
``ProcessPoolExecutor`` after the JAX import this fit chain pulls in (``dmipy_sim.replay.so3``, for the SH
|
| 98 |
+
basis), which JAX warns is unsafe. Thread-level parallelism (BLAS/OSQP) is capped by
|
| 99 |
+
``OMP_NUM_THREADS``/``MKL_NUM_THREADS`` in the environment, per this lab's shared-box rule.
|
| 100 |
+
|
| 101 |
+
Returns ``(sh, fractions, S0_responses, response_models, scheme, seconds)``: ``sh`` is ``(X, Y, Z, n_coef)`` (the
|
| 102 |
+
WM FOD, zero outside the fitted voxels), ``fractions`` is ``(X, Y, Z, 3)`` (wm, gm, csf, zero outside), the rest
|
| 103 |
+
are for the manifest / checks."""
|
| 104 |
+
from dmipy_fit.core.acquisition_scheme import acquisition_scheme_from_bvalues
|
| 105 |
+
from dmipy_fit.core.modeling_framework import MultiCompartmentSphericalHarmonicsModel
|
| 106 |
+
from dmipy_fit.tissue_response.three_tissue_response import three_tissue_response_dhollander16
|
| 107 |
+
|
| 108 |
+
scheme = acquisition_scheme_from_bvalues(bvals * 1e6, bvecs, b0_threshold=B0_THRESHOLD_S_MM2 * 1e6)
|
| 109 |
+
data = np.nan_to_num(np.asarray(data, dtype=np.float64), nan=0.0)
|
| 110 |
+
|
| 111 |
+
t0 = time.perf_counter()
|
| 112 |
+
# The responses are selected from the brain mask eroded by 3 passes (the function's default, MRtrix's
|
| 113 |
+
# dwi2response dhollander -erode 3), the white matter by Tournier 2013's iterative peak-ratio selection (its
|
| 114 |
+
# default wm_algorithm): RESPONSES names both in the manifest.
|
| 115 |
+
(s0_wm, s0_gm, s0_csf), (tr2_wm, tr1_gm, tr1_csf), _selection = three_tissue_response_dhollander16(
|
| 116 |
+
scheme, data, mask=mask, erode=RESPONSE_ERODE)
|
| 117 |
+
response_seconds = time.perf_counter() - t0
|
| 118 |
+
|
| 119 |
+
mc = MultiCompartmentSphericalHarmonicsModel(
|
| 120 |
+
models=[tr2_wm, tr1_gm, tr1_csf], S0_tissue_responses=[s0_wm, s0_gm, s0_csf], sh_order=sh_order)
|
| 121 |
+
|
| 122 |
+
fit_mask = mask if voxel_positions is None else voxel_positions
|
| 123 |
+
t0 = time.perf_counter()
|
| 124 |
+
fitted = mc.fit(scheme, data, mask=fit_mask, solver=solver, verbose=False, use_parallel_processing=False)
|
| 125 |
+
fit_seconds = time.perf_counter() - t0
|
| 126 |
+
|
| 127 |
+
sh = np.asarray(fitted.fitted_parameters["sh_coeff"], dtype=np.float32)
|
| 128 |
+
fractions = np.stack([
|
| 129 |
+
np.asarray(fitted.fitted_parameters["partial_volume_0"], dtype=np.float32),
|
| 130 |
+
np.asarray(fitted.fitted_parameters["partial_volume_1"], dtype=np.float32),
|
| 131 |
+
np.asarray(fitted.fitted_parameters["partial_volume_2"], dtype=np.float32),
|
| 132 |
+
], axis=-1)
|
| 133 |
+
responses = {"S0_wm": float(s0_wm), "S0_gm": float(s0_gm), "S0_csf": float(s0_csf),
|
| 134 |
+
"response_seconds": response_seconds, "fit_seconds": fit_seconds,
|
| 135 |
+
"n_voxels_fit": int(np.sum(fit_mask))}
|
| 136 |
+
return sh, fractions, responses, scheme
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def _git_sha(repo_dir):
|
| 140 |
+
try:
|
| 141 |
+
return subprocess.check_output(["git", "-C", repo_dir, "rev-parse", "HEAD"], text=True).strip()
|
| 142 |
+
except Exception:
|
| 143 |
+
return None
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
def _dmipy_fit_commit():
|
| 147 |
+
"""The git commit of whichever ``dmipy-fit`` is actually importable (found from the package's own file path,
|
| 148 |
+
not a hard-coded location: ``PYTHONPATH`` picks which checkout this is)."""
|
| 149 |
+
import dmipy_fit
|
| 150 |
+
return _git_sha(os.path.dirname(os.path.dirname(os.path.abspath(dmipy_fit.__file__))))
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
def build_manifest(*, subject, scan, source_doi, grid_shape, voxel_size_mm, affine, bvals, bvecs, te_s, delta_s,
|
| 154 |
+
delta_cap_s, dmipy_fit_commit, disco_space_commit, solver, n_regions):
|
| 155 |
+
"""The asset's ``manifest.json`` payload (see disco-space#8's schema in the issue body)."""
|
| 156 |
+
return {
|
| 157 |
+
"subject": subject,
|
| 158 |
+
"source": {"dataset": "OpenNeuro ds003416", "doi": source_doi,
|
| 159 |
+
"paper_doi": "10.1002/mrm.28926", "license": "CC0", "scan": scan},
|
| 160 |
+
"grid": {"shape": list(int(s) for s in grid_shape), "voxel_size_mm": list(float(v) for v in voxel_size_mm),
|
| 161 |
+
"affine": np.asarray(affine, dtype=float).tolist()},
|
| 162 |
+
"protocol": {"bvals_s_mm2": np.asarray(bvals, dtype=float).tolist(),
|
| 163 |
+
"bvecs": np.asarray(bvecs, dtype=float).tolist(), "bvec_frame": "image",
|
| 164 |
+
"TE_s": te_s, "delta_s": delta_s, "Delta_s": delta_cap_s},
|
| 165 |
+
"fod": {"basis": "dmipy-fit tournier07 (dipy real_sh_tournier real-SH ordering)", "lmax": SH_ORDER,
|
| 166 |
+
"frame": "image"},
|
| 167 |
+
"fractions": ["wm", "gm", "csf"],
|
| 168 |
+
"reconstruction": {"tool": "dmipy-fit", "commit": dmipy_fit_commit,
|
| 169 |
+
"responses": RESPONSES, "solver": solver, "sh_order": SH_ORDER},
|
| 170 |
+
"parcellation": {"tool": "SynthSeg --parc --robust (BBillot/SynthSeg) + dipy rigid registration "
|
| 171 |
+
"(mutual information) + majority vote onto the diffusion grid",
|
| 172 |
+
"atlas": "Desikan-Killiany + aseg (fs_default 84)", "n_regions": n_regions},
|
| 173 |
+
"built_by": {"disco_space_commit": disco_space_commit, "date": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())},
|
| 174 |
+
}
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def save_checks_sample(out_dir, data, bvals, sh, fractions, mask, n_sample=2000, seed=0):
|
| 178 |
+
"""``checks/msmt_sample.npz``: a fixed-seed random sample of the input signal + fitted SH coefficients +
|
| 179 |
+
fractions, so dmipy-fit#39's fast solver can be checked against this (slow, cvxpy) reference."""
|
| 180 |
+
rng = np.random.default_rng(seed)
|
| 181 |
+
idx = np.argwhere(mask)
|
| 182 |
+
n_sample = min(n_sample, len(idx))
|
| 183 |
+
sel = idx[rng.choice(len(idx), size=n_sample, replace=False)]
|
| 184 |
+
pos = tuple(sel.T)
|
| 185 |
+
os.makedirs(os.path.join(out_dir, "checks"), exist_ok=True)
|
| 186 |
+
np.savez(os.path.join(out_dir, "checks", "msmt_sample.npz"),
|
| 187 |
+
voxel_index=sel.astype(np.int32), signal=data[pos].astype(np.float32),
|
| 188 |
+
bvals_s_mm2=np.asarray(bvals, dtype=np.float32),
|
| 189 |
+
sh_coeff=sh[pos].astype(np.float32), fractions=fractions[pos].astype(np.float32), seed=seed)
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
def fraction_sanity(fractions, mask):
|
| 193 |
+
"""The fraction-sum sanity numbers to report: the median and 99th percentile of ``wm + gm + csf`` in-mask (it
|
| 194 |
+
is not constrained to 1 by the unity constraint being off for ``S0_tissue_responses``-scaled fits -- see
|
| 195 |
+
``MultiCompartmentSphericalHarmonicsModel.fit``'s ``unity_constraint='kernel_dependent'`` default), and the
|
| 196 |
+
count of voxels with WM fraction > 0.5."""
|
| 197 |
+
s = fractions[mask].sum(axis=-1).astype(np.float64)
|
| 198 |
+
return {
|
| 199 |
+
"sum_median": float(np.median(s)),
|
| 200 |
+
"sum_p99": float(np.percentile(s, 99)),
|
| 201 |
+
"n_wm_gt_half": int(np.sum(fractions[..., 0][mask] > 0.5)),
|
| 202 |
+
"n_mask": int(mask.sum()),
|
| 203 |
+
}
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
def fod_peak_counts(sh, wm_mask, sh_order=SH_ORDER, relative_peak_threshold=0.5, min_separation_angle=25):
|
| 207 |
+
"""The number of FOD peaks per WM voxel (dipy's standard ``peak_directions`` on a fixed discrete sphere, the
|
| 208 |
+
tournier07 SH basis evaluated at its vertices): ``{n_peaks: count}``, the single-vs-crossing distribution."""
|
| 209 |
+
from collections import Counter
|
| 210 |
+
from dipy.data import get_sphere
|
| 211 |
+
from dipy.direction.peaks import peak_directions
|
| 212 |
+
from dmipy_tract import sh_matrix
|
| 213 |
+
|
| 214 |
+
sphere = get_sphere(name="repulsion724")
|
| 215 |
+
basis = sh_matrix(sh_order, sphere.vertices)
|
| 216 |
+
coef = np.nan_to_num(np.asarray(sh, np.float64))[wm_mask]
|
| 217 |
+
amplitudes = coef @ basis.T
|
| 218 |
+
counts = Counter()
|
| 219 |
+
for odf in amplitudes:
|
| 220 |
+
odf = np.clip(odf, 0, None)
|
| 221 |
+
if not np.any(odf > 0):
|
| 222 |
+
counts[0] += 1
|
| 223 |
+
continue
|
| 224 |
+
_, vals, _ = peak_directions(odf, sphere, relative_peak_threshold=relative_peak_threshold,
|
| 225 |
+
min_separation_angle=min_separation_angle)
|
| 226 |
+
counts[len(vals)] += 1
|
| 227 |
+
return dict(counts)
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
def save_mean_b0_fod_png(out_path, mean_b0_volume, sh, wm_mask, z=None, sh_order=SH_ORDER, step=2):
|
| 231 |
+
"""A PNG of one axial slice of the mean b = 0 image with the WM FOD's principal direction overlaid as a short
|
| 232 |
+
line segment per voxel (every ``step``-th voxel, to keep the plot legible); Matplotlib's ``Agg`` backend, no
|
| 233 |
+
display needed."""
|
| 234 |
+
import matplotlib
|
| 235 |
+
matplotlib.use("Agg")
|
| 236 |
+
import matplotlib.pyplot as plt
|
| 237 |
+
from dmipy_tract import hemisphere, sh_matrix
|
| 238 |
+
|
| 239 |
+
z = mean_b0_volume.shape[2] // 2 if z is None else z
|
| 240 |
+
dirs = hemisphere(362)
|
| 241 |
+
basis = sh_matrix(sh_order, dirs)
|
| 242 |
+
coef = np.nan_to_num(np.asarray(sh, np.float64)).reshape(-1, sh.shape[-1])
|
| 243 |
+
amp = coef @ basis.T
|
| 244 |
+
k = np.argmax(amp, axis=1)
|
| 245 |
+
peak = np.take_along_axis(amp, k[:, None], axis=1)[:, 0]
|
| 246 |
+
principal = np.where(peak[:, None] > 0, dirs[k], 0.0).reshape(sh.shape[:-1] + (3,))
|
| 247 |
+
|
| 248 |
+
fig, ax = plt.subplots(figsize=(6, 6))
|
| 249 |
+
ax.imshow(mean_b0_volume[:, :, z].T, cmap="gray", origin="lower")
|
| 250 |
+
xs, ys, us, vs = [], [], [], []
|
| 251 |
+
for x in range(0, mean_b0_volume.shape[0], step):
|
| 252 |
+
for y in range(0, mean_b0_volume.shape[1], step):
|
| 253 |
+
if not wm_mask[x, y, z]:
|
| 254 |
+
continue
|
| 255 |
+
d = principal[x, y, z]
|
| 256 |
+
if np.linalg.norm(d) < 1e-6:
|
| 257 |
+
continue
|
| 258 |
+
xs.append(x); ys.append(y); us.append(d[0]); vs.append(d[1])
|
| 259 |
+
ax.quiver(xs, ys, us, vs, angles="xy", scale_units="xy", scale=1.2, headaxislength=0, headlength=0,
|
| 260 |
+
width=0.003, color="red")
|
| 261 |
+
ax.set_title(f"mean b=0, axial z={z}, WM FOD principal direction")
|
| 262 |
+
ax.set_xticks([]); ax.set_yticks([])
|
| 263 |
+
fig.tight_layout()
|
| 264 |
+
fig.savefig(out_path, dpi=130)
|
| 265 |
+
plt.close(fig)
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
def run_checks(out_dir):
|
| 269 |
+
"""Loads a finished asset directory's arrays and writes ``checks/sanity_summary.json`` and
|
| 270 |
+
``checks/mean_b0_fod_slice.png`` (the peak-count / fraction-sum / WM-volume numbers this issue asks to report,
|
| 271 |
+
decoupled from the -- long -- fit itself, so a completed fit's checks can be (re)computed on their own)."""
|
| 272 |
+
fractions = np.load(os.path.join(out_dir, "fractions.npy")).astype(np.float32)
|
| 273 |
+
mask = np.load(os.path.join(out_dir, "mask.npy"))
|
| 274 |
+
sh = np.load(os.path.join(out_dir, "fod_wm.npy"))
|
| 275 |
+
mean_b0_volume = np.load(os.path.join(out_dir, "mean_b0.npy"))
|
| 276 |
+
wm_mask = mask & (fractions[..., 0] > 0.5)
|
| 277 |
+
|
| 278 |
+
summary = {"fractions": fraction_sanity(fractions, mask), "fod_peak_counts_in_wm": fod_peak_counts(sh, wm_mask)}
|
| 279 |
+
os.makedirs(os.path.join(out_dir, "checks"), exist_ok=True)
|
| 280 |
+
with open(os.path.join(out_dir, "checks", "sanity_summary.json"), "w") as f:
|
| 281 |
+
json.dump(summary, f, indent=2)
|
| 282 |
+
save_mean_b0_fod_png(os.path.join(out_dir, "checks", "mean_b0_fod_slice.png"), mean_b0_volume, sh, wm_mask)
|
| 283 |
+
print(json.dumps(summary, indent=2))
|
| 284 |
+
return summary
|
| 285 |
+
|
| 286 |
+
|
| 287 |
+
def main():
|
| 288 |
+
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
| 289 |
+
ap.add_argument("--dwi-dir", required=False, default=None)
|
| 290 |
+
ap.add_argument("--parcellation-dir", required=False, default=None)
|
| 291 |
+
ap.add_argument("--out-dir", required=True)
|
| 292 |
+
ap.add_argument("--subject", default="MASiVar sub-cIs1 ses-s1Ax1 run-1xx")
|
| 293 |
+
ap.add_argument("--source-doi", default="10.18112/openneuro.ds003416.v2.0.2")
|
| 294 |
+
ap.add_argument("--solver", default="csd_cvxpy")
|
| 295 |
+
ap.add_argument("--n-test-voxels", type=int, default=None,
|
| 296 |
+
help="fit only this many random masked voxels (a dry run; nothing written under --out-dir "
|
| 297 |
+
"except the printed timing)")
|
| 298 |
+
ap.add_argument("--seed", type=int, default=0)
|
| 299 |
+
ap.add_argument("--checks-only", action="store_true",
|
| 300 |
+
help="skip everything above and just (re)compute checks/sanity_summary.json + the FOD PNG "
|
| 301 |
+
"from an --out-dir a previous run already wrote")
|
| 302 |
+
a = ap.parse_args()
|
| 303 |
+
|
| 304 |
+
if a.checks_only:
|
| 305 |
+
run_checks(a.out_dir)
|
| 306 |
+
return
|
| 307 |
+
if not a.dwi_dir or not a.parcellation_dir:
|
| 308 |
+
ap.error("--dwi-dir and --parcellation-dir are required unless --checks-only")
|
| 309 |
+
|
| 310 |
+
import nibabel as nib
|
| 311 |
+
|
| 312 |
+
data, bvals, bvecs, affine, shells = merge_shells(a.dwi_dir)
|
| 313 |
+
b0 = mean_b0(data, bvals)
|
| 314 |
+
mask = brain_mask(b0)
|
| 315 |
+
voxel_size_mm = np.linalg.norm(affine[:3, :3], axis=0)
|
| 316 |
+
print(f"grid {data.shape[:3]}, voxel {voxel_size_mm} mm, {data.shape[-1]} measurements, shells {shells}, "
|
| 317 |
+
f"mask voxels {mask.sum()}")
|
| 318 |
+
|
| 319 |
+
if a.n_test_voxels:
|
| 320 |
+
rng = np.random.default_rng(a.seed)
|
| 321 |
+
idx = np.argwhere(mask)
|
| 322 |
+
sel = idx[rng.choice(len(idx), size=min(a.n_test_voxels, len(idx)), replace=False)]
|
| 323 |
+
voxel_positions = np.zeros(mask.shape, dtype=bool)
|
| 324 |
+
voxel_positions[tuple(sel.T)] = True
|
| 325 |
+
sh, fractions, responses, _scheme = fit_msmt_csd(
|
| 326 |
+
data, bvals, bvecs, mask, solver=a.solver, voxel_positions=voxel_positions)
|
| 327 |
+
per_voxel = responses["fit_seconds"] / responses["n_voxels_fit"]
|
| 328 |
+
print(f"responses {responses['response_seconds']:.1f} s; fit {responses['n_voxels_fit']} voxels in "
|
| 329 |
+
f"{responses['fit_seconds']:.1f} s ({per_voxel * 1e3:.1f} ms/voxel); whole brain "
|
| 330 |
+
f"({int(mask.sum())} voxels) extrapolates to {per_voxel * int(mask.sum()) / 60:.1f} min serial")
|
| 331 |
+
return
|
| 332 |
+
|
| 333 |
+
labels = np.load(os.path.join(a.parcellation_dir, "labels.npy"))
|
| 334 |
+
stop_mask = np.load(os.path.join(a.parcellation_dir, "stop_mask.npy"))
|
| 335 |
+
with open(os.path.join(a.parcellation_dir, "regions.json")) as f:
|
| 336 |
+
regions = json.load(f)
|
| 337 |
+
if labels.shape != data.shape[:3]:
|
| 338 |
+
raise ValueError(f"parcellation grid {labels.shape} does not match the DWI grid {data.shape[:3]}")
|
| 339 |
+
|
| 340 |
+
sh, fractions, responses, _scheme = fit_msmt_csd(data, bvals, bvecs, mask, solver=a.solver)
|
| 341 |
+
print(f"responses {responses['response_seconds']:.1f} s; whole-brain fit "
|
| 342 |
+
f"{responses['n_voxels_fit']} voxels in {responses['fit_seconds']:.1f} s")
|
| 343 |
+
|
| 344 |
+
os.makedirs(a.out_dir, exist_ok=True)
|
| 345 |
+
np.save(os.path.join(a.out_dir, "fod_wm.npy"), sh)
|
| 346 |
+
np.save(os.path.join(a.out_dir, "fractions.npy"), np.clip(fractions, 0, 1).astype(np.float16))
|
| 347 |
+
np.save(os.path.join(a.out_dir, "mask.npy"), mask)
|
| 348 |
+
np.save(os.path.join(a.out_dir, "mean_b0.npy"), b0)
|
| 349 |
+
np.save(os.path.join(a.out_dir, "labels.npy"), labels)
|
| 350 |
+
np.save(os.path.join(a.out_dir, "stop_mask.npy"), stop_mask)
|
| 351 |
+
with open(os.path.join(a.out_dir, "regions.json"), "w") as f:
|
| 352 |
+
json.dump(regions, f, indent=2)
|
| 353 |
+
|
| 354 |
+
manifest = build_manifest(
|
| 355 |
+
subject=a.subject, scan="ses-s1Ax1 run-1xx (b1000/1500/2000/2500/3000, n=96 each, PreQual-preprocessed)",
|
| 356 |
+
source_doi=a.source_doi, grid_shape=data.shape[:3], voxel_size_mm=voxel_size_mm, affine=affine,
|
| 357 |
+
bvals=bvals, bvecs=bvecs, te_s=None, delta_s=None, delta_cap_s=None,
|
| 358 |
+
dmipy_fit_commit=_dmipy_fit_commit(),
|
| 359 |
+
disco_space_commit=_git_sha(os.path.join(os.path.dirname(__file__), "..")),
|
| 360 |
+
solver=a.solver, n_regions=len(regions["regions"]))
|
| 361 |
+
with open(os.path.join(a.out_dir, "manifest.json"), "w") as f:
|
| 362 |
+
json.dump(manifest, f, indent=2)
|
| 363 |
+
|
| 364 |
+
save_checks_sample(a.out_dir, data, bvals, sh, fractions, mask, seed=a.seed)
|
| 365 |
+
run_checks(a.out_dir)
|
| 366 |
+
print(f"asset written to {a.out_dir}")
|
| 367 |
+
|
| 368 |
+
|
| 369 |
+
if __name__ == "__main__":
|
| 370 |
+
main()
|
tools/build_brain_fixture.py
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""The development fixture of the brain Space: the B.A.T.M.A.N. tutorial subject written in the layout of the brain
|
| 2 |
+
asset (``manifest.json``, ``fod_wm.npy``, ``fractions.npy``, ``mask.npy``, ``labels.npy``, ``regions.json``,
|
| 3 |
+
``stop_mask.npy``, ``mean_b0.npy``), so the ``Brain`` source is developed and tested against the asset's contract
|
| 4 |
+
before the MASiVar asset exists. It stays local (BATMAN's licence, dmipy-sim#193) and is for tests only.
|
| 5 |
+
|
| 6 |
+
What each file is:
|
| 7 |
+
|
| 8 |
+
* ``fod_wm.npy`` -- ``wmfod_norm.mif`` (MRtrix3 multi-tissue CSD, lmax 8, the MRtrix3 basis, which is dmipy-sim's
|
| 9 |
+
required basis and dmipy-fit's) turned from the scanner frame into the image frame by ``R.T`` (``R`` from
|
| 10 |
+
:meth:`dmipy_sim.phantom.Grid.from_oblique_affine`), zero outside the brain mask.
|
| 11 |
+
* ``fractions.npy`` -- WM / GM / CSF from ``5tt_coreg.mif`` (on the 1 mm T1 grid), averaged into every 2.5 mm
|
| 12 |
+
voxel on a 3^3 sub-grid as ``examples/rph/brain_from_csd.py`` does: GM is cortical + sub-cortical GM, WM where
|
| 13 |
+
the FOD has no positive l = 0 coefficient is counted as GM (no FOD, no oriented WM), zero outside the mask.
|
| 14 |
+
* ``labels.npy`` / ``regions.json`` -- there is no parcellation of this subject, so the GM voxels (GM fraction
|
| 15 |
+
above one half) are split into 84 blocks by k-means on their coordinates (42 per hemisphere, a fixed seed),
|
| 16 |
+
named ``fixture <hemisphere> <k>`` and given to 7 lobes by position: a fixture of the 84-node layout, no anatomy.
|
| 17 |
+
* ``stop_mask.npy`` -- the voxels whose 5TT WM fraction is above one half: where a streamline may continue.
|
| 18 |
+
* ``mean_b0.npy`` -- ``mean_b0_preprocessed.mif``.
|
| 19 |
+
* ``manifest.json`` -- the grid (the image's affine, voxel -> scanner RAS mm), the tutorial's gradient table
|
| 20 |
+
(scanner frame) with the capstone's pulse timing (TE 100 / delta 25 / Delta 55 ms, which the 100 ms packs play).
|
| 21 |
+
|
| 22 |
+
python tools/build_brain_fixture.py [--batman ~/dmrai-ws/data/batman] [--out ~/dmrai-ws/data/batman/brain_fixture]
|
| 23 |
+
"""
|
| 24 |
+
import argparse
|
| 25 |
+
import json
|
| 26 |
+
import os
|
| 27 |
+
import subprocess
|
| 28 |
+
|
| 29 |
+
import numpy as np
|
| 30 |
+
|
| 31 |
+
GM_COLS, WM_COL, CSF_COL = (0, 1), 2, 3 # the 5TT columns: cortical GM, sub-cortical GM, WM, CSF
|
| 32 |
+
LOBES = ("frontal", "insula", "cingulate", "temporal", "parietal", "occipital", "subcortical")
|
| 33 |
+
TIMING = dict(TE_s=0.100, delta_s=0.025, Delta_s=0.055) # the BATMAN capstone's (dmipy-sim#193)
|
| 34 |
+
SEED = 20260930
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def fractions_on(shape, target_affine, tt, sub=3):
|
| 38 |
+
"""The five 5TT fractions averaged into every voxel of the target grid: ``sub^3`` points per voxel mapped
|
| 39 |
+
through both affines and sampled trilinearly on the T1 grid; ``(X, Y, Z, 5)``."""
|
| 40 |
+
from scipy.ndimage import map_coordinates
|
| 41 |
+
off = (np.arange(sub) + 0.5) / sub - 0.5
|
| 42 |
+
o = np.stack(np.meshgrid(off, off, off, indexing="ij"), -1).reshape(-1, 3)
|
| 43 |
+
ijk = np.stack(np.meshgrid(*[np.arange(n) for n in shape], indexing="ij"), -1).reshape(-1, 3)
|
| 44 |
+
pts = (ijk[:, None, :] + o[None, :, :]).reshape(-1, 3)
|
| 45 |
+
xyz = pts @ target_affine[:3, :3].T + target_affine[:3, 3]
|
| 46 |
+
inv = np.linalg.inv(tt.affine)
|
| 47 |
+
src = xyz @ inv[:3, :3].T + inv[:3, 3]
|
| 48 |
+
out = np.stack([map_coordinates(tt.data[..., t], src.T, order=1, mode="constant", cval=0.0) for t in range(5)], -1)
|
| 49 |
+
return out.reshape(tuple(shape) + (sub ** 3, 5)).mean(axis=3)
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def parcellate(gm, shape):
|
| 53 |
+
"""84 k-means blocks of the GM voxels (42 per hemisphere, split at the median x of the brain), ``(labels,
|
| 54 |
+
regions)``: labels 1..42 left, 43..84 right; per hemisphere the six blocks nearest the brain's centre are
|
| 55 |
+
'subcortical' and the other 36, sorted front to back (image y), fill the six cortical lobes six at a time."""
|
| 56 |
+
from scipy.cluster.vq import kmeans2
|
| 57 |
+
ijk = np.argwhere(gm).astype(np.float64)
|
| 58 |
+
centre = ijk.mean(0)
|
| 59 |
+
labels = np.zeros(shape, np.int16)
|
| 60 |
+
regions = []
|
| 61 |
+
for h, (hemi, side) in enumerate((("left", ijk[:, 0] < centre[0]), ("right", ijk[:, 0] >= centre[0]))):
|
| 62 |
+
pts = ijk[side]
|
| 63 |
+
cents, lab = kmeans2(pts, 42, seed=SEED + h, minit="++", iter=50)
|
| 64 |
+
order = np.argsort(np.linalg.norm(cents - centre, axis=1))
|
| 65 |
+
sub = list(order[:6])
|
| 66 |
+
cortical = sorted(order[6:], key=lambda k: -cents[k, 1]) # anterior (large y) first
|
| 67 |
+
lobe_of = {k: "subcortical" for k in sub}
|
| 68 |
+
for i, k in enumerate(cortical):
|
| 69 |
+
lobe_of[k] = LOBES[i // 6]
|
| 70 |
+
for rank, k in enumerate(sorted(range(42), key=lambda k: (LOBES.index(lobe_of[k]), -cents[k, 1]))):
|
| 71 |
+
rid = 1 + 42 * h + rank
|
| 72 |
+
v = pts[lab == k].astype(int)
|
| 73 |
+
labels[v[:, 0], v[:, 1], v[:, 2]] = rid
|
| 74 |
+
regions.append(dict(id=rid, name=f"fixture {hemi} {rank + 1:02d}", hemisphere=hemi, lobe=lobe_of[k]))
|
| 75 |
+
return labels, regions
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def main(argv=None):
|
| 79 |
+
from dmipy_sim.io.mrtrix import read_mif
|
| 80 |
+
from dmipy_sim.phantom import Grid
|
| 81 |
+
from dmipy_sim.replay.so3 import rotate_sh
|
| 82 |
+
ap = argparse.ArgumentParser()
|
| 83 |
+
ap.add_argument("--batman", default=os.path.expanduser("~/dmrai-ws/data/batman"))
|
| 84 |
+
ap.add_argument("--out", default=os.path.expanduser("~/dmrai-ws/data/batman/brain_fixture"))
|
| 85 |
+
a = ap.parse_args(argv)
|
| 86 |
+
os.makedirs(a.out, exist_ok=True)
|
| 87 |
+
fod = read_mif(os.path.join(a.batman, "wmfod_norm.mif"))
|
| 88 |
+
mask = np.asarray(read_mif(os.path.join(a.batman, "mask_den_unr_preproc_unb.mif")).data, bool)
|
| 89 |
+
tt = read_mif(os.path.join(a.batman, "5tt_coreg.mif"))
|
| 90 |
+
b0 = read_mif(os.path.join(a.batman, "mean_b0_preprocessed.mif"))
|
| 91 |
+
shape = fod.shape[:3]
|
| 92 |
+
_, R = Grid.from_oblique_affine(fod.affine, shape)
|
| 93 |
+
sh = rotate_sh(np.asarray(fod.data, np.float64), np.asarray(R).T) * mask[..., None]
|
| 94 |
+
F = fractions_on(shape, fod.affine, tt) * mask[..., None]
|
| 95 |
+
has_fod = sh[..., 0] > 0
|
| 96 |
+
f_wm = F[..., WM_COL] * has_fod
|
| 97 |
+
f_gm = F[..., GM_COLS[0]] + F[..., GM_COLS[1]] + F[..., WM_COL] * ~has_fod
|
| 98 |
+
f_csf = F[..., CSF_COL]
|
| 99 |
+
fractions = np.stack([f_wm, f_gm, f_csf], -1)
|
| 100 |
+
labels, regions = parcellate(mask & (f_gm > 0.5), shape)
|
| 101 |
+
stop = mask & (F[..., WM_COL] > 0.5)
|
| 102 |
+
g = np.loadtxt(os.path.join(a.batman, "dwipreproc_grad.b"))
|
| 103 |
+
commit = subprocess.run(["git", "-C", os.path.dirname(os.path.abspath(__file__)), "rev-parse", "HEAD"], capture_output=True, text=True).stdout.strip()
|
| 104 |
+
groups = []
|
| 105 |
+
for r in regions:
|
| 106 |
+
name = f"{r['hemisphere'][0].upper()} {r['lobe']}"
|
| 107 |
+
grp = next((x for x in groups if x["name"] == name), None)
|
| 108 |
+
if grp is None:
|
| 109 |
+
grp = dict(name=name, hemisphere=r["hemisphere"], lobe=r["lobe"], ids=[]); groups.append(grp)
|
| 110 |
+
grp["ids"].append(r["id"])
|
| 111 |
+
manifest = {
|
| 112 |
+
"subject": "BATMAN (fixture)",
|
| 113 |
+
"source": {"dataset": "B.A.T.M.A.N. MRtrix3 tutorial (Tahedl 2018), Supplementary_Files", "doi": "10.17605/OSF.IO/FKYHT",
|
| 114 |
+
"paper_doi": None, "license": "local development fixture only (dmipy-sim#193 item 1)"},
|
| 115 |
+
"grid": {"shape": list(shape), "voxel_size_mm": [float(x) for x in np.linalg.norm(fod.affine[:3, :3], axis=0)],
|
| 116 |
+
"affine": np.asarray(fod.affine, float).tolist()},
|
| 117 |
+
"protocol": {"bvals_s_mm2": [float(round(b)) for b in g[:, 3]], "bvecs": g[:, :3].tolist(), "bvec_frame": "scanner", **TIMING},
|
| 118 |
+
"fod": {"basis": "tournier07", "lmax": 8, "frame": "image"},
|
| 119 |
+
"fractions": ["wm", "gm", "csf"],
|
| 120 |
+
"reconstruction": {"by": "MRtrix3 dwi2fod msmt_csd (the tutorial's wmfod_norm.mif), 5TT fractions", "fixture": True},
|
| 121 |
+
"parcellation": {"method": "fixture: k-means blocks of the GM voxels, 42 per hemisphere, seed %d" % SEED, "n_regions": len(regions)},
|
| 122 |
+
"built_by": {"tool": "disco-space tools/build_brain_fixture.py", "commit": commit},
|
| 123 |
+
}
|
| 124 |
+
np.save(os.path.join(a.out, "fod_wm.npy"), sh.astype(np.float32))
|
| 125 |
+
np.save(os.path.join(a.out, "fractions.npy"), fractions.astype(np.float16))
|
| 126 |
+
np.save(os.path.join(a.out, "mask.npy"), mask)
|
| 127 |
+
np.save(os.path.join(a.out, "labels.npy"), labels)
|
| 128 |
+
np.save(os.path.join(a.out, "stop_mask.npy"), stop)
|
| 129 |
+
np.save(os.path.join(a.out, "mean_b0.npy"), np.asarray(b0.data, np.float32))
|
| 130 |
+
with open(os.path.join(a.out, "regions.json"), "w") as f:
|
| 131 |
+
json.dump(dict(regions=regions, groups=groups), f, indent=1)
|
| 132 |
+
with open(os.path.join(a.out, "manifest.json"), "w") as f:
|
| 133 |
+
json.dump(manifest, f, indent=1)
|
| 134 |
+
print(f"{a.out}: grid {shape}, {int(mask.sum())} brain voxels, {int((f_wm > 0).sum())} with WM, {int(stop.sum())} in the stop mask, "
|
| 135 |
+
f"{len(regions)} regions ({len(groups)} lobar groups), {len(g)} measurements")
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
if __name__ == "__main__":
|
| 139 |
+
main()
|
tools/build_parcellation.py
ADDED
|
@@ -0,0 +1,233 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Desikan-Killiany + aseg (the MRtrix ``fs_default`` convention, 84 nodes: 34 cortical + 8 subcortical per
|
| 2 |
+
hemisphere), majority-voted from a SynthSeg segmentation in T1 space onto a diffusion grid, plus a 14-node lobar
|
| 3 |
+
grouping (7 lobes x 2 hemispheres) and a white-matter stop mask for tracking.
|
| 4 |
+
|
| 5 |
+
The segmentation itself is made *outside* this repo by ``SynthSeg --parc --robust`` (BBillot/SynthSeg;
|
| 6 |
+
https://github.com/BBillot/SynthSeg) on the T1, run in its own environment (this script has no TensorFlow
|
| 7 |
+
dependency). This module only consumes that NIfTI: it registers the T1 onto the diffusion grid (rigid, dipy, mutual
|
| 8 |
+
information) and resamples the labels with true majority voting -- for every diffusion voxel, every label found
|
| 9 |
+
among its ``factor**3`` sub-points (sampled at the T1's native resolution through the fitted transform) is counted
|
| 10 |
+
and the plurality wins, rather than a single nearest-neighbour point sample.
|
| 11 |
+
|
| 12 |
+
python tools/build_parcellation.py --t1 T1w.nii.gz --synthseg aseg.nii.gz --ref mean_b0.nii.gz --out-dir OUT
|
| 13 |
+
|
| 14 |
+
Writes, on the reference (diffusion) grid, under ``--out-dir``:
|
| 15 |
+
labels.npy int16 (X, Y, Z): compact node id 1..84 in the 84 regions, 0 elsewhere
|
| 16 |
+
stop_mask.npy bool (X, Y, Z): True where the segmentation's majority label is white matter (a streamline may
|
| 17 |
+
continue there; leaving white matter into cortex, a ventricle or CSF ends it)
|
| 18 |
+
regions.json the 84 nodes (id, name, hemisphere, lobe) and the 14 lobar groups
|
| 19 |
+
"""
|
| 20 |
+
from __future__ import annotations
|
| 21 |
+
|
| 22 |
+
import argparse
|
| 23 |
+
import json
|
| 24 |
+
|
| 25 |
+
import numpy as np
|
| 26 |
+
|
| 27 |
+
# ---- the FreeSurfer label tables (FreeSurferColorLUT.txt), restricted to what SynthSeg --parc --robust emits -----
|
| 28 |
+
|
| 29 |
+
# The 34 Desikan-Killiany cortical regions, FreeSurfer's own (alphabetical) ctx-lh-* numbering, 1001..1035 skipping
|
| 30 |
+
# 1004 (corpuscallosum, not part of the DK pial surface labelling and not emitted by SynthSeg); ctx-rh-* is +1000.
|
| 31 |
+
CORTICAL_NAMES = {
|
| 32 |
+
1001: "bankssts", 1002: "caudalanteriorcingulate", 1003: "caudalmiddlefrontal", 1005: "cuneus",
|
| 33 |
+
1006: "entorhinal", 1007: "fusiform", 1008: "inferiorparietal", 1009: "inferiortemporal",
|
| 34 |
+
1010: "isthmuscingulate", 1011: "lateraloccipital", 1012: "lateralorbitofrontal", 1013: "lingual",
|
| 35 |
+
1014: "medialorbitofrontal", 1015: "middletemporal", 1016: "parahippocampal", 1017: "paracentral",
|
| 36 |
+
1018: "parsopercularis", 1019: "parsorbitalis", 1020: "parstriangularis", 1021: "pericalcarine",
|
| 37 |
+
1022: "postcentral", 1023: "posteriorcingulate", 1024: "precentral", 1025: "precuneus",
|
| 38 |
+
1026: "rostralanteriorcingulate", 1027: "rostralmiddlefrontal", 1028: "superiorfrontal",
|
| 39 |
+
1029: "superiorparietal", 1030: "superiortemporal", 1031: "supramarginal", 1032: "frontalpole",
|
| 40 |
+
1033: "temporalpole", 1034: "transversetemporal", 1035: "insula",
|
| 41 |
+
}
|
| 42 |
+
|
| 43 |
+
# The 8 subcortical structures per hemisphere SynthSeg --parc --robust emits (aseg ids); left and right are not a
|
| 44 |
+
# uniform offset of one another, so both are given explicitly.
|
| 45 |
+
SUBCORTICAL_NAMES_LEFT = {
|
| 46 |
+
10: "Thalamus", 11: "Caudate", 12: "Putamen", 13: "Pallidum",
|
| 47 |
+
17: "Hippocampus", 18: "Amygdala", 26: "Accumbens-area", 28: "VentralDC",
|
| 48 |
+
}
|
| 49 |
+
SUBCORTICAL_NAMES_RIGHT = {
|
| 50 |
+
49: "Thalamus", 50: "Caudate", 51: "Putamen", 52: "Pallidum",
|
| 51 |
+
53: "Hippocampus", 54: "Amygdala", 58: "Accumbens-area", 60: "VentralDC",
|
| 52 |
+
}
|
| 53 |
+
|
| 54 |
+
# A standard six-lobe grouping of the 34 DK cortical regions (Klein & Tourville 2012-style), plus a seventh
|
| 55 |
+
# "subcortical" group per hemisphere for the 8 subcortical structures: 7 lobes x 2 hemispheres = 14 groups.
|
| 56 |
+
LOBE_OF_CORTICAL = {
|
| 57 |
+
"superiorfrontal": "frontal", "rostralmiddlefrontal": "frontal", "caudalmiddlefrontal": "frontal",
|
| 58 |
+
"parsopercularis": "frontal", "parstriangularis": "frontal", "parsorbitalis": "frontal",
|
| 59 |
+
"lateralorbitofrontal": "frontal", "medialorbitofrontal": "frontal", "precentral": "frontal",
|
| 60 |
+
"paracentral": "frontal", "frontalpole": "frontal",
|
| 61 |
+
"superiorparietal": "parietal", "inferiorparietal": "parietal", "supramarginal": "parietal",
|
| 62 |
+
"postcentral": "parietal", "precuneus": "parietal",
|
| 63 |
+
"superiortemporal": "temporal", "middletemporal": "temporal", "inferiortemporal": "temporal",
|
| 64 |
+
"bankssts": "temporal", "fusiform": "temporal", "transversetemporal": "temporal", "entorhinal": "temporal",
|
| 65 |
+
"temporalpole": "temporal", "parahippocampal": "temporal",
|
| 66 |
+
"lateraloccipital": "occipital", "lingual": "occipital", "cuneus": "occipital", "pericalcarine": "occipital",
|
| 67 |
+
"caudalanteriorcingulate": "cingulate", "rostralanteriorcingulate": "cingulate",
|
| 68 |
+
"posteriorcingulate": "cingulate", "isthmuscingulate": "cingulate",
|
| 69 |
+
"insula": "insula",
|
| 70 |
+
}
|
| 71 |
+
assert set(LOBE_OF_CORTICAL) == set(CORTICAL_NAMES.values())
|
| 72 |
+
LOBES = ("frontal", "parietal", "temporal", "occipital", "cingulate", "insula", "subcortical")
|
| 73 |
+
|
| 74 |
+
# White-matter labels: a streamline may continue here (cerebral + cerebellar white matter, brain-stem); leaving
|
| 75 |
+
# this set (into cortex, a ventricle or CSF) ends it. Judgement call, not part of the 84-node parcellation itself.
|
| 76 |
+
WM_STOP_LABELS = frozenset({2, 41, 7, 46, 16}) # Left/Right-Cerebral-WM, Left/Right-Cerebellum-WM, Brain-Stem
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def node_table():
|
| 80 |
+
"""The 84 nodes in a fixed, documented order: node id 1..42 is the left hemisphere (34 cortical by ascending
|
| 81 |
+
FreeSurfer id, then the 8 subcortical structures), 43..84 the same for the right. Each entry is
|
| 82 |
+
``{"id", "fs_label", "name", "hemisphere", "lobe"}``."""
|
| 83 |
+
nodes = []
|
| 84 |
+
for hemi, cortical, subcortical in (
|
| 85 |
+
("left", CORTICAL_NAMES, SUBCORTICAL_NAMES_LEFT),
|
| 86 |
+
("right", {k + 1000: v for k, v in CORTICAL_NAMES.items()}, SUBCORTICAL_NAMES_RIGHT),
|
| 87 |
+
):
|
| 88 |
+
for fs_id in sorted(cortical):
|
| 89 |
+
name = cortical[fs_id]
|
| 90 |
+
nodes.append({"fs_label": fs_id, "name": name, "hemisphere": hemi, "lobe": LOBE_OF_CORTICAL[name]})
|
| 91 |
+
for fs_id in sorted(subcortical):
|
| 92 |
+
nodes.append({"fs_label": fs_id, "name": subcortical[fs_id], "hemisphere": hemi, "lobe": "subcortical"})
|
| 93 |
+
for i, node in enumerate(nodes, start=1):
|
| 94 |
+
node["id"] = i
|
| 95 |
+
assert len(nodes) == 84
|
| 96 |
+
return nodes
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def regions_payload():
|
| 100 |
+
"""``regions.json``'s content: the 84 nodes plus the 14 lobar groups (lobe x hemisphere)."""
|
| 101 |
+
nodes = node_table()
|
| 102 |
+
groups = [f"{lobe}-{hemi}" for lobe in LOBES for hemi in ("left", "right")]
|
| 103 |
+
return {
|
| 104 |
+
"convention": "Desikan-Killiany + aseg (MRtrix fs_default, 84 nodes: 34 cortical + 8 subcortical per hemisphere)",
|
| 105 |
+
"regions": nodes,
|
| 106 |
+
"lobes": groups,
|
| 107 |
+
}
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def register_t1_to_ref(t1_data, t1_affine, ref_data, ref_affine):
|
| 111 |
+
"""The rigid (6 DOF) transform of ``t1``'s world space onto ``ref``'s (dipy, mutual information: a standard
|
| 112 |
+
cross-modal registration). Returns the ``AffineMap``-style 4x4 matrix mapping a point in ``ref``'s world space
|
| 113 |
+
to the corresponding point in ``t1``'s world space (dipy's convention: domain -> codomain)."""
|
| 114 |
+
from dipy.align.imaffine import transform_centers_of_mass, AffineRegistration, MutualInformationMetric
|
| 115 |
+
from dipy.align.transforms import RigidTransform3D
|
| 116 |
+
|
| 117 |
+
com = transform_centers_of_mass(ref_data, ref_affine, t1_data, t1_affine)
|
| 118 |
+
metric = MutualInformationMetric(nbins=32, sampling_proportion=0.3)
|
| 119 |
+
affreg = AffineRegistration(metric=metric, level_iters=[1000, 200, 50], sigmas=[3.0, 1.0, 0.0], factors=[4, 2, 1])
|
| 120 |
+
rigid = affreg.optimize(ref_data, t1_data, RigidTransform3D(), params0=None,
|
| 121 |
+
static_grid2world=ref_affine, moving_grid2world=t1_affine,
|
| 122 |
+
starting_affine=com.affine)
|
| 123 |
+
return rigid.affine
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def _supersampled_affine(ref_affine, factor):
|
| 127 |
+
"""The grid-to-world affine of ``ref``'s grid split ``factor`` ways per axis, each sub-voxel centred within its
|
| 128 |
+
parent voxel (sub-index ``k``'s continuous parent coordinate is ``(k + 0.5) / factor - 0.5``)."""
|
| 129 |
+
c = 0.5 / factor - 0.5
|
| 130 |
+
m = np.eye(4)
|
| 131 |
+
m[0, 0] = m[1, 1] = m[2, 2] = 1.0 / factor
|
| 132 |
+
m[:3, 3] = c
|
| 133 |
+
return ref_affine @ m
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def majority_vote(seg_data, seg_affine, ref_shape, ref_affine, t1_to_ref_affine, factor=4):
|
| 137 |
+
"""The segmentation's majority label per voxel of ``ref``'s grid: every voxel is split into ``factor**3``
|
| 138 |
+
sub-points (sampled through the fitted rigid transform at nearest-neighbour), and the plurality label among them
|
| 139 |
+
is kept. ``0`` where nothing in ``seg_data`` maps there. Returns an ``int32`` array of shape ``ref_shape``."""
|
| 140 |
+
from dipy.align.imaffine import AffineMap
|
| 141 |
+
|
| 142 |
+
if factor < 1:
|
| 143 |
+
raise ValueError(f"factor must be a positive integer, got {factor}")
|
| 144 |
+
sup_shape = tuple(int(s) * factor for s in ref_shape)
|
| 145 |
+
sup_affine = _supersampled_affine(ref_affine, factor)
|
| 146 |
+
amap = AffineMap(t1_to_ref_affine, domain_grid_shape=sup_shape, domain_grid2world=sup_affine,
|
| 147 |
+
codomain_grid_shape=seg_data.shape, codomain_grid2world=seg_affine)
|
| 148 |
+
sup_labels = amap.transform(seg_data.astype(np.int32), interpolation="nearest")
|
| 149 |
+
|
| 150 |
+
X, Y, Z = ref_shape
|
| 151 |
+
blocks = sup_labels.reshape(X, factor, Y, factor, Z, factor)
|
| 152 |
+
blocks = np.transpose(blocks, (0, 2, 4, 1, 3, 5)).reshape(X, Y, Z, factor ** 3)
|
| 153 |
+
|
| 154 |
+
uniq, inverse = np.unique(blocks, return_inverse=True)
|
| 155 |
+
inverse = inverse.reshape(X * Y * Z, factor ** 3)
|
| 156 |
+
counts = np.zeros((X * Y * Z, len(uniq)), dtype=np.int32)
|
| 157 |
+
for k in range(factor ** 3):
|
| 158 |
+
np.add.at(counts, (np.arange(X * Y * Z), inverse[:, k]), 1)
|
| 159 |
+
majority = uniq[counts.argmax(axis=1)].reshape(X, Y, Z)
|
| 160 |
+
return majority.astype(np.int32)
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def labels_and_stop_mask(majority_fs_labels):
|
| 164 |
+
"""``(labels, stop_mask)`` on ``majority_fs_labels``'s grid: ``labels`` is the compact node id (1..84, 0
|
| 165 |
+
elsewhere) of :func:`node_table`; ``stop_mask`` is True on :data:`WM_STOP_LABELS`."""
|
| 166 |
+
nodes = node_table()
|
| 167 |
+
fs_to_node = {n["fs_label"]: n["id"] for n in nodes}
|
| 168 |
+
labels = np.zeros(majority_fs_labels.shape, dtype=np.int16)
|
| 169 |
+
for fs_id, node_id in fs_to_node.items():
|
| 170 |
+
labels[majority_fs_labels == fs_id] = node_id
|
| 171 |
+
stop_mask = np.isin(majority_fs_labels, list(WM_STOP_LABELS))
|
| 172 |
+
return labels, stop_mask
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
def label_volumes_mm3(labels, voxel_volume_mm3):
|
| 176 |
+
"""``{node_id: volume_mm3}`` for every node present in ``labels`` (0 excluded)."""
|
| 177 |
+
vals, counts = np.unique(labels, return_counts=True)
|
| 178 |
+
return {int(v): float(c) * voxel_volume_mm3 for v, c in zip(vals, counts) if v != 0}
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
def build_parcellation(t1_path, synthseg_path, ref_path, out_dir, factor=4):
|
| 182 |
+
"""The CLI's body: register, majority-vote, write ``labels.npy``, ``stop_mask.npy``, ``regions.json`` under
|
| 183 |
+
``out_dir``. Returns ``(labels, stop_mask, regions)`` for a caller (``build_brain_asset.py``) that wants them
|
| 184 |
+
in memory instead of round-tripping through disk."""
|
| 185 |
+
import os
|
| 186 |
+
import nibabel as nib
|
| 187 |
+
|
| 188 |
+
t1_im = nib.load(t1_path)
|
| 189 |
+
seg_im = nib.load(synthseg_path)
|
| 190 |
+
ref_im = nib.load(ref_path)
|
| 191 |
+
if seg_im.shape != t1_im.shape or not np.allclose(seg_im.affine, t1_im.affine, atol=1e-3):
|
| 192 |
+
raise ValueError("the SynthSeg output must be on the T1's own grid (it is by construction unless T1 was "
|
| 193 |
+
"not already at the resolution SynthSeg resamples to internally)")
|
| 194 |
+
|
| 195 |
+
t1_data = np.asarray(t1_im.dataobj, dtype=np.float64)
|
| 196 |
+
ref_data = np.asarray(ref_im.dataobj, dtype=np.float64)
|
| 197 |
+
seg_data = np.asarray(seg_im.dataobj, dtype=np.int32)
|
| 198 |
+
|
| 199 |
+
t1_to_ref = register_t1_to_ref(t1_data, t1_im.affine, ref_data, ref_im.affine)
|
| 200 |
+
majority_fs = majority_vote(seg_data, seg_im.affine, ref_im.shape, ref_im.affine, t1_to_ref, factor=factor)
|
| 201 |
+
labels, stop_mask = labels_and_stop_mask(majority_fs)
|
| 202 |
+
regions = regions_payload()
|
| 203 |
+
|
| 204 |
+
voxel_mm3 = float(np.abs(np.linalg.det(ref_im.affine[:3, :3])))
|
| 205 |
+
volumes = label_volumes_mm3(labels, voxel_mm3)
|
| 206 |
+
n_present = sum(1 for n in regions["regions"] if n["id"] in volumes)
|
| 207 |
+
print(f"{n_present}/84 nodes present on the diffusion grid")
|
| 208 |
+
if volumes:
|
| 209 |
+
v = np.array(list(volumes.values()))
|
| 210 |
+
print(f"per-label volume mm3: min {v.min():.1f}, median {np.median(v):.1f}, max {v.max():.1f}")
|
| 211 |
+
|
| 212 |
+
os.makedirs(out_dir, exist_ok=True)
|
| 213 |
+
np.save(os.path.join(out_dir, "labels.npy"), labels)
|
| 214 |
+
np.save(os.path.join(out_dir, "stop_mask.npy"), stop_mask)
|
| 215 |
+
with open(os.path.join(out_dir, "regions.json"), "w") as f:
|
| 216 |
+
json.dump(regions, f, indent=2)
|
| 217 |
+
return labels, stop_mask, regions
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
def main():
|
| 221 |
+
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
| 222 |
+
ap.add_argument("--t1", required=True, help="the subject's T1 (the grid SynthSeg's output is on)")
|
| 223 |
+
ap.add_argument("--synthseg", required=True, help="SynthSeg --parc --robust's output NIfTI, on the T1 grid")
|
| 224 |
+
ap.add_argument("--ref", required=True, help="a NIfTI defining the diffusion grid (e.g. the mean b=0)")
|
| 225 |
+
ap.add_argument("--out-dir", required=True)
|
| 226 |
+
ap.add_argument("--factor", type=int, default=4, help="sub-points per axis per diffusion voxel for the "
|
| 227 |
+
"majority vote (default 4, i.e. 64 sub-points)")
|
| 228 |
+
a = ap.parse_args()
|
| 229 |
+
build_parcellation(a.t1, a.synthseg, a.ref, a.out_dir, factor=a.factor)
|
| 230 |
+
|
| 231 |
+
|
| 232 |
+
if __name__ == "__main__":
|
| 233 |
+
main()
|
tools/deploy.py
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Deploy this checkout to the Space: the files the image needs (workflows left out), one commit on the Space repo
|
| 2 |
+
naming the source commit; Hugging Face rebuilds the image on that push. With ``--base-tag`` the Space's Dockerfile
|
| 3 |
+
is ``Dockerfile.space`` on the prebuilt ``ghcr.io/dmrai-lab/disco-space:<tag>`` (the image workflow's output), so
|
| 4 |
+
the build copies files instead of installing the stack.
|
| 5 |
+
|
| 6 |
+
HF_TOKEN=... python tools/deploy.py [--space rfick/disco] [--sha <git sha>] [--base-tag <sha|latest>] [--zero] [--config brain.toml]
|
| 7 |
+
|
| 8 |
+
``--config`` names the configuration the Space serves (a file in ``space/``; ``config.toml``, the DiSCo Space, by
|
| 9 |
+
default): the deploy sets the Space variable ``DISCO_CONFIG`` to it (and removes it for the default), and a ZeroGPU
|
| 10 |
+
deployment takes ``README-zero.md`` for the default and ``README-<stem>-zero.md`` for another (``brain.toml`` ->
|
| 11 |
+
``README-brain-zero.md``). ``rfick/brain-zero`` is this repository deployed with ``--zero --config brain.toml``.
|
| 12 |
+
|
| 13 |
+
The Spaces read their data from the Hub at the config's revision when their container starts (disco-space#4: the
|
| 14 |
+
bucket is retired), so the deploy also removes a ``DISCO_MOMENTS`` variable and any mounted volume it finds.
|
| 15 |
+
"""
|
| 16 |
+
import argparse
|
| 17 |
+
import os
|
| 18 |
+
import shutil
|
| 19 |
+
import subprocess
|
| 20 |
+
import tempfile
|
| 21 |
+
|
| 22 |
+
IGNORE = [".git/*", "__pycache__/*", "*.pyc", ".github/*", ".pytest_cache/*", ".gitignore", "gate.json"] # tests and tools go too: the gate job runs on the Space's own files
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def retire_bucket(api, space):
|
| 26 |
+
"""No ``DISCO_MOMENTS`` variable and no volume on ``space``: the app then downloads the layout from the Hub."""
|
| 27 |
+
try:
|
| 28 |
+
api.delete_space_variable(space, "DISCO_MOMENTS")
|
| 29 |
+
print("removed the DISCO_MOMENTS variable")
|
| 30 |
+
except Exception as e: # absent already, or the API says so
|
| 31 |
+
print("DISCO_MOMENTS variable:", repr(e)[:120])
|
| 32 |
+
try:
|
| 33 |
+
api.delete_space_volumes(space)
|
| 34 |
+
print("volumes removed")
|
| 35 |
+
except Exception as e: # "has no attached volumes" is the state we want
|
| 36 |
+
print("no volumes mounted" if "no attached" in str(e) else f"volumes: {e!r}"[:160])
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
DEFAULT_CONFIG = "config.toml"
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def readme_for(config):
|
| 43 |
+
"""The ZeroGPU README of a configuration: ``README-zero.md`` for the default, ``README-<stem>-zero.md`` else."""
|
| 44 |
+
return "README-zero.md" if config == DEFAULT_CONFIG else f"README-{os.path.splitext(config)[0]}-zero.md"
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def set_config(api, space, config):
|
| 48 |
+
"""``DISCO_CONFIG`` on the Space: the configuration's name, absent for the default."""
|
| 49 |
+
if config == DEFAULT_CONFIG:
|
| 50 |
+
try:
|
| 51 |
+
api.delete_space_variable(space, "DISCO_CONFIG")
|
| 52 |
+
print("removed the DISCO_CONFIG variable (the default configuration)")
|
| 53 |
+
except Exception as e: # absent already
|
| 54 |
+
print("DISCO_CONFIG variable:", repr(e)[:120])
|
| 55 |
+
else:
|
| 56 |
+
api.add_space_variable(space, "DISCO_CONFIG", config)
|
| 57 |
+
print(f"DISCO_CONFIG = {config}")
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def main():
|
| 61 |
+
ap = argparse.ArgumentParser()
|
| 62 |
+
ap.add_argument("--space", default=os.environ.get("DISCO_SPACE", "rfick/disco"))
|
| 63 |
+
ap.add_argument("--sha", default=None)
|
| 64 |
+
ap.add_argument("--base-tag", default=None, help="deploy on ghcr.io/dmrai-lab/disco-space:<tag> through Dockerfile.space")
|
| 65 |
+
ap.add_argument("--zero", action="store_true", help="the ZeroGPU (Gradio SDK) deployment: README-zero.md, requirements-zero.txt, app.py")
|
| 66 |
+
ap.add_argument("--config", default=os.environ.get("DISCO_CONFIG", DEFAULT_CONFIG), help="the configuration in space/ the Space serves (DISCO_CONFIG)")
|
| 67 |
+
a = ap.parse_args()
|
| 68 |
+
root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
| 69 |
+
if not os.path.exists(os.path.join(root, "space", a.config)):
|
| 70 |
+
raise SystemExit(f"no configuration space/{a.config}")
|
| 71 |
+
sha = a.sha or subprocess.run(["git", "-C", root, "rev-parse", "HEAD"], capture_output=True, text=True, check=True).stdout.strip()
|
| 72 |
+
from huggingface_hub import HfApi
|
| 73 |
+
api = HfApi(token=os.environ.get("HF_TOKEN") or None)
|
| 74 |
+
folder = root; staged = None
|
| 75 |
+
if a.zero:
|
| 76 |
+
staged = tempfile.mkdtemp(prefix="disco-zero-")
|
| 77 |
+
for name in ("space", "data", "tests", "tools"):
|
| 78 |
+
shutil.copytree(os.path.join(root, name), os.path.join(staged, name), ignore=shutil.ignore_patterns("__pycache__", "*.pyc"))
|
| 79 |
+
for name in ("app.py", "pyproject.toml"):
|
| 80 |
+
shutil.copy(os.path.join(root, name), staged)
|
| 81 |
+
shutil.copy(os.path.join(root, readme_for(a.config)), os.path.join(staged, "README.md"))
|
| 82 |
+
shutil.copy(os.path.join(root, "requirements-zero.txt"), os.path.join(staged, "requirements.txt"))
|
| 83 |
+
folder = staged
|
| 84 |
+
elif a.base_tag:
|
| 85 |
+
staged = tempfile.mkdtemp(prefix="disco-space-")
|
| 86 |
+
for name in ("space", "data", "tests", "tools"):
|
| 87 |
+
shutil.copytree(os.path.join(root, name), os.path.join(staged, name), ignore=shutil.ignore_patterns("__pycache__", "*.pyc"))
|
| 88 |
+
for name in ("README.md", "requirements.txt", "entrypoint.sh", "pyproject.toml"):
|
| 89 |
+
shutil.copy(os.path.join(root, name), staged)
|
| 90 |
+
with open(os.path.join(root, "Dockerfile.space")) as f, open(os.path.join(staged, "Dockerfile"), "w") as g:
|
| 91 |
+
g.write(f.read().replace("BASE_TAG", a.base_tag))
|
| 92 |
+
folder = staged
|
| 93 |
+
info = api.upload_folder(folder_path=folder, repo_id=a.space, repo_type="space", ignore_patterns=IGNORE,
|
| 94 |
+
delete_patterns=["Dockerfile", "Dockerfile.base", "Dockerfile.space", "entrypoint.sh", "README-*zero.md", "requirements-zero.txt"] if a.zero
|
| 95 |
+
else (["Dockerfile.base", "Dockerfile.space"] if a.base_tag else None),
|
| 96 |
+
commit_message=f"disco-space {sha[:12]}" + (f" on base {a.base_tag[:12]}" if a.base_tag else "") + (f", {a.config}" if a.config != DEFAULT_CONFIG else ""))
|
| 97 |
+
if staged:
|
| 98 |
+
shutil.rmtree(staged)
|
| 99 |
+
set_config(api, a.space, a.config)
|
| 100 |
+
retire_bucket(api, a.space)
|
| 101 |
+
print(info.commit_url)
|
| 102 |
+
print("stage", api.get_space_runtime(a.space).stage)
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
if __name__ == "__main__":
|
| 106 |
+
main()
|
tools/gate_job.py
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""The acceptance gate as a Hugging Face Job in the Space's own image (``hf.co/spaces/<space>``: the image Hugging
|
| 2 |
+
Face built from the deployed Dockerfile, tests included), so the gate runs on exactly what is deployed and installs
|
| 3 |
+
nothing but pytest. The job runs ``tests/test_acceptance.py`` and prints ``gate.json``; this script starts it, waits,
|
| 4 |
+
prints its log and exits with the job's outcome. The Space is private, so the container gets the caller's Hub token
|
| 5 |
+
as the job secret ``HF_TOKEN`` (the layout download reads it too).
|
| 6 |
+
|
| 7 |
+
python tools/gate_job.py [--space rfick/disco] [--flavor l4x1] [--timeout 45m]
|
| 8 |
+
"""
|
| 9 |
+
import argparse
|
| 10 |
+
import os
|
| 11 |
+
import sys
|
| 12 |
+
import time
|
| 13 |
+
|
| 14 |
+
SCRIPT = r'''
|
| 15 |
+
set -e
|
| 16 |
+
cd /app
|
| 17 |
+
pip install -q --retries 10 pytest
|
| 18 |
+
python -c "import jax; print('devices', jax.devices())"
|
| 19 |
+
JAX_PLATFORMS=cuda XLA_PYTHON_CLIENT_PREALLOCATE=false XLA_FLAGS=--xla_gpu_deterministic_ops=true HF_HOME=/tmp/hf JAX_COMPILATION_CACHE_DIR=/tmp/jax-cache \
|
| 20 |
+
GATE_OUT=/tmp/gate.json PYTHONPATH=/app pytest tests/test_acceptance.py -s -q -p no:cacheprovider
|
| 21 |
+
echo "=== gate.json"; cat /tmp/gate.json; echo; echo "=== GATE PASSED"
|
| 22 |
+
'''
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def main():
|
| 26 |
+
ap = argparse.ArgumentParser()
|
| 27 |
+
ap.add_argument("--space", default=os.environ.get("DISCO_SPACE", "rfick/disco"))
|
| 28 |
+
ap.add_argument("--flavor", default="l4x1")
|
| 29 |
+
ap.add_argument("--timeout", default="45m")
|
| 30 |
+
a = ap.parse_args()
|
| 31 |
+
from huggingface_hub import HfApi, get_token
|
| 32 |
+
token = os.environ.get("HF_TOKEN") or get_token()
|
| 33 |
+
api = HfApi(token=token)
|
| 34 |
+
rev = api.repo_info(a.space, repo_type="space").sha
|
| 35 |
+
job = api.run_job(image=f"hf.co/spaces/{a.space}", command=["bash", "-c", SCRIPT],
|
| 36 |
+
secrets={"HF_TOKEN": token}, flavor=a.flavor, timeout=a.timeout, name=f"disco-space-gate-{rev[:8]}")
|
| 37 |
+
print(f"job {job.id} on {a.flavor}: the image of {a.space} (repo at {rev})", flush=True)
|
| 38 |
+
t0 = time.time()
|
| 39 |
+
done = api.wait_for_job(job.id, poll_interval=15)
|
| 40 |
+
stage = done.status.stage
|
| 41 |
+
print(f"job {job.id} {stage} after {time.time() - t0:.0f} s", flush=True)
|
| 42 |
+
log = "\n".join(api.fetch_job_logs(job_id=job.id))
|
| 43 |
+
print(log[-20000:])
|
| 44 |
+
ok = stage == "COMPLETED" and "=== GATE PASSED" in log
|
| 45 |
+
print("GATE", "PASSED" if ok else "FAILED", flush=True)
|
| 46 |
+
sys.exit(0 if ok else 1)
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
if __name__ == "__main__":
|
| 50 |
+
main()
|
tools/live.py
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""The live Space through its Gradio API: the configuration's first preset at SNR 30 with the tissue panel's defaults,
|
| 2 |
+
then a custom two-shell protocol on the configuration's first timing class; prints the headline, the timings and the
|
| 3 |
+
seconds the worker spent on the packs' responses the page had not cached and, with ``--stream``, every stage update as it
|
| 4 |
+
arrives; downloads the figures and files to ``$LIVE_OUT``. ``--config`` is the configuration the Space serves
|
| 5 |
+
(``DISCO_CONFIG``: ``config.toml`` for the DiSCo Spaces, ``brain.toml`` for ``rfick/brain-zero``): the inputs are
|
| 6 |
+
built from its source's panel, presets and knobs, not spelled here.
|
| 7 |
+
|
| 8 |
+
python tools/live.py [space] [--config brain.toml] [--stream] [--preset NAME] [--no-ladder] [--knob CHOICE]
|
| 9 |
+
"""
|
| 10 |
+
import argparse
|
| 11 |
+
import os
|
| 12 |
+
import sys
|
| 13 |
+
import time
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def main():
|
| 17 |
+
ap = argparse.ArgumentParser()
|
| 18 |
+
ap.add_argument("space", nargs="?", default="rfick/disco")
|
| 19 |
+
ap.add_argument("--config", default=os.environ.get("DISCO_CONFIG", "config.toml"), help="the configuration in space/ the Space serves")
|
| 20 |
+
ap.add_argument("--stream", action="store_true", help="print every stage update as it arrives")
|
| 21 |
+
ap.add_argument("--preset", action="append", help="an acquisition to run (default: the first preset, then custom shells)")
|
| 22 |
+
ap.add_argument("--no-ladder", action="store_true", help="skip the explorer's tier ladder (the shortest GPU reservation)")
|
| 23 |
+
ap.add_argument("--knob", default=None, help="B: the same run with this knob changed (a choice of the page's dropdown)")
|
| 24 |
+
a = ap.parse_args()
|
| 25 |
+
os.environ["DISCO_CONFIG"] = a.config # before the page module reads its configuration
|
| 26 |
+
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
| 27 |
+
from gradio_client import Client
|
| 28 |
+
from huggingface_hub import get_token
|
| 29 |
+
from space import app as A, pipeline as P, sources
|
| 30 |
+
|
| 31 |
+
cfg = P.config()
|
| 32 |
+
S = sources.source_class(cfg)
|
| 33 |
+
panel = S.panel(cfg)
|
| 34 |
+
defaults = {c.name: c.value for row in panel.rows for c in row}
|
| 35 |
+
tc = S.tracking_controls(cfg)
|
| 36 |
+
shapes = list(S.shapes_of(cfg))
|
| 37 |
+
physics = [defaults[name] for name in panel.fields]
|
| 38 |
+
|
| 39 |
+
def inputs(preset, *, knob, n_keys=1, ladder=True):
|
| 40 |
+
shells = [True, shapes[0], 1000, 30, 12.0, 24.0, 53.5, True, shapes[0], 3000, 45, 8.0, 20.0, 53.5,
|
| 41 |
+
False, shapes[0], 3000, 90, 17.0, 30.0, 53.5, False, shapes[0], 6000, 60, 17.0, 30.0, 53.5]
|
| 42 |
+
return [preset, 2, True, 30, tc["density"][2], tc["max_angle"][2], tc["step"][2], 0, None, knob, A.IDEAL, n_keys, ladder, *physics, *shells]
|
| 43 |
+
|
| 44 |
+
c = Client(a.space, token=get_token(), verbose=False, download_files=os.environ.get("LIVE_OUT", "/tmp/disco-live"), httpx_kwargs={"timeout": 900})
|
| 45 |
+
for preset in a.preset or (S.presets(cfg)[0], A.CUSTOM):
|
| 46 |
+
t0 = time.perf_counter()
|
| 47 |
+
args = inputs(preset, knob=a.knob or A.NO_KNOB, ladder=not a.no_ladder)
|
| 48 |
+
print(f"{preset}: the client's own estimate {A.estimated_seconds(*args)} s (the page's cache is not known here; the Space prices "
|
| 49 |
+
f"the responses it has not cached on top)", flush=True)
|
| 50 |
+
job = c.submit(*args, api_name="/run_pipeline")
|
| 51 |
+
seen = 0
|
| 52 |
+
while a.stream and not job.done():
|
| 53 |
+
outs = job.outputs()
|
| 54 |
+
for o in outs[seen:]:
|
| 55 |
+
print(f" +{time.perf_counter() - t0:5.1f} s: {str(o[1])[:100]}", flush=True)
|
| 56 |
+
seen = len(outs)
|
| 57 |
+
time.sleep(1)
|
| 58 |
+
out = job.result()
|
| 59 |
+
print(f"{preset}: {time.perf_counter() - t0:.1f} s wall; result received at unix {time.time():.1f}", flush=True)
|
| 60 |
+
named = dict(zip([n for n in A.OUTPUTS if n not in ("result", "b_row")], out)) # the API returns neither the gr.State nor the gr.Row
|
| 61 |
+
print(named["headline"]); print(named["timings"])
|
| 62 |
+
rows = named["timings"]["data"] if isinstance(named["timings"], dict) else named["timings"]
|
| 63 |
+
responses = [r[1] for r in rows if r[0] == A.RESPONSES_ROW]
|
| 64 |
+
print(f"the packs' responses on the worker: {responses[0] if responses else 'none (the source prepares nothing)'} s", flush=True)
|
| 65 |
+
print("tck", named["tck"], "volumes", named["volumes"], flush=True)
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
if __name__ == "__main__":
|
| 69 |
+
main()
|
tools/measure_brain.py
ADDED
|
@@ -0,0 +1,184 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""The brain source's costs, measured: the packs' pose responses (JAX on the CPU, as in the page's process and the
|
| 2 |
+
GPU worker of a ZeroGPU Space) and every device stage of a run (the contraction, the noise, the reconstruction, the
|
| 3 |
+
tracking and the truth's tracking at density 1, 2 and 4, the scoring, the ladder), first call and steady, the
|
| 4 |
+
streamline counts, the truth connectome's reproducibility at one key and its spread over keys (the score's floor),
|
| 5 |
+
and the size of the payload that crosses from the GPU worker to the page. Writes a JSON the ``[budget]`` of
|
| 6 |
+
``space/brain.toml`` is refit from.
|
| 7 |
+
|
| 8 |
+
DISCO_RECONSTRUCTION=tournier07 python tools/measure_brain.py --asset DIR --wm-pack WM.rpk --gm-pack GM.rpk [--out brain_costs.json]
|
| 9 |
+
|
| 10 |
+
With ``--saves WM1.rpk,WM2.rpk,...`` it measures only the responses' cost by the WM pack's saves spanned (the
|
| 11 |
+
``per_save`` of ``[budget]``'s ``response_*``): per WM pack, in a fresh interpreter (nothing compiled), ``prepare`` of
|
| 12 |
+
one protocol (``--saves-protocol``: a manifest.json whose protocol rows are played, else the asset's own; retimed to
|
| 13 |
+
``--saves-class``, the scan's own class by default) cold, warm and with the field tier off, beside the saves the class spans on that pack; and the
|
| 14 |
+
least-squares slope of the seconds over the saves per state.
|
| 15 |
+
|
| 16 |
+
python tools/measure_brain.py --asset DIR --gm-pack GM.rpk --saves A.rpk,B.rpk [--saves-protocol manifest.json] [--saves-class scan]
|
| 17 |
+
"""
|
| 18 |
+
import argparse
|
| 19 |
+
import json
|
| 20 |
+
import os
|
| 21 |
+
import pickle
|
| 22 |
+
import sys
|
| 23 |
+
import time
|
| 24 |
+
from dataclasses import replace
|
| 25 |
+
|
| 26 |
+
import numpy as np
|
| 27 |
+
|
| 28 |
+
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
| 29 |
+
from space import pipeline as P # noqa: E402
|
| 30 |
+
from space.sources import brain as B # noqa: E402
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def sync():
|
| 34 |
+
import torch
|
| 35 |
+
if torch.cuda.is_available():
|
| 36 |
+
torch.cuda.synchronize()
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def five_shells():
|
| 40 |
+
"""MASiVar's shape: b = 1000 / 1500 / 2000 / 2500 / 3000 x 96 directions and 15 b = 0, on the scan's timing."""
|
| 41 |
+
return P.Protocol(tuple(P.Shell(B.SCAN, b, 96) for b in (1000, 1500, 2000, 2500, 3000)), n_b0=15, name="five shells x 96")
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def saves_one(asset, wm_pack, gm_pack, protocol_manifest, shape):
|
| 45 |
+
"""``prepare``'s seconds cold (the first call), warm (the same band at another tissue) and with the field tier off
|
| 46 |
+
(each the faster of two calls), on one WM pack in this process, with the saves the protocol's class spans on it."""
|
| 47 |
+
cfg = P.config(os.path.join(P.HERE, "brain.toml"))
|
| 48 |
+
cfg["asset"] = {"local": asset}
|
| 49 |
+
cfg["packs"] = {"wm": [{"label": "wm", "uri": wm_pack}], "gm": [{"label": "gm", "uri": gm_pack}]}
|
| 50 |
+
src = B.Brain(cfg)
|
| 51 |
+
panel = B.Brain.panel(cfg)
|
| 52 |
+
v = {c.name: c.value for row in panel.rows for c in row if c.name in panel.fields}
|
| 53 |
+
v.update(wm_pack="wm", gm_pack="gm")
|
| 54 |
+
ph = B.Brain.physics_from(cfg, v)
|
| 55 |
+
if protocol_manifest:
|
| 56 |
+
with open(protocol_manifest) as f:
|
| 57 |
+
prot = B.scan_protocol(json.load(f), name="the manifest's protocol")
|
| 58 |
+
else:
|
| 59 |
+
prot = B.Brain.protocol(cfg, B.Brain.presets(cfg)[0])
|
| 60 |
+
prot = P.retime(prot, shape)
|
| 61 |
+
meas = src.validate(prot, ph)
|
| 62 |
+
seg = src.segments("wm", "wm")
|
| 63 |
+
saves = B.Brain.saves_spanned(seg, src.windows_needed("wm", "wm", meas))
|
| 64 |
+
seconds = {}
|
| 65 |
+
other = lambda f: replace(ph, T2={**ph.T2, "gm": ph.T2["gm"] * f}) # the same band at another tissue
|
| 66 |
+
for state, physics in (("cold", [ph]), ("warm", [other(1.0001), other(1.0002)]), ("no_field", [replace(ph, field=False), replace(other(1.0001), field=False)])):
|
| 67 |
+
times = []
|
| 68 |
+
for phys in physics:
|
| 69 |
+
t = time.perf_counter(); src.prepare(meas, phys); times.append(time.perf_counter() - t)
|
| 70 |
+
seconds[state] = min(times)
|
| 71 |
+
pk = src.packs[("wm", "wm")]
|
| 72 |
+
return dict(pack=wm_pack, id=pk.meta.get("id"), n_walkers=int(pk.n_walkers), K=int(pk.K), segments=seg, saves=saves,
|
| 73 |
+
n_meas=int(len(meas.bvals)), shape=shape, seconds=seconds)
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def measure_saves(a):
|
| 77 |
+
""":func:`saves_one` per WM pack of ``--saves``, each in a fresh interpreter, and the slope of the seconds over the
|
| 78 |
+
saves per state (least squares with an intercept)."""
|
| 79 |
+
import multiprocessing as mp
|
| 80 |
+
rows = []
|
| 81 |
+
for pack in a.saves.split(","):
|
| 82 |
+
with mp.get_context("spawn").Pool(1) as pool:
|
| 83 |
+
row = pool.apply(saves_one, (a.asset, pack, a.gm_pack, a.saves_protocol, a.saves_class))
|
| 84 |
+
rows.append(row)
|
| 85 |
+
print(json.dumps(row), flush=True)
|
| 86 |
+
x = np.array([r["saves"] for r in rows], float)
|
| 87 |
+
fit = {}
|
| 88 |
+
for state in ("cold", "warm", "no_field"):
|
| 89 |
+
y = np.array([r["seconds"][state] for r in rows])
|
| 90 |
+
slope, icpt = np.polyfit(x, y, 1) if len(rows) > 1 else (float("nan"), float("nan"))
|
| 91 |
+
fit[state] = dict(per_save=float(slope), intercept=float(icpt))
|
| 92 |
+
out = dict(cpu_threads=os.environ.get("OMP_NUM_THREADS"), rows=rows, fit=fit)
|
| 93 |
+
print(json.dumps(fit), flush=True)
|
| 94 |
+
with open(a.out, "w") as f:
|
| 95 |
+
json.dump(out, f, indent=1, default=float)
|
| 96 |
+
print("wrote", a.out)
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def main():
|
| 100 |
+
ap = argparse.ArgumentParser()
|
| 101 |
+
ap.add_argument("--asset", required=True)
|
| 102 |
+
ap.add_argument("--wm-pack")
|
| 103 |
+
ap.add_argument("--gm-pack", required=True)
|
| 104 |
+
ap.add_argument("--out", default="brain_costs.json")
|
| 105 |
+
ap.add_argument("--densities", default="1,2,4")
|
| 106 |
+
ap.add_argument("--saves", default=None, help="WM packs, comma-separated: measure the responses' cost by the saves spanned only")
|
| 107 |
+
ap.add_argument("--saves-protocol", default=None, help="a manifest.json whose protocol the saves measurement plays")
|
| 108 |
+
ap.add_argument("--saves-class", default=B.SCAN, help="the timing class the saves measurement plays it on")
|
| 109 |
+
a = ap.parse_args()
|
| 110 |
+
if a.saves:
|
| 111 |
+
return measure_saves(a)
|
| 112 |
+
if not a.wm_pack:
|
| 113 |
+
ap.error("--wm-pack is required (or --saves)")
|
| 114 |
+
cfg = P.config(os.path.join(P.HERE, "brain.toml"))
|
| 115 |
+
cfg["asset"] = {"local": a.asset}
|
| 116 |
+
cfg["packs"] = {"wm": [{"label": "wm", "uri": a.wm_pack}], "gm": [{"label": "gm", "uri": a.gm_pack}]}
|
| 117 |
+
import torch
|
| 118 |
+
out = dict(device=torch.cuda.get_device_name(0) if torch.cuda.is_available() else "cpu", reconstruction=P.reconstruction(cfg), backend=P.backend(cfg))
|
| 119 |
+
t0 = time.perf_counter(); src = B.Brain(cfg); out["load_seconds"] = time.perf_counter() - t0
|
| 120 |
+
out["voxels"] = int(src.mask.sum()); out["wm_voxels"] = int(src.asset.stop.sum()); out["grid"] = list(src.mask.shape)
|
| 121 |
+
panel = B.Brain.panel(cfg)
|
| 122 |
+
v = {c.name: c.value for row in panel.rows for c in row if c.name in panel.fields}
|
| 123 |
+
v.update(wm_pack="wm", gm_pack="gm")
|
| 124 |
+
ph = B.Brain.physics_from(cfg, v)
|
| 125 |
+
protocols = {"scan": B.Brain.protocol(cfg, B.Brain.presets(cfg)[0]), "five shells x 96": five_shells()}
|
| 126 |
+
host = {}
|
| 127 |
+
for name, prot in protocols.items():
|
| 128 |
+
meas = src.validate(prot, ph)
|
| 129 |
+
rows = {}
|
| 130 |
+
for label, phys in [("every tier (cold)", ph), ("every tier (warm)", replace(ph, T2={**ph.T2, "gm": ph.T2["gm"] * 1.0001}))] + \
|
| 131 |
+
[(f"rung: {l}", r) for l, r in src.ladder_steps(ph)]:
|
| 132 |
+
t = time.perf_counter(); src.prepare(meas, phys); rows[label] = time.perf_counter() - t
|
| 133 |
+
host[name] = dict(n_meas=prot.n_meas, seconds=rows)
|
| 134 |
+
print(name, json.dumps(host[name]), flush=True)
|
| 135 |
+
out["host_prepare"] = host
|
| 136 |
+
device = {}
|
| 137 |
+
for name, prot in protocols.items():
|
| 138 |
+
meas = src.validate(prot, ph)
|
| 139 |
+
k = src.cached(meas, ph)
|
| 140 |
+
rec = dict(n_meas=prot.n_meas)
|
| 141 |
+
for rep in ("first", "steady"):
|
| 142 |
+
sync(); t = time.perf_counter(); dwi, floor, fac, _ = src.replay(meas, ph, k); sync(); rec[f"replay_{rep}"] = time.perf_counter() - t
|
| 143 |
+
t = time.perf_counter(); noisy = P.add_noise(dwi, 30.0, fac, seed=0, backend="torch"); rec["noise"] = time.perf_counter() - t
|
| 144 |
+
signal = np.isfinite(dwi[..., 0])
|
| 145 |
+
for rep in ("first", "steady"):
|
| 146 |
+
sync(); t = time.perf_counter(); sh, secs, extras = src.reconstruct(noisy, fac, meas, signal); sync(); rec[f"reconstruct_{rep}"] = time.perf_counter() - t
|
| 147 |
+
rec["reconstruct_rows"] = secs
|
| 148 |
+
rec["roundtrip"] = extras["roundtrip"]
|
| 149 |
+
ladder = [src.cached(meas, r) for _, r in src.ladder_steps(ph)]
|
| 150 |
+
sync(); t = time.perf_counter(); src.ladder(meas, ph, ladder); sync(); rec["ladder"] = time.perf_counter() - t
|
| 151 |
+
t = time.perf_counter(); src.ingredients(meas, ph, k); rec["ingredients"] = time.perf_counter() - t
|
| 152 |
+
tracks = {}
|
| 153 |
+
for d in [int(x) for x in a.densities.split(",")]:
|
| 154 |
+
tr = B.Brain.tracking(cfg, density=d, max_angle=cfg["tracking"]["max_angle"], step=cfg["tracking"]["step_mm"], key=0)
|
| 155 |
+
fld, seeds = src.tracking_inputs(sh, d)
|
| 156 |
+
row = dict(seeds=int(len(seeds)))
|
| 157 |
+
for rep in ("first", "steady"):
|
| 158 |
+
sync(); t = time.perf_counter(); tg, _ = P.track(fld, seeds, tr, src.backend); sync(); row[f"track_{rep}"] = time.perf_counter() - t
|
| 159 |
+
row["streamlines"] = len(tg); row["points"] = int(tg.n_points.sum())
|
| 160 |
+
src._reference.clear()
|
| 161 |
+
sync(); t = time.perf_counter(); ref, _ = src.reference(tr, seeds); sync(); row["truth"] = time.perf_counter() - t
|
| 162 |
+
t = time.perf_counter(); M = src.regions.matrix(tg); s = src.score(M, ref); row["score_seconds"] = time.perf_counter() - t
|
| 163 |
+
row["score"] = s; row["truth_streamlines"] = ref["streamlines"]
|
| 164 |
+
src._reference.clear(); again, _ = src.reference(tr, seeds)
|
| 165 |
+
row["truth_bit_for_bit"] = bool(np.array_equal(again["matrix"], ref["matrix"]))
|
| 166 |
+
src._reference.clear(); other, _ = src.reference(replace(tr, key=1), seeds)
|
| 167 |
+
pairs = src.regions.pairs
|
| 168 |
+
row["truth_key0_vs_key1_pearson_log"] = P.pearson(np.log1p(ref["matrix"][pairs]), np.log1p(other["matrix"][pairs]))
|
| 169 |
+
src._reference.clear()
|
| 170 |
+
tracks[d] = row
|
| 171 |
+
print(name, d, json.dumps({k_: v_ for k_, v_ in row.items() if k_ != "score"}), json.dumps(s), flush=True)
|
| 172 |
+
rec["tracking"] = tracks
|
| 173 |
+
res = P.Result(prot, meas, noisy.astype(np.float32), floor, fac, sh, tg, seeds, M, s, clean=dwi.astype(np.float32), extras=extras)
|
| 174 |
+
t = time.perf_counter(); blob = pickle.dumps(res, protocol=pickle.HIGHEST_PROTOCOL); rec["payload_mb"] = len(blob) / 1e6; rec["pickle_seconds"] = time.perf_counter() - t
|
| 175 |
+
device[name] = rec
|
| 176 |
+
print(name, json.dumps({k_: v_ for k_, v_ in rec.items() if k_ not in ("tracking", "roundtrip")}), flush=True)
|
| 177 |
+
out["device"] = device
|
| 178 |
+
with open(a.out, "w") as f:
|
| 179 |
+
json.dump(out, f, indent=1, default=float)
|
| 180 |
+
print("wrote", a.out)
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
if __name__ == "__main__":
|
| 184 |
+
main()
|
tools/measure_scanners.py
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""What a machine of the scanner menu costs on the brain: the scan's own protocol at the default panel on the ideal
|
| 2 |
+
scanner and on each machine of ``brain.toml``'s menu -- the encoding classes, the packs' pose responses (``prepare``,
|
| 3 |
+
JAX on the CPU as in the page's process and the GPU worker) and the contraction on the device (``replay``, first call
|
| 4 |
+
and steady) -- and the delivered image's departure from the ideal one. Writes a JSON (docs/scanner.md quotes it).
|
| 5 |
+
|
| 6 |
+
python tools/measure_scanners.py --asset DIR --wm-pack WM.rpk --gm-pack GM.rpk [--out brain_scanners.json]
|
| 7 |
+
"""
|
| 8 |
+
import argparse
|
| 9 |
+
import json
|
| 10 |
+
import os
|
| 11 |
+
import sys
|
| 12 |
+
import time
|
| 13 |
+
|
| 14 |
+
import numpy as np
|
| 15 |
+
|
| 16 |
+
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
| 17 |
+
from space import pipeline as P # noqa: E402
|
| 18 |
+
from space.sources import brain as B # noqa: E402
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def sync():
|
| 22 |
+
import torch
|
| 23 |
+
if torch.cuda.is_available():
|
| 24 |
+
torch.cuda.synchronize()
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def main():
|
| 28 |
+
ap = argparse.ArgumentParser()
|
| 29 |
+
ap.add_argument("--asset", required=True)
|
| 30 |
+
ap.add_argument("--wm-pack", required=True)
|
| 31 |
+
ap.add_argument("--gm-pack", required=True)
|
| 32 |
+
ap.add_argument("--out", default="brain_scanners.json")
|
| 33 |
+
a = ap.parse_args()
|
| 34 |
+
cfg = P.config(os.path.join(P.HERE, "brain.toml"))
|
| 35 |
+
cfg["asset"] = {"local": a.asset}
|
| 36 |
+
cfg["packs"] = {"wm": [{"label": "wm", "uri": a.wm_pack}], "gm": [{"label": "gm", "uri": a.gm_pack}]}
|
| 37 |
+
src = B.Brain(cfg)
|
| 38 |
+
panel = B.Brain.panel(cfg)
|
| 39 |
+
v = {c.name: c.value for row in panel.rows for c in row if c.name in panel.fields}
|
| 40 |
+
v.update(wm_pack="wm", gm_pack="gm")
|
| 41 |
+
prot = B.Brain.protocol(cfg, B.Brain.presets(cfg)[0])
|
| 42 |
+
out = {}
|
| 43 |
+
|
| 44 |
+
def measure(ph):
|
| 45 |
+
meas = src.validate(prot, ph)
|
| 46 |
+
t0 = time.perf_counter(); n_cls = src.n_classes(meas, ph); t_cls = time.perf_counter() - t0
|
| 47 |
+
t0 = time.perf_counter(); k = src.prepare(meas, ph); t_prep = time.perf_counter() - t0
|
| 48 |
+
secs = []
|
| 49 |
+
for _ in range(2):
|
| 50 |
+
sync(); t0 = time.perf_counter(); dwi, _, factor, _ = src.replay(meas, ph, k); sync(); secs.append(time.perf_counter() - t0)
|
| 51 |
+
row = dict(scanner=ph.scanner, field_T=ph.field_T, n_meas=int(len(meas.bvals)), encoding_classes=int(n_cls), classes_seconds=t_cls,
|
| 52 |
+
prepare_seconds=t_prep, prepare_stages=k.stages, replay_first=secs[0], replay_steady=secs[1])
|
| 53 |
+
return row, dwi * factor[..., None]
|
| 54 |
+
|
| 55 |
+
for label, key in P.machines(cfg).items():
|
| 56 |
+
L = P.limits(key)
|
| 57 |
+
on = B.Brain.physics_from(cfg, v, scanner=key)
|
| 58 |
+
priced = src.responses([(src.validate(prot, on), on)]) # before prepare caches it
|
| 59 |
+
ideal, S0 = measure(B.Brain.physics_from(cfg, dict(v, field_T=float(L.field_T), b0_mode=list(B.B0_MODES)[0])))
|
| 60 |
+
row, S = measure(on)
|
| 61 |
+
both = np.isfinite(S0) & np.isfinite(S)
|
| 62 |
+
d = np.abs(S - S0)[both]
|
| 63 |
+
row.update(ideal_at_its_field=ideal, max_abs_dS=float(d.max()), median_abs_dS=float(np.median(d)), priced=priced,
|
| 64 |
+
reserved=B.Brain.estimated_seconds(cfg, prot, density=cfg["tracking"]["density"], knob=P.NO_KNOB, n_keys=1, ladder=True,
|
| 65 |
+
responses=priced, scanner=key))
|
| 66 |
+
out[label] = row
|
| 67 |
+
print(label, json.dumps(row, indent=1, default=str), flush=True)
|
| 68 |
+
with open(a.out, "w") as f:
|
| 69 |
+
json.dump(out, f, indent=1, default=str)
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
if __name__ == "__main__":
|
| 73 |
+
main()
|
tools/scanner_brain_bmap.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""The b each brain voxel is delivered on the scan's b = 1000 shell (96 directions, δ 25 / Δ 55 ms, TE 100 ms,
|
| 2 |
+
square pulses) by each machine, the head centre at isocentre: b = gamma^2 int (int eps g)^2 with the delivered
|
| 3 |
+
waveform eps(t) [s(t) q_v,i + g0_v] (bore.delivered_moments), whose three time integrals are taken once.
|
| 4 |
+
|
| 5 |
+
ASSET=/asset/dir python tools/scanner_brain_bmap.py
|
| 6 |
+
"""
|
| 7 |
+
import json, os, sys
|
| 8 |
+
import numpy as np
|
| 9 |
+
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
| 10 |
+
import dmipy_sim as d
|
| 11 |
+
from dmipy_sim.constants import GAMMA
|
| 12 |
+
from dmipy_sim.phantom.bore import delivered_moments
|
| 13 |
+
from space import pipeline as P
|
| 14 |
+
from space.sources import brain as B
|
| 15 |
+
cfg = P.config(os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "space", "brain.toml")); cfg["asset"] = {"local": os.environ["ASSET"]}
|
| 16 |
+
cfg["packs"] = {"wm": [{"label": "w", "uri": "x"}], "gm": [{"label": "g", "uri": "y"}]}
|
| 17 |
+
br = B.Brain(cfg)
|
| 18 |
+
grid, idx = br.bore_grid
|
| 19 |
+
t = B.Brain.shape_table(cfg, os.environ["ASSET"])["scan"]
|
| 20 |
+
prot = B.scan_protocol(br.asset.manifest, name="scan"); meas = P.measurements(prot, br.shapes)
|
| 21 |
+
rows = np.flatnonzero(np.round(meas.bvals) == 1000)
|
| 22 |
+
u = meas.dirs[rows] # image frame = the bore grid's frame
|
| 23 |
+
seq = d.pgse([[0.0, 0.0, 1.0]], t["delta"], t["Delta"], bvalues=[1e9], TE=t["TE"], n_t=2000, slew_rate=np.inf)
|
| 24 |
+
g = float(np.abs(np.asarray(seq.G)).max()); s = np.asarray(seq.G)[0, :, 2] / g
|
| 25 |
+
sgn = seq.rf.sign(np.arange(seq.n_t) * seq.dt)
|
| 26 |
+
Fs = np.cumsum(sgn * s) * seq.dt; F0 = np.cumsum(sgn) * seq.dt
|
| 27 |
+
I = {k: GAMMA ** 2 * np.sum(a * b_) * seq.dt for k, (a, b_) in dict(ss=(Fs, Fs), s0=(Fs, F0), oo=(F0, F0)).items()}
|
| 28 |
+
b_nom = g ** 2 * I["ss"]
|
| 29 |
+
out = {}
|
| 30 |
+
maps = {}
|
| 31 |
+
for key in ("hyperfine_swoop_64mT", "siemens_magnetom_prisma_3T", "siemens_magnetom_terra_7T"):
|
| 32 |
+
L = P.limits(key)
|
| 33 |
+
radius = L.b0_validity_radius or L.gnl_validity_radius or 1.0
|
| 34 |
+
r = np.linalg.norm(grid.offset_m(idx), axis=1)
|
| 35 |
+
inside = r <= radius
|
| 36 |
+
q_all = np.full((len(idx), len(rows), 3), np.nan); g0_all = np.zeros((len(idx), 3))
|
| 37 |
+
dm = delivered_moments(L, grid, s, np.full(len(rows), g), u, voxels=idx[inside], transmit=True)
|
| 38 |
+
q_all[inside] = dm.q
|
| 39 |
+
if dm.g0 is not None:
|
| 40 |
+
g0_all[inside] = dm.g0
|
| 41 |
+
bq = np.einsum("vmi,vmi->vm", q_all, q_all) * I["ss"] + 2 * np.einsum("vmi,vi->vm", q_all, g0_all) * I["s0"] + (g0_all ** 2).sum(1)[:, None] * I["oo"]
|
| 42 |
+
frac = bq / b_nom
|
| 43 |
+
mean = np.nanmean(frac, 1)
|
| 44 |
+
vol = np.full(br.mask.shape, np.nan); vol[tuple(br.vox.T)] = mean
|
| 45 |
+
maps[key] = vol
|
| 46 |
+
kap = np.full(len(idx), np.nan)
|
| 47 |
+
if dm.kappa is not None:
|
| 48 |
+
kap[inside] = dm.kappa
|
| 49 |
+
out[key] = dict(voxels=int(len(idx)), inside_anchor=int(inside.sum()), anchor_cm=radius * 100,
|
| 50 |
+
direction_mean_b_fraction=dict(median=float(np.nanmedian(mean)), p01=float(np.nanquantile(mean, 0.01)), p99=float(np.nanquantile(mean, 0.99)),
|
| 51 |
+
min=float(np.nanmin(mean)), max=float(np.nanmax(mean))),
|
| 52 |
+
per_direction_b_fraction=dict(p01=float(np.nanquantile(frac, 0.01)), p99=float(np.nanquantile(frac, 0.99)),
|
| 53 |
+
min=float(np.nanmin(frac)), max=float(np.nanmax(frac))),
|
| 54 |
+
direction_spread_median=float(np.nanmedian(np.nanmax(frac, 1) - np.nanmin(frac, 1))),
|
| 55 |
+
voxels_off_by_more_than_5pc=float(np.nanmean(np.abs(mean - 1) > 0.05)),
|
| 56 |
+
transmit_scale=None if dm.kappa is None else dict(median=float(np.nanmedian(kap)), min=float(np.nanmin(kap)), max=float(np.nanmax(kap))),
|
| 57 |
+
G_needed_mT_m=g * 1e3, G_max_mT_m=float(L.G_max) * 1e3)
|
| 58 |
+
print(key, json.dumps(out[key], indent=1), flush=True)
|
| 59 |
+
np.savez_compressed("brain_bmap.npz", **{k: v for k, v in maps.items()}, affine=br.affine)
|
| 60 |
+
json.dump(out, open("brain_bmap.json", "w"), indent=1)
|
tools/scanner_disco_effects.py
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Effect sizes on the DiSCo page: each machine at 7.9 cm from isocentre (along R-L) against the same run on the
|
| 2 |
+
ideal scanner at the machine's field and direction (so only the delivered gradient and the transmit scale differ),
|
| 3 |
+
noiseless, the layout replayed on the CPU. Per machine: a protocol it can play on the layout's TE 53.5 ms classes.
|
| 4 |
+
|
| 5 |
+
LAYOUT=/stamped/layout python tools/scanner_disco_effects.py # [DIST_CM=7.9 AXIS='R-L (x)' DENSITY=4 ONLY=swoop OUT=...]
|
| 6 |
+
"""
|
| 7 |
+
import json, os, sys, time
|
| 8 |
+
from dataclasses import replace
|
| 9 |
+
import numpy as np
|
| 10 |
+
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
| 11 |
+
from space import pipeline as P
|
| 12 |
+
from space.sources import disco as D
|
| 13 |
+
LAYOUT = os.environ["LAYOUT"]
|
| 14 |
+
cfg = P.config()
|
| 15 |
+
keep = ["d12-D24", "d17-D30", "d17.7-D35.8", "d10.2-D16.7"]
|
| 16 |
+
cfg["shapes"] = {k: cfg["shapes"][k] for k in keep}
|
| 17 |
+
src = D.Layout(cfg, local=LAYOUT)
|
| 18 |
+
src.backend = "jax"
|
| 19 |
+
axis = np.array(D.OFFSET_AXES[os.environ.get("AXIS", "R-L (x)")])
|
| 20 |
+
dist = float(os.environ.get("DIST_CM", "7.9")) * 1e-2
|
| 21 |
+
tracking = D.Disco.tracking(cfg, density=int(os.environ.get("DENSITY", "4")), max_angle=cfg["tracking"]["max_angle"], step=cfg["tracking"]["step_mm"], key=0)
|
| 22 |
+
runs = [("hyperfine_swoop_64mT", P.Protocol((P.Shell("d17.7-D35.8", 350.0, 60),), n_b0=3, name="Swoop-playable: b 350 x 60 on d17.7-D35.8")),
|
| 23 |
+
("siemens_magnetom_prisma_3T", D.Disco.protocol(cfg, "research 3-shell x 90")),
|
| 24 |
+
("siemens_magnetom_terra_7T", D.Disco.protocol(cfg, "research 3-shell x 90"))]
|
| 25 |
+
only = os.environ.get("ONLY")
|
| 26 |
+
out = {}
|
| 27 |
+
for key, prot in runs:
|
| 28 |
+
if only and only not in key:
|
| 29 |
+
continue
|
| 30 |
+
L = P.limits(key)
|
| 31 |
+
assert all(r[-1] for r in P.playable(prot, cfg["shapes"], key)), (key, P.playable(prot, cfg["shapes"], key))
|
| 32 |
+
A = P.Physics.at(float(L.field_T), pools=D.pools(cfg), b0_direction=tuple(L.b0_axis or (0, 0, 1)))
|
| 33 |
+
B = replace(A, scanner=key, offset_m=tuple(dist * axis))
|
| 34 |
+
meas = src.validate(prot, B)
|
| 35 |
+
t0 = time.perf_counter(); ra = P.run(src, prot, tracking=tracking, physics=A); ta = time.perf_counter() - t0
|
| 36 |
+
t0 = time.perf_counter(); rb = P.run(src, prot, tracking=tracking, physics=B); tb = time.perf_counter() - t0
|
| 37 |
+
m = np.isfinite(ra.dwi[..., 0]) & src.mask
|
| 38 |
+
shells = {}
|
| 39 |
+
for b in sorted(set(np.round(meas.bvals[~meas.b0]))):
|
| 40 |
+
rows = np.flatnonzero(np.round(meas.bvals) == b)
|
| 41 |
+
a = ra.dwi[m][:, rows].mean(1); bb = rb.dwi[m][:, rows].mean(1)
|
| 42 |
+
rel = (bb - a) / a
|
| 43 |
+
shells[str(b)] = dict(mean_A=float(np.mean(a)), mean_B=float(np.mean(bb)), rel_median=float(np.median(rel)), rel_p01=float(np.quantile(rel, 0.01)),
|
| 44 |
+
rel_p99=float(np.quantile(rel, 0.99)), abs_dwi_median=float(np.median(np.abs(rb.dwi[m][:, rows] - ra.dwi[m][:, rows]))),
|
| 45 |
+
abs_dwi_p99=float(np.quantile(np.abs(rb.dwi[m][:, rows] - ra.dwi[m][:, rows]), 0.99)))
|
| 46 |
+
s0 = rb.s0_factor[m] / ra.s0_factor[m]
|
| 47 |
+
out[key] = dict(protocol=prot.name, n_meas=int(len(meas.bvals)), offset_m=list(B.offset_m), field_T=float(L.field_T),
|
| 48 |
+
pearson_count=dict(ideal=ra.score["pearson_count"], machine=rb.score["pearson_count"]),
|
| 49 |
+
pearson_area=dict(ideal=ra.score["pearson_area"], machine=rb.score["pearson_area"]),
|
| 50 |
+
streamlines=dict(ideal=len(ra.tractogram), machine=len(rb.tractogram)), shells=shells,
|
| 51 |
+
s0_ratio_median=float(np.median(s0)), floor_median=float(np.nanmedian(rb.floor[m])),
|
| 52 |
+
seconds=dict(ideal=ta, machine=tb, replay_ideal=ra.seconds["replay"], replay_machine=rb.seconds["replay"]))
|
| 53 |
+
print(key, json.dumps(out[key], indent=1), flush=True)
|
| 54 |
+
json.dump(out, open(os.environ.get("OUT", "disco_effects.json"), "w"), indent=1)
|
tools/scanner_disco_terms.py
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Each term alone on the DiSCo layout: the Swoop at 7.9 cm along R-L, the Swoop-playable shell (b 350 x 60 on
|
| 2 |
+
d17.7-D35.8), noiseless, the catalogue's white matter at 64 mT: the DWI's change against the ideal scanner per term
|
| 3 |
+
(the S0-normalised signal, so the transmit scale's common factor cancels and only its S0 survives).
|
| 4 |
+
|
| 5 |
+
LAYOUT=/stamped/layout python tools/scanner_disco_terms.py
|
| 6 |
+
"""
|
| 7 |
+
import json, os, sys
|
| 8 |
+
import numpy as np
|
| 9 |
+
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
| 10 |
+
from space import pipeline as P
|
| 11 |
+
from space.sources import disco as D
|
| 12 |
+
from dmipy_sim.replay.shape_moments import ShapeMoments
|
| 13 |
+
from dmipy_tract import hemisphere
|
| 14 |
+
sm = ShapeMoments(os.environ["LAYOUT"])
|
| 15 |
+
L = P.limits("hyperfine_swoop_64mT")
|
| 16 |
+
ph = P.Physics.at(0.064, pools=("intra", "extra"), b0_direction=(0.0, 1.0, 0.0))
|
| 17 |
+
tissue, scanner = P.tissue_and_scanner(ph, ("myelin",))
|
| 18 |
+
dirs = np.concatenate([np.tile([[0.0, 0.0, 1.0]], (3, 1)), hemisphere(60)]); b = np.r_[np.zeros(3), np.full(60, 350e6)]
|
| 19 |
+
grid = sm.grid.centred_at((0.079, 0.0, 0.0))
|
| 20 |
+
def img(**terms):
|
| 21 |
+
dl = None if not terms else sm.delivery("d17.7-D35.8", b, dirs, L, grid, **terms)
|
| 22 |
+
S, fl = sm.image("d17.7-D35.8", b, dirs, tissue=tissue, scanner=scanner, b0_direction=(0.0, 1.0, 0.0), delivered=dl)
|
| 23 |
+
return S / np.nanmean(S[..., :3], -1, keepdims=True), fl, S[..., :3].mean(-1)
|
| 24 |
+
off = dict(nonlinearity=False, background=False, concomitant=False, transmit=False)
|
| 25 |
+
A, floor, S0A = img()
|
| 26 |
+
m = np.isfinite(A[..., 0])
|
| 27 |
+
out = {}
|
| 28 |
+
for term in ("nonlinearity", "background", "concomitant", "transmit", "all"):
|
| 29 |
+
Bt, _, S0B = img(**({k: True for k in off} if term == "all" else {**off, term: True}))
|
| 30 |
+
d = np.abs(Bt - A)[m][:, 3:]
|
| 31 |
+
mean = (Bt[m][:, 3:].mean(1) - A[m][:, 3:].mean(1)) / A[m][:, 3:].mean(1)
|
| 32 |
+
out[term] = dict(abs_dwi_median=float(np.median(d)), abs_dwi_p99=float(np.quantile(d, 0.99)), direction_mean_rel_median=float(np.median(mean)),
|
| 33 |
+
s0_ratio_median=float(np.median(S0B[m] / S0A[m])))
|
| 34 |
+
print(term, json.dumps(out[term]), flush=True)
|
| 35 |
+
out["floor_median"] = float(np.nanmedian(floor[m]))
|
| 36 |
+
json.dump(out, open("disco_terms.json", "w"), indent=1)
|
tools/stamp_disco_background.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Stamp the background moments onto DiSCo's shape-moment layout (dmipy-sim's shape_moments.stamp_background): one
|
| 2 |
+
pass over the columnar source, the bg_<g>.npy columns and the manifest's background and RF schedules written into
|
| 3 |
+
DIR, which holds the layout's manifest.json and tiles.npy (the rest of the layout is not read and not touched; copy
|
| 4 |
+
the new columns and manifest beside it). Measured on a CPU host, from the Hub: 42.4 GB read, 1,016 s.
|
| 5 |
+
|
| 6 |
+
python tools/stamp_disco_background.py DIR
|
| 7 |
+
"""
|
| 8 |
+
import json, os, sys, time
|
| 9 |
+
import numpy as np
|
| 10 |
+
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
| 11 |
+
import dmipy_sim as d
|
| 12 |
+
from dmipy_sim.replay.shape_moments import stamp_background
|
| 13 |
+
out = sys.argv[1]
|
| 14 |
+
man = json.load(open(os.path.join(out, "manifest.json")))
|
| 15 |
+
shapes = {}
|
| 16 |
+
for name, rec in man["shapes"].items():
|
| 17 |
+
fam, kw = rec["build_spec"]
|
| 18 |
+
kw = dict(kw); dirs = kw.pop("gradient_directions")
|
| 19 |
+
if fam == "pgse":
|
| 20 |
+
shapes[name] = d.pgse(dirs, kw["delta"], kw["Delta"], gradient_strengths=kw["gradient_strengths"], TE=kw["TE"], n_t=kw["n_t"], slew_rate=np.inf)
|
| 21 |
+
else:
|
| 22 |
+
shapes[name] = d.pgste(dirs, kw["delta"], kw["TM"], gradient_strengths=kw["gradient_strengths"], n_t=kw["n_t"], slew_rate=np.inf,
|
| 23 |
+
ste_flip_angles=tuple(kw["ste_flip_angles"]))
|
| 24 |
+
last = [0.0]
|
| 25 |
+
def progress(rows, nbytes, secs):
|
| 26 |
+
if secs - last[0] > 60:
|
| 27 |
+
last[0] = secs
|
| 28 |
+
print(time.strftime("%H:%M:%S"), f"{rows:,} rows, {nbytes / 1e9:.1f} GB, {secs:.0f} s, {nbytes / max(secs, 1) / 1e6:.0f} MB/s", flush=True)
|
| 29 |
+
m = stamp_background(out, "hf://SubstrateCommons/disco-replay/disco", shapes, workers=16, progress=progress)
|
| 30 |
+
print("DONE", json.dumps(m["background"]), json.dumps(m["stamps"][-1]), flush=True)
|