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..a922b59 --- /dev/null +++ b/dlccore/io/labeled_data/arrays/from_long.py @@ -0,0 +1,102 @@ +# +# 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.long.model import FRAME_COLUMNS, keypoints_of +from dlccore.io.labeled_data.model import LIKELIHOOD_COORD, POSITION_COORDS, FramePath, Keypoint + +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. + keypoints: The keypoints, in keypoint order. + 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, ...] + keypoints: tuple[Keypoint, ...] + 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)``, or ``likelihood`` not ``(frames, keypoints)``. + """ + + shape = (len(self.frames), len(self.keypoints)) + 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() + n_frames, n_keypoints = long["frame_index"].nunique(), long["keypoint_index"].nunique() + + # Rows are frame-major, so the first frame's rows name the keypoints and every K-th row starts a frame. + first_frame = long.iloc[:n_keypoints] + frame_starts = long.iloc[::n_keypoints] if n_keypoints else long.iloc[:0] + + frames = tuple(zip(*(frame_starts[name].astype(str) for name in FRAME_COLUMNS), strict=True)) + keypoints = keypoints_of(first_frame) + + 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 labels.has_likelihood else None + + return LabeledDataArrays(frames, keypoints, _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..04d6d8b --- /dev/null +++ b/dlccore/io/labeled_data/long/model.py @@ -0,0 +1,194 @@ +# +# 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.abc import Sequence +from dataclasses import dataclass, field +from typing import TYPE_CHECKING, Literal + +import pandas as pd + +from dlccore.io.labeled_data.model import LIKELIHOOD_COORD, POSITION_COORDS, Keypoint + +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. + + Strict on columns, dtypes and identities, never on values. + 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) + + def __post_init__(self) -> None: + """Check the table against the contract, keeping a copy in frame then keypoint order. + + Raises: + ValueError: Naming the first broken rule: columns, dtypes, density, or identities. + """ + + object.__setattr__(self, "_df", _checked(self._df)) + + @classmethod + def from_long_df(cls, df: pd.DataFrame) -> LabeledData: + """Wrap a long table holding the contract. + + Args: + df: One row per frame and keypoint, in either schema; any column and row order. + + Raises: + ValueError: Naming the first broken rule: columns, dtypes, density, or identities. + """ + + return cls(df) + + @property + def is_multi_animal(self) -> bool: + return identity_columns(self._df) == MULTI_ANIMAL_KEYPOINT_COLUMNS + + @property + def has_likelihood(self) -> bool: + return LIKELIHOOD_COORD in self._df.columns + + 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(keypoints: Sequence[Keypoint], *, multi_animal: bool) -> dict[str, list[str | None]]: + """The identity columns of ``keypoints``, one value per keypoint: the only place attributes become columns.""" + + values = { + "scorer": [k.scorer for k in keypoints], + "individual": [k.individual for k in keypoints], + "bodypart": [k.bodypart for k in keypoints], + } + columns = MULTI_ANIMAL_KEYPOINT_COLUMNS if multi_animal else SINGLE_ANIMAL_KEYPOINT_COLUMNS + return {name: values[name] for name in columns} + + +def keypoints_of(identities: pd.DataFrame) -> tuple[Keypoint, ...]: + """One ``Keypoint`` 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( + Keypoint(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 = POSITION_COORDS + ((LIKELIHOOD_COORD,) if LIKELIHOOD_COORD in df.columns else ()) + 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.") + if df.empty: + raise ValueError("The table has no frames; the model holds keypoints only through frames.") + + 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 _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/dlccore/io/labeled_data/wide/from_long.py b/dlccore/io/labeled_data/wide/from_long.py new file mode 100644 index 0000000..18e799f --- /dev/null +++ b/dlccore/io/labeled_data/wide/from_long.py @@ -0,0 +1,53 @@ +# +# 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.long.model import FRAME_COLUMNS, LabeledData, identity_columns +from dlccore.io.labeled_data.model import LIKELIHOOD_COORD, POSITION_COORDS +from dlccore.io.labeled_data.wide.header import MULTI_ANIMAL_LEVELS, SINGLE_ANIMAL_LEVELS + + +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() + keypoint_columns = identity_columns(long) + coords = (*POSITION_COORDS, LIKELIHOOD_COORD) if labels.has_likelihood else POSITION_COORDS + n_frames, n_keypoints = long["frame_index"].nunique(), long["keypoint_index"].nunique() + + # Rows are frame-major, so the first frame's rows name the keypoints and every K-th row starts a frame. + keypoints = long.iloc[:n_keypoints] + frames = long.iloc[::n_keypoints] if n_keypoints else long.iloc[:0] + + columns = pd.MultiIndex.from_arrays( + [ + *(keypoints[name].astype(str).repeat(len(coords)).to_numpy() for name in keypoint_columns), + list(coords) * n_keypoints, + ], + names=MULTI_ANIMAL_LEVELS if labels.is_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/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..a9a8008 --- /dev/null +++ b/tests/io/labeled_data/long/test_long_model.py @@ -0,0 +1,201 @@ +# +# 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 + +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.is_multi_animal is multi + assert labels.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, "no frames"), + (_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_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]