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..5807d58 --- /dev/null +++ b/dlccore/io/labeled_data/checks/file.py @@ -0,0 +1,191 @@ +# +# 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 + +from typing import TYPE_CHECKING + +import pandas as pd + +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, + split_frame_path, +) + +if TYPE_CHECKING: + from dlccore.io.labeled_data.wide.h5 import H5KeySelection + +_COORDINATES = frozenset({*POSITION_COORDS, LIKELIHOOD_COORD}) + + +def unread_h5_keys(selection: H5KeySelection | None) -> tuple[str, ...]: + """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 dlccore.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: + """Return the file's only key if it is a legacy key, such as napari-deeplabcut's ``keypoints``. + + 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: + """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. + + 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) + + +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: + """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_without_the_likelihood_others_store(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.""" + + return tuple(label for label, column in df.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: + """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) + ) + + +def frame_absorbed_into_index_names(row_index: LabeledDataRowIndex) -> tuple[str, ...]: + """Return the frame path held in the row index's level names, if any. + + 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)] + 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(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. + + Returns: + The first row's entry if all its values are NaN; otherwise empty. + """ + + 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 new file mode 100644 index 0000000..f790cff --- /dev/null +++ b/dlccore/io/labeled_data/checks/model.py @@ -0,0 +1,72 @@ +# +# 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 dlccore.io.labeled_data.model import BodypartScope, Keypoint +from dlccore.io.suffixes import HUMAN_LABELS_PREFIX + +if TYPE_CHECKING: + from dlccore.io.labeled_data.long.model import LabeledData + + +def likelihood_in_human_labels(labels: LabeledData, path: PurePath) -> bool: + """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, ...]: + """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. + + 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] + 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, ...]: + """Return any keypoint with individual ``""``, in keypoint order. + + 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 04d6d8b..77c7ad4 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: + """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 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..6644d79 --- /dev/null +++ b/dlccore/io/labeled_data/wide/to_long.py @@ -0,0 +1,158 @@ +# +# 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_with_unrecognised_coords, + keypoints_without_the_likelihood_others_store, + non_numeric_columns, + row_index_is_unrecognised, +) +from dlccore.io.labeled_data.long.model import ( + FRAME_COLUMNS, + LabeledData, + identity_values, +) +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( + 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; + - 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) + + 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.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 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)) + + +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 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(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, 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..e5ec2f2 --- /dev/null +++ b/tests/io/labeled_data/long/test_long_boundaries.py @@ -0,0 +1,59 @@ +# +# 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", + "has_likelihood", + "is_multi_animal", + "to_arrays", + "to_long_df", + "to_wide_df", + }