diff --git a/benchmark/adapters/cellprofiler.py b/benchmark/adapters/cellprofiler.py index 46b742fe0b..c6ed63a287 100644 --- a/benchmark/adapters/cellprofiler.py +++ b/benchmark/adapters/cellprofiler.py @@ -36,7 +36,7 @@ ToolNotInstalledError, ) from benchmark.timing import BenchmarkPhase, PhaseTimingTrace -from openhcs.constants import AllComponents, Backend +from openhcs.constants import Backend from openhcs.core.config import GlobalPipelineConfig, WellFilterConfig from openhcs.core.source_binding_workspace import ( SourceBindingWorkspaceMaterialization, @@ -55,6 +55,7 @@ ) from openhcs.microscopes.source_schema import SourceSchemaFilenameParser from openhcs.processing.backends.cellprofiler.infrastructure import MetadataModule +from openhcs.domains.microscopy.axes import Microscopy PYTHONHASHSEED_ENV = "PYTHONHASHSEED" DETERMINISTIC_PYTHONHASHSEED = "0" @@ -439,7 +440,7 @@ def _virtual_path_well( raise ValueError( f"Cannot parse source-binding virtual filename {virtual_path!r}." ) - return str(parsed.required_value(AllComponents.WELL)) + return str(parsed.required_value(Microscopy.Well)) @staticmethod def _workspace_source_path( diff --git a/benchmark/agent_validation/perturbations.py b/benchmark/agent_validation/perturbations.py index d7c8002566..b79ed63659 100644 --- a/benchmark/agent_validation/perturbations.py +++ b/benchmark/agent_validation/perturbations.py @@ -13,7 +13,6 @@ ) from benchmark.agent_validation.contracts import DiagnosticCheck, ScoringCase from benchmark.agent_validation.declarations import ValidationTaskDeclaration -from openhcs.constants import GroupBy from openhcs.core.config import ( LazyProcessingConfig, LazyStepMaterializationConfig, @@ -21,6 +20,7 @@ ) from openhcs.core.pipeline_document import PipelineDocument, PipelineDocumentAuthority from openhcs.core.steps.function_step import FunctionStep +from openhcs.core.axes import Ungrouped class DiagnosticPerturbationDeclaration(ABC, metaclass=AutoRegisterMeta): @@ -159,7 +159,7 @@ def flawed_pipeline_document(cls) -> PipelineDocument: name="Expand labels without overlap", processing_config=LazyProcessingConfig( variable_components=[], - group_by=GroupBy.NONE, + group_by=Ungrouped, ), step_materialization_config=LazyStepMaterializationConfig( enabled=True, diff --git a/benchmark/bioformats_hcs_validation.py b/benchmark/bioformats_hcs_validation.py index cd83afea95..f957c297a6 100644 --- a/benchmark/bioformats_hcs_validation.py +++ b/benchmark/bioformats_hcs_validation.py @@ -17,11 +17,12 @@ ) from benchmark.datasets.acquire import acquire_dataset from benchmark.datasets.registry import DATASET_REGISTRY -from openhcs.constants import AllComponents -from openhcs.core.components.component_values import OpenHCSComponentValues +from openhcs.core.components.component_values import AxisValues from openhcs.core.virtual_workspace_metadata import component_metadata_field from openhcs.microscopes import create_microscope_handler from openhcs.microscopes.bioformats import BioFormatsHandler +from openhcs.core.axes import AxisFamily +from openhcs.domains.microscopy.axes import Microscopy BIOFORMATS_HCS_VALIDATION_CSV = "bioformats_hcs_validation.csv" BIOFORMATS_HCS_VALIDATION_JSON = "bioformats_hcs_validation.json" @@ -152,18 +153,18 @@ def validate_acquired_bioformats_hcs_dataset( metadata_handler = handler.metadata_handler component_values = metadata_handler.component_value_set(acquired.path) - component_keys = OpenHCSComponentValues( + component_keys = AxisValues( ( component, _component_keys(component_values.values_for(component)), ) - for component in AllComponents + for component in AxisFamily.active().axes ) - wells = component_keys[AllComponents.WELL] - sites = component_keys[AllComponents.SITE] - channels = component_keys[AllComponents.CHANNEL] - z_indexes = component_keys[AllComponents.Z_INDEX] - timepoints = component_keys[AllComponents.TIMEPOINT] + wells = component_keys[Microscopy.Well] + sites = component_keys[Microscopy.Site] + channels = component_keys[Microscopy.Channel] + z_indexes = component_keys[Microscopy.ZIndex] + timepoints = component_keys[Microscopy.Timepoint] grid_dimensions = tuple( metadata_handler.get_metadata_grid_dimensions(acquired.path) ) @@ -297,7 +298,7 @@ def _result_fieldnames() -> tuple[str, ...]: def _csv_row(result: BioFormatsHcsValidationResult) -> dict[str, object]: row = asdict(result) - for component in AllComponents: + for component in AxisFamily.active().axes: field_name = component_metadata_field(component) row[field_name] = ";".join(row[field_name]) row["grid_dimensions"] = ( @@ -310,7 +311,7 @@ def _csv_row(result: BioFormatsHcsValidationResult) -> dict[str, object]: def _json_row(result: BioFormatsHcsValidationResult) -> dict[str, object]: row = asdict(result) - for component in AllComponents: + for component in AxisFamily.active().axes: field_name = component_metadata_field(component) row[field_name] = list(row[field_name]) row["grid_dimensions"] = ( diff --git a/benchmark/demos/official30_lab_meeting.py b/benchmark/demos/official30_lab_meeting.py index d05bd685f0..da4d74fc77 100644 --- a/benchmark/demos/official30_lab_meeting.py +++ b/benchmark/demos/official30_lab_meeting.py @@ -23,7 +23,6 @@ JSONValue, ManifestCasePayload, ) -from openhcs.constants.constants import AllComponents from openhcs.core.aligned_image_payload import AlignedImageSliceContext from openhcs.core.artifacts import ArtifactType, MeasurementsArtifactType from openhcs.core.config import ( @@ -44,6 +43,7 @@ prepare_cellprofiler_input_workspace, ) from openhcs.processing.presets.demo_contribution import PipelineDemoContribution +from openhcs.domains.microscopy.axes import Microscopy REPOSITORY_ROOT = Path(__file__).resolve().parents[2] OFFICIAL30_MANIFEST_PATH = ( @@ -233,7 +233,7 @@ def _materialized_well_labels( for metadata in prepared.materialization.source_metadata.values() for value in source_component_metadata_values( metadata, - AllComponents.WELL, + Microscopy.Well, ) } ) diff --git a/benchmark/equivalence/outputs.py b/benchmark/equivalence/outputs.py index 163a95241b..08078f3c84 100644 --- a/benchmark/equivalence/outputs.py +++ b/benchmark/equivalence/outputs.py @@ -25,7 +25,6 @@ RuntimeArtifactExecutionObservation, ) from openhcs.core.runtime_exports import RuntimeExportObservation -from openhcs.constants.constants import AllComponents from openhcs.core.source_bindings import SourceProjectionRole from openhcs.core.source_matching import SourceImageSetIdentityPolicy from openhcs.core.source_projection import SourceProjectionSet @@ -34,6 +33,7 @@ METADATA_CONFIG, OpenHCSMetadataSubdirectories, ) +from openhcs.domains.microscopy.axes import Microscopy @dataclass(frozen=True, slots=True) @@ -136,7 +136,7 @@ def image_snapshots( if ( not paths or not source_workspaces - or image_set_policy.is_identity_component(AllComponents.Z_INDEX) + or image_set_policy.is_identity_component(Microscopy.ZIndex) ): return tuple(RuntimeImageSnapshot.from_image_file(path) for path in paths) expected_paths = frozenset(path.absolute() for path in paths) diff --git a/benchmark/matched_cellprofiler_batch.py b/benchmark/matched_cellprofiler_batch.py index c4ddaba76b..e0e9fce281 100644 --- a/benchmark/matched_cellprofiler_batch.py +++ b/benchmark/matched_cellprofiler_batch.py @@ -70,7 +70,6 @@ _write_progress_diagnostics, well_throughput_start_method_from_manifest, ) -from openhcs.constants.constants import AllComponents from openhcs.core.config import ( AnalysisConsolidationConfig, GlobalPipelineConfig, @@ -122,6 +121,7 @@ ZMQRuntimeObservationExportScope, ) from python_introspect import to_jsonable +from openhcs.domains.microscopy.axes import Microscopy def _parser() -> argparse.ArgumentParser: @@ -1291,7 +1291,7 @@ def _run_case(args: argparse.Namespace, client: ZMQExecutionClient | None) -> in ): raise RuntimeError("CellProfiler import did not prepare a complete document.") source_wells = { - source_component_metadata_value(metadata, AllComponents.WELL) + source_component_metadata_value(metadata, Microscopy.Well) for metadata in prepared.materialization.source_metadata.values() } wells = _select_genuine_wells( diff --git a/benchmark/native_synthetic_well_scaling.py b/benchmark/native_synthetic_well_scaling.py index 726a693fac..adebd2da8a 100644 --- a/benchmark/native_synthetic_well_scaling.py +++ b/benchmark/native_synthetic_well_scaling.py @@ -27,12 +27,12 @@ _native_python_executable, ) from benchmark.well_throughput_scaling import _synthetic_well_ids -from openhcs.constants.constants import AllComponents from openhcs.core.input_workspace import InputWorkspacePreparationRequest from openhcs.core.source_matching import source_component_metadata_value from openhcs.interop.cellprofiler.plate_workspace import ( prepare_cellprofiler_input_workspace, ) +from openhcs.domains.microscopy.axes import Microscopy def _parser() -> argparse.ArgumentParser: @@ -126,7 +126,7 @@ def main(argv: list[str] | None = None) -> int: if prepared.materialization is None: raise RuntimeError("Pipeline import has no declared source-binding planes.") source_wells = { - source_component_metadata_value(metadata, AllComponents.WELL) + source_component_metadata_value(metadata, Microscopy.Well) for metadata in prepared.materialization.source_metadata.values() } if len(source_wells) != 1 or None in source_wells or "" in source_wells: diff --git a/benchmark/pipelines/bbbc021_nuclei_segmentation.py b/benchmark/pipelines/bbbc021_nuclei_segmentation.py index e3966546ce..5aef70093d 100644 --- a/benchmark/pipelines/bbbc021_nuclei_segmentation.py +++ b/benchmark/pipelines/bbbc021_nuclei_segmentation.py @@ -26,7 +26,6 @@ LazyStepMaterializationConfig, LazyNapariStreamingConfig, ) -from openhcs.constants.constants import VariableComponents # ============================================================================ # SELECT BACKEND (uncomment one set) @@ -35,6 +34,7 @@ # --- CPU Backend (numpy/scipy) --- from benchmark.pipelines.cellprofiler_preprocess import preprocess_cpu as preprocess from benchmark.pipelines.cellprofiler_nuclei import identify_primary_objects as segment +from openhcs.domains.microscopy.axes import Microscopy # --- GPU Backend (pyclesperanto - OpenCL, works on AMD/NVIDIA/Intel) --- # from benchmark.pipelines.cellprofiler_preprocess import preprocess_gpu as preprocess @@ -65,7 +65,7 @@ ), name="CellProfiler Preprocessing", processing_config=LazyProcessingConfig( - variable_components=[VariableComponents.CHANNEL] + variable_components=[Microscopy.Channel] ), ) pipeline_steps.append(step_1) @@ -87,7 +87,7 @@ ), name="IdentifyPrimaryObjects (Nuclei)", processing_config=LazyProcessingConfig( - variable_components=[VariableComponents.CHANNEL] + variable_components=[Microscopy.Channel] ), napari_streaming_config=LazyNapariStreamingConfig(), step_materialization_config=LazyStepMaterializationConfig(), diff --git a/benchmark/pipelines/bbbc022_nuclei_segmentation.py b/benchmark/pipelines/bbbc022_nuclei_segmentation.py index 13ded17621..97d4bf3ca7 100644 --- a/benchmark/pipelines/bbbc022_nuclei_segmentation.py +++ b/benchmark/pipelines/bbbc022_nuclei_segmentation.py @@ -26,7 +26,6 @@ LazyStepMaterializationConfig, LazyNapariStreamingConfig, ) -from openhcs.constants.constants import VariableComponents # ============================================================================ # SELECT BACKEND (uncomment one set) @@ -35,6 +34,7 @@ # --- CPU Backend (numpy/scipy) --- from benchmark.pipelines.cellprofiler_preprocess import preprocess_cpu as preprocess from benchmark.pipelines.cellprofiler_nuclei import identify_primary_objects as segment +from openhcs.domains.microscopy.axes import Microscopy # --- GPU Backend (pyclesperanto - OpenCL, works on AMD/NVIDIA/Intel) --- # from benchmark.pipelines.cellprofiler_preprocess import preprocess_gpu as preprocess @@ -65,7 +65,7 @@ ), name="CellProfiler Preprocessing", processing_config=LazyProcessingConfig( - variable_components=[VariableComponents.CHANNEL] + variable_components=[Microscopy.Channel] ), ) pipeline_steps.append(step_1) @@ -87,7 +87,7 @@ ), name="IdentifyPrimaryObjects (Nuclei)", processing_config=LazyProcessingConfig( - variable_components=[VariableComponents.CHANNEL] + variable_components=[Microscopy.Channel] ), napari_streaming_config=LazyNapariStreamingConfig(), step_materialization_config=LazyStepMaterializationConfig(), diff --git a/benchmark/validation/corpus.py b/benchmark/validation/corpus.py index 383573bad7..f059edd6f2 100644 --- a/benchmark/validation/corpus.py +++ b/benchmark/validation/corpus.py @@ -32,7 +32,7 @@ from benchmark.datasets.registry import get_dataset_spec from benchmark.validation.layouts import ValidationCorpusLayoutStrategy from benchmark.validation.references import ValidationReferenceStrategy -from openhcs.constants import AllComponents, Microscope +from openhcs.constants import Microscope from openhcs.core.config import LazySourceBindingsConfig, PipelineConfig from openhcs.core.source_bindings import ( ComponentSelector, @@ -53,6 +53,7 @@ SourceFilterSubject, SourceSelector, ) +from openhcs.domains.microscopy.axes import Microscopy class ValidationCorpusPreparationError(RuntimeError): @@ -532,7 +533,7 @@ def source_bindings_for_validation( origin=SourceBindingOrigin.PIPELINE_START, component_identity=( ComponentSelector( - component=AllComponents.CHANNEL, + component=Microscopy.Channel, value=channel.value, ), ), diff --git a/benchmark/well_throughput_scaling.py b/benchmark/well_throughput_scaling.py index d3a0a621d5..12b32bb8da 100644 --- a/benchmark/well_throughput_scaling.py +++ b/benchmark/well_throughput_scaling.py @@ -36,7 +36,6 @@ execute_measured_openhcs_pipeline_on_client, ) from benchmark.timing import BenchmarkPhase, PhaseTimingTrace -from openhcs.constants.constants import AllComponents from openhcs.core.components.parser_metaprogramming import FilenameParseResult from openhcs.core.config import ( AnalysisConsolidationConfig, @@ -80,6 +79,8 @@ ZMQRuntimeObservationExportScope, ) from python_introspect import to_jsonable +from openhcs.domains.microscopy.axes import Microscopy +from openhcs.core.virtual_workspace_metadata import component_metadata_field WELL_THROUGHPUT_ROWS_CSV = "well_throughput.csv" WELL_THROUGHPUT_EVENTS_CSV = "well_throughput_progress_events.csv" @@ -3139,7 +3140,7 @@ def _replicate_source_binding_workspace_wells( available_source_wells = tuple( dict.fromkeys( - projection.address.value_for(AllComponents.WELL) + projection.address.value_for(Microscopy.Well) for projection in source_projections.entries.values() if projection.address is not None ) @@ -3173,7 +3174,7 @@ def _replicate_source_binding_workspace_wells( f"Source projection ref disagrees with workspace mapping: {virtual_path!r}" ) if ( - projection.address.value_for(AllComponents.WELL) + projection.address.value_for(Microscopy.Well) not in selected_source_well_keys ): continue @@ -3188,7 +3189,7 @@ def _replicate_source_binding_workspace_wells( f"Source projection address disagrees with virtual path: {virtual_path!r}" ) for well_id in target_wells: - site = parsed.required_value(AllComponents.SITE) + site = parsed.required_value(Microscopy.Site) expanded_path = _synthetic_well_virtual_path( parser, str(virtual_path), @@ -3242,7 +3243,7 @@ def _replicate_source_binding_workspace_wells( ) ) main_metadata[FIELDS.IMAGE_FILES] = expanded_image_files - main_metadata[FIELDS.WELLS] = {well_id: None for well_id in target_wells} + main_metadata[component_metadata_field(Microscopy.Well)] = {well_id: None for well_id in target_wells} AtomicMetadataWriter().replace_subdirectory_metadata( metadata_path, FIELDS.DEFAULT_SUBDIRECTORY, main_metadata ) @@ -3259,8 +3260,8 @@ def _synthetic_well_virtual_path( filename = parser.construct_filename( parsed.with_values( ( - (AllComponents.WELL, well_id), - (AllComponents.SITE, site), + (Microscopy.Well, well_id), + (Microscopy.Site, site), ) ) ) diff --git a/docs/refactor/consolidation-20261009/G1-axis-family.md b/docs/refactor/consolidation-20261009/G1-axis-family.md new file mode 100644 index 0000000000..b38328fd10 --- /dev/null +++ b/docs/refactor/consolidation-20261009/G1-axis-family.md @@ -0,0 +1,97 @@ +# G1: The axis family + +**Head audited:** `openhcs` `main` at `34abdf41e` (#1160). **Rules:** [00-RULES.md](00-RULES.md). **Step 2.** +**Architecture:** [04-ARCHITECTURE.md](04-ARCHITECTURE.md), "The axis family". *Builds:* `Axis`, `AxisFamily`, `AxisRole` and the value-kind mixins. *Uses:* `AutoRegisterMeta`. + +## What is wrong + +**The kernel cannot be told which axes exist: the component family is a hardcoded template, and five enums manufactured from it restate two sets with identity that does not survive a second call (IDEN-1, MEMB-2, IMPL-2).** + +- `core/components/framework.py:173-182` hardcodes `_ComponentTemplate` (site, channel, z_index, timepoint, well). `constants/constants.py:66` `get_openhcs_config()` returns a **new** configuration over a **new** template enum on every call, so `get_openhcs_config().multiprocessing_axis == AllComponents.WELL` is `False`. Identity falls back to `.value` (`constants.py:114,121`, `component_set.py:55`, `path_planner.py:244`, `compiler.py:389,683`, `source_bindings.py:2248`, `callable_contract.py:2471,2512`, `function_contracts.py:354,396`, `pipeline_import.py:362`, `module_declarations.py:382`) and to a value-equality `__eq__`/`__hash__` patched onto `GroupBy` (`constants.py:79-99`). It runs during every step validation (`funcstep_contract_validator.py:686,794`, `compilation_session.py:331`). +- `constants.py:_create_enums` generates `AllComponents`, `VariableComponents`, `SequentialComponents` and `GroupBy` (`VariableComponents` plus `NONE`), and `_create_streaming_components` a fifth, `StreamingComponents`, equal to `AllComponents` and used by nothing. `constants/__init__.py` freezes three more import-time copies (`DEFAULT_VARIABLE_COMPONENTS`, `DEFAULT_GROUP_BY`, `MULTIPROCESSING_AXIS`). +- Reach at this head: 103 production files and 140 test files name the five enums (≈840 production lines); 186 production lines name a member (`AllComponents.WELL` …), 110 of them in kernel modules (`config.py` 20, `source_projection.py` 18, `source_binding_workspace.py` 10, `viewer_component_system.py` 7, `source_metadata.py` 7, `virtual_workspace_metadata.py` 5, CellProfiler backends 20, …). +- Import-time binding: strategy class bodies key on members (`steps/function_io.py:201-229`, `source_metadata.py:1231-1308`), `virtual_workspace_metadata.py:358-362` derives a field roster from members, `NapariDisplayConfig`/`FijiDisplayConfig` carry one field per member (`config.py:285-327, 439-475`) and `COMPONENT_ORDER` ClassVars. A second family fails at import. + +## Target + +```python +# openhcs/core/axes.py (kernel) +class AxisRole(ABC): cardinality: ClassVar[type[Cardinality]] = Many +class PartitionAxis(AxisRole): cardinality = ExactlyOne # parallel axis +class StackAxis(AxisRole): cardinality = AtMostOne +class ColourAxis(AxisRole); class TileAxis(AxisRole); class TimeAxis(AxisRole) +class DefaultVariable(AxisRole); class DefaultGroupBy(AxisRole): cardinality = AtMostOne +class LabelValued(AxisValueKind); class OrdinalValued(AxisValueKind) + +class GroupingDeclaration(ABC): # what a step's group_by holds + grouping_axes() -> tuple[type[Axis], ...] +class Axis(GroupingDeclaration, metaclass=AxisMeta): # AxisMeta(AutoRegisterMeta) + name: ClassVar[str] +class Ungrouped(GroupingDeclaration): ... # explicit absent-grouping declaration +class AxisFamily(metaclass=AxisMeta): + axes # nested Axis classes, declaration order + with_role(role) / one(role) / named(name) / names() + variable_axes() # every axis without PartitionAxis + partition_axis() / default_variable() / default_group_by() + activate() / active() # one active family per process + +# openhcs/domains/microscopy/axes.py (domain) +class Microscopy(AxisFamily): + class Site(Axis, TileAxis, DefaultVariable, OrdinalValued): name = "site" + class Channel(Axis, ColourAxis, DefaultGroupBy, OrdinalValued): name = "channel" + class ZIndex(Axis, StackAxis, OrdinalValued): name = "z_index" + class Timepoint(Axis, TimeAxis, OrdinalValued): name = "timepoint" + class Well(Axis, PartitionAxis, LabelValued): name = "well" +``` + +- The product package root (`openhcs/__init__.py`) is the microscopy distribution's entry point and activates `Microscopy` once per process, before any kernel use. Spawned workers and viewer processes import `openhcs` first, so each process activates it. Kernel modules never import the domain package. +- Every consumer takes axis classes. Subsets are family queries. `GroupBy.NONE` becomes `Ungrouped`. Strings exist only at boundaries (wire, viewer payloads, MCP, filenames, metadata), derived from `Axis.name` and decoded by `family.named()`. +- Strategy families keyed by a member (`function_io`, `source_metadata`, `source_projection`) key on a role. Viewer display configs carry one field per **role** (`partition_mode`, `tile_mode`, `colour_mode`, `stack_mode`, `time_mode`), projected onto the active family's axes; G6 turns these into slot families. +- **Deleted:** `core/components/framework.py` (`ComponentConfiguration`, `ComponentConfigurationFactory`, `_ComponentTemplate`), `get_openhcs_config`, `_create_enums`, `_create_streaming_components`, the GroupBy `__eq__`/`__hash__` patch, `convert_enum_by_value`, `get_default_variable_components`, `get_default_group_by`, `get_multiprocessing_axis`, `DEFAULT_VARIABLE_COMPONENTS`, `DEFAULT_GROUP_BY`, `MULTIPROCESSING_AXIS`, the five enum names and every `.value` identity bridge between them. + +## Persisted state + +| Store | Class | At cutover | +|---|---|---| +| Compiled plans, worker bundles, metadata caches, function registry cache | runtime | reset | +| Global config document (`global_config.config`, executable Python) | durable | `GroupBy.X`/`VariableComponents.X` become `Microscopy.X`/`Ungrouped`; per-member viewer mode fields become per-role fields | +| Saved `.py` pipelines (pycodify source) | durable | same rewrite as config documents | +| Pickled pipelines | deprecated (owner) | not converted; surface F1 deletes the GUI pickle path | + +Pre-G1 sources name the deleted classes, so they cannot load unchanged. Owner decision G1-Q1: pickles are deprecated; `tools/cutover/g1_axis_family.py` rewrites pycodify Python sources (enum members, `GroupBy.NONE`, per-member viewer mode fields, `required_variable_components`/`allowed_group_by`, imports), keeping a `.pre-g1` backup. `tests/unit/test_g1_cutover_tool.py` converts fixtures rendered by pre-G1 main and loads and validates them. Tool, test and fixtures are deleted once the owner has migrated. + +## Guards + +`tests/unit/test_axis_family_guards.py`: +- No module under `openhcs/`, `benchmark/` (excluding recorded `benchmark/results/`), `scripts/` or `tests/` names `AllComponents`, `VariableComponents`, `SequentialComponents`, `StreamingComponents`, `GroupBy`, `get_openhcs_config`, `_ComponentTemplate`, `ComponentConfiguration`, `MULTIPROCESSING_AXIS`, `DEFAULT_GROUP_BY` or `DEFAULT_VARIABLE_COMPONENTS`. +- No kernel module (outside the domain modules listed in the test) imports `openhcs.domains` or names the microscopy family or one of its member classes. +- Axis-name string literals are not guarded yet: 24 remain in kernel modules, each owned by a later surface (Handoff). + +## Tests + +- One family test: cardinality validation, role queries, name decoding, activation. +- Witness test: a remote-sensing family (scene, band, tile, date; no stack axis) activated in-process; family queries, `ProcessingConfig` defaults, viewer config projection and compiler axis resolution work with zero kernel edits. +- Tests of deleted code (`ComponentConfiguration`, enum conversion helpers) are deleted. Enum-coupled tests are rewritten against axis classes. + +## New-case experiments + +Today a second domain needs edits to `framework.py`, `constants.py`, `config.py` (two dataclasses, ten fields), five strategy classes and every member reference, and still fails at import. After: one `AxisFamily` subclass and one `activate()` call. + +## Handoff (recorded for later surfaces) + +Member references left in domain modules (allowed; P moves these packages under `openhcs/domains/`), for **G2/G4**: `microscopes/bioformats_adapter.py` 30, `opera_phenix.py` 25, `imagexpress.py` 14, `omero.py` 9, `openhcs.py` 5, `microscope_base.py` 4; `processing/presets/` 34 across 9 files; `demo/` 9; `mcp/installed_demo.py` 11. + +Role resolutions that assume one axis per role (`family.one(role)`), to generalise: +- **G4:** `source_tile_geometry.py` (tile, colour); `pos_gen/acquisition_positions.py` (tile); `consolidate_analysis_results.py` (partition); `SourceComponentProjectionStrategy` leaves keyed by role still carry microscopy metadata aliases (`"wellrow"`, `"zplane"`, the `"A01"` default) and must become per-axis declarations. +- **G5:** CellProfiler image names map to `one(ColourAxis)`, "Process as 3D" to `one(StackAxis)` (`processing/backends/cellprofiler/infrastructure.py`). +- **G3:** stack handling in `source_projection.py`, `source_image_provenance.py`, `roi_point_metadata.py` uses `one(StackAxis)`. + +Axis-name string literals left in kernel modules (24, from 49 at head): source metadata aliases (G4), Fiji/NGFF spellings that are external contracts (`FijiDimensionMode.CHANNEL`, NGFF `"channel"`), MCP plate DTO and dev-client rosters (`agent/dto/plate.py`, `mcp/dev_client_commands/plate.py`: G8), `formats/experimental_*` (G8), progress vocabulary (G7). + +Viewer display configs carry one mode field per role; G6 turns them into slot families. The image browser plate grid uses the partition axis; G8 separates a grid role from the partition role. The debug JSON switches (`debug_views.py`, `debug_view_models.py`) gained an axis case beside their enum case; K6 merges them onto `to_jsonable`. + +Decision G1-Q1 (owner, decided): pickled pipelines are deprecated; `.py` pipelines and config documents are rewritten by `tools/cutover/g1_axis_family.py`, which is deleted once the owner has migrated. + +## Done when + +The five enums, the template, the factory and the per-call construction are gone; every consumer takes axis classes; the guards and the witness test pass; the touched tests, the GUI import check and the 30-workflow parity check are green (baseline: 29/30). diff --git a/docs/source/api/index.rst b/docs/source/api/index.rst index ded249fedd..392e57e4db 100644 --- a/docs/source/api/index.rst +++ b/docs/source/api/index.rst @@ -17,15 +17,15 @@ configuration objects. .. code-block:: python - from openhcs.constants import VariableComponents from openhcs.core.config import LazyProcessingConfig, ProcessingConfig from openhcs.core.steps.function_step import FunctionStep + from openhcs.domains.microscopy.axes import Microscopy def normalize(image, *, scale=1.0): return image * scale processing = ProcessingConfig( - variable_components=(VariableComponents.SITE,), + variable_components=(Microscopy.Site,), ) step = FunctionStep( func=(normalize, {"scale": 0.5}), diff --git a/docs/source/architecture/artifact_contract_system.rst b/docs/source/architecture/artifact_contract_system.rst index d3ea09a728..f2f71b050d 100644 --- a/docs/source/architecture/artifact_contract_system.rst +++ b/docs/source/architecture/artifact_contract_system.rst @@ -88,7 +88,7 @@ Measurement source provenance Measurement rows retain the exact biological coordinates of the runtime planes they represent. ``SourceImageProvenance`` is the authority for source image -names and ``AllComponents`` values such as well, site, channel, z-index, and +names and declared axis values such as well, site, channel, z-index, and timepoint. A row carrying the canonical ``slice_index`` receives the matching plane coordinates. A row without a slice axis receives only coordinates common to the whole represented stack; OpenHCS does not label an aggregate row with a diff --git a/docs/source/architecture/component_system_integration.rst b/docs/source/architecture/component_system_integration.rst index 90bb6b7733..62493f7a5e 100644 --- a/docs/source/architecture/component_system_integration.rst +++ b/docs/source/architecture/component_system_integration.rst @@ -25,7 +25,7 @@ those projections; they do not invent component keys or depend on a concrete microscope module. Complete component values cross internal boundaries as -``OpenHCSComponentValues`` keyed by ``AllComponents`` members in declaration +``AxisValues`` keyed by the active family's axes in declaration order. Filename parsers carry that value set in ``FilenameParseResult`` and metadata handlers project it through ``MetadataComponentValueSet``. Missing values remain explicit entries rather than making each consumer maintain a diff --git a/docs/source/architecture/component_validation_system.rst b/docs/source/architecture/component_validation_system.rst index 11c663d77e..2905286bb7 100644 --- a/docs/source/architecture/component_validation_system.rst +++ b/docs/source/architecture/component_validation_system.rst @@ -2,11 +2,11 @@ Component validation ==================== Component declarations describe semantic microscope dimensions such as well, -site, channel, Z, and time point. ``AllComponents``, ``VariableComponents``, -``SequentialComponents``, and ``GroupBy`` are typed views used at different -boundaries; equal string values do not make the declarations interchangeable. +site, channel, Z, and time point. Each is an ``Axis`` class declared by the +active ``AxisFamily``; subsets such as the variable axes are family queries, +and a step's absent grouping is the explicit ``Ungrouped`` declaration. -Validation converts external values to the exact owning enum and rejects +Validation decodes external names through ``AxisFamily.named`` and rejects unknown or semantically invalid combinations. It checks, among other things, that: diff --git a/docs/source/architecture/microscope_handler_integration.rst b/docs/source/architecture/microscope_handler_integration.rst index aa23124df3..7164dec998 100644 --- a/docs/source/architecture/microscope_handler_integration.rst +++ b/docs/source/architecture/microscope_handler_integration.rst @@ -48,9 +48,9 @@ read one post-initialisation authority instead of conditionally combining raw store coordinates with projected workspace coordinates. ``MetadataHandler.component_value_set()`` returns one complete -``MetadataComponentValueSet`` keyed by the canonical ``AllComponents`` -declaration. Handlers implement that single projection; generic consumers -iterate the declaration instead of calling one handler method per concrete +``MetadataComponentValueSet`` keyed by the axes of the active ``AxisFamily``. +Handlers implement that single projection; generic consumers +iterate the family instead of calling one handler method per concrete axis. Viewer and serialized mappings receive string keys only at their explicit boundary. diff --git a/docs/source/architecture/quick_start.rst b/docs/source/architecture/quick_start.rst index c027ff054d..12e8476831 100644 --- a/docs/source/architecture/quick_start.rst +++ b/docs/source/architecture/quick_start.rst @@ -223,7 +223,6 @@ For files such as ``A01_s1_DNA.tif`` and ``A01_s1_GFP.tif``: .. code-block:: python - from openhcs.constants import AllComponents from openhcs.core.config import ( LazyProcessingConfig, LazySourceBindingsConfig, @@ -241,6 +240,7 @@ For files such as ``A01_s1_DNA.tif`` and ``A01_s1_GFP.tif``: SourceSelector, ) from openhcs.core.steps.function_step import FunctionStep + from openhcs.domains.microscopy.axes import Microscopy from openhcs.processing.backends.processors.numpy_processor import ( stack_percentile_normalize, ) @@ -258,7 +258,7 @@ For files such as ``A01_s1_DNA.tif`` and ``A01_s1_GFP.tif``: ), ), component_identity=( - ComponentSelector(AllComponents.CHANNEL, channel), + ComponentSelector(Microscopy.Channel, channel), ), ) diff --git a/docs/source/concepts/component_system_concepts.rst b/docs/source/concepts/component_system_concepts.rst index 66ee2f34bb..7b694af41a 100644 --- a/docs/source/concepts/component_system_concepts.rst +++ b/docs/source/concepts/component_system_concepts.rst @@ -1,44 +1,49 @@ Component identities ==================== -Components name semantic microscopy dimensions such as well, site, channel, -Z index, and timepoint. OpenHCS creates process-stable enum families from the -authoritative component configuration. +Components name the semantic dimensions of a dataset. For microscopy they are +well, site, channel, Z index, and timepoint. Each is a declared axis: a class +nested in the domain's axis family, which the domain activates once per process. -Enum families -------------- +Axes, families, and roles +------------------------- -``AllComponents`` - The complete component set, including the multiprocessing execution axis. +``Axis`` + One declared dimension. The class is its identity; ``Axis.name`` is its + spelling at external boundaries (wire payloads, filenames, metadata, MCP). -``VariableComponents`` - Components that may vary along a step's assembled image stack. The - multiprocessing axis is excluded. +``AxisFamily`` + A domain's ordered set of axes. Microscopy declares ``Microscopy`` in + ``openhcs.domains.microscopy.axes``; the kernel asks only + ``AxisFamily.active()``. -``GroupBy`` - Components available for grouping plus the explicit ``NONE`` member. +Roles + Capability mixins an axis carries: ``PartitionAxis`` (exactly one; the + parallel axis), ``TileAxis``, ``ColourAxis``, ``StackAxis``, ``TimeAxis``, + ``DefaultVariable`` and ``DefaultGroupBy``. Kernel code selects axes by role, + for example ``AxisFamily.active().with_role(StackAxis)``, never by member. -``SequentialComponents`` - Components available for sequential-processing policy. +``Ungrouped`` + The explicit absent-grouping declaration a step's ``group_by`` may hold. -Multiprocessing axis --------------------- +Partition axis +-------------- -The configured multiprocessing axis—normally well—partitions orchestrator work. -The compiler creates a context for every selected value on this axis. It is an -``AllComponents`` member but not a ``VariableComponents`` member. +The partition axis (normally well) partitions orchestrator work. The compiler +creates a context for every selected value on this axis. Every other axis is a +variable axis that a step may assemble, group, or sequence along. Stack and grouping use ---------------------- .. code-block:: python - from openhcs.constants import GroupBy, VariableComponents from openhcs.core.config import LazyProcessingConfig, ProcessingConfig + from openhcs.domains.microscopy.axes import Microscopy processing = ProcessingConfig( - variable_components=(VariableComponents.SITE,), - group_by=GroupBy.CHANNEL, + variable_components=(Microscopy.Site,), + group_by=Microscopy.Channel, ) step = FunctionStep( func={"1": nuclei, "2": neurites}, @@ -59,8 +64,9 @@ recovered from path text at runtime. Extension rule -------------- -Extend the authoritative component configuration and its generic projections. -Do not create copied component lists in compiler, UI, storage, or backend code. +A new domain declares one ``AxisFamily`` subclass and activates it. Do not +create copied component lists or name family members in compiler, UI, +storage, or backend code; ask the active family by role. See :doc:`data_dimensions` and :doc:`../architecture/processing_semantics`. diff --git a/docs/source/concepts/data_dimensions.rst b/docs/source/concepts/data_dimensions.rst index 83f186e64b..baedf54635 100644 --- a/docs/source/concepts/data_dimensions.rst +++ b/docs/source/concepts/data_dimensions.rst @@ -83,12 +83,12 @@ Example .. code-block:: python - from openhcs.constants import GroupBy, VariableComponents from openhcs.core.config import LazyProcessingConfig, ProcessingConfig + from openhcs.domains.microscopy.axes import Microscopy processing = ProcessingConfig( - variable_components=(VariableComponents.SITE,), - group_by=GroupBy.CHANNEL, + variable_components=(Microscopy.Site,), + group_by=Microscopy.Channel, ) step = FunctionStep( func={"1": nuclei, "2": neurites}, diff --git a/docs/source/concepts/function_patterns.rst b/docs/source/concepts/function_patterns.rst index 28467b3b8d..6c90e2d698 100644 --- a/docs/source/concepts/function_patterns.rst +++ b/docs/source/concepts/function_patterns.rst @@ -37,12 +37,12 @@ A dictionary selects a function pattern for each compiled group key. The .. code-block:: python - from openhcs.constants import GroupBy, VariableComponents from openhcs.core.config import LazyProcessingConfig, ProcessingConfig + from openhcs.domains.microscopy.axes import Microscopy by_channel = ProcessingConfig( - variable_components=(VariableComponents.SITE,), - group_by=GroupBy.CHANNEL, + variable_components=(Microscopy.Site,), + group_by=Microscopy.Channel, ) step = FunctionStep( func={ diff --git a/docs/source/concepts/pipelines_and_steps.rst b/docs/source/concepts/pipelines_and_steps.rst index 4b676bb239..0f49040652 100644 --- a/docs/source/concepts/pipelines_and_steps.rst +++ b/docs/source/concepts/pipelines_and_steps.rst @@ -13,15 +13,15 @@ FunctionStep .. code-block:: python - from openhcs.constants import VariableComponents from openhcs.core.config import LazyProcessingConfig, ProcessingConfig from openhcs.core.steps.function_step import FunctionStep + from openhcs.domains.microscopy.axes import Microscopy def normalize(image, *, low=1.0, high=99.0): return image processing = ProcessingConfig( - variable_components=(VariableComponents.SITE,), + variable_components=(Microscopy.Site,), ) normalize_step = FunctionStep( func=(normalize, {"low": 1.0, "high": 99.0}), diff --git a/docs/source/development/mcp_knowledge_base_manifest.json b/docs/source/development/mcp_knowledge_base_manifest.json index f3b70bf0d9..d79d1b0224 100644 --- a/docs/source/development/mcp_knowledge_base_manifest.json +++ b/docs/source/development/mcp_knowledge_base_manifest.json @@ -392,12 +392,12 @@ "document_id": "openhcs_component_system", "section_count": 0, "source_path": "docs/source/concepts/component_system_concepts.rst", - "summary": "AllComponents, VariableComponents, GroupBy, MULTIPROCESSING_AXIS, component configuration, axis caching, wells, sites, channels, and z/time axes.", + "summary": "Axis, AxisFamily, axis roles (partition, tile, colour, stack, time), the Microscopy family, Ungrouped, axis caching, wells, sites, channels, and z/time axes.", "tags": [ - "AllComponents", - "VariableComponents", - "GroupBy", - "MULTIPROCESSING_AXIS", + "Axis", + "AxisFamily", + "axis roles", + "Ungrouped", "well", "site", "channel" diff --git a/docs/source/guide_for_biologists/image_sources.rst b/docs/source/guide_for_biologists/image_sources.rst index 1489383024..36e6577440 100644 --- a/docs/source/guide_for_biologists/image_sources.rst +++ b/docs/source/guide_for_biologists/image_sources.rst @@ -177,7 +177,7 @@ Do not use ``group_by=CHANNEL`` for assembly. ``group_by`` partitions an already assembled value and selects branches only for a dictionary function pattern. For this non-dictionary MetaXpress callable, an overlapping ``group_by=CHANNEL`` is redundant and the compiler normalizes it to -``GroupBy.NONE``. +``Ungrouped``. The explicit-subset regression is intentionally generic rather than a MetaXpress channel map: an implicit-main-flow callable must retain its ordered @@ -425,13 +425,13 @@ values equal merely to satisfy validation. .. code-block:: python - from openhcs.constants.constants import AllComponents from openhcs.core.config import LazySourceBindingsConfig, PipelineConfig from openhcs.core.source_bindings import ( ComponentSelector, NamedSourceBinding, SourceSelector, ) + from openhcs.domains.microscopy.axes import Microscopy pipeline_config = PipelineConfig( source_bindings_config=LazySourceBindingsConfig( @@ -440,12 +440,12 @@ values equal merely to satisfy validation. alias="DNA", selector=SourceSelector( components=( - ComponentSelector(AllComponents.WELL, "A01"), - ComponentSelector(AllComponents.CHANNEL, "2"), + ComponentSelector(Microscopy.Well, "A01"), + ComponentSelector(Microscopy.Channel, "2"), ), ), component_identity=( - ComponentSelector(AllComponents.CHANNEL, "DNA"), + ComponentSelector(Microscopy.Channel, "DNA"), ), ), ), diff --git a/external/pyqt-reactive b/external/pyqt-reactive index 11924d92f6..29d2ad3196 160000 --- a/external/pyqt-reactive +++ b/external/pyqt-reactive @@ -1 +1 @@ -Subproject commit 11924d92f654c88e1a11205e555b1726f30153f9 +Subproject commit 29d2ad319642de047410bca00c978a115e3f3452 diff --git a/external/python-introspect b/external/python-introspect index 496fedb0bd..c008baa8ae 160000 --- a/external/python-introspect +++ b/external/python-introspect @@ -1 +1 @@ -Subproject commit 496fedb0bd284361c8b32b74d091582506e0396a +Subproject commit c008baa8aec7a7481b37ea66e80539d25726499c diff --git a/openhcs/__init__.py b/openhcs/__init__.py index 07b24ec7f0..bdf3dbed44 100644 --- a/openhcs/__init__.py +++ b/openhcs/__init__.py @@ -19,6 +19,13 @@ ensure_source_checkout_external_paths() +# This distribution is the microscopy domain's entry point: it selects the +# process's axis family before any kernel module asks for it. Spawned workers +# and viewer processes import this package first, so each process activates it. +from openhcs.domains.microscopy.axes import Microscopy # noqa: E402 + +Microscopy.activate() + # Force UTF-8 encoding for stdout/stderr on Windows # This ensures emoji and Unicode characters work in console output if platform.system() == "Windows": diff --git a/openhcs/agent/capabilities.py b/openhcs/agent/capabilities.py index 73bd5caa95..51e44baa36 100644 --- a/openhcs/agent/capabilities.py +++ b/openhcs/agent/capabilities.py @@ -3342,7 +3342,7 @@ class SetViewerImageColorCapability(ViewerNativePresentationCapability): title = "Set native image colormap and blending" description = ( "Set an installed Napari colormap and blending mode on one exact mounted scalar " - "image route. Returns actual native readback. Use channel_mode=LAYER in the " + "image route. Returns actual native readback. Use colour_mode=LAYER in the " "stream's original display_config for simultaneous channel composition, and " "the existing image-intensity tool for each route's numeric window. No pixels, " "axes, transforms or physical source identities change. RGB images fail closed." diff --git a/openhcs/agent/dto/functions.py b/openhcs/agent/dto/functions.py index 322e63675f..9ac95cb3d0 100644 --- a/openhcs/agent/dto/functions.py +++ b/openhcs/agent/dto/functions.py @@ -525,7 +525,7 @@ class FunctionRuntimeContractSummary: processing_contract: str | None = None declared_processing_contract: str | None = None runtime_bound_parameters: tuple[str, ...] = () - required_variable_components: tuple[str, ...] = () + required_axis_roles: tuple[str, ...] = () artifact_inputs: tuple[FunctionArtifactSpec, ...] = () artifact_outputs: tuple[FunctionArtifactSpec, ...] = () cellprofiler_module: CellProfilerModuleDeclarationSummary | None = None diff --git a/openhcs/agent/dto/plate.py b/openhcs/agent/dto/plate.py index 65ffc9a5ba..cc5ac0bfec 100644 --- a/openhcs/agent/dto/plate.py +++ b/openhcs/agent/dto/plate.py @@ -15,7 +15,6 @@ ) from python_introspect import JsonObject, JsonValue, to_jsonable from openhcs.agent.dto.execution import ExecutionConnectionSpec -from openhcs.constants.constants import AllComponents from openhcs.core.config import NapariDisplayConfig from openhcs.core.plate_file_inventory import ( PlateFileInventoryQuery, @@ -915,9 +914,9 @@ class PlateInspectionComponentValue: @dataclass(frozen=True, slots=True) class PlateInspectionComponentSummary: - """Bounded values for one HCS component dimension.""" + """Bounded values for one declared axis, named by its boundary name.""" - component: AllComponents + component: str source: PlateInspectionValueSource count: int values: tuple[PlateInspectionComponentValue, ...] = () diff --git a/openhcs/agent/services/config_service.py b/openhcs/agent/services/config_service.py index 684235b709..5125546694 100644 --- a/openhcs/agent/services/config_service.py +++ b/openhcs/agent/services/config_service.py @@ -34,6 +34,7 @@ coerce_enum_member, declared_enum_type, enum_input_values, + resolve_optional, ) from openhcs.agent.dto.common import AgentError, RenderedSource, SCHEMA_VERSION @@ -58,6 +59,7 @@ from openhcs.core.config_document import ConfigDocumentAuthority from openhcs.core.steps.abstract import AbstractStep from openhcs.core.steps.function_step import FunctionStep +from openhcs.core.axes import AxisFamily, GroupingDeclaration AgentConfig: TypeAlias = GlobalPipelineConfig | PipelineConfig @@ -506,6 +508,11 @@ def _coerce_patch_value(field_type, value: JsonValue) -> object: if enum_type is not None: return coerce_enum_member(enum_type, value) + if isinstance(value, str) and _is_grouping_declaration_type( + resolve_optional(unwrapped_type) + ): + return AxisFamily.active().grouping_named(value) + path_type = _unwrap_path_type(unwrapped_type) if path_type is not None and isinstance(value, str): return path_type(value) @@ -517,6 +524,15 @@ def _coerce_patch_value(field_type, value: JsonValue) -> object: return value +def _is_grouping_declaration_type(field_type) -> bool: + """Whether a field holds an axis or grouping declaration (``type[...]``).""" + + if get_origin(field_type) is not type: + return False + (bound,) = get_args(field_type) + return isinstance(bound, type) and issubclass(bound, GroupingDeclaration) + + def _coerce_collection_patch_value(field_type, value: JsonValue) -> tuple[bool, object]: field_type = _unwrap_annotated(field_type) origin = get_origin(field_type) @@ -705,8 +721,10 @@ def _field_schema_tree( field_descriptions = dataclass_parameter_descriptions(cls) try: resolved_types = get_type_hints(cls) + declared_types = get_type_hints(cls, include_extras=True) except (NameError, TypeError): resolved_types = {} + declared_types = {} direct_fields: list[ConfigFieldSchema] = [] nested_fields: list[ConfigFieldSchema] = [] next_ancestors = (*ancestors, cls) @@ -720,6 +738,7 @@ def _field_schema_tree( field_descriptions, declaring_cls=cls, field_type=field_type, + declared_type=declared_types.get(config_field.name, field_type), field_path=field_path, authoring_value_path=authoring_value_path, inheritable=inherited_from_lazy_scope, @@ -752,6 +771,7 @@ def _schema_for_field( *, declaring_cls: type, field_type=None, + declared_type=None, field_path: str | None = None, authoring_value_path: tuple[str, ...] | None = None, inheritable: bool = False, @@ -774,7 +794,9 @@ def _schema_for_field( default_repr=default_repr, required=_is_required(field), description=field_descriptions.get(field.name), - enum_values=enum_input_values(source_type), + enum_values=enum_input_values( + source_type if declared_type is None else declared_type + ), registry_values=_registered_type_values(source_type), ui_hidden=ui_hidden, lazy=lazy_base is not None, diff --git a/openhcs/agent/services/function_catalog_service.py b/openhcs/agent/services/function_catalog_service.py index 60cafbceb0..d3ad4f8f22 100644 --- a/openhcs/agent/services/function_catalog_service.py +++ b/openhcs/agent/services/function_catalog_service.py @@ -1254,8 +1254,8 @@ def _runtime_contract_summary( processing_contract=_enum_member_name(contract.processing_contract), declared_processing_contract=contract.declared_processing_contract, runtime_bound_parameters=contract.runtime_bound_parameters, - required_variable_components=tuple( - component.name for component in contract.required_variable_components + required_axis_roles=tuple( + role.__name__ for role in contract.required_axis_roles ), artifact_inputs=artifact_inputs, artifact_outputs=artifact_outputs, diff --git a/openhcs/agent/services/llm_context_service.py b/openhcs/agent/services/llm_context_service.py index b75f5c0f67..a556a5096d 100644 --- a/openhcs/agent/services/llm_context_service.py +++ b/openhcs/agent/services/llm_context_service.py @@ -288,7 +288,7 @@ def render(cls, service: "AgentAuthoringContextService") -> str: - source_stack_components describe axes physically contained inside each selected file/store payload. Do not declare SITE or another source-stack axis for separate ordinary 2-D files; give those files component identities and use processing_config.variable_components to assemble the selected files into a callable stack. - Keep three layers separate: the full pipeline source universe, the resolved/compiled ordered per-step binding plan, and the callable stack assembled according to variable_components. Callable channel indices are zero-based positions in that per-step assembled stack, not physical microscope CHANNEL values. If the step plan orders (SMI312 channel 4, Hoechst channel 1) with variable_components=CHANNEL, use callable positions 0 and 1. Source provenance remains channel 4 and channel 1, and route provenance retains those declared values when the output carries them. - The simplest canonical MetaXpress neurite step omits the step subset, inherits (Hoechst channel 1, MAP2 channel 2, SMI312 channel 4), sets input_source=PIPELINE_START and variable_components=[CHANNEL], and uses nuclear index 0, cell-body index 1, and neurite index 2. This is the compact preset's scientifically preferred Hoechst/MAP2/SMI312 model. A two-plane (SMI312, Hoechst) subset with neurite index 0 and nuclear index 1 is only the legacy shared-signal model where cell bodies are intentionally detected from SMI312 too; it is not equivalent to MAP2-seeded analysis. Retain MAP2 whenever it owns the bodies. The generic compiler regression protects any explicit ordered primary-plane subset for an implicit-main-flow callable; it is not a MetaXpress channel map. -- variable_components=[CHANNEL] assembles that stack. group_by=CHANNEL does not: group_by partitions an already assembled value and routes dictionary patterns. Because the MetaXpress callable is non-dictionary and CHANNEL already owns its assembled axis, the overlap is redundant and compilation normalizes group_by to GroupBy.NONE. +- variable_components=[CHANNEL] assembles that stack. group_by=CHANNEL does not: group_by partitions an already assembled value and routes dictionary patterns. Because the MetaXpress callable is non-dictionary and CHANNEL already owns its assembled axis, the overlap is redundant and compilation normalizes group_by to Ungrouped. - Step source subsets/reordering select or re-enter original declared sources, especially at PIPELINE_START or a deliberate source branch. They do not reinterpret a previous-step output after stitching, Z/channel projection, or filtering changes its axes/cardinality. Follow current artifact provenance plus the downstream variable_components declaration; group_by then partitions that already assembled value. - Source bindings compile into a source universe, per-step binding plans, and a virtual workspace. Query projected virtual paths and source_metadata rather than treating physical filenames, decoders, or storage backends as the pipeline ABI. Source-satisfied typed artifact inputs do not require invented runtime producer plans. - Validate on representative files: inspect the full pipeline source workspace, then the resolved FunctionStep.source_bindings subset/order, then CompiledSourceBindingPlan.bindings, runtime-matched files, and current viewer routes. An unexpectedly empty compiled step plan when two bindings were selected explains why all three universe planes may flow. Do not guess a third callable index: use {agent_capabilities.get_viewer_window_payloads.name} to compare the current execution's layer/payload route keys and physical component values. MAP2 channel 2 is valid in the source workspace; it is a leaked source only on a current route for a step whose resolved/compiled plan selects SMI312 and Hoechst. A route from another submission or a step that selects MAP2 is different evidence. Conflicts and missing required aliases must be fixed in the declarations, never hidden by fallback matching. diff --git a/openhcs/agent/services/plate_inspection_service.py b/openhcs/agent/services/plate_inspection_service.py index 7e083f2e29..4b27898498 100644 --- a/openhcs/agent/services/plate_inspection_service.py +++ b/openhcs/agent/services/plate_inspection_service.py @@ -48,7 +48,7 @@ from openhcs.agent.ui_bridge_identities import ( PlateManagerOrchestratorCodeDocumentIdentity, ) -from openhcs.constants.constants import AllComponents, Backend, Microscope +from openhcs.constants.constants import Backend, Microscope from openhcs.core.config import GlobalPipelineConfig, PathPlanningConfig from openhcs.core.plate_image_inventory import ( PlateFileKind, @@ -61,6 +61,7 @@ PlateResultFilePreviewReader, PlateResultFileInventory, ) +from openhcs.core.axes import Axis, AxisFamily if TYPE_CHECKING: from openhcs.core.components.parser_metaprogramming import ( FilenameParseResult, @@ -351,20 +352,20 @@ def preview( class PlateInspectionComponentEntrySet: """Nominal value set for one HCS component axis.""" - component: AllComponents + component: type[Axis] values: tuple[PlateInspectionComponentValue, ...] = () @classmethod def empty( cls, - component: AllComponents, + component: type[Axis], ) -> "PlateInspectionComponentEntrySet": return cls(component=component) @classmethod def parsed( cls, - component: AllComponents, + component: type[Axis], keys: tuple[str, ...], ) -> "PlateInspectionComponentEntrySet": return cls( @@ -382,7 +383,7 @@ def parsed( @classmethod def metadata( cls, - component: AllComponents, + component: type[Axis], values: Mapping[str, str | None] | None, ) -> "PlateInspectionComponentEntrySet": if values is None: @@ -424,13 +425,13 @@ def empty(cls) -> "PlateInspectionComponentCollection": return cls( tuple( PlateInspectionComponentEntrySet.empty(component) - for component in AllComponents + for component in AxisFamily.active().axes ) ) def for_component( self, - component: AllComponents, + component: type[Axis], ) -> PlateInspectionComponentEntrySet: for entry in self.entries: if entry.component is component: @@ -464,7 +465,7 @@ def from_value_set( component, component_values.values_for(component), ) - for component in AllComponents + for component in AxisFamily.active().axes ) ) @@ -473,12 +474,12 @@ def from_value_set( class PlateInspectionMutableParsedComponents: """Mutable accumulator before parsed component values are frozen.""" - values: dict[AllComponents, set[str]] = field( - default_factory=lambda: {component: set() for component in AllComponents} + values: dict[type[Axis], set[str]] = field( + default_factory=lambda: {component: set() for component in AxisFamily.active().axes} ) def add_parsed_filename_values(self, parsed: "FilenameParseResult") -> None: - for component in AllComponents: + for component in AxisFamily.active().axes: self._add_optional( self.values[component], parsed.value_for(component), @@ -501,7 +502,7 @@ def freeze(self) -> PlateInspectionComponentCollection: ) ), ) - for component in AllComponents + for component in AxisFamily.active().axes ) ) @@ -596,7 +597,7 @@ def build( bounds: PlateInspectionBounds, ) -> tuple[PlateInspectionComponentSummary, ...]: summaries: list[PlateInspectionComponentSummary] = [] - for component in AllComponents: + for component in AxisFamily.active().axes: metadata_entries = metadata_values.for_component(component) parsed_entries = parsed_values.for_component(component) keys = tuple( @@ -616,7 +617,7 @@ def build( ) summaries.append( PlateInspectionComponentSummary( - component=component, + component=component.name, source=self._source(metadata_entries, parsed_entries), count=len(keys), values=values, diff --git a/openhcs/agent/services/plate_streaming_service.py b/openhcs/agent/services/plate_streaming_service.py index d3a96d777b..65c32d725e 100644 --- a/openhcs/agent/services/plate_streaming_service.py +++ b/openhcs/agent/services/plate_streaming_service.py @@ -33,7 +33,7 @@ DEFAULT_UI_BRIDGE_CONNECTION_SPEC, UiBridgeService, ) -from openhcs.constants import AllComponents, Backend +from openhcs.constants import Backend from openhcs.core.config import StreamingConfig from openhcs.core.plate_image_inventory import ( PlateFileKind, @@ -67,6 +67,7 @@ DetachedViewerLaunchFailure, ViewerGraphicalSessionUnavailableError, ) +from openhcs.core.axes import AxisFamily class PlateStreamingService: @@ -413,8 +414,8 @@ def _receipt_source_projection( first_components = planes.component_metadata[0] projection = SourcePlaneProjection( address=OpenHCSPlaneAddress( - (component, first_components[component.value]) - for component in AllComponents + (component, first_components[component.name]) + for component in AxisFamily.active().axes ), ref=source_ref, source_metadata=first_components, diff --git a/openhcs/constants/__init__.py b/openhcs/constants/__init__.py index f68f781eee..3548723e9b 100644 --- a/openhcs/constants/__init__.py +++ b/openhcs/constants/__init__.py @@ -12,8 +12,6 @@ DEFAULT_ASSEMBLER_LOG_LEVEL, DEFAULT_BACKEND, DEFAULT_CPU_THREAD_COUNT, - get_default_group_by, - get_multiprocessing_axis, DEFAULT_IMAGE_EXTENSION, DEFAULT_IMAGE_EXTENSIONS, LOADABLE_IMAGE_EXTENSIONS, @@ -27,7 +25,6 @@ DEFAULT_RECURSIVE_PATTERN_SEARCH, DEFAULT_SITE_PADDING, DEFAULT_TILE_OVERLAP, - get_default_variable_components, FORCE_DISK_WRITE, GPU_MEMORY_TYPES, MEMORY_TYPE_CUPY, @@ -45,17 +42,9 @@ VALID_MEMORY_TYPES, WRITE_BACKEND, Backend, - AllComponents, - GroupBy, MemoryType, - SequentialComponents, - VariableComponents, ) -DEFAULT_VARIABLE_COMPONENTS = get_default_variable_components() -DEFAULT_GROUP_BY = get_default_group_by() -MULTIPROCESSING_AXIS = get_multiprocessing_axis() - __all__ = [ # Backends "Backend", @@ -84,15 +73,8 @@ "LOADABLE_IMAGE_EXTENSIONS", "DEFAULT_SITE_PADDING", "DEFAULT_RECURSIVE_PATTERN_SEARCH", - "DEFAULT_VARIABLE_COMPONENTS", - "DEFAULT_GROUP_BY", - "AllComponents", - "GroupBy", - "SequentialComponents", - "VariableComponents", "Microscope", "DEFAULT_MICROSCOPE", - "MULTIPROCESSING_AXIS", # Input Source "InputSource", # Pipeline diff --git a/openhcs/constants/constants.py b/openhcs/constants/constants.py index 118809ecfa..27f2e29790 100644 --- a/openhcs/constants/constants.py +++ b/openhcs/constants/constants.py @@ -3,14 +3,10 @@ This module defines all constants related to backends, defaults, I/O, memory, and pipeline. These constants are governed by various doctrinal clauses. - -Component enums are created once per process from the declared component order. """ -import logging from enum import Enum -from functools import lru_cache -from typing import Any, Set +from typing import Set from arraybridge.types import ( CPU_MEMORY_TYPES as CPU_MEMORY_TYPES, @@ -50,8 +46,6 @@ ) from polystore.constants import Backend -logger = logging.getLogger(__name__) - class Microscope(Enum): AUTO = "auto" @@ -63,164 +57,6 @@ class Microscope(Enum): SOURCE_BINDINGS = "source_bindings" -def get_openhcs_config(): - """Get the OpenHCS configuration, initializing it if needed.""" - from openhcs.core.components.framework import ComponentConfigurationFactory - - return ComponentConfigurationFactory.create_openhcs_default_configuration() - - -def _enum_value_for_comparison(value: Any) -> Any: - """Return enum value for equality hooks without reflective attribute access.""" - if isinstance(value, Enum): - return value.value - return value - - -def _add_groupby_methods(GroupBy: Enum) -> Enum: - """Add custom methods to GroupBy enum.""" - - def groupby_eq(self, other: Any) -> bool: - # GroupBy.NONE is a concrete enum value in user/config state. It must - # not compare equal to Python None, which is the lazy-inheritance - # sentinel in ObjectState and lazy dataclass fields. - if other is None: - return False - return self.value == _enum_value_for_comparison(other) - - GroupBy.component = property(lambda self: self.value) - GroupBy.__eq__ = groupby_eq - GroupBy.__hash__ = lambda self: ( - hash("GroupBy.NONE") if self.value is None else hash(self.value) - ) - GroupBy.__str__ = lambda self: f"GroupBy.{self.name}" - GroupBy.__repr__ = lambda self: f"GroupBy.{self.name}" - return GroupBy - - -def _add_allcomponents_methods(AllComponents: Enum) -> Enum: - """Add component-axis semantic methods to the dynamic component enum.""" - - def from_value(cls, value: Any): - for component in cls: - if component.value == value: - return component - return None - - def ordered_names(cls) -> tuple[str, ...]: - return tuple(component.value for component in cls) - - def is_multiprocessing_axis(self) -> bool: - return self.value == get_multiprocessing_axis().value - - def is_variable_axis(self) -> bool: - return not self.is_multiprocessing_axis() - - def is_default_group_by_axis(self) -> bool: - group_by = get_default_group_by() - return group_by is not None and self.value == group_by.value - - AllComponents.from_value = classmethod(from_value) - AllComponents.ordered_names = classmethod(ordered_names) - AllComponents.is_multiprocessing_axis = is_multiprocessing_axis - AllComponents.is_variable_axis = is_variable_axis - AllComponents.is_default_group_by_axis = is_default_group_by_axis - return AllComponents - - -# Simple lazy initialization - just defer the config call -@lru_cache(maxsize=1) -def _create_enums(): - """Create process-local component enums when first needed. - - CRITICAL: This function must create enums with proper __module__ and __qualname__ - attributes so they can be pickled correctly in multiprocessing contexts. - The enums are stored in module globals() to ensure identity consistency. - - The function-local cache preserves enum identity within the process. - """ - import os - - logger.debug("_create_enums() called in process %s", os.getpid()) - logger.debug("_create_enums() cache_info: %s", _create_enums.cache_info()) - if logger.isEnabledFor(logging.DEBUG): - import traceback - - logger.debug( - "_create_enums() stack trace:\n%s", - "".join(traceback.format_stack()), - ) - - config = get_openhcs_config() - remaining = config.get_remaining_components() - - # AllComponents: ALL possible dimensions (including multiprocessing axis) - all_components_dict = {c.name: c.value for c in config.all_components} - all_components = Enum("AllComponents", all_components_dict) - all_components.__module__ = __name__ - all_components.__qualname__ = "AllComponents" - all_components = _add_allcomponents_methods(all_components) - - # VariableComponents: Components available for variable selection (excludes multiprocessing axis) - vc_dict = {c.name: c.value for c in remaining} - vc = Enum("VariableComponents", vc_dict) - vc.__module__ = __name__ - vc.__qualname__ = "VariableComponents" - - # GroupBy: Same as VariableComponents + NONE option (they're the same concept) - gb_dict = {c.name: c.value for c in remaining} - gb_dict["NONE"] = None - GroupBy = Enum("GroupBy", gb_dict) - GroupBy.__module__ = __name__ - GroupBy.__qualname__ = "GroupBy" - GroupBy = _add_groupby_methods(GroupBy) - - # SequentialComponents: Same as VariableComponents (for sequential processing) - sc_dict = {c.name: c.value for c in remaining} - sc = Enum("SequentialComponents", sc_dict) - sc.__module__ = __name__ - sc.__qualname__ = "SequentialComponents" - - logger.debug( - "_create_enums() returning in process %s: AllComponents=%s, " - "VariableComponents=%s, GroupBy=%s, SequentialComponents=%s", - os.getpid(), - id(all_components), - id(vc), - id(GroupBy), - id(sc), - ) - logger.debug( - "_create_enums() cache_info after return: %s", - _create_enums.cache_info(), - ) - return all_components, vc, GroupBy, sc - - -@lru_cache(maxsize=1) -def _create_streaming_components(): - """Create StreamingComponents enum from real filename components.""" - import os - - logger.debug("_create_streaming_components() called in process %s", os.getpid()) - - components_dict = {c.name: c.value for c in AllComponents} - - streaming_components = Enum("StreamingComponents", components_dict) - streaming_components.__module__ = __name__ - streaming_components.__qualname__ = "StreamingComponents" - - logger.debug( - "_create_streaming_components() returning: StreamingComponents=%s", - id(streaming_components), - ) - return streaming_components - - -AllComponents, VariableComponents, GroupBy, SequentialComponents = _create_enums() -StreamingComponents = _create_streaming_components() - - # Documentation URL DOCUMENTATION_URL = "https://openhcs.readthedocs.io/en/latest/" @@ -305,33 +141,6 @@ def __new__( DEFAULT_RECURSIVE_PATTERN_SEARCH = False -# Lazy default resolution using lru_cache -@lru_cache(maxsize=1) -def get_default_variable_components(): - """Get default variable components from ComponentConfiguration.""" - _, vc, _, _ = _create_enums() # Get the enum directly - return [vc.__members__[c.name] for c in get_openhcs_config().default_variable] - - -@lru_cache(maxsize=1) -def get_default_group_by(): - """Get default group_by from ComponentConfiguration.""" - _, _, gb, _ = _create_enums() # Get the enum directly - config = get_openhcs_config() - if config.default_group_by is None: - return gb.__members__["NONE"] - return gb.__members__[config.default_group_by.name] - - -@lru_cache(maxsize=1) -def get_multiprocessing_axis(): - """Get the multiprocessing axis from the canonical component enum.""" - - all_components, _, _, _ = _create_enums() - config = get_openhcs_config() - return all_components.__members__[config.multiprocessing_axis.name] - - DEFAULT_MICROSCOPE: Microscope = Microscope.AUTO diff --git a/openhcs/core/artifacts.py b/openhcs/core/artifacts.py index ce2bfd0b27..78c6016341 100644 --- a/openhcs/core/artifacts.py +++ b/openhcs/core/artifacts.py @@ -19,9 +19,9 @@ from metaclass_registry import AutoRegisterMeta -from openhcs.constants.constants import AllComponents from openhcs.core.component_group_scope import ComponentGroupScope from openhcs.core.component_set import ComponentSet +from openhcs.core.axes import Axis, AxisFamily if TYPE_CHECKING: from openhcs.core.steps.function_output_identity import FunctionOutputIdentity @@ -917,7 +917,7 @@ def normalize_group_scoped_payload( if projection.axis_size != 1: raise ValueError( f"Group-scoped scalar artifact {output_plan.name!r} for " - f"{output_plan.group_component.value!r} cannot retain a declared " + f"{output_plan.group_component.name!r} cannot retain a declared " f"runtime-slice axis of size {projection.axis_size}." ) return RuntimeSliceProjection.value_for_slice( @@ -1447,7 +1447,7 @@ def uses_aggregate_materialization_identity(cls, data: object) -> bool: return False provenance = data.source_provenance return bool( - provenance.varying_plane_component_values(tuple(AllComponents)) + provenance.varying_plane_component_values(AxisFamily.active().axes) or len(provenance.represented_source_identities) > 1 ) @@ -3340,8 +3340,8 @@ class ArtifactPlan(ABC, metaclass=AutoRegisterMeta): path: str artifact_type: type[ArtifactType] = SpecialArtifactType group_keys: tuple[str | None, ...] = (None,) - group_component: AllComponents | None = None - variable_components: tuple[AllComponents, ...] = () + group_component: type[Axis] | None = None + variable_components: tuple[type[Axis], ...] = () component_domains: tuple[ComponentGroupScope, ...] = () paths_by_group: Mapping[str | None, str] | None = None sidecar_role: ArtifactSidecarRole | None = None @@ -3378,9 +3378,9 @@ def __post_init__(self) -> None: object.__setattr__( self, "variable_components", - ComponentSet.coerce(self.variable_components).as_tuple(), + ComponentSet.of(self.variable_components).as_tuple(), ) - normalized_domains: dict[AllComponents, ComponentGroupScope] = {} + normalized_domains: dict[type[Axis], ComponentGroupScope] = {} for domain in self.component_domains: if not isinstance(domain, ComponentGroupScope): raise TypeError( @@ -3397,7 +3397,7 @@ def __post_init__(self) -> None: if existing is not None and existing != canonical_domain: raise ValueError( f"Artifact plan {self.name!r} declares conflicting domains for " - f"component {domain.component.value!r}: {existing!r} and " + f"component {domain.component.name!r}: {existing!r} and " f"{canonical_domain!r}." ) normalized_domains[domain.component] = canonical_domain @@ -3409,7 +3409,7 @@ def __post_init__(self) -> None: if self.group_component in self.variable_components: raise ValueError( f"Artifact plan {self.name!r} cannot group by " - f"{self.group_component.value!r} while also retaining it as a " + f"{self.group_component.name!r} while also retaining it as a " "variable component." ) self.group_scope() @@ -3430,7 +3430,7 @@ def participates_in_main_flow(self) -> bool: def component_domain( self, - component: AllComponents, + component: type[Axis], ) -> ComponentGroupScope | None: """Return the compiled domain inherited for one component axis.""" @@ -3465,7 +3465,7 @@ def component_coordinate_scopes(self) -> tuple[ComponentGroupScope, ...]: scopes_by_component[component] for component in sorted( scopes_by_component, - key=lambda value: value.value, + key=lambda value: value.name, ) ) @@ -3911,7 +3911,7 @@ class ArtifactInputProjectionPlan: invocation_scope: ComponentGroupScope producer_selection_scope: ComponentGroupScope component_scopes: tuple[ComponentGroupScope, ...] = () - consumer_variable_components: tuple[AllComponents, ...] = () + consumer_variable_components: tuple[type[Axis], ...] = () @staticmethod def declared_producer_selection_scope( @@ -4014,7 +4014,7 @@ def __post_init__(self) -> None: ), ) - normalized_scopes: dict[AllComponents, ComponentGroupScope] = {} + normalized_scopes: dict[type[Axis], ComponentGroupScope] = {} for scope in self.component_scopes: if not isinstance(scope, ComponentGroupScope): raise TypeError( @@ -4034,7 +4034,7 @@ def __post_init__(self) -> None: if existing is not None and existing != canonical_scope: raise ValueError( "Artifact input projection declares conflicting scopes for " - f"component {scope.component.value!r}: {existing!r} and " + f"component {scope.component.name!r}: {existing!r} and " f"{canonical_scope!r}." ) normalized_scopes[scope.component] = canonical_scope @@ -4046,12 +4046,12 @@ def __post_init__(self) -> None: object.__setattr__( self, "consumer_variable_components", - ComponentSet.coerce(self.consumer_variable_components).as_tuple(), + ComponentSet.of(self.consumer_variable_components).as_tuple(), ) def component_scope( self, - component: AllComponents, + component: type[Axis], ) -> ComponentGroupScope | None: """Return the exact compiled coordinate for one projected component.""" @@ -4066,10 +4066,10 @@ def projected_variable_components( ) -> ComponentSet: """Return producer stack axes projected out for this consumer invocation.""" - consumer_components = ComponentSet.coerce(self.consumer_variable_components) + consumer_components = ComponentSet.of(self.consumer_variable_components) if storage_plan.retains_producer_stack(consumer_components): return ComponentSet() - return ComponentSet.coerce(storage_plan.variable_components) + return ComponentSet.of(storage_plan.variable_components) def validate_storage_plan(self, storage_plan: ArtifactInputPlan) -> None: """Require this projection to select within its producer storage plan.""" @@ -4087,7 +4087,7 @@ def validate_storage_plan(self, storage_plan: ArtifactInputPlan) -> None: if selection_scope.component is not producer_scope.component: raise ValueError( f"Artifact input {artifact_ref!r} producer component " - f"{producer_scope.component.value!r} does not match selection " + f"{producer_scope.component.name!r} does not match selection " f"{selection_scope.component!r}." ) if not selection_scope.is_dynamic: @@ -4105,14 +4105,14 @@ def validate_axis_projection(self, storage_plan: ArtifactInputPlan) -> None: artifact_ref = storage_plan.ref() producer_scope = storage_plan.producer_group_scope() selection_scope = self.producer_selection_scope - retained_components = ComponentSet.coerce(self.consumer_variable_components) + retained_components = ComponentSet.of(self.consumer_variable_components) if ( not producer_scope.is_ungrouped and producer_scope.component in retained_components ): if selection_scope != producer_scope: raise ValueError( - f"Retained producer axis {producer_scope.component.value!r} for " + f"Retained producer axis {producer_scope.component.name!r} for " f"{artifact_ref!r} must select the complete producer scope." ) elif not producer_scope.is_ungrouped: @@ -4132,12 +4132,12 @@ def validate_axis_projection(self, storage_plan: ArtifactInputPlan) -> None: if scope is None: raise ValueError( f"Artifact input {artifact_ref!r} projects producer stack " - f"component {component.value!r} without an exact coordinate." + f"component {component.name!r} without an exact coordinate." ) if not scope.is_dynamic and len(scope.keys) != 1: raise ValueError( f"Artifact input {artifact_ref!r} projection for component " - f"{component.value!r} is not a single exact coordinate: {scope!r}." + f"{component.name!r} is not a single exact coordinate: {scope!r}." ) if scope.is_dynamic and self.invocation_scope.component is not component: raise ValueError( diff --git a/openhcs/core/axes.py b/openhcs/core/axes.py new file mode 100644 index 0000000000..2480216fc8 --- /dev/null +++ b/openhcs/core/axes.py @@ -0,0 +1,553 @@ +"""Declared data axes: the kernel's only notion of which dimensions exist. + +A domain declares one :class:`AxisFamily` whose nested :class:`Axis` classes +are the axes. Each axis is a nominal class: identity is the class, membership +in a role is inheritance from an :class:`AxisRole` capability mixin, and the +behaviour the kernel needs lives on the role. The kernel never names a member; +it asks the active family by role (``AxisFamily.active().with_role(StackAxis)``). + +Strings exist only at external boundaries (wire payloads, filenames, metadata, +MCP), spelled by ``Axis.name`` and decoded by ``AxisFamily.named``. +""" + +from __future__ import annotations + +from abc import ABC, abstractmethod +from typing import ClassVar, TypeGuard + +from metaclass_registry import AutoRegisterMeta + + +class AxisDeclarationMeta(AutoRegisterMeta): + """Metaclass for axis declarations: classes that are values. + + Axis classes travel through configs, logs and placeholders as values, so + their ``repr`` is their declared qualified name rather than ````. + """ + + def __init__(cls, name, bases, namespace, **kwargs) -> None: + # Declarations are checked once the class is complete. Raising from + # ``__init_subclass__`` would leave a half-built ABC subclass whose + # inherited subclass-check state makes unrelated axes pass role checks. + super().__init__(name, bases, namespace, **kwargs) + validate = getattr(cls, "_validate_declaration", None) + if validate is not None: + validate() + + def __repr__(cls) -> str: + return cls.__qualname__ + + __str__ = __repr__ + + +# --------------------------------------------------------------------------- +# Cardinality +# --------------------------------------------------------------------------- + + +class Cardinality(ABC): + """How many axes of one family may carry a role.""" + + @classmethod + @abstractmethod + def admits(cls, count: int) -> bool: + """Return whether ``count`` axes may carry the role.""" + + @classmethod + @abstractmethod + def describe(cls) -> str: + """Human-readable rule for error messages.""" + + +class Many(Cardinality): + @classmethod + def admits(cls, count: int) -> bool: + return count >= 0 + + @classmethod + def describe(cls) -> str: + return "any number of axes" + + +class ExactlyOne(Cardinality): + @classmethod + def admits(cls, count: int) -> bool: + return count == 1 + + @classmethod + def describe(cls) -> str: + return "exactly one axis" + + +class AtMostOne(Cardinality): + @classmethod + def admits(cls, count: int) -> bool: + return count <= 1 + + @classmethod + def describe(cls) -> str: + return "at most one axis" + + +# --------------------------------------------------------------------------- +# Roles and value kinds (capability mixins) +# --------------------------------------------------------------------------- + + +class AxisRole(ABC): + """Capability an axis carries; the kernel asks the family by role.""" + + cardinality: ClassVar[type[Cardinality]] = Many + + +class PartitionAxis(AxisRole): + """The parallel axis: one worker lane, filter target and reduction key per value.""" + + cardinality = ExactlyOne + + +class StackAxis(AxisRole): + """Ordered planes; a "plane" is one slice along this axis.""" + + cardinality = AtMostOne + + +class ColourAxis(AxisRole): + """Spectral or channel axis.""" + + +class TileAxis(AxisRole): + """Spatial tiles or fields that together cover one partition.""" + + +class TimeAxis(AxisRole): + """Acquisition time.""" + + +class DefaultVariable(AxisRole): + """Axes a step assembles along when it declares no variable axes.""" + + +class DefaultGroupBy(AxisRole): + """The axis a step groups by when it declares no grouping.""" + + cardinality = AtMostOne + + +class AxisValueKind(ABC): + """How an axis spells its values. Every axis carries exactly one kind.""" + + @classmethod + @abstractmethod + def sort_key(cls, value: object) -> tuple[int, int | str]: + """Order key for one axis value.""" + + @classmethod + @abstractmethod + def normalize_value(cls, value: object) -> str: + """Canonical text for one axis value.""" + + +class LabelValued(AxisValueKind): + """Values are labels compared as text (for example ``"A01"``).""" + + @classmethod + def sort_key(cls, value: object) -> tuple[int, int | str]: + return (1, str(value)) + + @classmethod + def normalize_value(cls, value: object) -> str: + return str(value) + + +class OrdinalValued(AxisValueKind): + """Values are ordinals; numeric text orders numerically.""" + + @classmethod + def sort_key(cls, value: object) -> tuple[int, int | str]: + text = str(value) + if text.isdigit(): + return (0, int(text)) + return (1, text) + + @classmethod + def normalize_value(cls, value: object) -> str: + text = str(value) + return str(int(text)) if text.isdecimal() else text + + +# --------------------------------------------------------------------------- +# Grouping declarations: an axis, or the explicit absence of grouping +# --------------------------------------------------------------------------- + + +class GroupingDeclaration(ABC, metaclass=AxisDeclarationMeta): + """What a step's ``group_by`` holds: one axis, or :class:`Ungrouped`. + + Declarations register under their boundary ``name``, which is therefore + also their JSON spelling. Boundaries decode names through the active family + (``AxisFamily.named``), never through this registry: two families may + declare the same name. + """ + + __registry_key__ = "name" + __skip_if_no_key__ = True + + name: ClassVar[str] + + @classmethod + @abstractmethod + def grouping_axes(cls) -> tuple[type[Axis], ...]: + """The axes whose values partition an assembled value (empty: none).""" + + +class Axis(GroupingDeclaration): + """One declared axis. Subclasses are nested in an :class:`AxisFamily`.""" + + name: ClassVar[str] + family: ClassVar[type[AxisFamily]] + filename_prefix: ClassVar[str | None] = None + """Token before this axis's value in plane filenames (variable axes).""" + filename_padding: ClassVar[int] = 0 + """Zero padding for ordinal values in plane filenames.""" + + sort_key: ClassVar # supplied by the axis's AxisValueKind + normalize_value: ClassVar # supplied by the axis's AxisValueKind + + @classmethod + def _validate_declaration(cls) -> None: + if "_validate_declaration" in cls.__dict__: + return # the declaring base itself + if "name" not in cls.__dict__: + raise TypeError(f"Axis {cls.__qualname__} must declare its boundary name.") + kinds = [base for base in cls.__mro__ if AxisValueKind in base.__bases__] + if len(kinds) != 1: + raise TypeError( + f"Axis {cls.__qualname__} must carry exactly one AxisValueKind; " + f"found {[kind.__name__ for kind in kinds]}." + ) + + def __new__(cls, *args: object, **kwargs: object): + raise TypeError(f"{cls.__qualname__} is an axis declaration, not a value type.") + + @classmethod + def grouping_axes(cls) -> tuple[type[Axis], ...]: + return (cls,) + + @classmethod + def has_role(cls, role: type[AxisRole]) -> bool: + return issubclass(cls, role) + + @classmethod + def filename_token(cls, value: object) -> str: + """Spell one value in a plane filename.""" + + if cls.filename_prefix is None: + raise TypeError(f"Axis {cls!r} declares no filename prefix.") + text = cls.normalize_value(value) + if cls.filename_padding and text.isdecimal(): + text = f"{int(text):0{cls.filename_padding}d}" + return f"{cls.filename_prefix}{text}" + + + +class Ungrouped(GroupingDeclaration): + """Explicit absent-grouping declaration: the step does not partition its value.""" + + name = "none" + + @classmethod + def grouping_axes(cls) -> tuple[type[Axis], ...]: + return () + + +def is_axis(value: object) -> TypeGuard[type[Axis]]: + """Return whether ``value`` is a declared axis class.""" + + return isinstance(value, type) and issubclass(value, Axis) and value is not Axis + + +def is_grouping_declaration(value: object) -> TypeGuard[type[GroupingDeclaration]]: + """Return whether ``value`` is an axis or :class:`Ungrouped`.""" + + return is_axis(value) or value is Ungrouped + + +# --------------------------------------------------------------------------- +# Families +# --------------------------------------------------------------------------- + + +class AxisFamilyNotActive(RuntimeError): + """The kernel was used before a domain activated its axis family.""" + + +class AxisFamily(metaclass=AxisDeclarationMeta): + """A domain's declared axes, in declaration order. + + Subclasses declare their axes as nested :class:`Axis` subclasses. Role + cardinalities are checked when the family is declared. + """ + + __registry_key__ = "family_name" + __skip_if_no_key__ = True + + family_name: ClassVar[str | None] = None + axes: ClassVar[tuple[type[Axis], ...]] = () + + _active: ClassVar[type[AxisFamily] | None] = None + + @classmethod + def _validate_declaration(cls) -> None: + if "_validate_declaration" in cls.__dict__: + return # the declaring base itself + declared = tuple(value for value in cls.__dict__.values() if is_axis(value)) + + if not declared: + raise TypeError(f"Axis family {cls.__qualname__} declares no axes.") + names = [axis.name for axis in declared] + if Ungrouped.name in names: + raise TypeError( + f"Axis family {cls.__qualname__} may not name an axis " + f"{Ungrouped.name!r}; that spelling belongs to Ungrouped." + ) + duplicates = sorted({name for name in names if names.count(name) > 1}) + if duplicates: + raise TypeError( + f"Axis family {cls.__qualname__} declares duplicate names {duplicates}." + ) + for role in _declared_roles(declared): + count = sum(1 for axis in declared if issubclass(axis, role)) + if not role.cardinality.admits(count): + raise TypeError( + f"Axis family {cls.__qualname__} gives {role.__name__} to " + f"{count} axes; the role admits {role.cardinality.describe()}." + ) + partition_count = sum(1 for axis in declared if issubclass(axis, PartitionAxis)) + if not PartitionAxis.cardinality.admits(partition_count): + raise TypeError( + f"Axis family {cls.__qualname__} must declare exactly one PartitionAxis." + ) + for axis in declared: + if "family" in axis.__dict__: + raise TypeError(f"Axis {axis.__qualname__} already belongs to a family.") + axis.family = cls + cls.axes = declared + cls.family_name = f"{cls.__module__}:{cls.__qualname__}" + + + def __new__(cls, *args: object, **kwargs: object): + raise TypeError(f"{cls.__qualname__} is a family declaration, not a value type.") + + # -- activation --------------------------------------------------------- + + @classmethod + def activate(cls) -> None: + """Make this family the process's active family.""" + + if cls is AxisFamily: + raise TypeError("Activate a declared family, not the AxisFamily base.") + AxisFamily._active = cls + + @staticmethod + def active() -> type[AxisFamily]: + """Return the process's active family.""" + + family = AxisFamily._active + if family is None: + raise AxisFamilyNotActive( + "No axis family is active; the domain entry point must call " + ".activate() before the kernel is used." + ) + return family + + # -- queries ------------------------------------------------------------ + + @classmethod + def with_role(cls, role: type[AxisRole]) -> tuple[type[Axis], ...]: + """Axes carrying ``role``, in declaration order.""" + + return tuple(axis for axis in cls.axes if issubclass(axis, role)) + + @classmethod + def one(cls, role: type[AxisRole]) -> type[Axis]: + """The single axis carrying ``role``; fails unless exactly one does.""" + + matches = cls.with_role(role) + if len(matches) != 1: + raise LookupError( + f"Axis family {cls.__qualname__} has {len(matches)} axes with " + f"role {role.__name__}; exactly one is required here." + ) + return matches[0] + + @classmethod + def partition_axis(cls) -> type[Axis]: + """The parallel axis.""" + + return cls.one(PartitionAxis) + + @classmethod + def variable_axes(cls) -> tuple[type[Axis], ...]: + """Axes a step may assemble, group or sequence along (all but the partition).""" + + return tuple(axis for axis in cls.axes if not issubclass(axis, PartitionAxis)) + + @classmethod + def default_variable(cls) -> tuple[type[Axis], ...]: + return cls.with_role(DefaultVariable) + + @classmethod + def default_group_by(cls) -> type[GroupingDeclaration]: + grouping = cls.with_role(DefaultGroupBy) + return grouping[0] if grouping else Ungrouped + + @classmethod + def grouping_choices(cls) -> tuple[type[GroupingDeclaration], ...]: + """Every value a step's ``group_by`` may hold.""" + + return (*cls.variable_axes(), Ungrouped) + + @classmethod + def names(cls) -> tuple[str, ...]: + """Boundary names in declaration order.""" + + return tuple(axis.name for axis in cls.axes) + + @classmethod + def grouping_named(cls, name: str) -> type[GroupingDeclaration]: + """Decode one boundary ``group_by`` spelling (an axis name or ``"none"``).""" + + if name == Ungrouped.name: + return Ungrouped + return cls.named(name) + + @classmethod + def named(cls, name: str) -> type[Axis]: + """Decode one boundary name.""" + + for axis in cls.axes: + if axis.name == name: + return axis + raise ValueError( + f"{name!r} is not an axis of {cls.__qualname__}; " + f"declared axes are {cls.names()}." + ) + + @classmethod + def contains(cls, axis: object) -> bool: + return is_axis(axis) and axis in cls.axes + + @classmethod + def require(cls, axis: object) -> type[Axis]: + """Return ``axis`` if it is declared by this family.""" + + if not cls.contains(axis): + raise TypeError( + f"{axis!r} is not an axis of {cls.__qualname__}; " + f"declared axes are {cls.names()}." + ) + return axis # type: ignore[return-value] + + @classmethod + def index(cls, axis: type[Axis]) -> int: + """Declaration position of ``axis``.""" + + return cls.axes.index(cls.require(axis)) + + +# --------------------------------------------------------------------------- +# Strategy families keyed by role +# --------------------------------------------------------------------------- + + +class AxisRoleKeyedStrategyMixin: + """Strategy family whose leaves each implement one axis role. + + The class that lists this mixin directly among its bases is the family + root. Each leaf declares ``implements_role``; an axis selects the one leaf + whose role it carries. + """ + + implements_role: ClassVar[type[AxisRole]] + _role_strategies: ClassVar[dict[type[AxisRole], type]] + + def __init_subclass__(cls, **kwargs: object) -> None: + super().__init_subclass__(**kwargs) + if AxisRoleKeyedStrategyMixin in cls.__bases__: + cls._role_strategies = {} + return + role = cls.__dict__.get("implements_role") + if role is None: + return + existing = cls._role_strategies.get(role) + if existing is not None: + raise TypeError( + f"{cls.__qualname__} and {existing.__qualname__} both implement " + f"{role.__name__}." + ) + cls._role_strategies[role] = cls + + @classmethod + def role_strategy_types(cls) -> tuple[type, ...]: + return tuple(cls._role_strategies.values()) + + @classmethod + def strategy_type_for_axis(cls, axis: type[Axis]) -> type: + matches = tuple( + strategy + for role, strategy in cls._role_strategies.items() + if issubclass(axis, role) + ) + if len(matches) != 1: + raise LookupError( + f"{cls.__qualname__} needs exactly one strategy for {axis!r}; " + f"found {[strategy.__qualname__ for strategy in matches]}." + ) + return matches[0] + + @classmethod + def for_axis(cls, axis: type[Axis]): + return cls.strategy_type_for_axis(axis)() + + +def _declared_roles(axes: tuple[type[Axis], ...]) -> tuple[type[AxisRole], ...]: + roles: list[type[AxisRole]] = [] + for axis in axes: + for base in axis.__mro__: + if ( + isinstance(base, type) + and issubclass(base, AxisRole) + and base is not AxisRole + and base not in roles + ): + roles.append(base) + return tuple(roles) + + +__all__ = [ + "AtMostOne", + "Axis", + "AxisDeclarationMeta", + "AxisFamily", + "AxisFamilyNotActive", + "AxisRole", + "AxisRoleKeyedStrategyMixin", + "AxisValueKind", + "Cardinality", + "ColourAxis", + "DefaultGroupBy", + "DefaultVariable", + "ExactlyOne", + "GroupingDeclaration", + "LabelValued", + "Many", + "OrdinalValued", + "PartitionAxis", + "StackAxis", + "TileAxis", + "TimeAxis", + "Ungrouped", + "is_axis", + "is_grouping_declaration", +] diff --git a/openhcs/core/axis_boundaries.py b/openhcs/core/axis_boundaries.py new file mode 100644 index 0000000000..5027f4dfb4 --- /dev/null +++ b/openhcs/core/axis_boundaries.py @@ -0,0 +1,50 @@ +"""Form choice sets for fields that hold axes. + +Kept out of :mod:`openhcs.core.axes` so that declaring and activating a family +(done by the product entry point in every process) stays free of the +annotation library. JSON spells a declaration by its registry key, its name. +""" + +from __future__ import annotations + +from python_introspect import AnnotationChoices + +from openhcs.core.axes import AxisFamily + + +class _AxisDeclarationChoices(AnnotationChoices): + def label(self, choice: object) -> str: + return choice.name # type: ignore[attr-defined] + + def __eq__(self, other: object) -> bool: + return type(self) is type(other) + + def __hash__(self) -> int: + return hash(type(self)) + + def __repr__(self) -> str: + return f"{type(self).__name__}()" + + +class AxisChoices(_AxisDeclarationChoices): + """A field holding any axis of the active family.""" + + def choices(self) -> tuple[object, ...]: + return AxisFamily.active().axes + + +class VariableAxisChoices(_AxisDeclarationChoices): + """A field holding variable axes of the active family.""" + + def choices(self) -> tuple[object, ...]: + return AxisFamily.active().variable_axes() + + +class GroupingChoices(_AxisDeclarationChoices): + """A field holding a grouping declaration of the active family.""" + + def choices(self) -> tuple[object, ...]: + return AxisFamily.active().grouping_choices() + + +__all__ = ["AxisChoices", "GroupingChoices", "VariableAxisChoices"] diff --git a/openhcs/core/callable_contract.py b/openhcs/core/callable_contract.py index e8b33d1df3..a437eaea5c 100644 --- a/openhcs/core/callable_contract.py +++ b/openhcs/core/callable_contract.py @@ -40,7 +40,6 @@ validate_annotation_value, ) -from openhcs.constants.constants import GroupBy, VariableComponents from openhcs.core.image_payload_execution_mode import ( ImagePayloadExecutionMode, ) @@ -61,6 +60,7 @@ VariableComponentStackRequirement, ) from metaclass_registry.caches import IdentityBoundProcessCache +from openhcs.core.axes import AxisRole if TYPE_CHECKING: from openhcs.core.aligned_image_payload import ( @@ -384,11 +384,11 @@ class CallableMetadata: artifact_input_parameter_names: tuple[str, ...] = () artifact_outputs: tuple[ArtifactSpec, ...] = () runtime_bound_parameters: tuple[type[RuntimeParameterDeclarationABC], ...] = () - required_variable_components: tuple[VariableComponents, ...] = () + required_axis_roles: tuple[type[AxisRole], ...] = () variable_component_stack_requirement: VariableComponentStackRequirement | None = ( None ) - allowed_group_by: tuple[GroupBy, ...] = () + allowed_group_by_roles: tuple[type[AxisRole], ...] = () runtime_adapter: RuntimeAdapterSpec | None = None runtime_context_parameter: str | None = None execution_scope: FunctionStepExecutionScope = FunctionStepExecutionScope.AXIS @@ -680,16 +680,16 @@ def from_projection( runtime_bound_parameters=reader.optional_runtime_parameter_type_tuple( FunctionContractAttribute.runtime_bound_parameters, ), - required_variable_components=reader.optional_variable_component_tuple( - FunctionContractAttribute.required_variable_components, + required_axis_roles=reader.optional_axis_role_tuple( + FunctionContractAttribute.required_axis_roles, ), variable_component_stack_requirement=( reader.optional_variable_component_stack_requirement( FunctionContractAttribute.variable_component_stack_requirement ) ), - allowed_group_by=reader.optional_group_by_tuple( - FunctionContractAttribute.allowed_group_by, + allowed_group_by_roles=reader.optional_axis_role_tuple( + FunctionContractAttribute.allowed_group_by_roles, ), runtime_adapter=runtime_adapter, runtime_context_parameter=_runtime_context_parameter(reader, signature), @@ -779,17 +779,17 @@ def as_namespace(self) -> dict[str, object]: namespace[FunctionContractAttribute.runtime_bound_parameters] = ( self.runtime_bound_parameters ) - if self.required_variable_components: - namespace[FunctionContractAttribute.required_variable_components] = ( - self.required_variable_components + if self.required_axis_roles: + namespace[FunctionContractAttribute.required_axis_roles] = ( + self.required_axis_roles ) if self.variable_component_stack_requirement is not None: namespace[ FunctionContractAttribute.variable_component_stack_requirement ] = self.variable_component_stack_requirement - if self.allowed_group_by: - namespace[FunctionContractAttribute.allowed_group_by] = ( - self.allowed_group_by + if self.allowed_group_by_roles: + namespace[FunctionContractAttribute.allowed_group_by_roles] = ( + self.allowed_group_by_roles ) if self.runtime_adapter is not None: namespace[FunctionContractAttribute.runtime_adapter] = self.runtime_adapter @@ -1359,9 +1359,9 @@ def resolve_declared_paths( return resolved @property - def required_variable_components(self) -> tuple[VariableComponents, ...]: - """Declared FunctionStep variable axes required by this callable.""" - return self.metadata.required_variable_components + def required_axis_roles(self) -> tuple[type[AxisRole], ...]: + """Axis roles the step's variable axes must cover for this callable.""" + return self.metadata.required_axis_roles @property def variable_component_stack_requirement( @@ -1381,9 +1381,9 @@ def variable_component_stack_requirement( return processing_contract.variable_component_stack_requirement @property - def allowed_group_by(self) -> tuple[GroupBy, ...]: - """Declared FunctionStep group_by values allowed by this callable.""" - return self.metadata.allowed_group_by + def allowed_group_by_roles(self) -> tuple[type[AxisRole], ...]: + """Axis roles this callable's step may group by (empty: any).""" + return self.metadata.allowed_group_by_roles @property def processing_contract(self) -> Enum | None: @@ -2450,33 +2450,26 @@ def optional_runtime_parameter_type_tuple( boundary=f"{self.function_name!r}.{field_name}", ) - def optional_variable_component_tuple( + def optional_axis_role_tuple( self, field_name: str, - ) -> tuple[VariableComponents, ...]: - """Return optional required FunctionStep variable-component metadata.""" + ) -> tuple[type[AxisRole], ...]: + """Return an optional tuple of declared axis roles.""" value = self.namespace.get(field_name) if value is None: return () - if not isinstance(value, tuple): + if not isinstance(value, tuple) or not all( + isinstance(role, type) and issubclass(role, AxisRole) for role in value + ): raise TypeError( - f"{self.function_name!r}.{field_name} must be a tuple, " - f"got {type(value).__name__}." + f"{self.function_name!r}.{field_name} must be a tuple of axis " + f"roles, got {value!r}." ) - normalized = tuple( - ( - component - if isinstance(component, VariableComponents) - else VariableComponents(component) - ) - for component in value - ) - if len(normalized) != len(set(normalized)): + if len(value) != len(set(value)): raise TypeError( - f"{self.function_name!r}.{field_name} must contain unique " - "VariableComponents values." + f"{self.function_name!r}.{field_name} must contain unique roles." ) - return normalized + return value def optional_variable_component_stack_requirement( self, @@ -2494,29 +2487,6 @@ def optional_variable_component_stack_requirement( ) return value - def optional_group_by_tuple( - self, - field_name: str, - ) -> tuple[GroupBy, ...]: - """Return optional allowed FunctionStep group_by metadata.""" - value = self.namespace.get(field_name) - if value is None: - return () - if not isinstance(value, tuple): - raise TypeError( - f"{self.function_name!r}.{field_name} must be a tuple, " - f"got {type(value).__name__}." - ) - normalized = tuple( - group_by if isinstance(group_by, GroupBy) else GroupBy(group_by) - for group_by in value - ) - if len(normalized) != len(set(normalized)): - raise TypeError( - f"{self.function_name!r}.{field_name} must contain unique " - "GroupBy values." - ) - return normalized def optional_execution_mode( self, diff --git a/openhcs/core/compiled_step_plan.py b/openhcs/core/compiled_step_plan.py index 795c05cb9d..cdc92b594c 100644 --- a/openhcs/core/compiled_step_plan.py +++ b/openhcs/core/compiled_step_plan.py @@ -10,13 +10,7 @@ from polystore.streaming.identity import StreamProducerIdentity -from openhcs.constants.constants import ( - Backend, - GPU_MEMORY_TYPES, - MemoryType, - SequentialComponents, - VariableComponents, -) +from openhcs.constants.constants import Backend, GPU_MEMORY_TYPES, MemoryType from openhcs.core.artifacts import ( ArtifactInputPlan, ArtifactOutputPlan, @@ -34,6 +28,7 @@ CompiledSourceUniversePlan, ) from openhcs.core.step_dependencies import StepInputDependency +from openhcs.core.axes import Axis if TYPE_CHECKING: from openhcs.core.aligned_image_payload import AlignedImageSliceContext @@ -201,12 +196,12 @@ class MaterializedOutputPlan: class SequentialRuntimeFilter: """One compile-resolved sequential component constraint.""" - component: SequentialComponents + component: type[Axis] value: str @property def component_name(self) -> str: - return self.component.value + return self.component.name @dataclass(frozen=True, slots=True) @@ -274,7 +269,7 @@ class CompiledStepPlan: analysis_results_dir: str | None = None pipeline_position: int | None = None input_source: Any = None - variable_components: Sequence[VariableComponents] | None = None + variable_components: Sequence[type[Axis]] | None = None group_by: Any = None sequential_processing: Any = None sequential_filter_plan: SequentialRuntimeFilterPlan = field( @@ -484,7 +479,7 @@ def require_function_execution_ready(self) -> "CompiledStepPlan": ) return self - def require_variable_components(self) -> Sequence[VariableComponents]: + def require_variable_components(self) -> Sequence[type[Axis]]: variable_components = self.variable_components if variable_components is None: raise ValueError( @@ -557,18 +552,11 @@ def memory_device_scope( return self.device_assignment.scope_for(declaration) - @property - def variable_component_values(self) -> list[str]: - return [component.value for component in self.require_variable_components()] - - @property - def group_by_value(self) -> str | None: - return self.group_by.value if self.group_by else None @property def execution_group_value(self) -> str | None: component = self.execution_group_scope.component - return None if component is None else component.value + return None if component is None else component.name @property def artifact_output_plate_root(self) -> str: diff --git a/openhcs/core/component_group_scope.py b/openhcs/core/component_group_scope.py index 42331e6062..6f89f38105 100644 --- a/openhcs/core/component_group_scope.py +++ b/openhcs/core/component_group_scope.py @@ -4,17 +4,15 @@ from collections.abc import Hashable, Iterable, Mapping, Sequence from dataclasses import dataclass -from enum import Enum from typing import TYPE_CHECKING -from openhcs.constants.constants import AllComponents from openhcs.core.component_set import ComponentSet from openhcs.core.source_metadata import ( SourceMetadataFields, SourceMetadataMapping, SourceMetadataScalar, - SourceMetadataValue, ) +from openhcs.core.axes import Axis, AxisFamily, PartitionAxis, is_axis if TYPE_CHECKING: from openhcs.core.context.processing_context import ProcessingContext @@ -25,7 +23,7 @@ ) ComponentGroupKey = str | None -RuntimeFixedComponentValues = tuple[tuple[AllComponents, str], ...] +RuntimeFixedComponentValues = tuple[tuple[type[Axis], str], ...] @dataclass(frozen=True, slots=True) @@ -33,7 +31,7 @@ class ComponentGroupScope: """One validated ungrouped, static, or runtime-discovered component scope.""" keys: tuple[ComponentGroupKey, ...] - component: AllComponents | None = None + component: type[Axis] | None = None def __post_init__(self) -> None: if not self.keys: @@ -47,13 +45,8 @@ def __post_init__(self) -> None: "ComponentGroupScope may use None only as the sole dynamic or " "ungrouped key." ) - if self.component is not None and not isinstance( - self.component, - AllComponents, - ): - raise TypeError( - "ComponentGroupScope.component must be an AllComponents value." - ) + if self.component is not None and not is_axis(self.component): + raise TypeError("ComponentGroupScope.component must be a declared axis.") if self.component is None and self.keys != (None,): raise ValueError( "Concrete component-group keys require a component identity." @@ -66,7 +59,7 @@ def ungrouped(cls) -> "ComponentGroupScope": @classmethod def dynamic( cls, - component: AllComponents, + component: type[Axis], ) -> "ComponentGroupScope": """Declare a typed scope whose concrete keys are discovered at runtime.""" @@ -77,12 +70,12 @@ def from_raw( cls, group_keys: Iterable[Hashable | None], *, - component: AllComponents | Enum | str | None = None, + component: type[Axis] | None = None, ) -> "ComponentGroupScope": return cls( tuple(cls.normalize_key(group_key) for group_key in group_keys), component=( - None if component is None else ComponentSet.coerce_component(component) + None if component is None else AxisFamily.active().require(component) ), ) @@ -123,7 +116,7 @@ def runtime_keys( ) if not keys: raise ValueError( - f"Dynamic {self.component.value} execution scope requires " + f"Dynamic {self.component.name} execution scope requires " "component-grouped runtime patterns." ) return keys @@ -163,14 +156,14 @@ def resolve_runtime_key( if self.is_dynamic: if normalized_key is None: raise ValueError( - f"Dynamic {self.component.value} component scope requires a " + f"Dynamic {self.component.name} component scope requires a " "concrete runtime key." ) return normalized_key if normalized_key in self.keys: return normalized_key raise ValueError( - f"Component scope {self.component.value!r} groups {self.keys!r} do not " + f"Component scope {self.component.name!r} groups {self.keys!r} do not " f"contain runtime key {normalized_key!r}." ) @@ -211,8 +204,8 @@ def output_lineage_scope( if consumer_scope.is_ungrouped or self.component is consumer_scope.component: return self raise ValueError( - f"Output lineage component {self.component.value!r} is neither the " - f"consumer group component {consumer_scope.component.value!r} nor one " + f"Output lineage component {self.component.name!r} is neither the " + f"consumer group component {consumer_scope.component.name!r} nor one " "of its variable components." ) @@ -222,7 +215,7 @@ class RuntimeExecutionAxisScope: """Typed runtime axis coordinate for component projection.""" axis_id: str - component: AllComponents | None = None + component: type[Axis] | None = None value: SourceMetadataScalar = None fixed_component_values: RuntimeFixedComponentValues = () @@ -231,7 +224,7 @@ def from_context( cls, context: "ProcessingContext", *, - component: AllComponents | str | None = None, + component: type[Axis] | str | None = None, value: SourceMetadataScalar = None, ) -> "RuntimeExecutionAxisScope": axis_id = context.axis_id @@ -250,16 +243,16 @@ def from_raw( cls, axis_id: str, *, - component: AllComponents | Enum | str | None, + component: type[Axis] | None, value: SourceMetadataScalar, fixed_component_values: Iterable[ - tuple[AllComponents | Enum | str, SourceMetadataScalar] + tuple[type[Axis], SourceMetadataScalar] ] = (), ) -> "RuntimeExecutionAxisScope": if not axis_id: raise ValueError("RuntimeExecutionAxisScope.axis_id cannot be empty.") resolved_component = ( - None if component is None else ComponentSet.coerce_component(component) + None if component is None else AxisFamily.active().require(component) ) canonical_value = None if value is None else str(value) canonical_fixed_values = cls._canonical_fixed_component_values( @@ -276,9 +269,9 @@ def from_raw( def __post_init__(self) -> None: if not self.axis_id: raise ValueError("RuntimeExecutionAxisScope.axis_id cannot be empty.") - if self.component is not None and not isinstance(self.component, AllComponents): + if self.component is not None and not is_axis(self.component): raise TypeError( - "RuntimeExecutionAxisScope.component must be an AllComponents value. " + "RuntimeExecutionAxisScope.component must be a declared axis. " "Use RuntimeExecutionAxisScope.from_raw() for coercion." ) if (self.component is None) != (self.value is None): @@ -305,17 +298,17 @@ def __post_init__(self) -> None: @staticmethod def _canonical_fixed_component_values( fixed_component_values: Iterable[ - tuple[AllComponents | Enum | str, SourceMetadataScalar] + tuple[type[Axis], SourceMetadataScalar] ], *, - group_component: AllComponents | None, + group_component: type[Axis] | None, ) -> RuntimeFixedComponentValues: """Validate and order fixed coordinates before scope construction.""" - normalized_fixed_values: dict[AllComponents, str] = {} + normalized_fixed_values: dict[type[Axis], str] = {} for component, value in fixed_component_values: - resolved_component = ComponentSet.coerce_component(component) - if resolved_component.is_multiprocessing_axis(): + resolved_component = AxisFamily.active().require(component) + if issubclass(resolved_component, PartitionAxis): raise ValueError( "RuntimeExecutionAxisScope fixed components cannot repeat the " "multiprocessing axis." @@ -327,7 +320,7 @@ def _canonical_fixed_component_values( if resolved_component in normalized_fixed_values: raise ValueError( "RuntimeExecutionAxisScope fixed components cannot contain " - f"duplicate {resolved_component.value!r} identity." + f"duplicate {resolved_component.name!r} identity." ) normalized_fixed_values[resolved_component] = str(value) if group_component in normalized_fixed_values: @@ -337,7 +330,7 @@ def _canonical_fixed_component_values( ) return tuple( (component, normalized_fixed_values[component]) - for component in AllComponents + for component in AxisFamily.active().axes if component in normalized_fixed_values ) @@ -345,7 +338,7 @@ def _canonical_fixed_component_values( def component_name(self) -> str | None: if self.component is None: return None - return str(self.component.value) + return str(self.component.name) def require_component_name(self) -> str: component_name = self.component_name @@ -367,14 +360,14 @@ def require_value_text(self) -> str: def value_text_for_component( self, - component: AllComponents | Enum | str | None, + component: type[Axis] | None, ) -> str | None: """Return this runtime scope's value for one component axis.""" if component is None: return None - resolved_component = ComponentSet.coerce_component(component) - if resolved_component.is_multiprocessing_axis(): + resolved_component = AxisFamily.active().require(component) + if issubclass(resolved_component, PartitionAxis): return self.axis_id if self.component == resolved_component: return self.value_text @@ -424,8 +417,8 @@ def join_execution_cohort( def source_component_values(self) -> RuntimeFixedComponentValues: """Return every typed source coordinate represented by this scope.""" - values: list[tuple[AllComponents, str]] = [] - for component in AllComponents: + values: list[tuple[type[Axis], str]] = [] + for component in AxisFamily.active().axes: value = self.value_text_for_component(component) if value is not None: values.append((component, value)) @@ -437,8 +430,8 @@ def presentation_component_values(self) -> RuntimeFixedComponentValues: values = self.source_component_values return ( - *(item for item in values if item[0].is_multiprocessing_axis()), - *(item for item in values if not item[0].is_multiprocessing_axis()), + *(item for item in values if issubclass(item[0], PartitionAxis)), + *(item for item in values if not issubclass(item[0], PartitionAxis)), ) @property @@ -446,19 +439,19 @@ def coordinate_label(self) -> str: """Return a stable user-facing label without enum representations.""" return " / ".join( - f"{component.value}={value}" + f"{component.name}={value}" for component, value in self.presentation_component_values ) def for_group_coordinate( self, - component: AllComponents | Enum | str | None, + component: type[Axis] | None, value: SourceMetadataScalar, ) -> "RuntimeExecutionAxisScope": """Project this execution identity onto one artifact group coordinate.""" resolved_component = ( - None if component is None else ComponentSet.coerce_component(component) + None if component is None else AxisFamily.active().require(component) ) if (resolved_component is None) != (value is None): raise ValueError( @@ -471,7 +464,7 @@ def for_group_coordinate( if existing is not None and existing != self.require_value_text(): raise ValueError( "Runtime execution group conflicts with its fixed component " - f"identity for {self.component.value!r}." + f"identity for {self.component.name!r}." ) fixed_values[self.component] = self.require_value_text() if resolved_component is not None: @@ -479,7 +472,7 @@ def for_group_coordinate( if existing is not None and existing != resolved_value: raise ValueError( "Artifact group coordinate conflicts with fixed runtime identity " - f"for {resolved_component.value!r}: {existing!r} != " + f"for {resolved_component.name!r}: {existing!r} != " f"{resolved_value!r}." ) if ( @@ -488,7 +481,7 @@ def for_group_coordinate( ): raise ValueError( "Artifact group coordinate conflicts with runtime execution group " - f"for {resolved_component.value!r}: {self.value_text!r} != " + f"for {resolved_component.name!r}: {self.value_text!r} != " f"{resolved_value!r}." ) return type(self).from_raw( @@ -524,7 +517,7 @@ def source_component_metadata( if existing is not None and str(existing) != value: raise ValueError( "Runtime execution scope conflicts with source component metadata " - f"for {component.value!r}: {existing!r} != {value!r}." + f"for {component.name!r}: {existing!r} != {value!r}." ) merged = with_source_component_metadata(merged, component, value) return merged @@ -546,24 +539,23 @@ def group_scope(self) -> ComponentGroupScope: @property def cache_key(self) -> tuple[tuple[str, str], ...]: return tuple( - (component.value, value) + (component.name, value) for component, value in self.source_component_values - if not component.is_multiprocessing_axis() + if not issubclass(component, PartitionAxis) ) def source_axis_metadata_scope(self) -> "SourceAxisMetadataScope": """Return metadata constraints for this runtime axis.""" - from openhcs.constants.constants import get_multiprocessing_axis from openhcs.core.source_matching import SourceAxisMetadataScope component_values = tuple( - (component.value, value) + (component.name, value) for component, value in self.source_component_values ) - multiprocessing_component = get_multiprocessing_axis() + multiprocessing_component = AxisFamily.active().partition_axis() if not any( - component_name == multiprocessing_component.value + component_name == multiprocessing_component.name for component_name, _value in component_values ): raise RuntimeError( @@ -583,7 +575,7 @@ def source_image_set_identity( return SourceImageSetIdentity( tuple( - (component.value, value) + (component.name, value) for component, value in self.source_component_values if component in components if policy.is_identity_component(component) diff --git a/openhcs/core/component_set.py b/openhcs/core/component_set.py index c7fb095986..25fc759e7a 100644 --- a/openhcs/core/component_set.py +++ b/openhcs/core/component_set.py @@ -1,42 +1,38 @@ -"""Nominal component-set operations for dynamic OpenHCS component enums.""" +"""Ordered unique sets of declared axes.""" from __future__ import annotations from collections.abc import Iterable, Iterator from dataclasses import dataclass -from enum import Enum -from openhcs.constants.constants import ( - AllComponents, - VariableComponents, - get_default_group_by, - get_default_variable_components, -) -from openhcs.core.components.validation import convert_enum_by_value +from openhcs.core.axes import Axis, AxisFamily, PartitionAxis, is_axis @dataclass(slots=True) class ComponentSet: - """Ordered unique set of ``AllComponents`` with enum-aware operations.""" + """Ordered unique set of declared axes.""" - components: tuple[AllComponents, ...] = () + components: tuple[type[Axis], ...] = () def __post_init__(self) -> None: - normalized: list[AllComponents] = [] + normalized: list[type[Axis]] = [] for component in self.components: - if not isinstance(component, AllComponents): + if not is_axis(component): raise TypeError( - "ComponentSet components must be AllComponents values, " - f"got {type(component).__name__}." + f"ComponentSet components must be declared axes, got {component!r}." ) if component not in normalized: normalized.append(component) self.components = tuple(normalized) + @classmethod + def of(cls, components: Iterable[type[Axis]]) -> "ComponentSet": + return cls(tuple(components)) + @classmethod def collect( cls, - *groups: Iterable[AllComponents | None], + *groups: Iterable[type[Axis] | None], ) -> "ComponentSet": return cls( tuple( @@ -47,54 +43,24 @@ def collect( ) ) - @classmethod - def from_enum_values( - cls, - values: Iterable[Enum], - ) -> "ComponentSet": - return cls(tuple(AllComponents(value.value) for value in values)) - - @classmethod - def coerce( - cls, - values: Iterable[AllComponents | Enum | str], - ) -> "ComponentSet": - return cls(tuple(cls.coerce_component(value) for value in values)) - - @staticmethod - def coerce_component(value: AllComponents | Enum | str) -> AllComponents: - if isinstance(value, AllComponents): - return value - if isinstance(value, Enum): - converted = convert_enum_by_value(value, AllComponents) - if converted is None: - raise ValueError( - f"Component enum {value!r} is not an OpenHCS component." - ) - return converted - return AllComponents(value) - @classmethod def default_variable(cls) -> "ComponentSet": - return cls.from_enum_values(get_default_variable_components()) + return cls(AxisFamily.active().default_variable()) @classmethod def default_group_by(cls) -> "ComponentSet": - group_by = get_default_group_by() - if group_by is None or group_by.value is None: - return cls() - return cls.from_enum_values((group_by,)) + return cls(AxisFamily.active().default_group_by().grouping_axes()) def __bool__(self) -> bool: return bool(self.components) - def __contains__(self, component: AllComponents) -> bool: + def __contains__(self, component: type[Axis]) -> bool: return component in self.components - def __iter__(self) -> Iterator[AllComponents]: + def __iter__(self) -> Iterator[type[Axis]]: return iter(self.components) - def as_tuple(self) -> tuple[AllComponents, ...]: + def as_tuple(self) -> tuple[type[Axis], ...]: return self.components def variable(self) -> "ComponentSet": @@ -102,7 +68,7 @@ def variable(self) -> "ComponentSet": tuple( component for component in self.components - if component.name in VariableComponents.__members__ + if not issubclass(component, PartitionAxis) ) ) @@ -121,19 +87,19 @@ def intersection(self, other: "ComponentSet") -> "ComponentSet": tuple(component for component in self.components if component in other) ) - def required_last(self, error_message: str) -> AllComponents: + def required_last(self, error_message: str) -> type[Axis]: if not self.components: raise ValueError(error_message) return self.components[-1] - def single_or_none(self, multiple_error_message: str) -> AllComponents | None: + def single_or_none(self, multiple_error_message: str) -> type[Axis] | None: if not self.components: return None if len(self.components) == 1: return self.components[0] raise ValueError(multiple_error_message) - def last(self) -> AllComponents | None: + def last(self) -> type[Axis] | None: if not self.components: return None return self.components[-1] diff --git a/openhcs/core/components/component_values.py b/openhcs/core/components/component_values.py index 2e8a09c259..3af9f5c10f 100644 --- a/openhcs/core/components/component_values.py +++ b/openhcs/core/components/component_values.py @@ -1,160 +1,139 @@ -"""Nominal value sets keyed by the canonical OpenHCS component declaration.""" +"""Complete value sets over the active axis family.""" from __future__ import annotations from collections.abc import Iterable, Iterator, Mapping -from enum import Enum from types import MappingProxyType from typing import Generic, TypeVar -from openhcs.constants.constants import AllComponents +from openhcs.core.axes import Axis, AxisFamily, is_axis ComponentValueT = TypeVar("ComponentValueT") -class OpenHCSComponentValues( - Mapping[AllComponents, ComponentValueT], +class AxisValues( + Mapping[type[Axis], ComponentValueT], Generic[ComponentValueT], ): - """Complete immutable values owned by the canonical OpenHCS axes.""" + """Complete immutable values, one per axis of the active family.""" __slots__ = ("_declared_values",) def __init__( self, - component_values: Iterable[tuple[AllComponents, ComponentValueT]], + component_values: Iterable[tuple[type[Axis], ComponentValueT]], ) -> None: + family = AxisFamily.active() supplied_values = tuple(component_values) - if any( - not isinstance(component, AllComponents) for component, _ in supplied_values - ): - raise TypeError("Component values require exact AllComponents members") - - values_by_component = dict(supplied_values) - if len(values_by_component) != len(supplied_values): - raise ValueError("Each OpenHCS component may be bound only once") - - missing = tuple( - component - for component in AllComponents - if component not in values_by_component - ) + if any(not family.contains(axis) for axis, _ in supplied_values): + raise TypeError( + f"Axis values require axes of {family.__qualname__}; got " + f"{[axis for axis, _ in supplied_values if not family.contains(axis)]}" + ) + + values_by_axis = dict(supplied_values) + if len(values_by_axis) != len(supplied_values): + raise ValueError("Each axis may be bound only once") + + missing = tuple(axis for axis in family.axes if axis not in values_by_axis) if missing: raise ValueError( - "Component values must bind the canonical declaration exactly: " - + ", ".join(f"missing {component.value}" for component in missing) + "Axis values must bind the active family exactly: " + + ", ".join(f"missing {axis.name}" for axis in missing) ) self._declared_values = tuple( - (component, values_by_component[component]) for component in AllComponents + (axis, values_by_axis[axis]) for axis in family.axes ) @classmethod - def from_member_projection( + def from_partial( cls, - source_values: Iterable[tuple[Enum, ComponentValueT]], - ) -> "OpenHCSComponentValues[ComponentValueT]": - """Project another nominal enum by matching its declared member names.""" - - projected_by_name: dict[str, ComponentValueT] = {} - for component, value in source_values: - if not isinstance(component, Enum): - raise TypeError("Projected components must be nominal enum members") - if component.name in projected_by_name: - raise ValueError( - f"Projected component {component.name!r} was bound more than once" - ) - projected_by_name[component.name] = value - - missing = tuple( - component.name - for component in AllComponents - if component.name not in projected_by_name - ) - if missing: - raise ValueError( - "Component projection lacks declared members: " + ", ".join(missing) - ) + component_values: Iterable[tuple[type[Axis], ComponentValueT]], + *, + missing_value: ComponentValueT, + ) -> "AxisValues[ComponentValueT]": + """Complete a partial binding with one explicit absent value.""" + + supplied_values = tuple(component_values) + values_by_axis = dict(supplied_values) + if len(values_by_axis) != len(supplied_values): + raise ValueError("Each axis may be bound only once") + family = AxisFamily.active() + for axis in values_by_axis: + family.require(axis) return cls( - (component, projected_by_name[component.name]) - for component in AllComponents + (axis, values_by_axis.get(axis, missing_value)) for axis in family.axes ) @classmethod - def from_partial( + def from_wire_mapping( cls, - component_values: Iterable[tuple[AllComponents, ComponentValueT]], + component_values: Mapping[str, ComponentValueT], *, missing_value: ComponentValueT, - ) -> "OpenHCSComponentValues[ComponentValueT]": - """Complete a partial nominal binding with one explicit absent value.""" + ) -> "AxisValues[ComponentValueT]": + """Read each declared axis's boundary name from ``component_values``.""" - supplied_values = tuple(component_values) - if any( - not isinstance(component, AllComponents) for component, _ in supplied_values - ): - raise TypeError("Component values require exact AllComponents members") - values_by_component = dict(supplied_values) - if len(values_by_component) != len(supplied_values): - raise ValueError("Each OpenHCS component may be bound only once") + family = AxisFamily.active() return cls( - ( - component, - values_by_component.get(component, missing_value), - ) - for component in AllComponents + (axis, component_values.get(axis.name, missing_value)) + for axis in family.axes ) def declared_values( self, - ) -> tuple[tuple[AllComponents, ComponentValueT], ...]: - """Return values in canonical declaration order.""" + ) -> tuple[tuple[type[Axis], ComponentValueT], ...]: + """Return values in declaration order.""" return self._declared_values - def __getitem__(self, component: AllComponents) -> ComponentValueT: + def __getitem__(self, component: type[Axis]) -> ComponentValueT: return self.value_for(component) - def __iter__(self) -> Iterator[AllComponents]: - return (component for component, _ in self._declared_values) + def __iter__(self) -> Iterator[type[Axis]]: + return (axis for axis, _ in self._declared_values) def __len__(self) -> int: return len(self._declared_values) - def value_for(self, component: AllComponents) -> ComponentValueT: - """Return the value for one exact canonical component.""" + def value_for(self, component: type[Axis]) -> ComponentValueT: + """Return the value for one declared axis.""" - if not isinstance(component, AllComponents): - raise TypeError("Component lookup requires an exact AllComponents member") - for declared_component, value in self._declared_values: - if declared_component is component: + if not is_axis(component): + raise TypeError(f"Axis lookup requires a declared axis; got {component!r}") + for declared_axis, value in self._declared_values: + if declared_axis is component: return value raise KeyError(component) def with_value( self, - component: AllComponents, + component: type[Axis], value: ComponentValueT, - ) -> "OpenHCSComponentValues[ComponentValueT]": - """Return a value set with one canonical component replaced.""" + ) -> "AxisValues[ComponentValueT]": + """Return a value set with one axis replaced.""" self.value_for(component) return type(self)( ( - declared_component, - value if declared_component is component else current_value, + declared_axis, + value if declared_axis is component else current_value, ) - for declared_component, current_value in self._declared_values + for declared_axis, current_value in self._declared_values ) def wire_mapping(self) -> Mapping[str, ComponentValueT]: """Serialize values at an explicit string-keyed boundary.""" return MappingProxyType( - {component.value: value for component, value in self._declared_values} + {axis.name: value for axis, value in self._declared_values} ) def __eq__(self, other: object) -> bool: - if not isinstance(other, OpenHCSComponentValues): + if not isinstance(other, AxisValues): return NotImplemented return self._declared_values == other._declared_values + + def __hash__(self) -> int: + return hash(self._declared_values) diff --git a/openhcs/core/components/framework.py b/openhcs/core/components/framework.py deleted file mode 100644 index 70ded83cfe..0000000000 --- a/openhcs/core/components/framework.py +++ /dev/null @@ -1,182 +0,0 @@ -""" -Core framework for generic component configuration. - -This module provides the foundational classes for configuring any enum as components -with configurable multiprocessing axis and validation constraints. -""" - -from dataclasses import dataclass -from typing import Generic, TypeVar, List, Optional, Type -from enum import Enum - -T = TypeVar("T", bound=Enum) -_auto_default_group_by = object() - - -@dataclass(frozen=True) -class ComponentConfiguration(Generic[T]): - """ - Generic configuration for any enum-based component system. - - This class encapsulates the configuration for a component system where: - - Components are defined by an enum - - One component serves as the multiprocessing axis - - Default variable components and group_by are specified - - Generic constraint validation is enforced: group_by ∉ variable_components - """ - - all_components: tuple[T, ...] - multiprocessing_axis: T - default_variable: List[T] - default_group_by: Optional[T] - - def __post_init__(self): - """Validate configuration constraints.""" - # Ensure multiprocessing_axis is in all_components - if self.multiprocessing_axis not in self.all_components: - raise ValueError( - f"multiprocessing_axis {self.multiprocessing_axis.value} " - f"must be in all_components" - ) - - # Ensure default_variable components are in all_components - for component in self.default_variable: - if component not in self.all_components: - raise ValueError( - f"default_variable component {component.value} " - f"must be in all_components" - ) - - # Ensure default_group_by is in all_components (if specified) - if self.default_group_by and self.default_group_by not in self.all_components: - raise ValueError( - f"default_group_by {self.default_group_by.value} " - f"must be in all_components" - ) - - # Validate default combination - self.validate_combination(self.default_variable, self.default_group_by) - - def validate_combination(self, variable: List[T], group_by: Optional[T]) -> None: - """ - Validate that group_by is not in variable_components. - - This enforces the core constraint: group_by ∉ variable_components - - Args: - variable: List of variable components - group_by: Optional group_by component - - Raises: - ValueError: If group_by is in variable_components - """ - if group_by and group_by in variable: - raise ValueError( - f"group_by {group_by.value} cannot be in variable_components " - f"{[v.value for v in variable]}" - ) - - def get_remaining_components(self) -> tuple[T, ...]: - """ - Get components available for variable_components and group_by selection. - - Returns all components except the multiprocessing_axis. - - Returns: - Components available for variable/group_by selection in declaration order - """ - return tuple( - component - for component in self.all_components - if component is not self.multiprocessing_axis - ) - - -class ComponentConfigurationFactory: - """Factory for creating ComponentConfiguration instances.""" - - @staticmethod - def create_configuration( - component_enum: Type[T], - multiprocessing_axis: T, - default_variable: Optional[List[T]] = None, - default_group_by: Optional[T] | object = _auto_default_group_by, - ) -> ComponentConfiguration[T]: - """ - Create a ComponentConfiguration for the given enum with dynamic component resolution. - - When multiprocessing_axis is specified, the remaining components are automatically - available for variable_components and group_by selection. - - Args: - component_enum: The enum class defining all components - multiprocessing_axis: Component to use for multiprocessing - default_variable: Default variable components (auto-resolved if None) - default_group_by: Default group_by component. Omit to auto-resolve; - pass None for an explicit no-fanout default. - - Returns: - ComponentConfiguration instance - """ - all_components = tuple(component_enum) - - # Dynamic resolution: remaining components = all_components - multiprocessing_axis - remaining_components = tuple( - component - for component in all_components - if component is not multiprocessing_axis - ) - - # Auto-resolve default_variable if not specified - if default_variable is None: - # Use the first remaining component as default variable - default_variable = [remaining_components[0]] if remaining_components else [] - - # Auto-resolve default_group_by if not specified - if default_group_by is _auto_default_group_by and len(remaining_components) > 1: - # Use the second remaining component as default group_by (if available) - # Ensure group_by is not in default_variable - for component in remaining_components: - if component not in default_variable: - default_group_by = component - break - - return ComponentConfiguration( - all_components=all_components, - multiprocessing_axis=multiprocessing_axis, - default_variable=default_variable, - default_group_by=( - default_group_by - if default_group_by is not _auto_default_group_by - else None - ), - ) - - @staticmethod - def create_openhcs_default_configuration(): - """ - Create the default OpenHCS configuration. - - This defines the current OpenHCS setup: - - Well as multiprocessing axis - - Site as default variable component - - Channel as default group_by component - """ - # Import here to avoid circular import with constants.py - from enum import Enum - - # CRITICAL: Use a different name to avoid conflicts with the real VariableComponents - # enum created in constants.py. This is just a template for creating the configuration. - class _ComponentTemplate(Enum): - SITE = "site" - CHANNEL = "channel" - Z_INDEX = "z_index" - TIMEPOINT = "timepoint" - WELL = "well" - - return ComponentConfigurationFactory.create_configuration( - _ComponentTemplate, - multiprocessing_axis=_ComponentTemplate.WELL, - default_variable=[_ComponentTemplate.SITE], - default_group_by=_ComponentTemplate.CHANNEL, - ) diff --git a/openhcs/core/components/parser_metaprogramming.py b/openhcs/core/components/parser_metaprogramming.py index 5f85e3928d..7a98b80e94 100644 --- a/openhcs/core/components/parser_metaprogramming.py +++ b/openhcs/core/components/parser_metaprogramming.py @@ -1,16 +1,15 @@ -"""Filename parsing bound to the canonical OpenHCS component declaration.""" +"""Filename parsing bound to the active axis family.""" import logging from abc import ABC, abstractmethod from collections.abc import Iterable, Mapping from dataclasses import dataclass -from enum import Enum from typing import Optional, Tuple, TypeAlias from polystore.streaming.viewer_transport import ViewerFilenameParseResultABC -from openhcs.constants.constants import AllComponents -from openhcs.core.components.component_values import OpenHCSComponentValues +from openhcs.core.axes import Axis, AxisFamily +from openhcs.core.components.component_values import AxisValues logger = logging.getLogger(__name__) @@ -19,14 +18,14 @@ @dataclass(frozen=True, slots=True, init=False) class FilenameParseResult(ViewerFilenameParseResultABC): - """Immutable parser result keyed by nominal component declarations.""" + """Immutable parser result keyed by declared axes.""" - components: OpenHCSComponentValues[FilenameParseValue] + components: AxisValues[FilenameParseValue] extension: str def __init__( self, - component_values: Iterable[tuple[AllComponents, FilenameParseValue]], + component_values: Iterable[tuple[type[Axis], FilenameParseValue]], *, extension: str, ) -> None: @@ -36,27 +35,13 @@ def __init__( if not normalized_extension.startswith("."): normalized_extension = f".{normalized_extension}" - object.__setattr__(self, "components", OpenHCSComponentValues(component_values)) + object.__setattr__(self, "components", AxisValues(component_values)) object.__setattr__(self, "extension", normalized_extension) - @classmethod - def from_projection( - cls, - source_values: Iterable[tuple[Enum, FilenameParseValue]], - *, - extension: str, - ) -> "FilenameParseResult": - """Project one nominal component enum onto another by declared member name.""" - - return cls.from_components( - OpenHCSComponentValues.from_member_projection(source_values), - extension=extension, - ) - @classmethod def from_components( cls, - components: OpenHCSComponentValues[FilenameParseValue], + components: AxisValues[FilenameParseValue], *, extension: str, ) -> "FilenameParseResult": @@ -73,29 +58,26 @@ def from_wire_mapping( ) -> "FilenameParseResult": """Create a nominal result at an explicit keyword or wire boundary.""" - return cls( - ( - (component, component_values.get(component.value)) - for component in AllComponents - ), + return cls.from_components( + AxisValues.from_wire_mapping(component_values, missing_value=None), extension=extension, ) def declared_values( self, - ) -> tuple[tuple[AllComponents, FilenameParseValue], ...]: + ) -> tuple[tuple[type[Axis], FilenameParseValue], ...]: """Return parsed values in declaration order.""" return self.components.declared_values() - def value_for(self, component: AllComponents) -> FilenameParseValue: + def value_for(self, component: type[Axis]) -> FilenameParseValue: """Return the value owned by one exact component declaration.""" return self.components.value_for(component) def with_value( self, - component: AllComponents, + component: type[Axis], value: FilenameParseValue, ) -> "FilenameParseResult": """Return a result with one nominal component value replaced.""" @@ -107,16 +89,16 @@ def with_value( def with_values( self, - replacements: Iterable[tuple[AllComponents, FilenameParseValue]], + replacements: Iterable[tuple[type[Axis], FilenameParseValue]], ) -> "FilenameParseResult": """Return a result with nominally declared component replacements.""" components = self.components - seen: set[AllComponents] = set() + seen: set[type[Axis]] = set() for component, value in replacements: if component in seen: raise ValueError( - f"Filename component {component.value!r} was replaced more than once" + f"Filename component {component.name!r} was replaced more than once" ) seen.add(component) components = components.with_value(component, value) @@ -124,7 +106,7 @@ def with_values( def component_matches( self, - component: AllComponents, + component: type[Axis], expected_value: object, ) -> bool: """Compare one parsed component through its nominal declaration.""" @@ -134,12 +116,12 @@ def component_matches( return parsed_value is expected_value return str(parsed_value) == str(expected_value) - def required_value(self, component: AllComponents) -> str | int | float | bool: + def required_value(self, component: type[Axis]) -> str | int | float | bool: """Return one required component or fail with its declared identity.""" value = self.value_for(component) if value is None or value == "": - raise MissingFilenameComponentError(component.value, empty=True) + raise MissingFilenameComponentError(component.name, empty=True) return value def wire_mapping(self) -> Mapping[str, FilenameParseValue]: @@ -178,7 +160,7 @@ class GenericFilenameParser(ABC): DEFAULT_EXTENSION = ".tif" def __init__(self) -> None: - self.FILENAME_COMPONENTS = tuple(AllComponents) + self.FILENAME_COMPONENTS = AxisFamily.active().axes self.PLACEHOLDER_PATTERN = "{iii}" @classmethod @@ -218,10 +200,10 @@ def construct_acquisition_filename( """ return self.construct_filename(components) - def component_for_name(self, component_name: str) -> AllComponents: - """Resolve one external component name through the declared enum.""" + def component_for_name(self, component_name: str) -> type[Axis]: + """Decode one external axis name through the active family.""" - return AllComponents(component_name) + return AxisFamily.active().named(component_name) def bind_component_values( self, @@ -238,7 +220,7 @@ def bind_component_values( def bind_declared_values( self, - component_values: Iterable[tuple[AllComponents, FilenameParseValue]], + component_values: Iterable[tuple[type[Axis], FilenameParseValue]], *, extension: str | None = None, ) -> FilenameParseResult: diff --git a/openhcs/core/components/validation.py b/openhcs/core/components/validation.py index 62ef36dbf7..262d5f7443 100644 --- a/openhcs/core/components/validation.py +++ b/openhcs/core/components/validation.py @@ -6,45 +6,13 @@ """ import logging -from typing import Generic, TypeVar, List, Optional, Dict, Any, Union, Type -from enum import Enum from dataclasses import dataclass +from typing import Any, Dict, List, Optional, Sequence -from openhcs.core.components.framework import ComponentConfiguration -from openhcs.constants.constants import GroupBy +from openhcs.core.axes import Axis, AxisFamily, GroupingDeclaration logger = logging.getLogger(__name__) -T = TypeVar("T", bound=Enum) -U = TypeVar("U", bound=Enum) - - -def convert_enum_by_value(source_enum: T, target_enum_class: Type[U]) -> Optional[U]: - """ - Generic utility to convert between enum types with matching .value attributes. - - This function enables conversion between any two enum classes that have - overlapping values, without requiring hardcoded mappings. - - Args: - source_enum: Source enum instance to convert from - target_enum_class: Target enum class to convert to - - Returns: - Target enum instance with matching value, or None if no match found - - Example: - >>> convert_enum_by_value(VariableComponents.CHANNEL, GroupBy) - - """ - source_value = source_enum.value - - for target_enum in target_enum_class: - if target_enum.value == source_value: - return target_enum - - return None - @dataclass class ValidationResult: @@ -55,95 +23,77 @@ class ValidationResult: warnings: Optional[List[str]] = None -class GenericValidator(Generic[T]): - """ - Generic validator for component-agnostic validation. +class GenericValidator: + """Step validation over an axis family's declared constraints.""" - This class replaces the hardcoded component-specific validation logic - with a configurable system that works with any component configuration. - """ - - def __init__(self, config: ComponentConfiguration[T]): - """ - Initialize the validator with a component configuration. - - Args: - config: ComponentConfiguration for validation rules - """ - self.config = config - if logger.isEnabledFor(logging.DEBUG): - logger.debug( - "GenericValidator initialized for components: %s", - [c.value for c in config.all_components], - ) + def __init__(self, family: type[AxisFamily]): + self.family = family def validate_step( self, - variable_components: List[T], - group_by: Optional[Union[T, "GroupBy"]], + variable_components: Sequence[type[Axis]], + group_by: type[GroupingDeclaration] | None, is_grouped: bool, step_name: str, ) -> ValidationResult: - """ - Validate a step configuration using generic rules. + """Validate one step's variable axes and grouping against the family. Args: - variable_components: List of variable components - group_by: Optional group_by component + variable_components: Axes the step assembles along + group_by: The step's grouping declaration is_grouped: Whether the admitted function pattern dispatches by group step_name: Name of the step for error reporting - - Returns: - ValidationResult indicating success or failure """ - try: - # 1. Validate component combination - self.config.validate_combination(variable_components, group_by) + grouping_axes = () if group_by is None else group_by.grouping_axes() + overlap = [axis for axis in grouping_axes if axis in variable_components] + if overlap: + return ValidationResult( + is_valid=False, + error_message=( + f"group_by {overlap[0].name} cannot be in variable_components " + f"{[axis.name for axis in variable_components]}" + ), + ) + + if is_grouped and not grouping_axes: + return ValidationResult( + is_valid=False, + error_message=( + f"Dict pattern requires a concrete group_by axis in " + f"step '{step_name}'. variable_components declares the " + "3D stack axis; dict keys declare dispatch groups and " + "cannot use Ungrouped." + ), + ) - # 2. Validate dict pattern requirements - if is_grouped and (group_by is None or group_by.value is None): + variable_axes = self.family.variable_axes() + partition_name = self.family.partition_axis().name + for axis in variable_components: + if axis not in variable_axes: return ValidationResult( is_valid=False, error_message=( - f"Dict pattern requires a concrete group_by component in " - f"step '{step_name}'. variable_components declares the " - "3D stack axis; dict keys declare dispatch groups and " - "cannot use GroupBy.NONE." + f"Variable component {axis.name} not available " + f"(multiprocessing axis: {partition_name})" ), ) - # 3. Validate components are in remaining components (not multiprocessing axis) - remaining_components = self.config.get_remaining_components() - remaining_values = {comp.value for comp in remaining_components} - - for component in variable_components: - if component.value not in remaining_values: - return ValidationResult( - is_valid=False, - error_message=f"Variable component {component.value} not available (multiprocessing axis: {self.config.multiprocessing_axis.value})", - ) - - # Check group_by is valid if it's not None - # Note: group_by can be an enum with .value = None, so check the value explicitly - if ( - group_by is not None - and group_by.value is not None - and group_by.value not in remaining_values - ): + for axis in grouping_axes: + if axis not in variable_axes: return ValidationResult( is_valid=False, - error_message=f"Group_by component {group_by.value} not available (multiprocessing axis: {self.config.multiprocessing_axis.value})", + error_message=( + f"Group_by component {axis.name} not available " + f"(multiprocessing axis: {partition_name})" + ), ) - return ValidationResult(is_valid=True) - - except ValueError as e: - return ValidationResult(is_valid=False, error_message=str(e)) + return ValidationResult(is_valid=True) def validate_dict_pattern_keys( self, func_pattern: Dict[str, Any], - group_by: T, + group_by: type[Axis], step_name: str, orchestrator, *, @@ -157,7 +107,7 @@ def validate_dict_pattern_keys( Args: func_pattern: Dict function pattern to validate - group_by: GroupBy component specifying component type + group_by: Axis whose values key the dict pattern step_name: Name of the step containing the function orchestrator: Orchestrator for component key access resolved_config: Held compilation configuration, or live saved configuration. @@ -168,7 +118,7 @@ def validate_dict_pattern_keys( from openhcs.core.function_patterns import NormalizedFunctionPattern try: - # Use enum objects directly - orchestrator now accepts VariableComponents + # The orchestrator decodes the grouping axis itself available_keys = orchestrator.get_component_keys( group_by, resolved_config=resolved_config ) @@ -205,7 +155,7 @@ def validate_dict_pattern_keys( is_valid=False, error_message=( f"Function pattern keys {sorted(missing_numeric)} not found in available " - f"{group_by.value} components {sorted(available_numeric)} for step '{step_name}'" + f"{group_by.name} components {sorted(available_numeric)} for step '{step_name}'" ), ) except (ValueError, TypeError): @@ -214,7 +164,7 @@ def validate_dict_pattern_keys( is_valid=False, error_message=( f"Function pattern keys {sorted(missing_keys)} not found in available " - f"{group_by.value} components {sorted(available_keys_set)} for step '{step_name}'" + f"{group_by.name} components {sorted(available_keys_set)} for step '{step_name}'" ), ) @@ -223,5 +173,5 @@ def validate_dict_pattern_keys( except Exception as e: return ValidationResult( is_valid=False, - error_message=f"Failed to validate dict pattern keys for {group_by.value}: {e}", + error_message=f"Failed to validate dict pattern keys for {group_by.name}: {e}", ) diff --git a/openhcs/core/config.py b/openhcs/core/config.py index da05b257c5..45d4156b6f 100644 --- a/openhcs/core/config.py +++ b/openhcs/core/config.py @@ -9,24 +9,26 @@ import logging import inspect from collections.abc import Mapping -from dataclasses import dataclass, field +from dataclasses import dataclass, field, fields from pathlib import Path from typing import Optional, Union, List, Annotated, ClassVar, Callable from enum import Enum from abc import ABC, abstractmethod from arraybridge.decorators import DtypeConversion, DtypeConversionConfig from polystore import config as _polystore_config -from openhcs.constants import ( - AllComponents, - Microscope, - SequentialComponents, - VariableComponents, - GroupBy, -) -from openhcs.constants.constants import ( - Backend, - get_default_variable_components, - get_default_group_by, +from openhcs.constants import Microscope +from openhcs.constants.constants import Backend +from openhcs.core.axis_boundaries import GroupingChoices, VariableAxisChoices +from openhcs.core.axes import ( + Axis, + AxisFamily, + AxisRole, + ColourAxis, + GroupingDeclaration, + PartitionAxis, + StackAxis, + TileAxis, + TimeAxis, ) from metaclass_registry import AutoRegisterMeta from openhcs.constants.input_source import InputSource @@ -237,6 +239,73 @@ class GlobalPipelineConfig(AnnotatedDataclassValidationMixin): # (GlobalPipelineConfig → PipelineConfig by removing "Global" prefix) +class AxisRoleModeDisplayConfig: + """Viewer display config whose mode fields are declared per axis role. + + Each mode field names its role in ``metadata["axis_role"]``. An axis takes + the mode of the first mode field whose role it carries, so the wire + projection covers whichever family is active. + """ + + @classmethod + def role_mode_fields(cls) -> tuple[tuple[type[AxisRole], str], ...]: + return tuple( + (declared.metadata["axis_role"], declared.name) + for declared in fields(cls) + if "axis_role" in declared.metadata + ) + + @property + def COMPONENT_ORDER(self) -> tuple[str, ...]: + return AxisFamily.active().names() + + @classmethod + def mode_field_for_axis(cls, axis: type[Axis]) -> str: + for role, field_name in cls.role_mode_fields(): + if issubclass(axis, role): + return field_name + raise TypeError( + f"Axis {axis!r} carries none of the viewer roles of {cls.__name__}: " + f"{[role.__name__ for role, _ in cls.role_mode_fields()]}." + ) + + def component_modes(self) -> dict[str, str]: + """Project role mode fields onto the active family's axis names.""" + + return { + axis.name: getattr(self, self.mode_field_for_axis(axis)).value + for axis in AxisFamily.active().axes + } + + @classmethod + def role_modes_from_wire( + cls, + component_modes: Mapping[str, ViewerWireValue], + mode_type: type[Enum], + viewer_label: str, + ) -> dict[str, Enum]: + """Decode wire modes by axis name back onto the role mode fields.""" + + if not isinstance(component_modes, Mapping): + raise TypeError(f"{viewer_label} component_modes must be a mapping.") + family = AxisFamily.active() + if set(component_modes) != set(family.names()): + raise ValueError( + f"{viewer_label} component_modes must exactly match " + f"{family.names()!r}; got {tuple(component_modes)!r}." + ) + modes_by_field: dict[str, Enum] = {} + for axis in family.axes: + field_name = cls.mode_field_for_axis(axis) + mode = mode_type(str(component_modes[axis.name])) + if modes_by_field.setdefault(field_name, mode) is not mode: + raise ValueError( + f"{viewer_label} axes sharing {field_name} must share one mode; " + f"{axis.name} has {mode.value}." + ) + return modes_by_field + + class NapariDimensionMode(Enum): """How component values are placed in Napari image layers.""" @@ -255,12 +324,11 @@ class NapariVariableSizeHandling(Enum): @dataclass(frozen=True) class NapariDisplayConfig( + AxisRoleModeDisplayConfig, ViewerDisplayConfigABC, AnnotatedDataclassValidationMixin, ): - """Map streamed OpenHCS dimensions and intensity data onto Napari layers.""" - - COMPONENT_ORDER: ClassVar[tuple[str, ...]] = AllComponents.ordered_names() + """Map streamed axes and intensity data onto Napari layers.""" colormap: NonBlankString = field( default="gray", @@ -282,50 +350,52 @@ class NapariDisplayConfig( ) }, ) - site_mode: NapariDimensionMode = field( + partition_mode: NapariDimensionMode = field( default=NapariDimensionMode.STACK, metadata={ - "description": "Whether site values are stacked or use separate layers." + "axis_role": PartitionAxis, + "description": ( + "Whether parallel-axis values are stacked or use separate layers." + ), }, ) - channel_mode: NapariDimensionMode = field( + tile_mode: NapariDimensionMode = field( default=NapariDimensionMode.STACK, metadata={ - "description": "Whether channel values are stacked or use separate layers." + "axis_role": TileAxis, + "description": ( + "Whether tile-axis values are stacked or use separate layers." + ), }, ) - z_index_mode: NapariDimensionMode = field( + colour_mode: NapariDimensionMode = field( default=NapariDimensionMode.STACK, metadata={ - "description": "Whether z-index values are stacked or use separate layers." + "axis_role": ColourAxis, + "description": ( + "Whether colour-axis values are stacked or use separate layers." + ), }, ) - timepoint_mode: NapariDimensionMode = field( + stack_mode: NapariDimensionMode = field( default=NapariDimensionMode.STACK, metadata={ + "axis_role": StackAxis, "description": ( - "Whether timepoint values are stacked or use separate layers." - ) + "Whether stack-axis values are stacked or use separate layers." + ), }, ) - well_mode: NapariDimensionMode = field( + time_mode: NapariDimensionMode = field( default=NapariDimensionMode.STACK, metadata={ - "description": "Whether well values are stacked or use separate layers." + "axis_role": TimeAxis, + "description": ( + "Whether time-axis values are stacked or use separate layers." + ), }, ) - def component_modes(self) -> dict[str, str]: - """Project typed component fields onto the viewer wire vocabulary.""" - - return { - AllComponents.SITE.value: self.site_mode.value, - AllComponents.CHANNEL.value: self.channel_mode.value, - AllComponents.Z_INDEX.value: self.z_index_mode.value, - AllComponents.TIMEPOINT.value: self.timepoint_mode.value, - AllComponents.WELL.value: self.well_mode.value, - } - def display_payload_extra(self) -> dict[str, str]: """Project Napari-specific display settings onto the wire payload.""" @@ -347,14 +417,11 @@ def from_display_payload( from polystore.napari_stream import NapariDisplayWireField - component_modes = payload[ViewerDisplayConfigWireField.COMPONENT_MODES.value] - if not isinstance(component_modes, Mapping): - raise TypeError("Napari component_modes must be a mapping.") - if set(component_modes) != set(cls.COMPONENT_ORDER): - raise ValueError( - "Napari component_modes must exactly match " - f"{cls.COMPONENT_ORDER!r}; got {tuple(component_modes)!r}." - ) + role_modes = cls.role_modes_from_wire( + payload[ViewerDisplayConfigWireField.COMPONENT_MODES.value], + NapariDimensionMode, + "Napari", + ) colormap = str(payload[NapariDisplayWireField.COLORMAP.value]).strip() if not colormap: raise ValueError("Napari colormap name must not be blank.") @@ -363,21 +430,7 @@ def from_display_payload( variable_size_handling=NapariVariableSizeHandling( str(payload[NapariDisplayWireField.VARIABLE_SIZE_HANDLING.value]) ), - site_mode=NapariDimensionMode( - str(component_modes[AllComponents.SITE.value]) - ), - channel_mode=NapariDimensionMode( - str(component_modes[AllComponents.CHANNEL.value]) - ), - z_index_mode=NapariDimensionMode( - str(component_modes[AllComponents.Z_INDEX.value]) - ), - timepoint_mode=NapariDimensionMode( - str(component_modes[AllComponents.TIMEPOINT.value]) - ), - well_mode=NapariDimensionMode( - str(component_modes[AllComponents.WELL.value]) - ), + **role_modes, ) @@ -396,7 +449,7 @@ class FijiDimensionMode(Enum): How to map OpenHCS dimensions to ImageJ hyperstack dimensions. ImageJ hyperstacks have 3 dimensions: Channels (C), Slices (Z), Frames (T). - Each OpenHCS component (site, channel, z_index, timepoint) can be mapped to one of these. + Each axis role (tile, colour, stack, time, partition) maps to one of these. - WINDOW: Create separate windows for each value (like Napari LAYER mode) - CHANNEL: Map to ImageJ Channel dimension (C) @@ -412,12 +465,11 @@ class FijiDimensionMode(Enum): @dataclass(frozen=True) class FijiDisplayConfig( + AxisRoleModeDisplayConfig, ViewerDisplayConfigABC, AnnotatedDataclassValidationMixin, ): - """Map streamed OpenHCS dimensions and intensity data onto Fiji hyperstacks.""" - - COMPONENT_ORDER: ClassVar[tuple[str, ...]] = AllComponents.ordered_names() + """Map streamed axes and intensity data onto Fiji hyperstacks.""" lut: NonBlankString = field( default="Grays", @@ -436,58 +488,52 @@ class FijiDisplayConfig( ) }, ) - site_mode: FijiDimensionMode = field( + partition_mode: FijiDimensionMode = field( default=FijiDimensionMode.FRAME, metadata={ + "axis_role": PartitionAxis, "description": ( - "ImageJ dimension used for site values, or WINDOW for separate windows." - ) + "ImageJ dimension used for parallel-axis values, or WINDOW for separate windows." + ), }, ) - channel_mode: FijiDimensionMode = field( - default=FijiDimensionMode.CHANNEL, + tile_mode: FijiDimensionMode = field( + default=FijiDimensionMode.FRAME, metadata={ + "axis_role": TileAxis, "description": ( - "ImageJ dimension used for channel values, or WINDOW for separate windows." - ) + "ImageJ dimension used for tile-axis values, or WINDOW for separate windows." + ), }, ) - z_index_mode: FijiDimensionMode = field( - default=FijiDimensionMode.SLICE, + colour_mode: FijiDimensionMode = field( + default=FijiDimensionMode.CHANNEL, metadata={ + "axis_role": ColourAxis, "description": ( - "ImageJ dimension used for z-index values, or WINDOW for separate windows." - ) + "ImageJ dimension used for colour-axis values, or WINDOW for separate windows." + ), }, ) - timepoint_mode: FijiDimensionMode = field( - default=FijiDimensionMode.FRAME, + stack_mode: FijiDimensionMode = field( + default=FijiDimensionMode.SLICE, metadata={ + "axis_role": StackAxis, "description": ( - "ImageJ dimension used for timepoint values, or WINDOW for separate windows." - ) + "ImageJ dimension used for stack-axis values, or WINDOW for separate windows." + ), }, ) - well_mode: FijiDimensionMode = field( + time_mode: FijiDimensionMode = field( default=FijiDimensionMode.FRAME, metadata={ + "axis_role": TimeAxis, "description": ( - "ImageJ dimension used for well values, or WINDOW for separate windows." - ) + "ImageJ dimension used for time-axis values, or WINDOW for separate windows." + ), }, ) - def component_modes(self) -> dict[str, str]: - """Project typed component fields onto the viewer wire vocabulary.""" - - return { - AllComponents.SITE.value: self.site_mode.value, - AllComponents.CHANNEL.value: self.channel_mode.value, - AllComponents.Z_INDEX.value: self.z_index_mode.value, - AllComponents.TIMEPOINT.value: self.timepoint_mode.value, - AllComponents.WELL.value: self.well_mode.value, - } - def display_payload_extra(self) -> dict[str, str | bool]: """Project Fiji-specific display settings onto the wire payload.""" @@ -507,14 +553,11 @@ def from_display_payload( from polystore.fiji_stream import FijiDisplayWireField - component_modes = payload[ViewerDisplayConfigWireField.COMPONENT_MODES.value] - if not isinstance(component_modes, Mapping): - raise TypeError("Fiji component_modes must be a mapping.") - if set(component_modes) != set(cls.COMPONENT_ORDER): - raise ValueError( - "Fiji component_modes must exactly match " - f"{cls.COMPONENT_ORDER!r}; got {tuple(component_modes)!r}." - ) + role_modes = cls.role_modes_from_wire( + payload[ViewerDisplayConfigWireField.COMPONENT_MODES.value], + FijiDimensionMode, + "Fiji", + ) lut = str(payload[FijiDisplayWireField.LUT.value]).strip() if not lut: raise ValueError("Fiji LUT name must not be blank.") @@ -524,21 +567,7 @@ def from_display_payload( "Fiji auto_contrast must be bool, " f"got {type(auto_contrast).__name__}." ) - return cls( - lut=lut, - auto_contrast=auto_contrast, - site_mode=FijiDimensionMode(str(component_modes[AllComponents.SITE.value])), - channel_mode=FijiDimensionMode( - str(component_modes[AllComponents.CHANNEL.value]) - ), - z_index_mode=FijiDimensionMode( - str(component_modes[AllComponents.Z_INDEX.value]) - ), - timepoint_mode=FijiDimensionMode( - str(component_modes[AllComponents.TIMEPOINT.value]) - ), - well_mode=FijiDimensionMode(str(component_modes[AllComponents.WELL.value])), - ) + return cls(lut=lut, auto_contrast=auto_contrast, **role_modes) # Apply the global pipeline config decorator with ui_hidden=True @@ -699,18 +728,18 @@ def annotation_type(cls) -> type["DtypeConfig"]: class ProcessingConfig(AnnotatedDataclassValidationMixin): """Independent stack-axis, post-assembly grouping, and main-flow choices.""" - variable_components: Annotated[List[VariableComponents], abbreviation("vars")] = ( - field(default_factory=get_default_variable_components) - ) + variable_components: Annotated[ + List[type[Axis]], abbreviation("vars"), VariableAxisChoices() + ] = field(default_factory=lambda: list(AxisFamily.active().default_variable())) """Components whose values vary along the assembled array axis. This field is the stack-axis meaning authority. It is independent of ``group_by`` and of whether the callable executes per plane or per stack. """ - group_by: Annotated[Optional[GroupBy], abbreviation("group")] = field( - default_factory=get_default_group_by - ) + group_by: Annotated[ + Optional[type[GroupingDeclaration]], abbreviation("group"), GroupingChoices() + ] = field(default_factory=lambda: AxisFamily.active().default_group_by()) """Component used to partition already assembled values. A dictionary function pattern uses the resulting group identity for branch @@ -757,7 +786,7 @@ class SequentialProcessingConfig(AnnotatedDataclassValidationMixin): """ sequential_components: Annotated[ - List[SequentialComponents], abbreviation("seq_comp") + List[type[Axis]], abbreviation("seq_comp"), VariableAxisChoices() ] = field(default_factory=list) """Plate components whose value combinations run through the whole pipeline in turn. diff --git a/openhcs/core/debug_view_models.py b/openhcs/core/debug_view_models.py index 0827b72323..e5fb3ddc46 100644 --- a/openhcs/core/debug_view_models.py +++ b/openhcs/core/debug_view_models.py @@ -18,6 +18,7 @@ from typing import ClassVar, Mapping from metaclass_registry import AutoRegisterMeta +from openhcs.core.axes import is_grouping_declaration class DebugViewTableProjection(Enum): @@ -431,6 +432,8 @@ def debug_view_jsonable(value: object) -> object: return value if isinstance(value, Enum): return value.value + if is_grouping_declaration(value): + return value.name if isinstance(value, tuple): return [debug_view_jsonable(item) for item in value] if isinstance(value, list): diff --git a/openhcs/core/debug_views.py b/openhcs/core/debug_views.py index 911de491eb..af8ea0ee31 100644 --- a/openhcs/core/debug_views.py +++ b/openhcs/core/debug_views.py @@ -32,6 +32,7 @@ RuntimeValueStore, StoredRuntimeValue, ) +from openhcs.core.axes import is_grouping_declaration def dataclass_record_columns(record_type: type) -> tuple[str, ...]: @@ -260,6 +261,8 @@ def _debug_table_jsonable(value: object) -> object: return value if isinstance(value, Enum): return value.value + if is_grouping_declaration(value): + return value.name if isinstance(value, type) and issubclass(value, ArtifactType): return value.require_value() if isinstance(value, tuple): diff --git a/openhcs/core/function_contract_metadata.py b/openhcs/core/function_contract_metadata.py index 09713a46ce..315ae4301d 100644 --- a/openhcs/core/function_contract_metadata.py +++ b/openhcs/core/function_contract_metadata.py @@ -30,13 +30,11 @@ class FunctionContractAttribute: ) runtime_bound_parameters: ClassVar[str] = "__openhcs_runtime_bound_parameters__" runtime_context_parameter: ClassVar[str] = "__openhcs_runtime_context_parameter__" - required_variable_components: ClassVar[str] = ( - "__openhcs_required_variable_components__" - ) + required_axis_roles: ClassVar[str] = "__openhcs_required_axis_roles__" variable_component_stack_requirement: ClassVar[str] = ( "__openhcs_variable_component_stack_requirement__" ) - allowed_group_by: ClassVar[str] = "__openhcs_allowed_group_by__" + allowed_group_by_roles: ClassVar[str] = "__openhcs_allowed_group_by_roles__" object_label_input_execution_mode: ClassVar[str] = ( "__object_label_input_execution_mode__" ) diff --git a/openhcs/core/invocation_artifacts.py b/openhcs/core/invocation_artifacts.py index dc0e860c23..ed41d66a08 100644 --- a/openhcs/core/invocation_artifacts.py +++ b/openhcs/core/invocation_artifacts.py @@ -9,7 +9,6 @@ from metaclass_registry import AutoRegisterMeta -from openhcs.constants.constants import GroupBy from openhcs.constants.input_source import InputSource from openhcs.core.artifact_key_selection import ArtifactPlanKeySelector from openhcs.core.artifacts import ( @@ -20,6 +19,7 @@ ) from openhcs.core.config import StepSourceBindingsConfig from openhcs.core.source_bindings import EMPTY_SOURCE_BINDINGS +from openhcs.core.axes import GroupingDeclaration, Ungrouped, is_grouping_declaration _ClaimValue = TypeVar("_ClaimValue") @@ -68,7 +68,7 @@ class ArtifactDeclarationStepContext: step_name: str | None = None step_index: int | None = None source_bindings: StepSourceBindingsConfig = EMPTY_SOURCE_BINDINGS - group_by: GroupBy = GroupBy.NONE + group_by: type[GroupingDeclaration] = Ungrouped input_source: InputSource = InputSource.PREVIOUS_STEP available_artifacts: ArtifactSpecCollection = field( default_factory=lambda: ArtifactSpecCollection(()) @@ -99,10 +99,11 @@ def __post_init__(self) -> None: "ArtifactDeclarationStepContext.source_bindings must be " f"StepSourceBindingsConfig, got {type(self.source_bindings).__name__}." ) - if not isinstance(self.group_by, GroupBy): + if not is_grouping_declaration(self.group_by): raise TypeError( - "ArtifactDeclarationStepContext.group_by must be GroupBy, got " - f"{type(self.group_by).__name__}." + "ArtifactDeclarationStepContext.group_by must be an axis or " + f"Ungrouped, got {self.group_by!r}." + ) if not isinstance(self.input_source, InputSource): raise TypeError( @@ -216,7 +217,7 @@ def with_source_binding_scope( self, *, source_bindings: StepSourceBindingsConfig, - group_by: GroupBy, + group_by: type[GroupingDeclaration], input_source: InputSource, source_groups: tuple[str | None, ...] = (), ) -> "ArtifactDeclarationStepContext": diff --git a/openhcs/core/measurement_row_materialization.py b/openhcs/core/measurement_row_materialization.py index ec1b8e5cbc..3349071547 100644 --- a/openhcs/core/measurement_row_materialization.py +++ b/openhcs/core/measurement_row_materialization.py @@ -19,7 +19,6 @@ from typing import Any, ClassVar, TYPE_CHECKING, TypeAlias, cast from metaclass_registry import AutoRegisterMeta -from openhcs.constants.constants import AllComponents from openhcs.core.alias_property import AliasProperty import numpy as np @@ -49,6 +48,7 @@ from openhcs.core.source_matching import source_component_metadata_value from enum import Enum +from openhcs.core.axes import AxisFamily @lru_cache(maxsize=32768) @@ -2401,7 +2401,7 @@ def metadata_for_row(row_index: int): return source_provenance.component_metadata_for_plane(slice_index) metadata_by_row = tuple(metadata_for_row(index) for index in range(row_count)) - for component in AllComponents: + for component in AxisFamily.active().axes: values = tuple( ( MEASUREMENT_SPARSE_CELL @@ -2417,7 +2417,8 @@ def metadata_for_row(row_index: int): for row_index in range(row_count) ) if not all(is_structural_missing_measurement_cell(value) for value in values): - coordinate_columns[component.value] = values + coordinate_columns[component.name] = values + def source_names_for_row(row_index: int) -> tuple[str, ...]: if slice_values is None: diff --git a/openhcs/core/metadata_cache.py b/openhcs/core/metadata_cache.py index d44aaf03bf..6e2a757059 100644 --- a/openhcs/core/metadata_cache.py +++ b/openhcs/core/metadata_cache.py @@ -5,8 +5,7 @@ from pathlib import Path from typing import Dict, Optional -from openhcs.core.components.validation import convert_enum_by_value -from openhcs.constants.constants import AllComponents +from openhcs.core.axes import Axis, AxisFamily logger = logging.getLogger(__name__) @@ -15,7 +14,7 @@ class MetadataCache: """Stores component key→name mappings with basic invalidation and thread safety.""" def __init__(self): - self._cache: Dict["AllComponents", Dict[str, Optional[str]]] = {} + self._cache: Dict[type[Axis], Dict[str, Optional[str]]] = {} self._metadata_file_mtimes: Dict[Path, float] = {} self._lock = threading.Lock() @@ -29,13 +28,13 @@ def cache_metadata( logger.info(f"🔍 METADATA_CACHE: parse_metadata returned: {metadata}") # Initialize all components with keys mapped to None - for component in AllComponents: + for component in AxisFamily.active().axes: component_keys = component_keys_cache.get(component, []) self._cache[component] = {key: None for key in component_keys} # Update with actual metadata where available for component_name, mapping in metadata.items(): - component = AllComponents(component_name) + component = AxisFamily.active().named(component_name) logger.info( f"🔍 METADATA_CACHE: Caching {component_name} -> {component}: {mapping}" ) @@ -61,16 +60,15 @@ def cache_metadata( ) def get_component_metadata(self, component, key: str) -> Optional[str]: - """Get metadata display name for a component key. Accepts GroupBy or VariableComponents.""" + """Get metadata display name for one axis value.""" with self._lock: if not self._is_cache_valid(): logger.warning(f"🔍 METADATA_CACHE: Cache invalid, clearing") self._cache.clear() return None - # Convert GroupBy to AllComponents using OpenHCS generic utility - component = convert_enum_by_value(component, AllComponents) or component component_cache = self._cache.get(component) + if component_cache is None: logger.debug("🔍 METADATA_CACHE: component %s not cached", component) return None @@ -84,7 +82,7 @@ def get_component_metadata(self, component, key: str) -> Optional[str]: return component_cache.get(key) def get_cached_metadata( - self, component: "AllComponents" + self, component: "type[Axis]" ) -> Optional[Dict[str, Optional[str]]]: """Get all cached metadata for a component.""" with self._lock: diff --git a/openhcs/core/orchestrator/analysis_consolidation.py b/openhcs/core/orchestrator/analysis_consolidation.py index 2d87fc1b88..1a293cd5b1 100644 --- a/openhcs/core/orchestrator/analysis_consolidation.py +++ b/openhcs/core/orchestrator/analysis_consolidation.py @@ -10,7 +10,7 @@ import pandas as pd -from openhcs.constants.constants import AllComponents +from openhcs.core.axes import AxisFamily from openhcs.core.config import AnalysisConsolidationConfig, PlateMetadataConfig from openhcs.core.context.processing_context import ProcessingContext from openhcs.core.orchestrator.execution_result import ( @@ -325,17 +325,19 @@ def runtime_analysis_table_output( """Project table identity from the typed runtime address, never its filename.""" scope = materialization.record.key.scope - well_id = scope.value_text_for_component(AllComponents.WELL) + partition_axis = AxisFamily.active().partition_axis() + well_id = scope.value_text_for_component(partition_axis) if well_id is None: raise ValueError( - "Analysis consolidation requires a well coordinate in the runtime " - f"artifact scope for {materialization.output_plan.name!r}." + f"Analysis consolidation requires a {partition_axis.name} coordinate in " + f"the runtime artifact scope for {materialization.output_plan.name!r}." ) coordinate_segments = tuple( - f"{component.value}-{value}" + f"{component.name}-{value}" for component, value in scope.presentation_component_values - if component is not AllComponents.WELL + if component is not partition_axis ) + analysis_type = "_".join( ( *coordinate_segments, diff --git a/openhcs/core/orchestrator/orchestrator.py b/openhcs/core/orchestrator/orchestrator.py index 8468fac3ae..902556d274 100644 --- a/openhcs/core/orchestrator/orchestrator.py +++ b/openhcs/core/orchestrator/orchestrator.py @@ -9,14 +9,7 @@ from pathlib import Path from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Union, Set -from openhcs.constants.constants import ( - Backend, - LOADABLE_IMAGE_EXTENSIONS, - GroupBy, - OrchestratorState, - AllComponents, - VariableComponents, -) +from openhcs.constants.constants import Backend, LOADABLE_IMAGE_EXTENSIONS, OrchestratorState from openhcs.constants import Microscope from openhcs.core.compiled_execution import CompiledExecutionBundle from openhcs.core.config import GlobalPipelineConfig @@ -33,7 +26,7 @@ from openhcs.core.source_bindings import source_bindings_defaults_to_base from openhcs.core.pipeline.compiler import PipelineCompiler from openhcs.core.steps.abstract import AbstractStep -from openhcs.core.components.validation import convert_enum_by_value + from openhcs.core.orchestrator.execution_result import ( ExecutionResult, RuntimeObservationMode, @@ -63,6 +56,7 @@ from openhcs.microscopes import create_microscope_handler from openhcs.microscopes.microscope_base import MicroscopeHandler from openhcs.core.alias_property import AliasProperty +from openhcs.core.axes import Axis, AxisFamily, GroupingDeclaration # Import generic component system - required for orchestrator functionality @@ -233,8 +227,8 @@ def _initialize_runtime_services( if progress_callback: logger.info("PipelineOrchestrator initialized with progress callback") - # Component keys cache for fast access - uses AllComponents (includes multiprocessing axis) - self._component_keys_cache: Dict["AllComponents", List[str]] = {} + # Component keys cache for every declared axis (including the partition axis) + self._component_keys_cache: Dict[type[Axis], List[str]] = {} self.metadata_cache = MetadataCache() @@ -553,9 +547,8 @@ def adopt_compiled_execution( self.input_dir = source.input_dir self.workspace_path = source.workspace_path self.default_pipeline_definition = list(execution_bundle.pipeline_definition) - from openhcs.constants import MULTIPROCESSING_AXIS - self._component_keys_cache[MULTIPROCESSING_AXIS] = list( + self._component_keys_cache[AxisFamily.active().partition_axis()] = list( execution_bundle.axis_ids ) self._initialized = True @@ -677,7 +670,7 @@ def create_context( # CRITICAL: Pass metadata cache for OpenHCS metadata creation # Extract cached metadata from service and convert to dict format expected by OpenHCSMetadataGenerator metadata_dict = {} - for component in AllComponents: + for component in AxisFamily.active().axes: cached_metadata = self.metadata_cache.get_cached_metadata( component ) @@ -822,13 +815,13 @@ def execute_compiled_plate( def get_component_keys( self, - component: Union["AllComponents", "VariableComponents"], + component: type[GroupingDeclaration], component_filter: Optional[List[Union[str, int]]] = None, *, resolved_config: GlobalPipelineConfig | None = None, ) -> List[str]: """ - Generic method to get component keys using VariableComponents directly. + Return the discovered values of one declared axis. Returns the discovered component values as strings to match the pattern detection system format. @@ -836,8 +829,8 @@ def get_component_keys( Tries metadata cache first, falls back to filename parsing cache if metadata is empty. Args: - component: AllComponents or VariableComponents enum specifying which component to extract - (also accepts GroupBy enum which will be converted to AllComponents) + component: The axis whose values to return; a step's grouping + declaration is accepted when it names one axis component_filter: Optional list of component values to filter by resolved_config: Existing compilation configuration. Omit for live inspection of the current saved declaration. @@ -853,12 +846,10 @@ def get_component_keys( "Orchestrator must be initialized before getting component keys." ) - # Convert GroupBy to AllComponents using OpenHCS generic utility - if isinstance(component, GroupBy) and component.value is None: - raise ValueError("Cannot get component keys for GroupBy.NONE") - - # Convert to AllComponents for cache lookup (includes multiprocessing axis) - component = convert_enum_by_value(component, AllComponents) or component + grouping_axes = component.grouping_axes() + if len(grouping_axes) != 1: + raise ValueError(f"Cannot get component keys for {component!r}") + (component,) = grouping_axes effective_config = ( self.get_effective_config() if resolved_config is None else resolved_config @@ -867,7 +858,7 @@ def get_component_keys( effective_config.source_bindings_config ) # Use component directly - let natural errors occur for wrong types - component_name = component.value + component_name = component.name # Try metadata cache first (preferred source) cached_metadata = self.metadata_cache.get_cached_metadata(component) @@ -895,7 +886,7 @@ def get_component_keys( return [] logger.debug( - f"Using filename parsing cache for {component.value}: {len(all_components)} components" + f"Using filename parsing cache for {component.name}: {len(all_components)} components" ) if component_filter: @@ -912,7 +903,7 @@ def get_component_keys( return all_components def cache_component_keys( - self, components: Optional[List["AllComponents"]] = None + self, components: Optional[List[type[Axis]]] = None ) -> None: """ Pre-compute and cache component keys for fast access using single-pass parsing. @@ -921,8 +912,8 @@ def cache_component_keys( extracting all component types in a single pass for maximum efficiency. Args: - components: Optional list of AllComponents to cache. - If None, caches all components in the AllComponents enum. + components: Optional list of axes to cache. + If None, caches every axis of the active family. """ if not self.is_initialized(): raise RuntimeError( @@ -930,16 +921,14 @@ def cache_component_keys( ) if components is None: - components = list( - AllComponents - ) # Cache all enum values including multiprocessing axis + components = list(AxisFamily.active().axes) logger.info( - f"Caching component keys for: {[comp.value for comp in components]}" + f"Caching component keys for: {[comp.name for comp in components]}" ) # Initialize component sets for all requested components - component_sets: Dict["AllComponents", Set[Union[str, int]]] = {} + component_sets: Dict[type[Axis], Set[Union[str, int]]] = {} for component in components: component_sets[component] = set() @@ -1006,11 +995,11 @@ def cache_component_keys( for component, component_set in component_sets.items(): sorted_components = [str(comp) for comp in sorted(list(component_set))] self._component_keys_cache[component] = sorted_components - logger.debug(f"Cached {len(sorted_components)} {component.value} keys") + logger.debug(f"Cached {len(sorted_components)} {component.name} keys") if not sorted_components: logger.warning( - f"No {component.value} values found in input directory: {self.input_dir}" + f"No {component.name} values found in input directory: {self.input_dir}" ) logger.info( @@ -1018,7 +1007,7 @@ def cache_component_keys( ) def clear_component_cache( - self, components: Optional[List["AllComponents"]] = None + self, components: Optional[List[type[Axis]]] = None ) -> None: """ Clear cached component keys to force recomputation. @@ -1027,7 +1016,7 @@ def clear_component_cache( to refresh the component key cache. Args: - components: Optional list of AllComponents to clear from cache. + components: Optional list of axes to clear from cache. If None, clears entire cache. """ if components is None: @@ -1037,7 +1026,8 @@ def clear_component_cache( for component in components: if component in self._component_keys_cache: del self._component_keys_cache[component] - logger.debug(f"Cleared cache for {component.value}") + logger.debug(f"Cleared cache for {component.name}") + logger.info(f"Cleared cache for {len(components)} component types") # Global config management removed - handled by UI layer diff --git a/openhcs/core/pipeline/compilation_session.py b/openhcs/core/pipeline/compilation_session.py index f6e9a2de12..f657d3ebb6 100644 --- a/openhcs/core/pipeline/compilation_session.py +++ b/openhcs/core/pipeline/compilation_session.py @@ -31,6 +31,7 @@ FileManagerLike, PlatePathDeclaration, ) +from openhcs.core.axes import AxisFamily, Ungrouped if TYPE_CHECKING: from openhcs.core.config import GlobalPipelineConfig @@ -193,7 +194,6 @@ def _admit_artifact_graphs(self) -> None: """Admit fixed contracts and forward topology once, before axis fanout.""" if self._artifact_graphs is not None: return - from openhcs.constants import GroupBy from openhcs.core.callable_contract import FunctionStepExecutionScope from openhcs.core.pipeline.artifact_planning import ( ArtifactGraph, @@ -218,7 +218,7 @@ def _admit_artifact_graphs(self) -> None: step.func, ) if isinstance(step, FunctionStep) - else GroupBy.NONE + else Ungrouped ) context = replace( context, step_name=step.name, step_index=index @@ -324,11 +324,11 @@ def validate_source_group_domains( global_config: GlobalPipelineConfig, ) -> None: """Validate declaration-owned group keys once against the whole plate.""" - from openhcs.constants.constants import GroupBy, get_openhcs_config from openhcs.core.callable_contract import FunctionStepExecutionScope from openhcs.core.components.validation import GenericValidator - validator = GenericValidator(get_openhcs_config()) + validator = GenericValidator(AxisFamily.active()) + for index, (graph, context) in enumerate( zip(self.artifact_graphs, self.artifact_contexts) ): @@ -336,7 +336,7 @@ def validate_source_group_domains( if ( pattern is None or not pattern.is_grouped - or context.group_by is GroupBy.NONE + or context.group_by is Ungrouped ): continue if FunctionStepExecutionScope.require_uniform( diff --git a/openhcs/core/pipeline/compiler.py b/openhcs/core/pipeline/compiler.py index 6c7272c709..6c8302d2c4 100644 --- a/openhcs/core/pipeline/compiler.py +++ b/openhcs/core/pipeline/compiler.py @@ -21,8 +21,6 @@ import dill as pickle from openhcs.constants.constants import ( - AllComponents, - get_multiprocessing_axis, OrchestratorState, READ_BACKEND, WRITE_BACKEND, @@ -102,6 +100,7 @@ from openhcs.core.steps.function_step import FunctionStep # Used for isinstance check from openhcs.core.progress import emit, ProgressPhase, ProgressStatus from dataclasses import dataclass, replace +from openhcs.core.axes import AxisFamily if TYPE_CHECKING: from openhcs.core.orchestrator.orchestrator import PipelineOrchestrator @@ -358,7 +357,7 @@ def _supplement_step_plans(session: CompilationSession) -> None: logger.warning( "Step %r uses a non-routed function pattern with group_by=%s " "also present in variable_components; compiled group_by is " - "GroupBy.NONE because variable_components owns the runtime " + "Ungrouped because variable_components owns the runtime " "stack axis.", step.name, declared_group_by.name, @@ -386,7 +385,7 @@ def _compile_sequential_runtime_filter_plan( for seq_component in seq_config.sequential_components if len( session.orchestrator.get_component_keys( - AllComponents(seq_component.value), + seq_component, resolved_config=session.global_config, ) ) @@ -511,7 +510,7 @@ def declare_zarr_stores(session: CompilationSession) -> None: last_step_index = session.step_count - 1 session.plan(last_step_index).zarr_config = { "all_wells": session.orchestrator.get_component_keys( - get_multiprocessing_axis(), resolved_config=session.global_config + AxisFamily.active().partition_axis(), resolved_config=session.global_config ), "needs_initialization": True, } @@ -612,7 +611,7 @@ def validate_sequential_components_compatibility( Args: steps: ObjectState-resolved pipeline steps - sequential_components: List of SequentialComponents from pipeline config + sequential_components: Sequential axes from pipeline config Raises: ValueError: If any step has variable_components that overlap with sequential_components @@ -620,7 +619,7 @@ def validate_sequential_components_compatibility( if not sequential_components: return - seq_comp_values = {sc.value for sc in sequential_components} + seq_comp_values = {sc.name for sc in sequential_components} for step in steps: if not isinstance(step, FunctionStep): @@ -628,7 +627,7 @@ def validate_sequential_components_compatibility( var_comps = step.processing_config.variable_components if not var_comps: continue - var_comp_values = {vc.value for vc in var_comps} + var_comp_values = {vc.name for vc in var_comps} overlap = seq_comp_values & var_comp_values if overlap: @@ -666,11 +665,10 @@ def analyze_pipeline_sequential_mode( if seq_config and seq_config.sequential_components: # Enable pipeline-wide sequential mode context.pipeline_sequential_mode = True - seq_comps = tuple(sc.value for sc in seq_config.sequential_components) + seq_comps = tuple(seq_config.sequential_components) # Precompute combinations from orchestrator's component keys cache # This cache is populated from filename parsing during init, so it's always available - from openhcs.constants import AllComponents import itertools # Extract component values from orchestrator's cache for each sequential component @@ -679,14 +677,12 @@ def analyze_pipeline_sequential_mode( filtered_seq_comps = [] for seq_comp in seq_comps: - # Convert component name to AllComponents enum - component_enum = AllComponents(seq_comp) - # Get component values from orchestrator's cache (populated from filename parsing) component_values = orchestrator.get_component_keys( - component_enum, resolved_config=global_config + seq_comp, resolved_config=global_config ) + if not component_values: logger.warning(f"No {seq_comp} values found in orchestrator cache") component_values_lists.append([]) @@ -901,7 +897,7 @@ def _axis_values_to_process( ) if well_filter_config and well_filter_config.well_filter is not None: available_wells = orchestrator.get_component_keys( - get_multiprocessing_axis(), resolved_config=effective_config + AxisFamily.active().partition_axis(), resolved_config=effective_config ) resolved_wells = WellFilterProcessor.resolve_filter_with_mode( well_filter_config.well_filter, @@ -923,7 +919,7 @@ def _axis_values_to_process( ) return orchestrator.get_component_keys( - get_multiprocessing_axis(), + AxisFamily.active().partition_axis(), resolved_axis_filter, resolved_config=effective_config, ) @@ -1249,7 +1245,7 @@ def _validate_primary_image_carrier_source_anchor( raise ValueError( f"{owner}: cannot project source bindings for routed group " f"{routed_group!r} on " - f"{execution_scope.component.value!r}: {error}" + f"{execution_scope.component.name!r}: {error}" ) from error if ( source_binding_plan is not None @@ -1653,7 +1649,7 @@ def compile_pipelines( filemanager=orchestrator.filemanager, input_dir=orchestrator.input_dir, available_axis_values=orchestrator.get_component_keys( - get_multiprocessing_axis(), resolved_config=effective_config + AxisFamily.active().partition_axis(), resolved_config=effective_config ), ), source_projections_by_axis=DEFAULT_SOURCE_PROJECTION_CACHE.partition_by_axes( @@ -1753,7 +1749,7 @@ def _resolve_step_axis_filters( # Get available axis values from orchestrator using multiprocessing axis available_axis_values = orchestrator.get_component_keys( - get_multiprocessing_axis(), resolved_config=global_config + AxisFamily.active().partition_axis(), resolved_config=global_config ) if not available_axis_values: logger.warning("No available axis values found for axis filter resolution") diff --git a/openhcs/core/pipeline/funcstep_contract_validator.py b/openhcs/core/pipeline/funcstep_contract_validator.py index ad4e1a9c45..a7605a4ac6 100644 --- a/openhcs/core/pipeline/funcstep_contract_validator.py +++ b/openhcs/core/pipeline/funcstep_contract_validator.py @@ -29,10 +29,6 @@ get_type_hints, ) -from openhcs.constants.constants import ( - GroupBy, - get_openhcs_config, -) from openhcs.core.callable_contract import CallableContract, FunctionStepExecutionScope from openhcs.core.function_patterns import ( CompiledFunctionPattern, @@ -49,6 +45,7 @@ ) from openhcs.core.components.validation import GenericValidator +from openhcs.core.axes import AxisFamily, Ungrouped if TYPE_CHECKING: from openhcs.core.context.processing_context import ProcessingContext @@ -541,9 +538,11 @@ def normalized_group_by( ): """Return pattern-aware grouping semantics for compiled execution.""" variable_components = () if variable_components is None else variable_components - if group_by and group_by.value in [vc.value for vc in variable_components]: + if group_by is not None and any( + axis in variable_components for axis in group_by.grouping_axes() + ): if not pattern.is_grouped: - return GroupBy.NONE + return Ungrouped variable_component_names = tuple( component.name for component in variable_components ) @@ -683,8 +682,7 @@ def validate_compiled_step_plan(step_plan) -> None: "bindings." ) return - config = get_openhcs_config() - validator = GenericValidator(config) + validator = GenericValidator(AxisFamily.active()) group_by = step_plan.group_by if step_plan.variable_components is None: variable_components = () @@ -707,7 +705,7 @@ def validate_compiled_step_plan(step_plan) -> None: if not validation_result.is_valid: raise ValueError(validation_result.error_message) - FuncStepContractValidator.validate_required_variable_components( + FuncStepContractValidator.validate_required_axis_roles( variable_components, contracts, step_name, @@ -791,8 +789,7 @@ def validate_funcstep( return # Validate using generic validation system - config = get_openhcs_config() - validator = GenericValidator(config) + validator = GenericValidator(AxisFamily.active()) # Check for constraint violation: group_by ∈ variable_components group_by = FuncStepContractValidator.normalized_group_by( @@ -811,7 +808,7 @@ def validate_funcstep( if not validation_result.is_valid: raise ValueError(validation_result.error_message) - FuncStepContractValidator.validate_required_variable_components( + FuncStepContractValidator.validate_required_axis_roles( variable_components, contracts, step_name, @@ -831,7 +828,8 @@ def validate_funcstep( if ( orchestrator is not None and normalized.is_grouped - and group_by not in (None, GroupBy.NONE) + and group_by is not None + and group_by.grouping_axes() ): dict_validation_result = validator.validate_dict_pattern_keys( func_pattern, group_by, step_name, orchestrator @@ -1120,26 +1118,33 @@ def _normalized_function_pattern( raise ValueError(invalid_pattern_error(func)) from exc @staticmethod - def validate_required_variable_components( + def validate_required_axis_roles( variable_components, contracts: Sequence[CallableContract], step_name: str, ) -> None: - """Validate callable/module required axes against resolved step config.""" - resolved_components = set(variable_components or ()) + """Require the step's variable axes to cover each callable's roles.""" + resolved_components = tuple(variable_components or ()) for contract in contracts: missing = tuple( - component - for component in contract.required_variable_components - if component not in resolved_components + role + for role in contract.required_axis_roles + if not any(issubclass(axis, role) for axis in resolved_components) ) if not missing: continue - required = ", ".join(component.name for component in missing) + family = AxisFamily.active() + required = ", ".join( + f"{role.__name__} " + f"({', '.join(axis.name for axis in family.with_role(role)) or 'none'})" + for role in missing + ) + actual = ", ".join(component.name for component in resolved_components) raise ValueError( f"Step '{step_name}' callable '{contract.function_name}' requires " - f"variable_components {required}; resolved {actual or 'none'}." + f"variable_components with role {required}; resolved " + f"{actual or 'none'}." ) @staticmethod @@ -1224,19 +1229,23 @@ def validate_allowed_group_by( contracts: Sequence[CallableContract], step_name: str, ) -> None: - """Validate callable/module allowed group_by values against step config.""" - resolved_group_by = GroupBy.NONE if group_by is None else group_by + """Require the step's grouping axes to carry a role each callable allows.""" + resolved_group_by = Ungrouped if group_by is None else group_by + grouping_axes = resolved_group_by.grouping_axes() for contract in contracts: - allowed = contract.allowed_group_by - if not allowed or resolved_group_by in allowed: + allowed = contract.allowed_group_by_roles + if not allowed or ( + grouping_axes + and all( + any(issubclass(axis, role) for role in allowed) + for axis in grouping_axes + ) + ): continue - allowed_names = ", ".join(value.name for value in allowed) - actual = ( - resolved_group_by.name - if isinstance(resolved_group_by, Enum) - else str(resolved_group_by) - ) + allowed_names = ", ".join(role.__name__ for role in allowed) raise ValueError( f"Step '{step_name}' callable '{contract.function_name}' allows " - f"group_by {allowed_names}; resolved {actual}." + f"group_by axes with role {allowed_names}; resolved " + f"{resolved_group_by.name}." ) + diff --git a/openhcs/core/pipeline/function_contracts.py b/openhcs/core/pipeline/function_contracts.py index a48c154de6..70fadc01c5 100644 --- a/openhcs/core/pipeline/function_contracts.py +++ b/openhcs/core/pipeline/function_contracts.py @@ -17,7 +17,6 @@ from python_introspect import RuntimeParameterDeclarationABC, add_parameter_exclusions -from openhcs.constants.constants import GroupBy, VariableComponents from openhcs.core.artifacts import ( ArtifactInputPlan, ArtifactOutputPlan, @@ -38,6 +37,7 @@ VariableComponentStackRequirement, ) from openhcs.processing.materialization import MaterializationSpec +from openhcs.core.axes import AxisRole F = TypeVar("F", bound=Callable) @@ -343,21 +343,21 @@ def _runtime_parameter_declaration_types( ) -def required_variable_components( - *components: VariableComponents, -) -> Callable[[F], F]: - """Declare FunctionStep variable axes required by a callable.""" - normalized = tuple( - ( - component - if isinstance(component, VariableComponents) - else VariableComponents(component) - ) - for component in components - ) +def _axis_roles(roles: tuple[type[AxisRole], ...], decorator_name: str) -> tuple: + for role in roles: + if not (isinstance(role, type) and issubclass(role, AxisRole)): + raise TypeError(f"{decorator_name} takes axis roles; got {role!r}.") + if len(roles) != len(set(roles)): + raise TypeError(f"{decorator_name} roles must be unique.") + return roles + + +def required_axis_roles(*roles: type[AxisRole]) -> Callable[[F], F]: + """Declare axis roles the step's variable axes must cover for a callable.""" + normalized = _axis_roles(roles, "required_axis_roles") def decorator(func: F) -> F: - vars(func)[FunctionContractAttribute.required_variable_components] = normalized + vars(func)[FunctionContractAttribute.required_axis_roles] = normalized return func return decorator @@ -390,15 +390,12 @@ def decorator(func: F) -> F: return decorator -def allowed_group_by(*group_by_values: GroupBy) -> Callable[[F], F]: - """Declare FunctionStep group_by values allowed by a callable.""" - normalized = tuple( - group_by if isinstance(group_by, GroupBy) else GroupBy(group_by) - for group_by in group_by_values - ) +def allowed_group_by_roles(*roles: type[AxisRole]) -> Callable[[F], F]: + """Declare the axis roles a callable's step may group by.""" + normalized = _axis_roles(roles, "allowed_group_by_roles") def decorator(func: F) -> F: - vars(func)[FunctionContractAttribute.allowed_group_by] = normalized + vars(func)[FunctionContractAttribute.allowed_group_by_roles] = normalized return func return decorator diff --git a/openhcs/core/pipeline/path_planner.py b/openhcs/core/pipeline/path_planner.py index 987e1a2db7..4defc85df9 100644 --- a/openhcs/core/pipeline/path_planner.py +++ b/openhcs/core/pipeline/path_planner.py @@ -14,7 +14,6 @@ from pathlib import Path from typing import Dict, List, Mapping, Optional -from openhcs.constants import AllComponents, GroupBy, VariableComponents from openhcs.constants.input_source import InputSource from openhcs.core.axis_filter import StepAxisFilterSet from openhcs.core.artifacts import ( @@ -76,6 +75,7 @@ ) from openhcs.core.steps.abstract import AbstractStep from openhcs.core.steps.function_step import FunctionStep +from openhcs.core.axes import Axis, AxisFamily, GroupingDeclaration, Ungrouped logger = logging.getLogger(__name__) @@ -136,7 +136,7 @@ def from_plan( def relation_scope_from_plan( cls, plan: ArtifactInputPlan | ArtifactOutputPlan, - component: AllComponents | None, + component: type[Axis] | None, ) -> "PathPlannerGroupScope": """Return the plan domain relevant to one relation component.""" @@ -188,7 +188,7 @@ def single_group_key(self) -> PlannerGroupKey | None: class PathPlannerComponentScopes: """Component value scopes carried by the main-flow image branch.""" - scopes: Mapping[VariableComponents, PathPlannerGroupScope] + scopes: Mapping[type[Axis], PathPlannerGroupScope] @classmethod def empty(cls) -> "PathPlannerComponentScopes": @@ -196,7 +196,7 @@ def empty(cls) -> "PathPlannerComponentScopes": def scope_for_group_by( self, - group_by: GroupBy | None, + group_by: type[GroupingDeclaration] | None, ) -> PathPlannerGroupScope | None: group_by_component = self.component_from_group_by(group_by) if group_by_component is None: @@ -238,10 +238,13 @@ def output_after( return PathPlannerComponentScopes(scopes) @staticmethod - def component_from_group_by(group_by: GroupBy | None) -> VariableComponents | None: - if group_by is None or group_by is GroupBy.NONE: + def component_from_group_by( + group_by: type[GroupingDeclaration] | None, + ) -> type[Axis] | None: + if group_by is None: return None - return VariableComponents(group_by.value) + grouping_axes = group_by.grouping_axes() + return grouping_axes[0] if grouping_axes else None @dataclass(frozen=True) @@ -271,7 +274,7 @@ def context_producer_scope( self, producer: ArtifactProducer, *, - source_component: AllComponents | None, + source_component: type[Axis] | None, ) -> PathPlannerGroupScope: """Resolve producer groups against their own compiled axis authority.""" @@ -400,7 +403,7 @@ def artifact_owned_execution_scope( normalized_group_component = ( None if group_component is None - else ComponentSet.coerce_component(group_component) + else AxisFamily.active().require(group_component) ) scopes: list[PathPlannerGroupScope] = [] for spec in owner_specs: @@ -440,7 +443,7 @@ def artifact_owned_execution_scope( spec.name ): continue - if group_by is not GroupBy.NONE: + if group_by is not Ungrouped: raise ValueError( f"Artifact-owned FunctionStep {step.name!r} cannot " f"resolve group scope for {spec.ref()!r}." @@ -468,7 +471,7 @@ def artifact_owned_execution_scope( if source_group_keys else PathPlannerGroupScope.ungrouped() ) - if source_scope.is_ungrouped and group_by is not GroupBy.NONE: + if source_scope.is_ungrouped and group_by is not Ungrouped: raise ValueError( f"Artifact-owned FunctionStep {step.name!r} cannot " f"resolve group scope for {spec.ref()!r}." @@ -478,7 +481,7 @@ def artifact_owned_execution_scope( if not scopes: return consumer_scope - consumer_variable_components = ComponentSet.from_enum_values( + consumer_variable_components = ComponentSet.of( step.processing_config.variable_components or () ) projected_scopes = tuple( @@ -499,7 +502,7 @@ def artifact_owned_execution_scope( def dynamic_execution_scope_for_group_by( self, step: AbstractStep, - group_by: GroupBy | None, + group_by: type[GroupingDeclaration] | None, ) -> PathPlannerGroupScope: """Return a typed runtime-discovered scope for a concrete group axis.""" group_by_component = PathPlannerComponentScopes.component_from_group_by(group_by) @@ -518,16 +521,16 @@ def dynamic_execution_scope_for_group_by( if source_keys: return PathPlannerGroupScope.from_raw( source_keys, - component=ComponentSet.coerce_component(group_by_component), + component=AxisFamily.active().require(group_by_component), ) return PathPlannerGroupScope.dynamic( - ComponentSet.coerce_component(group_by_component) + AxisFamily.active().require(group_by_component) ) def source_binding_scope_for_group_by( self, step: AbstractStep, - group_by: GroupBy | None, + group_by: type[GroupingDeclaration] | None, *, source_bindings: SourceBindingDeclarationsMixin | None = None, ) -> PathPlannerGroupScope: @@ -540,7 +543,7 @@ def source_binding_scope_for_group_by( source_bindings = step.source_bindings if not source_bindings.binding_declarations: return PathPlannerGroupScope.ungrouped() - component = ComponentSet.coerce_component(group_by_component) + component = AxisFamily.active().require(group_by_component) group_keys = source_binding_group_keys_for_group_by( source_bindings, group_by, @@ -552,20 +555,22 @@ def source_binding_scope_for_group_by( @staticmethod def execution_component_for_dict_pattern( - group_by: GroupBy | None, + group_by: type[GroupingDeclaration] | None, step_name: str | None, - ) -> AllComponents: + ) -> type[Axis]: """Return the declared component for dict-pattern runtime dispatch.""" - if group_by is None or group_by is GroupBy.NONE or group_by.value is None: + grouping_axes = () if group_by is None else group_by.grouping_axes() + if not grouping_axes: raise ValueError( f"Step '{step_name}' uses a dict function pattern without a " "concrete group_by component. Dict keys are dispatch groups; " - "GroupBy.NONE is only valid for non-dict function patterns." + "Ungrouped is only valid for non-dict function patterns." ) - return AllComponents.from_value(group_by.value) + return grouping_axes[0] + @staticmethod - def normalized_group_by(step: AbstractStep) -> GroupBy: + def normalized_group_by(step: AbstractStep) -> type[GroupingDeclaration]: """Use the same group_by normalization as compiled execution plans.""" from openhcs.core.pipeline.funcstep_contract_validator import ( FuncStepContractValidator, @@ -634,7 +639,7 @@ def source_binding_component_domains( ) return tuple( PathPlannerGroupScope.from_raw(values, component=component) - for component in AllComponents + for component in AxisFamily.active().axes for values in ( tuple(dict.fromkeys( value @@ -672,7 +677,7 @@ def compile_plan_maps( source_universe_plan = CompiledSourceUniversePlan.from_source_binding_plan( source_binding_plan ) - consumer_variable_components = ComponentSet.from_enum_values( + consumer_variable_components = ComponentSet.of( step.processing_config.variable_components or () ) artifact_inputs = self.process_artifact_inputs( @@ -875,7 +880,7 @@ def relation_source_scopes_by_ref( *, group_scope: PathPlannerGroupScope, source_bindings: SourceBindingDeclarationsMixin, - group_by: GroupBy | None, + group_by: type[GroupingDeclaration] | None, ) -> dict[ArtifactSpecRef, PathPlannerGroupScope]: """Return exact group scopes for every declared relation source.""" @@ -890,7 +895,7 @@ def relation_source_scopes_by_ref( group_by ) if grouped_component is not None: - component = ComponentSet.coerce_component(grouped_component) + component = AxisFamily.active().require(grouped_component) for input_ref, spec in declarations.inputs.items(): input_plan = artifact_inputs.get(input_ref) if input_plan is None: @@ -1059,7 +1064,7 @@ def build_step_compiled_function_pattern( artifact_inputs=artifact_inputs, relation_source_scopes=relation_source_scopes, execution_group_scope=execution_group_scope, - consumer_variable_components=ComponentSet.from_enum_values( + consumer_variable_components=ComponentSet.of( step.processing_config.variable_components or () ), source_bindings=step_context.source_bindings, @@ -1307,8 +1312,8 @@ def exact_component_scopes( ) -> tuple[ComponentGroupScope, ...]: """Resolve exact producer coordinates without conflating consumer scope.""" - by_component: dict[AllComponents, ComponentGroupScope] = {} - storage_components: set[AllComponents] = set() + by_component: dict[type[Axis], ComponentGroupScope] = {} + storage_components: set[type[Axis]] = set() for domain in storage_domains: if domain.is_ungrouped or domain.is_dynamic or len(domain.keys) != 1: continue @@ -1330,7 +1335,7 @@ def exact_component_scopes( if existing is not None and existing != scope: raise ValueError( f"Invocation {invocation.key!r} input {artifact_ref!r} declares " - f"conflicting {component.value!r} coordinates {existing!r} and " + f"conflicting {component.name!r} coordinates {existing!r} and " f"{scope!r}." ) by_component[component] = scope @@ -1349,7 +1354,7 @@ def exact_component_scopes( ): raise ValueError( f"Invocation {invocation.key!r} input {artifact_ref!r} " - f"has exact {component.value!r} coordinate {exact_scope!r} " + f"has exact {component.name!r} coordinate {exact_scope!r} " f"outside component domain {domain!r}." ) @@ -1491,7 +1496,7 @@ def process_artifact_outputs( f"undeclared input {source_ref!r}." ) lineage_domains_by_component: dict[ - AllComponents, + type[Axis], list[PathPlannerGroupScope], ] = defaultdict(list) for domain in source_stack_domains: @@ -1502,7 +1507,7 @@ def process_artifact_outputs( if domain not in lineage_domains_by_component[domain.component]: lineage_domains_by_component[domain.component].append(domain) binding_domains_by_component: dict[ - AllComponents, + type[Axis], list[PathPlannerGroupScope], ] = defaultdict(list) for domain in source_binding_domains: @@ -1532,7 +1537,7 @@ def process_artifact_outputs( ): raise ValueError( f"Artifact output {spec.ref()!r} inherits " - f"{component.value!r} lineage {lineage_domain!r} outside " + f"{component.name!r} lineage {lineage_domain!r} outside " f"source-binding domain {binding_domain!r}." ) component_domain = lineage_domain or binding_domain diff --git a/openhcs/core/roi_point_metadata.py b/openhcs/core/roi_point_metadata.py index 90ef89c57e..6604d824a5 100644 --- a/openhcs/core/roi_point_metadata.py +++ b/openhcs/core/roi_point_metadata.py @@ -8,7 +8,7 @@ from polystore.roi import ROI -from openhcs.constants.constants import AllComponents +from openhcs.core.axes import AxisFamily, StackAxis from openhcs.core.runtime_image_values import ImagePayloadMetadata from openhcs.core.source_image_provenance import SourceComponentMetadata from openhcs.core.source_matching import source_component_metadata_items @@ -54,7 +54,8 @@ def source_component_domain( domain = planes.component_metadata if not domain or any(plane is None for plane in domain): raise ValueError("3D point ROI requires an exact source-plane Z domain.") - z_field = AllComponents.Z_INDEX.value + stack_axis = AxisFamily.active().one(StackAxis) + z_field = stack_axis.name if any(z_field not in plane for plane in domain): raise ValueError("3D point ROI source planes require z_index metadata.") z_values = tuple(plane[z_field] for plane in domain) @@ -88,9 +89,9 @@ def source_component_domain( components = tuple( dict(source_component_metadata_items(plane)) for plane in domain ) - common_keys = set(components[0]) - {AllComponents.Z_INDEX} + common_keys = set(components[0]) - {stack_axis} if any( - set(plane) - {AllComponents.Z_INDEX} != common_keys + set(plane) - {stack_axis} != common_keys for plane in components ): raise ValueError("3D point ROI source planes have inconsistent components.") diff --git a/openhcs/core/roi_source_metadata.py b/openhcs/core/roi_source_metadata.py index 51fef9ba48..feda0b8f79 100644 --- a/openhcs/core/roi_source_metadata.py +++ b/openhcs/core/roi_source_metadata.py @@ -14,6 +14,7 @@ from openhcs.core.runtime_slice_projection import RuntimeProjectionPlaneMetadata from openhcs.core.source_image_provenance import SourceComponentMetadata from python_introspect import to_jsonable +from openhcs.core.axes import AxisFamily @dataclass(frozen=True, slots=True) @@ -83,12 +84,11 @@ def source_component_domain( @staticmethod def component_values(metadata: ImagePayloadMetadata) -> dict[str, tuple[object, ...]]: - from openhcs.constants.constants import AllComponents return { component: tuple(dict.fromkeys(values)) for component, values in metadata.source_provenance.varying_plane_component_values( - tuple(AllComponents) + AxisFamily.active().axes ).items() } diff --git a/openhcs/core/runtime_adapters.py b/openhcs/core/runtime_adapters.py index b9a9486ac7..b4b738dfd5 100644 --- a/openhcs/core/runtime_adapters.py +++ b/openhcs/core/runtime_adapters.py @@ -9,7 +9,7 @@ from python_introspect import add_parameter_exclusions -from openhcs.constants.constants import Backend, VariableComponents +from openhcs.constants.constants import Backend from openhcs.core.artifact_key_selection import ( ArtifactOutputPolicy, NativeReturnArtifactOutputPolicy, @@ -40,6 +40,7 @@ RuntimePlaneAxisValueProjection, RuntimePlaneProjection, ) +from openhcs.core.axes import Axis if TYPE_CHECKING: from openhcs.core.callable_contract import CallableContract @@ -80,7 +81,7 @@ class RuntimeAdapterRequest: plane_projection: RuntimePlaneProjection = field( default_factory=RuntimePlaneProjection.stack ) - variable_components: tuple[VariableComponents, ...] = () + variable_components: tuple[type[Axis], ...] = () execution_scope: "FunctionCoreExecutor | None" = None def __post_init__(self) -> None: diff --git a/openhcs/core/runtime_execution_validation.py b/openhcs/core/runtime_execution_validation.py index 0063e86e8d..8f48cdcb0e 100644 --- a/openhcs/core/runtime_execution_validation.py +++ b/openhcs/core/runtime_execution_validation.py @@ -37,7 +37,7 @@ def runtime_artifact_viewer_component_identity( """Return nominal component coordinates from source or viewer metadata.""" return tuple( - (component.value, str(value)) + (component.name, str(value)) for component, value in source_component_metadata_items(metadata) ) @@ -274,7 +274,7 @@ def _runtime_artifact_viewer_output_payloads( payloads.append( RuntimeArtifactViewerPayloadExpectation( components=tuple( - (component.value, str(value)) + (component.name, str(value)) for component, value in source_component_metadata_items( source_identity.component_metadata or {} ) diff --git a/openhcs/core/runtime_image_values.py b/openhcs/core/runtime_image_values.py index 4bb5e53343..3f1f3c3b5e 100644 --- a/openhcs/core/runtime_image_values.py +++ b/openhcs/core/runtime_image_values.py @@ -22,7 +22,6 @@ ) from collections.abc import Mapping -from openhcs.constants.constants import AllComponents from openhcs.core.alias_property import AliasProperty from openhcs.core.runtime_array_values import ( DataBackedRuntimeArrayPayload, @@ -52,6 +51,7 @@ from openhcs.core.source_spatial_domain import ( _spatial_shape_pair as _source_spatial_shape_pair, ) +from openhcs.core.axes import AxisFamily PhysicalBorderEdgesYX = tuple[bool, bool, bool, bool] | None @@ -527,7 +527,7 @@ def retained_plane_component_values( if self.plane_axis is None: return {} return self.source_provenance.varying_plane_component_values( - tuple(AllComponents) + AxisFamily.active().axes ) @classmethod @@ -1220,7 +1220,7 @@ def with_source_context_from( # Scalar context cannot collapse coordinates that vary across this # payload's represented source planes, including runtime stacks. varying = self.source_provenance.varying_plane_component_values( - tuple(AllComponents) + AxisFamily.active().axes ) if varying: fallback_provenance = fallback_provenance.with_source_component_metadata( diff --git a/openhcs/core/runtime_measurements.py b/openhcs/core/runtime_measurements.py index 16f0160a9b..e6424ed7a3 100644 --- a/openhcs/core/runtime_measurements.py +++ b/openhcs/core/runtime_measurements.py @@ -6,7 +6,6 @@ from functools import lru_cache from dataclasses import dataclass -from openhcs.constants.constants import AllComponents from openhcs.core.artifacts import ( NamedArtifactPayload, ) @@ -40,6 +39,7 @@ import math import numpy as np import re +from openhcs.core.axes import AxisFamily @dataclass(slots=True, kw_only=True) @@ -1144,7 +1144,7 @@ def field_names(cls) -> frozenset[str]: return frozenset( ( *(field.value for field in cls), - *(component.value for component in AllComponents), + *AxisFamily.active().names(), ) ) diff --git a/openhcs/core/runtime_pattern_cache.py b/openhcs/core/runtime_pattern_cache.py index f791fe7873..7b775d9747 100644 --- a/openhcs/core/runtime_pattern_cache.py +++ b/openhcs/core/runtime_pattern_cache.py @@ -7,10 +7,10 @@ from pathlib import Path from typing import Hashable, TYPE_CHECKING -from openhcs.constants.constants import AllComponents from openhcs.core.components.parser_metaprogramming import FilenameParseResult from openhcs.core.function_patterns import FunctionGroupKey from openhcs.core.source_binding_selection import SourceCandidatePath +from openhcs.core.axes import Axis, GroupingDeclaration if TYPE_CHECKING: from openhcs.microscopes.microscope_interfaces import FilenameParser @@ -27,8 +27,8 @@ class RuntimePatternDiscoveryCacheKey: axis_id: str source_files: tuple[str, ...] - group_by: str | None - variable_components: tuple[str, ...] + group_by: type[GroupingDeclaration] | None + variable_components: tuple[type[Axis], ...] @classmethod def from_source_files( @@ -36,8 +36,8 @@ def from_source_files( *, axis_id: str, source_files: Sequence[str], - group_by: str | None, - variable_components: Sequence[str], + group_by: type[GroupingDeclaration] | None, + variable_components: Sequence[type[Axis]], ) -> "RuntimePatternDiscoveryCacheKey": if not axis_id: raise ValueError("Runtime pattern cache axis_id cannot be empty.") @@ -46,10 +46,8 @@ def from_source_files( return cls( axis_id=str(axis_id), source_files=tuple(str(source_file) for source_file in source_files), - group_by=None if group_by is None else str(group_by), - variable_components=tuple( - str(component) for component in variable_components - ), + group_by=group_by, + variable_components=tuple(variable_components), ) @@ -127,7 +125,7 @@ class RuntimePatternDiscoveryCache: FilenameParseResult | None, ] = field(default_factory=dict) filenames_by_component: dict[ - tuple["FilenameParser", tuple[Hashable, ...], AllComponents, str], set[str], + tuple["FilenameParser", tuple[Hashable, ...], type[Axis], str], set[str], ] = field(default_factory=dict) def metadata_for_filename( @@ -150,7 +148,7 @@ def files_for_component( self, parser: "FilenameParser", files: Sequence[str], - component: AllComponents, + component: type[Axis], value: object, ) -> list[str]: """Select component membership from the admitted filename inventory.""" diff --git a/openhcs/core/runtime_slice_projection.py b/openhcs/core/runtime_slice_projection.py index eba0821907..c851e87858 100644 --- a/openhcs/core/runtime_slice_projection.py +++ b/openhcs/core/runtime_slice_projection.py @@ -14,7 +14,6 @@ from arraybridge.decorators import DtypeConversionConfig from metaclass_registry import AutoRegisterMeta -from openhcs.constants.constants import VariableComponents from openhcs.core.aligned_image_payload import ( AlignedImageStack, ImagePayloadSliceStack, @@ -67,6 +66,7 @@ from openhcs.core.source_image_provenance import ( SourceComponentMetadata, ) +from openhcs.core.axes import Axis RuntimeProjectionPrimitive: TypeAlias = str | bytes | int | float | bool | None RuntimeProjectionMapping: TypeAlias = Mapping[str, "RuntimeProjectionData"] @@ -104,7 +104,7 @@ class RuntimeProjectionSourceIdentityRequest: value: RuntimeProjectionData source_description: str - variable_components: Sequence[VariableComponents] = field(default_factory=tuple) + variable_components: Sequence[type[Axis]] = field(default_factory=tuple) plane_projection: RuntimePlaneAxisValueProjection | None = None def runtime_slice_count(self) -> int | None: diff --git a/openhcs/core/runtime_source_binding_cache.py b/openhcs/core/runtime_source_binding_cache.py index 48167d65d7..fe32f560b5 100644 --- a/openhcs/core/runtime_source_binding_cache.py +++ b/openhcs/core/runtime_source_binding_cache.py @@ -25,7 +25,7 @@ SourceUniverseRuntimeState, ) from openhcs.core.source_image_provenance import SourceImageIdentity - from openhcs.constants.constants import AllComponents + from openhcs.core.axes import Axis from openhcs.core.source_workspace_projection import ( VirtualWorkspaceSourceProjection, ) @@ -39,7 +39,7 @@ class RuntimeSourceResolutionSnapshot: projection: "VirtualWorkspaceSourceProjection" context: "SourcePatternResolutionContext" path_resolutions: Mapping[str, "SourceCandidatePathResolution"] - component_values: Mapping[str, tuple[Mapping["AllComponents", str], ...]] + component_values: Mapping[str, tuple[Mapping["type[Axis]", str], ...]] def context_for_matching(self) -> "SourcePatternResolutionContext": """Expose this admitted epoch through the existing matching context.""" diff --git a/openhcs/core/runtime_stores.py b/openhcs/core/runtime_stores.py index 1a84a47b5e..6713098d28 100644 --- a/openhcs/core/runtime_stores.py +++ b/openhcs/core/runtime_stores.py @@ -12,7 +12,7 @@ from python_introspect import RuntimeParameterDeclarationABC, to_jsonable -from openhcs.constants.constants import AllComponents, Backend +from openhcs.constants.constants import Backend from openhcs.core.artifacts import ( ArtifactInputPlan, ArtifactOutputPlan, @@ -47,6 +47,7 @@ semantic_source_metadata_value, ) from openhcs.core.source_bindings import CompiledSourceBindingPlan +from openhcs.core.axes import Axis, AxisFamily, PartitionAxis if TYPE_CHECKING: from openhcs.processing.materialization.core import Output @@ -370,7 +371,7 @@ def selects_complete_producer(self) -> bool: return ( projection.selects_declared_complete_producer(self.edge_plan.spec, storage_plan) or storage_plan.composes_producer_groups( - ComponentSet.coerce(projection.consumer_variable_components) + ComponentSet.of(projection.consumer_variable_components) ) or ( selection_scope == producer_scope @@ -440,7 +441,7 @@ def candidate_execution_scopes( component_scope = projection.component_scope(component) if component_scope.is_dynamic: component_value = semantic_source_metadata_value( - metadata, component.value, + metadata, component.name, ) if component_value is None: break @@ -448,12 +449,12 @@ def candidate_execution_scopes( else: component_value = component_scope.select_runtime_key(None) if not SourceAxisMetadataScope.constraint_matches_metadata( - metadata, component.value, component_value, + metadata, component.name, component_value, ): break existing_value = coordinates.get(component) if existing_value is not None and not SourceAxisMetadataScope.constraint_matches_metadata( - metadata, component.value, existing_value, + metadata, component.name, existing_value, ): break coordinates.setdefault(component, component_value) @@ -477,7 +478,7 @@ def candidate_execution_scopes( (component, value) for component, value in coordinates.items() if component is not execution_scope.component - and not component.is_multiprocessing_axis() + and not issubclass(component, PartitionAxis) and component not in variable_components and identity_policy.is_identity_component(component) ) @@ -520,7 +521,7 @@ def all_records( f"Missing dynamic grouped artifact input {storage_plan.name!r} " f"({storage_plan.artifact_type.value}) on axis " f"{self.axis_scope.axis_id!r} for producer component " - f"{producer_scope.component.value!r}." + f"{producer_scope.component.name!r}." ) records_by_group: OrderedDict[str, list[StoredRuntimeValue]] = OrderedDict() for record in records: @@ -574,7 +575,7 @@ def _producer_group_composition_scope( """Return declared group-axis reconstruction semantics for this input.""" storage_plan = self.edge_plan.storage_plan - consumer_components = ComponentSet.coerce( + consumer_components = ComponentSet.of( self.edge_plan.projection.consumer_variable_components ) if not storage_plan.composes_producer_groups(consumer_components): @@ -582,7 +583,7 @@ def _producer_group_composition_scope( return storage_plan.producer_group_scope() def _axis_value(self, value: RuntimeValue) -> RuntimeValue: - projected_components = ComponentSet.coerce( + projected_components = ComponentSet.of( self.edge_plan.projection.projected_variable_components( self.edge_plan.storage_plan ) @@ -592,7 +593,7 @@ def _axis_value(self, value: RuntimeValue) -> RuntimeValue: component_values = tuple( ( - component.value, + component.name, self._consumer_component_value(component), ) for component in projected_components @@ -664,13 +665,13 @@ def _axis_value(self, value: RuntimeValue) -> RuntimeValue: materialization_source_metadata=value.materialization_source_metadata, ) - def _consumer_component_value(self, component: AllComponents) -> str: + def _consumer_component_value(self, component: type[Axis]) -> str: component_scope = self.edge_plan.projection.component_scope(component) if component_scope is None: raise RuntimeError( "Artifact input " f"{self.edge_plan.storage_plan.name!r} has no compiled coordinate " - f"for component {component.value!r}." + f"for component {component.name!r}." ) runtime_value = self.axis_scope.value_text_for_component(component) return component_scope.select_runtime_key(runtime_value) @@ -736,7 +737,7 @@ def _matches_execution_scope( ) -> bool: """Match image-set context, preserving declared producer/axis projections.""" - projected_components = ComponentSet.coerce( + projected_components = ComponentSet.of( self.edge_plan.projection.projected_variable_components( self.edge_plan.storage_plan ) @@ -970,7 +971,8 @@ def from_dict(cls, data: Mapping[str, Any]) -> "RuntimeArtifactAddress": "RuntimeArtifactAddress.key.scope.fixed_component_values must be a " "sequence." ) - fixed_values: list[tuple[str, str]] = [] + family = AxisFamily.active() + fixed_values: list[tuple[type[Axis], str]] = [] for item in fixed_component_values: if ( not isinstance(item, Sequence) @@ -981,7 +983,7 @@ def from_dict(cls, data: Mapping[str, Any]) -> "RuntimeArtifactAddress": "Runtime artifact fixed component coordinates must be " "two-item sequences." ) - fixed_values.append((str(item[0]), str(item[1]))) + fixed_values.append((family.named(str(item[0])), str(item[1]))) value_type = data.get("value_type") return cls( key=ArtifactKey( @@ -989,7 +991,8 @@ def from_dict(cls, data: Mapping[str, Any]) -> "RuntimeArtifactAddress": artifact_type=ArtifactType.coerce(str(key["artifact_type"])), scope=RuntimeExecutionAxisScope.from_raw( str(scope["axis_id"]), - component=component, + component=None if component is None else family.named(str(component)), + value=None if value is None else str(value), fixed_component_values=tuple(fixed_values), ), @@ -1194,7 +1197,7 @@ def find( name: str | None = None, artifact_type: ArtifactType | None = None, axis_id: str | None = None, - group_component: AllComponents | None = None, + group_component: type[Axis] | None = None, group_key: str | None = None, match_component: bool = False, match_group: bool = False, diff --git a/openhcs/core/source_binding_workspace.py b/openhcs/core/source_binding_workspace.py index 39f26dfa42..a04af5302c 100644 --- a/openhcs/core/source_binding_workspace.py +++ b/openhcs/core/source_binding_workspace.py @@ -13,7 +13,7 @@ from metaclass_registry import AutoRegisterMeta from polystore.virtual_workspace import SourcePixelRef -from openhcs.constants.constants import AllComponents, Backend, Microscope +from openhcs.constants.constants import Backend, Microscope from openhcs.core.image_shapes import ArrayShape from metaclass_registry.strategies import EnumKeyedStrategyMixin from openhcs.core.runtime_image_values import ( @@ -67,6 +67,7 @@ get_metadata_path, ) from openhcs.core.vfs_protocol import FileManagerLike +from openhcs.core.axes import AxisFamily, ColourAxis, PartitionAxis if TYPE_CHECKING: from openhcs.core.source_workspace_projection import VirtualWorkspaceSourceProjection @@ -527,12 +528,13 @@ def projection( address: OpenHCSPlaneAddress, ) -> SourceProjection: component_labels = dict(candidate.component_labels) - declared_channels = binding.component_values(AllComponents.CHANNEL) - if len(declared_channels) == 1 and source_metadata_values_equal( - declared_channels[0], - address.value_for(AllComponents.CHANNEL), - ): - component_labels[AllComponents.CHANNEL.value] = binding.alias + for colour_axis in AxisFamily.active().with_role(ColourAxis): + declared_colours = binding.component_values(colour_axis) + if len(declared_colours) == 1 and source_metadata_values_equal( + declared_colours[0], + address.value_for(colour_axis), + ): + component_labels[colour_axis.name] = binding.alias return SourcePlaneProjection( address=address, ref=candidate.source_ref, @@ -1066,7 +1068,7 @@ def _candidate_with_binding_components( if current is not None and not source_metadata_values_equal(current, value): raise ValueError( f"Source candidate {candidate.relative_path!r} has conflicting " - f"{component.value!r} values {current!r} and {value!r}." + f"{component.name!r} values {current!r} and {value!r}." ) metadata = with_source_component_metadata(metadata, component, value) for identity in binding.component_identity: @@ -1079,7 +1081,7 @@ def _candidate_with_binding_components( identity.value, ): OriginalSourceMetadata.from_mapping( - {identity.component.value: current} + {identity.component.name: current} ).merge_into( metadata, path=candidate.relative_path, @@ -1089,7 +1091,7 @@ def _candidate_with_binding_components( identity.component, identity.value, ) - component_labels[identity.component.value] = None + component_labels[identity.component.name] = None return replace( candidate, metadata=metadata, @@ -1204,28 +1206,20 @@ def _source_set_projections( ): address = candidate.declared_address else: - address = OpenHCSPlaneAddress.from_values( - well=well, - site=SourceComponentProjectionStrategy.project_component( - AllComponents.SITE, - source_set.metadata, - source_set.index, - ), - channel=SourceComponentProjectionStrategy.project_component( - AllComponents.CHANNEL, - candidate.metadata, - projection_index, - ), - z_index=SourceComponentProjectionStrategy.project_component( - AllComponents.Z_INDEX, - source_set.metadata, - source_set.index, - ), - timepoint=SourceComponentProjectionStrategy.project_component( - AllComponents.TIMEPOINT, - source_set.metadata, - source_set.index, - ), + address = OpenHCSPlaneAddress( + ( + axis, + well + if issubclass(axis, PartitionAxis) + else SourceComponentProjectionStrategy.project_bound_component( + axis, + set_metadata=source_set.metadata, + set_index=source_set.index, + candidate_metadata=candidate.metadata, + candidate_index=projection_index, + ), + ) + for axis in AxisFamily.active().axes ) projections.append( SourceBindingProjectionStrategy.for_enum_member( @@ -1252,7 +1246,7 @@ def _source_set_well(self, source_set: _SourceSet) -> str: fields = self.source_bindings.grouping_metadata_fields if not fields: return SourceComponentProjectionStrategy.project_component( - AllComponents.WELL, + AxisFamily.active().partition_axis(), source_set.metadata, source_set.index, ) @@ -1267,22 +1261,23 @@ def _source_set_well(self, source_set: _SourceSet) -> str: ) group_metadata[field_name] = str(value) - fields_are_well_identity = all( + partition_axis = AxisFamily.active().partition_axis() + fields_are_partition_identity = all( SourceComponentProjectionStrategy.component_for_metadata_field(field) - is AllComponents.WELL + is partition_axis for field in fields ) - if fields_are_well_identity: - well = SourceComponentProjectionStrategy.metadata_component( - AllComponents.WELL, + if fields_are_partition_identity: + partition_value = SourceComponentProjectionStrategy.metadata_component( + partition_axis, group_metadata, ) - if well is None: + if partition_value is None: raise ValueError( - "Source grouping fields declared well identity but did not " - f"resolve one from {group_metadata!r}." + f"Source grouping fields declared {partition_axis.name} identity " + f"but did not resolve one from {group_metadata!r}." ) - return well + return partition_value encoded_fields: list[str] = [] for field_name in fields: @@ -1328,7 +1323,7 @@ def _ungrouped_projections( index, ), ) - for component in AllComponents + for component in AxisFamily.active().axes ), ref=candidate.source_ref, source_metadata=_workspace_source_metadata(candidate), @@ -1435,7 +1430,7 @@ def _projected_candidate_components( candidates: tuple[SourceCandidate, ...], ) -> SourceMetadataMapping: projected: dict[str, str] = {} - for component in AllComponents: + for component in AxisFamily.active().axes: values = { value for candidate in candidates @@ -1452,14 +1447,14 @@ def _projected_candidate_components( if not values: continue value = next(iter(values)) - existing = source_metadata_value(group_metadata, component.value) + existing = source_metadata_value(group_metadata, component.name) if existing is not None and not source_metadata_values_equal(existing, value): raise ValueError( - f"Source set has conflicting {component.value!r} values " + f"Source set has conflicting {component.name!r} values " f"{existing!r} and {value!r}." ) if existing is None: - projected[component.value] = value + projected[component.name] = value return MappingProxyType(projected) diff --git a/openhcs/core/source_bindings.py b/openhcs/core/source_bindings.py index 6b65435782..de00e990c5 100644 --- a/openhcs/core/source_bindings.py +++ b/openhcs/core/source_bindings.py @@ -22,7 +22,7 @@ from python_introspect import Enableable from python_introspect.enableable import EnableableMeta -from openhcs.constants.constants import AllComponents, GroupBy, Microscope +from openhcs.constants.constants import Microscope from openhcs.constants.input_source import InputSource from openhcs.core.artifacts import ( ArtifactInputPlan, @@ -34,7 +34,6 @@ ) from openhcs.core.component_set import ComponentSet from openhcs.core.field_label import FieldLabel -from openhcs.core.components.validation import convert_enum_by_value from openhcs.core.runtime_tabular_values import FieldSpec from openhcs.core.source_metadata import ( SourceMetadataFields, @@ -48,6 +47,8 @@ ) from openhcs.core.xdg_paths import get_openhcs_cache_dir from openhcs.core.source_spatial_domain import SourceSpatialDomain +from openhcs.core.axis_boundaries import AxisChoices +from openhcs.core.axes import Axis, AxisFamily, GroupingDeclaration if TYPE_CHECKING: from openhcs.core.callable_contract import CallableContract @@ -603,8 +604,8 @@ def __post_init__(self) -> None: class ComponentSelector: """Component-axis key/value pair used either to select sources or assign identity.""" - component: AllComponents - """OpenHCS plate component, such as channel, site, Z index, or timepoint.""" + component: Annotated[type[Axis], AxisChoices()] + """Declared axis of the active family, such as channel, site, Z index, or timepoint.""" value: str """Exact semantic value selected or assigned for ``component``.""" @@ -792,13 +793,13 @@ def __post_init__(self) -> None: self.component_identity, ComponentSelector, ) - seen_components: dict[AllComponents, str] = {} + seen_components: dict[type[Axis], str] = {} for selector in component_identity: existing = seen_components.get(selector.component) if existing is not None and existing != selector.value: raise ValueError( f"{type(self).__name__}.component_identity contains " - f"conflicting {selector.component.value!r} values " + f"conflicting {selector.component.name!r} values " f"{existing!r} and {selector.value!r}." ) seen_components[selector.component] = selector.value @@ -843,7 +844,7 @@ def component_identity_with( if existing.value != selector.value: raise ValueError( f"Source assignment {self.alias!r} declares " - f"{selector.component.value!r} identity {existing.value!r}, " + f"{selector.component.name!r} identity {existing.value!r}, " f"but {selector.value!r} was requested." ) return self.component_identity @@ -851,7 +852,7 @@ def component_identity_with( def is_compatible_with_component_group( self, - component: AllComponents, + component: type[Axis], group_key: str, ) -> bool: """Return whether this identity permits one typed execution group.""" @@ -867,7 +868,7 @@ def is_compatible_with_component_group( def requires_cross_group_candidate_resolution( self, - component: AllComponents, + component: type[Axis], group_key: str, ) -> bool: """Return whether assigned identity differs from its selected coordinate.""" @@ -1206,7 +1207,7 @@ def _monochrome_source_data( def component_values( self, - component: AllComponents, + component: type[Axis], *, realized_source_metadata: Iterable[SourceMetadataMapping] | None = None, ) -> tuple[str, ...]: @@ -1229,7 +1230,7 @@ def component_values( return tuple(dict.fromkeys(values)) def _declared_component_values( - self, component: AllComponents + self, component: type[Axis] ) -> tuple[str, ...]: """Resolve exact identity values before selector-derived coordinates.""" for declarations in (self.component_identity, self.selector.components): @@ -1246,17 +1247,17 @@ def component_domains( self, *, realized_source_metadata: Iterable[SourceMetadataMapping] | None = None, - ) -> Mapping[AllComponents, tuple[str, ...]]: + ) -> Mapping[type[Axis], tuple[str, ...]]: """Admit all component domains from the same matched source records.""" domains = { component: values - for component in AllComponents + for component in AxisFamily.active().axes for values in (self._declared_component_values(component),) if values } - if realized_source_metadata is None or len(domains) == len(AllComponents): + if realized_source_metadata is None or len(domains) == len(AxisFamily.active().axes): return domains - realized: dict[AllComponents, list[str]] = {} + realized: dict[type[Axis], list[str]] = {} for metadata in realized_source_metadata: if not self.matches_realized_source_metadata(metadata): continue @@ -1292,7 +1293,7 @@ def input_plan( self, *, group_keys: tuple[str | None, ...], - group_component: AllComponents | None, + group_component: type[Axis] | None, ) -> ArtifactInputPlan: """Project this source declaration into a compiler input plan.""" @@ -1317,7 +1318,7 @@ def requires_selector_resolution(self) -> bool: def requires_step_input_component_stack( self, - components: tuple[AllComponents, ...], + components: tuple[type[Axis], ...], ) -> bool: """Whether resolving this binding needs component-varying step input.""" if self.origin is not SourceBindingOrigin.STEP_INPUT: @@ -1330,17 +1331,12 @@ def requires_step_input_component_stack( selector.component in components for selector in self.selector.components ) - @property - def requires_step_input_channel_stack(self) -> bool: - """Whether resolving this binding needs channel-varying step input.""" - return self.requires_step_input_component_stack((AllComponents.CHANNEL,)) - class SourceBindingDeclarationsMixin: """Shared named-binding view for editable and compiled source plans.""" bindings: tuple[NamedSourceBinding, ...] | None - source_stack_components: tuple[AllComponents, ...] + source_stack_components: tuple[type[Axis], ...] source_spatial_domain: SourceSpatialDomain @property @@ -1429,7 +1425,7 @@ def measurement_source_names(self) -> tuple[str, ...]: def requires_step_input_component_stack( self, - components: tuple[AllComponents, ...], + components: tuple[type[Axis], ...], ) -> bool: """Whether any declaration needs component-resolved step input.""" return any( @@ -1437,11 +1433,6 @@ def requires_step_input_component_stack( for binding in self.binding_declarations ) - @property - def requires_step_input_channel_stack(self) -> bool: - """Whether any declaration needs channel-resolved step input.""" - return self.requires_step_input_component_stack((AllComponents.CHANNEL,)) - @property def requires_pipeline_start_resolution(self) -> bool: """Whether any declaration resolves from the pipeline-start universe.""" @@ -1474,7 +1465,7 @@ def requires_step_input_selector_resolution(self) -> bool: def bindings_for_component_group( self, - component: AllComponents | None, + component: type[Axis] | None, group_key: str | None, ) -> tuple[NamedSourceBinding, ...]: """Return bindings compatible with one typed execution group.""" @@ -1500,14 +1491,14 @@ def bindings_for_component_group( ) if not matching_bindings: raise ValueError( - f"No source binding declares {normalized_component.value} " + f"No source binding declares {normalized_component.name} " f"group {normalized_group_key!r}." ) return matching_bindings def requires_cross_group_candidate_resolution( self, - component: AllComponents, + component: type[Axis], group_key: str, ) -> bool: """Return whether this semantic group must search other source groups.""" @@ -1587,7 +1578,7 @@ def for_represented_source_stack( def for_component_group( self, - component: AllComponents, + component: type[Axis], group_key: str, ) -> Self: """Return these declarations scoped to one typed component group.""" @@ -1616,7 +1607,7 @@ def for_execution_axis_scope( def component_group_keys_for_artifact_specs( self, - component: AllComponents, + component: type[Axis], specs: Iterable[ArtifactSpec], available_artifacts: ArtifactSpecCollection, *, @@ -1898,7 +1889,7 @@ class SourceBindingsConfig(SourceBindingDeclarationsMixin, _SourceBindingPlanBas imported_metadata_tables: tuple[ImportedMetadataTable, ...] = () """External metadata tables joined to source records before matching.""" - source_stack_components: tuple[AllComponents, ...] = () + source_stack_components: tuple[type[Axis], ...] = () """Ordered plate components that form one logical source image stack.""" source_spatial_domain: SourceSpatialDomain = field( @@ -2246,7 +2237,7 @@ def for_input_source(self, input_source: InputSource) -> Self: def source_binding_group_keys_for_group_by( source_bindings: SourceBindingDeclarationsMixin, - group_by: GroupBy, + group_by: type[GroupingDeclaration], *, realized_source_metadata: Iterable[SourceMetadataMapping] | None = None, ) -> tuple[str, ...]: @@ -2257,10 +2248,10 @@ def source_binding_group_keys_for_group_by( "source_binding_group_keys_for_group_by requires " f"SourceBindingDeclarationsMixin, got {type(source_bindings).__name__}." ) - resolved_group_by = group_by if isinstance(group_by, GroupBy) else GroupBy(group_by) - if resolved_group_by.value is None: + grouping_axes = group_by.grouping_axes() + if not grouping_axes: return () - component = AllComponents.from_value(resolved_group_by.value) + (component,) = grouping_axes realized_metadata = ( None if realized_source_metadata is None else tuple(realized_source_metadata) ) @@ -2316,7 +2307,7 @@ class CompiledSourceBindingPlan(SourceBindingDeclarationsMixin, _SourceBindingPl registry_key: ClassVar[str] = "compiled" bindings: tuple[NamedSourceBinding, ...] = () - source_stack_components: tuple[AllComponents, ...] = () + source_stack_components: tuple[type[Axis], ...] = () source_spatial_domain: SourceSpatialDomain = field( default_factory=SourceSpatialDomain ) @@ -2416,7 +2407,7 @@ def has_primary_content(self) -> bool: def for_main_flow_scope( self, *, - component: AllComponents | None, + component: type[Axis] | None, group_key: str | None, main_flow_refs: tuple[ArtifactSpecRef, ...] | None, ) -> "CompiledSourceBindingPlan | None": @@ -2449,7 +2440,7 @@ def __reduce__( tuple[MetadataExtractionRule, ...], SourceBindingMatchPlan | None, tuple[FieldSpec, ...], - tuple[AllComponents, ...], + tuple[type[Axis], ...], SourceSpatialDomain, ], ]: @@ -2483,7 +2474,7 @@ def _from_pickled_state( metadata_rules: tuple[MetadataExtractionRule, ...], match_plan: SourceBindingMatchPlan | None, metadata_fields: tuple[FieldSpec, ...], - source_stack_components: tuple[AllComponents, ...], + source_stack_components: tuple[type[Axis], ...], source_spatial_domain: SourceSpatialDomain, ) -> CompiledSourceBindingPlan: return cls( @@ -2547,16 +2538,12 @@ def normalized(self) -> Mapping[str, SourceMetadataMapping]: EMPTY_SOURCE_BINDINGS = StepSourceBindingsConfig() -def _coerce_component(value: Any, field_name: str) -> Any: - if isinstance(value, AllComponents): - return value - if isinstance(value, Enum) and ( - converted := convert_enum_by_value(value, AllComponents) - ): - return converted - return AllComponents( - value, - ) +def _coerce_component(value: Any, field_name: str) -> type[Axis]: + try: + return AxisFamily.active().require(value) + except TypeError as error: + raise TypeError(f"{field_name}: {error}") from error + def _require_name(value: str, field_name: str) -> None: diff --git a/openhcs/core/source_image_provenance.py b/openhcs/core/source_image_provenance.py index 45dd7a4ee9..4b67d8783b 100644 --- a/openhcs/core/source_image_provenance.py +++ b/openhcs/core/source_image_provenance.py @@ -16,7 +16,6 @@ from python_introspect.validation import validate_annotation_value from python_introspect import to_jsonable -from openhcs.constants.constants import AllComponents from openhcs.core.source_metadata import ( SOURCE_PLANE_COUNT_FIELD, SOURCE_PLANE_INDEX_FIELD, @@ -34,6 +33,7 @@ source_metadata_value, with_source_component_metadata, ) +from openhcs.core.axes import Axis, AxisFamily, StackAxis SourceComponentMetadata = SourceMetadataMapping SourceImageProvenancePlanePathValues = tuple[str | None, ...] @@ -452,7 +452,7 @@ def from_component_domain( Neither filenames, page counts, nor plate cardinalities establish this coordinate domain. The caller must supply its original declaration. """ - component_names = frozenset(component.value for component in AllComponents) + component_names = frozenset(AxisFamily.active().names()) if ( len(aggregate_components) != 1 or set(fixed_components) & set(aggregate_components) @@ -1059,7 +1059,7 @@ def required_scalar_components( for contributor in contributors ) reduced = set() - for component in AllComponents: + for component in AxisFamily.active().axes: if component in scalar_components: continue if len(contributor_components) < 2 or not all( @@ -1070,7 +1070,7 @@ def required_scalar_components( value for values in contributor_components for value in values[component] ) if len(values) > 1: - reduced.add(component.value) + reduced.add(component.name) return tuple(component for component in component_order if component not in reduced) def image_set_identities( @@ -1234,7 +1234,7 @@ def for_source_image(self, source_image_name: str) -> "SourceImageProvenance": def varying_plane_component_values( self, - components: Sequence[AllComponents], + components: Sequence[type[Axis]], ) -> dict[str, tuple[SourceMetadataScalar, ...]]: """Return exact component values that vary across declared source planes.""" if not components or self.source_plane_count <= 1: @@ -1255,13 +1255,13 @@ def varying_plane_component_values( if any(value is None for value in values): continue if len(frozenset(values)) > 1: - values_by_component[component.value] = values + values_by_component[component.name] = values return values_by_component def require_common_component_values( self, - components: Sequence[AllComponents], - ) -> tuple[tuple[AllComponents, str], ...]: + components: Sequence[type[Axis]], + ) -> tuple[tuple[type[Axis], str], ...]: """Return fixed component values shared by every represented source plane.""" if not components: @@ -1274,7 +1274,7 @@ def require_common_component_values( if self.source_plane_count else (self.source_component_metadata or {},) ) - values: list[tuple[AllComponents, str]] = [] + values: list[tuple[type[Axis], str]] = [] for component in components: metadata_values = tuple( source_component_metadata_value( @@ -1286,12 +1286,12 @@ def require_common_component_values( if any(value is None for value in metadata_values): raise ValueError( "Source provenance does not declare component " - f"{component.value!r} on every represented plane." + f"{component.name!r} on every represented plane." ) unique_values = tuple(dict.fromkeys(metadata_values)) if len(unique_values) != 1: raise ValueError( - f"Source provenance component {component.value!r} is not fixed: " + f"Source provenance component {component.name!r} is not fixed: " f"{unique_values!r}." ) values.append((component, unique_values[0])) @@ -1591,9 +1591,9 @@ class SourcePlaneIndexedMetadata: source_plane_count: int @staticmethod - def projected_component() -> AllComponents: - """Return the component represented by indexed source-plane metadata.""" - return AllComponents.Z_INDEX + def projected_component() -> type[Axis]: + """Return the stack axis that indexed source-plane metadata represents.""" + return AxisFamily.active().one(StackAxis) @classmethod def from_metadata( @@ -1766,14 +1766,16 @@ def component_metadata_for_plane( SOURCE_PLANE_INDEX_FIELD: str(plane_index), SOURCE_PLANE_COUNT_FIELD: str(self.source_plane_count), }, - components=((AllComponents.Z_INDEX, self.z_index_for_plane(plane_index)),), + components=( + (self.projected_component(), self.z_index_for_plane(plane_index)), + ), ) return SourceMetadataFields.readonly_snapshot(metadata) def z_index_for_plane(self, plane_index: int) -> int: scalar_z_index = source_component_metadata_value( self.scalar_metadata, - AllComponents.Z_INDEX, + self.projected_component(), ) if scalar_z_index is None: return plane_index + 1 @@ -2118,7 +2120,7 @@ def is_empty(self) -> bool: return not self.axes def ordered_axes(self) -> tuple[str, ...]: - component_order = AllComponents.ordered_names() + component_order = AxisFamily.active().names() ordered_known = tuple(axis for axis in component_order if axis in self.axes) ordered_unknown = tuple(sorted(self.axes.difference(ordered_known))) return ordered_known + ordered_unknown @@ -2174,37 +2176,37 @@ def provenance_planes( ) @staticmethod - def component_for_axis(axis: str) -> AllComponents: - component = AllComponents.from_value(axis) - if component is None: + def component_for_axis(axis: str) -> type[Axis]: + if axis not in AxisFamily.active().names(): raise ValueError( "Variable component axis is not an OpenHCS component: " f"{axis!r}." ) + component = AxisFamily.active().named(axis) return component @staticmethod def projected_axis_value( metadata: SourceComponentMetadata, - component: AllComponents, + component: type[Axis], plane_index: int, ) -> int: current = source_component_metadata_raw_value(metadata, component) if current is None: raise ValueError( "Variable component axis projection requires scalar " - f"{component.value!r} metadata." + f"{component.name!r} metadata." ) if isinstance(current, bool): raise ValueError( "Variable component axis " - f"{component.value!r} must be numeric, got bool." + f"{component.name!r} must be numeric, got bool." ) try: base_value = int(current) except (TypeError, ValueError) as exc: raise ValueError( "Variable component axis " - f"{component.value!r} must be numeric, got {current!r}." + f"{component.name!r} must be numeric, got {current!r}." ) from exc return base_value + plane_index diff --git a/openhcs/core/source_matching.py b/openhcs/core/source_matching.py index ebc9880066..2f3c806132 100644 --- a/openhcs/core/source_matching.py +++ b/openhcs/core/source_matching.py @@ -13,7 +13,6 @@ from metaclass_registry import AutoRegisterMeta -from openhcs.constants.constants import AllComponents from polystore.formats import get_format_from_extension from openhcs.core.component_set import ComponentSet from openhcs.core.source_bindings import ( @@ -41,6 +40,7 @@ source_metadata_scalar, ) from openhcs.core.source_path_identity import source_path_identity_key +from openhcs.core.axes import Axis, AxisFamily if TYPE_CHECKING: from openhcs.core.config import PipelineConfig @@ -392,7 +392,7 @@ class SourceImageSetComponentRole(Enum): class SourceImageSetIdentityPolicy: """Nominal policy for reducing source plane metadata to image-set identity.""" - plane_member_components: frozenset[AllComponents] = frozenset() + plane_member_components: frozenset[type[Axis]] = frozenset() def __post_init__(self) -> None: object.__setattr__( @@ -401,17 +401,17 @@ def __post_init__(self) -> None: frozenset(self.plane_member_components), ) - def role(self, component: AllComponents) -> SourceImageSetComponentRole: + def role(self, component: type[Axis]) -> SourceImageSetComponentRole: """Return whether a component identifies the image set or a plane in it.""" if component in self.plane_member_components: return SourceImageSetComponentRole.IMAGE_PLANE_MEMBER return SourceImageSetComponentRole.IMAGE_SET_AXIS - def identity_components(self) -> tuple[AllComponents, ...]: + def identity_components(self) -> tuple[type[Axis], ...]: """Return generated source components that identify one image set.""" return tuple( component - for component in AllComponents + for component in AxisFamily.active().axes if self.role(component) is SourceImageSetComponentRole.IMAGE_SET_AXIS ) @@ -422,7 +422,7 @@ def from_plane_member_fields( ) -> "SourceImageSetIdentityPolicy": """Return the exact image-plane membership declared by the step stack.""" - plane_member_components: set[AllComponents] = set() + plane_member_components: set[type[Axis]] = set() for field in fields: component = source_metadata_component(field) if component is None: @@ -433,7 +433,7 @@ def from_plane_member_fields( plane_member_components.add(component) return cls(frozenset(plane_member_components)) - def is_identity_component(self, component: AllComponents) -> bool: + def is_identity_component(self, component: type[Axis]) -> bool: """Return whether a metadata component participates in image-set identity.""" return self.role(component) is SourceImageSetComponentRole.IMAGE_SET_AXIS @@ -453,7 +453,7 @@ def from_source_bindings( cls, source_bindings: SourceBindingDeclarationsMixin, *, - group_component: AllComponents | None = None, + group_component: type[Axis] | None = None, ) -> "SourceImageSetIdentityPolicy": """Return image-plane membership declared by source and group semantics. @@ -471,7 +471,7 @@ def from_source_bindings( bindings = source_bindings.primary_plane_bindings shared_components = frozenset( component - for component in AllComponents + for component in AxisFamily.active().axes if len(bindings) > 1 for values in ( tuple(binding.component_values(component) for binding in bindings), @@ -510,8 +510,9 @@ def from_pipeline_config( group_by = pipeline_config.processing_config.group_by group_component = ( None - if group_by is None or group_by.value is None - else ComponentSet.coerce_component(group_by) + if group_by is None or not group_by.grouping_axes() + else group_by.grouping_axes()[0] + ) source_bindings = resolve_lazy_configurations_for_serialization( pipeline_config.source_bindings_config @@ -542,7 +543,7 @@ def components_from_metadata( ) -> tuple[tuple[str, str], ...]: """Return ordered source image-set components from one metadata mapping.""" return tuple( - (component.value, value) + (component.name, value) for component in policy.identity_components() if ( value := SourceComponentProjectionStrategy.metadata_component( @@ -658,7 +659,7 @@ def merge_source_metadata( component = source_metadata_component(key) canonical_component_values_match = ( component is not None - and key == component.value + and key == component.name and str(existing) == str(normalized_value) ) if ( @@ -689,7 +690,7 @@ def overlay_source_metadata( overlaid = dict(metadata) projected_components = { component: value - for component in AllComponents + for component in AxisFamily.active().axes if ( value := SourceComponentProjectionStrategy.metadata_component( component, @@ -767,7 +768,7 @@ def source_metadata_value( def source_component_metadata_value( metadata: SourceMetadataMapping, - component: AllComponents, + component: type[Axis], ) -> str | None: """Return metadata for an OpenHCS component across canonical and alias fields.""" return SourceComponentProjectionStrategy.metadata_component(component, metadata) @@ -775,11 +776,11 @@ def source_component_metadata_value( def source_component_metadata_items( metadata: SourceMetadataMapping, -) -> tuple[tuple[AllComponents, SourceMetadataScalar], ...]: +) -> tuple[tuple[type[Axis], SourceMetadataScalar], ...]: """Return component metadata through each registered nominal projection.""" return tuple( (component, value) - for component in AllComponents + for component in AxisFamily.active().axes if ( value := SourceComponentProjectionStrategy.metadata_component( component, @@ -792,7 +793,7 @@ def source_component_metadata_items( def source_component_metadata_raw_value( metadata: SourceMetadataMapping, - component: AllComponents, + component: type[Axis], ) -> SourceMetadataScalar: """Return metadata through the registered nominal component projection.""" return SourceComponentProjectionStrategy.metadata_component(component, metadata) @@ -835,7 +836,7 @@ def semantic_source_metadata_value( def source_component_metadata_values( metadata: SourceMetadataMapping, - component: AllComponents, + component: type[Axis], ) -> tuple[str, ...]: """Return all metadata values that semantically describe a component.""" return SourceMetadataFields.component_values(metadata, component) @@ -843,7 +844,7 @@ def source_component_metadata_values( def with_source_component_metadata( metadata: SourceMetadataMapping, - component: AllComponents, + component: type[Axis], value: SourceMetadataScalar, ) -> SourceMetadataMapping: """Return metadata with one canonical component value. @@ -926,9 +927,8 @@ def matching_indices( def multiprocessing_axis_scope(self) -> "SourceAxisMetadataScope": """Return the stable worker-axis partition of this runtime scope.""" - from openhcs.constants.constants import get_multiprocessing_axis - multiprocessing_axis = ComponentSet.coerce_component(get_multiprocessing_axis()) + multiprocessing_axis = AxisFamily.active().require(AxisFamily.active().partition_axis()) return type(self).from_component_values( tuple( (component, value) diff --git a/openhcs/core/source_metadata.py b/openhcs/core/source_metadata.py index ed58aee7c0..fab1ce1e35 100644 --- a/openhcs/core/source_metadata.py +++ b/openhcs/core/source_metadata.py @@ -5,18 +5,25 @@ from abc import ABC, abstractmethod from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence from dataclasses import dataclass, field -from enum import Enum, StrEnum +from enum import StrEnum from functools import lru_cache from math import isfinite from pathlib import Path from types import MappingProxyType from typing import ClassVar, NoReturn, Self, TYPE_CHECKING, TypeAlias, TypeVar -from metaclass_registry import AutoRegisterMeta from zmqruntime.viewer_protocol import ViewerWireField -from openhcs.constants.constants import AllComponents -from metaclass_registry.strategies import EnumKeyedStrategyMixin +from openhcs.core.axes import ( + Axis, + AxisFamily, + AxisRoleKeyedStrategyMixin, + ColourAxis, + PartitionAxis, + StackAxis, + TileAxis, + TimeAxis, +) if TYPE_CHECKING: from openhcs.core.source_bindings import MetadataExtractionRule @@ -56,11 +63,11 @@ class SourceMetadataFields(Mapping[str, SourceMetadataValue]): @staticmethod def canonical_component_value( - component: AllComponents | None, + component: type[Axis] | None, value: SourceMetadataScalar, ) -> str | int: """Canonicalize numeric variable coordinates while retaining labels.""" - if component is None or not component.is_variable_axis(): + if component is None or issubclass(component, PartitionAxis): return str(value) value_text = str(value) return int(value_text) if value_text.isdecimal() else value_text @@ -129,14 +136,14 @@ def __eq__(self, other: object) -> bool: """Compare through the declared record or mapping namespace.""" def _derived_view( - self, key: str | AllComponents, derive: Callable[[], _MetadataViewT] + self, key: str | type[Axis], derive: Callable[[], _MetadataViewT] ) -> _MetadataViewT: return derive() @staticmethod def _view( metadata: SourceMetadataMapping, - key: str | AllComponents, + key: str | type[Axis], derive: Callable[[], _MetadataViewT], ) -> _MetadataViewT: if isinstance(metadata, SourceMetadataFields): @@ -265,12 +272,12 @@ def literal_field_types( @classmethod def component_value( - cls, metadata: SourceMetadataMapping, component: AllComponents + cls, metadata: SourceMetadataMapping, component: type[Axis] ) -> str | None: return cls._view( metadata, component, - lambda: SourceComponentProjectionStrategy.for_enum_member( + lambda: SourceComponentProjectionStrategy.for_axis( component ).metadata_value(metadata), ) @@ -278,11 +285,11 @@ def component_value( @classmethod def _ordered_component_fields( cls, metadata: SourceMetadataMapping - ) -> Iterator[tuple[AllComponents, SourceMetadataNonNullScalar]]: + ) -> Iterator[tuple[type[Axis], SourceMetadataNonNullScalar]]: """Admit component fields once, with canonical spelling before aliases.""" scalars = cls.scalar_items(metadata) cls.original_items(metadata) - aliases: list[tuple[AllComponents, SourceMetadataNonNullScalar]] = [] + aliases: list[tuple[type[Axis], SourceMetadataNonNullScalar]] = [] for name, value in scalars: if value is None: continue @@ -291,7 +298,7 @@ def _ordered_component_fields( if component is None: continue item = (component, value) - if name == component.value: + if name == component.name: yield item else: aliases.append(item) @@ -299,7 +306,7 @@ def _ordered_component_fields( @classmethod def component_values( - cls, metadata: SourceMetadataMapping, component: AllComponents + cls, metadata: SourceMetadataMapping, component: type[Axis] ) -> tuple[str, ...]: """Read only the requested component from the current field admission.""" return tuple(dict.fromkeys( @@ -311,9 +318,9 @@ def component_values( @classmethod def component_domains( cls, metadata: SourceMetadataMapping - ) -> Mapping[AllComponents, tuple[str, ...]]: + ) -> Mapping[type[Axis], tuple[str, ...]]: """Expand all ordered component domains from one current field admission.""" - domains: dict[AllComponents, list[str]] = {} + domains: dict[type[Axis], list[str]] = {} for component, value in cls._ordered_component_fields(metadata): domains.setdefault(component, []).append(str(value)) return { @@ -363,7 +370,7 @@ def with_fields( updates: SourceMetadataMapping, *, without: Iterable[str] = (), - components: Iterable[tuple[AllComponents, SourceMetadataScalar]] = (), + components: Iterable[tuple[type[Axis], SourceMetadataScalar]] = (), after_components: SourceMetadataMapping | None = None, ) -> SourceMetadataMapping: excluded = frozenset(without) @@ -376,7 +383,7 @@ def with_fields( if key == ORIGINAL_SOURCE_METADATA_FIELD or source_metadata_component(str(key)) is not component } - fields[component.value] = str(value) + fields[component.name] = str(value) if after_components is not None: fields.update(after_components) return cls.derived_mapping(metadata, fields) @@ -385,7 +392,7 @@ def with_fields( def with_component( cls, metadata: SourceMetadataMapping, - component: AllComponents, + component: type[Axis], value: SourceMetadataScalar, ) -> SourceMetadataMapping: return cls.with_fields(metadata, {}, components=((component, value),)) @@ -400,7 +407,7 @@ def with_missing_from( () if isinstance(metadata, SourceMetadataFields) and metadata._admitted_components_complete - else AllComponents + else AxisFamily.active().axes ) for component in components: if cls.component_value(current, component) is not None: @@ -409,7 +416,7 @@ def with_missing_from( if value is not None: if merged is None: merged = dict(metadata) - merged[component.value] = value + merged[component.name] = value current = merged if cls.literal_value(metadata, "extension") is None: extension = cls.literal_value(fallback, "extension") @@ -451,7 +458,7 @@ class OwnedSourceMetadataFields(SourceMetadataFields): _field_index: Mapping[str, SourceMetadataValue] = field( init=False, repr=False, compare=False ) - _views: dict[str | AllComponents, object] = field( + _views: dict[str | type[Axis], object] = field( default_factory=dict, init=False, repr=False, compare=False ) _cacheable: bool = field(init=False, repr=False, compare=False) @@ -531,7 +538,7 @@ def metadata_contents(self) -> SourceMetadataMapping: return self._field_index def _derived_view( - self, key: str | AllComponents, derive: Callable[[], _MetadataViewT] + self, key: str | type[Axis], derive: Callable[[], _MetadataViewT] ) -> _MetadataViewT: if not self._cacheable: return derive() @@ -542,7 +549,7 @@ def _derived_view( @property def _admitted_components_complete(self) -> bool: return self._cacheable and all( - self._views.get(component) is not None for component in AllComponents + self._views.get(component) is not None for component in AxisFamily.active().axes ) def _literal_value(self, key: str) -> SourceMetadataScalar: @@ -1093,9 +1100,13 @@ def layer_coordinate_kwargs( units = ["dimensionless"] * len(labels) scale[-2:] = self.spacing_for_ndim(2) units[-2:] = (self.native_coordinate_unit,) * 2 - z_component = AllComponents.Z_INDEX.value - if len(self.values_zyx) == 3 and z_component in labels: - z_axis = labels.index(z_component) + stack_labels = tuple( + axis.name + for axis in AxisFamily.active().with_role(StackAxis) + if axis.name in labels + ) + if len(self.values_zyx) == 3 and stack_labels: + z_axis = labels.index(stack_labels[0]) scale[z_axis] = self.spacing_for_ndim(3)[0] units[z_axis] = self.native_coordinate_unit return {"scale": tuple(scale), "units": tuple(units)} @@ -1134,35 +1145,53 @@ def source_metadata_field_identity(field: str) -> str: @lru_cache(maxsize=256) -def source_metadata_component(field: str) -> AllComponents | None: +def source_metadata_component(field: str) -> type[Axis] | None: """Return the nominal component owner of a metadata field.""" return SourceComponentProjectionStrategy.component_for_metadata_field(field) -class SourceComponentProjectionStrategy( - EnumKeyedStrategyMixin[AllComponents], - ABC, - metaclass=AutoRegisterMeta, -): - """Project one OpenHCS component through its nominal enum-owned leaf.""" +class SourceComponentProjectionStrategy(AxisRoleKeyedStrategyMixin, ABC): + """Project one axis through the leaf owning its role.""" - strategy_key: ClassVar[AllComponents | None] = None metadata_collection_field: ClassVar[str] metadata_field_groups: ClassVar[tuple[tuple[str, ...], ...]] = () + bound_per_candidate: ClassVar[bool] = False + """Each bound source candidate carries its own value (one per binding).""" @classmethod def project_component( cls, - component: AllComponents, + component: type[Axis], metadata: SourceMetadataMapping, image_set_index: int, ) -> str: - return cls.for_enum_member(component).project(metadata, image_set_index) + return cls.for_axis(component).project(metadata, image_set_index) + + @classmethod + def project_bound_component( + cls, + component: type[Axis], + *, + set_metadata: SourceMetadataMapping, + set_index: int, + candidate_metadata: SourceMetadataMapping, + candidate_index: int, + ) -> str: + """Project one axis of a bound source set. + + Axes whose role is bound per candidate read the candidate; every other + axis reads the shared source set. + """ + + strategy = cls.for_axis(component) + if strategy.bound_per_candidate: + return strategy.project(candidate_metadata, candidate_index) + return strategy.project(set_metadata, set_index) @classmethod def metadata_component( cls, - component: AllComponents, + component: type[Axis], metadata: SourceMetadataMapping, ) -> str | None: return SourceMetadataFields.component_value(metadata, component) @@ -1171,11 +1200,13 @@ def metadata_component( def component_for_metadata_field( cls, field: str, - ) -> AllComponents | None: + ) -> type[Axis] | None: + family = AxisFamily.active() owners = tuple( - strategy_type.strategy_key - for strategy_type in cls.registered_strategy_types() + axis + for strategy_type in cls.role_strategy_types() if strategy_type.owns_metadata_field(field) + for axis in family.with_role(strategy_type.implements_role) ) if len(owners) > 1: raise RuntimeError( @@ -1228,7 +1259,7 @@ def project( class WellSourceComponentProjection(SourceComponentProjectionStrategy): - strategy_key = AllComponents.WELL + implements_role = PartitionAxis metadata_collection_field = "wells" metadata_field_groups = ( ("well",), @@ -1256,7 +1287,7 @@ def project( class SiteSourceComponentProjection(SourceComponentProjectionStrategy): - strategy_key = AllComponents.SITE + implements_role = TileAxis metadata_collection_field = "sites" metadata_field_groups = (("site", "imagenumber"),) @@ -1271,15 +1302,20 @@ def project( if any( SourceComponentProjectionStrategy.metadata_component(component, metadata) is not None - for component in (AllComponents.Z_INDEX, AllComponents.TIMEPOINT) + for component in ( + *AxisFamily.active().with_role(StackAxis), + *AxisFamily.active().with_role(TimeAxis), + ) ): return "1" return str(image_set_index + 1) class ChannelSourceComponentProjection(SourceComponentProjectionStrategy): - strategy_key = AllComponents.CHANNEL + implements_role = ColourAxis metadata_collection_field = "channels" + bound_per_candidate = True + metadata_field_groups = (("channel", "channelnumber"),) def project( @@ -1291,7 +1327,7 @@ def project( class ZIndexSourceComponentProjection(SourceComponentProjectionStrategy): - strategy_key = AllComponents.Z_INDEX + implements_role = StackAxis metadata_collection_field = "z_indexes" metadata_field_groups = (("zindex", "z", "zplane", "zslice", "plane", "slice"),) @@ -1305,8 +1341,9 @@ def project( class TimepointSourceComponentProjection(SourceComponentProjectionStrategy): - strategy_key = AllComponents.TIMEPOINT + implements_role = TimeAxis metadata_collection_field = "timepoints" + metadata_field_groups = (("timepoint", "time", "framenumber", "frame"),) def project( diff --git a/openhcs/core/source_projection.py b/openhcs/core/source_projection.py index 2deefe36ea..263c652cf1 100644 --- a/openhcs/core/source_projection.py +++ b/openhcs/core/source_projection.py @@ -14,10 +14,9 @@ from polystore.virtual_workspace import SourcePixelRef -from openhcs.constants.constants import AllComponents 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.components.component_values import AxisValues from openhcs.core.runtime_image_values import ImagePayloadMetadata from openhcs.core.source_bindings import ( SOURCE_BINDING_ALIAS_METADATA_FIELD, @@ -43,6 +42,7 @@ source_metadata_scalar, ) from python_introspect import to_jsonable +from openhcs.core.axes import Axis, AxisFamily, PartitionAxis, StackAxis, TileAxis class SourceDatasetConflictError(ValueError): @@ -61,61 +61,37 @@ def metadata_payload(self) -> Mapping[str, Any]: class OpenHCSPlaneAddress: """Canonical OpenHCS logical address for one image plane.""" - _components: OpenHCSComponentValues[str] + _components: AxisValues[str] def __init__( self, - component_values: Iterable[tuple[AllComponents, object]], + component_values: Iterable[tuple[type[Axis], object]], ) -> None: - components = OpenHCSComponentValues(component_values) - normalized_values: list[tuple[AllComponents, str]] = [] + components = AxisValues(component_values) + normalized_values: list[tuple[type[Axis], str]] = [] for component, value in components.items(): if value is None or value == "": raise ValueError( - f"{component.value} cannot be empty in an OpenHCS plane address." + f"{component.name} cannot be empty in an OpenHCS plane address." ) - normalized = str(value) - if component is not AllComponents.WELL and normalized.isdecimal(): - normalized = str(int(normalized)) - normalized_values.append((component, normalized)) + normalized_values.append((component, component.normalize_value(value))) object.__setattr__( - self, "_components", OpenHCSComponentValues(normalized_values) + self, "_components", AxisValues(normalized_values) ) - @classmethod - def from_values( - cls, - well: object, - site: object, - channel: object, - z_index: object, - timepoint: object, - ) -> "OpenHCSPlaneAddress": - """Bind one plane emitted by an API with named native coordinates.""" - - return cls( - ( - (AllComponents.WELL, well), - (AllComponents.SITE, site), - (AllComponents.CHANNEL, channel), - (AllComponents.Z_INDEX, z_index), - (AllComponents.TIMEPOINT, timepoint), - ) - ) - - def component_values(self) -> OpenHCSComponentValues[str]: - """Return address values keyed by OpenHCS component enum.""" + def component_values(self) -> AxisValues[str]: + """Return address values keyed by declared axis.""" return self._components - def value_for(self, component: AllComponents) -> str: + def value_for(self, component: type[Axis]) -> str: """Return one logical coordinate through its nominal declaration.""" return self._components.value_for(component) def with_value( self, - component: AllComponents, + component: type[Axis], value: object, ) -> "OpenHCSPlaneAddress": """Return an address with one declared coordinate replaced.""" @@ -139,7 +115,7 @@ def as_component_metadata(self) -> dict[str, str]: def parsed_component_values( self, - ) -> tuple[tuple[AllComponents, str | int], ...]: + ) -> tuple[tuple[type[Axis], str | int], ...]: """Project canonical identities onto parsed filename scalar values.""" return tuple( @@ -171,7 +147,7 @@ def component_token(value: object) -> str: @classmethod def from_component_values( cls, - component_values: Iterable[tuple[AllComponents, object]], + component_values: Iterable[tuple[type[Axis], object]], ) -> "OpenHCSPlaneAddress": """Create an address from nominal OpenHCS component values.""" @@ -191,48 +167,44 @@ def from_complete_source_metadata( component, source_component_metadata_raw_value(metadata, component), ) - for component in AllComponents + for component in AxisFamily.active().axes ) 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[^_.]+)" - r"(?:_[^.]*)?(?P(?:\.\w+)+)$" - ) + def filename(self, extension: str = ".tif") -> str: + """Spell this address as an OpenHCS plane filename. - def filename( - self, - extension: str = ".tif", - site_padding: int = 3, - z_padding: int = 3, - timepoint_padding: int = 3, - ) -> str: + The partition value leads; each variable axis follows in declaration + order as its declared filename token. + """ + + family = AxisFamily.active() return ( - f"{self.value_for(AllComponents.WELL)}" - f"_s{_padded(self.value_for(AllComponents.SITE), site_padding)}" - f"_w{self.value_for(AllComponents.CHANNEL)}" - f"_z{_padded(self.value_for(AllComponents.Z_INDEX), z_padding)}" - f"_t{_padded(self.value_for(AllComponents.TIMEPOINT), timepoint_padding)}" - f"{extension}" + self.value_for(family.partition_axis()) + + "".join( + f"_{axis.filename_token(self.value_for(axis))}" + for axis in family.variable_axes() + ) + + extension ) @classmethod def from_filename(cls, filename: str) -> "OpenHCSPlaneFilename | None": - match = cls._filename_pattern.match(Path(str(filename)).name) + family = AxisFamily.active() + match = _plane_filename_pattern(family).match(Path(str(filename)).name) if match is None: return None - values = match.groupdict() + ordered_axes = (family.partition_axis(), *family.variable_axes()) return OpenHCSPlaneFilename( address=cls.from_component_values( ( - (component, _coordinate_value(values[component.value])) - for component in AllComponents + (axis, _coordinate_value(match.group(f"axis{index}"))) + for index, axis in enumerate(ordered_axes) ) ), - extension=values["extension"], + extension=match.group("extension"), ) @@ -432,7 +404,7 @@ def component_labels_for_address( projected_values = address.component_values() for component, source_value in self.declared_address.component_values().items(): if source_value != projected_values[component]: - labels[component.value] = None + labels[component.name] = None return MappingProxyType(labels) def identity_key(self) -> tuple[object, ...]: @@ -575,9 +547,12 @@ def _validated_candidates(self) -> tuple[SourceCandidate, ...]: self._record_identity( sample_groups, store_identity.sample_group_key, - ( - address.value_for(AllComponents.WELL), - address.value_for(AllComponents.SITE), + tuple( + address.value_for(axis) + for axis in ( + *AxisFamily.active().with_role(PartitionAxis), + *AxisFamily.active().with_role(TileAxis), + ) ), "sample group", ) @@ -644,7 +619,7 @@ def identity_key(self) -> tuple[object, ...]: return (self.projection_role, self.address) - def component_value(self, component: AllComponents) -> str | None: + def component_value(self, component: type[Axis]) -> str | None: """Return one scalar projection coordinate when the projection has one.""" if self.address is None: @@ -653,7 +628,7 @@ def component_value(self, component: AllComponents) -> str | None: def source_component_values( self, - ) -> tuple[tuple[AllComponents, str], ...]: + ) -> tuple[tuple[type[Axis], str], ...]: """Return scalar coordinates represented by this projection.""" if self.address is None: @@ -856,9 +831,11 @@ def identity_key(self) -> tuple[object, ...]: def image_plane_cohort_key( self, image_set_policy: SourceImageSetIdentityPolicy ) -> tuple[object, ...] | None: - """Derive an exact scalar Z cohort, or retain this whole image export.""" + """Derive an exact scalar stack cohort, or retain this whole image export.""" + stack_axes = AxisFamily.active().with_role(StackAxis) if ( - image_set_policy.is_identity_component(AllComponents.Z_INDEX) + not stack_axes + or image_set_policy.is_identity_component(stack_axes[0]) or self.address is None ): return None @@ -869,11 +846,11 @@ def image_plane_cohort_key( tuple( (component, value) for component, value in self.source_component_values() - if component is not AllComponents.Z_INDEX + if component is not stack_axes[0] ), ) - def component_value(self, component: AllComponents) -> str | None: + def component_value(self, component: type[Axis]) -> str | None: """Return scalar address or runtime-scope identity for one component.""" value = SourceProjection.component_value(self, component) @@ -883,7 +860,7 @@ def component_value(self, component: AllComponents) -> str | None: def source_component_values( self, - ) -> tuple[tuple[AllComponents, str], ...]: + ) -> tuple[tuple[type[Axis], str], ...]: """Return scalar address or runtime execution-scope coordinates.""" values = SourceProjection.source_component_values(self) @@ -1030,9 +1007,9 @@ def image_export_groups( groups.setdefault(key, []).append(projection) ordered_groups = [] for group in groups.values(): + stack_axis = AxisFamily.active().one(StackAxis) z_indexes = tuple( - projection.component_value(AllComponents.Z_INDEX) - for projection in group + projection.component_value(stack_axis) for projection in group ) if any(value is None or not value.isdecimal() for value in z_indexes): raise ValueError( @@ -1045,10 +1022,9 @@ def image_export_groups( key=lambda item: item[0], ) ) - first_z_index = int(ordered[0].component_value(AllComponents.Z_INDEX)) + first_z_index = int(ordered[0].component_value(stack_axis)) if tuple( - int(projection.component_value(AllComponents.Z_INDEX)) - for projection in ordered + int(projection.component_value(stack_axis)) for projection in ordered ) != tuple(range(first_z_index, first_z_index + len(ordered))): raise ValueError("Exported Z planes must be unique and contiguous.") ordered_groups.append(ordered) @@ -1164,15 +1140,15 @@ def component_metadata( self, projection_set: SourceProjectionSet, *, - labels: Mapping[AllComponents, Mapping[str, str | None] | None] | None = None, + labels: Mapping[type[Axis], Mapping[str, str | None] | None] | None = None, ) -> dict[str, dict[str, str | None]]: """Project inventory keys from typed addresses; labels cannot add keys.""" metadata = {} - for component in AllComponents: + for component in AxisFamily.active().axes: values = self._component_values(projection_set, component) component_labels = (labels or {}).get(component) or {} metadata[ - SourceComponentProjectionStrategy.for_enum_member( + SourceComponentProjectionStrategy.for_axis( component ).metadata_collection_field ] = { @@ -1294,18 +1270,18 @@ def virtual_path( def _component_values( self, projection_set: SourceProjectionSet, - component: AllComponents, + component: type[Axis], ) -> dict[str, str | None]: values: dict[str, str | None] = {} for projection in projection_set.projections: key = projection.component_value(component) if key is None: continue - label = projection.component_labels.get(component.value) + label = projection.component_labels.get(component.name) previous = values.get(key) if previous is not None and label is not None and previous != label: raise ValueError( - f"Conflicting label for {component.value}={key!r}: " + f"Conflicting label for {component.name}={key!r}: " f"{previous!r} vs {label!r}." ) values[key] = label if label is not None else previous @@ -1330,7 +1306,7 @@ def _source_metadata( for field, value in SourceMetadataFields.scalar_items(metadata) if ( (component := source_metadata_component(field)) is not None - and field != component.value + and field != component.name ) } if source_component_fields: @@ -1341,7 +1317,7 @@ def _source_metadata( ) original_metadata = dict(SourceMetadataFields.original_items(metadata)) for component, value in projection.source_component_values(): - canonical_value = metadata.get(component.value) + canonical_value = metadata.get(component.name) conflicts_with_address = ( canonical_value is not None and not isinstance(canonical_value, Mapping) @@ -1359,8 +1335,8 @@ def _source_metadata( for source_value in provenance_values ): raise ValueError( - f"Source metadata {component.value}={canonical_value!r} conflicts " - f"with canonical {component.value}={value!r}." + f"Source metadata {component.name}={canonical_value!r} conflicts " + f"with canonical {component.name}={value!r}." ) metadata = with_source_component_metadata(metadata, component, value) if projection.source_alias is not None: @@ -1408,8 +1384,20 @@ def _coordinate_value(value: str) -> str | int: return int(value) if value.isdecimal() else value -def _padded(value: str, width: int) -> str: - return f"{int(value):0{width}d}" if value.isdecimal() else value +@lru_cache(maxsize=8) +def _plane_filename_pattern(family: type[AxisFamily]) -> re.Pattern[str]: + """Plane filename grammar derived from the family's declared tokens.""" + + variable_axes = family.variable_axes() + tokens = "".join( + f"_{re.escape(axis.filename_prefix or '')}" + f"(?P[^_{'.' if index == len(variable_axes) else ''}]+)" + for index, axis in enumerate(variable_axes, start=1) + ) + return re.compile( + rf"^(?P[^_]+){tokens}(?:_[^.]*)?(?P(?:\.\w+)+)$" + ) + def _normalize_projection(projection: SourceProjection) -> None: diff --git a/openhcs/core/source_tile_geometry.py b/openhcs/core/source_tile_geometry.py index 2b0b5f9d19..65ad639adf 100644 --- a/openhcs/core/source_tile_geometry.py +++ b/openhcs/core/source_tile_geometry.py @@ -7,9 +7,9 @@ from polystore.source_tile_geometry import SourceTileGeometry -from openhcs.constants.constants import AllComponents from openhcs.core.source_metadata import SourceVoxelSpacing from openhcs.core.source_projection import SourceProjectionSet +from openhcs.core.axes import AxisFamily, ColourAxis, TileAxis @dataclass(frozen=True, slots=True) @@ -36,13 +36,16 @@ def from_projection_set( spacing_by_group: dict[tuple[str, ...], set[SourceVoxelSpacing]] = {} for projection in projections.plane_projections: address = projection.address + family = AxisFamily.active() + tile_axis = family.one(TileAxis) + colour_axis = family.one(ColourAxis) key = tuple( address.value_for(component) - for component in AllComponents - if component not in (AllComponents.SITE, AllComponents.CHANNEL) + for component in family.axes + if component not in (tile_axis, colour_axis) ) - channel = address.value_for(AllComponents.CHANNEL) - site = address.value_for(AllComponents.SITE) + channel = address.value_for(colour_axis) + site = address.value_for(tile_axis) geometry = SourceTileGeometry.from_source_metadata( projection.source_metadata ) diff --git a/openhcs/core/source_workspace_projection.py b/openhcs/core/source_workspace_projection.py index 038672296e..012edb3dcb 100644 --- a/openhcs/core/source_workspace_projection.py +++ b/openhcs/core/source_workspace_projection.py @@ -46,6 +46,7 @@ VirtualWorkspaceSourceMetadataEntries, ) from polystore.virtual_workspace import SourcePixelRef +from openhcs.core.axes import AxisFamily if TYPE_CHECKING: from openhcs.core.context.processing_context import ProcessingContext @@ -552,7 +553,6 @@ def partition_by_axes( axis_ids: Sequence[str], ) -> Mapping[str, "VirtualWorkspaceSourceProjection"]: """Admit all requested axis views in one traversal of this source epoch.""" - from openhcs.constants import MULTIPROCESSING_AXIS source_refs = {axis_id: {} for axis_id in axis_ids} source_metadata = {axis_id: {} for axis_id in source_refs} @@ -565,7 +565,9 @@ def partition_by_axes( ) values = ( () if metadata is None - else source_component_metadata_values(metadata, MULTIPROCESSING_AXIS) + else source_component_metadata_values( + metadata, AxisFamily.active().partition_axis() + ) ) selected_axes = ( tuple(dict.fromkeys(value for value in values if value in source_refs)) @@ -616,9 +618,10 @@ def _path_belongs_to_axis( ) if metadata is None: return True - from openhcs.constants import MULTIPROCESSING_AXIS - values = source_component_metadata_values(metadata, MULTIPROCESSING_AXIS) + values = source_component_metadata_values( + metadata, AxisFamily.active().partition_axis() + ) if not values: return True return any(source_metadata_values_equal(value, axis_id) for value in values) diff --git a/openhcs/core/steps/function_artifact_materialization.py b/openhcs/core/steps/function_artifact_materialization.py index 8f7de8b7b7..197b736dee 100644 --- a/openhcs/core/steps/function_artifact_materialization.py +++ b/openhcs/core/steps/function_artifact_materialization.py @@ -14,7 +14,7 @@ from polystore.streaming.identity import StreamProducerIdentity from polystore.streaming.viewer_transport import ViewerStreamProducer -from openhcs.constants.constants import AllComponents, Backend, VariableComponents +from openhcs.constants.constants import Backend from openhcs.core.artifacts import ( ArtifactOutputPlan, ) @@ -67,6 +67,7 @@ materialization_outputs, prepare_materialization, ) +from openhcs.core.axes import Axis, AxisFamily, PartitionAxis if TYPE_CHECKING: from polystore.filemanager import FileManager @@ -560,9 +561,9 @@ def _aggregate_identity( "" if scope is None else "".join( - (f"_{component.value}-" f"{OpenHCSPlaneAddress.component_token(value)}") + (f"_{component.name}-" f"{OpenHCSPlaneAddress.component_token(value)}") for component, value in scope.source_component_values - if not component.is_multiprocessing_axis() + if not issubclass(component, PartitionAxis) ) ) return ( @@ -689,14 +690,15 @@ def _analysis_identity( def missing_component_is_aggregated( component_name: str, execution_scope: RuntimeExecutionAxisScope, - invocation_variable_components: tuple[VariableComponents, ...], + invocation_variable_components: tuple[type[Axis], ...], ) -> bool: """Return whether a missing source coordinate is a stacked invocation axis.""" - component = AllComponents.from_value(component_name) - if component is None: + family = AxisFamily.active() + if component_name not in family.names(): return False - variable_components = ComponentSet.coerce(invocation_variable_components) + component = family.named(component_name) + variable_components = ComponentSet.of(invocation_variable_components) return ( component in variable_components and execution_scope.value_text_for_component(component) is None diff --git a/openhcs/core/steps/function_execution.py b/openhcs/core/steps/function_execution.py index 8f8133eae6..0ebb055984 100644 --- a/openhcs/core/steps/function_execution.py +++ b/openhcs/core/steps/function_execution.py @@ -9,7 +9,6 @@ from itertools import zip_longest from typing import TYPE_CHECKING -from openhcs.constants import MULTIPROCESSING_AXIS from openhcs.constants.constants import ( LOADABLE_IMAGE_EXTENSIONS, Backend, @@ -58,6 +57,7 @@ _process_single_pattern_group, ) from openhcs.formats.pattern.pattern_discovery import PatternDiscoveryEngine +from openhcs.core.axes import AxisFamily if TYPE_CHECKING: from openhcs.microscopes.microscope_interfaces import FilenameParser @@ -603,7 +603,7 @@ def candidate_scopes( ).candidate_execution_scopes( context.runtime_value_store, execution_scope, - variable_components=ComponentSet.coerce(plan.variable_components), + variable_components=ComponentSet.of(plan.variable_components), ) if scope.is_dynamic: @@ -803,7 +803,7 @@ def _log_execution_start(self) -> None: def _detect_patterns(self) -> dict[str, DiscoveredPatternCollection]: plan = self.plan - axis_name = MULTIPROCESSING_AXIS.value + axis_name = AxisFamily.active().partition_axis().name axis_filter = {f"{axis_name}_filter": [plan.axis_id]} source_files = step_output_manifest(self.context).producer_paths_for(plan) if source_files is None: @@ -822,8 +822,8 @@ def _detect_patterns(self) -> dict[str, DiscoveredPatternCollection]: cache_key = RuntimePatternDiscoveryCacheKey.from_source_files( axis_id=plan.axis_id, source_files=source_files, - group_by=plan.group_by_value, - variable_components=plan.variable_component_values, + group_by=plan.group_by, + variable_components=plan.require_variable_components(), ) cached_patterns = self.context.runtime_pattern_discovery_cache.get( cache_key @@ -837,7 +837,7 @@ def _detect_patterns(self) -> dict[str, DiscoveredPatternCollection]: ).auto_detect_patterns_from_axis_files( list(source_files), axis_id=plan.axis_id, - variable_components=plan.variable_component_values, + variable_components=plan.require_variable_components(), group_by=plan.group_by, ) self.context.runtime_pattern_discovery_cache.store( @@ -850,7 +850,7 @@ def _detect_patterns(self) -> dict[str, DiscoveredPatternCollection]: plan.read_backend, extensions=LOADABLE_IMAGE_EXTENSIONS, group_by=plan.group_by, - variable_components=plan.variable_component_values, + variable_components=plan.require_variable_components(), pattern_cache=self.context.runtime_pattern_discovery_cache, **axis_filter, ) @@ -984,7 +984,7 @@ def _prepare_groups( f"Step '{plan.step_name}' uses a dict function pattern without " "a concrete execution group component. Dict keys are dispatch " "groups and require group_by to resolve to a real component; " - "GroupBy.NONE is only valid for non-dict function patterns." + "Ungrouped is only valid for non-dict function patterns." ) if ( plan.execution_group_scope.is_ungrouped diff --git a/openhcs/core/steps/function_io.py b/openhcs/core/steps/function_io.py index 6ed49a696a..8236b78cea 100644 --- a/openhcs/core/steps/function_io.py +++ b/openhcs/core/steps/function_io.py @@ -9,25 +9,28 @@ from pathlib import Path, PurePosixPath from typing import TYPE_CHECKING, ClassVar, Mapping, Sequence, TypeAlias -from metaclass_registry import AutoRegisterMeta from polystore.zarr_batch import ZarrBatchAxis, ZarrBatchAxisRole, ZarrBatchLayout -from openhcs.constants.constants import ( - LOADABLE_IMAGE_EXTENSIONS, - AllComponents, - Backend, -) +from openhcs.constants.constants import LOADABLE_IMAGE_EXTENSIONS, Backend from openhcs.core.components.parser_metaprogramming import FilenameParseResult from openhcs.core.image_file_serialization import ( ImageFileFormat, prepare_disk_image_payloads, ) -from metaclass_registry.strategies import EnumKeyedStrategyMixin from openhcs.core.runtime_array_values import RuntimeArrayData from openhcs.core.runtime_image_values import ( image_payload_data, ) from openhcs.core.steps.function_output_identity import FunctionOutputIdentity +from openhcs.core.axes import ( + Axis, + AxisFamily, + AxisRoleKeyedStrategyMixin, + ColourAxis, + StackAxis, + TileAxis, + TimeAxis, +) if TYPE_CHECKING: from polystore.filemanager import FileManager @@ -90,9 +93,9 @@ def from_output( ( ( component, - output_identity.component_values.get(component.value), + output_identity.component_values.get(component.name), ) - for component in AllComponents + for component in AxisFamily.active().axes ), extension=output_identity.extension or ".tif", ), @@ -100,14 +103,9 @@ def from_output( ) -class ZarrComponentAxisProjection( - EnumKeyedStrategyMixin[AllComponents], - ABC, - metaclass=AutoRegisterMeta, -): - """Project one OpenHCS component into its declaration-owned NGFF axis.""" +class ZarrComponentAxisProjection(AxisRoleKeyedStrategyMixin, ABC): + """Project the axis carrying one role into its NGFF axis.""" - strategy_key: ClassVar[AllComponents | None] = None axis_order: ClassVar[int] axis_name: ClassVar[str] axis_type: ClassVar[str] @@ -118,7 +116,7 @@ def ordered_types(cls) -> tuple[type["ZarrComponentAxisProjection"], ...]: """Return declared storage axes in NGFF-valid order.""" return tuple( - sorted(cls.registered_strategy_types(), key=lambda item: item.axis_order) + sorted(cls.role_strategy_types(), key=lambda item: item.axis_order) ) @classmethod @@ -163,11 +161,17 @@ def project_item_values( cls, item_identities: Sequence[ZarrBatchItemIdentity], ) -> tuple[str, ...] | None: - """Project this axis when it is retained by every output identity.""" + """Project this role's axis when it is retained by every output identity.""" - component = cls.strategy_key - if component is None: - raise RuntimeError("Zarr axis projection is missing its component owner") + role_axes = AxisFamily.active().with_role(cls.implements_role) + if not role_axes: + return None + if len(role_axes) > 1: + raise ValueError( + f"NGFF axis {cls.axis_name!r} admits one axis with role " + f"{cls.implements_role.__name__}; the family declares {role_axes}." + ) + (component,) = role_axes presence = tuple( identity.component_values.value_for(component) is not None for identity in item_identities @@ -180,32 +184,31 @@ def project_item_values( ) raise ValueError( "Parsed output identities disagree on component " - f"{component.value!r}; missing from item indices {missing_indices!r}" + f"{component.name!r}; missing from item indices {missing_indices!r}" ) - return tuple(cls.item_value(identity) for identity in item_identities) + return tuple(cls.item_value(identity, component) for identity in item_identities) @classmethod - def item_value(cls, identity: ZarrBatchItemIdentity) -> str: - component = cls.strategy_key - if component is None: - raise RuntimeError("Zarr axis projection is missing its component owner") + def item_value( + cls, identity: ZarrBatchItemIdentity, component: type[Axis] + ) -> str: value = identity.component_values.value_for(component) if value is None: raise ValueError( - f"Parsed output identity is missing component {component.value!r}" + f"Parsed output identity is missing component {component.name!r}" ) return str(value) class TimepointZarrAxisProjection(ZarrComponentAxisProjection): - strategy_key = AllComponents.TIMEPOINT + implements_role = TimeAxis axis_order = 0 axis_name = "t" axis_type = "time" class SiteZarrAxisProjection(ZarrComponentAxisProjection): - strategy_key = AllComponents.SITE + implements_role = TileAxis axis_order = 1 axis_name = "field" axis_type = "field" @@ -213,20 +216,22 @@ class SiteZarrAxisProjection(ZarrComponentAxisProjection): class ChannelZarrAxisProjection(ZarrComponentAxisProjection): - strategy_key = AllComponents.CHANNEL + implements_role = ColourAxis axis_order = 2 axis_name = "c" axis_type = "channel" @classmethod - def item_value(cls, identity: ZarrBatchItemIdentity) -> str: - channel = super().item_value(identity) + def item_value( + cls, identity: ZarrBatchItemIdentity, component: type[Axis] + ) -> str: + channel = super().item_value(identity, component) qualifier = identity.filename_qualifier return channel if qualifier is None else f"{channel}:{qualifier}" class ZIndexZarrAxisProjection(ZarrComponentAxisProjection): - strategy_key = AllComponents.Z_INDEX + implements_role = StackAxis axis_order = 3 axis_name = "z" axis_type = "space" @@ -331,7 +336,6 @@ def get_all_image_paths( microscope_handler: MicroscopeHandler, ) -> list[str]: """Get all image file paths for one multiprocessing axis value.""" - from openhcs.constants import MULTIPROCESSING_AXIS all_image_files = filemanager.list_image_files( str(input_dir), @@ -345,7 +349,10 @@ def get_all_image_paths( for file_path in all_image_files: filename = os.path.basename(str(file_path)) metadata = parser.parse_filename(filename) - if metadata and metadata.component_matches(MULTIPROCESSING_AXIS, axis_id): + if metadata and metadata.component_matches( + AxisFamily.active().partition_axis(), axis_id + ): + axis_files.append(str(file_path)) full_file_paths = sorted( diff --git a/openhcs/core/steps/function_output_identity.py b/openhcs/core/steps/function_output_identity.py index ba429c253f..cabb63f200 100644 --- a/openhcs/core/steps/function_output_identity.py +++ b/openhcs/core/steps/function_output_identity.py @@ -8,7 +8,6 @@ from typing import ClassVar, Mapping, Sequence, TypeAlias from openhcs.core.source_path_identity import source_path_identity -from openhcs.constants.constants import AllComponents, VariableComponents from openhcs.core.runtime_image_values import ( ImagePayloadMetadata, image_payload_metadata, @@ -29,6 +28,7 @@ ) from openhcs.core.source_projection import OpenHCSPlaneAddress from openhcs.microscopes.microscope_interfaces import FilenameParser +from openhcs.core.axes import Axis, AxisFamily ParsedFilenameValue: TypeAlias = str | int | float | bool | None FunctionOutputComponentValue: TypeAlias = str | int @@ -99,7 +99,7 @@ class FunctionOutputPathRequest: output_dir: Path output_payload: RuntimeArrayData input_path: str | None - variable_components: Sequence[VariableComponents] = field(default_factory=tuple) + variable_components: Sequence[type[Axis]] = field(default_factory=tuple) input_aligned_output: bool = False identity_cache: FunctionOutputIdentityCache = field( default_factory=FunctionOutputIdentityCache @@ -162,8 +162,8 @@ def filename_values(self) -> FunctionOutputComponentValues: def filename_address(self) -> OpenHCSPlaneAddress: """Project the retained producer coordinates without parsing its path.""" return OpenHCSPlaneAddress.from_component_values( - (component, self.filename_values.get(component.value)) - for component in AllComponents + (component, self.filename_values.get(component.name)) + for component in AxisFamily.active().axes ) def component_metadata( @@ -366,7 +366,7 @@ def _component_values_from_source_metadata( if metadata is None: return {} return { - component.value: SourceMetadataFields.canonical_component_value( + component.name: SourceMetadataFields.canonical_component_value( component, value ) for component, value in source_component_metadata_items(metadata) @@ -378,7 +378,7 @@ def component_values_from_parsed( parsed: FilenameParseResult, ) -> dict[str, FunctionOutputComponentValue]: return { - str(component.value): SourceMetadataFields.canonical_component_value( + str(component.name): SourceMetadataFields.canonical_component_value( component, value ) for component, value in parsed.declared_values() @@ -413,7 +413,7 @@ def from_metadata( metadata: ImagePayloadMetadata, *, fallback_identity_path: str | None = None, - variable_components: Sequence[VariableComponents] = (), + variable_components: Sequence[type[Axis]] = (), input_aligned_output: bool = False, ) -> FunctionOutputIdentity | None: """Return parser-backed identity carried by image payload metadata.""" @@ -433,7 +433,7 @@ def from_metadata_with_cache( metadata: ImagePayloadMetadata, *, fallback_identity_path: str | None = None, - variable_components: Sequence[VariableComponents] = (), + variable_components: Sequence[type[Axis]] = (), input_aligned_output: bool = False, identity_cache: FunctionOutputIdentityCache, ) -> FunctionOutputIdentity | None: @@ -449,12 +449,12 @@ def from_metadata_with_cache( @staticmethod def _source_stack_identity_component_values( - variable_components: Sequence[VariableComponents], + variable_components: Sequence[type[Axis]], ) -> frozenset[str]: return frozenset( - component.value + component.name for component in variable_components - if component.value is not None + if component.name is not None ) @classmethod @@ -464,7 +464,7 @@ def _identity_from_metadata_with_cache( metadata: ImagePayloadMetadata, *, fallback_identity_path: str | None, - variable_components: Sequence[VariableComponents], + variable_components: Sequence[type[Axis]], input_aligned_output: bool, identity_cache: FunctionOutputIdentityCache, ) -> FunctionOutputIdentity | None: @@ -714,7 +714,7 @@ def _complete_identity_from_paths( identity_cache: FunctionOutputIdentityCache, ) -> FunctionOutputIdentity: if identity.extension is not None and all( - component.value in identity.component_values for component in AllComponents + component.name in identity.component_values for component in AxisFamily.active().axes ): return identity for path, source in candidates: @@ -931,7 +931,7 @@ def _source_stack_semantic_component_keys( - identity_component_values ) ordered_keys = tuple( - component.value for component in AllComponents if component.value in keys + component.name for component in AxisFamily.active().axes if component.name in keys ) extra_keys = tuple(sorted(keys - frozenset(ordered_keys))) return (*ordered_keys, *extra_keys) diff --git a/openhcs/core/steps/function_output_manifest.py b/openhcs/core/steps/function_output_manifest.py index 96128c0c0e..28e820c677 100644 --- a/openhcs/core/steps/function_output_manifest.py +++ b/openhcs/core/steps/function_output_manifest.py @@ -38,7 +38,7 @@ SourcePatternResolutionContext, ) from openhcs.core.source_matching import SourceImageSetIdentityPolicy -from openhcs.constants import AllComponents +from openhcs.core.axes import AxisFamily, PartitionAxis @dataclass(frozen=True, slots=True) @@ -132,7 +132,7 @@ def execution_scope(self, plan: CompiledStepPlan) -> RuntimeExecutionAxisScope: group_value = ( None if group_component is None - else self.component_values.get(group_component.value) + else self.component_values.get(group_component.name) ) return RuntimeExecutionAxisScope.from_raw( plan.axis_id, @@ -140,10 +140,10 @@ def execution_scope(self, plan: CompiledStepPlan) -> RuntimeExecutionAxisScope: value=group_value, fixed_component_values=tuple( (component, str(value)) - for component in AllComponents - if not component.is_multiprocessing_axis() + for component in AxisFamily.active().axes + if not issubclass(component, PartitionAxis) and component is not group_component - and (value := self.component_values.get(component.value)) is not None + and (value := self.component_values.get(component.name)) is not None ), ) @@ -392,7 +392,7 @@ def producer_patterns_by_execution_group( value = ( None if component is None - else record.component_values.get(component.value) + else record.component_values.get(component.name) ) key = plan.execution_group_scope.normalize_key(value) if plan.execution_group_scope.contains_runtime_key(key): diff --git a/openhcs/core/steps/function_runtime.py b/openhcs/core/steps/function_runtime.py index c7785c8f66..695dec8d38 100644 --- a/openhcs/core/steps/function_runtime.py +++ b/openhcs/core/steps/function_runtime.py @@ -19,7 +19,7 @@ import numpy as np -from openhcs.constants.constants import AllComponents, Backend +from openhcs.constants.constants import Backend from openhcs.core.artifacts import ( ArtifactInputPlan, ArtifactOutputPlan, @@ -145,6 +145,7 @@ FunctionOutputPathRequest, ) from openhcs.core.compiled_step_plan import CompiledStepPlan +from openhcs.core.axes import Axis, AxisFamily, PartitionAxis logger = logging.getLogger(__name__) @@ -286,7 +287,7 @@ def active_main_flow_source_binding_plan( ).source_provenance.represented_source_image_names ) if represented_names: - variable_components = ComponentSet.coerce( + variable_components = ComponentSet.of( self.execution_plan.variable_components or () ) return plan.for_represented_source_stack( @@ -324,11 +325,10 @@ def source_binding_plan(self) -> CompiledSourceBindingPlan: return self.main_flow_source_binding_plan @property - def axis_component(self) -> str | None: + def axis_component(self) -> type[Axis] | None: if self.component_value is None: return None - component = self.execution_plan.execution_group_scope.component - return None if component is None else component.value + return self.execution_plan.execution_group_scope.component @property def axis_component_value(self) -> str | None: @@ -404,14 +404,14 @@ def loaded_fixed_component_values( payload ).source_provenance.with_common_scalar_identity_from_planes() common_source_metadata = source_provenance.source_component_metadata or {} - variable_components = ComponentSet.coerce( + variable_components = ComponentSet.of( self.execution_plan.variable_components or () ) execution_group_component = self.execution_plan.execution_group_scope.component fixed_components = tuple( component - for component in AllComponents - if not component.is_multiprocessing_axis() + for component in AxisFamily.active().axes + if not issubclass(component, PartitionAxis) and component is not execution_group_component and component not in variable_components and source_component_metadata_value( @@ -635,11 +635,7 @@ def load_input_stack( request.pattern_group_info, context.filemanager, plan.read_backend, - ( - [component.value for component in plan.variable_components] - if plan.variable_components - else None - ), + list(plan.variable_components) if plan.variable_components else None, pattern_cache=context.runtime_pattern_discovery_cache, ) if producer_index is not None and not producer_matching_files: @@ -811,7 +807,7 @@ def _filter_matching_files_for_group( if self.main_flow_source_binding_plan.has_primary_content: return matching_files - group_component = self.execution_plan.execution_group_value + group_component = self.execution_plan.execution_group_scope.component component_value = self.component_value if group_component is None or component_value is None: return matching_files @@ -820,7 +816,8 @@ def _filter_matching_files_for_group( filtered = self.context.runtime_pattern_discovery_cache.files_for_component( parser, matching_files, - parser.component_for_name(group_component), + group_component, + component_value, ) if not filtered: diff --git a/openhcs/core/steps/stream_component_semantics.py b/openhcs/core/steps/stream_component_semantics.py index 6f29fad64f..6722dc0645 100644 --- a/openhcs/core/steps/stream_component_semantics.py +++ b/openhcs/core/steps/stream_component_semantics.py @@ -28,7 +28,6 @@ ViewerWireValue, ) -from openhcs.constants.constants import AllComponents, get_multiprocessing_axis from openhcs.core.config import FijiDimensionMode, NapariDimensionMode from openhcs.core.context.processing_context import ProcessingContext from openhcs.core.runtime_image_values import ImagePayloadMetadata @@ -62,6 +61,7 @@ ViewerComponentValueDomainPayload, ViewerObjectDisplayConfigInput, ) +from openhcs.core.axes import Axis, AxisFamily StreamComponentMetadata = SourceComponentMetadata | None ComponentDisplayName: TypeAlias = str | int | float | bool | None @@ -77,7 +77,7 @@ def payload_items_for_display( payload: RuntimeProjectionData, *, metadata: ImagePayloadMetadata, - plane_components: tuple[AllComponents, ...], + plane_components: tuple[type[Axis], ...], component_modes: Mapping[str, str], source_description: str, ) -> tuple[RuntimeProjectedPayloadItem, ...]: @@ -149,9 +149,9 @@ def item_fields( return cls._item_fields( metadata, tuple( - component + AxisFamily.active().named(component_name) for component_name in component_order - if (component := AllComponents.from_value(component_name)) is not None + if component_name in AxisFamily.active().names() ), project_singleton=False, ) @@ -160,7 +160,7 @@ def item_fields( def item_fields_for_plane_components( cls, metadata: ImagePayloadMetadata | None, - plane_components: tuple[AllComponents, ...], + plane_components: tuple[type[Axis], ...], ) -> dict[str, ViewerWireValue]: """Project retained image planes, with compiler-owned singleton identity.""" @@ -174,7 +174,7 @@ def item_fields_for_plane_components( def _item_fields( cls, metadata: ImagePayloadMetadata | None, - plane_components: tuple[AllComponents, ...], + plane_components: tuple[type[Axis], ...], *, project_singleton: bool, ) -> dict[str, ViewerWireValue]: @@ -217,7 +217,7 @@ def _item_fields( @staticmethod def _singleton_plane_component_values( metadata: ImagePayloadMetadata, - plane_components: tuple[AllComponents, ...], + plane_components: tuple[type[Axis], ...], ) -> dict[str, tuple[ComponentValue, ...]]: """Project one exact source plane onto its declared viewer component.""" @@ -225,7 +225,7 @@ def _singleton_plane_component_values( 0 ).source_component_metadata values = { - component.value: (value,) + component.name: (value,) for component in plane_components if ( value := source_component_metadata_raw_value( @@ -375,11 +375,13 @@ def component_value( metadata: SourceComponentMetadata, component: str, ) -> ComponentValue: - component_identity = AllComponents.from_value(component) - if component_identity is None: - value = metadata.get(component) + family = AxisFamily.active() + if component in family.names(): + value = source_component_metadata_raw_value( + metadata, family.named(component) + ) else: - value = source_component_metadata_raw_value(metadata, component_identity) + value = metadata.get(component) if value is None: return None return ViewerComponentValueParser.parse( @@ -699,7 +701,6 @@ class StreamExecutionAxisDomainProvider(StreamComponentDomainProvider): """Declared domain provider for the execution multiprocessing axis.""" registry_key: ClassVar[str] = "execution_axis" - axis_component: ClassVar[str] = str(get_multiprocessing_axis().value) execution_axis_values: tuple[ComponentValue, ...] = () @classmethod @@ -728,7 +729,8 @@ def build_for_component( @classmethod def supports(cls, component: str) -> bool: - return component == cls.axis_component + return component == AxisFamily.active().partition_axis().name + def domain_metadata_items(self) -> StreamComponentDomainMetadataItems: return tuple({self.component: value} for value in self.execution_axis_values) diff --git a/openhcs/core/utils.py b/openhcs/core/utils.py index a1549c57bc..28c1d61f0e 100644 --- a/openhcs/core/utils.py +++ b/openhcs/core/utils.py @@ -37,7 +37,7 @@ def resolve_filter_with_mode( Args: well_filter: Filter specification (list, string pattern, or max count) well_filter_mode: Whether to include or exclude the matched wells - available_wells: Ordered list of wells from orchestrator.get_component_keys(MULTIPROCESSING_AXIS) + available_wells: Ordered list of wells from orchestrator.get_component_keys(partition_axis) Returns: List of well IDs to process (order preserved from available_wells) @@ -100,7 +100,7 @@ def resolve_compilation_filter( Args: well_filter: Filter specification (list, string pattern, or max count) - available_wells: Ordered list of wells from orchestrator.get_component_keys(MULTIPROCESSING_AXIS) + available_wells: Ordered list of wells from orchestrator.get_component_keys(partition_axis) strict: If True, raise error for non-existent wells. If False, silently ignore them. Returns: diff --git a/openhcs/core/virtual_workspace_metadata.py b/openhcs/core/virtual_workspace_metadata.py index e3bfaed0ea..0c1140b218 100644 --- a/openhcs/core/virtual_workspace_metadata.py +++ b/openhcs/core/virtual_workspace_metadata.py @@ -15,7 +15,6 @@ from polystore.metadata_writer import MetadataConfig 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 @@ -35,6 +34,7 @@ SourceProjectionSet, ) from openhcs.core.source_tile_geometry import SourceTileLayout +from openhcs.core.axes import Axis, AxisFamily, ColourAxis, is_axis if TYPE_CHECKING: from openhcs.core.context.processing_context import ProcessingContext @@ -144,7 +144,7 @@ def publish_source_projection_metadata( saved_image_paths: Sequence[str], microscope_handler_name: str, source_filename_parser_name: str, - component_labels: Mapping[AllComponents, Mapping[str, str | None] | None], + component_labels: Mapping[type[Axis], Mapping[str, str | None] | None], backend: str, is_main: bool, results_dir: str | None, @@ -318,13 +318,13 @@ def get_metadata_path(plate_root: str | Path) -> Path: return METADATA_CONFIG.metadata_path(plate_root) -def component_metadata_field(component: AllComponents) -> str: +def component_metadata_field(component: type[Axis]) -> str: """Derive the persisted collection field for one declared component.""" - if not isinstance(component, AllComponents): - raise TypeError("Metadata fields require an exact AllComponents member") - suffix = "es" if component.value.endswith("x") else "s" - return f"{component.value}{suffix}" + if not is_axis(component): + raise TypeError(f"Metadata fields require a declared axis; got {component!r}") + suffix = "es" if component.name.endswith("x") else "s" + return f"{component.name}{suffix}" @dataclass(frozen=True) @@ -355,13 +355,8 @@ class OpenHCSMetadataFields: MICROSCOPE_HANDLER_NAME: str = ( SourceProjectionMetadataSerializer.MICROSCOPE_HANDLER_NAME_FIELD ) - CHANNELS: str = component_metadata_field(AllComponents.CHANNEL) - WELLS: str = component_metadata_field(AllComponents.WELL) - SITES: str = component_metadata_field(AllComponents.SITE) - Z_INDEXES: str = component_metadata_field(AllComponents.Z_INDEX) - TIMEPOINTS: str = component_metadata_field(AllComponents.TIMEPOINT) - # Declared legacy collection fields without a current AllComponents member; - # readers still consume them from persisted plates. + # Per-axis collection fields derive from component_metadata_field(axis). + # Collection fields owned by no axis; readers consume them from persisted plates. OBJECTIVES: str = "objectives" ACQUISITION_DATETIME: str = "acquisition_datetime" PLATE_NAME: str = "plate_name" @@ -682,13 +677,11 @@ def _projection_record( 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"), + address = OpenHCSPlaneAddress( + (axis, cls._required_text(address_value, axis.name)) + for axis in AxisFamily.active().axes ) + else: raise RuntimeError( "virtual_workspace source_projection address must be a mapping or " @@ -769,12 +762,16 @@ def _optional_execution_scope( "virtual_workspace source_projection execution_scope fixed " "components must be two-item sequences." ) - fixed_components.append((str(item[0]), str(item[1]))) + fixed_components.append( + (AxisFamily.active().named(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), + component=( + None if component is None else AxisFamily.active().named(str(component)) + ), value=None if scope_value is None else str(scope_value), fixed_component_values=tuple(fixed_components), ) @@ -881,7 +878,7 @@ def metadata_for(self, virtual_path: str) -> SourceMetadataMapping: @dataclass(frozen=True, slots=True) class VirtualWorkspaceChannelLabels: - """Validated channel labels for one virtual-workspace subdirectory.""" + """Validated colour-axis labels for one virtual-workspace subdirectory.""" entries: Mapping[str, str] @@ -890,14 +887,18 @@ def from_subdirectory( cls, subdirectory: OpenHCSSubdirectoryPayload, ) -> "VirtualWorkspaceChannelLabels": - channels = subdirectory.get(FIELDS.CHANNELS) - if channels is None: - return cls(MappingProxyType({})) - if not isinstance(channels, Mapping): - raise RuntimeError("virtual_workspace channels must be a mapping.") - return cls( - MappingProxyType({str(key): str(value) for key, value in channels.items()}) - ) + entries: dict[str, str] = {} + for colour_axis in AxisFamily.active().with_role(ColourAxis): + labels = subdirectory.get(component_metadata_field(colour_axis)) + if labels is None: + continue + if not isinstance(labels, Mapping): + raise RuntimeError( + f"virtual_workspace {colour_axis.name} labels must be a mapping." + ) + entries.update({str(key): str(value) for key, value in labels.items()}) + return cls(MappingProxyType(entries)) + def label_for(self, channel_value: SourceMetadataScalar) -> str | None: return self.entries.get(str(channel_value)) diff --git a/openhcs/demo/basic_pipeline.py b/openhcs/demo/basic_pipeline.py index 773c5f763c..96bc35f2a9 100644 --- a/openhcs/demo/basic_pipeline.py +++ b/openhcs/demo/basic_pipeline.py @@ -7,7 +7,6 @@ # Edit this pipeline and save to apply changes # Automatically collected imports -from openhcs.constants.constants import GroupBy, VariableComponents from openhcs.constants.input_source import InputSource from openhcs.core.config import ( LazyFijiStreamingConfig, @@ -32,6 +31,7 @@ create_projection, stack_percentile_normalize, ) +from openhcs.domains.microscopy.axes import Microscopy # Pipeline document pipeline_config = PipelineConfig() @@ -51,7 +51,7 @@ func=create_composite, name="create_composite", processing_config=LazyProcessingConfig( - variable_components=[VariableComponents.CHANNEL] + variable_components=[Microscopy.Channel] ), ) pipeline_steps.append(step_2) @@ -61,7 +61,7 @@ func=create_projection, name="Z-Stack Flattening", processing_config=LazyProcessingConfig( - variable_components=[VariableComponents.Z_INDEX] + variable_components=[Microscopy.ZIndex] ), step_materialization_config=LazyStepMaterializationConfig(), ) @@ -90,7 +90,7 @@ func=create_projection, name="Z-Stack Flattening", processing_config=LazyProcessingConfig( - variable_components=[VariableComponents.Z_INDEX] + variable_components=[Microscopy.ZIndex] ), napari_streaming_config=LazyNapariStreamingConfig(), fiji_streaming_config=LazyFijiStreamingConfig(), diff --git a/openhcs/demo/synthetic_data.py b/openhcs/demo/synthetic_data.py index a98758b35c..469e37c197 100644 --- a/openhcs/demo/synthetic_data.py +++ b/openhcs/demo/synthetic_data.py @@ -33,7 +33,6 @@ import tifffile from skimage import draw, filters -from openhcs.constants.constants import AllComponents from openhcs.core.source_projection import ( OpenHCSPlaneAddress, SourcePlaneProjection, SourceProjectionSet, SourceProjectionMetadataSerializer, @@ -45,6 +44,7 @@ from polystore.disk import DiskStorageBackend from polystore.filemanager import FileManager from polystore.virtual_workspace import SourcePixelRef +from openhcs.domains.microscopy.axes import Microscopy class SyntheticMicroscopyGenerator: @@ -996,9 +996,9 @@ def generate_dataset(self): def _plane_components(self, well: str, site: int, channel: int, z_index: int): """Bind the complete acquisition address before physical spelling.""" return self.parser.bind_declared_values( - ((AllComponents.WELL, well), (AllComponents.SITE, site), - (AllComponents.CHANNEL, channel), (AllComponents.Z_INDEX, z_index), - (AllComponents.TIMEPOINT, 1)) + ((Microscopy.Well, well), (Microscopy.Site, site), + (Microscopy.Channel, channel), (Microscopy.ZIndex, z_index), + (Microscopy.Timepoint, 1)) ) def _write_plane(self, tile, target_dir: Path, well: str, site: int, diff --git a/openhcs/demo/synthetic_plate_pipeline.py b/openhcs/demo/synthetic_plate_pipeline.py index d455cbcd68..e7ee69275c 100644 --- a/openhcs/demo/synthetic_plate_pipeline.py +++ b/openhcs/demo/synthetic_plate_pipeline.py @@ -7,7 +7,6 @@ # Edit this pipeline and save to apply changes # Automatically collected imports -from openhcs.constants.constants import VariableComponents from openhcs.constants.input_source import InputSource from openhcs.core.config import ( LazyNapariStreamingConfig, @@ -29,6 +28,7 @@ create_projection, stack_percentile_normalize, ) +from openhcs.domains.microscopy.axes import Microscopy # Pipeline document pipeline_config = PipelineConfig() @@ -46,7 +46,7 @@ func=create_composite, name="create_composite", processing_config=LazyProcessingConfig( - variable_components=[VariableComponents.CHANNEL] + variable_components=[Microscopy.Channel] ), ) pipeline_steps.append(step_2) @@ -56,7 +56,7 @@ func=create_projection, name="Z-Stack Flattening", processing_config=LazyProcessingConfig( - variable_components=[VariableComponents.Z_INDEX] + variable_components=[Microscopy.ZIndex] ), ) pipeline_steps.append(step_3) @@ -84,7 +84,7 @@ func=create_projection, name="Z-Stack Flattening", processing_config=LazyProcessingConfig( - variable_components=[VariableComponents.Z_INDEX] + variable_components=[Microscopy.ZIndex] ), ) pipeline_steps.append(step_7) diff --git a/openhcs/domains/__init__.py b/openhcs/domains/__init__.py new file mode 100644 index 0000000000..74595e1e3b --- /dev/null +++ b/openhcs/domains/__init__.py @@ -0,0 +1 @@ +"""Domains: declarations that instantiate the domain-blind kernel.""" diff --git a/openhcs/domains/microscopy/__init__.py b/openhcs/domains/microscopy/__init__.py new file mode 100644 index 0000000000..fd51a4240e --- /dev/null +++ b/openhcs/domains/microscopy/__init__.py @@ -0,0 +1 @@ +"""The microscopy domain: high-content screening plates.""" diff --git a/openhcs/domains/microscopy/axes.py b/openhcs/domains/microscopy/axes.py new file mode 100644 index 0000000000..a86ce99ccf --- /dev/null +++ b/openhcs/domains/microscopy/axes.py @@ -0,0 +1,42 @@ +"""The microscopy axis family: the axes of a high-content screening plate.""" + +from openhcs.core.axes import ( + Axis, + AxisFamily, + ColourAxis, + DefaultGroupBy, + DefaultVariable, + LabelValued, + OrdinalValued, + PartitionAxis, + StackAxis, + TileAxis, + TimeAxis, +) + + +class Microscopy(AxisFamily): + """Plate axes in canonical filename order; wells run in parallel.""" + + class Site(Axis, TileAxis, DefaultVariable, OrdinalValued): + name = "site" + filename_prefix = "s" + filename_padding = 3 + + class Channel(Axis, ColourAxis, DefaultGroupBy, OrdinalValued): + name = "channel" + filename_prefix = "w" + + class ZIndex(Axis, StackAxis, OrdinalValued): + name = "z_index" + filename_prefix = "z" + filename_padding = 3 + + class Timepoint(Axis, TimeAxis, OrdinalValued): + name = "timepoint" + filename_prefix = "t" + filename_padding = 3 + + + class Well(Axis, PartitionAxis, LabelValued): + name = "well" diff --git a/openhcs/formats/pattern/pattern_discovery.py b/openhcs/formats/pattern/pattern_discovery.py index 79ffd2d958..1eb7b54c8f 100644 --- a/openhcs/formats/pattern/pattern_discovery.py +++ b/openhcs/formats/pattern/pattern_discovery.py @@ -10,11 +10,12 @@ import os from collections import defaultdict from pathlib import Path +from collections.abc import Sequence from typing import Any, Dict, List, Optional, Union from polystore.filemanager import FileManager -from openhcs.constants.constants import DEFAULT_IMAGE_EXTENSION +from openhcs.core.axes import Axis, AxisFamily, GroupingDeclaration from openhcs.core.components.parser_metaprogramming import FilenameParseResult from openhcs.core.runtime_pattern_cache import RuntimePatternDiscoveryCache @@ -67,9 +68,13 @@ def path_list_from_pattern( directory: Union[str, Path], pattern: str, backend: str, - variable_components: Optional[List[str]] = None, + variable_components: Optional[Sequence[type[Axis]]] = None, ) -> List[str]: """Get a list of filenames matching a pattern in a directory.""" + variable_axes = tuple( + AxisFamily.active().require(component) + for component in variable_components or () + ) directory_path = str(directory) # Keep as string for FileManager consistency if not self.filemanager.is_dir(directory_path, backend): raise FileNotFoundError(f"Directory not found: {directory_path}") @@ -118,7 +123,7 @@ def path_list_from_pattern( # Check if file matches pattern structure if self._matches_pattern_structure( - file_metadata, pattern_metadata, variable_components or [] + file_metadata, pattern_metadata, variable_axes ): matching_files.append(filename) @@ -128,14 +133,11 @@ def _matches_pattern_structure( self, file_metadata: FilenameParseResult, pattern_metadata: FilenameParseResult, - variable_components: List[str], + variable_components: Sequence[type[Axis]], ) -> bool: """Check if a file's metadata matches a pattern's structure.""" # Check all components in the pattern - variable_declarations = { - self.parser.component_for_name(component) - for component in variable_components - } + variable_declarations = set(variable_components) for component in self.parser.FILENAME_COMPONENTS: pattern_value = pattern_metadata.value_for(component) file_value = file_metadata.value_for(component) @@ -154,7 +156,7 @@ def _matches_pattern_structure( return True def group_patterns_by_component( - self, patterns: List[str], component: str + self, patterns: List[str], component: type[Axis] ) -> Dict[str, List[str]]: """ Group patterns by a required component. @@ -171,9 +173,7 @@ def group_patterns_by_component( ValueError: If component is not present in a pattern """ grouped_patterns = defaultdict(list) - # Validate inputs - if not component or not isinstance(component, str): - raise ValueError(f"Component must be a non-empty string, got {component}") + component_declaration = AxisFamily.active().require(component) if not all(isinstance(p, str) for p in patterns): raise TypeError("All patterns must be strings") @@ -186,11 +186,11 @@ def group_patterns_by_component( # For pattern discovery and grouping, we WANT patterns with placeholders metadata = self.pattern_cache.metadata_for_filename(self.parser, pattern_str) - component_declaration = self.parser.component_for_name(component) if metadata is None or metadata.value_for(component_declaration) is None: raise ValueError( - f"Missing required component '{component}' in pattern: {pattern_str}" + f"Missing required component '{component.name}' in pattern: " + f"{pattern_str}" ) value = str(metadata.value_for(component_declaration)) @@ -199,16 +199,14 @@ def group_patterns_by_component( return grouped_patterns def subdivide_patterns_by_components( - self, patterns: List[str], components: List[str] + self, patterns: List[str], components: Sequence[type[Axis]] ) -> Dict[tuple, List[str]]: """Subdivide patterns by multiple component values.""" if not components: return {(): patterns} subdivided = defaultdict(list) - component_declarations = tuple( - self.parser.component_for_name(component) for component in components - ) + component_declarations = tuple(components) for pattern in patterns: metadata = self.pattern_cache.metadata_for_filename(self.parser, str(pattern)) if not metadata: @@ -225,20 +223,17 @@ def subdivide_patterns_by_components( def auto_detect_patterns( self, folder_path: Union[str, Path], - variable_components: List[str], + variable_components: Sequence[type[Axis]], backend: str, extensions: List[str] = None, - group_by=None, # Accept GroupBy enum or None + group_by: type[GroupingDeclaration] | None = None, recursive: bool = False, **kwargs, # Dynamic filter parameters (e.g., well_filter, site_filter) ) -> Dict[str, Any]: """ Automatically detect image patterns in a folder. """ - # Extract axis_filter from dynamic kwargs - from openhcs.constants import MULTIPROCESSING_AXIS - - axis_name = MULTIPROCESSING_AXIS.value + axis_name = AxisFamily.active().partition_axis().name axis_filter = kwargs.get(f"{axis_name}_filter") files_by_axis = self._find_and_filter_images( @@ -257,15 +252,13 @@ def auto_detect_patterns( def auto_detect_patterns_from_files( self, image_paths: List[Union[str, Path]], - variable_components: List[str], - group_by=None, + variable_components: Sequence[type[Axis]], + group_by: type[GroupingDeclaration] | None = None, **kwargs, ) -> Dict[str, Any]: """Automatically detect image patterns from an authoritative file list.""" - from openhcs.constants import MULTIPROCESSING_AXIS - - axis_name = MULTIPROCESSING_AXIS.value + axis_name = AxisFamily.active().partition_axis().name axis_filter = kwargs.get(f"{axis_name}_filter") files_by_axis = self._filter_images_by_axis(image_paths, axis_filter) if not files_by_axis: @@ -281,8 +274,8 @@ def auto_detect_patterns_from_axis_files( image_paths: List[Union[str, Path]], *, axis_id: str, - variable_components: List[str], - group_by=None, + variable_components: Sequence[type[Axis]], + group_by: type[GroupingDeclaration] | None = None, ) -> Dict[str, Any]: """Detect patterns from files already selected for one runtime axis.""" if not axis_id: @@ -298,8 +291,8 @@ def auto_detect_patterns_from_axis_files( def _patterns_for_files_by_axis( self, files_by_axis: Dict[str, List[Any]], - variable_components: List[str], - group_by=None, + variable_components: Sequence[type[Axis]], + group_by: type[GroupingDeclaration] | None = None, ) -> Dict[str, Any]: result = {} for axis_value, files in files_by_axis.items(): @@ -314,15 +307,12 @@ def _patterns_for_files_by_axis( f"Pattern generator returned invalid type: {type(pattern).__name__}" ) - if group_by: - # Extract string value from GroupBy enum for pattern grouping - component_string = group_by.value if group_by.value else None - if component_string: - result[axis_value] = self.group_patterns_by_component( - patterns, component=component_string - ) - else: - result[axis_value] = patterns + grouping_axes = () if group_by is None else group_by.grouping_axes() + if grouping_axes: + (grouping_axis,) = grouping_axes + result[axis_value] = self.group_patterns_by_component( + patterns, component=grouping_axis + ) else: result[axis_value] = patterns @@ -393,14 +383,12 @@ def _filter_images_by_axis( if not metadata: continue - # Get multiprocessing axis dynamically from configuration - from openhcs.constants import MULTIPROCESSING_AXIS - + partition_axis = AxisFamily.active().partition_axis() matched_axis = next( ( str(axis_value) for axis_value in axis_filter - if metadata.component_matches(MULTIPROCESSING_AXIS, axis_value) + if metadata.component_matches(partition_axis, axis_value) ), None, ) @@ -412,7 +400,10 @@ def _filter_images_by_axis( return files_by_axis def _generate_patterns_for_files( - self, files: List[Any], variable_components: List[str], axis_value: str + self, + files: List[Any], + variable_components: Sequence[type[Axis]], + axis_value: str, ) -> List[str]: """Generate patterns for a list of files.""" # Validate input parameters @@ -421,10 +412,9 @@ def _generate_patterns_for_files( f"Expected list of file path objects, got {type(files).__name__}" ) - if not isinstance(variable_components, list): - raise TypeError( - f"Expected list of variable components, got {type(variable_components).__name__}" - ) + variable_declarations = { + AxisFamily.active().require(component) for component in variable_components + } # Use microscope-specific parser for pattern generation @@ -444,15 +434,11 @@ def _generate_patterns_for_files( if not metadata: continue - variable_declarations = { - self.parser.component_for_name(component) - for component in variable_components - } key_parts = [] for component in self.parser.FILENAME_COMPONENTS: value = metadata.value_for(component) if component not in variable_declarations and value is not None: - key_parts.append(f"{component.value}={value}") + key_parts.append(f"{component.name}={value}") key = ",".join(key_parts) component_combinations[key].append((file_path, metadata)) @@ -464,10 +450,6 @@ def _generate_patterns_for_files( _, template_metadata = files_metadata[0] # Generate pattern arguments for all discovered components - variable_declarations = { - self.parser.component_for_name(component) - for component in variable_components - } pattern_str = self.parser.construct_filename( template_metadata.with_values( ( diff --git a/openhcs/interop/cellprofiler/database_column_dialect.py b/openhcs/interop/cellprofiler/database_column_dialect.py index ea3b27433b..f2f2223190 100644 --- a/openhcs/interop/cellprofiler/database_column_dialect.py +++ b/openhcs/interop/cellprofiler/database_column_dialect.py @@ -459,7 +459,7 @@ def source_acquisition_values( if metadata is None: return {} return { - component.value: ( + component.name: ( SourceMetadataFields.canonical_component_value(component, domain[0]) if len(domain) == 1 else None diff --git a/openhcs/interop/cellprofiler/module_artifact_contracts.py b/openhcs/interop/cellprofiler/module_artifact_contracts.py index becb8f9bd5..c89f3d77ad 100644 --- a/openhcs/interop/cellprofiler/module_artifact_contracts.py +++ b/openhcs/interop/cellprofiler/module_artifact_contracts.py @@ -6,7 +6,6 @@ from dataclasses import replace from typing import TYPE_CHECKING -from openhcs.constants.constants import AllComponents from openhcs.core.artifacts import ( ArtifactInputPlan, ArtifactOutputPlan, @@ -168,14 +167,15 @@ def advance_artifact_context( producer_groups: tuple[str | None, ...] = (invocation_key.group_key,) elif ( step_context.source_bindings.binding_declarations - and step_context.group_by.value is not None + and step_context.group_by.grouping_axes() ): + (grouped_component,) = step_context.group_by.grouping_axes() scoped_outputs = tuple( spec for spec in contract.artifact_outputs if spec.group_scope_sources() ) producer_groups = ( step_context.source_bindings.component_group_keys_for_artifact_specs( - AllComponents.from_value(step_context.group_by.value), + grouped_component, scoped_outputs or contract.artifact_inputs, step_context.available_artifacts, ) @@ -207,7 +207,7 @@ def _artifact_context_for_group( source_bindings = step_context.source_bindings main_flow_artifacts = step_context.main_flow_artifacts if group_key != DEFAULT_GROUP_KEY and source_bindings.binding_declarations: - grouped_component = AllComponents.from_value(step_context.group_by.value) + (grouped_component,) = step_context.group_by.grouping_axes() scoped_bindings = tuple( binding for binding in source_bindings.binding_declarations @@ -221,7 +221,8 @@ def _artifact_context_for_group( for binding in scoped_bindings ): raise ValueError( - f"No source binding declares {grouped_component.value} " + f"No source binding declares {grouped_component.name} " + f"group {group_key!r}." ) source_bindings = replace( diff --git a/openhcs/interop/cellprofiler/module_callable_abi.py b/openhcs/interop/cellprofiler/module_callable_abi.py index 97be2bc389..ceb212050f 100644 --- a/openhcs/interop/cellprofiler/module_callable_abi.py +++ b/openhcs/interop/cellprofiler/module_callable_abi.py @@ -15,7 +15,6 @@ get_type_hints, ) -from openhcs.constants.constants import VariableComponents from openhcs.core.artifacts import ( ArtifactSpec, ArtifactSpecCollection, @@ -29,6 +28,7 @@ annotation_produces_runtime_type, ) from openhcs.core.runtime_object_labels import ObjectLabelValue +from openhcs.core.axes import Axis if TYPE_CHECKING: from openhcs.core.aligned_image_payload import ImagePayloadExecutionMode @@ -115,7 +115,7 @@ def execution_mode( *, image: "RuntimeCallableArgument", kwargs: "RuntimeCallableKwargs", - variable_components: tuple[VariableComponents, ...], + variable_components: tuple[type[Axis], ...], ) -> "ImagePayloadExecutionMode": """Return the default runtime image execution mode.""" diff --git a/openhcs/interop/cellprofiler/module_declarations.py b/openhcs/interop/cellprofiler/module_declarations.py index 6526528ea9..a8f519cfd8 100644 --- a/openhcs/interop/cellprofiler/module_declarations.py +++ b/openhcs/interop/cellprofiler/module_declarations.py @@ -18,7 +18,6 @@ from metaclass_registry import AutoRegisterMeta, LazyDiscoveryDict, RegistryConfig -from openhcs.constants.constants import AllComponents, GroupBy, VariableComponents from openhcs.constants.input_source import InputSource from openhcs.core.artifacts import ArtifactSpec, ArtifactSpecRef from openhcs.core.callable_contract import ( @@ -60,6 +59,14 @@ from openhcs.processing.backends.lib_registry.openhcs_registry import ( OpenHCSFunctionCatalogDeclaration, ) +from openhcs.core.axes import ( + Axis, + AxisFamily, + AxisRole, + GroupingDeclaration, + Ungrouped, +) + _CELLPROFILER_BACKEND_PACKAGE = "openhcs.processing.backends.cellprofiler" _CELLPROFILER_MODULE_REGISTRY = LazyDiscoveryDict(enable_cache=False) @@ -171,8 +178,10 @@ class CellProfilerModule( confidence: ClassVar[float] = 0.5 validated: ClassVar[bool] = False respects_masks: ClassVar[bool] = False - group_by: ClassVar[GroupBy | None] = None - """Whether coalesced generated emissions must stay explicit per group. + group_by_role: ClassVar[type[AxisRole] | None] = None + """Axis role this module's invocations group by (resolved per family). + + Whether coalesced generated emissions must stay explicit per group. Most grouped emissions with identical public callable settings can be exposed as one normal OpenHCS callable. Modules that need per-group invocation @@ -375,11 +384,13 @@ def __init_subclass__(cls, **kwargs: object) -> None: ) cls.confidence = float(cls.confidence) cls.validated = bool(cls.validated) - if cls.group_by is not None: - cls.group_by = ( - cls.group_by - if isinstance(cls.group_by, GroupBy) - else GroupBy(cls.group_by) + if cls.group_by_role is not None and not ( + isinstance(cls.group_by_role, type) + and issubclass(cls.group_by_role, AxisRole) + ): + raise TypeError( + f"{cls.__name__}.group_by_role must be an axis role, got " + f"{cls.group_by_role!r}." ) _validate_unique_module_names(cls) CellProfilerModule._measurement_feature_marker_types_for_key_payload.__func__.cache_clear() @@ -962,29 +973,36 @@ def processing_config( f"{type(inherited).__name__}." ) if callable_contract.execution_scope is FunctionStepExecutionScope.PLATE: - variable_components: tuple[VariableComponents, ...] = () - group_by = GroupBy.NONE + variable_components: tuple[type[Axis], ...] = () + group_by: type[GroupingDeclaration] | None = Ungrouped input_source = InputSource.PREVIOUS_STEP else: - variable_components = tuple( - callable_contract.required_variable_components - or inherited.variable_components + family = AxisFamily.active() + required_axes = tuple( + dict.fromkeys( + axis + for role in callable_contract.required_axis_roles + for axis in family.with_role(role) + ) + ) + variable_components = required_axes or tuple(inherited.variable_components) + group_by = ( + family.one(cls.group_by_role) + if cls.group_by_role is not None + else inherited.group_by ) - group_by = cls.group_by if cls.group_by is not None else inherited.group_by input_source = inherited.input_source - if ( - group_by is not None - and group_by.value is not None - and step_context is not None - ): - grouping_component = AllComponents.from_value(group_by.value) + grouping_axes = () if group_by is None else group_by.grouping_axes() + if grouping_axes and step_context is not None: + (grouping_component,) = grouping_axes source_anchor_group_keys = step_context.source_bindings.component_group_keys_for_artifact_specs( + grouping_component, cls.processing_group_scope_inputs(callable_contract), step_context.available_artifacts, ) if len(source_anchor_group_keys) > 1: - group_by = GroupBy.NONE + group_by = Ungrouped return replace( inherited, variable_components=list(variable_components), diff --git a/openhcs/interop/cellprofiler/pipeline_import.py b/openhcs/interop/cellprofiler/pipeline_import.py index 636ada709b..8df4dd086a 100644 --- a/openhcs/interop/cellprofiler/pipeline_import.py +++ b/openhcs/interop/cellprofiler/pipeline_import.py @@ -13,7 +13,7 @@ resolve_lazy_configurations_for_serialization, ) -from openhcs.constants import AllComponents, Backend, GroupBy, VariableComponents +from openhcs.constants import Backend from openhcs.constants.input_source import InputSource from openhcs.core.artifacts import ( ArtifactInputPlan, @@ -23,7 +23,6 @@ ArtifactSpecRef, ) from openhcs.core.callable_contract import CallableContract -from openhcs.core.component_set import ComponentSet from openhcs.core.config import ( LazyProcessingConfig, LazyStepSourceBindingsConfig, @@ -57,6 +56,7 @@ SettingsBinder, SettingToKeywordBinding, ) +from openhcs.core.axes import AxisFamily, Ungrouped @dataclass(frozen=True, slots=True) @@ -332,7 +332,7 @@ def _parsed_pipeline_declaration( forward_context = ArtifactDeclarationStepContext().with_source_binding_scope( source_bindings=step_source_bindings, - group_by=GroupBy.NONE, + group_by=Ungrouped, input_source=InputSource.PIPELINE_START, ) target_units = _parsed_target_units( @@ -358,25 +358,24 @@ def _pipeline_processing_config( ) -> ProcessingConfig: """Resolve pipeline-wide axes from exact source and callable declarations.""" - variable_components = tuple( - VariableComponents(component.value) - for component in source_bindings.source_stack_components - ) + family = AxisFamily.active() + variable_components = tuple(source_bindings.source_stack_components) if source_bindings.grouping_metadata_fields: grouped_components = tuple( dict.fromkeys( - component + axis for module_type, _module in executable_modules for function_name in module_type.declared_function_names() - for component in CallableContract.from_callable( + for role in CallableContract.from_callable( module_type.require_callable(function_name) - ).required_variable_components + ).required_axis_roles + for axis in family.with_role(role) ) ) if len(grouped_components) > 1: raise ValueError( "CellProfiler source grouping contains callables with incompatible " - f"required variable components {grouped_components!r}." + f"required axis roles {grouped_components!r}." ) variable_components = tuple( dict.fromkeys((*variable_components, *grouped_components)) @@ -385,13 +384,10 @@ def _pipeline_processing_config( return ProcessingConfig() inherited = ProcessingConfig() group_by = inherited.group_by - if ( - group_by is not None - and group_by.value is not None - and AllComponents.from_value(group_by.value) - in ComponentSet.from_enum_values(variable_components) + if group_by is not None and any( + axis in variable_components for axis in group_by.grouping_axes() ): - group_by = GroupBy.NONE + group_by = Ungrouped return replace( inherited, variable_components=list(variable_components), @@ -948,7 +944,8 @@ def _lower_module_batch( ) lineage_keys: tuple[tuple[str, ...], ...] = ((),) * len(units) if source_group_keys: - group_component = AllComponents.from_value(processing_config.group_by.value) + (group_component,) = processing_config.group_by.grouping_axes() + lineage_keys = tuple( source_bindings.component_group_keys_for_artifact_specs( group_component, diff --git a/openhcs/mcp/dev_client.py b/openhcs/mcp/dev_client.py index ac95337138..b4a874e62a 100644 --- a/openhcs/mcp/dev_client.py +++ b/openhcs/mcp/dev_client.py @@ -19,7 +19,6 @@ FullLocalCapabilitySurfaceProfile, LocalCapabilitySurfaceProfile, ) -from openhcs.constants.constants import AllComponents as AllComponents from openhcs.mcp.dev_client_core import ( DEFAULT_CALL_TIMEOUT_SECONDS, DEFAULT_REGISTRY_DISCOVERY_TIMEOUT_SECONDS as DEFAULT_REGISTRY_DISCOVERY_TIMEOUT_SECONDS, @@ -54,7 +53,6 @@ _DECLARATION_MODULES = (dev_client_commands,) __all__ = ( - "AllComponents", "DEFAULT_CODE_DOCUMENT_MAX_CHARS", "DEFAULT_REGISTRY_DISCOVERY_TIMEOUT_SECONDS", "McpDevCliUsageError", diff --git a/openhcs/mcp/dev_client_commands/viewer.py b/openhcs/mcp/dev_client_commands/viewer.py index 992f06a5c9..bccc88c3c7 100644 --- a/openhcs/mcp/dev_client_commands/viewer.py +++ b/openhcs/mcp/dev_client_commands/viewer.py @@ -341,7 +341,7 @@ def configure_parser(self, parser: argparse.ArgumentParser) -> None: parser.add_argument( "--require-components", action="store_true", - help="Require every OpenHCS component label declared by AllComponents.", + help="Require every OpenHCS component label declared by the active axis family.", ) parser.add_argument( "--allow-zero-payloads", diff --git a/openhcs/mcp/dev_client_core.py b/openhcs/mcp/dev_client_core.py index 89a59c0439..84b82a31de 100644 --- a/openhcs/mcp/dev_client_core.py +++ b/openhcs/mcp/dev_client_core.py @@ -56,7 +56,7 @@ from openhcs.agent.path_policy import AgentPathPolicy from openhcs.agent.runtime_platform import AgentRuntimePlatformAuthority from openhcs.agent.ui_bridge_environment import UiBridgeDescriptorEnvironment -from openhcs.constants.constants import AllComponents, OrchestratorState +from openhcs.constants.constants import OrchestratorState from openhcs.core.execution_state import ( ManagerExecutionState, TerminalExecutionStatus, @@ -72,6 +72,7 @@ from openhcs.agent.ui_bridge_environment import UIConfigCacheEnvironment from openhcs.runtime.import_authority import OpenHCSRuntimeImportAuthority from openhcs.utils.environment import OpenHCSProcessEnvironment +from openhcs.core.axes import AxisFamily if TYPE_CHECKING: from mcp.types import ProgressNotification @@ -2050,8 +2051,8 @@ def extend_required_component_labels( if not require_all_components: return labels seen = set(labels) - for component in AllComponents: - label = component.value + for component in AxisFamily.active().axes: + label = component.name if label not in seen: labels.append(label) seen.add(label) diff --git a/openhcs/mcp/dev_client_renderers/plate.py b/openhcs/mcp/dev_client_renderers/plate.py index 19db27c7f3..04baad34d1 100644 --- a/openhcs/mcp/dev_client_renderers/plate.py +++ b/openhcs/mcp/dev_client_renderers/plate.py @@ -31,6 +31,7 @@ McpDevPayloadProjection, McpDiagnosticRenderer, ) +from openhcs.core.axes import AxisFamily class PlateImageSampleRenderer(McpDevTypedOutputRenderer): @@ -665,21 +666,27 @@ def _component_lines( ) return lines + @staticmethod + def _summary_axis_names() -> tuple[str, ...]: + """Partition axis first, then the variable axes in declaration order.""" + + family = AxisFamily.active() + return ( + family.partition_axis().name, + *(axis.name for axis in family.variable_axes()), + ) + @classmethod def _axis_summary_line( cls, components: tuple[Mapping[str, JsonValue], ...], ) -> str: counts = cls._component_counts(components) - return ( - "Axis sizes: " - f"wells={cls._axis_count_text(counts, 'well')} " - f"sites={cls._axis_count_text(counts, 'site')} " - f"channels={cls._axis_count_text(counts, 'channel')} " - f"z={cls._axis_count_text(counts, 'z_index')} " - f"timepoints={cls._axis_count_text(counts, 'timepoint')} " - f"profile={cls._axis_profile_text(counts)}" + sizes = " ".join( + f"{name}={cls._axis_count_text(counts, name)}" + for name in cls._summary_axis_names() ) + return f"Axis sizes: {sizes} profile={cls._axis_profile_text(counts)}" @classmethod def _metadata_sources_line( @@ -694,7 +701,7 @@ def _metadata_sources_line( } ordered_parts = [ f"{component}={sources.get(component, '')}" - for component in ("well", "site", "channel", "z_index", "timepoint") + for component in cls._summary_axis_names() if component in sources ] return f"Metadata sources: {', '.join(ordered_parts) or ''}" @@ -722,37 +729,19 @@ def _axis_count_text(counts: Mapping[str, int], component: str) -> str: @classmethod def _axis_profile_text(cls, counts: Mapping[str, int]) -> str: - profile = ( - cls._axis_profile_part(counts, "site", "multi-site", "single-site"), - cls._axis_profile_part( - counts, - "channel", - "multi-channel", - "single-channel", - ), - cls._axis_profile_part(counts, "z_index", "3D", "2D"), - cls._axis_profile_part( - counts, - "timepoint", - "time-series", - "single-timepoint", - ), + return ",".join( + cls._axis_profile_part(counts, axis.name) + for axis in AxisFamily.active().variable_axes() ) - return ",".join(profile) @staticmethod - def _axis_profile_part( - counts: Mapping[str, int], - component: str, - multiple_label: str, - singleton_label: str, - ) -> str: + def _axis_profile_part(counts: Mapping[str, int], component: str) -> str: count = counts.get(component) if count is None: return f"unknown-{component}" if count > 1: - return multiple_label - return singleton_label + return f"multi-{component}" + return f"single-{component}" @staticmethod def _component_value_text(value: Mapping[str, JsonValue]) -> str: diff --git a/openhcs/mcp/installed_demo.py b/openhcs/mcp/installed_demo.py index ecd2e759e4..4ae3f4b0c8 100644 --- a/openhcs/mcp/installed_demo.py +++ b/openhcs/mcp/installed_demo.py @@ -28,7 +28,6 @@ from openhcs.agent.capabilities import agent_capabilities from openhcs.agent.dto.execution import ExecutionJobStatus, ExecutionStatusRequest -from openhcs.constants.constants import AllComponents from openhcs.core.config import LazyNapariStreamingConfig from openhcs.core.execution_state import TerminalExecutionStatus from openhcs.core.native_threading import configure_native_thread_environment @@ -58,6 +57,8 @@ from openhcs.runtime.zmq_config import OPENHCS_ZMQ_CONFIG from openhcs.runtime.zmq_execution_client import ZMQExecutionClient from openhcs.utils.environment import OpenHCSProcessEnvironment +from openhcs.core.axes import Axis +from openhcs.domains.microscopy.axes import Microscopy if TYPE_CHECKING: from openhcs.processing.presets.pipelines.loose_operaphenix_neurite_outgrowth import ( @@ -221,11 +222,11 @@ def _record_metadata(record: Mapping[str, Any]) -> Mapping[str, Any]: return metadata -def _record_component(record: Mapping[str, Any], component: AllComponents) -> str: - value = _record_metadata(record).get(component.value) +def _record_component(record: Mapping[str, Any], component: type[Axis]) -> str: + value = _record_metadata(record).get(component.name) if value is None: raise InstalledDemoFailure( - f"Generated image record is missing {component.value!r} metadata." + f"Generated image record is missing {component.name!r} metadata." ) return str(value) @@ -251,40 +252,40 @@ def _neurite_inputs( ordered = sorted( records, - key=lambda record: int(_record_component(record, AllComponents.CHANNEL)), + key=lambda record: int(_record_component(record, Microscopy.Channel)), ) first, second = ordered shared_components = ( - AllComponents.WELL, - AllComponents.SITE, - AllComponents.Z_INDEX, - AllComponents.TIMEPOINT, + Microscopy.Well, + Microscopy.Site, + Microscopy.ZIndex, + Microscopy.Timepoint, ) for component in shared_components: values = {_record_component(record, component) for record in ordered} if len(values) != 1: raise InstalledDemoFailure( "Generated image records disagree on " - f"{component.value}: {sorted(values)}" + f"{component.name}: {sorted(values)}" ) return LooseOperaPhenixNeuriteInputs( plate_path=plate_path, output_root=output_root, - well=_record_component(first, AllComponents.WELL), - site=_record_component(first, AllComponents.SITE), - z_index=_record_component(first, AllComponents.Z_INDEX), - timepoint=_record_component(first, AllComponents.TIMEPOINT), + well=_record_component(first, Microscopy.Well), + site=_record_component(first, Microscopy.Site), + z_index=_record_component(first, Microscopy.ZIndex), + timepoint=_record_component(first, Microscopy.Timepoint), viewer_port=viewer_port, hoechst=SemanticImageSource( alias="Hoechst", filename=_record_filename(first), - channel=_record_component(first, AllComponents.CHANNEL), + channel=_record_component(first, Microscopy.Channel), ), map2=None, smi312=SemanticImageSource( alias="SMI312", filename=_record_filename(second), - channel=_record_component(second, AllComponents.CHANNEL), + channel=_record_component(second, Microscopy.Channel), ), ) diff --git a/openhcs/microscopes/bioformats.py b/openhcs/microscopes/bioformats.py index 49afd24a7f..7d3123ac17 100644 --- a/openhcs/microscopes/bioformats.py +++ b/openhcs/microscopes/bioformats.py @@ -9,7 +9,7 @@ from polystore.filemanager import FileManager from polystore.ome_zarr_storage import OmeZarrStorageBackend -from openhcs.constants.constants import AllComponents, Backend, Microscope +from openhcs.constants.constants import Backend, Microscope from openhcs.core.source_binding_workspace import SourceBindingWorkspaceProjector from openhcs.core.source_bindings import ( SourceBindingsConfig, @@ -37,6 +37,7 @@ ) from openhcs.microscopes.source_schema import SourceSchemaFilenameParser from openhcs.microscopes.openhcs import OpenHCSMetadataHandler +from openhcs.core.axes import Axis, AxisFamily class BioFormatsFilenameParser(SourceSchemaFilenameParser): @@ -95,7 +96,7 @@ def physical_source_paths( def _component_values( self, plate_path: Union[str, Path], - component: AllComponents, + component: type[Axis], ) -> Optional[Dict[str, Optional[str]]]: values: dict[str, str | None] = {} for candidate in self.source_dataset(plate_path).candidates: @@ -103,11 +104,11 @@ def _component_values( if address is None: raise ValueError("Store candidate lacks an exact plane address.") coordinate = address.component_values()[component] - label = candidate.component_labels.get(component.value) + label = candidate.component_labels.get(component.name) previous = values.get(coordinate) if previous is not None and label is not None and previous != label: raise ValueError( - f"Conflicting {component.value} label for {coordinate!r}." + f"Conflicting {component.name} label for {coordinate!r}." ) values[coordinate] = label if label is not None else previous return dict(sorted(values.items())) or None @@ -154,7 +155,7 @@ def component_value_set( return MetadataComponentValueSet( ( (component, self._component_values(plate_path, component)) - for component in AllComponents + for component in AxisFamily.active().axes ) ) diff --git a/openhcs/microscopes/bioformats_adapter.py b/openhcs/microscopes/bioformats_adapter.py index 3e6a55b254..c32cf6e3ea 100644 --- a/openhcs/microscopes/bioformats_adapter.py +++ b/openhcs/microscopes/bioformats_adapter.py @@ -24,7 +24,7 @@ from polystore.virtual_workspace import SourcePixelRef from polystore.zarr_batch import ZarrStoredBatchSemantics -from openhcs.constants.constants import AllComponents, Backend +from openhcs.constants.constants import Backend from openhcs.core.image_file_serialization import ImageFileFormat from openhcs.core.source_bindings import SourceBindingsConfig from openhcs.core.source_matching import ( @@ -42,6 +42,7 @@ SourcePlaneStoreIdentity, ) from openhcs.microscopes.bioformats_well_key import BIOFORMATS_WELL_KEYS +from openhcs.domains.microscopy.axes import Microscopy if TYPE_CHECKING: from ome_zarr.format import Format @@ -420,12 +421,14 @@ def _image_candidates( ) candidates = [] for plane in image.pixels.planes: - address = OpenHCSPlaneAddress.from_values( - well=well, - site=site, - channel=str(plane.c), - z_index=str(plane.z), - timepoint=str(plane.t), + address = OpenHCSPlaneAddress( + ( + (Microscopy.Well, well), + (Microscopy.Site, site), + (Microscopy.Channel, str(plane.c)), + (Microscopy.ZIndex, str(plane.z)), + (Microscopy.Timepoint, str(plane.t)), + ) ) metadata: dict[str, object] = { "ome_image_id": image.image_id, @@ -465,11 +468,11 @@ def _image_candidates( source_axis_shape=source_axis_shape, source_filter_paths=filter_paths, component_labels={ - AllComponents.WELL.value: well_label, - AllComponents.SITE.value: site_label, - AllComponents.CHANNEL.value: image.channel_names[plane.c - 1], - AllComponents.Z_INDEX.value: None, - AllComponents.TIMEPOINT.value: None, + Microscopy.Well.name: well_label, + Microscopy.Site.name: site_label, + Microscopy.Channel.name: image.channel_names[plane.c - 1], + Microscopy.ZIndex.name: None, + Microscopy.Timepoint.name: None, }, declared_address=address, dataset_identity=dataset_identity, @@ -918,12 +921,14 @@ def discover_stores(self, root: Path) -> tuple[SourcePlaneDataset, ...]: ) relative_path = _relative_path(root, source_path) sample_id = OpenHCSPlaneAddress.component_token(relative_path) - address = OpenHCSPlaneAddress.from_values( - well=sample_id, - site="1", - channel="1", - z_index="1", - timepoint="1", + address = OpenHCSPlaneAddress( + ( + (Microscopy.Well, sample_id), + (Microscopy.Site, "1"), + (Microscopy.Channel, "1"), + (Microscopy.ZIndex, "1"), + (Microscopy.Timepoint, "1"), + ) ) metadata: dict[str, object] = {} for component, value in address.component_values().items(): @@ -937,11 +942,11 @@ def discover_stores(self, root: Path) -> tuple[SourcePlaneDataset, ...]: metadata=metadata, source_filter_paths=_physical_path_identities(root, source_path), component_labels={ - AllComponents.WELL.value: relative_path, - AllComponents.SITE.value: None, - AllComponents.CHANNEL.value: None, - AllComponents.Z_INDEX.value: None, - AllComponents.TIMEPOINT.value: None, + Microscopy.Well.name: relative_path, + Microscopy.Site.name: None, + Microscopy.Channel.name: None, + Microscopy.ZIndex.name: None, + Microscopy.Timepoint.name: None, }, declared_address=address, dataset_identity=identity, @@ -1327,12 +1332,14 @@ def _ngff_image_candidates( "NGFF image declares unsupported nonspatial axes " f"{tuple(coordinates)!r}." ) - address = OpenHCSPlaneAddress.from_values( - well=well, - site=str(site), - channel=str(channel), - z_index=str(z_index), - timepoint=str(timepoint), + address = OpenHCSPlaneAddress( + ( + (Microscopy.Well, well), + (Microscopy.Site, str(site)), + (Microscopy.Channel, str(channel)), + (Microscopy.ZIndex, str(z_index)), + (Microscopy.Timepoint, str(timepoint)), + ) ) metadata: dict[str, object] = { "ngff_dataset_id": dataset_identity.value, @@ -1356,11 +1363,11 @@ def _ngff_image_candidates( source_axis_shape=source_axis_shape, source_filter_paths=filter_paths, component_labels={ - AllComponents.WELL.value: well, - AllComponents.SITE.value: None, - AllComponents.CHANNEL.value: channel_labels[channel_index], - AllComponents.Z_INDEX.value: None, - AllComponents.TIMEPOINT.value: None, + Microscopy.Well.name: well, + Microscopy.Site.name: None, + Microscopy.Channel.name: channel_labels[channel_index], + Microscopy.ZIndex.name: None, + Microscopy.Timepoint.name: None, }, declared_address=address, dataset_identity=dataset_identity, diff --git a/openhcs/microscopes/imagexpress.py b/openhcs/microscopes/imagexpress.py index dcad2bcd4d..839e505431 100644 --- a/openhcs/microscopes/imagexpress.py +++ b/openhcs/microscopes/imagexpress.py @@ -10,7 +10,7 @@ from pathlib import Path from typing import List, Optional, Tuple, Union, Type -from openhcs.constants.constants import AllComponents, Backend, Microscope +from openhcs.constants.constants import Backend, Microscope from openhcs.core.components.parser_metaprogramming import ( format_filename_component, ) @@ -25,6 +25,8 @@ MetadataHandler, MicroscopeImagePathParser, ) +from openhcs.core.axes import Axis +from openhcs.domains.microscopy.axes import Microscopy logger = logging.getLogger(__name__) @@ -36,12 +38,12 @@ class ImageXpressTimePointPaths(MicroscopeImagePathParser): def image_path_components( self, path: Path - ) -> tuple[tuple[AllComponents, int], ...]: + ) -> tuple[tuple[type[Axis], int], ...]: return ( *super().image_path_components(path), *self.indexed_folder_components( path, - AllComponents.TIMEPOINT, + Microscopy.Timepoint, self._timepoint_folder_pattern, ), ) @@ -54,12 +56,12 @@ class ImageXpressZStepPaths(MicroscopeImagePathParser): def image_path_components( self, path: Path - ) -> tuple[tuple[AllComponents, int], ...]: + ) -> tuple[tuple[type[Axis], int], ...]: return ( *super().image_path_components(path), *self.indexed_folder_components( path, - AllComponents.Z_INDEX, + Microscopy.ZIndex, self._zstep_folder_pattern, ), ) @@ -238,11 +240,11 @@ def parse_filename(self, filename: str) -> Optional[FilenameParseResult]: # Use the parsed components in the result result = FilenameParseResult( ( - (AllComponents.WELL, well), - (AllComponents.SITE, site), - (AllComponents.CHANNEL, channel), - (AllComponents.Z_INDEX, z_index), - (AllComponents.TIMEPOINT, timepoint), + (Microscopy.Well, well), + (Microscopy.Site, site), + (Microscopy.Channel, channel), + (Microscopy.ZIndex, z_index), + (Microscopy.Timepoint, timepoint), ), extension=ext if ext else ".tif", ) @@ -292,11 +294,11 @@ def construct_filename( ) -> str: """Construct an ImageXpress filename from nominal component values.""" - well = components.required_value(AllComponents.WELL) - site = components.required_value(AllComponents.SITE) - channel = components.required_value(AllComponents.CHANNEL) - z_index = components.value_for(AllComponents.Z_INDEX) - timepoint = components.value_for(AllComponents.TIMEPOINT) + well = components.required_value(Microscopy.Well) + site = components.required_value(Microscopy.Site) + channel = components.required_value(Microscopy.Channel) + z_index = components.value_for(Microscopy.ZIndex) + timepoint = components.value_for(Microscopy.Timepoint) parts = [f"{plate_name}_{well}" if plate_name is not None else well] @@ -327,7 +329,7 @@ def construct_acquisition_filename( """Own MetaXpress acquisition spelling, including folder-only Z axes.""" if not include_all_components or plate_name is not None: components = components.with_values( - ((AllComponents.Z_INDEX, None), (AllComponents.TIMEPOINT, None)) + ((Microscopy.ZIndex, None), (Microscopy.Timepoint, None)) ) return self.construct_filename( components, @@ -515,7 +517,7 @@ def component_value_set( if wave_name: channel_mapping[wave_num] = wave_name return MetadataComponentValueSet.from_partial( - ((AllComponents.CHANNEL, channel_mapping or None),) + ((Microscopy.Channel, channel_mapping or None),) ) diff --git a/openhcs/microscopes/microscope_base.py b/openhcs/microscopes/microscope_base.py index bc00147f5e..f191d54fa9 100644 --- a/openhcs/microscopes/microscope_base.py +++ b/openhcs/microscopes/microscope_base.py @@ -14,7 +14,7 @@ from typing import List, Optional, Tuple, Union, Type, TYPE_CHECKING # Import constants -from openhcs.constants.constants import AllComponents, Backend, Microscope +from openhcs.constants.constants import Backend, Microscope # Import generic metaclass infrastructure from external package from metaclass_registry import ( @@ -36,6 +36,7 @@ MetadataHandler, MicroscopeImagePathParser, ) +from openhcs.domains.microscopy.axes import Microscopy logger = logging.getLogger(__name__) @@ -649,14 +650,14 @@ def post_workspace( continue # Validate required components - site = metadata.value_for(AllComponents.SITE) + site = metadata.value_for(Microscopy.Site) if site is None: logger.warning( "Missing 'site' component in filename: %s", original_name ) continue - channel = metadata.value_for(AllComponents.CHANNEL) + channel = metadata.value_for(Microscopy.Channel) if channel is None: logger.warning( "Missing 'channel' component in filename: %s", original_name @@ -664,7 +665,7 @@ def post_workspace( continue # z_index is optional - default to 1 if not present - z_index = metadata.value_for(AllComponents.Z_INDEX) + z_index = metadata.value_for(Microscopy.ZIndex) if z_index is None: z_index = 1 @@ -679,7 +680,7 @@ def post_workspace( # Reconstruct the filename with proper padding new_name = parser.construct_filename( - metadata.with_value(AllComponents.Z_INDEX, z_index) + metadata.with_value(Microscopy.ZIndex, z_index) ) # Add to rename map if different @@ -778,8 +779,8 @@ def auto_detect_patterns( filemanager: FileManager instance for file operations backend: Backend to use for file operations (required) extensions: Optional list of file extensions to include - group_by: GroupBy enum to group patterns by (e.g., GroupBy.CHANNEL, GroupBy.Z_INDEX) - variable_components: List of components to make variable (e.g., ['site', 'z_index']) + group_by: Grouping declaration to group patterns by (an axis or Ungrouped) + variable_components: Axes to make variable (e.g., the site and z axes) **kwargs: Dynamic filter parameters (e.g., well_filter, site_filter, channel_filter) Returns: @@ -823,9 +824,10 @@ def path_list_from_pattern( pattern, filemanager: FileManager, backend: str, - variable_components: Optional[List[str]] = None, + variable_components=None, *, pattern_cache: "RuntimePatternDiscoveryCache | None" = None, + ): """ Delegate to pattern engine. @@ -835,7 +837,7 @@ def path_list_from_pattern( pattern: Pattern to match (str for literal filenames) filemanager: FileManager instance for file operations backend: Backend to use for file operations (required) - variable_components: List of components that can vary (will be ignored during matching) + variable_components: Axes that can vary (ignored during matching) Returns: List of matching filenames diff --git a/openhcs/microscopes/microscope_interfaces.py b/openhcs/microscopes/microscope_interfaces.py index 4327a1b6e0..44a1287b10 100644 --- a/openhcs/microscopes/microscope_interfaces.py +++ b/openhcs/microscopes/microscope_interfaces.py @@ -13,12 +13,12 @@ from pathlib import Path import re from typing import ClassVar, Dict, Mapping, Optional, TYPE_CHECKING, Tuple, Union -from openhcs.constants.constants import Backend, AllComponents +from openhcs.constants.constants import Backend from openhcs.core.components.parser_metaprogramming import ( FilenameParseResult, GenericFilenameParser, ) -from openhcs.core.components.component_values import OpenHCSComponentValues +from openhcs.core.components.component_values import AxisValues from openhcs.core.source_metadata import ( SourceMetadataValue, SourceVoxelSpacing, @@ -32,6 +32,8 @@ ) from polystore.filemanager import FileManager from polystore.virtual_workspace import SourcePixelRef +from openhcs.core.axes import Axis, AxisFamily + if TYPE_CHECKING: from openhcs.core.source_projection import SourcePlaneDataset, SourceProjection @@ -89,10 +91,10 @@ class MetadataComponentValueSet: def __init__( self, component_values: Iterable[ - tuple[AllComponents, MetadataComponentValuesInput | None] + tuple[type[Axis], MetadataComponentValuesInput | None] ], ) -> None: - self._component_values = OpenHCSComponentValues( + self._component_values = AxisValues( ( ( component, @@ -106,12 +108,12 @@ def __init__( def from_partial( cls, component_values: Iterable[ - tuple[AllComponents, MetadataComponentValuesInput | None] + tuple[type[Axis], MetadataComponentValuesInput | None] ], ) -> "MetadataComponentValueSet": """Fill undeclared metadata axes with an explicit unavailable value.""" - partial = OpenHCSComponentValues.from_partial( + partial = AxisValues.from_partial( component_values, missing_value=None, ) @@ -119,13 +121,13 @@ def from_partial( def component_values( self, - ) -> tuple[tuple[AllComponents, MetadataComponentValues | None], ...]: + ) -> tuple[tuple[type[Axis], MetadataComponentValues | None], ...]: """Return component metadata in the order declared by OpenHCS axes.""" return self._component_values.declared_values() def values_for( self, - component: AllComponents, + component: type[Axis], ) -> MetadataComponentValues | None: """Return metadata values for one OpenHCS component declaration.""" return self._component_values.value_for(component) @@ -306,9 +308,7 @@ class FilenameParser( """ Abstract base class for parsing microscopy image filenames. - This class now uses the metaprogramming system to generate component-specific - methods dynamically based on the VariableComponents enum, eliminating hardcoded - component assumptions. + Parsers bind filename values to the axes of the active axis family. """ # Registry configuration for AutoRegisterMeta @@ -316,7 +316,7 @@ class FilenameParser( __registry_name__ = "filename parser" # Human-readable name for logging def __init__(self): - """Initialize the parser with AllComponents enum.""" + """Initialize the parser over the active axis family.""" self.pattern_format: str | None = None super().__init__() @@ -415,16 +415,16 @@ def parse_image_path(self, relative_path: str) -> FilenameParseResult | None: def image_path_components( self, path: Path - ) -> tuple[tuple[AllComponents, int], ...]: + ) -> tuple[tuple[type[Axis], int], ...]: """Identity terminus for cooperative acquisition-coordinate capabilities.""" return () @staticmethod def indexed_folder_components( path: Path, - component: AllComponents, + component: type[Axis], pattern: re.Pattern[str], - ) -> tuple[tuple[AllComponents, int], ...]: + ) -> tuple[tuple[type[Axis], int], ...]: """Project a declared folder grammar onto an existing nominal component.""" return tuple( (component, int(match.group(1))) @@ -648,7 +648,7 @@ def get_component_values( """Project display values at the viewer's string-keyed boundary.""" values = self.component_value_set(plate_path).values_for( - AllComponents(component_name) + AxisFamily.active().named(component_name) ) return None if values is None else dict(values) @@ -687,7 +687,7 @@ def parse_metadata( component_values = self.component_value_set(plate_path) for component, values in component_values.component_values(): if values: - result[component.value] = dict(values) + result[component.name] = dict(values) return result def build_metadata_view_document( diff --git a/openhcs/microscopes/omero.py b/openhcs/microscopes/omero.py index ff52391f1a..95508ecf9d 100644 --- a/openhcs/microscopes/omero.py +++ b/openhcs/microscopes/omero.py @@ -11,6 +11,7 @@ from typing import ClassVar from polystore import ( + OMEROAddressComponent, OMEROPlaneAddress, OMEROPlaneFilenameTemplate, OMEROWellAddress, @@ -18,7 +19,7 @@ from polystore.exceptions import MetadataNotFoundError from polystore.filemanager import FileManager -from openhcs.constants.constants import AllComponents, Backend, Microscope +from openhcs.constants.constants import Backend, Microscope from openhcs.microscopes.microscope_base import ( MicroscopeHandler, MicroscopeSourceSelectionRole, @@ -29,6 +30,7 @@ MetadataComponentValueSet, MetadataHandler, ) +from openhcs.domains.microscopy.axes import Microscopy logger = logging.getLogger(__name__) @@ -126,14 +128,14 @@ def _load_plate_metadata(self, plate_id: int) -> MetadataComponentValueSet: metadata = MetadataComponentValueSet.from_partial( ( - (AllComponents.CHANNEL, all_channels), - (AllComponents.WELL, all_wells), + (Microscopy.Channel, all_channels), + (Microscopy.Well, all_wells), ( - AllComponents.Z_INDEX, + Microscopy.ZIndex, {str(z + 1): f"Z{z + 1}" for z in range(max_z)}, ), ( - AllComponents.TIMEPOINT, + Microscopy.Timepoint, {str(t + 1): f"T{t + 1}" for t in range(max_t)}, ), ) @@ -288,6 +290,16 @@ def get_image_files( return [Path(f).name for f in virtual_files] +OMERO_ADDRESS_AXES = ( + (OMEROAddressComponent.WELL, Microscopy.Well), + (OMEROAddressComponent.SITE, Microscopy.Site), + (OMEROAddressComponent.CHANNEL, Microscopy.Channel), + (OMEROAddressComponent.Z_INDEX, Microscopy.ZIndex), + (OMEROAddressComponent.TIMEPOINT, Microscopy.Timepoint), +) +"""PolyStore's OMERO address components bound to the microscopy axes.""" + + class OMEROFilenameParser(FilenameParser): """ Parser for OMERO virtual filenames. @@ -310,8 +322,9 @@ def parse_filename(self, filename: str) -> FilenameParseResult | None: template = OMEROPlaneFilenameTemplate.from_filename(filename) if template is None: return None - return FilenameParseResult.from_projection( - template.projected_values(), + values = dict(template.projected_values()) + return FilenameParseResult( + ((axis, values[component]) for component, axis in OMERO_ADDRESS_AXES), extension=template.extension, ) @@ -321,11 +334,15 @@ def construct_filename(self, components: FilenameParseResult) -> str: OMERO always generates complete filenames with all components. """ - return OMEROPlaneFilenameTemplate.from_member_projection( - components.declared_values(), + return OMEROPlaneFilenameTemplate( + ( + (component, components.value_for(axis)) + for component, axis in OMERO_ADDRESS_AXES + ), extension=components.extension, ).filename() + def extract_component_coordinates(self, component_value: str) -> tuple[str, str]: """Extract coordinates from well identifier (e.g., 'A01' → ('A', '01')).""" diff --git a/openhcs/microscopes/openhcs.py b/openhcs/microscopes/openhcs.py index 245abfd737..be975cb0a4 100644 --- a/openhcs/microscopes/openhcs.py +++ b/openhcs/microscopes/openhcs.py @@ -24,7 +24,7 @@ cast, ) -from openhcs.constants.constants import AllComponents, Backend, Microscope +from openhcs.constants.constants import Backend, Microscope from openhcs.core.source_metadata import ( SourceComponentProjectionStrategy, SourceVoxelSpacing, @@ -55,6 +55,8 @@ MetadataViewDocument, MetadataViewEntry, ) +from openhcs.core.axes import Axis, AxisFamily +from openhcs.domains.microscopy.axes import Microscopy if TYPE_CHECKING: from openhcs.core.context.processing_context import ProcessingContext @@ -547,7 +549,7 @@ def _aggregate_subdirectory_metadata( plate_path, OpenHCSMetadata.component_collection_field(component), ) - for component in AllComponents + for component in AxisFamily.active().axes } ), FIELDS.AVAILABLE_BACKENDS: self._merge_subdirectory_mapping( @@ -740,7 +742,7 @@ def component_value_set( component_metadata_field(component), ), ) - for component in AllComponents + for component in AxisFamily.active().axes ) ) @@ -885,10 +887,10 @@ def __post_init__(self) -> None: pass @staticmethod - def component_collection_field(component: AllComponents) -> str: + def component_collection_field(component: type[Axis]) -> str: """Project one nominal component to its persisted collection field.""" - return SourceComponentProjectionStrategy.for_enum_member( + return SourceComponentProjectionStrategy.for_axis( component ).metadata_collection_field @@ -897,19 +899,19 @@ def component_fields(cls) -> tuple[str, ...]: """Derive the component collection fields from their nominal owners.""" return tuple( - cls.component_collection_field(component) for component in AllComponents + cls.component_collection_field(component) for component in AxisFamily.active().axes ) @classmethod def component_kwargs( cls, - values_by_component: Mapping[AllComponents, Any], + values_by_component: Mapping[type[Axis], Any], ) -> Dict[str, Any]: """Build component collection kwargs from one component-keyed mapping.""" return { cls.component_collection_field(component): values_by_component[component] - for component in AllComponents + for component in AxisFamily.active().axes } @classmethod @@ -929,7 +931,7 @@ def from_component_value_set( """Construct persisted metadata from the nominal component authority.""" def serialized_values( - component: AllComponents, + component: type[Axis], ) -> Optional[Dict[str, str | None]]: values = component_values.values_for(component) return None if values is None else dict(values) @@ -941,7 +943,7 @@ def serialized_values( pixel_size=pixel_size, image_files=image_files, **cls.component_kwargs( - {component: serialized_values(component) for component in AllComponents} + {component: serialized_values(component) for component in AxisFamily.active().axes} ), available_backends=available_backends, source_diagnostics=source_diagnostics, @@ -988,7 +990,7 @@ def _openhcs_metadata_from_subdirectory( component: subdirectory_data[ OpenHCSMetadata.component_collection_field(component) ] - for component in AllComponents + for component in AxisFamily.active().axes } ), available_backends=dict(subdirectory_data[FIELDS.AVAILABLE_BACKENDS]), @@ -1228,19 +1230,17 @@ def _extract_metadata_from_disk_state( component_metadata, context.metadata_cache ) - # CRITICAL: Use AllComponents enum for cache lookups (cache is keyed by AllComponents) - # GroupBy and AllComponents have same values but different hashes, so dict.get() fails with GroupBy return OpenHCSMetadata( microscope_handler_name=handler.microscope_type, source_filename_parser_name=handler.parser.__class__.__name__, grid_dimensions=grid_dimensions, pixel_size=pixel_size, image_files=relative_files, - channels=merged_metadata.get(AllComponents.CHANNEL), - wells=merged_metadata.get(AllComponents.WELL), - sites=merged_metadata.get(AllComponents.SITE), - z_indexes=merged_metadata.get(AllComponents.Z_INDEX), - timepoints=merged_metadata.get(AllComponents.TIMEPOINT), + channels=merged_metadata.get(Microscopy.Channel), + wells=merged_metadata.get(Microscopy.Well), + sites=merged_metadata.get(Microscopy.Site), + z_indexes=merged_metadata.get(Microscopy.ZIndex), + timepoints=merged_metadata.get(Microscopy.Timepoint), available_backends={request.write_backend: True}, workspace_mapping=None, # Preserve existing - filtered out by create_metadata() main=request.is_main if request.is_main else None, @@ -1249,7 +1249,7 @@ def _extract_metadata_from_disk_state( def _extract_component_metadata_from_files( self, file_paths: list, parser - ) -> Dict[AllComponents, Optional[Dict[str, Optional[str]]]]: + ) -> Dict[type[Axis], Optional[Dict[str, Optional[str]]]]: """ Extract component metadata by parsing actual filenames. @@ -1258,9 +1258,10 @@ def _extract_component_metadata_from_files( parser: FilenameParser instance Returns: - Dict mapping AllComponents to component metadata dicts (key -> display_name) + Dict mapping each axis to its component metadata (key -> display_name) + """ - result = {component: {} for component in AllComponents} + result = {component: {} for component in AxisFamily.active().axes} for file_path in file_paths: filename = Path(file_path).name @@ -1269,7 +1270,7 @@ def _extract_component_metadata_from_files( continue # Extract each component from the parsed filename - for component in AllComponents: + for component in AxisFamily.active().axes: parsed_value = parsed.value_for(component) if parsed_value is not None: component_value = str(parsed_value) @@ -1285,9 +1286,9 @@ def _extract_component_metadata_from_files( def _merge_component_metadata( self, - extracted: Dict[AllComponents, Optional[Dict[str, Optional[str]]]], - cache: Dict[AllComponents, Optional[Dict[str, Optional[str]]]], - ) -> Dict[AllComponents, Optional[Dict[str, Optional[str]]]]: + extracted: Dict[type[Axis], Optional[Dict[str, Optional[str]]]], + cache: Dict[type[Axis], Optional[Dict[str, Optional[str]]]], + ) -> Dict[type[Axis], Optional[Dict[str, Optional[str]]]]: """ Merge extracted component keys with display names from original metadata cache. @@ -1304,7 +1305,7 @@ def _merge_component_metadata( Merged metadata with actual components and preserved display names """ result = {} - for component in AllComponents: + for component in AxisFamily.active().axes: extracted_dict = extracted.get(component) cache_dict = cache.get(component) diff --git a/openhcs/microscopes/opera_phenix.py b/openhcs/microscopes/opera_phenix.py index 5ae088b1ec..c38aed82b2 100644 --- a/openhcs/microscopes/opera_phenix.py +++ b/openhcs/microscopes/opera_phenix.py @@ -11,7 +11,7 @@ from pathlib import Path from typing import Any, Dict, List, Optional, Union, Type, Tuple -from openhcs.constants.constants import AllComponents, Backend, Microscope +from openhcs.constants.constants import Backend, Microscope from openhcs.core.components.parser_metaprogramming import ( format_filename_component, ) @@ -27,6 +27,7 @@ MetadataComponentValueSet, MetadataHandler, ) +from openhcs.domains.microscopy.axes import Microscopy logger = logging.getLogger(__name__) @@ -166,7 +167,7 @@ def _build_virtual_mapping( metadata = self.parser.parse_filename(file_name) if metadata is None: continue - original_field_id = metadata.value_for(AllComponents.SITE) + original_field_id = metadata.value_for(Microscopy.Site) if original_field_id is None: continue @@ -176,7 +177,7 @@ def _build_virtual_mapping( # Construct the new filename with proper padding new_name = self.parser.construct_filename( metadata.with_value( - AllComponents.SITE, + Microscopy.Site, new_field_id, ) ) @@ -263,11 +264,11 @@ def _fill_missing_images( sample_metadata = metadata # Collect dimension values - well = metadata.value_for(AllComponents.WELL) - channel = metadata.value_for(AllComponents.CHANNEL) - site = metadata.value_for(AllComponents.SITE) - z_index = metadata.value_for(AllComponents.Z_INDEX) - timepoint = metadata.value_for(AllComponents.TIMEPOINT) + well = metadata.value_for(Microscopy.Well) + channel = metadata.value_for(Microscopy.Channel) + site = metadata.value_for(Microscopy.Site) + z_index = metadata.value_for(Microscopy.ZIndex) + timepoint = metadata.value_for(Microscopy.Timepoint) if well: wells.add(well) @@ -338,11 +339,11 @@ def _fill_missing_images( filename = self.parser.construct_filename( sample_metadata.with_values( ( - (AllComponents.WELL, well), - (AllComponents.CHANNEL, channel), - (AllComponents.SITE, site), - (AllComponents.Z_INDEX, z_index), - (AllComponents.TIMEPOINT, timepoint), + (Microscopy.Well, well), + (Microscopy.Channel, channel), + (Microscopy.Site, site), + (Microscopy.ZIndex, z_index), + (Microscopy.Timepoint, timepoint), ) ), site_padding=3, # Virtual workspace uses standardized 3-digit padding @@ -495,11 +496,11 @@ def parse_comp(s): result = FilenameParseResult( ( - (AllComponents.WELL, well), - (AllComponents.SITE, site), - (AllComponents.CHANNEL, channel), - (AllComponents.Z_INDEX, z_index), - (AllComponents.TIMEPOINT, timepoint), + (Microscopy.Well, well), + (Microscopy.Site, site), + (Microscopy.Channel, channel), + (Microscopy.ZIndex, z_index), + (Microscopy.Timepoint, timepoint), ), extension=ext if ext else ".tif", ) @@ -516,11 +517,11 @@ def construct_filename( ) -> str: """Construct an Opera Phenix filename from nominal component values.""" - well = components.required_value(AllComponents.WELL) - site = components.required_value(AllComponents.SITE) - channel = components.required_value(AllComponents.CHANNEL) - z_index = components.required_value(AllComponents.Z_INDEX) - timepoint = components.required_value(AllComponents.TIMEPOINT) + well = components.required_value(Microscopy.Well) + site = components.required_value(Microscopy.Site) + channel = components.required_value(Microscopy.Channel) + z_index = components.required_value(Microscopy.ZIndex) + timepoint = components.required_value(Microscopy.Timepoint) row_name, column_name = self.extract_component_coordinates(well) row = ord(row_name) - ord("A") + 1 @@ -568,7 +569,7 @@ def remap_field_in_filename( metadata = self.parse_filename(filename) if metadata is None: return filename - site = metadata.value_for(AllComponents.SITE) + site = metadata.value_for(Microscopy.Site) if site is None: return filename @@ -580,7 +581,7 @@ def remap_field_in_filename( # This ensures all filenames have the same format, even if the field ID didn't change return self.construct_filename( metadata.with_value( - AllComponents.SITE, + Microscopy.Site, new_field_id, ) ) @@ -809,7 +810,7 @@ def component_value_set( ) channel_values = None return MetadataComponentValueSet.from_partial( - ((AllComponents.CHANNEL, channel_values),) + ((Microscopy.Channel, channel_values),) ) def create_xml_parser(self, xml_path: Union[str, Path]): diff --git a/openhcs/microscopes/source_schema.py b/openhcs/microscopes/source_schema.py index 5f0bd98a3b..a9a8ac9fe0 100644 --- a/openhcs/microscopes/source_schema.py +++ b/openhcs/microscopes/source_schema.py @@ -38,20 +38,10 @@ def extract_component_coordinates(self, component_value: str) -> tuple[str, str] return match.group(1), match.group(2) return component_value, "" - def construct_filename( - self, - components: FilenameParseResult, - site_padding: int = 3, - z_padding: int = 3, - timepoint_padding: int = 3, - ) -> str: + def construct_filename(self, components: FilenameParseResult) -> str: address = OpenHCSPlaneAddress.from_component_values( (component, components.required_value(component)) for component, _value in components.declared_values() ) - return address.filename( - extension=components.extension, - site_padding=site_padding, - z_padding=z_padding, - timepoint_padding=timepoint_padding, - ) + return address.filename(extension=components.extension) + diff --git a/openhcs/processing/backends/analysis/consolidate_analysis_results.py b/openhcs/processing/backends/analysis/consolidate_analysis_results.py index e2c80ee6f9..219851280c 100644 --- a/openhcs/processing/backends/analysis/consolidate_analysis_results.py +++ b/openhcs/processing/backends/analysis/consolidate_analysis_results.py @@ -26,7 +26,7 @@ import numpy as np import pandas as pd -from openhcs.constants.constants import AllComponents +from openhcs.core.axes import AxisFamily from openhcs.core.config import ( AnalysisConsolidationConfig, PlateMetadataConfig, @@ -167,7 +167,7 @@ def well_id_for(self, filename: str) -> str | None: parsed = self.filename_parser.parse_filename(filename) if parsed is None: return None - value = parsed.value_for(AllComponents.WELL) + value = parsed.value_for(AxisFamily.active().partition_axis()) if value is None: return None return str(value) diff --git a/openhcs/processing/backends/cellprofiler/alignment.py b/openhcs/processing/backends/cellprofiler/alignment.py index 7c1becdd96..62366caeaf 100644 --- a/openhcs/processing/backends/cellprofiler/alignment.py +++ b/openhcs/processing/backends/cellprofiler/alignment.py @@ -8,7 +8,8 @@ import numpy as np from metaclass_registry import AutoRegisterMeta from scipy.fftpack import fft2, ifft2 -from openhcs.constants.constants import GroupBy, MemoryType, VariableComponents +from openhcs.core.axes import ColourAxis, TileAxis +from openhcs.constants.constants import MemoryType from openhcs.core.aligned_image_payload import ( AlignedImageStack, ) @@ -25,7 +26,7 @@ SourceStackLineageSourceRelation, ) from openhcs.core.pipeline.function_contracts import ( - required_variable_components, + required_axis_roles, ) from python_introspect import public_names_from_objects from metaclass_registry.strategies import EnumKeyedStrategyMixin @@ -205,7 +206,7 @@ class AlignModule( module_name = "Align" function_name = "align" validated = True - group_by = GroupBy.SITE + group_by_role = TileAxis confidence = 1.0 class Method(Enum): @@ -1074,7 +1075,7 @@ def prepare_align() -> None: ).offset() -@required_variable_components(VariableComponents.CHANNEL) +@required_axis_roles(ColourAxis) @numpy(contract=ProcessingContract.PURE_3D) def align( image: RuntimeArrayData, diff --git a/openhcs/processing/backends/cellprofiler/colocalization.py b/openhcs/processing/backends/cellprofiler/colocalization.py index 49639292ae..ad52e43959 100644 --- a/openhcs/processing/backends/cellprofiler/colocalization.py +++ b/openhcs/processing/backends/cellprofiler/colocalization.py @@ -15,7 +15,8 @@ from metaclass_registry import AutoRegisterMeta import numpy as np -from openhcs.constants.constants import GroupBy, MemoryType, VariableComponents +from openhcs.core.axes import ColourAxis, TileAxis +from openhcs.constants.constants import MemoryType from openhcs.core.aligned_image_payload import ( AlignedImageStack, ImagePayloadExecutionMode, @@ -43,7 +44,7 @@ ObjectLabelInputExecutionMode, composed_image_payload, object_label_input_execution_mode, - required_variable_components, + required_axis_roles, resolved_callable_parameter, runtime_bound_parameters, special_inputs, @@ -533,7 +534,7 @@ class MeasureColocalizationModule( validated = True aliases = ("MeasureCorrelation",) function_variants = ("measure_colocalization_objects",) - group_by = GroupBy.SITE + group_by_role = TileAxis confidence = 1.0 measurement_category_prefixes = ( ("correlation",), @@ -2537,7 +2538,7 @@ def _colocalization_unit_interval_scale( return int(first_scale) -@required_variable_components(VariableComponents.CHANNEL) +@required_axis_roles(ColourAxis) @composed_image_payload @runtime_image_execution_mode(ImagePayloadExecutionMode.FULL_STACK) @numpy(contract=ProcessingContract.FLEXIBLE) @@ -2800,7 +2801,7 @@ def _measure_colocalization_objects_core( ) -@required_variable_components(VariableComponents.CHANNEL) +@required_axis_roles(ColourAxis) @composed_image_payload @numpy(contract=ProcessingContract.FLEXIBLE) @special_inputs("labels") diff --git a/openhcs/processing/backends/cellprofiler/color.py b/openhcs/processing/backends/cellprofiler/color.py index 9b6c42e6dd..1babbb8e84 100644 --- a/openhcs/processing/backends/cellprofiler/color.py +++ b/openhcs/processing/backends/cellprofiler/color.py @@ -13,7 +13,7 @@ from matplotlib.colors import CSS4_COLORS, to_rgb from metaclass_registry import AutoRegisterMeta -from openhcs.constants.constants import GroupBy, VariableComponents +from openhcs.core.axes import ColourAxis, TileAxis from openhcs.core.aligned_image_payload import ( AlignedImageSliceContext, AlignedImageStack, @@ -39,7 +39,7 @@ ) from openhcs.core.pipeline.function_contracts import ( composed_image_payload, - required_variable_components, + required_axis_roles, ) from openhcs.core.runtime_array_values import RuntimeArrayData from openhcs.core.runtime_image_values import ( @@ -643,7 +643,7 @@ class GrayToColorModule( module_name = "GrayToColor" function_name = "gray_to_color" validated = True - group_by = GroupBy.SITE + group_by_role = TileAxis confidence = 1.0 color_scheme_setting = SettingNameFamily("Select a color scheme") rescale_setting = SettingNameFamily("Rescale intensity") @@ -1542,7 +1542,7 @@ def run(self, request: GrayToColorRequest) -> np.ndarray: @declares_primary_image_carrier_transition( PrimaryImageCarrierTransition.CREATE_SOURCE_CHANNEL_AXIS, ) -@required_variable_components(VariableComponents.CHANNEL) +@required_axis_roles(ColourAxis) @composed_image_payload @numpy(contract=ProcessingContract.PURE_3D) def gray_to_color( @@ -2265,7 +2265,7 @@ class InvertForPrintingModule( "invert_for_printing_without_output", ) validated = True - group_by = GroupBy.SITE + group_by_role = TileAxis confidence = 1.0 input_mode_setting = "Input image type" diff --git a/openhcs/processing/backends/cellprofiler/contracts.json b/openhcs/processing/backends/cellprofiler/contracts.json index 12753203ae..179e184010 100644 --- a/openhcs/processing/backends/cellprofiler/contracts.json +++ b/openhcs/processing/backends/cellprofiler/contracts.json @@ -721,7 +721,7 @@ "contract": "pure_2d", "category": "image_operation", "confidence": 1.0, - "reasoning": "The Tile function is designed to arrange individual images (typically sites/fields of view) into a single large grid. It processes images independently and does not require volumetric Z-stacks or multiple channels simultaneously to perform its core logic. In the OpenHCS context, this is a per-site operation where the orchestrator handles the stacking of sites via variable_components=[VariableComponents.SITE].", + "reasoning": "The Tile function is designed to arrange individual images (typically sites/fields of view) into a single large grid. It processes images independently and does not require volumetric Z-stacks or multiple channels simultaneously to perform its core logic. In the OpenHCS context, this is a per-site operation where the orchestrator handles the stacking of sites via variable_components=[Microscopy.Site].", "validated": true }, "TrackObjects": { diff --git a/openhcs/processing/backends/cellprofiler/grid.py b/openhcs/processing/backends/cellprofiler/grid.py index 03f9c4ce5d..444cc4c1c6 100644 --- a/openhcs/processing/backends/cellprofiler/grid.py +++ b/openhcs/processing/backends/cellprofiler/grid.py @@ -16,7 +16,6 @@ from metaclass_registry import AutoRegisterMeta from numba import njit -from openhcs.constants.constants import VariableComponents from openhcs.core.aligned_image_payload import ImagePayloadExecutionMode from openhcs.core.runtime_array_values import RuntimeArrayData from openhcs.core.artifacts import ( @@ -84,6 +83,7 @@ parse_cellprofiler_int, ) from openhcs.processing.backends.lib_registry.unified_registry import ProcessingContract +from openhcs.core.axes import Axis if TYPE_CHECKING: from openhcs.core.artifacts import ArtifactSpec @@ -336,7 +336,7 @@ def execution_mode( *, image: RuntimeCallableArgument, kwargs: RuntimeCallableKwargs, - variable_components: tuple[VariableComponents, ...], + variable_components: tuple[type[Axis], ...], ) -> ImagePayloadExecutionMode: del cls, image, variable_components parameter_name = ( diff --git a/openhcs/processing/backends/cellprofiler/illumination.py b/openhcs/processing/backends/cellprofiler/illumination.py index 2fd02ed70b..4429677097 100644 --- a/openhcs/processing/backends/cellprofiler/illumination.py +++ b/openhcs/processing/backends/cellprofiler/illumination.py @@ -14,7 +14,7 @@ from metaclass_registry import AutoRegisterMeta from numba import njit -from openhcs.constants.constants import MemoryType, VariableComponents +from openhcs.constants.constants import MemoryType from openhcs.core.aligned_image_payload import ( AlignedImageStack, ImagePayloadExecutionMode, @@ -91,6 +91,7 @@ _fill_cellprofiler_line_points_numba, ) from openhcs.processing.backends.lib_registry.unified_registry import ProcessingContract +from openhcs.core.axes import Axis if TYPE_CHECKING: from openhcs.core.function_patterns import FunctionInvocationKey @@ -389,7 +390,7 @@ def execution_mode( *, image: RuntimeCallableArgument, kwargs: RuntimeCallableKwargs, - variable_components: tuple[VariableComponents, ...], + variable_components: tuple[type[Axis], ...], ) -> ImagePayloadExecutionMode: del cls, image, variable_components scope = kwargs.get("calculation_scope", CalculationScope.EACH) diff --git a/openhcs/processing/backends/cellprofiler/infrastructure.py b/openhcs/processing/backends/cellprofiler/infrastructure.py index 809171fe43..6da4215e7f 100644 --- a/openhcs/processing/backends/cellprofiler/infrastructure.py +++ b/openhcs/processing/backends/cellprofiler/infrastructure.py @@ -11,7 +11,6 @@ from pathlib import Path from typing import Callable, ClassVar -from openhcs.constants.constants import AllComponents from openhcs.core.artifacts import ( ArtifactType, ImageArtifactType, @@ -61,6 +60,7 @@ from openhcs.interop.cellprofiler.source_metadata import ( CellProfilerSourceMetadataField, ) +from openhcs.core.axes import Axis, AxisFamily, ColourAxis, StackAxis _METADATA_MATCH_PATTERN = re.compile( '\\(metadata does (?P[A-Za-z0-9_]+) \\"(?P[^\\"]+)\\"\\)' @@ -485,7 +485,7 @@ def _selector_from_rule_criteria(rule_criteria: str) -> SourceSelector: def _selector_component_identity( selector: SourceSelector, - component: AllComponents, + component: type[Axis], ) -> ComponentSelector | None: declared = tuple( candidate @@ -500,7 +500,7 @@ def _selector_component_identity( values = tuple(dict.fromkeys(candidate.value for candidate in declared)) if len(values) > 1: raise ValueError( - f"Source selector declares conflicting {component.value} values " + f"Source selector declares conflicting {component.name} values " f"{values!r}." ) if not values: @@ -510,7 +510,7 @@ def _selector_component_identity( def _metadata_rules_declare_component( config: SourceBindingsConfig, - component: AllComponents, + component: type[Axis], ) -> bool: return any( source_metadata_component(field) is component @@ -1310,9 +1310,11 @@ def contribute_source_bindings( bindings: list[NamedSourceBinding] = [] explicit_sources: list[ImagePlaneSource] = [] + # CellProfiler image names are the colour axis of the active family. + colour_axis = AxisFamily.active().one(ColourAxis) metadata_declares_channel = _metadata_rules_declare_component( config, - AllComponents.CHANNEL, + colour_axis, ) used_channel_values: set[str] = set() next_channel_index = 1 @@ -1346,13 +1348,13 @@ def contribute_source_bindings( if source_type.projection_role is SourceProjectionRole.PRIMARY_PLANE: channel_identity = _selector_component_identity( selector, - AllComponents.CHANNEL, + colour_axis, ) if channel_identity is None and not metadata_declares_channel: while str(next_channel_index) in used_channel_values: next_channel_index += 1 channel_identity = ComponentSelector( - component=AllComponents.CHANNEL, + component=colour_axis, value=str(next_channel_index), ) if channel_identity is not None: @@ -1396,7 +1398,7 @@ def contribute_source_bindings( while str(next_channel_index) in used_channel_values: next_channel_index += 1 channel_identity = ComponentSelector( - component=AllComponents.CHANNEL, + component=colour_axis, value=str(next_channel_index), ) used_channel_values.add(channel_identity.value) @@ -1412,7 +1414,9 @@ def contribute_source_bindings( source_spatial_domain = config.source_spatial_domain if module.get_setting("Process as 3D?", "No").strip().casefold() == "yes": source_stack_components = tuple( - dict.fromkeys((*source_stack_components, AllComponents.Z_INDEX)) + dict.fromkeys( + (*source_stack_components, AxisFamily.active().one(StackAxis)) + ) ) source_spatial_domain = VolumeSourceSpatialDomain() voxel_spacing = SourceVoxelSpacing.from_cellprofiler_xyz( diff --git a/openhcs/processing/backends/cellprofiler/morphology.py b/openhcs/processing/backends/cellprofiler/morphology.py index c9714fdc24..6f23124360 100644 --- a/openhcs/processing/backends/cellprofiler/morphology.py +++ b/openhcs/processing/backends/cellprofiler/morphology.py @@ -303,7 +303,10 @@ def resolve_function( del module, contract function_name = ( cls.function_variants[0] - if AllComponents.Z_INDEX in source_bindings.source_stack_components + if any( + issubclass(axis, StackAxis) + for axis in source_bindings.source_stack_components + ) else str(cls.function_name) ) return cls.require_callable(function_name) @@ -666,10 +669,8 @@ def artifact_output_relations( from typing import ClassVar from metaclass_registry import AutoRegisterMeta from numba import njit -from openhcs.constants.constants import ( - AllComponents, - MemoryType, -) +from openhcs.constants.constants import MemoryType +from openhcs.core.axes import StackAxis from openhcs.core.aligned_image_payload import ImagePayloadExecutionMode from openhcs.core.callable_contract import runtime_image_execution_mode from openhcs.core.memory.decorators import numpy as numpy_decorator diff --git a/openhcs/processing/backends/cellprofiler/outlines.py b/openhcs/processing/backends/cellprofiler/outlines.py index 817a501d6b..f92ca7f87b 100644 --- a/openhcs/processing/backends/cellprofiler/outlines.py +++ b/openhcs/processing/backends/cellprofiler/outlines.py @@ -24,7 +24,7 @@ import numpy as np from metaclass_registry import AutoRegisterMeta from numba import njit -from openhcs.constants.constants import MemoryType, VariableComponents +from openhcs.constants.constants import MemoryType from openhcs.core.artifacts import ( ArtifactSpec, ArtifactSpecCollection, @@ -79,6 +79,7 @@ ObjectLabelsInputBindingMixin, ) from openhcs.interop.cellprofiler.parser import ModuleBlock, ModuleSetting +from openhcs.core.axes import Axis if TYPE_CHECKING: from openhcs.core.function_patterns import ( @@ -136,7 +137,7 @@ def execution_mode( *, image: "RuntimeArrayData", kwargs: "RuntimeCallableKwargs", - variable_components: tuple[VariableComponents, ...], + variable_components: tuple[type[Axis], ...], ) -> ImagePayloadExecutionMode: """Preserve one payload-scoped object volume as one invocation.""" diff --git a/openhcs/processing/backends/cellprofiler/thresholding.py b/openhcs/processing/backends/cellprofiler/thresholding.py index ff8dfdc60a..af29360903 100644 --- a/openhcs/processing/backends/cellprofiler/thresholding.py +++ b/openhcs/processing/backends/cellprofiler/thresholding.py @@ -26,7 +26,7 @@ from metaclass_registry import AutoRegisterMeta from numba import njit -from openhcs.constants.constants import MemoryType, VariableComponents +from openhcs.constants.constants import MemoryType from openhcs.core.aligned_image_payload import ImagePayloadExecutionMode from openhcs.core.artifacts import ( ArtifactSpec, @@ -142,6 +142,7 @@ _yen_threshold_numba, ) from openhcs.processing.backends.lib_registry.unified_registry import ProcessingContract +from openhcs.core.axes import Axis, StackAxis if TYPE_CHECKING: from openhcs.core.artifacts import ArtifactSpecCollection, ArtifactSpecRelation @@ -3302,13 +3303,14 @@ def execution_mode( *, image, kwargs: RuntimeCallableKwargs, - variable_components: tuple[VariableComponents, ...], + variable_components: tuple[type[Axis], ...], ) -> ImagePayloadExecutionMode: """Execute CP volumetric thresholding only over a declared Z stack.""" del cls, image, kwargs - if VariableComponents.Z_INDEX in variable_components: + if any(issubclass(axis, StackAxis) for axis in variable_components): return default + return ImagePayloadExecutionMode.NATURAL @classmethod diff --git a/openhcs/processing/backends/cellprofiler/tracking.py b/openhcs/processing/backends/cellprofiler/tracking.py index 4502ec6308..7ca0016ce8 100644 --- a/openhcs/processing/backends/cellprofiler/tracking.py +++ b/openhcs/processing/backends/cellprofiler/tracking.py @@ -15,9 +15,10 @@ from metaclass_registry import AutoRegisterMeta from numba import njit +from openhcs.core.axes import TimeAxis from openhcs.processing.backends.cellprofiler._font_raster_native import rasterize -from openhcs.constants.constants import MemoryType, VariableComponents +from openhcs.constants.constants import MemoryType from openhcs.core.artifacts import ( ArtifactType, ImageArtifactType, @@ -38,7 +39,7 @@ from openhcs.core.pipeline.function_contracts import ( ObjectLabelInputExecutionMode, object_label_input_execution_mode, - required_variable_components, + required_axis_roles, special_inputs, ) from python_introspect import public_names_from_objects @@ -1319,7 +1320,7 @@ def _reverse_relationship_pairs( return tuple(pairs) -@required_variable_components(VariableComponents.TIMEPOINT) +@required_axis_roles(TimeAxis) @numpy(contract=ProcessingContract.PURE_3D) @object_label_input_execution_mode(ObjectLabelInputExecutionMode.FULL_STACK) @special_inputs("labels") diff --git a/openhcs/processing/backends/cellprofiler/worms.py b/openhcs/processing/backends/cellprofiler/worms.py index 4138fc2836..ecda6f97c2 100644 --- a/openhcs/processing/backends/cellprofiler/worms.py +++ b/openhcs/processing/backends/cellprofiler/worms.py @@ -11,6 +11,7 @@ import inspect +from openhcs.core.axes import ColourAxis, TileAxis from openhcs.interop.cellprofiler.setting_names import ( SettingNameFamily, block_setting_value, @@ -47,7 +48,6 @@ label, ) from python_introspect import set_signature_analysis_target -from openhcs.constants.constants import GroupBy, VariableComponents from openhcs.core.memory.decorators import numpy from openhcs.core.aligned_image_payload import ( AlignedImageStack, @@ -109,7 +109,7 @@ from openhcs.core.pipeline.function_contracts import ( ObjectLabelInputExecutionMode, object_label_input_execution_mode, - required_variable_components, + required_axis_roles, runtime_bound_parameters, special_inputs, ) @@ -710,7 +710,7 @@ class StraightenWormsModule( module_name = "StraightenWorms" function_name = "straighten_worms" validated = True - group_by = GroupBy.SITE + group_by_role = TileAxis confidence = 1.0 input_objects_setting = "Select the input untangled worm objects" @@ -2105,7 +2105,7 @@ def untangle_worms_both( del _function_name -@required_variable_components(VariableComponents.CHANNEL) +@required_axis_roles(ColourAxis) @numpy(contract=ProcessingContract.FLEXIBLE) @object_label_input_execution_mode(ObjectLabelInputExecutionMode.SLICE_ALIGNED) @special_inputs("worm_labels") diff --git a/openhcs/processing/backends/enhance/basic_processor_jax.py b/openhcs/processing/backends/enhance/basic_processor_jax.py index 12b0a5087f..439ea63a2f 100644 --- a/openhcs/processing/backends/enhance/basic_processor_jax.py +++ b/openhcs/processing/backends/enhance/basic_processor_jax.py @@ -6,7 +6,7 @@ from basicpy import BaSiC from basicpy.basicpy import FittingMode -from openhcs.constants.constants import GroupBy +from openhcs.core.axes import ColourAxis from openhcs.core.artifacts import ( ArtifactSidecarRole, ArtifactSpec, @@ -18,9 +18,9 @@ from openhcs.core.config import DtypeConfig from openhcs.core.memory import numpy as numpy_func from openhcs.core.pipeline.function_contracts import ( - allowed_group_by, + allowed_group_by_roles, artifact_outputs, - required_variable_components, + required_axis_roles, ) from openhcs.processing.backends.enhance.flatfield import FittedIlluminationFieldOutput from openhcs.processing.backends.lib_registry.unified_registry import ProcessingContract @@ -53,8 +53,9 @@ def _fitted_field_output(name: str) -> ArtifactSpec: @numpy_func(contract=ProcessingContract.PURE_3D, dtype_config_default=DtypeConfig()) -@allowed_group_by(GroupBy.CHANNEL) -@required_variable_components(FittedIlluminationFieldOutput.observation_axis) +@allowed_group_by_roles(ColourAxis) +@required_axis_roles(FittedIlluminationFieldOutput.observation_role) + @artifact_outputs(CORRECTED_OUTPUT, FLATFIELD_OUTPUT, DARKFIELD_OUTPUT) def basic_flatfield_correction_jax( image: np.ndarray, diff --git a/openhcs/processing/backends/enhance/flatfield.py b/openhcs/processing/backends/enhance/flatfield.py index 6e0669022e..69943d0a58 100644 --- a/openhcs/processing/backends/enhance/flatfield.py +++ b/openhcs/processing/backends/enhance/flatfield.py @@ -4,11 +4,11 @@ from enum import Enum from typing import ClassVar -from openhcs.constants.constants import AllComponents, VariableComponents from openhcs.core.projected_image_output import SourceProjectedImageOutput from openhcs.core.runtime_array_values import RuntimeArrayData from openhcs.core.runtime_image_values import image_payload_metadata from openhcs.core.runtime_plane_projection import RuntimePlaneAxisValueProjection +from openhcs.core.axes import AxisFamily, AxisRole, TileAxis class FlatfieldCorrectionMode(Enum): @@ -22,7 +22,7 @@ class FlatfieldCorrectionMode(Enum): class FittedIlluminationFieldOutput(SourceProjectedImageOutput): """One fitted field, owned by all independent observations, not one plane.""" - observation_axis: ClassVar[VariableComponents] = VariableComponents.SITE + observation_role: ClassVar[type[AxisRole]] = TileAxis data: RuntimeArrayData observation_count: int @@ -36,17 +36,19 @@ def __post_init__(self) -> None: def validate_observation_domain(cls, source: RuntimeArrayData) -> None: """Reject mislabeled metadata-backed ensembles before fitting.""" metadata = image_payload_metadata(source) + family = AxisFamily.active() retained_axes = tuple( - AllComponents.from_value(name) - for name in metadata.retained_plane_component_values() + family.named(name) for name in metadata.retained_plane_component_values() ) + observation_axes = family.with_role(cls.observation_role) # Plain NumPy observations have no claimed acquisition domain. Restrict # annotated sources using the metadata owner's declared presence state. - if metadata.has_values and retained_axes != ( - AllComponents.from_value(cls.observation_axis.value), + if metadata.has_values and ( + len(retained_axes) != 1 or retained_axes[0] not in observation_axes ): raise ValueError( - f"BaSiC requires independent {cls.observation_axis.name} observations " + f"BaSiC requires independent {cls.observation_role.__name__} " + f"observations ({', '.join(axis.name for axis in observation_axes)}) " "with every other source component fixed." ) diff --git a/openhcs/processing/backends/pos_gen/acquisition_positions.py b/openhcs/processing/backends/pos_gen/acquisition_positions.py index 35d6ab70bb..a655813851 100644 --- a/openhcs/processing/backends/pos_gen/acquisition_positions.py +++ b/openhcs/processing/backends/pos_gen/acquisition_positions.py @@ -5,7 +5,6 @@ import numpy as np from polystore.source_tile_geometry import SourceTileGeometry -from openhcs.constants.constants import AllComponents from openhcs.core.memory import numpy from openhcs.core.pipeline.function_contracts import artifact_outputs from openhcs.core.runtime_adapters import RuntimeAdapterRequest, runtime_adapter @@ -18,6 +17,7 @@ from openhcs.processing.backends.pos_gen.tile_position_artifacts import ( TILE_POSITIONS_OUTPUT, ) +from openhcs.core.axes import AxisFamily, TileAxis def _source_metadata(request: RuntimeAdapterRequest) -> ImagePayloadMetadata: @@ -64,8 +64,8 @@ def acquisition_tile_positions( record.source_component_metadata or {}, component, ) - for component in AllComponents - if component is not AllComponents.SITE + for component in AxisFamily.active().axes + if not issubclass(component, TileAxis) ) for record in records ) @@ -81,12 +81,14 @@ def acquisition_tile_positions( raise ValueError( "Source tiles lack exact embedded acquisition geometry; no grid is inferred." ) + tile_axis = AxisFamily.active().one(TileAxis) sites = tuple( source_component_metadata_value( - record.source_component_metadata or {}, AllComponents.SITE + record.source_component_metadata or {}, tile_axis ) for record in records ) + if None in sites or len(sites) != len(set(sites)): raise ValueError( "Every acquisition tile must carry a distinct source site identity." diff --git a/openhcs/processing/materialization/core.py b/openhcs/processing/materialization/core.py index e005270deb..7d3b8090e8 100644 --- a/openhcs/processing/materialization/core.py +++ b/openhcs/processing/materialization/core.py @@ -33,7 +33,6 @@ from zmqruntime.viewer_protocol import ViewerWireValue from openhcs.core.source_path_identity import source_path_identity -from openhcs.constants.constants import AllComponents, VariableComponents from openhcs.core.artifacts import ArtifactMaterializationPayload from openhcs.core.component_set import ComponentSet from openhcs.core.components.parser_metaprogramming import FilenameParseResult @@ -104,6 +103,7 @@ TextOptions, TiffStackOptions, ) +from openhcs.core.axes import Axis if TYPE_CHECKING: from polystore.filemanager import FileManager @@ -288,7 +288,7 @@ class Output: path: str content: MaterializationValue metadata: ImagePayloadMetadata | None = None - variable_components: tuple[AllComponents, ...] = () + variable_components: tuple[type[Axis], ...] = () image_numbers_by_axis: Mapping[str, tuple[int, ...]] | None = None def table_shape(self) -> tuple[tuple[str, ...], int] | None: @@ -401,13 +401,13 @@ def with_source_identity_fallback( def with_variable_components( self, - variable_components: Sequence[VariableComponents], + variable_components: Sequence[type[Axis]], ) -> Output: """Carry compiler-resolved runtime plane components to backend saving.""" return replace( self, - variable_components=ComponentSet.coerce(variable_components).as_tuple(), + variable_components=ComponentSet.of(variable_components).as_tuple(), ) @@ -1623,10 +1623,10 @@ def parsed_components_match_metadata( metadata: SourceComponentMetadata, ) -> bool: return all( - component.value in metadata + component.name in metadata and ParserBackedSourceStemAuthority.component_values_match( parsed_value, - metadata[component.value], + metadata[component.name], ) for component, parsed_value in parsed.declared_values() ) @@ -2511,7 +2511,7 @@ class MaterializationContext: context: ProcessingContext | None = None artifact_source_identity: SourceImageIdentity | None = None artifact_filename_identity: SourceImageIdentity | None = None - variable_components: Sequence[VariableComponents] = field(default_factory=tuple) + variable_components: Sequence[type[Axis]] = field(default_factory=tuple) write_mode: WriteMode = WriteMode.OVERWRITE source_paths: tuple[str, ...] = () pipeline_position: int | None = None @@ -3680,10 +3680,10 @@ class ROIMaterializationPlaneMetadataAuthority: @staticmethod def metadata_for_target( target: ROIMaterializationTarget, - variable_components: Sequence[VariableComponents], + variable_components: Sequence[type[Axis]], metadata: ImagePayloadMetadata, ) -> ImagePayloadMetadata: - components = ComponentSet.coerce(variable_components).as_tuple() + components = ComponentSet.of(variable_components).as_tuple() if not components: return metadata if len(target.items) != 1: @@ -4372,7 +4372,7 @@ def shape_text(value: MaterializationValue) -> str: class RuntimePlaneStackAxisMetadataProjection: """Project scalar source identity across variable component runtime planes.""" - variable_components: Sequence[VariableComponents] + variable_components: Sequence[type[Axis]] artifact_source_identity: SourceImageIdentity | None = None def metadata_for_item( @@ -4431,11 +4431,7 @@ def metadata_with_artifact_source_identity( def ordered_axes(self) -> tuple[str, ...]: return VariableComponentAxisProjection( - frozenset( - component.value - for component in self.variable_components - if component.value is not None - ) + frozenset(component.name for component in self.variable_components) ).ordered_axes() @@ -4443,7 +4439,7 @@ def ordered_axes(self) -> tuple[str, ...]: class RuntimePlaneStackAxesProjectionSelection: """Select variable component axes that still need runtime-plane projection.""" - variable_components: Sequence[VariableComponents] + variable_components: Sequence[type[Axis]] items: tuple[MaterializationInputItem, ...] artifact_source_identity: SourceImageIdentity | None = None @@ -4532,7 +4528,7 @@ def indexed_source_plane_axis( runtime_shape = self.runtime_plane_shape() if len(runtime_shape) != 1: return None - source_plane_axis = SourcePlaneIndexedMetadata.projected_component().value + source_plane_axis = SourcePlaneIndexedMetadata.projected_component().name if source_plane_axis not in ordered_axes: return None metadata_values = self.item_component_metadata() @@ -4579,7 +4575,7 @@ class TiffStackSliceMetadataRequest: materialization_input: MaterializationInput slice_count: int - variable_components: Sequence[VariableComponents] = field(default_factory=tuple) + variable_components: Sequence[type[Axis]] = field(default_factory=tuple) artifact_source_identity: SourceImageIdentity | None = None @property @@ -4653,7 +4649,8 @@ def metadata_for_slices( tuple( component for component in request.variable_components - if component.value in selected_variable_components + if component.name in selected_variable_components + ), request.artifact_source_identity, ) @@ -4719,7 +4716,7 @@ def metadata_for_slices( materialization_input: MaterializationInput, slice_count: int, *, - variable_components: Sequence[VariableComponents] = (), + variable_components: Sequence[type[Axis]] = (), artifact_source_identity: SourceImageIdentity | None = None, ) -> tuple[ImagePayloadMetadata, ...]: request = TiffStackSliceMetadataRequest( @@ -5024,7 +5021,7 @@ def materialization_outputs( *, artifact_source_identity: SourceImageIdentity | None = None, artifact_filename_identity: SourceImageIdentity | None = None, - variable_components: Sequence[VariableComponents] = (), + variable_components: Sequence[type[Axis]] = (), source_paths: Sequence[str] = (), pipeline_position: int | None = None, output_plan: ArtifactOutputPlan | None = None, @@ -5071,7 +5068,7 @@ def prepare_materialization( *, artifact_source_identity: SourceImageIdentity | None = None, artifact_filename_identity: SourceImageIdentity | None = None, - variable_components: Sequence[VariableComponents] = (), + variable_components: Sequence[type[Axis]] = (), source_paths: Sequence[str] = (), pipeline_position: int | None = None, output_plan: ArtifactOutputPlan | None = None, @@ -5117,7 +5114,7 @@ def materialize( *, artifact_source_identity: SourceImageIdentity | None = None, artifact_filename_identity: SourceImageIdentity | None = None, - variable_components: Sequence[VariableComponents] = (), + variable_components: Sequence[type[Axis]] = (), source_paths: Sequence[str] = (), pipeline_position: int | None = None, output_plan: ArtifactOutputPlan | None = None, diff --git a/openhcs/processing/presets/README.md b/openhcs/processing/presets/README.md index f72f0e91db..c2d0878379 100644 --- a/openhcs/processing/presets/README.md +++ b/openhcs/processing/presets/README.md @@ -264,9 +264,9 @@ step_2 = FunctionStep( Control which dimensions are collapsed: ```python -variable_components=[VariableComponents.CHANNEL] # Collapse channels → composite -variable_components=[VariableComponents.SITE] # Collapse sites → stitched -variable_components=[VariableComponents.Z_INDEX] # Collapse Z → projection +variable_components=[Microscopy.Channel] # Collapse channels → composite +variable_components=[Microscopy.Site] # Collapse sites → stitched +variable_components=[Microscopy.ZIndex] # Collapse Z → projection ``` ### Per-Channel Processing diff --git a/openhcs/processing/presets/mfd_specs.py b/openhcs/processing/presets/mfd_specs.py index e996c15de1..a1c08273ef 100644 --- a/openhcs/processing/presets/mfd_specs.py +++ b/openhcs/processing/presets/mfd_specs.py @@ -12,7 +12,6 @@ from metaclass_registry import AutoRegisterMeta from arraybridge.decorators import DtypeConversion -from openhcs.constants.constants import VariableComponents from openhcs.constants.input_source import InputSource from openhcs.core.config import LazyDtypeConfig, LazyProcessingConfig from openhcs.core.steps.function_step import FunctionStep @@ -45,6 +44,7 @@ stack_percentile_normalize, tophat, ) +from openhcs.domains.microscopy.axes import Microscopy MFD_WHOLE_DEVICE_TEMPLATE_PATH = Path("templates/mfd_96_sobel_10x_whole_device.tif") MFD_COMPARTMENT_WIDTH = 5046 @@ -259,7 +259,7 @@ def materialize_spec(self, definition: MfdPresetDefinition) -> PresetStepSpec: PresetStepTemplate( binding=PresetStepBinding( name="composite", - variable_components=(VariableComponents.CHANNEL,), + variable_components=(Microscopy.Channel,), ), func_factory_factory=lambda definition: lambda: create_composite, ), @@ -338,7 +338,7 @@ def materialize(self, definition: MfdPresetDefinition) -> list[FunctionStep]: PresetStepSpec( binding=PresetStepBinding( name="crop_device", - variable_components=(VariableComponents.CHANNEL,), + variable_components=(Microscopy.Channel,), ), func_factory=_template_crop_func, ), diff --git a/openhcs/processing/presets/pipelines/cy5_axon_cell_body_crop_analysis.py b/openhcs/processing/presets/pipelines/cy5_axon_cell_body_crop_analysis.py index 170e2510f1..d3f6bd5cf7 100755 --- a/openhcs/processing/presets/pipelines/cy5_axon_cell_body_crop_analysis.py +++ b/openhcs/processing/presets/pipelines/cy5_axon_cell_body_crop_analysis.py @@ -3,7 +3,6 @@ # Automatically collected imports from pathlib import Path -from openhcs.constants.constants import VariableComponents from openhcs.constants.input_source import InputSource from openhcs.core.config import LazyDtypeConfig, LazyStepMaterializationConfig from arraybridge.decorators import DtypeConversion @@ -22,6 +21,7 @@ skan_axon_skeletonize_and_analyze, ) from openhcs.processing.backends.processors.cupy_processor import crop, tophat +from openhcs.domains.microscopy.axes import Microscopy # Pipeline steps pipeline_steps = [] @@ -38,7 +38,7 @@ }, ), name="crop_device", - variable_components=[VariableComponents.CHANNEL], + variable_components=[Microscopy.Channel], ) pipeline_steps.append(step_1) @@ -105,7 +105,7 @@ }, ), name="crop_device", - variable_components=[VariableComponents.CHANNEL], + variable_components=[Microscopy.Channel], input_source=InputSource.PIPELINE_START, ) pipeline_steps.append(step_5) diff --git a/openhcs/processing/presets/pipelines/cy5_ctb_cell_count.py b/openhcs/processing/presets/pipelines/cy5_ctb_cell_count.py index 2effc552b8..a9c3a06152 100755 --- a/openhcs/processing/presets/pipelines/cy5_ctb_cell_count.py +++ b/openhcs/processing/presets/pipelines/cy5_ctb_cell_count.py @@ -1,13 +1,13 @@ # Edit this pipeline and save to apply changes # Automatically collected imports -from openhcs.constants.constants import VariableComponents from openhcs.core.config import LazyNapariStreamingConfig from openhcs.core.steps.function_step import FunctionStep from openhcs.processing.backends.processors.numpy_processor import ( stack_percentile_normalize, ) from openhcs.pyclesperanto import crop, top_hat +from openhcs.domains.microscopy.axes import Microscopy # Pipeline steps pipeline_steps = [] @@ -25,7 +25,7 @@ }, ), name="crop", - variable_components=[VariableComponents.CHANNEL], + variable_components=[Microscopy.Channel], ) pipeline_steps.append(step_1) diff --git a/openhcs/processing/presets/pipelines/czi_brain_axon_cellbody.py b/openhcs/processing/presets/pipelines/czi_brain_axon_cellbody.py index 5c23e04a39..b66ef5d53e 100644 --- a/openhcs/processing/presets/pipelines/czi_brain_axon_cellbody.py +++ b/openhcs/processing/presets/pipelines/czi_brain_axon_cellbody.py @@ -31,7 +31,7 @@ from polystore.filemanager import FileManager from polystore.streaming.identity import StreamProducerIdentity -from openhcs.constants import AllComponents, GroupBy, Microscope, VariableComponents +from openhcs.constants import Microscope from openhcs.constants.input_source import InputSource from openhcs.core.artifacts import ArtifactSpec from openhcs.core.config import ( @@ -70,6 +70,8 @@ ) from openhcs.processing.backends.processors.numpy_processor import tophat from openhcs.processing.presets.demo_contribution import PipelineDemoContribution +from openhcs.core.axes import Ungrouped +from openhcs.domains.microscopy.axes import Microscopy @dataclass(frozen=True, slots=True) @@ -130,19 +132,19 @@ def build_czi_brain_axon_cellbody_demo( NamedSourceBinding( alias="Axon", selector=SourceSelector( - components=(ComponentSelector(AllComponents.CHANNEL, "1"),), + components=(ComponentSelector(Microscopy.Channel, "1"),), ), ), NamedSourceBinding( alias="NeuronalSoma", selector=SourceSelector( - components=(ComponentSelector(AllComponents.CHANNEL, "2"),), + components=(ComponentSelector(Microscopy.Channel, "2"),), ), ), NamedSourceBinding( alias="Nuclei", selector=SourceSelector( - components=(ComponentSelector(AllComponents.CHANNEL, "3"),), + components=(ComponentSelector(Microscopy.Channel, "3"),), ), ), ), @@ -168,8 +170,8 @@ def build_czi_brain_axon_cellbody_demo( }, ), processing_config=LazyProcessingConfig( - variable_components=[VariableComponents.CHANNEL], - group_by=GroupBy.NONE, + variable_components=[Microscopy.Channel], + group_by=Ungrouped, input_source=InputSource.PIPELINE_START, ), ), @@ -194,8 +196,8 @@ def build_czi_brain_axon_cellbody_demo( }, ), processing_config=LazyProcessingConfig( - variable_components=[VariableComponents.CHANNEL], - group_by=GroupBy.NONE, + variable_components=[Microscopy.Channel], + group_by=Ungrouped, input_source=InputSource.PREVIOUS_STEP, ), napari_streaming_config=_analysis_stream( @@ -215,8 +217,8 @@ def build_czi_brain_axon_cellbody_demo( }, ), processing_config=LazyProcessingConfig( - variable_components=[VariableComponents.CHANNEL], - group_by=GroupBy.NONE, + variable_components=[Microscopy.Channel], + group_by=Ungrouped, input_source=InputSource.PIPELINE_START, ), source_bindings=LazyStepSourceBindingsConfig( @@ -243,8 +245,8 @@ def build_czi_brain_axon_cellbody_demo( }, ), processing_config=LazyProcessingConfig( - variable_components=[VariableComponents.CHANNEL], - group_by=GroupBy.NONE, + variable_components=[Microscopy.Channel], + group_by=Ungrouped, input_source=InputSource.PREVIOUS_STEP, ), napari_streaming_config=_analysis_stream( @@ -284,13 +286,13 @@ def _declared_crop_candidates( matches = tuple( candidate for candidate in dataset.candidates - if candidate.component_labels.get(AllComponents.SITE.value) + if candidate.component_labels.get(Microscopy.Site.name) == selection.site_label - and candidate.component_labels.get(AllComponents.CHANNEL.value) + and candidate.component_labels.get(Microscopy.Channel.name) == channel_label and candidate.declared_address is not None - and candidate.declared_address.value_for(AllComponents.Z_INDEX) == "1" - and candidate.declared_address.value_for(AllComponents.TIMEPOINT) == "1" + and candidate.declared_address.value_for(Microscopy.ZIndex) == "1" + and candidate.declared_address.value_for(Microscopy.Timepoint) == "1" ) if len(matches) != 1: raise ValueError( diff --git a/openhcs/processing/presets/pipelines/imx_96_well_neurite_outgrowth_pipeline_cpu.py b/openhcs/processing/presets/pipelines/imx_96_well_neurite_outgrowth_pipeline_cpu.py index 6c3696f63c..d0e0dc4f9a 100644 --- a/openhcs/processing/presets/pipelines/imx_96_well_neurite_outgrowth_pipeline_cpu.py +++ b/openhcs/processing/presets/pipelines/imx_96_well_neurite_outgrowth_pipeline_cpu.py @@ -1,7 +1,6 @@ # Edit this pipeline and save to apply changes # Automatically collected imports -from openhcs.constants.constants import VariableComponents from openhcs.constants.input_source import InputSource from openhcs.core.config import LazyNapariStreamingConfig from openhcs.core.steps.function_step import FunctionStep @@ -20,6 +19,7 @@ from openhcs.processing.backends.processors.torch_processor import ( stack_percentile_normalize as stack_percentile_normalize_torch_processor, ) +from openhcs.domains.microscopy.axes import Microscopy # Pipeline steps pipeline_steps = [] @@ -36,7 +36,7 @@ step_2 = FunctionStep( func=mean_projection, name="z_flatten", - variable_components=[VariableComponents.Z_INDEX], + variable_components=[Microscopy.ZIndex], napari_streaming_config=LazyNapariStreamingConfig(), ) pipeline_steps.append(step_2) @@ -45,7 +45,7 @@ step_3 = FunctionStep( func=create_composite, name="composite", - variable_components=[VariableComponents.CHANNEL], + variable_components=[Microscopy.Channel], napari_streaming_config=LazyNapariStreamingConfig(), ) pipeline_steps.append(step_3) diff --git a/openhcs/processing/presets/pipelines/imx_96_well_neurite_outgrowth_pipeline_gpu.py b/openhcs/processing/presets/pipelines/imx_96_well_neurite_outgrowth_pipeline_gpu.py index 7a03e90dd3..20345c42c2 100755 --- a/openhcs/processing/presets/pipelines/imx_96_well_neurite_outgrowth_pipeline_gpu.py +++ b/openhcs/processing/presets/pipelines/imx_96_well_neurite_outgrowth_pipeline_gpu.py @@ -1,7 +1,6 @@ # Edit this pipeline and save to apply changes # Automatically collected imports -from openhcs.constants.constants import VariableComponents from openhcs.constants.input_source import InputSource from openhcs.core.config import LazyNapariStreamingConfig from openhcs.core.steps.function_step import FunctionStep @@ -20,6 +19,7 @@ from openhcs.processing.backends.processors.torch_processor import ( stack_percentile_normalize as stack_percentile_normalize_torch_processor, ) +from openhcs.domains.microscopy.axes import Microscopy # Pipeline steps pipeline_steps = [] @@ -36,7 +36,7 @@ step_2 = FunctionStep( func=mean_projection, name="z_flatten", - variable_components=[VariableComponents.Z_INDEX], + variable_components=[Microscopy.ZIndex], napari_streaming_config=LazyNapariStreamingConfig(), ) pipeline_steps.append(step_2) @@ -45,7 +45,7 @@ step_3 = FunctionStep( func=create_composite, name="composite", - variable_components=[VariableComponents.CHANNEL], + variable_components=[Microscopy.Channel], napari_streaming_config=LazyNapariStreamingConfig(), ) pipeline_steps.append(step_3) diff --git a/openhcs/processing/presets/pipelines/loose_operaphenix_neurite_outgrowth.py b/openhcs/processing/presets/pipelines/loose_operaphenix_neurite_outgrowth.py index 7aea13ca99..fc2c7d1234 100644 --- a/openhcs/processing/presets/pipelines/loose_operaphenix_neurite_outgrowth.py +++ b/openhcs/processing/presets/pipelines/loose_operaphenix_neurite_outgrowth.py @@ -23,7 +23,7 @@ from polystore.streaming.identity import StreamProducerIdentity -from openhcs.constants.constants import AllComponents, Microscope +from openhcs.constants.constants import Microscope from openhcs.constants.input_source import InputSource from openhcs.core.aligned_image_payload import AlignedImageSliceContext from openhcs.core.artifacts import ImageArtifactType, ObjectLabelsArtifactType @@ -74,6 +74,7 @@ threshold, ) from openhcs.processing.presets.demo_contribution import PipelineDemoContribution +from openhcs.domains.microscopy.axes import Microscopy NEURITE_BRANCHPOINT_IMAGE_NAME = "NeuriteBranchpoints" @@ -141,11 +142,11 @@ def _exact_image_binding( ), ), component_identity=( - ComponentSelector(AllComponents.WELL, inputs.well), - ComponentSelector(AllComponents.SITE, inputs.site), - ComponentSelector(AllComponents.CHANNEL, source.channel), - ComponentSelector(AllComponents.Z_INDEX, inputs.z_index), - ComponentSelector(AllComponents.TIMEPOINT, inputs.timepoint), + ComponentSelector(Microscopy.Well, inputs.well), + ComponentSelector(Microscopy.Site, inputs.site), + ComponentSelector(Microscopy.Channel, source.channel), + ComponentSelector(Microscopy.ZIndex, inputs.z_index), + ComponentSelector(Microscopy.Timepoint, inputs.timepoint), ), ) diff --git a/openhcs/processing/presets/pipelines/loose_operaphenix_neurite_outgrowth_metaxpress.py b/openhcs/processing/presets/pipelines/loose_operaphenix_neurite_outgrowth_metaxpress.py index f73f534ad6..3d97bf72ec 100644 --- a/openhcs/processing/presets/pipelines/loose_operaphenix_neurite_outgrowth_metaxpress.py +++ b/openhcs/processing/presets/pipelines/loose_operaphenix_neurite_outgrowth_metaxpress.py @@ -13,7 +13,6 @@ from pathlib import Path -from openhcs.constants.constants import GroupBy, VariableComponents from openhcs.constants.input_source import InputSource from openhcs.core.config import ( LazyNapariStreamingConfig, @@ -34,6 +33,8 @@ SemanticImageSource, build_loose_operaphenix_neurite_config, ) +from openhcs.core.axes import Ungrouped +from openhcs.domains.microscopy.axes import Microscopy def build_loose_operaphenix_neurite_metaxpress_pipeline( @@ -73,8 +74,8 @@ def build_loose_operaphenix_neurite_metaxpress_pipeline( }, ), processing_config=LazyProcessingConfig( - variable_components=[VariableComponents.CHANNEL], - group_by=GroupBy.NONE, + variable_components=[Microscopy.Channel], + group_by=Ungrouped, input_source=InputSource.PIPELINE_START, ), napari_streaming_config=LazyNapariStreamingConfig( diff --git a/openhcs/processing/presets/pipelines/neuroncyto_ii_crossover_neurite_outgrowth.py b/openhcs/processing/presets/pipelines/neuroncyto_ii_crossover_neurite_outgrowth.py index 9fa78f5bfb..e9dc019d19 100644 --- a/openhcs/processing/presets/pipelines/neuroncyto_ii_crossover_neurite_outgrowth.py +++ b/openhcs/processing/presets/pipelines/neuroncyto_ii_crossover_neurite_outgrowth.py @@ -26,7 +26,7 @@ from polystore.streaming.identity import StreamProducerIdentity -from openhcs.constants import AllComponents, GroupBy, Microscope, VariableComponents +from openhcs.constants import Microscope from openhcs.constants.input_source import InputSource from openhcs.core.aligned_image_payload import AlignedImageSliceContext from openhcs.core.config import ( @@ -59,6 +59,8 @@ percentile_normalize_plane, ) from openhcs.processing.presets.demo_contribution import PipelineDemoContribution +from openhcs.core.axes import Ungrouped +from openhcs.domains.microscopy.axes import Microscopy @dataclass(frozen=True, slots=True) @@ -94,11 +96,11 @@ def _exact_source_binding( ), ), component_identity=( - ComponentSelector(AllComponents.WELL, inputs.image_id), - ComponentSelector(AllComponents.SITE, "1"), - ComponentSelector(AllComponents.CHANNEL, channel), - ComponentSelector(AllComponents.Z_INDEX, "1"), - ComponentSelector(AllComponents.TIMEPOINT, "1"), + ComponentSelector(Microscopy.Well, inputs.image_id), + ComponentSelector(Microscopy.Site, "1"), + ComponentSelector(Microscopy.Channel, channel), + ComponentSelector(Microscopy.ZIndex, "1"), + ComponentSelector(Microscopy.Timepoint, "1"), ), ) @@ -164,8 +166,8 @@ def build_neuroncyto_ii_crossover_demo( }, ), processing_config=LazyProcessingConfig( - variable_components=[VariableComponents.CHANNEL], - group_by=GroupBy.NONE, + variable_components=[Microscopy.Channel], + group_by=Ungrouped, input_source=InputSource.PIPELINE_START, ), napari_streaming_config=LazyNapariStreamingConfig( @@ -263,8 +265,8 @@ def prepare() -> None: }, ), processing_config=LazyProcessingConfig( - variable_components=[VariableComponents.CHANNEL], - group_by=GroupBy.NONE, + variable_components=[Microscopy.Channel], + group_by=Ungrouped, input_source=InputSource.PIPELINE_START, ), napari_streaming_config=LazyNapariStreamingConfig( @@ -279,8 +281,8 @@ def prepare() -> None: name=compact_step.name, func=compact_step.func, processing_config=LazyProcessingConfig( - variable_components=[VariableComponents.CHANNEL], - group_by=GroupBy.NONE, + variable_components=[Microscopy.Channel], + group_by=Ungrouped, input_source=InputSource.PREVIOUS_STEP, ), napari_streaming_config=compact_step.napari_streaming_config, diff --git a/openhcs/pyqt_gui/services/reactor_providers.py b/openhcs/pyqt_gui/services/reactor_providers.py index 1cbc75ff3b..1759a2b70c 100644 --- a/openhcs/pyqt_gui/services/reactor_providers.py +++ b/openhcs/pyqt_gui/services/reactor_providers.py @@ -195,10 +195,24 @@ def scan_for_server_logs(self) -> list[LogFileInfo]: class OpenHCSComponentSelectionProvider(ComponentSelectionProviderABC): """Component selection provider backed by OpenHCS orchestrator metadata.""" - def get_groupby_enum(self) -> Any: - from openhcs.constants.constants import GroupBy + def is_grouped(self, group_by: Any) -> bool: + return bool(group_by.grouping_axes()) - return GroupBy + def grouping_label(self, group_by: Any) -> str: + return group_by.name.replace("_", " ").title() + + def grouping_overlaps_variable_components( + self, + group_by: Any, + variable_components: Iterable[Any], + ) -> bool: + variable = tuple(variable_components) + return any(axis in variable for axis in group_by.grouping_axes()) + + @staticmethod + def _grouping_axis(group_by: Any): + (axis,) = group_by.grouping_axes() + return axis def _get_plate_manager(self): from pyqt_reactive.services.service_registry import ServiceRegistry @@ -229,7 +243,7 @@ def has_components_available(self, group_by: Any) -> bool: orchestrator = self._get_current_orchestrator() if orchestrator is None: return False - return bool(orchestrator.get_component_keys(group_by)) + return bool(orchestrator.get_component_keys(self._grouping_axis(group_by))) def get_component_keys(self, group_by: Any) -> list[str]: orchestrator = self._get_current_orchestrator() @@ -237,7 +251,7 @@ def get_component_keys(self, group_by: Any) -> list[str]: raise RuntimeError( "Component selection requires an initialized plate orchestrator." ) - return orchestrator.get_component_keys(group_by) + return orchestrator.get_component_keys(self._grouping_axis(group_by)) def get_component_display_name( self, group_by: Any, component_key: str @@ -246,7 +260,7 @@ def get_component_display_name( if orchestrator is None: return None return orchestrator.metadata_cache.get_component_metadata( - group_by, component_key + self._grouping_axis(group_by), component_key ) def select_components( @@ -263,7 +277,9 @@ def select_components( available_components=list(available_components), selected_components=list(selected_components), group_by=group_by, + group_label=self.grouping_label(group_by), metadata_lookup=self.get_component_display_name, + parent=parent, ) diff --git a/openhcs/pyqt_gui/widgets/artifact_plan_view.py b/openhcs/pyqt_gui/widgets/artifact_plan_view.py index 783c1da073..8c61ce7b5a 100644 --- a/openhcs/pyqt_gui/widgets/artifact_plan_view.py +++ b/openhcs/pyqt_gui/widgets/artifact_plan_view.py @@ -70,7 +70,7 @@ def group_scope_text(self) -> str: if self.plan is None: return "" scope = self.plan.group_scope() - component = "" if scope.component is None else scope.component.value + component = "" if scope.component is None else scope.component.name keys = ", ".join("default" if key is None else key for key in scope.keys) return keys if not component else f"{component}: {keys}" diff --git a/openhcs/pyqt_gui/widgets/image_browser.py b/openhcs/pyqt_gui/widgets/image_browser.py index 81b4b7d4f6..784828db5c 100644 --- a/openhcs/pyqt_gui/widgets/image_browser.py +++ b/openhcs/pyqt_gui/widgets/image_browser.py @@ -36,7 +36,7 @@ ImageTableValue, ) -from openhcs.constants.constants import AllComponents, FileFormat +from openhcs.constants.constants import FileFormat from openhcs.core.config import StreamingConfig from openhcs.core.plate_image_inventory import ( PlateFileInventory, @@ -48,12 +48,11 @@ from openhcs.pyqt_gui.services.ui_window_ids import OpenHCSUiWindowId from openhcs.runtime.zmq_config import OPENHCS_ZMQ_CONFIG, OpenHCSZMQConfig from openhcs.ui.shared.plate_scope_identity import SCOPE_SEGMENT_SEPARATOR +from openhcs.core.axes import AxisFamily logger = logging.getLogger(__name__) -ALL_COMPONENT_VALUES = frozenset(component.value for component in AllComponents) - def _streaming_config_field_names() -> tuple[str, ...]: """Registered streaming-config field names used by image-browser controls.""" @@ -279,9 +278,10 @@ def _resolve_display_value(self, metadata_key: str, value_str: str) -> str: return value_str try: - if metadata_key not in ALL_COMPONENT_VALUES: + family = AxisFamily.active() + if metadata_key not in family.names(): return value_str - component = AllComponents(metadata_key) + component = family.named(metadata_key) metadata_name = orchestrator.metadata_cache.get_component_metadata( component, value_str, @@ -1449,7 +1449,7 @@ def _on_detached_window_closed(self, event): def _on_wells_selected(self, well_ids: Set[str]): """Handle well selection from plate view.""" logger.info(f"[WELLS_SELECTED] Received {len(well_ids)} wells: {well_ids}") - well_key = AllComponents.WELL.value + well_key = AxisFamily.active().partition_axis().name self._syncing_plate_filter_selection = True try: synced = self.image_table_browser.set_column_filter_selection( @@ -1471,7 +1471,8 @@ def _on_table_filter_selection_changed( selected_values: frozenset[str], ) -> None: """Compose the generic Well filter selection into the plate view.""" - well_key = AllComponents.WELL.value + well_key = AxisFamily.active().partition_axis().name + if ( self._syncing_plate_filter_selection or column_key != well_key @@ -1599,7 +1600,7 @@ def _extract_well_id(self, metadata: dict) -> str: Raises KeyError if metadata missing 'well' component. """ # Well ID is a single component in metadata - return str(metadata["well"]) + return str(metadata[AxisFamily.active().partition_axis().name]) def _detect_plate_dimensions(self, well_ids: Set[str]) -> tuple[int, int]: """ diff --git a/openhcs/pyqt_gui/widgets/pipeline_editor.py b/openhcs/pyqt_gui/widgets/pipeline_editor.py index c028b92f24..ce93132e22 100644 --- a/openhcs/pyqt_gui/widgets/pipeline_editor.py +++ b/openhcs/pyqt_gui/widgets/pipeline_editor.py @@ -65,7 +65,7 @@ PipelineEditorStateSurfaceIdentityDeclaration, PipelineEditorWidgetIdentity, ) -from openhcs.constants.constants import GroupBy, OrchestratorState, VariableComponents +from openhcs.constants.constants import OrchestratorState from openhcs.constants.input_source import InputSource from openhcs.core.config import ( GlobalPipelineConfig, @@ -125,6 +125,7 @@ from openhcs.ui.shared.plate_scope_identity import ( PipelineScopeIdentity, ) +from openhcs.core.axes import Axis, GroupingDeclaration logger = logging.getLogger(__name__) @@ -312,15 +313,15 @@ def lines(self, processing_config: ProcessingConfig) -> list[str]: def variable_components_line( self, - variable_components: list[VariableComponents], + variable_components: list[type[Axis]], ) -> str: if not variable_components: return "Variable Components: None" comp_names = [component.name for component in variable_components] return f"Variable Components: [{', '.join(comp_names)}]" - def group_by_line(self, group_by: GroupBy) -> str: - if not group_by or group_by.value is None: + def group_by_line(self, group_by: type[GroupingDeclaration] | None) -> str: + if group_by is None or not group_by.grouping_axes(): return "Group By: None" return f"Group By: {group_by.name}" diff --git a/openhcs/pyqt_gui/widgets/shared/services/pipeline_editor_workflows.py b/openhcs/pyqt_gui/widgets/shared/services/pipeline_editor_workflows.py index 24b96ee237..ac3f18a1f4 100644 --- a/openhcs/pyqt_gui/widgets/shared/services/pipeline_editor_workflows.py +++ b/openhcs/pyqt_gui/widgets/shared/services/pipeline_editor_workflows.py @@ -116,17 +116,18 @@ def format_func_preview( orchestrator = self.editor._get_current_orchestrator() metadata_cache = orchestrator.metadata_cache if orchestrator else None step = state.to_object(update_delegate=False) if state else None - group_by = ( - step.processing_config.group_by + grouping_axes = ( + step.processing_config.group_by.grouping_axes() if isinstance(step, AbstractStep) - else None + and step.processing_config.group_by is not None + else () ) entries = [] for key in sorted(func.keys()): display_name = None - if group_by and metadata_cache: + if grouping_axes and metadata_cache: display_name = metadata_cache.get_component_metadata( - group_by, str(key) + grouping_axes[0], str(key) ) if display_name is None: display_name = str(key) diff --git a/openhcs/pyqt_gui/widgets/source_bindings_editor.py b/openhcs/pyqt_gui/widgets/source_bindings_editor.py index b451dd9258..e5ae749afd 100644 --- a/openhcs/pyqt_gui/widgets/source_bindings_editor.py +++ b/openhcs/pyqt_gui/widgets/source_bindings_editor.py @@ -86,7 +86,13 @@ InlineDataclassGroupBox, ) from pyqt_reactive.widgets.no_scroll_spinbox import NoScrollComboBox, NoneAwareCheckBox -from python_introspect import Enableable, SignatureAnalyzer, is_enableable +from python_introspect import ( + AnnotationChoices, + Enableable, + SignatureAnalyzer, + declared_annotation_choices, + is_enableable, +) from openhcs.core.field_label import FieldLabel from openhcs.core.source_bindings import ( @@ -343,18 +349,27 @@ def raw(self, table, row, column) -> bool: class ChoiceCellEditor(CellEditor): """Combo box whose choices are the field type's members. - An ``Enum`` type supplies its members; ``type[F]`` for an ``AutoRegisterMeta`` - family supplies the family registry, labelled by each member's registry key. + Declared ``AnnotationChoices`` supply their choices and labels; an ``Enum`` + type supplies its members; ``type[F]`` for an ``AutoRegisterMeta`` family + supplies the family registry, labelled by each member's registry key. """ COMBO_LOGICAL_TEXT_ROLE = Qt.ItemDataRole.UserRole + 1 @classmethod def accepts(cls, annotation: object) -> bool: - return cls.family(annotation) is not None or ( - isinstance(annotation, type) and issubclass(annotation, Enum) + return ( + cls.declared_choices(annotation) is not None + or cls.family(annotation) is not None + or (isinstance(annotation, type) and issubclass(annotation, Enum)) ) + @staticmethod + def declared_choices(annotation: object) -> AnnotationChoices | None: + if get_origin(annotation) is not Annotated: + return None + return declared_annotation_choices(annotation) + @staticmethod def family(annotation: object) -> type | None: if get_origin(annotation) is not type: @@ -364,6 +379,9 @@ def family(annotation: object) -> type | None: @property def choices(self) -> tuple[object, ...]: + declared = self.declared_choices(self.annotation) + if declared is not None: + return declared.choices() family = self.family(self.annotation) if family is not None: return tuple(family.__registry__.values()) @@ -379,6 +397,9 @@ def value_from_raw(self, raw: object) -> object: return raw def display(self, value: object) -> str: + declared = self.declared_choices(self.annotation) + if declared is not None: + return declared.label(value) family = self.family(self.annotation) if family is not None: return str(getattr(value, family.__registry_key__)) @@ -556,7 +577,12 @@ def _collect( if isinstance(annotation, type) and is_dataclass(annotation): cls._collect(annotation, path, columns) continue - editor = CellEditor.for_annotation(annotation) + editor = CellEditor.for_annotation( + hints[row_field.name] + if any(isinstance(item, AnnotationChoices) for item in metadata) + else annotation + ) + if editor is None: continue columns.append( diff --git a/openhcs/runtime/napari_streaming_handlers.py b/openhcs/runtime/napari_streaming_handlers.py index 3c0d1514d2..6be3577fc9 100644 --- a/openhcs/runtime/napari_streaming_handlers.py +++ b/openhcs/runtime/napari_streaming_handlers.py @@ -20,7 +20,7 @@ from polystore.streaming_constants import StreamingDataType from zmqruntime.viewer_protocol import ViewerComponentMode, ViewerWireField -from openhcs.constants import AllComponents +from openhcs.core.axes import AxisFamily, StackAxis from openhcs.core.artifacts import ObjectArtifactSubjectBinding from openhcs.core.config import NapariDisplayConfig from openhcs.core.roi_source_metadata import ROIArchiveSourceMetadata, ROIPlaneMetadata @@ -1422,7 +1422,12 @@ def spatial_axis_labels(self) -> tuple[str, ...]: """Spatial review axes, excluding acquisition selectors and payload bands.""" return tuple( axis - for axis in (AllComponents.Z_INDEX.value, "y", "x") + for axis in ( + *(stack.name for stack in AxisFamily.active().with_role(StackAxis)), + "y", + "x", + ) + if axis in self.axis_labels ) diff --git a/openhcs/runtime/napari_viewer_server.py b/openhcs/runtime/napari_viewer_server.py index c97a05ea34..e75033bcc9 100644 --- a/openhcs/runtime/napari_viewer_server.py +++ b/openhcs/runtime/napari_viewer_server.py @@ -73,7 +73,7 @@ ViewerSourceSpatialDomainPayload, ) -from openhcs.constants import AllComponents +from openhcs.core.axes import AxisFamily, StackAxis from openhcs.agent.dto.viewer import ( ViewerWindowDescriptor, ViewerWindowLayerRetirementRequest, ) @@ -1021,7 +1021,7 @@ def routing_context( if context.address.stream_layer_data_type is not StreamingDataType.IMAGE: return context - well_component = AllComponents.WELL.value + well_component = AxisFamily.active().partition_axis().name ViewerComponentCoordinateAuthority.required_value( context.address.components, well_component, @@ -1303,11 +1303,11 @@ def _build_nd_points( if fractional_z is not None: try: z_axis_index = axis_projection.projected_axis_components.index( - AllComponents.Z_INDEX.value + AxisFamily.active().one(StackAxis).name ) - except ValueError as exc: + except (ValueError, LookupError) as exc: raise ValueError( - "Fractional-Z point ROI requires a projected z_index axis." + "Fractional-Z point ROI requires a projected stack axis." ) from exc for coordinate_index, coord in enumerate(coordinates): @@ -2364,7 +2364,6 @@ def geometric_component_values( component_axis_semantics: ViewerComponentAxisSemantics, ) -> ComponentValues: """Keep the represented source span, not just occupied point Z, navigable.""" - z_component = AllComponents.Z_INDEX.value coordinates = tuple( (item, fractional_z) for item in items @@ -2375,12 +2374,15 @@ def geometric_component_values( ) if not coordinates: return {} + stack_axes = AxisFamily.active().with_role(StackAxis) + z_component = stack_axes[0].name if stack_axes else None if z_component not in component_axis_semantics.layout.components_for_mode( ViewerComponentMode.STACK ): raise ValueError( - "Fractional-Z point ROI requires a projected z_index axis." + "Fractional-Z point ROI requires a projected stack axis." ) + domain = component_axis_semantics.required_component_values((z_component,))[ z_component ] diff --git a/openhcs/runtime/viewer_component_system.py b/openhcs/runtime/viewer_component_system.py index 88248891f6..8e070ac986 100644 --- a/openhcs/runtime/viewer_component_system.py +++ b/openhcs/runtime/viewer_component_system.py @@ -3,7 +3,7 @@ from __future__ import annotations from abc import ABC, abstractmethod -from collections.abc import Callable, Mapping, Sequence +from collections.abc import Mapping, Sequence from dataclasses import dataclass, field from enum import Enum from itertools import product @@ -23,12 +23,19 @@ ViewerDisplayConfigWireField, ViewerWireMapping, ViewerWireValue, - viewer_component_mode_value, ) from polystore.streaming.viewer_transport import ViewerDisplayConfigABC -from openhcs.constants.constants import AllComponents from openhcs.runtime.viewer_protocol import ViewerComponentValueOrdering +from openhcs.core.axes import ( + AxisFamily, + AxisRoleKeyedStrategyMixin, + ColourAxis, + OrdinalValued, + PartitionAxis, + StackAxis, + TimeAxis, +) ComponentValue: TypeAlias = str | int | float | bool | tuple | None ComponentWireValue: TypeAlias = ComponentValue | Sequence[ComponentValue] @@ -87,10 +94,70 @@ def __new__(mcs, name: str, bases: tuple[type, ...], attrs: dict): return super().__new__(mcs, name, bases, attrs) -class ViewerComponentSemanticRole(Enum): - """Semantic roles that viewer backends may request from component axes.""" +class ViewerAxisLabelStrategy(AxisRoleKeyedStrategyMixin): + """Viewer label spelling owned by one axis role. + + Axes whose roles declare no leaf use their boundary name. + """ + + abbreviation: ClassVar[str | None] = None + + @classmethod + def for_component(cls, component: str) -> type["ViewerAxisLabelStrategy"]: + family = AxisFamily.active() + if component not in family.names(): + return cls + axis = family.named(component) + matches = tuple( + strategy + for strategy in cls.role_strategy_types() + if issubclass(axis, strategy.implements_role) + ) + if len(matches) > 1: + raise LookupError( + f"Axis {axis!r} has several viewer label roles: " + f"{[strategy.__qualname__ for strategy in matches]}." + ) + return matches[0] if matches else cls + + @classmethod + def abbreviate(cls, component: str) -> str: + if cls.abbreviation is not None: + return cls.abbreviation + if component in AxisFamily.active().names(): + return component.title() + return component + + @classmethod + def named_label(cls, component: str, value: ComponentValue, name: str) -> str: + return f"{component.title()} {value}: {name}" + + +class ColourAxisViewerLabel(ViewerAxisLabelStrategy): + implements_role = ColourAxis + abbreviation = "Ch" + + @classmethod + def named_label(cls, component: str, value: ComponentValue, name: str) -> str: + return f"{cls.abbreviation}{value}: {name}" + - COLOR = "color" +class StackAxisViewerLabel(ViewerAxisLabelStrategy): + implements_role = StackAxis + abbreviation = "Z" + + +class TimeAxisViewerLabel(ViewerAxisLabelStrategy): + implements_role = TimeAxis + abbreviation = "T" + + +class PartitionAxisViewerLabel(ViewerAxisLabelStrategy): + implements_role = PartitionAxis + + @classmethod + def named_label(cls, component: str, value: ComponentValue, name: str) -> str: + return str(name) class ViewerStreamingDataTypeHandler( @@ -314,8 +381,10 @@ def normalize(self, components: ComponentMap) -> ComponentMap: } def normalize_value(self, component: str, value: ComponentValue) -> ComponentValue: - component_identity = AllComponents.from_value(component) - if component_identity is None or not component_identity.is_variable_axis(): + family = AxisFamily.active() + if component not in family.names() or not issubclass( + family.named(component), OrdinalValued + ): return value if isinstance(value, str): stripped = value.strip() @@ -758,20 +827,6 @@ def __contains__(self, component: str) -> bool: class ViewerComponentNameMetadata(ComponentMetadataPresentationABC[ComponentValue]): """Component-value display names shared by viewer receivers.""" - ABBREVIATIONS: ClassVar[Mapping[str, str]] = { - AllComponents.CHANNEL.value: "Ch", - AllComponents.Z_INDEX.value: "Z", - AllComponents.TIMEPOINT.value: "T", - AllComponents.SITE.value: "Site", - AllComponents.WELL.value: "Well", - } - METADATA_FORMATTERS: ClassVar[ - Mapping[str, Callable[[ComponentValue, ComponentValue], str]] - ] = { - AllComponents.CHANNEL.value: lambda value, name: f"Ch{value}: {name}", - AllComponents.WELL.value: lambda _value, name: str(name), - } - store: ViewerComponentNameMetadataStore = field( default_factory=ViewerComponentNameMetadataStore ) @@ -813,15 +868,12 @@ def display_name(self, component: str, value: ComponentValue) -> str | None: return str(name) def abbreviation(self, component: str) -> str: - if component in self.ABBREVIATIONS: - return self.ABBREVIATIONS[component] - return component + return ViewerAxisLabelStrategy.for_component(component).abbreviate(component) def named_axis_label(self, component: str, value: ComponentValue, name: str) -> str: - formatter = self.METADATA_FORMATTERS.get(component) - if formatter is not None: - return formatter(value, name) - return f"{component.title()} {value}: {name}" + return ViewerAxisLabelStrategy.for_component(component).named_label( + component, value, name + ) def compact_tuple_labels( self, @@ -908,31 +960,6 @@ def component_order(self) -> tuple[str, ...]: def component_modes(self) -> ComponentModeMap: return self.layout.component_modes - def role_component_for_mode( - self, - *, - role: ViewerComponentSemanticRole, - mode: DisplayModeValue, - ) -> str | None: - mode_value = viewer_component_mode_value(mode) - for component in self.layout.component_order: - if self.layout.component_modes[component] != mode_value: - continue - component_identity = AllComponents.from_value(component) - if component_identity is not None and self.component_has_role( - component_identity, role - ): - return component - return None - - @staticmethod - def component_has_role( - component: AllComponents, - role: ViewerComponentSemanticRole, - ) -> bool: - if role is ViewerComponentSemanticRole.COLOR: - return component.is_default_group_by_axis() - raise ValueError(f"No component role mapping for {role!r}.") class ViewerComponentAxisSemanticsAuthority: diff --git a/openhcs/runtime/zmq_execution_server.py b/openhcs/runtime/zmq_execution_server.py index a1229f37a5..c895fe93a3 100644 --- a/openhcs/runtime/zmq_execution_server.py +++ b/openhcs/runtime/zmq_execution_server.py @@ -738,14 +738,18 @@ def _wells_for_execution( *, execution_bundle: CompiledExecutionBundle | None = None, ) -> list[str]: - from openhcs.constants import MULTIPROCESSING_AXIS + from openhcs.core.axes import AxisFamily if axis_filter is not None: return list(axis_filter) available_axis_ids = ( execution_bundle.axis_ids if execution_bundle is not None - else tuple(orchestrator.get_component_keys(MULTIPROCESSING_AXIS)) + else tuple( + orchestrator.get_component_keys( + AxisFamily.active().partition_axis() + ) + ) ) return debug_execution_policy.axis_filter_for_available(available_axis_ids) diff --git a/openhcs/serialization/pycodify_formatters.py b/openhcs/serialization/pycodify_formatters.py index 969b132fc6..e9a9d51d1f 100644 --- a/openhcs/serialization/pycodify_formatters.py +++ b/openhcs/serialization/pycodify_formatters.py @@ -13,6 +13,7 @@ from pyqt_reactive.pattern_metadata import PatternScopeToken from python_introspect import callable_declaration_kwargs, parameter_exclusions +from openhcs.core.axes import is_grouping_declaration from openhcs.core.callable_contract import CallableContract, CallableImportIdentity from openhcs.core.function_reference import ( FunctionReference, @@ -66,6 +67,22 @@ def reference_for(self, value) -> FunctionReference: ) +class AxisDeclarationFormatter(SourceFormatter): + """Axes and grouping declarations are spelled by their qualified class path.""" + + priority = 77 + + def can_format(self, value) -> bool: + return is_grouping_declaration(value) + + def format(self, value, context: FormatContext) -> SourceFragment: + root_name, _, nested_path = value.__qualname__.partition(".") + import_pair = (value.__module__, root_name) + mapped_root = NameMappingLookup.resolve(context, import_pair, root_name) + reference = f"{mapped_root}.{nested_path}" if nested_path else mapped_root + return SourceFragment(reference, frozenset([import_pair])) + + class PythonSourceLiteralFormatter(SourceFormatter): priority = 120 @@ -180,6 +197,8 @@ def format(self, value, context: FormatContext) -> SourceFragment: def _public_pattern_callable(value: object) -> Callable | None: if isinstance(value, FunctionReference): return value.resolve() + if is_grouping_declaration(value): + return None return value if callable(value) else None diff --git a/pyproject.toml b/pyproject.toml index 1fcddf5fdd..d2624c71d9 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -102,11 +102,11 @@ dependencies = [ "zmqruntime>=0.4.1,<0.5", "pycodify>=0.1.3,<0.2", "objectstate>=1.3.1,<2", - "python-introspect>=0.2.2,<0.3", + "python-introspect>=0.2.3,<0.3", "metaclass-registry>=0.3.0,<0.4", "arraybridge>=0.3.8,<0.4", "polystore>=0.3.3,<0.4", - "pyqt-reactive>=0.3.27,<0.4", + "pyqt-reactive>=0.3.28,<0.4", ] [project.optional-dependencies] diff --git a/scripts/check_basicpy_source.py b/scripts/check_basicpy_source.py index 24634cdce9..dd3a353743 100644 --- a/scripts/check_basicpy_source.py +++ b/scripts/check_basicpy_source.py @@ -96,9 +96,9 @@ def test_existing_contracts_own_pipeline_axis_admission(self): "jax_func(contract=ProcessingContract.PURE_3D, dtype_config_default=DtypeConfig())", decorators, ) - self.assertIn("allowed_group_by(GroupBy.CHANNEL)", decorators) + self.assertIn("allowed_group_by_roles(ColourAxis)", decorators) self.assertIn( - "required_variable_components(FittedIlluminationFieldOutput.observation_axis)", + "required_axis_roles(FittedIlluminationFieldOutput.observation_role)", decorators, ) self.assertFalse( diff --git a/scripts/mcp_assay_showcase.py b/scripts/mcp_assay_showcase.py index a4d07e607d..449b73e341 100644 --- a/scripts/mcp_assay_showcase.py +++ b/scripts/mcp_assay_showcase.py @@ -503,7 +503,7 @@ def _z_stack_processing_config_source() -> str: return """ processing_config=LazyProcessingConfig( input_source=InputSource.PIPELINE_START, - variable_components=[VariableComponents.Z_INDEX], + variable_components=[Microscopy.ZIndex], ), """ @@ -538,7 +538,7 @@ def _primary_object_source(plate_path: Path, output_path: Path) -> str: plate_path, output_path, processing_imports=( - "from openhcs.constants.constants import VariableComponents" + "from openhcs.domains.microscopy.axes import Microscopy" ), extra_imports=( """from openhcs.processing.backends.analysis.cell_counting_cpu import ( @@ -564,7 +564,8 @@ def _dual_channel_source(plate_path: Path, output_path: Path) -> str: plate_path, output_path, processing_imports=( - "from openhcs.constants.constants import GroupBy, VariableComponents" + "from openhcs.core.axes import Ungrouped\n" + "from openhcs.domains.microscopy.axes import Microscopy" ), extra_imports=( """from openhcs.processing.backends.analysis.count_cells_simple import ( @@ -600,8 +601,8 @@ def _dual_channel_source(plate_path: Path, output_path: Path) -> str: }, ), processing_config=LazyProcessingConfig( - variable_components=[VariableComponents.CHANNEL], - group_by=GroupBy.NONE, + variable_components=[Microscopy.Channel], + group_by=Ungrouped, input_source=InputSource.PIPELINE_START, ), """ @@ -618,7 +619,8 @@ def _colocalization_source(plate_path: Path, output_path: Path) -> str: plate_path, output_path, processing_imports=( - "from openhcs.constants.constants import GroupBy, VariableComponents" + "from openhcs.core.axes import Ungrouped\n" + "from openhcs.domains.microscopy.axes import Microscopy" ), extra_imports=( """from openhcs.processing.backends.cellprofiler.colocalization import ( @@ -652,8 +654,8 @@ def _colocalization_source(plate_path: Path, output_path: Path) -> str: }, ), processing_config=LazyProcessingConfig( - variable_components=[VariableComponents.CHANNEL], - group_by=GroupBy.NONE, + variable_components=[Microscopy.Channel], + group_by=Ungrouped, input_source=InputSource.PIPELINE_START, ), ), @@ -666,8 +668,8 @@ def _colocalization_source(plate_path: Path, output_path: Path) -> str: }, ), processing_config=LazyProcessingConfig( - variable_components=[VariableComponents.CHANNEL], - group_by=GroupBy.NONE, + variable_components=[Microscopy.Channel], + group_by=Ungrouped, input_source=InputSource.PIPELINE_START, ), """ diff --git a/scripts/mcp_thesis_demo_live.py b/scripts/mcp_thesis_demo_live.py index 911544980a..bfe7e635eb 100755 --- a/scripts/mcp_thesis_demo_live.py +++ b/scripts/mcp_thesis_demo_live.py @@ -73,7 +73,6 @@ PlateManagerStateSurfaceIdentityDeclaration, PlateManagerWidgetIdentity, ) -from openhcs.constants.constants import AllComponents from openhcs.core.config_cache import ConfigCacheSpec, save_config_sync from openhcs.mcp.dev_client import McpDevClient from openhcs.mcp.dev_client_core import ( @@ -97,6 +96,7 @@ ViewerTransportEndpoint, ) from openhcs.runtime.zmq_config import OPENHCS_ZMQ_CONFIG, OpenHCSZMQConfig +from openhcs.domains.microscopy.axes import Microscopy ROOT = Path(__file__).resolve().parents[1] DEFAULT_DEMO_ROOT = ROOT / "mcp_outputs" / "thesis_demo" / "live" @@ -188,7 +188,7 @@ ( "napari_streaming_config.enabled", "napari_streaming_config.port", - "napari_streaming_config.site_mode", + "napari_streaming_config.tile_mode", ), ), ( @@ -197,7 +197,7 @@ ( "fiji_streaming_config.enabled", "fiji_streaming_config.port", - "fiji_streaming_config.site_mode", + "fiji_streaming_config.tile_mode", ), ), ( @@ -239,7 +239,7 @@ ( "napari_streaming_config.enabled", "napari_streaming_config.port", - "napari_streaming_config.site_mode", + "napari_streaming_config.tile_mode", ), ), ( @@ -248,7 +248,7 @@ ( "fiji_streaming_config.enabled", "fiji_streaming_config.port", - "fiji_streaming_config.site_mode", + "fiji_streaming_config.tile_mode", ), ), ) @@ -1214,12 +1214,8 @@ def demo_source( from pathlib import Path from arraybridge.decorators import DtypeConversion -from openhcs.constants.constants import ( - AllComponents, - GroupBy, - VariableComponents, -) from openhcs.constants.input_source import InputSource +from openhcs.core.axes import Ungrouped from openhcs.core.config import ( GlobalPipelineConfig, LazyDtypeConfig, @@ -1238,6 +1234,7 @@ def demo_source( SourceSelector, ) from openhcs.core.steps.function_step import FunctionStep +from openhcs.domains.microscopy.axes import Microscopy from openhcs.processing.backends.analysis.cell_counting_cpu import ( DetectionMethod, count_cells_single_channel, @@ -1274,14 +1271,14 @@ def demo_source( selector=SourceSelector( components=( ComponentSelector( - component=AllComponents.CHANNEL, + component=Microscopy.Channel, value={primary_channel!r} ), ) ), component_identity=( ComponentSelector( - component=AllComponents.CHANNEL, + component=Microscopy.Channel, value={binding_state.channel_identity!r} ), ) @@ -1291,14 +1288,14 @@ def demo_source( selector=SourceSelector( components=( ComponentSelector( - component=AllComponents.CHANNEL, + component=Microscopy.Channel, value={secondary_channel!r} ), ) ), component_identity=( ComponentSelector( - component=AllComponents.CHANNEL, + component=Microscopy.Channel, value='MCP_AGP' ), ) @@ -1331,9 +1328,9 @@ def demo_source( name='create_composite', processing_config=LazyProcessingConfig( variable_components=[ - VariableComponents.CHANNEL + Microscopy.Channel ], - group_by=GroupBy.NONE + group_by=Ungrouped ) ), FunctionStep( @@ -1343,7 +1340,7 @@ def demo_source( name='Z-Stack Flattening', processing_config=LazyProcessingConfig( variable_components=[ - VariableComponents.Z_INDEX + Microscopy.ZIndex ] ), step_materialization_config=LazyStepMaterializationConfig() @@ -1373,7 +1370,7 @@ def demo_source( name='Z-Stack Flattening', processing_config=LazyProcessingConfig( variable_components=[ - VariableComponents.Z_INDEX + Microscopy.ZIndex ] ) ), @@ -1386,7 +1383,7 @@ def demo_source( }}), name='Cell Counting', processing_config=LazyProcessingConfig( - group_by=GroupBy.CHANNEL + group_by=Microscopy.Channel ), dtype_config=LazyDtypeConfig( default_dtype_conversion=DtypeConversion.UINT8 @@ -2005,9 +2002,9 @@ def assert_applied_document_state( expected_bindings = ( ( binding_state.source_alias, - ((AllComponents.CHANNEL, binding_state.channel_identity),), + ((Microscopy.Channel, binding_state.channel_identity),), ), - ("MCP_AGP", ((AllComponents.CHANNEL, "MCP_AGP"),)), + ("MCP_AGP", ((Microscopy.Channel, "MCP_AGP"),)), ) if observed_bindings != expected_bindings: raise RehearsalFailure( @@ -2031,9 +2028,9 @@ def assert_applied_document_state( processing_semantics.append( { "step_index": step_index, - "group_by": processing_config.group_by.value, + "group_by": processing_config.group_by.name, "variable_components": [ - component.value + component.name for component in processing_config.variable_components ], } @@ -2048,14 +2045,14 @@ def assert_applied_document_state( "alias": binding.alias, "selector_components": [ { - "component": selector.component.value, + "component": selector.component.name, "value": selector.value, } for selector in binding.selector.components ], "component_identity": [ { - "component": selector.component.value, + "component": selector.component.name, "value": selector.value, } for selector in binding.component_identity diff --git a/tests/diagnostics/check_custom_registration_live.py b/tests/diagnostics/check_custom_registration_live.py index 22f5931eed..b60c35ad8f 100644 --- a/tests/diagnostics/check_custom_registration_live.py +++ b/tests/diagnostics/check_custom_registration_live.py @@ -18,6 +18,7 @@ import time import traceback from pathlib import Path +from openhcs.domains.microscopy.axes import Microscopy SOURCE = Path(__file__).resolve().parents[2] PYTHON = Path("/home/ts/code/projects/openhcs/.venv/bin/python") @@ -125,7 +126,7 @@ def fixture(root: Path) -> tuple[Path, object]: projections = SourceProjectionSet( ( SourcePlaneProjection( - OpenHCSPlaneAddress.from_values("A01", 1, 1, 1, 1), + OpenHCSPlaneAddress(((Microscopy.Well, "A01"), (Microscopy.Site, 1), (Microscopy.Channel, 1), (Microscopy.ZIndex, 1), (Microscopy.Timepoint, 1))), SourcePixelRef("disk", path.name), image_metadata=fmt.persisted_metadata(path, payload), ), diff --git a/tests/diagnostics/check_owned_bootstrap_live.py b/tests/diagnostics/check_owned_bootstrap_live.py index 55b214d313..f7dd28fd0b 100644 --- a/tests/diagnostics/check_owned_bootstrap_live.py +++ b/tests/diagnostics/check_owned_bootstrap_live.py @@ -18,6 +18,7 @@ import sys import time import traceback +from openhcs.domains.microscopy.axes import Microscopy SOURCE = Path(__file__).resolve().parents[2] PYTHON = Path('/home/ts/code/projects/openhcs/.venv/bin/python') @@ -315,7 +316,7 @@ def finish(ref): from openhcs.core.config import (PipelineConfig, LazyPathPlanningConfig, LazyVFSConfig, MaterializationBackend, LazyStepMaterializationConfig, LazyProcessingConfig) - from openhcs.constants import Microscope, VariableComponents + from openhcs.constants import Microscope from openhcs.core.pipeline_document import PipelineDocumentAuthority from openhcs.core.steps.function_step import FunctionStep from openhcs.processing.custom_functions import ( @@ -328,7 +329,7 @@ def finish(ref): steps.append(FunctionStep( func=((function, dict(plane_indices=indices)) if phase == 0 else function), name=f'ProjectionCase{case}Step{phase}', - processing_config=LazyProcessingConfig(variable_components=[VariableComponents.Z_INDEX]), + processing_config=LazyProcessingConfig(variable_components=[Microscopy.ZIndex]), step_materialization_config=LazyStepMaterializationConfig(enabled=True))) document = PipelineDocumentAuthority.from_values( pipeline_config=PipelineConfig(num_workers=1, use_threading=True, diff --git a/tests/diagnostics/check_viewer_feature_measurement_live.py b/tests/diagnostics/check_viewer_feature_measurement_live.py index 72476cf80f..1775a9231f 100644 --- a/tests/diagnostics/check_viewer_feature_measurement_live.py +++ b/tests/diagnostics/check_viewer_feature_measurement_live.py @@ -17,6 +17,7 @@ import time import shlex import traceback +from openhcs.domains.microscopy.axes import Microscopy SOURCE = Path(__file__).resolve().parents[2] INSTALLED_PYTHON = Path("/home/ts/code/projects/openhcs/.venv/bin/python") @@ -58,7 +59,7 @@ def make_fixture(root: Path) -> tuple[Path, Path]: fmt.write(path, payload) projections.append( SourcePlaneProjection( - OpenHCSPlaneAddress.from_values("A01", 1, channel, channel, 1), + OpenHCSPlaneAddress(((Microscopy.Well, "A01"), (Microscopy.Site, 1), (Microscopy.Channel, channel), (Microscopy.ZIndex, channel), (Microscopy.Timepoint, 1))), SourcePixelRef("disk", path.name), image_metadata=fmt.persisted_metadata(path, payload), ) diff --git a/tests/diagnostics/create_basicpy_acquisition_fixture.py b/tests/diagnostics/create_basicpy_acquisition_fixture.py index b9dea03eb8..13e6d5a27f 100644 --- a/tests/diagnostics/create_basicpy_acquisition_fixture.py +++ b/tests/diagnostics/create_basicpy_acquisition_fixture.py @@ -7,7 +7,6 @@ import numpy as np -from openhcs.constants import AllComponents from openhcs.core.components.parser_metaprogramming import FilenameParseResult from openhcs.core.image_file_serialization import ImageFileFormat from openhcs.microscopes.imagexpress import ImageXpressFilenameParser @@ -18,6 +17,7 @@ from polystore.filemanager import FileManager from tests.diagnostics.basicpy_observation_fixture import shaded_observations +from openhcs.domains.microscopy.axes import Microscopy def create_acquisition(destination: Path) -> dict: @@ -34,11 +34,11 @@ def create_acquisition(destination: Path) -> dict: for site, pixels in enumerate(observations, start=1): components = FilenameParseResult( ( - (AllComponents.WELL, "A01"), - (AllComponents.SITE, site), - (AllComponents.CHANNEL, 1), - (AllComponents.Z_INDEX, 1), - (AllComponents.TIMEPOINT, 1), + (Microscopy.Well, "A01"), + (Microscopy.Site, site), + (Microscopy.Channel, 1), + (Microscopy.ZIndex, 1), + (Microscopy.Timepoint, 1), ), extension=".tif", ) @@ -54,7 +54,7 @@ def create_acquisition(destination: Path) -> dict: "plate_path": str(destination), "shape_nyx": list(observations.shape), "dtype": str(observations.dtype), - "independent_component": AllComponents.SITE.value, + "independent_component": Microscopy.Site.name, "source_xy_spacing_um": 0.65, "files": paths, } diff --git a/tests/diagnostics/owned_bootstrap_readback.py b/tests/diagnostics/owned_bootstrap_readback.py index 1c71506b64..28669db3bc 100644 --- a/tests/diagnostics/owned_bootstrap_readback.py +++ b/tests/diagnostics/owned_bootstrap_readback.py @@ -8,7 +8,6 @@ import numpy as np from openhcs.agent.dto.execution import ArtifactPlanInspection -from openhcs.constants import AllComponents from openhcs.core.artifacts import ArtifactType, ImageArtifactType from openhcs.core.image_file_serialization import ImageFileFormat from openhcs.core.roi_source_metadata import ROIArchiveSourceMetadata @@ -24,6 +23,8 @@ from openhcs.runtime.zmq_execution_observation import ZMQRuntimeExecutionObservationExport from python_introspect import to_jsonable from polystore.roi import load_rois_from_zip +from openhcs.core.axes import AxisFamily +from openhcs.domains.microscopy.axes import Microscopy def projections(plate: Path): @@ -39,7 +40,7 @@ def projections(plate: Path): def addresses(metadata): return tuple( tuple(source_component_metadata_value(plane.component_metadata, component) - for component in AllComponents) + for component in AxisFamily.active().axes) for plane in metadata.source_provenance.source_image_provenance_planes.planes ) @@ -81,7 +82,7 @@ def verify_volume_publication(owned: Path, image_path: Path, pixels: np.ndarray, [axis_id] = observation.records_by_axis records = observation.records_by_axis[axis_id] native = sorted(projections(image_path.parent), - key=lambda item: int(item.address.value_for(AllComponents.Z_INDEX))) + key=lambda item: int(item.address.value_for(Microscopy.ZIndex))) assert len(native) == 3 assert all(item.image_metadata is not None for item in native) source_addresses = tuple(addresses(item.image_metadata)[0] for item in native) @@ -144,8 +145,8 @@ def record(name): rows.rows.column_values('object_label'), rows.rows.column_values('pixel_count'), strict=True)) assert actual_rows == expected_rows - for component in AllComponents: - assert tuple(str(value) for value in rows.rows.column_values(component.value)) == tuple( + for component in AxisFamily.active().axes: + assert tuple(str(value) for value in rows.rows.column_values(component.name)) == tuple( address.value_for(component) for address in selected_addresses) analysis = Path(plans['volume_fixture_rows_v2'].materialization.analysis_output_dir) [csv_path] = list(analysis.glob(f'*_volume_fixture_rows_v2_step{summary.step_index}_details.csv')) diff --git a/tests/fixtures/g1_cutover/pre_g1_global_config.config.fixture b/tests/fixtures/g1_cutover/pre_g1_global_config.config.fixture new file mode 100644 index 0000000000..2f9110afca --- /dev/null +++ b/tests/fixtures/g1_cutover/pre_g1_global_config.config.fixture @@ -0,0 +1,15 @@ +# OpenHCS configuration + +from openhcs.constants.constants import SequentialComponents +from openhcs.core.config import ( + GlobalPipelineConfig, + SequentialProcessingConfig, +) + +config = GlobalPipelineConfig( + sequential_processing_config=SequentialProcessingConfig( + sequential_components=[ + SequentialComponents.TIMEPOINT + ] + ) +) \ No newline at end of file diff --git a/tests/fixtures/g1_cutover/pre_g1_pipeline.py.fixture b/tests/fixtures/g1_cutover/pre_g1_pipeline.py.fixture new file mode 100644 index 0000000000..97885a9dce --- /dev/null +++ b/tests/fixtures/g1_cutover/pre_g1_pipeline.py.fixture @@ -0,0 +1,54 @@ +# OpenHCS pipeline + +from openhcs.constants.constants import ( + GroupBy, + SequentialComponents, + VariableComponents, +) +from openhcs.core.config import ( + FijiDimensionMode, + FijiStreamingConfig, + LazySequentialProcessingConfig, + NapariDimensionMode, + NapariStreamingConfig, + PipelineConfig, + ProcessingConfig, +) +from openhcs.core.steps.function_step import FunctionStep +from openhcs.processing.backends.processors.numpy_processor import ( + create_projection, + stack_percentile_normalize, +) + +pipeline_config = PipelineConfig( + sequential_processing_config=LazySequentialProcessingConfig( + sequential_components=[ + SequentialComponents.CHANNEL + ] + ) +) + +pipeline_steps = [ + FunctionStep( + func=stack_percentile_normalize, + name='normalize', + processing_config=ProcessingConfig() + ), + FunctionStep( + func=create_projection, + name='project', + processing_config=ProcessingConfig( + variable_components=[ + VariableComponents.Z_INDEX + ], + group_by=GroupBy.NONE + ), + napari_streaming_config=NapariStreamingConfig( + channel_mode=NapariDimensionMode.LAYER, + well_mode=NapariDimensionMode.LAYER + ), + fiji_streaming_config=FijiStreamingConfig( + z_index_mode=FijiDimensionMode.FRAME + ) + ) +] \ No newline at end of file diff --git a/tests/fixtures/mcp/mcp_tool_contract.json b/tests/fixtures/mcp/mcp_tool_contract.json index 7e640df3ef..d0f1cbcd0a 100644 --- a/tests/fixtures/mcp/mcp_tool_contract.json +++ b/tests/fixtures/mcp/mcp_tool_contract.json @@ -5652,7 +5652,7 @@ "readOnlyHint": false, "title": "Set native image colormap and blending" }, - "description": "Set an installed Napari colormap and blending mode on one exact mounted scalar image route. Returns actual native readback. Use channel_mode=LAYER in the stream's original display_config for simultaneous channel composition, and the existing image-intensity tool for each route's numeric window. No pixels, axes, transforms or physical source identities change. RGB images fail closed.", + "description": "Set an installed Napari colormap and blending mode on one exact mounted scalar image route. Returns actual native readback. Use colour_mode=LAYER in the stream's original display_config for simultaneous channel composition, and the existing image-intensity tool for each route's numeric window. No pixels, axes, transforms or physical source identities change. RGB images fail closed.", "execution": null, "icons": null, "inputSchema": { @@ -6464,11 +6464,6 @@ }, "NapariDisplayConfig": { "properties": { - "channel_mode": { - "$ref": "#/$defs/NapariDimensionMode", - "default": "stack", - "description": "Whether channel values are stacked or use separate layers." - }, "colormap": { "default": "gray", "description": "Name of a colormap registered in the installed Napari viewer. Napari validates this extensible registry name when displaying the layer.", @@ -6476,30 +6471,35 @@ "title": "Colormap", "type": "string" }, - "site_mode": { + "colour_mode": { "$ref": "#/$defs/NapariDimensionMode", "default": "stack", - "description": "Whether site values are stacked or use separate layers." + "description": "Whether colour-axis values are stacked or use separate layers." }, - "timepoint_mode": { + "partition_mode": { "$ref": "#/$defs/NapariDimensionMode", "default": "stack", - "description": "Whether timepoint values are stacked or use separate layers." + "description": "Whether parallel-axis values are stacked or use separate layers." }, - "variable_size_handling": { - "$ref": "#/$defs/NapariVariableSizeHandling", - "default": "pad_to_max", - "description": "How Napari handles streamed images with different spatial dimensions: preserve each shape in separate layers or pad smaller images to the largest shape before stacking." + "stack_mode": { + "$ref": "#/$defs/NapariDimensionMode", + "default": "stack", + "description": "Whether stack-axis values are stacked or use separate layers." }, - "well_mode": { + "tile_mode": { "$ref": "#/$defs/NapariDimensionMode", "default": "stack", - "description": "Whether well values are stacked or use separate layers." + "description": "Whether tile-axis values are stacked or use separate layers." }, - "z_index_mode": { + "time_mode": { "$ref": "#/$defs/NapariDimensionMode", "default": "stack", - "description": "Whether z-index values are stacked or use separate layers." + "description": "Whether time-axis values are stacked or use separate layers." + }, + "variable_size_handling": { + "$ref": "#/$defs/NapariVariableSizeHandling", + "default": "pad_to_max", + "description": "How Napari handles streamed images with different spatial dimensions: preserve each shape in separate layers or pad smaller images to the largest shape before stacking." } }, "title": "NapariDisplayConfig", diff --git a/tests/integration/helpers/fixture_utils.py b/tests/integration/helpers/fixture_utils.py index 382a7956ff..19a3bb4fb3 100644 --- a/tests/integration/helpers/fixture_utils.py +++ b/tests/integration/helpers/fixture_utils.py @@ -133,9 +133,9 @@ def tophat(img): ZMQ_EXECUTION_MODE_CONFIGS = ["direct", "zmq", "zmq-tcp"] # Sequential processing configurations for parametrized testing -component1 = "TIMEPOINT" -component2 = "TIMEPOINT,CHANNEL" -component_invalid = "CHANNEL" +component1 = "timepoint" +component2 = "timepoint,channel" +component_invalid = "channel" SEQUENTIAL_CONFIGS = { "none": { "name": "none", @@ -152,14 +152,14 @@ def tophat(img): "valid_2_components": { "name": "valid_2_components", "description": "Sequential with 2 components (TIMEPOINT, CHANNEL)", - "sequential_components": ["TIMEPOINT", "CHANNEL"], + "sequential_components": ["timepoint", "channel"], "should_fail": False, "note": "CHANNEL will be filtered out for create_composite step (which uses CHANNEL in variable_components), but applied to other steps", }, "invalid_overlap": { "name": "invalid_overlap", "description": "CHANNEL conflicts with create_composite's variable_components - will be filtered out", - "sequential_components": ["CHANNEL"], + "sequential_components": ["channel"], "should_fail": False, "note": "CHANNEL will be filtered out for create_composite step, but applied to other steps", }, diff --git a/tests/integration/test_bioformats_imagexpress_synthetic.py b/tests/integration/test_bioformats_imagexpress_synthetic.py index 0968698a12..3fb60b70f0 100644 --- a/tests/integration/test_bioformats_imagexpress_synthetic.py +++ b/tests/integration/test_bioformats_imagexpress_synthetic.py @@ -3,7 +3,6 @@ import pytest -from openhcs.constants.constants import AllComponents from openhcs.microscopes.bioformats import BioFormatsHandler from openhcs.microscopes.bioformats_adapter import ( SourcePlaneStoreAdapter, @@ -11,6 +10,7 @@ from polystore.base import ensure_storage_registry, storage_registry from polystore.filemanager import FileManager from tests.unit.bioformats_imagexpress_fixture import IMAGE_XPRESS_PLATE_FACTORY +from openhcs.domains.microscopy.axes import Microscopy @pytest.mark.integration @@ -23,7 +23,7 @@ def test_bioformats_detects_synthetic_imagexpress_plate(tmp_path: Path) -> None: assert dataset.identity.value == "Plate:0" assert len(dataset.candidates) == 8 assert { - candidate.declared_address.value_for(AllComponents.WELL) + candidate.declared_address.value_for(Microscopy.Well) for candidate in dataset.candidates } == {"A01"} diff --git a/tests/integration/test_cellprofiler_generated_pipeline.py b/tests/integration/test_cellprofiler_generated_pipeline.py index 57d3eba777..ab3a37acf7 100644 --- a/tests/integration/test_cellprofiler_generated_pipeline.py +++ b/tests/integration/test_cellprofiler_generated_pipeline.py @@ -32,7 +32,6 @@ resolve_benchmark_path_root, ) from openhcs.constants import Backend, Microscope -from openhcs.constants.constants import AllComponents from openhcs.constants.input_source import InputSource from openhcs.core.artifacts import ( ArtifactType, @@ -96,6 +95,7 @@ from openhcs.demo.synthetic_data import ( SyntheticMicroscopyGenerator, ) +from openhcs.domains.microscopy.axes import Microscopy def _materialize_imported_sources( @@ -374,7 +374,7 @@ def test_invalid_public_cellprofiler_step_fails_during_zmq_compilation( ), origin=SourceBindingOrigin.PIPELINE_START, component_identity=( - ComponentSelector(AllComponents.CHANNEL, "1"), + ComponentSelector(Microscopy.Channel, "1"), ), ), ), @@ -841,7 +841,7 @@ def test_official_colocalization_preserves_relationships_and_configured_export( } == { "Objects1": ( ( - AllComponents.CHANNEL, + Microscopy.Channel, "1", (2, 1040, 1392), RuntimePlaneAxis.RUNTIME_SLICE, @@ -849,7 +849,7 @@ def test_official_colocalization_preserves_relationships_and_configured_export( ), "Objects2": ( ( - AllComponents.CHANNEL, + Microscopy.Channel, "2", (2, 1040, 1392), RuntimePlaneAxis.RUNTIME_SLICE, @@ -857,7 +857,7 @@ def test_official_colocalization_preserves_relationships_and_configured_export( ), "ColocalizedRegion": ( ( - AllComponents.CHANNEL, + Microscopy.Channel, "1", (2, 1040, 1392), RuntimePlaneAxis.RUNTIME_SLICE, @@ -1003,7 +1003,7 @@ def test_official_illumination_preserves_rule_row_binding_over_zmq( assert source_bindings.binding_for_alias("DNA") is None assert orig_green.origin is SourceBindingOrigin.PIPELINE_START assert orig_green.component_identity == ( - ComponentSelector(AllComponents.CHANNEL, "1"), + ComponentSelector(Microscopy.Channel, "1"), ) assert len(orig_green.selector.filters) == 1 source_filter = orig_green.selector.filters[0] diff --git a/tests/integration/test_chained_callable_lineage_journey.py b/tests/integration/test_chained_callable_lineage_journey.py index 8960728d8c..39ab217239 100644 --- a/tests/integration/test_chained_callable_lineage_journey.py +++ b/tests/integration/test_chained_callable_lineage_journey.py @@ -12,7 +12,7 @@ CompileInspectionInput, InProcessCompileInspectionGateway, ) -from openhcs.constants import AllComponents, Microscope +from openhcs.constants import Microscope from openhcs.core.artifacts import ArtifactInputPlan, ImageArtifactType from openhcs.core.config import ( GlobalPipelineConfig, @@ -45,6 +45,7 @@ # Reuse the public reference's authoritative code block, not a copied callable. from tests.unit.agent.test_callable_artifact_reference import reference_namespace # noqa: F401 +from openhcs.domains.microscopy.axes import Microscopy @pytest.fixture @@ -77,7 +78,7 @@ def test_chained_public_callable_uses_declared_main_flow_not_storage_argument( value="label-fixture", ), )), - component_identity=(ComponentSelector(AllComponents.CHANNEL, "1"),), + component_identity=(ComponentSelector(Microscopy.Channel, "1"),), ) document = PipelineDocumentAuthority.from_values( pipeline_config=PipelineConfig( diff --git a/tests/integration/test_count_cells_simple_dual_channel.py b/tests/integration/test_count_cells_simple_dual_channel.py index e89cf6da22..76916978ad 100644 --- a/tests/integration/test_count_cells_simple_dual_channel.py +++ b/tests/integration/test_count_cells_simple_dual_channel.py @@ -16,7 +16,7 @@ ) from objectstate.lazy_factory import ensure_global_config_context -from openhcs.constants import Microscope, VariableComponents +from openhcs.constants import Microscope from openhcs.core.artifacts import ( MeasurementsArtifactType, ObjectLabelsArtifactType, @@ -55,6 +55,7 @@ from openhcs.demo.synthetic_data import ( SyntheticMicroscopyGenerator, ) +from openhcs.domains.microscopy.axes import Microscopy def _write_known_dual_channel_images(plate_dir): @@ -153,7 +154,7 @@ def test_dual_channel_count_runs_on_synthetic_plate_with_channel_stack( }, ), processing_config=LazyProcessingConfig( - variable_components=[VariableComponents.CHANNEL], + variable_components=[Microscopy.Channel], ), ) aggregate_step = FunctionStep( @@ -171,8 +172,8 @@ def test_dual_channel_count_runs_on_synthetic_plate_with_channel_stack( ), processing_config=LazyProcessingConfig( variable_components=[ - VariableComponents.SITE, - VariableComponents.CHANNEL, + Microscopy.Site, + Microscopy.Channel, ], ), ) @@ -221,17 +222,17 @@ def persisted_special_output_probe(image): func=persisted_special_output_probe, processing_config=LazyProcessingConfig( variable_components=[ - VariableComponents.SITE, - VariableComponents.CHANNEL, + Microscopy.Site, + Microscopy.Channel, ], ), ) pipeline_steps = [step, aggregate_step, custom_step] - assert step.processing_config.variable_components == [VariableComponents.CHANNEL] + assert step.processing_config.variable_components == [Microscopy.Channel] assert aggregate_step.processing_config.variable_components == [ - VariableComponents.SITE, - VariableComponents.CHANNEL, + Microscopy.Site, + Microscopy.Channel, ] output_plate_root = PathPlannerPathAuthority.build_output_plate_root( diff --git a/tests/integration/test_image_math_publication_620.py b/tests/integration/test_image_math_publication_620.py index 1b74ea008f..cf7981aa42 100644 --- a/tests/integration/test_image_math_publication_620.py +++ b/tests/integration/test_image_math_publication_620.py @@ -12,7 +12,7 @@ from openhcs.agent.services.execution_session_service import ( AgentProgressQueue, CompileInspectionInput, InProcessCompileInspectionGateway, ) -from openhcs.constants import GroupBy, Microscope, VariableComponents +from openhcs.constants import Microscope from openhcs.core.config import ( GlobalPipelineConfig, LazyNapariStreamingConfig, LazyPathPlanningConfig, LazyProcessingConfig, @@ -27,6 +27,7 @@ OpenHCSMetadataSubdirectories, VirtualWorkspaceSourceProjectionEntries, ) from openhcs.interop.cellprofiler.pipeline_import import import_cellprofiler_pipeline +from openhcs.domains.microscopy.axes import Microscopy @pytest.mark.parametrize("rgb", (False, True)) @@ -46,7 +47,7 @@ def test_registered_mixed_image_math_publishes_once_in_both_operand_orders(tmp_p config = replace( imported, microscope=Microscope.SOURCE_BINDINGS, processing_config=LazyProcessingConfig( - variable_components=[VariableComponents.Z_INDEX], group_by=GroupBy.CHANNEL), + variable_components=[Microscopy.ZIndex], group_by=Microscopy.Channel), path_planning_config=LazyPathPlanningConfig(global_output_folder=tmp_path / 'results'), source_bindings_config=replace(imported.source_bindings_config, metadata_rules=(MetadataExtractionRule(source=MetadataSource.FILE_NAME, diff --git a/tests/integration/test_main.py b/tests/integration/test_main.py index a0941538b5..aa3cf69487 100644 --- a/tests/integration/test_main.py +++ b/tests/integration/test_main.py @@ -17,11 +17,6 @@ from pathlib import Path from typing import Dict, List, Union -from openhcs.constants.constants import ( - GroupBy, - VariableComponents, - SequentialComponents, -) from openhcs.constants.input_source import InputSource from openhcs.core.config import ( GlobalPipelineConfig, @@ -80,6 +75,8 @@ from objectstate.lazy_factory import ensure_global_config_context from openhcs.core.config import GlobalPipelineConfig, PipelineConfig +from openhcs.core.axes import AxisFamily, Ungrouped +from openhcs.domains.microscopy.axes import Microscopy @dataclass(frozen=True) @@ -275,8 +272,8 @@ def create_test_pipeline( Step( func=create_composite, processing_config=LazyProcessingConfig( - variable_components=[VariableComponents.CHANNEL], - group_by=GroupBy.NONE, + variable_components=[Microscopy.Channel], + group_by=Ungrouped, ), napari_streaming_config=LazyNapariStreamingConfig( port=5557, enabled=enable_napari @@ -289,7 +286,7 @@ def create_test_pipeline( name="Z-Stack Flattening", func=(create_projection, {"method": NumpyStackProjectionMethod.MAX}), processing_config=LazyProcessingConfig( - variable_components=[VariableComponents.Z_INDEX] + variable_components=[Microscopy.ZIndex] ), step_materialization_config=LazyStepMaterializationConfig(), ), @@ -311,7 +308,7 @@ def create_test_pipeline( name="Z-Stack Flattening", func=(create_projection, {"method": NumpyStackProjectionMethod.MAX}), processing_config=LazyProcessingConfig( - variable_components=[VariableComponents.Z_INDEX] + variable_components=[Microscopy.ZIndex] ), ), Step( @@ -498,11 +495,11 @@ def _initialize_orchestrator( omero_backend = OMEROLocalBackend(omero_conn=omero_manager.conn) storage_registry["omero_local"] = omero_backend - # Convert sequential component names to SequentialComponents enum + # Decode sequential axis names through the active family sequential_components = [] if sequential_config and sequential_config.get("sequential_components"): for comp_name in sequential_config["sequential_components"]: - sequential_components.append(SequentialComponents[comp_name]) + sequential_components.append(AxisFamily.active().named(comp_name)) # Determine materialization backend for OMERO tests # For OMERO tests, use omero_local backend for materialization @@ -601,13 +598,12 @@ def _execute_pipeline_phases( """Execute compilation and execution phases of the pipeline (direct mode).""" import multiprocessing import threading - from openhcs.constants import MULTIPROCESSING_AXIS from openhcs.core.progress import set_progress_queue import logging logger = logging.getLogger(__name__) - wells = orchestrator.get_component_keys(MULTIPROCESSING_AXIS) + wells = orchestrator.get_component_keys(AxisFamily.active().partition_axis()) if not wells: raise RuntimeError("No wells found for processing") @@ -759,11 +755,11 @@ def _execute_pipeline_with_mode( # Create global config for ZMQ execution global_config = _create_pipeline_config(test_config) - # Convert sequential component names to SequentialComponents enum + # Decode sequential axis names through the active family sequential_components = [] if sequential_config and sequential_config.get("sequential_components"): for comp_name in sequential_config["sequential_components"]: - sequential_components.append(SequentialComponents[comp_name]) + sequential_components.append(AxisFamily.active().named(comp_name)) # Determine materialization backend for OMERO tests # For OMERO tests, use omero_local backend for materialization diff --git a/tests/integration/test_measurement_declaration_journey.py b/tests/integration/test_measurement_declaration_journey.py index 0f72e605e6..015912b302 100644 --- a/tests/integration/test_measurement_declaration_journey.py +++ b/tests/integration/test_measurement_declaration_journey.py @@ -15,7 +15,7 @@ CompileInspectionInput, InProcessCompileInspectionGateway, ) -from openhcs.constants import AllComponents, GroupBy, Microscope, VariableComponents +from openhcs.constants import Microscope from openhcs.constants.input_source import InputSource from openhcs.core.artifacts import ( ArtifactInputPlan, @@ -90,6 +90,8 @@ register_custom_function, ) from openhcs.processing.materialization import CsvOptions, MaterializationSpec +from openhcs.core.axes import Ungrouped +from openhcs.domains.microscopy.axes import Microscopy @dataclass(frozen=True) @@ -188,7 +190,7 @@ def _source(alias, channel): ), ), ), - component_identity=(ComponentSelector(AllComponents.CHANNEL, channel),), + component_identity=(ComponentSelector(Microscopy.Channel, channel),), ) @@ -197,8 +199,8 @@ def _step(func, name, kwargs): func=(func, kwargs), name=name, processing_config=LazyProcessingConfig( - variable_components=[VariableComponents.SITE], - group_by=GroupBy.NONE, + variable_components=[Microscopy.Site], + group_by=Ungrouped, input_source=InputSource.PIPELINE_START, ), source_bindings=StepSourceBindingsConfig(enabled=True), @@ -438,8 +440,8 @@ def test_exact_secondary_selector_survives_authoring_compile_and_execution(tmp_p store = context.runtime_value_store [primary] = store.find(name="Nuclei", axis_id="A01") [secondary] = store.find(name="Cells", axis_id="A01") - assert primary.key.scope.value_text_for_component(AllComponents.CHANNEL) == "1" - assert secondary.key.scope.value_text_for_component(AllComponents.CHANNEL) == ( + assert primary.key.scope.value_text_for_component(Microscopy.Channel) == "1" + assert secondary.key.scope.value_text_for_component(Microscopy.Channel) == ( "1" if same_source else "2" ) primary_area = np.count_nonzero(object_label_dense_array(primary.data)) @@ -472,7 +474,7 @@ def test_omitted_secondary_selector_still_fails_closed(tmp_path): ) -@pytest.mark.parametrize("producer_group_by", [GroupBy.NONE, GroupBy.CHANNEL]) +@pytest.mark.parametrize("producer_group_by", [Ungrouped, Microscopy.Channel]) def test_explicit_measurement_rosters_preserve_compiled_source_groups( tmp_path, producer_group_by, ): @@ -507,7 +509,7 @@ def test_explicit_measurement_rosters_preserve_compiled_source_groups( context = bundle.runtime_contexts["A01"] executor = FunctionStepExecutor(context, 2) prepared = executor._prepare_groups(executor._detect_patterns()) - expected_keys = (None,) if producer_group_by is GroupBy.NONE else ("1", "2") + expected_keys = (None,) if producer_group_by is Ungrouped else ("1", "2") assert context.step_plans[2].execution_group_scope.keys == expected_keys assert tuple(prepared) == expected_keys assert all(len(patterns) == 1 for patterns in prepared.values()) diff --git a/tests/integration/test_neurite_outgrowth_synthetic_plate.py b/tests/integration/test_neurite_outgrowth_synthetic_plate.py index a83a596ace..b14d2fe608 100644 --- a/tests/integration/test_neurite_outgrowth_synthetic_plate.py +++ b/tests/integration/test_neurite_outgrowth_synthetic_plate.py @@ -37,7 +37,7 @@ from skimage.draw import disk, line from objectstate.lazy_factory import ensure_global_config_context -from openhcs.constants import AllComponents, GroupBy, Microscope, VariableComponents +from openhcs.constants import Microscope from openhcs.core.config import ( AnalysisConsolidationConfig, GlobalPipelineConfig, @@ -75,6 +75,7 @@ from openhcs.demo.synthetic_data import ( SyntheticMicroscopyGenerator, ) +from openhcs.domains.microscopy.axes import Microscopy def _write_known_neurite_images(plate_dir): @@ -157,8 +158,8 @@ def test_neurite_outgrowth_runs_on_synthetic_plate_as_2d_channel_stack( }, ), processing_config=LazyProcessingConfig( - variable_components=[VariableComponents.CHANNEL], - group_by=GroupBy.SITE, + variable_components=[Microscopy.Channel], + group_by=Microscopy.Site, ), ) @@ -190,11 +191,11 @@ def observe_dense_output(output, components): 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_component is Microscopy.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 + assert compiled_plan.variable_components == [Microscopy.Channel] + assert compiled_plan.group_by is Microscopy.Site compiled_pattern = compiled_plan.compiled_function_pattern assert compiled_pattern is not None compiled_invocation = next(compiled_pattern.iter_invocations()) diff --git a/tests/integration/test_primary_segmentation_diagnostics_journey.py b/tests/integration/test_primary_segmentation_diagnostics_journey.py index b8eb1f7c1f..4e703e4d4f 100644 --- a/tests/integration/test_primary_segmentation_diagnostics_journey.py +++ b/tests/integration/test_primary_segmentation_diagnostics_journey.py @@ -6,6 +6,8 @@ import numpy as np import pytest +from openhcs.core.axes import Ungrouped +from openhcs.domains.microscopy.axes import Microscopy def _field(empty=False): @@ -105,7 +107,7 @@ def test_normal_compiled_runtime_persists_diagnostics_and_preserves_secondary_bi CompileInspectionInput, InProcessCompileInspectionGateway, ) - from openhcs.constants import AllComponents, GroupBy, Microscope, VariableComponents + from openhcs.constants import Microscope from openhcs.constants.input_source import InputSource from openhcs.core.artifacts import ( ArtifactInputPlan, @@ -174,8 +176,8 @@ def step(func, name, kwargs): func=(func, kwargs), name=name, processing_config=LazyProcessingConfig( - variable_components=[VariableComponents.SITE], - group_by=GroupBy.NONE, + variable_components=[Microscopy.Site], + group_by=Ungrouped, input_source=InputSource.PIPELINE_START, ), source_bindings=StepSourceBindingsConfig(enabled=True), @@ -240,7 +242,7 @@ def step(func, name, kwargs): ) ), component_identity=( - ComponentSelector(AllComponents.CHANNEL, "1"), + ComponentSelector(Microscopy.Channel, "1"), ), ), ) @@ -403,7 +405,7 @@ def step(func, name, kwargs): assert result_record.source_projection == projection assert result_record.require_image_source_ref() == projection.ref for component, value in projection.address.component_values().items(): - assert str(result_record.metadata[component.value]) == value + assert str(result_record.metadata[component.name]) == value assert projection.source_alias == spec.name assert projection.artifact_kind is ImageArtifactType assert projection.image_metadata is not None diff --git a/tests/integration/test_source_schema_aggregate_publication.py b/tests/integration/test_source_schema_aggregate_publication.py index 39685d6a3d..1c1046ff27 100644 --- a/tests/integration/test_source_schema_aggregate_publication.py +++ b/tests/integration/test_source_schema_aggregate_publication.py @@ -18,7 +18,7 @@ CompileInspectionInput, InProcessCompileInspectionGateway, ) -from openhcs.constants import AllComponents, GroupBy, Microscope, VariableComponents +from openhcs.constants import Microscope from openhcs.constants.input_source import InputSource from openhcs.core.artifacts import ImageArtifactType, MainFlowStackOutputSpec, SpecialArtifactType from openhcs.core.config import ( @@ -46,6 +46,8 @@ register_custom_function, ) from openhcs.processing.materialization import CsvOptions, MaterializationSpec +from openhcs.core.axes import Ungrouped +from openhcs.domains.microscopy.axes import Microscopy @numpy_function(contract=ProcessingContract.PURE_3D) @@ -61,7 +63,7 @@ def volume_scalar_609(image: np.ndarray): return image, ({"volume_sum": int(image.sum()), "voxel_count": int(image.size)},) -@pytest.mark.parametrize("group_by", [GroupBy.NONE, GroupBy.CHANNEL]) +@pytest.mark.parametrize("group_by", [Ungrouped, Microscopy.Channel]) def test_real_z_aggregation_persists_scalar_and_unchanged_source_planes(tmp_path, group_by): source = tmp_path / "input" source.mkdir() @@ -84,14 +86,14 @@ def test_real_z_aggregation_persists_scalar_and_unchanged_source_planes(tmp_path ),), bindings=(NamedSourceBinding( alias="Fixture", selector=SourceSelector(), - component_identity=(ComponentSelector(AllComponents.CHANNEL, "1"),), + component_identity=(ComponentSelector(Microscopy.Channel, "1"),), ),), ), ), pipeline_steps=[FunctionStep( func=registered, name="Actual volume scalar", processing_config=LazyProcessingConfig( - variable_components=[VariableComponents.Z_INDEX], + variable_components=[Microscopy.ZIndex], group_by=group_by, input_source=InputSource.PIPELINE_START, ), @@ -103,7 +105,7 @@ def test_real_z_aggregation_persists_scalar_and_unchanged_source_planes(tmp_path progress_queue=AgentProgressQueue(), )).execution_bundle context = bundle.runtime_contexts["A01"] - assert tuple(context.step_plans[0].variable_components) == (VariableComponents.Z_INDEX,) + assert tuple(context.step_plans[0].variable_components) == (Microscopy.ZIndex,) orchestrator = PipelineOrchestrator(source, pipeline_config=document.pipeline_config).initialize() outcomes = orchestrator.execute_compiled_plate( execution_bundle=bundle, max_workers=1, diff --git a/tests/integration/test_source_store_code_mode_zmq.py b/tests/integration/test_source_store_code_mode_zmq.py index 749b273b4a..5e1b27779d 100644 --- a/tests/integration/test_source_store_code_mode_zmq.py +++ b/tests/integration/test_source_store_code_mode_zmq.py @@ -18,7 +18,7 @@ from zmqruntime.messages import MessageFields from openhcs.constants import Microscope -from openhcs.constants.constants import AllComponents, Backend +from openhcs.constants.constants import Backend from openhcs.constants.input_source import InputSource from openhcs.core.config import ( AnalysisConsolidationConfig, @@ -64,6 +64,8 @@ PlateManagerOrchestratorCodePayload, ) from tests.ome_zarr_fixture import NGFF_FORMATS, write_ngff_plate +from openhcs.core.axes import AxisFamily +from openhcs.domains.microscopy.axes import Microscopy LIVE_ZMQ_ENV = "OPENHCS_RUN_SOURCE_STORE_ZMQ_ACCEPTANCE" REQUIRE_FORMAT_FIXTURES_ENV = "OPENHCS_REQUIRE_SOURCE_STORE_FORMAT_FIXTURES" @@ -285,17 +287,17 @@ def test_code_mode_and_zmq_wire_preserve_mixed_store_sources( records = tuple(record for _path, record in records_by_alias.values()) assert set(records_by_alias) == set(stores) - assert {record.address.value_for(AllComponents.WELL) for record in records} == { + assert {record.address.value_for(Microscopy.Well) for record in records} == { "A01", "mask.png", "plain.tif", } assert { ( - record.address.value_for(AllComponents.SITE), - record.address.value_for(AllComponents.CHANNEL), - record.address.value_for(AllComponents.Z_INDEX), - record.address.value_for(AllComponents.TIMEPOINT), + record.address.value_for(Microscopy.Site), + record.address.value_for(Microscopy.Channel), + record.address.value_for(Microscopy.ZIndex), + record.address.value_for(Microscopy.Timepoint), ) for record in records } == {("1", "1", "1", "1")} @@ -306,13 +308,13 @@ def test_code_mode_and_zmq_wire_preserve_mixed_store_sources( assert len({record.ref.backend_address for record in records}) == len(records) assert { component: set(orchestrator.get_component_keys(component)) - for component in AllComponents + for component in AxisFamily.active().axes } == { - AllComponents.WELL: {"A01", "mask.png", "plain.tif"}, - AllComponents.SITE: {"1"}, - AllComponents.CHANNEL: {"1"}, - AllComponents.Z_INDEX: {"1"}, - AllComponents.TIMEPOINT: {"1"}, + Microscopy.Well: {"A01", "mask.png", "plain.tif"}, + Microscopy.Site: {"1"}, + Microscopy.Channel: {"1"}, + Microscopy.ZIndex: {"1"}, + Microscopy.Timepoint: {"1"}, } for alias, (source_path, pixels) in stores.items(): virtual_path, record = records_by_alias[alias] diff --git a/tests/source_contracts/test_synthetic_acquisition_identity.py b/tests/source_contracts/test_synthetic_acquisition_identity.py index 48597aae95..b0124fd112 100644 --- a/tests/source_contracts/test_synthetic_acquisition_identity.py +++ b/tests/source_contracts/test_synthetic_acquisition_identity.py @@ -12,7 +12,6 @@ from polystore.disk import DiskStorageBackend from polystore.filemanager import FileManager import openhcs.demo.synthetic_data as producer_module -from openhcs.constants.constants import AllComponents from openhcs.core.source_projection import ( OpenHCSPlaneAddress, SourcePlaneProjection, SourceProjectionSet, SourceProjectionMetadataSerializer, @@ -29,6 +28,8 @@ from openhcs.microscopes.imagexpress import ImageXpressFilenameParser, ImageXpressHandler from openhcs.microscopes.microscope_base import MICROSCOPE_HANDLERS from polystore.virtual_workspace import SourcePixelRef +from openhcs.core.axes import AxisFamily +from openhcs.domains.microscopy.axes import Microscopy class SyntheticAcquisitionIdentity(unittest.TestCase): @@ -65,7 +66,7 @@ def assert_coherent(self, plate, metadata, count): self.assertEqual(set(projections), set(paths)) self.assertEqual(set(metadata[FIELDS.WORKSPACE_MAPPING]), set(paths)) parser = FilenameParser.__registry__[metadata[FIELDS.SOURCE_FILENAME_PARSER_NAME]]() - address_sets = {component: set() for component in AllComponents} + address_sets = {component: set() for component in AxisFamily.active().axes} physical_refs = set() for path, projection in projections.items(): parsed = parser.parse_filename(Path(path).name) @@ -78,16 +79,16 @@ def assert_coherent(self, plate, metadata, count): self.assertTrue(physical.is_file()) self.assertEqual(tifffile.imread(physical).shape, (32, 32)) physical_refs.add(ref.backend_address) - for component in AllComponents: + for component in AxisFamily.active().axes: address_sets[component].add(projection.address.value_for(component)) self.assertEqual(len(physical_refs), count) - for component in AllComponents: + for component in AxisFamily.active().axes: self.assertEqual(set(metadata[component_metadata_field(component)]), address_sets[component]) # A fresh real metadata handler reads the persisted component authority. reopened = OpenHCSMetadataHandler( FileManager({"disk": DiskStorageBackend()}) ).component_value_set(plate) - for component in AllComponents: + for component in AxisFamily.active().axes: self.assertEqual(set(reopened.values_for(component)), address_sets[component]) return address_sets @@ -109,12 +110,12 @@ def test_raw_and_native_family_all_components_and_exact_source_refs(self): generator.generate_openhcs_metadata(sub_dir="custom") metadata = self.document(plate) values = self.assert_coherent(plate, metadata, 8 * z_levels) - self.assertEqual(values[AllComponents.WELL], + self.assertEqual(values[Microscopy.Well], {"A01", "D12"} if format == "ImageXpress" else {"R01C01", "R04C12"}) - self.assertEqual(values[AllComponents.SITE], {"1", "2"}) - self.assertEqual(values[AllComponents.CHANNEL], {"1", "2"}) - self.assertEqual(values[AllComponents.Z_INDEX], {str(z) for z in range(1, z_levels + 1)}) - self.assertEqual(values[AllComponents.TIMEPOINT], {"1"}) + self.assertEqual(values[Microscopy.Site], {"1", "2"}) + self.assertEqual(values[Microscopy.Channel], {"1", "2"}) + self.assertEqual(values[Microscopy.ZIndex], {str(z) for z in range(1, z_levels + 1)}) + self.assertEqual(values[Microscopy.Timepoint], {"1"}) self.assertEqual(metadata[FIELDS.MICROSCOPE_HANDLER_NAME], "imagexpress" if format == "ImageXpress" else "opera_phenix") @@ -122,10 +123,10 @@ def test_opera_original_well_disagreement_is_not_a_second_inventory_key(self): generator, plate = self.generate("OperaPhenix", explicit=True) metadata = self.document(plate) parser = FilenameParser.__registry__[metadata[FIELDS.SOURCE_FILENAME_PARSER_NAME]]() - parsed_wells = {parser.parse_filename(path.name).value_for(AllComponents.WELL) + parsed_wells = {parser.parse_filename(path.name).value_for(Microscopy.Well) for path in plate.rglob("*.tiff")} - self.assertEqual(set(metadata[FIELDS.WELLS]), parsed_wells) - self.assertEqual(set(metadata[FIELDS.WELLS]) | parsed_wells, {"R01C01"}) + self.assertEqual(set(metadata[component_metadata_field(Microscopy.Well)]), parsed_wells) + self.assertEqual(set(metadata[component_metadata_field(Microscopy.Well)]) | parsed_wells, {"R01C01"}) self.assert_coherent(plate, metadata, 2) def test_imagexpress_bioformats_stack_retains_folder_axis_and_refs(self): @@ -141,7 +142,7 @@ def test_skipped_plane_cannot_leave_phantom_catalog_or_reference(self): generator, plate = self.generate("OperaPhenix", skip_files=("r01c01f1p01-ch2sk1fk1fl1.tiff",)) metadata = self.document(plate) values = self.assert_coherent(plate, metadata, 1) - self.assertEqual(values[AllComponents.CHANNEL], {"1"}) + self.assertEqual(values[Microscopy.Channel], {"1"}) def test_repeat_generation_replaces_emitted_plane_inventory(self): generator, plate = self.generate("OperaPhenix", z_levels=2) @@ -154,7 +155,7 @@ def test_sparse_sites_are_derived_from_saved_planes(self): for site in (1, 3) for channel in (1, 2)) generator, plate = self.generate("OperaPhenix", grid=(1, 4), skip_files=skipped) values = self.assert_coherent(plate, self.document(plate), 4) - self.assertEqual(values[AllComponents.SITE], {"2", "4"}) + self.assertEqual(values[Microscopy.Site], {"2", "4"}) def test_new_complete_address_needs_no_metadata_variant(self): generator, plate = self.generate("OperaPhenix") @@ -163,10 +164,10 @@ def test_new_complete_address_needs_no_metadata_variant(self): plate / "Images", "D12", 17, 7, 99) generator.generate_openhcs_metadata(sub_dir="Images") values = self.assert_coherent(plate, self.document(plate), 3) - self.assertEqual(values[AllComponents.WELL], {"R01C01", "R04C12"}) - self.assertEqual(values[AllComponents.Z_INDEX], {"1", "99"}) - self.assertEqual(values[AllComponents.SITE], {"1", "17"}) - self.assertEqual(values[AllComponents.CHANNEL], {"1", "2", "7"}) + self.assertEqual(values[Microscopy.Well], {"R01C01", "R04C12"}) + self.assertEqual(values[Microscopy.ZIndex], {"1", "99"}) + self.assertEqual(values[Microscopy.Site], {"1", "17"}) + self.assertEqual(values[Microscopy.Channel], {"1", "2", "7"}) np.testing.assert_array_equal(tifffile.imread(plate / "Images/r04c12f17p99-ch7sk1fk1fl1.tiff"), np.full((32, 32), 172, dtype=np.uint16)) @@ -174,8 +175,8 @@ def test_bioformats_scalar_tokens_can_be_absent_without_losing_identity(self): generator, plate = self.generate("ImageXpress", channels=1, bioformats=True) self.assertEqual({path.name for path in plate.rglob("*.tif")}, {f"{plate.name}_A01.tif"}) values = self.assert_coherent(plate, self.document(plate), 1) - for component in AllComponents: - if component is not AllComponents.WELL: + for component in AxisFamily.active().axes: + if component is not Microscopy.Well: self.assertEqual(values[component], {"1"}) def test_xml_urls_and_physical_names_share_parser_owner(self): @@ -261,11 +262,11 @@ class ScopedRecordedImageXpressParser( parser = parser_type() self.assertIs(FilenameParser.__registry__[parser_type.__name__], parser_type) self.assertEqual(parser_type.__mro__.count(GenericFilenameParser), 1) - self.assertEqual(parser.FILENAME_COMPONENTS, tuple(AllComponents)) + self.assertEqual(parser.FILENAME_COMPONENTS, AxisFamily.active().axes) components = parser.bind_declared_values( - ((AllComponents.WELL, "D12"), (AllComponents.SITE, 17), - (AllComponents.CHANNEL, 7), (AllComponents.Z_INDEX, 99), - (AllComponents.TIMEPOINT, 3))) + ((Microscopy.Well, "D12"), (Microscopy.Site, 17), + (Microscopy.Channel, 7), (Microscopy.ZIndex, 99), + (Microscopy.Timepoint, 3))) physical_name = parser.construct_acquisition_filename(components) self.assertEqual(physical_name, "scope172_D12_s017_w7.tif") self.assertEqual(len(parser.acquisition_calls), 1) @@ -290,8 +291,8 @@ class ScopedRecordedImageXpressParser( grid_dimensions=[1, 1], pixel_size=0.65, main=True) AtomicMetadataWriter().replace_subdirectory_metadata(get_metadata_path(plate), ".", metadata) values = self.assert_coherent(plate, metadata, 1) - self.assertEqual(values[AllComponents.Z_INDEX], {"99"}) - self.assertEqual(values[AllComponents.TIMEPOINT], {"3"}) + self.assertEqual(values[Microscopy.ZIndex], {"99"}) + self.assertEqual(values[Microscopy.Timepoint], {"3"}) class RecordedScopedImageXpressHandler(ImageXpressHandler): _microscope_type = "recorded_scoped_imagexpress" diff --git a/tests/unit/agent/test_agent_services.py b/tests/unit/agent/test_agent_services.py index f5918b9137..4322ea788e 100644 --- a/tests/unit/agent/test_agent_services.py +++ b/tests/unit/agent/test_agent_services.py @@ -82,7 +82,6 @@ ViewerWindowService, ZMQViewerWindowGateway, ) -from openhcs.constants.constants import AllComponents from openhcs.core.artifacts import ( ArtifactInputPlan, ArtifactOutputPlan, @@ -141,6 +140,7 @@ ZMQRuntimeObservationExportScope, ) from python_introspect import to_jsonable +from openhcs.domains.microscopy.axes import Microscopy def sample_processing_function(image, sigma: float = 1.0): @@ -570,7 +570,7 @@ def _compile(self, request): ) step_plan.execution_group_scope = ComponentGroupScope.from_raw( ("A01",), - component=AllComponents.WELL, + component=Microscopy.Well, ) step_plan.materialized_output = MaterializedOutputPlan( output_dir=Path("/tmp/out/A01/checkpoints"), @@ -588,7 +588,7 @@ def _compile(self, request): name="positions", artifact_type=SpecialArtifactType, path="/tmp/out/A01/positions.pkl", - group_component=AllComponents.WELL, + group_component=Microscopy.Well, group_keys=("A01",), paths_by_group={"A01": "/tmp/out/A01/positions.pkl"}, source_step_id=0, @@ -599,7 +599,7 @@ def _compile(self, request): name="objects", artifact_type=ObjectLabelsArtifactType, path="/tmp/out/A01/objects.zarr", - group_component=AllComponents.WELL, + group_component=Microscopy.Well, group_keys=("A01",), paths_by_group={"A01": "/tmp/out/A01/objects.zarr"}, ) @@ -2807,7 +2807,7 @@ def test_config_service_reflects_pipeline_schema_without_materializing_lazy_valu assert "not another ``InputSource`` value" in input_source_description assert "source_bindings_config.bindings[].alias" in nested_paths assert "source_bindings_config.metadata_rules[].pattern" in nested_paths - assert "napari_streaming_config.site_mode" in nested_paths + assert "napari_streaming_config.tile_mode" in nested_paths assert nested_schema.path_prefix == "processing_config" with pytest.raises(ValueError, match="Unknown config schema path_prefix"): @@ -2939,7 +2939,7 @@ def test_config_service_coerces_generic_source_binding_patch_values(): source_bindings.bindings[0].selector.filters[0], SourceFilterClause, ) - assert source_bindings.bindings[0].component_identity[0].component.value == ( + assert source_bindings.bindings[0].component_identity[0].component.name == ( "channel" ) assert "source_bindings_config=LazySourceBindingsConfig" in rendered.source @@ -3118,8 +3118,8 @@ def test_pipeline_authoring_service_derives_step_config_overrides(monkeypatch): assert processing_patch.config_type == "LazyProcessingConfig" assert validation.valid is True assert "processing_config=LazyProcessingConfig(" in rendered.source - assert "VariableComponents.SITE" in rendered.source - assert "group_by=GroupBy.CHANNEL" in rendered.source + assert "Microscopy.Site" in rendered.source + assert "group_by=Microscopy.Channel" in rendered.source def test_pipeline_authoring_service_warns_for_empty_pipeline(monkeypatch): diff --git a/tests/unit/agent/test_authoring_roundtrip_boundaries.py b/tests/unit/agent/test_authoring_roundtrip_boundaries.py index 86a01ca462..7a09584096 100644 --- a/tests/unit/agent/test_authoring_roundtrip_boundaries.py +++ b/tests/unit/agent/test_authoring_roundtrip_boundaries.py @@ -81,7 +81,7 @@ def step_receipt(): "host": "127.0.0.1", "port": 5992, "transport_mode": "tcp", - "channel_mode": "layer", + "colour_mode": "layer", }, ), }, diff --git a/tests/unit/agent/test_config_schema_authority.py b/tests/unit/agent/test_config_schema_authority.py index 0899d814bb..c7ab26c1dc 100644 --- a/tests/unit/agent/test_config_schema_authority.py +++ b/tests/unit/agent/test_config_schema_authority.py @@ -245,4 +245,4 @@ def test_public_processing_schema_response_is_json_safe_and_self_routing(): "z_index", "timepoint", ] - assert fields_by_path["processing_config.group_by"]["enum_values"][-1] == ("NONE") + assert fields_by_path["processing_config.group_by"]["enum_values"][-1] == ("none") diff --git a/tests/unit/agent/test_imagexpress_readonly_paths.py b/tests/unit/agent/test_imagexpress_readonly_paths.py index 8e4470008a..a23079c5df 100644 --- a/tests/unit/agent/test_imagexpress_readonly_paths.py +++ b/tests/unit/agent/test_imagexpress_readonly_paths.py @@ -17,12 +17,13 @@ PlateInspectionFilenameParser, PlateInspectionService, ) -from openhcs.constants.constants import AllComponents from openhcs.core.plate_image_inventory import PlateFileInventory from openhcs.microscopes import create_microscope_handler from openhcs.microscopes.imagexpress import ImageXpressHandler from openhcs.microscopes.microscope_base import MICROSCOPE_HANDLERS from openhcs.microscopes.microscope_interfaces import MicroscopeImagePathParser +from openhcs.core.axes import AxisFamily +from openhcs.domains.microscopy.axes import Microscopy def write_plate(root: Path) -> Path: @@ -83,7 +84,7 @@ def inventory_for(plate: Path): def identity(record): return frozenset( - (c, record.metadata[c.value]) for c in AllComponents + (c, record.metadata[c.name]) for c in AxisFamily.active().axes ), record.source_path @@ -97,7 +98,7 @@ def test_raw_inspection_retains_folder_z_and_never_initializes(tmp_path: Path): assert result.image_files.count == result.parse_summary.parsed_file_count == 4 assert result.pixel_size == 0.5 z = next( - item for item in result.components if item.component is AllComponents.Z_INDEX + item for item in result.components if item.component == Microscopy.ZIndex.name ) assert z.count == 2 assert { @@ -113,11 +114,11 @@ def test_real_inventory_query_and_initialization_agree_on_physical_identity(tmp_ ( frozenset( ( - (AllComponents.WELL, "A01"), - (AllComponents.SITE, 1), - (AllComponents.CHANNEL, channel), - (AllComponents.Z_INDEX, z), - (AllComponents.TIMEPOINT, 1), + (Microscopy.Well, "A01"), + (Microscopy.Site, 1), + (Microscopy.Channel, channel), + (Microscopy.ZIndex, z), + (Microscopy.Timepoint, 1), ) ), str(plate / "TimePoint_1" / f"ZStep_{z}" / f"plate_A01_s1_w{channel}.tif"), @@ -156,7 +157,7 @@ def test_real_inventory_query_and_initialization_agree_on_physical_identity(tmp_ ) assert ( next( - c for c in inspection.components if c.component is AllComponents.Z_INDEX + c for c in inspection.components if c.component == Microscopy.ZIndex.name ).count == 2 ) @@ -175,9 +176,9 @@ def test_path_owner_preserves_flat_and_folder_precedence(relative_path, z, time) ensure_storage_registry() handler = ImageXpressHandler(FileManager(dict(storage_registry))) parsed = handler.parse_image_path(relative_path) - assert parsed.value_for(AllComponents.Z_INDEX) == z - assert parsed.value_for(AllComponents.TIMEPOINT) == time - assert parsed.value_for(AllComponents.CHANNEL) == 2 + assert parsed.value_for(Microscopy.ZIndex) == z + assert parsed.value_for(Microscopy.Timepoint) == time + assert parsed.value_for(Microscopy.Channel) == 2 def test_parse_bounds_errors_unparsed_and_absence_keep_original_receipts(tmp_path): @@ -191,7 +192,7 @@ def test_parse_bounds_errors_unparsed_and_absence_keep_original_receipts(tmp_pat ) == (2, 2) assert inspection.image_files.truncated_file_count == 3 channel = next( - c for c in inspection.components if c.component is AllComponents.CHANNEL + c for c in inspection.components if c.component == Microscopy.Channel.name ) assert channel.count == 2 and len(channel.values) == 1 handler, _, _ = inventory_for(plate) @@ -241,7 +242,7 @@ def image_path_components(self, path): *super().image_path_components(path), *self.indexed_folder_components( path, - AllComponents.SITE, + Microscopy.Site, self._site_pattern, ), ) @@ -268,9 +269,9 @@ def image_path_components(self, path): assert result.handler_class == subtype.__name__ assert result.image_files.count == result.parse_summary.parsed_file_count == 4 summaries = {item.component: item for item in result.components} - assert tuple(v.key for v in summaries[AllComponents.SITE].values) == ("7",) - assert tuple(v.key for v in summaries[AllComponents.TIMEPOINT].values) == ("3",) - assert summaries[AllComponents.Z_INDEX].count == 2 + assert tuple(v.key for v in summaries[Microscopy.Site.name].values) == ("7",) + assert tuple(v.key for v in summaries[Microscopy.Timepoint.name].values) == ("3",) + assert summaries[Microscopy.ZIndex.name].count == 2 query = service_for(plate).query_files( PlateFileQueryRequest.from_fields( plate_path=str(plate), diff --git a/tests/unit/agent/test_knowledge_base_service.py b/tests/unit/agent/test_knowledge_base_service.py index 6820b26a2e..8e312b318f 100644 --- a/tests/unit/agent/test_knowledge_base_service.py +++ b/tests/unit/agent/test_knowledge_base_service.py @@ -19,6 +19,7 @@ ) from openhcs.mcp.context import OpenHCSAgentContext from python_introspect import to_jsonable +from openhcs.core.axes import Ungrouped def test_knowledge_base_catalog_lists_source_backed_documents(): @@ -350,7 +351,7 @@ def test_knowledge_base_retrieves_canonical_image_source_guide(): document.content ) assert "compiler normalizes it to" in document.content - assert "``GroupBy.NONE``" in document.content + assert "``Ungrouped``" in document.content assert "intentionally generic rather than a" in document.content assert "They do not reinterpret a previous step's output" in document.content assert "current artifact provenance" in document.content diff --git a/tests/unit/agent/test_mcp_dev_client_config_renderer.py b/tests/unit/agent/test_mcp_dev_client_config_renderer.py index 0ba5ab6477..12511c7bce 100644 --- a/tests/unit/agent/test_mcp_dev_client_config_renderer.py +++ b/tests/unit/agent/test_mcp_dev_client_config_renderer.py @@ -16,6 +16,8 @@ McpDevOutputRenderer, McpDevPayloadProjection, ) +from openhcs.core.axes import Axis +from openhcs.domains.microscopy.axes import Microscopy def _config_schema_response() -> dict: @@ -74,8 +76,8 @@ def _config_schema_response() -> dict: }, { "path": "default_component", - "type_repr": "AllComponents", - "default_repr": "AllComponents.CHANNEL", + "type_repr": "type[Axis]", + "default_repr": "Microscopy.Channel", "required": False, "description": "Default source component.", "enum_values": ["channel", "z_index"], diff --git a/tests/unit/agent/test_mcp_self_description_contracts.py b/tests/unit/agent/test_mcp_self_description_contracts.py index 35ab70061f..b6255975d1 100644 --- a/tests/unit/agent/test_mcp_self_description_contracts.py +++ b/tests/unit/agent/test_mcp_self_description_contracts.py @@ -10,7 +10,7 @@ from openhcs.agent.path_policy import AgentPathPolicy, AgentPathPolicyError from openhcs.agent.services.config_service import ConfigService -from openhcs.constants.constants import AllComponents, FileFormat +from openhcs.constants.constants import FileFormat from openhcs.core.plate_file_inventory import ( PlateFileInventoryQuery, PlateFileKind, @@ -26,6 +26,7 @@ McpViewerTimeoutPolicy, ) from openhcs.microscopes.openhcs import OpenHCSMetadataHandler +from openhcs.domains.microscopy.axes import Microscopy def _tool_schemas() -> dict[str, dict]: @@ -204,7 +205,7 @@ def test_openhcs_metadata_preserves_null_component_labels(monkeypatch) -> None: ) handler = object.__new__(OpenHCSMetadataHandler) - assert handler.component_value_set("/plate").values_for(AllComponents.WELL) == { + assert handler.component_value_set("/plate").values_for(Microscopy.Well) == { "A01": None, "A02": "Treatment", } diff --git a/tests/unit/agent/test_mcp_server.py b/tests/unit/agent/test_mcp_server.py index 758df3b7a9..97f1835dc4 100644 --- a/tests/unit/agent/test_mcp_server.py +++ b/tests/unit/agent/test_mcp_server.py @@ -23,6 +23,7 @@ import openhcs.mcp.server as server import openhcs.mcp.stdio as mcp_stdio from openhcs.agent.authoring_contexts import AuthoringContextDeclaration +from openhcs.core.axes import AxisFamily from openhcs.agent.capabilities import ( AuthoringLocalCapabilitySurfaceProfile, CapabilityKind, @@ -5804,8 +5805,8 @@ def test_mcp_dev_client_inspect_plate_command_renders_compact_summary(): "root=Images metadata_detected=False diagnostic=Index.xml not found" ) in rendered assert ( - "Axis sizes: wells=1 sites= channels=2 z= " - "timepoints= profile=unknown-site,multi-channel,unknown-z_index," + "Axis sizes: well=1 site= channel=2 z_index= " + "timepoint= profile=unknown-site,multi-channel,unknown-z_index," "unknown-timepoint" ) in rendered assert ( @@ -13574,7 +13575,7 @@ def test_mcp_dev_client_validate_viewer_command_accepts_component_aliases(): assert call.arguments["required_axis_labels"] == ["channel", "y", "x"] assert call.arguments["required_component_labels"].count("well") == 1 assert set(call.arguments["required_component_labels"]) == { - component.value for component in dev_client.AllComponents + component.name for component in AxisFamily.active().axes } diff --git a/tests/unit/agent/test_native_presentation_451452.py b/tests/unit/agent/test_native_presentation_451452.py index 711867b404..db5a579df5 100644 --- a/tests/unit/agent/test_native_presentation_451452.py +++ b/tests/unit/agent/test_native_presentation_451452.py @@ -17,7 +17,7 @@ def test_stream_admits_original_display_declaration_without_changing_endpoint(): display = NapariDisplayConfig( - channel_mode=NapariDimensionMode.LAYER, colormap="green" + colour_mode=NapariDimensionMode.LAYER, colormap="green" ) request = PlateFileStreamRequest.from_fields( plate_path="/synthetic", @@ -25,10 +25,10 @@ def test_stream_admits_original_display_declaration_without_changing_endpoint(): port=6004, ) config = PlateStreamingService._streaming_config(request) - assert config.channel_mode is NapariDimensionMode.LAYER + assert config.colour_mode is NapariDimensionMode.LAYER assert config.colormap == "green" assert config.port == 6004 - assert request.as_tool_arguments()["display_config"]["channel_mode"] == "layer" + assert request.as_tool_arguments()["display_config"]["colour_mode"] == "layer" assert isinstance(config, NapariDisplayConfig) @@ -106,7 +106,7 @@ def test_two_physical_channel_layers_share_spatial_view_without_remapping_pixels PlateFileStreamRequest.from_fields( plate_path="/synthetic", display_config=NapariDisplayConfig( - channel_mode=NapariDimensionMode.LAYER, + colour_mode=NapariDimensionMode.LAYER, ), ) ) diff --git a/tests/unit/agent/test_native_presentation_mcp_451452.py b/tests/unit/agent/test_native_presentation_mcp_451452.py index cd2b49308d..a095712fc5 100644 --- a/tests/unit/agent/test_native_presentation_mcp_451452.py +++ b/tests/unit/agent/test_native_presentation_mcp_451452.py @@ -61,7 +61,7 @@ def test_original_mcp_generators_publish_and_invoke_both_native_operations(): tools = {tool.name: tool for tool in asyncio.run(built.list_tools())} stream = tools["openhcs_stream_plate_files_to_viewer"].inputSchema assert "display_config" in stream["properties"] - assert "channel_mode" in next( + assert "colour_mode" in next( definition["properties"] for definition in stream["$defs"].values() if definition.get("title") == "NapariDisplayConfig" diff --git a/tests/unit/agent/test_owned_bootstrap_readback.py b/tests/unit/agent/test_owned_bootstrap_readback.py index 440fee653f..745c7c6095 100644 --- a/tests/unit/agent/test_owned_bootstrap_readback.py +++ b/tests/unit/agent/test_owned_bootstrap_readback.py @@ -5,6 +5,7 @@ from types import SimpleNamespace from polystore.virtual_workspace import SourcePixelRef +from openhcs.domains.microscopy.axes import Microscopy from openhcs.agent.dto.execution import ArtifactMaterializationPlanSummary, ArtifactPlanSummary from openhcs.core.artifacts import ImageArtifactType from openhcs.core.source_projection import OpenHCSPlaneAddress, SourceArtifactProjection, SourcePlaneProjection @@ -27,7 +28,7 @@ def projections_for(addresses, name="probe_image"): def test_named_and_primary_inventory_is_complete_and_extends_from_declarations(): - addresses = tuple(OpenHCSPlaneAddress.from_values("image.ome.tif", 1, 1, z, 1) for z in (3, 1)) + addresses = tuple(OpenHCSPlaneAddress(((Microscopy.Well, "image.ome.tif"), (Microscopy.Site, 1), (Microscopy.Channel, 1), (Microscopy.ZIndex, z), (Microscopy.Timepoint, 1))) for z in (3, 1)) saved = projections_for(addresses) require_projection_inventory(saved, addresses, (image_plan(),)) with pytest.raises(AssertionError): @@ -42,7 +43,7 @@ def test_named_and_primary_inventory_is_complete_and_extends_from_declarations() @pytest.mark.parametrize("field", ["well", "site", "channel", "z_index", "timepoint"]) def test_csv_address_cannot_match_only_slice_label_and_count(field): - address = OpenHCSPlaneAddress.from_values("image.ome.tif", 1, 2, 3, 4) + address = OpenHCSPlaneAddress(((Microscopy.Well, "image.ome.tif"), (Microscopy.Site, 1), (Microscopy.Channel, 2), (Microscopy.ZIndex, 3), (Microscopy.Timepoint, 4))) row = dict(address.as_component_metadata(), slice_index="0", object_label="13", pixel_count="16", object_name="probe_labels") expected = ((0, 13, 16),) diff --git a/tests/unit/agent/test_persisted_output_reopen.py b/tests/unit/agent/test_persisted_output_reopen.py index 19835225d7..eb4fec5ebf 100644 --- a/tests/unit/agent/test_persisted_output_reopen.py +++ b/tests/unit/agent/test_persisted_output_reopen.py @@ -8,6 +8,7 @@ from polystore.virtual_workspace import SourcePixelRef from polystore.source_tile_geometry import SourceTileGeometry +from openhcs.domains.microscopy.axes import Microscopy from openhcs.agent.dto.plate import ( PlateFileQueryRequest, PlateFileStreamRequest, @@ -68,7 +69,7 @@ def declared_output(root, aliases): image_format.write(path, payload) virtual_path = str(path.relative_to(root)) projection = SourceArtifactProjection( - address=OpenHCSPlaneAddress.from_values("A01", 1, 2, 1, 1), + address=OpenHCSPlaneAddress(((Microscopy.Well, "A01"), (Microscopy.Site, 1), (Microscopy.Channel, 2), (Microscopy.ZIndex, 1), (Microscopy.Timepoint, 1))), ref=SourcePixelRef("disk", virtual_path), source_alias=alias, artifact_kind=ImageArtifactType, @@ -198,7 +199,7 @@ def test_mixed_plane_and_artifact_projections_keep_scope_and_storage_independent ImageFileFormat.require_path(plane_path).write(plane_path, pixels) row, column = divmod(site - 1, 2) planes.append(SourcePlaneProjection( - address=OpenHCSPlaneAddress.from_values("A01", site, 2, 1, 1), + address=OpenHCSPlaneAddress(((Microscopy.Well, "A01"), (Microscopy.Site, site), (Microscopy.Channel, 2), (Microscopy.ZIndex, 1), (Microscopy.Timepoint, 1))), ref=SourcePixelRef("disk", str(plane_path.relative_to(root))), source_metadata={SourceTileGeometry.metadata_field: SourceTileGeometry( x_pixels=column * 6, y_pixels=row * 5, diff --git a/tests/unit/agent/test_plate_inspection_service.py b/tests/unit/agent/test_plate_inspection_service.py index ba09552d25..9a62c90347 100644 --- a/tests/unit/agent/test_plate_inspection_service.py +++ b/tests/unit/agent/test_plate_inspection_service.py @@ -26,7 +26,6 @@ from openhcs.agent.services.synthetic_plate_service import ( SyntheticPlateGenerationService, ) -from openhcs.constants.constants import AllComponents from openhcs.core.config import GlobalPipelineConfig, PathPlanningConfig from openhcs.core.pipeline.path_planner import PathPlannerPathAuthority from openhcs.core.plate_image_inventory import PlateFileKind @@ -40,6 +39,8 @@ bioformats_filemanager, write_bioformats_manifest_fixture, ) +from openhcs.core.axes import AxisFamily +from openhcs.domains.microscopy.axes import Microscopy class ImageXpressPlateFixture: @@ -214,23 +215,23 @@ def test_plate_inspection_auto_detects_imagexpress_without_mutating(tmp_path: Pa ) ) - assert tuple(summary.component.value for summary in result.components) == ( - AllComponents.ordered_names() + assert tuple(summary.component for summary in result.components) == ( + AxisFamily.active().names() ) well_summary = next( summary for summary in result.components - if summary.component is AllComponents.WELL + if summary.component == Microscopy.Well.name ) site_summary = next( summary for summary in result.components - if summary.component is AllComponents.SITE + if summary.component == Microscopy.Site.name ) channel_summary = next( summary for summary in result.components - if summary.component is AllComponents.CHANNEL + if summary.component == Microscopy.Channel.name ) assert result.schema_version == "openhcs.agent.v1" assert result.errors == () @@ -524,7 +525,7 @@ def test_synthetic_plate_generation_service_writes_inspectable_plate(tmp_path: P channel_summary = next( summary for summary in inspection.components - if summary.component is AllComponents.CHANNEL + if summary.component == Microscopy.Channel.name ) assert generation.errors == () @@ -1268,12 +1269,12 @@ def test_plate_inspection_reads_no_main_openhcs_output_subdirectories( channel_summary = next( summary for summary in inspection.components - if summary.component is AllComponents.CHANNEL + if summary.component == Microscopy.Channel.name ) timepoint_summary = next( summary for summary in inspection.components - if summary.component is AllComponents.TIMEPOINT + if summary.component == Microscopy.Timepoint.name ) assert inspection.errors == () diff --git a/tests/unit/agent/test_plate_streaming_service.py b/tests/unit/agent/test_plate_streaming_service.py index 0ddb846cf3..c57bf0f3fd 100644 --- a/tests/unit/agent/test_plate_streaming_service.py +++ b/tests/unit/agent/test_plate_streaming_service.py @@ -49,6 +49,7 @@ ViewerGraphicalSessionUnavailableError, ViewerLaunchContext, ) +from openhcs.domains.microscopy.axes import Microscopy class FakeHandler: @@ -101,8 +102,8 @@ def test_saved_site_free_image_inventory_and_loading_preserve_original_scope(tmp address=None, ref=ref, source_alias="Signal", artifact_kind=ImageArtifactType, source_metadata=components, image_metadata=metadata, execution_scope=RuntimeExecutionAxisScope.from_raw( - "A01", component="channel", value="1", - fixed_component_values=(("z_index", "1"), ("timepoint", "1")), + "A01", component=Microscopy.Channel, value="1", + fixed_component_values=((Microscopy.ZIndex, "1"), (Microscopy.Timepoint, "1")), ), ) builder = VirtualWorkspaceSourceProjectionBuilder(tmp_path) diff --git a/tests/unit/agent/test_progressive_authoring_context.py b/tests/unit/agent/test_progressive_authoring_context.py index fcf082e3f5..e3e65f537a 100644 --- a/tests/unit/agent/test_progressive_authoring_context.py +++ b/tests/unit/agent/test_progressive_authoring_context.py @@ -33,6 +33,7 @@ from openhcs.agent.image_analysis_qa import ImageAnalysisQaPolicy from openhcs.agent.services.knowledge_base_service import KnowledgeBaseService from openhcs.agent.services.llm_context_service import AgentAuthoringContextService +from openhcs.core.axes import Ungrouped class _UnexpectedFunctionCatalog: @@ -445,7 +446,7 @@ def test_task_contexts_expose_only_the_next_relevant_boundary() -> None: assert "not equivalent to MAP2-seeded analysis" in folder assert "generic compiler regression protects any explicit ordered" in folder assert "variable_components=[CHANNEL] assembles that stack" in folder - assert "normalizes group_by to GroupBy.NONE" in folder + assert "normalizes group_by to Ungrouped" in folder assert "do not reinterpret a previous-step output" in folder assert "Follow current artifact provenance" in folder assert "Use SourceBindingsHandler only when an arbitrary image folder" not in folder diff --git a/tests/unit/cellprofiler_runtime_test_support.py b/tests/unit/cellprofiler_runtime_test_support.py index 6df8809f36..b2c0710b2d 100644 --- a/tests/unit/cellprofiler_runtime_test_support.py +++ b/tests/unit/cellprofiler_runtime_test_support.py @@ -8,7 +8,7 @@ from types import SimpleNamespace from typing import Any -from openhcs.constants.constants import AllComponents, Backend +from openhcs.constants.constants import Backend from openhcs.core.artifacts import ( ArtifactInputPlan, ArtifactInputProjectionPlan, @@ -37,6 +37,7 @@ ColumnarMeasurementTableSchema, ) from openhcs.microscopes.imagexpress import ImageXpressFilenameParser +from openhcs.core.axes import Axis @dataclass(slots=True) @@ -78,7 +79,7 @@ def cellprofiler_runtime_input_edge_for_test( invocation_scope: ComponentGroupScope, producer_selection_scope: ComponentGroupScope, component_scopes: tuple[ComponentGroupScope, ...], - consumer_variable_components: tuple[AllComponents, ...], + consumer_variable_components: tuple[type[Axis], ...], ) -> InvocationArtifactInputEdgePlan: """Build one exact compiled input edge without deriving projection semantics.""" diff --git a/tests/unit/progress/test_live_measurements.py b/tests/unit/progress/test_live_measurements.py index 614a6af92a..7af77d9b55 100644 --- a/tests/unit/progress/test_live_measurements.py +++ b/tests/unit/progress/test_live_measurements.py @@ -2,7 +2,6 @@ import pytest -from openhcs.constants.constants import AllComponents from openhcs.core.artifacts import ArtifactOutputPlan, MeasurementsArtifactType from openhcs.core.progress import ( ProgressEvent, @@ -32,6 +31,7 @@ ColumnarRows, FieldSpec, ) +from openhcs.domains.microscopy.axes import Microscopy @dataclass(frozen=True, slots=True) @@ -110,7 +110,7 @@ def _measurement_record( path=path, artifact_type=MeasurementsArtifactType, group_keys=("DAPI",), - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, ), MeasurementTable( name=name, diff --git a/tests/unit/pyqt_gui/test_config_window_state_resolution.py b/tests/unit/pyqt_gui/test_config_window_state_resolution.py index 37ef1e64cb..0a33483d65 100644 --- a/tests/unit/pyqt_gui/test_config_window_state_resolution.py +++ b/tests/unit/pyqt_gui/test_config_window_state_resolution.py @@ -22,7 +22,6 @@ from pyqt_reactive.services.window_navigation import WindowNavigationRequest from pyqt_reactive.theming.color_scheme import ColorScheme -from openhcs.constants.constants import VariableComponents from openhcs.core.config import ( GlobalPipelineConfig, PipelineConfig, @@ -41,6 +40,7 @@ ) from openhcs.runtime.zmq_config import OpenHCSZMQConfig from openhcs.ui.shared.plate_scope_identity import PlateScopeIdentity +from openhcs.domains.microscopy.axes import Microscopy class PipelineConfigHost: @@ -700,12 +700,12 @@ def test_global_config_concrete_variable_components_are_not_placeholder(qapp) -> group for group in groups if any( - enum_value is VariableComponents.SITE + enum_value is Microscopy.Site for enum_value, _ in group.checkbox_items() ) ) - assert variable_components_group.get_value() == [VariableComponents.SITE] + assert variable_components_group.get_value() == [Microscopy.Site] assert not variable_components_group.has_placeholder_state() for _, checkbox in variable_components_group.checkbox_items(): assert not checkbox.is_placeholder() diff --git a/tests/unit/pyqt_gui/test_live_measurements_window.py b/tests/unit/pyqt_gui/test_live_measurements_window.py index 0e3f802b40..287082e1ac 100644 --- a/tests/unit/pyqt_gui/test_live_measurements_window.py +++ b/tests/unit/pyqt_gui/test_live_measurements_window.py @@ -5,7 +5,6 @@ from PyQt6.QtWidgets import QApplication, QWidget -from openhcs.constants.constants import AllComponents from openhcs.core.component_group_scope import RuntimeExecutionAxisScope from openhcs.pyqt_gui.windows.live_measurements_window import ( LiveMeasurementsWindow, @@ -13,14 +12,15 @@ _scope_text, ) from openhcs.runtime.zmq_config import OpenHCSZMQConfig +from openhcs.domains.microscopy.axes import Microscopy def test_live_measurement_scope_uses_biological_coordinate_labels() -> None: scope = RuntimeExecutionAxisScope.from_raw( "A01", - component=AllComponents.CHANNEL, + component=Microscopy.Channel, value="2", - fixed_component_values=((AllComponents.SITE, "3"),), + fixed_component_values=((Microscopy.Site, "3"),), ) label = _scope_text(scope) diff --git a/tests/unit/pyqt_gui/test_parameter_form_manager_cross_window.py b/tests/unit/pyqt_gui/test_parameter_form_manager_cross_window.py index d89f466bea..9150c90cd4 100644 --- a/tests/unit/pyqt_gui/test_parameter_form_manager_cross_window.py +++ b/tests/unit/pyqt_gui/test_parameter_form_manager_cross_window.py @@ -6,7 +6,6 @@ from objectstate import ObjectStateRegistry from objectstate.global_config import set_global_config_for_editing from objectstate.object_state import ObjectState -from openhcs.constants.constants import VariableComponents from openhcs.core.config import GlobalPipelineConfig, PipelineConfig from pyqt_reactive.forms.parameter_form_chrome_sync import ParameterFormChromeSync from pyqt_reactive.forms.parameter_form_tree_index import ParameterFormTreeIndex @@ -19,6 +18,7 @@ FieldChangeEvent, ) from pyqt_reactive.theming.color_scheme import ColorScheme +from openhcs.domains.microscopy.axes import Microscopy class QtApplicationHarness: @@ -470,7 +470,7 @@ def test_list_enum_placeholder_preview_refreshes_structural_child_paths() -> Non checkbox_group for checkbox_group in manager.findChildren(CheckboxGroupAdapter) if any( - enum_value is VariableComponents.SITE + enum_value is Microscopy.Site for enum_value, _ in checkbox_group.checkbox_items() ) ) @@ -478,13 +478,13 @@ def test_list_enum_placeholder_preview_refreshes_structural_child_paths() -> Non assert plate_state.parameters["processing_config.variable_components"] is None assert group.get_value() is None - assert checkboxes[VariableComponents.SITE].isChecked() - assert not checkboxes[VariableComponents.CHANNEL].isChecked() + assert checkboxes[Microscopy.Site].isChecked() + assert not checkboxes[Microscopy.Channel].isChecked() assert group.has_placeholder_state() global_state.update_parameter( "processing_config.variable_components", - [VariableComponents.SITE, VariableComponents.CHANNEL], + [Microscopy.Site, Microscopy.Channel], ) loop = QEventLoop() QTimer.singleShot(300, loop.quit) @@ -493,12 +493,12 @@ def test_list_enum_placeholder_preview_refreshes_structural_child_paths() -> Non assert plate_state.get_resolved_value( "processing_config.variable_components" - ) == [VariableComponents.SITE, VariableComponents.CHANNEL] + ) == [Microscopy.Site, Microscopy.Channel] assert group.get_value() is None - assert checkboxes[VariableComponents.SITE].isChecked() - assert checkboxes[VariableComponents.CHANNEL].isChecked() - assert checkboxes[VariableComponents.SITE].get_value() is None - assert checkboxes[VariableComponents.CHANNEL].get_value() is None + assert checkboxes[Microscopy.Site].isChecked() + assert checkboxes[Microscopy.Channel].isChecked() + assert checkboxes[Microscopy.Site].get_value() is None + assert checkboxes[Microscopy.Channel].get_value() is None assert group.has_placeholder_state() finally: manager.deleteLater() diff --git a/tests/unit/pyqt_gui/test_pipeline_code_document_transactionality.py b/tests/unit/pyqt_gui/test_pipeline_code_document_transactionality.py index ccc1104f2c..3342d8e903 100644 --- a/tests/unit/pyqt_gui/test_pipeline_code_document_transactionality.py +++ b/tests/unit/pyqt_gui/test_pipeline_code_document_transactionality.py @@ -10,11 +10,11 @@ ManagerActionOperations, ) -from openhcs.constants import GroupBy from openhcs.core.pipeline_document import PipelineDocument from openhcs.pyqt_gui.widgets.shared.services.pipeline_editor_workflows import ( PipelineEditorCodeWorkflow, ) +from openhcs.domains.microscopy.axes import Microscopy class _Signal: @@ -94,26 +94,26 @@ def _operations(editor: _PipelineEditorHarness) -> ManagerActionOperations: """ VALID_SOURCE = """ -from openhcs.constants import GroupBy +from openhcs.domains.microscopy.axes import Microscopy from openhcs.core.config import LazyProcessingConfig, PipelineConfig from openhcs.core.steps.function_step import FunctionStep pipeline_config = PipelineConfig() pipeline_steps = [ FunctionStep( - func=[], processing_config=LazyProcessingConfig(group_by=GroupBy.CHANNEL) + func=[], processing_config=LazyProcessingConfig(group_by=Microscopy.Channel) ) ] """ VALID_DEFAULT_CONFIG_SOURCE = """ -from openhcs.constants import GroupBy +from openhcs.domains.microscopy.axes import Microscopy from openhcs.core.config import LazyProcessingConfig from openhcs.core.steps.function_step import FunctionStep pipeline_steps = [ FunctionStep( - func=[], processing_config=LazyProcessingConfig(group_by=GroupBy.CHANNEL) + func=[], processing_config=LazyProcessingConfig(group_by=Microscopy.Channel) ) ] """ @@ -137,7 +137,7 @@ def test_invalid_config_is_rejected_before_pipeline_editor_mutation() -> None: controller.apply_edited_code(operations, VALID_SOURCE) assert len(editor.pipeline_steps) == 1 - assert editor.pipeline_steps[0].processing_config.group_by is GroupBy.CHANNEL + assert editor.pipeline_steps[0].processing_config.group_by is Microscopy.Channel assert editor.item_list_update_count == 1 assert len(editor.pipeline_changed.values) == 1 diff --git a/tests/unit/pyqt_gui/test_pipeline_editor_widget.py b/tests/unit/pyqt_gui/test_pipeline_editor_widget.py index 348b455777..d58a5857c9 100644 --- a/tests/unit/pyqt_gui/test_pipeline_editor_widget.py +++ b/tests/unit/pyqt_gui/test_pipeline_editor_widget.py @@ -24,7 +24,6 @@ from pyqt_reactive.services.scope_token_service import ScopeTokenService from pyqt_reactive.theming import ColorScheme -from openhcs.constants import GroupBy from openhcs.constants.constants import OrchestratorState from openhcs.core.config import ( GlobalPipelineConfig, @@ -66,6 +65,8 @@ PipelineScopeIdentity, PlateScopeIdentity, ) +from openhcs.core.axes import Ungrouped +from openhcs.domains.microscopy.axes import Microscopy TEST_PLATE_SCOPE = "plate" @@ -1599,27 +1600,27 @@ def test_pipeline_update_refreshes_existing_step_scope_state() -> None: editor.plate_manager = None original = FunctionStep( name="IdentifyPrimaryObjects", - processing_config=LazyProcessingConfig(group_by=GroupBy.CHANNEL), + processing_config=LazyProcessingConfig(group_by=Microscopy.Channel), ) editor.update_pipeline_for_plate(TEST_PLATE_SCOPE, [original]) replacement = FunctionStep( name="IdentifyPrimaryObjects", - processing_config=LazyProcessingConfig(group_by=GroupBy.NONE), + processing_config=LazyProcessingConfig(group_by=Ungrouped), ) replacement._scope_token = original._scope_token editor.update_pipeline_for_plate(TEST_PLATE_SCOPE, [replacement]) resolved = editor.get_pipeline_for_plate(TEST_PLATE_SCOPE) - assert resolved[0].processing_config.group_by is GroupBy.NONE + assert resolved[0].processing_config.group_by is Ungrouped def test_groupby_none_is_concrete_object_state_override() -> None: ObjectStateRegistry.clear() - assert not (GroupBy.NONE == None) # noqa: E711 - assert not (None == GroupBy.NONE) # noqa: E711 + assert not (Ungrouped == None) # noqa: E711 + assert not (None == Ungrouped) # noqa: E711 state = ObjectState( FunctionStep( @@ -1629,9 +1630,9 @@ def test_groupby_none_is_concrete_object_state_override() -> None: scope_id="plate::functionstep_0", ) - state.update_parameter("processing_config.group_by", GroupBy.NONE) + state.update_parameter("processing_config.group_by", Ungrouped) - assert state.parameters["processing_config.group_by"] is GroupBy.NONE + assert state.parameters["processing_config.group_by"] is Ungrouped assert "processing_config.group_by" in state.signature_diff_fields state.reset_parameter("processing_config.group_by") diff --git a/tests/unit/pyqt_gui/test_reactor_providers.py b/tests/unit/pyqt_gui/test_reactor_providers.py index 04fb88f82c..3d51872227 100644 --- a/tests/unit/pyqt_gui/test_reactor_providers.py +++ b/tests/unit/pyqt_gui/test_reactor_providers.py @@ -2,17 +2,18 @@ from objectstate import ObjectStateRegistry -from openhcs.constants.constants import GroupBy, OrchestratorState +from openhcs.constants.constants import OrchestratorState from openhcs.core.orchestrator import PipelineOrchestrator from openhcs.pyqt_gui.services.reactor_providers import ( OpenHCSComponentSelectionProvider, ) +from openhcs.domains.microscopy.axes import Microscopy class _ComponentOrchestrator(PipelineOrchestrator): def get_component_keys(self, group_by, component_filter=None): del component_filter - assert group_by is GroupBy.CHANNEL + assert group_by is Microscopy.Channel return ["1", "2"] @@ -33,9 +34,9 @@ def test_component_provider_resolves_the_public_orchestrator_declaration( lambda _scope_id: orchestrator, ) - assert provider.has_components_available(GroupBy.CHANNEL) is False + assert provider.has_components_available(Microscopy.Channel) is False orchestrator.state = OrchestratorState.READY - assert provider.has_components_available(GroupBy.CHANNEL) is True - assert provider.get_component_keys(GroupBy.CHANNEL) == ["1", "2"] + assert provider.has_components_available(Microscopy.Channel) is True + assert provider.get_component_keys(Microscopy.Channel) == ["1", "2"] diff --git a/tests/unit/pyqt_gui/test_source_binding_round_trip.py b/tests/unit/pyqt_gui/test_source_binding_round_trip.py index 1e541ace33..0018926888 100644 --- a/tests/unit/pyqt_gui/test_source_binding_round_trip.py +++ b/tests/unit/pyqt_gui/test_source_binding_round_trip.py @@ -13,15 +13,15 @@ NamedSourceBinding, SourceSelector, ) -from openhcs.constants.constants import AllComponents from openhcs.pyqt_gui.widgets.source_bindings_editor import SourceBindingsEditorWidget +from openhcs.domains.microscopy.axes import Microscopy def binding_with_unlisted_fields() -> NamedSourceBinding: return NamedSourceBinding( alias="DNA", selector=SourceSelector( - components=(ComponentSelector(AllComponents.CHANNEL, "1"),), + components=(ComponentSelector(Microscopy.Channel, "1"),), ), explicit_source=ImagePlaneSource(uri="/data/plate/dna.tif", series="0"), load_as_monochrome=True, @@ -43,7 +43,7 @@ def test_bindings_table_round_trip_preserves_every_binding_field(qapp) -> None: editor.table.item(*editor.cell_position(0, "alias")).setText("Nuclei") editor.table.cellWidget(*editor.cell_position(0, "components")).set_value( - (ComponentSelector(AllComponents.CHANNEL, "2"),) + (ComponentSelector(Microscopy.Channel, "2"),) ) mask_checkbox = editor.table.cellWidget(*editor.cell_position(0, "load_as_mask")) assert isinstance(mask_checkbox, QCheckBox) @@ -54,7 +54,7 @@ def test_bindings_table_round_trip_preserves_every_binding_field(qapp) -> None: alias="Nuclei", selector=replace( binding.selector, - components=(ComponentSelector(AllComponents.CHANNEL, "2"),), + components=(ComponentSelector(Microscopy.Channel, "2"),), ), load_as_mask=False, ) diff --git a/tests/unit/pyqt_gui/test_source_bindings_editor.py b/tests/unit/pyqt_gui/test_source_bindings_editor.py index bfdf9d6a28..02487d8114 100644 --- a/tests/unit/pyqt_gui/test_source_bindings_editor.py +++ b/tests/unit/pyqt_gui/test_source_bindings_editor.py @@ -43,7 +43,7 @@ SourceBindingsConfig, StepSourceBindingsConfig, ) -from openhcs.constants.constants import AllComponents, Backend +from openhcs.constants.constants import Backend from openhcs.core.steps.function_step import FunctionStep from openhcs.core.source_bindings_preview import SourceInventory from openhcs.pyqt_gui.widgets.source_bindings_editor import ( @@ -99,6 +99,8 @@ from pyqt_reactive.widgets.no_scroll_spinbox import NoScrollComboBox, NoneAwareCheckBox from pyqt_reactive.widgets.shared.scoped_table_widget import ScopedTableWidget from pyqt_reactive.widgets.shared.scope_color_utils import get_scope_color_scheme +from openhcs.core.axes import AxisFamily +from openhcs.domains.microscopy.axes import Microscopy def assert_label_masked(label_widget, window, masks): @@ -224,7 +226,7 @@ def test_structured_selector_dialog_choices_come_from_field_type() -> None: dialog = StructuredSelectorDialog( element_type=ComponentSelector, suggestions=(), - value=(ComponentSelector(AllComponents.CHANNEL, "DNA"),), + value=(ComponentSelector(Microscopy.Channel, "DNA"),), ) component_widget = dialog.table.cellWidget( @@ -233,8 +235,8 @@ def test_structured_selector_dialog_choices_come_from_field_type() -> None: assert isinstance(component_widget, QComboBox) assert tuple( component_widget.itemData(index) for index in range(component_widget.count()) - ) == tuple(AllComponents) - assert component_widget.currentData() is AllComponents.CHANNEL + ) == AxisFamily.active().axes + assert component_widget.currentData() is Microscopy.Channel def test_structured_selector_dialog_reports_incomplete_rows() -> None: @@ -4507,7 +4509,7 @@ def test_source_bindings_editor_edits_step_binding_table() -> None: def test_source_bindings_editor_preserves_selector_on_basic_edits() -> None: QtApplicationHarness.app() selector = SourceSelector( - components=(ComponentSelector(AllComponents.CHANNEL, "DNA"),), + components=(ComponentSelector(Microscopy.Channel, "DNA"),), metadata=(MetadataSelector("Well", "A01"),), filters=( SourceFilterClause( @@ -4537,7 +4539,7 @@ def test_source_bindings_editor_preserves_binding_identity_on_basic_edits() -> N QtApplicationHarness.app() binding = NamedSourceBinding( alias="DNA", - component_identity=(ComponentSelector(AllComponents.CHANNEL, "1"),), + component_identity=(ComponentSelector(Microscopy.Channel, "1"),), projection_role=SourceProjectionRole.SOURCE_ARTIFACT, ) widget = SourceBindingsEditorWidget.from_bindings( @@ -4550,7 +4552,7 @@ def test_source_bindings_editor_preserves_binding_identity_on_basic_edits() -> N edited = widget.get_value().bindings[0] assert edited.alias == "OrigDNA" - assert edited.component_identity == (ComponentSelector(AllComponents.CHANNEL, "1"),) + assert edited.component_identity == (ComponentSelector(Microscopy.Channel, "1"),) assert edited.projection_role is SourceProjectionRole.SOURCE_ARTIFACT @@ -4564,7 +4566,7 @@ def test_source_bindings_editor_edits_binding_identity_columns() -> None: set_editable_cell_text( table, *binding_cell_position(0, "component_identity"), - (ComponentSelector(AllComponents.CHANNEL, "2"), ComponentSelector(AllComponents.SITE, "1")), + (ComponentSelector(Microscopy.Channel, "2"), ComponentSelector(Microscopy.Site, "1")), ) set_binding_cell_text( table, @@ -4582,8 +4584,8 @@ def test_source_bindings_editor_edits_binding_identity_columns() -> None: binding = widget.get_value().bindings[0] assert binding.component_identity == ( - ComponentSelector(AllComponents.CHANNEL, "2"), - ComponentSelector(AllComponents.SITE, "1"), + ComponentSelector(Microscopy.Channel, "2"), + ComponentSelector(Microscopy.Site, "1"), ) assert binding.source_set_role is SourceSetRole.BROADCAST assert binding.projection_role is SourceProjectionRole.SOURCE_ARTIFACT @@ -4599,7 +4601,7 @@ def test_source_bindings_editor_edits_selector_columns() -> None: set_editable_cell_text( table, *binding_cell_position(0, "components"), - (ComponentSelector(AllComponents.CHANNEL, "DNA"), ComponentSelector(AllComponents.SITE, "1")), + (ComponentSelector(Microscopy.Channel, "DNA"), ComponentSelector(Microscopy.Site, "1")), ) set_editable_cell_text( table, @@ -4616,8 +4618,8 @@ def test_source_bindings_editor_edits_selector_columns() -> None: selector = widget.get_value().bindings[0].selector assert selector.components == ( - ComponentSelector(AllComponents.CHANNEL, "DNA"), - ComponentSelector(AllComponents.SITE, "1"), + ComponentSelector(Microscopy.Channel, "DNA"), + ComponentSelector(Microscopy.Site, "1"), ) assert selector.metadata == (MetadataSelector("Well", "A01"),) assert selector.filters == ( diff --git a/tests/unit/pyqt_gui/test_ui_agent_bridge.py b/tests/unit/pyqt_gui/test_ui_agent_bridge.py index 6f881fdef5..3a7040b9d6 100644 --- a/tests/unit/pyqt_gui/test_ui_agent_bridge.py +++ b/tests/unit/pyqt_gui/test_ui_agent_bridge.py @@ -3246,7 +3246,7 @@ def test_object_state_field_help_uses_object_state_path_types() -> None: "channel", "z_index", "timepoint", - "NONE", + "none", ) diff --git a/tests/unit/test_acquisition_calibration_pipeline_journey.py b/tests/unit/test_acquisition_calibration_pipeline_journey.py index f47d6070ff..50ecc7fbcc 100644 --- a/tests/unit/test_acquisition_calibration_pipeline_journey.py +++ b/tests/unit/test_acquisition_calibration_pipeline_journey.py @@ -8,7 +8,7 @@ from objectstate import ObjectStateRegistry from objectstate.lazy_factory import ensure_global_config_context -from openhcs.constants import Microscope, VariableComponents +from openhcs.constants import Microscope from openhcs.core.config import ( GlobalPipelineConfig, LazyPathPlanningConfig, @@ -20,6 +20,7 @@ from openhcs.core.source_metadata import SourceVoxelSpacing, SourceVoxelSpacingUnit from openhcs.core.steps.function_step import FunctionStep from openhcs.processing.backends.processors.numpy_processor import gaussian_blur +from openhcs.domains.microscopy.axes import Microscopy def test_htd_spacing_survives_gaussian_compile_execute_and_persist(tmp_path): @@ -55,7 +56,7 @@ def test_htd_spacing_survives_gaussian_compile_execute_and_persist(tmp_path): FunctionStep( func=(gaussian_blur, {"sigma": 1}), processing_config=LazyProcessingConfig( - variable_components=[VariableComponents.Z_INDEX] + variable_components=[Microscopy.ZIndex] ), ) ], diff --git a/tests/unit/test_aggregate_layer_materialization_515.py b/tests/unit/test_aggregate_layer_materialization_515.py index 76ae717972..76de7488c1 100644 --- a/tests/unit/test_aggregate_layer_materialization_515.py +++ b/tests/unit/test_aggregate_layer_materialization_515.py @@ -9,7 +9,6 @@ import numpy as np import pytest -from openhcs.constants.constants import AllComponents, VariableComponents from openhcs.core.artifacts import ArtifactOutputPlan, ObjectLabelsArtifactType from openhcs.core.pipeline.artifact_planning import ( AutomaticObjectLabelsArtifactOutputMaterializationStrategy, @@ -60,6 +59,7 @@ _context, _plan, ) +from openhcs.domains.microscopy.axes import Microscopy class ComponentDisplayConfig(StreamingConfigStub): @@ -69,7 +69,7 @@ def __init__(self, component, mode): self.mode = mode def component_modes(self): - return {**super().component_modes(), self.component.value: self.mode} + return {**super().component_modes(), self.component.name: self.mode} def _source_bound_labels(component): @@ -78,7 +78,7 @@ def _source_bound_labels(component): pixels[1, 1:3, 2:5] = 2 source_fields = tuple( {"well": "A01", "site": 1, "channel": 1, "z_index": 1, - "timepoint": 1, component.value: value} + "timepoint": 1, component.name: value} for value in (1, 2) ) paths = tuple( @@ -108,7 +108,7 @@ def _automatic_label_tiff(component, mode, return_route, monkeypatch, tmp_path): labels, pixels = _source_bound_labels(component) output_plan = ArtifactOutputPlan( name="Nuclei", path="/memory/Nuclei.pkl", artifact_type=ObjectLabelsArtifactType, - variable_components=(VariableComponents(component.value),), + variable_components=(component,), materialization=AutomaticObjectLabelsArtifactOutputMaterializationStrategy().materialization(), ) ensure_storage_registry() @@ -144,7 +144,7 @@ def save_batch(contents, paths, backend, **kwargs): plan = replace(_plan( output_plan, streaming_configs={"napari_stream": ComponentDisplayConfig(component, mode)}, - variable_components=(VariableComponents(component.value),), + variable_components=(component,), ), analysis_results_dir=str(tmp_path / "analysis"), output_dir=tmp_path / "images") PersistentArtifactMaterializationTargetPlan("disk").materialize_outputs(filemanager, plan, context) assert len(disk_outputs) == 1 @@ -157,7 +157,7 @@ def save_batch(contents, paths, backend, **kwargs): assert metadata.plane_axis is RuntimePlaneAxis.SOURCE_BINDING assert metadata.source_provenance.source_plane_count == 2 assert metadata.source_voxel_spacing.values_zyx == (0.75, 0.75) - assert [metadata.source_provenance.for_source_plane(index).source_component_metadata[component.value] + assert [metadata.source_provenance.for_source_plane(index).source_component_metadata[component.name] for index in range(2)] == [1, 2] np.testing.assert_array_equal(labels.labels, pixels) tiff_saves = [saved for saved in stream_saves if saved[1].endswith(".labels.tif")] @@ -217,13 +217,13 @@ def _received_item(batch, pixels): return item, semantics -@pytest.mark.parametrize("component", (AllComponents.CHANNEL, AllComponents.SITE)) +@pytest.mark.parametrize("component", (Microscopy.Channel, Microscopy.Site)) def test_automatic_aggregate_label_tiff_honors_separate_layers(component, viewer_ack_return_route, monkeypatch, tmp_path): labels, pixels, saves, batches = _automatic_label_tiff(component, "layer", viewer_ack_return_route, monkeypatch, tmp_path) # This is the original strict receiver, not a test-side default or projection. keys = _route_keys(batches) items = [item for batch in batches for item in batch.batch_images] - assert [item["metadata"][component.value] for item in items] == [1, 2] + assert [item["metadata"][component.name] for item in items] == [1, 2] assert len(set(keys)) == 2 assert [tuple(item["shape"]) for item in items] == [(4, 5), (4, 5)] for index, (content, _path, _backend, _kwargs) in enumerate(saves): @@ -231,7 +231,7 @@ def test_automatic_aggregate_label_tiff_honors_separate_layers(component, viewer np.testing.assert_array_equal(labels.labels, pixels) -@pytest.mark.parametrize("component", (AllComponents.CHANNEL, AllComponents.SITE)) +@pytest.mark.parametrize("component", (Microscopy.Channel, Microscopy.Site)) def test_automatic_aggregate_label_tiff_preserves_stack(component, viewer_ack_return_route, monkeypatch, tmp_path): labels, pixels, saves, batches = _automatic_label_tiff(component, "stack", viewer_ack_return_route, monkeypatch, tmp_path) assert len(saves) == len(batches) == 1 @@ -240,23 +240,23 @@ def test_automatic_aggregate_label_tiff_preserves_stack(component, viewer_ack_re assert tuple(item["shape"]) == pixels.shape assert item["dtype"] == str(pixels.dtype) assert item["plane_axis"] == RuntimePlaneAxis.SOURCE_BINDING.value - assert item["plane_component_values"] == {component.value: ["1", "2"]} + assert item["plane_component_values"] == {component.name: ["1", "2"]} decoded = ImagePayloadMetadata.from_viewer_image_metadata(item["image_metadata"]) assert decoded.source_voxel_spacing.values_zyx == (0.75, 0.75) assert decoded.source_spatial_domain.source_shape_yx == (4, 5) - assert component.value not in item["metadata"] + assert component.name not in item["metadata"] assert len(_route_keys(batches)) == 1 received, semantics = _received_item(batches[0], saves[0][0]) bindings = NapariAggregateAxisBindingAuthority.bindings((received,), semantics) assert len(bindings.bindings) == 1 - assert bindings.bindings[0].component == component.value + assert bindings.bindings[0].component == component.name assert bindings.bindings[0].values == (1, 2) np.testing.assert_array_equal(labels.labels, pixels) def test_strict_receiver_still_rejects_aggregate_without_scalar_layer(viewer_ack_return_route, monkeypatch, tmp_path): _labels, _pixels, _saves, batches = _automatic_label_tiff( - AllComponents.CHANNEL, "stack", viewer_ack_return_route, monkeypatch, tmp_path, + Microscopy.Channel, "stack", viewer_ack_return_route, monkeypatch, tmp_path, ) batch = batches[0] layout = normalize_component_layout(batch.message["display_config"]) @@ -271,7 +271,7 @@ def test_single_output_kwargs_cannot_hide_projected_pixels( plane_count, viewer_ack_return_route, monkeypatch, tmp_path, ): labels, pixels, saves, _batches = _automatic_label_tiff( - AllComponents.CHANNEL, "stack", viewer_ack_return_route, monkeypatch, tmp_path, + Microscopy.Channel, "stack", viewer_ack_return_route, monkeypatch, tmp_path, ) metadata = labels.metadata.replace_fields( source_image_provenance_planes=SourceImageProvenancePlanes( @@ -280,12 +280,12 @@ def test_single_output_kwargs_cannot_hide_projected_pixels( ) request = replace( saves[0][3][ViewerStreamKwarg.STREAM_REQUEST.value], - display_config=ComponentDisplayConfig(AllComponents.CHANNEL, "layer"), + display_config=ComponentDisplayConfig(Microscopy.Channel, "layer"), ) kwargs = ViewerStreamBackendCallKwargs(ViewerStreamBackendKwargs(request)) output = Output( path=saves[0][1], content=pixels[:plane_count], metadata=metadata, - variable_components=(AllComponents.CHANNEL,), + variable_components=(Microscopy.Channel,), ) with pytest.raises(ValueError, match="requires batch saving"): kwargs.to_filemanager_kwargs(output) @@ -312,7 +312,7 @@ def test_strict_aggregate_receiver_rejects_malformed_tiff_domains( domain, error, viewer_ack_return_route, monkeypatch, tmp_path, ): _labels, _pixels, saves, batches = _automatic_label_tiff( - AllComponents.CHANNEL, "stack", viewer_ack_return_route, monkeypatch, tmp_path, + Microscopy.Channel, "stack", viewer_ack_return_route, monkeypatch, tmp_path, ) received, semantics = _received_item(batches[0], saves[0][0]) received = replace(received, plane_component_domain=ViewerComponentValueDomainPayload.from_ordered_wire_mapping( @@ -324,7 +324,7 @@ def test_strict_aggregate_receiver_rejects_malformed_tiff_domains( def test_strict_receiver_rejects_duplicate_plane_coordinates(viewer_ack_return_route, monkeypatch, tmp_path): _labels, _pixels, _saves, batches = _automatic_label_tiff( - AllComponents.CHANNEL, "stack", viewer_ack_return_route, monkeypatch, tmp_path, + Microscopy.Channel, "stack", viewer_ack_return_route, monkeypatch, tmp_path, ) wire = batches[0].batch_images[0] domain = {**wire["plane_component_values"], "channel": ["1", "1"]} @@ -336,7 +336,7 @@ def test_strict_receiver_rejects_duplicate_plane_coordinates(viewer_ack_return_r def test_strict_receiver_rejects_inconsistent_item_plane_domains(viewer_ack_return_route, monkeypatch, tmp_path): _labels, _pixels, saves, batches = _automatic_label_tiff( - AllComponents.CHANNEL, "stack", viewer_ack_return_route, monkeypatch, tmp_path, + Microscopy.Channel, "stack", viewer_ack_return_route, monkeypatch, tmp_path, ) received, semantics = _received_item(batches[0], saves[0][0]) reversed_item = replace( @@ -348,14 +348,14 @@ def test_strict_receiver_rejects_inconsistent_item_plane_domains(viewer_ack_retu NapariAggregateAxisBindingAuthority.bindings((received, reversed_item), semantics) -@pytest.mark.parametrize("component", (AllComponents.CHANNEL, AllComponents.SITE)) +@pytest.mark.parametrize("component", (Microscopy.Channel, Microscopy.Site)) def test_existing_projection_owns_source_binding_label_planes(component): labels, pixels = _source_bound_labels(component) payload = labels.metadata.attach_to(labels.image_data()) items = RuntimeProjectionSourceIdentityRequirement.REQUIRED_COMPONENT_METADATA.project_payload_items( RuntimeProjectionSourceIdentityRequest( value=payload, source_description="automatic label TIFF", - variable_components=(VariableComponents(component.value),), + variable_components=(component,), plane_projection=RuntimePlaneAxisValueProjection.preserve( axis=RuntimePlaneAxis.SOURCE_BINDING, axis_size=2, ), @@ -365,31 +365,31 @@ def test_existing_projection_owns_source_binding_label_planes(component): for index, item in enumerate(items): np.testing.assert_array_equal(item.data, pixels[index]) assert item.metadata.plane_axis is None - assert item.require_source_component_metadata()[component.value] == index + 1 + assert item.require_source_component_metadata()[component.name] == index + 1 assert item.metadata.source_voxel_spacing.values_zyx == (0.75, 0.75) assert np.shares_memory(item.data, labels.image_data()) def test_existing_projection_does_not_infer_runtime_axis_from_label_array(): - labels, _pixels = _source_bound_labels(AllComponents.CHANNEL) + labels, _pixels = _source_bound_labels(Microscopy.Channel) with pytest.raises(RuntimeSliceProjectionDeclarationError, match="requires a nominal payload"): RuntimeProjectionSourceIdentityRequirement.REQUIRED_COMPONENT_METADATA.project_payload_items( RuntimeProjectionSourceIdentityRequest( value=labels.metadata.attach_to(labels.image_data()), source_description="automatic label TIFF", - variable_components=(VariableComponents.CHANNEL,), + variable_components=(Microscopy.Channel,), ) ) def test_existing_projection_rejects_label_source_cardinality_mismatch(): - labels, _pixels = _source_bound_labels(AllComponents.CHANNEL) + labels, _pixels = _source_bound_labels(Microscopy.Channel) with pytest.raises(ValueError, match="metadata cardinality mismatch"): RuntimeProjectionSourceIdentityRequirement.REQUIRED_COMPONENT_METADATA.project_payload_items( RuntimeProjectionSourceIdentityRequest( value=labels.metadata.attach_to(labels.image_data()), source_description="automatic label TIFF", - variable_components=(VariableComponents.CHANNEL,), + variable_components=(Microscopy.Channel,), plane_projection=RuntimePlaneAxisValueProjection.preserve( axis=RuntimePlaneAxis.SOURCE_BINDING, axis_size=3, ), diff --git a/tests/unit/test_aligned_main_flow_projection.py b/tests/unit/test_aligned_main_flow_projection.py index 0bc40ba4da..70d25e0a36 100644 --- a/tests/unit/test_aligned_main_flow_projection.py +++ b/tests/unit/test_aligned_main_flow_projection.py @@ -8,7 +8,6 @@ import numpy as np import pytest -from openhcs.constants.constants import AllComponents from openhcs.core.aligned_image_payload import ( AlignedImageSliceContext, AlignedImageStack, @@ -34,6 +33,7 @@ CellProfilerModuleExecutor, ) from openhcs.processing.backends.cellprofiler.color import color_to_gray +from openhcs.domains.microscopy.axes import Microscopy class _CompiledInputRequest: @@ -174,7 +174,7 @@ def _compiled_image_output( artifact_type=spec.artifact_type, relations=spec.relations, group_keys=(channel,), - group_component=(None if channel is None else AllComponents.CHANNEL), + group_component=(None if channel is None else Microscopy.Channel), ) diff --git a/tests/unit/test_artifact_declaration_step_context.py b/tests/unit/test_artifact_declaration_step_context.py index b83c5943c6..248f0fc84d 100644 --- a/tests/unit/test_artifact_declaration_step_context.py +++ b/tests/unit/test_artifact_declaration_step_context.py @@ -2,7 +2,6 @@ from dataclasses import fields -from openhcs.constants.constants import GroupBy from openhcs.constants.input_source import InputSource from openhcs.core.artifacts import ( ArtifactInputPlan, @@ -21,6 +20,7 @@ NamedSourceBinding, StepSourceBindingsConfig, ) +from openhcs.core.axes import Ungrouped def test_context_owns_exact_step_artifact_projection_facts() -> None: @@ -30,7 +30,7 @@ def test_context_owns_exact_step_artifact_projection_facts() -> None: assert "input_source" in field_names assert "invocation_ordinal" not in field_names assert "processing_config" not in field_names - assert ArtifactDeclarationStepContext.empty().group_by is GroupBy.NONE + assert ArtifactDeclarationStepContext.empty().group_by is Ungrouped assert ( ArtifactDeclarationStepContext.empty().input_source is InputSource.PREVIOUS_STEP ) diff --git a/tests/unit/test_artifact_input_edge_cardinality.py b/tests/unit/test_artifact_input_edge_cardinality.py index 2fafc18b18..5250dacba6 100644 --- a/tests/unit/test_artifact_input_edge_cardinality.py +++ b/tests/unit/test_artifact_input_edge_cardinality.py @@ -2,7 +2,6 @@ from dataclasses import replace -from openhcs.constants.constants import AllComponents from openhcs.core.artifacts import ( ArtifactInputPlan, ArtifactSpec, @@ -19,6 +18,7 @@ InvocationContractProvider, ) from openhcs.core.pipeline.path_planner import PathPlanner, PathPlannerArtifactStage +from openhcs.domains.microscopy.axes import Microscopy class _RuntimeInputContractProvider(InvocationContractProvider): @@ -118,7 +118,7 @@ def consume_ambiguous_objects(image): path="/memory/source.pkl", artifact_type=ObjectLabelsArtifactType, group_keys=("1",), - group_component=AllComponents.SITE, + group_component=Microscopy.Site, ) compiled = compile_function_pattern( consume_ambiguous_objects, diff --git a/tests/unit/test_artifact_input_projection_plan.py b/tests/unit/test_artifact_input_projection_plan.py index 80a6e8e6e4..77c0a4b531 100644 --- a/tests/unit/test_artifact_input_projection_plan.py +++ b/tests/unit/test_artifact_input_projection_plan.py @@ -1,6 +1,5 @@ import pytest -from openhcs.constants.constants import AllComponents from openhcs.core.artifacts import ( ArtifactInputPlan, ArtifactInputProjectionPlan, @@ -10,6 +9,8 @@ ) from openhcs.core.component_group_scope import ComponentGroupScope from openhcs.core.component_set import ComponentSet +from openhcs.core.axes import Axis +from openhcs.domains.microscopy.axes import Microscopy def _projection( @@ -18,7 +19,7 @@ def _projection( invocation_scope: ComponentGroupScope, producer_selection_scope: ComponentGroupScope, component_scopes: tuple[ComponentGroupScope, ...] = (), - consumer_variable_components: tuple[AllComponents, ...] = (), + consumer_variable_components: tuple[type[Axis], ...] = (), ) -> ArtifactInputProjectionPlan: return ArtifactInputProjectionPlan( invocation_scope=invocation_scope, @@ -32,7 +33,7 @@ def _projection( "invocation_scope", ( ComponentGroupScope.ungrouped(), - ComponentGroupScope.dynamic(AllComponents.CHANNEL), + ComponentGroupScope.dynamic(Microscopy.Channel), ), ids=("ungrouped-invocation", "dynamic-dispatch-invocation"), ) @@ -44,13 +45,13 @@ def test_grouped_producer_selection_domain_is_independent_of_invocation_dispatch path="/memory/measurements.pkl", artifact_type=MeasurementsArtifactType, group_keys=("1", "2"), - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, ) projection = _projection( storage_plan, invocation_scope=invocation_scope, producer_selection_scope=storage_plan.producer_group_scope(), - consumer_variable_components=(AllComponents.SITE,), + consumer_variable_components=(Microscopy.Site,), ) projection.validate_axis_projection(storage_plan) @@ -62,13 +63,13 @@ def test_dynamic_producer_coordinate_requires_matching_invocation_dispatch() -> path="/memory/objects.pkl", artifact_type=ObjectLabelsArtifactType, group_keys=(None,), - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, ) projection = _projection( storage_plan, - invocation_scope=ComponentGroupScope.dynamic(AllComponents.SITE), - producer_selection_scope=ComponentGroupScope.dynamic(AllComponents.CHANNEL), - consumer_variable_components=(AllComponents.TIMEPOINT,), + invocation_scope=ComponentGroupScope.dynamic(Microscopy.Site), + producer_selection_scope=ComponentGroupScope.dynamic(Microscopy.Channel), + consumer_variable_components=(Microscopy.Timepoint,), ) with pytest.raises(ValueError, match="not owned by invocation scope"): @@ -83,10 +84,10 @@ def test_existing_producer_stack_is_retained_when_consumer_relabels_third_axis() path="/memory/objects.pkl", artifact_type=ObjectLabelsArtifactType, group_keys=("1",), - group_component=AllComponents.CHANNEL, - variable_components=(AllComponents.SITE,), + group_component=Microscopy.Channel, + variable_components=(Microscopy.Site,), ) - consumer_components = ComponentSet((AllComponents.TIMEPOINT,)) + consumer_components = ComponentSet((Microscopy.Timepoint,)) projection = _projection( storage_plan, invocation_scope=ComponentGroupScope.ungrouped(), @@ -111,8 +112,8 @@ def test_scalar_consumer_requires_coordinate_for_each_producer_stack_component() path="/memory/objects.pkl", artifact_type=ObjectLabelsArtifactType, group_keys=("1",), - group_component=AllComponents.CHANNEL, - variable_components=(AllComponents.SITE,), + group_component=Microscopy.Channel, + variable_components=(Microscopy.Site,), ) projection = _projection( storage_plan, @@ -130,15 +131,15 @@ def test_transposed_producer_group_axis_requires_old_stack_coordinate() -> None: path="/memory/image.pkl", artifact_type=ImageArtifactType, group_keys=("1", "2"), - group_component=AllComponents.CHANNEL, - variable_components=(AllComponents.SITE,), + group_component=Microscopy.Channel, + variable_components=(Microscopy.Site,), ) - consumer_components = ComponentSet((AllComponents.CHANNEL,)) + consumer_components = ComponentSet((Microscopy.Channel,)) projection = _projection( storage_plan, - invocation_scope=ComponentGroupScope.dynamic(AllComponents.CHANNEL), + invocation_scope=ComponentGroupScope.dynamic(Microscopy.Channel), producer_selection_scope=storage_plan.producer_group_scope(), - component_scopes=(ComponentGroupScope.dynamic(AllComponents.CHANNEL),), + component_scopes=(ComponentGroupScope.dynamic(Microscopy.Channel),), consumer_variable_components=consumer_components.as_tuple(), ) @@ -158,20 +159,20 @@ def test_transposed_producer_stack_rejects_multi_coordinate_projection() -> None path="/memory/image.pkl", artifact_type=ImageArtifactType, group_keys=("1", "2"), - group_component=AllComponents.CHANNEL, - variable_components=(AllComponents.SITE,), + group_component=Microscopy.Channel, + variable_components=(Microscopy.Site,), ) projection = _projection( storage_plan, - invocation_scope=ComponentGroupScope.dynamic(AllComponents.CHANNEL), + invocation_scope=ComponentGroupScope.dynamic(Microscopy.Channel), producer_selection_scope=storage_plan.producer_group_scope(), component_scopes=( ComponentGroupScope.from_raw( ("1", "2", "3"), - component=AllComponents.SITE, + component=Microscopy.Site, ), ), - consumer_variable_components=(AllComponents.CHANNEL,), + consumer_variable_components=(Microscopy.Channel,), ) with pytest.raises(ValueError, match="site.*not a single exact coordinate"): diff --git a/tests/unit/test_artifact_publication_journey.py b/tests/unit/test_artifact_publication_journey.py index 99268e1100..d304bc6a3b 100644 --- a/tests/unit/test_artifact_publication_journey.py +++ b/tests/unit/test_artifact_publication_journey.py @@ -9,7 +9,7 @@ import tifffile from polystore.virtual_workspace import SourcePixelRef -from openhcs.constants.constants import GroupBy, VariableComponents, Microscope +from openhcs.constants.constants import Microscope from openhcs.core.config import ( LazyPathPlanningConfig, PipelineConfig, @@ -50,6 +50,7 @@ ImageMode, convert_objects_to_image, ) +from openhcs.domains.microscopy.axes import Microscopy @artifact_outputs(ArtifactSpec.output("objects", ObjectLabelsArtifactType)) @@ -96,7 +97,7 @@ def _plate(root: Path, site_count: int = 1) -> Path: for site in range(1, site_count + 1): path = root / f"A01_s{site:03d}_w1_z001_t001.tif" tifffile.imwrite(path, pixels) - address = OpenHCSPlaneAddress.from_values("A01", site, 1, 1, 1) + address = OpenHCSPlaneAddress(((Microscopy.Well, "A01"), (Microscopy.Site, site), (Microscopy.Channel, 1), (Microscopy.ZIndex, 1), (Microscopy.Timepoint, 1))) metadata = ImagePayloadMetadata( source_path=str(path), source_component_metadata={**address.as_component_metadata(), "extension": ".tif"}, @@ -129,8 +130,8 @@ def _compile(root: Path, results: Path, main_filter=0): materialization_results_path=results, path_planning_config=LazyPathPlanningConfig(output_dir_suffix="_out", well_filter=main_filter), processing_config=LazyProcessingConfig( - group_by=GroupBy.CHANNEL, - variable_components=[VariableComponents.SITE], + group_by=Microscopy.Channel, + variable_components=[Microscopy.Site], ), num_workers=1, use_threading=True, @@ -183,7 +184,7 @@ def test_converted_checkpoint_has_typed_address_on_final_reconciliation(tmp_path reopened_metadata = orchestrator.microscope_handler.metadata_handler.load_metadata_document(saved.parent) reopened = VirtualWorkspaceSourceProjection.from_openhcs_metadata(saved.parent, reopened_metadata) retained = reopened.source_projections_by_virtual_path[projection["virtual_path"]] - assert retained.address == OpenHCSPlaneAddress.from_values("A01", 1, 1, 1, 1) + assert retained.address == OpenHCSPlaneAddress(((Microscopy.Well, "A01"), (Microscopy.Site, 1), (Microscopy.Channel, 1), (Microscopy.ZIndex, 1), (Microscopy.Timepoint, 1))) assert retained.image_metadata.source_voxel_spacing == SourceVoxelSpacing((0.65, 0.65)) assert retained.image_metadata.source_path == projected_metadata.source_path if main_filter: diff --git a/tests/unit/test_automatic_image_role_materialization_435.py b/tests/unit/test_automatic_image_role_materialization_435.py index a05b2eaf0f..4526b26f59 100644 --- a/tests/unit/test_automatic_image_role_materialization_435.py +++ b/tests/unit/test_automatic_image_role_materialization_435.py @@ -12,7 +12,7 @@ from polystore.memory import MemoryStorageBackend from test_function_outputs import context_stub, function_step_plan, record_output_path -from openhcs.constants.constants import Backend, Microscope, VariableComponents +from openhcs.constants.constants import Backend, Microscope from openhcs.core.aligned_image_payload import AlignedImageSliceContext, ImagePayloadBundleContext from openhcs.core.artifacts import ArtifactOutputPlan, ArtifactSpec, ImageArtifactType from openhcs.core.compiled_step_plan import RuntimeArtifactMaterializationPlan @@ -31,6 +31,7 @@ PrimaryImageMetadataTarget, ) from openhcs.microscopes.source_schema import SourceSchemaFilenameParser +from openhcs.domains.microscopy.axes import Microscopy @pytest.mark.parametrize("plane_count", (1, 2)) @@ -46,7 +47,7 @@ def test_automatic_two_role_images_publish_their_actual_saved_occurrences(tmp_pa context.tiff_config = None plan = function_step_plan( "Declared raw and capped roles", - variable_components=((VariableComponents.Z_INDEX,) if plane_count > 1 else ()), + variable_components=((Microscopy.ZIndex,) if plane_count > 1 else ()), ) plan.streaming_configs = {} plan.write_backend = Backend.DISK.value @@ -189,7 +190,7 @@ def test_retained_role_policy_preserves_authored_and_unnamed_image_paths(tmp_pat outputs = materialization_outputs( spec, value, str(tmp_path / "AuthoredBase"), filemanager, context=context, output_plan=output_plan, - variable_components=(VariableComponents.Z_INDEX,), + variable_components=(Microscopy.ZIndex,), ) expected_paths = ( ("authored/plane_1.tif", "authored/plane_2.tif") if purpose.endswith("template") @@ -234,7 +235,7 @@ def test_retained_image_qualifier_respects_complete_writer_suffix(tmp_path, suff manager = FileManager({Backend.MEMORY.value: MemoryStorageBackend()}) context = context_stub(manager, parser=SourceSchemaFilenameParser()) - plan = function_step_plan("Retained format role", variable_components=(VariableComponents.Z_INDEX,) if plane_count > 1 else ()) + plan = function_step_plan("Retained format role", variable_components=(Microscopy.ZIndex,) if plane_count > 1 else ()) plan.output_dir = tmp_path / "images" plan.analysis_results_dir = str(plan.output_dir) output_plan = ArtifactOutputPlan( diff --git a/tests/unit/test_axis_family_guards.py b/tests/unit/test_axis_family_guards.py new file mode 100644 index 0000000000..2e04e94784 --- /dev/null +++ b/tests/unit/test_axis_family_guards.py @@ -0,0 +1,121 @@ +"""G1 guards: the axis family is the only axis identity, and the kernel names no member.""" + +from __future__ import annotations + +import ast +from pathlib import Path + +import openhcs +from openhcs.core.axes import AxisFamily +from openhcs.domains.microscopy.axes import Microscopy + +REPO_ROOT = Path(openhcs.__file__).resolve().parents[1] + +DELETED_NAMES = frozenset( + { + "AllComponents", + "VariableComponents", + "SequentialComponents", + "StreamingComponents", + "GroupBy", + "get_openhcs_config", + "_ComponentTemplate", + "ComponentConfiguration", + "ComponentConfigurationFactory", + "MULTIPROCESSING_AXIS", + "DEFAULT_GROUP_BY", + "DEFAULT_VARIABLE_COMPONENTS", + "get_default_group_by", + "get_default_variable_components", + "get_multiprocessing_axis", + "convert_enum_by_value", + } +) + +# Domain modules may name microscopy members. P moves them under openhcs/domains/. +DOMAIN_MODULE_PREFIXES = ( + "openhcs/domains/", + "openhcs/microscopes/", + "openhcs/processing/presets/", + "openhcs/demo/", + "openhcs/mcp/installed_demo.py", +) +# The product package root is the microscopy distribution's entry point. +DOMAIN_ENTRY_POINT = "openhcs/__init__.py" + + +def _python_files(*roots: str) -> list[Path]: + files: list[Path] = [] + for root in roots: + base = REPO_ROOT / root + files.extend( + path for path in base.rglob("*.py") if "benchmark/results" not in path.as_posix() + ) + return files + + +def _relative(path: Path) -> str: + return path.relative_to(REPO_ROOT).as_posix() + + +def _identifiers(tree: ast.AST) -> set[str]: + names: set[str] = set() + for node in ast.walk(tree): + if isinstance(node, ast.Name): + names.add(node.id) + elif isinstance(node, ast.Attribute): + names.add(node.attr) + elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)): + names.add(node.name) + elif isinstance(node, ast.alias): + names.add(node.asname or node.name.rsplit(".", 1)[-1]) + return names + + +def test_deleted_component_enums_and_factory_do_not_exist() -> None: + offenders = { + _relative(path): sorted(DELETED_NAMES & _identifiers(ast.parse(path.read_text()))) + for path in _python_files("openhcs", "tests", "benchmark", "scripts") + if path.name != Path(__file__).name + } + assert {path: names for path, names in offenders.items() if names} == {} + assert not (REPO_ROOT / "openhcs/core/components/framework.py").exists() + + +def test_kernel_modules_name_no_microscopy_member() -> None: + member_names = {axis.__name__ for axis in Microscopy.axes} | {Microscopy.__name__} + offenders: dict[str, list[str]] = {} + for path in _python_files("openhcs"): + relative = _relative(path) + if relative.startswith(DOMAIN_MODULE_PREFIXES) or relative == DOMAIN_ENTRY_POINT: + continue + tree = ast.parse(path.read_text()) + found: set[str] = set() + for node in ast.walk(tree): + if isinstance(node, ast.ImportFrom) and (node.module or "").startswith( + "openhcs.domains" + ): + found.add(f"import {node.module}") + elif isinstance(node, ast.Import): + found.update( + f"import {alias.name}" + for alias in node.names + if alias.name.startswith("openhcs.domains") + ) + elif isinstance(node, ast.Attribute) and node.attr in member_names: + found.add(f".{node.attr}") + elif isinstance(node, ast.Name) and node.id == Microscopy.__name__: + found.add(node.id) + elif ( + isinstance(node, ast.Constant) + and isinstance(node.value, str) + and node.value.startswith("openhcs.domains") + ): + found.add(repr(node.value)) + if found: + offenders[relative] = sorted(found) + assert offenders == {} + + +def test_product_entry_point_activates_microscopy() -> None: + assert AxisFamily.active() is Microscopy diff --git a/tests/unit/test_axis_family_witness.py b/tests/unit/test_axis_family_witness.py new file mode 100644 index 0000000000..787c388d77 --- /dev/null +++ b/tests/unit/test_axis_family_witness.py @@ -0,0 +1,167 @@ +"""Witness: a second, non-microscopy family needs only its declaration. + +A remote-sensing family (scene, tile, band, date; no stack axis) is declared +here and activated in-process. Family queries, configuration defaults and +validation, viewer mode projection, plane filenames and the compiler's +axis resolution all follow it without kernel edits. +""" + +from __future__ import annotations + +from collections.abc import Iterator + +import pytest + +from openhcs.core.axes import ( + Axis, + AxisFamily, + ColourAxis, + DefaultGroupBy, + DefaultVariable, + LabelValued, + OrdinalValued, + PartitionAxis, + StackAxis, + TileAxis, + TimeAxis, + Ungrouped, +) +from openhcs.domains.microscopy.axes import Microscopy + + +class RemoteSensing(AxisFamily): + class Tile(Axis, TileAxis, DefaultVariable, OrdinalValued): + name = "tile" + filename_prefix = "f" + filename_padding = 3 + + class Band(Axis, ColourAxis, DefaultGroupBy, OrdinalValued): + name = "band" + filename_prefix = "b" + + class Date(Axis, TimeAxis, OrdinalValued): + name = "date" + filename_prefix = "d" + filename_padding = 3 + + class Scene(Axis, PartitionAxis, LabelValued): + name = "scene" + + +@pytest.fixture +def remote_sensing() -> Iterator[type[RemoteSensing]]: + RemoteSensing.activate() + try: + yield RemoteSensing + finally: + Microscopy.activate() + + +def test_family_queries_follow_the_declaration(remote_sensing) -> None: + family = AxisFamily.active() + assert family is RemoteSensing + assert family.partition_axis() is RemoteSensing.Scene + assert family.variable_axes() == ( + RemoteSensing.Tile, + RemoteSensing.Band, + RemoteSensing.Date, + ) + assert family.with_role(StackAxis) == () + assert family.default_variable() == (RemoteSensing.Tile,) + assert family.default_group_by() is RemoteSensing.Band + assert family.named("date") is RemoteSensing.Date + assert family.grouping_named("none") is Ungrouped + + +def test_configuration_derives_from_the_active_family(remote_sensing) -> None: + from openhcs.core.config import ( + FijiDisplayConfig, + NapariDisplayConfig, + ProcessingConfig, + SequentialProcessingConfig, + ) + + config = ProcessingConfig() + assert config.variable_components == [RemoteSensing.Tile] + assert config.group_by is RemoteSensing.Band + with pytest.raises(ValueError, match="variable_components"): + ProcessingConfig(variable_components=[RemoteSensing.Scene]) + with pytest.raises(ValueError, match="sequential_components"): + SequentialProcessingConfig(sequential_components=[Microscopy.Channel]) + + fiji = FijiDisplayConfig() + assert fiji.COMPONENT_ORDER == ("tile", "band", "date", "scene") + assert fiji.component_modes() == { + "tile": "frame", + "band": "channel", + "date": "frame", + "scene": "frame", + } + assert set(NapariDisplayConfig().component_modes()) == set(RemoteSensing.names()) + payload = {"component_modes": fiji.component_modes(), "lut": "Grays", "auto_contrast": True} + assert FijiDisplayConfig.from_display_payload(payload) == fiji + + +def test_plane_addresses_spell_the_declared_tokens(remote_sensing) -> None: + from openhcs.core.source_projection import OpenHCSPlaneAddress + + parsed = OpenHCSPlaneAddress.from_filename("S07_f002_b3_d014.tif") + assert parsed is not None + assert parsed.address.value_for(RemoteSensing.Scene) == "S07" + assert parsed.address.value_for(RemoteSensing.Band) == "3" + assert parsed.address.filename(".tif") == "S07_f002_b3_d014.tif" + + +def test_step_validation_and_compiler_axis_resolution(remote_sensing) -> None: + from openhcs.core.components.validation import GenericValidator + from openhcs.core.pipeline.path_planner import ( + PathPlannerComponentScopes, + PathPlannerExecutionGroups, + ) + + validator = GenericValidator(AxisFamily.active()) + assert validator.validate_step([RemoteSensing.Tile], RemoteSensing.Band, True, "s").is_valid + rejected = validator.validate_step([RemoteSensing.Band], RemoteSensing.Band, True, "s") + assert not rejected.is_valid + partition = validator.validate_step([RemoteSensing.Scene], Ungrouped, False, "s") + assert "multiprocessing axis: scene" in partition.error_message + + assert ( + PathPlannerComponentScopes.component_from_group_by(RemoteSensing.Date) + is RemoteSensing.Date + ) + assert PathPlannerComponentScopes.component_from_group_by(Ungrouped) is None + assert ( + PathPlannerExecutionGroups.execution_component_for_dict_pattern( + RemoteSensing.Band, "step" + ) + is RemoteSensing.Band + ) + with pytest.raises(ValueError, match="dict function pattern"): + PathPlannerExecutionGroups.execution_component_for_dict_pattern(Ungrouped, "s") + + +def test_family_declaration_enforces_role_cardinality() -> None: + with pytest.raises(TypeError, match="PartitionAxis"): + + class _TwoPartitions(AxisFamily): + class A(Axis, PartitionAxis, LabelValued): + name = "a" + + class B(Axis, PartitionAxis, LabelValued): + name = "b" + + with pytest.raises(TypeError, match="exactly one PartitionAxis"): + + class _NoPartition(AxisFamily): + class A(Axis, TileAxis, OrdinalValued): + name = "a" + + with pytest.raises(TypeError, match="value kind|AxisValueKind"): + + class _NoKind(Axis, TileAxis): + name = "x" + + # A rejected declaration must not leak into other axes' role checks. + assert not issubclass(Microscopy.Channel, TileAxis) + assert not issubclass(RemoteSensing.Band, PartitionAxis) diff --git a/tests/unit/test_basicpy_acquisition_fixture.py b/tests/unit/test_basicpy_acquisition_fixture.py index 04cea48e5f..c5afb06611 100644 --- a/tests/unit/test_basicpy_acquisition_fixture.py +++ b/tests/unit/test_basicpy_acquisition_fixture.py @@ -3,7 +3,6 @@ import numpy as np import pytest -from openhcs.constants import AllComponents from openhcs.core.image_file_serialization import ImageFileFormat from openhcs.microscopes.imagexpress import ImageXpressHandler @@ -14,6 +13,7 @@ from tests.diagnostics.basicpy_observation_fixture import shaded_observations from tests.diagnostics.create_basicpy_acquisition_fixture import create_acquisition +from openhcs.domains.microscopy.axes import Microscopy def test_saved_numerical_control_has_real_independent_site_calibration(tmp_path): @@ -29,9 +29,9 @@ def test_saved_numerical_control_has_real_independent_site_calibration(tmp_path) for path, expected in zip(files, observations, strict=True): parsed = handler.parser.parse_filename(path.name) assert parsed is not None - sites.append(parsed.required_value(AllComponents.SITE)) - assert parsed.required_value(AllComponents.CHANNEL) == 1 - assert parsed.required_value(AllComponents.Z_INDEX) == 1 + sites.append(parsed.required_value(Microscopy.Site)) + assert parsed.required_value(Microscopy.Channel) == 1 + assert parsed.required_value(Microscopy.ZIndex) == 1 np.testing.assert_array_equal(ImageFileFormat.require_path(path).read(path), expected) assert sites == list(range(1, 25)) np.testing.assert_array_equal( diff --git a/tests/unit/test_bioformats_java_adapter.py b/tests/unit/test_bioformats_java_adapter.py index 9620892a8f..b546567bc7 100644 --- a/tests/unit/test_bioformats_java_adapter.py +++ b/tests/unit/test_bioformats_java_adapter.py @@ -6,7 +6,7 @@ import pytest import tifffile -from openhcs.constants.constants import AllComponents, Backend +from openhcs.constants.constants import Backend from openhcs.microscopes.bioformats_adapter import ( BioFormatsContainerOpenError, BioFormatsDatasetAmbiguityError, @@ -17,6 +17,7 @@ from polystore.bioformats_java import BioFormatsOpenedReader, BioFormatsJavaContext from polystore.bioformats_java import sample_bioformats_plane from polystore.base import ImageSamplingRequest +from openhcs.domains.microscopy.axes import Microscopy class JavaValue: @@ -698,14 +699,14 @@ def test_java_adapter_projects_one_czi_ome_spw_metadata( assert dataset.identity.value == "Plate:0" assert dataset.pixel_size == 0.65 assert [ - candidate.declared_address.value_for(AllComponents.CHANNEL) + candidate.declared_address.value_for(Microscopy.Channel) for candidate in dataset.candidates ] == [ "1", "2", ] assert { - candidate.declared_address.value_for(AllComponents.WELL) + candidate.declared_address.value_for(Microscopy.Well) for candidate in dataset.candidates } == {"A01"} assert [ @@ -779,7 +780,7 @@ def test_java_adapter_aggregates_independent_czi_containers_with_one_plate_id( assert dataset.identity.value == "Plate:0" assert len(dataset.candidates) == 4 assert { - candidate.declared_address.value_for(AllComponents.WELL) + candidate.declared_address.value_for(Microscopy.Well) for candidate in dataset.candidates } == { "A01", @@ -827,14 +828,14 @@ def getPlateCount(self): assert dataset.identity.value == tmp_path.resolve().as_uri() assert { - candidate.declared_address.value_for(AllComponents.WELL) + candidate.declared_address.value_for(Microscopy.Well) for candidate in dataset.candidates } == { "sample-a.czi", "sample-b.czi", } assert { - candidate.declared_address.value_for(AllComponents.SITE) + candidate.declared_address.value_for(Microscopy.Site) for candidate in dataset.candidates } == {"1"} assert { diff --git a/tests/unit/test_bioformats_microscope_handler.py b/tests/unit/test_bioformats_microscope_handler.py index 49c3942b03..741a9b0576 100644 --- a/tests/unit/test_bioformats_microscope_handler.py +++ b/tests/unit/test_bioformats_microscope_handler.py @@ -6,7 +6,7 @@ from polystore.virtual_workspace import SourcePixelRef from objectstate.lazy_factory import ensure_global_config_context -from openhcs.constants.constants import AllComponents, Backend +from openhcs.constants.constants import Backend from openhcs.core.config import GlobalPipelineConfig from openhcs.core.orchestrator.orchestrator import PipelineOrchestrator from openhcs.core.source_workspace_projection import ( @@ -26,6 +26,7 @@ bioformats_filemanager, write_bioformats_manifest_fixture, ) +from openhcs.domains.microscopy.axes import Microscopy def test_bioformats_handler_writes_normalized_workspace_metadata( @@ -241,14 +242,14 @@ def test_bioformats_metadata_handler_reports_component_values(tmp_path: Path) -> assert handler.get_grid_dimensions(tmp_path) == (1, 1) assert handler.get_pixel_size(tmp_path) == 0.5 component_values = handler.component_value_set(tmp_path) - assert component_values.values_for(AllComponents.CHANNEL) == { + assert component_values.values_for(Microscopy.Channel) == { "1": "DAPI", "2": "GFP", } - assert component_values.values_for(AllComponents.WELL) == {"A01": "A01"} - assert component_values.values_for(AllComponents.SITE) == {"1": None} - assert component_values.values_for(AllComponents.Z_INDEX) == {"1": None} - assert component_values.values_for(AllComponents.TIMEPOINT) == {"1": None} + assert component_values.values_for(Microscopy.Well) == {"A01": "A01"} + assert component_values.values_for(Microscopy.Site) == {"1": None} + assert component_values.values_for(Microscopy.ZIndex) == {"1": None} + assert component_values.values_for(Microscopy.Timepoint) == {"1": None} def test_bioformats_auto_detection_is_late_fallback(tmp_path: Path) -> None: diff --git a/tests/unit/test_bioformats_preparation_selection.py b/tests/unit/test_bioformats_preparation_selection.py index 2153a60d86..95640af2b2 100644 --- a/tests/unit/test_bioformats_preparation_selection.py +++ b/tests/unit/test_bioformats_preparation_selection.py @@ -9,7 +9,7 @@ from objectstate.lazy_factory import ensure_global_config_context from polystore.bioformats_java import BioFormatsJavaContext -from openhcs.constants.constants import AllComponents, Microscope +from openhcs.constants.constants import Microscope from openhcs.core.config import ( GlobalPipelineConfig, LazySourceBindingsConfig, @@ -34,6 +34,7 @@ FakeBioFormatsContext, FakeBioFormatsMetadata, ) +from openhcs.domains.microscopy.axes import Microscopy def _file_filter(name): @@ -112,7 +113,7 @@ def counted_open(path): ).initialize() assert orchestrator.is_initialized() assert opened == [names[7]] * (2 if entrypoint == "auto_orchestrator" else 1) - assert len(orchestrator.get_component_keys(AllComponents.WELL)) == 1 + assert len(orchestrator.get_component_keys(Microscopy.Well)) == 1 workspace = json.loads((tmp_path / "openhcs_metadata.json").read_text()) mapping = workspace["subdirectories"]["."]["workspace_mapping"] assert len(mapping) == 2 diff --git a/tests/unit/test_bioformats_spw_projector.py b/tests/unit/test_bioformats_spw_projector.py index da1fb597ec..c3302a1564 100644 --- a/tests/unit/test_bioformats_spw_projector.py +++ b/tests/unit/test_bioformats_spw_projector.py @@ -2,7 +2,6 @@ import pytest -from openhcs.constants.constants import AllComponents from openhcs.core.source_projection import OpenHCSPlaneAddress from openhcs.core.source_metadata import SourceVoxelSpacing from openhcs.microscopes.bioformats_adapter import ( @@ -15,6 +14,7 @@ BioFormatsWell, BioFormatsWellSample, ) +from openhcs.domains.microscopy.axes import Microscopy def _image( @@ -80,10 +80,10 @@ def test_store_metadata_emits_exact_plate_planes(tmp_path: Path) -> None: assert dataset.identity.value == "Plate:0" assert [candidate.declared_address for candidate in dataset.candidates] == [ - OpenHCSPlaneAddress.from_values("A02", "3", "1", "1", "1"), - OpenHCSPlaneAddress.from_values("A02", "3", "2", "1", "1"), - OpenHCSPlaneAddress.from_values("A02", "3", "1", "1", "2"), - OpenHCSPlaneAddress.from_values("A02", "3", "2", "1", "2"), + OpenHCSPlaneAddress(((Microscopy.Well, "A02"), (Microscopy.Site, "3"), (Microscopy.Channel, "1"), (Microscopy.ZIndex, "1"), (Microscopy.Timepoint, "1"))), + OpenHCSPlaneAddress(((Microscopy.Well, "A02"), (Microscopy.Site, "3"), (Microscopy.Channel, "2"), (Microscopy.ZIndex, "1"), (Microscopy.Timepoint, "1"))), + OpenHCSPlaneAddress(((Microscopy.Well, "A02"), (Microscopy.Site, "3"), (Microscopy.Channel, "1"), (Microscopy.ZIndex, "1"), (Microscopy.Timepoint, "2"))), + OpenHCSPlaneAddress(((Microscopy.Well, "A02"), (Microscopy.Site, "3"), (Microscopy.Channel, "2"), (Microscopy.ZIndex, "1"), (Microscopy.Timepoint, "2"))), ] @@ -98,14 +98,14 @@ def test_nonplate_images_map_to_distinct_well_samples(tmp_path: Path) -> None: ).source_dataset() assert [ - candidate.declared_address.value_for(AllComponents.WELL) + candidate.declared_address.value_for(Microscopy.Well) for candidate in dataset.candidates ] == [ "Image%3Asample-a.npy", "Image%3Asample-b.npy", ] assert [ - candidate.declared_address.value_for(AllComponents.SITE) + candidate.declared_address.value_for(Microscopy.Site) for candidate in dataset.candidates ] == [ "1", @@ -126,8 +126,8 @@ def test_one_nonplate_czi_maps_many_scenes_to_exact_series_sites( assert dataset.identity.value == tmp_path.resolve().as_uri() assert [candidate.declared_address for candidate in dataset.candidates] == [ - OpenHCSPlaneAddress.from_values("many-scenes.czi", "1", "1", "1", "1"), - OpenHCSPlaneAddress.from_values("many-scenes.czi", "4", "1", "1", "1"), + OpenHCSPlaneAddress(((Microscopy.Well, "many-scenes.czi"), (Microscopy.Site, "1"), (Microscopy.Channel, "1"), (Microscopy.ZIndex, "1"), (Microscopy.Timepoint, "1"))), + OpenHCSPlaneAddress(((Microscopy.Well, "many-scenes.czi"), (Microscopy.Site, "4"), (Microscopy.Channel, "1"), (Microscopy.ZIndex, "1"), (Microscopy.Timepoint, "1"))), ] assert { candidate.store_identity.container_key for candidate in dataset.candidates @@ -174,9 +174,9 @@ def test_one_plate_czi_preserves_many_wells_and_sparse_sample_indexes( assert dataset.identity.value == "Plate:many-samples" assert [candidate.declared_address for candidate in dataset.candidates] == [ - OpenHCSPlaneAddress.from_values("A01", "1", "1", "1", "1"), - OpenHCSPlaneAddress.from_values("A01", "5", "1", "1", "1"), - OpenHCSPlaneAddress.from_values("B02", "10", "1", "1", "1"), + OpenHCSPlaneAddress(((Microscopy.Well, "A01"), (Microscopy.Site, "1"), (Microscopy.Channel, "1"), (Microscopy.ZIndex, "1"), (Microscopy.Timepoint, "1"))), + OpenHCSPlaneAddress(((Microscopy.Well, "A01"), (Microscopy.Site, "5"), (Microscopy.Channel, "1"), (Microscopy.ZIndex, "1"), (Microscopy.Timepoint, "1"))), + OpenHCSPlaneAddress(((Microscopy.Well, "B02"), (Microscopy.Site, "10"), (Microscopy.Channel, "1"), (Microscopy.ZIndex, "1"), (Microscopy.Timepoint, "1"))), ] assert { candidate.store_identity.sample_group_id for candidate in dataset.candidates diff --git a/tests/unit/test_callable_contract.py b/tests/unit/test_callable_contract.py index 5d29754c90..b3cb98fe36 100644 --- a/tests/unit/test_callable_contract.py +++ b/tests/unit/test_callable_contract.py @@ -10,7 +10,6 @@ from metaclass_registry import AutoRegisterMeta from python_introspect import parameter_exclusions -from openhcs.constants.constants import VariableComponents from openhcs.core.aligned_image_payload import ImagePayloadExecutionMode from openhcs.core.autoregister_preparation import AutoRegisterRegistryPreparation from openhcs.core.callable_contract import ( @@ -42,7 +41,7 @@ from openhcs.core.memory.decorators import numpy from openhcs.core.pipeline.artifact_planning import extract_artifact_declarations from openhcs.core.pipeline.function_contracts import ( - required_variable_components, + required_axis_roles, runtime_bound_parameters, special_inputs, ) @@ -55,6 +54,8 @@ ) from openhcs.processing.backends.lib_registry.cupy_registry import CupyRegistry from openhcs.processing.backends.lib_registry.unified_registry import ProcessingContract +from openhcs.core.axes import TimeAxis +from openhcs.domains.microscopy.axes import Microscopy _AUTOREGISTER_PREPARED_TEST_FAMILY_CALLS = 0 @@ -391,17 +392,17 @@ def process(image, *, context: ProcessingContext): ) -def test_callable_contract_reads_required_variable_components() -> None: - @required_variable_components(VariableComponents.TIMEPOINT) +def test_callable_contract_reads_required_axis_roles() -> None: + @required_axis_roles(TimeAxis) def process(image): return image contract = CallableContract.from_callable(process) - assert contract.required_variable_components == (VariableComponents.TIMEPOINT,) + assert contract.required_axis_roles == (TimeAxis,) assert CallableMetadata.from_callable(process).as_namespace()[ - FunctionContractAttribute.required_variable_components - ] == (VariableComponents.TIMEPOINT,) + FunctionContractAttribute.required_axis_roles + ] == (TimeAxis,) def test_callable_contract_reads_runtime_image_execution_mode_from_function_reference() -> ( diff --git a/tests/unit/test_cellprofiler_analyst_export.py b/tests/unit/test_cellprofiler_analyst_export.py index 839af3a54c..9a466ebe1e 100644 --- a/tests/unit/test_cellprofiler_analyst_export.py +++ b/tests/unit/test_cellprofiler_analyst_export.py @@ -11,7 +11,6 @@ import pytest from PIL import Image -from openhcs.constants.constants import AllComponents from openhcs.core.artifacts import ( ObjectLabelsArtifactType, ArtifactOutputPlan, @@ -100,6 +99,7 @@ ) from openhcs.processing.materialization import FileBundleOptions from openhcs.core.runtime_artifact_values import RuntimeValue +from openhcs.domains.microscopy.axes import Microscopy AXIS_ID = "A01_s1" RUNTIME_IMAGE_FIELD = MeasurementRowAxisField.SLICE_INDEX.value @@ -678,7 +678,7 @@ def test_projection_adds_common_typed_source_provenance_to_image_rows() -> None: input_specs=(dna, rna, measurements), records_by_axis={AXIS_ID: store.values()}, source_image_set_identity_policy=SourceImageSetIdentityPolicy( - frozenset((AllComponents.CHANNEL,)) + frozenset((Microscopy.Channel,)) ), ) @@ -858,13 +858,13 @@ def _borrowed_source_export_fixture( sources.extend( ( SourcePlaneProjection( - address=OpenHCSPlaneAddress.from_values("A01", site, 1, 1, 1), + address=OpenHCSPlaneAddress(((Microscopy.Well, "A01"), (Microscopy.Site, site), (Microscopy.Channel, 1), (Microscopy.ZIndex, 1), (Microscopy.Timepoint, 1))), ref=SourcePixelRef("disk", str(original)), source_alias="DNA", source_metadata=metadata, ), SourceArtifactProjection( - address=OpenHCSPlaneAddress.from_values("A01", site, 2, 1, 1), + address=OpenHCSPlaneAddress(((Microscopy.Well, "A01"), (Microscopy.Site, site), (Microscopy.Channel, 2), (Microscopy.ZIndex, 1), (Microscopy.Timepoint, 1))), ref=SourcePixelRef( "disk", str(calibration), (site - 1,) if embedded_tiff else () ), @@ -944,7 +944,7 @@ def _borrowed_source_export_fixture( ), records_by_axis={"A01": store.values()}, source_image_set_identity_policy=SourceImageSetIdentityPolicy( - frozenset((AllComponents.CHANNEL,)) + frozenset((Microscopy.Channel,)) ), source_binding_plan=plan, ) @@ -1132,7 +1132,7 @@ def test_measurement_provenance_projects_exact_named_contributors_by_site( ), records_by_axis={AXIS_ID: store.values()}, source_image_set_identity_policy=SourceImageSetIdentityPolicy( - frozenset((AllComponents.CHANNEL,)) + frozenset((Microscopy.Channel,)) ), ) channels = tuple( diff --git a/tests/unit/test_cellprofiler_artifact_declarations.py b/tests/unit/test_cellprofiler_artifact_declarations.py index fb9a9f8c32..228a84a9aa 100644 --- a/tests/unit/test_cellprofiler_artifact_declarations.py +++ b/tests/unit/test_cellprofiler_artifact_declarations.py @@ -13,7 +13,6 @@ from objectstate.lazy_factory import ensure_global_config_context from objectstate.object_state import ObjectState from objectstate.object_state_registry import ObjectStateRegistry -from openhcs.constants.constants import AllComponents, GroupBy from openhcs.constants.input_source import InputSource from openhcs.core.artifacts import ( ArtifactInputPlan, @@ -85,6 +84,7 @@ from openhcs.processing.backends.cellprofiler.texture import MeasureTextureModule from openhcs.processing.backends.cellprofiler.outlines import OverlayObjectsModule from openhcs.processing.backends.cellprofiler.morphology import MaskObjectsModule +from openhcs.domains.microscopy.axes import Microscopy def _module( @@ -625,11 +625,11 @@ def test_calculate_math_retains_measurement_subjects_across_producer_channels() path="/memory/intensity.pkl", artifact_type=MeasurementsArtifactType, group_keys=("2", "1"), - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, ) assert ArtifactInputProjectionPlan.declared_producer_selection_scope( measurement_input, storage - ) == ComponentGroupScope.from_raw(("2", "1"), component=AllComponents.CHANNEL) + ) == ComponentGroupScope.from_raw(("2", "1"), component=Microscopy.Channel) def test_declarations_carry_cross_step_object_and_measurement_flow() -> None: @@ -801,7 +801,7 @@ def test_primary_source_binding_resolves_the_exact_module_input() -> None: source_binding = NamedSourceBinding( alias=source_image.name, artifact_kind=ImageArtifactType, - component_identity=(ComponentSelector(AllComponents.CHANNEL, "2"),), + component_identity=(ComponentSelector(Microscopy.Channel, "2"),), ) contract = module_type.callable_contract( @@ -817,7 +817,7 @@ def test_primary_source_binding_resolves_the_exact_module_input() -> None: enabled=True, bindings=(source_binding,), ), - group_by=GroupBy.CHANNEL, + group_by=Microscopy.Channel, available_artifacts=ArtifactSpecCollection((source_image,)), main_flow_artifacts=ArtifactSpecCollection((source_image,)), ), @@ -858,12 +858,12 @@ def test_primary_source_binding_rejects_a_different_channel_group() -> None: alias=source_image.name, artifact_kind=ImageArtifactType, component_identity=( - ComponentSelector(AllComponents.CHANNEL, "2"), + ComponentSelector(Microscopy.Channel, "2"), ), ), ), ), - group_by=GroupBy.CHANNEL, + group_by=Microscopy.Channel, available_artifacts=ArtifactSpecCollection((source_image,)), main_flow_artifacts=ArtifactSpecCollection((source_image,)), ), @@ -873,22 +873,22 @@ def test_primary_source_binding_rejects_a_different_channel_group() -> None: def test_group_artifact_context_reseeds_main_flow_from_exact_primary_bindings() -> None: dna = NamedSourceBinding( alias="DNA", - component_identity=(ComponentSelector(AllComponents.CHANNEL, "1"),), + component_identity=(ComponentSelector(Microscopy.Channel, "1"),), ) rna = NamedSourceBinding( alias="RNA", - component_identity=(ComponentSelector(AllComponents.CHANNEL, "2"),), + component_identity=(ComponentSelector(Microscopy.Channel, "2"),), ) illumination = NamedSourceBinding( alias="Illumination", artifact_kind=ImageArtifactType, projection_role=SourceProjectionRole.SOURCE_ARTIFACT, - component_identity=(ComponentSelector(AllComponents.CHANNEL, "2"),), + component_identity=(ComponentSelector(Microscopy.Channel, "2"),), ) bindings = (dna, rna, illumination) context = ArtifactDeclarationStepContext( source_bindings=StepSourceBindingsConfig(enabled=True, bindings=bindings), - group_by=GroupBy.CHANNEL, + group_by=Microscopy.Channel, input_source=InputSource.PIPELINE_START, ).with_source_declarations(binding.input_spec() for binding in bindings) diff --git a/tests/unit/test_cellprofiler_artifact_identity_reconstruction.py b/tests/unit/test_cellprofiler_artifact_identity_reconstruction.py index 42b49b8e97..af62cf407f 100644 --- a/tests/unit/test_cellprofiler_artifact_identity_reconstruction.py +++ b/tests/unit/test_cellprofiler_artifact_identity_reconstruction.py @@ -16,7 +16,6 @@ ObjectLabelsArtifactType, ) from openhcs.core.callable_contract import CallableContract -from openhcs.constants.constants import AllComponents from openhcs.core.component_group_scope import ComponentGroupScope from openhcs.core.component_set import ComponentSet from openhcs.core.function_patterns import ( @@ -53,6 +52,7 @@ MeasureObjectIntensityModule, measure_object_intensity, ) +from openhcs.domains.microscopy.axes import Microscopy class _ContractProvider(InvocationContractProvider): @@ -170,7 +170,7 @@ def test_registered_reconstruction_overrides_stay_on_semantic_leaves() -> None: def test_authored_identity_remains_visible_through_compiled_artifact_graph() -> None: - object_scope = ComponentSelector(AllComponents.SITE, "A02") + object_scope = ComponentSelector(Microscopy.Site, "A02") source_bindings = StepSourceBindingsConfig( enabled=True, bindings=( diff --git a/tests/unit/test_cellprofiler_combineobjects_source_scope.py b/tests/unit/test_cellprofiler_combineobjects_source_scope.py index 2328a2c0f3..c62335179f 100644 --- a/tests/unit/test_cellprofiler_combineobjects_source_scope.py +++ b/tests/unit/test_cellprofiler_combineobjects_source_scope.py @@ -10,11 +10,6 @@ import tifffile from objectstate.lazy_factory import ensure_global_config_context -from openhcs.constants.constants import ( - AllComponents, - GroupBy, - VariableComponents, -) from openhcs.constants.input_source import InputSource from openhcs.core.artifacts import ( ArtifactSpec, @@ -40,6 +35,7 @@ from openhcs.interop.cellprofiler.plate_workspace import ( CellProfilerPlateWorkspacePreparer, ) +from openhcs.domains.microscopy.axes import Microscopy COMBINE_OBJECTS_CPIPE = """CellProfiler Pipeline: http://www.cellprofiler.org Version:5 @@ -96,8 +92,8 @@ def combine(object_labels): func=combine, name="combine", processing_config=LazyProcessingConfig( - variable_components=[VariableComponents.SITE], - group_by=GroupBy.CHANNEL, + variable_components=[Microscopy.Site], + group_by=Microscopy.Channel, input_source=InputSource.PIPELINE_START, ), source_bindings=source_bindings, @@ -118,13 +114,13 @@ def combine(object_labels): (CallableContract.from_callable(combine),), consumer_scope=PathPlannerGroupScope.from_raw( ("1", "2"), - component=AllComponents.CHANNEL, + component=Microscopy.Channel, ), ) assert scope == PathPlannerGroupScope.from_raw( ("2",), - component=AllComponents.CHANNEL, + component=Microscopy.Channel, ) @@ -163,11 +159,11 @@ def test_public_combineobjects_import_compiles_source_owned_scope( context = compilation.runtime_contexts["A01"] step_plan = context.step_plans[0] - assert tuple(step_plan.variable_components) == (VariableComponents.SITE,) - assert step_plan.group_by is GroupBy.CHANNEL + assert tuple(step_plan.variable_components) == (Microscopy.Site,) + assert step_plan.group_by is Microscopy.Channel assert step_plan.execution_group_scope == PathPlannerGroupScope.from_raw( ("1",), - component=AllComponents.CHANNEL, + component=Microscopy.Channel, ) assert tuple( binding.input_spec().ref() diff --git a/tests/unit/test_cellprofiler_generated_pipeline_execution.py b/tests/unit/test_cellprofiler_generated_pipeline_execution.py index 8e25890b97..42dea34e65 100644 --- a/tests/unit/test_cellprofiler_generated_pipeline_execution.py +++ b/tests/unit/test_cellprofiler_generated_pipeline_execution.py @@ -11,7 +11,7 @@ import tifffile from objectstate.lazy_factory import ensure_global_config_context -from openhcs.constants.constants import AllComponents, Microscope +from openhcs.constants.constants import Microscope from openhcs.constants.input_source import InputSource from openhcs.core.artifacts import ( ArtifactInputPlan, @@ -84,6 +84,7 @@ MeasureObjectSizeShapeModule, ) from openhcs.processing.backends.lib_registry.registry_service import RegistryService +from openhcs.domains.microscopy.axes import Microscopy PUBLIC_IMPORT_CPIPE = """CellProfiler Pipeline: https://cellprofiler.org NamesAndTypes:[module_num:1|enabled:True] @@ -170,7 +171,7 @@ def test_compiler_derives_runtime_executor_after_generic_transport( ), component_identity=( ComponentSelector( - component=AllComponents.CHANNEL, + component=Microscopy.Channel, value="1", ), ), diff --git a/tests/unit/test_cellprofiler_image_math_public_roundtrip.py b/tests/unit/test_cellprofiler_image_math_public_roundtrip.py index 483e2eaabb..4414b38097 100644 --- a/tests/unit/test_cellprofiler_image_math_public_roundtrip.py +++ b/tests/unit/test_cellprofiler_image_math_public_roundtrip.py @@ -2,10 +2,11 @@ from pathlib import Path -from openhcs.constants import GroupBy, VariableComponents from openhcs.core.function_patterns import normalize_function_pattern from openhcs.core.function_step_transport import FunctionStepTransportAuthority from openhcs.interop.cellprofiler.pipeline_import import import_cellprofiler_pipeline +from openhcs.core.axes import Ungrouped +from openhcs.domains.microscopy.axes import Microscopy def _image_math_public_kwargs(pipeline_steps) -> tuple[dict[str, object], ...]: @@ -14,8 +15,8 @@ def _image_math_public_kwargs(pipeline_steps) -> tuple[dict[str, object], ...]: ) assert len(image_math_steps) == 2 assert tuple(step.processing_config.group_by for step in image_math_steps) == ( - GroupBy.CHANNEL, - GroupBy.NONE, + Microscopy.Channel, + Ungrouped, ) return tuple( invocation.kwargs_dict @@ -75,6 +76,6 @@ def test_single_channel_image_math_retains_inherited_channel_grouping() -> None: assert len(image_math_steps) == 1 assert image_math_steps[0].processing_config.variable_components == [ - VariableComponents.SITE + Microscopy.Site ] - assert image_math_steps[0].processing_config.group_by is GroupBy.CHANNEL + assert image_math_steps[0].processing_config.group_by is Microscopy.Channel diff --git a/tests/unit/test_cellprofiler_image_quality.py b/tests/unit/test_cellprofiler_image_quality.py index 882cce186f..133e37b183 100644 --- a/tests/unit/test_cellprofiler_image_quality.py +++ b/tests/unit/test_cellprofiler_image_quality.py @@ -11,7 +11,6 @@ ) -from openhcs.constants.constants import AllComponents from openhcs.constants.input_source import InputSource from openhcs.core.aligned_image_payload import ImagePayloadExecutionMode from openhcs.core.artifacts import ( @@ -81,6 +80,7 @@ CellProfilerThresholdAssignment, ) from openhcs.processing.backends.lib_registry.unified_registry import ProcessingContract +from openhcs.domains.microscopy.axes import Microscopy @pytest.mark.parametrize("shape", [(32, 32), (33, 35), (64, 97), (97, 64)]) @@ -545,7 +545,7 @@ def test_quality_control_measurements_keep_distinct_site_image_identities() -> N ) projected_rows = CellProfilerImageSetNumbering( - SourceImageSetIdentityPolicy(frozenset((AllComponents.CHANNEL,))) + SourceImageSetIdentityPolicy(frozenset((Microscopy.Channel,))) ).project_measurement_rows( scope=RuntimeExecutionAxisScope(axis_id="A01"), table=table, diff --git a/tests/unit/test_cellprofiler_library_loading.py b/tests/unit/test_cellprofiler_library_loading.py index 436ea69d30..2a06b0c53a 100644 --- a/tests/unit/test_cellprofiler_library_loading.py +++ b/tests/unit/test_cellprofiler_library_loading.py @@ -178,7 +178,6 @@ from openhcs.processing.backends.cellprofiler.morphology import ( CellProfilerDeclumpMethod, ) -from openhcs.constants.constants import VariableComponents from openhcs.interop.cellprofiler.module_declarations import ( CellProfilerModule, ) @@ -189,6 +188,9 @@ SourceQualifiedMeasurementFeatureModule, SourceQualifiedWideMeasurementRowsModule, ) +from openhcs.core.axes import TimeAxis +from openhcs.domains.microscopy.axes import Microscopy + def test_module_registry_resolves_every_declared_function(): @@ -254,24 +256,25 @@ def test_track_objects_callable_requires_timepoint(): track_objects = CellProfilerModule.__registry__["TrackObjects"].require_callable() assert CallableContract.from_callable( track_objects - ).required_variable_components == (VariableComponents.TIMEPOINT,) + ).required_axis_roles == (TimeAxis,) def test_correct_illumination_apply_inherits_resolved_stack_grouping() -> None: assert ( CallableContract.from_callable( correct_illumination_apply - ).required_variable_components + ).required_axis_roles == () ) assert ( - CellProfilerModule.require_module("CorrectIlluminationApply").group_by is None + CellProfilerModule.require_module("CorrectIlluminationApply").group_by_role + is None ) def test_mask_objects_has_no_unconditional_image_stack_axis() -> None: assert ( - CallableContract.from_callable(mask_objects).required_variable_components == () + CallableContract.from_callable(mask_objects).required_axis_roles == () ) @@ -708,7 +711,7 @@ def test_threshold_executes_site_stacks_as_independent_planes() -> None: ImagePayloadExecutionMode.FULL_STACK, image=np.zeros((2, 4, 5), dtype=np.float32), kwargs={}, - variable_components=(VariableComponents.SITE,), + variable_components=(Microscopy.Site,), ) is ImagePayloadExecutionMode.NATURAL ) @@ -720,7 +723,7 @@ def test_threshold_preserves_declared_z_stack_execution() -> None: ImagePayloadExecutionMode.FULL_STACK, image=np.zeros((2, 4, 5), dtype=np.float32), kwargs={}, - variable_components=(VariableComponents.Z_INDEX,), + variable_components=(Microscopy.ZIndex,), ) is ImagePayloadExecutionMode.FULL_STACK ) diff --git a/tests/unit/test_cellprofiler_measurement_source_group_scope.py b/tests/unit/test_cellprofiler_measurement_source_group_scope.py index 10e8661e6f..f1561a1b4c 100644 --- a/tests/unit/test_cellprofiler_measurement_source_group_scope.py +++ b/tests/unit/test_cellprofiler_measurement_source_group_scope.py @@ -7,7 +7,6 @@ import numpy as np -from openhcs.constants.constants import AllComponents from openhcs.core.artifacts import ( ArtifactOutputPlan, ArtifactSpec, @@ -38,6 +37,7 @@ from tests.unit.cellprofiler_runtime_test_support import ( runtime_adapter_request_for_test, ) +from openhcs.domains.microscopy.axes import Microscopy class _PayloadBackedOutputRecordRequest(CellProfilerOutputRecordRequest): @@ -100,7 +100,7 @@ def combine_objects(object_labels): path="/artifacts/CombinedMeasurements", artifact_type=measurements.artifact_type, group_keys=("1",), - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, ) adapter = CellProfilerRuntimeAdapter( runtime_adapter_request_for_test( @@ -111,7 +111,7 @@ def combine_objects(object_labels): group_key="1", axis_scope=RuntimeExecutionAxisScope.from_raw( "A01", - component=AllComponents.CHANNEL, + component=Microscopy.Channel, value="1", ), ) diff --git a/tests/unit/test_cellprofiler_module_execution.py b/tests/unit/test_cellprofiler_module_execution.py index 6180b2248b..67109dc89b 100644 --- a/tests/unit/test_cellprofiler_module_execution.py +++ b/tests/unit/test_cellprofiler_module_execution.py @@ -14,13 +14,7 @@ DirectParentReferenceFeatureDeclaration, DirectParentReferenceMeasurementFeature, ) -from openhcs.constants.constants import ( - AllComponents, - Backend, - GroupBy, - MemoryType, - VariableComponents, -) +from openhcs.constants.constants import Backend, MemoryType from openhcs.core.aligned_image_payload import ( AlignedImageSliceContext, AlignedImageStack, @@ -407,6 +401,8 @@ cellprofiler_runtime_input_edge_for_test, runtime_adapter_request_for_test, ) +from openhcs.core.axes import Axis, Ungrouped +from openhcs.domains.microscopy.axes import Microscopy def _compiled_callable_contract( @@ -503,7 +499,7 @@ def test_default_invocation_keeps_compiled_source_bindings_outside_anchor_group( executor = _module_executor(contract) channel_scope = ComponentGroupScope( ("1",), - component=AllComponents.CHANNEL, + component=Microscopy.Channel, ) runtime = _FakeCellProfilerRuntime( {}, @@ -528,16 +524,16 @@ def test_default_invocation_keeps_compiled_source_bindings_outside_anchor_group( source_bindings=( NamedSourceBinding( alias="BF_image", - component_identity=(ComponentSelector(AllComponents.CHANNEL, "1"),), + component_identity=(ComponentSelector(Microscopy.Channel, "1"),), ), NamedSourceBinding( alias=image_spec.name, - component_identity=(ComponentSelector(AllComponents.CHANNEL, "2"),), + component_identity=(ComponentSelector(Microscopy.Channel, "2"),), ), ), axis_scope=RuntimeExecutionAxisScope.from_raw( "A01", - component=AllComponents.CHANNEL, + component=Microscopy.Channel, value="1", ), ) @@ -557,7 +553,7 @@ def test_active_inputs_restore_repeated_contract_roles_from_unique_storage() -> artifact_inputs=(objects, objects), ) executor = _module_executor(contract) - channel_scope = ComponentGroupScope(("1",), component=AllComponents.CHANNEL) + channel_scope = ComponentGroupScope(("1",), component=Microscopy.Channel) runtime = _FakeCellProfilerRuntime( {}, artifact_input_edges=( @@ -609,7 +605,7 @@ def test_active_inputs_exclude_unselected_independent_contract_roles() -> None: artifact_inputs=(first, second), ) executor = _module_executor(contract) - channel_scope = ComponentGroupScope(("1",), component=AllComponents.CHANNEL) + channel_scope = ComponentGroupScope(("1",), component=Microscopy.Channel) runtime = _FakeCellProfilerRuntime( {}, artifact_input_edges=( @@ -2746,7 +2742,7 @@ def test_object_label_output_source_preserves_matching_input_object_plane_contex consumer_variable_components=(), ), ), - variable_components=(VariableComponents.CHANNEL,), + variable_components=(Microscopy.Channel,), ) current_image = ImagePayloadMetadata( source_image_provenance_planes=SourceImageProvenancePlanes.from_components( @@ -4038,7 +4034,7 @@ def __init__( tuple[ArtifactSpec, ArtifactOutputPlan], ... ] = (), source_bindings: tuple[NamedSourceBinding, ...] = (), - variable_components: tuple[VariableComponents, ...] = (), + variable_components: tuple[type[Axis], ...] = (), plane_projection: RuntimePlaneProjection = RuntimePlaneProjection.stack(), axis_scope: RuntimeExecutionAxisScope | None = None, source_image_set_identity_policy: SourceImageSetIdentityPolicy = ( @@ -4118,7 +4114,7 @@ def __init__( self.objects: list[tuple[str, np.ndarray, dict[str, object]]] = [] self.spatial_grids: dict[str, SpatialGrid] = {} self.relationships: list[ObjectRelationship] = [] - self.group_by = GroupBy.NONE + self.group_by = Ungrouped def install_artifact_input_edges( self, @@ -8477,7 +8473,7 @@ def test_illumination_apply_projects_broadcast_input_to_selected_primary_site( illumination_spec, ), ), - variable_components=(VariableComponents.CHANNEL,), + variable_components=(Microscopy.Channel,), ) executor = _module_executor(contract) @@ -8612,7 +8608,7 @@ def test_illumination_apply_image_output_uses_original_input_source_payload() -> ( ((), None, None), ( - (VariableComponents.CHANNEL,), + (Microscopy.Channel,), RuntimePlaneAxisValueProjection.preserve( axis=RuntimePlaneAxis.RUNTIME_SLICE, axis_size=2, @@ -8622,7 +8618,7 @@ def test_illumination_apply_image_output_uses_original_input_source_payload() -> ), ) def test_image_output_projection_uses_exact_invocation_projection( - output_variable_components: tuple[VariableComponents, ...], + output_variable_components: tuple[type[Axis], ...], plane_projection: RuntimePlaneAxisValueProjection | None, expected_plane_axis: RuntimePlaneAxis | None, ) -> None: @@ -8667,7 +8663,7 @@ def test_image_output_projection_uses_exact_invocation_projection( ), ), ), - variable_components=(VariableComponents.CHANNEL,), + variable_components=(Microscopy.Channel,), plane_projection=RuntimePlaneProjection.stack(plane_count=2), ) executor = _module_executor( @@ -8747,14 +8743,14 @@ def test_declared_output_source_uses_projected_object_input_value() -> None: ) output_plan = replace( _artifact_output_plan(output_spec), - variable_components=(VariableComponents.SITE,), + variable_components=(Microscopy.Site,), ) runtime = _FakeCellProfilerRuntime( {}, objects={object_spec.name: labels}, artifact_input_edges=(_artifact_input_edge_for_test(object_spec),), artifact_output_bindings=((output_spec, output_plan),), - variable_components=(VariableComponents.SITE,), + variable_components=(Microscopy.Site,), plane_projection=RuntimePlaneProjection.selected(0, plane_count=1), ) callable_contract = _compiled_callable_contract( @@ -8833,7 +8829,7 @@ def test_image_output_recording_projects_masked_singleton_rgb_payload() -> None: runtime = _FakeCellProfilerRuntime( {source_spec.name: source_payload}, plane_projection=RuntimePlaneProjection.stack(plane_count=1), - variable_components=(VariableComponents.CHANNEL,), + variable_components=(Microscopy.Channel,), ) executor = _module_executor( _compiled_callable_contract( @@ -12326,11 +12322,11 @@ def align_function( source_bindings=( NamedSourceBinding( alias="Stain1Raw", - component_identity=(ComponentSelector(AllComponents.CHANNEL, "1"),), + component_identity=(ComponentSelector(Microscopy.Channel, "1"),), ), NamedSourceBinding( alias="Stain2Raw", - component_identity=(ComponentSelector(AllComponents.CHANNEL, "2"),), + component_identity=(ComponentSelector(Microscopy.Channel, "2"),), ), ), ) @@ -12847,7 +12843,7 @@ def test_filterobjects_binds_selection_measurement_values_to_label_slices( measurement_tables={"Cells": (measurements,)}, plane_projection=RuntimePlaneProjection.stack(2), source_image_set_identity_policy=SourceImageSetIdentityPolicy( - frozenset((AllComponents.CHANNEL,)) + frozenset((Microscopy.Channel,)) ), ) runtime._store_runtime_artifact( @@ -13589,7 +13585,7 @@ def test_object_measurement_table_uses_provenance_without_image_ownership() -> N output_plans=( replace( _artifact_output_plan(measurement_spec), - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, ), ), spec=measurement_spec, @@ -13607,7 +13603,7 @@ def test_object_measurement_table_uses_provenance_without_image_ownership() -> N path=f"/memory/{spec.name}.pkl", artifact_type=ObjectLabelsArtifactType, group_keys=(channel,), - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, paths_by_group={ channel: f"/memory/{spec.name}_{channel}.pkl" }, @@ -13616,20 +13612,20 @@ def test_object_measurement_table_uses_provenance_without_image_ownership() -> N invocation_scope=ComponentGroupScope.ungrouped(), producer_selection_scope=ComponentGroupScope( (channel,), - component=AllComponents.CHANNEL, + component=Microscopy.Channel, ), component_scopes=( ComponentGroupScope( (channel,), - component=AllComponents.CHANNEL, + component=Microscopy.Channel, ), ), - consumer_variable_components=(AllComponents.SITE,), + consumer_variable_components=(Microscopy.Site,), ) for spec, channel in zip(object_specs, ("1", "2"), strict=True) ) ), - variable_components=(VariableComponents.SITE,), + variable_components=(Microscopy.Site,), axis_scope=RuntimeExecutionAxisScope.from_raw( "test-axis", component=None, value=None ), @@ -13808,26 +13804,26 @@ def test_relate_objects_measurement_table_rejects_distinct_image_set_axes() -> N path=f"/memory/{name}.pkl", artifact_type=ObjectLabelsArtifactType, group_keys=(channel,), - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, paths_by_group={channel: f"/memory/{name}_{channel}.pkl"}, ), invocation_scope=ComponentGroupScope.ungrouped(), producer_selection_scope=ComponentGroupScope( (channel,), - component=AllComponents.CHANNEL, + component=Microscopy.Channel, ), component_scopes=( ComponentGroupScope( (channel,), - component=AllComponents.CHANNEL, + component=Microscopy.Channel, ), ), - consumer_variable_components=(AllComponents.SITE,), + consumer_variable_components=(Microscopy.Site,), ) for name, channel in (("Parents", "1"), ("Children", "2")) ) ), - variable_components=(VariableComponents.SITE,), + variable_components=(Microscopy.Site,), axis_scope=RuntimeExecutionAxisScope.from_raw( "test-axis", component=None, value=None ), @@ -18268,7 +18264,7 @@ def test_convert_objects_to_image_uses_declared_label_source_for_runtime_plane_d name="NucleiImage", path="/memory/NucleiImage.pkl", artifact_type=ImageArtifactType, - variable_components=(AllComponents.Z_INDEX,), + variable_components=(Microscopy.ZIndex,), relations=(GroupLineageSourceRelation(source_spec.ref()),), ) result = (ImageArtifactType if output_plan is None else output_plan.artifact_type).contextualize_output_from_projector( @@ -18300,7 +18296,7 @@ def test_object_label_image_output_rejects_source_plane_count_drift() -> None: name="NucleiImage", path="/memory/NucleiImage.pkl", artifact_type=ImageArtifactType, - variable_components=(AllComponents.Z_INDEX,), + variable_components=(Microscopy.ZIndex,), relations=(GroupLineageSourceRelation(source_spec.ref()),), ) with pytest.raises( @@ -18334,7 +18330,7 @@ def test_object_label_singleton_volume_output_declares_runtime_plane_axis() -> N name="NucleiImage", path="/memory/NucleiImage.pkl", artifact_type=ImageArtifactType, - variable_components=(AllComponents.Z_INDEX,), + variable_components=(Microscopy.ZIndex,), relations=(GroupLineageSourceRelation(source_spec.ref()),), ) @@ -18366,7 +18362,7 @@ def test_object_label_scalar_image_output_does_not_invent_runtime_plane_axis() - name="NucleiImage", path="/memory/NucleiImage.pkl", artifact_type=ImageArtifactType, - variable_components=(AllComponents.Z_INDEX,), + variable_components=(Microscopy.ZIndex,), relations=(GroupLineageSourceRelation(source_spec.ref()),), ) diff --git a/tests/unit/test_cellprofiler_module_function_resolution.py b/tests/unit/test_cellprofiler_module_function_resolution.py index 2d6db1eb70..1c94eb9a5d 100644 --- a/tests/unit/test_cellprofiler_module_function_resolution.py +++ b/tests/unit/test_cellprofiler_module_function_resolution.py @@ -4,7 +4,6 @@ import pytest -from openhcs.constants.constants import AllComponents from openhcs.core.artifacts import ( ArtifactSpec, ArtifactSpecCollection, @@ -27,6 +26,8 @@ RemoveHolesModule, ShrinkToObjectCentersModule, ) +from openhcs.core.axes import Axis +from openhcs.domains.microscopy.axes import Microscopy def _module(name: str, settings: dict[str, str]) -> ModuleBlock: @@ -44,7 +45,7 @@ def _contract_and_source_bindings( module: ModuleBlock, *, object_input: bool = False, - source_stack_components: tuple[AllComponents, ...] = (), + source_stack_components: tuple[type[Axis], ...] = (), ) -> tuple[CallableContract, StepSourceBindingsConfig]: module_type = CellProfilerModule.require_module(module.name) raw_contract = CallableContract.from_callable(module_type.require_callable()) @@ -197,7 +198,7 @@ def test_source_stack_variants_use_declared_source_components( contract, source_bindings = _contract_and_source_bindings( module, object_input=object_input, - source_stack_components=(AllComponents.Z_INDEX,), + source_stack_components=(Microscopy.ZIndex,), ) resolved = module_type.resolve_function( module, diff --git a/tests/unit/test_cellprofiler_module_processing_config.py b/tests/unit/test_cellprofiler_module_processing_config.py index f444e5ca87..7492ee072e 100644 --- a/tests/unit/test_cellprofiler_module_processing_config.py +++ b/tests/unit/test_cellprofiler_module_processing_config.py @@ -4,7 +4,6 @@ import pytest -from openhcs.constants.constants import GroupBy, VariableComponents from openhcs.constants.input_source import InputSource from openhcs.core.callable_contract import CallableContract from openhcs.core.config import ProcessingConfig @@ -23,6 +22,8 @@ straighten_worms, track_objects, ) +from openhcs.core.axes import Axis, GroupingDeclaration, Ungrouped +from openhcs.domains.microscopy.axes import Microscopy def _processing_config( @@ -41,8 +42,8 @@ def _processing_config( def test_processing_config_preserves_resolved_input_source() -> None: inherited = ProcessingConfig( - variable_components=[VariableComponents.CHANNEL], - group_by=GroupBy.SITE, + variable_components=[Microscopy.Channel], + group_by=Microscopy.Site, input_source=InputSource.PIPELINE_START, ) config = _processing_config( @@ -56,40 +57,40 @@ def test_processing_config_preserves_resolved_input_source() -> None: @pytest.mark.parametrize( ("func", "variable_components", "group_by"), ( - (gray_to_color, [VariableComponents.CHANNEL], GroupBy.SITE), - (align, [VariableComponents.CHANNEL], GroupBy.SITE), + (gray_to_color, [Microscopy.Channel], Microscopy.Site), + (align, [Microscopy.Channel], Microscopy.Site), ( measure_colocalization, - [VariableComponents.CHANNEL], - GroupBy.SITE, + [Microscopy.Channel], + Microscopy.Site, ), ( measure_colocalization_objects, - [VariableComponents.CHANNEL], - GroupBy.SITE, + [Microscopy.Channel], + Microscopy.Site, ), ( track_objects, - [VariableComponents.TIMEPOINT], - GroupBy.CHANNEL, + [Microscopy.Timepoint], + Microscopy.Channel, ), ( straighten_worms, - [VariableComponents.CHANNEL], - GroupBy.SITE, + [Microscopy.Channel], + Microscopy.Site, ), ), ) def test_callable_axes_and_module_import_grouping_lower_to_processing_config( func, - variable_components: list[VariableComponents], - group_by: GroupBy, + variable_components: list[type[Axis]], + group_by: type[GroupingDeclaration], ) -> None: config = _processing_config( func, inherited=ProcessingConfig( - variable_components=[VariableComponents.SITE], - group_by=GroupBy.CHANNEL, + variable_components=[Microscopy.Site], + group_by=Microscopy.Channel, ), ) @@ -107,8 +108,8 @@ def test_callable_axes_and_module_import_grouping_lower_to_processing_config( ) def test_generic_stack_consumers_inherit_pipeline_axis(func) -> None: inherited = ProcessingConfig( - variable_components=[VariableComponents.SITE], - group_by=GroupBy.CHANNEL, + variable_components=[Microscopy.Site], + group_by=Microscopy.Channel, ) assert _processing_config(func, inherited=inherited) == inherited @@ -116,8 +117,8 @@ def test_generic_stack_consumers_inherit_pipeline_axis(func) -> None: def test_generic_module_inherits_pipeline_processing_config() -> None: inherited = ProcessingConfig( - variable_components=[VariableComponents.Z_INDEX], - group_by=GroupBy.SITE, + variable_components=[Microscopy.ZIndex], + group_by=Microscopy.Site, ) config = _processing_config( relate_objects, @@ -129,8 +130,8 @@ def test_generic_module_inherits_pipeline_processing_config() -> None: def test_plate_execution_scope_selects_plate_processing() -> None: inherited = ProcessingConfig( - variable_components=[VariableComponents.Z_INDEX], - group_by=GroupBy.SITE, + variable_components=[Microscopy.ZIndex], + group_by=Microscopy.Site, ) config = _processing_config( export_to_database, @@ -140,7 +141,7 @@ def test_plate_execution_scope_selects_plate_processing() -> None: assert config == replace( inherited, variable_components=[], - group_by=GroupBy.NONE, + group_by=Ungrouped, ) diff --git a/tests/unit/test_cellprofiler_output_recording.py b/tests/unit/test_cellprofiler_output_recording.py index 7921ffcb1f..608a1b78fa 100644 --- a/tests/unit/test_cellprofiler_output_recording.py +++ b/tests/unit/test_cellprofiler_output_recording.py @@ -4,7 +4,6 @@ import numpy as np import pytest -from openhcs.constants.constants import VariableComponents from openhcs.core.aligned_image_payload import ImagePayloadExecutionMode from openhcs.core.artifacts import ( ArtifactOutputPlan, @@ -42,6 +41,7 @@ ImageOutputRecorder, RelationshipsOutputRecorder, ) +from openhcs.domains.microscopy.axes import Microscopy def _contract(*, outputs: tuple[ArtifactSpec, ...]) -> CallableContract: @@ -200,7 +200,7 @@ def test_image_output_recording_uses_exact_invocation_projection_for_rgb( path="ColorNeighbors.tif", artifact_type=output.artifact_type, relations=output.relations, - variable_components=(VariableComponents.SITE,), + variable_components=(Microscopy.Site,), ) source_slice = ImagePayloadMetadata( source_image_names=(measured_objects.name,), diff --git a/tests/unit/test_cellprofiler_pipeline_import.py b/tests/unit/test_cellprofiler_pipeline_import.py index 2a4445c915..3edf037ba9 100644 --- a/tests/unit/test_cellprofiler_pipeline_import.py +++ b/tests/unit/test_cellprofiler_pipeline_import.py @@ -10,7 +10,7 @@ import pytest from objectstate import config_context -from openhcs.constants import AllComponents, Backend, GroupBy, VariableComponents +from openhcs.constants import Backend from openhcs.constants.input_source import InputSource from openhcs.core.artifacts import ( ArtifactInputPlan, @@ -71,6 +71,8 @@ measure_object_neighbors, ) from openhcs.processing.backends.cellprofiler.outlines import OverlayObjectsModule +from openhcs.core.axes import Ungrouped +from openhcs.domains.microscopy.axes import Microscopy PIPELINE_IMPORT_PATH = ( Path(__file__).parents[2] @@ -730,14 +732,14 @@ def test_direct_import_preserves_3d_image_variant_for_derived_input() -> None: ) assert pipeline_config.source_bindings_config.source_stack_components == ( - AllComponents.Z_INDEX, + Microscopy.ZIndex, ) assert pipeline_config.processing_config.variable_components == [ - VariableComponents.Z_INDEX + Microscopy.ZIndex ] with config_context(pipeline_config): assert pipeline_steps[0].processing_config.variable_components == [ - VariableComponents.Z_INDEX + Microscopy.ZIndex ] assert ( pipeline_steps[1].processing_config.input_source @@ -850,7 +852,7 @@ def test_required_module_axis_is_local_to_its_step() -> None: ) assert pipeline_config.processing_config.variable_components == [ - VariableComponents.SITE + Microscopy.Site ] assert [step.name for step in pipeline_steps] == ["TrackObjects", "SaveImages"] track_invocation = next( @@ -860,10 +862,10 @@ def test_required_module_axis_is_local_to_its_step() -> None: assert track_invocation.kwargs_dict["name_the_output_image"] == "TrackedNuclei" with config_context(pipeline_config): assert pipeline_steps[0].processing_config.variable_components == [ - VariableComponents.TIMEPOINT + Microscopy.Timepoint ] assert pipeline_steps[1].processing_config.variable_components == [ - VariableComponents.SITE + Microscopy.Site ] assert ( len(tuple(normalize_function_pattern(pipeline_steps[1].func).iter_items())) == 2 @@ -908,11 +910,11 @@ def test_grouped_source_pipeline_inherits_declared_tracking_axis() -> None: ) assert pipeline_config.processing_config.variable_components == [ - VariableComponents.TIMEPOINT + Microscopy.Timepoint ] with config_context(pipeline_config): assert all( - step.processing_config.variable_components == [VariableComponents.TIMEPOINT] + step.processing_config.variable_components == [Microscopy.Timepoint] for step in pipeline_steps ) @@ -1363,7 +1365,7 @@ def test_repeated_measurement_images_preserve_one_complete_module_roster() -> No ) assert invocations[0].kwargs_dict["select_images_to_measure"] == ("DNA", "PH3") with config_context(pipeline_config): - assert measurement_step.processing_config.group_by is GroupBy.NONE + assert measurement_step.processing_config.group_by is Ungrouped assert measurement_step.processing_config.input_source is InputSource.PIPELINE_START @@ -1524,7 +1526,7 @@ def test_object_measurement_subjects_across_channels_share_one_invocation() -> N "Nuclei", "Cells", ) with config_context(config): - assert measurement_step.processing_config.group_by is GroupBy.NONE + assert measurement_step.processing_config.group_by is Ungrouped assert measurement_step.processing_config.input_source is InputSource.PREVIOUS_STEP @@ -1601,7 +1603,7 @@ def test_multi_image_source_contract_keeps_every_source_input_exact() -> None: bindings = tuple( NamedSourceBinding( alias=alias, - component_identity=(ComponentSelector(AllComponents.CHANNEL, channel),), + component_identity=(ComponentSelector(Microscopy.Channel, channel),), ) for alias, channel in ( ("origDNA", "2"), @@ -1614,7 +1616,7 @@ def test_multi_image_source_contract_keeps_every_source_input_exact() -> None: step_name="ImageMath", step_index=13, source_bindings=source_bindings, - group_by=GroupBy.CHANNEL, + group_by=Microscopy.Channel, input_source=InputSource.PIPELINE_START, ).with_source_declarations(binding.input_spec() for binding in bindings) module = ModuleBlock( diff --git a/tests/unit/test_cellprofiler_runtime_adapter.py b/tests/unit/test_cellprofiler_runtime_adapter.py index 57435f30b4..1ea80991f1 100644 --- a/tests/unit/test_cellprofiler_runtime_adapter.py +++ b/tests/unit/test_cellprofiler_runtime_adapter.py @@ -8,7 +8,6 @@ import numpy as np import pytest -from openhcs.constants.constants import AllComponents, VariableComponents from openhcs.constants.input_source import InputSource from openhcs.core.alias_property import AliasProperty from openhcs.core.aligned_image_payload import ImagePayloadExecutionMode @@ -182,6 +181,7 @@ from openhcs.interop.cellprofiler.runtime.artifact_binding import ( RuntimeInputBindingRequest, ) +from openhcs.domains.microscopy.axes import Microscopy AXIS_ID = "A01" DNA_IMAGE = "DNA" @@ -373,13 +373,16 @@ def runtime_axis_scope( component: str | None = None, value: str | None = None, ) -> RuntimeExecutionAxisScope: + """Build a scope from a boundary axis name, as the runtime wire carries it.""" return RuntimeExecutionAxisScope.from_raw( axis_id, - component=component, + component=None if component is None else Microscopy.named(component), value=value, ) + + @dataclass(frozen=True) class StaticFilenameParser: metadata: Mapping[str, object] @@ -702,7 +705,15 @@ def _source_bound_image_adapter(output_bindings, images): context = ContextStub(filemanager) projections = SourceProjectionSet(tuple( SourcePlaneProjection( - address=OpenHCSPlaneAddress.from_values('A01', '1', str(index), '1', '1'), + address=OpenHCSPlaneAddress( + ( + (Microscopy.Well, 'A01'), + (Microscopy.Site, '1'), + (Microscopy.Channel, str(index)), + (Microscopy.ZIndex, '1'), + (Microscopy.Timepoint, '1'), + ) + ), ref=SourcePixelRef('memory', f'/src/{alias}.tif'), source_alias=alias, ) @@ -1235,7 +1246,7 @@ def test_cellprofiler_adapter_does_not_cache_current_image_object_selection(): store = RuntimeValueStore() outputs = { NUCLEI: _plan( - NUCLEI, ObjectLabelsArtifactType, group_component=AllComponents.SITE + NUCLEI, ObjectLabelsArtifactType, group_component=Microscopy.Site ) } output_bindings = ( @@ -1297,18 +1308,18 @@ def test_cellprofiler_adapter_does_not_cache_current_image_object_selection(): name=NUCLEI, path=outputs[NUCLEI].path, artifact_type=ObjectLabelsArtifactType, - group_component=AllComponents.SITE, + group_component=Microscopy.Site, ), invocation_scope=ComponentGroupScope.ungrouped(), producer_selection_scope=ComponentGroupScope.dynamic( - AllComponents.SITE + Microscopy.Site ), - component_scopes=(ComponentGroupScope.dynamic(AllComponents.SITE),), - consumer_variable_components=(AllComponents.SITE,), + component_scopes=(ComponentGroupScope.dynamic(Microscopy.Site),), + consumer_variable_components=(Microscopy.Site,), ), ) }, - variable_components=(VariableComponents.SITE,), + variable_components=(Microscopy.Site,), microscope_handler=( processing_context.microscope_handler if processing_context is not None @@ -1352,7 +1363,7 @@ def test_cellprofiler_adapter_does_not_select_relationship_from_current_source_p path="/memory/relationships.pkl", artifact_type=RelationshipsArtifactType, group_keys=("1", "2"), - group_component=AllComponents.SITE, + group_component=Microscopy.Site, paths_by_group=group_paths, ) filemanager = FileManagerStub() @@ -1399,14 +1410,14 @@ def test_cellprofiler_adapter_does_not_select_relationship_from_current_source_p ), invocation_scope=ComponentGroupScope.ungrouped(), producer_selection_scope=ComponentGroupScope.from_raw( - ("1", "2"), component=AllComponents.SITE + ("1", "2"), component=Microscopy.Site ), component_scopes=( ComponentGroupScope.from_raw( - ("1", "2"), component=AllComponents.SITE + ("1", "2"), component=Microscopy.Site ), ), - consumer_variable_components=(AllComponents.SITE,), + consumer_variable_components=(Microscopy.Site,), ), ) } @@ -1415,7 +1426,7 @@ def test_cellprofiler_adapter_does_not_select_relationship_from_current_source_p runtime_value_store=store, axis_scope=runtime_axis_scope(AXIS_ID), artifact_inputs=_compiled_artifact_inputs, - variable_components=(VariableComponents.SITE,), + variable_components=(Microscopy.Site,), filemanager=filemanager, callable_contract=_compiled_callable_contract( calculate_math, @@ -1456,7 +1467,7 @@ def test_cellprofiler_adapter_aligns_grouped_relationships_to_runtime_slices(): path="/memory/relationships.pkl", artifact_type=RelationshipsArtifactType, group_keys=("1", "2"), - group_component=AllComponents.SITE, + group_component=Microscopy.Site, paths_by_group=group_paths, ) filemanager = FileManagerStub() @@ -1499,14 +1510,14 @@ def test_cellprofiler_adapter_aligns_grouped_relationships_to_runtime_slices(): ), invocation_scope=ComponentGroupScope.ungrouped(), producer_selection_scope=ComponentGroupScope.from_raw( - ("1", "2"), component=AllComponents.SITE + ("1", "2"), component=Microscopy.Site ), component_scopes=( ComponentGroupScope.from_raw( - ("1", "2"), component=AllComponents.SITE + ("1", "2"), component=Microscopy.Site ), ), - consumer_variable_components=(AllComponents.SITE,), + consumer_variable_components=(Microscopy.Site,), ), ) } @@ -1516,7 +1527,7 @@ def test_cellprofiler_adapter_aligns_grouped_relationships_to_runtime_slices(): axis_scope=runtime_axis_scope(AXIS_ID), artifact_inputs=_compiled_artifact_inputs, filemanager=filemanager, - variable_components=(VariableComponents.SITE,), + variable_components=(Microscopy.Site,), callable_contract=_compiled_callable_contract( calculate_math, artifact_inputs=tuple( @@ -1538,7 +1549,7 @@ def test_cellprofiler_adapter_does_not_source_scope_default_image_records(): store = RuntimeValueStore() outputs = { DNA_IMAGE: _plan( - DNA_IMAGE, ImageArtifactType, group_component=AllComponents.SITE + DNA_IMAGE, ImageArtifactType, group_component=Microscopy.Site ) } output_bindings = ( @@ -1573,14 +1584,14 @@ def test_cellprofiler_adapter_does_not_source_scope_default_image_records(): name=DNA_IMAGE, path=outputs[DNA_IMAGE].path, artifact_type=ImageArtifactType, - group_component=AllComponents.SITE, + group_component=Microscopy.Site, ), invocation_scope=ComponentGroupScope.ungrouped(), producer_selection_scope=ComponentGroupScope.dynamic( - AllComponents.SITE + Microscopy.Site ), - component_scopes=(ComponentGroupScope.dynamic(AllComponents.SITE),), - consumer_variable_components=(AllComponents.SITE,), + component_scopes=(ComponentGroupScope.dynamic(Microscopy.Site),), + consumer_variable_components=(Microscopy.Site,), ), ) } @@ -1589,7 +1600,7 @@ def test_cellprofiler_adapter_does_not_source_scope_default_image_records(): runtime_value_store=store, axis_scope=runtime_axis_scope(AXIS_ID), artifact_inputs=_compiled_artifact_inputs, - variable_components=(VariableComponents.SITE,), + variable_components=(Microscopy.Site,), filemanager=filemanager, callable_contract=_compiled_callable_contract( calculate_math, @@ -1627,7 +1638,7 @@ def test_cellprofiler_adapter_stacks_declared_default_image_input_runtime_groups path=image_path, artifact_type=ImageArtifactType, group_keys=(None,), - group_component=AllComponents.SITE, + group_component=Microscopy.Site, ) for group_key, source_path, value in ( @@ -1660,21 +1671,21 @@ def test_cellprofiler_adapter_stacks_declared_default_image_input_runtime_groups path=image_path, artifact_type=ImageArtifactType, group_keys=(None,), - group_component=AllComponents.SITE, + group_component=Microscopy.Site, ), invocation_scope=ComponentGroupScope.from_raw( - (AXIS_ID,), component=AllComponents.WELL + (AXIS_ID,), component=Microscopy.Well ), producer_selection_scope=ComponentGroupScope.dynamic( - AllComponents.SITE + Microscopy.Site ), component_scopes=( ComponentGroupScope.from_raw( - (AXIS_ID,), component=AllComponents.WELL + (AXIS_ID,), component=Microscopy.Well ), - ComponentGroupScope.dynamic(AllComponents.SITE), + ComponentGroupScope.dynamic(Microscopy.Site), ), - consumer_variable_components=(AllComponents.SITE,), + consumer_variable_components=(Microscopy.Site,), ), ) } @@ -1684,7 +1695,7 @@ def test_cellprofiler_adapter_stacks_declared_default_image_input_runtime_groups artifact_inputs=_compiled_artifact_inputs, microscope_handler=(context).microscope_handler, filemanager=filemanager, - variable_components=(VariableComponents.SITE,), + variable_components=(Microscopy.Site,), callable_contract=_compiled_callable_contract( calculate_math, artifact_inputs=tuple( @@ -1730,7 +1741,7 @@ def test_cellprofiler_adapter_keeps_multisource_current_image_grouped_when_files path=image_path, artifact_type=ImageArtifactType, group_keys=(None,), - group_component=AllComponents.SITE, + group_component=Microscopy.Site, ) for group_key, source_path, value in ( @@ -1762,14 +1773,14 @@ def test_cellprofiler_adapter_keeps_multisource_current_image_grouped_when_files path=image_path, artifact_type=ImageArtifactType, group_keys=(None,), - group_component=AllComponents.SITE, + group_component=Microscopy.Site, ), invocation_scope=ComponentGroupScope.ungrouped(), producer_selection_scope=ComponentGroupScope.dynamic( - AllComponents.SITE + Microscopy.Site ), - component_scopes=(ComponentGroupScope.dynamic(AllComponents.SITE),), - consumer_variable_components=(AllComponents.SITE,), + component_scopes=(ComponentGroupScope.dynamic(Microscopy.Site),), + consumer_variable_components=(Microscopy.Site,), ), ) } @@ -1780,7 +1791,7 @@ def test_cellprofiler_adapter_keeps_multisource_current_image_grouped_when_files artifact_inputs=_compiled_artifact_inputs, microscope_handler=(context).microscope_handler, filemanager=filemanager, - variable_components=(VariableComponents.SITE,), + variable_components=(Microscopy.Site,), callable_contract=_compiled_callable_contract( calculate_math, artifact_inputs=tuple( @@ -1820,7 +1831,7 @@ def test_cellprofiler_adapter_stacks_declared_image_input_for_pattern_group(): path=image_path, artifact_type=ImageArtifactType, group_keys=(None,), - group_component=AllComponents.SITE, + group_component=Microscopy.Site, ) for group_key, source_path, value in ( @@ -1853,14 +1864,14 @@ def test_cellprofiler_adapter_stacks_declared_image_input_for_pattern_group(): path=image_path, artifact_type=ImageArtifactType, group_keys=(None,), - group_component=AllComponents.SITE, + group_component=Microscopy.Site, ), invocation_scope=ComponentGroupScope.ungrouped(), producer_selection_scope=ComponentGroupScope.dynamic( - AllComponents.SITE + Microscopy.Site ), - component_scopes=(ComponentGroupScope.dynamic(AllComponents.SITE),), - consumer_variable_components=(AllComponents.SITE,), + component_scopes=(ComponentGroupScope.dynamic(Microscopy.Site),), + consumer_variable_components=(Microscopy.Site,), ), ) } @@ -1871,7 +1882,7 @@ def test_cellprofiler_adapter_stacks_declared_image_input_for_pattern_group(): artifact_inputs=_compiled_artifact_inputs, microscope_handler=(context).microscope_handler, filemanager=filemanager, - variable_components=(VariableComponents.SITE,), + variable_components=(Microscopy.Site,), callable_contract=_compiled_callable_contract( calculate_math, artifact_inputs=tuple( @@ -1908,7 +1919,7 @@ def test_cellprofiler_adapter_records_output_in_declared_invocation_group(): path=f"/memory/{output_name}.pkl", artifact_type=ImageArtifactType, group_keys=("0", "3"), - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, paths_by_group={ "0": f"/memory/{output_name}_w0.pkl", "3": f"/memory/{output_name}_w3.pkl", @@ -1918,11 +1929,11 @@ def test_cellprofiler_adapter_records_output_in_declared_invocation_group(): runtime_value_store=store, axis_scope=RuntimeExecutionAxisScope.from_raw( AXIS_ID, - component=AllComponents.CHANNEL, + component=Microscopy.Channel, value="3", fixed_component_values=( - (AllComponents.Z_INDEX, "1"), - (AllComponents.TIMEPOINT, "1"), + (Microscopy.ZIndex, "1"), + (Microscopy.Timepoint, "1"), ), ), group_key="3", @@ -1947,8 +1958,8 @@ def test_cellprofiler_adapter_records_output_in_declared_invocation_group(): assert stored.key.scope.value_text == "3" assert stored.key.scope.fixed_component_values == ( - (AllComponents.Z_INDEX, "1"), - (AllComponents.TIMEPOINT, "1"), + (Microscopy.ZIndex, "1"), + (Microscopy.Timepoint, "1"), ) assert ("memory", f"/memory/{output_name}_w3.pkl") in filemanager.saved @@ -1983,7 +1994,7 @@ def test_cellprofiler_adapter_projects_source_bound_runtime_image_to_group_plane path=image_path, artifact_type=ImageArtifactType, group_keys=(None,), - variable_components=(AllComponents.SITE,), + variable_components=(Microscopy.Site,), paths_by_group={None: image_path}, ), ), @@ -2018,14 +2029,14 @@ def test_cellprofiler_adapter_projects_source_bound_runtime_image_to_group_plane artifact_type=ImageArtifactType, group_keys=(None,), paths_by_group={None: image_path}, - variable_components=(AllComponents.SITE,), + variable_components=(Microscopy.Site,), ), invocation_scope=ComponentGroupScope.from_raw( - ("2",), component=AllComponents.SITE + ("2",), component=Microscopy.Site ), producer_selection_scope=ComponentGroupScope.ungrouped(), component_scopes=( - ComponentGroupScope.from_raw(("2",), component=AllComponents.SITE), + ComponentGroupScope.from_raw(("2",), component=Microscopy.Site), ), consumer_variable_components=(), ), @@ -2084,7 +2095,7 @@ def test_cellprofiler_adapter_deduplicates_grouped_runtime_image_input_locations path=image_path, artifact_type=ImageArtifactType, group_keys=(None,), - variable_components=(AllComponents.SITE,), + variable_components=(Microscopy.Site,), paths_by_group={None: image_path}, ), ), @@ -2119,14 +2130,14 @@ def test_cellprofiler_adapter_deduplicates_grouped_runtime_image_input_locations artifact_type=ImageArtifactType, group_keys=(None,), paths_by_group={None: image_path}, - variable_components=(AllComponents.SITE,), + variable_components=(Microscopy.Site,), ), invocation_scope=ComponentGroupScope.from_raw( - ("2",), component=AllComponents.SITE + ("2",), component=Microscopy.Site ), producer_selection_scope=ComponentGroupScope.ungrouped(), component_scopes=( - ComponentGroupScope.from_raw(("2",), component=AllComponents.SITE), + ComponentGroupScope.from_raw(("2",), component=Microscopy.Site), ), consumer_variable_components=(), ), @@ -2236,7 +2247,7 @@ def test_cellprofiler_adapter_uses_grouped_input_when_consumer_group_is_differen path=image_path, artifact_type=ImageArtifactType, group_keys=("1", "2"), - group_component=AllComponents.SITE, + group_component=Microscopy.Site, paths_by_group={ "1": "/memory/A01_w1_Mito.pkl", "2": "/memory/A01_w2_Mito.pkl", @@ -2266,27 +2277,27 @@ def test_cellprofiler_adapter_uses_grouped_input_when_consumer_group_is_differen path=image_path, artifact_type=ImageArtifactType, group_keys=("1", "2"), - group_component=AllComponents.SITE, + group_component=Microscopy.Site, paths_by_group={ "1": "/memory/A01_w1_Mito.pkl", "2": "/memory/A01_w2_Mito.pkl", }, ), invocation_scope=ComponentGroupScope.from_raw( - ("1",), component=AllComponents.CHANNEL + ("1",), component=Microscopy.Channel ), producer_selection_scope=ComponentGroupScope.from_raw( - ("1", "2"), component=AllComponents.SITE + ("1", "2"), component=Microscopy.Site ), component_scopes=( ComponentGroupScope.from_raw( - ("1",), component=AllComponents.CHANNEL + ("1",), component=Microscopy.Channel ), ComponentGroupScope.from_raw( - ("1", "2"), component=AllComponents.SITE + ("1", "2"), component=Microscopy.Site ), ), - consumer_variable_components=(AllComponents.SITE,), + consumer_variable_components=(Microscopy.Site,), ), ) } @@ -2296,7 +2307,7 @@ def test_cellprofiler_adapter_uses_grouped_input_when_consumer_group_is_differen group_key="1", artifact_inputs=_compiled_artifact_inputs, filemanager=filemanager, - variable_components=(VariableComponents.SITE,), + variable_components=(Microscopy.Site,), callable_contract=_compiled_callable_contract( calculate_math, artifact_inputs=tuple( @@ -2343,13 +2354,13 @@ def test_cellprofiler_adapter_does_not_project_channel_stack_for_site_group(): path=image_path, artifact_type=ImageArtifactType, group_keys=(None,), - variable_components=(AllComponents.CHANNEL,), + variable_components=(Microscopy.Channel,), paths_by_group={None: image_path}, ), ), ), filemanager=filemanager, - variable_components=(VariableComponents.CHANNEL,), + variable_components=(Microscopy.Channel,), ) producer.add_image( image_name, @@ -2378,19 +2389,19 @@ def test_cellprofiler_adapter_does_not_project_channel_stack_for_site_group(): artifact_type=ImageArtifactType, group_keys=(None,), paths_by_group={None: image_path}, - variable_components=(AllComponents.CHANNEL,), + variable_components=(Microscopy.Channel,), ), invocation_scope=ComponentGroupScope.from_raw( - ("2",), component=AllComponents.SITE + ("2",), component=Microscopy.Site ), producer_selection_scope=ComponentGroupScope.ungrouped(), component_scopes=( - ComponentGroupScope.from_raw(("2",), component=AllComponents.SITE), + ComponentGroupScope.from_raw(("2",), component=Microscopy.Site), ComponentGroupScope.from_raw( - ("1", "2"), component=AllComponents.CHANNEL + ("1", "2"), component=Microscopy.Channel ), ), - consumer_variable_components=(AllComponents.CHANNEL,), + consumer_variable_components=(Microscopy.Channel,), ), ) } @@ -2401,7 +2412,7 @@ def test_cellprofiler_adapter_does_not_project_channel_stack_for_site_group(): plane_projection=RuntimePlaneProjection.selected(1, 2), artifact_inputs=_compiled_artifact_inputs, filemanager=filemanager, - variable_components=(VariableComponents.CHANNEL,), + variable_components=(Microscopy.Channel,), callable_contract=_compiled_callable_contract( calculate_math, artifact_inputs=tuple( @@ -2442,7 +2453,7 @@ def test_cellprofiler_adapter_projects_stack_without_replacing_artifact_provenan path=image_path, artifact_type=ImageArtifactType, group_keys=(None,), - variable_components=(AllComponents.SITE,), + variable_components=(Microscopy.Site,), paths_by_group={None: image_path}, ), ), @@ -2486,14 +2497,14 @@ def test_cellprofiler_adapter_projects_stack_without_replacing_artifact_provenan artifact_type=ImageArtifactType, group_keys=(None,), paths_by_group={None: image_path}, - variable_components=(AllComponents.SITE,), + variable_components=(Microscopy.Site,), ), invocation_scope=ComponentGroupScope.from_raw( - ("2",), component=AllComponents.SITE + ("2",), component=Microscopy.Site ), producer_selection_scope=ComponentGroupScope.ungrouped(), component_scopes=( - ComponentGroupScope.from_raw(("2",), component=AllComponents.SITE), + ComponentGroupScope.from_raw(("2",), component=Microscopy.Site), ), consumer_variable_components=(), ), @@ -2545,7 +2556,7 @@ def test_cellprofiler_adapter_does_not_select_image_record_from_current_source_s path="/memory/Mito.pkl", artifact_type=ImageArtifactType, group_keys=("1", "2"), - group_component=AllComponents.SITE, + group_component=Microscopy.Site, paths_by_group=image_paths, ) for group_key, site, value in ( @@ -2581,19 +2592,19 @@ def test_cellprofiler_adapter_does_not_select_image_record_from_current_source_s path="/memory/Mito.pkl", artifact_type=ImageArtifactType, group_keys=("1", "2"), - group_component=AllComponents.SITE, + group_component=Microscopy.Site, paths_by_group=image_paths, ), invocation_scope=ComponentGroupScope.ungrouped(), producer_selection_scope=ComponentGroupScope.from_raw( - ("1", "2"), component=AllComponents.SITE + ("1", "2"), component=Microscopy.Site ), component_scopes=( ComponentGroupScope.from_raw( - ("1", "2"), component=AllComponents.SITE + ("1", "2"), component=Microscopy.Site ), ), - consumer_variable_components=(AllComponents.SITE,), + consumer_variable_components=(Microscopy.Site,), ), ) } @@ -2602,7 +2613,7 @@ def test_cellprofiler_adapter_does_not_select_image_record_from_current_source_s axis_scope=runtime_axis_scope(AXIS_ID), artifact_inputs=_compiled_artifact_inputs, filemanager=filemanager, - variable_components=(VariableComponents.SITE,), + variable_components=(Microscopy.Site,), callable_contract=_compiled_callable_contract( calculate_math, artifact_inputs=tuple( @@ -2652,7 +2663,7 @@ def test_cellprofiler_adapter_keeps_template_scoped_object_records_grouped(): store = RuntimeValueStore() outputs = { NUCLEI: _plan( - NUCLEI, ObjectLabelsArtifactType, group_component=AllComponents.SITE + NUCLEI, ObjectLabelsArtifactType, group_component=Microscopy.Site ) } output_bindings = ( @@ -2694,14 +2705,14 @@ def test_cellprofiler_adapter_keeps_template_scoped_object_records_grouped(): name=NUCLEI, path=outputs[NUCLEI].path, artifact_type=ObjectLabelsArtifactType, - group_component=AllComponents.SITE, + group_component=Microscopy.Site, ), invocation_scope=ComponentGroupScope.ungrouped(), producer_selection_scope=ComponentGroupScope.dynamic( - AllComponents.SITE + Microscopy.Site ), - component_scopes=(ComponentGroupScope.dynamic(AllComponents.SITE),), - consumer_variable_components=(AllComponents.SITE,), + component_scopes=(ComponentGroupScope.dynamic(Microscopy.Site),), + consumer_variable_components=(Microscopy.Site,), ), ) } @@ -2710,7 +2721,7 @@ def test_cellprofiler_adapter_keeps_template_scoped_object_records_grouped(): runtime_value_store=store, axis_scope=runtime_axis_scope(AXIS_ID), artifact_inputs=_compiled_artifact_inputs, - variable_components=(VariableComponents.SITE,), + variable_components=(Microscopy.Site,), filemanager=filemanager, callable_contract=_compiled_callable_contract( calculate_math, @@ -3020,7 +3031,7 @@ def test_cellprofiler_adapter_availability_accepts_grouped_runtime_inputs(): path=path, artifact_type=ObjectLabelsArtifactType, group_keys=(group_key,), - group_component=AllComponents.SITE, + group_component=Microscopy.Site, paths_by_group={group_key: path}, ), ), @@ -3044,19 +3055,19 @@ def test_cellprofiler_adapter_availability_accepts_grouped_runtime_inputs(): path="/memory/Nuclei.pkl", artifact_type=ObjectLabelsArtifactType, group_keys=tuple(group_paths), - group_component=AllComponents.SITE, + group_component=Microscopy.Site, paths_by_group=group_paths, ), invocation_scope=ComponentGroupScope.ungrouped(), producer_selection_scope=ComponentGroupScope.from_raw( - ("1", "2"), component=AllComponents.SITE + ("1", "2"), component=Microscopy.Site ), component_scopes=( ComponentGroupScope.from_raw( - ("1", "2"), component=AllComponents.SITE + ("1", "2"), component=Microscopy.Site ), ), - consumer_variable_components=(AllComponents.SITE,), + consumer_variable_components=(Microscopy.Site,), ), ) } @@ -3066,7 +3077,7 @@ def test_cellprofiler_adapter_availability_accepts_grouped_runtime_inputs(): axis_scope=runtime_axis_scope(AXIS_ID), artifact_inputs=_compiled_artifact_inputs, filemanager=filemanager, - variable_components=(VariableComponents.SITE,), + variable_components=(Microscopy.Site,), callable_contract=_compiled_callable_contract( calculate_math, artifact_inputs=tuple( @@ -3099,7 +3110,7 @@ def test_cellprofiler_adapter_discovers_single_realized_dynamic_grouped_input(): path=realized_path, artifact_type=ObjectLabelsArtifactType, group_keys=("1",), - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, paths_by_group={"1": realized_path}, ), ), @@ -3123,15 +3134,15 @@ def test_cellprofiler_adapter_discovers_single_realized_dynamic_grouped_input(): path="/memory/Nuclei.pkl", artifact_type=ObjectLabelsArtifactType, group_keys=(None,), - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, paths_by_group={"1": realized_path}, ), invocation_scope=ComponentGroupScope.ungrouped(), producer_selection_scope=ComponentGroupScope.dynamic( - AllComponents.CHANNEL + Microscopy.Channel ), - component_scopes=(ComponentGroupScope.dynamic(AllComponents.CHANNEL),), - consumer_variable_components=(AllComponents.CHANNEL,), + component_scopes=(ComponentGroupScope.dynamic(Microscopy.Channel),), + consumer_variable_components=(Microscopy.Channel,), ), ) } @@ -3141,7 +3152,7 @@ def test_cellprofiler_adapter_discovers_single_realized_dynamic_grouped_input(): axis_scope=runtime_axis_scope(AXIS_ID), artifact_inputs=_compiled_artifact_inputs, filemanager=filemanager, - variable_components=(VariableComponents.CHANNEL,), + variable_components=(Microscopy.Channel,), callable_contract=_compiled_callable_contract( calculate_math, artifact_inputs=tuple( @@ -3201,7 +3212,7 @@ def test_cellprofiler_adapter_discovers_realized_dynamic_grouped_object_inputs() path=group_paths[group_key], artifact_type=ObjectLabelsArtifactType, group_keys=(group_key,), - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, paths_by_group={group_key: group_paths[group_key]}, ), ), @@ -3227,15 +3238,15 @@ def test_cellprofiler_adapter_discovers_realized_dynamic_grouped_object_inputs() path="/memory/Cells.pkl", artifact_type=ObjectLabelsArtifactType, group_keys=(None,), - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, paths_by_group=group_paths, ), invocation_scope=ComponentGroupScope.ungrouped(), producer_selection_scope=ComponentGroupScope.dynamic( - AllComponents.CHANNEL + Microscopy.Channel ), - component_scopes=(ComponentGroupScope.dynamic(AllComponents.CHANNEL),), - consumer_variable_components=(AllComponents.CHANNEL,), + component_scopes=(ComponentGroupScope.dynamic(Microscopy.Channel),), + consumer_variable_components=(Microscopy.Channel,), ), ) } @@ -3245,7 +3256,7 @@ def test_cellprofiler_adapter_discovers_realized_dynamic_grouped_object_inputs() axis_scope=runtime_axis_scope(AXIS_ID), artifact_inputs=_compiled_artifact_inputs, filemanager=filemanager, - variable_components=(VariableComponents.CHANNEL,), + variable_components=(Microscopy.Channel,), callable_contract=_compiled_callable_contract( calculate_math, artifact_inputs=tuple( @@ -3288,7 +3299,7 @@ def test_cellprofiler_adapter_composes_object_input_across_declared_site_axis(): path=group_paths[group_key], artifact_type=ObjectLabelsArtifactType, group_keys=(group_key,), - group_component=AllComponents.SITE, + group_component=Microscopy.Site, paths_by_group={group_key: group_paths[group_key]}, ), ), @@ -3314,19 +3325,19 @@ def test_cellprofiler_adapter_composes_object_input_across_declared_site_axis(): path="/memory/Nuclei.pkl", artifact_type=ObjectLabelsArtifactType, group_keys=("1", "2"), - group_component=AllComponents.SITE, + group_component=Microscopy.Site, paths_by_group=group_paths, ), invocation_scope=ComponentGroupScope.ungrouped(), producer_selection_scope=ComponentGroupScope.from_raw( - ("1", "2"), component=AllComponents.SITE + ("1", "2"), component=Microscopy.Site ), component_scopes=( ComponentGroupScope.from_raw( - ("1", "2"), component=AllComponents.SITE + ("1", "2"), component=Microscopy.Site ), ), - consumer_variable_components=(AllComponents.SITE,), + consumer_variable_components=(Microscopy.Site,), ), ) } @@ -3336,7 +3347,7 @@ def test_cellprofiler_adapter_composes_object_input_across_declared_site_axis(): axis_scope=runtime_axis_scope(AXIS_ID), artifact_inputs=_compiled_artifact_inputs, filemanager=filemanager, - variable_components=(VariableComponents.SITE,), + variable_components=(Microscopy.Site,), callable_contract=_compiled_callable_contract( calculate_math, artifact_inputs=tuple( @@ -3381,7 +3392,7 @@ def test_cellprofiler_adapter_does_not_resolve_object_input_from_source_context( path=group_paths[group_key], artifact_type=ObjectLabelsArtifactType, group_keys=(group_key,), - group_component=AllComponents.SITE, + group_component=Microscopy.Site, paths_by_group={group_key: group_paths[group_key]}, ), ), @@ -3408,19 +3419,19 @@ def test_cellprofiler_adapter_does_not_resolve_object_input_from_source_context( path="/memory/Nuclei.pkl", artifact_type=ObjectLabelsArtifactType, group_keys=("1", "2"), - group_component=AllComponents.SITE, + group_component=Microscopy.Site, paths_by_group=group_paths, ), invocation_scope=ComponentGroupScope.ungrouped(), producer_selection_scope=ComponentGroupScope.from_raw( - ("1", "2"), component=AllComponents.SITE + ("1", "2"), component=Microscopy.Site ), component_scopes=( ComponentGroupScope.from_raw( - ("1", "2"), component=AllComponents.SITE + ("1", "2"), component=Microscopy.Site ), ), - consumer_variable_components=(AllComponents.SITE,), + consumer_variable_components=(Microscopy.Site,), ), ) } @@ -3430,7 +3441,7 @@ def test_cellprofiler_adapter_does_not_resolve_object_input_from_source_context( artifact_inputs=_compiled_artifact_inputs, microscope_handler=(ContextStub(filemanager)).microscope_handler, filemanager=filemanager, - variable_components=(VariableComponents.SITE,), + variable_components=(Microscopy.Site,), callable_contract=_compiled_callable_contract( calculate_math, artifact_inputs=tuple( @@ -3463,7 +3474,7 @@ def test_cellprofiler_adapter_preserves_ungrouped_runtime_slice_output_stack(): name=NUCLEI, path="/memory/Nuclei.pkl", artifact_type=ObjectLabelsArtifactType, - variable_components=(AllComponents.SITE,), + variable_components=(Microscopy.Site,), ), ), ), @@ -3497,16 +3508,16 @@ def test_cellprofiler_adapter_preserves_ungrouped_runtime_slice_output_stack(): name=NUCLEI, path="/memory/Nuclei.pkl", artifact_type=ObjectLabelsArtifactType, - variable_components=(AllComponents.SITE,), + variable_components=(Microscopy.Site,), ), invocation_scope=ComponentGroupScope.ungrouped(), producer_selection_scope=ComponentGroupScope.ungrouped(), component_scopes=( ComponentGroupScope.from_raw( - ("1", "2"), component=AllComponents.SITE + ("1", "2"), component=Microscopy.Site ), ), - consumer_variable_components=(AllComponents.SITE,), + consumer_variable_components=(Microscopy.Site,), ), ) } @@ -3516,7 +3527,7 @@ def test_cellprofiler_adapter_preserves_ungrouped_runtime_slice_output_stack(): axis_scope=runtime_axis_scope(AXIS_ID), artifact_inputs=_compiled_artifact_inputs, filemanager=filemanager, - variable_components=(VariableComponents.SITE,), + variable_components=(Microscopy.Site,), callable_contract=_compiled_callable_contract( calculate_math, artifact_inputs=tuple( @@ -3553,7 +3564,7 @@ def test_cellprofiler_adapter_stacks_dynamic_compiled_grouped_images(): path=group_paths["1"], artifact_type=ImageArtifactType, group_keys=("1",), - group_component=AllComponents.SITE, + group_component=Microscopy.Site, paths_by_group={"1": group_paths["1"]}, ), ), @@ -3573,7 +3584,7 @@ def test_cellprofiler_adapter_stacks_dynamic_compiled_grouped_images(): path=group_paths["2"], artifact_type=ImageArtifactType, group_keys=("2",), - group_component=AllComponents.SITE, + group_component=Microscopy.Site, paths_by_group={"2": group_paths["2"]}, ), ), @@ -3591,15 +3602,15 @@ def test_cellprofiler_adapter_stacks_dynamic_compiled_grouped_images(): path="/memory/DNA.pkl", artifact_type=ImageArtifactType, group_keys=(None,), - group_component=AllComponents.SITE, + group_component=Microscopy.Site, paths_by_group=group_paths, ), invocation_scope=ComponentGroupScope.ungrouped(), producer_selection_scope=ComponentGroupScope.dynamic( - AllComponents.SITE + Microscopy.Site ), - component_scopes=(ComponentGroupScope.dynamic(AllComponents.SITE),), - consumer_variable_components=(AllComponents.SITE,), + component_scopes=(ComponentGroupScope.dynamic(Microscopy.Site),), + consumer_variable_components=(Microscopy.Site,), ), ) } @@ -3609,7 +3620,7 @@ def test_cellprofiler_adapter_stacks_dynamic_compiled_grouped_images(): axis_scope=runtime_axis_scope(AXIS_ID), artifact_inputs=_compiled_artifact_inputs, filemanager=filemanager, - variable_components=(VariableComponents.SITE,), + variable_components=(Microscopy.Site,), callable_contract=_compiled_callable_contract( calculate_math, artifact_inputs=tuple( @@ -3772,7 +3783,7 @@ def test_cellprofiler_adapter_relationships_accept_grouped_parent_inputs(): path="/memory/Cells_s1.pkl", artifact_type=ObjectLabelsArtifactType, group_keys=("1",), - group_component=AllComponents.SITE, + group_component=Microscopy.Site, paths_by_group={"1": "/memory/Cells_s1.pkl"}, ), ), @@ -3792,7 +3803,7 @@ def test_cellprofiler_adapter_relationships_accept_grouped_parent_inputs(): path="/memory/Cells_s2.pkl", artifact_type=ObjectLabelsArtifactType, group_keys=("2",), - group_component=AllComponents.SITE, + group_component=Microscopy.Site, paths_by_group={"2": "/memory/Cells_s2.pkl"}, ), ), @@ -4151,7 +4162,7 @@ def test_cellprofiler_adapter_uses_static_output_scope(): path=output_path, artifact_type=ObjectLabelsArtifactType, group_keys=("3",), - group_component=AllComponents.SITE, + group_component=Microscopy.Site, paths_by_group={"3": output_path}, ), ), @@ -4310,7 +4321,7 @@ def test_cellprofiler_adapter_does_not_select_measurement_record_from_current_so path=object_group_paths[group_key], artifact_type=ObjectLabelsArtifactType, group_keys=(group_key,), - group_component=AllComponents.SITE, + group_component=Microscopy.Site, paths_by_group={group_key: object_group_paths[group_key]}, ), ), @@ -4322,7 +4333,7 @@ def test_cellprofiler_adapter_does_not_select_measurement_record_from_current_so path=group_paths[group_key], artifact_type=MeasurementsArtifactType, group_keys=(group_key,), - group_component=AllComponents.SITE, + group_component=Microscopy.Site, paths_by_group={group_key: group_paths[group_key]}, ), ), @@ -4359,19 +4370,19 @@ def test_cellprofiler_adapter_does_not_select_measurement_record_from_current_so path="/memory/NucleiMeasurements.pkl", artifact_type=MeasurementsArtifactType, group_keys=("1", "2"), - group_component=AllComponents.SITE, + group_component=Microscopy.Site, paths_by_group=group_paths, ), invocation_scope=ComponentGroupScope.ungrouped(), producer_selection_scope=ComponentGroupScope.from_raw( - ("1", "2"), component=AllComponents.SITE + ("1", "2"), component=Microscopy.Site ), component_scopes=( ComponentGroupScope.from_raw( - ("1", "2"), component=AllComponents.SITE + ("1", "2"), component=Microscopy.Site ), ), - consumer_variable_components=(AllComponents.SITE,), + consumer_variable_components=(Microscopy.Site,), ), ) } @@ -4381,7 +4392,7 @@ def test_cellprofiler_adapter_does_not_select_measurement_record_from_current_so artifact_inputs=_compiled_artifact_inputs, microscope_handler=(ContextStub(filemanager)).microscope_handler, filemanager=filemanager, - variable_components=(VariableComponents.SITE,), + variable_components=(Microscopy.Site,), callable_contract=_compiled_callable_contract( calculate_math, artifact_inputs=tuple( @@ -4660,7 +4671,7 @@ def test_declared_measurement_inputs_require_producer_declared_slice_indexes(): name=MEASUREMENTS, path=f"/memory/{MEASUREMENTS}.pkl", artifact_type=MeasurementsArtifactType, - group_component=AllComponents.SITE, + group_component=Microscopy.Site, group_keys=tuple(group_paths), paths_by_group=group_paths, ) @@ -4668,7 +4679,7 @@ def test_declared_measurement_inputs_require_producer_declared_slice_indexes(): group_key = str(index) producer = cellprofiler_runtime_adapter_for_test( runtime_value_store=store, - axis_scope=runtime_axis_scope(AXIS_ID, AllComponents.SITE, group_key), + axis_scope=runtime_axis_scope(AXIS_ID, Microscopy.Site.name, group_key), artifact_output_bindings=( _output_binding( MEASUREMENTS, @@ -4710,7 +4721,7 @@ def test_declared_measurement_inputs_require_producer_declared_slice_indexes(): consumer = cellprofiler_runtime_adapter_for_test( runtime_value_store=store, callable_contract=contract, - axis_scope=runtime_axis_scope(AXIS_ID, AllComponents.CHANNEL, "1"), + axis_scope=runtime_axis_scope(AXIS_ID, Microscopy.Channel.name, "1"), artifact_inputs={ edge.key: edge for edge in ( @@ -4719,30 +4730,30 @@ def test_declared_measurement_inputs_require_producer_declared_slice_indexes(): name=MEASUREMENTS, path=output_plan.path, artifact_type=MeasurementsArtifactType, - group_component=AllComponents.SITE, + group_component=Microscopy.Site, group_keys=output_plan.group_keys, paths_by_group=output_plan.paths_by_group, ), invocation_scope=ComponentGroupScope.from_raw( - ("1",), component=AllComponents.CHANNEL + ("1",), component=Microscopy.Channel ), producer_selection_scope=ComponentGroupScope.from_raw( - output_plan.group_keys, component=AllComponents.SITE + output_plan.group_keys, component=Microscopy.Site ), component_scopes=( ComponentGroupScope.from_raw( - ("1",), component=AllComponents.CHANNEL + ("1",), component=Microscopy.Channel ), ComponentGroupScope.from_raw( - output_plan.group_keys, component=AllComponents.SITE + output_plan.group_keys, component=Microscopy.Site ), ), - consumer_variable_components=(AllComponents.SITE,), + consumer_variable_components=(Microscopy.Site,), ), ) }, artifact_outputs={}, - variable_components=(VariableComponents.SITE,), + variable_components=(Microscopy.Site,), source_binding_plan=source_binding_plan, filemanager=filemanager, ) @@ -4763,12 +4774,12 @@ def test_cellprofiler_adapter_aligns_multiplane_measurements_across_groups(): filemanager = FileManagerStub() outputs = { NUCLEI: _plan( - NUCLEI, ObjectLabelsArtifactType, group_component=AllComponents.SITE + NUCLEI, ObjectLabelsArtifactType, group_component=Microscopy.Site ), NUCLEI_MEASUREMENTS: _plan( NUCLEI_MEASUREMENTS, MeasurementsArtifactType, - group_component=AllComponents.SITE, + group_component=Microscopy.Site, ), } output_bindings = ( @@ -4833,14 +4844,14 @@ def test_cellprofiler_adapter_aligns_multiplane_measurements_across_groups(): name=NUCLEI_MEASUREMENTS, path=outputs[NUCLEI_MEASUREMENTS].path, artifact_type=MeasurementsArtifactType, - group_component=AllComponents.SITE, + group_component=Microscopy.Site, ), invocation_scope=ComponentGroupScope.ungrouped(), producer_selection_scope=ComponentGroupScope.dynamic( - AllComponents.SITE + Microscopy.Site ), - component_scopes=(ComponentGroupScope.dynamic(AllComponents.SITE),), - consumer_variable_components=(AllComponents.SITE,), + component_scopes=(ComponentGroupScope.dynamic(Microscopy.Site),), + consumer_variable_components=(Microscopy.Site,), ), ) } @@ -4854,7 +4865,7 @@ def test_cellprofiler_adapter_aligns_multiplane_measurements_across_groups(): filemanager=filemanager, group_key="collapsed", plane_projection=RuntimePlaneProjection.stack(2), - variable_components=(VariableComponents.SITE,), + variable_components=(Microscopy.Site,), callable_contract=_compiled_callable_contract( calculate_math, artifact_inputs=tuple( @@ -5194,7 +5205,7 @@ def test_cellprofiler_adapter_multiplane_measurement_alignment_is_feature_scoped NUCLEI_MEASUREMENTS: _plan( NUCLEI_MEASUREMENTS, MeasurementsArtifactType, - group_component=AllComponents.SITE, + group_component=Microscopy.Site, ), } output_bindings = ( @@ -5261,14 +5272,14 @@ def test_cellprofiler_adapter_multiplane_measurement_alignment_is_feature_scoped name=NUCLEI_MEASUREMENTS, path=outputs[NUCLEI_MEASUREMENTS].path, artifact_type=MeasurementsArtifactType, - group_component=AllComponents.SITE, + group_component=Microscopy.Site, ), invocation_scope=ComponentGroupScope.ungrouped(), producer_selection_scope=ComponentGroupScope.dynamic( - AllComponents.SITE + Microscopy.Site ), - component_scopes=(ComponentGroupScope.dynamic(AllComponents.SITE),), - consumer_variable_components=(AllComponents.SITE,), + component_scopes=(ComponentGroupScope.dynamic(Microscopy.Site),), + consumer_variable_components=(Microscopy.Site,), ), ) } @@ -5282,7 +5293,7 @@ def test_cellprofiler_adapter_multiplane_measurement_alignment_is_feature_scoped filemanager=filemanager, group_key="collapsed", plane_projection=RuntimePlaneProjection.stack(2), - variable_components=(VariableComponents.SITE,), + variable_components=(Microscopy.Site,), callable_contract=_compiled_callable_contract( calculate_math, artifact_inputs=tuple( @@ -7031,7 +7042,7 @@ def test_relationship_plane_records_use_compiled_input_projection_order(): path=group_paths[group_key], artifact_type=RelationshipsArtifactType, group_keys=(group_key,), - group_component=AllComponents.SITE, + group_component=Microscopy.Site, paths_by_group={group_key: group_paths[group_key]}, ), relationship, @@ -7047,19 +7058,19 @@ def test_relationship_plane_records_use_compiled_input_projection_order(): path="/memory/relationships.pkl", artifact_type=RelationshipsArtifactType, group_keys=("site_a", "site_b"), - group_component=AllComponents.SITE, + group_component=Microscopy.Site, paths_by_group=group_paths, ), invocation_scope=ComponentGroupScope.ungrouped(), producer_selection_scope=ComponentGroupScope.from_raw( - ("site_a", "site_b"), component=AllComponents.SITE + ("site_a", "site_b"), component=Microscopy.Site ), component_scopes=( ComponentGroupScope.from_raw( - ("site_a", "site_b"), component=AllComponents.SITE + ("site_a", "site_b"), component=Microscopy.Site ), ), - consumer_variable_components=(AllComponents.SITE,), + consumer_variable_components=(Microscopy.Site,), ), ) } @@ -7067,7 +7078,7 @@ def test_relationship_plane_records_use_compiled_input_projection_order(): runtime_value_store=store, axis_scope=runtime_axis_scope(AXIS_ID), artifact_inputs=_compiled_artifact_inputs, - variable_components=(VariableComponents.SITE,), + variable_components=(Microscopy.Site,), callable_contract=_compiled_callable_contract( calculate_math, artifact_inputs=tuple( @@ -7500,7 +7511,7 @@ def test_adapter_measurement_vector_scope_rejects_undeclared_axis_table(): NUCLEI, ObjectLabelsArtifactType, plan=_plan( - NUCLEI, ObjectLabelsArtifactType, group_component=AllComponents.SITE + NUCLEI, ObjectLabelsArtifactType, group_component=Microscopy.Site ), ), _output_binding( @@ -7509,7 +7520,7 @@ def test_adapter_measurement_vector_scope_rejects_undeclared_axis_table(): plan=_plan( MEASUREMENTS, MeasurementsArtifactType, - group_component=AllComponents.SITE, + group_component=Microscopy.Site, ), ), ), diff --git a/tests/unit/test_cellprofiler_runtime_callable_introspection.py b/tests/unit/test_cellprofiler_runtime_callable_introspection.py index e9fa7ef811..dc0096cd3a 100644 --- a/tests/unit/test_cellprofiler_runtime_callable_introspection.py +++ b/tests/unit/test_cellprofiler_runtime_callable_introspection.py @@ -8,7 +8,6 @@ import pytest -from openhcs.constants.constants import AllComponents, VariableComponents from openhcs.constants.input_source import InputSource from openhcs.core.compiled_step_plan import CompiledStepPlan from openhcs.core.config import ( @@ -50,6 +49,7 @@ mask_objects, save_images, ) +from openhcs.domains.microscopy.axes import Microscopy def _compilation_session_for_steps( @@ -124,7 +124,7 @@ def test_imported_function_step_values_remain_signature_diffs_in_object_state(): enabled=False, debug_pause=True, processing_config=LazyProcessingConfig( - variable_components=[VariableComponents.SITE], + variable_components=[Microscopy.Site], input_source=InputSource.PIPELINE_START, ), ), @@ -138,7 +138,7 @@ def test_imported_function_step_values_remain_signature_diffs_in_object_state(): assert state.parameters["debug_pause"] is True assert state._signature_defaults["debug_pause"] is False assert state.parameters["processing_config.variable_components"] == [ - VariableComponents.SITE + Microscopy.Site ] assert state._signature_defaults["processing_config.variable_components"] is None assert ( @@ -421,12 +421,12 @@ def test_cellprofiler_compile_time_contract_provider_scopes_grouped_source_bindi NamedSourceBinding( alias="OrigStain1", artifact_kind=ImageArtifactType, - component_identity=(ComponentSelector(AllComponents.CHANNEL, "1"),), + component_identity=(ComponentSelector(Microscopy.Channel, "1"),), ), NamedSourceBinding( alias="OrigStain2", artifact_kind=ImageArtifactType, - component_identity=(ComponentSelector(AllComponents.CHANNEL, "2"),), + component_identity=(ComponentSelector(Microscopy.Channel, "2"),), ), ), ) @@ -475,12 +475,12 @@ def test_compile_time_provider_derives_group_contracts_from_public_pattern_after NamedSourceBinding( alias="OrigStain1", artifact_kind=ImageArtifactType, - component_identity=(ComponentSelector(AllComponents.CHANNEL, "1"),), + component_identity=(ComponentSelector(Microscopy.Channel, "1"),), ), NamedSourceBinding( alias="OrigStain2", artifact_kind=ImageArtifactType, - component_identity=(ComponentSelector(AllComponents.CHANNEL, "2"),), + component_identity=(ComponentSelector(Microscopy.Channel, "2"),), ), ), ) diff --git a/tests/unit/test_cellprofiler_runtime_input_binding_contract.py b/tests/unit/test_cellprofiler_runtime_input_binding_contract.py index 12b438abf9..343cb53c7b 100644 --- a/tests/unit/test_cellprofiler_runtime_input_binding_contract.py +++ b/tests/unit/test_cellprofiler_runtime_input_binding_contract.py @@ -8,7 +8,7 @@ import numpy as np import pytest -from openhcs.constants.constants import AllComponents, Backend +from openhcs.constants.constants import Backend from openhcs.core.artifacts import ( ArtifactInputPlan, ArtifactOutputPlan, @@ -49,6 +49,7 @@ cellprofiler_runtime_adapter_for_test, cellprofiler_runtime_input_edge_for_test, ) +from openhcs.domains.microscopy.axes import Microscopy def _contract(func, inputs: tuple[ArtifactSpec, ...] = ()) -> CallableContract: @@ -237,7 +238,7 @@ def consume(image: np.ndarray, mask: np.ndarray) -> np.ndarray: invocation_scope=ComponentGroupScope.ungrouped(), producer_selection_scope=ComponentGroupScope.ungrouped(), component_scopes=(), - consumer_variable_components=(AllComponents.Z_INDEX,), + consumer_variable_components=(Microscopy.ZIndex,), ) mask_plane_metadata = tuple( { @@ -293,8 +294,8 @@ def consume(image: np.ndarray, mask: np.ndarray) -> np.ndarray: ).payload_with(np.zeros((3, 2, 2), dtype=np.float32), None) source_binding_plan = CompiledSourceBindingPlan( source_stack_components=( - AllComponents.CHANNEL, - AllComponents.Z_INDEX, + Microscopy.Channel, + Microscopy.ZIndex, ) ) stack_adapter = cellprofiler_runtime_adapter_for_test( @@ -400,7 +401,7 @@ def consume(image: np.ndarray, mask: np.ndarray) -> np.ndarray: invocation_scope=ComponentGroupScope.ungrouped(), producer_selection_scope=ComponentGroupScope.ungrouped(), component_scopes=(), - consumer_variable_components=(AllComponents.Z_INDEX,), + consumer_variable_components=(Microscopy.ZIndex,), ) mask_payload = ImagePayloadMetadata( source_image_names=(mask.name,), @@ -457,8 +458,8 @@ def consume(image: np.ndarray, mask: np.ndarray) -> np.ndarray: plane_projection=RuntimePlaneProjection.stack(3), source_binding_plan=CompiledSourceBindingPlan( source_stack_components=( - AllComponents.CHANNEL, - AllComponents.Z_INDEX, + Microscopy.Channel, + Microscopy.ZIndex, ) ), ) diff --git a/tests/unit/test_cellprofiler_save_images.py b/tests/unit/test_cellprofiler_save_images.py index 16a75fe155..af1fb97890 100644 --- a/tests/unit/test_cellprofiler_save_images.py +++ b/tests/unit/test_cellprofiler_save_images.py @@ -9,7 +9,6 @@ import numpy as np import pytest -from openhcs.constants.constants import AllComponents from openhcs.core.artifacts import ( ArtifactInputPlan, ArtifactOutputPlan, @@ -85,6 +84,7 @@ ) from polystore.filemanager import FileManager from polystore.memory import MemoryStorageBackend +from openhcs.domains.microscopy.axes import Microscopy def _module(**settings: str) -> ModuleBlock: @@ -949,7 +949,7 @@ def test_image_output_context_projects_declared_group_lineage_source() -> None: name="SavedRGB", path="/memory/SavedRGB.pkl", artifact_type=ImageArtifactType, - variable_components=(AllComponents.SITE,), + variable_components=(Microscopy.Site,), relations=( GroupLineageSourceRelation( source=ArtifactSpec.input("OrigBlue", ImageArtifactType).ref(), @@ -1029,7 +1029,7 @@ def test_declared_group_lineage_source_overrides_complete_output_identity() -> N name="SavedRGB", path="/memory/SavedRGB.pkl", artifact_type=ImageArtifactType, - variable_components=(AllComponents.SITE,), + variable_components=(Microscopy.Site,), relations=( GroupLineageSourceRelation( source=ArtifactSpec.input("OrigBlue", ImageArtifactType).ref(), @@ -1077,7 +1077,7 @@ def test_planned_image_output_restores_axis_without_duplicate_provenance() -> No name="SavedCells", path="/memory/SavedCells.pkl", artifact_type=ImageArtifactType, - variable_components=(AllComponents.Z_INDEX,), + variable_components=(Microscopy.ZIndex,), relations=( GroupLineageSourceRelation( source=ArtifactSpec.input("CellsImage", ImageArtifactType).ref(), diff --git a/tests/unit/test_cellprofiler_source_bindings.py b/tests/unit/test_cellprofiler_source_bindings.py index 06b7a782ad..7508c1e57b 100644 --- a/tests/unit/test_cellprofiler_source_bindings.py +++ b/tests/unit/test_cellprofiler_source_bindings.py @@ -13,7 +13,6 @@ import pytest import openhcs.core.source_bindings as source_bindings_module -from openhcs.constants.constants import AllComponents from openhcs.core.artifacts import ImageArtifactType, ObjectLabelsArtifactType from openhcs.core.config import ( LazySourceBindingsConfig, @@ -53,6 +52,7 @@ ModuleBlock, ModuleSetting, ) +from openhcs.domains.microscopy.axes import Microscopy def _field_names(record_type: type[object]) -> frozenset[str]: @@ -123,7 +123,7 @@ def test_component_group_binding_scope_filters_its_axis_and_broadcasts_others() alias="DNA", component_identity=( ComponentSelector( - component=AllComponents.CHANNEL, + component=Microscopy.Channel, value="1", ), ), @@ -132,7 +132,7 @@ def test_component_group_binding_scope_filters_its_axis_and_broadcasts_others() alias="RNA", component_identity=( ComponentSelector( - component=AllComponents.CHANNEL, + component=Microscopy.Channel, value="2", ), ), @@ -143,19 +143,19 @@ def test_component_group_binding_scope_filters_its_axis_and_broadcasts_others() assert tuple( binding.alias for binding in config.bindings_for_component_group( - AllComponents.CHANNEL, + Microscopy.Channel, "2", ) ) == ("RNA",) assert tuple( binding.alias for binding in config.bindings_for_component_group( - AllComponents.SITE, + Microscopy.Site, "1", ) ) == ("DNA", "RNA") with pytest.raises(ValueError, match="channel|3"): - config.bindings_for_component_group(AllComponents.CHANNEL, "3") + config.bindings_for_component_group(Microscopy.Channel, "3") def test_lazy_source_configs_cover_every_inherited_dataclass_field() -> None: @@ -247,7 +247,7 @@ def test_complete_lazy_setup_facts_pycodify_and_reconstruct_in_fresh_process() - FieldSpec("Dose", float, required=False), FieldSpec("Frame", int, required=False), ), - source_stack_components=(AllComponents.TIMEPOINT,), + source_stack_components=(Microscopy.Timepoint,), grouping_metadata_fields=("Plate", "Well"), source_voxel_spacing=SourceVoxelSpacing((2.0, 1.0, 1.0)), ) @@ -259,7 +259,7 @@ def test_complete_lazy_setup_facts_pycodify_and_reconstruct_in_fresh_process() - script = "\n".join( ( source, - "from openhcs.constants.constants import AllComponents", + "from openhcs.domains.microscopy.axes import Microscopy", "from openhcs.core.artifacts import ObjectLabelsArtifactType", "cfg = pipeline_config.source_bindings_config", "assert cfg.bindings[0].artifact_kind is ObjectLabelsArtifactType", @@ -270,7 +270,7 @@ def test_complete_lazy_setup_facts_pycodify_and_reconstruct_in_fresh_process() - "assert cfg.imported_metadata_tables[0].joins[0].imported_metadata_field == 'WellID'", "assert cfg.metadata_fields[0].dtype is float", "assert cfg.metadata_fields[1].dtype is int", - "assert cfg.source_stack_components == (AllComponents.TIMEPOINT,)", + "assert cfg.source_stack_components == (Microscopy.Timepoint,)", "assert cfg.grouping_metadata_fields == ('Plate', 'Well')", "assert cfg.source_voxel_spacing.values_zyx == (2.0, 1.0, 1.0)", ) @@ -963,7 +963,7 @@ def test_names_and_types_contributes_3d_axis_and_voxel_spacing() -> None: from openhcs.core.source_spatial_domain import VolumeSourceSpatialDomain assert isinstance(config.source_spatial_domain, VolumeSourceSpatialDomain) - assert config.source_stack_components == (AllComponents.Z_INDEX,) + assert config.source_stack_components == (Microscopy.ZIndex,) assert config.source_voxel_spacing.values_zyx == (2.0, 1.0, 0.5) assert config.source_voxel_spacing.unit is SourceVoxelSpacingUnit.RELATIVE diff --git a/tests/unit/test_cellprofiler_source_bindings_ingestion.py b/tests/unit/test_cellprofiler_source_bindings_ingestion.py index 31e3832db2..975d087e9a 100644 --- a/tests/unit/test_cellprofiler_source_bindings_ingestion.py +++ b/tests/unit/test_cellprofiler_source_bindings_ingestion.py @@ -11,7 +11,7 @@ from polystore.filemanager import FileManager from polystore.virtual_workspace import SourcePixelRef -from openhcs.constants.constants import AllComponents, Backend +from openhcs.constants.constants import Backend from openhcs.core.source_binding_context import SourceBindingContext from openhcs.core.source_binding_workspace import SourceBindingWorkspaceProjector from openhcs.core.source_projection import SourceCandidate @@ -28,6 +28,8 @@ SourceFilterSubject, SourceSelector, ) +from openhcs.core.axes import Axis +from openhcs.domains.microscopy.axes import Microscopy def _field_names(record_type: type[object]) -> tuple[str, ...]: @@ -36,7 +38,7 @@ def _field_names(record_type: type[object]) -> tuple[str, ...]: def _two_channel_config( *, - source_stack_components: tuple[AllComponents, ...] = (), + source_stack_components: tuple[type[Axis], ...] = (), ) -> SourceBindingsConfig: return SourceBindingsConfig( metadata_rules=( @@ -66,7 +68,7 @@ def _two_channel_config( ), ), ), - component_identity=(ComponentSelector(AllComponents.CHANNEL, "1"),), + component_identity=(ComponentSelector(Microscopy.Channel, "1"),), ), NamedSourceBinding( alias="RNA", @@ -79,7 +81,7 @@ def _two_channel_config( ), ), ), - component_identity=(ComponentSelector(AllComponents.CHANNEL, "2"),), + component_identity=(ComponentSelector(Microscopy.Channel, "2"),), ), ), source_stack_components=source_stack_components, @@ -116,13 +118,16 @@ def test_source_candidate_owns_one_exact_source_ref() -> None: assert candidate.source_ref is source_ref -def test_component_projection_registry_exactly_covers_all_components() -> None: +def test_component_projection_strategies_cover_every_declared_axis() -> None: + from openhcs.core.axes import AxisFamily from openhcs.core.source_metadata import SourceComponentProjectionStrategy - assert { - registered_type.strategy_key - for registered_type in SourceComponentProjectionStrategy.registered_strategy_types() - } == set(AllComponents) + family = AxisFamily.active() + strategies = { + axis: SourceComponentProjectionStrategy.strategy_type_for_axis(axis) + for axis in family.axes + } + assert len(set(strategies.values())) == len(family.axes) def test_workspace_projection_uses_exact_submitted_root_and_file_universe( @@ -206,8 +211,8 @@ def test_workspace_projection_materializes_complete_declared_universe( assert len(projection_set.projections) == 4 assert { ( - projection.address.value_for(AllComponents.SITE), - projection.address.value_for(AllComponents.CHANNEL), + projection.address.value_for(Microscopy.Site), + projection.address.value_for(Microscopy.Channel), ) for projection in projection_set.projections } == {("1", "1"), ("1", "2"), ("2", "1"), ("2", "2")} @@ -238,12 +243,12 @@ def test_source_stack_expansion_is_declared_by_config(tmp_path: Path) -> None: np.save(rna, np.stack((np.full((4, 4), 3), np.full((4, 4), 4)))) projection_set = SourceBindingWorkspaceProjector( - _two_channel_config(source_stack_components=(AllComponents.TIMEPOINT,)) + _two_channel_config(source_stack_components=(Microscopy.Timepoint,)) ).projection_set(source_root, (dna, rna), filemanager=_filemanager()) assert len(projection_set.projections) == 4 assert { - projection.address.value_for(AllComponents.TIMEPOINT) + projection.address.value_for(Microscopy.Timepoint) for projection in projection_set.projections } == {"1", "2"} assert { diff --git a/tests/unit/test_cellprofiler_spreadsheet_export.py b/tests/unit/test_cellprofiler_spreadsheet_export.py index a1e81097ba..5b5e350610 100644 --- a/tests/unit/test_cellprofiler_spreadsheet_export.py +++ b/tests/unit/test_cellprofiler_spreadsheet_export.py @@ -13,7 +13,6 @@ from polystore.filemanager import FileManager from polystore.memory import MemoryStorageBackend -from openhcs.constants.constants import AllComponents from openhcs.core.artifacts import ( ObjectLabelsArtifactType, ArtifactInputPlan, @@ -106,6 +105,8 @@ materialize, materialization_outputs, ) +from openhcs.core.axes import Axis +from openhcs.domains.microscopy.axes import Microscopy def test_export_to_spreadsheet_declares_exact_plate_callable_abi() -> None: contract = CallableContract.from_callable(export_to_spreadsheet) @@ -733,7 +734,7 @@ def test_export_to_spreadsheet_projects_site_group_scope_without_relabeling_stac "result_value": shift, }, ), - group_component=AllComponents.SITE, + group_component=Microscopy.Site, group_key=site, ) for site, shift in (("1", -1.0), ("2", -2.0)) @@ -765,9 +766,9 @@ def test_export_to_spreadsheet_uses_declared_image_set_identity_across_channels( axis_id="A01", subject=MeasurementSubject(MeasurementScope.IMAGE, "Image"), rows=({"slice_index": 0, "Count": 2},), - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, group_key="1", - variable_components=(AllComponents.SITE,), + variable_components=(Microscopy.Site,), source_image_provenance_planes=SourceImageProvenancePlanes.from_components( component_metadata=({"site": "1", "channel": "1"},) ), @@ -781,9 +782,9 @@ def test_export_to_spreadsheet_uses_declared_image_set_identity_across_channels( "object_number", ), rows=({"slice_index": 0, "object_number": 1, "Area": 4.0},), - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, group_key="2", - variable_components=(AllComponents.SITE,), + variable_components=(Microscopy.Site,), source_image_provenance_planes=SourceImageProvenancePlanes.from_components( component_metadata=({"site": "1", "channel": "2"},) ), @@ -795,7 +796,7 @@ def test_export_to_spreadsheet_uses_declared_image_set_identity_across_channels( ), records_by_axis={"A01": (image_record, object_record)}, source_image_set_identity_policy=SourceImageSetIdentityPolicy( - frozenset((AllComponents.CHANNEL,)) + frozenset((Microscopy.Channel,)) ), ) @@ -826,11 +827,11 @@ def test_export_to_spreadsheet_pairs_fully_addressed_field_measurements() -> Non component_identity=tuple( ComponentSelector(component, value) for component, value in ( - (AllComponents.WELL, "A01"), - (AllComponents.SITE, "1"), - (AllComponents.CHANNEL, channel), - (AllComponents.Z_INDEX, "1"), - (AllComponents.TIMEPOINT, "1"), + (Microscopy.Well, "A01"), + (Microscopy.Site, "1"), + (Microscopy.Channel, channel), + (Microscopy.ZIndex, "1"), + (Microscopy.Timepoint, "1"), ) ), ) @@ -839,7 +840,7 @@ def test_export_to_spreadsheet_pairs_fully_addressed_field_measurements() -> Non ) policy = SourceImageSetIdentityPolicy.from_source_bindings( bindings, - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, ) records = [] # Two independent fields, each with two cells. Local slice/object IDs repeat @@ -873,9 +874,9 @@ def test_export_to_spreadsheet_pairs_fully_addressed_field_measurements() -> Non for number in (1, 2) ), source_image_provenance_planes=provenance, - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, group_key=channel, - variable_components=(AllComponents.SITE,), + variable_components=(Microscopy.Site,), ) ) records.append( @@ -885,9 +886,9 @@ def test_export_to_spreadsheet_pairs_fully_addressed_field_measurements() -> Non subject=MeasurementSubject(MeasurementScope.IMAGE, "Image"), rows=({"slice_index": 0, "Count_Cells": 2},), source_image_provenance_planes=provenance, - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, group_key="2", - variable_components=(AllComponents.SITE,), + variable_components=(Microscopy.Site,), ) ) batch = RuntimeArtifactBatch( @@ -928,9 +929,9 @@ def test_export_to_spreadsheet_nulls_metadata_that_differs_between_image_planes( axis_id="A01", subject=MeasurementSubject(MeasurementScope.IMAGE, "Image"), rows=({"slice_index": 0, f"Count_{channel}": int(channel)},), - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, group_key=channel, - variable_components=(AllComponents.SITE,), + variable_components=(Microscopy.Site,), source_image_provenance_planes=SourceImageProvenancePlanes.from_components( component_metadata=( { @@ -953,7 +954,7 @@ def test_export_to_spreadsheet_nulls_metadata_that_differs_between_image_planes( ), records_by_axis={"A01": records}, source_image_set_identity_policy=SourceImageSetIdentityPolicy( - frozenset((AllComponents.CHANNEL,)) + frozenset((Microscopy.Channel,)) ), ) @@ -1117,9 +1118,9 @@ def test_export_to_spreadsheet_merges_object_features_across_runtime_groups() -> feature_name: value, }, ), - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, group_key=channel, - variable_components=(AllComponents.SITE,), + variable_components=(Microscopy.Site,), source_image_provenance_planes=provenance, ) for name, channel, feature_name, value, provenance in zip( @@ -1138,7 +1139,7 @@ def test_export_to_spreadsheet_merges_object_features_across_runtime_groups() -> ), records_by_axis={"A01": records}, source_image_set_identity_policy=SourceImageSetIdentityPolicy( - frozenset((AllComponents.CHANNEL,)) + frozenset((Microscopy.Channel,)) ), ) @@ -1832,9 +1833,9 @@ def _measurement_record( rows: tuple[dict[str, object], ...] | ColumnarRows, source_image_name: str | None = None, source_image_provenance_planes: SourceImageProvenancePlanes | None = None, - group_component: AllComponents | None = None, + group_component: type[Axis] | None = None, group_key: str | None = None, - variable_components: tuple[AllComponents, ...] = (), + variable_components: tuple[type[Axis], ...] = (), ) -> StoredRuntimeValue: if not isinstance(rows, ColumnarRows): field_names = tuple( @@ -1862,13 +1863,13 @@ def _measurement_record( component_metadata=tuple( { **( - {group_component.value: group_key} + {group_component.name: group_key} if group_component is not None and group_key is not None else {} ), **( - {AllComponents.SITE.value: str(slice_index + 1)} - if group_component is not AllComponents.SITE + {Microscopy.Site.name: str(slice_index + 1)} + if group_component is not Microscopy.Site else {} ), } diff --git a/tests/unit/test_cellprofiler_static_deletion_gates.py b/tests/unit/test_cellprofiler_static_deletion_gates.py index 923f5a72aa..5a300db7c6 100644 --- a/tests/unit/test_cellprofiler_static_deletion_gates.py +++ b/tests/unit/test_cellprofiler_static_deletion_gates.py @@ -8,6 +8,7 @@ from functools import cache from pathlib import Path import warnings +from openhcs.core.axes import Axis PROJECT_ROOT = Path(__file__).parents[2] PLAN_PATH = ( @@ -1020,7 +1021,7 @@ def test_source_component_tuple_state_is_not_mirrored() -> None: for statement in node.body if isinstance(statement, ast.AnnAssign) and isinstance(statement.target, ast.Name) - and "tuple[AllComponents" in ast.unparse(statement.annotation) + and "tuple[type[Axis]" in ast.unparse(statement.annotation) ) assert source_component_fields diff --git a/tests/unit/test_child_measurement_producer_selection.py b/tests/unit/test_child_measurement_producer_selection.py index 7493daf581..ce92d267bf 100644 --- a/tests/unit/test_child_measurement_producer_selection.py +++ b/tests/unit/test_child_measurement_producer_selection.py @@ -4,7 +4,6 @@ import pytest -from openhcs.constants.constants import AllComponents from openhcs.core.artifacts import ( ArtifactInputPlan, ArtifactOutputPlan, @@ -32,6 +31,7 @@ from openhcs.core.source_bindings import EMPTY_SOURCE_BINDINGS from openhcs.processing.backends.cellprofiler.relationships import RelateObjectsModule from tests.unit.test_cellprofiler_relationship_contracts import _contract, _module +from openhcs.domains.microscopy.axes import Microscopy def _declared_input(*, enabled=True): @@ -72,7 +72,7 @@ def _compiled_edge(*, dynamic=False, declared=True): path="/memory/intensity.pkl", artifact_type=MeasurementsArtifactType, group_keys=(None,) if dynamic else ("1", "2", "5", "3"), - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, paths_by_group=( None if dynamic @@ -95,10 +95,10 @@ def _compiled_edge(*, dynamic=False, declared=True): input_spec=spec, storage_plan=storage, invocation_scope=PathPlannerGroupScope.from_raw( - ("3",), component=AllComponents.CHANNEL + ("3",), component=Microscopy.Channel ), relation_source_scopes={}, - consumer_variable_components=ComponentSet((AllComponents.SITE,)), + consumer_variable_components=ComponentSet((Microscopy.Site,)), source_bindings=EMPTY_SOURCE_BINDINGS, available_artifacts=ArtifactSpecCollection(()), main_flow_projection=None, @@ -112,14 +112,14 @@ def test_relate_prior_child_measurements_compile_all_source_channels(): edge.projection.producer_selection_scope == edge.storage_plan.producer_group_scope() ) - assert edge.projection.consumer_variable_components == (AllComponents.SITE,) + assert edge.projection.consumer_variable_components == (Microscopy.Site,) def test_ordinary_measurement_input_still_selects_invocation_channel(): edge, _ = _compiled_edge(declared=False) assert edge.projection.producer_selection_scope == ComponentGroupScope.from_raw( ("3",), - component=AllComponents.CHANNEL, + component=Microscopy.Channel, ) @@ -156,7 +156,7 @@ def _measurement_store(edge, *, well="A01", fixed=()): path=path, artifact_type=MeasurementsArtifactType, group_keys=(channel,), - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, ) for subject in ("Children", "Unrelated"): table = MeasurementTable( @@ -174,7 +174,7 @@ def _measurement_store(edge, *, well="A01", fixed=()): table, execution_scope=RuntimeExecutionAxisScope.from_raw( well, - component=AllComponents.CHANNEL, + component=Microscopy.Channel, value=channel, fixed_component_values=fixed, ), @@ -191,7 +191,7 @@ def _runtime_input(edge, *, fixed=()): backend="memory", axis_scope=RuntimeExecutionAxisScope.from_raw( "A01", - component=AllComponents.CHANNEL, + component=Microscopy.Channel, value="3", fixed_component_values=fixed, ), @@ -235,7 +235,7 @@ def test_ordinary_dynamic_input_keeps_current_channel_selection(): @pytest.mark.parametrize("dynamic", (False, True)) @pytest.mark.parametrize( - "component", (AllComponents.SITE, AllComponents.TIMEPOINT, AllComponents.Z_INDEX) + "component", (Microscopy.Site, Microscopy.Timepoint, Microscopy.ZIndex) ) def test_complete_measurement_selection_rejects_other_fixed_context(dynamic, component): edge, _ = _compiled_edge(dynamic=dynamic) @@ -271,7 +271,7 @@ def _source_axis(channel, *, sites=("1", "2"), well="A01", time="1"): bindings=tuple( NamedSourceBinding( alias=f"Orig{value}", - component_identity=(ComponentSelector(AllComponents.CHANNEL, value),), + component_identity=(ComponentSelector(Microscopy.Channel, value),), ) for value in ("1", "2", "5", "3") ) @@ -377,8 +377,8 @@ def _upstream_rows(*, sites=("1", "2"), well="A01", time="1"): path="/memory/children.pkl", artifact_type=ObjectLabelsArtifactType, group_keys=("3",), - group_component=AllComponents.CHANNEL, - variable_components=(AllComponents.SITE,), + group_component=Microscopy.Channel, + variable_components=(Microscopy.Site,), source_step_id=1, ) child_edge = InvocationArtifactInputEdgePlan( @@ -398,8 +398,8 @@ def _upstream_rows(*, sites=("1", "2"), well="A01", time="1"): path=storage.path, artifact_type=ObjectLabelsArtifactType, group_keys=("3",), - group_component=AllComponents.CHANNEL, - variable_components=(AllComponents.SITE,), + group_component=Microscopy.Channel, + variable_components=(Microscopy.Site,), ) store.record( RuntimeValue.normalize(plan, labels, axis_id="A01"), @@ -427,7 +427,7 @@ def _upstream_rows(*, sites=("1", "2"), well="A01", time="1"): path=path, artifact_type=MeasurementsArtifactType, group_keys=(channel,), - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, ) for subject in ("Children", "Unrelated"): table = MeasurementTable( @@ -466,7 +466,7 @@ def _upstream_rows(*, sites=("1", "2"), well="A01", time="1"): bindings=tuple( NamedSourceBinding( alias=f"Orig{channel}", - component_identity=(ComponentSelector(AllComponents.CHANNEL, channel),), + component_identity=(ComponentSelector(Microscopy.Channel, channel),), ) for channel in ("1", "2", "5", "3") ) @@ -476,7 +476,7 @@ def _upstream_rows(*, sites=("1", "2"), well="A01", time="1"): callable_contract=contract, artifact_inputs={edge.key: edge for edge in (child_edge, measurement_edge)}, axis_scope=RuntimeExecutionAxisScope.from_raw( - "A01", component=AllComponents.CHANNEL, value="3" + "A01", component=Microscopy.Channel, value="3" ), source_image_set_identity_policy=SourceImageSetIdentityPolicy.from_source_bindings( bindings @@ -652,7 +652,7 @@ def test_compiled_input_cannot_silently_narrow_complete_declaration(): projection=replace( edge.projection, producer_selection_scope=ComponentGroupScope.from_raw( - ("3",), component=AllComponents.CHANNEL + ("3",), component=Microscopy.Channel ), ), ) @@ -662,8 +662,8 @@ def test_compiled_input_cannot_silently_narrow_complete_declaration(): def test_complete_input_keeps_existing_record_scope_ambiguity_guard(): edge, _ = _compiled_edge(dynamic=True) - store = _measurement_store(edge, fixed=((AllComponents.SITE, "1"),)) - other = _measurement_store(edge, fixed=((AllComponents.SITE, "2"),)) + store = _measurement_store(edge, fixed=((Microscopy.Site, "1"),)) + other = _measurement_store(edge, fixed=((Microscopy.Site, "2"),)) store.merge_observed_values(other.observed_values) with pytest.raises(RuntimeError, match="Ambiguous RuntimeValueStore records"): _runtime_input(edge).records(store) @@ -716,7 +716,7 @@ class SingleChannelRelation(ArtifactSpecRelation): target_plan_type = ArtifactInputPlan def input_producer_selection_scope(self, producer_scope): - return ComponentGroupScope.from_raw(("1",), component=AllComponents.CHANNEL) + return ComponentGroupScope.from_raw(("1",), component=Microscopy.Channel) spec = replace( edge.spec, relations=(*edge.spec.relations, SingleChannelRelation(child.ref())) diff --git a/tests/unit/test_compilation_session.py b/tests/unit/test_compilation_session.py index 080ddc474f..fc2b7d11e8 100644 --- a/tests/unit/test_compilation_session.py +++ b/tests/unit/test_compilation_session.py @@ -8,7 +8,6 @@ from objectstate.object_state import ObjectState from objectstate.object_state_registry import ObjectStateRegistry -from openhcs.constants.constants import AllComponents, GroupBy, VariableComponents from openhcs.constants.input_source import InputSource from openhcs.core.artifacts import ArtifactSpec, ImageArtifactType from openhcs.core.callable_contract import CallableContract @@ -58,6 +57,8 @@ neurite_outgrowth_metaxpress, neurite_outgrowth_metaxpress_pixels, ) +from openhcs.core.axes import Ungrouped +from openhcs.domains.microscopy.axes import Microscopy def _identity(image): @@ -70,7 +71,7 @@ def test_shared_declaration_checks_full_plate_group_domain_with_held_config( ): step = FunctionStep(func={channel: _identity}, name="Grouped") step.processing_config = ProcessingConfig( - variable_components=[VariableComponents.SITE], group_by=GroupBy.CHANNEL + variable_components=[Microscopy.Site], group_by=Microscopy.Channel ) pipeline = ResolvedPipelineDefinition( (step,), {0: "plate::functionstep_0"}, {0: {}} @@ -91,7 +92,7 @@ def full_plate_keys(component, *, resolved_config): pipeline.validate_source_group_domains(orchestrator, held_config) else: pipeline.validate_source_group_domains(orchestrator, held_config) - assert requests == [(GroupBy.CHANNEL, held_config)] + assert requests == [(Microscopy.Channel, held_config)] @pytest.mark.parametrize( @@ -260,14 +261,14 @@ def _previous_step_and_external_source(image, dna): def _resolved_step( step: FunctionStep, - variable_components=(VariableComponents.SITE,), + variable_components=(Microscopy.Site,), source_bindings=EMPTY_SOURCE_BINDINGS, input_source: InputSource = InputSource.PREVIOUS_STEP, ) -> AbstractStep: step.source_bindings = source_bindings step.processing_config = ProcessingConfig( variable_components=list(variable_components), - group_by=GroupBy.NONE, + group_by=Ungrouped, input_source=input_source, ) step.step_materialization_config = StepMaterializationConfig(enabled=False) @@ -343,7 +344,7 @@ def test_axis_compilation_request_preserves_effective_auto_add_flag(): assert context.auto_add_output_plate_to_plate_manager is True assert context.source_image_set_identity_policy.plane_member_components == ( - frozenset((AllComponents.CHANNEL,)) + frozenset((Microscopy.Channel,)) ) @@ -495,7 +496,7 @@ def test_compiler_keeps_variable_components_as_stack_source(): global_config=GlobalPipelineConfig(), pipeline=ResolvedPipelineDefinition( steps=( - _resolved_step(step, variable_components=(VariableComponents.CHANNEL,)), + _resolved_step(step, variable_components=(Microscopy.Channel,)), ), step_scope_ids={0: "plate::functionstep_0"}, step_provenance={0: {}}, @@ -504,7 +505,7 @@ def test_compiler_keeps_variable_components_as_stack_source(): PipelineCompiler._supplement_step_plans(session) - assert session.plan(0).variable_components == [VariableComponents.CHANNEL] + assert session.plan(0).variable_components == [Microscopy.Channel] def test_path_planner_source_binding_plan_comes_from_objectstate_snapshot(): @@ -517,7 +518,7 @@ def test_path_planner_source_binding_plan_comes_from_objectstate_snapshot(): binding = NamedSourceBinding( alias="DNA", selector=SourceSelector( - components=(ComponentSelector(AllComponents.CHANNEL, "1"),) + components=(ComponentSelector(Microscopy.Channel, "1"),) ), ) ensure_global_config_context(GlobalPipelineConfig, GlobalPipelineConfig()) @@ -847,7 +848,7 @@ def test_path_planner_preserves_metaxpress_primary_source_order( step = FunctionStep(func=function, name="neurite") snapshot = _resolved_step( step, - variable_components=(VariableComponents.CHANNEL,), + variable_components=(Microscopy.Channel,), source_bindings=StepSourceBindingsConfig( enabled=True, bindings=selected_bindings, @@ -896,11 +897,11 @@ def test_path_planner_execution_groups_use_resolved_source_bindings(): bindings = ( NamedSourceBinding( alias="OrigStain1", - component_identity=(ComponentSelector(AllComponents.CHANNEL, "1"),), + component_identity=(ComponentSelector(Microscopy.Channel, "1"),), ), NamedSourceBinding( alias="OrigStain2", - component_identity=(ComponentSelector(AllComponents.CHANNEL, "2"),), + component_identity=(ComponentSelector(Microscopy.Channel, "2"),), ), ) snapshot = _resolved_step( @@ -915,12 +916,12 @@ def test_path_planner_execution_groups_use_resolved_source_bindings(): scope = PathPlannerExecutionGroups(planner).source_binding_scope_for_group_by( snapshot, - GroupBy.CHANNEL, + Microscopy.Channel, source_bindings=snapshot.source_bindings, ) assert scope.keys == ("1", "2") - assert scope.component is AllComponents.CHANNEL + assert scope.component is Microscopy.Channel def test_path_planner_execution_groups_preserve_declared_component_identity() -> None: @@ -929,16 +930,16 @@ def test_path_planner_execution_groups_preserve_declared_component_identity() -> NamedSourceBinding( alias="MCP_DNA", selector=SourceSelector( - components=(ComponentSelector(AllComponents.CHANNEL, "1"),), + components=(ComponentSelector(Microscopy.Channel, "1"),), ), - component_identity=(ComponentSelector(AllComponents.CHANNEL, "MCP_DNA"),), + component_identity=(ComponentSelector(Microscopy.Channel, "MCP_DNA"),), ), NamedSourceBinding( alias="MCP_AGP", selector=SourceSelector( - components=(ComponentSelector(AllComponents.CHANNEL, "2"),), + components=(ComponentSelector(Microscopy.Channel, "2"),), ), - component_identity=(ComponentSelector(AllComponents.CHANNEL, "MCP_AGP"),), + component_identity=(ComponentSelector(Microscopy.Channel, "MCP_AGP"),), ), ) snapshot = _resolved_step( @@ -958,12 +959,12 @@ def test_path_planner_execution_groups_preserve_declared_component_identity() -> scope = PathPlannerExecutionGroups(planner).source_binding_scope_for_group_by( snapshot, - GroupBy.CHANNEL, + Microscopy.Channel, source_bindings=snapshot.source_bindings, ) assert scope.keys == ("MCP_DNA", "MCP_AGP") - assert scope.component is AllComponents.CHANNEL + assert scope.component is Microscopy.Channel def test_path_planner_freezes_only_contract_selected_source_bindings(): @@ -1043,7 +1044,7 @@ def test_headless_resolution_preserves_saved_ui_ancestors_and_registrations(tmp_ PipelineConfig( source_bindings_config=LazySourceBindingsConfig(bindings=(saved_binding,)), processing_config=LazyProcessingConfig( - variable_components=[VariableComponents.SITE], + variable_components=[Microscopy.Site], ), ), scope_id=str(plate_path), @@ -1084,9 +1085,9 @@ def record_registration(scope, state): saved_components = object.__getattribute__( ui_state.object_instance.processing_config, "variable_components" ) - saved_components.append(VariableComponents.Z_INDEX) + saved_components.append(Microscopy.ZIndex) assert resolved.steps[0].processing_config.variable_components == [ - VariableComponents.SITE + Microscopy.Site ] finally: subscription.release() diff --git a/tests/unit/test_compiled_execution.py b/tests/unit/test_compiled_execution.py index 3f0de002b3..16b076a50a 100644 --- a/tests/unit/test_compiled_execution.py +++ b/tests/unit/test_compiled_execution.py @@ -6,7 +6,6 @@ from arraybridge import MemoryType -from openhcs.constants.constants import AllComponents from openhcs.core.artifacts import ( ArtifactOutputPlan, ImageArtifactType, @@ -47,6 +46,7 @@ from openhcs.core.runtime_tabular_values import FieldSpec from openhcs.processing.materialization import CsvOptions, MaterializationSpec from openhcs.processing.materialization.persistence import TerminalMaterializationSpec +from openhcs.domains.microscopy.axes import Microscopy def _runtime_environment() -> CompiledRuntimeEnvironmentPlan: @@ -269,7 +269,7 @@ def test_runtime_execution_observation_merges_into_parent_contexts(): name="measurements", path="/memory/measurements.pkl", artifact_type=MeasurementsArtifactType, - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, group_keys=("DAPI",), ), MeasurementTable( @@ -309,7 +309,7 @@ def test_worker_runtime_observation_excludes_inherited_store_history(monkeypatch name="measurements", path="/memory/measurements.pkl", artifact_type=MeasurementsArtifactType, - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, group_keys=("DAPI",), ) diff --git a/tests/unit/test_completed_output_publication_lifecycle.py b/tests/unit/test_completed_output_publication_lifecycle.py index a46c05455d..591c66a3e1 100644 --- a/tests/unit/test_completed_output_publication_lifecycle.py +++ b/tests/unit/test_completed_output_publication_lifecycle.py @@ -27,6 +27,7 @@ from openhcs.core.steps.function_outputs import PrimaryImageMetadataTarget from openhcs.core.virtual_workspace_metadata import VirtualWorkspaceSourceProjectionEntries from openhcs.microscopes.source_schema import SourceSchemaFilenameParser +from openhcs.domains.microscopy.axes import Microscopy def _facts(plate_root: Path) -> StepExecutionObservation: @@ -35,7 +36,7 @@ def _facts(plate_root: Path) -> StepExecutionObservation: sub_dir="images", results_dir=None, ) projection = SourcePlaneProjection( - address=OpenHCSPlaneAddress.from_values("A01", 1, 0, 1, 1), + address=OpenHCSPlaneAddress(((Microscopy.Well, "A01"), (Microscopy.Site, 1), (Microscopy.Channel, 0), (Microscopy.ZIndex, 1), (Microscopy.Timepoint, 1))), ref=SourcePixelRef("disk", "images/saved.tif"), source_alias="saved", image_metadata=ImagePayloadMetadata(source_dtype="uint16"), ) @@ -152,7 +153,7 @@ def test_runtime_axis_query_is_explicit_and_full_plate_outputs_remain_available( first = _facts(tmp_path) target, entries = next(iter(first.source_projection_entries_by_target.items())) projection, _ = entries.projection_paths[0] - second = replace(projection, address=OpenHCSPlaneAddress.from_values("A02", 1, 0, 1, 1)) + second = replace(projection, address=OpenHCSPlaneAddress(((Microscopy.Well, "A02"), (Microscopy.Site, 1), (Microscopy.Channel, 0), (Microscopy.ZIndex, 1), (Microscopy.Timepoint, 1)))) outputs = replace(first, source_projection_entries_by_target=MappingProxyType({ target: VirtualWorkspaceSourceProjectionEntries.from_projection_paths(( (projection, "images/A01.tif"), (second, "images/A02.tif"), diff --git a/tests/unit/test_czi_brain_axon_cellbody_demo.py b/tests/unit/test_czi_brain_axon_cellbody_demo.py index f8fbd7c542..2948ca9926 100644 --- a/tests/unit/test_czi_brain_axon_cellbody_demo.py +++ b/tests/unit/test_czi_brain_axon_cellbody_demo.py @@ -6,7 +6,7 @@ from polystore.bioformats_storage import BioFormatsPlaneRef from polystore.virtual_workspace import SourcePixelRef -from openhcs.constants import AllComponents, GroupBy, Microscope, VariableComponents +from openhcs.constants import Microscope from openhcs.constants.input_source import InputSource from openhcs.core.artifacts import ImageArtifactType from openhcs.core.callable_contract import CallableContract @@ -36,6 +36,8 @@ build_czi_brain_axon_cellbody_demo, czi_brain_axon_cellbody_demo_contribution, ) +from openhcs.core.axes import Ungrouped +from openhcs.domains.microscopy.axes import Microscopy def _inputs(plate_path: Path, output_root: Path) -> CziBrainAxonCellBodyInputs: @@ -70,16 +72,10 @@ def _candidate( relative_path=source_path.name, metadata={}, component_labels={ - AllComponents.SITE.value: site_label, - AllComponents.CHANNEL.value: channel_label, + Microscopy.Site.name: site_label, + Microscopy.Channel.name: channel_label, }, - declared_address=OpenHCSPlaneAddress.from_values( - well=".", - site=site, - channel=channel, - z_index="1", - timepoint="1", - ), + declared_address=OpenHCSPlaneAddress(((Microscopy.Well, "."), (Microscopy.Site, site), (Microscopy.Channel, channel), (Microscopy.ZIndex, "1"), (Microscopy.Timepoint, "1"))), dataset_identity=identity, store_identity=SourcePlaneStoreIdentity( container_paths=(source_path,), @@ -155,9 +151,9 @@ def test_czi_demo_declares_bounded_three_channel_analysis_and_artifacts( "Nuclei", ] assert [binding.selector.components for binding in source_bindings] == [ - (ComponentSelector(AllComponents.CHANNEL, "1"),), - (ComponentSelector(AllComponents.CHANNEL, "2"),), - (ComponentSelector(AllComponents.CHANNEL, "3"),), + (ComponentSelector(Microscopy.Channel, "1"),), + (ComponentSelector(Microscopy.Channel, "2"),), + (ComponentSelector(Microscopy.Channel, "3"),), ] assert [step.name for step in steps] == [ "CZI Tissue Background Correction", @@ -171,23 +167,23 @@ def test_czi_demo_declares_bounded_three_channel_analysis_and_artifacts( assert get_core_callable(steps[3].func) is skan_axon_skeletonize_and_analyze assert steps[0].processing_config.variable_components == [ - VariableComponents.CHANNEL + Microscopy.Channel ] assert steps[0].processing_config.input_source is InputSource.PIPELINE_START assert steps[1].processing_config.variable_components == [ - VariableComponents.CHANNEL + Microscopy.Channel ] assert steps[1].processing_config.input_source is InputSource.PREVIOUS_STEP - assert steps[2].processing_config.group_by is GroupBy.NONE + assert steps[2].processing_config.group_by is Ungrouped assert steps[2].processing_config.variable_components == [ - VariableComponents.CHANNEL + Microscopy.Channel ] assert steps[2].processing_config.input_source is InputSource.PIPELINE_START assert steps[2].source_bindings.enabled is True assert [binding.alias for binding in steps[2].source_bindings.bindings] == ["Axon"] - assert steps[3].processing_config.group_by is GroupBy.NONE + assert steps[3].processing_config.group_by is Ungrouped assert steps[3].processing_config.variable_components == [ - VariableComponents.CHANNEL + Microscopy.Channel ] assert steps[3].processing_config.input_source is InputSource.PREVIOUS_STEP @@ -403,11 +399,11 @@ def fake_source_filemanager(source_root, workspace_root): ) assert prepared_dataset.pixel_size == 0.325 assert [ - candidate.component_labels[AllComponents.CHANNEL.value] + candidate.component_labels[Microscopy.Channel.name] for candidate in prepared_dataset.candidates ] == list(selection.ordered_channel_labels) assert [ - candidate.declared_address.value_for(AllComponents.CHANNEL) + candidate.declared_address.value_for(Microscopy.Channel) for candidate in prepared_dataset.candidates if candidate.declared_address is not None ] == ["1", "2", "3"] @@ -485,7 +481,7 @@ def test_czi_contributor_rejects_missing_declared_role_plane( candidates=tuple( candidate for candidate in dataset.candidates - if candidate.component_labels.get(AllComponents.CHANNEL.value) + if candidate.component_labels.get(Microscopy.Channel.name) != "Rhodamine (Green Laser)" ), pixel_size=dataset.pixel_size, diff --git a/tests/unit/test_debug_runtime.py b/tests/unit/test_debug_runtime.py index 94b4bc1c88..dfe7056a44 100644 --- a/tests/unit/test_debug_runtime.py +++ b/tests/unit/test_debug_runtime.py @@ -11,7 +11,7 @@ import pytest from openhcs.core.alias_property import AliasProperty -from openhcs.constants.constants import AllComponents, MEMORY_TYPE_NUMPY +from openhcs.constants.constants import MEMORY_TYPE_NUMPY from openhcs.core.aligned_image_payload import ImagePayloadExecutionMode from openhcs.core.callable_contract import CallableContract, CallableMetadata from openhcs.core.component_group_scope import ComponentGroupScope @@ -137,6 +137,7 @@ from openhcs.core.runtime_stores import RuntimeValueStore from openhcs.processing.backends.lib_registry.unified_registry import ProcessingContract from openhcs.core.runtime_artifact_values import RuntimeValue +from openhcs.domains.microscopy.axes import Microscopy class DebugRuntimeTokenParameter: @@ -1536,7 +1537,7 @@ def test_debug_snapshot_round_trips_invocation_parameters_and_artifact_identity( name="objects", path="/tmp/objects.json", artifact_type=ObjectLabelsArtifactType, - group_component=AllComponents.WELL, + group_component=Microscopy.Well, group_keys=("A01",), ) event = DebugEvent( @@ -1581,7 +1582,7 @@ def test_paused_worker_runtime_inspection_projects_runtime_value_store(): name="measurements", path="/memory/measurements.pkl", artifact_type=MeasurementsArtifactType, - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, group_keys=("DAPI",), ), measurements, @@ -1608,7 +1609,7 @@ def test_paused_worker_runtime_inspection_projects_runtime_value_store(): assert key_record["name"] == "measurements" assert key_record["artifact_type"] == MeasurementsArtifactType.value assert key_record["scope"]["axis_id"] == DebugRuntimeFixture.AXIS_ID - assert key_record["scope"]["component"] == AllComponents.CHANNEL.value + assert key_record["scope"]["component"] == Microscopy.Channel.name assert key_record["scope"]["value"] == "DAPI" assert location_record["backend"] == DebugRuntimeFixture.DEBUG_SNAPSHOT_BACKEND assert location_record["path"] == "/memory/measurements.pkl" diff --git a/tests/unit/test_derived_role_publication_435.py b/tests/unit/test_derived_role_publication_435.py index e85a47f10c..feeaaf65db 100644 --- a/tests/unit/test_derived_role_publication_435.py +++ b/tests/unit/test_derived_role_publication_435.py @@ -14,9 +14,7 @@ context_stub, function_step_plan, record_output_path, ) from openhcs.microscopes.source_schema import SourceSchemaFilenameParser -from openhcs.constants.constants import ( - AllComponents, Backend, GroupBy, Microscope, VariableComponents, -) +from openhcs.constants.constants import Backend, Microscope from openhcs.core.aligned_image_payload import AlignedImageSliceContext, stack_image_payloads from openhcs.core.artifacts import ArtifactOutputPlan, ImageArtifactType, ObjectLabelsArtifactType from openhcs.core.component_group_scope import ComponentGroupScope, RuntimeExecutionAxisScope @@ -44,6 +42,7 @@ from openhcs.processing.materialization import ( ImageFileOptions, MaterializationSpec, MaterializedFilenameIdentity, ) +from openhcs.domains.microscopy.axes import Microscopy @pytest.mark.parametrize("scenario,aggregate", ( @@ -90,10 +89,10 @@ def test_saved_roles_publish_once_per_persisted_occurrence(tmp_path, scenario, a ) if aggregate: components.update(channel="1", z_index="0") - plan.variable_components = (VariableComponents.Z_INDEX,) - plan.group_by = GroupBy.CHANNEL + plan.variable_components = (Microscopy.ZIndex,) + plan.group_by = Microscopy.Channel plan.execution_group_scope = ComponentGroupScope.from_raw( - ("1",), component=AllComponents.CHANNEL, + ("1",), component=Microscopy.Channel, ) source_planes = [] source_dir = tmp_path / "physical_source" @@ -140,8 +139,8 @@ def test_saved_roles_publish_once_per_persisted_occurrence(tmp_path, scenario, a ) if aggregate: output_plan = replace( - output_plan, group_keys=("1",), group_component=AllComponents.CHANNEL, - variable_components=(AllComponents.Z_INDEX,), + output_plan, group_keys=("1",), group_component=Microscopy.Channel, + variable_components=(Microscopy.ZIndex,), ) plan.artifact_outputs[output_plan.ref()] = output_plan payload = ImageMetadataPayload( @@ -184,9 +183,9 @@ def test_saved_roles_publish_once_per_persisted_occurrence(tmp_path, scenario, a ) if aggregate: execution_scope = RuntimeExecutionAxisScope.from_raw( - "A01", component=AllComponents.CHANNEL, value="1", + "A01", component=Microscopy.Channel, value="1", fixed_component_values=( - (AllComponents.SITE, "1"), (AllComponents.TIMEPOINT, "1"), + (Microscopy.Site, "1"), (Microscopy.Timepoint, "1"), ), ) payload = RuntimeValue.normalize_for_execution_scope( @@ -218,9 +217,9 @@ def test_saved_roles_publish_once_per_persisted_occurrence(tmp_path, scenario, a output_plan, artifact_payload, execution_scope=( RuntimeExecutionAxisScope.from_raw( - "A01", component=AllComponents.CHANNEL, value="1", + "A01", component=Microscopy.Channel, value="1", fixed_component_values=( - (AllComponents.SITE, "2"), (AllComponents.TIMEPOINT, "1"), + (Microscopy.Site, "2"), (Microscopy.Timepoint, "1"), ), ) if scenario == "conflicting_scope" else execution_scope ), @@ -229,8 +228,8 @@ def test_saved_roles_publish_once_per_persisted_occurrence(tmp_path, scenario, a output_plan, artifact_payload, execution_scope=RuntimeExecutionAxisScope.from_raw( "A01", component=None, value=None, fixed_component_values=( - (AllComponents.CHANNEL, "2"), (AllComponents.Z_INDEX, "1"), - (AllComponents.TIMEPOINT, "1"), + (Microscopy.Channel, "2"), (Microscopy.ZIndex, "1"), + (Microscopy.Timepoint, "1"), ), ), ) if mosaic else RuntimeValue.normalize(output_plan, artifact_payload, axis_id="A01") @@ -381,8 +380,8 @@ def test_saved_roles_publish_once_per_persisted_occurrence(tmp_path, scenario, a assert metadata.source_image_provenance_planes.contributor_count == 2 assert metadata.source_voxel_spacing.values_zyx == (0.5, 0.5) assert projection.execution_scope.fixed_component_values == ( - (AllComponents.CHANNEL, "2"), (AllComponents.Z_INDEX, "1"), - (AllComponents.TIMEPOINT, "1"), + (Microscopy.Channel, "2"), (Microscopy.ZIndex, "1"), + (Microscopy.Timepoint, "1"), ) np.testing.assert_array_equal(tifffile.imread(tmp_path / relative_path), mosaic_pixels) continue diff --git a/tests/unit/test_fiji_viewer_server.py b/tests/unit/test_fiji_viewer_server.py index 22ce0a127c..e2c9870a79 100644 --- a/tests/unit/test_fiji_viewer_server.py +++ b/tests/unit/test_fiji_viewer_server.py @@ -9,6 +9,7 @@ from zmqruntime.streaming import StreamingVisualizerServer from zmqruntime.messages import AckReturnRoute, ImageTransferIdentity, ProcessIdentity +from openhcs.core.axes import AxisFamily from openhcs.core.config import ( FijiDisplayConfig, FijiStreamingConfig, @@ -598,7 +599,7 @@ def test_fiji_window_item_projection_preserves_nominal_items() -> None: assert projection.coordinate_components.z_axis_components == ["z_index"] assert projection.coordinate_components.frame == [ component - for component in FijiDisplayConfig.COMPONENT_ORDER + for component in AxisFamily.active().names() if component in {"site", "well", "timepoint"} ] diff --git a/tests/unit/test_fitted_illumination_fields.py b/tests/unit/test_fitted_illumination_fields.py index 592187ba13..cb1860219d 100644 --- a/tests/unit/test_fitted_illumination_fields.py +++ b/tests/unit/test_fitted_illumination_fields.py @@ -84,7 +84,8 @@ def test_z_only_stack_is_not_an_observation_ensemble(): for i in range(3) ] ) - with pytest.raises(ValueError, match="independent SITE observations"): + with pytest.raises(ValueError, match=r"independent TileAxis observations \(site\)"): + FittedIlluminationFieldOutput.validate_observation_domain(source) diff --git a/tests/unit/test_funcstep_contract_validator.py b/tests/unit/test_funcstep_contract_validator.py index d3b050121e..b6f89cb5c2 100644 --- a/tests/unit/test_funcstep_contract_validator.py +++ b/tests/unit/test_funcstep_contract_validator.py @@ -5,8 +5,6 @@ import numpy as np import pytest -from openhcs.constants import GroupBy, VariableComponents -from openhcs.constants.constants import AllComponents from openhcs.core.artifacts import ( ArtifactInputProjectionPlan, ArtifactInputPlan, @@ -38,10 +36,10 @@ FuncStepContractValidator, ) from openhcs.core.pipeline.function_contracts import ( - allowed_group_by, + allowed_group_by_roles, artifact_inputs, require_variable_component_stack, - required_variable_components, + required_axis_roles, ) from openhcs.core.config import LazyProcessingConfig from openhcs.core.steps.function_step import FunctionStep @@ -52,6 +50,16 @@ from openhcs.processing.backends.processors.numpy_processor import ( stack_percentile_normalize, ) +from openhcs.core.axes import ( + Axis, + ColourAxis, + GroupingDeclaration, + TileAxis, + TimeAxis, + Ungrouped, +) + +from openhcs.domains.microscopy.axes import Microscopy _TRANSPORTED_FLEXIBLE_CALL_SHAPES: list[tuple[int, ...]] = [] @@ -155,8 +163,8 @@ def _compiled_semantic_step_plan( pattern: FunctionPatternSyntax, *, provider: InvocationContractProvider, - variable_components: tuple[VariableComponents, ...] = (), - group_by: GroupBy = GroupBy.NONE, + variable_components: tuple[type[Axis], ...] = (), + group_by: type[GroupingDeclaration] = Ungrouped, ) -> CompiledStepPlan: return CompiledStepPlan( step_index=0, @@ -246,12 +254,12 @@ def test_validate_raw_function_pattern_rejects_invalid_execution_memory(): def test_normalized_group_by_resolves_non_grouped_variable_component_conflict(): assert ( FuncStepContractValidator.normalized_group_by( - GroupBy.CHANNEL, - (VariableComponents.CHANNEL,), + Microscopy.Channel, + (Microscopy.Channel,), "step", normalize_function_pattern(_function()), ) - is GroupBy.NONE + is Ungrouped ) @@ -260,13 +268,13 @@ def test_normalized_group_by_rejects_grouped_variable_component_conflict(): ValueError, match=( r"Step 'step' has invalid processing_config: " - r"group_by=CHANNEL cannot also appear in " - r"variable_components=\('CHANNEL',\)" + r"group_by=channel cannot also appear in " + r"variable_components=\('channel',\)" ), ): FuncStepContractValidator.normalized_group_by( - GroupBy.CHANNEL, - (VariableComponents.CHANNEL,), + Microscopy.Channel, + (Microscopy.Channel,), "step", normalize_function_pattern({"1": _function()}), ) @@ -279,41 +287,43 @@ def test_validate_funcstep_rejects_dict_pattern_groupby_none(): step = FunctionStep( func={"1": func}, name="dict-none", - processing_config=LazyProcessingConfig(group_by=GroupBy.NONE), + processing_config=LazyProcessingConfig(group_by=Ungrouped), ) with pytest.raises( ValueError, - match="Dict pattern requires a concrete group_by component", + match="Dict pattern requires a concrete group_by axis", ): FuncStepContractValidator.validate_funcstep( step, orchestrator=SimpleNamespace() ) -def test_validate_required_variable_components_allows_declared_axis(): - @required_variable_components(VariableComponents.TIMEPOINT) +def test_validate_required_axis_roles_allows_axis_with_declared_role(): + @required_axis_roles(TimeAxis) def process(image): return image contract = CallableContract.from_callable(process) - FuncStepContractValidator.validate_required_variable_components( - (VariableComponents.TIMEPOINT,), + FuncStepContractValidator.validate_required_axis_roles( + (Microscopy.Timepoint,), (contract,), "track", ) -def test_validate_required_variable_components_rejects_missing_callable_axis(): - @required_variable_components(VariableComponents.TIMEPOINT) +def test_validate_required_axis_roles_rejects_missing_role(): + @required_axis_roles(TimeAxis) def process(image): return image contract = CallableContract.from_callable(process) - with pytest.raises(ValueError, match="requires variable_components TIMEPOINT"): - FuncStepContractValidator.validate_required_variable_components( + with pytest.raises( + ValueError, match=r"requires variable_components with role TimeAxis \(timepoint\)" + ): + FuncStepContractValidator.validate_required_axis_roles( (), (contract,), "track", @@ -339,7 +349,7 @@ def full_stack(image): return image FuncStepContractValidator.validate_processing_contract_variable_components( - (VariableComponents.Z_INDEX,), + (Microscopy.ZIndex,), tuple(_compiled_pattern(full_stack).iter_invocations()), "full_stack", ) @@ -423,7 +433,7 @@ def consume_stack(image): ), ): FuncStepContractValidator.validate_processing_contract_chain( - (VariableComponents.SITE,), + (Microscopy.Site,), tuple(group.invocations for group in pattern.groups), "ordered_chain", ) @@ -440,7 +450,7 @@ def test_validate_processing_contract_chain_rejects_assembly_before_stack_normal ), ): FuncStepContractValidator.validate_processing_contract_chain( - (VariableComponents.SITE,), + (Microscopy.Site,), tuple(group.invocations for group in pattern.groups), "normalize_and_stitch", ) @@ -460,7 +470,7 @@ def consume_slice(image): ) FuncStepContractValidator.validate_processing_contract_chain( - (VariableComponents.SITE,), + (Microscopy.Site,), tuple(group.invocations for group in pattern.groups), "ordered_chain", ) @@ -482,7 +492,7 @@ def consume_stack(image): axis_id="A01", input_memory_type="numpy", output_memory_type="numpy", - variable_components=(VariableComponents.SITE,), + variable_components=(Microscopy.Site,), compiled_function_pattern=_compiled_pattern(pattern), ) @@ -547,44 +557,50 @@ def stacked_callable(image): ) -def test_validate_allowed_group_by_accepts_declared_group_by(): - @allowed_group_by(GroupBy.NONE) +def test_validate_allowed_group_by_accepts_axis_with_declared_role(): + @allowed_group_by_roles(ColourAxis) def process(image): return image contract = CallableContract.from_callable(process) FuncStepContractValidator.validate_allowed_group_by( - GroupBy.NONE, + Microscopy.Channel, (contract,), "cellprofiler", ) -def test_validate_allowed_group_by_treats_none_as_groupby_none(): - @allowed_group_by(GroupBy.NONE) +def test_validate_allowed_group_by_rejects_absent_grouping_when_roles_declared(): + @allowed_group_by_roles(ColourAxis) def process(image): return image contract = CallableContract.from_callable(process) - FuncStepContractValidator.validate_allowed_group_by( - None, - (contract,), - "cellprofiler", - ) + for absent in (None, Ungrouped): + with pytest.raises( + ValueError, match="allows group_by axes with role ColourAxis; resolved none" + ): + FuncStepContractValidator.validate_allowed_group_by( + absent, + (contract,), + "cellprofiler", + ) -def test_validate_allowed_group_by_rejects_forbidden_fanout(): - @allowed_group_by(GroupBy.NONE) +def test_validate_allowed_group_by_rejects_axis_without_declared_role(): + @allowed_group_by_roles(ColourAxis) def process(image): return image contract = CallableContract.from_callable(process) - with pytest.raises(ValueError, match="allows group_by NONE; resolved CHANNEL"): + with pytest.raises( + ValueError, match="allows group_by axes with role ColourAxis; resolved site" + ): FuncStepContractValidator.validate_allowed_group_by( - GroupBy.CHANNEL, + Microscopy.Site, (contract,), "cellprofiler", ) @@ -597,16 +613,18 @@ def test_compiled_group_rejects_enriched_allowed_group_by_before_runtime(): provider = _MetadataTransformProvider( lambda metadata: replace( metadata, - allowed_group_by=(GroupBy.SITE,), + allowed_group_by_roles=(TileAxis,), ) ) step_plan = _compiled_semantic_step_plan( {"1": first, "2": second}, provider=provider, - group_by=GroupBy.CHANNEL, + group_by=Microscopy.Channel, ) - with pytest.raises(ValueError, match="allows group_by SITE; resolved CHANNEL"): + with pytest.raises( + ValueError, match="allows group_by axes with role TileAxis; resolved channel" + ): FuncStepContractValidator.validate_compiled_step_plan(step_plan) assert runtime_calls == [] @@ -644,7 +662,7 @@ def combine(image): path=f"/memory/{name}.pkl", artifact_type=ImageArtifactType, group_keys=(key,), - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, paths_by_group={ key: f"/memory/{name}.pkl", }, @@ -657,11 +675,11 @@ def combine(image): step_name="combine", axis_id="A01", variable_components=(), - group_by=GroupBy.CHANNEL, + group_by=Microscopy.Channel, artifact_inputs=input_plans, execution_group_scope=ComponentGroupScope.from_raw( ("1", "2"), - component=AllComponents.CHANNEL, + component=Microscopy.Channel, ), compiled_function_pattern=_compiled_pattern_with_exact_input_edges( combine, @@ -690,7 +708,7 @@ def process_right(image): path=f"/memory/{name}.pkl", artifact_type=ImageArtifactType, group_keys=(key,), - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, paths_by_group={key: f"/memory/{name}.pkl"}, ) for name, key in (("left", "1"), ("right", "2")) @@ -701,11 +719,11 @@ def process_right(image): step_name="branch", axis_id="A01", variable_components=(), - group_by=GroupBy.CHANNEL, + group_by=Microscopy.Channel, artifact_inputs=input_plans, execution_group_scope=ComponentGroupScope.from_raw( ("1", "2"), - component=AllComponents.CHANNEL, + component=Microscopy.Channel, ), compiled_function_pattern=_compiled_pattern_with_exact_input_edges( pattern, @@ -723,14 +741,14 @@ def test_compiled_group_allows_distinct_enriched_callables_for_resolved_config() provider = _MetadataTransformProvider( lambda metadata: replace( metadata, - allowed_group_by=(GroupBy.CHANNEL,), + allowed_group_by_roles=(ColourAxis,), processing_contract=ProcessingContract.PURE_2D, ) ) step_plan = _compiled_semantic_step_plan( {"1": first, "2": second}, provider=provider, - group_by=GroupBy.CHANNEL, + group_by=Microscopy.Channel, ) FuncStepContractValidator.validate_compiled_step_plan(step_plan) @@ -738,8 +756,8 @@ def test_compiled_group_allows_distinct_enriched_callables_for_resolved_config() assert runtime_calls == [] -def test_validate_funcstep_enforces_required_variable_components(): - @required_variable_components(VariableComponents.TIMEPOINT) +def test_validate_funcstep_enforces_required_axis_roles(): + @required_axis_roles(TimeAxis) def process(image): return image @@ -750,9 +768,9 @@ def process(image): name="TrackObjects", processing_config=LazyProcessingConfig( variable_components=[], - group_by=GroupBy.NONE, + group_by=Ungrouped, ), ) - with pytest.raises(ValueError, match="requires variable_components TIMEPOINT"): + with pytest.raises(ValueError, match="requires variable_components with role TimeAxis"): FuncStepContractValidator.validate_funcstep(step) diff --git a/tests/unit/test_function_artifact_materialization.py b/tests/unit/test_function_artifact_materialization.py index 991e878aaf..c8ace42675 100644 --- a/tests/unit/test_function_artifact_materialization.py +++ b/tests/unit/test_function_artifact_materialization.py @@ -23,7 +23,6 @@ ) from zmqruntime.viewer_protocol import ViewerTransportEndpoint -from openhcs.constants.constants import AllComponents, GroupBy, VariableComponents from openhcs.core.artifacts import ( ArtifactOutputPlan, ArtifactSpec, @@ -167,11 +166,13 @@ ImageFileOptions, MaterializedFilenameIdentity, ) +from openhcs.core.axes import AxisFamily, Ungrouped +from openhcs.domains.microscopy.axes import Microscopy class StreamingConfigStub(ViewerDisplayConfigABC): backend = SimpleNamespace(value="napari_stream") - COMPONENT_ORDER = AllComponents.ordered_names() + COMPONENT_ORDER = AxisFamily.active().names() host = "127.0.0.1" transport_mode = "tcp" colormap = SimpleNamespace(value="gray") @@ -310,11 +311,11 @@ def construct_filename( self, components, ): - well = components.value_for(AllComponents.WELL) - site = components.value_for(AllComponents.SITE) - channel = components.value_for(AllComponents.CHANNEL) - z_index = components.value_for(AllComponents.Z_INDEX) - timepoint = components.value_for(AllComponents.TIMEPOINT) + well = components.value_for(Microscopy.Well) + site = components.value_for(Microscopy.Site) + channel = components.value_for(Microscopy.Channel) + z_index = components.value_for(Microscopy.ZIndex) + timepoint = components.value_for(Microscopy.Timepoint) extension = components.extension if str(site).startswith("POS"): return f"{well}_{site}_{channel}{extension}" @@ -404,11 +405,7 @@ def _plan( execution_group_value = group_by_value execution_group_scope = ComponentGroupScope.ungrouped() if execution_group_value is not None: - execution_group_component = AllComponents.from_value(execution_group_value) - if execution_group_component is None: - raise ValueError( - f"Unknown execution group component {execution_group_value!r}." - ) + execution_group_component = AxisFamily.active().named(execution_group_value) execution_group_scope = ComponentGroupScope.dynamic(execution_group_component) return CompiledStepPlan( step_index=6, @@ -424,7 +421,10 @@ def _plan( read_backend="memory", write_backend="memory", group_by=( - GroupBy(group_by_value) if group_by_value is not None else GroupBy.NONE + AxisFamily.active().named(group_by_value) + if group_by_value is not None + else Ungrouped + ), execution_group_scope=execution_group_scope, variable_components=variable_components, @@ -889,8 +889,8 @@ def fake_materialize(_spec, data, path, *_args, **_kwargs): PersistentArtifactMaterializationTargetPlan("disk").materialize_outputs(filemanager, _plan( output_plan, variable_components=( - VariableComponents.Z_INDEX, - VariableComponents.CHANNEL, + Microscopy.ZIndex, + Microscopy.Channel, ), ), context) @@ -922,7 +922,7 @@ def test_materialize_artifact_outputs_uses_output_plan_axes_for_source_named_run path="/memory/SavedImages.pkl", artifact_type=ImageArtifactType, materialization=materialization, - variable_components=(VariableComponents.SITE,), + variable_components=(Microscopy.Site,), ) payload = ImagePayloadMetadata( plane_axis=RuntimePlaneAxis.RUNTIME_SLICE, @@ -962,7 +962,7 @@ def fake_materialize(spec, data, path, manager, *_args, **kwargs): plan = _plan( output_plan, - variable_components=(VariableComponents.CHANNEL,), + variable_components=(Microscopy.Channel,), ) plan.runtime_artifact_materialization = RuntimeArtifactMaterializationPlan( persistent_enabled=True, @@ -1035,7 +1035,7 @@ def test_materialize_artifact_outputs_uses_runtime_record_identity_not_final_pat artifact_type=MeasurementsArtifactType, materialization=csv_only(), group_keys=("1",), - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, paths_by_group={"1": "/analysis/A01_measurements_step7.csv"}, ) runtime_output_plan = output_plan.for_group("1") @@ -1136,7 +1136,7 @@ def test_runtime_artifact_plan_materializes_3d_point_measurements(source_z_origi x_feature=features.CENTER_X, ) ), - variable_components=(AllComponents.Z_INDEX,), + variable_components=(Microscopy.ZIndex,), ) source_path = "/input/A01/image.ome.tif" table = MeasurementTable( @@ -1174,7 +1174,7 @@ def test_runtime_artifact_plan_materializes_3d_point_measurements(source_z_origi path=output_plan.path, backend="memory", ) - plan = _plan(output_plan, variable_components=(VariableComponents.Z_INDEX,)) + plan = _plan(output_plan, variable_components=(Microscopy.ZIndex,)) [materialization] = runtime_artifact_materializations(plan, context) [result] = materialization.outputs(plan, context) @@ -1197,7 +1197,7 @@ def test_runtime_artifact_plan_materializes_3d_point_measurements(source_z_origi config = streaming_config_stub() plan = _plan( output_plan, - variable_components=(VariableComponents.Z_INDEX,), + variable_components=(Microscopy.ZIndex,), streaming_configs={"napari_stream": config}, ) [saved] = StreamingOnlyArtifactMaterializationTargetPlan().materialize_outputs( @@ -1219,8 +1219,8 @@ def test_multi_plane_measurement_materialization_uses_aggregate_artifact_name(): artifact_type=MeasurementsArtifactType, materialization=csv_only(), variable_components=( - AllComponents.SITE, - AllComponents.CHANNEL, + Microscopy.Site, + Microscopy.Channel, ), ) source_metadata = ( @@ -1272,8 +1272,8 @@ def test_multi_plane_measurement_materialization_uses_aggregate_artifact_name(): plan = _plan( output_plan, variable_components=( - VariableComponents.SITE, - VariableComponents.CHANNEL, + Microscopy.Site, + Microscopy.Channel, ), ) @@ -1313,8 +1313,8 @@ def test_multi_plane_special_output_uses_aggregate_artifact_name(parser_type): component=None, value=None, fixed_component_values=( - (AllComponents.Z_INDEX, "1"), - (AllComponents.TIMEPOINT, "1"), + (Microscopy.ZIndex, "1"), + (Microscopy.Timepoint, "1"), ), ), ), @@ -1324,8 +1324,8 @@ def test_multi_plane_special_output_uses_aggregate_artifact_name(parser_type): plan = _plan( output_plan, variable_components=( - VariableComponents.SITE, - VariableComponents.CHANNEL, + Microscopy.Site, + Microscopy.Channel, ), ) @@ -1361,10 +1361,10 @@ def test_scalar_special_output_preserves_complete_source_identity(parser_type): component=None, value=None, fixed_component_values=( - (AllComponents.SITE, "1"), - (AllComponents.CHANNEL, "2"), - (AllComponents.Z_INDEX, "1"), - (AllComponents.TIMEPOINT, "1"), + (Microscopy.Site, "1"), + (Microscopy.Channel, "2"), + (Microscopy.ZIndex, "1"), + (Microscopy.Timepoint, "1"), ), ), ), @@ -1405,8 +1405,8 @@ def test_incomplete_scalar_special_output_keeps_strict_filename_failure(parser_t component=None, value=None, fixed_component_values=( - (AllComponents.Z_INDEX, "1"), - (AllComponents.TIMEPOINT, "1"), + (Microscopy.ZIndex, "1"), + (Microscopy.Timepoint, "1"), ), ), ), @@ -1428,7 +1428,7 @@ def test_grouped_special_output_retains_group_coordinate_in_aggregate_name(parse path="/memory/cell_counts.pkl", artifact_type=SpecialArtifactType, group_keys=("2",), - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, materialization=csv_only(), ) context = _context(FileManagerStub()) @@ -1445,11 +1445,11 @@ def test_grouped_special_output_retains_group_coordinate_in_aggregate_name(parse ), execution_scope=RuntimeExecutionAxisScope.from_raw( "A01", - component=AllComponents.CHANNEL, + component=Microscopy.Channel, value="2", fixed_component_values=( - (AllComponents.Z_INDEX, "1"), - (AllComponents.TIMEPOINT, "1"), + (Microscopy.ZIndex, "1"), + (Microscopy.Timepoint, "1"), ), ), ), @@ -1458,7 +1458,7 @@ def test_grouped_special_output_retains_group_coordinate_in_aggregate_name(parse ) plan = _plan( output_plan, - variable_components=(VariableComponents.SITE,), + variable_components=(Microscopy.Site,), ) [materialization] = runtime_artifact_materializations(plan, context) @@ -1480,8 +1480,8 @@ def test_multi_plane_roi_aggregate_defers_source_filenames_to_plane_writer(monke path="/memory/segmentation_masks.pkl", artifact_type=ObjectLabelsArtifactType, variable_components=( - VariableComponents.SITE, - VariableComponents.CHANNEL, + Microscopy.Site, + Microscopy.Channel, ), materialization=roi_zip(), ) @@ -1532,8 +1532,8 @@ def test_multi_plane_roi_aggregate_defers_source_filenames_to_plane_writer(monke component=None, value=None, fixed_component_values=( - (AllComponents.Z_INDEX, "1"), - (AllComponents.TIMEPOINT, "1"), + (Microscopy.ZIndex, "1"), + (Microscopy.Timepoint, "1"), ), ), ), @@ -1543,8 +1543,8 @@ def test_multi_plane_roi_aggregate_defers_source_filenames_to_plane_writer(monke plan = _plan( output_plan, variable_components=( - VariableComponents.SITE, - VariableComponents.CHANNEL, + Microscopy.Site, + Microscopy.Channel, ), ) @@ -1592,7 +1592,7 @@ def test_multi_plane_measurement_aggregate_names_retain_runtime_group_coordinate path="/memory/neurite_outgrowth_summary.pkl", artifact_type=MeasurementsArtifactType, materialization=csv_only(), - variable_components=(AllComponents.CHANNEL,), + variable_components=(Microscopy.Channel,), ) context = _context(FileManagerStub()) for site in ("1", "2"): @@ -1629,11 +1629,11 @@ def test_multi_plane_measurement_aggregate_names_retain_runtime_group_coordinate table, execution_scope=RuntimeExecutionAxisScope.from_raw( "A01", - component=AllComponents.SITE, + component=Microscopy.Site, value=site, fixed_component_values=( - (AllComponents.Z_INDEX, "1"), - (AllComponents.TIMEPOINT, "1"), + (Microscopy.ZIndex, "1"), + (Microscopy.Timepoint, "1"), ), ), ), @@ -1645,7 +1645,7 @@ def test_multi_plane_measurement_aggregate_names_retain_runtime_group_coordinate _plan( output_plan, group_by_value="site", - variable_components=(VariableComponents.CHANNEL,), + variable_components=(Microscopy.Channel,), ), context, ) @@ -1668,13 +1668,13 @@ def test_observed_materialized_paths_use_only_caller_owned_execution_records(): path="/memory/cell_counts.pkl", artifact_type=MeasurementsArtifactType, materialization=csv_only(), - variable_components=(AllComponents.CHANNEL,), + variable_components=(Microscopy.Channel,), ) context = _context(FileManagerStub()) plan = _plan( output_plan, group_by_value="site", - variable_components=(VariableComponents.CHANNEL,), + variable_components=(Microscopy.Channel,), ) plan.runtime_artifact_materialization = RuntimeArtifactMaterializationPlan( persistent_enabled=True, @@ -1714,11 +1714,11 @@ def record_for_site(site: str) -> None: ), execution_scope=RuntimeExecutionAxisScope.from_raw( "A01", - component=AllComponents.SITE, + component=Microscopy.Site, value=site, fixed_component_values=( - (AllComponents.Z_INDEX, "1"), - (AllComponents.TIMEPOINT, "1"), + (Microscopy.ZIndex, "1"), + (Microscopy.Timepoint, "1"), ), ), ), @@ -1793,13 +1793,13 @@ def test_scalar_acquired_tables_keep_fixed_site_addresses_on_shared_runtime_path AutomaticMeasurementsArtifactOutputMaterializationStrategy().materialization() if automatic else csv_only() ), - variable_components=(AllComponents.Z_INDEX,), + variable_components=(Microscopy.ZIndex,), ) context = _context(FileManagerStub()) plan = _plan( output_plan, group_by_value="channel", - variable_components=(VariableComponents.Z_INDEX,), + variable_components=(Microscopy.ZIndex,), ) plan.runtime_artifact_materialization = RuntimeArtifactMaterializationPlan( persistent_enabled=True, @@ -1828,10 +1828,10 @@ def test_scalar_acquired_tables_keep_fixed_site_addresses_on_shared_runtime_path subject=MeasurementSubject(MeasurementScope.ARTIFACT), ), execution_scope=RuntimeExecutionAxisScope.from_raw( - "A01", component=AllComponents.CHANNEL, value="1", + "A01", component=Microscopy.Channel, value="1", fixed_component_values=( - (AllComponents.SITE, site), - (AllComponents.TIMEPOINT, "1"), + (Microscopy.Site, site), + (Microscopy.Timepoint, "1"), ), ), ), @@ -1850,7 +1850,7 @@ def test_scalar_acquired_tables_keep_fixed_site_addresses_on_shared_runtime_path for item in saved: record = item.materialization.record observation = item.observation(plan, context) - site = record.key.scope.value_text_for_component(AllComponents.SITE) + site = record.key.scope.value_text_for_component(Microscopy.Site) paths = observation.paths_for(record) expected_stem = ( f"A01_site-{site}_channel-1_timepoint-1" @@ -2068,7 +2068,7 @@ def test_materialize_artifact_outputs_unions_measurement_subject_records( artifact_type=MeasurementsArtifactType, materialization=csv_only(), group_keys=("1",), - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, paths_by_group={"1": "/memory/A01_w1_measurements_step7.pkl"}, ) runtime_output_plan = output_plan.for_group("1") @@ -2134,7 +2134,7 @@ def test_fixed_component_scopes_materialize_distinct_measurement_paths() -> None path="/memory/measurements.pkl", artifact_type=MeasurementsArtifactType, group_keys=("2",), - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, paths_by_group={"2": "/memory/measurements.pkl"}, materialization=csv_only(), ) @@ -2147,9 +2147,9 @@ def test_fixed_component_scopes_materialize_distinct_measurement_paths() -> None ): execution_scope = RuntimeExecutionAxisScope.from_raw( "A01", - component=AllComponents.CHANNEL, + component=Microscopy.Channel, value="2", - fixed_component_values=((AllComponents.Z_INDEX, z_index),), + fixed_component_values=((Microscopy.ZIndex, z_index),), ) for subject_name in subjects: table = MeasurementTable( @@ -2189,7 +2189,7 @@ def test_fixed_component_scopes_materialize_distinct_measurement_paths() -> None plan = _plan( output_plan, group_by_value="channel", - variable_components=(VariableComponents.SITE,), + variable_components=(Microscopy.Site,), ) records = actual_materialization_records( store=context.runtime_value_store, @@ -2201,7 +2201,7 @@ def test_fixed_component_scopes_materialize_distinct_measurement_paths() -> None assert len(records) == 2 assert tuple(record.data.rows.row_count() for record in records) == (2, 1) assert tuple( - record.key.scope.value_text_for_component(AllComponents.Z_INDEX) + record.key.scope.value_text_for_component(Microscopy.ZIndex) for record in records ) == ("1", "2") assert tuple(str(item.base_path) for item in materializations) == ( @@ -2216,7 +2216,7 @@ def test_artifact_name_materialization_ignores_incomplete_source_identity() -> N path="/memory/SavedImage.pkl", artifact_type=ImageArtifactType, group_keys=("3",), - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, paths_by_group={"3": "/memory/SavedImage.pkl"}, materialization=MaterializationSpec( ImageFileOptions( @@ -2240,9 +2240,9 @@ def test_artifact_name_materialization_ignores_incomplete_source_identity() -> N ).payload_with(np.ones((3, 4), dtype=np.uint8), None), execution_scope=RuntimeExecutionAxisScope.from_raw( "A01", - component=AllComponents.CHANNEL, + component=Microscopy.Channel, value="3", - fixed_component_values=((AllComponents.Z_INDEX, "1"),), + fixed_component_values=((Microscopy.ZIndex, "1"),), ), ), path=group_plan.path, @@ -2265,7 +2265,7 @@ def test_fixed_scope_preserves_distinct_source_group_identity() -> None: path="/memory/measurements.pkl", artifact_type=MeasurementsArtifactType, group_keys=("2",), - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, paths_by_group={"2": "/memory/measurements.pkl"}, materialization=csv_only(), ) @@ -2295,9 +2295,9 @@ def test_fixed_scope_preserves_distinct_source_group_identity() -> None: ), execution_scope=RuntimeExecutionAxisScope.from_raw( "A01", - component=AllComponents.CHANNEL, + component=Microscopy.Channel, value="2", - fixed_component_values=((AllComponents.Z_INDEX, "1"),), + fixed_component_values=((Microscopy.ZIndex, "1"),), ), ), path=group_plan.path, @@ -2320,7 +2320,7 @@ def test_fixed_component_scope_rejects_unresolved_filename_identity() -> None: path="/memory/measurements.pkl", artifact_type=MeasurementsArtifactType, group_keys=("2",), - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, paths_by_group={"2": "/memory/measurements.pkl"}, materialization=csv_only(), ) @@ -2328,9 +2328,9 @@ def test_fixed_component_scope_rejects_unresolved_filename_identity() -> None: context = _context(FileManagerStub()) execution_scope = RuntimeExecutionAxisScope.from_raw( "A01", - component=AllComponents.CHANNEL, + component=Microscopy.Channel, value="2", - fixed_component_values=((AllComponents.Z_INDEX, "1"),), + fixed_component_values=((Microscopy.ZIndex, "1"),), ) context.runtime_value_store.record( RuntimeValue.normalize_for_execution_scope( @@ -2429,7 +2429,7 @@ def test_materialize_artifact_outputs_uses_actual_group_records(monkeypatch): path="/memory/A01_measurements_step7.pkl", artifact_type=MeasurementsArtifactType, group_keys=("1", "2"), - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, paths_by_group={ "1": "/memory/A01_w1_measurements_step7.pkl", "2": "/memory/A01_w2_measurements_step7.pkl", @@ -2500,11 +2500,11 @@ def _duplicate_scalar_image_context( group_plan = output_plan.for_group(channel) execution_scope = RuntimeExecutionAxisScope.from_raw( "A01", - component=AllComponents.CHANNEL, + component=Microscopy.Channel, value=channel, fixed_component_values=( - (AllComponents.Z_INDEX, "1"), - (AllComponents.TIMEPOINT, "1"), + (Microscopy.ZIndex, "1"), + (Microscopy.Timepoint, "1"), ), ) context.runtime_value_store.record( @@ -2549,7 +2549,7 @@ def test_overlay_and_save_image_materialization_use_source_address_owner( path=f"/memory/A01_{artifact_name}_step7.pkl", artifact_type=ImageArtifactType, group_keys=(None,), - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, paths_by_group={None: f"/memory/A01_{artifact_name}_step7.pkl"}, materialization=TerminalMaterializationSpec( ImageFileOptions(filename_suffix=".tif") @@ -2576,14 +2576,14 @@ def test_overlay_and_save_image_materialization_use_source_address_owner( assert len(records) == 1 assert ( - records[0].key.scope.value_text_for_component(AllComponents.CHANNEL) + records[0].key.scope.value_text_for_component(Microscopy.Channel) == source_channel ) assert len(materializations) == 1 assert len(observed_materializations) == 1 assert ( materializations[0].record.key.scope.value_text_for_component( - AllComponents.CHANNEL + Microscopy.Channel ) == source_channel ) @@ -2595,7 +2595,7 @@ def test_scalar_image_materialization_rejects_conflicting_duplicate_payloads(): path="/memory/A01_Overlay_step7.pkl", artifact_type=ImageArtifactType, group_keys=(None,), - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, paths_by_group={None: "/memory/A01_Overlay_step7.pkl"}, materialization=TerminalMaterializationSpec( ImageFileOptions(filename_suffix=".tif") @@ -2623,7 +2623,7 @@ def test_actual_materialization_records_uses_dynamic_runtime_groups(): path="/memory/A01_segmentation_masks_step7.pkl", artifact_type=ObjectLabelsArtifactType, group_keys=(None,), - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, paths_by_group={None: "/memory/A01_segmentation_masks_step7.pkl"}, ) group_one = output_plan.for_group("1") @@ -2667,7 +2667,7 @@ def test_materialize_artifact_outputs_uses_group_measurement_artifact_identity( path="/memory/A01_measurements_step7.pkl", artifact_type=MeasurementsArtifactType, group_keys=("1", "2"), - group_component=AllComponents.SITE, + group_component=Microscopy.Site, paths_by_group={ "1": "/memory/A01_s001_measurements_step7.pkl", "2": "/memory/A01_s002_measurements_step7.pkl", @@ -2757,7 +2757,7 @@ def test_materialize_artifact_outputs_uses_grouped_scope_not_record_location( path="/memory/A01_measurements_step7.pkl", artifact_type=MeasurementsArtifactType, group_keys=("2",), - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, paths_by_group={ "2": "/memory/A01_w2_measurements_step7.pkl", }, @@ -2808,7 +2808,7 @@ def test_materialize_artifact_outputs_uses_null_component_group_identity_for_str path="/memory/Nuclei.pkl", artifact_type=ObjectLabelsArtifactType, group_keys=("2",), - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, paths_by_group={ "2": "/memory/channel2_Nuclei.pkl", }, @@ -2951,7 +2951,7 @@ def test_projected_artifact_uses_filename_identity_without_restoring_collapsed_s path="/memory/neurons.pkl", artifact_type=ObjectLabelsArtifactType, materialization=roi_zip(), - variable_components=(VariableComponents.CHANNEL,), + variable_components=(Microscopy.Channel,), ) labels = ObjectLabelPayload( variant_data=ObjectLabelVariantData(labels=np.ones((2, 4, 4), dtype=np.int32)), @@ -3004,7 +3004,7 @@ def test_projected_artifact_uses_filename_identity_without_restoring_collapsed_s ) plan = _plan( output_plan, - variable_components=(VariableComponents.CHANNEL,), + variable_components=(Microscopy.Channel,), ) [materialization] = runtime_artifact_materializations(plan, context) @@ -3112,7 +3112,7 @@ def test_tile_positions_runtime_materializes_native_json_without_changing_payloa path=str(tmp_path / "runtime" / "positions.pkl"), artifact_type=spec.artifact_type, materialization=spec.materialization, - group_component=AllComponents.CHANNEL if group_key is not None else None, + group_component=Microscopy.Channel if group_key is not None else None, group_keys=(group_key,), ) ensure_storage_registry() @@ -3472,7 +3472,7 @@ def test_materialize_artifact_outputs_uses_runtime_plane_group_identity( artifact_type=ImageArtifactType, materialization=csv_only(), group_keys=("11",), - group_component=AllComponents.TIMEPOINT, + group_component=Microscopy.Timepoint, paths_by_group={ "11": "/memory/A01_t11_AdjacentImage_step7.pkl", }, @@ -3509,7 +3509,7 @@ def fake_materialize(_spec, data, path, *_args, **_kwargs): PersistentArtifactMaterializationTargetPlan("disk").materialize_outputs(filemanager, _plan( output_plan, group_by_value="timepoint", - variable_components=(VariableComponents.TIMEPOINT,), + variable_components=(Microscopy.Timepoint,), ), context) assert materialized == [ @@ -3663,7 +3663,7 @@ def fake_materialize( StreamingOnlyArtifactMaterializationTargetPlan().materialize_outputs(filemanager, _plan( output_plan, streaming_configs={"napari_stream": streaming_config}, - variable_components=(VariableComponents.Z_INDEX,), + variable_components=(Microscopy.ZIndex,), ), context) _spec, _data, path, _backends, backend_kwargs = materialized[0] @@ -3699,7 +3699,7 @@ def test_materialize_artifact_outputs_streams_singleton_roi_plane_from_output_pl name="Nuclei", path="/memory/Nuclei.pkl", artifact_type=ObjectLabelsArtifactType, - variable_components=(VariableComponents.SITE,), + variable_components=(Microscopy.Site,), materialization=roi_zip(), ) labels_array = np.zeros((1, 8, 8), dtype=np.int32) @@ -3727,7 +3727,7 @@ def test_materialize_artifact_outputs_streams_singleton_roi_plane_from_output_pl StreamingOnlyArtifactMaterializationTargetPlan().materialize_outputs(filemanager, _plan( output_plan, streaming_configs={"napari_stream": streaming_config_stub()}, - variable_components=(VariableComponents.Z_INDEX,), + variable_components=(Microscopy.ZIndex,), ), context) roi_saves = [item for item in filemanager.saved if item[1].endswith(".roi.zip")] @@ -3821,7 +3821,7 @@ def fake_materialize( StreamingOnlyArtifactMaterializationTargetPlan().materialize_outputs(filemanager, _plan( output_plan, streaming_configs={"napari_stream": streaming_config}, - variable_components=(VariableComponents.CHANNEL,), + variable_components=(Microscopy.Channel,), ), context) _spec, _data, path, _backends, backend_kwargs = materialized[0] @@ -3922,7 +3922,7 @@ def fake_materialize( StreamingOnlyArtifactMaterializationTargetPlan().materialize_outputs(filemanager, _plan( output_plan, streaming_configs={"napari_stream": streaming_config}, - variable_components=(VariableComponents.CHANNEL,), + variable_components=(Microscopy.Channel,), ), context) _spec, _data, path, _backends, backend_kwargs = materialized[0] @@ -3996,7 +3996,7 @@ def fake_materialize(_spec, _data, path, *_args, **_kwargs): _observe_materialization(monkeypatch, fake_materialize) - PersistentArtifactMaterializationTargetPlan("disk").materialize_outputs(filemanager, _plan(output_plan, variable_components=(VariableComponents.CHANNEL,)), context) + PersistentArtifactMaterializationTargetPlan("disk").materialize_outputs(filemanager, _plan(output_plan, variable_components=(Microscopy.Channel,)), context) assert materialized == ["/images/A01_s001_w1_z001_t001.TIF"] @@ -4070,7 +4070,7 @@ def test_compiled_z_axis_reaches_source_named_image_materialization() -> None: filename_identity=MaterializedFilenameIdentity.SOURCE_IDENTITY, ) ), - variable_components=(VariableComponents.Z_INDEX,), + variable_components=(Microscopy.ZIndex,), relations=( MaterializationSourceIdentityRelation(filename_source.ref()), GroupLineageSourceRelation(selected_image.ref()), @@ -4147,7 +4147,7 @@ def test_compiled_z_axis_reaches_source_named_image_materialization() -> None: ) plan = _plan( output_plan, - variable_components=(VariableComponents.Z_INDEX,), + variable_components=(Microscopy.ZIndex,), ) plan.runtime_artifact_materialization = RuntimeArtifactMaterializationPlan( persistent_enabled=True, @@ -4237,7 +4237,7 @@ def fake_materialize( StreamingOnlyArtifactMaterializationTargetPlan().materialize_outputs(filemanager, _plan( output_plan, streaming_configs={"napari_stream": streaming_config}, - variable_components=(VariableComponents.SITE,), + variable_components=(Microscopy.Site,), ), context) _spec, _data, path, _backends, backend_kwargs = materialized[0] diff --git a/tests/unit/test_function_artifact_outputs.py b/tests/unit/test_function_artifact_outputs.py index dc3640b28d..aaa49d55bc 100644 --- a/tests/unit/test_function_artifact_outputs.py +++ b/tests/unit/test_function_artifact_outputs.py @@ -6,7 +6,7 @@ import pytest import numpy as np -from openhcs.constants.constants import AllComponents, MEMORY_TYPE_NUMPY +from openhcs.constants.constants import MEMORY_TYPE_NUMPY from openhcs.core.artifacts import ( ArtifactType, ArtifactMeasurementSubjectRelation, @@ -113,6 +113,7 @@ from openhcs.processing.backends.analysis.multi_template_matching import ( TemplateMatchResult, ) +from openhcs.domains.microscopy.axes import Microscopy def passthrough(image): @@ -338,7 +339,7 @@ def test_image_output_context_preserves_stack_after_exact_source_projection(): name="CorrGray", path="/memory/CorrGray.pkl", artifact_type=ImageArtifactType, - variable_components=(AllComponents.Z_INDEX,), + variable_components=(Microscopy.ZIndex,), relations=(GroupLineageSourceRelation(source_spec.ref()),), ) @@ -388,7 +389,7 @@ def test_image_output_context_does_not_infer_axis_for_unmarked_payload(): name="SavedNuclei", path="/memory/SavedNuclei.pkl", artifact_type=ImageArtifactType, - variable_components=(AllComponents.Z_INDEX,), + variable_components=(Microscopy.ZIndex,), relations=(GroupLineageSourceRelation(source_spec.ref()),), ) @@ -416,7 +417,7 @@ def test_image_output_context_rejects_declared_output_axis_shape_drift(): name="SavedNuclei", path="/memory/SavedNuclei.pkl", artifact_type=ImageArtifactType, - variable_components=(AllComponents.Z_INDEX,), + variable_components=(Microscopy.ZIndex,), relations=(GroupLineageSourceRelation(source_spec.ref()),), ) @@ -457,7 +458,7 @@ def test_image_output_context_preserves_complete_scalar_rgb_identity() -> None: name="SavedColorNeighbors", path="/memory/SavedColorNeighbors.png", artifact_type=ImageArtifactType, - variable_components=(AllComponents.SITE,), + variable_components=(Microscopy.Site,), relations=(GroupLineageSourceRelation(source_spec.ref()),), ) @@ -543,7 +544,7 @@ def test_image_output_context_projects_complete_multi_plane_identity() -> None: name="SavedVolume", path="/memory/SavedVolume.tif", artifact_type=ImageArtifactType, - variable_components=(AllComponents.Z_INDEX,), + variable_components=(Microscopy.ZIndex,), relations=(GroupLineageSourceRelation(source_spec.ref()),), ) @@ -1096,7 +1097,7 @@ def segment(image): name="segmentation_masks", path="/memory/A01_w2_segmentation_masks.pkl", artifact_type=ObjectLabelsArtifactType, - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, group_keys=("2",), paths_by_group={ "2": "/memory/A01_w2_segmentation_masks.pkl", @@ -1105,7 +1106,7 @@ def segment(image): ) }, group_key="2", - execution_group_scope=ComponentGroupScope.dynamic(AllComponents.CHANNEL), + execution_group_scope=ComponentGroupScope.dynamic(Microscopy.Channel), ) ) @@ -1162,7 +1163,7 @@ def segment(image): path="/memory/A01_segmentation_masks.pkl", artifact_type=ObjectLabelsArtifactType, group_keys=(None,), - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, paths_by_group={ None: "/memory/A01_segmentation_masks.pkl", }, @@ -1170,7 +1171,7 @@ def segment(image): ) }, group_key="2", - execution_group_scope=ComponentGroupScope.dynamic(AllComponents.CHANNEL), + execution_group_scope=ComponentGroupScope.dynamic(Microscopy.Channel), ) ) @@ -1504,7 +1505,7 @@ def produce_image(image): name=output_spec.name, path="/memory/derived-image.pkl", artifact_type=ImageArtifactType, - variable_components=(AllComponents.SITE,), + variable_components=(Microscopy.Site,), ), ) }, @@ -1582,7 +1583,7 @@ def analyze(image): path="/memory/A01_measurements.pkl", artifact_type=MeasurementsArtifactType, relations=measurement_spec.relations, - group_component=AllComponents.SITE, + group_component=Microscopy.Site, group_keys=("1", "2"), paths_by_group={ "1": "/memory/A01_s1_measurements.pkl", @@ -1594,7 +1595,7 @@ def analyze(image): group_key="2", execution_group_scope=ComponentGroupScope.from_raw( ("2",), - component=AllComponents.SITE, + component=Microscopy.Site, ), ) ) @@ -2299,7 +2300,7 @@ def segment(image): name=output_spec.name, path="/memory/cells.pkl", artifact_type=ObjectLabelsArtifactType, - variable_components=(AllComponents.SITE,), + variable_components=(Microscopy.Site,), ), ) }, @@ -2514,8 +2515,8 @@ def count(image): path="/memory/cell-counts.pkl", artifact_type=MeasurementsArtifactType, variable_components=( - AllComponents.SITE, - AllComponents.CHANNEL, + Microscopy.Site, + Microscopy.Channel, ), relations=measurement_spec.relations, ), diff --git a/tests/unit/test_function_execution_lifecycle_anchors.py b/tests/unit/test_function_execution_lifecycle_anchors.py index 0517f26cc8..110dd219a1 100644 --- a/tests/unit/test_function_execution_lifecycle_anchors.py +++ b/tests/unit/test_function_execution_lifecycle_anchors.py @@ -8,7 +8,6 @@ import pytest -from openhcs.constants.constants import AllComponents from openhcs.core.artifacts import ( ArtifactInputPlan, ArtifactSpec, @@ -29,6 +28,7 @@ from openhcs.core.source_bindings import CompiledSourceBindingPlan, NamedSourceBinding from openhcs.core.step_dependencies import StepInputDependency from openhcs.core.steps.function_execution import FunctionStepExecutor +from openhcs.domains.microscopy.axes import Microscopy def _anchor_executor( @@ -100,7 +100,7 @@ def consume_measurements(image, *, runtime): source_step_id=7, source_step_scope_id="measurement-producer", group_keys=("2",), - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, paths_by_group={"2": "/memory/measurements_w2.pkl"}, ) compiled_pattern = compile_function_pattern( @@ -118,7 +118,7 @@ def consume_measurements(image, *, runtime): }, execution_group_scope=ComponentGroupScope.from_raw( ("1",), - component=AllComponents.CHANNEL, + component=Microscopy.Channel, ), consumer_variable_components=ComponentSet(), ) @@ -139,7 +139,7 @@ def consume_measurements(image, *, runtime): execution_group_value="channel", execution_group_scope=ComponentGroupScope.from_raw( ("1",), - component=AllComponents.CHANNEL, + component=Microscopy.Channel, ), compiled_function_pattern=compiled_pattern, ) diff --git a/tests/unit/test_function_io.py b/tests/unit/test_function_io.py index d5fb74ad50..53ffab28af 100644 --- a/tests/unit/test_function_io.py +++ b/tests/unit/test_function_io.py @@ -39,6 +39,7 @@ from openhcs.formats.pattern.pattern_discovery import PatternDiscoveryEngine from openhcs.microscopes.source_bindings_handler import SourceBindingsHandler from openhcs.microscopes.source_schema import SourceSchemaFilenameParser +from openhcs.domains.microscopy.axes import Microscopy def _filemanager() -> FileManager: @@ -129,7 +130,7 @@ def resolve_listed_address(listed_address, _backend, *, directory): "/virtual/1_s001_w1_z001_t001.tif", "/virtual/2_s001_w1_z001_t001.tif", ], - variable_components=["channel"], + variable_components=[Microscopy.Channel], well_filter=["1"], ) assert tuple(patterns) == ("1",) @@ -379,7 +380,7 @@ def test_object_only_source_anchors_match_compiled_pattern_after_loading( "A01_s{iii}_w1_z001_t001.tif", filemanager, Backend.MEMORY.value, - ["site"], + [Microscopy.Site], ) == ["A01_s001_w1_z001_t001.tif"] diff --git a/tests/unit/test_function_output_manifest_input_scope.py b/tests/unit/test_function_output_manifest_input_scope.py index b204338974..b7189daf59 100644 --- a/tests/unit/test_function_output_manifest_input_scope.py +++ b/tests/unit/test_function_output_manifest_input_scope.py @@ -34,6 +34,7 @@ StepOutputManifestStore, ) from openhcs.microscopes.source_schema import SourceSchemaFilenameParser +from openhcs.domains.microscopy.axes import Microscopy def test_artifact_output_kind_is_owned_by_original_compiled_plan() -> None: @@ -615,7 +616,6 @@ def test_same_scope_parameter_bound_input_does_not_select_lifecycle_output( def test_named_producer_members_keep_acquisition_filters_and_site_correlations(): - from openhcs.constants import AllComponents from openhcs.core.source_bindings import ( CompiledSourceBindingPlan, ComponentSelector, NamedSourceBinding, SourceFilterClause, SourceFilterMatchType, SourceFilterSubject, SourceSelector, @@ -654,7 +654,7 @@ def test_named_producer_members_keep_acquisition_filters_and_site_correlations() selector=SourceSelector(filters=(SourceFilterClause( SourceFilterSubject.FILE, SourceFilterMatchType.CONTAINS, "N_R", ),)), - component_identity=(ComponentSelector(AllComponents.CHANNEL, "1"),), + component_identity=(ComponentSelector(Microscopy.Channel, "1"),), ),)) index = ProducedPathRecordIndex.from_records(tuple(records), parser) anchors = index.matching_records("A01_s{iii}_w1_z001_t001.tif") diff --git a/tests/unit/test_function_outputs.py b/tests/unit/test_function_outputs.py index c071d1ab5b..cf46727479 100644 --- a/tests/unit/test_function_outputs.py +++ b/tests/unit/test_function_outputs.py @@ -17,7 +17,7 @@ from polystore.virtual_workspace import SourcePixelRef from zmqruntime.viewer_protocol import ViewerTransportEndpoint -from openhcs.constants.constants import AllComponents, Backend, VariableComponents +from openhcs.constants.constants import Backend from openhcs.core.aligned_image_payload import AlignedImageSliceContext from openhcs.core.artifacts import ( ArtifactOutputPlan, @@ -104,6 +104,8 @@ MaterializationSpec, MaterializedFilenameIdentity, ) +from openhcs.core.axes import Axis, AxisFamily +from openhcs.domains.microscopy.axes import Microscopy def _publish_saved_step(context, plan, *, artifact_materializations=()): @@ -297,7 +299,7 @@ def parse_filename(self, name): } ) return FilenameParseResult( - ((component, metadata.get(component.value)) for component in AllComponents), + ((component, metadata.get(component.name)) for component in AxisFamily.active().axes), extension=str(metadata["extension"]), ) @@ -404,7 +406,7 @@ def test_openhcs_metadata_handler_preserves_unknown_layout_for_serialization( def function_step_plan( step_name: str, - variable_components: tuple[VariableComponents, ...] = (), + variable_components: tuple[type[Axis], ...] = (), pipeline_position: int = 3, ) -> CompiledStepPlan: return CompiledStepPlan( @@ -434,7 +436,7 @@ def record_output_path( assert metadata is not None output_identity = identity or FunctionOutputIdentity( component_values={ - str(component.value): value + str(component.name): value for component, value in metadata.declared_values() if value is not None }, @@ -879,7 +881,7 @@ def test_stream_outputs_keeps_scalar_records_from_variable_component_step(): context = context_stub(filemanager) plan = function_step_plan( "Normalize", - variable_components=(VariableComponents.SITE,), + variable_components=(Microscopy.Site,), ) record_output_path(context, plan, path) @@ -982,8 +984,8 @@ def parse_filename(self, name): ) return FilenameParseResult( ( - (component, metadata.get(component.value)) - for component in AllComponents + (component, metadata.get(component.name)) + for component in AxisFamily.active().axes ), extension=str(metadata["extension"]), ) @@ -1069,7 +1071,7 @@ def test_stream_outputs_projects_declared_channel_stack_axis(): context = context_stub(filemanager) plan = function_step_plan( "CalculateMath", - variable_components=(VariableComponents.CHANNEL,), + variable_components=(Microscopy.Channel,), ) record_output_path(context, plan, path) @@ -1123,7 +1125,7 @@ def test_stream_outputs_projects_stack_planes_with_item_source_paths(): context = context_stub(filemanager) plan = function_step_plan( "MeasureColocalization", - variable_components=(VariableComponents.CHANNEL,), + variable_components=(Microscopy.Channel,), ) record_output_path(context, plan, path) @@ -1531,11 +1533,11 @@ def test_metadata_writer_preserves_unknown_layout_without_resolving_grid_artifac {"channel": {"1": "DNA"}} ) context.metadata_cache = { - AllComponents.WELL: {"A01": None}, - AllComponents.SITE: {"1": None}, - AllComponents.CHANNEL: {"1": "DNA"}, - AllComponents.Z_INDEX: {"1": None}, - AllComponents.TIMEPOINT: {"1": None}, + Microscopy.Well: {"A01": None}, + Microscopy.Site: {"1": None}, + Microscopy.Channel: {"1": "DNA"}, + Microscopy.ZIndex: {"1": None}, + Microscopy.Timepoint: {"1": None}, } plan = function_step_plan("Segment nuclei") plan.output_dir = output_dir @@ -1573,11 +1575,11 @@ def test_produced_projection_metadata_persists_typed_collapsed_semantics( ) ) context.metadata_cache = { - AllComponents.WELL: {"A01": None}, - AllComponents.SITE: {"1": None}, - AllComponents.CHANNEL: {"1": None}, - AllComponents.Z_INDEX: {"1": None}, - AllComponents.TIMEPOINT: {"1": None}, + Microscopy.Well: {"A01": None}, + Microscopy.Site: {"1": None}, + Microscopy.Channel: {"1": None}, + Microscopy.ZIndex: {"1": None}, + Microscopy.Timepoint: {"1": None}, } plan = function_step_plan("Mosaic") plan.output_dir = output_dir @@ -1717,11 +1719,11 @@ def test_runtime_image_artifact_projects_persisted_source_binding( key=SimpleNamespace( scope=RuntimeExecutionAxisScope.from_raw( "A49", - component=AllComponents.SITE, + component=Microscopy.Site, value="1", fixed_component_values=( - (AllComponents.Z_INDEX, "1"), - (AllComponents.TIMEPOINT, "1"), + (Microscopy.ZIndex, "1"), + (Microscopy.Timepoint, "1"), ), ) ) @@ -1840,11 +1842,11 @@ def test_runtime_multiplane_label_artifact_projects_persisted_source_binding( key=SimpleNamespace( scope=RuntimeExecutionAxisScope.from_raw( "A49", - component=AllComponents.SITE, + component=Microscopy.Site, value="1", fixed_component_values=( - (AllComponents.Z_INDEX, "1"), - (AllComponents.TIMEPOINT, "1"), + (Microscopy.ZIndex, "1"), + (Microscopy.Timepoint, "1"), ), ) ) @@ -1934,7 +1936,7 @@ def parse_filename(self, name): } ) return FilenameParseResult( - ((component, metadata.get(component.value)) for component in AllComponents), + ((component, metadata.get(component.name)) for component in AxisFamily.active().axes), extension=str(metadata["extension"]), ) @@ -1969,11 +1971,11 @@ def test_produced_projection_derives_artifact_alias_for_same_address_outputs( context.filemanager.save(pixels, str(first), Backend.MEMORY.value) context.filemanager.save(pixels, str(second), Backend.MEMORY.value) context.metadata_cache = { - AllComponents.WELL: {"A01": None}, - AllComponents.SITE: {"1": None}, - AllComponents.CHANNEL: {"1": None}, - AllComponents.Z_INDEX: {"1": None}, - AllComponents.TIMEPOINT: {"1": None}, + Microscopy.Well: {"A01": None}, + Microscopy.Site: {"1": None}, + Microscopy.Channel: {"1": None}, + Microscopy.ZIndex: {"1": None}, + Microscopy.Timepoint: {"1": None}, } plan = function_step_plan("SaveImages") plan.output_dir = output_dir @@ -2043,11 +2045,11 @@ def test_produced_address_publication_never_parses_generated_filenames( ) context = context_stub(filemanager, parser=parser) context.metadata_cache = { - AllComponents.WELL: {well: None, "not-produced": None}, - AllComponents.SITE: {"1": None}, - AllComponents.CHANNEL: {"1": "DNA", "99": "not-produced"}, - AllComponents.Z_INDEX: {"1": None, "2": None, "3": None, "99": None}, - AllComponents.TIMEPOINT: {"1": None}, + Microscopy.Well: {well: None, "not-produced": None}, + Microscopy.Site: {"1": None}, + Microscopy.Channel: {"1": "DNA", "99": "not-produced"}, + Microscopy.ZIndex: {"1": None, "2": None, "3": None, "99": None}, + Microscopy.Timepoint: {"1": None}, } plan = function_step_plan("typed identity") plan.output_dir = output_dir @@ -2086,7 +2088,7 @@ def test_produced_address_publication_never_parses_generated_filenames( parsed = parser.parse_filename(filename) assert parsed is not None assert parsed.extension == extension - assert parsed.value_for(AllComponents.WELL) == well + assert parsed.value_for(Microscopy.Well) == well path = output_dir / filename tifffile.imwrite(path, pixels) filemanager.save( @@ -2177,13 +2179,13 @@ def test_produced_stacked_dotted_identity_keeps_declared_extension( np.zeros((3, 4, 5), dtype=np.uint16), None ), input_path=Path(source_paths[0]).name, - variable_components=(VariableComponents.Z_INDEX,), + variable_components=(Microscopy.ZIndex,), ) identity = FunctionOutputIdentity.from_request(request) assert identity.extension == extension assert "z_index" not in identity.component_values - assert identity.filename_address.value_for(AllComponents.Z_INDEX) == "3" - assert identity.filename_address.value_for(AllComponents.WELL) == well + assert identity.filename_address.value_for(Microscopy.ZIndex) == "3" + assert identity.filename_address.value_for(Microscopy.Well) == well filename = identity.with_filename_qualifier("centre_dots").filename(parser) assert filename == f"{well}_s001_w1_z003_t001_centre_dots{extension}" @@ -2216,11 +2218,11 @@ def test_completed_plate_metadata_includes_outputs_written_after_owner_axis( filemanager.save(first_pixels, str(first_image), Backend.MEMORY.value) owner_context = context_stub(filemanager) owner_context.metadata_cache = { - AllComponents.WELL: {"A01": None, "B03": None}, - AllComponents.SITE: {"1": None}, - AllComponents.CHANNEL: {"1": "DNA"}, - AllComponents.Z_INDEX: {"1": None}, - AllComponents.TIMEPOINT: {"1": None}, + Microscopy.Well: {"A01": None, "B03": None}, + Microscopy.Site: {"1": None}, + Microscopy.Channel: {"1": "DNA"}, + Microscopy.ZIndex: {"1": None}, + Microscopy.Timepoint: {"1": None}, } owner_plan = function_step_plan("final") owner_plan.output_dir = images_dir @@ -2474,7 +2476,7 @@ def test_declared_image_destinations_publish_and_reconcile_after_value_cleanup( ).entries assert set(entries) == {path} projection = entries[path] - assert projection.component_value(AllComponents.CHANNEL) == "2" + assert projection.component_value(Microscopy.Channel) == "2" assert projection.source_metadata["site"] == "1" np.testing.assert_array_equal(tifffile.imread(tmp_path / path), pixels) @@ -2778,7 +2780,7 @@ def test_whole_volume_checkpoint_publication_retains_exact_producer_scope( manager.save(metadata.payload_with(pixels), str(path), "memory") context = context_stub(manager, parser=SourceSchemaFilenameParser()) plan = function_step_plan( - "Volume checkpoint", variable_components=(VariableComponents.Z_INDEX,) + "Volume checkpoint", variable_components=(Microscopy.ZIndex,) ) plan.output_dir = output_dir plan.output_plate_root = str(plate_root) @@ -2831,9 +2833,9 @@ def test_whole_volume_checkpoint_publication_retains_exact_producer_scope( component=None, value=None, fixed_component_values=( - (AllComponents.CHANNEL, "2"), - (AllComponents.SITE, "1"), - (AllComponents.TIMEPOINT, "1"), + (Microscopy.Channel, "2"), + (Microscopy.Site, "1"), + (Microscopy.Timepoint, "1"), ), ), ), @@ -2856,18 +2858,18 @@ def test_whole_volume_checkpoint_publication_retains_exact_producer_scope( assert projection.address is None assert projection.source_alias == "DNA" assert ( - projection.execution_scope.value_text_for_component(AllComponents.CHANNEL) + projection.execution_scope.value_text_for_component(Microscopy.Channel) == "2" ) assert ( - projection.execution_scope.value_text_for_component(AllComponents.SITE) == "1" + projection.execution_scope.value_text_for_component(Microscopy.Site) == "1" ) assert ( - projection.execution_scope.value_text_for_component(AllComponents.TIMEPOINT) + projection.execution_scope.value_text_for_component(Microscopy.Timepoint) == "1" ) assert ( - projection.execution_scope.value_text_for_component(AllComponents.Z_INDEX) + projection.execution_scope.value_text_for_component(Microscopy.ZIndex) is None ) assert ( diff --git a/tests/unit/test_function_patterns.py b/tests/unit/test_function_patterns.py index 1fecc254ce..fb4664921f 100644 --- a/tests/unit/test_function_patterns.py +++ b/tests/unit/test_function_patterns.py @@ -4,7 +4,6 @@ import pytest from arraybridge.decorators import DtypeConversion, DtypeConversionConfig -from openhcs.constants import AllComponents from openhcs.core.artifacts import ( ArtifactInputProjectionPlan, ArtifactInputPlan, @@ -56,6 +55,7 @@ from openhcs.core.runtime_relationships import ObjectRelationshipDeclaration from openhcs.core.source_bindings import CompiledSourceBindingPlan from openhcs.processing.materialization import csv_only +from openhcs.domains.microscopy.axes import Microscopy @artifact_outputs(ArtifactSpec.output("positions", SpecialArtifactType)) @@ -693,7 +693,7 @@ def measure_channels(image, *, runtime): artifact_type=measurements.artifact_type, relations=measurements.relations, group_keys=("1", "2"), - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, group_scope_sources_by_group={ "1": (blue.ref(),), "2": (green.ref(),), @@ -727,7 +727,7 @@ def measure_channels(image, *, runtime): group = replace(compiled.default_group, invocations=(invocation,)) execution_scope = ComponentGroupScope.from_raw( ("1", "2"), - component=AllComponents.CHANNEL, + component=Microscopy.Channel, ) assert group.main_flow_input_refs_for_component(execution_scope, "1", source_bindings=CompiledSourceBindingPlan.empty()) == ( @@ -817,7 +817,7 @@ def measure_with_aggregate(image, *, runtime): artifact_type=scoped.artifact_type, relations=scoped.relations, group_keys=("1",), - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, group_scope_sources_by_group={"1": (source.ref(),)}, ) invocation = compile_function_pattern( @@ -844,7 +844,7 @@ def measure_with_aggregate(image, *, runtime): active_outputs = invocation.output_plans_for_component( ComponentGroupScope.from_raw( ("1", "2"), - component=AllComponents.CHANNEL, + component=Microscopy.Channel, ), "2", ) @@ -896,7 +896,7 @@ def measure_green(image, *, runtime): artifact_type=blue_measurements.artifact_type, relations=(*blue_measurements.relations, *green_measurements.relations), group_keys=("1", "2"), - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, group_scope_sources_by_group={ "1": (blue.ref(),), "2": (green.ref(),), @@ -909,7 +909,7 @@ def measure_green(image, *, runtime): ).default_group.invocations execution_scope = ComponentGroupScope.from_raw( ("1", "2"), - component=AllComponents.CHANNEL, + component=Microscopy.Channel, ) assert blue_invocation.output_plans_for_component(execution_scope, "1") is not None @@ -1146,7 +1146,7 @@ def consume_cross_channel(image, *, runtime): path="/memory/cross_channel.pkl", artifact_type=ImageArtifactType, group_keys=("3",), - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, paths_by_group={"3": "/memory/cross_channel__3.pkl"}, ) current_channel_plan = ArtifactInputPlan( @@ -1154,7 +1154,7 @@ def consume_cross_channel(image, *, runtime): path="/memory/current_channel.pkl", artifact_type=ImageArtifactType, group_keys=("1",), - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, paths_by_group={"1": "/memory/current_channel__1.pkl"}, ) compiled = compile_function_pattern( @@ -1212,7 +1212,7 @@ def runtime_recorded_outputs(image, *, runtime): path="/memory/Cells.pkl", artifact_type=ObjectLabelsArtifactType, group_keys=("3",), - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, paths_by_group={"3": "/memory/w3_Cells.pkl"}, ) measurement_output = ArtifactOutputPlan( @@ -1220,7 +1220,7 @@ def runtime_recorded_outputs(image, *, runtime): path="/memory/Measurements.pkl", artifact_type=MeasurementsArtifactType, group_keys=("1",), - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, paths_by_group={"1": "/memory/w1_Measurements.pkl"}, ) compiled = compile_function_pattern( diff --git a/tests/unit/test_function_runtime_source_projection.py b/tests/unit/test_function_runtime_source_projection.py index 4da032c498..5367f0c642 100644 --- a/tests/unit/test_function_runtime_source_projection.py +++ b/tests/unit/test_function_runtime_source_projection.py @@ -16,12 +16,7 @@ from objectstate.global_config import GlobalContextValues from polystore.virtual_workspace import SourcePixelRef -from openhcs.constants.constants import ( - AllComponents, - Backend, - GroupBy, - VariableComponents, -) +from openhcs.constants.constants import Backend from openhcs.core.aligned_image_payload import ( AlignedImageSliceContext, ImagePayloadBundleContext, @@ -123,6 +118,7 @@ ) from openhcs.formats.pattern.pattern_discovery import PatternDiscoveryEngine from openhcs.microscopes.source_schema import SourceSchemaFilenameParser +from openhcs.domains.microscopy.axes import Microscopy def _anchor_executor( @@ -229,7 +225,7 @@ def test_pattern_discovery_uses_authoritative_virtual_source_files( patterns = engine.auto_detect_patterns_from_files( source_files, - variable_components=[VariableComponents.SITE.value], + variable_components=[Microscopy.Site], well_filter=["A01"], ) @@ -297,13 +293,7 @@ def test_workspace_source_files_select_exact_projection_roles( plate_path = tmp_path / "plate" canonical_path = "A01_s001_w1_z001_t001.tif" artifact_path = f"_source/Illumination/{canonical_path}" - address = OpenHCSPlaneAddress.from_values( - well="A01", - site="1", - channel="1", - z_index="1", - timepoint="1", - ) + address = OpenHCSPlaneAddress(((Microscopy.Well, "A01"), (Microscopy.Site, "1"), (Microscopy.Channel, "1"), (Microscopy.ZIndex, "1"), (Microscopy.Timepoint, "1"))) plane_projection = SourcePlaneProjection( address=address, ref=SourcePixelRef("disk", "/source/image.tif"), @@ -342,7 +332,7 @@ def test_workspace_logical_identity_requires_paired_projection_declaration( path = "A01_s001_w1_z001_t001.tif" full_path = str(tmp_path / path) first = SourcePlaneProjection( - address=OpenHCSPlaneAddress.from_values("A01", 1, 1, 1, 1), + address=OpenHCSPlaneAddress(((Microscopy.Well, "A01"), (Microscopy.Site, 1), (Microscopy.Channel, 1), (Microscopy.ZIndex, 1), (Microscopy.Timepoint, 1))), ref=SourcePixelRef("disk", "/physical/shared.tif"), source_alias="Original", ) @@ -358,7 +348,7 @@ def test_workspace_logical_identity_requires_paired_projection_declaration( # Sharing a backend reference does not prove a shared logical declaration. declarations[full_path] = replace( - first, address=OpenHCSPlaneAddress.from_values("B01", 1, 1, 1, 1) + first, address=OpenHCSPlaneAddress(((Microscopy.Well, "B01"), (Microscopy.Site, 1), (Microscopy.Channel, 1), (Microscopy.ZIndex, 1), (Microscopy.Timepoint, 1))) ) assert projection.logical_path_for(lookup) == full_path assert projection.source_path_for(lookup) == "/physical/shared.tif" @@ -375,13 +365,7 @@ def test_workspace_source_projection_carries_exact_aliases_into_stack_provenance projection_set = SourceProjectionSet( tuple( SourcePlaneProjection( - address=OpenHCSPlaneAddress.from_values( - well="A01", - site="1", - channel=str(channel), - z_index="1", - timepoint="1", - ), + address=OpenHCSPlaneAddress(((Microscopy.Well, "A01"), (Microscopy.Site, "1"), (Microscopy.Channel, str(channel)), (Microscopy.ZIndex, "1"), (Microscopy.Timepoint, "1"))), ref=SourcePixelRef("disk", str(source_path)), source_alias=alias, ) @@ -482,7 +466,7 @@ def test_workspace_replay_preserves_collapsed_semantic_identity( projection_set = SourceProjectionSet( ( SourcePlaneProjection( - address=OpenHCSPlaneAddress.from_values("A14", 1, 1, 1, 1), + address=OpenHCSPlaneAddress(((Microscopy.Well, "A14"), (Microscopy.Site, 1), (Microscopy.Channel, 1), (Microscopy.ZIndex, 1), (Microscopy.Timepoint, 1))), ref=SourcePixelRef("disk", "/outputs/A14_mosaic.tif"), source_alias="neurite", image_metadata=persisted_metadata, @@ -552,13 +536,7 @@ def test_workspace_source_loading_preserves_declared_tiff_intensity_scale( ) virtual_path = "A01_s001_w1_z001_t001.tif" source_plane = SourcePlaneProjection( - address=OpenHCSPlaneAddress.from_values( - well="A01", - site="1", - channel="1", - z_index="1", - timepoint="1", - ), + address=OpenHCSPlaneAddress(((Microscopy.Well, "A01"), (Microscopy.Site, "1"), (Microscopy.Channel, "1"), (Microscopy.ZIndex, "1"), (Microscopy.Timepoint, "1"))), ref=SourcePixelRef("disk", str(source_path)), source_alias="OrigBlue", ) @@ -1461,7 +1439,7 @@ def test_step_output_anchor_uses_compiler_owned_component_scope() -> None: ), execution_group_scope=ComponentGroupScope.from_raw( ("0",), - component=AllComponents.CHANNEL, + component=Microscopy.Channel, ), compiled_function_pattern=compile_function_pattern(lambda image: image, {}, {}), ) @@ -1503,7 +1481,7 @@ def identify_secondary(image): execution_group_value="channel", execution_group_scope=ComponentGroupScope.from_raw( ("2",), - component=AllComponents.CHANNEL, + component=Microscopy.Channel, ), compiled_function_pattern=compiled_pattern, ) @@ -1557,7 +1535,7 @@ def identify_primary_objects(image, *, runtime): }, execution_group_scope=ComponentGroupScope.from_raw( ("1",), - component=AllComponents.CHANNEL, + component=Microscopy.Channel, ), consumer_variable_components=ComponentSet(), ) @@ -1577,7 +1555,7 @@ def identify_primary_objects(image, *, runtime): execution_group_value="channel", execution_group_scope=ComponentGroupScope.from_raw( ("1",), - component=AllComponents.CHANNEL, + component=Microscopy.Channel, ), compiled_function_pattern=compiled_pattern, ) @@ -1648,7 +1626,7 @@ def test_step_output_anchor_resolves_dynamic_component_scope_from_patterns() -> source_step_index=4, source_step_scope_id="crop", ), - execution_group_scope=ComponentGroupScope.dynamic(AllComponents.SITE), + execution_group_scope=ComponentGroupScope.dynamic(Microscopy.Site), compiled_function_pattern=compile_function_pattern( lambda image: image, {}, @@ -1683,7 +1661,7 @@ def test_source_anchor_uses_compiler_owned_static_component_scope() -> None: main_input_dependency=StepInputDependency.pipeline_start(), execution_group_scope=ComponentGroupScope.from_raw( ("1",), - component=AllComponents.CHANNEL, + component=Microscopy.Channel, ), compiled_function_pattern=compile_function_pattern( lambda image: image, @@ -1713,18 +1691,18 @@ def test_source_bound_anchor_filter_combines_ordered_non_grouped_source_sets() - NamedSourceBinding( alias="OrigStain1", selector=SourceSelector( - components=(ComponentSelector(AllComponents.CHANNEL, "1"),), + components=(ComponentSelector(Microscopy.Channel, "1"),), ), origin=SourceBindingOrigin.PIPELINE_START, - component_identity=(ComponentSelector(AllComponents.CHANNEL, "1"),), + component_identity=(ComponentSelector(Microscopy.Channel, "1"),), ), NamedSourceBinding( alias="OrigStain2", selector=SourceSelector( - components=(ComponentSelector(AllComponents.CHANNEL, "2"),), + components=(ComponentSelector(Microscopy.Channel, "2"),), ), origin=SourceBindingOrigin.PIPELINE_START, - component_identity=(ComponentSelector(AllComponents.CHANNEL, "2"),), + component_identity=(ComponentSelector(Microscopy.Channel, "2"),), ), ) source_binding_plan = CompiledSourceBindingPlan( @@ -1753,7 +1731,7 @@ def measure_source_set(image): path="/memory/SourceSetMeasurements.pkl", artifact_type=MeasurementsArtifactType, group_keys=("1", "2"), - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, relations=source_set_measurements.relations, ) @@ -1765,7 +1743,7 @@ def measure_source_set(image): source_binding_plan=source_binding_plan, execution_group_scope=ComponentGroupScope.from_raw( ("1", "2"), - component=AllComponents.CHANNEL, + component=Microscopy.Channel, ), compiled_function_pattern=compile_function_pattern( measure_source_set, @@ -1887,7 +1865,7 @@ def save_image(image, *, image_to_save: np.ndarray): }, execution_group_scope=ComponentGroupScope.from_raw( ("3",), - component=AllComponents.CHANNEL, + component=Microscopy.Channel, ), consumer_variable_components=ComponentSet(), ) @@ -1907,18 +1885,18 @@ def save_image(image, *, image_to_save: np.ndarray): NamedSourceBinding( alias="OrigBlue", selector=SourceSelector( - components=(ComponentSelector(AllComponents.CHANNEL, "1"),), + components=(ComponentSelector(Microscopy.Channel, "1"),), ), origin=SourceBindingOrigin.PIPELINE_START, - component_identity=(ComponentSelector(AllComponents.CHANNEL, "1"),), + component_identity=(ComponentSelector(Microscopy.Channel, "1"),), ), NamedSourceBinding( alias="OrigRed", selector=SourceSelector( - components=(ComponentSelector(AllComponents.CHANNEL, "3"),), + components=(ComponentSelector(Microscopy.Channel, "3"),), ), origin=SourceBindingOrigin.PIPELINE_START, - component_identity=(ComponentSelector(AllComponents.CHANNEL, "3"),), + component_identity=(ComponentSelector(Microscopy.Channel, "3"),), ), ), match_plan=SourceBindingMatchPlan(method=SourceBindingMatchMethod.ORDER), @@ -1931,7 +1909,7 @@ def save_image(image, *, image_to_save: np.ndarray): source_binding_plan=source_binding_plan, execution_group_scope=ComponentGroupScope.from_raw( ("3",), - component=AllComponents.CHANNEL, + component=Microscopy.Channel, ), compiled_function_pattern=compiled_pattern, ) @@ -1973,10 +1951,10 @@ def exact_source_input(image): NamedSourceBinding( alias="OrigBlue", selector=SourceSelector( - components=(ComponentSelector(AllComponents.CHANNEL, "1"),), + components=(ComponentSelector(Microscopy.Channel, "1"),), ), origin=SourceBindingOrigin.PIPELINE_START, - component_identity=(ComponentSelector(AllComponents.CHANNEL, "1"),), + component_identity=(ComponentSelector(Microscopy.Channel, "1"),), ), ), match_plan=SourceBindingMatchPlan(method=SourceBindingMatchMethod.ORDER), @@ -1989,7 +1967,7 @@ def exact_source_input(image): source_binding_plan=source_binding_plan, execution_group_scope=ComponentGroupScope.from_raw( ("1",), - component=AllComponents.CHANNEL, + component=Microscopy.Channel, ), compiled_function_pattern=compiled_pattern, ) @@ -2027,10 +2005,10 @@ def exact_source_input(image): NamedSourceBinding( alias="OrigBlue", selector=SourceSelector( - components=(ComponentSelector(AllComponents.CHANNEL, "1"),), + components=(ComponentSelector(Microscopy.Channel, "1"),), ), origin=SourceBindingOrigin.PIPELINE_START, - component_identity=(ComponentSelector(AllComponents.CHANNEL, "1"),), + component_identity=(ComponentSelector(Microscopy.Channel, "1"),), ), ), match_plan=SourceBindingMatchPlan(method=SourceBindingMatchMethod.ORDER), @@ -2043,7 +2021,7 @@ def exact_source_input(image): source_binding_plan=source_binding_plan, execution_group_scope=ComponentGroupScope.from_raw( ("1",), - component=AllComponents.CHANNEL, + component=Microscopy.Channel, ), compiled_function_pattern=compile_function_pattern(exact_source_input, {}, {}), ) @@ -2072,18 +2050,18 @@ def test_pipeline_start_anchors_project_raw_selectors_to_semantic_groups() -> No NamedSourceBinding( alias="MCP_DNA", selector=SourceSelector( - components=(ComponentSelector(AllComponents.CHANNEL, "1"),), + components=(ComponentSelector(Microscopy.Channel, "1"),), ), origin=SourceBindingOrigin.PIPELINE_START, - component_identity=(ComponentSelector(AllComponents.CHANNEL, "MCP_DNA"),), + component_identity=(ComponentSelector(Microscopy.Channel, "MCP_DNA"),), ), NamedSourceBinding( alias="MCP_AGP", selector=SourceSelector( - components=(ComponentSelector(AllComponents.CHANNEL, "2"),), + components=(ComponentSelector(Microscopy.Channel, "2"),), ), origin=SourceBindingOrigin.PIPELINE_START, - component_identity=(ComponentSelector(AllComponents.CHANNEL, "MCP_AGP"),), + component_identity=(ComponentSelector(Microscopy.Channel, "MCP_AGP"),), ), ) plan = SimpleNamespace( @@ -2092,7 +2070,7 @@ def test_pipeline_start_anchors_project_raw_selectors_to_semantic_groups() -> No source_binding_plan=CompiledSourceBindingPlan(bindings=bindings), execution_group_scope=ComponentGroupScope.from_raw( ("MCP_DNA", "MCP_AGP"), - component=AllComponents.CHANNEL, + component=Microscopy.Channel, ), compiled_function_pattern=compile_function_pattern( lambda image: image, @@ -2163,16 +2141,16 @@ def test_first_step_prepares_raw_source_anchors_under_semantic_binding_groups( NamedSourceBinding( alias="MCP_DNA", selector=SourceSelector( - components=(ComponentSelector(AllComponents.CHANNEL, "1"),), + components=(ComponentSelector(Microscopy.Channel, "1"),), ), - component_identity=(ComponentSelector(AllComponents.CHANNEL, "MCP_DNA"),), + component_identity=(ComponentSelector(Microscopy.Channel, "MCP_DNA"),), ), NamedSourceBinding( alias="MCP_AGP", selector=SourceSelector( - components=(ComponentSelector(AllComponents.CHANNEL, "2"),), + components=(ComponentSelector(Microscopy.Channel, "2"),), ), - component_identity=(ComponentSelector(AllComponents.CHANNEL, "MCP_AGP"),), + component_identity=(ComponentSelector(Microscopy.Channel, "MCP_AGP"),), ), ) pipeline_config = PipelineConfig( @@ -2248,10 +2226,10 @@ def source_bound_module(image, *, runtime): NamedSourceBinding( alias="OrigStain1", selector=SourceSelector( - components=(ComponentSelector(AllComponents.CHANNEL, "1"),), + components=(ComponentSelector(Microscopy.Channel, "1"),), ), origin=SourceBindingOrigin.PIPELINE_START, - component_identity=(ComponentSelector(AllComponents.CHANNEL, "1"),), + component_identity=(ComponentSelector(Microscopy.Channel, "1"),), ), ), match_plan=SourceBindingMatchPlan(method=SourceBindingMatchMethod.ORDER), @@ -2301,11 +2279,11 @@ def test_default_callable_runtime_scope_projects_bindings_to_selected_group() -> bindings=( NamedSourceBinding( alias="OrigStain1", - component_identity=(ComponentSelector(AllComponents.CHANNEL, "1"),), + component_identity=(ComponentSelector(Microscopy.Channel, "1"),), ), NamedSourceBinding( alias="OrigStain2", - component_identity=(ComponentSelector(AllComponents.CHANNEL, "2"),), + component_identity=(ComponentSelector(Microscopy.Channel, "2"),), ), ) ) @@ -2313,7 +2291,7 @@ def test_default_callable_runtime_scope_projects_bindings_to_selected_group() -> context=SimpleNamespace(), execution_plan=SimpleNamespace( axis_id="A01", - execution_group_scope=ComponentGroupScope.dynamic(AllComponents.CHANNEL), + execution_group_scope=ComponentGroupScope.dynamic(Microscopy.Channel), source_binding_plan=source_binding_plan, compiled_function_pattern=compile_function_pattern( lambda image: image, @@ -2341,11 +2319,11 @@ def test_dict_callable_runtime_scope_projects_bindings_to_selected_group() -> No bindings=( NamedSourceBinding( alias="OrigStain1", - component_identity=(ComponentSelector(AllComponents.CHANNEL, "1"),), + component_identity=(ComponentSelector(Microscopy.Channel, "1"),), ), NamedSourceBinding( alias="OrigStain2", - component_identity=(ComponentSelector(AllComponents.CHANNEL, "2"),), + component_identity=(ComponentSelector(Microscopy.Channel, "2"),), ), ) ) @@ -2358,7 +2336,7 @@ def test_dict_callable_runtime_scope_projects_bindings_to_selected_group() -> No context=SimpleNamespace(), execution_plan=SimpleNamespace( axis_id="A01", - execution_group_scope=ComponentGroupScope.dynamic(AllComponents.CHANNEL), + execution_group_scope=ComponentGroupScope.dynamic(Microscopy.Channel), source_binding_plan=source_binding_plan, compiled_function_pattern=compiled_pattern, ), @@ -2384,11 +2362,11 @@ def test_grouped_runtime_adapter_receives_component_selected_source_bindings() - bindings=( NamedSourceBinding( alias="OrigStain1", - component_identity=(ComponentSelector(AllComponents.CHANNEL, "1"),), + component_identity=(ComponentSelector(Microscopy.Channel, "1"),), ), NamedSourceBinding( alias="OrigStain2", - component_identity=(ComponentSelector(AllComponents.CHANNEL, "2"),), + component_identity=(ComponentSelector(Microscopy.Channel, "2"),), ), ) ) @@ -2401,10 +2379,10 @@ def test_grouped_runtime_adapter_receives_component_selected_source_bindings() - step_index=0, step_name="consume channel source", axis_id="A01", - execution_group_scope=ComponentGroupScope.dynamic(AllComponents.CHANNEL), + execution_group_scope=ComponentGroupScope.dynamic(Microscopy.Channel), source_binding_plan=source_binding_plan, compiled_function_pattern=compiled_pattern, - variable_components=(VariableComponents.SITE,), + variable_components=(Microscopy.Site,), ) scope = PatternGroupData( matching_files=["first.tif", "second.tif"], @@ -2478,7 +2456,7 @@ def test_runtime_invocation_uses_only_active_source_bound_main_flow_edges( path=f"/memory/{spec.name}.pkl", artifact_type=spec.artifact_type, group_keys=(channel,), - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, paths_by_group={channel: f"/memory/{spec.name}__{channel}.pkl"}, relations=spec.relations, ) @@ -2523,10 +2501,10 @@ def consume_channel_source(image): step_index=0, step_name="consume channel source", axis_id="A01", - execution_group_scope=ComponentGroupScope.dynamic(AllComponents.CHANNEL), + execution_group_scope=ComponentGroupScope.dynamic(Microscopy.Channel), source_binding_plan=source_binding_plan, input_memory_type="numpy", - variable_components=(VariableComponents.SITE,), + variable_components=(Microscopy.Site,), compiled_function_pattern=compiled_pattern, artifact_inputs={}, artifact_outputs=output_plans, @@ -2685,7 +2663,7 @@ def test_runtime_chain_skips_adapter_invocation_without_component_outputs( path="/memory/FirstLabels.pkl", artifact_type=first_spec.artifact_type, group_keys=("1",), - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, paths_by_group={"1": "/memory/FirstLabels_1.pkl"}, ) second_plan = ArtifactOutputPlan( @@ -2693,7 +2671,7 @@ def test_runtime_chain_skips_adapter_invocation_without_component_outputs( path="/memory/SecondLabels.pkl", artifact_type=second_spec.artifact_type, group_keys=("2",), - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, paths_by_group={"2": "/memory/SecondLabels_2.pkl"}, ) @@ -2744,10 +2722,10 @@ def record_second_labels(image, *, runtime): step_index=0, step_scope_id="pipeline::step_0", step_name="record labels", - execution_group_scope=ComponentGroupScope.dynamic(AllComponents.CHANNEL), + execution_group_scope=ComponentGroupScope.dynamic(Microscopy.Channel), source_binding_plan=CompiledSourceBindingPlan.empty(), input_memory_type="numpy", - variable_components=(VariableComponents.SITE,), + variable_components=(Microscopy.Site,), artifact_inputs={}, artifact_outputs=output_plans, ) @@ -2800,11 +2778,11 @@ def test_invocation_source_artifact_owns_cross_component_runtime_binding_scope() bindings=( NamedSourceBinding( alias="OrigStain1", - component_identity=(ComponentSelector(AllComponents.CHANNEL, "1"),), + component_identity=(ComponentSelector(Microscopy.Channel, "1"),), ), NamedSourceBinding( alias="OrigStain2", - component_identity=(ComponentSelector(AllComponents.CHANNEL, "2"),), + component_identity=(ComponentSelector(Microscopy.Channel, "2"),), ), ) ) @@ -2819,7 +2797,7 @@ def exact_source_input(image): context=SimpleNamespace(), execution_plan=SimpleNamespace( axis_id="A01", - execution_group_scope=ComponentGroupScope.dynamic(AllComponents.SITE), + execution_group_scope=ComponentGroupScope.dynamic(Microscopy.Site), source_binding_plan=source_binding_plan, compiled_function_pattern=compiled_pattern, ), @@ -2839,11 +2817,11 @@ def test_main_flow_input_owns_runtime_binding_scope_with_auxiliary_source() -> N bindings=( NamedSourceBinding( alias="OrigStain1", - component_identity=(ComponentSelector(AllComponents.CHANNEL, "1"),), + component_identity=(ComponentSelector(Microscopy.Channel, "1"),), ), NamedSourceBinding( alias="OrigStain2", - component_identity=(ComponentSelector(AllComponents.CHANNEL, "2"),), + component_identity=(ComponentSelector(Microscopy.Channel, "2"),), ), ) ) @@ -2894,7 +2872,7 @@ def main_flow_with_auxiliary_source(image): context=SimpleNamespace(), execution_plan=SimpleNamespace( axis_id="A01", - execution_group_scope=ComponentGroupScope.dynamic(AllComponents.CHANNEL), + execution_group_scope=ComponentGroupScope.dynamic(Microscopy.Channel), source_binding_plan=source_binding_plan, compiled_function_pattern=compiled_pattern, ), @@ -2918,7 +2896,7 @@ def test_payload_provenance_excludes_auxiliary_binding_from_main_flow_scope() -> bindings=( NamedSourceBinding( alias="FilenamePrefix", - component_identity=(ComponentSelector(AllComponents.CHANNEL, "1"),), + component_identity=(ComponentSelector(Microscopy.Channel, "1"),), ), ) ) @@ -2937,9 +2915,9 @@ def save_main_flow_with_source_prefix(image): context=SimpleNamespace(), execution_plan=SimpleNamespace( axis_id="A01", - execution_group_scope=ComponentGroupScope.dynamic(AllComponents.CHANNEL), + execution_group_scope=ComponentGroupScope.dynamic(Microscopy.Channel), source_binding_plan=source_binding_plan, - variable_components=(VariableComponents.SITE,), + variable_components=(Microscopy.Site,), compiled_function_pattern=compiled_pattern, ), compiled_group=compiled_pattern.default_group, @@ -2962,7 +2940,7 @@ def test_payload_provenance_outranks_unrelated_artifact_execution_group() -> Non bindings=( NamedSourceBinding( alias="OrigGreen", - component_identity=(ComponentSelector(AllComponents.CHANNEL, "2"),), + component_identity=(ComponentSelector(Microscopy.Channel, "2"),), ), ) ) @@ -2973,10 +2951,10 @@ def test_payload_provenance_outranks_unrelated_artifact_execution_group() -> Non axis_id="A01", execution_group_scope=ComponentGroupScope.from_raw( ("1",), - component=AllComponents.CHANNEL, + component=Microscopy.Channel, ), source_binding_plan=source_binding_plan, - variable_components=(VariableComponents.SITE,), + variable_components=(Microscopy.Site,), ), compiled_group=compiled_pattern.default_group, component_value="1", @@ -3000,7 +2978,7 @@ def test_payload_provenance_preserves_bindings_across_a_variable_stack_axis() -> bindings=tuple( NamedSourceBinding( alias=alias, - component_identity=(ComponentSelector(AllComponents.CHANNEL, channel),), + component_identity=(ComponentSelector(Microscopy.Channel, channel),), ) for alias, channel in (("OrigBlue", "1"), ("OrigGreen", "2")) ) @@ -3046,9 +3024,9 @@ def consume_channel_stack(image): context=SimpleNamespace(), execution_plan=SimpleNamespace( axis_id="A01", - execution_group_scope=ComponentGroupScope.dynamic(AllComponents.SITE), + execution_group_scope=ComponentGroupScope.dynamic(Microscopy.Site), source_binding_plan=source_binding_plan, - variable_components=(VariableComponents.CHANNEL,), + variable_components=(Microscopy.Channel,), ), compiled_group=compiled_group, component_value="1", @@ -3072,7 +3050,7 @@ def test_main_flow_source_scope_intersects_cross_component_invocation_inputs() - bindings=tuple( NamedSourceBinding( alias=alias, - component_identity=(ComponentSelector(AllComponents.CHANNEL, channel),), + component_identity=(ComponentSelector(Microscopy.Channel, channel),), ) for alias, channel in ( ("Worms", "1"), @@ -3123,7 +3101,7 @@ def consume_selected_channels(image): context=SimpleNamespace(), execution_plan=SimpleNamespace( axis_id="A01", - execution_group_scope=ComponentGroupScope.dynamic(AllComponents.SITE), + execution_group_scope=ComponentGroupScope.dynamic(Microscopy.Site), source_binding_plan=source_binding_plan, compiled_function_pattern=compiled_pattern, ), @@ -3147,7 +3125,7 @@ def test_special_input_preserves_ordered_declared_main_flow_sources() -> None: bindings=tuple( NamedSourceBinding( alias=alias, - component_identity=(ComponentSelector(AllComponents.CHANNEL, channel),), + component_identity=(ComponentSelector(Microscopy.Channel, channel),), ) for alias, channel in (("SMI312", "4"), ("Hoechst", "1")) ) @@ -3188,7 +3166,7 @@ def measure_neurites(image, pixel_size=1.0): context=SimpleNamespace(), execution_plan=SimpleNamespace( axis_id="R04C09", - execution_group_scope=ComponentGroupScope.dynamic(AllComponents.SITE), + execution_group_scope=ComponentGroupScope.dynamic(Microscopy.Site), source_binding_plan=source_binding_plan, compiled_function_pattern=compiled_pattern, ), @@ -3239,11 +3217,11 @@ def test_pipeline_start_main_flow_survives_prior_producer_image_input( ) primary_source = NamedSourceBinding( alias="Primary", - component_identity=(ComponentSelector(AllComponents.CHANNEL, "1"),), + component_identity=(ComponentSelector(Microscopy.Channel, "1"),), ) pipeline_start = LazyProcessingConfig( - variable_components=[VariableComponents.SITE], - group_by=GroupBy.CHANNEL, + variable_components=[Microscopy.Site], + group_by=Microscopy.Channel, input_source=InputSource.PIPELINE_START, ) steps = [ @@ -3325,11 +3303,11 @@ def test_runtime_plane_count_comes_from_loaded_slices_not_dispatch_groups() -> N plan = SimpleNamespace( axis_id="A01", - execution_group_scope=ComponentGroupScope.dynamic(AllComponents.CHANNEL), + execution_group_scope=ComponentGroupScope.dynamic(Microscopy.Channel), source_binding_plan=CompiledSourceBindingPlan(), artifact_inputs={}, artifact_outputs={}, - variable_components=(VariableComponents.SITE,), + variable_components=(Microscopy.Site,), ) request = PatternGroupExecutionRequest( context=SimpleNamespace(), @@ -3380,8 +3358,8 @@ def test_runtime_plane_count_comes_from_loaded_slices_not_dispatch_groups() -> N assert scope.runtime_plane_count == 2 assert scope.axis_scope.fixed_component_values == ( - (AllComponents.Z_INDEX, "3"), - (AllComponents.TIMEPOINT, "2"), + (Microscopy.ZIndex, "3"), + (Microscopy.Timepoint, "2"), ) @@ -3403,7 +3381,7 @@ def test_grouped_main_flow_context_uses_component_selected_output_plan() -> None path="/memory/CorrectedStain1.pkl", artifact_type=corrected_stain_1_spec.artifact_type, group_keys=("1",), - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, paths_by_group={"1": "/memory/CorrectedStain1_1.pkl"}, ) corrected_stain_2 = ArtifactOutputPlan( @@ -3411,7 +3389,7 @@ def test_grouped_main_flow_context_uses_component_selected_output_plan() -> None path="/memory/CorrectedStain2.pkl", artifact_type=corrected_stain_2_spec.artifact_type, group_keys=("2",), - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, paths_by_group={"2": "/memory/CorrectedStain2_2.pkl"}, ) plan = SimpleNamespace( @@ -3419,7 +3397,7 @@ def test_grouped_main_flow_context_uses_component_selected_output_plan() -> None artifact_outputs={ plan.ref(): plan for plan in (corrected_stain_1, corrected_stain_2) }, - execution_group_scope=ComponentGroupScope.dynamic(AllComponents.CHANNEL), + execution_group_scope=ComponentGroupScope.dynamic(Microscopy.Channel), source_binding_plan=CompiledSourceBindingPlan(), ) @@ -3518,7 +3496,7 @@ def test_component_output_selection_keeps_distinct_axes_with_equal_keys() -> Non path="/memory/Stain1.pkl", artifact_type=ImageArtifactType, group_keys=("1",), - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, paths_by_group={"1": "/memory/Stain1_1.pkl"}, ) channel_2 = ArtifactOutputPlan( @@ -3526,13 +3504,13 @@ def test_component_output_selection_keeps_distinct_axes_with_equal_keys() -> Non path="/memory/Stain2.pkl", artifact_type=ImageArtifactType, group_keys=("2",), - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, paths_by_group={"2": "/memory/Stain2_2.pkl"}, ) plan = SimpleNamespace( artifact_inputs={}, artifact_outputs={plan.ref(): plan for plan in (channel_1, channel_2)}, - execution_group_scope=ComponentGroupScope.dynamic(AllComponents.SITE), + execution_group_scope=ComponentGroupScope.dynamic(Microscopy.Site), ) selected = PatternGroupExecutionScope._select_output_plans_for_component( @@ -3633,7 +3611,7 @@ def test_grouped_runtime_scope_preserves_empty_source_binding_plan() -> None: context=SimpleNamespace(), execution_plan=SimpleNamespace( axis_id="A01", - execution_group_scope=ComponentGroupScope.dynamic(AllComponents.SITE), + execution_group_scope=ComponentGroupScope.dynamic(Microscopy.Site), source_binding_plan=source_binding_plan, ), compiled_group=compiled_pattern.default_group, @@ -3661,7 +3639,7 @@ def test_grouped_runtime_source_expansion_uses_scoped_bindings( ), ) ), - component_identity=(ComponentSelector(AllComponents.CHANNEL, "1"),), + component_identity=(ComponentSelector(Microscopy.Channel, "1"),), ), NamedSourceBinding( alias="OrigStain2", @@ -3674,7 +3652,7 @@ def test_grouped_runtime_source_expansion_uses_scoped_bindings( ), ) ), - component_identity=(ComponentSelector(AllComponents.CHANNEL, "2"),), + component_identity=(ComponentSelector(Microscopy.Channel, "2"),), ), ) ) @@ -3686,16 +3664,16 @@ def test_grouped_runtime_source_expansion_uses_scoped_bindings( runtime = function_runtime.PatternGroupExecutionRequest( context=SimpleNamespace( source_image_set_identity_policy=SourceImageSetIdentityPolicy( - frozenset((AllComponents.SITE,)) + frozenset((Microscopy.Site,)) ) ), execution_plan=SimpleNamespace( axis_id="A01", - execution_group_scope=ComponentGroupScope.dynamic(AllComponents.CHANNEL), + execution_group_scope=ComponentGroupScope.dynamic(Microscopy.Channel), main_input_dependency=StepInputDependency.pipeline_start(), source_binding_plan=source_binding_plan, compiled_function_pattern=compiled_pattern, - variable_component_values=(VariableComponents.SITE.value,), + variable_component_values=(Microscopy.Site.name,), ), compiled_group=compiled_pattern.require_group("1"), component_value="1", @@ -3753,13 +3731,7 @@ def test_alias_only_workspace_filter_excludes_unselected_source_and_orders_stack ) source_planes = tuple( SourcePlaneProjection( - address=OpenHCSPlaneAddress.from_values( - well="R04C09", - site="11", - channel=channel, - z_index="1", - timepoint="1", - ), + address=OpenHCSPlaneAddress(((Microscopy.Well, "R04C09"), (Microscopy.Site, "11"), (Microscopy.Channel, channel), (Microscopy.ZIndex, "1"), (Microscopy.Timepoint, "1"))), ref=SourcePixelRef("disk", f"/source/ch{channel}.tiff"), source_alias=binding.alias, ) @@ -3833,11 +3805,11 @@ def test_unbound_workspace_source_keeps_filename_component_provenance( source_ref = SourcePixelRef("disk", str(tmp_path / "raw-image.tif")) source_metadata = { SOURCE_BINDING_ALIAS_METADATA_FIELD: "OrigDNA", - AllComponents.SITE.value: 2, - AllComponents.CHANNEL.value: 1, - AllComponents.Z_INDEX.value: 3, - AllComponents.TIMEPOINT.value: 4, - AllComponents.WELL.value: "A01", + Microscopy.Site.name: 2, + Microscopy.Channel.name: 1, + Microscopy.ZIndex.name: 3, + Microscopy.Timepoint.name: 4, + Microscopy.Well.name: "A01", SourceFilterSubject.EXTENSION.value: ".tif", } projection = VirtualWorkspaceSourceProjection( @@ -3845,13 +3817,7 @@ def test_unbound_workspace_source_keeps_filename_component_provenance( source_metadata_by_path={virtual_path: source_metadata}, source_projections_by_virtual_path={ virtual_path: SourcePlaneProjection( - address=OpenHCSPlaneAddress.from_values( - well="A01", - site="2", - channel="1", - z_index="3", - timepoint="4", - ), + address=OpenHCSPlaneAddress(((Microscopy.Well, "A01"), (Microscopy.Site, "2"), (Microscopy.Channel, "1"), (Microscopy.ZIndex, "3"), (Microscopy.Timepoint, "4"))), ref=source_ref, source_alias="OrigDNA", source_metadata=source_metadata, @@ -3907,11 +3873,11 @@ def resolve_address(backend_address, backend, *, base_path): ) assert image_payload_metadata(projected).source_component_metadata == { - AllComponents.SITE.value: 2, - AllComponents.CHANNEL.value: 1, - AllComponents.Z_INDEX.value: 3, - AllComponents.TIMEPOINT.value: 4, - AllComponents.WELL.value: "A01", + Microscopy.Site.name: 2, + Microscopy.Channel.name: 1, + Microscopy.ZIndex.name: 3, + Microscopy.Timepoint.name: 4, + Microscopy.Well.name: "A01", SourceFilterSubject.EXTENSION.value: ".tif", } assert image_payload_metadata( @@ -4000,13 +3966,7 @@ def test_producer_anchored_pipeline_start_paths_use_exact_source_projection_bund ) source_planes = tuple( SourcePlaneProjection( - address=OpenHCSPlaneAddress.from_values( - well="A01", - site="1", - channel=str(channel), - z_index="1", - timepoint="1", - ), + address=OpenHCSPlaneAddress(((Microscopy.Well, "A01"), (Microscopy.Site, "1"), (Microscopy.Channel, str(channel)), (Microscopy.ZIndex, "1"), (Microscopy.Timepoint, "1"))), ref=SourcePixelRef("disk", str(source_path)), source_alias=alias, ) @@ -4202,7 +4162,7 @@ def load_batch(self, paths, backend): axis_id="A01", input_dir=tmp_path, input_memory_type="numpy", - variable_components=(VariableComponents.Z_INDEX,), + variable_components=(Microscopy.ZIndex,), compiled_function_pattern=compile_function_pattern(lambda image: image, {}, {}), main_input_dependency=StepInputDependency.step_output( source_step_index=0, @@ -4324,7 +4284,7 @@ def test_ungrouped_runtime_scope_omits_axis_component() -> None: context=SimpleNamespace(), execution_plan=SimpleNamespace( axis_id="A01", - group_by_value=GroupBy.CHANNEL.value, + group_by_value=Microscopy.Channel.name, execution_group_value=None, ), compiled_group=SimpleNamespace(), @@ -5158,7 +5118,7 @@ def test_function_output_path_uses_variable_component_identity( output_dir=tmp_path, output_payload=payload, input_path=None, - variable_components=(VariableComponents.Z_INDEX,), + variable_components=(Microscopy.ZIndex,), ) identity = FunctionOutputIdentity.from_request(request) @@ -5213,7 +5173,7 @@ def test_collapsed_output_identity_uses_retained_source_contributors( output_dir=tmp_path, output_payload=payload, input_path=None, - variable_components=(VariableComponents.SITE,), + variable_components=(Microscopy.Site,), ) identity = FunctionOutputIdentity.from_request(request) @@ -5285,7 +5245,7 @@ def test_composite_then_z_collapse_uses_current_scalar_identity( output_dir=tmp_path, output_payload=payload, input_path="A01_s001_w1_z001_t001.tif", - variable_components=(VariableComponents.Z_INDEX,), + variable_components=(Microscopy.ZIndex,), ) identity = FunctionOutputIdentity.from_request(request) @@ -5322,7 +5282,7 @@ def test_variable_component_identity_uses_fallback_path_extension( output_dir=tmp_path, output_payload=payload, input_path="A01_s001_w2_z001_t001.png", - variable_components=(VariableComponents.CHANNEL,), + variable_components=(Microscopy.Channel,), ) identity = FunctionOutputIdentity.from_request(request) @@ -5394,7 +5354,7 @@ def test_function_output_path_rejects_variation_outside_identity_components( output_dir=tmp_path, output_payload=payload, input_path=None, - variable_components=(VariableComponents.Z_INDEX,), + variable_components=(Microscopy.ZIndex,), ) ) @@ -5418,7 +5378,7 @@ def test_function_output_path_rejects_group_by_component_stack_variation( output_dir=tmp_path, output_payload=payload, input_path=None, - variable_components=(VariableComponents.SITE,), + variable_components=(Microscopy.Site,), ) ) @@ -5439,7 +5399,7 @@ def test_input_aligned_stack_output_uses_input_filename_identity( output_dir=tmp_path, output_payload=payload, input_path="A01_s002_w1_z001_t001.png", - variable_components=(VariableComponents.SITE,), + variable_components=(Microscopy.Site,), input_aligned_output=True, ) @@ -5483,7 +5443,7 @@ def test_function_output_path_keeps_payload_split_axis_over_input_alignment( output_dir=tmp_path, output_payload=payload, input_path="A01_s003_w1_z001_t001.tif", - variable_components=(VariableComponents.SITE,), + variable_components=(Microscopy.Site,), input_aligned_output=True, ) @@ -5556,7 +5516,7 @@ def save_batch( axis_id="A01", output_dir=tmp_path, output_memory_type="numpy", - variable_components=(VariableComponents.SITE,), + variable_components=(Microscopy.Site,), step_name="ExplicitIdentity", pipeline_position=0, step_scope_id="explicit-identity", diff --git a/tests/unit/test_function_step_execution_plan.py b/tests/unit/test_function_step_execution_plan.py index 2f4df908db..d33b7c6766 100644 --- a/tests/unit/test_function_step_execution_plan.py +++ b/tests/unit/test_function_step_execution_plan.py @@ -5,7 +5,7 @@ import pytest -from openhcs.constants.constants import AllComponents, MemoryType, VariableComponents +from openhcs.constants.constants import MemoryType from openhcs.core.compiled_step_plan import ( CompiledStepPlan, FrameworkDeviceAssignment, @@ -43,6 +43,7 @@ RuntimeArtifactMaterialization, ) from openhcs.core.steps.function_runtime import PatternGroupExecutionScope +from openhcs.domains.microscopy.axes import Microscopy def noop(image): @@ -67,7 +68,7 @@ def _compiled_plan(**overrides): axis_id="A01", input_dir=Path("/tmp/input"), output_dir=Path("/tmp/output"), - variable_components=(VariableComponents.SITE,), + variable_components=(Microscopy.Site,), group_by=None, main_input_dependency=StepInputDependency.step_output( source_step_index=1, @@ -110,7 +111,7 @@ def test_compiled_step_plan_is_the_runtime_plan_owner(): compiled_plan = _compiled_plan( execution_group_scope=ComponentGroupScope.from_raw( ("2",), - component=VariableComponents.SITE, + component=Microscopy.Site, ) ) plan = compiled_plan.require_function_execution_ready() @@ -123,7 +124,7 @@ def test_compiled_step_plan_is_the_runtime_plan_owner(): } assert plan.step_scope_id == "plate::functionstep_2" assert plan.execution_group_scope.keys == ("2",) - assert plan.variable_components == (VariableComponents.SITE,) + assert plan.variable_components == (Microscopy.Site,) assert plan.main_input_dependency.kind is StepInputDependencyKind.STEP_OUTPUT assert plan.main_input_dependency.source_step_scope_id == "plate::functionstep_1" assert plan.source_binding_plan.is_empty @@ -410,7 +411,7 @@ def test_component_artifact_plan_selection_merges_global_and_group_outputs(): path="/tmp/measurements/A01", artifact_type=MeasurementsArtifactType, group_keys=("A01",), - group_component=AllComponents.WELL, + group_component=Microscopy.Well, paths_by_group={"A01": "/tmp/measurements/A01"}, ) @@ -419,7 +420,7 @@ def test_component_artifact_plan_selection_merges_global_and_group_outputs(): global_output.ref(): global_output, grouped_output.ref(): grouped_output, }, - ComponentGroupScope(("A01",), component=AllComponents.WELL), + ComponentGroupScope(("A01",), component=Microscopy.Well), "A01", ) @@ -435,13 +436,13 @@ def test_component_artifact_plan_selection_omits_unscoped_outputs_for_missing_gr path="/tmp/objects", artifact_type=ObjectLabelsArtifactType, group_keys=("3",), - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, paths_by_group={"3": "/tmp/objects_w3"}, ) selected = PatternGroupExecutionScope._select_output_plans_for_component( {output.ref(): output}, - ComponentGroupScope(("1", "3"), component=AllComponents.CHANNEL), + ComponentGroupScope(("1", "3"), component=Microscopy.Channel), "1", ) @@ -454,7 +455,7 @@ def test_default_invocation_keeps_compiled_grouped_output_plan(): path="/tmp/measurements", artifact_type=MeasurementsArtifactType, group_keys=("1", "3", "2"), - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, paths_by_group={ "1": "/tmp/w1_measurements", "3": "/tmp/w3_measurements", @@ -490,7 +491,7 @@ def publish_channels(image, *, runtime): path="/memory/channel_one.pkl", artifact_type=channel_one_spec.artifact_type, group_keys=("1",), - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, paths_by_group={"1": "/memory/channel_one__1.pkl"}, ) channel_two = ArtifactOutputPlan( @@ -498,7 +499,7 @@ def publish_channels(image, *, runtime): path="/memory/channel_two.pkl", artifact_type=channel_two_spec.artifact_type, group_keys=("2",), - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, paths_by_group={"2": "/memory/channel_two__2.pkl"}, ) invocation = compile_function_pattern( @@ -520,7 +521,7 @@ def test_invocation_output_selection_omits_inactive_component_outputs(): {channel_one.ref(): channel_one}, compiled_output_plans=invocation.output_plans_for_component( ComponentGroupScope.from_raw( - ("1", "2"), component=AllComponents.CHANNEL, + ("1", "2"), component=Microscopy.Channel, ), "1", ), @@ -657,7 +658,7 @@ def publish_derived_channels(image, *, illumination_function=None, runtime): path=f"/memory/{spec.name}.pkl", artifact_type=spec.artifact_type, group_keys=(channel,), - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, paths_by_group={channel: f"/memory/{spec.name}__{channel}.pkl"}, relations=spec.relations, ) @@ -673,7 +674,7 @@ def publish_derived_channels(image, *, illumination_function=None, runtime): ).default_group.invocations[0] execution_scope = ComponentGroupScope.from_raw( ("1", "2"), - component=AllComponents.CHANNEL, + component=Microscopy.Channel, ) invocation = invocation.with_artifact_input_edges( tuple( @@ -746,7 +747,7 @@ def test_invocation_output_selection_rejects_missing_active_component_output(): {}, compiled_output_plans=invocation.output_plans_for_component( ComponentGroupScope.from_raw( - ("1", "2"), component=AllComponents.CHANNEL, + ("1", "2"), component=Microscopy.Channel, ), "1", ), @@ -760,7 +761,7 @@ def test_invocation_output_selection_rejects_active_projection_drift(): path="/memory/drifted_channel_one.pkl", artifact_type=channel_one.artifact_type, group_keys=("1",), - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, paths_by_group={"1": "/memory/drifted_channel_one__1.pkl"}, ) @@ -769,7 +770,7 @@ def test_invocation_output_selection_rejects_active_projection_drift(): {drifted_channel_one.ref(): drifted_channel_one}, compiled_output_plans=invocation.output_plans_for_component( ComponentGroupScope.from_raw( - ("1", "2"), component=AllComponents.CHANNEL, + ("1", "2"), component=Microscopy.Channel, ), "1", ), @@ -794,7 +795,7 @@ def apply_illumination(image, *, runtime): path="/tmp/IllumStain1", artifact_type=ImageArtifactType, group_keys=("1",), - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, ) invocation = compile_function_pattern( apply_illumination, @@ -803,7 +804,7 @@ def apply_illumination(image, *, runtime): ).default_group.invocations[0] scope = ComponentGroupScope.from_raw( ("1",), - component=AllComponents.CHANNEL, + component=Microscopy.Channel, ) edge = InvocationArtifactInputEdgePlan( key=InvocationArtifactInputProjectionKey( @@ -820,7 +821,7 @@ def apply_illumination(image, *, runtime): invocation_scope=scope, producer_selection_scope=scope, component_scopes=(scope,), - consumer_variable_components=(AllComponents.SITE,), + consumer_variable_components=(Microscopy.Site,), ), ) invocation = invocation.with_artifact_input_edges((edge,)) diff --git a/tests/unit/test_function_step_execution_scope.py b/tests/unit/test_function_step_execution_scope.py index 88ba7fe27c..5f8e000839 100644 --- a/tests/unit/test_function_step_execution_scope.py +++ b/tests/unit/test_function_step_execution_scope.py @@ -13,7 +13,7 @@ from polystore.filemanager import FileManager from polystore.memory import MemoryStorageBackend -from openhcs.constants.constants import AllComponents, Backend +from openhcs.constants.constants import Backend from openhcs.core.artifacts import ( ArtifactInputPlan, ArtifactOutputPlan, @@ -86,6 +86,8 @@ from openhcs.core.steps.function_step import FunctionStep from openhcs.microscopes.source_schema import SourceSchemaFilenameParser from openhcs.processing.materialization import FileBundleOptions, MaterializationSpec +from openhcs.core.axes import Axis +from openhcs.domains.microscopy.axes import Microscopy def test_runtime_step_values_share_within_step_and_release_between_steps() -> None: @@ -110,7 +112,7 @@ class Counter: def test_runtime_axis_scope_returns_exact_complete_plane_selection() -> None: scope = RuntimeExecutionAxisScope.from_raw( "A01", - component=AllComponents.CHANNEL, + component=Microscopy.Channel, value="1", ) @@ -125,7 +127,7 @@ def test_runtime_axis_scope_returns_exact_complete_plane_selection() -> None: def test_runtime_axis_scope_returns_none_only_without_declared_component_axis() -> None: scope = RuntimeExecutionAxisScope.from_raw( "A01", - component=AllComponents.CHANNEL, + component=Microscopy.Channel, value="1", ) @@ -138,13 +140,13 @@ def test_runtime_axis_scope_joins_correlated_rows_without_inventing_states() -> rows = tuple( RuntimeExecutionAxisScope.from_raw( "A01", component=None, value=None, - fixed_component_values=((AllComponents.SITE, site), (AllComponents.TIMEPOINT, timepoint)), + fixed_component_values=((Microscopy.Site, site), (Microscopy.Timepoint, timepoint)), ) for site, timepoint in (("1", "3"), ("2", "4")) ) time_three = RuntimeExecutionAxisScope.from_raw( "A01", component=None, value=None, - fixed_component_values=((AllComponents.TIMEPOINT, "3"),), + fixed_component_values=((Microscopy.Timepoint, "3"),), ) joined = tuple( result for row in rows @@ -158,7 +160,7 @@ def test_runtime_axis_scope_empty_context_broadcasts_to_actual_correlated_row() empty = RuntimeExecutionAxisScope.from_raw("A01", component=None, value=None) source = RuntimeExecutionAxisScope.from_raw( "A01", component=None, value=None, - fixed_component_values=((AllComponents.SITE, "1"), (AllComponents.TIMEPOINT, "3")), + fixed_component_values=((Microscopy.Site, "1"), (Microscopy.Timepoint, "3")), ) assert empty.join_execution_cohort(source) == source assert source.join_execution_cohort(empty) == source @@ -166,12 +168,12 @@ def test_runtime_axis_scope_empty_context_broadcasts_to_actual_correlated_row() @pytest.mark.parametrize("axis,component,value", [ - ("B01", AllComponents.CHANNEL, "1"), - ("A01", AllComponents.SITE, "1"), - ("A01", AllComponents.CHANNEL, "2"), + ("B01", Microscopy.Channel, "1"), + ("A01", Microscopy.Site, "1"), + ("A01", Microscopy.Channel, "2"), ]) def test_runtime_axis_scope_cannot_join_other_execution_group(axis, component, value) -> None: - own = RuntimeExecutionAxisScope.from_raw("A01", component=AllComponents.CHANNEL, value="1") + own = RuntimeExecutionAxisScope.from_raw("A01", component=Microscopy.Channel, value="1") other = RuntimeExecutionAxisScope.from_raw(axis, component=component, value=value) assert own.join_execution_cohort(other) is None @@ -179,15 +181,15 @@ def test_runtime_axis_scope_cannot_join_other_execution_group(axis, component, v def test_runtime_axis_scope_join_derives_partial_fixed_context_union() -> None: left = RuntimeExecutionAxisScope.from_raw( "A01", component=None, value=None, - fixed_component_values=((AllComponents.SITE, "1"), (AllComponents.TIMEPOINT, "3")), + fixed_component_values=((Microscopy.Site, "1"), (Microscopy.Timepoint, "3")), ) right = RuntimeExecutionAxisScope.from_raw( "A01", component=None, value=None, - fixed_component_values=((AllComponents.TIMEPOINT, "3"), (AllComponents.Z_INDEX, "2")), + fixed_component_values=((Microscopy.Timepoint, "3"), (Microscopy.ZIndex, "2")), ) expected = RuntimeExecutionAxisScope.from_raw( "A01", component=None, value=None, - fixed_component_values=((AllComponents.SITE, "1"), (AllComponents.TIMEPOINT, "3"), (AllComponents.Z_INDEX, "2")), + fixed_component_values=((Microscopy.Site, "1"), (Microscopy.Timepoint, "3"), (Microscopy.ZIndex, "2")), ) assert left.join_execution_cohort(right) == expected assert right.join_execution_cohort(left) == expected @@ -468,7 +470,7 @@ def _record_measurements( path: str, count: int, object_name: str | None = None, - group_component: AllComponents | None = None, + group_component: type[Axis] | None = None, group_key: str | None = None, ) -> None: output_plan = ArtifactOutputPlan( @@ -989,7 +991,7 @@ def export(*, artifact_batch: RuntimeArtifactBatch): ) context = _plate_context("A01", (plan,)) context.source_image_set_identity_policy = SourceImageSetIdentityPolicy( - frozenset((AllComponents.CHANNEL,)) + frozenset((Microscopy.Channel,)) ) _record_measurements( context, @@ -1002,7 +1004,7 @@ def export(*, artifact_batch: RuntimeArtifactBatch): assert len(batches) == 1 assert batches[0].source_image_set_identity_policy.plane_member_components == ( - frozenset((AllComponents.CHANNEL,)) + frozenset((Microscopy.Channel,)) ) @@ -1032,7 +1034,7 @@ def export(*, artifact_batch: RuntimeArtifactBatch): name=measurement_spec.name, path=input_path, artifact_type=measurement_spec.artifact_type, - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, paths_by_group={None: input_path}, ), ), @@ -1050,7 +1052,7 @@ def export(*, artifact_batch: RuntimeArtifactBatch): name=measurement_spec.name, path=f"/memory/A01/measurements_w{group_key}", count=int(group_key), - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, group_key=group_key, ) diff --git a/tests/unit/test_function_step_transport.py b/tests/unit/test_function_step_transport.py index b61149f0cb..e4e990be5c 100644 --- a/tests/unit/test_function_step_transport.py +++ b/tests/unit/test_function_step_transport.py @@ -16,7 +16,6 @@ import pytest from zmqruntime.messages import ControlMessageType, MessageFields -from openhcs.constants.constants import GroupBy, VariableComponents from openhcs.core.config import ( GlobalPipelineConfig, LazyProcessingConfig, @@ -45,6 +44,7 @@ ZMQExecutionClient, ZMQExecutionRequestBuilder, ) +from openhcs.domains.microscopy.axes import Microscopy def _execute_spawned_custom_invocation( @@ -81,8 +81,8 @@ def _public_step() -> FunctionStep: ), name="CorrectIlluminationApply", processing_config=LazyProcessingConfig( - variable_components=[VariableComponents.CHANNEL], - group_by=GroupBy.SITE, + variable_components=[Microscopy.Channel], + group_by=Microscopy.Site, ), ) @@ -317,9 +317,9 @@ def test_transport_preserves_explicit_lazy_processing_defaults() -> None: restored = FunctionStepTransportAuthority.pipeline_steps_from_namespace(namespace) assert restored[0].processing_config.variable_components == [ - VariableComponents.CHANNEL + Microscopy.Channel ] - assert restored[0].processing_config.group_by is GroupBy.SITE + assert restored[0].processing_config.group_by is Microscopy.Site def test_cellprofiler_callable_uses_registered_function_reference() -> None: diff --git a/tests/unit/test_g1_cutover_tool.py b/tests/unit/test_g1_cutover_tool.py new file mode 100644 index 0000000000..a8a28ba54e --- /dev/null +++ b/tests/unit/test_g1_cutover_tool.py @@ -0,0 +1,117 @@ +"""The one-shot G1 cutover converts pre-G1 pycodify sources onto the axis family. + +The fixtures were rendered by pre-G1 ``main`` (34abdf41e). This test and its +fixtures are deleted with ``tools/cutover/g1_axis_family.py``. +""" + +from __future__ import annotations + +import importlib.util +import shutil +from pathlib import Path + +import openhcs +from openhcs.core.axes import ColourAxis, StackAxis, Ungrouped +from openhcs.core.config import ( + FijiDimensionMode, + GlobalPipelineConfig, + NapariDimensionMode, +) +from openhcs.core.config_document import ConfigDocumentAuthority +from openhcs.core.pipeline.funcstep_contract_validator import ( + FuncStepContractValidator, +) +from openhcs.core.pipeline_document import PipelineDocumentAuthority +from openhcs.domains.microscopy.axes import Microscopy + +REPO_ROOT = Path(openhcs.__file__).resolve().parents[1] +FIXTURES = REPO_ROOT / "tests" / "fixtures" / "g1_cutover" + + +def _cutover(): + spec = importlib.util.spec_from_file_location( + "g1_axis_family_cutover", REPO_ROOT / "tools" / "cutover" / "g1_axis_family.py" + ) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def _migrated(tmp_path: Path, fixture: str, name: str) -> tuple[Path, str]: + target = tmp_path / name + shutil.copy(FIXTURES / fixture, target) + original = target.read_text() + assert _cutover().migrate(target) is True + assert (tmp_path / f"{name}.pre-g1").read_text() == original + return target, original + + +def test_pre_g1_pipeline_loads_and_validates_on_the_axis_family(tmp_path) -> None: + target, original = _migrated(tmp_path, "pre_g1_pipeline.py.fixture", "pipeline.py") + assert "VariableComponents" in original and "GroupBy.NONE" in original + + document = PipelineDocumentAuthority.from_source(target.read_text()) + + normalize, project = document.pipeline_steps + assert project.processing_config.variable_components == [Microscopy.ZIndex] + assert project.processing_config.group_by is Ungrouped + assert project.napari_streaming_config.colour_mode is NapariDimensionMode.LAYER + assert project.napari_streaming_config.partition_mode is NapariDimensionMode.LAYER + assert project.fiji_streaming_config.stack_mode is FijiDimensionMode.FRAME + assert document.pipeline_config.sequential_processing_config.sequential_components == [ + Microscopy.Channel + ] + for step in document.pipeline_steps: + FuncStepContractValidator.validate_funcstep(step) + assert normalize.name == "normalize" + + +def test_pre_g1_config_document_loads_on_the_axis_family(tmp_path) -> None: + target, _ = _migrated( + tmp_path, "pre_g1_global_config.config.fixture", "global_config.config" + ) + + config = ConfigDocumentAuthority.from_source( + target.read_text(), expected_config_type=GlobalPipelineConfig + ) + + assert config.sequential_processing_config.sequential_components == [ + Microscopy.Timepoint + ] + + +def test_function_requirement_decorators_become_role_declarations() -> None: + source = ( + "from openhcs.constants.constants import GroupBy, VariableComponents\n" + "from openhcs.core.pipeline.function_contracts import (\n" + " allowed_group_by,\n" + " required_variable_components,\n" + ")\n" + "\n" + "@allowed_group_by(GroupBy.CHANNEL)\n" + "@required_variable_components(VariableComponents.Z_INDEX)\n" + "def fn(image):\n" + " return image\n" + ) + + rewritten = _cutover().rewrite_source(source) + + namespace: dict[str, object] = {} + exec(compile(rewritten, "", "exec"), namespace) + assert "@allowed_group_by_roles(ColourAxis)" in rewritten + assert "@required_axis_roles(StackAxis)" in rewritten + assert namespace["ColourAxis"] is ColourAxis + assert namespace["StackAxis"] is StackAxis + assert "constants" not in rewritten + + +def test_already_migrated_source_is_left_unchanged(tmp_path) -> None: + target = tmp_path / "pipeline.py" + shutil.copy(FIXTURES / "pre_g1_pipeline.py.fixture", target) + tool = _cutover() + assert tool.migrate(target) is True + migrated = target.read_text() + (tmp_path / "pipeline.py.pre-g1").unlink() + assert tool.migrate(target) is False + assert target.read_text() == migrated + assert not (tmp_path / "pipeline.py.pre-g1").exists() diff --git a/tests/unit/test_gray_to_color_binding_axis_432.py b/tests/unit/test_gray_to_color_binding_axis_432.py index 321cc8ba0b..3c2e987679 100644 --- a/tests/unit/test_gray_to_color_binding_axis_432.py +++ b/tests/unit/test_gray_to_color_binding_axis_432.py @@ -5,7 +5,6 @@ import numpy as np import pytest -from openhcs.constants.constants import VariableComponents from openhcs.core.component_group_scope import RuntimeExecutionAxisScope from openhcs.core.aligned_image_payload import AlignedImageStack, ImagePayloadBundleContext, ImagePayloadExecutionMode from openhcs.core.callable_contract import CallableContract @@ -35,6 +34,7 @@ from openhcs.processing.backends.cellprofiler.color import GrayToColorModule, gray_to_color from test_cellprofiler_generic_special_input_binding import _compile_public_step from tests.unit.cellprofiler_runtime_test_support import cellprofiler_runtime_adapter_for_test +from openhcs.domains.microscopy.axes import Microscopy @pytest.mark.parametrize("explicit_selector", [False, True]) @@ -71,7 +71,7 @@ def test_declared_fitc_runtime_plane_retains_values_and_physical_identity(explic source = metadata.payload_with(pixels[None], None) runtime = cellprofiler_runtime_adapter_for_test( runtime_value_store=RuntimeValueStore(), callable_contract=contract, - variable_components=(VariableComponents.CHANNEL,), + variable_components=(Microscopy.Channel,), axis_scope=RuntimeExecutionAxisScope.from_raw("synthetic", component=None, value=None), artifact_inputs={edge.key: InvocationArtifactInputEdgePlan.from_source_declarations( key=edge.key, spec=edge.spec, main_flow_artifacts=contract.artifact_inputs, diff --git a/tests/unit/test_image_output_context_projection_proof.py b/tests/unit/test_image_output_context_projection_proof.py index 69ff1c7be4..ff71f19462 100644 --- a/tests/unit/test_image_output_context_projection_proof.py +++ b/tests/unit/test_image_output_context_projection_proof.py @@ -1,7 +1,6 @@ import numpy as np import pytest -from openhcs.constants.constants import AllComponents from openhcs.core.artifacts import ( ArtifactOutputPlan, ArtifactSpec, @@ -20,6 +19,7 @@ RuntimePlaneProjection, ) from openhcs.core.source_image_provenance import SourceImageProvenancePlanes +from openhcs.domains.microscopy.axes import Microscopy @@ -63,7 +63,7 @@ def _scalar_rgb_output(): name="SavedColorNeighbors", path="/memory/SavedColorNeighbors.png", artifact_type=ImageArtifactType, - variable_components=(AllComponents.SITE,), + variable_components=(Microscopy.Site,), relations=(GroupLineageSourceRelation(source_spec.ref()),), ) return source, output, output_plan @@ -100,7 +100,7 @@ def test_projected_variable_stack_proves_source_ownership_once( name="SavedVolume", path="/memory/SavedVolume.tif", artifact_type=ImageArtifactType, - variable_components=(AllComponents.Z_INDEX,), + variable_components=(Microscopy.ZIndex,), relations=(GroupLineageSourceRelation(source_spec.ref()),), ) proof_calls = _track_ownership_proofs(monkeypatch) @@ -143,7 +143,7 @@ def test_derived_2d_image_does_not_inherit_input_runtime_plane_axis() -> None: name="Projection", path="/memory/Projection.tif", artifact_type=ImageArtifactType, - variable_components=(AllComponents.Z_INDEX,), + variable_components=(Microscopy.ZIndex,), relations=(GroupLineageSourceRelation(source_spec.ref()),), ) @@ -171,7 +171,7 @@ def test_bare_full_stack_image_inherits_source_runtime_plane_axis() -> None: name="FilteredVolume", path="/memory/FilteredVolume.tif", artifact_type=ImageArtifactType, - variable_components=(AllComponents.Z_INDEX,), + variable_components=(Microscopy.ZIndex,), relations=(GroupLineageSourceRelation(source_spec.ref()),), ) @@ -199,7 +199,7 @@ def test_derived_image_preserves_explicit_output_runtime_plane_axis() -> None: name="FilteredVolume", path="/memory/FilteredVolume.tif", artifact_type=ImageArtifactType, - variable_components=(AllComponents.Z_INDEX,), + variable_components=(Microscopy.ZIndex,), relations=(GroupLineageSourceRelation(source_spec.ref()),), ) @@ -255,7 +255,7 @@ def test_projected_crop_preserves_complete_spatial_domain_after_plane_compositio name="CropBlue", path="/memory/CropBlue.pkl", artifact_type=ImageArtifactType, - variable_components=(AllComponents.SITE,), + variable_components=(Microscopy.Site,), relations=(GroupLineageSourceRelation(source_spec.ref()),), ) @@ -321,7 +321,7 @@ def test_unowned_variable_output_without_projector_preserves_error( name="SavedVolume", path="/memory/SavedVolume.tif", artifact_type=ImageArtifactType, - variable_components=(AllComponents.Z_INDEX,), + variable_components=(Microscopy.ZIndex,), relations=(GroupLineageSourceRelation(source_spec.ref()),), ) proof_calls = _track_ownership_proofs(monkeypatch) diff --git a/tests/unit/test_image_stream_request_projection.py b/tests/unit/test_image_stream_request_projection.py index 3906d59839..e2a5e2db49 100644 --- a/tests/unit/test_image_stream_request_projection.py +++ b/tests/unit/test_image_stream_request_projection.py @@ -7,6 +7,7 @@ import pytest from polystore.virtual_workspace import SourcePixelRef +from openhcs.domains.microscopy.axes import Microscopy from openhcs.core.config import NapariStreamingConfig from openhcs.core.runtime_image_values import ( image_payload_data, @@ -194,7 +195,7 @@ class CalibratedFullWindow( metadata = image_payload_metadata(image) filename = "image.tif" declaration = SourcePlaneProjection( - address=OpenHCSPlaneAddress.from_values("A01", 1, 2, 1, 1), + address=OpenHCSPlaneAddress(((Microscopy.Well, "A01"), (Microscopy.Site, 1), (Microscopy.Channel, 2), (Microscopy.ZIndex, 1), (Microscopy.Timepoint, 1))), ref=SourcePixelRef("disk", filename), image_metadata=metadata, ) diff --git a/tests/unit/test_implicit_main_flow_compilation.py b/tests/unit/test_implicit_main_flow_compilation.py index 5fc5263d3f..41d88e09bb 100644 --- a/tests/unit/test_implicit_main_flow_compilation.py +++ b/tests/unit/test_implicit_main_flow_compilation.py @@ -7,7 +7,7 @@ import tifffile from objectstate.lazy_factory import ensure_global_config_context -from openhcs.constants import AllComponents, GroupBy, Microscope, VariableComponents +from openhcs.constants import Microscope from openhcs.constants.input_source import InputSource from openhcs.core.callable_contract import FunctionStepExecutionScope from openhcs.core.config import ( @@ -22,6 +22,7 @@ from openhcs.core.steps.function_step import FunctionStep from openhcs.processing.backends.cellprofiler.thresholding import threshold from openhcs.processing.backends.processors.numpy_processor import percentile_normalize +from openhcs.domains.microscopy.axes import Microscopy def test_native_grouped_main_flow_compiles_into_cellprofiler_consumer(tmp_path): @@ -42,13 +43,13 @@ def test_native_grouped_main_flow_compiles_into_cellprofiler_consumer(tmp_path): num_workers=1, ) pipeline_start_processing = LazyProcessingConfig( - variable_components=[VariableComponents.SITE], - group_by=GroupBy.CHANNEL, + variable_components=[Microscopy.Site], + group_by=Microscopy.Channel, input_source=InputSource.PIPELINE_START, ) previous_step_processing = LazyProcessingConfig( - variable_components=[VariableComponents.SITE], - group_by=GroupBy.CHANNEL, + variable_components=[Microscopy.Site], + group_by=Microscopy.Channel, input_source=InputSource.PREVIOUS_STEP, ) steps = [ @@ -89,7 +90,7 @@ def test_native_grouped_main_flow_compiles_into_cellprofiler_consumer(tmp_path): ) assert threshold_plan.execution_group_scope == PathPlannerGroupScope.from_raw( ("1", "2", "4"), - component=AllComponents.CHANNEL, + component=Microscopy.Channel, ) assert threshold_plan.compiled_function_pattern is not None invocation = next(threshold_plan.compiled_function_pattern.iter_invocations()) diff --git a/tests/unit/test_installed_mcp_demo.py b/tests/unit/test_installed_mcp_demo.py index 724633448c..4215dbf341 100644 --- a/tests/unit/test_installed_mcp_demo.py +++ b/tests/unit/test_installed_mcp_demo.py @@ -13,7 +13,6 @@ from zmqruntime.messages import TaskProgress from openhcs.agent.capabilities import agent_capabilities -from openhcs.constants.constants import AllComponents from openhcs.core.pipeline_document import PipelineDocumentAuthority from openhcs.core.plate_file_inventory import PlateFileKind from openhcs.mcp import installed_demo @@ -21,6 +20,7 @@ from openhcs.processing.presets.pipelines import ( loose_operaphenix_neurite_outgrowth as neurite_preset, ) +from openhcs.domains.microscopy.axes import Microscopy def _records(tmp_path: Path) -> tuple[dict[str, object], ...]: @@ -33,11 +33,11 @@ def _records(tmp_path: Path) -> tuple[dict[str, object], ...]: "kind": PlateFileKind.IMAGE.value, "source_path": str(source_path), "metadata": { - AllComponents.WELL.value: "A01", - AllComponents.SITE.value: "1", - AllComponents.CHANNEL.value: str(channel), - AllComponents.Z_INDEX.value: "1", - AllComponents.TIMEPOINT.value: "1", + Microscopy.Well.name: "A01", + Microscopy.Site.name: "1", + Microscopy.Channel.name: str(channel), + Microscopy.ZIndex.name: "1", + Microscopy.Timepoint.name: "1", }, } ) diff --git a/tests/unit/test_invocation_contract_provider.py b/tests/unit/test_invocation_contract_provider.py index 84d0700a7f..f1d33e64c9 100644 --- a/tests/unit/test_invocation_contract_provider.py +++ b/tests/unit/test_invocation_contract_provider.py @@ -38,6 +38,7 @@ from openhcs.core.pipeline.function_contracts import artifact_outputs from openhcs.core.runtime_adapters import runtime_adapter from openhcs.processing.backends.lib_registry.unified_registry import ProcessingContract +from openhcs.domains.microscopy.axes import Microscopy def _identity(image, *, sigma: float = 1.0): @@ -842,10 +843,6 @@ def test_cellprofiler_provider_leaves_native_same_name_callable_unclaimed() -> N def test_cellprofiler_invocation_contract_uses_one_complete_step_context() -> None: - from openhcs.constants.constants import ( - AllComponents, - GroupBy, - ) from openhcs.constants.input_source import InputSource from openhcs.core.artifacts import ( ArtifactSpec, @@ -870,7 +867,7 @@ def test_cellprofiler_invocation_contract_uses_one_complete_step_context() -> No alias=f"OrigStain{channel}", component_identity=( ComponentSelector( - component=AllComponents.CHANNEL, + component=Microscopy.Channel, value=str(channel), ), ), @@ -886,7 +883,7 @@ def test_cellprofiler_invocation_contract_uses_one_complete_step_context() -> No step_name="CorrectIlluminationCalculate", step_index=3, source_bindings=source_bindings, - group_by=GroupBy.CHANNEL, + group_by=Microscopy.Channel, input_source=InputSource.PIPELINE_START, available_artifacts=source_artifacts, main_flow_artifacts=source_artifacts, @@ -954,7 +951,6 @@ def capture_contract(cls, **kwargs): def test_grouped_contracts_project_prior_main_flow_by_producer_ownership() -> None: - from openhcs.constants.constants import GroupBy from openhcs.core.artifacts import ArtifactInputPlan, ArtifactSpecCollection from openhcs.core.pipeline.artifact_planning import artifact_producers_for_outputs from openhcs.interop.cellprofiler.module_declarations import CellProfilerModule @@ -978,7 +974,7 @@ def test_grouped_contracts_project_prior_main_flow_by_producer_ownership() -> No step_context = ArtifactDeclarationStepContext( step_name="IdentifyPrimaryObjects", step_index=1, - group_by=GroupBy.CHANNEL, + group_by=Microscopy.Channel, available_artifacts=ArtifactSpecCollection(grouped_images), main_flow_artifacts=ArtifactSpecCollection( image.for_plan_type(ArtifactInputPlan) for image in grouped_images diff --git a/tests/unit/test_loaded_pattern_group_ownership.py b/tests/unit/test_loaded_pattern_group_ownership.py index c31a45797e..617dd5b820 100644 --- a/tests/unit/test_loaded_pattern_group_ownership.py +++ b/tests/unit/test_loaded_pattern_group_ownership.py @@ -8,7 +8,6 @@ import numpy as np import pytest -from openhcs.constants.constants import AllComponents, VariableComponents from openhcs.core.compiled_step_plan import CompiledStepPlan from openhcs.core.component_group_scope import ComponentGroupScope from openhcs.core.context.processing_context import ProcessingContext @@ -30,6 +29,7 @@ PatternGroupExecutionScope, ) from openhcs.core.steps.function_output_manifest import NoStepOutputManifestMatch +from openhcs.domains.microscopy.axes import Microscopy def _identity(image): @@ -45,8 +45,8 @@ def _fixture(): step_scope_id="loaded-cohort", input_memory_type="numpy", output_memory_type="numpy", - execution_group_scope=ComponentGroupScope.dynamic(AllComponents.CHANNEL), - variable_components=(VariableComponents.SITE,), + execution_group_scope=ComponentGroupScope.dynamic(Microscopy.Channel), + variable_components=(Microscopy.Site,), source_binding_plan=CompiledSourceBindingPlan.empty(), ) context = ProcessingContext(axis_id="A01") @@ -58,7 +58,7 @@ def _fixture(): pattern_group_info="A01_s{iii}_w1_z003_t002.tif", component_index=7, component_count=99, - fixed_component_values=((AllComponents.Z_INDEX, "dispatch-value"),), + fixed_component_values=((Microscopy.ZIndex, "dispatch-value"),), ) paths = ["A01_s001_w1_z003_t002.tif", "A01_s002_w1_z003_t002.tif"] payload = ImagePayloadMetadata( @@ -131,8 +131,8 @@ def test_initial_coordinates_stay_captured_while_plan_selectors_follow_mutation( loaded = PatternGroupData.from_loaded_group(request, paths, payload) assert loaded.runtime_plane_count == 2 assert loaded.fixed_component_values == ( - (AllComponents.Z_INDEX, "3"), - (AllComponents.TIMEPOINT, "2"), + (Microscopy.ZIndex, "3"), + (Microscopy.Timepoint, "2"), ) paths.append("later-mutation.tif") image_payload_data(payload)[:] = -1 @@ -140,13 +140,13 @@ def test_initial_coordinates_stay_captured_while_plan_selectors_follow_mutation( assert len(loaded.matching_files) == 3 request.execution_plan.axis_id = "B02" request.execution_plan.execution_group_scope = ComponentGroupScope.dynamic( - AllComponents.SITE + Microscopy.Site ) assert loaded.axis_scope.axis_id == "B02" - assert loaded.axis_component == "site" + assert loaded.axis_component is Microscopy.Site assert loaded.fixed_component_values == ( - (AllComponents.Z_INDEX, "3"), - (AllComponents.TIMEPOINT, "2"), + (Microscopy.ZIndex, "3"), + (Microscopy.Timepoint, "2"), ) @@ -194,8 +194,8 @@ def execute(executor, *, debug_sink=None): assert loaded.main_data_stack is payload assert loaded.runtime_plane_count == 2 assert loaded.fixed_component_values == ( - (AllComponents.Z_INDEX, "3"), - (AllComponents.TIMEPOINT, "2"), + (Microscopy.ZIndex, "3"), + (Microscopy.Timepoint, "2"), ) @@ -315,13 +315,13 @@ def test_adapter_request_projects_live_fields_and_preserves_current_payload_epoc assert adapter.source_payload is not loaded.main_data_stack assert adapter.plane_projection is executor.plane_projection assert adapter.execution_scope is executor - assert adapter.variable_components == (VariableComponents.SITE,) + assert adapter.variable_components == (Microscopy.Site,) assert adapter.axis_scope.fixed_component_values == loaded.fixed_component_values request.execution_plan.axis_id = "B02" - request.execution_plan.variable_components = (VariableComponents.Z_INDEX,) + request.execution_plan.variable_components = (Microscopy.ZIndex,) updated = executor.runtime_adapter_request(current) assert updated.axis_scope.axis_id == "B02" - assert updated.variable_components == (VariableComponents.Z_INDEX,) + assert updated.variable_components == (Microscopy.ZIndex,) def test_adapter_tuple_admission_precedes_output_map_validation(): @@ -416,7 +416,7 @@ def consume(image, *, runtime): artifact_inputs={input_plan.ref(): input_plan}, relation_source_scopes={}, execution_group_scope=ComponentGroupScope.ungrouped(), - consumer_variable_components=ComponentSet((AllComponents.SITE,)), + consumer_variable_components=ComponentSet((Microscopy.Site,)), main_flow_artifacts=ArtifactSpecCollection((source,)), ) request.execution_plan.step_index = 1 @@ -432,8 +432,8 @@ def consume(image, *, runtime): component_index=7, component_count=99, fixed_component_values=( - (AllComponents.Z_INDEX, "3"), - (AllComponents.TIMEPOINT, "2"), + (Microscopy.ZIndex, "3"), + (Microscopy.Timepoint, "2"), ), ) payload = ( @@ -494,8 +494,8 @@ def test_stored_primary_admission_owns_independent_buffer_and_live_primary_bindi assert loaded.runtime_plane_count == 2 assert loaded.runtime_plane_index == 7 assert loaded.fixed_component_values == ( - (AllComponents.Z_INDEX, "3"), - (AllComponents.TIMEPOINT, "2"), + (Microscopy.ZIndex, "3"), + (Microscopy.Timepoint, "2"), ) replacement = replace( canonical, @@ -692,9 +692,9 @@ def test_checkpoint_demand_terminates_on_preserving_cycles_and_self_producers(): def test_artifact_loaded_coordinates_keep_producer_authority_over_original_source(): request, canonical = _stored_primary_fixture() exact_coordinates = ( - (AllComponents.CHANNEL, "ProducedChannel"), - (AllComponents.Z_INDEX, "3"), - (AllComponents.TIMEPOINT, "2"), + (Microscopy.Channel, "ProducedChannel"), + (Microscopy.ZIndex, "3"), + (Microscopy.Timepoint, "2"), ) request = replace(request, fixed_component_values=exact_coordinates) assert ( @@ -719,7 +719,7 @@ def test_artifact_loaded_coordinates_keep_producer_authority_over_original_sourc def test_conversion_and_sequential_filter_use_the_same_transport_admission(): from pathlib import Path - from openhcs.constants.constants import Backend, SequentialComponents + from openhcs.constants.constants import Backend from openhcs.core.compiled_step_plan import ( InputConversionPlan, SequentialRuntimeFilter, @@ -740,7 +740,7 @@ def test_conversion_and_sequential_filter_use_the_same_transport_admission(): ) plan.input_conversion = None plan.sequential_filter_plan = SequentialRuntimeFilterPlan( - filters=(SequentialRuntimeFilter(SequentialComponents.TIMEPOINT, "2"),), + filters=(SequentialRuntimeFilter(Microscopy.Timepoint, "2"),), ) assert ( plan.stored_primary_input_edges_for_group(request.compiled_group, None) is None @@ -798,8 +798,8 @@ def consume(image): ).compile_invocation_input_edges( compile_function_pattern([consume, consume], {}, {}), artifact_inputs={}, relation_source_scopes={}, - execution_group_scope=ComponentGroupScope.dynamic(AllComponents.CHANNEL), - consumer_variable_components=ComponentSet((AllComponents.SITE,)), + execution_group_scope=ComponentGroupScope.dynamic(Microscopy.Channel), + consumer_variable_components=ComponentSet((Microscopy.Site,)), main_flow_artifacts=ArtifactSpecCollection( (source,) if primary_only else (source, ArtifactSpec.input("Other", ImageArtifactType)), ), diff --git a/tests/unit/test_logical_image_output_snapshot.py b/tests/unit/test_logical_image_output_snapshot.py index 6f795edc3f..21a9de6e3f 100644 --- a/tests/unit/test_logical_image_output_snapshot.py +++ b/tests/unit/test_logical_image_output_snapshot.py @@ -10,7 +10,6 @@ from polystore.virtual_workspace import SourcePixelRef from benchmark.matched_cellprofiler_batch import _require_compared_output_inventory -from openhcs.constants.constants import AllComponents from openhcs.core.artifacts import ImageArtifactType from openhcs.core.component_group_scope import RuntimeExecutionAxisScope from benchmark.equivalence.comparison import runtime_image_differences @@ -33,8 +32,9 @@ from openhcs.core.source_spatial_domain import SourceSpatialDomain from openhcs.core.virtual_workspace_metadata import METADATA_CONFIG from openhcs.microscopes.source_schema import SourceSchemaFilenameParser +from openhcs.domains.microscopy.axes import Microscopy -Z_STACK = SourceImageSetIdentityPolicy(frozenset({AllComponents.Z_INDEX})) +Z_STACK = SourceImageSetIdentityPolicy(frozenset({Microscopy.ZIndex})) EXACT = RuntimeEquivalencePolicy(image_abs_tolerance=0, image_rel_tolerance=0) @@ -70,7 +70,7 @@ def exported_volume(tmp_path): for plane_index, plane in enumerate(volume): path = candidate / f"opaque-{plane_index}.tiff" imageio.imwrite(path, plane) - address = OpenHCSPlaneAddress.from_values("A01", "1", "2", plane_index + 1, "1") + address = OpenHCSPlaneAddress(((Microscopy.Well, "A01"), (Microscopy.Site, "1"), (Microscopy.Channel, "2"), (Microscopy.ZIndex, plane_index + 1), (Microscopy.Timepoint, "1"))) projections.append( SourceArtifactProjection( address=address, @@ -166,18 +166,18 @@ def test_observation_owns_the_grouping_axis(exported_volume): @pytest.mark.parametrize( "component", ( - AllComponents.WELL, - AllComponents.SITE, - AllComponents.CHANNEL, - AllComponents.TIMEPOINT, + Microscopy.Well, + Microscopy.Site, + Microscopy.Channel, + Microscopy.Timepoint, ), ) def test_different_source_cohorts_cannot_be_combined(exported_volume, component): candidate, _, _, projections = exported_volume changed_address = projections[1].address.with_value( - component, "B02" if component is AllComponents.WELL else "2" + component, "B02" if component is Microscopy.Well else "2" ) - if component is AllComponents.CHANNEL: + if component is Microscopy.Channel: changed_address = projections[1].address.with_value(component, "3") projections[1] = replace( projections[1], @@ -246,7 +246,7 @@ def test_source_z_origin_is_preserved_without_assuming_one(exported_volume): candidate, _, volume, projections = exported_volume shifted = [] for index, projection in enumerate(projections): - address = projection.address.with_value(AllComponents.Z_INDEX, str(index + 7)) + address = projection.address.with_value(Microscopy.ZIndex, str(index + 7)) shifted.append( replace( projection, diff --git a/tests/unit/test_loose_operaphenix_neurite_example.py b/tests/unit/test_loose_operaphenix_neurite_example.py index 9fee42897d..65804ff5e0 100644 --- a/tests/unit/test_loose_operaphenix_neurite_example.py +++ b/tests/unit/test_loose_operaphenix_neurite_example.py @@ -11,7 +11,7 @@ KnowledgeBaseSearchRequest, ) from openhcs.agent.services.knowledge_base_service import KnowledgeBaseService -from openhcs.constants.constants import AllComponents, Microscope +from openhcs.constants.constants import Microscope from openhcs.core.config import GlobalPipelineConfig from openhcs.core.function_patterns import get_core_callable, normalize_function_pattern from openhcs.core.orchestrator.orchestrator import PipelineOrchestrator @@ -39,6 +39,7 @@ build_loose_operaphenix_neurite_pipeline, loose_operaphenix_neurite_demo_contribution, ) +from openhcs.domains.microscopy.axes import Microscopy def _inputs(plate_path: Path, output_root: Path) -> LooseOperaPhenixNeuriteInputs: @@ -93,7 +94,7 @@ def test_neurite_example_declares_bounded_sources_and_final_user_result( next( selector.value for selector in binding.component_identity - if selector.component is AllComponents.CHANNEL + if selector.component is Microscopy.Channel ) for binding in bindings ] == ["1", "2", "4"] diff --git a/tests/unit/test_loose_operaphenix_neurite_metaxpress_example.py b/tests/unit/test_loose_operaphenix_neurite_metaxpress_example.py index 0f41e4a76f..796f4a1e74 100644 --- a/tests/unit/test_loose_operaphenix_neurite_metaxpress_example.py +++ b/tests/unit/test_loose_operaphenix_neurite_metaxpress_example.py @@ -9,7 +9,7 @@ from openhcs.agent.dto.knowledge import KnowledgeBaseDocumentRequest from openhcs.agent.services.knowledge_base_service import KnowledgeBaseService -from openhcs.constants import GroupBy, Microscope, VariableComponents +from openhcs.constants import Microscope from openhcs.constants.input_source import InputSource from openhcs.core.config import GlobalPipelineConfig from openhcs.core.function_patterns import get_core_callable @@ -31,6 +31,8 @@ from openhcs.processing.presets.pipelines.loose_operaphenix_neurite_outgrowth_metaxpress import ( build_loose_operaphenix_neurite_metaxpress_pipeline, ) +from openhcs.core.axes import Ungrouped +from openhcs.domains.microscopy.axes import Microscopy def _inputs(plate_path: Path, output_root: Path) -> LooseOperaPhenixNeuriteInputs: @@ -87,8 +89,8 @@ def test_compact_example_uses_owned_channel_order_and_one_function_step( step = steps[0] assert step.name == "CompactMetaXpressNeuriteOutgrowth" assert get_core_callable(step.func) is neurite_outgrowth_metaxpress - assert step.processing_config.variable_components == [VariableComponents.CHANNEL] - assert step.processing_config.group_by is GroupBy.NONE + assert step.processing_config.variable_components == [Microscopy.Channel] + assert step.processing_config.group_by is Ungrouped assert step.processing_config.input_source is InputSource.PIPELINE_START assert step.napari_streaming_config.enabled is True assert step.napari_streaming_config.well_filter is None @@ -185,5 +187,5 @@ def test_compact_example_compiles_the_full_ordered_channel_stack( context = compilation.runtime_contexts[inputs.well] plan = context.step_plans[0] assert plan.step_name == "CompactMetaXpressNeuriteOutgrowth" - assert tuple(plan.variable_components) == (VariableComponents.CHANNEL,) + assert tuple(plan.variable_components) == (Microscopy.Channel,) assert plan.compiled_function_pattern is not None diff --git a/tests/unit/test_materialization_core.py b/tests/unit/test_materialization_core.py index 85d93e9b97..554d7193d9 100644 --- a/tests/unit/test_materialization_core.py +++ b/tests/unit/test_materialization_core.py @@ -39,7 +39,6 @@ from zmqruntime.viewer_protocol import ViewerTransportEndpoint, ViewerWireField import openhcs # noqa: F401 -from openhcs.constants.constants import AllComponents, VariableComponents from openhcs.core.components.parser_metaprogramming import FilenameParseResult from openhcs.core.config import AnalysisConsolidationConfig from openhcs.core.measurement_row_materialization import ( @@ -127,6 +126,8 @@ RuntimePlaneStackAxesProjectionSelection, ViewerStreamBackendCallKwargs, ) +from openhcs.core.axes import AxisFamily +from openhcs.domains.microscopy.axes import Microscopy def _memory_materialize(spec, data, path, filemanager): @@ -338,7 +339,7 @@ def test_roi_output_projection_preserves_requested_summary_content(): class _TestViewerDisplayConfig(ViewerDisplayConfigABC): - COMPONENT_ORDER = AllComponents.ordered_names() + COMPONENT_ORDER = AxisFamily.active().names() variable_size_handling = None auto_contrast = True @@ -367,7 +368,7 @@ def parse_filename(self, filename): parsed.setdefault("z_index", "1") parsed.setdefault("timepoint", "1") return FilenameParseResult( - ((component, parsed[component.value]) for component in AllComponents), + ((component, parsed[component.name]) for component in AxisFamily.active().axes), extension=parsed.get("extension", ".tif"), ) @@ -539,8 +540,8 @@ def test_materialization_spec_declares_filename_identity() -> None: @pytest.mark.parametrize( ("component", "component_values"), ( - (VariableComponents.TIMEPOINT, (0, 1)), - (VariableComponents.Z_INDEX, (1, 2)), + (Microscopy.Timepoint, (0, 1)), + (Microscopy.ZIndex, (1, 2)), ), ) def test_indexed_image_materialization_streams_each_declared_component_plane( @@ -562,7 +563,7 @@ def test_indexed_image_materialization_streams_each_declared_component_plane( "channel": 1, "z_index": 1, "timepoint": 1, - component.value: value, + component.name: value, } for value in component_values ) @@ -595,7 +596,7 @@ def test_indexed_image_materialization_streams_each_declared_component_plane( request = kwargs["stream_request"] streamed_components.append( dict(request.source.metadata.component_metadata_for_item(path, 0))[ - component.value + component.name ] ) assert tuple(streamed_components) == component_values @@ -873,7 +874,7 @@ def test_point_roi_materialization_native_reopen_preserves_fractional_z( @pytest.mark.unit @pytest.mark.parametrize("source_z_origin", (0, 10)) -@pytest.mark.parametrize("variable_components", ((), (VariableComponents.Z_INDEX,))) +@pytest.mark.parametrize("variable_components", ((), (Microscopy.ZIndex,))) def test_payload_label_roi_reopen_preserves_geometric_plane_domain( tmp_path, source_z_origin, variable_components, ): @@ -1253,7 +1254,7 @@ def test_tiff_stack_streaming_projects_scalar_metadata_over_declared_stack_axis( filemanager=fm, backends=["napari_stream"], backend_kwargs={"napari_stream": _viewer_stream_backend_kwargs()}, - variable_components=(VariableComponents.Z_INDEX,), + variable_components=(Microscopy.ZIndex,), ) saved_images = [ @@ -1273,11 +1274,11 @@ def test_tiff_stack_projection_skips_axes_already_varying_in_slice_metadata() -> MaterializationInputItem( value=ImagePayloadMetadata( source_component_metadata={ - AllComponents.WELL.value: "A01", - AllComponents.SITE.value: 1, - AllComponents.Z_INDEX.value: index + 1, - AllComponents.CHANNEL.value: 3, - AllComponents.TIMEPOINT.value: 1, + Microscopy.Well.name: "A01", + Microscopy.Site.name: 1, + Microscopy.ZIndex.name: index + 1, + Microscopy.Channel.name: 3, + Microscopy.Timepoint.name: 1, }, ).payload_with(np.zeros((5, 7), dtype=np.float32), None), source_description="materialization payload", @@ -1290,7 +1291,7 @@ def test_tiff_stack_projection_skips_axes_already_varying_in_slice_metadata() -> ) axes = RuntimePlaneStackAxesProjectionSelection( - (VariableComponents.Z_INDEX, VariableComponents.CHANNEL), + (Microscopy.ZIndex, Microscopy.Channel), items, ).axes() @@ -1303,9 +1304,9 @@ def test_tiff_stack_projection_rejects_ambiguous_scalar_declared_axes() -> None: MaterializationInputItem( value=ImagePayloadMetadata( source_component_metadata={ - AllComponents.WELL.value: "A01", - AllComponents.SITE.value: 1, - AllComponents.CHANNEL.value: 3, + Microscopy.Well.name: "A01", + Microscopy.Site.name: 1, + Microscopy.Channel.name: 3, }, ).payload_with(np.zeros((5, 7), dtype=np.float32), None), source_description="materialization payload", @@ -1319,7 +1320,7 @@ def test_tiff_stack_projection_rejects_ambiguous_scalar_declared_axes() -> None: with pytest.raises(ValueError, match="cannot map runtime plane metadata"): RuntimePlaneStackAxesProjectionSelection( - (VariableComponents.Z_INDEX, VariableComponents.CHANNEL), + (Microscopy.ZIndex, Microscopy.Channel), items, ).axes() @@ -1339,19 +1340,19 @@ def test_tiff_stack_projection_uses_artifact_scalar_z_origin() -> None: ) axes = RuntimePlaneStackAxesProjectionSelection( - (VariableComponents.Z_INDEX, VariableComponents.CHANNEL), + (Microscopy.ZIndex, Microscopy.Channel), items, SourceImageIdentity( component_metadata={ - AllComponents.WELL.value: "A01", - AllComponents.SITE.value: 1, - AllComponents.Z_INDEX.value: 1, - AllComponents.CHANNEL.value: 3, + Microscopy.Well.name: "A01", + Microscopy.Site.name: 1, + Microscopy.ZIndex.name: 1, + Microscopy.Channel.name: 3, }, ), ).axes() - assert axes == frozenset((AllComponents.Z_INDEX.value,)) + assert axes == frozenset((Microscopy.ZIndex.name,)) @pytest.mark.unit @@ -1379,8 +1380,8 @@ def test_tiff_stack_streaming_preserves_runtime_source_plane_metadata() -> None: backends=["napari_stream"], backend_kwargs={"napari_stream": _viewer_stream_backend_kwargs()}, variable_components=( - VariableComponents.Z_INDEX, - VariableComponents.CHANNEL, + Microscopy.ZIndex, + Microscopy.Channel, ), ) @@ -1422,7 +1423,7 @@ def test_tiff_stack_streaming_projects_artifact_identity_over_declared_stack_axi "timepoint": 1, }, ), - variable_components=(VariableComponents.Z_INDEX,), + variable_components=(Microscopy.ZIndex,), ) saved_images = [ @@ -1696,7 +1697,7 @@ def test_roi_streaming_maps_payload_scoped_volume_planes_from_provenance(viewer_ filemanager=fm, backends=["napari_stream"], backend_kwargs={"napari_stream": _viewer_stream_backend_kwargs()}, - variable_components=(VariableComponents.Z_INDEX,), + variable_components=(Microscopy.ZIndex,), ) roi_saves = [item for item in fm.saved if item[1].endswith(".roi.zip")] @@ -1818,7 +1819,7 @@ def test_roi_streaming_maps_singleton_plane_from_exact_output_component( filemanager=fm, backends=["napari_stream"], backend_kwargs={"napari_stream": _viewer_stream_backend_kwargs()}, - variable_components=(VariableComponents.SITE,), + variable_components=(Microscopy.Site,), ) roi_saves = [item for item in fm.saved if item[1].endswith(".roi.zip")] @@ -2616,7 +2617,7 @@ def test_declared_volume_save_preserves_pixels_and_exact_plane_selection( manager, ("disk",), context=_SourceSchemaProcessingContext(), - variable_components=(VariableComponents.Z_INDEX,), + variable_components=(Microscopy.ZIndex,), artifact_filename_identity=SourceImageIdentity( component_metadata={**components[0], "extension": ".tif"}, ), @@ -2647,11 +2648,11 @@ def test_declared_volume_save_preserves_pixels_and_exact_plane_selection( image_metadata=saved_metadata, execution_scope=RuntimeExecutionAxisScope.from_raw( "A01", - component="channel", + component=Microscopy.Channel, value="2", fixed_component_values=( - (AllComponents.SITE, "1"), - (AllComponents.TIMEPOINT, "1"), + (Microscopy.Site, "1"), + (Microscopy.Timepoint, "1"), ), ), ) diff --git a/tests/unit/test_mcp_assay_showcase.py b/tests/unit/test_mcp_assay_showcase.py index 438cb2c845..8b2578b1cd 100644 --- a/tests/unit/test_mcp_assay_showcase.py +++ b/tests/unit/test_mcp_assay_showcase.py @@ -160,27 +160,21 @@ def test_showcase_sources_are_seven_bounded_distinct_pipeline_documents(tmp_path if blueprint_index >= 3: assert "export_to_spreadsheet" in source assert '"export_all_measurement_types": True' in source + microscopy_import = "from openhcs.domains.microscopy.axes import Microscopy" + ungrouped_import = "from openhcs.core.axes import Ungrouped" if blueprint.wavelengths == 1: if blueprint.z_stack_levels > 1: - assert ( - "from openhcs.constants.constants import VariableComponents" - in source - ) - assert "variable_components=[VariableComponents.Z_INDEX]" in source - elif "VariableComponents" in source: - assert ( - "from openhcs.constants.constants import " - "GroupBy, VariableComponents" in source - ) - assert "variable_components=[VariableComponents.SITE]" in source - assert "group_by=GroupBy.CHANNEL" in source + assert microscopy_import in source + assert "variable_components=[Microscopy.ZIndex]" in source + elif "Microscopy." in source: + assert microscopy_import in source + assert "variable_components=[Microscopy.Site]" in source + assert "group_by=Microscopy.Channel" in source else: - assert "GroupBy" not in source + assert "Ungrouped" not in source else: - assert ( - "from openhcs.constants.constants import GroupBy, VariableComponents" - in source - ) + assert microscopy_import in source + assert ungrouped_import in source generation = blueprint.generation_arguments(plate_path) assert generation[0] == "generate-synthetic-plate" diff --git a/tests/unit/test_mcp_thesis_demo_live.py b/tests/unit/test_mcp_thesis_demo_live.py index 4a0c55d051..1e418cc10a 100644 --- a/tests/unit/test_mcp_thesis_demo_live.py +++ b/tests/unit/test_mcp_thesis_demo_live.py @@ -1203,7 +1203,7 @@ def test_demo_source_saves_source_bindings_through_pipeline_config( assert "SourceBindingsConfig()" not in baseline_source assert demo.BASELINE_SOURCE_ALIAS in baseline_source assert demo.EDITED_SOURCE_ALIAS in edited_source - assert "group_by=GroupBy.CHANNEL" in baseline_source + assert "group_by=Microscopy.Channel" in baseline_source assert "pipeline_config =" not in baseline_source assert "pipeline_steps =" not in baseline_source assert UiCodeDocumentSourcePolicy().validate(baseline_source) == () @@ -1869,7 +1869,7 @@ def authored(alias: str) -> dict[str, object]: }, ], "processing_semantics": [ - {"group_by": None, "variable_components": ["z_index"]}, + {"group_by": "none", "variable_components": ["z_index"]}, {"group_by": "channel", "variable_components": []}, ], "config_families": { diff --git a/tests/unit/test_mfd_preset_specs.py b/tests/unit/test_mfd_preset_specs.py index dc4f7abe6e..de3ac624ff 100644 --- a/tests/unit/test_mfd_preset_specs.py +++ b/tests/unit/test_mfd_preset_specs.py @@ -3,7 +3,6 @@ from arraybridge.decorators import DtypeConversion -from openhcs.constants.constants import VariableComponents from openhcs.constants.input_source import InputSource from openhcs.core.config import LazyDtypeConfig from openhcs.processing.backends.analysis.cell_counting_cpu import ( @@ -40,6 +39,7 @@ MfdPresetKey, build_mfd_preset, ) +from openhcs.domains.microscopy.axes import Microscopy PIPELINE_DIR = ( Path(__file__).resolve().parents[2] @@ -88,7 +88,7 @@ def test_crop_analyze_spec_matches_expected_step_contract(): "analysis", ] assert steps[0].processing_config.variable_components == [ - VariableComponents.CHANNEL + Microscopy.Channel ] assert steps[0].func == ( multi_template_crop_reference_channel, @@ -175,7 +175,7 @@ def test_stitch_specs_share_structure_and_vary_backend(): assert cpu_steps[0].func == gpu_steps[0].func assert cpu_steps[1].func == gpu_steps[1].func == create_composite assert cpu_steps[1].processing_config.variable_components == [ - VariableComponents.CHANNEL + Microscopy.Channel ] assert cpu_steps[2].func == ( ashlar_compute_tile_positions_cpu, diff --git a/tests/unit/test_microscope_virtual_workspace_metadata.py b/tests/unit/test_microscope_virtual_workspace_metadata.py index 09dfaff244..6270216433 100644 --- a/tests/unit/test_microscope_virtual_workspace_metadata.py +++ b/tests/unit/test_microscope_virtual_workspace_metadata.py @@ -8,7 +8,6 @@ from polystore.virtual_workspace import SourcePixelRef -from openhcs.constants.constants import AllComponents from openhcs.core.virtual_workspace_metadata import FIELDS from openhcs.core.source_metadata import SourceVoxelSpacing, SourceVoxelSpacingUnit from openhcs.core.viewer_streaming_service import ViewerStreamingSource @@ -16,6 +15,7 @@ from openhcs.core.source_workspace_projection import ( VirtualWorkspaceSourceProjection, ) +from openhcs.domains.microscopy.axes import Microscopy def test_virtual_workspace_metadata_records_parser_owned_axis_values( @@ -48,8 +48,8 @@ def test_virtual_workspace_metadata_records_parser_owned_axis_values( (tmp_path / "openhcs_metadata.json").read_text(encoding="utf-8") ) source_metadata = metadata[FIELDS.SUBDIRECTORIES]["Images"][FIELDS.SOURCE_METADATA] - assert source_metadata[virtual_a][AllComponents.WELL.value] == "R01C01" - assert source_metadata[virtual_b][AllComponents.WELL.value] == "R02C03" + assert source_metadata[virtual_a][Microscopy.Well.name] == "R01C01" + assert source_metadata[virtual_b][Microscopy.Well.name] == "R02C03" projection = VirtualWorkspaceSourceProjection.from_openhcs_metadata( tmp_path, @@ -126,7 +126,7 @@ def test_compiler_source_queries_borrow_config_while_public_queries_stay_live( monkeypatch.setattr(owner, "get_effective_config", live_config) assert owner.get_component_keys( - AllComponents.WELL, resolved_config=held_config + Microscopy.Well, resolved_config=held_config ) == ["R01C01"] live_config.assert_not_called() owner.pipeline_config = replace( @@ -137,10 +137,10 @@ def test_compiler_source_queries_borrow_config_while_public_queries_stay_live( ) owner.initialize() live_config.reset_mock() - assert owner.get_component_keys(AllComponents.WELL) == ["R02C03"] + assert owner.get_component_keys(Microscopy.Well) == ["R02C03"] assert live_config.call_count == 1 assert owner.get_component_keys( - AllComponents.WELL, resolved_config=held_config + Microscopy.Well, resolved_config=held_config ) == ["R01C01"] assert live_config.call_count == 1 diff --git a/tests/unit/test_named_checkpoint_publication.py b/tests/unit/test_named_checkpoint_publication.py index bc08805e40..7a422615a2 100644 --- a/tests/unit/test_named_checkpoint_publication.py +++ b/tests/unit/test_named_checkpoint_publication.py @@ -12,7 +12,6 @@ import tifffile from test_artifact_publication_journey import _plate, progress_events -from openhcs.constants.constants import GroupBy, VariableComponents from openhcs.core.artifacts import ( ArtifactSidecarRole, ImageArtifactType, MainFlowPlaneProjectionOutputSpec, MainFlowStackOutputSpec, @@ -25,7 +24,7 @@ from openhcs.core.orchestrator.orchestrator import PipelineOrchestrator from openhcs.core.orchestrator.execution_result import RuntimeContextObservation, RuntimeExecutionObservation from openhcs.core.pipeline.function_contracts import ( - artifact_outputs, required_variable_components, + artifact_outputs, required_axis_roles, ) from openhcs.core.projected_image_output import SourceProjectedImageOutput from openhcs.core.runtime_image_values import ImagePayloadMetadata, image_payload_metadata @@ -39,6 +38,9 @@ from openhcs.processing.materialization import ( ImageFileOptions, MaterializationSpec, MaterializedFilenameIdentity, ) +from openhcs.core.axes import TileAxis +from openhcs.domains.microscopy.axes import Microscopy + @dataclass(frozen=True) @@ -64,7 +66,7 @@ def _field(name): @numpy_decorator(contract=ProcessingContract.PURE_3D) -@required_variable_components(VariableComponents.SITE) +@required_axis_roles(TileAxis) @artifact_outputs( MainFlowStackOutputSpec.output("corrected", ImageArtifactType), _field("flat"), _field("dark"), @@ -89,7 +91,7 @@ def test_named_and_ordinary_checkpoint_inventory_owns_every_address(tmp_path, ma step = FunctionStep( func=synthetic_three_outputs, processing_config=LazyProcessingConfig( - group_by=GroupBy.CHANNEL, variable_components=[VariableComponents.SITE], + group_by=Microscopy.Channel, variable_components=[Microscopy.Site], ), step_materialization_config=LazyStepMaterializationConfig(enabled=True), ) @@ -125,7 +127,7 @@ def test_named_and_ordinary_checkpoint_inventory_owns_every_address(tmp_path, ma ] assert len(ordinary) == len(checkpoints) - len(ordinary) == 24 assert {projection.address for projection in ordinary} == { - OpenHCSPlaneAddress.from_values("A01", site, 1, 1, 1) + OpenHCSPlaneAddress(((Microscopy.Well, "A01"), (Microscopy.Site, site), (Microscopy.Channel, 1), (Microscopy.ZIndex, 1), (Microscopy.Timepoint, 1))) for site in range(1, 25) } for item in checkpoints: diff --git a/tests/unit/test_napari_accepted_work_settlement.py b/tests/unit/test_napari_accepted_work_settlement.py index ed26b26cd5..4e1b08772d 100644 --- a/tests/unit/test_napari_accepted_work_settlement.py +++ b/tests/unit/test_napari_accepted_work_settlement.py @@ -92,7 +92,7 @@ def send(item): def wire_batch(item): items = item if isinstance(item, list) else [item] - config = NapariDisplayConfig(channel_mode=NapariDimensionMode.LAYER) + config = NapariDisplayConfig(colour_mode=NapariDimensionMode.LAYER) producer = StreamProducerIdentity.pipeline_output( output_kind="artifact", output_key="test", diff --git a/tests/unit/test_napari_reset_transitions.py b/tests/unit/test_napari_reset_transitions.py index bae135efa3..6a85ab226f 100644 --- a/tests/unit/test_napari_reset_transitions.py +++ b/tests/unit/test_napari_reset_transitions.py @@ -123,11 +123,11 @@ def enqueue( voxel_spacing=None, ): config = display_config or NapariDisplayConfig( - well_mode=NapariDimensionMode.STACK, - site_mode=NapariDimensionMode.LAYER, - channel_mode=NapariDimensionMode.LAYER, - z_index_mode=(NapariDimensionMode.STACK if z_domain else NapariDimensionMode.LAYER), - timepoint_mode=NapariDimensionMode.LAYER, + partition_mode=NapariDimensionMode.STACK, + tile_mode=NapariDimensionMode.LAYER, + colour_mode=NapariDimensionMode.LAYER, + stack_mode=(NapariDimensionMode.STACK if z_domain else NapariDimensionMode.LAYER), + time_mode=NapariDimensionMode.LAYER, variable_size_handling=NapariVariableSizeHandling.PAD_TO_MAX, ) semantics = ViewerComponentAxisSemanticsAuthority.from_display_config( @@ -211,7 +211,7 @@ def test_shared_slot_batch_aligns_two_manual_channels_and_wells( receiver.replace_layers = replace_layers wells = [f"{row}{column:02}" for row in "ABCDEFGH" for column in range(1, 13)] raw_config = NapariDisplayConfig( - channel_mode=NapariDimensionMode.LAYER, well_mode=NapariDimensionMode.LAYER, + colour_mode=NapariDimensionMode.LAYER, partition_mode=NapariDimensionMode.LAYER, ) result_config = NapariDisplayConfig() raw_routes = {} diff --git a/tests/unit/test_napari_streaming_handlers.py b/tests/unit/test_napari_streaming_handlers.py index 04a1d457e9..5c509cf786 100644 --- a/tests/unit/test_napari_streaming_handlers.py +++ b/tests/unit/test_napari_streaming_handlers.py @@ -14,6 +14,7 @@ from polystore.streaming_constants import StreamingDataType from zmqruntime.viewer_protocol import ViewerComponentMode +from openhcs.core.axes import AxisFamily from openhcs.core.artifacts import ObjectArtifactSubjectBinding from openhcs.core.config import ( NapariDisplayConfig, @@ -92,6 +93,7 @@ ViewerStateControlOptions, ) from openhcs.runtime.zmq_config import OPENHCS_ZMQ_CONFIG +from openhcs.domains.microscopy.axes import Microscopy def _component_name_metadata(payload, context="test component metadata"): @@ -1964,7 +1966,7 @@ class _RegionDisplayConfig(NapariDisplayConfig): """New display declaration: inherit existing modes and add one owned axis.""" REGION_COMPONENT = "region" - COMPONENT_ORDER = (*NapariDisplayConfig.COMPONENT_ORDER, REGION_COMPONENT) + COMPONENT_ORDER = (*AxisFamily.active().names(), REGION_COMPONENT) region_mode: NapariDimensionMode = NapariDimensionMode.STACK def component_modes(self) -> dict[str, str]: @@ -1977,8 +1979,8 @@ def component_modes(self) -> dict[str, str]: @pytest.mark.parametrize( "component, mode_field, config_type", [ - ("channel", "channel_mode", NapariDisplayConfig), - ("site", "site_mode", NapariDisplayConfig), + ("channel", "colour_mode", NapariDisplayConfig), + ("site", "tile_mode", NapariDisplayConfig), (_RegionDisplayConfig.REGION_COMPONENT, "region_mode", _RegionDisplayConfig), ], ) @@ -6401,7 +6403,7 @@ def test_napari_points_layer_rejects_fractional_z_without_z_axis(): projected_axis_components=("channel",), component_values={"channel": [1]}, ) - with pytest.raises(ValueError, match="projected z_index axis"): + with pytest.raises(ValueError, match="projected stack axis"): napari_viewer_server._build_nd_points([item], presentation.projection) diff --git a/tests/unit/test_napari_transport_ownership.py b/tests/unit/test_napari_transport_ownership.py index 7abb218291..2e9a6cd0c4 100644 --- a/tests/unit/test_napari_transport_ownership.py +++ b/tests/unit/test_napari_transport_ownership.py @@ -14,6 +14,7 @@ from zmqruntime.transport import get_zmq_transport_url, remove_ipc_socket from zmqruntime.viewer_protocol import ViewerBatchDisplayPayload +from openhcs.core.axes import AxisFamily from openhcs.core.config import NapariDisplayConfig from openhcs.runtime.viewer_protocol import NapariViewerServerRequest from openhcs.runtime.zmq_application import OPENHCS_ENDPOINT_APPLICATION @@ -89,7 +90,7 @@ def test_napari_transport_rep_follows_receiver_owned_shared_memory_copy( ], "display_config": ViewerBatchDisplayPayload( component_modes=NapariDisplayConfig().component_modes(), - component_order=NapariDisplayConfig.COMPONENT_ORDER, + component_order=AxisFamily.active().names(), extra=NapariDisplayConfig().display_payload_extra(), ).to_wire_mapping(), "component_value_domain": {"well": ["A01"]}, diff --git a/tests/unit/test_native_viewer_presentation.py b/tests/unit/test_native_viewer_presentation.py index 2d0ebbfd4f..d025cbb91e 100644 --- a/tests/unit/test_native_viewer_presentation.py +++ b/tests/unit/test_native_viewer_presentation.py @@ -21,6 +21,7 @@ from polystore.streaming_constants import StreamingDataType from zmqruntime.viewer_protocol import ViewerNativeViewportPresentation, ViewerWireField +from openhcs.domains.microscopy.axes import Microscopy from openhcs.agent.dto.execution import ExecutionConnectionSpec from openhcs.agent.dto.viewer import ViewerWindowViewportRequest from openhcs.agent.services.viewer_window_service import ( @@ -574,9 +575,9 @@ def test_selected_file_stream_restores_persisted_crop_calibration_and_native_bat spacing = SourceVoxelSpacing((1.3556, 1.3556)) domain = SourceSpatialDomain((7, 11), (20, 30), 0, "Retained crop") for channel in (1, 2): - address = OpenHCSPlaneAddress.from_values(well, 1, channel, 1, 1) + address = OpenHCSPlaneAddress(((Microscopy.Well, well), (Microscopy.Site, 1), (Microscopy.Channel, channel), (Microscopy.ZIndex, 1), (Microscopy.Timepoint, 1))) component_metadata = { - component.value: value + component.name: value for component, value in address.component_values().items() } contributors = tuple( diff --git a/tests/unit/test_neuroncyto_ii_neurite_demo.py b/tests/unit/test_neuroncyto_ii_neurite_demo.py index 7dd12be548..222eecf3f4 100644 --- a/tests/unit/test_neuroncyto_ii_neurite_demo.py +++ b/tests/unit/test_neuroncyto_ii_neurite_demo.py @@ -9,7 +9,7 @@ from objectstate import ObjectStateRegistry from objectstate.lazy_factory import ensure_global_config_context -from openhcs.constants import AllComponents, GroupBy, Microscope, VariableComponents +from openhcs.constants import Microscope from openhcs.constants.input_source import InputSource from openhcs.core.callable_contract import CallableContract from openhcs.core.artifacts import ArtifactViewerStreaming @@ -41,6 +41,8 @@ ) from polystore.base import ensure_storage_registry, storage_registry from polystore.filemanager import FileManager +from openhcs.core.axes import Ungrouped +from openhcs.domains.microscopy.axes import Microscopy def _inputs(plate_path: Path, output_root: Path) -> NeuronCytoIICrossoverInputs: @@ -79,7 +81,7 @@ def test_neuroncyto_demo_declares_exact_crossover_channel_semantics( next( selector.value for selector in binding.component_identity - if selector.component is AllComponents.CHANNEL + if selector.component is Microscopy.Channel ) for binding in bindings ] == ["1", "2"] @@ -87,8 +89,8 @@ def test_neuroncyto_demo_declares_exact_crossover_channel_semantics( assert len(steps) == 1 step = steps[0] assert get_core_callable(step.func) is neurite_outgrowth_metaxpress_pixels - assert step.processing_config.variable_components == [VariableComponents.CHANNEL] - assert step.processing_config.group_by is GroupBy.NONE + assert step.processing_config.variable_components == [Microscopy.Channel] + assert step.processing_config.group_by is Ungrouped assert step.processing_config.input_source is InputSource.PIPELINE_START assert step.napari_streaming_config.enabled is True assert step.napari_streaming_config.persistent is True @@ -188,7 +190,7 @@ def test_neuroncyto_demo_compiles_exact_loose_tiff_pair(tmp_path: Path) -> None: context = compilation.runtime_contexts[inputs.image_id] plan = context.step_plans[0] assert plan.step_name == "NeuronCyto II Crossover Neurite Outgrowth" - assert tuple(plan.variable_components) == (VariableComponents.CHANNEL,) + assert tuple(plan.variable_components) == (Microscopy.Channel,) assert plan.compiled_function_pattern is not None assert { output.name: output.viewer_streaming @@ -303,11 +305,11 @@ def test_neuroncyto_declared_identity_replaces_loose_tiff_store_coordinates( assert projection is not None source_projections = tuple(projection.source_projections_by_virtual_path.values()) assert { - source_projection.address.value_for(AllComponents.WELL) + source_projection.address.value_for(Microscopy.Well) for source_projection in source_projections } == {inputs.image_id} assert { - source_projection.address.value_for(AllComponents.CHANNEL) + source_projection.address.value_for(Microscopy.Channel) for source_projection in source_projections } == {"1", "2"} assert { diff --git a/tests/unit/test_omero_microscope_metadata.py b/tests/unit/test_omero_microscope_metadata.py index e383d2b8f7..fbccb0dd98 100644 --- a/tests/unit/test_omero_microscope_metadata.py +++ b/tests/unit/test_omero_microscope_metadata.py @@ -3,6 +3,7 @@ import sys from types import ModuleType, SimpleNamespace +from openhcs.domains.microscopy.axes import Microscopy from openhcs.formats.pattern.pattern_discovery import PatternDiscoveryEngine from openhcs.microscopes.omero import OMEROFilenameParser, OMEROMetadataHandler @@ -48,14 +49,14 @@ def test_omero_pattern_discovery_round_trips_symbolic_site() -> None: "/omero/plate_1/A01_s002_w2_z003_t001.tif", ], axis_id="A01", - variable_components=["site"], + variable_components=[Microscopy.Site], ) assert patterns == {"A01": ["A01_s{iii}_w2_z003_t001.tif"]} pattern = patterns["A01"][0] parsed = parser.parse_filename(pattern) assert parsed is not None - assert parsed.value_for(parser.component_for_name("site")) == "{iii}" + assert parsed.value_for(Microscopy.Site) == "{iii}" def test_grid_dimensions_follow_canonical_key_across_annotation_namespaces( diff --git a/tests/unit/test_path_planner_materialization.py b/tests/unit/test_path_planner_materialization.py index 16719d2ce3..51c71bd7f5 100644 --- a/tests/unit/test_path_planner_materialization.py +++ b/tests/unit/test_path_planner_materialization.py @@ -6,7 +6,6 @@ import pytest import numpy as np -from openhcs.constants.constants import AllComponents, GroupBy, VariableComponents from openhcs.constants.input_source import InputSource from openhcs.core.artifacts import ( ArtifactMeasurementSubjectRelation, @@ -117,6 +116,8 @@ from openhcs.microscopes.microscope_interfaces import MetadataArtifactProvider from openhcs.microscopes.openhcs import OpenHCSMetadataHandler from openhcs.processing.backends.analysis.metaxpress_utils import HiddenPixelSize +from openhcs.core.axes import Axis, GroupingDeclaration, Ungrouped +from openhcs.domains.microscopy.axes import Microscopy def _execute_compiled_metadata_pattern(compiled, input_plans=None, stored_outputs=()): @@ -312,8 +313,8 @@ def _resolved_step( is_function_step: bool = True, func=None, source_bindings: StepSourceBindingsConfig = EMPTY_SOURCE_BINDINGS, - group_by: GroupBy = GroupBy.CHANNEL, - variable_components: tuple[VariableComponents, ...] = (VariableComponents.SITE,), + group_by: type[GroupingDeclaration] = Microscopy.Channel, + variable_components: tuple[type[Axis], ...] = (Microscopy.Site,), input_source: InputSource = InputSource.PREVIOUS_STEP, processing_config: ProcessingConfig | None = None, step_materialization_config=None, @@ -411,7 +412,7 @@ def metadata_consumer(image, grid_dimensions): ) assert execution_bindings == CompiledSourceBindingPlan.empty() - assert execution_group_scope == PathPlannerGroupScope.dynamic(AllComponents.CHANNEL) + assert execution_group_scope == PathPlannerGroupScope.dynamic(Microscopy.Channel) assert runtime_input_plans == {} assert compiled is not None (invocation,) = compiled.default_group.invocations @@ -619,7 +620,7 @@ def export_measurements(*, artifact_batch: RuntimeArtifactBatch): enabled=True, bindings=(NamedSourceBinding(alias="DNA"),), ), - group_by=GroupBy.NONE, + group_by=Ungrouped, variable_components=(), input_source=InputSource.PIPELINE_START, ) @@ -878,7 +879,7 @@ def produce_shared(): producer_snapshot = _resolved_step( name="produce_shared", func=produce_shared, - group_by=GroupBy.NONE, + group_by=Ungrouped, variable_components=(), input_source=InputSource.PIPELINE_START, ) @@ -944,7 +945,7 @@ def consume_shared(image, shared_image, shared_labels): consumer_snapshot = _resolved_step( name="consume_shared", func=consume_shared, - group_by=GroupBy.NONE, + group_by=Ungrouped, variable_components=(), ) ( @@ -1053,18 +1054,18 @@ def test_artifact_output_plan_only_preserves_explicit_source_stack_scope(): name=source.name, path="/memory/source.pkl", artifact_type=source.artifact_type, - variable_components=(AllComponents.CHANNEL,), + variable_components=(Microscopy.Channel,), ) }, source_bindings=EMPTY_SOURCE_BINDINGS, - variable_components=ComponentSet((AllComponents.CHANNEL,)), + variable_components=ComponentSet((Microscopy.Channel,)), step_name="transform", execution_scope=FunctionStepExecutionScope.AXIS, ) assert outputs[output_specs[0].ref()].variable_components == () assert outputs[output_specs[1].ref()].variable_components == ( - AllComponents.CHANNEL, + Microscopy.Channel, ) @@ -1100,12 +1101,12 @@ def test_artifact_output_source_lookup_combines_repeated_main_flow_inputs(): sid=2, artifact_inputs={}, source_bindings=EMPTY_SOURCE_BINDINGS, - variable_components=ComponentSet((AllComponents.Z_INDEX,)), + variable_components=ComponentSet((Microscopy.ZIndex,)), step_name="watershed", execution_scope=FunctionStepExecutionScope.AXIS, ) - assert outputs[output.ref()].variable_components == (AllComponents.Z_INDEX,) + assert outputs[output.ref()].variable_components == (Microscopy.ZIndex,) @pytest.mark.parametrize("stored_main_flow", [False, True]) @@ -1155,7 +1156,7 @@ def combine_sources(image, secondary=None): artifact_inputs=stored_inputs, relation_source_scopes={}, execution_group_scope=PathPlannerGroupScope.ungrouped(), - consumer_variable_components=ComponentSet((AllComponents.Z_INDEX,)), + consumer_variable_components=ComponentSet((Microscopy.ZIndex,)), main_flow_artifacts=ArtifactSpecCollection(source_specs), ) @@ -1187,8 +1188,8 @@ def test_implicit_native_main_flow_provenance_drives_artifact_owned_scope(): ) processing_config = LazyProcessingConfig( - variable_components=[VariableComponents.SITE], - group_by=GroupBy.CHANNEL, + variable_components=[Microscopy.Site], + group_by=Microscopy.Channel, input_source=InputSource.PREVIOUS_STEP, ) steps = ( @@ -1237,7 +1238,7 @@ def test_implicit_native_main_flow_provenance_drives_artifact_owned_scope(): ) channel_scope = PathPlannerGroupScope.from_raw( ("1", "2", "4"), - component=AllComponents.CHANNEL, + component=Microscopy.Channel, ) planner.plans[0] = CompiledStepPlan( step_index=0, @@ -1258,7 +1259,7 @@ def test_implicit_native_main_flow_provenance_drives_artifact_owned_scope(): planner.artifact_context, step_name=steps[1].name, step_index=1, - group_by=GroupBy.CHANNEL, + group_by=Microscopy.Channel, input_source=InputSource.PREVIOUS_STEP, ) planner.artifact_context = consumer_context @@ -1299,7 +1300,7 @@ def test_implicit_native_main_flow_provenance_drives_artifact_owned_scope(): sid=1, consumer_scope=execution_scope, source_bindings=EMPTY_SOURCE_BINDINGS, - variable_components=ComponentSet((AllComponents.SITE,)), + variable_components=ComponentSet((Microscopy.Site,)), step_name="Threshold", execution_scope=FunctionStepExecutionScope.AXIS, ) @@ -1317,7 +1318,7 @@ def test_implicit_native_main_flow_provenance_drives_artifact_owned_scope(): artifact_inputs=compiled_inputs, relation_source_scopes={}, execution_group_scope=execution_scope, - consumer_variable_components=ComponentSet((AllComponents.SITE,)), + consumer_variable_components=ComponentSet((Microscopy.Site,)), main_flow_artifacts=planner.artifact_context.main_flow_artifacts, ) edge = next(compiled_consumer.iter_invocations()).artifact_input_edges[0] @@ -1365,16 +1366,16 @@ def test_artifact_output_source_uses_compiled_plan_across_parameter_occurrences( name=measured.name, path="/memory/Cells.pkl", artifact_type=measured.artifact_type, - variable_components=(AllComponents.Z_INDEX,), + variable_components=(Microscopy.ZIndex,), ) }, source_bindings=EMPTY_SOURCE_BINDINGS, - variable_components=ComponentSet((AllComponents.Z_INDEX,)), + variable_components=ComponentSet((Microscopy.ZIndex,)), step_name="MeasureObjectNeighbors", execution_scope=FunctionStepExecutionScope.AXIS, ) - assert outputs[output.ref()].variable_components == (AllComponents.Z_INDEX,) + assert outputs[output.ref()].variable_components == (Microscopy.ZIndex,) assert outputs[output.ref()].relations == output.relations @@ -1417,16 +1418,16 @@ def test_artifact_output_source_lookup_ignores_shared_input_broadcast_projection path="/memory/OrigGreen.pkl", artifact_type=ImageArtifactType, group_keys=("2",), - group_component=AllComponents.CHANNEL, - variable_components=(AllComponents.SITE,), + group_component=Microscopy.Channel, + variable_components=(Microscopy.Site,), ), red.ref(): ArtifactInputPlan( name=red.name, path="/memory/OrigRed.pkl", artifact_type=ImageArtifactType, group_keys=("3",), - group_component=AllComponents.CHANNEL, - variable_components=(AllComponents.SITE,), + group_component=Microscopy.Channel, + variable_components=(Microscopy.Site,), ), green_mask.ref(): ArtifactInputPlan( name=mask_name, @@ -1434,8 +1435,8 @@ def test_artifact_output_source_lookup_ignores_shared_input_broadcast_projection artifact_type=ImageArtifactType, sidecar_role=ArtifactSidecarRole.CROP_MASK, group_keys=("1",), - group_component=AllComponents.CHANNEL, - variable_components=(AllComponents.SITE,), + group_component=Microscopy.Channel, + variable_components=(Microscopy.Site,), ), } @@ -1458,7 +1459,7 @@ def test_artifact_output_source_lookup_ignores_shared_input_broadcast_projection sid=2, artifact_inputs=artifact_inputs, source_bindings=EMPTY_SOURCE_BINDINGS, - variable_components=ComponentSet((AllComponents.SITE,)), + variable_components=ComponentSet((Microscopy.Site,)), step_name="Crop", execution_scope=FunctionStepExecutionScope.AXIS, ) @@ -1491,13 +1492,13 @@ def test_artifact_output_source_lookup_ignores_shared_input_broadcast_projection sid=2, artifact_inputs=artifact_inputs, source_bindings=EMPTY_SOURCE_BINDINGS, - variable_components=ComponentSet((AllComponents.SITE,)), + variable_components=ComponentSet((Microscopy.Site,)), step_name="Crop", execution_scope=FunctionStepExecutionScope.AXIS, ) assert projected[ambiguous_output.ref()].variable_components == ( - AllComponents.SITE, + Microscopy.Site, ) @@ -1544,7 +1545,7 @@ def identify(main_image, Stain1): bindings=( NamedSourceBinding( alias=source_binding_spec.name, - component_identity=(ComponentSelector(AllComponents.CHANNEL, "1"),), + component_identity=(ComponentSelector(Microscopy.Channel, "1"),), ), ), ) @@ -1576,8 +1577,8 @@ def identify(main_image, Stain1): path="/memory/Stain1.pkl", artifact_type=ImageArtifactType, group_keys=("1", "2"), - group_component=AllComponents.SITE, - variable_components=(AllComponents.CHANNEL,), + group_component=Microscopy.Site, + variable_components=(Microscopy.Channel,), paths_by_group={ "1": "/memory/Stain1_site_1.pkl", "2": "/memory/Stain1_site_2.pkl", @@ -1619,22 +1620,22 @@ def identify(main_image, Stain1): expected_channel_scope = ComponentGroupScope.from_raw( ("1",), - component=AllComponents.CHANNEL, + component=Microscopy.Channel, ) assert maps.group_scope.keys == expected_channel_scope.keys assert maps.group_scope.component is expected_channel_scope.component assert maps.outputs[object_output.ref()].group_keys == ("1",) assert maps.outputs[object_output.ref()].variable_components == ( - AllComponents.SITE, + Microscopy.Site, ) edge = next(compiled.iter_invocations()).artifact_input_edges[0] assert edge.projection.invocation_scope == expected_channel_scope - assert edge.projection.component_scope(AllComponents.CHANNEL) == ( + assert edge.projection.component_scope(Microscopy.Channel) == ( expected_channel_scope ) assert edge.projection.producer_selection_scope == ComponentGroupScope.from_raw( ("1", "2"), - component=AllComponents.SITE, + component=Microscopy.Site, ) @@ -1672,7 +1673,7 @@ def test_fixed_source_component_domain_survives_produced_artifact_lineage( bindings=( NamedSourceBinding( alias=source.name, - component_identity=(ComponentSelector(AllComponents.CHANNEL, "1"),), + component_identity=(ComponentSelector(Microscopy.Channel, "1"),), ), ), ) @@ -1682,20 +1683,20 @@ def test_fixed_source_component_domain_survives_produced_artifact_lineage( ).with_source_declarations((source,)) producer_scope = PathPlannerGroupScope.from_raw( ("1",), - component=AllComponents.SITE, + component=Microscopy.Site, ) relation_scopes = planner.artifacts.relation_source_scopes_by_ref( producer_declarations, {}, group_scope=producer_scope, source_bindings=source_bindings, - group_by=GroupBy.SITE, + group_by=Microscopy.Site, ) output_groups = planner.artifacts.output_groups_from_declared_relations( producer_declarations, group_scope=producer_scope, relation_source_scopes=relation_scopes, - consumer_variable_components=ComponentSet((AllComponents.CHANNEL,)), + consumer_variable_components=ComponentSet((Microscopy.Channel,)), step_index=2, step_name="produce", ) @@ -1706,16 +1707,16 @@ def test_fixed_source_component_domain_survives_produced_artifact_lineage( artifact_inputs={}, relation_source_scopes=relation_scopes, source_bindings=source_bindings, - variable_components=ComponentSet((AllComponents.CHANNEL,)), + variable_components=ComponentSet((Microscopy.Channel,)), step_name="produce", execution_scope=FunctionStepExecutionScope.AXIS, )[output_spec.ref()] fixed_channel = ComponentGroupScope.from_raw( ("1",), - component=AllComponents.CHANNEL, + component=Microscopy.Channel, ) - assert output_plan.component_domain(AllComponents.CHANNEL) == fixed_channel + assert output_plan.component_domain(Microscopy.Channel) == fixed_channel input_spec = output_spec.for_plan_type(ArtifactInputPlan) @@ -1733,14 +1734,14 @@ def consume(image): ) consumer_scope = PathPlannerGroupScope.from_raw( ("2",), - component=AllComponents.CHANNEL, + component=Microscopy.Channel, ) input_plan = planner.artifacts.process_artifact_inputs( consumer_declarations, 3, consumer_scope, EMPTY_SOURCE_BINDINGS, - ComponentSet((AllComponents.SITE,)), + ComponentSet((Microscopy.Site,)), step_name="consume", execution_scope=FunctionStepExecutionScope.AXIS, )[input_spec.ref()] @@ -1749,7 +1750,7 @@ def consume(image): {input_plan.ref(): input_plan}, group_scope=consumer_scope, source_bindings=EMPTY_SOURCE_BINDINGS, - group_by=GroupBy.CHANNEL, + group_by=Microscopy.Channel, ) compiled = planner.artifacts.compile_invocation_input_edges( compile_function_pattern( @@ -1760,18 +1761,18 @@ def consume(image): artifact_inputs={input_plan.ref(): input_plan}, relation_source_scopes=consumer_relation_scopes, execution_group_scope=consumer_scope, - consumer_variable_components=ComponentSet((AllComponents.SITE,)), + consumer_variable_components=ComponentSet((Microscopy.Site,)), ) edge = next(compiled.iter_invocations()).artifact_input_edges[0] - assert input_plan.component_domain(AllComponents.CHANNEL) == fixed_channel + assert input_plan.component_domain(Microscopy.Channel) == fixed_channel assert consumer_relation_scopes[input_spec.ref()] == ( PathPlannerGroupScope.from_raw( fixed_channel.keys, component=fixed_channel.component, ) ) - assert edge.projection.component_scope(AllComponents.CHANNEL) == fixed_channel + assert edge.projection.component_scope(Microscopy.Channel) == fixed_channel @pytest.mark.parametrize( @@ -1779,13 +1780,13 @@ def consume(image): ( ( "Crop", - (AllComponents.SITE,), - ((), (AllComponents.SITE,)), + (Microscopy.Site,), + ((), (Microscopy.Site,)), ), ( "Align", - (AllComponents.CHANNEL,), - ((AllComponents.CHANNEL,), (), ()), + (Microscopy.Channel,), + ((Microscopy.Channel,), (), ()), ), ), ids=("crop-site-and-scalar-sources", "align-channel-and-scalar-sources"), @@ -1864,7 +1865,7 @@ def identify(image): scopes = planner.artifacts.output_groups_from_declared_relations( namespaced, - group_scope=PathPlannerGroupScope.from_raw(("1", "2"), component=AllComponents.CHANNEL), + group_scope=PathPlannerGroupScope.from_raw(("1", "2"), component=Microscopy.Channel), relation_source_scopes={}, consumer_variable_components=ComponentSet(), step_index=0, step_name="identify", ) @@ -1917,7 +1918,7 @@ def declared_artifact_owner(image): assert declarations.output_groups[output_ref] == {None} scopes = planner.artifacts.output_groups_from_declared_relations( namespaced, - group_scope=PathPlannerGroupScope.from_raw(("1", "2"), component=AllComponents.CHANNEL), + group_scope=PathPlannerGroupScope.from_raw(("1", "2"), component=Microscopy.Channel), relation_source_scopes={}, consumer_variable_components=ComponentSet(), step_index=0, step_name="correct_illumination", ) @@ -1933,7 +1934,7 @@ def test_declared_group_lineage_scopes_outputs_without_rewriting_execution(): path="/memory/Tile_of_grid.pkl", artifact_type=ObjectLabelsArtifactType, group_keys=("1",), - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, paths_by_group={"1": "/memory/Tile_of_grid_1.pkl"}, ), ) @@ -1971,7 +1972,7 @@ def test_declared_group_lineage_scopes_outputs_without_rewriting_execution(): _resolved_step(name="FilterObjects"), 3, declarations, - PathPlannerGroupScope.from_raw(("2",), component=AllComponents.CHANNEL), + PathPlannerGroupScope.from_raw(("2",), component=Microscopy.Channel), ) filtered_tiles_ref = ArtifactSpec.output( @@ -1984,11 +1985,11 @@ def test_declared_group_lineage_scopes_outputs_without_rewriting_execution(): ).ref() assert maps.outputs[filtered_tiles_ref].group_keys == ("1",) assert maps.outputs[measurements_ref].group_keys == ("1",) - assert maps.outputs[filtered_tiles_ref].group_component is AllComponents.CHANNEL - assert maps.outputs[measurements_ref].group_component is AllComponents.CHANNEL + assert maps.outputs[filtered_tiles_ref].group_component is Microscopy.Channel + assert maps.outputs[measurements_ref].group_component is Microscopy.Channel assert maps.group_scope == PathPlannerGroupScope.from_raw( ("2",), - component=AllComponents.CHANNEL, + component=Microscopy.Channel, ) @@ -2016,7 +2017,7 @@ def test_declared_group_lineage_uses_main_flow_scope_without_artifact_plan(): ) group_scope = PathPlannerGroupScope.from_raw( ("1", "2"), - component=AllComponents.SITE, + component=Microscopy.Site, ) maps = planner.artifacts.compile_plan_maps( @@ -2035,7 +2036,7 @@ def test_declared_group_lineage_uses_main_flow_scope_without_artifact_plan(): "1", "2", ) - assert maps.outputs[measurements_ref].group_component is AllComponents.SITE + assert maps.outputs[measurements_ref].group_component is Microscopy.Site def test_prior_main_flow_artifact_scopes_output_without_rewriting_execution(): @@ -2045,7 +2046,7 @@ def test_prior_main_flow_artifact_scopes_output_without_rewriting_execution(): path="/memory/CropRed.pkl", artifact_type=ImageArtifactType, group_keys=("3",), - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, paths_by_group={"3": "/memory/CropRed_3.pkl"}, ) _record_declared_output(planner, producer) @@ -2076,14 +2077,14 @@ def test_prior_main_flow_artifact_scopes_output_without_rewriting_execution(): declarations, PathPlannerGroupScope.from_raw( ("2", "3"), - component=AllComponents.CHANNEL, + component=Microscopy.Channel, ), ) assert maps.inputs == {} assert maps.group_scope == PathPlannerGroupScope.from_raw( ("2", "3"), - component=AllComponents.CHANNEL, + component=Microscopy.Channel, ) nuclei_ref = ArtifactSpec.output("Nuclei", ObjectLabelsArtifactType).ref() assert maps.outputs[nuclei_ref].group_keys == ("3",) @@ -2118,7 +2119,7 @@ def test_dict_invocation_lineage_uses_its_non_plan_input_group_scope(): declarations, PathPlannerGroupScope.from_raw( ("1", "2"), - component=AllComponents.CHANNEL, + component=Microscopy.Channel, ), ) @@ -2138,7 +2139,7 @@ def test_measurement_output_scope_compiles_exact_cross_group_consumer_edge(): path="/memory/Tile_of_grid.pkl", artifact_type=ObjectLabelsArtifactType, group_keys=("1",), - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, paths_by_group={"1": "/memory/Tile_of_grid_1.pkl"}, ), ) @@ -2188,13 +2189,13 @@ def test_measurement_output_scope_compiles_exact_cross_group_consumer_edge(): declarations, PathPlannerGroupScope.from_raw( ("2",), - component=AllComponents.CHANNEL, + component=Microscopy.Channel, ), ) assert maps.group_scope == PathPlannerGroupScope.from_raw( ("2",), - component=AllComponents.CHANNEL, + component=Microscopy.Channel, ) measurement_name = "MeasureObjectIntensity_3_measurements" measurement_ref = ArtifactSpec.output( @@ -2221,8 +2222,8 @@ def filter_objects(main_image, MeasureObjectIntensity_3_measurements): consumer_snapshot = _resolved_step( name="FilterObjects", func=filter_objects, - group_by=GroupBy.CHANNEL, - variable_components=(VariableComponents.SITE,), + group_by=Microscopy.Channel, + variable_components=(Microscopy.Site,), ) consumer_maps = planner.artifacts.compile_plan_maps( consumer_snapshot, @@ -2237,7 +2238,7 @@ def filter_objects(main_image, MeasureObjectIntensity_3_measurements): ), PathPlannerGroupScope.from_raw( ("1",), - component=AllComponents.CHANNEL, + component=Microscopy.Channel, ), ) compiled = planner.artifacts.build_step_compiled_function_pattern( @@ -2255,7 +2256,7 @@ def filter_objects(main_image, MeasureObjectIntensity_3_measurements): edge = next(compiled.iter_invocations()).artifact_input_edges[0] assert edge.projection.producer_selection_scope == ComponentGroupScope( ("2",), - component=AllComponents.CHANNEL, + component=Microscopy.Channel, ) @@ -2275,8 +2276,8 @@ def test_artifact_managed_lineage_keeps_exact_named_inputs_in_one_invocation(): path=f"/memory/{name}.pkl", artifact_type=artifact_type, group_keys=(channel,), - group_component=AllComponents.CHANNEL, - variable_components=(AllComponents.SITE,), + group_component=Microscopy.Channel, + variable_components=(Microscopy.Site,), paths_by_group={channel: f"/memory/{name}_{channel}.pkl"}, ), ) @@ -2340,7 +2341,7 @@ def test_artifact_managed_single_source_output_retains_source_group_scope(): path="/memory/CropBlue.pkl", artifact_type=ImageArtifactType, group_keys=("1",), - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, paths_by_group={"1": "/memory/CropBlue_1.pkl"}, ), ) @@ -2383,7 +2384,7 @@ def test_artifact_managed_single_source_output_retains_source_group_scope(): assert maps.group_scope == PathPlannerGroupScope.ungrouped() nuclei_ref = ArtifactSpec.output("Nuclei", ObjectLabelsArtifactType).ref() assert maps.outputs[nuclei_ref].group_keys == ("1",) - assert maps.outputs[nuclei_ref].group_component is AllComponents.CHANNEL + assert maps.outputs[nuclei_ref].group_component is Microscopy.Channel def test_declared_group_lineage_unions_compatible_source_groups(): @@ -2395,7 +2396,7 @@ def test_declared_group_lineage_unions_compatible_source_groups(): path="/memory/OrigStain1.pkl", artifact_type=ImageArtifactType, group_keys=("1",), - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, paths_by_group={"1": "/memory/OrigStain1_1.pkl"}, ), ) @@ -2406,7 +2407,7 @@ def test_declared_group_lineage_unions_compatible_source_groups(): path="/memory/OrigStain2.pkl", artifact_type=ImageArtifactType, group_keys=("2",), - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, paths_by_group={"2": "/memory/OrigStain2_2.pkl"}, ), ) @@ -2445,7 +2446,7 @@ def test_declared_group_lineage_unions_compatible_source_groups(): declarations, PathPlannerGroupScope.from_raw( ("1", "2"), - component=AllComponents.CHANNEL, + component=Microscopy.Channel, ), ) @@ -2455,18 +2456,18 @@ def test_declared_group_lineage_unions_compatible_source_groups(): ).ref() assert maps.outputs[measurements_ref].group_keys == ("1", "2") assert maps.relation_source_scopes[first_ref] == ( - PathPlannerGroupScope.from_raw(("1",), component=AllComponents.CHANNEL) + PathPlannerGroupScope.from_raw(("1",), component=Microscopy.Channel) ) assert maps.relation_source_scopes[second_ref] == ( - PathPlannerGroupScope.from_raw(("2",), component=AllComponents.CHANNEL) + PathPlannerGroupScope.from_raw(("2",), component=Microscopy.Channel) ) def test_dynamic_group_scope_union_remains_dynamic(): - dynamic_scope = PathPlannerGroupScope.dynamic(AllComponents.SITE) + dynamic_scope = PathPlannerGroupScope.dynamic(Microscopy.Site) concrete_scope = PathPlannerGroupScope.from_raw( ("1", "2"), - component=AllComponents.SITE, + component=Microscopy.Site, ) assert ( @@ -2489,8 +2490,8 @@ def test_collected_lineage_outputs_use_relation_owned_group_scope(): path=f"/memory/{name}.pkl", artifact_type=artifact_type, group_keys=(channel,), - group_component=AllComponents.CHANNEL, - variable_components=(AllComponents.SITE,), + group_component=Microscopy.Channel, + variable_components=(Microscopy.Site,), paths_by_group={channel: f"/memory/{name}_{channel}.pkl"}, ), ) @@ -2526,21 +2527,21 @@ def test_collected_lineage_outputs_use_relation_owned_group_scope(): maps = planner.artifacts.compile_plan_maps( _resolved_step( name="MeasureColocalization", - group_by=GroupBy.SITE, - variable_components=(VariableComponents.CHANNEL,), + group_by=Microscopy.Site, + variable_components=(Microscopy.Channel,), ), 3, declarations, - PathPlannerGroupScope.dynamic(AllComponents.SITE), + PathPlannerGroupScope.dynamic(Microscopy.Site), ) - assert maps.group_scope == PathPlannerGroupScope.dynamic(AllComponents.SITE) + assert maps.group_scope == PathPlannerGroupScope.dynamic(Microscopy.Site) measurements_ref = ArtifactSpec.output( "Measurements", MeasurementsArtifactType, ).ref() assert maps.outputs[measurements_ref].group_keys == (None,) - assert maps.outputs[measurements_ref].group_component is AllComponents.SITE + assert maps.outputs[measurements_ref].group_component is Microscopy.Site def test_output_lineage_uses_input_qualified_consumer_scope(): @@ -2563,7 +2564,7 @@ def test_output_lineage_uses_input_qualified_consumer_scope(): path="/memory/Nuclei.pkl", artifact_type=nuclei.artifact_type, group_keys=("1",), - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, paths_by_group={"1": "/memory/Nuclei_1.pkl"}, ), ) @@ -2574,7 +2575,7 @@ def test_output_lineage_uses_input_qualified_consumer_scope(): path="/memory/PriorMeasurements.pkl", artifact_type=prior_measurements.artifact_type, group_keys=("1", "2"), - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, paths_by_group={ "1": "/memory/PriorMeasurements_1.pkl", "2": "/memory/PriorMeasurements_2.pkl", @@ -2603,7 +2604,7 @@ def test_output_lineage_uses_input_qualified_consumer_scope(): declarations, PathPlannerGroupScope.from_raw( ("1", "2"), - component=AllComponents.CHANNEL, + component=Microscopy.Channel, ), ) @@ -2611,7 +2612,7 @@ def test_output_lineage_uses_input_qualified_consumer_scope(): assert maps.relation_source_scopes[prior_measurements.ref()] == ( PathPlannerGroupScope.from_raw( ("1", "2"), - component=AllComponents.CHANNEL, + component=Microscopy.Channel, ) ) assert output_plan.group_keys == ("1",) @@ -2670,7 +2671,7 @@ def measure_green(image, *, runtime): NamedSourceBinding( alias=name, origin=SourceBindingOrigin.PIPELINE_START, - component_identity=(ComponentSelector(AllComponents.CHANNEL, channel),), + component_identity=(ComponentSelector(Microscopy.Channel, channel),), ) for name, channel in ((blue.name, "1"), (green.name, "2")) ), @@ -2680,13 +2681,13 @@ def measure_green(image, *, runtime): name="MeasureChannels", func=functions, source_bindings=source_bindings, - group_by=GroupBy.CHANNEL, - variable_components=(VariableComponents.SITE,), + group_by=Microscopy.Channel, + variable_components=(Microscopy.Site,), input_source=InputSource.PIPELINE_START, ) execution_scope = PathPlannerGroupScope.from_raw( ("1", "2"), - component=AllComponents.CHANNEL, + component=Microscopy.Channel, ) maps = planner.artifacts.compile_plan_maps( @@ -2702,7 +2703,7 @@ def measure_green(image, *, runtime): artifact_inputs=maps.inputs, relation_source_scopes=maps.relation_source_scopes, execution_group_scope=execution_scope, - consumer_variable_components=ComponentSet((AllComponents.SITE,)), + consumer_variable_components=ComponentSet((Microscopy.Site,)), source_bindings=source_bindings, available_artifacts=planner.artifact_context.available_artifacts, main_flow_artifacts=planner.artifact_context.main_flow_artifacts, @@ -2749,8 +2750,8 @@ def test_real_object_measurement_preserves_selected_labels_group_scope( path="/memory/Cells.pkl", artifact_type=ObjectLabelsArtifactType, group_keys=("2",), - group_component=AllComponents.CHANNEL, - variable_components=(AllComponents.SITE,), + group_component=Microscopy.Channel, + variable_components=(Microscopy.Site,), paths_by_group={"2": "/memory/Cells_2.pkl"}, ), ) @@ -2768,7 +2769,7 @@ def test_real_object_measurement_preserves_selected_labels_group_scope( step_context = ArtifactDeclarationStepContext( step_name=snapshot.name, step_index=3, - group_by=GroupBy.CHANNEL, + group_by=Microscopy.Channel, available_artifacts=ArtifactSpecCollection((labels_input,)), available_artifact_producers=( ArtifactProducer( @@ -2820,7 +2821,7 @@ def test_real_object_measurement_preserves_selected_labels_group_scope( ) assert selector in consumed_names group_scope = PathPlannerGroupScope.from_raw( - ("1", "2"), component=AllComponents.CHANNEL + ("1", "2"), component=Microscopy.Channel ) if measurement_group == "1": @@ -2859,7 +2860,7 @@ def test_declared_group_lineage_cannot_rewrite_scalar_step_execution_scope(): path="/memory/MembInvertRemoveHoles.pkl", artifact_type=ImageArtifactType, group_keys=("3",), - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, paths_by_group={"3": "/memory/MembInvertRemoveHoles_3.pkl"}, ), ) @@ -2870,7 +2871,7 @@ def test_declared_group_lineage_cannot_rewrite_scalar_step_execution_scope(): path="/memory/MonolayerMask.pkl", artifact_type=ImageArtifactType, group_keys=("1",), - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, paths_by_group={"1": "/memory/MonolayerMask_1.pkl"}, ), ) @@ -2916,12 +2917,12 @@ def test_declared_group_lineage_cannot_rewrite_scalar_step_execution_scope(): _resolved_step(name="MaskImage"), 3, declarations, - PathPlannerGroupScope.from_raw(("1", "3"), component=AllComponents.CHANNEL), + PathPlannerGroupScope.from_raw(("1", "3"), component=Microscopy.Channel), ) assert maps.group_scope == PathPlannerGroupScope.from_raw( ("1", "3"), - component=AllComponents.CHANNEL, + component=Microscopy.Channel, ) masked_ref = ArtifactSpec.output("MembMasked", ImageArtifactType).ref() assert maps.outputs[masked_ref].group_keys == ("3",) @@ -2951,7 +2952,7 @@ def test_artifact_output_storage_scope_is_independent_of_execution_scope(): path="/memory/PriorMeasurements.pkl", artifact_type=MeasurementsArtifactType, group_keys=("1", "2"), - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, paths_by_group={ "1": "/memory/PriorMeasurements_1.pkl", "2": "/memory/PriorMeasurements_2.pkl", @@ -2967,7 +2968,7 @@ def test_artifact_output_storage_scope_is_independent_of_execution_scope(): path="/memory/Nuclei.pkl", artifact_type=ObjectLabelsArtifactType, group_keys=("1",), - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, paths_by_group={"1": "/memory/Nuclei_1.pkl"}, producer_step_index=2, producer_step_name="IdentifyPrimaryObjects", @@ -3005,12 +3006,12 @@ def test_artifact_output_storage_scope_is_independent_of_execution_scope(): _resolved_step(name="CalculateMath"), 3, declarations, - PathPlannerGroupScope.from_raw(("3",), component=AllComponents.CHANNEL), + PathPlannerGroupScope.from_raw(("3",), component=Microscopy.Channel), ) assert maps.group_scope == PathPlannerGroupScope.from_raw( ("3",), - component=AllComponents.CHANNEL, + component=Microscopy.Channel, ) ratio_ref = ArtifactSpec.output("Ratio", MeasurementsArtifactType).ref() assert maps.outputs[ratio_ref].group_keys == ("1",) @@ -3029,7 +3030,7 @@ def test_each_output_storage_scope_is_independent_of_execution_scope(): path="/memory/source.pkl", artifact_type=ImageArtifactType, group_keys=("2",), - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, paths_by_group={"2": "/memory/source_2.pkl"}, ), ) @@ -3075,17 +3076,17 @@ def test_each_output_storage_scope_is_independent_of_execution_scope(): declarations, PathPlannerGroupScope.from_raw( ("1", "2"), - component=AllComponents.CHANNEL, + component=Microscopy.Channel, ), ) execution_scope = PathPlannerGroupScope.from_raw( ("1", "2"), - component=AllComponents.CHANNEL, + component=Microscopy.Channel, ) relation_scope = PathPlannerGroupScope.from_raw( ("2",), - component=AllComponents.CHANNEL, + component=Microscopy.Channel, ) assert maps.group_scope == execution_scope scoped_ref = ArtifactSpec.output("scoped", ImageArtifactType).ref() @@ -3110,7 +3111,7 @@ def test_dict_pattern_output_groups_do_not_drive_scalar_scope_narrowing(): path="/memory/source.pkl", artifact_type=ImageArtifactType, group_keys=("3",), - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, paths_by_group={"3": "/memory/source_3.pkl"}, ), ) @@ -3149,12 +3150,12 @@ def test_dict_pattern_output_groups_do_not_drive_scalar_scope_narrowing(): _resolved_step(name="dict_pattern"), 3, declarations, - PathPlannerGroupScope.from_raw(("1", "3"), component=AllComponents.CHANNEL), + PathPlannerGroupScope.from_raw(("1", "3"), component=Microscopy.Channel), ) assert maps.group_scope == PathPlannerGroupScope.from_raw( ("1", "3"), - component=AllComponents.CHANNEL, + component=Microscopy.Channel, ) @@ -3183,7 +3184,7 @@ def test_source_binding_component_identity_narrows_declared_output_lineage(): bindings=( NamedSourceBinding( alias="origMemb", - component_identity=(ComponentSelector(AllComponents.CHANNEL, "3"),), + component_identity=(ComponentSelector(Microscopy.Channel, "3"),), ), ), enabled=True, @@ -3195,14 +3196,14 @@ def test_source_binding_component_identity_narrows_declared_output_lineage(): declarations, PathPlannerGroupScope.from_raw( ("1", "2", "3"), - component=AllComponents.CHANNEL, + component=Microscopy.Channel, ), source_bindings=source_bindings, ) cells_ref = ArtifactSpec.output("Cells", ObjectLabelsArtifactType).ref() assert maps.outputs[cells_ref].group_keys == ("3",) - assert maps.outputs[cells_ref].group_component is AllComponents.CHANNEL + assert maps.outputs[cells_ref].group_component is Microscopy.Channel def test_source_binding_identity_scopes_outputs_without_execution_fanout(): @@ -3230,7 +3231,7 @@ def test_source_binding_identity_scopes_outputs_without_execution_fanout(): bindings=( NamedSourceBinding( alias="origMemb", - component_identity=(ComponentSelector(AllComponents.CHANNEL, "3"),), + component_identity=(ComponentSelector(Microscopy.Channel, "3"),), ), ), enabled=True, @@ -3247,7 +3248,7 @@ def test_source_binding_identity_scopes_outputs_without_execution_fanout(): assert maps.group_scope == PathPlannerGroupScope.ungrouped() cells_ref = ArtifactSpec.output("Cells", ObjectLabelsArtifactType).ref() assert maps.outputs[cells_ref].group_keys == ("3",) - assert maps.outputs[cells_ref].group_component is AllComponents.CHANNEL + assert maps.outputs[cells_ref].group_component is Microscopy.Channel def test_image_object_outputs_keep_declared_image_execution_group_scope(): @@ -3262,7 +3263,7 @@ def test_image_object_outputs_keep_declared_image_execution_group_scope(): path="/memory/Tile_of_grid.pkl", artifact_type=ObjectLabelsArtifactType, group_keys=("1",), - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, paths_by_group={"1": "/memory/Tile_of_grid_1.pkl"}, ), ) @@ -3308,7 +3309,7 @@ def test_image_object_outputs_keep_declared_image_execution_group_scope(): declarations, PathPlannerGroupScope.from_raw( ("2",), - component=AllComponents.CHANNEL, + component=Microscopy.Channel, ), ) @@ -3328,7 +3329,7 @@ def test_group_lineage_source_resolves_prior_main_flow_output_without_store_inpu path="/memory/Tile_of_grid.pkl", artifact_type=ObjectLabelsArtifactType, group_keys=("1",), - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, paths_by_group={"1": "/memory/Tile_of_grid_1.pkl"}, ), ) @@ -3361,7 +3362,7 @@ def test_group_lineage_source_resolves_prior_main_flow_output_without_store_inpu declarations, PathPlannerGroupScope.from_raw( ("2",), - component=AllComponents.CHANNEL, + component=Microscopy.Channel, ), ) @@ -3393,8 +3394,8 @@ def declared_artifact_owner(image): snapshot = _resolved_step( is_function_step=True, func=(identify, {"artifact_name": "cells"}), - group_by=GroupBy.NONE, - variable_components=(VariableComponents.SITE,), + group_by=Ungrouped, + variable_components=(Microscopy.Site,), name="identify_cells", source_bindings=EMPTY_SOURCE_BINDINGS, input_source=InputSource.PREVIOUS_STEP, @@ -3453,17 +3454,17 @@ def filter_objects(image, *, runtime): snapshot = _resolved_step( is_function_step=True, func=filter_objects, - group_by=GroupBy.CHANNEL, - variable_components=(VariableComponents.SITE,), + group_by=Microscopy.Channel, + variable_components=(Microscopy.Site,), name="FilterObjects", source_bindings=EMPTY_SOURCE_BINDINGS, input_source=InputSource.PREVIOUS_STEP, ) input_component_scopes = PathPlannerComponentScopes( { - VariableComponents.CHANNEL: PathPlannerGroupScope.from_raw( + Microscopy.Channel: PathPlannerGroupScope.from_raw( ("1", "2"), - component=AllComponents.CHANNEL, + component=Microscopy.Channel, ) } ) @@ -3481,7 +3482,7 @@ def filter_objects(image, *, runtime): assert execution_groups == PathPlannerGroupScope.from_raw( ("1", "2"), - component=AllComponents.CHANNEL, + component=Microscopy.Channel, ) assert execution_scope is FunctionStepExecutionScope.AXIS @@ -3502,7 +3503,7 @@ def filter_objects(image, *, runtime): assert execution_groups == PathPlannerGroupScope.from_raw( ("1", "2"), - component=AllComponents.CHANNEL, + component=Microscopy.Channel, ) assert execution_scope is FunctionStepExecutionScope.AXIS @@ -3577,15 +3578,15 @@ def identify_primary_objects(image, *, runtime): path="/memory/Nuclei.pkl", artifact_type=nuclei.artifact_type, group_keys=("1", "2"), - group_component=AllComponents.SITE, + group_component=Microscopy.Site, component_domains=( ComponentGroupScope.from_raw( ("1",), - component=AllComponents.CHANNEL, + component=Microscopy.Channel, ), ComponentGroupScope.from_raw( ("1", "2"), - component=AllComponents.SITE, + component=Microscopy.Site, ), ), ), @@ -3593,17 +3594,17 @@ def identify_primary_objects(image, *, runtime): snapshot = _resolved_step( is_function_step=True, func=identify_primary_objects, - group_by=GroupBy.CHANNEL, - variable_components=(VariableComponents.SITE,), + group_by=Microscopy.Channel, + variable_components=(Microscopy.Site,), name="IdentifyPrimaryObjects", source_bindings=EMPTY_SOURCE_BINDINGS, input_source=InputSource.PREVIOUS_STEP, ) main_flow_scopes = PathPlannerComponentScopes( { - VariableComponents.CHANNEL: PathPlannerGroupScope.from_raw( + Microscopy.Channel: PathPlannerGroupScope.from_raw( ("2", "3"), - component=AllComponents.CHANNEL, + component=Microscopy.Channel, ) } ) @@ -3616,7 +3617,7 @@ def identify_primary_objects(image, *, runtime): assert scope == PathPlannerGroupScope.from_raw( ("1",), - component=AllComponents.CHANNEL, + component=Microscopy.Channel, ) @@ -3643,23 +3644,23 @@ def relate_objects(image, *, runtime): path=f"/memory/{spec.name}.pkl", artifact_type=spec.artifact_type, group_keys=(channel,), - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, ), ) snapshot = _resolved_step( is_function_step=True, func=relate_objects, - group_by=GroupBy.CHANNEL, - variable_components=(VariableComponents.SITE,), + group_by=Microscopy.Channel, + variable_components=(Microscopy.Site,), name="RelateObjects", source_bindings=EMPTY_SOURCE_BINDINGS, input_source=InputSource.PREVIOUS_STEP, ) main_flow_scopes = PathPlannerComponentScopes( { - VariableComponents.CHANNEL: PathPlannerGroupScope.from_raw( + Microscopy.Channel: PathPlannerGroupScope.from_raw( ("1", "2"), - component=AllComponents.CHANNEL, + component=Microscopy.Channel, ) } ) @@ -3672,7 +3673,7 @@ def relate_objects(image, *, runtime): assert scope == PathPlannerGroupScope.from_raw( ("1", "2"), - component=AllComponents.CHANNEL, + component=Microscopy.Channel, ) @@ -3697,23 +3698,23 @@ def measure_object_size_shape(image, *, runtime): path="/memory/CometOutline.pkl", artifact_type=comet_outline.artifact_type, group_keys=("1", "2"), - group_component=AllComponents.SITE, + group_component=Microscopy.Site, ), ) snapshot = _resolved_step( is_function_step=True, func=measure_object_size_shape, - group_by=GroupBy.CHANNEL, - variable_components=(VariableComponents.SITE,), + group_by=Microscopy.Channel, + variable_components=(Microscopy.Site,), name="MeasureObjectSizeShape", source_bindings=EMPTY_SOURCE_BINDINGS, input_source=InputSource.PREVIOUS_STEP, ) main_flow_scopes = PathPlannerComponentScopes( { - VariableComponents.CHANNEL: PathPlannerGroupScope.from_raw( + Microscopy.Channel: PathPlannerGroupScope.from_raw( ("1",), - component=AllComponents.CHANNEL, + component=Microscopy.Channel, ) } ) @@ -3726,7 +3727,7 @@ def measure_object_size_shape(image, *, runtime): assert scope == PathPlannerGroupScope.from_raw( ("1",), - component=AllComponents.CHANNEL, + component=Microscopy.Channel, ) @@ -3735,8 +3736,8 @@ def test_execution_groups_resolve_non_grouped_variable_component_conflicts(): snapshot = _resolved_step( is_function_step=True, func=lambda image: image, - group_by=GroupBy.CHANNEL, - variable_components=(VariableComponents.SITE, VariableComponents.CHANNEL), + group_by=Microscopy.Channel, + variable_components=(Microscopy.Site, Microscopy.Channel), name="source_bound_cellprofiler_step", source_bindings=EMPTY_SOURCE_BINDINGS, ) @@ -3757,8 +3758,8 @@ def test_non_dict_group_by_declares_dynamic_scope_without_plate_key_lookup(): source_snapshot = _resolved_step( is_function_step=True, func=lambda image: image, - group_by=GroupBy.CHANNEL, - variable_components=(VariableComponents.SITE,), + group_by=Microscopy.Channel, + variable_components=(Microscopy.Site,), name="enhance", source_bindings=EMPTY_SOURCE_BINDINGS, input_source=InputSource.PREVIOUS_STEP, @@ -3770,7 +3771,7 @@ def test_non_dict_group_by_declares_dynamic_scope_without_plate_key_lookup(): ) assert source_scope == PathPlannerGroupScope.from_raw( (None,), - component=AllComponents.CHANNEL, + component=Microscopy.Channel, ) @@ -3779,8 +3780,8 @@ def test_non_dict_group_by_uses_dynamic_source_scope_for_pipeline_start(): source_snapshot = _resolved_step( is_function_step=True, func=lambda image: image, - group_by=GroupBy.CHANNEL, - variable_components=(VariableComponents.SITE,), + group_by=Microscopy.Channel, + variable_components=(Microscopy.Site,), name="source_loaded_channel_callable", source_bindings=EMPTY_SOURCE_BINDINGS, input_source=InputSource.PIPELINE_START, @@ -3792,7 +3793,7 @@ def test_non_dict_group_by_uses_dynamic_source_scope_for_pipeline_start(): ) assert source_scope == PathPlannerGroupScope.from_raw( (None,), - component=AllComponents.CHANNEL, + component=Microscopy.Channel, ) @@ -3804,8 +3805,8 @@ def test_dict_pattern_group_by_declares_execution_group_component(): "1": lambda image: image, "2": lambda image: image, }, - group_by=GroupBy.CHANNEL, - variable_components=(VariableComponents.SITE,), + group_by=Microscopy.Channel, + variable_components=(Microscopy.Site,), name="channel_dispatch", source_bindings=EMPTY_SOURCE_BINDINGS, ) @@ -3817,7 +3818,7 @@ def test_dict_pattern_group_by_declares_execution_group_component(): assert scope == PathPlannerGroupScope.from_raw( ("1", "2"), - component=AllComponents.CHANNEL, + component=Microscopy.Channel, ) @@ -3829,8 +3830,8 @@ def test_dict_pattern_rejects_group_by_none_execution_component(): "1": lambda image: image, "2": lambda image: image, }, - group_by=GroupBy.NONE, - variable_components=(VariableComponents.CHANNEL,), + group_by=Ungrouped, + variable_components=(Microscopy.Channel,), name="channel_dispatch", source_bindings=EMPTY_SOURCE_BINDINGS, ) @@ -3851,14 +3852,14 @@ def test_execution_groups_reject_grouped_group_by_axis_conflict(): composite_snapshot = _resolved_step( is_function_step=True, func={"1": lambda image: image}, - group_by=GroupBy.CHANNEL, - variable_components=(VariableComponents.CHANNEL,), + group_by=Microscopy.Channel, + variable_components=(Microscopy.Channel,), name="channel_dispatch", source_bindings=EMPTY_SOURCE_BINDINGS, ) with pytest.raises( ValueError, - match="channel_dispatch.*group_by=CHANNEL cannot also appear", + match="channel_dispatch.*group_by=channel cannot also appear", ): planner.execution_groups.get_execution_groups( composite_snapshot, @@ -3870,18 +3871,18 @@ def test_non_dict_group_by_preserves_explicitly_collapsed_input_axis(): planner = _artifact_planner_stub() input_scopes = PathPlannerComponentScopes( { - VariableComponents.CHANNEL: PathPlannerGroupScope.ungrouped(), - VariableComponents.SITE: PathPlannerGroupScope.from_raw( + Microscopy.Channel: PathPlannerGroupScope.ungrouped(), + Microscopy.Site: PathPlannerGroupScope.from_raw( ("1", "2"), - component=AllComponents.SITE, + component=Microscopy.Site, ), } ) snapshot = _resolved_step( is_function_step=True, func=lambda image: image, - group_by=GroupBy.CHANNEL, - variable_components=(VariableComponents.SITE,), + group_by=Microscopy.Channel, + variable_components=(Microscopy.Site,), name="measure_channel_named_artifacts_over_site_stack", source_bindings=EMPTY_SOURCE_BINDINGS, input_source=InputSource.PREVIOUS_STEP, @@ -3926,23 +3927,23 @@ def measurement_only(image, *, runtime): ) input_scopes = PathPlannerComponentScopes( { - VariableComponents.CHANNEL: PathPlannerGroupScope.from_raw( + Microscopy.Channel: PathPlannerGroupScope.from_raw( ("1",), - component=AllComponents.CHANNEL, + component=Microscopy.Channel, ), - VariableComponents.SITE: PathPlannerGroupScope.ungrouped(), + Microscopy.Site: PathPlannerGroupScope.ungrouped(), } ) snapshot = _resolved_step( is_function_step=True, - variable_components=(VariableComponents.CHANNEL,), - group_by=GroupBy.SITE, + variable_components=(Microscopy.Channel,), + group_by=Microscopy.Site, name="measurement_only", ) output_scopes = input_scopes.output_after( snapshot, - PathPlannerGroupScope.dynamic(AllComponents.SITE), + PathPlannerGroupScope.dynamic(Microscopy.Site), pattern, ) @@ -3977,29 +3978,29 @@ def image_output(image): ) input_scopes = PathPlannerComponentScopes( { - VariableComponents.CHANNEL: PathPlannerGroupScope.from_raw( + Microscopy.Channel: PathPlannerGroupScope.from_raw( ("1",), - component=AllComponents.CHANNEL, + component=Microscopy.Channel, ), - VariableComponents.SITE: PathPlannerGroupScope.ungrouped(), + Microscopy.Site: PathPlannerGroupScope.ungrouped(), } ) snapshot = _resolved_step( is_function_step=True, - variable_components=(VariableComponents.CHANNEL,), - group_by=GroupBy.SITE, + variable_components=(Microscopy.Channel,), + group_by=Microscopy.Site, name="image_output", ) output_scopes = input_scopes.output_after( snapshot, - PathPlannerGroupScope.dynamic(AllComponents.SITE), + PathPlannerGroupScope.dynamic(Microscopy.Site), pattern, ) assert output_scopes == PathPlannerComponentScopes( { - VariableComponents.SITE: PathPlannerGroupScope.dynamic(AllComponents.SITE), + Microscopy.Site: PathPlannerGroupScope.dynamic(Microscopy.Site), } ) @@ -4021,8 +4022,8 @@ def test_non_dict_group_by_namespaces_artifact_outputs_with_dynamic_component(): snapshot = _resolved_step( is_function_step=True, func=lambda image: image, - group_by=GroupBy.CHANNEL, - variable_components=(VariableComponents.SITE,), + group_by=Microscopy.Channel, + variable_components=(Microscopy.Site,), name="single_callable_channel_artifacts", source_bindings=EMPTY_SOURCE_BINDINGS, input_source=InputSource.PREVIOUS_STEP, @@ -4034,7 +4035,7 @@ def test_non_dict_group_by_namespaces_artifact_outputs_with_dynamic_component(): declarations, PathPlannerGroupScope.from_raw( (None,), - component=AllComponents.CHANNEL, + component=Microscopy.Channel, ), ) @@ -4042,7 +4043,7 @@ def test_non_dict_group_by_namespaces_artifact_outputs_with_dynamic_component(): ArtifactSpec.output("segmentation_masks", ObjectLabelsArtifactType).ref() ] assert output_plan.group_keys == (None,) - assert output_plan.group_component is AllComponents.CHANNEL + assert output_plan.group_component is Microscopy.Channel def test_non_dict_group_by_uses_source_binding_identity_for_pipeline_start_scope(): @@ -4050,19 +4051,19 @@ def test_non_dict_group_by_uses_source_binding_identity_for_pipeline_start_scope snapshot = _resolved_step( is_function_step=True, func=lambda image: image, - group_by=GroupBy.CHANNEL, - variable_components=(VariableComponents.SITE,), + group_by=Microscopy.Channel, + variable_components=(Microscopy.Site,), name="source_bound_channel_groups", source_bindings=StepSourceBindingsConfig( enabled=True, bindings=( NamedSourceBinding( alias="OrigStain1", - component_identity=(ComponentSelector(AllComponents.CHANNEL, "1"),), + component_identity=(ComponentSelector(Microscopy.Channel, "1"),), ), NamedSourceBinding( alias="OrigStain2", - component_identity=(ComponentSelector(AllComponents.CHANNEL, "2"),), + component_identity=(ComponentSelector(Microscopy.Channel, "2"),), ), ), ), @@ -4076,7 +4077,7 @@ def test_non_dict_group_by_uses_source_binding_identity_for_pipeline_start_scope assert scope == PathPlannerGroupScope.from_raw( ("1", "2"), - component=AllComponents.CHANNEL, + component=Microscopy.Channel, ) @@ -4099,7 +4100,7 @@ def save_declared_payload(image): bindings = [ NamedSourceBinding( alias=prefix.name, - component_identity=(ComponentSelector(AllComponents.CHANNEL, "1"),), + component_identity=(ComponentSelector(Microscopy.Channel, "1"),), ) ] if stored_payload: @@ -4110,21 +4111,21 @@ def save_declared_payload(image): path="/memory/composed.pkl", artifact_type=payload.artifact_type, group_keys=("1", "2", "3"), - group_component=AllComponents.SITE, + group_component=Microscopy.Site, ), ) else: bindings.append( NamedSourceBinding( alias=payload.name, - component_identity=(ComponentSelector(AllComponents.CHANNEL, "3"),), + component_identity=(ComponentSelector(Microscopy.Channel, "3"),), ) ) snapshot = _resolved_step( is_function_step=True, func=save_declared_payload, - group_by=GroupBy.CHANNEL, - variable_components=(VariableComponents.SITE,), + group_by=Microscopy.Channel, + variable_components=(Microscopy.Site,), source_bindings=StepSourceBindingsConfig( enabled=True, bindings=tuple(bindings) ), @@ -4138,9 +4139,9 @@ def save_declared_payload(image): ) expected = ( - PathPlannerGroupScope.dynamic(AllComponents.CHANNEL) + PathPlannerGroupScope.dynamic(Microscopy.Channel) if stored_payload - else PathPlannerGroupScope.from_raw(("3",), component=AllComponents.CHANNEL) + else PathPlannerGroupScope.from_raw(("3",), component=Microscopy.Channel) ) assert scope == expected assert not scope.contains_runtime_key("1") or scope.is_dynamic @@ -4153,11 +4154,11 @@ def test_main_flow_source_anchor_restricts_execution_to_its_exact_channel(): bindings=( NamedSourceBinding( alias="BF_image", - component_identity=(ComponentSelector(AllComponents.CHANNEL, "1"),), + component_identity=(ComponentSelector(Microscopy.Channel, "1"),), ), NamedSourceBinding( alias="DF_image", - component_identity=(ComponentSelector(AllComponents.CHANNEL, "2"),), + component_identity=(ComponentSelector(Microscopy.Channel, "2"),), projection_role=SourceProjectionRole.SOURCE_ARTIFACT, ), ), @@ -4165,8 +4166,8 @@ def test_main_flow_source_anchor_restricts_execution_to_its_exact_channel(): snapshot = _resolved_step( is_function_step=True, func=lambda image: image, - group_by=GroupBy.CHANNEL, - variable_components=(VariableComponents.SITE,), + group_by=Microscopy.Channel, + variable_components=(Microscopy.Site,), name="bf_source_consumer", source_bindings=source_bindings, input_source=InputSource.PIPELINE_START, @@ -4211,7 +4212,7 @@ def test_main_flow_source_anchor_restricts_execution_to_its_exact_channel(): ) assert scope == PathPlannerGroupScope.from_raw( ("1",), - component=AllComponents.CHANNEL, + component=Microscopy.Channel, ) @@ -4240,8 +4241,8 @@ def measure(image, CropBlue): path="/memory/CropBlue.pkl", artifact_type=source.artifact_type, group_keys=("1", "2"), - group_component=AllComponents.CHANNEL, - variable_components=(AllComponents.SITE,), + group_component=Microscopy.Channel, + variable_components=(Microscopy.Site,), paths_by_group={ "1": "/memory/CropBlue_channel_1.pkl", "2": "/memory/CropBlue_channel_2.pkl", @@ -4253,12 +4254,12 @@ def measure(image, CropBlue): snapshot = _resolved_step( name="Measure", func=measure, - group_by=GroupBy.SITE, - variable_components=(VariableComponents.CHANNEL,), + group_by=Microscopy.Site, + variable_components=(Microscopy.Channel,), ) execution_scope = PathPlannerGroupScope.from_raw( ("1", "2", "3"), - component=AllComponents.SITE, + component=Microscopy.Site, ) declarations = extract_artifact_declarations(measure) @@ -4284,7 +4285,7 @@ def measure(image, CropBlue): assert maps.inputs[source.ref()].producer_group_scope() == ( ComponentGroupScope.from_raw( ("1", "2"), - component=AllComponents.CHANNEL, + component=Microscopy.Channel, ) ) assert PathPlannerGroupScope.from_output_plan(maps.outputs[measurements.ref()]) == ( @@ -4292,7 +4293,7 @@ def measure(image, CropBlue): ) edge = next(compiled.iter_invocations()).artifact_input_edges[0] assert edge.projection.invocation_scope == ComponentGroupScope.dynamic( - AllComponents.SITE + Microscopy.Site ) assert edge.projection.producer_selection_scope == ( maps.inputs[source.ref()].producer_group_scope() @@ -4319,11 +4320,11 @@ def test_execution_anchor_ignores_source_artifact_lineage(): bindings=( NamedSourceBinding( alias="OrigBlue", - component_identity=(ComponentSelector(AllComponents.CHANNEL, "1"),), + component_identity=(ComponentSelector(Microscopy.Channel, "1"),), ), NamedSourceBinding( alias="OrigRed", - component_identity=(ComponentSelector(AllComponents.CHANNEL, "3"),), + component_identity=(ComponentSelector(Microscopy.Channel, "3"),), projection_role=SourceProjectionRole.SOURCE_ARTIFACT, ), ), @@ -4380,7 +4381,7 @@ def test_runtime_artifact_input_plan_owns_relation_source_scope(): bindings=( NamedSourceBinding( alias="OrigRed", - component_identity=(ComponentSelector(AllComponents.CHANNEL, "3"),), + component_identity=(ComponentSelector(Microscopy.Channel, "3"),), ), ), ) @@ -4389,7 +4390,7 @@ def test_runtime_artifact_input_plan_owns_relation_source_scope(): path="/memory/RGBImage.pkl", artifact_type=ImageArtifactType, group_keys=("1", "2", "3"), - group_component=AllComponents.SITE, + group_component=Microscopy.Site, paths_by_group={ "1": "/memory/RGBImage_site_1.pkl", "2": "/memory/RGBImage_site_2.pkl", @@ -4410,15 +4411,15 @@ def test_runtime_artifact_input_plan_owns_relation_source_scope(): {artifact_input.ref(): artifact_input}, group_scope=PathPlannerGroupScope.from_raw( ("3",), - component=AllComponents.CHANNEL, + component=Microscopy.Channel, ), source_bindings=source_bindings, - group_by=GroupBy.CHANNEL, + group_by=Microscopy.Channel, ) assert relation_scopes[rgb_image.ref()] == PathPlannerGroupScope.from_raw( ("1", "2", "3"), - component=AllComponents.SITE, + component=Microscopy.Site, ) @@ -4583,19 +4584,19 @@ def test_non_dict_group_by_ignores_source_binding_identity_for_other_components( snapshot = _resolved_step( is_function_step=True, func=lambda image: image, - group_by=GroupBy.SITE, - variable_components=(VariableComponents.CHANNEL,), + group_by=Microscopy.Site, + variable_components=(Microscopy.Channel,), name="source_bound_site_groups", source_bindings=StepSourceBindingsConfig( enabled=True, bindings=( NamedSourceBinding( alias="OrigStain1", - component_identity=(ComponentSelector(AllComponents.CHANNEL, "1"),), + component_identity=(ComponentSelector(Microscopy.Channel, "1"),), ), NamedSourceBinding( alias="OrigStain2", - component_identity=(ComponentSelector(AllComponents.CHANNEL, "2"),), + component_identity=(ComponentSelector(Microscopy.Channel, "2"),), ), ), ), @@ -4609,26 +4610,26 @@ def test_non_dict_group_by_ignores_source_binding_identity_for_other_components( assert scope == PathPlannerGroupScope.from_raw( (None,), - component=AllComponents.SITE, + component=Microscopy.Site, ) def test_compiled_group_by_preserves_dynamic_execution_scope(): planner = _artifact_planner_stub() planner.cfg = PathConfigStub(sub_dir="images", output_dir_suffix="_generated") - planner.plans[3].group_by = GroupBy.CHANNEL - planner.plans[3].variable_components = (VariableComponents.SITE,) + planner.plans[3].group_by = Microscopy.Channel + planner.plans[3].variable_components = (Microscopy.Site,) snapshot = _resolved_step( is_function_step=True, func=lambda image: image, - group_by=GroupBy.CHANNEL, - variable_components=(VariableComponents.SITE,), + group_by=Microscopy.Channel, + variable_components=(Microscopy.Site,), name="measure_after_channel_collapse", input_source=InputSource.PREVIOUS_STEP, ) artifact_maps = ArtifactPlanMaps( declarations=ArtifactGraph.empty(), - group_scope=PathPlannerGroupScope.dynamic(AllComponents.CHANNEL), + group_scope=PathPlannerGroupScope.dynamic(Microscopy.Channel), inputs={}, outputs={}, relation_source_scopes={}, @@ -4649,9 +4650,9 @@ def test_compiled_group_by_preserves_dynamic_execution_scope(): None, ) - assert planner.plans[3].group_by is GroupBy.CHANNEL + assert planner.plans[3].group_by is Microscopy.Channel assert planner.plans[3].execution_group_scope == PathPlannerGroupScope.dynamic( - AllComponents.CHANNEL + Microscopy.Channel ) assert planner.plans[3].analysis_results_dir == "/data/plate1_generated/analysis" @@ -4802,7 +4803,7 @@ def test_artifact_input_plan_preserves_single_grouped_producer_scope(): path="/memory/illumination.pkl", artifact_type=ImageArtifactType, group_keys=("1",), - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, paths_by_group={"1": "/memory/illumination_channel_1.pkl"}, producer_step_index=1, producer_step_name="calculate_illumination", @@ -4820,7 +4821,7 @@ def test_artifact_input_plan_preserves_single_grouped_producer_scope(): ), consumer_scope=PathPlannerGroupScope.from_raw( ("2", "3"), - component=AllComponents.SITE, + component=Microscopy.Site, ), sid=2, step_name="apply_illumination", @@ -4832,7 +4833,7 @@ def test_artifact_input_plan_preserves_single_grouped_producer_scope(): illumination_ref = ArtifactSpec.input("illumination", ImageArtifactType).ref() plan = inputs[illumination_ref] assert plan.group_keys == ("1",) - assert plan.group_component is AllComponents.CHANNEL + assert plan.group_component is Microscopy.Channel assert plan.path == "/memory/illumination_channel_1.pkl" assert plan.paths_by_group == {"1": "/memory/illumination_channel_1.pkl"} @@ -4842,28 +4843,28 @@ def test_artifact_input_plan_preserves_single_grouped_producer_scope(): ( (PathPlannerGroupScope.ungrouped(), PathPlannerGroupScope.ungrouped(), True), ( - PathPlannerGroupScope.dynamic(AllComponents.CHANNEL), - PathPlannerGroupScope.dynamic(AllComponents.CHANNEL), + PathPlannerGroupScope.dynamic(Microscopy.Channel), + PathPlannerGroupScope.dynamic(Microscopy.Channel), True, ), ( - PathPlannerGroupScope.dynamic(AllComponents.CHANNEL), - PathPlannerGroupScope.from_raw(("1",), component=AllComponents.CHANNEL), + PathPlannerGroupScope.dynamic(Microscopy.Channel), + PathPlannerGroupScope.from_raw(("1",), component=Microscopy.Channel), True, ), ( - PathPlannerGroupScope.from_raw(("1", "2"), component=AllComponents.CHANNEL), - PathPlannerGroupScope.from_raw(("2",), component=AllComponents.CHANNEL), + PathPlannerGroupScope.from_raw(("1", "2"), component=Microscopy.Channel), + PathPlannerGroupScope.from_raw(("2",), component=Microscopy.Channel), True, ), ( - PathPlannerGroupScope.from_raw(("1",), component=AllComponents.CHANNEL), - PathPlannerGroupScope.dynamic(AllComponents.CHANNEL), + PathPlannerGroupScope.from_raw(("1",), component=Microscopy.Channel), + PathPlannerGroupScope.dynamic(Microscopy.Channel), False, ), ( - PathPlannerGroupScope.dynamic(AllComponents.CHANNEL), - PathPlannerGroupScope.dynamic(AllComponents.SITE), + PathPlannerGroupScope.dynamic(Microscopy.Channel), + PathPlannerGroupScope.dynamic(Microscopy.Site), False, ), ), @@ -4879,7 +4880,7 @@ def test_component_group_scope_contains_exact_required_scope( def test_component_group_scope_selects_runtime_key_from_static_domain(): scope = ComponentGroupScope.from_raw( ("1", "2"), - component=AllComponents.CHANNEL, + component=Microscopy.Channel, ) assert scope.select_runtime_key("2") == "2" @@ -4903,7 +4904,7 @@ def consume(main_image, image): path="/memory/image.pkl", artifact_type=ImageArtifactType, group_keys=("1", "2"), - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, paths_by_group={ "1": "/memory/image_channel_1.pkl", "2": "/memory/image_channel_2.pkl", @@ -4926,8 +4927,8 @@ def consume(main_image, image): snapshot = _resolved_step( name="consumer", func=consume, - group_by=GroupBy.NONE, - variable_components=(VariableComponents.SITE,), + group_by=Ungrouped, + variable_components=(Microscopy.Site,), ) maps = planner.artifacts.compile_plan_maps( snapshot, @@ -4966,7 +4967,7 @@ def consume(main_image, image): path="/memory/image_channel_2.pkl", artifact_type=ImageArtifactType, group_keys=("2",), - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, paths_by_group={"2": "/memory/image_channel_2.pkl"}, producer_step_index=1, producer_step_name="producer", @@ -4986,8 +4987,8 @@ def consume(main_image, image): snapshot = _resolved_step( name="consumer", func=consume, - group_by=GroupBy.NONE, - variable_components=(VariableComponents.SITE,), + group_by=Ungrouped, + variable_components=(Microscopy.Site,), ) maps = planner.artifacts.compile_plan_maps( snapshot, @@ -4998,7 +4999,7 @@ def consume(main_image, image): producer_scope = maps.inputs[input_spec.ref()].producer_group_scope() assert producer_scope.keys == ("2",) - assert producer_scope.component is AllComponents.CHANNEL + assert producer_scope.component is Microscopy.Channel compiled = planner.artifacts.build_step_compiled_function_pattern( snapshot, 3, @@ -5033,7 +5034,7 @@ def consume(main_image, relationships): path="/memory/relationships_channel_2.pkl", artifact_type=RelationshipsArtifactType, group_keys=("2",), - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, paths_by_group={"2": "/memory/relationships_channel_2.pkl"}, ) compiled = compile_function_pattern( @@ -5048,11 +5049,11 @@ def consume(main_image, relationships): input_spec.ref(): input_plan.producer_group_scope(), owner_spec.ref(): PathPlannerGroupScope.from_raw( ("2",), - component=AllComponents.CHANNEL, + component=Microscopy.Channel, ), }, execution_group_scope=PathPlannerGroupScope.ungrouped(), - consumer_variable_components=ComponentSet((AllComponents.SITE,)), + consumer_variable_components=ComponentSet((Microscopy.Site,)), ) edge = next(compiled.iter_invocations()).artifact_input_edges[0] assert edge.projection.invocation_scope.is_ungrouped @@ -5075,7 +5076,7 @@ def test_realized_source_scopes_compile_cross_group_artifact_consumption(): ) broad_channel_scope = PathPlannerGroupScope.from_raw( ("1", "2"), - component=AllComponents.CHANNEL, + component=Microscopy.Channel, ) def compile_source_producer( @@ -5126,7 +5127,7 @@ def produce(image, source_value): assert maps.group_scope == PathPlannerGroupScope.from_raw( (expected_group,), - component=AllComponents.CHANNEL, + component=Microscopy.Channel, ) return output @@ -5173,12 +5174,12 @@ def consume(image, Nuclei, PH3): artifact_inputs=maps.inputs, relation_source_scopes=maps.relation_source_scopes, execution_group_scope=maps.group_scope, - consumer_variable_components=ComponentSet((AllComponents.SITE,)), + consumer_variable_components=ComponentSet((Microscopy.Site,)), ) assert maps.group_scope == PathPlannerGroupScope.from_raw( ("1", "2"), - component=AllComponents.CHANNEL, + component=Microscopy.Channel, ) edges = { edge.spec.name: edge @@ -5206,7 +5207,7 @@ def consume(main_image, image, site_source): path="/memory/image.pkl", artifact_type=ImageArtifactType, group_keys=("1", "2"), - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, paths_by_group={ "1": "/memory/image_channel_1.pkl", "2": "/memory/image_channel_2.pkl", @@ -5217,7 +5218,7 @@ def consume(main_image, image, site_source): path="/memory/site_source.pkl", artifact_type=ImageArtifactType, group_keys=("1",), - group_component=AllComponents.SITE, + group_component=Microscopy.Site, paths_by_group={"1": "/memory/site_source_1.pkl"}, ) input_plans = { @@ -5236,7 +5237,7 @@ def consume(main_image, image, site_source): source_spec.ref(): source_plan.producer_group_scope(), }, execution_group_scope=PathPlannerGroupScope.ungrouped(), - consumer_variable_components=ComponentSet((AllComponents.SITE,)), + consumer_variable_components=ComponentSet((Microscopy.Site,)), ) @@ -5247,8 +5248,8 @@ def test_artifact_plan_rejects_group_component_as_variable_axis(): path="/memory/objects.pkl", artifact_type=ObjectLabelsArtifactType, group_keys=(None,), - group_component=AllComponents.SITE, - variable_components=(AllComponents.SITE,), + group_component=Microscopy.Site, + variable_components=(Microscopy.Site,), ) @@ -5261,7 +5262,7 @@ def test_artifact_input_plan_preserves_multi_grouped_producer_across_components( path="/memory/illumination_channel_1.pkl", artifact_type=ImageArtifactType, group_keys=("1", "2"), - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, paths_by_group={ "1": "/memory/illumination_channel_1.pkl", "2": "/memory/illumination_channel_2.pkl", @@ -5282,7 +5283,7 @@ def test_artifact_input_plan_preserves_multi_grouped_producer_across_components( ), consumer_scope=PathPlannerGroupScope.from_raw( ("1", "2"), - component=AllComponents.SITE, + component=Microscopy.Site, ), sid=2, step_name="apply_illumination", @@ -5294,7 +5295,7 @@ def test_artifact_input_plan_preserves_multi_grouped_producer_across_components( illumination_ref = ArtifactSpec.input("illumination", ImageArtifactType).ref() plan = inputs[illumination_ref] assert plan.group_keys == ("1", "2") - assert plan.group_component is AllComponents.CHANNEL + assert plan.group_component is Microscopy.Channel assert plan.paths_by_group == { "1": "/memory/illumination_channel_1.pkl", "2": "/memory/illumination_channel_2.pkl", @@ -5319,8 +5320,8 @@ def apply(image, illumination): path="/memory/illumination_channel_1.pkl", artifact_type=ImageArtifactType, group_keys=("1", "2"), - group_component=AllComponents.CHANNEL, - variable_components=(AllComponents.SITE,), + group_component=Microscopy.Channel, + variable_components=(Microscopy.Site,), paths_by_group={ "1": "/memory/illumination_channel_1.pkl", "2": "/memory/illumination_channel_2.pkl", @@ -5345,10 +5346,10 @@ def apply(image, illumination): artifact_inputs={input_plan.ref(): input_plan}, relation_source_scopes={ illumination_spec.ref(): input_plan.producer_group_scope(), - source_spec.ref(): PathPlannerGroupScope.dynamic(AllComponents.SITE), + source_spec.ref(): PathPlannerGroupScope.dynamic(Microscopy.Site), }, - execution_group_scope=PathPlannerGroupScope.dynamic(AllComponents.SITE), - consumer_variable_components=ComponentSet((AllComponents.CHANNEL,)), + execution_group_scope=PathPlannerGroupScope.dynamic(Microscopy.Site), + consumer_variable_components=ComponentSet((Microscopy.Channel,)), source_bindings=source_bindings, available_artifacts=ArtifactSpecCollection((source_spec, illumination_spec)), ) @@ -5359,10 +5360,10 @@ def apply(image, illumination): edge.storage_plan.producer_group_scope() ) assert edge.projection.invocation_scope == ComponentGroupScope.dynamic( - AllComponents.SITE + Microscopy.Site ) - assert edge.projection.component_scope(AllComponents.SITE) == ( - ComponentGroupScope.dynamic(AllComponents.SITE) + assert edge.projection.component_scope(Microscopy.Site) == ( + ComponentGroupScope.dynamic(Microscopy.Site) ) @@ -5384,18 +5385,18 @@ def apply_second(image): path="/memory/IllumStain1.pkl", artifact_type=ImageArtifactType, group_keys=("1",), - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, ) second = ArtifactInputPlan( name="IllumStain2", path="/memory/IllumStain2.pkl", artifact_type=ImageArtifactType, group_keys=("2",), - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, ) execution_scope = PathPlannerGroupScope.from_raw( ("1", "2"), - component=AllComponents.CHANNEL, + component=Microscopy.Channel, ) storage = {first.ref(): first, second.ref(): second} compiled = compile_function_pattern( @@ -5411,7 +5412,7 @@ def apply_second(image): second_spec.ref(): second.producer_group_scope(), }, execution_group_scope=execution_scope, - consumer_variable_components=ComponentSet((AllComponents.SITE,)), + consumer_variable_components=ComponentSet((Microscopy.Site,)), ) execution_plan = CompiledStepPlan( step_index=2, @@ -5443,13 +5444,13 @@ def apply_second(image): assert first_edge.projection.invocation_scope == ( ComponentGroupScope.from_raw( ("1",), - component=AllComponents.CHANNEL, + component=Microscopy.Channel, ) ) assert second_edge.projection.invocation_scope == ( ComponentGroupScope.from_raw( ("2",), - component=AllComponents.CHANNEL, + component=Microscopy.Channel, ) ) @@ -5467,15 +5468,15 @@ def consume(image, Objects1): path="/memory/Objects1.pkl", artifact_type=input_spec.artifact_type, group_keys=("1",), - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, ) invocation_scope = PathPlannerGroupScope.from_raw( ("1",), - component=AllComponents.CHANNEL, + component=Microscopy.Channel, ) producer_domain = PathPlannerGroupScope.from_raw( ("3",), - component=AllComponents.CHANNEL, + component=Microscopy.Channel, ) invocation = next( compile_function_pattern( @@ -5519,11 +5520,11 @@ def consume(image, Nuclei): ) producer_channel = PathPlannerGroupScope.from_raw( ("1",), - component=AllComponents.CHANNEL, + component=Microscopy.Channel, ) consumer_channel = PathPlannerGroupScope.from_raw( ("2",), - component=AllComponents.CHANNEL, + component=Microscopy.Channel, ) component_scopes = PathPlannerArtifactStage.exact_component_scopes( @@ -5560,11 +5561,11 @@ def consume(image, Objects): ) producer_domain = PathPlannerGroupScope.from_raw( ("1", "2"), - component=AllComponents.CHANNEL, + component=Microscopy.Channel, ) selected_channel = PathPlannerGroupScope.from_raw( ("2",), - component=AllComponents.CHANNEL, + component=Microscopy.Channel, ) component_scopes = PathPlannerArtifactStage.exact_component_scopes( @@ -5597,7 +5598,7 @@ def relate_objects(image, Cells): path="/memory/Cells.pkl", artifact_type=consumed.artifact_type, group_keys=("3",), - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, source_step_id=4, ) compiled = compile_function_pattern( @@ -5610,7 +5611,7 @@ def relate_objects(image, Cells): bindings=( NamedSourceBinding( alias=source.name, - component_identity=(ComponentSelector(AllComponents.CHANNEL, "5"),), + component_identity=(ComponentSelector(Microscopy.Channel, "5"),), ), ), ) @@ -5621,16 +5622,16 @@ def relate_objects(image, Cells): relation_source_scopes={source.ref(): input_plan.producer_group_scope()}, execution_group_scope=PathPlannerGroupScope.from_raw( ("5",), - component=AllComponents.CHANNEL, + component=Microscopy.Channel, ), - consumer_variable_components=ComponentSet((AllComponents.SITE,)), + consumer_variable_components=ComponentSet((Microscopy.Site,)), source_bindings=source_bindings, available_artifacts=ArtifactSpecCollection((source, consumed)), ) edge = next(compiled.iter_invocations()).artifact_input_edges[0] - assert edge.projection.component_scope(AllComponents.CHANNEL) == ( - ComponentGroupScope.from_raw(("3",), component=AllComponents.CHANNEL) + assert edge.projection.component_scope(Microscopy.Channel) == ( + ComponentGroupScope.from_raw(("3",), component=Microscopy.Channel) ) @@ -5647,9 +5648,9 @@ def assemble(image, positions): path="/memory/positions.pkl", artifact_type=SpecialArtifactType, group_keys=(None,), - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, ) - execution_scope = PathPlannerGroupScope.dynamic(AllComponents.CHANNEL) + execution_scope = PathPlannerGroupScope.dynamic(Microscopy.Channel) compiled = compile_function_pattern( assemble, {plan.ref(): plan for plan in (input_plan,)}, @@ -5663,11 +5664,11 @@ def assemble(image, positions): input_spec.ref(): input_plan.producer_group_scope(), }, execution_group_scope=execution_scope, - consumer_variable_components=ComponentSet((AllComponents.SITE,)), + consumer_variable_components=ComponentSet((Microscopy.Site,)), ) edge = next(compiled.iter_invocations()).artifact_input_edges[0] - expected_scope = ComponentGroupScope.dynamic(AllComponents.CHANNEL) + expected_scope = ComponentGroupScope.dynamic(Microscopy.Channel) assert edge.projection.invocation_scope == expected_scope assert edge.projection.producer_selection_scope == expected_scope @@ -5690,7 +5691,7 @@ def crop_red(image): path="/memory/crop_mask.pkl", artifact_type=ImageArtifactType, group_keys=("2", "3"), - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, paths_by_group={ "2": "/memory/crop_mask_2.pkl", "3": "/memory/crop_mask_3.pkl", @@ -5709,9 +5710,9 @@ def crop_red(image): }, execution_group_scope=PathPlannerGroupScope.from_raw( ("2", "3"), - component=AllComponents.CHANNEL, + component=Microscopy.Channel, ), - consumer_variable_components=ComponentSet((AllComponents.SITE,)), + consumer_variable_components=ComponentSet((Microscopy.Site,)), ) edges = compiled.artifact_input_edges_by_key() diff --git a/tests/unit/test_persisted_image_metadata.py b/tests/unit/test_persisted_image_metadata.py index b902fdb003..832269f9c9 100644 --- a/tests/unit/test_persisted_image_metadata.py +++ b/tests/unit/test_persisted_image_metadata.py @@ -43,6 +43,7 @@ ) from openhcs.microscopes.source_schema import SourceSchemaFilenameParser from python_introspect import to_jsonable +from openhcs.domains.microscopy.axes import Microscopy def metadata_fixture(): @@ -176,7 +177,7 @@ def test_atomic_perwell_projection_merge_preserves_all_records(tmp_path): def merge(well): virtual_path = f"{well}.tif" projection = SourcePlaneProjection( - OpenHCSPlaneAddress.from_values(well, 1, 1, 1, 1), + OpenHCSPlaneAddress(((Microscopy.Well, well), (Microscopy.Site, 1), (Microscopy.Channel, 1), (Microscopy.ZIndex, 1), (Microscopy.Timepoint, 1))), SourcePixelRef("disk", virtual_path), image_metadata=metadata_fixture(), ) @@ -202,7 +203,7 @@ def calibrated_projection(well, path, pixel_size): source_metadata = {} spacing.merge_into(source_metadata, path=path) return SourcePlaneProjection( - OpenHCSPlaneAddress.from_values(well, 1, 1, 1, 1), + OpenHCSPlaneAddress(((Microscopy.Well, well), (Microscopy.Site, 1), (Microscopy.Channel, 1), (Microscopy.ZIndex, 1), (Microscopy.Timepoint, 1))), SourcePixelRef("disk", path), source_metadata=source_metadata, image_metadata=metadata_fixture().replace_fields(source_voxel_spacing=spacing), diff --git a/tests/unit/test_persisted_roi_only_publication.py b/tests/unit/test_persisted_roi_only_publication.py index 68cc2685dc..f4a9c3e35e 100644 --- a/tests/unit/test_persisted_roi_only_publication.py +++ b/tests/unit/test_persisted_roi_only_publication.py @@ -43,6 +43,7 @@ prepare_materialization, ) from openhcs.processing.materialization.options import FileBundleOptions +from openhcs.domains.microscopy.axes import Microscopy def _publish_saved_step(context, plan, *, artifact_materializations=()): @@ -308,7 +309,7 @@ def test_measurement_only_step_does_not_reconcile_pending_image_producer( virtual_path = str(pending.relative_to(plate)) projection = SourceArtifactProjection( - address=OpenHCSPlaneAddress.from_values("A04", 1, 2, 1, 1), + address=OpenHCSPlaneAddress(((Microscopy.Well, "A04"), (Microscopy.Site, 1), (Microscopy.Channel, 2), (Microscopy.ZIndex, 1), (Microscopy.Timepoint, 1))), ref=SourcePixelRef(Backend.DISK.value, virtual_path), source_alias="declared_image", artifact_kind=ImageArtifactType, ) @@ -342,9 +343,7 @@ def test_reconciliation_keeps_artifact_destination_without_results_field( plate = tmp_path / "plate" plate.mkdir() projection = SourceArtifactProjection( - address=OpenHCSPlaneAddress.from_values( - well="A01", site="1", channel="2", z_index="1", timepoint="1" - ), + address=OpenHCSPlaneAddress(((Microscopy.Well, "A01"), (Microscopy.Site, "1"), (Microscopy.Channel, "2"), (Microscopy.ZIndex, "1"), (Microscopy.Timepoint, "1"))), ref=SourcePixelRef(Backend.DISK.value, "physical/acquisition-source.tif"), source_alias="Declared", artifact_kind=MetadataArtifactType, diff --git a/tests/unit/test_persisted_semantic_metadata.py b/tests/unit/test_persisted_semantic_metadata.py index 673ddb0d78..82da9e2058 100644 --- a/tests/unit/test_persisted_semantic_metadata.py +++ b/tests/unit/test_persisted_semantic_metadata.py @@ -10,7 +10,6 @@ import pytest 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, @@ -36,6 +35,7 @@ from openhcs.core.virtual_workspace_metadata import VirtualWorkspaceSourceProjectionEntries from openhcs.microscopes.source_schema import SourceSchemaFilenameParser from python_introspect import to_jsonable +from openhcs.domains.microscopy.axes import Microscopy VIRTUAL_PATH = "A01_s001_w1_z001_t001.tif" @@ -63,7 +63,7 @@ def _projection( source_metadata: Mapping[str, object] | None = None, ) -> SourcePlaneProjection: return SourcePlaneProjection( - address=OpenHCSPlaneAddress.from_values("A01", 1, 1, 1, 1), + address=OpenHCSPlaneAddress(((Microscopy.Well, "A01"), (Microscopy.Site, 1), (Microscopy.Channel, 1), (Microscopy.ZIndex, 1), (Microscopy.Timepoint, 1))), ref=SourcePixelRef("disk", VIRTUAL_PATH), image_metadata=image_metadata, source_metadata={} if source_metadata is None else source_metadata, @@ -127,7 +127,7 @@ def test_source_projection_serialization_decodes_typed_image_metadata() -> None: VirtualWorkspacePathLookup.from_paths(VIRTUAL_PATH, VIRTUAL_PATH) ) - assert projection.address.value_for(AllComponents.SITE) == "1" + assert projection.address.value_for(Microscopy.Site) == "1" assert projection.image_metadata == _collapsed_metadata() @@ -165,7 +165,7 @@ def test_image_artifact_projection_round_trips_typed_pixel_metadata() -> None: source_dtype="uint8", ) projection = SourceArtifactProjection( - address=OpenHCSPlaneAddress.from_values("A01", 1, 2, 1, 1), + address=OpenHCSPlaneAddress(((Microscopy.Well, "A01"), (Microscopy.Site, 1), (Microscopy.Channel, 2), (Microscopy.ZIndex, 1), (Microscopy.Timepoint, 1))), ref=SourcePixelRef("disk", "analysis/A01_candidate.checkpoint.tif"), source_alias="neurite_candidate_mask", artifact_kind=ImageArtifactType, @@ -253,7 +253,7 @@ def test_site_collapsed_serialize_read_project_roundtrip_keeps_semantics() -> No assert ( workspace.require_source_projection_for( VirtualWorkspacePathLookup.from_paths(VIRTUAL_PATH, VIRTUAL_PATH) - ).address.value_for(AllComponents.SITE) + ).address.value_for(Microscopy.Site) == "1" ) diff --git a/tests/unit/test_plane_store_sources.py b/tests/unit/test_plane_store_sources.py index b3ccbf51ff..3f582ba7e5 100644 --- a/tests/unit/test_plane_store_sources.py +++ b/tests/unit/test_plane_store_sources.py @@ -21,7 +21,7 @@ ZarrBatchLayout, ) -from openhcs.constants.constants import AllComponents, Backend, OrchestratorState +from openhcs.constants.constants import Backend, OrchestratorState from openhcs.core.config import ( GlobalPipelineConfig, LazySourceBindingsConfig, @@ -49,6 +49,8 @@ from openhcs.microscopes.microscope_base import create_microscope_handler from openhcs.microscopes.openhcs import OpenHCSMicroscopeHandler from tests.ome_zarr_fixture import NGFF_FORMATS, write_ngff_plate +from openhcs.core.axes import AxisFamily +from openhcs.domains.microscopy.axes import Microscopy @pytest.mark.parametrize("fmt", NGFF_FORMATS, ids=lambda fmt: fmt.version) @@ -101,11 +103,11 @@ def test_ngff_axis_cardinalities_and_plane_pixels_survive_discovery( assert direct.identity == nested.identity assert direct.pixel_size == nested.pixel_size == 1.0 expected_components = { - AllComponents.WELL: {"A01"}, - AllComponents.SITE: {"1"}, - AllComponents.CHANNEL: {"1", "2"}, - AllComponents.Z_INDEX: {"1", "2", "3"}, - AllComponents.TIMEPOINT: {"1", "2"}, + Microscopy.Well: {"A01"}, + Microscopy.Site: {"1"}, + Microscopy.Channel: {"1", "2"}, + Microscopy.ZIndex: {"1", "2", "3"}, + Microscopy.Timepoint: {"1", "2"}, } for component, expected in expected_components.items(): assert { @@ -113,7 +115,7 @@ def test_ngff_axis_cardinalities_and_plane_pixels_survive_discovery( for candidate in nested.candidates } == expected assert { - candidate.component_labels[AllComponents.CHANNEL.value] + candidate.component_labels[Microscopy.Channel.name] for candidate in nested.candidates } == {"NGFF", "NGFF-2"} backend = OmeZarrStorageBackend() @@ -123,9 +125,9 @@ def test_ngff_axis_cardinalities_and_plane_pixels_survive_discovery( expected_indices = tuple( int(address.value_for(component)) - 1 for component in ( - AllComponents.TIMEPOINT, - AllComponents.CHANNEL, - AllComponents.Z_INDEX, + Microscopy.Timepoint, + Microscopy.Channel, + Microscopy.ZIndex, ) ) assert candidate.source_ref.source_axis_indices == expected_indices @@ -158,7 +160,7 @@ def test_legacy_polystore_namespace_does_not_override_declared_source_identity( assert dataset.identity.value == "Plate:mixed" assert len(dataset.candidates) == 1 candidate = dataset.candidates[0] - assert candidate.declared_address.value_for(AllComponents.WELL) == "A01" + assert candidate.declared_address.value_for(Microscopy.Well) == "A01" loaded = OmeZarrStorageBackend().load(candidate.source_ref.backend_address) np.testing.assert_array_equal(loaded[0, 0, 0], pixels) @@ -177,7 +179,7 @@ def test_ngff_image_can_be_submitted_without_its_plate( assert len(dataset.candidates) == 1 candidate = dataset.candidates[0] assert candidate.source_axis_shape == (1, 1, 1) - assert candidate.component_labels[AllComponents.CHANNEL.value] == "NGFF" + assert candidate.component_labels[Microscopy.Channel.name] == "NGFF" loaded = OmeZarrStorageBackend().load(candidate.source_ref.backend_address) np.testing.assert_array_equal(loaded[0, 0, 0], pixels) @@ -273,10 +275,10 @@ def test_polystore_zarr_semantic_coordinates_round_trip_through_store_discovery( assert { ( - candidate.declared_address.value_for(AllComponents.SITE), - candidate.declared_address.value_for(AllComponents.CHANNEL), - candidate.declared_address.value_for(AllComponents.Z_INDEX), - candidate.declared_address.value_for(AllComponents.TIMEPOINT), + candidate.declared_address.value_for(Microscopy.Site), + candidate.declared_address.value_for(Microscopy.Channel), + candidate.declared_address.value_for(Microscopy.ZIndex), + candidate.declared_address.value_for(Microscopy.Timepoint), ) for candidate in dataset.candidates } == { @@ -308,7 +310,7 @@ def test_mixed_plane_stores_bind_and_load_through_virtual_workspace( Backend.OME_ZARR.value, } assert { - candidate.declared_address.value_for(AllComponents.WELL) + candidate.declared_address.value_for(Microscopy.Well) for candidate in dataset.candidates } == { "A01", @@ -427,17 +429,17 @@ def reject_editor(*args, **kwargs): for path in projection.relative_virtual_paths() ) assert {record.source_alias for record in records} == set(edited_aliases.values()) - assert {record.address.value_for(AllComponents.WELL) for record in records} == { + assert {record.address.value_for(Microscopy.Well) for record in records} == { "A01", "mask.png", "plain.tif", } assert { ( - record.address.value_for(AllComponents.SITE), - record.address.value_for(AllComponents.CHANNEL), - record.address.value_for(AllComponents.Z_INDEX), - record.address.value_for(AllComponents.TIMEPOINT), + record.address.value_for(Microscopy.Site), + record.address.value_for(Microscopy.Channel), + record.address.value_for(Microscopy.ZIndex), + record.address.value_for(Microscopy.Timepoint), ) for record in records } == {("1", "1", "1", "1")} @@ -447,15 +449,15 @@ def reject_editor(*args, **kwargs): } assert len({record.ref.backend_address for record in records}) == len(records) expected_components = { - AllComponents.WELL: {"A01", "mask.png", "plain.tif"}, - AllComponents.SITE: {"1"}, - AllComponents.CHANNEL: {"1"}, - AllComponents.Z_INDEX: {"1"}, - AllComponents.TIMEPOINT: {"1"}, + Microscopy.Well: {"A01", "mask.png", "plain.tif"}, + Microscopy.Site: {"1"}, + Microscopy.Channel: {"1"}, + Microscopy.ZIndex: {"1"}, + Microscopy.Timepoint: {"1"}, } assert { component: set(orchestrator.get_component_keys(component)) - for component in AllComponents + for component in AxisFamily.active().axes } == expected_components @@ -505,7 +507,7 @@ def test_mixed_plane_stores_materialize_and_reopen_with_source_identity( Backend.ZARR.value, orchestrator.get_effective_config().zarr_config, context, - record.address.value_for(AllComponents.WELL), + record.address.value_for(Microscopy.Well), ) np.testing.assert_array_equal(payload, stores[alias][1]) diff --git a/tests/unit/test_primary_image_carrier_compile_gate.py b/tests/unit/test_primary_image_carrier_compile_gate.py index c1a6beaf7f..46bf411e2d 100644 --- a/tests/unit/test_primary_image_carrier_compile_gate.py +++ b/tests/unit/test_primary_image_carrier_compile_gate.py @@ -8,7 +8,6 @@ from polystore.filemanager import FileManager from polystore.virtual_workspace import SourcePixelRef -from openhcs.constants import AllComponents from openhcs.core.callable_contract import ( CallableContract, PrimaryImageCarrierTransition, @@ -40,6 +39,7 @@ from openhcs.core.step_dependencies import StepInputDependency from openhcs.processing.backends.cellprofiler.color import color_to_gray from openhcs.processing.backends.cellprofiler.crop import crop +from openhcs.domains.microscopy.axes import Microscopy class _CarrierTestSession(SimpleNamespace): @@ -119,13 +119,7 @@ def _session( ) projections = { path.name: SourcePlaneProjection( - address=OpenHCSPlaneAddress.from_values( - "A01", - index, - 1, - 1, - 1, - ), + address=OpenHCSPlaneAddress(((Microscopy.Well, "A01"), (Microscopy.Site, index), (Microscopy.Channel, 1), (Microscopy.ZIndex, 1), (Microscopy.Timepoint, 1))), ref=SourcePixelRef("disk", str(path)), source_alias=binding.alias, ) @@ -227,11 +221,11 @@ def test_grouped_color_requirement_inspects_only_compatible_binding( ) grayscale_binding = NamedSourceBinding( alias="gray", - component_identity=(ComponentSelector(AllComponents.CHANNEL, "1"),), + component_identity=(ComponentSelector(Microscopy.Channel, "1"),), ) rgb_binding = NamedSourceBinding( alias="rgb", - component_identity=(ComponentSelector(AllComponents.CHANNEL, "2"),), + component_identity=(ComponentSelector(Microscopy.Channel, "2"),), ) def identity(image): @@ -254,13 +248,7 @@ def identity(image): ) projections = { path.name: SourcePlaneProjection( - address=OpenHCSPlaneAddress.from_values( - "A01", - index, - binding.component_identity[0].value, - 1, - 1, - ), + address=OpenHCSPlaneAddress(((Microscopy.Well, "A01"), (Microscopy.Site, index), (Microscopy.Channel, binding.component_identity[0].value), (Microscopy.ZIndex, 1), (Microscopy.Timepoint, 1))), ref=SourcePixelRef("disk", str(path)), source_alias=binding.alias, ) @@ -291,7 +279,7 @@ def identity(image): ), execution_group_scope=ComponentGroupScope.from_raw( ("1", "2"), - component=AllComponents.CHANNEL, + component=Microscopy.Channel, ), compiled_function_pattern=pattern, ) @@ -609,11 +597,11 @@ def test_unknown_routed_group_cannot_fall_back_to_all_primary_sources( ) grayscale_binding = NamedSourceBinding( alias="gray", - component_identity=(ComponentSelector(AllComponents.CHANNEL, "1"),), + component_identity=(ComponentSelector(Microscopy.Channel, "1"),), ) rgb_binding = NamedSourceBinding( alias="rgb", - component_identity=(ComponentSelector(AllComponents.CHANNEL, "2"),), + component_identity=(ComponentSelector(Microscopy.Channel, "2"),), ) color_invocation = CompiledFunctionInvocation( key=FunctionInvocationKey("color_to_gray", "3", 0), @@ -625,12 +613,12 @@ def test_unknown_routed_group_cannot_fall_back_to_all_primary_sources( ) projections = { grayscale_path.name: SourcePlaneProjection( - address=OpenHCSPlaneAddress.from_values("A01", 1, 1, 1, 1), + address=OpenHCSPlaneAddress(((Microscopy.Well, "A01"), (Microscopy.Site, 1), (Microscopy.Channel, 1), (Microscopy.ZIndex, 1), (Microscopy.Timepoint, 1))), ref=SourcePixelRef("disk", str(grayscale_path)), source_alias=grayscale_binding.alias, ), rgb_path.name: SourcePlaneProjection( - address=OpenHCSPlaneAddress.from_values("A01", 2, 2, 1, 1), + address=OpenHCSPlaneAddress(((Microscopy.Well, "A01"), (Microscopy.Site, 2), (Microscopy.Channel, 2), (Microscopy.ZIndex, 1), (Microscopy.Timepoint, 1))), ref=SourcePixelRef("disk", str(rgb_path)), source_alias=rgb_binding.alias, ), @@ -654,7 +642,7 @@ def test_unknown_routed_group_cannot_fall_back_to_all_primary_sources( ), execution_group_scope=ComponentGroupScope.from_raw( ("1", "2"), - component=AllComponents.CHANNEL, + component=Microscopy.Channel, ), compiled_function_pattern=pattern, ) diff --git a/tests/unit/test_pycodify_formatters.py b/tests/unit/test_pycodify_formatters.py index 41fc1bb84a..df06174083 100644 --- a/tests/unit/test_pycodify_formatters.py +++ b/tests/unit/test_pycodify_formatters.py @@ -11,7 +11,6 @@ import openhcs.serialization.pycodify_formatters # noqa: F401 from openhcs.constants import InputSource -from openhcs.constants.constants import GroupBy from openhcs.core.callable_contract import CallableContract, CallableImportIdentity from openhcs.core.config import ( DtypeConfig, @@ -41,6 +40,7 @@ TerminalMaterializationSpec, WriteMode, ) +from openhcs.domains.microscopy.axes import Microscopy @pytest.fixture(autouse=True) @@ -210,7 +210,7 @@ def test_clean_function_step_keeps_nondefault_lazy_config_values(): step = FunctionStep( func=count_cells_simple, name="count_cells", - processing_config=LazyProcessingConfig(group_by=GroupBy.CHANNEL), + processing_config=LazyProcessingConfig(group_by=Microscopy.Channel), ) source = generate_python_source( @@ -219,7 +219,7 @@ def test_clean_function_step_keeps_nondefault_lazy_config_values(): ) assert "processing_config=LazyProcessingConfig(" in source - assert "group_by=GroupBy.CHANNEL" in source + assert "group_by=Microscopy.Channel" in source assert "dtype_config=" not in source diff --git a/tests/unit/test_resolved_pipeline_definition.py b/tests/unit/test_resolved_pipeline_definition.py index 5df7c4edd5..4624ffd700 100644 --- a/tests/unit/test_resolved_pipeline_definition.py +++ b/tests/unit/test_resolved_pipeline_definition.py @@ -1,7 +1,6 @@ from openhcs.core.pipeline.compilation_session import ResolvedPipelineDefinition import pytest -from openhcs.constants import VariableComponents from openhcs.constants.input_source import InputSource from openhcs.core.config import ProcessingConfig, StepMaterializationConfig from openhcs.core.source_bindings import ( @@ -12,6 +11,7 @@ ) from openhcs.core.steps.function_step import FunctionStep from openhcs.core.function_patterns import normalize_function_pattern +from openhcs.domains.microscopy.axes import Microscopy def _identity(image): @@ -24,7 +24,7 @@ def test_resolved_pipeline_reads_steps_without_object_conversion(): NamedSourceBinding( alias="OrigBlue", selector=SourceSelector( - components=(ComponentSelector("channel", "1"),) + components=(ComponentSelector(Microscopy.Channel, "1"),) ), ), ) @@ -34,7 +34,7 @@ def test_resolved_pipeline_reads_steps_without_object_conversion(): name="identity", source_bindings=source_bindings, processing_config=ProcessingConfig( - variable_components=[VariableComponents.SITE], + variable_components=[Microscopy.Site], group_by=None, input_source=InputSource.PIPELINE_START, ), @@ -52,7 +52,7 @@ def test_resolved_pipeline_reads_steps_without_object_conversion(): pipeline.steps[0].processing_config.input_source is InputSource.PIPELINE_START ) assert pipeline.steps[0].processing_config.variable_components == [ - VariableComponents.SITE + Microscopy.Site ] diff --git a/tests/unit/test_routed_composite_execution.py b/tests/unit/test_routed_composite_execution.py index 0cb1384007..1ccb3cd237 100644 --- a/tests/unit/test_routed_composite_execution.py +++ b/tests/unit/test_routed_composite_execution.py @@ -8,7 +8,7 @@ from objectstate import ObjectStateRegistry from objectstate.lazy_factory import ensure_global_config_context -from openhcs.constants import InputSource, Microscope, VariableComponents +from openhcs.constants import InputSource, Microscope from openhcs.core.config import ( GlobalPipelineConfig, LazyPathPlanningConfig, @@ -31,6 +31,7 @@ crop, tophat, ) +from openhcs.domains.microscopy.axes import Microscopy @pytest.mark.parametrize("channels", [(1, 2), (2, 3)]) @@ -72,7 +73,7 @@ def test_reduced_channel_stack_is_the_next_steps_only_input( FunctionStep( func=[tophat, stack_function] if preprocess else stack_function, processing_config=LazyProcessingConfig( - variable_components=[VariableComponents.CHANNEL] + variable_components=[Microscopy.Channel] ), ), FunctionStep(func=identity), @@ -94,7 +95,7 @@ def test_reduced_channel_stack_is_the_next_steps_only_input( FunctionStep( func=create_projection, processing_config=LazyProcessingConfig( - variable_components=[VariableComponents.Z_INDEX] + variable_components=[Microscopy.ZIndex] ), ), ) @@ -108,7 +109,7 @@ def test_reduced_channel_stack_is_the_next_steps_only_input( {"template_path": str(template), "rotate_result": False}, ), processing_config=LazyProcessingConfig( - variable_components=[VariableComponents.CHANNEL] + variable_components=[Microscopy.Channel] ), ) ) diff --git a/tests/unit/test_runtime_adapter_source_artifacts.py b/tests/unit/test_runtime_adapter_source_artifacts.py index 102f2730c7..d5a9a6c012 100644 --- a/tests/unit/test_runtime_adapter_source_artifacts.py +++ b/tests/unit/test_runtime_adapter_source_artifacts.py @@ -8,7 +8,7 @@ from polystore.filemanager import FileManager from scipy.io import savemat -from openhcs.constants.constants import AllComponents, Backend +from openhcs.constants.constants import Backend from openhcs.constants.input_source import InputSource from openhcs.core.artifacts import ImageArtifactType, ObjectLabelsArtifactType from openhcs.core.component_group_scope import RuntimeExecutionAxisScope @@ -46,6 +46,7 @@ from openhcs.microscopes import create_microscope_handler from openhcs.microscopes.openhcs import OpenHCSMicroscopeHandler from openhcs.microscopes.source_schema import SourceSchemaFilenameParser +from openhcs.domains.microscopy.axes import Microscopy def _filemanager() -> FileManager: @@ -145,7 +146,7 @@ def binding( microscope_handler=microscope_handler, runtime_source_binding_context_cache=RuntimeSourceBindingContextCache(), source_image_set_identity_policy=SourceImageSetIdentityPolicy( - frozenset((AllComponents.CHANNEL,)) + frozenset((Microscopy.Channel,)) ), ) context.runtime_source_workspace_projection_authority = VirtualWorkspaceSourceProjectionAuthority.from_context( diff --git a/tests/unit/test_runtime_artifact_queries.py b/tests/unit/test_runtime_artifact_queries.py index 707229b39a..7726d60e32 100644 --- a/tests/unit/test_runtime_artifact_queries.py +++ b/tests/unit/test_runtime_artifact_queries.py @@ -5,7 +5,6 @@ import pytest -from openhcs.constants.constants import AllComponents from openhcs.core.artifacts import ( ArtifactOutputPlan, ArtifactType, @@ -75,6 +74,7 @@ CELLPROFILER_MEASUREMENT_LOOKUP_DIALECT, ) from openhcs.core.runtime_artifact_values import RuntimeValue +from openhcs.domains.microscopy.axes import Microscopy AXIS_ID = "A01" @@ -1750,7 +1750,7 @@ def _record_native( path=f"/memory/{native_value.name}.pkl", artifact_type=kind, group_keys=(group_key,) if group_key is not None else (), - group_component=(AllComponents.CHANNEL if group_key is not None else None), + group_component=(Microscopy.Channel if group_key is not None else None), ), native_value, axis_id=AXIS_ID, diff --git a/tests/unit/test_runtime_equivalence.py b/tests/unit/test_runtime_equivalence.py index 2572e729ec..19fed2d560 100644 --- a/tests/unit/test_runtime_equivalence.py +++ b/tests/unit/test_runtime_equivalence.py @@ -8,7 +8,6 @@ import numpy as np import pytest -from openhcs.constants.constants import AllComponents from openhcs.core.artifacts import ( ArtifactSpec, ImageArtifactType, @@ -141,6 +140,7 @@ from openhcs.processing.backends.cellprofiler.shape import ( MeasureObjectSizeShapeModule, ) +from openhcs.domains.microscopy.axes import Microscopy def RuntimeEquivalencePolicy(**kwargs): @@ -4489,7 +4489,7 @@ def test_runtime_reference_artifact_equivalence_deduplicates_full_axis_relations artifact_type=MeasurementsArtifactType, scope=RuntimeExecutionAxisScope( axis_id="A01", - component=AllComponents.CHANNEL, + component=Microscopy.Channel, value=f"w{index + 1}", ), ), @@ -4518,7 +4518,7 @@ def test_runtime_reference_artifact_equivalence_deduplicates_full_axis_relations artifact_type=RelationshipsArtifactType, scope=RuntimeExecutionAxisScope( axis_id="A01", - component=AllComponents.CHANNEL, + component=Microscopy.Channel, value=f"w{index + 1}", ), ), @@ -5377,7 +5377,7 @@ def test_runtime_reference_artifact_equivalence_does_not_treat_measurement_group artifact_type=MeasurementsArtifactType, scope=RuntimeExecutionAxisScope( axis_id="A01", - component=AllComponents.SITE, + component=Microscopy.Site, value=group_key, ), ), @@ -5471,7 +5471,7 @@ def test_runtime_reference_artifact_equivalence_does_not_treat_paired_artifact_g artifact_type=MeasurementsArtifactType, scope=RuntimeExecutionAxisScope( axis_id="A01", - component=AllComponents.SITE, + component=Microscopy.Site, value=group_key, ), ), @@ -5494,7 +5494,7 @@ def test_runtime_reference_artifact_equivalence_does_not_treat_paired_artifact_g artifact_type=RelationshipsArtifactType, scope=RuntimeExecutionAxisScope( axis_id="A01", - component=AllComponents.SITE, + component=Microscopy.Site, value=group_key, ), ), @@ -5661,7 +5661,7 @@ def test_runtime_reference_artifact_equivalence_aligns_scoped_child_tables_by_so artifact_type=MeasurementsArtifactType, scope=RuntimeExecutionAxisScope( axis_id="A01", - component=AllComponents.SITE, + component=Microscopy.Site, value=site, ), ), @@ -5714,7 +5714,7 @@ def test_runtime_reference_artifact_equivalence_aligns_scoped_child_tables_by_so ), RuntimeExportObservation.from_output_root(candidate_root), source_image_set_identity_policy=SourceImageSetIdentityPolicy( - frozenset((AllComponents.CHANNEL,)) + frozenset((Microscopy.Channel,)) ), ) @@ -8308,7 +8308,7 @@ def test_runtime_measurement_snapshot_deduplicates_aggregate_group_tables( artifact_type=MeasurementsArtifactType, scope=RuntimeExecutionAxisScope( axis_id="A01", - component=AllComponents.CHANNEL, + component=Microscopy.Channel, value=group_key, ), ), @@ -8480,7 +8480,7 @@ def measurement_table() -> MeasurementTable: artifact_type=MeasurementsArtifactType, scope=RuntimeExecutionAxisScope( axis_id="A01", - component=AllComponents.SITE, + component=Microscopy.Site, value=site, ), ), @@ -8634,7 +8634,7 @@ def test_runtime_measurement_snapshot_preserves_group_local_duplicate_rows( artifact_type=MeasurementsArtifactType, scope=RuntimeExecutionAxisScope( axis_id="A01", - component=AllComponents.CHANNEL, + component=Microscopy.Channel, value=group_key, ), ), @@ -8706,7 +8706,7 @@ def test_runtime_measurement_snapshot_deduplicates_grouped_full_axis_tables( artifact_type=MeasurementsArtifactType, scope=RuntimeExecutionAxisScope( axis_id="A01", - component=AllComponents.CHANNEL, + component=Microscopy.Channel, value=group_key, ), ), @@ -8834,7 +8834,7 @@ def test_runtime_measurement_snapshot_does_not_partition_location_rows_by_group_ artifact_type=MeasurementsArtifactType, scope=RuntimeExecutionAxisScope( axis_id="A01", - component=AllComponents.CHANNEL, + component=Microscopy.Channel, value=group_key, ), ), @@ -10865,7 +10865,7 @@ def test_runtime_reference_artifact_equivalence_ignores_grouped_duplicate_image_ artifact_type=MeasurementsArtifactType, scope=RuntimeExecutionAxisScope( axis_id="A01", - component=AllComponents.CHANNEL, + component=Microscopy.Channel, value=group_key, ), ), @@ -11159,7 +11159,7 @@ def test_runtime_reference_artifact_equivalence_ignores_group_replayed_image_tab artifact_type=MeasurementsArtifactType, scope=RuntimeExecutionAxisScope( axis_id="A01", - component=AllComponents.CHANNEL, + component=Microscopy.Channel, value=channel, ), ), @@ -11225,7 +11225,7 @@ def test_runtime_reference_artifact_equivalence_preserves_local_group_image_rows artifact_type=MeasurementsArtifactType, scope=RuntimeExecutionAxisScope( axis_id="A01", - component=AllComponents.CHANNEL, + component=Microscopy.Channel, value=channel, ), ), diff --git a/tests/unit/test_runtime_execution_scope_metadata.py b/tests/unit/test_runtime_execution_scope_metadata.py index e22bbb85bf..d9ca973cb5 100644 --- a/tests/unit/test_runtime_execution_scope_metadata.py +++ b/tests/unit/test_runtime_execution_scope_metadata.py @@ -3,19 +3,19 @@ import pytest -from openhcs.constants import AllComponents from openhcs.core.component_group_scope import RuntimeExecutionAxisScope from openhcs.core.source_matching import source_component_metadata_value +from openhcs.domains.microscopy.axes import Microscopy @pytest.mark.parametrize("grouped,fixed", [(False, False), (True, False), (False, True), (True, True)]) def test_scope_projects_every_owned_coordinate_without_inventing_absent_axes(grouped, fixed): scope = RuntimeExecutionAxisScope.from_raw( "A01", - component=AllComponents.CHANNEL if grouped else None, + component=Microscopy.Channel if grouped else None, value="2" if grouped else None, fixed_component_values=( - ((AllComponents.SITE, "3"), (AllComponents.TIMEPOINT, "4")) if fixed else () + ((Microscopy.Site, "3"), (Microscopy.Timepoint, "4")) if fixed else () ), ) original = {"source_alias": "Synthetic", "custom": {"retained": "value"}} @@ -23,23 +23,23 @@ def test_scope_projects_every_owned_coordinate_without_inventing_absent_axes(gro metadata = scope.source_component_metadata(original) for component, value in scope.source_component_values: assert source_component_metadata_value(metadata, component) == value - assert source_component_metadata_value(metadata, AllComponents.Z_INDEX) is None + assert source_component_metadata_value(metadata, Microscopy.ZIndex) is None assert metadata["source_alias"] == "Synthetic" assert metadata["custom"] == original["custom"] assert original == untouched @pytest.mark.parametrize("component,wrong", [ - (AllComponents.WELL, "B01"), - (AllComponents.SITE, "8"), - (AllComponents.TIMEPOINT, "7"), + (Microscopy.Well, "B01"), + (Microscopy.Site, "8"), + (Microscopy.Timepoint, "7"), ]) def test_scope_rejects_conflicting_axis_and_fixed_identity(component, wrong): scope = RuntimeExecutionAxisScope.from_raw( - "A01", component=AllComponents.CHANNEL, value="2", - fixed_component_values=((AllComponents.SITE, "3"), (AllComponents.TIMEPOINT, "4")), + "A01", component=Microscopy.Channel, value="2", + fixed_component_values=((Microscopy.Site, "3"), (Microscopy.Timepoint, "4")), ) - metadata = {component.value: wrong, "custom": "retained"} + metadata = {component.name: wrong, "custom": "retained"} untouched = dict(metadata) with pytest.raises(ValueError, match="Runtime execution scope conflicts"): scope.source_component_metadata(metadata) @@ -48,30 +48,30 @@ def test_scope_rejects_conflicting_axis_and_fixed_identity(component, wrong): def test_scope_canonicalizes_matching_component_alias_without_losing_source_fields(): scope = RuntimeExecutionAxisScope.from_raw( - "A01", component=AllComponents.CHANNEL, value="2", - fixed_component_values=((AllComponents.SITE, "3"),), + "A01", component=Microscopy.Channel, value="2", + fixed_component_values=((Microscopy.Site, "3"),), ) metadata = scope.source_component_metadata({"Well": "A01", "Channel": "2", "custom": "retained"}) - assert source_component_metadata_value(metadata, AllComponents.CHANNEL) == "2" + assert source_component_metadata_value(metadata, Microscopy.Channel) == "2" assert metadata["custom"] == "retained" @pytest.mark.parametrize("fixed", [False, True]) def test_scope_keeps_measured_source_channel_distinct_from_object_group(fixed): scope = RuntimeExecutionAxisScope.from_raw( - "A01", component=AllComponents.CHANNEL, value="2", - fixed_component_values=((AllComponents.Z_INDEX, "1"),) if fixed else (), + "A01", component=Microscopy.Channel, value="2", + fixed_component_values=((Microscopy.ZIndex, "1"),) if fixed else (), ) metadata = scope.source_component_metadata({"channel": "1", "custom": "retained"}) - assert source_component_metadata_value(metadata, AllComponents.CHANNEL) == "1" - assert scope.value_text_for_component(AllComponents.CHANNEL) == "2" + assert source_component_metadata_value(metadata, Microscopy.Channel) == "1" + assert scope.value_text_for_component(Microscopy.Channel) == "2" assert metadata["custom"] == "retained" def test_scope_still_rejects_a_contradictory_declared_group_coordinate(): scope = RuntimeExecutionAxisScope.from_raw( - "A01", component=AllComponents.CHANNEL, value="2", - fixed_component_values=((AllComponents.Z_INDEX, "1"),), + "A01", component=Microscopy.Channel, value="2", + fixed_component_values=((Microscopy.ZIndex, "1"),), ) with pytest.raises(ValueError, match="group coordinate conflicts"): - scope.for_group_coordinate(AllComponents.CHANNEL, "3") + scope.for_group_coordinate(Microscopy.Channel, "3") diff --git a/tests/unit/test_runtime_execution_validation.py b/tests/unit/test_runtime_execution_validation.py index c7c81e920b..90c38c6eb2 100644 --- a/tests/unit/test_runtime_execution_validation.py +++ b/tests/unit/test_runtime_execution_validation.py @@ -8,7 +8,6 @@ from polystore.base import ensure_storage_registry, storage_registry from polystore.filemanager import FileManager -from openhcs.constants.constants import VariableComponents from openhcs.core.artifacts import ( ArtifactOutputPlan, ImageArtifactType, @@ -74,6 +73,7 @@ from openhcs.runtime.zmq_execution_observation import ( ZMQRuntimeExecutionObservationExport, ) +from openhcs.domains.microscopy.axes import Microscopy def _compiled_pattern( @@ -404,7 +404,7 @@ def test_artifact_viewer_expectation_preserves_exact_output_plane_components() - path="/tmp/A01_w1_labels.roi.zip", content=(), metadata=metadata, - ).with_variable_components((VariableComponents.SITE,)) + ).with_variable_components((Microscopy.Site,)) payloads = _runtime_artifact_viewer_output_payloads((output,)) diff --git a/tests/unit/test_runtime_output_matching.py b/tests/unit/test_runtime_output_matching.py index 1670bfdf80..c41fdbf3fd 100644 --- a/tests/unit/test_runtime_output_matching.py +++ b/tests/unit/test_runtime_output_matching.py @@ -3,7 +3,6 @@ import numpy as np import pytest -from openhcs.constants.constants import AllComponents from openhcs.core.aligned_image_payload import ( AlignedImageSliceContext, AlignedImageStack, @@ -30,6 +29,7 @@ CompiledFunctionInvocation, FunctionInvocationKey, ) +from openhcs.domains.microscopy.axes import Microscopy def _contract( @@ -271,7 +271,7 @@ def test_compiled_output_selection_accepts_exact_runtime_group_projection( path="/memory/output", artifact_type=output.artifact_type, group_keys=("1", "2"), - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, paths_by_group={ "1": "/memory/output/1", "2": "/memory/output/2", @@ -296,7 +296,7 @@ def test_compiled_output_selection_rejects_same_ref_non_owner_projection() -> No path="/memory/output", artifact_type=output.artifact_type, group_keys=("1", "2"), - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, paths_by_group={ "1": "/memory/output/1", "2": "/memory/output/2", @@ -312,7 +312,7 @@ def test_compiled_output_selection_rejects_same_ref_non_owner_projection() -> No path="/memory/wrong", artifact_type=output.artifact_type, group_keys=("1",), - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, paths_by_group={"1": "/memory/wrong"}, ) diff --git a/tests/unit/test_runtime_slice_projection.py b/tests/unit/test_runtime_slice_projection.py index cebe8f9008..954fb65475 100644 --- a/tests/unit/test_runtime_slice_projection.py +++ b/tests/unit/test_runtime_slice_projection.py @@ -7,7 +7,6 @@ from arraybridge.decorators import PRESERVE_INPUT_DTYPE_CONFIG import openhcs.processing.backends.cellprofiler # noqa: F401 -from openhcs.constants.constants import VariableComponents from openhcs.core.aligned_image_payload import ( AlignedImageSliceContext, AlignedImageStack, @@ -61,6 +60,7 @@ from openhcs.core.runtime_tabular_values import ColumnarRows, FieldSpec from openhcs.core.source_image_provenance import SourceImageProvenancePlanes from openhcs.core.source_metadata import SourceVoxelSpacing +from openhcs.domains.microscopy.axes import Microscopy def _subclasses(root: type) -> tuple[type, ...]: @@ -642,7 +642,7 @@ def test_variable_component_projection_requires_declared_plane_provenance() -> N request = RuntimeProjectionSourceIdentityRequest( value=np.zeros((2, 4, 5), dtype=np.float32), source_description="undeclared image stack", - variable_components=(VariableComponents.SITE,), + variable_components=(Microscopy.Site,), ) with pytest.raises( @@ -661,7 +661,7 @@ def test_variable_component_projection_validates_declared_cardinality() -> None: request = RuntimeProjectionSourceIdentityRequest( value=payload, source_description="mismatched image stack", - variable_components=(VariableComponents.SITE,), + variable_components=(Microscopy.Site,), plane_projection=RuntimePlaneAxisValueProjection.preserve( axis=RuntimePlaneAxis.RUNTIME_SLICE, axis_size=2, @@ -681,7 +681,7 @@ def test_variable_component_projection_rejects_expanded_source_provenance() -> N request = RuntimeProjectionSourceIdentityRequest( value=payload, source_description="expanded-provenance image stack", - variable_components=(VariableComponents.SITE,), + variable_components=(Microscopy.Site,), plane_projection=RuntimePlaneAxisValueProjection.preserve( axis=RuntimePlaneAxis.RUNTIME_SLICE, axis_size=3, @@ -708,7 +708,7 @@ def test_variable_component_projection_uses_declared_plane_axis() -> None: RuntimeProjectionSourceIdentityRequest( value=payload, source_description="declared image stack", - variable_components=(VariableComponents.SITE,), + variable_components=(Microscopy.Site,), plane_projection=RuntimePlaneAxisValueProjection.preserve( axis=RuntimePlaneAxis.RUNTIME_SLICE, axis_size=2, diff --git a/tests/unit/test_runtime_source_resolution_snapshot.py b/tests/unit/test_runtime_source_resolution_snapshot.py index 1e08738376..38463d4261 100644 --- a/tests/unit/test_runtime_source_resolution_snapshot.py +++ b/tests/unit/test_runtime_source_resolution_snapshot.py @@ -6,7 +6,6 @@ import pytest from polystore.virtual_workspace import SourcePixelRef -from openhcs.constants.constants import AllComponents from openhcs.core.context.processing_context import ProcessingContext from openhcs.core.runtime_source_binding_cache import RuntimeSourceBindingContextCache from openhcs.core.source_binding_selection import ( @@ -28,6 +27,7 @@ from openhcs.core.source_workspace_projection import VirtualWorkspaceSourceProjection from openhcs.microscopes.microscope_interfaces import FilenameParseResult from openhcs.microscopes.source_schema import SourceSchemaFilenameParser +from openhcs.domains.microscopy.axes import Microscopy PATH = "A01_s001_w1_z001_t001.tif" @@ -48,7 +48,7 @@ def parse_filename(self, path): component, ( int(self.pattern_format) - if component is AllComponents.SITE + if component is Microscopy.Site else value ), ) @@ -272,7 +272,7 @@ def test_snapshot_owns_position_and_projection_map_views(): refs = {PATH: original_ref} positions = { PATH: SourcePlaneProjection( - address=OpenHCSPlaneAddress.from_values("A01", 1, 1, 1, 1), + address=OpenHCSPlaneAddress(((Microscopy.Well, "A01"), (Microscopy.Site, 1), (Microscopy.Channel, 1), (Microscopy.ZIndex, 1), (Microscopy.Timepoint, 1))), ref=original_ref, source_alias="original", ) diff --git a/tests/unit/test_runtime_value_store.py b/tests/unit/test_runtime_value_store.py index 772f259f0a..7942ecc5e3 100644 --- a/tests/unit/test_runtime_value_store.py +++ b/tests/unit/test_runtime_value_store.py @@ -4,7 +4,6 @@ import numpy as np import pytest -from openhcs.constants.constants import AllComponents, get_multiprocessing_axis from openhcs.core.artifacts import ( ArtifactInputProjectionPlan, ArtifactInputPlan, @@ -79,6 +78,8 @@ from openhcs.core.source_matching import SourceImageSetIdentityCompatibility, SourceImageSetIdentityPolicy from openhcs.interop.cellprofiler.runtime.artifact_binding import RuntimeInputBindingRequest from tests.unit.cellprofiler_runtime_test_support import cellprofiler_runtime_adapter_for_test +from openhcs.core.axes import Axis, AxisFamily +from openhcs.domains.microscopy.axes import Microscopy def _runtime_input_edge( @@ -87,7 +88,7 @@ def _runtime_input_edge( invocation_scope: ComponentGroupScope, producer_selection_scope: ComponentGroupScope, component_scopes: tuple[ComponentGroupScope, ...], - consumer_variable_components: tuple[AllComponents, ...], + consumer_variable_components: tuple[type[Axis], ...], ) -> InvocationArtifactInputEdgePlan: invocation_key = FunctionInvocationKey( "runtime_input_test", @@ -122,7 +123,7 @@ def _runtime_value(name="measurements", path="/memory/measurements.pkl"): path=path, artifact_type=MeasurementsArtifactType, group_keys=("DAPI",), - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, ), MeasurementTable( name=name, @@ -242,14 +243,14 @@ def test_output_plan_uses_its_single_scope_for_ungrouped_invocation(): path="/memory/Nuclei.pkl", artifact_type=ObjectLabelsArtifactType, group_keys=("1",), - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, paths_by_group={"1": "/memory/Nuclei_1.pkl"}, ) resolved = output_plan.for_invocation_group(None) assert resolved.group_keys == ("1",) - assert resolved.group_component is AllComponents.CHANNEL + assert resolved.group_component is Microscopy.Channel assert resolved.path == "/memory/Nuclei_1.pkl" @@ -273,11 +274,11 @@ def test_ungrouped_output_plan_ignores_incidental_invocation_group(): def test_runtime_artifact_address_round_trips_fixed_component_values(): scope = RuntimeExecutionAxisScope.from_raw( "A01", - component=AllComponents.CHANNEL, + component=Microscopy.Channel, value="2", fixed_component_values=( - (AllComponents.Z_INDEX, 3), - (AllComponents.SITE, 1), + (Microscopy.ZIndex, 3), + (Microscopy.Site, 1), ), ) address = RuntimeArtifactAddress( @@ -302,12 +303,12 @@ def test_runtime_artifact_address_round_trips_fixed_component_values(): def test_runtime_artifact_key_canonicalizes_group_coordinate_value(): numeric_scope = RuntimeExecutionAxisScope.from_raw( "A01", - component=AllComponents.CHANNEL, + component=Microscopy.Channel, value=2, ) text_scope = RuntimeExecutionAxisScope.from_raw( "A01", - component=AllComponents.CHANNEL, + component=Microscopy.Channel, value="2", ) @@ -328,7 +329,7 @@ def test_runtime_artifact_key_canonicalizes_group_coordinate_value(): with pytest.raises(TypeError, match="value must be canonical text"): RuntimeExecutionAxisScope( axis_id="A01", - component=AllComponents.CHANNEL, + component=Microscopy.Channel, value=2, ) @@ -339,7 +340,7 @@ def test_dynamic_output_plan_requires_invocation_group(): path="/memory/ChannelImage.pkl", artifact_type=ImageArtifactType, group_keys=(None,), - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, paths_by_group={None: "/memory/ChannelImage.pkl"}, ) @@ -379,16 +380,16 @@ def test_runtime_value_store_keeps_fixed_component_artifacts_distinct() -> None: path="/memory/measurements.pkl", artifact_type=MeasurementsArtifactType, group_keys=("2",), - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, ).for_group("2") store = RuntimeValueStore() records = [] for z_index in ("1", "2"): execution_scope = RuntimeExecutionAxisScope.from_raw( "A01", - component=AllComponents.CHANNEL, + component=Microscopy.Channel, value="2", - fixed_component_values=((AllComponents.Z_INDEX, z_index),), + fixed_component_values=((Microscopy.ZIndex, z_index),), ) value = RuntimeValue.normalize_for_execution_scope( output_plan, @@ -419,7 +420,7 @@ def test_runtime_value_store_keeps_fixed_component_artifacts_distinct() -> None: assert records[0].key != records[1].key assert store.values() == tuple(records) assert tuple( - record.key.scope.value_text_for_component(AllComponents.Z_INDEX) + record.key.scope.value_text_for_component(Microscopy.ZIndex) for record in store.values() ) == ("1", "2") @@ -428,21 +429,21 @@ def test_runtime_value_store_keeps_fixed_component_artifacts_distinct() -> None: path=output_plan.path, artifact_type=MeasurementsArtifactType, group_keys=("2",), - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, ) runtime_input = RuntimeArtifactInput( edge_plan=_runtime_input_edge( input_plan, - invocation_scope=ComponentGroupScope.dynamic(AllComponents.CHANNEL), + invocation_scope=ComponentGroupScope.dynamic(Microscopy.Channel), producer_selection_scope=input_plan.producer_group_scope(), - component_scopes=(ComponentGroupScope.dynamic(AllComponents.CHANNEL),), + component_scopes=(ComponentGroupScope.dynamic(Microscopy.Channel),), consumer_variable_components=(), ), axis_scope=RuntimeExecutionAxisScope.from_raw( "A01", - component=AllComponents.CHANNEL, + component=Microscopy.Channel, value="2", - fixed_component_values=((AllComponents.Z_INDEX, "2"),), + fixed_component_values=((Microscopy.ZIndex, "2"),), ), backend="memory", ) @@ -456,7 +457,7 @@ def test_runtime_value_empty_fixed_scope_preserves_ordinary_key_identity() -> No path="/memory/measurements.pkl", artifact_type=MeasurementsArtifactType, group_keys=("2",), - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, ).for_group("2") table = MeasurementTable( name="measurements", @@ -522,7 +523,7 @@ def test_runtime_value_store_find_matching_cache_invalidates_after_replace(): name="measurements", path="/memory/measurements.pkl", artifact_type=MeasurementsArtifactType, - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, ), "memory", ), @@ -548,7 +549,7 @@ def test_runtime_artifact_query_from_input_plan_uses_group_path(): path="/memory/DNA.pkl", artifact_type=ImageArtifactType, group_keys=("1", "2"), - group_component=AllComponents.SITE, + group_component=Microscopy.Site, paths_by_group={"1": "/memory/DNA_s1.pkl", "2": "/memory/DNA_s2.pkl"}, ), axis_id="A01", @@ -567,7 +568,7 @@ def test_runtime_artifact_query_from_dynamic_input_plan_matches_discovered_group name="measurements", path="/memory/measurements.pkl", artifact_type=MeasurementsArtifactType, - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, paths_by_group={None: "/memory/measurements.pkl"}, ), axis_id="A01", @@ -598,7 +599,7 @@ def test_observed_input_selection_preserves_groups_axis_backend_and_locations( path="/memory/RGB.pkl", artifact_type=ImageArtifactType, group_keys=(None,) if dynamic else ("1", "2", "3"), - group_component=AllComponents.SITE, + group_component=Microscopy.Site, paths_by_group=( {None: "/memory/RGB.pkl"} if dynamic @@ -606,16 +607,16 @@ def test_observed_input_selection_preserves_groups_axis_backend_and_locations( ), ) selection = ( - ComponentGroupScope.dynamic(AllComponents.SITE) + ComponentGroupScope.dynamic(Microscopy.Site) if dynamic - else ComponentGroupScope.from_raw(("2", "1"), component=AllComponents.SITE) + else ComponentGroupScope.from_raw(("2", "1"), component=Microscopy.Site) ) edge = _runtime_input_edge( storage_plan, invocation_scope=ComponentGroupScope.ungrouped(), producer_selection_scope=selection, component_scopes=(selection,), - consumer_variable_components=(AllComponents.SITE,), + consumer_variable_components=(Microscopy.Site,), ) records = tuple( StoredRuntimeValue( @@ -624,7 +625,7 @@ def test_observed_input_selection_preserves_groups_axis_backend_and_locations( artifact_type=ImageArtifactType, scope=RuntimeExecutionAxisScope.from_raw( "A01", - component=AllComponents.SITE, + component=Microscopy.Site, value=key, ), ), @@ -646,7 +647,7 @@ def test_observed_input_selection_preserves_groups_axis_backend_and_locations( first.key, scope=RuntimeExecutionAxisScope.from_raw( "B01", - component=AllComponents.SITE, + component=Microscopy.Site, value="1", ), ), @@ -700,7 +701,7 @@ def test_runtime_artifact_query_from_dynamic_output_plan_uses_runtime_group_path name="RGBImage", path="/memory/A01_RGBImage.pkl", artifact_type=ImageArtifactType, - group_component=AllComponents.SITE, + group_component=Microscopy.Site, paths_by_group={None: "/memory/A01_RGBImage.pkl"}, ), axis_id="A01", @@ -724,7 +725,7 @@ def test_runtime_artifact_input_projection_selects_same_component_group(): path="/memory/image.pkl", artifact_type=ImageArtifactType, group_keys=("1", "2"), - group_component=AllComponents.SITE, + group_component=Microscopy.Site, paths_by_group=paths, ) for group_key, value in (("1", 1.0), ("2", 2.0)): @@ -744,20 +745,20 @@ def test_runtime_artifact_input_projection_selects_same_component_group(): path="/memory/image.pkl", artifact_type=ImageArtifactType, group_keys=("1", "2"), - group_component=AllComponents.SITE, + group_component=Microscopy.Site, paths_by_group=paths, ) records = RuntimeArtifactInput( edge_plan=_runtime_input_edge( storage_plan, - invocation_scope=ComponentGroupScope.dynamic(AllComponents.SITE), - producer_selection_scope=ComponentGroupScope.dynamic(AllComponents.SITE), - component_scopes=(ComponentGroupScope.dynamic(AllComponents.SITE),), - consumer_variable_components=(AllComponents.CHANNEL,), + invocation_scope=ComponentGroupScope.dynamic(Microscopy.Site), + producer_selection_scope=ComponentGroupScope.dynamic(Microscopy.Site), + component_scopes=(ComponentGroupScope.dynamic(Microscopy.Site),), + consumer_variable_components=(Microscopy.Channel,), ), axis_scope=RuntimeExecutionAxisScope.from_raw( "A01", - component=AllComponents.SITE, + component=Microscopy.Site, value="2", ), backend="memory", @@ -777,7 +778,7 @@ def test_runtime_artifact_input_collects_exact_complete_producer_scope(): path="/memory/measurements.pkl", artifact_type=MeasurementsArtifactType, group_keys=("1", "2"), - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, paths_by_group=paths, ) for group_key in ("1", "2"): @@ -804,7 +805,7 @@ def test_runtime_artifact_input_collects_exact_complete_producer_scope(): path="/memory/measurements.pkl", artifact_type=MeasurementsArtifactType, group_keys=("1", "2"), - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, paths_by_group=paths, ) runtime_input = RuntimeArtifactInput( @@ -812,15 +813,15 @@ def test_runtime_artifact_input_collects_exact_complete_producer_scope(): storage_plan, invocation_scope=ComponentGroupScope( ("1",), - component=AllComponents.CHANNEL, + component=Microscopy.Channel, ), producer_selection_scope=storage_plan.producer_group_scope(), component_scopes=(), - consumer_variable_components=(AllComponents.SITE,), + consumer_variable_components=(Microscopy.Site,), ), axis_scope=RuntimeExecutionAxisScope.from_raw( "A01", - component=AllComponents.CHANNEL, + component=Microscopy.Channel, value="1", ), backend="memory", @@ -841,7 +842,7 @@ def test_runtime_artifact_input_projection_collects_variable_component_groups(): name="RGBImage", path="/memory/RGBImage.pkl", artifact_type=ImageArtifactType, - group_component=AllComponents.SITE, + group_component=Microscopy.Site, paths_by_group={None: "/memory/RGBImage.pkl"}, ) for group_key, value in (("1", 1.0), ("2", 2.0)): @@ -860,20 +861,20 @@ def test_runtime_artifact_input_projection_collects_variable_component_groups(): name="RGBImage", path="/memory/RGBImage.pkl", artifact_type=ImageArtifactType, - group_component=AllComponents.SITE, + group_component=Microscopy.Site, paths_by_group={None: "/memory/RGBImage.pkl"}, ) runtime_input = RuntimeArtifactInput( edge_plan=_runtime_input_edge( input_plan, - invocation_scope=ComponentGroupScope.dynamic(AllComponents.CHANNEL), + invocation_scope=ComponentGroupScope.dynamic(Microscopy.Channel), producer_selection_scope=input_plan.producer_group_scope(), - component_scopes=(ComponentGroupScope.dynamic(AllComponents.CHANNEL),), - consumer_variable_components=(AllComponents.SITE,), + component_scopes=(ComponentGroupScope.dynamic(Microscopy.Channel),), + consumer_variable_components=(Microscopy.Site,), ), axis_scope=RuntimeExecutionAxisScope.from_raw( "A01", - component=AllComponents.CHANNEL, + component=Microscopy.Channel, value="1", ), backend="memory", @@ -903,8 +904,8 @@ def test_runtime_artifact_input_projection_transposes_producer_stack_axis() -> N path="/memory/image.pkl", artifact_type=ImageArtifactType, group_keys=("1", "2", "3"), - group_component=AllComponents.CHANNEL, - variable_components=(AllComponents.SITE,), + group_component=Microscopy.Channel, + variable_components=(Microscopy.Site,), paths_by_group=paths, ) for channel_index, channel in enumerate(("1", "2", "3"), start=1): @@ -933,7 +934,7 @@ def test_runtime_artifact_input_projection_transposes_producer_stack_axis() -> N group_plan, payload, execution_scope=RuntimeExecutionAxisScope.from_raw( - "A01", component=AllComponents.CHANNEL, value=channel, + "A01", component=Microscopy.Channel, value=channel, ), ), path=group_plan.path, @@ -945,21 +946,21 @@ def test_runtime_artifact_input_projection_transposes_producer_stack_axis() -> N path="/memory/image.pkl", artifact_type=ImageArtifactType, group_keys=("1", "2", "3"), - group_component=AllComponents.CHANNEL, - variable_components=(AllComponents.SITE,), + group_component=Microscopy.Channel, + variable_components=(Microscopy.Site,), paths_by_group=paths, ) runtime_input = RuntimeArtifactInput( edge_plan=_runtime_input_edge( storage_plan, - invocation_scope=ComponentGroupScope.dynamic(AllComponents.SITE), + invocation_scope=ComponentGroupScope.dynamic(Microscopy.Site), producer_selection_scope=storage_plan.producer_group_scope(), - component_scopes=(ComponentGroupScope.dynamic(AllComponents.SITE),), - consumer_variable_components=(AllComponents.CHANNEL,), + component_scopes=(ComponentGroupScope.dynamic(Microscopy.Site),), + consumer_variable_components=(Microscopy.Channel,), ), axis_scope=RuntimeExecutionAxisScope.from_raw( "A01", - component=AllComponents.SITE, + component=Microscopy.Site, value="2", ), backend="memory", @@ -967,8 +968,8 @@ def test_runtime_artifact_input_projection_transposes_producer_stack_axis() -> N candidates = runtime_input.candidate_execution_scopes( store, - ComponentGroupScope.dynamic(AllComponents.SITE), - variable_components=ComponentSet((AllComponents.CHANNEL,)), + ComponentGroupScope.dynamic(Microscopy.Site), + variable_components=ComponentSet((Microscopy.Channel,)), ) assert tuple(scope.value_text for scope in candidates) == ("1", "2", "3") assert all(scope.fixed_component_values == () for scope in candidates) @@ -988,7 +989,7 @@ def test_runtime_artifact_input_projection_transposes_producer_stack_axis() -> N def test_artifact_candidate_scopes_preserve_projected_site_time_correlation() -> None: path = "/memory/processed_pixels.pkl" - variables = (AllComponents.SITE, AllComponents.TIMEPOINT) + variables = (Microscopy.Site, Microscopy.Timepoint) output_plan = ArtifactOutputPlan( name="image", path=path, artifact_type=ImageArtifactType, variable_components=variables, @@ -1015,11 +1016,11 @@ def test_artifact_candidate_scopes_preserve_projected_site_time_correlation() -> path=path, backend="memory") edge = _runtime_input_edge( storage_plan, - invocation_scope=ComponentGroupScope.dynamic(AllComponents.SITE), + invocation_scope=ComponentGroupScope.dynamic(Microscopy.Site), producer_selection_scope=ComponentGroupScope.ungrouped(), component_scopes=( - ComponentGroupScope.dynamic(AllComponents.SITE), - ComponentGroupScope.from_raw(("3",), component=AllComponents.TIMEPOINT), + ComponentGroupScope.dynamic(Microscopy.Site), + ComponentGroupScope.from_raw(("3",), component=Microscopy.Timepoint), ), consumer_variable_components=(), ) @@ -1028,12 +1029,12 @@ def test_artifact_candidate_scopes_preserve_projected_site_time_correlation() -> axis_scope=RuntimeExecutionAxisScope.from_raw("A01", component=None, value=None), ) candidates = runtime_input.candidate_execution_scopes( - store, ComponentGroupScope.dynamic(AllComponents.SITE), + store, ComponentGroupScope.dynamic(Microscopy.Site), variable_components=ComponentSet(), ) (coordinates,) = tuple(candidates) assert coordinates.value_text == "1" - assert coordinates.fixed_component_values == ((AllComponents.TIMEPOINT, "3"),) + assert coordinates.fixed_component_values == ((Microscopy.Timepoint, "3"),) assert candidates[coordinates] == path selected = replace(runtime_input, axis_scope=coordinates).resolve_value(store) np.testing.assert_array_equal(image_payload_data(selected), np.full((2, 2), 17.0)) @@ -1044,11 +1045,11 @@ def test_artifact_candidate_scopes_keep_actual_producer_group_as_fixed_context() path = "/memory/produced_pixels.pkl" output_plan = ArtifactOutputPlan( name="image", path=path, artifact_type=ImageArtifactType, - group_component=AllComponents.CHANNEL, group_keys=("1",), + group_component=Microscopy.Channel, group_keys=("1",), ) storage_plan = ArtifactInputPlan( name="image", path=path, artifact_type=ImageArtifactType, - group_component=AllComponents.CHANNEL, group_keys=("1",), + group_component=Microscopy.Channel, group_keys=("1",), ) payload = ImagePayloadMetadata( source_path="/source/old_filename_w9.tif", @@ -1059,8 +1060,8 @@ def test_artifact_candidate_scopes_keep_actual_producer_group_as_fixed_context() RuntimeValue.normalize_for_execution_scope( output_plan, payload, execution_scope=RuntimeExecutionAxisScope.from_raw( - "A01", component=AllComponents.CHANNEL, value="1", - fixed_component_values=((AllComponents.SITE, "2"), (AllComponents.TIMEPOINT, "3"), (AllComponents.Z_INDEX, "1")), + "A01", component=Microscopy.Channel, value="1", + fixed_component_values=((Microscopy.Site, "2"), (Microscopy.Timepoint, "3"), (Microscopy.ZIndex, "1")), ), ), path=path, backend="memory", @@ -1068,22 +1069,22 @@ def test_artifact_candidate_scopes_keep_actual_producer_group_as_fixed_context() runtime_input = RuntimeArtifactInput( edge_plan=_runtime_input_edge( storage_plan, - invocation_scope=ComponentGroupScope.dynamic(AllComponents.SITE), + invocation_scope=ComponentGroupScope.dynamic(Microscopy.Site), producer_selection_scope=storage_plan.producer_group_scope(), - component_scopes=(ComponentGroupScope.dynamic(AllComponents.SITE),), + component_scopes=(ComponentGroupScope.dynamic(Microscopy.Site),), consumer_variable_components=(), ), axis_scope=RuntimeExecutionAxisScope.from_raw("A01", component=None, value=None), backend="memory", ) candidates = runtime_input.candidate_execution_scopes( - store, ComponentGroupScope.dynamic(AllComponents.SITE), + store, ComponentGroupScope.dynamic(Microscopy.Site), variable_components=ComponentSet(), ) (coordinates,) = tuple(candidates) assert coordinates.value_text == "2" assert dict(coordinates.fixed_component_values) == { - AllComponents.CHANNEL: "1", AllComponents.TIMEPOINT: "3", AllComponents.Z_INDEX: "1", + Microscopy.Channel: "1", Microscopy.Timepoint: "3", Microscopy.ZIndex: "1", } selected = replace(runtime_input, axis_scope=coordinates).records(store) assert len(selected) == 1 @@ -1097,14 +1098,14 @@ def test_artifact_candidate_scopes_keep_actual_producer_group_as_fixed_context() RuntimeValue.normalize_for_execution_scope( output_plan, second_payload, execution_scope=RuntimeExecutionAxisScope.from_raw( - "A01", component=AllComponents.CHANNEL, value="1", - fixed_component_values=((AllComponents.SITE, "2"), (AllComponents.TIMEPOINT, "3"), (AllComponents.Z_INDEX, "2")), + "A01", component=Microscopy.Channel, value="1", + fixed_component_values=((Microscopy.Site, "2"), (Microscopy.Timepoint, "3"), (Microscopy.ZIndex, "2")), ), ), path=path, backend="memory", ) candidates = runtime_input.candidate_execution_scopes( - store, ComponentGroupScope.dynamic(AllComponents.SITE), + store, ComponentGroupScope.dynamic(Microscopy.Site), variable_components=ComponentSet(), ) assert len(candidates) == 2 @@ -1121,25 +1122,25 @@ def test_runtime_artifact_input_projection_ignores_scalar_pixel_contributors() - name="image", path=path, artifact_type=ImageArtifactType, - variable_components=(AllComponents.SITE,), + variable_components=(Microscopy.Site,), ) storage_plan = ArtifactInputPlan( name="image", path=path, artifact_type=ImageArtifactType, - variable_components=(AllComponents.SITE,), + variable_components=(Microscopy.Site,), ) runtime_input = RuntimeArtifactInput( edge_plan=_runtime_input_edge( storage_plan, - invocation_scope=ComponentGroupScope.dynamic(AllComponents.SITE), + invocation_scope=ComponentGroupScope.dynamic(Microscopy.Site), producer_selection_scope=ComponentGroupScope.ungrouped(), - component_scopes=(ComponentGroupScope.dynamic(AllComponents.SITE),), + component_scopes=(ComponentGroupScope.dynamic(Microscopy.Site),), consumer_variable_components=(), ), axis_scope=RuntimeExecutionAxisScope.from_raw( "A01", - component=AllComponents.SITE, + component=Microscopy.Site, value="2", ), backend="memory", @@ -1210,8 +1211,8 @@ def test_runtime_artifact_input_projection_collapses_excluded_singleton_axis() - path="/memory/image.pkl", artifact_type=ImageArtifactType, group_keys=("1", "2"), - group_component=AllComponents.SITE, - variable_components=(AllComponents.CHANNEL,), + group_component=Microscopy.Site, + variable_components=(Microscopy.Channel,), paths_by_group=paths, ) for site_index, site in enumerate(("1", "2"), start=1): @@ -1236,26 +1237,26 @@ def test_runtime_artifact_input_projection_collapses_excluded_singleton_axis() - path="/memory/image.pkl", artifact_type=ImageArtifactType, group_keys=("1", "2"), - group_component=AllComponents.SITE, - variable_components=(AllComponents.CHANNEL,), + group_component=Microscopy.Site, + variable_components=(Microscopy.Channel,), paths_by_group=paths, ) runtime_input = RuntimeArtifactInput( edge_plan=_runtime_input_edge( storage_plan, - invocation_scope=ComponentGroupScope.dynamic(AllComponents.CHANNEL), + invocation_scope=ComponentGroupScope.dynamic(Microscopy.Channel), producer_selection_scope=storage_plan.producer_group_scope(), component_scopes=( ComponentGroupScope( ("1",), - component=AllComponents.CHANNEL, + component=Microscopy.Channel, ), ), - consumer_variable_components=(AllComponents.SITE,), + consumer_variable_components=(Microscopy.Site,), ), axis_scope=RuntimeExecutionAxisScope.from_raw( "A01", - component=AllComponents.CHANNEL, + component=Microscopy.Channel, value="1", ), backend="memory", @@ -1287,7 +1288,7 @@ def test_runtime_artifact_input_reconstructs_singleton_producer_group_axis() -> path=path, artifact_type=ImageArtifactType, group_keys=("1",), - group_component=AllComponents.SITE, + group_component=Microscopy.Site, paths_by_group={"1": path}, ) store = RuntimeValueStore() @@ -1305,20 +1306,20 @@ def test_runtime_artifact_input_reconstructs_singleton_producer_group_axis() -> path=path, artifact_type=ImageArtifactType, group_keys=("1",), - group_component=AllComponents.SITE, + group_component=Microscopy.Site, paths_by_group={"1": path}, ) runtime_input = RuntimeArtifactInput( edge_plan=_runtime_input_edge( storage_plan, - invocation_scope=ComponentGroupScope.dynamic(AllComponents.CHANNEL), + invocation_scope=ComponentGroupScope.dynamic(Microscopy.Channel), producer_selection_scope=storage_plan.producer_group_scope(), - component_scopes=(ComponentGroupScope.dynamic(AllComponents.CHANNEL),), - consumer_variable_components=(AllComponents.SITE,), + component_scopes=(ComponentGroupScope.dynamic(Microscopy.Channel),), + consumer_variable_components=(Microscopy.Site,), ), axis_scope=RuntimeExecutionAxisScope.from_raw( "A01", - component=AllComponents.CHANNEL, + component=Microscopy.Channel, value="1", ), backend="memory", @@ -1341,7 +1342,7 @@ def test_runtime_artifact_input_keeps_singleton_scalar_selection_unstacked() -> path=path, artifact_type=ImageArtifactType, group_keys=("1",), - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, paths_by_group={"1": path}, ) store = RuntimeValueStore() @@ -1359,7 +1360,7 @@ def test_runtime_artifact_input_keeps_singleton_scalar_selection_unstacked() -> path=path, artifact_type=ImageArtifactType, group_keys=("1",), - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, paths_by_group={"1": path}, ) runtime_input = RuntimeArtifactInput( @@ -1368,9 +1369,9 @@ def test_runtime_artifact_input_keeps_singleton_scalar_selection_unstacked() -> invocation_scope=ComponentGroupScope.ungrouped(), producer_selection_scope=storage_plan.producer_group_scope(), component_scopes=( - ComponentGroupScope(("1",), component=AllComponents.CHANNEL), + ComponentGroupScope(("1",), component=Microscopy.Channel), ), - consumer_variable_components=(AllComponents.SITE,), + consumer_variable_components=(Microscopy.Site,), ), axis_scope=RuntimeExecutionAxisScope.from_raw( "A01", @@ -1392,7 +1393,7 @@ def test_runtime_artifact_input_projection_selects_compiler_owned_group_for_ungr path="/memory/image.pkl", artifact_type=ImageArtifactType, group_keys=("1", "2"), - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, ) runtime_input = RuntimeArtifactInput( edge_plan=_runtime_input_edge( @@ -1400,15 +1401,15 @@ def test_runtime_artifact_input_projection_selects_compiler_owned_group_for_ungr invocation_scope=ComponentGroupScope.ungrouped(), producer_selection_scope=ComponentGroupScope( ("2",), - component=AllComponents.CHANNEL, + component=Microscopy.Channel, ), component_scopes=( ComponentGroupScope( ("2",), - component=AllComponents.CHANNEL, + component=Microscopy.Channel, ), ), - consumer_variable_components=(AllComponents.SITE,), + consumer_variable_components=(Microscopy.Site,), ), axis_scope=RuntimeExecutionAxisScope.from_raw( "A01", @@ -1422,7 +1423,7 @@ def test_runtime_artifact_input_projection_selects_compiler_owned_group_for_ungr runtime_input.edge_plan.projection.producer_selection_scope == ComponentGroupScope( ("2",), - component=AllComponents.CHANNEL, + component=Microscopy.Channel, ) ) @@ -1430,8 +1431,8 @@ def test_runtime_artifact_input_projection_selects_compiler_owned_group_for_ungr def test_runtime_artifact_input_projection_keeps_equal_keys_component_typed(): store = RuntimeValueStore() for component, path, value in ( - (AllComponents.SITE, "/memory/site_image.pkl", 1.0), - (AllComponents.CHANNEL, "/memory/channel_image.pkl", 2.0), + (Microscopy.Site, "/memory/site_image.pkl", 1.0), + (Microscopy.Channel, "/memory/channel_image.pkl", 2.0), ): plan = ArtifactOutputPlan( name="image", @@ -1456,27 +1457,27 @@ def test_runtime_artifact_input_projection_keeps_equal_keys_component_typed(): path="/memory/site_image.pkl", artifact_type=ImageArtifactType, group_keys=("1",), - group_component=AllComponents.SITE, + group_component=Microscopy.Site, paths_by_group={"1": "/memory/site_image.pkl"}, ) records = RuntimeArtifactInput( edge_plan=_runtime_input_edge( storage_plan, - invocation_scope=ComponentGroupScope.dynamic(AllComponents.CHANNEL), + invocation_scope=ComponentGroupScope.dynamic(Microscopy.Channel), producer_selection_scope=storage_plan.producer_group_scope(), - component_scopes=(ComponentGroupScope.dynamic(AllComponents.CHANNEL),), - consumer_variable_components=(AllComponents.SITE,), + component_scopes=(ComponentGroupScope.dynamic(Microscopy.Channel),), + consumer_variable_components=(Microscopy.Site,), ), axis_scope=RuntimeExecutionAxisScope.from_raw( "A01", - component=AllComponents.CHANNEL, + component=Microscopy.Channel, value="1", ), backend="memory", ).records(store) assert len(records) == 1 - assert records[0].key.scope.component is AllComponents.SITE + assert records[0].key.scope.component is Microscopy.Site np.testing.assert_array_equal(records[0].data, np.full((2, 2), 1.0)) @@ -1488,7 +1489,7 @@ def test_runtime_artifact_input_projection_uses_compiled_group_for_plane_scope() path=path, artifact_type=ImageArtifactType, group_keys=("3",), - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, paths_by_group={"3": path}, ) payload = ImagePayloadMetadata( @@ -1504,7 +1505,7 @@ def test_runtime_artifact_input_projection_uses_compiled_group_for_plane_scope() path=path, artifact_type=ImageArtifactType, group_keys=("3",), - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, paths_by_group={"3": path}, ) runtime_input = RuntimeArtifactInput( @@ -1513,15 +1514,15 @@ def test_runtime_artifact_input_projection_uses_compiled_group_for_plane_scope() invocation_scope=ComponentGroupScope.ungrouped(), producer_selection_scope=ComponentGroupScope( ("3",), - component=AllComponents.CHANNEL, + component=Microscopy.Channel, ), component_scopes=( ComponentGroupScope( ("3",), - component=AllComponents.CHANNEL, + component=Microscopy.Channel, ), ), - consumer_variable_components=(AllComponents.SITE,), + consumer_variable_components=(Microscopy.Site,), ), axis_scope=RuntimeExecutionAxisScope.from_raw( "A01", @@ -1535,7 +1536,7 @@ def test_runtime_artifact_input_projection_uses_compiled_group_for_plane_scope() runtime_input.edge_plan.projection.producer_selection_scope == ComponentGroupScope( ("3",), - component=AllComponents.CHANNEL, + component=Microscopy.Channel, ) ) resolved = runtime_input.resolve_value(store) @@ -1746,10 +1747,10 @@ def _paired_channel_label_input(*, producer_axis="A01", producer_values=(), prod """One exact DNA producer consumed in its paired actin image-set context.""" fixed_values = { - AllComponents.CHANNEL: "1", - AllComponents.SITE: "1", - AllComponents.Z_INDEX: "1", - AllComponents.TIMEPOINT: "1", + Microscopy.Channel: "1", + Microscopy.Site: "1", + Microscopy.ZIndex: "1", + Microscopy.Timepoint: "1", **dict(producer_values), } storage_plan = ArtifactInputPlan( @@ -1783,16 +1784,16 @@ def _paired_channel_label_input(*, producer_axis="A01", producer_values=(), prod component=None, value=None, fixed_component_values=( - (AllComponents.CHANNEL, "2"), - (AllComponents.SITE, "1"), - (AllComponents.Z_INDEX, "1"), - (AllComponents.TIMEPOINT, "1"), + (Microscopy.Channel, "2"), + (Microscopy.Site, "1"), + (Microscopy.ZIndex, "1"), + (Microscopy.Timepoint, "1"), ), ) source_bindings = CompiledSourceBindingPlan( bindings=(NamedSourceBinding( alias="Actin", - component_identity=(ComponentSelector(AllComponents.CHANNEL, "2"),), + component_identity=(ComponentSelector(Microscopy.Channel, "2"),), ),), ) runtime_input = _ungrouped_runtime_artifact_input( @@ -1824,7 +1825,7 @@ def _grouped_label_input_with_distinct_consumer_channel(): name="Cells", path=path, artifact_type=ObjectLabelsArtifactType, - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, group_keys=("0",), paths_by_group={"0": path}, source_step_id=20, @@ -1844,9 +1845,9 @@ def _grouped_label_input_with_distinct_consumer_channel(): variant_data=ObjectLabelVariantData(labels=np.ones((2, 2), dtype=np.uint16)), ), execution_scope=RuntimeExecutionAxisScope.from_raw( - "W001", component=AllComponents.CHANNEL, value="0", + "W001", component=Microscopy.Channel, value="0", fixed_component_values=( - (AllComponents.SITE, "1"), (AllComponents.TIMEPOINT, "1"), + (Microscopy.Site, "1"), (Microscopy.Timepoint, "1"), ), ), ) @@ -1858,13 +1859,13 @@ def _grouped_label_input_with_distinct_consumer_channel(): invocation_scope=ComponentGroupScope.ungrouped(), producer_selection_scope=storage_plan.producer_group_scope(), component_scopes=(), - consumer_variable_components=(AllComponents.Z_INDEX,), + consumer_variable_components=(Microscopy.ZIndex,), ), axis_scope=RuntimeExecutionAxisScope.from_raw( "W001", component=None, value=None, fixed_component_values=( - (AllComponents.SITE, "1"), (AllComponents.CHANNEL, "2"), - (AllComponents.TIMEPOINT, "1"), + (Microscopy.Site, "1"), (Microscopy.Channel, "2"), + (Microscopy.Timepoint, "1"), ), ), backend="memory", @@ -1879,18 +1880,18 @@ def test_exact_producer_group_does_not_constrain_consumer_source_channel(): assert runtime_input.resolve_value(store) is record.data candidates = runtime_input.candidate_execution_scopes( store, ComponentGroupScope.ungrouped(), - variable_components=ComponentSet((AllComponents.Z_INDEX,)), + variable_components=ComponentSet((Microscopy.ZIndex,)), ) (scope,) = candidates # Discovery still owns the producer's semantic channel, rather than adopting # a later consumer's independently selected source-image channel. assert dict(scope.fixed_component_values) == { - AllComponents.SITE: "1", AllComponents.CHANNEL: "0", - AllComponents.TIMEPOINT: "1", + Microscopy.Site: "1", Microscopy.Channel: "0", + Microscopy.Timepoint: "1", } -@pytest.mark.parametrize("component", [AllComponents.SITE, AllComponents.TIMEPOINT]) +@pytest.mark.parametrize("component", [Microscopy.Site, Microscopy.Timepoint]) def test_exact_producer_group_preserves_shared_fixed_context_constraints(component): store, _record, runtime_input = _grouped_label_input_with_distinct_consumer_channel() fixed_values = dict(runtime_input.axis_scope.fixed_component_values) @@ -1919,7 +1920,7 @@ def test_exact_producer_group_rejects_other_producer_or_fixed_plane(mismatch): else: scope = RuntimeExecutionAxisScope.from_raw( scope.axis_id, component=scope.component, value=scope.value, - fixed_component_values=(*scope.fixed_component_values, (AllComponents.Z_INDEX, "2")), + fixed_component_values=(*scope.fixed_component_values, (Microscopy.ZIndex, "2")), ) runtime_input = replace( runtime_input, @@ -1929,7 +1930,7 @@ def test_exact_producer_group_rejects_other_producer_or_fixed_plane(mismatch): value=runtime_input.axis_scope.value, fixed_component_values=( *runtime_input.axis_scope.fixed_component_values, - (AllComponents.Z_INDEX, "1"), + (Microscopy.ZIndex, "1"), ), ), ) @@ -1947,14 +1948,14 @@ def test_different_producer_group_axis_preserves_fixed_source_channel_constraint # SITE is now the selected producer group. CHANNEL remains a genuine fixed # image context and cannot use the selected-group exemption. scope = RuntimeExecutionAxisScope.from_raw( - "W001", component=AllComponents.SITE, value="1", + "W001", component=Microscopy.Site, value="1", fixed_component_values=( - (AllComponents.CHANNEL, "0"), (AllComponents.TIMEPOINT, "1"), + (Microscopy.Channel, "0"), (Microscopy.Timepoint, "1"), ), ) storage_plan = replace( runtime_input.edge_plan.storage_plan, - group_component=AllComponents.SITE, group_keys=("1",), + group_component=Microscopy.Site, group_keys=("1",), paths_by_group={"1": record.location.path}, ) runtime_input = replace( @@ -2018,7 +2019,7 @@ def consume_labels(image, labels): assert request.artifact_value(edge) is record.data -@pytest.mark.parametrize("component", [AllComponents.SITE, AllComponents.Z_INDEX, AllComponents.TIMEPOINT]) +@pytest.mark.parametrize("component", [Microscopy.Site, Microscopy.ZIndex, Microscopy.Timepoint]) def test_paired_channel_input_rejects_other_context_coordinate(component): store, _record, runtime_input = _paired_channel_label_input( producer_values=((component, "2"),), @@ -2145,10 +2146,10 @@ def test_paired_channel_projection_rejects_a_different_producer_site_plane(): runtime_input, edge_plan=replace( edge, - storage_plan=replace(edge.storage_plan, variable_components=(AllComponents.SITE,)), + storage_plan=replace(edge.storage_plan, variable_components=(Microscopy.Site,)), projection=replace( edge.projection, - component_scopes=(ComponentGroupScope(("1",), component=AllComponents.SITE),), + component_scopes=(ComponentGroupScope(("1",), component=Microscopy.Site),), ), ), ) @@ -2160,7 +2161,7 @@ def test_paired_channel_projection_rejects_a_different_producer_site_plane(): def test_paired_channel_input_rejects_ambiguous_address_matched_contexts(): store, _record, runtime_input = _paired_channel_label_input() _other_store, other_record, _other_input = _paired_channel_label_input( - producer_values=((AllComponents.CHANNEL, "3"),), + producer_values=((Microscopy.Channel, "3"),), ) store.record(other_record, path=other_record.location.path, backend=other_record.location.backend) @@ -2178,16 +2179,16 @@ def test_runtime_artifact_input_preserves_same_scope_semantic_partitions(): @pytest.mark.parametrize("producer_values,consumer_values", [ pytest.param((), (), id="exact-unscoped"), - pytest.param((), ((AllComponents.Z_INDEX, "1"),), id="consumer-only"), - pytest.param(((AllComponents.TIMEPOINT, "1"),), (), id="producer-only"), + pytest.param((), ((Microscopy.ZIndex, "1"),), id="consumer-only"), + pytest.param(((Microscopy.Timepoint, "1"),), (), id="producer-only"), pytest.param( - ((AllComponents.TIMEPOINT, "1"),), - ((AllComponents.Z_INDEX, "1"),), + ((Microscopy.Timepoint, "1"),), + ((Microscopy.ZIndex, "1"),), id="disjoint-partial", ), pytest.param( - ((AllComponents.TIMEPOINT, "1"),), - ((AllComponents.Z_INDEX, "1"), (AllComponents.TIMEPOINT, "1")), + ((Microscopy.Timepoint, "1"),), + ((Microscopy.ZIndex, "1"), (Microscopy.Timepoint, "1")), id="shared-partial", ), ]) @@ -2238,11 +2239,11 @@ def test_runtime_artifact_input_accepts_exact_unscoped_and_partial_coordinates( @pytest.mark.parametrize("producer_values,consumer_values", [ pytest.param((), (), id="empty-projected-context"), - pytest.param(((AllComponents.TIMEPOINT, "1"),), (), id="producer-only"), - pytest.param((), ((AllComponents.Z_INDEX, "1"),), id="consumer-only"), + pytest.param(((Microscopy.Timepoint, "1"),), (), id="producer-only"), + pytest.param((), ((Microscopy.ZIndex, "1"),), id="consumer-only"), pytest.param( - ((AllComponents.TIMEPOINT, "1"),), - ((AllComponents.Z_INDEX, "1"),), + ((Microscopy.Timepoint, "1"),), + ((Microscopy.ZIndex, "1"),), id="disjoint-partial", ), ]) @@ -2265,7 +2266,7 @@ def test_exact_input_admits_no_shared_projected_context_constraints( ) source = NamedSourceBinding( alias="Reference", - component_identity=(ComponentSelector(get_multiprocessing_axis(), "A01"),), + component_identity=(ComponentSelector(AxisFamily.active().partition_axis(), "A01"),), ) consumer_scope = RuntimeExecutionAxisScope.from_raw( "A01", component=None, value=None, fixed_component_values=consumer_values, @@ -2339,7 +2340,7 @@ def test_runtime_artifact_input_rejects_conflicting_declared_fixed_coordinate(): "A01", component=None, value=None, - fixed_component_values=((AllComponents.TIMEPOINT, "2"),), + fixed_component_values=((Microscopy.Timepoint, "2"),), ), ) store.replace(value, path=storage_plan.path, backend="memory") @@ -2348,8 +2349,8 @@ def test_runtime_artifact_input_rejects_conflicting_declared_fixed_coordinate(): component=None, value=None, fixed_component_values=( - (AllComponents.Z_INDEX, "1"), - (AllComponents.TIMEPOINT, "1"), + (Microscopy.ZIndex, "1"), + (Microscopy.Timepoint, "1"), ), ) @@ -2387,7 +2388,7 @@ def test_runtime_artifact_input_rejects_unprojected_fixed_scope_partitions(): "A01", component=None, value=None, - fixed_component_values=((AllComponents.Z_INDEX, z_index),), + fixed_component_values=((Microscopy.ZIndex, z_index),), ), ) store.replace(value, path=storage_plan.path, backend="memory") @@ -2459,7 +2460,7 @@ def test_dynamic_input_query_distinguishes_compiled_paths_with_same_backend(): name="measurements", path=record.location.path, artifact_type=MeasurementsArtifactType, - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, paths_by_group={None: record.location.path, "DAPI": record.location.path}, ), axis_id="A01", @@ -2481,7 +2482,7 @@ def test_dynamic_input_query_retains_discovery_order_and_ignores_wrong_component name="measurements", path="/memory/measurements.pkl", artifact_type=MeasurementsArtifactType, - group_component=AllComponents.SITE, + group_component=Microscopy.Site, group_keys=("DAPI",), ), value.data, @@ -2494,7 +2495,7 @@ def test_dynamic_input_query_retains_discovery_order_and_ignores_wrong_component name="measurements", path="/memory/measurements.pkl", artifact_type=MeasurementsArtifactType, - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, ), axis_id="A01", backend="memory", @@ -2508,7 +2509,7 @@ def test_dynamic_query_snapshots_address_mapping_without_mutating_source_plan(): name="measurements", path="/memory/measurements.pkl", artifact_type=MeasurementsArtifactType, - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, paths_by_group=paths, ) old_query = RuntimeArtifactQuery.from_input_plan( @@ -2547,7 +2548,7 @@ def test_dynamic_query_retains_absent_and_empty_path_declarations(paths): name="measurements", path="/memory/measurements.pkl", artifact_type=MeasurementsArtifactType, - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, paths_by_group=paths, ) query = RuntimeArtifactQuery.from_input_plan(plan, axis_id="A01", backend="memory") @@ -2562,7 +2563,7 @@ def test_input_plan_owns_independent_immutable_runtime_address_snapshot(): name="measurements", path="/memory/measurements.pkl", artifact_type=MeasurementsArtifactType, - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, paths_by_group=paths, source_step_id=7, source_step_scope_id="producer-scope", @@ -2597,7 +2598,7 @@ def test_store_transport_excludes_all_derived_lookup_caches(): name="measurements", path=record.location.path, artifact_type=MeasurementsArtifactType, - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, paths_by_group={"DAPI": record.location.path}, ), axis_id="A01", @@ -2638,7 +2639,7 @@ def test_unified_store_cache_keeps_both_query_domains_and_empty_results(): name="measurements", path=record.location.path, artifact_type=MeasurementsArtifactType, - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, ), axis_id="A01", backend="memory", @@ -2674,7 +2675,7 @@ def test_unified_store_cache_eviction_recomputes_order_without_changing_record_a name="first", path=first.location.path, artifact_type=MeasurementsArtifactType, - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, group_keys=("DAPI",), ), axis_id="A01", diff --git a/tests/unit/test_runtime_values.py b/tests/unit/test_runtime_values.py index 8b88addc3d..abbe4d4f05 100644 --- a/tests/unit/test_runtime_values.py +++ b/tests/unit/test_runtime_values.py @@ -8,7 +8,6 @@ from python_introspect import to_jsonable -from openhcs.constants.constants import AllComponents from openhcs.core.artifacts import ( ArtifactSpec, ArtifactOutputPlan, @@ -139,6 +138,7 @@ from openhcs.processing.backends.lib_registry.unified_registry import ( Pure2DAuxiliaryOutputAggregator, ) +from openhcs.domains.microscopy.axes import Microscopy def test_object_label_set_is_a_runtime_array_payload() -> None: @@ -2853,7 +2853,7 @@ def test_normalize_artifact_value_builds_key_for_nominal_payload(): path="/memory/measurements.pkl", artifact_type=MeasurementsArtifactType, group_keys=("DAPI",), - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, ) table = MeasurementTable( name="measurements", @@ -2896,7 +2896,7 @@ def test_group_scoped_artifact_consumes_singleton_payload_axis() -> None: path="/memory/Corrected.tif", artifact_type=ImageArtifactType, group_keys=("1",), - group_component=AllComponents.SITE, + group_component=Microscopy.Site, ) value = RuntimeValue.normalize( @@ -2915,7 +2915,7 @@ def test_group_scoped_artifact_rejects_multi_plane_payload_axis() -> None: path="/memory/Corrected.tif", artifact_type=ImageArtifactType, group_keys=("1",), - group_component=AllComponents.SITE, + group_component=Microscopy.Site, ) with pytest.raises(ValueError, match="cannot retain a declared runtime-slice"): @@ -2932,8 +2932,8 @@ def test_group_scoped_stack_artifact_preserves_declared_payload_axis() -> None: path="/memory/Corrected.tif", artifact_type=ImageArtifactType, group_keys=("1",), - group_component=AllComponents.CHANNEL, - variable_components=(AllComponents.SITE,), + group_component=Microscopy.Channel, + variable_components=(Microscopy.Site,), ) value = RuntimeValue.normalize( @@ -2954,7 +2954,7 @@ def test_group_scoped_measurements_preserve_runtime_row_axis() -> None: path="/memory/Measurements.pkl", artifact_type=MeasurementsArtifactType, group_keys=("1",), - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, ) table = MeasurementTable( name="Measurements", @@ -2986,7 +2986,7 @@ def test_grouped_scalar_artifact_records_compose_one_runtime_axis() -> None: path=f"/memory/Corrected_{site}.tif", artifact_type=ImageArtifactType, group_keys=(site,), - group_component=AllComponents.SITE, + group_component=Microscopy.Site, ), ImagePayloadMetadata().payload_with( np.zeros((4, 5), dtype=np.float32), @@ -3385,7 +3385,7 @@ def test_normalize_image_metadata_payload_applies_declared_identity(): name="DNA", path="/memory/DNA.pkl", artifact_type=ImageArtifactType, - variable_components=(AllComponents.CHANNEL,), + variable_components=(Microscopy.Channel,), ) image = np.zeros((2, 2), dtype=np.float32) payload = ImagePayloadMetadata( diff --git a/tests/unit/test_selected_plane_stream_materialization.py b/tests/unit/test_selected_plane_stream_materialization.py index 23e2d7bae9..ba791ebb85 100644 --- a/tests/unit/test_selected_plane_stream_materialization.py +++ b/tests/unit/test_selected_plane_stream_materialization.py @@ -64,9 +64,10 @@ streaming_config_stub, ) from test_materialization_core import _viewer_stream_backend_kwargs +from openhcs.domains.microscopy.axes import Microscopy -def _source_stack(axis, component="channel"): +def _source_stack(axis, component=Microscopy.Channel.name): spacing = SourceVoxelSpacing((1.3556, 1.3556)) coordinates = tuple( { diff --git a/tests/unit/test_source_binding_path_admission.py b/tests/unit/test_source_binding_path_admission.py index 7a4359a886..a2e9f6f553 100644 --- a/tests/unit/test_source_binding_path_admission.py +++ b/tests/unit/test_source_binding_path_admission.py @@ -6,7 +6,6 @@ import pytest from polystore.virtual_workspace import SourcePixelRef -from openhcs.constants.constants import AllComponents from openhcs.core.source_binding_workspace import SourceBindingWorkspaceProjector from openhcs.core.source_bindings import ( ComponentSelector, @@ -20,6 +19,7 @@ SourceSelector, ) from openhcs.core.source_projection import SourceCandidate +from openhcs.domains.microscopy.axes import Microscopy def _candidate(path, *, identities=(), metadata=None): @@ -120,7 +120,7 @@ def test_physical_admission_does_not_predict_decoded_metadata_or_components( alias="selected", selector=SourceSelector( metadata=(MetadataSelector("well", "A01"),), - components=(ComponentSelector(AllComponents.CHANNEL, "1"),), + components=(ComponentSelector(Microscopy.Channel, "1"),), ), ) config = SourceBindingsConfig(bindings=(binding,)) diff --git a/tests/unit/test_source_binding_workspace.py b/tests/unit/test_source_binding_workspace.py index 4d1408c780..9c1124bd7c 100644 --- a/tests/unit/test_source_binding_workspace.py +++ b/tests/unit/test_source_binding_workspace.py @@ -9,7 +9,7 @@ import pytest import tifffile -from openhcs.constants.constants import AllComponents, Backend, Microscope +from openhcs.constants.constants import Backend, Microscope from openhcs.core.artifacts import ImageArtifactType, ObjectLabelsArtifactType from openhcs.core.source_binding_workspace import SourceBindingWorkspaceProjector from openhcs.core.runtime_tabular_values import FieldSpec @@ -61,6 +61,8 @@ from polystore.base import ensure_storage_registry, storage_registry from polystore.filemanager import FileManager from polystore.virtual_workspace import SourcePixelRef +from openhcs.domains.microscopy.axes import Microscopy +from openhcs.core.virtual_workspace_metadata import component_metadata_field def test_transient_axis_views_observe_each_new_projection_without_reusing_released_ids(): @@ -156,8 +158,8 @@ def observe_admission(projector, projection): plate_path=workspace, metadata_handler=handler.metadata_handler, filemanager=filemanager, cache=cache, source_bindings=config, ).projection_or_empty() - assert set(selected.component_values(AllComponents.SITE)) == set(map(str, expected_sites)) - assert set(selected.component_values(AllComponents.CHANNEL)) == {"1", "2"} + assert set(selected.component_values(Microscopy.Site)) == set(map(str, expected_sites)) + assert set(selected.component_values(Microscopy.Channel)) == {"1", "2"} assert len(selected.pipeline_start_files()) == len(expected_sites) * 2 for path in selected.pipeline_start_files(): lookup = VirtualWorkspacePathLookup.from_paths(path, path) @@ -202,7 +204,7 @@ def reject_redecode(_cls, _subdirectory): )) changed = context.runtime_source_workspace_projection_authority assert changed is not prior_authority - assert changed.projection_or_empty().component_values(AllComponents.SITE) == ("8",) + assert changed.projection_or_empty().component_values(Microscopy.Site) == ("8",) handler._source_bindings_config = replace(config, source_filters=()) assert context.runtime_source_workspace_projection_authority.projection_or_empty() is full handler._source_bindings_config = replace(config, source_filters=( @@ -225,9 +227,9 @@ def reject_redecode(_cls, _subdirectory): ), ).initialize() assert orchestrator.source_workspace_files() == selected.pipeline_start_files() - assert set(orchestrator.get_component_keys(AllComponents.SITE)) == set(map(str, expected_sites)) - assert orchestrator.get_component_keys(AllComponents.SITE, [str(expected_sites[0])]) == [str(expected_sites[0])] - assert orchestrator.get_component_keys(AllComponents.SITE, ["99"]) == [] + assert set(orchestrator.get_component_keys(Microscopy.Site)) == set(map(str, expected_sites)) + assert orchestrator.get_component_keys(Microscopy.Site, [str(expected_sites[0])]) == [str(expected_sites[0])] + assert orchestrator.get_component_keys(Microscopy.Site, ["99"]) == [] from tests.unit.test_completed_output_publication_lifecycle import _facts context.record_completed_step_outputs(_facts(workspace)) with_output = VirtualWorkspaceSourceProjectionAuthority.from_context(context).projection_or_empty() @@ -399,11 +401,11 @@ def test_source_workspace_excludes_non_pixel_sidecars_before_projection(tmp_path bindings=( NamedSourceBinding( alias="Blue", - component_identity=(ComponentSelector(AllComponents.CHANNEL, "1"),), + component_identity=(ComponentSelector(Microscopy.Channel, "1"),), ), NamedSourceBinding( alias="Green", - component_identity=(ComponentSelector(AllComponents.CHANNEL, "2"),), + component_identity=(ComponentSelector(Microscopy.Channel, "2"),), ), ), ), @@ -454,7 +456,7 @@ def test_source_binding_workspace_projector_assigns_selector_channels(tmp_path): value="nuclei_", ), ), - components=(ComponentSelector(AllComponents.CHANNEL, "1"),), + components=(ComponentSelector(Microscopy.Channel, "1"),), ), ), NamedSourceBinding( @@ -467,7 +469,7 @@ def test_source_binding_workspace_projector_assigns_selector_channels(tmp_path): value="membrane_", ), ), - components=(ComponentSelector(AllComponents.CHANNEL, "2"),), + components=(ComponentSelector(Microscopy.Channel, "2"),), ), ), ), @@ -484,13 +486,13 @@ def test_source_binding_workspace_projector_assigns_selector_channels(tmp_path): projection.source_alias: projection for projection in projection_set.projections } - assert by_alias["nuclei"].address.value_for(AllComponents.WELL) == "A01" - assert by_alias["nuclei"].address.value_for(AllComponents.SITE) == "1" - assert by_alias["nuclei"].address.value_for(AllComponents.CHANNEL) == "1" + assert by_alias["nuclei"].address.value_for(Microscopy.Well) == "A01" + assert by_alias["nuclei"].address.value_for(Microscopy.Site) == "1" + assert by_alias["nuclei"].address.value_for(Microscopy.Channel) == "1" assert by_alias["nuclei"].ref.backend_address == "raw/nuclei_A01_s1.png" - assert by_alias["membrane"].address.value_for(AllComponents.WELL) == "A01" - assert by_alias["membrane"].address.value_for(AllComponents.SITE) == "1" - assert by_alias["membrane"].address.value_for(AllComponents.CHANNEL) == "2" + assert by_alias["membrane"].address.value_for(Microscopy.Well) == "A01" + assert by_alias["membrane"].address.value_for(Microscopy.Site) == "1" + assert by_alias["membrane"].address.value_for(Microscopy.Channel) == "2" assert by_alias["membrane"].ref.backend_address == "raw/membrane_A01_s1.png" metadata = projection_set.metadata_dict( @@ -542,10 +544,10 @@ def test_source_binding_workspace_projects_semantic_identity_after_raw_selection NamedSourceBinding( alias="DNA", selector=SourceSelector( - components=(ComponentSelector(AllComponents.CHANNEL, "1"),), + components=(ComponentSelector(Microscopy.Channel, "1"),), ), component_identity=( - ComponentSelector(AllComponents.CHANNEL, "MCP_DNA"), + ComponentSelector(Microscopy.Channel, "MCP_DNA"), ), ), ), @@ -559,11 +561,11 @@ def test_source_binding_workspace_projects_semantic_identity_after_raw_selection filemanager=_filemanager(), ).projections - assert projection.address.value_for(AllComponents.CHANNEL) == "MCP_DNA" + assert projection.address.value_for(Microscopy.Channel) == "MCP_DNA" original_metadata = dict( SourceMetadataFields.original_items(projection.source_metadata) ) - assert original_metadata[AllComponents.CHANNEL.value] == "1" + assert original_metadata[Microscopy.Channel.name] == "1" def test_source_binding_workspace_remaps_store_addresses_and_labels(tmp_path): @@ -585,7 +587,7 @@ def binding(alias: str, channel: str) -> NamedSourceBinding: ), ), ), - component_identity=(ComponentSelector(AllComponents.CHANNEL, channel),), + component_identity=(ComponentSelector(Microscopy.Channel, channel),), ) projector = SourceBindingWorkspaceProjector( @@ -619,13 +621,13 @@ def binding(alias: str, channel: str) -> NamedSourceBinding: assert { ( - projection.address.value_for(AllComponents.WELL), - projection.address.value_for(AllComponents.SITE), + projection.address.value_for(Microscopy.Well), + projection.address.value_for(Microscopy.Site), ) for projection in projection_set.projections } == {("B02", "3")} - assert metadata[FIELDS.WELLS] == {"B02": None} - assert metadata[FIELDS.CHANNELS] == {"1": "DNA", "2": "RNA"} + assert metadata[component_metadata_field(Microscopy.Well)] == {"B02": None} + assert metadata[component_metadata_field(Microscopy.Channel)] == {"1": "DNA", "2": "RNA"} def test_source_binding_workspace_projects_declared_groups_to_wells(tmp_path): @@ -662,7 +664,7 @@ def test_source_binding_workspace_projects_declared_groups_to_wells(tmp_path): ), ), ), - component_identity=(ComponentSelector(AllComponents.CHANNEL, "1"),), + component_identity=(ComponentSelector(Microscopy.Channel, "1"),), ), ), match_plan=SourceBindingMatchPlan( @@ -681,11 +683,11 @@ def test_source_binding_workspace_projects_declared_groups_to_wells(tmp_path): assert { ( - projection.address.value_for(AllComponents.WELL), - projection.address.value_for(AllComponents.SITE), - projection.address.value_for(AllComponents.CHANNEL), - projection.address.value_for(AllComponents.Z_INDEX), - projection.address.value_for(AllComponents.TIMEPOINT), + projection.address.value_for(Microscopy.Well), + projection.address.value_for(Microscopy.Site), + projection.address.value_for(Microscopy.Channel), + projection.address.value_for(Microscopy.ZIndex), + projection.address.value_for(Microscopy.Timepoint), ) for projection in projection_set.projections } == { @@ -730,7 +732,7 @@ def test_source_binding_workspace_projects_registered_well_parts(tmp_path): ) assert { - projection.address.value_for(AllComponents.WELL) + projection.address.value_for(Microscopy.Well) for projection in projection_set.projections } == { "A01", @@ -758,7 +760,7 @@ def test_group_address_preserves_distinct_source_well_as_literal_metadata(tmp_pa bindings=( NamedSourceBinding( alias="OrigColor", - component_identity=(ComponentSelector(AllComponents.CHANNEL, "1"),), + component_identity=(ComponentSelector(Microscopy.Channel, "1"),), ), ), match_plan=SourceBindingMatchPlan( @@ -865,12 +867,12 @@ def test_source_binding_workspace_projector_order_matches_aliases(tmp_path): projection.source_alias: projection for projection in projection_set.projections } - assert by_alias["DAPI"].address.value_for(AllComponents.WELL) == "A01" - assert by_alias["DAPI"].address.value_for(AllComponents.SITE) == "1" - assert by_alias["DAPI"].address.value_for(AllComponents.CHANNEL) == "1" - assert by_alias["Actin"].address.value_for(AllComponents.WELL) == "A01" - assert by_alias["Actin"].address.value_for(AllComponents.SITE) == "1" - assert by_alias["Actin"].address.value_for(AllComponents.CHANNEL) == "2" + assert by_alias["DAPI"].address.value_for(Microscopy.Well) == "A01" + assert by_alias["DAPI"].address.value_for(Microscopy.Site) == "1" + assert by_alias["DAPI"].address.value_for(Microscopy.Channel) == "1" + assert by_alias["Actin"].address.value_for(Microscopy.Well) == "A01" + assert by_alias["Actin"].address.value_for(Microscopy.Site) == "1" + assert by_alias["Actin"].address.value_for(Microscopy.Channel) == "2" def test_order_source_sets_join_imported_metadata_across_aliases(tmp_path): @@ -922,7 +924,7 @@ def test_order_source_sets_join_imported_metadata_across_aliases(tmp_path): ), ), ), - component_identity=(ComponentSelector(AllComponents.CHANNEL, "1"),), + component_identity=(ComponentSelector(Microscopy.Channel, "1"),), ), NamedSourceBinding( alias="Actin", @@ -935,7 +937,7 @@ def test_order_source_sets_join_imported_metadata_across_aliases(tmp_path): ), ), ), - component_identity=(ComponentSelector(AllComponents.CHANNEL, "2"),), + component_identity=(ComponentSelector(Microscopy.Channel, "2"),), ), ), match_plan=SourceBindingMatchPlan(SourceBindingMatchMethod.ORDER), @@ -989,7 +991,7 @@ def test_order_source_sets_preserve_shared_virtual_stack_coordinates(tmp_path): ), ), ), - component_identity=(ComponentSelector(AllComponents.CHANNEL, "1"),), + component_identity=(ComponentSelector(Microscopy.Channel, "1"),), ), NamedSourceBinding( alias="Membrane", @@ -1002,11 +1004,11 @@ def test_order_source_sets_preserve_shared_virtual_stack_coordinates(tmp_path): ), ), ), - component_identity=(ComponentSelector(AllComponents.CHANNEL, "2"),), + component_identity=(ComponentSelector(Microscopy.Channel, "2"),), ), ), match_plan=SourceBindingMatchPlan(SourceBindingMatchMethod.ORDER), - source_stack_components=(AllComponents.Z_INDEX,), + source_stack_components=(Microscopy.ZIndex,), ) ).projection_set( tmp_path, @@ -1015,7 +1017,7 @@ def test_order_source_sets_preserve_shared_virtual_stack_coordinates(tmp_path): ) assert tuple( - (projection.source_alias, projection.address.value_for(AllComponents.Z_INDEX)) + (projection.source_alias, projection.address.value_for(Microscopy.ZIndex)) for projection in projection_set.projections ) == ( ("DNA", "1"), @@ -1180,7 +1182,7 @@ def test_imported_metadata_later_stage_overrides_extracted_field(tmp_path): assert metadata["Plate"] == "plate_1" assert metadata["Dose"] == "0" - assert projection.address.value_for(AllComponents.WELL) == "A01" + assert projection.address.value_for(Microscopy.Well) == "A01" original = dict(SourceMetadataFields.original_items(metadata)) assert original["Plate"] == "plate_1" assert original["Well"] == "A01" @@ -1614,17 +1616,17 @@ def test_source_binding_workspace_projector_expands_declared_source_stack(tmp_pa NamedSourceBinding( alias="Nuclei", selector=SourceSelector( - components=(ComponentSelector(AllComponents.CHANNEL, "1"),), + components=(ComponentSelector(Microscopy.Channel, "1"),), ), ), ), match_plan=SourceBindingMatchPlan(method=SourceBindingMatchMethod.ORDER), - source_stack_components=(AllComponents.Z_INDEX,), + source_stack_components=(Microscopy.ZIndex,), ) ).projection_set(tmp_path, (stack,), filemanager=_filemanager()) assert tuple( - projection.address.value_for(AllComponents.Z_INDEX) + projection.address.value_for(Microscopy.ZIndex) for projection in projection_set.projections ) == ("1", "2", "3") assert tuple( @@ -1667,7 +1669,7 @@ def test_order_source_sets_pair_expanded_stack_planes_across_aliases(tmp_path): ), ), match_plan=SourceBindingMatchPlan(method=SourceBindingMatchMethod.ORDER), - source_stack_components=(AllComponents.Z_INDEX,), + source_stack_components=(Microscopy.ZIndex,), ) ).projection_set( tmp_path, @@ -1678,7 +1680,7 @@ def test_order_source_sets_pair_expanded_stack_planes_across_aliases(tmp_path): assert tuple( ( projection.source_alias, - projection.address.value_for(AllComponents.Z_INDEX), + projection.address.value_for(Microscopy.ZIndex), projection.ref.source_axis_indices, ) for projection in projection_set.projections @@ -1800,7 +1802,7 @@ def test_source_binding_workspace_broadcasts_explicit_single_members(tmp_path): ) assert len(flatfield_projections) == 2 assert { - projection.address.value_for(AllComponents.SITE) + projection.address.value_for(Microscopy.Site) for projection in flatfield_projections } == { "1", @@ -1883,7 +1885,7 @@ def test_metadata_source_sets_reuse_declared_partial_match_members(tmp_path): projection.ref.backend_address for projection in illumination_projections } == {"plate_illum.tif"} assert { - projection.address.value_for(AllComponents.SITE) + projection.address.value_for(Microscopy.Site) for projection in illumination_projections } == { "1", diff --git a/tests/unit/test_source_bindings.py b/tests/unit/test_source_bindings.py index a3432d424d..f674bf8c00 100644 --- a/tests/unit/test_source_bindings.py +++ b/tests/unit/test_source_bindings.py @@ -15,7 +15,6 @@ from polystore.virtual_workspace import SourcePixelRef from openhcs.constants import Microscope -from openhcs.constants.constants import AllComponents, GroupBy, VariableComponents from openhcs.constants.input_source import InputSource from openhcs.core import source_bindings as source_bindings_module from openhcs.core.artifacts import ( @@ -90,20 +89,22 @@ from openhcs.core.source_workspace_projection import VirtualWorkspaceSourceProjection from openhcs.core.steps.function_step import FunctionStep from openhcs.microscopes.source_schema import SourceSchemaFilenameParser +from openhcs.core.axes import AxisFamily +from openhcs.domains.microscopy.axes import Microscopy def test_component_selector_coerces_existing_component_vocabulary(): - selector = ComponentSelector(component=GroupBy.CHANNEL, value=1) + selector = ComponentSelector(component=Microscopy.Channel, value=1) - assert selector.component is AllComponents.CHANNEL + assert selector.component is Microscopy.Channel assert selector.value == "1" variable_selector = ComponentSelector( - component=VariableComponents.SITE, + component=Microscopy.Site, value="3", ) - assert variable_selector.component is AllComponents.SITE + assert variable_selector.component is Microscopy.Site def test_metadata_selector_preserves_and_uses_declared_scalar_type(): @@ -126,15 +127,15 @@ def test_metadata_selector_preserves_and_uses_declared_scalar_type(): def test_source_image_set_plane_members_are_exactly_the_step_stack_axes(): site_stack = SourceImageSetIdentityPolicy.from_plane_member_fields( - frozenset((AllComponents.SITE.value,)) + frozenset((Microscopy.Site.name,)) ) assert ( - site_stack.role(AllComponents.SITE) + site_stack.role(Microscopy.Site) is SourceImageSetComponentRole.IMAGE_PLANE_MEMBER ) assert ( - site_stack.role(AllComponents.CHANNEL) + site_stack.role(Microscopy.Channel) is SourceImageSetComponentRole.IMAGE_SET_AXIS ) @@ -144,16 +145,16 @@ def test_source_image_set_policy_uses_binding_and_source_stack_declarations(): bindings=( NamedSourceBinding( alias="DNA", - component_identity=(ComponentSelector("channel", "1"),), + component_identity=(ComponentSelector(Microscopy.Channel, "1"),), ), ), - source_stack_components=(AllComponents.Z_INDEX,), + source_stack_components=(Microscopy.ZIndex,), ) policy = SourceImageSetIdentityPolicy.from_source_bindings(source_bindings) assert policy.plane_member_components == frozenset( - (AllComponents.CHANNEL, AllComponents.Z_INDEX) + (Microscopy.Channel, Microscopy.ZIndex) ) @@ -410,7 +411,7 @@ def test_step_source_bindings_inherit_plate_source_bindings_for_snapshot(): PipelineConfig( source_bindings_config=LazySourceBindingsConfig( bindings=(binding,), - source_stack_components=(AllComponents.Z_INDEX,), + source_stack_components=(Microscopy.ZIndex,), grouping_metadata_fields=("Plate",), metadata_fields=metadata_fields, ), @@ -433,14 +434,14 @@ def test_step_source_bindings_inherit_plate_source_bindings_for_snapshot(): ObjectStateRegistry.clear() assert snapshot.source_bindings.bindings == (binding,) - assert snapshot.source_bindings.source_stack_components == (AllComponents.Z_INDEX,) + assert snapshot.source_bindings.source_stack_components == (Microscopy.ZIndex,) assert snapshot.source_bindings.grouping_metadata_fields == ("Plate",) assert snapshot.source_bindings.metadata_fields == metadata_fields compiled = CompiledSourceBindingPlan.from_config( snapshot.source_bindings, ) assert compiled.bindings == (binding,) - assert compiled.source_stack_components == (AllComponents.Z_INDEX,) + assert compiled.source_stack_components == (Microscopy.ZIndex,) assert compiled.metadata_fields == metadata_fields assert compiled.has_primary_content assert pickle.loads(pickle.dumps(compiled)) == compiled @@ -558,7 +559,7 @@ def test_pipeline_start_binding_groups_do_not_mutate_resolved_enabled_state(): binding = NamedSourceBinding( alias="DNA", component_identity=( - ComponentSelector(component=AllComponents.CHANNEL, value="1"), + ComponentSelector(component=Microscopy.Channel, value="1"), ), ) source_bindings = StepSourceBindingsConfig( @@ -574,7 +575,7 @@ def test_pipeline_start_binding_groups_do_not_mutate_resolved_enabled_state(): assert source_bindings.enabled is False assert source_binding_group_keys_for_group_by( source_bindings, - GroupBy.CHANNEL, + Microscopy.Channel, ) == ("1",) assert ( source_bindings.for_input_source(InputSource.PIPELINE_START) is source_bindings @@ -596,7 +597,7 @@ def test_source_lineage_requires_its_declared_cursor_artifact() -> None: alias="DNA", component_identity=( ComponentSelector( - component=AllComponents.CHANNEL, + component=Microscopy.Channel, value="1", ), ), @@ -606,7 +607,7 @@ def test_source_lineage_requires_its_declared_cursor_artifact() -> None: with pytest.raises(ValueError, match="lineage.*unavailable source"): source_bindings.component_group_keys_for_artifact_specs( - AllComponents.CHANNEL, + Microscopy.Channel, (derived,), ArtifactSpecCollection(()), ) @@ -626,7 +627,7 @@ def test_source_lineage_resolves_consumer_view_to_active_artifact_binding() -> N alias="DNA", component_identity=( ComponentSelector( - component=AllComponents.CHANNEL, + component=Microscopy.Channel, value="1", ), ), @@ -635,7 +636,7 @@ def test_source_lineage_resolves_consumer_view_to_active_artifact_binding() -> N ) assert source_bindings.component_group_keys_for_artifact_specs( - AllComponents.CHANNEL, + Microscopy.Channel, (derived.for_plan_type(ArtifactInputPlan),), ArtifactSpecCollection((source, derived)), ) == ("1",) @@ -776,7 +777,7 @@ def test_source_bindings_expose_generic_resolution_requirements(): NamedSourceBinding( alias="DNA", selector=SourceSelector( - components=(ComponentSelector(AllComponents.CHANNEL, "1"),) + components=(ComponentSelector(Microscopy.Channel, "1"),) ), ), NamedSourceBinding( @@ -786,23 +787,25 @@ def test_source_bindings_expose_generic_resolution_requirements(): ) ) - assert config.requires_step_input_channel_stack + assert config.requires_step_input_component_stack((Microscopy.Channel,)) assert config.requires_pipeline_start_resolution assert config.bindings[0].requires_selector_resolution - assert not config.bindings[1].requires_step_input_channel_stack + assert not config.bindings[1].requires_step_input_component_stack( + (Microscopy.Channel,) + ) def test_component_identity_owns_realized_source_group_values() -> None: binding = NamedSourceBinding( alias="DNA", selector=SourceSelector( - components=(ComponentSelector(AllComponents.CHANNEL, "1"),), + components=(ComponentSelector(Microscopy.Channel, "1"),), ), - component_identity=(ComponentSelector(AllComponents.CHANNEL, "DNA"),), + component_identity=(ComponentSelector(Microscopy.Channel, "DNA"),), ) assert binding.component_values( - AllComponents.CHANNEL, + Microscopy.Channel, realized_source_metadata=( {"channel": 1}, {"channel": 2}, @@ -814,12 +817,12 @@ def test_realized_component_values_are_scoped_by_source_selector(monkeypatch) -> binding = NamedSourceBinding( alias="DNA", selector=SourceSelector( - components=(ComponentSelector(AllComponents.CHANNEL, "1"),), + components=(ComponentSelector(Microscopy.Channel, "1"),), ), ) assert binding.component_values( - AllComponents.SITE, + Microscopy.Site, realized_source_metadata=( {"channel": 1, "site": 3}, {"channel": 2, "site": 7}, @@ -833,7 +836,7 @@ def test_realized_component_values_are_scoped_by_source_selector(monkeypatch) -> component: binding.component_values( component, realized_source_metadata=records ) - for component in AllComponents + for component in AxisFamily.active().axes } matched = [] original_match = NamedSourceBinding.matches_realized_source_metadata @@ -844,12 +847,12 @@ def record_match(owner, metadata): monkeypatch.setattr(NamedSourceBinding, "matches_realized_source_metadata", record_match) domains = binding.component_domains(realized_source_metadata=iter(records)) - assert {component: domains.get(component, ()) for component in AllComponents} == expected + assert {component: domains.get(component, ()) for component in AxisFamily.active().axes} == expected assert matched == records - assert domains[AllComponents.SITE] == ("3",) - assert domains[AllComponents.Z_INDEX] == ("4", "5") + assert domains[Microscopy.Site] == ("3",) + assert domains[Microscopy.ZIndex] == ("4", "5") records[0]["channel"] = 2 - assert AllComponents.SITE not in binding.component_domains( + assert Microscopy.Site not in binding.component_domains( realized_source_metadata=records ) @@ -861,8 +864,8 @@ def test_compiled_source_binding_plan_preserves_named_selectors(): alias="OrigBlue", selector=SourceSelector( components=( - ComponentSelector("channel", "1"), - ComponentSelector(AllComponents.SITE, "3"), + ComponentSelector(Microscopy.Channel, "1"), + ComponentSelector(Microscopy.Site, "3"), ), metadata=(MetadataSelector("stain", "DAPI"),), ), @@ -912,7 +915,7 @@ def test_compiled_source_binding_plan_preserves_named_selectors(): assert plan.match_plan.method is SourceBindingMatchMethod.METADATA binding = plan.bindings[0] assert binding.alias == "OrigBlue" - assert binding.selector.components[0].component is AllComponents.CHANNEL + assert binding.selector.components[0].component is Microscopy.Channel assert binding.selector.metadata[0].field == "stain" assert plan.binding_for_alias("OrigBlue") == binding assert plan.binding_for_alias("Missing") is None @@ -925,7 +928,7 @@ def test_pipeline_start_binding_does_not_force_full_source_universe(): NamedSourceBinding( alias="OrigBlue", selector=SourceSelector( - components=(ComponentSelector(AllComponents.CHANNEL, "1"),), + components=(ComponentSelector(Microscopy.Channel, "1"),), ), origin=SourceBindingOrigin.PIPELINE_START, ), @@ -999,13 +1002,7 @@ def test_alias_only_step_bindings_filter_and_order_workspace_projections() -> No ) source_projections = { virtual_path: SourcePlaneProjection( - address=OpenHCSPlaneAddress.from_values( - well="R04C09", - site="11", - channel=channel, - z_index="1", - timepoint="1", - ), + address=OpenHCSPlaneAddress(((Microscopy.Well, "R04C09"), (Microscopy.Site, "11"), (Microscopy.Channel, channel), (Microscopy.ZIndex, "1"), (Microscopy.Timepoint, "1"))), ref=SourcePixelRef("disk", f"/source/ch{channel}.tiff"), source_alias=binding.alias, ) @@ -1075,7 +1072,7 @@ def test_narrow_step_binding_uses_exact_workspace_provenance_identity(): selector=SourceSelector( metadata=(MetadataSelector("ChannelNumber", channel),), ), - component_identity=(ComponentSelector(AllComponents.CHANNEL, channel),), + component_identity=(ComponentSelector(Microscopy.Channel, channel),), ) for alias, channel in (("DNA", "2"), ("Mito", "1"), ("Membrane", "0")) ) @@ -1207,8 +1204,8 @@ def test_source_binding_members_use_exact_source_identity_without_metadata_axes( "timepoint": "1", } coordinates = tuple( - ComponentSelector(component, metadata[component.value]) - for component in AllComponents + ComponentSelector(component, metadata[component.name]) + for component in AxisFamily.active().axes ) primary = NamedSourceBinding(alias="SavedImage", component_identity=coordinates) objects = NamedSourceBinding( @@ -1264,7 +1261,7 @@ def test_source_binding_members_load_one_store_for_multiple_matching_identities( selector=SourceSelector( metadata=(MetadataSelector("ChannelNumber", "0"),), ), - component_identity=(ComponentSelector(AllComponents.CHANNEL, "0"),), + component_identity=(ComponentSelector(Microscopy.Channel, "0"),), ) virtual_path = "A01_s001_w0_z001_t001.tif" source_path = "/source/channel_0.tif" @@ -1339,7 +1336,7 @@ def test_source_binding_members_canonicalize_declared_physical_spellings(aliases NamedSourceBinding( alias=alias, selector=SourceSelector(metadata=(MetadataSelector("channel", channel),)), - component_identity=(ComponentSelector(AllComponents.CHANNEL, channel),), + component_identity=(ComponentSelector(Microscopy.Channel, channel),), ) for alias, channel in zip(aliases, map(str, range(1, len(aliases) + 1)), strict=True) ) @@ -1392,7 +1389,7 @@ def test_source_binding_members_collapse_lookup_aliases_of_same_projection(): binding = NamedSourceBinding(alias="OriginalPhysical") projections = tuple( SourcePlaneProjection( - address=OpenHCSPlaneAddress.from_values("A01", "1", "1", z, "1"), + address=OpenHCSPlaneAddress(((Microscopy.Well, "A01"), (Microscopy.Site, "1"), (Microscopy.Channel, "1"), (Microscopy.ZIndex, z), (Microscopy.Timepoint, "1"))), ref=SourcePixelRef("disk", source_path), source_alias=binding.alias, ) for z in (0, 1) @@ -1622,13 +1619,7 @@ def test_virtual_workspace_source_matching_uses_declared_filter_identity(): def test_virtual_workspace_source_matching_requires_exact_projection_binding(): - address = OpenHCSPlaneAddress.from_values( - well="A01", - site="1", - channel="1", - z_index="1", - timepoint="1", - ) + address = OpenHCSPlaneAddress(((Microscopy.Well, "A01"), (Microscopy.Site, "1"), (Microscopy.Channel, "1"), (Microscopy.ZIndex, "1"), (Microscopy.Timepoint, "1"))) original_path = "A01_s001_w1_z001_t001.tif" illumination_path = f"_source/Illumination/{original_path}" original = SourcePlaneProjection( @@ -1698,7 +1689,7 @@ def test_compiled_source_binding_plan_round_trips_through_pickle(): NamedSourceBinding( alias="OrigBlue", selector=SourceSelector( - components=(ComponentSelector("channel", "1"),), + components=(ComponentSelector(Microscopy.Channel, "1"),), ), origin=SourceBindingOrigin.STEP_INPUT, ), diff --git a/tests/unit/test_source_bound_matched_image_set_anchors.py b/tests/unit/test_source_bound_matched_image_set_anchors.py index c52b9b1763..8b8974ef7c 100644 --- a/tests/unit/test_source_bound_matched_image_set_anchors.py +++ b/tests/unit/test_source_bound_matched_image_set_anchors.py @@ -5,7 +5,6 @@ import pytest from polystore.virtual_workspace import SourcePixelRef -from openhcs.constants.constants import AllComponents from openhcs.core.artifacts import ( ArtifactMeasurementSubjectRelation, ArtifactOutputPlan, @@ -47,6 +46,7 @@ FunctionStepExecutor, ) from openhcs.microscopes.source_schema import SourceSchemaFilenameParser +from openhcs.domains.microscopy.axes import Microscopy SOURCE_ALIASES = ( ("OrigER", "2"), @@ -101,7 +101,7 @@ def consume(*, payload): bindings=( NamedSourceBinding( alias="OrigDNA", - component_identity=(ComponentSelector(AllComponents.CHANNEL, "1"),), + component_identity=(ComponentSelector(Microscopy.Channel, "1"),), ), ), ) @@ -129,10 +129,10 @@ def _source_bindings() -> tuple[NamedSourceBinding, ...]: NamedSourceBinding( alias=alias, selector=SourceSelector( - components=(ComponentSelector(AllComponents.CHANNEL, channel),), + components=(ComponentSelector(Microscopy.Channel, channel),), ), origin=SourceBindingOrigin.PIPELINE_START, - component_identity=(ComponentSelector(AllComponents.CHANNEL, channel),), + component_identity=(ComponentSelector(Microscopy.Channel, channel),), ) for alias, channel in SOURCE_ALIASES ) @@ -236,7 +236,7 @@ def measure_images(image): if shared_output or output_spec.name == "AggregateMeasurements" else (binding.component_identity[0].value,) ), - group_component=AllComponents.CHANNEL, + group_component=Microscopy.Channel, relations=output_spec.relations, ) for output_spec, binding in zip( @@ -258,7 +258,7 @@ def measure_images(image): source_binding_plan=source_binding_plan, execution_group_scope=ComponentGroupScope.from_raw( tuple(binding.component_identity[0].value for binding in compiled_bindings), - component=AllComponents.CHANNEL, + component=Microscopy.Channel, ), compiled_function_pattern=compiled_pattern, ) @@ -430,7 +430,7 @@ def measure_hoechst(image): source_binding_plan=source_binding_plan, execution_group_scope=ComponentGroupScope.from_raw( ("2", "1"), - component=AllComponents.CHANNEL, + component=Microscopy.Channel, ), compiled_function_pattern=compiled_pattern, ) @@ -490,7 +490,7 @@ def identify_bodies(image): source_binding_plan=CompiledSourceBindingPlan(bindings=(binding,)), execution_group_scope=ComponentGroupScope.from_raw( ("2",), - component=AllComponents.CHANNEL, + component=Microscopy.Channel, ), compiled_function_pattern=compile_function_pattern( identify_bodies, @@ -505,13 +505,7 @@ def identify_bodies(image): aliases = ("Hoechst", "SMI312") projections = { path: SourcePlaneProjection( - address=OpenHCSPlaneAddress.from_values( - well="A01", - site="1", - channel=channel, - z_index="1", - timepoint="1", - ), + address=OpenHCSPlaneAddress(((Microscopy.Well, "A01"), (Microscopy.Site, "1"), (Microscopy.Channel, channel), (Microscopy.ZIndex, "1"), (Microscopy.Timepoint, "1"))), ref=SourcePixelRef("disk", f"/source/{path}"), source_alias=alias, ) @@ -563,10 +557,10 @@ def test_complete_source_set_templates_preserve_each_execution_group_anchor( NamedSourceBinding( alias=alias, selector=SourceSelector( - components=(ComponentSelector(AllComponents.CHANNEL, channel),), + components=(ComponentSelector(Microscopy.Channel, channel),), ), origin=SourceBindingOrigin.PIPELINE_START, - component_identity=(ComponentSelector(AllComponents.CHANNEL, channel),), + component_identity=(ComponentSelector(Microscopy.Channel, channel),), ) for alias, channel in (("OrigStain1", "1"), ("OrigStain2", "2")) ) @@ -591,7 +585,7 @@ def align_source_set(image): path="/memory/SourceSetMeasurements.pkl", artifact_type=measurements.artifact_type, group_keys=("1", "2"), - group_component=AllComponents.SITE, + group_component=Microscopy.Site, relations=measurements.relations, ) plan = SimpleNamespace( @@ -607,7 +601,7 @@ def align_source_set(image): ), execution_group_scope=ComponentGroupScope.from_raw( ("1", "2"), - component=AllComponents.SITE, + component=Microscopy.Site, ), compiled_function_pattern=compile_function_pattern( align_source_set, @@ -623,13 +617,7 @@ def align_source_set(image): aliases = ("OrigStain1", "OrigStain2") * 2 projections = { path: SourcePlaneProjection( - address=OpenHCSPlaneAddress.from_values( - well="A01", - site=str(site), - channel=str(channel), - z_index="1", - timepoint="1", - ), + address=OpenHCSPlaneAddress(((Microscopy.Well, "A01"), (Microscopy.Site, str(site)), (Microscopy.Channel, str(channel)), (Microscopy.ZIndex, "1"), (Microscopy.Timepoint, "1"))), ref=SourcePixelRef("disk", f"/source/{path}"), source_alias=alias, ) @@ -679,7 +667,7 @@ def test_static_site_groups_do_not_cross_project_natural_source_set_templates( filters=(), ), origin=SourceBindingOrigin.PIPELINE_START, - component_identity=(ComponentSelector(AllComponents.CHANNEL, channel),), + component_identity=(ComponentSelector(Microscopy.Channel, channel),), ) for alias, channel in (("OrigStain1", "1"), ("OrigStain2", "2")) ) @@ -719,7 +707,7 @@ def align_source_set(image): path=f"/memory/{spec.name}.pkl", artifact_type=spec.artifact_type, group_keys=("1", "2"), - group_component=AllComponents.SITE, + group_component=Microscopy.Site, relations=spec.relations, ) for spec in output_specs @@ -737,7 +725,7 @@ def align_source_set(image): ), execution_group_scope=ComponentGroupScope.from_raw( ("1", "2"), - component=AllComponents.SITE, + component=Microscopy.Site, ), compiled_function_pattern=compile_function_pattern( align_source_set, @@ -752,13 +740,7 @@ def align_source_set(image): ) projections = { path: SourcePlaneProjection( - address=OpenHCSPlaneAddress.from_values( - well="A01", - site=str(site), - channel=str(channel), - z_index="1", - timepoint="1", - ), + address=OpenHCSPlaneAddress(((Microscopy.Well, "A01"), (Microscopy.Site, str(site)), (Microscopy.Channel, str(channel)), (Microscopy.ZIndex, "1"), (Microscopy.Timepoint, "1"))), ref=SourcePixelRef("disk", f"/source/{path}"), source_alias=f"OrigStain{channel}", ) diff --git a/tests/unit/test_source_image_provenance.py b/tests/unit/test_source_image_provenance.py index 03b2716f36..a3b3943ea8 100644 --- a/tests/unit/test_source_image_provenance.py +++ b/tests/unit/test_source_image_provenance.py @@ -3,7 +3,6 @@ import numpy as np import pytest -from openhcs.constants.constants import AllComponents from openhcs.core.runtime_image_values import ( ImagePayloadMetadata, image_payload_data, @@ -22,6 +21,8 @@ SourceImageProvenancePlanes, ) from openhcs.core.source_matching import SourceImageSetIdentityPolicy +from openhcs.core.axes import AxisFamily +from openhcs.domains.microscopy.axes import Microscopy def test_source_provenance_projects_scalar_image_set_identity() -> None: @@ -33,7 +34,7 @@ def test_source_provenance_projects_scalar_image_set_identity() -> None: "channel": "1", }, ) - policy = SourceImageSetIdentityPolicy(frozenset((AllComponents.CHANNEL,))) + policy = SourceImageSetIdentityPolicy(frozenset((Microscopy.Channel,))) identities = provenance.image_set_identities(policy) @@ -57,7 +58,7 @@ def test_source_provenance_preserves_plane_positions_before_axis_deduplication() ), ), ) - policy = SourceImageSetIdentityPolicy(frozenset((AllComponents.CHANNEL,))) + policy = SourceImageSetIdentityPolicy(frozenset((Microscopy.Channel,))) plane_identities = provenance.image_set_plane_identities(policy) axis = provenance.image_set_axis(policy) @@ -93,16 +94,16 @@ def test_plane_coordinate_reads_preserve_runtime_scope_and_scalar_fallback() -> assert dict(provenance.component_metadata_for_plane(0)) == { "well": "A01", "site": "1", "channel": "1", "timepoint": "3", } - assert provenance.varying_plane_component_values(tuple(AllComponents)) == { + assert provenance.varying_plane_component_values(AxisFamily.active().axes) == { "site": ("1", "2"), "channel": ("1", "2"), } assert provenance.require_common_component_values( - (AllComponents.WELL, AllComponents.TIMEPOINT) - ) == ((AllComponents.WELL, "A01"), (AllComponents.TIMEPOINT, "3")) + (Microscopy.Well, Microscopy.Timepoint) + ) == ((Microscopy.Well, "A01"), (Microscopy.Timepoint, "3")) with pytest.raises(ValueError, match="'site' is not fixed"): - provenance.require_common_component_values((AllComponents.SITE,)) + provenance.require_common_component_values((Microscopy.Site,)) identities = provenance.image_set_plane_identities( - SourceImageSetIdentityPolicy(frozenset((AllComponents.CHANNEL,))) + SourceImageSetIdentityPolicy(frozenset((Microscopy.Channel,))) ) assert len(identities) == 2 assert tuple(next(iter(value)).components for value in identities) == ( @@ -111,8 +112,8 @@ def test_plane_coordinate_reads_preserve_runtime_scope_and_scalar_fallback() -> ) provenance.source_identity.component_metadata = {"well": "B02", "timepoint": "4"} assert provenance.require_common_component_values( - (AllComponents.WELL, AllComponents.TIMEPOINT) - ) == ((AllComponents.WELL, "B02"), (AllComponents.TIMEPOINT, "4")) + (Microscopy.Well, Microscopy.Timepoint) + ) == ((Microscopy.Well, "B02"), (Microscopy.Timepoint, "4")) def test_source_provenance_axis_retains_distinct_image_sets() -> None: @@ -128,7 +129,7 @@ def test_source_provenance_axis_retains_distinct_image_sets() -> None: ), ), ) - policy = SourceImageSetIdentityPolicy(frozenset((AllComponents.CHANNEL,))) + policy = SourceImageSetIdentityPolicy(frozenset((Microscopy.Channel,))) axis = provenance.image_set_axis(policy) diff --git a/tests/unit/test_source_image_set_identity_policy.py b/tests/unit/test_source_image_set_identity_policy.py index b163730e82..cf46932252 100644 --- a/tests/unit/test_source_image_set_identity_policy.py +++ b/tests/unit/test_source_image_set_identity_policy.py @@ -2,7 +2,6 @@ import pytest -from openhcs.constants.constants import AllComponents, GroupBy from openhcs.core.component_group_scope import RuntimeExecutionAxisScope from openhcs.core.source_bindings import ( ComponentSelector, @@ -18,6 +17,7 @@ from openhcs.interop.cellprofiler.image_set_numbering import ( CellProfilerImageSetNumbering, ) +from openhcs.domains.microscopy.axes import Microscopy def _bindings(*, stack=(), selectors=False): @@ -36,11 +36,11 @@ def _bindings(*, stack=(), selectors=False): tuple( ComponentSelector(component, value) for component, value in ( - (AllComponents.WELL, "A01"), - (AllComponents.SITE, "1"), - (AllComponents.CHANNEL, channel), - (AllComponents.Z_INDEX, "1"), - (AllComponents.TIMEPOINT, "1"), + (Microscopy.Well, "A01"), + (Microscopy.Site, "1"), + (Microscopy.Channel, channel), + (Microscopy.ZIndex, "1"), + (Microscopy.Timepoint, "1"), ) ), ) @@ -54,11 +54,11 @@ def test_shared_binding_coordinates_remain_field_axes(selectors): _bindings(selectors=selectors) ) - assert policy.plane_member_components == frozenset((AllComponents.CHANNEL,)) + assert policy.plane_member_components == frozenset((Microscopy.Channel,)) @pytest.mark.parametrize( - "component", (AllComponents.SITE, AllComponents.Z_INDEX, AllComponents.TIMEPOINT) + "component", (Microscopy.Site, Microscopy.ZIndex, Microscopy.Timepoint) ) def test_explicit_stack_and_group_axes_override_shared_coordinates(component): for policy in ( @@ -70,24 +70,24 @@ def test_explicit_stack_and_group_axes_override_shared_coordinates(component): ), ): assert policy.plane_member_components == frozenset( - (AllComponents.CHANNEL, component) + (Microscopy.Channel, component) ) @pytest.mark.parametrize( "component", ( - AllComponents.WELL, - AllComponents.SITE, - AllComponents.Z_INDEX, - AllComponents.TIMEPOINT, + Microscopy.Well, + Microscopy.Site, + Microscopy.ZIndex, + Microscopy.Timepoint, ), ) def test_numbering_combines_channels_but_preserves_independent_fields(component): policy = SourceImageSetIdentityPolicy.from_source_bindings(_bindings()) numbering = CellProfilerImageSetNumbering(policy) scope = RuntimeExecutionAxisScope.from_raw( - "A01", component=AllComponents.CHANNEL, value="1" + "A01", component=Microscopy.Channel, value="1" ) metadata = { "well": "A01", @@ -103,7 +103,7 @@ def test_numbering_combines_channels_but_preserves_independent_fields(component) source_path=f"/synthetic/field-{field_value}-plane-{channel}.tif", source_component_metadata={ **metadata, - component.value: field_value, + component.name: field_value, "channel": channel, }, ) @@ -122,11 +122,11 @@ def test_component_assignment_owns_identity_over_physical_selector(): NamedSourceBinding( alias=f"Plane{channel}", selector=SourceSelector( - components=(ComponentSelector(AllComponents.SITE, physical_site),) + components=(ComponentSelector(Microscopy.Site, physical_site),) ), component_identity=( - ComponentSelector(AllComponents.SITE, "1"), - ComponentSelector(AllComponents.CHANNEL, channel), + ComponentSelector(Microscopy.Site, "1"), + ComponentSelector(Microscopy.Channel, channel), ), ) for channel, physical_site in (("1", "7"), ("2", "8")) @@ -134,7 +134,7 @@ def test_component_assignment_owns_identity_over_physical_selector(): ) policy = SourceImageSetIdentityPolicy.from_source_bindings(declarations) - assert policy.plane_member_components == frozenset((AllComponents.CHANNEL,)) + assert policy.plane_member_components == frozenset((Microscopy.Channel,)) def test_path_identity_stays_distinct_without_semantic_field_coordinates(): @@ -155,10 +155,10 @@ def test_pipeline_config_compiles_the_same_paired_field_identity_policy(): ) config = PipelineConfig( - processing_config=LazyProcessingConfig(group_by=GroupBy.CHANNEL), + processing_config=LazyProcessingConfig(group_by=Microscopy.Channel), source_bindings_config=LazySourceBindingsConfig(bindings=_bindings().bindings), ) policy = SourceImageSetIdentityPolicy.from_pipeline_config(config) - assert policy.plane_member_components == frozenset((AllComponents.CHANNEL,)) + assert policy.plane_member_components == frozenset((Microscopy.Channel,)) diff --git a/tests/unit/test_source_matching.py b/tests/unit/test_source_matching.py index 5243b09e56..86e7b03739 100644 --- a/tests/unit/test_source_matching.py +++ b/tests/unit/test_source_matching.py @@ -1,6 +1,5 @@ import pytest -from openhcs.constants.constants import AllComponents from openhcs.core.source_bindings import ( SourceFilterClause, SourceFilterMatchType, @@ -20,6 +19,8 @@ with_source_component_metadata, with_original_source_metadata, ) +from openhcs.core.axes import Axis +from openhcs.domains.microscopy.axes import Microscopy @pytest.mark.parametrize( @@ -97,14 +98,14 @@ def test_source_filters_match_flat_conjunction_of_disjunction_groups() -> None: @pytest.mark.parametrize( ("field", "component"), ( - ("well", AllComponents.WELL), - ("Metadata_Site", AllComponents.SITE), - ("ChannelNumber", AllComponents.CHANNEL), + ("well", Microscopy.Well), + ("Metadata_Site", Microscopy.Site), + ("ChannelNumber", Microscopy.Channel), ), ) def test_source_metadata_component_matches_semantic_component_names( field: str, - component: AllComponents, + component: type[Axis], ): assert source_metadata_component(field) is component @@ -112,8 +113,8 @@ def test_source_metadata_component_matches_semantic_component_names( def test_source_component_metadata_value_matches_alias_fields(): metadata = {"ChannelNumber": "01", "Metadata_Site": "A"} - assert source_component_metadata_value(metadata, AllComponents.CHANNEL) == "01" - assert source_component_metadata_value(metadata, AllComponents.SITE) == "A" + assert source_component_metadata_value(metadata, Microscopy.Channel) == "01" + assert source_component_metadata_value(metadata, Microscopy.Site) == "A" def test_semantic_well_value_uses_registered_compound_component_projection(): @@ -125,14 +126,14 @@ def test_semantic_well_value_uses_registered_compound_component_projection(): def test_source_component_metadata_value_prefers_canonical_field_over_alias(): metadata = {"ChannelNumber": "00", "channel": "3"} - assert source_component_metadata_value(metadata, AllComponents.CHANNEL) == "3" - assert source_component_metadata_raw_value(metadata, AllComponents.CHANNEL) == "3" + assert source_component_metadata_value(metadata, Microscopy.Channel) == "3" + assert source_component_metadata_raw_value(metadata, Microscopy.Channel) == "3" def test_source_component_metadata_values_include_native_and_alias_fields(): metadata = {"channel": "1", "ChannelNumber": "00"} - assert source_component_metadata_values(metadata, AllComponents.CHANNEL) == ( + assert source_component_metadata_values(metadata, Microscopy.Channel) == ( "1", "00", ) @@ -147,7 +148,7 @@ def test_original_source_metadata_preserves_literal_selectors_without_axis_pollu assert source_metadata_value(metadata, "ChannelNumber") == "2" assert source_metadata_value(metadata, "channel") == "1" - assert source_component_metadata_values(metadata, AllComponents.CHANNEL) == ("1",) + assert source_component_metadata_values(metadata, Microscopy.Channel) == ("1",) def test_source_metadata_value_preserves_literal_and_component_ownership(): @@ -158,7 +159,7 @@ def test_source_metadata_value_preserves_literal_and_component_ownership(): ) assert source_metadata_value(metadata, "well") == "A01" - assert source_component_metadata_value(metadata, AllComponents.WELL) == "fields" + assert source_component_metadata_value(metadata, Microscopy.Well) == "fields" def test_source_metadata_value_requires_exact_literal_field_identity(): @@ -184,7 +185,7 @@ def test_with_source_component_metadata_replaces_alias_fields(): updated = with_source_component_metadata( metadata, - AllComponents.WELL, + Microscopy.Well, "W001", ) @@ -193,7 +194,7 @@ def test_with_source_component_metadata_replaces_alias_fields(): "ChannelNumber": "1", "well": "W001", } - assert source_component_metadata_values(updated, AllComponents.WELL) == ("W001",) + assert source_component_metadata_values(updated, Microscopy.Well) == ("W001",) def test_source_metadata_values_equal_preserves_declared_scalar_identity(): diff --git a/tests/unit/test_source_metadata_live_mutation.py b/tests/unit/test_source_metadata_live_mutation.py index 935fc63373..bc41db0ab6 100644 --- a/tests/unit/test_source_metadata_live_mutation.py +++ b/tests/unit/test_source_metadata_live_mutation.py @@ -2,7 +2,6 @@ import pytest -from openhcs.constants.constants import AllComponents from openhcs.core.source_binding_selection import DeclaredSourceMetadataRecord from openhcs.core.source_matching import ( ORIGINAL_SOURCE_METADATA_FIELD, @@ -11,6 +10,7 @@ source_component_metadata_values, source_metadata_value, ) +from openhcs.domains.microscopy.axes import Microscopy @pytest.mark.parametrize("readonly_outer", (False, True)) @@ -20,14 +20,14 @@ def test_metadata_queries_observe_scalar_mutation(readonly_outer): assert source_metadata_value(metadata, "well") == "A01" assert semantic_source_metadata_value(metadata, "well") == "A01" - assert source_component_metadata_values(metadata, AllComponents.WELL) == ("A01",) + assert source_component_metadata_values(metadata, Microscopy.Well) == ("A01",) backing["well"] = "A02" assert source_metadata_value(metadata, "well") == "A02" assert semantic_source_metadata_value(metadata, "well") == "A02" - assert source_component_metadata_value(metadata, AllComponents.WELL) == "A02" - assert source_component_metadata_values(metadata, AllComponents.WELL) == ("A02",) + assert source_component_metadata_value(metadata, Microscopy.Well) == "A02" + assert source_component_metadata_values(metadata, Microscopy.Well) == ("A02",) @pytest.mark.parametrize( @@ -44,8 +44,8 @@ def test_literal_queries_observe_nested_original_mutation(view): assert source_metadata_value(metadata, "Well") == "LiteralB" assert semantic_source_metadata_value(metadata, "Well") == "LiteralB" - assert source_component_metadata_value(metadata, AllComponents.WELL) == "A01" - assert source_component_metadata_values(metadata, AllComponents.WELL) == ("A01",) + assert source_component_metadata_value(metadata, Microscopy.Well) == "A01" + assert source_component_metadata_values(metadata, Microscopy.Well) == ("A01",) def test_live_alias_queries_preserve_priority_cardinality_and_null_fallback(): @@ -57,8 +57,8 @@ def test_live_alias_queries_preserve_priority_cardinality_and_null_fallback(): ORIGINAL_SOURCE_METADATA_FIELD: original, } assert source_metadata_value(metadata, "ChannelNumber") == "literal" - assert source_component_metadata_value(metadata, AllComponents.CHANNEL) == "1" - assert source_component_metadata_values(metadata, AllComponents.CHANNEL) == ( + assert source_component_metadata_value(metadata, Microscopy.Channel) == "1" + assert source_component_metadata_values(metadata, Microscopy.Channel) == ( "1", "2", ) @@ -70,12 +70,12 @@ def test_live_alias_queries_preserve_priority_cardinality_and_null_fallback(): assert source_metadata_value(metadata, "ChannelNumber") == "3" assert semantic_source_metadata_value(metadata, "ChannelNumber") == "3" - assert source_component_metadata_value(metadata, AllComponents.CHANNEL) == "3" - assert source_component_metadata_values(metadata, AllComponents.CHANNEL) == ("3",) + assert source_component_metadata_value(metadata, Microscopy.Channel) == "3" + assert source_component_metadata_values(metadata, Microscopy.Channel) == ("3",) del metadata["ChannelNumber"] metadata["Metadata_Channel"] = None assert source_metadata_value(metadata, "ChannelNumber") is None assert semantic_source_metadata_value(metadata, "ChannelNumber") is None - assert source_component_metadata_values(metadata, AllComponents.CHANNEL) == () + assert source_component_metadata_values(metadata, Microscopy.Channel) == () diff --git a/tests/unit/test_source_metadata_owner.py b/tests/unit/test_source_metadata_owner.py index 67b40fea25..e343235abe 100644 --- a/tests/unit/test_source_metadata_owner.py +++ b/tests/unit/test_source_metadata_owner.py @@ -10,7 +10,6 @@ import pytest 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 ( ImagePayloadMetadata, @@ -54,6 +53,8 @@ VirtualWorkspaceSourceMetadataEntries, ) from python_introspect import to_jsonable +from openhcs.domains.microscopy.axes import Microscopy +from openhcs.core.axes import AxisFamily @pytest.mark.parametrize("owner", (ResolvedSourceMetadataRecord, DurableSourceMetadata)) @@ -103,9 +104,7 @@ def test_runtime_birth_canonicalizes_but_durable_and_derived_values_keep_literal assert derived["path"] == str(tmp_path / "image.tif") assert derived["new_path"] == spelling projection = SourcePlaneProjection( - address=OpenHCSPlaneAddress.from_values( - well="A01", site="1", channel="1", z_index="1", timepoint="1" - ), + address=OpenHCSPlaneAddress(((Microscopy.Well, "A01"), (Microscopy.Site, "1"), (Microscopy.Channel, "1"), (Microscopy.ZIndex, "1"), (Microscopy.Timepoint, "1"))), ref=SourcePixelRef("disk", "plane.tif"), source_metadata=derived, ) @@ -173,11 +172,11 @@ def test_owned_updates_replace_aliases_and_keep_original_literals(): ORIGINAL_SOURCE_METADATA_FIELD: {"ChannelNumber": "literal"}, } ) - updated = with_source_component_metadata(owner, AllComponents.CHANNEL, "3") + updated = with_source_component_metadata(owner, Microscopy.Channel, "3") assert isinstance(updated, DurableSourceMetadata) assert "ChannelNumber" not in updated assert source_metadata_value(updated, "ChannelNumber") == "literal" - assert source_component_metadata_values(updated, AllComponents.CHANNEL) == ("3",) + assert source_component_metadata_values(updated, Microscopy.Channel) == ("3",) assert owner["channel"] == "1" @@ -194,9 +193,9 @@ def __repr__(self): value.tag = "before" record = owner.from_mapping({"channel": value}) first = SourceImageIdentity(component_metadata=record) - assert source_component_metadata_value(record, AllComponents.CHANNEL) == "before" + assert source_component_metadata_value(record, Microscopy.Channel) == "before" value.tag = "after" - assert source_component_metadata_value(record, AllComponents.CHANNEL) == "after" + assert source_component_metadata_value(record, Microscopy.Channel) == "after" assert SourceImageIdentity(component_metadata=record).identity != first.identity assert first.identity[1] == (("channel", "before"),) @@ -210,13 +209,13 @@ def test_lazy_role_errors_are_unchanged_by_owned_construction(): ORIGINAL_SOURCE_METADATA_FIELD: 7, } ) - assert source_component_metadata_value(record, AllComponents.CHANNEL) == "1" + assert source_component_metadata_value(record, Microscopy.Channel) == "1" with pytest.raises(ValueError): - source_component_metadata_value(record, AllComponents.WELL) + source_component_metadata_value(record, Microscopy.Well) with pytest.raises(RuntimeError, match="must be a mapping"): source_metadata_value(record, "channel") with pytest.raises(RuntimeError, match="must be a mapping"): - source_component_metadata_values(record, AllComponents.CHANNEL) + source_component_metadata_values(record, Microscopy.Channel) @pytest.mark.parametrize("invalid", ([1], {"deep": {"unsupported": 1}}, object())) @@ -357,7 +356,7 @@ def test_owned_transport_stores_only_authoritative_fields_and_rebuilds_local_vie ) before = SourceImageIdentity(component_metadata=record).identity assert source_metadata_value(record, "literal") == "value" - assert source_component_metadata_value(record, AllComponents.WELL) == "A01" + assert source_component_metadata_value(record, Microscopy.Well) == "A01" assert record._views restored = serializer.loads(serializer.dumps(record)) assert isinstance(restored, owner) @@ -401,7 +400,7 @@ def test_ordered_component_batch_matches_sequential_raw_updates(): ORIGINAL_SOURCE_METADATA_FIELD: {"Well": "literal"}, } components = tuple( - (component, str(index)) for index, component in enumerate(AllComponents, 1) + (component, str(index)) for index, component in enumerate(AxisFamily.active().axes, 1) ) raw = dict(fields) for component, value in components: @@ -451,9 +450,7 @@ def test_stringified_key_collisions_keep_platform_map_last_value_at_owned_birth( durable = VirtualWorkspaceSourceMetadataEntries.normalize_metadata_fields(fields) assert tuple(durable.items()) == (("1", "last"),) projection = SourcePlaneProjection( - address=OpenHCSPlaneAddress.from_values( - well="A01", site="1", channel="1", z_index="1", timepoint="1" - ), + address=OpenHCSPlaneAddress(((Microscopy.Well, "A01"), (Microscopy.Site, "1"), (Microscopy.Channel, "1"), (Microscopy.ZIndex, "1"), (Microscopy.Timepoint, "1"))), ref=SourcePixelRef("disk", "plane.tif"), source_metadata=fields, ) @@ -508,9 +505,7 @@ def test_mapping_and_ordered_record_equality_namespaces_stay_separate(): lambda metadata: RuntimeSourceImageProvenancePlane(SourceImageIdentity(component_metadata=metadata)), lambda metadata: SourcePlaneIndexedMetadata(metadata, 0, 1), lambda metadata: SourcePlaneProjection( - address=OpenHCSPlaneAddress.from_values( - well="A01", site="1", channel="1", z_index="1", timepoint="1" - ), + address=OpenHCSPlaneAddress(((Microscopy.Well, "A01"), (Microscopy.Site, "1"), (Microscopy.Channel, "1"), (Microscopy.ZIndex, "1"), (Microscopy.Timepoint, "1"))), ref=SourcePixelRef("disk", "plane.tif"), source_metadata=metadata, ), diff --git a/tests/unit/test_source_projection.py b/tests/unit/test_source_projection.py index 5871a9745f..f6f5f2f22c 100644 --- a/tests/unit/test_source_projection.py +++ b/tests/unit/test_source_projection.py @@ -6,7 +6,6 @@ import pytest from polystore.bioformats_storage import BioFormatsPlaneRef -from openhcs.constants.constants import AllComponents from openhcs.core.artifacts import ImageArtifactType, ObjectLabelsArtifactType from openhcs.core.source_bindings import SourceProjectionRole from openhcs.core.source_metadata import ( @@ -21,6 +20,8 @@ SourceProjectionSet, ) from openhcs.microscopes.source_schema import SourceSchemaFilenameParser +from openhcs.core.axes import Axis +from openhcs.domains.microscopy.axes import Microscopy _OWNED_PROJECTION_MODULES = ( Path("openhcs/core/source_projection.py"), @@ -30,13 +31,7 @@ def test_projection_nominal_owners_declare_projection_semantics() -> None: - address = OpenHCSPlaneAddress.from_values( - well="A01", - site="1", - channel="1", - z_index="1", - timepoint="1", - ) + address = OpenHCSPlaneAddress(((Microscopy.Well, "A01"), (Microscopy.Site, "1"), (Microscopy.Channel, "1"), (Microscopy.ZIndex, "1"), (Microscopy.Timepoint, "1"))) plane = SourcePlaneProjection( address=address, ref=SourcePixelRef("disk", "plane.tif"), @@ -117,13 +112,7 @@ def test_source_projection_serializes_canonical_virtual_filename() -> None: projection_set = SourceProjectionSet( ( SourcePlaneProjection( - address=OpenHCSPlaneAddress.from_values( - well="A01", - site="1", - channel="2", - z_index="3", - timepoint="4", - ), + address=OpenHCSPlaneAddress(((Microscopy.Well, "A01"), (Microscopy.Site, "1"), (Microscopy.Channel, "2"), (Microscopy.ZIndex, "3"), (Microscopy.Timepoint, "4"))), ref=SourcePixelRef( backend="bioformats", backend_address=BioFormatsPlaneRef( @@ -171,34 +160,16 @@ def test_source_projection_serializes_canonical_virtual_filename() -> None: def test_source_plane_address_canonicalizes_numeric_axis_padding() -> None: - address = OpenHCSPlaneAddress.from_values( - well="01", - site="001", - channel="02", - z_index="003", - timepoint="0004", - ) + address = OpenHCSPlaneAddress(((Microscopy.Well, "01"), (Microscopy.Site, "001"), (Microscopy.Channel, "02"), (Microscopy.ZIndex, "003"), (Microscopy.Timepoint, "0004"))) - assert address == OpenHCSPlaneAddress.from_values( - well="01", - site="1", - channel="2", - z_index="3", - timepoint="4", - ) + assert address == OpenHCSPlaneAddress(((Microscopy.Well, "01"), (Microscopy.Site, "1"), (Microscopy.Channel, "2"), (Microscopy.ZIndex, "3"), (Microscopy.Timepoint, "4"))) def test_source_projection_rejects_metadata_component_conflict() -> None: projection_set = SourceProjectionSet( ( SourcePlaneProjection( - address=OpenHCSPlaneAddress.from_values( - well="A01", - site="1", - channel="2", - z_index="3", - timepoint="4", - ), + address=OpenHCSPlaneAddress(((Microscopy.Well, "A01"), (Microscopy.Site, "1"), (Microscopy.Channel, "2"), (Microscopy.ZIndex, "3"), (Microscopy.Timepoint, "4"))), ref=SourcePixelRef( backend="disk", backend_address="image.tif", @@ -221,25 +192,19 @@ def test_source_projection_rejects_metadata_component_conflict() -> None: @pytest.mark.parametrize( ("component", "source_value", "address_value"), ( - (AllComponents.WELL, "A01", "fields"), - (AllComponents.SITE, "7", "1"), - (AllComponents.CHANNEL, "9", "2"), - (AllComponents.Z_INDEX, "8", "3"), - (AllComponents.TIMEPOINT, "6", "4"), + (Microscopy.Well, "A01", "fields"), + (Microscopy.Site, "7", "1"), + (Microscopy.Channel, "9", "2"), + (Microscopy.ZIndex, "8", "3"), + (Microscopy.Timepoint, "6", "4"), ), ) def test_source_projection_preserves_provenance_owned_component_remaps( - component: AllComponents, + component: type[Axis], source_value: str, address_value: str, ) -> None: - address = OpenHCSPlaneAddress.from_values( - well="A01", - site="1", - channel="2", - z_index="3", - timepoint="4", - ).with_value(component, address_value) + address = OpenHCSPlaneAddress(((Microscopy.Well, "A01"), (Microscopy.Site, "1"), (Microscopy.Channel, "2"), (Microscopy.ZIndex, "3"), (Microscopy.Timepoint, "4"))).with_value(component, address_value) projection_set = SourceProjectionSet( ( SourcePlaneProjection( @@ -249,9 +214,9 @@ def test_source_projection_preserves_provenance_owned_component_remaps( backend_address="image.tif", ), source_metadata={ - component.value: source_value, + component.name: source_value, ORIGINAL_SOURCE_METADATA_FIELD: { - component.value: source_value, + component.name: source_value, }, }, ), @@ -267,21 +232,15 @@ def test_source_projection_preserves_provenance_owned_component_remaps( ) source_metadata = next(iter(metadata["source_metadata"].values())) - assert source_metadata[component.value] == address_value + assert source_metadata[component.name] == address_value assert ( - dict(SourceMetadataFields.original_items(source_metadata))[component.value] + dict(SourceMetadataFields.original_items(source_metadata))[component.name] == source_value ) def test_source_projection_rejects_duplicate_addresses() -> None: - address = OpenHCSPlaneAddress.from_values( - well="A01", - site="1", - channel="1", - z_index="1", - timepoint="1", - ) + address = OpenHCSPlaneAddress(((Microscopy.Well, "A01"), (Microscopy.Site, "1"), (Microscopy.Channel, "1"), (Microscopy.ZIndex, "1"), (Microscopy.Timepoint, "1"))) with pytest.raises(ValueError, match="Duplicate source projection address"): SourceProjectionSet( @@ -301,13 +260,7 @@ def test_source_projection_rejects_duplicate_addresses() -> None: def test_artifact_only_projection_set_serializes_typed_execution_anchors() -> None: projections = tuple( SourceArtifactProjection( - address=OpenHCSPlaneAddress.from_values( - well="A01", - site="1", - channel=str(channel), - z_index="1", - timepoint="1", - ), + address=OpenHCSPlaneAddress(((Microscopy.Well, "A01"), (Microscopy.Site, "1"), (Microscopy.Channel, str(channel)), (Microscopy.ZIndex, "1"), (Microscopy.Timepoint, "1"))), ref=SourcePixelRef("disk", source_path), source_alias=alias, artifact_kind=ObjectLabelsArtifactType, diff --git a/tests/unit/test_source_schema_filename_contract.py b/tests/unit/test_source_schema_filename_contract.py index e378b38b95..a0089528c1 100644 --- a/tests/unit/test_source_schema_filename_contract.py +++ b/tests/unit/test_source_schema_filename_contract.py @@ -2,13 +2,13 @@ import pytest -from openhcs.constants import AllComponents from openhcs.core.components.parser_metaprogramming import MissingFilenameComponentError from openhcs.core.steps.function_output_identity import ( FunctionOutputIdentity, IncompleteFunctionOutputFilenameIdentityError, ) from openhcs.microscopes.source_schema import SourceSchemaFilenameParser +from openhcs.core.axes import AxisFamily COMPONENTS = {"well": "A01", "site": "1", "channel": "2", "z_index": "3", "timepoint": "4"} @@ -24,14 +24,14 @@ def test_complete_scalar_filename_round_trips_exactly(): assert all(parsed.component_matches(component, value) for component, value in bound.declared_values()) -@pytest.mark.parametrize("component", tuple(AllComponents)) +@pytest.mark.parametrize("component", AxisFamily.active().axes) @pytest.mark.parametrize("missing", [None, ""]) def test_missing_scalar_component_keeps_its_nominal_identity(component, missing): - values = {**COMPONENTS, component.value: missing} + values = {**COMPONENTS, component.name: missing} parser = SourceSchemaFilenameParser() with pytest.raises(MissingFilenameComponentError) as error: parser.construct_filename(parser.bind_component_values(values, extension=".tif")) - assert error.value.component_name == component.value + assert error.value.component_name == component.name with pytest.raises(IncompleteFunctionOutputFilenameIdentityError) as wrapped: FunctionOutputIdentity(values, ".tif", "synthetic contract").filename(parser) - assert wrapped.value.component_name == component.value + assert wrapped.value.component_name == component.name diff --git a/tests/unit/test_source_tile_geometry.py b/tests/unit/test_source_tile_geometry.py index 2fa9782d1f..80aaa8a32a 100644 --- a/tests/unit/test_source_tile_geometry.py +++ b/tests/unit/test_source_tile_geometry.py @@ -12,7 +12,7 @@ from polystore.source_tile_geometry import SourceTileGeometry from polystore.tiff_header import TiffImageHeader -from openhcs.constants.constants import AllComponents, Backend +from openhcs.constants.constants import Backend from openhcs.core.callable_contract import CallableContract from openhcs.core.memory import numpy from openhcs.core.runtime_adapters import runtime_adapter @@ -43,6 +43,8 @@ _source_metadata, acquisition_tile_positions, ) +from openhcs.core.axes import Ungrouped +from openhcs.domains.microscopy.axes import Microscopy def _xml( @@ -258,8 +260,8 @@ def test_materialization_preserves_binding_axes_serialization_and_shared_sparse_ assert SourceTileLayout.metadata_grid_dimensions(projection) == [] assert { ( - p.address.value_for(AllComponents.SITE), - p.address.value_for(AllComponents.CHANNEL), + p.address.value_for(Microscopy.Site), + p.address.value_for(Microscopy.Channel), ) for p in projection.plane_projections } == {("1", "1"), ("1", "2"), ("3", "1"), ("3", "2")} @@ -395,7 +397,7 @@ def _verify_paired_stitched_mosaics( assert len(records) == 2 assert tuple( source_component_metadata_value( - record.source_component_metadata, AllComponents.CHANNEL + record.source_component_metadata, Microscopy.Channel ) for record in records ) == ("1", "2") @@ -468,7 +470,7 @@ def test_synthetic_pipeline_compiles_and_executes_positions_artifact_then_paired from objectstate import ObjectStateRegistry from objectstate.lazy_factory import ensure_global_config_context - from openhcs.constants.constants import GroupBy, Microscope, VariableComponents + from openhcs.constants.constants import Microscope from openhcs.core.config import ( AnalysisConsolidationConfig, GlobalPipelineConfig, @@ -545,7 +547,7 @@ def test_synthetic_pipeline_compiles_and_executes_positions_artifact_then_paired orchestrator = PipelineOrchestrator(plate, pipeline_config=config).initialize() if embedded: site_processing = LazyProcessingConfig( - variable_components=[VariableComponents.SITE], group_by=GroupBy.CHANNEL + variable_components=[Microscopy.Site], group_by=Microscopy.Channel ) steps = [ FunctionStep( @@ -565,8 +567,8 @@ def test_synthetic_pipeline_compiles_and_executes_positions_artifact_then_paired enabled=True, sub_dir="checkpoints" ), processing_config=LazyProcessingConfig( - variable_components=[VariableComponents.CHANNEL], - group_by=GroupBy.NONE, + variable_components=[Microscopy.Channel], + group_by=Ungrouped, input_source=InputSource.PREVIOUS_STEP, ), ), @@ -597,7 +599,7 @@ def test_synthetic_pipeline_compiles_and_executes_positions_artifact_then_paired edge.spec.name == "positions" for edge in consumer.artifact_input_edges ) assert context.step_plans[2].variable_components == [ - VariableComponents.CHANNEL + Microscopy.Channel ] result = orchestrator.execute_compiled_plate( execution_bundle=compilation, @@ -678,8 +680,8 @@ def test_synthetic_pipeline_compiles_and_executes_positions_artifact_then_paired FunctionStep( func=_verify_paired_stitched_mosaics, processing_config=LazyProcessingConfig( - variable_components=[VariableComponents.CHANNEL], - group_by=GroupBy.NONE, + variable_components=[Microscopy.Channel], + group_by=Ungrouped, input_source=InputSource.PIPELINE_START, ), ) diff --git a/tests/unit/test_step_input_artifact_origin.py b/tests/unit/test_step_input_artifact_origin.py index b4a0380169..715404e7ee 100644 --- a/tests/unit/test_step_input_artifact_origin.py +++ b/tests/unit/test_step_input_artifact_origin.py @@ -5,7 +5,6 @@ import numpy as np import pytest -from openhcs.constants.constants import AllComponents from openhcs.core.component_group_scope import RuntimeExecutionAxisScope from openhcs.core.runtime_adapters import RuntimeAdapterRequest from openhcs.core.runtime_image_values import ( @@ -27,6 +26,7 @@ SourceSelector, ) from openhcs.core.source_image_provenance import SourceImageProvenancePlanes +from openhcs.domains.microscopy.axes import Microscopy @pytest.mark.parametrize("alias", ("Raw", "Response")) @@ -64,7 +64,7 @@ def test_step_input_selects_current_component_planes_not_original_aliases(): ).payload_with(data) binding = NamedSourceBinding( alias="Processed2", - selector=SourceSelector(components=(ComponentSelector(AllComponents.CHANNEL, "2"),)), + selector=SourceSelector(components=(ComponentSelector(Microscopy.Channel, "2"),)), ) result = binding.project_step_input_payload(payload) @@ -74,7 +74,7 @@ def test_step_input_selects_current_component_planes_not_original_aliases(): assert image_payload_metadata(result).source_path == "/synthetic/ch2.tif" missing = NamedSourceBinding( alias="Absent", - selector=SourceSelector(components=(ComponentSelector(AllComponents.CHANNEL, "3"),)), + selector=SourceSelector(components=(ComponentSelector(Microscopy.Channel, "3"),)), ) with pytest.raises(ValueError, match="selects no current planes"): missing.project_step_input_payload(payload) @@ -129,7 +129,7 @@ def test_existing_alias_and_explicit_selector_must_agree(): ).payload_with(np.ones((2, 4, 5))) binding = NamedSourceBinding( alias="Raw1", - selector=SourceSelector(components=(ComponentSelector(AllComponents.CHANNEL, "2"),)), + selector=SourceSelector(components=(ComponentSelector(Microscopy.Channel, "2"),)), ) with pytest.raises(ValueError, match="selects no current planes"): binding.project_step_input_payload(payload) diff --git a/tests/unit/test_stream_component_semantics.py b/tests/unit/test_stream_component_semantics.py index 2cb1f19fb3..6ecb14bd98 100644 --- a/tests/unit/test_stream_component_semantics.py +++ b/tests/unit/test_stream_component_semantics.py @@ -2,7 +2,6 @@ import pytest -from openhcs.constants.constants import AllComponents from openhcs.core.runtime_plane_projection import RuntimePlaneAxis from openhcs.core.source_image_provenance import SourceImageProvenancePlanes from openhcs.core.source_image_provenance import SourceImageIdentity @@ -21,6 +20,8 @@ WorkerAssignmentPlan, WorkerLaneExecutionContext, ) +from openhcs.core.axes import AxisFamily +from openhcs.domains.microscopy.axes import Microscopy def test_streaming_domain_spans_worker_lanes_without_mirroring_worker_identity(): @@ -44,13 +45,13 @@ def test_streaming_domain_spans_worker_lanes_without_mirroring_worker_identity() assert lane.owned_wells == tuple(assignments.worker_assignments[slot]) provider = StreamExecutionAxisDomainProvider.build_for_component( context=context, - component=StreamExecutionAxisDomainProvider.axis_component, + component=AxisFamily.active().partition_axis().name, metadata_roots=(), ) domains.append(provider.domain_metadata_items()) assert domains[0] == domains[1] assert { - item[StreamExecutionAxisDomainProvider.axis_component] for item in domains[0] + item[AxisFamily.active().partition_axis().name] for item in domains[0] } == { "R02C05", "R04C04", @@ -63,7 +64,7 @@ def test_streaming_domain_requires_bound_execution(): with pytest.raises(RuntimeError, match="execution_runtime"): StreamExecutionAxisDomainProvider.build_for_component( context=ProcessingContext(), - component=StreamExecutionAxisDomainProvider.axis_component, + component=AxisFamily.active().partition_axis().name, metadata_roots=(), ) @@ -244,13 +245,13 @@ def test_collapsed_contributors_do_not_restore_a_stream_pixel_axis(): @pytest.mark.parametrize("axis", tuple(RuntimePlaneAxis)) -@pytest.mark.parametrize("component", tuple(AllComponents)) +@pytest.mark.parametrize("component", AxisFamily.active().axes) def test_retained_image_plane_domain_does_not_require_artifact_storage_axes( axis, component ): metadata = _plane_metadata( axis, - ({component.value: "1"}, {component.value: "2"}), + ({component.name: "1"}, {component.name: "2"}), ) fields = StreamImagePayloadMetadataProjector.item_fields_for_plane_components( @@ -258,7 +259,7 @@ def test_retained_image_plane_domain_does_not_require_artifact_storage_axes( ) assert fields["plane_axis"] == axis.value - assert fields["plane_component_values"] == {component.value: ("1", "2")} + assert fields["plane_component_values"] == {component.name: ("1", "2")} assert ( metadata.retained_plane_component_values() == fields["plane_component_values"] ) @@ -269,7 +270,7 @@ def test_projected_contributors_do_not_declare_a_retained_pixel_plane_domain(): assert metadata.retained_plane_component_values() == {} wire = StreamImagePayloadMetadataProjector.item_fields_for_plane_components( - metadata, (AllComponents.CHANNEL,) + metadata, (Microscopy.Channel,) ) assert "plane_axis" not in wire assert "plane_component_values" not in wire @@ -281,7 +282,7 @@ def test_projected_contributors_do_not_declare_a_retained_pixel_plane_domain(): ) -@pytest.mark.parametrize("storage_components", [(), (AllComponents.CHANNEL,)]) +@pytest.mark.parametrize("storage_components", [(), (Microscopy.Channel,)]) def test_retained_plane_domain_rejects_multiple_varying_components(storage_components): metadata = _plane_metadata( RuntimePlaneAxis.SOURCE_BINDING, @@ -301,7 +302,7 @@ def test_singleton_plane_projection_remains_exactly_compiler_owned(): ) assert StreamImagePayloadMetadataProjector.item_fields_for_plane_components( - metadata, (AllComponents.SITE,) + metadata, (Microscopy.Site,) )["plane_component_values"] == {"site": ("3",)} with pytest.raises(ValueError, match="exactly one exact component"): StreamImagePayloadMetadataProjector.item_fields_for_plane_components( @@ -317,5 +318,5 @@ def test_singleton_plane_projection_rejects_ambiguous_compiler_components(): with pytest.raises(ValueError, match="exactly one"): StreamImagePayloadMetadataProjector.item_fields_for_plane_components( - metadata, (AllComponents.SITE, AllComponents.CHANNEL) + metadata, (Microscopy.Site, Microscopy.Channel) ) diff --git a/tests/unit/test_streaming_service.py b/tests/unit/test_streaming_service.py index ddf4673d1f..4b76eb0838 100644 --- a/tests/unit/test_streaming_service.py +++ b/tests/unit/test_streaming_service.py @@ -22,7 +22,7 @@ from zmqruntime.viewer_protocol import ViewerBatchWireField, ViewerWireField from zmqruntime.viewer_state import ViewerStateManager -from openhcs.constants.constants import AllComponents +from openhcs.core.axes import AxisFamily from openhcs.core.artifacts import ObjectLabelsArtifactType from openhcs.core.component_group_scope import RuntimeExecutionAxisScope from openhcs.core.components.parser_metaprogramming import FilenameParseResult @@ -92,6 +92,7 @@ PointROIOptions, materialize, ) +from openhcs.domains.microscopy.axes import Microscopy class FakeFileManager: @@ -161,11 +162,11 @@ def source_voxel_spacing(self, plate_path) -> SourceVoxelSpacing: def filename_parse_result(*, channel: int = 1) -> FilenameParseResult: values = { - AllComponents.WELL: "A01", - AllComponents.SITE: 1, - AllComponents.CHANNEL: channel, - AllComponents.Z_INDEX: 1, - AllComponents.TIMEPOINT: 1, + Microscopy.Well: "A01", + Microscopy.Site: 1, + Microscopy.Channel: channel, + Microscopy.ZIndex: 1, + Microscopy.Timepoint: 1, } return FilenameParseResult(values.items(), extension=".tif") @@ -241,7 +242,7 @@ def test_all_streaming_ports_read_declared_registry_fields(config) -> None: def test_streaming_config_component_modes_apply_display_defaults() -> None: assert NapariStreamingConfig().component_modes() == { component: NapariDimensionMode.STACK.value - for component in NapariStreamingConfig.COMPONENT_ORDER + for component in AxisFamily.active().names() } assert FijiStreamingConfig().component_modes() == { "site": FijiDimensionMode.FRAME.value, @@ -260,7 +261,7 @@ def test_napari_dimension_modes_distinguish_layers_from_slices() -> None: assert NapariDimensionMode.LAYER.value == "layer" assert ( NapariStreamingConfig( - site_mode=NapariDimensionMode.LAYER, + tile_mode=NapariDimensionMode.LAYER, ).component_modes()["site"] == "layer" ) @@ -688,7 +689,7 @@ def source_path( "A49", component=None, value=None, - fixed_component_values=(("z_index", "1"), ("timepoint", "1")), + fixed_component_values=((Microscopy.ZIndex, "1"), (Microscopy.Timepoint, "1")), ), ) workspace_projection = VirtualWorkspaceSourceProjection( diff --git a/tests/unit/test_template_crop_pipeline_execution.py b/tests/unit/test_template_crop_pipeline_execution.py index 472a81eec6..22b55f8ebb 100644 --- a/tests/unit/test_template_crop_pipeline_execution.py +++ b/tests/unit/test_template_crop_pipeline_execution.py @@ -9,7 +9,7 @@ from objectstate import ObjectStateRegistry from objectstate.lazy_factory import ensure_global_config_context -from openhcs.constants import GroupBy, Microscope, VariableComponents +from openhcs.constants import Microscope from openhcs.core.config import ( GlobalPipelineConfig, LazyPathPlanningConfig, @@ -26,6 +26,7 @@ multi_template_crop_subset, ) from openhcs.processing.backends.processors.numpy_processor import crop +from openhcs.domains.microscopy.axes import Microscopy @pytest.mark.parametrize( @@ -62,7 +63,7 @@ def test_template_crop_persists_each_source_channel( tifffile.imwrite(image_dir / f"A01_s001_w{channel}_z001_t001.tif", pixels) processing = LazyProcessingConfig( - variable_components=[VariableComponents.CHANNEL], group_by=GroupBy.SITE + variable_components=[Microscopy.Channel], group_by=Microscopy.Site ) steps = [ FunctionStep( diff --git a/tests/unit/test_viewer_channel_display_metadata.py b/tests/unit/test_viewer_channel_display_metadata.py index 10167c9c0a..c843882d67 100644 --- a/tests/unit/test_viewer_channel_display_metadata.py +++ b/tests/unit/test_viewer_channel_display_metadata.py @@ -7,7 +7,6 @@ ViewerComponentMode, ) -from openhcs.constants.constants import AllComponents from openhcs.core.source_binding_workspace import PrimaryPlaneBindingProjection from openhcs.core.source_bindings import ComponentSelector, NamedSourceBinding from openhcs.core.source_projection import ( @@ -29,16 +28,11 @@ ViewerComponentNameMetadata, ViewerLayerAxisProjection, ) +from openhcs.domains.microscopy.axes import Microscopy def _address(channel: str = "1") -> OpenHCSPlaneAddress: - return OpenHCSPlaneAddress.from_values( - well="A01", - site="1", - channel=channel, - z_index="1", - timepoint="1", - ) + return OpenHCSPlaneAddress(((Microscopy.Well, "A01"), (Microscopy.Site, "1"), (Microscopy.Channel, channel), (Microscopy.ZIndex, "1"), (Microscopy.Timepoint, "1"))) def _component_name_metadata() -> ViewerComponentNameMetadata: @@ -64,13 +58,13 @@ def test_primary_plane_projection_preserves_exact_binding_alias_as_channel_label projection = PrimaryPlaneBindingProjection().projection( NamedSourceBinding( alias="DNA", - component_identity=(ComponentSelector(AllComponents.CHANNEL, "1"),), + component_identity=(ComponentSelector(Microscopy.Channel, "1"),), ), candidate, address, ) - assert projection.address.value_for(AllComponents.CHANNEL) == "1" + assert projection.address.value_for(Microscopy.Channel) == "1" assert dict(projection.component_labels) == {"channel": "DNA"} metadata = SourceProjectionSet((projection,)).metadata_dict( parser=SourceSchemaFilenameParser(), diff --git a/tests/unit/test_viewer_receipt_replay.py b/tests/unit/test_viewer_receipt_replay.py index 2dd21c6b22..be7f100b6c 100644 --- a/tests/unit/test_viewer_receipt_replay.py +++ b/tests/unit/test_viewer_receipt_replay.py @@ -32,7 +32,6 @@ from openhcs.agent.path_policy import AgentPathPolicy from openhcs.agent.services.plate_inspection_service import PlateInspectionService from openhcs.agent.services.plate_streaming_service import PlateStreamingService -from openhcs.constants.constants import AllComponents from openhcs.core.runtime_image_values import image_payload_metadata, image_payload_data from openhcs.core.source_image_provenance import SourceImageProvenancePlanes from openhcs.core.source_metadata import SourceVoxelSpacing, SourceVoxelSpacingUnit @@ -42,15 +41,17 @@ from openhcs.core.plate_image_inventory import PlateFileRecord from python_introspect import to_jsonable from openhcs.runtime.viewer_protocol import ViewerPayloadSummary +from openhcs.core.axes import AxisFamily +from openhcs.domains.microscopy.axes import Microscopy def receipt_state(path, *, summary=None): fixed = { - component.value: 1 - for component in AllComponents - if component is not AllComponents.CHANNEL + component.name: 1 + for component in AxisFamily.active().axes + if component is not Microscopy.Channel } - fixed[AllComponents.WELL.value] = "1" + fixed[Microscopy.Well.name] = "1" summary = summary if summary is not None else ViewerPayloadSummary.from_wire_mapping(dict( path=str(path), data_type="image", @@ -342,7 +343,7 @@ def test_native_persisted_aggregate_source_projection_preserves_order( source_items = source.image_source_metadata_items( (str(path),), components, projection ) - component_order = tuple(component.value for component in AllComponents) + component_order = tuple(component.name for component in AxisFamily.active().axes) assert tuple( item["channel"] for item in source_items.domain_metadata_items(component_order) ) == (2, 1) diff --git a/tests/unit/test_volume_projection_fixture.py b/tests/unit/test_volume_projection_fixture.py index f3e2a58bbb..05566a127e 100644 --- a/tests/unit/test_volume_projection_fixture.py +++ b/tests/unit/test_volume_projection_fixture.py @@ -13,7 +13,6 @@ import numpy as np import pytest -from openhcs.constants import AllComponents from openhcs.core.artifacts import ArtifactOutputPlan, ArtifactSpec, ArtifactSpecCollection, ImageArtifactType from openhcs.core.runtime_image_values import ImagePayloadMetadata, image_payload_data, image_payload_metadata from openhcs.core.runtime_object_labels import object_label_dense_array @@ -21,6 +20,8 @@ from openhcs.core.source_image_provenance import SourceImageProvenancePlanes from openhcs.core.source_projection import OpenHCSPlaneAddress from openhcs.core.source_matching import source_component_metadata_value +from openhcs.core.axes import AxisFamily +from openhcs.domains.microscopy.axes import Microscopy @@ -38,7 +39,7 @@ def source_volume(): pixels = np.zeros((3, 8, 9), dtype=np.uint16) for index in range(3): pixels[index, 1:index + 3, 1:index + 3] = index + 11 - addresses = tuple(OpenHCSPlaneAddress.from_values("image.ome.tif", 1, 1, z + 1, 1) for z in range(3)) + addresses = tuple(OpenHCSPlaneAddress(((Microscopy.Well, "image.ome.tif"), (Microscopy.Site, 1), (Microscopy.Channel, 1), (Microscopy.ZIndex, z + 1), (Microscopy.Timepoint, 1))) for z in range(3)) metadata = ImagePayloadMetadata( source_image_provenance_planes=SourceImageProvenancePlanes.from_components( paths=("/synthetic-unit-input/image.ome.tif",) * 3, @@ -55,7 +56,7 @@ def output_plan(declaration): return ArtifactOutputPlan( name=bound.name, path="/synthetic-unit-output/" + bound.name, artifact_type=bound.artifact_type, relations=bound.relations, - variable_components=(AllComponents.Z_INDEX,), + variable_components=(Microscopy.ZIndex,), ) @@ -99,8 +100,8 @@ def test_selected_then_full_stack_outputs_keep_exact_source_context(source_volum assert contextual_rows.source_provenance == expected_provenance assert contextual_rows.subject.object_name == fixture.VOLUME_LABELS.name assert contextual_rows.subject.id_field == "object_label" - for component in AllComponents: - assert tuple(contextual_rows.rows.column_values(component.value)) == tuple( + for component in AxisFamily.active().axes: + assert tuple(contextual_rows.rows.column_values(component.name)) == tuple( source_component_metadata_value( source_metadata.source_image_provenance_planes.plane(index).component_metadata, component, diff --git a/tests/unit/test_well_throughput_scaling.py b/tests/unit/test_well_throughput_scaling.py index 525e6e2405..d7554f6120 100644 --- a/tests/unit/test_well_throughput_scaling.py +++ b/tests/unit/test_well_throughput_scaling.py @@ -42,7 +42,6 @@ well_throughput_start_method_from_manifest, write_well_throughput_csv, ) -from openhcs.constants.constants import AllComponents from openhcs.core.config import ( MultiprocessingStartMethod, PipelineConfig, @@ -62,6 +61,8 @@ from openhcs.microscopes.source_schema import SourceSchemaFilenameParser from openhcs.runtime.zmq_execution_observation import ZMQRuntimeExecutionOutcomeExport from openhcs.runtime.zmq_execution_signature import ZMQRuntimeObservationExportScope +from openhcs.domains.microscopy.axes import Microscopy +from openhcs.core.virtual_workspace_metadata import component_metadata_field def test_reused_server_suite_keeps_one_client_and_distinct_resume_identity( @@ -605,7 +606,7 @@ def test_repeated_wells_keep_all_declared_projection_fields_coherent( ) -> None: parser = SourceSchemaFilenameParser() original = SourcePlaneProjection( - address=OpenHCSPlaneAddress.from_values("A01", 1, 1, 1, 1), + address=OpenHCSPlaneAddress(((Microscopy.Well, "A01"), (Microscopy.Site, 1), (Microscopy.Channel, 1), (Microscopy.ZIndex, 1), (Microscopy.Timepoint, 1))), ref=SourcePixelRef("disk", "/source/blue.tif"), source_alias="Blue", source_metadata={"Well": "A01", "site": "1", "channel": "1"}, @@ -615,7 +616,7 @@ def test_repeated_wells_keep_all_declared_projection_fields_coherent( main = { **serializer.projection_fields(((original, original_path),)), FIELDS.IMAGE_FILES: [original_path], - FIELDS.WELLS: {"A01": None}, + component_metadata_field(Microscopy.Well): {"A01": None}, } metadata_path = tmp_path / "openhcs_metadata.json" metadata_path.write_text( @@ -636,7 +637,7 @@ def test_repeated_wells_keep_all_declared_projection_fields_coherent( assert set(mapping) == set(projections) == set(updated[FIELDS.IMAGE_FILES]) assert len(projections) == 2 assert { - projection.address.value_for(AllComponents.WELL) + projection.address.value_for(Microscopy.Well) for projection in projections.values() } == { "W001", @@ -659,7 +660,7 @@ def test_repeated_wells_use_manifest_source_well_scope( serializer = SourceProjectionMetadataSerializer(parser=parser) sources = tuple( SourcePlaneProjection( - address=OpenHCSPlaneAddress.from_values(well, 1, 1, 1, 1), + address=OpenHCSPlaneAddress(((Microscopy.Well, well), (Microscopy.Site, 1), (Microscopy.Channel, 1), (Microscopy.ZIndex, 1), (Microscopy.Timepoint, 1))), ref=SourcePixelRef("disk", f"/source/{well}.tif"), source_metadata={"Well": well}, ) @@ -672,7 +673,7 @@ def test_repeated_wells_use_manifest_source_well_scope( main = { **serializer.projection_fields(entries), FIELDS.IMAGE_FILES: [path for _source, path in entries], - FIELDS.WELLS: {"A01": None, "B01": None}, + component_metadata_field(Microscopy.Well): {"A01": None, "B01": None}, } metadata_path = tmp_path / "openhcs_metadata.json" metadata_path.write_text( diff --git a/tests/unit/test_zmq_execution_server.py b/tests/unit/test_zmq_execution_server.py index 6fd01bb26a..585b69a104 100644 --- a/tests/unit/test_zmq_execution_server.py +++ b/tests/unit/test_zmq_execution_server.py @@ -16,7 +16,6 @@ ) import openhcs.runtime.zmq_execution_server as zmq_execution_server_module -from openhcs.constants.constants import GroupBy from openhcs.core.config import ( GlobalPipelineConfig, PipelineConfig, @@ -57,11 +56,12 @@ ZMQExecutionRequestPayload, ZMQRuntimeObservationExportScope, ) +from openhcs.domains.microscopy.axes import Microscopy def test_zmq_execution_context_seeds_saved_global_config_for_compilation() -> None: global_config = GlobalPipelineConfig( - processing_config=ProcessingConfig(group_by=GroupBy.CHANNEL) + processing_config=ProcessingConfig(group_by=Microscopy.Channel) ) configs = OpenHCSExecutionConfigBundle( global_pipeline=global_config, @@ -96,7 +96,7 @@ def test_zmq_execution_context_seeds_saved_global_config_for_compilation() -> No use_live=False, ) assert saved_global_config is global_config - assert saved_global_config.processing_config.group_by is GroupBy.CHANNEL + assert saved_global_config.processing_config.group_by is Microscopy.Channel @pytest.mark.parametrize("failed", [False, True]) @@ -780,7 +780,7 @@ def reject_source_discovery(*args, **kwargs): def test_compiled_request_keeps_config_scope_without_resolving_configuration(monkeypatch): server = ZMQExecutionServer(port=5555) global_config = GlobalPipelineConfig( - processing_config=ProcessingConfig(group_by=GroupBy.CHANNEL) + processing_config=ProcessingConfig(group_by=Microscopy.Channel) ) context = ZMQExecutionContext( execution_id="compiled-adoption", diff --git a/tools/cutover/g1_axis_family.py b/tools/cutover/g1_axis_family.py new file mode 100644 index 0000000000..6469a2a6e3 --- /dev/null +++ b/tools/cutover/g1_axis_family.py @@ -0,0 +1,178 @@ +"""One-shot G1 cutover: rewrite saved OpenHCS Python sources onto the axis family. + +Surface G1 deleted the component enums (``AllComponents``, +``VariableComponents``, ``SequentialComponents``, ``StreamingComponents``, +``GroupBy``), replaced the per-member viewer mode fields with per-role fields, +and turned the member-keyed function requirements into role declarations. +Pipelines and configs are saved as pycodify-generated Python (``.py`` +pipelines, ``global_config.config`` and plate configs); this tool rewrites any +such source, and custom-function source that uses the decorators. + +Usage:: + + python tools/cutover/g1_axis_family.py PATH [PATH ...] + +Each file is rewritten in place after a ``.pre-g1`` backup is written +beside it. Pickled pipelines are deprecated and are not converted. This tool +is deleted once the owner has migrated; nothing in ``openhcs/`` reads the +pre-G1 format. +""" + +from __future__ import annotations + +import ast +import re +import shutil +import sys +from pathlib import Path + +ENUM_NAMES = ( + "AllComponents", + "VariableComponents", + "SequentialComponents", + "StreamingComponents", + "GroupBy", +) +MEMBER_CLASSES = { + "WELL": "Well", + "SITE": "Site", + "CHANNEL": "Channel", + "Z_INDEX": "ZIndex", + "TIMEPOINT": "Timepoint", +} +MEMBER_ROLES = { + "WELL": "PartitionAxis", + "SITE": "TileAxis", + "CHANNEL": "ColourAxis", + "Z_INDEX": "StackAxis", + "TIMEPOINT": "TimeAxis", +} +MODE_FIELDS = { + "well_mode": "partition_mode", + "site_mode": "tile_mode", + "channel_mode": "colour_mode", + "z_index_mode": "stack_mode", + "timepoint_mode": "time_mode", +} +DECORATORS = { + "required_variable_components": "required_axis_roles", + "allowed_group_by": "allowed_group_by_roles", +} +REMOVED_CONSTANT_NAMES = { + *ENUM_NAMES, + "DEFAULT_GROUP_BY", + "DEFAULT_VARIABLE_COMPONENTS", + "MULTIPROCESSING_AXIS", +} +_ENUM_ALT = "|".join(ENUM_NAMES) +_MEMBER_ALT = "|".join(MEMBER_CLASSES) + + +def rewrite_source(source: str) -> str: + """Return ``source`` rewritten onto the axis family; it must still parse.""" + + text = _rewrite_decorators(source) + text = re.sub(r"\bGroupBy\.NONE\b", "Ungrouped", text) + text = re.sub( + rf"\b(?:{_ENUM_ALT})\.({_MEMBER_ALT})\b", + lambda match: f"Microscopy.{MEMBER_CLASSES[match.group(1)]}", + text, + ) + for old, new in MODE_FIELDS.items(): + text = re.sub(rf"\b{old}(?=\s*=)", new, text) + text = _drop_removed_imports(text) + imports = [] + if "Microscopy." in text and not _imports(text, "Microscopy"): + imports.append("from openhcs.domains.microscopy.axes import Microscopy\n") + axes_names = sorted( + name + for name in ("Ungrouped", *MEMBER_ROLES.values()) + if re.search(rf"\b{name}\b", text) and not _imports(text, name) + ) + if axes_names: + imports.append(f"from openhcs.core.axes import {', '.join(axes_names)}\n") + if imports: + text = _insert_after_imports(text, "".join(imports)) + ast.parse(text) + return text + + +def _rewrite_decorators(text: str) -> str: + for old, new in DECORATORS.items(): + text = re.sub( + rf"\b{old}\(([^()]*)\)", + lambda match, new=new: f"{new}({_members_to_roles(match.group(1))})", + text, + ) + text = re.sub(rf"\b{old}\b", new, text) + return text + + +def _members_to_roles(arguments: str) -> str: + return re.sub( + rf"\b(?:{_ENUM_ALT})\.({_MEMBER_ALT})\b", + lambda match: MEMBER_ROLES[match.group(1)], + arguments, + ) + + +def _imports(text: str, name: str) -> bool: + tree = ast.parse(text) + return any( + isinstance(node, ast.ImportFrom) + and any((alias.asname or alias.name) == name for alias in node.names) + for node in tree.body + ) + + +def _drop_removed_imports(text: str) -> str: + pattern = re.compile( + r"^from openhcs\.constants(?:\.constants)? import (\([^)]*\)|[^\n]*)\n", + re.MULTILINE, + ) + + def replace(match: re.Match[str]) -> str: + body = match.group(1).strip("()") + names = [n.strip() for n in body.replace("\n", ",").split(",") if n.strip()] + kept = [n for n in names if n.split(" as ")[0] not in REMOVED_CONSTANT_NAMES] + if not kept: + return "" + module = match.group(0).split(" import ")[0][len("from ") :] + return f"from {module} import {', '.join(kept)}\n" + + return pattern.sub(replace, text) + + +def _insert_after_imports(text: str, block: str) -> str: + tree = ast.parse(text) + imports = [n for n in tree.body if isinstance(n, (ast.Import, ast.ImportFrom))] + lines = text.splitlines(keepends=True) + index = max((n.end_lineno for n in imports), default=0) + lines.insert(index, block) + return "".join(lines) + + +def migrate(path: Path) -> bool: + """Rewrite one source file; return whether it changed.""" + + source = path.read_text(encoding="utf-8") + rewritten = rewrite_source(source) + if rewritten == source: + return False + shutil.copy2(path, path.with_name(path.name + ".pre-g1")) + path.write_text(rewritten, encoding="utf-8") + return True + + +def main(argv: list[str]) -> int: + if not argv: + print(__doc__) + return 2 + for name in argv: + changed = migrate(Path(name)) + print(f"{'migrated' if changed else 'unchanged'}: {name}") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main(sys.argv[1:]))