Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions dlccore/io/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
#
# DeepLabCut Toolbox (deeplabcut.org)
# © A. & M.W. Mathis Labs
# https://github.com/DeepLabCut/dlccore
#
# Contributors:
# https://github.com/DeepLabCut/dlccore/graphs/contributors
#
# Licensed under GNU Lesser General Public License v3.0
#

"""Per-file I/O for DeepLabCut project files.

Paths in, typed results out.

Should not import from ``dlccore``.
Each file kind's reader is imported from a dedicated module,
to avoid loading dependencies eagerly.
"""
32 changes: 32 additions & 0 deletions dlccore/io/labeled_data/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
#
# DeepLabCut Toolbox (deeplabcut.org)
# © A. & M.W. Mathis Labs
# https://github.com/DeepLabCut/dlccore
#
# Contributors:
# https://github.com/DeepLabCut/dlccore/graphs/contributors
#
# Licensed under GNU Lesser General Public License v3.0
#

"""Labeled-data files. The public API is ``__all__``.

``__all__`` holds the identity types. ``model`` holds concepts common to all formats.
``_wide``, DeepLabCut's stored table, is internal to dlccore.
"""

from dlccore.io.labeled_data.model import (
BodypartScope,
FramePath,
KeypointDataFields,
KeypointIdentifier,
KeypointIdentifiers,
)

__all__ = [
"BodypartScope",
"FramePath",
"KeypointDataFields",
"KeypointIdentifier",
"KeypointIdentifiers",
]
15 changes: 15 additions & 0 deletions dlccore/io/labeled_data/_wide/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
#
# DeepLabCut Toolbox (deeplabcut.org)
# © A. & M.W. Mathis Labs
# https://github.com/DeepLabCut/dlccore
#
# Contributors:
# https://github.com/DeepLabCut/dlccore/graphs/contributors
#
# Licensed under GNU Lesser General Public License v3.0
#

"""DeepLabCut's wide labeled-data table: its header, its row index, and the containers that store it.

Imports nothing eagerly: ``h5`` loads pandas and PyTables, so import it explicitly.
"""
127 changes: 127 additions & 0 deletions dlccore/io/labeled_data/_wide/header.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
#
# DeepLabCut Toolbox (deeplabcut.org)
# © A. & M.W. Mathis Labs
# https://github.com/DeepLabCut/dlccore
#
# Contributors:
# https://github.com/DeepLabCut/dlccore/graphs/contributors
#
# Licensed under GNU Lesser General Public License v3.0
#

"""DeepLabCut's wide labeled-data column header, grouped into keypoints without dropping any column."""

from __future__ import annotations

from collections.abc import Iterable
from dataclasses import dataclass
from enum import Enum

from dlccore.io.labeled_data.model import KeypointIdentifier

SINGLE_ANIMAL_LEVELS = ("scorer", "bodyparts", "coords")
MULTI_ANIMAL_LEVELS = ("scorer", "individuals", "bodyparts", "coords")


class LabeledDataHeaderShape(str, Enum):
"""Column layouts used by a header, if recognised."""

SINGLE_ANIMAL = "single_animal"
MULTI_ANIMAL = "multi_animal"
UNRECOGNISED = "unrecognised"


_HEADER_SHAPES: dict[tuple[str | None, ...], LabeledDataHeaderShape] = {
SINGLE_ANIMAL_LEVELS: LabeledDataHeaderShape.SINGLE_ANIMAL,
MULTI_ANIMAL_LEVELS: LabeledDataHeaderShape.MULTI_ANIMAL,
}


@dataclass(frozen=True)
class KeypointColumns:
"""The columns of one keypoint in a wide header.

Attributes:
identifier: The keypoint's identifier. The individual is ``None`` in a single-animal header, and the scope is
``UNIQUE`` only when the individual is ``"single"``.
coords: The coordinate name of each column (e.g. ``"x"``), in column order, duplicates kept.
positions: Each column's index in the header, aligned with ``coords``.
"""

identifier: KeypointIdentifier
coords: tuple[str, ...]
positions: tuple[int, ...]


@dataclass(frozen=True)
class LabeledDataHeader:
"""A wide labeled-data column header, classified.

Attributes:
level_names: The header's level names, as stored.
shape: The DeepLabCut layout these level names match, or ``UNRECOGNISED``.
keypoints: The keypoints, in order of first appearance; empty when ``shape`` is ``UNRECOGNISED``.
unrecognised_columns: The raw column tuples, kept only when ``shape`` is ``UNRECOGNISED`` so that nothing is
lost.
"""

level_names: tuple[str | None, ...]
shape: LabeledDataHeaderShape
keypoints: tuple[KeypointColumns, ...] = ()
unrecognised_columns: tuple[tuple[str, ...], ...] = ()


HEADER_DEPTHS: tuple[int, ...] = tuple(sorted({len(level_names) for level_names in _HEADER_SHAPES}, reverse=True))


def header_shape(level_names: Iterable[str | None]) -> LabeledDataHeaderShape:
"""Return the DeepLabCut layout these level names match, or ``UNRECOGNISED``."""

return _HEADER_SHAPES.get(tuple(level_names), LabeledDataHeaderShape.UNRECOGNISED)


def classify_labeled_data_header(
level_names: Iterable[str | None],
columns: Iterable[tuple[str, ...]],
) -> LabeledDataHeader:
"""Group a wide header's columns into keypoints.

Each column is read on its own and grouped by (scorer, individual, bodypart). The header is never expanded
from its per-level values (a MultiIndex's ``levels``), which would add keypoints that have no column.

Reordered headers give the same keypoints at other positions,
any missing pair is omitted rather than padded, and duplicated columns are kept.

Args:
level_names: The header's level names, outermost first.
columns: One tuple per column, aligned with ``level_names``.
"""

level_names = tuple(level_names)
columns = tuple(tuple(column) for column in columns)
shape = header_shape(level_names)

if shape is LabeledDataHeaderShape.UNRECOGNISED:
return LabeledDataHeader(level_names=level_names, shape=shape, unrecognised_columns=columns)

groups: dict[tuple[str, str | None, str], list[tuple[str, int]]] = {}

for position, column in enumerate(columns):
if shape is LabeledDataHeaderShape.SINGLE_ANIMAL:
scorer, bodypart, coord = column
individual = None
else:
scorer, individual, bodypart, coord = column

groups.setdefault((scorer, individual, bodypart), []).append((coord, position))

keypoints = tuple(
KeypointColumns(
identifier=KeypointIdentifier(scorer=scorer, individual=individual, bodypart=bodypart),
coords=tuple(coord for coord, _position in members),
positions=tuple(position for _coord, position in members),
)
for (scorer, individual, bodypart), members in groups.items()
)

return LabeledDataHeader(level_names=level_names, shape=shape, keypoints=keypoints)
121 changes: 121 additions & 0 deletions dlccore/io/labeled_data/_wide/row_index.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
#
# DeepLabCut Toolbox (deeplabcut.org)
# © A. & M.W. Mathis Labs
# https://github.com/DeepLabCut/dlccore
#
# Contributors:
# https://github.com/DeepLabCut/dlccore/graphs/contributors
#
# Licensed under GNU Lesser General Public License v3.0
#

"""DeepLabCut's labeled-data row index: each row's frame path, split into path components as stored."""

from __future__ import annotations

from collections.abc import Iterable
from dataclasses import dataclass
from enum import Enum
from numbers import Integral


class RowIndexShape(str, Enum):
"""How a row index stores its frame paths.

``PATH_PARTS``: a MultiIndex, one level per path component. ``FLAT_PATHS``: one path string per row.
``EMPTY``: no rows, whatever the index type. ``UNRECOGNISED``: anything else.
"""

PATH_PARTS = "path_parts"
FLAT_PATHS = "flat_paths"
EMPTY = "empty"
UNRECOGNISED = "unrecognised"


@dataclass(frozen=True)
class LabeledDataRowIndex:
"""A labeled-data row index, classified.

Attributes:
shape: How the frame paths are stored.
names: The level names as stored; ``None`` for each unnamed level.
entries: The entries as stored.
frames: Each entry's path components as stored. Entries of different depths keep their own length.
Empty when ``shape`` is ``EMPTY`` or ``UNRECOGNISED``.
"""

shape: RowIndexShape
names: tuple[object, ...]
entries: tuple[object, ...]
frames: tuple[tuple[object, ...], ...] = ()


# Frame identity rather than wide storage: moves to ``model`` once a second format needs it.
def split_frame_path(entry: str) -> tuple[str, ...]:
"""Split a labeled-data row-index entry into its path components.

Does not validate: empty and repeated separators give empty components instead of being dropped.

Args:
entry: A row-index entry, e.g. ``labeled-data/vid1/img1.png``. Forward slashes and backslashes both separate.
"""

return tuple(entry.replace("\\", "/").split("/"))


def frame_part_as_text(part: object) -> str | None:
"""Return a row-index part as the folder or file name it stands for.

A string is returned unchanged. An integer is converted with ``str()``: when a video folder's name is a
number (e.g. ``labeled-data/123/``), pandas may read that level back as an integer, and DeepLabCut's
``guarantee_multiindex_rows`` converts it to a string the same way.

Returns:
The name, or ``None`` for any other type. A float or bool cannot be turned back into the original
name (``1.0`` vs ``"1"``), so no guessing is involved.
"""

if isinstance(part, str):
return part
if isinstance(part, Integral) and not isinstance(part, bool):
return str(part)
return None


def classify_labeled_data_row_index(
names: Iterable[object],
entries: Iterable[object],
*,
is_multi_index: bool,
) -> LabeledDataRowIndex:
"""Classify a row index by how it stores frame paths. Path strings are split but not normalised.

Args:
names: The row index's level names.
entries: The row-index entries, in order; tuples for a MultiIndex.
is_multi_index: Whether the entries came from a MultiIndex.
"""

names = tuple(names)
entries = tuple(entries)

if not entries:
return LabeledDataRowIndex(shape=RowIndexShape.EMPTY, names=names, entries=entries)

if is_multi_index:
return LabeledDataRowIndex(
shape=RowIndexShape.PATH_PARTS,
names=names,
entries=entries,
frames=tuple(tuple(entry) for entry in entries),
)

if all(isinstance(entry, str) for entry in entries):
return LabeledDataRowIndex(
shape=RowIndexShape.FLAT_PATHS,
names=names,
entries=entries,
frames=tuple(split_frame_path(entry) for entry in entries),
)

return LabeledDataRowIndex(shape=RowIndexShape.UNRECOGNISED, names=names, entries=entries)
Loading
Loading