diff --git a/docs/validation/calibrated-gaussian980/OWNER-CHECKPOINT.rst b/docs/validation/calibrated-gaussian980/OWNER-CHECKPOINT.rst new file mode 100644 index 0000000000..66051aa14f --- /dev/null +++ b/docs/validation/calibrated-gaussian980/OWNER-CHECKPOINT.rst @@ -0,0 +1,185 @@ +Calibrated Gaussian source-axis owner checkpoint +============================================== + +Issue980 preserves the original receiving25 failure and author source. No +original execution is replayed or scientist prefix changed. This branch starts +from actual merged main c882d5edc67bffe7ec7f2eb3a2eeb7fe64e9415a in the reused +finished context-bounding checkout; foreign gitlinks and keepers are preserved. +Current normal-main integration and capability ownership supersede that initial +base as recorded in the final section below. + +Determining cause +----------------- + +GaussianFilterModule declares FLEXIBLE/FULL_STACK. Its raw implementation +passed total pixel rank to SourceVoxelSpacing.spacing_for_ndim. The supplied +SITE/Y/X cohort therefore requested three physical spacing values for a +calibrated two-dimensional source. This also let uncalibrated multi-site +arrays blur between sites instead of representing independent images. + +SourceSpatialDomain.spatial_rank already owns intrinsic Y/X versus Z/Y/X. +VolumeSourceSpatialDomain.admit_source_cohort promotes explicitly declared +volume cohorts through the existing source-binding and main-flow loaders. +ImagePayloadMetadata already owns channel-axis normalization and spatial Y/X +placement. Its new spatial_axes projection consumes these same declarations; +Gaussian derives its sigma vector from that projection with zero smoothing +on nonspatial axes. No new stored axis/domain facts, execution mode, codec, +spacing fallback or reader relaxation is introduced. + +Owner and consumers +------------------- + +The pre-edit refactor-audit measure_source/AST pass parsed twelve relevant +production modules without omissions: runtime_image_values, source_spatial_domain, +source_metadata, runtime_plane_projection, aligned_image_payload, source_bindings, +source_binding_selection, steps/function_runtime, callable_contract, +interop/cellprofiler/runtime/function_contract_execution, Gaussian and shape. +Dynamic contract selection was read semantically; AST is not a runtime proof. + +Both source-binding load and main-flow load admit the original cohort domain. +Full-stack projection retains that metadata. SourceVoxelSpacing continues to +reject physical rank greater than its declared calibration. Viewer coordinate +scales and object feature spacing are separate existing consumers, unchanged. +Shape feature spacing applies to its physical label-image geometry, not this +Gaussian full-stack source-cohort dispatch. Gaussian's competing total-rank +decision is deleted. No active #973/#977 file overlaps these two source methods. + +Acceptance boundary +------------------- + +Source qualification is complete at the published checkpoint below. Installed +public compile/execute qualification remains pending; the draft is not claimed +merge-ready. +Required controls: calibrated singleton SITE/Y/X; multiple independent sites +with no cross-site smoothing; anisotropic declared intrinsic Z/Y/X parity; +SITE/Z/Y/X and declared channels; original metadata/provenance and mask +preservation; strict missing physical-Z spacing and invalid channel/rank +rejection. The ordinary installed public MCP compile/execute and persisted +result check use a separately recorded synthetic engineering destination, +not the original scientist or receiving25. No merge readiness is claimed yet. + +Qualified source checkpoint +--------------------------- + +At the initial qualified checkpoint, production bytes were unchanged since +c0d67deff and its final fixture head was 775163f06. Original source checks used +the paired Python3.12 interpreter and +the five receiving25 qualified dependencies, without modifying their prefix. +The isolated Git source archive has no foreign external checkouts. Its original +unchanged _tabular_native.abi3.so was reused from receiving25; both copies have +SHA256 eb91e62b2f2bac4b86c06d602fc1905fd52d9191ecc8356fc738a55c5f3cc7e3. + +Original receipts are retained under +/home/ts/wt/openhcs-issue-batch-20260929/engineering-gaussian980: + +* controls02.log/time: original session89273, terminal0, 50 passed in20.82s; + full process peak532804KiB, zero swaps. Covers Gaussian controls, prepared + geometry ABI, and original saved label-plane/calibration family. +* controls05.log/time: original session37603, terminal0, two added composed + provenance controls passed in2.76s; process peak373936KiB, zero swaps. + Original source-plane count is preserved for independent SITE and explicitly + admitted physical Z cohorts, using the existing provenance count property. + +Original negatives remain intact: controls01 lacked the Git archive's native +extension during import; controls03 was incorrectly launched from the source +checkout and selected its foreign old ZMQ dependency before collection; +controls04 numerical/provenance equality assertions passed but the added count +assertion used a nonexistent .planes property. It was corrected to the original +SourceImageProvenance.source_plane_count, with no production change or weakened +assertion. None was a scientist execution or an UNKNOWN replay. + +Initial qualified production byte pins (superseded below for metadata only): + +* runtime_image_values.py: + 118750a9171d45114a9be18c5bb0bd8df29eee3718a04c5a085a7217f7778c33 +* gaussian_filter.py: + df06de7964caf889ff6f5539da93ff7656864b9ebaeceba4654250e9d6301b35 + +Additional semantic closure confirms the original CellProfiler infrastructure +``Process as 3D?`` declaration selects VolumeSourceSpatialDomain and Z stack +components. RuntimeSliceProjection composes declared aligned stacks without +discarding the metadata. The installed skimage Gaussian delegates the full +sigma vector to scipy.ndimage; zeros exclude nonspatial axes without changing +the filter implementation, border mode or intensity conversion. + +Next installed acceptance uses the ordinary whole-candidate builder once for +this source and the next natural guide bundle, with a synthetic engineering +destination and an exact lane handoff from Dewey. Required public evidence is +registered Gaussian compile/execute COMPLETE, exact persisted pixels against +independent-site and anisotropic-volume expectations, and unchanged source +provenance/calibration. No viewer or biological rerun is necessary. Receiving25 +and all blind-author packages remain immutable. + +Parent IMPL-12 cleanup before candidate build +------------------------------------------- + +Source head 5991cabc9 deletes the duplicated pixel-rank/channel-normalization/ +axis enumeration from spatial_axes and spatial_axes_yx. The existing metadata +owner now provides non_channel_axes once. Optional Y/X projection still returns +None for fewer than two non-channel axes, including a channel-bearing rank2 +payload with only one non-channel axis. Strict intrinsic projection still +rejects insufficient declared Y/X or Z/Y/X dimensions. A volume declaration +does not make optional Y/X placement reject a rank2 image. Both paths continue +to reject an invalid declared channel index through the original normalizer. + +Relevant post-edit AST closure parsed seven metadata/placement/consumer modules +with zero omissions. Existing Y/X callers in aligned payloads, streaming-axis +binding, viewer sampling and viewer source-domain materialization retain the +optional contract and their own established None handling. Gaussian alone +consumes the strict intrinsic projection; its implementation is unchanged. +This is a focused owner-family audit, not a global R1 or native runtime proof. + +Original controls06 session89764 is terminal0: all59 Gaussian, optional/strict +projection, prepared geometry and saved-label domain controls passed in3.56s. +Full process elapsed8.75s, peak426164KiB, zero swaps. Original log/time remain at +/home/ts/wt/openhcs-issue-batch-20260929/engineering-gaussian980/controls06.log +and controls06.time. No whole-candidate build was started before this cleanup. + +Current metadata SHA256: +33810f045251604c1404fe91f98da7048ae9b9481a77a41fe61fd04e73dff1bb. +Gaussian SHA256 remains +df06de7964caf889ff6f5539da93ff7656864b9ebaeceba4654250e9d6301b35. +Installed registered MCP pixels/provenance acceptance remains required and +unclaimed. No current scientist, target or shared dependency was changed. + +Current-main capability integration +----------------------------------- + +Normal merge 0d3bc97ca has parents79491d543 and current merged main +c13028ecf46bbe68249e19939aa05a709eee0e0c. Merged990 already moved the channel +normalizer and optional Y/X projection onto ImagePayloadAxisFields. The real +runtime_image_values.py conflict was resolved in that existing capability: +non_channel_axes lives there and spatial_axes_yx consumes it. The metadata +copies of non_channel_axes, spatial_axes_yx and is_declared_source_channel_plane +were deleted; the normalizer and plane/stack predicates are inherited without +forwarding methods. This closes the IMPL-12 lead without copying the new base. + +Strict spatial_axes remains on ImagePayloadMetadata, composing the inherited +non-channel projection with the existing SourceSpatialDomain.spatial_rank. +No abstract source-domain property/default, new carrier or stored field was +added to ImagePayloadAxisFields. This capability keeps its original abstract +channel/plane declarations; metadata keeps its concrete dataclass defaults. +The instantiated MRO control verifies inherited method identity and default +source_channel_axis=None/plane_axis=None, not just successful AST parsing. + +Original controls07 session31394 is terminal0:149 passed in22.08s on the +integrated source. Full process elapsed27.80s, peak549612KiB, zero swaps. +The same Gaussian/geometry/saved-domain controls now include original metadata +projection algebra and mixed-carrier intensity-domain/MRO controls. Receipts: +/home/ts/wt/openhcs-issue-batch-20260929/engineering-gaussian980/controls07.log +and controls07.time. Source was materialized at source-controls02 from the +merge commit, using the unchanged receiving26 qualified dependency artifacts +and native table extension; no prefix or scientist was modified. + +The determining diff against c13028ecf contains only this receipt, metadata's +shared projection, Gaussian, and its focused controls. Current metadata SHA256: +468abdc4c5d890ce1a9fb271bae0116620244d869396e6684ee7647d8d5d78b5. +Gaussian SHA256 remains +df06de7964caf889ff6f5539da93ff7656864b9ebaeceba4654250e9d6301b35. + +Receiving26 is frozen at its original77c3a34f candidate containing79491d543. +Its qualification and acceptance remain evidence for that earlier combination, +not installed proof of this main990 composition. Dewey is notified of the exact +resolved head before merge/final package selection; integrated installed +registered-MCP compiled pixels/provenance acceptance remains separately named +and required. No original client is replayed and no receiving26 bytes relabelled. diff --git a/openhcs/core/runtime_image_values.py b/openhcs/core/runtime_image_values.py index df553cf0d5..4f2b20eee9 100644 --- a/openhcs/core/runtime_image_values.py +++ b/openhcs/core/runtime_image_values.py @@ -352,11 +352,15 @@ def normalized_source_channel_axis(self, data: Any) -> int | None: ) return normalized - def spatial_axes_yx(self, data: Any) -> tuple[int, int] | None: - """Return Y/X axes after excluding the declared channel axis.""" + def non_channel_axes(self, data: Any) -> tuple[int, ...]: + """Return pixel axes excluding this payload's declared channel axis.""" ndim = image_payload_geometry(data).ndim channel_axis = self.normalized_source_channel_axis(data) - candidate_axes = tuple(axis for axis in range(ndim) if axis != channel_axis) + return tuple(axis for axis in range(ndim) if axis != channel_axis) + + def spatial_axes_yx(self, data: Any) -> tuple[int, int] | None: + """Return Y/X axes after excluding the declared channel axis.""" + candidate_axes = self.non_channel_axes(data) if len(candidate_axes) < 2: return None return candidate_axes[-2], candidate_axes[-1] @@ -827,8 +831,24 @@ def compose( ).compose() + def spatial_axes(self, data: Any) -> tuple[int, ...]: + """Project the declared intrinsic spatial domain onto current pixels. - + Source cohorts can add leading SITE, time or binding axes without + adding a physical dimension. Channel axes likewise do not belong to + the spatial domain. Intrinsic Y/X or Z/Y/X axes are the trailing + non-channel axes, including an assembled Z cohort admitted by the + original volume-domain owner. + """ + candidate_axes = self.non_channel_axes(data) + spatial_rank = self.source_spatial_domain.spatial_rank + if len(candidate_axes) < spatial_rank: + raise ValueError( + f"Declared spatial rank {spatial_rank} exceeds payload rank " + f"{image_payload_geometry(data).ndim} after excluding its " + "source channel axis." + ) + return candidate_axes[-spatial_rank:] def mask_domain(self, data: Any) -> "ImageMaskDomain": """Return the mask domain declared for this payload.""" diff --git a/openhcs/processing/backends/cellprofiler/gaussian_filter.py b/openhcs/processing/backends/cellprofiler/gaussian_filter.py index 7018d62595..490044c17e 100644 --- a/openhcs/processing/backends/cellprofiler/gaussian_filter.py +++ b/openhcs/processing/backends/cellprofiler/gaussian_filter.py @@ -46,14 +46,19 @@ def gaussian_filter(image: RuntimeArrayData, sigma: float = 1.0) -> np.ndarray: """ Apply CellProfiler-compatible Gaussian smoothing to an image. - CellProfiler divides the user sigma by image voxel spacing before invoking - the library filter, so volumetric source metadata must stay on the payload.""" + CellProfiler divides the user sigma by physical voxel spacing before + invoking the library filter. Assembled source cohorts and channels are + independent images, not additional physical dimensions. + """ from skimage.filters import gaussian as skimage_gaussian pixel_data = np.asarray(image_payload_data(image)) - spacing = image_payload_metadata(image).source_voxel_spacing.spacing_for_ndim( - pixel_data.ndim + metadata = image_payload_metadata(image) + spatial_axes = metadata.spatial_axes(pixel_data) + spacing = metadata.source_voxel_spacing.spacing_for_ndim(len(spatial_axes)) + effective_sigma = np.zeros(pixel_data.ndim, dtype=np.float64) + effective_sigma[list(spatial_axes)] = np.divide( + float(sigma), np.asarray(spacing, dtype=np.float64) ) - effective_sigma = np.divide(float(sigma), np.asarray(spacing, dtype=np.float64)) filtered = skimage_gaussian(pixel_data, sigma=effective_sigma) return with_image_payload_data(image, filtered) diff --git a/tests/unit/test_calibrated_gaussian_spatial_axes.py b/tests/unit/test_calibrated_gaussian_spatial_axes.py new file mode 100644 index 0000000000..761ed7fcdc --- /dev/null +++ b/tests/unit/test_calibrated_gaussian_spatial_axes.py @@ -0,0 +1,210 @@ +"""Gaussian consumes declared physical axes, not assembled payload rank.""" + +from dataclasses import replace + +import numpy as np +import pytest +from skimage.filters import gaussian + +from openhcs.core.aligned_image_payload import ImagePayloadExecutionMode +from openhcs.core.callable_contract import CallableContract +from openhcs.core.runtime_image_values import ( + ImagePayloadAxisFields, + ImagePayloadMetadata, + image_payload_data, + image_payload_mask, + image_payload_metadata, +) +from openhcs.core.runtime_plane_projection import RuntimePlaneAxis +from openhcs.core.source_metadata import SourceVoxelSpacing +from openhcs.core.source_spatial_domain import SourceSpatialDomain, VolumeSourceSpatialDomain +from openhcs.interop.cellprofiler.runtime.adapter import CellProfilerRuntimeAdapter +from openhcs.interop.cellprofiler.runtime.function_contract_execution import CellProfilerFunctionContractExecutor +from openhcs.processing.backends.cellprofiler.gaussian_filter import gaussian_filter + + +def _execute(source): + contract = CallableContract.from_callable(gaussian_filter).with_prepared_signature() + contract = replace(contract, metadata=replace( + contract.metadata, runtime_adapter=CellProfilerRuntimeAdapter.runtime_adapter_spec(), + )) + return CellProfilerFunctionContractExecutor().execute( + contract, contract.resolve_canonical_raw_callable(), source, {"sigma": 1.5}, + execution_mode=ImagePayloadExecutionMode.FULL_STACK, + ) + + +def _source(pixels, *, domain=None, spacing=(0.5, 0.75), channel_axis=None, cohort=False): + metadata = ImagePayloadMetadata( + source_path="/synthetic/original.tif", + source_image_names=("Original",), + source_component_metadata={"well": "A01", "site": 1, "channel": 1}, + source_voxel_spacing=SourceVoxelSpacing(values_zyx=spacing), + source_spatial_domain=SourceSpatialDomain() if domain is None else domain, + source_channel_axis=channel_axis, + plane_axis=RuntimePlaneAxis.RUNTIME_SLICE if cohort else None, + ) + return metadata.payload_with(pixels, np.ones(pixels.shape, dtype=bool)) + + +@pytest.mark.parametrize("count", (1, 3)) +def test_calibrated_sites_filter_independently_and_preserve_source(count): + pixels = np.zeros((count, 9, 11), dtype=np.float32) + pixels[0, 4, 5] = 1 + source = _source(pixels, cohort=True) + result = _execute(source) + expected = np.stack([gaussian(plane, sigma=(3, 2)) for plane in pixels]) + np.testing.assert_allclose(image_payload_data(result), expected) + np.testing.assert_array_equal(image_payload_data(result)[1:], 0) + assert image_payload_metadata(result) == image_payload_metadata(source) + np.testing.assert_array_equal(image_payload_mask(result), image_payload_mask(source)) + np.testing.assert_array_equal(image_payload_data(source), pixels) + + +@pytest.mark.parametrize("cohort", (False, True)) +def test_anisotropic_physical_z_matches_library_without_site_blur(cohort): + volume = np.zeros((5, 9, 11), dtype=np.float32) + volume[2, 4, 5] = 1 + pixels = np.stack((volume, np.zeros_like(volume))) if cohort else volume + source = _source( + pixels, domain=VolumeSourceSpatialDomain(source_depth=5), + spacing=(2, 0.5, 0.75), cohort=cohort, + ) + result = _execute(source) + expected_volume = gaussian(volume, sigma=(0.75, 3, 2)) + expected = np.stack((expected_volume, np.zeros_like(volume))) if cohort else expected_volume + np.testing.assert_allclose(image_payload_data(result), expected) + assert image_payload_metadata(result) == image_payload_metadata(source) + assert np.any(image_payload_data(result)[0, 1] if cohort else image_payload_data(result)[1]) + + +@pytest.mark.parametrize("channel_axis", (0, 1, -1)) +def test_declared_channel_axis_is_not_smoothed(channel_axis): + channels = np.zeros((2, 9, 11), dtype=np.float32) + channels[0, 4, 5] = 1 + pixels = np.moveaxis(channels, 0, channel_axis) + result = _execute(_source(pixels, channel_axis=channel_axis)) + expected = np.moveaxis(np.stack([ + gaussian(plane, sigma=(3, 2)) for plane in channels + ]), 0, channel_axis) + np.testing.assert_allclose(image_payload_data(result), expected) + + +def test_physical_volume_with_channels_and_independent_sites(): + pixels = np.zeros((2, 5, 9, 11, 2), dtype=np.float32) + pixels[0, 2, 4, 5, 0] = 1 + source = _source( + pixels, domain=VolumeSourceSpatialDomain(source_depth=5), + spacing=(2, 0.5, 0.75), channel_axis=-1, cohort=True, + ) + result = _execute(source) + expected = np.zeros_like(pixels) + expected[0, ..., 0] = gaussian(pixels[0, ..., 0], sigma=(0.75, 3, 2)) + np.testing.assert_allclose(image_payload_data(result), expected) + assert image_payload_metadata(result) == image_payload_metadata(source) + + +def test_missing_physical_z_spacing_still_rejects(): + source = _source(np.zeros((3, 9, 11)), domain=VolumeSourceSpatialDomain(source_depth=3)) + with pytest.raises(ValueError, match="Cannot project"): + _execute(source) + + +def test_invalid_channel_and_spatial_rank_still_reject(): + with pytest.raises(ValueError, match="channel axis"): + _execute(_source(np.zeros((9, 11)), channel_axis=4)) + with pytest.raises(ValueError, match="spatial rank"): + _execute(_source(np.zeros((9, 11)), domain=VolumeSourceSpatialDomain(source_depth=3))) + + +@pytest.mark.parametrize( + "shape,channel_axis,non_channel_axes,yx", + ( + ((7,), None, (0,), None), + ((7, 9), 0, (1,), None), + ((7, 9), None, (0, 1), (0, 1)), + ((2, 7, 9, 3), -1, (0, 1, 2), (1, 2)), + ), +) +def test_optional_yx_and_strict_intrinsic_share_non_channel_projection( + shape, channel_axis, non_channel_axes, yx, +): + metadata = ImagePayloadMetadata(source_channel_axis=channel_axis) + pixels = np.zeros(shape) + assert metadata.non_channel_axes(pixels) == non_channel_axes + assert metadata.spatial_axes_yx(pixels) == yx + if yx is None: + with pytest.raises(ValueError, match="spatial rank"): + metadata.spatial_axes(pixels) + else: + assert metadata.spatial_axes(pixels) == yx + + +def test_yx_does_not_inherit_strict_volume_rank_requirement(): + metadata = ImagePayloadMetadata(source_spatial_domain=VolumeSourceSpatialDomain()) + pixels = np.zeros((7, 9)) + assert metadata.spatial_axes_yx(pixels) == (0, 1) + with pytest.raises(ValueError, match="spatial rank"): + metadata.spatial_axes(pixels) + + +def test_axis_capability_is_inherited_without_metadata_overrides(): + for name in ( + "non_channel_axes", "normalized_source_channel_axis", "spatial_axes_yx", + "is_declared_source_channel_plane", "is_declared_source_channel_stack", + ): + assert name not in ImagePayloadMetadata.__dict__ + assert getattr(ImagePayloadMetadata, name) is getattr(ImagePayloadAxisFields, name) + metadata = ImagePayloadMetadata() + assert metadata.source_channel_axis is None + assert metadata.plane_axis is None + assert metadata.non_channel_axes(np.zeros((3, 7, 9))) == (0, 1, 2) + + +@pytest.mark.parametrize("projection", ("spatial_axes_yx", "spatial_axes")) +def test_both_spatial_projections_preserve_invalid_channel_rejection(projection): + metadata = ImagePayloadMetadata(source_channel_axis=4) + with pytest.raises(ValueError, match="channel axis"): + getattr(metadata, projection)(np.zeros((7, 9))) + + +def test_plain_two_dimensional_pixels_preserve_unscaled_gaussian(): + pixels = np.zeros((9, 11), dtype=np.float32) + pixels[4, 5] = 1 + np.testing.assert_allclose(image_payload_data(_execute(pixels)), gaussian(pixels, sigma=1.5)) + + +@pytest.mark.parametrize("physical_volume", (False, True)) +def test_original_cohort_composition_keeps_every_source_plane(physical_volume): + planes = tuple( + ImagePayloadMetadata( + source_path=f"/synthetic/plane{index}.tif", + source_image_names=("Original",), + source_component_metadata={ + "well": "A01", "site": 1 if physical_volume else index + 1, + "z_index": index if physical_volume else 0, + }, + source_voxel_spacing=SourceVoxelSpacing( + values_zyx=(2, 0.5, 0.75) if physical_volume else (0.5, 0.75) + ), + ).payload_with(np.eye(9, 11, dtype=np.float32) * (index + 1), None) + for index in range(3) + ) + metadata = ImagePayloadMetadata.compose(planes).replace_fields( + plane_axis=RuntimePlaneAxis.RUNTIME_SLICE, + ) + if physical_volume: + metadata = metadata.replace_fields( + source_spatial_domain=VolumeSourceSpatialDomain().admit_source_cohort( + metadata.source_spatial_domain, depth=len(planes), + ) + ) + pixels = np.stack([image_payload_data(plane) for plane in planes]) + result = _execute(metadata.payload_with(pixels, None)) + expected = ( + gaussian(pixels, sigma=(0.75, 3, 2)) if physical_volume + else np.stack([gaussian(plane, sigma=(3, 2)) for plane in pixels]) + ) + np.testing.assert_allclose(image_payload_data(result), expected) + assert image_payload_metadata(result) == metadata + assert image_payload_metadata(result).source_provenance.source_plane_count == 3