diff --git a/.claude/agents/trial.agent.md b/.claude/agents/trial.agent.md new file mode 100644 index 0000000..aede8a0 --- /dev/null +++ b/.claude/agents/trial.agent.md @@ -0,0 +1,9 @@ +--- +name: trial +description: Describe what this custom agent does and when to use it. +tools: Read, Grep, Glob, Bash # specify the tools this agent can use. If not set, all enabled tools are allowed. +--- + + + +Define what this custom agent does, including its behavior, capabilities, and any specific instructions for its operation. \ No newline at end of file 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/.github/workflows/tests.yml b/.github/workflows/tests.yml new file mode 100644 index 0000000..27c86af --- /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 -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 -o addopts= -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/.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/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..0fae014 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,53 @@ +# 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) +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/) +``` + + +## 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 → archive → batch.archived → DANDI upload → batch.dandi_uploaded`, and `mosaic.ready → en-face stitch + Slack QC → mosaic.enface_stitched → slice.ready → 3D optic axis (opt-in)` (details below). Uploads always run as separate event-triggered flows, so they never block compute. Deployments are served through `ops lsm serve` / `ops oct serve all` (`ops oct run` serves and watches together), 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}-psoct-config"`, or `LSMScanConfig` saved as `"{project_name}-lsm-config"`, both in `opticstream/config/`. Fields removed from a config model must be added to its legacy-key drop list (`REMOVED_FIELDS` in `psoct_scan_config.py`) so saved blocks still load. `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. + +**PS-OCT chain.** There is no tile reconstruction in the pipeline: the MATLAB processing (psoct-toolbox), Fiji stitching, volume stitching and slice registration were removed, and replacement processing will subscribe to the events later (all event constants are kept, some unemitted). The steps are: + +1. `ops oct watch` (one watcher, `cli/oct/watch.py`) counts a tile once it has its raw spectral file **and** the acquisition's en-face maps (aip/mip/ori/ret, plus surf when mapped in `acquisition.filename_modality_map`). It emits `BATCH_READY` for each complete, stable batch and records the batch. When it records a mosaic's last batch, it emits `MOSAIC_READY` with `input_dir`, `acquisition` and `image_offset`. +2. `BATCH_READY` → `tile_batch_archive_flow` → `BATCH_ARCHIVED` → `tile_batch_upload_flow` (milestone `dandi_uploaded`, event `BATCH_DANDI_UPLOADED`). +3. `MOSAIC_READY` → `acquisition_preview_flow.preview_enface_mosaic`. It stitches the maps into JPEGs with linc-convert `mosaic2d`, posts them to Slack, and only then sets `enface_stitched` and emits `MOSAIC_ENFACE_STITCHED`. +4. Its `check_slice_ready_hook` emits `SLICE_READY` once all `mosaics_per_slice` mosaics are stitched. + `SLICE_READY` → `optic_axis_3d_flow.fit_optic_axis_3d_slice` (opt-in via the block's `optic_axis_3d.enabled`). It lists the slice's en-face tiles as the previews found them, runs `data_processing/optic_axis_3d/run_3daxis.jl` with Julia/PSOCTRec, then sets the slice milestone `optic_axis_3d` and emits `SLICE_OPTIC_AXIS_3D`. +5. `spectral_cleanup_flow` deletes a slice's spectral files last; every state milestone needs a `MILESTONE_RULES` entry there. + +`data_processing/psoct_recon` (numpy ports) and `data_processing/stitch` are kept as building blocks but are unused by the flows. + +**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/README.md b/README.md index 43ac95a..3bdcae1 100644 --- a/README.md +++ b/README.md @@ -60,7 +60,6 @@ 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). diff --git a/docker-compose.yaml b/docker-compose.yaml index 3ad6812..619876a 100644 --- a/docker-compose.yaml +++ b/docker-compose.yaml @@ -12,6 +12,9 @@ services: volumes: - ./db:/var/lib/postgresql profiles: ["server"] + ports: + - "1542:5432" + #- "127.0.0.1:1542:5432" ### MinIO for flow storage minio: diff --git a/docs/acquisition_enface_previews.md b/docs/acquisition_enface_previews.md new file mode 100644 index 0000000..6afd13d --- /dev/null +++ b/docs/acquisition_enface_previews.md @@ -0,0 +1,204 @@ +# Acquisition en-face stitch and Slack QC + +When every batch of a mosaic is ready, `ops oct watch` emits `MOSAIC_READY`. The +`preview-enface-mosaic` deployment (served by `ops oct serve all` / `ops oct run`) then: + +1. stitches the mosaic's AIP, MIP, orientation (`ori`) and retardance (`ret`) tiles, plus + surface-finding (`surf`) maps when the project maps them, into JPEGs with linc-convert + `mosaic2d()`; +2. posts the JPEGs to Slack for QC; +3. sets the mosaic's `enface_stitched` milestone and emits `MOSAIC_ENFACE_STITCHED`. + +Its completion hook emits `SLICE_READY` once every mosaic of the slice is stitched. + +The maps are the ones the acquisition software writes. mosaic2d writes only the JPEGs (no +NIfTI). Orientation is coloured by angle, with a colour wheel. The JPEGs are not uploaded to +DANDI. + +There is no separate preview watcher: the one watcher waits for each tile's spectral file +*and* its maps before it counts a batch as ready (see +[OCT events and state](developer/oct_events_and_state.md)), so `MOSAIC_READY` means the maps +are all there. + +## Configure and run + +The maps are found with the project's input naming (see oct_input_naming.md): + +- `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 en-face maps (all four + required); + - a label mapped to `surf` adds a surface-finding map, which then becomes required too. + +`ops oct watch` refuses to start when the naming cannot find the maps. + +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 +{ + "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" + } +} +``` + +**Matching rules:** +- 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 (e.g. `processed`, the intensity volume) are ignored. +- `{image}` matches any zero padding. Two files for the same modality and image (e.g. + `..._0001_...` and `..._1_...`) are an error. + +**Supported maps:** +- NIfTI (`.nii`/`.nii.gz`) and the other formats the QC loader reads are accepted. +- Only 2D maps, or maps with singleton trailing dimensions, are supported. +- Orientation maps are read in degrees. Set `acquisition.orientation_units` to `radians` if + the acquisition writes radians (default `degrees`); mosaic2d then converts them to degrees + before blending and colouring. + +From Miniforge Prompt, with the project's venv activated and the Prefect API configured: + +```cmd +opticstream oct run human-10um D:\data\acquisition +``` + +**Continuous numbering.** With continuously numbered files (a `filename_pattern` without +`{slice}` or `{acq}`), each mosaic's maps are the images in its range; for example, mosaic 2 +of a 22 x 16 grid starts at image 353. The watcher passes that offset (`image_offset`) and the +mosaic's `acquisition_mosaic_map` label in the `MOSAIC_READY` payload. + +**Rerunning.** To redo one mosaic, run the manual `preview-enface-mosaic` deployment with the +mosaic's ident, the acquisition folder, its label, its `image_offset` and `force_rerun`. + +`ops oct preview` still stitches a quick M x N test mosaic outside the pipeline (no project +state, no events). + +## Geometry + +Tiles are numbered consecutively within the mosaic, starting at image 1 (with continuous +numbering, at the mosaic's first image). Batch 1 holds the first `grid_size_y` tiles, batch 2 +the next set, and so on. The mosaic has `grid_size_x` * `grid_size_y` tiles. + +Tilted mosaics use `grid_size_y_tilted` in place of `grid_size_y` when it is set. For example, +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-rows` / +`left-down`. Individual images are not flipped. + +Coordinates use the actual image dimensions and the mosaic's overlaps, in percent (X is +between batches, Y within a batch): +- normal mosaics: `acquisition.tile_overlap_x_normal` / `tile_overlap_y_normal`; +- tilted mosaics: `tile_overlap_x_tilted` / `tile_overlap_y_tilted`. + +These are nominal-grid QC mosaics, not image-registered ones. Inspect alignment against a +known acquisition before relying on the geometry. + +**Blending.** Orientation uses circular blending; AIP, MIP and retardance use ordinary +blending. Acquisition originals are never changed. Only non-NIfTI tiles are copied, to a +temporary NIfTI, before stitching. + +**Stability.** Readiness is a heuristic, not a producer completion handshake: the watcher +waits until a batch's files have kept their sizes and modification times for +`--stability-seconds` (15 by default). Increase it if acquisition pauses during writes. A +missing, corrupt or inconsistent tile fails the stitch rather than producing a partial mosaic. + +## Outputs, Slack and retries + +All JPEGs for a slice go in one folder, `project_base_path/slice-NN/acquisition_previews/`, +with the mosaic in the file name: `mosaic_001_aip.jpg`, ..., `mosaic_001_surf.jpg` and the +checkpoint `mosaic_001_progress.json`. Per-batch files from earlier versions +(`mosaic_001_batch_0003_*`) are left in place and can be deleted. + +**The checkpoint.** +- `progress.json` records which modalities are stitched and posted, so a rerun skips + completed work. +- It also records where the mosaic's tiles are; spectral cleanup reads that. +- Changes to the inputs' paths, sizes or mtimes, or to the `acquisition` settings, invalidate + it, so the mosaic may be restitched and posted again after editing them. +- Changing only file content, without changing size or mtime, is not detected. + +**Slack.** +- The existing Slack bot credentials and channel, and the `slack-notifications-enabled` + variable, are reused. +- When Slack is disabled, stitching still runs and the mosaic is marked stitched. +- Successful uploads are checkpointed per modality. If any upload fails, the flow fails + without emitting `MOSAIC_ENFACE_STITCHED`, and a rerun posts only the missing ones. +- Slack delivery is not exactly-once: a crash after Slack accepts an upload but before the + checkpoint is saved can duplicate it. + +## Deleting raw spectral files (always last) + +With the block's `delete_spectral_after_previews` set to true (default false), a slice's +spectral files are deleted as the slice's **last** operation. `sweep-spectral-cleanup` checks +every 5 minutes. `ops oct serve all ` (and `ops oct run`) serve it; with `all` +instead of a project, only the manual flow is served. It deletes a slice's files only when all +of these hold: + +1. **En-face stitch.** The stitch has finished for every mosaic of the slice (its + `progress.json` is complete). +2. **Archive.** When `archive_path` is set, every tile of the slice has: + - its archive copy, named by `archive_tile_name_format`; + - the archive's `.sha256`, which is written once the gzip is complete. + + Tiles are counted rather than batches, so slices batched under an earlier grid setting + still qualify. +3. **State milestones.** Every milestone of the slice, its mosaics and its batches that the + block enables is done, every batch and mosaic is completed, and nothing in the slice's + state is running or failed: + + | Enabled by | Milestones | + |---|---| + | always | mosaic `enface_stitched` | + | `archive_path` | batch `archived`, raw-tile DANDI upload (`dandi_uploaded`) | + +4. **No activity.** No Prefect flow run whose parameters refer to the slice is scheduled, + pending, running, paused or cancelling, or ended in the last 2 minutes: + - parameters refer to the slice when they hold an ident or payload with its `project_name` + and `slice_id`; + - the 2 minutes give events emitted at the end of a run time to create the runs they + trigger. + +Two rules keep deletion last as the pipeline grows: + +- **New state milestones block until given a rule.** Every boolean milestone field of the + batch, mosaic and slice state needs an entry in `MILESTONE_RULES` + (`flows/psoct/spectral_cleanup_flow.py`) saying which settings produce it. A field without + one blocks deletion, and `test_every_state_milestone_has_a_rule` fails. +- **New flows are covered by the activity check.** Any flow taking the slice's identifiers + holds deletion off until it finishes, with or without a milestone. + +A DANDI upload switched off with the `dandi-uploads-enabled` Prefect Variable never sets its +milestone, so the slice's spectral files are kept until uploads are turned back on and finish. + +**What is deleted.** Only the files `filename_modality_map` maps to `spectral`, in the image +ranges recorded in `mosaic_NNN_progress.json`. En-face maps and every other file are kept. + +**Afterwards.** `slice-NN/acquisition_previews/spectral_deleted.json` records the deletion, and +the sweep skips that slice from then on. Each sweep logs why it is keeping each slice's files. + +**By hand.** To delete one slice, run `delete-slice-spectral` with the project's config and +the slice id. It makes the same checks, ignores the switch, and is safe to run again. + +Restart the watcher after editing block fields. A project-state reset does not erase the +stitch checkpoints. To deliberately resend, delete or move the mosaic's `*_progress.json`. +Deleting only its `.jpg` files restitches without resending. diff --git a/docs/concepts/acquisition_watchers.md b/docs/concepts/acquisition_watchers.md index 8a06958..0e324e0 100644 --- a/docs/concepts/acquisition_watchers.md +++ b/docs/concepts/acquisition_watchers.md @@ -50,12 +50,12 @@ flowchart LR gate --> out ``` -- **Discover** — What paths are candidates? (LSM: new `Run*` subfolders; OCT: spectral NIfTI glob in a fixed folder.) +- **Discover** — What paths are candidates? (LSM: new `Run*` subfolders; OCT: files matching `acquisition.filename_pattern` in a fixed folder, where a tile counts once it has its spectral file and its en-face maps.) - **Stable** — Has the data settled? (LSM: **`wait_until_stable`** on the strip folder. OCT: **per-batch** fingerprint stability in **`PollingStableWatcher`**—each batch’s file paths + mtimes + sizes must stay unchanged for **`stability_seconds`** before dispatch; **`poll_interval`** is how often the loop re-scans and updates stability.) - **Readable** — Can the process open the files for read? (OCT: `is_file` + `os.R_OK` per spectral file; LSM relies on the folder-level stability snapshot for strip content.) - **Identity** — Parse folder/filenames into slice/strip/channel or mosaic/batch. - **State gate** — `peek_strip` / `peek_batch`: skip if already tracked (unless forced resend). -- **Dispatch** — Emit `STRIP_READY` / `BATCH_READY`, or run `process_tile_batch` directly; then optional host-specific steps (e.g. OCT direct-mode disk refresh). +- **Dispatch** — Emit `STRIP_READY` / `BATCH_READY` (OCT also emits `MOSAIC_READY` after a mosaic's last batch); then optional host-specific steps (e.g. OCT disk refresh). **Stability vs readability (OCT):** Per-batch fingerprint stability is about **time and content** (sizes/mtimes for that batch’s files); readability is about **permission and basic file validity**. Both are needed: a file can look stable in listing but still not readable, or pass `os.access` while another write is in flight (fingerprint changes reset the timer). @@ -66,9 +66,9 @@ flowchart LR | | LSM | PS-OCT | |---|-----|--------| | **Trigger** | New **subdirectory** under a watch root | Repeated **rescan** of one **known** folder (`poll_interval` between iterations; each logical batch must meet **per-batch** fingerprint stability for `stability_seconds` before dispatch) | -| **Discovery** | Watchdog + polling queue of new folders | Glob `*cropped_focus*.nii` | +| **Discovery** | Watchdog + polling queue of new folders | `acquisition.filename_pattern`: spectral files plus en-face maps | | **Batch unit** | One strip folder | One logical tile batch (from filename indices + `grid_size_y`) | -| **Default dispatch** | Prefect event (`STRIP_READY`) | In-process flow (`process_tile_batch`); optional event mode | +| **Default dispatch** | Prefect event (`STRIP_READY`) | Prefect events (`BATCH_READY`, and `MOSAIC_READY` per mosaic) | LSM is **event-driven** at the filesystem; OCT runs a **polling loop** (`PollingStableWatcher`) that rediscovers candidates each iteration, advances stability per batch, and processes **every** stable-ready batch in an iteration. diff --git a/docs/concepts/data_processing_pipeline.md b/docs/concepts/data_processing_pipeline.md index 04eea21..1cfd3f9 100644 --- a/docs/concepts/data_processing_pipeline.md +++ b/docs/concepts/data_processing_pipeline.md @@ -21,28 +21,27 @@ Typical strip processing stages are: ## PS-OCT processing stages -Typical PS-OCT processing stages are: +The PS-OCT reconstruction that ran in MATLAB was removed; the en-face maps come from the +acquisition software. The stages are: -- batch discovery from spectral files (`opticstream cli oct watch`) -- tile-batch conversion (`opticstream.flows.psoct.tile_batch_process_flow`) -- mosaic processing and enface stitching (`mosaic_process_flow.py`) -- slice registration (`slice_process_flow.py`) -- volume stitching (`mosaic_volume_stitch_flow.py`) -- archive/upload/QC flows (`tile_batch_archive_flow.py`, - `tile_batch_upload_flow.py`, `mosaic_*_upload_flow.py`, - `mosaic_enface_qc_flow.py`) +- batch discovery from spectral files and en-face maps (`opticstream oct watch`, `BATCH_READY`) +- raw-tile archive and DANDI upload (`tile_batch_archive_flow.py`, `tile_batch_upload_flow.py`) +- mosaic en-face stitch and Slack QC (`acquisition_preview_flow.py`, on `MOSAIC_READY`) +- `SLICE_READY` once every mosaic of a slice is stitched (no listener yet) +- spectral cleanup (`spectral_cleanup_flow.py`) ## Data-processing utility modules -Key utilities currently used by flows include: +Lower-level PS-OCT modules kept for the replacement processing (not used by the current +flows): -- `opticstream.data_processing.spectral_raw.spectral2complex` -- `opticstream.data_processing.volume_3d.complex2vol` -- `opticstream.data_processing.enface.vol2enface` -- `opticstream.data_processing.stitch.fiji_stitch` -- `opticstream.data_processing.stitch.fit_coord_files` -- `opticstream.data_processing.stitch.generate_mask` -- `opticstream.data_processing.convert_image` +- `opticstream.data_processing.psoct_recon` (numpy ports of spectral → complex → volume → enface) +- `opticstream.data_processing.stitch` (tile grids, coordinate fitting, Fiji helpers, blending) + +Used by the current flows: + +- `opticstream.data_processing.qc.convert_image` +- linc-convert `generate_tile_config` / `mosaic2d` (en-face stitch) These modules are intentionally lower-level; pipeline sequencing, retries, and state transitions happen in Prefect flow modules. diff --git a/docs/concepts/flows_and_state_models.md b/docs/concepts/flows_and_state_models.md index b871eb8..c2b875d 100644 --- a/docs/concepts/flows_and_state_models.md +++ b/docs/concepts/flows_and_state_models.md @@ -13,24 +13,13 @@ hierarchical project state services. Primary flow entrypoints include: -- `process_strip` / `process_strip_event` (`strip_process_flow.py`) -- `upload_strip_to_dandi_flow` / `upload_strip_to_dandi_event_flow` (`strip_upload_flow.py`) -- `process_channel` / `process_channel_event` (`channel_process_flow.py`) -- `process_channel_volume` / `process_channel_volume_event` (`channel_volume_flow.py`) -- `upload_channel_volume` / `upload_channel_volume_event` (`channel_upload_flow.py`) - -### PS-OCT flow modules (`opticstream.flows.psoct`) - -Primary flow entrypoints include: - -- `process_tile_batch` / `process_tile_batch_event_flow` (`tile_batch_process_flow.py`) -- `process_mosaic` / `process_mosaic_event_flow` (`mosaic_process_flow.py`) -- `stitch_enface_modalities` (`mosaic_process_flow.py`) -- `register_slice_flow` / `register_slice_event_flow` (`slice_process_flow.py`) -- `stitch_volume_flow` / `stitch_volume_event_flow` (`mosaic_volume_stitch_flow.py`) -- `archive_tile_batch_flow` (`tile_batch_archive_flow.py`) -- upload flows for batch/mosaic/volume outputs in `tile_batch_upload_flow.py`, - `mosaic_upload_flow.py`, and `mosaic_volume_upload_flow.py` +- `archive_tile_batch_flow` / `archive_tile_batch_event_flow` (`tile_batch_archive_flow.py`, + on `BATCH_READY`) +- `upload_to_dandi_tile_batch` / `upload_to_dandi_batch_event_flow` + (`tile_batch_upload_flow.py`, on `BATCH_ARCHIVED`) +- `preview_enface_mosaic` / `preview_enface_mosaic_event_flow` + (`acquisition_preview_flow.py`, on `MOSAIC_READY`) +- `delete_slice_spectral` / `sweep_spectral_cleanup` (`spectral_cleanup_flow.py`) ## State hierarchies @@ -57,7 +46,7 @@ Canonical event names follow: Examples: - `linc.opticstream.psoct.batch.ready` -- `linc.opticstream.psoct.mosaic.volume_stitched` +- `linc.opticstream.psoct.mosaic.enface_stitched` - `linc.opticstream.lsm.strip.ready` - `linc.opticstream.lsm.channel.volume_uploaded` diff --git a/docs/concepts/scan_configurations.md b/docs/concepts/scan_configurations.md index 69563eb..8215776 100644 --- a/docs/concepts/scan_configurations.md +++ b/docs/concepts/scan_configurations.md @@ -31,7 +31,6 @@ PS-OCT configuration is split into nested models: - `PSOCTScanConfigModel` (top-level project settings) - `PSOCTAcquisitionParams` (tile/grid geometry and acquisition constants) -- `PSOCTProcessingParams` (processing/MATLAB behavior) - `PSOCTScanConfig` (Prefect block type) Key enums used by the model: diff --git a/docs/design.md b/docs/design.md index dc481c1..48c78fc 100644 --- a/docs/design.md +++ b/docs/design.md @@ -12,14 +12,12 @@ This page is a high-level entry point for the OCT pipeline design. The detailed - `developer/oct_design_overview.md` - **OCT data flow and folder layout**: hierarchy, processing steps, and on-disk structure - `developer/oct_data_flow.md` -- **OCT events and state management**: event model, flag files, artifacts, and state flows +- **OCT events and state management**: the current event chain, payloads, state milestones, artifacts and Slack - `developer/oct_events_and_state.md` - **Prefect Variable–backed project state**: generic store, locking, and `open_*` / `read_*` / `peek_*` APIs - `developer/prefect_state_design.md` - **OCT processing hosts and deployment**: hosts, work pools, and agents - `developer/oct_deployment_and_hosts.md` -- **OCT MATLAB batch processing, upload, and stitching**: batch processing, upload flows, MATLAB integration, and stitching - - `developer/oct_matlab_and_stitching.md` - **OCT algorithms, error handling, and QC**: algorithms, retries, and quality control - `developer/oct_algorithms_and_qc.md` - **OCT future extensions**: planned improvements and extensions @@ -27,6 +25,18 @@ This page is a high-level entry point for the OCT pipeline design. The detailed Refer to those developer docs for the full design details. +# Original design (historical) + +> **Historical.** The rest of this page is the original design document, kept for reference. +> It describes MATLAB tile processing, Fiji coordinate stitching, 3D volume stitching, slice +> registration and flag-file state, all of which have been removed or replaced: +> - The pipeline now archives and uploads the raw tiles and stitches the acquisition's own +> en-face maps for QC. +> - State lives in PostgreSQL. +> +> For the current chain, see `developer/oct_events_and_state.md` and +> `developer/oct_data_flow.md`. + # Distributed OCT Data Acquisition & Real-Time Processing System > Audience: advanced users and maintainers who need a detailed view of the @@ -870,7 +880,7 @@ Project-level parameters define the structure and configuration of a processing * **`project_base_path`**: Base filesystem path for project data * **`grid_size_x_normal/grid_size_x_tilted`**: Number of batches (columns) per mosaic - determines how tiles are organized for MATLAB batch processing * **`grid_size_y`**: Number of tiles per batch (rows) - determines batch size for MATLAB processing -* **`tile_overlap`**: Overlap between tiles in pixels (default: 20.0) +* **`tile_overlap_x_normal`**, **`tile_overlap_y_normal`**, **`tile_overlap_x_tilted`**, **`tile_overlap_y_tilted`**: Overlap between tiles in percent along X (between batches) and Y (within a batch) for each illumination (defaults: 20, 20, 42, 20). Blocks saved with the single `tile_overlap` use it for the normal overlaps. * **`mask_threshold_normal`**: Threshold for mask generation and coordinate processing for normal illumination (default: 60.0) * **`mask_threshold_tilted`**: Threshold for mask generation and coordinate processing for tilted illumination (default: 55.0) * **`scan_resolution_3d`**: Scan resolution for 3D volumes [x, y, z] in millimeters (default: [0.01, 0.01, 0.0025]) diff --git a/docs/developer/cli_overview.md b/docs/developer/cli_overview.md index a39da0f..4bc735f 100644 --- a/docs/developer/cli_overview.md +++ b/docs/developer/cli_overview.md @@ -31,12 +31,12 @@ 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 ... --acq-mosaic-map normal0deg=1,tilted15deg=2 --filename-pattern 'spectral_{image}_{modality}.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]` -- `opticstream oct deploy [--project-name ... --deployment-name ... --work-pool-name ...]` -- `opticstream oct serve register [--project-name ... --deployment-name ...]` +- `opticstream oct watch PROJECT_NAME FOLDER_PATH [MOSAIC_RANGES] [--slice-offset ... --stability-seconds ... --poll-interval ... --slice ... --mosaic ... --acquisition ... --start-image ... --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 serve all PROJECT_NAME [--deployment-name ... --exclude ...]` - `opticstream oct state reset PROJECT_NAME [--slice N --mosaic N --batch N]` - `opticstream oct state mark PROJECT_NAME {slice|mosaic|batch} FIELD [VALUE] [--slice N --mosaic N --batch N]` diff --git a/docs/developer/code_layout.md b/docs/developer/code_layout.md index 1a798c4..426a1af 100644 --- a/docs/developer/code_layout.md +++ b/docs/developer/code_layout.md @@ -22,7 +22,7 @@ opticstream/ tasks/ # reusable Prefect tasks (archive, DANDI, LINC uploads) artifacts/ # artifact publishing hooks/tasks data_processing/ # stitching, image conversion, spectral and volume helpers - utils/ # shared runtime utilities (watching, naming, MATLAB, etc.) + utils/ # shared runtime utilities (watching, naming, settings, etc.) scripts/ # standalone scripts for operations and analysis ``` diff --git a/docs/developer/documentation_workflow.md b/docs/developer/documentation_workflow.md index c265796..85c0218 100644 --- a/docs/developer/documentation_workflow.md +++ b/docs/developer/documentation_workflow.md @@ -24,14 +24,13 @@ pip install "opticstream[dev]" This installs MkDocs and any additional documentation-related dependencies declared by the project. -## Working with external dependencies (linc-convert, nifti-zarr, psoct-toolbox) +## Working with external dependencies (linc-convert, nifti-zarr) -The project depends on three external algorithm libraries that can be sourced +The project depends on two external algorithm libraries that can be sourced either from GitHub or from local clones: - `linc-convert` - `nifti-zarr` -- `psoct-toolbox` In `pyproject.toml` these appear in two places: @@ -43,19 +42,18 @@ In `pyproject.toml` these appear in two places: [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 } - psoct-toolbox = { path = "/space/megaera/1/users/kchai/code/psoct-toolbox", editable = true } ``` ### Using local clones instead of GitHub -- **To work against local repositories**, ensure the three lines under +- **To work against local repositories**, ensure the two lines under `[tool.uv.sources]` in `pyproject.toml` are **uncommented** and point at your local checkout paths. - When you then install or sync the environment with `uv` (for example `uv sync` or `uv pip install .`), `uv` will prefer these local source directories and install them in editable mode instead of pulling from GitHub. -If you comment out these `linc-convert`, `nifti-zarr`, and `psoct-toolbox` +If you comment out these `linc-convert` and `nifti-zarr` entries, `uv` will fall back to the GitHub URLs defined in `[project.dependencies]`. diff --git a/docs/developer/oct_data_flow.md b/docs/developer/oct_data_flow.md index 39ef88d..9bebdf0 100644 --- a/docs/developer/oct_data_flow.md +++ b/docs/developer/oct_data_flow.md @@ -13,206 +13,120 @@ title: OCT data flow and folder layout * Manages flow deployments, event triggers, state, and artifacts * **Processing Workers** - * Zircon: high I/O, large-memory tasks (tile processing, mosaics) - * Auxiliary hosts: compute-heavy, low-I/O tasks (e.g., registration) + * Serve the event-triggered deployments (`ops oct serve all`) * **Event Bus (Prefect Events)** - * Coordinates downstream workflows when upstream flows complete + * Coordinates downstream workflows when upstream flows complete (see + [OCT events and state](oct_events_and_state.md)) * **Storage Backends** - * Local high-speed SSDs (temporary processing) + * Local high-speed SSDs (acquisition folder, previews) * External raw data archiving drives - * DANDI / LINC s3 storage + * DANDI storage ## Data processing flow -Processing is organized hierarchically: **Tile → Mosaic → Slice → All-Slices**. +Processing is organized hierarchically: **Tile → Batch → Mosaic → Slice**. The acquisition +software (OCTAcquisition) writes each tile's raw spectral file and its en-face maps; opticstream +archives and uploads the raw tiles and stitches the maps for QC. The reconstruction that used to +run in MATLAB (spectral → complex → volumes → en-face maps, mosaic stitching with Fiji, slice +registration) was removed and will be replaced later. -### Tile-level processing - -Each tile represents the smallest independently processed unit in the data hierarchy. Tiles are the atomic data unit - the fundamental building blocks that compose mosaics. +### Tile and batch level #### Inputs -* Spectral raw data **or** complex data -* File naming convention encodes acquisition metadata (parsed at ingest) - -#### Tile processing steps - -1. **Metadata Parsing** - * Extract slice, mosaic, tile index, illumination -2. **Integrity & Compression** - * Compute SHA-256 checksum - * Compress raw tile data - * Ensure single-read semantics where possible -3. **Spectral → Complex Conversion** - * When input is spectral raw data: Performed in MATLAB to convert spectral data to complex format - * When input is already complex data: Files are soft linked to `complex/` directory instead of converting - * Output stored in `complex/` - * See the MATLAB batch processing design doc for details on batch processing optimization -4. **Complex → 3D Volumes Conversion** - * Convert complex tiles to 3D volumes (dBI, O3D, R3D modalities) - * Performed in MATLAB - * See the MATLAB batch processing design doc for details on batch processing optimization -5. **Surface Finding** - * Automatic surface detection from intensity data - * Surface finding method can be configured (e.g., \"find\" for automatic detection) -6. **Enface Image Generation** - * Generate 2D enface images from 3D volumes using surface information - * Multiple enface modalities: AIP (Average Intensity Projection), MIP (Maximum Intensity Projection), orientation, retardance, birefringence - * Surface maps generated for visualization -7. **Archival Upload** - * Compressed raw data uploaded to DANDI/LINC - * Uploads are handled by a dedicated, event-triggered flow (see the upload strategy design doc for details) - -#### MATLAB integration - -* MATLAB is invoked via command-line interface from Python -* MATLAB functions handle spectral-to-complex and complex-to-processed conversions -* Data flow: Python → MATLAB → Python (processed tiles) -* Currently executed in MATLAB (future Python migration planned) -* Future migration to Python-native implementations will eliminate the need for batch processing optimization - -#### Tile-level QC - -* Validate surface finding overlap with intensity images -* Verify processing quality at tile level -* QC images emitted as Prefect artifacts and Slack notifications - -### Mosaic-level processing - -Triggered once **all tiles in a mosaic** complete tile-level processing. A mosaic contains all tiles for a given slice and illumination type (normal or tilted). - -#### First slice processing - -For each illumination type of the first slice (mosaic_001 for normal, mosaic_002 for tilted, maybe more types of illumination), additional processing steps are required that are not needed for subsequent slices: - -1. **Tile Coordinate Determination** - * Determine tile positions and alignment for stitching - * Generates coordinate template that is reusable for all mosaics of the same illumination type - * For subsequent slices of the same illumination type, the template from the first slice is reused - * See the stitching and coordinate determination design doc for detailed algorithms and methods -2. **Focus Finding** - * Determine optimal focus plane for 3D volume stitching - * Focus finding requires accurate surface information, so it uses an unfiltered version of the surface data - * QC validation: verify focus finding overlap with intensity images - * See the focus finding algorithms design doc for details - -#### 2D enface mosaic stitching - -1. **Template Application** - * Apply coordinate template to current mosaic tiles - * For first slice: use newly generated template - * For subsequent slices: reuse template from first slice of same illumination type - * Generate tile information files for each enface modality -2. **Stitch enface modalities** - * Stitch all 2D enface modalities: AIP, MIP, orientation, retardance, birefringence, surface - * Each modality is stitched independently using the same coordinate template - * Generate overlap QC images to verify stitching quality -3. **Mask generation and application** - * Generate mask from stitched AIP using threshold-based approach - * Apply mask to all stitched enface outputs - * Mask removes background/noise regions -4. **Output generation** - * Save stitched enface images in multiple formats (NIfTI, JPEG) - * Upload stitched 2D mosaics to cloud storage - -#### 3D volume mosaic stitching - -1. **Focus plane application** - * For first slice: use focus plane determined during first slice processing - * For subsequent slices: reuse focus plane from first slice of same illumination type - * Apply focus plane for optimal 3D volume alignment -2. **Stitch 3D volumes** - * Stitch 3D volume modalities: dBI, O3D, R3D - * Use coordinate template from 2D stitching - * Apply mask to stitched volumes -3. **Upload stitched volumes** - * Upload stitched 3D volumes to cloud storage - * Volumes stored in appropriate format for downstream analysis - -### Slice-level processing - -Triggered once **all mosaics in a slice** are complete. Each slice contains two (or more in future) mosaics: one with normal illumination and one with tilted illumination. - -#### Registration process - -1. **Thruplane registration** - * Register normal and tilted illumination mosaics to combine orientations - * Uses MATLAB-based registration algorithm - * Accounts for tilt angle (gamma parameter) between illuminations - * Compute-heavy but low I/O, suitable for offloading to auxiliary hosts -2. **3D orientation computation** - * Combines information from both illumination angles - * Generates 3D axis representations (normalization needed) - * Generates RGB visualization of 3D axis orientation -3. **RGB 3D axis visualization** - * Provides visual representation of fiber orientation in 3D space - * Useful for quality control and visualization - -#### Slice-level outputs - -* Registered slice-level 2D/3D data -* Thru-plane and in-plane data in `.mat` -* 3D axis data in NIfTI -* Orientation images in JPEG (thru-plane, in-plane, 3D axis) - -### All-slices processing - -Currently manual: - -* Stack 2D mosaics across slices -* Stack 3D volumes across slices +Per tile, as named by `acquisition.filename_pattern` and `filename_modality_map`. For example, +with OCTAcquisition's defaults: + +* the raw spectral file, `spectral_####.nii`; +* the en-face maps, `spectral_####_processed_{aip,mip,orientation,retardance,surface_finding}.nii`; +* the intensity volume, `spectral_####_processed.nii`, which is not used. + +A batch is one strip of `grid_size_y` tiles. It is ready once every tile has its raw file and +its en-face maps and the files are stable (see the [watcher design](watcher_design_lsm_oct.md)). + +#### Steps + +1. **Detection**: `ops oct watch` emits `BATCH_READY` with the batch's files. +2. **Integrity and compression** (`archive-tile-batch`, when `archive_path` is set): + * gzip each tile's raw file into the archive, named by `archive_tile_name_format`; + * write a SHA-256 checksum next to each archive; + * validate the archives; + * optionally write BIDS sidecars; + * emit `BATCH_ARCHIVED`. +3. **Archival upload** (`upload-to-dandi`): upload the archives (and sidecars) to DANDI, set + `dandi_uploaded`, and emit `BATCH_DANDI_UPLOADED`. + +### Mosaic level + +A mosaic is all tiles of one slice and illumination (normal or tilted). When the watcher +dispatches a mosaic's last batch, it emits `MOSAIC_READY`, and `preview-enface-mosaic`: + +1. **Collects the tiles.** These are the mosaic's aip, mip, ori, ret (and surf) tiles from the + acquisition folder. +2. **Stitches each modality to a JPEG.** It uses linc-convert's `generate_tile_config` and + `mosaic2d`: + * the grid is the nominal one, snake by rows starting left-down, with the scan config's X/Y + overlaps; + * orientation is coloured by angle. +3. **Posts the JPEGs to Slack** for QC. +4. **Records the result.** It sets the mosaic's `enface_stitched` and emits + `MOSAIC_ENFACE_STITCHED`. + +### Slice level + +Once every mosaic of the slice is stitched, `SLICE_READY` is emitted. Nothing listens yet. + +### Spectral cleanup + +With `delete_spectral_after_previews` on, `sweep-spectral-cleanup` deletes a slice's spectral +files as its last operation. The conditions are listed in +`opticstream/flows/psoct/spectral_cleanup_flow.py`: + +* every mosaic is stitched; +* every tile has an archive and its hash; +* every batch's DANDI upload is done; +* no flow run for the slice is active. + +The en-face maps are kept. + +## Upload strategy + +Uploads are handled by dedicated, event-triggered flows that run independently of the rest of +the pipeline: + +* **Event-triggered**: `BATCH_ARCHIVED` starts the DANDI upload of the batch's archives. +* **Non-blocking**: uploads never hold up the watcher or the en-face stitch. +* **Isolated**: upload failures don't affect the other flows, and an upload can be rerun on its + own (the manual `upload-to-dandi-tile-batch` deployment). +* **Switchable**: the `dandi-uploads-enabled` Prefect Variable turns uploads off without + marking them done. + +DANDI uploads use the `dandi` Python API with the nearest `dandiset.yaml` +(`opticstream/tasks/dandi_upload.py`). The deprecated LINC instance is refused. ## Folder structure ### Project directory structure ```text -project/ -│ ├─ mosaic-{mosaic_id:02d}/ -│ │ ├─ complex/ # complex tiles (symlinked if needed) -│ │ ├─ processed/ # intermediate processed data (SSD) -│ │ ├─ stitched/ # outputs (symlinked to dandiset) -│ │ ├─ state/ # flag files for batch tracking -│ │ │ ├─ batch-001.started -│ │ │ ├─ batch-001.archived -│ │ │ ├─ batch-001.processed -│ │ │ ├─ batch-001.uploaded -│ │ │ └─ ... -│ │ └─ archived/ # raw data (symlinked to dandiset raw) -│ ├─ registered/ -│ ├─ state/ -│ ├─ focus-normal.nii # focus finding results (first slice) -│ ├─ focus-tilted.nii # focus finding results (first slice) -│ └─ tilemap-normal.j2 # tile coordinate map -│ └─ tilemap-tilted.j2 # tile coordinate map +{project_base_path}/ +└─ slice-{slice_id:02d}/ + └─ acquisition_previews/ + ├─ mosaic_{mosaic_id:03d}_{aip,mip,ori,ret,surf}.jpg # stitched en-face QC images + ├─ mosaic_{mosaic_id:03d}_progress.json # stitch/upload checkpoint, tile source + └─ spectral_deleted.json # written by spectral cleanup ``` -### DANDI/LINC storage structure +### DANDI storage structure ```text DANDISET/ -├─ rawdata/... # raw compressed tiles -│ └─ sub-{subject_id}/ -│ └─ sample-slice-{slice_id:03d}_chunk-{tile_id:04d}_acq-{acq}_OCT.nii.gz -└─ derivative/ +└─ rawdata/ └─ sub-{subject_id}/ - └─ mosaic_{mosaic_id:03d}_{modality}.nii - └─ .../*.ome.zarr (for large volumes) + └─ ..._sample-slice{slice_id:04d}_acq-{acq}_chunk-{tile_id:04d}_OCT.nii.gz # raw tiles ``` -### Symlink strategy - -Symlinks are used extensively to balance I/O performance and long-term storage: - -* **Performance**: Processing occurs on high-speed SSDs (local paths) -* **Archival**: Final outputs symlinked to DANDI/LINC storage for long-term preservation -* **Efficiency**: Avoids data duplication while maintaining fast access during processing -* **Transparency**: Symlinks make data appear in both locations without copying - -Symlinks are created: - -* From processing directories to DANDI/LINC storage for final outputs -* From DANDI/LINC storage to processing directories for inputs (when needed) - +The archive layout follows `archive_path` and `archive_tile_name_format`. For BIDS +compatibility, use `/rawdata/sub-/micr`. diff --git a/docs/developer/oct_deployment_and_hosts.md b/docs/developer/oct_deployment_and_hosts.md index dad0498..32fe13c 100644 --- a/docs/developer/oct_deployment_and_hosts.md +++ b/docs/developer/oct_deployment_and_hosts.md @@ -28,7 +28,7 @@ This hybrid strategy maximizes throughput while minimizing contention on shared Different work pools are configured for different task types to optimize resource allocation: * **Tile processing pool**: High parallelism, CPU-intensive, moderate memory - * Handles MATLAB batch processing, spectral-to-complex conversion + * Handles batch archiving and future tile processing * Many concurrent workers for parallel tile processing * **Stitching pool**: Moderate parallelism, memory-intensive * Handles mosaic stitching operations diff --git a/docs/developer/oct_events_and_state.md b/docs/developer/oct_events_and_state.md index 0c70f6b..e388e47 100644 --- a/docs/developer/oct_events_and_state.md +++ b/docs/developer/oct_events_and_state.md @@ -6,201 +6,138 @@ title: OCT events and state management ## Workflow orchestration and event model -### Flow granularity +### The PS-OCT chain + +```text +ops oct watch (one watcher) + batch ready: every tile has its raw spectral file and en-face maps, stable + ├─ BATCH_READY ─► archive-tile-batch ─► BATCH_ARCHIVED ─► upload-to-dandi ─► BATCH_DANDI_UPLOADED + └─ last batch of a mosaic ─► MOSAIC_READY + └─► preview-enface-mosaic: stitch JPEGs, post to Slack + ─► MOSAIC_ENFACE_STITCHED + completion hook: every mosaic of the slice stitched + ─► SLICE_READY (no listener yet) +``` + +Each arrow after the watcher is a Prefect event and an event-triggered deployment served by +`ops oct serve all` (`ops oct run` starts both the deployments and the watcher). Flows never +call downstream flows directly, so uploads and QC never block the watcher. + +There is no tile processing in the pipeline: the PS-OCT reconstruction that ran in MATLAB was +removed, and the en-face maps come from the acquisition software. Replacement processing will +hook into these events later. -Flows operate at the fundamental data hierarchy levels: **Tile** and **Mosaic** (see the OCT data flow doc for data hierarchy details). +### Flow granularity -* **Tile-level flows**: Handle ingestion, conversion, QC, upload triggers. When MATLAB processing is required, tiles are grouped into batches for efficiency, but tiles remain the atomic processing unit. -* **Mosaic-level flows**: Handle stitching, coordinate determination, focus finding, mosaic uploads. Operate on complete mosaics once all tiles are processed. -* **Slice-level flows**: Handle registration between normal and tilted illumination mosaics. -* **Upload flows**: Always isolated and event-triggered, never block compute pipelines. +* **Batch-level flows**: archiving of the raw tiles and their DANDI upload. +* **Mosaic-level flows**: the en-face stitch and Slack QC, once every batch is ready. +* **Slice-level**: `SLICE_READY` is emitted once every mosaic of the slice is stitched. +* **Uploads**: always isolated and event-triggered. ### Event-driven architecture -The system uses an event-driven architecture where downstream flows are started via **Prefect events**, not synchronous waits. This decouples processing stages and enables independent scaling and resilience. - -#### Benefits of event-driven architecture - -* **Decoupling**: Flows don't need to wait for downstream processing to complete -* **Scalability**: Event-driven flows can scale independently based on workload -* **Resilience**: Failed downstream flows don't block upstream flows - they can retry independently -* **Flexibility**: Easy to add new event listeners without modifying existing flows -* **Non-blocking**: Long-running operations (uploads, QC) don't block compute-intensive processing +Downstream flows start from **Prefect events**, not synchronous waits: -Synchronous processing is only used when direct I/O dependencies exist (e.g., reading source files, writing intermediate results). - -Downstream flows are automatically triggered when upstream flows emit completion events. +* **Decoupling**: flows don't wait for downstream processing. +* **Resilience**: a failed downstream flow can be rerun without redoing upstream work. +* **Flexibility**: new listeners can subscribe to an event without changing its emitter. ## Event design ### Event naming convention -Events follow a consistent hierarchical naming pattern: `linc.opticstream.psoct.{hierarchy}.{state}`. - -* **Format**: `linc.opticstream.psoct.{hierarchy}.{state}` -* **Hierarchy levels**: `batch`, `mosaic`, `slice` -* **Standardized states**: `started`, `archived`, `processed`, `uploaded`, `ready`, `stitched`, `registered` - -This consistent naming convention enables clear identification of event hierarchy and state, making event routing and filtering straightforward. - -### Event catalog (examples) - -**Batch-level events** - -* `linc.opticstream.psoct.batch.ready` - Batch of tiles detected (to start converting to complex data) -* `linc.opticstream.psoct.batch.complexed` - Batch complex data prepared -* `linc.opticstream.psoct.batch.processed` - Batch of tiles processed (complex-to-processed conversion complete) - * Triggers: state management updates (emit `mosaic.ready` when all batches are done) -* `linc.opticstream.psoct.batch.archived` - Batch of tiles archived and compressed - * Triggers: upload flow, state management updates -* `linc.opticstream.psoct.batch.uploaded` - Batch uploaded to LINC storage - * Triggers: upload completion handlers - -**Mosaic-level events** - -* `linc.opticstream.psoct.mosaic.ready` - All tiles in mosaic processed (all batches complete) - * Triggers: mosaic stitching flow (`opticstream.flows.psoct.mosaic_process_flow.process_mosaic_event_flow`) -* `linc.opticstream.psoct.mosaic.enface_uploaded` - Enface outputs uploaded - * Triggers: mosaic/slice state updates and notification or downstream upload handlers -* `linc.opticstream.psoct.mosaic.volume_stitched` - Volume modalities stitched - * Triggers: volume upload flow -* `linc.opticstream.psoct.mosaic.volume_uploaded` - Volume modalities uploaded - * Triggers: upload completion handlers - -**Slice-level events** - -* `linc.opticstream.psoct.slice.ready` - Both mosaics in slice are stitched, ready for registration - * Triggers: slice registration flow -* `linc.opticstream.psoct.slice.registered` - Slice registration complete - * Triggers: slice state management flow, upload flow - -### `MOSAIC_READY` and mosaic stitching - -`process_mosaic_event_flow` requires `mosaic_ident` in the event payload. Stitching -parameters (grid sizes, masks, modalities, etc.) are taken from the project -config block (`PSOCTScanConfig`); the payload may override individual keys -(see `PROCESS_MOSAIC_FLOW_KWARGS_KEYS` in `opticstream.flows.psoct.utils`), same -idea as LSM strip flows. - -Emitters include `mosaic_ident` (e.g. `state_management_flow`, `check_mosaic_ready_hook` via `emit_mosaic_psoct_event`). - -### Event payload structure - -Event payloads carry contextual information needed by downstream flows: - -* **Project context**: `project_name`, `project_base_path` -* **Entity identifiers**: `mosaic_id`, `slice_id`, `batch_id` -* **Processing metadata**: `total_batches`, `grid_size_x`, `grid_size_y` -* **File paths**: Paths to processed files, coordinate files, templates -* **Output information**: Paths to generated outputs, artifact keys - -Payloads are automatically extracted by event-driven deployments using Jinja2 templates, enabling parameter passing from events to flows. - -### Deployment triggers - -Flows are deployed with event triggers that automatically start flows when matching events are emitted: - -* **Event matching**: Deployments listen for specific event names -* **Parameter extraction**: Event payloads are automatically mapped to flow parameters -* **Automatic triggering**: No manual intervention needed - flows start automatically when events are emitted +Events follow `linc.opticstream.psoct.{hierarchy}.{state}`, with hierarchy `batch`, `mosaic` +or `slice`. The constants are in `opticstream/events/psoct_events.py`; emitters are in +`psoct_event_emitters.py`. + +### Event catalog + +| Event | Emitted by | Triggers | +|---|---|---| +| `batch.ready` (`BATCH_READY`) | `ops oct watch`, once per complete, stable batch | `archive-tile-batch-event-flow` | +| `batch.archived` (`BATCH_ARCHIVED`) | `archive_tile_batch` after the gzip archives validate | `upload-to-dandi-batch-event-flow` | +| `batch.dandi_uploaded` (`BATCH_DANDI_UPLOADED`) | `upload_to_dandi_tile_batch` (milestone `dandi_uploaded`) | nothing yet | +| `mosaic.ready` (`MOSAIC_READY`) | `ops oct watch`, when the mosaic's last batch is dispatched | `preview-enface-mosaic-event-flow` | +| `mosaic.enface_stitched` (`MOSAIC_ENFACE_STITCHED`) | `preview-enface-mosaic` (milestone `enface_stitched`) | nothing yet | +| `slice.ready` (`SLICE_READY`) | `check_slice_ready_hook`, on completion of `preview-enface-mosaic` | nothing yet | + +These constants are kept but nothing emits them now: `BATCH_COMPLEXED`, `BATCH_PROCESSED`, +`BATCH_COMPLEX_ARCHIVED`, `BATCH_UPLOADED` (superseded by `BATCH_DANDI_UPLOADED`), +`MOSAIC_VOLUME_STITCHED`, `MOSAIC_VOLUME_UPLOADED`, `MOSAIC_ENFACE_UPLOADED`, +`SLICE_REGISTERED`. + +### When a batch and a mosaic are ready + +* **Batch**: every one of its `grid_size_y` (or `grid_size_y_tilted`) tiles has: + * its raw file (`spectral`, or `complex` when `tile_saving_type` is `complex`); + * the en-face maps mapped in `acquisition.filename_modality_map`: aip, mip, ori, ret, and + surf when mapped. + + The files must also be unchanged for `--stability-seconds`. `ops oct watch` refuses to start + when `filename_pattern` has no `{modality}` or the maps are not mapped. +* **Mosaic**: batches 1..`grid_size_x` all have batch state, i.e. `BATCH_READY` has been emitted + for each (`OCTMosaicStateView.all_batches_ready`). `MOSAIC_READY` does not wait for archiving + or uploads. +* **Slice**: every one of `mosaics_per_slice` mosaics (2: normal and tilted; 3: normal, tiltPos + and tiltNeg) has `enface_stitched` set (`OCTSliceStateView.all_mosaics_enface_stitched`). + +### Event payloads + +Every event carries the typed identifier (`batch_ident`, `mosaic_ident` or `slice_ident`), +which parses into `OCTBatchId` / `OCTMosaicId` / `OCTSliceId`. The resource carries +`linc.opticstream.project`, which deployment triggers match on when served for one project. + +| Event | Extra payload keys | +|---|---| +| `BATCH_READY` | `file_list` (raw files and en-face maps), `project_base_path`, `force_rerun` (with `--force-resend`) | +| `BATCH_ARCHIVED` | `file_list` (archives and BIDS sidecars to upload) | +| `MOSAIC_READY` | `input_dir`, `acquisition` (label), `image_offset` (continuous numbering: tile 1 is image `1 + image_offset`), `project_base_path`, `force_rerun` | +| `MOSAIC_ENFACE_STITCHED` | `enface_outputs`: modality → JPEG path | + +The event-flow wrappers (`*_event_flow`) turn the payload into flow parameters; the scan config +comes from the project's `PSOCTScanConfig` block. ## State management and observability -The system uses multiple complementary mechanisms for tracking processing state and providing observability: flag files (authoritative state), Prefect Artifacts (human-readable progress), Slack notifications (real-time updates), and event-driven state management flows (automatic state updates). - -For a detailed description of the PostgreSQL-backed project state store (locks, views vs mutable models, `open_*` / `read_*` / `peek_*` APIs), see the [state design](prefect_state_design.md) developer document. - -### Flag files - -Flag files serve as the authoritative source of truth for processing state. They enable idempotent operations, crash recovery, and efficient state checking without database queries. - -#### Flag file location and naming - -Flag files are stored in a `state/` directory at `{project_base_path}/mosaic-{mosaic_id}/state/`. The directory structure is shown in the OCT data flow doc. - -Flag files follow the naming pattern: `{hierarchy}-{id}.{state}` (e.g., `batch-0.started`). Note that flag files do not include the `linc.opticstream.psoct` prefix used in event names. - -**Batch-level flag files** (for MATLAB batch processing tracking): - -* `batch-{batch_id}.started` - Batch processing initiated -* `batch-{batch_id}.archived` - Batch archived and compressed -* `batch-{batch_id}.processed` - Batch processed by MATLAB (complex-to-processed conversion complete) -* `batch-{batch_id}.uploaded` - Batch uploaded to cloud storage - -**Mosaic-level state** - -* Mosaic completion determined by checking if all batches have `.processed` flag files -* `mosaic-{mosaic_id}.started` -* `mosaic-{mosaic_id}.stitched` -* `mosaic-{mosaic_id}.volume_stitched` -* `mosaic-{mosaic_id}.volume_uploaded` - -**Slice-level state** - -* Slice readiness determined by checking both mosaic states -* `slice-{slice_id}.started` -* `slice-{slice_id}.registered` -* `slice-{slice_id}.uploaded` - -#### Flag file lifecycle and benefits - -1. **Creation**: Flag files are created at key processing milestones -2. **Checking**: Flows check flag files before processing to avoid duplicate work (idempotency) -3. **Counting**: Mosaic and slice flows count flag files to determine completion status -4. **Persistence**: Flag files persist across flow runs, enabling recovery after crashes +Project state lives in PostgreSQL (see the [state design](prefect_state_design.md)). Each +level has a `processing_state` (pending, running, completed, failed) and boolean milestones: + +| Level | Milestones | Set by | +|---|---|---| +| Batch | `archived` | `archive_tile_batch` | +| | `dandi_uploaded` | `upload_to_dandi_tile_batch` (skipped, and not set, when the `dandi-uploads-enabled` Variable is false) | +| Mosaic | `enface_stitched` | `preview-enface-mosaic` | + +* **Batch state** is created by the watcher when it emits `BATCH_READY`, and marked completed + then. A recorded batch is never dispatched again unless `--force-resend` is given. +* **Mosaic processing state** follows `preview-enface-mosaic`: running while it stitches, + completed once `MOSAIC_ENFACE_STITCHED` is emitted, failed on an error. A completed mosaic is + skipped unless `force_rerun`. +* **Old rows**: state saved by earlier versions still loads. Removed fields (`complexed`, + `enface_processed`, `volume_stitched`, `registered`, ...) are ignored, and the old batch + `uploaded` flag reads as `dandi_uploaded`. +* **Resets**: `reset_archived` also clears `dandi_uploaded`. + +`ops oct progress ` shows, per slice and mosaic label, the batches archived, the +batches uploaded to DANDI, and the stitch status ("done", "stitching" once every batch is +ready, or "n/N batches"). `ops oct state show|reset|mark` inspect and edit the rows. ### Prefect artifacts -Prefect Artifacts provide human-readable progress reports visible in the Prefect UI. They complement flag files by providing formatted, visual progress tracking. - -**Mosaic progress artifacts** (`{project_name}_mosaic_{mosaic_id}_progress`): - -* Progress table showing batch state counts (started, archived, processed, uploaded) -* Progress percentage calculation -* Milestone tracking (25%, 50%, 75%, 100% completion) -* Timestamp of last update - -**Slice progress artifacts** (`{project_name}_progress`): - -* Progress table for mosaics -* Overall slice status - -Artifacts are updated automatically by state management flows and are visible in Prefect UI under flow run artifacts. - -### Notifications (Slack) - -Milestone-based notifications provide real-time updates on processing progress. - -**Notification milestones**: - -* **25% tile completion**: When 25% of tiles in a mosaic are processed -* **50% tile completion**: When 50% of tiles in a mosaic are processed -* **75% tile completion**: When 75% of tiles in a mosaic are processed -* **100% tile completion**: When all tiles in a mosaic are processed -* **Mosaic stitching complete**: When mosaic stitching is complete (includes stitched image preview) -* **Slice registration complete**: When slice registration is complete - -**Notification content**: - -* Processing milestone information (percentage, counts) -* QC image previews (stitched mosaics, registration results) -* Links to uploaded dandiset assets -* Error notifications for failures requiring attention - -Notifications are sent asynchronously and don't block processing flows. - -### State management flows +Prefect artifacts give human-readable progress tables in the Prefect UI. They are published by +the completion hooks of the archive, upload and stitch flows (`hooks/publish_hooks.py`): -State management flows are triggered by events, not called as subflows. This decoupled approach ensures state management doesn't block processing flows: +* **Per-mosaic artifact** (`{project}-mosaic-{id}-progress`): one row per batch, showing + processing state, archived and DANDI uploaded. +* **Project artifact** (`{project}-all-mosaics-progress`): one row per mosaic, showing batches, + archived, DANDI uploaded and en-face stitched. -* **Batch state flow** - * Scans flag files to count batch states - * Updates Prefect Artifacts with progress - * Checks if all batches are processed - * Emits mosaic completion event when all batches complete -* **Slice state flow** - * Checks state of both mosaics in slice - * Updates Prefect Artifacts with slice progress - * Checks if both mosaics are stitched - * Emits slice ready event when both mosaics complete +### Slack +* **En-face QC**: `preview-enface-mosaic` posts the mosaic's JPEGs (aip, mip, orientation, + retardance, surface) when the `slack-notifications-enabled` Variable is on. Uploads are + checkpointed per modality in the mosaic's `progress.json`. If any upload fails, the flow + fails and does not emit `MOSAIC_ENFACE_STITCHED`; a rerun posts only the missing ones. +* **Failures**: flows notify through `slack_notification_hook` on failure. +* **Reused file numbers**: the watcher warns through the webhook when files appear for a batch + that was already recorded. diff --git a/docs/developer/oct_future_extensions.md b/docs/developer/oct_future_extensions.md index 71ca4a9..3c302ed 100644 --- a/docs/developer/oct_future_extensions.md +++ b/docs/developer/oct_future_extensions.md @@ -4,14 +4,21 @@ title: OCT future extensions # OCT future extensions -## MATLAB to Python migration - -Planned improvements include: - -* **Replace MATLAB steps**: Migrate spectral-to-complex and complex-to-processed conversions to Python-native implementations -* **Eliminate batch processing**: Python can process tiles individually more efficiently, eliminating need for batch processing optimization -* **Maintainability**: Single language codebase improves maintainability -* **Performance**: Potential performance improvements by eliminating MATLAB startup overhead +## Replacing the removed MATLAB processing + +The MATLAB reconstruction (spectral → complex → volumes → en-face maps), Fiji tile-coordinate +stitching, 3D volume stitching and slice registration were removed. The pipeline now archives +the raw tiles and stitches the acquisition's own en-face maps for QC. Replacement processing can +subscribe to the events that are kept: + +* **Batch processing**: on `BATCH_READY`; may emit `BATCH_COMPLEXED` / `BATCH_PROCESSED`. +* **Mosaic stitching**: on `MOSAIC_READY` or `MOSAIC_ENFACE_STITCHED`; may emit + `MOSAIC_VOLUME_STITCHED`, `MOSAIC_VOLUME_UPLOADED` and `MOSAIC_ENFACE_UPLOADED`. +* **Slice registration**: on `SLICE_READY`; may emit `SLICE_REGISTERED`. +* **Building blocks**: the numpy ports in `opticstream.data_processing.psoct_recon` and the + stitching helpers in `opticstream.data_processing.stitch`. +* **Bookkeeping**: a new state milestone needs a rule in the spectral cleanup's + `MILESTONE_RULES`. ## Enhanced retry policies @@ -37,7 +44,7 @@ The OCT design provides a robust, scalable framework for distributed OCT data pr * **Event-driven orchestration**: Downstream flows are triggered by events, not synchronous waits, enabling decoupling, scalability, and resilience * **Hierarchical data organization**: Clear hierarchy of Tile → Mosaic → Slice → All-Slices, with tiles as the atomic data unit -* **MATLAB batch processing optimization**: Batch processing exists as an implementation detail for MATLAB efficiency, not as a data hierarchy level -* **Flag file-based state management**: Flag files serve as the source of truth for processing state, enabling idempotency and crash recovery +* **Batches as acquisition strips**: a batch is one strip of `grid_size_y` tiles, the unit the watcher detects, archives and uploads +* **PostgreSQL project state**: project state rows are the source of truth for processing state, enabling idempotency and crash recovery * **Hybrid host strategy**: Optimize for different workload characteristics (high I/O vs compute-intensive) diff --git a/docs/developer/oct_matlab_and_stitching.md b/docs/developer/oct_matlab_and_stitching.md deleted file mode 100644 index 1a760a5..0000000 --- a/docs/developer/oct_matlab_and_stitching.md +++ /dev/null @@ -1,180 +0,0 @@ ---- -title: OCT MATLAB batch processing, upload, and stitching ---- - -# OCT MATLAB batch processing, upload, and stitching - -## MATLAB batch processing (implementation detail) - -> See also the OCT data flow doc for a high-level overview of batch-level processing. This section provides additional implementation details. - -### Data hierarchy vs batch processing - -Batches are a temporary grouping used only during MATLAB processing for efficiency. - -### Grid configuration - -The grid configuration defines how tiles are organized for MATLAB batch processing: - -* **`grid_size_x`**: Number of batches (columns) per mosaic - * Determines how many batches are needed to process all tiles in a mosaic - * Each batch contains `grid_size_y` tiles -* **`grid_size_y`**: Number of tiles per batch (rows) - * Determines batch size for MATLAB processing - * Normal and tilted illuminations share the same `grid_size_y` -* **Total tiles per mosaic**: `grid_size_x × grid_size_y` - -### Why batches are used - -Batch processing is used specifically because MATLAB processing is more efficient when processing multiple tiles together: - -* Reduces MATLAB startup overhead by processing many tiles per session -* Enables better use of MATLAB's parallel operations -* Reduces the number of MATLAB processes and improves resource utilization - -### Batch organization and state tracking - -Tiles are organized into batches based on their position in the acquisition grid: - -* Each column (`grid_size_x`) becomes a batch -* Each batch contains `grid_size_y` tiles (rows) -* Batches are processed in parallel for efficiency - -Batch completion is tracked using flag files stored in the `state/` directory. See the events and state management doc for comprehensive details on flag file structure, lifecycle, and benefits. The batch-level flag files (`batch-{batch_id}.started`, `.archived`, `.processed`, `.uploaded`) enable progress tracking, idempotency, and crash recovery for MATLAB batch processing. - -### Post-MATLAB processing - -Once MATLAB batch processing completes, the system operates on individual tiles again for downstream processing (stitching, QC, coordinate determination). The batch grouping is only relevant during MATLAB processing and exists purely as an implementation optimization; tiles remain the atomic data unit in the hierarchy. - -## Upload strategy - -### Separate upload flows (event-driven, non-blocking) - -Uploads are handled by dedicated, event-triggered flows that run independently of compute pipelines: - -* **Event-triggered**: Upload flows are triggered by events (e.g., `linc.oct.batch.uploaded`) -* **Non-blocking**: Upload flows don't block compute-intensive processing -* **Isolated**: Upload failures don't affect compute pipeline -* **Independent retry**: Upload flows can retry independently without blocking upstream processing - -### Upload queue management - -Upload queue management enables controlled, concurrent uploads: - -* **Concurrency control**: Maximum number of concurrent uploads (e.g., 5) -* **Queue-based**: Files are queued for upload, processed by background workers -* **Non-blocking enqueue**: Adding files to upload queue returns immediately -* **Background processing**: Actual uploads happen in background threads/processes - -This prevents uploads from overwhelming network bandwidth or cloud storage APIs. - -### Cloud storage integration (DANDI/LINC) - -* **DANDI archive**: Processed data uploaded to DANDI archive for long-term preservation -* **LINC storage**: Raw compressed tiles uploaded to LINC storage -* **Symlinks**: Final outputs symlinked to DANDI/LINC storage locations -* **Metadata**: Upload events include metadata for tracking and verification - -### Upload retry and error handling - -* **Retry logic**: Upload failures are retried automatically with exponential backoff -* **Error logging**: Upload errors are logged for debugging and monitoring -* **Failure notification**: Critical upload failures trigger notifications -* **Resumability**: Partial uploads can be resumed using flag files - -## MATLAB integration - -### MATLAB invocation - -MATLAB is invoked from Python via command-line interface: - -* **Batch mode**: MATLAB runs in batch mode (non-interactive) for automation -* **Function calls**: Python constructs MATLAB function calls with batch of tiles -* **Path management**: MATLAB paths are configured to include required toolboxes and functions -* **Output capture**: MATLAB output is captured and logged for debugging - -### Batch processing requirement - -MATLAB processes tiles in batches (not individually) for efficiency: - -* **Spectral-to-complex**: Multiple tiles passed to MATLAB function for batch conversion -* **Complex-to-processed**: Multiple tiles passed to MATLAB function for batch processing -* **Reduced overhead**: Batching reduces MATLAB startup overhead per tile - -This is why batch-level processing exists - it's an optimization for MATLAB efficiency, not a data hierarchy level. - -### MATLAB functions used - -High-level MATLAB functions (not specific implementation details): - -* **Spectral-to-complex**: Converts spectral raw data to complex format -* **Complex-to-processed**: Converts complex data to 3D volumes and enface images -* **Surface finding**: Automatic surface detection from intensity data -* **Registration**: Thruplane registration for combining normal and tilted illuminations - -### Data flow between Python and MATLAB - -* **Python → MATLAB**: Batches of tile file paths passed to MATLAB functions -* **MATLAB processing**: MATLAB reads files, processes tiles, writes outputs -* **MATLAB → Python**: Processed tile files written to filesystem, Python reads results -* **File-based interface**: Communication via filesystem (no in-memory data transfer) - -### Future migration strategy - -When MATLAB steps are migrated to Python-native implementations: - -* Batch processing may no longer be necessary (Python can process tiles individually more efficiently) -* Data hierarchy remains Tile → Mosaic (no change to fundamental structure) -* Processing efficiency may improve (no MATLAB startup overhead) -* System becomes more maintainable (single language codebase) - -## Coordinate determination and stitching - -### Fiji-based coordinate determination - -Fiji (ImageJ) is used for initial tile alignment and coordinate determination: - -* **Tile configuration**: Fiji generates `TileConfiguration.txt` with initial tile positions -* **Overlap-based**: Uses tile overlap information to align tiles -* **First slice only**: Coordinate determination runs only for first slice of each illumination type -* **Template generation**: Coordinates are processed and converted to reusable templates - -### Template generation and reuse strategy - -Templates are generated once per illumination type and reused for all slices: - -* **Template generation**: Jinja2 templates generated from first slice coordinates -* **Template reuse**: Subsequent slices of same illumination type reuse template -* **Efficiency**: Avoids redundant coordinate determination for each slice -* **Consistency**: Ensures consistent tile positioning across slices - -Templates contain: - -* Tile positioning information -* Scan resolution parameters -* Base directory paths (parameterized for reuse) - -### Stitching process - -#### 2D enface stitching - -* **Template application**: Apply coordinate template to current mosaic tiles -* **Modality stitching**: Stitch each enface modality independently (AIP, MIP, orientation, retardance, birefringence, surface) -* **Mask generation**: Generate mask from stitched AIP using threshold -* **Mask application**: Apply mask to all stitched enface outputs -* **Output formats**: Save in multiple formats (NIfTI, JPEG, TIFF) - -#### 3D volume stitching - -* **Focus finding**: Determine optimal focus plane (first slice only) -* **Volume stitching**: Stitch 3D volume modalities (dBI, O3D, R3D) -* **Template reuse**: Use same coordinate template as 2D stitching -* **Mask application**: Apply mask to stitched volumes - -### Mask generation and application - -* **Threshold-based**: Mask generated from stitched AIP using intensity threshold -* **Background removal**: Mask removes background/noise regions -* **Consistent application**: Same mask applied to all stitched modalities -* **Quality control**: Mask quality validated as part of QC process - diff --git a/docs/developer/testing_and_ci.md b/docs/developer/testing_and_ci.md index f11c242..258914f 100644 --- a/docs/developer/testing_and_ci.md +++ b/docs/developer/testing_and_ci.md @@ -4,7 +4,23 @@ 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 -ra +``` + +Pytest excludes tests marked `integration` by default, so the local command +does not connect to Prefect or Docker. + +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/docs/developer/watcher_design_lsm_oct.md b/docs/developer/watcher_design_lsm_oct.md index 65f60f7..e72b449 100644 --- a/docs/developer/watcher_design_lsm_oct.md +++ b/docs/developer/watcher_design_lsm_oct.md @@ -51,16 +51,20 @@ For **step-by-step commands** for lab operators: ## OCT watcher (`opticstream oct watch`) -**Role:** Poll a **known acquisition folder** for spectral NIfTI tiles matching `*cropped_focus*.nii`, group them into batches using the configured **grid_size_y** (batch size), wait until each batch’s on-disk fingerprint is **stable**, then either: +**Role:** Poll a **known acquisition folder** for tiles named by `acquisition.filename_pattern`. -- **Direct mode (default):** run **`process_tile_batch`** in-process; or -- **`--no-direct`:** emit **`BATCH_READY`** so a Prefect deployment runs **`process_tile_batch_event_flow`**. +1. Group them into batches of the configured **grid_size_y** (batch size). A tile counts once it has its raw spectral file **and** the acquisition's en-face maps (aip, mip, ori, ret, and surf when mapped in `filename_modality_map`). +2. Wait until each complete batch's on-disk fingerprint is **stable**. +3. Emit **`BATCH_READY`** with the batch's files, and record the batch in project state. The served **`archive-tile-batch-event-flow`** deployment archives the raw tiles from that event. +4. When the last batch of a mosaic is recorded, also emit **`MOSAIC_READY`**, which starts the en-face stitch and Slack QC (`preview-enface-mosaic`). Its payload carries the folder, the acquisition label and the continuous-numbering offset. + +There is no in-process ("direct") mode and no separate preview watcher. `ops oct watch` refuses to start when the naming cannot locate the en-face maps. **Why check that each file is readable** Spectral files can appear in the directory **before** they are fully written or visible with correct permissions (slow writes, NFS or network filesystem quirks, or umask). Including only paths that are **regular files** (`Path.is_file()`) **and** pass **`os.access(..., os.R_OK)`** avoids: -- feeding incomplete files into MATLAB / downstream flows; +- feeding incomplete files into downstream flows; - noisy failures that are hard for operators to interpret. This check works together with **per-batch fingerprint stability**: the fingerprint includes file size and mtime, so incomplete writes tend to reset stability; readability filters paths the process can actually open. @@ -69,9 +73,13 @@ This check works together with **per-batch fingerprint stability**: the fingerpr **Skip / dedupe:** If **`peek_batch`** already has state for that mosaic batch and **`--force-resend`** is not set, the watcher skips that batch. -**Direct mode and disk refresh** +**Disk refresh** -Disk refresh is **optional**. Pass **`--refresh`** with a registered hook name (see **`opticstream.utils.refresh_disk`**: e.g. **`sas2`**, **`sas`**, **`sas3`**, **`none`**). When set, after each successful **`process_tile_batch`** in **direct** mode the watcher runs the corresponding unmount/mount scripts (for **`sas2`**, `/usr/etc/sas2_unmount` and `/usr/etc/sas2_mount`). If those scripts are missing or fail (e.g. on a dev laptop), the failure is logged as a warning and the loop continues. If **`--refresh`** is omitted, no refresh runs. +Disk refresh is **optional**. +- **Enabling it:** pass **`--refresh`** with a registered hook name (see **`opticstream.utils.refresh_disk`**: e.g. **`sas2`**, **`sas`**, **`sas3`**, **`none`**). +- **What it does:** after each batch the watcher emits, it runs the corresponding unmount/mount scripts (for **`sas2`**, `/usr/etc/sas2_unmount` and `/usr/etc/sas2_mount`). +- **Failures:** if those scripts are missing or fail (e.g. on a dev laptop), the failure is logged as a warning and the loop continues. +- If **`--refresh`** is omitted, no refresh runs. **Config loading:** The `PSOCTScanConfig` / project block is loaded **once** when the **`watch`** command starts, not on every loop iteration. @@ -82,7 +90,7 @@ Disk refresh is **optional**. Pass **`--refresh`** with a registered hook name ( Both watchers align with the rest of OpticStream by consulting **Prefect-backed project state** before doing work: - LSM: **`peek_strip`** (and optional **`open_strip`** after emit). -- OCT: **`peek_batch`** (and **`open_batch`** after emit in event mode). +- OCT: **`peek_batch`** (and **`open_batch`** after emitting `BATCH_READY`; `peek_mosaic` to decide `MOSAIC_READY`). That keeps “already submitted or completed” semantics consistent with flows that update the same state objects. diff --git a/docs/getting-started/configuration.md b/docs/getting-started/configuration.md index 3df4416..4460f3a 100644 --- a/docs/getting-started/configuration.md +++ b/docs/getting-started/configuration.md @@ -36,10 +36,24 @@ grid layout, overlap, formats, and stitching parameters for PS-OCT processing. It is composed from: - `PSOCTAcquisitionParams` (tile/grid geometry and acquisition metadata) -- `PSOCTProcessingParams` (MATLAB/processing behavior and algorithm options) - 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`. Project setup selects the `dandi-api-key` Secret block +by default (with a warning and the field left unset if that block does not exist). +Select another block in the Prefect dashboard, or pass its block name during +project setup, 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 @@ -48,7 +62,6 @@ OpticStream depends on several git-based Python packages during development, inc - `linc-convert` (LSM features branch) - `nifti-zarr` (port-multizarr branch) -- `psoct-toolbox` When you install OpticStream from its git repository (for example with `pip install -e .`), these packages are installed from the git URLs specified in `pyproject.toml`. This is the @@ -61,7 +74,6 @@ by using the `[tool.uv.sources]` section in `pyproject.toml`. For example: [tool.uv.sources] linc-convert = { path = "/path/to/your/local/linc-convert" } nifti-zarr = { path = "/path/to/your/local/nifti-zarr" } -psoct-toolbox = { path = "/path/to/your/local/psoct-toolbox" } ``` After updating the `path` values to match your machine, run: @@ -70,10 +82,9 @@ After updating the `path` values to match your machine, run: uv sync ``` -This causes `uv` to install `linc-convert`, `nifti-zarr`, and `psoct-toolbox` from your local +This causes `uv` to install `linc-convert` and `nifti-zarr` from your local directories instead of the remote git repositories, while other users who do not modify `[tool.uv.sources]` continue to use the default git URLs defined in `pyproject.toml`. The exact `path = "..."` values are machine-specific. Each developer should adjust them in their own clone as needed. - diff --git a/docs/oct_input_naming.md b/docs/oct_input_naming.md new file mode 100644 index 0000000..53642ae --- /dev/null +++ b/docs/oct_input_naming.md @@ -0,0 +1,149 @@ +# 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. +The default `filename_pattern` is `spectral_{image}_{modality}.nii` (see below). Setting it to +null selects legacy `mosaic__image__*` parsing. + +```json +{ + "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`, `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. + +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` (`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 +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_0001_processed_aip.nii`, +..., `spectral_0002.nii`, ...), keep the default `"filename_pattern": "spectral_{image}_{modality}.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: + +```bash +ops oct watch myproject /path/to/scanner/output +``` + +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` (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. +`--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. OpticStream never opens this file: the acquisition software rewrites it +while scanning, and a read could stop it from reaching the file. Tiles are placed +by number alone, so make sure Tiles in Tiling 1/2 match the grid sizes and both +programs start at the same slice. 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. + +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}_{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 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. + +A batch is ready once every tile has its raw file (`spectral`, or `complex` when +`tile_saving_type` is `complex`) and its en-face maps: the labels mapped to aip, mip, +ori and ret, plus surf when mapped (see acquisition_enface_previews.md). All of +these files go into the batch's `BATCH_READY` file list; the archive reads only the +raw file. Other mapped labels, such as the processed intensity volume, are not +batched. `ops oct watch` refuses to start when `filename_pattern` has no +`{modality}` or the en-face maps are not mapped. + +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 +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/docs/reference/cli_commands.md b/docs/reference/cli_commands.md index 8951343..1975dc5 100644 --- a/docs/reference/cli_commands.md +++ b/docs/reference/cli_commands.md @@ -44,8 +44,10 @@ 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 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 `