From e6ef1255847df9e4c4a646daad92072d14034f64 Mon Sep 17 00:00:00 2001 From: C-Achard Date: Tue, 24 Nov 2026 15:37:05 +0100 Subject: [PATCH 1/4] Copy labeled-data file reading and writing --- dlccore/io/labeled_data/__init__.py | 31 +- dlccore/io/labeled_data/file.py | 158 +++++++ dlccore/io/labeled_data/wide/storage.py | 252 +++++++++++ tests/io/labeled_data/arrays/test_arrays.py | 151 +++++++ tests/io/labeled_data/test_checks.py | 256 ++++++++++++ tests/io/labeled_data/test_file.py | 200 +++++++++ tests/io/labeled_data/test_write.py | 415 +++++++++++++++++++ tests/io/labeled_data/wide/test_from_long.py | 87 ++++ tests/io/labeled_data/wide/test_storage.py | 215 ++++++++++ tests/io/labeled_data/wide/test_to_long.py | 162 ++++++++ 10 files changed, 1915 insertions(+), 12 deletions(-) create mode 100644 dlccore/io/labeled_data/file.py create mode 100644 dlccore/io/labeled_data/wide/storage.py create mode 100644 tests/io/labeled_data/arrays/test_arrays.py create mode 100644 tests/io/labeled_data/test_checks.py create mode 100644 tests/io/labeled_data/test_file.py create mode 100644 tests/io/labeled_data/test_write.py create mode 100644 tests/io/labeled_data/wide/test_from_long.py create mode 100644 tests/io/labeled_data/wide/test_storage.py create mode 100644 tests/io/labeled_data/wide/test_to_long.py diff --git a/dlccore/io/labeled_data/__init__.py b/dlccore/io/labeled_data/__init__.py index 6ce0188..33d06c8 100644 --- a/dlccore/io/labeled_data/__init__.py +++ b/dlccore/io/labeled_data/__init__.py @@ -1,15 +1,22 @@ -# -# DeepLabCut Toolbox (deeplabcut.org) -# © A. & M.W. Mathis Labs -# https://github.com/DeepLabCut/dlccore -# -# Contributors: -# https://github.com/DeepLabCut/dlccore/graphs/contributors -# -# Licensed under GNU Lesser General Public License v3.0 -# - """Labeled-data files: ``model`` holds what is true in any format, and each table format is a subpackage. -Imports no format eagerly, so no format's dependencies load until that format is imported. +Imports no format eagerly, so no format's dependencies load until a file is read or written, or that format is +imported. """ + +from dlc_octopus.io.labeled_data.arrays.from_long import LabeledDataArrays +from dlc_octopus.io.labeled_data.file import LabeledDataFile, read_labeled_data, write_labeled_data +from dlc_octopus.io.labeled_data.long.model import LABELED_DATA_LONG_VERSION, LabeledData +from dlc_octopus.io.labeled_data.model import BodypartScope, FramePath, Keypoint + +__all__ = [ + "LABELED_DATA_LONG_VERSION", + "BodypartScope", + "FramePath", + "Keypoint", + "LabeledData", + "LabeledDataArrays", + "LabeledDataFile", + "read_labeled_data", + "write_labeled_data", +] diff --git a/dlccore/io/labeled_data/file.py b/dlccore/io/labeled_data/file.py new file mode 100644 index 0000000..be9ecd4 --- /dev/null +++ b/dlccore/io/labeled_data/file.py @@ -0,0 +1,158 @@ +"""One labeled-data file as consumers use it, whatever layout stores it, and the read and write that move it.""" + +from __future__ import annotations + +from dataclasses import dataclass +from pathlib import Path +from typing import TYPE_CHECKING + +from dlc_octopus.io.file_stat import FileStat +from dlc_octopus.io.labeled_data.model import FramePath, Keypoint + +if TYPE_CHECKING: + import pandas as pd + from dlc_octopus.io.labeled_data.long.model import LabeledData + from dlc_octopus.io.labeled_data.wide.h5 import H5KeySelection + from dlc_octopus.io.labeled_data.wide.header import LabeledDataHeader + from dlc_octopus.io.labeled_data.wide.row_index import LabeledDataRowIndex + from dlc_octopus.io.labeled_data.wide.storage import WideLabeledDataStorage + from dlc_octopus.io.stamp import WriterStamp + + +@dataclass(frozen=True) +class LabeledDataFile: + """One labeled-data file: its table as read, and its labels as the model where they can be interpreted. + + Its facts (``key_selection``, ``writer_stamp``, ``writer_stamp_error``, ``raw_header``, ``raw_row_index``) say + what the stored file holds, uninterpreted; the checks take them. Nothing else reads the storage behind them. + + Attributes: + path: The path as given; never resolved. + stat: The file's stat, taken just before it was read; pass it as ``replaces`` to write the file back. + ``None`` when it could not be taken, and the writer then refuses to replace the file. + """ + + path: Path + _stored: WideLabeledDataStorage + stat: FileStat | None + + @property + def keypoints(self) -> tuple[Keypoint, ...] | None: + """The keypoints, in order of first appearance; ``None`` when invalid.""" + + return self._stored.keypoints + + @property + def frames(self) -> tuple[FramePath, ...] | None: + """The frame paths, in row order; ``None`` when invalid.""" + + return self._stored.frames + + @property + def key_selection(self) -> H5KeySelection | None: + """The keys of an H5 file and the one read; ``None`` for a container with one table, such as CSV.""" + + return self._stored.key_selection + + @property + def writer_stamp(self) -> WriterStamp | None: + """Provenance stamp; ``None`` if unavailable.""" + + return self._stored.writer_stamp + + @property + def writer_stamp_error(self) -> str | None: + """Why a stamp that is present could not be read; ``None`` when there is none or it read.""" + + return self._stored.writer_stamp_error + + @property + def raw_header(self) -> LabeledDataHeader: + """The column header as stored, classified without loss.""" + + return self._stored.header + + @property + def raw_row_index(self) -> LabeledDataRowIndex: + """The row index as stored, classified without loss: its level names, entries and frame parts.""" + + return self._stored.row_index + + @property + def labeled_data(self) -> LabeledData: + """The labels as the model, built on each access. + + Raises: + ValueError: Naming the file and why it has no model, e.g. a frame of other than three parts. + """ + + from dlc_octopus.io.labeled_data.wide.to_long import wide_to_long + + try: + return wide_to_long(self._stored.dataframe, self._stored.header, self._stored.row_index) + except ValueError as error: + raise ValueError(f"{self.path}: {error}") from error + + def to_raw_wide_df(self) -> pd.DataFrame: + """A copy of the table exactly as read: for a file stored wide, what ``pd.read_hdf`` returns. + + Raw, never normalised: a legacy key, a flat row index or a header in another order come back as found. For + DeepLabCut's current form, use ``labeled_data.to_wide_df()``. + """ + + return self._stored.dataframe.copy() + + +def read_labeled_data(path: Path) -> LabeledDataFile: + """Read one labeled-data file and interpret its keypoints and frames. + + Args: + path: A ``CollectedData_*`` or ``machinelabels*`` file. + + Raises: + UnreadableFileError: If the file cannot be read. + ValueError: If no reader handles the suffix. + """ + + from dlc_octopus.io.labeled_data.wide.storage import read_wide_labeled_data + + try: + stat = FileStat.of(path) + except OSError: + stat = None + stored = read_wide_labeled_data(path) # raises for an unknown suffix or an unreadable file + + return LabeledDataFile(path, stored, stat) + + +def write_labeled_data(labels: LabeledData, path: Path, *, replaces: FileStat | None) -> FileStat: + """Write labels in DeepLabCut's current form: ``path`` (``.h5``) and its ``.csv`` twin. + + Writes are atomic, and ``path`` is replaced only if it corresponds to the state described by ``replaces``. + + Args: + labels: What to write. + path: The H5 file to create or replace. Its suffix must equal ``.h5`` ignoring case. The CSV twin is + written beside it, with suffix ``.CSV`` if ``path``'s suffix is upper case and ``.csv`` otherwise. + replaces: ``LabeledDataFile.stat`` of the file being replaced, or ``None`` to create a file that must not exist. + + Returns: + The stat of the written file, to pass as ``replaces`` to the next write. + + Raises: + ValueError: If ``path``'s suffix is not ``.h5`` ignoring case, ``path`` is human labels + (``CollectedData_*``) and the labels have a likelihood, a keypoint's individual is named ``""``, or + ``path`` holds several keys, which a write of one key would drop. + UnreadableFileError: If ``replaces`` is given and ``path`` cannot be opened as HDF5, so the keys it would + drop are unknown. + FileExistsError: If ``replaces`` is ``None`` and ``path`` exists. + FileChangedError: If ``path`` changed or vanished since ``replaces`` was taken. + + Warns: + UserWarning: Once both files are in place, for each frame the CSV twin reads back without: a first frame + without values, which pandas and DeepLabCut read as the row index's names. The H5 keeps it. + """ + + from dlc_octopus.io.labeled_data.wide.storage import write_wide_labeled_data + + return write_wide_labeled_data(labels, path, replaces=replaces) diff --git a/dlccore/io/labeled_data/wide/storage.py b/dlccore/io/labeled_data/wide/storage.py new file mode 100644 index 0000000..036828c --- /dev/null +++ b/dlccore/io/labeled_data/wide/storage.py @@ -0,0 +1,252 @@ +"""Labels stored wide, as DeepLabCut writes them in H5 and CSV: the table, its classification, and the read.""" + +from __future__ import annotations + +import os +import shutil +import uuid +import warnings +from collections.abc import Callable +from dataclasses import dataclass +from pathlib import Path +from typing import TYPE_CHECKING, cast + +import pandas as pd +from dlc_octopus.io.errors import FileChangedError +from dlc_octopus.io.file_stat import FileStat +from dlc_octopus.io.labeled_data.model import FramePath, Keypoint +from dlc_octopus.io.labeled_data.wide.header import LabeledDataHeader, LabeledDataHeaderShape +from dlc_octopus.io.labeled_data.wide.row_index import LabeledDataRowIndex, RowIndexShape, frame_part_as_text +from dlc_octopus.io.labeled_data.wide.table import LabeledDataRead, classify_labeled_data_read +from dlc_octopus.io.stamp import WriterStamp +from dlc_octopus.io.suffixes import ( + CSV_SUFFIX, + H5_SUFFIX, + LABELED_DATA_TABLE_SUFFIXES, + suffix_in, +) + +if TYPE_CHECKING: + from dlc_octopus.io.labeled_data.long.model import LabeledData + from dlc_octopus.io.labeled_data.wide.h5 import H5KeySelection + + +@dataclass(frozen=True, eq=False) +class WideLabeledDataStorage: + """Labels stored wide: one row per frame; scorer, individual, bodypart and coordinate as column levels. + + Compared and hashed by identity, since a DataFrame has neither value equality nor a hash; compare content + through ``keypoints``, ``frames`` or ``dataframe`` explicitly. + + Attributes: + key_selection: For a container holding several tables, the keys found and the one read; ``None`` for a + container with one table, such as CSV. + header: The column header, classified without loss. + row_index: The row index, classified without loss. + dataframe: The table as the container returned it, unmodified. + writer_stamp: Who wrote the file, when this package's writer did; ``None`` otherwise. + writer_stamp_error: Why a stamp that is present could not be read; ``None`` when there is none or it read. + """ + + key_selection: H5KeySelection | None + header: LabeledDataHeader + row_index: LabeledDataRowIndex + dataframe: pd.DataFrame + writer_stamp: WriterStamp | None = None + writer_stamp_error: str | None = None + + @property + def keypoints(self) -> tuple[Keypoint, ...] | None: + """The keypoints, in order of first appearance; ``None`` when the header is unrecognised.""" + + if self.header.shape is LabeledDataHeaderShape.UNRECOGNISED: + return None + return tuple(columns.keypoint for columns in self.header.keypoints) + + @property + def frames(self) -> tuple[FramePath, ...] | None: + """The frame paths as text, in row order; ``None`` when the row index is unrecognised or a part has no name. + + Parts become text as ``frame_part_as_text`` gives it; ``row_index`` keeps every part as stored. + """ + + if self.row_index.shape is RowIndexShape.UNRECOGNISED: + return None + frames = tuple(tuple(frame_part_as_text(part) for part in frame) for frame in self.row_index.frames) + if any(part is None for frame in frames for part in frame): + return None + return cast("tuple[FramePath, ...]", frames) + + +def wide_suffix(path: Path) -> str | None: + """Return ``path``'s suffix lowercased if it equals ``.h5`` or ``.csv`` ignoring case; ``None`` otherwise.""" + + return suffix_in(path, LABELED_DATA_TABLE_SUFFIXES) + + +def _read_h5(path: Path) -> LabeledDataRead: + from dlc_octopus.io.labeled_data.wide.h5 import read_labeled_data_h5 + + return read_labeled_data_h5(path) + + +def _read_csv(path: Path) -> LabeledDataRead: + from dlc_octopus.io.labeled_data.wide.csv import read_labeled_data_csv + + return read_labeled_data_csv(path) + + +_READERS: dict[str, Callable[[Path], LabeledDataRead]] = {H5_SUFFIX: _read_h5, CSV_SUFFIX: _read_csv} + + +def read_wide_labeled_data(path: Path) -> WideLabeledDataStorage: + """Read a wide labeled-data H5 or CSV file and classify its header and row index. + + Args: + path: A ``CollectedData_*`` or ``machinelabels*`` file whose suffix equals ``.h5`` or ``.csv`` ignoring case. + + Raises: + UnreadableFileError: If the file cannot be read. + ValueError: If the suffix is neither ``.h5`` nor ``.csv``. + """ + + suffix = wide_suffix(path) + + if suffix is None: + raise ValueError(f"{path}: no wide labeled-data reader for {path.suffix!r}; expected {sorted(_READERS)}.") + + reader = _READERS[suffix] + + read = reader(path) + header, row_index = classify_labeled_data_read(read) + + return WideLabeledDataStorage( + key_selection=read.key_selection, + header=header, + row_index=row_index, + dataframe=read.dataframe, + writer_stamp=read.writer_stamp, + writer_stamp_error=read.writer_stamp_error, + ) + + +WRITER_NAME = "dlc_octopus.io.labeled_data" + + +def write_wide_labeled_data(labels: LabeledData, path: Path, *, replaces: FileStat | None) -> FileStat: + """Write labels as an H5 file in DeepLabCut's current wide form, with its CSV twin beside it. + + Both files are written to temporary names in the same directory and replaced only once both are complete, + so neither is ever left half-written. The H5 is stamped with this writer's name and package version. The + CSV twin is replaced without a check of its own: the H5 is the file the check guards. A replaced file keeps + its permission bits and a new one gets the umask's; the group is the writer's unless the directory sets it. + + Args: + labels: What to write. + path: The H5 file to create or replace. Its suffix must equal ``.h5`` ignoring case. The CSV twin is + ``csv_twin(path)``. + replaces: The stat of ``path`` when the caller read it, or ``None`` to create a file that must not exist. + + Returns: + The stat of the written file, to pass as ``replaces`` to the next write. + + Raises: + ValueError: If ``path``'s suffix is not ``.h5`` ignoring case, ``path`` is human labels + (``CollectedData_*``) and the labels have a likelihood, a keypoint's individual is named ``""``, or + ``path`` holds several keys, which a write of one key would drop. + UnreadableFileError: If ``replaces`` is given and ``path`` cannot be opened as HDF5, so the keys it would + drop are unknown. + FileExistsError: If ``replaces`` is ``None`` and ``path`` exists. + FileChangedError: If ``path`` changed or vanished since ``replaces`` was taken. + + Warns: + UserWarning: Once both files are in place, for each frame the CSV twin reads back without. + """ + + from dlc_octopus.io.labeled_data.checks.file import frames_lost_to_csv, unread_h5_keys + from dlc_octopus.io.labeled_data.checks.model import keypoints_with_empty_individual, likelihood_in_human_labels + from dlc_octopus.io.labeled_data.wide.csv import write_labeled_data_csv + from dlc_octopus.io.labeled_data.wide.h5 import select_h5_key, write_labeled_data_h5 + + if suffix_in(path, frozenset({H5_SUFFIX})) is None: + raise ValueError(f"{path}: the labeled-data writer writes an .h5 file and its .csv twin; got {path.suffix!r}.") + if likelihood_in_human_labels(labels, path): + # DeepLabCut's training-set creation assumes x and y only (DeepLabCut #3319). + raise ValueError(f"{path}: human labels never carry a likelihood; drop it first.") + if unnamed := keypoints_with_empty_individual(labels): + raise ValueError( + f"{path}: {unnamed[0]} has an empty individual name; DeepLabCut's header names an individual or has no " + "individuals level." + ) + # Any change to the keys since the caller's read fails the stat check before the replace. + if replaces is not None and path.exists() and (dropped := unread_h5_keys(select_h5_key(path))): + raise ValueError(f"{path}: holds keys {list(dropped)} besides the one read; a write would drop them.") + + frame = labels.to_wide_df() + temporaries: list[Path] = [] + + try: + temporaries.append(temporary_h5 := _reserve_temporary(path, H5_SUFFIX)) + temporaries.append(temporary_csv := _reserve_temporary(path, CSV_SUFFIX)) + write_labeled_data_h5(frame, temporary_h5, WriterStamp.current(WRITER_NAME)) + write_labeled_data_csv(frame, temporary_csv) + _check_unchanged(path, replaces) + _keep_mode(path, temporary_h5) + _keep_mode(csv_twin(path), temporary_csv) + os.replace(temporary_h5, path) + os.replace(temporary_csv, csv_twin(path)) + finally: + for temporary in temporaries: + temporary.unlink(missing_ok=True) + + for entry in frames_lost_to_csv(frame): + warnings.warn( + f"{csv_twin(path)}: frame {entry} has no values and comes first, so this CSV reads back without it; " + f"{path.name} keeps it.", + UserWarning, + stacklevel=3, + ) + + return FileStat.of(path) + + +def csv_twin(path: Path) -> Path: + """Return ``path`` with its suffix replaced by ``.CSV`` if ``path.suffix.isupper()``, and by ``.csv`` otherwise.""" + + return path.with_suffix(CSV_SUFFIX.upper() if path.suffix.isupper() else CSV_SUFFIX) + + +def _reserve_temporary(path: Path, suffix: str) -> Path: + """Create an empty file with a name no other call is given, beside ``path`` so a replace stays atomic. + + Created as any new file is, so the umask applies; ``mkstemp`` would make it, and the file it replaces, + owner-only. + """ + + while True: + temporary = path.parent / f".{path.stem}.{uuid.uuid4().hex[:8]}.tmp{suffix}" + try: + os.close(os.open(temporary, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o666)) + except FileExistsError: + continue + return temporary + + +def _keep_mode(original: Path, temporary: Path) -> None: + """Give ``temporary`` the permission bits of the file it is about to replace, if there is one.""" + + if original.exists(): + shutil.copymode(original, temporary) + + +def _check_unchanged(path: Path, replaces: FileStat | None) -> None: + if replaces is None: + if path.exists(): + raise FileExistsError(f"{path}: exists; pass the stat taken when it was read to replace it.") + return + try: + current = FileStat.of(path) + except FileNotFoundError as error: + raise FileChangedError(f"{path}: was removed since it was read.") from error + if current != replaces: + raise FileChangedError(f"{path}: changed since it was read ({replaces} then, {current} now).") diff --git a/tests/io/labeled_data/arrays/test_arrays.py b/tests/io/labeled_data/arrays/test_arrays.py new file mode 100644 index 0000000..4a66020 --- /dev/null +++ b/tests/io/labeled_data/arrays/test_arrays.py @@ -0,0 +1,151 @@ +from dataclasses import fields, replace +from pathlib import Path + +import numpy as np +import pandas as pd +import pytest +from dlc_octopus.io.labeled_data import BodypartScope, Keypoint, LabeledData, LabeledDataArrays, read_labeled_data + +FIXTURES_DIR = Path(__file__).parents[2] / "fixtures" / "labeled_data" +FIXTURES = sorted(path.name for path in FIXTURES_DIR.glob("*") if path.suffix in {".h5", ".csv"}) +FRAMES = (("labeled-data", "s1", "img0.png"), ("labeled-data", "s1", "img1.png")) +KEYPOINTS = tuple(Keypoint("Sc", None, bodypart) for bodypart in ("nose", "tail", "ear")) + + +def _arrays(**changes: object) -> LabeledDataArrays: + arrays = LabeledDataArrays(FRAMES, KEYPOINTS, np.zeros((2, 3, 2)), np.zeros((2, 3))) + return replace(arrays, **changes) + + +def test_arrays_matching_their_frames_and_keypoints_are_built() -> None: + # Control for the refusals below. + assert _arrays(likelihood=None).xy.shape == (2, 3, 2) + + +@pytest.mark.parametrize( + "xy", + [np.zeros((3, 3, 2)), np.zeros((2, 2, 2)), np.zeros((2, 3, 3)), np.zeros((2, 3))], + ids=["frames", "keypoints", "coordinates", "rank"], +) +def test_xy_must_have_one_pair_per_frame_and_keypoint(xy: np.ndarray) -> None: + with pytest.raises(ValueError, match="xy"): + _arrays(xy=xy) + + +@pytest.mark.parametrize("likelihood", [np.zeros((3, 3)), np.zeros((2, 2)), np.zeros((2, 3, 1))]) +def test_likelihood_must_have_one_value_per_frame_and_keypoint(likelihood: np.ndarray) -> None: + with pytest.raises(ValueError, match="likelihood"): + _arrays(likelihood=likelihood) + + +def test_every_fixture_is_found() -> None: + # Control: an empty glob would let the parametrized tests below pass by running nothing. + assert len(FIXTURES) == 10 + + +@pytest.mark.parametrize("filename", FIXTURES) +def test_the_arrays_equal_the_long_values_on_every_fixture(filename: str) -> None: + labels = read_labeled_data(FIXTURES_DIR / filename) + long = labels.labeled_data.to_long_df() + + arrays = labels.labeled_data.to_arrays() + + assert (arrays.frames, arrays.keypoints) == (labels.frames, labels.keypoints) + at = (long["frame_index"].to_numpy(), long["keypoint_index"].to_numpy()) + np.testing.assert_array_equal(arrays.xy[at], long[["x", "y"]].to_numpy()) + if "likelihood" in long.columns: + assert arrays.likelihood is not None + np.testing.assert_array_equal(arrays.likelihood[at], long["likelihood"].to_numpy()) + else: + assert arrays.likelihood is None + # Control: NaN compares equal above, so an all-NaN view would pass without some labeled value. + assert arrays.labeled.any() + + +@pytest.mark.parametrize("filename", FIXTURES) +def test_every_fixture_yields_every_cell_in_its_table(filename: str) -> None: + labels = read_labeled_data(FIXTURES_DIR / filename) + xs = labels.to_raw_wide_df().xs("x", level="coords", axis=1) + + arrays = labels.labeled_data.to_arrays() + + assert arrays.xy.shape == (len(arrays.frames), len(arrays.keypoints), 2) + assert arrays.labeled.shape == arrays.xy.shape[:2] + assert int(arrays.labeled.sum()) == int(xs.notna().to_numpy().sum()) + + +def test_a_missing_pair_is_not_labeled_and_a_present_one_is_its_stored_value() -> None: + labels = read_labeled_data(FIXTURES_DIR / "single_animal_machine.h5") + frame_0, frame_3 = labels.to_raw_wide_df().iloc[0], labels.to_raw_wide_df().iloc[3] + arrays = labels.labeled_data.to_arrays() + nose, tail = (arrays.keypoints.index(k) for k in arrays.keypoints) + + assert not arrays.labeled[3, nose] + assert np.isnan(arrays.xy[3, nose]).all() + assert arrays.likelihood is not None + assert arrays.likelihood[3, nose] == frame_3[("Sc", "nose", "likelihood")] + assert arrays.labeled[0, tail] + assert tuple(arrays.xy[0, tail]) == tuple(frame_0[("Sc", "tailbase", c)] for c in ("x", "y")) + + +def test_human_labels_have_no_likelihood() -> None: + arrays = read_labeled_data(FIXTURES_DIR / "single_animal_human.h5").labeled_data.to_arrays() + + assert arrays.likelihood is None + + +def test_unique_bodyparts_keep_their_scope() -> None: + arrays = read_labeled_data(FIXTURES_DIR / "multi_animal_unique_bodyparts.h5").labeled_data.to_arrays() + + scopes = {keypoint.individual: keypoint.scope for keypoint in arrays.keypoints} + + assert scopes.pop("single") is BodypartScope.UNIQUE + assert set(scopes.values()) == {BodypartScope.INDIVIDUAL} + + +def test_the_arrays_are_read_only() -> None: + arrays = read_labeled_data(FIXTURES_DIR / "single_animal_machine.h5").labeled_data.to_arrays() + assert arrays.likelihood is not None + + with pytest.raises(ValueError, match="read-only"): + arrays.xy[0, 0, 0] = 0.0 + with pytest.raises(ValueError, match="read-only"): + arrays.likelihood[0, 0] = 0.0 + + +def _with_coords(coords: list[str], values: list[object]) -> LabeledData: + columns = pd.MultiIndex.from_tuples([("Sc", "nose", c) for c in coords], names=["scorer", "bodyparts", "coords"]) + return LabeledData.from_wide_df(pd.DataFrame([values], columns=columns, index=["labeled-data/v1/img0.png"])) + + +def test_plain_x_and_y_are_interpreted() -> None: + arrays = _with_coords(["x", "y"], [1.0, 2.0]).to_arrays() + + assert (arrays.xy.tolist(), arrays.labeled.tolist()) == ([[[1.0, 2.0]]], [[True]]) + + +@pytest.mark.parametrize( + ("x", "y"), + [(0.0, 0.0), (-1.0, -1.0), (3.5, -0.25)], + ids=["origin", "minus_one_pair", "negative"], +) +def test_a_pair_with_both_values_is_labeled_whatever_they_are(x: float, y: float) -> None: + # Negative coordinates and DeepLabCut's (-1, -1) are facts here; what they mean is each consumer's rule. + arrays = _with_coords(["x", "y"], [x, y]).to_arrays() + + assert arrays.labeled.tolist() == [[True]] + assert arrays.xy.tolist() == [[[x, y]]] + + +@pytest.mark.parametrize( + ("x", "y"), [(float("nan"), float("nan")), (float("nan"), 2.0)], ids=["missing", "half_missing"] +) +def test_a_pair_with_a_missing_value_is_not_labeled_and_keeps_the_other(x: float, y: float) -> None: + arrays = _with_coords(["x", "y"], [x, y]).to_arrays() + + assert arrays.labeled.tolist() == [[False]] + np.testing.assert_array_equal(arrays.xy[0, 0], [x, y]) + + +def test_a_keypoint_is_named_by_scorer_individual_and_bodypart_only() -> None: + assert [field.name for field in fields(Keypoint)] == ["scorer", "individual", "bodypart"] diff --git a/tests/io/labeled_data/test_checks.py b/tests/io/labeled_data/test_checks.py new file mode 100644 index 0000000..3ea3204 --- /dev/null +++ b/tests/io/labeled_data/test_checks.py @@ -0,0 +1,256 @@ +import importlib +from pathlib import Path, PurePath + +import pandas as pd +import pytest +from dlc_octopus.io.labeled_data import Keypoint, LabeledData, read_labeled_data +from dlc_octopus.io.labeled_data.checks.file import ( + frame_absorbed_into_index_names, + frames_of_other_depth, + frames_with_unnamed_parts, + has_no_frames, + header_is_unrecognised, + keypoints_with_unrecognised_coords, + keypoints_without_the_likelihood_others_store, + non_numeric_columns, + row_index_is_unrecognised, + unread_h5_keys, +) +from dlc_octopus.io.labeled_data.checks.model import ( + keypoints_with_empty_individual, + likelihood_in_human_labels, + missing_keypoints, +) +from dlc_octopus.io.labeled_data.wide.h5 import H5KeySelectionOutcome, select_h5_key +from dlc_octopus.io.labeled_data.wide.header import LabeledDataHeader, classify_labeled_data_header +from dlc_octopus.io.labeled_data.wide.row_index import LabeledDataRowIndex, classify_labeled_data_row_index + +FIXTURES_DIR = Path(__file__).parents[1] / "fixtures" / "labeled_data" +SINGLE_ANIMAL_LEVELS = ["scorer", "bodyparts", "coords"] +MULTI_ANIMAL_LEVELS = ["scorer", "individuals", "bodyparts", "coords"] + + +def _labels(keypoints: list[tuple[str, ...]], coords: tuple[str, ...] = ("x", "y")) -> LabeledData: + names = MULTI_ANIMAL_LEVELS if len(keypoints[0]) == 3 else SINGLE_ANIMAL_LEVELS + columns = pd.MultiIndex.from_tuples([(*k, c) for k in keypoints for c in coords], names=names) + return LabeledData.from_wide_df( + pd.DataFrame([[1.0] * len(columns)], columns=columns, index=["labeled-data/s1/img0.png"]) + ) + + +def _individual(scorer: str, individual: str, bodypart: str) -> Keypoint: + return Keypoint(scorer, individual, bodypart) + + +WITH_LIKELIHOOD = _labels([("Sc", "nose")], coords=("x", "y", "likelihood")) + + +def test_a_likelihood_in_human_labels_is_found() -> None: + assert likelihood_in_human_labels(WITH_LIKELIHOOD, PurePath("labeled-data/s1/CollectedData_Sc.h5")) + + +@pytest.mark.parametrize( + ("labels", "name"), + [ + (WITH_LIKELIHOOD, "machinelabels-iter0.h5"), + (WITH_LIKELIHOOD, "collecteddata_Sc.h5"), + (_labels([("Sc", "nose")]), "CollectedData_Sc.h5"), + ], + ids=["machine_labels", "other_case", "no_likelihood"], +) +def test_a_likelihood_elsewhere_or_human_labels_without_one_is_not_found(labels: LabeledData, name: str) -> None: + assert not likelihood_in_human_labels(labels, PurePath(name)) + + +def test_an_individual_lacking_a_bodypart_another_has_is_found() -> None: + labels = _labels([("Sc", "mouse1", "nose"), ("Sc", "mouse1", "tail"), ("Sc", "mouse2", "nose")]) + + assert missing_keypoints(labels) == (_individual("Sc", "mouse2", "tail"),) + + +def test_missing_keypoints_come_in_individual_then_bodypart_order() -> None: + labels = _labels([("Sc", "mouse1", "tail"), ("Sc", "mouse2", "nose"), ("Sc", "mouse3", "ear")]) + + assert missing_keypoints(labels) == ( + _individual("Sc", "mouse1", "nose"), + _individual("Sc", "mouse1", "ear"), + _individual("Sc", "mouse2", "tail"), + _individual("Sc", "mouse2", "ear"), + _individual("Sc", "mouse3", "tail"), + _individual("Sc", "mouse3", "nose"), + ) + + +@pytest.mark.parametrize( + "keypoints", + [ + [("Sc", "mouse1", "nose"), ("Sc", "mouse2", "nose")], + [("Sc", "mouse1", "nose"), ("Sc", "mouse2", "nose"), ("Sc", "single", "box")], + [("Sc1", "mouse1", "nose"), ("Sc2", "mouse2", "tail")], + [("Sc", "nose"), ("Sc", "tail")], + ], + ids=["complete", "unique_bodyparts_apart", "scorers_apart", "single_animal"], +) +def test_no_keypoint_is_missing_where_every_individual_has_its_scorers_bodyparts( + keypoints: list[tuple[str, ...]], +) -> None: + assert missing_keypoints(_labels(keypoints)) == () + + +@pytest.mark.parametrize( + "filename", ["multi_animal_human.h5", "multi_animal_machine.h5", "multi_animal_unique_bodyparts.h5"] +) +def test_the_multi_animal_fixtures_miss_no_keypoint(filename: str) -> None: + assert missing_keypoints(read_labeled_data(FIXTURES_DIR / filename).labeled_data) == () + + +def test_the_keys_a_multi_key_file_leaves_unread_are_found() -> None: + selection = select_h5_key(FIXTURES_DIR / "ambiguous_multi_key.h5") + assert selection.outcome is H5KeySelectionOutcome.MULTI_KEY # control: the fixture is the case under test + + unread = unread_h5_keys(selection) + + assert unread + assert set(unread) == set(selection.keys_found) - {selection.selected_key} + + +@pytest.mark.parametrize("filename", ["single_animal_human.h5", "single_animal_human_legacy_index.h5"]) +def test_a_file_with_one_key_leaves_none_unread(filename: str) -> None: + assert unread_h5_keys(select_h5_key(FIXTURES_DIR / filename)) == () + + +def test_a_container_without_keys_leaves_none_unread() -> None: + assert unread_h5_keys(None) == () + + +def _parts(frames: list[tuple[object, ...]], names: tuple[object, ...] = ()) -> LabeledDataRowIndex: + return classify_labeled_data_row_index(names, frames, is_multi_index=True) + + +def test_frames_of_other_than_three_parts_are_found_by_row() -> None: + frames = [("labeled-data", "s1", "img0.png"), ("s1", "img1.png"), ("labeled-data", "s1", "extra", "img2.png")] + + assert frames_of_other_depth(_parts(frames)) == (1, 2) + + +def test_frames_of_three_parts_are_not_found() -> None: + assert frames_of_other_depth(_parts([("labeled-data", "s1", "img0.png"), ("labeled-data", 2019, "img1.png")])) == () + + +def test_frames_with_a_part_naming_nothing_are_found_by_row() -> None: + frames = [("labeled-data", "s1", "img0.png"), ("labeled-data", 2019.5, "img1.png"), ("labeled-data", True, "a")] + + assert frames_with_unnamed_parts(_parts(frames)) == (1, 2) + + +def test_frames_of_text_and_integer_parts_are_not_found() -> None: + frames = [("labeled-data", "s1", "img0.png"), ("labeled-data", 2019, "img1.png")] + + assert frames_with_unnamed_parts(_parts(frames)) == () + + +def test_a_table_without_rows_has_no_frames_and_one_with_rows_has() -> None: + assert has_no_frames(classify_labeled_data_row_index((None,), (), is_multi_index=False)) + assert not has_no_frames(_parts([("labeled-data", "s1", "img0.png")])) + + +def test_a_row_index_of_numbers_is_unrecognised_and_one_of_paths_is_not() -> None: + assert row_index_is_unrecognised(classify_labeled_data_row_index((None,), (0, 1), is_multi_index=False)) + assert not row_index_is_unrecognised( + classify_labeled_data_row_index((None,), ("labeled-data/s1/img0.png",), is_multi_index=False) + ) + + +def _header(coords_by_bodypart: dict[str, tuple[str, ...]], levels: tuple[str, ...] = ()) -> LabeledDataHeader: + columns = [("Sc", bodypart, coord) for bodypart, coords in coords_by_bodypart.items() for coord in coords] + return classify_labeled_data_header(levels or SINGLE_ANIMAL_LEVELS, columns) + + +def test_a_header_with_other_level_names_is_unrecognised_and_deeplabcuts_is_not() -> None: + assert header_is_unrecognised(_header({"nose": ("x", "y")}, levels=("scorer", "bodypart", "coord"))) + assert not header_is_unrecognised(_header({"nose": ("x", "y")})) + + +@pytest.mark.parametrize( + "coords", [("x", "y", "z"), ("x",), ("x", "y", "y"), ("x", "x", "y")], ids=["xyz", "x_only", "y_twice", "x_twice"] +) +def test_coordinates_other_than_x_y_likelihood_once_each_are_found(coords: tuple[str, ...]) -> None: + header = _header({"nose": ("x", "y"), "tail": coords}) + + assert [columns.keypoint.bodypart for columns in keypoints_with_unrecognised_coords(header)] == ["tail"] + + +@pytest.mark.parametrize("coords", [("x", "y"), ("y", "x"), ("x", "y", "likelihood")], ids=["xy", "yx", "xyl"]) +def test_x_y_and_an_optional_likelihood_in_any_order_are_not_found(coords: tuple[str, ...]) -> None: + assert keypoints_with_unrecognised_coords(_header({"nose": coords})) == () + + +def test_a_keypoint_without_the_likelihood_another_stores_is_found() -> None: + header = _header({"nose": ("x", "y", "likelihood"), "tail": ("x", "y"), "ear": ("x", "y", "likelihood")}) + + assert [columns.keypoint.bodypart for columns in keypoints_without_the_likelihood_others_store(header)] == ["tail"] + + +@pytest.mark.parametrize("coords", [("x", "y"), ("x", "y", "likelihood")], ids=["none_store_one", "all_store_one"]) +def test_keypoints_that_agree_on_a_likelihood_are_not_found(coords: tuple[str, ...]) -> None: + assert keypoints_without_the_likelihood_others_store(_header({"nose": coords, "tail": coords})) == () + + +@pytest.mark.parametrize("value", ["1.0", True, 1 + 2j], ids=["text", "bool", "complex"]) +def test_a_column_of_values_that_are_not_real_numbers_is_found(value: object) -> None: + table = pd.DataFrame({("Sc", "nose", "x"): [value], ("Sc", "nose", "y"): [2.0]}) + + assert non_numeric_columns(table) == (("Sc", "nose", "x"),) + + +def test_integer_and_float_columns_are_not_found() -> None: + assert non_numeric_columns(pd.DataFrame({("Sc", "nose", "x"): [1], ("Sc", "nose", "y"): [float("nan")]})) == () + + +def _csv_with_first_frame(tmp_path: Path, *, flat: bool, empty: bool = True) -> Path: + frames = [("labeled-data", "Sample4", "0155.png"), ("labeled-data", "Sample4", "0156.png")] + index = pd.Index(["/".join(frame) for frame in frames]) if flat else pd.MultiIndex.from_tuples(frames) + columns = pd.MultiIndex.from_tuples([("Sc", "nose", "x"), ("Sc", "nose", "y")], names=SINGLE_ANIMAL_LEVELS) + first = [float("nan")] * 2 if empty else [1.0, 2.0] + path = tmp_path / "CollectedData_Sc.csv" + pd.DataFrame([first, [3.0, 4.0]], index=index, columns=columns).to_csv(path) + return path + + +@pytest.mark.parametrize("flat", [False, True], ids=["path_parts", "flat_paths"]) +def test_a_first_frame_pandas_read_as_index_names_is_found(tmp_path: Path, *, flat: bool) -> None: + labels = read_labeled_data(_csv_with_first_frame(tmp_path, flat=flat)) + assert len(labels.raw_row_index.entries) == 1 # control: the CSV did lose its first frame + + assert frame_absorbed_into_index_names(labels.raw_row_index) == ("labeled-data", "Sample4", "0155.png") + + +def test_a_csv_whose_first_frame_has_values_absorbs_nothing(tmp_path: Path) -> None: + labels = read_labeled_data(_csv_with_first_frame(tmp_path, flat=False, empty=False)) + + assert frame_absorbed_into_index_names(labels.raw_row_index) == () + + +@pytest.mark.parametrize( + "names", + [(None, None, None), ("image",), ("a", "b"), ("labeled-data", None, "img0.png")], + ids=["unnamed", "one_name", "two_names", "one_unnamed"], +) +def test_index_names_that_spell_no_three_part_frame_are_not_found(names: tuple[object, ...]) -> None: + assert frame_absorbed_into_index_names(_parts([("labeled-data", "s1", "img1.png")], names=names)) == () + + +def test_checks_are_split_into_file_and_model_facts() -> None: + importlib.import_module("dlc_octopus.io.labeled_data.checks.file") + importlib.import_module("dlc_octopus.io.labeled_data.checks.model") + + +def test_a_keypoint_whose_individual_is_named_empty_is_found() -> None: + labels = _labels([("Sc", "mouse1", "nose"), ("Sc", "", "nose")]) + + assert keypoints_with_empty_individual(labels) == (_individual("Sc", "", "nose"),) + + +@pytest.mark.parametrize("keypoints", [[("Sc", "mouse1", "nose")], [("Sc", "nose")]], ids=["named", "single_animal"]) +def test_named_or_absent_individuals_are_not_found(keypoints: list[tuple[str, ...]]) -> None: + assert keypoints_with_empty_individual(_labels(keypoints)) == () diff --git a/tests/io/labeled_data/test_file.py b/tests/io/labeled_data/test_file.py new file mode 100644 index 0000000..fcc9500 --- /dev/null +++ b/tests/io/labeled_data/test_file.py @@ -0,0 +1,200 @@ +from pathlib import Path + +import dlc_octopus.io.labeled_data as labeled_data +import pandas as pd +import pytest +from dlc_octopus.io.errors import UnreadableFileError +from dlc_octopus.io.labeled_data import LabeledData, LabeledDataFile, read_labeled_data, write_labeled_data +from dlc_octopus.io.labeled_data.wide.storage import WideLabeledDataStorage, read_wide_labeled_data + +FIXTURES_DIR = Path(__file__).parents[1] / "fixtures" / "labeled_data" +FIXTURES = sorted(path.name for path in FIXTURES_DIR.glob("*") if path.suffix in {".h5", ".csv"}) + + +def _wide_columns() -> pd.MultiIndex: + return pd.MultiIndex.from_product([["Sc"], ["nose", "tail"], ["x", "y"]], names=["scorer", "bodyparts", "coords"]) + + +def test_every_fixture_is_found() -> None: + # Control: an empty glob would let the parametrized test below pass by running nothing. + assert len(FIXTURES) == 10 + + +@pytest.mark.parametrize("filename", FIXTURES) +def test_every_fixture_reads_as_its_wide_storage_interprets_it(filename: str) -> None: + path = FIXTURES_DIR / filename + + labels = read_labeled_data(path) + storage = read_wide_labeled_data(path) + + assert labels.path == path + assert isinstance(labels._stored, WideLabeledDataStorage) + assert (labels.keypoints, labels.frames) == (storage.keypoints, storage.frames) + assert labels.keypoints is not None + assert labels.frames is not None + + +def _read_written(tmp_path: Path, frame: pd.DataFrame) -> LabeledDataFile: + path = tmp_path / "CollectedData_Sc.h5" + frame.to_hdf(path, key="df_with_missing", mode="w") + return read_labeled_data(path) + + +def test_frames_are_kept_when_the_header_is_unrecognised(tmp_path: Path) -> None: + frame = pd.DataFrame([[1.0, 2.0]], columns=["nose_x", "nose_y"], index=["labeled-data/v1/img0.png"]) + + labels = _read_written(tmp_path, frame) + + assert labels.keypoints is None + assert labels.frames == (("labeled-data", "v1", "img0.png"),) + + +def test_keypoints_are_kept_when_the_row_index_is_unrecognised(tmp_path: Path) -> None: + labels = _read_written(tmp_path, pd.DataFrame([[1.0, 2.0, 3.0, 4.0]], columns=_wide_columns())) + + assert labels.frames is None + assert labels.keypoints is not None + assert [keypoint.bodypart for keypoint in labels.keypoints] == ["nose", "tail"] + + +def test_read_errors_propagate_unchanged(tmp_path: Path) -> None: + with pytest.raises(UnreadableFileError): + read_labeled_data(tmp_path / "missing.csv") + with pytest.raises(ValueError, match=r"'\.txt'"): + read_labeled_data(tmp_path / "CollectedData_Sc.txt") + + +def test_two_reads_of_one_file_are_distinct_and_hashable() -> None: + first, second = (read_labeled_data(FIXTURES_DIR / "single_animal_human.h5") for _ in range(2)) + + assert first != second + assert len({first, second}) == 2 + + +def test_the_package_exports_exactly_the_consumer_surface() -> None: + assert sorted(labeled_data.__all__) == [ + "BodypartScope", + "FramePath", + "Keypoint", + "LABELED_DATA_LONG_VERSION", + "LabeledData", + "LabeledDataArrays", + "LabeledDataFile", + "read_labeled_data", + "write_labeled_data", + ] + assert labeled_data.LabeledDataFile is LabeledDataFile + + +def test_a_labeled_data_file_yields_arrays_of_every_frame_and_keypoint() -> None: + labels = read_labeled_data(FIXTURES_DIR / "single_animal_human.h5") + + arrays = labels.labeled_data.to_arrays() + + assert labels.frames is not None + assert labels.keypoints is not None + assert arrays.xy.shape == (len(labels.frames), len(labels.keypoints), 2) + assert arrays.labeled.size == len(labels.frames) * len(labels.keypoints) > 0 + + +def test_a_legacy_labeled_data_file_is_written_back_in_the_current_deeplabcut_form(tmp_path: Path) -> None: + table = read_labeled_data(FIXTURES_DIR / "single_animal_human_legacy_index.h5").labeled_data + + path = tmp_path / "CollectedData_Sc.h5" + write_labeled_data(table, path, replaces=None) + + with pd.HDFStore(path, mode="r") as store: + assert list(store.keys()) == ["/df_with_missing"] + written = pd.read_hdf(path, key="df_with_missing") + assert written.columns.nlevels == 3 + assert isinstance(written.index, pd.MultiIndex) + assert written.index[0] == ("labeled-data", "session-03", "img000.png") + + +H5_FIXTURES = [name for name in FIXTURES if name.endswith(".h5") and name != "ambiguous_multi_key.h5"] + + +def test_the_ambiguous_fixture_is_the_one_h5_left_out() -> None: + # Control: keyless read_hdf refuses a file with several keys, so the comparison below cannot include it. + with pytest.raises(ValueError, match="key must be provided"): + pd.read_hdf(FIXTURES_DIR / "ambiguous_multi_key.h5") + assert len(H5_FIXTURES) == 7 + + +@pytest.mark.parametrize("filename", H5_FIXTURES) +def test_the_raw_wide_view_is_what_read_hdf_returns(filename: str) -> None: + # The swap-in guarantee: replacing pd.read_hdf(path) with read_labeled_data(path).to_raw_wide_df() changes nothing. + path = FIXTURES_DIR / filename + + pd.testing.assert_frame_equal(read_labeled_data(path).to_raw_wide_df(), pd.read_hdf(path), check_exact=True) + + +def test_the_raw_wide_view_is_a_copy() -> None: + labels = read_labeled_data(FIXTURES_DIR / "single_animal_human.h5") + + view = labels.to_raw_wide_df() + view.iloc[0, 0] = -99.0 + + assert labels.to_raw_wide_df().iloc[0, 0] != -99.0 + + +@pytest.mark.parametrize("filename", FIXTURES) +def test_every_fixture_has_labeled_data_with_one_row_per_frame_and_keypoint(filename: str) -> None: + labels = read_labeled_data(FIXTURES_DIR / filename) + + assert labels.frames is not None + assert labels.keypoints is not None + assert len(labels.labeled_data.to_long_df()) == len(labels.frames) * len(labels.keypoints) + + +def test_a_file_without_a_model_names_itself_and_the_reason(tmp_path: Path) -> None: + index = pd.MultiIndex.from_tuples([("labeled-data", "v1", "extra", "img0.png")]) + labels = _read_written(tmp_path, pd.DataFrame([[1.0, 2.0, 3.0, 4.0]], index=index, columns=_wide_columns())) + + with pytest.raises(ValueError, match=r"CollectedData_Sc\.h5: .*has 4 parts"): + _ = labels.labeled_data + assert labels.to_raw_wide_df().shape == (1, 4) + + +def test_the_package_exports_the_long_model() -> None: + from dlc_octopus.io.labeled_data.long.model import LabeledData as Model + + assert LabeledData is Model + + +@pytest.mark.parametrize("filename", FIXTURES) +def test_the_raw_table_and_the_written_table_both_give_back_the_read_labels(filename: str) -> None: + # from_wide_df interprets any wide form as a read does: the raw table as found, and the converged one written. + labels = read_labeled_data(FIXTURES_DIR / filename) + model = labels.labeled_data.to_long_df() + + from_raw = LabeledData.from_wide_df(labels.to_raw_wide_df()).to_long_df() + from_written = LabeledData.from_wide_df(labels.labeled_data.to_wide_df()).to_long_df() + + pd.testing.assert_frame_equal(from_raw, model) + pd.testing.assert_frame_equal(from_written, model) + + +def test_a_wide_table_without_a_model_is_refused_with_the_facts() -> None: + columns = pd.MultiIndex.from_tuples([("Sc", "nose", "x")], names=["scorer", "bodypart", "coord"]) + + with pytest.raises(ValueError, match="Header levels"): + LabeledData.from_wide_df(pd.DataFrame([[1.0]], index=["labeled-data/v1/img0.png"], columns=columns)) + + +@pytest.mark.parametrize("filename", ["single_animal_human.h5", "multi_animal_unique_bodyparts.csv"]) +def test_a_file_exposes_its_stored_facts_read_only(filename: str) -> None: + labels = read_labeled_data(FIXTURES_DIR / filename) + stored = labels._stored + + assert labels.key_selection is stored.key_selection + assert (labels.writer_stamp, labels.writer_stamp_error) == (stored.writer_stamp, stored.writer_stamp_error) + assert (labels.raw_header, labels.raw_row_index) == (stored.header, stored.row_index) + with pytest.raises(AttributeError): + labels.raw_header = stored.header # type: ignore[misc] + + +def test_an_h5_file_has_a_key_selection_and_a_csv_none() -> None: + # Control for the identity checks above: a fact that differs by container is not trivially None. + assert read_labeled_data(FIXTURES_DIR / "single_animal_human.h5").key_selection is not None + assert read_labeled_data(FIXTURES_DIR / "multi_animal_unique_bodyparts.csv").key_selection is None diff --git a/tests/io/labeled_data/test_write.py b/tests/io/labeled_data/test_write.py new file mode 100644 index 0000000..28a91c5 --- /dev/null +++ b/tests/io/labeled_data/test_write.py @@ -0,0 +1,415 @@ +import os +import pickle +import stat +import warnings +from collections.abc import Iterator +from importlib.metadata import version +from pathlib import Path + +import numpy as np +import pandas as pd +import pytest +import tables +from dlc_octopus.io import FileChangedError, FileStat +from dlc_octopus.io.labeled_data import LabeledData, read_labeled_data, write_labeled_data +from dlc_octopus.io.labeled_data.checks.file import frames_lost_to_csv +from dlc_octopus.io.labeled_data.wide.storage import csv_twin +from dlc_octopus.io.stamp import WRITER_KEY, WRITER_VERSION_KEY, WriterStamp + +FIXTURES_DIR = Path(__file__).parents[1] / "fixtures" / "labeled_data" +FIXTURES = sorted(path.name for path in FIXTURES_DIR.glob("*") if path.suffix in {".h5", ".csv"}) + + +def _table(path: Path) -> LabeledData: + return read_labeled_data(path).labeled_data + + +def _labels_path(tmp_path: Path, table: LabeledData) -> Path: + # Human labels never carry a likelihood, so labels that have one are written as machine labels. + return tmp_path / ("machinelabels-iter0.h5" if table.has_likelihood else "CollectedData_Sc.h5") + + +def _without_likelihood(table: LabeledData) -> LabeledData: + return LabeledData.from_long_df(table.to_long_df().drop(columns="likelihood")) + + +def _assert_same(first: LabeledData, second: LabeledData) -> None: + a, b = first.to_arrays(), second.to_arrays() + assert (a.frames, a.keypoints) == (b.frames, b.keypoints) + np.testing.assert_array_equal(a.xy, b.xy) + assert (a.likelihood is None) == (b.likelihood is None) + if a.likelihood is not None and b.likelihood is not None: + np.testing.assert_array_equal(a.likelihood, b.likelihood) + + +def test_every_fixture_is_found() -> None: + # Control: an empty glob would let the round trip below pass by running nothing. + assert len(FIXTURES) == 10 + + +@pytest.mark.parametrize("filename", FIXTURES) +def test_every_fixture_is_written_and_read_back_unchanged(tmp_path: Path, filename: str) -> None: + table = _table(FIXTURES_DIR / filename) + path = _labels_path(tmp_path, table) + + write_labeled_data(table, path, replaces=None) + + _assert_same(_table(path), table) + with pd.HDFStore(path, mode="r") as store: + assert list(store.keys()) == ["/df_with_missing"] + + +@pytest.mark.parametrize("filename", FIXTURES) +def test_the_csv_twin_reads_back_as_the_same_table_within_float_formatting(tmp_path: Path, filename: str) -> None: + table = _table(FIXTURES_DIR / filename) + path = _labels_path(tmp_path, table) + + write_labeled_data(table, path, replaces=None) + + twin, arrays = _table(path.with_suffix(".csv")).to_arrays(), table.to_arrays() + assert (twin.frames, twin.keypoints) == (arrays.frames, arrays.keypoints) + np.testing.assert_allclose(twin.xy, arrays.xy, rtol=1e-12, equal_nan=True) + + +def _without_values(table: LabeledData, frame: int) -> LabeledData: + long = table.to_long_df() + long.loc[long["frame_index"] == frame, ["x", "y"]] = np.nan + return LabeledData.from_long_df(long) + + +@pytest.mark.parametrize("empty", [None, 0, 1], ids=["none", "first", "second"]) +def test_frames_lost_to_csv_are_the_frames_pandas_reads_back_without(tmp_path: Path, empty: int | None) -> None: + table = _table(FIXTURES_DIR / "single_animal_human.h5") + frame = (table if empty is None else _without_values(table, empty)).to_wide_df() + frame.to_csv(tmp_path / "labels.csv") + + back = pd.read_csv(tmp_path / "labels.csv", index_col=[0, 1, 2], header=[0, 1, 2]) + + assert list(frames_lost_to_csv(frame)) == [entry for entry in frame.index if entry not in back.index] + + +def test_a_first_frame_without_values_is_kept_in_the_h5_with_a_warning_that_the_csv_twin_loses_it( + tmp_path: Path, +) -> None: + table = _without_values(_table(FIXTURES_DIR / "single_animal_human.h5"), 0) + path = tmp_path / "CollectedData_Sc.h5" + + with pytest.warns(UserWarning, match="reads back without it") as caught: + write_labeled_data(table, path, replaces=None) + + assert _table(path).to_arrays().frames == table.to_arrays().frames + assert [Path(warning.filename) for warning in caught] == [Path(__file__)] + + +def test_a_write_whose_csv_twin_keeps_every_frame_warns_nothing(tmp_path: Path) -> None: + # Control for the warning above. + table = _without_values(_table(FIXTURES_DIR / "single_animal_human.h5"), 1) + + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + write_labeled_data(table, tmp_path / "CollectedData_Sc.h5", replaces=None) + + assert [warning for warning in caught if "reads back without" in str(warning.message)] == [] + + +@pytest.mark.xfail( + reason="the CSV twin loses a first frame without values, as pandas and DeepLabCut read it as the row index's " + "names; owed: a CSV form that keeps it, adopted with DeepLabCut and napari-deeplabcut", + strict=True, + raises=AssertionError, +) +def test_the_csv_twin_keeps_a_first_frame_without_values(tmp_path: Path) -> None: + table = _without_values(_table(FIXTURES_DIR / "single_animal_human.h5"), 0) + path = tmp_path / "CollectedData_Sc.h5" + with warnings.catch_warnings(): + warnings.simplefilter("ignore", UserWarning) + write_labeled_data(table, path, replaces=None) + + assert _table(path.with_suffix(".csv")).to_arrays().frames == table.to_arrays().frames + + +def test_a_written_file_carries_the_writer_stamp_and_a_fixture_does_not(tmp_path: Path) -> None: + path = tmp_path / "CollectedData_Sc.h5" + write_labeled_data(_table(FIXTURES_DIR / "single_animal_human.h5"), path, replaces=None) + + stored = read_labeled_data(path) + fixture = read_labeled_data(FIXTURES_DIR / "single_animal_human.h5") + + assert stored.writer_stamp == WriterStamp("dlc_octopus.io.labeled_data", version("dlc-octopus")) + assert fixture.writer_stamp is None + assert (stored.writer_stamp_error, fixture.writer_stamp_error) == (None, None) + + +def test_the_stamp_is_stored_as_plain_strings_never_as_a_pickle(tmp_path: Path) -> None: + path = tmp_path / "CollectedData_Sc.h5" + write_labeled_data(_table(FIXTURES_DIR / "single_animal_human.h5"), path, replaces=None) + stamp = WriterStamp.current("dlc_octopus.io.labeled_data") + + raw = path.read_bytes() + with tables.open_file(str(path)) as h5: + attributes = h5.get_node("/df_with_missing")._v_attrs + stored = {name: attributes[name] for name in stamp.as_metadata()} + + assert all(type(value) is np.str_ for value in stored.values()) + for protocol in range(pickle.HIGHEST_PROTOCOL + 1): + for value in (stamp.as_metadata(), *stamp.as_metadata().values()): + assert pickle.dumps(value, protocol=protocol) not in raw + + +@pytest.mark.parametrize("damage", ["wrong_type", "one_key_missing"]) +def test_a_file_with_a_malformed_stamp_is_read_and_the_stamp_reported(tmp_path: Path, damage: str) -> None: + path = tmp_path / "CollectedData_Sc.h5" + written = _table(FIXTURES_DIR / "single_animal_human.h5") + write_labeled_data(written, path, replaces=None) + with tables.open_file(str(path), mode="a") as h5: + attributes = h5.get_node("/df_with_missing")._v_attrs + if damage == "wrong_type": + attributes[WRITER_VERSION_KEY] = 1 + else: + del attributes[WRITER_KEY] + + stored = read_labeled_data(path) + + assert stored.writer_stamp is None + assert stored.writer_stamp_error is not None + assert str(path) in stored.writer_stamp_error + assert "malformed writer stamp" in stored.writer_stamp_error + _assert_same(_table(path), written) + + +def test_the_stamp_is_invisible_to_a_plain_pandas_read(tmp_path: Path) -> None: + table = _table(FIXTURES_DIR / "multi_animal_machine.h5") + path = tmp_path / "machinelabels-iter0.h5" + + write_labeled_data(table, path, replaces=None) + + arrays = table.to_arrays() + assert pd.read_hdf(path).shape == (len(arrays.frames), len(arrays.keypoints) * 3) + + +def test_a_file_that_exists_is_not_replaced_without_its_stat(tmp_path: Path) -> None: + path = tmp_path / "CollectedData_Sc.h5" + path.write_bytes(b"someone else's file") + + with pytest.raises(FileExistsError): + write_labeled_data(_table(FIXTURES_DIR / "single_animal_human.h5"), path, replaces=None) + + assert path.read_bytes() == b"someone else's file" + + +def test_a_file_changed_since_it_was_read_is_not_replaced(tmp_path: Path) -> None: + path = tmp_path / "CollectedData_Sc.h5" + write_labeled_data(_table(FIXTURES_DIR / "single_animal_human.h5"), path, replaces=None) + labels = read_labeled_data(path) + with path.open("ab") as stream: + stream.write(b"\0") # someone else's change after our read + changed = path.read_bytes() + + with pytest.raises(FileChangedError, match=path.name): + write_labeled_data(_table(FIXTURES_DIR / "multi_animal_human.h5"), path, replaces=labels.stat) + + assert path.read_bytes() == changed + assert sorted(p.name for p in tmp_path.iterdir()) == ["CollectedData_Sc.csv", "CollectedData_Sc.h5"] + + +def test_a_file_removed_since_it_was_read_is_not_recreated(tmp_path: Path) -> None: + path = tmp_path / "CollectedData_Sc.h5" + write_labeled_data(_table(FIXTURES_DIR / "single_animal_human.h5"), path, replaces=None) + stat = read_labeled_data(path).stat + path.unlink() + + with pytest.raises(FileChangedError, match="removed"): + write_labeled_data(_table(FIXTURES_DIR / "single_animal_human.h5"), path, replaces=stat) + + assert not path.exists() + + +def test_a_file_unchanged_since_it_was_read_is_replaced_and_the_new_stat_is_returned(tmp_path: Path) -> None: + # Control for the two refusals above: with the right stat, the write goes through. + path = tmp_path / "CollectedData_Sc.h5" + write_labeled_data(_table(FIXTURES_DIR / "single_animal_human.h5"), path, replaces=None) + labels = read_labeled_data(path) + machine = _without_likelihood(_table(FIXTURES_DIR / "single_animal_machine.h5")) + + new_stat = write_labeled_data(machine, path, replaces=labels.stat) + + _assert_same(_table(path), machine) + assert new_stat == FileStat.of(path) + assert new_stat != labels.stat + + +def test_a_human_labels_file_is_never_written_with_a_likelihood(tmp_path: Path) -> None: + machine = _table(FIXTURES_DIR / "single_animal_machine.h5") + assert machine.has_likelihood + + with pytest.raises(ValueError, match="likelihood"): + write_labeled_data(machine, tmp_path / "CollectedData_Sc.h5", replaces=None) + + assert list(tmp_path.iterdir()) == [] + + +def test_a_human_labels_file_takes_labels_whose_likelihood_the_caller_dropped(tmp_path: Path) -> None: + path = tmp_path / "CollectedData_Sc.h5" + machine = _table(FIXTURES_DIR / "single_animal_machine.h5") + + write_labeled_data(_without_likelihood(machine), path, replaces=None) + + assert not _table(path).has_likelihood + + +def test_a_machine_labels_file_keeps_its_likelihood(tmp_path: Path) -> None: + # Control for the refusal above: the rule is about human labels, not about likelihood. + path = tmp_path / "machinelabels-iter0.h5" + machine = _table(FIXTURES_DIR / "single_animal_machine.h5") + + write_labeled_data(machine, path, replaces=None) + + _assert_same(_table(path), machine) + + +def test_an_empty_individual_name_is_refused_and_touches_nothing(tmp_path: Path) -> None: + wide = _table(FIXTURES_DIR / "multi_animal_human.h5").to_wide_df() + unnamed = LabeledData.from_wide_df(wide.rename(columns={"animalA": ""}, level="individuals")) + + with pytest.raises(ValueError, match="empty individual"): + write_labeled_data(unnamed, tmp_path / "CollectedData_Sc.h5", replaces=None) + + assert list(tmp_path.iterdir()) == [] + + +def test_a_file_holding_several_keys_is_not_replaced_and_the_dropped_keys_are_named(tmp_path: Path) -> None: + path = tmp_path / "CollectedData_Sc.h5" + path.write_bytes((FIXTURES_DIR / "ambiguous_multi_key.h5").read_bytes()) + labels = read_labeled_data(path) + before = path.read_bytes() + + with pytest.raises(ValueError, match=r"\['keypoints'\].*drop"): + write_labeled_data(labels.labeled_data, path, replaces=labels.stat) + + assert path.read_bytes() == before + assert [p.name for p in tmp_path.iterdir()] == ["CollectedData_Sc.h5"] + + +def test_a_file_holding_one_legacy_key_is_replaced_under_the_current_key(tmp_path: Path) -> None: + # Control for the refusal above: a single key is converted, never dropped alongside another. + path = tmp_path / "CollectedData_Sc.h5" + pd.read_hdf(FIXTURES_DIR / "single_animal_human.h5").to_hdf(path, key="keypoints", mode="w") + labels = read_labeled_data(path) + + write_labeled_data(labels.labeled_data, path, replaces=labels.stat) + + with pd.HDFStore(path, mode="r") as store: + assert list(store.keys()) == ["/df_with_missing"] + _assert_same(_table(path), labels.labeled_data) + + +@pytest.mark.parametrize(("name", "twin"), [("x.h5", "x.csv"), ("x.H5", "x.CSV")]) +def test_the_csv_twin_takes_the_case_of_the_h5_suffix(name: str, twin: str) -> None: + # Compare names: WindowsPath equality ignores case, so comparing paths could not fail on Windows. + assert csv_twin(Path(name)).name == twin + + +def test_an_upper_case_h5_is_written_read_and_replaced_with_its_twin_in_the_same_case(tmp_path: Path) -> None: + table = _table(FIXTURES_DIR / "single_animal_human.h5") + path = tmp_path / "CollectedData_Sc.H5" + + write_labeled_data(table, path, replaces=None) + write_labeled_data(table, path, replaces=read_labeled_data(path).stat) + + assert sorted(entry.name for entry in tmp_path.iterdir()) == ["CollectedData_Sc.CSV", "CollectedData_Sc.H5"] + _assert_same(_table(path), table) + assert _table(tmp_path / "CollectedData_Sc.CSV").to_arrays().keypoints == table.to_arrays().keypoints + + +def test_only_an_h5_path_is_written(tmp_path: Path) -> None: + with pytest.raises(ValueError, match=r"'\.csv'"): + write_labeled_data(_table(FIXTURES_DIR / "single_animal_human.h5"), tmp_path / "x.csv", replaces=None) + + assert list(tmp_path.iterdir()) == [] + + +def test_a_file_without_a_stat_is_read_but_cannot_be_replaced(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + path = tmp_path / "CollectedData_Sc.h5" + write_labeled_data(_table(FIXTURES_DIR / "single_animal_human.h5"), path, replaces=None) + before = path.read_bytes() + + def no_stat(_path: Path) -> FileStat: + raise PermissionError("stat denied") + + with monkeypatch.context() as patch: + patch.setattr(FileStat, "of", no_stat) + labels = read_labeled_data(path) + + assert labels.stat is None + assert labels.keypoints is not None + with pytest.raises(FileExistsError): + write_labeled_data(_table(FIXTURES_DIR / "multi_animal_human.h5"), path, replaces=labels.stat) + assert path.read_bytes() == before + + +def test_files_beside_the_target_survive_a_write(tmp_path: Path) -> None: + path = tmp_path / "CollectedData_Sc.h5" + bystanders = [tmp_path / ".CollectedData_Sc.tmp.h5", tmp_path / ".CollectedData_Sc.tmp.csv"] + for bystander in bystanders: + bystander.write_bytes(b"not ours") + + write_labeled_data(_table(FIXTURES_DIR / "single_animal_human.h5"), path, replaces=None) + + assert [bystander.read_bytes() for bystander in bystanders] == [b"not ours", b"not ours"] + assert sorted(p.name for p in tmp_path.iterdir()) == sorted( + ["CollectedData_Sc.h5", "CollectedData_Sc.csv", *(bystander.name for bystander in bystanders)] + ) + + +def test_reading_records_the_stat_taken_before_the_read(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + from dlc_octopus.io.labeled_data.wide import storage + + path = tmp_path / "CollectedData_Sc.h5" + path.write_bytes((FIXTURES_DIR / "single_animal_human.h5").read_bytes()) + before = FileStat.of(path) + read = storage.read_wide_labeled_data + + def read_then_change(source: Path) -> storage.WideLabeledDataStorage: + stored = read(source) + with source.open("ab") as stream: + stream.write(b"\0") + return stored + + monkeypatch.setattr(storage, "read_wide_labeled_data", read_then_change) + + assert read_labeled_data(path).stat == before + assert FileStat.of(path) != before + + +def _mode(path: Path) -> int: + return stat.S_IMODE(path.stat().st_mode) + + +@pytest.fixture +def group_umask() -> Iterator[None]: + previous = os.umask(0o002) + yield + os.umask(previous) + + +@pytest.mark.skipif(os.name != "posix", reason="permission bits are POSIX") +@pytest.mark.usefixtures("group_umask") +def test_a_new_file_and_its_twin_get_the_umask_default(tmp_path: Path) -> None: + path = tmp_path / "CollectedData_Sc.h5" + + write_labeled_data(_table(FIXTURES_DIR / "single_animal_human.h5"), path, replaces=None) + + assert (_mode(path), _mode(csv_twin(path))) == (0o664, 0o664) + + +@pytest.mark.skipif(os.name != "posix", reason="permission bits are POSIX") +@pytest.mark.usefixtures("group_umask") +def test_a_replaced_file_and_its_twin_keep_their_modes(tmp_path: Path) -> None: + path = tmp_path / "CollectedData_Sc.h5" + write_labeled_data(_table(FIXTURES_DIR / "single_animal_human.h5"), path, replaces=None) + path.chmod(0o640) + csv_twin(path).chmod(0o604) + + write_labeled_data(_table(FIXTURES_DIR / "multi_animal_human.h5"), path, replaces=read_labeled_data(path).stat) + + assert (_mode(path), _mode(csv_twin(path))) == (0o640, 0o604) diff --git a/tests/io/labeled_data/wide/test_from_long.py b/tests/io/labeled_data/wide/test_from_long.py new file mode 100644 index 0000000..f36d100 --- /dev/null +++ b/tests/io/labeled_data/wide/test_from_long.py @@ -0,0 +1,87 @@ +from pathlib import Path + +import numpy as np +import pandas as pd +import pytest +from dlc_octopus.io.labeled_data.long.model import LabeledData +from dlc_octopus.io.labeled_data.wide.from_long import long_to_wide +from dlc_octopus.io.labeled_data.wide.storage import read_wide_labeled_data +from dlc_octopus.io.labeled_data.wide.to_long import wide_frame_to_long, wide_to_long + +FIXTURES_DIR = Path(__file__).parents[2] / "fixtures" / "labeled_data" +FIXTURES = sorted(path.name for path in FIXTURES_DIR.glob("*") if path.suffix in {".h5", ".csv"}) +SINGLE_ANIMAL_LEVELS = ["scorer", "bodyparts", "coords"] +MULTI_ANIMAL_LEVELS = ["scorer", "individuals", "bodyparts", "coords"] +PARTS = pd.MultiIndex.from_tuples([("labeled-data", "s1", "img0.png"), ("labeled-data", "s1", "img1.png")]) + + +def _labels(columns: list[tuple[str, ...]], rows: list[list[float]], index: object, names: list[str]) -> LabeledData: + frame = pd.DataFrame(rows, columns=pd.MultiIndex.from_tuples(columns, names=names), index=index) + return wide_frame_to_long(frame) + + +def _single_animal_columns(coords: tuple[str, ...] = ("x", "y")) -> list[tuple[str, ...]]: + return [("Sc", bodypart, coord) for bodypart in ("nose", "tail") for coord in coords] + + +def test_every_fixture_is_found() -> None: + # Control: an empty glob would let the parametrized test below pass by running nothing. + assert len(FIXTURES) == 10 + + +@pytest.mark.parametrize("name", FIXTURES) +def test_every_fixture_round_trips_through_wide(name: str) -> None: + storage = read_wide_labeled_data(FIXTURES_DIR / name) + long = wide_to_long(storage.dataframe, storage.header, storage.row_index) + + wide = long_to_wide(long) + pd.testing.assert_frame_equal(wide_frame_to_long(wide).to_long_df(), long.to_long_df()) + + +def test_the_wide_table_is_deeplabcuts_current_form() -> None: + # Control for the tests below: the exact table DeepLabCut writes, built by hand. + rows = [[1.0, 2.0, 3.0, np.nan], [5.0, 6.0, 7.0, 8.0]] + expected = pd.DataFrame( + rows, index=PARTS, columns=pd.MultiIndex.from_tuples(_single_animal_columns(), names=SINGLE_ANIMAL_LEVELS) + ) + + wide = long_to_wide(_labels(_single_animal_columns(), rows, PARTS, SINGLE_ANIMAL_LEVELS)) + + pd.testing.assert_frame_equal(wide, expected) + + +def test_levels_are_plain_text_never_categorical() -> None: + wide = long_to_wide(_labels(_single_animal_columns(), [[1.0, 2.0, 3.0, 4.0]] * 2, PARTS, SINGLE_ANIMAL_LEVELS)) + + levels = [*wide.index.levels, *wide.columns.levels] + + assert not any(isinstance(level.dtype, pd.CategoricalDtype) for level in levels) + assert all(isinstance(value, str) for level in levels for value in level) + + +def test_flat_paths_are_written_as_path_parts() -> None: + flat = ["labeled-data/s1/img0.png", "labeled-data/s1/img1.png"] + + wide = long_to_wide(_labels(_single_animal_columns(), [[1.0, 2.0, 3.0, 4.0]] * 2, flat, SINGLE_ANIMAL_LEVELS)) + + assert wide.index.equals(PARTS) + + +def test_a_reordered_header_is_written_one_keypoint_at_a_time_in_coordinate_order() -> None: + columns = [("Sc", "nose", "y"), ("Sc", "tail", "x"), ("Sc", "nose", "x"), ("Sc", "tail", "y")] + + wide = long_to_wide(_labels(columns, [[2.0, 3.0, 1.0, 4.0]], PARTS[:1], SINGLE_ANIMAL_LEVELS)) + + assert list(wide.columns) == _single_animal_columns() + assert wide.to_numpy().tolist() == [[1.0, 2.0, 3.0, 4.0]] + + +def test_multi_animal_labels_with_likelihood_get_four_levels_and_three_coordinates() -> None: + columns = [("Sc", "mouse1", "nose", coord) for coord in ("x", "y", "likelihood")] + columns += [("Sc", "single", "box", coord) for coord in ("x", "y", "likelihood")] + + wide = long_to_wide(_labels(columns, [[1.0, 2.0, 0.5, 3.0, 4.0, 0.25]], PARTS[:1], MULTI_ANIMAL_LEVELS)) + + assert list(wide.columns.names) == MULTI_ANIMAL_LEVELS + assert list(wide.columns) == columns + assert wide.to_numpy().tolist() == [[1.0, 2.0, 0.5, 3.0, 4.0, 0.25]] diff --git a/tests/io/labeled_data/wide/test_storage.py b/tests/io/labeled_data/wide/test_storage.py new file mode 100644 index 0000000..4ea16c4 --- /dev/null +++ b/tests/io/labeled_data/wide/test_storage.py @@ -0,0 +1,215 @@ +import shutil +from pathlib import Path + +import pandas as pd +import pytest +from dlc_octopus.io.errors import UnreadableFileError +from dlc_octopus.io.labeled_data import LabeledData +from dlc_octopus.io.labeled_data.wide.csv import read_labeled_data_csv +from dlc_octopus.io.labeled_data.wide.h5 import read_labeled_data_h5 +from dlc_octopus.io.labeled_data.wide.storage import WideLabeledDataStorage, read_wide_labeled_data +from dlc_octopus.io.labeled_data.wide.table import LabeledDataRead, classify_labeled_data_read +from dlc_octopus.io.labeled_data.wide.to_long import wide_to_long + +FIXTURES_DIR = Path(__file__).parents[2] / "fixtures" / "labeled_data" +FIXTURES = sorted(path.name for path in FIXTURES_DIR.glob("*") if path.suffix in {".h5", ".csv"}) +CONTAINER_READERS = {".h5": read_labeled_data_h5, ".csv": read_labeled_data_csv} + + +def _wide_columns() -> pd.MultiIndex: + return pd.MultiIndex.from_product([["Sc"], ["nose", "tail"], ["x", "y"]], names=["scorer", "bodyparts", "coords"]) + + +def _write_h5(path: Path, frame: pd.DataFrame) -> Path: + frame.to_hdf(path, key="df_with_missing", mode="w") + return path + + +def test_every_fixture_is_found() -> None: + # Control: an empty glob would let the parametrized tests below pass by running nothing. + assert [Path(name).suffix for name in FIXTURES].count(".h5") == 8 + assert [Path(name).suffix for name in FIXTURES].count(".csv") == 2 + + +@pytest.mark.parametrize("filename", FIXTURES) +def test_every_fixture_is_interpreted_as_its_container_read_classifies_it(filename: str) -> None: + path = FIXTURES_DIR / filename + read = CONTAINER_READERS[path.suffix](path) + header, row_index = classify_labeled_data_read(read) + + storage = read_wide_labeled_data(path) + + assert storage.keypoints == tuple(columns.keypoint for columns in header.keypoints) + assert storage.frames == row_index.frames + assert storage.keypoints is not None + assert storage.frames is not None + assert storage.key_selection == read.key_selection + pd.testing.assert_frame_equal(storage.dataframe, read.dataframe) + + +@pytest.mark.parametrize("filename", [name for name in FIXTURES if name.endswith(".csv")]) +def test_a_csv_is_interpreted_as_its_h5_twin(filename: str) -> None: + csv_storage = read_wide_labeled_data(FIXTURES_DIR / filename) + h5_storage = read_wide_labeled_data((FIXTURES_DIR / filename).with_suffix(".h5")) + + assert (csv_storage.keypoints, csv_storage.frames) == (h5_storage.keypoints, h5_storage.frames) + + +def test_an_unrecognised_header_has_no_keypoints_but_keeps_its_frames(tmp_path: Path) -> None: + frame = pd.DataFrame([[1.0, 2.0]], columns=["nose_x", "nose_y"], index=["labeled-data/v1/img0.png"]) + + storage = read_wide_labeled_data(_write_h5(tmp_path / "CollectedData_Sc.h5", frame)) + + assert storage.keypoints is None + assert storage.frames == (("labeled-data", "v1", "img0.png"),) + assert storage.header.columns == (("nose_x",), ("nose_y",)) + + +def test_an_unrecognised_row_index_has_no_frames_but_keeps_its_keypoints(tmp_path: Path) -> None: + frame = pd.DataFrame([[1.0, 2.0, 3.0, 4.0]], columns=_wide_columns()) + + storage = read_wide_labeled_data(_write_h5(tmp_path / "CollectedData_Sc.h5", frame)) + + assert storage.frames is None + assert storage.keypoints is not None + assert [keypoint.bodypart for keypoint in storage.keypoints] == ["nose", "tail"] + + +def _storage_with_folder(tmp_path: Path, folder: object) -> WideLabeledDataStorage: + index = pd.MultiIndex.from_tuples([("labeled-data", folder, "img0.png")]) + frame = pd.DataFrame([[1.0, 2.0, 3.0, 4.0]], index=index, columns=_wide_columns()) + return read_wide_labeled_data(_write_h5(tmp_path / "CollectedData_Sc.h5", frame)) + + +@pytest.mark.parametrize("folder", [2019.5, True], ids=["float", "bool"]) +def test_a_path_part_naming_no_folder_leaves_the_frames_uninterpreted_and_unconverted( + tmp_path: Path, folder: object +) -> None: + storage = _storage_with_folder(tmp_path, folder) + + assert storage.frames is None + assert storage.row_index.frames == (("labeled-data", folder, "img0.png"),) + + +def test_an_integer_path_part_is_read_as_text_and_kept_as_stored(tmp_path: Path) -> None: + # A folder named by a number, as pandas infers it from a CSV; DeepLabCut casts it back to text. + storage = _storage_with_folder(tmp_path, 2019) + + assert storage.frames == (("labeled-data", "2019", "img0.png"),) + assert storage.row_index.frames == (("labeled-data", 2019, "img0.png"),) + + +def test_the_same_path_part_as_text_is_interpreted(tmp_path: Path) -> None: + # Control: without it, frames that were never interpreted would pass the test above. + assert _storage_with_folder(tmp_path, "2019").frames == (("labeled-data", "2019", "img0.png"),) + + +@pytest.mark.parametrize(("filename", "content"), [("garbage.h5", b"not an hdf5 file"), ("missing.csv", None)]) +def test_an_unreadable_file_raises_from_the_original(tmp_path: Path, filename: str, content: bytes | None) -> None: + path = tmp_path / filename + if content is not None: + path.write_bytes(content) + + with pytest.raises(UnreadableFileError, match=filename) as raised: + read_wide_labeled_data(path) + + assert raised.value.__cause__ is not None + + +@pytest.mark.parametrize("filename", ["single_animal_legacy_index_dlc.h5", "single_animal_legacy_index_dlc.csv"]) +def test_a_suffix_in_upper_case_is_read_as_in_lower_case(tmp_path: Path, filename: str) -> None: + lower = FIXTURES_DIR / filename + upper = Path(shutil.copy(lower, tmp_path / f"{lower.stem}{lower.suffix.upper()}")) + + storage = read_wide_labeled_data(upper) + + expected = read_wide_labeled_data(lower) + assert (storage.keypoints, storage.frames) == (expected.keypoints, expected.frames) + + +def test_an_unknown_suffix_is_refused_without_reading(tmp_path: Path) -> None: + with pytest.raises(ValueError, match=r"'\.txt'"): + read_wide_labeled_data(tmp_path / "CollectedData_Sc.txt") + + +def test_two_reads_of_one_file_are_distinct_and_hashable() -> None: + first, second = (read_wide_labeled_data(FIXTURES_DIR / "single_animal_human.h5") for _ in range(2)) + + assert first != second + assert len({first, second}) == 2 + assert second not in [first] + + +def test_a_read_equals_itself() -> None: + # Control: identity equality must still hold, or the test above passes for any broken __eq__. + storage = read_wide_labeled_data(FIXTURES_DIR / "single_animal_human.h5") + + assert storage == storage + assert {storage} == {storage} + + +def _in_memory(tmp_path: Path, columns: list[tuple[str, ...]], values: list[object]) -> WideLabeledDataStorage: + # Built in memory: an H5 file cannot hold a repeated column, and the normaliser is what is under test. + names = ["scorer", "bodyparts", "coords"] + frame = pd.DataFrame( + [values], columns=pd.MultiIndex.from_tuples(columns, names=names), index=["labeled-data/v1/img0.png"] + ) + header, row_index = classify_labeled_data_read(LabeledDataRead(tmp_path / "in-memory.h5", frame, None)) + return WideLabeledDataStorage(key_selection=None, header=header, row_index=row_index, dataframe=frame) + + +def _with_coords(tmp_path: Path, coords: list[str], values: list[object]) -> WideLabeledDataStorage: + return _in_memory(tmp_path, [("Sc", "nose", c) for c in coords], values) + + +def _model(storage: WideLabeledDataStorage) -> LabeledData: + return wide_to_long(storage.dataframe, storage.header, storage.row_index) + + +@pytest.mark.parametrize( + ("coords", "values"), + [(["x", "x", "y"], [1.0, 1.5, 2.0]), (["x"], [1.0]), (["x", "y", "z"], [1.0, 2.0, 3.0])], + ids=["repeated", "missing_y", "triangulated_xyz"], # xyz: DeepLabCut 3D output, out of scope (TODO.md) +) +def test_coordinates_that_are_not_x_y_likelihood_are_not_interpreted( + tmp_path: Path, coords: list[str], values: list[object] +) -> None: + storage = _with_coords(tmp_path, coords, values) + + assert storage.keypoints is not None + with pytest.raises(ValueError, match="coordinates"): + _model(storage) + + +def test_a_likelihood_on_some_keypoints_only_is_not_interpreted(tmp_path: Path) -> None: + columns = [ + ("Sc", "nose", "x"), + ("Sc", "nose", "y"), + ("Sc", "nose", "likelihood"), + ("Sc", "tail", "x"), + ("Sc", "tail", "y"), + ] + + with pytest.raises(ValueError, match="likelihood"): + _model(_in_memory(tmp_path, columns, [1.0, 2.0, 0.9, 3.0, 4.0])) + control = _model(_in_memory(tmp_path, columns[:2] + columns[3:], [1.0, 2.0, 3.0, 4.0])) + assert control.to_arrays().xy.shape == (1, 2, 2) + + +@pytest.mark.parametrize("x", ["1.0", 1 + 2j], ids=["text", "complex"]) +def test_a_non_real_column_is_not_interpreted_or_converted(tmp_path: Path, x: object) -> None: + storage = _with_coords(tmp_path, ["x", "y"], [x, 2.0]) + + with pytest.raises(ValueError, match="not numeric"): + _model(storage) + assert storage.dataframe.iloc[0, 0] == x + + +def test_uninterpretable_frames_give_no_table(tmp_path: Path) -> None: + frame = pd.DataFrame([[1.0, 2.0, 3.0, 4.0]], columns=_wide_columns()) + + storage = read_wide_labeled_data(_write_h5(tmp_path / "CollectedData_Sc.h5", frame)) + + assert storage.frames is None + with pytest.raises(ValueError, match="not text"): + _model(storage) diff --git a/tests/io/labeled_data/wide/test_to_long.py b/tests/io/labeled_data/wide/test_to_long.py new file mode 100644 index 0000000..aaa87b4 --- /dev/null +++ b/tests/io/labeled_data/wide/test_to_long.py @@ -0,0 +1,162 @@ +from pathlib import Path + +import numpy as np +import pandas as pd +import pytest +from dlc_octopus.io.labeled_data.long.model import LabeledData +from dlc_octopus.io.labeled_data.wide.storage import read_wide_labeled_data +from dlc_octopus.io.labeled_data.wide.to_long import wide_frame_to_long, wide_to_long + +FIXTURES_DIR = Path(__file__).parents[2] / "fixtures" / "labeled_data" +FIXTURES = sorted(path.name for path in FIXTURES_DIR.glob("*") if path.suffix in {".h5", ".csv"}) +SINGLE_ANIMAL_LEVELS = ["scorer", "bodyparts", "coords"] +MULTI_ANIMAL_LEVELS = ["scorer", "individuals", "bodyparts", "coords"] + + +def _long(columns: list[tuple[str, ...]], rows: list[list[object]], index: object, names: list[str]) -> LabeledData: + # Built in memory: what is under test is the conversion, not a container. + frame = pd.DataFrame(rows, columns=pd.MultiIndex.from_tuples(columns, names=names), index=index) + return wide_frame_to_long(frame) + + +def _single_animal(rows: list[list[object]], index: object, coords: tuple[str, ...] = ("x", "y")) -> LabeledData: + columns = [("Sc", bodypart, coord) for bodypart in ("nose", "tail") for coord in coords] + return _long(columns, rows, index, SINGLE_ANIMAL_LEVELS) + + +FLAT = ["labeled-data/s1/img0.png", "labeled-data/s1/img1.png"] + + +def test_every_fixture_is_found() -> None: + # Control: an empty glob would let the parametrized test below pass by running nothing. + assert len(FIXTURES) == 10 + + +@pytest.mark.parametrize("name", FIXTURES) +def test_every_fixture_has_a_model_with_one_row_per_frame_and_keypoint(name: str) -> None: + storage = read_wide_labeled_data(FIXTURES_DIR / name) + + long = wide_to_long(storage.dataframe, storage.header, storage.row_index).to_long_df() + + assert storage.keypoints is not None + assert len(long) == len(storage.dataframe) * len(storage.keypoints) + + +def test_values_are_taken_frame_major_and_as_stored() -> None: + long = _single_animal([[1.0, 2.0, 3.0, np.nan], [5.0, 6.0, 7.0, 8.0]], FLAT).to_long_df() + + assert long[["image", "bodypart"]].astype(str).values.tolist() == [ + ["img0.png", "nose"], + ["img0.png", "tail"], + ["img1.png", "nose"], + ["img1.png", "tail"], + ] + np.testing.assert_array_equal(long[["x", "y"]].to_numpy(), [[1.0, 2.0], [3.0, np.nan], [5.0, 6.0], [7.0, 8.0]]) + + +def test_a_reordered_header_gives_the_same_model() -> None: + # Columns are taken by classified position, never by level values. + ordered = _single_animal([[1.0, 2.0, 3.0, 4.0]], FLAT[:1]).to_long_df() + columns = [("Sc", "nose", "x"), ("Sc", "tail", "y"), ("Sc", "nose", "y"), ("Sc", "tail", "x")] + + reordered = _long(columns, [[1.0, 4.0, 2.0, 3.0]], FLAT[:1], SINGLE_ANIMAL_LEVELS).to_long_df() + + pd.testing.assert_frame_equal(reordered, ordered) + + +def test_multi_animal_keeps_the_individual_and_unique_bodyparts_under_single() -> None: + columns = [("Sc", "mouse1", "nose", "x"), ("Sc", "mouse1", "nose", "y"), ("Sc", "single", "box", "x")] + columns.append(("Sc", "single", "box", "y")) + + labels = _long(columns, [[1.0, 2.0, 3.0, 4.0]], FLAT[:1], MULTI_ANIMAL_LEVELS) + + assert labels.is_multi_animal + assert labels.to_long_df()["individual"].astype(str).tolist() == ["mouse1", "single"] + + +def test_a_likelihood_is_kept_when_every_keypoint_stores_one() -> None: + labels = _single_animal([[1.0, 2.0, 0.5, 3.0, 4.0, 0.25]], FLAT[:1], coords=("x", "y", "likelihood")) + + assert labels.has_likelihood + assert labels.to_long_df()["likelihood"].tolist() == [0.5, 0.25] + + +def test_path_parts_and_flat_paths_give_the_same_frames() -> None: + parts = pd.MultiIndex.from_tuples([tuple(path.split("/")) for path in FLAT]) + rows = [[1.0, 2.0, 3.0, 4.0], [5.0, 6.0, 7.0, 8.0]] + + pd.testing.assert_frame_equal(_single_animal(rows, parts).to_long_df(), _single_animal(rows, FLAT).to_long_df()) + + +def test_an_integer_frame_part_becomes_text() -> None: + # A dataset folder named by a number; DeepLabCut's guarantee_multiindex_rows casts it the same way. + index = pd.MultiIndex.from_tuples([("labeled-data", 2019, "img0.png")]) + + long = _single_animal([[1.0, 2.0, 3.0, 4.0]], index).to_long_df() + + assert long["dataset"].astype(str).tolist() == ["2019", "2019"] + + +def test_storage_frames_and_the_long_model_agree_on_an_integer_frame_part(tmp_path: Path) -> None: + # Both read frame parts through frame_part_as_text: one policy, so the two can never disagree on a frame. + index = pd.MultiIndex.from_tuples([("labeled-data", 2019, "img0.png")]) + frame = pd.DataFrame( + [[1.0, 2.0]], + index=index, + columns=pd.MultiIndex.from_tuples([("Sc", "nose", "x"), ("Sc", "nose", "y")], names=SINGLE_ANIMAL_LEVELS), + ) + frame.to_hdf(tmp_path / "CollectedData_Sc.h5", key="df_with_missing", mode="w") + storage = read_wide_labeled_data(tmp_path / "CollectedData_Sc.h5") + + long = wide_to_long(storage.dataframe, storage.header, storage.row_index).to_long_df() + + assert storage.frames == (tuple(long.loc[0, ["folder", "dataset", "image"]].astype(str)),) + + +@pytest.mark.parametrize( + ("index", "message"), + [ + (pd.MultiIndex.from_tuples([("labeled-data", "s1", "extra", "img0.png")]), "4 parts"), + (pd.MultiIndex.from_tuples([("labeled-data", 2019.5, "img0.png")]), "neither text nor an integer"), + (pd.MultiIndex.from_tuples([("labeled-data", True, "img0.png")]), "neither text nor an integer"), + (pd.Index([0]), "entry 0 is not text"), + (pd.Index([], dtype=object), "no frames"), + ], + ids=["four_parts", "float_part", "bool_part", "integer_index", "empty"], +) +def test_a_row_index_without_three_text_parts_has_no_model(index: object, message: str) -> None: + rows = [[1.0, 2.0, 3.0, 4.0]] * len(index) + + with pytest.raises(ValueError, match=message): + _single_animal(rows, index) + + +@pytest.mark.parametrize( + ("coords", "rows", "message"), + [ + (("x", "y", "z"), [[1.0, 2.0, 3.0, 4.0, 5.0, 6.0]], "coordinates"), + (("x", "y"), [["a", 2.0, 3.0, 4.0]], "not numeric"), + ], + ids=["triangulated_xyz", "text_value"], +) +def test_values_that_are_not_x_y_likelihood_numbers_have_no_model( + coords: tuple[str, ...], rows: list[list[object]], message: str +) -> None: + with pytest.raises(ValueError, match=message): + _single_animal(rows, FLAT[:1], coords=coords) + + +def test_a_likelihood_on_some_keypoints_only_has_no_model() -> None: + columns = [("Sc", "nose", "x"), ("Sc", "nose", "y"), ("Sc", "nose", "likelihood"), ("Sc", "tail", "x")] + columns.append(("Sc", "tail", "y")) + + with pytest.raises(ValueError, match="likelihood") as raised: + _long(columns, [[1.0, 2.0, 0.5, 3.0, 4.0]], FLAT[:1], SINGLE_ANIMAL_LEVELS) + + assert "'nose'" in str(raised.value) + assert "'tail'" in str(raised.value) + + +def test_an_unrecognised_header_has_no_model() -> None: + with pytest.raises(ValueError, match="Header levels"): + _long([("Sc", "nose", "x")], [[1.0]], FLAT[:1], ["scorer", "bodypart", "coord"]) From dc4e27df14f7328f5effc7bdc6b9b12ab791fa53 Mon Sep 17 00:00:00 2001 From: C-Achard Date: Tue, 24 Nov 2026 15:42:04 +0100 Subject: [PATCH 2/4] Adapt labeled-data file reading and writing to dlccore - Rename the package to dlccore.io and add the dlccore license header - Stamp written H5 files with the writer name dlccore.io.labeled_data - Use wide_df_to_long and name DataFrames `df`, never `frame` - Add import-boundary tests: no format module or the video reader loads until imported, and only LabeledDataFile reads its storage --- dlccore/io/labeled_data/__init__.py | 19 ++++-- dlccore/io/labeled_data/file.py | 57 ++++++++++------- dlccore/io/labeled_data/wide/storage.py | 56 ++++++++++------- tests/io/labeled_data/arrays/test_arrays.py | 14 ++++- tests/io/labeled_data/test_checks.py | 28 ++++++--- tests/io/labeled_data/test_file.py | 30 ++++++--- tests/io/labeled_data/test_write.py | 34 ++++++---- tests/io/labeled_data/wide/test_from_long.py | 26 +++++--- tests/io/labeled_data/wide/test_storage.py | 54 +++++++++------- tests/io/labeled_data/wide/test_to_long.py | 26 +++++--- tests/io/test_boundaries.py | 65 +++++++++++++++++++- 11 files changed, 295 insertions(+), 114 deletions(-) diff --git a/dlccore/io/labeled_data/__init__.py b/dlccore/io/labeled_data/__init__.py index 33d06c8..b4b3831 100644 --- a/dlccore/io/labeled_data/__init__.py +++ b/dlccore/io/labeled_data/__init__.py @@ -1,13 +1,24 @@ +# +# DeepLabCut Toolbox (deeplabcut.org) +# © A. & M.W. Mathis Labs +# https://github.com/DeepLabCut/dlccore +# +# Contributors: +# https://github.com/DeepLabCut/dlccore/graphs/contributors +# +# Licensed under GNU Lesser General Public License v3.0 +# + """Labeled-data files: ``model`` holds what is true in any format, and each table format is a subpackage. Imports no format eagerly, so no format's dependencies load until a file is read or written, or that format is imported. """ -from dlc_octopus.io.labeled_data.arrays.from_long import LabeledDataArrays -from dlc_octopus.io.labeled_data.file import LabeledDataFile, read_labeled_data, write_labeled_data -from dlc_octopus.io.labeled_data.long.model import LABELED_DATA_LONG_VERSION, LabeledData -from dlc_octopus.io.labeled_data.model import BodypartScope, FramePath, Keypoint +from dlccore.io.labeled_data.arrays.from_long import LabeledDataArrays +from dlccore.io.labeled_data.file import LabeledDataFile, read_labeled_data, write_labeled_data +from dlccore.io.labeled_data.long.model import LABELED_DATA_LONG_VERSION, LabeledData +from dlccore.io.labeled_data.model import BodypartScope, FramePath, Keypoint __all__ = [ "LABELED_DATA_LONG_VERSION", diff --git a/dlccore/io/labeled_data/file.py b/dlccore/io/labeled_data/file.py index be9ecd4..079cf2d 100644 --- a/dlccore/io/labeled_data/file.py +++ b/dlccore/io/labeled_data/file.py @@ -1,3 +1,14 @@ +# +# DeepLabCut Toolbox (deeplabcut.org) +# © A. & M.W. Mathis Labs +# https://github.com/DeepLabCut/dlccore +# +# Contributors: +# https://github.com/DeepLabCut/dlccore/graphs/contributors +# +# Licensed under GNU Lesser General Public License v3.0 +# + """One labeled-data file as consumers use it, whatever layout stores it, and the read and write that move it.""" from __future__ import annotations @@ -6,17 +17,17 @@ from pathlib import Path from typing import TYPE_CHECKING -from dlc_octopus.io.file_stat import FileStat -from dlc_octopus.io.labeled_data.model import FramePath, Keypoint +from dlccore.io.file_stat import FileStat +from dlccore.io.labeled_data.model import FramePath, Keypoint if TYPE_CHECKING: import pandas as pd - from dlc_octopus.io.labeled_data.long.model import LabeledData - from dlc_octopus.io.labeled_data.wide.h5 import H5KeySelection - from dlc_octopus.io.labeled_data.wide.header import LabeledDataHeader - from dlc_octopus.io.labeled_data.wide.row_index import LabeledDataRowIndex - from dlc_octopus.io.labeled_data.wide.storage import WideLabeledDataStorage - from dlc_octopus.io.stamp import WriterStamp + from dlccore.io.labeled_data.long.model import LabeledData + from dlccore.io.labeled_data.wide.h5 import H5KeySelection + from dlccore.io.labeled_data.wide.header import LabeledDataHeader + from dlccore.io.labeled_data.wide.row_index import LabeledDataRowIndex + from dlccore.io.labeled_data.wide.storage import WideLabeledDataStorage + from dlccore.io.stamp import WriterStamp @dataclass(frozen=True) @@ -62,31 +73,31 @@ def writer_stamp(self) -> WriterStamp | None: @property def writer_stamp_error(self) -> str | None: - """Why a stamp that is present could not be read; ``None`` when there is none or it read.""" + """Any provenance reading error; ``None`` if absent.""" return self._stored.writer_stamp_error @property def raw_header(self) -> LabeledDataHeader: - """The column header as stored, classified without loss.""" + """The column header as stored, classified.""" return self._stored.header @property def raw_row_index(self) -> LabeledDataRowIndex: - """The row index as stored, classified without loss: its level names, entries and frame parts.""" + """The row index as stored, classified with level names, entries and frame parts.""" return self._stored.row_index @property def labeled_data(self) -> LabeledData: - """The labels as the model, built on each access. + """Data in long format, built on each access. Raises: ValueError: Naming the file and why it has no model, e.g. a frame of other than three parts. """ - from dlc_octopus.io.labeled_data.wide.to_long import wide_to_long + from dlccore.io.labeled_data.wide.to_long import wide_to_long try: return wide_to_long(self._stored.dataframe, self._stored.header, self._stored.row_index) @@ -94,17 +105,17 @@ def labeled_data(self) -> LabeledData: raise ValueError(f"{self.path}: {error}") from error def to_raw_wide_df(self) -> pd.DataFrame: - """A copy of the table exactly as read: for a file stored wide, what ``pd.read_hdf`` returns. + """A copy of the table as read. - Raw, never normalised: a legacy key, a flat row index or a header in another order come back as found. For - DeepLabCut's current form, use ``labeled_data.to_wide_df()``. + Raw, never normalised: legacy keys, a flat row index or a header in another order come back as found. + For DeepLabCut's current form, use ``labeled_data.to_wide_df()``. """ return self._stored.dataframe.copy() def read_labeled_data(path: Path) -> LabeledDataFile: - """Read one labeled-data file and interpret its keypoints and frames. + """Read one labeled-data file. Args: path: A ``CollectedData_*`` or ``machinelabels*`` file. @@ -114,7 +125,7 @@ def read_labeled_data(path: Path) -> LabeledDataFile: ValueError: If no reader handles the suffix. """ - from dlc_octopus.io.labeled_data.wide.storage import read_wide_labeled_data + from dlccore.io.labeled_data.wide.storage import read_wide_labeled_data try: stat = FileStat.of(path) @@ -128,13 +139,13 @@ def read_labeled_data(path: Path) -> LabeledDataFile: def write_labeled_data(labels: LabeledData, path: Path, *, replaces: FileStat | None) -> FileStat: """Write labels in DeepLabCut's current form: ``path`` (``.h5``) and its ``.csv`` twin. - Writes are atomic, and ``path`` is replaced only if it corresponds to the state described by ``replaces``. + Writes are atomic, and ``path`` is replaced only if it corresponds to the state snapshot described by ``replaces``. Args: - labels: What to write. - path: The H5 file to create or replace. Its suffix must equal ``.h5`` ignoring case. The CSV twin is + labels: Data to write. + path: H5 file to create or replace. Its suffix must equal ``.h5`` ignoring case. The CSV twin is written beside it, with suffix ``.CSV`` if ``path``'s suffix is upper case and ``.csv`` otherwise. - replaces: ``LabeledDataFile.stat`` of the file being replaced, or ``None`` to create a file that must not exist. + replaces: ``LabeledDataFile.stat`` of the file being replaced, or ``None`` to create a new file (must not already exist). Returns: The stat of the written file, to pass as ``replaces`` to the next write. @@ -153,6 +164,6 @@ def write_labeled_data(labels: LabeledData, path: Path, *, replaces: FileStat | without values, which pandas and DeepLabCut read as the row index's names. The H5 keeps it. """ - from dlc_octopus.io.labeled_data.wide.storage import write_wide_labeled_data + from dlccore.io.labeled_data.wide.storage import write_wide_labeled_data return write_wide_labeled_data(labels, path, replaces=replaces) diff --git a/dlccore/io/labeled_data/wide/storage.py b/dlccore/io/labeled_data/wide/storage.py index 036828c..8f53f49 100644 --- a/dlccore/io/labeled_data/wide/storage.py +++ b/dlccore/io/labeled_data/wide/storage.py @@ -1,3 +1,14 @@ +# +# DeepLabCut Toolbox (deeplabcut.org) +# © A. & M.W. Mathis Labs +# https://github.com/DeepLabCut/dlccore +# +# Contributors: +# https://github.com/DeepLabCut/dlccore/graphs/contributors +# +# Licensed under GNU Lesser General Public License v3.0 +# + """Labels stored wide, as DeepLabCut writes them in H5 and CSV: the table, its classification, and the read.""" from __future__ import annotations @@ -12,14 +23,15 @@ from typing import TYPE_CHECKING, cast import pandas as pd -from dlc_octopus.io.errors import FileChangedError -from dlc_octopus.io.file_stat import FileStat -from dlc_octopus.io.labeled_data.model import FramePath, Keypoint -from dlc_octopus.io.labeled_data.wide.header import LabeledDataHeader, LabeledDataHeaderShape -from dlc_octopus.io.labeled_data.wide.row_index import LabeledDataRowIndex, RowIndexShape, frame_part_as_text -from dlc_octopus.io.labeled_data.wide.table import LabeledDataRead, classify_labeled_data_read -from dlc_octopus.io.stamp import WriterStamp -from dlc_octopus.io.suffixes import ( + +from dlccore.io.errors import FileChangedError +from dlccore.io.file_stat import FileStat +from dlccore.io.labeled_data.model import FramePath, Keypoint +from dlccore.io.labeled_data.wide.header import LabeledDataHeader, LabeledDataHeaderShape +from dlccore.io.labeled_data.wide.row_index import LabeledDataRowIndex, RowIndexShape, frame_part_as_text +from dlccore.io.labeled_data.wide.table import LabeledDataRead, classify_labeled_data_read +from dlccore.io.stamp import WriterStamp +from dlccore.io.suffixes import ( CSV_SUFFIX, H5_SUFFIX, LABELED_DATA_TABLE_SUFFIXES, @@ -27,8 +39,8 @@ ) if TYPE_CHECKING: - from dlc_octopus.io.labeled_data.long.model import LabeledData - from dlc_octopus.io.labeled_data.wide.h5 import H5KeySelection + from dlccore.io.labeled_data.long.model import LabeledData + from dlccore.io.labeled_data.wide.h5 import H5KeySelection @dataclass(frozen=True, eq=False) @@ -85,13 +97,13 @@ def wide_suffix(path: Path) -> str | None: def _read_h5(path: Path) -> LabeledDataRead: - from dlc_octopus.io.labeled_data.wide.h5 import read_labeled_data_h5 + from dlccore.io.labeled_data.wide.h5 import read_labeled_data_h5 return read_labeled_data_h5(path) def _read_csv(path: Path) -> LabeledDataRead: - from dlc_octopus.io.labeled_data.wide.csv import read_labeled_data_csv + from dlccore.io.labeled_data.wide.csv import read_labeled_data_csv return read_labeled_data_csv(path) @@ -100,7 +112,7 @@ def _read_csv(path: Path) -> LabeledDataRead: def read_wide_labeled_data(path: Path) -> WideLabeledDataStorage: - """Read a wide labeled-data H5 or CSV file and classify its header and row index. + """Read a wide labeled-data H5 or CSV file and classify the header and row index. Args: path: A ``CollectedData_*`` or ``machinelabels*`` file whose suffix equals ``.h5`` or ``.csv`` ignoring case. @@ -130,7 +142,7 @@ def read_wide_labeled_data(path: Path) -> WideLabeledDataStorage: ) -WRITER_NAME = "dlc_octopus.io.labeled_data" +WRITER_NAME = "dlccore.io.labeled_data" def write_wide_labeled_data(labels: LabeledData, path: Path, *, replaces: FileStat | None) -> FileStat: @@ -163,10 +175,10 @@ def write_wide_labeled_data(labels: LabeledData, path: Path, *, replaces: FileSt UserWarning: Once both files are in place, for each frame the CSV twin reads back without. """ - from dlc_octopus.io.labeled_data.checks.file import frames_lost_to_csv, unread_h5_keys - from dlc_octopus.io.labeled_data.checks.model import keypoints_with_empty_individual, likelihood_in_human_labels - from dlc_octopus.io.labeled_data.wide.csv import write_labeled_data_csv - from dlc_octopus.io.labeled_data.wide.h5 import select_h5_key, write_labeled_data_h5 + from dlccore.io.labeled_data.checks.file import frames_lost_to_csv, unread_h5_keys + from dlccore.io.labeled_data.checks.model import keypoints_with_empty_individual, likelihood_in_human_labels + from dlccore.io.labeled_data.wide.csv import write_labeled_data_csv + from dlccore.io.labeled_data.wide.h5 import select_h5_key, write_labeled_data_h5 if suffix_in(path, frozenset({H5_SUFFIX})) is None: raise ValueError(f"{path}: the labeled-data writer writes an .h5 file and its .csv twin; got {path.suffix!r}.") @@ -182,14 +194,14 @@ def write_wide_labeled_data(labels: LabeledData, path: Path, *, replaces: FileSt if replaces is not None and path.exists() and (dropped := unread_h5_keys(select_h5_key(path))): raise ValueError(f"{path}: holds keys {list(dropped)} besides the one read; a write would drop them.") - frame = labels.to_wide_df() + df = labels.to_wide_df() temporaries: list[Path] = [] try: temporaries.append(temporary_h5 := _reserve_temporary(path, H5_SUFFIX)) temporaries.append(temporary_csv := _reserve_temporary(path, CSV_SUFFIX)) - write_labeled_data_h5(frame, temporary_h5, WriterStamp.current(WRITER_NAME)) - write_labeled_data_csv(frame, temporary_csv) + write_labeled_data_h5(df, temporary_h5, WriterStamp.current(WRITER_NAME)) + write_labeled_data_csv(df, temporary_csv) _check_unchanged(path, replaces) _keep_mode(path, temporary_h5) _keep_mode(csv_twin(path), temporary_csv) @@ -199,7 +211,7 @@ def write_wide_labeled_data(labels: LabeledData, path: Path, *, replaces: FileSt for temporary in temporaries: temporary.unlink(missing_ok=True) - for entry in frames_lost_to_csv(frame): + for entry in frames_lost_to_csv(df): warnings.warn( f"{csv_twin(path)}: frame {entry} has no values and comes first, so this CSV reads back without it; " f"{path.name} keeps it.", diff --git a/tests/io/labeled_data/arrays/test_arrays.py b/tests/io/labeled_data/arrays/test_arrays.py index 4a66020..2e3eb90 100644 --- a/tests/io/labeled_data/arrays/test_arrays.py +++ b/tests/io/labeled_data/arrays/test_arrays.py @@ -1,10 +1,22 @@ +# +# DeepLabCut Toolbox (deeplabcut.org) +# © A. & M.W. Mathis Labs +# https://github.com/DeepLabCut/dlccore +# +# Contributors: +# https://github.com/DeepLabCut/dlccore/graphs/contributors +# +# Licensed under GNU Lesser General Public License v3.0 +# + from dataclasses import fields, replace from pathlib import Path import numpy as np import pandas as pd import pytest -from dlc_octopus.io.labeled_data import BodypartScope, Keypoint, LabeledData, LabeledDataArrays, read_labeled_data + +from dlccore.io.labeled_data import BodypartScope, Keypoint, LabeledData, LabeledDataArrays, read_labeled_data FIXTURES_DIR = Path(__file__).parents[2] / "fixtures" / "labeled_data" FIXTURES = sorted(path.name for path in FIXTURES_DIR.glob("*") if path.suffix in {".h5", ".csv"}) diff --git a/tests/io/labeled_data/test_checks.py b/tests/io/labeled_data/test_checks.py index 3ea3204..ce3b5d8 100644 --- a/tests/io/labeled_data/test_checks.py +++ b/tests/io/labeled_data/test_checks.py @@ -1,10 +1,22 @@ +# +# DeepLabCut Toolbox (deeplabcut.org) +# © A. & M.W. Mathis Labs +# https://github.com/DeepLabCut/dlccore +# +# Contributors: +# https://github.com/DeepLabCut/dlccore/graphs/contributors +# +# Licensed under GNU Lesser General Public License v3.0 +# + import importlib from pathlib import Path, PurePath import pandas as pd import pytest -from dlc_octopus.io.labeled_data import Keypoint, LabeledData, read_labeled_data -from dlc_octopus.io.labeled_data.checks.file import ( + +from dlccore.io.labeled_data import Keypoint, LabeledData, read_labeled_data +from dlccore.io.labeled_data.checks.file import ( frame_absorbed_into_index_names, frames_of_other_depth, frames_with_unnamed_parts, @@ -16,14 +28,14 @@ row_index_is_unrecognised, unread_h5_keys, ) -from dlc_octopus.io.labeled_data.checks.model import ( +from dlccore.io.labeled_data.checks.model import ( keypoints_with_empty_individual, likelihood_in_human_labels, missing_keypoints, ) -from dlc_octopus.io.labeled_data.wide.h5 import H5KeySelectionOutcome, select_h5_key -from dlc_octopus.io.labeled_data.wide.header import LabeledDataHeader, classify_labeled_data_header -from dlc_octopus.io.labeled_data.wide.row_index import LabeledDataRowIndex, classify_labeled_data_row_index +from dlccore.io.labeled_data.wide.h5 import H5KeySelectionOutcome, select_h5_key +from dlccore.io.labeled_data.wide.header import LabeledDataHeader, classify_labeled_data_header +from dlccore.io.labeled_data.wide.row_index import LabeledDataRowIndex, classify_labeled_data_row_index FIXTURES_DIR = Path(__file__).parents[1] / "fixtures" / "labeled_data" SINGLE_ANIMAL_LEVELS = ["scorer", "bodyparts", "coords"] @@ -241,8 +253,8 @@ def test_index_names_that_spell_no_three_part_frame_are_not_found(names: tuple[o def test_checks_are_split_into_file_and_model_facts() -> None: - importlib.import_module("dlc_octopus.io.labeled_data.checks.file") - importlib.import_module("dlc_octopus.io.labeled_data.checks.model") + importlib.import_module("dlccore.io.labeled_data.checks.file") + importlib.import_module("dlccore.io.labeled_data.checks.model") def test_a_keypoint_whose_individual_is_named_empty_is_found() -> None: diff --git a/tests/io/labeled_data/test_file.py b/tests/io/labeled_data/test_file.py index fcc9500..313be18 100644 --- a/tests/io/labeled_data/test_file.py +++ b/tests/io/labeled_data/test_file.py @@ -1,11 +1,23 @@ +# +# DeepLabCut Toolbox (deeplabcut.org) +# © A. & M.W. Mathis Labs +# https://github.com/DeepLabCut/dlccore +# +# Contributors: +# https://github.com/DeepLabCut/dlccore/graphs/contributors +# +# Licensed under GNU Lesser General Public License v3.0 +# + from pathlib import Path -import dlc_octopus.io.labeled_data as labeled_data import pandas as pd import pytest -from dlc_octopus.io.errors import UnreadableFileError -from dlc_octopus.io.labeled_data import LabeledData, LabeledDataFile, read_labeled_data, write_labeled_data -from dlc_octopus.io.labeled_data.wide.storage import WideLabeledDataStorage, read_wide_labeled_data + +import dlccore.io.labeled_data as labeled_data +from dlccore.io.errors import UnreadableFileError +from dlccore.io.labeled_data import LabeledData, LabeledDataFile, read_labeled_data, write_labeled_data +from dlccore.io.labeled_data.wide.storage import WideLabeledDataStorage, read_wide_labeled_data FIXTURES_DIR = Path(__file__).parents[1] / "fixtures" / "labeled_data" FIXTURES = sorted(path.name for path in FIXTURES_DIR.glob("*") if path.suffix in {".h5", ".csv"}) @@ -34,16 +46,16 @@ def test_every_fixture_reads_as_its_wide_storage_interprets_it(filename: str) -> assert labels.frames is not None -def _read_written(tmp_path: Path, frame: pd.DataFrame) -> LabeledDataFile: +def _read_written(tmp_path: Path, df: pd.DataFrame) -> LabeledDataFile: path = tmp_path / "CollectedData_Sc.h5" - frame.to_hdf(path, key="df_with_missing", mode="w") + df.to_hdf(path, key="df_with_missing", mode="w") return read_labeled_data(path) def test_frames_are_kept_when_the_header_is_unrecognised(tmp_path: Path) -> None: - frame = pd.DataFrame([[1.0, 2.0]], columns=["nose_x", "nose_y"], index=["labeled-data/v1/img0.png"]) + df = pd.DataFrame([[1.0, 2.0]], columns=["nose_x", "nose_y"], index=["labeled-data/v1/img0.png"]) - labels = _read_written(tmp_path, frame) + labels = _read_written(tmp_path, df) assert labels.keypoints is None assert labels.frames == (("labeled-data", "v1", "img0.png"),) @@ -157,7 +169,7 @@ def test_a_file_without_a_model_names_itself_and_the_reason(tmp_path: Path) -> N def test_the_package_exports_the_long_model() -> None: - from dlc_octopus.io.labeled_data.long.model import LabeledData as Model + from dlccore.io.labeled_data.long.model import LabeledData as Model assert LabeledData is Model diff --git a/tests/io/labeled_data/test_write.py b/tests/io/labeled_data/test_write.py index 28a91c5..84cb18d 100644 --- a/tests/io/labeled_data/test_write.py +++ b/tests/io/labeled_data/test_write.py @@ -1,3 +1,14 @@ +# +# DeepLabCut Toolbox (deeplabcut.org) +# © A. & M.W. Mathis Labs +# https://github.com/DeepLabCut/dlccore +# +# Contributors: +# https://github.com/DeepLabCut/dlccore/graphs/contributors +# +# Licensed under GNU Lesser General Public License v3.0 +# + import os import pickle import stat @@ -10,11 +21,12 @@ import pandas as pd import pytest import tables -from dlc_octopus.io import FileChangedError, FileStat -from dlc_octopus.io.labeled_data import LabeledData, read_labeled_data, write_labeled_data -from dlc_octopus.io.labeled_data.checks.file import frames_lost_to_csv -from dlc_octopus.io.labeled_data.wide.storage import csv_twin -from dlc_octopus.io.stamp import WRITER_KEY, WRITER_VERSION_KEY, WriterStamp + +from dlccore.io import FileChangedError, FileStat +from dlccore.io.labeled_data import LabeledData, read_labeled_data, write_labeled_data +from dlccore.io.labeled_data.checks.file import frames_lost_to_csv +from dlccore.io.labeled_data.wide.storage import csv_twin +from dlccore.io.stamp import WRITER_KEY, WRITER_VERSION_KEY, WriterStamp FIXTURES_DIR = Path(__file__).parents[1] / "fixtures" / "labeled_data" FIXTURES = sorted(path.name for path in FIXTURES_DIR.glob("*") if path.suffix in {".h5", ".csv"}) @@ -80,12 +92,12 @@ def _without_values(table: LabeledData, frame: int) -> LabeledData: @pytest.mark.parametrize("empty", [None, 0, 1], ids=["none", "first", "second"]) def test_frames_lost_to_csv_are_the_frames_pandas_reads_back_without(tmp_path: Path, empty: int | None) -> None: table = _table(FIXTURES_DIR / "single_animal_human.h5") - frame = (table if empty is None else _without_values(table, empty)).to_wide_df() - frame.to_csv(tmp_path / "labels.csv") + df = (table if empty is None else _without_values(table, empty)).to_wide_df() + df.to_csv(tmp_path / "labels.csv") back = pd.read_csv(tmp_path / "labels.csv", index_col=[0, 1, 2], header=[0, 1, 2]) - assert list(frames_lost_to_csv(frame)) == [entry for entry in frame.index if entry not in back.index] + assert list(frames_lost_to_csv(df)) == [entry for entry in df.index if entry not in back.index] def test_a_first_frame_without_values_is_kept_in_the_h5_with_a_warning_that_the_csv_twin_loses_it( @@ -135,7 +147,7 @@ def test_a_written_file_carries_the_writer_stamp_and_a_fixture_does_not(tmp_path stored = read_labeled_data(path) fixture = read_labeled_data(FIXTURES_DIR / "single_animal_human.h5") - assert stored.writer_stamp == WriterStamp("dlc_octopus.io.labeled_data", version("dlc-octopus")) + assert stored.writer_stamp == WriterStamp("dlccore.io.labeled_data", version("dlccore")) assert fixture.writer_stamp is None assert (stored.writer_stamp_error, fixture.writer_stamp_error) == (None, None) @@ -143,7 +155,7 @@ def test_a_written_file_carries_the_writer_stamp_and_a_fixture_does_not(tmp_path def test_the_stamp_is_stored_as_plain_strings_never_as_a_pickle(tmp_path: Path) -> None: path = tmp_path / "CollectedData_Sc.h5" write_labeled_data(_table(FIXTURES_DIR / "single_animal_human.h5"), path, replaces=None) - stamp = WriterStamp.current("dlc_octopus.io.labeled_data") + stamp = WriterStamp.current("dlccore.io.labeled_data") raw = path.read_bytes() with tables.open_file(str(path)) as h5: @@ -362,7 +374,7 @@ def test_files_beside_the_target_survive_a_write(tmp_path: Path) -> None: def test_reading_records_the_stat_taken_before_the_read(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: - from dlc_octopus.io.labeled_data.wide import storage + from dlccore.io.labeled_data.wide import storage path = tmp_path / "CollectedData_Sc.h5" path.write_bytes((FIXTURES_DIR / "single_animal_human.h5").read_bytes()) diff --git a/tests/io/labeled_data/wide/test_from_long.py b/tests/io/labeled_data/wide/test_from_long.py index f36d100..6618dc6 100644 --- a/tests/io/labeled_data/wide/test_from_long.py +++ b/tests/io/labeled_data/wide/test_from_long.py @@ -1,12 +1,24 @@ +# +# DeepLabCut Toolbox (deeplabcut.org) +# © A. & M.W. Mathis Labs +# https://github.com/DeepLabCut/dlccore +# +# Contributors: +# https://github.com/DeepLabCut/dlccore/graphs/contributors +# +# Licensed under GNU Lesser General Public License v3.0 +# + from pathlib import Path import numpy as np import pandas as pd import pytest -from dlc_octopus.io.labeled_data.long.model import LabeledData -from dlc_octopus.io.labeled_data.wide.from_long import long_to_wide -from dlc_octopus.io.labeled_data.wide.storage import read_wide_labeled_data -from dlc_octopus.io.labeled_data.wide.to_long import wide_frame_to_long, wide_to_long + +from dlccore.io.labeled_data.long.model import LabeledData +from dlccore.io.labeled_data.wide.from_long import long_to_wide +from dlccore.io.labeled_data.wide.storage import read_wide_labeled_data +from dlccore.io.labeled_data.wide.to_long import wide_df_to_long, wide_to_long FIXTURES_DIR = Path(__file__).parents[2] / "fixtures" / "labeled_data" FIXTURES = sorted(path.name for path in FIXTURES_DIR.glob("*") if path.suffix in {".h5", ".csv"}) @@ -16,8 +28,8 @@ def _labels(columns: list[tuple[str, ...]], rows: list[list[float]], index: object, names: list[str]) -> LabeledData: - frame = pd.DataFrame(rows, columns=pd.MultiIndex.from_tuples(columns, names=names), index=index) - return wide_frame_to_long(frame) + df = pd.DataFrame(rows, columns=pd.MultiIndex.from_tuples(columns, names=names), index=index) + return wide_df_to_long(df) def _single_animal_columns(coords: tuple[str, ...] = ("x", "y")) -> list[tuple[str, ...]]: @@ -35,7 +47,7 @@ def test_every_fixture_round_trips_through_wide(name: str) -> None: long = wide_to_long(storage.dataframe, storage.header, storage.row_index) wide = long_to_wide(long) - pd.testing.assert_frame_equal(wide_frame_to_long(wide).to_long_df(), long.to_long_df()) + pd.testing.assert_frame_equal(wide_df_to_long(wide).to_long_df(), long.to_long_df()) def test_the_wide_table_is_deeplabcuts_current_form() -> None: diff --git a/tests/io/labeled_data/wide/test_storage.py b/tests/io/labeled_data/wide/test_storage.py index 4ea16c4..cebf9ed 100644 --- a/tests/io/labeled_data/wide/test_storage.py +++ b/tests/io/labeled_data/wide/test_storage.py @@ -1,15 +1,27 @@ +# +# DeepLabCut Toolbox (deeplabcut.org) +# © A. & M.W. Mathis Labs +# https://github.com/DeepLabCut/dlccore +# +# Contributors: +# https://github.com/DeepLabCut/dlccore/graphs/contributors +# +# Licensed under GNU Lesser General Public License v3.0 +# + import shutil from pathlib import Path import pandas as pd import pytest -from dlc_octopus.io.errors import UnreadableFileError -from dlc_octopus.io.labeled_data import LabeledData -from dlc_octopus.io.labeled_data.wide.csv import read_labeled_data_csv -from dlc_octopus.io.labeled_data.wide.h5 import read_labeled_data_h5 -from dlc_octopus.io.labeled_data.wide.storage import WideLabeledDataStorage, read_wide_labeled_data -from dlc_octopus.io.labeled_data.wide.table import LabeledDataRead, classify_labeled_data_read -from dlc_octopus.io.labeled_data.wide.to_long import wide_to_long + +from dlccore.io.errors import UnreadableFileError +from dlccore.io.labeled_data import LabeledData +from dlccore.io.labeled_data.wide.csv import read_labeled_data_csv +from dlccore.io.labeled_data.wide.h5 import read_labeled_data_h5 +from dlccore.io.labeled_data.wide.storage import WideLabeledDataStorage, read_wide_labeled_data +from dlccore.io.labeled_data.wide.table import LabeledDataRead, classify_labeled_data_read +from dlccore.io.labeled_data.wide.to_long import wide_to_long FIXTURES_DIR = Path(__file__).parents[2] / "fixtures" / "labeled_data" FIXTURES = sorted(path.name for path in FIXTURES_DIR.glob("*") if path.suffix in {".h5", ".csv"}) @@ -20,8 +32,8 @@ def _wide_columns() -> pd.MultiIndex: return pd.MultiIndex.from_product([["Sc"], ["nose", "tail"], ["x", "y"]], names=["scorer", "bodyparts", "coords"]) -def _write_h5(path: Path, frame: pd.DataFrame) -> Path: - frame.to_hdf(path, key="df_with_missing", mode="w") +def _write_h5(path: Path, df: pd.DataFrame) -> Path: + df.to_hdf(path, key="df_with_missing", mode="w") return path @@ -56,9 +68,9 @@ def test_a_csv_is_interpreted_as_its_h5_twin(filename: str) -> None: def test_an_unrecognised_header_has_no_keypoints_but_keeps_its_frames(tmp_path: Path) -> None: - frame = pd.DataFrame([[1.0, 2.0]], columns=["nose_x", "nose_y"], index=["labeled-data/v1/img0.png"]) + df = pd.DataFrame([[1.0, 2.0]], columns=["nose_x", "nose_y"], index=["labeled-data/v1/img0.png"]) - storage = read_wide_labeled_data(_write_h5(tmp_path / "CollectedData_Sc.h5", frame)) + storage = read_wide_labeled_data(_write_h5(tmp_path / "CollectedData_Sc.h5", df)) assert storage.keypoints is None assert storage.frames == (("labeled-data", "v1", "img0.png"),) @@ -66,9 +78,9 @@ def test_an_unrecognised_header_has_no_keypoints_but_keeps_its_frames(tmp_path: def test_an_unrecognised_row_index_has_no_frames_but_keeps_its_keypoints(tmp_path: Path) -> None: - frame = pd.DataFrame([[1.0, 2.0, 3.0, 4.0]], columns=_wide_columns()) + df = pd.DataFrame([[1.0, 2.0, 3.0, 4.0]], columns=_wide_columns()) - storage = read_wide_labeled_data(_write_h5(tmp_path / "CollectedData_Sc.h5", frame)) + storage = read_wide_labeled_data(_write_h5(tmp_path / "CollectedData_Sc.h5", df)) assert storage.frames is None assert storage.keypoints is not None @@ -77,8 +89,8 @@ def test_an_unrecognised_row_index_has_no_frames_but_keeps_its_keypoints(tmp_pat def _storage_with_folder(tmp_path: Path, folder: object) -> WideLabeledDataStorage: index = pd.MultiIndex.from_tuples([("labeled-data", folder, "img0.png")]) - frame = pd.DataFrame([[1.0, 2.0, 3.0, 4.0]], index=index, columns=_wide_columns()) - return read_wide_labeled_data(_write_h5(tmp_path / "CollectedData_Sc.h5", frame)) + df = pd.DataFrame([[1.0, 2.0, 3.0, 4.0]], index=index, columns=_wide_columns()) + return read_wide_labeled_data(_write_h5(tmp_path / "CollectedData_Sc.h5", df)) @pytest.mark.parametrize("folder", [2019.5, True], ids=["float", "bool"]) @@ -151,11 +163,11 @@ def test_a_read_equals_itself() -> None: def _in_memory(tmp_path: Path, columns: list[tuple[str, ...]], values: list[object]) -> WideLabeledDataStorage: # Built in memory: an H5 file cannot hold a repeated column, and the normaliser is what is under test. names = ["scorer", "bodyparts", "coords"] - frame = pd.DataFrame( + df = pd.DataFrame( [values], columns=pd.MultiIndex.from_tuples(columns, names=names), index=["labeled-data/v1/img0.png"] ) - header, row_index = classify_labeled_data_read(LabeledDataRead(tmp_path / "in-memory.h5", frame, None)) - return WideLabeledDataStorage(key_selection=None, header=header, row_index=row_index, dataframe=frame) + header, row_index = classify_labeled_data_read(LabeledDataRead(tmp_path / "in-memory.h5", df, None)) + return WideLabeledDataStorage(key_selection=None, header=header, row_index=row_index, dataframe=df) def _with_coords(tmp_path: Path, coords: list[str], values: list[object]) -> WideLabeledDataStorage: @@ -169,7 +181,7 @@ def _model(storage: WideLabeledDataStorage) -> LabeledData: @pytest.mark.parametrize( ("coords", "values"), [(["x", "x", "y"], [1.0, 1.5, 2.0]), (["x"], [1.0]), (["x", "y", "z"], [1.0, 2.0, 3.0])], - ids=["repeated", "missing_y", "triangulated_xyz"], # xyz: DeepLabCut 3D output, out of scope (TODO.md) + ids=["repeated", "missing_y", "triangulated_xyz"], # xyz: DeepLabCut 3D output, not supported yet ) def test_coordinates_that_are_not_x_y_likelihood_are_not_interpreted( tmp_path: Path, coords: list[str], values: list[object] @@ -206,9 +218,9 @@ def test_a_non_real_column_is_not_interpreted_or_converted(tmp_path: Path, x: ob def test_uninterpretable_frames_give_no_table(tmp_path: Path) -> None: - frame = pd.DataFrame([[1.0, 2.0, 3.0, 4.0]], columns=_wide_columns()) + df = pd.DataFrame([[1.0, 2.0, 3.0, 4.0]], columns=_wide_columns()) - storage = read_wide_labeled_data(_write_h5(tmp_path / "CollectedData_Sc.h5", frame)) + storage = read_wide_labeled_data(_write_h5(tmp_path / "CollectedData_Sc.h5", df)) assert storage.frames is None with pytest.raises(ValueError, match="not text"): diff --git a/tests/io/labeled_data/wide/test_to_long.py b/tests/io/labeled_data/wide/test_to_long.py index aaa87b4..d665cd5 100644 --- a/tests/io/labeled_data/wide/test_to_long.py +++ b/tests/io/labeled_data/wide/test_to_long.py @@ -1,11 +1,23 @@ +# +# DeepLabCut Toolbox (deeplabcut.org) +# © A. & M.W. Mathis Labs +# https://github.com/DeepLabCut/dlccore +# +# Contributors: +# https://github.com/DeepLabCut/dlccore/graphs/contributors +# +# Licensed under GNU Lesser General Public License v3.0 +# + from pathlib import Path import numpy as np import pandas as pd import pytest -from dlc_octopus.io.labeled_data.long.model import LabeledData -from dlc_octopus.io.labeled_data.wide.storage import read_wide_labeled_data -from dlc_octopus.io.labeled_data.wide.to_long import wide_frame_to_long, wide_to_long + +from dlccore.io.labeled_data.long.model import LabeledData +from dlccore.io.labeled_data.wide.storage import read_wide_labeled_data +from dlccore.io.labeled_data.wide.to_long import wide_df_to_long, wide_to_long FIXTURES_DIR = Path(__file__).parents[2] / "fixtures" / "labeled_data" FIXTURES = sorted(path.name for path in FIXTURES_DIR.glob("*") if path.suffix in {".h5", ".csv"}) @@ -15,8 +27,8 @@ def _long(columns: list[tuple[str, ...]], rows: list[list[object]], index: object, names: list[str]) -> LabeledData: # Built in memory: what is under test is the conversion, not a container. - frame = pd.DataFrame(rows, columns=pd.MultiIndex.from_tuples(columns, names=names), index=index) - return wide_frame_to_long(frame) + df = pd.DataFrame(rows, columns=pd.MultiIndex.from_tuples(columns, names=names), index=index) + return wide_df_to_long(df) def _single_animal(rows: list[list[object]], index: object, coords: tuple[str, ...] = ("x", "y")) -> LabeledData: @@ -100,12 +112,12 @@ def test_an_integer_frame_part_becomes_text() -> None: def test_storage_frames_and_the_long_model_agree_on_an_integer_frame_part(tmp_path: Path) -> None: # Both read frame parts through frame_part_as_text: one policy, so the two can never disagree on a frame. index = pd.MultiIndex.from_tuples([("labeled-data", 2019, "img0.png")]) - frame = pd.DataFrame( + df = pd.DataFrame( [[1.0, 2.0]], index=index, columns=pd.MultiIndex.from_tuples([("Sc", "nose", "x"), ("Sc", "nose", "y")], names=SINGLE_ANIMAL_LEVELS), ) - frame.to_hdf(tmp_path / "CollectedData_Sc.h5", key="df_with_missing", mode="w") + df.to_hdf(tmp_path / "CollectedData_Sc.h5", key="df_with_missing", mode="w") storage = read_wide_labeled_data(tmp_path / "CollectedData_Sc.h5") long = wide_to_long(storage.dataframe, storage.header, storage.row_index).to_long_df() diff --git a/tests/io/test_boundaries.py b/tests/io/test_boundaries.py index 3c92858..d3fe42d 100644 --- a/tests/io/test_boundaries.py +++ b/tests/io/test_boundaries.py @@ -9,11 +9,15 @@ # Licensed under GNU Lesser General Public License v3.0 # -"""``dlccore.io`` imports nothing from ``dlccore`` outside itself, and its suffixes only the standard library.""" +"""``dlccore.io``'s import boundaries: nothing from ``dlccore`` outside io, suffixes only the standard library, and +no format module loaded until it is imported. +""" import ast +import subprocess import sys from collections.abc import Iterator +from functools import cache from pathlib import Path import pytest @@ -93,3 +97,62 @@ def test_a_relative_import_in_a_package_init_resolves_inside_it() -> None: found = _imported_modules("from . import fingerprints\n", IO, is_package=True) assert f"{IO}.fingerprints" in found + + +_FRESH_IMPORTS = (IO, f"{IO}.labeled_data.wide", f"{IO}.labeled_data.wide.h5", f"{IO}.labeled_data") +_UNLOAD_AND_IMPORT_EACH = f""" +import importlib, sys +for module in {_FRESH_IMPORTS!r}: + for name in [name for name in sys.modules if name.split(".")[0] == "dlccore"]: + del sys.modules[name] + importlib.import_module(module) + print("LOADED", module, *(name for name in sys.modules if name.split(".")[0] == "dlccore")) +""" + + +@cache +def _loaded_by_importing() -> dict[str, frozenset[str]]: + """Return, per module, the ``dlccore`` modules importing it loads, from one fresh interpreter per session. + + ``dlccore`` is unloaded before each import; third-party modules stay cached, so only ours are reported. + """ + + result = subprocess.run([sys.executable, "-c", _UNLOAD_AND_IMPORT_EACH], capture_output=True, text=True, check=True) + lines = [line.split()[1:] for line in result.stdout.splitlines() if line.startswith("LOADED ")] + + return {module: frozenset(loaded) for module, *loaded in lines} + + +def test_importing_io_loads_its_fingerprints() -> None: + # Control: the fresh interpreter does load what io's __init__ imports, so an absence below means something. + assert f"{IO}.fingerprints" in _loaded_by_importing()[IO] + + +def test_each_fresh_import_starts_without_the_previous_ones() -> None: + # Control: the h5 module is imported just before its grandparent package, which does not import it. + assert f"{IO}.labeled_data.wide.h5" in _loaded_by_importing()[f"{IO}.labeled_data.wide.h5"] + assert f"{IO}.labeled_data.wide.h5" not in _loaded_by_importing()[f"{IO}.labeled_data"] + + +def test_importing_io_does_not_load_the_video_module() -> None: + assert f"{IO}.video" not in _loaded_by_importing()[IO] + + +@pytest.mark.parametrize("package", [f"{IO}.labeled_data", f"{IO}.labeled_data.wide"]) +def test_importing_a_labeled_data_package_does_not_load_the_h5_module(package: str) -> None: + assert f"{IO}.labeled_data.wide.h5" not in _loaded_by_importing()[package] + + +_FILE_MODULE = PACKAGE_ROOT / "io" / "labeled_data" / "file.py" + + +def _reads_of_stored(path: Path) -> int: + tree = ast.parse(path.read_text(encoding="utf-8")) + return sum(isinstance(node, ast.Attribute) and node.attr == "_stored" for node in ast.walk(tree)) + + +def test_only_the_file_class_reads_its_storage() -> None: + assert _reads_of_stored(_FILE_MODULE) # control: the class itself does, so a zero below means something + readers = [path for path in PACKAGE_ROOT.rglob("*.py") if path != _FILE_MODULE and _reads_of_stored(path)] + + assert readers == [] From da4d77fbfa5fc7b10019c618447501fd58e63581 Mon Sep 17 00:00:00 2001 From: C-Achard Date: Tue, 24 Nov 2026 17:29:31 +0100 Subject: [PATCH 3/4] pre-commit --- dlccore/io/labeled_data/file.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/dlccore/io/labeled_data/file.py b/dlccore/io/labeled_data/file.py index 079cf2d..86b2e0f 100644 --- a/dlccore/io/labeled_data/file.py +++ b/dlccore/io/labeled_data/file.py @@ -22,6 +22,7 @@ if TYPE_CHECKING: import pandas as pd + from dlccore.io.labeled_data.long.model import LabeledData from dlccore.io.labeled_data.wide.h5 import H5KeySelection from dlccore.io.labeled_data.wide.header import LabeledDataHeader @@ -107,7 +108,7 @@ def labeled_data(self) -> LabeledData: def to_raw_wide_df(self) -> pd.DataFrame: """A copy of the table as read. - Raw, never normalised: legacy keys, a flat row index or a header in another order come back as found. + Raw, never normalised: legacy keys, a flat row index or a header in another order come back as found. For DeepLabCut's current form, use ``labeled_data.to_wide_df()``. """ @@ -145,7 +146,8 @@ def write_labeled_data(labels: LabeledData, path: Path, *, replaces: FileStat | labels: Data to write. path: H5 file to create or replace. Its suffix must equal ``.h5`` ignoring case. The CSV twin is written beside it, with suffix ``.CSV`` if ``path``'s suffix is upper case and ``.csv`` otherwise. - replaces: ``LabeledDataFile.stat`` of the file being replaced, or ``None`` to create a new file (must not already exist). + replaces: ``LabeledDataFile.stat`` of the file being replaced, or ``None`` to create a new file (must not + already exist). Returns: The stat of the written file, to pass as ``replaces`` to the next write. From 2e0cd3fbb67a490ca8d5442cfe8985117d47209e Mon Sep 17 00:00:00 2001 From: Cyril Achard Date: Fri, 27 Nov 2026 14:31:06 +0100 Subject: [PATCH 4/4] Fix writer stamp factory calls Use WriterStamp._current when writing labeled data and checking stamp serialization, matching the factory method name. --- dlccore/io/labeled_data/wide/storage.py | 2 +- tests/io/labeled_data/test_write.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/dlccore/io/labeled_data/wide/storage.py b/dlccore/io/labeled_data/wide/storage.py index 8f53f49..bb5cbed 100644 --- a/dlccore/io/labeled_data/wide/storage.py +++ b/dlccore/io/labeled_data/wide/storage.py @@ -200,7 +200,7 @@ def write_wide_labeled_data(labels: LabeledData, path: Path, *, replaces: FileSt try: temporaries.append(temporary_h5 := _reserve_temporary(path, H5_SUFFIX)) temporaries.append(temporary_csv := _reserve_temporary(path, CSV_SUFFIX)) - write_labeled_data_h5(df, temporary_h5, WriterStamp.current(WRITER_NAME)) + write_labeled_data_h5(df, temporary_h5, WriterStamp._current(WRITER_NAME)) write_labeled_data_csv(df, temporary_csv) _check_unchanged(path, replaces) _keep_mode(path, temporary_h5) diff --git a/tests/io/labeled_data/test_write.py b/tests/io/labeled_data/test_write.py index 84cb18d..6c4a721 100644 --- a/tests/io/labeled_data/test_write.py +++ b/tests/io/labeled_data/test_write.py @@ -155,7 +155,7 @@ def test_a_written_file_carries_the_writer_stamp_and_a_fixture_does_not(tmp_path def test_the_stamp_is_stored_as_plain_strings_never_as_a_pickle(tmp_path: Path) -> None: path = tmp_path / "CollectedData_Sc.h5" write_labeled_data(_table(FIXTURES_DIR / "single_animal_human.h5"), path, replaces=None) - stamp = WriterStamp.current("dlccore.io.labeled_data") + stamp = WriterStamp._current("dlccore.io.labeled_data") raw = path.read_bytes() with tables.open_file(str(path)) as h5: