From 7955e37870c2ccc3b318c26eaf4c52e37799ed79 Mon Sep 17 00:00:00 2001 From: Tristan Simas Date: Mon, 21 Sep 2026 23:31:21 -0400 Subject: [PATCH 01/15] Update ObjectState for schema-evolution replay --- external/ObjectState | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/external/ObjectState b/external/ObjectState index ba1cd5df11..2af690df64 160000 --- a/external/ObjectState +++ b/external/ObjectState @@ -1 +1 @@ -Subproject commit ba1cd5df11c544f8bc288325ec262f4ddfae0a20 +Subproject commit 2af690df64aad48b881847888ce4497516c0b47a From 9c5c5b71a49b4ff30ae81d0d8647d98370c15eec Mon Sep 17 00:00:00 2001 From: Tristan Simas Date: Mon, 21 Sep 2026 23:32:33 -0400 Subject: [PATCH 02/15] Preserve exact source projections across viewer routes --- openhcs/agent/capabilities.py | 4 +- openhcs/agent/dto/execution.py | 6 +- openhcs/agent/dto/viewer.py | 1 + .../services/plate_inspection_service.py | 1 + .../agent/services/plate_streaming_service.py | 37 +- .../agent/services/viewer_window_service.py | 33 +- openhcs/core/artifacts.py | 34 + openhcs/core/config.py | 19 +- openhcs/core/invocation_artifacts.py | 7 +- .../orchestrator/compiled_plate_execution.py | 16 +- openhcs/core/plate_image_inventory.py | 91 +- openhcs/core/source_projection.py | 159 ++- .../core/steps/function_output_identity.py | 3 + openhcs/core/steps/function_outputs.py | 209 ++-- .../core/steps/stream_component_semantics.py | 34 +- openhcs/core/streaming_config_factory.py | 51 +- openhcs/core/viewer_streaming_service.py | 96 +- openhcs/core/virtual_workspace_metadata.py | 95 +- openhcs/mcp/dev_client_commanding.py | 32 +- openhcs/mcp/dev_client_commands/viewer.py | 6 +- openhcs/mcp/server.py | 22 +- openhcs/processing/materialization/core.py | 17 +- openhcs/pyqt_gui/services/ui_bridge_server.py | 74 +- openhcs/runtime/napari_stream_visualizer.py | 36 +- openhcs/runtime/napari_streaming_handlers.py | 129 ++- openhcs/runtime/napari_viewer_server.py | 313 ++++-- openhcs/runtime/viewer_component_system.py | 355 ++++--- openhcs/runtime/viewer_controls.py | 14 +- openhcs/runtime/viewer_protocol.py | 50 +- tests/unit/agent/test_agent_services.py | 23 + tests/unit/agent/test_mcp_server.py | 100 +- .../agent/test_plate_inspection_service.py | 44 + .../agent/test_plate_streaming_service.py | 47 +- tests/unit/pyqt_gui/test_ui_agent_bridge.py | 65 +- .../test_ui_bridge_lifecycle_config.py | 119 ++- tests/unit/test_artifact_spec_collection.py | 18 + tests/unit/test_function_outputs.py | 287 ++++- ...test_function_runtime_source_projection.py | 14 +- tests/unit/test_napari_streaming_handlers.py | 978 ++++++++++++++++-- tests/unit/test_orchestrator_lane_planning.py | 2 +- .../unit/test_persisted_semantic_metadata.py | 47 + tests/unit/test_plate_image_inventory.py | 43 + tests/unit/test_stream_component_semantics.py | 25 + tests/unit/test_streaming_service.py | 307 +++++- tests/unit/test_viewer_protocol.py | 47 +- .../test_viewer_result_element_selection.py | 38 + 46 files changed, 3650 insertions(+), 498 deletions(-) diff --git a/openhcs/agent/capabilities.py b/openhcs/agent/capabilities.py index 6c80b2fb29..b012e52c70 100644 --- a/openhcs/agent/capabilities.py +++ b/openhcs/agent/capabilities.py @@ -187,6 +187,7 @@ ViewerWindowViewportResult, ) from openhcs.serialization.json import to_jsonable +from openhcs.runtime.viewer_controls import ViewerNavigationControlOptions class CapabilityKind(Enum): @@ -3014,7 +3015,8 @@ class NavigateViewerWindowCapability(ViewerWindowCliConnectionCapability): "axis indices, and can select one zero-based data_index on a native " "feature-bearing result layer. The result reports feature_row_count and " "selected_data_indices so agents can verify the visible overlay and " - "Napari feature-table selection are linked." + "Napari feature-table selection are linked. " + f"{ViewerNavigationControlOptions.DATA_INDEX_SEMANTICS}." ) service = "viewer_window" mutating = True diff --git a/openhcs/agent/dto/execution.py b/openhcs/agent/dto/execution.py index 5cb6666631..a0389570d7 100644 --- a/openhcs/agent/dto/execution.py +++ b/openhcs/agent/dto/execution.py @@ -706,7 +706,7 @@ class RuntimeServerExecutionStatusRequest( """Request bounded execution status from a runtime server.""" execution_id: str | None = None - timeout_ms: int = OPENHCS_ZMQ_CONFIG.server_info_timeout_ms + timeout_ms: int = OPENHCS_ZMQ_CONFIG.control_timeout_ms @classmethod def from_fields( @@ -717,7 +717,7 @@ def from_fields( port: int | None = None, transport_mode: TransportMode | None = None, persistent: bool = True, - timeout_ms: int | None = OPENHCS_ZMQ_CONFIG.server_info_timeout_ms, + timeout_ms: int | None = OPENHCS_ZMQ_CONFIG.control_timeout_ms, ) -> "RuntimeServerExecutionStatusRequest": return cls( connection=ExecutionConnectionSpec( @@ -728,7 +728,7 @@ def from_fields( ), execution_id=execution_id, timeout_ms=( - OPENHCS_ZMQ_CONFIG.server_info_timeout_ms + OPENHCS_ZMQ_CONFIG.control_timeout_ms if timeout_ms is None else timeout_ms ), diff --git a/openhcs/agent/dto/viewer.py b/openhcs/agent/dto/viewer.py index 27df95cfb8..b60024ae63 100644 --- a/openhcs/agent/dto/viewer.py +++ b/openhcs/agent/dto/viewer.py @@ -776,6 +776,7 @@ class ViewerWindowLayerState(ViewerWindowLayerDescriptor): labels: JsonObject = field(default_factory=dict) axis_component_values: JsonObject = field(default_factory=dict) routed_component_values: JsonObject = field(default_factory=dict) + routed_component_coordinates: tuple[tuple[JsonValue, ...], ...] = () data_shape: tuple[int, ...] = () native_transform: ViewerNativeLayerTransform = field( default_factory=ViewerNativeLayerTransform diff --git a/openhcs/agent/services/plate_inspection_service.py b/openhcs/agent/services/plate_inspection_service.py index 8fa1a17930..6779c449b6 100644 --- a/openhcs/agent/services/plate_inspection_service.py +++ b/openhcs/agent/services/plate_inspection_service.py @@ -1991,6 +1991,7 @@ def _image_inventory( parser=parser, filemanager=filemanager, backend=handler.get_primary_backend(plate_path, filemanager), + source_projection=source_projection, all_subdirs=True, ) except Exception as exc: diff --git a/openhcs/agent/services/plate_streaming_service.py b/openhcs/agent/services/plate_streaming_service.py index 494ff1f00a..1e9580e8c9 100644 --- a/openhcs/agent/services/plate_streaming_service.py +++ b/openhcs/agent/services/plate_streaming_service.py @@ -6,6 +6,11 @@ from dataclasses import replace from pathlib import Path +from polystore.streaming.identity import ( + FixedStreamProducerIdentityKind, + StreamProducerIdentity, +) +from polystore.streaming.viewer_transport import ViewerStreamProducer from zmqruntime.viewer_protocol import ViewerSourceSpatialDomainPayload from openhcs.agent.dto.common import ( @@ -22,16 +27,20 @@ from openhcs.agent.dto.ui_bridge import UiBridgeConnectionSpec from openhcs.agent.dto.viewer import ViewerWindowStateResult from openhcs.agent.services.plate_inspection_service import ( - PlateInspectionFileQueryProjection, PlateInspectionContext, + PlateInspectionFileQueryProjection, PlateInspectionService, ) from openhcs.agent.services.ui_bridge_service import ( DEFAULT_UI_BRIDGE_CONNECTION_SPEC, UiBridgeService, ) +from openhcs.constants import AllComponents, Backend from openhcs.core.config import StreamingConfig -from openhcs.constants import Backend, AllComponents +from openhcs.core.plate_image_inventory import ( + PlateFileInventoryQuery, + PlateFileRecord, +) from openhcs.core.runtime_image_values import ImagePayloadMetadata from openhcs.core.runtime_plane_projection import RuntimePlaneAxis from openhcs.core.source_image_provenance import ( @@ -44,25 +53,20 @@ VirtualWorkspaceSourceProjection, VirtualWorkspaceSourceProjectionBuilder, ) -from openhcs.core.virtual_workspace_metadata import ( - VirtualWorkspaceSourceProjectionEntries, -) -from openhcs.core.plate_image_inventory import ( - PlateFileInventoryQuery, - PlateFileRecord, -) from openhcs.core.viewer_streaming_service import ( ImageStreamingRequest, RoiStreamingRequest, StreamingService, StreamingViewerLifecycle, ) -from polystore.streaming.viewer_transport import ViewerStreamProducer +from openhcs.core.virtual_workspace_metadata import ( + VirtualWorkspaceSourceProjectionEntries, +) +from openhcs.runtime.viewer_component_system import ViewerComponentValueDomainPayload from openhcs.runtime.viewer_protocol import ( DetachedViewerLaunchFailure, ViewerGraphicalSessionUnavailableError, ) -from openhcs.runtime.viewer_component_system import ViewerComponentValueDomainPayload class PlateStreamingService: @@ -228,6 +232,14 @@ def stream_files( ) ) if roi_paths: + roi_producer = ViewerStreamProducer.from_identities( + StreamProducerIdentity.fixed_output( + FixedStreamProducerIdentityKind.MANUAL, + record.key, + ) + for record in resolved_records + if record.streamable_roi_path is not None + ) streaming_service.stream_rois( RoiStreamingRequest( viewer=viewer, @@ -236,6 +248,7 @@ def stream_files( error_callback=status_messages.append, roi_filenames=roi_paths, component_metadata_by_path=roi_component_metadata_by_path, + producer=roi_producer, ) ) except Exception as exc: @@ -415,7 +428,7 @@ def _resolve_records( kinds = PlateFileInventoryQuery.kinds_for(request.kind) if request.file_paths: return tuple( - inventory.require_file_record(file_path, kinds=kinds) + inventory.require_stream_record(file_path, kinds=kinds) for file_path in request.file_paths ) requested_limit = max(0, int(request.limit)) diff --git a/openhcs/agent/services/viewer_window_service.py b/openhcs/agent/services/viewer_window_service.py index a36986b050..08c98d8c55 100644 --- a/openhcs/agent/services/viewer_window_service.py +++ b/openhcs/agent/services/viewer_window_service.py @@ -285,14 +285,6 @@ def from_layer( cls, layer: ViewerWindowLayerState, ) -> "ViewerLayerValidationProjection": - routed_component_coordinates = tuple( - coordinate - for payload_summary in layer.payload_summaries - for coordinate in ViewerLayerPayloadCoordinateSet._payload_coordinates( - layer.stack_axes, - ViewerPayloadComponentProjection.from_summary(payload_summary), - ) - ) return cls( projection=ViewerLayerAxisProjection( projected_axis_components=layer.stack_axes, @@ -306,9 +298,7 @@ def from_layer( layer.stack_axes, context="viewer layer routed domains", ), - routed_component_coordinates=tuple( - dict.fromkeys(routed_component_coordinates) - ), + routed_component_coordinates=layer.routed_component_coordinates, axis_offsets=layer.axis_offsets, ) ) @@ -2556,6 +2546,12 @@ def _layer_state_from_payload( payload, ViewerLayerField.ROUTED_COMPONENT_VALUES, ), + routed_component_coordinates=tuple( + self._required_sequence_tuple( + payload, + ViewerLayerField.ROUTED_COMPONENT_COORDINATES, + ) + ), data_shape=self._required_typed_tuple( payload, ViewerLayerField.DATA_SHAPE, @@ -2646,6 +2642,21 @@ def _required_sequence( raise TypeError(f"Viewer response field {field_name!r} must be a sequence.") return tuple(value) + @staticmethod + def _required_sequence_tuple( + payload: Mapping[str, JsonValue], + field_name: str, + ) -> tuple[tuple[JsonValue, ...], ...]: + values = ViewerWindowService._required_sequence(payload, field_name) + coordinates: list[tuple[JsonValue, ...]] = [] + for value in values: + if not isinstance(value, (list, tuple)): + raise TypeError( + f"Viewer response field {field_name!r} values must be sequences." + ) + coordinates.append(tuple(value)) + return tuple(coordinates) + @staticmethod def _sequence_length( payload: Mapping[str, JsonValue], diff --git a/openhcs/core/artifacts.py b/openhcs/core/artifacts.py index 6dd6f49473..81c419e4d7 100644 --- a/openhcs/core/artifacts.py +++ b/openhcs/core/artifacts.py @@ -924,6 +924,7 @@ class ArtifactSidecarRole(str, Enum): CROP_MASK = "crop_mask" MATERIALIZED_IMAGE_COPY = "materialized_image_copy" + QA_CHECKPOINT = "qa_checkpoint" def name_for( self, @@ -1312,6 +1313,22 @@ def stack_broadcast_source(self) -> ArtifactSpecRef: return self.source +class AssembledStackGroupLineageSourceRelation(ArtifactSpecRelation): + """Declare one contributor to an assembled stack output's group scope. + + The runtime projected-image payload owns exact source-plane context. This + relation therefore carries grouping only; it does not manufacture a single + source-context owner for an output assembled from multiple image inputs. + """ + + relation_key: ClassVar[str] = "assembled_stack_group_lineage_source" + + def group_scope_source(self) -> ArtifactSpecRef: + """Return one compiled main-flow contributor to the output group.""" + + return self.source + + class MaterializationSourceIdentityRelation(ArtifactSpecRelation): """Materialized output filenames inherit one declared source identity.""" @@ -1823,6 +1840,23 @@ def bind_main_flow_source(self, sources: "ArtifactSpecCollection") -> ArtifactSp ) +class MainFlowPlaneProjectionOutputSpec(ArtifactSpec): + """An explicit plane projection from the invocation's assembled image stack.""" + + def bind_main_flow_source(self, sources: "ArtifactSpecCollection") -> ArtifactSpec: + if not sources: + return self + declared_sources = frozenset(self.group_scope_sources()) + new_relations = tuple( + AssembledStackGroupLineageSourceRelation(source=source.ref()) + for source in sources + if source.ref() not in declared_sources + ) + if not new_relations: + return self + return replace(self, relations=(*self.relations, *new_relations)) + + @dataclass(frozen=True, slots=True) class ArtifactSpecAccumulator: """Ordered artifact-spec merge authority for one producer/consumer role.""" diff --git a/openhcs/core/config.py b/openhcs/core/config.py index 077a3efd04..8aec5091bc 100644 --- a/openhcs/core/config.py +++ b/openhcs/core/config.py @@ -1124,7 +1124,10 @@ def display_name_for_config_key(cls, config_key: str) -> str: return cls.config_type_for_key(config_key)().display_name -from openhcs.core.streaming_config_factory import StreamingConfigBehaviorMixin +from openhcs.core.streaming_config_factory import ( + StreamingConfigBehaviorMixin, + ViewerProcessLaunchConfig, +) @abbreviation("nap") @@ -1141,6 +1144,20 @@ class NapariStreamingConfig( port: TcpPort = 5555 """Napari viewer transport port; choose a free local port when streaming is enabled.""" + font_dpi: Optional[PositiveInteger] = None + """Font DPI for the detached Napari interface. + + ``None`` preserves the graphical session's declared DPI. Set an explicit + value when the X11 logical DPI does not match the desired Napari interface + scale. The value is applied before Qt constructs the viewer and therefore + requires the managed viewer process to restart. + """ + + def viewer_process_launch_config(self) -> ViewerProcessLaunchConfig: + """Project Napari's process-global Qt setting onto viewer launch.""" + + return ViewerProcessLaunchConfig(qt_font_dpi=self.font_dpi) + @abbreviation("fiji") @global_pipeline_config(preview_label="FIJI") diff --git a/openhcs/core/invocation_artifacts.py b/openhcs/core/invocation_artifacts.py index f5090639f2..158fed1e68 100644 --- a/openhcs/core/invocation_artifacts.py +++ b/openhcs/core/invocation_artifacts.py @@ -381,7 +381,12 @@ def __call__( ): return None source_refs = frozenset( - ref for output in outputs for ref in output.source_stack_scope_sources() + ref + for output in outputs + for ref in ( + *output.source_stack_scope_sources(), + *output.group_scope_sources(), + ) ) inputs = ArtifactSpecCollection( ( diff --git a/openhcs/core/orchestrator/compiled_plate_execution.py b/openhcs/core/orchestrator/compiled_plate_execution.py index 62868c784b..f2e49a305c 100644 --- a/openhcs/core/orchestrator/compiled_plate_execution.py +++ b/openhcs/core/orchestrator/compiled_plate_execution.py @@ -527,6 +527,10 @@ def execute_plate_scoped_steps( owner_context, owner_plan.require_function_execution_ready(), ) + OpenHCSMetadataWriter.write( + owner_context, + owner_plan.require_function_execution_ready(), + ) _emit_execution_progress( progress_queue=progress_queue, progress_context=progress_context, @@ -1088,15 +1092,20 @@ def settle_viewer_state( progress_queue: ProgressQueue | None = None, progress_context: ProgressExecutionContext | None = None, ) -> Mapping[int, "ViewerControlResponse"]: - """Drain queued updates and capture state before transient viewer shutdown.""" + """Drain every viewer and capture state before transient viewer shutdown. + + Persistence determines process ownership, not whether accepted stream work is + part of execution completion. A persistent viewer must therefore settle its + queued display updates even though its process remains open and its state is + not captured for shutdown evidence. + """ if (progress_queue is None) is not (progress_context is None): raise ValueError( "Viewer settlement progress requires both queue and execution context." ) - owned_visualizers = execution_owned_visualizers(visualizers) - for vis in owned_visualizers: + for vis in visualizers: observer = ( None if progress_queue is None or progress_context is None @@ -1116,6 +1125,7 @@ def settle_viewer_state( f"Failed to settle streamed updates for viewer on port {vis.port}." ) + owned_visualizers = execution_owned_visualizers(visualizers) viewer_states: dict[int, ViewerControlResponse] = {} for vis in owned_visualizers: if vis.port in viewer_states: diff --git a/openhcs/core/plate_image_inventory.py b/openhcs/core/plate_image_inventory.py index 23f07f6d0a..edc810e965 100644 --- a/openhcs/core/plate_image_inventory.py +++ b/openhcs/core/plate_image_inventory.py @@ -102,8 +102,14 @@ def from_orchestrator( handler = orchestrator.microscope_handler if handler is None: return cls(plate_path=Path(orchestrator.plate_path), records=()) + plate_path = Path(orchestrator.plate_path) + source_projection = cls._projection( + plate_path, + handler.metadata_handler, + orchestrator.filemanager, + ) return cls.from_handler( - plate_path=Path(orchestrator.plate_path), + plate_path=plate_path, metadata_handler=handler.metadata_handler, parser=handler.parser, filemanager=orchestrator.filemanager, @@ -111,6 +117,7 @@ def from_orchestrator( orchestrator.plate_path, orchestrator.filemanager, ), + source_projection=source_projection, all_subdirs=all_subdirs, ) @@ -123,15 +130,11 @@ def from_handler( parser: "FilenameParser | None", filemanager: "FileManager", backend: str, + source_projection: VirtualWorkspaceSourceProjection | None, all_subdirs: bool = True, ) -> "PlateImageInventory": - projection = cls._projection( - plate_path, - metadata_handler, - filemanager, - ) source_dataset = metadata_handler.source_dataset(plate_path) - if projection is None and source_dataset is not None: + if source_projection is None and source_dataset is not None: if parser is None: raise ValueError( "Exact source datasets require a filename parser for inventory " @@ -150,8 +153,8 @@ def from_handler( ), ) image_files = ( - tuple(sorted(projection.relative_virtual_paths())) - if projection is not None + tuple(sorted(source_projection.relative_virtual_paths())) + if source_projection is not None else tuple( str(image_file) for image_file in sorted( @@ -167,7 +170,7 @@ def from_handler( plate_path=plate_path, image_file=image_file, parser=parser, - projection=projection, + projection=source_projection, filemanager=filemanager, backend=backend, ) @@ -360,6 +363,11 @@ def streamable_roi_path(self) -> str | None: return self.full_path or self.key return None + @property + def streamable_path(self) -> str | None: + """Return the exact address this record declares for viewer streaming.""" + return self.streamable_image_path or self.streamable_roi_path + @classmethod def from_image(cls, record: PlateImageRecord) -> "PlateFileRecord": return cls( @@ -935,12 +943,18 @@ def from_handler( all_subdirs: bool = True, ) -> "PlateFileInventory": """Build the same file inventory shape when only a handler is available.""" + source_projection = PlateImageInventory._projection( + plate_path, + metadata_handler, + filemanager, + ) image_inventory = PlateImageInventory.from_handler( plate_path=plate_path, metadata_handler=metadata_handler, parser=parser, filemanager=filemanager, backend=backend, + source_projection=source_projection, all_subdirs=all_subdirs, ) if path_config is None: @@ -1053,6 +1067,31 @@ def require_file_record( f"requested kind filter ({requested})." ) from exc + def require_stream_record( + self, + file_path: str, + *, + kinds: tuple[PlateFileKind, ...] = (), + ) -> PlateFileRecord: + """Resolve one viewer-stream record by its declared streaming address. + + A physical image may be projected both as a metadata-bearing image and + as a result artifact. Those semantic records remain visible to general + inventory queries, while an explicit streaming address selects the one + that declares that exact address for streaming. + """ + try: + return self.require_file_record(file_path, kinds=kinds) + except PlateFileRecordAmbiguityError as exc: + direct_stream_matches = tuple( + record + for record in exc.records + if record.streamable_path == file_path + ) + if len(direct_stream_matches) == 1: + return direct_stream_matches[0] + raise + @staticmethod def _require_file_record_from( file_path: str, @@ -1079,7 +1118,11 @@ def _require_file_record_from( if len(exact_matches) == 1: return exact_matches[0] if len(exact_matches) > 1: - raise ValueError(f"File path {file_path!r} matched multiple records.") + raise PlateFileRecordAmbiguityError( + file_path, + exact_matches, + matched_basename=False, + ) basename_matches = tuple( record @@ -1100,7 +1143,11 @@ def _require_file_record_from( if len(basename_matches) == 1: return basename_matches[0] if len(basename_matches) > 1: - raise ValueError(f"File basename {file_path!r} is ambiguous.") + raise PlateFileRecordAmbiguityError( + file_path, + basename_matches, + matched_basename=True, + ) raise PlateFileRecordNotFoundError( f"File path {file_path!r} was not found in the plate." ) @@ -1110,6 +1157,26 @@ class PlateFileRecordNotFoundError(ValueError): """Raised when no unified plate inventory record matches an explicit path.""" +class PlateFileRecordAmbiguityError(ValueError): + """Raised with the typed records behind an ambiguous file address.""" + + def __init__( + self, + file_path: str, + records: tuple[PlateFileRecord, ...], + *, + matched_basename: bool, + ) -> None: + self.file_path = file_path + self.records = records + self.matched_basename = matched_basename + if matched_basename: + message = f"File basename {file_path!r} is ambiguous." + else: + message = f"File path {file_path!r} matched multiple records." + super().__init__(message) + + @dataclass(frozen=True, slots=True) class PlateImageSample: """Bounded pixel sample and summary statistics for one plate image.""" diff --git a/openhcs/core/source_projection.py b/openhcs/core/source_projection.py index 36d405fae6..dd05b6a4b7 100644 --- a/openhcs/core/source_projection.py +++ b/openhcs/core/source_projection.py @@ -5,7 +5,7 @@ import re from abc import ABC, abstractmethod from collections.abc import Iterable -from dataclasses import dataclass, field, replace, fields +from dataclasses import dataclass, field, fields, replace from pathlib import Path, PurePosixPath from types import MappingProxyType from functools import lru_cache @@ -13,18 +13,19 @@ from urllib.parse import quote from polystore.virtual_workspace import SourcePixelRef -from openhcs.core.runtime_image_values import ImagePayloadMetadata -from openhcs.serialization.json import to_jsonable from openhcs.constants.constants import AllComponents -from openhcs.core.components.component_values import OpenHCSComponentValues from openhcs.core.artifacts import ArtifactType, ImageArtifactType +from openhcs.core.component_group_scope import RuntimeExecutionAxisScope +from openhcs.core.components.component_values import OpenHCSComponentValues +from openhcs.core.runtime_image_values import ImagePayloadMetadata from openhcs.core.source_bindings import ( SOURCE_BINDING_ALIAS_METADATA_FIELD, NamedSourceBinding, SourceProjectionRole, ) from openhcs.core.source_matching import ( + source_component_metadata_raw_value, source_component_metadata_values, source_metadata_component, source_metadata_values_equal, @@ -40,6 +41,7 @@ source_metadata_dict, source_metadata_scalar, ) +from openhcs.serialization.json import to_jsonable class SourceDatasetConflictError(ValueError): @@ -174,6 +176,26 @@ def from_component_values( return cls(component_values) + @classmethod + def from_complete_source_metadata( + cls, + metadata: SourceMetadataMapping | None, + ) -> "OpenHCSPlaneAddress | None": + """Return one address only when every declared component is scalar.""" + + if metadata is None: + return None + component_values = tuple( + ( + component, + source_component_metadata_raw_value(metadata, component), + ) + for component in AllComponents + ) + if any(value is None for _component, value in component_values): + return None + return cls(component_values) + _filename_pattern: ClassVar[re.Pattern[str]] = re.compile( r"^(?P[^_]+)_s(?P[^_]+)_w(?P[^_]+)" r"_z(?P[^_]+)_t(?P[^_.]+)" @@ -600,13 +622,14 @@ class SourceProjection: """Nominal root for typed source projections.""" projection_role: ClassVar[SourceProjectionRole] - address: OpenHCSPlaneAddress + address: OpenHCSPlaneAddress | None ref: SourcePixelRef source_alias: str | None artifact_kind: type[ArtifactType] source_metadata: SourceMetadataMapping component_labels: Mapping[str, str | None] image_metadata: ClassVar[ImagePayloadMetadata | None] = None + execution_scope: ClassVar[RuntimeExecutionAxisScope | None] = None @property def identity_key(self) -> tuple[object, ...]: @@ -614,6 +637,40 @@ def identity_key(self) -> tuple[object, ...]: return (self.projection_role, self.address) + def component_value(self, component: AllComponents) -> str | None: + """Return one scalar projection coordinate when the projection has one.""" + + if self.address is None: + return None + return self.address.value_for(component) + + def source_component_values( + self, + ) -> tuple[tuple[AllComponents, str], ...]: + """Return scalar coordinates represented by this projection.""" + + if self.address is None: + return () + return self.address.component_values().declared_values() + + def serialized_address(self) -> dict[str, str] | None: + """Project the optional scalar address to the metadata boundary.""" + + if self.address is None: + return None + return self.address.as_component_metadata() + + def serialized_execution_scope(self) -> Mapping[str, Any] | None: + """Return runtime scope metadata when the nominal leaf owns one.""" + + return None + + @property + def requires_explicit_persisted_path(self) -> bool: + """Return whether a canonical filename cannot represent this projection.""" + + return False + @property def payload_composition_alias(self) -> str | None: """Return the alias that contributes a source-binding payload axis.""" @@ -726,7 +783,7 @@ class SourceArtifactProjection(SourceProjection): SourceProjectionRole.SOURCE_ARTIFACT ) - address: OpenHCSPlaneAddress + address: OpenHCSPlaneAddress | None ref: SourcePixelRef source_alias: str artifact_kind: type[ArtifactType] @@ -736,6 +793,8 @@ class SourceArtifactProjection(SourceProjection): component_labels: Mapping[str, str | None] = field( default_factory=lambda: MappingProxyType({}) ) + image_metadata: ImagePayloadMetadata | None = None + execution_scope: RuntimeExecutionAxisScope | None = None def __post_init__(self) -> None: normalized_alias = str(self.source_alias).strip() @@ -749,11 +808,59 @@ def __post_init__(self) -> None: ) _normalize_projection(self) + @classmethod + def scalar_address_for_image_metadata( + cls, + metadata: ImagePayloadMetadata, + ) -> OpenHCSPlaneAddress | None: + """Return a plane address only when the whole artifact is scalar.""" + + return OpenHCSPlaneAddress.from_complete_source_metadata( + metadata.source_component_metadata + ) + @property def identity_key(self) -> tuple[object, ...]: """Distinguish colocated source artifacts by their declared alias.""" - return (*super(SourceArtifactProjection, self).identity_key, self.source_alias) + identity = (*super(SourceArtifactProjection, self).identity_key, self.source_alias) + if self.address is not None: + return identity + return (*identity, self.execution_scope, self.ref) + + def component_value(self, component: AllComponents) -> str | None: + """Return scalar address or runtime-scope identity for one component.""" + + value = SourceProjection.component_value(self, component) + if value is not None or self.execution_scope is None: + return value + return self.execution_scope.value_text_for_component(component) + + def source_component_values( + self, + ) -> tuple[tuple[AllComponents, str], ...]: + """Return scalar address or runtime execution-scope coordinates.""" + + values = SourceProjection.source_component_values(self) + if values or self.execution_scope is None: + return values + return self.execution_scope.source_component_values + + def serialized_execution_scope(self) -> Mapping[str, Any] | None: + """Project the exact runtime scope for aggregate persisted artifacts.""" + + if self.execution_scope is None: + return None + payload = to_jsonable(self.execution_scope) + if not isinstance(payload, Mapping): + raise TypeError("Source artifact execution scope must serialize as a mapping.") + return payload + + @property + def requires_explicit_persisted_path(self) -> bool: + """Aggregate artifacts cannot synthesize a scalar plane filename.""" + + return self.address is None def virtual_workspace_path( self, @@ -780,6 +887,15 @@ def extend_serialized_payload(self, payload: dict[str, Any]) -> None: """Declare this source artifact's nominal kind in its wire payload.""" payload["artifact_kind"] = self.artifact_kind.require_value() + if self.image_metadata is not None: + payload[SourcePlaneProjection.image_metadata_wire_field()] = to_jsonable( + self.image_metadata + ) + + def persisted_image_metadata(self) -> ImagePayloadMetadata | None: + """Return pixel metadata when this artifact is independently loadable.""" + + return self.image_metadata @dataclass(frozen=True, slots=True) @@ -1014,6 +1130,12 @@ def virtual_path( """Render and validate one canonical typed source virtual path.""" address = projection.address + if projection.requires_explicit_persisted_path: + raise ValueError( + "Aggregate source artifacts require an explicit persisted path." + ) + if address is None: # pragma: no cover - nominal contract above + raise RuntimeError("Scalar projection has no address.") path = self.parser.construct_filename( self.parser.bind_declared_values( ( @@ -1051,7 +1173,9 @@ def _component_values( ) -> dict[str, str | None]: values: dict[str, str | None] = {} for projection in projection_set.projections: - key = projection.address.component_values()[component] + key = projection.component_value(component) + if key is None: + continue label = projection.component_labels.get(component.value) previous = values.get(key) if previous is not None and label is not None and previous != label: @@ -1090,7 +1214,7 @@ def _source_metadata( path=projection.ref.backend_address, ) original_metadata = dict(SourceMetadataRoleView(metadata).original_items()) - for component, value in projection.address.component_values().items(): + for component, value in projection.source_component_values(): canonical_value = metadata.get(component.value) conflicts_with_address = ( canonical_value is not None @@ -1128,7 +1252,7 @@ def _source_projection_payload( ) -> dict[str, Any]: payload: dict[str, Any] = { "virtual_path": path, - "address": projection.address.as_component_metadata(), + "address": projection.serialized_address(), "ref": projection.ref.to_workspace_mapping(), "projection_role": projection.projection_role.value, } @@ -1140,6 +1264,9 @@ def _source_projection_payload( ) if projection.component_labels: payload["component_labels"] = dict(projection.component_labels) + execution_scope = projection.serialized_execution_scope() + if execution_scope is not None: + payload["execution_scope"] = execution_scope projection.extend_serialized_payload(payload) return payload @@ -1176,8 +1303,18 @@ def _normalized_source_metadata_value( def _normalize_projection(projection: SourceProjection) -> None: """Normalize fields shared by every nominal source projection.""" - if not isinstance(projection.address, OpenHCSPlaneAddress): + if projection.address is not None and not isinstance( + projection.address, OpenHCSPlaneAddress + ): raise TypeError("Source projection address must be OpenHCSPlaneAddress.") + if projection.address is None and ( + projection.projection_role is not SourceProjectionRole.SOURCE_ARTIFACT + or projection.execution_scope is None + ): + raise TypeError( + "Only a source artifact with an execution scope may omit its scalar " + "plane address." + ) if not isinstance(projection.ref, SourcePixelRef): raise TypeError("Source projection ref must be SourcePixelRef.") object.__setattr__( diff --git a/openhcs/core/steps/function_output_identity.py b/openhcs/core/steps/function_output_identity.py index 300bde7ac2..0ececb0d74 100644 --- a/openhcs/core/steps/function_output_identity.py +++ b/openhcs/core/steps/function_output_identity.py @@ -1056,6 +1056,9 @@ def _input_aligned_payload_identity( ): continue filename_component_values[component_name] = component_value + # Positional alignment fills unresolved storage coordinates; it + # cannot rename a component already identified by the payload. + filename_component_values.update(component_values) return replace( identity, component_values=component_values, diff --git a/openhcs/core/steps/function_outputs.py b/openhcs/core/steps/function_outputs.py index c39346acbd..c42d16c242 100644 --- a/openhcs/core/steps/function_outputs.py +++ b/openhcs/core/steps/function_outputs.py @@ -14,34 +14,23 @@ from polystore.virtual_workspace import SourcePixelRef from openhcs.constants.constants import Backend +from openhcs.core.artifacts import ImageArtifactType from openhcs.core.axis_filter import step_axis_allows_config from openhcs.core.compiled_step_plan import ( CompiledStepPlan, RuntimeArtifactMaterializationPlan, ) from openhcs.core.context.processing_context import ProcessingContext +from openhcs.core.image_file_serialization import ( + ImageFileFormat, + ImageFileSourceMetadata, +) from openhcs.core.runtime_array_values import RuntimeArrayData from openhcs.core.runtime_image_values import ( ImagePayloadMetadata, + image_intensity_scale_for_dtype, image_payload_data, image_payload_metadata, - image_intensity_scale_for_dtype, -) -from openhcs.core.image_file_serialization import ( - ImageFileFormat, - ImageFileSourceMetadata, -) -from openhcs.core.artifacts import ImageArtifactType -from openhcs.core.source_projection import ( - OpenHCSPlaneAddress, - SourceArtifactProjection, - SourcePlaneProjection, - SourceProjectionSet, - SourceProjectionMetadataSerializer, -) -from openhcs.core.virtual_workspace_metadata import ( - AtomicMetadataWriter, - METADATA_CONFIG, ) from openhcs.core.runtime_profile import RuntimeProfileLogger from openhcs.core.runtime_slice_projection import ( @@ -52,10 +41,18 @@ from openhcs.core.source_image_provenance import ( SourceComponentMetadata, ) +from openhcs.core.source_projection import ( + OpenHCSPlaneAddress, + SourceArtifactProjection, + SourcePlaneProjection, + SourceProjectionMetadataSerializer, + SourceProjectionSet, +) from openhcs.core.steps.function_artifact_materialization import ( PersistentArtifactMaterializationTargetPlan, StreamingOnlyArtifactMaterializationTargetPlan, materialize_artifact_outputs, + runtime_artifact_materializations, ) from openhcs.core.steps.function_io import ( prepare_storage_image_payloads, @@ -76,6 +73,10 @@ StreamImagePayloadMetadataProjector, StreamSourceComponentMetadataItems, ) +from openhcs.core.virtual_workspace_metadata import ( + METADATA_CONFIG, + AtomicMetadataWriter, +) from openhcs.microscopes.microscope_interfaces import FilenameParser logger = logging.getLogger(__name__) @@ -133,8 +134,8 @@ def finalize_function_step_outputs( MemoryOutputWriter.write_if_needed(context, plan) MaterializedImageOutputWriter.write_if_needed(context, plan) StreamOutputsAuthority.stream_outputs(context, plan) - OpenHCSMetadataWriter.write(context, plan) RuntimeArtifactMaterializationAuthority.materialize(context, plan) + OpenHCSMetadataWriter.write(context, plan) return _profile_finalization_phase( @@ -153,13 +154,13 @@ def finalize_function_step_outputs( plan, ) _profile_finalization_phase( - "finalize_openhcs_metadata", - lambda: OpenHCSMetadataWriter.write(context, plan), + "finalize_runtime_artifacts", + lambda: RuntimeArtifactMaterializationAuthority.materialize(context, plan), plan, ) _profile_finalization_phase( - "finalize_runtime_artifacts", - lambda: RuntimeArtifactMaterializationAuthority.materialize(context, plan), + "finalize_openhcs_metadata", + lambda: OpenHCSMetadataWriter.write(context, plan), plan, ) @@ -792,14 +793,16 @@ def produced_projection_metadata( for record in step_output_manifest(context).produced_records_for(plan) if record.is_image_payload ) - if not records: - return None - payloads = context.filemanager.load_batch( - [ - ProducedMemoryPathsAuthority.memory_path(record, plan) - for record in records - ], - Backend.MEMORY.value, + payloads = ( + context.filemanager.load_batch( + [ + ProducedMemoryPathsAuthority.memory_path(record, plan) + for record in records + ], + Backend.MEMORY.value, + ) + if records + else () ) projection_paths = [] declared_addresses: set[OpenHCSPlaneAddress] = set() @@ -814,32 +817,11 @@ def produced_projection_metadata( raise ValueError( f"Produced image has no declared filename address: {destination}." ) - physical_path = context.filemanager.physical_source_path( - destination, - self.backend, - base_path=self.output_dir, + metadata = self.persisted_image_metadata( + context, + destination=destination, + payload=payload, ) - if physical_path is None: - native_dtype = context.filemanager.source_image_dtype( - destination, - self.backend, - base_path=self.output_dir, - ) - metadata = ImageFileSourceMetadata( - source_dtype=native_dtype, - intensity_scale=image_intensity_scale_for_dtype(native_dtype), - ).project_image_metadata( - image_payload_metadata(payload), - values_preserved=context.filemanager.image_serialization_preserves_values( - self.backend, - image_payload_data(payload).dtype, - native_dtype, - ), - ) - else: - metadata = ImageFileFormat.require_path( - physical_path - ).persisted_metadata(Path(physical_path), payload) source_metadata = dict( record.component_metadata(metadata.source_component_metadata) ) @@ -869,10 +851,16 @@ def produced_projection_metadata( source_alias=record.producer_identity.output_key, artifact_kind=ImageArtifactType, source_metadata=source_metadata, + image_metadata=metadata, ), virtual_path, ) ) + projection_paths.extend( + self.runtime_artifact_projection_paths(context, plan) + ) + if not projection_paths: + return None projection_set = SourceProjectionSet( tuple(projection for projection, _path in projection_paths) ) @@ -887,6 +875,111 @@ def produced_projection_metadata( projection_paths=tuple(projection_paths), ) + def runtime_artifact_projection_paths( + self, + context: ProcessingContext, + plan: CompiledStepPlan, + ) -> tuple[tuple[SourceArtifactProjection, str], ...]: + """Project persisted image artifacts into the target source authority.""" + + if not plan.runtime_artifact_materialization.has_persistent_target: + return () + artifact_target = self.materialized(plan) or self.primary(plan) + if artifact_target != self: + return () + if ( + plan.runtime_artifact_materialization.require_persistent_backend() + != self.backend + ): + raise ValueError( + "Runtime artifact backend does not match its materialized " + "metadata target." + ) + projection_paths = [] + for materialization in runtime_artifact_materializations(plan, context): + if not materialization.spec.participates_in_persistent_materialization(): + continue + for output in materialization.outputs( + plan, + context, + output_path_filter=ImageFileFormat.is_image_path, + ): + if not ImageFileFormat.is_image_path(output.path): + continue + if output.metadata is None: + raise ValueError( + f"Image artifact {output.path!r} has no typed image " + "metadata." + ) + destination = output.path + virtual_path = str(Path(destination).relative_to(self.plate_root)) + payload = output.metadata.attach_to(output.content) + metadata = self.persisted_image_metadata( + context, + destination=destination, + payload=payload, + ) + address = SourceArtifactProjection.scalar_address_for_image_metadata( + metadata + ) + source_metadata = metadata.source_component_metadata or {} + persisted_source_metadata = dict(source_metadata) + metadata.source_voxel_spacing.merge_into( + persisted_source_metadata, path=destination + ) + projection_paths.append( + ( + SourceArtifactProjection( + address=address, + ref=SourcePixelRef(self.backend, virtual_path), + source_alias=materialization.output_plan.name, + artifact_kind=materialization.output_plan.artifact_type, + source_metadata=persisted_source_metadata, + image_metadata=metadata, + execution_scope=materialization.record.key.scope, + ), + virtual_path, + ) + ) + return tuple(projection_paths) + + def persisted_image_metadata( + self, + context: ProcessingContext, + *, + destination: str, + payload, + ) -> ImagePayloadMetadata: + """Describe one saved image through its backend or physical format.""" + + if context.filemanager is None: + raise ValueError("OpenHCS metadata requires a file manager.") + physical_path = context.filemanager.physical_source_path( + destination, + self.backend, + base_path=self.output_dir, + ) + if physical_path is not None: + return ImageFileFormat.require_path(physical_path).persisted_metadata( + Path(physical_path), payload + ) + native_dtype = context.filemanager.source_image_dtype( + destination, + self.backend, + base_path=self.output_dir, + ) + return ImageFileSourceMetadata( + source_dtype=native_dtype, + intensity_scale=image_intensity_scale_for_dtype(native_dtype), + ).project_image_metadata( + image_payload_metadata(payload), + values_preserved=context.filemanager.image_serialization_preserves_values( + self.backend, + image_payload_data(payload).dtype, + native_dtype, + ), + ) + @classmethod def write( cls, @@ -919,9 +1012,9 @@ def finalize_completed_plate( ) -> None: """Write each populated metadata target after all axis outputs exist.""" - target_contexts: dict[OpenHCSMetadataWriter.OutputTarget, ProcessingContext] = ( - {} - ) + target_contexts: dict[ + OpenHCSMetadataWriter.OutputTarget, ProcessingContext + ] = {} for context in compiled_contexts.values(): for plan in context.step_plans.values(): if not plan.create_openhcs_metadata: diff --git a/openhcs/core/steps/stream_component_semantics.py b/openhcs/core/steps/stream_component_semantics.py index dec06cbb6e..ded3cd8c89 100644 --- a/openhcs/core/steps/stream_component_semantics.py +++ b/openhcs/core/steps/stream_component_semantics.py @@ -243,6 +243,28 @@ class StreamViewerComponentMetadataProjector: component_order: tuple[str, ...] + @classmethod + def for_item_fields( + cls, + component_order: Iterable[str], + item_fields: Mapping[str, ViewerWireValue], + ) -> "StreamViewerComponentMetadataProjector": + """Exclude components represented by a payload-local plane axis.""" + + plane_component_values = item_fields.get( + ViewerWireField.PLANE_COMPONENT_VALUES.value, + {}, + ) + if not isinstance(plane_component_values, Mapping): + raise TypeError("Viewer stream plane_component_values must be a mapping.") + return cls( + tuple( + component + for component in component_order + if component not in plane_component_values + ) + ) + def project_required( self, *, @@ -826,7 +848,15 @@ def viewer_backend_kwargs( def path_mapped_source_metadata( self, metadata_by_path: Mapping[str, StreamComponentMetadata], + *, + item_fields: Mapping[str, ViewerWireValue] | None = None, ) -> ViewerStreamSourceMetadata: - return StreamViewerComponentMetadataProjector( + projector = StreamViewerComponentMetadataProjector( self.layout.component_order - ).path_mapped_source_metadata(metadata_by_path) + ) + if item_fields is not None: + projector = StreamViewerComponentMetadataProjector.for_item_fields( + self.layout.component_order, + item_fields, + ) + return projector.path_mapped_source_metadata(metadata_by_path) diff --git a/openhcs/core/streaming_config_factory.py b/openhcs/core/streaming_config_factory.py index 4dcb0649d4..6e7325728a 100644 --- a/openhcs/core/streaming_config_factory.py +++ b/openhcs/core/streaming_config_factory.py @@ -2,7 +2,9 @@ from __future__ import annotations -from dataclasses import dataclass +from collections.abc import Mapping +from dataclasses import dataclass, field +from enum import Enum from typing import TYPE_CHECKING, ClassVar from objectstate import DataclassFieldAccess, get_base_config_type @@ -74,6 +76,44 @@ def viewer_backend_kwargs( ) +class ViewerProcessLaunchField(str, Enum): + """Wire fields projected from the viewer process-launch declaration.""" + + QT_FONT_DPI = "qt_font_dpi" + + +@dataclass(frozen=True, slots=True) +class ViewerProcessLaunchConfig: + """Process-global settings that must exist before viewer construction.""" + + qt_font_dpi: int | None = None + + def __post_init__(self) -> None: + if self.qt_font_dpi is not None and self.qt_font_dpi <= 0: + raise ValueError("Viewer Qt font DPI must be positive when provided.") + + def to_wire_mapping(self) -> dict[str, int | None]: + """Project the launch declaration onto the viewer control boundary.""" + + return { + ViewerProcessLaunchField.QT_FONT_DPI.value: self.qt_font_dpi, + } + + @classmethod + def from_wire_mapping( + cls, + payload: Mapping[str, object], + ) -> "ViewerProcessLaunchConfig": + """Rehydrate an exact launch declaration from viewer state.""" + + value = payload[ViewerProcessLaunchField.QT_FONT_DPI.value] + if value is not None and ( + not isinstance(value, int) or isinstance(value, bool) + ): + raise TypeError("Viewer Qt font DPI must be an integer or None.") + return cls(qt_font_dpi=value) + + @dataclass(frozen=True, slots=True) class StreamingViewerRuntimeConfig: """Concrete runtime objects shared by viewer lifecycle and backend dispatch.""" @@ -84,6 +124,9 @@ class StreamingViewerRuntimeConfig: transport_config: ZMQConfig = OPENHCS_ZMQ_CONFIG display_enabled: bool = True scope_accent_color: str | None = None + process_launch: ViewerProcessLaunchConfig = field( + default_factory=ViewerProcessLaunchConfig + ) class StreamingConfigBehaviorMixin: @@ -141,8 +184,14 @@ def viewer_runtime_config( display_enabled=self.enabled, viewer_type=self.viewer_type, scope_accent_color=self.scope_accent_color, + process_launch=self.viewer_process_launch_config(), ) + def viewer_process_launch_config(self) -> ViewerProcessLaunchConfig: + """Return process-launch settings owned by this viewer declaration.""" + + return ViewerProcessLaunchConfig() + def viewer_surface( self, source: ViewerStreamSourceIdentity, diff --git a/openhcs/core/viewer_streaming_service.py b/openhcs/core/viewer_streaming_service.py index 8a51b8d66a..7cf4a51838 100644 --- a/openhcs/core/viewer_streaming_service.py +++ b/openhcs/core/viewer_streaming_service.py @@ -10,10 +10,12 @@ import logging import re import time -from collections.abc import Mapping -from dataclasses import dataclass, field +from collections.abc import Callable, Mapping +from dataclasses import dataclass, field, replace +from hashlib import sha256 +from json import dumps from pathlib import Path -from typing import TYPE_CHECKING, Callable +from typing import TYPE_CHECKING, ClassVar from objectstate import spawn_thread_with_context from polystore.streaming.identity import ( @@ -29,11 +31,13 @@ from openhcs.core.runtime_image_loading import ImagePayloadSourceMetadataContext from openhcs.core.runtime_image_values import ( + ImagePayloadMetadata, image_payload_data, image_payload_mask, image_payload_metadata, ) from openhcs.core.source_image_provenance import SourceImageIdentity +from openhcs.core.source_metadata import SourceVoxelSpacing from openhcs.core.source_workspace_projection import ( VirtualWorkspacePathLookup, VirtualWorkspaceSourceProjection, @@ -86,6 +90,36 @@ class ImageStreamingRequest(ViewerStreamingContext): producer: ViewerStreamProducer | None = None +@dataclass(frozen=True, slots=True) +class ManualImageStreamProjectionIdentity: + """Exact route identity for one manually selected source-image set.""" + + plate_path: str + filenames: tuple[str, ...] + + OUTPUT_KEY: ClassVar[str] = "selected_images" + + def producer_identity(self) -> StreamProducerIdentity: + """Return the producer identity for this exact selection.""" + + canonical_selection = dumps( + { + "plate_path": self.plate_path, + "filenames": sorted(self.filenames), + }, + sort_keys=True, + separators=(",", ":"), + ) + projection_digest = sha256(canonical_selection.encode("utf-8")).hexdigest() + return replace( + StreamProducerIdentity.fixed_output( + FixedStreamProducerIdentityKind.MANUAL, + self.OUTPUT_KEY, + ), + projection_key=f"{self.OUTPUT_KEY}_{projection_digest}", + ) + + @dataclass(frozen=True, slots=True) class RoiStreamingRequest(ViewerStreamingContext): """Request to stream ROI files to one viewer.""" @@ -94,6 +128,7 @@ class RoiStreamingRequest(ViewerStreamingContext): component_metadata_by_path: Mapping[str, ViewerWireMapping] = field( default_factory=dict ) + producer: ViewerStreamProducer | None = None @dataclass(frozen=True, slots=True) @@ -287,6 +322,15 @@ def source_workspace_projection(self) -> VirtualWorkspaceSourceProjection: filemanager=self.filemanager, ).projection_or_empty() + def roi_image_metadata(self) -> ImagePayloadMetadata: + """Return plate-owned physical calibration for ROI pixel coordinates.""" + pixel_size = float( + self.microscope_handler.metadata_handler.get_pixel_size(self.plate_path) + ) + return ImagePayloadMetadata( + source_voxel_spacing=SourceVoxelSpacing((pixel_size, pixel_size)) + ) + def load_image( self, filename: str, @@ -578,10 +622,10 @@ def stream_images( source_metadata_items=source_metadata_items, ) producer = request.producer or ViewerStreamProducer.from_identity( - StreamProducerIdentity.fixed_output( - FixedStreamProducerIdentityKind.MANUAL, - "selected_images", - ) + ManualImageStreamProjectionIdentity( + plate_path=str(self.source.plate_path), + filenames=request.filenames, + ).producer_identity() ) for chunk_idx in range(num_chunks): @@ -622,6 +666,14 @@ def stream_images( component_order, ): metadata = image_payload_metadata(image_data_list[indices[0]]) + item_fields = StreamImagePayloadMetadataProjector.item_fields( + metadata, + component_order, + ) + partition_metadata_by_path = { + file_paths[index]: all_metadata_by_path[file_paths[index]] + for index in indices + } producer_subset = producer.for_indices( tuple(start_idx + index for index in indices), total_images ) @@ -632,14 +684,11 @@ def stream_images( **message_authority.viewer_backend_kwargs( producer=producer_subset, source_metadata=message_authority.path_mapped_source_metadata( - all_metadata_by_path + partition_metadata_by_path, + item_fields=item_fields, ), ) - .with_item_fields( - StreamImagePayloadMetadataProjector.item_fields( - metadata, component_order - ) - ) + .with_item_fields(item_fields) .to_kwargs(), ) logger.info( @@ -714,6 +763,7 @@ def stream_rois( data_list: list = [] paths: list[str] = [] + loaded_indices: list[int] = [] for i, filename in enumerate(request.roi_filenames, 1): file_path = Path(self.source.plate_path) / filename @@ -724,6 +774,7 @@ def stream_rois( data_list.append(rois) paths.append(filename) + loaded_indices.append(i - 1) if i % 5 == 0 or i == total: message = f"Loading ROIs: {i}/{total} file(s)..." @@ -777,16 +828,25 @@ def stream_rois( viewer_surface, source_metadata_items=source_metadata_items, ) + producer = request.producer or ViewerStreamProducer.from_identity( + StreamProducerIdentity.fixed_output( + FixedStreamProducerIdentityKind.MANUAL, + "selected_rois", + ) + ) stream_backend_kwargs = message_authority.viewer_backend_kwargs( - producer=ViewerStreamProducer.from_identity( - StreamProducerIdentity.fixed_output( - FixedStreamProducerIdentityKind.MANUAL, - "selected_rois", - ) + producer=producer.for_indices( + loaded_indices, + total, ), source_metadata=message_authority.path_mapped_source_metadata( metadata_by_path ), + ).with_item_fields( + StreamImagePayloadMetadataProjector.item_fields( + self.source.roi_image_metadata(), + message_authority.layout.component_order, + ) ) message = f"Streaming {len(paths)} ROI file(s) to {display_name}..." diff --git a/openhcs/core/virtual_workspace_metadata.py b/openhcs/core/virtual_workspace_metadata.py index 16696e71e3..248520dfc5 100644 --- a/openhcs/core/virtual_workspace_metadata.py +++ b/openhcs/core/virtual_workspace_metadata.py @@ -13,14 +13,16 @@ from polystore.atomic import LOCK_CONFIG, FileLockError, atomic_update_json from polystore.virtual_workspace import SourcePixelRef +from openhcs.constants.constants import AllComponents from openhcs.core.artifacts import ArtifactType +from openhcs.core.component_group_scope import RuntimeExecutionAxisScope from openhcs.core.runtime_image_values import ImagePayloadMetadata -from openhcs.constants.constants import AllComponents from openhcs.core.source_bindings import SourceProjectionRole from openhcs.core.source_metadata import ( SourceMetadataMapping, SourceMetadataScalar, SourceMetadataValue, + SourceVoxelSpacing, ) from openhcs.core.source_projection import ( OpenHCSPlaneAddress, @@ -31,7 +33,6 @@ SourceProjectionSet, ) from openhcs.core.source_tile_geometry import SourceTileLayout -from openhcs.core.source_metadata import SourceVoxelSpacing @dataclass(frozen=True) @@ -383,20 +384,6 @@ def _projection_record( "virtual_workspace source_projection records must be mappings." ) virtual_path = cls._required_text(record, "virtual_path") - address_value = record.get("address") - if not isinstance(address_value, Mapping): - raise RuntimeError( - "virtual_workspace source_projection address must be a mapping." - ) - address = OpenHCSPlaneAddress.from_values( - well=cls._required_text(address_value, "well"), - site=cls._required_text(address_value, "site"), - channel=cls._required_text(address_value, "channel"), - z_index=cls._required_text(address_value, "z_index"), - timepoint=cls._required_text(address_value, "timepoint"), - ) - ref_value = record.get("ref") - ref = SourcePixelRef.from_workspace_mapping(ref_value) try: projection_role = SourceProjectionRole( cls._required_text(record, "projection_role") @@ -405,6 +392,31 @@ def _projection_record( raise RuntimeError( "virtual_workspace source_projection has an unknown projection_role." ) from exc + address_value = record.get("address") + if address_value is None: + address = None + elif isinstance(address_value, Mapping): + address = OpenHCSPlaneAddress.from_values( + well=cls._required_text(address_value, "well"), + site=cls._required_text(address_value, "site"), + channel=cls._required_text(address_value, "channel"), + z_index=cls._required_text(address_value, "z_index"), + timepoint=cls._required_text(address_value, "timepoint"), + ) + else: + raise RuntimeError( + "virtual_workspace source_projection address must be a mapping or " + "null." + ) + if ( + projection_role is SourceProjectionRole.PRIMARY_PLANE + and address is None + ): + raise RuntimeError( + "Primary source projections require a complete plane address." + ) + ref_value = record.get("ref") + ref = SourcePixelRef.from_workspace_mapping(ref_value) source_metadata = cls._optional_metadata(record, "source_metadata") component_labels = cls._optional_component_labels(record) source_alias = cls._optional_text(record, "source_alias") @@ -430,6 +442,9 @@ def _projection_record( "Source-artifact projection records require source_alias." ) artifact_kind = cls._required_text(record, "artifact_kind") + image_metadata_value = record.get( + SourcePlaneProjection.image_metadata_wire_field() + ) projection = SourceArtifactProjection( address=address, ref=ref, @@ -437,9 +452,57 @@ def _projection_record( artifact_kind=ArtifactType.coerce(artifact_kind), source_metadata=source_metadata, component_labels=component_labels, + image_metadata=( + None + if image_metadata_value is None + else ImagePayloadMetadata.from_mapping(image_metadata_value) + ), + execution_scope=cls._optional_execution_scope(record), ) return virtual_path, projection + @classmethod + def _optional_execution_scope( + cls, + record: Mapping[str, JsonValue], + ) -> RuntimeExecutionAxisScope | None: + value = record.get("execution_scope") + if value is None: + return None + if not isinstance(value, Mapping): + raise RuntimeError( + "virtual_workspace source_projection execution_scope must be a " + "mapping." + ) + fixed_value = value.get("fixed_component_values", ()) + if not isinstance(fixed_value, Sequence) or isinstance( + fixed_value, (str, bytes) + ): + raise RuntimeError( + "virtual_workspace source_projection execution_scope fixed " + "components must be a sequence." + ) + fixed_components: list[tuple[str, str]] = [] + for item in fixed_value: + if ( + not isinstance(item, Sequence) + or isinstance(item, (str, bytes)) + or len(item) != 2 + ): + raise RuntimeError( + "virtual_workspace source_projection execution_scope fixed " + "components must be two-item sequences." + ) + fixed_components.append((str(item[0]), str(item[1]))) + component = value.get("component") + scope_value = value.get("value") + return RuntimeExecutionAxisScope.from_raw( + cls._required_text(value, "axis_id"), + component=None if component is None else str(component), + value=None if scope_value is None else str(scope_value), + fixed_component_values=tuple(fixed_components), + ) + @staticmethod def _required_text(record: Mapping[str, JsonValue], field: str) -> str: value = record.get(field) diff --git a/openhcs/mcp/dev_client_commanding.py b/openhcs/mcp/dev_client_commanding.py index 39041698c2..9f0a9cca9d 100644 --- a/openhcs/mcp/dev_client_commanding.py +++ b/openhcs/mcp/dev_client_commanding.py @@ -30,6 +30,7 @@ RuntimeServerConnectionToolRequest, RuntimeServerToolRequest, ) +from openhcs.mcp.control_timeout import McpUiBridgeTimeoutPolicy from openhcs.mcp.dev_client_core import ( DEFAULT_CALL_TIMEOUT_SECONDS, McpDevCliUsageError, @@ -50,6 +51,7 @@ captured_server_stderr_tail, list_mcp_session_tools, mcp_dev_command_key, + mcp_tool_timeout_seconds, ui_tool_arguments, viewer_connection_arguments, ) @@ -399,10 +401,19 @@ def calls_from_args( self, args: argparse.Namespace, ) -> tuple[McpDevToolCall, ...]: + try: + tool_arguments = self.tool_arguments(args) + except McpDevCliUsageError: + raise + except (TypeError, ValueError) as exc: + # Manual command projections construct the same declaration-owned + # request DTOs as generated commands. Preserve their validation as + # a local usage failure instead of a transport failure or traceback. + raise McpDevCliUsageError(str(exc)) from exc return ( McpDevToolCall( self.tool_name, - self.tool_arguments(args), + tool_arguments, ), ) @@ -442,6 +453,25 @@ def calls_from_args( ), ) + async def run_session( + self, + session: McpDevStdioSession, + args: argparse.Namespace, + *, + prepared_calls: tuple[McpDevToolCall, ...] | None = None, + ) -> McpDevToolBatchResponse: + """Keep the MCP deadline outside the request-owned bridge deadline.""" + + timeout_ms = McpUiBridgeTimeoutPolicy.resolve(args.timeout_ms) + return await call_mcp_session( + session, + self.calls_from_args(args) if prepared_calls is None else prepared_calls, + timeout_seconds=mcp_tool_timeout_seconds( + timeout_ms, + timeout_seconds=self.timeout_seconds(args), + ), + ) + class GeneratedCapabilityCommandBinding: """Instance binding shared by generated capability-backed CLI commands.""" diff --git a/openhcs/mcp/dev_client_commands/viewer.py b/openhcs/mcp/dev_client_commands/viewer.py index ad5c9b047c..167e8162fb 100644 --- a/openhcs/mcp/dev_client_commands/viewer.py +++ b/openhcs/mcp/dev_client_commands/viewer.py @@ -52,6 +52,7 @@ viewer_visible_route_keys_argument, ) from openhcs.mcp.dev_client_rendering import ViewerImageSampleRenderOptions +from openhcs.runtime.viewer_controls import ViewerNavigationControlOptions class ViewerPayloadsCommandSpec(CapabilityBackedCommandSpec): @@ -632,8 +633,9 @@ def configure_parser(self, parser: argparse.ArgumentParser) -> None: "--data-index", type=int, help=( - "Select one zero-based row on a native feature-bearing result " - "layer so the overlay and feature table highlight stay linked." + f"{ViewerNavigationControlOptions.DATA_INDEX_SEMANTICS} " + "so the overlay and feature table highlight stay linked. Omit " + "--data-index when hiding or deselecting a layer." ), ) visibility = parser.add_mutually_exclusive_group() diff --git a/openhcs/mcp/server.py b/openhcs/mcp/server.py index bca86c5f6a..13c64a274f 100644 --- a/openhcs/mcp/server.py +++ b/openhcs/mcp/server.py @@ -458,18 +458,16 @@ async def _await_with_declared_progress( ) task = asyncio.ensure_future(operation) while True: - try: - return await asyncio.wait_for( - asyncio.shield(task), - timeout=heartbeat_seconds, - ) - except TimeoutError: - elapsed_seconds += heartbeat_seconds - await _report_progress_if_available( - mcp_context, - elapsed_seconds, - message=f"{capability.title}: still running", - ) + completed, _ = await asyncio.wait({task}, timeout=heartbeat_seconds) + if completed: + # An operation's own TimeoutError is terminal, not a heartbeat. + return task.result() + elapsed_seconds += heartbeat_seconds + await _report_progress_if_available( + mcp_context, + elapsed_seconds, + message=f"{capability.title}: still running", + ) async def _report_progress_if_available( diff --git a/openhcs/processing/materialization/core.py b/openhcs/processing/materialization/core.py index 6e42ad091f..c8733dc8d5 100644 --- a/openhcs/processing/materialization/core.py +++ b/openhcs/processing/materialization/core.py @@ -26,7 +26,7 @@ PathMappedViewerStreamSourceMetadata, ViewerStreamBackendKwargs, ) -from zmqruntime.viewer_protocol import ViewerWireField, ViewerWireValue +from zmqruntime.viewer_protocol import ViewerWireValue from openhcs.constants.constants import AllComponents, VariableComponents from openhcs.core.artifacts import ArtifactMaterializationPayload @@ -1618,19 +1618,10 @@ def _output_fields( output.variable_components, ) ) - plane_component_values = item_fields.get( - ViewerWireField.PLANE_COMPONENT_VALUES.value, - {}, - ) - if not isinstance(plane_component_values, Mapping): - raise TypeError("Viewer stream plane_component_values must be a mapping.") display_semantics = self.values.stream_request.display_semantics - projected_metadata = StreamViewerComponentMetadataProjector( - tuple( - component - for component in display_semantics.component_order - if component not in plane_component_values - ) + projected_metadata = StreamViewerComponentMetadataProjector.for_item_fields( + display_semantics.component_order, + item_fields, ).project_required(index=0, metadata=component_metadata) return projected_metadata, item_fields diff --git a/openhcs/pyqt_gui/services/ui_bridge_server.py b/openhcs/pyqt_gui/services/ui_bridge_server.py index bd9d6f9f18..0ec4b374af 100644 --- a/openhcs/pyqt_gui/services/ui_bridge_server.py +++ b/openhcs/pyqt_gui/services/ui_bridge_server.py @@ -21,7 +21,12 @@ PongResponse, ServerRole, ) -from zmqruntime.transport import resolve_transport_mode +from zmqruntime.timeouts import OperationDeadline +from zmqruntime.transport import ( + TransportEndpoint, + endpoint_startup_lock, + resolve_transport_mode, +) from openhcs.agent.dto.common import SCHEMA_VERSION, AgentError, JsonObject from openhcs.agent.dto.execution import ExecutionConnectionSpec @@ -180,6 +185,22 @@ def __str__(self) -> str: return f"Unsupported UI bridge operation: {self.operation_name}" +@dataclass(slots=True) +class UiBridgeEndpointInUseError(RuntimeError): + """Raised before a UI bridge can replace another live endpoint pair.""" + + endpoint: TransportEndpoint + occupied_ports: frozenset[int] + + def __str__(self) -> str: + ports = ", ".join(str(port) for port in sorted(self.occupied_ports)) + return ( + f"UI bridge endpoint {self.endpoint.transport_mode.value}://" + f"{self.endpoint.host}:{self.endpoint.port} is already in use " + f"(occupied ports: {ports})." + ) + + class UiBridgeServerInProcessGateway(InProcessUiBridgeGateway): """In-process gateway with server descriptor details in status responses.""" @@ -503,6 +524,28 @@ def start( return self.binding if self._stop_event.is_set(): raise RuntimeError("A stopped UI bridge server cannot be restarted.") + deadline = OperationDeadline.after_milliseconds( + max(1, int(timeout_seconds * 1000)), + operation="UI bridge endpoint startup", + ) + endpoint = self._requested_endpoint() + if endpoint is None: + return self._start_before_deadline(deadline) + with endpoint_startup_lock( + endpoint.port, + endpoint.transport_mode, + self._transport_config, + operation_deadline=deadline, + ) as acquired: + if not acquired: + raise TimeoutError("UI bridge endpoint startup was cancelled.") + self._require_available_endpoint(endpoint) + return self._start_before_deadline(deadline) + + def _start_before_deadline( + self, + deadline: OperationDeadline, + ) -> UiBridgeServerBinding: self._ready_event.clear() self._startup_error = None self._thread = threading.Thread( @@ -511,13 +554,20 @@ def start( daemon=True, ) self._thread.start() - if not self._ready_event.wait(timeout_seconds): + if not self._ready_event.wait(deadline.remaining_seconds()): self.stop() - raise TimeoutError("Timed out waiting for UI bridge server to start.") + if self._startup_error is not None: + error = self._startup_error + raise RuntimeError( + f"Failed to start UI bridge server: {error}" + ) from error + raise deadline.timeout_error() if self._startup_error is not None: error = self._startup_error self.stop() - raise RuntimeError("Failed to start UI bridge server.") from error + raise RuntimeError( + f"Failed to start UI bridge server: {error}" + ) from error return self.binding def stop(self) -> None: @@ -605,6 +655,22 @@ def _serve(self) -> None: if connection is not None: connection.transport_endpoint().cleanup(self._transport_config) + def _requested_endpoint(self) -> TransportEndpoint | None: + requested_connection = self._config + if requested_connection.port is None: + return None + return TransportEndpoint( + host=requested_connection.host, + port=requested_connection.port, + transport_mode=resolve_transport_mode(requested_connection.transport_mode), + ) + + def _require_available_endpoint(self, endpoint: TransportEndpoint) -> None: + endpoint.cleanup_stale_addresses(self._transport_config) + occupied_ports = endpoint.occupied_ports(self._transport_config) + if occupied_ports: + raise UiBridgeEndpointInUseError(endpoint, occupied_ports) + def _write_descriptor_file(self, descriptor: UiBridgeDescriptorFile) -> Path: path = AgentRuntimePlatformAuthority.resolved_path( descriptor.descriptor_file_path diff --git a/openhcs/runtime/napari_stream_visualizer.py b/openhcs/runtime/napari_stream_visualizer.py index 1f646f474b..8fb25ef146 100644 --- a/openhcs/runtime/napari_stream_visualizer.py +++ b/openhcs/runtime/napari_stream_visualizer.py @@ -15,6 +15,7 @@ import logging import threading +from collections.abc import Mapping from pathlib import Path from typing import Optional @@ -22,12 +23,18 @@ from polystore.filemanager import FileManager from openhcs.core.streaming_config_declarations import ViewerType -from openhcs.core.streaming_config_factory import StreamingViewerRuntimeConfig +from openhcs.core.streaming_config_factory import ( + StreamingViewerRuntimeConfig, + ViewerProcessLaunchConfig, +) from openhcs.runtime.viewer_protocol import ( DetachedViewerPythonArguments, DetachedViewerPythonExpression, DetachedViewerServerEntrypointSpec, ManagedViewerLifecycleMixin, + OpenHCSViewerControlMessageType, + ViewerControlField, + ViewerControlMessageRequest, ) from openhcs.utils.import_utils import optional_import_or_none @@ -86,8 +93,35 @@ def detached_server_arguments( ).append( DetachedViewerPythonExpression.symbol("transport_mode"), DetachedViewerPythonExpression.literal(self.scope_accent_color), + DetachedViewerPythonExpression.literal(self.process_launch.qt_font_dpi), ) + def existing_viewer_matches_process_launch(self) -> bool: + """Require exact process-global settings before reusing a viewer.""" + + try: + response = ViewerControlMessageRequest( + endpoint=self.runtime_endpoint, + message_type=( + OpenHCSViewerControlMessageType.PROCESS_LAUNCH.value + ), + ).send() + if not response.succeeded(): + return False + wire_config = response.payload[ViewerControlField.PROCESS_LAUNCH.value] + if not isinstance(wire_config, Mapping): + raise TypeError( + "Napari process-launch response must contain a mapping." + ) + active_config = ViewerProcessLaunchConfig.from_wire_mapping(wire_config) + except Exception as error: + logger.warning( + "Napari viewer process-launch compatibility check failed: %s", + error, + ) + return False + return active_config == self.process_launch + def start_viewer(self, async_mode: bool = True): """ Starts the Napari viewer in a separate process. diff --git a/openhcs/runtime/napari_streaming_handlers.py b/openhcs/runtime/napari_streaming_handlers.py index 069b3910e7..f9ad766b54 100644 --- a/openhcs/runtime/napari_streaming_handlers.py +++ b/openhcs/runtime/napari_streaming_handlers.py @@ -28,6 +28,7 @@ ComponentValue, ComponentValues, ViewerComponentAxisSemantics, + ViewerComponentLayout, ViewerComponentValueDomainPayload, ViewerLayerAxisProjection, ) @@ -1107,13 +1108,32 @@ def __post_init__(self) -> None: f"order; got route {self.projection.projected_axis_components!r} " f"within {self.display_axis_components!r}." ) - @property def display_axis_components(self) -> tuple[str, ...]: """Return the declaration-owned shared stack slots for this presentation.""" return self.layout.components_for_mode(ViewerComponentMode.STACK) + def axis_projection_semantics(self) -> ViewerComponentAxisSemantics: + """Derive the route-addressable axes from its declared value domain.""" + + declared_components = self.component_values() + component_order = tuple( + component + for component in self.layout.component_order + if component in declared_components + ) + return ViewerComponentAxisSemantics( + entries=self.entries, + layout=ViewerComponentLayout.from_parts( + component_modes={ + component: self.layout.component_modes[component] + for component in component_order + }, + component_order=component_order, + ), + ) + @property def projected_display_axis_indices(self) -> tuple[int, ...]: """Return the display slot owned by each route-local projected axis.""" @@ -1133,6 +1153,91 @@ def projected_display_axis_indices(self) -> tuple[int, ...]: for component in self.projection.projected_axis_components ) + @property + def route_local_component_axes(self) -> tuple[str, ...]: + """Return component axes addressable in this route's local domain. + + Multi-valued components remain projected axes. Components collapsed out + of the native payload shape still own one real route-local coordinate at + index zero; they are not display padding and remain valid selectors. + """ + + available = { + *self.projection.projected_axis_components, + *self.projection.scalar_component_values, + } + return tuple( + component + for component in self.display_axis_components + if component in available + ) + + def route_local_component_indices( + self, + projected_indices: Sequence[int], + *, + context: str, + ) -> dict[str, int]: + """Derive every component index from one projected payload coordinate.""" + + projected = tuple(projected_indices) + projected_axes = self.projection.projected_axis_components + if len(projected) != len(projected_axes): + raise ValueError( + f"{context} projected coordinate rank {len(projected)} does not " + f"match route axes {projected_axes!r}." + ) + indices = dict(zip(projected_axes, projected, strict=True)) + indices.update( + { + component: 0 + for component in self.projection.scalar_component_values + } + ) + return { + component: indices[component] + for component in self.route_local_component_axes + } + + def route_local_component_indices_match( + self, + projected_indices: Sequence[int], + requested_indices: Mapping[str, int], + *, + context: str, + ) -> bool: + """Match projected and collapsed coordinates through one route authority.""" + + available_axes = self.route_local_component_axes + unknown_axes = tuple( + axis_name + for axis_name in requested_indices + if axis_name not in available_axes + ) + if unknown_axes: + raise ValueError( + f"{context} contains unknown component axes {unknown_axes!r}; " + f"available route-local component axes are {available_axes!r}." + ) + + local_indices = self.route_local_component_indices( + projected_indices, + context=context, + ) + for axis_name, requested_index in requested_indices.items(): + if axis_name in self.projection.component_values: + extent = len(self.projection.component_values[axis_name]) + else: + extent = len(self.projection.scalar_component_values[axis_name]) + if requested_index >= extent: + raise ValueError( + f"{context} index {requested_index} for axis {axis_name!r} is " + f"outside the route-local extent {extent}." + ) + if local_indices[axis_name] != requested_index: + return False + return True + @property def axis_labels(self) -> tuple[str, ...]: return tuple( @@ -1183,6 +1288,17 @@ def align_array(self, data: np.ndarray) -> np.ndarray: aligned_stack_shape[display_index] = data.shape[projected_index] return data.reshape((*aligned_stack_shape, *data.shape[projected_rank:])) + def aligned_component_shape(self) -> tuple[int, ...]: + """Return the native layer extents owned by semantic display axes.""" + + shape = [1] * len(self.display_axis_components) + for projected_index, display_index in enumerate( + self.projected_display_axis_indices + ): + component = self.projection.projected_axis_components[projected_index] + shape[display_index] = len(self.projection.component_values[component]) + return tuple(shape) + def align_coordinates(self, coordinates: np.ndarray) -> np.ndarray: """Insert zero-valued columns for absent semantic display axes.""" @@ -1337,6 +1453,17 @@ def set_dimension_state( ) -> None: self.layer_dimension_states[layer_key] = state + def mounted_dimension_states( + self, + ) -> tuple[tuple[str, NapariDimensionLayerState], ...]: + """Return mounted route presentations in receiver insertion order.""" + + return tuple( + (layer_key, state) + for layer_key, state in self.layer_dimension_states.items() + if layer_key in self.layers + ) + def axis_origins_for(self, axis_labels: tuple[str, ...]) -> tuple[int, ...]: """Return normalized-viewer origins derived from mounted route offsets.""" compatible_states = tuple( diff --git a/openhcs/runtime/napari_viewer_server.py b/openhcs/runtime/napari_viewer_server.py index b250b152c2..d8c9062e8f 100644 --- a/openhcs/runtime/napari_viewer_server.py +++ b/openhcs/runtime/napari_viewer_server.py @@ -74,6 +74,7 @@ ) from openhcs.core.source_spatial_domain import SourceSpatialDomain from openhcs.core.streaming_config_declarations import ViewerType +from openhcs.core.streaming_config_factory import ViewerProcessLaunchConfig from openhcs.runtime.napari_streaming_handlers import ( DimensionLabelMap, LayerData, @@ -113,10 +114,9 @@ ViewerComponentMetadataPayload, ViewerComponentNameMetadata, ViewerComponentValueDomainPayload, - ViewerDisplayAxisDomain, ViewerDisplayBatchContext, ViewerLayerAxisProjection, - ViewerLayerAxisProjectionRequest, + ViewerLayerAxisProjectionRequestAuthority, ViewerLayerAxisProjector, ViewerMappingDisplayConfigInput, ViewerObjectDisplayConfigInput, @@ -124,10 +124,15 @@ ViewerStreamingDataTypeHandler, ViewerStreamingDataTypeHandlerMeta, ) -from openhcs.runtime.viewer_controls import ViewerResultElementCoordinateAuthority +from openhcs.runtime.viewer_controls import ( + ViewerIntensityWindowControlOptions, + ViewerResultElementCoordinateAuthority, +) from openhcs.runtime.viewer_protocol import ( NapariLayerKind, NapariViewerServerRequest, + OpenHCSViewerServerABC, + OpenHCSViewerControlMessageType, ViewerBatchMessageType, ViewerBatchWireField, ViewerComponentValueOrdering, @@ -141,10 +146,9 @@ ViewerLayerField, ViewerLayerIsolationControlOptions, ViewerLayerIsolationField, - ViewerLayerField, ViewerNavigationControlOptions, - ViewerPayloadProjectionOptions, ViewerPayloadField, + ViewerPayloadProjectionOptions, ViewerPayloadSummaryField, ViewerProtocolStatus, ViewerQtEnvironmentPolicy, @@ -917,13 +921,13 @@ def display( server: "NapariViewerServer", ) -> None: routed_data = data + self._reconcile_deleted_layers(server) route = self._route( data=routed_data, stream_layer_context=stream_layer_context, server=server, ) self._log_route(route) - self._reconcile_deleted_layer(server, route.route_key) group = self._group_for(server, route.route_key) self._clear_group_for_replace(server, route.route_key, group) self._upsert_item( @@ -978,6 +982,18 @@ def _log_route( route.component_info, ) + @staticmethod + def _reconcile_deleted_layers( + server: "NapariViewerServer", + ) -> None: + """Purge every route whose native layer was removed from the viewer.""" + + for layer_key in tuple(server.layer_route_state.layers): + NapariComponentAwareDisplayCoordinator._reconcile_deleted_layer( + server, + layer_key, + ) + @staticmethod def _reconcile_deleted_layer( server: "NapariViewerServer", @@ -990,6 +1006,7 @@ def _reconcile_deleted_layer( num_items = server.component_groups.item_count(layer_key) server.layer_route_state.purge_route(layer_key) server.component_groups.purge(layer_key) + server.component_values.purge(layer_key) logger.info( "🔬 NAPARI PROCESS: Reconciling state — '%s' was deleted from viewer; " "purged stale caches (had %d items in component_groups)", @@ -1018,6 +1035,7 @@ def _clear_group_for_replace( layer_key, ) group.clear() + server.component_values.purge(layer_key) def _upsert_item( self, @@ -2002,45 +2020,66 @@ def display_axis_projection( if aggregate_axis_bindings is None: aggregate_axis_bindings = NapariAggregateAxisBindingSet() - axis_components = component_axis_semantics.layout.components_for_mode( - ViewerComponentMode.STACK - ) - self.server.component_values.update( - layer_key, - axis_components, - layer_items, - ) - self.server.display_axis_domain.record_display_axis_values( - axis_components, - layer_items, + projection_request = ( + ViewerLayerAxisProjectionRequestAuthority.from_component_axis_semantics( + route_key=layer_key, + component_axis_semantics=component_axis_semantics, + layer_items=layer_items, + route_value_tracker=self.server.component_values, + aggregate_component_values=aggregate_axis_bindings.component_values, + ) ) + return self.axis_projector.project(projection_request) - aggregate_component_values = aggregate_axis_bindings.component_values - if aggregate_component_values: - self.server.component_values.update_component_values( - layer_key, - axis_components, - aggregate_component_values, + def reconcile_mounted_axis_projections( + self, + *, + updated_route_key: str, + ) -> None: + """Align mounted routes with the viewer-wide semantic coordinate domain. + + Independently streamed routes can declare different subsets of the same + component axis. A newly observed value may therefore change the shared + coordinate assigned to an already mounted singleton route. Shape-neutral + changes are applied directly to that route's native transform and semantic + presentation. A change that would alter stored array extents fails during + dispatch instead of leaving silently misaligned layers. + """ + + for ( + route_key, + state, + ) in self.server.layer_route_state.mounted_dimension_states(): + if route_key == updated_route_key or state.presentation is None: + continue + items = self.server.component_groups.existing_items_for(route_key) + if not items: + continue + axis_projection_semantics = state.presentation.axis_projection_semantics() + aggregate_axis_bindings = NapariAggregateAxisBindingAuthority.bindings( + items, + axis_projection_semantics, ) - self.server.display_axis_domain.record_display_component_values( - axis_components, - aggregate_component_values, + projection = self.display_axis_projection( + route_key, + axis_projection_semantics, + items, + aggregate_axis_bindings, ) - - projection_request = ViewerLayerAxisProjectionRequest.from_component_values( - projected_axis_components=axis_components, - route_component_values=self.server.component_values.values_for( - self.server.component_values.domain_key(layer_key, axis_components), - axis_components, - ), - viewer_component_values=self.server.display_axis_domain.display_axis_values_for( - axis_components - ), - declared_component_values=component_axis_semantics.required_component_values( - axis_components - ), - ) - return self.axis_projector.project(projection_request) + presentation = replace(state.presentation, projection=projection) + if ( + presentation.aligned_component_shape() + != state.presentation.aligned_component_shape() + ): + raise ValueError( + "Napari shared semantic axis expansion requires route " + f"{route_key!r} to be rematerialized; old component shape=" + f"{state.presentation.aligned_component_shape()!r}, new=" + f"{presentation.aligned_component_shape()!r}." + ) + layer = self.server.layer_route_state.layer(route_key) + layer.translate = presentation.translate(presentation.payload_axis_labels) + self.dimension_label_store.apply(presentation) def schedule_layer_update( self, @@ -2301,6 +2340,9 @@ def display_layer_batch( items, aggregate_axis_bindings, ) + self.reconcile_mounted_axis_projections( + updated_route_key=layer_key, + ) work = NapariLayerDisplayHandler.for_data_type(data_type).display_work( NapariLayerDisplayRequest( pipeline=self, @@ -2441,6 +2483,36 @@ def handle( ).to_wire_mapping() +class NapariProcessLaunchControlMessageAction(NapariControlMessageAction): + """Report immutable process-global settings without entering the Qt thread.""" + + message_type = OpenHCSViewerControlMessageType.PROCESS_LAUNCH.value + + def handle( + self, + server: "NapariViewerServer", + message: Mapping[str, object], + ) -> dict[str, object]: + del message + response = ViewerControlReplyPayload( + ViewerControlReplyHeader( + ViewerProtocolStatus.SUCCESS, + response_type="process_launch_ack", + ) + ).to_wire_mapping() + response[ViewerControlField.PROCESS_LAUNCH.value] = ( + server.process_launch.to_wire_mapping() + ) + return response + + def transport_thread_response( + self, + server: "NapariViewerServer", + message: Mapping[str, object], + ) -> dict[str, object]: + return self.handle(server, message) + + class NapariSettleControlMessageAction(NapariControlMessageAction): """Registered action that drains queued debounced layer updates.""" @@ -2850,11 +2922,27 @@ def select( layer: NapariLayerHandle, data_index: int, ) -> NapariResultElementSelectionState: - cls.require_data_index(layer, data_index) + return cls.select_indices(layer, (data_index,)) + + @classmethod + def select_indices( + cls, + layer: NapariLayerHandle, + data_indices: Iterable[int], + ) -> NapariResultElementSelectionState: + """Select one exact, validated set of native feature rows.""" + + indices = tuple(sorted(set(data_indices))) + if not indices: + raise ValueError("Napari result selection must contain at least one row.") + for data_index in indices: + if isinstance(data_index, bool) or not isinstance(data_index, Integral): + raise TypeError("Napari result selection indices must be integers.") + cls.require_data_index(layer, int(data_index)) selectable_layer = cast(NapariShapesLayerHandle, layer) - selectable_layer.selected_data = {data_index} + selectable_layer.selected_data = set(indices) observed = cls.state(layer) - if observed.selected_data_indices != (data_index,): + if observed.selected_data_indices != indices: raise RuntimeError( "Napari did not retain the requested native data selection." ) @@ -3188,6 +3276,16 @@ def _synchronize_linked_group( self._notify_selection_observers() return linked + def select_result_element( + self, + layer: NapariLayerHandle, + data_index: int, + ) -> tuple[tuple[NapariLayerHandle, tuple[int, ...]], ...]: + """Select the complete declared result subject containing one row.""" + + NapariResultElementSelectionAuthority.require_data_index(layer, data_index) + return self._synchronize_linked_group(layer, data_index) + def _apply_selection( self, layer_reference: weakref.ReferenceType[object], @@ -3440,6 +3538,9 @@ def choose_group_color() -> None: class NapariViewerProjectionABC(ABC, Generic[NapariViewerProjectionRequestT]): """Shared projection of live Napari route and component stores.""" + MAX_NONZERO_COORDINATE_PROJECTION_COUNT: ClassVar[int] = 65_536 + MAX_NONZERO_EXAMPLE_COORDINATE_COUNT: ClassVar[int] = 16 + server: "NapariViewerServer" viewer: NapariViewerLayerCreator request: NapariViewerProjectionRequestT @@ -3542,6 +3643,9 @@ def layer_state_for(self, route_key: str) -> dict[str, NapariWireValue]: ViewerLayerField.ROUTED_COMPONENT_VALUES.value: ( self.routed_component_values(dimension_state) ), + ViewerLayerField.ROUTED_COMPONENT_COORDINATES.value: ( + self.routed_component_coordinates(dimension_state) + ), ViewerLayerField.DATA_SHAPE.value: self.layer_data_shape(layer), ViewerLayerField.NATIVE_TRANSFORM.value: native_transform.to_wire_mapping(), ViewerLayerField.NATIVE_INTENSITY.value: ( @@ -3690,6 +3794,14 @@ def routed_component_values( ) } + @staticmethod + def routed_component_coordinates( + dimension_state: NapariDimensionLayerState, + ) -> tuple[tuple[ComponentValue, ...], ...]: + if dimension_state.presentation is None: + return () + return dimension_state.presentation.projection.routed_component_coordinates + @classmethod def payload_summary( cls, @@ -3770,21 +3882,74 @@ def shape_source_spatial_shape( value_name="Napari shape payload", ).source_shape_yx - @staticmethod - def array_summary(array: np.ndarray) -> dict[str, NapariWireValue]: + @classmethod + def array_summary(cls, array: np.ndarray) -> dict[str, NapariWireValue]: + nonzero_count = int(np.count_nonzero(array)) summary: dict[str, NapariWireValue] = { ViewerPayloadSummaryField.SHAPE.value: tuple( int(axis) for axis in array.shape ), "dtype": str(array.dtype), "size": int(array.size), - ViewerPayloadSummaryField.NONZERO_COUNT.value: int(np.count_nonzero(array)), + ViewerPayloadSummaryField.NONZERO_COUNT.value: nonzero_count, } + summary.update( + cls.nonzero_coordinate_summary( + array, + nonzero_count=nonzero_count, + ) + ) if array.size: - summary["min"] = NapariViewerStateProjection.json_scalar(array.min()) - summary["max"] = NapariViewerStateProjection.json_scalar(array.max()) + summary["min"] = cls.json_scalar(array.min()) + summary["max"] = cls.json_scalar(array.max()) return summary + @classmethod + def nonzero_coordinate_summary( + cls, + array: np.ndarray, + *, + nonzero_count: int, + ) -> dict[str, NapariWireValue]: + """Project exact bounds and bounded examples for sparse array payloads.""" + + if nonzero_count > cls.MAX_NONZERO_COORDINATE_PROJECTION_COUNT: + return { + ViewerPayloadSummaryField.NONZERO_COORDINATE_OMISSION_REASON.value: ( + "nonzero count exceeds bounded coordinate projection limit " + f"{cls.MAX_NONZERO_COORDINATE_PROJECTION_COUNT}" + ) + } + + coordinates = np.argwhere(array != 0) + if nonzero_count == 0: + return { + ViewerPayloadSummaryField.NONZERO_EXAMPLE_COORDINATES.value: (), + } + + example_count = min( + nonzero_count, + cls.MAX_NONZERO_EXAMPLE_COORDINATE_COUNT, + ) + example_indices = np.linspace( + 0, + nonzero_count - 1, + num=example_count, + dtype=np.int64, + ) + return { + ViewerPayloadSummaryField.NONZERO_MIN_COORDINATE.value: tuple( + int(value) for value in coordinates.min(axis=0) + ), + ViewerPayloadSummaryField.NONZERO_MAX_COORDINATE.value: tuple( + int(value) for value in coordinates.max(axis=0) + ), + ViewerPayloadSummaryField.NONZERO_EXAMPLE_COORDINATES.value: tuple( + tuple(int(value) for value in coordinates[index]) + for index in example_indices + ), + } + @staticmethod def json_scalar(value: np.generic | bool | int | float | str) -> NapariWireValue: if isinstance(value, np.generic): @@ -3984,18 +4149,17 @@ def semantic_axis_indices_match( semantic_axis_indices: Mapping[str, int], ) -> bool: if dimension_state.presentation is None: - return not semantic_axis_indices - axis_labels = dimension_state.presentation.projection.projected_axis_components - for axis_name, axis_index in semantic_axis_indices.items(): - if axis_name not in axis_labels: - return False - tuple_index = axis_labels.index(axis_name) - if ( - tuple_index >= len(axis_indices) - or axis_indices[tuple_index] != axis_index - ): - return False - return True + if semantic_axis_indices: + raise ValueError( + "Napari payload axis_indices require a route with semantic " + "axis presentation." + ) + return True + return dimension_state.presentation.route_local_component_indices_match( + axis_indices, + semantic_axis_indices, + context="Napari payload axis_indices", + ) @staticmethod def aggregate_index_tuples( @@ -4601,18 +4765,6 @@ def _matched_payload_records( for item in items ) - axis_labels = presentation.projection.projected_axis_components - unknown_axes = tuple( - axis_name - for axis_name in request.axis_indices - if axis_name not in axis_labels - ) - if unknown_axes: - raise ValueError( - f"Viewer intensity-window axis_indices contain unknown axes " - f"{unknown_axes!r}; available axes are {axis_labels!r}." - ) - aggregate_bindings = presentation.aggregate_axis_bindings records = [] for item in items: @@ -4629,10 +4781,10 @@ def _matched_payload_records( components, context="Napari intensity-window payload selection", ) - if not NapariViewerPayloadProjection.semantic_axis_indices_match( + if not presentation.route_local_component_indices_match( axis_indices, - dimension_state, request.axis_indices, + context="Viewer intensity-window axis_indices", ): continue records.append( @@ -5372,7 +5524,7 @@ def _response_payload(self, request_payload: bytes) -> bytes: ) -class NapariViewerServer(StreamingVisualizerServer): +class NapariViewerServer(OpenHCSViewerServerABC): """ ZMQ server for Napari viewer that receives images from clients. @@ -5413,9 +5565,9 @@ def __init__(self, request: NapariViewerServerRequest): # Advertise the endpoint application identity on every heartbeat so # clients can reject stale viewer endpoints before dispatch. self.application = OPENHCS_ENDPOINT_APPLICATION - self.napari_window_title = request.viewer_title self.replace_layers = request.replace_layers + self.process_launch = request.process_launch self.viewer = None self.result_selection_surface: NapariResultSelectionSurface | None = None self.result_selection_toolbar = None @@ -5424,7 +5576,6 @@ def __init__(self, request: NapariViewerServerRequest): self.component_name_metadata = ViewerComponentNameMetadata.empty() self.component_values = ViewerRouteComponentValueTracker() - self.display_axis_domain = ViewerDisplayAxisDomain() # Debouncing + locking for layer updates to prevent race conditions self.layer_update_lock = threading.Lock() # Prevent concurrent updates self.layer_batch_processor_debounce_policy = NapariLayerBatchDebouncePolicy() @@ -5566,7 +5717,6 @@ def clear_accumulated_stream_state(self) -> None: ) self.component_groups.clear() self.component_values = ViewerRouteComponentValueTracker() - self.display_axis_domain = ViewerDisplayAxisDomain() self.component_name_metadata.clear() self.layer_route_state.clear_update_errors() self.batch_processors = NapariBatchProcessorStore( @@ -5744,6 +5894,7 @@ def run_napari_viewer_process( log_file_path: str | None = None, transport_mode: TransportMode = TransportMode.IPC, scope_accent_color: str | None = None, + font_dpi: int | None = None, ) -> None: """ Napari viewer process entry point. Runs in a separate process. @@ -5756,6 +5907,7 @@ def run_napari_viewer_process( log_file_path: Path to log file (for client discovery via ping/pong) transport_mode: ZMQ transport mode (IPC or TCP) scope_accent_color: Exact UI-owned scope accent used to frame this window + font_dpi: Explicit Qt font DPI applied before viewer construction """ server: NapariViewerServer | None = None try: @@ -5765,6 +5917,7 @@ def run_napari_viewer_process( replace_layers=replace_layers, log_file_path=log_file_path, transport_mode=transport_mode, + process_launch=ViewerProcessLaunchConfig(qt_font_dpi=font_dpi), ) # Create ZMQ server instance (inherits from ZMQServer ABC) @@ -5773,7 +5926,7 @@ def run_napari_viewer_process( # OpenCV wheels can replace Qt's platform-plugin path when imported. # Reassert the active binding's authoritative path after module imports # and immediately before native Qt/Napari construction. - ViewerQtEnvironmentPolicy().apply_to(os.environ) + ViewerQtEnvironmentPolicy(font_dpi=font_dpi).apply_to(os.environ) # Create napari viewer in this process (main thread) viewer = napari.Viewer(title=viewer_title, show=True) diff --git a/openhcs/runtime/viewer_component_system.py b/openhcs/runtime/viewer_component_system.py index 7a4352ccbf..6b8509c797 100644 --- a/openhcs/runtime/viewer_component_system.py +++ b/openhcs/runtime/viewer_component_system.py @@ -34,6 +34,7 @@ ComponentWireValue: TypeAlias = ComponentValue | Sequence[ComponentValue] ComponentMap: TypeAlias = dict[str, ComponentValue] ComponentValues: TypeAlias = dict[str, list[ComponentValue]] +ComponentCoordinate: TypeAlias = tuple[ComponentValue, ...] ComponentDomainKey: TypeAlias = str | tuple[str, ...] | tuple[str, tuple[str, ...]] ComponentModeMap: TypeAlias = dict[str, str] DisplayModeValue: TypeAlias = str | Enum @@ -935,63 +936,79 @@ class ViewerDisplayBatchContext( @dataclass(slots=True) class ViewerComponentValueDomain: - """Store observed component values for keyed streaming domains.""" + """Own observed and declared values for one routed component domain.""" - domain_values: dict[ComponentDomainKey, dict[str, set[ComponentValue]]] = field( - default_factory=dict - ) + axis_components: tuple[str, ...] + observed_values: dict[str, set[ComponentValue]] + declared_values: dict[str, set[ComponentValue]] - def update( - self, - domain_key: ComponentDomainKey, + @classmethod + def for_axes( + cls, axis_components: Sequence[str], + ) -> "ViewerComponentValueDomain": + axes = tuple(axis_components) + return cls( + axis_components=axes, + observed_values={component: set() for component in axes}, + declared_values={component: set() for component in axes}, + ) + + def replace_observed( + self, layer_items: Sequence[ViewerComponentAddressedItem], ) -> None: - if domain_key not in self.domain_values: - self.domain_values[domain_key] = { - component: set() for component in axis_components - } - - observed_values = self.domain_values[domain_key] + self.observed_values = { + component: set() for component in self.axis_components + } for item in layer_items: components = item.address.components - for component in axis_components: + for component in self.axis_components: if component in components: - observed_values[component].add(components[component]) + self.observed_values[component].add(components[component]) - def update_component_values( + def observe_component_values( self, - domain_key: ComponentDomainKey, - axis_components: Sequence[str], component_values: ComponentValues, ) -> None: - if domain_key not in self.domain_values: - self.domain_values[domain_key] = { - component: set() for component in axis_components - } - - observed_values = self.domain_values[domain_key] for component, values in component_values.items(): - if component not in observed_values: + if component not in self.observed_values: raise ValueError( - f"Component value domain {domain_key!r} cannot record " - f"undeclared component {component!r}." + "Component value domain cannot observe undeclared component " + f"{component!r}; axes={self.axis_components!r}." ) - observed_values[component].update(values) + self.observed_values[component].update(values) - def values_for( + def declare( self, - domain_key: ComponentDomainKey, - axis_components: Sequence[str], - ) -> ComponentValues: - if domain_key not in self.domain_values: - return {component: [] for component in axis_components} + component_values: ComponentValues, + ) -> None: + missing = tuple( + component + for component in self.axis_components + if component not in component_values + ) + if missing: + raise ValueError( + "Declared component value domain is missing route axis component(s) " + f"{missing!r}." + ) + self.declared_values = { + component: set(component_values[component]) + for component in self.axis_components + } + def observed(self) -> ComponentValues: return { component: sorted(values, key=ViewerComponentValueOrdering.key) - for component, values in self.domain_values[domain_key].items() + for component, values in self.observed_values.items() } + def coordinate_values(self, component: str) -> set[ComponentValue]: + if component not in self.observed_values: + return set() + return self.observed_values[component] | self.declared_values[component] + @dataclass(frozen=True, slots=True) class ViewerComponentValueDomainView: @@ -1035,21 +1052,20 @@ def has_multiple_values(self, component: str) -> bool: @dataclass(slots=True) -class ViewerRouteComponentValueTracker(ViewerComponentValueDomain): +class ViewerRouteComponentValueTracker: """Track observed component values for one routed viewer layer.""" + domains: dict[tuple[str, tuple[str, ...]], ViewerComponentValueDomain] = field( + default_factory=dict + ) + def update( self, route_key: str, axis_components: Sequence[str], layer_items: Sequence[ViewerComponentAddressedItem], ) -> None: - ViewerComponentValueDomain.update( - self, - self.domain_key(route_key, axis_components), - axis_components, - layer_items, - ) + self.domain_for(route_key, axis_components).replace_observed(layer_items) def update_component_values( self, @@ -1057,88 +1073,78 @@ def update_component_values( axis_components: Sequence[str], component_values: ComponentValues, ) -> None: - ViewerComponentValueDomain.update_component_values( - self, - self.domain_key(route_key, axis_components), - axis_components, - component_values, + self.domain_for(route_key, axis_components).observe_component_values( + component_values ) - @staticmethod - def domain_key( - route_key: str, - axis_components: Sequence[str], - ) -> tuple[str, tuple[str, ...]]: - return (route_key, tuple(axis_components)) - - -class ViewerDisplayAxisDomainContract(ABC): - """Axis-domain contract observed by viewer layer projection.""" - - @abstractmethod - def record_display_axis_values( + def declare_component_values( self, + route_key: str, axis_components: Sequence[str], - layer_items: Sequence[ViewerComponentAddressedItem], + component_values: ComponentValues, ) -> None: - """Record observed values for the shared viewer axis domain.""" + """Record the exact declared axis domain for one route generation.""" - @abstractmethod - def record_display_component_values( + self.domain_for(route_key, axis_components).declare(component_values) + + def domain_for( self, + route_key: str, axis_components: Sequence[str], - component_values: ComponentValues, - ) -> None: - """Record declared values represented by aggregate payload axes.""" + ) -> ViewerComponentValueDomain: + domain_key = self.domain_key(route_key, axis_components) + if domain_key not in self.domains: + self.domains[domain_key] = ViewerComponentValueDomain.for_axes( + axis_components + ) + return self.domains[domain_key] - @abstractmethod - def display_axis_values_for( + def values_for( self, + domain_key: tuple[str, tuple[str, ...]], axis_components: Sequence[str], ) -> ComponentValues: - """Return observed values for the shared viewer axis domain.""" + if domain_key not in self.domains: + return {component: [] for component in axis_components} + return self.domains[domain_key].observed() + def purge(self, route_key: str) -> None: + """Remove every component domain owned by one retired route.""" -@dataclass(slots=True) -class ViewerDisplayAxisDomain( - ViewerComponentValueDomain, - ViewerDisplayAxisDomainContract, -): - """Track shared viewer axis values for one stack-component layout.""" + for domain_key in tuple(self.domains): + if domain_key[0] == route_key: + self.domains.pop(domain_key) - def record_display_axis_values( - self, - axis_components: Sequence[str], - layer_items: Sequence[ViewerComponentAddressedItem], - ) -> None: - ViewerComponentValueDomain.update( - self, - tuple(axis_components), - axis_components, - layer_items, - ) - - def record_display_component_values( - self, + @staticmethod + def domain_key( + route_key: str, axis_components: Sequence[str], - component_values: ComponentValues, - ) -> None: - ViewerComponentValueDomain.update_component_values( - self, - tuple(axis_components), - axis_components, - component_values, - ) + ) -> tuple[str, tuple[str, ...]]: + return (route_key, tuple(axis_components)) - def display_axis_values_for( + def shared_values_for( self, axis_components: Sequence[str], ) -> ComponentValues: - return ViewerComponentValueDomain.values_for( - self, - tuple(axis_components), - axis_components, - ) + """Derive the viewer-wide coordinate domain from routed domains. + + Route domains remain independently owned so route-local selection keeps + its exact indices. The shared domain is only a derived coordinate view: + equal semantic values must occupy equal viewer coordinates even when the + values arrived through different stream requests. + """ + + return { + component: sorted( + { + value + for domain in self.domains.values() + for value in domain.coordinate_values(component) + }, + key=ViewerComponentValueOrdering.key, + ) + for component in axis_components + } @dataclass(frozen=True, slots=True) @@ -1192,25 +1198,25 @@ def invalid_missing_indices( return tuple(sorted(expected_indices - occupied_indices)) def expected_indices(self) -> set[tuple[int, ...]]: - """Return all viewer coordinates implied by the projected axis domains.""" + """Return viewer coordinates backed by routed payload identities.""" if not self.projected_axis_components: return {()} - return set( - product( - *( - tuple( - ViewerComponentCoordinateAuthority.index( - components={component: value}, - component_values=self.component_values, - component=component, - context="viewer route domain", - ) - for value in self.routed_component_values[component] - ) - for component in self.projected_axis_components + return { + tuple( + ViewerComponentCoordinateAuthority.value_index( + value=value, + component_values=self.component_values, + component=component, + context="viewer routed coordinate", + ) + for component, value in zip( + self.projected_axis_components, + coordinate, + strict=True, ) ) - ) + for coordinate in self.routed_component_coordinates + } def require_matching_scalar_components( self, @@ -1292,9 +1298,10 @@ def collapses_to_coordinate_singleton( self, coordinate_values: Sequence[ComponentValue], ) -> bool: - return len( - coordinate_values - ) == 1 and not self.request.declared_domain.has_multiple_values(self.component) + return len(coordinate_values) == 1 and not ( + self.request.declared_domain.has_multiple_values(self.component) + or self.request.viewer_domain.has_multiple_values(self.component) + ) def route_domain_values(self) -> list[ComponentValue]: if not self.request.route_domain.values.get(self.component, []): @@ -1346,6 +1353,7 @@ class ViewerLayerAxisProjectionRequest: """Typed domain bundle for projecting layer-local axes into viewer axes.""" requested_components: tuple[str, ...] + route_component_coordinates: tuple[ComponentCoordinate, ...] route_domain: ViewerComponentValueDomainView viewer_domain: ViewerComponentValueDomainView declared_domain: ViewerComponentValueDomainView @@ -1362,6 +1370,9 @@ def from_component_values( ) -> "ViewerLayerAxisProjectionRequest": return cls( requested_components=tuple(projected_axis_components), + route_component_coordinates=tuple( + tuple(coordinate) for coordinate in route_component_coordinates + ), route_domain=ViewerComponentValueDomainView( route_component_values, "route", @@ -1396,25 +1407,93 @@ def from_component_axis_semantics( component_axis_semantics: ViewerComponentAxisSemantics, layer_items: Sequence[ViewerComponentAddressedItem], route_value_tracker: ViewerRouteComponentValueTracker, - display_axis_domain: ViewerDisplayAxisDomainContract, + aggregate_component_values: ComponentValues, ) -> ViewerLayerAxisProjectionRequest: axis_components = component_axis_semantics.layout.components_for_mode( ViewerComponentMode.STACK ) route_value_tracker.update(route_key, axis_components, layer_items) - display_axis_domain.record_display_axis_values(axis_components, layer_items) + if aggregate_component_values: + route_value_tracker.update_component_values( + route_key, + axis_components, + aggregate_component_values, + ) + declared_component_values = component_axis_semantics.required_component_values( + axis_components + ) + route_value_tracker.declare_component_values( + route_key, + axis_components, + declared_component_values, + ) + viewer_component_values = route_value_tracker.shared_values_for(axis_components) return ViewerLayerAxisProjectionRequest.from_component_values( projected_axis_components=axis_components, + route_component_coordinates=( + ViewerLayerAxisProjectionRequestAuthority.route_coordinates( + axis_components=axis_components, + layer_items=layer_items, + aggregate_component_values=aggregate_component_values, + ) + ), route_component_values=route_value_tracker.values_for( route_value_tracker.domain_key(route_key, axis_components), axis_components, ), - viewer_component_values=declared_component_values, + viewer_component_values=viewer_component_values, declared_component_values=( component_axis_semantics.required_component_values(axis_components) ), ) + @staticmethod + def route_coordinates( + *, + axis_components: Sequence[str], + layer_items: Sequence[ViewerComponentAddressedItem], + aggregate_component_values: ComponentValues, + ) -> tuple[ComponentCoordinate, ...]: + """Return exact routed coordinates, preserving cross-axis identity.""" + + aggregate_components = tuple( + component + for component in axis_components + if component in aggregate_component_values + ) + aggregate_coordinates = tuple( + product( + *( + aggregate_component_values[component] + for component in aggregate_components + ) + ) + ) + if not aggregate_coordinates: + aggregate_coordinates = ((),) + + coordinates: set[ComponentCoordinate] = set() + for item in layer_items: + for aggregate_coordinate in aggregate_coordinates: + components = { + **item.address.components, + **dict( + zip( + aggregate_components, + aggregate_coordinate, + strict=True, + ) + ), + } + coordinates.add( + ViewerComponentCoordinateAuthority.value_tuple( + components, + axis_components, + context="viewer routed item", + ) + ) + return tuple(sorted(coordinates, key=ViewerComponentValueOrdering.tuple_key)) + class ViewerLayerAxisProjector: """Project route component values into the current viewer axis domain.""" @@ -1441,6 +1520,15 @@ def project( routed_component_values={ axis.component: axis.routed_values for axis in projected_axes }, + routed_component_coordinates=tuple( + dict.fromkeys( + tuple( + coordinate[request.requested_components.index(axis.component)] + for axis in projected_axes + ) + for coordinate in request.route_component_coordinates + ) + ), axis_offsets=tuple(axis.axis_offset for axis in projected_axes), scalar_component_values=scalar_component_values, ) @@ -1488,6 +1576,23 @@ def index( component, context=context, ) + return cls.value_index( + value=value, + component_values=component_values, + component=component, + context=context, + ) + + @classmethod + def value_index( + cls, + *, + value: ComponentValue, + component_values: ComponentAxisValues, + component: str, + context: str, + ) -> int: + """Return the positional index for one semantic component value.""" values = cls.required_axis_values( component_values, component, diff --git a/openhcs/runtime/viewer_controls.py b/openhcs/runtime/viewer_controls.py index 412c964fb4..e924ddc7de 100644 --- a/openhcs/runtime/viewer_controls.py +++ b/openhcs/runtime/viewer_controls.py @@ -7,7 +7,7 @@ from enum import Enum from math import isfinite from numbers import Real -from typing import Self, TypeAlias, TypeVar +from typing import ClassVar, Self, TypeAlias, TypeVar from zmqruntime.viewer_protocol import ViewerWireField @@ -466,6 +466,11 @@ def _percentile(value: object, field_name: str) -> float: class ViewerNavigationControlOptions: """Formal viewer navigation controls shared by agent and viewer runtimes.""" + DATA_INDEX_SEMANTICS: ClassVar[str] = ( + "Selecting a native feature row by data_index requires the target layer " + "to remain visible and selected" + ) + route_key: str axis_indices: Mapping[str, int] = field(default_factory=dict) visible: bool | None = None @@ -506,11 +511,14 @@ def __post_init__(self) -> None: raise ValueError("Viewer navigation data_index must be nonnegative.") if self.visible is False: raise ValueError( - "Viewer navigation data_index cannot target a hidden layer." + f"Viewer navigation: {self.DATA_INDEX_SEMANTICS}; it cannot " + "target a hidden layer. Omit data_index when hiding the layer." ) if self.selected is False: raise ValueError( - "Viewer navigation data_index cannot target a deselected layer." + f"Viewer navigation: {self.DATA_INDEX_SEMANTICS}; it cannot " + "target a deselected layer. Omit data_index when deselecting " + "the layer." ) @classmethod diff --git a/openhcs/runtime/viewer_protocol.py b/openhcs/runtime/viewer_protocol.py index b49e8250b6..829cc76819 100644 --- a/openhcs/runtime/viewer_protocol.py +++ b/openhcs/runtime/viewer_protocol.py @@ -61,6 +61,7 @@ from openhcs.core.streaming_config_declarations import ViewerType from openhcs.core.streaming_config_factory import ( StreamingViewerRuntimeConfig, + ViewerProcessLaunchConfig, ) from openhcs.core.xdg_paths import get_openhcs_log_dir from openhcs.runtime.viewer_controls import ( @@ -120,6 +121,10 @@ class ViewerPayloadSummaryField(str, Enum): SHAPE = "shape" NONZERO_COUNT = "nonzero_count" + NONZERO_MIN_COORDINATE = "nonzero_min_coordinate" + NONZERO_MAX_COORDINATE = "nonzero_max_coordinate" + NONZERO_EXAMPLE_COORDINATES = "nonzero_example_coordinates" + NONZERO_COORDINATE_OMISSION_REASON = "nonzero_coordinate_omission_reason" class ViewerControlField(str, Enum): @@ -139,6 +144,13 @@ class ViewerControlField(str, Enum): NATIVE_VIEWPORT = "native_viewport" COMPONENT_GROUP_COUNT = "component_group_count" COMPONENT_ITEM_COUNT = "component_item_count" + PROCESS_LAUNCH = "process_launch" + + +class OpenHCSViewerControlMessageType(str, Enum): + """OpenHCS-owned viewer control messages beyond the transport protocol.""" + + PROCESS_LAUNCH = "process_launch" class ViewerLayerIsolationField(str, Enum): @@ -184,6 +196,7 @@ class ViewerLayerField(str, Enum): PAYLOAD_SUMMARIES_TRUNCATED = "payload_summaries_truncated" AXIS_COMPONENT_VALUES = "axis_component_values" ROUTED_COMPONENT_VALUES = "routed_component_values" + ROUTED_COMPONENT_COORDINATES = "routed_component_coordinates" DATA_SHAPE = "data_shape" NATIVE_TRANSFORM = "native_transform" NATIVE_INTENSITY = "native_intensity" @@ -661,6 +674,9 @@ class ViewerServerLaunchRequest: port: int log_file_path: str | None = None transport_mode: TransportMode = TransportMode.IPC + process_launch: ViewerProcessLaunchConfig = field( + default_factory=ViewerProcessLaunchConfig + ) class OpenHCSViewerServerABC(StreamingVisualizerServer, ABC): @@ -903,6 +919,9 @@ class DetachedViewerLaunchRequest(ViewerTypeIdentity): platform: ViewerProcessPlatform = field( default_factory=ViewerProcessPlatform.current ) + process_launch: ViewerProcessLaunchConfig = field( + default_factory=ViewerProcessLaunchConfig + ) @classmethod def log_file_for( @@ -941,7 +960,10 @@ def launch(self) -> subprocess.Popen[bytes]: ) self.log_file.parent.mkdir(parents=True, exist_ok=True) launch_env = self.launch_context.child_environment(os.environ) - ViewerQtEnvironmentPolicy(self.platform).apply_to(launch_env) + ViewerQtEnvironmentPolicy( + platform=self.platform, + font_dpi=self.process_launch.qt_font_dpi, + ).apply_to(launch_env) log_handle = self.log_file.open("w") launch_policy = BackgroundProcessLaunchPolicy.current(detached=True) return subprocess.Popen( @@ -1026,6 +1048,7 @@ def launch_request( cwd: Path | None = None, launch_context: ViewerLaunchContext | None = None, import_authority: OpenHCSRuntimeImportAuthority | None = None, + process_launch: ViewerProcessLaunchConfig | None = None, ) -> DetachedViewerLaunchRequest: if cwd is None: cwd = Path.cwd() @@ -1033,6 +1056,8 @@ def launch_request( launch_context = ViewerLaunchContext.inherited_graphical_session() if import_authority is None: import_authority = OpenHCSRuntimeImportAuthority.current() + if process_launch is None: + process_launch = ViewerProcessLaunchConfig() return DetachedViewerLaunchRequest( viewer_type=self.viewer_type, port=port, @@ -1044,6 +1069,7 @@ def launch_request( log_file=log_file, cwd=cwd, launch_context=launch_context, + process_launch=process_launch, ) @@ -1076,6 +1102,11 @@ class ViewerQtEnvironmentPolicy: platform: ViewerProcessPlatform = field( default_factory=ViewerProcessPlatform.current ) + font_dpi: int | None = None + + def __post_init__(self) -> None: + if self.font_dpi is not None and self.font_dpi <= 0: + raise ValueError("Viewer Qt font DPI must be positive when provided.") @staticmethod def active_qt_plugin_path() -> str | None: @@ -1094,6 +1125,8 @@ def apply_to( env: MutableMapping[str, str], ) -> MutableMapping[str, str]: self.platform.qt_environment_policy().apply_to(env) + if self.font_dpi is not None: + env["QT_FONT_DPI"] = str(self.font_dpi) plugin_path = self.active_qt_plugin_path() if plugin_path is not None: # Private plugin trees exported by dependencies such as OpenCV are @@ -1284,6 +1317,7 @@ def __init__( self.persistent: bool = runtime_config.persistent self.display_enabled: bool = runtime_config.display_enabled self.scope_accent_color = runtime_config.scope_accent_color + self.process_launch = runtime_config.process_launch self._launch_context = ViewerLaunchContext.inherited_graphical_session() self.runtime_endpoint = ViewerRuntimeEndpoint( transport=runtime_config.transport_endpoint, @@ -1379,6 +1413,14 @@ def existing_viewer_is_ready(self) -> bool: timeout_ms=request.timeout_ms, require_ready=request.require_ready, ).require_match() + if not self.existing_viewer_matches_process_launch(): + logging.getLogger(type(self).__module__).warning( + "%s viewer on port %s has a different process-launch " + "declaration and cannot be reused.", + self.viewer_process_label, + self.required_port, + ) + return False except (RuntimeError, EndpointApplicationCompatibilityError) as error: logging.getLogger(type(self).__module__).warning( "%s viewer on port %s cannot be reused: %s", @@ -1389,6 +1431,11 @@ def existing_viewer_is_ready(self) -> bool: return False return True + def existing_viewer_matches_process_launch(self) -> bool: + """Return whether a reachable viewer matches process-global settings.""" + + return True + def wait_for_ready(self, timeout: float = 10.0) -> bool: """Wait for the viewer endpoint to bind and report ready.""" if not self.runtime_endpoint.wait_ready( @@ -1420,6 +1467,7 @@ def detached_launch_request(self) -> DetachedViewerLaunchRequest: arguments=self.detached_server_arguments(log_file=log_file), log_file=log_file, launch_context=self._launch_context, + process_launch=self.process_launch, ) def launch_detached_viewer(self) -> subprocess.Popen[bytes]: diff --git a/tests/unit/agent/test_agent_services.py b/tests/unit/agent/test_agent_services.py index 14b1c0eb82..514961368a 100644 --- a/tests/unit/agent/test_agent_services.py +++ b/tests/unit/agent/test_agent_services.py @@ -32,6 +32,7 @@ OrchestratorSessionCreationRequest, PipelineSourceArtifactPlanInspectionRequest, PipelineSourceOrchestratorSessionRequest, + RuntimeServerExecutionStatusRequest, ) from openhcs.agent.dto.functions import FunctionParameterSource from openhcs.agent.dto.pipeline import CreatePipelineRequest @@ -860,6 +861,10 @@ def window_state(self, request): "site": (1,), "channel": (0,), }, + "routed_component_coordinates": ( + ("A14", 1, 0), + ("B13", 1, 0), + ), "data_shape": (2, 1, 1, 16, 16), "native_transform": { "scale": (1.0, 1.0, 1.0, 0.65, 0.65), @@ -1122,6 +1127,12 @@ def window_state(self, request): "site": (1,), "channel": (0, 2), } + layer["routed_component_coordinates"] = ( + ("A14", 1, 0), + ("A14", 1, 2), + ("B13", 1, 0), + ("B13", 1, 2), + ) state["layers"] = (layer,) return state @@ -1159,6 +1170,7 @@ def window_state(self, request): layer["routed_component_values"] = { "channel": (0,), } + layer["routed_component_coordinates"] = ((0,),) layer["data_shape"] = (1, 16, 16) layer["native_transform"] = { "scale": (1.0, 0.65, 0.65), @@ -1247,6 +1259,11 @@ def window_state(self, request): "z_index": (1, 2, 3), "channel": (1,), } + layer["routed_component_coordinates"] = ( + (1, 1), + (2, 1), + (3, 1), + ) layer["data_shape"] = (3, 1, 16, 16) state["layers"] = (layer,) state["axis_labels"] = ("z_index", "channel", "y", "x") @@ -3829,6 +3846,12 @@ def test_runtime_server_service_reads_runtime_server_state(): ) +def test_runtime_execution_status_request_uses_control_timeout_by_default(): + request = RuntimeServerExecutionStatusRequest.from_fields(port=5555) + + assert request.timeout_ms == OPENHCS_ZMQ_CONFIG.control_timeout_ms + + def test_runtime_server_scan_filters_by_declared_server_role(): service = RuntimeServerService(gateway=_MixedRoleRuntimeServerGateway()) diff --git a/tests/unit/agent/test_mcp_server.py b/tests/unit/agent/test_mcp_server.py index 2aaba75927..48d4d820ac 100644 --- a/tests/unit/agent/test_mcp_server.py +++ b/tests/unit/agent/test_mcp_server.py @@ -7695,7 +7695,7 @@ def test_mcp_dev_client_runtime_status_command_renders_execution_counts(): assert call.arguments["port"] == 7777 assert call.arguments["execution_id"] == "run-1" assert call.arguments["transport_mode"] == "ipc" - assert call.arguments["timeout_ms"] == 500 + assert call.arguments["timeout_ms"] == OPENHCS_ZMQ_CONFIG.control_timeout_ms response = { "errors": [], @@ -8245,6 +8245,52 @@ def test_mcp_dev_client_code_documents_command_projects_tool_arguments(): } +def test_mcp_dev_client_code_documents_preserves_inner_bridge_timeout_payload(): + if importlib.util.find_spec("mcp") is None: + return + + import openhcs.mcp.dev_client as dev_client + from openhcs.mcp.control_timeout import McpUiBridgeTimeoutPolicy + from openhcs.mcp.dev_client_core import MCP_TOOL_TIMEOUT_MARGIN_SECONDS + + observed_timeout_seconds: list[float] = [] + + class RecordingSession: + server_spec = dev_client.McpDevServerSpec(sys.executable) + + async def call_tool(self, name, arguments, *, timeout_seconds): + del name, arguments + observed_timeout_seconds.append(timeout_seconds) + return { + "structuredContent": { + "schema_version": SCHEMA_VERSION, + "documents": [], + "errors": [ + { + "code": "ui_bridge_timeout", + "message": "UI bridge operation timed out after 5000ms.", + } + ], + } + } + + parser = dev_client._build_parser() + args = parser.parse_args(("code-documents", "--json")) + response = asyncio.run( + dev_client.McpDevCommandSpec.for_name("code-documents").run_session( + RecordingSession(), + args, + ) + ) + + inner_timeout_seconds = McpUiBridgeTimeoutPolicy.resolve(None) / 1000.0 + assert observed_timeout_seconds == [ + inner_timeout_seconds + MCP_TOOL_TIMEOUT_MARGIN_SECONDS + ] + assert observed_timeout_seconds[0] > inner_timeout_seconds + assert response.results[0].has_only_agent_error_code("ui_bridge_timeout") + + def test_mcp_dev_client_code_documents_command_renders_compact_summary(): if importlib.util.find_spec("mcp") is None: return @@ -13120,6 +13166,7 @@ def test_mcp_dev_client_viewer_state_command_renders_component_metadata(tmp_path ], "axis_component_values": {"channel": [1, 2]}, "routed_component_values": {"channel": [1, 2]}, + "routed_component_coordinates": [[1], [2]], "payload_summary_count": 2, "payload_summaries_truncated": False, "payload_summaries": [ @@ -14730,7 +14777,14 @@ def test_mcp_dev_client_launches_fresh_current_source_server(): async def call_health_through_dev_client(): args = dev_client._build_parser().parse_args( - ("call", "openhcs_health_check", "--json", "--timeout-seconds", "5") + ( + "call", + "openhcs_health_check", + "--json", + "--timeout-seconds", + str(dev_client.DEFAULT_REGISTRY_DISCOVERY_TIMEOUT_SECONDS), + "--no-resident", + ) ) return await dev_client.McpDevCommandSpec.for_name("call").run( dev_client.McpDevServerSpec(sys.executable), @@ -15283,6 +15337,48 @@ async def exercise(): assert len(context.progress) >= 3 +@pytest.mark.parametrize("error_type", [TimeoutError, ValueError, asyncio.CancelledError]) +@pytest.mark.parametrize("after_heartbeat", [False, True]) +def test_declared_progress_propagates_terminal_operation_errors( + monkeypatch, error_type, after_heartbeat +): + completed = False + heartbeat = asyncio.Event() + + class RecordingMcpContext: + request_context = object() + + async def report_progress(self, progress, total=None, message=None): + # Fail promptly even with the old loop rather than hanging the test. + assert not completed, "Terminal operation reported as still running" + if progress: + heartbeat.set() + + monkeypatch.setattr( + CreateOrchestratorSessionFromPipelineSourceCapability, + "progress_heartbeat_seconds", + 0.005, + ) + capability = CreateOrchestratorSessionFromPipelineSourceCapability.to_spec() + error = error_type("operation terminated") + + async def operation(): + nonlocal completed + if after_heartbeat: + await heartbeat.wait() + completed = True + raise error + + async def exercise(): + with pytest.raises(error_type) as caught: + await server._await_with_declared_progress( + capability, RecordingMcpContext(), operation() + ) + assert caught.value is error + + asyncio.run(exercise()) + + def test_verbose_blocking_operation_arms_bounded_stack_diagnostic(monkeypatch): monkeypatch.setenv(server.MCP_VERBOSE_ENVIRONMENT_VARIABLE, "1") capability = CreateOrchestratorSessionFromPipelineSourceCapability.to_spec() diff --git a/tests/unit/agent/test_plate_inspection_service.py b/tests/unit/agent/test_plate_inspection_service.py index 6a5f07a126..8ad097bcc8 100644 --- a/tests/unit/agent/test_plate_inspection_service.py +++ b/tests/unit/agent/test_plate_inspection_service.py @@ -30,6 +30,9 @@ from openhcs.core.config import GlobalPipelineConfig, PathPlanningConfig from openhcs.core.pipeline.path_planner import PathPlannerPathAuthority from openhcs.core.plate_image_inventory import PlateFileKind +from openhcs.core.source_workspace_projection import ( + VirtualWorkspaceSourceProjectionAuthority, +) from openhcs.microscopes.bioformats import BioFormatsHandler from openhcs.microscopes.microscope_base import MicroscopeSourceSelectionRole from openhcs.microscopes.source_bindings_handler import SourceBindingsHandler @@ -1418,3 +1421,44 @@ def test_plate_inspection_reports_path_policy_errors(tmp_path: Path): ) assert "arbitrary TIFF, PNG" in result.workflow_advice.message assert "CZI, OME" in result.workflow_advice.message + + +def test_plate_file_query_resolves_source_projection_once( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + plate = ImageXpressPlateFixture.write(tmp_path) + source_projection_resolution_count = 0 + original_from_plate_metadata = ( + VirtualWorkspaceSourceProjectionAuthority.from_plate_metadata.__func__ + ) + + def counted_from_plate_metadata(cls, **kwargs): + nonlocal source_projection_resolution_count + source_projection_resolution_count += 1 + return original_from_plate_metadata(cls, **kwargs) + + monkeypatch.setattr( + VirtualWorkspaceSourceProjectionAuthority, + "from_plate_metadata", + classmethod(counted_from_plate_metadata), + ) + service = PlateInspectionService( + AgentPathPolicy.with_roots( + readable_roots=(tmp_path,), + writable_roots=(tmp_path,), + ) + ) + + query = service.query_files( + PlateFileQueryRequest( + plate_path=str(plate), + microscope_type="imagexpress", + kind=PlateFileKind.IMAGE, + limit=1, + ) + ) + + assert query.errors == () + assert query.total_count == 2 + assert source_projection_resolution_count == 1 diff --git a/tests/unit/agent/test_plate_streaming_service.py b/tests/unit/agent/test_plate_streaming_service.py index 6ecd044bb8..783b76a8ee 100644 --- a/tests/unit/agent/test_plate_streaming_service.py +++ b/tests/unit/agent/test_plate_streaming_service.py @@ -6,8 +6,8 @@ from openhcs.agent.dto.plate import ( PlateFileStreamRequest, ) -from openhcs.agent.services.plate_streaming_service import PlateStreamingService from openhcs.agent.services.plate_inspection_service import PlateInspectionContext +from openhcs.agent.services.plate_streaming_service import PlateStreamingService from openhcs.constants.constants import FileFormat from openhcs.core.plate_image_inventory import ( PlateFileInventory, @@ -15,8 +15,8 @@ PlateImageRecord, PlateResultFileRecord, ) -from openhcs.mcp.context import OpenHCSAgentContext from openhcs.core.streaming_config_declarations import ViewerType +from openhcs.mcp.context import OpenHCSAgentContext from openhcs.runtime.viewer_protocol import ( DetachedViewerLaunchFailure, ViewerGraphicalSessionUnavailableError, @@ -445,6 +445,42 @@ def test_plate_streaming_service_reports_explicit_result_excluded_by_default_kin assert "excluded by the requested kind filter (image)" in result.errors[0].message +def test_explicit_stream_path_selects_its_declared_dual_projection(): + relative_path = "images_results/A01_objects_step1.labels.tif" + full_path = f"/plate/{relative_path}" + inventory = PlateFileInventory( + plate_path=Path("/plate"), + image_records=( + PlateImageRecord( + virtual_path=relative_path, + full_virtual_path=full_path, + backend="virtual_workspace", + source_path=full_path, + ), + ), + result_records=( + PlateResultFileRecord( + relative_path=relative_path, + full_path=full_path, + file_format=FileFormat.TIFF, + ), + ), + ) + + records = PlateStreamingService._resolve_records( + PlateFileStreamRequest( + plate_path="/plate", + file_paths=(relative_path,), + kind=None, + ), + inventory, + ) + + assert len(records) == 1 + assert records[0].kind is PlateFileKind.IMAGE + assert records[0].streamable_image_path == relative_path + + def test_plate_streaming_service_query_limit_counts_streamable_roi_results(monkeypatch): captured = {} roi_one_path = "/plate_openhcs/checkpoints_step7_results/A01_w1_rois.roi.zip" @@ -489,6 +525,9 @@ def fake_stream_rois(self, request): del self captured["roi_filenames"] = request.roi_filenames captured["component_metadata_by_path"] = request.component_metadata_by_path + captured["producer_output_keys"] = tuple( + identity.output_key for identity in request.producer.identities + ) request.status_callback("streamed query rois") monkeypatch.setattr( @@ -520,6 +559,10 @@ def fake_stream_rois(self, request): roi_one_path: {"well": "A01", "channel": 1}, roi_two_path: {"well": "A01", "channel": 2}, }, + "producer_output_keys": ( + "checkpoints_step7_results/A01_w1_rois.roi.zip", + "checkpoints_step7_results/A01_w2_rois.roi.zip", + ), } assert result.status_messages == ("streamed query rois",) diff --git a/tests/unit/pyqt_gui/test_ui_agent_bridge.py b/tests/unit/pyqt_gui/test_ui_agent_bridge.py index 1df5fac438..39e51897ac 100644 --- a/tests/unit/pyqt_gui/test_ui_agent_bridge.py +++ b/tests/unit/pyqt_gui/test_ui_agent_bridge.py @@ -52,7 +52,7 @@ OBJECT_STATE_PATH_ROLE, SIG_DIFF_FIELDS_ROLE, ) -from zmqruntime import EndpointApplication +from zmqruntime import DataControlPortPairAuthority, EndpointApplication from zmqruntime.config import TransportMode from openhcs.agent.dto.common import SCHEMA_VERSION @@ -220,6 +220,7 @@ ) from openhcs.pyqt_gui.windows.live_measurements_window import LiveMeasurementTableModel from openhcs.runtime.zmq_application import OPENHCS_ENDPOINT_APPLICATION +from openhcs.runtime.zmq_config import OPENHCS_ZMQ_CONFIG from openhcs.serialization.json import to_jsonable from openhcs.ui.shared.plate_manager_code_document import ( PlateManagerCodeDocumentAuthority, @@ -5034,6 +5035,68 @@ def test_ui_bridge_control_server_round_trips_documents_through_descriptor( assert not Path(binding.descriptor_file_path).exists() +def test_two_ipc_ui_bridges_route_each_descriptor_to_its_exact_instance( + tmp_path: Path, +) -> None: + first_pair = DataControlPortPairAuthority.acquire( + OPENHCS_ZMQ_CONFIG, + transport_mode=TransportMode.IPC, + ) + second_pair = DataControlPortPairAuthority.acquire( + OPENHCS_ZMQ_CONFIG, + transport_mode=TransportMode.IPC, + excluded=first_pair.ports, + ) + descriptor_directory = tmp_path / "descriptors" + first_server = UiBridgeControlServer( + UiAgentBridgeService(dispatcher=InlineDispatcher()), + AgentUiBridgeConfig( + port=first_pair.data_port, + transport_mode=TransportMode.IPC, + descriptor_directory_path=descriptor_directory, + bridge_instance_id="first-bridge", + auth_token="first-token", + ), + ) + second_server = UiBridgeControlServer( + UiAgentBridgeService(dispatcher=InlineDispatcher()), + AgentUiBridgeConfig( + port=second_pair.data_port, + transport_mode=TransportMode.IPC, + descriptor_directory_path=descriptor_directory, + bridge_instance_id="second-bridge", + auth_token="second-token", + ), + ) + + first_binding = first_server.start() + try: + second_binding = second_server.start() + service = UiBridgeService() + first_status = service.status( + service.connection_from_args( + descriptor_file_path=first_binding.descriptor_file_path + ) + ) + second_status = service.status( + service.connection_from_args( + descriptor_file_path=second_binding.descriptor_file_path + ) + ) + + assert first_status.reachable is True + assert first_status.bridge_instance_id == "first-bridge" + assert first_status.connection.port == first_pair.data_port + assert second_status.reachable is True + assert second_status.bridge_instance_id == "second-bridge" + assert second_status.connection.port == second_pair.data_port + finally: + if second_server.is_running: + second_server.stop() + if first_server.is_running: + first_server.stop() + + def test_ui_bridge_control_server_preserves_bad_auth_error(tmp_path: Path) -> None: bridge = UiAgentBridgeService(dispatcher=InlineDispatcher()) server = UiBridgeControlServer( diff --git a/tests/unit/pyqt_gui/test_ui_bridge_lifecycle_config.py b/tests/unit/pyqt_gui/test_ui_bridge_lifecycle_config.py index 49810c6d3d..a79b63eaaa 100644 --- a/tests/unit/pyqt_gui/test_ui_bridge_lifecycle_config.py +++ b/tests/unit/pyqt_gui/test_ui_bridge_lifecycle_config.py @@ -11,6 +11,8 @@ from pyqt_reactive.services.zmq_server_scan_service import ZMQServerScanService from zmqruntime import ( ControlMessageType, + DataControlPortPairAuthority, + OperationTimeoutError, ResponseType, ServerRole, TcpDataControlPortPairAuthority, @@ -32,6 +34,7 @@ from openhcs.pyqt_gui.services.ui_bridge_server import ( UI_BRIDGE_BROWSER_SERVER_NAME, UiBridgeControlServer, + UiBridgeEndpointInUseError, ) from openhcs.runtime.zmq_application import OPENHCS_ENDPOINT_APPLICATION from openhcs.runtime.zmq_config import OPENHCS_ZMQ_CONFIG, OpenHCSZMQConfig @@ -466,6 +469,117 @@ def test_ui_bridge_answers_zmq_browser_control_ping(tmp_path) -> None: assert response["application"] == OPENHCS_ENDPOINT_APPLICATION.to_dict() +def test_second_ipc_ui_bridge_cannot_replace_live_endpoint_pair(tmp_path) -> None: + transport_config = replace( + OPENHCS_ZMQ_CONFIG, + ipc_socket_dir=str(tmp_path / "ipc"), + ipc_socket_prefix="ui-bridge-collision", + ) + endpoint_pair = DataControlPortPairAuthority.acquire( + transport_config, + transport_mode=TransportMode.IPC, + ) + config = AgentUiBridgeConfig( + host="127.0.0.1", + port=endpoint_pair.data_port, + transport_mode=TransportMode.IPC, + descriptor_directory_path=tmp_path / "descriptors", + ) + original = UiBridgeControlServer( + bridge=SimpleNamespace(close=lambda: None), + config=replace(config, bridge_instance_id="original"), + transport_config=transport_config, + ) + contender = UiBridgeControlServer( + bridge=SimpleNamespace(close=lambda: None), + config=replace(config, bridge_instance_id="contender"), + transport_config=transport_config, + ) + + context = None + socket = None + original_binding = original.start() + try: + with pytest.raises(UiBridgeEndpointInUseError, match="already in use"): + contender.start() + + assert original.is_running + assert Path(original_binding.descriptor_file_path).exists() + assert not (tmp_path / "descriptors" / "ui_bridge_contender.json").exists() + + context = zmq.Context() + socket = context.socket(zmq.REQ) + socket.setsockopt(zmq.LINGER, 0) + socket.setsockopt(zmq.RCVTIMEO, 1000) + socket.connect(original_binding.connection.zmq_control_url(transport_config)) + socket.send(pickle.dumps({"type": ControlMessageType.PING.value})) + response = pickle.loads(socket.recv()) + assert response["bridge_instance_id"] == "original" + finally: + original.stop() + if contender.is_running: + contender.stop() + if socket is not None: + socket.close(linger=0) + if context is not None: + context.term() + + assert original_binding.connection.transport_endpoint().occupied_ports( + transport_config + ) == frozenset() + + +def test_ui_bridge_startup_lock_timeout_precedes_worker_readiness_wait( + monkeypatch, + tmp_path, +) -> None: + server = UiBridgeControlServer( + bridge=SimpleNamespace(close=lambda: None), + config=AgentUiBridgeConfig( + port=7999, + transport_mode=TransportMode.IPC, + descriptor_directory_path=tmp_path, + ), + ) + + class ExpiringStartupLock: + def __init__(self, deadline) -> None: + self.deadline = deadline + + def __enter__(self): + assert server._thread is None + threading.Event().wait(0.01) + self.deadline.remaining_seconds() + raise AssertionError("Expired startup lock unexpectedly acquired") + + def __exit__(self, exc_type, exc, traceback) -> None: + del exc_type, exc, traceback + + def expiring_startup_lock( + port, + transport_mode, + transport_config, + *, + operation_deadline, + ): + del port, transport_mode, transport_config + return ExpiringStartupLock(operation_deadline) + + monkeypatch.setattr( + "openhcs.pyqt_gui.services.ui_bridge_server.endpoint_startup_lock", + expiring_startup_lock, + ) + + with pytest.raises( + OperationTimeoutError, + match="UI bridge endpoint startup", + ): + server.start(timeout_seconds=0.001) + + assert server._thread is None + assert not tuple(tmp_path.glob("ui_bridge_*.json")) + + def test_ui_bridge_matches_only_its_exact_live_declarations(tmp_path) -> None: transport_config = OpenHCSZMQConfig() port = TcpDataControlPortPairAuthority.acquire(transport_config).data_port @@ -505,7 +619,10 @@ def test_ui_bridge_matches_only_its_exact_live_declarations(tmp_path) -> None: def test_zmq_browser_scan_service_discovers_ui_bridge_default_transport( tmp_path, ) -> None: - port = TcpDataControlPortPairAuthority.acquire(OPENHCS_ZMQ_CONFIG).data_port + port = DataControlPortPairAuthority.acquire( + OPENHCS_ZMQ_CONFIG, + transport_mode=get_default_transport_mode(), + ).data_port server = UiBridgeControlServer( bridge=SimpleNamespace(close=lambda: None), config=AgentUiBridgeConfig( diff --git a/tests/unit/test_artifact_spec_collection.py b/tests/unit/test_artifact_spec_collection.py index e78401eb56..db6e37dd1c 100644 --- a/tests/unit/test_artifact_spec_collection.py +++ b/tests/unit/test_artifact_spec_collection.py @@ -9,6 +9,7 @@ ArtifactSpecCollection, GroupLineageSourceRelation, ImageArtifactType, + MainFlowPlaneProjectionOutputSpec, MeasurementsArtifactType, ObjectLabelsArtifactType, ) @@ -171,3 +172,20 @@ def test_image_output_plan_requires_one_exact_source_context() -> None: relations=relations, ) assert measurements.source_context_source() is None + + +def test_main_flow_plane_projection_binds_group_lineage_without_fake_context() -> None: + first = ArtifactSpec.input("First", ImageArtifactType) + second = ArtifactSpec.input("Second", ImageArtifactType) + sources = ArtifactSpecCollection((first, second)) + declared = MainFlowPlaneProjectionOutputSpec.output( + "Projected", + ImageArtifactType, + ) + + bound = declared.bind_main_flow_source(sources) + + assert bound.group_scope_sources() == (first.ref(), second.ref()) + assert bound.source_context_sources() == () + assert bound.source_stack_scope_sources() == () + assert bound.bind_main_flow_source(sources) is bound diff --git a/tests/unit/test_function_outputs.py b/tests/unit/test_function_outputs.py index 4155c9a180..0d0b752459 100644 --- a/tests/unit/test_function_outputs.py +++ b/tests/unit/test_function_outputs.py @@ -3,8 +3,8 @@ from types import SimpleNamespace import numpy as np -import tifffile import pytest +import tifffile from polystore.disk import DiskStorageBackend from polystore.filemanager import FileManager from polystore.memory import MemoryStorageBackend @@ -13,6 +13,7 @@ ViewerStreamKwarg, ViewerStreamSourceIdentity, ) +from polystore.virtual_workspace import SourcePixelRef from zmqruntime.viewer_protocol import ViewerTransportEndpoint from openhcs.constants.constants import AllComponents, Backend, VariableComponents @@ -22,7 +23,12 @@ ObjectLabelsArtifactType, ) from openhcs.core.axis_filter import StepAxisFilterResolution, StepAxisFilterSet -from openhcs.core.compiled_step_plan import CompiledStepPlan, MaterializedOutputPlan +from openhcs.core.compiled_step_plan import ( + CompiledStepPlan, + MaterializedOutputPlan, + RuntimeArtifactMaterializationPlan, +) +from openhcs.core.component_group_scope import RuntimeExecutionAxisScope from openhcs.core.components.parser_metaprogramming import FilenameParseResult from openhcs.core.config import WellFilterMode from openhcs.core.function_patterns import compile_function_pattern @@ -57,16 +63,23 @@ MemoryOutputWriter, OpenHCSMetadataWriter, ProducedMemoryPathsAuthority, + RuntimeArtifactMaterializationAuthority, StreamOutputsAuthority, + finalize_function_step_outputs, ) -from openhcs.microscopes.microscope_interfaces import MetadataHandler from openhcs.core.streaming_config_declarations import ViewerType from openhcs.core.streaming_config_factory import ( StreamingViewerRuntimeConfig, StreamingViewerSurface, ) -from openhcs.core.virtual_workspace_metadata import FIELDS +from openhcs.core.virtual_workspace_metadata import ( + FIELDS, + VirtualWorkspaceSourceProjectionEntries, +) +from openhcs.microscopes.microscope_interfaces import MetadataHandler from openhcs.microscopes.openhcs import OpenHCSMetadataHandler +from openhcs.microscopes.source_schema import SourceSchemaFilenameParser +from openhcs.processing.materialization.core import Output @pytest.mark.parametrize("backend", [Backend.ZARR.value, "custom-array-store"]) @@ -89,6 +102,40 @@ def test_memory_output_writer_projects_runtime_image_payload_for_array_storage( assert prepared[0] is image +def test_function_step_metadata_follows_runtime_artifact_persistence( + monkeypatch, +) -> None: + events = [] + context = SimpleNamespace() + plan = SimpleNamespace() + for authority, method_name, event in ( + (MemoryOutputWriter, "write_if_needed", "memory"), + (MaterializedImageOutputWriter, "write_if_needed", "materialized"), + (StreamOutputsAuthority, "stream_outputs", "stream"), + ( + RuntimeArtifactMaterializationAuthority, + "materialize", + "runtime_artifacts", + ), + (OpenHCSMetadataWriter, "write", "metadata"), + ): + monkeypatch.setattr( + authority, + method_name, + lambda _context, _plan, event=event: events.append(event), + ) + + finalize_function_step_outputs(context, plan) + + assert events == [ + "memory", + "materialized", + "stream", + "runtime_artifacts", + "metadata", + ] + + def test_memory_output_writer_rejects_payload_path_cardinality_mismatch(): with pytest.raises(ValueError, match="1 payloads for 0 paths"): MemoryOutputWriter.payloads( @@ -1482,6 +1529,237 @@ def test_produced_projection_metadata_persists_typed_collapsed_semantics( assert subdirectory[FIELDS.SOURCE_METADATA]["images/A01_s1_w1.tif"]["site"] == "1" +def test_runtime_image_artifact_projects_persisted_source_binding( + tmp_path, monkeypatch +) -> None: + plate_root = tmp_path / "output_plate" + output_dir = plate_root / "analysis_inputs" + output_dir.mkdir(parents=True) + output_path = ( + output_dir / "A49_s001_w2_z001_t001_neurite_candidate_mask.checkpoint.tif" + ) + pixels = np.ones((4, 5), dtype=np.uint8) + tifffile.imwrite(output_path, pixels) + context = context_stub( + FileManager( + { + Backend.DISK.value: DiskStorageBackend(), + Backend.MEMORY.value: MemoryStorageBackend(), + } + ), + parser=SourceSchemaFilenameParser(), + ) + plan = function_step_plan("Neurite checkpoint") + plan.materialized_output = MaterializedOutputPlan( + output_dir=output_dir, + backend=Backend.DISK.value, + plate_root=str(plate_root), + sub_dir="analysis_inputs", + analysis_results_dir=str(plate_root / "analysis_inputs_results"), + ) + plan.runtime_artifact_materialization = RuntimeArtifactMaterializationPlan( + persistent_enabled=True, + persistent_backend=Backend.DISK.value, + ) + metadata = ImagePayloadMetadata( + source_component_metadata={ + "well": "A49", + "site": "1", + "channel": "2", + "z_index": "1", + "timepoint": "1", + } + ) + output = Output.from_metadata( + path=str(output_path), + content=pixels, + metadata=metadata, + ) + materialization = SimpleNamespace( + spec=SimpleNamespace(participates_in_persistent_materialization=lambda: True), + output_plan=SimpleNamespace( + name="neurite_candidate_mask", + artifact_type=ImageArtifactType, + ), + record=SimpleNamespace( + key=SimpleNamespace( + scope=RuntimeExecutionAxisScope.from_raw( + "A49", + component=AllComponents.SITE, + value="1", + fixed_component_values=( + (AllComponents.Z_INDEX, "1"), + (AllComponents.TIMEPOINT, "1"), + ), + ) + ) + ), + outputs=lambda _plan, _context, **_kwargs: (output,), + ) + monkeypatch.setattr( + "openhcs.core.steps.function_outputs.runtime_artifact_materializations", + lambda _plan, _context: (materialization,), + ) + + target = OpenHCSMetadataWriter.OutputTarget.materialized(plan) + assert target is not None + [(projection, virtual_path)] = target.runtime_artifact_projection_paths( + context, plan + ) + + assert virtual_path == ( + "analysis_inputs/A49_s001_w2_z001_t001_neurite_candidate_mask.checkpoint.tif" + ) + assert projection.source_alias == "neurite_candidate_mask" + assert projection.artifact_kind is ImageArtifactType + assert projection.image_metadata is not None + assert projection.image_metadata.source_dtype == "uint8" + assert projection.ref == SourcePixelRef(Backend.DISK.value, virtual_path) + structured = target.produced_projection_metadata(context, plan) + assert structured is not None + [record] = structured[FIELDS.SOURCE_PROJECTION] + assert record["virtual_path"] == virtual_path + assert record["source_alias"] == "neurite_candidate_mask" + assert record["artifact_kind"] == ImageArtifactType.value + assert ( + record[SourceProjectionMetadataSerializer.IMAGE_METADATA_FIELD]["source_dtype"] + == "uint8" + ) + + +def test_runtime_multiplane_label_artifact_projects_persisted_source_binding( + tmp_path, monkeypatch +) -> None: + plate_root = tmp_path / "output_plate" + output_dir = plate_root / "analysis_inputs" + output_dir.mkdir(parents=True) + output_path = ( + plate_root + / "analysis_inputs_results" + / "A49_z_index-1_timepoint-1_neurite_outgrowth_step0.labels.tif" + ) + output_path.parent.mkdir(parents=True) + pixels = np.ones((2, 4, 5), dtype=np.int32) + tifffile.imwrite(output_path, pixels) + context = context_stub( + FileManager( + { + Backend.DISK.value: DiskStorageBackend(), + Backend.MEMORY.value: MemoryStorageBackend(), + } + ), + parser=SourceSchemaFilenameParser(), + ) + plan = function_step_plan("Neurite labels") + plan.materialized_output = MaterializedOutputPlan( + output_dir=output_dir, + backend=Backend.DISK.value, + plate_root=str(plate_root), + sub_dir="analysis_inputs", + analysis_results_dir=str(plate_root / "analysis_inputs_results"), + ) + plan.runtime_artifact_materialization = RuntimeArtifactMaterializationPlan( + persistent_enabled=True, + persistent_backend=Backend.DISK.value, + ) + common_metadata = { + "well": "A49", + "site": "1", + "z_index": "1", + "timepoint": "1", + } + metadata = ImagePayloadMetadata( + source_provenance=SourceImageProvenance( + source_component_metadata=common_metadata, + source_image_provenance_planes=( + SourceImageProvenancePlanes.from_components( + paths=("/source/A49_w1.tif", "/source/A49_w2.tif"), + component_metadata=( + {**common_metadata, "channel": "1"}, + {**common_metadata, "channel": "2"}, + ), + ) + ), + ), + plane_axis=RuntimePlaneAxis.RUNTIME_SLICE, + ) + output = Output.from_metadata( + path=str(output_path), + content=pixels, + metadata=metadata, + ) + materialization = SimpleNamespace( + spec=SimpleNamespace(participates_in_persistent_materialization=lambda: True), + output_plan=SimpleNamespace( + name="neurite_outgrowth", + artifact_type=ObjectLabelsArtifactType, + ), + record=SimpleNamespace( + key=SimpleNamespace( + scope=RuntimeExecutionAxisScope.from_raw( + "A49", + component=AllComponents.SITE, + value="1", + fixed_component_values=( + (AllComponents.Z_INDEX, "1"), + (AllComponents.TIMEPOINT, "1"), + ), + ) + ) + ), + outputs=lambda _plan, _context, **_kwargs: (output,), + ) + monkeypatch.setattr( + "openhcs.core.steps.function_outputs.runtime_artifact_materializations", + lambda _plan, _context: (materialization,), + ) + + target = OpenHCSMetadataWriter.OutputTarget.materialized(plan) + assert target is not None + [(projection, virtual_path)] = target.runtime_artifact_projection_paths( + context, plan + ) + + assert virtual_path == ( + "analysis_inputs_results/" + "A49_z_index-1_timepoint-1_neurite_outgrowth_step0.labels.tif" + ) + assert projection.artifact_kind is ObjectLabelsArtifactType + assert projection.address is None + assert projection.execution_scope == materialization.record.key.scope + assert projection.image_metadata is not None + assert projection.image_metadata.source_provenance.source_plane_count == 2 + assert tuple( + projection.image_metadata.for_source_plane(index).source_component_metadata[ + "channel" + ] + for index in range(2) + ) == ("1", "2") + structured = target.produced_projection_metadata(context, plan) + assert structured is not None + [record] = structured[FIELDS.SOURCE_PROJECTION] + assert record["artifact_kind"] == ObjectLabelsArtifactType.value + assert record["address"] is None + assert record["execution_scope"]["axis_id"] == "A49" + assert ( + len( + record[SourceProjectionMetadataSerializer.IMAGE_METADATA_FIELD][ + "source_provenance" + ]["source_image_provenance_planes"] + ) + == 2 + ) + restored = VirtualWorkspaceSourceProjectionEntries.from_subdirectory( + structured + ).entries[virtual_path] + assert restored.address is None + assert restored.execution_scope == materialization.record.key.scope + assert restored.artifact_kind is ObjectLabelsArtifactType + assert restored.image_metadata is not None + assert restored.image_metadata.plane_axis is RuntimePlaneAxis.RUNTIME_SLICE + assert restored.image_metadata.source_provenance.source_plane_count == 2 + + class _QualifierIgnoringParserStub: """Parse well/site/channel from filenames with an ignored output qualifier. @@ -1600,6 +1878,7 @@ def test_completed_plate_metadata_includes_outputs_written_after_owner_axis( first_image = images_dir / "A01_s1_w1.tif" later_image = images_dir / "B03_s1_w1.tif" from polystore.memory import MemoryStorageBackend + from openhcs.core.image_file_serialization import ImageFileFormat first_pixels = np.zeros((4, 5), dtype=np.uint16) diff --git a/tests/unit/test_function_runtime_source_projection.py b/tests/unit/test_function_runtime_source_projection.py index c80a3fd134..90ffc46056 100644 --- a/tests/unit/test_function_runtime_source_projection.py +++ b/tests/unit/test_function_runtime_source_projection.py @@ -5191,8 +5191,9 @@ def test_input_aligned_stack_output_uses_input_filename_identity( assert identity.filename_component_values["site"] == 2 +@pytest.mark.parametrize("retains_contributors", [False, True]) def test_function_output_path_keeps_payload_split_axis_over_input_alignment( - tmp_path: Path, + tmp_path: Path, retains_contributors: bool, ) -> None: payload = ImagePayloadMetadata( source_path="/source/A01_s001_w1_z001_t001.tif", @@ -5203,6 +5204,17 @@ def test_function_output_path_keeps_payload_split_axis_over_input_alignment( "z_index": "1", "timepoint": "1", }, + source_image_provenance_planes=( + SourceImageProvenancePlanes.from_contributor_components( + paths=( + "/source/A01_s001_w1_z001_t001.tif", + "/source/A01_s002_w1_z001_t001.tif", + ), + component_metadata=({"site": "1"}, {"site": "2"}), + ) + if retains_contributors + else SourceImageProvenancePlanes() + ), ).payload_with(np.zeros((4, 5), dtype=np.float32), None) request = FunctionOutputPathRequest( parser=SourceSchemaFilenameParser(), diff --git a/tests/unit/test_napari_streaming_handlers.py b/tests/unit/test_napari_streaming_handlers.py index 7d269db8ff..431342e6f1 100644 --- a/tests/unit/test_napari_streaming_handlers.py +++ b/tests/unit/test_napari_streaming_handlers.py @@ -1,14 +1,15 @@ from __future__ import annotations from dataclasses import replace +from itertools import product from pathlib import Path +from types import SimpleNamespace import numpy as np import pytest from napari.layers.shapes._shapes_constants import ShapeType - -from polystore.streaming_constants import StreamingDataType from polystore.streaming.identity import StreamProducerIdentity +from polystore.streaming_constants import StreamingDataType from zmqruntime.viewer_protocol import ViewerComponentMode from openhcs.core.artifacts import ObjectArtifactSubjectBinding @@ -16,11 +17,12 @@ NapariDisplayConfig, NapariVariableSizeHandling, ) -from openhcs.core.runtime_plane_projection import RuntimePlaneAxis from openhcs.core.runtime_image_values import ( ImagePayloadMetadata, ) +from openhcs.core.runtime_plane_projection import RuntimePlaneAxis from openhcs.core.source_spatial_domain import SourceSpatialDomain +from openhcs.core.streaming_config_factory import ViewerProcessLaunchConfig from openhcs.runtime.viewer_protocol import ( NapariLayerKind, NapariViewerServerRequest, @@ -41,36 +43,51 @@ NapariAggregateAxisBinding, NapariAggregateAxisBindingAuthority, NapariAggregateAxisBindingSet, - NapariBatchProcessorStore, NapariAxisPresentation, + NapariBatchProcessorStore, NapariComponentGroupStore, NapariDimensionLayerState, NapariImageLayerPresentationPolicy, NapariLayerBatchDebouncePolicy, - NapariPendingLayerUpdate, - NapariLayerUpdateAuthority, NapariLayerRouteStateStore, + NapariLayerUpdateAuthority, + NapariPendingLayerUpdate, NapariShapeFeatureColumns, NapariShapeLayerPayload, NapariStreamLayerAddress, NapariStreamLayerItem, ) -from openhcs.runtime.zmq_config import OPENHCS_ZMQ_CONFIG from openhcs.runtime.viewer_component_system import ( ViewerComponentAxisSemantics, ViewerComponentAxisSemanticsAuthority, + ViewerComponentCoordinateAuthority, ViewerComponentLayout, ViewerComponentMetadataNormalizer, ViewerComponentNameMetadata, ViewerComponentValueDomainPayload, - ViewerComponentCoordinateAuthority, - ViewerDisplayAxisDomain, ViewerLayerAxisProjection, ViewerLayerAxisProjectionRequest, ViewerLayerAxisProjector, ViewerMappingDisplayConfigInput, ViewerRouteComponentValueTracker, ) +from openhcs.runtime.viewer_protocol import ( + NapariLayerKind, + ViewerComponentValueOrdering, + ViewerControlMessageType, + ViewerControlResponse, + ViewerControlResponseField, + ViewerIntensityWindowControlOptions, + ViewerNavigationControlOptions, + ViewerPayloadControlOptions, + ViewerPayloadProjectionOptions, + ViewerProtocolStatus, + ViewerSettlePhase, + ViewerSettleProgress, + ViewerShapePayloadProjection, + ViewerStateControlOptions, +) +from openhcs.runtime.zmq_config import OPENHCS_ZMQ_CONFIG def _component_name_metadata(payload, context="test component metadata"): @@ -169,6 +186,7 @@ def _axis_presentation( axis_offsets: tuple[int, ...] | None = None, scalar_component_values: dict | None = None, display_axis_components: tuple[str, ...] | None = None, + routed_component_coordinates: tuple[tuple, ...] | None = None, ) -> NapariAxisPresentation: if component_values is None: component_values = {component: [1] for component in projected_axis_components} @@ -178,6 +196,15 @@ def _axis_presentation( scalar_component_values = {} if display_axis_components is None: display_axis_components = projected_axis_components + if routed_component_coordinates is None: + routed_component_coordinates = tuple( + product( + *( + component_values[component] + for component in projected_axis_components + ) + ) + ) component_axis_semantics = ViewerComponentAxisSemanticsAuthority.empty() component_layout = ViewerComponentLayout.from_parts( component_modes={ @@ -194,6 +221,7 @@ def _axis_presentation( projected_axis_components=projected_axis_components, component_values=component_values, routed_component_values=component_values, + routed_component_coordinates=routed_component_coordinates, axis_offsets=axis_offsets, scalar_component_values=scalar_component_values, ), @@ -205,13 +233,24 @@ def _axis_projection( projected_axis_components, component_values, scalar_component_values=None, + routed_component_coordinates=None, ) -> ViewerLayerAxisProjection: if scalar_component_values is None: scalar_component_values = {} + if routed_component_coordinates is None: + routed_component_coordinates = tuple( + product( + *( + component_values[component] + for component in projected_axis_components + ) + ) + ) return ViewerLayerAxisProjection( projected_axis_components=tuple(projected_axis_components), component_values=component_values, routed_component_values=component_values, + routed_component_coordinates=routed_component_coordinates, axis_offsets=tuple(0 for _ in projected_axis_components), scalar_component_values=scalar_component_values, ) @@ -247,6 +286,48 @@ def test_napari_viewer_state_projection_reports_empty_shape_payloads_as_zero(): assert summary["nonzero_count"] == 0 +def test_napari_viewer_state_projection_locates_sparse_array_payloads(): + data = np.zeros((6, 8), dtype=np.uint8) + data[1, 6] = 1 + data[4, 2] = 2 + + summary = _payload_summary( + _layer_item( + {"well": "A14", "site": 1, "channel": 1}, + data=data, + ) + ) + + assert summary["nonzero_count"] == 2 + assert summary["nonzero_min_coordinate"] == (1, 2) + assert summary["nonzero_max_coordinate"] == (4, 6) + assert summary["nonzero_example_coordinates"] == ((1, 6), (4, 2)) + + +def test_napari_viewer_state_projection_bounds_dense_coordinate_work(): + napari_viewer_server = pytest.importorskip("openhcs.runtime.napari_viewer_server") + projection = napari_viewer_server.NapariViewerStateProjection + data = np.ones( + (projection.MAX_NONZERO_COORDINATE_PROJECTION_COUNT + 1,), + dtype=np.uint8, + ) + + summary = _payload_summary( + _layer_item( + {"well": "A14", "site": 1, "channel": 1}, + data=data, + ) + ) + + assert summary["nonzero_count"] == data.size + assert "nonzero_min_coordinate" not in summary + assert "nonzero_max_coordinate" not in summary + assert "nonzero_example_coordinates" not in summary + assert "exceeds bounded coordinate projection limit" in summary[ + "nonzero_coordinate_omission_reason" + ] + + def test_napari_viewer_state_projection_reports_shape_spatial_evidence(): summary = _payload_summary( _layer_item( @@ -485,14 +566,14 @@ def test_napari_viewer_payload_projection_filters_semantic_axis_index(): presentation=_axis_presentation( layer_key=route_key, projected_axis_components=("channel",), - component_values={"channel": [1, 2]}, + component_values={"channel": [4, 7]}, ), ), ) server.component_groups.items_for(route_key).extend( ( - _layer_item({"channel": 1}, data=np.zeros((2, 2), dtype=np.uint16)), - _layer_item({"channel": 2}, data=np.ones((2, 2), dtype=np.uint16)), + _layer_item({"channel": 4}, data=np.zeros((2, 2), dtype=np.uint16)), + _layer_item({"channel": 7}, data=np.ones((2, 2), dtype=np.uint16)), ) ) @@ -512,7 +593,7 @@ def test_napari_viewer_payload_projection_filters_semantic_axis_index(): layer = payload["layers"][0] assert len(layer["payloads"]) == 1 record = layer["payloads"][0] - assert record["components"] == {"channel": 2} + assert record["components"] == {"channel": 7} assert record["axis_indices"] == (1,) @@ -785,17 +866,405 @@ def dimension_state_for(self, layer_key): class _FakeNapariServer: def __init__(self): self.layer_route_state = _FakeLayerState() + self.component_groups = NapariComponentGroupStore() self.component_name_metadata = _component_name_metadata( {"channel": {"1": "DAPI"}} ) self.component_values = ViewerRouteComponentValueTracker() - self.display_axis_domain = ViewerDisplayAxisDomain() self.transport_failure = None def bind_result_selection_layer(self, _layer): """Accept Shapes binding without modeling native Qt selection events.""" +def _intensity_window_server(route_key, presentation, items): + viewer = _FakeViewer() + layer = type( + "ImageLayer", + (), + { + "data": np.zeros((2, 2), dtype=np.float32), + "contrast_limits": (0.0, 1.0), + }, + )() + viewer.layers.append(layer) + server = type( + "Server", + (), + { + "viewer": viewer, + "layer_route_state": NapariLayerRouteStateStore.empty(), + "component_groups": NapariComponentGroupStore(), + }, + )() + server.layer_route_state.set_title(route_key, "Images") + server.layer_route_state.set_layer(route_key, layer) + server.layer_route_state.set_dimension_state( + route_key, + NapariDimensionLayerState(labels={}, presentation=presentation), + ) + server.component_groups.items_for(route_key).extend(items) + return server, layer + + +def _scalar_channel_presentation(route_key): + return _axis_presentation( + layer_key=route_key, + projected_axis_components=(), + component_values={}, + scalar_component_values={"channel": [2]}, + display_axis_components=("channel",), + ) + + +def _apply_intensity_window( + napari_viewer_server, + server, + route_key, + axis_indices, +): + return napari_viewer_server.NapariIntensityWindowControlMessageAction().handle( + server, + { + ViewerControlResponseField.PAYLOAD.value: ( + ViewerIntensityWindowControlOptions( + route_key=route_key, + axis_indices=axis_indices, + low_percentile=0.0, + high_percentile=100.0, + ) + ) + }, + ) + + +def test_napari_payload_projection_accepts_collapsed_scalar_axis_index_zero(): + napari_viewer_server = pytest.importorskip("openhcs.runtime.napari_viewer_server") + route_key = "scalar-route" + server = type( + "Server", + (), + { + "napari_window_title": "OpenHCS Napari Viewer", + "layer_route_state": NapariLayerRouteStateStore.empty(), + "component_groups": NapariComponentGroupStore(), + }, + )() + server.layer_route_state.set_title(route_key, "Images") + server.layer_route_state.set_dimension_state( + route_key, + NapariDimensionLayerState( + labels={}, + presentation=_scalar_channel_presentation(route_key), + ), + ) + server.component_groups.items_for(route_key).append( + _layer_item({"channel": 2}, data=np.array([[10.0, 20.0]])) + ) + + payload = napari_viewer_server.NapariViewerPayloadProjection( + server=server, + viewer=_FakeViewer(), + request=ViewerPayloadProjectionOptions( + controls=ViewerPayloadControlOptions.from_overrides( + route_key=route_key, + axis_indices={"channel": 0}, + ), + ), + ).to_wire_mapping() + + assert len(payload["layers"][0]["payloads"]) == 1 + assert payload["layers"][0]["payloads"][0]["components"] == {"channel": 2} + + +def test_napari_intensity_window_accepts_collapsed_scalar_axis_index_zero(): + napari_viewer_server = pytest.importorskip("openhcs.runtime.napari_viewer_server") + route_key = "scalar-route" + server, layer = _intensity_window_server( + route_key, + _scalar_channel_presentation(route_key), + (_layer_item({"channel": 2}, data=np.array([[10.0, 20.0]])),), + ) + + response = _apply_intensity_window( + napari_viewer_server, + server, + route_key, + {"channel": 0}, + ) + + assert response["status"] == "success" + assert response["matched_payload_count"] == 1 + assert response["resolved_limits"] == (10.0, 20.0) + assert layer.contrast_limits == (10.0, 20.0) + + +def test_napari_intensity_window_matches_projected_and_scalar_axis_indices(): + napari_viewer_server = pytest.importorskip("openhcs.runtime.napari_viewer_server") + route_key = "mixed-route" + server, _layer = _intensity_window_server( + route_key, + _axis_presentation( + layer_key=route_key, + projected_axis_components=("site",), + component_values={"site": [1, 2]}, + scalar_component_values={"channel": [2]}, + display_axis_components=("site", "channel"), + ), + ( + _layer_item( + {"site": 1, "channel": 2}, + data=np.array([[10.0, 20.0]]), + ), + _layer_item( + {"site": 2, "channel": 2}, + data=np.array([[30.0, 40.0]]), + ), + ), + ) + + response = _apply_intensity_window( + napari_viewer_server, + server, + route_key, + {"site": 1, "channel": 0}, + ) + + assert response["status"] == "success" + assert response["matched_payload_count"] == 1 + assert response["resolved_limits"] == (30.0, 40.0) + assert response["matched_payload_identities"][0]["components"] == { + "site": 2, + "channel": 2, + } + + +@pytest.mark.parametrize( + ("axis_indices", "message_fragment"), + ( + ({"channel": 1}, "outside the route-local extent 1"), + ( + {"unknown": 0}, + "available route-local component axes are ('channel',)", + ), + ), +) +def test_napari_intensity_window_rejects_invalid_scalar_route_axis_indices( + axis_indices, + message_fragment, +): + napari_viewer_server = pytest.importorskip("openhcs.runtime.napari_viewer_server") + route_key = "scalar-route" + server, layer = _intensity_window_server( + route_key, + _scalar_channel_presentation(route_key), + (_layer_item({"channel": 2}, data=np.array([[10.0, 20.0]])),), + ) + + response = _apply_intensity_window( + napari_viewer_server, + server, + route_key, + axis_indices, + ) + + assert response["status"] == "error" + assert message_fragment in response["message"] + assert layer.contrast_limits == (0.0, 1.0) + + +def test_napari_intensity_window_uses_matching_raw_payloads_not_sparse_padding(): + napari_viewer_server = pytest.importorskip("openhcs.runtime.napari_viewer_server") + route_key = "image-route" + viewer = _FakeViewer() + layer = type( + "ImageLayer", + (), + { + "data": np.array( + [ + [[0, 0, 0], [0, 10, 20]], + [[30, 40, 50], [60, 0, 0]], + ], + dtype=np.float32, + ), + "contrast_limits": (0.0, 1.0), + }, + )() + viewer.layers.append(layer) + server = type( + "Server", + (), + { + "viewer": viewer, + "layer_route_state": NapariLayerRouteStateStore.empty(), + "component_groups": NapariComponentGroupStore(), + }, + )() + server.layer_route_state.set_title(route_key, "Images") + server.layer_route_state.set_layer(route_key, layer) + server.layer_route_state.set_dimension_state( + route_key, + NapariDimensionLayerState( + labels={}, + presentation=_axis_presentation( + layer_key=route_key, + projected_axis_components=("well", "site"), + component_values={ + "well": ["A01", "B01", "C01"], + "site": [1, 2], + }, + routed_component_coordinates=( + ("A01", 1), + ("B01", 1), + ("C01", 2), + ), + ), + ), + ) + first = _layer_item( + {"well": "A01", "site": 1}, + data=np.array([[10.0, 20.0]]), + ) + second = _layer_item( + {"well": "B01", "site": 1}, + data=np.array([[30.0, 40.0], [50.0, 60.0]]), + ) + excluded = _layer_item( + {"well": "C01", "site": 2}, + data=np.array([[-1000.0, 1000.0]]), + ) + first = replace(first, address=replace(first.address, path="A01.tif")) + second = replace(second, address=replace(second.address, path="B01.tif")) + excluded = replace( + excluded, + address=replace(excluded.address, path="C01.tif"), + ) + server.component_groups.items_for(route_key).extend((first, second, excluded)) + + response = napari_viewer_server.NapariIntensityWindowControlMessageAction().handle( + server, + { + ViewerControlResponseField.PAYLOAD.value: ( + ViewerIntensityWindowControlOptions( + route_key=route_key, + axis_indices={"site": 0}, + low_percentile=0.0, + high_percentile=100.0, + ) + ) + }, + ) + + assert response["status"] == "success" + assert response["resolved_limits"] == (10.0, 60.0) + assert response["matched_payload_count"] == 2 + assert response["contributing_payload_count"] == 2 + assert response["contributing_pixel_count"] == 6 + assert response["axis_indices"] == {"site": 0} + assert tuple( + identity["path"] for identity in response["matched_payload_identities"] + ) == ("A01.tif", "B01.tif") + assert tuple( + identity["components"]["well"] + for identity in response["matched_payload_identities"] + ) == ("A01", "B01") + assert layer.contrast_limits == (10.0, 60.0) + + all_coordinates_response = ( + napari_viewer_server.NapariIntensityWindowControlMessageAction().handle( + server, + { + ViewerControlResponseField.PAYLOAD.value: ( + ViewerIntensityWindowControlOptions( + route_key=route_key, + low_percentile=0.0, + high_percentile=100.0, + ) + ) + }, + ) + ) + + assert all_coordinates_response["axis_indices"] == {} + assert all_coordinates_response["matched_payload_count"] == 3 + assert all_coordinates_response["contributing_pixel_count"] == 8 + assert all_coordinates_response["resolved_limits"] == (-1000.0, 1000.0) + + +@pytest.mark.parametrize( + ("items", "axis_indices", "message_fragment"), + ( + ( + (_layer_item({}, data=np.array([[np.nan, np.inf]])),), + {}, + "no finite pixel data", + ), + ( + ( + _layer_item( + {}, + data=[], + stream_layer_data_type=StreamingDataType.SHAPES, + ), + ), + {}, + "not an image route", + ), + ( + (_layer_item({}, data=np.array([[1.0, 2.0]])),), + {"unknown": 0}, + "require a route with semantic axis projection", + ), + ( + (_layer_item({}, data=np.ones((2, 2), dtype=np.float32)),), + {}, + "strictly increasing", + ), + ), +) +def test_napari_intensity_window_fails_closed( + items, + axis_indices, + message_fragment, +): + napari_viewer_server = pytest.importorskip("openhcs.runtime.napari_viewer_server") + route_key = "route" + viewer = _FakeViewer() + layer = type("Layer", (), {"contrast_limits": (0.0, 1.0)})() + viewer.layers.append(layer) + server = type( + "Server", + (), + { + "viewer": viewer, + "layer_route_state": NapariLayerRouteStateStore.empty(), + "component_groups": NapariComponentGroupStore(), + }, + )() + server.layer_route_state.set_title(route_key, "Route") + server.layer_route_state.set_layer(route_key, layer) + server.component_groups.items_for(route_key).extend(items) + + response = napari_viewer_server.NapariIntensityWindowControlMessageAction().handle( + server, + { + ViewerControlResponseField.PAYLOAD.value: ( + ViewerIntensityWindowControlOptions( + route_key=route_key, + axis_indices=axis_indices, + low_percentile=0.0, + high_percentile=100.0, + ) + ) + }, + ) + + assert response["status"] == "error" + assert message_fragment in response["message"] + assert layer.contrast_limits == (0.0, 1.0) + + def test_napari_layer_update_authority_replaces_existing_image_without_global_axis_labels(): viewer = _FakeViewer() layers = {} @@ -1322,7 +1791,7 @@ def test_napari_display_pipeline_projects_route_axes_locally(): assert second.translate() == (3.0, 0.0, 0.0, 0.0) -def test_napari_display_pipeline_aligns_derived_route_to_observed_source_domain(): +def test_napari_display_pipeline_uses_declared_domain_independent_of_arrival_order(): napari_viewer_server = pytest.importorskip("openhcs.runtime.napari_viewer_server") pipeline = napari_viewer_server.NapariLayerDisplayPipeline(_FakeNapariServer()) component_axis_semantics = ( @@ -1337,6 +1806,11 @@ def test_napari_display_pipeline_aligns_derived_route_to_observed_source_domain( ) ) + derived = pipeline.display_axis_projection( + "derived", + component_axis_semantics, + [_layer_item({"channel": 4})], + ) source = pipeline.display_axis_projection( "source", component_axis_semantics, @@ -1345,17 +1819,180 @@ def test_napari_display_pipeline_aligns_derived_route_to_observed_source_domain( _layer_item({"channel": 4}), ], ) - derived = pipeline.display_axis_projection( - "derived", - component_axis_semantics, - [_layer_item({"channel": 4})], - ) - assert source.component_values == {"channel": [1, 4]} + assert source.component_values == {"channel": [1, 2, 4]} assert source.axis_offsets == (0,) assert derived.component_values == {"channel": [4]} - assert derived.axis_offsets == (1,) - assert derived.translate() == (1.0, 0.0, 0.0) + assert derived.axis_offsets == (2,) + assert derived.translate() == (2.0, 0.0, 0.0) + + +def test_napari_display_pipeline_aligns_scalar_and_stack_routes_by_semantic_value(): + napari_viewer_server = pytest.importorskip("openhcs.runtime.napari_viewer_server") + ViewerModel = pytest.importorskip("napari.components").ViewerModel + server = _FakeNapariServer() + server.layer_route_state = NapariLayerRouteStateStore.empty() + server.viewer = ViewerModel() + pipeline = napari_viewer_server.NapariLayerDisplayPipeline(server) + + raw_route = "raw-channel-2" + raw_item = _layer_item( + {"channel": 2}, + data=np.full((4, 4), 2, dtype=np.uint16), + ) + raw_semantics = ViewerComponentAxisSemantics( + entries=_component_value_domain({"channel": [2]}).entries, + layout=ViewerComponentLayout.from_parts( + component_modes={"channel": ViewerComponentMode.STACK}, + component_order=("channel",), + ), + ) + server.layer_route_state.set_title(raw_route, "Raw channel 2") + server.component_groups.items_for(raw_route).append(raw_item) + raw_work = pipeline.display_layer_batch( + layer_key=raw_route, + items=[raw_item], + display_payload=NapariPendingLayerUpdate.from_semantics( + timer=_FakeTimer(), + data_type=StreamingDataType.IMAGE, + semantics=raw_semantics, + display_config=NapariDisplayConfig(), + ), + component_names_metadata=ViewerComponentNameMetadata.empty(), + ) + assert raw_work.advance() + assert tuple(server.layer_route_state.layer(raw_route).translate) == ( + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + ) + + stack_route = "channel-1-2-labels" + stack_items = [ + _layer_item( + {"channel": channel}, + data=np.full((4, 4), channel, dtype=np.uint16), + ) + for channel in (1, 2) + ] + stack_semantics = ViewerComponentAxisSemantics( + entries=_component_value_domain({"channel": [1, 2]}).entries, + layout=raw_semantics.layout, + ) + server.layer_route_state.set_title(stack_route, "Channel labels") + server.component_groups.items_for(stack_route).extend(stack_items) + stack_work = pipeline.display_layer_batch( + layer_key=stack_route, + items=stack_items, + display_payload=NapariPendingLayerUpdate.from_semantics( + timer=_FakeTimer(), + data_type=StreamingDataType.IMAGE, + semantics=stack_semantics, + display_config=NapariDisplayConfig(), + ), + component_names_metadata=ViewerComponentNameMetadata.empty(), + ) + assert stack_work.advance() + + raw_state = server.layer_route_state.dimension_state_for(raw_route) + stack_state = server.layer_route_state.dimension_state_for(stack_route) + assert raw_state.presentation is not None + assert stack_state.presentation is not None + assert raw_state.presentation.projection.component_values == {"channel": [2]} + assert raw_state.presentation.projection.axis_offsets == (1,) + assert stack_state.presentation.projection.component_values == {"channel": [1, 2]} + assert stack_state.presentation.projection.axis_offsets == (0,) + channel_axis = raw_state.presentation.display_axis_components.index("channel") + assert raw_state.presentation.viewer_step(0, channel_axis) == 1 + assert stack_state.presentation.viewer_step(1, channel_axis) == 1 + assert tuple(server.layer_route_state.layer(raw_route).translate) == ( + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + ) + assert tuple(server.layer_route_state.layer(stack_route).translate) == ( + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + ) + assert server.viewer.dims.nsteps == (1, 2, 1, 1, 1, 4, 4) + + +def test_napari_display_pipeline_rejects_shared_axis_expansion_requiring_rematerialization(): + napari_viewer_server = pytest.importorskip("openhcs.runtime.napari_viewer_server") + ViewerModel = pytest.importorskip("napari.components").ViewerModel + server = _FakeNapariServer() + server.layer_route_state = NapariLayerRouteStateStore.empty() + server.viewer = ViewerModel() + pipeline = napari_viewer_server.NapariLayerDisplayPipeline(server) + component_layout = ViewerComponentLayout.from_parts( + component_modes={"channel": ViewerComponentMode.STACK}, + component_order=("channel",), + ) + + sparse_route = "channels-1-3" + sparse_items = [ + _layer_item( + {"channel": channel}, + data=np.full((4, 4), channel, dtype=np.uint16), + ) + for channel in (1, 3) + ] + sparse_semantics = ViewerComponentAxisSemantics( + entries=_component_value_domain({"channel": [1, 3]}).entries, + layout=component_layout, + ) + server.layer_route_state.set_title(sparse_route, "Channels 1 and 3") + server.component_groups.items_for(sparse_route).extend(sparse_items) + sparse_work = pipeline.display_layer_batch( + layer_key=sparse_route, + items=sparse_items, + display_payload=NapariPendingLayerUpdate.from_semantics( + timer=_FakeTimer(), + data_type=StreamingDataType.IMAGE, + semantics=sparse_semantics, + display_config=NapariDisplayConfig(), + ), + component_names_metadata=ViewerComponentNameMetadata.empty(), + ) + assert sparse_work.advance() + + inserted_route = "channel-2" + inserted_item = _layer_item( + {"channel": 2}, + data=np.full((4, 4), 2, dtype=np.uint16), + ) + inserted_semantics = ViewerComponentAxisSemantics( + entries=_component_value_domain({"channel": [2]}).entries, + layout=component_layout, + ) + server.layer_route_state.set_title(inserted_route, "Channel 2") + server.component_groups.items_for(inserted_route).append(inserted_item) + + with pytest.raises(ValueError, match="requires route .* to be rematerialized"): + pipeline.display_layer_batch( + layer_key=inserted_route, + items=[inserted_item], + display_payload=NapariPendingLayerUpdate.from_semantics( + timer=_FakeTimer(), + data_type=StreamingDataType.IMAGE, + semantics=inserted_semantics, + display_config=NapariDisplayConfig(), + ), + component_names_metadata=ViewerComponentNameMetadata.empty(), + ) def test_napari_display_pipeline_projects_aggregate_payload_axes_into_route_domain(): @@ -1399,6 +2036,7 @@ def test_napari_axis_projector_validates_declared_domain_and_drops_route_singlet projection = ViewerLayerAxisProjector().project( ViewerLayerAxisProjectionRequest.from_component_values( projected_axis_components=("channel", "z_index"), + route_component_coordinates=((4, 1),), route_component_values={"channel": [4], "z_index": [1]}, viewer_component_values={"channel": [4], "z_index": [1]}, declared_component_values={ @@ -1424,6 +2062,7 @@ def test_napari_axis_projector_rejects_missing_declared_singleton_component(): ViewerLayerAxisProjector().project( ViewerLayerAxisProjectionRequest.from_component_values( projected_axis_components=("timepoint", "well", "channel"), + route_component_coordinates=(), route_component_values={ "timepoint": [], "well": ["A01"], @@ -1452,6 +2091,7 @@ def test_napari_axis_projector_rejects_missing_empty_declared_component(): ViewerLayerAxisProjector().project( ViewerLayerAxisProjectionRequest.from_component_values( projected_axis_components=("timepoint", "well", "channel"), + route_component_coordinates=(), route_component_values={ "timepoint": [], "well": ["A01"], @@ -1480,6 +2120,7 @@ def test_napari_axis_projector_rejects_missing_non_singleton_component(): ViewerLayerAxisProjector().project( ViewerLayerAxisProjectionRequest.from_component_values( projected_axis_components=("timepoint", "channel"), + route_component_coordinates=(), route_component_values={"timepoint": [], "channel": [1]}, viewer_component_values={"timepoint": [], "channel": [1]}, declared_component_values={"timepoint": [1, 2], "channel": [1]}, @@ -1493,6 +2134,7 @@ def test_napari_axis_projector_keeps_singleton_route_in_shared_viewer_domain(): projection = ViewerLayerAxisProjector().project( ViewerLayerAxisProjectionRequest.from_component_values( projected_axis_components=("site", "channel"), + route_component_coordinates=((1, 4), (2, 4)), route_component_values={"site": [1, 2], "channel": [4]}, viewer_component_values={"site": [1, 2], "channel": [1, 2, 3, 4, 5]}, declared_component_values={"site": [1, 2], "channel": [1, 2, 3, 4, 5]}, @@ -1512,6 +2154,7 @@ def test_napari_axis_projector_preserves_route_offset_in_shared_viewer_domain(): projection = ViewerLayerAxisProjector().project( ViewerLayerAxisProjectionRequest.from_component_values( projected_axis_components=("site", "channel"), + route_component_coordinates=((1, 4), (1, 5), (2, 4), (2, 5)), route_component_values={"site": [1, 2], "channel": [4, 5]}, viewer_component_values={"site": [1, 2], "channel": [1, 2, 3, 4, 5]}, declared_component_values={"site": [1, 2], "channel": [1, 2, 3, 4, 5]}, @@ -1530,6 +2173,7 @@ def test_napari_axis_projector_uses_route_domain_for_noncontiguous_routes(): projection = ViewerLayerAxisProjector().project( ViewerLayerAxisProjectionRequest.from_component_values( projected_axis_components=("channel",), + route_component_coordinates=((1,), (3,)), route_component_values={"channel": [1, 3]}, viewer_component_values={"channel": [1, 3]}, declared_component_values={"channel": [1, 2, 3, 4, 5]}, @@ -1549,6 +2193,7 @@ def test_napari_axis_projector_keeps_route_domain_for_noncontiguous_shared_axis( projection = ViewerLayerAxisProjector().project( ViewerLayerAxisProjectionRequest.from_component_values( projected_axis_components=("channel",), + route_component_coordinates=((1,), (2,), (3,), (5,)), route_component_values={"channel": [1, 2, 3, 5]}, viewer_component_values={"channel": [1, 2, 3, 4, 5]}, declared_component_values={"channel": [1, 2, 3, 4, 5]}, @@ -1569,6 +2214,7 @@ def test_napari_axis_projector_requires_declared_domain(): ViewerLayerAxisProjector().project( ViewerLayerAxisProjectionRequest.from_component_values( projected_axis_components=("channel",), + route_component_coordinates=((4,),), route_component_values={"channel": [4]}, viewer_component_values={"channel": [4]}, declared_component_values={}, @@ -2522,11 +3168,6 @@ def stop(self): server.component_groups.items_for("old").append(_layer_item({"well": "A14"})) server.component_values = ViewerRouteComponentValueTracker() server.component_values.update("old", ["well"], [_layer_item({"well": "A14"})]) - server.display_axis_domain = ViewerDisplayAxisDomain() - server.display_axis_domain.record_display_axis_values( - ["well"], - [_layer_item({"well": "A14"})], - ) server.component_name_metadata = _component_name_metadata({"well": {"A14": "A14"}}) server.layer_batch_processor_debounce_policy = NapariLayerBatchDebouncePolicy( delay_ms=123 @@ -2542,7 +3183,6 @@ def stop(self): assert server.component_values.values_for(("old", ("well",)), ["well"]) == { "well": [] } - assert server.display_axis_domain.display_axis_values_for(["well"]) == {"well": []} assert server.component_name_metadata.to_wire_mapping() == {} assert server.batch_processors.debounce_policy.delay_ms == 123 assert pending_timer.stopped is True @@ -2758,6 +3398,9 @@ def resize(width, height): monkeypatch.setattr(napari_viewer_server, "QTimer", FakeTimer) class FakeQtEnvironmentPolicy: + def __init__(self, *, font_dpi=None): + events.append(("qt_environment_policy", font_dpi)) + @staticmethod def apply_to(_environment): events.append("qt_environment_applied") @@ -2922,11 +3565,13 @@ def test_napari_runtime_launch_carries_the_projected_scope_accent(): log_file=Path("/tmp/napari-6200.log") ) - assert arguments.expressions[-1].source == "'#1464c8'" + assert arguments.expressions[-2].source == "'#1464c8'" + assert arguments.expressions[-1].source == "None" def test_napari_roi_manager_selects_authoritative_shapes_members(qtbot): from napari.components import ViewerModel + from openhcs.napari_roi_manager import QRoiManager viewer = ViewerModel() @@ -3065,12 +3710,9 @@ def test_declared_object_subject_selects_all_neuron_paths_and_metrics_row( ), ) - graph_layer.selected_data = {1} - qtbot.waitUntil( - lambda: graph_layer.selected_data == {0, 1} - and metrics_layer.selected_data == {0}, - timeout=2_000, - ) + server.result_selection_controller.select_result_element(graph_layer, 1) + assert graph_layer.selected_data == {0, 1} + assert metrics_layer.selected_data == {0} server.result_selection_controller.set_result_group_color( graph_layer, (1.0, 0.5, 0.0, 1.0), @@ -3101,6 +3743,7 @@ def test_roi_manager_selection_reveals_3d_roi_on_its_exact_slice(qtbot, monkeypa napari_viewer_server = pytest.importorskip("openhcs.runtime.napari_viewer_server") from napari.components import ViewerModel from napari.settings import get_settings + from openhcs.napari_roi_manager import QRoiManager settings = get_settings() @@ -3516,6 +4159,9 @@ def test_napari_control_dispatch_registry_is_module_local_and_eager(): assert registry[ViewerControlMessageType.CLEAR_STATE.value] is ( napari_viewer_server.NapariClearStateControlMessageAction ) + assert registry[ViewerControlMessageType.APPLY_INTENSITY_WINDOW.value] is ( + napari_viewer_server.NapariIntensityWindowControlMessageAction + ) def test_napari_endpoint_lifecycle_capabilities_derive_from_registered_actions(): @@ -3537,23 +4183,17 @@ def test_napari_endpoint_lifecycle_capabilities_derive_from_registered_actions() assert server._create_pong_response().control_capabilities == expected -def test_napari_endpoint_lifecycle_capabilities_derive_from_registered_actions(): +def test_napari_process_launch_action_reports_immutable_declaration(): napari_viewer_server = pytest.importorskip("openhcs.runtime.napari_viewer_server") - from zmqruntime.messages import EndpointControlCapability + process_launch = ViewerProcessLaunchConfig(qt_font_dpi=96) - expected = frozenset(EndpointControlCapability) - assert ( - napari_viewer_server.NapariControlMessageAction.endpoint_control_capabilities() - == expected - ) - server = napari_viewer_server.NapariViewerServer( - NapariViewerServerRequest( - port=54321, - viewer_title="lifecycle capability test", - ) + response = napari_viewer_server.NapariProcessLaunchControlMessageAction().handle( + SimpleNamespace(process_launch=process_launch), + {}, ) - assert server._create_pong_response().control_capabilities == expected + assert response["status"] == "success" + assert response["process_launch"] == process_launch.to_wire_mapping() def test_napari_axis_projector_drops_only_globally_singleton_axes(): @@ -3575,6 +4215,15 @@ def test_napari_axis_projector_drops_only_globally_singleton_axes(): "z_index", "well", ), + route_component_coordinates=tuple( + product( + component_values["site"], + component_values["timepoint"], + component_values["channel"], + component_values["z_index"], + component_values["well"], + ) + ), route_component_values=component_values, viewer_component_values=component_values, declared_component_values=component_values, @@ -3660,6 +4309,75 @@ def test_napari_layer_title_authority_uses_stream_display_name_policy(): assert title == "9. ConvertObjectsToImage NucleiObjects3D well A01 ROIs" +def test_napari_component_display_coordinator_purges_deleted_route_domain(): + napari_viewer_server = pytest.importorskip("openhcs.runtime.napari_viewer_server") + + class _FakeServer: + def __init__(self): + self.viewer = _FakeViewer() + self.layer_route_state = NapariLayerRouteStateStore.empty() + self.component_groups = NapariComponentGroupStore() + self.component_values = ViewerRouteComponentValueTracker() + + server = _FakeServer() + route_key = "deleted-channel-1" + deleted_layer = object() + server.layer_route_state.set_title(route_key, "Deleted channel 1") + server.layer_route_state.set_layer(route_key, deleted_layer) + server.component_groups.items_for(route_key).append( + _layer_item({"channel": 1}) + ) + server.component_values.update( + route_key, + ["channel"], + server.component_groups.items_for(route_key), + ) + server.component_values.declare_component_values( + route_key, + ["channel"], + {"channel": [1]}, + ) + + napari_viewer_server.NapariComponentAwareDisplayCoordinator._reconcile_deleted_layers( + server + ) + + assert not server.layer_route_state.has_layer(route_key) + assert server.component_groups.existing_items_for(route_key) is None + assert server.component_values.shared_values_for(["channel"]) == {"channel": []} + + +def test_napari_component_display_coordinator_clears_replaced_route_domain(): + napari_viewer_server = pytest.importorskip("openhcs.runtime.napari_viewer_server") + + class _FakeServer: + replace_layers = True + + def __init__(self): + self.component_groups = NapariComponentGroupStore() + self.component_values = ViewerRouteComponentValueTracker() + + server = _FakeServer() + route_key = "replaced-channel" + group = server.component_groups.items_for(route_key) + group.append(_layer_item({"channel": 1})) + server.component_values.update(route_key, ["channel"], group) + server.component_values.declare_component_values( + route_key, + ["channel"], + {"channel": [1]}, + ) + + napari_viewer_server.NapariComponentAwareDisplayCoordinator._clear_group_for_replace( + server, + route_key, + group, + ) + + assert group == [] + assert server.component_values.shared_values_for(["channel"]) == {"channel": []} + + def test_napari_component_display_coordinator_splits_declared_image_layouts(): napari_viewer_server = pytest.importorskip("openhcs.runtime.napari_viewer_server") @@ -4391,6 +5109,86 @@ def test_napari_image_stack_builder_preserves_route_local_collapsed_channels(): assert np.all(image[1] == 2) +def test_napari_image_stack_builder_preserves_sparse_routed_component_pairs(): + napari_viewer_server = pytest.importorskip("openhcs.runtime.napari_viewer_server") + component_values = { + "well": ["A02", "B04", "B12", "B17"], + "site": [1, 2, 4, 7], + } + routed_coordinates = ( + ("A02", 1), + ("B04", 4), + ("B12", 2), + ("B17", 7), + ) + + image = napari_viewer_server._build_nd_image_array( + [ + _layer_item( + {"well": well, "site": site}, + data=np.full((2, 2), value, dtype=np.uint16), + ) + for value, (well, site) in enumerate(routed_coordinates, start=1) + ], + _axis_projection( + ["well", "site"], + component_values, + routed_component_coordinates=routed_coordinates, + ), + ) + + assert image.shape == (4, 4, 2, 2) + assert np.count_nonzero(np.any(image != 0, axis=(-2, -1))) == 4 + assert np.all(image[0, 0] == 1) + assert np.all(image[1, 2] == 2) + assert np.all(image[2, 1] == 3) + assert np.all(image[3, 3] == 4) + + +def test_napari_display_projection_derives_sparse_coordinates_from_routed_items(): + napari_viewer_server = pytest.importorskip("openhcs.runtime.napari_viewer_server") + pipeline = napari_viewer_server.NapariLayerDisplayPipeline(_FakeNapariServer()) + component_values = { + "well": ["A02", "B04", "B12", "B17"], + "site": [1, 2, 4, 7], + } + component_axis_semantics = ( + ViewerComponentAxisSemanticsAuthority.from_display_config( + ViewerMappingDisplayConfigInput( + { + "component_modes": {"well": "stack", "site": "stack"}, + "component_order": ["well", "site"], + } + ), + _component_value_domain(component_values), + ) + ) + + projection = pipeline.display_axis_projection( + "sparse-fields", + component_axis_semantics, + [ + _layer_item({"well": "A02", "site": 1}), + _layer_item({"well": "B04", "site": 4}), + _layer_item({"well": "B12", "site": 2}), + _layer_item({"well": "B17", "site": 7}), + ], + ) + + assert projection.routed_component_coordinates == ( + ("A02", 1), + ("B04", 4), + ("B12", 2), + ("B17", 7), + ) + assert projection.expected_indices() == { + (0, 0), + (1, 2), + (2, 1), + (3, 3), + } + + def test_napari_image_stack_builder_consumes_aggregate_payload_axis_as_stack_component(): napari_viewer_server = pytest.importorskip("openhcs.runtime.napari_viewer_server") @@ -4468,48 +5266,52 @@ def test_napari_component_value_tracker_tracks_observed_axis_values_by_route(): assert tracker.values_for(("main", ("site",)), ["site"]) == {"site": []} -def test_napari_display_axis_domain_tracks_shared_active_axis_values(): - domain = ViewerDisplayAxisDomain() - projected_axis_components = ["site", "timepoint", "channel", "z_index", "well"] - - domain.record_display_axis_values( - projected_axis_components, - [ - _layer_item( - { - "site": site, - "timepoint": 1, - "channel": channel, - "z_index": 1, - "well": "A01", - } - ) - for site in [1, 2] - for channel in [1, 2, 3, 4, 5] - ], +def test_napari_component_value_tracker_derives_shared_domain_without_merging_routes(): + tracker = ViewerRouteComponentValueTracker() + tracker.update("raw", ["channel"], [_layer_item({"channel": 2})]) + tracker.declare_component_values("raw", ["channel"], {"channel": [2]}) + tracker.update( + "labels", + ["channel"], + [_layer_item({"channel": 1}), _layer_item({"channel": 2})], ) - domain.record_display_axis_values( - projected_axis_components, - [ - _layer_item( - { - "site": 1, - "timepoint": 1, - "channel": 1, - "z_index": 1, - "well": "A01", - } - ) - ], + tracker.declare_component_values( + "labels", + ["channel"], + {"channel": [1, 2]}, ) - assert domain.display_axis_values_for(projected_axis_components) == { - "site": [1, 2], - "timepoint": [1], - "channel": [1, 2, 3, 4, 5], - "z_index": [1], - "well": ["A01"], - } + assert tracker.shared_values_for(["channel"]) == {"channel": [1, 2]} + assert tracker.values_for(("raw", ("channel",)), ["channel"]) == {"channel": [2]} + + +def test_napari_component_value_tracker_replaces_current_route_domain_exactly(): + tracker = ViewerRouteComponentValueTracker() + tracker.update( + "raw", + ["channel"], + [_layer_item({"channel": 1}), _layer_item({"channel": 2})], + ) + tracker.declare_component_values("raw", ["channel"], {"channel": [1, 2]}) + + tracker.update("raw", ["channel"], [_layer_item({"channel": 2})]) + tracker.declare_component_values("raw", ["channel"], {"channel": [2]}) + + assert tracker.values_for(("raw", ("channel",)), ["channel"]) == {"channel": [2]} + assert tracker.shared_values_for(["channel"]) == {"channel": [2]} + + +def test_napari_component_value_tracker_purges_retired_route_domain(): + tracker = ViewerRouteComponentValueTracker() + tracker.update("raw", ["channel"], [_layer_item({"channel": 1})]) + tracker.declare_component_values("raw", ["channel"], {"channel": [1]}) + tracker.update("labels", ["channel"], [_layer_item({"channel": 2})]) + tracker.declare_component_values("labels", ["channel"], {"channel": [2]}) + + tracker.purge("raw") + + assert tracker.values_for(("raw", ("channel",)), ["channel"]) == {"channel": []} + assert tracker.shared_values_for(["channel"]) == {"channel": [2]} def test_viewer_component_value_ordering_sorts_unpadded_indices_numerically(): diff --git a/tests/unit/test_orchestrator_lane_planning.py b/tests/unit/test_orchestrator_lane_planning.py index 5d58aa4a7d..b26ec32794 100644 --- a/tests/unit/test_orchestrator_lane_planning.py +++ b/tests/unit/test_orchestrator_lane_planning.py @@ -1274,7 +1274,7 @@ def test_persistent_execution_viewer_is_settled_without_capture_or_cleanup(): stop_execution_visualizers([persistent]) assert viewer_states == {} - assert events == [] + assert events == ["settle"] def test_execution_visualizer_readiness_timeout_is_fatal(monkeypatch): diff --git a/tests/unit/test_persisted_semantic_metadata.py b/tests/unit/test_persisted_semantic_metadata.py index e761b9f63e..9dd251927c 100644 --- a/tests/unit/test_persisted_semantic_metadata.py +++ b/tests/unit/test_persisted_semantic_metadata.py @@ -10,6 +10,7 @@ from polystore.virtual_workspace import SourcePixelRef from openhcs.constants.constants import AllComponents +from openhcs.core.artifacts import ImageArtifactType from openhcs.core.runtime_image_values import ( ImageMetadataPayload, ImagePayloadMetadata, @@ -23,7 +24,9 @@ ) from openhcs.core.source_projection import ( OpenHCSPlaneAddress, + SourceArtifactProjection, SourcePlaneProjection, + SourceProjectionMetadataSerializer, SourceProjectionSet, ) from openhcs.core.source_workspace_projection import ( @@ -131,6 +134,50 @@ def test_source_projection_serialization_decodes_typed_image_metadata() -> None: assert projection.image_metadata == _collapsed_metadata() +def test_image_artifact_projection_round_trips_typed_pixel_metadata() -> None: + metadata = ImagePayloadMetadata( + source_component_metadata={ + "well": "A01", + "site": "1", + "channel": "2", + "z_index": "1", + "timepoint": "1", + }, + source_dtype="uint8", + ) + projection = SourceArtifactProjection( + address=OpenHCSPlaneAddress.from_values("A01", 1, 2, 1, 1), + ref=SourcePixelRef("disk", "analysis/A01_candidate.checkpoint.tif"), + source_alias="neurite_candidate_mask", + artifact_kind=ImageArtifactType, + source_metadata=metadata.source_component_metadata, + image_metadata=metadata, + ) + virtual_path = "analysis/A01_candidate.checkpoint.tif" + projection_set = SourceProjectionSet((projection,)) + subdirectory = SourceProjectionMetadataSerializer( + SourceSchemaFilenameParser() + ).metadata_dict( + projection_set, + microscope_handler_name="openhcs", + source_filename_parser_name="SourceSchemaFilenameParser", + grid_dimensions=[1, 1], + pixel_size=1.0, + projection_paths=((projection, virtual_path),), + ) + document = json.loads(json.dumps({"subdirectories": {"analysis": subdirectory}})) + + restored = VirtualWorkspaceSourceProjection.from_openhcs_metadata( + Path("/plate"), document + ).require_source_projection_for( + VirtualWorkspacePathLookup.from_paths(virtual_path, virtual_path) + ) + + assert restored.source_alias == "neurite_candidate_mask" + assert restored.artifact_kind is ImageArtifactType + assert restored.image_metadata == metadata + + def test_legacy_projection_replay_uses_complete_top_level_source_metadata() -> None: document = _serialized_metadata(None) workspace = VirtualWorkspaceSourceProjection.from_openhcs_metadata( diff --git a/tests/unit/test_plate_image_inventory.py b/tests/unit/test_plate_image_inventory.py index ce4e1d0317..5fc0606800 100644 --- a/tests/unit/test_plate_image_inventory.py +++ b/tests/unit/test_plate_image_inventory.py @@ -15,8 +15,10 @@ from openhcs.core.plate_image_inventory import ( PlateFileInventory, PlateFileRecord, + PlateFileRecordAmbiguityError, PlateImageRecord, PlateImageInventory, + PlateResultFileRecord, PlateResultFileInventory, PlateResultFilePreviewReader, ) @@ -203,3 +205,44 @@ def test_unified_image_record_preserves_declared_source_reference(): ) ) assert unified.require_image_source_ref() is source_ref + + +def test_stream_record_uses_declared_address_for_dual_image_result_projection(): + relative_path = "images_results/A01_objects_step1.labels.tif" + full_path = f"/plate/{relative_path}" + inventory = PlateFileInventory( + plate_path=Path("/plate"), + image_records=( + PlateImageRecord( + virtual_path=relative_path, + full_virtual_path=full_path, + backend=Backend.VIRTUAL_WORKSPACE.value, + source_path=full_path, + source_ref=SourcePixelRef( + backend=Backend.DISK.value, + backend_address=relative_path, + ), + ), + ), + result_records=( + PlateResultFileRecord( + relative_path=relative_path, + full_path=full_path, + file_format=FileFormat.TIFF, + source_ref=SourcePixelRef( + backend=Backend.DISK.value, + backend_address=full_path, + ), + ), + ), + ) + + with pytest.raises(PlateFileRecordAmbiguityError) as error: + inventory.require_file_record(relative_path) + + assert {record.kind for record in error.value.records} == { + PlateFileKind.IMAGE, + PlateFileKind.RESULT, + } + assert inventory.require_stream_record(relative_path).kind is PlateFileKind.IMAGE + assert inventory.require_stream_record(full_path).kind is PlateFileKind.RESULT diff --git a/tests/unit/test_stream_component_semantics.py b/tests/unit/test_stream_component_semantics.py index 1fe47d49c6..d65078b4ab 100644 --- a/tests/unit/test_stream_component_semantics.py +++ b/tests/unit/test_stream_component_semantics.py @@ -121,6 +121,31 @@ def test_stream_viewer_component_metadata_projector_requires_source_metadata(): projector.project_required(index=3, metadata=None) +def test_stream_route_metadata_excludes_payload_local_plane_component() -> None: + projector = StreamViewerComponentMetadataProjector.for_item_fields( + ("well", "site", "channel", "z_index", "timepoint"), + { + "plane_axis": RuntimePlaneAxis.RUNTIME_SLICE.value, + "plane_component_values": {"channel": ("1", "2")}, + }, + ) + + assert projector.project_required( + index=0, + metadata={ + "well": "A49", + "site": "1", + "z_index": "1", + "timepoint": "1", + }, + ) == { + "well": "A49", + "site": 1, + "z_index": 1, + "timepoint": 1, + } + + @pytest.mark.parametrize("well", (1, "1", "A01")) def test_stream_source_declared_domains_reuse_route_component_projection(well): source_metadata = StreamSourceComponentMetadataItems.from_values( diff --git a/tests/unit/test_streaming_service.py b/tests/unit/test_streaming_service.py index e070dd32d8..dcb1be425a 100644 --- a/tests/unit/test_streaming_service.py +++ b/tests/unit/test_streaming_service.py @@ -2,15 +2,23 @@ from dataclasses import replace from pathlib import Path +from types import MappingProxyType from types import SimpleNamespace -import pytest import numpy as np -from polystore.streaming.viewer_transport import ViewerStreamKwarg +import pytest +from polystore.streaming.identity import ( + FixedStreamProducerIdentityKind, + StreamProducerIdentity, +) +from polystore.streaming.viewer_transport import ViewerStreamKwarg, ViewerStreamProducer +from polystore.virtual_workspace import SourcePixelRef from polystore.zmq_config import POLYSTORE_ZMQ_CONFIG -from zmqruntime.viewer_protocol import ViewerBatchWireField +from zmqruntime.viewer_protocol import ViewerBatchWireField, ViewerWireField from openhcs.constants.constants import AllComponents +from openhcs.core.artifacts import ObjectLabelsArtifactType +from openhcs.core.component_group_scope import RuntimeExecutionAxisScope from openhcs.core.components.parser_metaprogramming import FilenameParseResult from openhcs.core.config import ( FijiDimensionMode, @@ -22,9 +30,18 @@ StreamingConfig, get_all_streaming_ports, ) +from openhcs.core.runtime_image_values import ImagePayloadMetadata +from openhcs.core.runtime_plane_projection import RuntimePlaneAxis +from openhcs.core.source_image_provenance import SourceImageProvenancePlanes +from openhcs.core.source_metadata import SourceVoxelSpacing +from openhcs.core.source_projection import SourceArtifactProjection +from openhcs.core.source_spatial_domain import SourceSpatialDomain +from openhcs.core.source_workspace_projection import VirtualWorkspaceSourceProjection from openhcs.core.streaming_config_declarations import ViewerType +from openhcs.core.streaming_config_factory import ViewerProcessLaunchConfig from openhcs.core.viewer_streaming_service import ( ImageStreamingRequest, + ManualImageStreamProjectionIdentity, RoiStreamingRequest, StreamingService, StreamingViewerLifecycle, @@ -34,6 +51,8 @@ from openhcs.runtime.viewer_protocol import ( DetachedViewerLaunchFailure, DetachedViewerServerEntrypointSpec, + ViewerControlMessageRequest, + ViewerControlResponse, ViewerLaunchContext, ) from openhcs.runtime.zmq_config import OPENHCS_ZMQ_CONFIG @@ -95,6 +114,10 @@ def get_component_values( ) -> dict[str, str]: return {} + def get_pixel_size(self, plate_path) -> float: + del plate_path + return 1.3556 + def filename_parse_result(*, channel: int = 1) -> FilenameParseResult: values = { @@ -130,6 +153,44 @@ def test_streaming_config_separates_registry_key_from_viewer_identity() -> None: assert NapariStreamingConfig().display_name == "Napari" +def test_napari_streaming_config_owns_process_launch_projection() -> None: + assert NapariStreamingConfig( + font_dpi=96 + ).viewer_runtime_config().process_launch == ViewerProcessLaunchConfig( + qt_font_dpi=96 + ) + assert ( + FijiStreamingConfig().viewer_runtime_config().process_launch + == ViewerProcessLaunchConfig() + ) + + +def test_napari_viewer_reuse_requires_matching_process_launch(monkeypatch) -> None: + visualizer = NapariStreamVisualizer( + filemanager=FakeFileManager(), + runtime_config=NapariStreamingConfig( + enabled=True, + font_dpi=96, + ).viewer_runtime_config(), + ) + active_launch = ViewerProcessLaunchConfig(qt_font_dpi=96) + + monkeypatch.setattr( + ViewerControlMessageRequest, + "send", + lambda _request: ViewerControlResponse( + { + "status": "success", + "process_launch": active_launch.to_wire_mapping(), + } + ), + ) + assert visualizer.existing_viewer_matches_process_launch() + + active_launch = ViewerProcessLaunchConfig(qt_font_dpi=120) + assert not visualizer.existing_viewer_matches_process_launch() + + @pytest.mark.parametrize("config", (GlobalPipelineConfig(), PipelineConfig())) def test_all_streaming_ports_read_declared_registry_fields(config) -> None: ports = get_all_streaming_ports(config, num_ports_per_type=1) @@ -243,7 +304,12 @@ def test_stream_images_uses_resolved_config_backend_not_viewer_name( "origin": "manual", "output_kind": "manual", "output_key": "selected_images", - "projection_key": "selected_images", + "projection_key": ManualImageStreamProjectionIdentity( + plate_path="/plate", + filenames=("A01/img.tif",), + ) + .producer_identity() + .projection_key, "step_name": None, "pipeline_position": None, "step_scope_id": None, @@ -252,6 +318,26 @@ def test_stream_images_uses_resolved_config_backend_not_viewer_name( } +def test_manual_image_projection_identity_separates_independent_selections() -> None: + first = ManualImageStreamProjectionIdentity( + plate_path="/plate", + filenames=("A60/channel-1.tif", "A60/channel-2.tif"), + ).producer_identity() + reordered = ManualImageStreamProjectionIdentity( + plate_path="/plate", + filenames=("A60/channel-2.tif", "A60/channel-1.tif"), + ).producer_identity() + second = ManualImageStreamProjectionIdentity( + plate_path="/plate", + filenames=("A03/channel-1.tif",), + ).producer_identity() + + assert first.output_key == second.output_key == "selected_images" + assert first.projection_key == reordered.projection_key + assert first.projection_key != second.projection_key + assert first.route_parts() != second.route_parts() + + def test_stream_images_reports_success_only_after_viewer_state_is_settled() -> None: events: list[str] = [] @@ -446,6 +532,113 @@ def physical_source_path( } +def test_stream_images_routes_aggregate_channel_through_payload_plane_axis( + tmp_path: Path, +) -> None: + path = tmp_path / "aggregate.labels.tif" + expected = np.arange(2 * 8 * 9, dtype=np.int32).reshape(2, 8, 9) + + class AggregateFileManager(FakeFileManager): + def load(self, path: str, read_backend: str) -> np.ndarray: + assert path == str(tmp_path / "aggregate.labels.tif") + assert read_backend == "disk" + return expected + + def source_path( + self, + address: str, + backend: str, + *, + base_path: str | Path, + ) -> str: + del backend, base_path + return address + + source_metadata = MappingProxyType( + { + "well": "A49", + "site": "1", + "z_index": "1", + "timepoint": "1", + "source_alias": "neurite_outgrowth", + "source_artifact_type": "object_labels", + } + ) + image_metadata = ImagePayloadMetadata( + source_spatial_domain=SourceSpatialDomain((0, 0), (8, 9)), + source_image_provenance_planes=SourceImageProvenancePlanes.from_components( + paths=("/source/channel-1.tif", "/source/channel-2.tif"), + component_metadata=( + {**source_metadata, "channel": "1"}, + {**source_metadata, "channel": "2"}, + ), + ), + source_dtype="int32", + plane_axis=RuntimePlaneAxis.RUNTIME_SLICE, + ) + projection = SourceArtifactProjection( + address=None, + ref=SourcePixelRef(backend="disk", backend_address=str(path)), + source_alias="neurite_outgrowth", + artifact_kind=ObjectLabelsArtifactType, + source_metadata=source_metadata, + image_metadata=image_metadata, + execution_scope=RuntimeExecutionAxisScope.from_raw( + "A49", + component=None, + value=None, + fixed_component_values=(("z_index", "1"), ("timepoint", "1")), + ), + ) + workspace_projection = VirtualWorkspaceSourceProjection( + source_refs_by_virtual_path=MappingProxyType({path.name: projection.ref}), + source_metadata_by_path=MappingProxyType({path.name: source_metadata}), + workspace_root=str(tmp_path), + source_projections_by_virtual_path=MappingProxyType( + {path.name: projection} + ), + ) + filemanager = AggregateFileManager() + service = StreamingService( + filemanager=filemanager, + microscope_handler=SimpleNamespace( + parser=SimpleNamespace(parse_filename=lambda _filename: None), + metadata_handler=FakeMetadataHandler(), + ), + plate_path=tmp_path, + ) + + service.stream_images( + ImageStreamingRequest( + viewer=FakeViewer(), + config=NapariStreamingConfig(enabled=True), + status_callback=lambda _status: None, + error_callback=lambda error: (_ for _ in ()).throw(AssertionError(error)), + filenames=(path.name,), + read_backend="disk", + source_projection=workspace_projection, + ) + ) + + assert len(filemanager.saved_batches) == 1 + _data, _paths, _backend, kwargs = filemanager.saved_batches[0] + stream_request = kwargs[ViewerStreamKwarg.STREAM_REQUEST.value] + assert stream_request.source.item_fields["plane_component_values"] == { + "channel": ["1", "2"] + } + assert stream_request.source.metadata.metadata_by_path == { + path.name: { + "well": "A49", + "site": 1, + "z_index": 1, + "timepoint": 1, + } + } + assert stream_request.message_extra[ + ViewerBatchWireField.COMPONENT_VALUE_DOMAIN.value + ]["channel"] == [1, 2] + + def test_stream_images_does_not_report_success_when_viewer_settlement_fails() -> None: statuses: list[str] = [] viewer = FakeViewer(settlement_succeeds=False) @@ -589,6 +782,112 @@ def test_stream_rois_uses_explicit_component_metadata(monkeypatch) -> None: "z_index": 1, "timepoint": 1, } + image_metadata = ImagePayloadMetadata.from_viewer_image_metadata( + stream_request.source.item_fields[ViewerWireField.IMAGE_METADATA.value] + ) + assert image_metadata.source_voxel_spacing == SourceVoxelSpacing((1.3556, 1.3556)) + + +def test_stream_rois_preserves_per_artifact_producer_identities(monkeypatch) -> None: + monkeypatch.setattr( + "polystore.roi.load_rois_from_zip", + lambda _path: [object()], + ) + filemanager = FakeFileManager() + config = FijiStreamingConfig(enabled=True) + roi_paths = ( + "/output/results/A01_bodies.roi.zip", + "/output/results/A01_neurites.roi.zip", + ) + service = StreamingService( + filemanager=filemanager, + microscope_handler=SimpleNamespace(metadata_handler=FakeMetadataHandler()), + plate_path=Path("/plate"), + ) + producer_identities = tuple( + StreamProducerIdentity.fixed_output( + FixedStreamProducerIdentityKind.MANUAL, + artifact_key, + ) + for artifact_key in ("A01_bodies", "A01_neurites") + ) + + service.stream_rois( + RoiStreamingRequest( + viewer=FakeViewer(), + config=config, + status_callback=lambda _status: None, + error_callback=lambda error: (_ for _ in ()).throw(AssertionError(error)), + roi_filenames=roi_paths, + component_metadata_by_path={ + path: { + "well": "A01", + "site": 1, + "channel": 2, + "z_index": 1, + "timepoint": 1, + } + for path in roi_paths + }, + producer=ViewerStreamProducer.from_identities(producer_identities), + ) + ) + + _data, _paths, _backend, metadata = filemanager.saved_batches[0] + stream_request = metadata[ViewerStreamKwarg.STREAM_REQUEST.value] + assert stream_request.producer.identities == producer_identities + + +def test_stream_rois_keeps_producer_identity_aligned_when_archive_is_empty( + monkeypatch, +) -> None: + roi_paths = ( + "/output/results/A01_empty.roi.zip", + "/output/results/A01_bodies.roi.zip", + ) + monkeypatch.setattr( + "polystore.roi.load_rois_from_zip", + lambda path: [] if str(path).endswith("A01_empty.roi.zip") else [object()], + ) + filemanager = FakeFileManager() + producer_identities = tuple( + StreamProducerIdentity.fixed_output( + FixedStreamProducerIdentityKind.MANUAL, + artifact_key, + ) + for artifact_key in ("A01_empty", "A01_bodies") + ) + service = StreamingService( + filemanager=filemanager, + microscope_handler=SimpleNamespace(metadata_handler=FakeMetadataHandler()), + plate_path=Path("/plate"), + ) + + service.stream_rois( + RoiStreamingRequest( + viewer=FakeViewer(), + config=FijiStreamingConfig(enabled=True), + status_callback=lambda _status: None, + error_callback=lambda error: (_ for _ in ()).throw(AssertionError(error)), + roi_filenames=roi_paths, + component_metadata_by_path={ + path: { + "well": "A01", + "site": 1, + "channel": 2, + "z_index": 1, + "timepoint": 1, + } + for path in roi_paths + }, + producer=ViewerStreamProducer.from_identities(producer_identities), + ) + ) + + _data, paths, _backend, metadata = filemanager.saved_batches[0] + stream_request = metadata[ViewerStreamKwarg.STREAM_REQUEST.value] + assert paths == [roi_paths[1]] + assert stream_request.producer.identities == (producer_identities[1],) def test_stream_rois_rejects_unresolved_source_plane_metadata() -> None: diff --git a/tests/unit/test_viewer_protocol.py b/tests/unit/test_viewer_protocol.py index a53efa89eb..91d4ae08f5 100644 --- a/tests/unit/test_viewer_protocol.py +++ b/tests/unit/test_viewer_protocol.py @@ -17,7 +17,10 @@ import openhcs.runtime.viewer_protocol as viewer_protocol from openhcs.core.execution_visualizer import ExecutionVisualizerABC from openhcs.core.streaming_config_declarations import ViewerType -from openhcs.core.streaming_config_factory import StreamingViewerRuntimeConfig +from openhcs.core.streaming_config_factory import ( + StreamingViewerRuntimeConfig, + ViewerProcessLaunchConfig, +) from openhcs.runtime.import_authority import OpenHCSRuntimeImportAuthority from openhcs.runtime.viewer_controls import ( ViewerIntensityWindowControlOptions, @@ -370,6 +373,19 @@ def compatibility(_endpoint, *, timeout_ms, require_ready=True): assert viewer.existing_viewer_is_ready() + monkeypatch.setattr( + viewer, + "existing_viewer_matches_process_launch", + lambda: False, + ) + assert not viewer.existing_viewer_is_ready() + + monkeypatch.setattr( + viewer, + "existing_viewer_matches_process_launch", + lambda: True, + ) + observed_application = EndpointApplication( identifier="openhcs", version="stale", @@ -637,6 +653,33 @@ def test_viewer_qt_environment_policy_applies_platform_rows(): expected_windows["QT_QPA_PLATFORM_PLUGIN_PATH"] = plugin_path assert windows_env == expected_windows + explicit_font_dpi = ViewerQtEnvironmentPolicy( + ViewerProcessPlatform.LINUX, + font_dpi=96, + ).apply_to({}) + assert explicit_font_dpi["QT_FONT_DPI"] == "96" + + with pytest.raises(ValueError, match="font DPI must be positive"): + ViewerQtEnvironmentPolicy( + ViewerProcessPlatform.LINUX, + font_dpi=0, + ) + + +def test_viewer_process_launch_config_round_trips_exact_wire_declaration(): + config = ViewerProcessLaunchConfig(qt_font_dpi=96) + + assert ViewerProcessLaunchConfig.from_wire_mapping( + config.to_wire_mapping() + ) == config + + with pytest.raises(KeyError): + ViewerProcessLaunchConfig.from_wire_mapping({}) + with pytest.raises(TypeError): + ViewerProcessLaunchConfig.from_wire_mapping({"qt_font_dpi": True}) + with pytest.raises(ValueError): + ViewerProcessLaunchConfig(qt_font_dpi=0) + def test_projected_graphical_viewer_replaces_noninteractive_qt_platform(): launch_context = ViewerLaunchContext.projected_graphical_session( @@ -877,6 +920,7 @@ def _popen(command, **kwargs): port=5555, python_code="pass", log_file=tmp_path / f"{viewer_type.wire_value}.log", + process_launch=ViewerProcessLaunchConfig(qt_font_dpi=96), ) request.launch() @@ -884,6 +928,7 @@ def _popen(command, **kwargs): assert captured["command"] == ["windowed-python", "-c", "pass"] assert captured["creationflags"] == 91 assert "start_new_session" not in captured + assert captured["env"]["QT_FONT_DPI"] == "96" captured["stdout"].close() diff --git a/tests/unit/test_viewer_result_element_selection.py b/tests/unit/test_viewer_result_element_selection.py index 2cb2ecdd3b..6ee5797f60 100644 --- a/tests/unit/test_viewer_result_element_selection.py +++ b/tests/unit/test_viewer_result_element_selection.py @@ -235,6 +235,22 @@ def test_viewer_navigation_rejects_invalid_data_index(invalid_index: object) -> ) +@pytest.mark.parametrize( + ("state_override", "message"), + (({"visible": False}, "hidden layer"), ({"selected": False}, "deselected layer")), +) +def test_viewer_navigation_rejects_data_index_without_visible_selection( + state_override: dict[str, bool], + message: str, +) -> None: + with pytest.raises(ValueError, match=message): + ViewerNavigationControlOptions( + route_key="result-rois", + data_index=0, + **state_override, + ) + + def test_napari_navigation_selects_native_feature_row_and_projects_evidence(qtbot): from napari.components import ViewerModel from openhcs.napari_roi_manager import QRoiManager @@ -602,6 +618,25 @@ def test_navigate_viewer_cli_projects_data_index() -> None: assert call.arguments["data_index"] == 3 +def test_navigate_viewer_cli_rejects_hidden_data_index_before_mcp_call() -> None: + import openhcs.mcp.dev_client as dev_client + + args = dev_client._build_parser().parse_args( + ( + "navigate-viewer", + "5900", + "result-rois", + "--data-index", + "0", + "--hidden", + "--selected", + ) + ) + + with pytest.raises(dev_client.McpDevCliUsageError, match="hidden layer"): + dev_client._calls_from_args(args) + + def test_mcp_navigation_schema_explains_linked_result_selection() -> None: if importlib.util.find_spec("mcp") is None: return @@ -620,3 +655,6 @@ def test_mcp_navigation_schema_explains_linked_result_selection() -> None: assert "data_index" in navigation.inputSchema["properties"] assert "native feature-bearing result layer" in navigation.description assert "selected_data_indices" in navigation.description + assert "requires the target layer to remain visible and selected" in ( + navigation.description + ) From e995f367885bf6849f8ebeefde2fe6c09d39cfe5 Mon Sep 17 00:00:00 2001 From: Tristan Simas Date: Mon, 21 Sep 2026 23:32:55 -0400 Subject: [PATCH 03/15] Strengthen neurite ownership and visual QA evidence --- openhcs/agent/image_analysis_qa.py | 177 +++- openhcs/agent/services/llm_context_service.py | 24 +- .../backends/analysis/count_cells_simple.py | 558 +++++++++++- .../backends/analysis/neurite_outgrowth.py | 816 ++++++++++++++++-- .../codex/openhcs/skills/use-openhcs/SKILL.md | 17 + .../test_neurite_outgrowth_synthetic_plate.py | 106 ++- tests/unit/agent/test_image_analysis_qa.py | 19 + .../test_progressive_authoring_context.py | 8 + tests/unit/test_count_cells_simple.py | 270 +++++- tests/unit/test_neurite_outgrowth.py | 459 +++++++++- tests/unit/test_neuroncyto_ii_neurite_demo.py | 15 + 11 files changed, 2288 insertions(+), 181 deletions(-) diff --git a/openhcs/agent/image_analysis_qa.py b/openhcs/agent/image_analysis_qa.py index 8411aa54ab..4fde0810c0 100644 --- a/openhcs/agent/image_analysis_qa.py +++ b/openhcs/agent/image_analysis_qa.py @@ -42,11 +42,62 @@ class ImageQaMeasure(Enum): SENSITIVITY_DELTA_BACKGROUND_GROWTH = ( "unsupported background growth in the sensitivity delta" ) - CANDIDATE_TRACE_PIXELS = "current candidate-skeleton pixels" - ROOTED_CANDIDATE_YIELD = "fraction of candidate-skeleton pixels retained as rooted" + CANDIDATE_TRACE_PIXELS = "candidate-skeleton pixels" + ROOTED_CANDIDATE_YIELD = "candidate-skeleton fraction retained as rooted" TOTAL_TRACE_PIXELS = "total trace pixels" ROOTED_TRACE_PIXELS = "root-connected trace pixels" UNROOTED_TRACE_PIXELS = "unrooted trace pixels" + INITIAL_TOPOLOGY_OWNED_TRACE_PIXELS = ( + "initial-topology owned trace pixels" + ) + SECONDARY_ADOPTED_TRACE_PIXELS = ( + "trace pixels after secondary-owner adoption" + ) + SIGNAL_REPAIRED_TRACE_PIXELS = ( + "trace pixels after signal-supported soma repair" + ) + CROSSING_CORE_TRACE_PIXELS = ( + "shared crossing-core trace pixels" + ) + FINAL_TOPOLOGY_DROPPED_TRACE_PIXELS = ( + "owned trace pixels dropped by final topology" + ) + FINAL_TOPOLOGY_DROPPED_CROSSING_SUPPORT_TRACE_PIXELS = ( + "dropped crossing-support trace pixels" + ) + FINAL_TOPOLOGY_DROPPED_UNROOTED_PATH_TRACE_PIXELS = ( + "dropped graph-path pixels rejected as unrooted" + ) + FINAL_TOPOLOGY_DROPPED_PHYSICALLY_ROOTED_PATH_TRACE_PIXELS = ( + "physically soma-rooted dropped path pixels" + ) + FINAL_TOPOLOGY_DROPPED_PHYSICALLY_UNROOTED_PATH_TRACE_PIXELS = ( + "physically soma-detached dropped path pixels" + ) + FINAL_TOPOLOGY_DROPPED_UNREPRESENTED_TRACE_PIXELS = ( + "dropped trace pixels absent from final path graph" + ) + FINAL_TOPOLOGY_ADDED_TRACE_PIXELS = ( + "final-topology added shared-core pixels" + ) + FINAL_TOPOLOGY_OWNED_TRACE_PIXELS = ( + "final-topology owned trace pixels" + ) + PUBLISHED_OWNED_TRACE_PIXELS = ( + "published single-owner trace pixels" + ) + OWNERSHIP_SUPPORTED_UNROOTED_TRACE_PIXELS = ( + "unrooted trace pixels inside a declared owner region" + ) + OWNERSHIP_UNSUPPORTED_UNROOTED_TRACE_PIXELS = ( + "unrooted trace pixels outside every declared owner region" + ) + OWNERSHIP_SUPPORTED_RESIDUAL_PIXELS = ( + "residual candidate pixels inside a declared owner region" + ) + OWNERSHIP_UNSUPPORTED_RESIDUAL_PIXELS = ( + "residual candidate pixels outside every declared owner region" + ) OWNERSHIP_CROSSOVER_COMPONENTS = "components touching multiple owners" CANDIDATE_COMPONENT_OWNER_CARDINALITY = ( "number of owner identities touching each candidate component" @@ -58,6 +109,33 @@ class ImageQaMeasure(Enum): class ImageQaPrecondition(Enum): """Evidence required before a reported miss can justify parameter tuning.""" + RAW_BIOLOGICAL_CONTRACT = ( + "record stain targets; inspect every raw channel at identical native " + "coordinates under full, moderate, and dim windows, then the composite; freeze " + "a raw-only ledger of plausible objects, processes, ambiguities, and debris. " + "DAPI supports a nuclear anchor, broader colocalised process-channel signal a " + "soma, and thin continuous signal from that soma a neurite; brightness, labels, " + "or proximity alone prove none, and nucleus count is not cell count. Before " + "splitting a lobed nucleus, inspect a less-saturated window and require multiple " + "independently supported nuclear intensity centres; outline shape alone does not " + "prove multiple nuclei" + ) + EARLIEST_FAILED_DEPENDENCY = ( + "review nuclear anchors, somata, candidates, rooted paths, and ownership in " + "dependency order; stop downstream tuning at the earliest failure. If final " + "masks cannot distinguish response, threshold, split, or size rejection, expose " + "typed intermediates before changing parameters. Seed hysteresis can discard a " + "dim component despite local response; compare pre/post-seed candidates first. " + "Disabling it is a diagnostic ablation, not acceptance: require rooted recovery " + "without added background at the same coordinates" + ) + VALIDATION_EXPOSURE = ( + "record which fields informed pipeline or parameter decisions; a field " + "used for tuning is development evidence even if its directory says " + "held-out. Preserve treatment blinding separately from the development " + "split; select an untouched validation reserve before freezing, or report " + "that only development validation is available" + ) CURRENT_OUTPUT_CONCORDANCE = ( "localize the reported view to source coordinates and reproduce it from " "the current raw and output artifacts" @@ -132,6 +210,11 @@ class ImageQaEvidenceRule(Enum): "reject a black, empty, stale, or mismatched capture when its active route, " "component values, or routed payload identity do not match the intended evidence" ) + SPARSE_DIAGNOSTIC_LOCALIZATION = ( + "for a sparse diagnostic mask, use its viewer-reported exact nonzero bounds " + "and bounded example coordinates to navigate to evidence before judging a " + "full-field capture where one-pixel structures may be subpixel" + ) DURABLE_ARTIFACT_EXISTENCE = ( "before freezing, verify every claimed durable label or measurement path exists " "and preserves the typed artifact identity rather than inferring persistence " @@ -142,6 +225,22 @@ class ImageQaEvidenceRule(Enum): "foreground fraction, and per-object area distributions; equal counts alone " "do not establish spatial concordance" ) + FINAL_TOPOLOGY_REWRITE_ACCOUNTING = ( + "when final topology both removes and introduces trace pixels, compare the " + "dropped mask, added mask, shared crossing-core mask, and owner identities at " + "the same raw coordinates; net pixel-count change is not evidence of pruning" + ) + ROUND_OBJECT_SOURCE_LINEAGE = ( + "for apparent nuclear over-segmentation, compare raw stain with " + "round_object_prefilter, round_object_accepted, " + "round_object_weak_core_candidates, " + "round_object_adjacent_satellite_candidates, and round_object_widths at " + "fixed coordinates. Use source_component_label and " + "source_component_output_count to distinguish a separate threshold-stage " + "component from a watershed split. Never globally reject weak-core objects: " + "reject only an adjacent weak fragment while preserving isolated faint objects " + "and multi-centre controls" + ) class ReferenceEvidenceRule(Enum): @@ -250,6 +349,19 @@ class SemanticGate(Enum): ImageQaMeasure.TOTAL_TRACE_PIXELS, ImageQaMeasure.ROOTED_TRACE_PIXELS, ImageQaMeasure.UNROOTED_TRACE_PIXELS, + ImageQaMeasure.INITIAL_TOPOLOGY_OWNED_TRACE_PIXELS, + ImageQaMeasure.SECONDARY_ADOPTED_TRACE_PIXELS, + ImageQaMeasure.SIGNAL_REPAIRED_TRACE_PIXELS, + ImageQaMeasure.CROSSING_CORE_TRACE_PIXELS, + ImageQaMeasure.FINAL_TOPOLOGY_DROPPED_TRACE_PIXELS, + ImageQaMeasure.FINAL_TOPOLOGY_DROPPED_CROSSING_SUPPORT_TRACE_PIXELS, + ImageQaMeasure.FINAL_TOPOLOGY_DROPPED_UNROOTED_PATH_TRACE_PIXELS, + ImageQaMeasure.FINAL_TOPOLOGY_DROPPED_PHYSICALLY_ROOTED_PATH_TRACE_PIXELS, + ImageQaMeasure.FINAL_TOPOLOGY_DROPPED_PHYSICALLY_UNROOTED_PATH_TRACE_PIXELS, + ImageQaMeasure.FINAL_TOPOLOGY_DROPPED_UNREPRESENTED_TRACE_PIXELS, + ImageQaMeasure.FINAL_TOPOLOGY_ADDED_TRACE_PIXELS, + ImageQaMeasure.FINAL_TOPOLOGY_OWNED_TRACE_PIXELS, + ImageQaMeasure.PUBLISHED_OWNED_TRACE_PIXELS, ImageQaMeasure.RESIDUAL_STRUCTURE_COUNT, ImageQaMeasure.RESIDUAL_STRUCTURE_SIGNAL_SUPPORT, ImageQaMeasure.RESIDUAL_STRUCTURE_DISPOSITION, @@ -267,6 +379,10 @@ class SemanticGate(Enum): ( ImageQaMeasure.OWNERSHIP_CROSSOVER_COMPONENTS, ImageQaMeasure.CANDIDATE_COMPONENT_OWNER_CARDINALITY, + ImageQaMeasure.OWNERSHIP_SUPPORTED_UNROOTED_TRACE_PIXELS, + ImageQaMeasure.OWNERSHIP_UNSUPPORTED_UNROOTED_TRACE_PIXELS, + ImageQaMeasure.OWNERSHIP_SUPPORTED_RESIDUAL_PIXELS, + ImageQaMeasure.OWNERSHIP_UNSUPPORTED_RESIDUAL_PIXELS, ImageQaMeasure.TOPOLOGY_PLAUSIBILITY, ), ) @@ -427,40 +543,25 @@ def repair_guidance(cls) -> str: disposition.value for disposition in ResidualStructureDisposition ) return ( - f"Before tuning, require that each precondition holds: {precondition_text}. " - f"Accept visual or artifact evidence only when: {evidence_rule_text}. " - f"When a reference exists: {reference_evidence_text}. " - f"For seeded secondary segmentation: {seeded_segmentation_text}. " - "Classify the current-output " - f"miss by stage: {miss_stage_text}. Then classify each residual miss: " - f"{gate_text}. Sweep exactly one declaration-owned gate per attempt. " - "For thin structures, retain a fixed-coordinate four-panel view: raw, " - "candidate, rooted, and candidate-only residual. For source-assisted " - "admission, rank nuclei without a nearby accepted soma by same-coordinate " - "body-channel support. Test source admission and target-body response as " - "separate attempts; accept a recovered source only when it maps plausibly, " - "rather than splitting an already admitted source. Threshold effects need " - "spatial deltas: a stricter threshold can split a merged object, while a " - "permissive one can merge neighbors. " - "Inspect the source channel (for example DAPI), target or process channel " - "(for example FITC), response, accepted-label overlay, bodies, and traces; " - f"record candidate reasons ({rejection_reasons}) and residual dispositions " - f"({residual_dispositions}). For an unexplained miss, make one adjacent " - "higher-sensitivity diagnostic attempt, subtract the accepted candidate mask, " - "rank connected additions by signal/root support, and treat the permissive " - "result as diagnostic evidence rather than an automatic replacement. Accept " - "only signal-supported, connected, plausible topology. If candidate signal is " - "lost from the rooted result, report candidate pixels, rooted-candidate yield, " - "and owner cardinality per connected component; multi-owner loss implicates " - "ownership, so lowering the detection threshold cannot repair it. If a " - "permissive setting harms a reference, declare the permissive value only on " - "the dataset or preset that needs it. " - "For thin-structure endpoint continuation, require every proposed path " - f"to be {continuation_constraint_text}; distance, ownership, and response " - "alone are insufficient. " - "When faint signal motivates monotone, ridge, or contrast preprocessing, " - f"require the transform to {signal_transform_constraint_text}. Aggregate " - "length or object-count agreement alone cannot accept it. Reject growth " - "without root-connected continuity, and preserve rejected parameter changes " - "with the evidence for each decision." + f"Preconditions—{precondition_text}. Evidence—{evidence_rule_text}. " + f"References—{reference_evidence_text}. Seeds—{seeded_segmentation_text}. " + f"Stages—{miss_stage_text}. Gates/measures—{gate_text}. Reasons—" + f"{rejection_reasons}. Residuals—{residual_dispositions}. Change one gate " + "per attempt. Keep a fixed-coordinate four-panel " + "view: raw, candidate, rooted, and candidate-only residual. Rank nuclei " + "without a nearby accepted soma by same-coordinate body-channel support; " + "test source admission and target-body response as separate attempts without " + "splitting an already admitted source. A stricter threshold can split a " + "merged object. Inspect source (for example DAPI), target, response, " + "accepted-label overlay, bodies, and traces. For one higher-sensitivity " + "diagnostic attempt, subtract the accepted candidate mask and treat gains as " + "diagnostic evidence rather than an automatic replacement. Report stage " + "counts and owner cardinality per connected component. Multi-owner loss is " + "ownership failure; lowering the detection threshold cannot repair it. " + "If permissiveness harms a reference, declare the permissive value only on " + "the dataset or preset that needs it. Thin-structure continuation must be " + f"{continuation_constraint_text}; distance, ownership, and response alone " + "are insufficient. For monotone, ridge, or contrast preprocessing require " + f"{signal_transform_constraint_text}. Aggregate length or object-count " + "agreement alone cannot accept it. Preserve rejected parameter changes." ) diff --git a/openhcs/agent/services/llm_context_service.py b/openhcs/agent/services/llm_context_service.py index 3f618a313e..7b899bc7b2 100644 --- a/openhcs/agent/services/llm_context_service.py +++ b/openhcs/agent/services/llm_context_service.py @@ -310,20 +310,19 @@ class ImageAnalysisWorkflowSection( section_id = "image_analysis_workflow" content = f"""=== IMAGE-ANALYSIS WORKFLOW === -- Begin from declarations and evidence. Search the example corpus for the closest biological operation, retrieve its complete generated OpenHCS Python, and describe each candidate through the live registry. Reuse declared structure and callable docstrings; do not dispatch on function-name strings or create parallel catalogues. +- Search examples for the operation, retrieve complete OpenHCS Python, and inspect candidates through the live registry. Reuse declarations; do not dispatch on function-name strings or create parallel catalogues. - Keep assembly and grouping distinct. `variable_components=[SITE]` plus `group_by=CHANNEL` compiles one SITE stack per channel. When its live declaration confirms percentile fitting, `stack_percentile_normalize` computes one low/high percentile pair over every site in that stack; it must not fit a separate percentile pair per field. Confirm the exact callable and reflected contract with {agent_capabilities.search_functions.name} and {agent_capabilities.describe_function.name}; names do not establish semantics. -- Treat registration as a separate branch. Build the declared reference, calculate one position set, and retain its typed artifact. Restart assembly from declared sources with `input_source=PIPELINE_START` when needed, reuse that same position set by consuming its artifact, and assemble raw channel stacks or stacks whose analytical normalisation was explicitly fitted across all sites. Never recalculate positions by channel, display window, or result. -- Preserve correspondence across every QC view. Inspect the raw mosaics at several percentile clipping windows, including the full range and progressively stronger low/high pairs, while keeping placement coordinates, crop, scale, and result overlays identical. Record each percentile pair and its computed intensity bounds. Compare channel histograms, clipped fractions, and segmentation coverage across tile interiors, joins, quadrants, and complete fields; report per-region object or traced-signal density so seams, field-dependent thresholds, and spatial sensitivity drift are measurable rather than merely visible. -- Display normalisation changes presentation only; analytical preprocessing requires an explicit compiled FunctionStep. Analytically normalised data retain parameters, source/group identity, assembled SITE axis, position artifact, and output artifact provenance; a similar-looking viewer layer is not that record. -- Validate both intensity extremes and the requested result. Inspect representative dim structures, bright structures, background, saturated pixels, and strong unassigned residuals in native coordinates. For masks, sample supported foreground, missed-signal components, and foreground unsupported by source signal; report false-negative residual coverage, unsupported-mask coverage, object splits/merges, and boundary agreement when a reference exists. For traces or spatial graphs, sample intensity along each path and in a surrounding background band, then inspect low-support segments, high-signal residuals, discontinuities, gaps, endpoints, branches, crossings, and ownership continuity. Never infer support from display colour or a nonzero mask alone. +- Treat registration as a separate branch: calculate one position set and retain its typed artifact. Restart with `input_source=PIPELINE_START`, reuse that same position set by consuming its artifact, and assemble raw channel stacks or stacks whose analytical normalisation was explicitly fitted across all sites. Never recalculate positions by channel or result. +- Preserve correspondence across QC views. Inspect raw mosaics at several percentile windows, including full range, while keeping placement coordinates, crop, scale, and result overlays identical. Record each pair and computed bounds. Compare channel histograms, clipped fractions, and segmentation coverage across tile interiors, joins, quadrants, and complete fields; report per-region object or traced-signal density so spatial drift is measured, not merely visible. +- Display normalisation changes presentation only; analytical preprocessing needs a compiled FunctionStep retaining parameters, source/group identity, assembled SITE axis, shared positions, and artifact provenance. +- Validate representative dim structures, bright structures, background, saturation, and strong unassigned residuals. For masks, sample supported foreground, missed-signal components, and unsupported foreground; report false-negative residual coverage, unsupported-mask coverage, splits/merges, and reference-boundary agreement. For traces, sample intensity along each path and its background band; inspect discontinuities, gaps, endpoints, branches, crossings, and ownership continuity. Display colour or a nonzero mask is not support. - {ImageAnalysisQaPolicy.repair_guidance()} -- Choose validation evidence before tuning. Freeze a blinded, spatially distributed representative set containing dim signal, bright signal, sparse background, dense structures, tile boundaries, and known controls; do not replace difficult fields after seeing results. Tune only on the declared development subset. Perturb each sensitive parameter around the candidate value while holding sources, coordinates, preprocessing, display windows, and controls fixed, and report whether object count, covered signal, path length, branches, endpoints, and control ordering remain stable. Score held-out fields once after freezing the pipeline. -- Treat each diagnostic rerun as one falsifiable experiment. Record the observed failure, one explicit hypothesis, one declaration-owned semantic change, the complete pipeline identity, compile result, bounded execution time, peak memory, and the same-coordinate visual and quantitative evidence. Preserve every rejected attempt instead of overwriting it; multiple simultaneous changes make repair quality unscoreable. -- When exact catalogue search cannot express the required operation, follow the custom-function authoring context and register one typed callable through the existing authority. Before using it, verify that the same reflected signature and defaults appear in function detail, generated code, the parameter form, and the MCP contract. A local script or unregistered callable is not an OpenHCS pipeline result. -- Keep the complete analytical operation inside the OpenHCS declaration and managed runtime. Do not preprocess scientific inputs in an external script, inject text or clicks through X11/desktop automation, or manipulate a viewer behind the MCP surface. Use source bindings, function patterns, artifacts, compiler evidence, and managed viewer commands so the pipeline remains reproducible and every observation retains its owner. -- Escalate rather than declare success when the raw/result comparison finds coherent missed signal, unsupported foreground or traces, split/merged objects that alter ownership, unexplained tile/quadrant drift, unstable controls, strong parameter sensitivity, or disagreement between artifacts, ROIs, and measurement rows. Preserve the current attempt and provenance, constrain the next run to representative evidence, revise the smallest declaration-owned parameter or function boundary that explains the failure, and repeat the same coordinates and metrics. Ask the domain expert when signal identity or biological acceptability cannot be decided from image evidence; do not hide uncertainty inside an aggregate. -- Reconcile image/label or graph artifacts with schema-bearing measurements and ROIs, including identities and cardinalities. Record enough counts and coordinates to reproduce the sampled checks. A completed execution, plausible aggregate, smooth mosaic, or non-empty layer proves neither spatially uniform segmentation nor scientific completeness. -- Use the corpus as a pattern source, not an authority. Reuse source-bound preprocessing, registration-reference branches that share one position artifact, diagnostic intermediates followed by an interpretable final artifact, and bounded validation before plate-scale execution. Current bindings, function contracts, compiler plan, runtime routes, and artifact provenance remain authoritative.""" +- Freeze a blinded, spatially distributed representative set spanning dim/bright signal, sparse/dense regions, joins, and controls. Tune only on the declared development subset. Perturb one parameter with sources, coordinates, preprocessing, and display fixed; require counts, coverage, length, branches, endpoints, and control ordering remain stable. Score held-out fields once after freezing. +- Record failure, one explicit hypothesis, one semantic change, pipeline identity, compile result, time, peak memory, and same-coordinate evidence. Preserve rejected attempts; multiple simultaneous changes make repair quality unscoreable. +- If catalogue search cannot express the operation, follow the custom-function context. Verify the same reflected signature and defaults in function detail, code, form, and MCP. A local script or unregistered callable is not an OpenHCS pipeline result. +- Keep analysis in the managed declaration/runtime. Do not preprocess scientific inputs in an external script, use X11/desktop automation, or manipulate a viewer behind the MCP surface. Use declared bindings, functions, artifacts, and managed viewer commands. +- Escalate rather than declare success for missed signal, unsupported traces, incorrect splits/merges, unexplained tile/quadrant drift, unstable controls, or contradictory artifacts. Preserve provenance and repeat the same coordinates after a bounded repair. Ask the domain expert when biological identity remains ambiguous. +- Reconcile artifacts with ROI and measurement identities. Record reproducible counts and coordinates; completion, aggregate plausibility, and layer existence are not scientific acceptance. Current declarations and artifact provenance remain authoritative.""" class ConfigSchemaHintsSection(AuthoringContextSection, PipelineAuthoringRulesContext): @@ -446,6 +445,7 @@ def render(cls, service: "AgentAuthoringContextService") -> str: === SAFE FIRST ACTION === - Start read-only. Query the active surface through {agent_capabilities.search_capabilities.name} with task-relevant workflow, target, or text filters; its registry-owned metadata is the authority for what this server exposes. Use {agent_capabilities.list_capabilities.name} only when the complete selected surface is required. - Guides describe workflows across capability profiles. Confirm a named tool is exposed before calling it. Desktop actions are discovered separately through {agent_capabilities.ui_list_actions.name}; an empty capability search does not establish that a running window lacks the action. +- Before operating a live desktop workflow, call {agent_capabilities.ui_list_windows.name} and resolve visible modal top-level windows first. Inspect each dialog through {agent_capabilities.ui_get_widget_tree.name} and invoke its declared button through {agent_capabilities.ui_invoke_widget_action.name}; acknowledge completed operations, cancel unsolicited update/restart prompts, and never use desktop-coordinate automation or leave a blocking dialog hidden behind the analysis viewer. - Request the matching task context before mutation. Do not read every knowledge document, enumerate every function, invent config fields, or load full-resolution image data up front. - When continuing an analysis, read and reuse its existing pipeline and configuration. Adapt only the required source/layout choices, preserve earlier outputs in a separate destination, and record unavailable acquisitions as missing rather than zero measurements. Validate a representative bounded run before expanding. - If returned guidance is truncated, retrieve the same context with a sufficient max_chars before acting on an incomplete workflow. diff --git a/openhcs/processing/backends/analysis/count_cells_simple.py b/openhcs/processing/backends/analysis/count_cells_simple.py index 59f4eebd00..764ffb762a 100644 --- a/openhcs/processing/backends/analysis/count_cells_simple.py +++ b/openhcs/processing/backends/analysis/count_cells_simple.py @@ -544,12 +544,55 @@ def count_cells_simple_dual_channel( ) +@dataclass(frozen=True) +class LabelShapeStatistics: + """Vectorized per-label geometry indexed by the label value.""" + + counts: np.ndarray + centroid_rows_px: np.ndarray + centroid_columns_px: np.ndarray + major_axis_lengths_px: np.ndarray + minor_axis_lengths_px: np.ndarray + + +@dataclass(frozen=True) +class RoundObjectSegmentationStages: + """Exact pre-filter labels and acceptance evidence for round objects.""" + + prefilter_labels: np.ndarray + source_component_by_label: np.ndarray + shape_statistics: LabelShapeStatistics + peak_response_by_label: np.ndarray + mean_response_by_label: np.ndarray + width_keep_mask: np.ndarray + adjacent_satellite_mask: np.ndarray + + @property + def keep_mask(self) -> np.ndarray: + return self.width_keep_mask & ~self.adjacent_satellite_mask + + @property + def accepted_labels(self) -> np.ndarray: + return _relabel_by_keep_mask(self.prefilter_labels, self.keep_mask) + + def segment_metaxpress_round_objects( slice_data: np.ndarray, settings: MetaXpressWavelengthSettings, pixel_size_um: float, ) -> np.ndarray: """Segment bright round objects using shared MetaXpress-style controls.""" + return round_object_segmentation_stages( + slice_data, settings, pixel_size_um + ).accepted_labels + + +def round_object_segmentation_stages( + slice_data: np.ndarray, + settings: MetaXpressWavelengthSettings, + pixel_size_um: float, +) -> RoundObjectSegmentationStages: + """Run the shared detector once and retain its exact acceptance evidence.""" min_width_px = settings.approx_min_width / pixel_size_um max_width_px = settings.approx_max_width / pixel_size_um @@ -560,30 +603,318 @@ def segment_metaxpress_round_objects( ) binary = intensity_above_background >= settings.intensity_above_local_background - max_object_area = max(1, int(np.ceil(np.pi * (max_width_px / 2.0) ** 2))) + minimum_pair_area = max( + 1, + int(np.ceil(2.0 * np.pi * (min_width_px / 2.0) ** 2)), + ) seed_spacing = max(1, int(round(min_width_px / 2.0))) seed_footprint = odd_size(max(1.0, min_width_px / 2.0)) - labeled = _label_binary_components( + seed_prominence = max(1.0, min_width_px / 4.0) + intensity_smoothing_sigma = max(0.5, min_width_px / 4.0) + component_stages = _label_binary_component_stages( binary, watershed_large_objects=True, - watershed_split_size=max_object_area, + watershed_split_size=minimum_pair_area, watershed_max_size=None, watershed_min_distance=seed_spacing, watershed_footprint_size=seed_footprint, - watershed_peak_prominence=min_width_px / 2.0, + watershed_peak_prominence=seed_prominence, + watershed_marker_image=intensity_above_background, + watershed_marker_smoothing_sigma=intensity_smoothing_sigma, + watershed_marker_peak_prominence=( + settings.intensity_above_local_background / 4.0 + ), ) + labeled = component_stages.output_labels - _, minor_axis_lengths = _axis_lengths_by_label(labeled) - keep_mask = (minor_axis_lengths >= min_width_px) & ( - minor_axis_lengths <= max_width_px + shape_statistics = _shape_statistics_by_label(labeled) + peak_response, mean_response = _response_statistics_by_label( + labeled, + intensity_above_background, ) - if keep_mask.size: - keep_mask[0] = False - return _relabel_by_keep_mask(labeled, keep_mask) + width_keep_mask = ( + shape_statistics.minor_axis_lengths_px >= min_width_px + ) & ( + shape_statistics.minor_axis_lengths_px <= max_width_px + ) + if width_keep_mask.size: + width_keep_mask[0] = False + adjacent_satellite_mask = _adjacent_satellite_mask( + labeled, + shape_statistics.counts, + peak_response, + width_keep_mask, + maximum_candidate_area=minimum_pair_area, + minimum_core_response=( + 2.0 * settings.intensity_above_local_background + ), + maximum_gap_px=seed_spacing, + ) + return RoundObjectSegmentationStages( + labeled, + component_stages.source_component_by_output, + shape_statistics, + peak_response, + mean_response, + width_keep_mask, + adjacent_satellite_mask, + ) + + +@dataclass(frozen=True) +class RoundObjectWidthResult: + """Width-gate evidence keyed to an object before final label filtering.""" + object_label: int + accepted_label: int + source_component_label: int + source_component_output_count: int + split_from_source_component: bool + area_pixels: int + centroid_row_px: float + centroid_column_px: float + peak_intensity_above_local_background: float + mean_intensity_above_local_background: float + core_support_threshold: float + weak_core_candidate: bool + rejected_as_adjacent_satellite: bool + major_axis_um: float + minor_axis_um: float + minimum_width_um: float + maximum_width_um: float + + +ROUND_OBJECT_PREFILTER_OUTPUT = ArtifactSpec.output( + "round_object_prefilter", + ObjectLabelsArtifactType, + materialization=MaterializationSpec(ROIOptions()), +) +ROUND_OBJECT_ACCEPTED_OUTPUT = ArtifactSpec.output( + "round_object_accepted", + ObjectLabelsArtifactType, + materialization=MaterializationSpec(ROIOptions()), +) +ROUND_OBJECT_WEAK_CORE_OUTPUT = ArtifactSpec.output( + "round_object_weak_core_candidates", + ObjectLabelsArtifactType, + materialization=MaterializationSpec(ROIOptions()), +) +ROUND_OBJECT_ADJACENT_SATELLITE_OUTPUT = ArtifactSpec.output( + "round_object_adjacent_satellite_candidates", + ObjectLabelsArtifactType, + materialization=MaterializationSpec(ROIOptions()), +) +ROUND_OBJECT_WIDTHS_OUTPUT = ArtifactSpec.output( + "round_object_widths", + MeasurementsArtifactType, + materialization=MaterializationSpec(CsvOptions()), + relations=( + ObjectMeasurementSubjectRelation( + source=ROUND_OBJECT_PREFILTER_OUTPUT.ref(), + id_field="object_label", + ), + ), +) -def _axis_lengths_by_label(labeled: np.ndarray) -> tuple[np.ndarray, np.ndarray]: - """Return major and minor axis lengths indexed by 2D object label.""" + +@numpy +@artifact_inputs("pixel_size") +@artifact_outputs( + ROUND_OBJECT_WIDTHS_OUTPUT, + ROUND_OBJECT_PREFILTER_OUTPUT, + ROUND_OBJECT_ACCEPTED_OUTPUT, + ROUND_OBJECT_WEAK_CORE_OUTPUT, + ROUND_OBJECT_ADJACENT_SATELLITE_OUTPUT, +) +def inspect_metaxpress_round_objects( + image: np.ndarray, + settings: MetaXpressWavelengthSettings = MetaXpressWavelengthSettings(), + pixel_size: HiddenPixelSize = HiddenPixelSize(1.0), +) -> tuple[ + np.ndarray, + DataclassMeasurementColumnarRows, + np.ndarray, + np.ndarray, + np.ndarray, + np.ndarray, +]: + """Diagnose round-object admission stages without changing the detector. + + Input is a CHANNEL,Y,X stack. Only the selected channel is analysed; the + main image is returned unchanged. Prefilter and accepted object labels share + the input channel axis, with other channels empty. The typed outputs are the + per-object ``round_object_widths`` measurements plus + ``round_object_prefilter``, ``round_object_accepted``, + ``round_object_weak_core_candidates``, and + ``round_object_adjacent_satellite_candidates`` labels. Source-component + lineage distinguishes separate threshold-stage components from watershed + splits. Inspect every diagnostic beside raw stain morphology; acceptance is + not proof that an object is a biological nucleus or cell. + """ + settings.validate("settings") + if image.ndim != 3 or not 0 <= settings.channel_index < image.shape[0]: + raise ValueError("Expected CHANNEL,Y,X with the selected channel present") + pixel_size_um = float(pixel_size) + if not np.isfinite(pixel_size_um) or pixel_size_um <= 0: + raise ValueError("Pixel size must be finite and positive") + stages = round_object_segmentation_stages( + image[settings.channel_index], settings, pixel_size_um + ) + prefilter = np.zeros(image.shape, dtype=np.int32) + prefilter[settings.channel_index] = stages.prefilter_labels + accepted = np.zeros(image.shape, dtype=np.int32) + accepted[settings.channel_index] = stages.accepted_labels + core_support_threshold = 2.0 * settings.intensity_above_local_background + weak_core_mask = stages.width_keep_mask & ( + stages.peak_response_by_label < core_support_threshold + ) + weak_core = np.zeros(image.shape, dtype=np.int32) + weak_core[settings.channel_index] = _relabel_by_keep_mask( + stages.prefilter_labels, + weak_core_mask, + ) + adjacent_satellites = np.zeros(image.shape, dtype=np.int32) + adjacent_satellites[settings.channel_index] = _relabel_by_keep_mask( + stages.prefilter_labels, + stages.adjacent_satellite_mask, + ) + accepted_ids = np.cumsum(stages.keep_mask) * stages.keep_mask + source_output_counts = np.bincount(stages.source_component_by_label[1:]) + rows = tuple( + RoundObjectWidthResult( + object_label=int(label), + accepted_label=int(accepted_ids[label]), + source_component_label=int(stages.source_component_by_label[label]), + source_component_output_count=int( + source_output_counts[stages.source_component_by_label[label]] + ), + split_from_source_component=bool( + source_output_counts[stages.source_component_by_label[label]] > 1 + ), + area_pixels=int(stages.shape_statistics.counts[label]), + centroid_row_px=float(stages.shape_statistics.centroid_rows_px[label]), + centroid_column_px=float( + stages.shape_statistics.centroid_columns_px[label] + ), + peak_intensity_above_local_background=float( + stages.peak_response_by_label[label] + ), + mean_intensity_above_local_background=float( + stages.mean_response_by_label[label] + ), + core_support_threshold=float(core_support_threshold), + weak_core_candidate=bool(weak_core_mask[label]), + rejected_as_adjacent_satellite=bool( + stages.adjacent_satellite_mask[label] + ), + major_axis_um=float( + stages.shape_statistics.major_axis_lengths_px[label] * pixel_size_um + ), + minor_axis_um=float( + stages.shape_statistics.minor_axis_lengths_px[label] * pixel_size_um + ), + minimum_width_um=settings.approx_min_width, + maximum_width_um=settings.approx_max_width, + ) + for label in np.flatnonzero(stages.shape_statistics.counts[1:]) + 1 + ) + return ( + image, + DataclassMeasurementColumnarRows(rows, row_type=RoundObjectWidthResult), + prefilter, + accepted, + weak_core, + adjacent_satellites, + ) + + +def _adjacent_satellite_mask( + labeled: np.ndarray, + counts: np.ndarray, + peak_response: np.ndarray, + width_keep_mask: np.ndarray, + *, + maximum_candidate_area: int, + minimum_core_response: float, + maximum_gap_px: int, +) -> np.ndarray: + """Identify small weak fragments adjacent to a supported round object. + + The rule is deliberately conjunctive: an object must already pass the + declared width gate, lack a supported intensity core, be smaller than the + area needed for two minimum-width nuclei, and sit within the existing + watershed seed spacing of a larger width-accepted object with a supported + core. Isolated faint objects are retained for downstream QA rather than + being rejected by intensity alone. + """ + + if labeled.ndim != 2: + raise ValueError("Adjacent-satellite detection requires a 2D label plane") + if not ( + counts.shape == peak_response.shape == width_keep_mask.shape + and counts.shape[0] == int(labeled.max()) + 1 + ): + raise ValueError("Adjacent-satellite evidence must share label indexing") + if maximum_gap_px < 1: + raise ValueError("maximum_gap_px must be >= 1") + + weak_small = ( + width_keep_mask + & (counts < maximum_candidate_area) + & (peak_response < minimum_core_response) + ) + if weak_small.size: + weak_small[0] = False + candidates = np.flatnonzero(weak_small) + rejected = np.zeros_like(width_keep_mask, dtype=bool) + if not len(candidates): + return rejected + + offsets = np.arange(-maximum_gap_px, maximum_gap_px + 1) + offset_rows, offset_columns = np.meshgrid(offsets, offsets, indexing="ij") + neighborhood = ( + np.square(offset_rows) + np.square(offset_columns) + <= maximum_gap_px**2 + ) + object_slices = ndi.find_objects(labeled) + for candidate in candidates: + object_slice = object_slices[candidate - 1] + if object_slice is None: + continue + expanded_slice = tuple( + slice( + max(0, axis_slice.start - maximum_gap_px), + min(axis_size, axis_slice.stop + maximum_gap_px), + ) + for axis_slice, axis_size in zip( + object_slice, + labeled.shape, + strict=True, + ) + ) + local_labels = labeled[expanded_slice] + nearby = ndi.binary_dilation( + local_labels == candidate, + structure=neighborhood, + ) + neighbor_labels = np.unique( + local_labels[ + nearby + & (local_labels != 0) + & (local_labels != candidate) + ] + ) + if np.any( + width_keep_mask[neighbor_labels] + & (counts[neighbor_labels] >= maximum_candidate_area) + & (peak_response[neighbor_labels] >= minimum_core_response) + ): + rejected[candidate] = True + return rejected + + +def _shape_statistics_by_label(labeled: np.ndarray) -> LabelShapeStatistics: + """Return vectorized geometry indexed by 2D object label.""" labels = np.asarray(labeled) if labels.ndim != 2: @@ -596,7 +927,13 @@ def _axis_lengths_by_label(labeled: np.ndarray) -> tuple[np.ndarray, np.ndarray] foreground_indices = np.flatnonzero(flat_labels) if not len(foreground_indices): empty = np.zeros(output_size, dtype=float) - return empty, empty.copy() + return LabelShapeStatistics( + empty, + empty.copy(), + empty.copy(), + empty.copy(), + empty.copy(), + ) object_labels = flat_labels[foreground_indices] rows = (foreground_indices // labels.shape[1]).astype(float, copy=False) @@ -664,7 +1001,47 @@ def _axis_lengths_by_label(labeled: np.ndarray) -> tuple[np.ndarray, np.ndarray] 0.0, 0.5 * (row_variances + column_variances - discriminant), ) - return 4.0 * np.sqrt(major_variances), 4.0 * np.sqrt(minor_variances) + return LabelShapeStatistics( + counts, + mean_rows, + mean_columns, + 4.0 * np.sqrt(major_variances), + 4.0 * np.sqrt(minor_variances), + ) + + +def _response_statistics_by_label( + labeled: np.ndarray, + response: np.ndarray, +) -> tuple[np.ndarray, np.ndarray]: + """Return peak and mean response values indexed by object label.""" + + if response.shape != labeled.shape: + raise ValueError("Response image must match the object-label plane") + output_size = int(labeled.max()) + 1 + foreground = labeled > 0 + if not np.any(foreground): + empty = np.zeros(output_size, dtype=float) + return empty, empty.copy() + + object_labels = labeled[foreground] + object_responses = np.asarray(response, dtype=float)[foreground] + counts = np.bincount(object_labels, minlength=output_size) + response_sums = np.bincount( + object_labels, + weights=object_responses, + minlength=output_size, + ) + mean_response = np.divide( + response_sums, + counts, + out=np.zeros(output_size, dtype=float), + where=counts > 0, + ) + peak_response = np.full(output_size, -np.inf, dtype=float) + np.maximum.at(peak_response, object_labels, object_responses) + peak_response[~np.isfinite(peak_response)] = 0.0 + return peak_response, mean_response def _build_w2_compartments( @@ -769,20 +1146,81 @@ def _label_binary_components( watershed_min_distance: int, watershed_footprint_size: int, watershed_peak_prominence: float = 0.0, + watershed_marker_image: Optional[np.ndarray] = None, + watershed_marker_smoothing_sigma: float = 0.0, + watershed_marker_peak_prominence: float = 0.0, ) -> np.ndarray: """Label a binary mask and optionally split large connected components.""" - labeled, num_objects = ndi.label(binary) + return _label_binary_component_stages( + binary, + watershed_large_objects=watershed_large_objects, + watershed_split_size=watershed_split_size, + watershed_max_size=watershed_max_size, + watershed_min_distance=watershed_min_distance, + watershed_footprint_size=watershed_footprint_size, + watershed_peak_prominence=watershed_peak_prominence, + watershed_marker_image=watershed_marker_image, + watershed_marker_smoothing_sigma=watershed_marker_smoothing_sigma, + watershed_marker_peak_prominence=watershed_marker_peak_prominence, + ).output_labels + + +@dataclass(frozen=True) +class BinaryComponentStages: + """Connected-component identities before and after optional splitting.""" + + source_labels: np.ndarray + output_labels: np.ndarray + source_component_by_output: np.ndarray + + +def _label_binary_component_stages( + binary: np.ndarray, + *, + watershed_large_objects: bool, + watershed_split_size: int, + watershed_max_size: Optional[int], + watershed_min_distance: int, + watershed_footprint_size: int, + watershed_peak_prominence: float = 0.0, + watershed_marker_image: Optional[np.ndarray] = None, + watershed_marker_smoothing_sigma: float = 0.0, + watershed_marker_peak_prominence: float = 0.0, +) -> BinaryComponentStages: + """Retain source-component lineage across optional watershed splitting.""" + + source_labels, num_objects = ndi.label(binary) + output_labels = source_labels if watershed_large_objects and num_objects > 0: - labeled = _watershed_large_objects( - labeled, + output_labels = _watershed_large_objects( + source_labels, split_size=watershed_split_size, watershed_max_size=watershed_max_size, min_distance=watershed_min_distance, footprint_size=watershed_footprint_size, peak_prominence=watershed_peak_prominence, + marker_image=watershed_marker_image, + marker_smoothing_sigma=watershed_marker_smoothing_sigma, + marker_peak_prominence=watershed_marker_peak_prominence, ) - return labeled.astype(np.int32, copy=False) + source_labels = source_labels.astype(np.int32, copy=False) + output_labels = output_labels.astype(np.int32, copy=False) + source_component_by_output = np.zeros( + int(output_labels.max()) + 1, + dtype=np.int32, + ) + foreground = output_labels > 0 + np.maximum.at( + source_component_by_output, + output_labels[foreground], + source_labels[foreground], + ) + return BinaryComponentStages( + source_labels, + output_labels, + source_component_by_output, + ) def _filter_labels_by_area( @@ -842,6 +1280,9 @@ def _watershed_large_objects( min_distance: int, footprint_size: int, peak_prominence: float = 0.0, + marker_image: Optional[np.ndarray] = None, + marker_smoothing_sigma: float = 0.0, + marker_peak_prominence: float = 0.0, ) -> np.ndarray: """Split components above split_size and at or below watershed_max_size.""" counts = np.bincount(labeled.ravel()) @@ -855,10 +1296,34 @@ def _watershed_large_objects( if split_labels.size == 0: return labeled.astype(np.int32, copy=False) + footprint = np.ones((footprint_size, footprint_size), dtype=bool) + + def peak_coordinates( + surface: np.ndarray, + component: np.ndarray, + prominence: float, + ) -> np.ndarray: + peak_support = h_maxima(surface, prominence) if prominence > 0.0 else component + peak_components, _ = ndi.label(peak_support & component) + return peak_local_max( + surface, + min_distance=min_distance, + footprint=footprint, + labels=peak_components, + num_peaks_per_label=1 if prominence > 0.0 else np.inf, + exclude_border=False, + ) + + marker_array = None + if marker_image is not None: + marker_array = np.asarray(marker_image, dtype=float) + if marker_array.shape != labeled.shape: + raise ValueError("watershed marker image must match the label plane") + output = labeled.astype(np.int32, copy=True) object_slices = ndi.find_objects(labeled) next_label = int(labeled.max()) + 1 - footprint = np.ones((footprint_size, footprint_size), dtype=bool) + minimum_fragment_area = max(1, int(np.floor(split_size / 2.0))) for label_id in split_labels: component_slice = object_slices[label_id - 1] @@ -866,28 +1331,53 @@ def _watershed_large_objects( continue component = labeled[component_slice] == label_id - distance = ndi.distance_transform_edt(np.pad(component, 1))[1:-1, 1:-1] - # Width-based detection needs distinct object-scale peaks, not multiple - # pixel-scale maxima on the medial ridge of one elongated nucleus. - peak_support = ( - h_maxima(distance, peak_prominence) if peak_prominence > 0.0 else component - ) - peak_components, _ = ndi.label(peak_support) - seeds = peak_local_max( - distance, - min_distance=min_distance, - footprint=footprint, - labels=peak_components, - num_peaks_per_label=1 if peak_prominence > 0.0 else np.inf, - exclude_border=False, + filled_component = ndi.binary_fill_holes(component) + distance = ndi.distance_transform_edt(np.pad(filled_component, 1))[1:-1, 1:-1] + shape_seeds = peak_coordinates(distance, component, peak_prominence) + substantial_hole = ( + np.count_nonzero(filled_component) - np.count_nonzero(component) + >= minimum_fragment_area ) + marker_surface = None + intensity_seeds = np.empty((0, 2), dtype=np.intp) + if marker_array is not None and not substantial_hole: + marker_component = marker_array[component_slice] + if marker_smoothing_sigma > 0.0: + weights = ndi.gaussian_filter( + component.astype(float), marker_smoothing_sigma + ) + weighted = ndi.gaussian_filter( + np.where(component, marker_component, 0.0), + marker_smoothing_sigma, + ) + marker_surface = np.divide( + weighted, + weights, + out=np.zeros_like(weighted), + where=weights > np.finfo(float).eps, + ) + else: + marker_surface = marker_component + intensity_seeds = peak_coordinates( + marker_surface, + component, + marker_peak_prominence, + ) + + use_intensity = marker_surface is not None + seeds = intensity_seeds if use_intensity else shape_seeds if len(seeds) <= 1: continue markers = np.zeros_like(component, dtype=np.int32) markers[seeds[:, 0], seeds[:, 1]] = np.arange(1, len(seeds) + 1) - component_splits = watershed(-distance, markers, mask=component) + split_surface = marker_surface if use_intensity else distance + component_splits = watershed(-split_surface, markers, mask=component) + if use_intensity: + fragment_areas = np.bincount(component_splits.ravel())[1:] + if np.any(fragment_areas < minimum_fragment_area): + continue output_view = output[component_slice] output_view[component] = 0 diff --git a/openhcs/processing/backends/analysis/neurite_outgrowth.py b/openhcs/processing/backends/analysis/neurite_outgrowth.py index 15d460a99d..926f43f735 100644 --- a/openhcs/processing/backends/analysis/neurite_outgrowth.py +++ b/openhcs/processing/backends/analysis/neurite_outgrowth.py @@ -22,8 +22,11 @@ from openhcs.core.artifacts import ( ArtifactMeasurementSubjectRelation, + ArtifactSidecarRole, ArtifactSpec, ArtifactViewerStreaming, + ImageArtifactType, + MainFlowPlaneProjectionOutputSpec, MeasurementsArtifactType, ObjectArtifactMemberSubjectRelation, ObjectLabelsArtifactType, @@ -36,6 +39,7 @@ ) from openhcs.core.memory import numpy from openhcs.core.pipeline.function_contracts import artifact_inputs, artifact_outputs +from openhcs.core.projected_image_output import SelectedPlaneImageOutput from openhcs.core.runtime_image_values import image_payload_data from openhcs.core.runtime_object_label_building import ( SourceImageObjectLabelBuildRequest, @@ -332,6 +336,31 @@ class NeuriteOutgrowthSummary: percent_cells_significant_growth: float mean_outgrowth_average_intensity: float resolved_crossovers: int + candidate_trace_pixels: int + rooted_candidate_trace_pixels: int + unrooted_candidate_trace_pixels: int + rooted_candidate_trace_yield: float + initial_topology_owned_trace_pixels: int + secondary_adopted_trace_pixels: int + signal_repaired_trace_pixels: int + crossing_core_trace_pixels: int + final_topology_dropped_trace_pixels: int + final_topology_dropped_crossing_support_trace_pixels: int + final_topology_dropped_unrooted_path_trace_pixels: int + final_topology_dropped_physically_rooted_path_trace_pixels: int + final_topology_dropped_physically_unrooted_path_trace_pixels: int + final_topology_dropped_unrepresented_trace_pixels: int + final_topology_added_trace_pixels: int + final_topology_owned_trace_pixels: int + published_owned_trace_pixels: int + secondary_owned_unrooted_trace_pixels: int + secondary_unowned_unrooted_trace_pixels: int + candidate_mask_pixels: int + rooted_candidate_mask_pixels: int + unrooted_residual_pixels: int + secondary_owned_residual_pixels: int + secondary_unowned_residual_pixels: int + secondary_owned_residual_fraction: float @dataclass(frozen=True) @@ -482,6 +511,35 @@ class NeuronalCellBodyResult: ) +def _neurite_qa_checkpoint_output(name: str) -> ArtifactSpec: + """Declare a source-identifiable plane checkpoint from the assembled stack.""" + + return MainFlowPlaneProjectionOutputSpec.output( + name, + ImageArtifactType, + sidecar_role=ArtifactSidecarRole.QA_CHECKPOINT, + materialization=MaterializationSpec( + ImageFileOptions(filename_suffix=f"_{name}.checkpoint.tif") + ), + viewer_streaming=ArtifactViewerStreaming.ON_DEMAND, + ) + + +NEURITE_CANDIDATE_MASK_OUTPUT = _neurite_qa_checkpoint_output("neurite_candidate_mask") +NEURITE_UNROOTED_RESIDUAL_OUTPUT = _neurite_qa_checkpoint_output( + "neurite_unrooted_residual" +) +NEURITE_SECONDARY_OWNERSHIP_OUTPUT = _neurite_qa_checkpoint_output( + "neurite_secondary_ownership" +) +NEURITE_TOPOLOGY_DROPPED_TRACE_OUTPUT = _neurite_qa_checkpoint_output( + "neurite_topology_dropped_trace" +) +NEURITE_TOPOLOGY_ADDED_TRACE_OUTPUT = _neurite_qa_checkpoint_output( + "neurite_topology_added_trace" +) + + @dataclass(frozen=True) class _TopologyResult: path_owners: np.ndarray @@ -643,6 +701,11 @@ def count_neuronal_cell_bodies_metaxpress( NEURITE_LABELS_OUTPUT, UNIFIED_NEURONS_OUTPUT, NUCLEI_OUTPUT, + NEURITE_CANDIDATE_MASK_OUTPUT, + NEURITE_UNROOTED_RESIDUAL_OUTPUT, + NEURITE_SECONDARY_OWNERSHIP_OUTPUT, + NEURITE_TOPOLOGY_DROPPED_TRACE_OUTPUT, + NEURITE_TOPOLOGY_ADDED_TRACE_OUTPUT, NEURITE_MORPHOLOGY_OUTPUT, ) @artifact_inputs("pixel_size") @@ -663,6 +726,11 @@ def neurite_outgrowth_metaxpress( np.ndarray, np.ndarray, np.ndarray, + SelectedPlaneImageOutput, + SelectedPlaneImageOutput, + SelectedPlaneImageOutput, + SelectedPlaneImageOutput, + SelectedPlaneImageOutput, SpatialGraph, ]: """Measure cell bodies and attached neurites in one 2D channel stack. @@ -841,16 +909,35 @@ def neurite_outgrowth_metaxpress( outgrowth_skeleton.shape, topology, ) + initial_topology_owned_trace_pixels = int( + np.count_nonzero((owner_skeleton > 0) & (cell_body_labels == 0)) + ) if nuclear_seed_mode: - owner_skeleton = _adopt_secondary_owned_skeleton( - outgrowth_skeleton, + owner_skeleton = _adopt_secondary_owned_path_segments( + topology, owner_skeleton, secondary_owner_regions, ) + secondary_adopted_trace_pixels = int( + np.count_nonzero((owner_skeleton > 0) & (cell_body_labels == 0)) + ) crossing_support = _render_crossing_support( outgrowth_skeleton.shape, topology, ) + crossing_core_mask = _render_crossing_core_mask( + outgrowth_skeleton.shape, + topology, + ) + resolved_crossovers = _count_multi_owner_crossings( + crossing_core_mask, + crossing_support, + ) + crossing_core_support = np.where( + crossing_core_mask, + crossing_support, + 0, + ).astype(np.int32, copy=False) owner_skeleton = _repair_signal_supported_skeleton( owner_skeleton, outgrowth_response, @@ -863,19 +950,53 @@ def neurite_outgrowth_metaxpress( crossing_support, owner_skeleton, ).astype(np.int32, copy=False) - neurite_skeleton = owner_skeleton.copy() - neurite_skeleton[cell_body_labels > 0] = 0 - topology = _analyze_topology( - neurite_skeleton > 0, + signal_repaired_trace_pixels = int( + np.count_nonzero((owner_skeleton > 0) & (cell_body_labels == 0)) + ) + pre_topology_owner_skeleton = owner_skeleton.copy() + pre_topology_owner_skeleton[cell_body_labels > 0] = 0 + topology = _analyze_owned_topology( + pre_topology_owner_skeleton, cell_body_labels, pixel_size_um, outgrowth_width_px, - assigned_path_labels=neurite_skeleton, + shared_crossing_mask=crossing_core_mask, ) neurite_skeleton = _render_owned_skeleton( - neurite_skeleton.shape, + pre_topology_owner_skeleton.shape, + topology, + ) + topology_path_mask = _render_topology_path_mask( + pre_topology_owner_skeleton.shape, topology, ) + physically_soma_rooted_trace = _physically_soma_rooted_owner_mask( + pre_topology_owner_skeleton, + cell_body_labels, + maximum_root_distance=max(1, int(np.ceil(outgrowth_width_px)) + 2), + ) + topology_dropped_trace = ( + (pre_topology_owner_skeleton > 0) + & (neurite_skeleton == 0) + & ~crossing_core_mask + ) + topology_added_trace = ( + (neurite_skeleton > 0) + & (pre_topology_owner_skeleton == 0) + ) + final_topology_owned_trace_pixels = int( + np.count_nonzero(neurite_skeleton) + ) + # A physical crossing core supports two logical paths, but an object-label + # raster can store only one identity per pixel. The topology above remains + # authoritative for both neurites; publish the already-resolved nearest + # owner for each shared physical core pixel so QA and raster expansion do + # not misclassify valid crossover signal as an unrooted residual. + neurite_skeleton = np.where( + crossing_core_support > 0, + crossing_core_support, + neurite_skeleton, + ).astype(np.int32, copy=False) owner_outgrowth = _expand_skeleton_ownership( neurite_skeleton, outgrowth_binary, @@ -892,6 +1013,32 @@ def neurite_outgrowth_metaxpress( owner_outgrowth, ).astype(np.int32, copy=False) + candidate_neurite_mask = outgrowth_binary & (cell_body_labels == 0) + candidate_trace_mask = outgrowth_skeleton & (cell_body_labels == 0) + rooted_mask = owner_outgrowth > 0 + rooted_trace_mask = neurite_skeleton > 0 + unrooted_residual = candidate_neurite_mask & ~rooted_mask + secondary_owned_residual = unrooted_residual & (secondary_owner_regions > 0) + candidate_trace_pixels = int(np.count_nonzero(candidate_trace_mask)) + rooted_candidate_trace_pixels = int( + np.count_nonzero(candidate_trace_mask & rooted_trace_mask) + ) + secondary_owned_unrooted_trace_pixels = int( + np.count_nonzero( + candidate_trace_mask + & ~rooted_trace_mask + & (secondary_owner_regions > 0) + ) + ) + candidate_mask_pixels = int(np.count_nonzero(candidate_neurite_mask)) + rooted_candidate_mask_pixels = int( + np.count_nonzero(candidate_neurite_mask & rooted_mask) + ) + unrooted_residual_pixels = int(np.count_nonzero(unrooted_residual)) + secondary_owned_residual_pixels = int( + np.count_nonzero(secondary_owned_residual) + ) + cell_results = _build_cell_results( cell_body_labels, owner_outgrowth, @@ -908,12 +1055,77 @@ def neurite_outgrowth_metaxpress( nuclear_channel_index=( nuclear_stain.channel_index if use_nuclear_stain else -1 ), - resolved_crossovers=len(topology.crossing_nodes), + resolved_crossovers=resolved_crossovers, mean_outgrowth_average_intensity=( float(np.mean(neurite_image[owner_outgrowth > 0])) if np.any(owner_outgrowth > 0) else 0.0 ), + candidate_trace_pixels=candidate_trace_pixels, + rooted_candidate_trace_pixels=rooted_candidate_trace_pixels, + unrooted_candidate_trace_pixels=( + candidate_trace_pixels - rooted_candidate_trace_pixels + ), + rooted_candidate_trace_yield=( + rooted_candidate_trace_pixels / candidate_trace_pixels + if candidate_trace_pixels + else 0.0 + ), + initial_topology_owned_trace_pixels=initial_topology_owned_trace_pixels, + secondary_adopted_trace_pixels=secondary_adopted_trace_pixels, + signal_repaired_trace_pixels=signal_repaired_trace_pixels, + crossing_core_trace_pixels=int(np.count_nonzero(crossing_core_mask)), + final_topology_dropped_trace_pixels=int( + np.count_nonzero(topology_dropped_trace) + ), + final_topology_dropped_crossing_support_trace_pixels=int( + np.count_nonzero(topology_dropped_trace & (crossing_support > 0)) + ), + final_topology_dropped_unrooted_path_trace_pixels=int( + np.count_nonzero(topology_dropped_trace & topology_path_mask) + ), + final_topology_dropped_physically_rooted_path_trace_pixels=int( + np.count_nonzero( + topology_dropped_trace + & topology_path_mask + & physically_soma_rooted_trace + ) + ), + final_topology_dropped_physically_unrooted_path_trace_pixels=int( + np.count_nonzero( + topology_dropped_trace + & topology_path_mask + & ~physically_soma_rooted_trace + ) + ), + final_topology_dropped_unrepresented_trace_pixels=int( + np.count_nonzero(topology_dropped_trace & ~topology_path_mask) + ), + final_topology_added_trace_pixels=int( + np.count_nonzero(topology_added_trace) + ), + final_topology_owned_trace_pixels=final_topology_owned_trace_pixels, + published_owned_trace_pixels=int(np.count_nonzero(rooted_trace_mask)), + secondary_owned_unrooted_trace_pixels=( + secondary_owned_unrooted_trace_pixels + ), + secondary_unowned_unrooted_trace_pixels=( + candidate_trace_pixels + - rooted_candidate_trace_pixels + - secondary_owned_unrooted_trace_pixels + ), + candidate_mask_pixels=candidate_mask_pixels, + rooted_candidate_mask_pixels=rooted_candidate_mask_pixels, + unrooted_residual_pixels=unrooted_residual_pixels, + secondary_owned_residual_pixels=secondary_owned_residual_pixels, + secondary_unowned_residual_pixels=( + unrooted_residual_pixels - secondary_owned_residual_pixels + ), + secondary_owned_residual_fraction=( + secondary_owned_residual_pixels / unrooted_residual_pixels + if unrooted_residual_pixels + else 0.0 + ), ) cell_body_stack = np.zeros(image_array.shape, dtype=np.int32) @@ -934,7 +1146,6 @@ def neurite_outgrowth_metaxpress( neurite_morphology = neurite_morphology.replace_fields( source_plane_index=neurite_channel_index ) - return ( image, DataclassMeasurementColumnarRows( @@ -949,6 +1160,26 @@ def neurite_outgrowth_metaxpress( neurite_stack, unified_neuron_stack, nuclei_stack, + SelectedPlaneImageOutput( + outgrowth_binary.astype(np.uint8, copy=False)[None], + (neurite_channel_index,), + ), + SelectedPlaneImageOutput( + unrooted_residual.astype(np.uint8, copy=False)[None], + (neurite_channel_index,), + ), + SelectedPlaneImageOutput( + secondary_owner_regions.astype(np.int32, copy=False)[None], + (neurite_channel_index,), + ), + SelectedPlaneImageOutput( + topology_dropped_trace.astype(np.uint8, copy=False)[None], + (neurite_channel_index,), + ), + SelectedPlaneImageOutput( + topology_added_trace.astype(np.uint8, copy=False)[None], + (neurite_channel_index,), + ), neurite_morphology, ) @@ -1307,43 +1538,41 @@ def _propagate_neurite_owner_regions( ) -def _adopt_secondary_owned_skeleton( - skeleton: np.ndarray, +def _adopt_secondary_owned_path_segments( + topology: _TopologyResult, owner_skeleton: np.ndarray, secondary_owner_regions: np.ndarray, ) -> np.ndarray: - """Adopt a whole skeleton component when CP gives it one neuron identity.""" + """Partition unowned logical paths by secondary soma ownership. + + Raw connected components are not ownership units: a dense component can + contain multiple branches or resolved crossing arms belonging to different + neurons. The topology owns the first decomposition, while the propagated + secondary labels own the finer boundary between soma territories along an + otherwise uninterrupted path. Rooted paths retain their stronger topology + assignment. Unowned path pixels adopt their positive secondary owner and + are subsequently required to reconnect to that owner's soma through + continuous signal support. Crossing cores remain temporary physical + support and are never assigned here. + """ adopted = np.asarray(owner_skeleton, dtype=np.int32).copy() - components, component_count = ndi.label( - np.asarray(skeleton, dtype=bool), - structure=np.ones((3, 3), dtype=bool), - ) - if component_count == 0: - return adopted + secondary = np.asarray(secondary_owner_regions, dtype=np.int32) + if adopted.shape != secondary.shape: + raise ValueError( + "owner_skeleton and secondary_owner_regions must have the same shape" + ) - minimum_owners = np.full( - component_count + 1, - np.iinfo(np.int32).max, - dtype=np.int32, - ) - maximum_owners = np.zeros(component_count + 1, dtype=np.int32) - foreground_components = components > 0 - for owner_source in (adopted, secondary_owner_regions): - present = foreground_components & (owner_source > 0) - np.minimum.at( - minimum_owners, - components[present], - owner_source[present], - ) - np.maximum.at( - maximum_owners, - components[present], - owner_source[present], - ) - single_owner = (minimum_owners == maximum_owners) & (maximum_owners > 0) - adopted_owners = np.where(single_owner, maximum_owners, 0)[components] - adopted[adopted_owners > 0] = adopted_owners[adopted_owners > 0] + for path_index, coordinates in enumerate(topology.path_coordinates): + if path_index in topology.crossing_core_paths or not len(coordinates): + continue + path_owner = int(topology.path_owners[path_index]) + if path_owner > 0: + continue + secondary_path = secondary[tuple(coordinates.T)] + current = adopted[tuple(coordinates.T)] + assignable = (current == 0) & (secondary_path > 0) + adopted[tuple(coordinates[assignable].T)] = secondary_path[assignable] return adopted @@ -1413,35 +1642,43 @@ def _derive_signal_cell_bodies( local_seeds = seeds[owner_slice] seed = local_seeds == owner seed_coordinates = np.argwhere(seed) + seed_center = seed_coordinates.mean(axis=0) seed_centroid = tuple( int(np.clip(round(value), 0, seed.shape[axis] - 1)) - for axis, value in enumerate(seed_coordinates.mean(axis=0)) + for axis, value in enumerate(seed_center) ) local_foreground_width = ( 2.0 * float(foreground_distance[owner_slice][seed_centroid]) - 1.0 ) if local_foreground_width > settings.approximate_max_width / pixel_size_um: continue - distance_from_seed = ndi.distance_transform_edt(~seed) distance_to_nearest_seed, nearest_seed_coordinates = ndi.distance_transform_edt( local_seeds == 0, return_indices=True, ) nearest_seed = local_seeds[tuple(nearest_seed_coordinates)] local_body_foreground = body_foreground[owner_slice] + rows, columns = np.ogrid[: seed.shape[0], : seed.shape[1]] + distance_from_centroid_squared = ( + (rows - seed_center[0]) ** 2 + (columns - seed_center[1]) ** 2 + ) candidate = ( (nearest_seed == owner) - & (distance_from_seed <= maximum_radius_px) + & (distance_from_centroid_squared <= maximum_radius_px**2) & (distance_to_nearest_seed <= maximum_radius_px) & local_body_foreground ) components, component_count = ndi.label(candidate, structure=connectivity) if component_count == 0: continue + overlapping_components = np.unique(components[seed]) + overlapping_components = overlapping_components[overlapping_components > 0] + if not overlapping_components.size: + continue component = min( - range(1, component_count + 1), + (int(value) for value in overlapping_components), key=lambda value: ( - float(np.min(distance_from_seed[components == value])), + float(np.min(distance_from_centroid_squared[components == value])), value, ), ) @@ -1450,7 +1687,16 @@ def _derive_signal_cell_bodies( continue local_bodies = bodies[owner_slice] local_bodies[body] = owner - return bodies + + # Later seeds can overwrite shared pixels after an earlier body passed the + # area check. Reapply the public minimum-area contract to the final masks. + final_areas = np.bincount( + bodies.ravel(), + minlength=int(seeds.max()) + 1, + ) + keep = final_areas >= minimum_area_px + keep[0] = False + return np.where(keep[bodies], bodies, 0).astype(np.int32, copy=False) def _repair_signal_supported_skeleton( @@ -1617,6 +1863,43 @@ def _relabel(labels: np.ndarray, keep: np.ndarray) -> np.ndarray: return mapping[labels] +def _remove_three_pixel_cycles( + skeleton: np.ndarray, + connectivity: np.ndarray, +) -> np.ndarray: + """Remove endpoint-free three-pixel components that cannot encode a path.""" + + component_labels, component_count = ndi.label( + skeleton, + structure=connectivity, + ) + if component_count == 0: + return skeleton + + component_sizes = np.bincount(component_labels.ravel()) + candidate_labels = np.flatnonzero(component_sizes == 3) + candidate_labels = candidate_labels[candidate_labels != 0] + if len(candidate_labels) == 0: + return skeleton + + neighborhood = connectivity.copy() + neighborhood[(1,) * skeleton.ndim] = False + pixel_degrees = ndi.convolve( + skeleton.astype(np.uint8, copy=False), + neighborhood.astype(np.uint8, copy=False), + mode="constant", + cval=0, + ) + cycle_labels = tuple( + int(component_label) + for component_label in candidate_labels + if np.all(pixel_degrees[component_labels == component_label] == 2) + ) + if not cycle_labels: + return skeleton + return skeleton & ~np.isin(component_labels, cycle_labels) + + def _analyze_topology( skeleton: np.ndarray, cell_body_labels: np.ndarray, @@ -1635,11 +1918,15 @@ def _analyze_topology( # A neurite path requires an edge, not merely a foreground pixel. Skan's # full-neighborhood pixel graph has no paths for isolated vertices, and its # constructor builds the path CSR before exposing n_paths. - neighborhood = ndi.generate_binary_structure(skeleton.ndim, skeleton.ndim) + connectivity = ndi.generate_binary_structure(skeleton.ndim, skeleton.ndim) + neighborhood = connectivity.copy() neighborhood[(1,) * skeleton.ndim] = False skeleton = np.asarray(skeleton, dtype=bool) & ndi.binary_dilation( skeleton, structure=neighborhood ) + # Three mutually adjacent pixels form an endpoint-free cycle. They carry no + # neurite path, and Skan 0.13 cannot construct a path CSR for that graph. + skeleton = _remove_three_pixel_cycles(skeleton, connectivity) if not skeleton.any(): return _empty_topology() @@ -1812,6 +2099,39 @@ def _analyze_topology( path_owners[path_index] = Counter( int(label) for label in labels ).most_common(1)[0][0] + + # Geometric pairing is only provisional until nominal ownership is known. + # When same-owner arms were placed in different geometric pairs, connect + # those arms and give their endpoints one owner-qualified node identity. + # Two arms remain a crossover path; three or more arms are a branch for + # that owner. This prevents an apparent crossing from silently severing a + # soma-rooted neurite that the preceding ownership stage already proved. + crossing_branch_owners: dict[int, set[int]] = defaultdict(set) + for node, (crossing_pairs, _) in crossing_clusters.items(): + endpoints_by_owner: dict[int, list[tuple[int, int]]] = defaultdict(list) + for endpoint in ( + endpoint for pair in crossing_pairs for endpoint in pair + ): + owner = int(path_owners[endpoint[0]]) + if owner > 0: + endpoints_by_owner[owner].append(endpoint) + for owner, endpoints in endpoints_by_owner.items(): + endpoint_groups = { + path_endpoint_groups[path_index][endpoint_index] + for path_index, endpoint_index in endpoints + } + if len(endpoint_groups) <= 1: + continue + owner_paths = sorted({path_index for path_index, _ in endpoints}) + for first, second in combinations(owner_paths, 2): + transitions[first].add(second) + transitions[second].add(first) + merged_group = min(endpoint_groups) + for path_index, endpoint_index in endpoints: + path_endpoint_groups[path_index][endpoint_index] = merged_group + if len(owner_paths) >= 3: + branch_nodes.add(node) + crossing_branch_owners[node].add(owner) roots_by_cell: dict[int, list[int]] = defaultdict(list) for path_index, labels in root_labels_by_path.items(): owner = int(path_owners[path_index]) @@ -1840,12 +2160,25 @@ def _analyze_topology( if degree >= 3: branch_nodes_by_cell[owner].append(node) - used_crossings = { - node - for node in crossing_nodes - if any( - path_owners[path_index] > 0 for path_index in crossing_paths_by_node[node] + active_crossing_paths_by_node: dict[int, tuple[int, ...]] = {} + for node in crossing_nodes: + owner_counts = Counter( + int(path_owners[path_index]) + for path_index in crossing_paths_by_node[node] + if path_owners[path_index] > 0 ) + active_owners = { + owner + for owner, path_count in owner_counts.items() + if path_count == 2 and owner not in crossing_branch_owners[node] + } + active_crossing_paths_by_node[node] = tuple( + path_index + for path_index in crossing_paths_by_node[node] + if path_owners[path_index] in active_owners + ) + used_crossings = { + node for node, paths in active_crossing_paths_by_node.items() if paths } return _TopologyResult( path_owners=path_owners, @@ -1874,7 +2207,7 @@ def _analyze_topology( crossing_paths=frozenset( path_index for node in used_crossings - for path_index in crossing_paths_by_node[node] + for path_index in active_crossing_paths_by_node[node] ), crossing_core_paths=frozenset( path_index @@ -1884,6 +2217,206 @@ def _analyze_topology( ) +def _analyze_owned_topology( + owner_skeleton: np.ndarray, + cell_body_labels: np.ndarray, + pixel_size_um: float, + outgrowth_width_px: float, + *, + shared_crossing_mask: np.ndarray | None = None, +) -> _TopologyResult: + """Analyze each nominal owner without erasing ownership at shared borders. + + A binary union of all owned skeletons reconnects adjacent pixels belonging + to different neurons. Assigning that union back to one owner per Skan path + then discards valid segments by majority vote. Each owner is therefore + analyzed within its own bounded spatial crop and the resulting topologies + are combined only after their nominal identity has been preserved. + """ + + owned = np.asarray(owner_skeleton, dtype=np.int32) + bodies = np.asarray(cell_body_labels, dtype=np.int32) + if owned.shape != bodies.shape: + raise ValueError( + "owner_skeleton and cell_body_labels must have the same shape" + ) + crossing_mask = ( + np.zeros(owned.shape, dtype=bool) + if shared_crossing_mask is None + else np.asarray(shared_crossing_mask, dtype=bool) + ) + if crossing_mask.shape != owned.shape: + raise ValueError( + "shared_crossing_mask and owner_skeleton must have the same shape" + ) + if not np.any(owned > 0): + return _empty_topology() + + body_regions = {int(region.label): region for region in regionprops(bodies)} + owned_regions = {int(region.label): region for region in regionprops(owned)} + margin = max(1, int(np.ceil(outgrowth_width_px)) + 2) + connectivity = np.ones((3, 3), dtype=bool) + crossing_components, crossing_component_count = ndi.label( + crossing_mask, + structure=connectivity, + ) + shared_crossings_by_owner: dict[int, set[int]] = defaultdict(set) + for component in range(1, crossing_component_count + 1): + component_mask = crossing_components == component + adjacent = ndi.binary_dilation( + component_mask, + structure=connectivity, + ) & ~component_mask + for owner in np.unique(owned[adjacent]): + if owner > 0: + shared_crossings_by_owner[int(owner)].add(component) + + path_owners: list[np.ndarray] = [] + path_distances: list[np.ndarray] = [] + path_lengths: list[np.ndarray] = [] + path_euclidean_lengths: list[np.ndarray] = [] + path_coordinates: list[np.ndarray] = [] + path_endpoint_groups: list[tuple[int, int]] = [] + path_branch_types: list[np.ndarray] = [] + endpoint_group_coordinates: dict[int, tuple[float, float]] = {} + transitions: dict[int, tuple[int, ...]] = {} + root_paths_by_cell: dict[int, tuple[int, ...]] = {} + branch_nodes_by_cell: dict[int, tuple[int, ...]] = {} + crossing_nodes: set[int] = set() + crossing_paths: set[int] = set() + crossing_core_paths: set[int] = set() + path_offset = 0 + endpoint_group_offset = 0 + node_offset = 0 + + for owner in sorted(owned_regions): + owned_region = owned_regions[owner] + bounds = [owned_region.bbox] + body_region = body_regions.get(owner) + if body_region is not None: + bounds.append(body_region.bbox) + owner_slice = ( + slice( + max(0, min(bound[0] for bound in bounds) - margin), + min(owned.shape[0], max(bound[2] for bound in bounds) + margin), + ), + slice( + max(0, min(bound[1] for bound in bounds) - margin), + min(owned.shape[1], max(bound[3] for bound in bounds) + margin), + ), + ) + local_owner_mask = owned[owner_slice] == owner + owner_crossings = shared_crossings_by_owner.get(owner, set()) + if owner_crossings: + local_owner_mask |= np.isin( + crossing_components[owner_slice], + tuple(sorted(owner_crossings)), + ) + local_owned = np.where(local_owner_mask, owner, 0).astype( + np.int32, + copy=False, + ) + local = _analyze_topology( + local_owned > 0, + bodies[owner_slice], + pixel_size_um, + outgrowth_width_px, + assigned_path_labels=local_owned, + ) + local_path_count = len(local.path_owners) + if local_path_count == 0: + continue + + spatial_offset = np.array( + [owner_slice[0].start, owner_slice[1].start], + dtype=int, + ) + path_owners.append(local.path_owners) + path_distances.append(local.path_distances) + path_lengths.append(local.path_lengths) + path_euclidean_lengths.append(local.path_euclidean_lengths) + path_coordinates.extend( + coordinates + spatial_offset for coordinates in local.path_coordinates + ) + path_branch_types.append(local.path_branch_types) + + local_group_ids = set(local.endpoint_group_coordinates) + group_mapping = { + group_id: group_id + endpoint_group_offset + for group_id in local_group_ids + } + path_endpoint_groups.extend( + tuple(group_mapping[group_id] for group_id in groups) + for groups in local.path_endpoint_groups + ) + endpoint_group_coordinates.update( + { + group_mapping[group_id]: tuple( + coordinate + spatial_offset[axis] + for axis, coordinate in enumerate(coordinates) + ) + for group_id, coordinates in local.endpoint_group_coordinates.items() + } + ) + transitions.update( + { + path_index + path_offset: tuple( + neighbor + path_offset for neighbor in neighbors + ) + for path_index, neighbors in local.transitions.items() + } + ) + for cell, roots in local.root_paths_by_cell.items(): + root_paths_by_cell[int(cell)] = tuple( + root + path_offset for root in roots + ) + + local_node_ids = set(local.crossing_nodes) + local_node_ids.update( + node + for nodes in local.branch_nodes_by_cell.values() + for node in nodes + ) + branch_nodes_by_cell.update( + { + int(cell): tuple(node + node_offset for node in nodes) + for cell, nodes in local.branch_nodes_by_cell.items() + } + ) + crossing_nodes.update(node + node_offset for node in local.crossing_nodes) + crossing_paths.update( + path_index + path_offset for path_index in local.crossing_paths + ) + crossing_core_paths.update( + path_index + path_offset for path_index in local.crossing_core_paths + ) + + path_offset += local_path_count + if local_group_ids: + endpoint_group_offset += max(local_group_ids) + if local_node_ids: + node_offset += max(local_node_ids) + 1 + + if not path_owners: + return _empty_topology() + return _TopologyResult( + path_owners=np.concatenate(path_owners), + path_distances=np.concatenate(path_distances), + path_lengths=np.concatenate(path_lengths), + path_euclidean_lengths=np.concatenate(path_euclidean_lengths), + path_coordinates=tuple(path_coordinates), + path_endpoint_groups=tuple(path_endpoint_groups), + path_branch_types=np.concatenate(path_branch_types), + endpoint_group_coordinates=endpoint_group_coordinates, + transitions=transitions, + root_paths_by_cell=root_paths_by_cell, + branch_nodes_by_cell=branch_nodes_by_cell, + crossing_nodes=frozenset(crossing_nodes), + crossing_paths=frozenset(crossing_paths), + crossing_core_paths=frozenset(crossing_core_paths), + ) + + def _merge_nearby_nodes( nodes: Sequence[int], node_coordinates: Mapping[int, np.ndarray], @@ -2407,6 +2940,74 @@ def _render_owned_skeleton( return owner_skeleton +def _render_topology_path_mask( + shape: tuple[int, int], + topology: _TopologyResult, +) -> np.ndarray: + """Render every graph path independently of its final rooted owner.""" + + path_mask = np.zeros(shape, dtype=bool) + for coordinates in topology.path_coordinates: + path_mask[tuple(coordinates.T)] = True + return path_mask + + +def _physically_soma_rooted_owner_mask( + owner_skeleton: np.ndarray, + cell_body_labels: np.ndarray, + *, + maximum_root_distance: int, +) -> np.ndarray: + """Mark same-owner pixel components that reach their soma neighborhood.""" + + owned = np.asarray(owner_skeleton, dtype=np.int32) + bodies = np.asarray(cell_body_labels, dtype=np.int32) + if owned.shape != bodies.shape: + raise ValueError( + "owner_skeleton and cell_body_labels must have the same shape" + ) + if maximum_root_distance < 0: + raise ValueError("maximum_root_distance must be >= 0") + + expanded_bodies = expand_labels(bodies, distance=maximum_root_distance) + connectivity = np.ones((3, 3), dtype=bool) + rooted = np.zeros(owned.shape, dtype=bool) + body_regions = {int(region.label): region for region in regionprops(bodies)} + for owner_region in regionprops(owned): + owner = int(owner_region.label) + bounds = [owner_region.bbox] + body_region = body_regions.get(owner) + if body_region is not None: + bounds.append(body_region.bbox) + owner_slice = ( + slice( + max(0, min(bound[0] for bound in bounds) - maximum_root_distance), + min( + owned.shape[0], + max(bound[2] for bound in bounds) + maximum_root_distance, + ), + ), + slice( + max(0, min(bound[1] for bound in bounds) - maximum_root_distance), + min( + owned.shape[1], + max(bound[3] for bound in bounds) + maximum_root_distance, + ), + ), + ) + local_components, _ = ndi.label( + owned[owner_slice] == owner, + structure=connectivity, + ) + root_components = np.unique( + local_components[expanded_bodies[owner_slice] == owner] + ) + root_components = root_components[root_components > 0] + if root_components.size: + rooted[owner_slice] |= np.isin(local_components, root_components) + return rooted + + def _render_crossing_support( shape: tuple[int, int], topology: _TopologyResult, @@ -2435,6 +3036,49 @@ def _render_crossing_support( return support +def _render_crossing_core_mask( + shape: tuple[int, int], + topology: _TopologyResult, +) -> np.ndarray: + """Render physical pixels shared by the resolved logical crossing paths.""" + + crossing_core = np.zeros(shape, dtype=bool) + for path_index in topology.crossing_core_paths: + coordinates = topology.path_coordinates[path_index] + crossing_core[tuple(coordinates.T)] = True + return crossing_core + + +def _count_multi_owner_crossings( + crossing_core_mask: np.ndarray, + owner_support: np.ndarray, +) -> int: + """Count physical crossing cores joining two or more rooted owners.""" + + crossing_mask = np.asarray(crossing_core_mask, dtype=bool) + owners = np.asarray(owner_support, dtype=np.int32) + if crossing_mask.shape != owners.shape: + raise ValueError( + "crossing_core_mask and owner_support must have the same shape" + ) + connectivity = np.ones((3, 3), dtype=bool) + components, component_count = ndi.label( + crossing_mask, + structure=connectivity, + ) + resolved = 0 + for component in range(1, component_count + 1): + component_mask = components == component + adjacent = ndi.binary_dilation( + component_mask, + structure=connectivity, + ) & ~component_mask + adjacent_owners = np.unique(owners[adjacent]) + if np.count_nonzero(adjacent_owners > 0) >= 2: + resolved += 1 + return resolved + + def _expand_skeleton_ownership( owner_skeleton: np.ndarray, outgrowth_binary: np.ndarray, @@ -2568,6 +3212,31 @@ def _build_summary( nuclear_channel_index: int, resolved_crossovers: int, mean_outgrowth_average_intensity: float, + candidate_trace_pixels: int, + rooted_candidate_trace_pixels: int, + unrooted_candidate_trace_pixels: int, + rooted_candidate_trace_yield: float, + initial_topology_owned_trace_pixels: int, + secondary_adopted_trace_pixels: int, + signal_repaired_trace_pixels: int, + crossing_core_trace_pixels: int, + final_topology_dropped_trace_pixels: int, + final_topology_dropped_crossing_support_trace_pixels: int, + final_topology_dropped_unrooted_path_trace_pixels: int, + final_topology_dropped_physically_rooted_path_trace_pixels: int, + final_topology_dropped_physically_unrooted_path_trace_pixels: int, + final_topology_dropped_unrepresented_trace_pixels: int, + final_topology_added_trace_pixels: int, + final_topology_owned_trace_pixels: int, + published_owned_trace_pixels: int, + secondary_owned_unrooted_trace_pixels: int, + secondary_unowned_unrooted_trace_pixels: int, + candidate_mask_pixels: int, + rooted_candidate_mask_pixels: int, + unrooted_residual_pixels: int, + secondary_owned_residual_pixels: int, + secondary_unowned_residual_pixels: int, + secondary_owned_residual_fraction: float, ) -> NeuriteOutgrowthSummary: cell_count = len(cell_results) total_outgrowth = float(sum(row.total_outgrowth_um for row in cell_results)) @@ -2601,4 +3270,43 @@ def _build_summary( ), mean_outgrowth_average_intensity=mean_outgrowth_average_intensity, resolved_crossovers=resolved_crossovers, + candidate_trace_pixels=candidate_trace_pixels, + rooted_candidate_trace_pixels=rooted_candidate_trace_pixels, + unrooted_candidate_trace_pixels=unrooted_candidate_trace_pixels, + rooted_candidate_trace_yield=rooted_candidate_trace_yield, + initial_topology_owned_trace_pixels=initial_topology_owned_trace_pixels, + secondary_adopted_trace_pixels=secondary_adopted_trace_pixels, + signal_repaired_trace_pixels=signal_repaired_trace_pixels, + crossing_core_trace_pixels=crossing_core_trace_pixels, + final_topology_dropped_trace_pixels=final_topology_dropped_trace_pixels, + final_topology_dropped_crossing_support_trace_pixels=( + final_topology_dropped_crossing_support_trace_pixels + ), + final_topology_dropped_unrooted_path_trace_pixels=( + final_topology_dropped_unrooted_path_trace_pixels + ), + final_topology_dropped_physically_rooted_path_trace_pixels=( + final_topology_dropped_physically_rooted_path_trace_pixels + ), + final_topology_dropped_physically_unrooted_path_trace_pixels=( + final_topology_dropped_physically_unrooted_path_trace_pixels + ), + final_topology_dropped_unrepresented_trace_pixels=( + final_topology_dropped_unrepresented_trace_pixels + ), + final_topology_added_trace_pixels=final_topology_added_trace_pixels, + final_topology_owned_trace_pixels=final_topology_owned_trace_pixels, + published_owned_trace_pixels=published_owned_trace_pixels, + secondary_owned_unrooted_trace_pixels=( + secondary_owned_unrooted_trace_pixels + ), + secondary_unowned_unrooted_trace_pixels=( + secondary_unowned_unrooted_trace_pixels + ), + candidate_mask_pixels=candidate_mask_pixels, + rooted_candidate_mask_pixels=rooted_candidate_mask_pixels, + unrooted_residual_pixels=unrooted_residual_pixels, + secondary_owned_residual_pixels=secondary_owned_residual_pixels, + secondary_unowned_residual_pixels=secondary_unowned_residual_pixels, + secondary_owned_residual_fraction=secondary_owned_residual_fraction, ) diff --git a/packaging/codex/openhcs/skills/use-openhcs/SKILL.md b/packaging/codex/openhcs/skills/use-openhcs/SKILL.md index 084306dc84..5246b082cf 100644 --- a/packaging/codex/openhcs/skills/use-openhcs/SKILL.md +++ b/packaging/codex/openhcs/skills/use-openhcs/SKILL.md @@ -14,3 +14,20 @@ description: Operate local OpenHCS microscopy workflows through the bundled MCP 7. Validate and compile before execution. Do not infer that source code, UI state, or an earlier validation result implies a current compiled plan. 8. Start read-only. Use capability-registry metadata as the authority for mutation and exposure; before mutation, execution, UI actions, viewer launch, network use, or external data exposure, show the target/change, obtain approval, and refresh revision or request tokens. 9. Preserve the active ownership route. Discover the GUI bridge before UI tools and apply code/state changes with current tokens. Use headless tools only when their workflow group is exposed. Treat structured errors and recovery hints as authoritative; never bypass path policy, stale-process checks, compile requirements, or bridge authentication. + +## Image-analysis QA + +For segmentation, neurite tracing, faint structures, or a report that an overlay +looks wrong, load both `image_analysis_workflow` and `viewer_review` before +tuning or judging the result. These MCP contexts supply the shared raw-first +biological interpretation, native-coordinate inspection, display-window, +stage-diagnostic, and validation-split rules; do not depend on a prior agent's +conversation or on a separately installed assay skill. Follow the earliest +failed-stage decision through one bounded diagnostic and inspect its retained +artifacts before expanding the run. + +For apparent round-object over-segmentation, discover the registered +`inspect_metaxpress_round_objects` function and inspect its typed labels and +measurements at the same raw coordinates. Interpret them by the canonical +`image_analysis_workflow` policy; do not invent a second segmentation or a +viewer-only diagnosis. diff --git a/tests/integration/test_neurite_outgrowth_synthetic_plate.py b/tests/integration/test_neurite_outgrowth_synthetic_plate.py index b1c99648ed..a959eb254a 100644 --- a/tests/integration/test_neurite_outgrowth_synthetic_plate.py +++ b/tests/integration/test_neurite_outgrowth_synthetic_plate.py @@ -2,6 +2,7 @@ import csv import io +import json import logging from multiprocessing.shared_memory import SharedMemory from pathlib import Path @@ -36,7 +37,7 @@ from skimage.draw import disk, line from objectstate.lazy_factory import ensure_global_config_context -from openhcs.constants import GroupBy, Microscope, VariableComponents +from openhcs.constants import AllComponents, GroupBy, Microscope, VariableComponents from openhcs.core.config import ( AnalysisConsolidationConfig, GlobalPipelineConfig, @@ -50,11 +51,17 @@ VFSConfig, ) from openhcs.core.callable_contract import CallableContract +from openhcs.core.artifacts import ObjectLabelsArtifactType from openhcs.core.orchestrator.orchestrator import PipelineOrchestrator from openhcs.core.progress import ProgressEvent, set_progress_queue from openhcs.core.progress.live_measurements import LiveMeasurementProgressPayload from openhcs.core.steps import FunctionStep from openhcs.core.source_metadata import SourceVoxelSpacing +from openhcs.core.runtime_plane_projection import RuntimePlaneAxis +from openhcs.core.source_workspace_projection import ( + VirtualWorkspacePathLookup, + VirtualWorkspaceSourceProjection, +) from openhcs.processing.materialization.core import ( Output, ViewerStreamBackendCallKwargs, @@ -162,7 +169,7 @@ def test_neurite_outgrowth_runs_on_synthetic_plate_as_2d_channel_stack( def observe_dense_output(output, components): projected = original_with_components(output, components) - if projected.path.endswith(".labels.tif"): + if projected.path.endswith((".labels.tif", ".checkpoint.tif")): dense_outputs[projected.path] = projected return projected @@ -178,6 +185,14 @@ def observe_dense_output(output, components): ) compiled_context = compilation.runtime_contexts["A01"] compiled_plan = compiled_context.step_plans[0] + checkpoint_plan = next( + output + for output in compiled_plan.artifact_outputs.values() + if output.name == "neurite_candidate_mask" + ) + assert checkpoint_plan.group_component is AllComponents.SITE + assert checkpoint_plan.group_scope_sources() + assert checkpoint_plan.source_context_source() is None assert compiled_plan.variable_components == [VariableComponents.CHANNEL] assert compiled_plan.group_by is GroupBy.SITE compiled_pattern = compiled_plan.compiled_function_pattern @@ -280,6 +295,7 @@ def observe_dense_output(output, components): assert all("_w2_" in path.name for path in roi_paths if "nuclei" in path.name) assert all(load_rois_from_zip(path) for path in roi_paths) + all_label_paths = [] for artifact_name, expected_labels in zip( ("cell_bodies", "neurite_outgrowth", "neurons", "nuclei"), expected[3:7], @@ -287,14 +303,64 @@ def observe_dense_output(output, components): ): label_paths = tuple(tmp_path.rglob(f"*_{artifact_name}_step0.labels.tif")) assert len(label_paths) == 2 + all_label_paths.extend(label_paths) for label_path in label_paths: retained = tifffile.imread(label_path) assert retained.dtype == expected_labels.dtype np.testing.assert_array_equal(retained, expected_labels) + checkpoint_paths = [] + for artifact_name, expected_checkpoint in zip( + ( + "neurite_candidate_mask", + "neurite_unrooted_residual", + "neurite_secondary_ownership", + "neurite_topology_dropped_trace", + "neurite_topology_added_trace", + ), + expected[7:12], + strict=True, + ): + paths = tuple(tmp_path.rglob(f"*_{artifact_name}.checkpoint.tif")) + assert len(paths) == 2 + checkpoint_paths.extend(paths) + for path in paths: + retained = tifffile.imread(path) + np.testing.assert_array_equal( + retained, + np.asarray(expected_checkpoint)[0], + ) + assert len({path.name for path in checkpoint_paths}) == 10 + + assert compiled_plan.output_plate_root is not None + output_plate_root = Path(compiled_plan.output_plate_root) + projected_label_paths = tuple( + path for path in all_label_paths if path.is_relative_to(output_plate_root) + ) + assert len(projected_label_paths) == 8 + metadata_path = output_plate_root / "openhcs_metadata.json" + source_projection = VirtualWorkspaceSourceProjection.from_openhcs_metadata( + output_plate_root, + json.loads(metadata_path.read_text()), + ) + for label_path in projected_label_paths: + virtual_path = str(label_path.relative_to(output_plate_root)) + projection = source_projection.require_source_projection_for( + VirtualWorkspacePathLookup.from_paths( + virtual_path, + str(label_path), + ) + ) + assert projection.artifact_kind is ObjectLabelsArtifactType + assert projection.address is None + assert projection.execution_scope is not None + assert projection.image_metadata is not None + assert projection.image_metadata.plane_axis is RuntimePlaneAxis.RUNTIME_SLICE + assert projection.image_metadata.source_provenance.source_plane_count == 2 + # Exercise the real stream projection of the compiled writer outputs. # Artifact storage axes are legitimately empty; source image planes are not. - assert len(dense_outputs) == 8 + assert len(dense_outputs) == 18 stream_kwargs = ViewerStreamBackendCallKwargs( ViewerStreamBackendKwargs( ViewerStreamRequest( @@ -324,9 +390,22 @@ def observe_dense_output(output, components): tuple(dense_outputs.values()) ): request = kwargs["stream_request"] - assert request.source.item_fields["plane_component_values"] == { - "channel": ["1", "2"] - } + checkpoint_batch = all( + output.path.endswith(".checkpoint.tif") for output in outputs + ) + if checkpoint_batch: + assert "plane_component_values" not in request.source.item_fields + assert all( + request.source.metadata.component_metadata_for_item( + output.path, 0 + )["channel"] + == 1 + for output in outputs + ) + else: + assert request.source.item_fields["plane_component_values"] == { + "channel": ["1", "2"] + } batch = StreamingBatchMessageBuilder.build( backend, StreamingBatchMessageRequest( @@ -344,13 +423,16 @@ def observe_dense_output(output, components): # This fixture injects physical pixel_size into the callable, # but does not declare voxel spacing on its runtime images. assert output.metadata.source_voxel_spacing == SourceVoxelSpacing() - assert item["plane_component_values"] == {"channel": ["1", "2"]} - assert ( - "channel" - not in request.source.metadata.component_metadata_for_item( - output.path, 0 + if checkpoint_batch: + assert "_w1_" in Path(output.path).name + else: + assert item["plane_component_values"] == {"channel": ["1", "2"]} + assert ( + "channel" + not in request.source.metadata.component_metadata_for_item( + output.path, 0 + ) ) - ) memory = SharedMemory(name=item["shm_name"]) try: transmitted = np.ndarray( diff --git a/tests/unit/agent/test_image_analysis_qa.py b/tests/unit/agent/test_image_analysis_qa.py index eb0fcac090..ff73c8ec30 100644 --- a/tests/unit/agent/test_image_analysis_qa.py +++ b/tests/unit/agent/test_image_analysis_qa.py @@ -56,6 +56,13 @@ def test_repair_guidance_is_derived_from_every_typed_gate_and_measure() -> None: assert "subtract the accepted candidate mask" in guidance assert "diagnostic evidence rather than an automatic replacement" in guidance assert "owner cardinality per connected component" in guidance + assert "shared crossing-core trace pixels" in guidance + assert "dropped graph-path pixels rejected as unrooted" in guidance + assert "physically soma-rooted dropped path pixels" in guidance + assert "physically soma-detached dropped path pixels" in guidance + assert "dropped trace pixels absent from final path graph" in guidance + assert "owned trace pixels dropped by final topology" in guidance + assert "final-topology added shared-core pixels" in guidance assert "lowering the detection threshold cannot repair it" in guidance assert "declare the permissive value only on the dataset or preset" in guidance assert "distance, ownership, and response alone are insufficient" in guidance @@ -80,6 +87,18 @@ def test_repair_guidance_is_derived_from_every_typed_gate_and_measure() -> None: assert "black, empty, stale, or mismatched capture" in guidance assert "verify every claimed durable label or measurement path exists" in guidance assert "same-identity containment" in guidance + assert "shared crossing-core mask" in guidance + assert "net pixel-count change is not evidence of pruning" in guidance + assert ( + "require multiple independently supported nuclear intensity centres" in guidance + ) + assert "outline shape alone does not prove multiple nuclei" in guidance + assert "round_object_prefilter" in guidance + assert "round_object_adjacent_satellite_candidates" in guidance + assert "source_component_output_count" in guidance + assert "separate threshold-stage component from a watershed split" in guidance + assert "Never globally reject weak-core objects" in guidance + assert "preserving isolated faint objects and multi-centre controls" in guidance def test_trace_growth_requires_more_root_connected_continuity() -> None: diff --git a/tests/unit/agent/test_progressive_authoring_context.py b/tests/unit/agent/test_progressive_authoring_context.py index 383f805a91..e9e75cf2ae 100644 --- a/tests/unit/agent/test_progressive_authoring_context.py +++ b/tests/unit/agent/test_progressive_authoring_context.py @@ -120,6 +120,10 @@ def test_operating_guides_cover_resume_and_safe_execution_boundaries() -> None: assert "preserve earlier outputs in a separate destination" in first_use assert "Confirm a named tool is exposed" in first_use assert agent_capabilities.ui_list_actions.name in first_use + assert agent_capabilities.ui_list_windows.name in first_use + assert agent_capabilities.ui_get_widget_tree.name in first_use + assert agent_capabilities.ui_invoke_widget_action.name in first_use + assert "cancel unsolicited update/restart prompts" in first_use assert "observation timeout does not mean the job failed" in ui assert "do not issue another Run" in ui assert ui.count("only for bridge receipt terminality") == 1 @@ -437,6 +441,10 @@ def test_onboarding_surfaces_link_to_the_canonical_image_analysis_context() -> N for surface in (skill, default_prompt, client_guide, server_instructions): assert context_kind in surface + assert "inspect_metaxpress_round_objects" in skill + assert "typed labels" in skill + assert "measurements at the same raw coordinates" in skill + canonical_rules = ( "must not fit a separate percentile pair per field", "blinded, spatially distributed representative set", diff --git a/tests/unit/test_count_cells_simple.py b/tests/unit/test_count_cells_simple.py index dde11bd43e..d1ca06d631 100644 --- a/tests/unit/test_count_cells_simple.py +++ b/tests/unit/test_count_cells_simple.py @@ -4,6 +4,7 @@ import numpy as np import pytest +from scipy import ndimage as ndi from skimage.draw import disk, ellipse from skimage.measure import regionprops @@ -12,6 +13,7 @@ ObjectLabelsArtifactType, ) from openhcs.core.callable_contract import CallableContract +from openhcs.core.runtime_output_matching import RuntimeReturnedOutputMatcher from openhcs.processing.backends.analysis.count_cells_simple import ( Foreground, MetaXpressW2Settings, @@ -21,6 +23,8 @@ ThresholdMethod, count_cells_simple, count_cells_simple_dual_channel, + inspect_metaxpress_round_objects, + round_object_segmentation_stages, segment_metaxpress_round_objects, ) @@ -404,7 +408,111 @@ def test_width_based_watershed_preserves_one_elongated_nucleus(rotation_degrees) assert labels[48, 48] == 1 -def test_label_indexed_axis_lengths_match_regionprops(): +def test_width_based_watershed_splits_touching_nuclei_below_max_width_area(): + image = np.zeros((96, 96), dtype=np.float64) + centers = ((48, 43), (48, 53)) + for center in centers: + rows, columns = disk(center, 6, shape=image.shape) + image[rows, columns] = 1000.0 + rows, columns = disk(center, 2, shape=image.shape) + image[rows, columns] = 1800.0 + settings = MetaXpressWavelengthSettings( + approx_min_width=5.0, + approx_max_width=30.0, + intensity_above_local_background=300.0, + ) + + labels = segment_metaxpress_round_objects(image, settings, 1.0) + + foreground_area = np.count_nonzero(image) + maximum_object_area = np.pi * (settings.approx_max_width / 2.0) ** 2 + assert foreground_area < maximum_object_area + assert labels.max() == 2 + assert labels[centers[0]] != labels[centers[1]] + + +def test_width_based_watershed_preserves_unequal_touching_nucleus_peaks(): + image = np.zeros((96, 96), dtype=np.float64) + centers_and_radii = (((48, 44), 6), ((48, 52), 5)) + for center, radius in centers_and_radii: + rows, columns = disk(center, radius, shape=image.shape) + image[rows, columns] = 1000.0 + rows, columns = disk(center, 2, shape=image.shape) + image[rows, columns] = 1800.0 + settings = MetaXpressWavelengthSettings( + approx_min_width=5.0, + approx_max_width=30.0, + intensity_above_local_background=300.0, + ) + + labels = segment_metaxpress_round_objects(image, settings, 1.3556) + + centers = tuple(center for center, _ in centers_and_radii) + assert labels.max() == 2 + assert labels[centers[0]] != labels[centers[1]] + + +def test_round_object_declumping_uses_distinct_intensity_centers_in_one_silhouette(): + rows, columns = np.mgrid[:128, :128] + image = np.full((128, 128), 100.0) + foreground = np.zeros(image.shape, dtype=bool) + foreground_rows, foreground_columns = ellipse(64, 64, 10, 18, shape=image.shape) + foreground[foreground_rows, foreground_columns] = True + image[foreground] = 350.0 + centers = ((64, 58), (64, 70)) + for center, amplitude in zip(centers, (1000.0, 800.0), strict=True): + image += amplitude * np.exp( + -((rows - center[0]) ** 2 + (columns - center[1]) ** 2) / 8.0 + ) + settings = MetaXpressWavelengthSettings( + approx_min_width=5.0, + approx_max_width=50.0, + intensity_above_local_background=200.0, + ) + + labels = segment_metaxpress_round_objects(image, settings, 1.3556) + + assert ndi.label(foreground)[1] == 1 + assert labels.max() == 2 + assert labels[centers[0]] != labels[centers[1]] + + +def test_intensity_marker_refuses_shape_only_split_without_two_centers(): + component = np.zeros((96, 96), dtype=bool) + for center in ((48, 43), (48, 53)): + rows, columns = disk(center, 8, shape=component.shape) + component[rows, columns] = True + labeled, _ = ndi.label(component) + rows, columns = np.mgrid[:96, :96] + one_center_surface = 1000.0 * np.exp( + -((rows - 48) ** 2 + (columns - 43) ** 2) / 32.0 + ) + + shape_only = count_cells_simple_module._watershed_large_objects( + labeled, + split_size=100, + watershed_max_size=None, + min_distance=3, + footprint_size=3, + peak_prominence=1.0, + ) + intensity_supported = count_cells_simple_module._watershed_large_objects( + labeled, + split_size=100, + watershed_max_size=None, + min_distance=3, + footprint_size=3, + peak_prominence=1.0, + marker_image=one_center_surface, + marker_smoothing_sigma=1.0, + marker_peak_prominence=50.0, + ) + + assert shape_only.max() > 1 + assert intensity_supported.max() == 1 + + +def test_label_indexed_shape_statistics_match_regionprops(): labels = np.zeros((128, 144), dtype=np.int32) for label, center, radii, rotation in ( (1, (0, 0), (9, 7), 0.0), @@ -419,13 +527,22 @@ def test_label_indexed_axis_lengths_match_regionprops(): ) labels[rows, columns] = label - major_lengths, minor_lengths = count_cells_simple_module._axis_lengths_by_label( - labels - ) + statistics = count_cells_simple_module._shape_statistics_by_label(labels) for region in regionprops(labels): - assert major_lengths[region.label] == pytest.approx(region.axis_major_length) - assert minor_lengths[region.label] == pytest.approx(region.axis_minor_length) + assert statistics.counts[region.label] == region.area + assert statistics.centroid_rows_px[region.label] == pytest.approx( + region.centroid[0] + ) + assert statistics.centroid_columns_px[region.label] == pytest.approx( + region.centroid[1] + ) + assert statistics.major_axis_lengths_px[region.label] == pytest.approx( + region.axis_major_length + ) + assert statistics.minor_axis_lengths_px[region.label] == pytest.approx( + region.axis_minor_length + ) def test_round_object_width_filter_does_not_iterate_region_objects(monkeypatch): @@ -454,11 +571,152 @@ def reject_region_iteration(*args, **kwargs): assert labels[48, 48] == 1 +def test_round_object_diagnostics_preserve_kernel_output_and_rejection_identity(): + image = np.zeros((2, 96, 96), dtype=np.float32) + for center, radius in (((25, 25), 7), ((70, 70), 1)): + rr, cc = disk(center, radius, shape=image.shape[1:]) + image[0, rr, cc] = 1000.0 + image[1] = 123.0 + original = image.copy() + settings = MetaXpressWavelengthSettings( + channel_index=0, + approx_min_width=5.0, + approx_max_width=30.0, + intensity_above_local_background=200.0, + ) + stages = round_object_segmentation_stages(image[0], settings, 1.0) + returned = unwrap(inspect_metaxpress_round_objects)( + image, + settings=settings, + pixel_size=1.0, + ) + raw, measurements, prefilter, accepted, weak_core, adjacent_satellites = returned + contract = CallableContract.from_callable(inspect_metaxpress_round_objects) + matched = RuntimeReturnedOutputMatcher(contract, returned).resolve() + assert ( + matched[count_cells_simple_module.ROUND_OBJECT_WIDTHS_OUTPUT.ref()] + is measurements + ) + assert ( + matched[count_cells_simple_module.ROUND_OBJECT_PREFILTER_OUTPUT.ref()] + is prefilter + ) + assert ( + matched[count_cells_simple_module.ROUND_OBJECT_ACCEPTED_OUTPUT.ref()] + is accepted + ) + assert ( + matched[count_cells_simple_module.ROUND_OBJECT_WEAK_CORE_OUTPUT.ref()] + is weak_core + ) + assert ( + matched[ + count_cells_simple_module.ROUND_OBJECT_ADJACENT_SATELLITE_OUTPUT.ref() + ] + is adjacent_satellites + ) + assert raw is image + np.testing.assert_array_equal(image, original) + np.testing.assert_array_equal(prefilter[0], stages.prefilter_labels) + np.testing.assert_array_equal( + accepted[0], + segment_metaxpress_round_objects( + image[0], + settings, + 1.0, + ), + ) + assert not np.any(prefilter[1]) + assert not np.any(accepted[1]) + assert not np.any(weak_core[1]) + assert not np.any(adjacent_satellites[1]) + rows = _rows(measurements) + assert len(rows) == 2 + for row in rows: + support = prefilter[0] == row["object_label"] + assert row["area_pixels"] == np.count_nonzero(support) + assert np.all(accepted[0][support] == row["accepted_label"]) + assert row["source_component_output_count"] == 1 + assert row["split_from_source_component"] is False + expected_centroid = regionprops(support.astype(np.uint8))[0].centroid + assert row["centroid_row_px"] == pytest.approx(expected_centroid[0]) + assert row["centroid_column_px"] == pytest.approx(expected_centroid[1]) + assert row["peak_intensity_above_local_background"] >= row[ + "mean_intensity_above_local_background" + ] + assert row["core_support_threshold"] == 400.0 + assert row["weak_core_candidate"] == ( + bool(stages.width_keep_mask[row["object_label"]]) + and row["peak_intensity_above_local_background"] < 400.0 + ) + assert row["rejected_as_adjacent_satellite"] is False + width_accepted = 5.0 <= row["minor_axis_um"] <= 30.0 + assert (row["accepted_label"] > 0) == width_accepted + assert {row["accepted_label"] for row in rows} == {0, 1} + + +def test_round_object_diagnostics_report_watershed_source_component_lineage(): + image = np.zeros((1, 96, 96), dtype=np.float32) + centers = ((48, 43), (48, 53)) + for center in centers: + rr, cc = disk(center, 6, shape=image.shape[1:]) + image[0, rr, cc] = 1000.0 + rr, cc = disk(center, 2, shape=image.shape[1:]) + image[0, rr, cc] = 1800.0 + settings = MetaXpressWavelengthSettings( + channel_index=0, + approx_min_width=5.0, + approx_max_width=30.0, + intensity_above_local_background=300.0, + ) + + _, measurements, prefilter, accepted, _, _ = unwrap( + inspect_metaxpress_round_objects + )( + image, + settings=settings, + pixel_size=1.0, + ) + + rows = _rows(measurements) + assert len(rows) == 2 + assert np.count_nonzero(np.unique(prefilter)) == 2 + assert accepted.max() == 2 + assert {row["source_component_label"] for row in rows} == {1} + assert {row["source_component_output_count"] for row in rows} == {2} + assert {row["split_from_source_component"] for row in rows} == {True} + + +def test_adjacent_satellite_filter_is_conjunctive_and_keeps_isolated_faint_objects(): + labels = np.zeros((48, 64), dtype=np.int32) + labels[20:23, 20:25] = 1 + labels[18:30, 26:38] = 2 + labels[35:38, 4:9] = 3 + labels[8:11, 50:55] = 4 + counts = np.bincount(labels.ravel()) + peaks = np.array([0.0, 280.0, 900.0, 280.0, 900.0]) + width_keep = np.array([False, True, True, True, True]) + + rejected = count_cells_simple_module._adjacent_satellite_mask( + labels, + counts, + peaks, + width_keep, + maximum_candidate_area=22, + minimum_core_response=400.0, + maximum_gap_px=2, + ) + + assert rejected.tolist() == [False, True, False, False, False] + + def test_width_settings_derive_watershed_for_touching_w1_nuclei(): image = np.full((2, 64, 64), 100.0) for center in ((32, 27), (32, 37)): rr, cc = disk(center, 6, shape=image.shape[1:]) image[0, rr, cc] = 1000.0 + rr, cc = disk(center, 2, shape=image.shape[1:]) + image[0, rr, cc] = 1800.0 _, results, _, w1_labels, _ = _count_cells_simple_dual_channel_impl()( image, diff --git a/tests/unit/test_neurite_outgrowth.py b/tests/unit/test_neurite_outgrowth.py index b006b80509..7b0a998c46 100644 --- a/tests/unit/test_neurite_outgrowth.py +++ b/tests/unit/test_neurite_outgrowth.py @@ -10,6 +10,9 @@ from skimage.draw import disk, line from openhcs.core.artifacts import ( + ArtifactSidecarRole, + ArtifactViewerStreaming, + ImageArtifactType, MeasurementsArtifactType, ObjectLabelsArtifactType, SpatialGraphArtifactType, @@ -28,15 +31,18 @@ MetaXpressNuclearSettings, MetaXpressOutgrowthSettings, NeuriteIllumination, - _adopt_secondary_owned_skeleton, + _adopt_secondary_owned_path_segments, + _analyze_owned_topology, _analyze_topology, _build_neurite_morphology_graph, _cell_body_contract_candidates, _derive_signal_cell_bodies, _expand_skeleton_ownership, _identify_cell_bodies_cellprofiler, + _physically_soma_rooted_owner_mask, _propagate_neurite_owner_regions, _repair_signal_supported_skeleton, + _render_owned_skeleton, _seeded_candidate_components, _TopologyResult, count_neuronal_cell_bodies_metaxpress, @@ -157,6 +163,11 @@ def test_signature_exposes_documented_metaxpress_controls_only(): "neurite_outgrowth", "neurons", "nuclei", + "neurite_candidate_mask", + "neurite_unrooted_residual", + "neurite_secondary_ownership", + "neurite_topology_dropped_trace", + "neurite_topology_added_trace", "neurite_morphology", ) ( @@ -166,6 +177,11 @@ def test_signature_exposes_documented_metaxpress_controls_only(): neurite_spec, neurons_spec, nuclei_spec, + candidate_spec, + residual_spec, + secondary_ownership_spec, + topology_dropped_trace_spec, + topology_added_trace_spec, morphology_spec, ) = contract.artifact_outputs assert summary_spec.artifact_type is MeasurementsArtifactType @@ -183,6 +199,20 @@ def test_signature_exposes_documented_metaxpress_controls_only(): ImageFileOptions, ) assert spec.materialization.primary == 0 + for spec in ( + candidate_spec, + residual_spec, + secondary_ownership_spec, + topology_dropped_trace_spec, + topology_added_trace_spec, + ): + assert spec.artifact_type is ImageArtifactType + assert spec.sidecar_role is ArtifactSidecarRole.QA_CHECKPOINT + assert spec.viewer_streaming is ArtifactViewerStreaming.ON_DEMAND + assert tuple(type(output) for output in spec.materialization.outputs) == ( + ImageFileOptions, + ) + assert spec.materialization.primary == 0 assert morphology_spec.artifact_type is SpatialGraphArtifactType morphology_subject = morphology_spec.relations[0].object_subject_binding() assert morphology_subject.source == neurons_spec.ref() @@ -413,7 +443,7 @@ def test_topology_metrics_and_significant_threshold_is_scoring_only(): def test_unrooted_crossing_arm_is_not_reported_as_a_branch(): image = _with_separate_body_channel(_draw_fluorescent_neuron(crossing=True)) - _, summary_rows, cell_rows, _, neurite_labels, _, _, _ = _implementation()( + (_, summary_rows, cell_rows, _, neurite_labels, _, _, _, *_) = _implementation()( image, neurite_channel_index=1, cell_body=_cell_body_settings(channel_index=0), @@ -495,6 +525,64 @@ def test_isolated_pixels_do_not_change_connected_path_geometry_or_ownership(diag ) +def test_three_pixel_cycle_has_empty_topology(): + skeleton = np.zeros((17, 17), dtype=bool) + skeleton[7, 7] = skeleton[7, 8] = skeleton[8, 7] = True + original = skeleton.copy() + + topology = _analyze_topology( + skeleton, + np.zeros(skeleton.shape, dtype=np.int32), + pixel_size_um=1.0, + outgrowth_width_px=3.0, + ) + + assert all(len(getattr(topology, field.name)) == 0 for field in fields(topology)) + np.testing.assert_array_equal(skeleton, original) + + +def test_three_pixel_cycle_does_not_change_valid_path_topology(): + skeleton = np.zeros((33, 33), dtype=bool) + skeleton[16, 8:25] = True + bodies = np.zeros(skeleton.shape, dtype=np.int32) + bodies[14:19, 6:10] = 1 + expected = _analyze_topology(skeleton, bodies, 1.0, 3.0) + + skeleton[2, 2] = skeleton[2, 3] = skeleton[3, 2] = True + actual = _analyze_topology(skeleton, bodies, 1.0, 3.0) + + np.testing.assert_array_equal(actual.path_lengths, expected.path_lengths) + np.testing.assert_array_equal(actual.path_owners, expected.path_owners) + np.testing.assert_array_equal(actual.path_distances, expected.path_distances) + assert actual.path_endpoint_groups == expected.path_endpoint_groups + assert actual.transitions == expected.transitions + assert all( + np.array_equal(left, right) + for left, right in zip(actual.path_coordinates, expected.path_coordinates) + ) + + +def test_owned_topology_ignores_three_pixel_cycle_for_separate_owner(): + owned = np.zeros((33, 33), dtype=np.int32) + owned[16, 8:25] = 1 + owned[2, 2] = owned[2, 3] = owned[3, 2] = 2 + bodies = np.zeros_like(owned) + bodies[14:19, 6:10] = 1 + bodies[1:5, 1:5] = 2 + + topology = _analyze_owned_topology( + owned, + bodies, + pixel_size_um=1.0, + outgrowth_width_px=3.0, + ) + rendered = _render_owned_skeleton(owned.shape, topology) + + assert len(topology.path_coordinates) == 1 + assert np.all(topology.path_owners == 1) + np.testing.assert_array_equal(rendered > 0, owned == 1) + + def test_crossing_resolution_retains_two_logical_endpoint_groups(): skeleton = np.zeros((65, 65), dtype=bool) skeleton[32, 5:60] = True @@ -527,6 +615,27 @@ def test_crossing_resolution_retains_two_logical_endpoint_groups(): assert np.all(topology.path_branch_types == 0) +def test_owned_geometric_crossing_uses_nominal_owner_as_branch(): + owned = np.zeros((65, 65), dtype=np.int32) + bodies = np.zeros_like(owned) + bodies[29:36, 2:9] = 1 + owned[32, 9:57] = 1 + owned[8:57, 32] = 1 + + topology = _analyze_owned_topology( + owned, + bodies, + pixel_size_um=1.0, + outgrowth_width_px=2.0, + ) + rendered = _render_owned_skeleton(owned.shape, topology) + + np.testing.assert_array_equal(rendered > 0, owned > 0) + assert np.all(topology.path_owners == 1) + assert topology.crossing_nodes == frozenset() + assert len(topology.branch_nodes_by_cell[1]) == 1 + + @pytest.mark.parametrize("pixel_size_um", [0.5, 1.0, 1.3556, 2.0]) def test_short_two_junction_crossing_resolves_opposite_rooted_traces(pixel_size_um): skeleton = np.zeros((70, 70), dtype=bool) @@ -920,6 +1029,11 @@ def test_explicit_body_nuclear_and_neurite_channels_are_aligned(): neurite_labels, neurons, nuclei, + candidate_mask, + unrooted_residual, + secondary_ownership, + topology_dropped_trace, + topology_added_trace, morphology, ) = _implementation()( image, @@ -954,6 +1068,91 @@ def test_explicit_body_nuclear_and_neurite_channels_are_aligned(): assert nuclei[0].max() == 1 assert np.count_nonzero(nuclei[[1, 2]]) == 0 assert isinstance(morphology, SpatialGraph) + assert candidate_mask.source_indices == (2,) + assert unrooted_residual.source_indices == (2,) + assert secondary_ownership.source_indices == (2,) + assert topology_dropped_trace.source_indices == (2,) + assert topology_added_trace.source_indices == (2,) + assert np.asarray(candidate_mask).shape == (1, *image.shape[1:]) + assert np.asarray(unrooted_residual).shape == (1, *image.shape[1:]) + assert np.asarray(secondary_ownership).shape == (1, *image.shape[1:]) + assert np.asarray(topology_dropped_trace).shape == (1, *image.shape[1:]) + assert np.asarray(topology_added_trace).shape == (1, *image.shape[1:]) + assert not np.any( + np.asarray(topology_dropped_trace)[0] & (cell_bodies[1] > 0) + ) + assert np.all(np.asarray(unrooted_residual) <= np.asarray(candidate_mask)) + assert not np.any(np.asarray(unrooted_residual)[0] & (cell_bodies[1] > 0)) + candidate_neurite = np.asarray(candidate_mask)[0].astype(bool) & ( + cell_bodies[1] == 0 + ) + residual = np.asarray(unrooted_residual)[0].astype(bool) + secondary_owned_residual = residual & ( + np.asarray(secondary_ownership)[0] > 0 + ) + assert summary["candidate_mask_pixels"] == np.count_nonzero(candidate_neurite) + assert summary["rooted_candidate_mask_pixels"] == np.count_nonzero( + candidate_neurite & (neurons[2] > 0) + ) + assert summary["unrooted_residual_pixels"] == np.count_nonzero(residual) + assert summary["secondary_owned_residual_pixels"] == np.count_nonzero( + secondary_owned_residual + ) + assert summary["secondary_unowned_residual_pixels"] == np.count_nonzero( + residual & ~secondary_owned_residual + ) + assert summary["secondary_owned_residual_fraction"] == pytest.approx( + np.count_nonzero(secondary_owned_residual) / np.count_nonzero(residual) + if np.any(residual) + else 0.0 + ) + assert ( + summary["rooted_candidate_trace_pixels"] + + summary["unrooted_candidate_trace_pixels"] + == summary["candidate_trace_pixels"] + ) + assert summary["rooted_candidate_trace_yield"] == pytest.approx( + summary["rooted_candidate_trace_pixels"] + / summary["candidate_trace_pixels"] + if summary["candidate_trace_pixels"] + else 0.0 + ) + assert ( + summary["secondary_owned_unrooted_trace_pixels"] + + summary["secondary_unowned_unrooted_trace_pixels"] + == summary["unrooted_candidate_trace_pixels"] + ) + assert summary["initial_topology_owned_trace_pixels"] <= summary[ + "secondary_adopted_trace_pixels" + ] + assert summary["published_owned_trace_pixels"] == np.count_nonzero( + neurite_labels[2] + ) + assert summary["published_owned_trace_pixels"] >= summary[ + "final_topology_owned_trace_pixels" + ] + assert summary["final_topology_dropped_trace_pixels"] == np.count_nonzero( + np.asarray(topology_dropped_trace) + ) + assert summary[ + "final_topology_dropped_crossing_support_trace_pixels" + ] <= summary["final_topology_dropped_trace_pixels"] + assert ( + summary["final_topology_dropped_unrooted_path_trace_pixels"] + + summary["final_topology_dropped_unrepresented_trace_pixels"] + == summary["final_topology_dropped_trace_pixels"] + ) + assert ( + summary["final_topology_dropped_physically_rooted_path_trace_pixels"] + + summary["final_topology_dropped_physically_unrooted_path_trace_pixels"] + == summary["final_topology_dropped_unrooted_path_trace_pixels"] + ) + assert summary["final_topology_added_trace_pixels"] == np.count_nonzero( + np.asarray(topology_added_trace) + ) + assert summary["final_topology_added_trace_pixels"] <= summary[ + "crossing_core_trace_pixels" + ] def test_expanded_ownership_preserves_response_repaired_trace_support(): @@ -988,14 +1187,17 @@ def test_filled_two_neuron_crossing_keeps_the_same_owners_as_final_traces(): outgrowth=_outgrowth_settings(), pixel_size=1.0, ) + summary = _rows(result[1])[0] bodies, traces, neurons = result[3][0], result[4][1], result[5][1] horizontal_owner = bodies[64, 20] vertical_owner = bodies[20, 75] assert horizontal_owner > 0 and vertical_owner > 0 assert horizontal_owner != vertical_owner + assert summary["resolved_crossovers"] == 1 assert traces[64, 105] == horizontal_owner assert traces[105, 75] == vertical_owner + assert traces[64, 75] in {horizontal_owner, vertical_owner} np.testing.assert_array_equal(neurons[traces > 0], traces[traces > 0]) np.testing.assert_array_equal(neurons[bodies > 0], bodies[bodies > 0]) @@ -1125,7 +1327,7 @@ def test_overwide_nuclear_guided_foreground_is_not_a_cell_body(): rows, columns = disk((42, 92), 5, shape=image.shape[1:]) image[1, rows, columns] = 1200 - _, summary_rows, _, cell_bodies, _, _, nuclei, _ = _implementation()( + _, summary_rows, _, cell_bodies, _, _, nuclei, *_ = _implementation()( image, cell_body=_cell_body_settings(), outgrowth=_outgrowth_settings(), @@ -1151,7 +1353,7 @@ def test_transmission_mode_detects_dark_cell_and_neurite(): transmission = np.full(fluorescence.shape, 2000, dtype=np.uint16) transmission[fluorescence > 0] = 500 - _, summary_rows, cell_rows, _, _, _, _, _ = _implementation()( + _, summary_rows, cell_rows, _, _, _, _, *_ = _implementation()( transmission[None, ...], illumination=NeuriteIllumination.TRANSMISSION, cell_body=_cell_body_settings(), @@ -1176,7 +1378,7 @@ def forbidden_remeasurement(*args, **kwargs): "openhcs.processing.backends.cellprofiler.skeleton.measure_object_skeleton", forbidden_remeasurement, ) - _, summary_rows, cell_rows, _, _, _, _, _ = _implementation()( + _, summary_rows, cell_rows, _, _, _, _, *_ = _implementation()( image, neurite_channel_index=1, cell_body=MetaXpressCellBodySettings( @@ -1354,9 +1556,10 @@ def reject_hidden_secondary_threshold(*args, **kwargs): assert cell_bodies[1].max() == 2 assert nuclei[0].max() == 2 assert np.count_nonzero(nuclei[1]) == 0 - # The final owned path is 85 pixels long. Independent CP seed-relative - # remeasurement previously reported 42 for this same published path. - assert sorted(row["total_outgrowth_um"] for row in cell_rows) == [0.0, 85.0] + # The centroid-bounded soma leaves a final owned path 89 pixels long. + # Independent CP seed-relative remeasurement previously reported 42 for + # this same published path. + assert sorted(row["total_outgrowth_um"] for row in cell_rows) == [0.0, 89.0] zero_growth_cell = next( row["cell"] for row in cell_rows if row["total_outgrowth_um"] == 0.0 ) @@ -1425,7 +1628,7 @@ def record_distance_transform(array, *args, **kwargs): assert set(np.unique(bodies)) == {0, 1, 2} assert observed_shapes[0] == shape - assert len(observed_shapes) == 5 + assert len(observed_shapes) == 3 assert all( rows < shape[0] and columns < shape[1] for rows, columns in observed_shapes[1:] ) @@ -1456,6 +1659,91 @@ def test_signal_body_derivation_partitions_shared_signal_by_nearest_nucleus(): assert np.count_nonzero(bodies == 2) > 100 +def test_signal_body_derivation_enforces_maximum_width_from_nuclear_centroid(): + shape = (96, 96) + seeds = np.zeros(shape, dtype=np.int32) + seeds[44:52, 20:76] = 1 + image = np.zeros(shape, dtype=np.uint16) + image[43:53, 10:86] = 1200 + + bodies = _derive_signal_cell_bodies( + seeds, + image, + MetaXpressCellBodySettings( + approximate_max_width=20.0, + minimum_area=10.0, + intensity_above_local_background=100.0, + channel_index=1, + ), + 1.0, + bright_objects=True, + ) + + coordinates = np.argwhere(bodies == 1) + assert np.ptp(coordinates[:, 0]) <= 20 + assert np.ptp(coordinates[:, 1]) <= 20 + + +def test_signal_body_derivation_rejects_nearby_signal_without_nuclear_overlap( + monkeypatch, +): + shape = (64, 64) + seeds = np.zeros(shape, dtype=np.int32) + rows, columns = disk((32, 32), 4, shape=shape) + seeds[rows, columns] = 1 + response = np.zeros(shape, dtype=float) + rows, columns = disk((32, 43), 4, shape=shape) + response[rows, columns] = 200.0 + monkeypatch.setattr( + "openhcs.processing.backends.analysis.neurite_outgrowth." + "local_background_response", + lambda *args, **kwargs: response, + ) + + bodies = _derive_signal_cell_bodies( + seeds, + response, + MetaXpressCellBodySettings( + approximate_max_width=30.0, + minimum_area=10.0, + intensity_above_local_background=100.0, + channel_index=1, + ), + 1.0, + bright_objects=True, + ) + + assert not np.any(bodies) + + +def test_signal_body_derivation_reapplies_minimum_area_after_shared_pixel_overwrite(): + shape = (72, 72) + seeds = np.zeros(shape, dtype=np.int32) + for owner, center in ((1, (36, 25)), (2, (36, 47))): + rows, columns = disk(center, 4, shape=shape) + seeds[rows, columns] = owner + image = np.zeros(shape, dtype=np.uint16) + rows, columns = disk((36, 36), 20, shape=shape) + image[rows, columns] = 1200 + + bodies = _derive_signal_cell_bodies( + seeds, + image, + MetaXpressCellBodySettings( + approximate_max_width=30.0, + minimum_area=500.0, + intensity_above_local_background=100.0, + channel_index=1, + ), + 1.0, + bright_objects=True, + ) + + body_areas = np.bincount(bodies.ravel(), minlength=3) + assert body_areas[1] == 0 + assert body_areas[2] >= 500 + + def test_cell_body_contract_bounds_each_object_distance_transform(monkeypatch): shape = (512, 512) labels = np.zeros(shape, dtype=np.int32) @@ -1519,29 +1807,150 @@ def test_signal_supported_repair_follows_curved_trace_instead_of_chord(): assert not np.any(repaired[32, 16:43]) -def test_secondary_ownership_adopts_only_single_owner_components(): - skeleton = np.zeros((24, 32), dtype=bool) - skeleton[4, 3:12] = True - skeleton[12, 3:12] = True - skeleton[20, 3:12] = True +def test_physical_soma_root_mask_distinguishes_attached_and_detached_components(): + owned = np.zeros((32, 48), dtype=np.int32) + bodies = np.zeros_like(owned) + bodies[13:20, 3:10] = 1 + owned[16, 10:27] = 1 + owned[5, 34:43] = 1 + + rooted = _physically_soma_rooted_owner_mask( + owned, + bodies, + maximum_root_distance=3, + ) + + assert np.all(rooted[16, 10:27]) + assert not np.any(rooted[5, 34:43]) + + +def test_secondary_ownership_adopts_logical_paths_not_whole_components(): + skeleton = np.zeros((33, 33), dtype=bool) + skeleton[16, 4:29] = True + skeleton[16:29, 16] = True + topology = _analyze_topology( + skeleton, + np.zeros(skeleton.shape, dtype=np.int32), + pixel_size_um=1.0, + outgrowth_width_px=2.0, + ) owner_skeleton = np.zeros(skeleton.shape, dtype=np.int32) - owner_skeleton[4, 3] = 1 - owner_skeleton[12, 3] = 2 secondary_regions = np.zeros(skeleton.shape, dtype=np.int32) - secondary_regions[3:6, 2:13] = 1 - secondary_regions[11:14, 2:7] = 2 - secondary_regions[11:14, 7:13] = 3 + secondary_regions[15:18, 3:16] = 1 + secondary_regions[15:18, 17:30] = 2 + secondary_regions[17:30, 15:18] = 3 - adopted = _adopt_secondary_owned_skeleton( - skeleton, + adopted = _adopt_secondary_owned_path_segments( + topology, owner_skeleton, secondary_regions, ) - assert np.all(adopted[4, 3:12] == 1) - assert adopted[12, 3] == 2 - assert not np.any(adopted[12, 4:12]) - assert not np.any(adopted[20, 3:12]) + assert np.all(adopted[16, 4:16] == 1) + assert np.all(adopted[16, 17:29] == 2) + assert np.all(adopted[17:29, 16] == 3) + assert adopted[16, 16] == 0 + + +def test_secondary_ownership_partitions_a_path_at_nominal_owner_boundaries(): + skeleton = np.zeros((24, 32), dtype=bool) + skeleton[12, 3:29] = True + topology = _analyze_topology( + skeleton, + np.zeros(skeleton.shape, dtype=np.int32), + pixel_size_um=1.0, + outgrowth_width_px=2.0, + ) + secondary_regions = np.zeros(skeleton.shape, dtype=np.int32) + secondary_regions[11:14, 2:16] = 1 + secondary_regions[11:14, 16:30] = 2 + + adopted = _adopt_secondary_owned_path_segments( + topology, + np.zeros(skeleton.shape, dtype=np.int32), + secondary_regions, + ) + + assert np.all(adopted[12, 3:16] == 1) + assert np.all(adopted[12, 16:29] == 2) + + +def test_owned_topology_preserves_adjacent_nominal_neuron_paths(): + owned = np.zeros((48, 64), dtype=np.int32) + bodies = np.zeros_like(owned) + bodies[20:27, 2:9] = 1 + bodies[20:27, 55:62] = 2 + owned[23, 9:32] = 1 + owned[23, 32:55] = 2 + + topology = _analyze_owned_topology( + owned, + bodies, + pixel_size_um=1.0, + outgrowth_width_px=2.0, + ) + rendered = np.zeros_like(owned) + for path_index, coordinates in enumerate(topology.path_coordinates): + owner = int(topology.path_owners[path_index]) + rendered[tuple(coordinates.T)] = owner + + assert set(topology.path_owners) == {1, 2} + assert np.all(rendered[23, 9:32] == 1) + assert np.all(rendered[23, 32:55] == 2) + assert topology.root_paths_by_cell.keys() == {1, 2} + + +def test_secondary_path_adoption_survives_only_with_soma_rooted_signal_support(): + shape = (64, 64) + cell_bodies = np.zeros(shape, dtype=np.int32) + cell_bodies[29:36, 5:12] = 1 + skeleton = np.zeros(shape, dtype=bool) + skeleton[32, 30:53] = True + topology = _analyze_topology( + skeleton, + cell_bodies, + pixel_size_um=1.0, + outgrowth_width_px=2.0, + ) + assert not np.any(topology.path_owners) + + def repaired_topology(*, connected: bool): + owner_regions = np.zeros(shape, dtype=np.int32) + response = np.zeros(shape, dtype=float) + owner_regions[32, 30:53] = 1 + response[32, 30:53] = 150.0 + if connected: + owner_regions[29:36, 5:53] = 1 + response[32, 11:53] = 150.0 + adopted = _adopt_secondary_owned_path_segments( + topology, + np.zeros(shape, dtype=np.int32), + owner_regions, + ) + assert np.all(adopted[32, 30:53] == 1) + repaired = _repair_signal_supported_skeleton( + adopted, + response, + owner_regions, + cell_bodies, + minimum_response=100.0, + ) + repaired[cell_bodies > 0] = 0 + return repaired, _analyze_topology( + repaired > 0, + cell_bodies, + pixel_size_um=1.0, + outgrowth_width_px=2.0, + assigned_path_labels=repaired, + ) + + disconnected_labels, disconnected_topology = repaired_topology(connected=False) + assert not np.any(disconnected_labels) + assert not np.any(disconnected_topology.path_owners) + + connected_labels, connected_topology = repaired_topology(connected=True) + assert np.all(connected_labels[32, 12:53] == 1) + assert np.all(connected_topology.path_owners == 1) def test_signal_supported_repair_bounds_compiled_search_to_owner_regions(monkeypatch): diff --git a/tests/unit/test_neuroncyto_ii_neurite_demo.py b/tests/unit/test_neuroncyto_ii_neurite_demo.py index 62bb4cd2cb..182820ed2c 100644 --- a/tests/unit/test_neuroncyto_ii_neurite_demo.py +++ b/tests/unit/test_neuroncyto_ii_neurite_demo.py @@ -126,6 +126,11 @@ def test_neuroncyto_demo_declares_exact_crossover_channel_semantics( "neurite_outgrowth", "neurons", "nuclei", + "neurite_candidate_mask", + "neurite_unrooted_residual", + "neurite_secondary_ownership", + "neurite_topology_dropped_trace", + "neurite_topology_added_trace", "neurite_morphology", ) assert {spec.name: spec.viewer_streaming for spec in artifact_outputs} == { @@ -135,6 +140,11 @@ def test_neuroncyto_demo_declares_exact_crossover_channel_semantics( "neurite_outgrowth": ArtifactViewerStreaming.ON_DEMAND, "neurons": ArtifactViewerStreaming.AUTOMATIC, "nuclei": ArtifactViewerStreaming.ON_DEMAND, + "neurite_candidate_mask": ArtifactViewerStreaming.ON_DEMAND, + "neurite_unrooted_residual": ArtifactViewerStreaming.ON_DEMAND, + "neurite_secondary_ownership": ArtifactViewerStreaming.ON_DEMAND, + "neurite_topology_dropped_trace": ArtifactViewerStreaming.ON_DEMAND, + "neurite_topology_added_trace": ArtifactViewerStreaming.ON_DEMAND, "neurite_morphology": ArtifactViewerStreaming.AUTOMATIC, } @@ -184,6 +194,11 @@ def test_neuroncyto_demo_compiles_exact_loose_tiff_pair(tmp_path: Path) -> None: "neurite_outgrowth": ArtifactViewerStreaming.ON_DEMAND, "neurons": ArtifactViewerStreaming.AUTOMATIC, "nuclei": ArtifactViewerStreaming.ON_DEMAND, + "neurite_candidate_mask": ArtifactViewerStreaming.ON_DEMAND, + "neurite_unrooted_residual": ArtifactViewerStreaming.ON_DEMAND, + "neurite_secondary_ownership": ArtifactViewerStreaming.ON_DEMAND, + "neurite_topology_dropped_trace": ArtifactViewerStreaming.ON_DEMAND, + "neurite_topology_added_trace": ArtifactViewerStreaming.ON_DEMAND, "neurite_morphology": ArtifactViewerStreaming.AUTOMATIC, } From 351746b3846e4945c7e2c6085cd3d2a7c5eeecab Mon Sep 17 00:00:00 2001 From: Tristan Simas Date: Mon, 21 Sep 2026 23:33:28 -0400 Subject: [PATCH 04/15] Add reproducible blind neurite preparation --- .../own_neurite_blind_20260915_preparation.md | 31 ++ benchmark/prepare_blind_neurite.py | 337 ++++++++++++++++++ tests/unit/test_prepare_blind_neurite.py | 71 ++++ 3 files changed, 439 insertions(+) create mode 100644 benchmark/own_neurite_blind_20260915_preparation.md create mode 100644 benchmark/prepare_blind_neurite.py create mode 100644 tests/unit/test_prepare_blind_neurite.py diff --git a/benchmark/own_neurite_blind_20260915_preparation.md b/benchmark/own_neurite_blind_20260915_preparation.md new file mode 100644 index 0000000000..d8909f0fd5 --- /dev/null +++ b/benchmark/own_neurite_blind_20260915_preparation.md @@ -0,0 +1,31 @@ +# Neutral neurite-input readiness receipt + +Prepared and verified 2026-09-15. This is input/metadata preparation only: no biological pipeline was authored or executed, no parameter was tuned, and no commercial measurement informed preparation. + +Author input root: `/run/media/ts/0BA20E780BA20E78/slas-neurite-coded-20260915`. + +| Property | Verified value | +| --- | --- | +| Plates | `P001`, `P002` | +| Images / fields | 2,160 TIFFs / 1,080 fields | +| Each plate | 60 coded wells `A01:A60` × nine sites × two channels | +| Filename example | `P001/A01_s001_w1_z001_t001.tif` | +| Channels | `w1` DAPI; `w2` FITC | +| Geometry | Scalar 1024 × 1024 uint16; one Z plane, one timepoint | +| Calibration | Exactly 1.3556 µm/pixel in X and Y | +| Input file bytes | 4,545,087,760 (~4.23 GiB) | +| External free bytes after cleanup | 64,414,490,624 (~60.0 GiB), at readiness | + +Coded well identities do not encode physical plate positions. Site numbers and relative within-well geometry remain available. Inputs contain no original plate/well identity, treatment layout, commercial measurements, original timestamps, absolute stage positions, or source links. Original identities and full metadata remain only in separate private evaluation bookkeeping. This is protocol isolation, not an OS security sandbox: the author must not inspect that bookkeeping, original data tree, or preparation context. + +Verification: + +- Every staged array equals its original array exactly, including dtype. Every source file was hashed before and after staging and remained byte-identical. Source-file, staged-file and pixel checksums are recorded privately for every image. +- Final independent header audit checked all 2,160 files: calibration and **every nonidentity XML property** were unchanged; only declared identity properties and the identity-bearing description prefix were removed/recoded. Filenames are accepted by the existing ImageXpress filename parser. +- Files were created in coded order with uniform neutral filesystem modification times, avoiding exposure of the original well iteration order. There is no original HTD in the author root; use the existing declared-file SourceBinding metadata route rather than native HTD discovery. +- Seven focused preparation/cleanup safety tests passed: `.venv/bin/python -m pytest -q tests/unit/test_prepare_blind_neurite.py`. `git diff --check` passed. Tooling: [prepare_blind_neurite.py](prepare_blind_neurite.py). +- An initial preparation was interrupted to add the coded-order safeguard. After final verification, exactly 694 validated task-owned partial TIFF copies were deleted, reclaiming 1,460,319,872 bytes. A compact failure/checksum cleanup receipt remains private. Original raw data was neither removed nor modified. + +Neutral fingerprint: SHA-256 `55f952ce5cb5e1c65fc249c2a2d9ff7da17cf8eeecff487120ff9232a0dd9dc4`, over sorted neutral records `relative_path + TAB + staged_file_sha256 + LF`. This does not expose source identifiers. Safe `INPUT_CONTRACT.txt` SHA-256: `536dd8f1b4678ff24275a2dbddb447473214b8c19b3922330af722cf42979d36`. + +Suggested persistent output root: `/run/media/ts/0BA20E780BA20E78/slas-neurite-coded-results-20260915`. Two uint32 label planes per field require ~8.44 GiB uncompressed over the complete corpus; two uint8 masks add ~2.11 GiB. Avoid unnecessary raw-array/RGB-overlay duplication and use supported lossless compression. The fresh blinded author owns development, pipeline freeze and the complete 1,080-field run; comparison/unblinding must wait for that freeze and completion inventory. diff --git a/benchmark/prepare_blind_neurite.py b/benchmark/prepare_blind_neurite.py new file mode 100644 index 0000000000..049d0b1b6f --- /dev/null +++ b/benchmark/prepare_blind_neurite.py @@ -0,0 +1,337 @@ +"""Lossless, identity-sanitized input staging; never performs biological analysis. + +The private receipt contains original identities/XML. Do not expose that receipt, +this preparation context, or the source tree to the blinded pipeline author. +""" +from __future__ import annotations + +import argparse +from dataclasses import dataclass, replace +from enum import Enum +import hashlib +import json +import os +from pathlib import Path +import random +import re +import secrets +import shutil +import xml.etree.ElementTree as ET + +import numpy as np +import tifffile + +from openhcs.serialization.json import to_jsonable + + +class Channel(Enum): + DAPI = (1, "DAPI") + FITC = (2, "FITC") + + @property + def number(self) -> int: + return self.value[0] + + @property + def illumination(self) -> str: + return self.value[1] + + @classmethod + def from_number(cls, number: int) -> Channel: + return next(channel for channel in cls if channel.number == number) + + +@dataclass(frozen=True) +class SourceImage: + path: Path + well: str + site: int + channel: Channel + + +@dataclass(frozen=True) +class SanitizedMetadata: + xml: str + original_xml: str + removed_property_ids: tuple[str, ...] + calibration_um: tuple[float, float] + + +@dataclass(frozen=True) +class PrivateImageReceipt: + source_path: str + source_well: str + site: int + channel: Channel + coded_relative_path: str + source_file_sha256: str + staged_file_sha256: str + pixel_sha256: str + shape: tuple[int, int] + dtype: str + original_xml: str + removed_property_ids: tuple[str, ...] + calibration_um: tuple[float, float] + + +@dataclass(frozen=True) +class PrivatePreparationReceipt: + protocol_version: int + opaque_random_seed: str + author_root: str + identity_redactions: tuple[str, ...] + images: tuple[PrivateImageReceipt, ...] + + +@dataclass(frozen=True) +class DiscardedTaskFile: + relative_path: str + bytes: int + sha256: str + + +@dataclass(frozen=True) +class AbortedPreparationCleanup: + removed_exact_root: str + file_count: int + bytes_reclaimed: int + reason: str + files: tuple[DiscardedTaskFile, ...] + + +IDENTITY_PROPERTIES = frozenset({ + "plane-guid", "acquisition-time-local", "modification-time-local", + "stage-position-x", "stage-position-y", "z-position", + "ImageXpress Micro X", "ImageXpress Micro Y", "ImageXpress Micro Z", + "Instrument Serial Number", +}) +IDENTITY_TOKENS = ( + "F04", "analogs", "controls", "24098", "24099", "Tristan", + "09-027", "06-049", "09-037", "08-115", "09-079", + "FC-A", "EpoB", "DMSO", "Y27", +) +SOURCE_FILENAME = re.compile(r".+_([B-G](?:0[2-9]|1[01]))_s([1-9])_w([12])\.TIF") +SOURCE_TAG_CODES = frozenset({254, 256, 257, 258, 259, 262, 270, 273, + 274, 277, 278, 279, 305, 306}) + + +def sha256_file(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as stream: + for chunk in iter(lambda: stream.read(1024 * 1024), b""): + digest.update(chunk) + return digest.hexdigest() + + +def pixel_sha256(image: np.ndarray) -> str: + return hashlib.sha256(np.ascontiguousarray(image).tobytes()).hexdigest() + + +def assert_no_identity_leak(text: str) -> None: + folded = text.casefold() + found = tuple(token for token in IDENTITY_TOKENS if token.casefold() in folded) + if found: + raise ValueError(f"Identity-bearing metadata survived: {found}") + + +def sanitize_metadata(original_xml: str, coded_well: str, site: int, + channel: Channel) -> SanitizedMetadata: + root = ET.fromstring(original_xml) + props = {element.attrib["id"]: element for element in root.iter() + if "id" in element.attrib} + if props["_IllumSetting_"].attrib["value"] != channel.illumination: + raise ValueError("Filename channel differs from acquisition illumination") + if props["spatial-calibration-state"].attrib["value"] != "on": + raise ValueError("Spatial calibration disabled") + calibration = tuple(float(props[key].attrib["value"]) for key in + ("spatial-calibration-x", "spatial-calibration-y")) + if calibration != (1.3556, 1.3556) or props["spatial-calibration-units"].attrib["value"] != "um": + raise ValueError("Unexpected calibration; refuse silent geometry changes") + description = props["Description"].attrib["value"] + prefix, separator, acquisition = description.partition("Exposure:") + if not separator or "Plate Name:" not in prefix: + raise ValueError("Unknown description layout; refuse broad metadata deletion") + props["Description"].set("value", "Exposure:" + acquisition) + props["stage-label"].set("value", f"{coded_well} : Site {site}") + removed: list[str] = [] + for parent in root.iter(): + for element in tuple(parent): + if "id" in element.attrib and element.attrib["id"] in IDENTITY_PROPERTIES: + removed.append(element.attrib["id"]) + parent.remove(element) + if set(removed) != IDENTITY_PROPERTIES: + raise ValueError("Unexpected acquisition identity schema") + xml = ET.tostring(root, encoding="unicode") + assert_no_identity_leak(xml) + return SanitizedMetadata(xml, original_xml, tuple(sorted(removed)), calibration) + + +def inventory_plate(root: Path) -> tuple[SourceImage, ...]: + images: list[SourceImage] = [] + for path in sorted(root.rglob("*.TIF")): + match = SOURCE_FILENAME.fullmatch(path.name) + if match is None: + raise ValueError(f"Unexpected raw filename: {path}") + well, site, channel = match.groups() + images.append(SourceImage(path, well, int(site), Channel.from_number(int(channel)))) + expected = {(f"{row}{column:02}", site, channel) + for row in "BCDEFG" for column in range(2, 12) + for site in range(1, 10) for channel in Channel} + actual = {(image.well, image.site, image.channel) for image in images} + if len(images) != 1080 or actual != expected: + raise ValueError("Incomplete/duplicate acquisition; no missing field is filled with zero") + return tuple(images) + + +def stage_image(source: SourceImage, destination: Path, coded_well: str) -> PrivateImageReceipt: + original_hash = sha256_file(source.path) + with tifffile.TiffFile(source.path) as tiff: + if len(tiff.pages) != 1 or {tag.code for tag in tiff.pages[0].tags.values()} != SOURCE_TAG_CODES: + raise ValueError("Unexpected TIFF page/tag schema") + page = tiff.pages[0] + pixels = page.asarray() + if pixels.shape != (1024, 1024) or pixels.dtype != np.dtype("uint16"): + raise ValueError("Unexpected raw image geometry") + source_props = {e.attrib["id"]: e.attrib["value"] + for e in ET.fromstring(page.description).iter() + if "id" in e.attrib} + if source_props["stage-label"] != f"{source.well} : Site {source.site}": + raise ValueError("Filename and acquisition field identity differ") + metadata = sanitize_metadata(page.description, coded_well, source.site, source.channel) + if page.photometric != tifffile.PHOTOMETRIC.MINISBLACK or int(page.tags[274].value) != 1: + raise ValueError("Unexpected pixel display/orientation semantics") + destination.parent.mkdir(parents=True, exist_ok=True) + tifffile.imwrite(destination, pixels, photometric="minisblack", metadata=None, + description=metadata.xml, software=page.tags[305].value, + byteorder=tiff.byteorder, rowsperstrip=page.rowsperstrip, + subfiletype=int(page.tags[254].value), + extratags=[(274, "H", 1, 1, False)]) + with tifffile.TiffFile(destination) as staged: + copied = staged.asarray() + if not np.array_equal(copied, pixels) or copied.dtype != pixels.dtype: + raise ValueError("Staged pixels differ from original") + assert_no_identity_leak(staged.pages[0].description) + if 306 in staged.pages[0].tags: + raise ValueError("Original acquisition timestamp survived") + copied_props = {e.attrib["id"]: e.attrib["value"] + for e in ET.fromstring(staged.pages[0].description).iter() + if "id" in e.attrib} + if tuple(float(copied_props[k]) for k in ("spatial-calibration-x", "spatial-calibration-y")) != metadata.calibration_um: + raise ValueError("Staged calibration differs") + if sha256_file(source.path) != original_hash: + raise ValueError("Original source changed while staging") + # Neutral filesystem timestamps also avoid disclosing acquisition/write order. + os.utime(destination, (1789430400, 1789430400)) + return PrivateImageReceipt(str(source.path), source.well, source.site, source.channel, + str(destination.name), original_hash, sha256_file(destination), + pixel_sha256(pixels), pixels.shape, str(pixels.dtype), + metadata.original_xml, metadata.removed_property_ids, + metadata.calibration_um) + + +def prepare(source_root: Path, author_root: Path, private_root: Path) -> PrivatePreparationReceipt: + if author_root.exists() or private_root.exists(): + raise FileExistsError("Task roots must be new; never overwrite a staged corpus/key") + if source_root.resolve() in (author_root.resolve(), private_root.resolve()): + raise ValueError("Source and task roots must differ") + if author_root.resolve() in private_root.resolve().parents or private_root.resolve() in author_root.resolve().parents: + raise ValueError("Private evaluation and author roots must be disjoint") + plates = tuple(sorted(path for path in source_root.iterdir() if path.is_dir())) + if len(plates) != 2: + raise ValueError("Expected exactly two acquisition plates") + inventories = {plate: inventory_plate(plate) for plate in plates} + if shutil.disk_usage(author_root.parent).free < 5_000_000_000: + raise ValueError("Insufficient external-drive space") + seed = secrets.token_hex(32) + generator = random.Random(int(seed, 16)) + shuffled_plates = list(plates) + generator.shuffle(shuffled_plates) + staging_root = author_root.parent / (".blind-staging-" + secrets.token_hex(8)) + staging_root.mkdir() + private_root.mkdir(parents=True, mode=0o700) + receipts: list[PrivateImageReceipt] = [] + for plate_number, plate in enumerate(shuffled_plates, 1): + plate_id = f"P{plate_number:03}" + wells = sorted({image.well for image in inventories[plate]}) + generator.shuffle(wells) + well_codes = {well: f"A{number:02}" for number, well in enumerate(wells, 1)} + # Create files in coded order, not the original physical-well order. + for source in sorted(inventories[plate], key=lambda image: + (well_codes[image.well], image.site, image.channel.number)): + coded_well = well_codes[source.well] + filename = f"{coded_well}_s{source.site:03}_w{source.channel.number}_z001_t001.tif" + destination = staging_root / plate_id / filename + receipt = stage_image(source, destination, coded_well) + receipts.append(replace(receipt, coded_relative_path=f"{plate_id}/{filename}")) + print(f"Staged {plate_id}: 1080 images, 60 coded wells, 9 sites, 2 channels", flush=True) + receipt = PrivatePreparationReceipt( + 1, seed, str(author_root), + ("Description identity/treatment prefix", "stage-label replaced with coded identity", + "TIFF DateTime omitted", *tuple(sorted(IDENTITY_PROPERTIES))), tuple(receipts)) + private_manifest = private_root / "private_source_key.json" + private_manifest.write_text(json.dumps(to_jsonable(receipt), indent=2) + "\n") + private_manifest.chmod(0o600) + public_text = ( + "Neutral acquisition corpus. Two plates P001/P002, each 60 coded wells A01:A60, " + "nine sites per well, two channels: w1 DAPI, w2 FITC. All images are scalar " + "1024 x 1024 uint16; one timepoint and one Z plane. Spatial calibration " + "is 1.3556 um/pixel in X/Y. Coded well IDs do not imply physical plate positions. " + "Site numbers and relative within-well geometry are retained. No treatment " + "labels, original well/plate identifiers, original acquisition times, " + "absolute stage positions, or comparator values are supplied.\n" + ) + (staging_root / "INPUT_CONTRACT.txt").write_text(public_text) + if len(tuple(staging_root.rglob("*.tif"))) != 2160: + raise ValueError("Unexpected staged image count") + staging_root.rename(author_root) + print(f"Author input root: {author_root}", flush=True) + print(f"Private key root (do not expose to author): {private_root}", flush=True) + print(f"Private receipt SHA256: {sha256_file(private_manifest)}", flush=True) + return receipt + + +def cleanup_aborted_identity_order(author_root: Path, private_root: Path) -> AbortedPreparationCleanup: + """Authorized cleanup of one exact, validated interrupted task-copy directory.""" + aborted = private_root.with_name("neurite-source-key-aborted-identity-order") + if private_root.name != "neurite-source-key" or aborted.is_symlink(): + raise ValueError("Unexpected private task-root identity") + if not (private_root / "private_source_key.json").is_file(): + raise ValueError("Final private receipt missing") + if len(tuple(author_root.rglob("*.tif"))) != 2160: + raise ValueError("Final author corpus incomplete") + if not aborted.is_dir() or tuple(aborted.iterdir()) != (aborted / "staging-residue",): + raise ValueError("Unexpected aborted contents; refuse deletion") + files: list[DiscardedTaskFile] = [] + for item in sorted(aborted.rglob("*")): + if item.is_symlink(): + raise ValueError("Symlink in aborted copy root; refuse deletion") + if item.is_dir(): + if item.name not in {"staging-residue", "P001", "P002"}: + raise ValueError("Unexpected aborted directory") + continue + if item.suffix != ".tif" or item.parent.name not in {"P001", "P002"}: + raise ValueError("Unexpected aborted non-TIFF file") + files.append(DiscardedTaskFile(str(item.relative_to(aborted)), item.stat().st_size, + sha256_file(item))) + receipt = AbortedPreparationCleanup(str(aborted.resolve()), len(files), + sum(file.bytes for file in files), + "Interrupted preparation was superseded by coded-order creation and neutral timestamps", + tuple(files)) + receipt_path = private_root / "aborted_preparation_cleanup.json" + receipt_path.write_text(json.dumps(to_jsonable(receipt), indent=2) + "\n") + receipt_path.chmod(0o600) + shutil.rmtree(aborted) + return receipt + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--source-root", type=Path, required=True) + parser.add_argument("--author-root", type=Path, required=True) + parser.add_argument("--private-root", type=Path, required=True) + arguments = parser.parse_args() + prepare(arguments.source_root, arguments.author_root, arguments.private_root) + + +if __name__ == "__main__": + main() diff --git a/tests/unit/test_prepare_blind_neurite.py b/tests/unit/test_prepare_blind_neurite.py new file mode 100644 index 0000000000..71fe95b606 --- /dev/null +++ b/tests/unit/test_prepare_blind_neurite.py @@ -0,0 +1,71 @@ +"""Identity-sanitization tests; no biological pipeline execution.""" +import xml.etree.ElementTree as ET + +import pytest + +from benchmark.prepare_blind_neurite import ( + Channel, IDENTITY_PROPERTIES, assert_no_identity_leak, + cleanup_aborted_identity_order, sanitize_metadata, +) + + +def metadata_xml() -> str: + root = ET.Element("MetaData") + values = { + "Description": "Plate Name: F04-controls\nFolder Name: Tristan\nB-C: Y27 EpoB\nExposure: 10 ms\nBinning: 2 x 2", + "_IllumSetting_": "FITC", + "spatial-calibration-state": "on", + "spatial-calibration-x": "1.3556", + "spatial-calibration-y": "1.3556", + "spatial-calibration-units": "um", + "stage-label": "B02 : Site 1", + "SiteX": "1", "SiteY": "1", "OffsetFromWellCenterUmX": "-1249.5", + **{identity: "original_identifier" for identity in IDENTITY_PROPERTIES}, + } + for identity, value in values.items(): + ET.SubElement(root, "prop", id=identity, value=value) + return ET.tostring(root, encoding="unicode") + + +def test_metadata_identity_is_removed_without_acquisition_changes() -> None: + original = metadata_xml() + result = sanitize_metadata(original, "A47", 1, Channel.FITC) + props = {e.attrib["id"]: e.attrib["value"] for e in ET.fromstring(result.xml)} + assert result.original_xml == original + assert result.calibration_um == (1.3556, 1.3556) + assert set(result.removed_property_ids) == IDENTITY_PROPERTIES + assert props["stage-label"] == "A47 : Site 1" + assert props["Description"] == "Exposure: 10 ms\nBinning: 2 x 2" + assert props["OffsetFromWellCenterUmX"] == "-1249.5" + assert props["SiteX"] == "1" + assert_no_identity_leak(result.xml) + + +def test_unknown_description_fails_closed() -> None: + with pytest.raises(ValueError, match="Unknown description layout"): + sanitize_metadata(metadata_xml().replace("Exposure:", "Unrecognized:"), "A01", 1, Channel.FITC) + + +def test_unexpected_calibration_fails_closed() -> None: + with pytest.raises(ValueError, match="Unexpected calibration"): + sanitize_metadata(metadata_xml().replace("1.3556", "1.0"), "A01", 1, Channel.FITC) + + +def test_illumination_disagreement_fails_closed() -> None: + with pytest.raises(ValueError, match="Filename channel differs"): + sanitize_metadata(metadata_xml(), "A01", 1, Channel.DAPI) + + +def test_leaked_identifier_fails_closed() -> None: + with pytest.raises(ValueError, match="Identity-bearing metadata survived"): + sanitize_metadata(metadata_xml().replace("10 ms", "DMSO"), "A01", 1, Channel.FITC) + + +def test_cleanup_refuses_wrong_task_root(tmp_path) -> None: + with pytest.raises(ValueError, match="Unexpected private task-root identity"): + cleanup_aborted_identity_order(tmp_path / "inputs", tmp_path / "not-a-key-root") + + +def test_cleanup_refuses_missing_final_receipt(tmp_path) -> None: + with pytest.raises(ValueError, match="Final private receipt missing"): + cleanup_aborted_identity_order(tmp_path / "inputs", tmp_path / "neurite-source-key") From c71bfc282d736b7b046ea55bd3b8751d33ac4fe4 Mon Sep 17 00:00:00 2001 From: Tristan Simas Date: Mon, 21 Sep 2026 23:33:28 -0400 Subject: [PATCH 05/15] Retain matched-batch pilot receipts and driver --- .../matched_batch_pilot_20260915/README.md | 94 +++++++ .../candidate_probe.json | 35 +++ .../matched_batch_pilot_20260915/design.md | 100 ++++++++ .../native_report.json | 53 ++++ .../native_request.json | 8 + .../pilot_driver.py | 220 ++++++++++++++++ .../matched_batch_pilot_20260915/receipt.json | 234 ++++++++++++++++++ 7 files changed, 744 insertions(+) create mode 100644 benchmark/results/matched_batch_pilot_20260915/README.md create mode 100644 benchmark/results/matched_batch_pilot_20260915/candidate_probe.json create mode 100644 benchmark/results/matched_batch_pilot_20260915/design.md create mode 100644 benchmark/results/matched_batch_pilot_20260915/native_report.json create mode 100644 benchmark/results/matched_batch_pilot_20260915/native_request.json create mode 100644 benchmark/results/matched_batch_pilot_20260915/pilot_driver.py create mode 100644 benchmark/results/matched_batch_pilot_20260915/receipt.json diff --git a/benchmark/results/matched_batch_pilot_20260915/README.md b/benchmark/results/matched_batch_pilot_20260915/README.md new file mode 100644 index 0000000000..69833ad2ee --- /dev/null +++ b/benchmark/results/matched_batch_pilot_20260915/README.md @@ -0,0 +1,94 @@ +# Matched-batch experiment handoff + +Status: native warm-batch timing works; the eight-well production probe found +two correctness gaps and an output-policy mismatch. No matched speedup or +Supplementary Figure 6 replacement is produced. + +## Observations + +- Native CellProfiler completed one warm-up and three repeated batches of eight + genuine image assignments. Invocation durations were 19.2508, 17.1796 and + 18.8893 seconds; first-module-through-post-run durations were 18.8870, 16.9119 + and 18.6581 seconds. These are native-only observations. +- Production OpenHCS 0.8.5 executed all eight axes successfully in its own TCP + ZMQ server, with `num_workers=1`. Its first batch stopped the pilot at strict + observation validation, before any candidate repeat was accepted. +- Eight requested TIFFs compare pixel-exactly. Native and candidate databases + both contain eight image rows, with identical object counts per image. +- The retained SQLite comparison reports four differences: three cytoplasm + correlation mean features and the corresponding object-table values. + +## Concrete repairs before continuing + +1. Preserve execution scope in runtime artifact expectations. The compiler + declares SQLite/CPA as a plate-scoped artifact, produced once by its owner; + `RuntimeArtifactExecutionExpectation.from_compiled_contexts` collapses outputs + to a flat kind set, and `_runtime_artifact_failures` requires that kind on each + axis. Seven axes consequently fail the `special` kind check despite a complete + plate export. Repair the declaration-to-expectation projection, not a + `special`-string exemption or a relaxed validation call. +2. Preserve undefined object correlation values. `Per_Object` cytoplasm K1, K2 + and overlap are native NULL/NaN but candidate 0 for image/object pairs (3,91), + (3,108) and (7,7). Image 3 is B01, image 7 is D01. The resulting candidate means + include those zeros; native means exclude NULL. For example B01 K1 is + 1.952585605558394 native versus 1.9265511308176155 candidate, the 148/150 factor. + The demonstrated owner path is object threshold metrics in + `colocalization.py` through `_divide_measurements`. Preserve each metric's + native undefined semantics rather than blanket-changing all correlation + families. Add both a focused native oracle and this multi-well export case. +3. Resolve terminal write policy for the benchmark. The live candidate writes + an extra terminal `CellAndNucleiOverlay.tif` per well in addition to the native + pipeline's requested overlay export. The runtime materialization flag alone + did not disable it. Select/derive a matching declared policy before timing, + or make equivalent writes on both sides and describe that scoped export + extension. Do not silently count unequal output work as a matched comparison. + +After those repairs, rerun this case at concurrency 1, settle source-owned start +and completion membership, then extend to one production server with N workers +against N native whole-group batches. Multi-job SQLite union, grouped/time-aware +partitioning and corpus breadth remain design work; see design.md. No full +corpus sweep was launched. + +## Evidence + +- `native_report.json`: actual native environment and four batch observations. +- `candidate_probe.json`: actual endpoint identity, compile/artifact/execution + IDs, coarse timing, all eight successful axes and seven validation failures. +- `events_-1.json.gz`: losslessly compressed raw source progress events for the + final production probe. +- `receipt.json`: source/manifest/script digests, environment, direct SQLite + cell differences, per-image object counts and TIFF pixel digests. +- `native_warmup/` and `candidate_warmup/`: paired requested outputs, about 22 MiB + total. Extra candidate terminal copies are documented but not archived here. +- `pilot_driver.py`: reproduction driver. It differs from the executed temporary + driver only in using the caller's output directory argument and current checkout + instead of hard-coded paths; both digests are retained. + +Task-owned temporary workspaces (176 MiB) and native staging were removed after +retaining these artifacts. Both owned probe servers exited normally. + +The processing source was HEAD `b2f3cf83` plus the existing dirty intensity fix; +its scoped diff digest is retained. No processing fix for the newly found gaps +was made in this benchmark pass. Neither manuscript nor historical reference +tree was modified. No commit, push or release was performed. + +## Reproduce the bounded probe + +From the OpenHCS checkout, allocate a fresh task-owned directory with `mktemp -d` +and substitute its full path for `/tmp/OPENHCS_PILOT_DIRECTORY` below. This +command intentionally fails closed at the currently demonstrated observation +validation gap; it does not proceed to candidate timing repeats. + +```sh +OMP_NUM_THREADS=1 OPENBLAS_NUM_THREADS=1 MKL_NUM_THREADS=1 \ +NUMEXPR_NUM_THREADS=1 VECLIB_MAXIMUM_THREADS=1 \ +NPY_DISABLE_CPU_FEATURES=AVX512_SKX,X86_V4 PYTHONHASHSEED=0 PYTHONPATH="$PWD" \ +.venv/bin/python \ +benchmark/results/matched_batch_pilot_20260915/pilot_driver.py \ +/tmp/OPENHCS_PILOT_DIRECTORY +``` + +The native runner uses `.venv-cellprofiler39/bin/python`. Its recorded versions +are CP/core 4.2.8.1, Python 3.9.25, NumPy 1.24.4 and SciPy 1.9.0. The candidate +is OpenHCS 0.8.5, Python 3.12.3, NumPy 2.1.3 and SciPy 1.18.0. These are measured +pilot versions, not inferred release-CI versions. diff --git a/benchmark/results/matched_batch_pilot_20260915/candidate_probe.json b/benchmark/results/matched_batch_pilot_20260915/candidate_probe.json new file mode 100644 index 0000000000..46c58864e4 --- /dev/null +++ b/benchmark/results/matched_batch_pilot_20260915/candidate_probe.json @@ -0,0 +1,35 @@ +{ + "repetition": -1, + "execution_id": "ab12ffcc-d468-4c4c-96a5-97f69d7c1c1a", + "compile_artifact_id": "2403deda-1311-4927-bad7-0fa95c61022f", + "compile_api_seconds": 15.630939054302871, + "invocation_seconds": 20.70744155300781, + "first_axis_through_completion_observed_seconds": 20.41277503967285, + "pre_first_axis_seconds": 0.29466819763183594, + "axis_count": 8, + "endpoint_pid": 2453602, + "endpoint_log_path": "/home/ts/.local/share/openhcs/logs/openhcs_zmq_server_port_7777_1789493936246341.log", + "endpoint_application_version": "0.8.5", + "output_files": [ + "/tmp/openhcs-matched-batch-pilot-1ayGug/candidate/source_workspace_matched_pilot/images/A01_s001_w1_z001_t001_Overlay.tiff", + "/tmp/openhcs-matched-batch-pilot-1ayGug/candidate/source_workspace_matched_pilot/images_results/DefaultDB.db", + "/tmp/openhcs-matched-batch-pilot-1ayGug/candidate/source_workspace_matched_pilot/images_results/DefaultDB.properties", + "/tmp/openhcs-matched-batch-pilot-1ayGug/candidate/source_workspace_matched_pilot/images/A12_s001_w1_z001_t001_Overlay.tiff", + "/tmp/openhcs-matched-batch-pilot-1ayGug/candidate/source_workspace_matched_pilot/images/B01_s001_w1_z001_t001_Overlay.tiff", + "/tmp/openhcs-matched-batch-pilot-1ayGug/candidate/source_workspace_matched_pilot/images/B12_s001_w1_z001_t001_Overlay.tiff", + "/tmp/openhcs-matched-batch-pilot-1ayGug/candidate/source_workspace_matched_pilot/images/C01_s001_w1_z001_t001_Overlay.tiff", + "/tmp/openhcs-matched-batch-pilot-1ayGug/candidate/source_workspace_matched_pilot/images/C12_s001_w1_z001_t001_Overlay.tiff", + "/tmp/openhcs-matched-batch-pilot-1ayGug/candidate/source_workspace_matched_pilot/images/D01_s001_w1_z001_t001_Overlay.tiff", + "/tmp/openhcs-matched-batch-pilot-1ayGug/candidate/source_workspace_matched_pilot/images/D12_s001_w1_z001_t001_Overlay.tiff" + ], + "execution_failures": [], + "validation_failures": [ + "axis 'A12' produced no runtime records for declared artifact kind 'special'", + "axis 'B01' produced no runtime records for declared artifact kind 'special'", + "axis 'B12' produced no runtime records for declared artifact kind 'special'", + "axis 'C01' produced no runtime records for declared artifact kind 'special'", + "axis 'C12' produced no runtime records for declared artifact kind 'special'", + "axis 'D01' produced no runtime records for declared artifact kind 'special'", + "axis 'D12' produced no runtime records for declared artifact kind 'special'" + ] +} \ No newline at end of file diff --git a/benchmark/results/matched_batch_pilot_20260915/design.md b/benchmark/results/matched_batch_pilot_20260915/design.md new file mode 100644 index 0000000000..f92bc0ef33 --- /dev/null +++ b/benchmark/results/matched_batch_pilot_20260915/design.md @@ -0,0 +1,100 @@ +# Warm-batch timing pilot, 2026-09-15 + +This is infrastructure validation for a future matched benchmark. It is not a +replacement for Supplementary Figure 6 and does not establish a speedup. + +## Workload and execution geometry + +The pilot imports the pinned CellProfiler tutorial `Translocation_final.cppipe` +through the existing comparison manifest and source-binding workspace. It uses +eight genuine wells, A01, A12, B01, B12, C01, C12, D01 and D12: one site and two +channels in each well, hence eight native image assignments. No images or wells +are synthetically repeated. The pipeline disables Groups and emits SQLite +measurements, CellProfiler Analyst properties and an overlay TIFF per assignment. + +Native input selection, imported metadata rewriting and headless export policy +come from `NativeCellProfilerInputDomainStrategy` and +`HeadlessCellProfilerPipelinePolicy`; the driver does not rewrite biological +analysis settings. The native process starts Java and loads the pipeline once, +then executes a complete warm-up batch and three complete observed batches. + +OpenHCS uses one isolated production ZMQ execution server and `num_workers=1`. +At this worker count, the production worker-executor owner executes inline in the +server; this is not a pool of external benchmark-only OpenHCS processes. Source +workspace creation and server/catalog startup precede the observations. Each +batch is compiled before its execution timer, then submitted by compile-artifact +ID. Production consumes that artifact, so subsequent batches compile again; +debug replay retention is not enabled for the benchmark. A complete first batch +is planned as warm-up; the following three are planned observations. The live +probe stopped at strict validation of that first batch. Requested exports remain +enabled, and equivalence checks use the actual resulting exports. + +The probe also writes an additional terminal `CellAndNucleiOverlay.tif` per well. +Setting `materialize_runtime_artifacts=False` preserves requested exports but did +not suppress these terminal copies in the live probe. Equal requested export +lists are therefore insufficient to prove equal write work. A declared policy +for terminal/main-flow persistence must be resolved before a matched comparison. + +Both sides run sequentially, not concurrently with one another, with +OMP, OpenBLAS, MKL, NumExpr and vecLib thread limits set to one. Native and +candidate NumPy CPU-dispatch controls are retained in the run receipt. + +## Timing membership + +| Interval | Starts | Ends | Interpretation | +| --- | --- | --- | --- | +| Native invocation | Before iterating `Pipeline.run_with_yield` | Generator completion, including `post_run` and `end_run` | Preparation and complete batch execution; imports/Java startup excluded | +| Native module interval | First public `status_callback`, immediately before first `run_module` | Same generator completion | Excludes `prepare_run` and first `prepare_group`; includes NamesAndTypes image-provider creation and subsequent pixel reads/modules/exports | +| OpenHCS compile API | Compile request submission | Compile completion observed | Recorded separately from execution | +| OpenHCS invocation | Prepared execution request submission | Successful completion observed by client | Request processing, worker setup, complete batch execution and completion observation | +| OpenHCS axis interval | First source `AXIS_STARTED` timestamp | Successful completion observed by client | Excludes earlier request/worker/context setup; includes first axis step processing and plate-scoped exports | + +Source receipts: CellProfiler's `run_with_yield` calls `prepare_run`, constructs +and enters its group, then invokes `status_callback` before each module's +`run_module`. NamesAndTypes creates image providers in its `run` method, after +that callback. OpenHCS emits `AXIS_STARTED` before entering the first context's +step loop. Completion of `execute_compiled_plate_request` includes plate-scoped +steps, analysis consolidation and completed-plate metadata; the ZMQ lifecycle +marks the execution complete only after `execute_task` returns. + +The event intervals are not yet proven identical. Native `prepare_run` can +perform source/header inspection; OpenHCS compilation and pre-axis setup do +different work. The OpenHCS endpoint is a client-observed completion, so its +interval includes polling/transport delay. Raw progress events, a 50 ms requested +poll interval and both coarse invocation durations are retained. No ratio should +be derived from these intervals until timing membership is settled explicitly. + +## Extension required before a corpus comparison + +1. Define indivisible partition units from declared source groups, stacks and + time series. Preserve group-dependent illumination, tracking and plate-wide + export semantics; do not split or repeat arbitrary image sets. +2. For matched concurrency N, use one production OpenHCS server with N worker + lanes and N native batch jobs, not N external inline OpenHCS instances. + Retain actual assignment counts and native batch ranges. +3. Preserve native global image identities when partitioning. Comparing native + per-job SQLite outputs with a production plate-wide export requires a + contract-derived table union or another equivalent whole-plate observation. + This pilot does not introduce or pretend to validate that union. +4. Settle a common completion/start boundary, including first-image reads, + preparation, group finalization and requested exports. Prefer source-owned + execution timestamps to a client-polling endpoint where available. +5. Check readiness RSS and available memory before larger concurrency. The host + initially had about 7.8 GiB available RAM and already used 20 GiB of swap; + concurrency four is not automatically a clean throughput observation. +6. Run repeated observations across the supported corpus only after those + ownership/boundary checks, retaining source, input, environment and raw result + provenance. Historical 30-workflow and dated value-extension evidence remain + separate. + +## Native runner + +`benchmark/native_cellprofiler_batch_worker.py` is deliberately executed as a +standalone script with the native Python 3.9 interpreter. Importing the benchmark +package bootstraps OpenHCS, which requires a newer Python; the runner does not +add import-path aliases or weaken that boundary. Its JSON request and result are +derived from its dataclass declarations. + +The retained candidate driver takes a task-owned output directory argument and +is a reproduction/experimental harness, not a new production API. See README.md +for the command and the observed blockers. diff --git a/benchmark/results/matched_batch_pilot_20260915/native_report.json b/benchmark/results/matched_batch_pilot_20260915/native_report.json new file mode 100644 index 0000000000..5949230bc0 --- /dev/null +++ b/benchmark/results/matched_batch_pilot_20260915/native_report.json @@ -0,0 +1,53 @@ +{ + "startup_seconds": 1.2386435749940574, + "environment": { + "python_executable": "/home/ts/code/projects/openhcs/.venv-cellprofiler39/bin/python", + "python_version": "3.9.25", + "cellprofiler_version": "4.2.8.1", + "cellprofiler_core_version": "4.2.8.1", + "numpy_version": "1.24.4", + "scipy_version": "1.9.0" + }, + "request": { + "pipeline_path": "/tmp/openhcs-matched-batch-pilot-1ayGug/native_preparation/native_cellprofiler_headless/Translocation_final.cppipe", + "input_dir": "/tmp/openhcsnativecellprofiler/jmgckfedifcnhidd/input", + "output_root": "/tmp/openhcs-matched-batch-pilot-1ayGug/native", + "expected_image_sets": 8, + "repetitions": 3, + "file_list_path": null + }, + "observations": [ + { + "repetition": -1, + "output_root": "/tmp/openhcs-matched-batch-pilot-1ayGug/native/-1", + "image_set_count": 8, + "invocation_seconds": 15.907739978283644, + "pre_first_module_seconds": 0.44451354909688234, + "first_module_through_post_run_seconds": 15.463226429186761 + }, + { + "repetition": 0, + "output_root": "/tmp/openhcs-matched-batch-pilot-1ayGug/native/0", + "image_set_count": 8, + "invocation_seconds": 19.25082396902144, + "pre_first_module_seconds": 0.3638419699855149, + "first_module_through_post_run_seconds": 18.886981999035925 + }, + { + "repetition": 1, + "output_root": "/tmp/openhcs-matched-batch-pilot-1ayGug/native/1", + "image_set_count": 8, + "invocation_seconds": 17.179643767885864, + "pre_first_module_seconds": 0.2677275352180004, + "first_module_through_post_run_seconds": 16.911916232667863 + }, + { + "repetition": 2, + "output_root": "/tmp/openhcs-matched-batch-pilot-1ayGug/native/2", + "image_set_count": 8, + "invocation_seconds": 18.889288197271526, + "pre_first_module_seconds": 0.23114556726068258, + "first_module_through_post_run_seconds": 18.658142630010843 + } + ] +} \ No newline at end of file diff --git a/benchmark/results/matched_batch_pilot_20260915/native_request.json b/benchmark/results/matched_batch_pilot_20260915/native_request.json new file mode 100644 index 0000000000..a8d910eed5 --- /dev/null +++ b/benchmark/results/matched_batch_pilot_20260915/native_request.json @@ -0,0 +1,8 @@ +{ + "pipeline_path": "/tmp/openhcs-matched-batch-pilot-1ayGug/native_preparation/native_cellprofiler_headless/Translocation_final.cppipe", + "input_dir": "/tmp/openhcsnativecellprofiler/jmgckfedifcnhidd/input", + "file_list_path": null, + "output_root": "/tmp/openhcs-matched-batch-pilot-1ayGug/native", + "expected_image_sets": 8, + "repetitions": 3 +} \ No newline at end of file diff --git a/benchmark/results/matched_batch_pilot_20260915/pilot_driver.py b/benchmark/results/matched_batch_pilot_20260915/pilot_driver.py new file mode 100644 index 0000000000..e75bbe1b0e --- /dev/null +++ b/benchmark/results/matched_batch_pilot_20260915/pilot_driver.py @@ -0,0 +1,220 @@ +from __future__ import annotations + +import hashlib +import json +import logging +import os +import platform +import shutil +import subprocess +import sys +import time +from dataclasses import replace +from pathlib import Path + +import numpy +import scipy +import openhcs +from benchmark.adapters.cellprofiler import ( + CellProfilerRunRequest, + HeadlessCellProfilerPipelinePolicy, + NativeCellProfilerInputDomainStrategy, +) +from benchmark.adapters.cppipe_source import resolve_cppipe_source +from benchmark.cellprofiler_comparison import load_comparison_cases +from benchmark.cellprofiler_export_equivalence import cellprofiler_database_export_equivalence +from openhcs.constants.constants import AllComponents +from openhcs.core.config import ( + AnalysisConsolidationConfig, + GlobalPipelineConfig, + LazyPathPlanningConfig, + LazyWellFilterConfig, + MaterializationBackend, + PathPlanningConfig, + VFSConfig, + WellFilterConfig, +) +from openhcs.core.equivalence.comparison import runtime_image_differences +from openhcs.core.equivalence.outputs import RuntimeOutputSnapshot +from openhcs.core.input_workspace import InputWorkspacePreparationRequest +from openhcs.core.runtime_execution_validation import runtime_artifact_execution_failures +from openhcs.core.pipeline_document import PipelineDocumentAuthority +from openhcs.core.progress.types import ProgressEvent, ProgressPhase +from openhcs.core.source_matching import source_component_metadata_value +from openhcs.interop.cellprofiler.measurement_dialect import cellprofiler_runtime_equivalence_policy +from openhcs.interop.cellprofiler.plate_workspace import prepare_cellprofiler_input_workspace +from openhcs.runtime.zmq_execution_client import OpenHCSExecutionSubmission, ZMQExecutionClient +from openhcs.runtime.zmq_execution_observation import ZMQRuntimeExecutionObservationExport +from objectstate.lazy_factory import ensure_global_config_context, rebuild_lazy_config_with_new_global_reference +from zmqruntime.execution import ExecutionSubmissionResponse, ExecutionWaitResult +from zmqruntime import DataControlPortPairAuthority, TransportMode +from openhcs.runtime.zmq_config import OPENHCS_ZMQ_CONFIG + + +ROOT = Path(sys.argv[1]).resolve() +ROOT.mkdir(parents=True, exist_ok=True) +PROJECT = Path.cwd().resolve() +logging.basicConfig(level=logging.WARNING) +case, = [c for c in load_comparison_cases(PROJECT / 'benchmark/manifests/official30_portable_axis1.json') if c.name == 'cp_tutorial_translocation_final'] +prepared = prepare_cellprofiler_input_workspace(InputWorkspacePreparationRequest( + selected_path=case.dataset_path, + selected_pipeline_path=case.cppipe_path, + workspace_root=ROOT / 'source_workspace', + generated_source_path=ROOT / 'pipeline.py', +)) +assert prepared.pipeline_import_error is None, prepared.pipeline_import_error +assert prepared.materialization is not None +assert prepared.pipeline_steps is not None and prepared.pipeline_config is not None +wells = tuple(sorted({source_component_metadata_value(m, AllComponents.WELL) for m in prepared.materialization.source_metadata.values()}))[:8] +assert len(wells) == 8 and None not in wells, wells +global_config = GlobalPipelineConfig( + num_workers=1, + use_threading=False, + well_filter_config=WellFilterConfig(well_filter=list(wells)), + path_planning_config=PathPlanningConfig(global_output_folder=ROOT / 'candidate', output_dir_suffix='_matched_pilot'), + vfs_config=VFSConfig(materialization_backend=MaterializationBackend.DISK), + analysis_consolidation_config=AnalysisConsolidationConfig(enabled=False), + materialize_runtime_artifacts=False, +) +ensure_global_config_context(GlobalPipelineConfig, global_config) +pipeline_config = replace( + prepared.pipeline_config, + well_filter_config=LazyWellFilterConfig(well_filter=list(wells)), + path_planning_config=LazyPathPlanningConfig(global_output_folder=ROOT / 'candidate', output_dir_suffix='_matched_pilot'), +) +pipeline_config = rebuild_lazy_config_with_new_global_reference(pipeline_config, global_config, GlobalPipelineConfig) +native_request = CellProfilerRunRequest( + dataset_path=case.dataset_path, + pipeline_name=case.name, + pipeline_params={'dataset_id': case.resolved_dataset_id, 'cppipe_path': str(case.cppipe_path)}, + metrics=(), + output_dir=ROOT / 'native_preparation', + global_config=global_config, +) +source = resolve_cppipe_source(native_request.cppipe_source) +execution_path = HeadlessCellProfilerPipelinePolicy.execution_path(source.path, native_request.output_dir) +native_domain = NativeCellProfilerInputDomainStrategy.select_for(native_request, source).prepare(native_request, source, execution_path) +native_payload = { + 'pipeline_path': str(native_domain.cppipe_path), + 'input_dir': str(native_domain.input_dir), + 'file_list_path': str(native_domain.file_list_path) if native_domain.file_list_path is not None else None, + 'output_root': str(ROOT / 'native'), + 'expected_image_sets': 8, + 'repetitions': 3, +} +(ROOT / 'native_request.json').write_text(json.dumps(native_payload, indent=2)) +print('Wells', wells, flush=True) +if (ROOT / 'native_report.json').exists(): + native_report = json.loads((ROOT / 'native_report.json').read_text()) +else: + native_completed = subprocess.run( + [str(PROJECT / '.venv-cellprofiler39/bin/python'), str(PROJECT / 'benchmark/native_cellprofiler_batch_worker.py'), str(ROOT / 'native_request.json')], + cwd=PROJECT, env=os.environ.copy(), capture_output=True, text=True, timeout=900, + ) + (ROOT / 'native_stdout.log').write_text(native_completed.stdout) + (ROOT / 'native_stderr.log').write_text(native_completed.stderr) + native_completed.check_returncode() + native_report = json.loads(native_completed.stdout.splitlines()[-1]) + (ROOT / 'native_report.json').write_text(json.dumps(native_report, indent=2)) +print('Native completed', flush=True) +port = DataControlPortPairAuthority.acquire(OPENHCS_ZMQ_CONFIG, transport_mode=TransportMode.TCP).data_port +events = [] +client = ZMQExecutionClient(port=port, persistent=False, transport_mode=TransportMode.TCP, progress_callback=lambda event: events.append(dict(event))) +observation_path = ROOT / 'candidate_observation.pkl' +submission = OpenHCSExecutionSubmission( + plate_id=case.dataset_path, + execution_plate_id=prepared.execution_plate_path, + selected_pipeline_path=case.cppipe_path, + pipeline_document=PipelineDocumentAuthority.from_values(pipeline_config=pipeline_config, pipeline_steps=prepared.pipeline_steps), + global_config=global_config, + config_params={'runtime_observation_export_path': str(observation_path)}, +) +observations = [] +policy = cellprofiler_runtime_equivalence_policy(compare_image_pixels=True) +try: + with client: + client.endpoint_compatibility().require_match() + endpoint = client.connected_endpoint + output_roots = () + for repetition in range(-1, 3): + for output_root in output_roots: + assert output_root.is_relative_to(ROOT / 'candidate') + shutil.rmtree(output_root) + compilation_started = time.perf_counter() + compiled = ExecutionSubmissionResponse.from_wire(client.submit_compile(submission)) + artifact_id = compiled.require_execution_id('Pilot compilation') + ExecutionWaitResult.from_wire(client.wait_for_completion(artifact_id, poll_interval=0.05)).require_complete('Pilot compilation') + compilation_seconds = time.perf_counter() - compilation_started + execution_submission = OpenHCSExecutionSubmission( + plate_id=case.dataset_path, execution_plate_id=prepared.execution_plate_path, + selected_pipeline_path=case.cppipe_path, + pipeline_document=submission.pipeline_document, + global_config=global_config, + config_params={'runtime_observation_export_path': str(observation_path)}, + compile_artifact_id=artifact_id, + ) + events.clear() + started_wall = time.time() + started = time.perf_counter() + response = ExecutionSubmissionResponse.from_wire(client.submit_pipeline(execution_submission)) + execution_id = response.require_execution_id('Pilot execution') + ExecutionWaitResult.from_wire(client.wait_for_completion(execution_id, poll_interval=0.05)).require_complete('Pilot execution') + completed = time.perf_counter() + completed_wall = time.time() + (ROOT / ('events_' + str(repetition) + '.json')).write_text(json.dumps(events, indent=2)) + observation = ZMQRuntimeExecutionObservationExport.read(observation_path) + current_events = [ProgressEvent.from_dict(event) for event in events if event['execution_id'] == execution_id] + axis_started = min(event.timestamp for event in current_events if event.phase is ProgressPhase.AXIS_STARTED) + probe_receipt = { + 'repetition': repetition, 'execution_id': execution_id, 'compile_artifact_id': artifact_id, + 'compile_api_seconds': compilation_seconds, + 'invocation_seconds': completed - started, + 'first_axis_through_completion_observed_seconds': completed_wall - axis_started, + 'pre_first_axis_seconds': axis_started - started_wall, + 'axis_count': observation.axis_count, + 'endpoint_pid': endpoint.process_identity.pid, + 'endpoint_log_path': endpoint.log_file_path, + 'endpoint_application_version': endpoint.application.version, + 'output_files': [str(path) for path in observation.exports.output_files], + 'execution_failures': observation.execution_failures(), + 'validation_failures': runtime_artifact_execution_failures(observation.expectation, observation.observation()), + } + (ROOT / 'candidate_probe.json').write_text(json.dumps(probe_receipt, indent=2)) + observation.require_valid_observation() + assert observation.axis_count == 8, observation.axis_count + output_roots = tuple(Path(path) for path in observation.output_roots) + native_root = ROOT / 'native' / str(repetition) + database_report = cellprofiler_database_export_equivalence(native_root, observation.exports, policy=policy) + native_images = RuntimeOutputSnapshot.from_output_root(native_root).images + candidate_images = RuntimeOutputSnapshot.from_export_observation(observation.exports).images + image_differences = runtime_image_differences(native_images, candidate_images, policy) + assert len(native_images) == len(candidate_images) == 8 + current_events = [ProgressEvent.from_dict(event) for event in events if event['execution_id'] == execution_id] + axis_started = min(event.timestamp for event in current_events if event.phase is ProgressPhase.AXIS_STARTED) + row = { + 'repetition': repetition, 'execution_id': execution_id, 'compile_artifact_id': artifact_id, + 'compile_api_seconds': compilation_seconds, + 'invocation_seconds': completed - started, + 'first_axis_through_completion_observed_seconds': completed_wall - axis_started, + 'pre_first_axis_seconds': axis_started - started_wall, + 'axis_count': observation.axis_count, + 'database_differences': [str(d) for d in database_report.differences], + 'image_differences': [str(d) for d in image_differences], + 'image_count': len(candidate_images), + 'output_roots': [str(path) for path in output_roots], + } + observations.append(row) + (ROOT / 'candidate_report.json').write_text(json.dumps(observations, indent=2)) + (ROOT / ('events_' + str(repetition) + '.json')).write_text(json.dumps(events, indent=2)) + print('Candidate', row, flush=True) +finally: + client.disconnect() +report = { + 'source_commit': subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=PROJECT, text=True).strip(), + 'scoped_dirty_diff_sha256': hashlib.sha256(subprocess.check_output(['git', 'diff', '--', 'openhcs/processing/backends/cellprofiler/intensity.py', 'openhcs/processing/backends/cellprofiler/intensity_object_quantiles_numba.py'], cwd=PROJECT)).hexdigest(), + 'case_name': case.name, 'wells': wells, 'concurrency': 1, 'repetitions': 3, + 'candidate_environment': {'python_executable': sys.executable, 'python_version': platform.python_version(), 'openhcs_version': openhcs.__version__, 'numpy_version': numpy.__version__, 'scipy_version': scipy.__version__}, + 'thread_environment': {name: os.environ[name] for name in ('OMP_NUM_THREADS', 'OPENBLAS_NUM_THREADS', 'MKL_NUM_THREADS', 'NUMEXPR_NUM_THREADS', 'VECLIB_MAXIMUM_THREADS', 'NPY_DISABLE_CPU_FEATURES')}, + 'native': native_report, 'candidate': observations, +} +(ROOT / 'report.json').write_text(json.dumps(report, indent=2)) diff --git a/benchmark/results/matched_batch_pilot_20260915/receipt.json b/benchmark/results/matched_batch_pilot_20260915/receipt.json new file mode 100644 index 0000000000..f910c4a750 --- /dev/null +++ b/benchmark/results/matched_batch_pilot_20260915/receipt.json @@ -0,0 +1,234 @@ +{ + "status": "blocked_pilot_no_matched_timing_claim", + "source_commit": "b2f3cf83b70238856193d669c0893d32ad958362", + "processing_dirty_diff_sha256": "441e265e0720bb4efbaafb9caac258e82d1d1979ff1ba4d885e13f56c3aaaa12", + "native_runner_sha256": "3d9f5b079509ba53f03e3f2b124a3c32de5156b0d8247afb6491ab142de811e1", + "executed_driver_sha256": "9b5c88e9728e8f4a5a2794303e49953d4a431eb6aca9ebda6a9f9ad760dfddf8", + "retained_driver_sha256": "694d83bbb4879a9dea5b0ac4cb33c110711911b06bb4e49af8d314f59266c32d", + "manifest_sha256": "a4a7c23ac2414614678012b05b058bc9c18cf3668b105cd663528a38ef2b437e", + "original_pipeline_sha256": "a1600b567d0212ab29d4e86cc4da52bf278500fc820775ccd0d4ed4761b4e2de", + "candidate_environment": { + "python_executable": "/home/ts/code/projects/openhcs/.venv/bin/python", + "python_version": "3.12.3", + "openhcs_version": "0.8.5", + "numpy_version": "2.1.3", + "scipy_version": "1.18.0", + "platform": "Linux-7.1.5-arch1-2-x86_64-with-glibc2.44" + }, + "requested_thread_environment": { + "OMP_NUM_THREADS": "1", + "OPENBLAS_NUM_THREADS": "1", + "MKL_NUM_THREADS": "1", + "NUMEXPR_NUM_THREADS": "1", + "VECLIB_MAXIMUM_THREADS": "1" + }, + "numpy_disabled_cpu_features": "AVX512_SKX,X86_V4", + "python_hash_seed": "0", + "candidate_runtime_materialize_flag": false, + "object_counts_by_image": { + "native": [ + [ + 1, + 306 + ], + [ + 2, + 182 + ], + [ + 3, + 150 + ], + [ + 4, + 147 + ], + [ + 5, + 142 + ], + [ + 6, + 194 + ], + [ + 7, + 160 + ], + [ + 8, + 167 + ] + ], + "candidate": [ + [ + 1, + 306 + ], + [ + 2, + 182 + ], + [ + 3, + 150 + ], + [ + 4, + 147 + ], + [ + 5, + 142 + ], + [ + 6, + 194 + ], + [ + 7, + 160 + ], + [ + 8, + 167 + ] + ] + }, + "database_difference_count": 4, + "database_differences": [ + { + "kind": "measurement_content", + "message": "SQLite database 'DefaultDB.db' table 'Per_Image': measurement feature object:cytoplasm/mean(k_raw_dna_raw_gfp) values differ" + }, + { + "kind": "measurement_content", + "message": "SQLite database 'DefaultDB.db' table 'Per_Image': measurement feature object:cytoplasm/mean(k_raw_gfp_raw_dna) values differ" + }, + { + "kind": "measurement_content", + "message": "SQLite database 'DefaultDB.db' table 'Per_Image': measurement feature object:cytoplasm/mean(overlap_raw_dna_raw_gfp) values differ" + }, + { + "kind": "table_content", + "message": "SQLite database 'DefaultDB.db' table 'Per_Object': table schema ('Cells_Children_Cytoplasm_Count', 'Cells_Location_Center_X', 'Cells_Location_Center_Y', 'Cells_Location_Center_Z', 'Cells_Number_Object_Number', 'Cells_Parent_Nuclei', 'Cytoplasm_Correlation_Correlation_rawDNA_rawGFP', 'Cytoplasm_Correlation_Costes_rawDNA_rawGFP', 'Cytoplasm_Correlation_Costes_rawGFP_rawDNA', 'Cytoplasm_Correlation_K_rawDNA_rawGFP', 'Cytoplasm_Correlation_K_rawGFP_rawDNA', 'Cytoplasm_Correlation_Manders_rawDNA_rawGFP', 'Cytoplasm_Correlation_Manders_rawGFP_rawDNA', 'Cytoplasm_Correlation_Overlap_rawDNA_rawGFP', 'Cytoplasm_Correlation_RWC_rawDNA_rawGFP', 'Cytoplasm_Correlation_RWC_rawGFP_rawDNA', 'Cytoplasm_Intensity_IntegratedIntensityEdge_rawGFP', 'Cytoplasm_Intensity_IntegratedIntensity_rawGFP', 'Cytoplasm_Intensity_LowerQuartileIntensity_rawGFP', 'Cytoplasm_Intensity_MADIntensity_rawGFP', 'Cytoplasm_Intensity_MassDisplacement_rawGFP', 'Cytoplasm_Intensity_MaxIntensityEdge_rawGFP', 'Cytoplasm_Intensity_MaxIntensity_rawGFP', 'Cytoplasm_Intensity_MeanIntensityEdge_rawGFP', 'Cytoplasm_Intensity_MeanIntensity_rawGFP', 'Cytoplasm_Intensity_MedianIntensity_rawGFP', 'Cytoplasm_Intensity_MinIntensityEdge_rawGFP', 'Cytoplasm_Intensity_MinIntensity_rawGFP', 'Cytoplasm_Intensity_StdIntensityEdge_rawGFP', 'Cytoplasm_Intensity_StdIntensity_rawGFP', 'Cytoplasm_Intensity_UpperQuartileIntensity_rawGFP', 'Cytoplasm_Location_CenterMassIntensity_X_rawGFP', 'Cytoplasm_Location_CenterMassIntensity_Y_rawGFP', 'Cytoplasm_Location_CenterMassIntensity_Z_rawGFP', 'Cytoplasm_Location_Center_X', 'Cytoplasm_Location_Center_Y', 'Cytoplasm_Location_MaxIntensity_X_rawGFP', 'Cytoplasm_Location_MaxIntensity_Y_rawGFP', 'Cytoplasm_Location_MaxIntensity_Z_rawGFP', 'Cytoplasm_Math_IntensityRatio', 'Cytoplasm_Number_Object_Number', 'Cytoplasm_Parent_Cells', 'Cytoplasm_Parent_Nuclei', 'ImageNumber', 'Nuclei_Children_Cells_Count', 'Nuclei_Children_Cytoplasm_Count', 'Nuclei_Correlation_Correlation_rawDNA_rawGFP', 'Nuclei_Correlation_Costes_rawDNA_rawGFP', 'Nuclei_Correlation_Costes_rawGFP_rawDNA', 'Nuclei_Correlation_K_rawDNA_rawGFP', 'Nuclei_Correlation_K_rawGFP_rawDNA', 'Nuclei_Correlation_Manders_rawDNA_rawGFP', 'Nuclei_Correlation_Manders_rawGFP_rawDNA', 'Nuclei_Correlation_Overlap_rawDNA_rawGFP', 'Nuclei_Correlation_RWC_rawDNA_rawGFP', 'Nuclei_Correlation_RWC_rawGFP_rawDNA', 'Nuclei_Intensity_IntegratedIntensityEdge_rawGFP', 'Nuclei_Intensity_IntegratedIntensity_rawGFP', 'Nuclei_Intensity_LowerQuartileIntensity_rawGFP', 'Nuclei_Intensity_MADIntensity_rawGFP', 'Nuclei_Intensity_MassDisplacement_rawGFP', 'Nuclei_Intensity_MaxIntensityEdge_rawGFP', 'Nuclei_Intensity_MaxIntensity_rawGFP', 'Nuclei_Intensity_MeanIntensityEdge_rawGFP', 'Nuclei_Intensity_MeanIntensity_rawGFP', 'Nuclei_Intensity_MedianIntensity_rawGFP', 'Nuclei_Intensity_MinIntensityEdge_rawGFP', 'Nuclei_Intensity_MinIntensity_rawGFP', 'Nuclei_Intensity_StdIntensityEdge_rawGFP', 'Nuclei_Intensity_StdIntensity_rawGFP', 'Nuclei_Intensity_UpperQuartileIntensity_rawGFP', 'Nuclei_Location_CenterMassIntensity_X_rawGFP', 'Nuclei_Location_CenterMassIntensity_Y_rawGFP', 'Nuclei_Location_CenterMassIntensity_Z_rawGFP', 'Nuclei_Location_Center_X', 'Nuclei_Location_Center_Y', 'Nuclei_Location_Center_Z', 'Nuclei_Location_MaxIntensity_X_rawGFP', 'Nuclei_Location_MaxIntensity_Y_rawGFP', 'Nuclei_Location_MaxIntensity_Z_rawGFP', 'Nuclei_Math_IntensityRatio', 'Nuclei_Number_Object_Number', 'ObjectNumber') values differ" + } + ], + "specific_correlation_cell_differences": [ + { + "image_number": 3, + "object_number": 91, + "native": [ + null, + null, + null + ], + "candidate": [ + 0.0, + 0.0, + 0.0 + ] + }, + { + "image_number": 3, + "object_number": 108, + "native": [ + null, + null, + null + ], + "candidate": [ + 0.0, + 0.0, + 0.0 + ] + }, + { + "image_number": 7, + "object_number": 7, + "native": [ + null, + null, + null + ], + "candidate": [ + 0.0, + 0.0, + 0.0 + ] + } + ], + "native_image_count": 8, + "candidate_image_count": 8, + "image_difference_count": 0, + "image_pixel_digests": { + "native": [ + { + "name": "BBBC013_A01_s1_w1_Overlay.tiff", + "digest": "de4166afb448fb9a85af20da2d390c7da7ca1183d0aa9412a4f7b9b132c38754" + }, + { + "name": "BBBC013_A12_s1_w1_Overlay.tiff", + "digest": "67e96ad1c5e14bbd9066c33819c3e01b593f92c78fb8b5ad724ec698b14fbb59" + }, + { + "name": "BBBC013_B01_s1_w1_Overlay.tiff", + "digest": "c58c22ec95c0fce93fa787aad42061be2ab77221c68973d4b6bc83701c2544ae" + }, + { + "name": "BBBC013_B12_s1_w1_Overlay.tiff", + "digest": "548433113c4f7c9f52c8d25c16738a9d5ffc97daecc2399fd33278aa92eb3aff" + }, + { + "name": "BBBC013_C01_s1_w1_Overlay.tiff", + "digest": "b95191b91ddc1bddd16c80f1f79ff1cd8672489f071430d3166353d9b6fe52dc" + }, + { + "name": "BBBC013_C12_s1_w1_Overlay.tiff", + "digest": "f6529e87b91f2278d4c8d1bb7e1ff8259b838176857e5dc0cb40359b9dcbb58f" + }, + { + "name": "BBBC013_D01_s1_w1_Overlay.tiff", + "digest": "3dd05fc67f0138833dddd0b16c737701b900ad08e38b8ff97ef7b88a87b39677" + }, + { + "name": "BBBC013_D12_s1_w1_Overlay.tiff", + "digest": "4ca8bbf6403076ff800a48295e1fc8f61120108333bfc3e063bae92ba04a1d65" + } + ], + "candidate": [ + { + "name": "A01_s001_w1_z001_t001_Overlay.tiff", + "digest": "de4166afb448fb9a85af20da2d390c7da7ca1183d0aa9412a4f7b9b132c38754" + }, + { + "name": "A12_s001_w1_z001_t001_Overlay.tiff", + "digest": "67e96ad1c5e14bbd9066c33819c3e01b593f92c78fb8b5ad724ec698b14fbb59" + }, + { + "name": "B01_s001_w1_z001_t001_Overlay.tiff", + "digest": "c58c22ec95c0fce93fa787aad42061be2ab77221c68973d4b6bc83701c2544ae" + }, + { + "name": "B12_s001_w1_z001_t001_Overlay.tiff", + "digest": "548433113c4f7c9f52c8d25c16738a9d5ffc97daecc2399fd33278aa92eb3aff" + }, + { + "name": "C01_s001_w1_z001_t001_Overlay.tiff", + "digest": "b95191b91ddc1bddd16c80f1f79ff1cd8672489f071430d3166353d9b6fe52dc" + }, + { + "name": "C12_s001_w1_z001_t001_Overlay.tiff", + "digest": "f6529e87b91f2278d4c8d1bb7e1ff8259b838176857e5dc0cb40359b9dcbb58f" + }, + { + "name": "D01_s001_w1_z001_t001_Overlay.tiff", + "digest": "3dd05fc67f0138833dddd0b16c737701b900ad08e38b8ff97ef7b88a87b39677" + }, + { + "name": "D12_s001_w1_z001_t001_Overlay.tiff", + "digest": "4ca8bbf6403076ff800a48295e1fc8f61120108333bfc3e063bae92ba04a1d65" + } + ] + } +} From 3953825ddfdde54efe5fba3cab2fcd7dc259003c Mon Sep 17 00:00:00 2001 From: Tristan Simas Date: Mon, 21 Sep 2026 23:34:55 -0400 Subject: [PATCH 06/15] Revise SLAS evidence and neurite figures --- paper/build_paper.py | 2 + paper/figures/build_slas_agent.py | 438 +++- paper/figures/build_slas_cellprofiler.py | 4 + .../figures/slas/cellprofiler_translation.pdf | Bin 53882 -> 53882 bytes .../figures/slas/cellprofiler_translation.svg | 90 +- .../slas/cellprofiler_translation_imported.py | 9 +- .../cellprofiler_translation_provenance.json | 14 +- paper/figures/slas/figure3_agent_workflow.pdf | Bin 871250 -> 538575 bytes paper/figures/slas/figure3_agent_workflow.png | Bin 1306273 -> 947007 bytes paper/figures/slas/figure3_agent_workflow.svg | 2057 ++++++++++++++++- paper/figures/slas/figure3_provenance.json | 67 +- paper/manuscript.md | 69 +- paper/openhcs_references.json | 53 + ...o_fourth_replay_receipt_review_20260915.md | 91 + .../own_data_neurite_comparator_20260915.md | 162 ++ .../own_neurite_blind_analysis_20260915.md | 157 ++ .../plans/slas_framing_discussion_20260914.md | 10 +- paper/plans/slas_revision_20260915.md | 111 + paper/requirements-build.txt | 5 +- paper/supplementary/README.md | 184 +- .../current_neurite_replay_summary.md | 81 + .../neuroncyto_reference_audit.md | 173 ++ paper/test_build_paper.py | 9 + 23 files changed, 3468 insertions(+), 318 deletions(-) create mode 100644 paper/plans/neuroncyto_fourth_replay_receipt_review_20260915.md create mode 100644 paper/plans/own_data_neurite_comparator_20260915.md create mode 100644 paper/plans/own_neurite_blind_analysis_20260915.md create mode 100644 paper/plans/slas_revision_20260915.md create mode 100644 paper/supplementary/current_neurite_replay_summary.md create mode 100644 paper/supplementary/neuroncyto_reference_audit.md diff --git a/paper/build_paper.py b/paper/build_paper.py index 4e83847f89..fe8465d890 100644 --- a/paper/build_paper.py +++ b/paper/build_paper.py @@ -25,6 +25,7 @@ def resolve( for path in ( root / "build_docx_from_markdown.py", root / "requirements-build.txt", + root.parent / "scripts/requirements-quality.txt", *sorted((root / "figures").glob("build_slas*.py")), ): observations.read(path) @@ -41,6 +42,7 @@ def refresh(self, root: Path) -> None: PAPER = PaperDefinition( identity="slas-openhcs", + output_prefix="openhcs", root=ROOT, declaration=Path(__file__).resolve(), documents=( diff --git a/paper/figures/build_slas_agent.py b/paper/figures/build_slas_agent.py index 0e8b1c2f7f..9dd598df15 100644 --- a/paper/figures/build_slas_agent.py +++ b/paper/figures/build_slas_agent.py @@ -1,30 +1,28 @@ -"""Assemble original inputs and a frame from the retained unattended run.""" +"""Assemble the agent-authored neurite workflow and current native replay.""" from __future__ import annotations import ast +import csv import hashlib import json -import subprocess from pathlib import Path import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt -from matplotlib.patches import Rectangle +import numpy as np import tifffile +from skimage.segmentation import find_boundaries ROOT = Path(__file__).resolve().parents[2] -ASSETS = ROOT / "website/assets/agent" OUTPUT = Path(__file__).resolve().parent / "slas" -FRAME_SECONDS = 600 -# Editorial selections in the verified 1280 x 720 archived video frame. -# Coordinates are (left, top, right, bottom), without image resampling. -FRAME_DETAILS = ( - ("D Neuron and neurite outlines", (380, 70, 725, 400)), - ("E Three path measurements", (691, 501, 978, 580)), -) +SOURCE_MANIFEST = OUTPUT / "figure3_current_replay_sources.json" +NEURITE_PIPELINE_SUFFIX = "/neurite/plate" +# Native screenshot coordinates: x0, y0, x1, y1 of the napari canvas. +DETAIL_CANVAS_XYXY = (580, 40, 1753, 720) +SOMA_ASSIGNMENT_PADDING = 72 def digest(path: Path) -> str: @@ -32,153 +30,337 @@ def digest(path: Path) -> str: return hashlib.file_digest(stream, "sha256").hexdigest() -def build() -> None: - record_path = ASSETS / "cold-start-workflow-record.json" - record = json.loads(record_path.read_text()) - media = record["evidence"]["media"] - video = ASSETS / media["uncut_video_path"] - if digest(video) != media["uncut_video_sha256"]: - raise ValueError("Original uncut video hash differs from run record") - fixture = record["fixture"] - images = [] - sources = { - str(record_path.relative_to(ROOT)): digest(record_path), - str(video.relative_to(ROOT)): digest(video), - } - for item in fixture["file_manifest"]: - if Path(item["path"]).suffix != ".tif": - continue - path = Path(fixture["plate_root"]) / item["path"] - if digest(path) != item["sha256"]: - raise ValueError(f"Input hash differs from run record: {path}") - pixels = tifffile.imread(path) - if list(pixels.shape) != item["shape"] or str(pixels.dtype) != item["dtype"]: - raise ValueError(f"Input geometry differs from run record: {path}") - sources[str(path.relative_to(ROOT))] = digest(path) - images.append((item["path"], pixels)) - if len(images) != 2: - raise ValueError("This figure requires the recorded pair of input channels") - OUTPUT.mkdir(parents=True, exist_ok=True) - frame = OUTPUT / "figure3_original_video_frame.png" - subprocess.run( - [ - "ffmpeg", - "-v", - "error", - "-y", - "-ss", - str(FRAME_SECONDS), - "-i", - str(video), - "-frames:v", - "1", - str(frame), - ], - check=True, +def verified_sources() -> tuple[dict[str, object], dict[str, Path]]: + manifest = json.loads(SOURCE_MANIFEST.read_text(encoding="utf-8")) + paths: dict[str, Path] = {} + for role, declaration in manifest["sources"].items(): + path = ROOT / declaration["path"] + if digest(path) != declaration["sha256"]: + raise ValueError(f"Figure 3 source hash differs for {role}: {path}") + paths[role] = path + return manifest, paths + + +def neurite_step_labels(path: Path) -> list[str]: + tree = ast.parse(path.read_text(encoding="utf-8")) + pipeline_data = next( + node.value + for node in tree.body + if isinstance(node, ast.Assign) + and any( + isinstance(target, ast.Name) and target.id == "pipeline_data" + for target in node.targets + ) ) - pipeline = ASSETS / record["evidence"]["pipeline_source_path"] - if digest(pipeline) != record["evidence"]["pipeline_source_sha256"]: - raise ValueError("Saved pipeline differs from original run record") - sources[str(pipeline.relative_to(ROOT))] = digest(pipeline) - tree = ast.parse(pipeline.read_text()) - steps = [ - node - for node in ast.walk(tree) - if isinstance(node, ast.Call) - and isinstance(node.func, ast.Name) - and node.func.id == "FunctionStep" - ] - step_labels = [] - for step in steps: + if not isinstance(pipeline_data, ast.Dict): + raise ValueError("pipeline_data must be a literal dictionary") + step_nodes = next( + value.elts + for key, value in zip(pipeline_data.keys, pipeline_data.values, strict=True) + if isinstance(key, ast.Constant) + and isinstance(key.value, str) + and key.value.endswith(NEURITE_PIPELINE_SUFFIX) + and isinstance(value, ast.List) + ) + labels: list[str] = [] + for step in step_nodes: + if not isinstance(step, ast.Call): + raise ValueError("Neurite pipeline entries must be FunctionStep calls") keywords = {item.arg: item.value for item in step.keywords} name = ast.literal_eval(keywords["name"]) - function = ast.unparse(keywords["func"].elts[0]) - step_labels.append(f"{name}\n{function}") - if len(step_labels) != 2: - raise ValueError("Review the diagram when the retained step sequence changes") - video_pixels = plt.imread(frame) - if video_pixels.shape[:2] != (720, 1280): - raise ValueError("Review editorial crops when original video geometry changes") - fig = plt.figure(figsize=(9, 9.3), layout="constrained") - grid = fig.add_gridspec(4, 6, height_ratios=(1, 0.24, 1.25, 0.85)) - for index, (name, pixels) in enumerate(images): - axis = fig.add_subplot(grid[0, index * 3 : (index + 1) * 3]) + function_node = keywords["func"] + if isinstance(function_node, ast.Tuple): + function_node = function_node.elts[0] + labels.append(f"{name}\n{ast.unparse(function_node)}") + if len(labels) != 2: + raise ValueError("Figure 3 expects the frozen two-step neurite pipeline") + return labels + + +def read_measurements( + cell_path: Path, + summary_path: Path, +) -> tuple[list[dict[str, str]], dict[str, str]]: + with cell_path.open(newline="", encoding="utf-8") as stream: + cells = list(csv.DictReader(stream)) + with summary_path.open(newline="", encoding="utf-8") as stream: + summaries = list(csv.DictReader(stream)) + if len(summaries) != 1: + raise ValueError("Figure 3 expects one retained summary row") + summary = summaries[0] + if int(summary["number_of_cells"]) != len(cells): + raise ValueError("Summary cell count differs from the per-cell table") + total_length = sum(float(row["total_outgrowth_um"]) for row in cells) + if not np.isclose(total_length, float(summary["total_outgrowth_um"]), atol=1e-9): + raise ValueError("Summary length differs from the per-cell table") + if sum(int(row["processes"]) for row in cells) != int(summary["total_processes"]): + raise ValueError("Summary process count differs from the per-cell table") + if sum(int(row["branches"]) for row in cells) != int(summary["total_branches"]): + raise ValueError("Summary branch count differs from the per-cell table") + return cells, summary + + +def detail_canvas(path: Path) -> np.ndarray: + pixels = plt.imread(path) + left, top, right, bottom = DETAIL_CANVAS_XYXY + if pixels.shape[1] < right or pixels.shape[0] < bottom: + raise ValueError(f"Native detail capture geometry changed: {path}") + return pixels[top:bottom, left:right] + + +def nonempty_label_plane(path: Path) -> np.ndarray: + """Return the one spatial plane containing labels in a retained artifact.""" + + labels = np.asarray(tifffile.imread(path)) + if labels.ndim == 2: + return labels + planes = labels.reshape((-1, *labels.shape[-2:])) + nonempty = tuple(plane for plane in planes if np.any(plane)) + if len(nonempty) != 1: + raise ValueError( + f"Expected one nonempty label plane in {path}; found {len(nonempty)}" + ) + return nonempty[0] + + +def overlapping_label( + labels: np.ndarray, + selection: np.ndarray, + *, + role: str, +) -> int: + """Resolve one retained label identity from maximal spatial overlap.""" + + identities, counts = np.unique(labels[selection], return_counts=True) + candidates = tuple( + (int(identity), int(count)) + for identity, count in zip(identities, counts, strict=True) + if identity != 0 + ) + if not candidates: + raise ValueError(f"Selected soma has no overlapping {role} label") + maximum = max(count for _, count in candidates) + winners = tuple(identity for identity, count in candidates if count == maximum) + if len(winners) != 1: + raise ValueError(f"Selected soma has ambiguous {role} labels: {winners}") + return winners[0] + + +def soma_assignment_overlay( + neurite_signal: np.ndarray, + nuclei_labels: np.ndarray, + cell_body_labels: np.ndarray, + neuron_labels: np.ndarray, +) -> tuple[np.ndarray, dict[str, object]]: + """Render one derived nucleus-to-soma-to-neuron ownership example.""" + + body_identities = tuple( + int(value) for value in np.unique(cell_body_labels) if value + ) + if not body_identities: + raise ValueError("Retained replay contains no cell-body labels") + body_centroid_y = { + identity: float(np.nonzero(cell_body_labels == identity)[0].mean()) + for identity in body_identities + } + target_body = max(body_identities, key=body_centroid_y.__getitem__) + body_mask = cell_body_labels == target_body + target_nucleus = overlapping_label( + nuclei_labels, + body_mask, + role="nucleus", + ) + target_neuron = overlapping_label( + neuron_labels, + body_mask, + role="neuron", + ) + nucleus_mask = nuclei_labels == target_nucleus + neuron_mask = neuron_labels == target_neuron + + rows, columns = np.nonzero(body_mask | nucleus_mask) + top = max(0, int(rows.min()) - SOMA_ASSIGNMENT_PADDING) + bottom = min(neurite_signal.shape[0], int(rows.max()) + SOMA_ASSIGNMENT_PADDING + 1) + left = max(0, int(columns.min()) - SOMA_ASSIGNMENT_PADDING) + right = min( + neurite_signal.shape[1], int(columns.max()) + SOMA_ASSIGNMENT_PADDING + 1 + ) + crop = np.s_[top:bottom, left:right] + + grayscale = neurite_signal[crop].astype(np.float32) / 255.0 + overlay = np.repeat(grayscale[..., np.newaxis], 3, axis=-1) + cropped_body = body_mask[crop] + cropped_nucleus = nucleus_mask[crop] + cropped_neuron = neuron_mask[crop] + overlay[cropped_body] = 0.55 * overlay[cropped_body] + 0.45 * np.array( + [0.0, 0.85, 0.95] + ) + overlay[cropped_nucleus] = 0.45 * overlay[cropped_nucleus] + 0.55 * np.array( + [1.0, 0.15, 0.55] + ) + overlay[find_boundaries(cropped_neuron, mode="outer")] = (1.0, 0.78, 0.0) + overlay[find_boundaries(cropped_body, mode="outer")] = (0.0, 0.95, 1.0) + overlay[find_boundaries(cropped_nucleus, mode="outer")] = (1.0, 0.15, 0.55) + return overlay, { + "cell_body_label": target_body, + "nucleus_label": target_nucleus, + "neuron_label": target_neuron, + "crop_xyxy": [left, top, right, bottom], + "selection": "cell body with greatest image-row centroid", + "label_matching": "maximal nonzero pixel overlap with selected cell body", + "colors": { + "nucleus": "magenta", + "cell_body": "cyan", + "assigned_neuron": "yellow", + }, + } + + +def build() -> None: + manifest, sources = verified_sources() + images = [ + ("Neurite and soma signal", tifffile.imread(sources["input_neurite"])), + ("Nuclear signal", tifffile.imread(sources["input_nuclear"])), + ] + if any( + pixels.shape != (800, 800) or pixels.dtype != np.uint8 for _, pixels in images + ): + raise ValueError("Figure 3 input geometry or dtype changed") + step_labels = neurite_step_labels(sources["pipeline_source"]) + cells, summary = read_measurements( + sources["cell_measurements"], + sources["summary_measurements"], + ) + overview = plt.imread(sources["viewer_overview"]) + crossing_detail = detail_canvas(sources["crossing_detail"]) + nuclei_labels = nonempty_label_plane(sources["nuclei_labels"]) + cell_body_labels = nonempty_label_plane(sources["cell_body_labels"]) + neuron_labels = nonempty_label_plane(sources["neuron_labels"]) + soma_detail, soma_overlay_receipt = soma_assignment_overlay( + images[0][1], + nuclei_labels, + cell_body_labels, + neuron_labels, + ) + nuclei_count = int(np.count_nonzero(np.unique(nuclei_labels))) + + OUTPUT.mkdir(parents=True, exist_ok=True) + figure = plt.figure(figsize=(9, 9.2), layout="constrained") + grid = figure.add_gridspec( + 5, + 6, + height_ratios=(1.0, 0.2, 1.1, 0.9, 0.8), + ) + for index, (title, pixels) in enumerate(images): + axis = figure.add_subplot(grid[0, index * 3 : (index + 1) * 3]) axis.imshow(pixels, cmap="gray", vmin=0, vmax=255, interpolation="nearest") - axis.set_title(f"{'AB'[index]} Original input: {name}", fontsize=12) + axis.set_title(f"{'AB'[index]} {title}", fontsize=12) axis.set_axis_off() + for index, label in enumerate(step_labels): - axis = fig.add_subplot(grid[1, index * 3 : (index + 1) * 3]) + axis = figure.add_subplot(grid[1, index * 3 : (index + 1) * 3]) axis.text( 0.5, 0.5, f"Step {index + 1}: {label}", - fontsize=10, + fontsize=9.5, color="#16877f", ha="center", va="center", bbox={ - "boxstyle": "round,pad=0.6", + "boxstyle": "round,pad=0.55", "facecolor": "#edf7f5", "edgecolor": "#16877f", }, ) axis.set_axis_off() - axis = fig.add_subplot(grid[2, :4]) - axis.imshow(video_pixels) - axis.set_title("C Recorded napari inspection", fontsize=12) - axis.set_axis_off() - detail_positions = (grid[2, 4:], grid[3, :]) - for position, (title, (left, top, right, bottom)) in zip( - detail_positions, FRAME_DETAILS, strict=True + + overview_axis = figure.add_subplot(grid[2:4, :4]) + overview_axis.imshow(overview, interpolation="nearest") + overview_axis.set_title("C Current-source napari review", fontsize=12) + overview_axis.set_axis_off() + + for position, title, pixels in ( + (grid[2, 4:], "D Nucleus-supported soma", soma_detail), + (grid[3, 4:], "E Resolved crossing", crossing_detail), ): - axis.add_patch( - Rectangle( - (left, top), - right - left, - bottom - top, - fill=False, - edgecolor="#f3ac44", - linewidth=1, - ) - ) - axis.text(left, top - 6, title[0], color="#f3ac44", fontsize=10) - detail = fig.add_subplot(position) - detail.imshow(video_pixels[top:bottom, left:right], interpolation="nearest") - detail.set_title(title, fontsize=11) - detail.set_axis_off() - detail.text( - 0.5, - -0.12, - "Native _um labels; physical calibration not recorded", - transform=detail.transAxes, - ha="center", - fontsize=10, - color="#526174", + axis = figure.add_subplot(position) + axis.imshow(pixels, interpolation="nearest") + axis.set_title(title, fontsize=10.5) + axis.set_axis_off() + + lengths_axis = figure.add_subplot(grid[4, :4]) + cell_ids = [int(row["cell"]) for row in cells] + lengths = [float(row["total_outgrowth_um"]) for row in cells] + lengths_axis.bar(cell_ids, lengths, color="#16877f", width=0.72) + lengths_axis.set_title("F Measured path length by neuron", fontsize=11) + lengths_axis.set_xlabel("Neuron identity") + lengths_axis.set_ylabel("Path length (pixels)") + lengths_axis.set_xticks(cell_ids) + lengths_axis.spines[["top", "right"]].set_visible(False) + lengths_axis.grid(axis="y", color="#d9e0e5", linewidth=0.7) + lengths_axis.set_axisbelow(True) + + summary_axis = figure.add_subplot(grid[4, 4:]) + summary_axis.set_title("G Current replay", fontsize=11) + summary_rows = ( + ("Neurons", int(summary["number_of_cells"])), + ("Nuclei", nuclei_count), + ("Processes", int(summary["total_processes"])), + ("Branch events", int(summary["total_branches"])), + ("Resolved crossovers", int(summary["resolved_crossovers"])), + ("Total path", f"{float(summary['total_outgrowth_um']):.1f} px"), ) - outputs = [frame] + table = summary_axis.table( + cellText=summary_rows, + colWidths=(0.68, 0.32), + cellLoc="left", + loc="center", + ) + table.auto_set_font_size(False) + table.set_fontsize(9) + table.scale(1.0, 1.35) + for (row, column), cell in table.get_celld().items(): + cell.set_edgecolor("#d9e0e5") + cell.set_facecolor("#edf7f5" if row % 2 == 0 else "white") + if column == 1: + cell.get_text().set_ha("right") + summary_axis.set_axis_off() + + outputs: list[Path] = [] for suffix in ("png", "pdf", "svg"): destination = OUTPUT / f"figure3_agent_workflow.{suffix}" - fig.savefig(destination, dpi=300) + figure.savefig(destination, dpi=300) outputs.append(destination) - plt.close(fig) + plt.close(figure) + receipt = { - "source_sha256": sources, - "generator_sha256": digest(Path(__file__)), - "run_id": record["run"]["run_id"], - "openhcs_version": record["openhcs"]["version"], - "video_frame_seconds": FRAME_SECONDS, - "image_display": "Original uint8 TIFF pixels displayed linearly at 0..255; no spatial crop", - "video_display": "Full original frame with labelled detail rectangles; D/E are unchanged pixel crops of the same frame, not the later corrected replay", - "video_detail_crops_xyxy": { - title: list(bounds) for title, bounds in FRAME_DETAILS + "source_manifest": str(SOURCE_MANIFEST.relative_to(ROOT)), + "source_manifest_sha256": digest(SOURCE_MANIFEST), + "source_sha256": { + str(path.relative_to(ROOT)): digest(path) for path in sources.values() }, + "generator_sha256": digest(Path(__file__)), + "replay_execution_id": manifest["replay_execution_id"], + "image_display": "Original uint8 TIFF pixels displayed linearly at 0..255", + "viewer_display": ( + "Panel C and the crossing detail are native Qt captures; the crossing " + f"detail is an unchanged canvas crop using xyxy={DETAIL_CANVAS_XYXY}. " + "Panel D is a deterministic overlay of retained input pixels and labels." + ), + "soma_assignment_overlay": soma_overlay_receipt, + "measurement_units": ( + "Pixels: the retained source has unit spacing and no physical calibration" + ), "step_labels": step_labels, - "output_sha256": {p.name: digest(p) for p in outputs}, + "derived_summary": {label: value for label, value in summary_rows}, + "output_sha256": {path.name: digest(path) for path in outputs}, } (OUTPUT / "figure3_provenance.json").write_text( - json.dumps(receipt, indent=2) + "\n" + json.dumps(receipt, indent=2) + "\n", + encoding="utf-8", ) - print(f"Rendered original-run agent figure to {OUTPUT}") + print(f"Rendered current-replay agent figure to {OUTPUT}") if __name__ == "__main__": diff --git a/paper/figures/build_slas_cellprofiler.py b/paper/figures/build_slas_cellprofiler.py index 7d2ee668a9..7388406232 100644 --- a/paper/figures/build_slas_cellprofiler.py +++ b/paper/figures/build_slas_cellprofiler.py @@ -11,6 +11,7 @@ import json from pathlib import Path +import black from matplotlib.patches import Rectangle from objectstate import semantic_values_equal @@ -72,7 +73,10 @@ def build(): document_source = PipelineDocumentAuthority.render( PipelineDocument(config, steps), clean_mode=False ) + document_source = black.format_str(document_source, mode=black.Mode()) restored = PipelineDocumentAuthority.from_source(document_source) + if not semantic_values_equal(config, restored.pipeline_config): + raise ValueError("Generated Python did not preserve imported pipeline settings") for original, recovered in zip(steps, restored.pipeline_steps, strict=True): for before, after in zip( normalize_function_pattern(original.func).iter_items(), diff --git a/paper/figures/slas/cellprofiler_translation.pdf b/paper/figures/slas/cellprofiler_translation.pdf index 24bc8096dd7c7893506b65b00ee6352e4aa1a673..a504b25e1337634e4f608fe14e114709474d2e15 100644 GIT binary patch delta 22 ecmeyhg!$JJ<_!lAvzr=PnwT0`Y(8;#6CVJ2CJF2S delta 22 ecmeyhg!$JJ<_!lAvzr*28k-v#Z$5E&6CVJ1=?Uck diff --git a/paper/figures/slas/cellprofiler_translation.svg b/paper/figures/slas/cellprofiler_translation.svg index 231d5047d7..de16744067 100644 --- a/paper/figures/slas/cellprofiler_translation.svg +++ b/paper/figures/slas/cellprofiler_translation.svg @@ -6,7 +6,7 @@ - 2026-09-14T15:37:24.154549 + 2026-09-15T19:45:09.125955 image/svg+xml @@ -32,12 +32,12 @@ z +" clip-path="url(#p6628149e2d)" style="fill: none; stroke: #16877f; stroke-width: 1.4; stroke-linecap: round"/> +" clip-path="url(#p6628149e2d)" style="fill: #16877f; stroke: #16877f; stroke-width: 1.4; stroke-linecap: round"/> +" clip-path="url(#p6628149e2d)" style="fill: #f3f6f9"/> +" clip-path="url(#p6628149e2d)" style="fill: none; stroke: #16877f; stroke-width: 1.4; stroke-linecap: round"/> +" clip-path="url(#p6628149e2d)" style="fill: #16877f; stroke: #16877f; stroke-width: 1.4; stroke-linecap: round"/> +" clip-path="url(#p6628149e2d)" style="fill: none; stroke: #16877f; stroke-width: 1.4; stroke-linecap: round"/> +" clip-path="url(#p6628149e2d)" style="fill: #16877f; stroke: #16877f; stroke-width: 1.4; stroke-linecap: round"/> +" clip-path="url(#p6628149e2d)" style="fill: #f3f6f9"/> +" clip-path="url(#p6628149e2d)" style="fill: none; stroke: #16877f; stroke-width: 1.4; stroke-linecap: round"/> +" clip-path="url(#p6628149e2d)" style="fill: #16877f; stroke: #16877f; stroke-width: 1.4; stroke-linecap: round"/> +" clip-path="url(#p6628149e2d)" style="fill: none; stroke: #16877f; stroke-width: 1.4; stroke-linecap: round"/> +" clip-path="url(#p6628149e2d)" style="fill: #16877f; stroke: #16877f; stroke-width: 1.4; stroke-linecap: round"/> +" clip-path="url(#p6628149e2d)" style="fill: #f3f6f9"/> +" clip-path="url(#p6628149e2d)" style="fill: none; stroke: #16877f; stroke-width: 1.4; stroke-linecap: round"/> +" clip-path="url(#p6628149e2d)" style="fill: #16877f; stroke: #16877f; stroke-width: 1.4; stroke-linecap: round"/> +" clip-path="url(#p6628149e2d)" style="fill: none; stroke: #16877f; stroke-width: 1.4; stroke-linecap: round"/> +" clip-path="url(#p6628149e2d)" style="fill: #16877f; stroke: #16877f; stroke-width: 1.4; stroke-linecap: round"/> +" clip-path="url(#p6628149e2d)" style="fill: #f3f6f9"/> +" clip-path="url(#p6628149e2d)" style="fill: none; stroke: #16877f; stroke-width: 1.4; stroke-linecap: round"/> +" clip-path="url(#p6628149e2d)" style="fill: #16877f; stroke: #16877f; stroke-width: 1.4; stroke-linecap: round"/> +" clip-path="url(#p6628149e2d)" style="fill: none; stroke: #16877f; stroke-width: 1.4; stroke-linecap: round"/> +" clip-path="url(#p6628149e2d)" style="fill: #16877f; stroke: #16877f; stroke-width: 1.4; stroke-linecap: round"/> +" clip-path="url(#p6628149e2d)" style="fill: #f3f6f9"/> +" clip-path="url(#p6628149e2d)" style="fill: none; stroke: #16877f; stroke-width: 1.4; stroke-linecap: round"/> +" clip-path="url(#p6628149e2d)" style="fill: #16877f; stroke: #16877f; stroke-width: 1.4; stroke-linecap: round"/> +" clip-path="url(#p6628149e2d)" style="fill: none; stroke: #16877f; stroke-width: 1.4; stroke-linecap: round"/> +" clip-path="url(#p6628149e2d)" style="fill: #16877f; stroke: #16877f; stroke-width: 1.4; stroke-linecap: round"/> +" clip-path="url(#p6628149e2d)" style="fill: #f3f6f9"/> +" clip-path="url(#p6628149e2d)" style="fill: none; stroke: #16877f; stroke-width: 1.4; stroke-linecap: round"/> +" clip-path="url(#p6628149e2d)" style="fill: #16877f; stroke: #16877f; stroke-width: 1.4; stroke-linecap: round"/> +" clip-path="url(#p6628149e2d)" style="fill: none; stroke: #b76a29; stroke-width: 1.4; stroke-linecap: round"/> +" clip-path="url(#p6628149e2d)" style="fill: #b76a29; stroke: #b76a29; stroke-width: 1.4; stroke-linecap: round"/> +" clip-path="url(#p6628149e2d)" style="fill: none; stroke: #7960a5; stroke-width: 1.4; stroke-linecap: round"/> +" clip-path="url(#p6628149e2d)" style="fill: #7960a5; stroke: #7960a5; stroke-width: 1.4; stroke-linecap: round"/> +" clip-path="url(#p6628149e2d)" style="fill: none; stroke: #7960a5; stroke-width: 1.4; stroke-linecap: round"/> +" clip-path="url(#p6628149e2d)" style="fill: #7960a5; stroke: #7960a5; stroke-width: 1.4; stroke-linecap: round"/> +" clip-path="url(#p6628149e2d)" style="fill: #ffffff; stroke: #16877f; stroke-width: 1.15; stroke-linejoin: miter"/> +" clip-path="url(#p6628149e2d)" style="fill: #ffffff; stroke: #7960a5; stroke-width: 1.15; stroke-linejoin: miter"/> +" clip-path="url(#p6628149e2d)" style="fill: #ffffff; stroke: #7960a5; stroke-width: 1.15; stroke-linejoin: miter"/> +" clip-path="url(#p6628149e2d)" style="fill: #ffffff; stroke: #7960a5; stroke-width: 1.15; stroke-linejoin: miter"/> +" clip-path="url(#p6628149e2d)" style="fill: #ffffff; stroke: #7960a5; stroke-width: 1.15; stroke-linejoin: miter"/> +" clip-path="url(#p6628149e2d)" style="fill: #ffffff; stroke: #16877f; stroke-width: 1.15; stroke-linejoin: miter"/> +" clip-path="url(#p6628149e2d)" style="fill: #ffffff; stroke: #7960a5; stroke-width: 1.15; stroke-linejoin: miter"/> @@ -4768,7 +4768,7 @@ z - + diff --git a/paper/figures/slas/cellprofiler_translation_imported.py b/paper/figures/slas/cellprofiler_translation_imported.py index f788d86851..4c8bb350d0 100644 --- a/paper/figures/slas/cellprofiler_translation_imported.py +++ b/paper/figures/slas/cellprofiler_translation_imported.py @@ -43,7 +43,10 @@ SourceSelector, SourceSetRole, ) -from openhcs.core.source_metadata import SourceVoxelSpacing +from openhcs.core.source_metadata import ( + SourceVoxelSpacing, + SourceVoxelSpacingUnit, +) from openhcs.core.steps.function_step import FunctionStep from openhcs.interop.cellprofiler.measurement_scope import ( CellProfilerMeasurementTargetScope, @@ -184,7 +187,9 @@ imported_metadata_tables=(), source_stack_components=(), grouping_metadata_fields=(), - source_voxel_spacing=SourceVoxelSpacing(values_zyx=(1.0, 1.0, 1.0)), + source_voxel_spacing=SourceVoxelSpacing( + values_zyx=(1.0, 1.0, 1.0), unit=SourceVoxelSpacingUnit.RELATIVE + ), ), step_source_bindings_config=LazyStepSourceBindingsConfig( enabled=None, diff --git a/paper/figures/slas/cellprofiler_translation_provenance.json b/paper/figures/slas/cellprofiler_translation_provenance.json index 826dc47d48..84c57d2f49 100644 --- a/paper/figures/slas/cellprofiler_translation_provenance.json +++ b/paper/figures/slas/cellprofiler_translation_provenance.json @@ -1,9 +1,9 @@ { - "generator_sha256": "c0134cf20b33cc6048722dff5503f143b711ec56c2ef8f9036e5ee40d6db0999", + "generator_sha256": "fa19dc2a6f5e9b4992fd58686b6af2192e134e8137498cc1458f2e23eab2b147", "source_sha256": { "benchmark/native_refs/official30_scoped_rows/ExampleCometAssay_ExampleCometAssay_wells_include_first1/native_cellprofiler_headless/ExampleCometAssay.cppipe": "daec62eb90d9457a240bd28dcb3a1002b480db366a5d6aa849a8813f1073f8b6", - "paper/figures/build_slas_cellprofiler.py": "c0134cf20b33cc6048722dff5503f143b711ec56c2ef8f9036e5ee40d6db0999", - "paper/figures/slas/cellprofiler_translation_imported.py": "fb77e8e97af83376e6c66f7e8800a1dee3d814be19e2f013abf01ef903debab0", + "paper/figures/build_slas_cellprofiler.py": "fa19dc2a6f5e9b4992fd58686b6af2192e134e8137498cc1458f2e23eab2b147", + "paper/figures/slas/cellprofiler_translation_imported.py": "d933bad3b789811fb44669c4fe92ecb3d02b568acf09084de681232629520742", "openhcs/interop/cellprofiler/parser.py": "25fd96f8fdd4a4f02b01fc2f55e8fdb978efa331f16ca612b1466c9435e4ac89", "openhcs/interop/cellprofiler/pipeline_import.py": "b547c838b2c86fe7cc5fe12d6cbf6a6715e83055c2d8c1a109ac22566d22c51e", "openhcs/interop/cellprofiler/module_declarations.py": "89dd65abc003c464ba6c489f52d3a4fa47be1d5f8b87d26ad72b7537f188cf8b", @@ -18,17 +18,17 @@ "openhcs/processing/backends/cellprofiler/morphology.py": "f174e6b6f940e083c904245354cdf384e81d287b1b2c6354eb7cb08aae4514ac", "openhcs/processing/backends/cellprofiler/shape.py": "ebf6bbde9013e99b1cf527386b0c9efd4ed10da369843864b4cfcf28340e2823", "openhcs/processing/backends/cellprofiler/texture.py": "640d9d2b5a17f643c3fe70b70bf424caa5b785693c7f6bae5d851942d52fb6f5", - "openhcs/processing/backends/cellprofiler/intensity.py": "f529b5bfc9c595a3f7017d2022d52425b05d2f5ed7e810823073f556e520cf1f", + "openhcs/processing/backends/cellprofiler/intensity.py": "646e837759d6504e496b09fd903744c95e020ae02d0a424bbe408cb772d8b2f0", "openhcs/processing/backends/cellprofiler/outlines.py": "82c865640a5d07401ce24fc3eeeef7fa61b1e27da45f6f0fb10348c942d8e0f9", "openhcs/processing/backends/cellprofiler/save_images.py": "0042b72bdc53fabbb93248aea61c3c7ed3f488e563e9d190b9f65746d434257c", "openhcs/processing/backends/cellprofiler/spreadsheet_export.py": "5787bab5727e85c045e3aed03135bb64ddc62c5a5796fea62f9570576681e6f2", - "paper/figures/build_slas_visual_story.py": "7eb189ca5fa55aff5c6dfdeac48da7dc5cb0af3217b214e836afeda3c0a7715d" + "paper/figures/build_slas_visual_story.py": "29f1936406b2453b90dae232bc8ec1bbea1e998145da6994c38ef397630db8eb" }, "ui_crops": [], "output_sha256": { "cellprofiler_translation.png": "4a6c8f6708314c273c364abb3bb8ab2b9ee47ef0a403784116fe869018ba1fc7", - "cellprofiler_translation.pdf": "f881fe911aedf8e1e0f64a0d4af40953e237dfa1afaaae182b5732da3815dc2c", - "cellprofiler_translation.svg": "3e0685123106c42fded116f8277be1014140f1040cab01b4102d87b3f19d8f42" + "cellprofiler_translation.pdf": "5ec3ec0ca3ce0268230a948ddabfc09ebff1c3db8edf93dfc79239afda231880", + "cellprofiler_translation.svg": "f2c4adfe20ca0b86066200735d41bf9f9c446ebe0daf7b31aa6fe34ad8f0bad4" }, "interpretation": "Current parser/importer translation of the retained public ExampleCometAssay benchmark pipeline. No analysis was run. Panel A shows all enabled modules and all imported steps; multiplicity counts actual callable invocations, not parallel workers. Panel B expands the actual MeasureObjectSizeShape function list; panel C shows the actual MaskObjects named-object selections and inverted-mask setting. Layout is specific to this example, not a universal one-module-to-one-step claim.", "imported_document": "paper/figures/slas/cellprofiler_translation_imported.py", diff --git a/paper/figures/slas/figure3_agent_workflow.pdf b/paper/figures/slas/figure3_agent_workflow.pdf index 9a71ef7ebcb022ccb72e8e222f8abf67500a6947..7168a4e784380791823464905088bafe15fa59c6 100644 GIT binary patch literal 538575 zcmb4r1z1)~*S2(brw`rr(B0kLNOyNjmvpyuHwqFW4bmm45=x77C?fv`J>Pr2_wZfE zpM7nf*?Ui{Su?ZdUTbC+m5PKE6B{!JB2~?MP<1;Z8;BL;WNM2jAOK>~@Nu>Pv51?v zo7g*9fml>btSsC>U?74TNJt3L!qNOLBG2CvNI5yWgV^sQu;?h8+FF>ogSdY^N_x9X ztGk=HTYxxzy-+c6ceikL1aaOyBC@Dko0!`;T7kHJe|2>-Q@3yj=>x?|NCBi+c)NpG zWE}t!#D4#Z|NfN)8UBqNwtrUOj_y0^T`d6Wev!|jX5r@K;c5od=Z=0g5R0OPxs8dK zlQ&QzD{ygf@PN3uz|0&VLqryFpjtp$HxTcyxT21ZPQVk}UBth$;_mZbyi>4nv~srw zvHdPj%Elh3Er>5I=;|BxoPql2Ae$HK$S>n5fBCB(E0?RYbrjdsvO&<+;7SjwI%a?ggcP-;XORb{8+Da`@o)g}Ee>I#>~KPgMs$aq*n zTT_}t7@Yh!dP#*W(7Jk{Y<<7G&G*c1$KJ4hxZW_ud>>X2qT$)jU0OdwcNms5fd+ru z*{$|oH>;~d!pEhDa3u0atkyg|#*6vc*Ip!>ny-(pk+kYhi}cH}HgyBd*IiOz3ZD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