diff --git a/dlccore/io/labeled_data/__init__.py b/dlccore/io/labeled_data/__init__.py index 7ad6cb4..a7ee8ed 100644 --- a/dlccore/io/labeled_data/__init__.py +++ b/dlccore/io/labeled_data/__init__.py @@ -11,10 +11,22 @@ """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. +``__all__`` holds: +- Model and views +- Arrays view +- Identity types +``model`` holds concepts common to all formats. +``_wide``, DeepLabCut's stored table, and ``_checks`` are internal to dlccore. + +Imports no format eagerly. """ +# Future formats to consider: +# - NWB +# - NPZ + +from dlccore.io.labeled_data.arrays.from_long import LabeledDataArrays +from dlccore.io.labeled_data.long.model import LABELED_DATA_LONG_VERSION, LabeledData from dlccore.io.labeled_data.model import ( BodypartScope, FramePath, @@ -24,9 +36,12 @@ ) __all__ = [ + "LABELED_DATA_LONG_VERSION", "BodypartScope", "FramePath", "KeypointDataFields", "KeypointIdentifier", "KeypointIdentifiers", + "LabeledData", + "LabeledDataArrays", ] diff --git a/dlccore/io/labeled_data/_checks/__init__.py b/dlccore/io/labeled_data/_checks/__init__.py new file mode 100644 index 0000000..9a3ea09 --- /dev/null +++ b/dlccore/io/labeled_data/_checks/__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 +# + +"""Pure checks on labeled data. Never a verdict. + +A write refuses or warns on a check, and validation reports the same check as a finding; neither re-derives it. +``file`` holds facts about a file as stored, ``model`` facts about the labels it holds. + +Checks are for acting at the moment of use, such as refusing a write; to know a file's condition, use validation, +whose findings carry every relevant check. +""" diff --git a/dlccore/io/labeled_data/_checks/file.py b/dlccore/io/labeled_data/_checks/file.py new file mode 100644 index 0000000..3de1ffd --- /dev/null +++ b/dlccore/io/labeled_data/_checks/file.py @@ -0,0 +1,105 @@ +# +# 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 +# + +"""Checks on a labeled-data file as stored: H5 keys, header, row index and values. + +Each check takes one intermediate result of reading the file, e.g. the H5 key selection. +Any problematic items are returnedas as a truthy value. +When there is nothing to report, it returns a falsy value. +""" + +from __future__ import annotations + +import pandas as pd + +from dlccore.io.labeled_data._wide.header import KeypointColumns, LabeledDataHeader, LabeledDataHeaderShape +from dlccore.io.labeled_data._wide.row_index import ( + LabeledDataRowIndex, + RowIndexShape, + frame_part_as_text, +) +from dlccore.io.labeled_data.long.model import FRAME_COLUMNS +from dlccore.io.labeled_data.model import LIKELIHOOD_COORD, POSITION_COORDS + +_COORDINATES = frozenset({*POSITION_COORDS, LIKELIHOOD_COORD}) + + +def header_is_unrecognised(header: LabeledDataHeader) -> bool: + """Return whether the header matches neither DeepLabCut layout (single- or multi-animal).""" + + return header.shape is LabeledDataHeaderShape.UNRECOGNISED + + +def keypoints_with_unrecognised_coords(header: LabeledDataHeader) -> tuple[KeypointColumns, ...]: + """Return the keypoints whose coordinate columns are not ``x``, ``y`` and optionally ``likelihood``. + + A keypoint is returned if it lacks ``x`` or ``y``, has any other coordinate, or repeats one. + """ + + return tuple( + columns + for columns in header.keypoints + if len(set(columns.coords)) != len(columns.coords) + or not set(POSITION_COORDS) <= set(columns.coords) <= _COORDINATES + ) + + +def keypoints_missing_likelihood(header: LabeledDataHeader) -> tuple[KeypointColumns, ...]: + """Return the keypoints with no ``likelihood`` column when at least one other keypoint has one. + + Empty when every keypoint has a likelihood (machine labels) or none does (human labels). + """ + + without = tuple(columns for columns in header.keypoints if LIKELIHOOD_COORD not in columns.coords) + return without if len(without) < len(header.keypoints) else () + + +def non_numeric_columns(df: pd.DataFrame) -> tuple[object, ...]: + """Return the labels of the columns of a wide DataFrame holding text, bool or complex values. + + Empty columns are skipped. + """ + + return tuple(label for label, column in df.items() if not (column.empty or _is_real(column))) + + +def _is_real(column: pd.Series) -> bool: + return ( + pd.api.types.is_numeric_dtype(column) + and not pd.api.types.is_bool_dtype(column) + and not pd.api.types.is_complex_dtype(column) + ) + + +def has_no_frames(row_index: LabeledDataRowIndex) -> bool: + """Return whether the row index has no rows.""" + + return row_index.shape is RowIndexShape.EMPTY + + +def row_index_is_unrecognised(row_index: LabeledDataRowIndex) -> bool: + """Return whether the row index is neither a MultiIndex of path parts nor flat path strings.""" + + return row_index.shape is RowIndexShape.UNRECOGNISED + + +def frames_of_other_depth(row_index: LabeledDataRowIndex) -> tuple[int, ...]: + """Return the positions of the rows whose frame path is not three parts (folder, dataset, image).""" + + return tuple(row for row, frame in enumerate(row_index.frames) if len(frame) != len(FRAME_COLUMNS)) + + +def frames_with_unnamed_parts(row_index: LabeledDataRowIndex) -> tuple[int, ...]: + """Return the positions of the rows whose frame path has a part that is neither text nor an integer (e.g. NaN).""" + + return tuple( + row for row, frame in enumerate(row_index.frames) if any(frame_part_as_text(part) is None for part in frame) + ) diff --git a/dlccore/io/labeled_data/_wide/from_long.py b/dlccore/io/labeled_data/_wide/from_long.py new file mode 100644 index 0000000..58dcda9 --- /dev/null +++ b/dlccore/io/labeled_data/_wide/from_long.py @@ -0,0 +1,57 @@ +# +# 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 +# + +"""``LabeledData`` as DeepLabCut's current wide table: the one form this package writes.""" + +from __future__ import annotations + +import pandas as pd + +from dlccore.io.labeled_data._wide.header import MULTI_ANIMAL_LEVELS, SINGLE_ANIMAL_LEVELS +from dlccore.io.labeled_data.long.model import FRAME_COLUMNS, LabeledData, identity_values + + +def long_to_wide(labels: LabeledData) -> pd.DataFrame: + """Return the wide table DeepLabCut writes today for these labels. + + One row per frame, indexed by path parts. + Levels must hold plain text, never categoricals: DeepLabCut and + napari-deeplabcut group on them without ``observed=``. + + Args: + labels: The labels to write. + """ + + long = labels.to_long_df() + identifiers = labels.identifiers + coords = labels.data_fields.names + n_frames, n_keypoints = long["frame_index"].nunique(), len(identifiers) + + # The long table has one row per (frame, keypoint), all of a frame's keypoints together, in the same order for + # every frame. + frames = long.iloc[::n_keypoints] if n_keypoints else long.iloc[:0] + + # The column header is built from the keypoints, not from the rows; labels with no frames + # are written as a header-only file. + columns = pd.MultiIndex.from_arrays( + [ + *( + pd.Index(values).repeat(len(coords)) + for values in identity_values(identifiers, multi_animal=identifiers.multi_animal).values() + ), + list(coords) * n_keypoints, + ], + names=MULTI_ANIMAL_LEVELS if identifiers.multi_animal else SINGLE_ANIMAL_LEVELS, + ) + index = pd.MultiIndex.from_arrays([frames[name].astype(str).to_numpy() for name in FRAME_COLUMNS]) + values = long[list(coords)].to_numpy().reshape(n_frames, n_keypoints * len(coords)) + + return pd.DataFrame(values, index=index, columns=columns) diff --git a/dlccore/io/labeled_data/_wide/table.py b/dlccore/io/labeled_data/_wide/table.py new file mode 100644 index 0000000..4e8c707 --- /dev/null +++ b/dlccore/io/labeled_data/_wide/table.py @@ -0,0 +1,34 @@ +# +# 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 +# + +"""The wide labeled-data table as any container returns it, and its classification. + +Containers (``h5``, ``csv``) only open files; everything about the table itself is decided here and in the modules +this one calls, once for every container. +""" + +from __future__ import annotations + +import pandas as pd + +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 + + +def classify_wide_df(df: pd.DataFrame) -> tuple[LabeledDataHeader, LabeledDataRowIndex]: + """Classify the header and row index of a wide table, whether read from a file or built in memory.""" + + columns = (column if isinstance(column, tuple) else (column,) for column in df.columns) + + return ( + classify_labeled_data_header(df.columns.names, columns), + classify_labeled_data_row_index(df.index.names, df.index, is_multi_index=isinstance(df.index, pd.MultiIndex)), + ) diff --git a/dlccore/io/labeled_data/_wide/to_long.py b/dlccore/io/labeled_data/_wide/to_long.py new file mode 100644 index 0000000..c1a3271 --- /dev/null +++ b/dlccore/io/labeled_data/_wide/to_long.py @@ -0,0 +1,157 @@ +# +# 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 +# + +"""Conversion of a wide DataFrame to ``LabeledData``. + +Values are taken from the column positions the header classification found, never looked up by level values, so +duplicated or reordered columns cannot pick up the wrong values. +""" + +from __future__ import annotations + +from typing import cast + +import numpy as np +import pandas as pd + +from dlccore.io.labeled_data._checks.file import ( + frames_of_other_depth, + frames_with_unnamed_parts, + has_no_frames, + header_is_unrecognised, + keypoints_missing_likelihood, + keypoints_with_unrecognised_coords, + non_numeric_columns, + row_index_is_unrecognised, +) +from dlccore.io.labeled_data._wide.header import LabeledDataHeader, LabeledDataHeaderShape +from dlccore.io.labeled_data._wide.row_index import LabeledDataRowIndex, frame_part_as_text +from dlccore.io.labeled_data._wide.table import classify_wide_df +from dlccore.io.labeled_data.long.model import ( + FRAME_COLUMNS, + LabeledData, + identity_values, +) +from dlccore.io.labeled_data.model import LIKELIHOOD_COORD, POSITION_COORDS, KeypointIdentifiers + + +def wide_to_long( + df: pd.DataFrame, + header: LabeledDataHeader, + row_index: LabeledDataRowIndex, +) -> LabeledData: + """Convert a wide DataFrame, already classified, to ``LabeledData``: one row per frame and keypoint. + + Values are copied as stored. A frame path part stored as an integer (e.g. a folder named ``2019``) becomes + text, as DeepLabCut's ``guarantee_multiindex_rows`` does; ``row_index`` itself is not changed. + + Args: + df: The wide DataFrame as read. + header: The classified header of ``df``. + row_index: The classified row index of ``df``. + + Raises: + ValueError: On the first of these problems found: + + - Invalid header or row index; + - A frame path is not three parts, or has a part that is neither text nor an integer; + - A keypoint's coordinates are not ``x``, ``y`` and optionally ``likelihood``; + - Some keypoints have a likelihood and others do not; + - A value column is not numeric. + """ + + frames = _frame_parts(row_index) + + if header_is_unrecognised(header): + raise ValueError(f"Header levels {list(header.level_names)} are not a header DeepLabCut writes.") + + positions = _value_positions(df, header) + + n_frames, n_keypoints = len(frames), len(positions) + keypoints = [columns.identifier for columns in header.keypoints] + is_multi_animal = header.shape is LabeledDataHeaderShape.MULTI_ANIMAL + + def values(coordinate: str) -> np.ndarray: + # Frame-major, matching the row order below. + return df.iloc[:, [position[coordinate] for position in positions]].to_numpy(dtype=float).reshape(-1) + + long = {name: _expanded([frame[i] for frame in frames], repeat=n_keypoints) for i, name in enumerate(FRAME_COLUMNS)} + long |= { + name: _expanded(column, tile=n_frames) + for name, column in identity_values(keypoints, multi_animal=is_multi_animal).items() + } + long |= {name: values(name) for name in POSITION_COORDS} + if positions and LIKELIHOOD_COORD in positions[0]: + long[LIKELIHOOD_COORD] = values(LIKELIHOOD_COORD) + long["frame_index"] = np.repeat(np.arange(n_frames, dtype=np.int64), n_keypoints) + long["keypoint_index"] = np.tile(np.arange(n_keypoints, dtype=np.int64), n_frames) + + return LabeledData.from_long_df(pd.DataFrame(long), identifiers=KeypointIdentifiers(keypoints)) + + +def wide_df_to_long(df: pd.DataFrame) -> LabeledData: + """Classify a wide DataFrame's header and row index, then convert it with ``wide_to_long``. + + Raises: + ValueError: As ``wide_to_long``. + """ + + header, row_index = classify_wide_df(df) + return wide_to_long(df, header, row_index) + + +def _value_positions(df: pd.DataFrame, header: LabeledDataHeader) -> list[dict[str, int]]: + """Return each keypoint's column position per coordinate, in header order, or raise the first failed check.""" + + if unrecognised := keypoints_with_unrecognised_coords(header): + columns = unrecognised[0] + raise ValueError( + f"{columns.identifier} has coordinates {list(columns.coords)}; x, y and optionally likelihood are " + "needed, each once." + ) + if lacking := keypoints_missing_likelihood(header): + stores = next(columns.identifier for columns in header.keypoints if LIKELIHOOD_COORD in columns.coords) + raise ValueError( + f"Some keypoints store a likelihood and others do not: {stores} does, {lacking[0].identifier} does not." + ) + if not_numeric := non_numeric_columns(df): + raise ValueError(f"Value columns {list(not_numeric)} are not numeric.") + + return [dict(zip(columns.coords, columns.positions, strict=True)) for columns in header.keypoints] + + +def _expanded(values: list[str], *, repeat: int = 1, tile: int = 1) -> pd.Categorical: + """Return ``values`` repeated element-wise, then tiled, as a categorical built from integer codes. + + Only the codes are expanded to one per row; the text is hashed once per distinct value, never once per row. + """ + + codes, categories = pd.factorize(np.asarray(values, dtype=object), sort=True) + return pd.Categorical.from_codes(np.tile(np.repeat(codes, repeat), tile), categories=categories) + + +def _frame_parts(row_index: LabeledDataRowIndex) -> list[tuple[str, ...]]: + """Return each frame's three parts as text, none for a table with no rows, or raise.""" + + if has_no_frames(row_index): + return [] + if row_index_is_unrecognised(row_index): + entry = next(entry for entry in row_index.entries if not isinstance(entry, str)) + raise ValueError(f"The row index is neither path parts nor path strings: entry {entry!r} is not text.") + + if other_depth := frames_of_other_depth(row_index): + frame = row_index.frames[other_depth[0]] + raise ValueError(f"Frame {frame} has {len(frame)} parts; the model needs {len(FRAME_COLUMNS)}.") + if unnamed := frames_with_unnamed_parts(row_index): + frame = row_index.frames[unnamed[0]] + part = next(part for part in frame if frame_part_as_text(part) is None) + raise ValueError(f"Frame {frame} has a part {part!r} that is neither text nor an integer.") + return [tuple(cast("str", frame_part_as_text(part)) for part in frame) for frame in row_index.frames] diff --git a/dlccore/io/labeled_data/arrays/__init__.py b/dlccore/io/labeled_data/arrays/__init__.py new file mode 100644 index 0000000..7250a92 --- /dev/null +++ b/dlccore/io/labeled_data/arrays/__init__.py @@ -0,0 +1,12 @@ +# +# 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 as arrays: a view of the long model, built by ``LabeledData.to_arrays()``.""" diff --git a/dlccore/io/labeled_data/arrays/from_long.py b/dlccore/io/labeled_data/arrays/from_long.py new file mode 100644 index 0000000..e240b97 --- /dev/null +++ b/dlccore/io/labeled_data/arrays/from_long.py @@ -0,0 +1,114 @@ +# +# 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 +# + +"""``LabeledData`` as read-only arrays: axis 0 is the frame, axis 1 the keypoint.""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import TYPE_CHECKING + +import numpy as np + +from dlccore.io.labeled_data.model import ( + LIKELIHOOD_COORD, + POSITION_COORDS, + FramePath, + KeypointDataFields, + KeypointIdentifiers, +) + +if TYPE_CHECKING: + from dlccore.io.labeled_data.long.model import LabeledData + +# TODO: 3D support, NPZ export + + +@dataclass(frozen=True, eq=False) +class LabeledDataArrays: + """Canonical array view of labeled data as [frames, keypoints]. + + Values are as stored, with no interpretation beyond "a coordinate pair is present". Compared and hashed by + identity, since arrays have no single truth value. + + Attributes: + frames: The frames, in frame order. + identifiers: The keypoints' identifiers, in keypoint order. + data_fields: What each keypoint stores; says whether ``likelihood`` is present. + xy: Shape ``(frames, keypoints, 2)``; values as stored, NaN where missing. + likelihood: Shape ``(frames, keypoints)``, NaN where missing; ``None`` when the labels store none. + """ + + frames: tuple[FramePath, ...] + identifiers: KeypointIdentifiers + data_fields: KeypointDataFields + xy: np.ndarray + likelihood: np.ndarray | None + + def __post_init__(self) -> None: + """Refuse arrays that do not have one entry per frame and keypoint. + + Raises: + ValueError: If ``xy`` is not ``(frames, keypoints, 2)``, ``likelihood`` not ``(frames, keypoints)``, or + ``likelihood`` is present when ``data_fields`` says it is not, or the reverse. + """ + + if (self.likelihood is not None) != self.data_fields.has_likelihood: + raise ValueError( + f"likelihood is {'present' if self.likelihood is not None else 'absent'}; " + f"data_fields.has_likelihood is {self.data_fields.has_likelihood}." + ) + + shape = (len(self.frames), len(self.identifiers)) + if self.xy.shape != (*shape, 2): + raise ValueError( + f"xy has shape {self.xy.shape}; {shape[0]} frames and {shape[1]} keypoints need {(*shape, 2)}." + ) + if self.likelihood is not None and self.likelihood.shape != shape: + raise ValueError( + f"likelihood has shape {self.likelihood.shape}; {shape[0]} frames and {shape[1]} keypoints need " + f"{shape}." + ) + + @property + def labeled(self) -> np.ndarray: + """Where both coordinates are present, shape ``(frames, keypoints)``; their values are not judged.""" + + return ~np.isnan(self.xy).any(axis=-1) + + +def long_to_arrays(labels: LabeledData) -> LabeledDataArrays: + """Return the labels as read-only arrays in frame then keypoint order, values as stored. + + Args: + labels: The labels to view. + """ + + long = labels.to_long_df() + identifiers, data_fields = labels.identifiers, labels.data_fields + n_frames, n_keypoints = long["frame_index"].nunique(), len(identifiers) + + frames = labels.frames + + def values(coordinate: str) -> np.ndarray: + return long[coordinate].to_numpy(dtype=float, copy=True).reshape(n_frames, n_keypoints) + + xy = np.stack([values(coordinate) for coordinate in POSITION_COORDS], axis=-1) + likelihood = values(LIKELIHOOD_COORD) if data_fields.has_likelihood else None + + return LabeledDataArrays( + frames, identifiers, data_fields, _read_only(xy), None if likelihood is None else _read_only(likelihood) + ) + + +def _read_only(array: np.ndarray) -> np.ndarray: + array.setflags(write=False) + return array diff --git a/dlccore/io/labeled_data/long/__init__.py b/dlccore/io/labeled_data/long/__init__.py new file mode 100644 index 0000000..a3b94cd --- /dev/null +++ b/dlccore/io/labeled_data/long/__init__.py @@ -0,0 +1,16 @@ +# +# 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 as one long table: the model every format converts to and from. + +Each format's conversion code lives in that format's module. A format behind an optional extra is reached only through +free functions there, never through a ``LabeledData`` method, so the model needs no extra. +""" diff --git a/dlccore/io/labeled_data/long/model.py b/dlccore/io/labeled_data/long/model.py new file mode 100644 index 0000000..e1d3d7f --- /dev/null +++ b/dlccore/io/labeled_data/long/model.py @@ -0,0 +1,308 @@ +# +# 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 +# + +"""``LabeledData``: every keypoint in every frame as one long table, and the contract it holds.""" + +from __future__ import annotations + +from collections import Counter +from collections.abc import Sequence +from dataclasses import dataclass, field +from typing import TYPE_CHECKING, Literal, cast + +import pandas as pd + +from dlccore.io.labeled_data.model import ( + LIKELIHOOD_COORD, + FramePath, + KeypointDataFields, + KeypointIdentifier, + KeypointIdentifiers, +) + +if TYPE_CHECKING: + from dlccore.io.labeled_data.arrays.from_long import LabeledDataArrays + +FRAME_COLUMNS = ("folder", "dataset", "image") +SINGLE_ANIMAL_KEYPOINT_COLUMNS = ("scorer", "bodypart") +MULTI_ANIMAL_KEYPOINT_COLUMNS = ("scorer", "individual", "bodypart") +ORDER_COLUMNS = ("frame_index", "keypoint_index") + +# 0.x carries no compatibility promise. +LabeledDataLongVersion = Literal["0.0"] +LABELED_DATA_LONG_VERSION: LabeledDataLongVersion = "0.0" + + +@dataclass(frozen=True, eq=False) +class LabeledData: + """Every keypoint in every frame, one row each: dense, NaN where unlabeled, frozen. + + Stores its keypoints separately from the table, so labels with no frames keep their header's keypoints. + When the table has rows, each frame lists exactly these keypoints, labeled or not, in the same order. + Construction rejects a table with wrong columns, wrong dtypes or inconsistent keypoints, but never checks the + coordinate values themselves: NaN (unlabeled) and infinite values are kept as given. + Every method returns a new object, and the table itself is private. + Compared and hashed by identity, as a DataFrame has neither value + equality nor a hash. + + Methods convert only to forms built from core dependencies (the wide DataFrame, arrays). A format that needs an + optional extra is converted by free functions in that format's own module, so this class never imports one. + """ + + _df: pd.DataFrame = field(repr=False) + _identifiers: KeypointIdentifiers | None = None + + def __post_init__(self) -> None: + """Check the table against the contract, keeping a copy in frame then keypoint order, and its identifiers. + + Raises: + ValueError: on the first broken rule: columns, dtypes, density, or identities; or identifiers that are + missing for a table with no rows, or that disagree with the rows. + """ + + checked = _checked(self._df) + object.__setattr__(self, "_df", checked) + object.__setattr__(self, "_identifiers", _checked_identifiers(checked, self._identifiers)) + + @classmethod + def from_long_df(cls, df: pd.DataFrame, *, identifiers: KeypointIdentifiers | None = None) -> LabeledData: + """Wrap a long table holding the contract. + + The data fields are always the table's value columns, so only the identifiers can be given. + + Args: + df: One row per frame and keypoint, in either schema; any column and row order. + identifiers: The table's keypoint identifiers. Required when ``df`` has no rows, which cannot name them; + otherwise checked against the rows. Code that selects frames passes them, so selecting none keeps + them. + + Raises: + ValueError: on the first broken rule: columns, dtypes, density, or identities; if ``df`` has no rows + and ``identifiers`` is not given; or if ``identifiers`` disagrees with ``df``. + """ + + return cls(df, identifiers) + + @classmethod + def without_frames(cls, identifiers: KeypointIdentifiers, data_fields: KeypointDataFields) -> LabeledData: + """Labels with these keypoints and no frames, as a labels file holding only its header. + + Args: + identifiers: The keypoints' identifiers. + data_fields: What each keypoint stores; with no table, nothing else can say. + """ + + identities = MULTI_ANIMAL_KEYPOINT_COLUMNS if identifiers.multi_animal else SINGLE_ANIMAL_KEYPOINT_COLUMNS + empty = {name: pd.Categorical([], categories=pd.Index([], dtype=object)) for name in FRAME_COLUMNS + identities} + empty |= {name: pd.Series([], dtype="float64") for name in data_fields.names} + empty |= {name: pd.Series([], dtype="int64") for name in ORDER_COLUMNS} + + return cls(pd.DataFrame(empty), identifiers) + + @classmethod + def from_wide_df(cls, df: pd.DataFrame) -> LabeledData: + """Build labels from a wide DataFrame, converting it as reading a file does. + + Args: + df: A wide DataFrame in any layout DeepLabCut reads. + + Raises: + ValueError: If ``df`` cannot be converted; see ``wide.to_long.wide_to_long`` for the cases. + """ + + from dlccore.io.labeled_data._wide.to_long import wide_df_to_long + + return wide_df_to_long(df) + + @property + def identifiers(self) -> KeypointIdentifiers: + """The keypoints' identifiers, in order, also for labels with no frames; ``to_arrays().identifiers``.""" + + return cast("KeypointIdentifiers", self._identifiers) + + @property + def data_fields(self) -> KeypointDataFields: + """What each keypoint stores: the table's value columns, also for labels with no frames.""" + + return KeypointDataFields.make_2d(with_likelihood=LIKELIHOOD_COORD in self._df.columns) + + @property + def frames(self) -> tuple[FramePath, ...]: + """Each frame's path, in frame order; empty for labels with no frames. Two frames may share a path.""" + + starts = self._df.drop_duplicates("frame_index") + return tuple(zip(*(starts[name].astype(str) for name in FRAME_COLUMNS), strict=True)) + + def select(self, *, frame_positions: Sequence[int]) -> LabeledData: + """Labels for the selected frames in the order requested. Identifiers and data fields are unchanged. + + Args: + frame_positions: Requested positions in ``frames``, each at most once. + + Raises: + ValueError: If a position is out of range or given twice. + """ + + positions = list(frame_positions) + n_frames = self._df["frame_index"].nunique() + if outside := [p for p in positions if not 0 <= p < n_frames]: + raise ValueError(f"Frame positions {outside} are out of range; the labels have {n_frames} frames.") + if repeated := sorted(p for p, count in Counter(positions).items() if count > 1): + raise ValueError(f"Frame positions {repeated} are given more than once; a frame is selected once.") + + renumbered = pd.Series(range(len(positions)), index=positions, dtype="int64") + df = self._df[self._df["frame_index"].isin(positions)].copy() + df["frame_index"] = df["frame_index"].map(renumbered).astype("int64") + return LabeledData.from_long_df(df, identifiers=self.identifiers) + + def to_arrays(self) -> LabeledDataArrays: + from dlccore.io.labeled_data.arrays.from_long import long_to_arrays + + return long_to_arrays(self) + + def to_wide_df(self) -> pd.DataFrame: + from dlccore.io.labeled_data._wide.from_long import long_to_wide + + return long_to_wide(self) + + def to_long_df(self) -> pd.DataFrame: + """A copy of the table, rows ordered by frame then keypoint.""" + return self._df.copy() + + +def identity_columns(df: pd.DataFrame) -> tuple[str, ...]: + """The columns naming a keypoint: the only place that branches on single- or multi-animal.""" + + return MULTI_ANIMAL_KEYPOINT_COLUMNS if "individual" in df.columns else SINGLE_ANIMAL_KEYPOINT_COLUMNS + + +def identity_values(identifiers: Sequence[KeypointIdentifier], *, multi_animal: bool) -> dict[str, list[str | None]]: + """The identity columns of ``identifiers``, one value per keypoint: the only place attributes become columns.""" + + values = { + "scorer": [k.scorer for k in identifiers], + "individual": [k.individual for k in identifiers], + "bodypart": [k.bodypart for k in identifiers], + } + columns = MULTI_ANIMAL_KEYPOINT_COLUMNS if multi_animal else SINGLE_ANIMAL_KEYPOINT_COLUMNS + return {name: values[name] for name in columns} + + +def identifiers_of(identities: pd.DataFrame) -> tuple[KeypointIdentifier, ...]: + """One ``KeypointIdentifier`` per row of a table holding the identity columns, in row order.""" + + columns = {name: identities[name].astype(str).tolist() for name in identity_columns(identities)} + individuals = columns.get("individual", [None] * len(identities)) + return tuple( + KeypointIdentifier(scorer=s, individual=i, bodypart=b) + for s, i, b in zip(columns["scorer"], individuals, columns["bodypart"], strict=True) + ) + + +def _checked(df: pd.DataFrame) -> pd.DataFrame: + keypoint_columns = identity_columns(df) + text_columns = FRAME_COLUMNS + keypoint_columns + value_columns = KeypointDataFields.make_2d(with_likelihood=LIKELIHOOD_COORD in df.columns).names + expected = text_columns + value_columns + ORDER_COLUMNS + + if sorted(df.columns) != sorted(expected): + raise ValueError(f"Columns are {sorted(df.columns)}; this schema needs exactly {sorted(expected)}.") + + for column in text_columns: + dtype = df[column].dtype + if not isinstance(dtype, pd.CategoricalDtype) or not all(isinstance(c, str) for c in dtype.categories): + raise ValueError(f"Column {column!r} is {dtype}; it must be categorical with text categories.") + if df[column].isna().any(): + row = df.index[df[column].isna()][0] + raise ValueError(f"Column {column!r} is missing at row {row}; every row names its frame and keypoint.") + for column in value_columns: + if df[column].dtype != "float64": + raise ValueError(f"Column {column!r} is {df[column].dtype}; it must be float64.") + for column in ORDER_COLUMNS: + if df[column].dtype != "int64": + raise ValueError(f"Column {column!r} is {df[column].dtype}; it must be int64.") + checked = df[list(expected)].sort_values(list(ORDER_COLUMNS)).reset_index(drop=True) + _check_dense(checked) + + for index, identity in (("frame_index", FRAME_COLUMNS), ("keypoint_index", keypoint_columns)): + disagreeing = checked.groupby(index, observed=True)[list(identity)].nunique() > 1 + if disagreeing.any(axis=None): + value = disagreeing.any(axis=1).idxmax() + columns = list(disagreeing.columns[disagreeing.loc[value]]) + raise ValueError(f"Rows with {index} {int(value)} disagree on {columns}.") + + keypoints = checked.drop_duplicates("keypoint_index") + repeated = keypoints[keypoints.duplicated(list(keypoint_columns), keep=False)] + if not repeated.empty: + groups = repeated.groupby(list(keypoint_columns), observed=True)["keypoint_index"].apply(list) + raise ValueError(f"keypoint_index values {groups.iloc[0]} all name the keypoint {groups.index[0]}.") + + # One representation per dataset: only the categories in use, in sorted order. + for column in text_columns: + used = checked[column].cat.remove_unused_categories() + checked[column] = used.cat.reorder_categories(sorted(used.cat.categories)) + + return checked + + +def _checked_identifiers(df: pd.DataFrame, given: KeypointIdentifiers | None) -> KeypointIdentifiers: + """Return the identifiers of a checked table: ``given`` if it agrees with the rows, else those the rows name. + + Raises: + ValueError: If ``df`` has no rows and nothing is given, or ``given`` disagrees with the table on its keypoints, + their order or individuals. + """ + + multi_animal = identity_columns(df) == MULTI_ANIMAL_KEYPOINT_COLUMNS + + if given is None: + if df.empty: + raise ValueError("The table has no rows, so it cannot name its keypoints; pass them as identifiers.") + return KeypointIdentifiers(identifiers_of(df.iloc[: df["keypoint_index"].nunique()])) + + if given and given.multi_animal is not multi_animal: + raise ValueError( + f"The identifiers {'name' if given.multi_animal else 'do not name'} individuals; " + f"the table {'has' if multi_animal else 'has no'} individual column." + ) + if not df.empty: + named = identifiers_of(df.iloc[: df["keypoint_index"].nunique()]) + if named != given.identifiers: + first = next((i for i, (a, b) in enumerate(zip(named, given.identifiers, strict=False)) if a != b), None) + detail = ( + f"{len(named)} keypoints in the table, {len(given)} given" + if first is None + else f"keypoint_index {first} is {named[first]} in the table, {given[first]} given" + ) + raise ValueError(f"The identifiers disagree with the table: {detail}.") + return given + + +def _check_dense(df: pd.DataFrame) -> None: + """Raise naming the first repeated, missing or out-of-range (frame_index, keypoint_index) pair, if any.""" + + n_frames, n_keypoints = df["frame_index"].nunique(), df["keypoint_index"].nunique() + dense = pd.MultiIndex.from_product([range(n_frames), range(n_keypoints)], names=list(ORDER_COLUMNS)) + actual = pd.MultiIndex.from_frame(df[list(ORDER_COLUMNS)]) + + if actual.equals(dense): + return + + offenders = ( + ("repeated", actual[actual.duplicated()]), + ("missing", dense.difference(actual)), + ("out of range", actual.difference(dense)), + ) + first = "; ".join(f"{kind} {tuple(int(i) for i in pairs[0])}" for kind, pairs in offenders if len(pairs)) + raise ValueError( + f"Rows must be dense, each frame_index 0..{n_frames - 1} with each keypoint_index 0..{n_keypoints - 1} exactly " + f"once; first (frame_index, keypoint_index) {first}." + ) 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..1766ac6 --- /dev/null +++ b/tests/io/labeled_data/arrays/test_arrays.py @@ -0,0 +1,105 @@ +# +# 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 + +import numpy as np +import pandas as pd +import pytest + +from dlccore.io.labeled_data import ( + KeypointDataFields, + KeypointIdentifier, + KeypointIdentifiers, + LabeledData, + LabeledDataArrays, +) + +FRAMES = (("labeled-data", "s1", "img0.png"), ("labeled-data", "s1", "img1.png")) +KEYPOINTS = tuple(KeypointIdentifier("Sc", None, bodypart) for bodypart in ("nose", "tail", "ear")) + + +def _arrays(**changes: object) -> LabeledDataArrays: + arrays = LabeledDataArrays( + FRAMES, + KeypointIdentifiers(KEYPOINTS), + KeypointDataFields.make_2d(with_likelihood=True), + 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().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) + + +@pytest.mark.parametrize("has_likelihood", [True, False]) +def test_likelihood_is_present_exactly_when_the_data_fields_say_so(has_likelihood: bool) -> None: + data_fields = KeypointDataFields.make_2d(with_likelihood=not has_likelihood) + + with pytest.raises(ValueError, match="has_likelihood"): + _arrays(data_fields=data_fields, likelihood=np.zeros((2, 3)) if has_likelihood else None) + + +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(KeypointIdentifier)] == ["scorer", "individual", "bodypart"] diff --git a/tests/io/labeled_data/long/test_long_boundaries.py b/tests/io/labeled_data/long/test_long_boundaries.py new file mode 100644 index 0000000..3eb2de2 --- /dev/null +++ b/tests/io/labeled_data/long/test_long_boundaries.py @@ -0,0 +1,62 @@ +# +# 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 +# + +"""``LabeledData``'s table is private to ``long/``, and its public names change only by a reviewed edit here.""" + +import ast +from pathlib import Path + +import dlccore +from dlccore.io.labeled_data.long.model import LabeledData + +PACKAGE_ROOT = Path(dlccore.__file__).parent +LONG = PACKAGE_ROOT / "io" / "labeled_data" / "long" +PRIVATE_TABLE = "_df" + + +def _modules_touching_the_table() -> set[Path]: + return { + path.relative_to(PACKAGE_ROOT) + for path in PACKAGE_ROOT.rglob("*.py") + for node in ast.walk(ast.parse(path.read_text(encoding="utf-8"))) + if isinstance(node, ast.Attribute) and node.attr == PRIVATE_TABLE + } + + +def test_the_scan_sees_the_table_in_long() -> None: + # Control: a scan that matched nothing would let the test below pass. + assert (LONG / "model.py").relative_to(PACKAGE_ROOT) in _modules_touching_the_table() + + +def test_the_private_table_is_touched_only_in_long() -> None: + # Everything outside long/ goes through the public API, so the table's layout can change behind it. + outside = {path for path in _modules_touching_the_table() if LONG.relative_to(PACKAGE_ROOT) not in path.parents} + + assert outside == set() + + +def test_the_public_surface_is_pinned() -> None: + # Adding a name is a reviewed diff here, not drift: an operation that does not need the private table belongs + # outside the class. + public = {name for name in dir(LabeledData) if not name.startswith("_")} + + assert public == { + "from_long_df", + "from_wide_df", + "data_fields", + "frames", + "identifiers", + "select", + "to_arrays", + "to_long_df", + "to_wide_df", + "without_frames", + } diff --git a/tests/io/labeled_data/long/test_long_model.py b/tests/io/labeled_data/long/test_long_model.py new file mode 100644 index 0000000..69980ef --- /dev/null +++ b/tests/io/labeled_data/long/test_long_model.py @@ -0,0 +1,286 @@ +# +# 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 re +from collections.abc import Callable +from dataclasses import FrozenInstanceError + +import numpy as np +import pandas as pd +import pytest + +from dlccore.io.labeled_data.long.model import LABELED_DATA_LONG_VERSION, LabeledData +from dlccore.io.labeled_data.model import KeypointIdentifiers + +TEXT_COLUMNS = ("folder", "dataset", "image", "scorer", "individual", "bodypart") +# What each long-format version holds, multi-animal with likelihood: columns in order, with their dtypes. +LONG_FORMATS = { + "0.0": [ + *((column, "category") for column in TEXT_COLUMNS), + ("x", "float64"), + ("y", "float64"), + ("likelihood", "float64"), + ("frame_index", "int64"), + ("keypoint_index", "int64"), + ], +} + + +def _long(*, multi: bool = False, likelihood: bool = False) -> pd.DataFrame: + """Two frames by two keypoints, frame-major, with text columns categorical as the contract requires.""" + + rows = [] + for frame_index, image in enumerate(("img0.png", "img1.png")): + for keypoint_index, bodypart in enumerate(("nose", "tail")): + row = { + "folder": "labeled-data", + "dataset": "s1", + "image": image, + "scorer": "Sc", + "individual": "mouse1", + "bodypart": bodypart, + "x": 1.0 + frame_index, + "y": np.nan, + "likelihood": 0.5, + "frame_index": frame_index, + "keypoint_index": keypoint_index, + } + rows.append(row) + df = pd.DataFrame(rows) + if not multi: + df = df.drop(columns="individual") + if not likelihood: + df = df.drop(columns="likelihood") + for column in TEXT_COLUMNS: + if column in df.columns: + df[column] = df[column].astype("category") + return df + + +@pytest.mark.parametrize("multi", [False, True], ids=["single", "multi"]) +@pytest.mark.parametrize("likelihood", [False, True], ids=["xy", "likelihood"]) +def test_a_table_holding_the_contract_is_wrapped_unchanged(*, multi: bool, likelihood: bool) -> None: + # Control for every refusal below. + df = _long(multi=multi, likelihood=likelihood) + + labels = LabeledData.from_long_df(df) + + assert labels.identifiers.multi_animal is multi + assert labels.data_fields.has_likelihood is likelihood + pd.testing.assert_frame_equal(labels.to_long_df(), df[labels.to_long_df().columns]) + + +def test_rows_in_any_order_come_back_ordered_by_frame_then_keypoint() -> None: + df = _long() + + labels = LabeledData.from_long_df(df.iloc[::-1]) + + pd.testing.assert_frame_equal(labels.to_long_df(), df[labels.to_long_df().columns]) + + +def test_the_table_cannot_be_changed_through_its_view_or_its_attributes() -> None: + labels = LabeledData.from_long_df(_long()) + + view = labels.to_long_df() + view.loc[0, "x"] = 99.0 + + assert labels.to_long_df().loc[0, "x"] == 1.0 + with pytest.raises(FrozenInstanceError): + labels._df = _long() # type: ignore[misc] + + +def test_constructing_directly_checks_the_contract_too() -> None: + with pytest.raises(ValueError, match="Columns"): + LabeledData(_long().drop(columns="bodypart")) + + +def test_categories_are_canonical_whatever_the_caller_built() -> None: + # One dataset, one representation: unused categories dropped, the rest sorted. + canonical = LabeledData.from_long_df(_long()).to_long_df() + df = _long() + df["bodypart"] = df["bodypart"].cat.add_categories(["ghost"]).cat.reorder_categories(["tail", "ghost", "nose"]) + + built = LabeledData.from_long_df(df).to_long_df() + + pd.testing.assert_frame_equal(built, canonical) + assert list(built["bodypart"].cat.categories) == ["nose", "tail"] + + +def _drop_column(df: pd.DataFrame) -> pd.DataFrame: + return df.drop(columns="bodypart") + + +def _add_column(df: pd.DataFrame) -> pd.DataFrame: + return df.assign(scope="individual") + + +def _text_as_object(df: pd.DataFrame) -> pd.DataFrame: + return df.assign(image=df["image"].astype(object)) + + +def _numeric_categories(df: pd.DataFrame) -> pd.DataFrame: + return df.assign(dataset=pd.Categorical([1, 1, 1, 1])) + + +def _missing_text(df: pd.DataFrame) -> pd.DataFrame: + return df.assign(bodypart=df["bodypart"].where(df.index != 0)) + + +def _integer_values(df: pd.DataFrame) -> pd.DataFrame: + return df.assign(x=df["x"].astype("int64")) + + +def _float_order(df: pd.DataFrame) -> pd.DataFrame: + return df.assign(frame_index=df["frame_index"].astype("float64")) + + +def _no_rows(df: pd.DataFrame) -> pd.DataFrame: + return df.iloc[:0] + + +def _row_missing(df: pd.DataFrame) -> pd.DataFrame: + return df.drop(index=3) + + +def _row_repeated(df: pd.DataFrame) -> pd.DataFrame: + return pd.concat([df, df.iloc[[0]]]) + + +def _index_skipped(df: pd.DataFrame) -> pd.DataFrame: + return df.assign(frame_index=df["frame_index"] * 2) + + +def _frame_parts_disagree(df: pd.DataFrame) -> pd.DataFrame: + return df.assign(image=pd.Categorical(["img0.png", "other.png", "img1.png", "img1.png"])) + + +def _keypoint_names_disagree(df: pd.DataFrame) -> pd.DataFrame: + return df.assign(bodypart=pd.Categorical(["nose", "tail", "ear", "tail"])) + + +def _two_indices_one_keypoint(df: pd.DataFrame) -> pd.DataFrame: + return df.assign(bodypart=pd.Categorical(["nose"] * 4)) + + +@pytest.mark.parametrize( + ("break_contract", "message"), + [ + (_drop_column, "Columns"), + (_add_column, "Columns"), + (_text_as_object, "categorical"), + (_numeric_categories, "categorical"), + (_missing_text, "missing at row 0"), + (_integer_values, "float64"), + (_float_order, "int64"), + (_no_rows, "cannot name its keypoints"), + (_row_missing, re.escape("missing (1, 1)")), + (_row_repeated, re.escape("repeated (0, 0)")), + (_index_skipped, re.escape("missing (1, 0); out of range (2, 0)")), + (_frame_parts_disagree, re.escape("frame_index 0 disagree on ['image']")), + (_keypoint_names_disagree, re.escape("keypoint_index 0 disagree on ['bodypart']")), + (_two_indices_one_keypoint, re.escape("values [0, 1] all name the keypoint ('Sc', 'nose')")), + ], +) +def test_a_table_breaking_the_contract_is_refused_with_the_rule( + break_contract: Callable[[pd.DataFrame], pd.DataFrame], message: str +) -> None: + with pytest.raises(ValueError, match=message): + LabeledData.from_long_df(break_contract(_long())) + + +def test_a_table_with_no_rows_takes_the_keypoints_it_is_given() -> None: + keypoints = LabeledData.from_long_df(_long()).identifiers + + labels = LabeledData.from_long_df(_long().iloc[:0], identifiers=keypoints) + + assert labels.identifiers == keypoints + assert labels.to_long_df().empty + + +def test_keypoints_given_with_rows_must_be_the_rows_keypoints_in_order() -> None: + identifiers = LabeledData.from_long_df(_long()).identifiers + reordered = KeypointIdentifiers(tuple(reversed(identifiers))) + + with pytest.raises(ValueError, match=re.escape("keypoint_index 0 is")): + LabeledData.from_long_df(_long(), identifiers=reordered) + + +@pytest.mark.parametrize(("multi", "likelihood"), [(False, False), (True, False), (False, True), (True, True)]) +def test_labels_without_frames_have_the_full_tables_columns_and_no_rows(multi: bool, likelihood: bool) -> None: + full = LabeledData.from_long_df(_long(multi=multi, likelihood=likelihood)) + + empty = LabeledData.without_frames(full.identifiers, full.data_fields) + + assert (empty.identifiers, empty.data_fields) == (full.identifiers, full.data_fields) + assert empty.to_long_df().empty + + def schema(labels: LabeledData) -> list[tuple[str, str]]: + return [(column, str(dtype)) for column, dtype in labels.to_long_df().dtypes.items()] + + assert schema(empty) == schema(full) + + +FRAME_0 = ("labeled-data", "s1", "img0.png") +FRAME_1 = ("labeled-data", "s1", "img1.png") + + +def test_frames_are_the_frame_paths_in_frame_order() -> None: + labels = LabeledData.from_long_df(_long()) + + assert labels.frames == (FRAME_0, FRAME_1) + assert LabeledData.without_frames(labels.identifiers, labels.data_fields).frames == () + + +def test_selecting_frames_keeps_them_in_the_order_given_with_their_values() -> None: + labels = LabeledData.from_long_df(_long(multi=True, likelihood=True)) + + selected = labels.select(frame_positions=[1, 0]) + + assert selected.frames == (FRAME_1, FRAME_0) + assert (selected.identifiers, selected.data_fields) == (labels.identifiers, labels.data_fields) + np.testing.assert_array_equal(selected.to_arrays().xy, labels.to_arrays().xy[[1, 0]]) + + +@pytest.mark.parametrize("likelihood", [False, True], ids=["xy", "likelihood"]) +def test_selecting_no_frame_keeps_the_keypoints_and_data_fields(likelihood: bool) -> None: + labels = LabeledData.from_long_df(_long(multi=True, likelihood=likelihood)) + + selected = labels.select(frame_positions=[]) + + assert selected.frames == () + assert (selected.identifiers, selected.data_fields) == (labels.identifiers, labels.data_fields) + + +def test_one_of_two_frames_sharing_a_path_can_be_selected() -> None: + # A repeated frame, as dropduplicatesinannotatinfiles removes: positions tell the copies apart, paths cannot. + df = _long() + df["image"] = pd.Categorical(["img0.png"] * len(df)) + labels = LabeledData.from_long_df(df) + + selected = labels.select(frame_positions=[0]) + + assert labels.frames == (FRAME_0, FRAME_0) + assert selected.frames == (FRAME_0,) + + +@pytest.mark.parametrize( + ("positions", "message"), + [([2], "Frame positions [2] are out of range"), ([-1], "[-1] are out of range"), ([0, 0], "[0] are given more")], +) +def test_selecting_a_frame_that_is_not_there_or_twice_is_refused(positions: list[int], message: str) -> None: + with pytest.raises(ValueError, match=re.escape(message)): + LabeledData.from_long_df(_long()).select(frame_positions=positions) + + +def test_the_long_format_changes_only_with_its_version() -> None: + held = LabeledData.from_long_df(_long(multi=True, likelihood=True)).to_long_df() + + assert [(column, str(dtype)) for column, dtype in held.dtypes.items()] == LONG_FORMATS[LABELED_DATA_LONG_VERSION] diff --git a/tests/io/labeled_data/test_checks.py b/tests/io/labeled_data/test_checks.py new file mode 100644 index 0000000..7c242dc --- /dev/null +++ b/tests/io/labeled_data/test_checks.py @@ -0,0 +1,130 @@ +# +# 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 pandas as pd +import pytest + +from dlccore.io.labeled_data import KeypointIdentifier, LabeledData +from dlccore.io.labeled_data._checks.file import ( + frames_of_other_depth, + frames_with_unnamed_parts, + has_no_frames, + header_is_unrecognised, + keypoints_missing_likelihood, + keypoints_with_unrecognised_coords, + non_numeric_columns, + row_index_is_unrecognised, +) +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 + +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) -> KeypointIdentifier: + return KeypointIdentifier(scorer, individual, bodypart) + + +WITH_LIKELIHOOD = _labels([("Sc", "nose")], coords=("x", "y", "likelihood")) + + +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.identifier.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.identifier.bodypart for columns in keypoints_missing_likelihood(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_missing_likelihood(_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")]})) == () 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..8bb1482 --- /dev/null +++ b/tests/io/labeled_data/wide/test_from_long.py @@ -0,0 +1,80 @@ +# +# 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 + +from dlccore.io.labeled_data._wide.from_long import long_to_wide +from dlccore.io.labeled_data._wide.to_long import wide_df_to_long +from dlccore.io.labeled_data.long.model import LabeledData + +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: + 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, ...]]: + return [("Sc", bodypart, coord) for bodypart in ("nose", "tail") for coord in coords] + + +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_to_long.py b/tests/io/labeled_data/wide/test_to_long.py new file mode 100644 index 0000000..0709a4d --- /dev/null +++ b/tests/io/labeled_data/wide/test_to_long.py @@ -0,0 +1,146 @@ +# +# 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.to_long import wide_df_to_long +from dlccore.io.labeled_data.long.model import LabeledData + +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. + 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: + 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_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.identifiers.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.data_fields.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_a_header_with_no_rows_is_a_model_holding_the_headers_keypoints() -> None: + labels = _single_animal([], pd.Index([], dtype=object)) + + assert [keypoint.bodypart for keypoint in labels.identifiers] == ["nose", "tail"] + assert labels.to_long_df().empty + assert labels.to_arrays().xy.shape == (0, 2, 2) + + +@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"), + ], + ids=["four_parts", "float_part", "bool_part", "integer_index"], +) +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"])