# Diatom field-review pilot

This prototype turns one native-resolution field from a tiled OME-TIFF Z stack into a static review bundle. A diatom-trained YOLO detector proposes boxes, MobileSAM produces a mask for each box, and a frozen ImageNet ResNet-18 retrieves species-labeled reference images. A reviewer can mark each proposal, enter or select a taxon, add a missed specimen, draw a separate rough visible outline for any candidate or manual mark, and download a review JSON that includes the bundle provenance and original suggestions.

**The species suggestions are not validated identifications.** The included demonstration gallery is tiny, from another dataset and microscope domain, and includes only a few taxa. Cosine similarities are not probabilities. The system does not know all freshwater species and can force a superficially similar reference for debris, an unknown taxon or a partial valve. Every proposed species remains unresolved until a person enters or selects a name. The review is not a scientifically validated count; a scientist must establish specimen identities, counting rules and taxonomy before production use.

The prototype runs inference on one plane and one field per invocation, and includes the same field from all focal planes for review. It can optionally generate experimental split alternatives, but it does not reliably separate merged instances, interactively generate model masks for manual points, deduplicate between fields or focal planes, create a taxonomic count table, or interface with a microscope. Manual outlines are polygons drawn by the reviewer and do not modify the original model masks. Incomplete or overlapping specimens can be marked separately, but proposals will miss some. Never interpret an unmarked region as empty.

The demonstration also displays an optional diatom-trained DIAMORPH model's top five suggestions for the original detector candidates and, where generated, split alternatives, tiled candidates and cross-plane tracks. This is a closed-vocabulary model and will offer a name even for debris or an unknown species; scores have not been calibrated on these slides. Suggestions are not copied into the reviewer taxon field. They can bias a reviewer, so blind independent expert annotation should be done without viewing them. Manual points do not currently receive these classifier suggestions. Model and taxonomy hashes and the candidate crop hashes are recorded in `classifier-suggestions.json`, which is included in new review exports.

Taxon hints and reference images are hidden initially. The **Show reference images and model taxon suggestions** checkbox reveals them for training or comparison; the review context records `taxonomy_hints_shown: true` once the checkbox has been enabled. Hiding hints afterward does not erase that record. Its absence in an older review is unknown, not evidence that the reviewer was unexposed. This is a convenience for independent review, not a blinded study: prior exposure, existing taxon entries, visible detector proposals, the downloaded JSON and accessible bundle files can all reveal information. A scientist should establish a separate blinded protocol for evaluation.

To add the same optional predictions to a different existing bundle, use `diatom_pilot/classifier_suggestions.py --bundle results/pilot/new-field --weights /tmp/diatom-diamorph-species-v2.pt`. To classify split alternatives, tiled candidates and cross-plane tracks, run the same command with `--alternatives`; it writes a separate manifest and requires the same checkpoint and taxonomy as existing original-candidate suggestions. The outputs must not already exist. The checkpoint is not included in this project; model provenance, diagnostic results and redistribution terms are documented in [R28](../research/R28.md) and [R30](../research/R30.md).

## Run the existing demonstration

The experimental environment and model files used during development are temporary. With those files present, run from the project root:

```sh
YOLO_CONFIG_DIR=/tmp/diatom-yolo-config MPLCONFIGDIR=/tmp/mpl-diatom \
  /tmp/diatom-research-venv/bin/python diatom_pilot/run_field.py \
  --slide scans/GC108240a_GS137733_40x_BF_Zstack_7stps_0.5um.ome.tiff \
  --x 29952 --y 19968 --z 2 \
  --output results/pilot/new-field \
  --detector /tmp/diatom-detector.pt \
  --segmenter /tmp/mobile_sam.pt \
  --encoder /tmp/resnet18-f37072fd.pth \
  --gallery results/r7/reference-manifest.json
```

The output directory must be new or empty. The tool rejects scans smaller than 1 GB, probes the TIFF tail through `experiments/scan_fields.py`, verifies bounds, and reads only the requested field. Native pixel coordinates, scale, model hashes, detector parameters, image paths, reference labels and reference-image hashes are stored in `bundle.json`. The script expects an 8-bit grayscale OME-TIFF stack with the layout supported by `Stack`; arbitrary microscope formats are not supported. It requires Python, libtiff, Pillow, NumPy, PyTorch, torchvision and ultralytics in a compatible environment. Use only checkpoints from sources you trust.

## Run a list of fields

The [example jobs file](/results/pilot/batch-practice-jobs.json) lists two manually chosen practice fields; its `slide` paths are relative to the working directory. A jobs file has format `diatom-field-jobs-v1` and a `fields` array. Each field specifies a unique `id`, scan path, integer `x`, `y` and `z`, and optional square `size` (default 768 pixels). Run from the project root:

```sh
/tmp/diatom-research-venv/bin/python diatom_pilot/batch_fields.py \
  --jobs results/pilot/batch-practice-jobs.json --output results/pilot/batch-practice \
  --detector /tmp/diatom-detector.pt --segmenter /tmp/mobile_sam.pt \
  --encoder /tmp/resnet18-f37072fd.pth --gallery results/r7/reference-manifest.json
```

The generated [batch index](/results/pilot/batch-practice/) links to each review page. New runs publish a progress snapshot at job boundaries, so finished fields can be opened while later fields are still pending. The page refreshes periodically, but checking or processing status can be stale if the runner stops; the timestamp is not a heartbeat. The runner checks the 1 GB cutoff and the existing field pipeline's image and model constraints. Completed outputs can be resumed only if their scan name and size, coordinates, model hashes, focal-plane hashes and required files match. On failure, a `.partial-…` directory is retained for inspection; move it out of the output directory after inspection before retrying that field. This is a list of selected fields, not whole-slide processing or a sample-separated performance evaluation.

For split-mask alternatives in a new batch, add `--split-proposals`; these are hypotheses, not confirmed distinct specimens. For a new batch, add `--stack-proposals --species-weights /tmp/diatom-diamorph-species-v2.pt` to run cross-plane detection and produce specialist suggestions for both original candidates and tracks before each field is published. The [two-field example](/results/pilot/batch-stack-practice/) has two and one track hypotheses, respectively; these can duplicate the original detections or merge specimens, and model names are not expert identifications. Existing fields are not modified when these options are newly requested; use a new batch output directory. Click **Show additional cross-plane hypotheses** on a field page to see tracks and **Show reference images and model taxon suggestions** to reveal names.

Serve the repository with an HTTP server and open the bundle's `index.html`. To outline a candidate, select **Draw visible outline** on its card; to outline a missed specimen, first add its point and use the same action on the resulting manual card. Click around the visible boundary, use **Undo last point** if needed, and select **Finish outline** after at least three distinct, non-collinear points. Draw separate outlines for overlapping specimens. Redrawing replaces the previous reviewer outline only when finished; cancel keeps it. Export is disabled while a draft outline is in progress. Coordinates are integer pixels relative to the field origin on the recorded Z plane; they are not inferred 3D or amodal masks.

Use the **Focal plane** selector to view other planes at the same field coordinates. Detector boxes are guides from their source planes and may not align perfectly on other planes; each model mask appears only on its own source plane. Manual points and reviewer polygons appear on their recorded planes. An individual record has one reviewer outline; redrawing it on another plane replaces the previous outline after finishing. The export records each manual point's `z` and each reviewer's `outline_z`; older reviews without these fields are interpreted as belonging to the model plane. The focal-plane manifest contains image hashes but does not prove registration between planes.

The demonstration field also offers **Show additional cross-plane hypotheses**. These are the 13 existing R5 greedy linked tracks, represented by their highest-confidence plane. Selecting one moves to its source plane; its mask appears only there. They are optional candidates, not confirmed specimens: they can duplicate the six original proposals, merge overlapping valves, split one valve across tracks, or contain non-diatoms. The review export preserves each track's source plane and observations; the ingestion tool uses that plane for its mask and crop. No automatic deduplication or counting is performed.

For a cross-plane track, the orange box follows the recorded detector observation on each plane where the track was detected. On other planes the orange box is dashed and shows the representative box as an approximate guide. The **Observed on** buttons in a track's card jump to individual recorded planes. These boxes and their links are model hypotheses, and the focal planes are not guaranteed to be registered.

For a different existing field bundle, generate cross-plane hypotheses with its original model files and gallery:

```sh
/tmp/diatom-research-venv/bin/python diatom_pilot/stack_proposals.py \
  --bundle results/pilot/new-field --detector /tmp/diatom-detector.pt \
  --segmenter /tmp/mobile_sam.pt --encoder /tmp/resnet18-f37072fd.pth \
  --gallery results/r7/reference-manifest.json
```

This runs the same detector on each saved focus plane, greedily links boxes across adjacent planes using IoU, and segments the highest-confidence observation of each track. It verifies the model and focus image hashes against the bundle and records the per-plane proposal limits and linking settings. `--link-iou` and `--max-z-gap` control linking; defaults are 0.3 and one plane. It refuses to replace an existing stack manifest or stack image directory. These links assume comparable coordinates across planes and can miss specimens or combine distinct overlapping valves; they must be reviewed, not counted automatically. Omitting `--detector` retains the original R5-track mode for the specific previously analyzed field. Details and limitations are in [R5](../research/R5.md).

Each bundle is static: review decisions stay in browser storage associated with the bundle ID and are **not uploaded** to the server. Download the JSON when finished and move it to the project for incorporation. The export preserves the bundle metadata and proposed candidates, the available focal-plane manifest, reviewer decisions, manually added positions and reviewer polygons in `outline`. Keep the bundle directory with its images when sharing or archiving an export.

To continue on another computer, download the review JSON, transfer that file, open the same field's review page and choose **Open saved review JSON**. The page checks the saved bundle and focal-plane, split and cross-plane manifests against those currently available before opening it. Opening a review replaces the receiving browser's review for that field after confirmation; download any existing work first. The file stays on the computer in its browser and is not uploaded to the server. If a required manifest is unavailable or has changed, restore the matching bundle before opening the file.

If browser-stored decisions reference candidate IDs or focal planes unavailable on the current page, the page blocks a normal review export and displays a persistent warning. Reopen the matching field page with its original proposal and focal-plane files to export the complete review. A separate **Download browser recovery backup** preserves the current state for manual recovery, but is not an importable review or a replacement for the missing provenance. Candidate-ID checks cannot prove that two different proposal manifests with the same IDs describe the same objects; retain the original files and exported reviews.

Reviewers can optionally record their ID, their self-described experience and the biological sample ID, and state whether they attempted to mark the complete field. Each record can separately mark partial visibility, overlap and an optional shared overlap-group ID. These are reviewer statements, not automatically verified facts; unassessed flags stay unknown. An incomplete field must not be used to infer negative examples or recall.

For each candidate or manual mark, the reviewer can record a taxon rank (genus, species or other) and whether the identification is tentative, confident or unresolved. These are independent reviewer statements; the software does not infer rank from a name, verify taxonomy, or turn a confidence choice into an adjudicated label. Earlier reviews without these fields remain `unknown` when ingested.

The [practice review import page](/results/pilot/batch-stack-practice/practice-review-import.html) offers portable reviews for two fields from the earlier nonexpert practice round. Download the appropriate JSON and open it on the matching field page. Import replaces that browser's current review after confirmation, so save any work to keep first. These manual points can duplicate model candidates and are neither adjudicated identities nor an exhaustive count.

The [practice mark comparison](/results/pilot/batch-stack-practice/observation-comparison/) shows these points against the original proposals and the track observations on the marked plane, with one-to-one point containment assignments for boxes and masks. Track masks exist only on their representative planes, so a track can have a comparable box but no comparable mask. In these two fields the pooled proposals match the same points as the original candidates. This is a tiny, nonexpert diagnostic rather than an estimate of recall or precision. Recreate it with `diatom_pilot/practice_coverage.py --batch results/pilot/batch-stack-practice --jobs results/pilot/batch-practice-jobs.json --output NEW_EMPTY_DIRECTORY`.

For other matching fields, `diatom_pilot/import_practice.py --practice results/diatom-practice-round1.json --bundle results/pilot/FIELD --output results/pilot/FIELD-practice-review.json` converts matching practice points. It checks slide, field origin, slide coordinates and focal planes; preserves the original flags in notes; carries forward explicit partial flags; and records the source hash and provisional nonexpert status. An `edge` or `cross` flag is not automatically interpreted as overlap or a partial specimen.

## Prepare reviewed specimens

Once a downloaded review JSON and its exact bundle are available locally, make a traceable specimen package:

```sh
/tmp/diatom-research-venv/bin/python diatom_pilot/ingest_review.py \
  --review results/diatom-field-review.json \
  --bundle results/pilot/field-01 \
  --output results/reviewed/example \
  --sample-id biological-sample-id --reviewer-id reviewer-id --reviewer-role nonexpert
```

Sample and reviewer IDs are required either in the review or as arguments. The same biological sample must use the same sample ID across slides and focal planes. Conflicting values are rejected. The output directory must be new or empty. The manifest records review provenance, the supplied role, self-reported field coverage, specimen decisions, taxon text, partial/overlap flags, group IDs, and geometry provenance. Crops and masks use the recorded focal plane; reviewer polygons and unverified model masks remain distinct. A manual point without an outline yields a `manual_point_context` image centered on the mark, clipped at field edges, with no mask or asserted boundary. Its default radius is 128 pixels; change it with `--point-crop-radius`. The crop can contain neighboring specimens or debris and is not an isolated or validated training instance. Alternatives remain separate records and can be duplicates: this tool does not deduplicate, automatically count, or adjudicate them.

Even a self-reported expert review remains unadjudicated. No unreviewed or rejected candidate, guessed taxon rank, missing annotation or unassessed field should silently become a training label or an evaluation negative. Use sample-separated, expert-reviewed and adjudicated data under a scientist-approved protocol before assessing the 95%/60% targets.

## Propose masks from manual points

To generate review-only masks for manual marks marked **Possible specimen** or **Countable specimen**, use the exported review and its exact field bundle:

```sh
/tmp/diatom-research-venv/bin/python diatom_pilot/point_masks.py \
  --review results/diatom-field-review.json --bundle results/pilot/field-01 \
  --segmenter /tmp/mobile_sam.pt --output results/pilot/point-masks
```

Open `index.html` in the output to inspect the overlays. The point-only proposal uses the mark as a positive prompt. When multiple eligible marks on the same plane have the same nonempty overlap-group ID, a second proposal uses the other marks as negative prompts. This treats each mark as a different object; use distinct points and assign the same group only when that is what the reviewer intends. Marks on different focal planes are not used as negatives for each other. The output records the prompts, model and source hashes, and whether the mask contains the prompts. It does not update the review or turn the masks into accepted annotations. The [practice preview](/results/pilot/point-prompt-practice/) shows three provisional marks; it is not an expert accuracy assessment.

Optionally pass `--local-radius 160` (or another positive radius in field pixels) to add proposals inferred from a bounded crop around each mark. Only negative points inside that crop are used. The output maps masks back to field coordinates, draws the local inference boundary in blue and flags masks touching that boundary. A local crop can truncate a specimen or make a background mask look smaller; neither outcome indicates a correct segmentation. In the [three-mark comparison](/results/pilot/point-prompt-local-practice/), the broad background failure remains and all local masks touch an inference edge.

## Experimental split alternatives

Pass `--split-hypotheses` to generate alternatives during bundle creation. To add them to an existing bundle without changing its ID or prior browser reviews:

```sh
YOLO_CONFIG_DIR=/tmp/diatom-yolo-config MPLCONFIGDIR=/tmp/mpl-diatom \
  /tmp/diatom-research-venv/bin/python diatom_pilot/split_hypotheses.py \
  --bundle results/pilot/field-01 --segmenter /tmp/mobile_sam.pt \
  --encoder /tmp/resnet18-f37072fd.pth --gallery results/r7/reference-manifest.json
```

For masks with two interior-distance peaks, the generator alternates positive and negative points and keeps sufficiently distinct model masks. The review page displays alternatives in purple with their parent proposal. They may be duplicates, debris, or pieces of one valve, and are **not** additional confirmed specimens. Species suggestions on these crops have the same limitations as other suggestions. The research basis and limits are in [L20](../research/L20.md). The `split-alternatives.json` extension records prompts and parent IDs and is included in the review export. It is separate from the original bundle so adding it does not invalidate existing browser reviews.

## Gallery format and provenance

`--gallery` accepts a JSON array, or an object with a `rows` array. Each entry needs `species` and `local_file` relative to the manifest. `source_slide` and `annotation_id` are retained when available. If entries have a `split` value, only `gallery` entries are used; omit `split` for a custom reference gallery. Empty or literal `None`, `null`, `nan`, and `n/a` labels are excluded. The tool copies reference images into the output and records their hashes; only use images you are authorized to copy and serve. Use expert-confirmed, properly licensed voucher references with sample-disjoint evaluation before treating suggestions as meaningful.

The demonstration reference images and labels are from [UDE DIATOMS in the Wild 2024](https://doi.org/10.5281/zenodo.10410655), credited in [R7](../research/R7.md). Its frozen detector is a public diatom model with noncommercial/share-alike terms documented in [R3](../research/R3.md); verify all model and dataset terms before redistribution or deployment. The weights are not included here. Their exact hashes are in each bundle.

## Generate a grid of fields

`grid_jobs.py` creates jobs for a rectangular scan region. For example, this produces four overlapping 768-pixel fields covering a 1,024 × 1,024 pixel region:

```sh
/tmp/diatom-research-venv/bin/python diatom_pilot/grid_jobs.py \
  --slide scans/GC104890a_GS028783_40x_BF_Zstack_8stps_0.5um.ome.tiff \
  --region 19968 29952 1024 1024 --z 0 --size 768 --stride 512 \
  --output results/pilot/grid-practice-jobs.json
```

Pass the resulting jobs file to `batch_fields.py`. The [example grid results](/results/pilot/grid-practice/) use the selected plane; one field had no model proposal, which does not imply it is empty. The last field aligns with the region edge, so the final stride can be smaller than requested. Omitting `--region` requests the scan's full image bounds; the default 1,000-field cap prevents accidental huge runs and can be explicitly changed with `--max-fields`. Scans under 1 GB are rejected. Overlapping fields may repeat the same specimen; cross-field deduplication and whole-slide counts are not implemented.

For a completed grid, `cross_field_duplicates.py --batch results/pilot/grid-practice --jobs results/pilot/grid-practice-jobs.json --output results/pilot/grid-practice/duplicate-review-with-crops` flags overlapping model-mask pairs for review. The [example report](/results/pilot/grid-practice/duplicate-review-with-crops/) shows one pair. The tool checks that pixels agree in the shared area, compares masks only on the same Z plane, and reports candidates above adjustable overlap thresholds. These are suggestions only: distinct overlapping diatoms can also have overlapping masks, and missing masks or other planes are not assessed. It never merges records or calculates a specimen count.

The [interactive duplicate review](/results/pilot/grid-practice/duplicate-review-interactive/) lets a reviewer mark each suggested pair as likely the same, likely different, or unsure and download the decisions. The export embeds the exact pair data and its hash. To continue on another computer, download the JSON, open the same duplicate review page there, and use **Open saved pair review**. The importer verifies the pair data before asking to replace that browser’s review; download any existing work to keep it first. Decisions are saved in that browser until downloaded and are self-reported, not adjudicated; they do not merge records. As with field review, bring in a scientist before relying on those decisions.

## Optional tiled detector hypotheses

`tile_proposals.py --bundle results/pilot/FIELD --detector /tmp/diatom-detector.pt --segmenter /tmp/mobile_sam.pt --encoder /tmp/resnet18-f37072fd.pth --gallery results/r7/reference-manifest.json` runs overlapping tiles on the bundle's model plane and adds a separate optional proposal manifest. It uses the bundle's detector confidence, 384-pixel tiles, stride 256, 640-pixel detector input and 0.5 global box IoU suppression by default; settings and proposal counts are recorded. Global suppression can discard nearby overlapping specimens, and tile boundaries can split or truncate them. Original candidates remain visible and are not suppressed against tiled candidates, so duplicates are expected. A new bundle copies the current review page; to add this extension to an older bundle, update its `index.html` from `diatom_pilot/review.html` after preserving any local changes.

In the [first practice-field preview](/results/pilot/tile-practice/comparison.html), the original and tiled box each contain a different one of two provisional marks. The preview is not an expert or sample-separated accuracy test. Tiled hypotheses appear when their checkbox is enabled and remain unverified when exported or ingested.

For new batches, add `--tile-proposals` to generate tiled candidates, and combine it with `--species-weights /tmp/diatom-diamorph-species-v2.pt` to generate provisional specialist suggestions for them. The [combined example](/results/pilot/tile-stack-practice/) includes full-field, tiled and cross-plane candidates; use the respective checkboxes to reveal the alternatives and the taxonomy-hints checkbox to reveal names. Existing output bundles are not modified when new options are requested; use a new output directory.

## Prepare species-label crops for development

After ingesting one or more field reviews, create a JSON split map such as `{"format":"diatom-sample-splits-v1","samples":{"sample-a":"train","sample-b":"validation"}}`. Use the same biological sample ID for every field, slide and focal plane derived from that sample. Then run:

```sh
/tmp/diatom-research-venv/bin/python diatom_pilot/prepare_classifier_data.py \
  --package results/reviewed/example --split-map results/sample-splits.json \
  --output results/classifier-data/example --allow-provisional
```

Repeat `--package` for additional reviewed packages. Only explicitly species-ranked, non-unresolved, possible or countable records with an instance mask and crop are included. Point-only context crops are excluded; partially visible and overlapping examples are retained with their flags. The tool checks image and mask hashes, records review and sample provenance, and rejects an exact crop shared across splits. It does not establish biological sample independence, reconcile synonyms, remove duplicates within a split, verify masks, or train a model. Unadjudicated labels require `--allow-provisional` and cannot enter the test split. Initial review ingestion does not produce adjudicated packages. A later expert adjudication step is available below; a scientifically valid expert-reviewed held-out test set remains to be established before final evaluation.

`train_centroids.py --dataset results/classifier-data/example --encoder /tmp/resnet18-f37072fd.pth --output results/classifier-model/example --allow-provisional` fits a simple class centroid to frozen ResNet-18 embeddings from training rows and scores validation rows. At least two training species are required. It checks declared sample separation and crop hashes, and never opens or scores test images. It records training counts, sample IDs, model hashes, validation predictions and validation species absent from training. This is a closed-set development baseline: it forces a nearest species for unknown taxa and the similarity is not a calibrated probability. Provisional labels require explicit opt-in. Sample IDs and labels still need scientific verification, and a model trained or selected this way cannot by itself establish the end-to-end accuracy goals.

To show a trained centroid model's suggestions on a field, run `diatom_pilot/centroid_suggestions.py --bundle results/pilot/FIELD --model results/classifier-model/example --encoder /tmp/resnet18-f37072fd.pth --sample-id BIOLOGICAL_SAMPLE_ID`. The page displays them only after taxonomy hints are revealed, keeps the reviewer taxon blank, and exports the suggestion manifest. It scores original, split, tile and cross-plane candidates present when the command runs. The command rejects declared held-out sample IDs and bundle IDs, but it cannot detect mislabeled or biologically related samples; reserve the test set independently. Models created before held-out IDs were added to the model metadata must be retrained before this command can use them. For an older bundle, update its page from `diatom_pilot/review.html` after preserving local changes. No open-set detection or calibrated probability is provided.

Add `--crop-mode masked` when fitting centroids to replace pixels outside each supplied mask with that crop's median background intensity. Prediction uses the same masking mode recorded in the model, crops each full-field model mask to its candidate box, and skips candidates with no mask or no foreground inside the crop. The prediction manifest records mask hashes and skip reasons. With the default legacy framing, training packages crop around mask bounds with padding while field candidates use detector boxes, so framing can differ. When training a new model, `--crop-framing mask_bounds_8` instead uses mask bounds plus eight pixels of context for both training and inference, for raw or masked crops. Models record this choice; existing models continue using legacy framing. A candidate without a usable mask yields no suggestion in the new framing mode. A wrong or incomplete mask can remove relevant parts of an overlapping or partial diatom, so this mode is experimental and should be compared with raw crops under a scientist-approved, sample-separated evaluation.

For genus suggestions, add `--taxonomy-map path/to/taxonomy.json` when training. The supplied file must have format `diatom-taxonomy-map-v1`, a `version` string, and a `species_to_genus` object mapping every training species to an explicit genus, for example `{"format":"diatom-taxonomy-map-v1","version":"example-only","species_to_genus":{"Example species":"Example"}}`. A real map needs scientific review. The model records its hash and training-species mappings; validation rows without mapped genera are reported as unmapped. Candidate genus suggestions rank the maximum species similarity within each genus. They are closed-set suggestions, not calibrated probabilities or proof of 95% genus accuracy.

The classifier-data preparation and centroid trainer also require a consistent biological sample ID for each slide and reject the same source-field image across splits, even if crop images differ. New centroid models record held-out slide names as well as sample and bundle IDs; the field suggestion command refuses a matching held-out slide. These checks use declared IDs and slide names, not a verified biological sample registry. Different slides of one sample, renamed copies, near-duplicate images and incomplete split maps still require explicit review. Datasets created before slide and source-field provenance was added must be regenerated, and older centroid models without held-out slide metadata must be retrained before generating suggestions.

Newly generated point-mask pages allow a reviewer to choose a preferred variant for each mark and download the choices. The [practice example](/results/pilot/point-prompt-review-practice/) uses three provisional marks. To carry choices into specimen packages, run `ingest_review.py` with both `--point-proposals PATH_TO_PROPOSAL_DIRECTORY` and `--point-choices PATH_TO_DOWNLOADED_CHOICES_JSON`, alongside the original field review and bundle. A mask reviewer ID is required. The ingester checks that the choices refer to the exact source review, proposal manifest, plane and mask file. A reviewer-drawn outline and a selected model mask cannot both be assigned to the same mark in one package. The chosen geometry is labeled `model_mask_reviewer_selected`, not a reviewer-drawn outline or adjudicated mask; classifier data preparation keeps that provenance. Older point-proposal reports without mask hashes must be regenerated before choices can be ingested.

When a saved review includes detector candidates, add `--candidate-boxes` to `point_masks.py` to generate an additional point-plus-box variant for each mark contained by a same-plane original, tiled or cross-plane representative box. The smallest containing box is selected; its ID, coordinates and source manifest hashes are recorded. When other marks in the same overlap group lie inside the box on that plane, a further variant uses them as negative points. [Two provisional practice examples](/results/pilot/tile-point-practice/) show the alternatives. A box can be wrong, omit part of a specimen or merge neighboring diatoms; no result is automatically promoted. The reviewer can select a variant using the same mask-choice and ingestion workflow.

To continue mask review on another computer, download mask choices and transfer the file, then open the same proposal page and select **Open saved mask choices**. The page checks the saved proposal data and asks before replacing the receiving browser's choices. This does not upload decisions to the server.

On the field-review page, the **Zoom** control enlarges the displayed image up to four times fit-to-width; scroll inside the image area to inspect other locations. Saved marks and outlines remain in native field coordinates. Zoom enlarges existing pixels and does not add optical detail.

`validation_thresholds.py --model results/classifier-model/example --output results/classifier-thresholds/example` reports validation-only acceptance, correct/eligible, correct/accepted and acceptance of validation taxa absent from training over a fixed similarity grid. Repeat `--threshold VALUE` to supply a different grid. The program does not choose a threshold; validation-selected settings can overfit, especially when examples or unknown taxa are scarce. For a later development field, `centroid_suggestions.py` can take explicit `--species-threshold` and, with a taxonomy map, `--genus-threshold`. Below a threshold the rank abstains; the reviewer can still inspect ranked hints. Genus and species use the same maximum similarity, so when both thresholds are supplied the genus threshold cannot exceed the species threshold. No threshold is calibrated by default, and held-out test IDs remain protected by the existing checks. Validation uses preselected crops and cannot measure missed detections or prove the end-to-end targets.

For genus-only classifier development, add `--rank genus` to `prepare_classifier_data.py`. Explicit genus-ranked review labels are retained. Species-ranked labels can also be included when `--taxonomy-map` supplies an explicit versioned species-to-genus map; unmapped species are excluded rather than parsed or guessed. `train_centroids.py` recognizes the dataset rank and trains a separate genus model; its field suggestions report genera only. These models and labels remain provisional until reviewed and evaluated on independent samples, and they do not establish the genus target.

Genus and species centroid models can both be run against a field using `centroid_suggestions.py`. Species outputs use `centroid-suggestions.json`; genus-only outputs use `centroid-genus-suggestions.json`. Both commands must declare the same biological sample ID, and each independently checks its held-out samples and slides. The review page shows the two models separately, since their suggestions can disagree; it does not combine them into a confirmed identification. Previously generated genus-only suggestions under the older `centroid-suggestions.json` name remain readable, but must be regenerated into separate manifests to add a species model alongside them.


## Specimen adjudication by an expert

Run `make_adjudication_page.py --package results/reviewed/example --output results/adjudication/example` to prepare a static page of specimen crops without showing previous taxon labels. The page can be practiced by a nonexpert, but applying decisions requires a declared expert ID, expert role and protocol ID. The [practice page](/results/pilot/adjudication-practice/) uses provisional nonexpert points and a placeholder sample ID; no expert has adjudicated it.

After a qualified reviewer downloads the decisions, run `apply_adjudication.py --package results/reviewed/example --decisions DOWNLOADED_DECISIONS.json --output results/reviewed/adjudicated-example`. It verifies the source package and crop hashes, writes a separate package, and retains original review labels alongside the later decision. A confirmed or rejected item is marked as adjudicated; unsure and unreviewed items are not. The new package records the self-declared adjudicator and protocol separately from the original reviewer. `prepare_classifier_data.py` accepts a declared expert-adjudicated label without `--allow-provisional`; test-split labels additionally require explicit confident identification.

This workflow does not verify a person's credentials, the independence of their review, the quality of model-generated masks, specimen duplicates, or that all objects in a field were annotated. Showing crops without previous names does not itself establish blinding. An Academy scientist must establish and oversee the adjudication protocol and biological sample splits before using the resulting labels for final testing.

Pass `--bundle FIELD_BUNDLE_DIRECTORY` when creating an adjudication page to include the same specimen crop from each saved focal plane. The generator verifies the field and focal-plane hashes and checks that the original crop matches its source pixels. The [focal-plane practice page](/results/pilot/adjudication-practice-z/) shows two provisional point-centered crops. When applying decisions from such a page, pass `--display-bundle FIELD_BUNDLE_DIRECTORY` to verify and retain the recorded display provenance. The same XY crop is used on each plane; registration is not verified, and the provenance records which images were available, not which ones the reviewer actually inspected.

In the field reviewer, use **Compare A** and **Compare B** on candidate cards to overlay two model masks: A is cyan and B is orange. **Clear mask comparison** returns to the normal single-mask display. Masks only appear on their own source planes; when A and B come from different planes, change focus to inspect each rather than interpreting them as a registered overlay. This is a visual aid, not a determination that the candidates are the same or different specimens.

With two masks selected, choose **Likely the same specimen**, **Likely different specimens**, or **Unsure**, optionally add a note, and click **Record assessment**. The opinion is saved in browser storage and the downloaded review, and can be removed for that pair. Record it before selecting a different pair. Ingestion retains the assessment, reviewer context, and both original proposal records as unadjudicated `candidate_relationships`; it does not merge proposals, change specimen counts, or treat the opinion as expert validation.

Expand **Recorded pair assessments** to find previously recorded opinions and reopen their two masks. Opening a pair enables the extra proposal layers it needs. If proposal files are unavailable, the pair cannot be reopened and the review must be recovered with its original field files.

Classifier-data preparation stops if both candidates in a recorded **same** or **unsure** pair are eligible crops in the same package. Review that pair and update its assessment or exclude one candidate in the field review, then export and ingest the review again. It also stops when two eligible candidates are connected through a chain of recorded likely-same relationships, even if an intermediate candidate is excluded. This is a conservative review flag, not proof that the endpoints are the same specimen. It cannot find unrecorded duplicates or verify an assessment that two candidates are different.

New specimen adjudication pages also list recorded candidate pairs without showing the previous pair opinion. The reviewer can select same, different, or unsure and add a note; the original opinion remains in the package alongside the declared expert assessment when decisions are applied. Pair crops may be missing or inadequate, so inspect the original field and focal planes. This workflow records declared expertise and available display provenance; it cannot establish reviewer credentials, actual image viewing, or whether a pair is resolved correctly. Classifier-data preparation uses the declared expert pair assessment when its adjudication provenance matches the package, otherwise it uses the original opinion. Previously generated adjudication pages must be regenerated to include pair controls.

When an adjudication page is generated with `--bundle`, each recorded pair includes shared field context across the verified focal planes, even when one proposal has no specimen crop. Cyan A and orange B boxes show the recorded proposal coordinates; they are approximate guides, repeated without registration across planes, not specimen outlines. Consult the original field when those guides or crops are inadequate.

The [pair-adjudication practice page](/results/pilot/pair-adjudication-demo/) shows a model proposal and its split alternative on a real field. Its sample ID, specimen decisions, and pair opinion were synthesized for this demonstration; they are not human or expert labels.

Adjudicators can download decisions and use **Open saved decisions** on another computer to resume the same package and focal-plane display. Opening a file replaces that browser’s decisions for the package after confirmation. The page checks the source package hash, display provenance, and specimen and pair IDs before importing; keep a downloaded backup.

To apply a downloaded cross-field duplicate review while preparing classifier data, add `--cross-field-review DOWNLOADED_REVIEW.json --cross-field-pairs PAIR_REVIEW_DIR/pairs.json --cross-field-jobs JOBS.json --cross-field-batch BATCH_DIR` to `prepare_classifier_data.py`. Repeat all four arguments in the same order for additional batches. The command checks the review, source pair and job hashes, bundle identities, proposal planes and masks, then stops if two eligible crops are marked likely-same or unsure. It also flags eligible crops connected by a chain of likely-same assessments, including links within individual fields; these are conservative review flags, not automatic merges. The dataset records the supplied review hashes, reviewer role and number of unreviewed pairs. Newly generated cross-field review packages also bind the source field images, source crops and rendered review images by hash; the training guard verifies them and records `display_assets_verified: true`. Older review packages remain usable as conservative flags, but lack those image hashes and are recorded as `display_assets_verified: false`; they cannot establish which images were presented. A different or unreviewed assessment does not establish distinctness, and pairs absent from the heuristic review remain unchecked. The current cross-field proposals compare original candidate masks on the same plane only.

The [sample registry](/results/pilot/sample-registry/) lists local scan files at least 1 GB and starts every biological sample ID blank. Assign the same ID only when there is a reason to believe the scans came from the same biological sample, and record the basis or leave it unknown. The page saves locally in the browser and supports downloaded export, import, and a raw recovery backup. Confirmation and experience are self-reported; filenames and sizes are not content hashes or proof of biological independence. Generate a new inventory with `make_sample_registry.py --scans scans --output NEW_EMPTY_DIR`; a saved registry can be imported into a newer inventory only when every annotated scan still has the same filename and size.

For a consistency check during classifier-data preparation, pass both `--sample-registry DOWNLOADED_REGISTRY.json --sample-inventory REGISTRY_PAGE_DIR/inventory.json`. Each input package's slide must be assigned to the same sample ID and have the recorded scan size; older packages without scan size must be re-ingested. The resulting dataset records the registry and inventory hashes. This is optional and checks declarations for consistency, not whether two slides are genuinely biologically independent or contain the same bytes.

### Reversible cross-plane proposal links

`diatom_pilot.crossplane_links.build_possible_links` accepts candidates with a unique `id`, native-plane index `z`, and equal-shaped boolean `mask`. It returns every candidate as a separate node, exact mask digests and all adjacent-plane links whose mask IoU reaches a specified threshold. The caller retains the original masks and image/plane metadata. Empty masks stay in the graph without links. The function assumes masks already share a coordinate frame; it does not register images or establish biological identity, and callers must not treat a link as an instruction to merge specimens.

The [L77 experiment](/results/l77/) illustrates why: even a stricter mutual-best rule merges a deliberately constructed pair of distinct overlapping source silhouettes. The builder reproduces the frozen overlap links for 108 synthetic scene variants and has been applied without new inference to four unlabelled Academy fields; neither result validates real specimen identities or segmentation accuracy.
