# Evaluation targets and current species retrieval diagnostic

The project goal is genus identification in 95% of cases and species identification in 60% of cases, while identifying partially occluded and overlapping diatoms. These thresholds are not established by the current prototype. For a conservative working protocol, count an abstention as not identified when calculating the fraction of all eligible specimens identified correctly, and separately report accuracy among accepted suggestions and the abstention rate. The Academy scientist should define eligibility, diagnostic limits, taxonomy and whether the final contract uses this denominator. Do not make the targets appear met by excluding unknown taxa, difficult partials, overlapping groups or uncertain predictions after seeing results.

## Pilot retrieval check

The [pilot result page](/results/pilot/species-evaluation/) evaluates the exact frozen ResNet-18 embedding and species-ranking rule used by `run_field.py`: cosine similarity to gallery images, then take the highest-scoring reference per species. The gallery has 11 labeled public images of six species from four filename-derived source slides, not Academy expert-confirmed vouchers. Two development checks use [UDE DIATOMS in the Wild](https://doi.org/10.5281/zenodo.10410655) images and metadata:

1. **Leave-one-source-slide-out within the gallery.** For each of the 11 images, remove every image with the same source-slide identifier, then find the nearest remaining references. On the 11 queries, the top reference had the recorded genus in 10; only eight queries' species had another reference in the remaining gallery, and top-one species matched on seven of those eight. Top three contained the recorded species on all eight. The other three species were absent from their fold's gallery; a forced species suggestion cannot be correct under the recorded labels.
2. **Unknown-species stress set.** The previously recovered nonrandom public archive prefix contains 61 images from one different source-slide identifier; two lack a usable species label and are excluded. All 59 remaining images have recorded species absent from the six-species gallery; 57 also have genera absent. The retrieval rule nevertheless produces a nearest species-labeled reference for all 59. It cannot identify an absent species, and its similarity score is not a probability. The pilot presents these as comparison images and leaves the taxon blank until a reviewer makes a selection.

This is an optimistic, tiny, preselected and repeatedly inspected public development set, not a test of the Academy workflow or the 95%/60% targets. Images can share specimens, slide preparation, acquisition or biological samples even when filename-derived slide identifiers differ. Public species annotations and source crops have not been expert-reconciled for this project. The test has no local expert ground truth, no detection or mask error, no true overlap stratification, no calibration or open-set rejection, and no uncertainty interval meaningful for the intended population. A query is a source cutout, not a pipeline-proposed Academy specimen. Seven of eight should not be reported as species accuracy for freshwater diatoms.

Reproduce with `YOLO_CONFIG_DIR=/tmp/diatom-yolo-config MPLCONFIGDIR=/tmp/mpl-diatom /tmp/diatom-research-venv/bin/python diatom_pilot/evaluate_species.py` and the prior public image subsets and `/tmp/resnet18-f37072fd.pth`. [Per-query results](/results/pilot/species-evaluation/evaluation.json) contain source slide identifiers, named references and similarity scores. Source images are credited in [R7](../research/R7.md).

## Evidence needed to assess the goal

- Assemble a reference vocabulary with expert-confirmed species names, voucher images and meaningful coverage of the Academy's samples; record synonyms, uncertain IDs and unresolved diagnostic cases. Split by independent biological sample before any tuning or data augmentation, keeping all planes, crops and fields from a sample together. Preserve independent look-alike and unrepresented species for open-set testing.
- Create a blinded expert-reviewed test set with all count-eligible objects in sampled fields, including each distinct valve in overlaps and partials, plus non-diatom distractors. Record whether genus and species are actually resolvable under the available optics; retain disagreements and adjudication. Choose group-level and mask/localization criteria before the final evaluation.
- Evaluate the complete pipeline at the instance level: missed and duplicate specimens, complete overlap-group recovery, partial-object recovery and false proposals per field; then genus and species correctness on all eligible reference specimens, including detection misses in the end-to-end result. Also report conditional classifier performance given expert crops, to separate identification from detection errors.
- Lock any decision thresholds and stopping rules on a separate development/validation split. Report raw denominators, accepted and abstained results, per-sample and per-taxon variation, and confidence intervals at an appropriate independent-sample level. Evaluate performance specifically for overlaps, partials, rare taxa and unseen taxa. The final expert protocol must define how unresolved objects and inter-expert disagreement count toward the contractual targets.

## Instance-level evaluation input

`evaluate_instances.py` computes preliminary end-to-end metrics from a separately prepared, explicitly matched reference set. It is not connected to the nonexpert practice reviews and does not convert them into ground truth. The [synthetic example](examples/synthetic-evaluation.json) illustrates the `diatom-instance-evaluation-v1` structure; **all its samples, labels, and declarations are invented**. To exercise the calculator without creating project results:

```sh
python3 diatom_pilot/evaluate_instances.py \
  --input diatom_pilot/examples/synthetic-evaluation.json \
  --output /tmp/diatom-synthetic-evaluation-result.json
```

A real input must declare a fixed protocol, matching rule, taxonomy version, held-out test split, expert-adjudicated reference and matching status, and the development sample IDs. Each field needs a biological sample ID, an exhaustive-reference declaration, reference objects, and predictions. The evaluator rejects an explicit sample-ID collision, duplicate IDs, multiple predictions matched to one reference, and incomplete fields. These checks cannot prove that the declarations or sample grouping are correct. Matching must be performed according to a prespecified expert protocol; the program does not establish object correspondence or mask quality itself.

For each reference, eligibility at genus and species level is explicit and requires the canonical reference name at that rank. A missing prediction or a prediction that abstains contributes no correct identification for every eligible rank. The result separately reports eligibility, misses, detected abstentions and accuracy among accepted predictions; taxonomy is compared by exact string, so synonyms must be reconciled beforehand. Unmatched predictions are recorded as duplicate, other or unknown. Partial status must be yes, no or unknown; a named overlap group must contain at least two references in that field. The result reports sample-level and partial/overlap strata and complete group recovery, but does not declare the goals achieved. It also reports pooled and per-sample overlap-group counts: fully detected groups and, separately for each taxonomic rank, groups where every member is eligible and every member is detected and correctly named. A miss, abstention or wrong name makes an eligible group incomplete; groups with any ineligible member are counted separately and excluded from that rank’s group fraction. These group summaries complement, rather than replace, the specimen-level denominators. The scorer separately records whether each proposal mask is nonempty, empty, or missing; the evaluator reports those states for matched references and counts overlap groups whose every member has a matched nonempty mask. Older records without a mask state are counted as unknown and cannot satisfy that group count. A nonempty mask is only an availability check: it does not prove that the mask covers the correct specimen or has an acceptable boundary. A separately declared expert assessment records mask acceptability under the frozen rule. The evaluator reports assessments and groups with all masks marked acceptable, as well as correct identification with an acceptable mask. That fraction is omitted when any matched eligible specimen has an unreviewed, unsure, or merged mask assessment, or when no mask rule was frozen; unresolved masks are not treated as failures or successes. Overlap-group counts separately identify groups containing unsure, merged, or unreviewed matched masks. A merged label flags a suspected fusion. The reviewer may optionally identify additional reference specimens inside that mask; those additional references are not counted as matched detections unless a separate proposal is matched to them. The report distinguishes groups with identified merged neighbors and fields with additional unmatched reference mentions. This does not establish that every fused specimen was identified or automatically determine mask acceptability. A scientist must define and adjudicate the matching and segmentation criteria. The output also breaks eligible specimens down by canonical genus and species, with sample and field counts, misses, abstentions, and identification fractions. It reports how often unmatched proposals were named at each rank, separately for the declared duplicate, other, and unknown categories. These categories depend on expert matching and do not by themselves establish whether an unmatched proposal is a false positive or an unseen taxon. Small per-taxon counts are descriptive and should not be treated as reliable population-level estimates. Eligibility, localization rules, unknown species handling and appropriate sample-level uncertainty still require the Academy's scientific protocol.

Optionally, `--bootstrap-replicates 2000 --bootstrap-seed 0` adds a 95% sample-cluster percentile bootstrap interval for pooled end-to-end genus and species fractions. It resamples entire declared biological samples with replacement, retaining all of each selected sample’s fields and eligible specimens; each resample is weighted by its eligible specimen count. Resamples with no eligible specimens at a rank are excluded for that rank and counted explicitly. At least two sample IDs are required. Independence must be established externally, and percentile intervals can be unstable with few samples or rare errors and spuriously narrow when all observed outcomes agree. The scientist must approve the uncertainty method and sample design; this output alone cannot prove a target.

## Frozen crop-level test path

For a future expert-adjudicated dataset with declared test rows, `validation_thresholds.py` can produce a validation-only threshold report. After the scientist agrees on the protocol and a threshold, freeze the model and one listed threshold with:

```sh
/tmp/diatom-research-venv/bin/python diatom_pilot/freeze_centroid_protocol.py \
  --model MODEL_DIRECTORY --validation-report VALIDATION_REPORT/thresholds.json \
  --protocol-id APPROVED_PROTOCOL_ID --threshold VALIDATION_THRESHOLD \
  --output FROZEN_PROTOCOL.json
```

The command records model, dataset, encoder, centroid and validation-report hashes without opening test images. If there are no labeled crop-level test rows but a separate field test will be predeclared, `--allow-no-crop-test-rows` explicitly permits freezing a validation-selected threshold for that field-only purpose. This does not create a crop-level test set. When authorized by the agreed protocol, score the preselected test crops with `evaluate_centroid_test.py --dataset DATASET_DIRECTORY --model MODEL_DIRECTORY --encoder ENCODER_WEIGHTS --protocol FROZEN_PROTOCOL.json --output NEW_EMPTY_DIRECTORY`. It checks frozen hashes, split consistency and declared expert-adjudicated test rows, and reports accepted, abstained, correct and unseen-vocabulary counts for the model's declared rank.

This is **conditional crop classification**, not an end-to-end test: the crops have already been selected and do not include missed detections, field-level false positives or automatic overlap recovery. The scripts cannot verify the truth of the expert, independence or prior-exposure declarations, prevent a user from running the test again into a different output directory, or establish confidence intervals or target attainment. Repeated inspection or tuning on the same test set invalidates its role as an independent final test. No real held-out Academy test was run to implement this path.

## Frozen field-prediction path (prototype)

`freeze_field_protocol.py` locks the detector candidate policy and configuration from a **development** bundle, an explicit held-out field list, and one or both independently frozen genus/species centroid protocols. Original detector candidates are always included. Add `--include-tile`, `--include-stack`, and/or `--include-split` to freeze the corresponding development-bundle proposal settings and include all such proposals; no automatic deduplication is performed. It opens the development bundle and model metadata, but not the declared test fields. Without a separate sample-split file, each selected test sample must appear in every selected model's declared held-out crop sample list. Alternatively, pass `--sample-splits PREDECLARED_SPLITS.json` using `diatom-sample-splits-v1`; every test field sample must be declared `test`, and all model train, validation and labeled test sample IDs must agree with that file. This permits a reserved test sample with no eligible labeled crop rows. The file hash and its declared development sample IDs are retained; the file cannot prove biological independence or prior nonexposure. The declared development slide must differ from every held-out slide.

Within the declared held-out field list, the same slide cannot have multiple biological sample IDs. Fields whose XY regions overlap on the same slide—including fields on different focal planes—are rejected unless `--overlap-handling-id PREDECLARED_OWNERSHIP_RULE` names a predetermined rule for assigning specimens. The protocol records overlapping field pairs and the rule ID. This is a declaration, not automatic cross-field deduplication: the scientist must ensure reference ownership and matching follow that rule. Even adjacent nonoverlapping fields can cut the same specimen at a boundary and require an agreed counting rule.

Optionally pass `--sample-registry DOWNLOADED_REGISTRY.json --sample-inventory REGISTRY_PAGE_DIR/inventory.json`. With this check enabled, each declared field must also include `slide_size_bytes` matching the registry, and its sample ID must match the declared scan assignment. The development slide must be assigned too, and cannot share a declared sample ID with a test field. If a sample-split file is supplied, the development slide sample must be train or validation. The registry and inventory hashes are recorded; filenames and sizes are not file-content hashes, and the reported biological relationships still require expert verification.

The held-out list has this structure (the names and coordinates below are placeholders):

```json
{"format":"diatom-held-out-fields-v1","fields":[{"id":"test-field-1","sample_id":"independent-test-sample","slide":"test-slide.ome.tiff","origin_xy":[0,0],"z":0,"size":768}]}
```

For each rank, pass both `--genus-model MODEL_DIR --genus-protocol FROZEN_CROP_PROTOCOL.json` or the analogous species arguments. If a scientist has predefined a mask-acceptability criterion, pass `--mask-rule-id PREDECLARED_MASK_RULE` when freezing the field protocol. The ID identifies the external rule; it does not contain or validate the rule itself. Pass `--development-bundle DEVELOPMENT_FIELD/bundle.json --test-fields HELD_OUT_FIELDS.json --protocol-id APPROVED_ID --matching-rule-id PREDECLARED_RULE --taxonomy-version TAXONOMY_VERSION --output FROZEN_FIELD_PROTOCOL.json`. After a scientist approves the design and authorizes the test, run `score_frozen_field.py --protocol FROZEN_FIELD_PROTOCOL.json --field-id test-field-1 --bundle TEST_FIELD_DIR --encoder ENCODER_WEIGHTS --genus-model MODEL_DIR --species-model MODEL_DIR --output NEW_PREDICTIONS.json`, omitting a rank's model if that rank was not frozen.

The scorer checks the field identity, frozen proposal settings, model and encoder hashes, and that candidate crops equal their source-plane pixels. It records every included proposal's box, source plane, crop and mask provenance, and accepted or abstained genus/species predictions. It does **not** match proposals to references or calculate accuracy. A separately prepared expert reference and match file is still needed; `assemble_instance_evaluation.py` validates and combines it with frozen field predictions for `evaluate_instances.py`. No real Academy held-out test exists. This prototype can include original, tiled, cross-plane track and split-hypothesis proposals, but does not deduplicate candidates. Each proposal is a separate prediction, and experts must classify duplicate and merged proposals under the predetermined matching rule. The frozen protocol records hashes of relevant local source files and versions of Python and key packages; the scorer refuses a mismatch. These fingerprints do not fully capture system libraries, hardware, or dependency state, and cannot prove that an existing bundle was produced by the declared code and detector, that sample names represent independent samples, or that a field was previously unseen. Protocols created before these fingerprints were added must be recreated before scoring. Repeat test access cannot be prevented by these files. The input declarations, taxonomy, matching rules and final protocol require scientific review.

The expert reference file has format `diatom-expert-field-reference-v1`, declares `protocol_sha256`, `reference_status` and `matching_status` as `expert_adjudicated`, `reviewer_role` as `expert`, a `reviewer_id`, the same `matching_rule_id` and `taxonomy_version` as the frozen protocol, and `development_sample_ids` including every model development sample and any other detector development samples. Its `fields` array must cover every frozen field, each with `id`, `sample_id`, `exhaustive: true`, `predictions_sha256`, a `references` array in the instance-evaluation format, and a `matches` array. Each match has `prediction_id` and `reference_id`; use a null reference ID plus `unmatched_type` (`duplicate`, `other`, or `unknown`) for an unmatched proposal. Every prediction must occur exactly once; a reference with no match remains a miss.

Run `assemble_instance_evaluation.py --protocol FROZEN_FIELD_PROTOCOL.json --predictions FIELD_PREDICTIONS.json --expert-reference EXPERT_REFERENCES.json --output EVALUATION_INPUT.json`, repeating `--predictions` for all frozen fields. It validates the input with the existing instance evaluator before writing, and records the protocol, prediction and reference file hashes. Then run `evaluate_instances.py` on the assembled input. The expert reference file is presently hand-authored; the program does not create the references, perform matching, confirm expertise, or guarantee independent annotation. The scientist must agree on the full protocol before any held-out results are inspected.

### Visual matching against an independent reference

`make_field_matching_page.py --protocol FROZEN_FIELD_PROTOCOL.json --predictions FIELD_PREDICTIONS.json --reference INDEPENDENT_FIELD_REFERENCE.json --bundle TEST_FIELD_DIR --output NEW_PAGE_DIR` prepares a static matching page after independent references and frozen predictions exist. The reference file uses `diatom-independent-field-reference-v1` with the frozen `protocol_sha256`, `field_id`, `sample_id`, `field_image_sha256`, `reference_status: "expert_adjudicated"`, `reviewer_role: "expert"`, `reviewer_id`, `exhaustive: true`, and `references` in the instance-evaluation format. Each reference also needs `field_xy: [x,y]` and integer `z` for its independently annotated point. Reference images, eligibility and taxon labels must be established independently under the scientist's protocol before inspecting predictions.

Before rendering, the generator checks recorded focal-plane, proposal-manifest, crop, and mask hashes and verifies that each crop matches the appropriate focal-plane pixels. The page hides taxon predictions and reference names. When the frozen protocol has a mask rule, a reviewer may separately mark each matched nonempty mask acceptable, unacceptable, merged with another specimen, or unsure under that rule; missing and empty masks are recorded as unavailable. This is optional, and an unassessed mask remains unreviewed. It shows the focal stack with proposal boxes as approximate guides. Reference points appear only on their recorded plane, and available model masks appear only on their proposal source plane. Reviewers must consult the original stack as needed. For every proposal, select a unique reference or one of the unmatched types, then download the matching decisions. The page uses browser-local storage. Use **Download unfinished work** to move an incomplete review to another computer, or download completed matching decisions; **Open saved matches** restores either file after verifying the displayed evidence. Opening a file replaces the browser’s current work for that field. Unfinished-work files are not accepted as completed expert matches. Newly generated matching pages also protect damaged or incompatible browser data: editing is disabled until a valid saved match file is opened, and the original browser data can be downloaded as a raw recovery backup. Previously generated static pages keep their original behavior; download any existing work before regenerating them. A declared expert must perform the match for the collection step; neither their credentials nor their actual inspection can be verified automatically.

`collect_field_matches.py --protocol FROZEN_FIELD_PROTOCOL.json --reference INDEPENDENT_FIELD_REFERENCE.json --predictions FIELD_PREDICTIONS.json --matches FIELD_MATCHES.json --matching-page MATCHING_PAGE_DIR --output EXPERT_REFERENCES.json` collects the declared expert references and decisions for the assembler. Repeat all four field arguments for multiple fields; add `--additional-development-sample ID` for detector or other development samples not already listed in the frozen classifier protocols. It verifies source-file hashes, the matching-page display payload, every recorded display-image hash and the displayed identifiers; it retains the page hash and per-field reviewer and display-asset provenance, and requires every frozen field. It does not prove that the independent reference was created before predictions were viewed, that the displayed files were actually inspected, that coordinates are registered across Z planes, or that the declarations and matches are correct.

To create an independent reference without showing proposal boxes or taxon suggestions, run `make_reference_page.py --protocol FROZEN_FIELD_PROTOCOL.json --field-id FIELD_ID --bundle TEST_FIELD_DIR --output NEW_REFERENCE_PAGE_DIR` and serve the resulting static page. It verifies the declared field identity and focal-plane image hashes and copies only the focal-plane images, not the model proposals. A reviewer clicks separate specimen points, records partial and overlap-group flags, and explicitly assesses whether each taxonomic rank is resolvable. The field can be zoomed and scrolled; each specimen card can return to its recorded focal plane and highlight its point. Use **Move point** to correct its location or focal plane without discarding the taxon, eligibility, or overlap-group entries; canceling a move preserves the original point. Incomplete work can be downloaded and reopened on another computer. If existing browser data is damaged or incompatible, editing is disabled and the raw browser data can be downloaded as a recovery backup before opening a valid saved file. Exporting an expert reference requires a self-declared expert ID, exhaustive-field declaration, expert-adjudicated declaration, and explicit rank eligibility for every point. Those declarations are not independently verified. The exported reference can be supplied to `make_field_matching_page.py`.

The reference page records points rather than expert instance masks; it cannot by itself assess mask boundary quality. It shows each marked point only on the focal plane where it was placed, and does not register images across planes. A scientist must define eligibility, counting units, overlap groups, taxonomy and adjudication, and must use an independently created reference before viewing predictions. Generating a reference page from a bundle does not prove that the reviewer or the person who prepared the bundle had no prior prediction exposure.

The [visual matching practice page](/results/pilot/matching-practice/) uses a real microscope field and two model proposals, but its reference points, reviewer, protocol and expert declarations are synthetic. It is an interface demonstration, not an evaluation or scientific ground truth.

Centroid models may be trained with `--crop-framing mask_bounds_8` to use the same padded mask bounds for reviewed training crops and field inference. The selected framing is part of the model and frozen field protocol; a missing or empty proposal mask produces an unavailable classification rather than an invented crop. Earlier models retain legacy detector-box inference. This framing change has only been exercised with synthetic labels and needs a scientist-approved, sample-separated comparison before any performance conclusion.

For a readable static summary of an evaluation result, run `render_instance_report.py --input EVALUATION_RESULT.json --output NEW_REPORT_DIR`. It displays counts and denominators, per-sample and per-taxon breakdowns, overlap and mask-review completeness, unmatched proposals, and a standalone chart. If the evaluation result includes the optional sample-cluster bootstrap, it displays the intervals and the number of valid resamples; otherwise it says no interval was supplied. It checks that sample-level counts add up to the overall totals. Rendering does not independently verify the declarations in the input. The [synthetic report example](/results/pilot/synthetic-instance-report/) uses invented references, labels and expert declarations; both its page and chart are marked as a demonstration.

An optional versioned `diatom-taxonomy-map-v1` can be fixed with `--taxonomy-map TAXONOMY.json` when freezing the field protocol. Its `version` must equal the frozen `--taxonomy-version`, and it must cover the species labels used by a frozen species model. Supply the exact same file to `assemble_instance_evaluation.py --taxonomy-map TAXONOMY.json`; its hash is checked before use. Every species-eligible reference must appear in the frozen map, and any supplied reference genus must agree. An absent or conflicting reference is an error requiring scientific protocol review, not an automatic exclusion or a post-test taxonomy edit.

Genus and species predictions are not rewritten: the assembler labels a pair as consistent, conflicting, unmapped, not applicable, or unchecked, and the evaluator and report summarize those states. Agreement with a map does not make a prediction correct. A map assembled or changed after inspecting test labels is not an independent predeclared taxonomy, even if its contents are internally consistent. If no taxonomy map was frozen, predictions are marked unchecked.

The matching page notes when a reference point and proposal originate on different Z planes. The assembled evaluation separately reports matched same-plane, cross-plane and unknown-plane relationships, and overlap groups containing cross-plane matches. A cross-plane match is not automatically wrong; equal plane numbers do not prove spatial alignment. These counts use the proposal representative plane and the reference point plane, not an independently verified three-dimensional registration.

For reference-first annotation, `make_reference_from_scan.py --protocol FROZEN_FIELD_PROTOCOL.json --field-id FIELD_ID --slide scans/SCAN.ome.tiff --output NEW_REFERENCE_PAGE_DIR` reads the declared field directly from the scan and writes only focal-plane images and the reference UI; it does not run a detector or include predictions. It rejects scans smaller than 1 GB, checks the declared field identity and frozen software fingerprints, and reads only the selected field from each focal plane. After a model bundle is generated separately, the matching-page generator checks that its field image and every focal-plane image match the reference page's recorded hashes. The scan itself is not fully hashed, and these checks cannot prove a reviewer had no prior access to predictions or that annotation was independent. Existing bundle-based reference pages remain supported.
