brainchop 0.2.3__tar.gz → 0.2.4__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (25) hide show
  1. {brainchop-0.2.3/brainchop.egg-info → brainchop-0.2.4}/PKG-INFO +10 -1
  2. {brainchop-0.2.3 → brainchop-0.2.4}/README.md +9 -0
  3. {brainchop-0.2.3 → brainchop-0.2.4}/brainchop/api.py +32 -13
  4. {brainchop-0.2.3 → brainchop-0.2.4}/brainchop/cli.py +10 -4
  5. {brainchop-0.2.3 → brainchop-0.2.4}/brainchop/niimath/__init__.py +78 -23
  6. {brainchop-0.2.3 → brainchop-0.2.4}/brainchop/tiny_meshnet.py +12 -4
  7. {brainchop-0.2.3 → brainchop-0.2.4/brainchop.egg-info}/PKG-INFO +10 -1
  8. {brainchop-0.2.3 → brainchop-0.2.4}/pyproject.toml +1 -1
  9. {brainchop-0.2.3 → brainchop-0.2.4}/tests/test_api.py +17 -0
  10. {brainchop-0.2.3 → brainchop-0.2.4}/LICENSE +0 -0
  11. {brainchop-0.2.3 → brainchop-0.2.4}/MANIFEST.in +0 -0
  12. {brainchop-0.2.3 → brainchop-0.2.4}/brainchop/__init__.py +0 -0
  13. {brainchop-0.2.3 → brainchop-0.2.4}/brainchop/convert_tfjs_to_pth.py +0 -0
  14. {brainchop-0.2.3 → brainchop-0.2.4}/brainchop/export_model.py +0 -0
  15. {brainchop-0.2.3 → brainchop-0.2.4}/brainchop/sae_model.py +0 -0
  16. {brainchop-0.2.3 → brainchop-0.2.4}/brainchop/utils.py +0 -0
  17. {brainchop-0.2.3 → brainchop-0.2.4}/brainchop.egg-info/SOURCES.txt +0 -0
  18. {brainchop-0.2.3 → brainchop-0.2.4}/brainchop.egg-info/dependency_links.txt +0 -0
  19. {brainchop-0.2.3 → brainchop-0.2.4}/brainchop.egg-info/entry_points.txt +0 -0
  20. {brainchop-0.2.3 → brainchop-0.2.4}/brainchop.egg-info/requires.txt +0 -0
  21. {brainchop-0.2.3 → brainchop-0.2.4}/brainchop.egg-info/top_level.txt +0 -0
  22. {brainchop-0.2.3 → brainchop-0.2.4}/setup.cfg +0 -0
  23. {brainchop-0.2.3 → brainchop-0.2.4}/tests/test_backend_comparison.py +0 -0
  24. {brainchop-0.2.3 → brainchop-0.2.4}/tests/test_batching.py +0 -0
  25. {brainchop-0.2.3 → brainchop-0.2.4}/tests/test_sequential_argmax.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: brainchop
3
- Version: 0.2.3
3
+ Version: 0.2.4
4
4
  Summary: Portable and lightweight brain segmentation using tinygrad
5
5
  Author-email: Mike Doan <spikedoanz@gmail.com>
6
6
  License: MIT
@@ -31,6 +31,15 @@ BrainChop is a lightweight tool for brain segmentation that runs on pretty much
31
31
 
32
32
  ---
33
33
 
34
+ ## (NEW) No install single command use
35
+
36
+ Using [uv](https://docs.astral.sh/uv/), brainchop can be ran without needing an enviroment
37
+ ```
38
+ uvx brainchop --help
39
+ ```
40
+
41
+ ```
42
+
34
43
  ## Installation
35
44
 
36
45
  ```bash
@@ -4,6 +4,15 @@ BrainChop is a lightweight tool for brain segmentation that runs on pretty much
4
4
 
5
5
  ---
6
6
 
7
+ ## (NEW) No install single command use
8
+
9
+ Using [uv](https://docs.astral.sh/uv/), brainchop can be ran without needing an enviroment
10
+ ```
11
+ uvx brainchop --help
12
+ ```
13
+
14
+ ```
15
+
7
16
  ## Installation
8
17
 
9
18
  ```bash
@@ -22,6 +22,8 @@ from brainchop.niimath import (
22
22
  conform,
23
23
  bwlabel,
24
24
  truncate_header_bytes,
25
+ set_header_intent_label,
26
+ _run_niimath,
25
27
  )
26
28
  from brainchop.tiny_meshnet import load_meshnet, chunked_conv
27
29
  from brainchop.sae_model import load_sae
@@ -130,18 +132,33 @@ def list_models() -> dict[str, str]:
130
132
  return {name: details["description"] for name, details in AVAILABLE_MODELS.items()}
131
133
 
132
134
 
133
- def load(path: str, *, crop: float | None = None, ct: bool = False, comply: bool = False) -> Volume:
135
+ def _load_single(path: str | Path, *, crop: float | None = None, ct: bool = False, comply: bool = False) -> Volume:
136
+ from brainchop.utils import crop_to_cutoff
137
+
138
+ data, header = conform(os.path.abspath(path), ct=ct, comply=comply)
139
+ if crop is not None:
140
+ data, _ = crop_to_cutoff(data, crop)
141
+ return Volume(Tensor(data.copy()), header)
142
+
143
+
144
+ def load(
145
+ path: str | Path | list[str | Path],
146
+ *,
147
+ crop: float | None = None,
148
+ ct: bool = False,
149
+ comply: bool = False,
150
+ ) -> Volume | list[Volume]:
134
151
  """
135
- Load NIfTI file and conform to 256x256x256.
152
+ Load NIfTI file(s) and conform to 256x256x256.
136
153
 
137
154
  Args:
138
- path: Path to NIfTI file (.nii or .nii.gz)
155
+ path: Path or list of paths to NIfTI file(s) (.nii or .nii.gz)
139
156
  crop: Crop intensity percentile (e.g., 0.01 removes bottom 1%)
140
157
  ct: Use CT windowing instead of MRI normalization
141
158
  comply: Insert niimath compliance arguments before conform
142
159
 
143
160
  Returns:
144
- Volume with data Tensor (256,256,256) and header bytes
161
+ Single Volume if path is a single path, list[Volume] if path is a list
145
162
 
146
163
  Example:
147
164
  ```python
@@ -149,15 +166,16 @@ def load(path: str, *, crop: float | None = None, ct: bool = False, comply: bool
149
166
  >>> vol.data.shape
150
167
  (256, 256, 256)
151
168
 
169
+ >>> vols = load(["brain1.nii.gz", "brain2.nii.gz"])
170
+ >>> len(vols)
171
+ 2
172
+
152
173
  >>> vol = load("brain.nii.gz", crop=0.01) # crop dark voxels
153
174
  ```
154
175
  """
155
- from brainchop.utils import crop_to_cutoff
156
-
157
- data, header = conform(os.path.abspath(path), ct=ct, comply=comply)
158
- if crop is not None:
159
- data, _ = crop_to_cutoff(data, crop)
160
- return Volume(Tensor(data.copy()), header)
176
+ if isinstance(path, list):
177
+ return [_load_single(p, crop=crop, ct=ct, comply=comply) for p in path]
178
+ return _load_single(path, crop=crop, ct=ct, comply=comply)
161
179
 
162
180
 
163
181
  def save(volume: Volume, path: str) -> None:
@@ -175,13 +193,14 @@ def save(volume: Volume, path: str) -> None:
175
193
  >>> save(result, "segmented.nii.gz")
176
194
  ```
177
195
  """
178
- header = truncate_header_bytes(volume.header)
196
+ # Segmentation output is a categorical label map: tag the NIfTI header with
197
+ # NIFTI_INTENT_LABEL (1002) so downstream viewers treat it as labels.
198
+ header = set_header_intent_label(truncate_header_bytes(volume.header))
179
199
  gz = "1" if path.endswith(".gz") else "0"
180
200
  data = volume.data.cast("uint8").numpy().tobytes()
181
- subprocess.run(
201
+ _run_niimath(
182
202
  ["niimath", "-", "-gz", gz, path, "-odt", "char"],
183
203
  input=header + data,
184
- check=True,
185
204
  )
186
205
 
187
206
 
@@ -11,7 +11,12 @@ from brainchop.api import (
11
11
  Volume, load, save, segment, list_models, optimize, export_classes,
12
12
  _is_first_run, _get_best_beam,
13
13
  )
14
- from brainchop.niimath import grow_border, truncate_header_bytes
14
+ from brainchop.niimath import (
15
+ grow_border,
16
+ truncate_header_bytes,
17
+ set_header_intent_label,
18
+ _run_niimath,
19
+ )
15
20
 
16
21
 
17
22
  def get_parser() -> argparse.ArgumentParser:
@@ -205,11 +210,12 @@ def _save_mindgrab(result: Volume, source_path: str, args, output_path: str):
205
210
 
206
211
  def _save_inverse_conform(result: Volume, source_path: str, output_path: str):
207
212
  """Save with inverse conform."""
208
- header = truncate_header_bytes(result.header)
213
+ # Categorical label output -> tag header with NIFTI_INTENT_LABEL (1002).
214
+ header = set_header_intent_label(truncate_header_bytes(result.header))
209
215
  gz = "0" if output_path.endswith(".nii") else "1"
210
- subprocess.run(
216
+ _run_niimath(
211
217
  ["niimath", "-", "-reslice_nn", source_path, "-gz", gz, output_path, "-odt", "char"],
212
- input=header + result.data.cast("uint8").numpy().tobytes(), check=True
218
+ input=header + result.data.cast("uint8").numpy().tobytes(),
213
219
  )
214
220
 
215
221
 
@@ -10,6 +10,25 @@ from tinygrad import Tensor
10
10
  from typing import Tuple
11
11
 
12
12
 
13
+ def _run_niimath(cmd, *, input: bytes | None = None) -> subprocess.CompletedProcess:
14
+ """Run a niimath command, surfacing its stderr on failure.
15
+
16
+ niimath aborts (e.g. SIGABRT / exit 134) on some inputs -- extended headers
17
+ with operation history, unusual datatypes, 4D volumes. ``capture_output``
18
+ otherwise swallows the reason and leaves only an opaque CalledProcessError,
19
+ so on a non-zero exit we decode and re-raise niimath's own stderr.
20
+ """
21
+ try:
22
+ return subprocess.run(cmd, input=input, capture_output=True, check=True)
23
+ except subprocess.CalledProcessError as e:
24
+ stderr = (e.stderr or b"").decode("utf-8", "replace").strip()
25
+ msg = f"niimath failed (exit {e.returncode}): {' '.join(map(str, cmd))}"
26
+ if stderr:
27
+ msg += f"\n{stderr}"
28
+ print(msg, file=sys.stderr)
29
+ raise RuntimeError(msg) from e
30
+
31
+
13
32
  def _get_executable():
14
33
  """
15
34
  Locate the niimath binary, either via NIIMATH_PATH or on your PATH.
@@ -127,21 +146,23 @@ def _read_nifti(filename):
127
146
 
128
147
  INITIAL_HEADER_READ_SIZE = 352
129
148
 
130
- # NIfTI datatype codes to numpy dtypes mapping
149
+ # NIfTI-1 datatype codes -> numpy dtypes (see nifti1.h). NOTE: the previous
150
+ # table was shifted (e.g. 16 mapped to complex64 instead of float32) and
151
+ # referenced np.float128, which does not exist on Apple Silicon. Both are
152
+ # fixed here.
131
153
  nifti_dtypes = {
132
- 1: np.uint8, # DT_UNSIGNED_CHAR
133
- 2: np.int16, # DT_SIGNED_SHORT
134
- 4: np.int32, # DT_SIGNED_INT
135
- 8: np.float32, # DT_FLOAT
136
- 16: np.complex64, # DT_COMPLEX
137
- 32: np.float64, # DT_DOUBLE
138
- 64: np.int8, # DT_INT8 (NIfTI-1 extension)
139
- 128: np.uint16, # DT_UINT16 (NIfTI-1 extension)
140
- 256: np.uint32, # DT_UINT32 (NIfTI-1 extension)
141
- 512: np.int64, # DT_INT64 (NIfTI-1 extension)
142
- 768: np.uint64, # DT_UINT64 (NIfTI-1 extension)
143
- 1024: np.float128, # DT_FLOAT128 (NIfTI-1 extension)
144
- 1792: np.complex128, # DT_COMPLEX128 (NIfTI-1 extension)
154
+ 2: np.uint8, # DT_UINT8
155
+ 4: np.int16, # DT_INT16
156
+ 8: np.int32, # DT_INT32
157
+ 16: np.float32, # DT_FLOAT32
158
+ 32: np.complex64, # DT_COMPLEX64
159
+ 64: np.float64, # DT_FLOAT64
160
+ 256: np.int8, # DT_INT8
161
+ 512: np.uint16, # DT_UINT16
162
+ 768: np.uint32, # DT_UINT32
163
+ 1024: np.int64, # DT_INT64
164
+ 1280: np.uint64, # DT_UINT64
165
+ 1792: np.complex128, # DT_COMPLEX128
145
166
  }
146
167
 
147
168
  file_size = os.path.getsize(filename)
@@ -244,6 +265,28 @@ def _read_nifti(filename):
244
265
  return data.reshape(reshaped_dims), header_bytes
245
266
 
246
267
 
268
+ def _read_nifti_any(path):
269
+ """Like _read_nifti but transparently handles gzip-compressed (.nii.gz) files.
270
+
271
+ _read_nifti seeks by byte offset on the raw file, so a gzip stream must be
272
+ decompressed to a plain NIfTI first.
273
+ """
274
+ with open(path, "rb") as f:
275
+ magic = f.read(2)
276
+ if magic == b"\x1f\x8b": # gzip
277
+ import tempfile
278
+ with gzip.open(path, "rb") as gf:
279
+ raw = gf.read()
280
+ tmp = tempfile.NamedTemporaryFile(suffix=".nii", delete=False)
281
+ try:
282
+ tmp.write(raw)
283
+ tmp.close()
284
+ return _read_nifti(tmp.name)
285
+ finally:
286
+ os.unlink(tmp.name)
287
+ return _read_nifti(path)
288
+
289
+
247
290
  def _write_nifti(path, data, header):
248
291
  # write header + raw voxel data
249
292
  with open(path, "wb") as f:
@@ -262,16 +305,28 @@ def conform(input_image_path, comply=False, ct=False):
262
305
 
263
306
  comply_args = ["-comply", "256", "256", "256", "1", "1", "1", "1", "1"]
264
307
 
265
- cmd = ["niimath", str(inp)]
266
- if ct:
267
- cmd += ["-h2c"]
268
- if comply:
269
- cmd += comply_args
270
- cmd += ["-conform", "-gz", "0", "-", "-odt", "char"]
308
+ def _conform_args(read_from):
309
+ cmd = ["niimath", read_from]
310
+ if ct:
311
+ cmd += ["-h2c"]
312
+ if comply:
313
+ cmd += comply_args
314
+ cmd += ["-conform", "-gz", "0", "-", "-odt", "char"]
315
+ return cmd
271
316
 
272
- # run niimath, capture stdout (header+raw voxels)
273
- res = subprocess.run(cmd, capture_output=True, check=True)
274
- out = res.stdout
317
+ # Fast path: let niimath read the file directly.
318
+ try:
319
+ out = _run_niimath(_conform_args(str(inp))).stdout
320
+ except RuntimeError:
321
+ # niimath could not read the file. This happens with NIfTI files that
322
+ # carry a header extension (e.g. AFNI/FSL operation history): vox_offset
323
+ # points past the extension and niimath's reader miscounts the image
324
+ # buffer ("data bytes needed > data bytes input"). Re-read the volume in
325
+ # Python honoring vox_offset, then hand niimath a clean, extension-free
326
+ # volume (vox_offset=352) via stdin.
327
+ vol_data, clean_header = _read_nifti_any(str(inp))
328
+ piped = clean_header + np.ascontiguousarray(vol_data).tobytes()
329
+ out = _run_niimath(_conform_args("-"), input=piped).stdout
275
330
 
276
331
  # split off header and data
277
332
  header, data = header_data_split(out)
@@ -171,7 +171,7 @@ def set_channel_num(config, in_channels, n_classes, channels):
171
171
  return config
172
172
 
173
173
 
174
- def construct_layer(dropout_p=0, bnorm=True, gelu=False, elu=False, *args, **kwargs):
174
+ def construct_layer(dropout_p=0, bnorm=True, gelu=False, elu=False, affine=False, *args, **kwargs):
175
175
  layers = []
176
176
  kwargs["kernel_size"] = [kwargs["kernel_size"]] * 3
177
177
  layers.append(nn.Conv2d(*args, **kwargs))
@@ -180,7 +180,7 @@ def construct_layer(dropout_p=0, bnorm=True, gelu=False, elu=False, *args, **kwa
180
180
  nn.GroupNorm(
181
181
  num_groups=kwargs["out_channels"],
182
182
  num_channels=kwargs["out_channels"],
183
- affine=False,
183
+ affine=affine,
184
184
  )
185
185
  )
186
186
 
@@ -223,15 +223,23 @@ class MeshNet:
223
223
  self.model = []
224
224
  # Check if config specifies bias (default False for backward compat)
225
225
  use_bias = config.get("bias", False)
226
+ # Learnable per-channel scale/shift in GroupNorm (default False for
227
+ # backward compat). Models trained with affine GroupNorm (e.g. the deep
228
+ # gridding-free DK-atlas model) carry extra GN weight/bias params.
229
+ use_affine = config.get("affine", False)
226
230
 
227
231
  for block_kwargs in config["layers"][:-1]: # All but the last layer
232
+ # Per-layer "bias" overrides the global default, so a stack can keep
233
+ # bias-free hidden convs while still allowing a biased layer.
234
+ layer_bias = block_kwargs.get("bias", use_bias)
228
235
  self.model.extend(
229
236
  construct_layer(
230
237
  dropout_p=config["dropout_p"],
231
238
  bnorm=config["bnorm"],
232
239
  gelu=config.get("gelu", False),
233
240
  elu=config.get("elu", False),
234
- **{**block_kwargs, "bias": use_bias},
241
+ affine=use_affine,
242
+ **{**block_kwargs, "bias": layer_bias},
235
243
  )
236
244
  )
237
245
 
@@ -245,7 +253,7 @@ class MeshNet:
245
253
  padding=last_config["padding"],
246
254
  stride=last_config["stride"],
247
255
  dilation=last_config["dilation"],
248
- bias=use_bias,
256
+ bias=last_config.get("bias", use_bias),
249
257
  )
250
258
  )
251
259
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: brainchop
3
- Version: 0.2.3
3
+ Version: 0.2.4
4
4
  Summary: Portable and lightweight brain segmentation using tinygrad
5
5
  Author-email: Mike Doan <spikedoanz@gmail.com>
6
6
  License: MIT
@@ -31,6 +31,15 @@ BrainChop is a lightweight tool for brain segmentation that runs on pretty much
31
31
 
32
32
  ---
33
33
 
34
+ ## (NEW) No install single command use
35
+
36
+ Using [uv](https://docs.astral.sh/uv/), brainchop can be ran without needing an enviroment
37
+ ```
38
+ uvx brainchop --help
39
+ ```
40
+
41
+ ```
42
+
34
43
  ## Installation
35
44
 
36
45
  ```bash
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "brainchop"
7
- version = "0.2.3"
7
+ version = "0.2.4"
8
8
  description = "Portable and lightweight brain segmentation using tinygrad"
9
9
  readme = "README.md"
10
10
  license = {text = "MIT"}
@@ -35,6 +35,23 @@ class TestLoad:
35
35
  assert vol.data.shape == (256, 256, 256)
36
36
  assert isinstance(vol.header, bytes)
37
37
 
38
+ def test_load_pathlib(self, test_nifti_path):
39
+ vol = load(test_nifti_path)
40
+ assert isinstance(vol, Volume)
41
+ assert vol.data.shape == (256, 256, 256)
42
+
43
+ def test_load_list_of_str(self, test_nifti_path):
44
+ vols = load([str(test_nifti_path), str(test_nifti_path)])
45
+ assert isinstance(vols, list)
46
+ assert len(vols) == 2
47
+ assert all(isinstance(v, Volume) for v in vols)
48
+
49
+ def test_load_list_of_paths(self, test_nifti_path):
50
+ vols = load([test_nifti_path, test_nifti_path])
51
+ assert isinstance(vols, list)
52
+ assert len(vols) == 2
53
+ assert all(isinstance(v, Volume) for v in vols)
54
+
38
55
  def test_load_with_crop(self, test_nifti_path):
39
56
  vol = load(str(test_nifti_path), crop=2.0)
40
57
  assert vol.data.shape[0] <= 256
File without changes
File without changes
File without changes
File without changes