gdevenyi commited on
Commit
8cf867e
·
verified ·
1 Parent(s): 19e3b76

noddi: NODDI toolbox 1.05 reference on the ds005134 slab (neurodesk/webapps#424)

Browse files
Files changed (22) hide show
  1. .gitattributes +1 -0
  2. noddi/validation/noddi-toolbox/README.md +222 -0
  3. noddi/validation/noddi-toolbox/SHA256SUMS +20 -0
  4. noddi/validation/noddi-toolbox/compare_app.py +54 -0
  5. noddi/validation/noddi-toolbox/compare_erfi.m +12 -0
  6. noddi/validation/noddi-toolbox/fit_chunk.m +9 -0
  7. noddi/validation/noddi-toolbox/make_roi.py +46 -0
  8. noddi/validation/noddi-toolbox/prepare.sh +31 -0
  9. noddi/validation/noddi-toolbox/run_all.sh +52 -0
  10. noddi/validation/noddi-toolbox/run_fit.sh +17 -0
  11. noddi/validation/noddi-toolbox/save_maps.m +34 -0
  12. noddi/validation/noddi-toolbox/setup_noddi.m +16 -0
  13. noddi/validation/noddi-toolbox/sub-01_dir-AP_desc-slab_desc-brain_mask.nii.gz +3 -0
  14. noddi/validation/noddi-toolbox/sub-01_dir-AP_desc-slab_model-noddi_desc-toolbox_parameters.mat +3 -0
  15. noddi/validation/noddi-toolbox/sub-01_dir-AP_desc-slab_model-noddi_param-direction_dwimap.nii.gz +3 -0
  16. noddi/validation/noddi-toolbox/sub-01_dir-AP_desc-slab_model-noddi_param-errorcode_dwimap.nii.gz +3 -0
  17. noddi/validation/noddi-toolbox/sub-01_dir-AP_desc-slab_model-noddi_param-fmin_dwimap.nii.gz +3 -0
  18. noddi/validation/noddi-toolbox/sub-01_dir-AP_desc-slab_model-noddi_param-icvf_dwimap.nii.gz +3 -0
  19. noddi/validation/noddi-toolbox/sub-01_dir-AP_desc-slab_model-noddi_param-isovf_dwimap.nii.gz +3 -0
  20. noddi/validation/noddi-toolbox/sub-01_dir-AP_desc-slab_model-noddi_param-kappa_dwimap.nii.gz +3 -0
  21. noddi/validation/noddi-toolbox/sub-01_dir-AP_desc-slab_model-noddi_param-odi_dwimap.nii.gz +3 -0
  22. noddi/validation/noddi-toolbox/write_maps.py +66 -0
.gitattributes CHANGED
@@ -292,3 +292,4 @@ lcmodel/examples/philips-megapress/sub-01_megapress_act.sdat filter=lfs diff=lfs
292
  lcmodel/examples/philips-megapress/sub-01_megapress_ref.sdat filter=lfs diff=lfs merge=lfs -text
293
  sdc/reference/mask/slab/sub-01_dir-AP_desc-slab_desc-meanb0_dwiref.nii filter=lfs diff=lfs merge=lfs -text
294
  sdc/reference/mask/sub-01_dir-AP_run-001_desc-meanb0_dwiref.nii filter=lfs diff=lfs merge=lfs -text
 
 
292
  lcmodel/examples/philips-megapress/sub-01_megapress_ref.sdat filter=lfs diff=lfs merge=lfs -text
293
  sdc/reference/mask/slab/sub-01_dir-AP_desc-slab_desc-meanb0_dwiref.nii filter=lfs diff=lfs merge=lfs -text
294
  sdc/reference/mask/sub-01_dir-AP_run-001_desc-meanb0_dwiref.nii filter=lfs diff=lfs merge=lfs -text
295
+ noddi/validation/noddi-toolbox/sub-01_dir-AP_desc-slab_model-noddi_desc-toolbox_parameters.mat filter=lfs diff=lfs merge=lfs -text
noddi/validation/noddi-toolbox/README.md ADDED
@@ -0,0 +1,222 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # NODDI toolbox 1.05 reference on the ds005134 slab
2
+
3
+ This folder holds the NODDI toolbox reference for the neurodesk/webapps `noddi` app
4
+ (issue #424). The NODDI toolbox 1.05 (MATLAB code, run here in GNU Octave) fits
5
+ NODDI-Watson (`WatsonSHStickTortIsoV_B0`) to the multi-shell example slab, inside the app's own
6
+ brain mask. A future port of the toolbox method must agree with these maps. Each NODDI method is
7
+ compared with its own reference only: the AMICO port has `noddi/validation/` and
8
+ `noddi/validation/dmipy/`.
9
+
10
+ ## Input
11
+
12
+ `noddi/examples/sub-01_dir-AP_desc-slab_dwi.{nii.gz,bval,bvec}` at dataset commit
13
+ `ce028ecca10e9abe7988f965e03ad51627ca9c52`: OpenNeuro ds005134 sub-01, 67 × 92 × 10 × 137 at
14
+ 2 mm, 13 b0, 12 × b500, 48 × b1000, 64 × b2000 (CC0). SHA-256 of the DWI:
15
+ `1e7c8461d9bfc3c80633f930dc1df16d892a6bfd5e15db4c5a2be9d021e48d00`.
16
+
17
+ ## Files
18
+
19
+ | File | Content | Licence |
20
+ | --- | --- | --- |
21
+ | `sub-01_dir-AP_desc-slab_desc-brain_mask.nii.gz` | the app's mask: MindGrab 0.1.20260925 (CPU) of the mean b0, 45965 voxels. Byte copy of the `noddi` command line's output (same file as in `noddi/validation/dmipy/`) | MIT (MindGrab output), CC0 input |
22
+ | `sub-01_dir-AP_desc-slab_model-noddi_param-icvf_dwimap.nii.gz` | ICVF, toolbox `ficvf` (intra-neurite fraction of the non-CSF signal) | CC0 |
23
+ | `sub-01_dir-AP_desc-slab_model-noddi_param-isovf_dwimap.nii.gz` | ISOVF, toolbox `fiso` | CC0 |
24
+ | `sub-01_dir-AP_desc-slab_model-noddi_param-odi_dwimap.nii.gz` | ODI, toolbox `odi` = `atan2(1, kappa * 10) * 2 / pi` | CC0 |
25
+ | `sub-01_dir-AP_desc-slab_model-noddi_param-direction_dwimap.nii.gz` | fibre direction, 3 frames, toolbox `fibredirs_{x,y,z}vec` (`GetFibreOrientation`), unit vector in the bvec frame | CC0 |
26
+ | `sub-01_dir-AP_desc-slab_model-noddi_param-kappa_dwimap.nii.gz` | toolbox `kappa` (the toolbox's scaled Watson concentration: the model uses `kappa * 10`) | CC0 |
27
+ | `sub-01_dir-AP_desc-slab_model-noddi_param-fmin_dwimap.nii.gz` | toolbox `fmin`: `fobj_ml`, the Rician log-likelihood at the fitted parameters | CC0 |
28
+ | `sub-01_dir-AP_desc-slab_model-noddi_param-errorcode_dwimap.nii.gz` | toolbox `error_code` (0 = fit done, 2 = the gradient-descent stage stopped with an error) | CC0 |
29
+ | `sub-01_dir-AP_desc-slab_model-noddi_desc-toolbox_parameters.mat` | the toolbox's `FittedParams.mat` for all mask voxels (MAT v7, float64): `model`, `gsps`, `fobj_gs`, `mlps`, `fobj_ml`, `error_code`, and `idx` (1-based i, j, k of each row) | CC0 |
30
+ | `setup_noddi.m` | the shared Octave set-up (packages, paths, checks that the overrides are used) | Apache-2.0 |
31
+ | `fit_chunk.m` | fits one voxel chunk with the toolbox's `batch_fitting_single` | Apache-2.0 |
32
+ | `save_maps.m` | merges the chunks and computes the maps as `SaveParamsAsNIfTI.m` does | Apache-2.0 |
33
+ | `make_roi.py` | writes the ROI (`CreateROI.m` without niftimatlib) and the 32 chunks | Apache-2.0 |
34
+ | `write_maps.py` | writes the NIfTI maps from `save_maps.m`'s output | Apache-2.0 |
35
+ | `compare_erfi.m` | compares the bundled `NODDI_erfi.m` with Octave's `erfi` (run locally only) | Apache-2.0 |
36
+ | `compare_app.py` | the plausibility check against the app's AMICO maps | Apache-2.0 |
37
+ | `prepare.sh` | unzips the toolbox, writes the two patched override files, writes the ROI | Apache-2.0 |
38
+ | `run_fit.sh` | runs the 32 chunks in parallel | Apache-2.0 |
39
+ | `run_all.sh` | every command, in order | Apache-2.0 |
40
+ | `SHA256SUMS` | SHA-256 of every other file | CC0 |
41
+
42
+ The maps are float32 on the slab's header (same affine, qform and sform). `scl_slope` and
43
+ `scl_inter` are NaN in the written header, which NIfTI readers take as no scaling (nibabel writes
44
+ this after `set_slope_inter(1, 0)`; the dmipy maps have the same header). The maps are 0 outside
45
+ the mask. The file names follow the app's BEP016 names, so a test can pair each file with the
46
+ app's file of the same name.
47
+
48
+ This folder holds no toolbox code. The toolbox files, the bundled `NODDI_erfi.m` and the patched
49
+ copies are not uploaded; "Patches" below describes each change.
50
+
51
+ ## Toolbox
52
+
53
+ `NODDI_toolbox_v1.05.zip` from NITRC (http://www.nitrc.org/projects/noddi_toolbox, a login is
54
+ necessary), SHA-256 `d4f8a1fe5c5e038a29174c40c4f6de0c868728e4d4cdf59c1d7f6dd399ca8143`. Its
55
+ `VERSION` file says "This version of the toolbox is extracted from WUZI r1032". Licence: Artistic
56
+ License 2.0 (`LICENSE.txt`), except the bundled `models/watson/NODDI_erfi.m` (Per Sundqvist), which
57
+ has no licence.
58
+
59
+ ## Model
60
+
61
+ The toolbox's in-vivo NODDI model, `MakeModel('WatsonSHStickTortIsoV_B0')`, with its defaults:
62
+ intra-axial diffusivity 1.7e-3 mm²/s and isotropic diffusivity 3.0e-3 mm²/s (fixed), tortuosity,
63
+ b0 estimated from the data. The fit is the toolbox's three-stage fit (`ThreeStageFittingVoxel`):
64
+ a grid search on the Rician log-likelihood (`GridSearchRician`), then gradient descent with the
65
+ orientation and kappa fixed, then gradient descent on all free parameters (`fmincon_fix`, which
66
+ calls `fmincon`). `model.noOfStages` is 2 (the toolbox default), so the MCMC stage does not run.
67
+ `model.GD.type` is `'single'`, so there is no multistart and no random step. Sigma is estimated per
68
+ voxel (`model.sigma.perVoxel` 1).
69
+
70
+ The protocol is `FSL2Protocol(bval, bvec)` with its default b0 threshold 0: the 13 b = 0 volumes
71
+ are the b0 measurements. The ROI is every voxel of the mask, in `CreateROI.m` order (i outer,
72
+ k inner), with the DWI signal as float64 (`scl_slope`, `scl_inter` are NaN in the slab: no
73
+ scaling).
74
+
75
+ ## erfi
76
+
77
+ The run uses Octave's built-in `erfi` (Octave 11.3.0 core, computed with the Faddeeva package by
78
+ Steven G. Johnson, MIT licence). The toolbox calls `NODDI_erfi(sqrt(kappa * 10))` in
79
+ `WatsonSHCoeff.m` and `WatsonHinderedDiffusionCoeff.m`. The override `NODDI_erfi.m` holds only
80
+ `y = erfi(x);`. It is not uploaded.
81
+
82
+ Reason: the bundled `NODDI_erfi.m` calls `gammainc` with a negative first argument, which fails on
83
+ vectors in Octave 11.3.0. The toolbox calls it with vectors, so the bundled file cannot run the fit.
84
+
85
+ `compare_erfi.m` compares the two, element by element, on 7701 points in [0.3, 8] (the bundled
86
+ file called one scalar at a time, which works):
87
+
88
+ | Range | max relative difference |
89
+ | --- | --- |
90
+ | x in [0.3, 5.7) | 2.899e-06 |
91
+ | x in [5.7, 8] | 1.590e-02 (at x = 5.7010) |
92
+
93
+ The bundled file changes method at x = 5.7. x ≥ 5.7 is toolbox kappa ≥ 3.249 (kappa * 10 ≥ 32.49,
94
+ ODI < 0.0196). **179 fitted voxels have kappa ≥ 3.249**: there, a MATLAB run with the bundled
95
+ `erfi` can give different values.
96
+
97
+ ## Patches
98
+
99
+ Octave with optim 1.6.3 cannot run three toolbox files as they are. `prepare.sh` writes a changed
100
+ copy of two files into an override directory; `setup_noddi.m` puts that directory first on the
101
+ path and checks that Octave uses the override files.
102
+
103
+ 1. `models/watson/NODDI_erfi.m`: replaced by Octave's `erfi` (see "erfi").
104
+ 2. `fitting/fmincon_fix.m`: one line changed. The toolbox calls
105
+ `fmincon(fun, x0f, A, b, Aeq, beq, lb, ub, nonlcon, options, varargin{:}, fix, x0)` with 7 outputs
106
+ (the old MATLAB syntax that passes extra objective arguments after `options`). optim 1.6.3's
107
+ `fmincon` takes at most 10 arguments and gives 4 outputs, and its bound handling needs a column
108
+ start vector. The patched line binds the extra arguments in an anonymous function, gives
109
+ `x0f(:)`, `lb(:)` and `ub(:)` as columns, reshapes the vector back to a row for the objective,
110
+ asks for 4 outputs and sets `lambda`, `grad` and `hessian` to `[]` (the toolbox does not use
111
+ them). `prepare.sh` holds the old and the new line as text.
112
+ 3. `fitting/ThreeStageFittingVoxel.m`: `'Hessian', 'off'` removed from the `optimset` call. With
113
+ optim loaded, `optimset` refuses `'Hessian'` as ambiguous (`hessian_objf_pstruct`,
114
+ `HessianFcn`). `'off'` is the default. All other options are kept.
115
+
116
+ Other changes, outside the toolbox files:
117
+
118
+ - `make_roi.py` writes the ROI file instead of `CreateROI.m` (which needs niftimatlib).
119
+ - The fit runs `batch_fitting_single` on 32 contiguous chunks of the ROI in 32 single-threaded
120
+ Octave processes, instead of `batch_fitting` with `parfor`. Each voxel is fitted independently,
121
+ so the chunks do not change the result.
122
+ - `save_maps.m` (Octave) and `write_maps.py` do what `SaveParamsAsNIfTI.m` does (it needs
123
+ niftimatlib): the fitted non-angle parameters, ODI from kappa, `fmin`, `error_code` and the
124
+ fibre direction, each put at its voxel.
125
+
126
+ The optimizer is not MATLAB's. The toolbox asks for `'Algorithm', 'active-set'`; optim 1.6.3's
127
+ `fmincon` maps `active-set` to its `octave_sqp` backend (Octave's `sqp`). Tolerances (`TolX`,
128
+ `TolFun` 1e-6, `MaxIter` 100, `MaxFunEvals` 20000) are the toolbox's. A MATLAB run will not give
129
+ the same digits.
130
+
131
+ ## Versions
132
+
133
+ | Item | Version |
134
+ | --- | --- |
135
+ | NODDI toolbox | 1.05 (zip SHA-256 above) |
136
+ | GNU Octave | 11.3.0, container `docker://gnuoctave/octave@sha256:b22abbe607c15ed821521ab9cf8a7c466dc47506730a0de9503bd554731b3e32` under Apptainer 1.5.4 |
137
+ | Octave Forge packages | optim 1.6.3 (`fmincon`), struct 1.0.18, datatypes 1.5.0, statistics 2.0.1 (`pkg install -forge`) |
138
+ | Python (ROI and NIfTI only) | uv 0.13.4, nibabel 5.3.2, numpy 2.3.4, scipy 1.16.2 |
139
+ | Mask | neurodesk/webapps `3da92c8a7888f38fc05594858874fea64a47a559`, `@neurodesk/noddi` 0.4.20261022, `@brainchop/mindgrab` 0.1.20260925 on the CPU, Node 24.9.0, pnpm 11.7.0 |
140
+
141
+ ## Commands
142
+
143
+ `run_all.sh` holds every command. In short:
144
+
145
+ ```sh
146
+ node repo/packages/noddi/bin/noddi.js "$in/sub-01_dir-AP_desc-slab_dwi.nii.gz" \
147
+ "$in/sub-01_dir-AP_desc-slab_dwi.bval" "$in/sub-01_dir-AP_desc-slab_dwi.bvec" app-cli
148
+ bash prepare.sh work NODDI_toolbox_v1.05.zip "$in/sub-01_dir-AP_desc-slab_dwi.nii.gz" "$mask" 32
149
+ bash run_fit.sh work octave-11.3.0.sif octpkg "$in/sub-01_dir-AP_desc-slab_dwi.bval" \
150
+ "$in/sub-01_dir-AP_desc-slab_dwi.bvec" 32
151
+ # each chunk: octave --no-gui --no-window-system fit_chunk.m BVAL BVEC roi_NNN.mat fit_NNN.mat
152
+ octave --no-gui --no-window-system save_maps.m work/fit 32 \
153
+ out/sub-01_dir-AP_desc-slab_model-noddi_desc-toolbox_parameters.mat work/maps.mat
154
+ python -I write_maps.py "$in/sub-01_dir-AP_desc-slab_dwi.nii.gz" work/maps.mat out sub-01_dir-AP_desc-slab
155
+ ```
156
+
157
+ `fit_chunk.m` is, after `setup_noddi.m`:
158
+
159
+ ```matlab
160
+ protocol = FSL2Protocol(bval, bvec);
161
+ noddi = MakeModel('WatsonSHStickTortIsoV_B0');
162
+ batch_fitting_single(roi_chunk, protocol, noddi, out);
163
+ ```
164
+
165
+ ## Run
166
+
167
+ Host: AMD Ryzen 9 9950X (16 cores, 32 threads), 123 GB, Linux 7.2.9, 2026-10-23. The fit ran as a
168
+ `systemd-run --user` unit.
169
+
170
+ | Step | Wall time | Peak memory |
171
+ | --- | --- | --- |
172
+ | `noddi` command line (MindGrab mask, tensor and AMICO fit) | 31 s | 2.84 GB (`/usr/bin/time -v`) |
173
+ | toolbox fit, 45965 voxels in 32 single-threaded processes | 5141 s (1 h 25 min 41 s); chunks of 1436-1437 voxels took 4326-5140 s; CPU time 130801 s user + 124 s system (36.4 h) | 5.69 GB for the whole unit (systemd `MemoryPeak` of the cgroup, polled every 20 s; it includes page cache); 124.5 MB for the largest single Octave process (`/usr/bin/time -v`); 3.87 GB is the sum of the 32 per-process peaks |
174
+ | `save_maps.m` | 0.7 s | 0.11 GB |
175
+
176
+ The fit took about 2.8 s of CPU time per voxel.
177
+
178
+ ## Result counts
179
+
180
+ | Count | Voxels |
181
+ | --- | --- |
182
+ | mask voxels fitted | 45965 |
183
+ | `error_code` 0 | 45951 |
184
+ | `error_code` 2 | 14 |
185
+ | `mlps` equal to `gsps` (no gain from gradient descent) | 622 (the 14 errors and 608 other voxels) |
186
+ | kappa ≥ 3.249 (bundled-`erfi` range, see "erfi"), `error_code` 0 | 179 |
187
+ | kappa at the upper bound 6.4 | 121 |
188
+ | ODI < 0.02 | 180 |
189
+
190
+ For the 14 voxels with `error_code` 2, `fmincon` stopped with
191
+ `operator *: nonconformant arguments (op1 is 5x10, op2 is 0x0)` (12 voxels) or `(op1 is 2x4,
192
+ op2 is 0x0)` (2 voxels) in optim's `octave_sqp` path. The toolbox then keeps the grid-search
193
+ values, so the maps hold the grid-search values there. Exclude these voxels from tests. They are
194
+ not the 14 voxels that dmipy skips (first volume not positive): the toolbox fits those 14 with
195
+ `error_code` 0. Their (i, j, k), 0-based: (12, 59, 9), (17, 36, 4), (24, 9, 2), (36, 4, 6),
196
+ (36, 74, 4), (37, 17, 1), (37, 87, 4), (40, 12, 7), (40, 32, 1), (42, 39, 1), (50, 21, 7),
197
+ (58, 64, 6), (64, 22, 4), (66, 35, 5).
198
+
199
+ Values at a bound (`error_code` 0): ICVF 0 in 919 voxels, ICVF 1 in 5786 (≥ 0.99 in 7416; median
200
+ ISOVF there 0.29); ISOVF 0 in 10739, ISOVF 1 in 919; kappa 0 in 1. The toolbox does not wrap the
201
+ angles (`theta` outside [0, π] in 322 voxels, `phi` outside [-π, π] in 1303); the direction map is
202
+ the same for either form.
203
+
204
+ ## Plausibility check
205
+
206
+ `compare_app.py` against the app's AMICO maps on the 45951 voxels with `error_code` 0 (the app's
207
+ `noddi` command line at the commit above). This is a check for gross errors (units, parameter
208
+ names, frames), not a validation:
209
+
210
+ | Map | toolbox median | app (AMICO) median | median abs diff | p95 abs diff | Pearson r | Spearman ρ |
211
+ |---|---|---|---|---|---|---|
212
+ | ICVF | 0.508 | 0.500 | 0.003 | 0.244 | 0.885 | 0.952 |
213
+ | ISOVF | 0.107 | 0.090 | 0.003 | 0.070 | 0.991 | 0.965 |
214
+ | ODI | 0.364 | 0.368 | 0.010 | 0.155 | 0.914 | 0.958 |
215
+
216
+ Direction: median angle 1.61°, 95th percentile 26.41°.
217
+
218
+ ## Check
219
+
220
+ ```sh
221
+ sha256sum -c SHA256SUMS
222
+ ```
noddi/validation/noddi-toolbox/SHA256SUMS ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 0732ddf60ee79746ea5a36f7b7d1f70695e985332268df4161d01a1740a3f0ee README.md
2
+ f45873310b1569ff7cb34d261cd07b76e01e0a75fd6ff49a8dffd2b86aafbaaa compare_app.py
3
+ 32698ad8ea284cb733315be86257fbd5b86b50c0968245ccbee35612abd24664 compare_erfi.m
4
+ 078080f81245bf5de048251078bfd01d85ce5d0df75888acd2a65a373ab6c440 fit_chunk.m
5
+ 1ec29dbfc8a90c519e35c49b76094e772c1d6aee8e76640cef23acae37503936 make_roi.py
6
+ 8595d3af6d618a82d4c5ed8c559d880ae34e027c28689b8a2cb0a41daf26b0cc prepare.sh
7
+ 86c369832258638f3312bf2c38f57b86519e77a5fb0e01d821d5bcd90d8a47f9 run_all.sh
8
+ bc9a36999e2ce4746d78b9b9f01d4a00f5b6d5b72c448316f2416ea1e7be7897 run_fit.sh
9
+ b7608abb7bff05c250c0d6d31ea299595738661b454d9ac9cd70637d5877c8fa save_maps.m
10
+ 2fdc3cc9c7771fd0c8bf5b7f53d9aaec5bf80ee0ebdf0459b28d70b87b96de08 setup_noddi.m
11
+ 18781033cb63ac5f3637f43f1faaf76ea3eb6fe72d4b3c03153bf0df871c66aa sub-01_dir-AP_desc-slab_desc-brain_mask.nii.gz
12
+ 55ababf964536f5ad8e27570e790e154090455bcdd63cc8d6a567c3ab0288520 sub-01_dir-AP_desc-slab_model-noddi_desc-toolbox_parameters.mat
13
+ db5dbab08092200f62cae481c9315ed461f5649fc4ed75f0fe26b6f61065bbd0 sub-01_dir-AP_desc-slab_model-noddi_param-direction_dwimap.nii.gz
14
+ abddfa7429f944797cad00cea0b1d39b9f546638d5278332d24b01addf9c98c5 sub-01_dir-AP_desc-slab_model-noddi_param-errorcode_dwimap.nii.gz
15
+ 19acbd33369651e8340acc1d17e4b68c484d4f18c67ad9d170ec1606d9684fea sub-01_dir-AP_desc-slab_model-noddi_param-fmin_dwimap.nii.gz
16
+ b3b4822292f7bcb173edb81b28488331302853b183dea236b65ebe80948a7628 sub-01_dir-AP_desc-slab_model-noddi_param-icvf_dwimap.nii.gz
17
+ 1c09d9a51f8b2c33b5c9d2b2da828b0bfbb745e8b19289a04717db018decadbe sub-01_dir-AP_desc-slab_model-noddi_param-isovf_dwimap.nii.gz
18
+ 7706ec919dc0e3c55f2d67e8b5263e61ffdd8e8d2e2f929ec5dd58790b1521e4 sub-01_dir-AP_desc-slab_model-noddi_param-kappa_dwimap.nii.gz
19
+ 1257a7b589b47c7dc87b7ef7330df55fccae18c952ce8b4e4971274aa524a592 sub-01_dir-AP_desc-slab_model-noddi_param-odi_dwimap.nii.gz
20
+ 25dcd2002e7742bf1881636192d48431340361f98cb0b4d7e3727591f0a93846 write_maps.py
noddi/validation/noddi-toolbox/compare_app.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Sanity check: compare the toolbox maps with the noddi command line's AMICO maps.
2
+
3
+ Not a pass/fail test. Each NODDI method has its own reference; this only
4
+ shows that the two fits agree in the expected way. Both folders use the
5
+ app's BEP016 names. Voxels with a toolbox error code are left out.
6
+
7
+ Usage: python -I compare_app.py TOOLBOX_DIR APP_DIR STEM MASK
8
+ """
9
+
10
+ import sys
11
+
12
+ import nibabel as nib
13
+ import numpy as np
14
+ from scipy.stats import spearmanr
15
+
16
+
17
+ def load(path: str) -> np.ndarray:
18
+ return np.asanyarray(nib.load(path).dataobj, dtype=np.float64)
19
+
20
+
21
+ def main() -> None:
22
+ tb_dir, app_dir, stem, mask_path = sys.argv[1:5]
23
+ mask = load(mask_path) > 0
24
+ ok = mask & (
25
+ load(f"{tb_dir}/{stem}_model-noddi_param-errorcode_dwimap.nii.gz") == 0
26
+ )
27
+ print(
28
+ "| Map | toolbox median | app (AMICO) median | median abs diff | p95 abs diff | Pearson r | Spearman rho |"
29
+ )
30
+ print("|---|---|---|---|---|---|---|")
31
+ for param in ["icvf", "isovf", "odi"]:
32
+ a = load(f"{tb_dir}/{stem}_model-noddi_param-{param}_dwimap.nii.gz")[ok]
33
+ b = load(f"{app_dir}/{stem}_model-noddi_param-{param}_dwimap.nii.gz")[ok]
34
+ d = np.abs(a - b)
35
+ r = np.corrcoef(a, b)[0, 1]
36
+ rho = spearmanr(a, b).statistic
37
+ print(
38
+ f"| {param.upper()} | {np.median(a):.3f} | {np.median(b):.3f} | {np.median(d):.3f} "
39
+ f"| {np.percentile(d, 95):.3f} | {r:.3f} | {rho:.3f} |"
40
+ )
41
+ v = load(f"{tb_dir}/{stem}_model-noddi_param-direction_dwimap.nii.gz")[ok]
42
+ w = load(f"{app_dir}/{stem}_model-noddi_param-direction_dwimap.nii.gz")[ok]
43
+ v = v / np.maximum(np.linalg.norm(v, axis=1, keepdims=True), 1e-12)
44
+ w = w / np.maximum(np.linalg.norm(w, axis=1, keepdims=True), 1e-12)
45
+ angle = np.degrees(np.arccos(np.clip(np.abs(np.sum(v * w, axis=1)), 0, 1)))
46
+ print(
47
+ f"direction: median angle {np.median(angle):.2f} deg, "
48
+ f"95th percentile {np.percentile(angle, 95):.2f} deg"
49
+ )
50
+ print(f"voxels compared: {int(ok.sum())} of {int(mask.sum())} in the mask")
51
+
52
+
53
+ if __name__ == "__main__":
54
+ main()
noddi/validation/noddi-toolbox/compare_erfi.m ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ % Compare Octave built-in erfi with the bundled NODDI_erfi.m, element by element.
2
+ % Usage: octave --no-gui compare_erfi.m BUNDLED_DIR
3
+ args = argv();
4
+ addpath(args{1});
5
+ x = linspace(0.3, 8, 7701);
6
+ b = arrayfun(@(v) NODDI_erfi(v), x);
7
+ e = erfi(x);
8
+ rel = abs(b - e) ./ abs(e);
9
+ below = x < 5.7;
10
+ printf("x in [0.3, 5.7): max relative difference %.3e\n", max(rel(below)));
11
+ printf("x in [5.7, 8]: max relative difference %.3e at x = %.4f\n", max(rel(!below)), x(!below)(find(rel(!below) == max(rel(!below)), 1)));
12
+ printf("x = 5.7: relative difference %.3e\n", abs(NODDI_erfi(5.7) - erfi(5.7)) / erfi(5.7));
noddi/validation/noddi-toolbox/fit_chunk.m ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ % Fit one ROI chunk with the toolbox's batch_fitting_single.
2
+ % Usage: octave --no-gui fit_chunk.m BVAL BVEC ROI.mat OUT.mat
3
+ args = argv();
4
+ run(fullfile(fileparts(mfilename('fullpath')), 'setup_noddi.m'));
5
+ protocol = FSL2Protocol(args{1}, args{2});
6
+ noddi = MakeModel('WatsonSHStickTortIsoV_B0');
7
+ t0 = tic;
8
+ batch_fitting_single(args{3}, protocol, noddi, args{4});
9
+ printf('chunk %s: %.1f s\n', args{3}, toc(t0));
noddi/validation/noddi-toolbox/make_roi.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Write the NODDI toolbox ROI file (roi.mat) from a 4-D DWI and a mask.
2
+
3
+ This does what the toolbox's CreateROI.m does, without niftimatlib:
4
+ the voxel loop is i (x) outer, j (y), k (z) inner, `roi` holds the
5
+ signals of the mask voxels as double, `idx` their 1-based (i, j, k),
6
+ and `mask` the mask with each voxel's 1-based ROI index.
7
+
8
+ Usage: python -I make_roi.py DWI.nii.gz MASK.nii.gz OUT.mat CHUNKS OUTDIR
9
+ Writes OUT.mat (all voxels) and OUTDIR/roi_NNN.mat (CHUNKS contiguous parts).
10
+ """
11
+
12
+ import sys
13
+
14
+ import nibabel as nib
15
+ import numpy as np
16
+ from scipy.io import savemat
17
+
18
+
19
+ def main() -> None:
20
+ dwi_path, mask_path, out_path, chunks, out_dir = sys.argv[1:6]
21
+ dwi_img = nib.load(dwi_path)
22
+ mask_img = nib.load(mask_path)
23
+ if not np.allclose(dwi_img.affine, mask_img.affine) or dwi_img.shape[:3] != mask_img.shape:
24
+ raise SystemExit("the mask is not on the DWI grid")
25
+ # get_fdata applies scl_slope/scl_inter when they are set (here they are NaN: no scaling).
26
+ dwi = dwi_img.get_fdata(dtype=np.float64)
27
+ mask = np.asanyarray(mask_img.dataobj) > 0
28
+ # C order over (i, j, k) is CreateROI's loop order: i outer, k inner.
29
+ ijk = np.argwhere(mask)
30
+ roi = dwi[ijk[:, 0], ijk[:, 1], ijk[:, 2], :]
31
+ idx = (ijk + 1).astype(np.float64)
32
+ numbered = np.zeros(mask.shape, dtype=np.float64)
33
+ numbered[ijk[:, 0], ijk[:, 1], ijk[:, 2]] = np.arange(1, len(ijk) + 1)
34
+ savemat(out_path, {"roi": roi, "mask": numbered, "idx": idx}, do_compression=False)
35
+ parts = np.array_split(np.arange(len(ijk)), int(chunks))
36
+ for n, part in enumerate(parts, start=1):
37
+ savemat(
38
+ f"{out_dir}/roi_{n:03d}.mat",
39
+ {"roi": roi[part], "idx": idx[part], "first": float(part[0] + 1)},
40
+ do_compression=False,
41
+ )
42
+ print(f"{len(ijk)} voxels, {roi.shape[1]} measurements, {len(parts)} chunks")
43
+
44
+
45
+ if __name__ == "__main__":
46
+ main()
noddi/validation/noddi-toolbox/prepare.sh ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # Unzip the toolbox, make the fmincon_fix.m override and the ROI chunks.
3
+ # Usage: prepare.sh WORK_DIR NODDI_TOOLBOX_ZIP DWI MASK CHUNKS
4
+ set -euo pipefail
5
+ work=$1 zip=$2 dwi=$3 mask=$4 chunks=$5
6
+ here=$(cd "$(dirname "$0")" && pwd)
7
+ mkdir -p "$work/toolbox" "$work/overrides" "$work/fit"
8
+ echo "d4f8a1fe5c5e038a29174c40c4f6de0c868728e4d4cdf59c1d7f6dd399ca8143 $zip" | sha256sum -c -
9
+ unzip -q -o "$zip" -x '__MACOSX/*' -d "$work/toolbox"
10
+ cp "$here/overrides/NODDI_erfi.m" "$work/overrides/"
11
+ # optim 1.6.3's fmincon takes at most 10 arguments and returns 4 outputs.
12
+ # fmincon_fix.m passes the extra objective arguments after OPTIONS (old
13
+ # MATLAB syntax) and asks for 7 outputs. Bind the arguments in a handle.
14
+ orig="$work/toolbox/NODDI_toolbox_v1.05/fitting/fmincon_fix.m"
15
+ line='[x,fval,exitflag,output,lambda,grad,hessian] = fmincon(fun,x0f,A,b,Aeq,beq,lb,ub,nonlcon,options,varargin{:}, fix, x0);'
16
+ # It also needs a column start vector: its linear-constraint form of the
17
+ # bounds multiplies by the parameters as a column. The objective still
18
+ # gets the row vector the toolbox uses.
19
+ new='[x,fval,exitflag,output] = fmincon(@(xv) fun(reshape(xv, size(x0f)), varargin{:}, fix, x0),x0f(:),A,b,Aeq,beq,lb(:),ub(:),nonlcon,options); lambda = []; grad = []; hessian = [];'
20
+ [ "$(grep -cF "$line" "$orig")" = 1 ]
21
+ # The toolbox files have CRLF line ends; the patched line keeps its CR.
22
+ awk -v old="$line" -v new="$new" '{ l = $0; sub(/\r$/, "", l) } l == old { print new "\r"; next } { print }' "$orig" > "$work/overrides/fmincon_fix.m"
23
+ ! diff -q "$orig" "$work/overrides/fmincon_fix.m" > /dev/null
24
+ diff "$orig" "$work/overrides/fmincon_fix.m" | cat -v || true
25
+ # optimset in Octave with optim loaded refuses 'Hessian' as ambiguous
26
+ # (hessian_objf_pstruct, HessianFcn). 'off' is the default, so drop it.
27
+ orig="$work/toolbox/NODDI_toolbox_v1.05/fitting/ThreeStageFittingVoxel.m"
28
+ [ "$(grep -cF "'GradObj','off', 'Hessian', 'off', 'FunValCheck'" "$orig")" = 1 ]
29
+ sed "s/'GradObj','off', 'Hessian', 'off', 'FunValCheck'/'GradObj','off', 'FunValCheck'/" "$orig" > "$work/overrides/ThreeStageFittingVoxel.m"
30
+ diff "$orig" "$work/overrides/ThreeStageFittingVoxel.m" | cat -v || true
31
+ uv run --with nibabel==5.3.2 --with numpy==2.3.4 --with scipy==1.16.2 python -I "$here/make_roi.py" "$dwi" "$mask" "$work/roi.mat" "$chunks" "$work/fit"
noddi/validation/noddi-toolbox/run_all.sh ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # The whole run, in order, as it was done on the epic host (AMD Ryzen 9 9950X, 32 threads).
3
+ # The fit steps ran under `systemd-run --user`; they are shown here as plain commands.
4
+ set -euo pipefail
5
+ root=$HOME/scratch/noddi-toolbox-424
6
+ scripts=$root/scripts
7
+ in=$root/input/hf/noddi/examples
8
+ cd "$root"
9
+
10
+ # 1. Input: the ds005134 sub-01 slab at the pinned dataset commit.
11
+ hf download neurodeskorg/webapps --repo-type dataset --revision ce028ecca10e9abe7988f965e03ad51627ca9c52 \
12
+ --include "noddi/examples/*" --local-dir input/hf
13
+ (cd "$in" && sha256sum -c SHA256SUMS)
14
+
15
+ # 2. Mask: MindGrab of the mean b0 with the repository's noddi command line
16
+ # (neurodesk/webapps 3da92c8a, MindGrab 0.1.20260925 on the CPU through @neurodesk/node-drivers).
17
+ git clone --filter=blob:none https://github.com/neurodesk/webapps.git repo
18
+ git -C repo checkout 3da92c8a7888f38fc05594858874fea64a47a559
19
+ (cd repo && npx -y pnpm@11.7.0 install --filter "@neurodesk/noddi..." --frozen-lockfile --ignore-scripts)
20
+ /usr/bin/time -v node repo/packages/noddi/bin/noddi.js "$in/sub-01_dir-AP_desc-slab_dwi.nii.gz" \
21
+ "$in/sub-01_dir-AP_desc-slab_dwi.bval" "$in/sub-01_dir-AP_desc-slab_dwi.bvec" app-cli
22
+ mask=$root/app-cli/sub-01_dir-AP_desc-slab_desc-brain_mask.nii.gz
23
+
24
+ # 3. Octave 11.3.0 and optim 1.6.3 (fmincon) with its dependencies.
25
+ apptainer pull containers/octave-11.3.0.sif \
26
+ docker://gnuoctave/octave@sha256:b22abbe607c15ed821521ab9cf8a7c466dc47506730a0de9503bd554731b3e32
27
+ sif=$root/containers/octave-11.3.0.sif
28
+ mkdir -p octpkg
29
+ apptainer exec -B "$root" "$sif" octave --no-gui --eval "pkg prefix $root/octpkg $root/octpkg; pkg local_list $root/octpkg/list; \
30
+ pkg install -forge struct; pkg install -forge datatypes; pkg install -forge statistics; pkg install -forge optim"
31
+
32
+ # 4. Toolbox, overrides and ROI (NODDI_toolbox_v1.05.zip from NITRC, which needs a login).
33
+ bash "$scripts/prepare.sh" "$root/work" NODDI_toolbox_v1.05.zip "$in/sub-01_dir-AP_desc-slab_dwi.nii.gz" "$mask" 32
34
+
35
+ # 5. Fit: 32 chunks, 32 single-threaded Octave processes.
36
+ /usr/bin/time -v bash "$scripts/run_fit.sh" "$root/work" "$sif" "$root/octpkg" \
37
+ "$in/sub-01_dir-AP_desc-slab_dwi.bval" "$in/sub-01_dir-AP_desc-slab_dwi.bvec" 32
38
+
39
+ # 6. Merge and maps (BEP016 names, as noddi/validation/dmipy/).
40
+ export NODDI_TOOLBOX=$root/work/toolbox/NODDI_toolbox_v1.05 NODDI_OVERRIDES=$root/work/overrides NODDI_PKG=$root/octpkg
41
+ S=sub-01_dir-AP_desc-slab
42
+ apptainer exec -B "$root" "$sif" octave --no-gui --no-window-system "$scripts/save_maps.m" \
43
+ "$root/work/fit" 32 "$root/out/${S}_model-noddi_desc-toolbox_parameters.mat" "$root/work/maps.mat"
44
+ uv run --with nibabel==5.3.2 --with numpy==2.3.4 --with scipy==1.16.2 python -I "$scripts/write_maps.py" \
45
+ "$in/${S}_dwi.nii.gz" "$root/work/maps.mat" "$root/out" "$S"
46
+ cp "$mask" "$root/out/"
47
+
48
+ # 7. erfi check and the sanity comparison with the noddi command line's AMICO maps.
49
+ apptainer exec -B "$root" "$sif" octave --no-gui --no-window-system "$scripts/compare_erfi.m" \
50
+ "$root/work/toolbox/NODDI_toolbox_v1.05/models/watson"
51
+ uv run --with nibabel==5.3.2 --with numpy==2.3.4 --with scipy==1.16.2 python -I "$scripts/compare_app.py" "$root/out" \
52
+ "$root/app-cli" "$S" "$mask"
noddi/validation/noddi-toolbox/run_fit.sh ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # Fit every ROI chunk in its own single-threaded Octave process, JOBS at a time.
3
+ # Usage: run_fit.sh WORK_DIR SIF PKG_DIR BVAL BVEC JOBS
4
+ set -euo pipefail
5
+ work=$1 sif=$2 pkgdir=$3 bval=$4 bvec=$5 jobs=$6
6
+ here=$(cd "$(dirname "$0")" && pwd)
7
+ export OMP_NUM_THREADS=1 OPENBLAS_NUM_THREADS=1
8
+ export NODDI_TOOLBOX=$work/toolbox/NODDI_toolbox_v1.05 NODDI_OVERRIDES=$work/overrides NODDI_PKG=$pkgdir
9
+ start=$(date +%s)
10
+ ls "$work"/fit/roi_*.mat | sort | xargs -P "$jobs" -I{} sh -c '
11
+ roi={}; out=$(echo "$roi" | sed "s/roi_/fit_/"); log=${out%.mat}
12
+ /usr/bin/time -v -o "$log.time" apptainer exec --cleanenv \
13
+ --env OMP_NUM_THREADS=1,OPENBLAS_NUM_THREADS=1,NODDI_TOOLBOX=$NODDI_TOOLBOX,NODDI_OVERRIDES=$NODDI_OVERRIDES,NODDI_PKG=$NODDI_PKG \
14
+ -B "'"$work"'" -B "'"$pkgdir"'" -B "'"$here"'" -B "$(dirname "'"$bval"'")" "'"$sif"'" \
15
+ octave --no-gui --no-window-system "'"$here"'/fit_chunk.m" "'"$bval"'" "'"$bvec"'" "$roi" "$out" > "$log.log" 2>&1
16
+ '
17
+ echo "wall seconds: $(( $(date +%s) - start ))"
noddi/validation/noddi-toolbox/save_maps.m ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ % Merge the fitted chunks and compute the maps as SaveParamsAsNIfTI.m does.
2
+ % Usage: octave --no-gui save_maps.m FIT_DIR NCHUNKS OUT_PARAMS.mat OUT_MAPS.mat
3
+ args = argv();
4
+ run(fullfile(fileparts(mfilename('fullpath')), 'setup_noddi.m'));
5
+ fitdir = args{1};
6
+ nchunks = str2double(args{2});
7
+ gsps = []; mlps = []; fobj_gs = []; fobj_ml = []; error_code = []; idx = [];
8
+ for n = 1:nchunks
9
+ fit = load(fullfile(fitdir, sprintf('fit_%03d.mat', n)));
10
+ roi = load(fullfile(fitdir, sprintf('roi_%03d.mat', n)));
11
+ assert(!isfield(fit, 'current_index'), 'chunk %d did not finish', n);
12
+ gsps = [gsps; fit.gsps];
13
+ mlps = [mlps; fit.mlps];
14
+ fobj_gs = [fobj_gs; fit.fobj_gs];
15
+ fobj_ml = [fobj_ml; fit.fobj_ml];
16
+ error_code = [error_code; fit.error_code];
17
+ idx = [idx; roi.idx];
18
+ model = fit.model;
19
+ end
20
+ save(args{3}, 'model', 'gsps', 'fobj_gs', 'mlps', 'fobj_ml', 'error_code', 'idx');
21
+
22
+ % SaveParamsAsNIfTI: the fitted parameters other than the two orientation
23
+ % angles, ODI from kappa, the objective, the error code and the fibre direction.
24
+ idxOfFitted = find(model.GD.fixed(1:end-2) == 0);
25
+ names = model.paramsStr(idxOfFitted);
26
+ values = mlps(:, idxOfFitted);
27
+ idxOfKappa = find(ismember(model.paramsStr, 'kappa') == 1);
28
+ odi = atan2(1, mlps(:, idxOfKappa) * 10) * 2 / pi;
29
+ fibredirs = GetFibreOrientation(model.name, mlps);
30
+ names = [names, {'odi', 'fmin', 'error_code', 'fibredirs_xvec', 'fibredirs_yvec', 'fibredirs_zvec'}];
31
+ values = [values, odi, fobj_ml, error_code, fibredirs'];
32
+ save(args{4}, 'names', 'values', 'idx');
33
+ printf('%d voxels; error codes: %s\n', rows(mlps), mat2str(unique(error_code)'));
34
+ printf('voxels with mlps == gsps: %d\n', sum(all(mlps == gsps, 2)));
noddi/validation/noddi-toolbox/setup_noddi.m ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ % Shared set-up for every Octave session of this run.
2
+ % NODDI_TOOLBOX: the unzipped NODDI_toolbox_v1.05 directory.
3
+ % NODDI_OVERRIDES: the directory with the NODDI_erfi.m, fmincon_fix.m and
4
+ % ThreeStageFittingVoxel.m overrides (prepare.sh writes the last two).
5
+ % NODDI_PKG: the Octave package prefix that holds optim 1.6.3 and its dependencies.
6
+ save_default_options('-v7');
7
+ pkg('prefix', getenv('NODDI_PKG'), getenv('NODDI_PKG'));
8
+ pkg('local_list', fullfile(getenv('NODDI_PKG'), 'list'));
9
+ pkg('load', 'optim');
10
+ addpath(genpath(getenv('NODDI_TOOLBOX')));
11
+ % addpath puts a directory first, so the overrides shadow the toolbox files.
12
+ addpath(getenv('NODDI_OVERRIDES'));
13
+ overrides = canonicalize_file_name(getenv('NODDI_OVERRIDES'));
14
+ assert(strcmp(canonicalize_file_name(which('NODDI_erfi')), fullfile(overrides, 'NODDI_erfi.m')));
15
+ assert(strcmp(canonicalize_file_name(which('fmincon_fix')), fullfile(overrides, 'fmincon_fix.m')));
16
+ assert(strcmp(canonicalize_file_name(which('ThreeStageFittingVoxel')), fullfile(overrides, 'ThreeStageFittingVoxel.m')));
noddi/validation/noddi-toolbox/sub-01_dir-AP_desc-slab_desc-brain_mask.nii.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:18781033cb63ac5f3637f43f1faaf76ea3eb6fe72d4b3c03153bf0df871c66aa
3
+ size 1840
noddi/validation/noddi-toolbox/sub-01_dir-AP_desc-slab_model-noddi_desc-toolbox_parameters.mat ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:55ababf964536f5ad8e27570e790e154090455bcdd63cc8d6a567c3ab0288520
3
+ size 3321643
noddi/validation/noddi-toolbox/sub-01_dir-AP_desc-slab_model-noddi_param-direction_dwimap.nii.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:db5dbab08092200f62cae481c9315ed461f5649fc4ed75f0fe26b6f61065bbd0
3
+ size 518793
noddi/validation/noddi-toolbox/sub-01_dir-AP_desc-slab_model-noddi_param-errorcode_dwimap.nii.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:abddfa7429f944797cad00cea0b1d39b9f546638d5278332d24b01addf9c98c5
3
+ size 449
noddi/validation/noddi-toolbox/sub-01_dir-AP_desc-slab_model-noddi_param-fmin_dwimap.nii.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:19acbd33369651e8340acc1d17e4b68c484d4f18c67ad9d170ec1606d9684fea
3
+ size 166604
noddi/validation/noddi-toolbox/sub-01_dir-AP_desc-slab_model-noddi_param-icvf_dwimap.nii.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b3b4822292f7bcb173edb81b28488331302853b183dea236b65ebe80948a7628
3
+ size 142367
noddi/validation/noddi-toolbox/sub-01_dir-AP_desc-slab_model-noddi_param-isovf_dwimap.nii.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1c09d9a51f8b2c33b5c9d2b2da828b0bfbb745e8b19289a04717db018decadbe
3
+ size 140006
noddi/validation/noddi-toolbox/sub-01_dir-AP_desc-slab_model-noddi_param-kappa_dwimap.nii.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7706ec919dc0e3c55f2d67e8b5263e61ffdd8e8d2e2f929ec5dd58790b1521e4
3
+ size 165686
noddi/validation/noddi-toolbox/sub-01_dir-AP_desc-slab_model-noddi_param-odi_dwimap.nii.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1257a7b589b47c7dc87b7ef7330df55fccae18c952ce8b4e4971274aa524a592
3
+ size 164723
noddi/validation/noddi-toolbox/write_maps.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Write the NODDI toolbox maps (maps.mat from save_maps.m) as NIfTI.
2
+
3
+ save_maps.m does the per-voxel math of the toolbox's SaveParamsAsNIfTI.m
4
+ in Octave. This script only puts each column on the DWI grid at the
5
+ voxel `idx` gives, as SaveParamsAsNIfTI does, with zero outside the mask,
6
+ and writes float32 NIfTI on the DWI header (same affine), as the dmipy
7
+ reference does. The file names are the app's BEP016 names; the three
8
+ fibre direction columns go into one 3-frame map.
9
+
10
+ Usage: python -I write_maps.py DWI.nii.gz MAPS.mat OUTDIR STEM
11
+ """
12
+
13
+ import gzip
14
+ import sys
15
+
16
+ import nibabel as nib
17
+ import numpy as np
18
+ from scipy.io import loadmat
19
+
20
+ # Toolbox output name -> BEP016 parameter label.
21
+ LABELS = {
22
+ "ficvf": "icvf",
23
+ "fiso": "isovf",
24
+ "odi": "odi",
25
+ "kappa": "kappa",
26
+ "fmin": "fmin",
27
+ "error_code": "errorcode",
28
+ }
29
+ DIRECTION = ["fibredirs_xvec", "fibredirs_yvec", "fibredirs_zvec"]
30
+
31
+
32
+ def write(ref: nib.Nifti1Image, vol: np.ndarray, path: str) -> None:
33
+ img = nib.Nifti1Image(vol.astype(np.float32), ref.affine, ref.header)
34
+ # The DWI header is int16; without this nibabel writes the maps as int16.
35
+ img.set_data_dtype(np.float32)
36
+ img.header.set_slope_inter(1, 0)
37
+ with open(path, "wb") as fh:
38
+ fh.write(gzip.compress(img.to_bytes(), compresslevel=9, mtime=0))
39
+ print(path)
40
+
41
+
42
+ def main() -> None:
43
+ dwi_path, maps_path, out_dir, stem = sys.argv[1:5]
44
+ ref = nib.load(dwi_path)
45
+ shape = ref.shape[:3]
46
+ maps = loadmat(maps_path, squeeze_me=False)
47
+ idx = maps["idx"].astype(np.int64) - 1
48
+ names = [
49
+ str(n[0]) if hasattr(n, "__len__") else str(n) for n in maps["names"].ravel()
50
+ ]
51
+ values = maps["values"]
52
+ if sorted(names) != sorted(list(LABELS) + DIRECTION):
53
+ raise SystemExit(f"unexpected map names: {names}")
54
+ i, j, k = idx[:, 0], idx[:, 1], idx[:, 2]
55
+ for name, label in LABELS.items():
56
+ vol = np.zeros(shape, dtype=np.float32)
57
+ vol[i, j, k] = values[:, names.index(name)]
58
+ write(ref, vol, f"{out_dir}/{stem}_model-noddi_param-{label}_dwimap.nii.gz")
59
+ vol = np.zeros(shape + (3,), dtype=np.float32)
60
+ for c, name in enumerate(DIRECTION):
61
+ vol[i, j, k, c] = values[:, names.index(name)]
62
+ write(ref, vol, f"{out_dir}/{stem}_model-noddi_param-direction_dwimap.nii.gz")
63
+
64
+
65
+ if __name__ == "__main__":
66
+ main()