Skip to content

Commit 41b524e

Browse files
authored
Merge pull request #157 from mbel-tech/fatina-del-codice/sp5-item1-water-column-mask
2 parents 384f25c + 9f1b25e commit 41b524e

6 files changed

Lines changed: 137 additions & 18 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/).
4343

4444
### Fixed
4545

46+
- **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.
4647
- **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.
4748
- **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.
4849
- **idtracker.ai bare exports.** A CSV bundle written without a time column (idtracker.ai omits it when the frame rate is unknown) no longer crashes with a bare `ValueError`: the column count decides whether a leading time column is present, for `trajectories.csv` and `id_probabilities.csv` alike. `id_probabilities` that do not match the trajectories (frames or animals) are now refused with `IDT_SHAPE_MISMATCH` instead of passing silently. The idtracker.ai reader gains optional `fps`, `width_px` and `height_px` options for exports that record no video size or frame rate; they fill gaps only, behind the trajectory file and `session.json`. A folder whose only trajectory format is a pickle and has no consent now fails with `IDT_PICKLE_REFUSED` (was `IDT_FORMAT_AMBIGUOUS`). `track2data add --option fps=... --option width_px=... --option height_px=...` now works for idtracker.ai (the reader's detection carried no options, so the CLI and the confirm dialog rejected them). New `track2data add --allow-pickle` records consent for pickled trajectories on the project. `track2data validate` now also opens each session and reports what a run would fail on (missing video size or frame rate, pickle without consent), even when no metric is selected. A bare export that lacks the frame rate and the video size now gets one error naming every missing field (also from `validate`), and `scan` explains a loose idtracker.ai export outside a `trajectories/` folder. The run README gains a **Units** note (why `*_cm` columns are empty under body-length calibration), lists the reader options the user supplied, and lists identity slots that are more than 90% missing; `IDT_VERSION_UNKNOWN` is information for 4.x files. The README also gains a **Columns with no values** section that lists every metric column that is entirely NaN with the reason (for example the fragment diagnostics D-7 to D-9, D-13 and D-14 need `list_of_fragments.json`, which a bare export lacks). A pickle refused for lack of consent now also says that pickled files usually record no video size, so the size options can be given in the same step.

‎tests/test_integration/test_native_3d.py‎

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -230,13 +230,18 @@ def test_il15_with_the_water_column_counts_the_outside_values(
230230
assert _value(two, "IL-15", "mean_depth_fraction") == pytest.approx(0.74, abs=1e-9)
231231
assert _value(two, "IL-15", "mean_depth_cm") == pytest.approx(14.8, abs=1e-9)
232232
assert _value(two, "IL-15", "frac_outside_extent") == pytest.approx(2 / 11, abs=1e-12)
233-
assert _value(two, "IL-16", "path_length_3d_cm") == pytest.approx(PATH_CM, abs=1e-9)
234-
# the speed uses the absolute z, so outside-the-column frames keep their 3-D speed
233+
# the water column also bounds the 3-D metrics: the two frames below the floor are out of the
234+
# path (8 of the 10 steps remain, 1.3 cm each) and have no speed; the rest is unchanged
235+
assert _value(two, "IL-16", "path_length_3d_cm") == pytest.approx(8 * STEP_CM, abs=1e-9)
235236
assert _value(two, "IL-17", "mean_speed_3d_cm_s") == pytest.approx(SPEED_CM_S, abs=1e-9)
237+
assert _value(two, "IL-17", "max_speed_3d_cm_s") == pytest.approx(SPEED_CM_S, abs=1e-9)
238+
# fish1 has nothing outside, so it keeps the full path
239+
assert _value(one, "IL-16", "path_length_3d_cm") == pytest.approx(PATH_CM, abs=1e-9)
236240
frames = pd.read_csv(tmp_path / "o" / "fish2" / "master_fish_by_frame.csv")
237241
depth = frames["depth_fraction"].to_numpy()
238242
assert np.isnan(depth[9:]).all() and np.isfinite(depth[:9]).all()
239-
assert "z" not in frames.columns
243+
# the exported z_cm is the file's own coordinate, outside samples included
244+
np.testing.assert_allclose(frames["z_cm"].to_numpy()[9:], [20.8, 22.0], atol=1e-9)
240245

241246

242247
def test_a_reversed_water_column_gives_the_same_depth_cm(project: Path, tmp_path: Path) -> None:
Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
"""The water column bounds z for every 3-D metric, not only IL-15."""
2+
3+
from __future__ import annotations
4+
5+
import numpy as np
6+
import pytest
7+
8+
from tests.test_api import _make_psess, _make_session
9+
from track2data.calibration.water_column import apply_water_column
10+
from track2data.core.models import WaterColumn
11+
from track2data.metrics.geometry3d import positions_cm, vertical_cm
12+
from track2data.metrics.group import NearestNeighbourDistance3D
13+
from track2data.metrics.individual import PathLength3D, Speed3D
14+
15+
PX_PER_CM = 10.0
16+
17+
18+
def _native(z, *, column: WaterColumn | None = None, n_animals: int = 1):
19+
"""A native 3-D psess: x = 3 cm/frame, y = 4 cm/frame, z as given, 10 px/cm."""
20+
z = np.asarray(z, dtype=float)
21+
n = z.shape[0]
22+
z = np.broadcast_to(z.reshape(n, 1), (n, n_animals)).copy()
23+
psess = _make_psess(_make_session(n_frames=n, n_animals=n_animals))
24+
t = np.arange(n, dtype=float)[:, None]
25+
psess.xy = np.stack(
26+
[np.broadcast_to(3.0 * t * PX_PER_CM, (n, n_animals)),
27+
np.broadcast_to(4.0 * t * PX_PER_CM, (n, n_animals))],
28+
axis=-1,
29+
)
30+
psess.px_per_cm = PX_PER_CM
31+
psess.z = z
32+
return apply_water_column(psess, column) if column is not None else psess
33+
34+
35+
def test_vertical_cm_is_z_when_there_is_no_water_column() -> None:
36+
psess = _native([0.0, 1.0, 5.0, 2.0])
37+
np.testing.assert_array_equal(vertical_cm(psess)[:, 0], [0.0, 1.0, 5.0, 2.0])
38+
39+
40+
def test_vertical_cm_drops_samples_outside_the_water_column() -> None:
41+
psess = _native([0.0, 1.0, 5.0, 2.0], column=WaterColumn(surface_z=0.0, floor_z=3.0))
42+
np.testing.assert_array_equal(vertical_cm(psess)[:, 0], [0.0, 1.0, np.nan, 2.0])
43+
# the stored z is the data and is not modified
44+
np.testing.assert_array_equal(psess.z[:, 0], [0.0, 1.0, 5.0, 2.0])
45+
46+
47+
def test_vertical_cm_of_a_fused_session_is_depth_times_height() -> None:
48+
psess = _make_psess(_make_session(n_frames=3, n_animals=1))
49+
psess.depth = np.array([[0.1], [0.5], [np.nan]])
50+
psess.depth_height_cm = 20.0
51+
np.testing.assert_allclose(vertical_cm(psess)[:, 0], [2.0, 10.0, np.nan])
52+
53+
54+
def test_vertical_cm_is_none_without_a_vertical_coordinate() -> None:
55+
assert vertical_cm(_make_psess(_make_session(n_frames=3, n_animals=1))) is None
56+
57+
58+
def test_positions_cm_has_no_position_where_z_is_outside_the_column() -> None:
59+
psess = _native([0.0, 1.0, 5.0, 2.0], column=WaterColumn(surface_z=0.0, floor_z=3.0))
60+
pos = positions_cm(psess)
61+
assert np.isnan(pos[2]).all() and np.isfinite(pos[[0, 1, 3]]).all()
62+
63+
64+
def test_il16_leaves_out_every_step_touching_an_outside_sample() -> None:
65+
# steps: 0->1 (3,4,1) = 5.099, 1->2 and 2->3 touch the outside sample, so only one is valid
66+
inside = _native([0.0, 1.0, 5.0, 2.0], column=WaterColumn(surface_z=0.0, floor_z=3.0))
67+
row = PathLength3D().compute(inside).iloc[0]
68+
assert row["n_valid_steps"] == 1
69+
assert row["path_length_3d_cm"] == pytest.approx(np.sqrt(9 + 16 + 1))
70+
71+
72+
def test_il16_is_unchanged_when_the_column_contains_every_sample() -> None:
73+
z = [0.0, 1.0, 5.0, 2.0]
74+
plain = PathLength3D().compute(_native(z)).iloc[0]
75+
wide = PathLength3D().compute(
76+
_native(z, column=WaterColumn(surface_z=0.0, floor_z=10.0))
77+
).iloc[0]
78+
assert plain["path_length_3d_cm"] == wide["path_length_3d_cm"]
79+
assert plain["n_valid_steps"] == wide["n_valid_steps"] == 3
80+
81+
82+
def test_il17_has_no_speed_where_z_is_outside_the_column() -> None:
83+
z = [0.0, 1.0, 5.0, 2.0, 3.0, 2.0, 1.0]
84+
column = WaterColumn(surface_z=0.0, floor_z=3.0)
85+
with_column = Speed3D().compute(_native(z, column=column)).iloc[0]
86+
without = Speed3D().compute(_native(z)).iloc[0]
87+
assert with_column["max_speed_3d_cm_s"] < without["max_speed_3d_cm_s"] # the spike is gone
88+
assert np.isfinite(with_column["mean_speed_3d_cm_s"])
89+
90+
91+
def test_gl16_leaves_out_frames_with_an_animal_outside_the_column() -> None:
92+
column = WaterColumn(surface_z=0.0, floor_z=3.0)
93+
psess = _native([0.0, 1.0, 5.0, 2.0], column=column, n_animals=2)
94+
psess.xy[:, 1] += 50.0 # separate the two animals in the horizontal plane
95+
row = NearestNeighbourDistance3D().compute(psess).iloc[0]
96+
assert row["n_skipped_frames_3d"] == 1
97+
assert row["frac_frames_used_3d"] == pytest.approx(0.75)

‎track2data/metrics/geometry3d.py‎

Lines changed: 25 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -14,22 +14,40 @@
1414
from track2data.core.models import PreprocessedSession
1515

1616

17+
def vertical_cm(psess: PreprocessedSession) -> np.ndarray | None:
18+
"""``(n_frames, n_animals)`` vertical coordinate in cm that the 3-D metrics use, or None.
19+
20+
A native 3-D session's ``psess.z`` (already absolute, in the project's length unit) with the
21+
samples that fall outside the water column set to NaN: the column that bounds IL-15's depth
22+
bounds the path length and the speed too, so a mis-triangulated or out-of-tank sample is out
23+
of every 3-D metric alike. Nothing is clipped, and ``psess.z`` itself is not modified (the
24+
exported ``z_cm`` is the file's own coordinate). Without a water column the whole z is used.
25+
A fused session has ``depth * depth_height_cm``, which is already NaN outside the column.
26+
None when there is neither a ``z`` nor a ``depth`` with its ``depth_height_cm``.
27+
"""
28+
if psess.z is not None:
29+
z = np.array(psess.z, dtype=np.float64)
30+
if psess.depth_outside_mask is not None:
31+
z[np.asarray(psess.depth_outside_mask, dtype=bool)] = np.nan
32+
return z
33+
if psess.depth is not None and psess.depth_height_cm is not None:
34+
return np.asarray(psess.depth, dtype=np.float64) * float(psess.depth_height_cm)
35+
return None
36+
37+
1738
def positions_cm(psess: PreprocessedSession) -> np.ndarray | None:
1839
"""``(n_frames, n_animals, 3)`` float64 ``(X, Y, Z)`` in cm, or None without a 3-D scale.
1940
20-
``X = x_px / px_per_cm``, ``Y = y_px / px_per_cm``. ``Z`` is ``psess.z`` when the session
21-
carries an absolute z (a native 3-D file), else ``depth * depth_height_cm``. A position is
41+
``X = x_px / px_per_cm``, ``Y = y_px / px_per_cm``. ``Z`` is :func:`vertical_cm` (a native
42+
3-D file's absolute z inside its water column, else ``depth * depth_height_cm``). A position is
2243
NaN in every component where any of the three is NaN (a step or a frame needs all three).
2344
None when ``px_per_cm`` is missing, or when there is neither a ``z`` nor a ``depth`` with
2445
its ``depth_height_cm``.
2546
"""
2647
if psess.px_per_cm is None:
2748
return None
28-
if psess.z is not None:
29-
z = np.asarray(psess.z, dtype=np.float64)
30-
elif psess.depth is not None and psess.depth_height_cm is not None:
31-
z = np.asarray(psess.depth, dtype=np.float64) * float(psess.depth_height_cm)
32-
else:
49+
z = vertical_cm(psess)
50+
if z is None:
3351
return None
3452
xy = np.asarray(psess.xy, dtype=np.float64)
3553
pos = np.empty((*xy.shape[:2], 3), dtype=np.float64)

‎track2data/metrics/individual.py‎

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717
from track2data.core.models import PreprocessedSession
1818
from track2data.metrics.base import Metric, MetricDocumentation, MetricParameter
1919
from track2data.metrics.bouts import compute_bout_criterion_interval
20-
from track2data.metrics.geometry3d import body_length_cm, positions_cm
20+
from track2data.metrics.geometry3d import body_length_cm, positions_cm, vertical_cm
2121
from track2data.metrics.references import (
2222
BENHAMOU_2004,
2323
BENHAMOU_2013,
@@ -2017,12 +2017,8 @@ def compute(self, session: PreprocessedSession, cfg: dict | None = None) -> pd.D
20172017
from track2data.preprocess.kinematics import compute_kinematics
20182018

20192019
speed_3d: np.ndarray | None = None
2020-
height, scale = session.depth_height_cm, session.px_per_cm
2021-
z_cm: np.ndarray | None = None
2022-
if session.z is not None: # a native 3-D file: z is already absolute, in the project unit
2023-
z_cm = np.asarray(session.z, dtype=np.float64)
2024-
elif session.depth is not None and height is not None:
2025-
z_cm = np.asarray(session.depth, dtype=np.float64) * float(height)
2020+
scale = session.px_per_cm
2021+
z_cm = vertical_cm(session) # inside the water column when one is set
20262022
if z_cm is not None and scale is not None:
20272023
kcfg = KinematicsCfg.model_validate((cfg or {}).get("kinematics") or {})
20282024
z = z_cm

‎ui/calibration_screen.py‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -351,7 +351,9 @@ def _build_ui(self) -> None:
351351
water_help = QLabel(
352352
"Where the water surface and the floor lie on the file's vertical axis. Depth "
353353
"(0 at the surface, 1 at the floor) and the vertical-position metrics need both. "
354-
"Leave one empty for none."
354+
"Samples outside the column are left out of those metrics and also of the 3-D path "
355+
"length, speed and nearest-neighbour distance; they are never clipped. Leave one "
356+
"empty for none."
355357
)
356358
water_help.setProperty("role", "muted")
357359
water_help.setWordWrap(True)

0 commit comments

Comments
 (0)