arrayview 0.58.3__py3-none-any.whl → 0.58.4__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/_launcher.py CHANGED
@@ -1038,6 +1038,12 @@ def _server_alive(port: int, timeout: float = 0.5) -> bool:
1038
1038
 
1039
1039
  def _server_pid(port: int) -> int | None:
1040
1040
  """Return the pid of the responding ArrayView server, or None if unreachable."""
1041
+ pids = _server_pids(port)
1042
+ return None if pids is None else pids[0]
1043
+
1044
+
1045
+ def _server_pids(port: int) -> tuple[int | None, int | None] | None:
1046
+ """Return (pid, parent pid) of the responding ArrayView server, or None."""
1041
1047
  url = f"http://{_LOOPBACK_HOST}:{port}/ping"
1042
1048
  try:
1043
1049
  with urllib.request.urlopen(url, timeout=0.5) as resp:
@@ -1045,7 +1051,7 @@ def _server_pid(port: int) -> int | None:
1045
1051
  return None
1046
1052
  payload = json.loads(resp.read().decode("utf-8"))
1047
1053
  if payload.get("ok") is True and payload.get("service") == "arrayview":
1048
- return payload.get("pid")
1054
+ return payload.get("pid"), payload.get("ppid")
1049
1055
  except Exception:
1050
1056
  pass
1051
1057
  return None
@@ -2644,7 +2650,10 @@ def _wait_for_spawned_server(
2644
2650
  return False
2645
2651
  except Exception:
2646
2652
  return False
2647
- if _server_pid(port) == expected_pid:
2653
+ # On Windows a venv's python.exe is a launcher that runs the real
2654
+ # interpreter as its child: the listener then reports *proc* as parent.
2655
+ pids = _server_pids(port)
2656
+ if pids is not None and expected_pid in pids:
2648
2657
  return True
2649
2658
  time.sleep(0.02)
2650
2659
  return False
@@ -2916,7 +2925,7 @@ _TUTORIAL_EXTRAS: dict[str, str] = {}
2916
2925
 
2917
2926
 
2918
2927
  def _register_tutorial_extras(port: int, expected_server_id: str | None = None) -> None:
2919
- """Register the tutorial's vector-field and ragged-collection sessions.
2928
+ """Register the tutorial's vector-field, MRI-head and ragged-collection sessions.
2920
2929
 
2921
2930
  Best effort: a failure here costs two sections, not the tour, so it is
2922
2931
  traced and swallowed rather than allowed to fail a launch that has already
@@ -2958,6 +2967,19 @@ def _register_tutorial_extras_impl(port, bundle, expected_server_id) -> None:
2958
2967
  except Exception as exc: # pragma: no cover - best effort
2959
2968
  _trace_launch_event("tutorial.extra_failed", extra="flow", error=str(exc))
2960
2969
 
2970
+ try:
2971
+ head = _load_session_from_filepath(
2972
+ port,
2973
+ bundle.head_file,
2974
+ "mri-head",
2975
+ expected_server_id=expected_server_id,
2976
+ )
2977
+ head_sid = head.get("sid")
2978
+ if head_sid and "error" not in head:
2979
+ _TUTORIAL_EXTRAS["head"] = str(head_sid)
2980
+ except Exception as exc: # pragma: no cover - best effort
2981
+ _trace_launch_event("tutorial.extra_failed", extra="head", error=str(exc))
2982
+
2961
2983
  try:
2962
2984
  stack = _load_session_from_filepath(
2963
2985
  port,
@@ -2,6 +2,8 @@ import base64
2
2
  import io
3
3
  import itertools
4
4
  import math
5
+ import os
6
+ import threading
5
7
 
6
8
  import numpy as np
7
9
  from fastapi import Body, Depends, Response
@@ -242,6 +244,33 @@ def register_analysis_routes(app, get_session_or_404) -> None:
242
244
 
243
245
  return {"rows": rows}
244
246
 
247
+ @app.get("/roi_floodfill_warm/{sid}")
248
+ def get_roi_floodfill_warm(
249
+ sid: str,
250
+ dim_x: int,
251
+ dim_y: int,
252
+ indices: str,
253
+ scope_dim: int,
254
+ complex_mode: int = 0,
255
+ smooth: float = 0.0,
256
+ session=Depends(get_session_or_404),
257
+ ):
258
+ """Gather (and smooth) the 3D wand volume while the cursor hovers."""
259
+ if session.rgb_axis is not None:
260
+ return {"ok": False}
261
+ shape = session.shape
262
+ idx = [int(v) for v in indices.split(",")][: len(shape)]
263
+ idx += [s // 2 for s in shape[len(idx):]]
264
+ idx = [min(max(v, 0), shape[i] - 1) for i, v in enumerate(idx)]
265
+ if scope_dim in {dim_x, dim_y} or not (0 <= scope_dim < len(shape)):
266
+ return {"ok": False}
267
+ volume, _r = _scoped_floodfill_volume(session, dim_x, dim_y, idx, complex_mode, int(scope_dim))
268
+ smooth = round(max(0.0, min(_FLOODFILL_SMOOTH_MAX, float(smooth))), 2)
269
+ if smooth > 0:
270
+ # Whole volume: every box the grow asks for is then a slice of it.
271
+ _blurred_box(volume, smooth, [0, 0, 0], list(volume.shape))
272
+ return {"ok": True}
273
+
245
274
  @app.get("/roi_floodfill/{sid}")
246
275
  def get_roi_floodfill(
247
276
  sid: str,
@@ -254,8 +283,10 @@ def register_analysis_routes(app, get_session_or_404) -> None:
254
283
  complex_mode: int = 0,
255
284
  scope_dim: int | None = None,
256
285
  preview: bool = False,
286
+ smooth: float = 0.0,
257
287
  session=Depends(get_session_or_404),
258
288
  ):
289
+ smooth = round(max(0.0, min(_FLOODFILL_SMOOTH_MAX, float(smooth))), 2)
259
290
  if session.rgb_axis is not None:
260
291
  return {"error": "not supported for RGB sessions"}
261
292
  idx_tuple = tuple(int(v) for v in indices.split(","))
@@ -271,40 +302,20 @@ def register_analysis_routes(app, get_session_or_404) -> None:
271
302
  complex_mode,
272
303
  scope_dim,
273
304
  preview=preview,
305
+ smooth=smooth,
274
306
  )
275
307
  raw = extract_slice(session, dim_x, dim_y, list(idx_tuple))
276
308
  data = apply_complex_mode(raw, complex_mode)
277
309
  h, w = data.shape
278
310
  if not (0 <= py < h and 0 <= px < w):
279
311
  return {"error": "seed out of bounds"}
280
- seed_val = float(data[py, px])
281
- try:
282
- from scipy.ndimage import label
283
-
284
- abs_tol = tolerance * (
285
- np.nanmax(np.abs(data)) - np.nanmin(np.abs(data)) + 1e-10
286
- )
287
- mask = np.abs(data - seed_val) <= abs_tol
288
- labeled, _n_features = label(mask)
289
- seed_label = labeled[py, px]
290
- if seed_label == 0:
291
- return {"error": "seed outside tolerance region"}
292
- component = labeled == seed_label
293
- except ImportError:
294
- abs_tol = tolerance * (
295
- np.nanmax(np.abs(data)) - np.nanmin(np.abs(data)) + 1e-10
296
- )
297
- component = np.zeros((h, w), dtype=bool)
298
- stack = [(py, px)]
299
- component[py, px] = True
300
- while stack:
301
- cy, cx = stack.pop()
302
- for dy, dx in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
303
- ny, nx = cy + dy, cx + dx
304
- if 0 <= ny < h and 0 <= nx < w and not component[ny, nx]:
305
- if abs(float(data[ny, nx]) - seed_val) <= abs_tol:
306
- component[ny, nx] = True
307
- stack.append((ny, nx))
312
+ abs_tol = tolerance * (
313
+ np.nanmax(np.abs(data)) - np.nanmin(np.abs(data)) + 1e-10
314
+ )
315
+ component, seed_val, _box, _crop = _grow_floodfill(data[None], (0, py, px), abs_tol, smooth)
316
+ component = component[0]
317
+ if not component.any():
318
+ return {"error": "seed outside tolerance region"}
308
319
  roi = data[component]
309
320
  finite = roi[np.isfinite(roi)]
310
321
  ys, xs = np.where(component)
@@ -326,6 +337,7 @@ def register_analysis_routes(app, get_session_or_404) -> None:
326
337
  "n": int(finite.size),
327
338
  "seed_value": _safe_float(seed_val),
328
339
  "tolerance": tolerance,
340
+ "smooth": smooth,
329
341
  "abs_tol": _safe_float(abs_tol),
330
342
  "bbox": bbox,
331
343
  "mask_b64": _encode_mask_b64(component, bbox),
@@ -631,8 +643,249 @@ def register_analysis_routes(app, get_session_or_404) -> None:
631
643
  def _encode_mask_b64(mask: np.ndarray, bbox: dict) -> str:
632
644
  x0, y0 = bbox["x0"], bbox["y0"]
633
645
  x1, y1 = bbox["x1"], bbox["y1"]
634
- sub = mask[y0 : y1 + 1, x0 : x1 + 1].astype(np.uint8)
635
- return base64.b64encode(sub.tobytes()).decode("ascii")
646
+ sub = mask[y0 : y1 + 1, x0 : x1 + 1]
647
+ # Bit-packed, lowest bit first. Readers tell packed from one-byte-per-pixel
648
+ # masks by length (see _decode_mask_bytes).
649
+ return base64.b64encode(
650
+ np.packbits(sub, axis=None, bitorder="little").tobytes()
651
+ ).decode("ascii")
652
+
653
+
654
+ def _decode_mask_bytes(encoded: str, n: int) -> np.ndarray:
655
+ """Decode a base64 mask of *n* pixels, packed or one byte per pixel."""
656
+ raw = np.frombuffer(base64.b64decode(encoded), dtype=np.uint8)
657
+ if raw.size != n and raw.size == (n + 7) // 8:
658
+ return np.unpackbits(raw, count=n, bitorder="little").astype(bool)
659
+ return raw.astype(bool)
660
+
661
+
662
+ # Last stacked volume a scoped flood fill grew through. Dragging the
663
+ # sensitivity re-runs the fill many times on the same volume; restacking it and
664
+ # rescanning its value range each step is wasted work. One entry only.
665
+ _FLOODFILL_VOLUME_CACHE: dict = {}
666
+ _FLOODFILL_VOLUME_LOCK = threading.Lock()
667
+ # Last scoped grow, so the release request reuses the region the last drag
668
+ # step already grew instead of growing it again (the grow dominates release).
669
+ _FLOODFILL_GROW_CACHE: dict = {}
670
+ # Recent smoothed copies of the image: (volume, smooth, lo, hi, blurred).
671
+ # Dragging only the sensitivity reuses them; a box inside one is a slice of it.
672
+ _FLOODFILL_BLUR_CACHE: dict = {}
673
+
674
+
675
+ def _blurred_box(volume, smooth, elo, ehi):
676
+ """In-plane blur of volume[elo:ehi] (sigma smooth/2), reusing a recent one.
677
+
678
+ Two entries: the seed-plane sizing pass and the 3D box would evict each
679
+ other from a single slot on every sensitivity step.
680
+ """
681
+ entries = _FLOODFILL_BLUR_CACHE.get("entries", [])
682
+ for vol, sm, lo, hi, arr in entries:
683
+ if vol is volume and sm == smooth and all(lo[i] <= elo[i] and ehi[i] <= hi[i] for i in range(3)):
684
+ return arr[
685
+ elo[0] - lo[0]: ehi[0] - lo[0],
686
+ elo[1] - lo[1]: ehi[1] - lo[1],
687
+ elo[2] - lo[2]: ehi[2] - lo[2],
688
+ ]
689
+ sub = volume[elo[0]:ehi[0], elo[1]:ehi[1], elo[2]:ehi[2]]
690
+ out = _blur_planes(sub, smooth / 2.0)
691
+ _FLOODFILL_BLUR_CACHE["entries"] = [(volume, smooth, list(elo), list(ehi), out)] + entries[:1]
692
+ return out
693
+
694
+
695
+ # Edge smoothing for the magic wand, a continuous level s in 0 (off) ..
696
+ # _FLOODFILL_SMOOTH_MAX. Compare a copy of the image blurred in-plane with
697
+ # sigma s/2, then blur the grown mask in-plane with sigma s, keep > 0.5, keep
698
+ # the seed's piece and fill in-plane holes. The viewer repeats this exactly for
699
+ # its instant single-slice preview (_roiLocalFloodFill) — keep the two in step.
700
+ _FLOODFILL_SMOOTH_MAX = 5.0
701
+
702
+
703
+ _FLOODFILL_POOL = None
704
+
705
+
706
+ def _by_plane_chunks(fn, arr: np.ndarray) -> np.ndarray:
707
+ """fn applied to z-chunks of a [z, y, x] array on a few threads (scipy
708
+ releases the GIL). Only for per-plane work: the result equals fn(arr)."""
709
+ global _FLOODFILL_POOL
710
+ nt = min(4, os.cpu_count() or 1, arr.shape[0])
711
+ if nt < 2 or arr.size < 1_000_000:
712
+ return fn(arr)
713
+ if _FLOODFILL_POOL is None:
714
+ from concurrent.futures import ThreadPoolExecutor
715
+
716
+ _FLOODFILL_POOL = ThreadPoolExecutor(4, thread_name_prefix="av-floodfill")
717
+ bounds = np.linspace(0, arr.shape[0], nt + 1).astype(int)
718
+ parts = list(_FLOODFILL_POOL.map(lambda i: fn(arr[bounds[i]:bounds[i + 1]]), range(nt)))
719
+ return np.concatenate(parts, axis=0)
720
+
721
+
722
+ def _blur_planes(values: np.ndarray, sigma: float) -> np.ndarray:
723
+ """Gaussian blur of each [y, x] plane of a [z, y, x] array; NaNs ignored."""
724
+ return _by_plane_chunks(lambda a: _blur_planes_one(a, sigma), values)
725
+
726
+
727
+ def _blur_planes_one(values: np.ndarray, sigma: float) -> np.ndarray:
728
+ from scipy.ndimage import gaussian_filter
729
+
730
+ sig = (0, sigma, sigma)
731
+ valid = np.isfinite(values)
732
+ if valid.all():
733
+ return gaussian_filter(values.astype(np.float32), sig, mode="reflect", truncate=4.0)
734
+ num = gaussian_filter(np.where(valid, values, 0).astype(np.float32), sig, mode="reflect", truncate=4.0)
735
+ den = gaussian_filter(valid.astype(np.float32), sig, mode="reflect", truncate=4.0)
736
+ with np.errstate(invalid="ignore", divide="ignore"):
737
+ out = num / den
738
+ out[~valid] = np.nan
739
+ return out
740
+
741
+
742
+ def _grow_in_box(volume, seed, abs_tol, smooth, lo, hi):
743
+ """Grow inside box [lo, hi). Returns (crop mask, seed value, axes hit).
744
+
745
+ *axes hit* lists the axes where the region could reach past an inner box
746
+ face (one that is not the volume edge): then the box result may differ
747
+ from the whole-volume one and the caller must retry with a bigger box.
748
+ """
749
+ shape = volume.shape
750
+ if smooth > 0:
751
+ r_img = int(4.0 * (smooth / 2.0) + 0.5)
752
+ r_mask = int(4.0 * smooth + 0.5)
753
+ else:
754
+ r_img = r_mask = 0
755
+ # The image blur needs r_img of real neighbours in-plane around the box.
756
+ elo = [lo[0]] + [max(0, lo[i] - r_img) for i in (1, 2)]
757
+ ehi = [hi[0]] + [min(shape[i], hi[i] + r_img) for i in (1, 2)]
758
+ img = _blurred_box(volume, smooth, elo, ehi) if smooth > 0 else volume[elo[0]:ehi[0], elo[1]:ehi[1], elo[2]:ehi[2]]
759
+ img = img[
760
+ :,
761
+ lo[1] - elo[1]: lo[1] - elo[1] + (hi[1] - lo[1]),
762
+ lo[2] - elo[2]: lo[2] - elo[2] + (hi[2] - lo[2]),
763
+ ]
764
+ local = tuple(seed[i] - lo[i] for i in range(3))
765
+ seed_val = float(img[local])
766
+ grown = _connected_component(np.abs(img - seed_val) <= abs_tol, local)
767
+ # Clearance from inner faces: one voxel along the stack (the grow could
768
+ # step through), r_mask + 1 in-plane (the mask blur must see only zeros).
769
+ hit = []
770
+ for axis, margin in ((0, 1), (1, r_mask + 1), (2, r_mask + 1)):
771
+ n = grown.shape[axis]
772
+ if (lo[axis] > 0 and np.take(grown, range(min(margin, n)), axis=axis).any()) or (
773
+ hi[axis] < shape[axis] and np.take(grown, range(max(0, n - margin), n), axis=axis).any()
774
+ ):
775
+ hit.append(axis)
776
+ if hit or smooth <= 0 or not grown.any():
777
+ return grown, seed_val, hit
778
+ # Round the edge only around the region: its bounding box plus the mask
779
+ # blur reach (outside it the blurred mask is exactly zero).
780
+ zz, yy, xx = (np.flatnonzero(grown.any(axis=a)) for a in ((1, 2), (0, 2), (0, 1)))
781
+ sub = (
782
+ slice(zz[0], zz[-1] + 1),
783
+ slice(max(0, yy[0] - r_mask - 1), min(grown.shape[1], yy[-1] + r_mask + 2)),
784
+ slice(max(0, xx[0] - r_mask - 1), min(grown.shape[2], xx[-1] + r_mask + 2)),
785
+ )
786
+ sub_seed = tuple(local[i] - sub[i].start for i in range(3))
787
+ rounded = _blur_planes(grown[sub].astype(np.float32), float(smooth)) > 0.5
788
+ rounded = _connected_component(rounded, sub_seed)
789
+ if not rounded.any():
790
+ return grown, seed_val, hit
791
+ rounded = _fill_holes_in_plane(rounded)
792
+ out = np.zeros_like(grown)
793
+ out[sub] = rounded
794
+ return out, seed_val, hit
795
+
796
+
797
+ def _fill_holes_in_plane(mask):
798
+ """binary_fill_holes on every [y, x] plane of a [z, y, x] mask."""
799
+ return _by_plane_chunks(_fill_holes_in_plane_one, mask)
800
+
801
+
802
+ def _fill_holes_in_plane_one(mask):
803
+ """binary_fill_holes on every [y, x] plane of a [z, y, x] mask, in one pass.
804
+
805
+ Background is labelled with 4-connectivity within each plane only; pieces
806
+ that touch a plane's y/x border are outside, the rest are holes.
807
+ """
808
+ from scipy.ndimage import label
809
+
810
+ st = np.zeros((3, 3, 3), dtype=bool)
811
+ st[1, 1, :] = st[1, :, 1] = True
812
+ bg = ~mask
813
+ lab, n = label(bg, structure=st)
814
+ outside = np.zeros(n + 1, dtype=bool)
815
+ for face in (lab[:, 0, :], lab[:, -1, :], lab[:, :, 0], lab[:, :, -1]):
816
+ outside[face.ravel()] = True
817
+ outside[0] = True # label 0 is the mask itself
818
+ return mask | ~outside[lab]
819
+
820
+
821
+ def _grow_floodfill(volume, seed, abs_tol, smooth=0.0):
822
+ """Region of [z, y, x] *volume* joined to *seed*.
823
+
824
+ Returns (full mask, seed value, box slices, mask inside the box). Works in
825
+ a box around the seed and doubles it until the region fits, so a compact
826
+ region in a big volume costs only its own neighbourhood.
827
+ """
828
+ if smooth > 0:
829
+ try:
830
+ import scipy.ndimage # noqa: F401
831
+ except ImportError:
832
+ smooth = 0.0
833
+ shape = volume.shape
834
+ half = [24, 32, 32]
835
+ if shape[0] > 1:
836
+ # Size the first box from the region on the seed's own plane, so a
837
+ # big region does not walk up through several small boxes.
838
+ plo = [seed[0], 0, 0]
839
+ phi = [seed[0] + 1, shape[1], shape[2]]
840
+ plane, _v, _h = _grow_in_box(volume, seed, abs_tol, smooth, plo, phi)
841
+ ys, xs = np.flatnonzero(plane[0].any(axis=1)), np.flatnonzero(plane[0].any(axis=0))
842
+ if ys.size:
843
+ reach = max(seed[1] - ys[0], ys[-1] - seed[1], seed[2] - xs[0], xs[-1] - seed[2]) + 8
844
+ half = [max(24, reach), max(32, reach), max(32, reach)]
845
+ while True:
846
+ lo = [max(0, seed[i] - half[i]) for i in range(3)]
847
+ hi = [min(shape[i], seed[i] + half[i] + 1) for i in range(3)]
848
+ crop, seed_val, hit = _grow_in_box(volume, seed, abs_tol, smooth, lo, hi)
849
+ if not hit:
850
+ break
851
+ for axis in hit:
852
+ half[axis] *= 2
853
+ box = tuple(slice(lo[i], hi[i]) for i in range(3))
854
+ full = np.zeros(shape, dtype=bool)
855
+ full[box] = crop
856
+ return full, seed_val, box, crop
857
+
858
+
859
+ def _scoped_floodfill_volume(session, dim_x, dim_y, indices, complex_mode, scope_dim):
860
+ """Return ``(volume, abs_range)`` for a scoped grow; volume is [scope, y, x]."""
861
+ other = tuple(v for i, v in enumerate(indices) if i not in (dim_x, dim_y, scope_dim))
862
+ key = (
863
+ session.sid,
864
+ id(session.data),
865
+ getattr(session, "data_version", 0),
866
+ int(dim_x),
867
+ int(dim_y),
868
+ int(scope_dim),
869
+ int(complex_mode),
870
+ other,
871
+ )
872
+ with _FLOODFILL_VOLUME_LOCK:
873
+ hit = _FLOODFILL_VOLUME_CACHE.get("entry")
874
+ if hit is not None and hit[0] == key:
875
+ return hit[1], hit[2]
876
+ planes = []
877
+ for value in range(session.shape[scope_dim]):
878
+ idx = list(indices)
879
+ idx[scope_dim] = value
880
+ planes.append(
881
+ apply_complex_mode(extract_slice(session, dim_x, dim_y, idx), complex_mode)
882
+ )
883
+ volume = np.stack(planes, axis=0)
884
+ mag = np.abs(volume)
885
+ abs_range = float(np.nanmax(mag) - np.nanmin(mag) + 1e-10)
886
+ with _FLOODFILL_VOLUME_LOCK:
887
+ _FLOODFILL_VOLUME_CACHE["entry"] = (key, volume, abs_range)
888
+ return volume, abs_range
636
889
 
637
890
 
638
891
  def _scoped_floodfill_response(
@@ -646,6 +899,7 @@ def _scoped_floodfill_response(
646
899
  complex_mode: int,
647
900
  scope_dim: int,
648
901
  preview: bool = False,
902
+ smooth: float = 0.0,
649
903
  ) -> dict:
650
904
  shape = session.shape
651
905
  if len(indices) < len(shape):
@@ -659,28 +913,27 @@ def _scoped_floodfill_response(
659
913
  return {"error": "scope_dim must be exactly one non-display dimension"}
660
914
 
661
915
  values = list(range(shape[scope_dim]))
662
- planes = []
663
- for value in values:
664
- idx = list(indices)
665
- idx[scope_dim] = value
666
- planes.append(
667
- apply_complex_mode(
668
- extract_slice(session, dim_x, dim_y, idx), complex_mode
669
- )
670
- )
671
- volume = np.stack(planes, axis=0)
916
+ volume, abs_range = _scoped_floodfill_volume(
917
+ session, dim_x, dim_y, indices, complex_mode, scope_dim
918
+ )
672
919
  depth, h, w = volume.shape
673
920
  if not (0 <= py < h and 0 <= px < w):
674
921
  return {"error": "seed out of bounds"}
675
922
 
676
923
  seed_z = values.index(indices[scope_dim])
677
- seed_val = float(volume[seed_z, py, px])
678
- abs_tol = tolerance * (
679
- np.nanmax(np.abs(volume)) - np.nanmin(np.abs(volume)) + 1e-10
680
- )
681
- mask = np.abs(volume - seed_val) <= abs_tol
682
- component = _connected_component(mask, (seed_z, py, px))
683
- roi_values = volume[component]
924
+ abs_tol = tolerance * abs_range
925
+ grow_key = ((seed_z, py, px), float(abs_tol), float(smooth))
926
+ with _FLOODFILL_VOLUME_LOCK:
927
+ hit = _FLOODFILL_GROW_CACHE.get("entry")
928
+ if hit is not None and hit[0] is volume and hit[1] == grow_key:
929
+ component, seed_val, box, crop = hit[2]
930
+ else:
931
+ component, seed_val, box, crop = _grow_floodfill(
932
+ volume, (seed_z, py, px), abs_tol, smooth
933
+ )
934
+ with _FLOODFILL_VOLUME_LOCK:
935
+ _FLOODFILL_GROW_CACHE["entry"] = (volume, grow_key, (component, seed_val, box, crop))
936
+ roi_values = volume[box][crop]
684
937
  finite = roi_values[np.isfinite(roi_values)]
685
938
 
686
939
  if preview:
@@ -701,12 +954,19 @@ def _scoped_floodfill_response(
701
954
  "n": int(finite.size),
702
955
  "seed_value": _safe_float(seed_val),
703
956
  "tolerance": tolerance,
957
+ "smooth": smooth,
704
958
  "abs_tol": _safe_float(abs_tol),
705
959
  "bbox": bbox,
706
960
  "mask_b64": _encode_mask_b64(plane, bbox),
707
961
  "preview": True,
708
962
  }
709
963
 
964
+ # Release: the drag is over, so free the held volume.
965
+ with _FLOODFILL_VOLUME_LOCK:
966
+ _FLOODFILL_VOLUME_CACHE.clear()
967
+ _FLOODFILL_GROW_CACHE.clear()
968
+ _FLOODFILL_BLUR_CACHE.clear()
969
+
710
970
  slices = []
711
971
  scoped_values = []
712
972
  for z in range(depth):
@@ -743,7 +1003,10 @@ def _scoped_floodfill_response(
743
1003
  # every multiview pane, not just the plane it was seeded on. Shape
744
1004
  # axes are [scope_dim, dim_y, dim_x] (the grow axes); grow_dim_x /
745
1005
  # grow_dim_y record which data dims those are.
746
- "mask3d_b64": base64.b64encode(component.astype(np.uint8).tobytes()).decode("ascii"),
1006
+ # Bit-packed (LSB first, C order): 8x smaller than one byte per voxel.
1007
+ "mask3d_b64": base64.b64encode(
1008
+ np.packbits(component, axis=None, bitorder="little").tobytes()
1009
+ ).decode("ascii"),
747
1010
  "mask3d_shape": [int(s) for s in component.shape],
748
1011
  "grow_dim_x": int(dim_x),
749
1012
  "grow_dim_y": int(dim_y),
@@ -760,6 +1023,7 @@ def _scoped_floodfill_response(
760
1023
  "n": int(finite.size),
761
1024
  "seed_value": _safe_float(seed_val),
762
1025
  "tolerance": tolerance,
1026
+ "smooth": smooth,
763
1027
  "abs_tol": _safe_float(abs_tol),
764
1028
  "bbox": current_slice["bbox"] if current_slice else {"x0": 0, "y0": 0, "x1": 0, "y1": 0},
765
1029
  "mask_b64": current_slice["mask_b64"] if current_slice else "",
@@ -950,8 +1214,7 @@ def _floodfill_roi_mask(
950
1214
  bh = y1 - y0 + 1
951
1215
  if bw <= 0 or bh <= 0:
952
1216
  return mask
953
- sub = np.frombuffer(base64.b64decode(encoded), dtype=np.uint8)
954
- sub = sub.reshape((bh, bw)).astype(bool)
1217
+ sub = _decode_mask_bytes(encoded, bw * bh).reshape((bh, bw))
955
1218
  except Exception:
956
1219
  return mask
957
1220
  xa0, ya0 = max(0, x0), max(0, y0)
arrayview/_session.py CHANGED
@@ -157,6 +157,9 @@ def ping_payload(*, active_sessions: int) -> dict:
157
157
  "ok": True,
158
158
  "service": "arrayview",
159
159
  "pid": os.getpid(),
160
+ # Windows venv python.exe is a launcher that runs the real
161
+ # interpreter as its child, so the spawner only knows the parent pid.
162
+ "ppid": os.getppid(),
160
163
  "uid": os.geteuid() if hasattr(os, "geteuid") else None,
161
164
  "hostname": _socket.gethostname(),
162
165
  "protocol_version": runtime.protocol_version,
arrayview/_tutorial.py CHANGED
@@ -32,6 +32,7 @@ class TutorialBundle:
32
32
  flow_file: str
33
33
  flow_field_file: str
34
34
  stack_pattern: str
35
+ head_file: str
35
36
 
36
37
 
37
38
  # The main tutorial array is a small pixel-art campsite. It is 4D so every
@@ -425,6 +426,113 @@ def make_tutorial_arrays():
425
426
  )
426
427
 
427
428
 
429
+ # The volume chapter uses a made-up MRI head instead of the campsite:
430
+ # swapping axes, rotating and stepping through anatomical views only make
431
+ # sense on something with three real spatial axes. 2 mm voxels; y index 0
432
+ # is the front, z index 0 the top.
433
+ _HEAD_SHAPE = (96, 112, 80) # x (right-left), y (front-back), z (top-bottom), 2 mm voxels
434
+ _HEAD_TE = (10.0, 40.0, 80.0, 140.0) # ms
435
+ _HEAD_TR = (400.0, 1200.0, 4000.0) # ms
436
+ # tissue: (T1 ms, T2 ms, PD)
437
+ _HEAD_TISSUE = {
438
+ "air": (1.0, 1.0, 0.0),
439
+ "fat": (350.0, 70.0, 0.95),
440
+ "bone": (500.0, 10.0, 0.05),
441
+ "csf": (4000.0, 1800.0, 1.0),
442
+ "gm": (1400.0, 100.0, 0.84),
443
+ "muscle": (900.0, 45.0, 0.7),
444
+ "wm": (700.0, 70.0, 0.66),
445
+ }
446
+
447
+
448
+ def make_head_arrays():
449
+ """Return a made-up MRI head as (x, y, z, echo time, repetition time).
450
+
451
+ Each tissue has a T1, T2 and proton density; the signal at each echo
452
+ and repetition time is the spin-echo formula, with a little noise. The
453
+ two small trailing dims are there to try Shift+arrow layouts on.
454
+ """
455
+ import numpy as np
456
+ from scipy import ndimage
457
+
458
+ nx, ny, nz = _HEAD_SHAPE
459
+ rng = np.random.default_rng(11)
460
+ x = (np.arange(nx) - (nx - 1) / 2) * 2.0
461
+ y = (np.arange(ny) - (ny - 1) / 2) * 2.0
462
+ z = (np.arange(nz) - (nz - 1) / 2) * 2.0
463
+ X, Y, Z = np.meshgrid(x, y, z, indexing="ij")
464
+ Zu = -Z # z index 0 is the top of the head
465
+
466
+ def ell(cx, cy, cz, ax, ay, az):
467
+ return np.sqrt(((X - cx) / ax) ** 2 + ((Y - cy) / ay) ** 2 + ((Zu - cz) / az) ** 2)
468
+
469
+ def smooth_noise(sigma, amp):
470
+ n = ndimage.gaussian_filter(rng.standard_normal(_HEAD_SHAPE), sigma)
471
+ return amp * n / (n.std() + 1e-9)
472
+
473
+ label = np.zeros(_HEAD_SHAPE, dtype=np.uint8) # 0 air 1 fat 2 bone 3 csf 4 gm 5 wm
474
+ head = ell(0, 6, -2, 76, 100, 84)
475
+ label[head < 1.0] = 1
476
+ label[head < 0.93] = 2
477
+ brain = ell(0, 2, 10, 64, 84, 60)
478
+ label[brain < 1.0] = 3
479
+ # Folded cortex: sulci are narrow valleys along the zero lines of a
480
+ # smooth random field, read on a shell so they run straight inwards.
481
+ field = smooth_noise(2.5, 1.0)
482
+ c = np.array([nx - 1, ny - 1, nz - 1], np.float32) / 2
483
+ rho = np.maximum(brain, 1e-3)
484
+ idx = np.stack([c[0] + (np.arange(nx)[:, None, None] - c[0]) * 0.85 / rho,
485
+ c[1] + (np.arange(ny)[None, :, None] - c[1]) * 0.85 / rho,
486
+ c[2] + (np.arange(nz)[None, None, :] - c[2]) * 0.85 / rho])
487
+ shell = ndimage.map_coordinates(field, idx.reshape(3, -1), order=1, mode="nearest").reshape(_HEAD_SHAPE)
488
+ valley = np.exp(-(shell / 0.35) ** 2)
489
+ surface = 0.97 - 0.30 * valley
490
+ inside = brain < 1.0
491
+ label[inside & (brain < surface)] = 4
492
+ label[inside & (brain < surface - 0.10)] = 5
493
+ # Each hemisphere has cortex on its inner face too, with the corpus
494
+ # callosum bridging them just above the ventricles.
495
+ label[(np.abs(X) < 7.0) & (label == 5)] = 4
496
+ callosum = ell(0, 2, 18, 9, 36, 5) < 1.0
497
+ label[callosum & (label >= 4)] = 5
498
+ # between the hemispheres, down to the callosum
499
+ label[(np.abs(X) < 2.2) & (brain < 1.0) & (Zu > 23 - 0.25 * np.abs(Y)) & ~callosum] = 3
500
+ # ventricles and deep grey matter
501
+ for s in (-1, 1):
502
+ label[ell(s * 9, 6, 10, 5.5, 26, 9) < 1.0] = 3
503
+ label[ell(s * 14, 10, 2, 5, 9, 11) < 1.0] = 3 # horns going back and down
504
+ label[(ell(s * 20, -2, 2, 8, 13, 9) < 1.0)] = 4 # basal ganglia
505
+ # cerebellum and brain stem, low at the back
506
+ cereb = ell(0, 52, -38, 46, 26, 20)
507
+ label[(cereb < 1.0) & (label <= 2)] = 3
508
+ label[cereb < 0.9] = 4
509
+ leaves = np.sin(Zu * 0.9 + np.abs(X) * 0.15) > 0.55
510
+ label[(cereb < 0.65) & leaves] = 5
511
+ stem = np.sqrt((X / 8) ** 2 + ((Y - 18) / 10) ** 2) < 1.0
512
+ label[stem & (Zu < -4) & (Zu > -70)] = 5
513
+
514
+ # skull base and neck under the brain
515
+ gap = (head < 0.88) & (label == 2)
516
+ label[gap] = 3
517
+ label[gap & (brain > 1.12) & (cereb > 1.12)] = 6
518
+ names = ["air", "fat", "bone", "csf", "gm", "wm", "muscle"]
519
+ t1 = np.array([_HEAD_TISSUE[n][0] for n in names], np.float32)[label]
520
+ t2 = np.array([_HEAD_TISSUE[n][1] for n in names], np.float32)[label]
521
+ pd = np.array([_HEAD_TISSUE[n][2] for n in names], np.float32)[label]
522
+ # soft edges, as a real scan blurs tissue boundaries
523
+ t1 = ndimage.gaussian_filter(t1, 0.6)
524
+ t2 = ndimage.gaussian_filter(t2, 0.6)
525
+ pd = ndimage.gaussian_filter(pd, 0.6)
526
+ bias = 1.0 + 0.15 * (Y / 112) - 0.1 * (Zu / 80)
527
+ out = np.empty(_HEAD_SHAPE + (len(_HEAD_TE), len(_HEAD_TR)), np.float32)
528
+ for j, tr in enumerate(_HEAD_TR):
529
+ for i, te in enumerate(_HEAD_TE):
530
+ s = pd * bias * (1 - np.exp(-tr / t1)) * np.exp(-te / t2)
531
+ noise = 0.012 * (rng.standard_normal(_HEAD_SHAPE) + 1j * rng.standard_normal(_HEAD_SHAPE))
532
+ out[..., i, j] = np.abs(s + noise)
533
+ return out
534
+
535
+
428
536
  def make_flow_arrays():
429
537
  """Return a volume and a matching displacement field.
430
538
 
@@ -497,6 +605,7 @@ def create_tutorial_bundle() -> TutorialBundle:
497
605
  flow_file=os.path.join(extras, "flow-volume.npy"),
498
606
  flow_field_file=os.path.join(extras, "flow-field.npy"),
499
607
  stack_pattern=os.path.join(cases_dir, "*", "scan.npy"),
608
+ head_file=os.path.join(extras, "mri-head.nii.gz"),
500
609
  )
501
610
  try:
502
611
  base, compare, overlay = make_tutorial_arrays()
@@ -508,6 +617,14 @@ def create_tutorial_bundle() -> TutorialBundle:
508
617
  np.save(bundle.flow_file, flow)
509
618
  np.save(bundle.flow_field_file, field)
510
619
 
620
+ # A NIfTI with a real orientation, so `o` names the views and shows
621
+ # each one upright. y index 0 is the front and z index 0 the top,
622
+ # hence the negative steps.
623
+ import nibabel as nib
624
+
625
+ affine = np.diag([2.0, -2.0, -2.0, 1.0])
626
+ nib.save(nib.Nifti1Image(make_head_arrays(), affine), bundle.head_file)
627
+
511
628
  for index, volume in enumerate(make_stack_arrays(), start=1):
512
629
  case_dir = os.path.join(cases_dir, f"case{index:02d}")
513
630
  os.makedirs(case_dir, exist_ok=True)