arrayview 0.55.0__tar.gz → 0.56.0__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 (93) hide show
  1. {arrayview-0.55.0 → arrayview-0.56.0}/PKG-INFO +1 -1
  2. {arrayview-0.55.0 → arrayview-0.56.0}/pyproject.toml +1 -1
  3. {arrayview-0.55.0 → arrayview-0.56.0}/src/arrayview/_config.py +14 -0
  4. {arrayview-0.55.0 → arrayview-0.56.0}/src/arrayview/_diff.py +12 -34
  5. {arrayview-0.55.0 → arrayview-0.56.0}/src/arrayview/_io.py +124 -12
  6. {arrayview-0.55.0 → arrayview-0.56.0}/src/arrayview/_launcher.py +282 -93
  7. {arrayview-0.55.0 → arrayview-0.56.0}/src/arrayview/_render.py +7 -0
  8. {arrayview-0.55.0 → arrayview-0.56.0}/src/arrayview/_routes_loading.py +12 -14
  9. {arrayview-0.55.0 → arrayview-0.56.0}/src/arrayview/_routes_rendering.py +0 -7
  10. {arrayview-0.55.0 → arrayview-0.56.0}/src/arrayview/_routes_state.py +15 -5
  11. {arrayview-0.55.0 → arrayview-0.56.0}/src/arrayview/_server.py +3 -0
  12. {arrayview-0.55.0 → arrayview-0.56.0}/src/arrayview/_viewer.html +762 -181
  13. {arrayview-0.55.0 → arrayview-0.56.0}/src/arrayview/_watch.py +15 -3
  14. {arrayview-0.55.0 → arrayview-0.56.0}/tests/test_api.py +71 -14
  15. {arrayview-0.55.0 → arrayview-0.56.0}/tests/test_backend_shared.py +20 -15
  16. {arrayview-0.55.0 → arrayview-0.56.0}/tests/test_browser.py +75 -0
  17. {arrayview-0.55.0 → arrayview-0.56.0}/tests/test_cli.py +34 -1
  18. {arrayview-0.55.0 → arrayview-0.56.0}/tests/test_nifti_meta.py +15 -0
  19. {arrayview-0.55.0 → arrayview-0.56.0}/.gitignore +0 -0
  20. {arrayview-0.55.0 → arrayview-0.56.0}/LICENSE +0 -0
  21. {arrayview-0.55.0 → arrayview-0.56.0}/README.md +0 -0
  22. {arrayview-0.55.0 → arrayview-0.56.0}/src/arrayview/ARCHITECTURE.md +0 -0
  23. {arrayview-0.55.0 → arrayview-0.56.0}/src/arrayview/__init__.py +0 -0
  24. {arrayview-0.55.0 → arrayview-0.56.0}/src/arrayview/__main__.py +0 -0
  25. {arrayview-0.55.0 → arrayview-0.56.0}/src/arrayview/_analysis.py +0 -0
  26. {arrayview-0.55.0 → arrayview-0.56.0}/src/arrayview/_app.py +0 -0
  27. {arrayview-0.55.0 → arrayview-0.56.0}/src/arrayview/_bootstrap_app.py +0 -0
  28. {arrayview-0.55.0 → arrayview-0.56.0}/src/arrayview/_diagnostics.py +0 -0
  29. {arrayview-0.55.0 → arrayview-0.56.0}/src/arrayview/_dicom.py +0 -0
  30. {arrayview-0.55.0 → arrayview-0.56.0}/src/arrayview/_extra_ports.py +0 -0
  31. {arrayview-0.55.0 → arrayview-0.56.0}/src/arrayview/_icon.png +0 -0
  32. {arrayview-0.55.0 → arrayview-0.56.0}/src/arrayview/_imaging.py +0 -0
  33. {arrayview-0.55.0 → arrayview-0.56.0}/src/arrayview/_instance_registry.py +0 -0
  34. {arrayview-0.55.0 → arrayview-0.56.0}/src/arrayview/_launch_plan.py +0 -0
  35. {arrayview-0.55.0 → arrayview-0.56.0}/src/arrayview/_launch_trace.py +0 -0
  36. {arrayview-0.55.0 → arrayview-0.56.0}/src/arrayview/_lifecycle.py +0 -0
  37. {arrayview-0.55.0 → arrayview-0.56.0}/src/arrayview/_overlays.py +0 -0
  38. {arrayview-0.55.0 → arrayview-0.56.0}/src/arrayview/_platform.py +0 -0
  39. {arrayview-0.55.0 → arrayview-0.56.0}/src/arrayview/_routes_analysis.py +0 -0
  40. {arrayview-0.55.0 → arrayview-0.56.0}/src/arrayview/_routes_drop.py +0 -0
  41. {arrayview-0.55.0 → arrayview-0.56.0}/src/arrayview/_routes_export.py +0 -0
  42. {arrayview-0.55.0 → arrayview-0.56.0}/src/arrayview/_routes_persistence.py +0 -0
  43. {arrayview-0.55.0 → arrayview-0.56.0}/src/arrayview/_routes_preferences.py +0 -0
  44. {arrayview-0.55.0 → arrayview-0.56.0}/src/arrayview/_routes_preload.py +0 -0
  45. {arrayview-0.55.0 → arrayview-0.56.0}/src/arrayview/_routes_query.py +0 -0
  46. {arrayview-0.55.0 → arrayview-0.56.0}/src/arrayview/_routes_segmentation.py +0 -0
  47. {arrayview-0.55.0 → arrayview-0.56.0}/src/arrayview/_routes_vectorfield.py +0 -0
  48. {arrayview-0.55.0 → arrayview-0.56.0}/src/arrayview/_routes_websocket.py +0 -0
  49. {arrayview-0.55.0 → arrayview-0.56.0}/src/arrayview/_segmentation.py +0 -0
  50. {arrayview-0.55.0 → arrayview-0.56.0}/src/arrayview/_session.py +0 -0
  51. {arrayview-0.55.0 → arrayview-0.56.0}/src/arrayview/_session_spec.py +0 -0
  52. {arrayview-0.55.0 → arrayview-0.56.0}/src/arrayview/_shell.html +0 -0
  53. {arrayview-0.55.0 → arrayview-0.56.0}/src/arrayview/_source_safety.py +0 -0
  54. {arrayview-0.55.0 → arrayview-0.56.0}/src/arrayview/_synthetic_mri.py +0 -0
  55. {arrayview-0.55.0 → arrayview-0.56.0}/src/arrayview/_torch.py +0 -0
  56. {arrayview-0.55.0 → arrayview-0.56.0}/src/arrayview/_tutorial.py +0 -0
  57. {arrayview-0.55.0 → arrayview-0.56.0}/src/arrayview/_vectorfield.py +0 -0
  58. {arrayview-0.55.0 → arrayview-0.56.0}/src/arrayview/_view_memory.py +0 -0
  59. {arrayview-0.55.0 → arrayview-0.56.0}/src/arrayview/_vscode.py +0 -0
  60. {arrayview-0.55.0 → arrayview-0.56.0}/src/arrayview/_vscode_browser.py +0 -0
  61. {arrayview-0.55.0 → arrayview-0.56.0}/src/arrayview/_vscode_extension.py +0 -0
  62. {arrayview-0.55.0 → arrayview-0.56.0}/src/arrayview/_vscode_signal.py +0 -0
  63. {arrayview-0.55.0 → arrayview-0.56.0}/src/arrayview/arrayview-opener.vsix +0 -0
  64. {arrayview-0.55.0 → arrayview-0.56.0}/src/arrayview/gsap.min.js +0 -0
  65. {arrayview-0.55.0 → arrayview-0.56.0}/src/arrayview/todo.md +0 -0
  66. {arrayview-0.55.0 → arrayview-0.56.0}/tests/capture_patient_loading.py +0 -0
  67. {arrayview-0.55.0 → arrayview-0.56.0}/tests/capture_v_animation.py +0 -0
  68. {arrayview-0.55.0 → arrayview-0.56.0}/tests/conftest.py +0 -0
  69. {arrayview-0.55.0 → arrayview-0.56.0}/tests/make_vectorfield_test_arrays.py +0 -0
  70. {arrayview-0.55.0 → arrayview-0.56.0}/tests/test_1d_arrays.py +0 -0
  71. {arrayview-0.55.0 → arrayview-0.56.0}/tests/test_config.py +0 -0
  72. {arrayview-0.55.0 → arrayview-0.56.0}/tests/test_dicom.py +0 -0
  73. {arrayview-0.55.0 → arrayview-0.56.0}/tests/test_drop_import.py +0 -0
  74. {arrayview-0.55.0 → arrayview-0.56.0}/tests/test_first_slice_warmup.py +0 -0
  75. {arrayview-0.55.0 → arrayview-0.56.0}/tests/test_glides.py +0 -0
  76. {arrayview-0.55.0 → arrayview-0.56.0}/tests/test_instance_registry.py +0 -0
  77. {arrayview-0.55.0 → arrayview-0.56.0}/tests/test_io.py +0 -0
  78. {arrayview-0.55.0 → arrayview-0.56.0}/tests/test_large_arrays.py +0 -0
  79. {arrayview-0.55.0 → arrayview-0.56.0}/tests/test_launch_blackbox.py +0 -0
  80. {arrayview-0.55.0 → arrayview-0.56.0}/tests/test_mode_roundtrip.py +0 -0
  81. {arrayview-0.55.0 → arrayview-0.56.0}/tests/test_nifti_series.py +0 -0
  82. {arrayview-0.55.0 → arrayview-0.56.0}/tests/test_pane_names.py +0 -0
  83. {arrayview-0.55.0 → arrayview-0.56.0}/tests/test_rgb_pixel_art.py +0 -0
  84. {arrayview-0.55.0 → arrayview-0.56.0}/tests/test_safe_server_stop.py +0 -0
  85. {arrayview-0.55.0 → arrayview-0.56.0}/tests/test_source_safety.py +0 -0
  86. {arrayview-0.55.0 → arrayview-0.56.0}/tests/test_torch.py +0 -0
  87. {arrayview-0.55.0 → arrayview-0.56.0}/tests/test_tutorial.py +0 -0
  88. {arrayview-0.55.0 → arrayview-0.56.0}/tests/test_view_memory.py +0 -0
  89. {arrayview-0.55.0 → arrayview-0.56.0}/tests/test_viewer_port.py +0 -0
  90. {arrayview-0.55.0 → arrayview-0.56.0}/tests/test_vsix_bundle.py +0 -0
  91. {arrayview-0.55.0 → arrayview-0.56.0}/tests/ui_audit.py +0 -0
  92. {arrayview-0.55.0 → arrayview-0.56.0}/tests/v_anim_frames/.gitkeep +0 -0
  93. {arrayview-0.55.0 → arrayview-0.56.0}/tests/visual_smoke.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: arrayview
3
- Version: 0.55.0
3
+ Version: 0.56.0
4
4
  Summary: Fast multi-dimensional array viewer
5
5
  Project-URL: Home, https://github.com/oscarvanderheide/arrayview
6
6
  Project-URL: Source, https://github.com/oscarvanderheide/arrayview
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "arrayview"
7
- version = "0.55.0"
7
+ version = "0.56.0"
8
8
  description = "Fast multi-dimensional array viewer"
9
9
  readme = { file = "README.md", content-type = "text/markdown" }
10
10
  requires-python = ">=3.12"
@@ -16,6 +16,7 @@ _VALID_ENV_KEYS = {"default", "terminal", "vscode", "jupyter", "ssh", "julia"}
16
16
  _VALID_THEMES = {"dark", "light"}
17
17
  _VALID_ORTHO_LAYOUTS = {"horizontal", "big-left"}
18
18
  _VALID_DIMBAR_MODES = {"compact", "extended"}
19
+ _VALID_TURN_ANIMATIONS = {"rotate", "fade"}
19
20
  _CONFIG_LOCK = threading.Lock()
20
21
 
21
22
  WINDOW_PREFERENCE_OPTIONS = {
@@ -43,6 +44,7 @@ BUILTIN_PREFERENCES = {
43
44
  "remember_view": False,
44
45
  "ortho_layout": None,
45
46
  "dimbar_mode": "compact",
47
+ "turn_animation": "rotate",
46
48
  },
47
49
  }
48
50
  PREFERENCE_SCHEMA = {
@@ -56,6 +58,7 @@ PREFERENCE_SCHEMA = {
56
58
  "colormaps": "non-empty list of names",
57
59
  "ortho_layout": sorted(_VALID_ORTHO_LAYOUTS),
58
60
  "dimbar_mode": sorted(_VALID_DIMBAR_MODES),
61
+ "turn_animation": sorted(_VALID_TURN_ANIMATIONS),
59
62
  },
60
63
  "nninteractive": {"url": "string"},
61
64
  }
@@ -143,6 +146,8 @@ def _validate_preference(section: str, key: str, value):
143
146
  return _normalized_string(value, _VALID_ORTHO_LAYOUTS, "viewer.ortho_layout")
144
147
  if section == "viewer" and key == "dimbar_mode":
145
148
  return _normalized_string(value, _VALID_DIMBAR_MODES, "viewer.dimbar_mode")
149
+ if section == "viewer" and key == "turn_animation":
150
+ return _normalized_string(value, _VALID_TURN_ANIMATIONS, "viewer.turn_animation")
146
151
  if section == "nninteractive" and key == "url":
147
152
  if not isinstance(value, str) or not value.strip():
148
153
  raise InvalidPreferenceError("nninteractive.url must be a non-empty string")
@@ -282,6 +287,15 @@ def get_viewer_dimbar_mode() -> str | None:
282
287
  return value.strip().lower() if isinstance(value, str) and value.strip().lower() in _VALID_DIMBAR_MODES else None
283
288
 
284
289
 
290
+ def get_viewer_turn_animation() -> str | None:
291
+ """Return the preferred animation for r / t / o (rotate or fade)."""
292
+ viewer_cfg = load_config().get("viewer", {})
293
+ if not isinstance(viewer_cfg, dict):
294
+ return None
295
+ value = viewer_cfg.get("turn_animation")
296
+ return value.strip().lower() if isinstance(value, str) and value.strip().lower() in _VALID_TURN_ANIMATIONS else None
297
+
298
+
285
299
  def get_nninteractive_url() -> str | None:
286
300
  """Return configured nnInteractive server URL, or None."""
287
301
  env_val = os.environ.get("ARRAYVIEW_NNINTERACTIVE_URL", "").strip()
@@ -135,13 +135,8 @@ def _compute_diff(
135
135
  diff_mode,
136
136
  indices_a=None,
137
137
  indices_b=None,
138
- stats_out=None,
139
138
  ):
140
- """Return raw diff, display range, colormap, and optional separator mask.
141
-
142
- When *stats_out* is a dict it is filled with summary numbers for the
143
- compared view (see `_diff_summary`).
144
- """
139
+ """Return raw diff, display range, colormap, and optional separator mask."""
145
140
  def _parse_indices(raw_indices):
146
141
  if raw_indices is None:
147
142
  return ()
@@ -175,15 +170,15 @@ def _compute_diff(
175
170
  a = _render_values(session_a, dim_x, dim_y, idx_a, complex_mode, log_scale)
176
171
  b = _render_values(session_b, dim_x, dim_y, idx_b, complex_mode, log_scale)
177
172
  b = _resize_values_like(b, a)
178
- if stats_out is not None:
179
- stats_out.update(_diff_summary(a, b, nan_mask))
180
173
  if diff_mode == 1:
181
174
  raw = a - b
182
- lo = float(np.nanpercentile(raw, 1))
183
- hi = float(np.nanpercentile(raw, 99))
175
+ fg = raw[~((a == 0) & (b == 0))]
176
+ fg = fg if fg.size else raw
177
+ lo = float(np.nanpercentile(fg, 1))
178
+ hi = float(np.nanpercentile(fg, 99))
184
179
  vmax = max(abs(lo), abs(hi)) or 1.0
185
180
  vmin = -vmax
186
- colormap = "icefire"
181
+ colormap = "RdBu_r"
187
182
  elif diff_mode == 2:
188
183
  raw = np.abs(a - b)
189
184
  vmax = float(np.nanmax(raw)) or 1.0
@@ -196,32 +191,14 @@ def _compute_diff(
196
191
  vmin = 0.0
197
192
  colormap = "afmhot"
198
193
 
194
+ # Background (zero in both A and B, e.g. outside a masked head) becomes
195
+ # NaN: drawn black like the source panes instead of the colormap's
196
+ # zero colour (white for RdBu_r), and left out of histogram/hover.
197
+ raw = np.asarray(raw, dtype=np.float32)
198
+ raw[(a == 0) & (b == 0)] = np.nan
199
199
  return raw, vmin, vmax, colormap, nan_mask
200
200
 
201
201
 
202
- def _diff_summary(a: np.ndarray, b: np.ndarray, nan_mask: np.ndarray | None) -> dict[str, float]:
203
- """RMS of A−B, largest |A−B|, and RMS of A−B relative to the RMS of A.
204
-
205
- Pixels that are not finite in either array (or are mosaic separators)
206
- are left out. Empty or all-zero inputs give NaN for what is undefined.
207
- """
208
- a = np.asarray(a, dtype=np.float64)
209
- b = np.asarray(b, dtype=np.float64)
210
- valid = np.isfinite(a) & np.isfinite(b)
211
- if nan_mask is not None and nan_mask.shape == valid.shape:
212
- valid &= ~nan_mask
213
- if not valid.any():
214
- return {"rmse": float("nan"), "max_abs": float("nan"), "rel": float("nan")}
215
- d = a[valid] - b[valid]
216
- rmse = float(np.sqrt(np.mean(d * d)))
217
- rms_a = float(np.sqrt(np.mean(a[valid] ** 2)))
218
- return {
219
- "rmse": rmse,
220
- "max_abs": float(np.max(np.abs(d))),
221
- "rel": rmse / rms_a if rms_a > 0 else float("nan"),
222
- }
223
-
224
-
225
202
  def _render_diff_rgba(
226
203
  raw: np.ndarray,
227
204
  vmin: float,
@@ -237,6 +214,7 @@ def _render_diff_rgba(
237
214
  _ensure_lut(colormap)
238
215
  lut = LUTS.get(colormap, LUTS["gray"])
239
216
  rgba = lut_rgba(lut, (normalized * 255).astype(np.uint8))
217
+ rgba[~np.isfinite(raw)] = [0, 0, 0, 255]
240
218
  if nan_mask is not None and nan_mask.shape == rgba.shape[:2]:
241
219
  rgba[nan_mask] = [22, 22, 22, 255]
242
220
  return rgba
@@ -205,11 +205,12 @@ def _select_npz_array(npz, filepath):
205
205
  class _NiftiHeaderOnly:
206
206
  """What a collection scan reads from a NIfTI image, without the image."""
207
207
 
208
- __slots__ = ("shape", "affine", "_dtype")
208
+ __slots__ = ("shape", "affine", "header", "_dtype")
209
209
 
210
210
  def __init__(self, header):
211
211
  self.shape = tuple(int(v) for v in header.get_data_shape())
212
212
  self.affine = header.get_best_affine()
213
+ self.header = header
213
214
  self._dtype = header.get_data_dtype()
214
215
 
215
216
  def get_data_dtype(self):
@@ -246,6 +247,14 @@ def _read_plain_nifti1_header(filepath):
246
247
  return None
247
248
 
248
249
 
250
+ def _header_names_orientation(header):
251
+ """False only for a NIfTI header with neither sform nor qform set."""
252
+ try:
253
+ return int(header["sform_code"]) > 0 or int(header["qform_code"]) > 0
254
+ except Exception:
255
+ return True
256
+
257
+
249
258
  def _nifti_header_with_meta(filepath, *, native=False, header_only=False):
250
259
  """Return a NIfTI image and spatial metadata without reading voxels.
251
260
 
@@ -280,7 +289,13 @@ def _nifti_header_with_meta(filepath, *, native=False, header_only=False):
280
289
  for i in range(3):
281
290
  if canonical_voxel_sizes[i] > 0:
282
291
  norm_rot[:, i] = canonical_rot[:, i] / canonical_voxel_sizes[i]
283
- axis_labels = tuple(str(v) for v in nib.aff2axcodes(data_affine))
292
+ # Without an sform or qform the affine is nibabel's placeholder; naming
293
+ # anatomy from it would turn views on a guess.
294
+ axis_labels = (
295
+ tuple(str(v) for v in nib.aff2axcodes(data_affine))
296
+ if _header_names_orientation(getattr(img, "header", None))
297
+ else ()
298
+ )
284
299
  off_diag_max = max(
285
300
  (abs(norm_rot[i, j]) for i in range(3) for j in range(3) if i != j),
286
301
  default=0.0,
@@ -1251,12 +1266,37 @@ class _FileSeries:
1251
1266
  return result
1252
1267
 
1253
1268
 
1269
+ def forget_cached_volumes(series) -> None:
1270
+ """Drop the volumes a file series has read, so its files are read again."""
1271
+ lock = getattr(series, "_cache_lock", None)
1272
+ if lock is None:
1273
+ return
1274
+ jobs_lock = getattr(series, "_progressive_lock", None)
1275
+ if jobs_lock is not None:
1276
+ with jobs_lock:
1277
+ series._progressive_jobs.clear()
1278
+ with lock:
1279
+ series._vol_cache.clear()
1280
+ if hasattr(series, "_vol_cache_bytes"):
1281
+ series._vol_cache_bytes = 0
1282
+ region_lock = getattr(series, "_region_lock", None)
1283
+ if region_lock is not None:
1284
+ with region_lock:
1285
+ series._region_cache.clear()
1286
+ series._region_cache_bytes = 0
1287
+ series._region_generation += 1
1288
+
1289
+
1254
1290
  class _ArrayStack:
1255
- """Same-shape in-memory arrays seen as one array, cases along a new last dim.
1291
+ """In-memory arrays seen as one array, cases along a new last dim.
1256
1292
 
1257
1293
  What ``view(a, b, ...)`` shows, like several files on the command line.
1258
1294
  No copy: a slice reads straight from its array. ``replace(i, arr)`` swaps
1259
1295
  one case (``handle.update`` of that array's handle).
1296
+
1297
+ Arrays of the same rank but different sizes form a ragged stack, read the
1298
+ way ``_RaggedFileSeries`` is: ``shape`` is the largest size per dim, and a
1299
+ slice comes back in its own array's size.
1260
1300
  """
1261
1301
 
1262
1302
  _av_lazy = True
@@ -1265,16 +1305,26 @@ class _ArrayStack:
1265
1305
  arrays = list(arrays)
1266
1306
  if len(arrays) < 2:
1267
1307
  raise ValueError("a stack needs at least two arrays")
1268
- shape = tuple(int(s) for s in arrays[0].shape)
1269
- if any(tuple(int(s) for s in a.shape) != shape for a in arrays):
1270
- raise ValueError("stacked arrays must all have the same shape")
1308
+ shapes = [tuple(int(s) for s in a.shape) for a in arrays]
1309
+ if len({len(shape) for shape in shapes}) != 1:
1310
+ raise ValueError(
1311
+ "arrays shown side by side must have the same number of "
1312
+ f"dimensions, got shapes {shapes}"
1313
+ )
1271
1314
  self._arrays = arrays
1272
- self._vol_shape = shape
1315
+ self._set_shapes(shapes)
1273
1316
  self._dtype = np.result_type(*[np.dtype(a.dtype) for a in arrays])
1274
- self.shape = (*shape, len(arrays))
1275
1317
  self.ndim = len(self.shape)
1318
+ self._stack_axes = (self.ndim - 1,)
1276
1319
  self.case_names = [str(n) for n in case_names] if case_names else None
1277
1320
 
1321
+ def _set_shapes(self, shapes):
1322
+ self._shapes = shapes
1323
+ self._vol_shape = tuple(max(sizes) for sizes in zip(*shapes))
1324
+ self.shape = (*self._vol_shape, len(shapes))
1325
+ # Only a stack whose arrays differ in size takes the ragged path.
1326
+ self._av_ragged = len(set(shapes)) > 1
1327
+
1278
1328
  @classmethod
1279
1329
  def from_stacked(cls, data, case_names=None):
1280
1330
  """Split an array already stacked along its last dim (no copy)."""
@@ -1286,12 +1336,36 @@ class _ArrayStack:
1286
1336
 
1287
1337
  @property
1288
1338
  def nbytes(self):
1289
- return int(np.prod(self.shape)) * self._dtype.itemsize
1339
+ return int(sum(np.prod(shape) for shape in self._shapes)) * self._dtype.itemsize
1340
+
1341
+ @property
1342
+ def ragged_spatial_shapes(self):
1343
+ return [[shape] for shape in self._shapes]
1344
+
1345
+ def _case(self, idx_list):
1346
+ n = len(self._arrays)
1347
+ case = int(idx_list[-1]) if len(idx_list) >= self.ndim else 0
1348
+ if case < 0:
1349
+ case += n
1350
+ return max(0, min(n - 1, case))
1351
+
1352
+ def spatial_shape_for_indices(self, idx_list):
1353
+ return self._shapes[self._case(idx_list)]
1354
+
1355
+ def clamp_indices(self, idx_list):
1356
+ out = list(idx_list)
1357
+ for dim, size in enumerate(self.spatial_shape_for_indices(out)):
1358
+ if dim < len(out):
1359
+ out[dim] = max(0, min(int(size) - 1, int(out[dim])))
1360
+ if len(out) >= self.ndim:
1361
+ out[self.ndim - 1] = self._case(out)
1362
+ return out
1290
1363
 
1291
1364
  def replace(self, i, arr):
1292
- if tuple(int(s) for s in arr.shape) != self._vol_shape:
1365
+ shape = tuple(int(s) for s in arr.shape)
1366
+ if shape != self._shapes[i]:
1293
1367
  raise ValueError(
1294
- f"array {i + 1} must keep its shape {self._vol_shape}, got {tuple(arr.shape)}"
1368
+ f"array {i + 1} must keep its shape {self._shapes[i]}, got {shape}"
1295
1369
  )
1296
1370
  self._arrays[i] = arr
1297
1371
  self._dtype = np.result_type(*[np.dtype(a.dtype) for a in self._arrays])
@@ -1302,10 +1376,24 @@ class _ArrayStack:
1302
1376
  if not any(k is None or k is Ellipsis for k in key) and len(key) == self.ndim:
1303
1377
  case = key[-1]
1304
1378
  if isinstance(case, (int, np.integer)):
1305
- return np.asarray(self._arrays[int(case)][key[:-1]], dtype=self._dtype)
1379
+ case = self._case(key)
1380
+ spatial_key = key[:-1]
1381
+ if self._av_ragged:
1382
+ shape = self._shapes[case]
1383
+ spatial_key = tuple(
1384
+ max(0, min(shape[d] - 1, int(k) + (shape[d] if int(k) < 0 else 0)))
1385
+ if isinstance(k, (int, np.integer))
1386
+ else k
1387
+ for d, k in enumerate(spatial_key)
1388
+ )
1389
+ return np.asarray(self._arrays[case][spatial_key], dtype=self._dtype)
1390
+ if self._av_ragged:
1391
+ raise TypeError("Arrays of different sizes are read one array at a time.")
1306
1392
  return np.asarray(self)[key]
1307
1393
 
1308
1394
  def __array__(self, dtype=None, copy=None):
1395
+ if self._av_ragged:
1396
+ raise TypeError("Arrays of different sizes cannot be joined into one array.")
1309
1397
  result = np.empty(self.shape, dtype=self._dtype)
1310
1398
  for i, a in enumerate(self._arrays):
1311
1399
  result[..., i] = np.asarray(a)
@@ -1314,6 +1402,30 @@ class _ArrayStack:
1314
1402
  return result
1315
1403
 
1316
1404
 
1405
+ def save_array_stack(stack, filepath):
1406
+ """Write a stack where another process can ``load_array_stack`` it.
1407
+
1408
+ Same-size arrays go into one ``.npy`` along the last dim; arrays of
1409
+ different sizes into an ``.npz``, one entry each. Returns the path written.
1410
+ """
1411
+ if getattr(stack, "_av_ragged", False):
1412
+ filepath = filepath + ".npz"
1413
+ np.savez(filepath, **{f"a{i}": np.asarray(a) for i, a in enumerate(stack._arrays)})
1414
+ else:
1415
+ filepath = filepath + ".npy"
1416
+ np.save(filepath, np.asarray(stack))
1417
+ return filepath
1418
+
1419
+
1420
+ def load_array_stack(filepath, case_names):
1421
+ """Read what ``save_array_stack`` wrote back into an ``_ArrayStack``."""
1422
+ if filepath.endswith(".npz"):
1423
+ with np.load(filepath) as bundle:
1424
+ arrays = [bundle[f"a{i}"] for i in range(len(bundle.files))]
1425
+ return _ArrayStack(arrays, case_names)
1426
+ return _ArrayStack.from_stacked(np.load(filepath), case_names)
1427
+
1428
+
1317
1429
  class _RaggedFileSeries(_ProgressiveNiftiSeriesMixin, _ScatteredRegionMixin):
1318
1430
  """Lazy collection view over same-rank, same-dtype files with varying shapes.
1319
1431