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 @@ -35,6 +35,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/).

### Fixed

- **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`).
- **The test run no longer crashes at exit, and runs about three times faster.** After every test had passed, the Qt
tests intermittently ended with "QObject: shared QObject was deleted directly" and a segfault (exit 139), which
failed CI on a green run. The cause was in the application, not the tests: PySide keeps a `lambda` or
Expand Down
58 changes: 57 additions & 1 deletion tests/real_samples/fixtures_manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -208,6 +208,62 @@
"licence": "GPL-3.0 (repository licence; data terms not stated separately)",
"attribution": "qpetitjean/MoveR_SampleData sample_1",
"group": "trex"
},
"idtrackerai_test_B.trajectories.h5": {
"url": "https://raw.githubusercontent.com/animovement/movement-data/f02a8a75369d610c497b509d93ac2444c142cbcb/data/idtrackerai/trajectories.h5",
"sha256": "ad1dc121580e79622d68b68003042b9ebdca4f37181d28d34af48ada60cdc53a",
"bytes": 110472,
"licence": "movement-data README: CC BY 4.0; upstream licence still to be confirmed with the contributor (metadata.yaml)",
"attribution": "Jordi Torrents via animovement/movement-data",
"group": "idtrackerai"
},
"idtrackerai_test_B.trajectories.csv": {
"url": "https://raw.githubusercontent.com/animovement/movement-data/f02a8a75369d610c497b509d93ac2444c142cbcb/data/idtrackerai/trajectories_csv/trajectories.csv",
"sha256": "c7384191e34f1adea2f08bf7a898bd4695942614508bc4dc0d518f13b9741be5",
"bytes": 67515,
"licence": "movement-data README: CC BY 4.0; upstream licence still to be confirmed with the contributor (metadata.yaml)",
"attribution": "Jordi Torrents via animovement/movement-data",
"group": "idtrackerai"
},
"idtrackerai_test_B.id_probabilities.csv": {
"url": "https://raw.githubusercontent.com/animovement/movement-data/f02a8a75369d610c497b509d93ac2444c142cbcb/data/idtrackerai/trajectories_csv/id_probabilities.csv",
"sha256": "5b9007d6960feeb7e19a3fcf9e0225a0c0b461b19f8c5208519720ba812370b5",
"bytes": 42316,
"licence": "movement-data README: CC BY 4.0; upstream licence still to be confirmed with the contributor (metadata.yaml)",
"attribution": "Jordi Torrents via animovement/movement-data",
"group": "idtrackerai"
},
"idtrackerai_test_B.attributes.json": {
"url": "https://raw.githubusercontent.com/animovement/movement-data/f02a8a75369d610c497b509d93ac2444c142cbcb/data/idtrackerai/trajectories_csv/attributes.json",
"sha256": "018b743a587a8c23fc7eea85cc95f5b4a29d69acbb4eaf19b28e1eaa102a23a2",
"bytes": 491,
"licence": "movement-data README: CC BY 4.0; upstream licence still to be confirmed with the contributor (metadata.yaml)",
"attribution": "Jordi Torrents via animovement/movement-data",
"group": "idtrackerai"
},
"idtrackerai_synthetic_no_fps.trajectories.csv": {
"url": "https://raw.githubusercontent.com/animovement/movement-data/f02a8a75369d610c497b509d93ac2444c142cbcb/data/idtrackerai/trajectories_csv_no_fps/trajectories.csv",
"sha256": "4e4c8312f20f5c4b14f0d86af509c0ceb1146c001af0a22ac6f51771bd18fe1c",
"bytes": 132,
"licence": "CC BY 4.0 (metadata.yaml upstream.license); synthetic",
"attribution": "Mikkel Roald-Arbol via animovement/movement-data",
"group": "idtrackerai"
},
"idtrackerai_synthetic_no_fps.id_probabilities.csv": {
"url": "https://raw.githubusercontent.com/animovement/movement-data/f02a8a75369d610c497b509d93ac2444c142cbcb/data/idtrackerai/trajectories_csv_no_fps/id_probabilities.csv",
"sha256": "ba3404b4f49134eafa14bffc3d166a9ac21295f6ced2b093aa8df73b46f42357",
"bytes": 116,
"licence": "CC BY 4.0 (metadata.yaml upstream.license); synthetic",
"attribution": "Mikkel Roald-Arbol via animovement/movement-data",
"group": "idtrackerai"
},
"MoveR_sample_1.IdTrackerOutput.2602_ISA3080_Low_5.npy": {
"url": "https://raw.githubusercontent.com/qpetitjean/MoveR_SampleData/50972de006d20f62da9064e43b1c2db70983735a/sample_1/IdTrackerOutput/2602_ISA3080_Low_5.npy",
"sha256": "35035d134f39d927b99e12cb4c6b7c49deb96f7d11aabc8f228d3ce867f82693",
"bytes": 3851211,
"licence": "GPL-3.0 (repo level; no separate data licence found)",
"attribution": "qpetitjean/MoveR_SampleData",
"group": "idtrackerai"
}
}
}
}
149 changes: 149 additions & 0 deletions tests/real_samples/test_idtrackerai_samples.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
"""Worked example: testing idtracker.ai sample datasets (rows `idtracker.ai` of tracker_test_datasets.csv)
in Track2Data. Place in tests/real_samples/ and merge fixtures_manifest_idtrackerai_additions.json into
fixtures_manifest.json first. Run: pytest tests/real_samples/test_idtrackerai_samples.py -m contract

What it asserts, and which handoff finding each test documents:
F1 flat folders are not claimed; the same files inside <session>/trajectories/ are
F2 no video width/height in the files -> IDT_DICT_MISSING_KEY unless session.json supplies it
F7 reader options (fps / width_px / height_px) supply what a bare export does not record
oracle tests: positions equal an independent read of the file; h5 and CSV exports of one session agree
F3 CSV without a time column keeps both animals (and their probabilities)
FR-IMP-5 reading does not modify the input folder
The session.json width/height below are PLACEHOLDERS for the two test_B exports (true video size not recorded in the
files); only the mechanics are being tested.
"""
from __future__ import annotations

import hashlib
import json
import shutil
from pathlib import Path

import h5py
import numpy as np
import pytest

from track2data.core.errors import DataValidationError, ImportError_
from track2data.readers import detect_reader, read_session

pytestmark = pytest.mark.contract

H5 = "idtrackerai_test_B.trajectories.h5"
CSV_T, CSV_P, CSV_A = ("idtrackerai_test_B.trajectories.csv", "idtrackerai_test_B.id_probabilities.csv",
"idtrackerai_test_B.attributes.json")
NF_T, NF_P = "idtrackerai_synthetic_no_fps.trajectories.csv", "idtrackerai_synthetic_no_fps.id_probabilities.csv"
NPY = "MoveR_sample_1.IdTrackerOutput.2602_ISA3080_Low_5.npy"
SIZE_PLACEHOLDER = {"width": 1000, "height": 1000}


def _arrange(tmp: Path, name: str, files: list[tuple[str, str]], fx, session_json: dict | None = None) -> Path:
root = tmp / name
for fixture, dest in files:
target = root / dest
target.parent.mkdir(parents=True, exist_ok=True)
shutil.copy(fx(fixture), target)
if session_json is not None:
(root / "session.json").write_text(json.dumps(session_json))
return root


def _h5(tmp, fx, size=True):
return _arrange(tmp, "h5", [(H5, "trajectories/trajectories.h5")], fx, SIZE_PLACEHOLDER if size else None)


def _csv(tmp, fx, size=True):
d = "trajectories/trajectories_csv/"
return _arrange(tmp, "csv", [(CSV_T, d + "trajectories.csv"), (CSV_P, d + "id_probabilities.csv"),
(CSV_A, d + "attributes.json")], fx, SIZE_PLACEHOLDER if size else None)


def _tree_hash(root: Path) -> str:
digest = hashlib.sha256()
for path in sorted(p for p in root.rglob("*") if p.is_file()):
digest.update(path.relative_to(root).as_posix().encode())
digest.update(path.read_bytes())
return digest.hexdigest()


# --- F1: layout -------------------------------------------------------------------------------
def test_flat_folder_is_not_claimed(tmp_path, fx):
root = _arrange(tmp_path, "flat", [(H5, "trajectories.h5")], fx, SIZE_PLACEHOLDER)
assert detect_reader(root) is None


@pytest.mark.parametrize("build", [_h5, _csv], ids=["h5", "csv"])
def test_session_style_folder_is_claimed_by_the_idtrackerai_reader(tmp_path, fx, build):
reader = detect_reader(build(tmp_path, fx))
assert reader is not None and reader.name == "idtrackerai"


# --- F2 / F7: video size ------------------------------------------------------------------------
@pytest.mark.parametrize("build", [_h5, _csv], ids=["h5", "csv"])
def test_missing_video_size_is_refused_with_a_coded_error(tmp_path, fx, build):
with pytest.raises(DataValidationError) as err:
read_session(build(tmp_path, fx, size=False))
assert err.value.code == "IDT_DICT_MISSING_KEY" and err.value.subject == "width"


def test_reader_options_supply_the_video_size_a_bare_export_lacks(tmp_path, fx):
session = read_session(_h5(tmp_path, fx, size=False), options={"width_px": 1000, "height_px": 1000})
assert (session.video.width_px, session.video.height_px) == (1000, 1000)
assert session.video.fps == 28.0 # recorded in the file; options only fill gaps


# --- oracle tests -------------------------------------------------------------------------------
def test_h5_positions_equal_an_independent_read(tmp_path, fx):
session = read_session(_h5(tmp_path, fx))
with h5py.File(fx(H5), "r") as handle:
expected = handle["trajectories"][:]
fps = float(handle.attrs["frames_per_second"])
assert session.raw_xy.shape == expected.shape == (508, 8, 2)
np.testing.assert_array_equal(session.raw_xy, expected) # NaN positions compare equal
assert session.video.fps == fps == 28.0 and session.n_animals == 8


def test_csv_export_agrees_with_the_h5_export_of_the_same_session(tmp_path, fx):
from_h5 = read_session(_h5(tmp_path, fx))
from_csv = read_session(_csv(tmp_path, fx))
assert np.array_equal(np.isnan(from_h5.raw_xy), np.isnan(from_csv.raw_xy))
np.testing.assert_allclose(from_csv.raw_xy, from_h5.raw_xy, atol=6e-4, equal_nan=True) # CSV keeps 3 decimals
assert from_csv.video.fps == from_h5.video.fps == 28.0
assert from_csv.id_probabilities.shape == from_h5.id_probabilities.shape == (508, 8)


# --- pickled dict (MoveR sample) ------------------------------------------------------------------
def _npy(tmp, fx):
return _arrange(tmp, "npy", [(NPY, "trajectories/trajectories.npy")], fx, {"width": 3840, "height": 2160})


def test_pickled_dict_is_refused_without_consent(tmp_path, fx):
with pytest.raises(ImportError_) as err:
read_session(_npy(tmp_path, fx))
assert "IDT_PICKLE_REFUSED" in str(err.value)


def test_pickled_dict_positions_with_consent_equal_an_independent_read(tmp_path, fx):
# The fixture is sha256-pinned and its pickle opcodes reference numpy only, so loading it here is safe.
expected = np.load(fx(NPY), allow_pickle=True).item()
session = read_session(_npy(tmp_path, fx), allow_pickle=True)
np.testing.assert_array_equal(session.raw_xy, expected["trajectories"])
assert session.raw_xy.shape == (12033, 20, 2) and session.video.fps == 25.0


# --- F3: CSV without a time column ------------------------------------------------------------------
def test_csv_without_time_column_keeps_both_animals(tmp_path, fx):
d = "trajectories/trajectories_csv/"
root = _arrange(tmp_path, "nofps", [(NF_T, d + "trajectories.csv"), (NF_P, d + "id_probabilities.csv")], fx,
{**SIZE_PLACEHOLDER, "frames_per_second": 28})
session = read_session(root)
assert session.raw_xy.shape == (4, 2, 2)
assert session.id_probabilities.shape == session.raw_xy.shape[:2]


# --- FR-IMP-5 -------------------------------------------------------------------------------------------
@pytest.mark.parametrize("build", [_h5, _csv], ids=["h5", "csv"])
def test_reading_does_not_modify_the_input_folder(tmp_path, fx, build):
root = build(tmp_path, fx)
before = _tree_hash(root)
read_session(root)
assert _tree_hash(root) == before
89 changes: 89 additions & 0 deletions tests/test_readers/idtrackerai/test_csv_no_time_column.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
"""An idtracker.ai CSV written without a time column (frame rate unknown) must load.

idtracker.ai 6.0.15 omits the leading time column when the video's frame rate cannot be read.
The column count settles it: 2k columns are k animals' x,y; 2k+1 columns carry a leading time.
Data modelled on animovement/movement-data ``trajectories_csv_no_fps`` (CC BY 4.0).
"""

from __future__ import annotations

import json
from pathlib import Path

import numpy as np
import pytest

from track2data.core.errors import DataValidationError
from track2data.readers import read_session
from track2data.readers.idtrackerai.formats.csv_bundle import load_csv_bundle

TRAJ = (
"x1,y1,x2,y2\n853.333,173.355,879.044,323.819\n854.101,174.002,878.512,324.660\n"
"855.020,174.871,nan,nan\n855.874,175.530,877.230,326.101\n"
)
PROB = (
"id_probabilities1,id_probabilities2\n1.000e+00,9.980e-01\n1.000e+00,9.970e-01\n"
"1.000e+00,nan\n1.000e+00,9.950e-01\n"
)
TRAJ_T = "seconds," + TRAJ.replace("\n", "\n", 1)
TRAJ_T = "seconds,x1,y1,x2,y2\n" + "".join(
f"{i / 28:.3f},{line}\n" for i, line in enumerate(TRAJ.splitlines()[1:])
)
PROB_T = "seconds,id_probabilities1,id_probabilities2\n" + "".join(
f"{i / 28:.3f},{line}\n" for i, line in enumerate(PROB.splitlines()[1:])
)


def _bundle(root: Path, traj: str, prob: str | None) -> Path:
d = root / "trajectories" / "trajectories_csv"
d.mkdir(parents=True)
(d / "trajectories.csv").write_text(traj)
if prob is not None:
(d / "id_probabilities.csv").write_text(prob)
return d


def test_loader_keeps_both_animals_without_a_time_column(tmp_path: Path) -> None:
out = load_csv_bundle(_bundle(tmp_path, TRAJ, PROB))
assert out["trajectories"].shape == (4, 2, 2)
np.testing.assert_allclose(out["trajectories"][0], [[853.333, 173.355], [879.044, 323.819]])
assert out["id_probabilities"].shape == (4, 2)
assert out["id_probabilities"][0, 0] == pytest.approx(1.0)


def test_loader_still_drops_a_leading_time_column(tmp_path: Path) -> None:
out = load_csv_bundle(_bundle(tmp_path, TRAJ_T, PROB_T))
assert out["trajectories"].shape == (4, 2, 2)
np.testing.assert_allclose(out["trajectories"][0], [[853.333, 173.355], [879.044, 323.819]])
assert out["id_probabilities"].shape == (4, 2)


def test_time_column_in_one_file_only_is_handled_per_file(tmp_path: Path) -> None:
out = load_csv_bundle(_bundle(tmp_path, TRAJ, PROB_T))
assert out["trajectories"].shape == (4, 2, 2)
assert out["id_probabilities"].shape == (4, 2)


def test_probability_columns_that_fit_no_animal_count_are_a_coded_error(tmp_path: Path) -> None:
bad = "p1,p2,p3,p4,p5\n" + "1,1,1,1,1\n" * 4
with pytest.raises(DataValidationError) as err:
load_csv_bundle(_bundle(tmp_path, TRAJ, bad))
assert err.value.code == "IDT_SHAPE_MISMATCH"


def test_probability_row_count_mismatch_is_a_coded_error(tmp_path: Path) -> None:
short = "id_probabilities1,id_probabilities2\n1,1\n1,1\n"
with pytest.raises(DataValidationError) as err:
load_csv_bundle(_bundle(tmp_path, TRAJ, short))
assert err.value.code == "IDT_SHAPE_MISMATCH"


def test_session_reads_two_animals_when_size_and_fps_are_supplied(tmp_path: Path) -> None:
_bundle(tmp_path, TRAJ, PROB)
(tmp_path / "session.json").write_text(
json.dumps({"width": 1000, "height": 1000, "frames_per_second": 28})
)
session = read_session(tmp_path)
assert session.raw_xy.shape == (4, 2, 2)
assert session.id_probabilities is not None
assert session.id_probabilities.shape == (4, 2)
31 changes: 31 additions & 0 deletions tests/test_readers/idtrackerai/test_normaliser.py
Original file line number Diff line number Diff line change
Expand Up @@ -525,3 +525,34 @@ def test_known_keys_not_in_raw_attrs(self, tmp_path: Path) -> None:
assert "id_probabilities" not in s.raw_attrs
# Unknown key is captured
assert "some_future_key" in s.raw_attrs


class TestIdProbabilityShape:
"""F4: a probability array that disagrees with the trajectories must not pass silently."""

def test_wrong_animal_count_is_refused(self) -> None:
import numpy as np

from track2data.core.errors import DataValidationError
from track2data.readers.idtrackerai.normaliser import Normaliser

with pytest.raises(DataValidationError) as err:
Normaliser._normalise_id_probabilities(np.ones((4, 1)), 4, 2)
assert err.value.code == "IDT_SHAPE_MISMATCH"

def test_wrong_frame_count_is_refused(self) -> None:
import numpy as np

from track2data.core.errors import DataValidationError
from track2data.readers.idtrackerai.normaliser import Normaliser

with pytest.raises(DataValidationError):
Normaliser._normalise_id_probabilities(np.ones((3, 2)), 4, 2)

def test_matching_shape_and_trailing_singleton_pass(self) -> None:
import numpy as np

from track2data.readers.idtrackerai.normaliser import Normaliser

assert Normaliser._normalise_id_probabilities(np.ones((4, 2)), 4, 2).shape == (4, 2)
assert Normaliser._normalise_id_probabilities(np.ones((4, 2, 1)), 4, 2).shape == (4, 2)
Loading