From e7f5453aea40afb1e927f209fb1f1b3144495111 Mon Sep 17 00:00:00 2001 From: C-Achard Date: Tue, 24 Nov 2026 14:32:05 +0100 Subject: [PATCH 1/2] Copy labeled-data checks and wide-to-long conversion --- dlccore/io/labeled_data/checks/__init__.py | 8 + dlccore/io/labeled_data/checks/file.py | 144 ++++++++++++++++++ dlccore/io/labeled_data/checks/model.py | 50 ++++++ dlccore/io/labeled_data/long/model.py | 15 ++ dlccore/io/labeled_data/wide/to_long.py | 138 +++++++++++++++++ .../labeled_data/long/test_long_boundaries.py | 47 ++++++ 6 files changed, 402 insertions(+) create mode 100644 dlccore/io/labeled_data/checks/__init__.py create mode 100644 dlccore/io/labeled_data/checks/file.py create mode 100644 dlccore/io/labeled_data/checks/model.py create mode 100644 dlccore/io/labeled_data/wide/to_long.py create mode 100644 tests/io/labeled_data/long/test_long_boundaries.py diff --git a/dlccore/io/labeled_data/checks/__init__.py b/dlccore/io/labeled_data/checks/__init__.py new file mode 100644 index 0000000..a1a9cef --- /dev/null +++ b/dlccore/io/labeled_data/checks/__init__.py @@ -0,0 +1,8 @@ +"""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..a6122ee --- /dev/null +++ b/dlccore/io/labeled_data/checks/file.py @@ -0,0 +1,144 @@ +"""Facts about a labeled-data file as stored: its keys, header, row index, values, and what its CSV copy keeps. + +Each check takes one of ``LabeledDataFile``'s facts, or the table ``to_raw_wide_df()`` returns. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +import pandas as pd + +from dlc_octopus.io.labeled_data.long.model import FRAME_COLUMNS +from dlc_octopus.io.labeled_data.model import LIKELIHOOD_COORD, POSITION_COORDS +from dlc_octopus.io.labeled_data.wide.header import KeypointColumns, LabeledDataHeader, LabeledDataHeaderShape +from dlc_octopus.io.labeled_data.wide.row_index import ( + LabeledDataRowIndex, + RowIndexShape, + frame_part_as_text, + split_frame_path, +) + +if TYPE_CHECKING: + from dlc_octopus.io.labeled_data.wide.h5 import H5KeySelection + +_COORDINATES = frozenset({*POSITION_COORDS, LIKELIHOOD_COORD}) + + +def unread_h5_keys(selection: H5KeySelection | None) -> tuple[str, ...]: + """The keys found but not read, in the file's order: non-empty exactly when the outcome is ``MULTI_KEY``.""" + + from dlc_octopus.io.labeled_data.wide.h5 import H5KeySelectionOutcome + + if selection is None or selection.outcome is not H5KeySelectionOutcome.MULTI_KEY: + return () + return tuple(key for key in selection.keys_found if key != selection.selected_key) + + +def legacy_h5_key(selection: H5KeySelection | None) -> str | None: + """The file's one key, when it is a key older DeepLabCut releases wrote; ``None`` otherwise.""" + + from dlc_octopus.io.labeled_data.wide.h5 import H5KeySelectionOutcome + + return _single_key(selection, H5KeySelectionOutcome.SINGLE_LEGACY) + + +def unknown_h5_key(selection: H5KeySelection | None) -> str | None: + """The file's one key, when no DeepLabCut release is known to write it; ``None`` otherwise.""" + + from dlc_octopus.io.labeled_data.wide.h5 import H5KeySelectionOutcome + + return _single_key(selection, H5KeySelectionOutcome.SINGLE_UNKNOWN) + + +def _single_key(selection: H5KeySelection | None, outcome: object) -> str | None: + return selection.selected_key if selection is not None and selection.outcome is outcome else None + + +def header_is_unrecognised(header: LabeledDataHeader) -> bool: + """Whether the header's level names are neither of the two DeepLabCut writes.""" + + return header.shape is LabeledDataHeaderShape.UNRECOGNISED + + +def keypoints_with_unrecognised_coords(header: LabeledDataHeader) -> tuple[KeypointColumns, ...]: + """The keypoints whose coordinates are not exactly x, y and optionally likelihood, each once.""" + + 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_without_the_likelihood_others_store(header: LabeledDataHeader) -> tuple[KeypointColumns, ...]: + """The keypoints storing no likelihood where another keypoint stores one; empty when all or none do.""" + + 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(table: pd.DataFrame) -> tuple[object, ...]: + """The column labels of a wide table whose values are not real numbers: text, bool or complex.""" + + return tuple(label for label, column in table.items() if not _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: + """Whether the table has no rows.""" + + return row_index.shape is RowIndexShape.EMPTY + + +def row_index_is_unrecognised(row_index: LabeledDataRowIndex) -> bool: + """Whether the row index is neither path parts nor path strings.""" + + return row_index.shape is RowIndexShape.UNRECOGNISED + + +def frames_of_other_depth(row_index: LabeledDataRowIndex) -> tuple[int, ...]: + """The rows whose frame has other than the three parts the model holds.""" + + 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, ...]: + """The rows whose frame has a part that names nothing as ``frame_part_as_text`` reads it: not text or an integer.""" + + return tuple( + row for row, frame in enumerate(row_index.frames) if any(frame_part_as_text(part) is None for part in frame) + ) + + +def frame_absorbed_into_index_names(row_index: LabeledDataRowIndex) -> tuple[str, ...]: + """The frame the row index's level names spell, as pandas reads a CSV's first frame when it has no values. + + DeepLabCut writes no index names, so names that spell a frame of the model's three parts are one; empty + otherwise. Split as a path when there is one name, as a flat CSV index stores it. + """ + + names = [name for name in row_index.names if isinstance(name, str)] + if not names or len(names) != len(row_index.names): + return () + parts = split_frame_path(names[0]) if len(names) == 1 else tuple(names) + return parts if len(parts) == len(FRAME_COLUMNS) else () + + +def frames_lost_to_csv(frame: pd.DataFrame) -> tuple[object, ...]: + """The row-index entries of a wide ``frame`` that its CSV reads back without. + + pandas, and DeepLabCut's ``convertcsv2h5`` with it, read a first row without values as the row index's names. + """ + + if len(frame) and frame.iloc[0].isna().all(): + return (frame.index[0],) + return () diff --git a/dlccore/io/labeled_data/checks/model.py b/dlccore/io/labeled_data/checks/model.py new file mode 100644 index 0000000..5dba174 --- /dev/null +++ b/dlccore/io/labeled_data/checks/model.py @@ -0,0 +1,50 @@ +"""Facts about the labels a file holds, read through the model's public surface.""" + +from __future__ import annotations + +from pathlib import PurePath +from typing import TYPE_CHECKING + +from dlc_octopus.io.labeled_data.model import BodypartScope, Keypoint +from dlc_octopus.io.suffixes import HUMAN_LABELS_PREFIX + +if TYPE_CHECKING: + from dlc_octopus.io.labeled_data.long.model import LabeledData + + +def likelihood_in_human_labels(labels: LabeledData, path: PurePath) -> bool: + """Whether labels read from, or bound for, a human-labels (``CollectedData_*``) file store a likelihood.""" + + return labels.has_likelihood and path.name.startswith(HUMAN_LABELS_PREFIX) + + +def missing_keypoints(labels: LabeledData) -> tuple[Keypoint, ...]: + """The (individual, bodypart) pairs absent where another individual of the same scorer has the bodypart. + + Unique bodyparts, under ``"single"``, are their own set and never compared with an individual's. In order of + scorer, individual, then bodypart, each by first appearance. + """ + + keypoints = [k for k in labels.to_arrays().keypoints if k.scope is BodypartScope.INDIVIDUAL] + present = {(k.scorer, k.individual, k.bodypart) for k in keypoints} + missing = [] + for scorer in dict.fromkeys(k.scorer for k in keypoints): + individuals = dict.fromkeys(k.individual for k in keypoints if k.scorer == scorer) + bodyparts = dict.fromkeys(k.bodypart for k in keypoints if k.scorer == scorer) + missing += [ + Keypoint(scorer, individual, bodypart) + for individual in individuals + for bodypart in bodyparts + if (scorer, individual, bodypart) not in present + ] + return tuple(missing) + + +def keypoints_with_empty_individual(labels: LabeledData) -> tuple[Keypoint, ...]: + """The keypoints whose individual is named ``""``, in keypoint order. + + DeepLabCut's header either names an individual or has no individuals level; napari-deeplabcut spells "none" as + ``""`` in memory only. + """ + + return tuple(k for k in labels.to_arrays().keypoints if k.individual == "") diff --git a/dlccore/io/labeled_data/long/model.py b/dlccore/io/labeled_data/long/model.py index 04d6d8b..bc8150a 100644 --- a/dlccore/io/labeled_data/long/model.py +++ b/dlccore/io/labeled_data/long/model.py @@ -71,6 +71,21 @@ def from_long_df(cls, df: pd.DataFrame) -> LabeledData: return cls(df) + @classmethod + def from_wide_df(cls, df: pd.DataFrame) -> LabeledData: + """Interpret a wide table as a read does: columns by classified position, frame parts as text. + + Args: + df: A table in any wide form DeepLabCut reads, such as one from ``LabeledDataFile.to_raw_wide_df()``. + + Raises: + ValueError: Naming why the table has no model, as ``LabeledDataFile.labeled_data`` does. + """ + + from dlc_octopus.io.labeled_data.wide.to_long import wide_frame_to_long + + return wide_frame_to_long(df) + @property def is_multi_animal(self) -> bool: return identity_columns(self._df) == MULTI_ANIMAL_KEYPOINT_COLUMNS 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..e089bf5 --- /dev/null +++ b/dlccore/io/labeled_data/wide/to_long.py @@ -0,0 +1,138 @@ +"""A classified wide table as ``LabeledData``: columns taken by classified position, never by level values.""" + +from __future__ import annotations + +from typing import cast + +import numpy as np +import pandas as pd + +from dlc_octopus.io.labeled_data.checks.file import ( + frames_of_other_depth, + frames_with_unnamed_parts, + has_no_frames, + header_is_unrecognised, + keypoints_with_unrecognised_coords, + keypoints_without_the_likelihood_others_store, + non_numeric_columns, + row_index_is_unrecognised, +) +from dlc_octopus.io.labeled_data.long.model import ( + FRAME_COLUMNS, + LabeledData, + identity_values, +) +from dlc_octopus.io.labeled_data.model import LIKELIHOOD_COORD, POSITION_COORDS +from dlc_octopus.io.labeled_data.wide.header import LabeledDataHeader, LabeledDataHeaderShape +from dlc_octopus.io.labeled_data.wide.row_index import LabeledDataRowIndex, frame_part_as_text +from dlc_octopus.io.labeled_data.wide.table import classify_wide_frame + + +def wide_to_long( + dataframe: pd.DataFrame, + header: LabeledDataHeader, + row_index: LabeledDataRowIndex, +) -> LabeledData: + """Convert a classified wide table to the long model, one row per frame and keypoint, values as stored. + + An integer frame part, such as a dataset folder named by a number, becomes text, as DeepLabCut's + ``guarantee_multiindex_rows`` makes it; the raw row index keeps the integer. + + Args: + dataframe: The table as read. + header: Its classified header. + row_index: Its classified row index. + + Raises: + ValueError: Reports an unrecognised header or row index, no frames, a frame that is not three parts + or with a part that is neither text nor an integer, coordinates other than ``x``, ``y`` + and optionally ``likelihood``, a likelihood on some keypoints only, or a non-numeric value column. + """ + + 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(dataframe, header) + + n_frames, n_keypoints = len(frames), len(positions) + keypoints = [columns.keypoint 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 dataframe.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)) + + +def wide_frame_to_long(frame: pd.DataFrame) -> LabeledData: + """Classify a wide table built in memory, then convert it as ``wide_to_long`` does. + + Raises: + ValueError: As ``wide_to_long``. + """ + + header, row_index = classify_wide_frame(frame) + return wide_to_long(frame, header, row_index) + + +def _value_positions(dataframe: pd.DataFrame, header: LabeledDataHeader) -> list[dict[str, int]]: + """Return each keypoint's column position per coordinate, in header order, or raise naming the first check found.""" + + if unrecognised := keypoints_with_unrecognised_coords(header): + columns = unrecognised[0] + raise ValueError( + f"{columns.keypoint} has coordinates {list(columns.coords)}; x, y and optionally likelihood are " + "needed, each once." + ) + if lacking := keypoints_without_the_likelihood_others_store(header): + stores = next(columns.keypoint 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].keypoint} does not." + ) + if not_numeric := non_numeric_columns(dataframe): + 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, or raise naming why the row index has no model.""" + + if has_no_frames(row_index): + raise ValueError("The table has no frames; the model holds keypoints only through frames.") + 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/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..5796095 --- /dev/null +++ b/tests/io/labeled_data/long/test_long_boundaries.py @@ -0,0 +1,47 @@ +"""``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 dlc_octopus +from dlc_octopus.io.labeled_data.long.model import LabeledData + +PACKAGE_ROOT = Path(dlc_octopus.__file__).parent +LONG = PACKAGE_ROOT / "io" / "labeled_data" / "long" +PRIVATE_FRAME = "_frame" + + +def _modules_touching_the_frame() -> 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_FRAME + } + + +def test_the_scan_sees_the_frame_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_frame() + + +def test_the_private_frame_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_frame() 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: operations belong in ops unless they need the frame. + public = {name for name in dir(LabeledData) if not name.startswith("_")} + + assert public == { + "from_long_df", + "from_wide_df", + "has_likelihood", + "is_multi_animal", + "to_arrays", + "to_long_df", + "to_wide_df", + } From f4181ad3d6acd793130eb33970231d03940f5226 Mon Sep 17 00:00:00 2001 From: C-Achard Date: Tue, 24 Nov 2026 14:44:11 +0100 Subject: [PATCH 2/2] Adapt labeled-data checks and wide-to-long conversion to dlccore - Rename the package to dlccore.io and add the dlccore license header - Rename wide_frame_to_long to wide_df_to_long and DataFrame parameters to `df`, matching classify_wide_df - Rewrite the checks and conversion docstrings to state inputs, outputs and the reason for each check - Point the private-table boundary test at dlccore and at LabeledData._df --- dlccore/io/labeled_data/checks/__init__.py | 11 ++ dlccore/io/labeled_data/checks/file.py | 111 +++++++++++++----- dlccore/io/labeled_data/checks/model.py | 44 +++++-- dlccore/io/labeled_data/long/model.py | 10 +- dlccore/io/labeled_data/wide/to_long.py | 70 +++++++---- .../labeled_data/long/test_long_boundaries.py | 34 ++++-- 6 files changed, 196 insertions(+), 84 deletions(-) diff --git a/dlccore/io/labeled_data/checks/__init__.py b/dlccore/io/labeled_data/checks/__init__.py index a1a9cef..9a3ea09 100644 --- a/dlccore/io/labeled_data/checks/__init__.py +++ b/dlccore/io/labeled_data/checks/__init__.py @@ -1,3 +1,14 @@ +# +# DeepLabCut Toolbox (deeplabcut.org) +# © A. & M.W. Mathis Labs +# https://github.com/DeepLabCut/dlccore +# +# Contributors: +# https://github.com/DeepLabCut/dlccore/graphs/contributors +# +# Licensed under GNU Lesser General Public License v3.0 +# + """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. diff --git a/dlccore/io/labeled_data/checks/file.py b/dlccore/io/labeled_data/checks/file.py index a6122ee..5807d58 100644 --- a/dlccore/io/labeled_data/checks/file.py +++ b/dlccore/io/labeled_data/checks/file.py @@ -1,6 +1,18 @@ -"""Facts about a labeled-data file as stored: its keys, header, row index, values, and what its CSV copy keeps. - -Each check takes one of ``LabeledDataFile``'s facts, or the table ``to_raw_wide_df()`` returns. +# +# 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 part of a read (the H5 key selection, the classified header or row index, or the wide +DataFrame) and returns empty, ``None`` or ``False`` when there is nothing to report. """ from __future__ import annotations @@ -9,10 +21,10 @@ import pandas as pd -from dlc_octopus.io.labeled_data.long.model import FRAME_COLUMNS -from dlc_octopus.io.labeled_data.model import LIKELIHOOD_COORD, POSITION_COORDS -from dlc_octopus.io.labeled_data.wide.header import KeypointColumns, LabeledDataHeader, LabeledDataHeaderShape -from dlc_octopus.io.labeled_data.wide.row_index import ( +from dlccore.io.labeled_data.long.model import FRAME_COLUMNS +from dlccore.io.labeled_data.model import LIKELIHOOD_COORD, POSITION_COORDS +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, @@ -20,15 +32,22 @@ ) if TYPE_CHECKING: - from dlc_octopus.io.labeled_data.wide.h5 import H5KeySelection + from dlccore.io.labeled_data.wide.h5 import H5KeySelection _COORDINATES = frozenset({*POSITION_COORDS, LIKELIHOOD_COORD}) def unread_h5_keys(selection: H5KeySelection | None) -> tuple[str, ...]: - """The keys found but not read, in the file's order: non-empty exactly when the outcome is ``MULTI_KEY``.""" + """Return the keys of a multi-key H5 file that could not be read. + + Args: + selection: The key selection of an H5 read; ``None`` for a file that is not H5. + + Returns: + The unread keys, in the file's order. Empty unless the file holds several keys. + """ - from dlc_octopus.io.labeled_data.wide.h5 import H5KeySelectionOutcome + from dlccore.io.labeled_data.wide.h5 import H5KeySelectionOutcome if selection is None or selection.outcome is not H5KeySelectionOutcome.MULTI_KEY: return () @@ -36,17 +55,31 @@ def unread_h5_keys(selection: H5KeySelection | None) -> tuple[str, ...]: def legacy_h5_key(selection: H5KeySelection | None) -> str | None: - """The file's one key, when it is a key older DeepLabCut releases wrote; ``None`` otherwise.""" + """Return the file's only key if it is a legacy key, such as napari-deeplabcut's ``keypoints``. - from dlc_octopus.io.labeled_data.wide.h5 import H5KeySelectionOutcome + Args: + selection: The key selection of an H5 read; ``None`` for a file that is not H5. + + Returns: + The key, or ``None`` if the file is not H5, holds another key, or holds several keys. + """ + + from dlccore.io.labeled_data.wide.h5 import H5KeySelectionOutcome return _single_key(selection, H5KeySelectionOutcome.SINGLE_LEGACY) def unknown_h5_key(selection: H5KeySelection | None) -> str | None: - """The file's one key, when no DeepLabCut release is known to write it; ``None`` otherwise.""" + """Return the file's only key if no known writer uses it (it is not in ``H5_KEY_REGISTRY``). + + Args: + selection: The key selection of an H5 read; ``None`` for a file that is not H5. - from dlc_octopus.io.labeled_data.wide.h5 import H5KeySelectionOutcome + Returns: + The key, or ``None`` if the file is not H5, holds a known key, or holds several keys. + """ + + from dlccore.io.labeled_data.wide.h5 import H5KeySelectionOutcome return _single_key(selection, H5KeySelectionOutcome.SINGLE_UNKNOWN) @@ -56,13 +89,16 @@ def _single_key(selection: H5KeySelection | None, outcome: object) -> str | None def header_is_unrecognised(header: LabeledDataHeader) -> bool: - """Whether the header's level names are neither of the two DeepLabCut writes.""" + """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, ...]: - """The keypoints whose coordinates are not exactly x, y and optionally likelihood, each once.""" + """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 @@ -73,16 +109,19 @@ def keypoints_with_unrecognised_coords(header: LabeledDataHeader) -> tuple[Keypo def keypoints_without_the_likelihood_others_store(header: LabeledDataHeader) -> tuple[KeypointColumns, ...]: - """The keypoints storing no likelihood where another keypoint stores one; empty when all or none do.""" + """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(table: pd.DataFrame) -> tuple[object, ...]: - """The column labels of a wide table whose values are not real numbers: text, bool or complex.""" +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.""" - return tuple(label for label, column in table.items() if not _is_real(column)) + return tuple(label for label, column in df.items() if not _is_real(column)) def _is_real(column: pd.Series) -> bool: @@ -94,25 +133,25 @@ def _is_real(column: pd.Series) -> bool: def has_no_frames(row_index: LabeledDataRowIndex) -> bool: - """Whether the table has no rows.""" + """Return whether the row index has no rows.""" return row_index.shape is RowIndexShape.EMPTY def row_index_is_unrecognised(row_index: LabeledDataRowIndex) -> bool: - """Whether the row index is neither path parts nor path strings.""" + """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, ...]: - """The rows whose frame has other than the three parts the model holds.""" + """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, ...]: - """The rows whose frame has a part that names nothing as ``frame_part_as_text`` reads it: not text or an integer.""" + """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) @@ -120,10 +159,14 @@ def frames_with_unnamed_parts(row_index: LabeledDataRowIndex) -> tuple[int, ...] def frame_absorbed_into_index_names(row_index: LabeledDataRowIndex) -> tuple[str, ...]: - """The frame the row index's level names spell, as pandas reads a CSV's first frame when it has no values. + """Return the frame path held in the row index's level names, if any. - DeepLabCut writes no index names, so names that spell a frame of the model's three parts are one; empty - otherwise. Split as a path when there is one name, as a flat CSV index stores it. + When a CSV's first frame has no values, pandas reads that row as the row index's names, so the frame's path ends + up there. DeepLabCut writes no index names, so names forming a three-part path are taken to be such a frame. + + Returns: + The path's three parts; empty if the names are not all text or do not form a three-part path. A single name + is split as a path, as a flat CSV index stores it. """ names = [name for name in row_index.names if isinstance(name, str)] @@ -133,12 +176,16 @@ def frame_absorbed_into_index_names(row_index: LabeledDataRowIndex) -> tuple[str return parts if len(parts) == len(FRAME_COLUMNS) else () -def frames_lost_to_csv(frame: pd.DataFrame) -> tuple[object, ...]: - """The row-index entries of a wide ``frame`` that its CSV reads back without. +def frames_lost_to_csv(df: pd.DataFrame) -> tuple[object, ...]: + """Return the row-index entry that writing a wide DataFrame to CSV would lose, if any. + + If the first row has no values, pandas reads it back from the CSV as the row index's names, as DeepLabCut's + ``convertcsv2h5`` does, and the row is gone. ``frame_absorbed_into_index_names`` finds it in a CSV already read. - pandas, and DeepLabCut's ``convertcsv2h5`` with it, read a first row without values as the row index's names. + Returns: + The first row's entry if all its values are NaN; otherwise empty. """ - if len(frame) and frame.iloc[0].isna().all(): - return (frame.index[0],) + if len(df) and df.iloc[0].isna().all(): + return (df.index[0],) return () diff --git a/dlccore/io/labeled_data/checks/model.py b/dlccore/io/labeled_data/checks/model.py index 5dba174..f790cff 100644 --- a/dlccore/io/labeled_data/checks/model.py +++ b/dlccore/io/labeled_data/checks/model.py @@ -1,28 +1,49 @@ -"""Facts about the labels a file holds, read through the model's public surface.""" +# +# 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 the labels a file holds, using only ``LabeledData``'s public methods.""" from __future__ import annotations from pathlib import PurePath from typing import TYPE_CHECKING -from dlc_octopus.io.labeled_data.model import BodypartScope, Keypoint -from dlc_octopus.io.suffixes import HUMAN_LABELS_PREFIX +from dlccore.io.labeled_data.model import BodypartScope, Keypoint +from dlccore.io.suffixes import HUMAN_LABELS_PREFIX if TYPE_CHECKING: - from dlc_octopus.io.labeled_data.long.model import LabeledData + from dlccore.io.labeled_data.long.model import LabeledData def likelihood_in_human_labels(labels: LabeledData, path: PurePath) -> bool: - """Whether labels read from, or bound for, a human-labels (``CollectedData_*``) file store a likelihood.""" + """Return whether labels store a likelihood although their file is a human-labels file. + + Only machine labels have a likelihood. Human labels are stored in ``CollectedData_*`` files. + + Args: + labels: The labels. + path: The file they were read from, or are about to be written to. + """ return labels.has_likelihood and path.name.startswith(HUMAN_LABELS_PREFIX) def missing_keypoints(labels: LabeledData) -> tuple[Keypoint, ...]: - """The (individual, bodypart) pairs absent where another individual of the same scorer has the bodypart. + """Return the bodyparts an individual lacks although another individual of the same scorer has them. + + Unique bodyparts (individual ``"single"``) are not compared with individuals' bodyparts. - Unique bodyparts, under ``"single"``, are their own set and never compared with an individual's. In order of - scorer, individual, then bodypart, each by first appearance. + Returns: + One keypoint per missing (individual, bodypart), ordered by scorer, then individual, then bodypart, each in + order of first appearance. """ keypoints = [k for k in labels.to_arrays().keypoints if k.scope is BodypartScope.INDIVIDUAL] @@ -41,10 +62,11 @@ def missing_keypoints(labels: LabeledData) -> tuple[Keypoint, ...]: def keypoints_with_empty_individual(labels: LabeledData) -> tuple[Keypoint, ...]: - """The keypoints whose individual is named ``""``, in keypoint order. + """Return any keypoint with individual ``""``, in keypoint order. - DeepLabCut's header either names an individual or has no individuals level; napari-deeplabcut spells "none" as - ``""`` in memory only. + DeepLabCut never writes this, the header either names the individual or has no individuals level. + napari-deeplabcut uses ``""`` for "no individual", but only in memory. + Any data that shows this should be considered malformed. """ return tuple(k for k in labels.to_arrays().keypoints if k.individual == "") diff --git a/dlccore/io/labeled_data/long/model.py b/dlccore/io/labeled_data/long/model.py index bc8150a..77c7ad4 100644 --- a/dlccore/io/labeled_data/long/model.py +++ b/dlccore/io/labeled_data/long/model.py @@ -73,18 +73,18 @@ def from_long_df(cls, df: pd.DataFrame) -> LabeledData: @classmethod def from_wide_df(cls, df: pd.DataFrame) -> LabeledData: - """Interpret a wide table as a read does: columns by classified position, frame parts as text. + """Build labels from a wide DataFrame, converting it as reading a file does. Args: - df: A table in any wide form DeepLabCut reads, such as one from ``LabeledDataFile.to_raw_wide_df()``. + df: A wide DataFrame in any layout DeepLabCut reads. Raises: - ValueError: Naming why the table has no model, as ``LabeledDataFile.labeled_data`` does. + ValueError: If ``df`` cannot be converted; see ``wide.to_long.wide_to_long`` for the cases. """ - from dlc_octopus.io.labeled_data.wide.to_long import wide_frame_to_long + from dlccore.io.labeled_data.wide.to_long import wide_df_to_long - return wide_frame_to_long(df) + return wide_df_to_long(df) @property def is_multi_animal(self) -> bool: diff --git a/dlccore/io/labeled_data/wide/to_long.py b/dlccore/io/labeled_data/wide/to_long.py index e089bf5..6644d79 100644 --- a/dlccore/io/labeled_data/wide/to_long.py +++ b/dlccore/io/labeled_data/wide/to_long.py @@ -1,4 +1,19 @@ -"""A classified wide table as ``LabeledData``: columns taken by classified position, never by level values.""" +# +# 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 @@ -7,7 +22,7 @@ import numpy as np import pandas as pd -from dlc_octopus.io.labeled_data.checks.file import ( +from dlccore.io.labeled_data.checks.file import ( frames_of_other_depth, frames_with_unnamed_parts, has_no_frames, @@ -17,36 +32,41 @@ non_numeric_columns, row_index_is_unrecognised, ) -from dlc_octopus.io.labeled_data.long.model import ( +from dlccore.io.labeled_data.long.model import ( FRAME_COLUMNS, LabeledData, identity_values, ) -from dlc_octopus.io.labeled_data.model import LIKELIHOOD_COORD, POSITION_COORDS -from dlc_octopus.io.labeled_data.wide.header import LabeledDataHeader, LabeledDataHeaderShape -from dlc_octopus.io.labeled_data.wide.row_index import LabeledDataRowIndex, frame_part_as_text -from dlc_octopus.io.labeled_data.wide.table import classify_wide_frame +from dlccore.io.labeled_data.model import LIKELIHOOD_COORD, POSITION_COORDS +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 def wide_to_long( - dataframe: pd.DataFrame, + df: pd.DataFrame, header: LabeledDataHeader, row_index: LabeledDataRowIndex, ) -> LabeledData: - """Convert a classified wide table to the long model, one row per frame and keypoint, values as stored. + """Convert a wide DataFrame, already classified, to ``LabeledData``: one row per frame and keypoint. - An integer frame part, such as a dataset folder named by a number, becomes text, as DeepLabCut's - ``guarantee_multiindex_rows`` makes it; the raw row index keeps the integer. + 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: - dataframe: The table as read. - header: Its classified header. - row_index: Its classified row index. + df: The wide DataFrame as read. + header: The classified header of ``df``. + row_index: The classified row index of ``df``. Raises: - ValueError: Reports an unrecognised header or row index, no frames, a frame that is not three parts - or with a part that is neither text nor an integer, coordinates other than ``x``, ``y`` - and optionally ``likelihood``, a likelihood on some keypoints only, or a non-numeric value column. + ValueError: On the first of these problems found: + + - Invalid header or row index; + - No rows; + - 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) @@ -54,7 +74,7 @@ def wide_to_long( if header_is_unrecognised(header): raise ValueError(f"Header levels {list(header.level_names)} are not a header DeepLabCut writes.") - positions = _value_positions(dataframe, header) + positions = _value_positions(df, header) n_frames, n_keypoints = len(frames), len(positions) keypoints = [columns.keypoint for columns in header.keypoints] @@ -62,7 +82,7 @@ def wide_to_long( def values(coordinate: str) -> np.ndarray: # Frame-major, matching the row order below. - return dataframe.iloc[:, [position[coordinate] for position in positions]].to_numpy(dtype=float).reshape(-1) + 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 |= { @@ -78,18 +98,18 @@ def values(coordinate: str) -> np.ndarray: return LabeledData.from_long_df(pd.DataFrame(long)) -def wide_frame_to_long(frame: pd.DataFrame) -> LabeledData: - """Classify a wide table built in memory, then convert it as ``wide_to_long`` does. +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_frame(frame) - return wide_to_long(frame, header, row_index) + header, row_index = classify_wide_df(df) + return wide_to_long(df, header, row_index) -def _value_positions(dataframe: pd.DataFrame, header: LabeledDataHeader) -> list[dict[str, int]]: +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 naming the first check found.""" if unrecognised := keypoints_with_unrecognised_coords(header): @@ -103,7 +123,7 @@ def _value_positions(dataframe: pd.DataFrame, header: LabeledDataHeader) -> list raise ValueError( f"Some keypoints store a likelihood and others do not: {stores} does, {lacking[0].keypoint} does not." ) - if not_numeric := non_numeric_columns(dataframe): + 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] diff --git a/tests/io/labeled_data/long/test_long_boundaries.py b/tests/io/labeled_data/long/test_long_boundaries.py index 5796095..e5ec2f2 100644 --- a/tests/io/labeled_data/long/test_long_boundaries.py +++ b/tests/io/labeled_data/long/test_long_boundaries.py @@ -1,39 +1,51 @@ +# +# 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 dlc_octopus -from dlc_octopus.io.labeled_data.long.model import LabeledData +import dlccore +from dlccore.io.labeled_data.long.model import LabeledData -PACKAGE_ROOT = Path(dlc_octopus.__file__).parent +PACKAGE_ROOT = Path(dlccore.__file__).parent LONG = PACKAGE_ROOT / "io" / "labeled_data" / "long" -PRIVATE_FRAME = "_frame" +PRIVATE_TABLE = "_df" -def _modules_touching_the_frame() -> set[Path]: +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_FRAME + if isinstance(node, ast.Attribute) and node.attr == PRIVATE_TABLE } -def test_the_scan_sees_the_frame_in_long() -> None: +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_frame() + assert (LONG / "model.py").relative_to(PACKAGE_ROOT) in _modules_touching_the_table() -def test_the_private_frame_is_touched_only_in_long() -> None: +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_frame() if LONG.relative_to(PACKAGE_ROOT) not in path.parents} + 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: operations belong in ops unless they need the frame. + # 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 == {