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 files read with `vertical_axis = y` no longer have a mirrored horizontal plane.** The two axes that are not vertical were taken in file order, which for `y` gives `(x, z)`, the mirror image of the right-handed `(z, x)`. Distances, speeds and every magnitude were unaffected, but any signed quantity was reflected: **IL-11's `mean_heading_rad` (θ became π/2 − θ) and the sign of `left_right_turn_bias`** for such files. The plane is now taken in cyclic order after the vertical axis (`z`: x, y; `x`: y, z; `y`: z, x), so it is right-handed seen from above whichever axis is vertical. `vertical_axis = z` (the default) and `x` are unchanged; **only files read with `y` change**, and only those two signed values. `flip` still reverses the vertical axis alone, which also mirrors the view from above; that is a documented limit, not changed here.
- **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.
Expand Down
5 changes: 4 additions & 1 deletion docs/guide/USER_GUIDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -321,7 +321,10 @@ before relying on them.
`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`.
`z`: which axis of the file points up), `flip` (tick when it points down) and `keep_skeleton`. The
other two axes become the horizontal plane in cyclic order after the vertical one (`z`: x, y; `x`: y, z;
`y`: z, x), which keeps the plane right-handed seen from above, so headings and turn directions have the
same sense whichever axis the file calls up. `flip` reverses the vertical axis only.
- **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
Expand Down
3 changes: 2 additions & 1 deletion tests/test_readers/test_anipose.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,8 @@ def test_anipose_vertical_axis_and_flip(tmp_path: Path) -> None:
path = write_anipose_csv(tmp_path / "a.csv", ["a"], 2, xyz=xyz)
s = read(path, target_unit="mm", vertical_axis="y")
assert s.raw_z is not None
np.testing.assert_array_equal(s.raw_xy[:, 0, :], [[1, 3], [4, 6]])
# vertical y: the horizontal plane is (z, x), right-handed seen from above
np.testing.assert_array_equal(s.raw_xy[:, 0, :], [[3, 1], [6, 4]])
np.testing.assert_array_equal(s.raw_z[:, 0], [2, 5])
f = read(path, target_unit="mm", vertical_axis="y", flip=True)
assert f.raw_z is not None
Expand Down
3 changes: 2 additions & 1 deletion tests/test_readers/test_deeplabcut_3d.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,8 @@ def test_vertical_axis_and_flip(tmp_path: Path) -> None:
path = write_dlc3d_csv(tmp_path / "a.csv", ["a"], 2, xyz=xyz)
s = read(path, target_unit="mm", vertical_axis="y")
assert s.raw_z is not None and s.keypoints is not None
np.testing.assert_array_equal(s.raw_xy[:, 0, :], [[1, 3], [4, 6]])
# vertical y: the horizontal plane is (z, x), right-handed seen from above
np.testing.assert_array_equal(s.raw_xy[:, 0, :], [[3, 1], [6, 4]])
np.testing.assert_array_equal(s.raw_z[:, 0], [2, 5])
f = read(path, target_unit="mm", vertical_axis="y", flip=True)
assert f.raw_z is not None and f.keypoints is not None
Expand Down
36 changes: 33 additions & 3 deletions tests/test_readers/test_native3d.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,13 +36,43 @@ def test_convert_units_is_exact_for_common_cases() -> None:


def test_horizontal_axes() -> None:
# cyclic order after the vertical axis: x -> (y, z), y -> (z, x), z -> (x, y)
assert horizontal_axes("z") == (0, 1)
assert horizontal_axes("y") == (0, 2)
assert horizontal_axes("y") == (2, 0)
assert horizontal_axes("x") == (1, 2)
with pytest.raises(ValueError):
horizontal_axes("w")


@pytest.mark.parametrize("vertical", ["x", "y", "z"])
def test_the_horizontal_plane_is_right_handed_with_the_vertical_axis_up(vertical: str) -> None:
"""first x second = up, so a counterclockwise turn seen from above stays counterclockwise."""
first, second = horizontal_axes(vertical)
unit = np.eye(3)
np.testing.assert_array_equal(
np.cross(unit[first], unit[second]), unit["xyz".index(vertical)]
)


@pytest.mark.parametrize(
("vertical", "permutation"), [("z", (0, 1, 2)), ("x", (2, 0, 1)), ("y", (1, 2, 0))]
)
def test_a_proper_rotation_of_the_scene_leaves_the_horizontal_track_unchanged(
vertical: str, permutation: tuple[int, int, int]
) -> None:
"""The same physical track, with up on each axis in turn (cyclic permutations of the file
axes are proper rotations): the horizontal track the reader returns must not change, not
even by a mirror, or every signed heading and turn would."""
rng = np.random.default_rng(0)
base = rng.normal(size=(12, 1, 1, 3)) # (frames, animals, keypoints, xyz), z up
rotated = base[..., list(permutation)]
red, z = reduce_native(
rotated, ["a"], None, keypoint="a", cutoff=None, vertical_axis=vertical, flip=False
)
np.testing.assert_array_equal(red.raw_xy[:, 0, :], base[:, 0, 0, :2])
np.testing.assert_array_equal(z[:, 0], base[:, 0, 0, 2])


def test_native_parameters_order_and_requirements() -> None:
params = native_parameters("mm")
assert [p.name for p in params] == [
Expand Down Expand Up @@ -71,9 +101,9 @@ def test_reduce_native_picks_the_vertical_coordinate() -> None:
red, z = reduce_native(
xyz, ["a", "b"], None, keypoint="b", cutoff=None, vertical_axis="y", flip=True
)
np.testing.assert_array_equal(red.raw_xy[:, 0, :], xyz[:, 0, 1, [0, 2]])
np.testing.assert_array_equal(red.raw_xy[:, 0, :], xyz[:, 0, 1, [2, 0]])
np.testing.assert_array_equal(z[:, 0], -xyz[:, 0, 1, 1])
assert red.selection.plane == ("x", "z")
assert red.selection.plane == ("z", "x")


def _assemble(**over):
Expand Down
13 changes: 10 additions & 3 deletions track2data/readers/native3d.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,11 +89,18 @@ def convert_units(values: np.ndarray, unit: str, target: str) -> np.ndarray:


def horizontal_axes(vertical_axis: str) -> tuple[int, int]:
"""The two file axes that are not vertical, in file order."""
"""The two file axes that are not vertical, in cyclic order after the vertical one.

``z`` gives ``(x, y)``, ``x`` gives ``(y, z)`` and ``y`` gives ``(z, x)``. In that order the
first axis crossed with the second is the vertical axis, so the plane is right-handed seen
from above: a counterclockwise turn stays one, and the signed headings and turn directions
keep their sense whichever axis the file calls vertical. (File order would give ``(x, z)``
for ``y``, a mirror image.)
"""
if vertical_axis not in AXES:
raise ValueError(f"vertical_axis must be one of {list(AXES)}, got {vertical_axis!r}")
first, second = (i for i in range(3) if AXES[i] != vertical_axis)
return first, second
up = AXES.index(vertical_axis)
return (up + 1) % 3, (up + 2) % 3


def union_keypoints(keypoint_sets: Iterable[Sequence[str]]) -> tuple[str, ...]:
Expand Down