arrayview 0.57.0__py3-none-any.whl → 0.58.2__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
@@ -18,6 +18,7 @@ _VALID_ORTHO_LAYOUTS = {"horizontal", "big-left"}
18
18
  _VALID_DIMBAR_MODES = {"compact", "extended"}
19
19
  _VALID_TURN_ANIMATIONS = {"rotate", "fade"}
20
20
  _VALID_QMRI_STARTS = {"picker", "straight"}
21
+ _VALID_ROI_SHAPES = {"circle", "rect", "freehand", "floodfill"}
21
22
  # What q opens in qMRI: parameter maps by role, synthetic contrasts by name.
22
23
  QMRI_START_NAMES = (
23
24
  "t1", "t2", "pd", "b1", "db0", "phase",
@@ -52,6 +53,7 @@ BUILTIN_PREFERENCES = {
52
53
  "dimbar_mode": "compact",
53
54
  "turn_animation": "rotate",
54
55
  "qmri_start": "picker",
56
+ "roi_shape": "circle",
55
57
  },
56
58
  }
57
59
  PREFERENCE_SCHEMA = {
@@ -68,6 +70,7 @@ PREFERENCE_SCHEMA = {
68
70
  "turn_animation": sorted(_VALID_TURN_ANIMATIONS),
69
71
  "qmri_start": sorted(_VALID_QMRI_STARTS),
70
72
  "qmri_maps": "non-empty list of names",
73
+ "roi_shape": ["circle", "rect", "freehand", "floodfill"],
71
74
  },
72
75
  "nninteractive": {"url": "string"},
73
76
  }
@@ -159,6 +162,8 @@ def _validate_preference(section: str, key: str, value):
159
162
  return _normalized_string(value, _VALID_TURN_ANIMATIONS, "viewer.turn_animation")
160
163
  if section == "viewer" and key == "qmri_start":
161
164
  return _normalized_string(value, _VALID_QMRI_STARTS, "viewer.qmri_start")
165
+ if section == "viewer" and key == "roi_shape":
166
+ return _normalized_string(value, _VALID_ROI_SHAPES, "viewer.roi_shape")
162
167
  if section == "viewer" and key == "qmri_maps":
163
168
  if not isinstance(value, list) or not value or not all(isinstance(v, str) for v in value):
164
169
  raise InvalidPreferenceError("viewer.qmri_maps must be a non-empty list of names")
@@ -326,6 +331,15 @@ def get_viewer_qmri_start() -> str | None:
326
331
  return value.strip().lower() if isinstance(value, str) and value.strip().lower() in _VALID_QMRI_STARTS else None
327
332
 
328
333
 
334
+ def get_viewer_roi_shape() -> str | None:
335
+ """Return the shape ROI mode starts with (circle, rect, freehand, floodfill)."""
336
+ viewer_cfg = load_config().get("viewer", {})
337
+ if not isinstance(viewer_cfg, dict):
338
+ return None
339
+ value = viewer_cfg.get("roi_shape")
340
+ return value.strip().lower() if isinstance(value, str) and value.strip().lower() in _VALID_ROI_SHAPES else None
341
+
342
+
329
343
  def get_viewer_qmri_maps() -> list[str] | None:
330
344
  """Return the maps / contrasts q starts qMRI with (known names only), or None."""
331
345
  viewer_cfg = load_config().get("viewer", {})
arrayview/_platform.py CHANGED
@@ -475,6 +475,26 @@ def _process_is_alive(pid: object) -> bool:
475
475
  return True
476
476
 
477
477
 
478
+ def _registration_is_foreign(registration: object) -> bool:
479
+ """True when a window registration was written on another machine.
480
+
481
+ ``~/.arrayview`` can sit on a network home shared by several hosts; a pid
482
+ from another host says nothing about a process here. Registrations from
483
+ openers that predate the ``host`` field are judged locally, as before.
484
+ """
485
+ import socket
486
+
487
+ host = registration.get("host") if isinstance(registration, dict) else None
488
+ return isinstance(host, str) and bool(host) and host != socket.gethostname()
489
+
490
+
491
+ def _registration_is_live(registration: object) -> bool:
492
+ """True when a registration belongs to this host and its process runs."""
493
+ if not isinstance(registration, dict) or _registration_is_foreign(registration):
494
+ return False
495
+ return _process_is_alive(registration.get("pid"))
496
+
497
+
478
498
  def _superseding_window_registration(
479
499
  claimed_ids: list[str],
480
500
  signal_dir: str,
@@ -539,9 +559,7 @@ def _exact_vscode_window_registration(
539
559
  registration = json.load(handle)
540
560
  except (OSError, ValueError, TypeError):
541
561
  return None
542
- if not isinstance(registration, dict) or not _process_is_alive(
543
- registration.get("pid")
544
- ):
562
+ if not _registration_is_live(registration):
545
563
  return None
546
564
  return window_id, registration
547
565
 
@@ -640,8 +658,8 @@ def _has_live_vscode_remote_registration() -> bool:
640
658
  registration = json.load(handle)
641
659
  except (OSError, ValueError, TypeError):
642
660
  continue
643
- if registration.get("remoteName") is not None and _process_is_alive(
644
- registration.get("pid")
661
+ if registration.get("remoteName") is not None and _registration_is_live(
662
+ registration
645
663
  ):
646
664
  return True
647
665
  return False
@@ -253,6 +253,7 @@ def register_analysis_routes(app, get_session_or_404) -> None:
253
253
  tolerance: float = 0.1,
254
254
  complex_mode: int = 0,
255
255
  scope_dim: int | None = None,
256
+ preview: bool = False,
256
257
  session=Depends(get_session_or_404),
257
258
  ):
258
259
  if session.rgb_axis is not None:
@@ -269,6 +270,7 @@ def register_analysis_routes(app, get_session_or_404) -> None:
269
270
  tolerance,
270
271
  complex_mode,
271
272
  scope_dim,
273
+ preview=preview,
272
274
  )
273
275
  raw = extract_slice(session, dim_x, dim_y, list(idx_tuple))
274
276
  data = apply_complex_mode(raw, complex_mode)
@@ -324,6 +326,7 @@ def register_analysis_routes(app, get_session_or_404) -> None:
324
326
  "n": int(finite.size),
325
327
  "seed_value": _safe_float(seed_val),
326
328
  "tolerance": tolerance,
329
+ "abs_tol": _safe_float(abs_tol),
327
330
  "bbox": bbox,
328
331
  "mask_b64": _encode_mask_b64(component, bbox),
329
332
  }
@@ -380,6 +383,46 @@ def register_analysis_routes(app, get_session_or_404) -> None:
380
383
  )
381
384
  return {"results": results}
382
385
 
386
+ @app.post("/roi_stats_diff/{sid_a}/{sid_b}")
387
+ def get_roi_stats_diff(sid_a: str, sid_b: str, body: dict = Body(...)):
388
+ """ROI numbers on the side-by-side difference image (A−B, |A−B|,
389
+ |A−B|/|A|) at the current position. Same payload as /roi_stats plus
390
+ diff_mode and optional indices_a / indices_b."""
391
+ from arrayview._diff import _compute_diff
392
+ from arrayview._session import SESSIONS
393
+
394
+ session_a, session_b = SESSIONS.get(sid_a), SESSIONS.get(sid_b)
395
+ if not session_a or not session_b:
396
+ return Response(status_code=404)
397
+ dim_x = int(body.get("dim_x", 1))
398
+ dim_y = int(body.get("dim_y", 0))
399
+ indices = _roi_indices_from_body(body, session_a.data.ndim, session_a.shape)
400
+ join = lambda v: ",".join(str(int(i)) for i in v) if v else None # noqa: E731
401
+ try:
402
+ raw = _compute_diff(
403
+ session_a, session_b, dim_x, dim_y, join(indices), -1, 0,
404
+ int(body.get("complex_mode", 0)), False, int(body.get("diff_mode", 1)),
405
+ indices_a=join(body.get("indices_a")), indices_b=join(body.get("indices_b")),
406
+ )[0]
407
+ except Exception:
408
+ return Response(status_code=422)
409
+ results = []
410
+ for roi_idx, roi in enumerate(body.get("rois") or []):
411
+ mask = _roi_mask_for_shape(roi, raw.shape, tuple(indices))
412
+ finite = _roi_finite_values(raw, mask)
413
+ stats = None
414
+ if finite.size:
415
+ stats = {
416
+ "min": _safe_float(finite.min()),
417
+ "max": _safe_float(finite.max()),
418
+ "mean": _safe_float(finite.mean()),
419
+ "std": _safe_float(finite.std()),
420
+ "n": int(finite.size),
421
+ }
422
+ stats["hist"] = _roi_value_histogram([finite], stats["min"], stats["max"])
423
+ results.append({"roi": roi.get("id", roi_idx), "stats": stats})
424
+ return {"results": results}
425
+
383
426
  @app.post("/roi_mask/{sid}")
384
427
  def export_roi_mask_structured(
385
428
  sid: str,
@@ -602,6 +645,7 @@ def _scoped_floodfill_response(
602
645
  tolerance: float,
603
646
  complex_mode: int,
604
647
  scope_dim: int,
648
+ preview: bool = False,
605
649
  ) -> dict:
606
650
  shape = session.shape
607
651
  if len(indices) < len(shape):
@@ -639,6 +683,30 @@ def _scoped_floodfill_response(
639
683
  roi_values = volume[component]
640
684
  finite = roi_values[np.isfinite(roi_values)]
641
685
 
686
+ if preview:
687
+ # While the sensitivity is being dragged: stats of the whole grown
688
+ # region, but the mask of the shown plane only. The full 3D mask is
689
+ # megabytes per step and only needed once, on release.
690
+ plane = component[seed_z]
691
+ ys, xs = np.where(plane)
692
+ bbox = (
693
+ {"x0": int(xs.min()), "y0": int(ys.min()), "x1": int(xs.max()), "y1": int(ys.max())}
694
+ if len(xs) else {"x0": 0, "y0": 0, "x1": 0, "y1": 0}
695
+ )
696
+ return {
697
+ "min": _safe_float(finite.min()) if finite.size else None,
698
+ "max": _safe_float(finite.max()) if finite.size else None,
699
+ "mean": _safe_float(finite.mean()) if finite.size else None,
700
+ "std": _safe_float(finite.std()) if finite.size else None,
701
+ "n": int(finite.size),
702
+ "seed_value": _safe_float(seed_val),
703
+ "tolerance": tolerance,
704
+ "abs_tol": _safe_float(abs_tol),
705
+ "bbox": bbox,
706
+ "mask_b64": _encode_mask_b64(plane, bbox),
707
+ "preview": True,
708
+ }
709
+
642
710
  slices = []
643
711
  scoped_values = []
644
712
  for z in range(depth):
@@ -692,6 +760,7 @@ def _scoped_floodfill_response(
692
760
  "n": int(finite.size),
693
761
  "seed_value": _safe_float(seed_val),
694
762
  "tolerance": tolerance,
763
+ "abs_tol": _safe_float(abs_tol),
695
764
  "bbox": current_slice["bbox"] if current_slice else {"x0": 0, "y0": 0, "x1": 0, "y1": 0},
696
765
  "mask_b64": current_slice["mask_b64"] if current_slice else "",
697
766
  "scope": roi["scope"],
arrayview/_server.py CHANGED
@@ -54,6 +54,7 @@ from arrayview._config import (
54
54
  get_viewer_dimbar_mode,
55
55
  get_viewer_turn_animation,
56
56
  get_viewer_qmri_start,
57
+ get_viewer_roi_shape,
57
58
  get_viewer_qmri_maps,
58
59
  get_viewer_ortho_layout,
59
60
  get_viewer_rounded_panes,
@@ -497,6 +498,7 @@ def _viewer_ui_response(
497
498
  .replace("__DEFAULT_TURN_ANIMATION__", _default_turn_animation)
498
499
  .replace("__DEFAULT_QMRI_START__", json.dumps(get_viewer_qmri_start()))
499
500
  .replace("__DEFAULT_QMRI_MAPS__", json.dumps(get_viewer_qmri_maps()))
501
+ .replace("__DEFAULT_ROI_SHAPE__", json.dumps(get_viewer_roi_shape()))
500
502
  .replace("__BODY_CLASS__", "av-loading" if sid else "")
501
503
  .replace("__ARRAYVIEW_VERSION__", _av_version)
502
504
  )