diff --git a/dlccore/io/__init__.py b/dlccore/io/__init__.py new file mode 100644 index 0000000..faa721d --- /dev/null +++ b/dlccore/io/__init__.py @@ -0,0 +1,19 @@ +# +# 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 +# + +"""Per-file I/O for DeepLabCut project files. + +Paths in, typed results out. + +Should not import from ``dlccore``. +Each file kind's reader is imported from a dedicated module, +to avoid loading dependencies eagerly. +""" diff --git a/dlccore/io/labeled_data/__init__.py b/dlccore/io/labeled_data/__init__.py new file mode 100644 index 0000000..7ad6cb4 --- /dev/null +++ b/dlccore/io/labeled_data/__init__.py @@ -0,0 +1,32 @@ +# +# 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. The public API is ``__all__``. + +``__all__`` holds the identity types. ``model`` holds concepts common to all formats. +``_wide``, DeepLabCut's stored table, is internal to dlccore. +""" + +from dlccore.io.labeled_data.model import ( + BodypartScope, + FramePath, + KeypointDataFields, + KeypointIdentifier, + KeypointIdentifiers, +) + +__all__ = [ + "BodypartScope", + "FramePath", + "KeypointDataFields", + "KeypointIdentifier", + "KeypointIdentifiers", +] diff --git a/dlccore/io/labeled_data/_wide/__init__.py b/dlccore/io/labeled_data/_wide/__init__.py new file mode 100644 index 0000000..199a413 --- /dev/null +++ b/dlccore/io/labeled_data/_wide/__init__.py @@ -0,0 +1,15 @@ +# +# 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 +# + +"""DeepLabCut's wide labeled-data table: its header, its row index, and the containers that store it. + +Imports nothing eagerly: ``h5`` loads pandas and PyTables, so import it explicitly. +""" diff --git a/dlccore/io/labeled_data/_wide/header.py b/dlccore/io/labeled_data/_wide/header.py new file mode 100644 index 0000000..e3413e0 --- /dev/null +++ b/dlccore/io/labeled_data/_wide/header.py @@ -0,0 +1,127 @@ +# +# 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 +# + +"""DeepLabCut's wide labeled-data column header, grouped into keypoints without dropping any column.""" + +from __future__ import annotations + +from collections.abc import Iterable +from dataclasses import dataclass +from enum import Enum + +from dlccore.io.labeled_data.model import KeypointIdentifier + +SINGLE_ANIMAL_LEVELS = ("scorer", "bodyparts", "coords") +MULTI_ANIMAL_LEVELS = ("scorer", "individuals", "bodyparts", "coords") + + +class LabeledDataHeaderShape(str, Enum): + """Column layouts used by a header, if recognised.""" + + SINGLE_ANIMAL = "single_animal" + MULTI_ANIMAL = "multi_animal" + UNRECOGNISED = "unrecognised" + + +_HEADER_SHAPES: dict[tuple[str | None, ...], LabeledDataHeaderShape] = { + SINGLE_ANIMAL_LEVELS: LabeledDataHeaderShape.SINGLE_ANIMAL, + MULTI_ANIMAL_LEVELS: LabeledDataHeaderShape.MULTI_ANIMAL, +} + + +@dataclass(frozen=True) +class KeypointColumns: + """The columns of one keypoint in a wide header. + + Attributes: + identifier: The keypoint's identifier. The individual is ``None`` in a single-animal header, and the scope is + ``UNIQUE`` only when the individual is ``"single"``. + coords: The coordinate name of each column (e.g. ``"x"``), in column order, duplicates kept. + positions: Each column's index in the header, aligned with ``coords``. + """ + + identifier: KeypointIdentifier + coords: tuple[str, ...] + positions: tuple[int, ...] + + +@dataclass(frozen=True) +class LabeledDataHeader: + """A wide labeled-data column header, classified. + + Attributes: + level_names: The header's level names, as stored. + shape: The DeepLabCut layout these level names match, or ``UNRECOGNISED``. + keypoints: The keypoints, in order of first appearance; empty when ``shape`` is ``UNRECOGNISED``. + unrecognised_columns: The raw column tuples, kept only when ``shape`` is ``UNRECOGNISED`` so that nothing is + lost. + """ + + level_names: tuple[str | None, ...] + shape: LabeledDataHeaderShape + keypoints: tuple[KeypointColumns, ...] = () + unrecognised_columns: tuple[tuple[str, ...], ...] = () + + +HEADER_DEPTHS: tuple[int, ...] = tuple(sorted({len(level_names) for level_names in _HEADER_SHAPES}, reverse=True)) + + +def header_shape(level_names: Iterable[str | None]) -> LabeledDataHeaderShape: + """Return the DeepLabCut layout these level names match, or ``UNRECOGNISED``.""" + + return _HEADER_SHAPES.get(tuple(level_names), LabeledDataHeaderShape.UNRECOGNISED) + + +def classify_labeled_data_header( + level_names: Iterable[str | None], + columns: Iterable[tuple[str, ...]], +) -> LabeledDataHeader: + """Group a wide header's columns into keypoints. + + Each column is read on its own and grouped by (scorer, individual, bodypart). The header is never expanded + from its per-level values (a MultiIndex's ``levels``), which would add keypoints that have no column. + + Reordered headers give the same keypoints at other positions, + any missing pair is omitted rather than padded, and duplicated columns are kept. + + Args: + level_names: The header's level names, outermost first. + columns: One tuple per column, aligned with ``level_names``. + """ + + level_names = tuple(level_names) + columns = tuple(tuple(column) for column in columns) + shape = header_shape(level_names) + + if shape is LabeledDataHeaderShape.UNRECOGNISED: + return LabeledDataHeader(level_names=level_names, shape=shape, unrecognised_columns=columns) + + groups: dict[tuple[str, str | None, str], list[tuple[str, int]]] = {} + + for position, column in enumerate(columns): + if shape is LabeledDataHeaderShape.SINGLE_ANIMAL: + scorer, bodypart, coord = column + individual = None + else: + scorer, individual, bodypart, coord = column + + groups.setdefault((scorer, individual, bodypart), []).append((coord, position)) + + keypoints = tuple( + KeypointColumns( + identifier=KeypointIdentifier(scorer=scorer, individual=individual, bodypart=bodypart), + coords=tuple(coord for coord, _position in members), + positions=tuple(position for _coord, position in members), + ) + for (scorer, individual, bodypart), members in groups.items() + ) + + return LabeledDataHeader(level_names=level_names, shape=shape, keypoints=keypoints) diff --git a/dlccore/io/labeled_data/_wide/row_index.py b/dlccore/io/labeled_data/_wide/row_index.py new file mode 100644 index 0000000..2d592f6 --- /dev/null +++ b/dlccore/io/labeled_data/_wide/row_index.py @@ -0,0 +1,121 @@ +# +# 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 +# + +"""DeepLabCut's labeled-data row index: each row's frame path, split into path components as stored.""" + +from __future__ import annotations + +from collections.abc import Iterable +from dataclasses import dataclass +from enum import Enum +from numbers import Integral + + +class RowIndexShape(str, Enum): + """How a row index stores its frame paths. + + ``PATH_PARTS``: a MultiIndex, one level per path component. ``FLAT_PATHS``: one path string per row. + ``EMPTY``: no rows, whatever the index type. ``UNRECOGNISED``: anything else. + """ + + PATH_PARTS = "path_parts" + FLAT_PATHS = "flat_paths" + EMPTY = "empty" + UNRECOGNISED = "unrecognised" + + +@dataclass(frozen=True) +class LabeledDataRowIndex: + """A labeled-data row index, classified. + + Attributes: + shape: How the frame paths are stored. + names: The level names as stored; ``None`` for each unnamed level. + entries: The entries as stored. + frames: Each entry's path components as stored. Entries of different depths keep their own length. + Empty when ``shape`` is ``EMPTY`` or ``UNRECOGNISED``. + """ + + shape: RowIndexShape + names: tuple[object, ...] + entries: tuple[object, ...] + frames: tuple[tuple[object, ...], ...] = () + + +# Frame identity rather than wide storage: moves to ``model`` once a second format needs it. +def split_frame_path(entry: str) -> tuple[str, ...]: + """Split a labeled-data row-index entry into its path components. + + Does not validate: empty and repeated separators give empty components instead of being dropped. + + Args: + entry: A row-index entry, e.g. ``labeled-data/vid1/img1.png``. Forward slashes and backslashes both separate. + """ + + return tuple(entry.replace("\\", "/").split("/")) + + +def frame_part_as_text(part: object) -> str | None: + """Return a row-index part as the folder or file name it stands for. + + A string is returned unchanged. An integer is converted with ``str()``: when a video folder's name is a + number (e.g. ``labeled-data/123/``), pandas may read that level back as an integer, and DeepLabCut's + ``guarantee_multiindex_rows`` converts it to a string the same way. + + Returns: + The name, or ``None`` for any other type. A float or bool cannot be turned back into the original + name (``1.0`` vs ``"1"``), so no guessing is involved. + """ + + if isinstance(part, str): + return part + if isinstance(part, Integral) and not isinstance(part, bool): + return str(part) + return None + + +def classify_labeled_data_row_index( + names: Iterable[object], + entries: Iterable[object], + *, + is_multi_index: bool, +) -> LabeledDataRowIndex: + """Classify a row index by how it stores frame paths. Path strings are split but not normalised. + + Args: + names: The row index's level names. + entries: The row-index entries, in order; tuples for a MultiIndex. + is_multi_index: Whether the entries came from a MultiIndex. + """ + + names = tuple(names) + entries = tuple(entries) + + if not entries: + return LabeledDataRowIndex(shape=RowIndexShape.EMPTY, names=names, entries=entries) + + if is_multi_index: + return LabeledDataRowIndex( + shape=RowIndexShape.PATH_PARTS, + names=names, + entries=entries, + frames=tuple(tuple(entry) for entry in entries), + ) + + if all(isinstance(entry, str) for entry in entries): + return LabeledDataRowIndex( + shape=RowIndexShape.FLAT_PATHS, + names=names, + entries=entries, + frames=tuple(split_frame_path(entry) for entry in entries), + ) + + return LabeledDataRowIndex(shape=RowIndexShape.UNRECOGNISED, names=names, entries=entries) diff --git a/dlccore/io/labeled_data/model.py b/dlccore/io/labeled_data/model.py new file mode 100644 index 0000000..c7cca91 --- /dev/null +++ b/dlccore/io/labeled_data/model.py @@ -0,0 +1,198 @@ +# +# 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 +# + +"""DeepLabCut's labeled-data model: what is true in any file format.""" + +from __future__ import annotations + +from collections import Counter +from collections.abc import Iterable, Sequence +from dataclasses import dataclass +from enum import Enum +from typing import overload + +# Keypoint data: always x and y, and a likelihood for models +# NOTE: 3D support is obviously missing +POSITION_COORDS = ("x", "y") +LIKELIHOOD_COORD = "likelihood" + +# In multi-animal project, this denotes keypoints that do not belong to any individual. +# Extra caution is needed as this is a sentinel value, make sure to treat it accordingly. +# TODO: do not reuse this pattern in new formats +# as it was a major source of confusion and potential bugs. +# It should not be used in any other format than the wide table "legacy" format. +UNIQUE_BODYPARTS_INDIVIDUAL = "single" + +FramePath = tuple[str, ...] +"""A frame's path components as stored, e.g. ``("labeled-data", "session-01", "img000.png")``.""" + + +class BodypartScope(str, Enum): + """Whether a bodypart is labeled once per individual, or once per frame as DeepLabCut's ``uniquebodyparts``.""" + + INDIVIDUAL = "individual" + UNIQUE = "unique" + + +@dataclass(frozen=True) +class KeypointIdentifier: + """Keypoint properties. + + Identifies a keypoint; does not describe the data (see ``KeypointDataFields``). + + Attributes: + scorer: As stored. + individual: As stored; ``None`` when the source names no individual. + bodypart: As stored. + """ + + scorer: str + individual: str | None + bodypart: str + + @property + def scope(self) -> BodypartScope: + """``UNIQUE`` exactly when the individual is DeepLabCut's unique-bodyparts bucket.""" + + return BodypartScope.UNIQUE if self.individual == UNIQUE_BODYPARTS_INDIVIDUAL else BodypartScope.INDIVIDUAL + + +@dataclass(frozen=True) +class KeypointIdentifiers(Sequence[KeypointIdentifier]): + """The identifiers of labeled data's keypoints, in keypoint order. + + Available as ``identifiers`` on: + + - ``LabeledDataFile``: read from the header; equal to the model's when the model can be built. + For inspecting a file without building the model, or a file with no frames. + - ``LabeledData``: available after construction (``from_wide_df``, ``from_long_df``, ``without_frames``). + - ``LabeledDataArrays``: the model's. Column ``k`` of each array is keypoint ``k``, so the arrays can be used + without the model. + + Pass it along with arrays that leave ``LabeledDataArrays``, such as tensors in a training dataset. + Selecting frames, train/test splits or batches leaves it unchanged, since only frames are removed. + Compared and hashed by value. For JSON, use ``pydantic.TypeAdapter(KeypointIdentifiers)``. + + Attributes: + identifiers: In keypoint order. + """ + + identifiers: tuple[KeypointIdentifier, ...] + + def __post_init__(self) -> None: + """Refuse a repeated identifier, and identifiers that mix named individuals with none. + + Raises: + ValueError: If an identifier appears twice, or only some identifiers name an individual. + """ + + object.__setattr__(self, "identifiers", tuple(self.identifiers)) + repeated = next((k for k, n in Counter(self.identifiers).items() if n > 1), None) + if repeated is not None: + raise ValueError( + f"Keypoint {repeated} appears {self.identifiers.count(repeated)} times; each keypoint appears once." + ) + unnamed = sum(identifier.individual is None for identifier in self.identifiers) + if 0 < unnamed < len(self.identifiers): + raise ValueError( + f"{len(self.identifiers) - unnamed} of {len(self.identifiers)} keypoints are tied to an individual; " + "either every keypoint has an individual, or none does." + ) + + @overload + def __getitem__(self, index: int) -> KeypointIdentifier: ... + + @overload + def __getitem__(self, index: slice) -> tuple[KeypointIdentifier, ...]: ... + + def __getitem__(self, index: int | slice) -> KeypointIdentifier | tuple[KeypointIdentifier, ...]: + """The identifier at ``index`` of axis 1, or a tuple of them for a slice.""" + + return self.identifiers[index] + + def __len__(self) -> int: + """The number of keypoints, the length of axis 1.""" + + return len(self.identifiers) + + @property + def multi_animal(self) -> bool: + """Whether the identifiers name individuals.""" + + return any(identifier.individual is not None for identifier in self.identifiers) + + @property + def individuals(self) -> tuple[str, ...]: + """Individuals in first-seen order, without DeepLabCut's unique-bodyparts bucket; empty for single-animal.""" + + return _unique_in_order(k.individual for k in self._per_individual if k.individual is not None) + + @property + def bodyparts(self) -> tuple[str, ...]: + """Bodyparts labeled per individual, in first-seen order; every bodypart for single-animal labels.""" + + return _unique_in_order(k.bodypart for k in self._per_individual) + + @property + def unique_bodyparts(self) -> tuple[str, ...]: + """Bodyparts labeled once per frame, DeepLabCut's ``uniquebodyparts``, in order.""" + + return tuple(k.bodypart for k in self.identifiers if k.scope is BodypartScope.UNIQUE) + + @property + def _per_individual(self) -> tuple[KeypointIdentifier, ...]: + return tuple(k for k in self.identifiers if k.scope is BodypartScope.INDIVIDUAL) + + +_ACCEPTED_DATA_FIELDS = (POSITION_COORDS, (*POSITION_COORDS, LIKELIHOOD_COORD)) + + +@dataclass(frozen=True) +class KeypointDataFields: + """The data fields of a keypoint: currently coordinates, and a likelihood if from a model. + + Describes the values, never holds them. Only DeepLabCut's 2D fields are accepted, ``("x", "y")`` and + ``("x", "y", "likelihood")``; any other field is refused until something reads it. Compared and hashed by value. + + Attributes: + names: The fields, in stored order. + """ + + names: tuple[str, ...] + + def __post_init__(self) -> None: + """Refuse fields other than DeepLabCut's 2D ones. + + Raises: + ValueError: If ``names`` is neither ``("x", "y")`` nor ``("x", "y", "likelihood")``. + """ + + object.__setattr__(self, "names", tuple(self.names)) + if self.names not in _ACCEPTED_DATA_FIELDS: + raise ValueError( + f"Data fields {self.names} are not supported; only {' or '.join(map(str, _ACCEPTED_DATA_FIELDS))}." + ) + + @classmethod + def make_2d(cls, *, with_likelihood: bool) -> KeypointDataFields: + """The 2D fields, with a likelihood or without.""" + + return cls((*POSITION_COORDS, LIKELIHOOD_COORD) if with_likelihood else POSITION_COORDS) + + @property + def has_likelihood(self) -> bool: + """Whether a likelihood accompanies the coordinates.""" + + return LIKELIHOOD_COORD in self.names + + +def _unique_in_order(values: Iterable[str]) -> tuple[str, ...]: + return tuple(dict.fromkeys(values)) diff --git a/pyproject.toml b/pyproject.toml index 24747d8..d1ce395 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -23,6 +23,7 @@ classifiers = [ dynamic = [ "version" ] dependencies = [ "numpy>=1.22.4", + "pandas>=2.3.3", "pydantic>=2.1,<3", "ruamel-yaml>=0.16", "typing-extensions", @@ -81,3 +82,11 @@ lint.pydocstyle.convention = "google" [tool.pyproject-fmt] max_supported_python = "3.12" + +[tool.pytest] +ini_options.addopts = "--strict-markers" +ini_options.xfail_strict = true +ini_options.filterwarnings = [ + # A categorical groupby must state observed=; the default changes in pandas 3. + "error:The default of observed=False is deprecated:FutureWarning", +] diff --git a/tests/io/labeled_data/test_keypoints.py b/tests/io/labeled_data/test_keypoints.py new file mode 100644 index 0000000..31e64cc --- /dev/null +++ b/tests/io/labeled_data/test_keypoints.py @@ -0,0 +1,124 @@ +# +# 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 FrozenInstanceError + +import pytest +from pydantic import TypeAdapter, ValidationError + +from dlccore.io.labeled_data import KeypointDataFields, KeypointIdentifier, KeypointIdentifiers + +SINGLE = tuple(KeypointIdentifier("Sc", None, bodypart) for bodypart in ("nose", "tail")) +MULTI = ( + *(KeypointIdentifier("Sc", individual, bodypart) for individual in ("a", "b") for bodypart in ("nose", "tail")), + KeypointIdentifier("Sc", "single", "corner"), +) + + +def test_keypoints_are_a_sequence_in_array_order() -> None: + keypoints = KeypointIdentifiers(MULTI) + + assert len(keypoints) == len(MULTI) + assert keypoints[2] == MULTI[2] + assert tuple(keypoints) == MULTI + assert MULTI[-1] in keypoints + assert keypoints.index(MULTI[1]) == 1 + + +def test_an_empty_set_is_falsy() -> None: + assert not KeypointIdentifiers(()) + + +def test_equal_keypoints_compare_and_hash_alike() -> None: + first = KeypointIdentifiers(MULTI) + second = KeypointIdentifiers(list(MULTI)) # a list is stored as a tuple + + assert first == second + assert hash(first) == hash(second) + assert first != KeypointIdentifiers(MULTI[:-1]) + + +def test_keypoints_round_trip_through_json_with_a_type_adapter() -> None: + adapter = TypeAdapter(KeypointIdentifiers) + keypoints = KeypointIdentifiers(MULTI) + + assert adapter.validate_json(adapter.dump_json(keypoints)) == keypoints + + +def test_json_with_a_repeated_keypoint_is_refused() -> None: + adapter = TypeAdapter(KeypointIdentifiers) + payload = adapter.dump_json(KeypointIdentifiers(SINGLE)) + repeated = payload.replace(b'"bodypart":"tail"', b'"bodypart":"nose"') + assert repeated != payload # control: the payload was altered + + with pytest.raises(ValidationError, match="appears 2 times"): + adapter.validate_json(repeated) + + +def test_keypoints_are_frozen() -> None: + keypoints = KeypointIdentifiers(SINGLE) + + with pytest.raises(FrozenInstanceError): + keypoints.identifiers = () # type: ignore[misc] + + +def test_a_keypoint_may_appear_once() -> None: + with pytest.raises(ValueError, match="appears 2 times"): + KeypointIdentifiers((*SINGLE, SINGLE[0])) + + +def test_individuals_are_named_on_every_keypoint_or_none() -> None: + with pytest.raises(ValueError, match="1 of 3 keypoints are tied to an individual"): + KeypointIdentifiers((*SINGLE, KeypointIdentifier("Sc", "a", "ear"))) + + +def test_multi_animal_keypoints_name_their_individuals_and_bodyparts() -> None: + keypoints = KeypointIdentifiers(MULTI) + + assert keypoints.multi_animal + assert keypoints.individuals == ("a", "b") + assert keypoints.bodyparts == ("nose", "tail") + assert keypoints.unique_bodyparts == ("corner",) + + +def test_single_animal_keypoints_have_bodyparts_and_no_individuals() -> None: + keypoints = KeypointIdentifiers(SINGLE) + + assert not keypoints.multi_animal + assert (keypoints.individuals, keypoints.bodyparts, keypoints.unique_bodyparts) == ((), ("nose", "tail"), ()) + + +@pytest.mark.parametrize( + ("names", "has_likelihood"), [(("x", "y"), False), (("x", "y", "likelihood"), True)], ids=["human", "machine"] +) +def test_data_fields_accept_deeplabcuts_2d_fields(names: tuple[str, ...], has_likelihood: bool) -> None: + fields = KeypointDataFields(names) + + assert fields.has_likelihood is has_likelihood + assert fields == KeypointDataFields.make_2d(with_likelihood=has_likelihood) + assert hash(fields) == hash(KeypointDataFields(list(names))) # a list is stored as a tuple + + +@pytest.mark.parametrize( + "names", + [("x", "y", "z"), ("y", "x"), ("x",), ("x", "y", "likelihood", "z"), ("likelihood", "x", "y")], + ids=["triangulated", "swapped", "x_only", "extra", "likelihood_first"], +) +def test_data_fields_other_than_deeplabcuts_2d_ones_are_refused(names: tuple[str, ...]) -> None: + with pytest.raises(ValueError, match="not supported"): + KeypointDataFields(names) + + +def test_data_fields_are_frozen() -> None: + fields = KeypointDataFields.make_2d(with_likelihood=False) + + with pytest.raises(FrozenInstanceError): + fields.names = ("x", "y", "likelihood") # type: ignore[misc] diff --git a/tests/io/labeled_data/wide/test_header.py b/tests/io/labeled_data/wide/test_header.py new file mode 100644 index 0000000..93831c5 --- /dev/null +++ b/tests/io/labeled_data/wide/test_header.py @@ -0,0 +1,93 @@ +# +# 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 dlccore.io.labeled_data._wide.header import ( + LabeledDataHeader, + LabeledDataHeaderShape, + classify_labeled_data_header, +) +from dlccore.io.labeled_data.model import BodypartScope + +MULTI_ANIMAL = ("scorer", "individuals", "bodyparts", "coords") + + +def _rebuilt_columns(header: LabeledDataHeader) -> list[tuple[str, ...]]: + columns: dict[int, tuple[str, ...]] = {} + + for placed in header.keypoints: + keypoint = placed.identifier + + for coord, position in zip(placed.coords, placed.positions, strict=True): + if header.shape is LabeledDataHeaderShape.SINGLE_ANIMAL: + columns[position] = (keypoint.scorer, keypoint.bodypart, coord) + else: + columns[position] = (keypoint.scorer, keypoint.individual, keypoint.bodypart, coord) + + return [columns[position] for position in sorted(columns)] + + +def _multi_animal(columns: list[tuple[str, str, str, str]]) -> LabeledDataHeader: + return classify_labeled_data_header(MULTI_ANIMAL, columns) + + +def test_a_name_containing_single_is_an_individual() -> None: + header = _multi_animal([("Sc", "single_mouse", "nose", "x"), ("Sc", "single_mouse", "nose", "y")]) + + assert header.keypoints[0].identifier.scope is BodypartScope.INDIVIDUAL + + +def test_reordered_columns_give_the_same_keypoints_at_other_positions() -> None: + columns = [("Sc", "a", "nose", "x"), ("Sc", "a", "nose", "y"), ("Sc", "b", "nose", "x"), ("Sc", "b", "nose", "y")] + reordered = [columns[2], columns[0], columns[3], columns[1]] + + in_order, shuffled = _multi_animal(columns), _multi_animal(reordered) + + assert {(k.identifier, k.coords) for k in in_order.keypoints} == { + (k.identifier, k.coords) for k in shuffled.keypoints + } + assert [k.positions for k in in_order.keypoints] != [k.positions for k in shuffled.keypoints] + + +def test_a_missing_pair_is_absent_not_padded() -> None: + header = _multi_animal([("Sc", "a", "nose", "x"), ("Sc", "a", "tail", "x"), ("Sc", "b", "nose", "x")]) + + assert [(placed.identifier.individual, placed.identifier.bodypart) for placed in header.keypoints] == [ + ("a", "nose"), + ("a", "tail"), + ("b", "nose"), + ] + + +def test_a_duplicated_column_is_kept() -> None: + header = _multi_animal([("Sc", "a", "nose", "x"), ("Sc", "a", "nose", "x")]) + + (keypoint,) = header.keypoints + + assert (keypoint.coords, keypoint.positions) == (("x", "x"), (0, 1)) + + +def test_coordinates_are_classified_whatever_they_are() -> None: + header = _multi_animal([("Sc", "a", "nose", "z")]) + + assert header.keypoints[0].coords == ("z",) + + +def test_unrecognised_level_names_keep_the_columns_and_raise_nothing() -> None: + columns = [("Sc", "nose", "x", "extra")] + + header = classify_labeled_data_header(("scorer", "bodyparts", "coords", "extra"), columns) + + assert (header.shape, header.keypoints, header.unrecognised_columns) == ( + LabeledDataHeaderShape.UNRECOGNISED, + (), + (("Sc", "nose", "x", "extra"),), + ) diff --git a/tests/io/labeled_data/wide/test_row_index.py b/tests/io/labeled_data/wide/test_row_index.py new file mode 100644 index 0000000..9797f3e --- /dev/null +++ b/tests/io/labeled_data/wide/test_row_index.py @@ -0,0 +1,82 @@ +# +# 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 numpy as np +import pandas as pd +import pytest + +from dlccore.io.labeled_data._wide.row_index import ( + RowIndexShape, + classify_labeled_data_row_index, + frame_part_as_text, + split_frame_path, +) + + +def test_both_separators_split_alike() -> None: + row_index = classify_labeled_data_row_index( + [None], [r"labeled-data\vid1\img1.png", "labeled-data/vid1/img2.png"], is_multi_index=False + ) + + assert row_index.frames == (("labeled-data", "vid1", "img1.png"), ("labeled-data", "vid1", "img2.png")) + + +def test_a_ragged_index_stays_ragged() -> None: + row_index = classify_labeled_data_row_index( + [None], ["labeled-data/vid1/img1.png", "img2.png"], is_multi_index=False + ) + + assert row_index.frames == (("labeled-data", "vid1", "img1.png"), ("img2.png",)) + + +def test_a_numeric_index_is_unrecognised_and_kept() -> None: + row_index = classify_labeled_data_row_index([None], [0, 1], is_multi_index=False) + + assert (row_index.shape, row_index.entries, row_index.frames) == (RowIndexShape.UNRECOGNISED, (0, 1), ()) + + +@pytest.mark.parametrize( + "index", + [pd.RangeIndex(0), pd.Index([], dtype=object), pd.MultiIndex.from_tuples([], names=[None, None, None])], + ids=["range", "object", "multi"], +) +def test_an_index_without_entries_is_empty_whatever_its_type(index: pd.Index) -> None: + row_index = classify_labeled_data_row_index(index.names, index, is_multi_index=isinstance(index, pd.MultiIndex)) + + assert (row_index.shape, row_index.entries, row_index.frames) == (RowIndexShape.EMPTY, (), ()) + + +def test_a_numeric_folder_is_not_stringified() -> None: + index = pd.MultiIndex.from_tuples([("labeled-data", 2019, "img1.png")]) + + row_index = classify_labeled_data_row_index(index.names, index, is_multi_index=True) + + assert row_index.frames == (("labeled-data", 2019, "img1.png"),) + + +def test_split_frame_path_keeps_empty_components() -> None: + assert split_frame_path("labeled-data//img1.png") == ("labeled-data", "", "img1.png") + + +@pytest.mark.parametrize( + ("part", "text"), + [("s1", "s1"), ("007", "007"), (2019, "2019"), (np.int64(2019), "2019")], + ids=["text", "zero_padded_text", "int", "numpy_int"], +) +def test_a_frame_part_with_a_name_is_read_as_that_text(part: object, text: str) -> None: + assert frame_part_as_text(part) == text + + +@pytest.mark.parametrize("part", [2019.0, True, np.True_, None], ids=["float", "bool", "numpy_bool", "none"]) +def test_a_frame_part_naming_no_folder_has_no_text(part: object) -> None: + # A float or bool would become a folder name that never existed. + assert frame_part_as_text(part) is None