arrayview 0.55.0__py3-none-any.whl → 0.55.1__py3-none-any.whl

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.
arrayview/_config.py CHANGED
@@ -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()
arrayview/_io.py CHANGED
@@ -1251,12 +1251,37 @@ class _FileSeries:
1251
1251
  return result
1252
1252
 
1253
1253
 
1254
+ def forget_cached_volumes(series) -> None:
1255
+ """Drop the volumes a file series has read, so its files are read again."""
1256
+ lock = getattr(series, "_cache_lock", None)
1257
+ if lock is None:
1258
+ return
1259
+ jobs_lock = getattr(series, "_progressive_lock", None)
1260
+ if jobs_lock is not None:
1261
+ with jobs_lock:
1262
+ series._progressive_jobs.clear()
1263
+ with lock:
1264
+ series._vol_cache.clear()
1265
+ if hasattr(series, "_vol_cache_bytes"):
1266
+ series._vol_cache_bytes = 0
1267
+ region_lock = getattr(series, "_region_lock", None)
1268
+ if region_lock is not None:
1269
+ with region_lock:
1270
+ series._region_cache.clear()
1271
+ series._region_cache_bytes = 0
1272
+ series._region_generation += 1
1273
+
1274
+
1254
1275
  class _ArrayStack:
1255
- """Same-shape in-memory arrays seen as one array, cases along a new last dim.
1276
+ """In-memory arrays seen as one array, cases along a new last dim.
1256
1277
 
1257
1278
  What ``view(a, b, ...)`` shows, like several files on the command line.
1258
1279
  No copy: a slice reads straight from its array. ``replace(i, arr)`` swaps
1259
1280
  one case (``handle.update`` of that array's handle).
1281
+
1282
+ Arrays of the same rank but different sizes form a ragged stack, read the
1283
+ way ``_RaggedFileSeries`` is: ``shape`` is the largest size per dim, and a
1284
+ slice comes back in its own array's size.
1260
1285
  """
1261
1286
 
1262
1287
  _av_lazy = True
@@ -1265,16 +1290,26 @@ class _ArrayStack:
1265
1290
  arrays = list(arrays)
1266
1291
  if len(arrays) < 2:
1267
1292
  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")
1293
+ shapes = [tuple(int(s) for s in a.shape) for a in arrays]
1294
+ if len({len(shape) for shape in shapes}) != 1:
1295
+ raise ValueError(
1296
+ "arrays shown side by side must have the same number of "
1297
+ f"dimensions, got shapes {shapes}"
1298
+ )
1271
1299
  self._arrays = arrays
1272
- self._vol_shape = shape
1300
+ self._set_shapes(shapes)
1273
1301
  self._dtype = np.result_type(*[np.dtype(a.dtype) for a in arrays])
1274
- self.shape = (*shape, len(arrays))
1275
1302
  self.ndim = len(self.shape)
1303
+ self._stack_axes = (self.ndim - 1,)
1276
1304
  self.case_names = [str(n) for n in case_names] if case_names else None
1277
1305
 
1306
+ def _set_shapes(self, shapes):
1307
+ self._shapes = shapes
1308
+ self._vol_shape = tuple(max(sizes) for sizes in zip(*shapes))
1309
+ self.shape = (*self._vol_shape, len(shapes))
1310
+ # Only a stack whose arrays differ in size takes the ragged path.
1311
+ self._av_ragged = len(set(shapes)) > 1
1312
+
1278
1313
  @classmethod
1279
1314
  def from_stacked(cls, data, case_names=None):
1280
1315
  """Split an array already stacked along its last dim (no copy)."""
@@ -1286,12 +1321,36 @@ class _ArrayStack:
1286
1321
 
1287
1322
  @property
1288
1323
  def nbytes(self):
1289
- return int(np.prod(self.shape)) * self._dtype.itemsize
1324
+ return int(sum(np.prod(shape) for shape in self._shapes)) * self._dtype.itemsize
1325
+
1326
+ @property
1327
+ def ragged_spatial_shapes(self):
1328
+ return [[shape] for shape in self._shapes]
1329
+
1330
+ def _case(self, idx_list):
1331
+ n = len(self._arrays)
1332
+ case = int(idx_list[-1]) if len(idx_list) >= self.ndim else 0
1333
+ if case < 0:
1334
+ case += n
1335
+ return max(0, min(n - 1, case))
1336
+
1337
+ def spatial_shape_for_indices(self, idx_list):
1338
+ return self._shapes[self._case(idx_list)]
1339
+
1340
+ def clamp_indices(self, idx_list):
1341
+ out = list(idx_list)
1342
+ for dim, size in enumerate(self.spatial_shape_for_indices(out)):
1343
+ if dim < len(out):
1344
+ out[dim] = max(0, min(int(size) - 1, int(out[dim])))
1345
+ if len(out) >= self.ndim:
1346
+ out[self.ndim - 1] = self._case(out)
1347
+ return out
1290
1348
 
1291
1349
  def replace(self, i, arr):
1292
- if tuple(int(s) for s in arr.shape) != self._vol_shape:
1350
+ shape = tuple(int(s) for s in arr.shape)
1351
+ if shape != self._shapes[i]:
1293
1352
  raise ValueError(
1294
- f"array {i + 1} must keep its shape {self._vol_shape}, got {tuple(arr.shape)}"
1353
+ f"array {i + 1} must keep its shape {self._shapes[i]}, got {shape}"
1295
1354
  )
1296
1355
  self._arrays[i] = arr
1297
1356
  self._dtype = np.result_type(*[np.dtype(a.dtype) for a in self._arrays])
@@ -1302,10 +1361,24 @@ class _ArrayStack:
1302
1361
  if not any(k is None or k is Ellipsis for k in key) and len(key) == self.ndim:
1303
1362
  case = key[-1]
1304
1363
  if isinstance(case, (int, np.integer)):
1305
- return np.asarray(self._arrays[int(case)][key[:-1]], dtype=self._dtype)
1364
+ case = self._case(key)
1365
+ spatial_key = key[:-1]
1366
+ if self._av_ragged:
1367
+ shape = self._shapes[case]
1368
+ spatial_key = tuple(
1369
+ max(0, min(shape[d] - 1, int(k) + (shape[d] if int(k) < 0 else 0)))
1370
+ if isinstance(k, (int, np.integer))
1371
+ else k
1372
+ for d, k in enumerate(spatial_key)
1373
+ )
1374
+ return np.asarray(self._arrays[case][spatial_key], dtype=self._dtype)
1375
+ if self._av_ragged:
1376
+ raise TypeError("Arrays of different sizes are read one array at a time.")
1306
1377
  return np.asarray(self)[key]
1307
1378
 
1308
1379
  def __array__(self, dtype=None, copy=None):
1380
+ if self._av_ragged:
1381
+ raise TypeError("Arrays of different sizes cannot be joined into one array.")
1309
1382
  result = np.empty(self.shape, dtype=self._dtype)
1310
1383
  for i, a in enumerate(self._arrays):
1311
1384
  result[..., i] = np.asarray(a)
@@ -1314,6 +1387,30 @@ class _ArrayStack:
1314
1387
  return result
1315
1388
 
1316
1389
 
1390
+ def save_array_stack(stack, filepath):
1391
+ """Write a stack where another process can ``load_array_stack`` it.
1392
+
1393
+ Same-size arrays go into one ``.npy`` along the last dim; arrays of
1394
+ different sizes into an ``.npz``, one entry each. Returns the path written.
1395
+ """
1396
+ if getattr(stack, "_av_ragged", False):
1397
+ filepath = filepath + ".npz"
1398
+ np.savez(filepath, **{f"a{i}": np.asarray(a) for i, a in enumerate(stack._arrays)})
1399
+ else:
1400
+ filepath = filepath + ".npy"
1401
+ np.save(filepath, np.asarray(stack))
1402
+ return filepath
1403
+
1404
+
1405
+ def load_array_stack(filepath, case_names):
1406
+ """Read what ``save_array_stack`` wrote back into an ``_ArrayStack``."""
1407
+ if filepath.endswith(".npz"):
1408
+ with np.load(filepath) as bundle:
1409
+ arrays = [bundle[f"a{i}"] for i in range(len(bundle.files))]
1410
+ return _ArrayStack(arrays, case_names)
1411
+ return _ArrayStack.from_stacked(np.load(filepath), case_names)
1412
+
1413
+
1317
1414
  class _RaggedFileSeries(_ProgressiveNiftiSeriesMixin, _ScatteredRegionMixin):
1318
1415
  """Lazy collection view over same-rank, same-dtype files with varying shapes.
1319
1416