arrayview 0.56.1__tar.gz → 0.58.1__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 (96) hide show
  1. {arrayview-0.56.1 → arrayview-0.58.1}/PKG-INFO +1 -1
  2. {arrayview-0.56.1 → arrayview-0.58.1}/pyproject.toml +1 -1
  3. {arrayview-0.56.1 → arrayview-0.58.1}/src/arrayview/_config.py +58 -0
  4. {arrayview-0.56.1 → arrayview-0.58.1}/src/arrayview/_io.py +19 -7
  5. {arrayview-0.56.1 → arrayview-0.58.1}/src/arrayview/_platform.py +23 -5
  6. {arrayview-0.56.1 → arrayview-0.58.1}/src/arrayview/_render.py +24 -6
  7. {arrayview-0.56.1 → arrayview-0.58.1}/src/arrayview/_routes_analysis.py +69 -0
  8. {arrayview-0.56.1 → arrayview-0.58.1}/src/arrayview/_routes_loading.py +1 -1
  9. {arrayview-0.56.1 → arrayview-0.58.1}/src/arrayview/_routes_state.py +35 -4
  10. {arrayview-0.56.1 → arrayview-0.58.1}/src/arrayview/_routes_websocket.py +16 -10
  11. {arrayview-0.56.1 → arrayview-0.58.1}/src/arrayview/_server.py +6 -0
  12. {arrayview-0.56.1 → arrayview-0.58.1}/src/arrayview/_session.py +1 -0
  13. {arrayview-0.56.1 → arrayview-0.58.1}/src/arrayview/_viewer.html +2128 -841
  14. {arrayview-0.56.1 → arrayview-0.58.1}/src/arrayview/_vscode_extension.py +15 -4
  15. {arrayview-0.56.1 → arrayview-0.58.1}/src/arrayview/_vscode_signal.py +6 -6
  16. arrayview-0.58.1/src/arrayview/arrayview-opener.vsix +0 -0
  17. {arrayview-0.56.1 → arrayview-0.58.1}/tests/test_api.py +42 -0
  18. {arrayview-0.56.1 → arrayview-0.58.1}/tests/test_browser.py +492 -38
  19. {arrayview-0.56.1 → arrayview-0.58.1}/tests/test_config.py +26 -0
  20. {arrayview-0.56.1 → arrayview-0.58.1}/tests/test_glides.py +8 -4
  21. {arrayview-0.56.1 → arrayview-0.58.1}/tests/test_large_arrays.py +14 -0
  22. {arrayview-0.56.1 → arrayview-0.58.1}/tests/test_mode_roundtrip.py +4 -2
  23. arrayview-0.58.1/tests/test_shared_home_registrations.py +47 -0
  24. {arrayview-0.56.1 → arrayview-0.58.1}/tests/visual_smoke.py +26 -17
  25. arrayview-0.56.1/src/arrayview/arrayview-opener.vsix +0 -0
  26. {arrayview-0.56.1 → arrayview-0.58.1}/.gitignore +0 -0
  27. {arrayview-0.56.1 → arrayview-0.58.1}/LICENSE +0 -0
  28. {arrayview-0.56.1 → arrayview-0.58.1}/README.md +0 -0
  29. {arrayview-0.56.1 → arrayview-0.58.1}/src/arrayview/ARCHITECTURE.md +0 -0
  30. {arrayview-0.56.1 → arrayview-0.58.1}/src/arrayview/__init__.py +0 -0
  31. {arrayview-0.56.1 → arrayview-0.58.1}/src/arrayview/__main__.py +0 -0
  32. {arrayview-0.56.1 → arrayview-0.58.1}/src/arrayview/_analysis.py +0 -0
  33. {arrayview-0.56.1 → arrayview-0.58.1}/src/arrayview/_app.py +0 -0
  34. {arrayview-0.56.1 → arrayview-0.58.1}/src/arrayview/_bootstrap_app.py +0 -0
  35. {arrayview-0.56.1 → arrayview-0.58.1}/src/arrayview/_diagnostics.py +0 -0
  36. {arrayview-0.56.1 → arrayview-0.58.1}/src/arrayview/_dicom.py +0 -0
  37. {arrayview-0.56.1 → arrayview-0.58.1}/src/arrayview/_diff.py +0 -0
  38. {arrayview-0.56.1 → arrayview-0.58.1}/src/arrayview/_extra_ports.py +0 -0
  39. {arrayview-0.56.1 → arrayview-0.58.1}/src/arrayview/_icon.png +0 -0
  40. {arrayview-0.56.1 → arrayview-0.58.1}/src/arrayview/_imaging.py +0 -0
  41. {arrayview-0.56.1 → arrayview-0.58.1}/src/arrayview/_instance_registry.py +0 -0
  42. {arrayview-0.56.1 → arrayview-0.58.1}/src/arrayview/_launch_plan.py +0 -0
  43. {arrayview-0.56.1 → arrayview-0.58.1}/src/arrayview/_launch_trace.py +0 -0
  44. {arrayview-0.56.1 → arrayview-0.58.1}/src/arrayview/_launcher.py +0 -0
  45. {arrayview-0.56.1 → arrayview-0.58.1}/src/arrayview/_lifecycle.py +0 -0
  46. {arrayview-0.56.1 → arrayview-0.58.1}/src/arrayview/_overlays.py +0 -0
  47. {arrayview-0.56.1 → arrayview-0.58.1}/src/arrayview/_routes_drop.py +0 -0
  48. {arrayview-0.56.1 → arrayview-0.58.1}/src/arrayview/_routes_export.py +0 -0
  49. {arrayview-0.56.1 → arrayview-0.58.1}/src/arrayview/_routes_persistence.py +0 -0
  50. {arrayview-0.56.1 → arrayview-0.58.1}/src/arrayview/_routes_preferences.py +0 -0
  51. {arrayview-0.56.1 → arrayview-0.58.1}/src/arrayview/_routes_preload.py +0 -0
  52. {arrayview-0.56.1 → arrayview-0.58.1}/src/arrayview/_routes_query.py +0 -0
  53. {arrayview-0.56.1 → arrayview-0.58.1}/src/arrayview/_routes_rendering.py +0 -0
  54. {arrayview-0.56.1 → arrayview-0.58.1}/src/arrayview/_routes_segmentation.py +0 -0
  55. {arrayview-0.56.1 → arrayview-0.58.1}/src/arrayview/_routes_vectorfield.py +0 -0
  56. {arrayview-0.56.1 → arrayview-0.58.1}/src/arrayview/_segmentation.py +0 -0
  57. {arrayview-0.56.1 → arrayview-0.58.1}/src/arrayview/_session_spec.py +0 -0
  58. {arrayview-0.56.1 → arrayview-0.58.1}/src/arrayview/_shell.html +0 -0
  59. {arrayview-0.56.1 → arrayview-0.58.1}/src/arrayview/_source_safety.py +0 -0
  60. {arrayview-0.56.1 → arrayview-0.58.1}/src/arrayview/_synthetic_mri.py +0 -0
  61. {arrayview-0.56.1 → arrayview-0.58.1}/src/arrayview/_torch.py +0 -0
  62. {arrayview-0.56.1 → arrayview-0.58.1}/src/arrayview/_tutorial.py +0 -0
  63. {arrayview-0.56.1 → arrayview-0.58.1}/src/arrayview/_vectorfield.py +0 -0
  64. {arrayview-0.56.1 → arrayview-0.58.1}/src/arrayview/_view_memory.py +0 -0
  65. {arrayview-0.56.1 → arrayview-0.58.1}/src/arrayview/_vscode.py +0 -0
  66. {arrayview-0.56.1 → arrayview-0.58.1}/src/arrayview/_vscode_browser.py +0 -0
  67. {arrayview-0.56.1 → arrayview-0.58.1}/src/arrayview/_watch.py +0 -0
  68. {arrayview-0.56.1 → arrayview-0.58.1}/src/arrayview/gsap.min.js +0 -0
  69. {arrayview-0.56.1 → arrayview-0.58.1}/src/arrayview/todo.md +0 -0
  70. {arrayview-0.56.1 → arrayview-0.58.1}/tests/capture_patient_loading.py +0 -0
  71. {arrayview-0.56.1 → arrayview-0.58.1}/tests/capture_v_animation.py +0 -0
  72. {arrayview-0.56.1 → arrayview-0.58.1}/tests/conftest.py +0 -0
  73. {arrayview-0.56.1 → arrayview-0.58.1}/tests/make_vectorfield_test_arrays.py +0 -0
  74. {arrayview-0.56.1 → arrayview-0.58.1}/tests/test_1d_arrays.py +0 -0
  75. {arrayview-0.56.1 → arrayview-0.58.1}/tests/test_backend_shared.py +0 -0
  76. {arrayview-0.56.1 → arrayview-0.58.1}/tests/test_cli.py +0 -0
  77. {arrayview-0.56.1 → arrayview-0.58.1}/tests/test_dicom.py +0 -0
  78. {arrayview-0.56.1 → arrayview-0.58.1}/tests/test_diff_readahead.py +0 -0
  79. {arrayview-0.56.1 → arrayview-0.58.1}/tests/test_drop_import.py +0 -0
  80. {arrayview-0.56.1 → arrayview-0.58.1}/tests/test_first_slice_warmup.py +0 -0
  81. {arrayview-0.56.1 → arrayview-0.58.1}/tests/test_instance_registry.py +0 -0
  82. {arrayview-0.56.1 → arrayview-0.58.1}/tests/test_io.py +0 -0
  83. {arrayview-0.56.1 → arrayview-0.58.1}/tests/test_launch_blackbox.py +0 -0
  84. {arrayview-0.56.1 → arrayview-0.58.1}/tests/test_nifti_meta.py +0 -0
  85. {arrayview-0.56.1 → arrayview-0.58.1}/tests/test_nifti_series.py +0 -0
  86. {arrayview-0.56.1 → arrayview-0.58.1}/tests/test_pane_names.py +0 -0
  87. {arrayview-0.56.1 → arrayview-0.58.1}/tests/test_rgb_pixel_art.py +0 -0
  88. {arrayview-0.56.1 → arrayview-0.58.1}/tests/test_safe_server_stop.py +0 -0
  89. {arrayview-0.56.1 → arrayview-0.58.1}/tests/test_source_safety.py +0 -0
  90. {arrayview-0.56.1 → arrayview-0.58.1}/tests/test_torch.py +0 -0
  91. {arrayview-0.56.1 → arrayview-0.58.1}/tests/test_tutorial.py +0 -0
  92. {arrayview-0.56.1 → arrayview-0.58.1}/tests/test_view_memory.py +0 -0
  93. {arrayview-0.56.1 → arrayview-0.58.1}/tests/test_viewer_port.py +0 -0
  94. {arrayview-0.56.1 → arrayview-0.58.1}/tests/test_vsix_bundle.py +0 -0
  95. {arrayview-0.56.1 → arrayview-0.58.1}/tests/ui_audit.py +0 -0
  96. {arrayview-0.56.1 → arrayview-0.58.1}/tests/v_anim_frames/.gitkeep +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: arrayview
3
- Version: 0.56.1
3
+ Version: 0.58.1
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.56.1"
7
+ version = "0.58.1"
8
8
  description = "Fast multi-dimensional array viewer"
9
9
  readme = { file = "README.md", content-type = "text/markdown" }
10
10
  requires-python = ">=3.12"
@@ -17,6 +17,13 @@ _VALID_THEMES = {"dark", "light"}
17
17
  _VALID_ORTHO_LAYOUTS = {"horizontal", "big-left"}
18
18
  _VALID_DIMBAR_MODES = {"compact", "extended"}
19
19
  _VALID_TURN_ANIMATIONS = {"rotate", "fade"}
20
+ _VALID_QMRI_STARTS = {"picker", "straight"}
21
+ _VALID_ROI_SHAPES = {"circle", "rect", "freehand", "floodfill"}
22
+ # What q opens in qMRI: parameter maps by role, synthetic contrasts by name.
23
+ QMRI_START_NAMES = (
24
+ "t1", "t2", "pd", "b1", "db0", "phase",
25
+ "t1w", "t2w", "pdw", "t2flair", "stir", "psir",
26
+ )
20
27
  _CONFIG_LOCK = threading.Lock()
21
28
 
22
29
  WINDOW_PREFERENCE_OPTIONS = {
@@ -45,6 +52,8 @@ BUILTIN_PREFERENCES = {
45
52
  "ortho_layout": None,
46
53
  "dimbar_mode": "compact",
47
54
  "turn_animation": "rotate",
55
+ "qmri_start": "picker",
56
+ "roi_shape": "circle",
48
57
  },
49
58
  }
50
59
  PREFERENCE_SCHEMA = {
@@ -59,6 +68,9 @@ PREFERENCE_SCHEMA = {
59
68
  "ortho_layout": sorted(_VALID_ORTHO_LAYOUTS),
60
69
  "dimbar_mode": sorted(_VALID_DIMBAR_MODES),
61
70
  "turn_animation": sorted(_VALID_TURN_ANIMATIONS),
71
+ "qmri_start": sorted(_VALID_QMRI_STARTS),
72
+ "qmri_maps": "non-empty list of names",
73
+ "roi_shape": ["circle", "rect", "freehand", "floodfill"],
62
74
  },
63
75
  "nninteractive": {"url": "string"},
64
76
  }
@@ -148,6 +160,20 @@ def _validate_preference(section: str, key: str, value):
148
160
  return _normalized_string(value, _VALID_DIMBAR_MODES, "viewer.dimbar_mode")
149
161
  if section == "viewer" and key == "turn_animation":
150
162
  return _normalized_string(value, _VALID_TURN_ANIMATIONS, "viewer.turn_animation")
163
+ if section == "viewer" and key == "qmri_start":
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")
167
+ if section == "viewer" and key == "qmri_maps":
168
+ if not isinstance(value, list) or not value or not all(isinstance(v, str) for v in value):
169
+ raise InvalidPreferenceError("viewer.qmri_maps must be a non-empty list of names")
170
+ normalized = list(dict.fromkeys(v.strip().lower() for v in value))
171
+ unknown = [v for v in normalized if v not in QMRI_START_NAMES]
172
+ if unknown:
173
+ raise InvalidPreferenceError(
174
+ f"viewer.qmri_maps: unknown {', '.join(unknown)}; use {', '.join(QMRI_START_NAMES)}"
175
+ )
176
+ return normalized
151
177
  if section == "nninteractive" and key == "url":
152
178
  if not isinstance(value, str) or not value.strip():
153
179
  raise InvalidPreferenceError("nninteractive.url must be a non-empty string")
@@ -296,6 +322,38 @@ def get_viewer_turn_animation() -> str | None:
296
322
  return value.strip().lower() if isinstance(value, str) and value.strip().lower() in _VALID_TURN_ANIMATIONS else None
297
323
 
298
324
 
325
+ def get_viewer_qmri_start() -> str | None:
326
+ """Return what q does outside qMRI: "picker" (ask first) or "straight"."""
327
+ viewer_cfg = load_config().get("viewer", {})
328
+ if not isinstance(viewer_cfg, dict):
329
+ return None
330
+ value = viewer_cfg.get("qmri_start")
331
+ return value.strip().lower() if isinstance(value, str) and value.strip().lower() in _VALID_QMRI_STARTS else None
332
+
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
+
343
+ def get_viewer_qmri_maps() -> list[str] | None:
344
+ """Return the maps / contrasts q starts qMRI with (known names only), or None."""
345
+ viewer_cfg = load_config().get("viewer", {})
346
+ if not isinstance(viewer_cfg, dict):
347
+ return None
348
+ value = viewer_cfg.get("qmri_maps")
349
+ if isinstance(value, str): # `arrayview config set viewer.qmri_maps t1,t2,pd`
350
+ value = value.split(",")
351
+ if not isinstance(value, list):
352
+ return None
353
+ names = [v.strip().lower() for v in value if isinstance(v, str) and v.strip().lower() in QMRI_START_NAMES]
354
+ return list(dict.fromkeys(names)) or None
355
+
356
+
299
357
  def get_nninteractive_url() -> str | None:
300
358
  """Return configured nnInteractive server URL, or None."""
301
359
  env_val = os.environ.get("ARRAYVIEW_NNINTERACTIVE_URL", "").strip()
@@ -1696,13 +1696,25 @@ def _explicit_case_files(patterns, keep_order=False):
1696
1696
 
1697
1697
 
1698
1698
  def _distinguishing_path_parts(paths):
1699
- """Name each path by the first path component in which the paths differ."""
1700
- split = [os.path.normpath(p).split(os.sep) for p in paths]
1701
- if len({len(parts) for parts in split}) == 1:
1702
- for i in range(len(split[0])):
1703
- names = [parts[i] for parts in split]
1704
- if len(set(names)) == len(names):
1705
- return [_strip_array_ext(n) if i == len(split[0]) - 1 else n for n in names]
1699
+ """Short unique names for paths that may share a file name.
1700
+
1701
+ Works back from the file name: the file name (no extension) when those
1702
+ differ, else the nearest folder that differs, adding further differing
1703
+ folders until every name is unique (p1/pre, p2/pre, p2/post). Parts that
1704
+ every path shares are left out. Same rule as the viewer's compare titles.
1705
+ """
1706
+ split = [os.path.normpath(os.path.abspath(p)).split(os.sep) for p in paths]
1707
+ split = [[*parts[:-1], _strip_array_ext(p)] for parts, p in zip(split, paths)]
1708
+ depth = max(len(parts) for parts in split)
1709
+ rev = [parts[::-1] + [""] * (depth - len(parts)) for parts in split]
1710
+ keep = []
1711
+ for i in range(depth):
1712
+ if len({r[i] for r in rev}) < 2:
1713
+ continue
1714
+ keep.append(i)
1715
+ names = ["/".join(r[j] for j in reversed(keep) if r[j]) for r in rev]
1716
+ if all(names) and len(set(names)) == len(names):
1717
+ return names
1706
1718
  return [_default_collection_case_key(p) for p in paths]
1707
1719
 
1708
1720
 
@@ -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
@@ -924,6 +924,7 @@ def render_mosaic(
924
924
  progress=None,
925
925
  fit=None,
926
926
  dim_z2=-1,
927
+ window_out=None,
927
928
  ):
928
929
  """Render the mosaic grid of every slice along *dim_z* (and *dim_z2*, down).
929
930
 
@@ -931,6 +932,9 @@ def render_mosaic(
931
932
  (as the live socket would before sending) and caches it that way, so a
932
933
  grid warmed ahead of time is ready to send: the shrink of a 240-slice
933
934
  grid costs as much as rendering it.
935
+
936
+ ``window_out``, a list, receives the (vmin, vmax) the tiles were coloured
937
+ with — the whole stack's, not the current slice's.
934
938
  """
935
939
  idx_norm = list(idx_tuple)
936
940
  idx_norm[dim_z] = 0
@@ -938,18 +942,30 @@ def render_mosaic(
938
942
  idx_norm[dim_z2] = 0
939
943
  key = (dim_x, dim_y, dim_z, tuple(idx_norm), colormap, dr, complex_mode, log_scale, mosaic_cols, vmin_override, vmax_override, dim_z2)
940
944
 
945
+ windows = session.__dict__.setdefault("_mosaic_windows", {})
946
+
941
947
  def build_full():
942
- return _build_mosaic_rgba(
948
+ win = []
949
+ rgba = _build_mosaic_rgba(
943
950
  session, dim_x, dim_y, dim_z, idx_tuple, colormap, dr, complex_mode,
944
951
  log_scale, mosaic_cols, vmin_override, vmax_override, progress,
945
- dim_z2=dim_z2,
952
+ dim_z2=dim_z2, window_out=win,
946
953
  )
954
+ if win:
955
+ if len(windows) > 256:
956
+ windows.clear()
957
+ windows[key] = win[0]
958
+ return rgba
947
959
 
948
960
  full = lambda: _mosaic_once(session, key, build_full)
949
961
  if not fit:
950
- return full()
951
- fit_w, fit_h = int(fit[0]), int(fit[1])
952
- return _mosaic_once(session, key + (("fit", fit_w, fit_h),), lambda: fit_rgba(full(), fit_w, fit_h))
962
+ out = full()
963
+ else:
964
+ fit_w, fit_h = int(fit[0]), int(fit[1])
965
+ out = _mosaic_once(session, key + (("fit", fit_w, fit_h),), lambda: fit_rgba(full(), fit_w, fit_h))
966
+ if window_out is not None and key in windows:
967
+ window_out.append(windows[key])
968
+ return out
953
969
 
954
970
 
955
971
  def _mosaic_once(session, key, build):
@@ -1021,7 +1037,7 @@ def fit_rgba(rgba, canvas_w, canvas_h):
1021
1037
  def _build_mosaic_rgba(
1022
1038
  session, dim_x, dim_y, dim_z, idx_tuple, colormap, dr, complex_mode,
1023
1039
  log_scale, mosaic_cols, vmin_override, vmax_override, progress,
1024
- dim_z2=-1,
1040
+ dim_z2=-1, window_out=None,
1025
1041
  ):
1026
1042
  tiles = mosaic_tile_indices(session.shape, dim_z, dim_z2, idx_tuple)
1027
1043
  n = len(tiles)
@@ -1050,6 +1066,8 @@ def _build_mosaic_rgba(
1050
1066
  # One call partitions once for both ends; two calls sorted the whole
1051
1067
  # stack twice (~0.14 s of a 240-slice mosaic step).
1052
1068
  vmin, vmax = (float(v) for v in np.percentile(all_data, [1, 99]))
1069
+ if window_out is not None:
1070
+ window_out.append((vmin, vmax))
1053
1071
 
1054
1072
  if mosaic_cols is not None:
1055
1073
  grid, rows, cols = _build_mosaic_grid(all_data, n, cols=mosaic_cols)
@@ -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"],
@@ -653,7 +653,7 @@ def register_loading_routes(app, *, notify_shells, setup_rgb) -> None:
653
653
 
654
654
  @app.post("/popout/{sid}")
655
655
  async def toggle_session_tab_window(sid: str, request: Request):
656
- """Move this VS Code browser tab into its own window, or back."""
656
+ """Make this VS Code browser tab fill its window, or put the layout back."""
657
657
  from arrayview._routes_websocket import viewer_tab_window_id
658
658
  from arrayview._vscode_signal import _request_vscode_tab_reveal
659
659
 
@@ -18,6 +18,16 @@ def _meta_equal(a, b) -> bool:
18
18
  return a is b
19
19
 
20
20
 
21
+ def _fft_shifted(data, axes):
22
+ """Centred n-D FFT over `axes`, multithreaded; keeps single precision."""
23
+ full = np.asarray(data) # materialise memmaps / lazy arrays
24
+ try:
25
+ import scipy.fft as sfft
26
+ except ImportError: # scipy is a dependency, but stay usable without it
27
+ return np.fft.fftshift(np.fft.fftn(full, axes=axes), axes=axes)
28
+ return sfft.fftshift(sfft.fftn(full, axes=axes, workers=-1), axes=axes)
29
+
30
+
21
31
  def register_state_routes(app, get_session_or_404) -> None:
22
32
  @app.get("/clearcache/{sid}")
23
33
  def clear_cache(sid: str):
@@ -133,8 +143,16 @@ def register_state_routes(app, get_session_or_404) -> None:
133
143
  return {"error": f"stack: {s.name} cannot be stacked"}
134
144
  if len({len(s.data.shape) for s in sessions}) != 1:
135
145
  return {"error": "stack: arrays differ in number of dimensions"}
146
+ names = [s.name for s in sessions]
147
+ paths = [s.filepath for s in sessions]
148
+ if len(set(names)) < len(names) and all(paths):
149
+ # Same file name from different folders: name each by the
150
+ # nearest folders that tell them apart.
151
+ from arrayview._io import _distinguishing_path_parts
152
+
153
+ names = _distinguishing_path_parts(paths)
136
154
  try:
137
- data = _ArrayStack([s.data for s in sessions], [s.name for s in sessions])
155
+ data = _ArrayStack([s.data for s in sessions], names)
138
156
  stack = await asyncio.to_thread(
139
157
  Session, data, name=" · ".join(s.name for s in sessions)
140
158
  )
@@ -300,6 +318,9 @@ def register_state_routes(app, get_session_or_404) -> None:
300
318
  body = await request.json()
301
319
  axes_str = str(body.get("axes", "")).strip()
302
320
 
321
+ if session.fft_busy:
322
+ return {"error": "FFT is still being computed"}
323
+
303
324
  if session.fft_original_data is not None:
304
325
  session.data = session.fft_original_data
305
326
  session.shape = session.data.shape
@@ -331,9 +352,19 @@ def register_state_routes(app, get_session_or_404) -> None:
331
352
  "too_large": True,
332
353
  }
333
354
 
334
- session.fft_original_data = session.data
335
- full = np.array(session.data)
336
- session.data = np.fft.fftshift(np.fft.fftn(full, axes=axes), axes=axes)
355
+ # Off the event loop: the viewer keeps answering while it computes.
356
+ original = session.data
357
+ session.fft_busy = True
358
+ try:
359
+ result = await asyncio.to_thread(_fft_shifted, original, axes)
360
+ except Exception as e:
361
+ return {"error": str(e)}
362
+ finally:
363
+ session.fft_busy = False
364
+ if session.data is not original:
365
+ return {"error": "data changed while computing FFT"}
366
+ session.fft_original_data = original
367
+ session.data = result
337
368
  session.shape = session.data.shape
338
369
  session.fft_axes = axes
339
370
  session.reset_caches()
@@ -721,6 +721,7 @@ def register_websocket_routes(app) -> None:
721
721
  if canvas_w and canvas_h and not msg.get("overlay_sid")
722
722
  else None
723
723
  )
724
+ mosaic_window = []
724
725
  rgba = await _render(
725
726
  loop,
726
727
  lambda: render_mosaic(
@@ -739,6 +740,7 @@ def register_websocket_routes(app) -> None:
739
740
  progress=_render_progress_reporter(loop, ws, label='Building mosaic'),
740
741
  fit=mosaic_fit,
741
742
  dim_z2=dim_z2,
743
+ window_out=mosaic_window,
742
744
  ),
743
745
  )
744
746
  rgba = _composite_mosaic_overlays(
@@ -748,16 +750,20 @@ def register_websocket_routes(app) -> None:
748
750
  idx_tuple, session.shape, mosaic_cols, dim_z2=dim_z2,
749
751
  )
750
752
  h, w = rgba.shape[:2]
751
- raw = extract_slice(session, dim_x, dim_y, list(idx_tuple))
752
- _, vmin, vmax = _prepare_display(
753
- session,
754
- raw,
755
- complex_mode,
756
- dr,
757
- log_scale,
758
- vmin_override=vmin_override,
759
- vmax_override=vmax_override,
760
- )
753
+ if mosaic_window:
754
+ # The range the tiles were coloured with (whole stack).
755
+ vmin, vmax = mosaic_window[0]
756
+ else:
757
+ raw = extract_slice(session, dim_x, dim_y, list(idx_tuple))
758
+ _, vmin, vmax = _prepare_display(
759
+ session,
760
+ raw,
761
+ complex_mode,
762
+ dr,
763
+ log_scale,
764
+ vmin_override=vmin_override,
765
+ vmax_override=vmax_override,
766
+ )
761
767
  elif projection_mode > 0 and projection_dim >= 0:
762
768
  _pm = projection_mode
763
769
  _pd = projection_dim
@@ -53,6 +53,9 @@ from arrayview._config import (
53
53
  get_viewer_colormaps,
54
54
  get_viewer_dimbar_mode,
55
55
  get_viewer_turn_animation,
56
+ get_viewer_qmri_start,
57
+ get_viewer_roi_shape,
58
+ get_viewer_qmri_maps,
56
59
  get_viewer_ortho_layout,
57
60
  get_viewer_rounded_panes,
58
61
  get_viewer_qmri_gapless,
@@ -493,6 +496,9 @@ def _viewer_ui_response(
493
496
  .replace("__DEFAULT_ORTHO_LAYOUT__", _default_ortho_layout)
494
497
  .replace("__DEFAULT_DIMBAR_MODE__", _default_dimbar_mode)
495
498
  .replace("__DEFAULT_TURN_ANIMATION__", _default_turn_animation)
499
+ .replace("__DEFAULT_QMRI_START__", json.dumps(get_viewer_qmri_start()))
500
+ .replace("__DEFAULT_QMRI_MAPS__", json.dumps(get_viewer_qmri_maps()))
501
+ .replace("__DEFAULT_ROI_SHAPE__", json.dumps(get_viewer_roi_shape()))
496
502
  .replace("__BODY_CLASS__", "av-loading" if sid else "")
497
503
  .replace("__ARRAYVIEW_VERSION__", _av_version)
498
504
  )
@@ -591,6 +591,7 @@ class Session:
591
591
  )
592
592
  self.fft_original_data = None
593
593
  self.fft_axes = None
594
+ self.fft_busy = False # an FFT is being computed off the event loop
594
595
  self.data_version = 0 # incremented by /reload when file is reloaded
595
596
  self.viewer_leases = 1 # one release is required for each tab using this SID
596
597