File size: 9,767 Bytes
25a57da
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
# Copyright (c) MONAI Consortium
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#     http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Port of the upstream reference implementation's default (non-CT,
non-comply) preprocessing pipeline for mindmap: conform.c's
`scale_intensity` + `conform_reslice`, the uint8 cast the reference
implementation applies before its main inference step, and
`bc_accel_normalize_input` in backend_accel.c (quantile_mode "rank", the
mode mindmap's model_meta.json selects).

This reproduces FreeSurfer-style conforming: resample to a 256^3, 1mm
isotropic grid in LIA orientation, centered on the input volume, using
trilinear interpolation. mindmap's network was trained on volumes
preprocessed this way, so skipping it (e.g. feeding an arbitrary-sized,
arbitrary-orientation volume directly) changes the output.
"""

from __future__ import annotations

import numpy as np

__all__ = ["mindmap_preprocess", "reslice_to_grid"]


def _niimath_scale_intensity(img: np.ndarray) -> np.ndarray:
    """conform.c `scale_intensity`: niimath's training-intensity transform,
    fixed at f_low=0, f_high=.98. Clips outlier-high intensity using a
    1000-bin histogram over the 98th percentile of nonzero voxels, then
    linearly rescales into [0, 255].
    """
    flat = img.astype(np.float64).ravel()
    n = flat.size
    src_min = float(flat.min())
    src_max = float(flat.max())
    nz = int(np.count_nonzero(np.abs(flat) >= 1e-15))
    nltz = int(np.count_nonzero(flat < 0.0))
    if src_min < 0.0 and 100.0 * nltz / n < 2.0:
        src_min = 0.0

    bin_size = (src_max - src_min) / 1000.0
    if not (bin_size > 0.0):
        return img.astype(np.float32)

    bins = np.clip(((flat - src_min) / bin_size).astype(np.int64), 0, 999)
    hist = np.bincount(bins, minlength=1000)[:1000].astype(np.int64)

    nth = n - int(0.02 * nz)
    cumulative = 0
    idx = 0
    while idx < 999:
        cumulative += int(hist[idx])
        if cumulative + int(hist[idx + 1]) >= nth:
            break
        idx += 1

    clip_max = idx * bin_size + src_min
    scale = 255.0 / (clip_max - src_min) if src_min != clip_max else 1.0
    out = np.clip(0.0 + scale * (flat - src_min), 0.0, 255.0)
    return out.reshape(img.shape).astype(np.float32)


def _conform_affine(in_dim: tuple[int, int, int], in_affine: np.ndarray) -> np.ndarray:
    """conform.c `conform_xform`, `ras=0` branch (the reference
    implementation's conform step always calls conform_reslice with
    ras=0): a 256^3, 1mm, LIA-oriented grid, centered on the input volume's
    geometric center.
    """
    half = np.array([in_dim[0] / 2.0, in_dim[1] / 2.0, in_dim[2] / 2.0, 1.0])
    center = (in_affine @ half)[:3]

    out_affine = np.array([[-1.0, 0.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, -1.0, 0.0, 0.0], [0.0, 0.0, 0.0, 1.0]])
    out_center = (out_affine @ np.array([256.0, 256.0, 256.0, 1.0]))[:3]
    out_affine[0, 3] = center[0] - 0.5 * out_center[0]
    out_affine[1, 3] = center[1] - 0.5 * out_center[1]
    out_affine[2, 3] = center[2] - 0.5 * out_center[2]
    return out_affine


def reslice_to_grid(
    img: np.ndarray,
    in_affine: np.ndarray,
    out_affine: np.ndarray,
    out_shape: tuple[int, int, int],
    linear: bool = True,
    fill: float | None = None,
) -> np.ndarray:
    """conform.c `do_reslice`/`reslice_rows`, generalized over its `linear`
    flag: `linear=True` is the trilinear path used going into conform space
    (mindmap_preprocess); `linear=False` is the nearest-neighbor path the
    reference implementation's reslice step uses to bring a conform-space
    prediction back onto the input's native grid.

    Out-of-FOV voxels are filled with `img`'s own minimum by default (not
    zero), matching `do_reslice`'s `mn` prefill. In the trilinear case a
    destination voxel is only interpolated if its full 2x2x2 input
    neighborhood is in-bounds -- an all-or-nothing rule, not a partial blend.
    """
    if fill is None:
        fill = float(img.min())
    nx, ny, nz = img.shape
    out_to_in = np.linalg.inv(in_affine) @ out_affine

    # Broadcastable singleton-axis coordinates rather than np.meshgrid's fully
    # materialized (256, 256, 256) arrays: arithmetic broadcasting below
    # produces identical values, but without three redundant ~128MiB float64
    # allocations for a 256^3 grid.
    x = np.arange(out_shape[0], dtype=np.float64)[:, None, None]
    y = np.arange(out_shape[1], dtype=np.float64)[None, :, None]
    z = np.arange(out_shape[2], dtype=np.float64)[None, None, :]

    m = out_to_in
    fxp = m[0, 0] * x + m[0, 1] * y + m[0, 2] * z + m[0, 3]
    fyp = m[1, 0] * x + m[1, 1] * y + m[1, 2] * z + m[1, 3]
    fzp = m[2, 0] * x + m[2, 1] * y + m[2, 2] * z + m[2, 3]

    if not linear:
        ix = np.round(fxp).astype(np.int64)
        iy = np.round(fyp).astype(np.int64)
        iz = np.round(fzp).astype(np.int64)
        valid = (ix >= 0) & (iy >= 0) & (iz >= 0) & (ix < nx) & (iy < ny) & (iz < nz)
        ix_c = np.clip(ix, 0, nx - 1)
        iy_c = np.clip(iy, 0, ny - 1)
        iz_c = np.clip(iz, 0, nz - 1)
        val = img[ix_c, iy_c, iz_c]
        return np.where(valid, val, fill).astype(np.float32)

    ix = np.floor(fxp).astype(np.int64)
    iy = np.floor(fyp).astype(np.int64)
    iz = np.floor(fzp).astype(np.int64)
    dx = (fxp - ix).astype(np.float32)
    dy = (fyp - iy).astype(np.float32)
    dz = (fzp - iz).astype(np.float32)
    del fxp, fyp, fzp  # not used past this point; drop them before the corner arrays below

    valid = (ix >= 0) & (iy >= 0) & (iz >= 0) & (ix + 1 < nx) & (iy + 1 < ny) & (iz + 1 < nz)
    ix_c = np.clip(ix, 0, nx - 2)
    iy_c = np.clip(iy, 0, ny - 2)
    iz_c = np.clip(iz, 0, nz - 2)

    c000 = img[ix_c, iy_c, iz_c]
    c001 = img[ix_c, iy_c, iz_c + 1]
    c010 = img[ix_c, iy_c + 1, iz_c]
    c011 = img[ix_c, iy_c + 1, iz_c + 1]
    c100 = img[ix_c + 1, iy_c, iz_c]
    c101 = img[ix_c + 1, iy_c, iz_c + 1]
    c110 = img[ix_c + 1, iy_c + 1, iz_c]
    c111 = img[ix_c + 1, iy_c + 1, iz_c + 1]

    wx0, wy0, wz0 = 1 - dx, 1 - dy, 1 - dz
    val = (
        c000 * wx0 * wy0 * wz0
        + c001 * wx0 * wy0 * dz
        + c010 * wx0 * dy * wz0
        + c011 * wx0 * dy * dz
        + c100 * dx * wy0 * wz0
        + c101 * dx * wy0 * dz
        + c110 * dx * dy * wz0
        + c111 * dx * dy * dz
    )
    return np.where(valid, val, fill).astype(np.float32)


def _accel_quantile_rank(cumulative: np.ndarray, quantile: float, nvox: int, upper: bool) -> float:
    """backend_accel.c `accel_quantile`, `BC_MODEL_QUANTILE_MODE == 1` branch
    (the "rank" mode mindmap's model_meta.json selects): plain rank selection
    over the 256-bin histogram, no interpolation. `upper` picks which end of
    the quantile pair this is (`ceil(n*q) - 1` vs a plain truncation) rather
    than inferring it from the quantile value, matching the reference.
    """
    rank = (int(np.ceil(nvox * quantile)) - 1) if upper else int(nvox * quantile)
    bin_idx = 0
    while bin_idx < 255 and cumulative[bin_idx] <= rank:
        bin_idx += 1
    return float(bin_idx)


def _quantile_normalize_uint8(
    img_uint8: np.ndarray, q_low: float = 0.05, q_high: float = 0.95, denom_eps: float = 0.0, clamp: bool = False
) -> np.ndarray:
    """backend_accel.c `bc_accel_normalize_input`, parameterized with
    mindmap's model_meta.json values (q_low=0.05, q_high=0.95, denom_eps=0.0,
    clamp=False, quantile_mode="rank").
    """
    nvox = img_uint8.size
    hist = np.bincount(img_uint8.ravel().astype(np.int64), minlength=256)[:256]
    cumulative = np.cumsum(hist)
    low = _accel_quantile_rank(cumulative, q_low, nvox, upper=False)
    high = _accel_quantile_rank(cumulative, q_high, nvox, upper=True)
    denom = high - low + denom_eps
    if not (denom > 0.0):
        denom = 1.0
    out = (img_uint8.astype(np.float32) - np.float32(low)) / np.float32(denom)
    if clamp:
        out = np.clip(out, 0.0, 1.0)
    return out.astype(np.float32)


def mindmap_preprocess(img: np.ndarray, affine: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
    """Full default (MRI, non-CT, non-comply) preprocessing chain for
    mindmap: scale_intensity -> conform reslice -> uint8 cast -> quantile
    normalize (rank mode).

    Args:
        img: input volume, shape (nx, ny, nz), any real-valued dtype.
        affine: 4x4 voxel-to-world (RAS mm) affine, i.e. what nibabel/MONAI
            report as the image's affine.

    Returns:
        normalized: float32 array of shape (256, 256, 256), ready to feed to
            MindMapNet. Not clamped to [0, 1] (mindmap's norm block sets
            `clamp: false`), so values can fall slightly outside that range.
        conform_affine: the 4x4 voxel-to-world affine of `normalized`'s grid,
            needed to reslice the network's output back onto the input's
            native grid.
    """
    scaled = _niimath_scale_intensity(np.asarray(img))
    conform_affine = _conform_affine(scaled.shape, np.asarray(affine, dtype=np.float64))
    conformed = reslice_to_grid(
        scaled, np.asarray(affine, dtype=np.float64), conform_affine, out_shape=(256, 256, 256), linear=True
    )
    conformed_u8 = np.clip(np.round(conformed), 0, 255).astype(np.uint8)
    normalized = _quantile_normalize_uint8(conformed_u8)
    return normalized, conform_affine