Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/).

### Fixed

- **Native 3-D projects refuse files on different vertical axes.** The project has one water column, entered on "the file's own vertical axis", but `vertical_axis` was only recorded in provenance, so two files read with different axes shared a surface and floor that meant different things for each. The import rule that already refuses mixed units now also refuses a file whose `vertical_axis` differs from the project's (`NATIVE_3D_AXIS_MISMATCH`, naming both axes and the fix), whether it comes in with the same batch, was already in the project, or is a session just read. A missing option counts as `z`, the default; `flip` may still differ because it is compensated per session. The rule runs whenever a session is read, as the unit rule does, so an existing project whose files already disagree is refused with the same message until they are re-added on one axis. The origin of the axis cannot be checked from the files, so the water column still assumes one shared origin.
- **Native 3-D files: the water column now bounds every 3-D metric.** It already excluded out-of-column samples from IL-15's depth statistics, but IL-16, IL-17 and GL-16 read the raw z, so a mis-triangulated or out-of-tank sample (a reflection, a fish out of the water) stayed in the path length and speed. One helper, `vertical_cm`, now gives the vertical coordinate to all of them: a sample outside the water column is NaN there, so a step or frame that needs it is dropped (nothing is clipped). The exported `z_cm` column stays the file's own coordinate. **IL-16, IL-17 and GL-16 change for native 3-D projects that set a water column and have samples outside it**; without a column, or with every sample inside, they are unchanged. The Calibration page says so.
- **IL-15 on fused 3-D projects: `frac_outside_extent` no longer grows with top-view gaps.** The share was counted over samples that also had a depth, which needs the top view as well, so a fish the top view lost for half the video reported twice the true share of side-view samples outside the water column (0.20 against 0.10 in the review's probe), and the warning blamed the fusion settings. The fused session now records where the side view had a position (`depth_side_valid`) and the share is over those samples. A side sample with a y but no x now gives a depth (x is only used for the view-agreement check). Native 3-D files are unchanged.
- **Native 3-D files: the vertical axis is now preprocessed like the horizontal plane.** `z` was laid out and then left raw, so a smoothed x/y was combined with an unsmoothed z in IL-16 and IL-17 and no setting could reduce the vertical share of the 3-D path. It now goes through the same steps and settings as x/y: blanked where a jump was replaced, bridged across tracking intervals, gap-filled (same `max_gap_frames`, same limits) and smoothed (same method, window and polyorder). On a synthetic helix with 2 mm noise (true 3-D path 251.5 cm, true vertical path 15.96 cm) the vertical contribution to IL-16 was 129.14 cm at every smoothing setting; it is now 60.09 cm at window 5 (default) and 16.49 cm at window 41, and IL-16 is 275.78 cm and 252.06 cm (was 307.66 and 294.20). **Native 3-D IL-16 and `max_speed_3d_cm_s` will be lower than before on noisy files**; the sensitivity sweep now varies the vertical half too. Cached preprocessing is rebuilt once (cache schema 7); `project_hash` is unchanged.
Expand Down
6 changes: 4 additions & 2 deletions docs/guide/USER_GUIDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -325,8 +325,10 @@ before relying on them.
- **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.
is refused (`NATIVE_3D_UNIT_MISMATCH`, naming both units). They must also share the **vertical
axis**, because one water column serves every session: a file read with another `vertical_axis` is
refused (`NATIVE_3D_AXIS_MISMATCH`, naming both axes); `flip` may differ. 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.
Expand Down
93 changes: 93 additions & 0 deletions tests/test_native3d/test_vertical_axis_rule.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
"""Native sessions of one project must share a vertical axis: one water column serves them all."""

from __future__ import annotations

from pathlib import Path

import pytest

from track2data.api import Engine
from track2data.core.errors import ImportError_
from track2data.core.models import SessionRef

from .test_project_rules import _manifest, _native


def _ref(session_id: str, axis: str | None = None, **extra) -> SessionRef:
options: dict = {"fps": 25.0, "unit": "mm", **extra}
if axis is not None:
options["vertical_axis"] = axis
return SessionRef(
session_id=session_id,
folder=Path("/tmp") / session_id,
sha256="",
reader="anipose",
reader_options=options,
)


def _with_axis(session, axis: str):
attrs = {"native_3d": {"vertical_axis": axis, "flip": False}}
return session.model_copy(update={"raw_attrs": attrs})


def test_a_batch_with_two_vertical_axes_is_refused_naming_both() -> None:
engine = Engine(_manifest([]))
with pytest.raises(ImportError_) as caught:
engine.check_native_refs([_ref("a", "z"), _ref("b", "y")])
assert caught.value.code == "NATIVE_3D_AXIS_MISMATCH"
message = str(caught.value)
assert "'a'" in message and "'b'" in message and "'z'" in message and "'y'" in message


def test_a_file_on_another_axis_than_the_projects_is_refused() -> None:
engine = Engine(_manifest([_ref("a", "z")]))
with pytest.raises(ImportError_) as caught:
engine.check_native_refs([_ref("b", "x")])
assert caught.value.code == "NATIVE_3D_AXIS_MISMATCH"
assert "'a'" in str(caught.value) and "'b'" in str(caught.value)


def test_the_default_axis_is_z_when_the_option_is_not_saved() -> None:
engine = Engine(_manifest([_ref("a")])) # no vertical_axis saved: z
engine.check_native_refs([_ref("b", "z")]) # does not raise
with pytest.raises(ImportError_):
engine.check_native_refs([_ref("c", "y")])


def test_the_same_axis_with_a_different_flip_is_accepted() -> None:
engine = Engine(_manifest([_ref("a", "z", flip=False)]))
engine.check_native_refs([_ref("b", "z", flip=True)])


def test_a_read_session_on_another_axis_is_refused() -> None:
engine = Engine(_manifest([_ref("a", "z")]))
with pytest.raises(ImportError_) as caught:
engine.check_native_import(_with_axis(_native("b"), "y"))
assert caught.value.code == "NATIVE_3D_AXIS_MISMATCH"


def test_a_read_session_on_the_projects_axis_is_accepted() -> None:
engine = Engine(_manifest([_ref("a", "y")]))
engine.check_native_import(_with_axis(_native("b"), "y"))


def test_a_session_without_axis_attributes_counts_as_z() -> None:
engine = Engine(_manifest([_ref("a", "z")]))
engine.check_native_import(_native("b")) # raw_attrs carries nothing: z


def test_the_refusal_says_how_to_fix_it() -> None:
engine = Engine(_manifest([_ref("a", "z")]))
with pytest.raises(ImportError_) as caught:
engine.check_native_refs([_ref("b", "y")])
assert "vertical_axis" in (caught.value.remediation or "")


def test_a_project_whose_files_already_disagree_is_refused_when_one_is_read() -> None:
"""The rule runs on every import, as the unit rule does, so an existing mixed project says
why instead of computing a water column that means two things."""
engine = Engine(_manifest([_ref("a", "z"), _ref("b", "y")]))
with pytest.raises(ImportError_) as caught:
engine.check_native_import(_native("a"))
assert caught.value.code == "NATIVE_3D_AXIS_MISMATCH"
35 changes: 31 additions & 4 deletions track2data/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -155,20 +155,25 @@ class _ImportFact:
reader: str | None
native: bool
unit: str | None
vertical_axis: str | None = None

@classmethod
def of_session(cls, session: Session) -> _ImportFact:
from track2data.readers.native3d import NATIVE_3D_READERS
from track2data.readers.native3d import DEFAULT_VERTICAL_AXIS, NATIVE_3D_READERS

native = session.reader in NATIVE_3D_READERS or not session.has_pixel_frame
return cls(session.session_id, session.reader, native, session.coordinate_unit)
attrs = (session.raw_attrs or {}).get("native_3d") or {}
axis = str(attrs.get("vertical_axis") or DEFAULT_VERTICAL_AXIS) if native else None
return cls(session.session_id, session.reader, native, session.coordinate_unit, axis)

@classmethod
def of_ref(cls, ref: SessionRef) -> _ImportFact:
from track2data.readers.native3d import ref_target_unit
from track2data.readers.native3d import ref_target_unit, ref_vertical_axis

unit = ref_target_unit(ref)
return cls(ref.session_id, ref.reader, unit is not None, unit)
return cls(
ref.session_id, ref.reader, unit is not None, unit, ref_vertical_axis(ref)
)


def _view_note(psess: PreprocessedSession) -> str:
Expand Down Expand Up @@ -612,6 +617,28 @@ def _native_rule(
return None
cfg = self._manifest.calibration
first = natives[0]
# One water column serves every session, so they must share the vertical axis it is
# entered on (flip may differ: it is compensated per session).
from track2data.readers.native3d import ref_vertical_axis

axes = [
(r.session_id, ref_vertical_axis(r))
for r in existing
if r.reader in NATIVE_3D_READERS
]
axes += [(f.session_id, f.vertical_axis) for f in natives]
axis_ref = axes[0]
for other_id, other_axis in axes[1:]:
if other_axis != axis_ref[1]:
raise ImportError_(
f"Sessions {axis_ref[0]!r} and {other_id!r} have different vertical axes, "
f"{axis_ref[1]!r} and {other_axis!r}; the project's water column is entered "
"on one axis",
code="NATIVE_3D_AXIS_MISMATCH",
subject=other_id,
remediation=f"Add it again with vertical_axis = {axis_ref[1]!r}, or add the "
"files to projects of their own.",
)
for other in natives[1:]:
if other.unit != first.unit:
raise ImportError_(
Expand Down
10 changes: 10 additions & 0 deletions track2data/readers/native3d.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
#: The ``target_unit`` option's default: the project length unit a file is converted to when the
#: user chose none.
DEFAULT_TARGET_UNIT = "cm"
DEFAULT_VERTICAL_AXIS = "z"
AXES: tuple[str, ...] = ("x", "y", "z")


Expand All @@ -53,6 +54,15 @@ def manifest_native_3d(manifest: Any) -> bool:
return any(ref.reader in NATIVE_3D_READERS for ref in manifest.sessions)


def ref_vertical_axis(ref: Any) -> str | None:
"""The vertical axis a native entry's file is read with, from its saved options (None for an
entry of another reader). Confirmed entries save only the options that were given, so a
missing one is the default."""
if ref.reader not in NATIVE_3D_READERS:
return None
return str(ref.reader_options.get("vertical_axis") or DEFAULT_VERTICAL_AXIS)


def ref_target_unit(ref: Any) -> str | None:
"""The unit a native entry's file is converted to, from its saved options (None for an entry
of another reader). Confirmed entries save only the options that were given, so a missing
Expand Down