Skip to content
213 changes: 212 additions & 1 deletion openhcs/core/artifacts.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,9 @@
MeasurementTable,
RuntimeMeasurementFeatureOwner,
)
from openhcs.core.runtime_stores import StoredRuntimeValue
from openhcs.core.source_projection import OpenHCSPlaneAddress
from openhcs.core.component_group_scope import RuntimeExecutionAxisScope
from openhcs.core.runtime_slice_alignment import RuntimeSliceAlignedValueSet


Expand Down Expand Up @@ -430,6 +433,70 @@ def publishes_to_main_flow(

return cls.participates_in_main_flow_output and sidecar_role is None

@classmethod
def reduce_materialization_records(
cls,
*,
records: tuple[StoredRuntimeValue, ...],
output_plan: ArtifactOutputPlan,
) -> tuple[StoredRuntimeValue, ...]:
"""Reduce records across every compiled group of one artifact output."""

del output_plan
return records

@classmethod
def reduce_materialization_scopes(
cls,
*,
records: tuple[StoredRuntimeValue, ...],
output_plan: ArtifactOutputPlan,
group_key: str | None,
) -> tuple[StoredRuntimeValue, ...]:
"""Partition records by exact scope before artifact-specific reduction."""

records_by_scope: dict[
RuntimeExecutionAxisScope,
list[StoredRuntimeValue],
] = {}
for record in records:
records_by_scope.setdefault(record.key.scope, []).append(record)
return tuple(
reduced_record
for scoped_records in records_by_scope.values()
for reduced_record in cls.reduce_materialization_scope(
records=tuple(scoped_records),
output_plan=output_plan,
group_key=group_key,
)
)

@classmethod
def reduce_materialization_scope(
cls,
*,
records: tuple[StoredRuntimeValue, ...],
output_plan: ArtifactOutputPlan,
group_key: str | None,
) -> tuple[StoredRuntimeValue, ...]:
del output_plan, group_key
if len(records) <= 1:
return records
record_locations = tuple(
(
record.key.semantic_id,
record.location.path,
)
for record in records
)
raise RuntimeError(
f"Ambiguous RuntimeValueStore records for planned artifact "
f"materialization '{records[0].key.name}' "
f"({records[0].key.artifact_type.value}) on axis "
f"'{records[0].key.scope.axis_id}' group "
f"{records[0].key.scope.value_text!r}: {record_locations!r}."
)


ArtifactTypeValue = type[ArtifactType] | str

Expand Down Expand Up @@ -814,7 +881,9 @@ def compose_runtime_values(
payloads = tuple(value.data for value in values)
arrays = tuple(image_payload_data(payload) for payload in payloads)
return stack_image_payloads(
payloads, memory_type=detect_memory_type(arrays[0]), device_id=0,
payloads,
memory_type=detect_memory_type(arrays[0]),
device_id=0,
metadata_mode=ImagePayloadMetadataCompositionMode.for_plane_axis(
RuntimePlaneAxis.RUNTIME_SLICE
),
Expand Down Expand Up @@ -850,6 +919,110 @@ def normalize_group_scoped_payload(
projection.selected_plane(0),
)

@classmethod
def reduce_materialization_records(
cls,
*,
records: tuple[StoredRuntimeValue, ...],
output_plan: ArtifactOutputPlan,
) -> tuple[StoredRuntimeValue, ...]:
from openhcs.core.runtime_image_values import image_payload_metadata
from openhcs.core.source_projection import OpenHCSPlaneAddress

if not output_plan.materialization_uses_source_identity_filename():
return records

addressed_records: list[
tuple[StoredRuntimeValue, OpenHCSPlaneAddress | None]
] = []
records_by_address: dict[
OpenHCSPlaneAddress,
list[StoredRuntimeValue],
] = {}
for record in records:
payload = output_plan.materialization_payload(record)
metadata = image_payload_metadata(payload)
address = OpenHCSPlaneAddress.from_complete_source_metadata(
metadata.source_component_metadata
)
addressed_records.append((record, address))
if address is not None:
records_by_address.setdefault(address, []).append(record)

reduced_records: list[StoredRuntimeValue] = []
emitted_addresses: set[OpenHCSPlaneAddress] = set()
for record, address in addressed_records:
if address is None:
reduced_records.append(record)
continue
if address in emitted_addresses:
continue
emitted_addresses.add(address)
reduced_records.append(
cls._materialization_record_for_scalar_address(
output_plan,
address,
tuple(records_by_address[address]),
)
)
return tuple(reduced_records)

@classmethod
def _materialization_record_for_scalar_address(
cls,
output_plan: ArtifactOutputPlan,
address: OpenHCSPlaneAddress,
records: tuple[StoredRuntimeValue, ...],
) -> StoredRuntimeValue:
if len(records) == 1:
return records[0]

owner_records = tuple(
record
for record in records
if all(
address.value_for(component) == value
for component, value in record.key.scope.source_component_values
)
)
if len(owner_records) != 1:
raise ValueError(
"Scalar image materialization requires one execution scope matching "
f"source address {address!r} for artifact {output_plan.name!r}; "
f"found {len(owner_records)} among "
f"{tuple(record.key.scope for record in records)!r}."
)

owner_record = owner_records[0]
owner_payload = output_plan.materialization_payload(owner_record)
for record in records:
payload = output_plan.materialization_payload(record)
if not cls._materialization_payloads_are_equivalent(owner_payload, payload):
raise ValueError(
"Conflicting scalar image materialization payloads for source "
f"address {address!r} and artifact {output_plan.name!r}: "
f"{owner_record.key.scope!r} != {record.key.scope!r}."
)
return owner_record

@staticmethod
def _materialization_payloads_are_equivalent(left: object, right: object) -> bool:
import numpy as np
from openhcs.core.runtime_image_values import (
image_payload_data,
image_payload_metadata,
)

left_metadata = image_payload_metadata(left)
right_metadata = image_payload_metadata(right)
if left_metadata != right_metadata:
return False
left_data = np.asarray(image_payload_data(left))
right_data = np.asarray(image_payload_data(right))
return left_data.dtype == right_data.dtype and np.array_equal(
left_data, right_data, equal_nan=True
)


class ObjectLabelsArtifactType(ArtifactType):
"""Object-label array artifact type."""
Expand Down Expand Up @@ -1254,6 +1427,44 @@ def uses_aggregate_materialization_identity(cls, data: object) -> bool:
or len(provenance.represented_source_identities) > 1
)

@classmethod
def reduce_materialization_scope(
cls,
*,
records: tuple[StoredRuntimeValue, ...],
output_plan: ArtifactOutputPlan,
group_key: str | None,
) -> tuple[StoredRuntimeValue, ...]:
from openhcs.constants.constants import Backend
from openhcs.core.runtime_artifact_values import RuntimeValue
from openhcs.core.runtime_measurements import MeasurementTable
from openhcs.core.runtime_stores import (
RuntimeArtifactLocation,
StoredRuntimeValue,
)

if len(records) <= 1:
return records
group_plan = output_plan.for_group(group_key)
tables = tuple(cast(MeasurementTable, record.data) for record in records)
table = MeasurementTable.join_artifact(output_plan.name, tables)
value = RuntimeValue.normalize_for_execution_scope(
group_plan,
table,
execution_scope=records[0].key.scope,
)
return (
StoredRuntimeValue(
key=value.key,
data=value.data,
materialization_source_metadata=value.materialization_source_metadata,
location=RuntimeArtifactLocation(
path=group_plan.path,
backend=Backend.MEMORY.value,
),
),
)


class ObjectLineageArtifactType(ArtifactType):
"""Internal directed object lineage used to project object measurements."""
Expand Down
21 changes: 13 additions & 8 deletions openhcs/core/orchestrator/compiled_plate_execution.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,9 +79,11 @@
)
from openhcs.core.source_bindings import CompiledSourceBindingPlan
from openhcs.core.steps.abstract import AbstractStep, StepExecutionObservation
from openhcs.core.steps.function_artifact_materialization import (
ArtifactMaterializationTargetPlan,
)
from openhcs.core.steps.function_outputs import (
OpenHCSMetadataWriter,
RuntimeArtifactMaterializationAuthority,
OpenHCSMetadataTarget,
)

if TYPE_CHECKING:
Expand Down Expand Up @@ -272,7 +274,7 @@ def execute_compiled_plate_request(
execution_results,
plate_runtime_observation=plate_runtime_observation,
)
OpenHCSMetadataWriter.finalize_completed_plate(
OpenHCSMetadataTarget.finalize_completed_plate(
validated.compiled_contexts,
)
viewer_states_by_port = settle_viewer_state(
Expand Down Expand Up @@ -537,11 +539,11 @@ def execute_plate_scoped_steps(
)
records_by_axis = _records_with_output(records_by_axis, record)

materializations = RuntimeArtifactMaterializationAuthority.materialize(
materializations = ArtifactMaterializationTargetPlan.materialize(
owner_context,
owner_plan.require_function_execution_ready(),
)
OpenHCSMetadataWriter.write(
OpenHCSMetadataTarget.write_for_step(
owner_context,
owner_plan.require_function_execution_ready(),
artifact_materializations=materializations,
Expand All @@ -553,7 +555,8 @@ def execute_plate_scoped_steps(
)
observations_by_context[owner_context_key].append(
StepExecutionObservation.combine(
item.observation(owner_plan, owner_context) for item in materializations
item.observation(owner_plan, owner_context)
for item in materializations
)
)
_emit_execution_progress(
Expand All @@ -575,13 +578,15 @@ def execute_plate_scoped_steps(
records=records,
runtime_export_paths=tuple(
dict.fromkeys(
path for item in observations_by_context[context_key]
path
for item in observations_by_context[context_key]
for path in item.runtime_export_paths
)
),
runtime_observation_mode=RuntimeObservationMode.MERGE_INTO_PARENT,
analysis_inputs=RuntimeAnalysisConsolidationInputs.combine(
item.analysis_inputs for item in observations_by_context[context_key]
item.analysis_inputs
for item in observations_by_context[context_key]
),
)
for context_key, context in compiled_contexts.items()
Expand Down
4 changes: 3 additions & 1 deletion openhcs/core/projected_image_output.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,9 @@
ObjectLabelValue,
object_label_dense_array,
)
from openhcs.core.runtime_object_label_building import SourceImageObjectLabelBuildRequest
from openhcs.core.runtime_object_label_building import (
SourceImageObjectLabelBuildRequest,
)
from openhcs.core.runtime_plane_projection import (
RuntimePlaneAxis,
RuntimePlaneAxisValueProjection,
Expand Down
Loading
Loading