From c4153484d763c3b556cb0740a064484905e23fae Mon Sep 17 00:00:00 2001 From: mbel-tech Date: Sun, 11 Oct 2026 12:00:17 +0200 Subject: [PATCH] fix(idtrackerai): CSV without time column, probability shape check, video-info options - csv_bundle: column parity decides whether a leading time column exists (F3); id_probabilities follow the trajectories' animal count, mismatches raise IDT_SHAPE_MISMATCH - normaliser: id_probabilities shape is checked against (n_frames, n_animals) (F4) - reader: optional fps/width_px/height_px options fill gaps behind file and session.json (F7) - reader: pickle-only folder without consent raises IDT_PICKLE_REFUSED (F5) - tests: offline regression tests; real-sample idtracker.ai fixtures and tests (7 pinned files) Co-Authored-By: Claude Sonnet 5.5 --- CHANGELOG.md | 1 + tests/real_samples/fixtures_manifest.json | 58 ++++++- .../real_samples/test_idtrackerai_samples.py | 149 ++++++++++++++++++ .../idtrackerai/test_csv_no_time_column.py | 89 +++++++++++ .../idtrackerai/test_normaliser.py | 31 ++++ .../idtrackerai/test_video_info_options.py | 60 +++++++ tests/test_readers/test_pickle_gate.py | 2 +- .../readers/idtrackerai/formats/csv_bundle.py | 38 ++++- track2data/readers/idtrackerai/normaliser.py | 32 +++- track2data/readers/idtrackerai/reader.py | 68 +++++++- 10 files changed, 505 insertions(+), 23 deletions(-) create mode 100644 tests/real_samples/test_idtrackerai_samples.py create mode 100644 tests/test_readers/idtrackerai/test_csv_no_time_column.py create mode 100644 tests/test_readers/idtrackerai/test_video_info_options.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 27cf52fa..ecc9bb69 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/tests/real_samples/fixtures_manifest.json b/tests/real_samples/fixtures_manifest.json index 4da25509..de47faa2 100644 --- a/tests/real_samples/fixtures_manifest.json +++ b/tests/real_samples/fixtures_manifest.json @@ -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" } } -} \ No newline at end of file +} diff --git a/tests/real_samples/test_idtrackerai_samples.py b/tests/real_samples/test_idtrackerai_samples.py new file mode 100644 index 00000000..39ffe270 --- /dev/null +++ b/tests/real_samples/test_idtrackerai_samples.py @@ -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 /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 diff --git a/tests/test_readers/idtrackerai/test_csv_no_time_column.py b/tests/test_readers/idtrackerai/test_csv_no_time_column.py new file mode 100644 index 00000000..2653bf63 --- /dev/null +++ b/tests/test_readers/idtrackerai/test_csv_no_time_column.py @@ -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) diff --git a/tests/test_readers/idtrackerai/test_normaliser.py b/tests/test_readers/idtrackerai/test_normaliser.py index da402efa..7244d425 100644 --- a/tests/test_readers/idtrackerai/test_normaliser.py +++ b/tests/test_readers/idtrackerai/test_normaliser.py @@ -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) diff --git a/tests/test_readers/idtrackerai/test_video_info_options.py b/tests/test_readers/idtrackerai/test_video_info_options.py new file mode 100644 index 00000000..2a4ced0c --- /dev/null +++ b/tests/test_readers/idtrackerai/test_video_info_options.py @@ -0,0 +1,60 @@ +"""A bare idtracker.ai export records no video size; the reader takes it as options (F2/F7). + +Precedence is trajectory file, then session.json, then the options: the options fill gaps and +never override what the tracker itself recorded. +""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest + +from track2data.core.errors import DataValidationError, ImportError_ +from track2data.readers import IDTrackerAiReader, read_session + +TRAJ = "x1,y1,x2,y2\n1,2,3,4\n2,3,4,5\n3,4,5,6\n" +OPTS = {"width_px": 640, "height_px": 480, "fps": 25.0} + + +def _bare(root: Path) -> Path: + d = root / "trajectories" / "trajectories_csv" + d.mkdir(parents=True) + (d / "trajectories.csv").write_text(TRAJ) + return root + + +def test_reader_declares_optional_video_info_options() -> None: + by_name = {p.name: p for p in IDTrackerAiReader.parameters} + assert {"fps", "width_px", "height_px"} <= set(by_name) + assert not any(by_name[n].required for n in ("fps", "width_px", "height_px")) + + +def test_options_supply_a_missing_video_size_and_fps(tmp_path: Path) -> None: + session = read_session(_bare(tmp_path), options=OPTS) + assert (session.video.width_px, session.video.height_px) == (640, 480) + assert session.video.fps == 25.0 + + +def test_without_options_or_session_json_it_is_still_refused(tmp_path: Path) -> None: + with pytest.raises(DataValidationError) as err: + read_session(_bare(tmp_path)) + assert err.value.code == "IDT_DICT_MISSING_KEY" + assert "option 'fps'" in (err.value.remediation or "") + + +def test_session_json_wins_over_options(tmp_path: Path) -> None: + root = _bare(tmp_path) + (root / "session.json").write_text( + json.dumps({"width": 1000, "height": 900, "frames_per_second": 30}) + ) + session = read_session(root, options=OPTS) + assert (session.video.width_px, session.video.height_px) == (1000, 900) + assert session.video.fps == 30.0 + + +def test_an_invalid_option_is_refused(tmp_path: Path) -> None: + with pytest.raises(ImportError_) as err: + read_session(_bare(tmp_path), options={**OPTS, "width_px": 0}) + assert err.value.code == "READER_OPTION_INVALID" diff --git a/tests/test_readers/test_pickle_gate.py b/tests/test_readers/test_pickle_gate.py index b2a3982a..3419217d 100644 --- a/tests/test_readers/test_pickle_gate.py +++ b/tests/test_readers/test_pickle_gate.py @@ -132,7 +132,7 @@ def test_reader_refuses_a_pickle_only_folder( with pytest.raises(ImportError_) as exc: read_session(folder) - assert exc.value.code == "IDT_FORMAT_AMBIGUOUS" + assert exc.value.code == "IDT_PICKLE_REFUSED" # The message has to name consent as the cause, or the user is left # thinking their file is corrupt. assert "IDT_PICKLE_REFUSED" in str(exc.value) diff --git a/track2data/readers/idtrackerai/formats/csv_bundle.py b/track2data/readers/idtrackerai/formats/csv_bundle.py index 9c2300ef..28ca0ae3 100644 --- a/track2data/readers/idtrackerai/formats/csv_bundle.py +++ b/track2data/readers/idtrackerai/formats/csv_bundle.py @@ -23,6 +23,17 @@ from track2data.core.errors import ImportError_ +def _shape_error(message: str, subject: str) -> ImportError_: + return ImportError_( + message, + code="IDT_SHAPE_MISMATCH", + severity="error", + subject=subject, + remediation="Re-export the session, or check that trajectories.csv and " + "id_probabilities.csv come from the same run.", + ) + + def load_csv_bundle(csv_dir: Path) -> dict[str, Any]: """ Read the trajectories_csv/ directory and return a normaliser-ready dict. @@ -52,26 +63,37 @@ def load_csv_bundle(csv_dir: Path) -> dict[str, Any]: remediation="The CSV bundle must contain at least trajectories.csv.", ) - # Load trajectories: first column = frame index, remaining = x_1, y_1, x_2, y_2, … + # Load trajectories: x_1, y_1, x_2, y_2, ... with an optional leading time column. + # idtracker.ai omits that column when it could not read the video's frame rate, so the + # column count decides: 2k columns are k animals, 2k+1 carry a leading time/frame column. traj_data = np.genfromtxt(traj_csv, delimiter=",", skip_header=1) if traj_data.ndim == 1: traj_data = traj_data.reshape(1, -1) - n_frames = traj_data.shape[0] - xy_cols = traj_data[:, 1:] # drop frame column - # Reshape (N, M*2) → (N, M, 2) - n_coord_cols = xy_cols.shape[1] - n_animals = n_coord_cols // 2 + n_frames, n_cols = traj_data.shape + xy_cols = traj_data[:, 1:] if n_cols % 2 == 1 else traj_data + if xy_cols.shape[1] == 0: + raise _shape_error(f"{traj_csv.name} holds no coordinate columns.", str(traj_csv)) + n_animals = xy_cols.shape[1] // 2 + # Reshape (N, M*2) -> (N, M, 2) trajectories = xy_cols.reshape(n_frames, n_animals, 2) payload: dict[str, Any] = {"trajectories": trajectories} - # id_probabilities.csv + # id_probabilities.csv: one column per animal, same optional leading time column. prob_csv = csv_dir / "id_probabilities.csv" if prob_csv.exists(): prob_data = np.genfromtxt(prob_csv, delimiter=",", skip_header=1) if prob_data.ndim == 1: prob_data = prob_data.reshape(1, -1) - payload["id_probabilities"] = prob_data[:, 1:] # drop frame column → (N, M) + if prob_data.shape[1] == n_animals + 1: + prob_data = prob_data[:, 1:] + if prob_data.shape != (n_frames, n_animals): + raise _shape_error( + f"{prob_csv.name} has shape {prob_data.shape} but {traj_csv.name} holds " + f"{n_frames} frames of {n_animals} animals.", + str(prob_csv), + ) + payload["id_probabilities"] = prob_data # attributes.json — merge into payload (provides version, fps, etc.) attr_file = csv_dir / "attributes.json" diff --git a/track2data/readers/idtrackerai/normaliser.py b/track2data/readers/idtrackerai/normaliser.py index dc87d1b9..69d2c56b 100644 --- a/track2data/readers/idtrackerai/normaliser.py +++ b/track2data/readers/idtrackerai/normaliser.py @@ -37,6 +37,9 @@ _UNCALIBRATED_SENTINEL = -1.0 +_OPTION_NAMES = {"frames_per_second": "fps", "width": "width_px", "height": "height_px"} + + class Normaliser: def __init__(self, folder: Path) -> None: self._folder = Path(folder) @@ -47,6 +50,7 @@ def normalise( *, trajectory_format: str | None = None, session_meta: dict[str, Any] | None = None, + video_defaults: dict[str, Any] | None = None, ) -> Session: """ Transform a raw trajectory dict into a canonical Session. @@ -59,9 +63,13 @@ def normalise( Which file format the payload was loaded from (e.g. "npy", "h5", "csv"). session_meta: Parsed contents of session.json, if available. + video_defaults: + User-supplied ``frames_per_second`` / ``width`` / ``height``; the last resort, + behind the trajectory payload and session.json. """ payload = self._apply_aliases(payload) meta = session_meta or {} + given = video_defaults or {} raw_xy = self._extract_trajectories(payload, meta) n_frames, n_animals = raw_xy.shape[0], raw_xy.shape[1] @@ -73,13 +81,14 @@ def normalise( version = payload.get("version") or meta.get("version") raw_attrs = self._collect_unknown_keys(payload) fps = self._require_positive_number( - "frames_per_second", payload.get("frames_per_second"), meta.get("frames_per_second") + "frames_per_second", payload.get("frames_per_second"), meta.get("frames_per_second"), + given.get("frames_per_second"), ) width = int(self._require_positive_number( - "width", payload.get("width"), meta.get("width") + "width", payload.get("width"), meta.get("width"), given.get("width"), )) height = int(self._require_positive_number( - "height", payload.get("height"), meta.get("height") + "height", payload.get("height"), meta.get("height"), given.get("height"), )) video_paths = payload.get("video_paths") or meta.get("video_paths") or [] video_path = self._resolve_video_path(video_paths) @@ -240,11 +249,21 @@ def _normalise_id_probabilities( arr = arr[:, :, 0] if arr.ndim != 2: return None + if arr.shape != (n_frames, n_animals): + raise DataValidationError( + f"id_probabilities has shape {arr.shape} but the trajectories hold " + f"{n_frames} frames of {n_animals} animals.", + code="IDT_SHAPE_MISMATCH", + severity="error", + subject="id_probabilities", + remediation="The probabilities and trajectories come from different runs, " + "or a column was dropped; re-export the session.", + ) return arr @staticmethod def _require_positive_number( - field_name: str, primary: Any, fallback: Any + field_name: str, primary: Any, fallback: Any, last_resort: Any = None ) -> float: """ Resolve *field_name* from the trajectory dict, falling back to @@ -260,7 +279,7 @@ def _require_positive_number( so a NaN value used to pass this check silently too -- isfinite() below closes that hole. """ - for candidate in (primary, fallback): + for candidate in (primary, fallback, last_resort): if candidate is None: continue try: @@ -277,7 +296,8 @@ def _require_positive_number( subject=field_name, remediation=( f"Ensure the session's trajectory file or session.json carries a " - f"valid '{field_name}' value; it cannot be safely defaulted." + f"valid '{field_name}' value, or give the reader option " + f"'{_OPTION_NAMES.get(field_name, field_name)}'; it cannot be safely defaulted." ), ) diff --git a/track2data/readers/idtrackerai/reader.py b/track2data/readers/idtrackerai/reader.py index d5614dab..54bc9d37 100644 --- a/track2data/readers/idtrackerai/reader.py +++ b/track2data/readers/idtrackerai/reader.py @@ -50,6 +50,7 @@ parse_timers_to_durations, ) from track2data.readers.index import ScanIndex +from track2data.readers.params import ReaderParameter, resolve_options from track2data.readers.peek import Peeker logger = logging.getLogger(__name__) @@ -100,6 +101,32 @@ class IDTrackerAiReader(SessionReader): verification: ClassVar[Literal["real_sample", "synthetic_only"]] = "real_sample" provides_body_length: ClassVar[bool] = True provides_identification_quality: ClassVar[bool] = True + # A bare export (h5, csv, a pickled dict) records no video size, and a csv written without + # a time column records no frame rate. These fill such gaps only: the trajectory file, then + # session.json, win over them, so they never override what the tracker itself recorded. + parameters: ClassVar[tuple[ReaderParameter, ...]] = ( + ReaderParameter( + name="fps", + label="Frame rate (frames per second)", + kind="float", + minimum=0.001, + help="Used only when neither the trajectory file nor session.json records it.", + ), + ReaderParameter( + name="width_px", + label="Frame width (pixels)", + kind="int", + minimum=1, + help="Bare idtracker.ai exports do not record the video's size; " + "used only when session.json does not either.", + ), + ReaderParameter( + name="height_px", + label="Frame height (pixels)", + kind="int", + minimum=1, + ), + ) # ── SessionReader protocol ───────────────────────────────────────────────── @@ -149,15 +176,24 @@ def accept(folder: Path) -> SessionCandidate | None: hint = _trajectories_subfolder_hint(cls, index) return [hint] if hint is not None else [] - def read(self, folder: Path, *, allow_pickle: bool = False) -> Session: + def read( + self, + folder: Path, + *, + allow_pickle: bool = False, + options: Mapping[str, Any] | None = None, + ) -> Session: """Parse *folder* and return a Session. ``allow_pickle`` gates the formats whose deserialisation executes code (npy). Defaults to False; when the folder also carries an h5 or csv trajectory, the fallback walk in ``_load_payload`` uses that instead and the refusal is invisible to the user. + + ``options`` are the declared ``parameters`` (frame rate and video size), used only + where the trajectory file and session.json record none. """ - return self._read(folder, light=False, allow_pickle=allow_pickle) + return self._read(folder, light=False, allow_pickle=allow_pickle, options=options) def probe( self, @@ -175,12 +211,20 @@ def probe( ``allow_pickle`` is the same consent ``read`` takes: a probe loads the same trajectory file, so it must be refused (or allowed) the same way. - ``options`` is part of the probe contract; this reader takes none. + ``options`` are the same video-info options ``read`` takes. """ - return self._read(folder, light=True, allow_pickle=allow_pickle) + return self._read(folder, light=True, allow_pickle=allow_pickle, options=options) - def _read(self, folder: Path, *, light: bool, allow_pickle: bool) -> Session: + def _read( + self, + folder: Path, + *, + light: bool, + allow_pickle: bool, + options: Mapping[str, Any] | None = None, + ) -> Session: folder = Path(folder) + opts = resolve_options(self.name, self.parameters, options) hit = detect(folder) if hit is None: from track2data.core.errors import ImportError_ @@ -222,7 +266,14 @@ def _read(self, folder: Path, *, light: bool, allow_pickle: bool) -> Session: # Build the normalised Session (core trajectory data + quality + labels). normaliser = Normaliser(folder) session = normaliser.normalise( - payload, trajectory_format=fmt_used, session_meta=session_meta + payload, + trajectory_format=fmt_used, + session_meta=session_meta, + video_defaults={ + "frames_per_second": opts["fps"], + "width": opts["width_px"], + "height": opts["height_px"], + }, ) # Enrich from session.json (tracking_intervals, roi_list, etc.). @@ -365,9 +416,12 @@ def _load_payload( # i.e. nowhere the person hitting the error would look. why = f" Skipped: {'; '.join(skipped)}." if skipped else "" refused_pickle = any("IDT_PICKLE_REFUSED" in s for s in skipped) + # Consent is the whole problem when every format passed over was refused for it: + # nothing is ambiguous, so say so with the code the consent prompt looks for. + only_refusals = bool(skipped) and all("IDT_PICKLE_REFUSED" in s for s in skipped) raise ImportError_( f"No readable trajectory format among: {available}.{why}", - code="IDT_FORMAT_AMBIGUOUS", + code="IDT_PICKLE_REFUSED" if only_refusals else "IDT_FORMAT_AMBIGUOUS", severity="error", subject=str(hit.path), remediation=(