diff --git a/CHANGELOG.md b/CHANGELOG.md index 27cf52fa..71875055 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/). ### Added +- **Native 3-D files: Anipose and DeepLabCut 3-D.** Two new readers (`anipose` for `pose-3d` CSV, `deeplabcut_3d` for the triangulated tables; both built from the published layouts and tested on synthetic files only, so labelled *synthetic only*) give sessions with an absolute z in the project's length unit. `fps` and `unit` (mm, cm, m, in) are required options and never guessed (Anipose proposes `mm`, DeepLabCut 3-D proposes nothing); `target_unit` (default `cm`), `keypoint`, `likelihood_cutoff` (Anipose only), `vertical_axis` (`x`, `y`, `z`; default `z`), `flip` and `keep_skeleton` are optional. Units are converted when the file is read. IL-16 and IL-17 run on them with no water column; the 2-D metrics measure on the horizontal plane. **IL-15** runs once you give the **water column** (Surface z and Floor z on the Calibration screen); positions outside it have no depth and are counted in `frac_outside_extent`, never clipped. A native 3-D project is a 2-D project (leave Analysis type on 2D) with no Views or Fusion step; adding the first file sets Session calibration, the unit label and its confirmation, and later files must use the same target unit (`NATIVE_3D_UNIT_MISMATCH`); native and pixel sessions cannot share a project (`NATIVE_3D_MIXED`); other calibration modes are blocked (`NATIVE_3D_NEEDS_SESSION_CALIBRATION`). Not offered for native files (greyed out with a reason): every group metric, GL-16 included (a file holds one animal), and IL-3, IL-9, IL-10 and IL-14 (pixel-sized defaults that would change with the project unit). The water column is entered on the file's own vertical axis; each session's flip is applied for you. Limits: one animal per file, no z column in the per-frame table, no zones or background image, no refraction correction, a multi-animal DeepLabCut 3-D table (or one without full x, y, z triples) is still named by the scan as one it cannot read yet. The run `README.md` gains a **Native 3-D source** section. See the user guide and decision D-043. - **3-D metrics (fused 3-D projects).** Three new metrics next to the 2-D ones, which are unchanged: **IL-16 3-D Distance Travelled** (`path_length_3d_cm`, `path_length_3d_bl`, `n_valid_steps`), **IL-17 3-D Speed** (`mean_speed_3d_cm_s`, `median_speed_3d_cm_s`, `max_speed_3d_cm_s`, `mean_speed_3d_bl_s`) and **GL-16 3-D Nearest-Neighbour Distance** (`mean_nnd_3d_cm`, `median_nnd_3d_cm`, `mean_nnd_3d_bl`, `n_skipped_frames_3d`). Positions are in cm: x and y from the top view divided by its scale, depth fraction times the tank height from the fusion settings. IL-16 and IL-17 need identities, GL-16 does not; all three compute per time bin like their 2-D counterparts. They need the top view's cm scale (scalar or session calibration): in a 2-D project they are greyed out ("needs a fused 3-D session"), under body-length calibration they are greyed out ("needs a cm scale for the top view (use scalar or session calibration)"), and a unit whose top view has no scale is skipped at run time ("needs a cm scale for the top view"), with the reason in the run README. Track2Data does not estimate the scale from the fusion. IL-17 uses the project's kinematics estimator for the vertical speed, and its horizontal part is IL-2's speed. A step, frame or speed needs a valid x, y and depth, otherwise the value is NaN, never 0. Not included: vertical speed as its own metric, 3-D inter-individual distance and cohesion. The Metrics screen presets (for example *All metrics*) no longer tick any row that is greyed out for the project (also, for instance, identity-needing metrics when every session is identity-free). `codebook.csv` lists the whole registry, so it gains rows for the three metrics in 2-D runs too; no other 2-D output changes. `track2data list-metrics` shows "fused 3-D + cm scale" for them. - **Run a 3-D project.** A 3-D project now runs: every top/side pair with fusion settings that fuses without error becomes one run unit (id `+`, output folder `/+/`), and each unit goes through the usual pipeline as a fused session. Sessions in no fusable pair, and pairs that fail to fuse, are left out with their reason: the Processing screen lists them, the run writes them to `skipped.csv` and to a "Skipped sessions" section of `PROJECT_SUMMARY.md` (both only when something was skipped), and `track2data run` prints them. A 3-D project with no fusable pair refuses to run ("no pair is ready to fuse: ..." or "Pair and fuse a top and a side session first"); one bad pair among good ones does not stop the run. Vertical position (IL-15) reads the fused depth, with `depth_extent_source` = `fusion`, and is available for a fused session whatever the project's camera view is; `frac_outside_extent` counts the side positions that fell outside the water column. Where the fused frames jump (a frame one of the views lacks), the fused track keeps a break, as a 2-D session tracked in separate intervals does, so path length and every other metric that steps from frame to frame never bridges the gap. A unit carries the TOP session's metadata (session-level columns such as `group_id`, `treatment` or `sex`), and per-animal metadata matches the fused fish by the top session's label or index. The per-frame tables (CSV long, Feather, Excel) gain `depth_fraction` and `depth_cm` for fused sessions; `sessions.csv`, each unit's README ("3-D fusion") and `manifest.json` (`run_metadata.fusion`) record how the pair was fused, including the SHA-256 of the side trajectory file. `PROJECT_SUMMARY.md` counts "Units processed (fused pairs)", and the pooled `all_sessions/manifest.json` records each unit's fusion. `track2data validate` and Validate check only the sessions that run: the consistency report reads the top session of each pair with fusion settings, and session calibration checks both sessions of such pairs. Serial and parallel runs give identical files. Processing, Preview and Export are blocked only while no pair has fusion settings; Processing shows what will run and what is skipped, and Preview shows the top-view tracks of a fused unit. `track2data validate` lists unfusable pairs as notes. 2-D projects are unchanged. Still missing: 3-D speed, path length and neighbour distance (sub-project B2); zones are one set applied to the top view; `sensitivity` refuses 3-D projects. New `Engine.run_units`, `RunPlan`, `RunUnit` and `Engine.validation_issues`. - **Fusion of top and side views (3-D projects).** The Views page gains a **Fusion** section for the selected pair with a status line and **Set up fusion…**. The dialog shows the side view with two draggable lines for the water surface and the tank floor, fields for both rows, the tank height (default 20 cm), the shared horizontal axis (top-view x or y) with Flip, and the frame offset (hidden and fixed at 0 for "One video, two panels"), a live summary (shared frames, fused fish, positions outside the water column, agreement) and **Suggest offset**, which scans ±5 s around 0 (about 3 s on a 1-hour, 5-fish recording; needs a calibrated top view, otherwise it is disabled with a hint). The fusion keeps the fish matched in the pair on the frames both views have and adds a depth (0 = surface, 1 = floor; positions outside the column become empty and are counted). The cameras are assumed to be at right angles; the two views' horizontal positions are compared in cm and a warning shows when they disagree by more than 10% of the top-view range (needs a calibrated top view). Frame rates must match. New `FusionSettings` on each pair (`ViewPair.fusion`), `PreprocessedSession.depth`, `Engine.fuse_pair`, `fuse_all` and `suggest_offset`. The Views status warns "Fusion setup needed for …" and never blocks. A fused pair is what a 3-D run is made of (see "Run a 3-D project" above). diff --git a/README.md b/README.md index e5edd4ea..5d204b5d 100644 --- a/README.md +++ b/README.md @@ -31,6 +31,12 @@ It is a desktop application and a Python engine you can drive headlessly for bat → export sessions.csv ``` +**Reads** idtracker.ai (6.x and v5), DeepLabCut (CSV, also Lightning Pose), SLEAP +(analysis HDF5), Ctrax (raw `.mat`), `trx.mat`, and two native 3-D formats, Anipose +`pose-3d` CSV and DeepLabCut 3-D tables (positions in physical units; the 3-D metrics +the 3-D metrics IL-16 and IL-17 run on them, and IL-15 once you give the water column; GL-16 does not, because a native file holds one animal). Run +`track2data list-readers` for the list and the options each reader needs. + **Individual** — distance travelled, speed, acceleration, tortuosity, freezing bouts, thigmotaxis, turn rate, home-base use. **Group** — nearest-neighbour and inter-individual distance, polarisation, diff --git a/docs/3d-movement/2026-10-08-3d-roadmap.md b/docs/3d-movement/2026-10-08-3d-roadmap.md index 45bf095e..2d214fe4 100644 --- a/docs/3d-movement/2026-10-08-3d-roadmap.md +++ b/docs/3d-movement/2026-10-08-3d-roadmap.md @@ -1,6 +1,6 @@ # 3-D movement: roadmap -**Status:** approved 2026-10-08. Sub-project C is in progress; E (mode switch), G, F, D (fusion) B1 (running a 3-D project) and B2 (3-D metrics) are implemented; A is not started. +**Status:** approved 2026-10-08. Sub-project C is in progress; E (mode switch), G, F, D (fusion) B1 (running a 3-D project) and B2 (3-D metrics) and A (native 3-D files) are implemented. **Relates to:** `docs/dev/DECISIONS.md` D-031, `docs/dev/ROADMAP.md` (Z-10), `docs/tracker-formats/2026-10-07-tracker-import-design.md` (Tier 3) @@ -13,12 +13,12 @@ build cycle. | **E** | **2D/3D project mode**: `ProjectManifest.mode`, Project-screen choice, lock, 3-D compute blocked. Done; see [the spec](2026-10-09-mode-switch-design.md) | nothing | | F | **Panel split**: one video with the top and side views in two panels becomes two sessions (a panel rectangle per session, panel-relative coordinates). Done; see [the spec](2026-10-09-panel-split-design.md) | E | | G | **ID correspondence**: view roles, pairing top and side sessions (regex or by hand), fish mapping between views, a Views step. Done; see [the spec](2026-10-09-id-correspondence-design.md) | E | -| A | Read 3-D tracker files (Anipose pose-3d CSV, DLC-3D). Metrics run on a chosen plane and z is stored (D-031 as written) | `feat/native-units` merged | +| A | Read 3-D tracker files (Anipose pose-3d CSV, DLC-3D). Metrics run on the horizontal plane and z is stored in the project unit. Done; see [the spec](2026-10-10-native-3d-files-design.md). **Amends D-031 a second time** | `feat/native-units` merged | | B1 | **Run a 3-D project**: run units per fused pair, IL-15 from the fused depth, depth in the exports, UI and CLI. Done; see [the spec](2026-10-10-3d-run-design.md) | D | | B2 | Metrics that use z: 3-D speed and path length, 3-D neighbour distance. Done; see [the spec](2026-10-10-3d-metrics-design.md). **Amends D-031** | B1 | | D | Fuse top and side recordings into one 3-D session. Done; see [the spec](2026-10-09-fusion-design.md) | F and G (done) | -**Order: C, F/G/E, D, B1 and B2 are done; A remains.** A moves first if real 3-D files turn up. C went +**Order: all sub-projects are done.** C went first because no data of any kind existed, it is testable on synthetic tracks, and it created the project-level camera-view setting that B reuses. @@ -26,7 +26,7 @@ project-level camera-view setting that B reuses. - `KeypointSelection.plane` and `camera_view` have no defined precedence. A and B must define a vertical axis for 3-D data. -- The `has_pixel_frame` guard from native-units joins the IL-15 extent derivation when A lands. +- The `has_pixel_frame` guard from native-units joined the IL-3 and IL-14 arena fallback in A (the data extent is used, with a warning). - Per-session camera views arrive with D (`Engine.camera_view_for(session)` is the seam). - Whether IL-3 and IL-14, which assume a top-down view, should be gated for side views is left open. diff --git a/docs/3d-movement/2026-10-10-native-3d-files-design.md b/docs/3d-movement/2026-10-10-native-3d-files-design.md new file mode 100644 index 00000000..9952011e --- /dev/null +++ b/docs/3d-movement/2026-10-10-native-3d-files-design.md @@ -0,0 +1,159 @@ +# Reading native 3-D tracker files (sub-project A) + +**Status:** implemented 2026-10-11 (decision D-043). See "Changes made during the build" at the end. +**Part of:** [the 3-D roadmap](2026-10-08-3d-roadmap.md). Builds on [3-D metrics](2026-10-10-3d-metrics-design.md) (B2) and [running a 3-D project](2026-10-10-3d-run-design.md) (B1). Amends D-031 a second time (B2 was the first). + +## Why + +Fusion (D) builds a 3-D session from a top and a side recording. Some trackers deliver 3-D positions +directly: Anipose (`pose-3d` CSV) and DeepLabCut's 3-D triangulation (DLC-3D). Their coordinates are +in physical units (the calibration board's unit), have an absolute z axis, and have no pixel frame. +A adds readers for both and lets the 3-D metrics of B2 and IL-15 run on them. + +## Sub-project order + +| | Sub-project | Scope | +|---|---|---| +| E, G, F, D, B1, B2 | Mode switch, ID correspondence, panel split, fusion, running a 3-D project, 3-D metrics | Done | +| **A** | **Native 3-D files** (this spec) | Two readers; minimal native-unit handling; absolute `z`; IL-15 from a user-given water column | + +## Decisions + +- **Two readers, built from the published layouts** (`verification = "synthetic_only"`, D-012): + `anipose` (pose-3d CSV) and `deeplabcut_3d`. There are no real sample files at hand for the DLC-3D + layout. For Anipose the repo's published sample (`tests/real_samples/`) is used by the existing + reader-contract case when the fixture is present; it is not required. +- **One animal per file.** Neither format carries an animal axis. Several animals are several files + (several sessions), as for the other single-animal readers. +- **Units are converted when reading, to the project's length unit.** The reader takes `unit` (the + file's unit: mm, cm, m, in; Anipose proposes mm, which the file does not state, so it is always + confirmed) and `target_unit` (default cm). The first import sets the project's + `calibration.length_unit_label` to `target_unit` and confirms it; later imports must use the same + target (a different one is an error naming both). The `_cm` column suffix is unchanged and nominal, + as it already is for a project calibrated in mm; the README states the real unit. +- **A native 3-D session has no pixel frame.** `Session.has_pixel_frame: bool = True` (False here), + `Session.coordinate_unit: str | None = None` (the project unit it was converted to), and + `length_unit = 1.0` (so the existing "session" calibration reads "1 coordinate unit = 1 project + unit" with no new calibration path; it is confirmed automatically for these sessions). +- **Absolute `z`.** `Session.raw_z: np.ndarray | None` of shape `(n_frames, n_animals)` in the project + unit, and the same array on `PreprocessedSession.z`. It is not smoothed or interpolated, like the + fused `depth`. It follows the same rows as `xy` everywhere `depth` does (`slice_psess`, windows, + gap rows). +- **Vertical axis.** The reader option `vertical_axis` (`x`, `y`, `z`; default `z`) with `flip` + (default false) says which file axis is up. The other two axes are the horizontal plane that + becomes `raw_xy`; `KeypointData.xy` keeps all three axes (D = 3). +- **Position from one keypoint,** as for the other pose readers (`reduce_keypoints`, with the + likelihood cutoff applied to the Anipose `_score` or the DLC likelihood; never an average). +- **Water column for IL-15.** `calibration.water_column: WaterColumn | None` with `surface_z` and + `floor_z` (project unit, finite, different). When set, a native 3-D session gets + `depth = (z - surface_z) / (floor_z - surface_z)` (0 surface, 1 floor), `depth_height_cm = + |floor_z - surface_z|`, positions outside [0, 1] become NaN and are counted + (`depth_outside_mask`), never clipped. Without it IL-15 is unavailable with the reason "needs the + water column (surface and floor z) on the Calibration page". +- **No mixing in a project.** A project holds either pixel sessions (including fused pairs) or native + 3-D sessions; importing the other kind is refused with an error naming both. +- **No Views or Fusion step** for native 3-D projects (nothing to pair or fuse). + +## Design + +1. **Readers** (`track2data/readers/anipose.py`, `deeplabcut_3d.py`, registered like the others). + - Anipose detect: a CSV with `fnum` and at least one `_x/_y/_z` triple (suffixes split from + the right, since keypoint names contain hyphens); `M_xx` and `center_*` columns are ignored. + Missing is NaN in x, y and z together. `fnum` gives the frame index. + - DLC-3D detect: the three-row header (`scorer`, `bodyparts`, `coords`) with `x`, `y`, `z` + columns; 0 means missing. The frame index is the row number. + - Options: `fps` (required, never defaulted), `unit`, `target_unit`, `keypoint`, + `likelihood_cutoff`, `vertical_axis`, `flip`, `keep_skeleton`. The `keypoint` choices are filled + from the scanned files as the DLC reader does. + - Both finish through `assemble_session`, which gains a 3-axis path (axis permutation, flip, + unit factor, `raw_z`, `has_pixel_frame = False`). `video` is a placeholder `VideoInfo` with the + fps and the frame count, `width_px = height_px = 0` (never used when `has_pixel_frame` is false). +2. **Pipeline.** The preprocess step copies `raw_z` to `PreprocessedSession.z` row-aligned with `xy`, + and derives `depth`, `depth_height_cm` and `depth_outside_mask` from the water column when set. + `px_per_cm` comes from the confirmed `length_unit = 1.0`. +3. **Zones, background, arena.** For a session with `has_pixel_frame = False`: zones and the + background image are disabled on their screens (with the reason), and the IL-3 and IL-14 arena + fallback (`metrics/derived.py`) uses the data extent plus a warning instead of + `video.width_px / height_px`. +4. **Metrics.** `geometry3d.positions_cm` takes Z from `psess.z` when it is set, otherwise + `depth * depth_height_cm`; it returns None when neither exists, or when `px_per_cm` is missing. + `availability.depth_scale_reason` and `view_unavailable_reason` treat "has z" as having 3-D data + (today "has depth"); IL-15 keeps requiring `depth`. A native 3-D project's camera view is + irrelevant: it is treated as `top` for view gating, and the 2-D metrics run on the horizontal plane. +5. **UI and CLI.** The confirm dialog renders the new options. The Calibration page shows the water + column fields (surface z, floor z) for native 3-D projects only. The Metrics screen needs no new + rows. `t2d import` takes the options with `--option` as for the other readers. +6. **Outputs and docs.** A z column group in the per-frame table is not added (z is not exported in + this cycle except through the metrics); the run README gets a "Native 3-D source" block (reader, + file unit, project unit, vertical axis, flip, water column or its absence). Docs: the tracker + formats table and design (P5, plus a DLC-3D entry), the user guide, CHANGELOG, a decision entry, the roadmap row + and D-031's amendment. + +## Testing + +- Readers on synthetic files: layout detection and rejection of near-misses, hyphenated keypoint + names, NaN/0 as missing, `fnum` gaps, unit conversion (mm to cm, m to cm, in to mm), axis + permutation and flip, keypoint choice and cutoff, required `fps`, the `target_unit` consistency rule. +- Session and pipeline: `raw_z`/`z` row alignment through gap rows and `slice_psess`, `has_pixel_frame` + false disables zones and uses the data-extent arena fallback with a warning, a mixed project is + refused, `length_unit = 1.0` calibration. +- Metrics end to end: a known 3-D track gives exact IL-16, IL-17 and GL-16 values with no water + column; IL-15 unavailable with its reason without it, available with it (exact fractions, outside + positions NaN and counted); 2-D metrics on the horizontal plane equal a hand computation; serial and + parallel runs agree. +- Regression: pixel-frame projects (idtracker.ai, DLC 2-D, fused 3-D) unchanged: the existing suites + and a 2-D control run. +- Docs: tests for the guide and reference consistency as the existing ones require. + +## Not in this cycle + +Mixed native and fused projects, several animals in one Anipose file, mm or m export suffixes, reading +the camera model or the reprojection error, a z column in the per-frame table, and a water column +estimated from the data. + +## Changes made during the build + +The design above is what was proposed; these rulings were made while building it and are what the +code does. + +- **A native 3-D project is a `dimension "2d"` project** whose sessions come from native readers + (`NATIVE_3D_READERS`). The spec's "No Views or Fusion step" holds, and no new dimension value was + added: `"3d"` keeps meaning "top and side views to fuse", which avoids about thirty-five + dimension-keyed sites. The mode banner and the Project screen therefore say 2-D (cosmetic). +- **Only the add entry point sets up calibration.** `Engine.set_up_native_import` (used by + `track2data add` and the GUI's add; a batch is checked as a whole) sets mode `session`, label = target + unit and confirmed. Import, validate and run are read-only on the manifest and only check; a native + session in a non-session calibration mode raises `NATIVE_3D_NEEDS_SESSION_CALIBRATION` (also + in validate); validate also reports an unconfirmed unit and a label that differs from the sessions' + unit. `Engine.import_sessions` only checks. +- **`unit` and `fps` are required options.** Anipose proposes `mm` (source `tool-default`) but never + defaults it; DLC-3D proposes nothing. `likelihood_cutoff` above 0 without `_score` columns for every + keypoint is `READER_OPTION_INVALID`; DLC-3D has no such option. +- **Missing values.** Anipose: NaN in x, y, z together (a partly NaN triple counts as missing). DLC-3D: + x, y, z all exactly 0 (or any non-finite). Anipose `fnum` gaps are kept as tracking intervals, not + filled; unsorted `fnum` is sorted; duplicate, negative or non-integer `fnum` is `ANIPOSE_BAD_FRAME_INDEX`. +- **Units are converted in the reader**, on all three axes and with exact integer ratios, so the stored + skeleton is in the project unit too (axes are neither permuted nor flipped there). +- **`fuse()` refuses native sessions** ("native 3-D sessions have no views to fuse"); mixing is + `NATIVE_3D_MIXED` and a second target unit `NATIVE_3D_UNIT_MISMATCH`. +- **IL-17 reads `z`.** The first build left IL-17 on `depth * height`, so a native session without the + water column got NaN; found by the end-to-end test and fixed. IL-15 outside values, and non-finite z, + are NaN and counted. +- **GL-16 is not offered for native files** (one animal per file; the metric needs two in a session). +- **The unreadable-format notice for DLC-3D was narrowed** in `readers/recognise.py`: the single-animal + tables the reader takes are no longer reported, while a multi-animal table (extra `individuals` header + row) or one without full x, y, z triples is still named as one that cannot be read yet. +- **Metrics not offered in a native project** (one reason each, through `availability.unavailable_reason`): + IL-3, IL-9, IL-10 and IL-14 (pixel-sized defaults would silently change with `target_unit`; the + data-extent arena fallback is kept but not reachable in a run) and every group metric, GL-16 included + (one animal per file). +- **The water column is on the file's axis.** For a session read with `flip`, `apply_water_column` negates + both values, so the same physical fish gets the same depth with or without flip. +- **Provenance and outputs.** `calibration.water_column` is left out of the serialised manifest while it + is None (and so out of `project_hash`, the cache key and `manifest.json`), and the provenance + `native_3d` key only appears for a native session: a pixel project hashes, caches and serialises exactly + as before (golden values from fc5b2fc). IL-15's `depth_extent_source` is `water_column` for native + sessions. A replaced jump also blanks z. +- **UI.** Zones and background are disabled for native projects; the trajectories preview frames the data + from its extent; the Calibration screen shows the **WATER COLUMN** group (Surface z, Floor z) for + native projects only; the GUI add refuses a batch that would break the rules before listing it. diff --git a/docs/METRICS_SPEC.md b/docs/METRICS_SPEC.md index b5a11ddf..c026a433 100644 --- a/docs/METRICS_SPEC.md +++ b/docs/METRICS_SPEC.md @@ -400,7 +400,7 @@ info-button modal (§6). | **Manuscript label** | Vertical position (depth in the water column) | | **Level** | Individual; trial summary | | **Priority** | Optional | -| **Inputs** | `PreprocessedSession.xy` (the y column); the water column, derived per session from the main zones (never user-supplied); `px_per_cm` when calibrated | +| **Inputs** | `PreprocessedSession.xy` (the y column); the water column, derived per session from the main zones, or, for a native 3-D file (Anipose, DeepLabCut 3-D), entered by the user as surface z and floor z on the Calibration page and applied to the absolute z (`depth_extent_source` = `water_column`); `px_per_cm` when calibrated | | **Required preprocessing** | Zone assignment is not needed; main-level zones must exist. The project's **camera view must be set to side view** (Calibration screen) or the metric is skipped and the run records why | | **Formula** | `T`, `B` = top and bottom image rows of the main zones (`T < B`); `d[t,k] = (y[t,k] − T) / (B − T)` for frames with `T ≤ y[t,k] ≤ B`; `mean_depth_fraction`, `median_depth_fraction` and `sd_depth_fraction` (n − 1) over those frames; `mean_depth_cm = mean(y − T) / px_per_cm`; `frac_outside_extent` = share of non-NaN frames with `y < T` or `y > B` | | **Output columns** | `individual_id`, `mean_depth_fraction`, `median_depth_fraction`, `sd_depth_fraction`, `mean_depth_cm`, `frac_outside_extent`, `depth_extent_source` | @@ -418,7 +418,7 @@ info-button modal (§6). | **Manuscript label** | Total distance travelled in 3-D | | **Level** | Individual; trial summary | | **Priority** | Optional | -| **Inputs** | `PreprocessedSession.xy`, `PreprocessedSession.depth`, `px_per_cm` and `depth_height_cm` of a fused 3-D session | +| **Inputs** | `PreprocessedSession.xy`, `PreprocessedSession.depth`, `px_per_cm` and `depth_height_cm` of a fused 3-D session; for a native 3-D file, `PreprocessedSession.xy` and the absolute `PreprocessedSession.z` in the project unit (no tank height, no water column needed) | | **Required preprocessing** | A fused 3-D session (top view plus side view) with a cm scale for the top view (scalar or session calibration, not body-length calibration). A project without these skips the metric and the run records why | | **Formula** | `Σ_t ‖P[t+1, k] − P[t, k]‖` over frame pairs where both positions are finite, with `P = (x_px / px_per_cm, y_px / px_per_cm, depth · tank_height_cm)` | | **Output columns** | `individual_id`, `path_length_3d_cm`, `path_length_3d_bl`, `n_valid_steps` | @@ -435,7 +435,7 @@ info-button modal (§6). | **Manuscript label** | Locomotor speed in 3-D | | **Level** | Individual; trial summary | | **Priority** | Optional | -| **Inputs** | `PreprocessedSession.kinematics.speed_px_s`, `PreprocessedSession.depth`, `px_per_cm` and `depth_height_cm` of a fused 3-D session; the pipeline's `KinematicsCfg` | +| **Inputs** | `PreprocessedSession.kinematics.speed_px_s`, `PreprocessedSession.depth`, `px_per_cm` and `depth_height_cm` of a fused 3-D session (for a native 3-D file, the absolute `PreprocessedSession.z` in place of `depth · tank_height_cm`); the pipeline's `KinematicsCfg` | | **Required preprocessing** | A fused 3-D session (top view plus side view) with a cm scale for the top view (scalar or session calibration, not body-length calibration). A project without these skips the metric and the run records why | | **Formula** | `v3[t, k] = sqrt(vh² + vz²)` with `vh = speed_px_s[t, k] / px_per_cm` (identical to the horizontal part of IL-2 in cm/s) and `vz` the vertical speed in cm/s of `Z = depth · tank_height_cm`, from the same estimator and window as the pipeline's kinematics (Savitzky-Golay by default, forward difference when the project selects it); mean/median/max over frames where both `vh` and `vz` are finite | | **Output columns** | `individual_id`, `mean_speed_3d_cm_s`, `median_speed_3d_cm_s`, `max_speed_3d_cm_s`, `mean_speed_3d_bl_s` | diff --git a/docs/dev/DECISIONS.md b/docs/dev/DECISIONS.md index be4c2368..a90411c1 100644 --- a/docs/dev/DECISIONS.md +++ b/docs/dev/DECISIONS.md @@ -1078,3 +1078,64 @@ the CLI and the README in agreement. Stating the inequalities as conditional kee true for gappy tracks. *Limits.* Depth comes from a side camera at right angles (no refraction or parallax correction); a wrong tank height scales every vertical distance; no vertical speed metric, 3-D inter-individual distance or cohesion. + +--- + +### D-043 · Native 3-D files: a 2-D project whose sessions come from native readers, units converted on reading, z absolute + +**Status:** accepted; implemented. Design: `docs/3d-movement/2026-10-10-native-3d-files-design.md` +(sub-project A of `docs/3d-movement/2026-10-08-3d-roadmap.md`). It amends D-031 a second time (D-042 +was the first): D-031 said "metrics use a chosen 2-D plane (default x, y); z is kept". For a +native 3-D file the 2-D metrics use the horizontal plane (the two axes that are not vertical), z is +kept as an absolute coordinate in the project unit, and the 3-D metrics of D-042 run on it. + +**Decision:** *Readers.* `anipose` and `deeplabcut_3d` (`readers/anipose.py`, +`readers/deeplabcut_3d.py`, shared `readers/native3d.py`), `verification = "synthetic_only"`; the +set of ids is `NATIVE_3D_READERS`. One animal per file. Options: `fps` and `unit` are required and +never defaulted (Anipose proposes `mm` with source `tool-default`; DeepLabCut 3-D proposes +nothing); `target_unit` (default `cm`), `keypoint`, `likelihood_cutoff` (Anipose only), `vertical_axis` +(default `z`), `flip`, `keep_skeleton`. Missing is NaN in x, y and z together (Anipose) and a row +where x, y and z are all exactly 0 (DeepLabCut 3-D), so a real 0 coordinate is kept. *A native +3-D project is a `dimension "2d"` project whose sessions come from native readers.* A new +dimension value would have meant about thirty-five dimension-keyed sites (run units, stage flow, +Views and Fusion steps) for nothing; "3d" keeps meaning "top and side views to fuse". The cost is +cosmetic (the mode banner and Project screen say 2-D). *Units.* Converted when reading, exactly (integer +ratios), to the project unit; the first add sets the calibration (`session`, label = target +unit, confirmed, `length_unit = 1.0`); only the add entry points (`Engine.set_up_native_import`, +used by `track2data add` and the GUI's add) do so. Import, validate and run are read-only on the +manifest: they check, and a native session in any other calibration mode raises +`NATIVE_3D_NEEDS_SESSION_CALIBRATION` (validate reports the same text, plus +`NATIVE_3D_UNIT_NOT_CONFIRMED` and the unit-versus-label message). `Engine.import_sessions` only +checks. *No mixing:* `NATIVE_3D_MIXED` (native with pixel sessions, or native in a fused 3-D project) +and `NATIVE_3D_UNIT_MISMATCH` (two target units); `fuse()` refuses native sessions. *z.* +`Session.raw_z` and `PreprocessedSession.z`, row-aligned with `xy`, not smoothed, interpolated +or permuted by identity fixes; `has_pixel_frame False`, `coordinate_unit`, `video.width_px = height_px = 0` +(zones and background disabled; the data-extent arena fallback of IL-3 and IL-14 is kept but not reachable, because those metrics are not offered). +`geometry3d.positions_cm` and IL-17 take Z from `z` when present, otherwise `depth * depth_height_cm`. +*IL-15* needs the water column (`CalibrationConfig.water_column`: `surface_z`, `floor_z`, finite, different, +either order): `depth = (z - surface_z) / (floor_z - surface_z)`, `depth_height_cm = |floor_z - surface_z|`, +values outside [0, 1] and non-finite z become NaN and are counted, never clipped; without it the +reason is "needs the water column (surface and floor z) on the Calibration page". *Outputs.* z is not +exported in the per-frame table (only through the metrics); with a water column the table carries the +depth columns; the run README has a "Native 3-D source" section. Pixel-frame outputs are unchanged +byte for byte: `water_column` is left out of the serialised manifest while None, so `project_hash`, the +cache key and `manifest.json` do not change, and the provenance `native_3d` key exists only for a native +session (golden values computed from fc5b2fc). IL-15's `depth_extent_source` is `water_column` there. +*The water column* is entered on the file's own axis; `apply_water_column` negates both values for a +session read with `flip`. *Not offered in a native project* (`availability.unavailable_reason`): IL-3, +IL-9, IL-10, IL-14 (pixel-sized defaults would silently change with `target_unit`) and every group metric +(one animal per file). *Recognition.* The `dlc_3d` entry of `readers/recognise.py` was narrowed: it names a +multi-animal DeepLabCut 3-D table (an extra `individuals` header row) or one without full x, y, z triples, +and never a table the reader takes. + +**Rationale:** A wrong unit silently scales every speed, so the unit is a required option and the +calibration is set once, by the add, and only checked afterwards; a run that rewrote the project +would change its hash and its results behind the user's back. Converting on reading keeps one +unit in the whole pipeline and lets the existing "session" calibration (`length_unit = 1.0`) +carry it with no new path. Keeping z absolute (not a fraction) means the 3-D metrics need no tank +height; the water column is an explicit entry because estimating the surface from the data would hide +an error. Missing-as-all-zero keeps a real zero coordinate that a per-axis rule would erase. +*Limits.* One animal per file (so no group metric, GL-16 included, is offered); no mixing with +pixel sessions; the board unit must be confirmed by the user; no refraction correction; the water +column is entered, not estimated; no z column in the per-frame table; formats are read from synthetic +files only. diff --git a/docs/guide/USER_GUIDE.md b/docs/guide/USER_GUIDE.md index 30074841..0ec9ffc1 100644 --- a/docs/guide/USER_GUIDE.md +++ b/docs/guide/USER_GUIDE.md @@ -299,6 +299,53 @@ a pair is set up, the Views step in the sidebar shows a warning "Fusion setup ne not block Next. A pair with fusion settings that fuses without error is run as one fused session; see [Running a 3-D project](#running-a-3-d-project). +### Native 3-D files (Anipose, DeepLabCut 3-D) + +Some trackers deliver 3-D positions directly, in physical units and with a vertical axis, so there +is nothing to pair or fuse. Track2Data reads two of them: + +| Software | Files | Reader id | +|---|---|---| +| **Anipose** | `pose-3d` CSV (`_x`, `_y`, `_z`, ..., `fnum`) | `anipose` | +| **DeepLabCut 3-D** | the triangulated table (three header rows, `x`, `y`, `z` per body part) | `deeplabcut_3d` | + +Both readers were written from the published layouts and tested on synthetic files only (they are +marked *synthetic only* in the confirm step); compare a few positions with the tracker's own output +before relying on them. + +- **Leave Analysis type on 2D.** A native 3-D project is an ordinary 2-D project whose sessions come + from these readers. It has no Views or Fusion step. +- **Options in the confirm step.** `fps` and `unit` are required and never guessed: the files record + neither, and a wrong unit scales every distance and speed. Anipose proposes `mm` (the usual board + unit) but you must confirm it; DeepLabCut 3-D proposes nothing. The other options are + `target_unit` (the project's length unit, default `cm`), `keypoint` (which keypoint stands for the + animal; never an average), `likelihood_cutoff` (Anipose only, applied to the `_score` columns; it + needs a score for every keypoint, otherwise set it to 0), `vertical_axis` (`x`, `y` or `z`, default + `z`: which axis of the file points up), `flip` (tick when it points down) and `keep_skeleton`. +- **Units are converted when the file is read**, from `unit` to `target_unit`. The first native file + you add sets the project's calibration for you: **Session calibration**, the unit label set to the + target unit and marked confirmed. Files added later must use the same target unit; a different one + is refused (`NATIVE_3D_UNIT_MISMATCH`, naming both units). The `_cm` column suffix is nominal, as for + any project calibrated in another unit; the run's `README.md` names the real unit. +- **No mixing.** A project holds pixel-tracked sessions or native 3-D sessions, not both, and native + files cannot join a 3-D (fused) project: the add is refused with `NATIVE_3D_MIXED`, naming the + session and both kinds. +- **One animal per file.** Neither format has an animal axis; several animals are several files, + hence several sessions. +- **Missing values.** Anipose: an empty cell (NaN) in x, y and z together. DeepLabCut 3-D: a row where + x, y and z are all exactly 0; a single 0 is a real coordinate. A gap in Anipose's `fnum` is not + filled: the session stores the frames the file has and records the gaps as tracking intervals. +- **Horizontal plane and vertical axis.** The two axes that are not vertical become x and y for the + 2-D metrics (IL-1, IL-2 and the rest); the vertical one is the absolute z. z is not smoothed or + interpolated. +- **Zones and background are not available** (there is no video frame). The metrics that need + an arena or a pixel-sized threshold (IL-3, IL-9, IL-10, IL-14) and all group metrics are not offered + (see [3-D metrics](#3-d-metrics)). + +From the command line: `track2data add PROJECT FOLDER --option unit=mm --option fps=25` (add +`--option target_unit=cm --option vertical_axis=y` as needed). Every native file is read in full +when it is added, so one unreadable file stops the add. + ## 3. Calibration Calibration decides which units distances and speeds are reported in. Figure 4 shows the default, @@ -381,6 +428,23 @@ is the surface and the bottom edge the floor; Track2Data never substitutes the v no main zone the depth columns are empty and say why. For time in the upper or lower part of the tank, draw stacked secondary zones and use the zone metrics (Z-1 to Z-9). +### Water column (native 3-D files) + +A native 3-D project shows a **WATER COLUMN** group with two fields, **Surface z** and **Floor z**: +where the water surface and the floor lie on the file's own vertical axis (as the file writes it, before any **flip**; Track2Data applies each session's flip itself), in the project's length unit +(either order is accepted; they must be finite and different). You enter them; Track2Data does not +estimate them from the data. With both set, each session gets a depth (0 at the surface, 1 at the +floor, `(z - surface) / (floor - surface)`) and a water height (`|floor - surface|`), which is what +**IL-15** needs. A position outside the column (above the surface or below the floor) has no depth: +it is left empty and counted in IL-15's `frac_outside_extent`, never clipped to the edge. Without the +water column IL-15 is greyed out ("needs the water column (surface and floor z) on the Calibration +page"); IL-16 and IL-17 do not need it, because z is already absolute. + +A native 3-D project must stay in **Session calibration** with the unit label equal to the target +unit and confirmed; the project is blocked otherwise (`NATIVE_3D_NEEDS_SESSION_CALIBRATION`, or a +message asking you to confirm the unit or to match the sessions' unit). The mode is set for you when +you add the first file, and nothing else (import, validate, run) changes it. + ## 4. Zones (optional) Zones are regions of interest (the whole arena, a centre area, a feeder). Zone metrics need at least @@ -686,6 +750,21 @@ keep measuring in the top-view plane. correction for refraction or parallax. Vertical speed as its own metric, 3-D inter-individual distance and cohesion are not included. +**In a native 3-D project** the same three metrics run on the sessions' absolute z (no tank height, +no fusion): the positions are `(x, y, z)` in the project's unit, and IL-16 and IL-17 need no water +column. Example: a fish that moves (3, 4, 12) mm per frame in an Anipose file at 25 frames per second, +read as cm, steps hypot(0.3, 0.4, 1.2) = 1.3 cm per frame, so 10 steps give an IL-16 of 13 cm and an +IL-17 of 1.3 x 25 = 32.5 cm/s; its 2-D metrics measure the horizontal steps of 0.5 cm (IL-1 5 cm, IL-2 +12.5 cm/s). **GL-16 is not offered for native files** (it needs two animals in one session and a file holds one), and neither is any other group metric ("needs several animals in one session; a native 3-D file holds one animal"). **IL-3, IL-9, IL-10 and IL-14 are not offered either** ("uses a pixel-sized default and the project's native 3-D files have no pixel frame"): their default thresholds are in pixels and would silently change with the project unit. The Metrics screen greys them out, `validate` and the run `README.md` list the reason. IL-15 appears once the water column is set. +The per-frame table has no z column (z is exported only through the metrics); with a water column it +carries `depth_fraction` and `depth_cm` as for a fused unit. The run's `README.md` has a **Native 3-D +source** section (reader, file unit, project unit, vertical axis, flip, water column or its absence). + +Limits of native 3-D files: one animal per file; no mixing with pixel sessions; the unit you give +must be the one of the calibration board (a wrong one scales everything); no refraction correction; +the water column is entered, not estimated; no zones or background image; no group metrics and no IL-3, IL-9, IL-10 or IL-14; a multi-animal DeepLabCut +3-D table (with an `individuals` header row) is named by the scan as one it cannot read yet. + Limits of this version: - Zones are one set, applied to the top view. There are no per-view or depth-band zones. diff --git a/docs/superpowers/plans/2026-10-11-native-3d-files.md b/docs/superpowers/plans/2026-10-11-native-3d-files.md new file mode 100644 index 00000000..c06a09e7 --- /dev/null +++ b/docs/superpowers/plans/2026-10-11-native-3d-files.md @@ -0,0 +1,128 @@ +# Native 3-D Files Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Read Anipose pose-3d CSV and DLC-3D files into sessions that carry an absolute `z` in the project's length unit, so IL-16, IL-17, GL-16 (and IL-15 once the user gives a water column) run on them. + +**Architecture:** Two readers share `readers/native3d.py` (unit table, axis permutation, assembly). A native session has `has_pixel_frame = False`, `length_unit = 1.0`, `raw_z`; the pipeline lays `raw_z` out beside `xy` as `PreprocessedSession.z`; the water column (a `CalibrationConfig` field) derives `depth` after calibration. A native 3-D project is a `dimension == "2d"` project whose sessions come from native readers, so run units, stage flow and the Views/Fusion steps need no change (a ruling that refines the spec: `dimension "3d"` keeps meaning "top + side views to fuse"). + +**Tech Stack:** Python, pydantic v2, numpy/pandas, PySide6, pytest/pytest-qt, ruff, mypy (CI: mypy 2.4.0 + numpy 2.4.6). + +**Spec:** `docs/3d-movement/2026-10-10-native-3d-files-design.md`. Builds on B1/B2: `track2data/metrics/geometry3d.py`, `track2data/metrics/availability.py`, `Engine.preprocess`/`run_units` in `track2data/api.py`. + +## Global Constraints + +- Reader ids `anipose` and `deeplabcut_3d`, `verification = "synthetic_only"`, class flag `provides_native_3d: ClassVar[bool] = True` (default False on `SessionReader`). The set of native reader names is the constant `NATIVE_3D_READERS = frozenset({"anipose", "deeplabcut_3d"})` in `track2data/readers/native3d.py`, which availability code uses without importing the registry. +- Options (`ReaderParameter`, in this order): `fps` (float, required), `unit` (choice `mm|cm|m|in`, required, Anipose proposes `mm` with source `tool-default`), `target_unit` (choice `mm|cm|m|in`, default `cm`), `keypoint`, `likelihood_cutoff` (Anipose only, applied to `_score`, default 0.0 = no cutoff; DLC-3D has no likelihood and no such option), `vertical_axis` (choice `x|y|z`, default `z`), `flip` (bool, default false), `keep_skeleton` (bool, default true). +- Unit factors to metres: mm 0.001, cm 0.01, m 1.0, in 0.0254; coordinate × factor(unit) / factor(target) = coordinate in `target_unit`. +- Session fields: `has_pixel_frame: bool = True`, `coordinate_unit: str | None = None`, `raw_z: np.ndarray | None = None` shape `(n_frames, n_animals)` float64; `PreprocessedSession.z` same rows as `xy`. Native sessions: `has_pixel_frame False`, `length_unit 1.0`, `video.width_px = video.height_px = 0`, `coordinate_unit = target_unit`, `raw_attrs["native_3d"]` = `{"source_unit","target_unit","vertical_axis","flip"}`. +- Missing values: Anipose NaN in x, y, z together; DLC-3D a row where x, y and z are all exactly 0 (a single 0 is a real coordinate). +- `CalibrationConfig.water_column: WaterColumn | None = None`, `WaterColumn(surface_z: float, floor_z: float)`, finite and `surface_z != floor_z` (either order allowed). Derived: `depth = (z - surface_z) / (floor_z - surface_z)`, `depth_height_cm = abs(floor_z - surface_z)`, outside [0, 1] -> NaN and `depth_outside_mask`/`depth_outside` (counted, never clipped). +- Reason strings, exactly: `NEEDS_WATER_COLUMN_REASON = "needs the water column (surface and floor z) on the Calibration page"`; for the project-mixing error codes `NATIVE_3D_MIXED` (message names both kinds and the session) and `NATIVE_3D_UNIT_MISMATCH` (names both target units). +- Native projects require `calibration.mode == "session"`, `length_unit_label == target_unit` and `length_unit_confirmed_by_user True`; the first native import sets them. `Engine.validate` blocks other modes. +- No existing output changes for sessions with `has_pixel_frame True`: existing suites stay green, `ruff check .` and CI-venv `mypy` clean, `-W error::RuntimeWarning` on the new tests. + +## Review Focus + +- A frame gap in the file (Anipose `fnum` skips, or rows missing) leaves `raw_z`, `xy` and the tracking intervals on the same rows, including bridged and separator rows (Task 1, Task 2). +- DLC-3D's `0 = missing` must not erase a real 0 coordinate: a row is missing only when x, y and z are all exactly 0 (Task 3). +- A wrong unit silently scales every speed: `unit` is required, never defaulted silently, and a missing one is an error naming the option (Task 2). +- A water column with the floor on the other side of the surface (reversed order) works; `surface_z == floor_z` or non-finite is refused (Task 1, Task 4). +- A native session in a pixel project, a pixel session in a native project, or a native session in a fused 3-D project is refused with the code above (Task 4); and no screen or metric crashes or invents an arena from `video.width_px = 0` (Task 5). + +--- + +### Task 1: Core: `z`, water column, pipeline, geometry + +**Files:** +- Modify: `track2data/core/models.py` (Session fields, `PreprocessedSession.z`, `WaterColumn`, `CalibrationConfig.water_column`), `track2data/preprocess/pipeline.py` (lay out `raw_z`), `track2data/metrics/binning.py` (`slice_psess` slices `z`), `track2data/metrics/geometry3d.py` (`positions_cm` uses `psess.z`), `track2data/api.py` (`Engine.preprocess` derives depth after calibration) +- Create: `track2data/calibration/water_column.py` +- Test: `tests/test_native3d/test_core.py` (new, with `__init__.py`) + +**Interfaces:** +- Produces: `WaterColumn(BaseModel)`; `apply_water_column(psess: PreprocessedSession, wc: WaterColumn) -> PreprocessedSession` (returns `dataclasses.replace(...)` with `depth`, `depth_height_cm`, `depth_outside`, `depth_outside_mask` set; unchanged when `psess.z is None`); `geometry3d.positions_cm` returns Z from `psess.z` when set, else `depth * depth_height_cm`, `None` only when neither exists or `px_per_cm` is missing (and `depth_height_cm` is no longer required when `z` is set). + +- [ ] **Step 1: Write failing tests** (names are the contract): `test_water_column_validation` (equal, NaN, inf refused; reversed order accepted); `test_apply_water_column_exact` (surface 0, floor 20, z = [0, 5, 20, 25, -1] gives depth [0, .25, 1, NaN, NaN], `depth_height_cm == 20`, outside mask [F,F,F,T,T], `depth_outside == 2`); `test_apply_water_column_reversed` (surface 20, floor 0 gives the same fractions for z = [20, 15, 0]); `test_pipeline_lays_out_z_with_xy` (a session with `tracking_intervals` that leave a gap: `psess.z.shape == psess.xy.shape[:2]`, NaN on separator rows, equal to `raw_z` on tracked rows; and the no-gap case equals `raw_z`); `test_slice_psess_slices_z`; `test_positions_cm_uses_z_without_depth` (xy 80,40 at `px_per_cm 8`, z 12 gives (10, 5, 12)); `test_positions_cm_none_without_z_or_depth`; `test_pixel_sessions_unchanged` (`z is None`, `has_pixel_frame True`). +- [ ] **Step 2: Run** `pytest tests/test_native3d/test_core.py -v`. Expected: FAIL. +- [ ] **Step 3: Implement** the fields and `WaterColumn` (a `model_validator` for finite and unequal); in `pipeline.run` lay `raw_z` out with `lay_out(expansion, session.raw_z)` when an expansion exists, else copy; pass `z=` into `PreprocessedSession`; `slice_psess` slices `z` beside `depth` (grep `depth_outside_mask` for every site that copies depth-like arrays and add `z`); `Engine.preprocess` calls `apply_water_column` after calibration when `calibration.water_column` is set and `psess.z` exists; `positions_cm` as in Interfaces (keep the fused path byte-identical). +- [ ] **Step 4: Run** `pytest tests/test_native3d tests/test_metrics tests/test_preprocess tests/test_fusion tests/test_integration -q -W error::RuntimeWarning`, `ruff check .`, `mypy`. Expected: PASS. +- [ ] **Step 5: Commit** `feat(native3d): absolute z, water column and 3-D positions from z`. + +### Task 2: Shared helpers and the Anipose reader + +**Files:** +- Create: `track2data/readers/native3d.py`, `track2data/readers/anipose.py` +- Modify: `track2data/readers/base.py` (`provides_native_3d` flag), `track2data/readers/assemble.py` (`assemble_native_session`), `track2data/readers/__init__.py` (register) +- Test: `tests/test_readers/test_native3d.py`, `tests/test_readers/test_anipose.py` (new; synthetic files built in the tests, helper `write_anipose_csv(tmp_path, keypoints, frames, ...)` in `tests/test_readers/native3d_files.py`) + +**Interfaces:** +- Produces in `native3d.py`: `NATIVE_3D_READERS`, `UNIT_FACTORS_M: dict[str, float]`, `convert_units(values: np.ndarray, unit: str, target: str) -> np.ndarray`, `horizontal_axes(vertical_axis: str) -> tuple[int, int]` (the two other axes, in file order), `native_parameters(unit_default: str | None) -> tuple[ReaderParameter, ...]` (the Global Constraints list), `reduce_native(xy3: np.ndarray, names: list[str], confidence: np.ndarray | None, *, keypoint: str | None, cutoff: float | None, vertical_axis: str, flip: bool) -> tuple[Reduction, np.ndarray]` (the Reduction from `reduce_keypoints(..., plane=horizontal_axes(...))` and the chosen keypoint's z `(F, A)`, negated when `flip`). +- Produces in `assemble.py`: `assemble_native_session(*, session_id, folder, reader, fps, raw_xy, raw_z, source_unit, target_unit, vertical_axis, flip, keypoints, tracking_intervals, trajectory_source, trajectory_format) -> Session` with the Session fields of Global Constraints and `DataValidationError(code="READER_OUTPUT_INVALID")` for bad shapes or fps. +- `AniposeReader(SessionReader)` with `name = "anipose"`, `provides_native_3d = True`, `coordinate_frame = "physical_unaligned"`, `detect`, `discover`, `read`; one animal, `identities_labels None`, `has_stable_identities True`. + +- [ ] **Step 1: Write failing tests:** `test_convert_units_table` (mm to cm /10, m to cm x100, in to mm x25.4, same unit identity); `test_horizontal_axes` (z -> (0,1), y -> (0,2), x -> (1,2)); `test_anipose_detects_layout_and_rejects_near_misses` (a DLC 2-D file, a CSV with `_x/_y` but no `_z`, no `fnum`); `test_anipose_hyphenated_keypoint_names` (`l-base_x` splits from the right); `test_anipose_reads_exact_values` (3 keypoints, 5 frames, mm to cm: `raw_xy`, `raw_z` equal the hand values; `keypoints.xy.shape == (5,1,3,3)`); `test_anipose_nan_triple_is_missing`; `test_anipose_fnum_gap_gives_tracking_intervals` (fnum 0,1,2,5,6 -> intervals [(0,3),(5,7)] and `raw_z` length 5); `test_anipose_vertical_axis_and_flip` (vertical `y` makes `raw_xy` the x and z columns, `raw_z` the y column; flip negates `raw_z`); `test_anipose_keypoint_and_score_cutoff`; `test_anipose_requires_fps_and_unit` (each missing -> `READER_OPTION_*` error naming the option); `test_anipose_session_flags` (`has_pixel_frame False`, `length_unit 1.0`, `coordinate_unit == target`, `video.width_px == 0`, `raw_attrs["native_3d"]`); `test_anipose_registered_and_discovered` (scan a folder, a `Detection` with `reader == "anipose"`, `proposed["unit"].value == "mm"` and source `tool-default`). +- [ ] **Step 2: Run** `pytest tests/test_readers/test_native3d.py tests/test_readers/test_anipose.py -v`. Expected: FAIL. +- [ ] **Step 3: Implement** the helpers, `assemble_native_session` and `AniposeReader` following `readers/deeplabcut.py` (`_files_in`, `discover` with the peeked header, `_build_session` shape); the file read uses pandas like `_read_table`; register after `DeepLabCutReader`; the `keep_skeleton` memory guard is `skeleton_fits` as for DLC. +- [ ] **Step 4: Run** `pytest tests/test_readers tests/real_samples -q -W error::RuntimeWarning` (the existing Anipose contract case may flip from XFAIL to run: if the fixture file is absent it stays skipped), `ruff check .`, `mypy`. Expected: PASS. +- [ ] **Step 5: Commit** `feat(readers): shared native 3-D helpers and the Anipose reader`. + +### Task 3: The DLC-3D reader + +**Files:** +- Create: `track2data/readers/deeplabcut_3d.py` +- Modify: `track2data/readers/__init__.py` (register) +- Test: `tests/test_readers/test_deeplabcut_3d.py` (new, uses the helper file writers in `tests/test_readers/native3d_files.py`, adding `write_dlc3d_csv`) + +**Interfaces:** +- Consumes: Task 2's `native_parameters`, `reduce_native`, `assemble_native_session`. +- Produces: `DeepLabCut3DReader(SessionReader)` with `name = "deeplabcut_3d"`, `provides_native_3d = True`, `detect`/`discover`/`read`; header is three rows `scorer`, `bodyparts`, `coords` with `x, y, z` per body part; no `likelihood_cutoff` option (it is dropped from `parameters`). + +- [ ] **Step 1: Write failing tests:** `test_detects_only_the_3d_header` (a 2-D DLC file with `likelihood` is not claimed, nor a header with `x, y` only; and `DeepLabCutReader` does not claim the 3-D file); `test_reads_exact_values_and_units`; `test_all_zero_row_is_missing_but_a_single_zero_is_real` (a keypoint row (0,0,0) is NaN; (0,5,3) keeps x=0); `test_vertical_axis_and_flip`; `test_requires_fps_and_unit`; `test_multi_frame_index_from_the_first_column` (the leading index column is the frame number, gaps give tracking intervals); `test_session_flags` as for Anipose. +- [ ] **Step 2: Run** `pytest tests/test_readers/test_deeplabcut_3d.py -v`. Expected: FAIL. +- [ ] **Step 3: Implement** `DeepLabCut3DReader` reusing `deeplabcut._read_table`-style parsing for the header (three rows), then `reduce_native` and `assemble_native_session`; confirm `DeepLabCutReader.discover`/`detect` reject the 3-D header (its parser needs `likelihood`; if it can accept a 3-D header, tighten it and add the regression test). +- [ ] **Step 4: Run** `pytest tests/test_readers -q -W error::RuntimeWarning`, `ruff check .`, `mypy`. Expected: PASS. +- [ ] **Step 5: Commit** `feat(readers): DLC-3D reader`. + +### Task 4: Project rules, availability and engine + +**Files:** +- Modify: `track2data/readers/native3d.py` (`manifest_native_3d`), `track2data/metrics/availability.py`, `track2data/api.py` (`import_sessions`/`import_ref`, `validate`, `preprocess` calibration for native, run-time availability, `_resolve_px_per_cm`), `ui/store/project_store.py` (`add_session` path sets the first-import calibration, using the same Engine function) +- Test: `tests/test_native3d/test_project_rules.py`, extend `tests/test_metrics/test_availability.py` + +**Interfaces:** +- Consumes: Task 1's `WaterColumn`/`psess.z`, Task 2's `NATIVE_3D_READERS`. +- Produces: `manifest_native_3d(manifest) -> bool` (any `SessionRef.reader in NATIVE_3D_READERS`); `Engine.register_native_import(session: Session) -> None` called by every import path (raises `ImportError_` codes `NATIVE_3D_MIXED` and `NATIVE_3D_UNIT_MISMATCH`; on the first native import sets `calibration.mode = "session"`, `length_unit_label = session.coordinate_unit`, `length_unit_confirmed_by_user = True`); availability for native projects: `manifest_view` returns `("top", water_column is not None)`; `manifest_depth_scale` reports the project as 3-D data (`dimension "3d"`, `has_depth True`, documented in its docstring: the name means "3-D data present" for native projects); IL-15 in a native project without a water column is unavailable with `NEEDS_WATER_COLUMN_REASON` (never the camera-view text); `Engine.validate` reports an error when a native project's calibration mode is not `session`; run time: a native unit's `has_depth` comes from `psess.z`, and the "3-D projects compute fused sessions only" guard in `compute_metrics` is unchanged for `dimension "3d"` and not applied to native sessions. + +- [ ] **Step 1: Write failing tests:** `test_first_native_import_sets_calibration` (mode `session`, label equals target, confirmed); `test_second_import_with_other_target_is_refused` (`NATIVE_3D_UNIT_MISMATCH` naming both); `test_native_into_pixel_project_and_back_are_refused` (`NATIVE_3D_MIXED`, both directions); `test_native_refused_in_a_fused_3d_project`; `test_validate_requires_session_mode`; availability: `test_native_project_offers_the_three_3d_metrics` (IL-16, IL-17, GL-16 available at manifest level and per unit), `test_il15_needs_the_water_column_in_a_native_project` (reason text exactly `NEEDS_WATER_COLUMN_REASON` in `Engine.skipped_metrics`, `validate`, and the Metrics screen row) and `test_il15_available_with_the_water_column`; `test_2d_and_fused_projects_unchanged` (their reasons are the existing strings). +- [ ] **Step 2: Run** `pytest tests/test_native3d/test_project_rules.py tests/test_metrics/test_availability.py -v`. Expected: FAIL. +- [ ] **Step 3: Implement** by routing every availability caller through `availability.unavailable_reason` (the B2 single function; thread the native/water-column facts the same way `depth_scale` was threaded: grep `manifest_depth_scale` and `manifest_view` for every caller, including `Engine.skipped_metrics`, `validate`, `_view_selection_notes`, the CLI `list-metrics` and `ui/metrics_screen.py`). +- [ ] **Step 4: Run** `pytest tests/test_native3d tests/test_metrics tests/test_camera_view_gating.py tests/test_api.py tests/test_ui -q -W error::RuntimeWarning`, `ruff check .`, `mypy`. Expected: PASS. +- [ ] **Step 5: Commit** `feat(native3d): project rules, calibration and availability`. + +### Task 5: No pixel frame: zones, arena, screens, Calibration page, CLI + +**Files:** +- Modify: `track2data/metrics/derived.py` (IL-3/IL-14 arena fallback), `track2data/core/session_consistency.py`, `track2data/zones/io.py`, `ui/zones_screen.py`, `ui/preview_screen.py`, `ui/store/session_facts.py`, `ui/calibration_screen.py` (water column fields), `track2data/exporters/readme.py` ("Native 3-D source" block), `track2data/cli.py` (confirm the readers' options reach `t2d import --option`) +- Test: `tests/test_native3d/test_no_pixel_frame.py`, `tests/test_ui/test_calibration_water_column.py` + +**Interfaces:** +- Consumes: Task 1's `Session.has_pixel_frame`/`coordinate_unit`, Task 4's `manifest_native_3d`. +- Produces: every consumer of `video.width_px`/`height_px` (grep: `session_consistency`, `derived`, `zones/io`, `zones_screen`, `preview_screen`, `session_facts`, `calibration_screen`) either skips or uses the data extent when `has_pixel_frame` is False; `derived` arena fallback `centre`/`radius` from the min/max of the finite `xy` with the warning text `"no pixel frame: the arena was taken from the extent of the tracked positions"`; the Zones screen shows a disabled notice `"This project's sessions have no pixel frame (native 3-D); zones are not available."`; the Calibration page shows the two water column fields (`surface z`, `floor z`, labelled with `length_unit_label`) only when `manifest_native_3d`, and writes `calibration.water_column` through the store (clearing it when either is empty; invalid values refused with the field named). + +- [ ] **Step 1: Write failing tests:** `test_arena_fallback_uses_extent_with_warning` (xy spanning 0..10 gives centre (5,5), radius 5, the warning present, no `ZeroDivisionError`/NaN); `test_no_consumer_reads_zero_video_size` (a native session through `core.session_consistency` checks and `session_facts` produces no error and no frame-size complaint); `test_zones_screen_is_disabled_for_native` (pytest-qt; no ROI can be added); `test_calibration_fields_only_for_native_projects`; `test_water_column_fields_round_trip_through_the_store` (type values, `manifest.calibration.water_column` equals them; clear one -> `None`; equal values -> refused with the field named); `test_readme_native_block` (reader, file unit, project unit, vertical axis, flip, water column or its absence); `test_cli_import_options` (`t2d import --option unit=mm --option fps=100` on a synthetic Anipose file creates the session). +- [ ] **Step 2: Run** `pytest tests/test_native3d/test_no_pixel_frame.py tests/test_ui/test_calibration_water_column.py -v`. Expected: FAIL. +- [ ] **Step 3: Implement** each consumer guard (a small helper `Session.pixel_size_known` property = `has_pixel_frame and width_px > 0 and height_px > 0` keeps the checks one-line), the screens, the README block and the store setter; a pixel session's behaviour stays byte-identical. +- [ ] **Step 4: Run** `pytest tests/test_native3d tests/test_ui tests/test_metrics tests/test_zones tests/test_exporters -q -W error::RuntimeWarning`, `ruff check .`, `mypy`. Expected: PASS. +- [ ] **Step 5: Commit** `feat(native3d): no-pixel-frame handling, water column fields, README block`. + +### Task 6: End to end, docs and full check + +**Files:** +- Create: `tests/test_integration/test_native_3d.py` +- Modify: `CHANGELOG.md` (`### Added`), `docs/dev/DECISIONS.md` (new entry after the last: amends D-031 a second time), `docs/guide/USER_GUIDE.md` (the 3-D section: native files, units, vertical axis, water column, limits), `docs/tracker-formats/2026-10-07-tracker-import-design.md` and `animal_tracking_output_formats.md` (P5 status, DLC-3D entry), `docs/3d-movement/2026-10-10-native-3d-files-design.md` (status "implemented", a "Changes made during the build" section recording the 2-D-dimension ruling), `docs/3d-movement/2026-10-08-3d-roadmap.md` (A done), README reader list and counts +- Test: `tests/test_docs/test_guide.py` + +- [ ] **Step 1: End-to-end tests** (synthetic Anipose file built in the test, a fish moving (3, 4, 12) mm per frame at 25 fps, 11 frames, unit `mm`, target `cm`): import through `Engine`, preprocess, run IL-16/IL-17/GL-16 with two files (two sessions) and assert exact values (10 steps x hypot(0.3, 0.4, 1.2) = 1.3 cm per step = 13 cm path, speed 1.3 cm x 25 fps = 32.5 cm/s; state this arithmetic in the test), IL-15 unavailable without and exact with a water column (including outside values counted), the 2-D metrics on the horizontal plane, a binned run, serial vs parallel agree, the same project with `vertical_axis="y"`; a pixel-frame (idtracker.ai/DLC 2-D) control project run unchanged (compare a sessions.csv header and a metric table with the existing expectations). +- [ ] **Step 2: Docs** written from the spec after verifying every id, option name, code and reason string in the code; state the limits (one animal per file, no z in the per-frame table, no mixing, board unit must be confirmed, no refraction correction, water column is entered not estimated). +- [ ] **Step 3: Run** `pytest tests/test_docs -q`, then the full `QT_QPA_PLATFORM=offscreen python -m pytest -q -x -W error::RuntimeWarning` (background, output to a file, poll), `ruff check .` and CI-venv `mypy`. Expected: all pass; report any segfault or abort at exit verbatim. +- [ ] **Step 4: Commit** `test: end-to-end native 3-D files` and `docs: describe native 3-D files`. diff --git a/docs/tracker-formats/2026-10-07-tracker-import-design.md b/docs/tracker-formats/2026-10-07-tracker-import-design.md index 01783790..557f0c2c 100644 --- a/docs/tracker-formats/2026-10-07-tracker-import-design.md +++ b/docs/tracker-formats/2026-10-07-tracker-import-design.md @@ -257,6 +257,11 @@ which are disabled when there is no pixel frame; and the IL-3 and IL-14 arena fallback, which uses data extent plus a warning instead of `width_px`/`height_px` = 0. Existing idtracker.ai outputs stay unchanged. +**Built (P5).** The two native 3-D readers use `has_pixel_frame False` and `coordinate_unit` +as described; they convert to the project unit when reading instead of at calibration time, +so the `_mm` suffix table was not needed (the `_cm` suffix is nominal, the run README states +the real unit). + ## 5. Rollout tiers | Tier | Prio | Importer | Citations | Cum. % | Gate | Suite cases that must flip XFAIL → PASS | @@ -266,7 +271,7 @@ Existing idtracker.ai outputs stay unchanged. | 1 | 2 | SLEAP analysis HDF5 (+ CSV layouts; `.slp` recognise-only) | 760 | 65.0 | none | `sleap_named_tracks`, `sleap_no_tracks` | | 2 | 3 | Ctrax raw `.mat`, `trx.mat`, FlyTracker `-track.mat` | 371 | 70.5 | G-JAABA, G-fragments | `ctrax_raw_mat` | | 3 | 4 | ToxTrac `Tracking_RealSpace.txt` (+ pixel twin) | 218 | 73.7 | G-units | `toxtrac_realspace` | -| 3 | 5 | Anipose pose-3d CSV (+ DLC-3D) | 195 | 76.6 | G-units | quirk tests; a Session-level case is added with the reader | +| 3 | 5 | Anipose pose-3d CSV (+ DLC-3D) | 195 | 76.6 | G-units | quirk tests; a Session-level case is added with the reader. **Built (P5)** | | 4 | 6 | TRex `.npz` (new and old versions; CSV export) | 166 | 79.0 | none | `trex_new_export`, `trex_old_export` | | 4 | 7 | AnimalTA CSV (fixed and variable; detailed = recognise-only) | 95 | 80.5 | none | `animalta_fixed_csv` | | 5 | – | Backlog by ease: FastTrack, OCTRON, generic table, WCON, TrackMate, Argos, Tierpsy, ZebraZoom, Stytra, ethoscope, `.slp`, NWB, movement `.nc`. Blocked (no documented schema): DANNCE, AlphaTracker, anTraX, MWT, MARGO, BioTracker, LabGym, pathtrackr, DeepPoseKit, FicTrac (not arena trajectories) | – | – | demand and a sample | – | @@ -375,7 +380,16 @@ tests. Where they differ, the pinned tests win. With no twin, native-unit mode applies. One session per arena. The suite's check is unit-neutral (axis directions only). -### P5 Anipose pose-3d CSV (quirk tests today; a Session-level case is added with the reader) +### P5 Anipose pose-3d CSV and DLC-3D (built; synthetic files only) + +**Status: built** (reader ids `anipose` and `deeplabcut_3d`, `verification = "synthetic_only"`; +spec `docs/3d-movement/2026-10-10-native-3d-files-design.md`, decision D-043). The notes below +are the design inputs; what was built differs in four ways. The reader requires `fps` **and** +`unit` (the file records neither; Anipose proposes `mm` and never defaults it); the unit is +converted to the project unit (`target_unit`, default `cm`) when reading, so the project's +calibration is `session`, label = that unit, confirmed, with `length_unit = 1.0`; the plane is +the horizontal one, chosen by `vertical_axis` (default `z`) and `flip`; and z is kept as +`Session.raw_z` (absolute, in the project unit) beside `KeypointData.xy` (D = 3). - **Detect.** Columns `_x/_y/_z/_error/_ncams/_score`, `M_00…M_22`, `center_0…2`, `fnum`. Pinned: 246 × 49, six keypoints (`l-base`, `l-edge`, `l-middle`, `r-base`, @@ -385,6 +399,18 @@ tests. Where they differ, the pinned tests win. - **From the user.** fps (200 in the sample, not stored) and the plane (default x,y). Board units (mm) mean native-unit mode with no pixel frame. z is kept in `Session.keypoints` (D = 3). +- **Anipose layout, Track2Data notes.** One subject per file; units are the calibration + board's (typically mm), which the file does not state. +- **DLC-3D** (`deeplabcut_3d`). The triangulated table of DeepLabCut's 3-D mode: three header + rows (`scorer`, `bodyparts`, `coords`) with `x`, `y`, `z` per body part, no likelihood, the + frame number in the first column. A body part that could not be triangulated is `0, 0, 0`: + a row is missing only when x, y **and** z are all exactly 0 (or any of them is not finite), + a single 0 is a real coordinate. The unit is the calibration board's; the reader proposes + none, so `unit` must be given. No `likelihood_cutoff` option. One animal per file: a + multi-animal table (four header rows, an `individuals` row) is not detected by this reader; + a narrowed `dlc_3d` entry of `readers/recognise.py` names it (and a table without full x, y, z + triples) as one Track2Data cannot read yet, while the single-animal tables the reader takes are + not reported. ### P6 TRex `.npz` (cases `trex_new_export`, `trex_old_export`) diff --git a/docs/tracker-formats/README.md b/docs/tracker-formats/README.md index e2e69dd7..1f4a47c3 100644 --- a/docs/tracker-formats/README.md +++ b/docs/tracker-formats/README.md @@ -55,7 +55,7 @@ reader fixture-test suite that must go from XFAIL to PASS when the reader lands. | 2 | SLEAP analysis HDF5 | 1 | **built** | `sleap_named_tracks`, `sleap_no_tracks` pass | | 3 | Ctrax raw `.mat` (**built**), `trx.mat`, FlyTracker | 2 | raw `.mat` built; `trx.mat` waits for a real sample; FlyTracker recognise-only | `ctrax_raw_mat` passes | | 4 | ToxTrac `Tracking_RealSpace.txt` | 3 | planned | `toxtrac_realspace` | -| 5 | Anipose pose-3d CSV (and DLC-3D) | 3 | planned | quirk tests only | +| 5 | Anipose pose-3d CSV (and DLC-3D) | 3 | **built** (both; synthetic files only, `verification = "synthetic_only"`) | quirk tests, and synthetic-file reader tests; the real-sample contract case runs when its fixture is present | | 6 | TRex `.npz` | 4 | planned | `trex_new_export`, `trex_old_export` | | 7 | AnimalTA CSV | 4 | planned | `animalta_fixed_csv` | diff --git a/docs/wiki/Compatibility.md b/docs/wiki/Compatibility.md index e51de8dc..454780b5 100644 --- a/docs/wiki/Compatibility.md +++ b/docs/wiki/Compatibility.md @@ -1,6 +1,6 @@ # Compatibility -**Applies to:** Track2Data v0.1.0 and `main` as of 2026-10-09. Reader support changes +**Applies to:** Track2Data v0.1.0 and `main` as of 2026-10-11. Reader support changes between releases; the [changelog](https://github.com/mbel-tech/Track2Data/blob/main/CHANGELOG.md) is authoritative. @@ -14,6 +14,8 @@ is authoritative. | **DeepLabCut** (CSV; also Lightning Pose) | **Supported** | One session per file. Frame rate and frame size are required options; the optional **Scale (pixels per cm)** feeds Session calibration | | **SLEAP** (analysis HDF5) | **Supported** | Export Analysis HDF5 from SLEAP. Same required options and optional scale as DeepLabCut | | **Ctrax** (raw `.mat`) | **Supported** | Frame size is a required option; the frame rate comes from the file. Ctrax track ids are fragments, so a session is identity-free. Optional scale as above | +| **Anipose** (`pose-3d` CSV) | **Unverified** | Built from the published layout, tested on synthetic files only. Native 3-D: one animal per file; the frame rate and the unit of the coordinates are required options (never guessed). See the 3-D section of the user guide | +| **DeepLabCut 3-D** (triangulated CSV) | **Unverified** | Same as Anipose; the unit is the calibration board's and is not proposed. Multi-animal 3-D tables are not read (the scan names them) | | **Ctrax / FlyTracker / JAABA** (`trx.mat`) | **Unverified** | Built from the documented layout with no real sample yet, and labelled as such in the confirm step. Classic MATLAB files only. `pxpermm` becomes the session scale | `track2data list-readers` prints what this build can read and which options each reader @@ -29,7 +31,7 @@ A scan names these rather than reporting "nothing recognised", and says what to instead: SLEAP `.slp` projects (export the Analysis HDF5), a `trx.mat` saved with MATLAB's `-v7.3` option (save it again with `-v7`), FlyTracker `-track.mat`, DANNCE `save_data_AVG.mat`, Multi-Worm Tracker `.blobs`, AnimalTA detailed -files, DeepLabCut 3-D tables, and FicTrac logs. +files, and FicTrac logs. ### Pickled trajectories diff --git a/docs/wiki/Formats-and-Interoperability.md b/docs/wiki/Formats-and-Interoperability.md index 39f34e0b..df0ae3ff 100644 --- a/docs/wiki/Formats-and-Interoperability.md +++ b/docs/wiki/Formats-and-Interoperability.md @@ -1,6 +1,6 @@ # Formats and Interoperability -Track2Data reads idtracker.ai, DeepLabCut, SLEAP (analysis HDF5), Ctrax (raw `.mat`) and `trx.mat` output; [[Compatibility]] has the status of each (pre-1.0, see the [changelog](https://github.com/mbel-tech/Track2Data/blob/main/CHANGELOG.md)). +Track2Data reads idtracker.ai, DeepLabCut, SLEAP (analysis HDF5), Ctrax (raw `.mat`), `trx.mat`, Anipose `pose-3d` CSV and DeepLabCut 3-D output; [[Compatibility]] has the status of each (pre-1.0, see the [changelog](https://github.com/mbel-tech/Track2Data/blob/main/CHANGELOG.md)). ## Headless commands diff --git a/docs/wiki/Glossary.md b/docs/wiki/Glossary.md index b289f10a..bac464b6 100644 --- a/docs/wiki/Glossary.md +++ b/docs/wiki/Glossary.md @@ -66,7 +66,7 @@ cleanup: see [[Statistics and Pseudoreplication]] and `track2data sensitivity`. | **Path length** | IL-1 | `path_length_px` / `_cm` / `_bl` — a *total*, so it scales with session duration | | **Speed** | IL-2 | `mean_speed_*`, `median_speed_*`, `max_speed_*` | | **Thigmotaxis** | IL-14, IL-3 | `mean_wall_distance_px`, `wall_contact_time_pct`; `time_in_centre_pct` | -| **Depth (vertical position)** | IL-15 | `mean_depth_fraction`, `median_depth_fraction`, `sd_depth_fraction` (0 = water surface, 1 = tank floor), `mean_depth_cm`, `frac_outside_extent`, `depth_extent_source`. Needs a side view and a main zone from the waterline to the floor. Height above the floor is 1 − depth | +| **Depth (vertical position)** | IL-15 | `mean_depth_fraction`, `median_depth_fraction`, `sd_depth_fraction` (0 = water surface, 1 = tank floor), `mean_depth_cm`, `frac_outside_extent`, `depth_extent_source`. Needs a side view and a main zone from the waterline to the floor, or, for a native 3-D file, the water column (surface z and floor z) entered on the Calibration page. Height above the floor is 1 − depth | | **Freezing / activity** | IL-4 | `active_fraction`, `freezing_fraction`, `threshold_px_s` | | **Bout** | IL-7, Z-3 | A run of consecutive frames meeting a criterion. `min_bout_frames_used` and `bout_criterion_effective` record the criterion actually applied — report it | | **Tortuosity** | IL-5 | `tortuosity` — path length ÷ net displacement | diff --git a/docs/wiki/Known-Issues.md b/docs/wiki/Known-Issues.md index 17ffc2f9..36341dbb 100644 --- a/docs/wiki/Known-Issues.md +++ b/docs/wiki/Known-Issues.md @@ -58,9 +58,9 @@ Those sessions are exported in pixels only. The run now says so instead of skipp calibration silently. **Only some trackers are readable.** idtracker.ai, DeepLabCut, SLEAP (analysis HDF5), Ctrax -(raw `.mat`) and `trx.mat` are. A scan *names* formats it recognises but cannot read — SLEAP +(raw `.mat`), `trx.mat`, Anipose `pose-3d` CSV and DeepLabCut 3-D tables are. A scan *names* formats it recognises but cannot read — SLEAP `.slp`, a `-v7.3` `trx.mat`, FlyTracker `-track.mat`, DANNCE, Multi-Worm Tracker `.blobs`, -AnimalTA, DeepLabCut 3-D and FicTrac — and says what to export instead. See +AnimalTA and FicTrac — and says what to export instead. See [[Formats and Interoperability]] and [[Compatibility]]. **The `trx.mat` reader has not been checked against a real file.** It follows the documented diff --git a/tests/test_integration/test_end_to_end.py b/tests/test_integration/test_end_to_end.py index 36b8c5b8..e8e34de1 100644 --- a/tests/test_integration/test_end_to_end.py +++ b/tests/test_integration/test_end_to_end.py @@ -1094,5 +1094,5 @@ def test_cli_list_metrics_names_the_requirement_of_the_3d_metrics() -> None: out = CliRunner().invoke(cli, ["list-metrics"]).output rows = {line.split()[0]: line for line in out.splitlines() if line[:3] in {"IL-", "GL-"}} for mid in ("IL-16", "IL-17", "GL-16"): - assert "fused 3-D + cm scale" in rows[mid] + assert "fused 3-D or native 3-D, cm scale" in rows[mid] assert "fused 3-D" not in rows["IL-1"] diff --git a/tests/test_integration/test_native_3d.py b/tests/test_integration/test_native_3d.py new file mode 100644 index 00000000..542ee312 --- /dev/null +++ b/tests/test_integration/test_native_3d.py @@ -0,0 +1,293 @@ +"""Native 3-D files end to end: synthetic Anipose files added through the real add flow (the CLI, +which sets up the project's calibration), preprocessed, and run through IL-15/IL-16/IL-17/GL-16. + +Scene: a fish that moves (3, 4, 12) mm per frame at 25 fps for 11 frames (10 steps), file unit mm, +project unit cm. One step is (0.3, 0.4, 1.2) cm, so + +* its length is hypot(0.3, 0.4, 1.2) = sqrt(0.09 + 0.16 + 1.44) = 1.3 cm; +* IL-16, the path, is 10 steps x 1.3 cm = 13 cm; +* IL-17, the speed, is 1.3 cm x 25 frames/s = 32.5 cm/s at every frame (mean = median = max); +* the horizontal plane (x, y with z vertical) has a step of 0.5 cm: IL-1 5 cm, IL-2 12.5 cm/s. + +The second file is the same track shifted by +100 mm in x and y and +100 mm in z (+10 cm). +""" + +from __future__ import annotations + +import math +import re +from datetime import UTC, datetime +from pathlib import Path + +import numpy as np +import pandas as pd +import pytest +from click.testing import CliRunner + +from tests.test_fusion.scene import build_scene +from tests.test_readers.native3d_files import write_anipose_csv +from track2data.api import NATIVE_3D_NEEDS_SESSION_CALIBRATION, Engine +from track2data.cli import cli +from track2data.core.manifest import read as read_manifest +from track2data.core.manifest import write as write_manifest +from track2data.core.models import ( + MetricSelection, + ProjectManifest, + ProjectMode, + WaterColumn, +) +from track2data.metrics.availability import NEEDS_SEVERAL_ANIMALS_REASON, NEEDS_WATER_COLUMN_REASON + +N_FRAMES = 11 +FPS = 25.0 +STEP_MM = np.array([3.0, 4.0, 12.0]) +SHIFT_MM = 100.0 +STEP_CM = 1.3 +PATH_CM = 13.0 +SPEED_CM_S = 32.5 +SELECTION = MetricSelection( + individual=["IL-1", "IL-2", "IL-15", "IL-16", "IL-17"], group=["GL-16"] +) +_STAMP = re.compile(rb"\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d+)?\+00:00") + + +def _track(shift_mm: float = 0.0) -> np.ndarray: + """``(frames, 1, 3)`` mm: the fish at frame f is at f * (3, 4, 12) mm, plus the shift.""" + return np.arange(N_FRAMES, dtype=float)[:, None, None] * STEP_MM + shift_mm + + +def _native_project(root: Path, *extra_options: str) -> Path: + """Two Anipose files added to a new project by ``t2d add`` (the real add flow).""" + data = root / "data" + data.mkdir(parents=True) + write_anipose_csv(data / "fish1.csv", ["head"], N_FRAMES, xyz=_track()) + write_anipose_csv(data / "fish2.csv", ["head"], N_FRAMES, xyz=_track(SHIFT_MM)) + now = datetime.now(tz=UTC) + project = root / "p.t2d.json" + write_manifest(ProjectManifest(project_name="native", created_at=now, updated_at=now), project) + args = ["add", str(project), str(data), "--option", "unit=mm", "--option", "fps=25", "--yes"] + for option in extra_options: + args += ["--option", option] + result = CliRunner().invoke(cli, args) + assert result.exit_code == 0, result.output + return project + + +def _manifest( + project: Path, + water_column: WaterColumn | None = None, + bin_minutes: float | None = None, +) -> ProjectManifest: + manifest = read_manifest(project) + calibration = manifest.calibration.model_copy(update={"water_column": water_column}) + metrics = SELECTION.model_copy(update={"timepoint_minutes": bin_minutes}) + return manifest.model_copy(update={"calibration": calibration, "metrics": metrics}) + + +def _long(out: Path, session: str) -> pd.DataFrame: + return pd.read_csv(out / session / "metrics_long.csv") + + +def _value(long: pd.DataFrame, metric: str, column: str) -> float: + rows = long[(long["metric_id"] == metric) & (long["column"] == column)] + assert len(rows) == 1, (metric, column, len(rows)) + return float(rows["value"].iloc[0]) + + +def _files(root: Path) -> dict[str, bytes]: + return { + str(p.relative_to(root)): _STAMP.sub(b"