From 8b1c7805cc67d5127526f897d9ca60d1d630db6e Mon Sep 17 00:00:00 2001 From: Noah Markowitz Date: Wed, 26 Aug 2026 16:15:06 -0400 Subject: [PATCH 01/65] ammend configs to select dandi api key --- docs/getting-started/configuration.md | 14 +++++++++- opticstream/cli/lsm/setup.py | 6 ++++- opticstream/cli/oct/setup.py | 4 +++ opticstream/config/lsm_scan_config.py | 9 +++++++ opticstream/config/psoct_scan_config.py | 8 ++++++ opticstream/flows/lsm/strip_upload_flow.py | 8 +++++- opticstream/flows/psoct/mosaic_upload_flow.py | 10 ++++++- .../flows/psoct/mosaic_volume_upload_flow.py | 10 ++++++- .../flows/psoct/tile_batch_upload_flow.py | 6 +++++ opticstream/tasks/dandi_upload.py | 18 ++++++++++--- tests/test_dandi_upload.py | 26 ++++++++++++++++++- 11 files changed, 110 insertions(+), 9 deletions(-) diff --git a/docs/getting-started/configuration.md b/docs/getting-started/configuration.md index 3df4416..fd32a1a 100644 --- a/docs/getting-started/configuration.md +++ b/docs/getting-started/configuration.md @@ -40,6 +40,19 @@ It is composed from: - top-level output and modality settings (`enface_modalities`, `volume_modalities`, naming formats, masking thresholds, `zarr_config`) +Both LSM and PS-OCT project configurations may reference a Prefect `Secret` +block in `dandi_api_key`. Select the block in the Prefect dashboard, or set it +during project setup by passing its block name, for example: + +```bash +opticstream oct setup PROJECT_NAME --dandi noah-dandi-api-key +opticstream lsm setup PROJECT_NAME --dandi noah-dandi-api-key +``` + +The API-key value remains in the Secret block; the project configuration stores +a block reference. If `dandi_api_key` is unset, upload tasks retain the legacy +instance-specific defaults (`dandi-api-key` or `linc-api-key`). + See the concepts section for more detail on these configuration models. ## Using local checkouts of dev dependencies @@ -76,4 +89,3 @@ directories instead of the remote git repositories, while other users who do not The exact `path = "..."` values are machine-specific. Each developer should adjust them in their own clone as needed. - diff --git a/opticstream/cli/lsm/setup.py b/opticstream/cli/lsm/setup.py index fa09834..ddbfab2 100644 --- a/opticstream/cli/lsm/setup.py +++ b/opticstream/cli/lsm/setup.py @@ -1,7 +1,10 @@ import logging +import warnings from pathlib import Path +from prefect.blocks.system import Secret + from opticstream.config import LSMScanConfig from opticstream.cli.lsm.cli import lsm_cli from opticstream.cli.setup_common import default_zarr_config @@ -15,7 +18,6 @@ datefmt="%Y-%m-%d %H:%M:%S", ) logger = logging.getLogger(__name__) -import warnings warnings.filterwarnings( "ignore", message=".*PydanticSerializationUnexpectedValue.*", @@ -52,6 +54,7 @@ def setup( project_base_path: Path | None = None, info_file: Path | None = None, output_path: Path | None = None, + dandi: str | None = None, ) -> None: update_block() ensure_lock(project_name) @@ -69,6 +72,7 @@ def setup( project_base_path=project_base_path if project_base_path else Path('.'), info_file=info_file if info_file else Path('./info.mat'), output_path=output_path if output_path else Path('.'), + dandi_api_key=Secret.load(dandi) if dandi else None, zarr_config=default_zarr_config(), ) scan_config.save(block_name, overwrite=True) diff --git a/opticstream/cli/oct/setup.py b/opticstream/cli/oct/setup.py index 1b1d80b..6dc7152 100644 --- a/opticstream/cli/oct/setup.py +++ b/opticstream/cli/oct/setup.py @@ -8,6 +8,8 @@ import warnings from pathlib import Path +from prefect.blocks.system import Secret + from opticstream.cli.oct import oct_cli from opticstream.cli.setup_common import default_zarr_config from opticstream.config.psoct_scan_config import get_psoct_scan_config_block_name @@ -56,6 +58,7 @@ def setup( grid_size_x_normal: int = 1, grid_size_x_tilted: int = 1, grid_size_y: int = 1, + dandi: str | None = None, ) -> None: """ Create or update the PSOCTScanConfig block for a project. @@ -83,6 +86,7 @@ def setup( }, mask_threshold_normal=_DEFAULT_MASK_NORMAL, mask_threshold_tilted=_DEFAULT_MASK_TILTED, + dandi_api_key=Secret.load(dandi) if dandi else None, zarr_config=default_zarr_config(), ) scan_config.save(block_name, overwrite=True) diff --git a/opticstream/config/lsm_scan_config.py b/opticstream/config/lsm_scan_config.py index 9e98a54..1478a10 100644 --- a/opticstream/config/lsm_scan_config.py +++ b/opticstream/config/lsm_scan_config.py @@ -4,6 +4,7 @@ from niizarr import ZarrConfig from prefect.blocks.core import Block +from prefect.blocks.system import Secret from pydantic import BaseModel, Field, field_validator from opticstream.config.utils import with_positions @@ -88,6 +89,13 @@ class LSMScanConfigModel(BaseModel): dandiset_path: str = Field( default="linc://000052/", description="Path to the DANDI set to use for upload" ) + dandi_api_key: Secret | None = Field( + default=None, + description=( + "Prefect Secret block containing the DANDI/LINC API key. " + "If not set, the uploader uses its instance-specific default Secret block." + ), + ) # for acquisition host cpu_affinity: Optional[List[int]] = Field( @@ -173,6 +181,7 @@ class LSMScanConfigOverrides(BaseModel): dandi_bin: Optional[str] = None dandi_instance: Optional[str] = None dandiset_path: Path | None = None + dandi_api_key: Secret | None = None cpu_affinity: Optional[List[int]] = Field(default=None) num_workers: Optional[int] = Field(default=None, ge=1) diff --git a/opticstream/config/psoct_scan_config.py b/opticstream/config/psoct_scan_config.py index 04bda90..df0f517 100644 --- a/opticstream/config/psoct_scan_config.py +++ b/opticstream/config/psoct_scan_config.py @@ -12,6 +12,7 @@ from pathlib import Path from prefect.blocks.core import Block +from prefect.blocks.system import Secret from pydantic import BaseModel, ConfigDict, Field, field_validator from niizarr import ZarrConfig @@ -265,6 +266,13 @@ class PSOCTScanConfigModel(BaseModel): default=None, description="Root path of the target DANDI dataset for upload, if not set, output will not be uploaded to DANDI", ) + dandi_api_key: Secret | None = Field( + default=None, + description=( + "Prefect Secret block containing the DANDI/LINC API key. " + "If not set, the uploader uses its instance-specific default Secret block." + ), + ) archive_path: Path | None = Field( default=None, description="Archive root path where raw tiles will be archived to, if not set, raw tiles will not be archived", diff --git a/opticstream/flows/lsm/strip_upload_flow.py b/opticstream/flows/lsm/strip_upload_flow.py index 369cf10..a9e5181 100644 --- a/opticstream/flows/lsm/strip_upload_flow.py +++ b/opticstream/flows/lsm/strip_upload_flow.py @@ -3,6 +3,7 @@ from typing import Any, Dict, Optional, Sequence from prefect import flow, get_run_logger +from prefect.blocks.system import Secret from opticstream.hooks.publish_hooks import ( publish_lsm_project_hook, @@ -36,6 +37,7 @@ def upload_strip_to_dandi_flow( output_path: Path, dandi_instance: str = "linc", dandi_bin: str = "dandi", + dandi_api_key: Secret | None = None, force_rerun: bool = False, ) -> None: """ @@ -46,7 +48,10 @@ def upload_strip_to_dandi_flow( logger.info(f"Output path: {output_path}") logger.info(f"Uploading {strip_ident} to DANDI") upload_to_dandi( - os.fspath(output_path), dandi_instance=dandi_instance, dandi_bin=dandi_bin + os.fspath(output_path), + dandi_instance=dandi_instance, + dandi_bin=dandi_bin, + dandi_api_key=dandi_api_key, ) logger.info(f"Successfully uploaded {strip_ident} to DANDI") @@ -71,6 +76,7 @@ def upload_strip_to_dandi_event_flow(payload: Dict[str, Any]) -> None: force_rerun=force_rerun_from_payload(payload), dandi_instance=payload.get("dandi_instance") or cfg.dandi_instance, dandi_bin=payload.get("dandi_bin") or cfg.dandi_bin, + dandi_api_key=cfg.dandi_api_key, ) # shutil.rmtree(output_path) diff --git a/opticstream/flows/psoct/mosaic_upload_flow.py b/opticstream/flows/psoct/mosaic_upload_flow.py index 6070c9d..7e2fcd9 100644 --- a/opticstream/flows/psoct/mosaic_upload_flow.py +++ b/opticstream/flows/psoct/mosaic_upload_flow.py @@ -1,6 +1,7 @@ from typing import Any, Dict, Optional, Sequence from prefect import flow, get_run_logger +from prefect.blocks.system import Secret from opticstream.hooks.publish_hooks import ( publish_oct_mosaic_hook, @@ -9,6 +10,7 @@ from opticstream.events import MOSAIC_ENFACE_STITCHED, get_event_trigger from opticstream.events.psoct_events import MOSAIC_ENFACE_UPLOADED from opticstream.flows.psoct.utils import ( + load_scan_config_for_payload, mosaic_ident_from_payload, nifti_paths_from_enface_outputs, ) @@ -32,6 +34,7 @@ def upload_mosaic_enface_to_dandi_flow( enface_outputs: Dict[str, str], *, dandi_instance: str = "linc", + dandi_api_key: Secret | None = None, force_rerun: bool = False, ) -> None: logger = get_run_logger() @@ -40,16 +43,21 @@ def upload_mosaic_enface_to_dandi_flow( logger.warning("No enface NIfTI files found for %s", mosaic_ident) return upload_to_dandi_batch( - file_list=file_list, dandi_instance=dandi_instance, realpath=False + file_list=file_list, + dandi_instance=dandi_instance, + realpath=False, + dandi_api_key=dandi_api_key, ) @flow def upload_mosaic_enface_to_dandi_event_flow(payload: Dict[str, Any]) -> Dict[str, Any]: mosaic_ident = mosaic_ident_from_payload(payload) + cfg = load_scan_config_for_payload(payload) return upload_mosaic_enface_to_dandi_flow( mosaic_ident=mosaic_ident, enface_outputs=payload.get("symlink_targets", {}), + dandi_api_key=cfg.dandi_api_key, force_rerun=force_rerun_from_payload(payload), ) diff --git a/opticstream/flows/psoct/mosaic_volume_upload_flow.py b/opticstream/flows/psoct/mosaic_volume_upload_flow.py index 730aefe..ab080b9 100644 --- a/opticstream/flows/psoct/mosaic_volume_upload_flow.py +++ b/opticstream/flows/psoct/mosaic_volume_upload_flow.py @@ -1,6 +1,7 @@ from typing import Any, Dict, Optional, Sequence from prefect import flow, get_run_logger +from prefect.blocks.system import Secret from opticstream.hooks.publish_hooks import ( publish_oct_mosaic_hook, @@ -13,6 +14,7 @@ ) from opticstream.events.psoct_event_emitters import emit_mosaic_psoct_event from opticstream.flows.psoct.utils import ( + load_scan_config_for_payload, mosaic_ident_from_payload, non_empty_paths_from_mapping, ) @@ -36,6 +38,7 @@ def upload_mosaic_volume_to_dandi_flow( volume_outputs: Dict[str, str], *, dandi_instance: str = "linc", + dandi_api_key: Secret | None = None, force_rerun: bool = False, ) -> Dict[str, Any]: logger = get_run_logger() @@ -44,7 +47,10 @@ def upload_mosaic_volume_to_dandi_flow( logger.warning("No volume files found for %s", mosaic_ident) return {"uploaded": 0} upload_to_dandi_batch( - file_list=file_list, dandi_instance=dandi_instance, realpath=False + file_list=file_list, + dandi_instance=dandi_instance, + realpath=False, + dandi_api_key=dandi_api_key, ) emit_mosaic_psoct_event(MOSAIC_VOLUME_UPLOADED, mosaic_ident) return {"uploaded": len(file_list)} @@ -53,9 +59,11 @@ def upload_mosaic_volume_to_dandi_flow( @flow def upload_mosaic_volume_to_dandi_event_flow(payload: Dict[str, Any]) -> Dict[str, Any]: mosaic_ident = mosaic_ident_from_payload(payload) + cfg = load_scan_config_for_payload(payload) return upload_mosaic_volume_to_dandi_flow( mosaic_ident=mosaic_ident, volume_outputs=payload.get("volume_outputs", {}), + dandi_api_key=cfg.dandi_api_key, force_rerun=force_rerun_from_payload(payload), ) diff --git a/opticstream/flows/psoct/tile_batch_upload_flow.py b/opticstream/flows/psoct/tile_batch_upload_flow.py index 87f454c..b22bdb7 100644 --- a/opticstream/flows/psoct/tile_batch_upload_flow.py +++ b/opticstream/flows/psoct/tile_batch_upload_flow.py @@ -2,6 +2,7 @@ from typing import Any, Dict, Optional, Sequence from prefect import flow +from prefect.blocks.system import Secret from prefect.logging import get_run_logger from opticstream.hooks.publish_hooks import ( @@ -11,6 +12,7 @@ from opticstream.events import BATCH_ARCHIVED, BATCH_UPLOADED, get_event_trigger from opticstream.flows.psoct.utils import ( batch_ident_from_payload, + load_scan_config_for_payload, path_list_from_payload, ) from opticstream.state.milestone_wrappers_psoct import oct_batch_processing_milestone @@ -32,6 +34,7 @@ def upload_to_dandi_tile_batch( *, dandi_instance: str = "linc", realpath: bool = True, + dandi_api_key: Secret | None = None, force_rerun: bool = False, ) -> None: logger = get_run_logger() @@ -43,15 +46,18 @@ def upload_to_dandi_tile_batch( file_list=[str(path) for path in file_list], dandi_instance=dandi_instance, realpath=realpath, + dandi_api_key=dandi_api_key, ) @flow def upload_to_linc_batch_event_flow(payload: Dict[str, Any]) -> None: batch_ident = batch_ident_from_payload(payload) + cfg = load_scan_config_for_payload(payload) return upload_to_dandi_tile_batch( batch_id=batch_ident, file_list=path_list_from_payload(payload), + dandi_api_key=cfg.dandi_api_key, force_rerun=force_rerun_from_payload(payload), ) diff --git a/opticstream/tasks/dandi_upload.py b/opticstream/tasks/dandi_upload.py index 36e8830..00ca6ca 100644 --- a/opticstream/tasks/dandi_upload.py +++ b/opticstream/tasks/dandi_upload.py @@ -65,6 +65,7 @@ def build_dandi_upload_command( def _build_dandi_upload_env( *, dandi_instance: DANDI_INSTANCE, + dandi_api_key: Secret | None = None, ) -> Dict[str, str]: """ Build environment variables required by the DANDI/LINC CLI. @@ -72,15 +73,20 @@ def _build_dandi_upload_env( Kept as a helper so both single-file and batch upload implementations share identical secret loading and env setup. """ - if dandi_instance == "linc": + if dandi_api_key is not None: + api_key = dandi_api_key.get() + elif dandi_instance == "linc": api_key = Secret.load(LINC_API_TOKEN_BLOCK_NAME, validate=False).get() + else: + api_key = Secret.load(DANDI_API_TOKEN_BLOCK_NAME, validate=False).get() + + if dandi_instance == "linc": return { "LINC_API_KEY": api_key, "DANDI_API_KEY": api_key, "DANDI_DEVEL": "1", } - api_key = Secret.load(DANDI_API_TOKEN_BLOCK_NAME, validate=False).get() return { "DANDI_API_KEY": api_key, "DANDI_DEVEL": "1", @@ -95,6 +101,7 @@ def upload_to_dandi_batch( dandi_bin: str = "dandi", realpath: bool = True, max_jobs: str = "10:10", + dandi_api_key: Secret | None = None, ) -> None: """ Upload multiple files to DANDI (or optionally to the LINC instance). @@ -110,7 +117,10 @@ def upload_to_dandi_batch( ) # Load secrets inside the task (not at import time). - env = _build_dandi_upload_env(dandi_instance=dandi_instance) + env = _build_dandi_upload_env( + dandi_instance=dandi_instance, + dandi_api_key=dandi_api_key, + ) logger.info("Running DANDI batch upload with %s files", len(file_list)) logger.info(command) @@ -133,6 +143,7 @@ def upload_to_dandi( dandi_bin: str = "dandi", realpath: bool = True, max_jobs: str = "10:10", + dandi_api_key: Secret | None = None, ) -> None: """ Upload the file to DANDI. @@ -143,6 +154,7 @@ def upload_to_dandi( dandi_bin=dandi_bin, realpath=realpath, max_jobs=max_jobs, + dandi_api_key=dandi_api_key, ) diff --git a/tests/test_dandi_upload.py b/tests/test_dandi_upload.py index bd02238..cfa1951 100644 --- a/tests/test_dandi_upload.py +++ b/tests/test_dandi_upload.py @@ -1,4 +1,9 @@ -from opticstream.tasks.dandi_upload import build_dandi_upload_command +from prefect.blocks.system import Secret + +from opticstream.tasks.dandi_upload import ( + _build_dandi_upload_env, + build_dandi_upload_command, +) def test_build_dandi_upload_command_defaults_to_dandi_instance() -> None: @@ -21,3 +26,22 @@ def test_build_dandi_upload_command_includes_linc_instance_flag() -> None: assert "-i linc" in cmd assert "/tmp/file1.nii" in cmd assert "/tmp/file2.nii" in cmd + + +def test_selected_secret_is_used_for_dandi() -> None: + env = _build_dandi_upload_env( + dandi_instance="dandi", + dandi_api_key=Secret(value="project-token"), + ) + + assert env["DANDI_API_KEY"] == "project-token" + + +def test_selected_secret_is_used_for_linc_compatibility_variables() -> None: + env = _build_dandi_upload_env( + dandi_instance="linc", + dandi_api_key=Secret(value="project-token"), + ) + + assert env["LINC_API_KEY"] == "project-token" + assert env["DANDI_API_KEY"] == "project-token" From 933d28396c465ae9475c0ed21054482d302edb2b Mon Sep 17 00:00:00 2001 From: Noah Markowitz Date: Thu, 27 Aug 2026 09:06:37 -0400 Subject: [PATCH 02/65] update pytests --- tests/test_lsm_delete_cli.py | 57 ------ tests/test_lsm_state_guards.py | 129 -------------- tests/test_state_guards.py | 313 +++++++++++++++++++++++++++++++++ 3 files changed, 313 insertions(+), 186 deletions(-) delete mode 100644 tests/test_lsm_delete_cli.py delete mode 100644 tests/test_lsm_state_guards.py create mode 100644 tests/test_state_guards.py diff --git a/tests/test_lsm_delete_cli.py b/tests/test_lsm_delete_cli.py deleted file mode 100644 index cb3f92d..0000000 --- a/tests/test_lsm_delete_cli.py +++ /dev/null @@ -1,57 +0,0 @@ -import pytest - -from opticstream.cli.lsm.delete import _validate_delete_args - - -def test_validate_delete_args_accepts_required_combinations(): - _validate_delete_args( - kind="slice", - slice_id=1, - channel_id=None, - strip_id=None, - ) - _validate_delete_args( - kind="channel", - slice_id=1, - channel_id=2, - strip_id=None, - ) - _validate_delete_args( - kind="strip", - slice_id=1, - channel_id=2, - strip_id=3, - ) - - -@pytest.mark.parametrize( - ("kind", "slice_id", "channel_id", "strip_id", "expected_message"), - [ - ("slice", None, None, None, "`--slice-id` is required when `--kind slice`."), - ( - "channel", - None, - None, - None, - "`--slice-id` is required when `--kind channel`.", - ), - ("channel", 1, None, None, "`--channel-id` is required when `--kind channel`."), - ("strip", None, None, None, "`--slice-id` is required when `--kind strip`."), - ("strip", 1, None, None, "`--channel-id` is required when `--kind strip`."), - ("strip", 1, 2, None, "`--strip-id` is required when `--kind strip`."), - ], -) -def test_validate_delete_args_rejects_missing_required_ids( - kind: str, - slice_id: int | None, - channel_id: int | None, - strip_id: int | None, - expected_message: str, -): - with pytest.raises(ValueError, match=expected_message): - _validate_delete_args( - kind=kind, # type: ignore[arg-type] - slice_id=slice_id, - channel_id=channel_id, - strip_id=strip_id, - ) diff --git a/tests/test_lsm_state_guards.py b/tests/test_lsm_state_guards.py deleted file mode 100644 index 2670c6a..0000000 --- a/tests/test_lsm_state_guards.py +++ /dev/null @@ -1,129 +0,0 @@ -"""Unit tests for opticstream.state.state_guards.""" - -import pytest -from types import SimpleNamespace - -from opticstream.state.state_guards import ( - RunDecision, - enter_flow_stage, - force_rerun_from_payload, - enter_milestone_stage, -) -from opticstream.state.project_state_core import ProcessingState - - -@pytest.mark.parametrize( - "payload,expected", - [ - ({}, False), - ({"force_rerun": False}, False), - ({"force_rerun": True}, True), - ({"force_rerun": 1}, True), - ({"force_rerun": 0}, False), - ], -) -def test_force_rerun_from_payload(payload, expected): - assert force_rerun_from_payload(payload) is expected - - -def _mock_logger(monkeypatch): - class _Logger: - def info(self, *_args, **_kwargs): - return None - - def warning(self, *_args, **_kwargs): - return None - - monkeypatch.setattr( - "opticstream.flows.lsm.state_guards.get_run_logger", lambda: _Logger() - ) - - -def test_enter_flow_stage_skip_completed(monkeypatch): - _mock_logger(monkeypatch) - called = {"started": False} - - decision = enter_flow_stage( - SimpleNamespace(processing_state=ProcessingState.COMPLETED), - force_rerun=False, - skip_if_running=False, - item_ident="item-1", - mark_started=lambda: called.__setitem__("started", True), - ) - assert decision == RunDecision.SKIPPED - assert called["started"] is False - - -def test_enter_flow_stage_restarted(monkeypatch): - _mock_logger(monkeypatch) - called = {"started": False} - - decision = enter_flow_stage( - SimpleNamespace(processing_state=ProcessingState.COMPLETED), - force_rerun=True, - skip_if_running=False, - item_ident="item-1", - mark_started=lambda: called.__setitem__("started", True), - ) - assert decision == RunDecision.RESTARTED - assert called["started"] is True - - -def test_enter_flow_stage_running_and_forced_warns_and_restarts(monkeypatch): - _mock_logger(monkeypatch) - called = {"started": False} - - decision = enter_flow_stage( - SimpleNamespace(processing_state=ProcessingState.RUNNING), - force_rerun=True, - skip_if_running=True, - item_ident="item-1", - mark_started=lambda: called.__setitem__("started", True), - ) - assert decision == RunDecision.RESTARTED - assert called["started"] is True - - -def test_enter_milestone_stage_skip_when_done(monkeypatch): - _mock_logger(monkeypatch) - calls = {"reset": 0} - - decision = enter_milestone_stage( - item_state_view=SimpleNamespace(uploaded=True), - item_ident="strip-1", - field_name="uploaded", - force_rerun=False, - reset=lambda: calls.__setitem__("reset", calls["reset"] + 1), - ) - assert decision == RunDecision.SKIPPED - assert calls["reset"] == 0 - - -def test_enter_milestone_stage_restarted_when_done_and_forced(monkeypatch): - _mock_logger(monkeypatch) - calls = {"reset": 0} - - decision = enter_milestone_stage( - item_state_view=SimpleNamespace(uploaded=True), - item_ident="strip-1", - field_name="uploaded", - force_rerun=True, - reset=lambda: calls.__setitem__("reset", calls["reset"] + 1), - ) - assert decision == RunDecision.RESTARTED - assert calls["reset"] == 1 - - -def test_enter_milestone_stage_started_when_not_done(monkeypatch): - _mock_logger(monkeypatch) - calls = {"reset": 0} - - decision = enter_milestone_stage( - item_state_view=SimpleNamespace(uploaded=False), - item_ident="strip-1", - field_name="uploaded", - force_rerun=False, - reset=lambda: calls.__setitem__("reset", calls["reset"] + 1), - ) - assert decision == RunDecision.STARTED - assert calls["reset"] == 1 diff --git a/tests/test_state_guards.py b/tests/test_state_guards.py new file mode 100644 index 0000000..ee79355 --- /dev/null +++ b/tests/test_state_guards.py @@ -0,0 +1,313 @@ +"""Unit tests for the shared LSM/PS-OCT state guards.""" + +from types import SimpleNamespace + +import pytest + +import opticstream.state.state_guards as state_guards +from opticstream.state.lsm_project_state import LSMChannelId, LSMStripId +from opticstream.state.oct_project_state import OCTBatchId, OCTMosaicId +from opticstream.state.project_state_core import ProcessingState +from opticstream.state.state_guards import ( + RunDecision, + enter_flow_stage, + enter_milestone_stage, + force_rerun_from_payload, + should_skip_run, +) + + +class _RecordingLogger: + def __init__(self) -> None: + self.info_messages: list[str] = [] + self.warning_messages: list[str] = [] + + def info(self, message: str, *_args, **_kwargs) -> None: + self.info_messages.append(message) + + def warning(self, message: str, *_args, **_kwargs) -> None: + self.warning_messages.append(message) + + +@pytest.fixture(autouse=True) +def recording_logger(monkeypatch) -> _RecordingLogger: + """Keep decision tests independent of a running Prefect flow context.""" + logger = _RecordingLogger() + monkeypatch.setattr(state_guards, "get_run_logger", lambda: logger) + return logger + + +@pytest.mark.parametrize( + "payload,expected", + [ + ({}, False), + ({"force_rerun": False}, False), + ({"force_rerun": True}, True), + ({"force_rerun": 1}, True), + ({"force_rerun": 0}, False), + ], +) +def test_force_rerun_from_payload(payload, expected): + assert force_rerun_from_payload(payload) is expected + + +@pytest.mark.parametrize( + ( + "processing_state", + "force_rerun", + "skip_if_running", + "expected_decision", + "expected_started_calls", + ), + [ + (None, False, False, RunDecision.STARTED, 1), + (ProcessingState.PENDING, False, False, RunDecision.STARTED, 1), + (ProcessingState.FAILED, False, False, RunDecision.STARTED, 1), + (ProcessingState.COMPLETED, False, False, RunDecision.SKIPPED, 0), + (ProcessingState.COMPLETED, True, False, RunDecision.RESTARTED, 1), + (ProcessingState.RUNNING, False, True, RunDecision.SKIPPED, 0), + (ProcessingState.RUNNING, True, True, RunDecision.RESTARTED, 1), + (ProcessingState.RUNNING, False, False, RunDecision.STARTED, 1), + ], +) +def test_enter_flow_stage_decisions( + processing_state, + force_rerun, + skip_if_running, + expected_decision, + expected_started_calls, +): + calls = {"started": 0} + view = ( + None + if processing_state is None + else SimpleNamespace(processing_state=processing_state) + ) + + decision = enter_flow_stage( + view, + force_rerun=force_rerun, + skip_if_running=skip_if_running, + item_ident="item-1", + mark_started=lambda: calls.__setitem__("started", calls["started"] + 1), + ) + + assert decision == expected_decision + assert calls["started"] == expected_started_calls + + +def test_forced_running_flow_warns(recording_logger): + decision = enter_flow_stage( + SimpleNamespace(processing_state=ProcessingState.RUNNING), + force_rerun=True, + skip_if_running=True, + item_ident="item-1", + mark_started=lambda: None, + ) + + assert decision == RunDecision.RESTARTED + assert any("duplicate processing" in msg for msg in recording_logger.warning_messages) + + +@pytest.mark.parametrize( + ( + "item_state_view", + "force_rerun", + "expected_decision", + "expected_reset_calls", + ), + [ + (None, False, RunDecision.STARTED, 1), + (SimpleNamespace(), False, RunDecision.STARTED, 1), + (SimpleNamespace(uploaded=False), False, RunDecision.STARTED, 1), + (SimpleNamespace(uploaded=True), False, RunDecision.SKIPPED, 0), + (SimpleNamespace(uploaded=True), True, RunDecision.RESTARTED, 1), + ], +) +def test_enter_milestone_stage_decisions( + item_state_view, + force_rerun, + expected_decision, + expected_reset_calls, +): + calls = {"reset": 0} + + decision = enter_milestone_stage( + item_state_view=item_state_view, + item_ident="item-1", + field_name="uploaded", + force_rerun=force_rerun, + reset=lambda: calls.__setitem__("reset", calls["reset"] + 1), + ) + + assert decision == expected_decision + assert calls["reset"] == expected_reset_calls + + +@pytest.mark.parametrize( + "decision,expected", + [ + (RunDecision.SKIPPED, True), + (RunDecision.STARTED, False), + (RunDecision.RESTARTED, False), + ], +) +def test_should_skip_run(decision, expected): + assert should_skip_run(decision) is expected + + +class _StateContext: + def __init__(self, state) -> None: + self.state = state + + def __enter__(self): + return self.state + + def __exit__(self, *_args) -> None: + return None + + +class _RecordingState: + def __init__(self) -> None: + self.calls: list[str] = [] + + def mark_started(self) -> None: + self.calls.append("mark_started") + + def reset_uploaded(self) -> None: + self.calls.append("reset_uploaded") + + +class _RecordingService: + def __init__(self, state) -> None: + self.state = state + self.calls: list[str] = [] + + def _open(self, name: str) -> _StateContext: + self.calls.append(name) + return _StateContext(self.state) + + def open_strip(self, *, strip_ident) -> _StateContext: + return self._open("open_strip") + + def open_channel(self, *, channel_ident) -> _StateContext: + return self._open("open_channel") + + def open_batch(self, *, batch_ident) -> _StateContext: + return self._open("open_batch") + + def open_mosaic(self, *, mosaic_ident) -> _StateContext: + return self._open("open_mosaic") + + +@pytest.mark.parametrize( + "item_ident,service_name,open_method", + [ + ( + LSMStripId(project_name="p", slice_id=1, channel_id=2, strip_id=3), + "LSM_STATE_SERVICE", + "open_strip", + ), + ( + LSMChannelId(project_name="p", slice_id=1, channel_id=2), + "LSM_STATE_SERVICE", + "open_channel", + ), + ( + OCTBatchId( + project_name="p", slice_id=1, mosaic_id=2, batch_id=3 + ), + "OCT_STATE_SERVICE", + "open_batch", + ), + ( + OCTMosaicId(project_name="p", slice_id=1, mosaic_id=2), + "OCT_STATE_SERVICE", + "open_mosaic", + ), + ], +) +def test_default_state_service_routing( + monkeypatch, + item_ident, + service_name, + open_method, +): + state = _RecordingState() + service = _RecordingService(state) + monkeypatch.setattr(state_guards, service_name, service) + + decision = enter_flow_stage( + None, + force_rerun=False, + skip_if_running=False, + item_ident=item_ident, + ) + + assert decision == RunDecision.STARTED + assert service.calls == [open_method] + assert state.calls == ["mark_started"] + + +def test_default_milestone_reset(monkeypatch): + state = _RecordingState() + service = _RecordingService(state) + monkeypatch.setattr(state_guards, "LSM_STATE_SERVICE", service) + + decision = enter_milestone_stage( + item_state_view=SimpleNamespace(uploaded=False), + item_ident=LSMStripId( + project_name="p", slice_id=1, channel_id=2, strip_id=3 + ), + field_name="uploaded", + force_rerun=False, + ) + + assert decision == RunDecision.STARTED + assert service.calls == ["open_strip"] + assert state.calls == ["reset_uploaded"] + + +def test_default_state_service_rejects_unsupported_identifier(): + with pytest.raises(TypeError, match="unsupported item_ident type"): + enter_flow_stage( + None, + force_rerun=False, + skip_if_running=False, + item_ident="unsupported", + ) + + +@pytest.mark.parametrize( + "entrypoint,missing_method", + [ + ("flow", "mark_started"), + ("milestone", "reset_uploaded"), + ], +) +def test_default_state_mutation_requires_expected_method( + monkeypatch, + entrypoint, + missing_method, +): + service = _RecordingService(SimpleNamespace()) + monkeypatch.setattr(state_guards, "LSM_STATE_SERVICE", service) + item_ident = LSMStripId( + project_name="p", slice_id=1, channel_id=2, strip_id=3 + ) + + with pytest.raises(AttributeError, match=missing_method): + if entrypoint == "flow": + enter_flow_stage( + None, + force_rerun=False, + skip_if_running=False, + item_ident=item_ident, + ) + else: + enter_milestone_stage( + item_state_view=SimpleNamespace(uploaded=False), + item_ident=item_ident, + field_name="uploaded", + force_rerun=False, + ) From 70aded7cb51f0f7e258ca297ddd295d079d8940b Mon Sep 17 00:00:00 2001 From: NoahMarkowitz Date: Thu, 27 Aug 2026 13:12:37 -0400 Subject: [PATCH 03/65] debugging updates --- .gitignore | 3 + opticstream.egg-info/PKG-INFO | 117 +++++++++++++++++ opticstream.egg-info/SOURCES.txt | 147 ++++++++++++++++++++++ opticstream.egg-info/dependency_links.txt | 1 + opticstream.egg-info/entry_points.txt | 3 + opticstream.egg-info/requires.txt | 25 ++++ opticstream.egg-info/top_level.txt | 1 + tests/test_lsm_flow_helpers.py | 12 +- tests/test_oct_watch_mosaic3.py | 25 ++-- tests/test_pipeline_opts_builder.py | 2 +- uv.lock | 89 +++++++++++-- 11 files changed, 398 insertions(+), 27 deletions(-) create mode 100644 opticstream.egg-info/PKG-INFO create mode 100644 opticstream.egg-info/SOURCES.txt create mode 100644 opticstream.egg-info/dependency_links.txt create mode 100644 opticstream.egg-info/entry_points.txt create mode 100644 opticstream.egg-info/requires.txt create mode 100644 opticstream.egg-info/top_level.txt diff --git a/.gitignore b/.gitignore index 5559d11..66a566a 100644 --- a/.gitignore +++ b/.gitignore @@ -2,3 +2,6 @@ *.pyc *.nii .vscode/ +/db/ +.DS_Store +.venv \ No newline at end of file diff --git a/opticstream.egg-info/PKG-INFO b/opticstream.egg-info/PKG-INFO new file mode 100644 index 0000000..fe87753 --- /dev/null +++ b/opticstream.egg-info/PKG-INFO @@ -0,0 +1,117 @@ +Metadata-Version: 2.4 +Name: opticstream +Version: 0.1.0 +Summary: Add your description here +Requires-Python: >=3.11 +Description-Content-Type: text/markdown +Requires-Dist: cyclopts>=3.3.0 +Requires-Dist: linc-convert[all] @ git+https://github.com/lincbrain/linc-convert.git@dc8f3243df01d09493a13e53305adede08784695 +Requires-Dist: nifti-zarr @ git+https://github.com/calvinchai/nifti-zarr-py.git@12336420beaa023cbdd9d9e5c24e3c115687fe9a +Requires-Dist: psoct-toolbox @ git+https://github.com/calvinchai/psoct-toolbox.git@5182337044d2b7f8337ca205a33c9da3ddd69bda +Requires-Dist: matplotlib>=3.10.8 +Requires-Dist: prefect[shell,slack,sqlalchemy]>=3.6.20 +Requires-Dist: watchdog +Requires-Dist: psutil +Requires-Dist: slack-sdk +Requires-Dist: pydantic +Requires-Dist: jinja2 +Requires-Dist: PyYAML +Requires-Dist: dask +Requires-Dist: nibabel +Requires-Dist: numpy +Requires-Dist: psycopg2-binary +Provides-Extra: dev +Requires-Dist: pytest; extra == "dev" +Requires-Dist: pytest-cov; extra == "dev" +Requires-Dist: mkdocs; extra == "dev" +Requires-Dist: mkdocs-material; extra == "dev" +Requires-Dist: mkdocstrings[python]; extra == "dev" +Requires-Dist: mkdocs-git-revision-date-localized-plugin; extra == "dev" +Requires-Dist: ruff; extra == "dev" + +## OpticStream + +OpticStream provides Prefect-based workflows and utilities for processing large +microscopy and imaging datasets, including LSM strips and PS-OCT tiles. + +The CLI is exposed as the `opticstream` command, with a short alias `ops`. + +```bash +opticstream --help # or: ops --help +opticstream deploy ... # or: ops deploy ... +``` + +## Documentation + +Full documentation is available at the hosted documentation site: + +https://your-docs-url-here + +If you want to build and browse the documentation locally while developing, +see the developer documentation under `docs/developer`. + +## Quick start + +### 1. Install and activate an environment (uv recommended) + +We recommend using [`uv`](https://docs.astral.sh/uv/) to manage the development +environment for OpticStream. + +```bash +git clone https://github.com/ORG/opticstream.git +cd opticstream + +# create and sync a uv-managed environment from pyproject.toml / uv.lock +uv sync + +# activate the virtual environment that uv created (optional) +source .venv/bin/activate # or use `uv run` directly, see below +``` + +You can also use a traditional virtual environment and `pip install -e .` if +you prefer. See the Installation guide in the documentation site for full +details on uv, pip, and pipx based installs. + +### 2. Explore the CLI + +```bash +opticstream --help # or: ops --help +opticstream deploy --help +``` + +### 3. Follow the full quickstart + +For a complete walkthrough (including configuring scan blocks and running an +example LSM strip processing flow), see the Quickstart in the documentation +site (`docs/getting-started/quickstart.md` when served with MkDocs). + +## Note about git-based dev dependencies + +OpticStream currently depends on several git-based repositories for development: + +- `linc-convert` (branch `lsm-features`) +- `nifti-zarr` (branch `port-multizarr`) +- `psoct-toolbox` + +These are referenced in `pyproject.toml` via explicit git URLs (and optionally in +`[tool.uv.sources]` for local development overrides). + +**Maintainers:** whenever any of the following happens, you must review and update +these references: + +- The `opticstream` repository is transferred to a different organization or + GitHub namespace. +- The branches used in these dependency URLs are renamed, merged, or deleted. +- The project is prepared for, or published to, PyPI and you switch to using + PyPI-hosted versions of these packages. + +In those cases, check and update: + +- The git URLs and branch names in `[project.dependencies]` in `pyproject.toml`. +- Any `[tool.uv.sources]` entries in `pyproject.toml` (for example `git = ...`, + `branch = ...`, or `path = ...` values). + +Avoid committing hard-coded, machine-specific paths (such as `path = "/home/username/..."`) +that may not exist on other systems. Failing to update these references can cause installs +from git or PyPI to break or to pull the wrong versions of the dev dependencies. + diff --git a/opticstream.egg-info/SOURCES.txt b/opticstream.egg-info/SOURCES.txt new file mode 100644 index 0000000..b9b54cf --- /dev/null +++ b/opticstream.egg-info/SOURCES.txt @@ -0,0 +1,147 @@ +README.md +pyproject.toml +opticstream/__init__.py +opticstream.egg-info/PKG-INFO +opticstream.egg-info/SOURCES.txt +opticstream.egg-info/dependency_links.txt +opticstream.egg-info/entry_points.txt +opticstream.egg-info/requires.txt +opticstream.egg-info/top_level.txt +opticstream/artifacts/__init__.py +opticstream/artifacts/common.py +opticstream/artifacts/lsm.py +opticstream/artifacts/oct.py +opticstream/cli/__init__.py +opticstream/cli/deploy_cmds.py +opticstream/cli/init.py +opticstream/cli/process_priority.py +opticstream/cli/root.py +opticstream/cli/setup_common.py +opticstream/cli/state_common.py +opticstream/cli/utils_cmds.py +opticstream/cli/lsm/__init__.py +opticstream/cli/lsm/cli.py +opticstream/cli/lsm/serve.py +opticstream/cli/lsm/setup.py +opticstream/cli/lsm/state.py +opticstream/cli/lsm/watch.py +opticstream/cli/oct/__init__.py +opticstream/cli/oct/cli.py +opticstream/cli/oct/deploy.py +opticstream/cli/oct/serve.py +opticstream/cli/oct/setup.py +opticstream/cli/oct/state.py +opticstream/cli/oct/watch.py +opticstream/cli/utils/__init__.py +opticstream/cli/utils/clear.py +opticstream/cli/utils/cli.py +opticstream/cli/utils/convert_image.py +opticstream/cli/utils/flow_runs.py +opticstream/cli/utils/hash_dir.py +opticstream/cli/utils/inspect_deps.py +opticstream/cli/utils/repull_deps.py +opticstream/config/__init__.py +opticstream/config/constants.py +opticstream/config/lsm_scan_config.py +opticstream/config/pipeline_opts_builder.py +opticstream/config/psoct_scan_config.py +opticstream/config/utils.py +opticstream/data_processing/__init__.py +opticstream/data_processing/psoct_recon/__init__.py +opticstream/data_processing/psoct_recon/complex2vol.py +opticstream/data_processing/psoct_recon/spectral2complex.py +opticstream/data_processing/psoct_recon/vol2enface.py +opticstream/data_processing/qc/__init__.py +opticstream/data_processing/qc/convert_image.py +opticstream/data_processing/qc/draw_planes.py +opticstream/data_processing/qc/generate_mask.py +opticstream/data_processing/stitch/__init__.py +opticstream/data_processing/stitch/blend.py +opticstream/data_processing/stitch/coords.py +opticstream/data_processing/stitch/fiji.py +opticstream/data_processing/stitch/fit_coord_files.py +opticstream/data_processing/stitch/grid.py +opticstream/events/__init__.py +opticstream/events/event_emitter_core.py +opticstream/events/lsm_event_emitters.py +opticstream/events/lsm_events.py +opticstream/events/psoct_event_emitters.py +opticstream/events/psoct_events.py +opticstream/events/utils.py +opticstream/flows/__init__.py +opticstream/flows/lsm/__init__.py +opticstream/flows/lsm/channel_process_flow.py +opticstream/flows/lsm/channel_upload_flow.py +opticstream/flows/lsm/channel_volume_flow.py +opticstream/flows/lsm/strip_archive_flow.py +opticstream/flows/lsm/strip_cleanup_flow.py +opticstream/flows/lsm/strip_process_flow.py +opticstream/flows/lsm/strip_upload_flow.py +opticstream/flows/lsm/utils.py +opticstream/flows/psoct/__init__.py +opticstream/flows/psoct/mosaic_coordinate_flow.py +opticstream/flows/psoct/mosaic_enface_qc_flow.py +opticstream/flows/psoct/mosaic_process_flow.py +opticstream/flows/psoct/mosaic_upload_flow.py +opticstream/flows/psoct/mosaic_volume_stitch_flow.py +opticstream/flows/psoct/mosaic_volume_upload_flow.py +opticstream/flows/psoct/slice_process_flow.py +opticstream/flows/psoct/tile_batch_archive_flow.py +opticstream/flows/psoct/tile_batch_process_flow.py +opticstream/flows/psoct/tile_batch_processed_validation.py +opticstream/flows/psoct/tile_batch_upload_flow.py +opticstream/flows/psoct/tile_file_reference.py +opticstream/flows/psoct/utils.py +opticstream/hooks/__init__.py +opticstream/hooks/check_channel_ready_hook.py +opticstream/hooks/check_mosaic_ready_hook.py +opticstream/hooks/check_slice_ready_hook.py +opticstream/hooks/publish_hooks.py +opticstream/hooks/slack_notification_hook.py +opticstream/scripts/compare_hash_files.py +opticstream/scripts/edit_tile_info_grid.py +opticstream/scripts/filter_tiles_by_signal.py +opticstream/scripts/find_tile_plane.py +opticstream/scripts/find_tile_plane_two_stage.py +opticstream/scripts/find_tile_region.py +opticstream/scripts/find_volume_surface.py +opticstream/state/__init__.py +opticstream/state/lsm_project_state.py +opticstream/state/milestone_hooks.py +opticstream/state/milestone_runtime.py +opticstream/state/milestone_wrappers_lsm.py +opticstream/state/milestone_wrappers_psoct.py +opticstream/state/oct_project_state.py +opticstream/state/project_state_core.py +opticstream/state/project_state_postgres.py +opticstream/state/state_guards.py +opticstream/tasks/__init__.py +opticstream/tasks/archive_file.py +opticstream/tasks/dandi_upload.py +opticstream/tasks/slack_notification.py +opticstream/utils/__init__.py +opticstream/utils/deployment_utils.py +opticstream/utils/directory_watch.py +opticstream/utils/filename_utils.py +opticstream/utils/filesystem.py +opticstream/utils/flow_run_name_parse.py +opticstream/utils/matlab_execution.py +opticstream/utils/naming_convention.py +opticstream/utils/path_conversion.py +opticstream/utils/polling_watcher.py +opticstream/utils/process_priority_thread.py +opticstream/utils/refresh_disk.py +opticstream/utils/runtime_paths.py +opticstream/utils/zarr_validation.py +tests/test_dandi_upload.py +tests/test_filename_utils_lsm.py +tests/test_flow_run_name_parse.py +tests/test_lsm_flow_helpers.py +tests/test_lsm_project_state.py +tests/test_lsm_strip_update_flow.py +tests/test_oct_watch_mosaic3.py +tests/test_pipeline_opts_builder.py +tests/test_process_priority_thread.py +tests/test_psoct_flow_utils.py +tests/test_scoped_events.py +tests/test_state_guards.py \ No newline at end of file diff --git a/opticstream.egg-info/dependency_links.txt b/opticstream.egg-info/dependency_links.txt new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/opticstream.egg-info/dependency_links.txt @@ -0,0 +1 @@ + diff --git a/opticstream.egg-info/entry_points.txt b/opticstream.egg-info/entry_points.txt new file mode 100644 index 0000000..9e3ad98 --- /dev/null +++ b/opticstream.egg-info/entry_points.txt @@ -0,0 +1,3 @@ +[console_scripts] +ops = opticstream.cli:main +opticstream = opticstream.cli:main diff --git a/opticstream.egg-info/requires.txt b/opticstream.egg-info/requires.txt new file mode 100644 index 0000000..62d83ef --- /dev/null +++ b/opticstream.egg-info/requires.txt @@ -0,0 +1,25 @@ +cyclopts>=3.3.0 +linc-convert[all] @ git+https://github.com/lincbrain/linc-convert.git@dc8f3243df01d09493a13e53305adede08784695 +nifti-zarr @ git+https://github.com/calvinchai/nifti-zarr-py.git@12336420beaa023cbdd9d9e5c24e3c115687fe9a +psoct-toolbox @ git+https://github.com/calvinchai/psoct-toolbox.git@5182337044d2b7f8337ca205a33c9da3ddd69bda +matplotlib>=3.10.8 +prefect[shell,slack,sqlalchemy]>=3.6.20 +watchdog +psutil +slack-sdk +pydantic +jinja2 +PyYAML +dask +nibabel +numpy +psycopg2-binary + +[dev] +pytest +pytest-cov +mkdocs +mkdocs-material +mkdocstrings[python] +mkdocs-git-revision-date-localized-plugin +ruff diff --git a/opticstream.egg-info/top_level.txt b/opticstream.egg-info/top_level.txt new file mode 100644 index 0000000..8d62908 --- /dev/null +++ b/opticstream.egg-info/top_level.txt @@ -0,0 +1 @@ +opticstream diff --git a/tests/test_lsm_flow_helpers.py b/tests/test_lsm_flow_helpers.py index f864f16..2d9c682 100644 --- a/tests/test_lsm_flow_helpers.py +++ b/tests/test_lsm_flow_helpers.py @@ -87,9 +87,10 @@ def test_strip_zarr_output_path_uses_project_base_when_output_none(): cfg = _minimal_cfg(output_path=None) sid = LSMStripId(project_name="myproj", slice_id=2, strip_id=7, channel_id=1) p = strip_zarr_output_path(sid, cfg) - assert str(p).startswith("/base") - assert "slice02" in p or "02" in p - assert "chunk-0007" in p or "0007" in p + path = str(p) + assert path.startswith("/base") + assert "slice02" in path or "02" in path + assert "chunk-0007" in path or "0007" in path def test_strip_zarr_output_path_prefers_output_path(): @@ -103,8 +104,9 @@ def test_strip_mip_output_path(): cfg = _minimal_cfg(output_path="/z") sid = LSMStripId(project_name="myproj", slice_id=1, strip_id=3, channel_id=1) p = strip_mip_output_path(sid, cfg) - assert str(p).startswith("/z") - assert "proc-mip" in p + path = str(p) + assert path.startswith("/z") + assert "proc-mip" in path def test_channel_zarr_volume_path(): diff --git a/tests/test_oct_watch_mosaic3.py b/tests/test_oct_watch_mosaic3.py index 7465021..0aca188 100644 --- a/tests/test_oct_watch_mosaic3.py +++ b/tests/test_oct_watch_mosaic3.py @@ -1,7 +1,7 @@ from pathlib import Path from types import SimpleNamespace -from opticstream.cli.oct.watch import OCTWatcherService +from opticstream.cli.oct.watch import _MIN_FILE_SIZE_BYTES, OCTWatcherService from opticstream.utils.filename_utils import extract_processed_index_from_filename @@ -28,7 +28,9 @@ def test_discover_three_mosaic_candidates_groups_by_derived_mosaic(tmp_path: Pat spectral_dir.mkdir(parents=True) for idx in range(1, 7): - (spectral_dir / f"processed_{idx:04d}.nii").write_bytes(b"ok") + (spectral_dir / f"processed_{idx:04d}.nii").write_bytes( + b"\0" * _MIN_FILE_SIZE_BYTES + ) (spectral_dir / "ignore_me.txt").write_text("nope", encoding="utf-8") service = OCTWatcherService( @@ -37,32 +39,29 @@ def test_discover_three_mosaic_candidates_groups_by_derived_mosaic(tmp_path: Pat project_base_path=str(tmp_path), mosaic_ranges=[(1, 9999)], slice_offset=0, - batch_size=10, + batch_size=3, scan_config=_scan_config_for_mosaic3(grid_size_x=3), direct=True, force_resend=False, ) candidates = service.discover_candidates() - assert len(candidates) == 3 + assert len(candidates) == 2 by_source_mosaic = {c.source_mosaic_id: c for c in candidates} - assert sorted(by_source_mosaic) == [1, 2, 3] + assert sorted(by_source_mosaic) == [1, 4] assert [p.name for p in by_source_mosaic[1].files] == [ "processed_0001.nii", - "processed_0004.nii", - ] - assert [p.name for p in by_source_mosaic[2].files] == [ "processed_0002.nii", - "processed_0005.nii", - ] - assert [p.name for p in by_source_mosaic[3].files] == [ "processed_0003.nii", + ] + assert [p.name for p in by_source_mosaic[4].files] == [ + "processed_0004.nii", + "processed_0005.nii", "processed_0006.nii", ] assert by_source_mosaic[1].logical_mosaic_id == 1 - assert by_source_mosaic[2].logical_mosaic_id == 2 - assert by_source_mosaic[3].logical_mosaic_id == 3 + assert by_source_mosaic[4].logical_mosaic_id == 4 assert all(c.logical_batch == 1 for c in candidates) diff --git a/tests/test_pipeline_opts_builder.py b/tests/test_pipeline_opts_builder.py index 444bf84..36fb579 100644 --- a/tests/test_pipeline_opts_builder.py +++ b/tests/test_pipeline_opts_builder.py @@ -48,7 +48,7 @@ def test_build_pipeline_opts_spectral_and_pixel_scale() -> None: assert po.spectral is not None assert po.spectral.aline_size == 100 assert po.spectral.bline_size == 200 - assert po.spectral.is_raw_format is True + assert po.spectral.is_raw_format is False po_t = build_pipeline_opts(cfg, illumination="tilted") assert po_t.spectral.aline_size == 50 diff --git a/uv.lock b/uv.lock index a1b4fcc..67ff3cb 100644 --- a/uv.lock +++ b/uv.lock @@ -1276,6 +1276,7 @@ dependencies = [ { name = "griffecli" }, { name = "griffelib" }, ] +sdist = { url = "https://files.pythonhosted.org/packages/04/56/28a0accac339c164b52a92c6cfc45a903acc0c174caa5c1713803467b533/griffe-2.0.0.tar.gz", hash = "sha256:c68979cd8395422083a51ea7cf02f9c119d889646d99b7b656ee43725de1b80f", size = 293906, upload-time = "2026-03-23T21:06:53.402Z" } wheels = [ { url = "https://files.pythonhosted.org/packages/8b/94/ee21d41e7eb4f823b94603b9d40f86d3c7fde80eacc2c3c71845476dddaa/griffe-2.0.0-py3-none-any.whl", hash = "sha256:5418081135a391c3e6e757a7f3f156f1a1a746cc7b4023868ff7d5e2f9a980aa", size = 5214, upload-time = "2026-02-09T19:09:44.105Z" }, ] @@ -1288,6 +1289,7 @@ dependencies = [ { name = "colorama" }, { name = "griffelib" }, ] +sdist = { url = "https://files.pythonhosted.org/packages/a4/f8/2e129fd4a86e52e58eefe664de05e7d502decf766e7316cc9e70fdec3e18/griffecli-2.0.0.tar.gz", hash = "sha256:312fa5ebb4ce6afc786356e2d0ce85b06c1c20d45abc42d74f0cda65e159f6ef", size = 56213, upload-time = "2026-03-23T21:06:54.8Z" } wheels = [ { url = "https://files.pythonhosted.org/packages/e6/ed/d93f7a447bbf7a935d8868e9617cbe1cadf9ee9ee6bd275d3040fbf93d60/griffecli-2.0.0-py3-none-any.whl", hash = "sha256:9f7cd9ee9b21d55e91689358978d2385ae65c22f307a63fb3269acf3f21e643d", size = 9345, upload-time = "2026-02-09T19:09:42.554Z" }, ] @@ -1296,6 +1298,7 @@ wheels = [ name = "griffelib" version = "2.0.0" source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/ad/06/eccbd311c9e2b3ca45dbc063b93134c57a1ccc7607c5e545264ad092c4a9/griffelib-2.0.0.tar.gz", hash = "sha256:e504d637a089f5cab9b5daf18f7645970509bf4f53eda8d79ed71cce8bd97934", size = 166312, upload-time = "2026-03-23T21:06:55.954Z" } wheels = [ { url = "https://files.pythonhosted.org/packages/4d/51/c936033e16d12b627ea334aaaaf42229c37620d0f15593456ab69ab48161/griffelib-2.0.0-py3-none-any.whl", hash = "sha256:01284878c966508b6d6f1dbff9b6fa607bc062d8261c5c7253cb285b06422a7f", size = 142004, upload-time = "2026-02-09T19:09:40.561Z" }, ] @@ -1655,7 +1658,7 @@ wheels = [ [[package]] name = "linc-convert" version = "0.0.1.dev666+dc8f324" -source = { git = "https://github.com/lincbrain/linc-convert.git?rev=lsm-features#dc8f3243df01d09493a13e53305adede08784695" } +source = { git = "https://github.com/lincbrain/linc-convert.git?rev=dc8f3243df01d09493a13e53305adede08784695#dc8f3243df01d09493a13e53305adede08784695" } dependencies = [ { name = "cyclopts" }, { name = "dask" }, @@ -2360,7 +2363,7 @@ wheels = [ [[package]] name = "nifti-zarr" version = "0+unknown" -source = { git = "https://github.com/calvinchai/nifti-zarr-py.git?rev=port-multizarr#1aa1471e61e00b19c933c6efd976fc65114d5f6b" } +source = { git = "https://github.com/calvinchai/nifti-zarr-py.git?rev=12336420beaa023cbdd9d9e5c24e3c115687fe9a#12336420beaa023cbdd9d9e5c24e3c115687fe9a" } dependencies = [ { name = "dask", extra = ["array"] }, { name = "nibabel" }, @@ -2517,9 +2520,10 @@ dependencies = [ { name = "nibabel" }, { name = "nifti-zarr" }, { name = "numpy" }, - { name = "prefect", extra = ["shell", "slack"] }, + { name = "prefect", extra = ["shell", "slack", "sqlalchemy"] }, { name = "psoct-toolbox" }, { name = "psutil" }, + { name = "psycopg2-binary" }, { name = "pydantic" }, { name = "pyyaml" }, { name = "slack-sdk" }, @@ -2542,18 +2546,19 @@ requires-dist = [ { name = "cyclopts", specifier = ">=3.3.0" }, { name = "dask" }, { name = "jinja2" }, - { name = "linc-convert", extras = ["all"], git = "https://github.com/lincbrain/linc-convert.git?rev=lsm-features" }, + { name = "linc-convert", extras = ["all"], git = "https://github.com/lincbrain/linc-convert.git?rev=dc8f3243df01d09493a13e53305adede08784695" }, { name = "matplotlib", specifier = ">=3.10.8" }, { name = "mkdocs", marker = "extra == 'dev'" }, { name = "mkdocs-git-revision-date-localized-plugin", marker = "extra == 'dev'" }, { name = "mkdocs-material", marker = "extra == 'dev'" }, { name = "mkdocstrings", extras = ["python"], marker = "extra == 'dev'" }, { name = "nibabel" }, - { name = "nifti-zarr", git = "https://github.com/calvinchai/nifti-zarr-py.git?rev=port-multizarr" }, + { name = "nifti-zarr", git = "https://github.com/calvinchai/nifti-zarr-py.git?rev=12336420beaa023cbdd9d9e5c24e3c115687fe9a" }, { name = "numpy" }, - { name = "prefect", extras = ["shell", "slack"], specifier = ">=3.6.20" }, - { name = "psoct-toolbox", git = "https://github.com/calvinchai/psoct-toolbox.git" }, + { name = "prefect", extras = ["shell", "slack", "sqlalchemy"], specifier = ">=3.6.20" }, + { name = "psoct-toolbox", git = "https://github.com/calvinchai/psoct-toolbox.git?rev=5182337044d2b7f8337ca205a33c9da3ddd69bda" }, { name = "psutil" }, + { name = "psycopg2-binary" }, { name = "pydantic" }, { name = "pytest", marker = "extra == 'dev'" }, { name = "pytest-cov", marker = "extra == 'dev'" }, @@ -2993,6 +2998,9 @@ shell = [ slack = [ { name = "prefect-slack" }, ] +sqlalchemy = [ + { name = "prefect-sqlalchemy" }, +] [[package]] name = "prefect-shell" @@ -3020,6 +3028,19 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/41/12/6b095a290517abd605875be2a746d222a95d0296d44ff81f56fc93a32eac/prefect_slack-0.3.1-py3-none-any.whl", hash = "sha256:84067ef89c9085fd991943747e4943accb3fe586a9401355180bb50dac5dab21", size = 10588, upload-time = "2024-11-15T17:17:27.495Z" }, ] +[[package]] +name = "prefect-sqlalchemy" +version = "0.6.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "prefect" }, + { name = "sqlalchemy" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/ff/14/41a605724a067e2917c6e88bdc254ed8675d2031179e52d05c772733708a/prefect_sqlalchemy-0.6.1.tar.gz", hash = "sha256:7fb13101a568840a9fff1697d1cb1ac6931a340a52a3ec0a3b75929daebb5c77", size = 19185, upload-time = "2026-02-12T22:03:55.885Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/32/19/2eb0b80e92fb1597ce53f765548fa58a87949fceeb0bacb350388d2be00a/prefect_sqlalchemy-0.6.1-py3-none-any.whl", hash = "sha256:c7cf4dbaedf30b987cbdbb3cd645e55d6d59dbac6308f8385b808f936da267e3", size = 14827, upload-time = "2026-02-12T22:03:54.224Z" }, +] + [[package]] name = "prometheus-client" version = "0.24.1" @@ -3131,7 +3152,7 @@ wheels = [ [[package]] name = "psoct-toolbox" version = "0.1.0" -source = { git = "https://github.com/calvinchai/psoct-toolbox.git#cc01a2c3d552bf0f60a0d14689eef4fd353e180d" } +source = { git = "https://github.com/calvinchai/psoct-toolbox.git?rev=5182337044d2b7f8337ca205a33c9da3ddd69bda#5182337044d2b7f8337ca205a33c9da3ddd69bda" } [[package]] name = "psutil" @@ -3161,6 +3182,58 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/8c/c7/7bb2e321574b10df20cbde462a94e2b71d05f9bbda251ef27d104668306a/psutil-7.2.2-cp37-abi3-win_arm64.whl", hash = "sha256:8c233660f575a5a89e6d4cb65d9f938126312bca76d8fe087b947b3a1aaac9ee", size = 134617, upload-time = "2026-01-28T18:15:36.514Z" }, ] +[[package]] +name = "psycopg2-binary" +version = "2.9.12" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/2a/60/a3624f79acea344c16fbef3a94d28b89a8042ddfb8f3e4ca83f538671409/psycopg2_binary-2.9.12.tar.gz", hash = "sha256:5ac9444edc768c02a6b6a591f070b8aae28ff3a99be57560ac996001580f294c", size = 379686, upload-time = "2026-04-21T09:40:34.304Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d5/19/d4ce60954f3bb9d8e3bc5e5c4d1f2487de2d3851bf2391d54954c9df12a6/psycopg2_binary-2.9.12-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:5c8ce6c61bd1b1f6b9c24ee32211599f6166af2c55abb19456090a21fd16554b", size = 3712338, upload-time = "2026-04-20T23:34:03.961Z" }, + { url = "https://files.pythonhosted.org/packages/53/71/c85409ee0d78890f0660eff262e815e7dd2bb741a17611d82e9e8cd9dc5e/psycopg2_binary-2.9.12-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:b4a9eaa6e7f4ff91bec10aa3fb296878e75187bced5cc4bafe17dc40915e1326", size = 3822407, upload-time = "2026-04-20T23:34:05.977Z" }, + { url = "https://files.pythonhosted.org/packages/3c/ed/60486c2c7f0d4d1ede2bfb1ed27e2498477ce646bc7f6b2759906303117e/psycopg2_binary-2.9.12-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:c6528cefc8e50fcc6f4a107e27a672058b36cc5736d665476aeb413ba88dbb06", size = 4578425, upload-time = "2026-04-20T23:34:08.246Z" }, + { url = "https://files.pythonhosted.org/packages/0b/b9/656cb03fad9f4f49f2145c334b1126ee75189929ca4e6187d485a2d59951/psycopg2_binary-2.9.12-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:e4e184b1fb6072bf05388aa41c697e1b2d01b3473f107e7ec44f186a32cfd0b8", size = 4273709, upload-time = "2026-04-20T23:34:10.974Z" }, + { url = "https://files.pythonhosted.org/packages/99/66/08cf0da0e25cc6fb142c89be45fc8418792858f0c4cbff5e24530ff02cd6/psycopg2_binary-2.9.12-cp311-cp311-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:4766ab678563054d3f1d064a4db19cc4b5f9e3a8d9018592a8285cf200c248f3", size = 5893779, upload-time = "2026-04-20T23:34:13.905Z" }, + { url = "https://files.pythonhosted.org/packages/17/d7/eecd9ce8e146d3721115d82d3836efdbb712187e4590325df549989d18f4/psycopg2_binary-2.9.12-cp311-cp311-manylinux_2_38_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:5a0253224780c978746cb9be55a946bcdaf40fe3519c0f622924cdabdafe2c39", size = 4109308, upload-time = "2026-04-20T23:34:16.761Z" }, + { url = "https://files.pythonhosted.org/packages/b6/2e/b1dc289b362cc8d45697b57eefbd673186f49a4ea0906928988e3affcc98/psycopg2_binary-2.9.12-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:0dc9228d47c46bda253d2ecd6bb93b56a9f2d7ad33b684a1fa3622bf74ffe30c", size = 3654405, upload-time = "2026-04-20T23:34:19.303Z" }, + { url = "https://files.pythonhosted.org/packages/eb/e4/4c4aea6473214dbdbd0fbba11aa4691e76dc01722c55724c5951719865ff/psycopg2_binary-2.9.12-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:f921f3cd87035ef7df233383011d7a53ea1d346224752c1385f1edfd790ceb6a", size = 3299187, upload-time = "2026-04-20T23:34:21.206Z" }, + { url = "https://files.pythonhosted.org/packages/ba/5d/b03b99986446a4f57b170ed9a2579fb7ff9783ca0fa5226b19db99737fee/psycopg2_binary-2.9.12-cp311-cp311-musllinux_1_2_riscv64.whl", hash = "sha256:3d999bd982a723113c1a45b55a7a6a90d64d0ed2278020ed625c490ff7bef96c", size = 3047716, upload-time = "2026-04-20T23:34:23.077Z" }, + { url = "https://files.pythonhosted.org/packages/14/86/382ee4afbd1d97500c9d2862b20c2fdeddf4b7335e984df3fb4309f64108/psycopg2_binary-2.9.12-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:29d4d134bd0ab46ffb04e94aa3c5fa3ef582e9026609165e2f758ff76fc3a3be", size = 3349237, upload-time = "2026-04-20T23:34:25.211Z" }, + { url = "https://files.pythonhosted.org/packages/a8/16/9a57c75ba1eda7165c017342f526810d5f5a12647dde749c99ae9a7141d7/psycopg2_binary-2.9.12-cp311-cp311-win_amd64.whl", hash = "sha256:cb4a1dacdd48077150dc762a9e5ddbf32c256d66cb46f80839391aa458774936", size = 2757036, upload-time = "2026-04-20T23:34:27.77Z" }, + { url = "https://files.pythonhosted.org/packages/e2/9f/ef4ef3c8e15083df90ca35265cfd1a081a2f0cc07bb229c6314c6af817f4/psycopg2_binary-2.9.12-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:5cdc05117180c5fa9c40eea8ea559ce64d73824c39d928b7da9fb5f6a9392433", size = 3712459, upload-time = "2026-04-20T23:34:30.549Z" }, + { url = "https://files.pythonhosted.org/packages/b5/01/3dd14e46ba48c1e1a6ec58ee599fa1b5efa00c246d5046cd903d0eeb1af1/psycopg2_binary-2.9.12-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:d3227a3bc228c10d21011a99245edca923e4e8bf461857e869a507d9a41fe9f6", size = 3822936, upload-time = "2026-04-20T23:34:32.77Z" }, + { url = "https://files.pythonhosted.org/packages/a6/f7/0640e4901119d8a9f7a1784b927f494e2198e213ceb593753d1f2c8b1b30/psycopg2_binary-2.9.12-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:995ce929eede89db6254b50827e2b7fd61e50d11f0b116b29fffe4a2e53c4580", size = 4578676, upload-time = "2026-04-20T23:34:35.18Z" }, + { url = "https://files.pythonhosted.org/packages/b0/55/44df3965b5f297c50cc0b1b594a31c67d6127a9d133045b8a66611b14dfb/psycopg2_binary-2.9.12-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:9fe06d93e72f1c048e731a2e3e7854a5bfaa58fc736068df90b352cefe66f03f", size = 4274917, upload-time = "2026-04-20T23:34:37.982Z" }, + { url = "https://files.pythonhosted.org/packages/b0/4b/74535248b1eac0c9336862e8617c765ac94dac76f9e25d7c4a79588c8907/psycopg2_binary-2.9.12-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:40e7b28b63aaf737cb3a1edc3a9bbc9a9f4ad3dcb7152e8c1130e4050eddcb7d", size = 5894843, upload-time = "2026-04-20T23:34:40.856Z" }, + { url = "https://files.pythonhosted.org/packages/f2/ba/f1bf8d2ae71868ad800b661099086ee52bc0f8d9f05be1acd8ebb06757cc/psycopg2_binary-2.9.12-cp312-cp312-manylinux_2_38_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:89d19a9f7899e8eb0656a2b3a08e0da04c720a06db6e0033eab5928aabe60fa9", size = 4110556, upload-time = "2026-04-20T23:34:44.016Z" }, + { url = "https://files.pythonhosted.org/packages/45/46/c15706c338403b7c420bcc0c2905aad116cc064545686d8bf85f1999ea00/psycopg2_binary-2.9.12-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:612b965daee295ae2da8f8218ce1d274645dc76ef3f1abf6a0a94fd57eff876d", size = 3655714, upload-time = "2026-04-20T23:34:46.233Z" }, + { url = "https://files.pythonhosted.org/packages/b3/7c/a2d5dc09b64a4564db242a0fe418fde7d33f6f8259dd2c5b9d7def00fb5a/psycopg2_binary-2.9.12-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:b9a339b79d37c1b45f3235265f07cdeb0cb5ad7acd2ac7720a5920989c17c24e", size = 3301154, upload-time = "2026-04-20T23:34:49.528Z" }, + { url = "https://files.pythonhosted.org/packages/c0/e8/cc8c9a4ce71461f9ec548d38cadc41dc184b34c73e6455450775a9334ccd/psycopg2_binary-2.9.12-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:3471336e1acfd9c7fe507b8bad5af9317b6a89294f9eb37bd9a030bb7bebcdc6", size = 3048882, upload-time = "2026-04-20T23:34:51.86Z" }, + { url = "https://files.pythonhosted.org/packages/19/6a/31e2296bc0787c5ab75d3d118e40b239db8151b5192b90b77c72bc9256e9/psycopg2_binary-2.9.12-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:7af18183109e23502c8b2ae7f6926c0882766f35b5175a4cd737ad825e4d7a1b", size = 3351298, upload-time = "2026-04-20T23:34:54.124Z" }, + { url = "https://files.pythonhosted.org/packages/5f/a8/75f4e3e11203b590150abed2cf7794b9c9c9f7eceddae955191138b44dde/psycopg2_binary-2.9.12-cp312-cp312-win_amd64.whl", hash = "sha256:398fcd4db988c7d7d3713e2b8e18939776fd3fb447052daae4f24fa39daede4c", size = 2757230, upload-time = "2026-04-20T23:34:56.242Z" }, + { url = "https://files.pythonhosted.org/packages/91/bb/4608c96f970f6e0c56572e87027ef4404f709382a3503e9934526d7ba051/psycopg2_binary-2.9.12-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:7c729a73c7b1b84de3582f73cdd27d905121dc2c531f3d9a3c32a3011033b965", size = 3712419, upload-time = "2026-04-20T23:34:58.754Z" }, + { url = "https://files.pythonhosted.org/packages/5e/af/48f76af9d50d61cf390f8cd657b503168b089e2e9298e48465d029fcc713/psycopg2_binary-2.9.12-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:4413d0caef93c5cf50b96863df4c2efe8c269bf2267df353225595e7e15e8df7", size = 3822990, upload-time = "2026-04-20T23:35:00.821Z" }, + { url = "https://files.pythonhosted.org/packages/7a/df/aba0f99397cd811d32e06fc0cc781f1f3ce98bc0e729cb423925085d781a/psycopg2_binary-2.9.12-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:4dfcf8e45ebb0c663be34a3442f65e17311f3367089cd4e5e3a3e8e62c978777", size = 4578696, upload-time = "2026-04-20T23:35:03.409Z" }, + { url = "https://files.pythonhosted.org/packages/95/9c/eaa74021ac4e4d5c2f83d82fc6615a63f4fe6c94dc4e94c3990427053f67/psycopg2_binary-2.9.12-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:c41321a14dd74aceb6a9a643b9253a334521babfa763fa873e33d89cfa122fb5", size = 4274982, upload-time = "2026-04-20T23:35:05.583Z" }, + { url = "https://files.pythonhosted.org/packages/35/ed/c25deff98bd26187ba48b3b250a3ffc3037c46c5b89362534a15d200e0db/psycopg2_binary-2.9.12-cp313-cp313-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:83946ba43979ebfdc99a3cd0ee775c89f221df026984ba19d46133d8d75d3cd9", size = 5894867, upload-time = "2026-04-20T23:35:07.902Z" }, + { url = "https://files.pythonhosted.org/packages/9a/81/8d0e21ca77373c6c9589e5c4528f6e8f0c08c62cafc76fb0bddb7a2cee22/psycopg2_binary-2.9.12-cp313-cp313-manylinux_2_38_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:411e85815652d13560fbe731878daa5d92378c4995a22302071890ec3397d019", size = 4110578, upload-time = "2026-04-20T23:35:10.149Z" }, + { url = "https://files.pythonhosted.org/packages/00/fc/f481e2435bd8f742d0123309174aae4165160ad3ef17c1b99c3622c241d2/psycopg2_binary-2.9.12-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:1c8ad4c08e00f7679559eaed7aff1edfffc60c086b976f93972f686384a95e2c", size = 3655816, upload-time = "2026-04-20T23:35:12.56Z" }, + { url = "https://files.pythonhosted.org/packages/53/79/b9f46466bdbe9f239c96cde8be33c1aace4842f06013b47b730dc9759187/psycopg2_binary-2.9.12-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:00814e40fa23c2b37ef0a1e3c749d89982c73a9cb5046137f0752a22d432e82f", size = 3301307, upload-time = "2026-04-20T23:35:15.029Z" }, + { url = "https://files.pythonhosted.org/packages/3f/19/7dc003b32fe35024df89b658104f7c8538a8b2dcbde7a4e746ce929742e7/psycopg2_binary-2.9.12-cp313-cp313-musllinux_1_2_riscv64.whl", hash = "sha256:98062447aebc20ed20add1f547a364fd0ef8933640d5372ff1873f8deb9b61be", size = 3048968, upload-time = "2026-04-20T23:35:16.757Z" }, + { url = "https://files.pythonhosted.org/packages/91/58/2dbd7db5c604d45f4950d988506aae672a14126ec22998ced5021cbb76bb/psycopg2_binary-2.9.12-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:66a7685d7e548f10fb4ce32fb01a7b7f4aa702134de92a292c7bd9e0d3dbd290", size = 3351369, upload-time = "2026-04-20T23:35:18.933Z" }, + { url = "https://files.pythonhosted.org/packages/42/ee/dee8dcaad07f735824de3d6563bc67119fa6c28257b17977a8d624f02fab/psycopg2_binary-2.9.12-cp313-cp313-win_amd64.whl", hash = "sha256:b6937f5fe4e180aeee87de907a2fa982ded6f7f15d7218f78a083e4e1d68f2a0", size = 2757347, upload-time = "2026-04-20T23:35:21.283Z" }, + { url = "https://files.pythonhosted.org/packages/13/1b/708c0dca874acfad6d65314271859899a79007686f3a1f74e82a2ed4b645/psycopg2_binary-2.9.12-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:6f3b3de8a74ef8db215f22edffb19e32dc6fa41340456de7ec99efdc8a7b3ec2", size = 3712428, upload-time = "2026-04-20T23:35:23.453Z" }, + { url = "https://files.pythonhosted.org/packages/d6/39/ddbea9d4b4de6aca9431b6ed253f530f8a02d3b8f9bcfd0dbfe2b3de6fe4/psycopg2_binary-2.9.12-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:1006fb62f0f0bc5ce256a832356c6262e91be43f5e4eb15b5eaf38079464caf2", size = 3823184, upload-time = "2026-04-20T23:35:25.92Z" }, + { url = "https://files.pythonhosted.org/packages/bf/a0/bc2fef74b106fa345567122a0659e6d94512ed7dc0131ec44c9e5aba3725/psycopg2_binary-2.9.12-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:840066105706cd2eb29b9a1c2329620056582a4bf3e8169dec5c447042d0869f", size = 4579157, upload-time = "2026-04-20T23:35:28.542Z" }, + { url = "https://files.pythonhosted.org/packages/57/d7/d4e3b2005d3de607ca4fbb0e8742e248056e52184a6b94ebda3c1c2c329b/psycopg2_binary-2.9.12-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:863f5d12241ebe1c76a72a04c2113b6dc905f90b9cef0e9be0efd994affd9354", size = 4274970, upload-time = "2026-04-20T23:35:30.418Z" }, + { url = "https://files.pythonhosted.org/packages/2e/42/c9853f8db3967fe08bcde11f53d53b85d351750cae726ce001cb68afa9c1/psycopg2_binary-2.9.12-cp314-cp314-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:a99eaab34a9010f1a086b126de467466620a750634d114d20455f3a824aae033", size = 5895175, upload-time = "2026-04-20T23:35:33.584Z" }, + { url = "https://files.pythonhosted.org/packages/eb/fd/b82b5601a97630308bef079f545ffec481bbbc795c2ba5ec416a01d03f60/psycopg2_binary-2.9.12-cp314-cp314-manylinux_2_38_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:ffdd7dc5463ccd61845ac37b7012d0f35a1548df9febe14f8dd549be4a0bc81e", size = 4110658, upload-time = "2026-04-20T23:35:35.638Z" }, + { url = "https://files.pythonhosted.org/packages/62/8c/32ca69b0389ef25dd22937bf9e8fbe2ce27aea20b05ded48c4ce4cb42475/psycopg2_binary-2.9.12-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:54a0dfecab1b48731f934e06139dfe11e24219fb6d0ceb32177cf0375f14c7b5", size = 3656251, upload-time = "2026-04-20T23:35:37.854Z" }, + { url = "https://files.pythonhosted.org/packages/c4/29/96992a2b59e3b9d730fcf9612d0a387305025dc867a9fc490a9e496e074e/psycopg2_binary-2.9.12-cp314-cp314-musllinux_1_2_ppc64le.whl", hash = "sha256:96937c9c5d891f772430f418a7a8b4691a90c3e6b93cf72b5bd7cad8cbca32a5", size = 3301810, upload-time = "2026-04-20T23:35:39.927Z" }, + { url = "https://files.pythonhosted.org/packages/56/ad/44b06659949b243ae10112cd3b20a197f9bf3e81d5651379b9eb889bfaad/psycopg2_binary-2.9.12-cp314-cp314-musllinux_1_2_riscv64.whl", hash = "sha256:77b348775efd4cdab410ec6609d81ccecd1139c90265fa583a7255c8064bc03d", size = 3048977, upload-time = "2026-04-20T23:35:41.806Z" }, + { url = "https://files.pythonhosted.org/packages/1d/f2/10a1bcebadb6aa55e280e1f58975c36a7b560ea525184c7aa4064c466633/psycopg2_binary-2.9.12-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:527e6342b3e44c2f0544f6b8e927d60de7f163f5723b8f1dfa7d2a84298738cd", size = 3351466, upload-time = "2026-04-20T23:35:43.993Z" }, + { url = "https://files.pythonhosted.org/packages/20/be/b732c8418ffa5bcfda002890f5dc4c869fc17db66ff11f53b17cfe44afc0/psycopg2_binary-2.9.12-cp314-cp314-win_amd64.whl", hash = "sha256:f12ae41fcafadb39b2785e64a40f9db05d6de2ac114077457e0e7c597f3af980", size = 2848762, upload-time = "2026-04-20T23:35:46.421Z" }, +] + [[package]] name = "py-key-value-aio" version = "0.4.4" From 92cf9d539f53daa77d2487e5b395f03da43ba3ca Mon Sep 17 00:00:00 2001 From: NoahMarkowitz Date: Thu, 27 Aug 2026 15:37:43 -0400 Subject: [PATCH 04/65] add github testing --- .github/workflows/tests.yml | 79 ++++++++++++++++++++++++++++++++ docs/developer/testing_and_ci.md | 27 +++++++++-- opticstream/cli/oct/setup.py | 16 +++++-- tests/test_lsm_project_state.py | 1 + tests/test_psoct_flow_utils.py | 13 +++++- 5 files changed, 127 insertions(+), 9 deletions(-) create mode 100644 .github/workflows/tests.yml diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml new file mode 100644 index 0000000..0efc48d --- /dev/null +++ b/.github/workflows/tests.yml @@ -0,0 +1,79 @@ +name: Tests + +on: + push: + pull_request: + workflow_dispatch: + +permissions: + contents: read + +jobs: + unit-tests: + name: Unit tests + runs-on: ubuntu-latest + timeout-minutes: 15 + steps: + - name: Check out repository + uses: actions/checkout@v4 + + - name: Set up Python + uses: actions/setup-python@v5 + with: + python-version: "3.11" + + - name: Install dependencies + run: | + python -m pip install --upgrade pip + pip install uv + uv sync --extra dev --frozen + + - name: Run unit tests + run: uv run pytest -m "not integration" -ra + + integration-tests: + name: Prefect integration tests + runs-on: ubuntu-latest + timeout-minutes: 20 + steps: + - name: Check out repository + uses: actions/checkout@v4 + + - name: Set up Python + uses: actions/setup-python@v5 + with: + python-version: "3.11" + + - name: Install dependencies + run: | + python -m pip install --upgrade pip + pip install uv + uv sync --extra dev --frozen + + - name: Start Prefect and PostgreSQL + run: docker compose --profile server up -d + + - name: Wait for Prefect + run: | + for attempt in {1..60}; do + if curl --fail --silent http://127.0.0.1:4200/api/health > /dev/null; then + exit 0 + fi + sleep 2 + done + docker compose --profile server logs --no-color + exit 1 + + - name: Configure Prefect client + run: uv run prefect config set PREFECT_API_URL=http://127.0.0.1:4200/api + + - name: Run integration tests + run: uv run pytest -m integration -ra + + - name: Show service logs after a failure + if: failure() + run: docker compose --profile server logs --no-color + + - name: Stop services + if: always() + run: docker compose --profile server down diff --git a/docs/developer/testing_and_ci.md b/docs/developer/testing_and_ci.md index f11c242..e675a1b 100644 --- a/docs/developer/testing_and_ci.md +++ b/docs/developer/testing_and_ci.md @@ -4,7 +4,28 @@ title: Testing and CI # Testing and CI -This page should describe how to run the test suite (in `tests/`), any -linting or formatting checks, and how continuous integration is configured for -the project. +Tests are split into unit tests, which do not require external services, and +integration tests backed by a Prefect server and PostgreSQL. +Run the unit tests locally with: + +```bash +uv run pytest -m "not integration" -ra +``` + +Run the integration tests locally after starting the server profile: + +```bash +docker compose --profile server up -d +uv run prefect config set PREFECT_API_URL=http://127.0.0.1:4200/api +uv run pytest -m integration -ra +docker compose --profile server down +``` + +The `Tests` GitHub Actions workflow runs these as separate jobs. The unit job +requires no services. The integration job starts Prefect and PostgreSQL with +Docker Compose on the GitHub-hosted runner, waits for the API health endpoint, +runs the integration-marked tests, and always stops the services afterward. + +Both jobs run for pushes and pull requests, and can also be started manually +with the workflow's **Run workflow** button. diff --git a/opticstream/cli/oct/setup.py b/opticstream/cli/oct/setup.py index 6dc7152..1c293a8 100644 --- a/opticstream/cli/oct/setup.py +++ b/opticstream/cli/oct/setup.py @@ -23,10 +23,6 @@ datefmt="%Y-%m-%d %H:%M:%S", ) logger = logging.getLogger(__name__) -warnings.filterwarnings( - "ignore", - message=".*PydanticSerializationUnexpectedValue.*", -) _DEFAULT_MASK_NORMAL = 60.0 _DEFAULT_MASK_TILTED = 55.0 @@ -89,7 +85,17 @@ def setup( dandi_api_key=Secret.load(dandi) if dandi else None, zarr_config=default_zarr_config(), ) - scan_config.save(block_name, overwrite=True) + # Prefect serializes the block through Pydantic, whose warning message is + # multiline when list-annotated dependency defaults contain tuples. Keep + # the suppression local to this serialization operation so unrelated + # Pydantic warnings remain visible. + with warnings.catch_warnings(): + warnings.filterwarnings( + "ignore", + message=r"(?s).*PydanticSerializationUnexpectedValue.*", + category=UserWarning, + ) + scan_config.save(block_name, overwrite=True) logger.info("Saved PSOCTScanConfig block as '%s'", block_name) created: list[Path] = [] diff --git a/tests/test_lsm_project_state.py b/tests/test_lsm_project_state.py index 892007e..e46d80f 100644 --- a/tests/test_lsm_project_state.py +++ b/tests/test_lsm_project_state.py @@ -271,6 +271,7 @@ def test_pydantic_validation_boundaries(): LSMStripState(slice_id=-1, strip_id=0, channel_id=1) +@pytest.mark.integration def test_lock_naming_helper_and_ensure_lock_do_not_crash(project_name: str): lock_name = _state_lock_name(project_name) diff --git a/tests/test_psoct_flow_utils.py b/tests/test_psoct_flow_utils.py index 2108a34..a94c44d 100644 --- a/tests/test_psoct_flow_utils.py +++ b/tests/test_psoct_flow_utils.py @@ -1,5 +1,9 @@ """Tests for PSOCT flow helper utilities.""" +from types import SimpleNamespace + +import pytest + from opticstream.flows.psoct.utils import ( oct_batch_ident, processed_output_prefix, @@ -11,7 +15,14 @@ def test_processed_output_prefix_matches_fiji_stem() -> None: assert processed_output_prefix(1, 3) == "mosaic_001_image_0003" -def test_oct_batch_ident_matches_slice_derivation() -> None: +def test_oct_batch_ident_matches_slice_derivation( + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.setattr( + "opticstream.flows.psoct.utils.get_psoct_scan_config", + lambda _project_name: SimpleNamespace(mosaics_per_slice=2), + ) + ident = oct_batch_ident("proj-a", mosaic_id=5, batch_id=2) assert ident.project_name == "proj-a" assert ident.mosaic_id == 5 From a77aa8d24ddbe5311ef39ffa68db9f9f244c4185 Mon Sep 17 00:00:00 2001 From: NoahMarkowitz Date: Thu, 27 Aug 2026 16:02:03 -0400 Subject: [PATCH 05/65] fix pytest integration test isolation --- .github/workflows/tests.yml | 4 ++-- docs/developer/testing_and_ci.md | 21 ++++++++------------- pyproject.toml | 4 +++- 3 files changed, 13 insertions(+), 16 deletions(-) diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 0efc48d..27c86af 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -29,7 +29,7 @@ jobs: uv sync --extra dev --frozen - name: Run unit tests - run: uv run pytest -m "not integration" -ra + run: uv run pytest -ra integration-tests: name: Prefect integration tests @@ -68,7 +68,7 @@ jobs: run: uv run prefect config set PREFECT_API_URL=http://127.0.0.1:4200/api - name: Run integration tests - run: uv run pytest -m integration -ra + run: uv run pytest -o addopts= -m integration -ra - name: Show service logs after a failure if: failure() diff --git a/docs/developer/testing_and_ci.md b/docs/developer/testing_and_ci.md index e675a1b..258914f 100644 --- a/docs/developer/testing_and_ci.md +++ b/docs/developer/testing_and_ci.md @@ -10,22 +10,17 @@ integration tests backed by a Prefect server and PostgreSQL. Run the unit tests locally with: ```bash -uv run pytest -m "not integration" -ra +uv run pytest -ra ``` -Run the integration tests locally after starting the server profile: +Pytest excludes tests marked `integration` by default, so the local command +does not connect to Prefect or Docker. -```bash -docker compose --profile server up -d -uv run prefect config set PREFECT_API_URL=http://127.0.0.1:4200/api -uv run pytest -m integration -ra -docker compose --profile server down -``` - -The `Tests` GitHub Actions workflow runs these as separate jobs. The unit job -requires no services. The integration job starts Prefect and PostgreSQL with -Docker Compose on the GitHub-hosted runner, waits for the API health endpoint, -runs the integration-marked tests, and always stops the services afterward. +The `Tests` GitHub Actions workflow runs unit and integration tests as separate +jobs. The unit job requires no services. The integration job overrides the +local default, starts Prefect and PostgreSQL with Docker Compose on the +GitHub-hosted runner, waits for the API health endpoint, runs the +integration-marked tests, and always stops the services afterward. Both jobs run for pushes and pull requests, and can also be started manually with the workflow's **Run workflow** button. diff --git a/pyproject.toml b/pyproject.toml index 588b633..1734cab 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -52,6 +52,8 @@ include = ["opticstream*"] exclude = ["notebooks*"] [tool.pytest.ini_options] +addopts = '-m "not integration"' +testpaths = ["tests"] markers = [ "integration: integration tests", -] \ No newline at end of file +] From 916920d86f624e3f8a6dcfd0487aa79689766c7e Mon Sep 17 00:00:00 2001 From: JoshBorn <111942554+jcborn93@users.noreply.github.com> Date: Tue, 8 Sep 2026 13:42:04 -0400 Subject: [PATCH 06/65] update configs --- .env | 2 +- docker-compose.yaml | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/.env b/.env index f39ffa6..ae2d104 100644 --- a/.env +++ b/.env @@ -1 +1 @@ -HOST_IP=172.20.126.96 +HOST_IP=172.20.126.209 \ No newline at end of file diff --git a/docker-compose.yaml b/docker-compose.yaml index 3ad6812..175d93c 100644 --- a/docker-compose.yaml +++ b/docker-compose.yaml @@ -12,6 +12,8 @@ services: volumes: - ./db:/var/lib/postgresql profiles: ["server"] + ports: + - "127.0.0.1:1542:5432" ### MinIO for flow storage minio: From 1bf800f10dd160dc6d2f6c300ad446fcac694e5f Mon Sep 17 00:00:00 2001 From: JoshBorn <111942554+jcborn93@users.noreply.github.com> Date: Thu, 10 Sep 2026 09:19:44 -0400 Subject: [PATCH 07/65] enable toggle slack notifications --- docs/user-guides/troubleshooting.md | 13 ++++ opticstream/config/constants.py | 1 + opticstream/hooks/slack_notification_hook.py | 4 ++ opticstream/tasks/slack_notification.py | 16 ++++- opticstream/utils/slack_settings.py | 19 ++++++ tests/test_slack_settings.py | 70 ++++++++++++++++++++ 6 files changed, 121 insertions(+), 2 deletions(-) create mode 100644 opticstream/utils/slack_settings.py create mode 100644 tests/test_slack_settings.py diff --git a/docs/user-guides/troubleshooting.md b/docs/user-guides/troubleshooting.md index 50ebcfe..adf9499 100644 --- a/docs/user-guides/troubleshooting.md +++ b/docs/user-guides/troubleshooting.md @@ -19,6 +19,19 @@ Checks: - run `opticstream lsm setup PROJECT_NAME` or `opticstream oct setup PROJECT_NAME` - verify block names follow project naming conventions used by setup commands +## Disable Slack notifications + +In the Prefect UI, create or edit the variable `slack-notifications-enabled`. +Set its value to the JSON boolean `false` (without quotes) to skip OpticStream +Slack failure hooks, messages, and file uploads before any Slack blocks are loaded. +Set it to `true` to enable notifications again. If absent, notifications are enabled. +The setting applies to OCT and LSM jobs using the same Prefect server. + +The switch is read on each notification attempt, so subsequent changes do not +require restarting watchers. Restart existing watchers/workers once after installing +the code that supports this switch. Processing and its failure states are unaffected; +disabled notification tasks return normally without sending anything. + ## State lock or state backend issues Symptoms: diff --git a/opticstream/config/constants.py b/opticstream/config/constants.py index e254804..3677a3f 100644 --- a/opticstream/config/constants.py +++ b/opticstream/config/constants.py @@ -4,6 +4,7 @@ SLACK_API_TOKEN_BLOCK_NAME = "watchdog" SLACK_CHANNEL_BLOCK_NAME = "watchdog-channel" SLACK_ONCALL_VARIABLE_NAME = "oncall-person" +SLACK_NOTIFICATIONS_ENABLED_VARIABLE_NAME = "slack-notifications-enabled" DANDI_API_TOKEN_BLOCK_NAME = "dandi-api-key" LINC_API_TOKEN_BLOCK_NAME = "linc-api-key" diff --git a/opticstream/hooks/slack_notification_hook.py b/opticstream/hooks/slack_notification_hook.py index 96500f5..3944fc9 100644 --- a/opticstream/hooks/slack_notification_hook.py +++ b/opticstream/hooks/slack_notification_hook.py @@ -5,12 +5,16 @@ from prefect.variables import Variable from opticstream.config.constants import SLACK_ONCALL_VARIABLE_NAME, SLACK_WEBHOOK_BLOCK_NAME +from opticstream.utils.slack_settings import slack_notifications_enabled def slack_notification_hook(flow: Any, flow_run: Any, state: Any) -> None: """ Send a Slack notification when a flow enters a state. """ + if not slack_notifications_enabled(): + return + oncall_person = Variable.get(SLACK_ONCALL_VARIABLE_NAME, default={}) oncall_person_mention = " ".join([f"<@{person}>" for person in oncall_person.values()]) slack_webhook_block = SlackWebhook.load(SLACK_WEBHOOK_BLOCK_NAME) diff --git a/opticstream/tasks/slack_notification.py b/opticstream/tasks/slack_notification.py index 6ea151d..36fe142 100644 --- a/opticstream/tasks/slack_notification.py +++ b/opticstream/tasks/slack_notification.py @@ -7,6 +7,7 @@ from prefect.blocks.system import Secret from prefect.blocks.notifications import SlackWebhook from prefect_slack import SlackCredentials +from opticstream.utils.slack_settings import slack_notifications_enabled from opticstream.config.constants import ( SLACK_API_TOKEN_BLOCK_NAME, @@ -36,8 +37,11 @@ def send_slack_message( Returns ------- bool - True if message sent successfully, False otherwise + True if message sent successfully, False if disabled or unsuccessful """ + if not slack_notifications_enabled(): + return False + if slack_bot_token is None: slack_bot_token = SlackCredentials.load( SLACK_API_TOKEN_BLOCK_NAME @@ -78,7 +82,12 @@ def send_slack_message_webhook( ) -> bool: """ Send a text message to Slack channel using a webhook. + + Returns False when notifications are disabled. """ + if not slack_notifications_enabled(): + return False + if webhook is None: webhook = SlackWebhook.load(SLACK_WEBHOOK_BLOCK_NAME) webhook.notify(body, subject=subject) @@ -115,8 +124,11 @@ def upload_multiple_files_to_slack( Returns ------- Dict[str, bool] - Dictionary mapping filepath to upload success status + Dictionary mapping filepath to upload success status; False when disabled """ + if not slack_notifications_enabled(): + return {filepath: False for filepath in filepaths} + if slack_bot_token is None: slack_bot_token = SlackCredentials.load( SLACK_API_TOKEN_BLOCK_NAME diff --git a/opticstream/utils/slack_settings.py b/opticstream/utils/slack_settings.py new file mode 100644 index 0000000..8a07b4c --- /dev/null +++ b/opticstream/utils/slack_settings.py @@ -0,0 +1,19 @@ +"""Runtime switch shared by Slack hooks and notification tasks.""" + +from prefect.logging.loggers import get_logger +from prefect.variables import Variable + +from opticstream.config.constants import SLACK_NOTIFICATIONS_ENABLED_VARIABLE_NAME + + +def slack_notifications_enabled() -> bool: + """Read the server-wide switch each time; absent means enabled.""" + enabled = Variable.get(SLACK_NOTIFICATIONS_ENABLED_VARIABLE_NAME, default=True) + if not isinstance(enabled, bool): + raise ValueError( + f"{SLACK_NOTIFICATIONS_ENABLED_VARIABLE_NAME} must be a JSON boolean " + "(true or false), not a string or another value." + ) + if not enabled: + get_logger(__name__).info("Slack notifications disabled; skipping.") + return enabled diff --git a/tests/test_slack_settings.py b/tests/test_slack_settings.py new file mode 100644 index 0000000..bf6fad7 --- /dev/null +++ b/tests/test_slack_settings.py @@ -0,0 +1,70 @@ +from contextlib import ExitStack +from importlib import import_module +import unittest +from unittest.mock import Mock, patch + +from opticstream.utils import slack_settings + + +hook_module = import_module("opticstream.hooks.slack_notification_hook") +tasks = import_module("opticstream.tasks.slack_notification") + + +class SlackSettingsTests(unittest.TestCase): + def test_default_and_runtime_changes(self): + values = {} + with patch.object( + slack_settings.Variable, "get", + side_effect=lambda name, default=None: values.get(name, default), + ): + self.assertIs(slack_settings.slack_notifications_enabled(), True) + values["slack-notifications-enabled"] = False + self.assertIs(slack_settings.slack_notifications_enabled(), False) + values["slack-notifications-enabled"] = True + self.assertIs(slack_settings.slack_notifications_enabled(), True) + + def test_rejects_non_boolean_values(self): + for value in ("false", "true", None, 0, 1, {}): + with self.subTest(value=value), patch.object( + slack_settings.Variable, "get", return_value=value, + ): + with self.assertRaisesRegex(ValueError, "JSON boolean"): + slack_settings.slack_notifications_enabled() + + def test_disabled_skips_all_slack_paths_before_loading_blocks(self): + def read_toggle(name, default=None): + self.assertEqual(name, "slack-notifications-enabled") + return False + + forbidden = Mock(side_effect=AssertionError("Slack must not be accessed")) + webhook = Mock() + with ExitStack() as stack: + stack.enter_context(patch.object( + slack_settings.Variable, "get", side_effect=read_toggle, + )) + for block in (tasks.SlackCredentials, tasks.Secret, tasks.SlackWebhook): + stack.enter_context(patch.object(block, "load", forbidden)) + stack.enter_context(patch.object(tasks, "WebClient", forbidden)) + stack.enter_context(patch.object(tasks.os.path, "exists", forbidden)) + hook_module.slack_notification_hook(None, None, None) + self.assertIs(tasks.send_slack_message.fn("test"), False) + self.assertIs(tasks.send_slack_message.fn("test", "token", "channel"), False) + self.assertIs(tasks.send_slack_message_webhook.fn("test"), False) + self.assertIs( + tasks.send_slack_message_webhook.fn("test", webhook=webhook), False, + ) + self.assertEqual( + tasks.upload_multiple_files_to_slack.fn(["missing.nii"]), + {"missing.nii": False}, + ) + forbidden.assert_not_called() + webhook.notify.assert_not_called() + + def test_enabled_webhook_still_sends(self): + webhook = Mock() + with patch.object(slack_settings.Variable, "get", return_value=True), patch.object( + tasks.SlackWebhook, "load", return_value=webhook, + ) as load: + tasks.send_slack_message_webhook.fn("test", subject="subject") + load.assert_called_once_with("watchdog") + webhook.notify.assert_called_once_with("test", subject="subject") From 41a147adc8c8884e5597c7a8eab8d3836a35251a Mon Sep 17 00:00:00 2001 From: NoahMarkowitz Date: Fri, 11 Sep 2026 12:05:37 -0400 Subject: [PATCH 08/65] dandi upload now working --- opticstream/cli/deploy_cmds.py | 2 +- opticstream/cli/oct/deploy.py | 12 ---- .../flows/psoct/tile_batch_upload_flow.py | 8 +-- opticstream/tasks/dandi_upload.py | 58 +++++++++++++++++-- pyproject.toml | 1 + 5 files changed, 58 insertions(+), 23 deletions(-) diff --git a/opticstream/cli/deploy_cmds.py b/opticstream/cli/deploy_cmds.py index 3669aea..57ad15b 100644 --- a/opticstream/cli/deploy_cmds.py +++ b/opticstream/cli/deploy_cmds.py @@ -66,7 +66,7 @@ class FlowDeploymentSpec: # Note: mosaic enface/volume uploads are deployed via `opticstream cli oct deploy`. # This CLI entry covers only the tile-batch upload flow. # Add mosaic upload deployments here only if their modules define `__main__` deployments. - "upload_to_linc_batch_event_flow_deployment", + "upload_to_dandi_batch_event_flow_deployment", ), description="Upload flow for tile batches to DANDI.", ), diff --git a/opticstream/cli/oct/deploy.py b/opticstream/cli/oct/deploy.py index 05e03d0..bd19668 100644 --- a/opticstream/cli/oct/deploy.py +++ b/opticstream/cli/oct/deploy.py @@ -93,18 +93,6 @@ def deploy( # Upload Flow Deployments # ============================================================================ - upload_to_linc_batch_event_flow.from_source( - source=Path(__file__).parent.parent.parent / "flows", - entrypoint="psoct/tile_batch_upload_flow.py:upload_to_linc_batch_event_flow", - ).deploy( - name=deployment_name, - work_pool_name=work_pool_name, - tags=["event-driven", "tile-batch", "upload-to-linc", *COMMON_TAGS], - triggers=[get_event_trigger(BATCH_ARCHIVED, project_name=project_name)], - build=False, - push=False, - ) - upload_mosaic_enface_to_dandi_event_flow.from_source( source=Path(__file__).parent.parent.parent / "flows", entrypoint="psoct/mosaic_upload_flow.py:upload_mosaic_enface_to_dandi_event_flow", diff --git a/opticstream/flows/psoct/tile_batch_upload_flow.py b/opticstream/flows/psoct/tile_batch_upload_flow.py index b22bdb7..f86f4c8 100644 --- a/opticstream/flows/psoct/tile_batch_upload_flow.py +++ b/opticstream/flows/psoct/tile_batch_upload_flow.py @@ -32,7 +32,7 @@ def upload_to_dandi_tile_batch( batch_id: OCTBatchId, file_list: list[Path], *, - dandi_instance: str = "linc", + dandi_instance: str = "dandi", realpath: bool = True, dandi_api_key: Secret | None = None, force_rerun: bool = False, @@ -51,7 +51,7 @@ def upload_to_dandi_tile_batch( @flow -def upload_to_linc_batch_event_flow(payload: Dict[str, Any]) -> None: +def upload_to_dandi_batch_event_flow(payload: Dict[str, Any]) -> None: batch_ident = batch_ident_from_payload(payload) cfg = load_scan_config_for_payload(payload) return upload_to_dandi_tile_batch( @@ -71,13 +71,13 @@ def to_deployment( """ Create both deployments: - manual `upload_to_dandi_tile_batch` (ad-hoc reruns) - - event-driven `upload_to_linc_batch_event_flow` (triggered by BATCH_ARCHIVED) + - event-driven DANDI upload (triggered by BATCH_ARCHIVED) """ manual = upload_to_dandi_tile_batch.to_deployment( name=deployment_name, tags=["tile-batch", "upload-to-linc", *list(extra_tags)], ) - event = upload_to_linc_batch_event_flow.to_deployment( + event = upload_to_dandi_batch_event_flow.to_deployment( name=deployment_name, tags=["event-driven", "tile-batch", "upload-to-linc", *list(extra_tags)], triggers=[get_event_trigger(BATCH_ARCHIVED, project_name=project_name)], diff --git a/opticstream/tasks/dandi_upload.py b/opticstream/tasks/dandi_upload.py index 00ca6ca..7476991 100644 --- a/opticstream/tasks/dandi_upload.py +++ b/opticstream/tasks/dandi_upload.py @@ -9,6 +9,7 @@ import os import shlex +from pathlib import Path from typing import Dict, List, Tuple from prefect import get_run_logger, task @@ -47,12 +48,10 @@ def build_dandi_upload_command( if dandi_instance != "dandi": command += f"-i {shlex.quote(dandi_instance)} " - # Match the CLI flags used elsewhere in the codebase. - command += f"{file_paths_str} -J {shlex.quote(max_jobs)} --allow-any-path" - if dandi_instance == "dandi" or True: - command += " --existing overwrite --validation skip" - else: - command += " --existing OVERWRITE --validation SKIP" + command += f"{file_paths_str} -J {shlex.quote(max_jobs)}" + if dandi_instance != "dandi": + command += " --allow-any-path" + command += " --existing overwrite --validation skip" # DANDI CLI errors can sometimes be clearer when run from file directory. working_dir = os.path.dirname(file_list[0]) if file_list[0] else os.getcwd() @@ -93,6 +92,48 @@ def _build_dandi_upload_env( } +def _upload_dandi_api( + file_list: List[str], + *, + max_jobs: str, +) -> None: + """Upload DANDI assets through the API, including generic NIfTI files. + + Recent DANDI CLIs filter unrecognized files before upload and no longer + provide the ``--allow-any-path`` switch. The API equivalent is + ``allow_any_path=True``. + """ + from dandi.upload import UploadExisting, UploadValidation, upload + + try: + jobs, jobs_per_file = (int(part) for part in max_jobs.split(":", 1)) + except (ValueError, AttributeError): + jobs = jobs_per_file = 5 + + paths = [Path(os.path.realpath(path)) for path in file_list] + # DANDI needs the local dandiset metadata alongside assets in order to + # resolve the target dataset. Walk upward from each asset and include the + # nearest dandiset.yaml once when it exists (e.g. .../001769/dandiset.yaml). + metadata_paths: list[Path] = [] + for path in paths: + for parent in (path.parent, *path.parents): + metadata = parent / "dandiset.yaml" + if metadata.is_file(): + if metadata not in metadata_paths: + metadata_paths.append(metadata) + break + + upload( + paths=[*paths, *metadata_paths], + existing=UploadExisting.OVERWRITE, + validation=UploadValidation.SKIP, + dandi_instance="dandi", + allow_any_path=True, + jobs=jobs, + jobs_per_file=jobs_per_file, + ) + + @task(tags=["dandi-upload"], retries=1) def upload_to_dandi_batch( file_list: List[str], @@ -125,6 +166,11 @@ def upload_to_dandi_batch( logger.info("Running DANDI batch upload with %s files", len(file_list)) logger.info(command) + if dandi_instance == "dandi": + _upload_dandi_api(file_list, max_jobs=max_jobs) + logger.info("DANDI batch upload completed") + return + with ShellOperation( commands=[command], env=env, diff --git a/pyproject.toml b/pyproject.toml index 1734cab..c174278 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -11,6 +11,7 @@ dependencies = [ "psoct-toolbox @ git+https://github.com/calvinchai/psoct-toolbox.git@5182337044d2b7f8337ca205a33c9da3ddd69bda", "matplotlib>=3.10.8", "prefect[shell,slack,sqlalchemy]>=3.6.20", + "dandi>=0.78.0", "watchdog", "psutil", "slack-sdk", From 8f30ada352bf09eee34cb113ef8338b8bc76cff3 Mon Sep 17 00:00:00 2001 From: NoahMarkowitz Date: Fri, 11 Sep 2026 15:05:53 -0400 Subject: [PATCH 09/65] matlab processing working --- .../+psoct/+spectral/spectral2complex.m | 309 ++++++++++++++++++ opticstream/matlab/README.md | 25 ++ .../matlab/opticstream_interpolationwave.m | 160 +++++++++ .../matlab/opticstream_read_dispersion.m | 45 +++ opticstream/utils/matlab_execution.py | 8 +- pyproject.toml | 3 + tests/matlab/test_spectral_overlay.m | 33 ++ 7 files changed, 582 insertions(+), 1 deletion(-) create mode 100644 opticstream/matlab/+psoct/+spectral/spectral2complex.m create mode 100644 opticstream/matlab/README.md create mode 100644 opticstream/matlab/opticstream_interpolationwave.m create mode 100644 opticstream/matlab/opticstream_read_dispersion.m create mode 100644 tests/matlab/test_spectral_overlay.m diff --git a/opticstream/matlab/+psoct/+spectral/spectral2complex.m b/opticstream/matlab/+psoct/+spectral/spectral2complex.m new file mode 100644 index 0000000..44ca58d --- /dev/null +++ b/opticstream/matlab/+psoct/+spectral/spectral2complex.m @@ -0,0 +1,309 @@ +function [Jones1_3D, Jones2_3D] = spectral2complex(spectralFile, spectralOpts, outputOpts) +%SPECTRAL2COMPLEX Convert spectral data to complex data. +% +% [Jones1_3D, Jones2_3D] = spectral2complex(spectralFile, spectralOpts) +% +% Input +% spectralFile : Path to the spectral data file. +% spectralOpts : Struct with fields: +% - dispCompFile: Path to the dispersion compensation file. +% - AlineSize : Size of the A-line (pixels of X axis). +% - BlineSize : Size of the B-line (pixels of Y axis). +% - isRawFormat : Whether input is in packed 12-bit raw format. +% outputOpts : Struct with fields: +% - Paths : Struct with fields: +% - complex : Path to the output complex NIfTI file. +% - InfoLike : NIfTI-info-like struct used as write template. +% +% Output +% Jones1_3D : Complex Jones volume for channel 1 (Aline x Bline x Depth). +% Jones2_3D : Complex Jones volume for channel 2 (Aline x Bline x Depth). +% +% This function is designed to be numerically equivalent to the legacy +% s2c_raw implementation when called with the corresponding parameters. +arguments + spectralFile {mustBeTextScalar, mustBeNonempty} + spectralOpts struct = struct() + outputOpts struct = struct() +end + +spectralOpts = psoct.internal.opts.normalizeSpectralOpts(spectralOpts); +outputOpts = psoct.internal.opts.normalizeOutputOpts(outputOpts); + +dispCompFile = string(spectralOpts.dispCompFile); +AlineSize = spectralOpts.AlineSize; +BlineSize = spectralOpts.BlineSize; +isRawFormat = spectralOpts.isRawFormat; + +% Constants describing the acquisition format. +HEADER_BYTES = 352; % Header size of Nifti-1 file +BITS_PER_SAMPLE_RAW = 12; % Packed 12-bit samples for raw format +BYTES_PER_UINT16 = 2; % 16-bit unsigned integers + +warning off MATLAB:polyfit:RepeatedPointsOrRescale %#ok + +Aline = AlineSize; +Bline = BlineSize; +fprintf('AlineSize = %i; BlineSize = %i \n', AlineSize, BlineSize); + +% Parameters copied from original script / s2c_raw +AutoCorrPeakCut = 24; % multiple of 8 +DepthL = 1024 - AutoCorrPeakCut; %#ok kept for compatibility +AlineLength = 2048; % Headerless packed raw retains its legacy geometry. +niftiData = []; +if ~isRawFormat + info = niftiinfo(spectralFile); + niftiData = niftiread(info); + dims = size(niftiData); + if ndims(niftiData) > 3 || mod(dims(2), 2) ~= 0 + error('spectral2complex:Geometry', ... + 'Expected [spectra, 2*A-lines per channel, B-lines] NIfTI.'); + end + AlineLength = dims(1); + AlineSize = dims(2)/2; + BlineSize = size(niftiData, 3); + Aline = AlineSize; + Bline = BlineSize; + fprintf('NIfTI geometry: %d spectra, %d A-lines/channel, %d B-lines\n', ... + AlineLength, Aline, Bline); +end +DepthL = floor(AlineLength/2) - AutoCorrPeakCut; +if DepthL < 1 + error('spectral2complex:TooShort', 'Need at least 50 spectral samples.'); +end + +% Buffer size bookkeeping +numSamplesPerBuffer = AlineLength * AlineSize; +if isRawFormat + % Packed 12-bit: 3 bytes per 2 samples + bytesPerBuffer = numSamplesPerBuffer * (BITS_PER_SAMPLE_RAW / 8); +else + % 16-bit samples + bytesPerBuffer = numSamplesPerBuffer * BYTES_PER_UINT16; +end + +% Depth / interpolation configuration +PaddingFactor = 1; +PaddingLength = AlineLength * PaddingFactor; +OriginalLineLength1 = AlineLength; +OriginalLineLength2 = AlineLength; +Start1 = 1; +Start2 = 1; + +InterpolationParameters = [ ... + PaddingFactor, PaddingLength, ... + OriginalLineLength1, Start1, ... + OriginalLineLength2, Start2]; + +[Wavelengths_l, Wavelengths_r, InterpolatedWavelengths2, Ks] = ... + opticstream_interpolationwave(InterpolationParameters); %#ok + +% Package parameters that are shared across B-lines +params = struct(); +params.AlineSize = AlineSize; +params.BlineSize = BlineSize; +params.AlineLength = AlineLength; +params.AutoCorrPeakCut = AutoCorrPeakCut; +params.PaddingFactor = PaddingFactor; +params.PaddingLength = PaddingLength; +params.OriginalLineLength1 = OriginalLineLength1; +params.OriginalLineLength2 = OriginalLineLength2; +params.Start1 = Start1; +params.Start2 = Start2; +params.numSamplesPerBuffer = numSamplesPerBuffer; +params.bytesPerBuffer = bytesPerBuffer; +params.Wavelengths_l = Wavelengths_l; +params.Wavelengths_r = Wavelengths_r; +params.InterpolatedWavelengths = InterpolatedWavelengths2; + +% Read dispersion correction file(s) +dispCompFile1 = dispCompFile; +dispCompFile2 = dispCompFile; + +phaseCorrection1 = opticstream_read_dispersion(dispCompFile1, AlineLength); +phaseCorrection2 = opticstream_read_dispersion(dispCompFile2, AlineLength); + +% Replicate along A-line dimension to match interpolated buffer size +phaseCorrection1 = repmat(phaseCorrection1, 1, Aline); +phaseCorrection2 = repmat(phaseCorrection2, 1, Aline); + +% Preallocate complex stacks for Jones1 and Jones2: +% dimensions: Bline x Aline x DepthL (complex) +Jones1_3D = complex(zeros(Bline, Aline, DepthL)); +Jones2_3D = complex(zeros(Bline, Aline, DepthL)); + +% Basic validation of input file size (best-effort check) +fileInfo = dir(spectralFile); +if ~isempty(fileInfo) + expectedBytes = Bline * (2 * bytesPerBuffer); + if ~isRawFormat + expectedBytes = expectedBytes + HEADER_BYTES; + end + if fileInfo.bytes < expectedBytes + warning('spectral2complex:FileTooSmall', ... + 'Spectral file "%s" appears smaller (%d bytes) than expected (~%d bytes).', ... + spectralFile, fileInfo.bytes, expectedBytes); + end +end + +fid = fopen(spectralFile, 'rb'); +if fid == -1 + error('spectral2complex:FileOpenFailed', ... + 'Could not open spectral data file "%s".', spectralFile); +end +cleanupObj = onCleanup(@() fclose(fid)); %#ok + +for blineIndex = 1:Bline + if mod(blineIndex, 10) == 0 || blineIndex == Bline + pct = 100 * blineIndex / Bline; + fprintf('\rProcessing bline: %d / %d (%.1f%%)', blineIndex, Bline, pct); + end + + % Read raw wavelength buffers for both polarization channels + if isRawFormat + [WavelengthBuffer1, WavelengthBuffer2] = readBlineBuffers( ... + fid, blineIndex, params, isRawFormat, HEADER_BYTES); + else + WavelengthBuffer1 = double(niftiData(:, 1:Aline, blineIndex)); + WavelengthBuffer2 = flipud(double(niftiData(:, Aline+1:2*Aline, blineIndex))); + end + + % Convert spectral buffers into Jones vectors for this B-line + [Jones1, Jones2] = processBlineBuffers( ... + WavelengthBuffer1, WavelengthBuffer2, params, ... + phaseCorrection1, phaseCorrection2); + + % Store into the stack. Jones returned as Depth x Aline -> transpose to Aline x Depth + % We want shape Bline x Aline x Depth, so transpose Jones and assign: + Jones1_3D(blineIndex,:,:) = Jones1'; % Bline x Aline x Depth + Jones2_3D(blineIndex,:,:) = Jones2'; +end % for blineIndex + +Jones1_3D = permute(Jones1_3D, [2 1 3]); +Jones2_3D = permute(Jones2_3D, [2 1 3]); + +Jones1_3d = flip(Jones1_3D, 3); +Jones2_3d = flip(Jones2_3D, 3); + +outputPath = outputOpts.Paths.complex; +if outputPath ~= "" + % real_J1: Bline x Aline x Depth -> we'll stack along dim 1, + % so cat(1, real, imag) -> (2*Bline) x Aline x Depth + Jstack_all = cat(1, ... + real(Jones1_3D), imag(Jones1_3D), ... + real(Jones2_3D), imag(Jones2_3D)); + + fprintf('Saving output to: %s\n', outputPath); + Jstack_all = single(Jstack_all); + futures = {}; + futures = psoct.internal.nifti.appendWriteFuture(futures, ... + psoct.internal.nifti.writeNiftiIfPath(outputPath, Jstack_all, outputOpts.InfoLike)); + psoct.internal.nifti.waitWriteFutures(futures); +end + +end + +% ------------------------------------------------------------------------- +% Local helpers +% ------------------------------------------------------------------------- + +function [WavelengthBuffer1, WavelengthBuffer2] = readBlineBuffers( ... + fid, blineIndex, params, isRawFormat, headerBytes) +%READBLINEBUFFERS Read both polarization buffers for a single B-line. + +offsetBase = (blineIndex - 1) * (2 * params.bytesPerBuffer); % two buffers (channels) per B-line +if ~isRawFormat + offsetBase = offsetBase + headerBytes; % header is present once at the beginning +end + +fseekStatus = fseek(fid, offsetBase, 'bof'); +if fseekStatus ~= 0 + error('spectral2complex:SeekFailed', ... + 'Failed to seek to offset %d in spectral file.', offsetBase); +end + +if ~isRawFormat + data1 = fread(fid, params.numSamplesPerBuffer, 'uint16'); + data2 = fread(fid, params.numSamplesPerBuffer, 'uint16'); +else + raw1 = fread(fid, params.bytesPerBuffer, 'uint8=>uint8'); + raw2 = fread(fid, params.bytesPerBuffer, 'uint8=>uint8'); + if numel(raw1) < params.bytesPerBuffer || numel(raw2) < params.bytesPerBuffer + error('spectral2complex:UnexpectedEOF', ... + 'Reached end of file while reading raw buffers for B-line %d.', blineIndex); + end + data1 = psoct.spectral.unpack12bits(raw1); + data2 = psoct.spectral.unpack12bits(raw2); +end + +if numel(data1) ~= params.numSamplesPerBuffer || numel(data2) ~= params.numSamplesPerBuffer + error('spectral2complex:UnexpectedSampleCount', ... + 'Expected %d samples per buffer but read %d and %d.', ... + params.numSamplesPerBuffer, numel(data1), numel(data2)); +end + +WavelengthBuffer1 = reshape(data1, params.AlineLength, []); +WavelengthBuffer2 = flipud(reshape(data2, params.AlineLength, [])); +end + +function [Jones1, Jones2] = processBlineBuffers( ... + WavelengthBuffer1, WavelengthBuffer2, params, ... + phaseCorrection1, phaseCorrection2) +%PROCESSBLINEBUFFERS Convert spectral buffers into Jones vectors. + +Aline = params.AlineSize; +PaddingFactor = params.PaddingFactor; +OriginalLineLength1 = params.OriginalLineLength1; +OriginalLineLength2 = params.OriginalLineLength2; +Start1 = params.Start1; +Start2 = params.Start2; + +% Remove reference (mean across A-lines) +refdata1 = mean(WavelengthBuffer1, 2); +refdata2 = mean(WavelengthBuffer2, 2); +MeanScan1 = WavelengthBuffer1 - refdata1; +MeanScan2 = WavelengthBuffer2 - refdata2; + +% Crop to original line length +OriginalBuffer1 = MeanScan1(Start1:OriginalLineLength1 - 1 + Start1, :); +OriginalBuffer2 = MeanScan2(Start2:OriginalLineLength2 - 1 + Start2, :); + +% Zero padding +ZeroPaddedBuffer1 = OriginalBuffer1; % PaddingFactor is one; preserve arbitrary sample counts. +ZeroPaddedBuffer2 = OriginalBuffer2; +% Retain legacy even-length numerical behavior; its helper cannot index odd lengths. +if mod(size(OriginalBuffer1, 1), 2) == 0 + ZeroPaddedBuffer1 = psoct.legacy.ZeroPadBuffer(OriginalBuffer1, PaddingFactor); + ZeroPaddedBuffer2 = psoct.legacy.ZeroPadBuffer(OriginalBuffer2, PaddingFactor); +end + +% Interpolation onto k-space grid +InterpolatedBuffer1 = interp1(params.Wavelengths_l, ZeroPaddedBuffer1, ... + params.InterpolatedWavelengths, 'linear', 'extrap'); +InterpolatedBuffer2 = interp1(params.Wavelengths_r, ZeroPaddedBuffer2, ... + params.InterpolatedWavelengths, 'linear', 'extrap'); + +% Remove DC component using median across A-lines +InterpolatedBuffer1 = InterpolatedBuffer1 - median(InterpolatedBuffer1, 2); +InterpolatedBuffer2 = InterpolatedBuffer2 - median(InterpolatedBuffer2, 2); + +% Apply dispersion correction +InterpolatedBuffer1 = InterpolatedBuffer1 .* phaseCorrection1; +InterpolatedBuffer2 = InterpolatedBuffer2 .* phaseCorrection2; + +% Obtain Jones vectors (complex) for this B-line (size: Depth x Aline) +Jones1 = buffer2jones(InterpolatedBuffer1, PaddingFactor, params.AutoCorrPeakCut); +Jones2 = buffer2jones(InterpolatedBuffer2, PaddingFactor, params.AutoCorrPeakCut); +end + +function [Jones]=buffer2jones(OriginalBuffer, PaddingFactor, AutoCorrPeakCut) +% [Jones]=Buffer2JonesDispComp(OriginalBuffer, PaddingFactor, AutoCorrPeakCut) + +% % upsampling +% AlineLength = size(OriginalBuffer, 1) / (2*PaddingFactor)*4; +% Jones = fft(OriginalBuffer,4*size(OriginalBuffer,1)); +AlineLength = floor(size(OriginalBuffer, 1) / (2*PaddingFactor)); +Jones = (fft(OriginalBuffer,size(OriginalBuffer,1))); +Jones(AlineLength+1:end, :) = []; +Jones(1:AutoCorrPeakCut, :) = []; % Cut out autocorrelation peak +end diff --git a/opticstream/matlab/README.md b/opticstream/matlab/README.md new file mode 100644 index 0000000..d077e11 --- /dev/null +++ b/opticstream/matlab/README.md @@ -0,0 +1,25 @@ +OpticStream MATLAB overlay +========================= + +The execution helper prepends this directory after loading psoct_toolbox. +The package override and interpolation helper are adapted from psoct-toolbox +commit 5182337044d2b7f8337ca205a33c9da3ddd69bda. + +Spectral NIfTI layout: [spectral samples, two concatenated channel A-line +blocks, B-lines]. Header dimensions override AlineSize/BlineSize for NIfTI. +All spectral samples are retained, including nonmultiples of 1024. +Headerless packed raw retains the original 2048-sample geometry. + +Dispersion formats: +- .txt/.csv/.tsv: one phase angle in radians per row, two real/imaginary + columns, or one complex multiplier per row (e.g. 0.98+0.12i). +- Other extensions: native-endian binary float64 phase angles. + +The file must contain exactly one finite coefficient per spectral sample. +Complex multipliers are applied directly; phase angles use exp(-1i*phase). +The same correction is used for both channels, as in the upstream reader. +No coefficients are silently truncated, padded or recalibrated. + +The legacy wavelength calibration and channel-2 reversal remain in use; +support for additional lengths does not validate that calibration for a +different scanner. Output depth is floor(samples/2)-24. diff --git a/opticstream/matlab/opticstream_interpolationwave.m b/opticstream/matlab/opticstream_interpolationwave.m new file mode 100644 index 0000000..107a9a2 --- /dev/null +++ b/opticstream/matlab/opticstream_interpolationwave.m @@ -0,0 +1,160 @@ +function [Wavelengths_l, Wavelengths_r,InterpolatedWavelengths, Ks, Ko1, Ko2]=opticstream_interpolationwave(Parameters) +% [Wavelengths_l, Wavelengths_r,InterpolatedWavelengths,Ks]=interpolationwave_20201130(Parameters) +% Parameters=[PaddingFactor, PaddingLength, OriginalLineLength1, Start1, OriginalLineLength2, Start2] + +format long + +load(psoct.internal.getDataFile('wave-pixel.mat')); +% mu wavelength wave_prime (where wave_prime == wavelength) + +disp(' interpolating buffer '); + +if nargin<1 + PaddingFactor=1; + PaddingLength=PaddingFactor*2048; + OriginalLineLength1=2048; + Start1=1; + OriginalLineLength2=2048; + Start2=1; +else + % InterpolationParameters = [PaddingFactor,PaddingLength,OriginalLineLength1,Start1,OriginalLineLength2,Start2]; + PaddingFactor = Parameters(1); + PaddingLength = Parameters(2); + OriginalLineLength1 = Parameters(3); + Start1 = Parameters(4); + OriginalLineLength2 = Parameters(5); + Start2 = Parameters(6); +end + +% PaddingFactor1=OriginalLineLength1/PaddingLength; +% PaddingFactor2=OriginalLineLength2/PaddingLength; + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% 021309 + +% position_r=[30 98 169 238 307 377 448 518 589 660 804 876]; +% position_l=[18 86 155 224 293 362 432 501 572 641 783 854]; +% wave_sample=[805 810 815 820 825 830 835 840 845 850 860 865]; +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% 022009 +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +% position_l=[40 81 150 220 290 361 431 502 573 645 717 784 862 891]; +% position_r=[13 54 123 192 261 331 401 471 541 612 682 753 825 853]; +% wave_sample=[807 810 815 820 825 830 835 840 845 850 855 860 865 867]; + +% l is left position pixel recorded, r is right position pixel recorded + +% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% % 071009 +% % l is left position pixel recorded, r is right position pixel recorded +% position_l=[2 65.5 144 221 297 372 446 520 592 664 734.5 804 873.5 927.5]; +% position_r= [33 93.5 168 242 314 386 457 528 597 666 734 801 868 920]+1024; +% wave_sample=[806 810 815 820 825 830 835 840 845 850 855 860 865 869]; +% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% For CMOS camera +% % 020212 +% % l is left position pixel recorded, r is right position pixel recorded +% position_l=[14 98 237 378 517 660 802 944 1088 1231 1374 1520 1663 1807]; +% position_r= [2158 2239 2374 2510 2644 2783 2920 3057 3197 3336 3475 3616 3756 3896]; +% wave_sample=[802 805 810 815 820 825 830 835 840 845 850 855 860 865]; +% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% 022212 +% % horizontal binning disabled +% position_l=[6 22 161 301 442 583 724 866 1007 1153 1293.5 1439 1582 1727.5 1870]; +% position_r= [2138 2153 2288 2424 2561 2697 2834 2972 3110 3251 3389 3531 3671 3813 3953]-2048; +% wave_sample=[799.43 800 805 810 815 820 825 830 835 840 845 850 855 860 865]; + +% horizontal binning enabled, used in CMOS now +% position_l=[3 11 80 150 221 291 362 433 503 576 646.5 719 791 863.5 935]; +% position_r= [1069 1076 1144 1212 1280 1348 1417 1486 1555 1625 1694 1765 1835 1906 1976]; +% wave_sample=[799.43 800 805 810 815 820 825 830 835 840 845 850 855 860 865]; + + +% 1300 two-cameras +position_l= mu(:,1); +% position_l(1)=position_l(1)-4; +% position_l(2)=position_l(2)+1; +% % position_l(3)=position_l(3)-3; +% % position_l(4)=position_l(4)-2; +% % position_l(5)=position_l(5)-1; +% position_l(6)=position_l(6)-5; +% % position_l(7)=position_l(7)+3; +% % position_l(8)=position_l(8)+4; +% position_l(9)=position_l(9)-6; + +position_r= mu(:,2); +% position_r(6)=position_r(6)-6; +% position_r(2)=position_r(2)-6; +% position_r(9)=position_r(9)-8; + +wave_sample=wave_prime; +if size(wave_sample)~=size(position_l) + wave_sample=wave_sample'; +end + +% position_l=([283 353 616 686 926 999 988 1065 1067 1122 1111 1172 1186 1262 1231 1306 1555 1624])'; +% position_r=([282 352 618 687 925 1002 989 1068 1067 1122 1113 1175 1185 1265 1233 1307 1556 1627])'; +% wave_sample=([1192.7 1204.3 1246.3 1256 1292 1303 1301.3 1313.2 1312.5 1325.5 1326.5 1338 1333.2 1346.3 1343.5 1355.5 1395.5 1407.3])'; +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +% Do second order least-squares fitting to find the wavelengths of the whole +% spectrums +pcoeff1=polyfit(position_l,wave_sample,1); % linear interpolation +pcoeff1 +x1=1:(Start1+OriginalLineLength1-1); +lamda_l=polyval(pcoeff1,x1); +pcoeff2=polyfit(position_r,wave_sample,1); % linear interpolation +pcoeff2 +x2=1:(Start2+OriginalLineLength2-1); +lamda_r=polyval(pcoeff2,x2); + +W_l=lamda_l(Start1:Start1+OriginalLineLength1-1); +W_r=lamda_r(Start2:Start2+OriginalLineLength2-1); +xx1=linspace(Start1,Start1+OriginalLineLength1-1,PaddingLength); +Wavelengths_l=1e-9*interp1([Start1:Start1+OriginalLineLength1-1],W_l,xx1,'linear','extrap')'; +xx2=linspace(Start2,Start2+OriginalLineLength2-1,PaddingLength); +Wavelengths_r=1e-9*interp1([Start2:Start2+OriginalLineLength2-1],W_r,xx2,'linear','extrap')'; +% Wavelengths_l(1) +% Wavelengths_r(1) +% Wavelengths_l(end) +% Wavelengths_r(end) +minK = 2*pi / min([Wavelengths_l(end) Wavelengths_r(end)]); +maxK = 2*pi / max([Wavelengths_l(1) Wavelengths_r(1)]); +% Wavelengths=(Wavelengths_l + Wavelengths_r)/2; +% minK = 2*pi / max(Wavelengths) +% maxK = 2*pi / min(Wavelengths) +Ko1 = (2*pi) ./ Wavelengths_l; +Ko2 = (2*pi) ./ Wavelengths_r; + + +% figure,plot([lamda_l' lamda_r']); legend('\lambda_l','\lambda_r'); +% fout=['/autofs/cluster/octdata2/users/Hui/PSCalibration/SpectrometerCal_10xw_20201016/interpolationwave_lambda_plot.png']; +% print(gcf,fout,'-dpng','-r300'); +% +% figure('position',[288 153 960 798]); hold on; +% plot((1:PaddingLength)',[Wavelengths_l Wavelengths_r],'linewidth',1.5); +% plot(position_l*PaddingFactor,1e-9*wave_sample,'.','markersize',14,'color','r'); +% plot(position_r*PaddingFactor,1e-9*wave_sample,'.','markersize',14,'color','g'); +% legend('wavelengths_l','wavelengths_r','position_l*pad vs wavesample','position_l*pad vs wavesample','Location','best'); +% fout=['/autofs/cluster/octdata2/users/Hui/PSCalibration/SpectrometerCal_10xw_20201016/interpolationwave_wavelengths_plot1.png']; +% print(gcf,fout,'-dpng','-r300'); +% +% figure,plot((Wavelengths_l-Wavelengths_r)*(1e+9)); +% title('wavelengths_l - wavelength_r'); +% fout=['/autofs/cluster/octdata2/users/Hui/PSCalibration/SpectrometerCal_10xw_20201016/interpolationwave_wavelengths_plot2.png']; +% print(gcf,fout,'-dpng','-r300'); + + +% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +% clear x1 lamda_l x2 lamda_r W_l W_r xx1 xx2 + +Ks=flipud(linspace(minK,maxK,PaddingLength)'); +InterpolatedWavelengths = (2*pi) ./ Ks; + +disp(' '); diff --git a/opticstream/matlab/opticstream_read_dispersion.m b/opticstream/matlab/opticstream_read_dispersion.m new file mode 100644 index 0000000..4198fa1 --- /dev/null +++ b/opticstream/matlab/opticstream_read_dispersion.m @@ -0,0 +1,45 @@ +function correction = opticstream_read_dispersion(filename, spectra) +% Text: N complex rows, N-by-2 real/imaginary pairs, or N phase angles. +% Binary (.dat/.bin): N native-endian float64 phase angles, legacy convention. +% A complex pair counts as ONE spectral coefficient. +[~,~,ext] = fileparts(filename); +if any(strcmpi(ext, {'.txt', '.csv', '.tsv'})) + lines = strip(splitlines(string(fileread(filename)))); + lines(lines == "") = []; + if any(contains(lower(lines), ["i", "j"])) + % str2double parses complex literals without evaluating MATLAB code. + correction = str2double(lines); + if any(isnan(correction)) + error('spectral2complex:DispersionFormat', ... + 'Expected one complex number per row, e.g. 0.98+0.12i.'); + end + else + values = readmatrix(filename, 'FileType', 'text'); + if size(values, 2) == 2 + correction = complex(values(:,1), values(:,2)); + elseif isvector(values) + correction = exp(-1i .* values(:)); + else + error('spectral2complex:DispersionFormat', ... + 'Text dispersion must contain phase angles or two real/imaginary columns.'); + end + end +else + fid = fopen(filename, 'rb'); + if fid < 0 + error('spectral2complex:DispersionOpenFailed', 'Cannot open %s.', filename); + end + cleanup = onCleanup(@() fclose(fid)); + bytes = dir(filename); + if mod(bytes.bytes, 8) ~= 0 + error('spectral2complex:DispersionFormat', 'Binary phase file must contain float64 values.'); + end + correction = exp(-1i .* fread(fid, inf, 'double')); +end +if numel(correction) ~= spectra || any(~isfinite(correction(:))) + error('spectral2complex:BadDispersionLength', ... + 'Dispersion file "%s" has %d coefficients; NIfTI requires exactly %d finite coefficients.', ... + filename, numel(correction), spectra); +end +correction = correction(:); +end diff --git a/opticstream/utils/matlab_execution.py b/opticstream/utils/matlab_execution.py index e3711a9..e3c098b 100644 --- a/opticstream/utils/matlab_execution.py +++ b/opticstream/utils/matlab_execution.py @@ -69,7 +69,13 @@ def run_matlab_batch_command_or_cli( """ logger = get_run_logger() resolved_path = resolve_matlab_root(matlab_script_path) - matlab_cmd = f"addpath(genpath('{resolved_path}'));{command}" + bundled_path = Path(__file__).resolve().parents[1] / "matlab" + root_literal = str(resolved_path).replace("'", "''") + bundled_literal = str(bundled_path).replace("'", "''") + matlab_cmd = ( + f"addpath(genpath('{root_literal}'));" + f"addpath('{bundled_literal}', '-begin');{command}" + ) logger.info(f"MATLAB command: {matlab_cmd}") if _is_matlab_engine_available(): import matlab.engine # type: ignore[import-not-found] diff --git a/pyproject.toml b/pyproject.toml index c174278..3535b8c 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -52,6 +52,9 @@ build-backend = "setuptools.build_meta" include = ["opticstream*"] exclude = ["notebooks*"] +[tool.setuptools.package-data] +opticstream = ["matlab/*.m", "matlab/+psoct/+spectral/*.m", "matlab/*.md"] + [tool.pytest.ini_options] addopts = '-m "not integration"' testpaths = ["tests"] diff --git a/tests/matlab/test_spectral_overlay.m b/tests/matlab/test_spectral_overlay.m new file mode 100644 index 0000000..bcef2dc --- /dev/null +++ b/tests/matlab/test_spectral_overlay.m @@ -0,0 +1,33 @@ +function test_spectral_overlay +% Run with the upstream toolbox and opticstream/matlab on the MATLAB path. +folder = tempname; +mkdir(folder); +cleanup = onCleanup(@() rmdir(folder, 's')); +for n = [1152 1153 2048] + file = fullfile(folder, 'disp.txt'); + fid = fopen(file, 'w'); + fprintf(fid, '0.8+0.6i\n'); + for k = 2:n + fprintf(fid, '0.8+0.6i\n'); + end + fclose(fid); + c = opticstream_read_dispersion(file, n); + assert(all(abs(c-(0.8+0.6i)) < 1e-12)); + rejected = false; + try + opticstream_read_dispersion(file, n+1); + catch ME + rejected = strcmp(ME.identifier, 'spectral2complex:BadDispersionLength'); + end + assert(rejected); + data = int16(randi([-100 100], n, 8, 2)); + input = fullfile(folder, 'input.nii'); + niftiwrite(data, input); + [a,b] = psoct.spectral.spectral2complex(input, ... + struct('dispCompFile', file, 'isRawFormat', false), struct()); + assert(isequal(size(a), [4 2 floor(n/2)-24])); + assert(isequal(size(a), size(b))); + assert(all(isfinite(a(:))) && all(isfinite(b(:)))); +end +disp('Spectral overlay tests passed'); +end From 9c717a8bd794708756418e782d47479a929c8ef6 Mon Sep 17 00:00:00 2001 From: NoahMarkowitz Date: Fri, 11 Sep 2026 16:21:02 -0400 Subject: [PATCH 10/65] matlab tile batch flow workings --- opticstream/config/psoct_scan_config.py | 2 +- opticstream/utils/matlab_execution.py | 6 ++++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/opticstream/config/psoct_scan_config.py b/opticstream/config/psoct_scan_config.py index df0f517..e25c9fe 100644 --- a/opticstream/config/psoct_scan_config.py +++ b/opticstream/config/psoct_scan_config.py @@ -194,7 +194,7 @@ class PSOCTProcessingParams(BaseModel): ) surface_spec: Optional[str] = Field( - default="gradient ", + default="gradient", description="Surface extraction spec string", ) matlab_num_workers: Optional[int] = Field( diff --git a/opticstream/utils/matlab_execution.py b/opticstream/utils/matlab_execution.py index e3c098b..8912b0e 100644 --- a/opticstream/utils/matlab_execution.py +++ b/opticstream/utils/matlab_execution.py @@ -56,7 +56,8 @@ def run_matlab_batch_command_or_cli( """ Run a MATLAB batch command via the Engine when available, else ``matlab -batch``. - Uses ``addpath(genpath(root));`` as preamble in both the engine and CLI paths. + Loads the toolbox and bundled overrides, then clears cached functions and + refreshes the MATLAB path in both the engine and CLI paths. Parameters ---------- @@ -74,7 +75,8 @@ def run_matlab_batch_command_or_cli( bundled_literal = str(bundled_path).replace("'", "''") matlab_cmd = ( f"addpath(genpath('{root_literal}'));" - f"addpath('{bundled_literal}', '-begin');{command}" + f"addpath('{bundled_literal}', '-begin');" + f"clear functions;rehash;{command}" ) logger.info(f"MATLAB command: {matlab_cmd}") if _is_matlab_engine_available(): From bbee95922de0bbc35f699d7403a1e33ccf049f87 Mon Sep 17 00:00:00 2001 From: NoahMarkowitz Date: Tue, 15 Sep 2026 14:19:53 -0400 Subject: [PATCH 11/65] fixes and updates --- docs/oct_input_naming.md | 47 +++++++++++++ opticstream/cli/oct/watch.py | 14 +++- opticstream/config/psoct_scan_config.py | 37 ++++++++++ opticstream/flows/lsm/strip_upload_flow.py | 2 + opticstream/flows/psoct/mosaic_upload_flow.py | 2 + .../flows/psoct/mosaic_volume_upload_flow.py | 2 + .../flows/psoct/tile_batch_upload_flow.py | 2 + .../flows/psoct/tile_file_reference.py | 16 +++++ opticstream/utils/oct_input_naming.py | 52 ++++++++++++++ opticstream/utils/upload_settings.py | 38 +++++++++++ tests/test_oct_input_naming.py | 67 +++++++++++++++++++ tests/test_upload_settings.py | 39 +++++++++++ 12 files changed, 317 insertions(+), 1 deletion(-) create mode 100644 docs/oct_input_naming.md create mode 100644 opticstream/utils/oct_input_naming.py create mode 100644 opticstream/utils/upload_settings.py create mode 100644 tests/test_oct_input_naming.py create mode 100644 tests/test_upload_settings.py diff --git a/docs/oct_input_naming.md b/docs/oct_input_naming.md new file mode 100644 index 0000000..c59a7cc --- /dev/null +++ b/docs/oct_input_naming.md @@ -0,0 +1,47 @@ +# Configurable OCT input filenames + +Edit the existing PSOCTScanConfig block's `acquisition` section after registering +the updated block schema. Restart the watcher after saving the block. +Omitting `filename_pattern` (or setting it to null) preserves legacy parsing. + +```json +{ + "filename_pattern": "sub-{subject}_sample-slice{slice}_chunk-{image}_acq-{acquisition}_{modality}{extension}", + "acquisition_mosaic_map": {"normal0deg": 1, "tilted15deg": 2} +} +``` + +This is a template, not a regular expression. Required placeholders are `slice`, +`image`, and `acquisition`. Optional placeholders are `subject`, `modality`, and +`extension`. Each may appear once; do not add format specifiers such as `:04d`. +Numeric fields accept zero padding. Matching is case-sensitive and covers the +entire basename. The watcher scans the selected directory, not recursively. + +For `sub-MF283_sample-slice037_chunk-0041_acq-normal0deg_spectral.nii`, +slice is 37, image is 41, and the mosaic slot is 1. With two mosaics per slice, +the global source mosaic is 73. The tilted15deg file maps to source mosaic 74. +Watcher mosaic-range filters use these global source IDs. Slice offsets retain +their existing behavior. Image numbers must be 1-based indices within a mosaic; +batch size remains `grid_size_y`, and incomplete batches are not dispatched. + +Acquisition labels are arbitrary: change the map to accept `normal5deg` or +another label. Values are mosaic slots, not angle measurements. Slot ordering +must agree with the project's existing two-/three-mosaic illumination layout. +The subject field is matched but does not select a project: do not mix subjects +with overlapping slice/tile IDs in the same watched directory. + +No `_spectral.nii` suffix is required. For example, use +`s{slice}_tile{image}_{acquisition}.nii` with +`filename_default_modality: "spectral"`. Or keep `{modality}{extension}` and +set `filename_modality_map` to `{"rawscan": "spectral"}` for `_rawscan.nii`. +The default map accepts spectral, complex, processed, aip, mip, ori, ret, surf, +and dbi. Unknown acquisition/modality labels are ignored. Duplicate files for +the same tile and modality cause an error rather than silently replacing data. + +The extension placeholder accepts `.nii`, `.nii.gz`, `.raw`, etc.; the actual +contents must still be supported by the configured reader and tile saving type. +Matching a name does not convert a file format. Files must still meet the +watcher's size/readability/stability requirements. + +Generated archive/processed/upload names are unchanged. Custom parsing applies +to input discovery and input references in both direct and event-driven flows. diff --git a/opticstream/cli/oct/watch.py b/opticstream/cli/oct/watch.py index a2cc37f..adc6d46 100644 --- a/opticstream/cli/oct/watch.py +++ b/opticstream/cli/oct/watch.py @@ -202,7 +202,7 @@ def discover_candidates(self) -> list[OCTBatchCandidate]: logger.debug("Scanning folder: %s", self.folder_path) - if self.scan_config.mosaics_per_slice == 3: + if self.scan_config.mosaics_per_slice == 3 and not getattr(self.scan_config.acquisition, "filename_pattern", None): candidates = self._discover_three_mosaic_candidates() else: candidates = self._discover_two_mosaic_candidates() @@ -302,6 +302,12 @@ def _discover_two_mosaic_files(self) -> list[ParsedTileFile]: continue parsed: ParsedTileFile | None = None + if getattr(self.scan_config.acquisition, "filename_pattern", None): + from opticstream.utils.oct_input_naming import parse_input_name + custom = parse_input_name(path.name, self.scan_config.acquisition, self.scan_config.mosaics_per_slice) + if custom is not None: + out.append(ParsedTileFile(path=path, source_mosaic_id=custom.source_mosaic_id, image_index=custom.image_index)) + continue for parser in ( self._parse_complex_file, self._parse_spectral_nii_file, @@ -475,6 +481,12 @@ def _parse_tile_nii_file(self, path: Path) -> ParsedTileFile | None: ) def _image_index_from_file(self, path: Path) -> int: + if getattr(self.scan_config.acquisition, "filename_pattern", None): + from opticstream.utils.oct_input_naming import parse_input_name + custom = parse_input_name(path.name, self.scan_config.acquisition, self.scan_config.mosaics_per_slice) + if custom is None: + raise ValueError(f"Filename does not match configured input naming: {path.name}") + return custom.image_index for parser in ( self._parse_complex_file, self._parse_spectral_nii_file, diff --git a/opticstream/config/psoct_scan_config.py b/opticstream/config/psoct_scan_config.py index e25c9fe..ac038f8 100644 --- a/opticstream/config/psoct_scan_config.py +++ b/opticstream/config/psoct_scan_config.py @@ -56,6 +56,43 @@ class PSOCTAcquisitionParams(BaseModel): """Physical / hardware facts about the acquisition.""" model_config = ConfigDict(extra="forbid", validate_assignment=True) + filename_pattern: Optional[str] = Field( + default=None, + description=( + "Optional full input filename template; null preserves legacy naming. " + "Example: sub-{subject}_sample-slice{slice}_chunk-{image}_acq-{acquisition}_{modality}{extension}. " + "slice037/chunk-0041/acq-normal0deg means slice 37, image 41, and the mosaic slot mapped from normal0deg. " + "Required placeholders: {slice}, {image}, {acquisition}; optional: {subject}, {modality}, {extension}. " + "Numbers accept zero padding; do not use :04d format specifiers. Literals and labels are case-sensitive. " + "Suffixes/extensions may be literals or placeholders; matching an extension does not add support for its file format." + ), + ) + acquisition_mosaic_map: Dict[str, int] = Field( + default_factory=lambda: {"normal0deg": 1, "tilted15deg": 2}, + description="Exact acquisition labels mapped to 1-based mosaic slots within each slice. Edit angles freely, e.g. normal5deg: 1. Slot 1 is normal; remaining slots follow the project's existing mosaic ordering. Source mosaic = (slice - 1) * mosaics_per_slice + slot.", + ) + filename_default_modality: str = Field( + default="spectral", description="Modality label when filename_pattern omits {modality}, including patterns with a literal suffix.", + ) + filename_modality_map: Dict[str, Literal["spectral", "complex", "processed", "aip", "mip", "ori", "ret", "surf", "dbi"]] = Field( + default_factory=lambda: {key: key for key in ("spectral", "complex", "processed", "aip", "mip", "ori", "ret", "surf", "dbi")}, + description="Map filename modality labels to processing types; e.g. rawscan: spectral. Unknown labels are ignored. No fixed _spectral.nii suffix is required.", + ) + + @field_validator("filename_pattern") + @classmethod + def validate_filename_pattern(cls, value): + if value is not None: + from opticstream.utils.oct_input_naming import compile_pattern + compile_pattern(value) + return value + + @field_validator("acquisition_mosaic_map") + @classmethod + def validate_acquisition_mosaic_map(cls, value): + if any(not label or slot < 1 for label, slot in value.items()): + raise ValueError("Acquisition labels must be nonempty and mosaic slots positive.") + return value grid_size_x_normal: int = Field( ..., ge=1, diff --git a/opticstream/flows/lsm/strip_upload_flow.py b/opticstream/flows/lsm/strip_upload_flow.py index a9e5181..1a4cabf 100644 --- a/opticstream/flows/lsm/strip_upload_flow.py +++ b/opticstream/flows/lsm/strip_upload_flow.py @@ -24,6 +24,7 @@ from opticstream.state.lsm_project_state import LSMStripId from opticstream.tasks.dandi_upload import upload_to_dandi from opticstream.hooks.slack_notification_hook import slack_notification_hook +from opticstream.utils.upload_settings import upload_flow_enabled @flow( @@ -31,6 +32,7 @@ on_completion=[publish_lsm_slice_hook, publish_lsm_project_hook], on_failure=[slack_notification_hook], ) +@upload_flow_enabled @strip_processing_milestone(field_name="uploaded", success_event=STRIP_UPLOADED) def upload_strip_to_dandi_flow( strip_ident: LSMStripId, diff --git a/opticstream/flows/psoct/mosaic_upload_flow.py b/opticstream/flows/psoct/mosaic_upload_flow.py index 7e2fcd9..6d5a6e1 100644 --- a/opticstream/flows/psoct/mosaic_upload_flow.py +++ b/opticstream/flows/psoct/mosaic_upload_flow.py @@ -19,6 +19,7 @@ from opticstream.state.state_guards import force_rerun_from_payload from opticstream.tasks.dandi_upload import upload_to_dandi_batch from opticstream.hooks.slack_notification_hook import slack_notification_hook +from opticstream.utils.upload_settings import upload_flow_enabled @flow( @@ -26,6 +27,7 @@ on_completion=[publish_oct_mosaic_hook, publish_oct_project_hook], on_failure=[slack_notification_hook], ) +@upload_flow_enabled @oct_mosaic_processing_milestone( field_name="enface_uploaded", success_event=MOSAIC_ENFACE_UPLOADED ) diff --git a/opticstream/flows/psoct/mosaic_volume_upload_flow.py b/opticstream/flows/psoct/mosaic_volume_upload_flow.py index ab080b9..6ded8d2 100644 --- a/opticstream/flows/psoct/mosaic_volume_upload_flow.py +++ b/opticstream/flows/psoct/mosaic_volume_upload_flow.py @@ -23,6 +23,7 @@ from opticstream.state.state_guards import force_rerun_from_payload from opticstream.tasks.dandi_upload import upload_to_dandi_batch from opticstream.hooks.slack_notification_hook import slack_notification_hook +from opticstream.utils.upload_settings import upload_flow_enabled @flow( @@ -30,6 +31,7 @@ on_completion=[publish_oct_mosaic_hook, publish_oct_project_hook], on_failure=[slack_notification_hook], ) +@upload_flow_enabled @oct_mosaic_processing_milestone( field_name="volume_uploaded", success_event=MOSAIC_VOLUME_UPLOADED ) diff --git a/opticstream/flows/psoct/tile_batch_upload_flow.py b/opticstream/flows/psoct/tile_batch_upload_flow.py index f86f4c8..76c7fdd 100644 --- a/opticstream/flows/psoct/tile_batch_upload_flow.py +++ b/opticstream/flows/psoct/tile_batch_upload_flow.py @@ -20,6 +20,7 @@ from opticstream.state.state_guards import force_rerun_from_payload from opticstream.tasks.dandi_upload import upload_to_dandi_batch from opticstream.hooks.slack_notification_hook import slack_notification_hook +from opticstream.utils.upload_settings import upload_flow_enabled @flow( @@ -27,6 +28,7 @@ on_completion=[publish_oct_mosaic_hook, publish_oct_project_hook], on_failure=[slack_notification_hook], ) +@upload_flow_enabled @oct_batch_processing_milestone(field_name="uploaded", success_event=BATCH_UPLOADED) def upload_to_dandi_tile_batch( batch_id: OCTBatchId, diff --git a/opticstream/flows/psoct/tile_file_reference.py b/opticstream/flows/psoct/tile_file_reference.py index cc3195d..5f723c7 100644 --- a/opticstream/flows/psoct/tile_file_reference.py +++ b/opticstream/flows/psoct/tile_file_reference.py @@ -44,6 +44,22 @@ def build_tile_file_reference_list( grid_size_x = mosaic_context.grid_size_x(config) refs: dict[int, TileFileReference] = defaultdict(TileFileReference) for p in file_list: + if config.acquisition.filename_pattern: + from opticstream.utils.oct_input_naming import parse_input_name + parsed = parse_input_name(p.name, config.acquisition, mosaics_per_slice) + if parsed is None: + raise ValueError(f"Filename does not match configured input naming: {p.name}") + tile_number = parsed.image_index + modality = parsed.modality + if modality == "processed": + modality = "complex" if config.acquisition.tile_saving_type in (TileSavingType.COMPLEX_WITH_SPECTRAL, TileSavingType.COMPLEX) else "dbi" + field = f"{modality}_file_path" + ref = refs[tile_number] + if getattr(ref, field) is not None: + raise ValueError(f"Duplicate {modality} input for tile {tile_number}: {p}") + ref.tile_number = tile_number + setattr(ref, field, p) + continue if mosaics_per_slice == 2: tile_number = extract_tile_number_from_filename(str(p)) else: diff --git a/opticstream/utils/oct_input_naming.py b/opticstream/utils/oct_input_naming.py new file mode 100644 index 0000000..f34d1ee --- /dev/null +++ b/opticstream/utils/oct_input_naming.py @@ -0,0 +1,52 @@ +"""Configurable input names, independent of generated output names.""" +import re +from functools import lru_cache +from string import Formatter +from dataclasses import dataclass + + +@lru_cache(maxsize=64) +def compile_pattern(pattern): + fields = set() + parts = [] + for literal, field, spec, conversion in Formatter().parse(pattern): + parts.append(re.escape(literal)) + if field is None: + continue + if field not in {"subject", "slice", "image", "acquisition", "modality", "extension"}: + raise ValueError(f"Unknown filename placeholder: {field}") + if field in fields or spec or conversion: + raise ValueError("Filename placeholders must be unique and have no format specifiers.") + fields.add(field) + value = r"[0-9]+" if field in {"slice", "image"} else (r"\.[A-Za-z0-9.]+" if field == "extension" else r"[^/\\]+?") + parts.append(f"(?P<{field}>{value})") + if not {"slice", "image", "acquisition"} <= fields: + raise ValueError("filename_pattern requires {slice}, {image}, and {acquisition}.") + return re.compile("".join(parts)) + + +@dataclass(frozen=True) +class InputTile: + source_mosaic_id: int + image_index: int + modality: str + + +def parse_input_name(name, acquisition, mosaics_per_slice): + match = compile_pattern(acquisition.filename_pattern).fullmatch(name) + if match is None: + return None + values = match.groupdict() + slot = acquisition.acquisition_mosaic_map.get(values["acquisition"]) + if slot is None: + return None + if not 1 <= slot <= mosaics_per_slice: + raise ValueError("acquisition_mosaic_map values must fit mosaics_per_slice.") + slice_id, image = int(values["slice"]), int(values["image"]) + if slice_id < 1 or image < 1: + raise ValueError("Filename slice and image numbers must be positive.") + label = values.get("modality", acquisition.filename_default_modality) + modality = acquisition.filename_modality_map.get(label) + if modality is None: + return None + return InputTile((slice_id - 1) * mosaics_per_slice + slot, image, modality) diff --git a/opticstream/utils/upload_settings.py b/opticstream/utils/upload_settings.py new file mode 100644 index 0000000..bd00e46 --- /dev/null +++ b/opticstream/utils/upload_settings.py @@ -0,0 +1,38 @@ +"""Live Prefect switches for destination-specific upload flows.""" + +from functools import wraps +from inspect import signature + +from prefect.logging.loggers import get_logger +from prefect.variables import Variable + + +def uploads_enabled(instance: str) -> bool: + """Missing switches preserve existing behavior; only JSON booleans are valid.""" + if instance not in ("linc", "dandi"): + return True + name = f"{instance}-uploads-enabled" + enabled = Variable.get(name, default=True) + if not isinstance(enabled, bool): + raise ValueError(f"{name} must be a JSON boolean (true or false).") + return enabled + + +def upload_flow_enabled(func): + """Place outside milestone decorators to avoid recording skipped uploads.""" + sig = signature(func) + + @wraps(func) + def wrapper(*args, **kwargs): + bound = sig.bind(*args, **kwargs) + bound.apply_defaults() + instance = bound.arguments["dandi_instance"] + if not uploads_enabled(instance): + get_logger(__name__).info( + "%s uploads disabled; skipping %s without marking uploaded.", + instance, func.__name__, + ) + return None + return func(*args, **kwargs) + + return wrapper diff --git a/tests/test_oct_input_naming.py b/tests/test_oct_input_naming.py new file mode 100644 index 0000000..d28fa18 --- /dev/null +++ b/tests/test_oct_input_naming.py @@ -0,0 +1,67 @@ +import unittest +from pathlib import Path +from tempfile import TemporaryDirectory +from types import SimpleNamespace + +from opticstream.config.psoct_scan_config import PSOCTAcquisitionParams +from opticstream.utils.oct_input_naming import parse_input_name +from opticstream.flows.psoct.tile_file_reference import build_tile_file_reference_list +from opticstream.cli.oct.watch import OCTWatcherService + + +PATTERN = "sub-{subject}_sample-slice{slice}_chunk-{image}_acq-{acquisition}_{modality}{extension}" + + +class InputNamingTests(unittest.TestCase): + def acquisition(self, **kwargs): + return PSOCTAcquisitionParams(grid_size_x_normal=50, grid_size_x_tilted=50, + grid_size_y=1, **kwargs) + + def test_examples_and_downstream(self): + acq = self.acquisition(filename_pattern=PATTERN) + config = SimpleNamespace(acquisition=acq, mosaics_per_slice=2) + context = SimpleNamespace(grid_size_x=lambda cfg: 50) + for tile, label, mosaic in [(41, "normal0deg", 73), (50, "normal0deg", 73), (50, "tilted15deg", 74)]: + path = Path(f"sub-MF283_sample-slice037_chunk-{tile:04d}_acq-{label}_spectral.nii") + parsed = parse_input_name(path.name, acq, 2) + self.assertEqual((parsed.source_mosaic_id, parsed.image_index), (mosaic, tile)) + refs = build_tile_file_reference_list([path], config=config, mosaic_context=context) + self.assertEqual(refs[tile].spectral_file_path, path) + + def test_custom_suffix_and_angle(self): + acq = self.acquisition(filename_pattern=PATTERN, acquisition_mosaic_map={"normal7deg": 1}, + filename_modality_map={"rawscan": "spectral"}) + parsed = parse_input_name("sub-X_sample-slice001_chunk-0001_acq-normal7deg_rawscan.nii.gz", acq, 2) + self.assertEqual(parsed.modality, "spectral") + self.assertIsNone(parse_input_name("unrelated.txt", acq, 2)) + + def test_literal_suffix(self): + acq = self.acquisition(filename_pattern="s{slice}_i{image}_{acquisition}.nii") + self.assertEqual(parse_input_name("s1_i2_normal0deg.nii", acq, 2).modality, "spectral") + + def test_validation_and_legacy_default(self): + self.assertIsNone(self.acquisition().filename_pattern) + for pattern in ("{image}", "{slice}_{image}_{acquisition}_{unknown}", "{slice}_{image}_{image}_{acquisition}"): + with self.assertRaises(ValueError): + self.acquisition(filename_pattern=pattern) + + def test_watcher_discovery(self): + for pattern, name, mosaic in [(PATTERN, "sub-X_sample-slice037_chunk-0041_acq-normal0deg_spectral.nii", 73), + (None, "mosaic_001_image_0041_spectral_0041.nii", 1)]: + with TemporaryDirectory() as folder: + path = Path(folder) / name + path.write_bytes(b"\0" * (100 * 1024)) + watcher = OCTWatcherService(project_name="test", folder_path=Path(folder), + project_base_path=folder, mosaic_ranges=[(1, 100)], slice_offset=0, + batch_size=1, scan_config=SimpleNamespace(acquisition=self.acquisition(filename_pattern=pattern), mosaics_per_slice=2), + direct=True, force_resend=False) + files = watcher._discover_two_mosaic_files() + self.assertEqual(len(files), 1) + self.assertEqual((files[0].source_mosaic_id, files[0].image_index), (mosaic, 41)) + candidates = watcher.discover_candidates() + self.assertEqual(len(candidates), 1) + self.assertEqual(candidates[0].source_mosaic_id, mosaic) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_upload_settings.py b/tests/test_upload_settings.py new file mode 100644 index 0000000..8908ad5 --- /dev/null +++ b/tests/test_upload_settings.py @@ -0,0 +1,39 @@ +import unittest +from unittest.mock import Mock, patch + +from opticstream.utils.upload_settings import upload_flow_enabled, uploads_enabled + + +class UploadSettingsTests(unittest.TestCase): + @patch("opticstream.utils.upload_settings.Variable.get") + def test_destinations_and_default(self, get): + get.return_value = True + for instance in ("linc", "dandi"): + self.assertTrue(uploads_enabled(instance)) + get.assert_called_with(f"{instance}-uploads-enabled", default=True) + + @patch("opticstream.utils.upload_settings.Variable.get", return_value="false") + def test_reject_string(self, get): + with self.assertRaises(ValueError): + uploads_enabled("dandi") + + @patch("opticstream.utils.upload_settings.Variable.get") + def test_live_toggle_skips_wrapped_milestone(self, get): + milestone = Mock() + + @upload_flow_enabled + def flow(dandi_instance="linc"): + milestone() + return "uploaded" + + get.return_value = False + self.assertIsNone(flow()) + milestone.assert_not_called() + get.return_value = True + self.assertEqual(flow("dandi"), "uploaded") + milestone.assert_called_once() + get.assert_called_with("dandi-uploads-enabled", default=True) + + +if __name__ == "__main__": + unittest.main() From d2e27605c668d7653b747060b5d29ecab5b429a6 Mon Sep 17 00:00:00 2001 From: Noah Markowitz Date: Thu, 17 Sep 2026 15:46:58 -0400 Subject: [PATCH 12/65] dispersion takes multiple channels --- .../psoct_recon/spectral2complex.py | 34 ++++++++++++++++--- .../+psoct/+spectral/spectral2complex.m | 9 ++--- opticstream/matlab/README.md | 4 +-- .../matlab/opticstream_read_dispersion.m | 17 ++++++---- tests/matlab/test_spectral_overlay.m | 11 +++--- tests/test_dispersion_channels.py | 34 +++++++++++++++++++ 6 files changed, 86 insertions(+), 23 deletions(-) create mode 100644 tests/test_dispersion_channels.py diff --git a/opticstream/data_processing/psoct_recon/spectral2complex.py b/opticstream/data_processing/psoct_recon/spectral2complex.py index deba936..27350ba 100644 --- a/opticstream/data_processing/psoct_recon/spectral2complex.py +++ b/opticstream/data_processing/psoct_recon/spectral2complex.py @@ -44,6 +44,24 @@ def read_spectral_file_raw(filename, header_bytes=352): return np.frombuffer(raw, dtype=np.uint16) +def _load_dispersion_channels(filename, samples_per_channel): + """Load two consecutive float64 phase vectors from one binary file.""" + phase_dispersion = np.fromfile(filename, dtype=np.float64) + expected_values = 2 * samples_per_channel + if phase_dispersion.size != expected_values: + raise ValueError( + f"Dispersion file {filename!s} has {phase_dispersion.size} values; " + f"expected {expected_values} ({samples_per_channel} per channel)." + ) + if not np.isfinite(phase_dispersion).all(): + raise ValueError(f"Dispersion file {filename!s} contains non-finite values.") + + return ( + phase_dispersion[:samples_per_channel], + phase_dispersion[samples_per_channel:], + ) + + def save_jstack_nifti(Jstack_all, output_file): """ Save Jstack_all to a NIfTI file (float32). @@ -155,7 +173,9 @@ def spectral2complex( Input: - spectral_array: MUST be shaped as (AlineLength, Aline, 2, Bline) (dtype can be uint16 or numeric; will be cast to float64) - - disp_comp_file: optional binary float64 dispersion correction file path (used for both channels) + - disp_comp_file: optional binary float64 dispersion correction file path. + The first AlineLength values apply to channel 1 and + the second AlineLength values apply to channel 2. - AlineLength, AutoCorrPeakCut, PaddingFactor: processing parameters (kept for compatibility) Output: - Jstack_all: numpy array shaped (4*Aline, Bline, Depth) @@ -200,10 +220,11 @@ def spectral2complex( ) newLen = InterpolatedWavelengths2.shape[0] - # Load dispersion correction if provided (same for both channels) + # Load the channel-specific dispersion corrections. if disp_comp_file is not None: - phaseDispersion = np.fromfile(disp_comp_file, dtype=np.float64) - phaseDispersion1 = phaseDispersion2 = phaseDispersion + phaseDispersion1, phaseDispersion2 = _load_dispersion_channels( + disp_comp_file, AlineLength + ) else: phaseDispersion1 = phaseDispersion2 = np.zeros(PaddingLength, dtype=np.float64) @@ -357,7 +378,10 @@ def parse_args(): p.add_argument( "--disp_comp", default=None, - help="Optional dispersion correction binary float64 file (applied to both channels).", + help=( + "Optional dispersion correction binary float64 file; the first half " + "applies to channel 1 and the second half to channel 2." + ), ) p.add_argument( "--save", action="store_true", help="If set, save output NIfTI to --output" diff --git a/opticstream/matlab/+psoct/+spectral/spectral2complex.m b/opticstream/matlab/+psoct/+spectral/spectral2complex.m index 44ca58d..0121333 100644 --- a/opticstream/matlab/+psoct/+spectral/spectral2complex.m +++ b/opticstream/matlab/+psoct/+spectral/spectral2complex.m @@ -116,12 +116,9 @@ params.Wavelengths_r = Wavelengths_r; params.InterpolatedWavelengths = InterpolatedWavelengths2; -% Read dispersion correction file(s) -dispCompFile1 = dispCompFile; -dispCompFile2 = dispCompFile; - -phaseCorrection1 = opticstream_read_dispersion(dispCompFile1, AlineLength); -phaseCorrection2 = opticstream_read_dispersion(dispCompFile2, AlineLength); +% Read the channel-specific corrections from the two halves of one file. +[phaseCorrection1, phaseCorrection2] = ... + opticstream_read_dispersion(dispCompFile, AlineLength); % Replicate along A-line dimension to match interpolated buffer size phaseCorrection1 = repmat(phaseCorrection1, 1, Aline); diff --git a/opticstream/matlab/README.md b/opticstream/matlab/README.md index d077e11..310bd40 100644 --- a/opticstream/matlab/README.md +++ b/opticstream/matlab/README.md @@ -15,9 +15,9 @@ Dispersion formats: columns, or one complex multiplier per row (e.g. 0.98+0.12i). - Other extensions: native-endian binary float64 phase angles. -The file must contain exactly one finite coefficient per spectral sample. +The file must contain exactly two finite coefficients per spectral sample: +the first half applies to channel 1 and the second half applies to channel 2. Complex multipliers are applied directly; phase angles use exp(-1i*phase). -The same correction is used for both channels, as in the upstream reader. No coefficients are silently truncated, padded or recalibrated. The legacy wavelength calibration and channel-2 reversal remain in use; diff --git a/opticstream/matlab/opticstream_read_dispersion.m b/opticstream/matlab/opticstream_read_dispersion.m index 4198fa1..9d25ad6 100644 --- a/opticstream/matlab/opticstream_read_dispersion.m +++ b/opticstream/matlab/opticstream_read_dispersion.m @@ -1,6 +1,7 @@ -function correction = opticstream_read_dispersion(filename, spectra) -% Text: N complex rows, N-by-2 real/imaginary pairs, or N phase angles. -% Binary (.dat/.bin): N native-endian float64 phase angles, legacy convention. +function [correction1, correction2] = opticstream_read_dispersion(filename, spectra) +% Text: 2N complex rows, 2N-by-2 real/imaginary pairs, or 2N phase angles. +% Binary (.dat/.bin): 2N native-endian float64 phase angles, legacy convention. +% The first N coefficients apply to channel 1; the second N apply to channel 2. % A complex pair counts as ONE spectral coefficient. [~,~,ext] = fileparts(filename); if any(strcmpi(ext, {'.txt', '.csv', '.tsv'})) @@ -36,10 +37,14 @@ end correction = exp(-1i .* fread(fid, inf, 'double')); end -if numel(correction) ~= spectra || any(~isfinite(correction(:))) +expectedCoefficients = 2 * spectra; +if numel(correction) ~= expectedCoefficients || any(~isfinite(correction(:))) error('spectral2complex:BadDispersionLength', ... - 'Dispersion file "%s" has %d coefficients; NIfTI requires exactly %d finite coefficients.', ... - filename, numel(correction), spectra); + ['Dispersion file "%s" has %d coefficients; NIfTI requires exactly %d finite ' ... + 'coefficients (%d per channel).'], ... + filename, numel(correction), expectedCoefficients, spectra); end correction = correction(:); +correction1 = correction(1:spectra); +correction2 = correction(spectra+1:end); end diff --git a/tests/matlab/test_spectral_overlay.m b/tests/matlab/test_spectral_overlay.m index bcef2dc..61dd270 100644 --- a/tests/matlab/test_spectral_overlay.m +++ b/tests/matlab/test_spectral_overlay.m @@ -6,13 +6,16 @@ for n = [1152 1153 2048] file = fullfile(folder, 'disp.txt'); fid = fopen(file, 'w'); - fprintf(fid, '0.8+0.6i\n'); - for k = 2:n + for k = 1:n fprintf(fid, '0.8+0.6i\n'); end + for k = 1:n + fprintf(fid, '0.6+0.8i\n'); + end fclose(fid); - c = opticstream_read_dispersion(file, n); - assert(all(abs(c-(0.8+0.6i)) < 1e-12)); + [c1,c2] = opticstream_read_dispersion(file, n); + assert(all(abs(c1-(0.8+0.6i)) < 1e-12)); + assert(all(abs(c2-(0.6+0.8i)) < 1e-12)); rejected = false; try opticstream_read_dispersion(file, n+1); diff --git a/tests/test_dispersion_channels.py b/tests/test_dispersion_channels.py new file mode 100644 index 0000000..933fc76 --- /dev/null +++ b/tests/test_dispersion_channels.py @@ -0,0 +1,34 @@ +import numpy as np +import pytest + +from opticstream.data_processing.psoct_recon.spectral2complex import ( + _load_dispersion_channels, +) + + +def test_load_dispersion_channels_splits_file_in_half(tmp_path) -> None: + channel_1 = np.array([0.1, 0.2, 0.3], dtype=np.float64) + channel_2 = np.array([1.1, 1.2, 1.3], dtype=np.float64) + path = tmp_path / "dispersion.dat" + np.concatenate((channel_1, channel_2)).tofile(path) + + actual_1, actual_2 = _load_dispersion_channels(path, samples_per_channel=3) + + np.testing.assert_array_equal(actual_1, channel_1) + np.testing.assert_array_equal(actual_2, channel_2) + + +def test_load_dispersion_channels_rejects_wrong_length(tmp_path) -> None: + path = tmp_path / "dispersion.dat" + np.arange(5, dtype=np.float64).tofile(path) + + with pytest.raises(ValueError, match=r"expected 6 \(3 per channel\)"): + _load_dispersion_channels(path, samples_per_channel=3) + + +def test_load_dispersion_channels_rejects_non_finite_values(tmp_path) -> None: + path = tmp_path / "dispersion.dat" + np.array([0.1, 0.2, np.nan, 1.1, 1.2, 1.3], dtype=np.float64).tofile(path) + + with pytest.raises(ValueError, match="contains non-finite values"): + _load_dispersion_channels(path, samples_per_channel=3) From fad9aeaec08f9c9f6b0f0aa9e5e6bba871f0208e Mon Sep 17 00:00:00 2001 From: NoahMarkowitz Date: Fri, 18 Sep 2026 13:39:21 -0400 Subject: [PATCH 13/65] update PSOCTScanConfig blocks --- docs/matlab_processing_toggle.md | 54 +++++++++++++ opticstream/config/migrate_psoct_blocks.py | 78 +++++++++++++++++++ opticstream/config/psoct_scan_config.py | 10 +++ opticstream/flows/psoct/slice_process_flow.py | 2 + .../flows/psoct/tile_batch_process_flow.py | 2 + opticstream/hooks/check_mosaic_ready_hook.py | 3 + opticstream/utils/matlab_settings.py | 37 +++++++++ tests/test_matlab_settings.py | 69 ++++++++++++++++ tests/test_migrate_psoct_blocks.py | 51 ++++++++++++ 9 files changed, 306 insertions(+) create mode 100644 docs/matlab_processing_toggle.md create mode 100644 opticstream/config/migrate_psoct_blocks.py create mode 100644 opticstream/utils/matlab_settings.py create mode 100644 tests/test_matlab_settings.py create mode 100644 tests/test_migrate_psoct_blocks.py diff --git a/docs/matlab_processing_toggle.md b/docs/matlab_processing_toggle.md new file mode 100644 index 0000000..4c9cb3f --- /dev/null +++ b/docs/matlab_processing_toggle.md @@ -0,0 +1,54 @@ +# Per-project MATLAB processing toggle + +Each PSOCTScanConfig block has a top-level boolean `matlab_processing_enabled`. +It defaults to `true`, including for existing saved configurations. + +Set it to `false` to skip `process_tile_batch` (both spectral and complex input) +and `register_slice_flow`, including their event-driven entry points. Skips appear +as `MatlabDisabled` completed flow states, without changing processing milestones +or emitting processing-success/readiness events. Force-rerun does not override it. + +The entire tile-batch flow is skipped, including its embedded archiving step. +Standalone archiving/upload flows, Python/Fiji mosaic stitching and QC are not +disabled. This is not an upload toggle and does not stop already-running MATLAB +sessions. Low-level tasks called directly outside these flows are not gated. + +Tile flows use the config passed to the run. Registration loads the project's saved +block at entry. Restart watchers after editing the block because they hold a +loaded config; existing scheduled runs with serialized configs can retain old values. +When enabling processing again, manually rerun skipped batches if watcher state +already exists; enabling the field does not automatically replay events. + +## Update an existing block + +Restart serving processes after installing this code. Registering the schema alone +does not migrate existing block documents. In Miniforge Prompt, using the correct +Prefect API configuration, run (replace the example block name): + +```cmd +"C:\Users\Ayman\Documents\opticstream_nm\opticstream\.venv\Scripts\python.exe" -c "from opticstream.config.psoct_scan_config import PSOCTScanConfig; PSOCTScanConfig.register_type_and_schema(); b = PSOCTScanConfig.load('human-10um-psoct-config'); b.matlab_processing_enabled = False; b.save('human-10um-psoct-config', overwrite=True)" +``` + +This updates only that block, preserving its other validated fields. Fix any +pre-existing validation errors first. Refresh the block editor to see the field. +Use `True` to re-enable. No global Prefect Variable is used. + +## Refresh every PSOCT block after additive schema changes + +Use the installed code version and the Prefect API/profile for your dashboard: + +```cmd +".venv\Scripts\python.exe" -m opticstream.config.migrate_psoct_blocks +".venv\Scripts\python.exe" -m opticstream.config.migrate_psoct_blocks --apply +``` + +The first command only validates. The second registers the current schema and +resaves all named PSOCTScanConfig blocks, retaining existing values and filling +new fields with their defaults. It does not set every MATLAB toggle to false. +All blocks must validate before any are saved. Secret values are not printed. +Writes are sequential, not transactional; a save failure reports partial progress. +Pause block editing and preferably processing during migration; refresh the UI +and restart consumers afterward. This is an explicit deployment step, not an +automatic action during imports or watcher startup. Renamed/removed fields or new +required fields without defaults need a dedicated data migration first; this tool +is intended for backward-compatible additive changes. diff --git a/opticstream/config/migrate_psoct_blocks.py b/opticstream/config/migrate_psoct_blocks.py new file mode 100644 index 0000000..b51370c --- /dev/null +++ b/opticstream/config/migrate_psoct_blocks.py @@ -0,0 +1,78 @@ +"""Refresh saved PSOCT schemas: python -m opticstream.config.migrate_psoct_blocks.""" + +import argparse + +from prefect.client.orchestration import get_client + +from opticstream.config.psoct_scan_config import PSOCTScanConfig + + +def migrate_blocks(*, apply=False, client=None, block_class=PSOCTScanConfig): + """Validate all named blocks before writing; never print block values/secrets. + + This is an additive-schema migration, not a transactional server operation. + Pause block editing while applying; saves overwrite each document individually. + """ + if client is None: + with get_client(sync_client=True) as active_client: + return migrate_blocks(apply=apply, client=active_client, block_class=block_class) + + names = set() + offset = 0 + while True: + documents = client.read_block_documents( + offset=offset, limit=100, include_secrets=False, + ) + if not documents: + break + for document in documents: + if (document.block_type.slug == block_class.get_block_type_slug() + and document.name and not document.is_anonymous): + names.add(document.name) + offset += len(documents) + + blocks = [] + failed = False + for name in sorted(names): + try: + # Load normally to retain nested Secret references and apply defaults. + block = block_class.load(name) + except Exception as exc: + # Exception messages from validation can include secret input values. + print(f"INVALID: {name} ({type(exc).__name__}); inspect this block privately.") + failed = True + else: + blocks.append((name, block)) + print(f"VALID: {name}") + if failed: + print("Aborted: no blocks saved. Correct invalid blocks and retry.") + return 1 + if not apply: + print(f"Dry run: {len(blocks)} block(s) validated. Use --apply to update schemas.") + return 0 + if not blocks: + print("No matching named blocks found.") + return 0 + + block_class.register_type_and_schema() + for index, (name, block) in enumerate(blocks): + try: + block.save(name, overwrite=True) + except Exception as exc: + print(f"SAVE FAILED: {name} ({type(exc).__name__}). " + f"{index} earlier block(s) updated; remaining blocks not attempted. Retry after fixing.") + return 1 + print(f"UPDATED: {name}") + print(f"Updated {len(blocks)} block(s). Refresh the dashboard and restart consumers.") + return 0 + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--apply", action="store_true", help="Save all validated blocks; default is dry-run.") + args = parser.parse_args() + return migrate_blocks(apply=args.apply) + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/opticstream/config/psoct_scan_config.py b/opticstream/config/psoct_scan_config.py index ac038f8..0302220 100644 --- a/opticstream/config/psoct_scan_config.py +++ b/opticstream/config/psoct_scan_config.py @@ -273,6 +273,16 @@ class PSOCTScanConfigModel(BaseModel): description="Base filesystem path for project data. All intermediate and output files should be stored under this path.", ) + matlab_processing_enabled: bool = Field( + default=True, + description=( + "Enable MATLAB-based tile-batch processing and slice registration for this block. " + "When false, these flows skip before processing, archiving within the tile flow, " + "or updating processing milestones. Standalone archive/upload and non-MATLAB " + "flows are unaffected. Does not stop already-running MATLAB sessions." + ), + ) + mosaics_per_slice: Literal[2, 3] = Field( default=2, ge=1, diff --git a/opticstream/flows/psoct/slice_process_flow.py b/opticstream/flows/psoct/slice_process_flow.py index e743594..51c2437 100644 --- a/opticstream/flows/psoct/slice_process_flow.py +++ b/opticstream/flows/psoct/slice_process_flow.py @@ -23,6 +23,7 @@ from opticstream.events.psoct_event_emitters import emit_slice_psoct_event from opticstream.state.oct_project_state import OCTSliceId, OCT_STATE_SERVICE from opticstream.utils.matlab_execution import run_matlab_batch_command_or_cli +from opticstream.utils.matlab_settings import matlab_flow_enabled from opticstream.flows.psoct.utils import get_slice_paths @@ -164,6 +165,7 @@ def thruplane_from_files_task( flow_run_name="{project_name}-slice-{slice_id}-register", on_completion=[publish_oct_project_hook], ) +@matlab_flow_enabled def register_slice_flow( project_name: str, project_base_path: str, diff --git a/opticstream/flows/psoct/tile_batch_process_flow.py b/opticstream/flows/psoct/tile_batch_process_flow.py index 6457218..925df21 100644 --- a/opticstream/flows/psoct/tile_batch_process_flow.py +++ b/opticstream/flows/psoct/tile_batch_process_flow.py @@ -37,6 +37,7 @@ should_skip_run, ) from opticstream.utils.matlab_execution import run_matlab_batch_command_or_cli +from opticstream.utils.matlab_settings import matlab_flow_enabled from psoct_toolbox.matlab_bridge import ( build_complex2processed_batch_indexed_command, @@ -200,6 +201,7 @@ def split_channel_data( on_completion=[publish_oct_mosaic_hook, publish_oct_project_hook, check_mosaic_ready_hook], on_failure=[slack_notification_hook], ) +@matlab_flow_enabled @oct_batch_processing_milestone( field_name="enface_processed", success_event=BATCH_PROCESSED ) diff --git a/opticstream/hooks/check_mosaic_ready_hook.py b/opticstream/hooks/check_mosaic_ready_hook.py index 8e9ab0f..d8accde 100644 --- a/opticstream/hooks/check_mosaic_ready_hook.py +++ b/opticstream/hooks/check_mosaic_ready_hook.py @@ -7,6 +7,7 @@ from prefect.logging.loggers import flow_run_logger from opticstream.config.psoct_scan_config import get_psoct_scan_config +from opticstream.utils.matlab_settings import MATLAB_DISABLED_STATE from opticstream.events.psoct_event_emitters import emit_mosaic_psoct_event from opticstream.events.psoct_events import MOSAIC_READY from opticstream.flows.psoct.utils import mosaic_context_from_ident @@ -28,6 +29,8 @@ def check_mosaic_ready_hook(flow: Any, flow_run: Any, state: Any) -> None: run name, loads the scan config, computes the expected batch count, and checks the mosaic state. """ + if getattr(state, "name", None) == MATLAB_DISABLED_STATE: + return logger = flow_run_logger(flow_run, flow) parsed = parse_flow_run_name_fields(flow_run.name or "") missing = missing_required_fields(parsed, _REQUIRED_FIELDS) diff --git a/opticstream/utils/matlab_settings.py b/opticstream/utils/matlab_settings.py new file mode 100644 index 0000000..7ba128f --- /dev/null +++ b/opticstream/utils/matlab_settings.py @@ -0,0 +1,37 @@ +"""Per-scan-config gate, applied outside processing milestone decorators.""" + +from functools import wraps +from inspect import signature + +from prefect import get_run_logger +from prefect.states import Completed + +from opticstream.config.psoct_scan_config import get_psoct_scan_config + + +MATLAB_DISABLED_STATE = "MatlabDisabled" + + +def matlab_flow_enabled(func): + """Skip a MATLAB flow before its body/milestones, preserving its signature. + + Tile flows use their explicit config (including manual-run overrides). + Registration flows resolve the project's block because they accept no config. + Fail closed if that block cannot be loaded instead of silently running MATLAB. + """ + sig = signature(func) + + @wraps(func) + def wrapper(*args, **kwargs): + bound = sig.bind(*args, **kwargs) + bound.apply_defaults() + config = bound.arguments.get("config") + if config is None: + config = get_psoct_scan_config(bound.arguments["project_name"]) + if not config.matlab_processing_enabled: + message = "MATLAB processing disabled by this project's PSOCTScanConfig." + get_run_logger().info("Skipping %s: %s", func.__name__, message) + return Completed(name=MATLAB_DISABLED_STATE, message=message) + return func(*args, **kwargs) + + return wrapper diff --git a/tests/test_matlab_settings.py b/tests/test_matlab_settings.py new file mode 100644 index 0000000..fc113fd --- /dev/null +++ b/tests/test_matlab_settings.py @@ -0,0 +1,69 @@ +import unittest +from types import SimpleNamespace +from unittest.mock import Mock, patch + +from opticstream.config.psoct_scan_config import PSOCTScanConfigModel +from opticstream.utils.matlab_settings import matlab_flow_enabled + + +class MatlabSettingsTests(unittest.TestCase): + def test_default_and_schema(self): + field = PSOCTScanConfigModel.model_fields["matlab_processing_enabled"] + self.assertIs(field.default, True) + self.assertIs(field.annotation, bool) + + @patch("opticstream.utils.matlab_settings.get_run_logger") + def test_block_isolation_and_enabled_execution(self, logger): + body = Mock(return_value="processed") + + @matlab_flow_enabled + def run(config, *, force_rerun=False): + return body() + + disabled = SimpleNamespace(matlab_processing_enabled=False) + enabled = SimpleNamespace(matlab_processing_enabled=True) + self.assertEqual(run(disabled, force_rerun=True).name, "MatlabDisabled") + body.assert_not_called() + self.assertEqual(run(enabled), "processed") + body.assert_called_once() + + @patch("opticstream.utils.matlab_settings.get_run_logger") + @patch("opticstream.utils.matlab_settings.get_psoct_scan_config") + def test_actual_tile_flow_skips_milestone_and_archive(self, load, logger): + from opticstream.flows.psoct.tile_batch_process_flow import process_tile_batch + + with patch("opticstream.flows.psoct.tile_batch_process_flow.OCT_STATE_SERVICE") as state, \ + patch("opticstream.flows.psoct.tile_batch_process_flow.archive_tile_batch") as archive, \ + patch("opticstream.flows.psoct.tile_batch_process_flow.run_matlab_batch_command_or_cli") as matlab: + result = process_tile_batch.fn( + batch_id=None, config=SimpleNamespace(matlab_processing_enabled=False), + file_list=[], force_rerun=True, + ) + self.assertEqual(result.name, "MatlabDisabled") + self.assertEqual(state.mock_calls, []) + archive.submit.assert_not_called() + matlab.assert_not_called() + load.assert_not_called() + + @patch("opticstream.utils.matlab_settings.get_run_logger") + @patch("opticstream.utils.matlab_settings.get_psoct_scan_config") + def test_actual_registration_loads_block_before_io(self, load, logger): + from opticstream.flows.psoct.slice_process_flow import register_slice_flow + + load.return_value = SimpleNamespace(matlab_processing_enabled=False) + with patch("opticstream.flows.psoct.slice_process_flow.thruplane_from_files_task") as matlab: + result = register_slice_flow.fn("disabled-project", "missing", 1, 1, 2) + self.assertEqual(result.name, "MatlabDisabled") + load.assert_called_once_with("disabled-project") + matlab.assert_not_called() + + def test_disabled_completion_does_not_emit_mosaic_ready(self): + from opticstream.hooks.check_mosaic_ready_hook import check_mosaic_ready_hook + + with patch("opticstream.hooks.check_mosaic_ready_hook.emit_mosaic_psoct_event") as emit: + check_mosaic_ready_hook(None, None, SimpleNamespace(name="MatlabDisabled")) + emit.assert_not_called() + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_migrate_psoct_blocks.py b/tests/test_migrate_psoct_blocks.py new file mode 100644 index 0000000..3b7a803 --- /dev/null +++ b/tests/test_migrate_psoct_blocks.py @@ -0,0 +1,51 @@ +import unittest +from types import SimpleNamespace +from unittest.mock import Mock + +from opticstream.config.migrate_psoct_blocks import migrate_blocks + + +def document(name, slug="psoctscanconfig"): + return SimpleNamespace(name=name, block_type=SimpleNamespace(slug=slug), is_anonymous=False) + + +class MigrationTests(unittest.TestCase): + def setup_mocks(self): + client = Mock() + client.read_block_documents.side_effect = [ + [document("a"), document("other", "secret")], [document("b")], [], + ] + cls = Mock() + cls.get_block_type_slug.return_value = "psoctscanconfig" + blocks = [Mock(), Mock()] + cls.load.side_effect = blocks + return client, cls, blocks + + def test_dry_run_paginated_and_type_filtered(self): + client, cls, blocks = self.setup_mocks() + self.assertEqual(migrate_blocks(client=client, block_class=cls), 0) + self.assertEqual(cls.load.call_count, 2) + cls.register_type_and_schema.assert_not_called() + for block in blocks: + block.save.assert_not_called() + self.assertEqual(client.read_block_documents.call_args.kwargs["offset"], 3) + + def test_apply_preserves_loaded_objects(self): + client, cls, blocks = self.setup_mocks() + self.assertEqual(migrate_blocks(apply=True, client=client, block_class=cls), 0) + cls.register_type_and_schema.assert_called_once() + blocks[0].save.assert_called_once_with("a", overwrite=True) + blocks[1].save.assert_called_once_with("b", overwrite=True) + + def test_invalid_aborts_all_writes(self): + client, cls, blocks = self.setup_mocks() + cls.load.side_effect = [blocks[0], ValueError("private")] + self.assertEqual(migrate_blocks(apply=True, client=client, block_class=cls), 1) + cls.register_type_and_schema.assert_not_called() + blocks[0].save.assert_not_called() + + def test_partial_save_failure_stops(self): + client, cls, blocks = self.setup_mocks() + blocks[0].save.side_effect = RuntimeError("private") + self.assertEqual(migrate_blocks(apply=True, client=client, block_class=cls), 1) + blocks[1].save.assert_not_called() From 5836ca4912020f0b95b8e37adb84aaf4b52784df Mon Sep 17 00:00:00 2001 From: NoahMarkowitz Date: Fri, 18 Sep 2026 14:04:23 -0400 Subject: [PATCH 14/65] port linc-convert tiling --- docs/acquisition_enface_previews.md | 93 ++++++++ opticstream/cli/oct/__init__.py | 1 + opticstream/cli/oct/serve.py | 4 + opticstream/cli/oct/watch_enface.py | 87 ++++++++ opticstream/config/enface_preview.py | 37 ++++ opticstream/config/psoct_scan_config.py | 6 + .../flows/psoct/acquisition_preview_flow.py | 206 ++++++++++++++++++ tests/test_acquisition_previews.py | 159 ++++++++++++++ 8 files changed, 593 insertions(+) create mode 100644 docs/acquisition_enface_previews.md create mode 100644 opticstream/cli/oct/watch_enface.py create mode 100644 opticstream/config/enface_preview.py create mode 100644 opticstream/flows/psoct/acquisition_preview_flow.py create mode 100644 tests/test_acquisition_previews.py diff --git a/docs/acquisition_enface_previews.md b/docs/acquisition_enface_previews.md new file mode 100644 index 0000000..a0ca821 --- /dev/null +++ b/docs/acquisition_enface_previews.md @@ -0,0 +1,93 @@ +# Acquisition-produced enface previews + +Two new Prefect flows call linc-convert `mosaic2d()` and send JPEG previews to Slack: + +- `preview-enface-batch`: one complete strip of `acquisition.grid_size_y` tiles. +- `preview-enface-acquisition`: every tile in one acquisition/mosaic. + +These consume AIP, MIP, orientation (`ori`) and retardance (`ret`) files written by +the acquisition software, independently of spectral processing and MATLAB. They +do not set OpticStream processing/upload milestones. Existing processed-output QC +flows remain separate. Preview images are not uploaded to DANDI or LINC. + +## Configure and run + +Refresh saved block schemas with `python -m opticstream.config.migrate_psoct_blocks +--apply` using the project's virtual environment. In the block's new +`enface_preview` group, configure all four filename patterns. They are exact Python +format templates (not globs), with `{image}` required and `{slice}`, `{mosaic}`, +`{acquisition}`, `{project}` optional. Numeric formats such as `{image:04d}` are +supported. These templates are separate from the spectral watcher's parser. + +For example: + +```json +{ + "aip_pattern": "slice-{slice}_acq-{acquisition}_aip_{image:04d}.nii", + "mip_pattern": "slice-{slice}_acq-{acquisition}_mip_{image:04d}.nii", + "ori_pattern": "slice-{slice}_acq-{acquisition}_ori_{image:04d}.nii", + "ret_pattern": "slice-{slice}_acq-{acquisition}_ret_{image:04d}.nii" +} +``` + +Change names/suffixes to match the acquisition software exactly. Simple names such +as `aip_{image:04d}.nii` are supported when the folder contains only that acquisition. +NIfTI (.nii/.nii.gz) and formats supported by the existing QC loader are accepted; +only 2D maps or maps with singleton trailing dimensions are supported. All four +modalities must be present for every expected tile before a candidate is ready. + +From Miniforge Prompt, with the project's venv activated and Prefect API configured: + +```cmd +opticstream oct watch-enface human-10um D:\data\acquisition --slice 1 --mosaic 1 --acquisition normal +``` + +This command runs the flows directly as files stabilize; it does not require +`oct serve`. `oct serve all` additionally registers the two manual preview flows. +The existing `oct watch` remains unchanged; run `watch-enface` separately. +Use one watcher per acquisition, and do not run a manual preview for the same +acquisition concurrently. Select the correct mosaic ID (normal vs tilted) so the +existing `grid_size_x_normal`/`grid_size_x_tilted` selects the correct batch count. +Slice/mosaic identify outputs explicitly; acquisition is the exact filename label. + +## Geometry and readiness + +Tiles are numbered consecutively within the acquisition starting at `first_image` +(default 1). Batch 1 contains the first `grid_size_y` tiles, batch 2 the next set, +etc. Total tiles = selected `grid_size_x` * `grid_size_y`. + +Within each batch, tiles advance along Y; batches advance along X. Set `traversal` +to `snake-by-columns` if alternate batches reverse direction. Default is +`column-by-column`. Individual images are not flipped. Coordinates use actual +image dimensions and `acquisition.tile_overlap` (percentage). These are nominal +grid QC previews, not image-registered/Fiji-optimized mosaics. Inspect alignment +against a known acquisition before relying on the preview geometry. + +Orientation uses circular blending; set `orientation_units` to degrees (default) +or radians. AIP/MIP/retardance use ordinary blending. Acquisition originals are +never changed. Temporary 2D NIfTI copies accommodate singleton NIfTI dimensions. + +The watcher waits for all expected files to have stable sizes and modification +times (15 seconds by default). This is a heuristic, not a producer completion +handshake; increase `--stability-seconds` if acquisition pauses during writes. +Corrupt or inconsistent tiles cause failure rather than a partial mosaic. + +## Outputs, Slack and retries + +Outputs and per-scope `progress.json` checkpoints are under +`project_base_path/acquisition-previews/slice-NNN/mosaic-NNN/`, with separate +`batch-NNNN` and `acquisition` directories. Completed work is skipped on restart. +Input path/size/mtime or relevant configuration changes invalidate checkpoints. +Changing only file content without changing size/mtime is not detected. + +The existing Slack bot credentials/channel and `slack-notifications-enabled` +variable are reused. When Slack is disabled, stitching still runs; uploading waits +until Slack is enabled. Successful modality uploads are checkpointed; failures +retry after another stability interval. Slack delivery is not exactly-once: a crash +after Slack accepts an upload but before the checkpoint is saved can duplicate it. + +`matlab_processing_enabled` does not gate these non-MATLAB flows. Disable batch or +full previews independently with `batch_enabled`/`acquisition_enabled`. Restart the +watcher after editing block fields. A project-state reset does not erase preview +checkpoints; to deliberately resend, archive/move the relevant preview output +directory while the watcher is stopped. diff --git a/opticstream/cli/oct/__init__.py b/opticstream/cli/oct/__init__.py index 24f0a07..6a0950a 100644 --- a/opticstream/cli/oct/__init__.py +++ b/opticstream/cli/oct/__init__.py @@ -4,5 +4,6 @@ from . import setup # noqa: F401 - register oct setup commands from . import state # noqa: F401 - register oct state commands from . import watch # noqa: F401 - register oct watch commands +from . import watch_enface # noqa: F401 - register acquisition preview watcher __all__ = ["oct_cli", "deploy", "serve", "setup", "state", "watch"] diff --git a/opticstream/cli/oct/serve.py b/opticstream/cli/oct/serve.py index d31face..9967874 100644 --- a/opticstream/cli/oct/serve.py +++ b/opticstream/cli/oct/serve.py @@ -5,6 +5,7 @@ from opticstream.cli.oct import oct_cli from opticstream.utils.runtime_paths import chdir_to_opticstream_install_root +from opticstream.flows.psoct.acquisition_preview_flow import to_deployment as acquisition_preview_deployments from opticstream.flows.psoct.mosaic_enface_qc_flow import ( to_deployment as mosaic_enface_qc_deployments, @@ -136,6 +137,9 @@ def build_deployments( ) ) + deployments.extend(acquisition_preview_deployments( + deployment_name=deployment_name, extra_tags=COMMON_TAGS, + )) return deployments diff --git a/opticstream/cli/oct/watch_enface.py b/opticstream/cli/oct/watch_enface.py new file mode 100644 index 0000000..8093635 --- /dev/null +++ b/opticstream/cli/oct/watch_enface.py @@ -0,0 +1,87 @@ +"""Watch externally acquired enface maps without running MATLAB.""" +from pathlib import Path + +from opticstream.cli.oct.cli import oct_cli +from opticstream.cli.oct.watch import _configure_logging +from opticstream.config.psoct_scan_config import get_psoct_scan_config +from opticstream.flows.psoct.acquisition_preview_flow import ( + MODALITIES, expected_tiles, fingerprint, preview_dir, read_progress, + preview_enface_batch, preview_enface_acquisition, +) +from opticstream.flows.psoct.utils import mosaic_context_from_ident +from opticstream.state.oct_project_state import OCTMosaicId +from opticstream.utils.polling_watcher import PollingStableWatcher +from opticstream.utils.slack_settings import slack_notifications_enabled + + +class EnfacePreviewWatcher: + def __init__(self, config, mosaic_ident, folder, acquisition): + self.config = config + self.ident = mosaic_ident + self.folder = Path(folder) + self.acquisition = acquisition + context = mosaic_context_from_ident(mosaic_ident, config) + self.candidates = list(range(1, context.grid_size_x(config) + 1)) if config.enface_preview.batch_enabled else [] + if config.enface_preview.acquisition_enabled: + self.candidates.append(None) + + def files(self, batch): + return expected_tiles(self.config, self.ident, self.folder, self.acquisition, batch) + + def fingerprint(self, batch): + return fingerprint(self.config, self.files(batch)) + + def discover(self): + slack_enabled = slack_notifications_enabled() + for batch in self.candidates: + files = self.files(batch) + if not all(p.is_file() for paths in files.values() for p in paths.values()): + continue + try: + signature = fingerprint(self.config, files) + except (OSError, ValueError): + continue + directory = preview_dir(self.config, self.ident, batch) + progress = read_progress(directory, signature) + stitched = all(m in progress["stitched"] and (directory / f"{m}.jpg").exists() + and (directory / f"{m}.nii").exists() for m in MODALITIES) + uploaded = all(m in progress["uploaded"] for m in MODALITIES) + if not stitched or (slack_enabled and not uploaded): + yield batch + + def process(self, batch): + kwargs = dict(config=self.config, mosaic_ident=self.ident, + input_dir=self.folder, acquisition=self.acquisition) + if batch is None: + preview_enface_acquisition(**kwargs) + else: + preview_enface_batch(**kwargs, batch_id=batch) + return 1 + + +@oct_cli.command +def watch_enface(project_name: str, folder_path: Path, *, slice: int, mosaic: int, + acquisition: str, stability_seconds: int = 15, + poll_interval: int = 5, verbose: bool = False): + """Watch one acquisition for complete batches and a complete full mosaic. + + slice/mosaic identify the acquisition explicitly, allowing filenames such as + aip_0001.nii without embedded IDs. acquisition substitutes into file patterns. + Use one watcher per acquisition. No MATLAB or spectral watcher is required. + """ + _configure_logging(verbose) + if slice < 1 or mosaic < 1: + raise ValueError("slice and mosaic must be positive") + if not folder_path.is_dir(): + raise ValueError(f"Input directory does not exist: {folder_path}") + config = get_psoct_scan_config(project_name) + if not config.enface_preview.batch_enabled and not config.enface_preview.acquisition_enabled: + raise ValueError("Both enface preview flows are disabled in this block") + ident = OCTMosaicId(project_name=project_name, slice_id=slice, mosaic_id=mosaic) + worker = EnfacePreviewWatcher(config, ident, folder_path.resolve(), acquisition) + # Validate templates before entering the polling loop. + worker.files(None) + PollingStableWatcher(discover_candidates=worker.discover, + candidate_key=lambda batch: batch, fingerprint=worker.fingerprint, + process=worker.process, stability_seconds=stability_seconds, + poll_interval=poll_interval, running_message="Watching acquisition enface maps").run() diff --git a/opticstream/config/enface_preview.py b/opticstream/config/enface_preview.py new file mode 100644 index 0000000..2a91060 --- /dev/null +++ b/opticstream/config/enface_preview.py @@ -0,0 +1,37 @@ +"""Acquisition-produced image preview configuration.""" +from pathlib import PureWindowsPath +from string import Formatter +from typing import Literal + +from pydantic import BaseModel, ConfigDict, Field, field_validator + + +class EnfacePreviewConfig(BaseModel): + model_config = ConfigDict(extra="forbid", validate_assignment=True) + + batch_enabled: bool = Field(default=True, description="Stitch each complete grid_size_y-tile batch and send previews to Slack when watch-enface runs.") + acquisition_enabled: bool = Field(default=True, description="Also stitch the complete acquisition/mosaic and send previews to Slack.") + aip_pattern: str = Field(default="mosaic_{mosaic:03d}_image_{image:04d}_aip.nii", description="Exact filename format, not a glob. Required {image}; optional {slice}, {mosaic}, {acquisition}, {project}. Supports :04d zero-padding. Example: slice-{slice}_acq-{acquisition}_aip_{image:04d}.nii") + mip_pattern: str = Field(default="mosaic_{mosaic:03d}_image_{image:04d}_mip.nii", description="MIP filename format; same placeholders as aip_pattern. Set the actual suffix, including .nii.gz if used.") + ori_pattern: str = Field(default="mosaic_{mosaic:03d}_image_{image:04d}_ori.nii", description="Orientation filename format. Orientation is blended with circular averaging.") + ret_pattern: str = Field(default="mosaic_{mosaic:03d}_image_{image:04d}_ret.nii", description="Retardance filename format; no hardcoded modality suffix.") + traversal: Literal["column-by-column", "snake-by-columns"] = Field(default="column-by-column", description="Each batch advances along Y; batches advance along X. Snake reverses Y placement in alternate batches without flipping individual images.") + first_image: int = Field(default=1, ge=0, description="First filename image index within this acquisition. Batches themselves remain 1-based.") + orientation_units: Literal["degrees", "radians"] = Field(default="degrees", description="Units of acquisition orientation maps; radians are converted to degrees for linc-convert.") + + @field_validator("aip_pattern", "mip_pattern", "ori_pattern", "ret_pattern") + @classmethod + def validate_pattern(cls, value): + fields = [] + for _, field, spec, conversion in Formatter().parse(value): + if field is None: + continue + if field not in {"image", "slice", "mosaic", "acquisition", "project"} or conversion: + raise ValueError("Unsupported preview filename placeholder or conversion") + fields.append(field) + if "image" not in fields: + raise ValueError("Preview filename must contain {image} (optional numeric format allowed)") + rendered = value.format(image=1, slice=1, mosaic=1, acquisition="normal", project="test") + if PureWindowsPath(rendered).name != rendered or rendered in {".", ".."}: + raise ValueError("Preview patterns must be basenames, without directories") + return value diff --git a/opticstream/config/psoct_scan_config.py b/opticstream/config/psoct_scan_config.py index 0302220..d8aaea6 100644 --- a/opticstream/config/psoct_scan_config.py +++ b/opticstream/config/psoct_scan_config.py @@ -18,6 +18,7 @@ from niizarr import ZarrConfig import psoct_toolbox from opticstream.config.utils import with_positions +from opticstream.config.enface_preview import EnfacePreviewConfig from opticstream.utils.naming_convention import normalize_project_name @@ -298,6 +299,11 @@ class PSOCTScanConfigModel(BaseModel): description="Project-level MATLAB processing options", ) + enface_preview: EnfacePreviewConfig = Field( + default_factory=EnfacePreviewConfig, + description="Acquisition-produced AIP/MIP/orientation/retardance previews for watch-enface; independent of MATLAB and spectral processing state.", + ) + mask_threshold_normal: float = Field( default=60.0, ge=0.0, diff --git a/opticstream/flows/psoct/acquisition_preview_flow.py b/opticstream/flows/psoct/acquisition_preview_flow.py new file mode 100644 index 0000000..2ac8bcb --- /dev/null +++ b/opticstream/flows/psoct/acquisition_preview_flow.py @@ -0,0 +1,206 @@ +"""Batch and acquisition QC previews from externally produced enface tiles. + +No processing milestones are mutated. Local manifests permit resumable previews. +Run only one preview watcher for a given project/slice/mosaic at a time. +""" +import hashlib +import json +from pathlib import Path +import tempfile +import time + +import nibabel as nib +import numpy as np +from prefect import flow, task +import yaml + +from opticstream.config.psoct_scan_config import PSOCTScanConfigModel +from opticstream.data_processing.qc.convert_image import convert_image +from opticstream.flows.psoct.utils import mosaic_context_from_ident +from opticstream.state.oct_project_state import OCTMosaicId +from opticstream.tasks.slack_notification import upload_multiple_files_to_slack +from opticstream.utils.slack_settings import slack_notifications_enabled + +MODALITIES = ("aip", "mip", "ori", "ret") + + +def expected_tiles(config, mosaic_ident, input_dir, acquisition, batch_id=None): + """Return exact expected paths, never infer completeness from file counts.""" + context = mosaic_context_from_ident(mosaic_ident, config) + rows = config.acquisition.grid_size_y + columns = context.grid_size_x(config) + if batch_id is not None and not 1 <= batch_id <= columns: + raise ValueError(f"batch_id must be between 1 and {columns}") + indices = range(columns * rows) if batch_id is None else range((batch_id - 1) * rows, batch_id * rows) + root = Path(input_dir).resolve() + result = {} + for modality in MODALITIES: + pattern = getattr(config.enface_preview, f"{modality}_pattern") + paths = {} + for index in indices: + name = pattern.format(image=index + config.enface_preview.first_image, + slice=mosaic_ident.slice_id, mosaic=mosaic_ident.mosaic_id, + acquisition=acquisition, project=mosaic_ident.project_name) + path = (root / name).resolve() + if path.parent != root: + raise ValueError("Rendered preview filename must remain inside the input directory") + paths[index] = path + result[modality] = paths + all_paths = [p for paths in result.values() for p in paths.values()] + if len(set(all_paths)) != len(all_paths): + raise ValueError("Preview patterns must identify distinct modality/tile files") + return result + + +def fingerprint(config, files): + records = [] + for modality, paths in files.items(): + for index, path in paths.items(): + stat = path.stat() + if not path.is_file() or stat.st_size == 0: + raise ValueError(f"Empty or invalid tile: {path}") + records.append((modality, index, str(path), stat.st_size, stat.st_mtime_ns)) + settings = (config.enface_preview.model_dump(mode="json"), config.acquisition.model_dump(mode="json")) + return hashlib.sha256(json.dumps([records, settings], sort_keys=True).encode()).hexdigest() + + +def preview_dir(config, mosaic_ident, batch_id=None): + scope = "acquisition" if batch_id is None else f"batch-{batch_id:04d}" + return Path(config.project_base_path) / "acquisition-previews" / f"slice-{mosaic_ident.slice_id:03d}" / f"mosaic-{mosaic_ident.mosaic_id:03d}" / scope + + +def read_progress(directory, signature): + try: + data = json.loads((directory / "progress.json").read_text()) + except (FileNotFoundError, ValueError): + return {"signature": signature, "stitched": [], "uploaded": []} + if data.get("signature") != signature: + return {"signature": signature, "stitched": [], "uploaded": []} + return data + + +def save_progress(directory, progress): + directory.mkdir(parents=True, exist_ok=True) + temporary = directory / "progress.json.tmp" + temporary.write_text(json.dumps(progress, indent=2)) + # Windows indexers/antivirus may briefly hold the replaced file open. + for attempt in range(5): + try: + temporary.replace(directory / "progress.json") + break + except PermissionError: + if attempt == 4: + raise + time.sleep(0.1 * (attempt + 1)) + + +def tile_position(index, rows, shape, overlap, traversal, batch_id=None): + column, row = divmod(index, rows) + if traversal == "snake-by-columns" and column % 2: + row = rows - 1 - row + if batch_id is not None: + column = 0 + return round(column * shape[0] * (1 - overlap)), round(row * shape[1] * (1 - overlap)) + + +@task +def stitch_preview_modality(config: PSOCTScanConfigModel, files: dict[int, Path], + modality: str, output: Path, batch_id: int | None = None) -> Path: + """Normalize singleton NIfTI maps to 2D then call linc-convert mosaic2d. + + Temporary files leave acquisition originals untouched and prevent linc-convert + from silently skipping unreadable inputs. TIFF and other formats accepted by + the existing QC loader can also be used through configurable suffixes. + """ + from opticstream.data_processing.qc.convert_image import load_data + from linc_convert.modalities.psoct.mosaic import mosaic2d + + overlap = config.acquisition.tile_overlap / 100.0 + if not 0 <= overlap < 1: + raise ValueError("Preview tile_overlap must be a percentage in [0, 100)") + output.parent.mkdir(parents=True, exist_ok=True) + shape = None + with tempfile.TemporaryDirectory(prefix="enface-preview-", dir=output.parent) as scratch: + entries = [] + for index, path in files.items(): + # Treat only the final extension as a format indicator; acquisition + # labels may contain dots (e.g. tilted12.5deg). + if path.name.lower().endswith((".nii", ".nii.gz")): + array = np.asarray(nib.load(path).dataobj) + else: + array = np.asarray(load_data(input_path=path, mat_variable=None)) + if array.ndim > 2 and all(size == 1 for size in array.shape[2:]): + array = array.reshape(array.shape[:2]) + if array.ndim != 2: + raise ValueError(f"Expected 2D enface map (or singleton trailing axes): {path}, {array.shape}") + if shape is not None and array.shape != shape: + raise ValueError(f"Tile dimensions differ: {path}, {array.shape} != {shape}") + shape = array.shape + array = array.astype(np.float32) + if modality == "ori" and config.enface_preview.orientation_units == "radians": + array = np.rad2deg(array) + normalized = Path(scratch) / f"tile-{index}.nii" + nib.save(nib.Nifti1Image(array, np.eye(4)), normalized) + x, y = tile_position(index, config.acquisition.grid_size_y, shape, overlap, + config.enface_preview.traversal, batch_id) + entries.append({"filepath": str(normalized.resolve()), "x": x, "y": y}) + spec = Path(scratch) / "tiles.yaml" + spec.write_text(yaml.safe_dump({"metadata": {"scan_resolution": config.acquisition.scan_resolution_3d[:2]}, "tiles": entries})) + mosaic2d(tile_info_file=str(spec), nifti_output=str(output), + tile_overlap=overlap if overlap else 0, circular_mean=modality == "ori") + if not output.is_file(): + raise RuntimeError(f"mosaic2d did not produce {output}") + jpeg = output.with_suffix(".jpg") + convert_image(input=output, output=jpeg, angle_to_rgb=modality == "ori", output_format="jpg") + return jpeg + + +def run_preview(config, mosaic_ident, input_dir, acquisition, batch_id=None): + enabled = config.enface_preview.acquisition_enabled if batch_id is None else config.enface_preview.batch_enabled + if not enabled: + return {} + files = expected_tiles(config, mosaic_ident, input_dir, acquisition, batch_id) + signature = fingerprint(config, files) + directory = preview_dir(config, mosaic_ident, batch_id) + progress = read_progress(directory, signature) + for modality in MODALITIES: + output = directory / f"{modality}.nii" + if modality not in progress["stitched"] or not output.with_suffix(".jpg").exists() or not output.exists(): + stitch_preview_modality(config, files[modality], modality, output, batch_id) + if fingerprint(config, files) != signature: + raise RuntimeError("Acquisition files changed while stitching; wait for stability and retry") + if modality not in progress["stitched"]: + progress["stitched"].append(modality) + save_progress(directory, progress) + if slack_notifications_enabled(): + remaining = [m for m in MODALITIES if m not in progress["uploaded"]] + if remaining: + paths = [str(directory / f"{m}.jpg") for m in remaining] + scope = "full acquisition" if batch_id is None else f"batch {batch_id}" + label = f"{mosaic_ident.project_name}, slice {mosaic_ident.slice_id}, mosaic {mosaic_ident.mosaic_id}, {acquisition}, {scope}" + results = upload_multiple_files_to_slack(filepaths=paths, + titles=[f"{label} - {m.upper()}" for m in remaining], initial_comment=label) + for modality, path in zip(remaining, paths): + if results.get(path): + progress["uploaded"].append(modality) + save_progress(directory, progress) + if any(not results.get(path) for path in paths): + raise RuntimeError("Some preview Slack uploads failed; successful uploads are checkpointed") + return {m: str(directory / f"{m}.jpg") for m in MODALITIES} + + +@flow(name="preview-enface-batch") +def preview_enface_batch(config: PSOCTScanConfigModel, mosaic_ident: OCTMosaicId, + input_dir: Path, acquisition: str, batch_id: int): + return run_preview(config, mosaic_ident, input_dir, acquisition, batch_id) + + +@flow(name="preview-enface-acquisition") +def preview_enface_acquisition(config: PSOCTScanConfigModel, mosaic_ident: OCTMosaicId, + input_dir: Path, acquisition: str): + return run_preview(config, mosaic_ident, input_dir, acquisition) + + +def to_deployment(*, deployment_name="local", extra_tags=()): + return [f.to_deployment(name=deployment_name, tags=["acquisition-preview", *extra_tags], concurrency_limit=1) + for f in (preview_enface_batch, preview_enface_acquisition)] diff --git a/tests/test_acquisition_previews.py b/tests/test_acquisition_previews.py new file mode 100644 index 0000000..f236250 --- /dev/null +++ b/tests/test_acquisition_previews.py @@ -0,0 +1,159 @@ +import unittest +from pathlib import Path +from tempfile import TemporaryDirectory +from types import SimpleNamespace +from unittest.mock import patch + +import nibabel as nib +import numpy as np + +from opticstream.config.enface_preview import EnfacePreviewConfig +from opticstream.config.psoct_scan_config import PSOCTAcquisitionParams +from opticstream.flows.psoct import acquisition_preview_flow as preview +from opticstream.cli.oct.watch_enface import EnfacePreviewWatcher +from opticstream.state.oct_project_state import OCTMosaicId + + +def config(root): + return SimpleNamespace(project_base_path=Path(root) / "out", mosaics_per_slice=2, + enface_preview=EnfacePreviewConfig(**{f"{m}_pattern": f"{m}_{{image:04d}}.nii" for m in preview.MODALITIES}), + acquisition=PSOCTAcquisitionParams(grid_size_y=2, grid_size_x_normal=2, + grid_size_x_tilted=3, tile_overlap=0)) + + +class PreviewTests(unittest.TestCase): + def setUp(self): + self.temp = TemporaryDirectory() + self.addCleanup(self.temp.cleanup) + self.root = Path(self.temp.name) + self.cfg = config(self.root) + self.ident = OCTMosaicId(project_name="test", slice_id=1, mosaic_id=1) + + def create_tiles(self, count=4): + for m in preview.MODALITIES: + for i in range(1, count + 1): + data = np.full((8, 6, 1), i, dtype=np.float32) + nib.save(nib.Nifti1Image(data, np.eye(4)), self.root / f"{m}_{i:04d}.nii") + + def test_patterns(self): + for value in ("aip.nii", "../{image}.nii", "{unknown}_{image}.nii"): + with self.assertRaises(ValueError): + EnfacePreviewConfig(aip_pattern=value) + files = preview.expected_tiles(self.cfg, self.ident, self.root, "normal", 2) + self.assertEqual(list(files["aip"]), [2, 3]) + self.assertEqual(files["aip"][2].name, "aip_0003.nii") + with self.assertRaises(ValueError): + preview.expected_tiles(self.cfg, self.ident, self.root, "normal", 3) + + def test_geometry(self): + self.assertEqual(preview.tile_position(2, 2, (10, 20), .2, "column-by-column"), (8, 0)) + self.assertEqual(preview.tile_position(2, 2, (10, 20), .2, "snake-by-columns"), (8, 16)) + self.assertEqual(preview.tile_position(2, 2, (10, 20), .2, "snake-by-columns", 2), (0, 16)) + + @patch("opticstream.cli.oct.watch_enface.slack_notifications_enabled", return_value=False) + def test_complete_batches_and_acquisition_only(self, slack): + watcher = EnfacePreviewWatcher(self.cfg, self.ident, self.root, "normal") + self.create_tiles(2) + self.assertEqual(list(watcher.discover()), [1]) + self.create_tiles(4) + self.assertEqual(list(watcher.discover()), [1, 2, None]) + (self.root / "ret_0004.nii").unlink() + self.assertEqual(list(watcher.discover()), [1]) + + def test_tilted_grid_and_duplicate_patterns(self): + ident = OCTMosaicId(project_name="test", slice_id=1, mosaic_id=2) + files = preview.expected_tiles(self.cfg, ident, self.root, "tilted") + self.assertEqual(len(files["aip"]), 6) + self.cfg.enface_preview.mip_pattern = self.cfg.enface_preview.aip_pattern + with self.assertRaises(ValueError): + preview.expected_tiles(self.cfg, ident, self.root, "tilted") + + @patch.object(preview, "slack_notifications_enabled", return_value=False) + def test_checkpoint_resume_then_slack(self, slack): + self.create_tiles() + def stitch(cfg, files, modality, output, batch_id): + output.parent.mkdir(parents=True, exist_ok=True) + output.write_bytes(b"nifti") + output.with_suffix(".jpg").write_bytes(b"jpeg") + with patch.object(preview, "stitch_preview_modality", side_effect=stitch) as stitch_mock, \ + patch.object(preview, "upload_multiple_files_to_slack") as upload: + preview.preview_enface_batch.fn(self.cfg, self.ident, self.root, "normal", 1) + self.assertEqual(stitch_mock.call_count, 4) + upload.assert_not_called() + preview.preview_enface_batch.fn(self.cfg, self.ident, self.root, "normal", 1) + self.assertEqual(stitch_mock.call_count, 4) + slack.return_value = True + upload.side_effect = lambda **kw: {p: True for p in kw["filepaths"]} + preview.preview_enface_batch.fn(self.cfg, self.ident, self.root, "normal", 1) + preview.preview_enface_batch.fn(self.cfg, self.ident, self.root, "normal", 1) + upload.assert_called_once() + self.assertEqual(stitch_mock.call_count, 4) + + def test_disabled_flow_no_io(self): + self.cfg.enface_preview.batch_enabled = False + with patch.object(preview, "stitch_preview_modality") as stitch: + self.assertEqual(preview.preview_enface_batch.fn(self.cfg, self.ident, self.root, "normal", 1), {}) + stitch.assert_not_called() + + @patch.object(preview, "slack_notifications_enabled", return_value=True) + def test_failed_upload_retries_only_missing_modalities(self, slack): + self.create_tiles() + def stitch(cfg, files, modality, output, batch_id): + output.parent.mkdir(parents=True, exist_ok=True) + output.write_bytes(b"nifti") + output.with_suffix(".jpg").write_bytes(b"jpeg") + with patch.object(preview, "stitch_preview_modality", side_effect=stitch) as stitched, \ + patch.object(preview, "upload_multiple_files_to_slack") as upload: + upload.side_effect = lambda **kw: {p: Path(p).stem != "ret" for p in kw["filepaths"]} + with self.assertRaises(RuntimeError): + preview.run_preview(self.cfg, self.ident, self.root, "normal", 1) + upload.side_effect = lambda **kw: {p: True for p in kw["filepaths"]} + preview.run_preview(self.cfg, self.ident, self.root, "normal", 1) + self.assertEqual(len(upload.call_args.kwargs["filepaths"]), 1) + self.assertEqual(stitched.call_count, 4) + + def test_changed_input_invalidates_progress(self): + self.create_tiles() + files = preview.expected_tiles(self.cfg, self.ident, self.root, "normal", 1) + before = preview.fingerprint(self.cfg, files) + directory = preview.preview_dir(self.cfg, self.ident, 1) + preview.save_progress(directory, {"signature": before, "stitched": list(preview.MODALITIES), "uploaded": []}) + with (self.root / "aip_0001.nii").open("ab") as stream: + stream.write(b"changed") + after = preview.fingerprint(self.cfg, files) + self.assertNotEqual(before, after) + self.assertEqual(preview.read_progress(directory, after)["stitched"], []) + + @patch("opticstream.cli.oct.watch_enface.slack_notifications_enabled", return_value=False) + def test_polling_waits_for_stability(self, slack): + from opticstream.utils.polling_watcher import PollingStableWatcher + self.create_tiles(2) + worker = EnfacePreviewWatcher(self.cfg, self.ident, self.root, "normal") + with patch.object(worker, "process", return_value=1) as process: + poller = PollingStableWatcher(discover_candidates=worker.discover, + candidate_key=lambda batch: batch, fingerprint=worker.fingerprint, + process=process, stability_seconds=15) + with patch("opticstream.utils.polling_watcher.time.time") as clock: + for instant in (0, 1, 10): + clock.return_value = instant + poller._run_iteration() + process.assert_not_called() + clock.return_value = 17 + poller._run_iteration() + process.assert_called_once_with(1) + + def test_real_mosaic2d_singleton_nifti(self): + self.create_tiles() + files = preview.expected_tiles(self.cfg, self.ident, self.root, "normal") + for modality in ("aip", "ori"): + output = self.root / "stitched" / f"{modality}.nii" + jpeg = preview.stitch_preview_modality.fn(self.cfg, files[modality], modality, output) + self.assertTrue(jpeg.is_file()) + result = nib.load(output).get_fdata() + self.assertEqual(result.shape, (16, 12)) + self.assertAlmostEqual(result[3, 3], 1, places=4) + self.assertAlmostEqual(result[11, 9], 4, places=4) + + +if __name__ == "__main__": + unittest.main() From ce418a610d1f324633fdd5cac20dab016b5dfd7f Mon Sep 17 00:00:00 2001 From: NoahMarkowitz Date: Fri, 18 Sep 2026 15:01:27 -0400 Subject: [PATCH 15/65] enface previewing --- docs/acquisition_enface_previews.md | 29 ++++++++++++-- opticstream/config/enface_preview.py | 31 ++++++++++++++- .../flows/psoct/acquisition_preview_flow.py | 32 ++++++++++++--- tests/test_acquisition_previews.py | 39 ++++++++++++++++++- 4 files changed, 119 insertions(+), 12 deletions(-) diff --git a/docs/acquisition_enface_previews.md b/docs/acquisition_enface_previews.md index a0ca821..9c80bd4 100644 --- a/docs/acquisition_enface_previews.md +++ b/docs/acquisition_enface_previews.md @@ -56,13 +56,36 @@ Tiles are numbered consecutively within the acquisition starting at `first_image (default 1). Batch 1 contains the first `grid_size_y` tiles, batch 2 the next set, etc. Total tiles = selected `grid_size_x` * `grid_size_y`. -Within each batch, tiles advance along Y; batches advance along X. Set `traversal` -to `snake-by-columns` if alternate batches reverse direction. Default is -`column-by-column`. Individual images are not flipped. Coordinates use actual +In the block editor, `enface_preview.grid_config` exposes all linc-convert modes: + +| grid_type | Valid order values | +| --- | --- | +| row-by-row / snake-by-rows | right-down, left-down, right-up, left-up | +| column-by-column / snake-by-columns | down-right, down-left, up-right, up-left | + +The first direction is motion within the first strip; the second is motion between +strips. `right-down` and `down-right` start at top-left; `left-down` and `down-left` +at top-right; `right-up` and `up-right` at bottom-left; `left-up` and `up-left` at +bottom-right. Snake reverses the fast direction on alternate strips. + +Default is `column-by-column` / `down-right`. In column-first mode strips advance +along Y and batches along X; row-first swaps those axes. **Batch size stays +grid_size_y and batch count stays the selected grid_size_x**, so row-first has +grid_size_y physical columns and grid_size_x physical rows. This keeps the existing +consecutive batch convention. Individual images are not flipped. Coordinates use actual image dimensions and `acquisition.tile_overlap` (percentage). These are nominal grid QC previews, not image-registered/Fiji-optimized mosaics. Inspect alignment against a known acquisition before relying on the preview geometry. +Existing saved `enface_preview.traversal` settings migrate automatically to +`grid_config.grid_type` with `order=down-right` when loaded/resaved by the block +migration command. Explicit new grid_config values take precedence. Change both +grid_type and order together to a compatible pair. These settings affect the new +acquisition-preview flows, not the existing Fiji-registered processing pipeline. +The new grid_config representation changes preview fingerprints, including after +legacy migration, so existing previews may be regenerated and sent again. Disable +Slack temporarily if you only want to inspect the regenerated images locally. + Orientation uses circular blending; set `orientation_units` to degrees (default) or radians. AIP/MIP/retardance use ordinary blending. Acquisition originals are never changed. Temporary 2D NIfTI copies accommodate singleton NIfTI dimensions. diff --git a/opticstream/config/enface_preview.py b/opticstream/config/enface_preview.py index 2a91060..1d30936 100644 --- a/opticstream/config/enface_preview.py +++ b/opticstream/config/enface_preview.py @@ -3,7 +3,23 @@ from string import Formatter from typing import Literal -from pydantic import BaseModel, ConfigDict, Field, field_validator +from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator + + +class PreviewGridConfig(BaseModel): + model_config = ConfigDict(extra="forbid", validate_assignment=True) + grid_type: Literal["row-by-row", "column-by-column", "snake-by-rows", "snake-by-columns"] = Field( + default="column-by-column", description="Acquisition traversal. Snake reverses the fast direction on alternate strips; individual images are not flipped. Each strip still contains grid_size_y consecutive tiles.") + order: Literal["right-down", "left-down", "right-up", "left-up", "down-right", "down-left", "up-right", "up-left"] = Field( + default="down-right", description="Rows: right-down (top-left), left-down (top-right), right-up (bottom-left), left-up (bottom-right). Columns: down-right (top-left), down-left (top-right), up-right (bottom-left), up-left (bottom-right). First word is initial within-strip movement; second is movement between strips. Must match grid_type.") + + @model_validator(mode="after") + def compatible_order(self): + row_based = self.grid_type in {"row-by-row", "snake-by-rows"} + valid = {"right-down", "left-down", "right-up", "left-up"} if row_based else {"down-right", "down-left", "up-right", "up-left"} + if self.order not in valid: + raise ValueError(f"{self.grid_type} requires order in {sorted(valid)}") + return self class EnfacePreviewConfig(BaseModel): @@ -15,10 +31,21 @@ class EnfacePreviewConfig(BaseModel): mip_pattern: str = Field(default="mosaic_{mosaic:03d}_image_{image:04d}_mip.nii", description="MIP filename format; same placeholders as aip_pattern. Set the actual suffix, including .nii.gz if used.") ori_pattern: str = Field(default="mosaic_{mosaic:03d}_image_{image:04d}_ori.nii", description="Orientation filename format. Orientation is blended with circular averaging.") ret_pattern: str = Field(default="mosaic_{mosaic:03d}_image_{image:04d}_ret.nii", description="Retardance filename format; no hardcoded modality suffix.") - traversal: Literal["column-by-column", "snake-by-columns"] = Field(default="column-by-column", description="Each batch advances along Y; batches advance along X. Snake reverses Y placement in alternate batches without flipping individual images.") + grid_config: PreviewGridConfig = Field(default_factory=PreviewGridConfig, description="linc-convert-compatible grid traversal and starting direction for acquisition previews. grid_size_y is tiles per strip; selected grid_size_x is number of strips, regardless of traversal axis.") first_image: int = Field(default=1, ge=0, description="First filename image index within this acquisition. Batches themselves remain 1-based.") orientation_units: Literal["degrees", "radians"] = Field(default="degrees", description="Units of acquisition orientation maps; radians are converted to degrees for linc-convert.") + @model_validator(mode="before") + @classmethod + def migrate_traversal(cls, value): + if isinstance(value, dict) and "traversal" in value: + value = dict(value) + traversal = value.pop("traversal") + if traversal not in {"column-by-column", "snake-by-columns"}: + raise ValueError("Invalid legacy preview traversal") + value.setdefault("grid_config", {"grid_type": traversal, "order": "down-right"}) + return value + @field_validator("aip_pattern", "mip_pattern", "ori_pattern", "ret_pattern") @classmethod def validate_pattern(cls, value): diff --git a/opticstream/flows/psoct/acquisition_preview_flow.py b/opticstream/flows/psoct/acquisition_preview_flow.py index 2ac8bcb..4828fc7 100644 --- a/opticstream/flows/psoct/acquisition_preview_flow.py +++ b/opticstream/flows/psoct/acquisition_preview_flow.py @@ -94,12 +94,30 @@ def save_progress(directory, progress): time.sleep(0.1 * (attempt + 1)) -def tile_position(index, rows, shape, overlap, traversal, batch_id=None): - column, row = divmod(index, rows) - if traversal == "snake-by-columns" and column % 2: - row = rows - 1 - row +def tile_position(index, rows, shape, overlap, traversal, batch_id=None, *, order=None, columns=None): + """Map acquisition sequence to linc-convert grid coordinates. + + rows is the historical tiles-per-batch setting, not the physical Y extent + in row-first mode. columns is the number of batches for the full acquisition. + """ + row_based = traversal in {"row-by-row", "snake-by-rows"} + order = order or ("right-down" if row_based else "down-right") + from opticstream.config.enface_preview import PreviewGridConfig + PreviewGridConfig(grid_type=traversal, order=order) + strip, fast = divmod(index, rows) + slow = strip + count = columns if columns is not None else strip + 1 + initial, subsequent = order.split("-") + reverse_fast = initial in {"left", "up"} + if traversal.startswith("snake-") and strip % 2: + reverse_fast = not reverse_fast + if reverse_fast: + fast = rows - 1 - fast + if subsequent in {"left", "up"}: + slow = count - 1 - slow if batch_id is not None: - column = 0 + slow = 0 + column, row = (fast, slow) if row_based else (slow, fast) return round(column * shape[0] * (1 - overlap)), round(row * shape[1] * (1 - overlap)) @@ -141,8 +159,10 @@ def stitch_preview_modality(config: PSOCTScanConfigModel, files: dict[int, Path] array = np.rad2deg(array) normalized = Path(scratch) / f"tile-{index}.nii" nib.save(nib.Nifti1Image(array, np.eye(4)), normalized) + grid = config.enface_preview.grid_config x, y = tile_position(index, config.acquisition.grid_size_y, shape, overlap, - config.enface_preview.traversal, batch_id) + grid.grid_type, batch_id, order=grid.order, + columns=max(files) // config.acquisition.grid_size_y + 1) entries.append({"filepath": str(normalized.resolve()), "x": x, "y": y}) spec = Path(scratch) / "tiles.yaml" spec.write_text(yaml.safe_dump({"metadata": {"scan_resolution": config.acquisition.scan_resolution_3d[:2]}, "tiles": entries})) diff --git a/tests/test_acquisition_previews.py b/tests/test_acquisition_previews.py index f236250..c55f538 100644 --- a/tests/test_acquisition_previews.py +++ b/tests/test_acquisition_previews.py @@ -7,7 +7,7 @@ import nibabel as nib import numpy as np -from opticstream.config.enface_preview import EnfacePreviewConfig +from opticstream.config.enface_preview import EnfacePreviewConfig, PreviewGridConfig from opticstream.config.psoct_scan_config import PSOCTAcquisitionParams from opticstream.flows.psoct import acquisition_preview_flow as preview from opticstream.cli.oct.watch_enface import EnfacePreviewWatcher @@ -50,6 +50,43 @@ def test_geometry(self): self.assertEqual(preview.tile_position(2, 2, (10, 20), .2, "snake-by-columns"), (8, 16)) self.assertEqual(preview.tile_position(2, 2, (10, 20), .2, "snake-by-columns", 2), (0, 16)) + def test_grid_modes_match_linc_convert(self): + from linc_convert.modalities.psoct import generate_tile_config as grids + generators = { + "row-by-row": grids._generate_row_by_row, + "column-by-column": grids._generate_column_by_column, + "snake-by-rows": grids._generate_snake_by_rows, + "snake-by-columns": grids._generate_snake_by_columns, + } + for mode, generator in generators.items(): + row_based = mode in {"row-by-row", "snake-by-rows"} + orders = ["right-down", "left-down", "right-up", "left-up"] if row_based else ["down-right", "down-left", "up-right", "up-left"] + for order in orders: + with self.subTest(mode=mode, order=order): + # Non-square acquisition: 3 strips of 2 tiles. + expected = generator(2 if row_based else 3, 3 if row_based else 2, + 10, 20, .2, .2, order, "tile_{tile_number:04d}.nii") + actual = [preview.tile_position(i, 2, (10, 20), .2, mode, + order=order, columns=3) for i in range(6)] + self.assertEqual(actual, [(t["x"], t["y"]) for t in expected]) + for batch in range(1, 4): + points = actual[(batch - 1) * 2:batch * 2] + cropped = [(x-min(p[0] for p in points), y-min(p[1] for p in points)) for x, y in points] + strip = [preview.tile_position(i, 2, (10, 20), .2, mode, batch, + order=order, columns=3) for i in range((batch-1)*2, batch*2)] + self.assertEqual(strip, cropped) + + def test_grid_schema_validation_and_legacy_migration(self): + for mode in ("column-by-column", "snake-by-columns"): + migrated = EnfacePreviewConfig.model_validate({"traversal": mode}) + self.assertEqual(migrated.grid_config.grid_type, mode) + self.assertEqual(migrated.grid_config.order, "down-right") + self.assertNotIn("traversal", migrated.model_dump()) + with self.assertRaises(ValueError): + PreviewGridConfig(grid_type="row-by-row", order="down-right") + cfg = EnfacePreviewConfig(grid_config={"grid_type": "snake-by-rows", "order": "left-up"}) + self.assertEqual(cfg.grid_config.order, "left-up") + @patch("opticstream.cli.oct.watch_enface.slack_notifications_enabled", return_value=False) def test_complete_batches_and_acquisition_only(self, slack): watcher = EnfacePreviewWatcher(self.cfg, self.ident, self.root, "normal") From 7901d7e2d02868586dca11d52050fc965e63b173 Mon Sep 17 00:00:00 2001 From: NoahMarkowitz Date: Sun, 20 Sep 2026 15:20:09 -0400 Subject: [PATCH 16/65] add 3d tile saving as option --- docs/matlab_enface_only.md | 39 ++++++ opticstream/config/pipeline_opts_builder.py | 16 +++ opticstream/config/psoct_scan_config.py | 8 ++ opticstream/data_processing/stitch/fiji.py | 1 + .../flows/psoct/mosaic_volume_stitch_flow.py | 5 + .../flows/psoct/mosaic_volume_upload_flow.py | 2 + .../psoct/tile_batch_processed_validation.py | 4 +- .../+file/+internal/applyVolumeOutputPolicy.m | 14 ++ .../+file/complex2processed_batch_indexed.m | 119 +++++++++++++++++ .../+file/spectral2processed_batch_indexed.m | 120 ++++++++++++++++++ opticstream/utils/volume_settings.py | 22 ++++ pyproject.toml | 2 +- tests/matlab/test_volume_output_policy.m | 22 ++++ tests/test_volume_output_setting.py | 91 +++++++++++++ 14 files changed, 462 insertions(+), 3 deletions(-) create mode 100644 docs/matlab_enface_only.md create mode 100644 opticstream/matlab/+psoct/+file/+internal/applyVolumeOutputPolicy.m create mode 100644 opticstream/matlab/+psoct/+file/complex2processed_batch_indexed.m create mode 100644 opticstream/matlab/+psoct/+file/spectral2processed_batch_indexed.m create mode 100644 opticstream/utils/volume_settings.py create mode 100644 tests/matlab/test_volume_output_policy.m create mode 100644 tests/test_volume_output_setting.py diff --git a/docs/matlab_enface_only.md b/docs/matlab_enface_only.md new file mode 100644 index 0000000..6cf42ed --- /dev/null +++ b/docs/matlab_enface_only.md @@ -0,0 +1,39 @@ +# MATLAB enface-only disk output + +Each PSOCTScanConfig has `processing.save_volume_outputs` (default `true`). +Set it to `false` to stop writing per-tile dBI, R3D and O3D NIfTI volumes. +MATLAB still reconstructs intermediate volumes in memory to calculate enface maps. +This saves disk space and write time, not the reconstruction memory allocation. + +Both spectral and complex indexed MATLAB batch routes honor the flag, in serial +and parallel execution. OpticStream bundles the overrides in `opticstream/matlab`; +its normal MATLAB connector puts this path first. No edits to `.venv` are required. + +Enface outputs, raw archives, raw uploads, enface stitching and enface events are +unchanged. Volume output validation, volume stitching, and volume uploads are +skipped. Skipped volume work does not emit volume-success events or set volume +milestones. Existing volume files and completed milestones are not deleted/reset. +Slice registration remains enabled; this setting controls reconstructed tile +volumes and their mosaic outputs, not registration-derived orientation products. + +`processing.save_enface_2d_as_3d` is independent: false stores enface maps as 2D +NIfTI instead of X-by-Y-by-1. `stitch_3d_volumes` remains an independent switch; +enabling volume saving does not override disabled stitching. + +## Enable for an existing block + +Stop the watcher and serve processes first. Run in Miniforge Prompt with the same +PREFECT_API_URL as your services (example uses the current LAN server): + +```bat +cd /d C:\Users\Ayman\Documents\opticstream_nm\opticstream +set "PREFECT_API_URL=http://172.20.126.209:4200/api" +".venv\Scripts\opticstream.exe" oct update-block +".venv\Scripts\python.exe" -c "from opticstream.config.psoct_scan_config import PSOCTScanConfig; b=PSOCTScanConfig.load('human-10um-psoct-config'); b.processing.save_volume_outputs=False; b.save('human-10um-psoct-config', overwrite=True)" +``` + +Replace the block name to target another project. This load/save also migrates +that block to the registered schema, preserving its other values. Refresh the +dashboard to see the new setting under Processing. Restart watcher and serve +processes so cached configs and code are refreshed. No project-state reset is needed +for future batches. Existing completed batches are not automatically reprocessed. diff --git a/opticstream/config/pipeline_opts_builder.py b/opticstream/config/pipeline_opts_builder.py index 17912c7..abaa47d 100644 --- a/opticstream/config/pipeline_opts_builder.py +++ b/opticstream/config/pipeline_opts_builder.py @@ -20,6 +20,17 @@ from opticstream.config.psoct_scan_config import PSOCTScanConfigModel, TileSavingType +class VolumeOutputOpts(OutputOpts): + """Extra flag consumed by OpticStream's bundled indexed batch wrappers.""" + + save_volume_outputs: bool = True + + def to_matlab_struct(self): + result = super().to_matlab_struct() + result["SaveVolumeOutputs"] = self.save_volume_outputs + return result + + def build_pipeline_opts( config: PSOCTScanConfigModel, illumination: str = "normal", @@ -84,6 +95,11 @@ def build_pipeline_opts( surface = SurfaceOpts(spec=proc.surface_spec) + output_opts = VolumeOutputOpts( + **(output_opts.model_dump(exclude={"save_volume_outputs"}) if output_opts else {}), + save_volume_outputs=proc.save_volume_outputs, + ) + return PipelineOpts( spectral=spectral, surface=surface, diff --git a/opticstream/config/psoct_scan_config.py b/opticstream/config/psoct_scan_config.py index ac038f8..f4bed72 100644 --- a/opticstream/config/psoct_scan_config.py +++ b/opticstream/config/psoct_scan_config.py @@ -178,6 +178,14 @@ def validate_scan_resolution_3d(cls, value: List[float]) -> List[float]: class PSOCTProcessingParams(BaseModel): """MATLAB processing parameters that are project-level constants.""" + save_volume_outputs: bool = Field( + default=True, + description=("Save per-tile dBI, R3D and O3D volume files. Disable for enface-only " + "disk output; intermediate volumes are still computed in memory. " + "Also skips volume validation, mosaic volume stitching and volume uploads. " + "Existing files are not deleted; raw archives and enface workflows are unaffected."), + ) + disp_comp_file: Path | None = Field( default=None, description=( diff --git a/opticstream/data_processing/stitch/fiji.py b/opticstream/data_processing/stitch/fiji.py index 873beef..4a674b5 100644 --- a/opticstream/data_processing/stitch/fiji.py +++ b/opticstream/data_processing/stitch/fiji.py @@ -12,6 +12,7 @@ from cyclopts import App DEFAULT_FIJI_PATH = Path("/autofs/cluster/octdata2/users/Hui/Fiji.app/ImageJ-linux64") +#DEFAULT_FIJI_PATH = Path(r"C:\Users\Ayman\Downloads\fiji-latest-win64-jdk\Fiji\fiji-windows-x64.exe") app = App(name="fiji") diff --git a/opticstream/flows/psoct/mosaic_volume_stitch_flow.py b/opticstream/flows/psoct/mosaic_volume_stitch_flow.py index bd1853e..5107bee 100644 --- a/opticstream/flows/psoct/mosaic_volume_stitch_flow.py +++ b/opticstream/flows/psoct/mosaic_volume_stitch_flow.py @@ -281,6 +281,11 @@ def stitch_volume_flow( Dictionary mapping modality to output file paths """ logger = get_run_logger() + if not config.processing.save_volume_outputs: + logger.info("Volume output disabled for this project; skipping volume stitching") + with OCT_STATE_SERVICE.open_mosaic(mosaic_ident=mosaic_ident) as mosaic_state: + mosaic_state.mark_completed() + return {} if should_skip_run( enter_milestone_stage( item_state_view=OCT_STATE_SERVICE.peek_mosaic(mosaic_ident=mosaic_ident), diff --git a/opticstream/flows/psoct/mosaic_volume_upload_flow.py b/opticstream/flows/psoct/mosaic_volume_upload_flow.py index 6ded8d2..c754f5a 100644 --- a/opticstream/flows/psoct/mosaic_volume_upload_flow.py +++ b/opticstream/flows/psoct/mosaic_volume_upload_flow.py @@ -24,6 +24,7 @@ from opticstream.tasks.dandi_upload import upload_to_dandi_batch from opticstream.hooks.slack_notification_hook import slack_notification_hook from opticstream.utils.upload_settings import upload_flow_enabled +from opticstream.utils.volume_settings import volume_output_upload_enabled @flow( @@ -31,6 +32,7 @@ on_completion=[publish_oct_mosaic_hook, publish_oct_project_hook], on_failure=[slack_notification_hook], ) +@volume_output_upload_enabled @upload_flow_enabled @oct_mosaic_processing_milestone( field_name="volume_uploaded", success_event=MOSAIC_VOLUME_UPLOADED diff --git a/opticstream/flows/psoct/tile_batch_processed_validation.py b/opticstream/flows/psoct/tile_batch_processed_validation.py index f3098f0..4a8ed56 100644 --- a/opticstream/flows/psoct/tile_batch_processed_validation.py +++ b/opticstream/flows/psoct/tile_batch_processed_validation.py @@ -50,7 +50,7 @@ def expected_processed_nifti_suffixes(config: PSOCTScanConfigModel) -> tuple[str return tuple( dict.fromkeys( m.value - for modalities in (config.volume_modalities, config.enface_modalities) + for modalities in (config.volume_modalities if config.processing.save_volume_outputs else [], config.enface_modalities) for m in modalities ) ) @@ -73,7 +73,7 @@ def validate_processed_batch_outputs( processed_dir = processed_dir.resolve() grouped_suffixes = { - "volume": tuple(dict.fromkeys(m.value for m in config.volume_modalities)), + "volume": tuple(dict.fromkeys(m.value for m in config.volume_modalities)) if config.processing.save_volume_outputs else (), "enface": tuple(dict.fromkeys(m.value for m in config.enface_modalities)), } diff --git a/opticstream/matlab/+psoct/+file/+internal/applyVolumeOutputPolicy.m b/opticstream/matlab/+psoct/+file/+internal/applyVolumeOutputPolicy.m new file mode 100644 index 0000000..4f7e3e1 --- /dev/null +++ b/opticstream/matlab/+psoct/+file/+internal/applyVolumeOutputPolicy.m @@ -0,0 +1,14 @@ +function outputOpts = applyVolumeOutputPolicy(outputOpts) +% Consume OpticStream's flag after indexed paths have been assigned. +% Empty volume paths disable disk writes, not intermediate reconstruction. +if isfield(outputOpts, 'SaveVolumeOutputs') + enabled = outputOpts.SaveVolumeOutputs; + validateattributes(enabled, {'logical'}, {'scalar'}); + outputOpts = rmfield(outputOpts, 'SaveVolumeOutputs'); + if ~enabled + outputOpts.Paths.dBI = ''; + outputOpts.Paths.R3D = ''; + outputOpts.Paths.O3D = ''; + end +end +end diff --git a/opticstream/matlab/+psoct/+file/complex2processed_batch_indexed.m b/opticstream/matlab/+psoct/+file/complex2processed_batch_indexed.m new file mode 100644 index 0000000..b600e35 --- /dev/null +++ b/opticstream/matlab/+psoct/+file/complex2processed_batch_indexed.m @@ -0,0 +1,119 @@ +function complex2processed_batch_indexed(filenames, outputDir, mosaicId, tileIndices, surfaceOpts, enfaceOpts, acquisitionOpts, outputOpts, volumeOpts, optsMatFile, numWorkers, poolType) +%COMPLEX2PROCESSED_BATCH_INDEXED Batch complex→processed with explicit mosaic/tile indices. +% +% complex2processed_batch_indexed(filenames, outputDir, mosaicId, tileIndices, ... +% surfaceOpts, enfaceOpts, acquisitionOpts, outputOpts, volumeOpts, ... +% optsMatFile, numWorkers, poolType) +% +% Same as complex2processed_batch except output stems are built as +% mosaic_{mosaicId:03d}_image_{tileIndices(k):04d} +% for file k (no basename parsing). numel(tileIndices) must equal numel(filenames). +% +% See psoct.file.internal.buildProcessedOutputPrefix. + +arguments + filenames + outputDir {mustBeText} + mosaicId (1,1) double {mustBeInteger, mustBeNonnegative} + tileIndices double + surfaceOpts struct = struct() + enfaceOpts struct = struct() + acquisitionOpts struct = struct() + outputOpts struct = struct() + volumeOpts struct = struct() + optsMatFile {mustBeTextScalar} = "" + numWorkers double = [] + poolType string {mustBeMember(poolType, ["process","thread"])} = "process" +end + +files = psoct.file.internal.normalizeFilenames(filenames); +tileIndices = tileIndices(:); +if numel(tileIndices) ~= numel(files) + error("psoct:file:complex2processed_batch_indexed:TileIndicesMismatch", ... + "tileIndices must have length %d (number of files), got %d.", ... + numel(files), numel(tileIndices)); +end + +outputDir = string(outputDir); +optsMatFile = string(optsMatFile); + +if optsMatFile ~= "" && ~isfile(optsMatFile) + error("psoct:file:complex2processed_batch_indexed:OptsFileNotFound", ... + "Opts .mat file not found: ""%s"".", optsMatFile); +end + +psoct.file.internal.ensureParpool(numWorkers, poolType); + +modalities = psoct.file.internal.processedModalities(); + +if ~isempty(numWorkers) && numWorkers == 1 + for idx = 1:numel(files) + inFile = files{idx}; + try + prefix = psoct.file.internal.buildProcessedOutputPrefix(mosaicId, tileIndices(idx)); + inDir = string(fileparts(inFile)); + + perOutputOpts = outputOpts; + if ~isfield(perOutputOpts, "Paths") || isempty(perOutputOpts.Paths) + perOutputOpts.Paths = struct(); + end + + baseDir = outputDir; + if strlength(baseDir) == 0 + baseDir = inDir; + end + + for m = 1:numel(modalities) + key = modalities(m); + outName = prefix + "_" + key + ".nii"; + perOutputOpts.Paths.(key) = fullfile(baseDir, outName); + end + + fprintf("complex2processed_batch_indexed: %s -> %s_*\n", inFile, prefix); + + perOutputOpts = psoct.file.internal.applyVolumeOutputPolicy(perOutputOpts); + psoct.file.complex2processed( ... + inFile, surfaceOpts, enfaceOpts, acquisitionOpts, ... + perOutputOpts, volumeOpts, optsMatFile); + catch ME + warning("psoct:file:complex2processed_batch_indexed:FailedFile", ... + "Failed to process %s: %s", inFile, ME.message); + end + end +else +parfor idx = 1:numel(files) + inFile = files{idx}; + try + prefix = psoct.file.internal.buildProcessedOutputPrefix(mosaicId, tileIndices(idx)); + inDir = string(fileparts(inFile)); + + perOutputOpts = outputOpts; + if ~isfield(perOutputOpts, "Paths") || isempty(perOutputOpts.Paths) + perOutputOpts.Paths = struct(); + end + + baseDir = outputDir; + if strlength(baseDir) == 0 + baseDir = inDir; + end + + for m = 1:numel(modalities) + key = modalities(m); + outName = prefix + "_" + key + ".nii"; + perOutputOpts.Paths.(key) = fullfile(baseDir, outName); + end + + fprintf("complex2processed_batch_indexed: %s -> %s_*\n", inFile, prefix); + + perOutputOpts = psoct.file.internal.applyVolumeOutputPolicy(perOutputOpts); + psoct.file.complex2processed( ... + inFile, surfaceOpts, enfaceOpts, acquisitionOpts, ... + perOutputOpts, volumeOpts, optsMatFile); + catch ME + warning("psoct:file:complex2processed_batch_indexed:FailedFile", ... + "Failed to process %s: %s", inFile, ME.message); + end +end +end + +end diff --git a/opticstream/matlab/+psoct/+file/spectral2processed_batch_indexed.m b/opticstream/matlab/+psoct/+file/spectral2processed_batch_indexed.m new file mode 100644 index 0000000..61efc66 --- /dev/null +++ b/opticstream/matlab/+psoct/+file/spectral2processed_batch_indexed.m @@ -0,0 +1,120 @@ +function spectral2processed_batch_indexed(filenames, outputDir, mosaicId, tileIndices, spectralOpts, surfaceOpts, enfaceOpts, acquisitionOpts, outputOpts, volumeOpts, optsMatFile, numWorkers, poolType) +%SPECTRAL2PROCESSED_BATCH_INDEXED Batch spectral→processed with explicit mosaic/tile indices. +% +% spectral2processed_batch_indexed(filenames, outputDir, mosaicId, tileIndices, ... +% spectralOpts, surfaceOpts, enfaceOpts, acquisitionOpts, outputOpts, ... +% volumeOpts, optsMatFile, numWorkers, poolType) +% +% Same as spectral2processed_batch except output stems are built as +% mosaic_{mosaicId:03d}_image_{tileIndices(k):04d} +% for file k (no basename parsing). numel(tileIndices) must equal numel(filenames). +% +% See psoct.file.internal.buildProcessedOutputPrefix. + +arguments + filenames + outputDir {mustBeText} + mosaicId (1,1) double {mustBeInteger, mustBeNonnegative} + tileIndices double + spectralOpts struct = struct() + surfaceOpts struct = struct() + enfaceOpts struct = struct() + acquisitionOpts struct = struct() + outputOpts struct = struct() + volumeOpts struct = struct() + optsMatFile {mustBeTextScalar} = "" + numWorkers double = [] + poolType string {mustBeMember(poolType, ["process","thread"])} = "process" +end + +files = psoct.file.internal.normalizeFilenames(filenames); +tileIndices = tileIndices(:); +if numel(tileIndices) ~= numel(files) + error("psoct:file:spectral2processed_batch_indexed:TileIndicesMismatch", ... + "tileIndices must have length %d (number of files), got %d.", ... + numel(files), numel(tileIndices)); +end + +outputDir = string(outputDir); +optsMatFile = string(optsMatFile); + +if optsMatFile ~= "" && ~isfile(optsMatFile) + error("psoct:file:spectral2processed_batch_indexed:OptsFileNotFound", ... + "Opts .mat file not found: ""%s"".", optsMatFile); +end + +psoct.file.internal.ensureParpool(numWorkers, poolType); + +modalities = psoct.file.internal.processedModalities(); + +if ~isempty(numWorkers) && numWorkers == 1 + for idx = 1:numel(files) + inFile = files{idx}; + try + prefix = psoct.file.internal.buildProcessedOutputPrefix(mosaicId, tileIndices(idx)); + inDir = string(fileparts(inFile)); + + perOutputOpts = outputOpts; + if ~isfield(perOutputOpts, "Paths") || isempty(perOutputOpts.Paths) + perOutputOpts.Paths = struct(); + end + + baseDir = outputDir; + if strlength(baseDir) == 0 + baseDir = inDir; + end + + for m = 1:numel(modalities) + key = modalities(m); + outName = prefix + "_" + key + ".nii"; + perOutputOpts.Paths.(key) = fullfile(baseDir, outName); + end + + fprintf("spectral2processed_batch_indexed: %s -> %s_*\n", inFile, prefix); + + perOutputOpts = psoct.file.internal.applyVolumeOutputPolicy(perOutputOpts); + psoct.file.spectral2processed( ... + inFile, spectralOpts, surfaceOpts, enfaceOpts, ... + acquisitionOpts, perOutputOpts, volumeOpts, optsMatFile); + catch ME + warning("psoct:file:spectral2processed_batch_indexed:FailedFile", ... + "Failed to process %s: %s", inFile, ME.message); + end + end +else +parfor idx = 1:numel(files) + inFile = files{idx}; + try + prefix = psoct.file.internal.buildProcessedOutputPrefix(mosaicId, tileIndices(idx)); + inDir = string(fileparts(inFile)); + + perOutputOpts = outputOpts; + if ~isfield(perOutputOpts, "Paths") || isempty(perOutputOpts.Paths) + perOutputOpts.Paths = struct(); + end + + baseDir = outputDir; + if strlength(baseDir) == 0 + baseDir = inDir; + end + + for m = 1:numel(modalities) + key = modalities(m); + outName = prefix + "_" + key + ".nii"; + perOutputOpts.Paths.(key) = fullfile(baseDir, outName); + end + + fprintf("spectral2processed_batch_indexed: %s -> %s_*\n", inFile, prefix); + + perOutputOpts = psoct.file.internal.applyVolumeOutputPolicy(perOutputOpts); + psoct.file.spectral2processed( ... + inFile, spectralOpts, surfaceOpts, enfaceOpts, ... + acquisitionOpts, perOutputOpts, volumeOpts, optsMatFile); + catch ME + warning("psoct:file:spectral2processed_batch_indexed:FailedFile", ... + "Failed to process %s: %s", inFile, ME.message); + end +end +end + +end diff --git a/opticstream/utils/volume_settings.py b/opticstream/utils/volume_settings.py new file mode 100644 index 0000000..61a673e --- /dev/null +++ b/opticstream/utils/volume_settings.py @@ -0,0 +1,22 @@ +"""Guard volume uploads before milestone bookkeeping, including stale events.""" +from functools import wraps +from inspect import signature + +from prefect.logging.loggers import get_logger +from opticstream.config.psoct_scan_config import get_psoct_scan_config + + +def volume_output_upload_enabled(func): + sig = signature(func) + + @wraps(func) + def wrapper(*args, **kwargs): + bound = sig.bind(*args, **kwargs) + ident = bound.arguments["mosaic_ident"] + config = get_psoct_scan_config(ident.project_name) + if not config.processing.save_volume_outputs: + get_logger(__name__).info("Volume output disabled for %s; skipping volume upload", ident.project_name) + return {"uploaded": 0} + return func(*args, **kwargs) + + return wrapper diff --git a/pyproject.toml b/pyproject.toml index 3535b8c..1cea494 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -53,7 +53,7 @@ include = ["opticstream*"] exclude = ["notebooks*"] [tool.setuptools.package-data] -opticstream = ["matlab/*.m", "matlab/+psoct/+spectral/*.m", "matlab/*.md"] +opticstream = ["matlab/*.m", "matlab/+psoct/+spectral/*.m", "matlab/+psoct/+file/*.m", "matlab/+psoct/+file/+internal/*.m", "matlab/*.md"] [tool.pytest.ini_options] addopts = '-m "not integration"' diff --git a/tests/matlab/test_volume_output_policy.m b/tests/matlab/test_volume_output_policy.m new file mode 100644 index 0000000..e697446 --- /dev/null +++ b/tests/matlab/test_volume_output_policy.m @@ -0,0 +1,22 @@ +function test_volume_output_policy() +paths = struct('dBI', 'dBI.nii', 'R3D', 'R3D.nii', 'O3D', 'O3D.nii', 'aip', 'aip.nii'); +for enabled = [false, true] + opts = psoct.file.internal.applyVolumeOutputPolicy(struct('Paths', paths, 'SaveVolumeOutputs', enabled)); + assert(~isfield(opts, 'SaveVolumeOutputs')); + assert(strcmp(opts.Paths.aip, 'aip.nii')); + for name = ["dBI", "R3D", "O3D"] + if enabled + assert(strcmp(opts.Paths.(name), paths.(name))); + else + assert(isempty(opts.Paths.(name))); + future = psoct.internal.nifti.writeNiftiIfPath(opts.Paths.(name), zeros(2,2,2), struct()); + assert(isempty(future)); + end + end + normalized = psoct.internal.opts.normalizeOutputOpts(opts); + assert(strcmp(normalized.Paths.aip, 'aip.nii')); +end +opts = psoct.file.internal.applyVolumeOutputPolicy(struct('Paths', paths)); +assert(isequal(opts.Paths, paths)); +disp('Volume output policy tests passed'); +end diff --git a/tests/test_volume_output_setting.py b/tests/test_volume_output_setting.py new file mode 100644 index 0000000..a37e9c9 --- /dev/null +++ b/tests/test_volume_output_setting.py @@ -0,0 +1,91 @@ +from contextlib import contextmanager +from types import SimpleNamespace +from unittest.mock import Mock, patch + +import unittest +from tempfile import TemporaryDirectory +from pathlib import Path +from niizarr import ZarrConfig +from psoct_toolbox.matlab_bridge import build_spectral2processed_batch_indexed_command, build_complex2processed_batch_indexed_command + +from opticstream.config.pipeline_opts_builder import build_pipeline_opts +from opticstream.config.psoct_scan_config import PSOCTScanConfigModel, PSOCTProcessingParams +from opticstream.flows.psoct.tile_batch_processed_validation import validate_processed_batch_outputs +from opticstream.flows.psoct.tile_file_reference import TileFileReference +from opticstream.state.oct_project_state import OCTMosaicId + + +def config(tmp_path, enabled): + return PSOCTScanConfigModel(project_name="test", project_base_path=tmp_path, + acquisition=dict(grid_size_x_normal=1, grid_size_x_tilted=1, grid_size_y=1), + processing=dict(save_volume_outputs=enabled), enface_modalities=["aip"], zarr_config=ZarrConfig()) + + +def _check_command_flag_and_enface_validation(tmp_path, enabled): + cfg = config(tmp_path, enabled) + opts = build_pipeline_opts(cfg) + for builder in (build_spectral2processed_batch_indexed_command, build_complex2processed_batch_indexed_command): + command = builder(["input.nii"], output_dir=str(tmp_path), mosaic_id=1, tile_indices=[1], pipeline_opts=opts) + assert f"'SaveVolumeOutputs', {str(enabled).lower()}" in command + (tmp_path / "mosaic_001_image_0001_aip.nii").write_bytes(b"enface") + args = dict(processed_dir=tmp_path, file_reference_list=[TileFileReference(tile_number=1)], + mosaic_id=1, config=cfg, min_enface_file_size_bytes=1) + if enabled: + with unittest.TestCase().assertRaisesRegex(RuntimeError, "volume"): + validate_processed_batch_outputs(**args) + else: + validate_processed_batch_outputs(**args) + (tmp_path / "mosaic_001_image_0001_aip.nii").unlink() + with unittest.TestCase().assertRaisesRegex(RuntimeError, "enface"): + validate_processed_batch_outputs(**args) + + +def _check_existing_blocks_default_enabled(): + assert PSOCTProcessingParams.model_validate({}).save_volume_outputs is True + + +def _check_disabled_upload_skips_all_milestones(tmp_path): + from opticstream.flows.psoct.mosaic_volume_upload_flow import upload_mosaic_volume_to_dandi_flow + cfg = config(tmp_path, False) + with patch("opticstream.utils.volume_settings.get_psoct_scan_config", return_value=cfg), \ + patch("opticstream.state.milestone_wrappers_psoct.OCT_STATE_SERVICE") as state, \ + patch("opticstream.flows.psoct.mosaic_volume_upload_flow.upload_to_dandi_batch") as upload: + result = upload_mosaic_volume_to_dandi_flow.fn( + mosaic_ident=OCTMosaicId(project_name="test", slice_id=1, mosaic_id=1), volume_outputs={"dBI": "old.nii"}) + assert result == {"uploaded": 0} + assert not state.mock_calls + upload.assert_not_called() + + +def _check_disabled_stitch_skips_before_volume_milestone(tmp_path): + from opticstream.flows.psoct import mosaic_volume_stitch_flow as module + @contextmanager + def opened(**kwargs): + yield Mock() + with patch.object(module, "get_run_logger", return_value=Mock()), \ + patch.object(module.OCT_STATE_SERVICE, "open_mosaic", side_effect=opened), \ + patch.object(module, "enter_milestone_stage") as enter, \ + patch.object(module, "emit_mosaic_psoct_event") as emit: + result = module.stitch_volume_flow.fn( + mosaic_ident=OCTMosaicId(project_name="test", slice_id=1, mosaic_id=1), config=config(tmp_path, False)) + assert result == {} + enter.assert_not_called() + emit.assert_not_called() + + +class VolumeOutputTests(unittest.TestCase): + def test_commands_and_validation(self): + for enabled in (True, False): + with self.subTest(enabled=enabled), TemporaryDirectory() as folder: + _check_command_flag_and_enface_validation(Path(folder), enabled) + + def test_default(self): + _check_existing_blocks_default_enabled() + + def test_upload(self): + with TemporaryDirectory() as folder: + _check_disabled_upload_skips_all_milestones(Path(folder)) + + def test_stitch(self): + with TemporaryDirectory() as folder: + _check_disabled_stitch_skips_before_volume_milestone(Path(folder)) From 8cdd1284b8044b854c0584042615a2e88266d035 Mon Sep 17 00:00:00 2001 From: NoahMarkowitz Date: Mon, 21 Sep 2026 08:54:05 -0400 Subject: [PATCH 17/65] add opts for calibrated files --- docs/phase_calibration.md | 82 +++++++++++++++++++ opticstream/config/pipeline_opts_builder.py | 32 +++++++- opticstream/config/psoct_scan_config.py | 22 +++++ .../+internal/+opts/normalizeSpectralOpts.m | 38 +++++++++ .../+psoct/+spectral/loadPhaseCalibration.m | 54 ++++++++++++ .../+psoct/+spectral/spectral2complex.m | 39 +++++++-- pyproject.toml | 2 +- tests/matlab/test_phase_calibration.m | 67 +++++++++++++++ tests/test_phase_calibration.py | 66 +++++++++++++++ 9 files changed, 393 insertions(+), 9 deletions(-) create mode 100644 docs/phase_calibration.md create mode 100644 opticstream/matlab/+psoct/+internal/+opts/normalizeSpectralOpts.m create mode 100644 opticstream/matlab/+psoct/+spectral/loadPhaseCalibration.m create mode 100644 tests/matlab/test_phase_calibration.m create mode 100644 tests/test_phase_calibration.py diff --git a/docs/phase_calibration.md b/docs/phase_calibration.md new file mode 100644 index 0000000..aac4eec --- /dev/null +++ b/docs/phase_calibration.md @@ -0,0 +1,82 @@ +# Phase-calibrated spectral interpolation + +PSOCTScanConfig now exposes these per-project `processing` settings: + +| Field | Default | Meaning | +| --- | --- | --- | +| interpolation_method | wavelength | Existing wavelength calibration, or phase_calibration | +| interpolation_path | null | Directory containing dphase.mat and linPhase.mat | +| phase_calibration_dispersion | false | Also load dspPhase.mat instead of disp_comp_file | +| flip_channel2_spectra | null | Automatic: true for wavelength, false for phase_calibration. Set explicitly to override. | + +MAT files must contain variables with the matching names: `dphase`, `linPhase`, +and optionally `dspPhase`. Each must be a real finite vector with one entry per +acquired spectral sample (1152 entries for 1152-sample input). Row and column +vectors are accepted. dphase must be strictly monotonic; linPhase must be strictly +monotonic and uniformly spaced. The target length currently must equal the source +length. Extrapolation is permitted and produces a warning. + +The new interpolation is applied to all A-lines in each B-line: + +```matlab +interp1(dphase(:), backgroundSubtractedBuffer, linPhase(:), 'linear', 'extrap') +``` + +It bypasses wave-pixel.mat and the legacy ZeroPadBuffer helper. Both channels use +the same phase coordinates. They must describe the data ordering after the optional +channel-2 reversal. This implementation does not assume that the shared calibration +is valid for both detectors; verify that against your calibration procedure. + +When phase_calibration_dispersion is true, dspPhase must contain phase angles in +radians; both channels receive `exp(-1i*dspPhase(:))`. Otherwise the existing +disp_comp_file reader and its separate channel corrections remain in use. Ensure +those coefficients match the new target sampling grid. + +This changes interpolation, not the entire reconstruction algorithm. Reference +subtraction across A-lines, post-interpolation median subtraction, the 24-bin +autocorrelation crop, and existing Jones storage conventions remain unchanged. +The output depth for 1152 samples remains 552. It does not reproduce the supplied +script's B-line reference averaging or zero-bin crop. + +## Enable for a project + +Stop the watcher and serve processes. Register the schema using the project's +virtual environment and your existing PREFECT_API_URL: + +```bat +".venv\Scripts\opticstream.exe" oct update-block +``` + +For an existing block, use this in a notebook connected to the same Prefect server: + +```python +from pathlib import Path +from opticstream.config.psoct_scan_config import PSOCTScanConfig + +block = await PSOCTScanConfig.load("human-10um-psoct-config") +block.processing.interpolation_method = "phase_calibration" +block.processing.interpolation_path = Path(r"D:\data\calibration") +block.processing.phase_calibration_dispersion = True # Use your dspPhase.mat +block.processing.flip_channel2_spectra = False # Original acquisition order +await block.save("human-10um-psoct-config", overwrite=True) +``` + +Refresh the dashboard and restart watcher/serve processes. Calibration files must +be readable on the machine executing MATLAB. Existing completed batches are not +automatically reprocessed. Set interpolation_method back to wavelength and +phase_calibration_dispersion to false to restore the old route; use null for the +automatic channel-order selection. + +All MATLAB changes are bundled beneath `opticstream/matlab/+psoct`; no installed +toolbox files are modified. For direct MATLAB use, add the installed toolbox root, +then add `opticstream/matlab` with `'-begin'`, followed by `clear functions; rehash`. +# Individual calibration files + +Under the block's `processing` settings, set `dphase_file`, `lin_phase_file`, +and optionally `dsp_phase_file` to full paths accessible to the MATLAB machine. +Each explicit path overrides the corresponding file in `interpolation_path`. +The directory can be omitted when all required individual paths are supplied. +Filenames may differ, but the variables inside must remain `dphase`, `linPhase`, +and `dspPhase`, respectively. Set `interpolation_method="phase_calibration"`; +`dsp_phase_file` is used only with `phase_calibration_dispersion=true`. +Existing directory-based configurations remain supported. diff --git a/opticstream/config/pipeline_opts_builder.py b/opticstream/config/pipeline_opts_builder.py index abaa47d..2bac1f0 100644 --- a/opticstream/config/pipeline_opts_builder.py +++ b/opticstream/config/pipeline_opts_builder.py @@ -4,6 +4,7 @@ import math from typing import Optional +from pydantic import Field from prefect import get_run_logger from psoct_toolbox.opts_models import ( @@ -31,6 +32,18 @@ def to_matlab_struct(self): return result +class CalibratedSpectralOpts(SpectralOpts): + """OpticStream extensions serialized by the existing toolbox bridge.""" + + interpolation_method: str = Field(default="wavelength", alias="interpolationMethod") + interpolation_path: Optional[str] = Field(default=None, alias="interpolationPath") + dphase_file: Optional[str] = Field(default=None, alias="dphaseFile") + lin_phase_file: Optional[str] = Field(default=None, alias="linPhaseFile") + dsp_phase_file: Optional[str] = Field(default=None, alias="dspPhaseFile") + phase_calibration_dispersion: bool = Field(default=False, alias="phaseCalibrationDispersion") + flip_channel2_spectra: bool = Field(default=True, alias="flipChannel2Spectra") + + def build_pipeline_opts( config: PSOCTScanConfigModel, illumination: str = "normal", @@ -57,11 +70,26 @@ def build_pipeline_opts( aline_size = ( acq.tile_size_x_normal if illumination == "normal" else acq.tile_size_x_tilted ) - spectral = SpectralOpts( - disp_comp_file=str(proc.disp_comp_file), + if proc.interpolation_method == "phase_calibration" and proc.interpolation_path is None: + if proc.dphase_file is None or proc.lin_phase_file is None: + raise ValueError("phase_calibration requires dphase_file and lin_phase_file, or interpolation_path") + if proc.phase_calibration_dispersion and proc.dsp_phase_file is None: + raise ValueError("phase_calibration_dispersion requires dsp_phase_file or interpolation_path") + if proc.phase_calibration_dispersion and proc.interpolation_method != "phase_calibration": + raise ValueError("phase_calibration_dispersion requires phase_calibration interpolation") + spectral = CalibratedSpectralOpts( + disp_comp_file=str(proc.disp_comp_file) if proc.disp_comp_file is not None else None, aline_size=aline_size, bline_size=acq.tile_size_y, is_raw_format=(acq.tile_saving_type == TileSavingType.SPECTRAL_12bit), + interpolation_method=proc.interpolation_method, + interpolation_path=str(proc.interpolation_path) if proc.interpolation_path is not None else None, + dphase_file=str(proc.dphase_file) if proc.dphase_file is not None else None, + lin_phase_file=str(proc.lin_phase_file) if proc.lin_phase_file is not None else None, + dsp_phase_file=str(proc.dsp_phase_file) if proc.dsp_phase_file is not None else None, + phase_calibration_dispersion=proc.phase_calibration_dispersion, + flip_channel2_spectra=(proc.flip_channel2_spectra if proc.flip_channel2_spectra is not None + else proc.interpolation_method == "wavelength"), ) compute = EnfaceComputeFlags( diff --git a/opticstream/config/psoct_scan_config.py b/opticstream/config/psoct_scan_config.py index f4bed72..a89c0d0 100644 --- a/opticstream/config/psoct_scan_config.py +++ b/opticstream/config/psoct_scan_config.py @@ -178,6 +178,28 @@ def validate_scan_resolution_3d(cls, value: List[float]) -> List[float]: class PSOCTProcessingParams(BaseModel): """MATLAB processing parameters that are project-level constants.""" + interpolation_method: Literal["wavelength", "phase_calibration"] = Field( + default="wavelength", description="wavelength preserves the existing wave-pixel calibration. phase_calibration interpolates from dphase onto linPhase loaded from interpolation_path.", + ) + interpolation_path: Path | None = Field( + default=None, description="Calibration directory containing dphase.mat (variable dphase) and linPhase.mat (variable linPhase). Both must be real, finite vectors matching the spectral sample count; linPhase must be uniformly spaced.", + ) + dphase_file: Path | None = Field( + default=None, description="Path to the .mat file containing variable dphase. Overrides interpolation_path/dphase.mat. Real finite vector matching the spectral sample count.", + ) + lin_phase_file: Path | None = Field( + default=None, description="Path to the .mat file containing variable linPhase. Overrides interpolation_path/linPhase.mat. Uniformly spaced real finite vector matching the spectral sample count.", + ) + dsp_phase_file: Path | None = Field( + default=None, description="Path to the .mat file containing variable dspPhase (radians). Overrides interpolation_path/dspPhase.mat. Used only when phase_calibration_dispersion is true; vector length must match the spectral sample count.", + ) + phase_calibration_dispersion: bool = Field( + default=False, description="In phase_calibration mode, use dspPhase.mat (variable dspPhase, radians) from interpolation_path for both channels instead of disp_comp_file. False preserves the existing channel-specific dispersion correction.", + ) + flip_channel2_spectra: bool | None = Field( + default=None, description="Reverse channel 2 along the spectral axis before interpolation. null selects true for wavelength mode (legacy behavior), false for phase_calibration. Calibration vectors must describe the selected sample ordering.", + ) + save_volume_outputs: bool = Field( default=True, description=("Save per-tile dBI, R3D and O3D volume files. Disable for enface-only " diff --git a/opticstream/matlab/+psoct/+internal/+opts/normalizeSpectralOpts.m b/opticstream/matlab/+psoct/+internal/+opts/normalizeSpectralOpts.m new file mode 100644 index 0000000..755e91c --- /dev/null +++ b/opticstream/matlab/+psoct/+internal/+opts/normalizeSpectralOpts.m @@ -0,0 +1,38 @@ +function spectralOpts = normalizeSpectralOpts(spectralOpts) +% OpticStream spectral options; legacy defaults remain unchanged. +nargs = namedargs2cell(spectralOpts); +spectralOpts = iNormalizeSpectralOpts(nargs{:}); +if isempty(spectralOpts.flipChannel2Spectra) + spectralOpts.flipChannel2Spectra = spectralOpts.interpolationMethod == "wavelength"; +end +if spectralOpts.interpolationMethod == "phase_calibration" && strlength(spectralOpts.interpolationPath) == 0 + if strlength(spectralOpts.dphaseFile) == 0 || strlength(spectralOpts.linPhaseFile) == 0 + error('psoct:calibration:MissingPath', 'Specify dphaseFile and linPhaseFile, or interpolationPath.'); + end + if spectralOpts.phaseCalibrationDispersion && strlength(spectralOpts.dspPhaseFile) == 0 + error('psoct:calibration:MissingPath', 'Specify dspPhaseFile or interpolationPath for phase dispersion.'); + end +end +if spectralOpts.phaseCalibrationDispersion && spectralOpts.interpolationMethod ~= "phase_calibration" + error('psoct:calibration:InvalidMode', 'phaseCalibrationDispersion requires phase_calibration.'); +end +end + +function nargs = iNormalizeSpectralOpts(nargs) +arguments + nargs.dispCompFile {mustBeTextScalar} = psoct.internal.getDataFile("LSM03_mineral_oil_placecorrectionmeanall2.dat") + nargs.AlineSize (1,1) int32 {mustBeInteger, mustBePositive} = 200 + nargs.BlineSize (1,1) int32 {mustBeInteger, mustBePositive} = 350 + nargs.isRawFormat (1,1) logical = false + nargs.interpolationMethod (1,1) string {mustBeMember(nargs.interpolationMethod, ["wavelength", "phase_calibration"])} = "wavelength" + nargs.interpolationPath (1,1) string = "" + nargs.dphaseFile (1,1) string = "" + nargs.linPhaseFile (1,1) string = "" + nargs.dspPhaseFile (1,1) string = "" + nargs.phaseCalibrationDispersion (1,1) logical = false + nargs.flipChannel2Spectra logical = [] +end +if ~isempty(nargs.flipChannel2Spectra) && ~isscalar(nargs.flipChannel2Spectra) + error('psoct:calibration:InvalidFlip', 'flipChannel2Spectra must be a scalar logical.'); +end +end diff --git a/opticstream/matlab/+psoct/+spectral/loadPhaseCalibration.m b/opticstream/matlab/+psoct/+spectral/loadPhaseCalibration.m new file mode 100644 index 0000000..c9fb85c --- /dev/null +++ b/opticstream/matlab/+psoct/+spectral/loadPhaseCalibration.m @@ -0,0 +1,54 @@ +function calibration = loadPhaseCalibration(folder, sampleCount, useDispersion, dphaseFile, linPhaseFile, dspPhaseFile) +% Shared calibration for both channels, in their selected spectral ordering. +arguments + folder (1,1) string + sampleCount (1,1) double {mustBeInteger, mustBePositive} + useDispersion (1,1) logical = false + dphaseFile (1,1) string = "" + linPhaseFile (1,1) string = "" + dspPhaseFile (1,1) string = "" +end +calibration.dphase = readVector(folder, 'dphase', sampleCount, dphaseFile); +calibration.linPhase = readVector(folder, 'linPhase', sampleCount, linPhaseFile); +delta = diff(calibration.dphase); +if ~(all(delta > 0) || all(delta < 0)) + error('psoct:calibration:NonMonotonic', 'dphase must be strictly monotonic with no repeated samples.'); +end +delta = diff(calibration.linPhase); +if ~(all(delta > 0) || all(delta < 0)) + error('psoct:calibration:NonMonotonic', 'linPhase must be strictly monotonic.'); +end +tolerance = max(abs(mean(delta))*1e-5, 100*eps(max(abs(calibration.linPhase)))); +if any(abs(delta - mean(delta)) > tolerance) + error('psoct:calibration:NonUniform', 'linPhase must be uniformly spaced.'); +end +if min(calibration.linPhase) < min(calibration.dphase) || max(calibration.linPhase) > max(calibration.dphase) + warning('psoct:calibration:Extrapolation', 'linPhase extends beyond dphase; linear extrapolation will be used.'); +end +calibration.dispersion = []; +if useDispersion + dspPhase = readVector(folder, 'dspPhase', sampleCount, dspPhaseFile); + calibration.dispersion = exp(-1i .* dspPhase); +end +end + +function vector = readVector(folder, name, sampleCount, filename) +if strlength(filename) == 0 + if strlength(folder) == 0 + error('psoct:calibration:MissingPath', 'Specify a file path for %s or a calibration directory.', name); + end + filename = fullfile(folder, [name '.mat']); +end +if ~isfile(filename) + error('psoct:calibration:MissingFile', 'Calibration file not found: %s', filename); +end +loaded = load(filename, name); +if ~isfield(loaded, name) + error('psoct:calibration:MissingVariable', '%s must contain variable %s.', filename, name); +end +vector = loaded.(name); +if ~isnumeric(vector) || ~isreal(vector) || ~isvector(vector) || numel(vector) ~= sampleCount || any(~isfinite(vector(:))) + error('psoct:calibration:InvalidVector', '%s must contain a real finite vector of %d samples.', name, sampleCount); +end +vector = double(vector(:)); +end diff --git a/opticstream/matlab/+psoct/+spectral/spectral2complex.m b/opticstream/matlab/+psoct/+spectral/spectral2complex.m index 0121333..5bea857 100644 --- a/opticstream/matlab/+psoct/+spectral/spectral2complex.m +++ b/opticstream/matlab/+psoct/+spectral/spectral2complex.m @@ -95,11 +95,22 @@ OriginalLineLength1, Start1, ... OriginalLineLength2, Start2]; -[Wavelengths_l, Wavelengths_r, InterpolatedWavelengths2, Ks] = ... - opticstream_interpolationwave(InterpolationParameters); %#ok +phaseMode = spectralOpts.interpolationMethod == "phase_calibration"; +Wavelengths_l = []; Wavelengths_r = []; InterpolatedWavelengths2 = []; +calibration = struct(); +if phaseMode + calibration = psoct.spectral.loadPhaseCalibration( ... + spectralOpts.interpolationPath, AlineLength, spectralOpts.phaseCalibrationDispersion, ... + spectralOpts.dphaseFile, spectralOpts.linPhaseFile, spectralOpts.dspPhaseFile); +else + [Wavelengths_l, Wavelengths_r, InterpolatedWavelengths2, Ks] = ... + opticstream_interpolationwave(InterpolationParameters); %#ok +end % Package parameters that are shared across B-lines params = struct(); +params.phaseMode = phaseMode; +params.calibration = calibration; params.AlineSize = AlineSize; params.BlineSize = BlineSize; params.AlineLength = AlineLength; @@ -117,8 +128,13 @@ params.InterpolatedWavelengths = InterpolatedWavelengths2; % Read the channel-specific corrections from the two halves of one file. -[phaseCorrection1, phaseCorrection2] = ... - opticstream_read_dispersion(dispCompFile, AlineLength); +if phaseMode && spectralOpts.phaseCalibrationDispersion + phaseCorrection1 = calibration.dispersion; + phaseCorrection2 = calibration.dispersion; +else + [phaseCorrection1, phaseCorrection2] = ... + opticstream_read_dispersion(dispCompFile, AlineLength); +end % Replicate along A-line dimension to match interpolated buffer size phaseCorrection1 = repmat(phaseCorrection1, 1, Aline); @@ -162,7 +178,10 @@ fid, blineIndex, params, isRawFormat, HEADER_BYTES); else WavelengthBuffer1 = double(niftiData(:, 1:Aline, blineIndex)); - WavelengthBuffer2 = flipud(double(niftiData(:, Aline+1:2*Aline, blineIndex))); + WavelengthBuffer2 = double(niftiData(:, Aline+1:2*Aline, blineIndex)); + end + if spectralOpts.flipChannel2Spectra + WavelengthBuffer2 = flipud(WavelengthBuffer2); end % Convert spectral buffers into Jones vectors for this B-line @@ -240,7 +259,7 @@ end WavelengthBuffer1 = reshape(data1, params.AlineLength, []); -WavelengthBuffer2 = flipud(reshape(data2, params.AlineLength, [])); +WavelengthBuffer2 = reshape(data2, params.AlineLength, []); end function [Jones1, Jones2] = processBlineBuffers( ... @@ -265,6 +284,13 @@ OriginalBuffer1 = MeanScan1(Start1:OriginalLineLength1 - 1 + Start1, :); OriginalBuffer2 = MeanScan2(Start2:OriginalLineLength2 - 1 + Start2, :); +if params.phaseMode + % Each column is an A-line. Calibration is shared by both channels. + InterpolatedBuffer1 = interp1(params.calibration.dphase, OriginalBuffer1, ... + params.calibration.linPhase, 'linear', 'extrap'); + InterpolatedBuffer2 = interp1(params.calibration.dphase, OriginalBuffer2, ... + params.calibration.linPhase, 'linear', 'extrap'); +else % Zero padding ZeroPaddedBuffer1 = OriginalBuffer1; % PaddingFactor is one; preserve arbitrary sample counts. ZeroPaddedBuffer2 = OriginalBuffer2; @@ -279,6 +305,7 @@ params.InterpolatedWavelengths, 'linear', 'extrap'); InterpolatedBuffer2 = interp1(params.Wavelengths_r, ZeroPaddedBuffer2, ... params.InterpolatedWavelengths, 'linear', 'extrap'); +end % Remove DC component using median across A-lines InterpolatedBuffer1 = InterpolatedBuffer1 - median(InterpolatedBuffer1, 2); diff --git a/pyproject.toml b/pyproject.toml index 1cea494..e384843 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -53,7 +53,7 @@ include = ["opticstream*"] exclude = ["notebooks*"] [tool.setuptools.package-data] -opticstream = ["matlab/*.m", "matlab/+psoct/+spectral/*.m", "matlab/+psoct/+file/*.m", "matlab/+psoct/+file/+internal/*.m", "matlab/*.md"] +opticstream = ["matlab/*.m", "matlab/+psoct/+spectral/*.m", "matlab/+psoct/+internal/+opts/*.m", "matlab/+psoct/+file/*.m", "matlab/+psoct/+file/+internal/*.m", "matlab/*.md"] [tool.pytest.ini_options] addopts = '-m "not integration"' diff --git a/tests/matlab/test_phase_calibration.m b/tests/matlab/test_phase_calibration.m new file mode 100644 index 0000000..78c78e9 --- /dev/null +++ b/tests/matlab/test_phase_calibration.m @@ -0,0 +1,67 @@ +function test_phase_calibration +folder = tempname; +mkdir(folder); +cleanup = onCleanup(@() rmdir(folder, 's')); +N = 1152; +dphase = linspace(0, 1, N).^1.3; % Nonuniform measured phase, row vector +linPhase = linspace(0, 1, N)'; +dspPhase = linspace(0, 0.2, N); +save(fullfile(folder, 'dphase.mat'), 'dphase'); +save(fullfile(folder, 'linPhase.mat'), 'linPhase'); +save(fullfile(folder, 'dspPhase.mat'), 'dspPhase'); +cal = psoct.spectral.loadPhaseCalibration(folder, N, true); +assert(isequal(size(cal.dphase), [N 1])); +assert(max(abs(cal.dispersion - exp(-1i*dspPhase(:)))) < 1e-12); +save(fullfile(folder, 'custom-d.mat'), 'dphase'); +save(fullfile(folder, 'custom-l.mat'), 'linPhase'); +save(fullfile(folder, 'custom-s.mat'), 'dspPhase'); +explicit = psoct.spectral.loadPhaseCalibration("", N, true, ... + fullfile(folder, 'custom-d.mat'), fullfile(folder, 'custom-l.mat'), fullfile(folder, 'custom-s.mat')); +assert(isequal(cal, explicit)); +mixed = psoct.spectral.loadPhaseCalibration(folder, N, true, fullfile(folder, 'custom-d.mat')); +assert(isequal(cal, mixed)); +defaults = psoct.internal.opts.normalizeSpectralOpts(struct()); +assert(defaults.flipChannel2Spectra); +for reversed = [false true] + rng(42); + data = int16(randi([-1000 1000], N, 8, 2)); + input = fullfile(folder, 'input.nii'); + niftiwrite(data, input); + opts = struct('interpolationMethod', 'phase_calibration', 'interpolationPath', folder, ... + 'phaseCalibrationDispersion', true, 'flipChannel2Spectra', reversed); + if reversed + opts.interpolationPath = ""; + opts.dphaseFile = fullfile(folder, 'custom-d.mat'); + opts.linPhaseFile = fullfile(folder, 'custom-l.mat'); + opts.dspPhaseFile = fullfile(folder, 'custom-s.mat'); + end + [actual1, actual2] = psoct.spectral.spectral2complex(input, opts, struct()); + expected = complex(zeros(4, 2, N/2-24, 2)); + for b = 1:2 + for channel = 1:2 + buffer = double(data(:, (channel-1)*4+(1:4), b)); + if channel == 2 && reversed, buffer = flipud(buffer); end + buffer = buffer - mean(buffer, 2); + buffer = interp1(dphase(:), buffer, linPhase(:), 'linear', 'extrap'); + buffer = buffer - median(buffer, 2); + buffer = buffer .* exp(-1i*dspPhase(:)); + depth = fft(buffer); + % Existing toolbox uses a conjugate transpose when storing Jones data. + expected(:,b,:,channel) = depth(25:N/2,:)'; + end + end + delta = abs(actual1 - expected(:,:,:,1)); assert(max(delta(:)) < 1e-8); + delta = abs(actual2 - expected(:,:,:,2)); assert(max(delta(:)) < 1e-8); +end +% Invalid vectors fail explicitly. +dphase(2) = dphase(1); +save(fullfile(folder, 'dphase.mat'), 'dphase'); +rejected = false; +try + psoct.spectral.loadPhaseCalibration(folder, N, false); +catch ME + rejected = strcmp(ME.identifier, 'psoct:calibration:NonMonotonic'); +end +assert(rejected); +disp('Phase calibration tests passed'); +end diff --git a/tests/test_phase_calibration.py b/tests/test_phase_calibration.py new file mode 100644 index 0000000..2c7084f --- /dev/null +++ b/tests/test_phase_calibration.py @@ -0,0 +1,66 @@ +import unittest +from niizarr import ZarrConfig +from opticstream.config.psoct_scan_config import PSOCTScanConfigModel +from opticstream.config.pipeline_opts_builder import build_pipeline_opts +from psoct_toolbox.matlab_bridge import build_spectral2processed_batch_indexed_command + + +class PhaseCalibrationTests(unittest.TestCase): + def config(self, **processing): + return PSOCTScanConfigModel(project_name="test", project_base_path="D:/test", + acquisition=dict(grid_size_x_normal=1, grid_size_x_tilted=1, grid_size_y=1), + processing=processing, zarr_config=ZarrConfig()) + + def test_legacy_defaults(self): + opts = build_pipeline_opts(self.config()).spectral.to_matlab_struct() + self.assertEqual(opts["interpolationMethod"], "wavelength") + self.assertTrue(opts["flipChannel2Spectra"]) + self.assertFalse(opts["phaseCalibrationDispersion"]) + self.assertNotIn("dispCompFile", opts) # MATLAB default, not literal 'None' + + def test_bridge(self): + cfg = self.config(interpolation_method="phase_calibration", interpolation_path="D:/calibration", + phase_calibration_dispersion=True) + opts = build_pipeline_opts(cfg) + values = opts.spectral.to_matlab_struct() + self.assertFalse(values["flipChannel2Spectra"]) + command = build_spectral2processed_batch_indexed_command(["input.nii"], output_dir="output", + mosaic_id=1, tile_indices=[1], pipeline_opts=opts) + for token in ("'interpolationMethod', 'phase_calibration'", "'phaseCalibrationDispersion', true", + "'flipChannel2Spectra', false", "'interpolationPath'"): + self.assertIn(token, command) + + def test_invalid_options(self): + for opts in (dict(interpolation_method="phase_calibration"), dict(phase_calibration_dispersion=True)): + with self.assertRaises(ValueError): + build_pipeline_opts(self.config(**opts)) + + def test_individual_files(self): + cfg = self.config(interpolation_method="phase_calibration", + dphase_file="D:/cal/a.mat", lin_phase_file="D:/other/b.mat", + dsp_phase_file="D:/third/c.mat", phase_calibration_dispersion=True) + cfg = PSOCTScanConfigModel.model_validate(cfg.model_dump()) + opts = build_pipeline_opts(cfg) + values = opts.spectral.to_matlab_struct() + self.assertNotIn("interpolationPath", values) + for key in ("dphaseFile", "linPhaseFile", "dspPhaseFile"): + self.assertIn(key, values) + command = build_spectral2processed_batch_indexed_command(["input.nii"], output_dir="output", + mosaic_id=1, tile_indices=[1], pipeline_opts=opts) + for key in ("dphaseFile", "linPhaseFile", "dspPhaseFile"): + self.assertIn(key, command) + cfg.processing.dsp_phase_file = None + with self.assertRaises(ValueError): + build_pipeline_opts(cfg) + cfg.processing.phase_calibration_dispersion = False + build_pipeline_opts(cfg) + cfg.processing.lin_phase_file = None + with self.assertRaises(ValueError): + build_pipeline_opts(cfg) + cfg.processing.interpolation_path = "D:/fallback" + build_pipeline_opts(cfg) + + def test_flip_override_and_round_trip(self): + cfg = self.config(interpolation_method="phase_calibration", interpolation_path="D:/calibration", flip_channel2_spectra=True) + reloaded = PSOCTScanConfigModel.model_validate(cfg.model_dump()) + self.assertTrue(build_pipeline_opts(reloaded).spectral.to_matlab_struct()["flipChannel2Spectra"]) From a090b65584c7a02c3e02a301aebd16bab54c3483 Mon Sep 17 00:00:00 2001 From: NoahMarkowitz Date: Mon, 21 Sep 2026 16:41:47 -0400 Subject: [PATCH 18/65] update docker yaml --- docker-compose.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docker-compose.yaml b/docker-compose.yaml index 175d93c..61ab8f6 100644 --- a/docker-compose.yaml +++ b/docker-compose.yaml @@ -13,7 +13,7 @@ services: - ./db:/var/lib/postgresql profiles: ["server"] ports: - - "127.0.0.1:1542:5432" + - "1542:5432" ### MinIO for flow storage minio: @@ -38,7 +38,7 @@ services: # Option A: create a .env next to this file with HOST_IP=192.168.x.x (see .env.example) # Option B: export HOST_IP=192.168.x.x before `docker compose up` # Default 127.0.0.1 is for access only from the Docker host. - - PREFECT_UI_URL=http://${HOST_IP:-127.0.0.1}:4200/api + - PREFECT_UI_URL=http://${HOST_IP:-127.0.0.1}:4200 - PREFECT_API_URL=http://${HOST_IP:-127.0.0.1}:4200/api - PREFECT_SERVER_API_HOST=0.0.0.0 - PREFECT_API_DATABASE_CONNECTION_URL=postgresql+asyncpg://postgres:postgres@database:5432/prefect From e8ace463b6dd7cf5c7418e916870cdb6b2c24a8d Mon Sep 17 00:00:00 2001 From: NoahMarkowitz Date: Mon, 21 Sep 2026 17:14:27 -0400 Subject: [PATCH 19/65] update docker file --- docker-compose.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docker-compose.yaml b/docker-compose.yaml index 61ab8f6..9caa3d1 100644 --- a/docker-compose.yaml +++ b/docker-compose.yaml @@ -13,7 +13,7 @@ services: - ./db:/var/lib/postgresql profiles: ["server"] ports: - - "1542:5432" + - "0.0.0.0:1542:5432" ### MinIO for flow storage minio: From 77451733ab293e9a5514abac7018d8e1d168deab Mon Sep 17 00:00:00 2001 From: Noah Markowitz Date: Tue, 22 Sep 2026 10:18:20 -0400 Subject: [PATCH 20/65] change fiji path --- opticstream/data_processing/stitch/fiji.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/opticstream/data_processing/stitch/fiji.py b/opticstream/data_processing/stitch/fiji.py index 873beef..2e1234c 100644 --- a/opticstream/data_processing/stitch/fiji.py +++ b/opticstream/data_processing/stitch/fiji.py @@ -11,7 +11,8 @@ from cyclopts import App -DEFAULT_FIJI_PATH = Path("/autofs/cluster/octdata2/users/Hui/Fiji.app/ImageJ-linux64") +#DEFAULT_FIJI_PATH = Path("/autofs/cluster/octdata2/users/Hui/Fiji.app/ImageJ-linux64") +DEFAULT_FIJI_PATH = Path("/usr/pubsw/packages/ImageJ/current/ImageJ-linux64") app = App(name="fiji") From d6583b16ba3758e08f2df357c30ec7c5bbd2a99c Mon Sep 17 00:00:00 2001 From: Noah Markowitz Date: Tue, 22 Sep 2026 13:56:50 -0400 Subject: [PATCH 21/65] update toml file --- pyproject.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pyproject.toml b/pyproject.toml index e384843..8156f23 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -6,7 +6,7 @@ readme = "README.md" requires-python = ">=3.11" dependencies = [ "cyclopts>=3.3.0", - "linc-convert[all] @ git+https://github.com/lincbrain/linc-convert.git@dc8f3243df01d09493a13e53305adede08784695", + "linc-convert[all] @ git+https://github.com/nmarkowitz/linc-convert.git@050bd354e166b14fb5bca244e94107d559e0aa0a", "nifti-zarr @ git+https://github.com/calvinchai/nifti-zarr-py.git@12336420beaa023cbdd9d9e5c24e3c115687fe9a", "psoct-toolbox @ git+https://github.com/calvinchai/psoct-toolbox.git@5182337044d2b7f8337ca205a33c9da3ddd69bda", "matplotlib>=3.10.8", From cc52a58a6a9bfeb7676b4d3c490fb4787281d82f Mon Sep 17 00:00:00 2001 From: Noah Markowitz Date: Tue, 22 Sep 2026 23:26:20 -0400 Subject: [PATCH 22/65] fixes Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 45 +++++++++++++++++++ opticstream/cli/deploy_cmds.py | 2 +- opticstream/cli/oct/deploy.py | 2 +- .../flows/psoct/mosaic_process_flow.py | 2 +- opticstream/tasks/dandi_upload.py | 45 +++++++++++++++---- 5 files changed, 85 insertions(+), 11 deletions(-) create mode 100644 CLAUDE.md diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..a95c139 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,45 @@ +# CLAUDE.md + +This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository. + +## Overview + +OpticStream is a set of Prefect 3 workflows for processing large microscopy datasets. It runs two pipelines: **LSM** (light-sheet strips → channels → volumes) and **PS-OCT** (tile batches → mosaics → slices). The CLI is `opticstream`, also available as `ops` (Cyclopts, `opticstream/cli`). + +## Commands + +```bash +uv sync --extra dev # install (Python >=3.11; git-pinned deps: linc-convert, nifti-zarr, psoct-toolbox) +uv run pytest -ra # unit tests (integration tests are excluded by default via addopts) +uv run pytest tests/test_state_guards.py::TestName::test_name # single test +uv run pytest -o addopts= -m integration -ra # integration tests; need a Prefect server + Postgres: +docker compose --profile server up -d # Prefect at :4200, then: prefect config set PREFECT_API_URL=http://127.0.0.1:4200/api +uv run ruff check opticstream # lint (ruff is in dev extras; no project-specific ruff config) +mkdocs serve # docs (mkdocs.yml, docs/) +``` + +`tests/matlab/*.m` are MATLAB tests for the bundled MATLAB overlay. They need a MATLAB install and are not run by CI. + +## Architecture + +**Event-driven flow graph.** Flows do not call downstream flows directly. Each stage emits a Prefect event named `linc.opticstream.{pipeline}.{hierarchy}.{state}` (constants live in `opticstream/events/{lsm,psoct}_events.py`, and emitters in `*_event_emitters.py`). Deployments subscribe to those events through `get_event_trigger` / `create_event_deployment` (`opticstream/utils/deployment_utils.py`), and Jinja templates map the event payload into flow parameters. For example, PS-OCT runs `batch.ready → batch.complexed → batch.processed → mosaic.ready → mosaic stitch → slice.ready → …`. Uploads always run as separate event-triggered flows, so they never block compute. Deployments are registered and served through `ops lsm|oct deploy/serve`, and watchers (`ops lsm|oct watch`, `opticstream/utils/directory_watch.py`, `polling_watcher.py`) watch acquisition directories and emit the first events. + +**Payload conventions.** Event payloads carry typed identifiers such as `mosaic_ident` and `strip_ident`, which parse into `OCTMosaicId`, `LSMStripId`, and so on. Most processing parameters come from the project's scan-config **Prefect Block**: `PSOCTScanConfig` saved as `"{project_name}-config"`, or `LSMScanConfig` saved as `"{project_name}-lsm-config"`, both in `opticstream/config/`. A payload may override only the keys whitelisted in the flow utils, e.g. `PROCESS_MOSAIC_FLOW_KWARGS_KEYS` in `opticstream/flows/psoct/utils.py`. `force_rerun` in a payload bypasses the skip guards. + +**Project state (PostgreSQL).** `opticstream/state/` stores per-project state as JSONB rows keyed by `(project_type, project_name)` and accessed through a Prefect `SqlAlchemyConnector` block (`project_state_postgres.py`). Every mutation takes a project-scoped Prefect global concurrency lock (limit 1), then loads, mutates, and saves. The services are `OCT_STATE_SERVICE` and `LSM_STATE_SERVICE`, and they expose three kinds of access: +- `open_*`: locked context manager that yields a **mutable** model and saves on exit. +- `read_*`: locked read that returns a frozen **View** model. +- `peek_*`: unlocked, best-effort read. + +Mutable models only exist inside `open_*` scopes; use `to_view()` to take a snapshot. See `docs/developer/prefect_state_design.md`. + +**Idempotency / milestones.** Flows call `state_guards.should_skip_run` / `enter_flow_stage` to skip work that is already done or to restart it. Milestone decorators (`state/milestone_wrappers_{psoct,lsm}.py`, built on `milestone_runtime.guarded_milestone`) set a boolean field through `set_()` on success and optionally emit the next event. When you add a milestone field, the state model needs matching `set_` and `reset_` methods. Flow hooks in `opticstream/hooks/` (such as `check_mosaic_ready_hook` and `check_slice_ready_hook`) check whether a parent level is complete and emit its `ready` event. Other hooks handle Slack notifications and publishing artifacts. + +**MATLAB processing.** The PS-OCT spectral → complex → volume/enface reconstruction runs MATLAB code from `psoct-toolbox` through `utils/matlab_execution.run_matlab_batch_command_or_cli`, which uses the MATLAB Engine when it is importable and falls back to `matlab -batch`. `opticstream/matlab/` is an overlay that gets prepended to the MATLAB path after the toolbox loads, so it overrides toolbox functions. Its `.m` files ship as package-data (listed explicitly in `pyproject.toml`, so a new subpackage directory must be added there). `config/pipeline_opts_builder.py` converts the scan config into the MATLAB opts struct. Stitching uses Fiji (`data_processing/stitch/fiji.py`). + +**Uploads.** `tasks/dandi_upload.py` handles DANDI and LINC uploads, and `tasks/archive_file.py` handles archiving. + +## Notes + +- Dependencies are pinned to specific git commits in `pyproject.toml`. Local editable overrides go in `[tool.uv.sources]` (commented out by default). Don't commit machine-specific `path =` entries. +- Deeper design docs are in `docs/developer/`: `oct_*.md`, `watcher_design_lsm_oct.md`, and `prefect_state_design.md`. Concept docs are in `docs/concepts/`. diff --git a/opticstream/cli/deploy_cmds.py b/opticstream/cli/deploy_cmds.py index 57ad15b..bad155d 100644 --- a/opticstream/cli/deploy_cmds.py +++ b/opticstream/cli/deploy_cmds.py @@ -51,7 +51,7 @@ class FlowDeploymentSpec: description="Event-driven mosaic processing flow (MOSAIC_READY -> process_mosaic_flow).", ), "volume-stitching": FlowDeploymentSpec( - module_path="opticstream.flows.volume_stitching_flow", + module_path="opticstream.flows.psoct.mosaic_volume_stitch_flow", deployment_names=("stitch_volume_event_flow_deployment",), description="Event-driven 3D volume stitching flow (MOSAIC_ENFACE_STITCHED -> stitch_volume_flow).", ), diff --git a/opticstream/cli/oct/deploy.py b/opticstream/cli/oct/deploy.py index bd19668..3d57ceb 100644 --- a/opticstream/cli/oct/deploy.py +++ b/opticstream/cli/oct/deploy.py @@ -135,7 +135,7 @@ def deploy( stitch_volume_event_flow.from_source( source=Path(__file__).parent.parent.parent / "flows", - entrypoint="volume_stitching_flow.py:stitch_volume_event_flow", + entrypoint="psoct/mosaic_volume_stitch_flow.py:stitch_volume_event_flow", ).deploy( name=deployment_name, work_pool_name=work_pool_name, diff --git a/opticstream/flows/psoct/mosaic_process_flow.py b/opticstream/flows/psoct/mosaic_process_flow.py index c983390..358ed96 100644 --- a/opticstream/flows/psoct/mosaic_process_flow.py +++ b/opticstream/flows/psoct/mosaic_process_flow.py @@ -281,8 +281,8 @@ def stitch_enface_modalities( template_path: Path, processed_path: Path, stitched_path: Path, - mask_path: Path, scan_resolution_2d: List[float], + mask_path: Optional[Path] = None, ) -> Dict[str, Path]: """ Subflow to stitch all 2D enface modalities. diff --git a/opticstream/tasks/dandi_upload.py b/opticstream/tasks/dandi_upload.py index 7476991..c010057 100644 --- a/opticstream/tasks/dandi_upload.py +++ b/opticstream/tasks/dandi_upload.py @@ -96,6 +96,7 @@ def _upload_dandi_api( file_list: List[str], *, max_jobs: str, + dandi_api_key: Secret | None = None, ) -> None: """Upload DANDI assets through the API, including generic NIfTI files. @@ -123,15 +124,39 @@ def _upload_dandi_api( metadata_paths.append(metadata) break - upload( - paths=[*paths, *metadata_paths], - existing=UploadExisting.OVERWRITE, - validation=UploadValidation.SKIP, + # The Python DANDI API authenticates from DANDI_API_KEY. Unlike the + # subprocess path below, it does not receive the environment assembled by + # _build_dandi_upload_env, so set the key explicitly for this call. Keep + # the change scoped to the upload and restore the worker environment after + # the call completes. + env = _build_dandi_upload_env( dandi_instance="dandi", - allow_any_path=True, - jobs=jobs, - jobs_per_file=jobs_per_file, + dandi_api_key=dandi_api_key, ) + api_key = env["DANDI_API_KEY"] + if not api_key: + raise RuntimeError( + "No DANDI API key is configured. Set the project's dandi_api_key " + "Secret or create the 'dandi-api-key' Secret block." + ) + + previous_api_key = os.environ.get("DANDI_API_KEY") + os.environ["DANDI_API_KEY"] = api_key + try: + upload( + paths=[*paths, *metadata_paths], + existing=UploadExisting.OVERWRITE, + validation=UploadValidation.SKIP, + dandi_instance="dandi", + allow_any_path=True, + jobs=jobs, + jobs_per_file=jobs_per_file, + ) + finally: + if previous_api_key is None: + os.environ.pop("DANDI_API_KEY", None) + else: + os.environ["DANDI_API_KEY"] = previous_api_key @task(tags=["dandi-upload"], retries=1) @@ -167,7 +192,11 @@ def upload_to_dandi_batch( logger.info(command) if dandi_instance == "dandi": - _upload_dandi_api(file_list, max_jobs=max_jobs) + _upload_dandi_api( + file_list, + max_jobs=max_jobs, + dandi_api_key=dandi_api_key, + ) logger.info("DANDI batch upload completed") return From 4979043fa5d00e71b09a1294d438bfc0f3544663 Mon Sep 17 00:00:00 2001 From: Noah Markowitz Date: Wed, 23 Sep 2026 14:56:06 -0400 Subject: [PATCH 23/65] bug fixing --- opticstream/artifacts/oct.py | 2 +- opticstream/config/lsm_scan_config.py | 4 +- opticstream/data_processing/stitch/coords.py | 58 +++++++++++++--- opticstream/flows/lsm/strip_upload_flow.py | 2 +- opticstream/flows/psoct/mosaic_upload_flow.py | 2 +- .../flows/psoct/mosaic_volume_stitch_flow.py | 8 ++- .../flows/psoct/mosaic_volume_upload_flow.py | 2 +- opticstream/flows/psoct/slice_process_flow.py | 67 ++++++++++++++++--- .../flows/psoct/tile_batch_upload_flow.py | 4 +- opticstream/scripts/find_tile_plane.py | 5 ++ opticstream/tasks/dandi_upload.py | 13 +++- tests/test_coords_drift_fallback.py | 39 +++++++++++ tests/test_dandi_upload.py | 26 +++++++ 13 files changed, 198 insertions(+), 34 deletions(-) create mode 100644 tests/test_coords_drift_fallback.py diff --git a/opticstream/artifacts/oct.py b/opticstream/artifacts/oct.py index 78fea47..2ae6cd2 100644 --- a/opticstream/artifacts/oct.py +++ b/opticstream/artifacts/oct.py @@ -158,7 +158,7 @@ def build_oct_mosaic_description( Last Updated: {timestamp_str()} The table lists each batch (rows) with processing state; flags use ✅ / ❌. -Batch uploaded is per-batch LINC upload. Mosaic-level upload/stitch status is on the all-mosaics artifact. +Batch uploaded is per-batch DANDI upload. Mosaic-level upload/stitch status is on the all-mosaics artifact. Status: {status_text} diff --git a/opticstream/config/lsm_scan_config.py b/opticstream/config/lsm_scan_config.py index 1478a10..22a769e 100644 --- a/opticstream/config/lsm_scan_config.py +++ b/opticstream/config/lsm_scan_config.py @@ -84,7 +84,9 @@ class LSMScanConfigModel(BaseModel): description="Path to the DANDI CLI binary, useful for installation in a separate conda/venv environment", ) dandi_instance: str = Field( - default="linc", min_length=1, description="DANDI instance to use for upload" + default="dandi", + min_length=1, + description="DANDI instance to use for upload (LINC is deprecated)", ) dandiset_path: str = Field( default="linc://000052/", description="Path to the DANDI set to use for upload" diff --git a/opticstream/data_processing/stitch/coords.py b/opticstream/data_processing/stitch/coords.py index 0c41ace..98ff3c7 100644 --- a/opticstream/data_processing/stitch/coords.py +++ b/opticstream/data_processing/stitch/coords.py @@ -179,7 +179,41 @@ def print_tile_map(self): print(line) print("-" * total_width) - def compute_registered_offset(self, signal_threshold: float = 55.0): + @staticmethod + def _validated_drift( + drifts: List[Tuple[float, float]], + ideal: Tuple[float, float], + label: str, + max_deviation: float, + ) -> Tuple[float, float]: + """ + Median registered drift, or the ideal grid step if registration is unusable. + + Falls back when no reliable neighbor pairs exist, or when the median + deviates from the ideal step by more than ``max_deviation`` times the + ideal step length (e.g. Fiji collapsing tiles onto the same position). + """ + ideal_len = float(np.hypot(*ideal)) + if not drifts: + print( + f"WARNING: no reliable {label} tile pairs; " + f"falling back to ideal {label} step {ideal}" + ) + return ideal + drift = tuple(np.median(np.array(drifts), axis=0).tolist()) + deviation = float(np.hypot(drift[0] - ideal[0], drift[1] - ideal[1])) + if ideal_len > 0 and deviation > max_deviation * ideal_len: + print( + f"WARNING: registered {label} drift {drift} deviates from ideal " + f"step {ideal} by {deviation:.1f} px (> {max_deviation:.0%} of step); " + f"registration likely failed, falling back to ideal step" + ) + return ideal + return drift + + def compute_registered_offset( + self, signal_threshold: float = 55.0, max_drift_deviation: float = 0.5 + ): horizontal_drifts = [] vertical_drifts = [] @@ -209,16 +243,18 @@ def compute_registered_offset(self, signal_threshold: float = 55.0): dy = b.stitched_coord[1] - a.stitched_coord[1] vertical_drifts.append((dx, dy)) - horizontal_drift = (0.0, 0.0) - vertical_drift = (0.0, 0.0) - if horizontal_drifts: - horizontal_drift = tuple( - np.median(np.array(horizontal_drifts), axis=0).tolist() - ) - if vertical_drifts: - vertical_drift = tuple( - np.median(np.array(vertical_drifts), axis=0).tolist() - ) + ideal_horizontal = ( + (self.x_coords[1] - self.x_coords[0], 0.0) if self.num_cols > 1 else (0.0, 0.0) + ) + ideal_vertical = ( + (0.0, self.y_coords[1] - self.y_coords[0]) if self.num_rows > 1 else (0.0, 0.0) + ) + horizontal_drift = self._validated_drift( + horizontal_drifts, ideal_horizontal, "horizontal", max_drift_deviation + ) + vertical_drift = self._validated_drift( + vertical_drifts, ideal_vertical, "vertical", max_drift_deviation + ) print("\nComputed drifts:") print( diff --git a/opticstream/flows/lsm/strip_upload_flow.py b/opticstream/flows/lsm/strip_upload_flow.py index 1a4cabf..61fb0e7 100644 --- a/opticstream/flows/lsm/strip_upload_flow.py +++ b/opticstream/flows/lsm/strip_upload_flow.py @@ -37,7 +37,7 @@ def upload_strip_to_dandi_flow( strip_ident: LSMStripId, output_path: Path, - dandi_instance: str = "linc", + dandi_instance: str = "dandi", dandi_bin: str = "dandi", dandi_api_key: Secret | None = None, force_rerun: bool = False, diff --git a/opticstream/flows/psoct/mosaic_upload_flow.py b/opticstream/flows/psoct/mosaic_upload_flow.py index 6d5a6e1..2619990 100644 --- a/opticstream/flows/psoct/mosaic_upload_flow.py +++ b/opticstream/flows/psoct/mosaic_upload_flow.py @@ -35,7 +35,7 @@ def upload_mosaic_enface_to_dandi_flow( mosaic_ident: OCTMosaicId, enface_outputs: Dict[str, str], *, - dandi_instance: str = "linc", + dandi_instance: str = "dandi", dandi_api_key: Secret | None = None, force_rerun: bool = False, ) -> None: diff --git a/opticstream/flows/psoct/mosaic_volume_stitch_flow.py b/opticstream/flows/psoct/mosaic_volume_stitch_flow.py index 5107bee..8d1b041 100644 --- a/opticstream/flows/psoct/mosaic_volume_stitch_flow.py +++ b/opticstream/flows/psoct/mosaic_volume_stitch_flow.py @@ -218,7 +218,8 @@ def find_focus_plane_task( find_tile_plane.main( yaml_path=str(filtered_tile_info_path), output=str(focus_plane_path_slice), - base_dir=str(slice_focus_dir), + # Surface maps live in the processed dir recorded in the YAML metadata. + base_dir=None, subsample=1, avg_signal_threshold=signal_threshold, plot=str(slice_focus_dir / f"plane_{config_illumination}.png"), @@ -410,8 +411,9 @@ def stitch_volume_flow( errors = [] for modality, future in volume_futures.items(): future.wait() - if future.exception(): - errors.append(future.exception()) + # Prefect futures expose a state, not concurrent.futures' exception(). + if not future.state.is_completed(): + errors.append(f"{modality}: {future.state.message}") if errors: raise RuntimeError(f"Errors occurred during volume stitching: {errors}") diff --git a/opticstream/flows/psoct/mosaic_volume_upload_flow.py b/opticstream/flows/psoct/mosaic_volume_upload_flow.py index c754f5a..d040e71 100644 --- a/opticstream/flows/psoct/mosaic_volume_upload_flow.py +++ b/opticstream/flows/psoct/mosaic_volume_upload_flow.py @@ -41,7 +41,7 @@ def upload_mosaic_volume_to_dandi_flow( mosaic_ident: OCTMosaicId, volume_outputs: Dict[str, str], *, - dandi_instance: str = "linc", + dandi_instance: str = "dandi", dandi_api_key: Secret | None = None, force_rerun: bool = False, ) -> Dict[str, Any]: diff --git a/opticstream/flows/psoct/slice_process_flow.py b/opticstream/flows/psoct/slice_process_flow.py index 51c2437..8464a72 100644 --- a/opticstream/flows/psoct/slice_process_flow.py +++ b/opticstream/flows/psoct/slice_process_flow.py @@ -16,7 +16,7 @@ from prefect import flow, task from prefect.logging import get_run_logger -from psoct_toolbox.matlab_bridge import build_thruplane_from_files_command +from psoct_toolbox.matlab_bridge import _matlab_literal from opticstream.hooks.publish_hooks import publish_oct_project_hook from opticstream.events import SLICE_READY, SLICE_REGISTERED, get_event_trigger @@ -27,6 +27,56 @@ from opticstream.flows.psoct.utils import get_slice_paths +# Output filenames written by thruplane registration, keyed by the +# outputOpts.Paths field names of psoct.registration.thruplane. +THRUPLANE_OUTPUT_FILES: Dict[str, tuple[str, str]] = { + "data": ("dataMat", "data_data.mat"), + "inplane_tiff": ("inplaneTiff", "data_inplane.tiff"), + "inplane_jpg": ("inplaneJpg", "data_inplane.jpg"), + "alpha_tiff": ("alphaTiff", "data_alpha.tiff"), + "alpha_jpg": ("alphaJpg", "data_alpha.jpg"), + "axis_nii": ("axisNiiNorm", "3daxis.nii"), + "axis_jpg": ("axisJpg", "3daxis.jpg"), +} + + +def build_thruplane_command( + fixed_ori_path: str, + moving_ori_path: str, + fixed_biref_path: str, + moving_biref_path: str, + output_dir: Path, + gamma: float, +) -> str: + """ + Build a ``psoct.registration.thruplane(...)`` MATLAB command. + + psoct_toolbox's ``build_thruplane_from_files_command`` targets + ``thruplane_from_files``, which is not callable unqualified and depends on + a registration backend missing from the pinned toolbox. + """ + paths = { + field: str(output_dir / filename) + for field, filename in THRUPLANE_OUTPUT_FILES.values() + } + args = ", ".join( + [ + _matlab_literal(fixed_ori_path), + _matlab_literal(moving_ori_path), + _matlab_literal(fixed_biref_path), + _matlab_literal(moving_biref_path), + "''", # fixed_mask + "''", # moving_mask + "55", # fixed_mask_threshold (unused without a mask) + "55", # moving_mask_threshold (unused without a mask) + "[]", # crop_rect + _matlab_literal(float(gamma)), + _matlab_literal({"Paths": paths}), + ] + ) + return f"psoct.registration.thruplane({args})" + + @task def thruplane_from_files_task( fixed_ori_path: str, @@ -126,13 +176,13 @@ def thruplane_from_files_task( ) try: - cmd = build_thruplane_from_files_command( + cmd = build_thruplane_command( fixed_ori_abs, moving_ori_abs, fixed_biref_abs, moving_biref_abs, - output_dir=output_dir_abs, - gamma=float(gamma), + output_dir=Path(output_dir_abs), + gamma=gamma, ) run_matlab_batch_command_or_cli( cmd, @@ -144,13 +194,8 @@ def thruplane_from_files_task( # Collect output file paths outputs = { - "data": output_path / "data_data.mat", - "inplane_tiff": output_path / "data_inplane.tiff", - "inplane_jpg": output_path / "data_inplane.jpg", - "alpha_tiff": output_path / "data_alpha.tiff", - "alpha_jpg": output_path / "data_alpha.jpg", - "axis_nii": output_path / "3daxis.nii", - "axis_jpg": output_path / "3daxis.jpg", + key: output_path / filename + for key, (_, filename) in THRUPLANE_OUTPUT_FILES.items() } # Verify outputs exist diff --git a/opticstream/flows/psoct/tile_batch_upload_flow.py b/opticstream/flows/psoct/tile_batch_upload_flow.py index 76c7fdd..5a782a4 100644 --- a/opticstream/flows/psoct/tile_batch_upload_flow.py +++ b/opticstream/flows/psoct/tile_batch_upload_flow.py @@ -77,11 +77,11 @@ def to_deployment( """ manual = upload_to_dandi_tile_batch.to_deployment( name=deployment_name, - tags=["tile-batch", "upload-to-linc", *list(extra_tags)], + tags=["tile-batch", "upload-to-dandi", *list(extra_tags)], ) event = upload_to_dandi_batch_event_flow.to_deployment( name=deployment_name, - tags=["event-driven", "tile-batch", "upload-to-linc", *list(extra_tags)], + tags=["event-driven", "tile-batch", "upload-to-dandi", *list(extra_tags)], triggers=[get_event_trigger(BATCH_ARCHIVED, project_name=project_name)], ) return [manual, event] diff --git a/opticstream/scripts/find_tile_plane.py b/opticstream/scripts/find_tile_plane.py index f78a870..cb32dc4 100755 --- a/opticstream/scripts/find_tile_plane.py +++ b/opticstream/scripts/find_tile_plane.py @@ -41,6 +41,11 @@ from scipy.optimize import least_squares, minimize try: + import matplotlib + + # Plots are only saved to files. A GUI backend (picked when DISPLAY is set) + # aborts the process when its Tk objects are collected from worker threads. + matplotlib.use("Agg") import matplotlib.pyplot as plt HAS_MATPLOTLIB = True except ImportError: diff --git a/opticstream/tasks/dandi_upload.py b/opticstream/tasks/dandi_upload.py index c010057..6356bfd 100644 --- a/opticstream/tasks/dandi_upload.py +++ b/opticstream/tasks/dandi_upload.py @@ -170,8 +170,17 @@ def upload_to_dandi_batch( dandi_api_key: Secret | None = None, ) -> None: """ - Upload multiple files to DANDI (or optionally to the LINC instance). + Upload multiple files to DANDI. + + LINC is deprecated: requesting it raises instead of uploading there or + silently switching instances (dandiset ids differ between the two). """ + if dandi_instance == "linc": + raise ValueError( + "LINC uploads are deprecated; upload to DANDI instead. Set " + "dandi_instance='dandi' (e.g. in the project's scan config block) " + "and point dandiset_path at the DANDI dandiset." + ) logger = get_run_logger() command, working_dir, _ = build_dandi_upload_command( @@ -214,7 +223,7 @@ def upload_to_dandi_batch( def upload_to_dandi( file_path: str, *, - dandi_instance: DANDI_INSTANCE = "linc", + dandi_instance: DANDI_INSTANCE = "dandi", dandi_bin: str = "dandi", realpath: bool = True, max_jobs: str = "10:10", diff --git a/tests/test_coords_drift_fallback.py b/tests/test_coords_drift_fallback.py new file mode 100644 index 0000000..b5598ab --- /dev/null +++ b/tests/test_coords_drift_fallback.py @@ -0,0 +1,39 @@ +import unittest + +from opticstream.data_processing.stitch.coords import Grid, Tile + + +def _grid(stitched_step, rows=3, cols=4, step=280.0): + tiles = [] + for r in range(rows): + for c in range(cols): + tiles.append( + Tile( + path=f"mosaic_001_image_{r * cols + c + 1:04d}_aip.nii", + normal_coord=(c * step, r * step), + stitched_coord=(c * stitched_step, r * stitched_step), + avg_signal=100.0, + ) + ) + return Grid.from_tiles(tiles) + + +class TestDriftFallback(unittest.TestCase): + def test_collapsed_registration_falls_back_to_ideal_step(self): + grid = _grid(stitched_step=0.0) + grid.compute_registered_offset(signal_threshold=60) + self.assertEqual(grid._tile_at(2, 3).derived_coord, (840.0, 560.0)) + + def test_plausible_registration_is_kept(self): + grid = _grid(stitched_step=270.0) + grid.compute_registered_offset(signal_threshold=60) + self.assertEqual(grid._tile_at(2, 3).derived_coord, (810.0, 540.0)) + + def test_no_reliable_tiles_falls_back_to_ideal_step(self): + grid = _grid(stitched_step=0.0) + grid.compute_registered_offset(signal_threshold=1000) + self.assertEqual(grid._tile_at(0, 1).derived_coord, (280.0, 0.0)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_dandi_upload.py b/tests/test_dandi_upload.py index cfa1951..777f40b 100644 --- a/tests/test_dandi_upload.py +++ b/tests/test_dandi_upload.py @@ -45,3 +45,29 @@ def test_selected_secret_is_used_for_linc_compatibility_variables() -> None: assert env["LINC_API_KEY"] == "project-token" assert env["DANDI_API_KEY"] == "project-token" + + +def test_linc_uploads_are_refused() -> None: + import inspect + + import pytest + + from opticstream.flows.lsm.strip_upload_flow import upload_strip_to_dandi_flow + from opticstream.flows.psoct.mosaic_upload_flow import ( + upload_mosaic_enface_to_dandi_flow, + ) + from opticstream.flows.psoct.mosaic_volume_upload_flow import ( + upload_mosaic_volume_to_dandi_flow, + ) + from opticstream.tasks.dandi_upload import upload_to_dandi_batch + + with pytest.raises(ValueError, match="LINC uploads are deprecated"): + upload_to_dandi_batch.fn(["/tmp/file.nii"], dandi_instance="linc") + + for flow in ( + upload_strip_to_dandi_flow, + upload_mosaic_enface_to_dandi_flow, + upload_mosaic_volume_to_dandi_flow, + ): + default = inspect.signature(flow.fn).parameters["dandi_instance"].default + assert default == "dandi", flow.name From 6edb2556af54c06e0e8c148d4a496757ca153925 Mon Sep 17 00:00:00 2001 From: Noah Markowitz Date: Wed, 23 Sep 2026 21:31:08 -0400 Subject: [PATCH 24/65] more updates --- docs/matlab_enface_only.md | 6 +- docs/oct_input_naming.md | 28 ++++- opticstream/cli/oct/watch.py | 115 +++++++++++++++++- opticstream/config/psoct_scan_config.py | 12 +- .../flows/psoct/mosaic_volume_stitch_flow.py | 14 +-- opticstream/utils/oct_input_naming.py | 41 +++++-- opticstream/utils/volume_settings.py | 3 + tests/test_oct_input_naming.py | 56 ++++++++- tests/test_volume_output_setting.py | 30 +++-- 9 files changed, 266 insertions(+), 39 deletions(-) diff --git a/docs/matlab_enface_only.md b/docs/matlab_enface_only.md index 6cf42ed..764cb42 100644 --- a/docs/matlab_enface_only.md +++ b/docs/matlab_enface_only.md @@ -17,8 +17,10 @@ Slice registration remains enabled; this setting controls reconstructed tile volumes and their mosaic outputs, not registration-derived orientation products. `processing.save_enface_2d_as_3d` is independent: false stores enface maps as 2D -NIfTI instead of X-by-Y-by-1. `stitch_3d_volumes` remains an independent switch; -enabling volume saving does not override disabled stitching. +NIfTI instead of X-by-Y-by-1. `stitch_3d_volumes` (default `true`) is an +independent switch: set it to `false` to keep saving per-tile volumes but skip +mosaic volume stitching (including focus finding) and mosaic volume uploads. +Enabling volume saving does not override disabled stitching. ## Enable for an existing block diff --git a/docs/oct_input_naming.md b/docs/oct_input_naming.md index c59a7cc..631d417 100644 --- a/docs/oct_input_naming.md +++ b/docs/oct_input_naming.md @@ -11,9 +11,9 @@ Omitting `filename_pattern` (or setting it to null) preserves legacy parsing. } ``` -This is a template, not a regular expression. Required placeholders are `slice`, -`image`, and `acquisition`. Optional placeholders are `subject`, `modality`, and -`extension`. Each may appear once; do not add format specifiers such as `:04d`. +This is a template, not a regular expression. The only required placeholder is +`image`. Optional placeholders are `slice`, `acquisition`, `subject`, `modality`, +and `extension`. Each may appear once; do not add format specifiers such as `:04d`. Numeric fields accept zero padding. Matching is case-sensitive and covers the entire basename. The watcher scans the selected directory, not recursively. @@ -30,6 +30,28 @@ must agree with the project's existing two-/three-mosaic illumination layout. The subject field is matched but does not select a project: do not mix subjects with overlapping slice/tile IDs in the same watched directory. +## Scanner names without slice or acquisition + +If the scanner only numbers its output (`spectral_0001.nii`, `spectral_0002.nii`, +...), set `"filename_pattern": "spectral_{image}.nii"` and tell the watcher which +slice and acquisition the folder holds: + +```bash +ops oct watch myproject /path/to/scanner/output --slice 3 --acquisition normal0deg +ops oct watch myproject /path/to/scanner/output --mosaic 5 # same thing with 2 mosaics per slice +``` + +`--acquisition` must be a key of `acquisition_mosaic_map`. `--mosaic` is the global +source mosaic id, `(slice - 1) * mosaics_per_slice + slot`; if you pass it together +with `--slice` or `--acquisition`, they must agree. Files the watcher cannot place +(no slice/acquisition in the name and none on the command line) are skipped with +a warning. Run one watcher per slice/acquisition folder, and restart it with new +values when the scanner moves on, because image numbers repeat between mosaics. + +When the filename already contains `{slice}`/`{acquisition}`, or uses legacy +`mosaic_###_image_####` names, these options act as a filter: only matching files +are dispatched. + No `_spectral.nii` suffix is required. For example, use `s{slice}_tile{image}_{acquisition}.nii` with `filename_default_modality: "spectral"`. Or keep `{modality}{extension}` and diff --git a/opticstream/cli/oct/watch.py b/opticstream/cli/oct/watch.py index adc6d46..7ee0748 100644 --- a/opticstream/cli/oct/watch.py +++ b/opticstream/cli/oct/watch.py @@ -20,6 +20,7 @@ from opticstream.flows.psoct.utils import oct_batch_ident from opticstream.flows.psoct.utils import ( logical_mosaic_from_source_mosaic, + mosaic_position_in_slice, slice_from_mosaic, ) from opticstream.state.oct_project_state import OCT_STATE_SERVICE @@ -127,6 +128,42 @@ def _parse_mosaic_ranges(mosaic_ranges_str: str) -> list[tuple[int, int]]: return out +def resolve_fixed_mosaic( + scan_config: PSOCTScanConfigModel, + *, + slice_id: int | None = None, + acquisition: str | None = None, + mosaic: int | None = None, +) -> tuple[int | None, int | None]: + """ + Resolve watch --slice/--acquisition/--mosaic into (slice_id, mosaic_slot). + + ``mosaic`` is a global source mosaic id; ``acquisition`` is a label from + ``acquisition.acquisition_mosaic_map``. Values given together must agree. + """ + mosaics_per_slice = scan_config.mosaics_per_slice + slot = None + if acquisition is not None: + mosaic_map = scan_config.acquisition.acquisition_mosaic_map + if acquisition not in mosaic_map: + raise ValueError( + f"Unknown acquisition {acquisition!r}; expected one of {sorted(mosaic_map)} " + "(acquisition.acquisition_mosaic_map)" + ) + slot = mosaic_map[acquisition] + if slice_id is not None and slice_id < 1: + raise ValueError(f"--slice must be >= 1, got {slice_id}") + if mosaic is not None: + mosaic_slice = slice_from_mosaic(mosaic, mosaics_per_slice) + mosaic_slot = mosaic_position_in_slice(mosaic, mosaics_per_slice) + if slice_id is not None and slice_id != mosaic_slice: + raise ValueError(f"--mosaic {mosaic} belongs to slice {mosaic_slice}, not --slice {slice_id}") + if slot is not None and slot != mosaic_slot: + raise ValueError(f"--mosaic {mosaic} is slot {mosaic_slot}, but --acquisition {acquisition} is slot {slot}") + slice_id, slot = mosaic_slice, mosaic_slot + return slice_id, slot + + @dataclass(frozen=True) class ParsedTileFile: path: Path @@ -167,8 +204,13 @@ def __init__( refresh_hook: RefreshHook | None = None, min_complex_file_size_bytes: int = 1, prefer_spectral_for_complex_with_spectral: bool = True, + fixed_slice_id: int | None = None, + fixed_mosaic_slot: int | None = None, ) -> None: self.project_name = project_name + self.fixed_slice_id = fixed_slice_id + self.fixed_mosaic_slot = fixed_mosaic_slot + self._warned_unplaced: set[str] = set() self.folder_path = folder_path self.project_base_path = project_base_path self.mosaic_ranges = mosaic_ranges @@ -290,6 +332,19 @@ def _discover_two_mosaic_candidates(self) -> list[OCTBatchCandidate]: return out + def _matches_fixed_mosaic(self, source_mosaic_id: int) -> bool: + """Apply --slice/--acquisition/--mosaic as a filter to legacy filenames.""" + mosaics_per_slice = self.scan_config.mosaics_per_slice + if self.fixed_slice_id is not None and ( + slice_from_mosaic(source_mosaic_id, mosaics_per_slice) != self.fixed_slice_id + ): + return False + if self.fixed_mosaic_slot is not None and ( + mosaic_position_in_slice(source_mosaic_id, mosaics_per_slice) != self.fixed_mosaic_slot + ): + return False + return True + def _discover_two_mosaic_files(self) -> list[ParsedTileFile]: logger.debug("_discover_two_mosaic_files: scanning all tile files") out: list[ParsedTileFile] = [] @@ -304,9 +359,25 @@ def _discover_two_mosaic_files(self) -> list[ParsedTileFile]: parsed: ParsedTileFile | None = None if getattr(self.scan_config.acquisition, "filename_pattern", None): from opticstream.utils.oct_input_naming import parse_input_name - custom = parse_input_name(path.name, self.scan_config.acquisition, self.scan_config.mosaics_per_slice) - if custom is not None: - out.append(ParsedTileFile(path=path, source_mosaic_id=custom.source_mosaic_id, image_index=custom.image_index)) + custom = parse_input_name( + path.name, + self.scan_config.acquisition, + self.scan_config.mosaics_per_slice, + slice_id=self.fixed_slice_id, + mosaic_slot=self.fixed_mosaic_slot, + ) + if custom is None: + continue + if custom.source_mosaic_id is None: + if path.name not in self._warned_unplaced: + self._warned_unplaced.add(path.name) + logger.warning( + "Cannot place %s: filename has no slice/acquisition; " + "pass --slice with --acquisition, or --mosaic", + path.name, + ) + continue + out.append(ParsedTileFile(path=path, source_mosaic_id=custom.source_mosaic_id, image_index=custom.image_index)) continue for parser in ( self._parse_complex_file, @@ -319,7 +390,8 @@ def _discover_two_mosaic_files(self) -> list[ParsedTileFile]: break if parsed is not None: - out.append(parsed) + if self._matches_fixed_mosaic(parsed.source_mosaic_id): + out.append(parsed) else: logger.debug("File did not match any tile pattern: %s", path.name) @@ -483,7 +555,13 @@ def _parse_tile_nii_file(self, path: Path) -> ParsedTileFile | None: def _image_index_from_file(self, path: Path) -> int: if getattr(self.scan_config.acquisition, "filename_pattern", None): from opticstream.utils.oct_input_naming import parse_input_name - custom = parse_input_name(path.name, self.scan_config.acquisition, self.scan_config.mosaics_per_slice) + custom = parse_input_name( + path.name, + self.scan_config.acquisition, + self.scan_config.mosaics_per_slice, + slice_id=self.fixed_slice_id, + mosaic_slot=self.fixed_mosaic_slot, + ) if custom is None: raise ValueError(f"Filename does not match configured input naming: {path.name}") return custom.image_index @@ -595,6 +673,8 @@ def watch_oct( force_resend: bool = False, refresh_hook: RefreshHook | None = None, min_complex_file_size_bytes: int = 1, + fixed_slice_id: int | None = None, + fixed_mosaic_slot: int | None = None, ) -> None: service = OCTWatcherService( project_name=project_name, @@ -608,6 +688,8 @@ def watch_oct( force_resend=force_resend, refresh_hook=refresh_hook, min_complex_file_size_bytes=min_complex_file_size_bytes, + fixed_slice_id=fixed_slice_id, + fixed_mosaic_slot=fixed_mosaic_slot, ) watcher = PollingStableWatcher[OCTBatchCandidate, tuple[int, int]]( @@ -635,6 +717,9 @@ def watch( refresh: str | None = None, force_resend: bool = False, min_complex_file_size_bytes: int = 1, + slice: int | None = None, + acquisition: str | None = None, + mosaic: int | None = None, verbose: bool = False, ) -> None: """ @@ -650,6 +735,13 @@ def watch( - discovery is from processed-index files (e.g. spectral/processed_.nii) - source mosaic id is derived from processed index and grid_size_x - slice_offset controls logical slice numbering via derived source mosaic ids + + --slice, --acquisition and --mosaic say which slice/mosaic the folder holds. + They fill in values missing from acquisition.filename_pattern (e.g. a block + pattern of "spectral_{image}.nii" with --slice 3 --acquisition normal0deg), + and filter files whose names already contain them. --acquisition is a label + from acquisition.acquisition_mosaic_map; --mosaic is a global source mosaic + id and can replace --slice/--acquisition. """ _configure_logging(verbose) @@ -667,6 +759,17 @@ def watch( refresh_hook = resolve_refresh_hook(refresh) + fixed_slice_id, fixed_mosaic_slot = resolve_fixed_mosaic( + scan_config, slice_id=slice, acquisition=acquisition, mosaic=mosaic + ) + if (fixed_slice_id, fixed_mosaic_slot) != (None, None): + if scan_config.mosaics_per_slice == 3 and not scan_config.acquisition.filename_pattern: + raise ValueError( + "--slice/--acquisition/--mosaic need acquisition.filename_pattern " + "when mosaics_per_slice == 3" + ) + logger.info("Using slice=%s mosaic_slot=%s from command line", fixed_slice_id, fixed_mosaic_slot) + logger.info("Using batch_size=%s", batch_size) logger.info("Using mosaics_per_slice=%s", scan_config.mosaics_per_slice) logger.info("Using tile_saving_type=%s", scan_config.acquisition.tile_saving_type) @@ -685,4 +788,6 @@ def watch( force_resend=force_resend, refresh_hook=refresh_hook, min_complex_file_size_bytes=min_complex_file_size_bytes, + fixed_slice_id=fixed_slice_id, + fixed_mosaic_slot=fixed_mosaic_slot, ) diff --git a/opticstream/config/psoct_scan_config.py b/opticstream/config/psoct_scan_config.py index 96f9355..6c86b1f 100644 --- a/opticstream/config/psoct_scan_config.py +++ b/opticstream/config/psoct_scan_config.py @@ -63,7 +63,9 @@ class PSOCTAcquisitionParams(BaseModel): "Optional full input filename template; null preserves legacy naming. " "Example: sub-{subject}_sample-slice{slice}_chunk-{image}_acq-{acquisition}_{modality}{extension}. " "slice037/chunk-0041/acq-normal0deg means slice 37, image 41, and the mosaic slot mapped from normal0deg. " - "Required placeholders: {slice}, {image}, {acquisition}; optional: {subject}, {modality}, {extension}. " + "Required placeholder: {image}; optional: {slice}, {acquisition}, {subject}, {modality}, {extension}. " + "Without {slice}/{acquisition} (e.g. spectral_{image}.nii), pass them to `ops oct watch` " + "via --slice and --acquisition (or --mosaic). " "Numbers accept zero padding; do not use :04d format specifiers. Literals and labels are case-sensitive. " "Suffixes/extensions may be literals or placeholders; matching an extension does not add support for its file format." ), @@ -420,7 +422,13 @@ class PSOCTScanConfigModel(BaseModel): stitch_3d_volumes: bool = Field( default=True, - description="Enable stitching of 3D volume outputs", + description=( + "Enable 3D mosaic volume stitching (including focus finding) and " + "mosaic volume uploads. When false, both are skipped without setting " + "volume milestones or emitting volume events. Per-tile volumes are " + "still saved (see processing.save_volume_outputs); enface workflows " + "are unaffected." + ), ) crop_focus_plane_depth: int = Field( diff --git a/opticstream/flows/psoct/mosaic_volume_stitch_flow.py b/opticstream/flows/psoct/mosaic_volume_stitch_flow.py index 8d1b041..5b9963e 100644 --- a/opticstream/flows/psoct/mosaic_volume_stitch_flow.py +++ b/opticstream/flows/psoct/mosaic_volume_stitch_flow.py @@ -287,6 +287,13 @@ def stitch_volume_flow( with OCT_STATE_SERVICE.open_mosaic(mosaic_ident=mosaic_ident) as mosaic_state: mosaic_state.mark_completed() return {} + if not config.stitch_3d_volumes: + logger.info( + f"Skipping volume stitching for mosaic {mosaic_ident} as stitch_3d_volumes is disabled" + ) + with OCT_STATE_SERVICE.open_mosaic(mosaic_ident=mosaic_ident) as mosaic_state: + mosaic_state.mark_completed() + return {} if should_skip_run( enter_milestone_stage( item_state_view=OCT_STATE_SERVICE.peek_mosaic(mosaic_ident=mosaic_ident), @@ -298,13 +305,6 @@ def stitch_volume_flow( with OCT_STATE_SERVICE.open_mosaic(mosaic_ident=mosaic_ident) as mosaic_state: mosaic_state.mark_completed() return {} - if not config.stitch_3d_volumes: - logger.info( - f"Skipping volume stitching for mosaic {mosaic_ident} as stitch_3d_volumes is disabled" - ) - with OCT_STATE_SERVICE.open_mosaic(mosaic_ident=mosaic_ident) as mosaic_state: - mosaic_state.mark_completed() - return {} ctx = mosaic_context_from_ident(mosaic_ident, config) mosaic_id = mosaic_ident.mosaic_id project_base_path = config.project_base_path diff --git a/opticstream/utils/oct_input_naming.py b/opticstream/utils/oct_input_naming.py index f34d1ee..cf207de 100644 --- a/opticstream/utils/oct_input_naming.py +++ b/opticstream/utils/oct_input_naming.py @@ -20,33 +20,52 @@ def compile_pattern(pattern): fields.add(field) value = r"[0-9]+" if field in {"slice", "image"} else (r"\.[A-Za-z0-9.]+" if field == "extension" else r"[^/\\]+?") parts.append(f"(?P<{field}>{value})") - if not {"slice", "image", "acquisition"} <= fields: - raise ValueError("filename_pattern requires {slice}, {image}, and {acquisition}.") + # {slice} and {acquisition} may instead be supplied by the watcher + # (ops oct watch --slice/--acquisition/--mosaic), e.g. "spectral_{image}.nii". + if "image" not in fields: + raise ValueError("filename_pattern requires {image}.") return re.compile("".join(parts)) @dataclass(frozen=True) class InputTile: - source_mosaic_id: int + # None when the filename has no {slice}/{acquisition} and none was supplied. + source_mosaic_id: int | None image_index: int modality: str -def parse_input_name(name, acquisition, mosaics_per_slice): +def parse_input_name(name, acquisition, mosaics_per_slice, *, slice_id=None, mosaic_slot=None): + """ + Parse an input filename with the configured pattern. + + ``slice_id`` / ``mosaic_slot`` fill in values the filename lacks. When the + filename also contains them, they act as filters: a mismatch returns None. + """ match = compile_pattern(acquisition.filename_pattern).fullmatch(name) if match is None: return None values = match.groupdict() - slot = acquisition.acquisition_mosaic_map.get(values["acquisition"]) - if slot is None: - return None - if not 1 <= slot <= mosaics_per_slice: + slot = mosaic_slot + if "acquisition" in values: + slot = acquisition.acquisition_mosaic_map.get(values["acquisition"]) + if slot is None or (mosaic_slot is not None and slot != mosaic_slot): + return None + if slot is not None and not 1 <= slot <= mosaics_per_slice: raise ValueError("acquisition_mosaic_map values must fit mosaics_per_slice.") - slice_id, image = int(values["slice"]), int(values["image"]) - if slice_id < 1 or image < 1: + file_slice = slice_id + if "slice" in values: + file_slice = int(values["slice"]) + if slice_id is not None and file_slice != slice_id: + return None + image = int(values["image"]) + if (file_slice is not None and file_slice < 1) or image < 1: raise ValueError("Filename slice and image numbers must be positive.") label = values.get("modality", acquisition.filename_default_modality) modality = acquisition.filename_modality_map.get(label) if modality is None: return None - return InputTile((slice_id - 1) * mosaics_per_slice + slot, image, modality) + source_mosaic_id = None + if file_slice is not None and slot is not None: + source_mosaic_id = (file_slice - 1) * mosaics_per_slice + slot + return InputTile(source_mosaic_id, image, modality) diff --git a/opticstream/utils/volume_settings.py b/opticstream/utils/volume_settings.py index 61a673e..a23eed9 100644 --- a/opticstream/utils/volume_settings.py +++ b/opticstream/utils/volume_settings.py @@ -17,6 +17,9 @@ def wrapper(*args, **kwargs): if not config.processing.save_volume_outputs: get_logger(__name__).info("Volume output disabled for %s; skipping volume upload", ident.project_name) return {"uploaded": 0} + if not config.stitch_3d_volumes: + get_logger(__name__).info("3D volume stitching disabled for %s; skipping volume upload", ident.project_name) + return {"uploaded": 0} return func(*args, **kwargs) return wrapper diff --git a/tests/test_oct_input_naming.py b/tests/test_oct_input_naming.py index d28fa18..8a1b0e5 100644 --- a/tests/test_oct_input_naming.py +++ b/tests/test_oct_input_naming.py @@ -41,7 +41,8 @@ def test_literal_suffix(self): def test_validation_and_legacy_default(self): self.assertIsNone(self.acquisition().filename_pattern) - for pattern in ("{image}", "{slice}_{image}_{acquisition}_{unknown}", "{slice}_{image}_{image}_{acquisition}"): + self.assertEqual(self.acquisition(filename_pattern="spectral_{image}.nii").filename_pattern, "spectral_{image}.nii") + for pattern in ("{slice}_{acquisition}.nii", "{slice}_{image}_{acquisition}_{unknown}", "{slice}_{image}_{image}_{acquisition}"): with self.assertRaises(ValueError): self.acquisition(filename_pattern=pattern) @@ -62,6 +63,59 @@ def test_watcher_discovery(self): self.assertEqual(len(candidates), 1) self.assertEqual(candidates[0].source_mosaic_id, mosaic) + def test_image_only_pattern_uses_supplied_slice_and_acquisition(self): + acq = self.acquisition(filename_pattern="spectral_{image}.nii") + parsed = parse_input_name("spectral_0041.nii", acq, 2) + self.assertEqual((parsed.source_mosaic_id, parsed.image_index, parsed.modality), (None, 41, "spectral")) + parsed = parse_input_name("spectral_0041.nii", acq, 2, slice_id=37, mosaic_slot=2) + self.assertEqual((parsed.source_mosaic_id, parsed.image_index), (74, 41)) + config = SimpleNamespace(acquisition=acq, mosaics_per_slice=2) + context = SimpleNamespace(grid_size_x=lambda cfg: 50) + path = Path("spectral_0041.nii") + refs = build_tile_file_reference_list([path], config=config, mosaic_context=context) + self.assertEqual(refs[41].spectral_file_path, path) + + def test_supplied_values_filter_full_pattern(self): + acq = self.acquisition(filename_pattern=PATTERN) + name = "sub-X_sample-slice037_chunk-0041_acq-normal0deg_spectral.nii" + self.assertEqual(parse_input_name(name, acq, 2, slice_id=37, mosaic_slot=1).source_mosaic_id, 73) + self.assertIsNone(parse_input_name(name, acq, 2, slice_id=38)) + self.assertIsNone(parse_input_name(name, acq, 2, mosaic_slot=2)) + + def test_resolve_fixed_mosaic(self): + from opticstream.cli.oct.watch import resolve_fixed_mosaic + cfg = SimpleNamespace(acquisition=self.acquisition(), mosaics_per_slice=2) + self.assertEqual(resolve_fixed_mosaic(cfg), (None, None)) + self.assertEqual(resolve_fixed_mosaic(cfg, slice_id=37, acquisition="tilted15deg"), (37, 2)) + self.assertEqual(resolve_fixed_mosaic(cfg, mosaic=74), (37, 2)) + self.assertEqual(resolve_fixed_mosaic(cfg, slice_id=37, acquisition="tilted15deg", mosaic=74), (37, 2)) + for kwargs in ({"acquisition": "unknown"}, {"slice_id": 36, "mosaic": 74}, + {"acquisition": "normal0deg", "mosaic": 74}, {"slice_id": 0}): + with self.assertRaises(ValueError): + resolve_fixed_mosaic(cfg, **kwargs) + + def _watcher(self, folder, pattern, **fixed): + return OCTWatcherService(project_name="test", folder_path=Path(folder), + project_base_path=folder, mosaic_ranges=[(1, 100)], slice_offset=0, + batch_size=1, scan_config=SimpleNamespace(acquisition=self.acquisition(filename_pattern=pattern), mosaics_per_slice=2), + direct=True, force_resend=False, **fixed) + + def test_watcher_image_only_names(self): + with TemporaryDirectory() as folder: + (Path(folder) / "spectral_0041.nii").write_bytes(b"\0" * (100 * 1024)) + self.assertEqual(self._watcher(folder, "spectral_{image}.nii")._discover_two_mosaic_files(), []) + watcher = self._watcher(folder, "spectral_{image}.nii", fixed_slice_id=37, fixed_mosaic_slot=1) + candidates = watcher.discover_candidates() + self.assertEqual(len(candidates), 1) + self.assertEqual((candidates[0].source_mosaic_id, candidates[0].logical_batch), (73, 41)) + + def test_watcher_filters_legacy_names(self): + with TemporaryDirectory() as folder: + for mosaic in (1, 2): + (Path(folder) / f"mosaic_{mosaic:03d}_image_0041_spectral_0041.nii").write_bytes(b"\0" * (100 * 1024)) + files = self._watcher(folder, None, fixed_slice_id=1, fixed_mosaic_slot=2)._discover_two_mosaic_files() + self.assertEqual([f.source_mosaic_id for f in files], [2]) + if __name__ == "__main__": unittest.main() diff --git a/tests/test_volume_output_setting.py b/tests/test_volume_output_setting.py index a37e9c9..79f789f 100644 --- a/tests/test_volume_output_setting.py +++ b/tests/test_volume_output_setting.py @@ -15,10 +15,11 @@ from opticstream.state.oct_project_state import OCTMosaicId -def config(tmp_path, enabled): +def config(tmp_path, enabled, stitch_3d_volumes=True): return PSOCTScanConfigModel(project_name="test", project_base_path=tmp_path, acquisition=dict(grid_size_x_normal=1, grid_size_x_tilted=1, grid_size_y=1), - processing=dict(save_volume_outputs=enabled), enface_modalities=["aip"], zarr_config=ZarrConfig()) + processing=dict(save_volume_outputs=enabled), enface_modalities=["aip"], zarr_config=ZarrConfig(), + stitch_3d_volumes=stitch_3d_volumes) def _check_command_flag_and_enface_validation(tmp_path, enabled): @@ -44,9 +45,8 @@ def _check_existing_blocks_default_enabled(): assert PSOCTProcessingParams.model_validate({}).save_volume_outputs is True -def _check_disabled_upload_skips_all_milestones(tmp_path): +def _check_disabled_upload_skips_all_milestones(tmp_path, cfg): from opticstream.flows.psoct.mosaic_volume_upload_flow import upload_mosaic_volume_to_dandi_flow - cfg = config(tmp_path, False) with patch("opticstream.utils.volume_settings.get_psoct_scan_config", return_value=cfg), \ patch("opticstream.state.milestone_wrappers_psoct.OCT_STATE_SERVICE") as state, \ patch("opticstream.flows.psoct.mosaic_volume_upload_flow.upload_to_dandi_batch") as upload: @@ -57,7 +57,7 @@ def _check_disabled_upload_skips_all_milestones(tmp_path): upload.assert_not_called() -def _check_disabled_stitch_skips_before_volume_milestone(tmp_path): +def _check_disabled_stitch_skips_before_volume_milestone(tmp_path, cfg): from opticstream.flows.psoct import mosaic_volume_stitch_flow as module @contextmanager def opened(**kwargs): @@ -67,7 +67,7 @@ def opened(**kwargs): patch.object(module, "enter_milestone_stage") as enter, \ patch.object(module, "emit_mosaic_psoct_event") as emit: result = module.stitch_volume_flow.fn( - mosaic_ident=OCTMosaicId(project_name="test", slice_id=1, mosaic_id=1), config=config(tmp_path, False)) + mosaic_ident=OCTMosaicId(project_name="test", slice_id=1, mosaic_id=1), config=cfg) assert result == {} enter.assert_not_called() emit.assert_not_called() @@ -84,8 +84,22 @@ def test_default(self): def test_upload(self): with TemporaryDirectory() as folder: - _check_disabled_upload_skips_all_milestones(Path(folder)) + _check_disabled_upload_skips_all_milestones(Path(folder), config(Path(folder), False)) def test_stitch(self): with TemporaryDirectory() as folder: - _check_disabled_stitch_skips_before_volume_milestone(Path(folder)) + _check_disabled_stitch_skips_before_volume_milestone(Path(folder), config(Path(folder), False)) + + def test_stitch_3d_volumes_disabled_skips_upload(self): + with TemporaryDirectory() as folder: + cfg = config(Path(folder), True, stitch_3d_volumes=False) + _check_disabled_upload_skips_all_milestones(Path(folder), cfg) + + def test_stitch_3d_volumes_disabled_skips_stitch(self): + with TemporaryDirectory() as folder: + cfg = config(Path(folder), True, stitch_3d_volumes=False) + _check_disabled_stitch_skips_before_volume_milestone(Path(folder), cfg) + + def test_stitch_3d_volumes_default_enabled(self): + with TemporaryDirectory() as folder: + self.assertTrue(config(Path(folder), True).stitch_3d_volumes) From ddbad5d82e0b485839ea988fbb13b34c438ea0f0 Mon Sep 17 00:00:00 2001 From: Noah Markowitz Date: Thu, 24 Sep 2026 14:28:08 -0400 Subject: [PATCH 25/65] many updates --- docs/acquisition_enface_previews.md | 65 +++++--- opticstream/cli/oct/watch.py | 91 ++++++++++- opticstream/cli/oct/watch_enface.py | 43 ++++-- opticstream/config/enface_preview.py | 6 +- opticstream/config/psoct_scan_config.py | 10 +- .../flows/psoct/acquisition_preview_flow.py | 97 +++++++++--- .../flows/psoct/mosaic_enface_qc_flow.py | 17 +- .../+psoct/+spectral/loadPhaseCalibration.m | 30 ++-- .../+psoct/+spectral/spectral2complex.m | 23 +-- opticstream/matlab/README.md | 6 + opticstream/matlab/angle2tensor.m | 19 +++ opticstream/matlab/tensor2angle.m | 26 ++++ opticstream/tasks/dandi_upload.py | 11 +- opticstream/utils/polling_watcher.py | 38 ++++- tests/test_acquisition_previews.py | 57 ++++++- tests/test_dandi_upload.py | 33 ++++ tests/test_watch_previews.py | 146 ++++++++++++++++++ 17 files changed, 625 insertions(+), 93 deletions(-) create mode 100644 opticstream/matlab/angle2tensor.m create mode 100644 opticstream/matlab/tensor2angle.m create mode 100644 tests/test_watch_previews.py diff --git a/docs/acquisition_enface_previews.md b/docs/acquisition_enface_previews.md index 9c80bd4..e3e500b 100644 --- a/docs/acquisition_enface_previews.md +++ b/docs/acquisition_enface_previews.md @@ -7,8 +7,12 @@ Two new Prefect flows call linc-convert `mosaic2d()` and send JPEG previews to S These consume AIP, MIP, orientation (`ori`) and retardance (`ret`) files written by the acquisition software, independently of spectral processing and MATLAB. They -do not set OpticStream processing/upload milestones. Existing processed-output QC -flows remain separate. Preview images are not uploaded to DANDI or LINC. +do not set OpticStream processing/upload milestones. Preview images are not +uploaded to DANDI or LINC. + +These previews are the pipeline's Slack QC images. The pipeline's own stitched 2D +mosaics (`slice-NN/stitched/mosaic_NNN_*.jpg`) are still written but are posted to +Slack only when the block's `stitched_enface_slack_upload` is true (default false). ## Configure and run @@ -16,22 +20,25 @@ Refresh saved block schemas with `python -m opticstream.config.migrate_psoct_blo --apply` using the project's virtual environment. In the block's new `enface_preview` group, configure all four filename patterns. They are exact Python format templates (not globs), with `{image}` required and `{slice}`, `{mosaic}`, -`{acquisition}`, `{project}` optional. Numeric formats such as `{image:04d}` are -supported. These templates are separate from the spectral watcher's parser. +`{acquisition}`, `{project}` optional. A plain `{image}` matches the tile number with +any zero padding (`spectral_{image}_processed_aip.nii` finds +`spectral_0001_processed_aip.nii`), like the spectral watcher's `filename_pattern`. +An explicit format such as `{image:04d}` renders the name exactly instead. Two files +that differ only in padding (`aip_1.nii` and `aip_0001.nii`) are an error. For example: ```json { - "aip_pattern": "slice-{slice}_acq-{acquisition}_aip_{image:04d}.nii", - "mip_pattern": "slice-{slice}_acq-{acquisition}_mip_{image:04d}.nii", - "ori_pattern": "slice-{slice}_acq-{acquisition}_ori_{image:04d}.nii", - "ret_pattern": "slice-{slice}_acq-{acquisition}_ret_{image:04d}.nii" + "aip_pattern": "slice-{slice}_acq-{acquisition}_aip_{image}.nii", + "mip_pattern": "slice-{slice}_acq-{acquisition}_mip_{image}.nii", + "ori_pattern": "slice-{slice}_acq-{acquisition}_ori_{image}.nii", + "ret_pattern": "slice-{slice}_acq-{acquisition}_ret_{image}.nii" } ``` Change names/suffixes to match the acquisition software exactly. Simple names such -as `aip_{image:04d}.nii` are supported when the folder contains only that acquisition. +as `aip_{image}.nii` are supported when the folder contains only that acquisition. NIfTI (.nii/.nii.gz) and formats supported by the existing QC loader are accepted; only 2D maps or maps with singleton trailing dimensions are supported. All four modalities must be present for every expected tile before a candidate is ready. @@ -39,12 +46,28 @@ modalities must be present for every expected tile before a candidate is ready. From Miniforge Prompt, with the project's venv activated and Prefect API configured: ```cmd -opticstream oct watch-enface human-10um D:\data\acquisition --slice 1 --mosaic 1 --acquisition normal +opticstream oct watch human-10um D:\data\acquisition --slice 1 --acquisition normal0deg +``` + +The main `oct watch` runs the previews in a background polling loop next to batch +dispatch whenever it knows the folder's slice and mosaic (`--slice` with `--acquisition`, or +`--mosaic`); the acquisition label is looked up from `acquisition_mosaic_map` when +only `--mosaic` is given. Previews do not wait for batch processing (e.g. MATLAB on +the last batch): the full-acquisition preview starts as soon as the last batch's +maps have been stable for `--stability-seconds` (default 15), ahead of any batch +previews still pending. A preview error is logged and never stops batch watching. +Pass `--no-previews` to turn them off for one run, or disable them in the block with +`batch_enabled`/`acquisition_enabled`. + +To preview without processing, run the standalone watcher instead: + +```cmd +opticstream oct watch-enface human-10um D:\data\acquisition --slice 1 --mosaic 1 --acquisition normal0deg ``` -This command runs the flows directly as files stabilize; it does not require -`oct serve`. `oct serve all` additionally registers the two manual preview flows. -The existing `oct watch` remains unchanged; run `watch-enface` separately. +Both run the flows directly as files stabilize; neither requires `oct serve`. +`oct serve all` additionally registers the two manual preview flows. Do not run +`watch` and `watch-enface` for the same acquisition at the same time. Use one watcher per acquisition, and do not run a manual preview for the same acquisition concurrently. Select the correct mosaic ID (normal vs tilted) so the existing `grid_size_x_normal`/`grid_size_x_tilted` selects the correct batch count. @@ -97,9 +120,15 @@ Corrupt or inconsistent tiles cause failure rather than a partial mosaic. ## Outputs, Slack and retries -Outputs and per-scope `progress.json` checkpoints are under -`project_base_path/acquisition-previews/slice-NNN/mosaic-NNN/`, with separate -`batch-NNNN` and `acquisition` directories. Completed work is skipped on restart. +All previews for a slice go in one folder, `project_base_path/slice-NN/acquisition_previews/`, +next to the pipeline's `processed/` and `stitched/`. File names carry the mosaic (and +batch) so mosaics never collide: + +- full acquisition: `mosaic_001_aip.nii`, `mosaic_001_aip.jpg`, ... and `mosaic_001_progress.json` +- batch 3: `mosaic_001_batch_0003_aip.nii`, `mosaic_001_batch_0003_aip.jpg`, ... and + `mosaic_001_batch_0003_progress.json` + +The `progress.json` files are per-scope checkpoints. Completed work is skipped on restart. Input path/size/mtime or relevant configuration changes invalidate checkpoints. Changing only file content without changing size/mtime is not detected. @@ -112,5 +141,5 @@ after Slack accepts an upload but before the checkpoint is saved can duplicate i `matlab_processing_enabled` does not gate these non-MATLAB flows. Disable batch or full previews independently with `batch_enabled`/`acquisition_enabled`. Restart the watcher after editing block fields. A project-state reset does not erase preview -checkpoints; to deliberately resend, archive/move the relevant preview output -directory while the watcher is stopped. +checkpoints; to deliberately resend, delete or move that scope's `*_progress.json` +while the watcher is stopped (deleting only its `.nii`/`.jpg` restitches without resending). diff --git a/opticstream/cli/oct/watch.py b/opticstream/cli/oct/watch.py index 7ee0748..e694906 100644 --- a/opticstream/cli/oct/watch.py +++ b/opticstream/cli/oct/watch.py @@ -23,7 +23,7 @@ mosaic_position_in_slice, slice_from_mosaic, ) -from opticstream.state.oct_project_state import OCT_STATE_SERVICE +from opticstream.state.oct_project_state import OCT_STATE_SERVICE, OCTMosaicId from opticstream.utils.filename_utils import ( extract_processed_index_from_filename, extract_spectral_index_from_filename, @@ -658,6 +658,70 @@ def _process_event(self, candidate: OCTBatchCandidate, batch_ident: Any) -> int: return 1 +def build_watch_previews( + scan_config: PSOCTScanConfigModel, + *, + project_name: str, + folder_path: Path, + fixed_slice_id: int | None, + fixed_mosaic_slot: int | None, + acquisition: str | None, + slice_offset: int, + stability_seconds: int, + poll_interval: int, +) -> PollingStableWatcher | None: + """Enface preview watcher for the folder's slice/mosaic, or None when not applicable.""" + preview = scan_config.enface_preview + if not (preview.batch_enabled or preview.acquisition_enabled): + logger.info("Enface previews disabled in the block (batch_enabled/acquisition_enabled)") + return None + if fixed_slice_id is None or fixed_mosaic_slot is None: + logger.info( + "Enface previews need the folder's slice and mosaic; pass --slice with " + "--acquisition, or --mosaic, to enable them" + ) + return None + if acquisition is None: + labels = [ + label + for label, slot in scan_config.acquisition.acquisition_mosaic_map.items() + if slot == fixed_mosaic_slot + ] + if not labels: + logger.warning( + "No acquisition_mosaic_map label for mosaic slot %s; enface previews off", + fixed_mosaic_slot, + ) + return None + acquisition = labels[0] + source_mosaic_id = (fixed_slice_id - 1) * scan_config.mosaics_per_slice + fixed_mosaic_slot + logical_slice_id, logical_mosaic_id = logical_mosaic_from_source_mosaic( + source_mosaic_id, + mosaics_per_slice=scan_config.mosaics_per_slice, + slice_offset=slice_offset, + ) + ident = OCTMosaicId( + project_name=project_name, slice_id=logical_slice_id, mosaic_id=logical_mosaic_id + ) + # Imported here: watch_enface imports this module. + from opticstream.cli.oct.watch_enface import build_preview_watcher + + logger.info( + "Enface previews on for slice=%s mosaic=%s acquisition=%s", + logical_slice_id, + logical_mosaic_id, + acquisition, + ) + return build_preview_watcher( + scan_config, + ident, + folder_path, + acquisition, + stability_seconds=stability_seconds, + poll_interval=poll_interval, + ) + + def watch_oct( *, project_name: str, @@ -675,6 +739,7 @@ def watch_oct( min_complex_file_size_bytes: int = 1, fixed_slice_id: int | None = None, fixed_mosaic_slot: int | None = None, + companions: tuple[PollingStableWatcher, ...] = (), ) -> None: service = OCTWatcherService( project_name=project_name, @@ -701,7 +766,7 @@ def watch_oct( stability_seconds=stability_seconds, running_message=f"OCT polling watcher running ({'direct' if direct else 'event'} mode)", ) - watcher.run() + watcher.run(*companions) @oct_cli.command @@ -720,6 +785,7 @@ def watch( slice: int | None = None, acquisition: str | None = None, mosaic: int | None = None, + previews: bool = True, verbose: bool = False, ) -> None: """ @@ -742,6 +808,10 @@ def watch( and filter files whose names already contain them. --acquisition is a label from acquisition.acquisition_mosaic_map; --mosaic is a global source mosaic id and can replace --slice/--acquisition. + + With the slice and mosaic known, a background loop also stitches enface previews + from the acquisition's own AIP/MIP/orientation/retardance maps (block + enface_preview settings) and posts them to Slack. --no-previews turns this off. """ _configure_logging(verbose) @@ -774,6 +844,22 @@ def watch( logger.info("Using mosaics_per_slice=%s", scan_config.mosaics_per_slice) logger.info("Using tile_saving_type=%s", scan_config.acquisition.tile_saving_type) + companions = () + if previews: + preview_watcher = build_watch_previews( + scan_config, + project_name=project_name, + folder_path=watch_path, + fixed_slice_id=fixed_slice_id, + fixed_mosaic_slot=fixed_mosaic_slot, + acquisition=acquisition, + slice_offset=slice_offset, + stability_seconds=stability_seconds, + poll_interval=poll_interval, + ) + if preview_watcher is not None: + companions = (preview_watcher,) + watch_oct( project_name=project_name, folder_path=watch_path, @@ -790,4 +876,5 @@ def watch( min_complex_file_size_bytes=min_complex_file_size_bytes, fixed_slice_id=fixed_slice_id, fixed_mosaic_slot=fixed_mosaic_slot, + companions=companions, ) diff --git a/opticstream/cli/oct/watch_enface.py b/opticstream/cli/oct/watch_enface.py index 8093635..0bf6cb0 100644 --- a/opticstream/cli/oct/watch_enface.py +++ b/opticstream/cli/oct/watch_enface.py @@ -5,7 +5,7 @@ from opticstream.cli.oct.watch import _configure_logging from opticstream.config.psoct_scan_config import get_psoct_scan_config from opticstream.flows.psoct.acquisition_preview_flow import ( - MODALITIES, expected_tiles, fingerprint, preview_dir, read_progress, + MODALITIES, expected_tiles, fingerprint, preview_path, progress_path, read_progress, preview_enface_batch, preview_enface_acquisition, ) from opticstream.flows.psoct.utils import mosaic_context_from_ident @@ -21,9 +21,11 @@ def __init__(self, config, mosaic_ident, folder, acquisition): self.folder = Path(folder) self.acquisition = acquisition context = mosaic_context_from_ident(mosaic_ident, config) - self.candidates = list(range(1, context.grid_size_x(config) + 1)) if config.enface_preview.batch_enabled else [] - if config.enface_preview.acquisition_enabled: - self.candidates.append(None) + # The full acquisition goes first: once its last batch is stable it is + # stitched before any batch previews still waiting in the same pass. + self.candidates = [None] if config.enface_preview.acquisition_enabled else [] + if config.enface_preview.batch_enabled: + self.candidates += list(range(1, context.grid_size_x(config) + 1)) def files(self, batch): return expected_tiles(self.config, self.ident, self.folder, self.acquisition, batch) @@ -41,10 +43,11 @@ def discover(self): signature = fingerprint(self.config, files) except (OSError, ValueError): continue - directory = preview_dir(self.config, self.ident, batch) - progress = read_progress(directory, signature) - stitched = all(m in progress["stitched"] and (directory / f"{m}.jpg").exists() - and (directory / f"{m}.nii").exists() for m in MODALITIES) + progress = read_progress(progress_path(self.config, self.ident, batch), signature) + stitched = all(m in progress["stitched"] + and preview_path(self.config, self.ident, batch, f"{m}.jpg").exists() + and preview_path(self.config, self.ident, batch, f"{m}.nii").exists() + for m in MODALITIES) uploaded = all(m in progress["uploaded"] for m in MODALITIES) if not stitched or (slack_enabled and not uploaded): yield batch @@ -59,12 +62,27 @@ def process(self, batch): return 1 +def build_preview_watcher(config, mosaic_ident, folder, acquisition, *, + stability_seconds=15, poll_interval=5): + """Polling watcher that stitches previews for one acquisition folder.""" + worker = EnfacePreviewWatcher(config, mosaic_ident, Path(folder).resolve(), acquisition) + # Validate templates before entering the polling loop. + worker.files(None) + return PollingStableWatcher(discover_candidates=worker.discover, + candidate_key=lambda batch: batch, fingerprint=worker.fingerprint, + process=worker.process, stability_seconds=stability_seconds, + poll_interval=poll_interval, running_message="Watching acquisition enface maps") + + @oct_cli.command def watch_enface(project_name: str, folder_path: Path, *, slice: int, mosaic: int, acquisition: str, stability_seconds: int = 15, poll_interval: int = 5, verbose: bool = False): """Watch one acquisition for complete batches and a complete full mosaic. + `ops oct watch` already runs these previews when given --slice/--acquisition + or --mosaic; use this command only to preview without processing. + slice/mosaic identify the acquisition explicitly, allowing filenames such as aip_0001.nii without embedded IDs. acquisition substitutes into file patterns. Use one watcher per acquisition. No MATLAB or spectral watcher is required. @@ -78,10 +96,5 @@ def watch_enface(project_name: str, folder_path: Path, *, slice: int, mosaic: in if not config.enface_preview.batch_enabled and not config.enface_preview.acquisition_enabled: raise ValueError("Both enface preview flows are disabled in this block") ident = OCTMosaicId(project_name=project_name, slice_id=slice, mosaic_id=mosaic) - worker = EnfacePreviewWatcher(config, ident, folder_path.resolve(), acquisition) - # Validate templates before entering the polling loop. - worker.files(None) - PollingStableWatcher(discover_candidates=worker.discover, - candidate_key=lambda batch: batch, fingerprint=worker.fingerprint, - process=worker.process, stability_seconds=stability_seconds, - poll_interval=poll_interval, running_message="Watching acquisition enface maps").run() + build_preview_watcher(config, ident, folder_path, acquisition, + stability_seconds=stability_seconds, poll_interval=poll_interval).run() diff --git a/opticstream/config/enface_preview.py b/opticstream/config/enface_preview.py index 1d30936..168d6ee 100644 --- a/opticstream/config/enface_preview.py +++ b/opticstream/config/enface_preview.py @@ -8,9 +8,9 @@ class PreviewGridConfig(BaseModel): model_config = ConfigDict(extra="forbid", validate_assignment=True) - grid_type: Literal["row-by-row", "column-by-column", "snake-by-rows", "snake-by-columns"] = Field( + grid_type: Literal["snake-by-columns", "row-by-row", "column-by-column", "snake-by-rows"] = Field( default="column-by-column", description="Acquisition traversal. Snake reverses the fast direction on alternate strips; individual images are not flipped. Each strip still contains grid_size_y consecutive tiles.") - order: Literal["right-down", "left-down", "right-up", "left-up", "down-right", "down-left", "up-right", "up-left"] = Field( + order: Literal["up-right", "right-down", "left-down", "right-up", "left-up", "down-right", "down-left", "up-left"] = Field( default="down-right", description="Rows: right-down (top-left), left-down (top-right), right-up (bottom-left), left-up (bottom-right). Columns: down-right (top-left), down-left (top-right), up-right (bottom-left), up-left (bottom-right). First word is initial within-strip movement; second is movement between strips. Must match grid_type.") @model_validator(mode="after") @@ -27,7 +27,7 @@ class EnfacePreviewConfig(BaseModel): batch_enabled: bool = Field(default=True, description="Stitch each complete grid_size_y-tile batch and send previews to Slack when watch-enface runs.") acquisition_enabled: bool = Field(default=True, description="Also stitch the complete acquisition/mosaic and send previews to Slack.") - aip_pattern: str = Field(default="mosaic_{mosaic:03d}_image_{image:04d}_aip.nii", description="Exact filename format, not a glob. Required {image}; optional {slice}, {mosaic}, {acquisition}, {project}. Supports :04d zero-padding. Example: slice-{slice}_acq-{acquisition}_aip_{image:04d}.nii") + aip_pattern: str = Field(default="mosaic_{mosaic:03d}_image_{image:04d}_aip.nii", description="Filename format, not a glob. Required {image}; optional {slice}, {mosaic}, {acquisition}, {project}. A plain {image} matches the number with any zero padding (1, 01, 0001), like filename_pattern; {image:04d} renders exactly. Example: slice-{slice}_acq-{acquisition}_aip_{image}.nii") mip_pattern: str = Field(default="mosaic_{mosaic:03d}_image_{image:04d}_mip.nii", description="MIP filename format; same placeholders as aip_pattern. Set the actual suffix, including .nii.gz if used.") ori_pattern: str = Field(default="mosaic_{mosaic:03d}_image_{image:04d}_ori.nii", description="Orientation filename format. Orientation is blended with circular averaging.") ret_pattern: str = Field(default="mosaic_{mosaic:03d}_image_{image:04d}_ret.nii", description="Retardance filename format; no hardcoded modality suffix.") diff --git a/opticstream/config/psoct_scan_config.py b/opticstream/config/psoct_scan_config.py index 6c86b1f..29fec42 100644 --- a/opticstream/config/psoct_scan_config.py +++ b/opticstream/config/psoct_scan_config.py @@ -333,7 +333,15 @@ class PSOCTScanConfigModel(BaseModel): enface_preview: EnfacePreviewConfig = Field( default_factory=EnfacePreviewConfig, - description="Acquisition-produced AIP/MIP/orientation/retardance previews for watch-enface; independent of MATLAB and spectral processing state.", + description="Acquisition-produced AIP/MIP/orientation/retardance previews, stitched by `ops oct watch` (or watch-enface) and posted to Slack; independent of MATLAB and spectral processing state.", + ) + stitched_enface_slack_upload: bool = Field( + default=False, + description=( + "Post the pipeline's stitched 2D enface mosaics (slice-NN/stitched/mosaic_NNN_*.jpg) " + "to Slack. The JPEGs are always written; when false, only the acquisition " + "previews (enface_preview) go to Slack." + ), ) mask_threshold_normal: float = Field( diff --git a/opticstream/flows/psoct/acquisition_preview_flow.py b/opticstream/flows/psoct/acquisition_preview_flow.py index 4828fc7..2e35154 100644 --- a/opticstream/flows/psoct/acquisition_preview_flow.py +++ b/opticstream/flows/psoct/acquisition_preview_flow.py @@ -5,7 +5,10 @@ """ import hashlib import json +import os from pathlib import Path +import re +from string import Formatter import tempfile import time @@ -16,7 +19,7 @@ from opticstream.config.psoct_scan_config import PSOCTScanConfigModel from opticstream.data_processing.qc.convert_image import convert_image -from opticstream.flows.psoct.utils import mosaic_context_from_ident +from opticstream.flows.psoct.utils import get_slice_paths, mosaic_context_from_ident from opticstream.state.oct_project_state import OCTMosaicId from opticstream.tasks.slack_notification import upload_multiple_files_to_slack from opticstream.utils.slack_settings import slack_notifications_enabled @@ -24,6 +27,42 @@ MODALITIES = ("aip", "mip", "ori", "ret") +def _padded_image_matches(pattern, values, root): + """Map image number -> filename for a pattern whose {image} has no format spec. + + Like filename_pattern, a bare {image} matches any zero padding (1, 01, 0001), + compared as a number. Returns None when {image} has an explicit format spec + (e.g. {image:04d}), which keeps exact rendering. + """ + parts = [] + for literal, field, spec, conversion in Formatter().parse(pattern): + parts.append(re.escape(literal)) + if field is None: + continue + if field == "image": + if spec or conversion: + return None + parts.append(r"(?P[0-9]+)") + else: + parts.append(re.escape(format(values[field], spec))) + regex = re.compile("".join(parts)) + matches = {} + try: + entries = list(os.scandir(root)) + except FileNotFoundError: + return matches + for entry in entries: + found = regex.fullmatch(entry.name) + if found is None: + continue + number = int(found["image"]) + if number in matches: + raise ValueError(f"Several files match image {number} of {pattern!r}: " + f"{matches[number]}, {entry.name}") + matches[number] = entry.name + return matches + + def expected_tiles(config, mosaic_ident, input_dir, acquisition, batch_id=None): """Return exact expected paths, never infer completeness from file counts.""" context = mosaic_context_from_ident(mosaic_ident, config) @@ -33,14 +72,17 @@ def expected_tiles(config, mosaic_ident, input_dir, acquisition, batch_id=None): raise ValueError(f"batch_id must be between 1 and {columns}") indices = range(columns * rows) if batch_id is None else range((batch_id - 1) * rows, batch_id * rows) root = Path(input_dir).resolve() + values = dict(slice=mosaic_ident.slice_id, mosaic=mosaic_ident.mosaic_id, + acquisition=acquisition, project=mosaic_ident.project_name) result = {} for modality in MODALITIES: pattern = getattr(config.enface_preview, f"{modality}_pattern") + existing = _padded_image_matches(pattern, values, root) paths = {} for index in indices: - name = pattern.format(image=index + config.enface_preview.first_image, - slice=mosaic_ident.slice_id, mosaic=mosaic_ident.mosaic_id, - acquisition=acquisition, project=mosaic_ident.project_name) + image = index + config.enface_preview.first_image + # Missing tiles keep the unpadded name so callers still see them as absent. + name = (existing or {}).get(image) or pattern.format(image=image, **values) path = (root / name).resolve() if path.parent != root: raise ValueError("Rendered preview filename must remain inside the input directory") @@ -64,14 +106,27 @@ def fingerprint(config, files): return hashlib.sha256(json.dumps([records, settings], sort_keys=True).encode()).hexdigest() -def preview_dir(config, mosaic_ident, batch_id=None): - scope = "acquisition" if batch_id is None else f"batch-{batch_id:04d}" - return Path(config.project_base_path) / "acquisition-previews" / f"slice-{mosaic_ident.slice_id:03d}" / f"mosaic-{mosaic_ident.mosaic_id:03d}" / scope +def preview_dir(config, mosaic_ident): + """``{project_base}/slice-NN/acquisition_previews``, shared by all mosaics of a slice.""" + slice_path, *_ = get_slice_paths(config.project_base_path, mosaic_ident.slice_id) + return slice_path / "acquisition_previews" + + +def preview_path(config, mosaic_ident, batch_id, name): + """Scope-prefixed file, e.g. ``mosaic_001_aip.nii`` or ``mosaic_001_batch_0003_aip.nii``.""" + prefix = f"mosaic_{mosaic_ident.mosaic_id:03d}" + if batch_id is not None: + prefix += f"_batch_{batch_id:04d}" + return preview_dir(config, mosaic_ident) / f"{prefix}_{name}" + + +def progress_path(config, mosaic_ident, batch_id=None): + return preview_path(config, mosaic_ident, batch_id, "progress.json") -def read_progress(directory, signature): +def read_progress(path, signature): try: - data = json.loads((directory / "progress.json").read_text()) + data = json.loads(Path(path).read_text()) except (FileNotFoundError, ValueError): return {"signature": signature, "stitched": [], "uploaded": []} if data.get("signature") != signature: @@ -79,14 +134,15 @@ def read_progress(directory, signature): return data -def save_progress(directory, progress): - directory.mkdir(parents=True, exist_ok=True) - temporary = directory / "progress.json.tmp" +def save_progress(path, progress): + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + temporary = path.with_name(path.name + ".tmp") temporary.write_text(json.dumps(progress, indent=2)) # Windows indexers/antivirus may briefly hold the replaced file open. for attempt in range(5): try: - temporary.replace(directory / "progress.json") + temporary.replace(path) break except PermissionError: if attempt == 4: @@ -181,21 +237,22 @@ def run_preview(config, mosaic_ident, input_dir, acquisition, batch_id=None): return {} files = expected_tiles(config, mosaic_ident, input_dir, acquisition, batch_id) signature = fingerprint(config, files) - directory = preview_dir(config, mosaic_ident, batch_id) - progress = read_progress(directory, signature) + progress_file = progress_path(config, mosaic_ident, batch_id) + progress = read_progress(progress_file, signature) + outputs = {m: preview_path(config, mosaic_ident, batch_id, f"{m}.nii") for m in MODALITIES} for modality in MODALITIES: - output = directory / f"{modality}.nii" + output = outputs[modality] if modality not in progress["stitched"] or not output.with_suffix(".jpg").exists() or not output.exists(): stitch_preview_modality(config, files[modality], modality, output, batch_id) if fingerprint(config, files) != signature: raise RuntimeError("Acquisition files changed while stitching; wait for stability and retry") if modality not in progress["stitched"]: progress["stitched"].append(modality) - save_progress(directory, progress) + save_progress(progress_file, progress) if slack_notifications_enabled(): remaining = [m for m in MODALITIES if m not in progress["uploaded"]] if remaining: - paths = [str(directory / f"{m}.jpg") for m in remaining] + paths = [str(outputs[m].with_suffix(".jpg")) for m in remaining] scope = "full acquisition" if batch_id is None else f"batch {batch_id}" label = f"{mosaic_ident.project_name}, slice {mosaic_ident.slice_id}, mosaic {mosaic_ident.mosaic_id}, {acquisition}, {scope}" results = upload_multiple_files_to_slack(filepaths=paths, @@ -203,10 +260,10 @@ def run_preview(config, mosaic_ident, input_dir, acquisition, batch_id=None): for modality, path in zip(remaining, paths): if results.get(path): progress["uploaded"].append(modality) - save_progress(directory, progress) + save_progress(progress_file, progress) if any(not results.get(path) for path in paths): raise RuntimeError("Some preview Slack uploads failed; successful uploads are checkpointed") - return {m: str(directory / f"{m}.jpg") for m in MODALITIES} + return {m: str(outputs[m].with_suffix(".jpg")) for m in MODALITIES} @flow(name="preview-enface-batch") diff --git a/opticstream/flows/psoct/mosaic_enface_qc_flow.py b/opticstream/flows/psoct/mosaic_enface_qc_flow.py index 1710f0c..4c8429b 100644 --- a/opticstream/flows/psoct/mosaic_enface_qc_flow.py +++ b/opticstream/flows/psoct/mosaic_enface_qc_flow.py @@ -11,6 +11,7 @@ from prefect import flow, task from prefect.logging import get_run_logger +from opticstream.config.psoct_scan_config import get_psoct_scan_config from opticstream.data_processing.qc.convert_image import convert_image from opticstream.events import MOSAIC_ENFACE_STITCHED from opticstream.events.utils import get_event_trigger @@ -80,10 +81,13 @@ def mosaic_enface_qc_slack_upload_flow( *, mosaic_ident: OCTMosaicId, enface_outputs: Dict[str, Path], + upload_to_slack: Optional[bool] = None, ) -> Dict[str, bool]: """ - Convert stitched enface NIfTIs to JPEG previews and upload to Slack. + Convert stitched enface NIfTIs to JPEG previews and optionally upload to Slack. + ``upload_to_slack`` defaults to the block's ``stitched_enface_slack_upload``; + pass True for a manual rerun that should post regardless. Best-effort: any Slack failure is logged and returns False results. """ logger = get_run_logger() @@ -117,6 +121,17 @@ def mosaic_enface_qc_slack_upload_flow( logger.warning(f"No QC JPEGs to upload for mosaic {mosaic_id}") return {m: False for m in expected_modalities} + if upload_to_slack is None: + upload_to_slack = get_psoct_scan_config( + mosaic_ident.project_name + ).stitched_enface_slack_upload + if not upload_to_slack: + logger.info( + f"Wrote {len(modality_to_jpeg)} QC JPEGs for mosaic {mosaic_id}; Slack upload " + "off (stitched_enface_slack_upload=false)" + ) + return {m: False for m in expected_modalities} + filepaths = [str(p) for p in modality_to_jpeg.values()] titles = [f"Mosaic {mosaic_id} - {m.upper()}" for m in modality_to_jpeg.keys()] initial_comment = f"Enface QC previews for mosaic {mosaic_id}" diff --git a/opticstream/matlab/+psoct/+spectral/loadPhaseCalibration.m b/opticstream/matlab/+psoct/+spectral/loadPhaseCalibration.m index c9fb85c..e7f17e9 100644 --- a/opticstream/matlab/+psoct/+spectral/loadPhaseCalibration.m +++ b/opticstream/matlab/+psoct/+spectral/loadPhaseCalibration.m @@ -10,21 +10,21 @@ end calibration.dphase = readVector(folder, 'dphase', sampleCount, dphaseFile); calibration.linPhase = readVector(folder, 'linPhase', sampleCount, linPhaseFile); -delta = diff(calibration.dphase); -if ~(all(delta > 0) || all(delta < 0)) - error('psoct:calibration:NonMonotonic', 'dphase must be strictly monotonic with no repeated samples.'); -end -delta = diff(calibration.linPhase); -if ~(all(delta > 0) || all(delta < 0)) - error('psoct:calibration:NonMonotonic', 'linPhase must be strictly monotonic.'); -end -tolerance = max(abs(mean(delta))*1e-5, 100*eps(max(abs(calibration.linPhase)))); -if any(abs(delta - mean(delta)) > tolerance) - error('psoct:calibration:NonUniform', 'linPhase must be uniformly spaced.'); -end -if min(calibration.linPhase) < min(calibration.dphase) || max(calibration.linPhase) > max(calibration.dphase) - warning('psoct:calibration:Extrapolation', 'linPhase extends beyond dphase; linear extrapolation will be used.'); -end +% delta = diff(calibration.dphase); +% if ~(all(delta > 0) || all(delta < 0)) +% error('psoct:calibration:NonMonotonic', 'dphase must be strictly monotonic with no repeated samples.'); +% end +% delta = diff(calibration.linPhase); +% if ~(all(delta > 0) || all(delta < 0)) +% error('psoct:calibration:NonMonotonic', 'linPhase must be strictly monotonic.'); +% end +% tolerance = max(abs(mean(delta))*1e-5, 100*eps(max(abs(calibration.linPhase)))); +% if any(abs(delta - mean(delta)) > tolerance) +% error('psoct:calibration:NonUniform', 'linPhase must be uniformly spaced.'); +% end +% if min(calibration.linPhase) < min(calibration.dphase) || max(calibration.linPhase) > max(calibration.dphase) +% warning('psoct:calibration:Extrapolation', 'linPhase extends beyond dphase; linear extrapolation will be used.'); +% end calibration.dispersion = []; if useDispersion dspPhase = readVector(folder, 'dspPhase', sampleCount, dspPhaseFile); diff --git a/opticstream/matlab/+psoct/+spectral/spectral2complex.m b/opticstream/matlab/+psoct/+spectral/spectral2complex.m index 5bea857..92502b1 100644 --- a/opticstream/matlab/+psoct/+spectral/spectral2complex.m +++ b/opticstream/matlab/+psoct/+spectral/spectral2complex.m @@ -9,7 +9,8 @@ % - dispCompFile: Path to the dispersion compensation file. % - AlineSize : Size of the A-line (pixels of X axis). % - BlineSize : Size of the B-line (pixels of Y axis). -% - isRawFormat : Whether input is in packed 12-bit raw format. +% - isRawFormat : Input is headerless packed 12-bit data +% (read into local variable is12bit). % outputOpts : Struct with fields: % - Paths : Struct with fields: % - complex : Path to the output complex NIfTI file. @@ -33,7 +34,7 @@ dispCompFile = string(spectralOpts.dispCompFile); AlineSize = spectralOpts.AlineSize; BlineSize = spectralOpts.BlineSize; -isRawFormat = spectralOpts.isRawFormat; +is12bit = spectralOpts.isRawFormat; % packed 12-bit, headerless (tile_saving_type=spectral_12bit) % Constants describing the acquisition format. HEADER_BYTES = 352; % Header size of Nifti-1 file @@ -51,7 +52,7 @@ DepthL = 1024 - AutoCorrPeakCut; %#ok kept for compatibility AlineLength = 2048; % Headerless packed raw retains its legacy geometry. niftiData = []; -if ~isRawFormat +if ~is12bit info = niftiinfo(spectralFile); niftiData = niftiread(info); dims = size(niftiData); @@ -74,7 +75,7 @@ % Buffer size bookkeeping numSamplesPerBuffer = AlineLength * AlineSize; -if isRawFormat +if is12bit % Packed 12-bit: 3 bytes per 2 samples bytesPerBuffer = numSamplesPerBuffer * (BITS_PER_SAMPLE_RAW / 8); else @@ -128,7 +129,7 @@ params.InterpolatedWavelengths = InterpolatedWavelengths2; % Read the channel-specific corrections from the two halves of one file. -if phaseMode && spectralOpts.phaseCalibrationDispersion +if phaseMode && spectralOpts.phaseCalibrationDispersion && ~isempty(calibration.dispersion) phaseCorrection1 = calibration.dispersion; phaseCorrection2 = calibration.dispersion; else @@ -149,7 +150,7 @@ fileInfo = dir(spectralFile); if ~isempty(fileInfo) expectedBytes = Bline * (2 * bytesPerBuffer); - if ~isRawFormat + if ~is12bit expectedBytes = expectedBytes + HEADER_BYTES; end if fileInfo.bytes < expectedBytes @@ -173,9 +174,9 @@ end % Read raw wavelength buffers for both polarization channels - if isRawFormat + if is12bit [WavelengthBuffer1, WavelengthBuffer2] = readBlineBuffers( ... - fid, blineIndex, params, isRawFormat, HEADER_BYTES); + fid, blineIndex, params, is12bit, HEADER_BYTES); else WavelengthBuffer1 = double(niftiData(:, 1:Aline, blineIndex)); WavelengthBuffer2 = double(niftiData(:, Aline+1:2*Aline, blineIndex)); @@ -224,11 +225,11 @@ % ------------------------------------------------------------------------- function [WavelengthBuffer1, WavelengthBuffer2] = readBlineBuffers( ... - fid, blineIndex, params, isRawFormat, headerBytes) + fid, blineIndex, params, is12bit, headerBytes) %READBLINEBUFFERS Read both polarization buffers for a single B-line. offsetBase = (blineIndex - 1) * (2 * params.bytesPerBuffer); % two buffers (channels) per B-line -if ~isRawFormat +if ~is12bit offsetBase = offsetBase + headerBytes; % header is present once at the beginning end @@ -238,7 +239,7 @@ 'Failed to seek to offset %d in spectral file.', offsetBase); end -if ~isRawFormat +if ~is12bit data1 = fread(fid, params.numSamplesPerBuffer, 'uint16'); data2 = fread(fid, params.numSamplesPerBuffer, 'uint16'); else diff --git a/opticstream/matlab/README.md b/opticstream/matlab/README.md index 310bd40..4f58890 100644 --- a/opticstream/matlab/README.md +++ b/opticstream/matlab/README.md @@ -23,3 +23,9 @@ No coefficients are silently truncated, padded or recalibrated. The legacy wavelength calibration and channel-2 reversal remain in use; support for additional lengths does not validate that calibration for a different scanner. Output depth is floor(samples/2)-24. + +Orientation helpers (top level, unpackaged, from chaos_scientific_report_scripts): +- angle2tensor.m: orientation angle in degrees -> 4-component orientation tensor. +- tensor2angle.m: orientation tensor -> angle in radians. +psoct.registration.thruplane_registration calls both, unqualified, to warp +orientation maps; the toolbox does not ship them. diff --git a/opticstream/matlab/angle2tensor.m b/opticstream/matlab/angle2tensor.m new file mode 100644 index 0000000..4498237 --- /dev/null +++ b/opticstream/matlab/angle2tensor.m @@ -0,0 +1,19 @@ + +function moving_OC = angle2tensor (moving_o1) + +% convert angle in degrees to orientation tensor +if length(size(moving_o1)) == 2 + moving_OC=zeros([size(moving_o1) 4]); + moving_OC(:,:,1)=cos(moving_o1/180*pi).*cos(moving_o1/180*pi); + moving_OC(:,:,2)=cos(moving_o1/180*pi).*sin(moving_o1/180*pi); + moving_OC(:,:,3)=moving_OC(:,:,2); + moving_OC(:,:,4)=sin(moving_o1/180*pi).*sin(moving_o1/180*pi); +else + moving_OC=zeros([size(moving_o1) 4]); + for zz = 1:size (moving_o1,3) + moving_OC(:,:,zz,1)=cos(moving_o1(:,:,zz)/180*pi).*cos(moving_o1(:,:,zz)/180*pi); + moving_OC(:,:,zz,2)=cos(moving_o1(:,:,zz)/180*pi).*sin(moving_o1(:,:,zz)/180*pi); + moving_OC(:,:,zz,3)=moving_OC(:,:,zz,2); + moving_OC(:,:,zz,4)=sin(moving_o1(:,:,zz)/180*pi).*sin(moving_o1(:,:,zz)/180*pi); + end +end \ No newline at end of file diff --git a/opticstream/matlab/tensor2angle.m b/opticstream/matlab/tensor2angle.m new file mode 100644 index 0000000..a898358 --- /dev/null +++ b/opticstream/matlab/tensor2angle.m @@ -0,0 +1,26 @@ +function Data2 = tensor2angle(Ma) + +% convert orientation tensor to angle in radians +if length(size(Ma)) == 3 + + for st1 = 1:size(Ma,1) + for st2 = 1:size(Ma,2) + a = [Ma(st1,st2,1) Ma(st1,st2,3);Ma(st1,st2,2) Ma(st1,st2,4)]; + [V, D] = eig(a); + Data2(st1,st2) = atan(V(2,2)/V(1,2)); + end + end + +else + + for st = 1:size(Ma,1) + for tt = 1:size(Ma,2) + for zt = 1:size(Ma,3) + a = [Ma(st,tt,zt, 1) Ma(st,tt,zt,3);Ma(st,tt,zt,2) Ma(st,tt,zt,4)]; + [V, D] = eig(a); + Data2(st,tt,zt) = atan(V(2,2)/V(1,2)); + end + end + end + +end \ No newline at end of file diff --git a/opticstream/tasks/dandi_upload.py b/opticstream/tasks/dandi_upload.py index 6356bfd..78cea3b 100644 --- a/opticstream/tasks/dandi_upload.py +++ b/opticstream/tasks/dandi_upload.py @@ -97,12 +97,17 @@ def _upload_dandi_api( *, max_jobs: str, dandi_api_key: Secret | None = None, + realpath: bool = True, ) -> None: """Upload DANDI assets through the API, including generic NIfTI files. Recent DANDI CLIs filter unrecognized files before upload and no longer provide the ``--allow-any-path`` switch. The API equivalent is ``allow_any_path=True``. + + ``realpath=False`` keeps symlinks as given (e.g. enface outputs symlinked + into the dandiset), so the dandiset is found from the link location rather + than from the link target outside it. """ from dandi.upload import UploadExisting, UploadValidation, upload @@ -111,7 +116,10 @@ def _upload_dandi_api( except (ValueError, AttributeError): jobs = jobs_per_file = 5 - paths = [Path(os.path.realpath(path)) for path in file_list] + paths = [ + Path(os.path.realpath(path)) if realpath else Path(path).absolute() + for path in file_list + ] # DANDI needs the local dandiset metadata alongside assets in order to # resolve the target dataset. Walk upward from each asset and include the # nearest dandiset.yaml once when it exists (e.g. .../001769/dandiset.yaml). @@ -205,6 +213,7 @@ def upload_to_dandi_batch( file_list, max_jobs=max_jobs, dandi_api_key=dandi_api_key, + realpath=realpath, ) logger.info("DANDI batch upload completed") return diff --git a/opticstream/utils/polling_watcher.py b/opticstream/utils/polling_watcher.py index 01bf89c..0c03cfb 100644 --- a/opticstream/utils/polling_watcher.py +++ b/opticstream/utils/polling_watcher.py @@ -2,6 +2,7 @@ import logging import signal +import threading import time from collections.abc import Callable, Iterable from dataclasses import dataclass @@ -78,9 +79,22 @@ def __init__( self._stability: dict[K, StabilityRecord] = {} - def run(self) -> None: + def run(self, *companions: "PollingStableWatcher") -> None: + """Poll until Ctrl+C / SIGTERM. + + ``companions`` (e.g. enface previews alongside batch dispatch) are polled in + a background thread, so they react as soon as their files are stable instead + of waiting for this watcher's processing (e.g. a MATLAB batch). Their errors + are logged and never stop this watcher. + """ global _shutdown_requested _shutdown_requested = False + companion_thread = None + if companions: + companion_thread = threading.Thread( + target=_run_companions, args=(companions,), name="companion-watchers", + daemon=True, + ) signal.signal(signal.SIGINT, _signal_handler) signal.signal(signal.SIGTERM, _signal_handler) @@ -93,6 +107,8 @@ def run(self) -> None: ) logger.info("Press Ctrl+C to stop") + if companion_thread is not None: + companion_thread.start() iteration = 0 try: while not _shutdown_requested: @@ -107,6 +123,10 @@ def run(self) -> None: except KeyboardInterrupt: logger.info("Keyboard interrupt, shutting down") finally: + if companion_thread is not None: + _shutdown_requested = True + # Daemon thread: an in-progress companion job does not block exit. + companion_thread.join(timeout=1) logger.info("Watcher stopped after %s iterations", iteration) def _run_iteration(self) -> None: @@ -175,3 +195,19 @@ def _run_iteration(self) -> None: for key in disappeared_keys: logger.debug("Candidate disappeared from disk, dropping from tracking: key=%r", key) self._stability.pop(key, None) + + +def _run_companions(companions) -> None: + """Background loop for ``PollingStableWatcher.run`` companions.""" + while not _shutdown_requested: + for companion in companions: + if _shutdown_requested: + return + try: + companion._run_iteration() + except Exception as exc: + logger.exception("Companion watcher iteration failed: %s", exc) + interval = min(companion.poll_interval for companion in companions) + deadline = time.monotonic() + interval + while not _shutdown_requested and time.monotonic() < deadline: + time.sleep(min(0.5, interval)) diff --git a/tests/test_acquisition_previews.py b/tests/test_acquisition_previews.py index c55f538..5736438 100644 --- a/tests/test_acquisition_previews.py +++ b/tests/test_acquisition_previews.py @@ -45,6 +45,30 @@ def test_patterns(self): with self.assertRaises(ValueError): preview.expected_tiles(self.cfg, self.ident, self.root, "normal", 3) + def test_plain_image_matches_any_padding(self): + self.cfg.enface_preview.aip_pattern = "spectral_{image}_processed_aip.nii" + (self.root / "spectral_0003_processed_aip.nii").write_bytes(b"x") + (self.root / "spectral_4_processed_aip.nii").write_bytes(b"x") + (self.root / "spectral_0003_processed_aip.nii.bak").write_bytes(b"x") + files = preview.expected_tiles(self.cfg, self.ident, self.root, "normal", 2) + self.assertEqual(files["aip"][2].name, "spectral_0003_processed_aip.nii") + self.assertEqual(files["aip"][3].name, "spectral_4_processed_aip.nii") + # Missing tiles keep a rendered name and are reported absent. + files = preview.expected_tiles(self.cfg, self.ident, self.root, "normal", 1) + self.assertEqual(files["aip"][0].name, "spectral_1_processed_aip.nii") + self.assertFalse(files["aip"][0].exists()) + + def test_plain_image_with_other_placeholders_and_ambiguity(self): + self.cfg.enface_preview.aip_pattern = "s{slice}_m{mosaic:03d}_{acquisition}_{image}.nii" + (self.root / "s1_m001_normal_01.nii").write_bytes(b"x") + (self.root / "s1_m002_normal_02.nii").write_bytes(b"x") + files = preview.expected_tiles(self.cfg, self.ident, self.root, "normal", 1) + self.assertEqual(files["aip"][0].name, "s1_m001_normal_01.nii") + self.assertFalse(files["aip"][1].exists()) + (self.root / "s1_m001_normal_1.nii").write_bytes(b"x") + with self.assertRaises(ValueError): + preview.expected_tiles(self.cfg, self.ident, self.root, "normal", 1) + def test_geometry(self): self.assertEqual(preview.tile_position(2, 2, (10, 20), .2, "column-by-column"), (8, 0)) self.assertEqual(preview.tile_position(2, 2, (10, 20), .2, "snake-by-columns"), (8, 16)) @@ -93,7 +117,7 @@ def test_complete_batches_and_acquisition_only(self, slack): self.create_tiles(2) self.assertEqual(list(watcher.discover()), [1]) self.create_tiles(4) - self.assertEqual(list(watcher.discover()), [1, 2, None]) + self.assertEqual(list(watcher.discover()), [None, 1, 2]) (self.root / "ret_0004.nii").unlink() self.assertEqual(list(watcher.discover()), [1]) @@ -141,7 +165,7 @@ def stitch(cfg, files, modality, output, batch_id): output.with_suffix(".jpg").write_bytes(b"jpeg") with patch.object(preview, "stitch_preview_modality", side_effect=stitch) as stitched, \ patch.object(preview, "upload_multiple_files_to_slack") as upload: - upload.side_effect = lambda **kw: {p: Path(p).stem != "ret" for p in kw["filepaths"]} + upload.side_effect = lambda **kw: {p: not Path(p).stem.endswith("_ret") for p in kw["filepaths"]} with self.assertRaises(RuntimeError): preview.run_preview(self.cfg, self.ident, self.root, "normal", 1) upload.side_effect = lambda **kw: {p: True for p in kw["filepaths"]} @@ -149,17 +173,40 @@ def stitch(cfg, files, modality, output, batch_id): self.assertEqual(len(upload.call_args.kwargs["filepaths"]), 1) self.assertEqual(stitched.call_count, 4) + @patch.object(preview, "slack_notifications_enabled", return_value=False) + def test_outputs_in_slice_folder_named_by_mosaic(self, slack): + self.create_tiles() + def stitch(cfg, files, modality, output, batch_id): + output.parent.mkdir(parents=True, exist_ok=True) + output.write_bytes(b"nifti") + output.with_suffix(".jpg").write_bytes(b"jpeg") + folder = self.root / "out" / "slice-01" / "acquisition_previews" + with patch.object(preview, "stitch_preview_modality", side_effect=stitch): + result = preview.run_preview(self.cfg, self.ident, self.root, "normal") + preview.run_preview(self.cfg, self.ident, self.root, "normal", 2) + mosaic2 = OCTMosaicId(project_name="test", slice_id=1, mosaic_id=2) + self.cfg.acquisition.grid_size_x_tilted = 2 + preview.run_preview(self.cfg, mosaic2, self.root, "tilted") + self.assertEqual(result["aip"], str(folder / "mosaic_001_aip.jpg")) + names = {p.name for p in folder.iterdir()} + for prefix in ("mosaic_001", "mosaic_001_batch_0002", "mosaic_002"): + for m in preview.MODALITIES: + self.assertIn(f"{prefix}_{m}.nii", names) + self.assertIn(f"{prefix}_{m}.jpg", names) + self.assertIn(f"{prefix}_progress.json", names) + self.assertEqual(len(names), 3 * (2 * len(preview.MODALITIES) + 1)) + def test_changed_input_invalidates_progress(self): self.create_tiles() files = preview.expected_tiles(self.cfg, self.ident, self.root, "normal", 1) before = preview.fingerprint(self.cfg, files) - directory = preview.preview_dir(self.cfg, self.ident, 1) - preview.save_progress(directory, {"signature": before, "stitched": list(preview.MODALITIES), "uploaded": []}) + progress_file = preview.progress_path(self.cfg, self.ident, 1) + preview.save_progress(progress_file, {"signature": before, "stitched": list(preview.MODALITIES), "uploaded": []}) with (self.root / "aip_0001.nii").open("ab") as stream: stream.write(b"changed") after = preview.fingerprint(self.cfg, files) self.assertNotEqual(before, after) - self.assertEqual(preview.read_progress(directory, after)["stitched"], []) + self.assertEqual(preview.read_progress(progress_file, after)["stitched"], []) @patch("opticstream.cli.oct.watch_enface.slack_notifications_enabled", return_value=False) def test_polling_waits_for_stability(self, slack): diff --git a/tests/test_dandi_upload.py b/tests/test_dandi_upload.py index 777f40b..90cd5dc 100644 --- a/tests/test_dandi_upload.py +++ b/tests/test_dandi_upload.py @@ -71,3 +71,36 @@ def test_linc_uploads_are_refused() -> None: ): default = inspect.signature(flow.fn).parameters["dandi_instance"].default assert default == "dandi", flow.name + + +def test_dandi_api_upload_keeps_symlinks_inside_dandiset_when_not_realpath() -> None: + import tempfile + from pathlib import Path + from unittest.mock import patch + + from opticstream.tasks import dandi_upload + + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + dandiset = root / "dandiset" / "001769" + slice_dir = dandiset / "rawdata" / "sub-X" / "sample-slice01" + slice_dir.mkdir(parents=True) + (dandiset / "dandiset.yaml").write_text("identifier: '001769'\n") + target = root / "project_base" / "slice-01" / "stitched" / "mosaic_001_aip.nii.gz" + target.parent.mkdir(parents=True) + target.write_bytes(b"nifti") + link = slice_dir / "sub-X_sample-slice01_acq-normal_proc-aip_OCT.nii.gz" + link.symlink_to(target) + + for realpath, expected_asset in ((False, link), (True, target)): + with patch("dandi.upload.upload") as upload: + dandi_upload._upload_dandi_api( + [str(link)], + max_jobs="1:1", + dandi_api_key=Secret(value="token"), + realpath=realpath, + ) + paths = upload.call_args.kwargs["paths"] + assert paths[0] == expected_asset + # Only the symlink location has the dandiset.yaml above it. + assert ((dandiset / "dandiset.yaml") in paths) is (not realpath) diff --git a/tests/test_watch_previews.py b/tests/test_watch_previews.py new file mode 100644 index 0000000..3301b50 --- /dev/null +++ b/tests/test_watch_previews.py @@ -0,0 +1,146 @@ +"""`ops oct watch` runs enface previews; pipeline mosaic JPEGs skip Slack by default.""" +import threading +import unittest +from pathlib import Path +from tempfile import TemporaryDirectory +from types import SimpleNamespace +from unittest.mock import patch + +from opticstream.cli.oct.watch import build_watch_previews +from opticstream.config.enface_preview import EnfacePreviewConfig +from opticstream.config.psoct_scan_config import PSOCTAcquisitionParams +from opticstream.flows.psoct import mosaic_enface_qc_flow as qc +from opticstream.state.oct_project_state import OCTMosaicId +from opticstream.utils import polling_watcher +from opticstream.utils.polling_watcher import PollingStableWatcher + + +def scan_config(root, **preview): + return SimpleNamespace( + project_base_path=Path(root) / "out", + mosaics_per_slice=2, + enface_preview=EnfacePreviewConfig( + aip_pattern="{acquisition}_aip_{image}.nii", + mip_pattern="{acquisition}_mip_{image}.nii", + ori_pattern="{acquisition}_ori_{image}.nii", + ret_pattern="{acquisition}_ret_{image}.nii", + **preview, + ), + acquisition=PSOCTAcquisitionParams( + grid_size_y=2, grid_size_x_normal=2, grid_size_x_tilted=3, tile_overlap=0, + acquisition_mosaic_map={"normal0deg": 1, "tilted15deg": 2}, + ), + ) + + +class WatchPreviewTests(unittest.TestCase): + def setUp(self): + self.temp = TemporaryDirectory() + self.addCleanup(self.temp.cleanup) + self.root = Path(self.temp.name) + + def build(self, cfg, **kwargs): + args = dict(project_name="proj", folder_path=self.root, fixed_slice_id=1, + fixed_mosaic_slot=1, acquisition=None, slice_offset=0, + stability_seconds=0, poll_interval=1) + args.update(kwargs) + return build_watch_previews(cfg, **args) + + def worker_of(self, watcher): + return watcher.discover_candidates.__self__ + + def test_needs_slice_and_mosaic(self): + cfg = scan_config(self.root) + self.assertIsNone(self.build(cfg, fixed_slice_id=None)) + self.assertIsNone(self.build(cfg, fixed_mosaic_slot=None)) + + def test_disabled_in_block(self): + cfg = scan_config(self.root, batch_enabled=False, acquisition_enabled=False) + self.assertIsNone(self.build(cfg)) + + def test_acquisition_label_and_slice_offset(self): + cfg = scan_config(self.root) + worker = self.worker_of(self.build(cfg, fixed_slice_id=3, fixed_mosaic_slot=2, + slice_offset=2)) + self.assertEqual(worker.acquisition, "tilted15deg") + self.assertEqual(worker.ident, OCTMosaicId(project_name="proj", slice_id=5, mosaic_id=10)) + worker = self.worker_of(self.build(cfg, acquisition="normal0deg")) + self.assertEqual(worker.acquisition, "normal0deg") + self.assertEqual(worker.ident.mosaic_id, 1) + + +class CompanionTests(unittest.TestCase): + def watcher(self, discover, poll_interval=1): + return PollingStableWatcher(discover_candidates=discover, candidate_key=str, + fingerprint=str, process=lambda c: 0, + poll_interval=poll_interval, stability_seconds=0) + + def test_companions_run_while_main_watcher_is_busy(self): + companion_ran = threading.Event() + seen = {} + + def busy_main_discover(): + # Simulates a long MATLAB batch: returns only once the companion has + # run (or after a timeout if companions were serialized behind it). + seen["companion_during_main"] = companion_ran.wait(timeout=5) + polling_watcher._shutdown_requested = True + return [] + + def broken_companion_discover(): + companion_ran.set() + raise ValueError("bad preview pattern") + + with patch.object(polling_watcher.signal, "signal"): + self.watcher(busy_main_discover).run(self.watcher(broken_companion_discover)) + self.assertTrue(seen["companion_during_main"]) + + def test_acquisition_preview_is_checked_first(self): + from opticstream.cli.oct.watch_enface import EnfacePreviewWatcher + with TemporaryDirectory() as temp: + worker = EnfacePreviewWatcher(scan_config(temp), OCTMosaicId( + project_name="proj", slice_id=1, mosaic_id=1), temp, "normal0deg") + self.assertEqual(worker.candidates, [None, 1, 2]) + + +class StitchedEnfaceSlackTests(unittest.TestCase): + def run_qc(self, root, **kwargs): + outputs = {"aip": root / "mosaic_001_aip.nii.gz", "mask": root / "mosaic_001_mask.nii.gz"} + for path in outputs.values(): + path.write_bytes(b"x") + + def convert(*, mosaic_ident, modality, nifti_path): + jpeg = Path(str(nifti_path).replace(".nii.gz", ".jpg")) + jpeg.write_bytes(b"jpeg") + return jpeg + + ident = OCTMosaicId(project_name="proj", slice_id=1, mosaic_id=1) + with patch.object(qc.convert_enface_nifti_to_jpeg_task, "submit", + side_effect=lambda **kw: SimpleNamespace(result=lambda: convert(**kw))), \ + patch.object(qc, "get_psoct_scan_config", + return_value=SimpleNamespace(stitched_enface_slack_upload=False)), \ + patch.object(qc, "upload_multiple_files_to_slack", + side_effect=lambda **kw: {p: True for p in kw["filepaths"]}) as upload, \ + patch.object(qc, "send_slack_message") as message, \ + patch.object(qc, "get_run_logger"): + result = qc.mosaic_enface_qc_slack_upload_flow.fn( + mosaic_ident=ident, enface_outputs=outputs, **kwargs) + return result, upload, message + + def test_jpegs_written_but_not_posted_by_default(self): + with TemporaryDirectory() as temp: + root = Path(temp) + result, upload, message = self.run_qc(root) + self.assertTrue((root / "mosaic_001_aip.jpg").is_file()) + upload.assert_not_called() + message.assert_not_called() + self.assertEqual(result, {"aip": False}) + + def test_manual_override_posts(self): + with TemporaryDirectory() as temp: + result, upload, _ = self.run_qc(Path(temp), upload_to_slack=True) + upload.assert_called_once() + self.assertEqual(result, {"aip": True}) + + +if __name__ == "__main__": + unittest.main() From 46dc0cb502f1da0f3d41300ad48285de5ba9aebf Mon Sep 17 00:00:00 2001 From: Noah Markowitz Date: Thu, 24 Sep 2026 15:59:05 -0400 Subject: [PATCH 26/65] Follow continuous tile numbering across mosaics and slices in oct watch Scanners that number output continuously (spectral_0001.nii, ...) with no slice or acquisition in the name previously had every file pinned to one mosaic, so tiles past the first mosaic became phantom batches 23, 24, ... and the next mosaic never started. - Add AcquisitionSequence: maps an image number to slice, mosaic and tile. Each mosaic holds grid_size_x * grid_size_y tiles (normal/tilted grids), tiles are renumbered from 1, and after the slice's last mosaic the sequence moves to mosaic 1 of the next slice. Placement depends only on the image number, so restarting the watcher is safe. - watch: when filename_pattern has no {slice}/{acquisition}, use the sequence, with --slice/--mosaic (default 1/1) giving where image 1 starts. --mosaic is now the position within the slice (1 = normal, 2 = tilted) instead of a global mosaic id; --acquisition remains an optional alternative. - Never dispatch a batch number beyond a mosaic's grid_size_x. - Enface previews follow the same sequence (per-mosaic image offset and acquisition label from acquisition_mosaic_map), share one folder listing per poll, and drop finished mosaics once the next one has started. - Docs and tests updated. Co-Authored-By: Claude Opus 5.5 --- docs/acquisition_enface_previews.md | 11 +- docs/oct_input_naming.md | 36 +++-- opticstream/cli/oct/watch.py | 105 +++++++++++--- opticstream/cli/oct/watch_enface.py | 105 +++++++++++++- .../flows/psoct/acquisition_preview_flow.py | 81 +++++++---- opticstream/utils/acquisition_sequence.py | 87 ++++++++++++ opticstream/utils/oct_input_naming.py | 22 ++- tests/test_acquisition_sequence.py | 131 ++++++++++++++++++ tests/test_oct_input_naming.py | 10 +- 9 files changed, 521 insertions(+), 67 deletions(-) create mode 100644 opticstream/utils/acquisition_sequence.py create mode 100644 tests/test_acquisition_sequence.py diff --git a/docs/acquisition_enface_previews.md b/docs/acquisition_enface_previews.md index e3e500b..2023c43 100644 --- a/docs/acquisition_enface_previews.md +++ b/docs/acquisition_enface_previews.md @@ -46,13 +46,16 @@ modalities must be present for every expected tile before a candidate is ready. From Miniforge Prompt, with the project's venv activated and Prefect API configured: ```cmd -opticstream oct watch human-10um D:\data\acquisition --slice 1 --acquisition normal0deg +opticstream oct watch human-10um D:\data\acquisition --slice 1 --mosaic 1 ``` The main `oct watch` runs the previews in a background polling loop next to batch -dispatch whenever it knows the folder's slice and mosaic (`--slice` with `--acquisition`, or -`--mosaic`); the acquisition label is looked up from `acquisition_mosaic_map` when -only `--mosaic` is given. Previews do not wait for batch processing (e.g. MATLAB on +dispatch. With continuously numbered files (a `filename_pattern` without `{slice}` or +`{acquisition}`, see oct_input_naming.md) the previews follow the same sequence: +each mosaic's maps are the images in its range (mosaic 2 of a 22 x 16 grid starts at +image 353), named with its `acquisition_mosaic_map` label. Preview patterns then +need only `{image}`. Otherwise previews need the folder's slice and mosaic (`--slice` +with `--mosaic` or `--acquisition`). Previews do not wait for batch processing (e.g. MATLAB on the last batch): the full-acquisition preview starts as soon as the last batch's maps have been stable for `--stability-seconds` (default 15), ahead of any batch previews still pending. A preview error is logged and never stops batch watching. diff --git a/docs/oct_input_naming.md b/docs/oct_input_naming.md index 631d417..74b81c0 100644 --- a/docs/oct_input_naming.md +++ b/docs/oct_input_naming.md @@ -33,20 +33,36 @@ with overlapping slice/tile IDs in the same watched directory. ## Scanner names without slice or acquisition If the scanner only numbers its output (`spectral_0001.nii`, `spectral_0002.nii`, -...), set `"filename_pattern": "spectral_{image}.nii"` and tell the watcher which -slice and acquisition the folder holds: +...), set `"filename_pattern": "spectral_{image}.nii"`. The numbers are then one +continuous sequence across mosaics and slices, and `--slice`/`--mosaic` say where +image 1 starts (both default to 1): ```bash -ops oct watch myproject /path/to/scanner/output --slice 3 --acquisition normal0deg -ops oct watch myproject /path/to/scanner/output --mosaic 5 # same thing with 2 mosaics per slice +ops oct watch myproject /path/to/scanner/output --slice 1 --mosaic 1 ``` -`--acquisition` must be a key of `acquisition_mosaic_map`. `--mosaic` is the global -source mosaic id, `(slice - 1) * mosaics_per_slice + slot`; if you pass it together -with `--slice` or `--acquisition`, they must agree. Files the watcher cannot place -(no slice/acquisition in the name and none on the command line) are skipped with -a warning. Run one watcher per slice/acquisition folder, and restart it with new -values when the scanner moves on, because image numbers repeat between mosaics. +With 22 x 16 grids for both illuminations, that places: + +| Images | Slice | Mosaic | +|---|---|---| +| 1-352 | 1 | 1 (normal) | +| 353-704 | 1 | 2 (tilted) | +| 705-1056 | 2 | 1 (normal) | +| ... | ... | ... | + +Each mosaic holds `grid_size_x * grid_size_y` tiles, using `grid_size_x_normal` or +`grid_size_x_tilted` for its illumination, and its tiles are renumbered from 1. After +the slice's last mosaic the sequence continues with mosaic 1 of the next slice. +Placement depends only on the image number, so restarting the watcher is safe. + +`--mosaic` is the mosaic's position within its slice (1..`mosaics_per_slice`, e.g. +1 = normal, 2 = tilted), not a global mosaic id. `--acquisition` may name that +position by its `acquisition_mosaic_map` label instead; you never need both. To +start a folder partway through, e.g. with the tilted mosaic of slice 3, pass +`--slice 3 --mosaic 2`. `--slice-offset` still shifts the resulting slice numbers. + +A batch number beyond a mosaic's `grid_size_x` is never dispatched (it is logged +and ignored), whatever the naming. When the filename already contains `{slice}`/`{acquisition}`, or uses legacy `mosaic_###_image_####` names, these options act as a filter: only matching files diff --git a/opticstream/cli/oct/watch.py b/opticstream/cli/oct/watch.py index e694906..bd766d5 100644 --- a/opticstream/cli/oct/watch.py +++ b/opticstream/cli/oct/watch.py @@ -20,6 +20,7 @@ from opticstream.flows.psoct.utils import oct_batch_ident from opticstream.flows.psoct.utils import ( logical_mosaic_from_source_mosaic, + mosaic_context_from_ids, mosaic_position_in_slice, slice_from_mosaic, ) @@ -28,6 +29,8 @@ extract_processed_index_from_filename, extract_spectral_index_from_filename, ) +from opticstream.utils.acquisition_sequence import AcquisitionSequence +from opticstream.utils.oct_input_naming import pattern_names_mosaic from opticstream.utils.polling_watcher import PollingStableWatcher from opticstream.utils.refresh_disk import RefreshHook, resolve_refresh_hook @@ -138,8 +141,9 @@ def resolve_fixed_mosaic( """ Resolve watch --slice/--acquisition/--mosaic into (slice_id, mosaic_slot). - ``mosaic`` is a global source mosaic id; ``acquisition`` is a label from - ``acquisition.acquisition_mosaic_map``. Values given together must agree. + ``mosaic`` is the mosaic's position within its slice (1..mosaics_per_slice, + e.g. 1 = normal, 2 = tilted); ``acquisition`` is the same position named by + its ``acquisition.acquisition_mosaic_map`` label. Values given together must agree. """ mosaics_per_slice = scan_config.mosaics_per_slice slot = None @@ -154,13 +158,14 @@ def resolve_fixed_mosaic( if slice_id is not None and slice_id < 1: raise ValueError(f"--slice must be >= 1, got {slice_id}") if mosaic is not None: - mosaic_slice = slice_from_mosaic(mosaic, mosaics_per_slice) - mosaic_slot = mosaic_position_in_slice(mosaic, mosaics_per_slice) - if slice_id is not None and slice_id != mosaic_slice: - raise ValueError(f"--mosaic {mosaic} belongs to slice {mosaic_slice}, not --slice {slice_id}") - if slot is not None and slot != mosaic_slot: - raise ValueError(f"--mosaic {mosaic} is slot {mosaic_slot}, but --acquisition {acquisition} is slot {slot}") - slice_id, slot = mosaic_slice, mosaic_slot + if not 1 <= mosaic <= mosaics_per_slice: + raise ValueError( + f"--mosaic is the mosaic's position within the slice (1..{mosaics_per_slice}), " + f"got {mosaic}; use --slice for the slice" + ) + if slot is not None and slot != mosaic: + raise ValueError(f"--mosaic {mosaic} does not match --acquisition {acquisition} (mosaic {slot})") + slot = mosaic return slice_id, slot @@ -206,11 +211,15 @@ def __init__( prefer_spectral_for_complex_with_spectral: bool = True, fixed_slice_id: int | None = None, fixed_mosaic_slot: int | None = None, + sequence: AcquisitionSequence | None = None, ) -> None: self.project_name = project_name self.fixed_slice_id = fixed_slice_id self.fixed_mosaic_slot = fixed_mosaic_slot + # Continuous numbering: image numbers alone place tiles (see AcquisitionSequence). + self.sequence = sequence self._warned_unplaced: set[str] = set() + self._warned_extra_batches: set[tuple[int, int]] = set() self.folder_path = folder_path self.project_base_path = project_base_path self.mosaic_ranges = mosaic_ranges @@ -280,7 +289,18 @@ def _discover_two_mosaic_candidates(self) -> list[OCTBatchCandidate]: logical_batch = (image_index - 1) // self.batch_size + 1 batches[logical_batch].append(image_index) + max_batches = self._batches_in_mosaic(source_mosaic_id) for logical_batch, batch_tile_indices in sorted(batches.items()): + if logical_batch > max_batches: + if (source_mosaic_id, logical_batch) not in self._warned_extra_batches: + self._warned_extra_batches.add((source_mosaic_id, logical_batch)) + logger.warning( + "Ignoring source_mosaic=%s batch %s: the grid has only %s batches", + source_mosaic_id, + logical_batch, + max_batches, + ) + continue if len(batch_tile_indices) < self.batch_size: logger.warning( "Incomplete batch source_mosaic=%s logical_batch=%s (%s tiles, need %s)", @@ -332,6 +352,14 @@ def _discover_two_mosaic_candidates(self) -> list[OCTBatchCandidate]: return out + def _batches_in_mosaic(self, source_mosaic_id: int) -> int: + context = mosaic_context_from_ids( + slice_id=slice_from_mosaic(source_mosaic_id, self.scan_config.mosaics_per_slice), + mosaic_id=source_mosaic_id, + mosaics_per_slice=self.scan_config.mosaics_per_slice, + ) + return context.grid_size_x(self.scan_config) + def _matches_fixed_mosaic(self, source_mosaic_id: int) -> bool: """Apply --slice/--acquisition/--mosaic as a filter to legacy filenames.""" mosaics_per_slice = self.scan_config.mosaics_per_slice @@ -365,6 +393,7 @@ def _discover_two_mosaic_files(self) -> list[ParsedTileFile]: self.scan_config.mosaics_per_slice, slice_id=self.fixed_slice_id, mosaic_slot=self.fixed_mosaic_slot, + sequence=self.sequence, ) if custom is None: continue @@ -669,16 +698,31 @@ def build_watch_previews( slice_offset: int, stability_seconds: int, poll_interval: int, + sequence: AcquisitionSequence | None = None, ) -> PollingStableWatcher | None: """Enface preview watcher for the folder's slice/mosaic, or None when not applicable.""" preview = scan_config.enface_preview if not (preview.batch_enabled or preview.acquisition_enabled): logger.info("Enface previews disabled in the block (batch_enabled/acquisition_enabled)") return None + if sequence is not None: + # Imported here: watch_enface imports this module. + from opticstream.cli.oct.watch_enface import build_sequence_preview_watcher + + logger.info("Enface previews on; following the continuous numbering") + return build_sequence_preview_watcher( + scan_config, + sequence, + folder_path, + project_name, + slice_offset=slice_offset, + stability_seconds=stability_seconds, + poll_interval=poll_interval, + ) if fixed_slice_id is None or fixed_mosaic_slot is None: logger.info( "Enface previews need the folder's slice and mosaic; pass --slice with " - "--acquisition, or --mosaic, to enable them" + "--mosaic (or --acquisition) to enable them" ) return None if acquisition is None: @@ -739,6 +783,7 @@ def watch_oct( min_complex_file_size_bytes: int = 1, fixed_slice_id: int | None = None, fixed_mosaic_slot: int | None = None, + sequence: AcquisitionSequence | None = None, companions: tuple[PollingStableWatcher, ...] = (), ) -> None: service = OCTWatcherService( @@ -755,6 +800,7 @@ def watch_oct( min_complex_file_size_bytes=min_complex_file_size_bytes, fixed_slice_id=fixed_slice_id, fixed_mosaic_slot=fixed_mosaic_slot, + sequence=sequence, ) watcher = PollingStableWatcher[OCTBatchCandidate, tuple[int, int]]( @@ -802,12 +848,18 @@ def watch( - source mosaic id is derived from processed index and grid_size_x - slice_offset controls logical slice numbering via derived source mosaic ids - --slice, --acquisition and --mosaic say which slice/mosaic the folder holds. - They fill in values missing from acquisition.filename_pattern (e.g. a block - pattern of "spectral_{image}.nii" with --slice 3 --acquisition normal0deg), - and filter files whose names already contain them. --acquisition is a label - from acquisition.acquisition_mosaic_map; --mosaic is a global source mosaic - id and can replace --slice/--acquisition. + --slice and --mosaic (the mosaic's position within the slice: 1 = normal, + 2 = tilted) say where the folder starts. --acquisition may name the mosaic by + its acquisition.acquisition_mosaic_map label instead of --mosaic. + + When acquisition.filename_pattern has no {slice} or {acquisition} (e.g. + "spectral_{image}.nii"), image numbers are one continuous sequence: image 1 is + the start mosaic (default slice 1, mosaic 1), and after that mosaic's + grid_size_x * grid_size_y tiles the sequence continues into the next mosaic + and then the next slice, each sized by its own grid. + + When filenames contain {slice}/{acquisition}, the names place each tile and + --slice/--mosaic only filter which tiles this watcher handles. With the slice and mosaic known, a background loop also stitches enface previews from the acquisition's own AIP/MIP/orientation/retardance maps (block @@ -832,8 +884,23 @@ def watch( fixed_slice_id, fixed_mosaic_slot = resolve_fixed_mosaic( scan_config, slice_id=slice, acquisition=acquisition, mosaic=mosaic ) - if (fixed_slice_id, fixed_mosaic_slot) != (None, None): - if scan_config.mosaics_per_slice == 3 and not scan_config.acquisition.filename_pattern: + sequence = None + filename_pattern = scan_config.acquisition.filename_pattern + if filename_pattern and not pattern_names_mosaic(filename_pattern): + sequence = AcquisitionSequence( + scan_config, + start_slice=fixed_slice_id or 1, + start_mosaic=fixed_mosaic_slot or 1, + ) + logger.info( + "Continuous numbering: image 1 is slice %s mosaic %s; mosaic sizes %s tiles", + sequence.start_slice, + sequence.start_mosaic, + sequence.sizes, + ) + fixed_slice_id = fixed_mosaic_slot = None + elif (fixed_slice_id, fixed_mosaic_slot) != (None, None): + if scan_config.mosaics_per_slice == 3 and not filename_pattern: raise ValueError( "--slice/--acquisition/--mosaic need acquisition.filename_pattern " "when mosaics_per_slice == 3" @@ -856,6 +923,7 @@ def watch( slice_offset=slice_offset, stability_seconds=stability_seconds, poll_interval=poll_interval, + sequence=sequence, ) if preview_watcher is not None: companions = (preview_watcher,) @@ -876,5 +944,6 @@ def watch( min_complex_file_size_bytes=min_complex_file_size_bytes, fixed_slice_id=fixed_slice_id, fixed_mosaic_slot=fixed_mosaic_slot, + sequence=sequence, companions=companions, ) diff --git a/opticstream/cli/oct/watch_enface.py b/opticstream/cli/oct/watch_enface.py index 0bf6cb0..1a721c9 100644 --- a/opticstream/cli/oct/watch_enface.py +++ b/opticstream/cli/oct/watch_enface.py @@ -5,21 +5,29 @@ from opticstream.cli.oct.watch import _configure_logging from opticstream.config.psoct_scan_config import get_psoct_scan_config from opticstream.flows.psoct.acquisition_preview_flow import ( - MODALITIES, expected_tiles, fingerprint, preview_path, progress_path, read_progress, - preview_enface_batch, preview_enface_acquisition, + MODALITIES, expected_tiles, fingerprint, image_numbers_present, list_names, + preview_path, progress_path, read_progress, preview_enface_batch, + preview_enface_acquisition, +) +from opticstream.flows.psoct.utils import ( + logical_mosaic_from_source_mosaic, + mosaic_context_from_ident, ) -from opticstream.flows.psoct.utils import mosaic_context_from_ident from opticstream.state.oct_project_state import OCTMosaicId from opticstream.utils.polling_watcher import PollingStableWatcher from opticstream.utils.slack_settings import slack_notifications_enabled class EnfacePreviewWatcher: - def __init__(self, config, mosaic_ident, folder, acquisition): + def __init__(self, config, mosaic_ident, folder, acquisition, image_offset=0): self.config = config self.ident = mosaic_ident self.folder = Path(folder) self.acquisition = acquisition + # Continuous numbering: tile 1 of this mosaic is image first_image + image_offset. + self.image_offset = image_offset + # Optional folder listing shared across mosaics for one polling pass. + self.names = None context = mosaic_context_from_ident(mosaic_ident, config) # The full acquisition goes first: once its last batch is stable it is # stitched before any batch previews still waiting in the same pass. @@ -28,7 +36,8 @@ def __init__(self, config, mosaic_ident, folder, acquisition): self.candidates += list(range(1, context.grid_size_x(config) + 1)) def files(self, batch): - return expected_tiles(self.config, self.ident, self.folder, self.acquisition, batch) + return expected_tiles(self.config, self.ident, self.folder, self.acquisition, batch, + image_offset=self.image_offset, names=self.names) def fingerprint(self, batch): return fingerprint(self.config, self.files(batch)) @@ -54,7 +63,8 @@ def discover(self): def process(self, batch): kwargs = dict(config=self.config, mosaic_ident=self.ident, - input_dir=self.folder, acquisition=self.acquisition) + input_dir=self.folder, acquisition=self.acquisition, + image_offset=self.image_offset) if batch is None: preview_enface_acquisition(**kwargs) else: @@ -62,6 +72,89 @@ def process(self, batch): return 1 +class SequencePreviewWatcher: + """Previews for continuously numbered acquisitions (see AcquisitionSequence). + + Follows the sequence from its start mosaic up to the mosaic holding the newest + image. A mosaic with nothing left to do is dropped once a later mosaic has + started, so long runs do not keep rescanning finished mosaics. + """ + + def __init__(self, config, sequence, folder, project_name, *, slice_offset=0): + self.config = config + self.sequence = sequence + self.folder = Path(folder) + self.project_name = project_name + self.slice_offset = slice_offset + self.labels = {slot: label for label, slot in reversed( + list(config.acquisition.acquisition_mosaic_map.items()))} + self.workers = {} + self.finished = set() + + def _worker(self, position): + key = position.source_mosaic_id + if key not in self.workers: + slice_id, mosaic_id = logical_mosaic_from_source_mosaic( + key, mosaics_per_slice=self.sequence.mosaics_per_slice, + slice_offset=self.slice_offset) + ident = OCTMosaicId(project_name=self.project_name, slice_id=slice_id, + mosaic_id=mosaic_id) + offset = self.sequence.first_image(position.slice_id, position.mosaic_slot) - 1 + label = self.labels.get(position.mosaic_slot, str(position.mosaic_slot)) + self.workers[key] = EnfacePreviewWatcher(self.config, ident, self.folder, label, + image_offset=offset) + return self.workers[key] + + def _positions(self, last_image): + """Start of each mosaic from the sequence start through ``last_image``.""" + image = 1 + while image <= last_image: + position = self.sequence.locate(image) + yield position + image += self.sequence.sizes[position.mosaic_slot] - position.tile + 1 + + def discover(self): + names = list_names(self.folder) + pattern = self.config.enface_preview.aip_pattern + start = self.sequence.locate(1) + values = dict(slice=start.slice_id, mosaic=start.source_mosaic_id, acquisition="", + project=self.project_name) + present = image_numbers_present(pattern, values, names) + if not present: + return + last_image = max(present) - self.config.enface_preview.first_image + 1 + positions = list(self._positions(last_image)) + for number, position in enumerate(positions): + key = position.source_mosaic_id + if key in self.finished: + continue + worker = self._worker(position) + worker.names = names + pending = [(key, batch) for batch in worker.discover()] + yield from pending + if not pending and number < len(positions) - 1: + self.finished.add(key) + + def fingerprint(self, candidate): + key, batch = candidate + return self.workers[key].fingerprint(batch) + + def process(self, candidate): + key, batch = candidate + return self.workers[key].process(batch) + + +def build_sequence_preview_watcher(config, sequence, folder, project_name, *, + slice_offset=0, stability_seconds=15, poll_interval=5): + """Polling watcher for previews of a continuously numbered acquisition folder.""" + worker = SequencePreviewWatcher(config, sequence, Path(folder).resolve(), project_name, + slice_offset=slice_offset) + return PollingStableWatcher(discover_candidates=worker.discover, + candidate_key=lambda candidate: candidate, fingerprint=worker.fingerprint, + process=worker.process, stability_seconds=stability_seconds, + poll_interval=poll_interval, running_message="Watching acquisition enface maps") + + def build_preview_watcher(config, mosaic_ident, folder, acquisition, *, stability_seconds=15, poll_interval=5): """Polling watcher that stitches previews for one acquisition folder.""" diff --git a/opticstream/flows/psoct/acquisition_preview_flow.py b/opticstream/flows/psoct/acquisition_preview_flow.py index 2e35154..0c40268 100644 --- a/opticstream/flows/psoct/acquisition_preview_flow.py +++ b/opticstream/flows/psoct/acquisition_preview_flow.py @@ -27,12 +27,11 @@ MODALITIES = ("aip", "mip", "ori", "ret") -def _padded_image_matches(pattern, values, root): - """Map image number -> filename for a pattern whose {image} has no format spec. +def _image_regex(pattern, values, *, any_padding): + """Regex for a preview pattern with {image} as a digits group, or None. - Like filename_pattern, a bare {image} matches any zero padding (1, 01, 0001), - compared as a number. Returns None when {image} has an explicit format spec - (e.g. {image:04d}), which keeps exact rendering. + Returns None when ``any_padding`` is False and {image} has an explicit + format spec (e.g. {image:04d}), which keeps exact rendering. """ parts = [] for literal, field, spec, conversion in Formatter().parse(pattern): @@ -40,31 +39,59 @@ def _padded_image_matches(pattern, values, root): if field is None: continue if field == "image": - if spec or conversion: + if (spec or conversion) and not any_padding: return None parts.append(r"(?P[0-9]+)") else: parts.append(re.escape(format(values[field], spec))) - regex = re.compile("".join(parts)) - matches = {} + return re.compile("".join(parts)) + + +def list_names(root): + """File names in ``root`` (empty if it does not exist yet).""" try: - entries = list(os.scandir(root)) + return [entry.name for entry in os.scandir(root)] except FileNotFoundError: - return matches - for entry in entries: - found = regex.fullmatch(entry.name) + return [] + + +def image_numbers_present(pattern, values, names): + """Image numbers of files matching ``pattern``, whatever their padding.""" + regex = _image_regex(pattern, values, any_padding=True) + return {int(found["image"]) for name in names if (found := regex.fullmatch(name))} + + +def _padded_image_matches(pattern, values, names): + """Map image number -> filename for a pattern whose {image} has no format spec. + + Like filename_pattern, a bare {image} matches any zero padding (1, 01, 0001), + compared as a number. Returns None when {image} has an explicit format spec + (e.g. {image:04d}), which keeps exact rendering. + """ + regex = _image_regex(pattern, values, any_padding=False) + if regex is None: + return None + matches = {} + for name in names: + found = regex.fullmatch(name) if found is None: continue number = int(found["image"]) if number in matches: raise ValueError(f"Several files match image {number} of {pattern!r}: " - f"{matches[number]}, {entry.name}") - matches[number] = entry.name + f"{matches[number]}, {name}") + matches[number] = name return matches -def expected_tiles(config, mosaic_ident, input_dir, acquisition, batch_id=None): - """Return exact expected paths, never infer completeness from file counts.""" +def expected_tiles(config, mosaic_ident, input_dir, acquisition, batch_id=None, *, + image_offset=0, names=None): + """Return exact expected paths, never infer completeness from file counts. + + ``image_offset`` shifts filename image numbers for continuously numbered + acquisitions (tile 1 of this mosaic is image first_image + image_offset). + ``names`` is an optional pre-read listing of ``input_dir``. + """ context = mosaic_context_from_ident(mosaic_ident, config) rows = config.acquisition.grid_size_y columns = context.grid_size_x(config) @@ -74,13 +101,15 @@ def expected_tiles(config, mosaic_ident, input_dir, acquisition, batch_id=None): root = Path(input_dir).resolve() values = dict(slice=mosaic_ident.slice_id, mosaic=mosaic_ident.mosaic_id, acquisition=acquisition, project=mosaic_ident.project_name) + if names is None: + names = list_names(root) result = {} for modality in MODALITIES: pattern = getattr(config.enface_preview, f"{modality}_pattern") - existing = _padded_image_matches(pattern, values, root) + existing = _padded_image_matches(pattern, values, names) paths = {} for index in indices: - image = index + config.enface_preview.first_image + image = index + config.enface_preview.first_image + image_offset # Missing tiles keep the unpadded name so callers still see them as absent. name = (existing or {}).get(image) or pattern.format(image=image, **values) path = (root / name).resolve() @@ -231,11 +260,12 @@ def stitch_preview_modality(config: PSOCTScanConfigModel, files: dict[int, Path] return jpeg -def run_preview(config, mosaic_ident, input_dir, acquisition, batch_id=None): +def run_preview(config, mosaic_ident, input_dir, acquisition, batch_id=None, *, image_offset=0): enabled = config.enface_preview.acquisition_enabled if batch_id is None else config.enface_preview.batch_enabled if not enabled: return {} - files = expected_tiles(config, mosaic_ident, input_dir, acquisition, batch_id) + files = expected_tiles(config, mosaic_ident, input_dir, acquisition, batch_id, + image_offset=image_offset) signature = fingerprint(config, files) progress_file = progress_path(config, mosaic_ident, batch_id) progress = read_progress(progress_file, signature) @@ -268,14 +298,17 @@ def run_preview(config, mosaic_ident, input_dir, acquisition, batch_id=None): @flow(name="preview-enface-batch") def preview_enface_batch(config: PSOCTScanConfigModel, mosaic_ident: OCTMosaicId, - input_dir: Path, acquisition: str, batch_id: int): - return run_preview(config, mosaic_ident, input_dir, acquisition, batch_id) + input_dir: Path, acquisition: str, batch_id: int, + image_offset: int = 0): + return run_preview(config, mosaic_ident, input_dir, acquisition, batch_id, + image_offset=image_offset) @flow(name="preview-enface-acquisition") def preview_enface_acquisition(config: PSOCTScanConfigModel, mosaic_ident: OCTMosaicId, - input_dir: Path, acquisition: str): - return run_preview(config, mosaic_ident, input_dir, acquisition) + input_dir: Path, acquisition: str, image_offset: int = 0): + return run_preview(config, mosaic_ident, input_dir, acquisition, + image_offset=image_offset) def to_deployment(*, deployment_name="local", extra_tags=()): diff --git a/opticstream/utils/acquisition_sequence.py b/opticstream/utils/acquisition_sequence.py new file mode 100644 index 0000000..80a653c --- /dev/null +++ b/opticstream/utils/acquisition_sequence.py @@ -0,0 +1,87 @@ +"""Continuous tile numbering across mosaics and slices. + +When the scanner numbers files continuously (spectral_0001.nii, spectral_0002.nii, +...) without a slice or acquisition in the name, the image number alone says where +a tile belongs: the first ``grid_size_x * grid_size_y`` images fill the starting +mosaic, the next images fill the following mosaic (sized by its own grid), and +after the slice's last mosaic the sequence moves to mosaic 1 of the next slice. +""" +from __future__ import annotations + +from dataclasses import dataclass + +from opticstream.flows.psoct.utils import mosaic_context_from_ids + + +@dataclass(frozen=True) +class SequencePosition: + slice_id: int + mosaic_slot: int + tile: int + mosaics_per_slice: int + + @property + def source_mosaic_id(self) -> int: + return (self.slice_id - 1) * self.mosaics_per_slice + self.mosaic_slot + + +class AcquisitionSequence: + """Map continuous image numbers (1-based) to slice/mosaic/tile. + + ``start_slice``/``start_mosaic`` place image 1: e.g. start_slice=3, + start_mosaic=2 means the folder starts with the tilted mosaic of slice 3. + ``start_mosaic`` is the mosaic's position within its slice. + """ + + def __init__(self, scan_config, start_slice: int = 1, start_mosaic: int = 1) -> None: + self.mosaics_per_slice = scan_config.mosaics_per_slice + if start_slice < 1: + raise ValueError(f"start slice must be >= 1, got {start_slice}") + if not 1 <= start_mosaic <= self.mosaics_per_slice: + raise ValueError( + f"start mosaic must be between 1 and {self.mosaics_per_slice} " + f"(its position within the slice), got {start_mosaic}" + ) + self.start_slice = start_slice + self.start_mosaic = start_mosaic + rows = scan_config.acquisition.grid_size_y + self.sizes = {} + for slot in range(1, self.mosaics_per_slice + 1): + context = mosaic_context_from_ids( + slice_id=1, mosaic_id=slot, mosaics_per_slice=self.mosaics_per_slice + ) + self.sizes[slot] = context.grid_size_x(scan_config) * rows + self.slice_total = sum(self.sizes.values()) + + def locate(self, image: int) -> SequencePosition: + if image < 1: + raise ValueError(f"image number must be >= 1, got {image}") + remaining = image - 1 + for slot in range(self.start_mosaic, self.mosaics_per_slice + 1): + if remaining < self.sizes[slot]: + return self._position(self.start_slice, slot, remaining + 1) + remaining -= self.sizes[slot] + full_slices, remaining = divmod(remaining, self.slice_total) + slice_id = self.start_slice + 1 + full_slices + for slot in range(1, self.mosaics_per_slice + 1): + if remaining < self.sizes[slot]: + return self._position(slice_id, slot, remaining + 1) + remaining -= self.sizes[slot] + raise AssertionError("unreachable") + + def first_image(self, slice_id: int, mosaic_slot: int) -> int | None: + """Image number of tile 1 of a mosaic, or None if it precedes the start.""" + if (slice_id, mosaic_slot) < (self.start_slice, self.start_mosaic): + return None + if slice_id == self.start_slice: + before = sum(self.sizes[s] for s in range(self.start_mosaic, mosaic_slot)) + else: + before = ( + sum(self.sizes[s] for s in range(self.start_mosaic, self.mosaics_per_slice + 1)) + + (slice_id - self.start_slice - 1) * self.slice_total + + sum(self.sizes[s] for s in range(1, mosaic_slot)) + ) + return before + 1 + + def _position(self, slice_id: int, slot: int, tile: int) -> SequencePosition: + return SequencePosition(slice_id, slot, tile, self.mosaics_per_slice) diff --git a/opticstream/utils/oct_input_naming.py b/opticstream/utils/oct_input_naming.py index cf207de..e2ea5df 100644 --- a/opticstream/utils/oct_input_naming.py +++ b/opticstream/utils/oct_input_naming.py @@ -35,17 +35,37 @@ class InputTile: modality: str -def parse_input_name(name, acquisition, mosaics_per_slice, *, slice_id=None, mosaic_slot=None): +def pattern_names_mosaic(pattern): + """True when filenames carry their own {slice} or {acquisition}.""" + return bool({"slice", "acquisition"} & set(compile_pattern(pattern).groupindex)) + + +def parse_input_name(name, acquisition, mosaics_per_slice, *, slice_id=None, mosaic_slot=None, + sequence=None): """ Parse an input filename with the configured pattern. ``slice_id`` / ``mosaic_slot`` fill in values the filename lacks. When the filename also contains them, they act as filters: a mismatch returns None. + ``sequence`` (an AcquisitionSequence) places names with neither {slice} nor + {acquisition} by their continuous image number; image_index is then the tile + number within that mosaic. """ match = compile_pattern(acquisition.filename_pattern).fullmatch(name) if match is None: return None values = match.groupdict() + if sequence is not None and "slice" not in values and "acquisition" not in values: + image = int(values["image"]) + if image < 1: + raise ValueError("Filename image numbers must be positive.") + modality = acquisition.filename_modality_map.get( + values.get("modality", acquisition.filename_default_modality) + ) + if modality is None: + return None + position = sequence.locate(image) + return InputTile(position.source_mosaic_id, position.tile, modality) slot = mosaic_slot if "acquisition" in values: slot = acquisition.acquisition_mosaic_map.get(values["acquisition"]) diff --git a/tests/test_acquisition_sequence.py b/tests/test_acquisition_sequence.py new file mode 100644 index 0000000..c34145f --- /dev/null +++ b/tests/test_acquisition_sequence.py @@ -0,0 +1,131 @@ +"""Continuous image numbering across mosaics and slices (`ops oct watch`).""" +import unittest +from pathlib import Path +from tempfile import TemporaryDirectory +from types import SimpleNamespace +from unittest.mock import patch + +from opticstream.cli.oct.watch import OCTWatcherService, build_watch_previews +from opticstream.config.enface_preview import EnfacePreviewConfig +from opticstream.config.psoct_scan_config import PSOCTAcquisitionParams +from opticstream.utils.acquisition_sequence import AcquisitionSequence + +BIG = 100 * 1024 # the watcher ignores files smaller than 100 KB + + +def config(root="/tmp", normal=3, tilted=2, rows=2, pattern="spectral_{image}.nii"): + return SimpleNamespace( + project_base_path=Path(root) / "out", + mosaics_per_slice=2, + acquisition=PSOCTAcquisitionParams( + grid_size_x_normal=normal, grid_size_x_tilted=tilted, grid_size_y=rows, + tile_overlap=0, filename_pattern=pattern, + acquisition_mosaic_map={"normal0deg": 1, "tilted15deg": 2}), + enface_preview=EnfacePreviewConfig(**{ + f"{m}_pattern": f"img_{{image}}_{m}.nii" for m in ("aip", "mip", "ori", "ret")}), + ) + + +def write(folder, names): + for name in names: + with open(Path(folder) / name, "wb") as f: + f.truncate(BIG) + + +class SequenceTests(unittest.TestCase): + def test_sizes_follow_each_mosaic_grid(self): + # 22x16 normal and tilted, as in sub-TestBscans. + seq = AcquisitionSequence(config(normal=22, tilted=22, rows=16)) + self.assertEqual(seq.sizes, {1: 352, 2: 352}) + where = lambda i: (lambda p: (p.slice_id, p.mosaic_slot, p.tile))(seq.locate(i)) + self.assertEqual(where(1), (1, 1, 1)) + self.assertEqual(where(352), (1, 1, 352)) + self.assertEqual(where(353), (1, 2, 1)) + self.assertEqual(where(704), (1, 2, 352)) + self.assertEqual(where(705), (2, 1, 1)) + self.assertEqual(where(1409), (3, 1, 1)) + + def test_unequal_grids_and_start_position(self): + seq = AcquisitionSequence(config(normal=3, tilted=2, rows=2), start_slice=5, start_mosaic=2) + self.assertEqual(seq.sizes, {1: 6, 2: 4}) + pos = [seq.locate(i) for i in (1, 4, 5, 10, 11, 15)] + self.assertEqual([(p.slice_id, p.mosaic_slot, p.tile) for p in pos], + [(5, 2, 1), (5, 2, 4), (6, 1, 1), (6, 1, 6), (6, 2, 1), (7, 1, 1)]) + self.assertEqual(pos[0].source_mosaic_id, 10) + for slice_id, slot in [(5, 2), (6, 1), (6, 2), (7, 1)]: + self.assertEqual(seq.locate(seq.first_image(slice_id, slot)).tile, 1) + self.assertIsNone(seq.first_image(5, 1)) + + def test_invalid_start(self): + for kwargs in ({"start_slice": 0}, {"start_mosaic": 3}, {"start_mosaic": 0}): + with self.assertRaises(ValueError): + AcquisitionSequence(config(), **kwargs) + + +class WatcherSequenceTests(unittest.TestCase): + def watcher(self, folder, cfg, **kwargs): + return OCTWatcherService(project_name="p", folder_path=Path(folder), + project_base_path=folder, mosaic_ranges=[(1, 999)], slice_offset=0, + batch_size=cfg.acquisition.grid_size_y, scan_config=cfg, direct=True, + force_resend=False, **kwargs) + + def batches(self, watcher): + return sorted((c.source_mosaic_id, c.logical_batch, tuple(p.name for p in c.files)) + for c in watcher.discover_candidates()) + + def test_accumulating_files_move_to_next_mosaic_and_slice(self): + cfg = config(normal=3, tilted=2, rows=2) # mosaic 1: 6 tiles, mosaic 2: 4 tiles + with TemporaryDirectory() as folder: + write(folder, [f"spectral_{i:04d}.nii" for i in range(1, 13)]) + found = self.batches(self.watcher(folder, cfg, sequence=AcquisitionSequence(cfg))) + self.assertEqual([(m, b) for m, b, _ in found], + [(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (3, 1)]) + self.assertEqual(found[3][2], ("spectral_0007.nii", "spectral_0008.nii")) + self.assertEqual(found[5][2], ("spectral_0011.nii", "spectral_0012.nii")) + + def test_start_mosaic_two_of_slice_three(self): + cfg = config(normal=3, tilted=2, rows=2) + with TemporaryDirectory() as folder: + write(folder, [f"spectral_{i:04d}.nii" for i in range(1, 7)]) + seq = AcquisitionSequence(cfg, start_slice=3, start_mosaic=2) + found = self.batches(self.watcher(folder, cfg, sequence=seq)) + # slice 3 tilted = mosaic 6 (4 tiles), then slice 4 normal = mosaic 7. + self.assertEqual([(m, b) for m, b, _ in found], [(6, 1), (6, 2), (7, 1)]) + + def test_fixed_mosaic_ignores_batches_beyond_grid(self): + cfg = config(normal=3, tilted=2, rows=2) + with TemporaryDirectory() as folder: + write(folder, [f"spectral_{i:04d}.nii" for i in range(1, 11)]) + found = self.batches(self.watcher(folder, cfg, fixed_slice_id=1, fixed_mosaic_slot=1)) + self.assertEqual([(m, b) for m, b, _ in found], [(1, 1), (1, 2), (1, 3)]) + + +class SequencePreviewTests(unittest.TestCase): + @patch("opticstream.cli.oct.watch_enface.slack_notifications_enabled", return_value=False) + def test_previews_follow_sequence(self, slack): + with TemporaryDirectory() as folder: + cfg = config(folder, normal=3, tilted=2, rows=2) + seq = AcquisitionSequence(cfg) + watcher = build_watch_previews(cfg, project_name="p", folder_path=Path(folder), + fixed_slice_id=None, fixed_mosaic_slot=None, acquisition=None, slice_offset=0, + stability_seconds=0, poll_interval=1, sequence=seq) + worker = watcher.discover_candidates.__self__ + maps = lambda images: [f"img_{i}_{m}.nii" for i in images + for m in ("aip", "mip", "ori", "ret")] + write(folder, maps(range(1, 9))) # mosaic 1 complete + mosaic 2 batch 1 + found = list(worker.discover()) + self.assertEqual(found, [(1, None), (1, 1), (1, 2), (1, 3), (2, 1)]) + mosaic2 = worker.workers[2] + self.assertEqual((mosaic2.ident.mosaic_id, mosaic2.acquisition, mosaic2.image_offset), + (2, "tilted15deg", 6)) + self.assertEqual([p.name for p in mosaic2.files(1)["aip"].values()], + ["img_7_aip.nii", "img_8_aip.nii"]) + + # Mosaic 1 finished (previews exist); it is dropped once mosaic 2 has started. + with patch.object(worker.workers[1], "discover", return_value=iter(())): + self.assertEqual(list(worker.discover()), [(2, 1)]) + self.assertIn(1, worker.finished) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_oct_input_naming.py b/tests/test_oct_input_naming.py index 8a1b0e5..b81695d 100644 --- a/tests/test_oct_input_naming.py +++ b/tests/test_oct_input_naming.py @@ -87,10 +87,12 @@ def test_resolve_fixed_mosaic(self): cfg = SimpleNamespace(acquisition=self.acquisition(), mosaics_per_slice=2) self.assertEqual(resolve_fixed_mosaic(cfg), (None, None)) self.assertEqual(resolve_fixed_mosaic(cfg, slice_id=37, acquisition="tilted15deg"), (37, 2)) - self.assertEqual(resolve_fixed_mosaic(cfg, mosaic=74), (37, 2)) - self.assertEqual(resolve_fixed_mosaic(cfg, slice_id=37, acquisition="tilted15deg", mosaic=74), (37, 2)) - for kwargs in ({"acquisition": "unknown"}, {"slice_id": 36, "mosaic": 74}, - {"acquisition": "normal0deg", "mosaic": 74}, {"slice_id": 0}): + # --mosaic is the position within the slice (1 = normal, 2 = tilted). + self.assertEqual(resolve_fixed_mosaic(cfg, mosaic=2), (None, 2)) + self.assertEqual(resolve_fixed_mosaic(cfg, slice_id=37, mosaic=1), (37, 1)) + self.assertEqual(resolve_fixed_mosaic(cfg, slice_id=37, acquisition="tilted15deg", mosaic=2), (37, 2)) + for kwargs in ({"acquisition": "unknown"}, {"mosaic": 3}, {"mosaic": 0}, + {"acquisition": "normal0deg", "mosaic": 2}, {"slice_id": 0}): with self.assertRaises(ValueError): resolve_fixed_mosaic(cfg, **kwargs) From 981ebf1ef7625e5ee3d232b757bc6e4a55f27be6 Mon Sep 17 00:00:00 2001 From: Noah Markowitz Date: Thu, 24 Sep 2026 17:23:49 -0400 Subject: [PATCH 27/65] save complex files --- opticstream/config/pipeline_opts_builder.py | 13 +- opticstream/config/psoct_scan_config.py | 22 +++ .../flows/psoct/tile_batch_archive_flow.py | 68 ++++++++- .../flows/psoct/tile_batch_process_flow.py | 50 ++++++- .../+internal/applyComplexOutputPolicy.m | 15 ++ .../+file/spectral2processed_batch_indexed.m | 2 + .../+psoct/+spectral/spectral2complex.m | 6 +- opticstream/matlab/README.md | 8 ++ tests/test_complex_outputs.py | 133 ++++++++++++++++++ 9 files changed, 303 insertions(+), 14 deletions(-) create mode 100644 opticstream/matlab/+psoct/+file/+internal/applyComplexOutputPolicy.m create mode 100644 tests/test_complex_outputs.py diff --git a/opticstream/config/pipeline_opts_builder.py b/opticstream/config/pipeline_opts_builder.py index 2bac1f0..744ba8d 100644 --- a/opticstream/config/pipeline_opts_builder.py +++ b/opticstream/config/pipeline_opts_builder.py @@ -22,13 +22,17 @@ class VolumeOutputOpts(OutputOpts): - """Extra flag consumed by OpticStream's bundled indexed batch wrappers.""" + """Extra fields consumed by OpticStream's bundled indexed batch wrappers.""" save_volume_outputs: bool = True + # Directory for per-tile complex volumes (_complex.nii); None keeps them in memory. + complex_output_dir: Optional[str] = None def to_matlab_struct(self): result = super().to_matlab_struct() result["SaveVolumeOutputs"] = self.save_volume_outputs + if self.complex_output_dir: + result["ComplexOutputDir"] = self.complex_output_dir return result @@ -49,6 +53,7 @@ def build_pipeline_opts( illumination: str = "normal", output_opts: Optional[OutputOpts] = None, opts_mat_file: Optional[str] = None, + complex_output_dir: Optional[str] = None, ) -> PipelineOpts: """ Assemble MATLAB-facing PipelineOpts from project scan config. @@ -63,6 +68,8 @@ def build_pipeline_opts( Per-run output paths; omit to let MATLAB fill defaults. opts_mat_file Optional path to opts .mat cache. + complex_output_dir + Save each tile's complex volume here (spectral input only). """ acq = config.acquisition proc = config.processing @@ -124,8 +131,10 @@ def build_pipeline_opts( surface = SurfaceOpts(spec=proc.surface_spec) output_opts = VolumeOutputOpts( - **(output_opts.model_dump(exclude={"save_volume_outputs"}) if output_opts else {}), + **(output_opts.model_dump(exclude={"save_volume_outputs", "complex_output_dir"}) + if output_opts else {}), save_volume_outputs=proc.save_volume_outputs, + complex_output_dir=complex_output_dir, ) return PipelineOpts( diff --git a/opticstream/config/psoct_scan_config.py b/opticstream/config/psoct_scan_config.py index 29fec42..59d41d4 100644 --- a/opticstream/config/psoct_scan_config.py +++ b/opticstream/config/psoct_scan_config.py @@ -211,6 +211,17 @@ class PSOCTProcessingParams(BaseModel): "Existing files are not deleted; raw archives and enface workflows are unaffected."), ) + save_complex_outputs: bool = Field( + default=False, + description=("Spectral input only: save each tile's complex (Jones) volume that " + "spectral2complex computes, then archive it with complex_tile_name_format " + "next to the raw tiles and upload it to DANDI with them. About 2x the size " + "of the spectral tile (~1.1 GB per 350x350 tile with 1152 samples). " + "Needs archive_path. The archived/uploaded copies are gzipped (.nii.gz) and " + "kept; the uncompressed slice-NN/complex copy is deleted once its gzipped " + "archive copy is validated."), + ) + disp_comp_file: Path | None = Field( default=None, description=( @@ -379,6 +390,17 @@ class PSOCTScanConfigModel(BaseModel): "(supports placeholders: project_name, slice_id, tile_id, acq)" ), ) + complex_tile_name_format: str = Field( + default=( + "{project_name}_sample-slice{slice_id:02d}_chunk-{tile_id:04d}_acq-{acq}" + "_desc-complex_OCT.nii.gz" + ), + description=( + "Filename template for archived complex tiles when " + "processing.save_complex_outputs is true " + "(supports placeholders: project_name, slice_id, tile_id, acq)" + ), + ) mosaic_volume_format: str = Field( default=( "{project_name}_sample-slice{slice_id:02d}_acq-{acq}_proc-{modality}_OCT.ome.zarr" diff --git a/opticstream/flows/psoct/tile_batch_archive_flow.py b/opticstream/flows/psoct/tile_batch_archive_flow.py index af807c9..a7d2f66 100644 --- a/opticstream/flows/psoct/tile_batch_archive_flow.py +++ b/opticstream/flows/psoct/tile_batch_archive_flow.py @@ -10,6 +10,7 @@ from opticstream.events.psoct_event_emitters import emit_batch_psoct_event from opticstream.events.psoct_events import BATCH_ARCHIVED from opticstream.flows.psoct.tile_file_reference import TileFileReference +from opticstream.flows.psoct.utils import processed_output_prefix from opticstream.state.milestone_wrappers_psoct import oct_batch_processing_milestone from opticstream.state.oct_project_state import OCT_STATE_SERVICE, OCTBatchId from opticstream.tasks.archive_file import archive_file @@ -29,7 +30,13 @@ def archive_tile_batch( archive_path: Path, archive_tile_name_format: str, force_rerun: bool = False, -) -> None: + emit_event: bool = True, +) -> list[str]: + """Archive the batch's raw tiles; returns the archived paths. + + ``emit_event=False`` leaves BATCH_ARCHIVED to the caller, e.g. to add the + batch's complex tiles to the same upload. + """ logger = get_run_logger() archive_path.mkdir(parents=True, exist_ok=True) with OCT_STATE_SERVICE.open_batch(batch_ident=batch_id) as batch: @@ -66,11 +73,60 @@ def archive_tile_batch( f"{len(files_with_issue)} file(s): " + " | ".join(files_with_issue) ) - emit_batch_psoct_event( - BATCH_ARCHIVED, - batch_id, - extra_payload={"file_list": archived_file_paths}, - ) + if emit_event: + emit_batch_psoct_event( + BATCH_ARCHIVED, + batch_id, + extra_payload={"file_list": archived_file_paths}, + ) + return archived_file_paths + + +@task(on_failure=[slack_notification_hook]) +def archive_complex_tiles( + batch_id: OCTBatchId, + file_reference_list: list[TileFileReference], + *, + acquisition_label: str, + archive_path: Path, + complex_tile_name_format: str, + complex_dir: Path, +) -> list[str]: + """gzip each tile's saved complex volume into the archive; returns the archived paths. + + Each uncompressed ``_complex.nii`` is deleted once the whole batch's + gzipped archive copies are validated; the archive copies are never deleted. + """ + logger = get_run_logger() + local_paths = [] + futures = [] + for ref in file_reference_list: + local = complex_dir / f"{processed_output_prefix(batch_id.mosaic_id, ref.tile_number)}_complex.nii" + if not local.is_file(): + raise FileNotFoundError(f"Complex output missing for tile {ref.tile_number}: {local}") + output_name = complex_tile_name_format.format( + project_name=batch_id.project_name, + slice_id=batch_id.slice_id, + tile_id=ref.tile_number, + acq=acquisition_label, + ) + local_paths.append(local) + futures.append(archive_file.submit(local, archive_path / output_name)) + archived = [str(future.result()) for future in futures] + files_with_issue = check_archive_result(batch_id, archived) + if files_with_issue: + raise RuntimeError( + "Complex archive validation failed for " + f"{len(files_with_issue)} file(s): " + " | ".join(files_with_issue) + ) + for local in local_paths: + local.unlink() + logger.info("Archived %d complex tiles for %s", len(archived), batch_id) + return archived + + +def emit_batch_archived(batch_id: OCTBatchId, file_list: list[str]) -> None: + emit_batch_psoct_event(BATCH_ARCHIVED, batch_id, extra_payload={"file_list": file_list}) def check_archive_result( diff --git a/opticstream/flows/psoct/tile_batch_process_flow.py b/opticstream/flows/psoct/tile_batch_process_flow.py index 925df21..e4c4607 100644 --- a/opticstream/flows/psoct/tile_batch_process_flow.py +++ b/opticstream/flows/psoct/tile_batch_process_flow.py @@ -12,7 +12,11 @@ ) from opticstream.config.psoct_scan_config import PSOCTScanConfigModel, TileSavingType from opticstream.events import BATCH_PROCESSED, BATCH_READY, get_event_trigger -from opticstream.flows.psoct.tile_batch_archive_flow import archive_tile_batch +from opticstream.flows.psoct.tile_batch_archive_flow import ( + archive_complex_tiles, + archive_tile_batch, + emit_batch_archived, +) from opticstream.flows.psoct.tile_batch_processed_validation import ( validate_processed_batch_outputs, ) @@ -60,6 +64,23 @@ def _determine_processing_mode( raise ValueError(f"Invalid tile saving type: {tile_saving_type}") +def complex_output_dir_for_batch( + config: PSOCTScanConfigModel, mode: str, slice_id: int +) -> Path | None: + """``slice-NN/complex`` when this batch should save complex tiles, else None.""" + if not config.processing.save_complex_outputs: + return None + logger = get_run_logger() + if mode != "spectral": + logger.warning("save_complex_outputs applies to spectral input only; ignoring for %s", mode) + return None + if not config.archive_path: + logger.warning("save_complex_outputs needs archive_path; complex tiles will not be saved") + return None + _, _, _, complex_dir = get_slice_paths(str(config.project_base_path), slice_id) + return complex_dir + + @task(task_run_name="spectral-to-processed-{batch_id}") def spectral_to_processed_tile_batch( batch_id: OCTBatchId, @@ -67,6 +88,7 @@ def spectral_to_processed_tile_batch( *, config: PSOCTScanConfigModel, mosaic_context: MosaicContext, + complex_output_dir: Path | None = None, ) -> Path: logger = get_run_logger() @@ -76,6 +98,7 @@ def spectral_to_processed_tile_batch( pipeline_opts = build_pipeline_opts( config=config, illumination=mosaic_context.config_illumination, + complex_output_dir=str(complex_output_dir) if complex_output_dir else None, ) cmd = build_spectral2processed_batch_indexed_command( [str(ref.spectral_file_path) for ref in file_reference_list], @@ -240,6 +263,13 @@ def process_tile_batch( file_reference_list = list(file_reference_list.values()) logger.info("File reference list: %s", file_reference_list) + mode = _determine_processing_mode( + tile_saving_type=config.acquisition.tile_saving_type, + ) + # Complex tiles join the raw tiles in one BATCH_ARCHIVED event (one DANDI upload). + complex_dir = complex_output_dir_for_batch(config, mode, batch_id.slice_id) + save_complex = complex_dir is not None + archive_future = None if config.archive_path: archive_future = archive_tile_batch.submit( @@ -249,11 +279,9 @@ def process_tile_batch( archive_path=config.archive_path, archive_tile_name_format=config.archive_tile_name_format, force_rerun=force_rerun, + emit_event=not save_complex, ) - mode = _determine_processing_mode( - tile_saving_type=config.acquisition.tile_saving_type, - ) processed_path: Path | None = None if mode == "spectral": processed_path = spectral_to_processed_tile_batch( @@ -261,6 +289,7 @@ def process_tile_batch( file_reference_list=file_reference_list, config=config, mosaic_context=mosaic_context, + complex_output_dir=complex_dir, ) elif mode == "complex": processed_path = complex_to_processed_tile_batch( @@ -278,7 +307,18 @@ def process_tile_batch( ) - if archive_future: + if archive_future and save_complex: + raw_archived = archive_future.result() + complex_archived = archive_complex_tiles( + batch_id=batch_id, + file_reference_list=file_reference_list, + acquisition_label=mosaic_context.acquisition_label, + archive_path=config.archive_path, + complex_tile_name_format=config.complex_tile_name_format, + complex_dir=complex_dir, + ) + emit_batch_archived(batch_id, raw_archived + complex_archived) + elif archive_future: archive_future.wait() with OCT_STATE_SERVICE.open_batch(batch_ident=batch_id) as batch_state: batch_state.mark_completed() diff --git a/opticstream/matlab/+psoct/+file/+internal/applyComplexOutputPolicy.m b/opticstream/matlab/+psoct/+file/+internal/applyComplexOutputPolicy.m new file mode 100644 index 0000000..a0a5a30 --- /dev/null +++ b/opticstream/matlab/+psoct/+file/+internal/applyComplexOutputPolicy.m @@ -0,0 +1,15 @@ +function outputOpts = applyComplexOutputPolicy(outputOpts, prefix) +% Consume OpticStream's ComplexOutputDir: save the complex (Jones) volume that +% spectral2complex computes anyway as /_complex.nii. +% An empty or missing directory leaves the complex data in memory only. +if isfield(outputOpts, 'ComplexOutputDir') + complexDir = string(outputOpts.ComplexOutputDir); + outputOpts = rmfield(outputOpts, 'ComplexOutputDir'); + if strlength(complexDir) > 0 + if ~isfolder(complexDir) + mkdir(complexDir); + end + outputOpts.Paths.complex = fullfile(complexDir, prefix + "_complex.nii"); + end +end +end diff --git a/opticstream/matlab/+psoct/+file/spectral2processed_batch_indexed.m b/opticstream/matlab/+psoct/+file/spectral2processed_batch_indexed.m index 61efc66..8653923 100644 --- a/opticstream/matlab/+psoct/+file/spectral2processed_batch_indexed.m +++ b/opticstream/matlab/+psoct/+file/spectral2processed_batch_indexed.m @@ -73,6 +73,7 @@ function spectral2processed_batch_indexed(filenames, outputDir, mosaicId, tileIn fprintf("spectral2processed_batch_indexed: %s -> %s_*\n", inFile, prefix); perOutputOpts = psoct.file.internal.applyVolumeOutputPolicy(perOutputOpts); + perOutputOpts = psoct.file.internal.applyComplexOutputPolicy(perOutputOpts, prefix); psoct.file.spectral2processed( ... inFile, spectralOpts, surfaceOpts, enfaceOpts, ... acquisitionOpts, perOutputOpts, volumeOpts, optsMatFile); @@ -107,6 +108,7 @@ function spectral2processed_batch_indexed(filenames, outputDir, mosaicId, tileIn fprintf("spectral2processed_batch_indexed: %s -> %s_*\n", inFile, prefix); perOutputOpts = psoct.file.internal.applyVolumeOutputPolicy(perOutputOpts); + perOutputOpts = psoct.file.internal.applyComplexOutputPolicy(perOutputOpts, prefix); psoct.file.spectral2processed( ... inFile, spectralOpts, surfaceOpts, enfaceOpts, ... acquisitionOpts, perOutputOpts, volumeOpts, optsMatFile); diff --git a/opticstream/matlab/+psoct/+spectral/spectral2complex.m b/opticstream/matlab/+psoct/+spectral/spectral2complex.m index 92502b1..1779388 100644 --- a/opticstream/matlab/+psoct/+spectral/spectral2complex.m +++ b/opticstream/matlab/+psoct/+spectral/spectral2complex.m @@ -212,9 +212,13 @@ fprintf('Saving output to: %s\n', outputPath); Jstack_all = single(Jstack_all); + % The template is usually the spectral input's header, whose size differs + % from the complex stack; resize it as the toolbox does for volume outputs + % (default 10x10x2.5 um voxels). + infoComplex = psoct.internal.nifti.shrinkNiftiHeader(Jstack_all, outputOpts.InfoLike); futures = {}; futures = psoct.internal.nifti.appendWriteFuture(futures, ... - psoct.internal.nifti.writeNiftiIfPath(outputPath, Jstack_all, outputOpts.InfoLike)); + psoct.internal.nifti.writeNiftiIfPath(outputPath, Jstack_all, infoComplex)); psoct.internal.nifti.waitWriteFutures(futures); end diff --git a/opticstream/matlab/README.md b/opticstream/matlab/README.md index 4f58890..58713e7 100644 --- a/opticstream/matlab/README.md +++ b/opticstream/matlab/README.md @@ -29,3 +29,11 @@ Orientation helpers (top level, unpackaged, from chaos_scientific_report_scripts - tensor2angle.m: orientation tensor -> angle in radians. psoct.registration.thruplane_registration calls both, unqualified, to warp orientation maps; the toolbox does not ship them. + +Complex outputs (processing.save_complex_outputs): +- The indexed spectral batch wrapper reads OutputOpts.ComplexOutputDir + (+psoct/+file/+internal/applyComplexOutputPolicy.m) and sets Paths.complex to + /_complex.nii, so spectral2complex saves the volume it already computes. +- The file is single, [4*A-lines, B-lines, depth]: real(J1), imag(J1), real(J2), + imag(J2) stacked along the first axis. Its header is resized from the spectral + input's (default 10x10x2.5 um voxels) because that header's size differs. diff --git a/tests/test_complex_outputs.py b/tests/test_complex_outputs.py new file mode 100644 index 0000000..bb1da0b --- /dev/null +++ b/tests/test_complex_outputs.py @@ -0,0 +1,133 @@ +"""Optional saving, archiving and upload of complex tiles from spectral input.""" +import gzip +import unittest +from pathlib import Path +from tempfile import TemporaryDirectory +from types import SimpleNamespace +from unittest.mock import Mock, patch + +from niizarr import ZarrConfig + +from opticstream.config.pipeline_opts_builder import build_pipeline_opts +from opticstream.config.psoct_scan_config import ( + PSOCTAcquisitionParams, + PSOCTProcessingParams, + PSOCTScanConfigModel, +) +from opticstream.flows.psoct import tile_batch_archive_flow as archive_flow +from opticstream.flows.psoct import tile_batch_process_flow as process_flow +from opticstream.state.oct_project_state import OCTBatchId + + +def scan_config(root="/tmp", archive=True, **processing): + return PSOCTScanConfigModel( + project_name="sub-T", + project_base_path=Path(root) / "base", + archive_path=Path(root) / "archive" if archive else None, + acquisition=PSOCTAcquisitionParams(grid_size_x_normal=2, grid_size_x_tilted=2, + grid_size_y=2), + processing=PSOCTProcessingParams(**processing), + zarr_config=ZarrConfig(), + ) + + +class ConfigTests(unittest.TestCase): + def test_defaults(self): + cfg = scan_config() + self.assertFalse(cfg.processing.save_complex_outputs) + self.assertEqual( + cfg.complex_tile_name_format, + "{project_name}_sample-slice{slice_id:02d}_chunk-{tile_id:04d}_acq-{acq}" + "_desc-complex_OCT.nii.gz", + ) + + def test_matlab_opts_carry_complex_dir_only_when_set(self): + cfg = scan_config() + with_dir = build_pipeline_opts(cfg, complex_output_dir="/data/slice-01/complex") + self.assertEqual(with_dir.output.to_matlab_struct()["ComplexOutputDir"], + "/data/slice-01/complex") + self.assertNotIn("ComplexOutputDir", build_pipeline_opts(cfg).output.to_matlab_struct()) + + +class BatchDecisionTests(unittest.TestCase): + def decide(self, cfg, mode="spectral"): + with patch.object(process_flow, "get_run_logger", return_value=Mock()): + return process_flow.complex_output_dir_for_batch(cfg, mode, 3) + + def test_enabled_spectral_uses_slice_complex_folder(self): + with TemporaryDirectory() as root: + cfg = scan_config(root, save_complex_outputs=True) + self.assertEqual(self.decide(cfg), Path(root) / "base" / "slice-03" / "complex") + + def test_off_by_default_and_needs_spectral_input_and_archive(self): + with TemporaryDirectory() as root: + self.assertIsNone(self.decide(scan_config(root))) + self.assertIsNone(self.decide(scan_config(root, save_complex_outputs=True), "complex")) + self.assertIsNone(self.decide(scan_config(root, archive=False, save_complex_outputs=True))) + + +class ArchiveComplexTests(unittest.TestCase): + def test_archives_gzipped_with_name_format_and_removes_uncompressed_copies(self): + with TemporaryDirectory() as root: + root = Path(root) + complex_dir = root / "complex" + complex_dir.mkdir() + refs = [SimpleNamespace(tile_number=n) for n in (5, 6)] + for n in (5, 6): + (complex_dir / f"mosaic_003_image_{n:04d}_complex.nii").write_bytes(b"jones%d" % n) + batch = OCTBatchId(project_name="sub-T", slice_id=2, mosaic_id=3, batch_id=3) + + def submit(local, out): + return SimpleNamespace(result=lambda: archive_flow.archive_file.fn(local, out)) + + with patch.object(archive_flow, "get_run_logger", return_value=Mock()), \ + patch("opticstream.tasks.archive_file.get_run_logger", return_value=Mock()), \ + patch.object(archive_flow.archive_file, "submit", side_effect=submit), \ + patch.object(archive_flow, "check_archive_result", return_value=[]): + archived = archive_flow.archive_complex_tiles.fn( + batch, refs, acquisition_label="normal0deg", archive_path=root / "archive", + complex_tile_name_format="{project_name}_sample-slice{slice_id:02d}_chunk-" + "{tile_id:04d}_acq-{acq}_desc-complex_OCT.nii.gz", + complex_dir=complex_dir) + + self.assertEqual([Path(p).name for p in archived], [ + "sub-T_sample-slice02_chunk-0005_acq-normal0deg_desc-complex_OCT.nii.gz", + "sub-T_sample-slice02_chunk-0006_acq-normal0deg_desc-complex_OCT.nii.gz", + ]) + with gzip.open(archived[0]) as f: + self.assertEqual(f.read(), b"jones5") + self.assertEqual(list(complex_dir.iterdir()), []) + self.assertTrue(all(Path(p).is_file() for p in archived)) + + def test_failed_validation_keeps_uncompressed_copies(self): + with TemporaryDirectory() as root: + root = Path(root) + local = root / "mosaic_001_image_0001_complex.nii" + local.write_bytes(b"jones") + batch = OCTBatchId(project_name="sub-T", slice_id=1, mosaic_id=1, batch_id=1) + with patch.object(archive_flow, "get_run_logger", return_value=Mock()), \ + patch.object(archive_flow.archive_file, "submit", + return_value=SimpleNamespace(result=lambda: root / "a.nii.gz")), \ + patch.object(archive_flow, "check_archive_result", return_value=["a.nii.gz (small)"]): + with self.assertRaises(RuntimeError): + archive_flow.archive_complex_tiles.fn( + batch, [SimpleNamespace(tile_number=1)], acquisition_label="normal0deg", + archive_path=root, complex_tile_name_format="{tile_id}.nii.gz", + complex_dir=root) + self.assertTrue(local.is_file()) + + def test_missing_complex_output_fails_before_archiving(self): + with TemporaryDirectory() as root: + batch = OCTBatchId(project_name="sub-T", slice_id=1, mosaic_id=1, batch_id=1) + with patch.object(archive_flow, "get_run_logger", return_value=Mock()), \ + patch.object(archive_flow.archive_file, "submit") as submit: + with self.assertRaises(FileNotFoundError): + archive_flow.archive_complex_tiles.fn( + batch, [SimpleNamespace(tile_number=1)], acquisition_label="normal0deg", + archive_path=Path(root), complex_tile_name_format="{tile_id}.nii.gz", + complex_dir=Path(root)) + submit.assert_not_called() + + +if __name__ == "__main__": + unittest.main() From ae4ba27eb544520cac4e090da5300b294af24095 Mon Sep 17 00:00:00 2001 From: Noah Markowitz Date: Fri, 25 Sep 2026 15:13:30 -0400 Subject: [PATCH 28/65] enface acquisition previews working --- .../flows/psoct/acquisition_preview_flow.py | 132 ++++++++++-------- tests/test_acquisition_previews.py | 38 +++-- 2 files changed, 98 insertions(+), 72 deletions(-) diff --git a/opticstream/flows/psoct/acquisition_preview_flow.py b/opticstream/flows/psoct/acquisition_preview_flow.py index 0c40268..5ea86ea 100644 --- a/opticstream/flows/psoct/acquisition_preview_flow.py +++ b/opticstream/flows/psoct/acquisition_preview_flow.py @@ -179,41 +179,61 @@ def save_progress(path, progress): time.sleep(0.1 * (attempt + 1)) -def tile_position(index, rows, shape, overlap, traversal, batch_id=None, *, order=None, columns=None): - """Map acquisition sequence to linc-convert grid coordinates. - - rows is the historical tiles-per-batch setting, not the physical Y extent - in row-first mode. columns is the number of batches for the full acquisition. +def tile_shape(path): + """In-plane (x, y) size of an enface tile, from the NIfTI header when possible.""" + # Treat only the final extension as a format indicator; acquisition labels + # may contain dots (e.g. tilted12.5deg). + if path.name.lower().endswith((".nii", ".nii.gz")): + shape = nib.load(path).shape + else: + from opticstream.data_processing.qc.convert_image import load_data + shape = np.shape(load_data(input_path=path, mat_variable=None)) + if len(shape) < 2 or any(size != 1 for size in shape[2:]): + raise ValueError(f"Expected 2D enface map (or singleton trailing axes): {path}, {shape}") + return tuple(shape[:2]) + + +def tile_config(config, files, shape, overlap, out): + """Write a linc-convert tile YAML for ``files`` (acquisition index -> path). + + The full grid comes from linc-convert's generate_tile_config; entries are then + limited to ``files`` (a single batch keeps the direction its strip has in the + full snake), pointed at the resolved paths, and shifted to start at (0, 0). """ - row_based = traversal in {"row-by-row", "snake-by-rows"} - order = order or ("right-down" if row_based else "down-right") - from opticstream.config.enface_preview import PreviewGridConfig - PreviewGridConfig(grid_type=traversal, order=order) - strip, fast = divmod(index, rows) - slow = strip - count = columns if columns is not None else strip + 1 - initial, subsequent = order.split("-") - reverse_fast = initial in {"left", "up"} - if traversal.startswith("snake-") and strip % 2: - reverse_fast = not reverse_fast - if reverse_fast: - fast = rows - 1 - fast - if subsequent in {"left", "up"}: - slow = count - 1 - slow - if batch_id is not None: - slow = 0 - column, row = (fast, slow) if row_based else (slow, fast) - return round(column * shape[0] * (1 - overlap)), round(row * shape[1] * (1 - overlap)) + from linc_convert.modalities.psoct.generate_tile_config import generate_tile_config + + grid = config.enface_preview.grid_config + per_strip = config.acquisition.grid_size_y + strips = max(files) // per_strip + 1 + row_based = grid.grid_type in {"row-by-row", "snake-by-rows"} + columns, rows = (per_strip, strips) if row_based else (strips, per_strip) + generate_tile_config(columns=columns, rows=rows, tile_size_x=shape[0], tile_size_y=shape[1], + base_dir="", naming_format="{tile_number}", grid_type=grid.grid_type, + order=grid.order, overlap_percentage=overlap, out=str(out)) + spec = yaml.safe_load(Path(out).read_text()) + tiles = [tile for tile in spec["tiles"] if tile["tile_number"] - 1 in files] + x0 = min(tile["x"] for tile in tiles) + y0 = min(tile["y"] for tile in tiles) + for tile in tiles: + index = tile["tile_number"] - 1 + # Round like pixel offsets; mosaic2d truncates, so 20.999... would become 20. + tile.update(filepath=str(files[index]), tile_number=index + 1, + x=round(tile["x"] - x0), y=round(tile["y"] - y0)) + spec["tiles"] = tiles + spec["metadata"].update(base_dir="", scan_resolution=list(config.acquisition.scan_resolution_3d[:2])) + Path(out).write_text(yaml.safe_dump(spec)) + return out @task def stitch_preview_modality(config: PSOCTScanConfigModel, files: dict[int, Path], modality: str, output: Path, batch_id: int | None = None) -> Path: - """Normalize singleton NIfTI maps to 2D then call linc-convert mosaic2d. + """Stitch acquisition tiles in place with linc-convert generate_tile_config + mosaic2d. - Temporary files leave acquisition originals untouched and prevent linc-convert - from silently skipping unreadable inputs. TIFF and other formats accepted by - the existing QC loader can also be used through configurable suffixes. + Writes ``output`` (NIfTI), a JPEG next to it, and a ``*_grid.jpg`` tile diagram. + Tiles are copied to a scratch directory only when they need converting: + radian orientation maps (linc-convert expects degrees) and plain 2D maps + (mosaic2d writes 3D voxel sizes, so tiles keep a singleton third axis). """ from opticstream.data_processing.qc.convert_image import load_data from linc_convert.modalities.psoct.mosaic import mosaic2d @@ -222,41 +242,39 @@ def stitch_preview_modality(config: PSOCTScanConfigModel, files: dict[int, Path] if not 0 <= overlap < 1: raise ValueError("Preview tile_overlap must be a percentage in [0, 100)") output.parent.mkdir(parents=True, exist_ok=True) - shape = None + shapes = {index: tile_shape(path) for index, path in files.items()} + shape = next(iter(shapes.values())) + for index, other in shapes.items(): + if other != shape: + raise ValueError(f"Tile dimensions differ: {files[index]}, {other} != {shape}") + to_degrees = modality == "ori" and config.enface_preview.orientation_units == "radians" + jpeg = output.with_suffix(".jpg") with tempfile.TemporaryDirectory(prefix="enface-preview-", dir=output.parent) as scratch: - entries = [] + sources = dict(files) for index, path in files.items(): - # Treat only the final extension as a format indicator; acquisition - # labels may contain dots (e.g. tilted12.5deg). - if path.name.lower().endswith((".nii", ".nii.gz")): - array = np.asarray(nib.load(path).dataobj) - else: - array = np.asarray(load_data(input_path=path, mat_variable=None)) - if array.ndim > 2 and all(size == 1 for size in array.shape[2:]): - array = array.reshape(array.shape[:2]) - if array.ndim != 2: - raise ValueError(f"Expected 2D enface map (or singleton trailing axes): {path}, {array.shape}") - if shape is not None and array.shape != shape: - raise ValueError(f"Tile dimensions differ: {path}, {array.shape} != {shape}") - shape = array.shape - array = array.astype(np.float32) - if modality == "ori" and config.enface_preview.orientation_units == "radians": + is_nifti = path.name.lower().endswith((".nii", ".nii.gz")) + if not to_degrees and is_nifti and len(nib.load(path).shape) > 2: + continue + array = (np.asarray(nib.load(path).dataobj) if is_nifti + else np.asarray(load_data(input_path=path, mat_variable=None))) + array = array.reshape(*shape, 1).astype(np.float32) + if to_degrees: array = np.rad2deg(array) - normalized = Path(scratch) / f"tile-{index}.nii" - nib.save(nib.Nifti1Image(array, np.eye(4)), normalized) - grid = config.enface_preview.grid_config - x, y = tile_position(index, config.acquisition.grid_size_y, shape, overlap, - grid.grid_type, batch_id, order=grid.order, - columns=max(files) // config.acquisition.grid_size_y + 1) - entries.append({"filepath": str(normalized.resolve()), "x": x, "y": y}) - spec = Path(scratch) / "tiles.yaml" - spec.write_text(yaml.safe_dump({"metadata": {"scan_resolution": config.acquisition.scan_resolution_3d[:2]}, "tiles": entries})) + sources[index] = Path(scratch) / f"tile-{index}.nii" + nib.save(nib.Nifti1Image(array, np.eye(4)), sources[index]) + spec = tile_config(config, sources, shape, overlap, Path(scratch) / "tiles.yaml") mosaic2d(tile_info_file=str(spec), nifti_output=str(output), - tile_overlap=overlap if overlap else 0, circular_mean=modality == "ori") + jpeg_output=None if modality == "ori" else str(jpeg), + print_grid=str(output.with_name(f"{output.stem}_grid.jpg")), + tile_overlap=overlap if overlap else 0, circular_mean=modality == "ori", + voxel_size_xyz=list(config.acquisition.scan_resolution_3d[:2])) if not output.is_file(): raise RuntimeError(f"mosaic2d did not produce {output}") - jpeg = output.with_suffix(".jpg") - convert_image(input=output, output=jpeg, angle_to_rgb=modality == "ori", output_format="jpg") + if modality == "ori": + # mosaic2d's JPEG is grayscale; orientation previews use an angle colormap. + # Transpose to match the orientation of mosaic2d's JPEGs. + angles = np.asarray(nib.load(output).dataobj).squeeze().T + convert_image(data=angles, output=jpeg, angle_to_rgb=True, output_format="jpg") return jpeg diff --git a/tests/test_acquisition_previews.py b/tests/test_acquisition_previews.py index 5736438..ceb8659 100644 --- a/tests/test_acquisition_previews.py +++ b/tests/test_acquisition_previews.py @@ -69,12 +69,16 @@ def test_plain_image_with_other_placeholders_and_ambiguity(self): with self.assertRaises(ValueError): preview.expected_tiles(self.cfg, self.ident, self.root, "normal", 1) - def test_geometry(self): - self.assertEqual(preview.tile_position(2, 2, (10, 20), .2, "column-by-column"), (8, 0)) - self.assertEqual(preview.tile_position(2, 2, (10, 20), .2, "snake-by-columns"), (8, 16)) - self.assertEqual(preview.tile_position(2, 2, (10, 20), .2, "snake-by-columns", 2), (0, 16)) - - def test_grid_modes_match_linc_convert(self): + def layout(self, files, mode, order, columns=3): + self.cfg.acquisition.tile_overlap = 20 + self.cfg.enface_preview.grid_config = PreviewGridConfig(grid_type=mode, order=order) + with TemporaryDirectory() as scratch: + out = preview.tile_config(self.cfg, files, (10, 20), .2, Path(scratch) / "tiles.yaml") + import yaml + return {t["tile_number"] - 1: (t["x"], t["y"], t["filepath"]) + for t in yaml.safe_load(out.read_text())["tiles"]} + + def test_tile_config_uses_linc_convert_grid(self): from linc_convert.modalities.psoct import generate_tile_config as grids generators = { "row-by-row": grids._generate_row_by_row, @@ -90,15 +94,18 @@ def test_grid_modes_match_linc_convert(self): # Non-square acquisition: 3 strips of 2 tiles. expected = generator(2 if row_based else 3, 3 if row_based else 2, 10, 20, .2, .2, order, "tile_{tile_number:04d}.nii") - actual = [preview.tile_position(i, 2, (10, 20), .2, mode, - order=order, columns=3) for i in range(6)] - self.assertEqual(actual, [(t["x"], t["y"]) for t in expected]) + expected = [(round(t["x"]), round(t["y"])) for t in expected] + files = {i: Path(f"/data/image_{i + 7}.nii") for i in range(6)} + actual = self.layout(files, mode, order) + x0, y0 = min(x for x, _ in expected), min(y for _, y in expected) + self.assertEqual([actual[i][:2] for i in range(6)], + [(x - x0, y - y0) for x, y in expected]) + self.assertEqual(actual[4][2], "/data/image_11.nii") for batch in range(1, 4): - points = actual[(batch - 1) * 2:batch * 2] - cropped = [(x-min(p[0] for p in points), y-min(p[1] for p in points)) for x, y in points] - strip = [preview.tile_position(i, 2, (10, 20), .2, mode, batch, - order=order, columns=3) for i in range((batch-1)*2, batch*2)] - self.assertEqual(strip, cropped) + points = expected[(batch - 1) * 2:batch * 2] + cropped = [(x - min(p[0] for p in points), y - min(p[1] for p in points)) for x, y in points] + strip = self.layout({i: files[i] for i in range((batch - 1) * 2, batch * 2)}, mode, order) + self.assertEqual([strip[i][:2] for i in sorted(strip)], cropped) def test_grid_schema_validation_and_legacy_migration(self): for mode in ("column-by-column", "snake-by-columns"): @@ -233,7 +240,8 @@ def test_real_mosaic2d_singleton_nifti(self): output = self.root / "stitched" / f"{modality}.nii" jpeg = preview.stitch_preview_modality.fn(self.cfg, files[modality], modality, output) self.assertTrue(jpeg.is_file()) - result = nib.load(output).get_fdata() + self.assertTrue(output.with_name(f"{modality}_grid.jpg").is_file()) + result = nib.load(output).get_fdata().squeeze() self.assertEqual(result.shape, (16, 12)) self.assertAlmostEqual(result[3, 3], 1, places=4) self.assertAlmostEqual(result[11, 9], 4, places=4) From e8944f6f3d2e55fb8549fd34b42bcc1ec011b182 Mon Sep 17 00:00:00 2001 From: Noah Markowitz Date: Mon, 28 Sep 2026 16:57:43 -0400 Subject: [PATCH 29/65] default and processing updates --- docs/acquisition_enface_previews.md | 2 +- docs/developer/cli_overview.md | 2 +- docs/matlab_enface_only.md | 8 +- opticstream/cli/oct/setup.py | 109 +++++++++++++++++- opticstream/config/enface_preview.py | 6 +- opticstream/config/psoct_scan_config.py | 8 +- .../+file/spectral2processed_batch_indexed.m | 34 ++++++ .../+internal/+opts/normalizeSpectralOpts.m | 1 + .../+spectral/loadSpectralCorrections.m | 45 ++++++++ .../+psoct/+spectral/spectral2complex.m | 33 +++--- tests/test_acquisition_previews.py | 7 +- tests/test_acquisition_sequence.py | 2 +- tests/test_complex_outputs.py | 6 +- tests/test_volume_output_setting.py | 13 ++- tests/test_watch_previews.py | 2 + 15 files changed, 233 insertions(+), 45 deletions(-) create mode 100644 opticstream/matlab/+psoct/+spectral/loadSpectralCorrections.m diff --git a/docs/acquisition_enface_previews.md b/docs/acquisition_enface_previews.md index 2023c43..e07ba5e 100644 --- a/docs/acquisition_enface_previews.md +++ b/docs/acquisition_enface_previews.md @@ -94,7 +94,7 @@ strips. `right-down` and `down-right` start at top-left; `left-down` and `down-l at top-right; `right-up` and `up-right` at bottom-left; `left-up` and `up-left` at bottom-right. Snake reverses the fast direction on alternate strips. -Default is `column-by-column` / `down-right`. In column-first mode strips advance +Default is `snake-by-columns` / `up-right`; batch previews (`batch_enabled`) are off by default. In column-first mode strips advance along Y and batches along X; row-first swaps those axes. **Batch size stays grid_size_y and batch count stays the selected grid_size_x**, so row-first has grid_size_y physical columns and grid_size_x physical rows. This keeps the existing diff --git a/docs/developer/cli_overview.md b/docs/developer/cli_overview.md index a39da0f..3cfd86c 100644 --- a/docs/developer/cli_overview.md +++ b/docs/developer/cli_overview.md @@ -31,7 +31,7 @@ is exposed as `opticstream` (with alias `ops`). ### `oct` -- `opticstream oct setup PROJECT_NAME [--project-base-path ... --grid-size-x-normal ... --grid-size-x-tilted ... --grid-size-y ...]` +- `opticstream oct setup PROJECT_NAME [--project-base-path ... --grid-size-x-normal ... --grid-size-x-tilted ... --grid-size-y ... --dandi ... --dandi-path ... --archive-path ... --interpolation {wavelength,phase_calibration} --num-workers ... --linphase-file ... --dspphase-file ... --dispcomp-file ... --dphase-file ... --acq-mosaic-map normal0deg=1,tilted15deg=2 --filename-pattern 'spectral_{image}.nii']` - `opticstream oct create-lock PROJECT_NAME` - `opticstream oct update-block` - `opticstream oct watch PROJECT_NAME FOLDER_PATH [MOSAIC_RANGES] [--slice-offset ... --stability-seconds ... --poll-interval ... --direct/--no-direct --refresh ... --force-resend --min-complex-file-size-bytes ... --verbose]` diff --git a/docs/matlab_enface_only.md b/docs/matlab_enface_only.md index 764cb42..c3532c6 100644 --- a/docs/matlab_enface_only.md +++ b/docs/matlab_enface_only.md @@ -1,7 +1,7 @@ # MATLAB enface-only disk output -Each PSOCTScanConfig has `processing.save_volume_outputs` (default `true`). -Set it to `false` to stop writing per-tile dBI, R3D and O3D NIfTI volumes. +Each PSOCTScanConfig has `processing.save_volume_outputs` (default `false`). +When `false`, OpticStream does not write per-tile dBI, R3D and O3D NIfTI volumes. MATLAB still reconstructs intermediate volumes in memory to calculate enface maps. This saves disk space and write time, not the reconstruction memory allocation. @@ -17,8 +17,8 @@ Slice registration remains enabled; this setting controls reconstructed tile volumes and their mosaic outputs, not registration-derived orientation products. `processing.save_enface_2d_as_3d` is independent: false stores enface maps as 2D -NIfTI instead of X-by-Y-by-1. `stitch_3d_volumes` (default `true`) is an -independent switch: set it to `false` to keep saving per-tile volumes but skip +NIfTI instead of X-by-Y-by-1. `stitch_3d_volumes` (default `false`) is an +independent switch: when `false`, per-tile volumes can still be saved but OpticStream skips mosaic volume stitching (including focus finding) and mosaic volume uploads. Enabling volume saving does not override disabled stitching. diff --git a/opticstream/cli/oct/setup.py b/opticstream/cli/oct/setup.py index 1c293a8..ab873eb 100644 --- a/opticstream/cli/oct/setup.py +++ b/opticstream/cli/oct/setup.py @@ -7,6 +7,7 @@ import logging import warnings from pathlib import Path +from typing import Literal from prefect.blocks.system import Secret @@ -28,6 +29,40 @@ _DEFAULT_MASK_TILTED = 55.0 +def parse_acq_mosaic_map(value: str) -> dict[str, int]: + """ + Parse an acquisition -> mosaic slot map from the command line. + + Accepts ``normal=1,tilted=2``, ``normal:1,tilted:2`` or + ``{normal: 1, tilted: 2}`` (quotes around labels are optional). + """ + body = value.strip() + if body.startswith("{") and body.endswith("}"): + body = body[1:-1] + mapping: dict[str, int] = {} + for item in body.split(","): + item = item.strip() + if not item: + continue + sep = "=" if "=" in item else ":" + label, _, slot = item.partition(sep) + label = label.strip().strip("'\"") + slot = slot.strip().strip("'\"") + if not label or not slot: + raise ValueError( + f"Invalid acq-mosaic-map entry {item!r}; expected LABEL=SLOT" + ) + try: + mapping[label] = int(slot) + except ValueError: + raise ValueError( + f"Invalid mosaic slot {slot!r} for acquisition {label!r}" + ) from None + if not mapping: + raise ValueError("acq-mosaic-map is empty") + return mapping + + @oct_cli.command def update_block() -> None: """ @@ -55,6 +90,16 @@ def setup( grid_size_x_tilted: int = 1, grid_size_y: int = 1, dandi: str | None = None, + dandi_path: Path | None = None, + archive_path: Path | None = None, + interpolation: Literal["wavelength", "phase_calibration"] | None = None, + num_workers: int | None = None, + linphase_file: Path | None = None, + dspphase_file: Path | None = None, + dispcomp_file: Path | None = None, + dphase_file: Path | None = None, + acq_mosaic_map: str | None = None, + filename_pattern: str | None = None, ) -> None: """ Create or update the PSOCTScanConfig block for a project. @@ -62,7 +107,38 @@ def setup( Run this before ``opticstream oct watch``. The block name is derived from ``project_name`` (e.g. ``myproject`` -> ``myproject-psoct-config``). - Defaults keep CLI input minimal: grid sizes are ``1``. + Defaults keep CLI input minimal: grid sizes are ``1``; options left unset + use the PSOCTScanConfig defaults. + + Parameters + ---------- + dandi + Name of the Prefect Secret block holding the DANDI API key. + dandi_path + Local dandiset path (``dandiset_path``). + archive_path + Archive root for raw tiles; unset disables archiving. + interpolation + Spectral interpolation method. + num_workers + MATLAB parallel pool size for spectral-to-processed batches. + linphase_file + .mat file with variable ``linPhase``. + dspphase_file + .mat file with variable ``dspPhase``; also enables + ``phase_calibration_dispersion``. + dispcomp_file + Dispersion compensation file. + dphase_file + .mat file with variable ``dphase``. + acq_mosaic_map + Acquisition label -> mosaic slot, e.g. ``normal=1,tilted=2`` or + ``"{normal: 1, tilted: 2}"``. + filename_pattern + Input filename template; unset keeps legacy ``mosaic__image__*`` + naming. Requires ``{image}``; optional ``{slice}``, ``{acquisition}``, + ``{subject}``, ``{modality}``, ``{extension}``. Quote it in the shell, + e.g. ``'spectral_{image}.nii'``. """ update_block() ensure_lock(project_name) @@ -72,17 +148,38 @@ def setup( if project_base_path is None: logger.warning("project_base_path is not set, please set it using prefect UI") + acquisition: dict = { + "grid_size_x_normal": grid_size_x_normal, + "grid_size_x_tilted": grid_size_x_tilted, + "grid_size_y": grid_size_y, + } + if acq_mosaic_map is not None: + acquisition["acquisition_mosaic_map"] = parse_acq_mosaic_map(acq_mosaic_map) + if filename_pattern: + acquisition["filename_pattern"] = filename_pattern + + processing_overrides = { + "interpolation_method": interpolation, + "matlab_num_workers": num_workers, + "lin_phase_file": linphase_file, + "dsp_phase_file": dspphase_file, + "disp_comp_file": dispcomp_file, + "dphase_file": dphase_file, + } + processing = {k: v for k, v in processing_overrides.items() if v is not None} + if dspphase_file is not None: + processing["phase_calibration_dispersion"] = True + scan_config = PSOCTScanConfig( project_name=project_name if project_name else Path("."), project_base_path=project_base_path if project_base_path else Path("."), - acquisition={ - "grid_size_x_normal": grid_size_x_normal, - "grid_size_x_tilted": grid_size_x_tilted, - "grid_size_y": grid_size_y, - }, + acquisition=acquisition, + processing=processing, mask_threshold_normal=_DEFAULT_MASK_NORMAL, mask_threshold_tilted=_DEFAULT_MASK_TILTED, + dandiset_path=dandi_path, dandi_api_key=Secret.load(dandi) if dandi else None, + archive_path=archive_path, zarr_config=default_zarr_config(), ) # Prefect serializes the block through Pydantic, whose warning message is diff --git a/opticstream/config/enface_preview.py b/opticstream/config/enface_preview.py index 168d6ee..31834fa 100644 --- a/opticstream/config/enface_preview.py +++ b/opticstream/config/enface_preview.py @@ -9,9 +9,9 @@ class PreviewGridConfig(BaseModel): model_config = ConfigDict(extra="forbid", validate_assignment=True) grid_type: Literal["snake-by-columns", "row-by-row", "column-by-column", "snake-by-rows"] = Field( - default="column-by-column", description="Acquisition traversal. Snake reverses the fast direction on alternate strips; individual images are not flipped. Each strip still contains grid_size_y consecutive tiles.") + default="snake-by-columns", description="Acquisition traversal. Snake reverses the fast direction on alternate strips; individual images are not flipped. Each strip still contains grid_size_y consecutive tiles.") order: Literal["up-right", "right-down", "left-down", "right-up", "left-up", "down-right", "down-left", "up-left"] = Field( - default="down-right", description="Rows: right-down (top-left), left-down (top-right), right-up (bottom-left), left-up (bottom-right). Columns: down-right (top-left), down-left (top-right), up-right (bottom-left), up-left (bottom-right). First word is initial within-strip movement; second is movement between strips. Must match grid_type.") + default="up-right", description="Rows: right-down (top-left), left-down (top-right), right-up (bottom-left), left-up (bottom-right). Columns: down-right (top-left), down-left (top-right), up-right (bottom-left), up-left (bottom-right). First word is initial within-strip movement; second is movement between strips. Must match grid_type.") @model_validator(mode="after") def compatible_order(self): @@ -25,7 +25,7 @@ def compatible_order(self): class EnfacePreviewConfig(BaseModel): model_config = ConfigDict(extra="forbid", validate_assignment=True) - batch_enabled: bool = Field(default=True, description="Stitch each complete grid_size_y-tile batch and send previews to Slack when watch-enface runs.") + batch_enabled: bool = Field(default=False, description="Stitch each complete grid_size_y-tile batch and send previews to Slack when watch-enface runs.") acquisition_enabled: bool = Field(default=True, description="Also stitch the complete acquisition/mosaic and send previews to Slack.") aip_pattern: str = Field(default="mosaic_{mosaic:03d}_image_{image:04d}_aip.nii", description="Filename format, not a glob. Required {image}; optional {slice}, {mosaic}, {acquisition}, {project}. A plain {image} matches the number with any zero padding (1, 01, 0001), like filename_pattern; {image:04d} renders exactly. Example: slice-{slice}_acq-{acquisition}_aip_{image}.nii") mip_pattern: str = Field(default="mosaic_{mosaic:03d}_image_{image:04d}_mip.nii", description="MIP filename format; same placeholders as aip_pattern. Set the actual suffix, including .nii.gz if used.") diff --git a/opticstream/config/psoct_scan_config.py b/opticstream/config/psoct_scan_config.py index 59d41d4..b935e8e 100644 --- a/opticstream/config/psoct_scan_config.py +++ b/opticstream/config/psoct_scan_config.py @@ -204,7 +204,7 @@ class PSOCTProcessingParams(BaseModel): ) save_volume_outputs: bool = Field( - default=True, + default=False, description=("Save per-tile dBI, R3D and O3D volume files. Disable for enface-only " "disk output; intermediate volumes are still computed in memory. " "Also skips volume validation, mosaic volume stitching and volume uploads. " @@ -383,7 +383,7 @@ class PSOCTScanConfigModel(BaseModel): ) archive_tile_name_format: str = Field( default=( - "{project_name}_sample-slice{slice_id:02d}_chunk-{tile_id:04d}_acq-{acq}_OCT.nii.gz" + "{project_name}_slice-{slice_id:04d}_tile-{tile_id:04d}_acq-{acq}_OCT.nii.gz" ), description=( "Filename template for archived tile outputs " @@ -392,7 +392,7 @@ class PSOCTScanConfigModel(BaseModel): ) complex_tile_name_format: str = Field( default=( - "{project_name}_sample-slice{slice_id:02d}_chunk-{tile_id:04d}_acq-{acq}" + "{project_name}_slice-{slice_id:04d}_tile-{tile_id:04d}_acq-{acq}" "_desc-complex_OCT.nii.gz" ), description=( @@ -451,7 +451,7 @@ class PSOCTScanConfigModel(BaseModel): ) stitch_3d_volumes: bool = Field( - default=True, + default=False, description=( "Enable 3D mosaic volume stitching (including focus finding) and " "mosaic volume uploads. When false, both are skipped without setting " diff --git a/opticstream/matlab/+psoct/+file/spectral2processed_batch_indexed.m b/opticstream/matlab/+psoct/+file/spectral2processed_batch_indexed.m index 8653923..2828fc2 100644 --- a/opticstream/matlab/+psoct/+file/spectral2processed_batch_indexed.m +++ b/opticstream/matlab/+psoct/+file/spectral2processed_batch_indexed.m @@ -47,6 +47,10 @@ function spectral2processed_batch_indexed(filenames, outputDir, mosaicId, tileIn modalities = psoct.file.internal.processedModalities(); +% Load the phase calibration / dispersion compensation files once for the +% whole batch; each tile's spectral2complex reuses them instead of reopening. +spectralOpts = preloadSpectralCorrections(files, spectralOpts, optsMatFile); + if ~isempty(numWorkers) && numWorkers == 1 for idx = 1:numel(files) inFile = files{idx}; @@ -120,3 +124,33 @@ function spectral2processed_batch_indexed(filenames, outputDir, mosaicId, tileIn end end + +function spectralOpts = preloadSpectralCorrections(files, spectralOpts, optsMatFile) +%PRELOADSPECTRALCORRECTIONS Attach the batch's calibration/dispersion data to spectralOpts. +% Uses the same spectralOpts each tile sees (optsMatFile merged with the +% passed overrides). On failure, tiles fall back to reading the files +% themselves and report the error per tile as before. +if isempty(files) + return +end +try + effectiveOpts = spectralOpts; + if optsMatFile ~= "" + loadedOpts = psoct.internal.opts.loadOptsWithDefaults( ... + optsMatFile, "spectralOpts", "psoct:file:spectral2processed_batch_indexed"); + effectiveOpts = psoct.internal.opts.mergeStructs(loadedOpts.spectralOpts, spectralOpts); + end + normalizedOpts = psoct.internal.opts.normalizeSpectralOpts(effectiveOpts); + if normalizedOpts.isRawFormat + sampleCount = 2048; % headerless packed raw geometry (see spectral2complex) + else + info = niftiinfo(files{1}); + sampleCount = info.ImageSize(1); + end + spectralOpts.preloadedCorrections = ... + psoct.spectral.loadSpectralCorrections(effectiveOpts, sampleCount); +catch ME + warning("psoct:file:spectral2processed_batch_indexed:PreloadFailed", ... + "Could not preload spectral corrections; tiles will load them individually: %s", ME.message); +end +end diff --git a/opticstream/matlab/+psoct/+internal/+opts/normalizeSpectralOpts.m b/opticstream/matlab/+psoct/+internal/+opts/normalizeSpectralOpts.m index 755e91c..823ace7 100644 --- a/opticstream/matlab/+psoct/+internal/+opts/normalizeSpectralOpts.m +++ b/opticstream/matlab/+psoct/+internal/+opts/normalizeSpectralOpts.m @@ -31,6 +31,7 @@ nargs.dspPhaseFile (1,1) string = "" nargs.phaseCalibrationDispersion (1,1) logical = false nargs.flipChannel2Spectra logical = [] + nargs.preloadedCorrections = [] % from psoct.spectral.loadSpectralCorrections end if ~isempty(nargs.flipChannel2Spectra) && ~isscalar(nargs.flipChannel2Spectra) error('psoct:calibration:InvalidFlip', 'flipChannel2Spectra must be a scalar logical.'); diff --git a/opticstream/matlab/+psoct/+spectral/loadSpectralCorrections.m b/opticstream/matlab/+psoct/+spectral/loadSpectralCorrections.m new file mode 100644 index 0000000..de04898 --- /dev/null +++ b/opticstream/matlab/+psoct/+spectral/loadSpectralCorrections.m @@ -0,0 +1,45 @@ +function corrections = loadSpectralCorrections(spectralOpts, sampleCount) +%LOADSPECTRALCORRECTIONS Read the calibration/dispersion files spectral2complex needs. +% +% corrections = psoct.spectral.loadSpectralCorrections(spectralOpts, sampleCount) +% +% Reads the phase calibration (dphase/linPhase[/dspPhase]) or the dispersion +% compensation file for SAMPLECOUNT spectral samples. Batch wrappers call this +% once and pass the result as spectralOpts.preloadedCorrections, so each tile +% does not re-read the same files. +% +% Output struct fields: +% sampleCount : Spectral sample count the corrections were read for. +% calibration : Phase calibration struct (empty struct in wavelength mode). +% phaseCorrection1 : Channel 1 dispersion correction (sampleCount x 1). +% phaseCorrection2 : Channel 2 dispersion correction (sampleCount x 1). +arguments + spectralOpts struct + sampleCount (1,1) double {mustBeInteger, mustBePositive} +end + +spectralOpts = psoct.internal.opts.normalizeSpectralOpts(spectralOpts); +phaseMode = spectralOpts.interpolationMethod == "phase_calibration"; + +calibration = struct(); +if phaseMode + calibration = psoct.spectral.loadPhaseCalibration( ... + spectralOpts.interpolationPath, sampleCount, spectralOpts.phaseCalibrationDispersion, ... + spectralOpts.dphaseFile, spectralOpts.linPhaseFile, spectralOpts.dspPhaseFile); +end + +% Read the channel-specific corrections from the two halves of one file. +if phaseMode && spectralOpts.phaseCalibrationDispersion && ~isempty(calibration.dispersion) + phaseCorrection1 = calibration.dispersion; + phaseCorrection2 = calibration.dispersion; +else + [phaseCorrection1, phaseCorrection2] = ... + opticstream_read_dispersion(string(spectralOpts.dispCompFile), sampleCount); +end + +corrections = struct(); +corrections.sampleCount = sampleCount; +corrections.calibration = calibration; +corrections.phaseCorrection1 = phaseCorrection1; +corrections.phaseCorrection2 = phaseCorrection2; +end diff --git a/opticstream/matlab/+psoct/+spectral/spectral2complex.m b/opticstream/matlab/+psoct/+spectral/spectral2complex.m index 1779388..c6c74a2 100644 --- a/opticstream/matlab/+psoct/+spectral/spectral2complex.m +++ b/opticstream/matlab/+psoct/+spectral/spectral2complex.m @@ -11,6 +11,10 @@ % - BlineSize : Size of the B-line (pixels of Y axis). % - isRawFormat : Input is headerless packed 12-bit data % (read into local variable is12bit). +% - preloadedCorrections : Optional output of +% psoct.spectral.loadSpectralCorrections (set by +% the batch wrapper); skips re-reading the +% calibration/dispersion files. % outputOpts : Struct with fields: % - Paths : Struct with fields: % - complex : Path to the output complex NIfTI file. @@ -31,7 +35,6 @@ spectralOpts = psoct.internal.opts.normalizeSpectralOpts(spectralOpts); outputOpts = psoct.internal.opts.normalizeOutputOpts(outputOpts); -dispCompFile = string(spectralOpts.dispCompFile); AlineSize = spectralOpts.AlineSize; BlineSize = spectralOpts.BlineSize; is12bit = spectralOpts.isRawFormat; % packed 12-bit, headerless (tile_saving_type=spectral_12bit) @@ -98,12 +101,15 @@ phaseMode = spectralOpts.interpolationMethod == "phase_calibration"; Wavelengths_l = []; Wavelengths_r = []; InterpolatedWavelengths2 = []; -calibration = struct(); -if phaseMode - calibration = psoct.spectral.loadPhaseCalibration( ... - spectralOpts.interpolationPath, AlineLength, spectralOpts.phaseCalibrationDispersion, ... - spectralOpts.dphaseFile, spectralOpts.linPhaseFile, spectralOpts.dspPhaseFile); -else + +% Calibration/dispersion files: use the batch's preloaded copy when it matches +% this tile's sample count; otherwise (e.g. a standalone call) read them here. +corrections = spectralOpts.preloadedCorrections; +if isempty(corrections) || corrections.sampleCount ~= AlineLength + corrections = psoct.spectral.loadSpectralCorrections(spectralOpts, AlineLength); +end +calibration = corrections.calibration; +if ~phaseMode [Wavelengths_l, Wavelengths_r, InterpolatedWavelengths2, Ks] = ... opticstream_interpolationwave(InterpolationParameters); %#ok end @@ -128,18 +134,9 @@ params.Wavelengths_r = Wavelengths_r; params.InterpolatedWavelengths = InterpolatedWavelengths2; -% Read the channel-specific corrections from the two halves of one file. -if phaseMode && spectralOpts.phaseCalibrationDispersion && ~isempty(calibration.dispersion) - phaseCorrection1 = calibration.dispersion; - phaseCorrection2 = calibration.dispersion; -else - [phaseCorrection1, phaseCorrection2] = ... - opticstream_read_dispersion(dispCompFile, AlineLength); -end - % Replicate along A-line dimension to match interpolated buffer size -phaseCorrection1 = repmat(phaseCorrection1, 1, Aline); -phaseCorrection2 = repmat(phaseCorrection2, 1, Aline); +phaseCorrection1 = repmat(corrections.phaseCorrection1, 1, Aline); +phaseCorrection2 = repmat(corrections.phaseCorrection2, 1, Aline); % Preallocate complex stacks for Jones1 and Jones2: % dimensions: Bline x Aline x DepthL (complex) diff --git a/tests/test_acquisition_previews.py b/tests/test_acquisition_previews.py index ceb8659..66a2470 100644 --- a/tests/test_acquisition_previews.py +++ b/tests/test_acquisition_previews.py @@ -16,7 +16,8 @@ def config(root): return SimpleNamespace(project_base_path=Path(root) / "out", mosaics_per_slice=2, - enface_preview=EnfacePreviewConfig(**{f"{m}_pattern": f"{m}_{{image:04d}}.nii" for m in preview.MODALITIES}), + enface_preview=EnfacePreviewConfig(batch_enabled=True, grid_config={"grid_type": "column-by-column", "order": "down-right"}, + **{f"{m}_pattern": f"{m}_{{image:04d}}.nii" for m in preview.MODALITIES}), acquisition=PSOCTAcquisitionParams(grid_size_y=2, grid_size_x_normal=2, grid_size_x_tilted=3, tile_overlap=0)) @@ -115,6 +116,10 @@ def test_grid_schema_validation_and_legacy_migration(self): self.assertNotIn("traversal", migrated.model_dump()) with self.assertRaises(ValueError): PreviewGridConfig(grid_type="row-by-row", order="down-right") + defaults = EnfacePreviewConfig() + self.assertFalse(defaults.batch_enabled) + self.assertEqual((defaults.grid_config.grid_type, defaults.grid_config.order), + ("snake-by-columns", "up-right")) cfg = EnfacePreviewConfig(grid_config={"grid_type": "snake-by-rows", "order": "left-up"}) self.assertEqual(cfg.grid_config.order, "left-up") diff --git a/tests/test_acquisition_sequence.py b/tests/test_acquisition_sequence.py index c34145f..d8765ed 100644 --- a/tests/test_acquisition_sequence.py +++ b/tests/test_acquisition_sequence.py @@ -21,7 +21,7 @@ def config(root="/tmp", normal=3, tilted=2, rows=2, pattern="spectral_{image}.ni grid_size_x_normal=normal, grid_size_x_tilted=tilted, grid_size_y=rows, tile_overlap=0, filename_pattern=pattern, acquisition_mosaic_map={"normal0deg": 1, "tilted15deg": 2}), - enface_preview=EnfacePreviewConfig(**{ + enface_preview=EnfacePreviewConfig(batch_enabled=True, grid_config={"grid_type": "column-by-column", "order": "down-right"}, **{ f"{m}_pattern": f"img_{{image}}_{m}.nii" for m in ("aip", "mip", "ori", "ret")}), ) diff --git a/tests/test_complex_outputs.py b/tests/test_complex_outputs.py index bb1da0b..4737e54 100644 --- a/tests/test_complex_outputs.py +++ b/tests/test_complex_outputs.py @@ -37,9 +37,13 @@ def test_defaults(self): self.assertFalse(cfg.processing.save_complex_outputs) self.assertEqual( cfg.complex_tile_name_format, - "{project_name}_sample-slice{slice_id:02d}_chunk-{tile_id:04d}_acq-{acq}" + "{project_name}_slice-{slice_id:04d}_tile-{tile_id:04d}_acq-{acq}" "_desc-complex_OCT.nii.gz", ) + self.assertEqual( + cfg.archive_tile_name_format, + "{project_name}_slice-{slice_id:04d}_tile-{tile_id:04d}_acq-{acq}_OCT.nii.gz", + ) def test_matlab_opts_carry_complex_dir_only_when_set(self): cfg = scan_config() diff --git a/tests/test_volume_output_setting.py b/tests/test_volume_output_setting.py index 79f789f..4283bd0 100644 --- a/tests/test_volume_output_setting.py +++ b/tests/test_volume_output_setting.py @@ -41,8 +41,8 @@ def _check_command_flag_and_enface_validation(tmp_path, enabled): validate_processed_batch_outputs(**args) -def _check_existing_blocks_default_enabled(): - assert PSOCTProcessingParams.model_validate({}).save_volume_outputs is True +def _check_default_disabled(): + assert PSOCTProcessingParams.model_validate({}).save_volume_outputs is False def _check_disabled_upload_skips_all_milestones(tmp_path, cfg): @@ -80,7 +80,7 @@ def test_commands_and_validation(self): _check_command_flag_and_enface_validation(Path(folder), enabled) def test_default(self): - _check_existing_blocks_default_enabled() + _check_default_disabled() def test_upload(self): with TemporaryDirectory() as folder: @@ -100,6 +100,9 @@ def test_stitch_3d_volumes_disabled_skips_stitch(self): cfg = config(Path(folder), True, stitch_3d_volumes=False) _check_disabled_stitch_skips_before_volume_milestone(Path(folder), cfg) - def test_stitch_3d_volumes_default_enabled(self): + def test_stitch_3d_volumes_default_disabled(self): with TemporaryDirectory() as folder: - self.assertTrue(config(Path(folder), True).stitch_3d_volumes) + cfg = PSOCTScanConfigModel(project_name="test", project_base_path=Path(folder), + acquisition=dict(grid_size_x_normal=1, grid_size_x_tilted=1, grid_size_y=1), + zarr_config=ZarrConfig()) + self.assertFalse(cfg.stitch_3d_volumes) diff --git a/tests/test_watch_previews.py b/tests/test_watch_previews.py index 3301b50..44e8606 100644 --- a/tests/test_watch_previews.py +++ b/tests/test_watch_previews.py @@ -16,6 +16,8 @@ def scan_config(root, **preview): + preview.setdefault("batch_enabled", True) + preview.setdefault("grid_config", {"grid_type": "column-by-column", "order": "down-right"}) return SimpleNamespace( project_base_path=Path(root) / "out", mosaics_per_slice=2, From 80ee3381d357651d72777815115b701ea13f9457 Mon Sep 17 00:00:00 2001 From: Noah Markowitz Date: Tue, 29 Sep 2026 14:47:20 -0400 Subject: [PATCH 30/65] add grid-size-y-tilt --- docs/acquisition_enface_previews.md | 5 ++- docs/oct_input_naming.md | 5 +-- opticstream/cli/oct/setup.py | 5 +++ opticstream/cli/oct/watch.py | 35 +++++++++++++------ opticstream/config/enface_preview.py | 4 +-- opticstream/config/psoct_scan_config.py | 13 ++++++- .../flows/psoct/acquisition_preview_flow.py | 18 ++++++---- opticstream/flows/psoct/utils.py | 5 ++- opticstream/utils/acquisition_sequence.py | 3 +- tests/test_acquisition_previews.py | 34 ++++++++++++++++-- tests/test_acquisition_sequence.py | 19 +++++++++- 11 files changed, 117 insertions(+), 29 deletions(-) diff --git a/docs/acquisition_enface_previews.md b/docs/acquisition_enface_previews.md index e07ba5e..2c1b024 100644 --- a/docs/acquisition_enface_previews.md +++ b/docs/acquisition_enface_previews.md @@ -80,7 +80,10 @@ Slice/mosaic identify outputs explicitly; acquisition is the exact filename labe Tiles are numbered consecutively within the acquisition starting at `first_image` (default 1). Batch 1 contains the first `grid_size_y` tiles, batch 2 the next set, -etc. Total tiles = selected `grid_size_x` * `grid_size_y`. +etc. Total tiles = selected `grid_size_x` * `grid_size_y`. Tilted mosaics use +`grid_size_y_tilted` in place of `grid_size_y` when it is set, e.g. a scanner with +22 strips of 18 (normal) and 25 (tilted) tiles uses `grid_size_x_normal=22`, +`grid_size_x_tilted=22`, `grid_size_y=18`, `grid_size_y_tilted=25`. In the block editor, `enface_preview.grid_config` exposes all linc-convert modes: diff --git a/docs/oct_input_naming.md b/docs/oct_input_naming.md index 74b81c0..96b7273 100644 --- a/docs/oct_input_naming.md +++ b/docs/oct_input_naming.md @@ -22,7 +22,8 @@ slice is 37, image is 41, and the mosaic slot is 1. With two mosaics per slice, the global source mosaic is 73. The tilted15deg file maps to source mosaic 74. Watcher mosaic-range filters use these global source IDs. Slice offsets retain their existing behavior. Image numbers must be 1-based indices within a mosaic; -batch size remains `grid_size_y`, and incomplete batches are not dispatched. +batch size remains `grid_size_y` (`grid_size_y_tilted` for tilted mosaics when set), +and incomplete batches are not dispatched. Acquisition labels are arbitrary: change the map to accept `normal5deg` or another label. Values are mosaic slots, not angle measurements. Slot ordering @@ -51,7 +52,7 @@ With 22 x 16 grids for both illuminations, that places: | ... | ... | ... | Each mosaic holds `grid_size_x * grid_size_y` tiles, using `grid_size_x_normal` or -`grid_size_x_tilted` for its illumination, and its tiles are renumbered from 1. After +`grid_size_x_tilted` (and `grid_size_y_tilted`, when set) for its illumination, and its tiles are renumbered from 1. After the slice's last mosaic the sequence continues with mosaic 1 of the next slice. Placement depends only on the image number, so restarting the watcher is safe. diff --git a/opticstream/cli/oct/setup.py b/opticstream/cli/oct/setup.py index ab873eb..8754865 100644 --- a/opticstream/cli/oct/setup.py +++ b/opticstream/cli/oct/setup.py @@ -89,6 +89,7 @@ def setup( grid_size_x_normal: int = 1, grid_size_x_tilted: int = 1, grid_size_y: int = 1, + grid_size_y_tilted: int | None = None, dandi: str | None = None, dandi_path: Path | None = None, archive_path: Path | None = None, @@ -112,6 +113,8 @@ def setup( Parameters ---------- + grid_size_y_tilted + Tiles per batch for tilted mosaics; unset uses ``grid_size_y``. dandi Name of the Prefect Secret block holding the DANDI API key. dandi_path @@ -153,6 +156,8 @@ def setup( "grid_size_x_tilted": grid_size_x_tilted, "grid_size_y": grid_size_y, } + if grid_size_y_tilted is not None: + acquisition["grid_size_y_tilted"] = grid_size_y_tilted if acq_mosaic_map is not None: acquisition["acquisition_mosaic_map"] = parse_acq_mosaic_map(acq_mosaic_map) if filename_pattern: diff --git a/opticstream/cli/oct/watch.py b/opticstream/cli/oct/watch.py index bd766d5..f3cd920 100644 --- a/opticstream/cli/oct/watch.py +++ b/opticstream/cli/oct/watch.py @@ -284,9 +284,10 @@ def _discover_two_mosaic_candidates(self) -> list[OCTBatchCandidate]: if not tile_indices: continue + batch_size = self._batch_size(source_mosaic_id) batches: dict[int, list[int]] = defaultdict(list) for image_index in sorted(tile_indices): - logical_batch = (image_index - 1) // self.batch_size + 1 + logical_batch = (image_index - 1) // batch_size + 1 batches[logical_batch].append(image_index) max_batches = self._batches_in_mosaic(source_mosaic_id) @@ -301,13 +302,13 @@ def _discover_two_mosaic_candidates(self) -> list[OCTBatchCandidate]: max_batches, ) continue - if len(batch_tile_indices) < self.batch_size: + if len(batch_tile_indices) < batch_size: logger.warning( "Incomplete batch source_mosaic=%s logical_batch=%s (%s tiles, need %s)", source_mosaic_id, logical_batch, len(batch_tile_indices), - self.batch_size, + batch_size, ) continue @@ -352,13 +353,22 @@ def _discover_two_mosaic_candidates(self) -> list[OCTBatchCandidate]: return out - def _batches_in_mosaic(self, source_mosaic_id: int) -> int: - context = mosaic_context_from_ids( + def _mosaic_context(self, source_mosaic_id: int): + return mosaic_context_from_ids( slice_id=slice_from_mosaic(source_mosaic_id, self.scan_config.mosaics_per_slice), mosaic_id=source_mosaic_id, mosaics_per_slice=self.scan_config.mosaics_per_slice, ) - return context.grid_size_x(self.scan_config) + + def _batches_in_mosaic(self, source_mosaic_id: int) -> int: + return self._mosaic_context(source_mosaic_id).grid_size_x(self.scan_config) + + def _batch_size(self, source_mosaic_id: int) -> int: + """Tiles per batch: batch_size, or grid_size_y_tilted for tilted mosaics.""" + tilted = getattr(self.scan_config.acquisition, "grid_size_y_tilted", None) + if tilted is None or self._mosaic_context(source_mosaic_id).is_normal_config: + return self.batch_size + return tilted def _matches_fixed_mosaic(self, source_mosaic_id: int) -> bool: """Apply --slice/--acquisition/--mosaic as a filter to legacy filenames.""" @@ -441,19 +451,20 @@ def _discover_three_mosaic_candidates(self) -> list[OCTBatchCandidate]: for pf in parsed_files: files_by_tile[pf.tile_number].append(pf.path) + batch_size = self._batch_size(source_mosaic_id) batches: dict[int, list[int]] = defaultdict(list) for tile_number in sorted(files_by_tile.keys()): - logical_batch = (tile_number - 1) // self.batch_size + 1 + logical_batch = (tile_number - 1) // batch_size + 1 batches[logical_batch].append(tile_number) for logical_batch, batch_tile_numbers in sorted(batches.items()): - if len(batch_tile_numbers) < self.batch_size: + if len(batch_tile_numbers) < batch_size: logger.warning( "Incomplete batch source_mosaic=%s logical_batch=%s (%s tiles, need %s)", source_mosaic_id, logical_batch, len(batch_tile_numbers), - self.batch_size, + batch_size, ) continue @@ -907,7 +918,11 @@ def watch( ) logger.info("Using slice=%s mosaic_slot=%s from command line", fixed_slice_id, fixed_mosaic_slot) - logger.info("Using batch_size=%s", batch_size) + logger.info( + "Using batch_size=%s (tilted: %s)", + batch_size, + scan_config.acquisition.grid_size_y_tilted or batch_size, + ) logger.info("Using mosaics_per_slice=%s", scan_config.mosaics_per_slice) logger.info("Using tile_saving_type=%s", scan_config.acquisition.tile_saving_type) diff --git a/opticstream/config/enface_preview.py b/opticstream/config/enface_preview.py index 31834fa..49bd48e 100644 --- a/opticstream/config/enface_preview.py +++ b/opticstream/config/enface_preview.py @@ -9,7 +9,7 @@ class PreviewGridConfig(BaseModel): model_config = ConfigDict(extra="forbid", validate_assignment=True) grid_type: Literal["snake-by-columns", "row-by-row", "column-by-column", "snake-by-rows"] = Field( - default="snake-by-columns", description="Acquisition traversal. Snake reverses the fast direction on alternate strips; individual images are not flipped. Each strip still contains grid_size_y consecutive tiles.") + default="snake-by-columns", description="Acquisition traversal. Snake reverses the fast direction on alternate strips; individual images are not flipped. Each strip still contains grid_size_y (or grid_size_y_tilted) consecutive tiles.") order: Literal["up-right", "right-down", "left-down", "right-up", "left-up", "down-right", "down-left", "up-left"] = Field( default="up-right", description="Rows: right-down (top-left), left-down (top-right), right-up (bottom-left), left-up (bottom-right). Columns: down-right (top-left), down-left (top-right), up-right (bottom-left), up-left (bottom-right). First word is initial within-strip movement; second is movement between strips. Must match grid_type.") @@ -31,7 +31,7 @@ class EnfacePreviewConfig(BaseModel): mip_pattern: str = Field(default="mosaic_{mosaic:03d}_image_{image:04d}_mip.nii", description="MIP filename format; same placeholders as aip_pattern. Set the actual suffix, including .nii.gz if used.") ori_pattern: str = Field(default="mosaic_{mosaic:03d}_image_{image:04d}_ori.nii", description="Orientation filename format. Orientation is blended with circular averaging.") ret_pattern: str = Field(default="mosaic_{mosaic:03d}_image_{image:04d}_ret.nii", description="Retardance filename format; no hardcoded modality suffix.") - grid_config: PreviewGridConfig = Field(default_factory=PreviewGridConfig, description="linc-convert-compatible grid traversal and starting direction for acquisition previews. grid_size_y is tiles per strip; selected grid_size_x is number of strips, regardless of traversal axis.") + grid_config: PreviewGridConfig = Field(default_factory=PreviewGridConfig, description="linc-convert-compatible grid traversal and starting direction for acquisition previews. grid_size_y (grid_size_y_tilted for tilted mosaics) is tiles per strip; selected grid_size_x is number of strips, regardless of traversal axis.") first_image: int = Field(default=1, ge=0, description="First filename image index within this acquisition. Batches themselves remain 1-based.") orientation_units: Literal["degrees", "radians"] = Field(default="degrees", description="Units of acquisition orientation maps; radians are converted to degrees for linc-convert.") diff --git a/opticstream/config/psoct_scan_config.py b/opticstream/config/psoct_scan_config.py index b935e8e..160d00b 100644 --- a/opticstream/config/psoct_scan_config.py +++ b/opticstream/config/psoct_scan_config.py @@ -113,7 +113,18 @@ def validate_acquisition_mosaic_map(cls, value): grid_size_y: int = Field( ..., ge=1, - description="Number of tiles per batch (rows) - determines batch size (required)", + description=( + "Number of tiles per batch (rows) - determines batch size (required). " + "Used for normal illumination, and for tilted unless grid_size_y_tilted is set" + ), + ) + grid_size_y_tilted: int | None = Field( + default=None, + ge=1, + description=( + "Number of tiles per batch (rows) for tilted illumination; " + "unset uses grid_size_y" + ), ) tile_size_x_normal: int = Field( diff --git a/opticstream/flows/psoct/acquisition_preview_flow.py b/opticstream/flows/psoct/acquisition_preview_flow.py index 5ea86ea..4c223a6 100644 --- a/opticstream/flows/psoct/acquisition_preview_flow.py +++ b/opticstream/flows/psoct/acquisition_preview_flow.py @@ -93,7 +93,7 @@ def expected_tiles(config, mosaic_ident, input_dir, acquisition, batch_id=None, ``names`` is an optional pre-read listing of ``input_dir``. """ context = mosaic_context_from_ident(mosaic_ident, config) - rows = config.acquisition.grid_size_y + rows = context.grid_size_y(config) columns = context.grid_size_x(config) if batch_id is not None and not 1 <= batch_id <= columns: raise ValueError(f"batch_id must be between 1 and {columns}") @@ -193,9 +193,11 @@ def tile_shape(path): return tuple(shape[:2]) -def tile_config(config, files, shape, overlap, out): +def tile_config(config, files, shape, overlap, out, per_strip=None): """Write a linc-convert tile YAML for ``files`` (acquisition index -> path). + ``per_strip`` is the mosaic's tiles per strip (default: grid_size_y). + The full grid comes from linc-convert's generate_tile_config; entries are then limited to ``files`` (a single batch keeps the direction its strip has in the full snake), pointed at the resolved paths, and shifted to start at (0, 0). @@ -203,7 +205,7 @@ def tile_config(config, files, shape, overlap, out): from linc_convert.modalities.psoct.generate_tile_config import generate_tile_config grid = config.enface_preview.grid_config - per_strip = config.acquisition.grid_size_y + per_strip = per_strip or config.acquisition.grid_size_y strips = max(files) // per_strip + 1 row_based = grid.grid_type in {"row-by-row", "snake-by-rows"} columns, rows = (per_strip, strips) if row_based else (strips, per_strip) @@ -227,7 +229,8 @@ def tile_config(config, files, shape, overlap, out): @task def stitch_preview_modality(config: PSOCTScanConfigModel, files: dict[int, Path], - modality: str, output: Path, batch_id: int | None = None) -> Path: + modality: str, output: Path, batch_id: int | None = None, + per_strip: int | None = None) -> Path: """Stitch acquisition tiles in place with linc-convert generate_tile_config + mosaic2d. Writes ``output`` (NIfTI), a JPEG next to it, and a ``*_grid.jpg`` tile diagram. @@ -262,7 +265,8 @@ def stitch_preview_modality(config: PSOCTScanConfigModel, files: dict[int, Path] array = np.rad2deg(array) sources[index] = Path(scratch) / f"tile-{index}.nii" nib.save(nib.Nifti1Image(array, np.eye(4)), sources[index]) - spec = tile_config(config, sources, shape, overlap, Path(scratch) / "tiles.yaml") + spec = tile_config(config, sources, shape, overlap, Path(scratch) / "tiles.yaml", + per_strip) mosaic2d(tile_info_file=str(spec), nifti_output=str(output), jpeg_output=None if modality == "ori" else str(jpeg), print_grid=str(output.with_name(f"{output.stem}_grid.jpg")), @@ -288,10 +292,12 @@ def run_preview(config, mosaic_ident, input_dir, acquisition, batch_id=None, *, progress_file = progress_path(config, mosaic_ident, batch_id) progress = read_progress(progress_file, signature) outputs = {m: preview_path(config, mosaic_ident, batch_id, f"{m}.nii") for m in MODALITIES} + per_strip = mosaic_context_from_ident(mosaic_ident, config).grid_size_y(config) for modality in MODALITIES: output = outputs[modality] if modality not in progress["stitched"] or not output.with_suffix(".jpg").exists() or not output.exists(): - stitch_preview_modality(config, files[modality], modality, output, batch_id) + stitch_preview_modality(config, files[modality], modality, output, batch_id, + per_strip=per_strip) if fingerprint(config, files) != signature: raise RuntimeError("Acquisition files changed while stitching; wait for stability and retry") if modality not in progress["stitched"]: diff --git a/opticstream/flows/psoct/utils.py b/opticstream/flows/psoct/utils.py index 71a060c..04c4ee5 100644 --- a/opticstream/flows/psoct/utils.py +++ b/opticstream/flows/psoct/utils.py @@ -362,7 +362,10 @@ def grid_size_x(self, config: PSOCTScanConfigModel) -> int: ) def grid_size_y(self, config: PSOCTScanConfigModel) -> int: - return config.acquisition.grid_size_y + tilted = config.acquisition.grid_size_y_tilted + if self.is_normal_config or tilted is None: + return config.acquisition.grid_size_y + return tilted def tile_size_x(self, config: PSOCTScanConfigModel) -> int: return ( diff --git a/opticstream/utils/acquisition_sequence.py b/opticstream/utils/acquisition_sequence.py index 80a653c..3c63f59 100644 --- a/opticstream/utils/acquisition_sequence.py +++ b/opticstream/utils/acquisition_sequence.py @@ -44,13 +44,12 @@ def __init__(self, scan_config, start_slice: int = 1, start_mosaic: int = 1) -> ) self.start_slice = start_slice self.start_mosaic = start_mosaic - rows = scan_config.acquisition.grid_size_y self.sizes = {} for slot in range(1, self.mosaics_per_slice + 1): context = mosaic_context_from_ids( slice_id=1, mosaic_id=slot, mosaics_per_slice=self.mosaics_per_slice ) - self.sizes[slot] = context.grid_size_x(scan_config) * rows + self.sizes[slot] = context.grid_size_x(scan_config) * context.grid_size_y(scan_config) self.slice_total = sum(self.sizes.values()) def locate(self, image: int) -> SequencePosition: diff --git a/tests/test_acquisition_previews.py b/tests/test_acquisition_previews.py index 66a2470..135981c 100644 --- a/tests/test_acquisition_previews.py +++ b/tests/test_acquisition_previews.py @@ -79,6 +79,34 @@ def layout(self, files, mode, order, columns=3): return {t["tile_number"] - 1: (t["x"], t["y"], t["filepath"]) for t in yaml.safe_load(out.read_text())["tiles"]} + def test_tilted_mosaic_uses_grid_size_y_tilted(self): + self.cfg.acquisition.grid_size_y_tilted = 3 + tilted = OCTMosaicId(project_name="test", slice_id=1, mosaic_id=2) + self.assertEqual(list(preview.expected_tiles(self.cfg, tilted, self.root, "t", 2)["aip"]), + [3, 4, 5]) + self.assertEqual(len(preview.expected_tiles(self.cfg, tilted, self.root, "t")["aip"]), 9) + # Normal mosaics keep grid_size_y. + self.assertEqual(list(preview.expected_tiles(self.cfg, self.ident, self.root, "n", 2)["aip"]), + [2, 3]) + self.create_tiles(9) + def stitch(cfg, files, modality, output, batch_id, per_strip=None): + output.parent.mkdir(parents=True, exist_ok=True) + output.write_bytes(b"nifti") + output.with_suffix(".jpg").write_bytes(b"jpeg") + with patch.object(preview, "stitch_preview_modality", side_effect=stitch) as stitched, \ + patch.object(preview, "slack_notifications_enabled", return_value=False): + preview.run_preview(self.cfg, tilted, self.root, "t") + self.assertEqual({c.kwargs["per_strip"] for c in stitched.call_args_list}, {3}) + # 3 strips of 3 tiles: tile 4 starts the second strip. + files = {i: Path(f"/data/image_{i + 1}.nii") for i in range(9)} + with TemporaryDirectory() as scratch: + import yaml + out = preview.tile_config(self.cfg, files, (10, 20), 0, Path(scratch) / "t.yaml", 3) + xs = {t["tile_number"]: t["x"] for t in yaml.safe_load(out.read_text())["tiles"]} + self.assertEqual(len(set(xs.values())), 3) + self.assertEqual(xs[1], xs[3]) + self.assertNotEqual(xs[3], xs[4]) + def test_tile_config_uses_linc_convert_grid(self): from linc_convert.modalities.psoct import generate_tile_config as grids generators = { @@ -144,7 +172,7 @@ def test_tilted_grid_and_duplicate_patterns(self): @patch.object(preview, "slack_notifications_enabled", return_value=False) def test_checkpoint_resume_then_slack(self, slack): self.create_tiles() - def stitch(cfg, files, modality, output, batch_id): + def stitch(cfg, files, modality, output, batch_id, per_strip=None): output.parent.mkdir(parents=True, exist_ok=True) output.write_bytes(b"nifti") output.with_suffix(".jpg").write_bytes(b"jpeg") @@ -171,7 +199,7 @@ def test_disabled_flow_no_io(self): @patch.object(preview, "slack_notifications_enabled", return_value=True) def test_failed_upload_retries_only_missing_modalities(self, slack): self.create_tiles() - def stitch(cfg, files, modality, output, batch_id): + def stitch(cfg, files, modality, output, batch_id, per_strip=None): output.parent.mkdir(parents=True, exist_ok=True) output.write_bytes(b"nifti") output.with_suffix(".jpg").write_bytes(b"jpeg") @@ -188,7 +216,7 @@ def stitch(cfg, files, modality, output, batch_id): @patch.object(preview, "slack_notifications_enabled", return_value=False) def test_outputs_in_slice_folder_named_by_mosaic(self, slack): self.create_tiles() - def stitch(cfg, files, modality, output, batch_id): + def stitch(cfg, files, modality, output, batch_id, per_strip=None): output.parent.mkdir(parents=True, exist_ok=True) output.write_bytes(b"nifti") output.with_suffix(".jpg").write_bytes(b"jpeg") diff --git a/tests/test_acquisition_sequence.py b/tests/test_acquisition_sequence.py index d8765ed..0e95b28 100644 --- a/tests/test_acquisition_sequence.py +++ b/tests/test_acquisition_sequence.py @@ -13,12 +13,14 @@ BIG = 100 * 1024 # the watcher ignores files smaller than 100 KB -def config(root="/tmp", normal=3, tilted=2, rows=2, pattern="spectral_{image}.nii"): +def config(root="/tmp", normal=3, tilted=2, rows=2, pattern="spectral_{image}.nii", + rows_tilted=None): return SimpleNamespace( project_base_path=Path(root) / "out", mosaics_per_slice=2, acquisition=PSOCTAcquisitionParams( grid_size_x_normal=normal, grid_size_x_tilted=tilted, grid_size_y=rows, + grid_size_y_tilted=rows_tilted, tile_overlap=0, filename_pattern=pattern, acquisition_mosaic_map={"normal0deg": 1, "tilted15deg": 2}), enface_preview=EnfacePreviewConfig(batch_enabled=True, grid_config={"grid_type": "column-by-column", "order": "down-right"}, **{ @@ -45,6 +47,12 @@ def test_sizes_follow_each_mosaic_grid(self): self.assertEqual(where(705), (2, 1, 1)) self.assertEqual(where(1409), (3, 1, 1)) + def test_tilted_tiles_per_batch(self): + # 22 strips of 18 (normal) and 25 (tilted) tiles, as in sub-260928. + seq = AcquisitionSequence(config(normal=22, tilted=22, rows=18, rows_tilted=25)) + self.assertEqual(seq.sizes, {1: 396, 2: 550}) + self.assertEqual(seq.first_image(2, 1), 947) + def test_unequal_grids_and_start_position(self): seq = AcquisitionSequence(config(normal=3, tilted=2, rows=2), start_slice=5, start_mosaic=2) self.assertEqual(seq.sizes, {1: 6, 2: 4}) @@ -92,6 +100,15 @@ def test_start_mosaic_two_of_slice_three(self): # slice 3 tilted = mosaic 6 (4 tiles), then slice 4 normal = mosaic 7. self.assertEqual([(m, b) for m, b, _ in found], [(6, 1), (6, 2), (7, 1)]) + def test_tilted_batches_use_grid_size_y_tilted(self): + cfg = config(normal=2, tilted=2, rows=2, rows_tilted=3) # mosaic 1: 4 tiles, mosaic 2: 6 + with TemporaryDirectory() as folder: + write(folder, [f"spectral_{i:04d}.nii" for i in range(1, 11)]) + found = self.batches(self.watcher(folder, cfg, sequence=AcquisitionSequence(cfg))) + self.assertEqual([(m, b, len(files)) for m, b, files in found], + [(1, 1, 2), (1, 2, 2), (2, 1, 3), (2, 2, 3)]) + self.assertEqual(found[3][2], ("spectral_0008.nii", "spectral_0009.nii", "spectral_0010.nii")) + def test_fixed_mosaic_ignores_batches_beyond_grid(self): cfg = config(normal=3, tilted=2, rows=2) with TemporaryDirectory() as folder: From ac1013677a8a9cf264eb0ad6070f507ad9246150 Mon Sep 17 00:00:00 2001 From: NoahMarkowitz Date: Wed, 30 Sep 2026 15:02:04 -0400 Subject: [PATCH 31/65] archiving done without matlab needed --- docker-compose.yaml | 3 +- opticstream.egg-info/PKG-INFO | 3 +- opticstream.egg-info/SOURCES.txt | 38 +- opticstream.egg-info/requires.txt | 3 +- opticstream/cli/oct/serve.py | 11 + opticstream/cli/oct/watch.py | 13 + opticstream/events/__init__.py | 1 + opticstream/events/psoct_events.py | 1 + .../flows/psoct/acquisition_preview_flow.py | 2 +- .../flows/psoct/tile_batch_archive_flow.py | 116 +++- .../flows/psoct/tile_batch_process_flow.py | 27 +- .../flows/psoct/tile_batch_upload_flow.py | 51 +- opticstream/state/oct_project_state.py | 9 + pyproject.toml | 9 +- tests/test_complex_outputs.py | 40 ++ tests/test_matlab_settings.py | 4 +- uv.lock | 611 +++++++++++++++++- 17 files changed, 878 insertions(+), 64 deletions(-) diff --git a/docker-compose.yaml b/docker-compose.yaml index 175d93c..619876a 100644 --- a/docker-compose.yaml +++ b/docker-compose.yaml @@ -13,7 +13,8 @@ services: - ./db:/var/lib/postgresql profiles: ["server"] ports: - - "127.0.0.1:1542:5432" + - "1542:5432" + #- "127.0.0.1:1542:5432" ### MinIO for flow storage minio: diff --git a/opticstream.egg-info/PKG-INFO b/opticstream.egg-info/PKG-INFO index fe87753..b578e3d 100644 --- a/opticstream.egg-info/PKG-INFO +++ b/opticstream.egg-info/PKG-INFO @@ -5,11 +5,12 @@ Summary: Add your description here Requires-Python: >=3.11 Description-Content-Type: text/markdown Requires-Dist: cyclopts>=3.3.0 -Requires-Dist: linc-convert[all] @ git+https://github.com/lincbrain/linc-convert.git@dc8f3243df01d09493a13e53305adede08784695 +Requires-Dist: linc-convert[all] @ git+https://github.com/nmarkowitz/linc-convert.git@e00f6f31cd8bac5e2fa34b212d2d77817bfb6f81 Requires-Dist: nifti-zarr @ git+https://github.com/calvinchai/nifti-zarr-py.git@12336420beaa023cbdd9d9e5c24e3c115687fe9a Requires-Dist: psoct-toolbox @ git+https://github.com/calvinchai/psoct-toolbox.git@5182337044d2b7f8337ca205a33c9da3ddd69bda Requires-Dist: matplotlib>=3.10.8 Requires-Dist: prefect[shell,slack,sqlalchemy]>=3.6.20 +Requires-Dist: dandi>=0.78.0 Requires-Dist: watchdog Requires-Dist: psutil Requires-Dist: slack-sdk diff --git a/opticstream.egg-info/SOURCES.txt b/opticstream.egg-info/SOURCES.txt index b9b54cf..b390386 100644 --- a/opticstream.egg-info/SOURCES.txt +++ b/opticstream.egg-info/SOURCES.txt @@ -32,6 +32,7 @@ opticstream/cli/oct/serve.py opticstream/cli/oct/setup.py opticstream/cli/oct/state.py opticstream/cli/oct/watch.py +opticstream/cli/oct/watch_enface.py opticstream/cli/utils/__init__.py opticstream/cli/utils/clear.py opticstream/cli/utils/cli.py @@ -42,7 +43,9 @@ opticstream/cli/utils/inspect_deps.py opticstream/cli/utils/repull_deps.py opticstream/config/__init__.py opticstream/config/constants.py +opticstream/config/enface_preview.py opticstream/config/lsm_scan_config.py +opticstream/config/migrate_psoct_blocks.py opticstream/config/pipeline_opts_builder.py opticstream/config/psoct_scan_config.py opticstream/config/utils.py @@ -79,6 +82,7 @@ opticstream/flows/lsm/strip_process_flow.py opticstream/flows/lsm/strip_upload_flow.py opticstream/flows/lsm/utils.py opticstream/flows/psoct/__init__.py +opticstream/flows/psoct/acquisition_preview_flow.py opticstream/flows/psoct/mosaic_coordinate_flow.py opticstream/flows/psoct/mosaic_enface_qc_flow.py opticstream/flows/psoct/mosaic_process_flow.py @@ -98,6 +102,19 @@ opticstream/hooks/check_mosaic_ready_hook.py opticstream/hooks/check_slice_ready_hook.py opticstream/hooks/publish_hooks.py opticstream/hooks/slack_notification_hook.py +opticstream/matlab/README.md +opticstream/matlab/angle2tensor.m +opticstream/matlab/opticstream_interpolationwave.m +opticstream/matlab/opticstream_read_dispersion.m +opticstream/matlab/tensor2angle.m +opticstream/matlab/+psoct/+file/complex2processed_batch_indexed.m +opticstream/matlab/+psoct/+file/spectral2processed_batch_indexed.m +opticstream/matlab/+psoct/+file/+internal/applyComplexOutputPolicy.m +opticstream/matlab/+psoct/+file/+internal/applyVolumeOutputPolicy.m +opticstream/matlab/+psoct/+internal/+opts/normalizeSpectralOpts.m +opticstream/matlab/+psoct/+spectral/loadPhaseCalibration.m +opticstream/matlab/+psoct/+spectral/loadSpectralCorrections.m +opticstream/matlab/+psoct/+spectral/spectral2complex.m opticstream/scripts/compare_hash_files.py opticstream/scripts/edit_tile_info_grid.py opticstream/scripts/filter_tiles_by_signal.py @@ -120,28 +137,47 @@ opticstream/tasks/archive_file.py opticstream/tasks/dandi_upload.py opticstream/tasks/slack_notification.py opticstream/utils/__init__.py +opticstream/utils/acquisition_sequence.py opticstream/utils/deployment_utils.py opticstream/utils/directory_watch.py opticstream/utils/filename_utils.py opticstream/utils/filesystem.py opticstream/utils/flow_run_name_parse.py opticstream/utils/matlab_execution.py +opticstream/utils/matlab_settings.py opticstream/utils/naming_convention.py +opticstream/utils/oct_input_naming.py opticstream/utils/path_conversion.py opticstream/utils/polling_watcher.py opticstream/utils/process_priority_thread.py opticstream/utils/refresh_disk.py opticstream/utils/runtime_paths.py +opticstream/utils/slack_settings.py +opticstream/utils/upload_settings.py +opticstream/utils/volume_settings.py opticstream/utils/zarr_validation.py +tests/test_acquisition_previews.py +tests/test_acquisition_sequence.py +tests/test_complex_outputs.py +tests/test_coords_drift_fallback.py tests/test_dandi_upload.py +tests/test_dispersion_channels.py tests/test_filename_utils_lsm.py tests/test_flow_run_name_parse.py tests/test_lsm_flow_helpers.py tests/test_lsm_project_state.py tests/test_lsm_strip_update_flow.py +tests/test_matlab_settings.py +tests/test_migrate_psoct_blocks.py +tests/test_oct_input_naming.py tests/test_oct_watch_mosaic3.py +tests/test_phase_calibration.py tests/test_pipeline_opts_builder.py tests/test_process_priority_thread.py tests/test_psoct_flow_utils.py tests/test_scoped_events.py -tests/test_state_guards.py \ No newline at end of file +tests/test_slack_settings.py +tests/test_state_guards.py +tests/test_upload_settings.py +tests/test_volume_output_setting.py +tests/test_watch_previews.py \ No newline at end of file diff --git a/opticstream.egg-info/requires.txt b/opticstream.egg-info/requires.txt index 62d83ef..f746fee 100644 --- a/opticstream.egg-info/requires.txt +++ b/opticstream.egg-info/requires.txt @@ -1,9 +1,10 @@ cyclopts>=3.3.0 -linc-convert[all] @ git+https://github.com/lincbrain/linc-convert.git@dc8f3243df01d09493a13e53305adede08784695 +linc-convert[all] @ git+https://github.com/nmarkowitz/linc-convert.git@e00f6f31cd8bac5e2fa34b212d2d77817bfb6f81 nifti-zarr @ git+https://github.com/calvinchai/nifti-zarr-py.git@12336420beaa023cbdd9d9e5c24e3c115687fe9a psoct-toolbox @ git+https://github.com/calvinchai/psoct-toolbox.git@5182337044d2b7f8337ca205a33c9da3ddd69bda matplotlib>=3.10.8 prefect[shell,slack,sqlalchemy]>=3.6.20 +dandi>=0.78.0 watchdog psutil slack-sdk diff --git a/opticstream/cli/oct/serve.py b/opticstream/cli/oct/serve.py index 9967874..4d23286 100644 --- a/opticstream/cli/oct/serve.py +++ b/opticstream/cli/oct/serve.py @@ -25,6 +25,9 @@ from opticstream.flows.psoct.slice_process_flow import ( to_deployment as slice_process_deployments, ) +from opticstream.flows.psoct.tile_batch_archive_flow import ( + to_deployment as tile_batch_archive_deployments, +) from opticstream.flows.psoct.tile_batch_process_flow import ( to_deployment as tile_batch_process_deployments, ) @@ -74,6 +77,14 @@ def build_deployments( concurrency_limit=concurrency_limit, ) ) + deployments.extend( + tile_batch_archive_deployments( + project_name=normalized_project_name, + deployment_name=deployment_name, + extra_tags=COMMON_TAGS, + concurrency_limit=concurrency_limit, + ) + ) deployments.extend( tile_batch_upload_deployments( project_name=normalized_project_name, diff --git a/opticstream/cli/oct/watch.py b/opticstream/cli/oct/watch.py index f3cd920..001c92a 100644 --- a/opticstream/cli/oct/watch.py +++ b/opticstream/cli/oct/watch.py @@ -16,6 +16,7 @@ ) from opticstream.events import BATCH_READY from opticstream.events.psoct_event_emitters import emit_batch_psoct_event +from opticstream.flows.psoct.tile_batch_archive_flow import archive_tile_batch_flow from opticstream.flows.psoct.tile_batch_process_flow import process_tile_batch from opticstream.flows.psoct.utils import oct_batch_ident from opticstream.flows.psoct.utils import ( @@ -661,6 +662,18 @@ def _process_direct(self, candidate: OCTBatchCandidate, batch_ident: Any) -> int len(candidate.files), ) + # Archive (and its upload event) must not depend on MATLAB processing, and + # an archive failure must not block processing. + try: + archive_tile_batch_flow( + batch_id=batch_ident, + config=self.scan_config, + file_list=list(candidate.files), + force_rerun=self.force_resend, + ) + except Exception: + logger.exception("Archive failed for %s; continuing with processing", batch_ident) + process_tile_batch( batch_id=batch_ident, config=self.scan_config, diff --git a/opticstream/events/__init__.py b/opticstream/events/__init__.py index 28a8a17..8437268 100644 --- a/opticstream/events/__init__.py +++ b/opticstream/events/__init__.py @@ -7,6 +7,7 @@ from opticstream.events.psoct_events import ( BATCH_ARCHIVED, + BATCH_COMPLEX_ARCHIVED, BATCH_PROCESSED, BATCH_READY, BATCH_UPLOADED, diff --git a/opticstream/events/psoct_events.py b/opticstream/events/psoct_events.py index 8444b77..a7f1f90 100644 --- a/opticstream/events/psoct_events.py +++ b/opticstream/events/psoct_events.py @@ -9,6 +9,7 @@ BATCH_COMPLEXED = "linc.opticstream.psoct.batch.complexed" # Batch complexed (triggers complex to processed flow) BATCH_PROCESSED = "linc.opticstream.psoct.batch.processed" # Batch processed (triggers state management, emits mosaic.ready when all batches done) BATCH_ARCHIVED = "linc.opticstream.psoct.batch.archived" # Batch archived and compressed (triggers upload flow, state management) +BATCH_COMPLEX_ARCHIVED = "linc.opticstream.psoct.batch.complex_archived" # MATLAB complex tiles archived (triggers complex upload flow) BATCH_UPLOADED = "linc.opticstream.psoct.batch.uploaded" # Batch uploaded to LINC storage (triggers upload completion handlers) # Mosaic-Level Events diff --git a/opticstream/flows/psoct/acquisition_preview_flow.py b/opticstream/flows/psoct/acquisition_preview_flow.py index 4c223a6..26f063e 100644 --- a/opticstream/flows/psoct/acquisition_preview_flow.py +++ b/opticstream/flows/psoct/acquisition_preview_flow.py @@ -269,7 +269,7 @@ def stitch_preview_modality(config: PSOCTScanConfigModel, files: dict[int, Path] per_strip) mosaic2d(tile_info_file=str(spec), nifti_output=str(output), jpeg_output=None if modality == "ori" else str(jpeg), - print_grid=str(output.with_name(f"{output.stem}_grid.jpg")), + #print_grid=str(output.with_name(f"{output.stem}_grid.jpg")), tile_overlap=overlap if overlap else 0, circular_mean=modality == "ori", voxel_size_xyz=list(config.acquisition.scan_resolution_3d[:2])) if not output.is_file(): diff --git a/opticstream/flows/psoct/tile_batch_archive_flow.py b/opticstream/flows/psoct/tile_batch_archive_flow.py index a7d2f66..294377b 100644 --- a/opticstream/flows/psoct/tile_batch_archive_flow.py +++ b/opticstream/flows/psoct/tile_batch_archive_flow.py @@ -1,18 +1,31 @@ import os from pathlib import Path +from typing import Any, Dict, Optional, Sequence from prefect import flow, get_run_logger, task +from opticstream.config.psoct_scan_config import PSOCTScanConfigModel from opticstream.hooks.publish_hooks import ( publish_oct_mosaic_hook, publish_oct_project_hook, ) +from opticstream.events import BATCH_READY, get_event_trigger from opticstream.events.psoct_event_emitters import emit_batch_psoct_event -from opticstream.events.psoct_events import BATCH_ARCHIVED -from opticstream.flows.psoct.tile_file_reference import TileFileReference -from opticstream.flows.psoct.utils import processed_output_prefix +from opticstream.events.psoct_events import BATCH_ARCHIVED, BATCH_COMPLEX_ARCHIVED +from opticstream.flows.psoct.tile_file_reference import ( + TileFileReference, + build_tile_file_reference_list, +) +from opticstream.flows.psoct.utils import ( + batch_ident_from_payload, + load_scan_config_for_payload, + mosaic_context_from_ids, + path_list_from_payload, + processed_output_prefix, +) from opticstream.state.milestone_wrappers_psoct import oct_batch_processing_milestone from opticstream.state.oct_project_state import OCT_STATE_SERVICE, OCTBatchId +from opticstream.state.state_guards import force_rerun_from_payload from opticstream.tasks.archive_file import archive_file from opticstream.hooks.slack_notification_hook import slack_notification_hook @@ -30,13 +43,8 @@ def archive_tile_batch( archive_path: Path, archive_tile_name_format: str, force_rerun: bool = False, - emit_event: bool = True, ) -> list[str]: - """Archive the batch's raw tiles; returns the archived paths. - - ``emit_event=False`` leaves BATCH_ARCHIVED to the caller, e.g. to add the - batch's complex tiles to the same upload. - """ + """Archive the batch's raw tiles, emit BATCH_ARCHIVED; returns the archived paths.""" logger = get_run_logger() archive_path.mkdir(parents=True, exist_ok=True) with OCT_STATE_SERVICE.open_batch(batch_ident=batch_id) as batch: @@ -73,12 +81,11 @@ def archive_tile_batch( f"{len(files_with_issue)} file(s): " + " | ".join(files_with_issue) ) - if emit_event: - emit_batch_psoct_event( - BATCH_ARCHIVED, - batch_id, - extra_payload={"file_list": archived_file_paths}, - ) + emit_batch_psoct_event( + BATCH_ARCHIVED, + batch_id, + extra_payload={"file_list": archived_file_paths}, + ) return archived_file_paths @@ -96,8 +103,11 @@ def archive_complex_tiles( Each uncompressed ``_complex.nii`` is deleted once the whole batch's gzipped archive copies are validated; the archive copies are never deleted. + The caller emits BATCH_COMPLEX_ARCHIVED (see ``emit_batch_complex_archived``). """ logger = get_run_logger() + with OCT_STATE_SERVICE.open_batch(batch_ident=batch_id) as batch: + batch.reset_complex_uploaded() local_paths = [] futures = [] for ref in file_reference_list: @@ -125,8 +135,10 @@ def archive_complex_tiles( return archived -def emit_batch_archived(batch_id: OCTBatchId, file_list: list[str]) -> None: - emit_batch_psoct_event(BATCH_ARCHIVED, batch_id, extra_payload={"file_list": file_list}) +def emit_batch_complex_archived(batch_id: OCTBatchId, file_list: list[str]) -> None: + emit_batch_psoct_event( + BATCH_COMPLEX_ARCHIVED, batch_id, extra_payload={"file_list": file_list} + ) def check_archive_result( @@ -164,18 +176,72 @@ def check_archive_result( ) def archive_tile_batch_flow( batch_id: OCTBatchId, - file_reference_list: list[TileFileReference], + config: PSOCTScanConfigModel, + file_list: list[Path], *, - acquisition_label: str, - archive_path: Path, - archive_tile_name_format: str, force_rerun: bool = False, ) -> None: + """Archive a batch's raw tiles, independent of (and concurrent with) MATLAB processing. + + Runs regardless of ``matlab_processing_enabled``; a no-op when ``archive_path`` + is unset. BATCH_ARCHIVED then triggers the DANDI upload. + """ + if not config.archive_path: + get_run_logger().info("archive_path not configured; skipping archive of %s", batch_id) + return + mosaic_context = mosaic_context_from_ids( + slice_id=batch_id.slice_id, + mosaic_id=batch_id.mosaic_id, + mosaics_per_slice=config.mosaics_per_slice, + ) + file_reference_list = build_tile_file_reference_list( + file_list, + config=config, + mosaic_context=mosaic_context, + ) archive_tile_batch( batch_id=batch_id, - file_reference_list=file_reference_list, - acquisition_label=acquisition_label, - archive_path=archive_path, - archive_tile_name_format=archive_tile_name_format, + file_reference_list=list(file_reference_list.values()), + acquisition_label=mosaic_context.acquisition_label, + archive_path=config.archive_path, + archive_tile_name_format=config.archive_tile_name_format, force_rerun=force_rerun, ) + + +@flow +def archive_tile_batch_event_flow(payload: Dict[str, Any]) -> None: + """Event-driven wrapper for ``archive_tile_batch_flow``, triggered by BATCH_READY.""" + archive_tile_batch_flow( + batch_id=batch_ident_from_payload(payload), + config=load_scan_config_for_payload(payload), + file_list=path_list_from_payload(payload), + force_rerun=force_rerun_from_payload(payload), + ) + + +def to_deployment( + *, + project_name: Optional[str] = None, + deployment_name: str = "local", + extra_tags: Sequence[str] = (), + concurrency_limit: int = 1, +): + """ + Create both deployments: + - manual `archive_tile_batch_flow` (ad-hoc reruns) + - event-driven `archive_tile_batch_event_flow` (triggered by BATCH_READY, + alongside but independent of `process_tile_batch_event_flow`) + """ + manual = archive_tile_batch_flow.to_deployment( + name=deployment_name, + tags=["tile-batch", "archive-tile-batch", *list(extra_tags)], + concurrency_limit=concurrency_limit, + ) + event = archive_tile_batch_event_flow.to_deployment( + name=deployment_name, + tags=["event-driven", "tile-batch", "archive-tile-batch", *list(extra_tags)], + triggers=[get_event_trigger(BATCH_READY, project_name=project_name)], + concurrency_limit=concurrency_limit, + ) + return [manual, event] diff --git a/opticstream/flows/psoct/tile_batch_process_flow.py b/opticstream/flows/psoct/tile_batch_process_flow.py index e4c4607..8d48b6b 100644 --- a/opticstream/flows/psoct/tile_batch_process_flow.py +++ b/opticstream/flows/psoct/tile_batch_process_flow.py @@ -14,8 +14,7 @@ from opticstream.events import BATCH_PROCESSED, BATCH_READY, get_event_trigger from opticstream.flows.psoct.tile_batch_archive_flow import ( archive_complex_tiles, - archive_tile_batch, - emit_batch_archived, + emit_batch_complex_archived, ) from opticstream.flows.psoct.tile_batch_processed_validation import ( validate_processed_batch_outputs, @@ -266,21 +265,10 @@ def process_tile_batch( mode = _determine_processing_mode( tile_saving_type=config.acquisition.tile_saving_type, ) - # Complex tiles join the raw tiles in one BATCH_ARCHIVED event (one DANDI upload). + # Raw tiles are archived by the separate archive_tile_batch_flow (also on + # BATCH_READY). Complex tiles are MATLAB output, so they are archived here and + # uploaded on their own BATCH_COMPLEX_ARCHIVED event. complex_dir = complex_output_dir_for_batch(config, mode, batch_id.slice_id) - save_complex = complex_dir is not None - - archive_future = None - if config.archive_path: - archive_future = archive_tile_batch.submit( - batch_id=batch_id, - file_reference_list=file_reference_list, - acquisition_label=mosaic_context.acquisition_label, - archive_path=config.archive_path, - archive_tile_name_format=config.archive_tile_name_format, - force_rerun=force_rerun, - emit_event=not save_complex, - ) processed_path: Path | None = None if mode == "spectral": @@ -307,8 +295,7 @@ def process_tile_batch( ) - if archive_future and save_complex: - raw_archived = archive_future.result() + if complex_dir is not None: complex_archived = archive_complex_tiles( batch_id=batch_id, file_reference_list=file_reference_list, @@ -317,9 +304,7 @@ def process_tile_batch( complex_tile_name_format=config.complex_tile_name_format, complex_dir=complex_dir, ) - emit_batch_archived(batch_id, raw_archived + complex_archived) - elif archive_future: - archive_future.wait() + emit_batch_complex_archived(batch_id, complex_archived) with OCT_STATE_SERVICE.open_batch(batch_ident=batch_id) as batch_state: batch_state.mark_completed() diff --git a/opticstream/flows/psoct/tile_batch_upload_flow.py b/opticstream/flows/psoct/tile_batch_upload_flow.py index 5a782a4..3316261 100644 --- a/opticstream/flows/psoct/tile_batch_upload_flow.py +++ b/opticstream/flows/psoct/tile_batch_upload_flow.py @@ -9,7 +9,12 @@ publish_oct_mosaic_hook, publish_oct_project_hook, ) -from opticstream.events import BATCH_ARCHIVED, BATCH_UPLOADED, get_event_trigger +from opticstream.events import ( + BATCH_ARCHIVED, + BATCH_COMPLEX_ARCHIVED, + BATCH_UPLOADED, + get_event_trigger, +) from opticstream.flows.psoct.utils import ( batch_ident_from_payload, load_scan_config_for_payload, @@ -39,6 +44,30 @@ def upload_to_dandi_tile_batch( dandi_api_key: Secret | None = None, force_rerun: bool = False, ) -> None: + _upload_files(batch_id, file_list, dandi_instance, realpath, dandi_api_key) + + +@flow( + flow_run_name="upload-complex-to-dandi-batch-{batch_id}", + on_completion=[publish_oct_mosaic_hook, publish_oct_project_hook], + on_failure=[slack_notification_hook], +) +@upload_flow_enabled +@oct_batch_processing_milestone(field_name="complex_uploaded") +def upload_complex_to_dandi_tile_batch( + batch_id: OCTBatchId, + file_list: list[Path], + *, + dandi_instance: str = "dandi", + realpath: bool = True, + dandi_api_key: Secret | None = None, + force_rerun: bool = False, +) -> None: + """Upload a batch's archived complex tiles (tracked apart from the raw-tile upload).""" + _upload_files(batch_id, file_list, dandi_instance, realpath, dandi_api_key) + + +def _upload_files(batch_id, file_list, dandi_instance, realpath, dandi_api_key) -> None: logger = get_run_logger() if not file_list: logger.warning("No files provided for %s", batch_id) @@ -64,6 +93,18 @@ def upload_to_dandi_batch_event_flow(payload: Dict[str, Any]) -> None: ) +@flow +def upload_complex_to_dandi_batch_event_flow(payload: Dict[str, Any]) -> None: + batch_ident = batch_ident_from_payload(payload) + cfg = load_scan_config_for_payload(payload) + return upload_complex_to_dandi_tile_batch( + batch_id=batch_ident, + file_list=path_list_from_payload(payload), + dandi_api_key=cfg.dandi_api_key, + force_rerun=force_rerun_from_payload(payload), + ) + + def to_deployment( *, project_name: Optional[str] = None, @@ -74,6 +115,7 @@ def to_deployment( Create both deployments: - manual `upload_to_dandi_tile_batch` (ad-hoc reruns) - event-driven DANDI upload (triggered by BATCH_ARCHIVED) + - event-driven complex-tile DANDI upload (triggered by BATCH_COMPLEX_ARCHIVED) """ manual = upload_to_dandi_tile_batch.to_deployment( name=deployment_name, @@ -84,4 +126,9 @@ def to_deployment( tags=["event-driven", "tile-batch", "upload-to-dandi", *list(extra_tags)], triggers=[get_event_trigger(BATCH_ARCHIVED, project_name=project_name)], ) - return [manual, event] + complex_event = upload_complex_to_dandi_batch_event_flow.to_deployment( + name=deployment_name, + tags=["event-driven", "tile-batch", "upload-to-dandi", "complex", *list(extra_tags)], + triggers=[get_event_trigger(BATCH_COMPLEX_ARCHIVED, project_name=project_name)], + ) + return [manual, event, complex_event] diff --git a/opticstream/state/oct_project_state.py b/opticstream/state/oct_project_state.py index f63bc49..979ca59 100644 --- a/opticstream/state/oct_project_state.py +++ b/opticstream/state/oct_project_state.py @@ -130,6 +130,7 @@ class OCTBatchStateView(OCTStateView): enface_processed: bool = False uploaded: bool = False archived: bool = False + complex_uploaded: bool = False class OCTBatchState( @@ -181,6 +182,14 @@ def reset_uploaded(self) -> None: self.uploaded = False self.touch() + def set_complex_uploaded(self, value: bool = True) -> None: + self.complex_uploaded = value + self.touch() + + def reset_complex_uploaded(self) -> None: + self.complex_uploaded = False + self.touch() + class OCTMosaicStateView(OCTStateView): """Readonly view for one OCT mosaic; batches are keyed by batch_id.""" diff --git a/pyproject.toml b/pyproject.toml index 8156f23..dce68bd 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -6,7 +6,7 @@ readme = "README.md" requires-python = ">=3.11" dependencies = [ "cyclopts>=3.3.0", - "linc-convert[all] @ git+https://github.com/nmarkowitz/linc-convert.git@050bd354e166b14fb5bca244e94107d559e0aa0a", + "linc-convert[all] @ git+https://github.com/nmarkowitz/linc-convert.git@e00f6f31cd8bac5e2fa34b212d2d77817bfb6f81", "nifti-zarr @ git+https://github.com/calvinchai/nifti-zarr-py.git@12336420beaa023cbdd9d9e5c24e3c115687fe9a", "psoct-toolbox @ git+https://github.com/calvinchai/psoct-toolbox.git@5182337044d2b7f8337ca205a33c9da3ddd69bda", "matplotlib>=3.10.8", @@ -39,6 +39,13 @@ dev = [ opticstream = "opticstream.cli:main" ops = "opticstream.cli:main" +[tool.uv] +# linc-convert requires nifti-zarr ^1.0.0rc7, but this untagged fork builds as +# "0+unknown". The fork is needed for niizarr.multizarr / ZarrConfig. +override-dependencies = [ + "nifti-zarr @ git+https://github.com/calvinchai/nifti-zarr-py.git@12336420beaa023cbdd9d9e5c24e3c115687fe9a", +] + [tool.uv.sources] #linc-convert = { path = "/space/megaera/1/users/kchai/linc-convert", editable = true } #nifti-zarr = { path = "/space/megaera/1/users/kchai/nifti-zarr", editable = true } diff --git a/tests/test_complex_outputs.py b/tests/test_complex_outputs.py index 4737e54..ec75abf 100644 --- a/tests/test_complex_outputs.py +++ b/tests/test_complex_outputs.py @@ -85,6 +85,7 @@ def submit(local, out): return SimpleNamespace(result=lambda: archive_flow.archive_file.fn(local, out)) with patch.object(archive_flow, "get_run_logger", return_value=Mock()), \ + patch.object(archive_flow, "OCT_STATE_SERVICE") as state, \ patch("opticstream.tasks.archive_file.get_run_logger", return_value=Mock()), \ patch.object(archive_flow.archive_file, "submit", side_effect=submit), \ patch.object(archive_flow, "check_archive_result", return_value=[]): @@ -102,6 +103,8 @@ def submit(local, out): self.assertEqual(f.read(), b"jones5") self.assertEqual(list(complex_dir.iterdir()), []) self.assertTrue(all(Path(p).is_file() for p in archived)) + # A re-archive makes the complex upload run again. + state.open_batch.return_value.__enter__.return_value.reset_complex_uploaded.assert_called_once() def test_failed_validation_keeps_uncompressed_copies(self): with TemporaryDirectory() as root: @@ -110,6 +113,7 @@ def test_failed_validation_keeps_uncompressed_copies(self): local.write_bytes(b"jones") batch = OCTBatchId(project_name="sub-T", slice_id=1, mosaic_id=1, batch_id=1) with patch.object(archive_flow, "get_run_logger", return_value=Mock()), \ + patch.object(archive_flow, "OCT_STATE_SERVICE"), \ patch.object(archive_flow.archive_file, "submit", return_value=SimpleNamespace(result=lambda: root / "a.nii.gz")), \ patch.object(archive_flow, "check_archive_result", return_value=["a.nii.gz (small)"]): @@ -124,6 +128,7 @@ def test_missing_complex_output_fails_before_archiving(self): with TemporaryDirectory() as root: batch = OCTBatchId(project_name="sub-T", slice_id=1, mosaic_id=1, batch_id=1) with patch.object(archive_flow, "get_run_logger", return_value=Mock()), \ + patch.object(archive_flow, "OCT_STATE_SERVICE"), \ patch.object(archive_flow.archive_file, "submit") as submit: with self.assertRaises(FileNotFoundError): archive_flow.archive_complex_tiles.fn( @@ -133,5 +138,40 @@ def test_missing_complex_output_fails_before_archiving(self): submit.assert_not_called() +class RawArchiveFlowTests(unittest.TestCase): + """Raw-tile archive runs as its own flow, independent of MATLAB processing.""" + + def run_flow(self, cfg): + batch = OCTBatchId(project_name="sub-T", slice_id=1, mosaic_id=1, batch_id=2) + refs = {1: SimpleNamespace(tile_number=1)} + with patch.object(archive_flow, "get_run_logger", return_value=Mock()), \ + patch.object(archive_flow, "build_tile_file_reference_list", + return_value=refs) as build, \ + patch.object(archive_flow, "archive_tile_batch") as archive: + archive_flow.archive_tile_batch_flow.fn( + batch_id=batch, config=cfg, file_list=[Path("a.nii")], force_rerun=True) + return batch, build, archive + + def test_archives_even_when_matlab_disabled(self): + with TemporaryDirectory() as root: + cfg = scan_config(root).model_copy(update={"matlab_processing_enabled": False}) + batch, _, archive = self.run_flow(cfg) + archive.assert_called_once() + kwargs = archive.call_args.kwargs + self.assertEqual(kwargs["batch_id"], batch) + self.assertEqual(kwargs["archive_path"], cfg.archive_path) + self.assertEqual(kwargs["acquisition_label"], "normal") + self.assertTrue(kwargs["force_rerun"]) + + def test_no_archive_path_is_a_no_op(self): + with TemporaryDirectory() as root: + _, build, archive = self.run_flow(scan_config(root, archive=False)) + build.assert_not_called() + archive.assert_not_called() + + def test_process_flow_no_longer_archives_raw_tiles(self): + self.assertFalse(hasattr(process_flow, "archive_tile_batch")) + + if __name__ == "__main__": unittest.main() diff --git a/tests/test_matlab_settings.py b/tests/test_matlab_settings.py index fc113fd..97cc640 100644 --- a/tests/test_matlab_settings.py +++ b/tests/test_matlab_settings.py @@ -33,7 +33,7 @@ def test_actual_tile_flow_skips_milestone_and_archive(self, load, logger): from opticstream.flows.psoct.tile_batch_process_flow import process_tile_batch with patch("opticstream.flows.psoct.tile_batch_process_flow.OCT_STATE_SERVICE") as state, \ - patch("opticstream.flows.psoct.tile_batch_process_flow.archive_tile_batch") as archive, \ + patch("opticstream.flows.psoct.tile_batch_process_flow.archive_complex_tiles") as archive, \ patch("opticstream.flows.psoct.tile_batch_process_flow.run_matlab_batch_command_or_cli") as matlab: result = process_tile_batch.fn( batch_id=None, config=SimpleNamespace(matlab_processing_enabled=False), @@ -41,7 +41,7 @@ def test_actual_tile_flow_skips_milestone_and_archive(self, load, logger): ) self.assertEqual(result.name, "MatlabDisabled") self.assertEqual(state.mock_calls, []) - archive.submit.assert_not_called() + archive.assert_not_called() matlab.assert_not_called() load.assert_not_called() diff --git a/uv.lock b/uv.lock index 67ff3cb..46d9696 100644 --- a/uv.lock +++ b/uv.lock @@ -16,6 +16,18 @@ resolution-markers = [ "python_full_version < '3.12' and sys_platform != 'emscripten' and sys_platform != 'win32'", ] +[manifest] +overrides = [{ name = "nifti-zarr", git = "https://github.com/calvinchai/nifti-zarr-py.git?rev=12336420beaa023cbdd9d9e5c24e3c115687fe9a" }] + +[[package]] +name = "acres" +version = "0.5.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/ec/ba/94b63a9af588fbf7bde25ce44d55456199654a92fb7b2337767198a824b0/acres-0.5.0.tar.gz", hash = "sha256:128b6447bf5df3b6210264feccbfa018b4ac5bd337358319aec6563f99db8f3a", size = 57750, upload-time = "2025-06-04T12:40:30.329Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/39/e8/806475fe4cdfd8635535d3fa11bd61d19b7cc94b61b9147ebdd2ab4cbbee/acres-0.5.0-py3-none-any.whl", hash = "sha256:fcc32b974b510897de0f041609b4234f9ff03e2e960aea088f63973fb106c772", size = 12703, upload-time = "2025-06-04T12:40:28.745Z" }, +] + [[package]] name = "aiohappyeyeballs" version = "2.6.1" @@ -221,6 +233,19 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/fb/6b/cfa80a13437896eb8f4504ddac6dfa4ef7f1d2b2261057aa4a30003b8de6/apprise-1.9.7-py3-none-any.whl", hash = "sha256:c7640a81a1097685de66e0508e3da89f49235d566cb44bbead1dd98419bf5ee3", size = 1459879, upload-time = "2026-01-20T18:51:30.766Z" }, ] +[[package]] +name = "arrow" +version = "1.4.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "python-dateutil" }, + { name = "tzdata" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/b9/33/032cdc44182491aa708d06a68b62434140d8c50820a087fac7af37703357/arrow-1.4.0.tar.gz", hash = "sha256:ed0cc050e98001b8779e84d461b0098c4ac597e88704a655582b21d116e526d7", size = 152931, upload-time = "2025-10-18T17:46:46.761Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ed/c9/d7977eaacb9df673210491da99e6a247e93df98c715fc43fd136ce1d3d33/arrow-1.4.0-py3-none-any.whl", hash = "sha256:749f0769958ebdc79c173ff0b0670d59051a535fa26e8eba02953dc19eb43205", size = 68797, upload-time = "2025-10-18T17:46:45.663Z" }, +] + [[package]] name = "asgi-lifespan" version = "2.1.0" @@ -308,6 +333,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/77/f5/21d2de20e8b8b0408f0681956ca2c69f1320a3848ac50e6e7f39c6159675/babel-2.18.0-py3-none-any.whl", hash = "sha256:e2b422b277c2b9a9630c1d7903c2a00d0830c409c59ac8cae9081c92f1aeba35", size = 10196845, upload-time = "2026-02-01T12:30:53.445Z" }, ] +[[package]] +name = "backports-tarfile" +version = "1.2.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/86/72/cd9b395f25e290e633655a100af28cb253e4393396264a98bd5f5951d50f/backports_tarfile-1.2.0.tar.gz", hash = "sha256:d75e02c268746e1b8144c278978b6e98e85de6ad16f8e4b0844a154557eca991", size = 86406, upload-time = "2024-05-28T17:01:54.731Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b9/fa/123043af240e49752f1c4bd24da5053b6bd00cad78c2be53c0d1e8b975bc/backports.tarfile-1.2.0-py3-none-any.whl", hash = "sha256:77e284d754527b01fb1e6fa8a1afe577858ebe4e9dad8919e34c862cb399bc34", size = 30181, upload-time = "2024-05-28T17:01:53.112Z" }, +] + [[package]] name = "backrefs" version = "6.2" @@ -331,6 +365,45 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/71/cc/18245721fa7747065ab478316c7fea7c74777d07f37ae60db2e84f8172e8/beartype-0.22.9-py3-none-any.whl", hash = "sha256:d16c9bbc61ea14637596c5f6fbff2ee99cbe3573e46a716401734ef50c3060c2", size = 1333658, upload-time = "2025-12-13T06:50:28.266Z" }, ] +[[package]] +name = "bids-validator-deno" +version = "3.0.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "deno" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/51/a9/99478a37eac0b8a55f5608b193301adb5754bcba7b097a2404b7d411fb3d/bids_validator_deno-3.0.2.tar.gz", hash = "sha256:a1580cfa6f3320eff3551cb5af10916f4962a9365e76d39b9155a75470c8a45b", size = 142592, upload-time = "2026-09-18T16:26:33.88Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/e2/2c/f93f3600283d4440d4a413f46bd4a5a8dbda5b3a137f4adff7c0ead34cf8/bids_validator_deno-3.0.2-py3-none-any.whl", hash = "sha256:2607e11f18c7da5d788771e474a9cf0c95ed044cb6c3824e57faf45a02eeb5cd", size = 4385643, upload-time = "2026-09-18T16:26:32.123Z" }, +] + +[[package]] +name = "bidsschematools" +version = "1.2.7" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "acres" }, + { name = "click" }, + { name = "pyyaml" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/86/b6/ebf4bc6993d8ebd8b15f823954e0b2c351a9ca7a80b318f3dd74ce42d705/bidsschematools-1.2.7.tar.gz", hash = "sha256:fc4bdbbb27ac44cd9a1a296ce76922079bb7b5e42f5d51b3f34e9396b4d77639", size = 1768778, upload-time = "2026-07-20T16:48:36.157Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/f9/25/c7c2500f91089061e7d7fdefa04b1a9e008d32c0fde8f799705eb3178024/bidsschematools-1.2.7-py3-none-any.whl", hash = "sha256:4bda6ff33f82259b9dd11acebcccbd3fa1d3eee80a578abf012d4c4e6301346e", size = 194216, upload-time = "2026-07-20T16:48:34.665Z" }, +] + +[[package]] +name = "blessed" +version = "1.50.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "jinxed", marker = "sys_platform != 'win32'" }, + { name = "wcwidth", marker = "sys_platform != 'win32'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/0c/7d/44d82d953d9bbcac57fe26507ea7ffba65ef1ec8f41f2b58da2fb12ef26c/blessed-1.50.0.tar.gz", hash = "sha256:046c9b2a5283a9c5bc340ed23b7d1c1f10ef2d7fb30b14bae13ef7ffc1f3ba56", size = 14062021, upload-time = "2026-09-14T18:47:20.833Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/93/79/dbf3888fa9ee5566f0acf5b87e5eeeae854b4ff8d819a564a1e73d1b5b82/blessed-1.50.0-py3-none-any.whl", hash = "sha256:6a693d524f7c21129dd61c4d10f11bda89911c05dc7df91219854c9ccf394cbf", size = 140656, upload-time = "2026-09-14T18:47:15.736Z" }, +] + [[package]] name = "cachetools" version = "7.0.1" @@ -492,6 +565,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/0a/4c/925909008ed5a988ccbb72dcc897407e5d6d3bd72410d69e051fc0c14647/charset_normalizer-3.4.4-py3-none-any.whl", hash = "sha256:7a32c560861a02ff789ad905a2fe94e3f840803362c84fecf1851cb4cf3dc37f", size = 53402, upload-time = "2025-10-14T04:42:31.76Z" }, ] +[[package]] +name = "ci-info" +version = "0.4.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/f1/05/7880d5714b2e1c4c2f2ccbd04b2e2bdcd3753d91d5e925b3a91af25970db/ci_info-0.4.0.tar.gz", hash = "sha256:34d5a18726b3780abdf985234b871ac33124d64dd8e294870b8cc5b410c18418", size = 6862, upload-time = "2026-02-02T14:25:47.313Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/12/d5/27742bf24dde737fe05e6fba615d9aa1bf95f4dda258a45cf97eb403366e/ci_info-0.4.0-py2.py3-none-any.whl", hash = "sha256:204e8ef60cb70270eefb2b3035fe6acc78a186dbbcb02f8f4f051cb20a6fbb8d", size = 6316, upload-time = "2026-02-02T14:25:46.235Z" }, +] + [[package]] name = "click" version = "8.3.1" @@ -504,6 +586,18 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/98/78/01c019cdb5d6498122777c1a43056ebb3ebfeef2076d9d026bfe15583b2b/click-8.3.1-py3-none-any.whl", hash = "sha256:981153a64e25f12d547d3426c367a4857371575ee7ad18df2a6183ab0545b2a6", size = 108274, upload-time = "2025-11-15T20:45:41.139Z" }, ] +[[package]] +name = "click-didyoumean" +version = "0.3.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "click" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/30/ce/217289b77c590ea1e7c24242d9ddd6e249e52c795ff10fac2c50062c48cb/click_didyoumean-0.3.1.tar.gz", hash = "sha256:4f82fdff0dbe64ef8ab2279bd6aa3f6a99c3b28c05aa09cbfc07c9d7fbb5a463", size = 3089, upload-time = "2024-03-24T08:22:07.499Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/1b/5b/974430b5ffdb7a4f1941d13d83c64a0395114503cc357c6b9ae4ce5047ed/click_didyoumean-0.3.1-py3-none-any.whl", hash = "sha256:5c4bb6007cfea5f2fd6583a2fb6701a22a41eb98957e63d0fac41c10e7c3117c", size = 3631, upload-time = "2024-03-24T08:22:06.356Z" }, +] + [[package]] name = "cloudpickle" version = "3.1.2" @@ -813,6 +907,66 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/f0/8b/2c95f0645c6f40211896375e6fa51f504b8ccb29c21f6ae661fe87ab044e/cyclopts-3.24.0-py3-none-any.whl", hash = "sha256:809d04cde9108617106091140c3964ee6fceb33cecdd537f7ffa360bde13ed71", size = 86154, upload-time = "2025-09-08T15:40:56.41Z" }, ] +[[package]] +name = "dandi" +version = "0.80.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "bids-validator-deno" }, + { name = "bidsschematools" }, + { name = "click" }, + { name = "click-didyoumean" }, + { name = "dandischema" }, + { name = "etelemetry" }, + { name = "fasteners" }, + { name = "fscacher" }, + { name = "hdmf" }, + { name = "humanize" }, + { name = "interleave" }, + { name = "joblib" }, + { name = "keyring" }, + { name = "keyrings-alt" }, + { name = "numcodecs" }, + { name = "nwbinspector" }, + { name = "packaging" }, + { name = "platformdirs" }, + { name = "pycryptodomex" }, + { name = "pydantic" }, + { name = "pynwb" }, + { name = "pyout" }, + { name = "python-dateutil" }, + { name = "requests" }, + { name = "ruamel-yaml" }, + { name = "semantic-version" }, + { name = "tenacity" }, + { name = "tensorstore" }, + { name = "urllib3" }, + { name = "yarl" }, + { name = "zarr" }, + { name = "zarr-checksum" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/06/0a/d509ee0c51f351a9ece0b101387e6319619356143b842cb056c673256572/dandi-0.80.1.tar.gz", hash = "sha256:84f1fe7f096bb1be74e1fca425d3bfdca3efbbcad946831b53745879a416ac8d", size = 430410, upload-time = "2026-09-26T00:35:03.925Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/c8/07/7d168f184cb728c8adf88857a4c77acb736acb31c631a3895ac84aada791/dandi-0.80.1-py3-none-any.whl", hash = "sha256:d5ce671fec9d044a80abd376ef9f2322f75562632f165fc5bfff9e7b77d082b7", size = 430731, upload-time = "2026-09-26T00:35:02.194Z" }, +] + +[[package]] +name = "dandischema" +version = "0.14.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "jsonschema", extra = ["format"] }, + { name = "packaging" }, + { name = "pydantic", extra = ["email"] }, + { name = "pydantic-settings" }, + { name = "requests" }, + { name = "zarr-checksum" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/d9/e6/55c462074cb9106b553c53bc83b66b98a487ee32e154acbbe34b98c1fd9a/dandischema-0.14.0.tar.gz", hash = "sha256:963af71311c356bce99c4e056754f3a2bd1a4f33836f13d9197c399c7732176f", size = 102428, upload-time = "2026-08-05T19:32:26.784Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/a8/b5/0f0828a19e023ccf5535b69d434611a7cfd17fed88bc1eca7c836339c908/dandischema-0.14.0-py3-none-any.whl", hash = "sha256:fce0c6c9df5b9504a230ba44d623656f4a798507f47fc3c9b0777cda016fbb73", size = 121953, upload-time = "2026-08-05T19:32:25.634Z" }, +] + [[package]] name = "dask" version = "2026.1.2" @@ -874,6 +1028,28 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/9a/c7/95349670e193b2891176e1b8e5f43e12b31bff6d9994f70e74ab385047f6/dateparser-1.3.0-py3-none-any.whl", hash = "sha256:8dc678b0a526e103379f02ae44337d424bd366aac727d3c6cf52ce1b01efbb5a", size = 318688, upload-time = "2026-02-04T16:00:04.652Z" }, ] +[[package]] +name = "deno" +version = "2.9.7" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/82/f1/0d7ca153f2363559d4462faed0d742632eedb74c9f7b8c05ee0d0bacdaaf/deno-2.9.7.tar.gz", hash = "sha256:79f4b7acdd9a37e98a4d1e0ca08d71c4e55f6c0cb13bd1e0946fa9b5497be2d9", size = 8168, upload-time = "2026-09-17T09:08:45.061Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/fd/fe/661ee70cc000917881432ab306317c75bb6f97631323a60b35e91808c400/deno-2.9.7-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:826634a6719f0183d85ef33f702de4388adb47d1f097b0732f70e033599a43c2", size = 42301208, upload-time = "2026-09-17T09:08:23.59Z" }, + { url = "https://files.pythonhosted.org/packages/0a/60/291756d3ac61ec70dd13ab3c542eb7eccf3b303d38bd5bad77c2f570c4d5/deno-2.9.7-py3-none-macosx_11_0_arm64.whl", hash = "sha256:adc015b5630572c06d04d28741e6ac9eed8b053c501d0ae776bfb155f5b7204b", size = 38475190, upload-time = "2026-09-17T09:08:28.269Z" }, + { url = "https://files.pythonhosted.org/packages/5c/58/ed29b6599ebe73e61d612b62fed303d359601d7357b1cb7847bab974c5dd/deno-2.9.7-py3-none-manylinux_2_27_aarch64.whl", hash = "sha256:d8f4622774a5bed3a6b6305340495abe699f09c99b70d2882f52abc1ff23321a", size = 39827935, upload-time = "2026-09-17T09:08:32.907Z" }, + { url = "https://files.pythonhosted.org/packages/97/83/7168eaf88abd94777a62cf8fed9a849a2bd1adf9118d3b470b0b4ff5f08d/deno-2.9.7-py3-none-manylinux_2_27_x86_64.whl", hash = "sha256:836f2ab5918723b47b638a05bc4fdac99fc35e69b49a6771c24e32b19dff5d8a", size = 41608137, upload-time = "2026-09-17T09:08:37.461Z" }, + { url = "https://files.pythonhosted.org/packages/8d/90/87d4b92f3076832aae7aa06b0a4be95ceb29867d45e6f8e8ca7cde6abc16/deno-2.9.7-py3-none-win_amd64.whl", hash = "sha256:80b90a0aad3f167ffbfefe55830b7b14e9d49865eed741c013bb48f1c5996681", size = 41552994, upload-time = "2026-09-17T09:08:42.592Z" }, +] + +[[package]] +name = "dnspython" +version = "2.8.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/8c/8b/57666417c0f90f08bcafa776861060426765fdb422eb10212086fb811d26/dnspython-2.8.0.tar.gz", hash = "sha256:181d3c6996452cb1189c4046c61599b84a5a86e099562ffde77d26984ff26d0f", size = 368251, upload-time = "2025-09-07T18:58:00.022Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ba/5a/18ad964b0086c6e62e2e7500f7edc89e3faa45033c71c1893d34eed2b2de/dnspython-2.8.0-py3-none-any.whl", hash = "sha256:01d9bbc4a2d76bf0db7c1f729812ded6d912bd318d3b1cf81d30c0f845dbf3af", size = 331094, upload-time = "2025-09-07T18:57:58.071Z" }, +] + [[package]] name = "docker" version = "7.1.0" @@ -918,6 +1094,32 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/0c/d5/c5db1ea3394c6e1732fb3286b3bd878b59507a8f77d32a2cebda7d7b7cd4/donfig-0.8.1.post1-py3-none-any.whl", hash = "sha256:2a3175ce74a06109ff9307d90a230f81215cbac9a751f4d1c6194644b8204f9d", size = 21592, upload-time = "2024-05-23T14:13:55.283Z" }, ] +[[package]] +name = "email-validator" +version = "2.3.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "dnspython" }, + { name = "idna" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/f5/22/900cb125c76b7aaa450ce02fd727f452243f2e91a61af068b40adba60ea9/email_validator-2.3.0.tar.gz", hash = "sha256:9fc05c37f2f6cf439ff414f8fc46d917929974a82244c20eb10231ba60c54426", size = 51238, upload-time = "2025-08-26T13:09:06.831Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/de/15/545e2b6cf2e3be84bc1ed85613edd75b8aea69807a71c26f4ca6a9258e82/email_validator-2.3.0-py3-none-any.whl", hash = "sha256:80f13f623413e6b197ae73bb10bf4eb0908faf509ad8362c5edeb0be7fd450b4", size = 35604, upload-time = "2025-08-26T13:09:05.858Z" }, +] + +[[package]] +name = "etelemetry" +version = "0.3.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "ci-info" }, + { name = "packaging" }, + { name = "requests" }, +] +wheels = [ + { url = "https://files.pythonhosted.org/packages/83/27/f997c9da0e179986fadd6c8474d16743f1b3697c129c2fcd1e739cd038c2/etelemetry-0.3.1-py3-none-any.whl", hash = "sha256:a64f09bcd55cbfa5684e4d9fb6d1d6a018ab99d2ea28e638435c4c26e6814a6b", size = 6416, upload-time = "2023-10-13T15:13:16.067Z" }, +] + [[package]] name = "exceptiongroup" version = "1.3.1" @@ -964,6 +1166,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/d2/c9/a175a7779f3599dfa4adfc97a6ce0e157237b3d7941538604aadaf97bfb6/fastapi-0.133.1-py3-none-any.whl", hash = "sha256:658f34ba334605b1617a65adf2ea6461901bdb9af3a3080d63ff791ecf7dc2e2", size = 109029, upload-time = "2026-02-25T18:18:18.578Z" }, ] +[[package]] +name = "fasteners" +version = "0.20" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/2d/18/7881a99ba5244bfc82f06017316ffe93217dbbbcfa52b887caa1d4f2a6d3/fasteners-0.20.tar.gz", hash = "sha256:55dce8792a41b56f727ba6e123fcaee77fd87e638a6863cec00007bfea84c8d8", size = 25087, upload-time = "2025-08-11T10:19:37.785Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/51/ac/e5d886f892666d2d1e5cb8c1a41146e1d79ae8896477b1153a21711d3b44/fasteners-0.20-py3-none-any.whl", hash = "sha256:9422c40d1e350e4259f509fb2e608d6bc43c0136f79a00db1b49046029d0b3b7", size = 18702, upload-time = "2025-08-11T10:19:35.716Z" }, +] + [[package]] name = "fonttools" version = "4.61.1" @@ -1013,6 +1224,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/c7/4e/ce75a57ff3aebf6fc1f4e9d508b8e5810618a33d900ad6c19eb30b290b97/fonttools-4.61.1-py3-none-any.whl", hash = "sha256:17d2bf5d541add43822bcf0c43d7d847b160c9bb01d15d5007d84e2217aaa371", size = 1148996, upload-time = "2025-12-12T17:31:21.03Z" }, ] +[[package]] +name = "fqdn" +version = "1.6.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/02/01/248d44fbda9e78fa1a7b5a475194bef4c4a3e285db286419f3bb42f2efdf/fqdn-1.6.0.tar.gz", hash = "sha256:e39bf62e2a9481aa2cb780554fdfd944dd8ee5f230eb831684d539cbafed8de2", size = 130737, upload-time = "2026-09-28T05:43:35.482Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/15/d5/a8f9149b97cced9e1f4bff92ff0b6206120e2c853ae774d7020d6ecd8fa8/fqdn-1.6.0-py3-none-any.whl", hash = "sha256:6c793c312ccfa29981e1135b3ef5e1277ebe639731a6b0f7350d90e96e63f0b4", size = 12569, upload-time = "2026-09-28T05:43:33.951Z" }, +] + [[package]] name = "frozenlist" version = "1.8.0" @@ -1118,6 +1338,19 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/9a/9a/e35b4a917281c0b8419d4207f4334c8e8c5dbf4f3f5f9ada73958d937dcc/frozenlist-1.8.0-py3-none-any.whl", hash = "sha256:0c18a16eab41e82c295618a77502e17b195883241c563b00f0aa5106fc4eaa0d", size = 13409, upload-time = "2025-10-06T05:38:16.721Z" }, ] +[[package]] +name = "fscacher" +version = "0.5.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "joblib" }, + { name = "platformdirs" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/57/ea/5a9be8cf5bfa19e9cab85993dd961c80f41f7ae169cf1f7f44656945c790/fscacher-0.5.0.tar.gz", hash = "sha256:414afda5a98bb4f84a1c8e159d0cee3db254139cd832eec2dd74fa5124e92d14", size = 43793, upload-time = "2026-09-29T23:44:00.815Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/00/fa/e316e47fb3b5003f14544aa7dfc3aaccc9c05bcffb22b58ac82e01b2aca0/fscacher-0.5.0-py3-none-any.whl", hash = "sha256:26ac128c7544895d46ccec0ba0d032069cd5b706d673448c75b1ce3cc1f046be", size = 18234, upload-time = "2026-09-29T23:43:59.754Z" }, +] + [[package]] name = "fsspec" version = "2026.2.0" @@ -1165,16 +1398,16 @@ wheels = [ [[package]] name = "glymur" -version = "0.14.7" +version = "0.14.8" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "lxml" }, { name = "numpy" }, { name = "pillow" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/b7/60/52840f84d75a3735b3a76e5acf70ff611ac9dde2a5b5fe764209fd8561ae/glymur-0.14.7.tar.gz", hash = "sha256:29f220dd941272fcea978071b354aef669d7ebcbff4aca6e7f38b18d5eb2144f", size = 4581469, upload-time = "2026-02-04T15:47:06.171Z" } +sdist = { url = "https://files.pythonhosted.org/packages/a7/5f/7cfb58c3fab4318bf6b4d5dfbb2eed61ce79935dbc7e72c3943286c13d7a/glymur-0.14.8.tar.gz", hash = "sha256:29ec048e319e8aadede1e30aa9c26dd5dda48769a26a48848fa844bb0b670d42", size = 4581847, upload-time = "2026-05-13T20:31:10.428Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/02/e3/6ce81d9df11d13c952a70f6af56955438574e94785ce08c715abbb1ac954/glymur-0.14.7-py3-none-any.whl", hash = "sha256:68697d54e23701001b9420e2f81e51d08a4fdaf905944ec58fc684a097b9bc08", size = 2744496, upload-time = "2026-02-04T15:47:03.792Z" }, + { url = "https://files.pythonhosted.org/packages/c6/3b/446da532c455895c2c8c1117010fe9d9d6cf1380e496c5b3e6978434385d/glymur-0.14.8-py3-none-any.whl", hash = "sha256:33a53445a66cc91174cabf087cc02d06395e99a14803d80defc6629fe0a48a57", size = 2744805, upload-time = "2026-05-13T20:31:07.104Z" }, ] [[package]] @@ -1368,6 +1601,22 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/d3/b7/4a806f85d62c20157e62e58e03b27513dc9c55499768530acc4f4c5ce4be/h5py-3.15.1-cp314-cp314-win_arm64.whl", hash = "sha256:a6d8c5a05a76aca9a494b4c53ce8a9c29023b7f64f625c6ce1841e92a362ccdf", size = 2465544, upload-time = "2025-10-16T10:35:25.695Z" }, ] +[[package]] +name = "hdmf" +version = "6.2.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "h5py" }, + { name = "jsonschema" }, + { name = "numpy" }, + { name = "pandas" }, + { name = "ruamel-yaml" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/ed/0d/1d41f54b7bc2232b168bdfc84d3f46958b40f086081e04d24378f2bc573d/hdmf-6.2.0.tar.gz", hash = "sha256:47dd0d0ebdf834b0cc5d1fdbe6b73d718549cffa489e47f68f638a4add20b65d", size = 16703812, upload-time = "2026-08-19T14:52:50.954Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/02/97/c6db59c49643f10bf1d9185a23263be78e54205d881a6004c898573624fa/hdmf-6.2.0-py3-none-any.whl", hash = "sha256:303e5c066a175448b3176b3377389e5d16bb4c5fc753f2dca540d6bd7b118b7c", size = 366628, upload-time = "2026-08-19T14:52:48.53Z" }, +] + [[package]] name = "hpack" version = "4.1.0" @@ -1480,6 +1729,81 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/cb/b1/3846dd7f199d53cb17f49cba7e651e9ce294d8497c8c150530ed11865bb8/iniconfig-2.3.0-py3-none-any.whl", hash = "sha256:f631c04d2c48c52b84d0d0549c99ff3859c98df65b3101406327ecc7d53fbf12", size = 7484, upload-time = "2025-10-18T21:55:41.639Z" }, ] +[[package]] +name = "interleave" +version = "0.3.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/cb/73/f06bcda00889d164ee1918126381f2d5e0030a6deaf80c9887e84ba18e31/interleave-0.3.0.tar.gz", hash = "sha256:4c4595e05c5c3286d306db7459972bada9a38088fb8649c1199782c8e4a60a32", size = 15689, upload-time = "2025-01-28T19:48:04.286Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/7e/2b/13b5b2e418bc77574b7215c26be862f72d7850713116641c4ad56add61fd/interleave-0.3.0-py3-none-any.whl", hash = "sha256:09d772693b958c0cbb11e3cd8a6b726c6995c7e12b0530a10ae31a943b458c39", size = 11847, upload-time = "2025-01-28T19:48:03.081Z" }, +] + +[[package]] +name = "isodate" +version = "0.7.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/54/4d/e940025e2ce31a8ce1202635910747e5a87cc3a6a6bb2d00973375014749/isodate-0.7.2.tar.gz", hash = "sha256:4cd1aa0f43ca76f4a6c6c0292a85f40b35ec2e43e315b59f06e6d32171a953e6", size = 29705, upload-time = "2024-10-08T23:04:11.5Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/15/aa/0aca39a37d3c7eb941ba736ede56d689e7be91cab5d9ca846bde3999eba6/isodate-0.7.2-py3-none-any.whl", hash = "sha256:28009937d8031054830160fce6d409ed342816b543597cece116d966c6d99e15", size = 22320, upload-time = "2024-10-08T23:04:09.501Z" }, +] + +[[package]] +name = "isoduration" +version = "20.11.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "arrow" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/7c/1a/3c8edc664e06e6bd06cce40c6b22da5f1429aa4224d0c590f3be21c91ead/isoduration-20.11.0.tar.gz", hash = "sha256:ac2f9015137935279eac671f94f89eb00584f940f5dc49462a0c4ee692ba1bd9", size = 11649, upload-time = "2020-11-01T11:00:00.312Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/7b/55/e5326141505c5d5e34c5e0935d2908a74e4561eca44108fbfb9c13d2911a/isoduration-20.11.0-py3-none-any.whl", hash = "sha256:b2904c2a4228c3d44f409c8ae8e2370eb21a26f7ac2ec5446df141dde3452042", size = 11321, upload-time = "2020-11-01T10:59:58.02Z" }, +] + +[[package]] +name = "jaraco-classes" +version = "3.4.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "more-itertools" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/06/c0/ed4a27bc5571b99e3cff68f8a9fa5b56ff7df1c2251cc715a652ddd26402/jaraco.classes-3.4.0.tar.gz", hash = "sha256:47a024b51d0239c0dd8c8540c6c7f484be3b8fcf0b2d85c13825780d3b3f3acd", size = 11780, upload-time = "2024-03-31T07:27:36.643Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/7f/66/b15ce62552d84bbfcec9a4873ab79d993a1dd4edb922cbfccae192bd5b5f/jaraco.classes-3.4.0-py3-none-any.whl", hash = "sha256:f662826b6bed8cace05e7ff873ce0f9283b5c924470fe664fff1c2f00f581790", size = 6777, upload-time = "2024-03-31T07:27:34.792Z" }, +] + +[[package]] +name = "jaraco-context" +version = "6.1.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "backports-tarfile", marker = "python_full_version < '3.12'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/af/50/4763cd07e722bb6285316d390a164bc7e479db9d90daa769f22578f698b4/jaraco_context-6.1.2.tar.gz", hash = "sha256:f1a6c9d391e661cc5b8d39861ff077a7dc24dc23833ccee564b234b81c82dfe3", size = 16801, upload-time = "2026-03-20T22:13:33.922Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/f2/58/bc8954bda5fcda97bd7c19be11b85f91973d67a706ed4a3aec33e7de22db/jaraco_context-6.1.2-py3-none-any.whl", hash = "sha256:bf8150b79a2d5d91ae48629d8b427a8f7ba0e1097dd6202a9059f29a36379535", size = 7871, upload-time = "2026-03-20T22:13:32.808Z" }, +] + +[[package]] +name = "jaraco-functools" +version = "4.6.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "more-itertools" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/6c/1f/c23395957d41ccf27c4e535c3d334c4051e5395b3752057ba4cbaec35c56/jaraco_functools-4.6.0.tar.gz", hash = "sha256:880c577ec9720b3a052d5bc611fb9f2269b3d87902ef42440df443b88e443280", size = 20837, upload-time = "2026-07-14T01:28:02.544Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/02/36/ecc85bc96c273dc8a11273ed4782272975e6338d4a3e9228621175edf0e3/jaraco_functools-4.6.0-py3-none-any.whl", hash = "sha256:99e3dc0060c5cbe8fcd1cdb36258e2a65ca40f1566b2033b12abb1bb44dd3c30", size = 11677, upload-time = "2026-07-14T01:28:01.59Z" }, +] + +[[package]] +name = "jeepney" +version = "0.9.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/7b/6f/357efd7602486741aa73ffc0617fb310a29b588ed0fd69c2399acbb85b0c/jeepney-0.9.0.tar.gz", hash = "sha256:cf0e9e845622b81e4a28df94c40345400256ec608d0e55bb8a3feaa9163f5732", size = 106758, upload-time = "2025-02-27T18:51:01.684Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b2/a3/e137168c9c44d18eff0376253da9f1e9234d0239e0ee230d2fee6cea8e55/jeepney-0.9.0-py3-none-any.whl", hash = "sha256:97e5714520c16fc0a45695e5365a2e11b81ea79bba796e26f9f1d178cb182683", size = 49010, upload-time = "2025-02-27T18:51:00.104Z" }, +] + [[package]] name = "jinja2" version = "3.1.6" @@ -1505,6 +1829,27 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/26/b4/08c9d297edd5e1182506edecccbb88a92e1122a057953068cadac420ca5d/jinja2_humanize_extension-0.4.0-py3-none-any.whl", hash = "sha256:b6326e2da0f7d425338bebf58848e830421defbce785f12ae812e65128518156", size = 4769, upload-time = "2023-09-01T12:52:41.098Z" }, ] +[[package]] +name = "jinxed" +version = "2.1.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/39/d7/6e6d474ec5eaeca6a61acc17766bb19563b3a372b4b9d92910078f5fe49f/jinxed-2.1.0.tar.gz", hash = "sha256:7e755b831faa2443d44fb4ce7c0202eb9c3ed39bd5bf1193365888f4f6092b54", size = 61287, upload-time = "2026-07-03T15:46:48.153Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/f1/1d/0a6be99b69bb448448403a45a241aff0dca751832ae54f027ed940d2eb52/jinxed-2.1.0-py2.py3-none-any.whl", hash = "sha256:43b802d18b70e405d410fb66eb2837d1101e7e5ea922e666507bb43f34d11d09", size = 104999, upload-time = "2026-07-03T15:46:47.114Z" }, +] + +[[package]] +name = "joblib" +version = "1.6.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "cloudpickle" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/d5/1d/537ab090f302b838943a1b56497dd53059b9a9b46a074936470173a2e207/joblib-1.6.0.tar.gz", hash = "sha256:2ccc96785b12046c08fd6d55839c12857831b54a3c1673ffadd2f04bfc4eda03", size = 327903, upload-time = "2026-08-31T09:39:04.122Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/18/53/84099323c2ec4be98d935f63c033ac4151ee83836ca1050ede3b3aadf155/joblib-1.6.0-py3-none-any.whl", hash = "sha256:3dbbf9f6e4b592a2357b854608e980fe6390d131d7a82f011a377ef2ebef7aba", size = 306115, upload-time = "2026-08-31T09:39:02.298Z" }, +] + [[package]] name = "jsonpatch" version = "1.33" @@ -1541,6 +1886,18 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/69/90/f63fb5873511e014207a475e2bb4e8b2e570d655b00ac19a9a0ca0a385ee/jsonschema-4.26.0-py3-none-any.whl", hash = "sha256:d489f15263b8d200f8387e64b4c3a75f06629559fb73deb8fdfb525f2dab50ce", size = 90630, upload-time = "2026-01-07T13:41:05.306Z" }, ] +[package.optional-dependencies] +format = [ + { name = "fqdn" }, + { name = "idna" }, + { name = "isoduration" }, + { name = "jsonpointer" }, + { name = "rfc3339-validator" }, + { name = "rfc3987" }, + { name = "uri-template" }, + { name = "webcolors" }, +] + [[package]] name = "jsonschema-specifications" version = "2025.9.1" @@ -1553,6 +1910,37 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/41/45/1a4ed80516f02155c51f51e8cedb3c1902296743db0bbc66608a0db2814f/jsonschema_specifications-2025.9.1-py3-none-any.whl", hash = "sha256:98802fee3a11ee76ecaca44429fda8a41bff98b00a0f2838151b113f210cc6fe", size = 18437, upload-time = "2025-09-08T01:34:57.871Z" }, ] +[[package]] +name = "keyring" +version = "25.7.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "importlib-metadata", marker = "python_full_version < '3.12'" }, + { name = "jaraco-classes" }, + { name = "jaraco-context" }, + { name = "jaraco-functools" }, + { name = "jeepney", marker = "sys_platform == 'linux'" }, + { name = "pywin32-ctypes", marker = "sys_platform == 'win32'" }, + { name = "secretstorage", marker = "sys_platform == 'linux'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/43/4b/674af6ef2f97d56f0ab5153bf0bfa28ccb6c3ed4d1babf4305449668807b/keyring-25.7.0.tar.gz", hash = "sha256:fe01bd85eb3f8fb3dd0405defdeac9a5b4f6f0439edbb3149577f244a2e8245b", size = 63516, upload-time = "2025-11-16T16:26:09.482Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/81/db/e655086b7f3a705df045bf0933bdd9c2f79bb3c97bfef1384598bb79a217/keyring-25.7.0-py3-none-any.whl", hash = "sha256:be4a0b195f149690c166e850609a477c532ddbfbaed96a404d4e43f8d5e2689f", size = 39160, upload-time = "2025-11-16T16:26:08.402Z" }, +] + +[[package]] +name = "keyrings-alt" +version = "5.0.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "jaraco-classes" }, + { name = "jaraco-context" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/5c/7b/e3bf53326e0753bee11813337b1391179582ba5c6851b13e0d9502d15a50/keyrings_alt-5.0.2.tar.gz", hash = "sha256:8f097ebe9dc8b185106502b8cdb066c926d2180e13b4689fd4771a3eab7d69fb", size = 29229, upload-time = "2024-08-14T01:09:28.12Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/4a/0d/9c59313ab43d0858a9a665e80763bd830dc78d5f379afc3815e123c486c2/keyrings.alt-5.0.2-py3-none-any.whl", hash = "sha256:6be74693192f3f37bbb752bfac9b86e6177076b17d2ac12a390f1d6abff8ac7c", size = 17930, upload-time = "2024-08-14T01:09:26.785Z" }, +] + [[package]] name = "kiwisolver" version = "1.4.9" @@ -1657,11 +2045,9 @@ wheels = [ [[package]] name = "linc-convert" -version = "0.0.1.dev666+dc8f324" -source = { git = "https://github.com/lincbrain/linc-convert.git?rev=dc8f3243df01d09493a13e53305adede08784695#dc8f3243df01d09493a13e53305adede08784695" } +version = "0.0.1.dev645+e00f6f3" +source = { git = "https://github.com/nmarkowitz/linc-convert.git?rev=e00f6f31cd8bac5e2fa34b212d2d77817bfb6f81#e00f6f31cd8bac5e2fa34b212d2d77817bfb6f81" } dependencies = [ - { name = "cyclopts" }, - { name = "dask" }, { name = "nibabel" }, { name = "nifti-zarr" }, { name = "numpy" }, @@ -2219,6 +2605,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/ad/3f/3d42e9a78fe5edf792a83c074b13b9b770092a4fbf3462872f4303135f09/ml_dtypes-0.5.4-cp314-cp314t-win_arm64.whl", hash = "sha256:11942cbf2cf92157db91e5022633c0d9474d4dfd813a909383bd23ce828a4b7d", size = 168825, upload-time = "2025-11-17T22:32:23.766Z" }, ] +[[package]] +name = "more-itertools" +version = "11.1.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/de/1d/f4da6f02cdffe04d6362210b807146a26044c88d839208aec273bb0d9184/more_itertools-11.1.0.tar.gz", hash = "sha256:48e8f4d9e7e5878571ecf6f2b4e57634f93cd474cc8cfbd2376f2d11b396e30d", size = 145772, upload-time = "2026-05-22T14:14:29.909Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/e8/3d/1087453384dbde46a8c7f9356eead2c58be8a7bf156bca40243377c85715/more_itertools-11.1.0-py3-none-any.whl", hash = "sha256:4b65538ae22f6fed0ce4874efd317463a7489796a0939fa66824dd542125a192", size = 72226, upload-time = "2026-05-22T14:14:28.824Z" }, +] + [[package]] name = "multidict" version = "6.7.1" @@ -2336,6 +2731,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/81/08/7036c080d7117f28a4af526d794aab6a84463126db031b007717c1a6676e/multidict-6.7.1-py3-none-any.whl", hash = "sha256:55d97cc6dae627efa6a6e548885712d4864b81110ac76fa4e534c03819fa4a56", size = 12319, upload-time = "2026-01-26T02:46:44.004Z" }, ] +[[package]] +name = "natsort" +version = "8.4.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/e2/a9/a0c57aee75f77794adaf35322f8b6404cbd0f89ad45c87197a937764b7d0/natsort-8.4.0.tar.gz", hash = "sha256:45312c4a0e5507593da193dedd04abb1469253b601ecaf63445ad80f0a1ea581", size = 76575, upload-time = "2023-06-20T04:17:19.925Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ef/82/7a9d0550484a62c6da82858ee9419f3dd1ccc9aa1c26a1e43da3ecd20b0d/natsort-8.4.0-py3-none-any.whl", hash = "sha256:4732914fb471f56b5cce04d7bae6f164a592c7712e1c85f9ef585e197299521c", size = 38268, upload-time = "2023-06-20T04:17:17.522Z" }, +] + [[package]] name = "networkx" version = "3.6.1" @@ -2485,6 +2889,28 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/de/e5/b7d20451657664b07986c2f6e3be564433f5dcaf3482d68eaecd79afaf03/numpy-2.4.2-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:be71bf1edb48ebbbf7f6337b5bfd2f895d1902f6335a5830b20141fc126ffba0", size = 12502577, upload-time = "2026-01-31T23:13:07.08Z" }, ] +[[package]] +name = "nwbinspector" +version = "0.7.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "aiohttp" }, + { name = "click" }, + { name = "fsspec" }, + { name = "isodate" }, + { name = "jsonschema" }, + { name = "natsort" }, + { name = "packaging" }, + { name = "pynwb" }, + { name = "pyyaml" }, + { name = "requests" }, + { name = "tqdm" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/2e/7d/fcb4b0002445cc940dad1277e88dc840ee229cd628d404b693cf05bbafe8/nwbinspector-0.7.2.tar.gz", hash = "sha256:2e49bee5e5de9bcf2cd8e293aa88d8cf845a4a2a16387052aebd7faef8230ab4", size = 634193, upload-time = "2026-05-19T18:08:23.463Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/3f/0b/9ed001e9d16a94ea5bd74dee2462786fcc869c4bcb3dd568c2373ac9d260/nwbinspector-0.7.2-py3-none-any.whl", hash = "sha256:40d008eedd8afdc5d6841825d6efb6891933c1fd3b8c5b599ab2db14f62db8e8", size = 86926, upload-time = "2026-05-19T18:08:22.348Z" }, +] + [[package]] name = "oauthlib" version = "3.3.1" @@ -2513,6 +2939,7 @@ version = "0.1.0" source = { editable = "." } dependencies = [ { name = "cyclopts" }, + { name = "dandi" }, { name = "dask" }, { name = "jinja2" }, { name = "linc-convert", extra = ["all"] }, @@ -2544,9 +2971,10 @@ dev = [ [package.metadata] requires-dist = [ { name = "cyclopts", specifier = ">=3.3.0" }, + { name = "dandi", specifier = ">=0.78.0" }, { name = "dask" }, { name = "jinja2" }, - { name = "linc-convert", extras = ["all"], git = "https://github.com/lincbrain/linc-convert.git?rev=dc8f3243df01d09493a13e53305adede08784695" }, + { name = "linc-convert", extras = ["all"], git = "https://github.com/nmarkowitz/linc-convert.git?rev=e00f6f31cd8bac5e2fa34b212d2d77817bfb6f81" }, { name = "matplotlib", specifier = ">=3.10.8" }, { name = "mkdocs", marker = "extra == 'dev'" }, { name = "mkdocs-git-revision-date-localized-plugin", marker = "extra == 'dev'" }, @@ -3314,6 +3742,36 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/0c/c3/44f3fbbfa403ea2a7c779186dc20772604442dde72947e7d01069cbe98e3/pycparser-3.0-py3-none-any.whl", hash = "sha256:b727414169a36b7d524c1c3e31839a521725078d7b2ff038656844266160a992", size = 48172, upload-time = "2026-01-21T14:26:50.693Z" }, ] +[[package]] +name = "pycryptodomex" +version = "3.23.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/c9/85/e24bf90972a30b0fcd16c73009add1d7d7cd9140c2498a68252028899e41/pycryptodomex-3.23.0.tar.gz", hash = "sha256:71909758f010c82bc99b0abf4ea12012c98962fbf0583c2164f8b84533c2e4da", size = 4922157, upload-time = "2025-05-17T17:23:41.434Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/2e/00/10edb04777069a42490a38c137099d4b17ba6e36a4e6e28bdc7470e9e853/pycryptodomex-3.23.0-cp313-cp313t-macosx_10_13_universal2.whl", hash = "sha256:7b37e08e3871efe2187bc1fd9320cc81d87caf19816c648f24443483005ff886", size = 2498764, upload-time = "2025-05-17T17:22:21.453Z" }, + { url = "https://files.pythonhosted.org/packages/6b/3f/2872a9c2d3a27eac094f9ceaa5a8a483b774ae69018040ea3240d5b11154/pycryptodomex-3.23.0-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:91979028227543010d7b2ba2471cf1d1e398b3f183cb105ac584df0c36dac28d", size = 1643012, upload-time = "2025-05-17T17:22:23.702Z" }, + { url = "https://files.pythonhosted.org/packages/70/af/774c2e2b4f6570fbf6a4972161adbb183aeeaa1863bde31e8706f123bf92/pycryptodomex-3.23.0-cp313-cp313t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:6b8962204c47464d5c1c4038abeadd4514a133b28748bcd9fa5b6d62e3cec6fa", size = 2187643, upload-time = "2025-05-17T17:22:26.37Z" }, + { url = "https://files.pythonhosted.org/packages/de/a3/71065b24cb889d537954cedc3ae5466af00a2cabcff8e29b73be047e9a19/pycryptodomex-3.23.0-cp313-cp313t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:a33986a0066860f7fcf7c7bd2bc804fa90e434183645595ae7b33d01f3c91ed8", size = 2273762, upload-time = "2025-05-17T17:22:28.313Z" }, + { url = "https://files.pythonhosted.org/packages/c9/0b/ff6f43b7fbef4d302c8b981fe58467b8871902cdc3eb28896b52421422cc/pycryptodomex-3.23.0-cp313-cp313t-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:c7947ab8d589e3178da3d7cdeabe14f841b391e17046954f2fbcd941705762b5", size = 2313012, upload-time = "2025-05-17T17:22:30.57Z" }, + { url = "https://files.pythonhosted.org/packages/02/de/9d4772c0506ab6da10b41159493657105d3f8bb5c53615d19452afc6b315/pycryptodomex-3.23.0-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:c25e30a20e1b426e1f0fa00131c516f16e474204eee1139d1603e132acffc314", size = 2186856, upload-time = "2025-05-17T17:22:32.819Z" }, + { url = "https://files.pythonhosted.org/packages/28/ad/8b30efcd6341707a234e5eba5493700a17852ca1ac7a75daa7945fcf6427/pycryptodomex-3.23.0-cp313-cp313t-musllinux_1_2_i686.whl", hash = "sha256:da4fa650cef02db88c2b98acc5434461e027dce0ae8c22dd5a69013eaf510006", size = 2347523, upload-time = "2025-05-17T17:22:35.386Z" }, + { url = "https://files.pythonhosted.org/packages/0f/02/16868e9f655b7670dbb0ac4f2844145cbc42251f916fc35c414ad2359849/pycryptodomex-3.23.0-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:58b851b9effd0d072d4ca2e4542bf2a4abcf13c82a29fd2c93ce27ee2a2e9462", size = 2272825, upload-time = "2025-05-17T17:22:37.632Z" }, + { url = "https://files.pythonhosted.org/packages/ca/18/4ca89ac737230b52ac8ffaca42f9c6f1fd07c81a6cd821e91af79db60632/pycryptodomex-3.23.0-cp313-cp313t-win32.whl", hash = "sha256:a9d446e844f08299236780f2efa9898c818fe7e02f17263866b8550c7d5fb328", size = 1772078, upload-time = "2025-05-17T17:22:40Z" }, + { url = "https://files.pythonhosted.org/packages/73/34/13e01c322db027682e00986873eca803f11c56ade9ba5bbf3225841ea2d4/pycryptodomex-3.23.0-cp313-cp313t-win_amd64.whl", hash = "sha256:bc65bdd9fc8de7a35a74cab1c898cab391a4add33a8fe740bda00f5976ca4708", size = 1803656, upload-time = "2025-05-17T17:22:42.139Z" }, + { url = "https://files.pythonhosted.org/packages/54/68/9504c8796b1805d58f4425002bcca20f12880e6fa4dc2fc9a668705c7a08/pycryptodomex-3.23.0-cp313-cp313t-win_arm64.whl", hash = "sha256:c885da45e70139464f082018ac527fdaad26f1657a99ee13eecdce0f0ca24ab4", size = 1707172, upload-time = "2025-05-17T17:22:44.704Z" }, + { url = "https://files.pythonhosted.org/packages/dd/9c/1a8f35daa39784ed8adf93a694e7e5dc15c23c741bbda06e1d45f8979e9e/pycryptodomex-3.23.0-cp37-abi3-macosx_10_9_universal2.whl", hash = "sha256:06698f957fe1ab229a99ba2defeeae1c09af185baa909a31a5d1f9d42b1aaed6", size = 2499240, upload-time = "2025-05-17T17:22:46.953Z" }, + { url = "https://files.pythonhosted.org/packages/7a/62/f5221a191a97157d240cf6643747558759126c76ee92f29a3f4aee3197a5/pycryptodomex-3.23.0-cp37-abi3-macosx_10_9_x86_64.whl", hash = "sha256:b2c2537863eccef2d41061e82a881dcabb04944c5c06c5aa7110b577cc487545", size = 1644042, upload-time = "2025-05-17T17:22:49.098Z" }, + { url = "https://files.pythonhosted.org/packages/8c/fd/5a054543c8988d4ed7b612721d7e78a4b9bf36bc3c5ad45ef45c22d0060e/pycryptodomex-3.23.0-cp37-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:43c446e2ba8df8889e0e16f02211c25b4934898384c1ec1ec04d7889c0333587", size = 2186227, upload-time = "2025-05-17T17:22:51.139Z" }, + { url = "https://files.pythonhosted.org/packages/c8/a9/8862616a85cf450d2822dbd4fff1fcaba90877907a6ff5bc2672cafe42f8/pycryptodomex-3.23.0-cp37-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:f489c4765093fb60e2edafdf223397bc716491b2b69fe74367b70d6999257a5c", size = 2272578, upload-time = "2025-05-17T17:22:53.676Z" }, + { url = "https://files.pythonhosted.org/packages/46/9f/bda9c49a7c1842820de674ab36c79f4fbeeee03f8ff0e4f3546c3889076b/pycryptodomex-3.23.0-cp37-abi3-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:bdc69d0d3d989a1029df0eed67cc5e8e5d968f3724f4519bd03e0ec68df7543c", size = 2312166, upload-time = "2025-05-17T17:22:56.585Z" }, + { url = "https://files.pythonhosted.org/packages/03/cc/870b9bf8ca92866ca0186534801cf8d20554ad2a76ca959538041b7a7cf4/pycryptodomex-3.23.0-cp37-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:6bbcb1dd0f646484939e142462d9e532482bc74475cecf9c4903d4e1cd21f003", size = 2185467, upload-time = "2025-05-17T17:22:59.237Z" }, + { url = "https://files.pythonhosted.org/packages/96/e3/ce9348236d8e669fea5dd82a90e86be48b9c341210f44e25443162aba187/pycryptodomex-3.23.0-cp37-abi3-musllinux_1_2_i686.whl", hash = "sha256:8a4fcd42ccb04c31268d1efeecfccfd1249612b4de6374205376b8f280321744", size = 2346104, upload-time = "2025-05-17T17:23:02.112Z" }, + { url = "https://files.pythonhosted.org/packages/a5/e9/e869bcee87beb89040263c416a8a50204f7f7a83ac11897646c9e71e0daf/pycryptodomex-3.23.0-cp37-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:55ccbe27f049743a4caf4f4221b166560d3438d0b1e5ab929e07ae1702a4d6fd", size = 2271038, upload-time = "2025-05-17T17:23:04.872Z" }, + { url = "https://files.pythonhosted.org/packages/8d/67/09ee8500dd22614af5fbaa51a4aee6e342b5fa8aecf0a6cb9cbf52fa6d45/pycryptodomex-3.23.0-cp37-abi3-win32.whl", hash = "sha256:189afbc87f0b9f158386bf051f720e20fa6145975f1e76369303d0f31d1a8d7c", size = 1771969, upload-time = "2025-05-17T17:23:07.115Z" }, + { url = "https://files.pythonhosted.org/packages/69/96/11f36f71a865dd6df03716d33bd07a67e9d20f6b8d39820470b766af323c/pycryptodomex-3.23.0-cp37-abi3-win_amd64.whl", hash = "sha256:52e5ca58c3a0b0bd5e100a9fbc8015059b05cffc6c66ce9d98b4b45e023443b9", size = 1803124, upload-time = "2025-05-17T17:23:09.267Z" }, + { url = "https://files.pythonhosted.org/packages/f9/93/45c1cdcbeb182ccd2e144c693eaa097763b08b38cded279f0053ed53c553/pycryptodomex-3.23.0-cp37-abi3-win_arm64.whl", hash = "sha256:02d87b80778c171445d67e23d1caef279bf4b25c3597050ccd2e13970b57fd51", size = 1707161, upload-time = "2025-05-17T17:23:11.414Z" }, +] + [[package]] name = "pydantic" version = "2.12.5" @@ -3329,6 +3787,11 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/5a/87/b70ad306ebb6f9b585f114d0ac2137d792b48be34d732d60e597c2f8465a/pydantic-2.12.5-py3-none-any.whl", hash = "sha256:e561593fccf61e8a20fc46dfc2dfe075b8be7d0188df33f221ad1f0139180f9d", size = 463580, upload-time = "2025-11-26T15:11:44.605Z" }, ] +[package.optional-dependencies] +email = [ + { name = "email-validator" }, +] + [[package]] name = "pydantic-core" version = "2.41.5" @@ -3498,6 +3961,36 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/6f/2c/5b079febdc65e1c3fb2729bf958d18b45be7113828528e8a0b5850dd819a/pymdown_extensions-10.21-py3-none-any.whl", hash = "sha256:91b879f9f864d49794c2d9534372b10150e6141096c3908a455e45ca72ad9d3f", size = 268877, upload-time = "2026-02-15T20:44:05.464Z" }, ] +[[package]] +name = "pynwb" +version = "4.2.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "h5py" }, + { name = "hdmf" }, + { name = "numpy" }, + { name = "pandas" }, + { name = "platformdirs" }, + { name = "python-dateutil" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/a7/30/cceb14ab8ffb1702b062845e2f54358955378057660d811e973687ded1c2/pynwb-4.2.0.tar.gz", hash = "sha256:681e86b73cf21fc607003936ac9e575efdb64d3d01001bfa351862d40f9b5e7e", size = 36416898, upload-time = "2026-09-02T22:53:50.971Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/be/be/455b569cf15d7478a36d6ca4c7d5992f6af273edd1d56f3c34ace34c01ec/pynwb-4.2.0-py3-none-any.whl", hash = "sha256:9710364ecac03b6e6b8693d9eeaeb9f3dc6e61195baa88adb251def901655445", size = 1415526, upload-time = "2026-09-02T22:53:48.082Z" }, +] + +[[package]] +name = "pyout" +version = "0.8.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "blessed", marker = "sys_platform != 'win32'" }, + { name = "jsonschema" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/a1/0e/87f3d9aef4211fe7e88ddabf01794bd15c9051cae44633bcf507bdd3837d/pyout-0.8.1.tar.gz", hash = "sha256:57b0e96a9beb2e20336bd5a265e369915e1c23f50048a7d448b3fab5d076d1d1", size = 46887, upload-time = "2025-02-22T14:58:09.616Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/46/bb/cf48ce5ba1481d568c5fb2b74ecc55e64207a7ee6444a3d0cb04f0410020/pyout-0.8.1-py3-none-any.whl", hash = "sha256:31708f9a1ea0009e92371c1e045541a1b01e22ec006e1cb2f3407ec99c036a10", size = 53080, upload-time = "2025-02-22T14:58:08.032Z" }, +] + [[package]] name = "pyparsing" version = "3.3.2" @@ -3607,6 +4100,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/c0/d2/21af5c535501a7233e734b8af901574572da66fcc254cb35d0609c9080dd/pywin32-311-cp314-cp314-win_arm64.whl", hash = "sha256:a508e2d9025764a8270f93111a970e1d0fbfc33f4153b388bb649b7eec4f9b42", size = 8932540, upload-time = "2025-07-14T20:13:36.379Z" }, ] +[[package]] +name = "pywin32-ctypes" +version = "0.2.3" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/85/9f/01a1a99704853cb63f253eea009390c88e7131c67e66a0a02099a8c917cb/pywin32-ctypes-0.2.3.tar.gz", hash = "sha256:d162dc04946d704503b2edc4d55f3dba5c1d539ead017afa00142c38b9885755", size = 29471, upload-time = "2024-08-14T10:15:34.626Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/de/3d/8161f7711c017e01ac9f008dfddd9410dff3674334c233bde66e7ba65bbf/pywin32_ctypes-0.2.3-py3-none-any.whl", hash = "sha256:8a1513379d709975552d202d942d9837758905c8d01eb82b8bcc30918929e7b8", size = 30756, upload-time = "2024-08-14T10:15:33.187Z" }, +] + [[package]] name = "pyyaml" version = "6.0.3" @@ -3853,6 +4355,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/7b/44/4e421b96b67b2daff264473f7465db72fbdf36a07e05494f50300cc7b0c6/rfc3339_validator-0.1.4-py2.py3-none-any.whl", hash = "sha256:24f6ec1eda14ef823da9e36ec7113124b39c04d50a4d3d3a3c2859577e7791fa", size = 3490, upload-time = "2021-05-12T16:37:52.536Z" }, ] +[[package]] +name = "rfc3987" +version = "1.3.8" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/14/bb/f1395c4b62f251a1cb503ff884500ebd248eed593f41b469f89caa3547bd/rfc3987-1.3.8.tar.gz", hash = "sha256:d3c4d257a560d544e9826b38bc81db676890c79ab9d7ac92b39c7a253d5ca733", size = 20700, upload-time = "2018-07-29T17:23:47.954Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/65/d4/f7407c3d15d5ac779c3dd34fbbc6ea2090f77bd7dd12f207ccf881551208/rfc3987-1.3.8-py2.py3-none-any.whl", hash = "sha256:10702b1e51e5658843460b189b185c0366d2cf4cff716f13111b0ea9fd2dce53", size = 13377, upload-time = "2018-07-29T17:23:45.313Z" }, +] + [[package]] name = "rich" version = "14.3.3" @@ -4206,6 +4717,28 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/07/39/338d9219c4e87f3e708f18857ecd24d22a0c3094752393319553096b98af/scipy-1.17.1-cp314-cp314t-win_arm64.whl", hash = "sha256:200e1050faffacc162be6a486a984a0497866ec54149a01270adc8a59b7c7d21", size = 25489165, upload-time = "2026-02-23T00:22:29.563Z" }, ] +[[package]] +name = "secretstorage" +version = "3.5.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "cryptography", marker = "sys_platform != 'emscripten' and sys_platform != 'win32'" }, + { name = "jeepney", marker = "sys_platform != 'emscripten' and sys_platform != 'win32'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/1c/03/e834bcd866f2f8a49a85eaff47340affa3bfa391ee9912a952a1faa68c7b/secretstorage-3.5.0.tar.gz", hash = "sha256:f04b8e4689cbce351744d5537bf6b1329c6fc68f91fa666f60a380edddcd11be", size = 19884, upload-time = "2025-11-23T19:02:53.191Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b7/46/f5af3402b579fd5e11573ce652019a67074317e18c1935cc0b4ba9b35552/secretstorage-3.5.0-py3-none-any.whl", hash = "sha256:0ce65888c0725fcb2c5bc0fdb8e5438eece02c523557ea40ce0703c266248137", size = 15554, upload-time = "2025-11-23T19:02:51.545Z" }, +] + +[[package]] +name = "semantic-version" +version = "2.10.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/7d/31/f2289ce78b9b473d582568c234e104d2a342fd658cc288a7553d83bb8595/semantic_version-2.10.0.tar.gz", hash = "sha256:bdabb6d336998cbb378d4b9db3a4b56a1e3235701dc05ea2690d9a997ed5041c", size = 52289, upload-time = "2022-05-26T13:35:23.454Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/6a/23/8146aad7d88f4fcb3a6218f41a60f6c2d4e3a72de72da1825dc7c8f7877c/semantic_version-2.10.0-py2.py3-none-any.whl", hash = "sha256:de78a3b8e0feda74cabc54aab2da702113e33ac9d9eb9d2389bcf1f58b7d9177", size = 15552, upload-time = "2022-05-26T13:35:21.206Z" }, +] + [[package]] name = "semver" version = "3.0.4" @@ -4349,6 +4882,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/81/0d/13d1d239a25cbfb19e740db83143e95c772a1fe10202dda4b76792b114dd/starlette-0.52.1-py3-none-any.whl", hash = "sha256:0029d43eb3d273bc4f83a08720b4912ea4b071087a3b48db01b7c839f7954d74", size = 74272, upload-time = "2026-01-18T13:34:09.188Z" }, ] +[[package]] +name = "tenacity" +version = "9.1.4" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/47/c6/ee486fd809e357697ee8a44d3d69222b344920433d3b6666ccd9b374630c/tenacity-9.1.4.tar.gz", hash = "sha256:adb31d4c263f2bd041081ab33b498309a57c77f9acf2db65aadf0898179cf93a", size = 49413, upload-time = "2026-02-07T10:45:33.841Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d7/c1/eb8f9debc45d3b7918a32ab756658a0904732f75e555402972246b0b8e71/tenacity-9.1.4-py3-none-any.whl", hash = "sha256:6095a360c919085f28c6527de529e76a06ad89b23659fa881ae0649b867a9d55", size = 28926, upload-time = "2026-02-07T10:45:32.24Z" }, +] + [[package]] name = "tensorstore" version = "0.1.81" @@ -4560,6 +5102,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/dd/1a/5d9a402b39ec892d856bbdd9db502ff73ce28cdf4aff72eb1ce1d6843506/universal_pathlib-0.3.10-py3-none-any.whl", hash = "sha256:dfaf2fb35683d2eb1287a3ed7b215e4d6016aa6eaf339c607023d22f90821c66", size = 83528, upload-time = "2026-02-22T14:40:57.316Z" }, ] +[[package]] +name = "uri-template" +version = "1.3.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/31/c7/0336f2bd0bcbada6ccef7aaa25e443c118a704f828a0620c6fa0207c1b64/uri-template-1.3.0.tar.gz", hash = "sha256:0e00f8eb65e18c7de20d595a14336e9f337ead580c70934141624b6d1ffdacc7", size = 21678, upload-time = "2023-06-21T01:49:05.374Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/e7/00/3fca040d7cf8a32776d3d81a00c8ee7457e00f80c649f1e4a863c8321ae9/uri_template-1.3.0-py3-none-any.whl", hash = "sha256:a44a133ea12d44a0c0f06d7d42a52d71282e77e2f937d8abd5655b8d56fc1363", size = 11140, upload-time = "2023-06-21T01:49:03.467Z" }, +] + [[package]] name = "urllib3" version = "2.6.3" @@ -4609,6 +5160,37 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/33/e8/e40370e6d74ddba47f002a32919d91310d6074130fe4e17dabcafc15cbf1/watchdog-6.0.0-py3-none-win_ia64.whl", hash = "sha256:a1914259fa9e1454315171103c6a30961236f508b9b623eae470268bbcc6a22f", size = 79067, upload-time = "2024-11-01T14:07:11.845Z" }, ] +[[package]] +name = "wcwidth" +version = "0.9.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/dc/ac/3a943d2792c9bb368aaa8b50121c0f778460ba2d7fbdc0a0366201d9e761/wcwidth-0.9.1.tar.gz", hash = "sha256:5823209b0d43af322ce698c689380d7c15ca31fa8e6e3be8459f27031bef0af5", size = 952410, upload-time = "2026-09-23T20:23:49.127Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/48/7c/130de33c0a7f6efecee28fef5711fc1f8d55ac33885a6b85f4f6689004ba/wcwidth-0.9.1-cp310-abi3-macosx_10_9_x86_64.whl", hash = "sha256:10b00ba23482e352f874d2e8135e7ace9da838646c7dd800566246bbd46125ff", size = 604219, upload-time = "2026-09-23T20:23:22.071Z" }, + { url = "https://files.pythonhosted.org/packages/33/7c/c7bb03da54de7ac5a08753e186b963f91847b04ed8ae5be136a4d5f52b75/wcwidth-0.9.1-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:40d936d72c9bdc10df43f93a8be502bc5024b487259139f66a328722c07f34a9", size = 609038, upload-time = "2026-09-23T20:23:24.941Z" }, + { url = "https://files.pythonhosted.org/packages/0b/71/f57effdf895c2d6d49333f1d6833a9f5438725c55a04ed3124a1c95bb3aa/wcwidth-0.9.1-cp310-abi3-manylinux1_i686.manylinux2014_i686.manylinux_2_17_i686.manylinux_2_5_i686.whl", hash = "sha256:69bb970cf5652b88cfdb9d3fdd1764fc15e5f8ad531643e7bb3e894cd969740e", size = 761464, upload-time = "2026-09-23T20:23:32.425Z" }, + { url = "https://files.pythonhosted.org/packages/4f/16/15b03d8fb7a747d0d2cf4a33da7b1b3e092493c58780f6589d5b1e9e3b49/wcwidth-0.9.1-cp310-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:b5da43d6967668982e44a52fb551967d293f86d26cd86036ac95bbdd34394ed9", size = 770483, upload-time = "2026-09-23T20:23:28.128Z" }, + { url = "https://files.pythonhosted.org/packages/e2/a0/834886b30e3b885a5a96e8358f1b3917bc0bac43ae4178d77f0c210d079b/wcwidth-0.9.1-cp310-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:747fb724223f417a17541a95a17c1dac3a8ef9a0cf41684950f0eab191a35f65", size = 768443, upload-time = "2026-09-23T20:23:33.875Z" }, + { url = "https://files.pythonhosted.org/packages/a2/ae/1b7597e0132ebc2c920632f39d8c1c61881345c9b480c0a95eb91e7460fa/wcwidth-0.9.1-cp310-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:6e1272b7986cefe79783737e38bdb9eaae0682b333c7bd132024441193dd5ce7", size = 781171, upload-time = "2026-09-23T20:23:29.46Z" }, + { url = "https://files.pythonhosted.org/packages/fb/bb/32149e3b481953f4ef35f38f166e2532886d33ae54ccdd71393f821dfad9/wcwidth-0.9.1-cp310-abi3-musllinux_1_2_i686.whl", hash = "sha256:fe021c4d8de9d36c31a0cb41d0d2546dadd3b0708a301f1a0c66ce200851831f", size = 781576, upload-time = "2026-09-23T20:23:35.504Z" }, + { url = "https://files.pythonhosted.org/packages/d6/72/1ee3dff67697bda93bc56ec9f7b3b89609cd64b9abb328512a2f22eb9e47/wcwidth-0.9.1-cp310-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:708158c082364af442f9983de7b6ec9ac0d2e1b825ada25f0911b1f138d55405", size = 783526, upload-time = "2026-09-23T20:23:36.937Z" }, + { url = "https://files.pythonhosted.org/packages/0b/fb/bf93868205814f03d63e5b91757cf5bee99e024ce951c2e91fdeaab49c59/wcwidth-0.9.1-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:dc10e262c3ac0abbfd0a2a51e45a848b1b7f500b21ff512630277973ba25674d", size = 605391, upload-time = "2026-09-23T20:23:23.602Z" }, + { url = "https://files.pythonhosted.org/packages/59/bb/dd3ae682f8ab13b1bffd8d52320d2f7becc16e3200580015f52124636e3a/wcwidth-0.9.1-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:bcb9ed4a367cc025bf1092ac679a156759605182d60b7ed3c28f7221a42ddf55", size = 609851, upload-time = "2026-09-23T20:23:26.583Z" }, + { url = "https://files.pythonhosted.org/packages/56/e7/4f3a86953ab1f59eac15585795f7753da99370798f75b134d3cbf252b243/wcwidth-0.9.1-cp314-cp314t-manylinux1_i686.manylinux2014_i686.manylinux_2_17_i686.manylinux_2_5_i686.whl", hash = "sha256:0d68a30d504c68cfdff2a5f804675c1e7ab4c0bbe878024c8b680ec5579cde67", size = 774751, upload-time = "2026-09-23T20:23:38.473Z" }, + { url = "https://files.pythonhosted.org/packages/48/0c/a456332bb581ebf3eb1a7dedb1492747b15772ce82c0717cc05387a64a17/wcwidth-0.9.1-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:9f1636c5075ffd5c2e835b4561874f6e5dd2bbeba3c6c2c99f067d0d16883af8", size = 785798, upload-time = "2026-09-23T20:23:30.998Z" }, + { url = "https://files.pythonhosted.org/packages/1b/6e/a35de089370d6d872c5424d234e00a8580e62c1bff518ff583750e7b15f7/wcwidth-0.9.1-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:c4cead196551112cb8f43cdd1f80c235ef2456e34b1a9955c424537ec99961b2", size = 782933, upload-time = "2026-09-23T20:23:39.672Z" }, + { url = "https://files.pythonhosted.org/packages/96/a2/f06f2e0be4895e5943d358755b51968ace85774cf0a4cc42b4dafb793832/wcwidth-0.9.1-py3-none-any.whl", hash = "sha256:e0c3a1c45c5b9550c6919a4449e95f5b177f6e165786376981db8f1addae9b21", size = 300656, upload-time = "2026-09-23T20:23:20.674Z" }, +] + +[[package]] +name = "webcolors" +version = "25.10.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/1d/7a/eb316761ec35664ea5174709a68bbd3389de60d4a1ebab8808bfc264ed67/webcolors-25.10.0.tar.gz", hash = "sha256:62abae86504f66d0f6364c2a8520de4a0c47b80c03fc3a5f1815fedbef7c19bf", size = 53491, upload-time = "2025-10-31T07:51:03.977Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/e2/cc/e097523dd85c9cf5d354f78310927f1656c422bd7b2613b2db3e3f9a0f2c/webcolors-25.10.0-py3-none-any.whl", hash = "sha256:032c727334856fc0b968f63daa252a1ac93d33db2f5267756623c210e57a4f1d", size = 14905, upload-time = "2025-10-31T07:51:01.778Z" }, +] + [[package]] name = "websockets" version = "16.0" @@ -4907,6 +5489,19 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/44/15/bb13b4913ef95ad5448490821eee4671d0e67673342e4d4070854e5fe081/zarr-3.1.5-py3-none-any.whl", hash = "sha256:29cd905afb6235b94c09decda4258c888fcb79bb6c862ef7c0b8fe009b5c8563", size = 284067, upload-time = "2025-11-21T14:05:59.235Z" }, ] +[[package]] +name = "zarr-checksum" +version = "0.4.7" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "click" }, + { name = "tqdm" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/b4/af/eb603e6d7f02d16a60b05335ed97a08de4c71f5b109c2a65f3a571d2c4be/zarr_checksum-0.4.7.tar.gz", hash = "sha256:081f163d52533a286bc8249a241da5614b5dab0c06377b208980dc205e272da9", size = 12414, upload-time = "2025-04-01T15:54:48.548Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/e3/6b/a57376f2713b79e5f2eb8003ebc569aa3201a36779ee1472404f183e3c87/zarr_checksum-0.4.7-py3-none-any.whl", hash = "sha256:97cbffe2288338f9083f92a2312052f045fb2154a6f4ddbbcb1bde109b6fd22e", size = 15292, upload-time = "2025-04-01T15:54:47.27Z" }, +] + [[package]] name = "zipp" version = "3.23.0" From 341e6ad56e2f08c5042c97a947b00363f1b7f36e Mon Sep 17 00:00:00 2001 From: NoahMarkowitz Date: Wed, 30 Sep 2026 16:00:45 -0400 Subject: [PATCH 32/65] filename pattern changes --- docs/acquisition_enface_previews.md | 172 +++++++------- docs/oct_input_naming.md | 20 +- opticstream/cli/oct/setup.py | 2 +- opticstream/cli/oct/watch.py | 58 ++++- opticstream/cli/oct/watch_enface.py | 70 +++--- opticstream/config/enface_preview.py | 64 ------ opticstream/config/lsm_scan_config.py | 4 +- opticstream/config/migrate_psoct_blocks.py | 7 +- opticstream/config/psoct_scan_config.py | 59 +++-- .../flows/psoct/acquisition_preview_flow.py | 187 +++++++-------- opticstream/utils/oct_input_naming.py | 38 +++- tests/test_acquisition_previews.py | 215 ++++++++++-------- tests/test_acquisition_sequence.py | 26 ++- tests/test_name_formats.py | 38 ++++ tests/test_oct_input_naming.py | 31 ++- tests/test_watch_previews.py | 29 ++- 16 files changed, 597 insertions(+), 423 deletions(-) delete mode 100644 opticstream/config/enface_preview.py create mode 100644 tests/test_name_formats.py diff --git a/docs/acquisition_enface_previews.md b/docs/acquisition_enface_previews.md index 2c1b024..30676cb 100644 --- a/docs/acquisition_enface_previews.md +++ b/docs/acquisition_enface_previews.md @@ -6,7 +6,9 @@ Two new Prefect flows call linc-convert `mosaic2d()` and send JPEG previews to S - `preview-enface-acquisition`: every tile in one acquisition/mosaic. These consume AIP, MIP, orientation (`ori`) and retardance (`ret`) files written by -the acquisition software, independently of spectral processing and MATLAB. They +the acquisition software, plus surface-finding (`surf`) maps when the project maps +them, independently of spectral processing and MATLAB. Only JPEGs are written; the +stitched NIfTI that mosaic2d produces is kept in a scratch folder and deleted. They do not set OpticStream processing/upload milestones. Preview images are not uploaded to DANDI or LINC. @@ -16,32 +18,63 @@ Slack only when the block's `stitched_enface_slack_upload` is true (default fals ## Configure and run -Refresh saved block schemas with `python -m opticstream.config.migrate_psoct_blocks ---apply` using the project's virtual environment. In the block's new -`enface_preview` group, configure all four filename patterns. They are exact Python -format templates (not globs), with `{image}` required and `{slice}`, `{mosaic}`, -`{acquisition}`, `{project}` optional. A plain `{image}` matches the tile number with -any zero padding (`spectral_{image}_processed_aip.nii` finds -`spectral_0001_processed_aip.nii`), like the spectral watcher's `filename_pattern`. -An explicit format such as `{image:04d}` renders the name exactly instead. Two files -that differ only in padding (`aip_1.nii` and `aip_0001.nii`) are an error. +The maps are found with the project's input naming, the same settings the +spectral watcher uses (see oct_input_naming.md): -For example: +- `acquisition.filename_pattern` must contain `{modality}`. +- `acquisition.filename_modality_map` maps each filename label to a type. The + labels mapped to `aip`, `mip`, `ori` and `ret` are the preview maps (all four + required); a label mapped to `surf` adds a surface-finding preview. + +For example, a folder holding + +``` +sub-test_tile-0011_acq-normal0deg_spectral.nii +sub-test_tile-0011_acq-normal0deg_processed_aip.nii +sub-test_tile-0011_acq-normal0deg_processed_mip.nii +sub-test_tile-0011_acq-normal0deg_processed_orientation.nii +sub-test_tile-0011_acq-normal0deg_processed_retardance.nii +sub-test_tile-0011_acq-normal0deg_processed_surface_finding.nii +``` + +uses ```json { - "aip_pattern": "slice-{slice}_acq-{acquisition}_aip_{image}.nii", - "mip_pattern": "slice-{slice}_acq-{acquisition}_mip_{image}.nii", - "ori_pattern": "slice-{slice}_acq-{acquisition}_ori_{image}.nii", - "ret_pattern": "slice-{slice}_acq-{acquisition}_ret_{image}.nii" + "filename_pattern": "sub-test_tile-{image}_acq-{acq}_{modality}", + "filename_modality_map": { + "spectral": "spectral", + "processed_aip": "aip", + "processed_mip": "mip", + "processed_orientation": "ori", + "processed_retardance": "ret", + "processed_surface_finding": "surf" + } } ``` -Change names/suffixes to match the acquisition software exactly. Simple names such -as `aip_{image}.nii` are supported when the folder contains only that acquisition. -NIfTI (.nii/.nii.gz) and formats supported by the existing QC loader are accepted; -only 2D maps or maps with singleton trailing dimensions are supported. All four -modalities must be present for every expected tile before a candidate is ready. +The pattern may leave out the extension; it then matches `.nii`, `.nii.gz`, +`.mat` or `.raw` (see oct_input_naming.md). Labels missing from the map (here +`processed`) are ignored. The batch watcher puts only the processing input type into batches +(`spectral` for spectral `tile_saving_type`), so the enface maps in the same +folder are left to the previews. With `processed_with_spectral` input, every +mapped file is a processing input. + +`{image}` matches any zero padding. Two files for the same modality and image +(e.g. `..._0001_...` and `..._1_...`) are an error. NIfTI (.nii/.nii.gz) and formats +supported by the existing QC loader are accepted; only 2D maps or maps with +singleton trailing dimensions are supported. Every previewed modality (the four +required ones, plus `surf` when mapped) must be present for every expected tile +before a candidate is ready. + +Set `acquisition.orientation_units` to `radians` if the acquisition writes +orientation in radians (default `degrees`); radians are converted for linc-convert. + +After upgrading, refresh saved blocks with `python -m opticstream.config.migrate_psoct_blocks +--apply` using the project's virtual environment. It removes the old +`enface_preview` group (its per-modality patterns, grid settings, `first_image` +and enable switches), keeping its `orientation_units` under `acquisition`. +Blocks that were not re-saved still load; the old group is ignored. From Miniforge Prompt, with the project's venv activated and Prefect API configured: @@ -51,16 +84,20 @@ opticstream oct watch human-10um D:\data\acquisition --slice 1 --mosaic 1 The main `oct watch` runs the previews in a background polling loop next to batch dispatch. With continuously numbered files (a `filename_pattern` without `{slice}` or -`{acquisition}`, see oct_input_naming.md) the previews follow the same sequence: +`{acq}`, see oct_input_naming.md) the previews follow the same sequence: each mosaic's maps are the images in its range (mosaic 2 of a 22 x 16 grid starts at -image 353), named with its `acquisition_mosaic_map` label. Preview patterns then -need only `{image}`. Otherwise previews need the folder's slice and mosaic (`--slice` -with `--mosaic` or `--acquisition`). Previews do not wait for batch processing (e.g. MATLAB on -the last batch): the full-acquisition preview starts as soon as the last batch's -maps have been stable for `--stability-seconds` (default 15), ahead of any batch -previews still pending. A preview error is logged and never stops batch watching. -Pass `--no-previews` to turn them off for one run, or disable them in the block with -`batch_enabled`/`acquisition_enabled`. +image 353), named with its `acquisition_mosaic_map` label. Otherwise previews need +the folder's slice and mosaic (`--slice` with `--mosaic` or `--acquisition`). +Previews do not wait for batch processing (e.g. MATLAB on the last batch): the +full-acquisition preview starts as soon as the last batch's maps have been stable +for `--stability-seconds` (default 15), ahead of any batch previews still pending. +A preview error is logged and never stops batch watching. If the input naming +cannot locate the maps, `oct watch` logs why and runs without previews. + +Flags (on both `oct watch` and `oct watch-enface`): + +- `--no-previews`: skip the full-acquisition preview (on by default). +- `--batch-previews`: also preview each complete batch (off by default). To preview without processing, run the standalone watcher instead: @@ -78,46 +115,26 @@ Slice/mosaic identify outputs explicitly; acquisition is the exact filename labe ## Geometry and readiness -Tiles are numbered consecutively within the acquisition starting at `first_image` -(default 1). Batch 1 contains the first `grid_size_y` tiles, batch 2 the next set, -etc. Total tiles = selected `grid_size_x` * `grid_size_y`. Tilted mosaics use -`grid_size_y_tilted` in place of `grid_size_y` when it is set, e.g. a scanner with -22 strips of 18 (normal) and 25 (tilted) tiles uses `grid_size_x_normal=22`, -`grid_size_x_tilted=22`, `grid_size_y=18`, `grid_size_y_tilted=25`. - -In the block editor, `enface_preview.grid_config` exposes all linc-convert modes: - -| grid_type | Valid order values | -| --- | --- | -| row-by-row / snake-by-rows | right-down, left-down, right-up, left-up | -| column-by-column / snake-by-columns | down-right, down-left, up-right, up-left | - -The first direction is motion within the first strip; the second is motion between -strips. `right-down` and `down-right` start at top-left; `left-down` and `down-left` -at top-right; `right-up` and `up-right` at bottom-left; `left-up` and `up-left` at -bottom-right. Snake reverses the fast direction on alternate strips. - -Default is `snake-by-columns` / `up-right`; batch previews (`batch_enabled`) are off by default. In column-first mode strips advance -along Y and batches along X; row-first swaps those axes. **Batch size stays -grid_size_y and batch count stays the selected grid_size_x**, so row-first has -grid_size_y physical columns and grid_size_x physical rows. This keeps the existing -consecutive batch convention. Individual images are not flipped. Coordinates use actual -image dimensions and `acquisition.tile_overlap` (percentage). These are nominal -grid QC previews, not image-registered/Fiji-optimized mosaics. Inspect alignment -against a known acquisition before relying on the preview geometry. - -Existing saved `enface_preview.traversal` settings migrate automatically to -`grid_config.grid_type` with `order=down-right` when loaded/resaved by the block -migration command. Explicit new grid_config values take precedence. Change both -grid_type and order together to a compatible pair. These settings affect the new -acquisition-preview flows, not the existing Fiji-registered processing pipeline. -The new grid_config representation changes preview fingerprints, including after -legacy migration, so existing previews may be regenerated and sent again. Disable -Slack temporarily if you only want to inspect the regenerated images locally. - -Orientation uses circular blending; set `orientation_units` to degrees (default) -or radians. AIP/MIP/retardance use ordinary blending. Acquisition originals are -never changed. Temporary 2D NIfTI copies accommodate singleton NIfTI dimensions. +Tiles are numbered consecutively within the acquisition starting at image 1 +(with continuous numbering, at the mosaic's first image). Batch 1 contains the +first `grid_size_y` tiles, batch 2 the next set, etc. Total tiles = selected +`grid_size_x` * `grid_size_y`. Tilted mosaics use `grid_size_y_tilted` in place of +`grid_size_y` when it is set, e.g. a scanner with 22 strips of 18 (normal) and 25 +(tilted) tiles uses `grid_size_x_normal=22`, `grid_size_x_tilted=22`, +`grid_size_y=18`, `grid_size_y_tilted=25`. + +The grid traversal is fixed (`GRID_TYPE`/`GRID_ORDER` in +`opticstream/flows/psoct/acquisition_preview_flow.py`): linc-convert +`snake-by-columns` / `up-right`. Strips of `grid_size_y` tiles run along columns, +starting at the bottom-left, and alternate strips reverse direction; batches +advance along X. Individual images are not flipped. Coordinates use actual image +dimensions and `acquisition.tile_overlap` (percentage). These are nominal grid QC +previews, not image-registered/Fiji-optimized mosaics. Inspect alignment against a +known acquisition before relying on the preview geometry. + +Orientation uses circular blending. AIP/MIP/retardance use ordinary blending. +Acquisition originals are never changed. Temporary 2D NIfTI copies accommodate +singleton NIfTI dimensions. The watcher waits for all expected files to have stable sizes and modification times (15 seconds by default). This is a heuristic, not a producer completion @@ -130,13 +147,17 @@ All previews for a slice go in one folder, `project_base_path/slice-NN/acquisiti next to the pipeline's `processed/` and `stitched/`. File names carry the mosaic (and batch) so mosaics never collide: -- full acquisition: `mosaic_001_aip.nii`, `mosaic_001_aip.jpg`, ... and `mosaic_001_progress.json` -- batch 3: `mosaic_001_batch_0003_aip.nii`, `mosaic_001_batch_0003_aip.jpg`, ... and - `mosaic_001_batch_0003_progress.json` +- full acquisition: `mosaic_001_aip.jpg`, ..., `mosaic_001_surf.jpg` and `mosaic_001_progress.json` +- batch 3: `mosaic_001_batch_0003_aip.jpg`, ... and `mosaic_001_batch_0003_progress.json` + +No NIfTI files are written there. `.nii` previews from earlier versions are left +in place and can be deleted. The `progress.json` files are per-scope checkpoints. Completed work is skipped on restart. -Input path/size/mtime or relevant configuration changes invalidate checkpoints. -Changing only file content without changing size/mtime is not detected. +Input path/size/mtime or relevant configuration (the `acquisition` settings) +changes invalidate checkpoints, so previews may be regenerated and sent again +after editing them. Changing only file content without changing size/mtime is +not detected. The existing Slack bot credentials/channel and `slack-notifications-enabled` variable are reused. When Slack is disabled, stitching still runs; uploading waits @@ -144,8 +165,7 @@ until Slack is enabled. Successful modality uploads are checkpointed; failures retry after another stability interval. Slack delivery is not exactly-once: a crash after Slack accepts an upload but before the checkpoint is saved can duplicate it. -`matlab_processing_enabled` does not gate these non-MATLAB flows. Disable batch or -full previews independently with `batch_enabled`/`acquisition_enabled`. Restart the +`matlab_processing_enabled` does not gate these non-MATLAB flows. Restart the watcher after editing block fields. A project-state reset does not erase preview checkpoints; to deliberately resend, delete or move that scope's `*_progress.json` while the watcher is stopped (deleting only its `.nii`/`.jpg` restitches without resending). diff --git a/docs/oct_input_naming.md b/docs/oct_input_naming.md index 96b7273..0a49974 100644 --- a/docs/oct_input_naming.md +++ b/docs/oct_input_naming.md @@ -6,13 +6,13 @@ Omitting `filename_pattern` (or setting it to null) preserves legacy parsing. ```json { - "filename_pattern": "sub-{subject}_sample-slice{slice}_chunk-{image}_acq-{acquisition}_{modality}{extension}", + "filename_pattern": "sub-{subject}_sample-slice{slice}_chunk-{image}_acq-{acq}_{modality}{extension}", "acquisition_mosaic_map": {"normal0deg": 1, "tilted15deg": 2} } ``` This is a template, not a regular expression. The only required placeholder is -`image`. Optional placeholders are `slice`, `acquisition`, `subject`, `modality`, +`image`. Optional placeholders are `slice`, `acq` (the acquisition label), `subject`, `modality`, and `extension`. Each may appear once; do not add format specifiers such as `:04d`. Numeric fields accept zero padding. Matching is case-sensitive and covers the entire basename. The watcher scans the selected directory, not recursively. @@ -65,18 +65,30 @@ start a folder partway through, e.g. with the tilted mosaic of slice 3, pass A batch number beyond a mosaic's `grid_size_x` is never dispatched (it is logged and ignored), whatever the naming. -When the filename already contains `{slice}`/`{acquisition}`, or uses legacy +When the filename already contains `{slice}`/`{acq}`, or uses legacy `mosaic_###_image_####` names, these options act as a filter: only matching files are dispatched. No `_spectral.nii` suffix is required. For example, use -`s{slice}_tile{image}_{acquisition}.nii` with +`s{slice}_tile{image}_{acq}.nii` with `filename_default_modality: "spectral"`. Or keep `{modality}{extension}` and set `filename_modality_map` to `{"rawscan": "spectral"}` for `_rawscan.nii`. The default map accepts spectral, complex, processed, aip, mip, ori, ret, surf, and dbi. Unknown acquisition/modality labels are ignored. Duplicate files for the same tile and modality cause an error rather than silently replacing data. +Batches contain only the processing input for `tile_saving_type` (`spectral` for +spectral input; `complex`/`processed` for complex; all three for +`complex_with_spectral`; every mapped label for `processed_with_spectral`). Other +mapped labels in the same folder, such as `processed_aip: aip`, are not batched; +labels mapped to aip/mip/ori/ret are what acquisition enface previews read +(see acquisition_enface_previews.md). + +The extension can be left out: a pattern with no `{extension}` and no literal +extension at its end, such as `sub-test_tile-{image}_acq-{acq}_{modality}`, matches +names ending in `.nii`, `.nii.gz`, `.mat` or `.raw` (other endings, e.g. `.nii.bak`, +are ignored). A literal extension (`..._{modality}.nii`) is still matched exactly. + The extension placeholder accepts `.nii`, `.nii.gz`, `.raw`, etc.; the actual contents must still be supported by the configured reader and tile saving type. Matching a name does not convert a file format. Files must still meet the diff --git a/opticstream/cli/oct/setup.py b/opticstream/cli/oct/setup.py index 8754865..6cf2416 100644 --- a/opticstream/cli/oct/setup.py +++ b/opticstream/cli/oct/setup.py @@ -139,7 +139,7 @@ def setup( ``"{normal: 1, tilted: 2}"``. filename_pattern Input filename template; unset keeps legacy ``mosaic__image__*`` - naming. Requires ``{image}``; optional ``{slice}``, ``{acquisition}``, + naming. Requires ``{image}``; optional ``{slice}``, ``{acq}``, ``{subject}``, ``{modality}``, ``{extension}``. Quote it in the shell, e.g. ``'spectral_{image}.nii'``. """ diff --git a/opticstream/cli/oct/watch.py b/opticstream/cli/oct/watch.py index 001c92a..095cd3b 100644 --- a/opticstream/cli/oct/watch.py +++ b/opticstream/cli/oct/watch.py @@ -245,6 +245,23 @@ def _selected_tile_saving_type(self) -> TileSavingType: ) return saving_type + def _batch_input_modalities(self) -> set[str] | None: + """filename_modality_map values that form processing batches (None: all). + + With {modality} in filename_pattern one folder may also hold acquisition + enface maps (aip/mip/ori/ret, used for previews); only the processing + input type goes into batches, unless processed maps are that input. + """ + saving_type = self.scan_config.acquisition.tile_saving_type + if saving_type in (TileSavingType.SPECTRAL, TileSavingType.SPECTRAL_12bit): + return {"spectral"} + if saving_type is TileSavingType.COMPLEX: + return {"complex", "processed"} + if saving_type is TileSavingType.COMPLEX_WITH_SPECTRAL: + # Processing reads the complex tiles; archiving reads the spectral ones. + return {"spectral", "complex", "processed"} + return None + def discover_candidates(self) -> list[OCTBatchCandidate]: if not _is_readable_dir(self.folder_path): logger.warning( @@ -387,6 +404,7 @@ def _matches_fixed_mosaic(self, source_mosaic_id: int) -> bool: def _discover_two_mosaic_files(self) -> list[ParsedTileFile]: logger.debug("_discover_two_mosaic_files: scanning all tile files") out: list[ParsedTileFile] = [] + batch_modalities = self._batch_input_modalities() for path in self.folder_path.iterdir(): if not path.is_file(): @@ -408,6 +426,8 @@ def _discover_two_mosaic_files(self) -> list[ParsedTileFile]: ) if custom is None: continue + if batch_modalities is not None and custom.modality not in batch_modalities: + continue if custom.source_mosaic_id is None: if path.name not in self._warned_unplaced: self._warned_unplaced.add(path.name) @@ -723,12 +743,24 @@ def build_watch_previews( stability_seconds: int, poll_interval: int, sequence: AcquisitionSequence | None = None, + acquisition_previews: bool = True, + batch_previews: bool = False, ) -> PollingStableWatcher | None: """Enface preview watcher for the folder's slice/mosaic, or None when not applicable.""" - preview = scan_config.enface_preview - if not (preview.batch_enabled or preview.acquisition_enabled): - logger.info("Enface previews disabled in the block (batch_enabled/acquisition_enabled)") + from opticstream.flows.psoct.acquisition_preview_flow import naming_error + + if not (acquisition_previews or batch_previews): + logger.info("Enface previews off (--no-previews)") return None + error = naming_error(scan_config) + if error: + logger.info( + "Enface previews off: %s. Name the maps with {modality} and map their " + "labels to aip/mip/ori/ret in acquisition.filename_modality_map", + error, + ) + return None + previews = dict(acquisition_previews=acquisition_previews, batch_previews=batch_previews) if sequence is not None: # Imported here: watch_enface imports this module. from opticstream.cli.oct.watch_enface import build_sequence_preview_watcher @@ -742,6 +774,7 @@ def build_watch_previews( slice_offset=slice_offset, stability_seconds=stability_seconds, poll_interval=poll_interval, + **previews, ) if fixed_slice_id is None or fixed_mosaic_slot is None: logger.info( @@ -787,6 +820,7 @@ def build_watch_previews( acquisition, stability_seconds=stability_seconds, poll_interval=poll_interval, + **previews, ) @@ -856,6 +890,7 @@ def watch( acquisition: str | None = None, mosaic: int | None = None, previews: bool = True, + batch_previews: bool = False, verbose: bool = False, ) -> None: """ @@ -876,18 +911,23 @@ def watch( 2 = tilted) say where the folder starts. --acquisition may name the mosaic by its acquisition.acquisition_mosaic_map label instead of --mosaic. - When acquisition.filename_pattern has no {slice} or {acquisition} (e.g. + When acquisition.filename_pattern has no {slice} or {acq} (e.g. "spectral_{image}.nii"), image numbers are one continuous sequence: image 1 is the start mosaic (default slice 1, mosaic 1), and after that mosaic's grid_size_x * grid_size_y tiles the sequence continues into the next mosaic and then the next slice, each sized by its own grid. - When filenames contain {slice}/{acquisition}, the names place each tile and + When filenames contain {slice}/{acq}, the names place each tile and --slice/--mosaic only filter which tiles this watcher handles. + With {modality} in filename_pattern, only the processing input type (e.g. + spectral) forms batches; other mapped labels are left for previews. + With the slice and mosaic known, a background loop also stitches enface previews - from the acquisition's own AIP/MIP/orientation/retardance maps (block - enface_preview settings) and posts them to Slack. --no-previews turns this off. + from the acquisition's own AIP/MIP/orientation/retardance maps (found through + filename_pattern's {modality} and filename_modality_map) and posts them to + Slack. --no-previews turns off the full-acquisition preview; --batch-previews + also previews each complete batch. """ _configure_logging(verbose) @@ -940,7 +980,7 @@ def watch( logger.info("Using tile_saving_type=%s", scan_config.acquisition.tile_saving_type) companions = () - if previews: + if previews or batch_previews: preview_watcher = build_watch_previews( scan_config, project_name=project_name, @@ -952,6 +992,8 @@ def watch( stability_seconds=stability_seconds, poll_interval=poll_interval, sequence=sequence, + acquisition_previews=previews, + batch_previews=batch_previews, ) if preview_watcher is not None: companions = (preview_watcher,) diff --git a/opticstream/cli/oct/watch_enface.py b/opticstream/cli/oct/watch_enface.py index 1a721c9..883b557 100644 --- a/opticstream/cli/oct/watch_enface.py +++ b/opticstream/cli/oct/watch_enface.py @@ -5,7 +5,7 @@ from opticstream.cli.oct.watch import _configure_logging from opticstream.config.psoct_scan_config import get_psoct_scan_config from opticstream.flows.psoct.acquisition_preview_flow import ( - MODALITIES, expected_tiles, fingerprint, image_numbers_present, list_names, + enface_files, expected_tiles, fingerprint, list_names, naming_error, preview_path, progress_path, read_progress, preview_enface_batch, preview_enface_acquisition, ) @@ -19,20 +19,21 @@ class EnfacePreviewWatcher: - def __init__(self, config, mosaic_ident, folder, acquisition, image_offset=0): + def __init__(self, config, mosaic_ident, folder, acquisition, image_offset=0, *, + acquisition_previews=True, batch_previews=False): self.config = config self.ident = mosaic_ident self.folder = Path(folder) self.acquisition = acquisition - # Continuous numbering: tile 1 of this mosaic is image first_image + image_offset. + # Continuous numbering: tile 1 of this mosaic is image 1 + image_offset. self.image_offset = image_offset # Optional folder listing shared across mosaics for one polling pass. self.names = None context = mosaic_context_from_ident(mosaic_ident, config) # The full acquisition goes first: once its last batch is stable it is # stitched before any batch previews still waiting in the same pass. - self.candidates = [None] if config.enface_preview.acquisition_enabled else [] - if config.enface_preview.batch_enabled: + self.candidates = [None] if acquisition_previews else [] + if batch_previews: self.candidates += list(range(1, context.grid_size_x(config) + 1)) def files(self, batch): @@ -55,9 +56,8 @@ def discover(self): progress = read_progress(progress_path(self.config, self.ident, batch), signature) stitched = all(m in progress["stitched"] and preview_path(self.config, self.ident, batch, f"{m}.jpg").exists() - and preview_path(self.config, self.ident, batch, f"{m}.nii").exists() - for m in MODALITIES) - uploaded = all(m in progress["uploaded"] for m in MODALITIES) + for m in files) + uploaded = all(m in progress["uploaded"] for m in files) if not stitched or (slack_enabled and not uploaded): yield batch @@ -80,12 +80,15 @@ class SequencePreviewWatcher: started, so long runs do not keep rescanning finished mosaics. """ - def __init__(self, config, sequence, folder, project_name, *, slice_offset=0): + def __init__(self, config, sequence, folder, project_name, *, slice_offset=0, + acquisition_previews=True, batch_previews=False): self.config = config self.sequence = sequence self.folder = Path(folder) self.project_name = project_name self.slice_offset = slice_offset + self.previews = dict(acquisition_previews=acquisition_previews, + batch_previews=batch_previews) self.labels = {slot: label for label, slot in reversed( list(config.acquisition.acquisition_mosaic_map.items()))} self.workers = {} @@ -102,7 +105,7 @@ def _worker(self, position): offset = self.sequence.first_image(position.slice_id, position.mosaic_slot) - 1 label = self.labels.get(position.mosaic_slot, str(position.mosaic_slot)) self.workers[key] = EnfacePreviewWatcher(self.config, ident, self.folder, label, - image_offset=offset) + image_offset=offset, **self.previews) return self.workers[key] def _positions(self, last_image): @@ -115,14 +118,10 @@ def _positions(self, last_image): def discover(self): names = list_names(self.folder) - pattern = self.config.enface_preview.aip_pattern - start = self.sequence.locate(1) - values = dict(slice=start.slice_id, mosaic=start.source_mosaic_id, acquisition="", - project=self.project_name) - present = image_numbers_present(pattern, values, names) + present = {image for _, image in enface_files(self.config, names)} if not present: return - last_image = max(present) - self.config.enface_preview.first_image + 1 + last_image = max(present) positions = list(self._positions(last_image)) for number, position in enumerate(positions): key = position.source_mosaic_id @@ -145,10 +144,13 @@ def process(self, candidate): def build_sequence_preview_watcher(config, sequence, folder, project_name, *, - slice_offset=0, stability_seconds=15, poll_interval=5): + slice_offset=0, stability_seconds=15, poll_interval=5, + acquisition_previews=True, batch_previews=False): """Polling watcher for previews of a continuously numbered acquisition folder.""" worker = SequencePreviewWatcher(config, sequence, Path(folder).resolve(), project_name, - slice_offset=slice_offset) + slice_offset=slice_offset, + acquisition_previews=acquisition_previews, + batch_previews=batch_previews) return PollingStableWatcher(discover_candidates=worker.discover, candidate_key=lambda candidate: candidate, fingerprint=worker.fingerprint, process=worker.process, stability_seconds=stability_seconds, @@ -156,10 +158,13 @@ def build_sequence_preview_watcher(config, sequence, folder, project_name, *, def build_preview_watcher(config, mosaic_ident, folder, acquisition, *, - stability_seconds=15, poll_interval=5): + stability_seconds=15, poll_interval=5, + acquisition_previews=True, batch_previews=False): """Polling watcher that stitches previews for one acquisition folder.""" - worker = EnfacePreviewWatcher(config, mosaic_ident, Path(folder).resolve(), acquisition) - # Validate templates before entering the polling loop. + worker = EnfacePreviewWatcher(config, mosaic_ident, Path(folder).resolve(), acquisition, + acquisition_previews=acquisition_previews, + batch_previews=batch_previews) + # Validate the input naming before entering the polling loop. worker.files(None) return PollingStableWatcher(discover_candidates=worker.discover, candidate_key=lambda batch: batch, fingerprint=worker.fingerprint, @@ -170,24 +175,33 @@ def build_preview_watcher(config, mosaic_ident, folder, acquisition, *, @oct_cli.command def watch_enface(project_name: str, folder_path: Path, *, slice: int, mosaic: int, acquisition: str, stability_seconds: int = 15, - poll_interval: int = 5, verbose: bool = False): + poll_interval: int = 5, previews: bool = True, + batch_previews: bool = False, verbose: bool = False): """Watch one acquisition for complete batches and a complete full mosaic. `ops oct watch` already runs these previews when given --slice/--acquisition or --mosaic; use this command only to preview without processing. - slice/mosaic identify the acquisition explicitly, allowing filenames such as - aip_0001.nii without embedded IDs. acquisition substitutes into file patterns. - Use one watcher per acquisition. No MATLAB or spectral watcher is required. + Maps are found with acquisition.filename_pattern (which needs {modality}) and + filename_modality_map labels for aip, mip, ori and ret. slice/mosaic identify + the acquisition explicitly; acquisition is its filename label. + --no-previews skips the full-acquisition preview; --batch-previews also + previews each complete batch. Use one watcher per acquisition. + No MATLAB or spectral watcher is required. """ _configure_logging(verbose) if slice < 1 or mosaic < 1: raise ValueError("slice and mosaic must be positive") if not folder_path.is_dir(): raise ValueError(f"Input directory does not exist: {folder_path}") + if not previews and not batch_previews: + raise ValueError("Nothing to preview: --no-previews without --batch-previews") config = get_psoct_scan_config(project_name) - if not config.enface_preview.batch_enabled and not config.enface_preview.acquisition_enabled: - raise ValueError("Both enface preview flows are disabled in this block") + error = naming_error(config) + if error: + raise ValueError(f"Enface previews need the input naming to cover them: {error}") ident = OCTMosaicId(project_name=project_name, slice_id=slice, mosaic_id=mosaic) build_preview_watcher(config, ident, folder_path, acquisition, - stability_seconds=stability_seconds, poll_interval=poll_interval).run() + stability_seconds=stability_seconds, poll_interval=poll_interval, + acquisition_previews=previews, + batch_previews=batch_previews).run() diff --git a/opticstream/config/enface_preview.py b/opticstream/config/enface_preview.py deleted file mode 100644 index 49bd48e..0000000 --- a/opticstream/config/enface_preview.py +++ /dev/null @@ -1,64 +0,0 @@ -"""Acquisition-produced image preview configuration.""" -from pathlib import PureWindowsPath -from string import Formatter -from typing import Literal - -from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator - - -class PreviewGridConfig(BaseModel): - model_config = ConfigDict(extra="forbid", validate_assignment=True) - grid_type: Literal["snake-by-columns", "row-by-row", "column-by-column", "snake-by-rows"] = Field( - default="snake-by-columns", description="Acquisition traversal. Snake reverses the fast direction on alternate strips; individual images are not flipped. Each strip still contains grid_size_y (or grid_size_y_tilted) consecutive tiles.") - order: Literal["up-right", "right-down", "left-down", "right-up", "left-up", "down-right", "down-left", "up-left"] = Field( - default="up-right", description="Rows: right-down (top-left), left-down (top-right), right-up (bottom-left), left-up (bottom-right). Columns: down-right (top-left), down-left (top-right), up-right (bottom-left), up-left (bottom-right). First word is initial within-strip movement; second is movement between strips. Must match grid_type.") - - @model_validator(mode="after") - def compatible_order(self): - row_based = self.grid_type in {"row-by-row", "snake-by-rows"} - valid = {"right-down", "left-down", "right-up", "left-up"} if row_based else {"down-right", "down-left", "up-right", "up-left"} - if self.order not in valid: - raise ValueError(f"{self.grid_type} requires order in {sorted(valid)}") - return self - - -class EnfacePreviewConfig(BaseModel): - model_config = ConfigDict(extra="forbid", validate_assignment=True) - - batch_enabled: bool = Field(default=False, description="Stitch each complete grid_size_y-tile batch and send previews to Slack when watch-enface runs.") - acquisition_enabled: bool = Field(default=True, description="Also stitch the complete acquisition/mosaic and send previews to Slack.") - aip_pattern: str = Field(default="mosaic_{mosaic:03d}_image_{image:04d}_aip.nii", description="Filename format, not a glob. Required {image}; optional {slice}, {mosaic}, {acquisition}, {project}. A plain {image} matches the number with any zero padding (1, 01, 0001), like filename_pattern; {image:04d} renders exactly. Example: slice-{slice}_acq-{acquisition}_aip_{image}.nii") - mip_pattern: str = Field(default="mosaic_{mosaic:03d}_image_{image:04d}_mip.nii", description="MIP filename format; same placeholders as aip_pattern. Set the actual suffix, including .nii.gz if used.") - ori_pattern: str = Field(default="mosaic_{mosaic:03d}_image_{image:04d}_ori.nii", description="Orientation filename format. Orientation is blended with circular averaging.") - ret_pattern: str = Field(default="mosaic_{mosaic:03d}_image_{image:04d}_ret.nii", description="Retardance filename format; no hardcoded modality suffix.") - grid_config: PreviewGridConfig = Field(default_factory=PreviewGridConfig, description="linc-convert-compatible grid traversal and starting direction for acquisition previews. grid_size_y (grid_size_y_tilted for tilted mosaics) is tiles per strip; selected grid_size_x is number of strips, regardless of traversal axis.") - first_image: int = Field(default=1, ge=0, description="First filename image index within this acquisition. Batches themselves remain 1-based.") - orientation_units: Literal["degrees", "radians"] = Field(default="degrees", description="Units of acquisition orientation maps; radians are converted to degrees for linc-convert.") - - @model_validator(mode="before") - @classmethod - def migrate_traversal(cls, value): - if isinstance(value, dict) and "traversal" in value: - value = dict(value) - traversal = value.pop("traversal") - if traversal not in {"column-by-column", "snake-by-columns"}: - raise ValueError("Invalid legacy preview traversal") - value.setdefault("grid_config", {"grid_type": traversal, "order": "down-right"}) - return value - - @field_validator("aip_pattern", "mip_pattern", "ori_pattern", "ret_pattern") - @classmethod - def validate_pattern(cls, value): - fields = [] - for _, field, spec, conversion in Formatter().parse(value): - if field is None: - continue - if field not in {"image", "slice", "mosaic", "acquisition", "project"} or conversion: - raise ValueError("Unsupported preview filename placeholder or conversion") - fields.append(field) - if "image" not in fields: - raise ValueError("Preview filename must contain {image} (optional numeric format allowed)") - rendered = value.format(image=1, slice=1, mosaic=1, acquisition="normal", project="test") - if PureWindowsPath(rendered).name != rendered or rendered in {".", ".."}: - raise ValueError("Preview patterns must be basenames, without directories") - return value diff --git a/opticstream/config/lsm_scan_config.py b/opticstream/config/lsm_scan_config.py index 22a769e..72441e6 100644 --- a/opticstream/config/lsm_scan_config.py +++ b/opticstream/config/lsm_scan_config.py @@ -34,7 +34,7 @@ class LSMScanConfigModel(BaseModel): ) output_format: Optional[str] = Field( default=( - "{project_name}_sample-slice{slice_id:02d}_chunk-{strip_id:04d}_acq-{acq}.ome.zarr" + "{project_name}_sample-slice{slice_id:04d}_chunk-{strip_id:04d}_acq-{acq}.ome.zarr" ), min_length=1, ) @@ -43,7 +43,7 @@ class LSMScanConfigModel(BaseModel): ) output_mip_format: Optional[str] = Field( default=( - "{project_name}_sample-slice{slice_id:02d}_chunk-{strip_id:04d}_acq-{acq}_proc-mip.tiff" + "{project_name}_sample-slice{slice_id:04d}_chunk-{strip_id:04d}_acq-{acq}_proc-mip.tiff" ), min_length=1, ) diff --git a/opticstream/config/migrate_psoct_blocks.py b/opticstream/config/migrate_psoct_blocks.py index b51370c..c11c542 100644 --- a/opticstream/config/migrate_psoct_blocks.py +++ b/opticstream/config/migrate_psoct_blocks.py @@ -10,8 +10,11 @@ def migrate_blocks(*, apply=False, client=None, block_class=PSOCTScanConfig): """Validate all named blocks before writing; never print block values/secrets. - This is an additive-schema migration, not a transactional server operation. - Pause block editing while applying; saves overwrite each document individually. + Loading applies the model's legacy migrations (e.g. dropping the removed + ``enface_preview`` group, keeping its orientation_units under acquisition), so + re-saving writes the current schema. This is not a transactional server + operation. Pause block editing while applying; saves overwrite each document + individually. """ if client is None: with get_client(sync_client=True) as active_client: diff --git a/opticstream/config/psoct_scan_config.py b/opticstream/config/psoct_scan_config.py index 160d00b..19cf459 100644 --- a/opticstream/config/psoct_scan_config.py +++ b/opticstream/config/psoct_scan_config.py @@ -13,12 +13,11 @@ from prefect.blocks.core import Block from prefect.blocks.system import Secret -from pydantic import BaseModel, ConfigDict, Field, field_validator +from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator from niizarr import ZarrConfig import psoct_toolbox from opticstream.config.utils import with_positions -from opticstream.config.enface_preview import EnfacePreviewConfig from opticstream.utils.naming_convention import normalize_project_name @@ -61,10 +60,10 @@ class PSOCTAcquisitionParams(BaseModel): default=None, description=( "Optional full input filename template; null preserves legacy naming. " - "Example: sub-{subject}_sample-slice{slice}_chunk-{image}_acq-{acquisition}_{modality}{extension}. " + "Example: sub-{subject}_sample-slice{slice}_chunk-{image}_acq-{acq}_{modality}{extension}. " "slice037/chunk-0041/acq-normal0deg means slice 37, image 41, and the mosaic slot mapped from normal0deg. " - "Required placeholder: {image}; optional: {slice}, {acquisition}, {subject}, {modality}, {extension}. " - "Without {slice}/{acquisition} (e.g. spectral_{image}.nii), pass them to `ops oct watch` " + "Required placeholder: {image}; optional: {slice}, {acq} (acquisition label), {subject}, {modality}, {extension}. " + "Without {slice}/{acq} (e.g. spectral_{image}.nii), pass them to `ops oct watch` " "via --slice and --acquisition (or --mosaic). " "Numbers accept zero padding; do not use :04d format specifiers. Literals and labels are case-sensitive. " "Suffixes/extensions may be literals or placeholders; matching an extension does not add support for its file format." @@ -79,8 +78,20 @@ class PSOCTAcquisitionParams(BaseModel): ) filename_modality_map: Dict[str, Literal["spectral", "complex", "processed", "aip", "mip", "ori", "ret", "surf", "dbi"]] = Field( default_factory=lambda: {key: key for key in ("spectral", "complex", "processed", "aip", "mip", "ori", "ret", "surf", "dbi")}, - description="Map filename modality labels to processing types; e.g. rawscan: spectral. Unknown labels are ignored. No fixed _spectral.nii suffix is required.", + description="Map filename modality labels to processing types; e.g. rawscan: spectral, processed_aip: aip. Unknown labels are ignored. No fixed _spectral.nii suffix is required. Acquisition enface previews read the files mapped to aip, mip, ori and ret (filename_pattern needs {modality}).", ) + orientation_units: Literal["degrees", "radians"] = Field( + default="degrees", + description="Units of acquisition-written orientation maps; radians are converted to degrees for enface previews.", + ) + + @field_validator("filename_pattern", mode="before") + @classmethod + def rename_acquisition_placeholder(cls, value): + """Saved patterns from before the {acquisition} -> {acq} rename.""" + if isinstance(value, str): + return value.replace("{acquisition}", "{acq}") + return value @field_validator("filename_pattern") @classmethod @@ -318,6 +329,24 @@ class PSOCTScanConfigModel(BaseModel): validate_assignment=True, revalidate_instances="always" ) + @model_validator(mode="before") + @classmethod + def drop_enface_preview(cls, value: Any) -> Any: + """Blocks saved before enface_preview was removed: keep only orientation_units. + + Preview file names now come from acquisition.filename_pattern and + filename_modality_map; the grid is fixed; enabling moved to watch flags. + """ + if not isinstance(value, dict) or "enface_preview" not in value: + return value + value = dict(value) + legacy = value.pop("enface_preview") or {} + units = legacy.get("orientation_units") if isinstance(legacy, dict) else None + acquisition = value.get("acquisition") + if units and isinstance(acquisition, dict): + value["acquisition"] = {"orientation_units": units, **acquisition} + return value + project_name: str = Field( ..., min_length=1, @@ -332,8 +361,8 @@ class PSOCTScanConfigModel(BaseModel): default=True, description=( "Enable MATLAB-based tile-batch processing and slice registration for this block. " - "When false, these flows skip before processing, archiving within the tile flow, " - "or updating processing milestones. Standalone archive/upload and non-MATLAB " + "When false, these flows skip before processing or updating processing " + "milestones. Raw-tile archive/upload (a separate flow) and non-MATLAB " "flows are unaffected. Does not stop already-running MATLAB sessions." ), ) @@ -353,16 +382,12 @@ class PSOCTScanConfigModel(BaseModel): description="Project-level MATLAB processing options", ) - enface_preview: EnfacePreviewConfig = Field( - default_factory=EnfacePreviewConfig, - description="Acquisition-produced AIP/MIP/orientation/retardance previews, stitched by `ops oct watch` (or watch-enface) and posted to Slack; independent of MATLAB and spectral processing state.", - ) stitched_enface_slack_upload: bool = Field( default=False, description=( "Post the pipeline's stitched 2D enface mosaics (slice-NN/stitched/mosaic_NNN_*.jpg) " "to Slack. The JPEGs are always written; when false, only the acquisition " - "previews (enface_preview) go to Slack." + "enface previews from `ops oct watch` go to Slack." ), ) @@ -414,7 +439,7 @@ class PSOCTScanConfigModel(BaseModel): ) mosaic_volume_format: str = Field( default=( - "{project_name}_sample-slice{slice_id:02d}_acq-{acq}_proc-{modality}_OCT.ome.zarr" + "{project_name}_sample-slice{slice_id:04d}_acq-{acq}_proc-{modality}_OCT.ome.zarr" ), description=( "Filename template for stitched 3D volume outputs " @@ -423,7 +448,7 @@ class PSOCTScanConfigModel(BaseModel): ) mosaic_enface_format: str = Field( default=( - "{project_name}_sample-slice{slice_id:02d}_acq-{acq}_proc-{modality}_OCT.nii.gz" + "{project_name}_sample-slice{slice_id:04d}_acq-{acq}_proc-{modality}_OCT.nii.gz" ), description=( "Filename template for stitched enface outputs " @@ -431,14 +456,14 @@ class PSOCTScanConfigModel(BaseModel): ), ) mosaic_mask_format: str = Field( - default=("{project_name}_sample-slice{slice_id:03d}_acq-{acq}_OCT_mask.nii.gz"), + default=("{project_name}_sample-slice{slice_id:04d}_acq-{acq}_OCT_mask.nii.gz"), description=( "Filename template for stitched mask outputs " "(supports placeholders: project_name, slice_id, acq)" ), ) slice_registered_format: str = Field( - default=("{project_name}_sample-slice{slice_id:03d}_proc-3daxis_OCT.nii.gz"), + default=("{project_name}_sample-slice{slice_id:04d}_proc-3daxis_OCT.nii.gz"), description=( "Filename template for slice-registered axis outputs " "(supports placeholders: project_name, slice_id)" diff --git a/opticstream/flows/psoct/acquisition_preview_flow.py b/opticstream/flows/psoct/acquisition_preview_flow.py index 26f063e..b3bbcfd 100644 --- a/opticstream/flows/psoct/acquisition_preview_flow.py +++ b/opticstream/flows/psoct/acquisition_preview_flow.py @@ -1,14 +1,15 @@ """Batch and acquisition QC previews from externally produced enface tiles. -No processing milestones are mutated. Local manifests permit resumable previews. -Run only one preview watcher for a given project/slice/mosaic at a time. +The maps are found through the project's input naming: acquisition.filename_pattern +(with a {modality} placeholder) and filename_modality_map labels mapped to aip, mip, +ori and ret (required) and surf (when mapped). Only JPEGs are written. No processing +milestones are mutated. Local manifests permit resumable previews. Run only one +preview watcher for a given project/slice/mosaic at a time. """ import hashlib import json import os from pathlib import Path -import re -from string import Formatter import tempfile import time @@ -22,29 +23,38 @@ from opticstream.flows.psoct.utils import get_slice_paths, mosaic_context_from_ident from opticstream.state.oct_project_state import OCTMosaicId from opticstream.tasks.slack_notification import upload_multiple_files_to_slack +from opticstream.utils.oct_input_naming import compile_pattern from opticstream.utils.slack_settings import slack_notifications_enabled -MODALITIES = ("aip", "mip", "ori", "ret") +REQUIRED_MODALITIES = ("aip", "mip", "ori", "ret") +# Previewed only when filename_modality_map has a label for it. +OPTIONAL_MODALITIES = ("surf",) +MODALITIES = REQUIRED_MODALITIES + OPTIONAL_MODALITIES +# linc-convert traversal of the acquisition grid: strips of grid_size_y tiles run +# along columns, snaking, starting bottom-left. The same for every scanner. +GRID_TYPE = "snake-by-columns" +GRID_ORDER = "up-right" -def _image_regex(pattern, values, *, any_padding): - """Regex for a preview pattern with {image} as a digits group, or None. - Returns None when ``any_padding`` is False and {image} has an explicit - format spec (e.g. {image:04d}), which keeps exact rendering. - """ - parts = [] - for literal, field, spec, conversion in Formatter().parse(pattern): - parts.append(re.escape(literal)) - if field is None: - continue - if field == "image": - if (spec or conversion) and not any_padding: - return None - parts.append(r"(?P[0-9]+)") - else: - parts.append(re.escape(format(values[field], spec))) - return re.compile("".join(parts)) +def preview_modalities(config): + """Modalities previewed for this project: the required four plus mapped optional ones.""" + mapped = set(config.acquisition.filename_modality_map.values()) + return REQUIRED_MODALITIES + tuple(m for m in OPTIONAL_MODALITIES if m in mapped) + + +def naming_error(config): + """Why the input naming cannot locate enface maps, or None when it can.""" + pattern = config.acquisition.filename_pattern + if not pattern: + return "acquisition.filename_pattern is not set" + if "modality" not in compile_pattern(pattern).groupindex: + return "acquisition.filename_pattern has no {modality} placeholder" + mapped = set(config.acquisition.filename_modality_map.values()) + missing = [m for m in REQUIRED_MODALITIES if m not in mapped] + if missing: + return f"acquisition.filename_modality_map has no label for {', '.join(missing)}" + return None def list_names(root): @@ -55,33 +65,36 @@ def list_names(root): return [] -def image_numbers_present(pattern, values, names): - """Image numbers of files matching ``pattern``, whatever their padding.""" - regex = _image_regex(pattern, values, any_padding=True) - return {int(found["image"]) for name in names if (found := regex.fullmatch(name))} - +def enface_files(config, names, *, acquisition=None, slice_id=None): + """Map (modality, image number) -> file name for the enface maps in ``names``. -def _padded_image_matches(pattern, values, names): - """Map image number -> filename for a pattern whose {image} has no format spec. - - Like filename_pattern, a bare {image} matches any zero padding (1, 01, 0001), - compared as a number. Returns None when {image} has an explicit format spec - (e.g. {image:04d}), which keeps exact rendering. + Names are parsed with acquisition.filename_pattern; the {modality} label is + translated by filename_modality_map. When the pattern has {acq} or + {slice}, only names for ``acquisition`` / ``slice_id`` are kept. """ - regex = _image_regex(pattern, values, any_padding=False) - if regex is None: - return None - matches = {} + error = naming_error(config) + if error: + raise ValueError(f"Enface previews need the input naming to cover them: {error}") + acq = config.acquisition + regex = compile_pattern(acq.filename_pattern) + found = {} for name in names: - found = regex.fullmatch(name) - if found is None: + match = regex.fullmatch(name) + if match is None: + continue + values = match.groupdict() + modality = acq.filename_modality_map.get(values["modality"]) + if modality not in MODALITIES: + continue + if acquisition is not None and values.get("acq", acquisition) != acquisition: + continue + if slice_id is not None and int(values.get("slice", slice_id)) != slice_id: continue - number = int(found["image"]) - if number in matches: - raise ValueError(f"Several files match image {number} of {pattern!r}: " - f"{matches[number]}, {name}") - matches[number] = name - return matches + key = (modality, int(values["image"])) + if key in found: + raise ValueError(f"Several {modality} files for image {key[1]}: {found[key]}, {name}") + found[key] = name + return found def expected_tiles(config, mosaic_ident, input_dir, acquisition, batch_id=None, *, @@ -89,8 +102,9 @@ def expected_tiles(config, mosaic_ident, input_dir, acquisition, batch_id=None, """Return exact expected paths, never infer completeness from file counts. ``image_offset`` shifts filename image numbers for continuously numbered - acquisitions (tile 1 of this mosaic is image first_image + image_offset). + acquisitions (tile 1 of this mosaic is image 1 + image_offset). ``names`` is an optional pre-read listing of ``input_dir``. + Missing tiles get a path that does not exist, so callers see them as absent. """ context = mosaic_context_from_ident(mosaic_ident, config) rows = context.grid_size_y(config) @@ -99,27 +113,16 @@ def expected_tiles(config, mosaic_ident, input_dir, acquisition, batch_id=None, raise ValueError(f"batch_id must be between 1 and {columns}") indices = range(columns * rows) if batch_id is None else range((batch_id - 1) * rows, batch_id * rows) root = Path(input_dir).resolve() - values = dict(slice=mosaic_ident.slice_id, mosaic=mosaic_ident.mosaic_id, - acquisition=acquisition, project=mosaic_ident.project_name) if names is None: names = list_names(root) + found = enface_files(config, names, acquisition=acquisition, slice_id=mosaic_ident.slice_id) result = {} - for modality in MODALITIES: - pattern = getattr(config.enface_preview, f"{modality}_pattern") - existing = _padded_image_matches(pattern, values, names) + for modality in preview_modalities(config): paths = {} for index in indices: - image = index + config.enface_preview.first_image + image_offset - # Missing tiles keep the unpadded name so callers still see them as absent. - name = (existing or {}).get(image) or pattern.format(image=image, **values) - path = (root / name).resolve() - if path.parent != root: - raise ValueError("Rendered preview filename must remain inside the input directory") - paths[index] = path + image = index + 1 + image_offset + paths[index] = root / (found.get((modality, image)) or f"missing_{modality}_image_{image:04d}") result[modality] = paths - all_paths = [p for paths in result.values() for p in paths.values()] - if len(set(all_paths)) != len(all_paths): - raise ValueError("Preview patterns must identify distinct modality/tile files") return result @@ -131,7 +134,7 @@ def fingerprint(config, files): if not path.is_file() or stat.st_size == 0: raise ValueError(f"Empty or invalid tile: {path}") records.append((modality, index, str(path), stat.st_size, stat.st_mtime_ns)) - settings = (config.enface_preview.model_dump(mode="json"), config.acquisition.model_dump(mode="json")) + settings = (GRID_TYPE, GRID_ORDER, config.acquisition.model_dump(mode="json")) return hashlib.sha256(json.dumps([records, settings], sort_keys=True).encode()).hexdigest() @@ -204,14 +207,11 @@ def tile_config(config, files, shape, overlap, out, per_strip=None): """ from linc_convert.modalities.psoct.generate_tile_config import generate_tile_config - grid = config.enface_preview.grid_config per_strip = per_strip or config.acquisition.grid_size_y strips = max(files) // per_strip + 1 - row_based = grid.grid_type in {"row-by-row", "snake-by-rows"} - columns, rows = (per_strip, strips) if row_based else (strips, per_strip) - generate_tile_config(columns=columns, rows=rows, tile_size_x=shape[0], tile_size_y=shape[1], - base_dir="", naming_format="{tile_number}", grid_type=grid.grid_type, - order=grid.order, overlap_percentage=overlap, out=str(out)) + generate_tile_config(columns=strips, rows=per_strip, tile_size_x=shape[0], tile_size_y=shape[1], + base_dir="", naming_format="{tile_number}", grid_type=GRID_TYPE, + order=GRID_ORDER, overlap_percentage=overlap, out=str(out)) spec = yaml.safe_load(Path(out).read_text()) tiles = [tile for tile in spec["tiles"] if tile["tile_number"] - 1 in files] x0 = min(tile["x"] for tile in tiles) @@ -233,10 +233,11 @@ def stitch_preview_modality(config: PSOCTScanConfigModel, files: dict[int, Path] per_strip: int | None = None) -> Path: """Stitch acquisition tiles in place with linc-convert generate_tile_config + mosaic2d. - Writes ``output`` (NIfTI), a JPEG next to it, and a ``*_grid.jpg`` tile diagram. - Tiles are copied to a scratch directory only when they need converting: - radian orientation maps (linc-convert expects degrees) and plain 2D maps - (mosaic2d writes 3D voxel sizes, so tiles keep a singleton third axis). + Writes only the ``output`` JPEG; the stitched NIfTI mosaic2d produces stays in a + scratch directory that is removed afterwards. Tiles are copied to that scratch + directory only when they need converting: radian orientation maps (linc-convert + expects degrees) and plain 2D maps (mosaic2d writes 3D voxel sizes, so tiles + keep a singleton third axis). """ from opticstream.data_processing.qc.convert_image import load_data from linc_convert.modalities.psoct.mosaic import mosaic2d @@ -250,9 +251,10 @@ def stitch_preview_modality(config: PSOCTScanConfigModel, files: dict[int, Path] for index, other in shapes.items(): if other != shape: raise ValueError(f"Tile dimensions differ: {files[index]}, {other} != {shape}") - to_degrees = modality == "ori" and config.enface_preview.orientation_units == "radians" - jpeg = output.with_suffix(".jpg") + to_degrees = modality == "ori" and config.acquisition.orientation_units == "radians" + jpeg = output with tempfile.TemporaryDirectory(prefix="enface-preview-", dir=output.parent) as scratch: + stitched = Path(scratch) / f"{modality}.nii" sources = dict(files) for index, path in files.items(): is_nifti = path.name.lower().endswith((".nii", ".nii.gz")) @@ -267,35 +269,36 @@ def stitch_preview_modality(config: PSOCTScanConfigModel, files: dict[int, Path] nib.save(nib.Nifti1Image(array, np.eye(4)), sources[index]) spec = tile_config(config, sources, shape, overlap, Path(scratch) / "tiles.yaml", per_strip) - mosaic2d(tile_info_file=str(spec), nifti_output=str(output), + mosaic2d(tile_info_file=str(spec), nifti_output=str(stitched), jpeg_output=None if modality == "ori" else str(jpeg), #print_grid=str(output.with_name(f"{output.stem}_grid.jpg")), tile_overlap=overlap if overlap else 0, circular_mean=modality == "ori", voxel_size_xyz=list(config.acquisition.scan_resolution_3d[:2])) - if not output.is_file(): - raise RuntimeError(f"mosaic2d did not produce {output}") - if modality == "ori": - # mosaic2d's JPEG is grayscale; orientation previews use an angle colormap. - # Transpose to match the orientation of mosaic2d's JPEGs. - angles = np.asarray(nib.load(output).dataobj).squeeze().T - convert_image(data=angles, output=jpeg, angle_to_rgb=True, output_format="jpg") + if not stitched.is_file(): + raise RuntimeError(f"mosaic2d did not produce the stitched {modality} mosaic") + if modality == "ori": + # mosaic2d's JPEG is grayscale; orientation previews use an angle colormap. + # Transpose to match the orientation of mosaic2d's JPEGs. + # mmap=False: a memory-mapped scratch file cannot be deleted on Windows. + angles = np.asarray(nib.load(stitched, mmap=False).dataobj).squeeze().T + convert_image(data=angles, output=jpeg, angle_to_rgb=True, output_format="jpg") + if not jpeg.is_file(): + raise RuntimeError(f"mosaic2d did not produce {jpeg}") return jpeg def run_preview(config, mosaic_ident, input_dir, acquisition, batch_id=None, *, image_offset=0): - enabled = config.enface_preview.acquisition_enabled if batch_id is None else config.enface_preview.batch_enabled - if not enabled: - return {} - files = expected_tiles(config, mosaic_ident, input_dir, acquisition, batch_id, + files =expected_tiles(config, mosaic_ident, input_dir, acquisition, batch_id, image_offset=image_offset) signature = fingerprint(config, files) progress_file = progress_path(config, mosaic_ident, batch_id) progress = read_progress(progress_file, signature) - outputs = {m: preview_path(config, mosaic_ident, batch_id, f"{m}.nii") for m in MODALITIES} + modalities = list(files) + outputs = {m: preview_path(config, mosaic_ident, batch_id, f"{m}.jpg") for m in modalities} per_strip = mosaic_context_from_ident(mosaic_ident, config).grid_size_y(config) - for modality in MODALITIES: + for modality in modalities: output = outputs[modality] - if modality not in progress["stitched"] or not output.with_suffix(".jpg").exists() or not output.exists(): + if modality not in progress["stitched"] or not output.exists(): stitch_preview_modality(config, files[modality], modality, output, batch_id, per_strip=per_strip) if fingerprint(config, files) != signature: @@ -304,9 +307,9 @@ def run_preview(config, mosaic_ident, input_dir, acquisition, batch_id=None, *, progress["stitched"].append(modality) save_progress(progress_file, progress) if slack_notifications_enabled(): - remaining = [m for m in MODALITIES if m not in progress["uploaded"]] + remaining = [m for m in modalities if m not in progress["uploaded"]] if remaining: - paths = [str(outputs[m].with_suffix(".jpg")) for m in remaining] + paths = [str(outputs[m]) for m in remaining] scope = "full acquisition" if batch_id is None else f"batch {batch_id}" label = f"{mosaic_ident.project_name}, slice {mosaic_ident.slice_id}, mosaic {mosaic_ident.mosaic_id}, {acquisition}, {scope}" results = upload_multiple_files_to_slack(filepaths=paths, @@ -317,7 +320,7 @@ def run_preview(config, mosaic_ident, input_dir, acquisition, batch_id=None, *, save_progress(progress_file, progress) if any(not results.get(path) for path in paths): raise RuntimeError("Some preview Slack uploads failed; successful uploads are checkpointed") - return {m: str(outputs[m].with_suffix(".jpg")) for m in MODALITIES} + return {m: str(outputs[m]) for m in modalities} @flow(name="preview-enface-batch") diff --git a/opticstream/utils/oct_input_naming.py b/opticstream/utils/oct_input_naming.py index e2ea5df..b57d8f4 100644 --- a/opticstream/utils/oct_input_naming.py +++ b/opticstream/utils/oct_input_naming.py @@ -4,40 +4,60 @@ from string import Formatter from dataclasses import dataclass +# Matched after a pattern that names no extension, e.g. "spectral_{image}_{modality}". +IMPLICIT_EXTENSIONS = (".nii.gz", ".nii", ".mat", ".raw") + + +def _names_extension(literal): + """True when the pattern's trailing literal already names a file extension.""" + return "." in literal + @lru_cache(maxsize=64) def compile_pattern(pattern): + """Regex for a filename_pattern. + + Without {extension} and without a literal extension at the end (e.g. + ``sub-{subject}_tile-{image}_{modality}``), the name may end in any of + IMPLICIT_EXTENSIONS, captured as the ``extension`` group. + """ fields = set() parts = [] + trailing = "" for literal, field, spec, conversion in Formatter().parse(pattern): parts.append(re.escape(literal)) + trailing = literal if field is None: continue - if field not in {"subject", "slice", "image", "acquisition", "modality", "extension"}: + trailing = "" + if field not in {"subject", "slice", "image", "acq", "modality", "extension"}: raise ValueError(f"Unknown filename placeholder: {field}") if field in fields or spec or conversion: raise ValueError("Filename placeholders must be unique and have no format specifiers.") fields.add(field) value = r"[0-9]+" if field in {"slice", "image"} else (r"\.[A-Za-z0-9.]+" if field == "extension" else r"[^/\\]+?") parts.append(f"(?P<{field}>{value})") - # {slice} and {acquisition} may instead be supplied by the watcher + # {slice} and {acq} may instead be supplied by the watcher # (ops oct watch --slice/--acquisition/--mosaic), e.g. "spectral_{image}.nii". if "image" not in fields: raise ValueError("filename_pattern requires {image}.") + if "extension" not in fields and not _names_extension(trailing): + choices = "|".join(re.escape(ext) for ext in IMPLICIT_EXTENSIONS) + parts.append(f"(?P{choices})") return re.compile("".join(parts)) @dataclass(frozen=True) class InputTile: - # None when the filename has no {slice}/{acquisition} and none was supplied. + # None when the filename has no {slice}/{acq} and none was supplied. source_mosaic_id: int | None image_index: int modality: str def pattern_names_mosaic(pattern): - """True when filenames carry their own {slice} or {acquisition}.""" - return bool({"slice", "acquisition"} & set(compile_pattern(pattern).groupindex)) + """True when filenames carry their own {slice} or {acq}.""" + return bool({"slice", "acq"} & set(compile_pattern(pattern).groupindex)) def parse_input_name(name, acquisition, mosaics_per_slice, *, slice_id=None, mosaic_slot=None, @@ -48,14 +68,14 @@ def parse_input_name(name, acquisition, mosaics_per_slice, *, slice_id=None, mos ``slice_id`` / ``mosaic_slot`` fill in values the filename lacks. When the filename also contains them, they act as filters: a mismatch returns None. ``sequence`` (an AcquisitionSequence) places names with neither {slice} nor - {acquisition} by their continuous image number; image_index is then the tile + {acq} by their continuous image number; image_index is then the tile number within that mosaic. """ match = compile_pattern(acquisition.filename_pattern).fullmatch(name) if match is None: return None values = match.groupdict() - if sequence is not None and "slice" not in values and "acquisition" not in values: + if sequence is not None and "slice" not in values and "acq" not in values: image = int(values["image"]) if image < 1: raise ValueError("Filename image numbers must be positive.") @@ -67,8 +87,8 @@ def parse_input_name(name, acquisition, mosaics_per_slice, *, slice_id=None, mos position = sequence.locate(image) return InputTile(position.source_mosaic_id, position.tile, modality) slot = mosaic_slot - if "acquisition" in values: - slot = acquisition.acquisition_mosaic_map.get(values["acquisition"]) + if "acq" in values: + slot = acquisition.acquisition_mosaic_map.get(values["acq"]) if slot is None or (mosaic_slot is not None and slot != mosaic_slot): return None if slot is not None and not 1 <= slot <= mosaics_per_slice: diff --git a/tests/test_acquisition_previews.py b/tests/test_acquisition_previews.py index 135981c..6e368e0 100644 --- a/tests/test_acquisition_previews.py +++ b/tests/test_acquisition_previews.py @@ -7,19 +7,18 @@ import nibabel as nib import numpy as np -from opticstream.config.enface_preview import EnfacePreviewConfig, PreviewGridConfig -from opticstream.config.psoct_scan_config import PSOCTAcquisitionParams +from niizarr import ZarrConfig + +from opticstream.config.psoct_scan_config import PSOCTAcquisitionParams, PSOCTScanConfigModel from opticstream.flows.psoct import acquisition_preview_flow as preview from opticstream.cli.oct.watch_enface import EnfacePreviewWatcher from opticstream.state.oct_project_state import OCTMosaicId -def config(root): +def config(root, pattern="{modality}_{image}.nii"): return SimpleNamespace(project_base_path=Path(root) / "out", mosaics_per_slice=2, - enface_preview=EnfacePreviewConfig(batch_enabled=True, grid_config={"grid_type": "column-by-column", "order": "down-right"}, - **{f"{m}_pattern": f"{m}_{{image:04d}}.nii" for m in preview.MODALITIES}), acquisition=PSOCTAcquisitionParams(grid_size_y=2, grid_size_x_normal=2, - grid_size_x_tilted=3, tile_overlap=0)) + grid_size_x_tilted=3, tile_overlap=0, filename_pattern=pattern)) class PreviewTests(unittest.TestCase): @@ -36,43 +35,72 @@ def create_tiles(self, count=4): data = np.full((8, 6, 1), i, dtype=np.float32) nib.save(nib.Nifti1Image(data, np.eye(4)), self.root / f"{m}_{i:04d}.nii") - def test_patterns(self): - for value in ("aip.nii", "../{image}.nii", "{unknown}_{image}.nii"): + def test_naming_must_cover_enface_maps(self): + self.assertIsNone(preview.naming_error(self.cfg)) + for pattern in (None, "spectral_{image}.nii"): + cfg = config(self.root, pattern) + self.assertIsNotNone(preview.naming_error(cfg)) with self.assertRaises(ValueError): - EnfacePreviewConfig(aip_pattern=value) + preview.expected_tiles(cfg, self.ident, self.root, "normal") + cfg = config(self.root) + cfg.acquisition.filename_modality_map = {"spectral": "spectral", "aip": "aip"} + self.assertIn("mip, ori, ret", preview.naming_error(cfg)) + + def test_expected_tiles_by_batch(self): + self.create_tiles() files = preview.expected_tiles(self.cfg, self.ident, self.root, "normal", 2) self.assertEqual(list(files["aip"]), [2, 3]) self.assertEqual(files["aip"][2].name, "aip_0003.nii") + self.assertEqual(files["ori"][3].name, "ori_0004.nii") with self.assertRaises(ValueError): preview.expected_tiles(self.cfg, self.ident, self.root, "normal", 3) - def test_plain_image_matches_any_padding(self): - self.cfg.enface_preview.aip_pattern = "spectral_{image}_processed_aip.nii" - (self.root / "spectral_0003_processed_aip.nii").write_bytes(b"x") - (self.root / "spectral_4_processed_aip.nii").write_bytes(b"x") - (self.root / "spectral_0003_processed_aip.nii.bak").write_bytes(b"x") + def test_modality_labels_and_any_padding(self): + self.cfg = config(self.root, "spectral_{image}_{modality}.nii") + self.cfg.acquisition.filename_modality_map = { + "spectral": "spectral", "processed_aip": "aip", "processed_mip": "mip", + "processed_orientation": "ori", "processed_retardance": "ret"} + for name in ("spectral_0003_processed_aip.nii", "spectral_4_processed_aip.nii", + "spectral_0003_processed_orientation.nii", "spectral_0003_spectral.nii", + "spectral_0003_processed_surface_finding.nii", + "spectral_0003_processed_aip.nii.bak"): + (self.root / name).write_bytes(b"x") files = preview.expected_tiles(self.cfg, self.ident, self.root, "normal", 2) self.assertEqual(files["aip"][2].name, "spectral_0003_processed_aip.nii") self.assertEqual(files["aip"][3].name, "spectral_4_processed_aip.nii") - # Missing tiles keep a rendered name and are reported absent. + self.assertEqual(files["ori"][2].name, "spectral_0003_processed_orientation.nii") + # Missing tiles get a path that does not exist. + self.assertFalse(files["mip"][2].exists()) files = preview.expected_tiles(self.cfg, self.ident, self.root, "normal", 1) - self.assertEqual(files["aip"][0].name, "spectral_1_processed_aip.nii") self.assertFalse(files["aip"][0].exists()) - def test_plain_image_with_other_placeholders_and_ambiguity(self): - self.cfg.enface_preview.aip_pattern = "s{slice}_m{mosaic:03d}_{acquisition}_{image}.nii" - (self.root / "s1_m001_normal_01.nii").write_bytes(b"x") - (self.root / "s1_m002_normal_02.nii").write_bytes(b"x") + def test_slice_and_acquisition_filter_and_ambiguity(self): + self.cfg = config(self.root, "s{slice}_{acq}_{modality}_{image}.nii") + for name in ("s1_normal_aip_01.nii", "s2_normal_aip_02.nii", "s1_tilted_aip_02.nii"): + (self.root / name).write_bytes(b"x") files = preview.expected_tiles(self.cfg, self.ident, self.root, "normal", 1) - self.assertEqual(files["aip"][0].name, "s1_m001_normal_01.nii") + self.assertEqual(files["aip"][0].name, "s1_normal_aip_01.nii") self.assertFalse(files["aip"][1].exists()) - (self.root / "s1_m001_normal_1.nii").write_bytes(b"x") + (self.root / "s1_normal_aip_1.nii").write_bytes(b"x") with self.assertRaises(ValueError): preview.expected_tiles(self.cfg, self.ident, self.root, "normal", 1) - def layout(self, files, mode, order, columns=3): + def test_block_migration_drops_enface_preview(self): + legacy = dict( + project_name="p", project_base_path=str(self.root), zarr_config=ZarrConfig(), + acquisition=dict(grid_size_y=2, grid_size_x_normal=2, grid_size_x_tilted=2), + enface_preview=dict(aip_pattern="aip_{image}.nii", batch_enabled=True, + grid_config={"grid_type": "row-by-row", "order": "right-down"}, + orientation_units="radians")) + migrated = PSOCTScanConfigModel.model_validate(legacy) + self.assertNotIn("enface_preview", migrated.model_dump()) + self.assertEqual(migrated.acquisition.orientation_units, "radians") + legacy["enface_preview"] = {} + self.assertEqual( + PSOCTScanConfigModel.model_validate(legacy).acquisition.orientation_units, "degrees") + + def layout(self, files): self.cfg.acquisition.tile_overlap = 20 - self.cfg.enface_preview.grid_config = PreviewGridConfig(grid_type=mode, order=order) with TemporaryDirectory() as scratch: out = preview.tile_config(self.cfg, files, (10, 20), .2, Path(scratch) / "tiles.yaml") import yaml @@ -91,8 +119,7 @@ def test_tilted_mosaic_uses_grid_size_y_tilted(self): self.create_tiles(9) def stitch(cfg, files, modality, output, batch_id, per_strip=None): output.parent.mkdir(parents=True, exist_ok=True) - output.write_bytes(b"nifti") - output.with_suffix(".jpg").write_bytes(b"jpeg") + output.write_bytes(b"jpeg") with patch.object(preview, "stitch_preview_modality", side_effect=stitch) as stitched, \ patch.object(preview, "slack_notifications_enabled", return_value=False): preview.run_preview(self.cfg, tilted, self.root, "t") @@ -109,51 +136,27 @@ def stitch(cfg, files, modality, output, batch_id, per_strip=None): def test_tile_config_uses_linc_convert_grid(self): from linc_convert.modalities.psoct import generate_tile_config as grids - generators = { - "row-by-row": grids._generate_row_by_row, - "column-by-column": grids._generate_column_by_column, - "snake-by-rows": grids._generate_snake_by_rows, - "snake-by-columns": grids._generate_snake_by_columns, - } - for mode, generator in generators.items(): - row_based = mode in {"row-by-row", "snake-by-rows"} - orders = ["right-down", "left-down", "right-up", "left-up"] if row_based else ["down-right", "down-left", "up-right", "up-left"] - for order in orders: - with self.subTest(mode=mode, order=order): - # Non-square acquisition: 3 strips of 2 tiles. - expected = generator(2 if row_based else 3, 3 if row_based else 2, - 10, 20, .2, .2, order, "tile_{tile_number:04d}.nii") - expected = [(round(t["x"]), round(t["y"])) for t in expected] - files = {i: Path(f"/data/image_{i + 7}.nii") for i in range(6)} - actual = self.layout(files, mode, order) - x0, y0 = min(x for x, _ in expected), min(y for _, y in expected) - self.assertEqual([actual[i][:2] for i in range(6)], - [(x - x0, y - y0) for x, y in expected]) - self.assertEqual(actual[4][2], "/data/image_11.nii") - for batch in range(1, 4): - points = expected[(batch - 1) * 2:batch * 2] - cropped = [(x - min(p[0] for p in points), y - min(p[1] for p in points)) for x, y in points] - strip = self.layout({i: files[i] for i in range((batch - 1) * 2, batch * 2)}, mode, order) - self.assertEqual([strip[i][:2] for i in sorted(strip)], cropped) - - def test_grid_schema_validation_and_legacy_migration(self): - for mode in ("column-by-column", "snake-by-columns"): - migrated = EnfacePreviewConfig.model_validate({"traversal": mode}) - self.assertEqual(migrated.grid_config.grid_type, mode) - self.assertEqual(migrated.grid_config.order, "down-right") - self.assertNotIn("traversal", migrated.model_dump()) - with self.assertRaises(ValueError): - PreviewGridConfig(grid_type="row-by-row", order="down-right") - defaults = EnfacePreviewConfig() - self.assertFalse(defaults.batch_enabled) - self.assertEqual((defaults.grid_config.grid_type, defaults.grid_config.order), - ("snake-by-columns", "up-right")) - cfg = EnfacePreviewConfig(grid_config={"grid_type": "snake-by-rows", "order": "left-up"}) - self.assertEqual(cfg.grid_config.order, "left-up") + # Fixed traversal; non-square acquisition: 3 strips of 2 tiles. + self.assertEqual((preview.GRID_TYPE, preview.GRID_ORDER), ("snake-by-columns", "up-right")) + expected = grids._generate_snake_by_columns(3, 2, 10, 20, .2, .2, "up-right", + "tile_{tile_number:04d}.nii") + expected = [(round(t["x"]), round(t["y"])) for t in expected] + files = {i: Path(f"/data/image_{i + 7}.nii") for i in range(6)} + actual = self.layout(files) + x0, y0 = min(x for x, _ in expected), min(y for _, y in expected) + self.assertEqual([actual[i][:2] for i in range(6)], + [(x - x0, y - y0) for x, y in expected]) + self.assertEqual(actual[4][2], str(Path("/data/image_11.nii"))) + for batch in range(1, 4): + points = expected[(batch - 1) * 2:batch * 2] + cropped = [(x - min(p[0] for p in points), y - min(p[1] for p in points)) for x, y in points] + strip = self.layout({i: files[i] for i in range((batch - 1) * 2, batch * 2)}) + self.assertEqual([strip[i][:2] for i in sorted(strip)], cropped) @patch("opticstream.cli.oct.watch_enface.slack_notifications_enabled", return_value=False) def test_complete_batches_and_acquisition_only(self, slack): - watcher = EnfacePreviewWatcher(self.cfg, self.ident, self.root, "normal") + watcher = EnfacePreviewWatcher(self.cfg, self.ident, self.root, "normal", + batch_previews=True) self.create_tiles(2) self.assertEqual(list(watcher.discover()), [1]) self.create_tiles(4) @@ -161,48 +164,44 @@ def test_complete_batches_and_acquisition_only(self, slack): (self.root / "ret_0004.nii").unlink() self.assertEqual(list(watcher.discover()), [1]) - def test_tilted_grid_and_duplicate_patterns(self): + def test_preview_switches_choose_candidates(self): + make = lambda **kw: EnfacePreviewWatcher(self.cfg, self.ident, self.root, "normal", **kw) + self.assertEqual(make().candidates, [None]) + self.assertEqual(make(batch_previews=True).candidates, [None, 1, 2]) + self.assertEqual(make(acquisition_previews=False, batch_previews=True).candidates, [1, 2]) + self.assertEqual(make(acquisition_previews=False).candidates, []) + + def test_tilted_grid(self): ident = OCTMosaicId(project_name="test", slice_id=1, mosaic_id=2) files = preview.expected_tiles(self.cfg, ident, self.root, "tilted") self.assertEqual(len(files["aip"]), 6) - self.cfg.enface_preview.mip_pattern = self.cfg.enface_preview.aip_pattern - with self.assertRaises(ValueError): - preview.expected_tiles(self.cfg, ident, self.root, "tilted") @patch.object(preview, "slack_notifications_enabled", return_value=False) def test_checkpoint_resume_then_slack(self, slack): self.create_tiles() def stitch(cfg, files, modality, output, batch_id, per_strip=None): output.parent.mkdir(parents=True, exist_ok=True) - output.write_bytes(b"nifti") - output.with_suffix(".jpg").write_bytes(b"jpeg") + output.write_bytes(b"jpeg") with patch.object(preview, "stitch_preview_modality", side_effect=stitch) as stitch_mock, \ patch.object(preview, "upload_multiple_files_to_slack") as upload: preview.preview_enface_batch.fn(self.cfg, self.ident, self.root, "normal", 1) - self.assertEqual(stitch_mock.call_count, 4) + self.assertEqual(stitch_mock.call_count, len(preview.MODALITIES)) upload.assert_not_called() preview.preview_enface_batch.fn(self.cfg, self.ident, self.root, "normal", 1) - self.assertEqual(stitch_mock.call_count, 4) + self.assertEqual(stitch_mock.call_count, len(preview.MODALITIES)) slack.return_value = True upload.side_effect = lambda **kw: {p: True for p in kw["filepaths"]} preview.preview_enface_batch.fn(self.cfg, self.ident, self.root, "normal", 1) preview.preview_enface_batch.fn(self.cfg, self.ident, self.root, "normal", 1) upload.assert_called_once() - self.assertEqual(stitch_mock.call_count, 4) - - def test_disabled_flow_no_io(self): - self.cfg.enface_preview.batch_enabled = False - with patch.object(preview, "stitch_preview_modality") as stitch: - self.assertEqual(preview.preview_enface_batch.fn(self.cfg, self.ident, self.root, "normal", 1), {}) - stitch.assert_not_called() + self.assertEqual(stitch_mock.call_count, len(preview.MODALITIES)) @patch.object(preview, "slack_notifications_enabled", return_value=True) def test_failed_upload_retries_only_missing_modalities(self, slack): self.create_tiles() def stitch(cfg, files, modality, output, batch_id, per_strip=None): output.parent.mkdir(parents=True, exist_ok=True) - output.write_bytes(b"nifti") - output.with_suffix(".jpg").write_bytes(b"jpeg") + output.write_bytes(b"jpeg") with patch.object(preview, "stitch_preview_modality", side_effect=stitch) as stitched, \ patch.object(preview, "upload_multiple_files_to_slack") as upload: upload.side_effect = lambda **kw: {p: not Path(p).stem.endswith("_ret") for p in kw["filepaths"]} @@ -211,15 +210,14 @@ def stitch(cfg, files, modality, output, batch_id, per_strip=None): upload.side_effect = lambda **kw: {p: True for p in kw["filepaths"]} preview.run_preview(self.cfg, self.ident, self.root, "normal", 1) self.assertEqual(len(upload.call_args.kwargs["filepaths"]), 1) - self.assertEqual(stitched.call_count, 4) + self.assertEqual(stitched.call_count, len(preview.MODALITIES)) @patch.object(preview, "slack_notifications_enabled", return_value=False) def test_outputs_in_slice_folder_named_by_mosaic(self, slack): self.create_tiles() def stitch(cfg, files, modality, output, batch_id, per_strip=None): output.parent.mkdir(parents=True, exist_ok=True) - output.write_bytes(b"nifti") - output.with_suffix(".jpg").write_bytes(b"jpeg") + output.write_bytes(b"jpeg") folder = self.root / "out" / "slice-01" / "acquisition_previews" with patch.object(preview, "stitch_preview_modality", side_effect=stitch): result = preview.run_preview(self.cfg, self.ident, self.root, "normal") @@ -231,10 +229,9 @@ def stitch(cfg, files, modality, output, batch_id, per_strip=None): names = {p.name for p in folder.iterdir()} for prefix in ("mosaic_001", "mosaic_001_batch_0002", "mosaic_002"): for m in preview.MODALITIES: - self.assertIn(f"{prefix}_{m}.nii", names) self.assertIn(f"{prefix}_{m}.jpg", names) self.assertIn(f"{prefix}_progress.json", names) - self.assertEqual(len(names), 3 * (2 * len(preview.MODALITIES) + 1)) + self.assertEqual(len(names), 3 * (len(preview.MODALITIES) + 1)) # JPEGs only, no NIfTI def test_changed_input_invalidates_progress(self): self.create_tiles() @@ -252,7 +249,8 @@ def test_changed_input_invalidates_progress(self): def test_polling_waits_for_stability(self, slack): from opticstream.utils.polling_watcher import PollingStableWatcher self.create_tiles(2) - worker = EnfacePreviewWatcher(self.cfg, self.ident, self.root, "normal") + worker = EnfacePreviewWatcher(self.cfg, self.ident, self.root, "normal", + batch_previews=True) with patch.object(worker, "process", return_value=1) as process: poller = PollingStableWatcher(discover_candidates=worker.discover, candidate_key=lambda batch: batch, fingerprint=worker.fingerprint, @@ -267,18 +265,43 @@ def test_polling_waits_for_stability(self, slack): process.assert_called_once_with(1) def test_real_mosaic2d_singleton_nifti(self): + from linc_convert.modalities.psoct import mosaic as linc_mosaic self.create_tiles() files = preview.expected_tiles(self.cfg, self.ident, self.root, "normal") + stitched = {} + real_mosaic2d = linc_mosaic.mosaic2d + + def capture(*args, nifti_output, **kwargs): + # The stitched NIfTI lives only in a scratch dir; read it before cleanup. + real_mosaic2d(*args, nifti_output=nifti_output, **kwargs) + stitched["data"] = nib.load(nifti_output, mmap=False).get_fdata().squeeze() + for modality in ("aip", "ori"): - output = self.root / "stitched" / f"{modality}.nii" - jpeg = preview.stitch_preview_modality.fn(self.cfg, files[modality], modality, output) + output = self.root / "stitched" / f"{modality}.jpg" + with patch.object(linc_mosaic, "mosaic2d", side_effect=capture): + jpeg = preview.stitch_preview_modality.fn(self.cfg, files[modality], modality, output) + self.assertEqual(jpeg, output) self.assertTrue(jpeg.is_file()) - self.assertTrue(output.with_name(f"{modality}_grid.jpg").is_file()) - result = nib.load(output).get_fdata().squeeze() + # Only the JPEG is written next to the previews. + self.assertEqual(sorted(p.name for p in output.parent.iterdir()), + sorted({"aip.jpg", modality + ".jpg"})) + result = stitched["data"] self.assertEqual(result.shape, (16, 12)) - self.assertAlmostEqual(result[3, 3], 1, places=4) + # snake-by-columns / up-right: strip 1 goes up from the bottom-left + # (tile 1 below tile 2), strip 2 comes back down (tile 3 above tile 4). + self.assertAlmostEqual(result[3, 9], 1, places=4) + self.assertAlmostEqual(result[3, 3], 2, places=4) + self.assertAlmostEqual(result[11, 3], 3, places=4) self.assertAlmostEqual(result[11, 9], 4, places=4) + def test_surf_previewed_only_when_mapped(self): + self.assertIn("surf", preview.preview_modalities(self.cfg)) + self.cfg.acquisition.filename_modality_map = {m: m for m in preview.REQUIRED_MODALITIES} + self.assertEqual(preview.preview_modalities(self.cfg), preview.REQUIRED_MODALITIES) + self.assertIsNone(preview.naming_error(self.cfg)) + self.create_tiles() + self.assertNotIn("surf", preview.expected_tiles(self.cfg, self.ident, self.root, "normal")) + if __name__ == "__main__": unittest.main() diff --git a/tests/test_acquisition_sequence.py b/tests/test_acquisition_sequence.py index 0e95b28..c169987 100644 --- a/tests/test_acquisition_sequence.py +++ b/tests/test_acquisition_sequence.py @@ -6,7 +6,6 @@ from unittest.mock import patch from opticstream.cli.oct.watch import OCTWatcherService, build_watch_previews -from opticstream.config.enface_preview import EnfacePreviewConfig from opticstream.config.psoct_scan_config import PSOCTAcquisitionParams from opticstream.utils.acquisition_sequence import AcquisitionSequence @@ -23,8 +22,6 @@ def config(root="/tmp", normal=3, tilted=2, rows=2, pattern="spectral_{image}.ni grid_size_y_tilted=rows_tilted, tile_overlap=0, filename_pattern=pattern, acquisition_mosaic_map={"normal0deg": 1, "tilted15deg": 2}), - enface_preview=EnfacePreviewConfig(batch_enabled=True, grid_config={"grid_type": "column-by-column", "order": "down-right"}, **{ - f"{m}_pattern": f"img_{{image}}_{m}.nii" for m in ("aip", "mip", "ori", "ret")}), ) @@ -116,19 +113,36 @@ def test_fixed_mosaic_ignores_batches_beyond_grid(self): found = self.batches(self.watcher(folder, cfg, fixed_slice_id=1, fixed_mosaic_slot=1)) self.assertEqual([(m, b) for m, b, _ in found], [(1, 1), (1, 2), (1, 3)]) + def test_enface_maps_stay_out_of_spectral_batches(self): + cfg = config(normal=3, tilted=2, rows=2, pattern="img_{image}_{modality}.nii") + with TemporaryDirectory() as folder: + write(folder, [f"img_{i}_{m}.nii" for i in range(1, 5) + for m in ("spectral", "aip", "mip", "ori", "ret")]) + found = self.batches(self.watcher(folder, cfg, sequence=AcquisitionSequence(cfg))) + self.assertEqual(found, [(1, 1, ("img_1_spectral.nii", "img_2_spectral.nii")), + (1, 2, ("img_3_spectral.nii", "img_4_spectral.nii"))]) + + def test_processed_input_keeps_enface_maps_in_batches(self): + cfg = config(normal=3, tilted=2, rows=2, pattern="img_{image}_{modality}.nii") + cfg.acquisition.tile_saving_type = "processed_with_spectral" + with TemporaryDirectory() as folder: + write(folder, [f"img_{i}_{m}.nii" for i in (1, 2) for m in ("spectral", "aip")]) + found = self.batches(self.watcher(folder, cfg, sequence=AcquisitionSequence(cfg))) + self.assertEqual(len(found[0][2]), 4) + class SequencePreviewTests(unittest.TestCase): @patch("opticstream.cli.oct.watch_enface.slack_notifications_enabled", return_value=False) def test_previews_follow_sequence(self, slack): with TemporaryDirectory() as folder: - cfg = config(folder, normal=3, tilted=2, rows=2) + cfg = config(folder, normal=3, tilted=2, rows=2, pattern="img_{image}_{modality}.nii") seq = AcquisitionSequence(cfg) watcher = build_watch_previews(cfg, project_name="p", folder_path=Path(folder), fixed_slice_id=None, fixed_mosaic_slot=None, acquisition=None, slice_offset=0, - stability_seconds=0, poll_interval=1, sequence=seq) + stability_seconds=0, poll_interval=1, sequence=seq, batch_previews=True) worker = watcher.discover_candidates.__self__ maps = lambda images: [f"img_{i}_{m}.nii" for i in images - for m in ("aip", "mip", "ori", "ret")] + for m in ("aip", "mip", "ori", "ret", "surf")] write(folder, maps(range(1, 9))) # mosaic 1 complete + mosaic 2 batch 1 found = list(worker.discover()) self.assertEqual(found, [(1, None), (1, 1), (1, 2), (1, 3), (2, 1)]) diff --git a/tests/test_name_formats.py b/tests/test_name_formats.py new file mode 100644 index 0000000..b7a5939 --- /dev/null +++ b/tests/test_name_formats.py @@ -0,0 +1,38 @@ +"""Default output filename formats pad slice and tile/strip numbers to 4 digits.""" +import unittest +from string import Formatter + +from opticstream.config.lsm_scan_config import LSMScanConfigModel +from opticstream.config.psoct_scan_config import PSOCTScanConfigModel + +NUMBERED = {"slice_id", "tile_id", "strip_id"} + + +def format_defaults(model): + return {name: field.default for name, field in model.model_fields.items() + if name.endswith("_format") and isinstance(field.default, str)} + + +class NameFormatDefaultsTests(unittest.TestCase): + def test_numbers_are_zero_padded_to_four(self): + formats = {**format_defaults(PSOCTScanConfigModel), **format_defaults(LSMScanConfigModel)} + self.assertGreaterEqual(len(formats), 8) + for name, template in formats.items(): + specs = {field: spec for _, field, spec, _ in Formatter().parse(template) + if field in NUMBERED} + with self.subTest(format=name): + self.assertIn("slice_id", specs) + self.assertTrue(all(spec == "04d" for spec in specs.values()), specs) + + def test_rendered_names(self): + psoct = format_defaults(PSOCTScanConfigModel) + self.assertEqual( + psoct["archive_tile_name_format"].format(project_name="p", slice_id=3, tile_id=41, acq="normal"), + "p_slice-0003_tile-0041_acq-normal_OCT.nii.gz") + self.assertEqual( + psoct["mosaic_enface_format"].format(project_name="p", slice_id=3, acq="normal", modality="aip"), + "p_sample-slice0003_acq-normal_proc-aip_OCT.nii.gz") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_oct_input_naming.py b/tests/test_oct_input_naming.py index b81695d..0ff8d9a 100644 --- a/tests/test_oct_input_naming.py +++ b/tests/test_oct_input_naming.py @@ -9,7 +9,7 @@ from opticstream.cli.oct.watch import OCTWatcherService -PATTERN = "sub-{subject}_sample-slice{slice}_chunk-{image}_acq-{acquisition}_{modality}{extension}" +PATTERN = "sub-{subject}_sample-slice{slice}_chunk-{image}_acq-{acq}_{modality}{extension}" class InputNamingTests(unittest.TestCase): @@ -35,14 +35,39 @@ def test_custom_suffix_and_angle(self): self.assertEqual(parsed.modality, "spectral") self.assertIsNone(parse_input_name("unrelated.txt", acq, 2)) - def test_literal_suffix(self): + def test_saved_acquisition_placeholder_becomes_acq(self): acq = self.acquisition(filename_pattern="s{slice}_i{image}_{acquisition}.nii") + self.assertEqual(acq.filename_pattern, "s{slice}_i{image}_{acq}.nii") + self.assertEqual(parse_input_name("s1_i2_tilted15deg.nii", acq, 2).source_mosaic_id, 2) + + def test_pattern_without_extension_matches_data_extensions(self): + acq = self.acquisition(filename_pattern="sub-test_tile-{image}_acq-{acq}_{modality}", + filename_modality_map={"spectral": "spectral", + "processed_surface_finding": "surf"}) + for name, modality in [("sub-test_tile-0011_acq-normal0deg_spectral.nii", "spectral"), + ("sub-test_tile-0011_acq-normal0deg_spectral.nii.gz", "spectral"), + ("sub-test_tile-0011_acq-normal0deg_processed_surface_finding.nii", "surf"), + ("sub-test_tile-0011_acq-tilted15deg_spectral.raw", "spectral")]: + with self.subTest(name=name): + parsed = parse_input_name(name, acq, 2, slice_id=1) + self.assertEqual((parsed.image_index, parsed.modality), (11, modality)) + for name in ("sub-test_tile-0011_acq-normal0deg_spectral", + "sub-test_tile-0011_acq-normal0deg_spectral.nii.bak", + "sub-test_tile-0011_acq-normal0deg_spectral.txt"): + with self.subTest(name=name): + self.assertIsNone(parse_input_name(name, acq, 2, slice_id=1)) + # A literal extension in the pattern is still matched exactly. + literal = self.acquisition(filename_pattern="spectral_{image}.nii") + self.assertIsNone(parse_input_name("spectral_0001.nii.gz", literal, 2)) + + def test_literal_suffix(self): + acq = self.acquisition(filename_pattern="s{slice}_i{image}_{acq}.nii") self.assertEqual(parse_input_name("s1_i2_normal0deg.nii", acq, 2).modality, "spectral") def test_validation_and_legacy_default(self): self.assertIsNone(self.acquisition().filename_pattern) self.assertEqual(self.acquisition(filename_pattern="spectral_{image}.nii").filename_pattern, "spectral_{image}.nii") - for pattern in ("{slice}_{acquisition}.nii", "{slice}_{image}_{acquisition}_{unknown}", "{slice}_{image}_{image}_{acquisition}"): + for pattern in ("{slice}_{acq}.nii", "{slice}_{image}_{acq}_{unknown}", "{slice}_{image}_{image}_{acq}"): with self.assertRaises(ValueError): self.acquisition(filename_pattern=pattern) diff --git a/tests/test_watch_previews.py b/tests/test_watch_previews.py index 44e8606..75cfc61 100644 --- a/tests/test_watch_previews.py +++ b/tests/test_watch_previews.py @@ -7,7 +7,6 @@ from unittest.mock import patch from opticstream.cli.oct.watch import build_watch_previews -from opticstream.config.enface_preview import EnfacePreviewConfig from opticstream.config.psoct_scan_config import PSOCTAcquisitionParams from opticstream.flows.psoct import mosaic_enface_qc_flow as qc from opticstream.state.oct_project_state import OCTMosaicId @@ -15,22 +14,14 @@ from opticstream.utils.polling_watcher import PollingStableWatcher -def scan_config(root, **preview): - preview.setdefault("batch_enabled", True) - preview.setdefault("grid_config", {"grid_type": "column-by-column", "order": "down-right"}) +def scan_config(root, pattern="{acq}_{modality}_{image}.nii"): return SimpleNamespace( project_base_path=Path(root) / "out", mosaics_per_slice=2, - enface_preview=EnfacePreviewConfig( - aip_pattern="{acquisition}_aip_{image}.nii", - mip_pattern="{acquisition}_mip_{image}.nii", - ori_pattern="{acquisition}_ori_{image}.nii", - ret_pattern="{acquisition}_ret_{image}.nii", - **preview, - ), acquisition=PSOCTAcquisitionParams( grid_size_y=2, grid_size_x_normal=2, grid_size_x_tilted=3, tile_overlap=0, acquisition_mosaic_map={"normal0deg": 1, "tilted15deg": 2}, + filename_pattern=pattern, ), ) @@ -56,9 +47,16 @@ def test_needs_slice_and_mosaic(self): self.assertIsNone(self.build(cfg, fixed_slice_id=None)) self.assertIsNone(self.build(cfg, fixed_mosaic_slot=None)) - def test_disabled_in_block(self): - cfg = scan_config(self.root, batch_enabled=False, acquisition_enabled=False) - self.assertIsNone(self.build(cfg)) + def test_disabled_by_flags(self): + cfg = scan_config(self.root) + self.assertIsNone(self.build(cfg, acquisition_previews=False, batch_previews=False)) + worker = self.worker_of(self.build(cfg, acquisition_previews=False, batch_previews=True)) + self.assertEqual(worker.candidates, [1, 2]) + + def test_naming_without_modality_turns_previews_off(self): + # Watching continues without previews rather than failing. + self.assertIsNone(self.build(scan_config(self.root, "{acq}_{image}_spectral.nii"))) + self.assertIsNone(self.build(scan_config(self.root, None))) def test_acquisition_label_and_slice_offset(self): cfg = scan_config(self.root) @@ -100,7 +98,8 @@ def test_acquisition_preview_is_checked_first(self): from opticstream.cli.oct.watch_enface import EnfacePreviewWatcher with TemporaryDirectory() as temp: worker = EnfacePreviewWatcher(scan_config(temp), OCTMosaicId( - project_name="proj", slice_id=1, mosaic_id=1), temp, "normal0deg") + project_name="proj", slice_id=1, mosaic_id=1), temp, "normal0deg", + batch_previews=True) self.assertEqual(worker.candidates, [None, 1, 2]) From bb3aad61b829010af882aea607ad65c3801f63ec Mon Sep 17 00:00:00 2001 From: Noah Markowitz Date: Wed, 30 Sep 2026 16:36:31 -0400 Subject: [PATCH 33/65] update block cli --- docs/reference/cli_commands.md | 2 +- opticstream/cli/oct/setup.py | 40 ++++++++++++++++++++++++++++++---- 2 files changed, 37 insertions(+), 5 deletions(-) diff --git a/docs/reference/cli_commands.md b/docs/reference/cli_commands.md index 8951343..2dae34d 100644 --- a/docs/reference/cli_commands.md +++ b/docs/reference/cli_commands.md @@ -44,7 +44,7 @@ Valid `FLOW_NAME` values for `opticstream deploy` are: |---------|---------| | `opticstream oct setup PROJECT_NAME ...` | Create/update project PS-OCT block and lock. | | `opticstream oct create-lock PROJECT_NAME` | Ensure project-scoped OCT state lock exists. | -| `opticstream oct update-block` | Register/update `PSOCTScanConfig` block type metadata. | +| `opticstream oct update-block [PROJECT...]` | Register the current `PSOCTScanConfig` schema and re-save saved blocks (all, or the named projects) onto it so new fields appear in the Prefect UI. | | `opticstream oct watch PROJECT_NAME FOLDER_PATH [MOSAIC_RANGES] ...` | Watch spectral data and dispatch batch processing (direct or event mode). | | `opticstream oct deploy ...` | Create Prefect deployments from in-repo flow sources. | | `opticstream oct serve register ...` | Serve registration/dependent OCT flows for local execution. | diff --git a/opticstream/cli/oct/setup.py b/opticstream/cli/oct/setup.py index 8754865..547eceb 100644 --- a/opticstream/cli/oct/setup.py +++ b/opticstream/cli/oct/setup.py @@ -63,12 +63,44 @@ def parse_acq_mosaic_map(value: str) -> dict[str, int]: return mapping +def register_block_type() -> None: + """Register the current PSOCTScanConfig block type and schema with Prefect.""" + PSOCTScanConfig.register_type_and_schema() + + @oct_cli.command -def update_block() -> None: +def update_block(*project_names: str) -> None: """ - Update the PSOCTScanConfig block. + Update PSOCTScanConfig blocks to the current schema. + + Registers the current schema, then re-saves each saved block (all of them, + or only ``project_names``) so it uses that schema: new fields get their + defaults and appear in the Prefect UI. Values already set are kept. """ - PSOCTScanConfig.register_type_and_schema() + from prefect.client.orchestration import get_client + + register_block_type() + if project_names: + names = [get_psoct_scan_config_block_name(p) for p in project_names] + else: + with get_client(sync_client=True) as client: + names = sorted( + d.name + for d in client.read_block_documents_by_type( + PSOCTScanConfig.get_block_type_slug() + ) + ) + failed = [] + for name in names: + try: + PSOCTScanConfig.load(name).save(name, overwrite=True) + except Exception as exc: + failed.append(name) + print(f"Could not update block {name}: {exc}") + continue + print(f"Updated block {name}") + if failed: + raise SystemExit(f"{len(failed)} block(s) not updated: {', '.join(failed)}") @oct_cli.command @@ -143,7 +175,7 @@ def setup( ``{subject}``, ``{modality}``, ``{extension}``. Quote it in the shell, e.g. ``'spectral_{image}.nii'``. """ - update_block() + register_block_type() ensure_lock(project_name) block_name = get_psoct_scan_config_block_name(project_name) From 3ce5db4624bd5869229af18da3e83f8d6f1300c5 Mon Sep 17 00:00:00 2001 From: NoahMarkowitz Date: Thu, 1 Oct 2026 13:44:36 -0400 Subject: [PATCH 34/65] change hardcoded file size minimums --- opticstream/flows/psoct/mosaic_volume_stitch_flow.py | 2 +- opticstream/flows/psoct/tile_batch_archive_flow.py | 2 +- opticstream/flows/psoct/tile_batch_processed_validation.py | 4 ++-- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/opticstream/flows/psoct/mosaic_volume_stitch_flow.py b/opticstream/flows/psoct/mosaic_volume_stitch_flow.py index 5b9963e..bcdedf6 100644 --- a/opticstream/flows/psoct/mosaic_volume_stitch_flow.py +++ b/opticstream/flows/psoct/mosaic_volume_stitch_flow.py @@ -65,7 +65,7 @@ def stitch_mosaic_volume_task( crop_focus_plane_offset: int = 30, voxel_size_xyz: Sequence[float] = (0.01, 0.01, 0.0025), circular_mean: bool = False, - zarr_size_threshold: int = 10**9, + zarr_size_threshold: int = 1,#10**9, validate_zarr_output: bool = True, ) -> Path: """ diff --git a/opticstream/flows/psoct/tile_batch_archive_flow.py b/opticstream/flows/psoct/tile_batch_archive_flow.py index 294377b..a6caa48 100644 --- a/opticstream/flows/psoct/tile_batch_archive_flow.py +++ b/opticstream/flows/psoct/tile_batch_archive_flow.py @@ -144,7 +144,7 @@ def emit_batch_complex_archived(batch_id: OCTBatchId, file_list: list[str]) -> N def check_archive_result( batch_id: OCTBatchId, archived_file_paths: list[str], - min_file_size_bytes: int = 200 * 1024 * 1024, + min_file_size_bytes: int = 1 * 1024 * 1024, # 1MB file size ) -> list[str]: logger = get_run_logger() logger.info("Checking if the archived files are valid for %s", batch_id) diff --git a/opticstream/flows/psoct/tile_batch_processed_validation.py b/opticstream/flows/psoct/tile_batch_processed_validation.py index 4a8ed56..769cee7 100644 --- a/opticstream/flows/psoct/tile_batch_processed_validation.py +++ b/opticstream/flows/psoct/tile_batch_processed_validation.py @@ -62,8 +62,8 @@ def validate_processed_batch_outputs( *, mosaic_id: int, config: PSOCTScanConfigModel, - min_volume_file_size_bytes: int = 100 * 1024 * 1024, - min_enface_file_size_bytes: int = 100 * 1024, + min_volume_file_size_bytes: int = 1 * 1024 * 1024, # 1MB + min_enface_file_size_bytes: int = 1 * 1024, # 1KB ) -> None: """ Ensure each tile has the configured processed NIfTIs under ``processed_dir``. From 66be1e8285aaab03a92c6ccf9232664324e5f01e Mon Sep 17 00:00:00 2001 From: NoahMarkowitz Date: Thu, 1 Oct 2026 13:54:35 -0400 Subject: [PATCH 35/65] add --no-batches flag for state show --- opticstream/cli/oct/state.py | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/opticstream/cli/oct/state.py b/opticstream/cli/oct/state.py index bb3df4b..7f91f7e 100644 --- a/opticstream/cli/oct/state.py +++ b/opticstream/cli/oct/state.py @@ -26,41 +26,58 @@ def show( slice: int | None = None, mosaic: int | None = None, batch: int | None = None, + no_batches: Annotated[ + bool, + Parameter( + name=["--no-batches"], + negative="", + help="Omit batch entries, showing only slice and mosaic state.", + ), + ] = False, ) -> None: """ Show OCT project state as pretty JSON. Examples: - opticstream oct state show myproject + - opticstream oct state show myproject --no-batches - opticstream oct state show myproject --slice 1 - opticstream oct state show myproject --slice 1 --mosaic 1 - opticstream oct state show myproject --slice 1 --mosaic 1 --batch 1 """ + if no_batches and batch is not None: + raise ValueError("`--no-batches` cannot be used with `--batch`.") if batch is not None and mosaic is None: raise ValueError("`--mosaic` is required when `--batch` is provided.") if mosaic is not None and slice is None: raise ValueError("`--slice` is required when `--mosaic` is provided.") + # Pydantic exclude specs that drop `batches` at whichever level is shown. + exclude_batches = {"mosaics": {"__all__": {"batches"}}} + exclude = None with OCT_STATE_SERVICE.open_project_by_parts(project_name=project_name) as project: if slice is None: view = project.to_view() + exclude = {"slices": {"__all__": exclude_batches}} elif mosaic is None: slice_state = project.get_slice(slice) if slice_state is None: raise ValueError(f"Slice not found: slice={slice}") view = slice_state.to_view() + exclude = exclude_batches elif batch is None: mosaic_state = project.get_mosaic(slice, mosaic) if mosaic_state is None: raise ValueError(f"Mosaic not found: slice={slice}, mosaic={mosaic}") view = mosaic_state.to_view() + exclude = {"batches"} else: batch_state = project.get_batch(slice, mosaic, batch) if batch_state is None: raise ValueError(f"Batch not found: slice={slice}, mosaic={mosaic}, batch={batch}") view = batch_state.to_view() - print(view.model_dump_json(indent=2)) + print(view.model_dump_json(indent=2, exclude=exclude if no_batches else None)) @oct_state_cli.command From 7e515bc13fbc6b194bd9dc904e679a9bcb979d70 Mon Sep 17 00:00:00 2001 From: NoahMarkowitz Date: Thu, 1 Oct 2026 14:20:59 -0400 Subject: [PATCH 36/65] change x and y descriptors --- opticstream/config/psoct_scan_config.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/opticstream/config/psoct_scan_config.py b/opticstream/config/psoct_scan_config.py index 19cf459..5f455ef 100644 --- a/opticstream/config/psoct_scan_config.py +++ b/opticstream/config/psoct_scan_config.py @@ -111,21 +111,21 @@ def validate_acquisition_mosaic_map(cls, value): ..., ge=1, description=( - "Number of batches (columns) per mosaic for normal illumination (required)" + "Number of batches (rows) per mosaic for normal illumination (required)" ), ) grid_size_x_tilted: int = Field( ..., ge=1, description=( - "Number of batches (columns) per mosaic for tilted illumination (required)" + "Number of batches (rows) per mosaic for tilted illumination (required)" ), ) grid_size_y: int = Field( ..., ge=1, description=( - "Number of tiles per batch (rows) - determines batch size (required). " + "Number of tiles per batch (columns) - determines batch size (required). " "Used for normal illumination, and for tilted unless grid_size_y_tilted is set" ), ) @@ -133,7 +133,7 @@ def validate_acquisition_mosaic_map(cls, value): default=None, ge=1, description=( - "Number of tiles per batch (rows) for tilted illumination; " + "Number of tiles per batch (columns) for tilted illumination; " "unset uses grid_size_y" ), ) From 8f3de12693572ddf27bcdefdf58d017005389400 Mon Sep 17 00:00:00 2001 From: NoahMarkowitz Date: Fri, 2 Oct 2026 13:55:06 -0400 Subject: [PATCH 37/65] some adjustments --- docs/oct_input_naming.md | 43 +++-- opticstream/cli/oct/watch.py | 84 ++++++++-- opticstream/cli/oct/watch_enface.py | 2 +- .../flows/psoct/tile_batch_archive_flow.py | 1 + .../flows/psoct/tile_batch_process_flow.py | 1 + .../flows/psoct/tile_file_reference.py | 30 +++- opticstream/state/oct_project_state.py | 56 +++++++ opticstream/utils/acquisition_sequence.py | 147 +++++++++++++++++- opticstream/utils/oct_input_naming.py | 2 + tests/test_acquisition_sequence.py | 141 ++++++++++++++++- 10 files changed, 470 insertions(+), 37 deletions(-) diff --git a/docs/oct_input_naming.md b/docs/oct_input_naming.md index 0a49974..8ffa55f 100644 --- a/docs/oct_input_naming.md +++ b/docs/oct_input_naming.md @@ -35,11 +35,11 @@ with overlapping slice/tile IDs in the same watched directory. If the scanner only numbers its output (`spectral_0001.nii`, `spectral_0002.nii`, ...), set `"filename_pattern": "spectral_{image}.nii"`. The numbers are then one -continuous sequence across mosaics and slices, and `--slice`/`--mosaic` say where -image 1 starts (both default to 1): +continuous sequence across mosaics and slices. A new project starts at slice 1 +mosaic 1, so no options are needed: ```bash -ops oct watch myproject /path/to/scanner/output --slice 1 --mosaic 1 +ops oct watch myproject /path/to/scanner/output ``` With 22 x 16 grids for both illuminations, that places: @@ -52,15 +52,40 @@ With 22 x 16 grids for both illuminations, that places: | ... | ... | ... | Each mosaic holds `grid_size_x * grid_size_y` tiles, using `grid_size_x_normal` or -`grid_size_x_tilted` (and `grid_size_y_tilted`, when set) for its illumination, and its tiles are renumbered from 1. After -the slice's last mosaic the sequence continues with mosaic 1 of the next slice. -Placement depends only on the image number, so restarting the watcher is safe. +`grid_size_x_tilted` (and `grid_size_y_tilted`, when set) for its illumination, and +its tiles are renumbered from 1. After the slice's last mosaic the sequence +continues with mosaic 1 of the next slice. + +### Where the sequence starts is saved in project state + +The watcher records which image is tile 1 of which slice/mosaic, and in which +folder (`sequence_anchor`, shown by `ops oct state show`). On each start: + +- **No `--slice`/`--mosaic`, same folder:** resume the saved start. Restarting + the watcher is safe; batches already in project state are skipped. +- **No `--slice`/`--mosaic`, new folder:** continue with the mosaic after the last + one recorded in project state, starting at the folder's lowest image number + (1 if it is empty). +- **`--slice S --mosaic M`:** restart there. Slice S mosaic M and every later mosaic + are cleared from project state, so they are processed, archived and stitched + again. For example `--slice 5 --mosaic 2` redoes slice 5 mosaic 2, and the next + mosaic after it is slice 6 mosaic 1. + +When restarting, the first new file is taken to be: + +- in the folder already in use: the image after the highest number present (the + scanner kept counting; older files are ignored); +- in a new folder: its lowest image number, or image 1 if it is empty. + +Pass `--start-image N` when that guess is wrong, e.g. the scanner restarted at 1 in +the same folder and has already written some files. Running the same +`--slice`/`--mosaic` again on the same folder resumes rather than clearing again; +add `--start-image` to redo that mosaic once more. `--mosaic` is the mosaic's position within its slice (1..`mosaics_per_slice`, e.g. 1 = normal, 2 = tilted), not a global mosaic id. `--acquisition` may name that -position by its `acquisition_mosaic_map` label instead; you never need both. To -start a folder partway through, e.g. with the tilted mosaic of slice 3, pass -`--slice 3 --mosaic 2`. `--slice-offset` still shifts the resulting slice numbers. +position by its `acquisition_mosaic_map` label instead; you never need both. +`--slice-offset` still shifts the resulting slice numbers. A batch number beyond a mosaic's `grid_size_x` is never dispatched (it is logged and ignored), whatever the naming. diff --git a/opticstream/cli/oct/watch.py b/opticstream/cli/oct/watch.py index 095cd3b..0ca2b6f 100644 --- a/opticstream/cli/oct/watch.py +++ b/opticstream/cli/oct/watch.py @@ -30,8 +30,8 @@ extract_processed_index_from_filename, extract_spectral_index_from_filename, ) -from opticstream.utils.acquisition_sequence import AcquisitionSequence -from opticstream.utils.oct_input_naming import pattern_names_mosaic +from opticstream.utils.acquisition_sequence import AcquisitionSequence, start_sequence +from opticstream.utils.oct_input_naming import compile_pattern, pattern_names_mosaic from opticstream.utils.polling_watcher import PollingStableWatcher from opticstream.utils.refresh_disk import RefreshHook, resolve_refresh_hook @@ -824,6 +824,46 @@ def build_watch_previews( ) +def _sequence_images(folder: Path, pattern: str) -> set[int]: + """Image numbers of the files in ``folder`` that match ``pattern``.""" + regex = compile_pattern(pattern) + images: set[int] = set() + for path in folder.iterdir(): + match = regex.fullmatch(path.name) + if match is not None and path.is_file(): + images.add(int(match.group("image"))) + return images + + +def load_sequence( + project_name: str, + scan_config: PSOCTScanConfigModel, + folder: Path, + *, + slice_id: int | None, + mosaic_slot: int | None, + start_image: int | None, + slice_offset: int, +) -> AcquisitionSequence: + """Resolve and save the continuous-numbering start in project state (see start_sequence).""" + folder_key = os.path.normcase(str(folder.resolve())) + images = _sequence_images(folder, scan_config.acquisition.filename_pattern) + with OCT_STATE_SERVICE.open_project_by_parts(project_name=project_name) as project: + sequence, notes = start_sequence( + project, + scan_config, + folder_key, + images, + slice_id=slice_id, + mosaic_slot=mosaic_slot, + start_image=start_image, + slice_offset=slice_offset, + ) + for note in notes: + logger.info("%s", note) + return sequence + + def watch_oct( *, project_name: str, @@ -889,6 +929,7 @@ def watch( slice: int | None = None, acquisition: str | None = None, mosaic: int | None = None, + start_image: int | None = None, previews: bool = True, batch_previews: bool = False, verbose: bool = False, @@ -912,10 +953,19 @@ def watch( its acquisition.acquisition_mosaic_map label instead of --mosaic. When acquisition.filename_pattern has no {slice} or {acq} (e.g. - "spectral_{image}.nii"), image numbers are one continuous sequence: image 1 is - the start mosaic (default slice 1, mosaic 1), and after that mosaic's - grid_size_x * grid_size_y tiles the sequence continues into the next mosaic - and then the next slice, each sized by its own grid. + "spectral_{image}.nii"), image numbers are one continuous sequence: after a + mosaic's grid_size_x * grid_size_y tiles it continues into the next mosaic and + then the next slice, each sized by its own grid. Where it starts is saved in + project state: + - without --slice/--mosaic the watcher resumes the saved start for this + folder; a new project starts at slice 1 mosaic 1, and a new folder continues + with the mosaic after the last one in project state. + - --slice/--mosaic restart there: that mosaic and every later one are cleared + from project state and redone, e.g. --slice 5 --mosaic 2 redoes slice 5 + mosaic 2 and the next mosaic is slice 6 mosaic 1. The new files start after + the highest image already in a folder in use, or at the lowest image of a new + folder; --start-image N says otherwise. Rerunning the same --slice/--mosaic on + the same folder resumes rather than clearing again. When filenames contain {slice}/{acq}, the names place each tile and --slice/--mosaic only filter which tiles this watcher handles. @@ -951,18 +1001,22 @@ def watch( sequence = None filename_pattern = scan_config.acquisition.filename_pattern if filename_pattern and not pattern_names_mosaic(filename_pattern): - sequence = AcquisitionSequence( + sequence = load_sequence( + project_name, scan_config, - start_slice=fixed_slice_id or 1, - start_mosaic=fixed_mosaic_slot or 1, - ) - logger.info( - "Continuous numbering: image 1 is slice %s mosaic %s; mosaic sizes %s tiles", - sequence.start_slice, - sequence.start_mosaic, - sequence.sizes, + watch_path, + slice_id=fixed_slice_id, + mosaic_slot=fixed_mosaic_slot, + start_image=start_image, + slice_offset=slice_offset, ) + logger.info("Continuous numbering; mosaic sizes %s tiles", sequence.sizes) fixed_slice_id = fixed_mosaic_slot = None + elif start_image is not None: + raise ValueError( + "--start-image only applies to continuously numbered files " + "(filename_pattern without {slice} or {acq})." + ) elif (fixed_slice_id, fixed_mosaic_slot) != (None, None): if scan_config.mosaics_per_slice == 3 and not filename_pattern: raise ValueError( diff --git a/opticstream/cli/oct/watch_enface.py b/opticstream/cli/oct/watch_enface.py index 883b557..c10955a 100644 --- a/opticstream/cli/oct/watch_enface.py +++ b/opticstream/cli/oct/watch_enface.py @@ -110,7 +110,7 @@ def _worker(self, position): def _positions(self, last_image): """Start of each mosaic from the sequence start through ``last_image``.""" - image = 1 + image = self.sequence.start_image while image <= last_image: position = self.sequence.locate(image) yield position diff --git a/opticstream/flows/psoct/tile_batch_archive_flow.py b/opticstream/flows/psoct/tile_batch_archive_flow.py index a6caa48..24af69f 100644 --- a/opticstream/flows/psoct/tile_batch_archive_flow.py +++ b/opticstream/flows/psoct/tile_batch_archive_flow.py @@ -198,6 +198,7 @@ def archive_tile_batch_flow( file_list, config=config, mosaic_context=mosaic_context, + batch_id=batch_id.batch_id, ) archive_tile_batch( batch_id=batch_id, diff --git a/opticstream/flows/psoct/tile_batch_process_flow.py b/opticstream/flows/psoct/tile_batch_process_flow.py index 8d48b6b..aa53551 100644 --- a/opticstream/flows/psoct/tile_batch_process_flow.py +++ b/opticstream/flows/psoct/tile_batch_process_flow.py @@ -258,6 +258,7 @@ def process_tile_batch( file_list, config=config, mosaic_context=mosaic_context, + batch_id=batch_id.batch_id, ) file_reference_list = list(file_reference_list.values()) diff --git a/opticstream/flows/psoct/tile_file_reference.py b/opticstream/flows/psoct/tile_file_reference.py index 5f723c7..f38ec34 100644 --- a/opticstream/flows/psoct/tile_file_reference.py +++ b/opticstream/flows/psoct/tile_file_reference.py @@ -39,17 +39,43 @@ def build_tile_file_reference_list( *, config: PSOCTScanConfigModel, mosaic_context: MosaicContext, + batch_id: int | None = None, ) -> dict[int, TileFileReference]: + """ + Group a batch's input files by tile number. + + For continuously numbered names (filename_pattern without {slice}/{acq}) the + image number is not the tile number within the mosaic; with ``batch_id`` the + batch's lowest image becomes tile ``(batch_id - 1) * grid_size_y + 1``. This + assumes the batch's images are consecutive from its first tile, as the watcher + dispatches them. + """ mosaics_per_slice = config.mosaics_per_slice grid_size_x = mosaic_context.grid_size_x(config) refs: dict[int, TileFileReference] = defaultdict(TileFileReference) + tile_shift = 0 + pattern = config.acquisition.filename_pattern + if pattern and batch_id is not None: + from opticstream.utils.oct_input_naming import parse_input_name, pattern_names_mosaic + if not pattern_names_mosaic(pattern): + parsed_images = [ + parsed.image_index + for parsed in ( + parse_input_name(p.name, config.acquisition, mosaics_per_slice) + for p in file_list + ) + if parsed is not None + ] + if parsed_images: + first_tile = (batch_id - 1) * mosaic_context.grid_size_y(config) + 1 + tile_shift = first_tile - min(parsed_images) for p in file_list: - if config.acquisition.filename_pattern: + if pattern: from opticstream.utils.oct_input_naming import parse_input_name parsed = parse_input_name(p.name, config.acquisition, mosaics_per_slice) if parsed is None: raise ValueError(f"Filename does not match configured input naming: {p.name}") - tile_number = parsed.image_index + tile_number = parsed.image_index + tile_shift modality = parsed.modality if modality == "processed": modality = "complex" if config.acquisition.tile_saving_type in (TileSavingType.COMPLEX_WITH_SPECTRAL, TileSavingType.COMPLEX) else "dbi" diff --git a/opticstream/state/oct_project_state.py b/opticstream/state/oct_project_state.py index 979ca59..ff861c2 100644 --- a/opticstream/state/oct_project_state.py +++ b/opticstream/state/oct_project_state.py @@ -114,6 +114,12 @@ def mark_failed(self) -> None: self.processing_finished_at = now self.updated_at = now + def mark_pending(self) -> None: + self.processing_state = ProcessingState.PENDING + self.processing_started_at = None + self.processing_finished_at = None + self.touch() + class OCTBatchStateView(OCTStateView): """ @@ -344,12 +350,36 @@ def reset_uploaded(self) -> None: self.touch() +class OCTSequenceAnchor(BaseModel): + """ + Where continuous image numbering (e.g. ``spectral_{image}.nii``) starts. + + Written by ``ops oct watch``: ``start_image`` in ``folder`` is tile 1 of + ``mosaic_slot`` (position within the slice) of ``slice_id``, both before + ``--slice-offset`` is applied. Images numbered below ``start_image`` are ignored. + """ + + model_config = ConfigDict(frozen=True) + + folder: str + start_image: int = Field(default=1, ge=1) + slice_id: int = Field(..., ge=1) + mosaic_slot: int = Field(..., ge=1) + created_at: datetime = Field(default_factory=datetime.now) + + class OCTProjectStateView(OCTStateView): """ Readonly view of the entire persisted OCT state for one project. """ slices: dict[int, OCTSliceStateView] = Field(default_factory=dict) + sequence_anchor: OCTSequenceAnchor | None = None + + def last_mosaic_id(self) -> int | None: + """Highest mosaic id with at least one batch recorded, or None.""" + ids = [mosaic.mosaic_id for mosaic in self.iter_mosaics() if mosaic.batches] + return max(ids, default=None) def get_batch( self, @@ -453,6 +483,32 @@ def delete_batch(self, slice_id: int, mosaic_id: int, batch_id: int) -> bool: self.touch() return True + def clear_from_mosaic(self, slice_id: int, mosaic_id: int) -> list[tuple[int, int]]: + """ + Delete mosaic ``mosaic_id`` and every later mosaic and slice. + + Mosaic ids are global, so "later" means a higher mosaic id. When earlier + mosaics of ``slice_id`` remain, that slice's registration/upload flags and + status are reset since it must be registered again. Returns the deleted + ``(slice_id, mosaic_id)`` pairs. + """ + removed: list[tuple[int, int]] = [] + for sid in sorted(self.slices): + if sid < slice_id: + continue + slice_state = self.slices[sid] + doomed = sorted(m for m in slice_state.mosaics if sid > slice_id or m >= mosaic_id) + for mid in doomed: + del slice_state.mosaics[mid] + removed.append((sid, mid)) + if sid > slice_id or not slice_state.mosaics: + del self.slices[sid] + elif doomed: + slice_state.reset_registered() + slice_state.mark_pending() + self.touch() + return removed + def _get_slice_view( state: OCTProjectState, diff --git a/opticstream/utils/acquisition_sequence.py b/opticstream/utils/acquisition_sequence.py index 3c63f59..2b46cf2 100644 --- a/opticstream/utils/acquisition_sequence.py +++ b/opticstream/utils/acquisition_sequence.py @@ -8,9 +8,16 @@ """ from __future__ import annotations +from collections.abc import Collection from dataclasses import dataclass -from opticstream.flows.psoct.utils import mosaic_context_from_ids +from opticstream.flows.psoct.utils import ( + logical_mosaic_from_source_mosaic, + mosaic_context_from_ids, + mosaic_position_in_slice, + slice_from_mosaic, +) +from opticstream.state.oct_project_state import OCTSequenceAnchor @dataclass(frozen=True) @@ -28,12 +35,19 @@ def source_mosaic_id(self) -> int: class AcquisitionSequence: """Map continuous image numbers (1-based) to slice/mosaic/tile. - ``start_slice``/``start_mosaic`` place image 1: e.g. start_slice=3, - start_mosaic=2 means the folder starts with the tilted mosaic of slice 3. - ``start_mosaic`` is the mosaic's position within its slice. + ``start_slice``/``start_mosaic`` place ``start_image`` (default 1): e.g. + start_slice=3, start_mosaic=2 means that image is tile 1 of the tilted mosaic + of slice 3. ``start_mosaic`` is the mosaic's position within its slice. Images + numbered below ``start_image`` belong to an earlier run and are not placed. """ - def __init__(self, scan_config, start_slice: int = 1, start_mosaic: int = 1) -> None: + def __init__( + self, + scan_config, + start_slice: int = 1, + start_mosaic: int = 1, + start_image: int = 1, + ) -> None: self.mosaics_per_slice = scan_config.mosaics_per_slice if start_slice < 1: raise ValueError(f"start slice must be >= 1, got {start_slice}") @@ -42,8 +56,11 @@ def __init__(self, scan_config, start_slice: int = 1, start_mosaic: int = 1) -> f"start mosaic must be between 1 and {self.mosaics_per_slice} " f"(its position within the slice), got {start_mosaic}" ) + if start_image < 1: + raise ValueError(f"start image must be >= 1, got {start_image}") self.start_slice = start_slice self.start_mosaic = start_mosaic + self.start_image = start_image self.sizes = {} for slot in range(1, self.mosaics_per_slice + 1): context = mosaic_context_from_ids( @@ -52,10 +69,13 @@ def __init__(self, scan_config, start_slice: int = 1, start_mosaic: int = 1) -> self.sizes[slot] = context.grid_size_x(scan_config) * context.grid_size_y(scan_config) self.slice_total = sum(self.sizes.values()) - def locate(self, image: int) -> SequencePosition: + def locate(self, image: int) -> SequencePosition | None: + """Position of ``image``, or None if it precedes ``start_image``.""" if image < 1: raise ValueError(f"image number must be >= 1, got {image}") - remaining = image - 1 + if image < self.start_image: + return None + remaining = image - self.start_image for slot in range(self.start_mosaic, self.mosaics_per_slice + 1): if remaining < self.sizes[slot]: return self._position(self.start_slice, slot, remaining + 1) @@ -80,7 +100,118 @@ def first_image(self, slice_id: int, mosaic_slot: int) -> int | None: + (slice_id - self.start_slice - 1) * self.slice_total + sum(self.sizes[s] for s in range(1, mosaic_slot)) ) - return before + 1 + return before + self.start_image def _position(self, slice_id: int, slot: int, tile: int) -> SequencePosition: return SequencePosition(slice_id, slot, tile, self.mosaics_per_slice) + + +def start_sequence( + project, + scan_config, + folder: str, + images: Collection[int], + *, + slice_id: int | None = None, + mosaic_slot: int | None = None, + start_image: int | None = None, + slice_offset: int = 0, +) -> tuple[AcquisitionSequence, list[str]]: + """ + Decide where continuous numbering starts, using the anchor saved in project state. + + ``project`` is the mutable OCT project state and is updated in place; ``images`` + are the image numbers currently in ``folder``. Returns the sequence and log notes. + + - No ``slice_id``/``mosaic_slot``: resume the saved anchor for this folder. A new + folder continues with the mosaic after the last one recorded in project state, + starting at its lowest image number (1 if empty). + - ``slice_id``/``mosaic_slot`` (each defaults to 1): reset. That mosaic and every + later one are cleared from project state and redone; numbering restarts there. + ``start_image`` defaults to the image after the highest one in the folder when + the folder is the one already in use (the scanner kept counting), otherwise to + its lowest image (1 if empty). Repeating the saved slice/mosaic in the same + folder without ``start_image`` resumes instead, so rerunning a command does + not clear state twice. + """ + mps = scan_config.mosaics_per_slice + anchor = project.sequence_anchor + same_folder = anchor is not None and anchor.folder == folder + last_mosaic = project.last_mosaic_id() + notes: list[str] = [] + + def describe(mosaic_id: int) -> str: + return (f"slice {slice_from_mosaic(mosaic_id, mps)} " + f"mosaic {mosaic_position_in_slice(mosaic_id, mps)}") + + if slice_id is None and mosaic_slot is None: + if start_image is not None: + raise ValueError( + "--start-image needs --slice/--mosaic: it is the image number of " + "that mosaic's first tile." + ) + if same_folder: + notes.append("Resuming saved sequence start for this folder.") + elif anchor is None: + # Projects processed before anchors were saved placed image 1 at slice 1 + # mosaic 1; keep that for them. + first = 1 if last_mosaic is not None else min(images, default=1) + anchor = OCTSequenceAnchor(folder=folder, start_image=first, slice_id=1, + mosaic_slot=1) + notes.append("No saved sequence start; starting at slice 1 mosaic 1.") + else: + if last_mosaic is None: + target = (anchor.slice_id, anchor.mosaic_slot) + reason = "nothing has been processed yet" + else: + logical_slice = slice_from_mosaic(last_mosaic + 1, mps) + target = (logical_slice - slice_offset, + mosaic_position_in_slice(last_mosaic + 1, mps)) + if target[0] < 1: + raise ValueError( + f"--slice-offset {slice_offset} puts the next mosaic before slice 1; " + "pass --slice/--mosaic." + ) + reason = f"the last mosaic in project state is {describe(last_mosaic)}" + anchor = OCTSequenceAnchor(folder=folder, start_image=min(images, default=1), + slice_id=target[0], mosaic_slot=target[1]) + notes.append(f"New folder; continuing at slice {target[0]} mosaic {target[1]} " + f"({reason}).") + else: + target = (slice_id or 1, mosaic_slot or 1) + if (start_image is None and same_folder + and (anchor.slice_id, anchor.mosaic_slot) == target): + notes.append( + f"This folder already restarted at slice {target[0]} mosaic {target[1]}; " + "resuming without clearing state. Pass --start-image to redo it again." + ) + else: + if start_image is None: + if same_folder: + start_image = max(images, default=0) + 1 + elif anchor is None and last_mosaic is not None and images: + raise ValueError( + "This project has state from before the watcher saved where " + "numbering starts, so it is unclear which files in this folder " + f"belong to slice {target[0]} mosaic {target[1]}. Pass " + "--start-image N, the image number of its first tile." + ) + else: + start_image = min(images, default=1) + source_mosaic = (target[0] - 1) * mps + target[1] + logical_slice, logical_mosaic = logical_mosaic_from_source_mosaic( + source_mosaic, mosaics_per_slice=mps, slice_offset=slice_offset + ) + removed = project.clear_from_mosaic(logical_slice, logical_mosaic) + cleared = ", ".join(describe(mid) for _, mid in removed) or "nothing recorded yet" + notes.append(f"Cleared project state from {describe(logical_mosaic)} onward: " + f"{cleared}.") + anchor = OCTSequenceAnchor(folder=folder, start_image=start_image, + slice_id=target[0], mosaic_slot=target[1]) + + project.sequence_anchor = anchor + notes.append(f"Image {anchor.start_image} is tile 1 of slice {anchor.slice_id} " + f"mosaic {anchor.mosaic_slot}; lower image numbers are ignored.") + sequence = AcquisitionSequence(scan_config, anchor.slice_id, anchor.mosaic_slot, + anchor.start_image) + return sequence, notes diff --git a/opticstream/utils/oct_input_naming.py b/opticstream/utils/oct_input_naming.py index b57d8f4..b5371c7 100644 --- a/opticstream/utils/oct_input_naming.py +++ b/opticstream/utils/oct_input_naming.py @@ -85,6 +85,8 @@ def parse_input_name(name, acquisition, mosaics_per_slice, *, slice_id=None, mos if modality is None: return None position = sequence.locate(image) + if position is None: # numbered before the sequence's start image + return None return InputTile(position.source_mosaic_id, position.tile, modality) slot = mosaic_slot if "acq" in values: diff --git a/tests/test_acquisition_sequence.py b/tests/test_acquisition_sequence.py index c169987..0009b96 100644 --- a/tests/test_acquisition_sequence.py +++ b/tests/test_acquisition_sequence.py @@ -7,7 +7,10 @@ from opticstream.cli.oct.watch import OCTWatcherService, build_watch_previews from opticstream.config.psoct_scan_config import PSOCTAcquisitionParams -from opticstream.utils.acquisition_sequence import AcquisitionSequence +from opticstream.flows.psoct.tile_file_reference import build_tile_file_reference_list +from opticstream.flows.psoct.utils import mosaic_context_from_ids +from opticstream.state.oct_project_state import OCTProjectState, OCTSequenceAnchor +from opticstream.utils.acquisition_sequence import AcquisitionSequence, start_sequence BIG = 100 * 1024 # the watcher ignores files smaller than 100 KB @@ -62,10 +65,133 @@ def test_unequal_grids_and_start_position(self): self.assertIsNone(seq.first_image(5, 1)) def test_invalid_start(self): - for kwargs in ({"start_slice": 0}, {"start_mosaic": 3}, {"start_mosaic": 0}): + for kwargs in ({"start_slice": 0}, {"start_mosaic": 3}, {"start_mosaic": 0}, + {"start_image": 0}): with self.assertRaises(ValueError): AcquisitionSequence(config(), **kwargs) + def test_start_image_shifts_numbering(self): + # Scanner kept counting: image 21 is tile 1 of slice 5 mosaic 2. + seq = AcquisitionSequence(config(normal=3, tilted=2, rows=2), start_slice=5, + start_mosaic=2, start_image=21) + self.assertIsNone(seq.locate(20)) + where = lambda i: (lambda p: (p.slice_id, p.mosaic_slot, p.tile))(seq.locate(i)) + self.assertEqual([where(i) for i in (21, 24, 25, 31)], + [(5, 2, 1), (5, 2, 4), (6, 1, 1), (6, 2, 1)]) + self.assertEqual(seq.first_image(6, 1), 25) + + +def project(*mosaics): + """Project state with one batch in each (slice_id, mosaic_id).""" + state = OCTProjectState() + for slice_id, mosaic_id in mosaics: + state.get_or_create_batch(slice_id, mosaic_id, 1) + return state + + +class ProjectClearTests(unittest.TestCase): + def test_clear_from_second_mosaic_keeps_first_and_resets_slice(self): + state = project((4, 7), (4, 8), (5, 9), (5, 10), (6, 11)) + state.slices[5].set_registered(True) + removed = state.clear_from_mosaic(5, 10) + self.assertEqual(removed, [(5, 10), (6, 11)]) + self.assertEqual(sorted(state.slices), [4, 5]) + self.assertEqual(list(state.slices[5].mosaics), [9]) + self.assertFalse(state.slices[5].registered) + self.assertEqual(sorted(state.slices[4].mosaics), [7, 8]) + + def test_clear_from_first_mosaic_drops_slice(self): + state = project((5, 9), (5, 10)) + self.assertEqual(state.clear_from_mosaic(5, 9), [(5, 9), (5, 10)]) + self.assertEqual(state.slices, {}) + self.assertEqual(state.last_mosaic_id(), None) + + +class StartSequenceTests(unittest.TestCase): + cfg = config(normal=3, tilted=2, rows=2) # mosaic 1: 6 tiles, mosaic 2: 4 tiles + + def start(self, state, images, folder="/scan/a", **kwargs): + seq, _ = start_sequence(state, self.cfg, folder, set(images), **kwargs) + anchor = state.sequence_anchor + return seq, (anchor.folder, anchor.start_image, anchor.slice_id, anchor.mosaic_slot) + + def test_new_project_starts_at_slice_one(self): + state = project() + _, anchor = self.start(state, range(1, 5)) + self.assertEqual(anchor, ("/scan/a", 1, 1, 1)) + + def test_resumes_saved_start_for_same_folder(self): + state = project((1, 1)) + state.sequence_anchor = OCTSequenceAnchor(folder="/scan/a", start_image=7, + slice_id=3, mosaic_slot=2) + seq, anchor = self.start(state, range(1, 30)) + self.assertEqual(anchor[1:], (7, 3, 2)) + self.assertEqual(list(state.slices), [1]) # nothing cleared + + def test_reset_in_same_folder_continues_after_highest_image(self): + state = project((5, 9), (5, 10), (6, 11)) + state.sequence_anchor = OCTSequenceAnchor(folder="/scan/a", slice_id=1, mosaic_slot=1) + seq, anchor = self.start(state, range(1, 21), slice_id=5, mosaic_slot=2) + self.assertEqual(anchor, ("/scan/a", 21, 5, 2)) + self.assertEqual(list(state.slices[5].mosaics), [9]) + self.assertNotIn(6, state.slices) + # Slice 5 mosaic 2 is redone (4 tiles), then the next mosaic is slice 6 mosaic 1. + self.assertEqual((seq.locate(21).slice_id, seq.locate(21).mosaic_slot), (5, 2)) + self.assertEqual((seq.locate(25).slice_id, seq.locate(25).mosaic_slot), (6, 1)) + self.assertIsNone(seq.locate(20)) + + def test_repeating_same_reset_resumes_instead_of_clearing(self): + state = project((5, 10)) + state.sequence_anchor = OCTSequenceAnchor(folder="/scan/a", start_image=21, + slice_id=5, mosaic_slot=2) + _, anchor = self.start(state, range(1, 26), slice_id=5, mosaic_slot=2) + self.assertEqual(anchor[1:], (21, 5, 2)) + self.assertIn(10, state.slices[5].mosaics) + # --start-image forces a fresh reset of the same mosaic. + _, anchor = self.start(state, range(1, 26), slice_id=5, mosaic_slot=2, start_image=26) + self.assertEqual(anchor[1:], (26, 5, 2)) + self.assertNotIn(5, state.slices) + + def test_reset_in_new_folder_starts_at_its_lowest_image(self): + state = project((5, 10)) + state.sequence_anchor = OCTSequenceAnchor(folder="/scan/a", slice_id=1, mosaic_slot=1) + _, anchor = self.start(state, [1, 2, 3], folder="/scan/b", slice_id=5, mosaic_slot=2) + self.assertEqual(anchor, ("/scan/b", 1, 5, 2)) + _, anchor = self.start(state, [], folder="/scan/c", slice_id=7, mosaic_slot=1) + self.assertEqual(anchor, ("/scan/c", 1, 7, 1)) + + def test_new_folder_continues_after_last_mosaic_in_state(self): + state = project((5, 9), (5, 10)) + state.sequence_anchor = OCTSequenceAnchor(folder="/scan/a", slice_id=1, mosaic_slot=1) + _, anchor = self.start(state, [], folder="/scan/b") + self.assertEqual(anchor, ("/scan/b", 1, 6, 1)) + state = project((5, 9)) + state.sequence_anchor = OCTSequenceAnchor(folder="/scan/a", slice_id=1, mosaic_slot=1) + _, anchor = self.start(state, [], folder="/scan/b") + self.assertEqual(anchor[2:], (5, 2)) + + def test_unanchored_project_with_state_needs_start_image(self): + state = project((1, 1)) + with self.assertRaises(ValueError): + self.start(state, range(1, 10), slice_id=5, mosaic_slot=2) + _, anchor = self.start(state, range(1, 10), slice_id=5, mosaic_slot=2, start_image=4) + self.assertEqual(anchor[1:], (4, 5, 2)) + + def test_start_image_requires_slice_or_mosaic(self): + with self.assertRaises(ValueError): + self.start(project(), [], start_image=5) + + +class TileNumberTests(unittest.TestCase): + def test_continuous_names_numbered_within_mosaic(self): + cfg = config(normal=22, tilted=22, rows=16) + context = mosaic_context_from_ids(slice_id=1, mosaic_id=2, mosaics_per_slice=2) + files = [Path(f"/scan/spectral_{i:04d}.nii") for i in range(369, 385)] + refs = build_tile_file_reference_list(files, config=cfg, mosaic_context=context, + batch_id=2) + self.assertEqual(sorted(refs), list(range(17, 33))) + self.assertEqual(refs[17].spectral_file_path.name, "spectral_0369.nii") + class WatcherSequenceTests(unittest.TestCase): def watcher(self, folder, cfg, **kwargs): @@ -106,6 +232,17 @@ def test_tilted_batches_use_grid_size_y_tilted(self): [(1, 1, 2), (1, 2, 2), (2, 1, 3), (2, 2, 3)]) self.assertEqual(found[3][2], ("spectral_0008.nii", "spectral_0009.nii", "spectral_0010.nii")) + def test_files_before_start_image_are_ignored(self): + cfg = config(normal=3, tilted=2, rows=2) + with TemporaryDirectory() as folder: + write(folder, [f"spectral_{i:04d}.nii" for i in range(1, 27)]) + seq = AcquisitionSequence(cfg, start_slice=5, start_mosaic=2, start_image=21) + found = self.batches(self.watcher(folder, cfg, sequence=seq)) + # Images 21-24 redo slice 5 mosaic 2 (mosaic 10); 25-26 start slice 6 (mosaic 11). + self.assertEqual([(m, b, files[0]) for m, b, files in found], + [(10, 1, "spectral_0021.nii"), (10, 2, "spectral_0023.nii"), + (11, 1, "spectral_0025.nii")]) + def test_fixed_mosaic_ignores_batches_beyond_grid(self): cfg = config(normal=3, tilted=2, rows=2) with TemporaryDirectory() as folder: From cc8210874c3bc5b96f026f72fad8d780baa7820a Mon Sep 17 00:00:00 2001 From: NoahMarkowitz Date: Fri, 16 Oct 2026 11:58:40 -0400 Subject: [PATCH 38/65] many updates --- docs/developer/cli_overview.md | 2 + docs/oct_input_naming.md | 33 ++- docs/reference/cli_commands.md | 2 + opticstream/cli/oct/__init__.py | 3 +- opticstream/cli/oct/run.py | 153 ++++++++++++ opticstream/cli/oct/setup.py | 9 +- opticstream/cli/oct/state.py | 90 ++++++++ opticstream/cli/oct/watch.py | 53 +++++ opticstream/config/psoct_scan_config.py | 20 +- .../flows/psoct/mosaic_process_flow.py | 2 +- .../flows/psoct/mosaic_volume_stitch_flow.py | 2 +- .../flows/psoct/tile_batch_archive_flow.py | 3 +- .../flows/psoct/tile_batch_process_flow.py | 3 +- opticstream/flows/psoct/utils.py | 23 +- opticstream/utils/acquisition_csv.py | 126 ++++++++++ opticstream/utils/polling_watcher.py | 6 + tests/test_acquisition_csv_and_progress.py | 218 ++++++++++++++++++ tests/test_acquisition_previews.py | 15 +- tests/test_acquisition_sequence.py | 26 ++- tests/test_complex_outputs.py | 3 +- tests/test_oct_input_naming.py | 6 +- 21 files changed, 771 insertions(+), 27 deletions(-) create mode 100644 opticstream/cli/oct/run.py create mode 100644 opticstream/utils/acquisition_csv.py create mode 100644 tests/test_acquisition_csv_and_progress.py diff --git a/docs/developer/cli_overview.md b/docs/developer/cli_overview.md index 3cfd86c..0f155f6 100644 --- a/docs/developer/cli_overview.md +++ b/docs/developer/cli_overview.md @@ -35,6 +35,8 @@ is exposed as `opticstream` (with alias `ops`). - `opticstream oct create-lock PROJECT_NAME` - `opticstream oct update-block` - `opticstream oct watch PROJECT_NAME FOLDER_PATH [MOSAIC_RANGES] [--slice-offset ... --stability-seconds ... --poll-interval ... --direct/--no-direct --refresh ... --force-resend --min-complex-file-size-bytes ... --verbose]` +- `opticstream oct run PROJECT_NAME FOLDER_PATH [watch options ... --deployment-name ... --concurrency-limit ... --exclude ...]` +- `opticstream oct progress PROJECT_NAME` - `opticstream oct deploy [--project-name ... --deployment-name ... --work-pool-name ...]` - `opticstream oct serve register [--project-name ... --deployment-name ...]` - `opticstream oct serve all PROJECT_NAME [--deployment-name ... --exclude ...]` diff --git a/docs/oct_input_naming.md b/docs/oct_input_naming.md index 8ffa55f..282a695 100644 --- a/docs/oct_input_naming.md +++ b/docs/oct_input_naming.md @@ -2,7 +2,8 @@ Edit the existing PSOCTScanConfig block's `acquisition` section after registering the updated block schema. Restart the watcher after saving the block. -Omitting `filename_pattern` (or setting it to null) preserves legacy parsing. +The default `filename_pattern` is `spectral_{image}.nii` (see below). Setting it to +null selects legacy `mosaic__image__*` parsing. ```json { @@ -34,7 +35,7 @@ with overlapping slice/tile IDs in the same watched directory. ## Scanner names without slice or acquisition If the scanner only numbers its output (`spectral_0001.nii`, `spectral_0002.nii`, -...), set `"filename_pattern": "spectral_{image}.nii"`. The numbers are then one +...), keep the default `"filename_pattern": "spectral_{image}.nii"`. The numbers are then one continuous sequence across mosaics and slices. A new project starts at slice 1 mosaic 1, so no options are needed: @@ -87,6 +88,27 @@ add `--start-image` to redo that mosaic once more. position by its `acquisition_mosaic_map` label instead; you never need both. `--slice-offset` still shifts the resulting slice numbers. +### Deleted spectral files and reused numbers + +The acquisition software never reuses a `spectral_####` number in a dataset folder: +it continues from the highest number on disk or in its `filenames.csv`, so spectral +files of finished slices can be deleted to free space. If a file is nevertheless +written after its batch was recorded in project state (the scanner reused the +number), the watcher does not skip it silently: it logs an error, posts it to +Slack, and leaves it unprocessed. Use `--force-resend` only when those files really +are a redo of that batch. + +### filenames.csv + +The acquisition software writes `filenames.csv` in its dataset folder, one row per +tile: `rawname,descname,number,slice,acq,tile,datetime,json`. `descname` is the +descriptive name from the acquisition's File Name Template (for example +`sub-I58_slab-01_acq-normal0deg_tile-00001_slice-0001_OCT.nii`); no file with that +name is written. The watcher still places tiles by number alone. It only compares +each row with that placement and warns about rows that disagree, which happens when +Tiles in Tiling 1/2 differ from the grid sizes or the two programs start at +different slices. Keep this file when deleting spectral files. + A batch number beyond a mosaic's `grid_size_x` is never dispatched (it is logged and ignored), whatever the naming. @@ -98,8 +120,11 @@ No `_spectral.nii` suffix is required. For example, use `s{slice}_tile{image}_{acq}.nii` with `filename_default_modality: "spectral"`. Or keep `{modality}{extension}` and set `filename_modality_map` to `{"rawscan": "spectral"}` for `_rawscan.nii`. -The default map accepts spectral, complex, processed, aip, mip, ori, ret, surf, -and dbi. Unknown acquisition/modality labels are ignored. Duplicate files for +The default map is `{"spectral": "spectral", "processed_aip": "aip", +"processed_mip": "mip", "processed_orientation": "ori", "processed_retardance": +"ret", "processed_surface_finding": "surf"}`, matching OCTAcquisition's outputs. +Add labels such as `"complex": "complex"` or `"processed": "processed"` for +complex input. Unknown acquisition/modality labels are ignored. Duplicate files for the same tile and modality cause an error rather than silently replacing data. Batches contain only the processing input for `tile_saving_type` (`spectral` for diff --git a/docs/reference/cli_commands.md b/docs/reference/cli_commands.md index 2dae34d..1975dc5 100644 --- a/docs/reference/cli_commands.md +++ b/docs/reference/cli_commands.md @@ -46,6 +46,8 @@ Valid `FLOW_NAME` values for `opticstream deploy` are: | `opticstream oct create-lock PROJECT_NAME` | Ensure project-scoped OCT state lock exists. | | `opticstream oct update-block [PROJECT...]` | Register the current `PSOCTScanConfig` schema and re-save saved blocks (all, or the named projects) onto it so new fields appear in the Prefect UI. | | `opticstream oct watch PROJECT_NAME FOLDER_PATH [MOSAIC_RANGES] ...` | Watch spectral data and dispatch batch processing (direct or event mode). | +| `opticstream oct run PROJECT_NAME FOLDER_PATH ...` | Run `oct serve all` (child process) and `oct watch` together; needs the Prefect server already up. | +| `opticstream oct progress PROJECT_NAME` | One row per slice with `