napari-zenapi-streaming 0.0.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- napari_zen_streaming/ZEN_config.py +268 -0
- napari_zen_streaming/ZEN_init.py +359 -0
- napari_zen_streaming/ZEN_omezarr.py +909 -0
- napari_zen_streaming/ZEN_pipeline.py +477 -0
- napari_zen_streaming/ZEN_stream2omezarr.py +2326 -0
- napari_zen_streaming/ZEN_ui.py +2991 -0
- napari_zen_streaming/ZEN_utils.py +170 -0
- napari_zen_streaming/__init__.py +5 -0
- napari_zen_streaming/_logging.py +100 -0
- napari_zen_streaming/_scene_geometry.py +202 -0
- napari_zen_streaming/_tests/__init__.py +0 -0
- napari_zen_streaming/_tests/test_config.py +139 -0
- napari_zen_streaming/_tests/test_display_completion.py +62 -0
- napari_zen_streaming/_tests/test_experiment_stream_filter.py +140 -0
- napari_zen_streaming/_tests/test_experiment_xml.py +220 -0
- napari_zen_streaming/_tests/test_hcs_ui_option.py +189 -0
- napari_zen_streaming/_tests/test_initial_experiment_selection.py +589 -0
- napari_zen_streaming/_tests/test_live_preview.py +287 -0
- napari_zen_streaming/_tests/test_logging.py +68 -0
- napari_zen_streaming/_tests/test_progress_reporting.py +178 -0
- napari_zen_streaming/_tests/test_runtime_pixel_type.py +105 -0
- napari_zen_streaming/_tests/test_scene_geometry.py +97 -0
- napari_zen_streaming/_tests/test_scene_mosaic.py +660 -0
- napari_zen_streaming/_widget.py +126 -0
- napari_zen_streaming/main.py +236 -0
- napari_zen_streaming/misc.py +65 -0
- napari_zen_streaming/napari.yaml +10 -0
- napari_zenapi_streaming-0.0.1.dist-info/METADATA +884 -0
- napari_zenapi_streaming-0.0.1.dist-info/RECORD +33 -0
- napari_zenapi_streaming-0.0.1.dist-info/WHEEL +5 -0
- napari_zenapi_streaming-0.0.1.dist-info/entry_points.txt +2 -0
- napari_zenapi_streaming-0.0.1.dist-info/licenses/LICENSE +27 -0
- napari_zenapi_streaming-0.0.1.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,268 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Configuration for ZEN API streaming application.
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import configparser
|
|
7
|
+
import logging
|
|
8
|
+
import os
|
|
9
|
+
import sys
|
|
10
|
+
from dataclasses import dataclass, field
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
import numpy as np
|
|
14
|
+
from dotenv import load_dotenv
|
|
15
|
+
|
|
16
|
+
logger = logging.getLogger(__name__)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def default_config_dir() -> Path:
|
|
20
|
+
"""Return the platform-specific directory for user-owned configuration."""
|
|
21
|
+
if sys.platform == "win32":
|
|
22
|
+
base = Path(
|
|
23
|
+
os.getenv("APPDATA") or Path.home() / "AppData" / "Roaming"
|
|
24
|
+
)
|
|
25
|
+
else:
|
|
26
|
+
base = Path(os.getenv("XDG_CONFIG_HOME") or Path.home() / ".config")
|
|
27
|
+
return base / "napari-zenapi-streaming"
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def default_gateway_config() -> Path:
|
|
31
|
+
"""Prefer user configuration while retaining source-checkout defaults."""
|
|
32
|
+
user_config = default_config_dir() / "config.ini"
|
|
33
|
+
if user_config.is_file():
|
|
34
|
+
return user_config
|
|
35
|
+
working_config = Path.cwd() / "config.ini"
|
|
36
|
+
if working_config.is_file():
|
|
37
|
+
return working_config
|
|
38
|
+
checkout = Path(__file__).resolve().parents[2]
|
|
39
|
+
checkout_config = checkout / "config.ini"
|
|
40
|
+
if (checkout / "pyproject.toml").is_file() and checkout_config.is_file():
|
|
41
|
+
return checkout_config
|
|
42
|
+
return user_config
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def resolve_gateway_config() -> Path:
|
|
46
|
+
"""Return ``ZEN_CONFIG_FILE`` when set, else the default gateway config."""
|
|
47
|
+
config_file_raw = os.getenv("ZEN_CONFIG_FILE")
|
|
48
|
+
if not config_file_raw:
|
|
49
|
+
return default_gateway_config()
|
|
50
|
+
config_file = Path(config_file_raw).expanduser().resolve()
|
|
51
|
+
if config_file_raw == "config.ini" and not config_file.is_file():
|
|
52
|
+
return default_gateway_config()
|
|
53
|
+
return config_file
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def load_runtime_settings() -> Path | None:
|
|
57
|
+
"""Load optional user settings without replacing process environment.
|
|
58
|
+
|
|
59
|
+
``ZEN_ENV_FILE`` selects an explicit dotenv file. Otherwise the user
|
|
60
|
+
configuration directory is preferred, with a package-local dotenv file
|
|
61
|
+
retained only for editable source checkouts.
|
|
62
|
+
"""
|
|
63
|
+
explicit = os.getenv("ZEN_ENV_FILE")
|
|
64
|
+
settings_file = (
|
|
65
|
+
Path(explicit).expanduser()
|
|
66
|
+
if explicit
|
|
67
|
+
else default_config_dir() / ".env"
|
|
68
|
+
)
|
|
69
|
+
if explicit and not settings_file.is_file():
|
|
70
|
+
raise FileNotFoundError(f"Settings file not found: {settings_file}")
|
|
71
|
+
if not explicit and not settings_file.is_file():
|
|
72
|
+
package_file = Path(__file__).parent / ".env"
|
|
73
|
+
if (Path(__file__).resolve().parents[2] / "pyproject.toml").is_file():
|
|
74
|
+
settings_file = package_file
|
|
75
|
+
if not settings_file.is_file():
|
|
76
|
+
return None
|
|
77
|
+
load_dotenv(settings_file, override=False)
|
|
78
|
+
return settings_file
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def initialize_user_config() -> Path:
|
|
82
|
+
"""Create a gateway configuration template without overwriting a file."""
|
|
83
|
+
config_file = default_config_dir() / "config.ini"
|
|
84
|
+
config_file.parent.mkdir(parents=True, exist_ok=True)
|
|
85
|
+
template = configparser.ConfigParser()
|
|
86
|
+
template.read_dict(
|
|
87
|
+
{
|
|
88
|
+
"api": {
|
|
89
|
+
"host": "127.0.0.1",
|
|
90
|
+
"port": "5000",
|
|
91
|
+
"cert_file": r"C:\ProgramData\Carl Zeiss\ZenApiGateway\Certificates\ZenApiPersonalSigningRootCA.pem",
|
|
92
|
+
"control-token": "<YOUR_CONTROL_TOKEN_HERE>",
|
|
93
|
+
},
|
|
94
|
+
"image_streaming": {"host": "127.0.0.1", "port": "5280"},
|
|
95
|
+
}
|
|
96
|
+
)
|
|
97
|
+
with config_file.open("x", encoding="utf-8") as handle:
|
|
98
|
+
template.write(handle)
|
|
99
|
+
return config_file
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
# Raw ZEN stream dtype used by Display mode and legacy paths. The OME-ZARR
|
|
103
|
+
# writer derives its dtype from each runtime frame's PixelType instead.
|
|
104
|
+
DEFAULT_PIXEL_DTYPE = np.dtype(np.uint16)
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
@dataclass(frozen=True)
|
|
108
|
+
class ZENConfig:
|
|
109
|
+
"""Immutable configuration for ZEN API connection and experiment."""
|
|
110
|
+
|
|
111
|
+
# Experiment configuration
|
|
112
|
+
exp_name: str
|
|
113
|
+
exp_started_by_ui: bool = False
|
|
114
|
+
|
|
115
|
+
# API configuration
|
|
116
|
+
config_file: Path = field(default_factory=default_gateway_config)
|
|
117
|
+
|
|
118
|
+
# Data configuration
|
|
119
|
+
pixel_dtype: np.dtype = field(default_factory=lambda: DEFAULT_PIXEL_DTYPE)
|
|
120
|
+
display_dtype: np.dtype = field(default_factory=lambda: np.dtype(np.uint8))
|
|
121
|
+
|
|
122
|
+
# Processing configuration
|
|
123
|
+
image_buffer_size: int = 100
|
|
124
|
+
enable_raw_data: bool = False
|
|
125
|
+
channel_index: int | None = None
|
|
126
|
+
|
|
127
|
+
# Viewer configuration
|
|
128
|
+
# Seconds to wait before restructuring the live preview to final layers.
|
|
129
|
+
restructure_timeout: float = 10.0
|
|
130
|
+
show_only_last_frame_during_live: bool = True
|
|
131
|
+
|
|
132
|
+
# Default selections for the UI
|
|
133
|
+
default_output_dir: str = ""
|
|
134
|
+
|
|
135
|
+
def __post_init__(self) -> None:
|
|
136
|
+
"""
|
|
137
|
+
Validate configuration after initialization.
|
|
138
|
+
|
|
139
|
+
Raises:
|
|
140
|
+
FileNotFoundError: If config file doesn't exist
|
|
141
|
+
ValueError: If any configuration values are invalid
|
|
142
|
+
"""
|
|
143
|
+
if not self.config_file.is_file():
|
|
144
|
+
raise FileNotFoundError(
|
|
145
|
+
f"Config file not found: {self.config_file}. Run "
|
|
146
|
+
"python -m napari_zen_streaming.ZEN_config --init "
|
|
147
|
+
"or set ZEN_CONFIG_FILE to an existing gateway configuration."
|
|
148
|
+
)
|
|
149
|
+
|
|
150
|
+
if not self.exp_name:
|
|
151
|
+
raise ValueError("Experiment name cannot be empty")
|
|
152
|
+
|
|
153
|
+
if self.image_buffer_size < 1:
|
|
154
|
+
raise ValueError("Image buffer size must be positive")
|
|
155
|
+
|
|
156
|
+
if self.restructure_timeout <= 0:
|
|
157
|
+
raise ValueError("Restructure timeout must be positive")
|
|
158
|
+
|
|
159
|
+
logger.debug(
|
|
160
|
+
"Configuration validated: exp=%s, buffer=%s",
|
|
161
|
+
self.exp_name,
|
|
162
|
+
self.image_buffer_size,
|
|
163
|
+
)
|
|
164
|
+
|
|
165
|
+
@classmethod
|
|
166
|
+
def from_env(cls) -> "ZENConfig":
|
|
167
|
+
"""
|
|
168
|
+
Create configuration from environment variables.
|
|
169
|
+
|
|
170
|
+
Environment Variables:
|
|
171
|
+
ZEN_EXP_NAME: Experiment name (default: "ZEN_API_overview")
|
|
172
|
+
ZEN_UI_START: Start from UI? "true"/"false" (default: "true")
|
|
173
|
+
ZEN_CONFIG_FILE: Gateway config path (default: user directory)
|
|
174
|
+
ZEN_CHANNEL_INDEX: Specific channel to display (optional)
|
|
175
|
+
ZEN_RESTRUCTURE_TIMEOUT: Timeout before restructuring (default: 10.0)
|
|
176
|
+
ZEN_SHOW_ONLY_LAST_FRAME_DURING_LIVE: Use a 2D latest-frame
|
|
177
|
+
preview during acquisition (default: true)
|
|
178
|
+
ZEN_OUTPUT_DIR: Default output directory for OME-ZARR files (optional)
|
|
179
|
+
|
|
180
|
+
Returns:
|
|
181
|
+
ZENConfig: Configuration instance
|
|
182
|
+
|
|
183
|
+
Raises:
|
|
184
|
+
ValueError: If environment variables contain invalid values
|
|
185
|
+
"""
|
|
186
|
+
try:
|
|
187
|
+
config_file = resolve_gateway_config()
|
|
188
|
+
return cls(
|
|
189
|
+
exp_name=os.getenv("ZEN_EXP_NAME", "ZEN_API_overview"),
|
|
190
|
+
exp_started_by_ui=os.getenv("ZEN_UI_START", "true").lower()
|
|
191
|
+
== "true",
|
|
192
|
+
config_file=config_file,
|
|
193
|
+
channel_index=(
|
|
194
|
+
int(ci) if (ci := os.getenv("ZEN_CHANNEL_INDEX")) else None
|
|
195
|
+
),
|
|
196
|
+
restructure_timeout=float(
|
|
197
|
+
os.getenv("ZEN_RESTRUCTURE_TIMEOUT", "10.0")
|
|
198
|
+
),
|
|
199
|
+
show_only_last_frame_during_live=os.getenv(
|
|
200
|
+
"ZEN_SHOW_ONLY_LAST_FRAME_DURING_LIVE",
|
|
201
|
+
"true",
|
|
202
|
+
).lower()
|
|
203
|
+
== "true",
|
|
204
|
+
default_output_dir=os.getenv("ZEN_OUTPUT_DIR", ""),
|
|
205
|
+
)
|
|
206
|
+
except ValueError as e:
|
|
207
|
+
raise ValueError(f"Invalid environment variable value: {e}") from e
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
@dataclass
|
|
211
|
+
class ImageMetadata:
|
|
212
|
+
"""Runtime metadata for a single image frame."""
|
|
213
|
+
|
|
214
|
+
width: int
|
|
215
|
+
height: int
|
|
216
|
+
scaling_x_um: float
|
|
217
|
+
scaling_y_um: float
|
|
218
|
+
stage_x_um: float
|
|
219
|
+
stage_y_um: float
|
|
220
|
+
stage_z_um: float
|
|
221
|
+
frame_s: int
|
|
222
|
+
frame_m: int
|
|
223
|
+
frame_c: int
|
|
224
|
+
frame_h: int
|
|
225
|
+
frame_t: int
|
|
226
|
+
frame_z: int
|
|
227
|
+
|
|
228
|
+
@property
|
|
229
|
+
def shape(self) -> tuple[int, int]:
|
|
230
|
+
"""Get image shape as (height, width)."""
|
|
231
|
+
return (self.height, self.width)
|
|
232
|
+
|
|
233
|
+
@property
|
|
234
|
+
def stage_position(self) -> tuple[float, float, float]:
|
|
235
|
+
"""Get stage position as (x, y, z) in micrometers."""
|
|
236
|
+
return (self.stage_x_um, self.stage_y_um, self.stage_z_um)
|
|
237
|
+
|
|
238
|
+
@property
|
|
239
|
+
def scaling(self) -> tuple[float, float]:
|
|
240
|
+
"""Get pixel scaling as (x, y) in micrometers."""
|
|
241
|
+
return (self.scaling_x_um, self.scaling_y_um)
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def main() -> None:
|
|
245
|
+
"""Initialize configuration for an installed plugin or standalone app."""
|
|
246
|
+
parser = argparse.ArgumentParser(
|
|
247
|
+
description="Create a user-owned ZEN API configuration"
|
|
248
|
+
)
|
|
249
|
+
parser.add_argument(
|
|
250
|
+
"--init",
|
|
251
|
+
action="store_true",
|
|
252
|
+
required=True,
|
|
253
|
+
help="Create config.ini without overwriting existing settings",
|
|
254
|
+
)
|
|
255
|
+
parser.parse_args()
|
|
256
|
+
try:
|
|
257
|
+
config_file = initialize_user_config()
|
|
258
|
+
except FileExistsError:
|
|
259
|
+
parser.exit(
|
|
260
|
+
message=f"Configuration already exists: {default_config_dir() / 'config.ini'}\n"
|
|
261
|
+
)
|
|
262
|
+
parser.exit(
|
|
263
|
+
message=f"Created {config_file}. Set your control token and certificate path before connecting.\n"
|
|
264
|
+
)
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
if __name__ == "__main__":
|
|
268
|
+
main()
|
|
@@ -0,0 +1,359 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Initialization and connection management for ZEN API.
|
|
3
|
+
|
|
4
|
+
This module provides two main classes:
|
|
5
|
+
1. ZENConnection: Manages the gRPC connection to ZEN Blue and provides service stubs
|
|
6
|
+
2. ExperimentContext: Manages the lifecycle of a specific experiment
|
|
7
|
+
|
|
8
|
+
Separation of Concerns:
|
|
9
|
+
- Connection management is separate from experiment lifecycle
|
|
10
|
+
- Connection can be reused across multiple experiments
|
|
11
|
+
- Experiment context tracks whether experiment was started by UI or API
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
import logging
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
|
|
17
|
+
from zen_api.acquisition.v1beta import (
|
|
18
|
+
ExperimentServiceGetAvailableExperimentsRequest,
|
|
19
|
+
ExperimentServiceGetImageOutputPathRequest,
|
|
20
|
+
ExperimentServiceLoadRequest,
|
|
21
|
+
ExperimentServiceStartExperimentRequest,
|
|
22
|
+
ExperimentServiceStopRequest,
|
|
23
|
+
ExperimentServiceStub,
|
|
24
|
+
ExperimentStreamingServiceStub,
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
from napari_zen_streaming.misc import initialize_zenapi
|
|
28
|
+
from napari_zen_streaming.ZEN_config import ZENConfig
|
|
29
|
+
|
|
30
|
+
logger = logging.getLogger(__name__)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class ZENConnection:
|
|
34
|
+
"""
|
|
35
|
+
Manages connection to ZEN API and provides service stubs.
|
|
36
|
+
|
|
37
|
+
This class handles the low-level gRPC connection to ZEN Blue and provides
|
|
38
|
+
high-level service stubs for interacting with experiments.
|
|
39
|
+
|
|
40
|
+
Architecture:
|
|
41
|
+
- Creates persistent gRPC channel to ZEN Blue
|
|
42
|
+
- Provides ExperimentService for loading/starting experiments
|
|
43
|
+
- Provides ExperimentStreamingService for receiving image data
|
|
44
|
+
- Separates connection management from experiment lifecycle
|
|
45
|
+
|
|
46
|
+
Thread Safety:
|
|
47
|
+
- The grpclib channel and its stubs belong to their creation event loop.
|
|
48
|
+
- Schedule API calls on that loop rather than calling across threads.
|
|
49
|
+
"""
|
|
50
|
+
|
|
51
|
+
def __init__(self, config: ZENConfig):
|
|
52
|
+
"""
|
|
53
|
+
Initialize ZEN API connection.
|
|
54
|
+
|
|
55
|
+
Reads connection parameters from config.ini and establishes
|
|
56
|
+
gRPC channel to ZEN Blue application.
|
|
57
|
+
|
|
58
|
+
Args:
|
|
59
|
+
config: ZEN configuration object containing config_file path
|
|
60
|
+
|
|
61
|
+
Raises:
|
|
62
|
+
ConnectionError: If unable to connect to ZEN Blue
|
|
63
|
+
FileNotFoundError: If config file doesn't exist
|
|
64
|
+
"""
|
|
65
|
+
self.config = config
|
|
66
|
+
logger.debug(
|
|
67
|
+
f"Initializing ZEN API connection from {config.config_file}"
|
|
68
|
+
)
|
|
69
|
+
|
|
70
|
+
# Initialize gRPC channel and metadata from config file
|
|
71
|
+
# This reads host, port, and authentication from config.ini
|
|
72
|
+
self.channel, self.metadata = initialize_zenapi(
|
|
73
|
+
str(config.config_file)
|
|
74
|
+
)
|
|
75
|
+
|
|
76
|
+
# Create service stubs for API communication
|
|
77
|
+
# Streaming service: For receiving image data
|
|
78
|
+
self.streaming_service = ExperimentStreamingServiceStub(
|
|
79
|
+
channel=self.channel, metadata=self.metadata
|
|
80
|
+
)
|
|
81
|
+
|
|
82
|
+
# Experiment service: For loading, starting, managing experiments
|
|
83
|
+
self.experiment_service = ExperimentServiceStub(
|
|
84
|
+
channel=self.channel, metadata=self.metadata
|
|
85
|
+
)
|
|
86
|
+
|
|
87
|
+
logger.debug("ZEN API connection established successfully")
|
|
88
|
+
|
|
89
|
+
async def load_experiment(self, experiment_name: str) -> str:
|
|
90
|
+
"""
|
|
91
|
+
Load an experiment from ZEN.
|
|
92
|
+
|
|
93
|
+
Loads an experiment setup (.czexp file) into ZEN Blue memory.
|
|
94
|
+
Does not start acquisition - use start_experiment() for that.
|
|
95
|
+
|
|
96
|
+
Args:
|
|
97
|
+
experiment_name: Name of experiment setup to load (without .czexp extension)
|
|
98
|
+
|
|
99
|
+
Returns:
|
|
100
|
+
Experiment ID (UUID) assigned by ZEN
|
|
101
|
+
|
|
102
|
+
Raises:
|
|
103
|
+
Exception: If experiment not found or failed to load
|
|
104
|
+
|
|
105
|
+
Note:
|
|
106
|
+
Experiment must exist in ZEN's experiment folder.
|
|
107
|
+
"""
|
|
108
|
+
logger.debug(f"Loading experiment: {experiment_name}")
|
|
109
|
+
|
|
110
|
+
response = await self.experiment_service.load(
|
|
111
|
+
ExperimentServiceLoadRequest(experiment_name=experiment_name)
|
|
112
|
+
)
|
|
113
|
+
|
|
114
|
+
exp_id = response.experiment_id
|
|
115
|
+
logger.debug(
|
|
116
|
+
f"Loaded experiment '{experiment_name}' with ID: {exp_id}"
|
|
117
|
+
)
|
|
118
|
+
return exp_id
|
|
119
|
+
|
|
120
|
+
async def start_experiment(
|
|
121
|
+
self, experiment_name: str, overwrite: bool = True
|
|
122
|
+
) -> str:
|
|
123
|
+
"""
|
|
124
|
+
Load and start an experiment.
|
|
125
|
+
|
|
126
|
+
Complete workflow:
|
|
127
|
+
1. Load experiment setup from ZEN
|
|
128
|
+
2. Optionally delete existing output file
|
|
129
|
+
3. Start experiment execution (acquisition begins)
|
|
130
|
+
|
|
131
|
+
Args:
|
|
132
|
+
experiment_name: Name of experiment to start
|
|
133
|
+
overwrite: If True, delete existing .czi file (default: True)
|
|
134
|
+
|
|
135
|
+
Returns:
|
|
136
|
+
Experiment ID of the started experiment (for status monitoring)
|
|
137
|
+
|
|
138
|
+
Raises:
|
|
139
|
+
Exception: If experiment failed to load or start
|
|
140
|
+
|
|
141
|
+
Note:
|
|
142
|
+
The display pipeline uses ``exp_id`` to filter the perpetual
|
|
143
|
+
all-experiments pixel stream and to register for status updates.
|
|
144
|
+
"""
|
|
145
|
+
exp_id = await self.prepare_experiment(
|
|
146
|
+
experiment_name,
|
|
147
|
+
overwrite=overwrite,
|
|
148
|
+
)
|
|
149
|
+
await self.start_loaded_experiment(exp_id, experiment_name)
|
|
150
|
+
return exp_id
|
|
151
|
+
|
|
152
|
+
async def prepare_experiment(
|
|
153
|
+
self,
|
|
154
|
+
experiment_name: str,
|
|
155
|
+
overwrite: bool = True,
|
|
156
|
+
) -> str:
|
|
157
|
+
"""Load an experiment and prepare its output before acquisition.
|
|
158
|
+
|
|
159
|
+
This separate preparation step exposes the experiment ID before the
|
|
160
|
+
acquisition starts, allowing the pixel reader to arm an ID filter
|
|
161
|
+
without missing initial frames.
|
|
162
|
+
|
|
163
|
+
Args:
|
|
164
|
+
experiment_name: Experiment setup name without ``.czexp``.
|
|
165
|
+
overwrite: Delete an existing output CZI when true.
|
|
166
|
+
|
|
167
|
+
Returns:
|
|
168
|
+
The loaded experiment ID assigned by ZEN.
|
|
169
|
+
"""
|
|
170
|
+
experiment_id = await self.load_experiment(experiment_name)
|
|
171
|
+
if overwrite:
|
|
172
|
+
await self._cleanup_existing_experiment(experiment_name)
|
|
173
|
+
return experiment_id
|
|
174
|
+
|
|
175
|
+
async def start_loaded_experiment(
|
|
176
|
+
self,
|
|
177
|
+
experiment_id: str,
|
|
178
|
+
output_name: str,
|
|
179
|
+
) -> None:
|
|
180
|
+
"""Start a previously loaded experiment.
|
|
181
|
+
|
|
182
|
+
Args:
|
|
183
|
+
experiment_id: ID returned by :meth:`prepare_experiment`.
|
|
184
|
+
output_name: Output CZI name used by ZEN.
|
|
185
|
+
"""
|
|
186
|
+
logger.debug("Starting experiment execution: %s", output_name)
|
|
187
|
+
await self.experiment_service.start_experiment(
|
|
188
|
+
ExperimentServiceStartExperimentRequest(
|
|
189
|
+
experiment_id=experiment_id,
|
|
190
|
+
output_name=output_name,
|
|
191
|
+
)
|
|
192
|
+
)
|
|
193
|
+
logger.debug(
|
|
194
|
+
"Experiment '%s' started successfully with ID: %s",
|
|
195
|
+
output_name,
|
|
196
|
+
experiment_id,
|
|
197
|
+
)
|
|
198
|
+
|
|
199
|
+
async def stop_experiment(self, experiment_id: str) -> None:
|
|
200
|
+
"""
|
|
201
|
+
Stop a running experiment.
|
|
202
|
+
|
|
203
|
+
Sends a stop command to ZEN Blue for the specified experiment ID.
|
|
204
|
+
|
|
205
|
+
Args:
|
|
206
|
+
experiment_id: ID of the experiment to stop
|
|
207
|
+
Raises:
|
|
208
|
+
Exception: If stopping the experiment fails
|
|
209
|
+
"""
|
|
210
|
+
logger.debug(f"Stopping experiment with ID: {experiment_id}")
|
|
211
|
+
await self.experiment_service.stop(
|
|
212
|
+
ExperimentServiceStopRequest(experiment_id=experiment_id)
|
|
213
|
+
)
|
|
214
|
+
logger.debug(
|
|
215
|
+
f"Experiment with ID: {experiment_id} stopped successfully"
|
|
216
|
+
)
|
|
217
|
+
|
|
218
|
+
async def _cleanup_existing_experiment(self, experiment_name: str) -> None:
|
|
219
|
+
"""
|
|
220
|
+
Delete existing experiment file if it exists.
|
|
221
|
+
|
|
222
|
+
Prevents accumulation of old experiment files and ensures
|
|
223
|
+
fresh start for new acquisitions.
|
|
224
|
+
|
|
225
|
+
Args:
|
|
226
|
+
experiment_name: Name of experiment (used to construct file path)
|
|
227
|
+
|
|
228
|
+
Note:
|
|
229
|
+
- Gets output path from ZEN API (user's default save location)
|
|
230
|
+
- Constructs full path: <output_path>/<experiment_name>.czi
|
|
231
|
+
- Only deletes if file exists (no error if missing)
|
|
232
|
+
"""
|
|
233
|
+
# Get ZEN's default output folder
|
|
234
|
+
request = ExperimentServiceGetImageOutputPathRequest()
|
|
235
|
+
folder_response = await self.experiment_service.get_image_output_path(
|
|
236
|
+
request
|
|
237
|
+
)
|
|
238
|
+
|
|
239
|
+
# Construct full path to experiment file
|
|
240
|
+
file_path = (
|
|
241
|
+
Path(folder_response.image_output_path) / f"{experiment_name}.czi"
|
|
242
|
+
)
|
|
243
|
+
|
|
244
|
+
# Delete if exists
|
|
245
|
+
if file_path.exists():
|
|
246
|
+
logger.warning(f"Deleting existing experiment file: {file_path}")
|
|
247
|
+
file_path.unlink()
|
|
248
|
+
else:
|
|
249
|
+
logger.debug(f"No existing experiment file found at: {file_path}")
|
|
250
|
+
|
|
251
|
+
async def get_experiments(self) -> list[str]:
|
|
252
|
+
"""
|
|
253
|
+
Retrieve a list of available experiment names from ZEN API.
|
|
254
|
+
|
|
255
|
+
Queries ZEN Blue for all available experiment setups (.czexp files)
|
|
256
|
+
that can be loaded and started.
|
|
257
|
+
|
|
258
|
+
Returns:
|
|
259
|
+
List of available experiment names (without .czexp extension)
|
|
260
|
+
|
|
261
|
+
Example:
|
|
262
|
+
>>> experiments = await connection.get_experiments()
|
|
263
|
+
>>> print(experiments)
|
|
264
|
+
['ZEN_API_overview', 'MyExperiment', 'Timelapse_Setup']
|
|
265
|
+
|
|
266
|
+
Note:
|
|
267
|
+
Used to populate the UI dropdown in napari-started mode.
|
|
268
|
+
"""
|
|
269
|
+
request = ExperimentServiceGetAvailableExperimentsRequest()
|
|
270
|
+
response = await self.experiment_service.get_available_experiments(
|
|
271
|
+
request
|
|
272
|
+
)
|
|
273
|
+
|
|
274
|
+
experiment_names = sorted(exp.name for exp in response.experiments)
|
|
275
|
+
logger.debug(f"Found {len(experiment_names)} available experiments")
|
|
276
|
+
|
|
277
|
+
return experiment_names
|
|
278
|
+
|
|
279
|
+
def close(self):
|
|
280
|
+
"""
|
|
281
|
+
Close the gRPC connection to ZEN Blue.
|
|
282
|
+
|
|
283
|
+
Performs cleanup and releases resources.
|
|
284
|
+
Should be called when application shuts down.
|
|
285
|
+
"""
|
|
286
|
+
logger.debug("Closing ZEN API connection")
|
|
287
|
+
|
|
288
|
+
# Close gRPC channel if it has a close method
|
|
289
|
+
if hasattr(self.channel, "close"):
|
|
290
|
+
self.channel.close()
|
|
291
|
+
logger.debug("gRPC channel closed")
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
class ExperimentContext:
|
|
295
|
+
"""
|
|
296
|
+
Manages experiment lifecycle - separate from connection.
|
|
297
|
+
|
|
298
|
+
This class tracks the state of a specific experiment and whether
|
|
299
|
+
it was started by the application or by the user in ZEN Blue.
|
|
300
|
+
|
|
301
|
+
Two Modes:
|
|
302
|
+
``exp_started_by_ui=True`` selects napari-started acquisition;
|
|
303
|
+
``False`` selects passive watching of experiments started in ZEN.
|
|
304
|
+
Construction never triggers acquisition. The plugin starts only after
|
|
305
|
+
the user presses Start and arms the pipeline's experiment-ID filter.
|
|
306
|
+
"""
|
|
307
|
+
|
|
308
|
+
def __init__(self, connection: ZENConnection, config: ZENConfig):
|
|
309
|
+
"""
|
|
310
|
+
Initialize experiment context.
|
|
311
|
+
|
|
312
|
+
Args:
|
|
313
|
+
connection: Active ZEN connection (already established)
|
|
314
|
+
config: ZEN configuration (determines mode)
|
|
315
|
+
"""
|
|
316
|
+
self.connection = connection
|
|
317
|
+
self.config = config
|
|
318
|
+
self.experiment_id: str | None = (
|
|
319
|
+
None # Set when experiment is started/loaded
|
|
320
|
+
)
|
|
321
|
+
self._is_started = False # True if this context started the experiment
|
|
322
|
+
|
|
323
|
+
async def initialize(self) -> str | None:
|
|
324
|
+
"""Explicitly start a selected experiment, or remain in watch mode.
|
|
325
|
+
|
|
326
|
+
This helper is for Python callers. Plugin connection setup does not
|
|
327
|
+
invoke it; plugin starts go through the filtered display pipeline.
|
|
328
|
+
"""
|
|
329
|
+
if self.is_monitoring_mode:
|
|
330
|
+
logger.debug("Waiting for user to start experiment in ZEN Blue")
|
|
331
|
+
self.experiment_id = None
|
|
332
|
+
|
|
333
|
+
else:
|
|
334
|
+
logger.debug(
|
|
335
|
+
f"Starting experiment via API: {self.config.exp_name}"
|
|
336
|
+
)
|
|
337
|
+
self.experiment_id = await self.connection.start_experiment(
|
|
338
|
+
self.config.exp_name, overwrite=True
|
|
339
|
+
)
|
|
340
|
+
self._is_started = True
|
|
341
|
+
logger.debug(f"Experiment started with ID: {self.experiment_id}")
|
|
342
|
+
|
|
343
|
+
return self.experiment_id
|
|
344
|
+
|
|
345
|
+
@property
|
|
346
|
+
def is_monitoring_mode(self) -> bool:
|
|
347
|
+
"""Return whether the initial mode watches acquisitions started in ZEN."""
|
|
348
|
+
return not self.config.exp_started_by_ui
|
|
349
|
+
|
|
350
|
+
@property
|
|
351
|
+
def is_started(self) -> bool:
|
|
352
|
+
"""
|
|
353
|
+
Check if experiment was started by this context.
|
|
354
|
+
|
|
355
|
+
Returns:
|
|
356
|
+
True if this context started the experiment via API
|
|
357
|
+
False if experiment was started by user in ZEN Blue
|
|
358
|
+
"""
|
|
359
|
+
return self._is_started
|