napari-zenapi-streaming 0.0.2__tar.gz → 0.0.4__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 (42) hide show
  1. {napari_zenapi_streaming-0.0.2 → napari_zenapi_streaming-0.0.4}/CHANGELOG.md +33 -0
  2. {napari_zenapi_streaming-0.0.2/src/napari_zenapi_streaming.egg-info → napari_zenapi_streaming-0.0.4}/PKG-INFO +41 -17
  3. {napari_zenapi_streaming-0.0.2 → napari_zenapi_streaming-0.0.4}/README.md +40 -16
  4. {napari_zenapi_streaming-0.0.2 → napari_zenapi_streaming-0.0.4}/pyproject.toml +1 -1
  5. {napari_zenapi_streaming-0.0.2 → napari_zenapi_streaming-0.0.4}/src/napari_zen_streaming/ZEN_omezarr.py +101 -11
  6. {napari_zenapi_streaming-0.0.2 → napari_zenapi_streaming-0.0.4}/src/napari_zen_streaming/ZEN_pipeline.py +50 -20
  7. {napari_zenapi_streaming-0.0.2 → napari_zenapi_streaming-0.0.4}/src/napari_zen_streaming/ZEN_stream2omezarr.py +21 -0
  8. {napari_zenapi_streaming-0.0.2 → napari_zenapi_streaming-0.0.4}/src/napari_zen_streaming/ZEN_ui.py +75 -13
  9. {napari_zenapi_streaming-0.0.2 → napari_zenapi_streaming-0.0.4}/src/napari_zen_streaming/__init__.py +1 -1
  10. napari_zenapi_streaming-0.0.4/src/napari_zen_streaming/_tests/test_experiment_stream_filter.py +440 -0
  11. {napari_zenapi_streaming-0.0.2 → napari_zenapi_streaming-0.0.4}/src/napari_zen_streaming/_tests/test_experiment_xml.py +73 -0
  12. {napari_zenapi_streaming-0.0.2 → napari_zenapi_streaming-0.0.4}/src/napari_zen_streaming/_tests/test_initial_experiment_selection.py +13 -1
  13. {napari_zenapi_streaming-0.0.2 → napari_zenapi_streaming-0.0.4}/src/napari_zen_streaming/_tests/test_live_preview.py +6 -3
  14. {napari_zenapi_streaming-0.0.2 → napari_zenapi_streaming-0.0.4}/src/napari_zen_streaming/_tests/test_omezarr_viewer.py +59 -0
  15. {napari_zenapi_streaming-0.0.2 → napari_zenapi_streaming-0.0.4}/src/napari_zen_streaming/_tests/test_scene_mosaic.py +138 -0
  16. {napari_zenapi_streaming-0.0.2 → napari_zenapi_streaming-0.0.4}/src/napari_zen_streaming/main.py +4 -2
  17. {napari_zenapi_streaming-0.0.2 → napari_zenapi_streaming-0.0.4/src/napari_zenapi_streaming.egg-info}/PKG-INFO +41 -17
  18. napari_zenapi_streaming-0.0.2/src/napari_zen_streaming/_tests/test_experiment_stream_filter.py +0 -139
  19. {napari_zenapi_streaming-0.0.2 → napari_zenapi_streaming-0.0.4}/LICENSE +0 -0
  20. {napari_zenapi_streaming-0.0.2 → napari_zenapi_streaming-0.0.4}/MANIFEST.in +0 -0
  21. {napari_zenapi_streaming-0.0.2 → napari_zenapi_streaming-0.0.4}/setup.cfg +0 -0
  22. {napari_zenapi_streaming-0.0.2 → napari_zenapi_streaming-0.0.4}/src/napari_zen_streaming/ZEN_config.py +0 -0
  23. {napari_zenapi_streaming-0.0.2 → napari_zenapi_streaming-0.0.4}/src/napari_zen_streaming/ZEN_init.py +0 -0
  24. {napari_zenapi_streaming-0.0.2 → napari_zenapi_streaming-0.0.4}/src/napari_zen_streaming/ZEN_utils.py +0 -0
  25. {napari_zenapi_streaming-0.0.2 → napari_zenapi_streaming-0.0.4}/src/napari_zen_streaming/_logging.py +0 -0
  26. {napari_zenapi_streaming-0.0.2 → napari_zenapi_streaming-0.0.4}/src/napari_zen_streaming/_scene_geometry.py +0 -0
  27. {napari_zenapi_streaming-0.0.2 → napari_zenapi_streaming-0.0.4}/src/napari_zen_streaming/_tests/__init__.py +0 -0
  28. {napari_zenapi_streaming-0.0.2 → napari_zenapi_streaming-0.0.4}/src/napari_zen_streaming/_tests/test_config.py +0 -0
  29. {napari_zenapi_streaming-0.0.2 → napari_zenapi_streaming-0.0.4}/src/napari_zen_streaming/_tests/test_display_completion.py +0 -0
  30. {napari_zenapi_streaming-0.0.2 → napari_zenapi_streaming-0.0.4}/src/napari_zen_streaming/_tests/test_hcs_ui_option.py +0 -0
  31. {napari_zenapi_streaming-0.0.2 → napari_zenapi_streaming-0.0.4}/src/napari_zen_streaming/_tests/test_logging.py +0 -0
  32. {napari_zenapi_streaming-0.0.2 → napari_zenapi_streaming-0.0.4}/src/napari_zen_streaming/_tests/test_progress_reporting.py +0 -0
  33. {napari_zenapi_streaming-0.0.2 → napari_zenapi_streaming-0.0.4}/src/napari_zen_streaming/_tests/test_runtime_pixel_type.py +0 -0
  34. {napari_zenapi_streaming-0.0.2 → napari_zenapi_streaming-0.0.4}/src/napari_zen_streaming/_tests/test_scene_geometry.py +0 -0
  35. {napari_zenapi_streaming-0.0.2 → napari_zenapi_streaming-0.0.4}/src/napari_zen_streaming/_widget.py +0 -0
  36. {napari_zenapi_streaming-0.0.2 → napari_zenapi_streaming-0.0.4}/src/napari_zen_streaming/misc.py +0 -0
  37. {napari_zenapi_streaming-0.0.2 → napari_zenapi_streaming-0.0.4}/src/napari_zen_streaming/napari.yaml +0 -0
  38. {napari_zenapi_streaming-0.0.2 → napari_zenapi_streaming-0.0.4}/src/napari_zenapi_streaming.egg-info/SOURCES.txt +0 -0
  39. {napari_zenapi_streaming-0.0.2 → napari_zenapi_streaming-0.0.4}/src/napari_zenapi_streaming.egg-info/dependency_links.txt +0 -0
  40. {napari_zenapi_streaming-0.0.2 → napari_zenapi_streaming-0.0.4}/src/napari_zenapi_streaming.egg-info/entry_points.txt +0 -0
  41. {napari_zenapi_streaming-0.0.2 → napari_zenapi_streaming-0.0.4}/src/napari_zenapi_streaming.egg-info/requires.txt +0 -0
  42. {napari_zenapi_streaming-0.0.2 → napari_zenapi_streaming-0.0.4}/src/napari_zenapi_streaming.egg-info/top_level.txt +0 -0
@@ -1,5 +1,38 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.0.4 - 2026-11-18
4
+
5
+ ### Fixed
6
+
7
+ - Carry active-channel names and actual ZEN XML colors through plugin and
8
+ configured CLI OME-Zarr acquisition. Persist per-image OMERO display
9
+ settings in stream/subset order for generic scenes, HCS wells, and retained
10
+ source tiles, and preserve them when generating pyramids so
11
+ `napari-ome-zarr` automatically restores channel colors. Missing or invalid
12
+ XML colors warn and fall back to neutral grayscale.
13
+
14
+ ## 0.0.3 - 2026-11-18
15
+
16
+ ### Fixed
17
+
18
+ - Closing or removing the Experiment Selector dock now closes its pixel
19
+ stream subscriptions and cancels owned background tasks, including the
20
+ dedicated OME-ZARR writer. The ZEN acquisition and napari remain open.
21
+ - Start-selected Display mode no longer subscribes before Start is clicked.
22
+ The selected experiment ID is armed before subscription and acquisition,
23
+ retained through trailing-frame delivery, and cleared after finalization
24
+ when the reader returns to an unsubscribed idle state.
25
+ - Mode and channel-filter changes no longer arm an idle selected-experiment
26
+ reader. Passive watch mode continues to subscribe immediately.
27
+ - Serialize reader transitions to prevent duplicate listeners during
28
+ overlapping shutdown, mode changes, and repeated acquisitions.
29
+
30
+ ### Added
31
+
32
+ - Stream-lifecycle regression tests covering idle modes, mode and channel
33
+ changes, experiment filtering, repeated runs, failed starts, dock closure
34
+ and removal, dedicated-writer cancellation, and embedded worker shutdown.
35
+
3
36
  ## 0.0.2 - 2026-11-17
4
37
 
5
38
  ### Added
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: napari-zenapi-streaming
3
- Version: 0.0.2
3
+ Version: 0.0.4
4
4
  Summary: ZEN API streaming plugin for napari
5
5
  Author-email: "Krijn H. van der Steen" <k.h.vandersteen@umcutrecht.nl>, Sebastian Rhode <sebastian.rhode@zeiss.com>
6
6
  License-Expression: BSD-3-Clause
@@ -94,18 +94,23 @@ When finished the resulting OME-ZARR, created from the ZEN pixel stream can be s
94
94
 
95
95
  ## Current status
96
96
 
97
- - Release: **0.0.2** ([release notes](_release_notes/v0.0.2.md)).
97
+ - Release: **0.0.4** ([release notes](_release_notes/v0.0.4.md)).
98
98
  - Project phase: alpha / MVP
99
99
  - Primary OS target: Windows for ZEN Blue and the ZEN API Gateway
100
100
  - Python target: `>=3.12, <3.15`
101
101
 
102
- ### What's new in 0.0.2
102
+ ### What's new in 0.0.4
103
103
 
104
- - Original GRAY8/GRAY16 pixels in Display mode, without per-tile stretching.
105
- - Optional stream-only viewing with channel filtering and no final mosaic.
106
- - Scrollable experiment controls for smaller plugin docks.
107
- - OME-Zarr 0.6 output and collection-opening fixes. Reading older OME-Zarr
108
- acquisitions now requires explicit conversion outside the plugin.
104
+ - Configured OME-ZARR acquisition preserves active channel names and actual
105
+ display colors from the selected ZEN experiment.
106
+ - Per-image OMERO display metadata follows channel subscriptions and
107
+ single-channel selections across generic scenes, HCS wells, and retained
108
+ source tiles.
109
+ - Pyramid generation retains these settings so `napari-ome-zarr` opens new
110
+ output with the experiment's colors. Missing or invalid colors warn and
111
+ use neutral grayscale rather than guessing a biological color.
112
+ - See the [0.0.3 release notes](_release_notes/v0.0.3.md) for the preceding
113
+ stream-activation and shutdown fixes.
109
114
 
110
115
  ## Known limitations
111
116
 
@@ -250,17 +255,18 @@ without confirming redistribution rights.
250
255
  For a published PyPI release:
251
256
 
252
257
  ```powershell
253
- python -m pip install "napari-zenapi-streaming==0.0.2" "napari[pyqt6]" "PyQt6>=6.7,<6.10"
258
+ python -m pip install "napari-zenapi-streaming==0.0.4" "napari[pyqt6]" "PyQt6>=6.7,<6.10"
254
259
  ```
255
260
 
256
261
  To upgrade an existing environment with compatible ZEN wheels installed:
257
262
 
258
263
  ```powershell
259
- python -m pip install --upgrade "napari-zenapi-streaming==0.0.2"
264
+ python -m pip install --upgrade "napari-zenapi-streaming==0.0.4"
260
265
  ```
261
266
 
262
- Restart napari after upgrading. Version 0.0.2 writes OME-Zarr 0.6 and does not
263
- automatically migrate older stores. Use a reader that supports 0.6.
267
+ Restart napari after upgrading. Version 0.0.4 writes OME-Zarr 0.6 and does not
268
+ automatically migrate older stores or add channel colors to existing output.
269
+ Use a reader that supports 0.6 and OMERO channel display metadata.
264
270
 
265
271
  From this checkout, install the plugin:
266
272
 
@@ -475,6 +481,9 @@ python -m napari_zen_streaming.main --ui-start true \
475
481
 
476
482
  The plugin UI exposes three stream modes. Connecting the plugin never starts
477
483
  an acquisition; only clicking Start in a start-capable mode does so.
484
+ Closing the **Experiment Selector** dock stops its stream subscriptions and
485
+ background tasks without stopping the acquisition in ZEN or closing napari.
486
+ Open the plugin again to establish a new connection.
478
487
 
479
488
  #### Display: watch ZEN experiment (index 0)
480
489
 
@@ -485,6 +494,8 @@ The channel filter offers All channels or labels 1-16 (ZEN indices 0-15).
485
494
  #### Display: start selected experiment (index 1)
486
495
 
487
496
  The Start button loads and triggers the selected experiment via the ZEN API.
497
+ This mode does not subscribe to the pixel stream until Start is clicked, and
498
+ returns to an unsubscribed idle state after the acquisition is finalized.
488
499
  Its XML dimensions are shown in the widget, and the channel filter offers All
489
500
  channels or exactly the channels available in that setup. Until metadata has
490
501
  loaded, only All channels is available. Changing the selected setup reloads
@@ -505,8 +516,9 @@ Both Display modes use the full async streaming pipeline (`ZEN_pipeline.py`):
505
516
  is frozen during acquisition and re-enabled after completion.
506
517
  Stream-only viewing forces the latest-frame preview, retains no history,
507
518
  and leaves the last frame visible without assembling a mosaic.
508
- 2. **Channel filter** – Changing the filter immediately restarts the pipeline
509
- reader. Labels are 1-based, while the gRPC request uses zero-based indices.
519
+ 2. **Channel filter** – Changing the filter restarts an active pipeline reader
520
+ but does not open a stream in an idle start-selected mode. Labels are
521
+ 1-based, while the gRPC request uses zero-based indices.
510
522
  The initial value comes from `ZEN_CHANNEL_INDEX` in `.env`; leave it empty
511
523
  to receive all channels. An out-of-range choice resets to All channels.
512
524
  3. **Completion detection** –
@@ -523,15 +535,16 @@ Both Display modes use the full async streaming pipeline (`ZEN_pipeline.py`):
523
535
  5D layers (`S, T, Z, Y, X`). In overlap regions, pixels from the tile with
524
536
  the higher M index replace pixels from lower-M tiles.
525
537
 
526
- **Experiment identity:** Display mode keeps one
538
+ **Experiment identity:** While watching or acquiring, Display mode keeps one
527
539
  `monitor_all_experiments()` subscription open because the targeted ZEN stream
528
540
  can close when experiment status changes to finished, before trailing pixel
529
541
  payloads have arrived. For a Napari-started acquisition, the plugin loads the
530
542
  experiment first, arms a client-side filter for its `FrameData.experiment_id`,
531
543
  and only then starts acquisition. Frames from other experiments are ignored
532
544
  while that filter is active, including during trailing-frame drain. The filter
533
- is cleared after final restructure so later ZEN-started acquisitions remain
534
- discoverable. A ZEN-started run has no experiment ID known in advance and
545
+ is cleared and the subscription is closed after final restructure. Switch to
546
+ **Display: watch ZEN experiment** to discover independently started runs.
547
+ A ZEN-started run has no experiment ID known in advance and
535
548
  therefore continues to accept the global stream; keep only one such
536
549
  acquisition active at a time.
537
550
 
@@ -627,6 +640,17 @@ and **Create pyramid after acquisition** in its UI. When enabled, choose how
627
640
  many 2x Y/X downsampled levels to append after acquisition completes. Napari
628
641
  opens the OME-Zarr only after pyramid generation finishes. Existing level `0`
629
642
  is reused and is never rewritten.
643
+ Active channel names and display colors come from the selected experiment's
644
+ exported XML, in the same order as the channel subscriptions. ZEN's
645
+ `#AARRGGBB` colors are saved as OMERO `RRGGBB` colors on every image
646
+ (including HCS wells and retained source tiles), with display limits from
647
+ the runtime pixel type. Selecting a single channel retains that source
648
+ channel's name and color. Pyramid generation preserves these settings, so
649
+ `napari-ome-zarr` automatically opens the images with their ZEN colors.
650
+ Missing or invalid XML colors produce a warning and use neutral grayscale,
651
+ not an inferred fluorophore color. Direct writer configurations without
652
+ channel metadata keep the previous reader-default behavior.
653
+
630
654
  Generic scene mosaics also expose **Keep individual source tiles**; unchecked
631
655
  removes source groups only after mosaic creation succeeds. Advanced values
632
656
  intentionally use fixed defaults declared at the top of `ZEN_omezarr.py`:
@@ -42,18 +42,23 @@ When finished the resulting OME-ZARR, created from the ZEN pixel stream can be s
42
42
 
43
43
  ## Current status
44
44
 
45
- - Release: **0.0.2** ([release notes](_release_notes/v0.0.2.md)).
45
+ - Release: **0.0.4** ([release notes](_release_notes/v0.0.4.md)).
46
46
  - Project phase: alpha / MVP
47
47
  - Primary OS target: Windows for ZEN Blue and the ZEN API Gateway
48
48
  - Python target: `>=3.12, <3.15`
49
49
 
50
- ### What's new in 0.0.2
50
+ ### What's new in 0.0.4
51
51
 
52
- - Original GRAY8/GRAY16 pixels in Display mode, without per-tile stretching.
53
- - Optional stream-only viewing with channel filtering and no final mosaic.
54
- - Scrollable experiment controls for smaller plugin docks.
55
- - OME-Zarr 0.6 output and collection-opening fixes. Reading older OME-Zarr
56
- acquisitions now requires explicit conversion outside the plugin.
52
+ - Configured OME-ZARR acquisition preserves active channel names and actual
53
+ display colors from the selected ZEN experiment.
54
+ - Per-image OMERO display metadata follows channel subscriptions and
55
+ single-channel selections across generic scenes, HCS wells, and retained
56
+ source tiles.
57
+ - Pyramid generation retains these settings so `napari-ome-zarr` opens new
58
+ output with the experiment's colors. Missing or invalid colors warn and
59
+ use neutral grayscale rather than guessing a biological color.
60
+ - See the [0.0.3 release notes](_release_notes/v0.0.3.md) for the preceding
61
+ stream-activation and shutdown fixes.
57
62
 
58
63
  ## Known limitations
59
64
 
@@ -198,17 +203,18 @@ without confirming redistribution rights.
198
203
  For a published PyPI release:
199
204
 
200
205
  ```powershell
201
- python -m pip install "napari-zenapi-streaming==0.0.2" "napari[pyqt6]" "PyQt6>=6.7,<6.10"
206
+ python -m pip install "napari-zenapi-streaming==0.0.4" "napari[pyqt6]" "PyQt6>=6.7,<6.10"
202
207
  ```
203
208
 
204
209
  To upgrade an existing environment with compatible ZEN wheels installed:
205
210
 
206
211
  ```powershell
207
- python -m pip install --upgrade "napari-zenapi-streaming==0.0.2"
212
+ python -m pip install --upgrade "napari-zenapi-streaming==0.0.4"
208
213
  ```
209
214
 
210
- Restart napari after upgrading. Version 0.0.2 writes OME-Zarr 0.6 and does not
211
- automatically migrate older stores. Use a reader that supports 0.6.
215
+ Restart napari after upgrading. Version 0.0.4 writes OME-Zarr 0.6 and does not
216
+ automatically migrate older stores or add channel colors to existing output.
217
+ Use a reader that supports 0.6 and OMERO channel display metadata.
212
218
 
213
219
  From this checkout, install the plugin:
214
220
 
@@ -423,6 +429,9 @@ python -m napari_zen_streaming.main --ui-start true \
423
429
 
424
430
  The plugin UI exposes three stream modes. Connecting the plugin never starts
425
431
  an acquisition; only clicking Start in a start-capable mode does so.
432
+ Closing the **Experiment Selector** dock stops its stream subscriptions and
433
+ background tasks without stopping the acquisition in ZEN or closing napari.
434
+ Open the plugin again to establish a new connection.
426
435
 
427
436
  #### Display: watch ZEN experiment (index 0)
428
437
 
@@ -433,6 +442,8 @@ The channel filter offers All channels or labels 1-16 (ZEN indices 0-15).
433
442
  #### Display: start selected experiment (index 1)
434
443
 
435
444
  The Start button loads and triggers the selected experiment via the ZEN API.
445
+ This mode does not subscribe to the pixel stream until Start is clicked, and
446
+ returns to an unsubscribed idle state after the acquisition is finalized.
436
447
  Its XML dimensions are shown in the widget, and the channel filter offers All
437
448
  channels or exactly the channels available in that setup. Until metadata has
438
449
  loaded, only All channels is available. Changing the selected setup reloads
@@ -453,8 +464,9 @@ Both Display modes use the full async streaming pipeline (`ZEN_pipeline.py`):
453
464
  is frozen during acquisition and re-enabled after completion.
454
465
  Stream-only viewing forces the latest-frame preview, retains no history,
455
466
  and leaves the last frame visible without assembling a mosaic.
456
- 2. **Channel filter** – Changing the filter immediately restarts the pipeline
457
- reader. Labels are 1-based, while the gRPC request uses zero-based indices.
467
+ 2. **Channel filter** – Changing the filter restarts an active pipeline reader
468
+ but does not open a stream in an idle start-selected mode. Labels are
469
+ 1-based, while the gRPC request uses zero-based indices.
458
470
  The initial value comes from `ZEN_CHANNEL_INDEX` in `.env`; leave it empty
459
471
  to receive all channels. An out-of-range choice resets to All channels.
460
472
  3. **Completion detection** –
@@ -471,15 +483,16 @@ Both Display modes use the full async streaming pipeline (`ZEN_pipeline.py`):
471
483
  5D layers (`S, T, Z, Y, X`). In overlap regions, pixels from the tile with
472
484
  the higher M index replace pixels from lower-M tiles.
473
485
 
474
- **Experiment identity:** Display mode keeps one
486
+ **Experiment identity:** While watching or acquiring, Display mode keeps one
475
487
  `monitor_all_experiments()` subscription open because the targeted ZEN stream
476
488
  can close when experiment status changes to finished, before trailing pixel
477
489
  payloads have arrived. For a Napari-started acquisition, the plugin loads the
478
490
  experiment first, arms a client-side filter for its `FrameData.experiment_id`,
479
491
  and only then starts acquisition. Frames from other experiments are ignored
480
492
  while that filter is active, including during trailing-frame drain. The filter
481
- is cleared after final restructure so later ZEN-started acquisitions remain
482
- discoverable. A ZEN-started run has no experiment ID known in advance and
493
+ is cleared and the subscription is closed after final restructure. Switch to
494
+ **Display: watch ZEN experiment** to discover independently started runs.
495
+ A ZEN-started run has no experiment ID known in advance and
483
496
  therefore continues to accept the global stream; keep only one such
484
497
  acquisition active at a time.
485
498
 
@@ -575,6 +588,17 @@ and **Create pyramid after acquisition** in its UI. When enabled, choose how
575
588
  many 2x Y/X downsampled levels to append after acquisition completes. Napari
576
589
  opens the OME-Zarr only after pyramid generation finishes. Existing level `0`
577
590
  is reused and is never rewritten.
591
+ Active channel names and display colors come from the selected experiment's
592
+ exported XML, in the same order as the channel subscriptions. ZEN's
593
+ `#AARRGGBB` colors are saved as OMERO `RRGGBB` colors on every image
594
+ (including HCS wells and retained source tiles), with display limits from
595
+ the runtime pixel type. Selecting a single channel retains that source
596
+ channel's name and color. Pyramid generation preserves these settings, so
597
+ `napari-ome-zarr` automatically opens the images with their ZEN colors.
598
+ Missing or invalid XML colors produce a warning and use neutral grayscale,
599
+ not an inferred fluorophore color. Direct writer configurations without
600
+ channel metadata keep the previous reader-default behavior.
601
+
578
602
  Generic scene mosaics also expose **Keep individual source tiles**; unchecked
579
603
  removes source groups only after mosaic creation succeeds. Advanced values
580
604
  intentionally use fixed defaults declared at the top of `ZEN_omezarr.py`:
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "napari-zenapi-streaming"
3
- version = "0.0.2"
3
+ version = "0.0.4"
4
4
  description = "ZEN API streaming plugin for napari"
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.12, <3.15"
@@ -116,7 +116,10 @@ def finalize_omezarr_output(zarr_path: Path) -> None:
116
116
  converted_ome = converted.attrs["ome"]
117
117
  if not isinstance(converted_ome, Mapping):
118
118
  raise ValueError(f"Invalid converted OME-Zarr metadata: {path}")
119
- converted.attrs.update({**attributes, "ome": {**ome, **converted_ome}})
119
+ merged_ome = {**ome, **converted_ome}
120
+ if "omero" in ome:
121
+ merged_ome["omero"] = ome["omero"]
122
+ converted.attrs.update({**attributes, "ome": merged_ome})
120
123
  nz.from_ngff_zarr(path, validate=True, kind="multiscales")
121
124
  image_count += 1
122
125
  if not image_count:
@@ -135,6 +138,14 @@ def finalize_omezarr_output(zarr_path: Path) -> None:
135
138
  )
136
139
 
137
140
 
141
+ @dataclass(frozen=True)
142
+ class ExperimentChannelMetadata:
143
+ """Display metadata for one active ZEN channel in subscription order."""
144
+
145
+ name: str | None = None
146
+ color: str | None = None
147
+
148
+
138
149
  @dataclass
139
150
  class ExperimentConfig:
140
151
  """Parsed experiment configuration."""
@@ -166,6 +177,7 @@ class ExperimentConfig:
166
177
  spatial_shard_size_chunks: int | None = 2
167
178
  max_pending_frames: int = 4096
168
179
  pyramid_levels: int = 0
180
+ channel_metadata: tuple[ExperimentChannelMetadata, ...] = ()
169
181
 
170
182
 
171
183
  def create_plugin_experiment_config(
@@ -224,7 +236,7 @@ def create_plugin_experiment_config(
224
236
 
225
237
  @dataclass(frozen=True)
226
238
  class ExperimentAcquisitionMetadata:
227
- """Acquisition dimensions and positions exported from a ZEN experiment."""
239
+ """Dimensions, positions, and active channels exported by ZEN."""
228
240
 
229
241
  experiment_name: str
230
242
  time_points: int
@@ -234,6 +246,7 @@ class ExperimentAcquisitionMetadata:
234
246
  tiles: int
235
247
  scenes: int
236
248
  positions: tuple[dict[str, object], ...] = ()
249
+ channel_metadata: tuple[ExperimentChannelMetadata, ...] = ()
237
250
 
238
251
 
239
252
  def _xml_is_active(element: ET.Element | None, default: bool = True) -> bool:
@@ -469,11 +482,38 @@ def _parse_xml_tile_layout(block: ET.Element) -> tuple[int, int]:
469
482
  return max(tile_counts), len(tile_counts)
470
483
 
471
484
 
485
+ def _extract_xml_channels(
486
+ block: ET.Element,
487
+ ) -> tuple[ExperimentChannelMetadata, ...]:
488
+ """Read active track/channel names and ZEN ARGB colors in stream order."""
489
+ channels = []
490
+ for track in block.findall(".//MultiTrackSetup/Track"):
491
+ if not _xml_is_active(track):
492
+ continue
493
+ for channel in track.findall("./Channels/Channel"):
494
+ if not _xml_is_active(channel):
495
+ continue
496
+ name = channel.get("Name") or None
497
+ value = _xml_text(channel, "Color")
498
+ color = None
499
+ if value is not None and re.fullmatch(r"#[0-9A-Fa-f]{8}", value):
500
+ color = value[3:].upper()
501
+ else:
502
+ logger.warning(
503
+ "Active channel %s has missing or invalid ZEN ARGB "
504
+ "Color %r; OME-Zarr display will use neutral grayscale.",
505
+ name or len(channels),
506
+ value,
507
+ )
508
+ channels.append(ExperimentChannelMetadata(name, color))
509
+ return tuple(channels)
510
+
511
+
472
512
  def parse_experiment_xml(
473
513
  xml: str,
474
514
  experiment_name: str = "<experiment-export>",
475
515
  ) -> ExperimentAcquisitionMetadata:
476
- """Parse acquisition dimensions from a ZEN ``.czexp`` XML document."""
516
+ """Parse acquisition and channel metadata from ZEN ``.czexp`` XML."""
477
517
  root = ET.fromstring(xml)
478
518
  blocks = root.findall("./ExperimentBlocks/AcquisitionBlock")
479
519
  active_blocks = [block for block in blocks if _xml_is_active(block)]
@@ -486,13 +526,7 @@ def parse_experiment_xml(
486
526
  time_setup = _find_active_dimension_setup(block, "TimeSeriesSetup")
487
527
  time_points = max(1, _xml_int(time_setup, "Duration/Cycles"))
488
528
 
489
- channels = sum(
490
- 1
491
- for track in block.findall(".//MultiTrackSetup/Track")
492
- if _xml_is_active(track)
493
- for channel in track.findall("./Channels/Channel")
494
- if _xml_is_active(channel)
495
- )
529
+ channel_metadata = _extract_xml_channels(block)
496
530
 
497
531
  z_setup = _find_active_dimension_setup(block, "ZStackSetup")
498
532
  first = _xml_float(z_setup, "First/Distance/Value")
@@ -511,15 +545,71 @@ def parse_experiment_xml(
511
545
  return ExperimentAcquisitionMetadata(
512
546
  experiment_name=experiment_name,
513
547
  time_points=time_points,
514
- channels=max(1, channels),
548
+ channels=max(1, len(channel_metadata)),
515
549
  z_planes=z_planes,
516
550
  z_spacing=z_spacing,
517
551
  tiles=tiles,
518
552
  scenes=scenes,
519
553
  positions=positions,
554
+ channel_metadata=channel_metadata,
520
555
  )
521
556
 
522
557
 
558
+ def write_omezarr_channel_metadata(
559
+ zarr_path: Path,
560
+ channels: tuple[ExperimentChannelMetadata, ...],
561
+ source_channels: list[int],
562
+ ) -> None:
563
+ """Persist OMERO display settings on every final and retained image.
564
+
565
+ Source indices are the explicit subscriptions, not XML channel IDs or
566
+ frame C values. Only array metadata is read; intensities are unchanged.
567
+ """
568
+ import numpy as np
569
+ import zarr
570
+
571
+ if not channels:
572
+ return
573
+ if any(index < 0 or index >= len(channels) for index in source_channels):
574
+ raise ValueError("Selected stream channel has no experiment metadata")
575
+ selected = [channels[index] for index in source_channels]
576
+ for path, group in _omezarr_groups(zarr_path):
577
+ attributes: dict[str, Any] = dict(group.attrs)
578
+ ome = attributes.get("ome", {})
579
+ if not isinstance(ome, Mapping) or not ome.get("multiscales"):
580
+ continue
581
+ dataset = ome["multiscales"][0]["datasets"][0]["path"]
582
+ array = group[dataset]
583
+ if not isinstance(array, zarr.Array):
584
+ raise ValueError(f"Image dataset is not an array: {path}")
585
+ limits = np.iinfo(array.dtype)
586
+ display_channels = []
587
+ for source_index, channel in zip(
588
+ source_channels, selected, strict=True
589
+ ):
590
+ display_channels.append(
591
+ {
592
+ "label": channel.name or f"channel_{source_index}",
593
+ "color": channel.color or "FFFFFF",
594
+ "active": True,
595
+ "window": {
596
+ "min": int(limits.min),
597
+ "max": int(limits.max),
598
+ "start": int(limits.min),
599
+ "end": int(limits.max),
600
+ },
601
+ }
602
+ )
603
+ writable = zarr.open_group(path, mode="a", use_consolidated=False)
604
+ writable.attrs["ome"] = {
605
+ **ome,
606
+ "omero": {
607
+ "channels": display_channels,
608
+ "rdefs": {"model": "color"},
609
+ },
610
+ }
611
+
612
+
523
613
  def parse_experiment_file(
524
614
  path: str | Path,
525
615
  ) -> ExperimentAcquisitionMetadata:
@@ -92,9 +92,11 @@ class StreamingPipeline:
92
92
  # and the standalone OME-ZARR writer only receives half of them.
93
93
  self._reader_iter: Any = None
94
94
  self._reader_ready = asyncio.Event()
95
+ self._reader_lock = asyncio.Lock()
95
96
 
96
97
  # Napari-started runs use the perpetual all-experiments transport but
97
- # accept only frames carrying this ID. None preserves ZEN-started mode.
98
+ # accept only frames carrying this ID. None accepts frames in watch
99
+ # mode only.
98
100
  self._target_experiment_id: str | None = None
99
101
 
100
102
  # Processor task processes frames and updates viewer
@@ -109,16 +111,13 @@ class StreamingPipeline:
109
111
  """
110
112
  Start the streaming pipeline.
111
113
 
112
- Creates and starts two concurrent tasks:
113
- 1. Reader task: Pulls frames from ZEN API
114
- 2. Processor task: Processes frames from queue
115
-
116
- Both tasks run concurrently until stop() is called.
114
+ Start the processor and, in watch mode, the pixel reader. Selected
115
+ acquisition modes open their reader only when explicitly armed.
117
116
  """
118
117
  logger.debug("Starting streaming pipeline")
119
118
 
120
- # Start reader and processor tasks concurrently
121
- self.reader_task = asyncio.create_task(self._read_frames())
119
+ # Selected-experiment modes stay disconnected until explicitly armed.
120
+ await self.resume_reader()
122
121
  self.processor_task = asyncio.create_task(self._process_frames())
123
122
 
124
123
  logger.debug("Pipeline started - reader and processor tasks running")
@@ -139,13 +138,8 @@ class StreamingPipeline:
139
138
  # Signal all tasks to stop
140
139
  self.stop_event.set()
141
140
 
142
- # Cancel reader task (blocking on ZEN API async iterator)
143
- if self.reader_task:
144
- self.reader_task.cancel()
145
- try:
146
- await self.reader_task
147
- except asyncio.CancelledError:
148
- logger.debug("Reader task cancelled successfully")
141
+ # Serialize shutdown with any pending mode or channel change.
142
+ await self.suspend_reader()
149
143
 
150
144
  # Wait for queue to empty (process remaining frames)
151
145
  if self.queue:
@@ -298,12 +292,35 @@ class StreamingPipeline:
298
292
 
299
293
  def _accepts_response(self, response: Any) -> bool:
300
294
  """Return whether a streamed frame matches the active target."""
295
+ if not self.reader_enabled:
296
+ return False
301
297
  target = self._target_experiment_id
302
298
  return target is None or response.frame_data.experiment_id == target
303
299
 
300
+ @property
301
+ def reader_enabled(self) -> bool:
302
+ """Allow passive watching or one explicitly armed display run."""
303
+ return (
304
+ not self.stop_event.is_set()
305
+ and not self.viewer.closed.is_set()
306
+ and not self.viewer._standalone_zarr_active
307
+ and (
308
+ self.viewer.watch_enabled
309
+ or self._target_experiment_id is not None
310
+ )
311
+ )
312
+
313
+ async def refresh_reader(self) -> None:
314
+ """Apply mode and channel changes without arming an idle reader."""
315
+ async with self._reader_lock:
316
+ await self._suspend_reader()
317
+ self._resume_reader()
318
+
304
319
  async def ensure_reader_ready(self) -> None:
305
320
  """Ensure the perpetual all-experiments stream is armed."""
306
321
  await self.resume_reader()
322
+ if not self.reader_enabled:
323
+ raise RuntimeError("Pixel stream is not armed or has been closed")
307
324
  await self._reader_ready.wait()
308
325
 
309
326
  async def start_targeted_experiment(
@@ -313,23 +330,23 @@ class StreamingPipeline:
313
330
  ) -> str:
314
331
  """Prepare, filter, and start one napari-triggered experiment.
315
332
 
316
- The all-experiments stream is opened first for reliable trailing-frame
317
- delivery. ZEN then loads the experiment, the client-side ID filter is
318
- armed, and only then is acquisition started.
333
+ Load the experiment and arm its ID filter before opening the global
334
+ stream. Keep that stream open through trailing-frame delivery.
319
335
  """
320
- await self.ensure_reader_ready()
321
336
  experiment_id = await self.connection.prepare_experiment(
322
337
  experiment_name,
323
338
  overwrite=overwrite,
324
339
  )
325
340
  self.set_target_experiment(experiment_id)
326
341
  try:
342
+ await self.ensure_reader_ready()
327
343
  await self.connection.start_loaded_experiment(
328
344
  experiment_id,
329
345
  experiment_name,
330
346
  )
331
- except Exception:
347
+ except (Exception, asyncio.CancelledError):
332
348
  self.set_target_experiment(None)
349
+ await self.suspend_reader()
333
350
  raise
334
351
  return experiment_id
335
352
 
@@ -429,6 +446,11 @@ class StreamingPipeline:
429
446
 
430
447
  Safe to call when no reader is running (no-op).
431
448
  """
449
+ async with self._reader_lock:
450
+ await self._suspend_reader()
451
+
452
+ async def _suspend_reader(self) -> None:
453
+ """Close the current reader while holding the lifecycle lock."""
432
454
  if self.reader_task and not self.reader_task.done():
433
455
  self.reader_task.cancel()
434
456
  with contextlib.suppress(asyncio.CancelledError):
@@ -451,6 +473,14 @@ class StreamingPipeline:
451
473
  the next experiment in Display mode. Safe to call when the reader
452
474
  is already running (no-op).
453
475
  """
476
+ async with self._reader_lock:
477
+ self._resume_reader()
478
+
479
+ def _resume_reader(self) -> None:
480
+ """Open an eligible reader while holding the lifecycle lock."""
481
+ if not self.reader_enabled:
482
+ logger.debug("Pixel reader remains idle")
483
+ return
454
484
  if self.reader_task and not self.reader_task.done():
455
485
  logger.debug("Pipeline reader already running – skipping resume")
456
486
  return