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
15 changes: 15 additions & 0 deletions dlccore/io/labeled_data/__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
#

"""Labeled-data files: ``model`` holds what is true in any format, and each table format is a subpackage.

Imports no format eagerly, so no format's dependencies load until that format is imported.
"""
59 changes: 59 additions & 0 deletions dlccore/io/labeled_data/model.py
Original file line number Diff line number Diff line change
@@ -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
#

"""DeepLabCut's labeled-data model: what is true in any file format."""

from __future__ import annotations

from dataclasses import dataclass
from enum import Enum

# Keypoint data: always x and y, and a likelihood for models
# NOTE: 3D support is obviously missing
POSITION_COORDS = ("x", "y")
LIKELIHOOD_COORD = "likelihood"

# In multi-animal project, this denotes keypoints that do not belong to any individual.
# Extra caution is needed as this is a sentinel value, make sure to treat it accordingly.
# TODO: needs improvement in handling as this is a major source of confusion and potential bugs.
# It should not be used in any other format than the wide table "legacy" format.
UNIQUE_BODYPARTS_INDIVIDUAL = "single"

FramePath = tuple[str, ...]
"""A frame's path components as stored, e.g. ``("labeled-data", "session-01", "img000.png")``."""


class BodypartScope(str, Enum):
"""Whether a bodypart is labeled once per individual, or once per frame as DeepLabCut's ``uniquebodyparts``."""

INDIVIDUAL = "individual"
UNIQUE = "unique"


@dataclass(frozen=True)
class Keypoint:
"""Which keypoint: one bodypart, of one individual or unique, from one scorer.

Attributes:
scorer: As stored.
individual: As stored; ``None`` when the source names no individual.
bodypart: As stored.
"""

scorer: str
individual: str | None
bodypart: str

@property
def scope(self) -> BodypartScope:
"""``UNIQUE`` exactly when the individual is DeepLabCut's unique-bodyparts bucket."""

return BodypartScope.UNIQUE if self.individual == UNIQUE_BODYPARTS_INDIVIDUAL else BodypartScope.INDIVIDUAL
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.
"""
126 changes: 126 additions & 0 deletions dlccore/io/labeled_data/wide/header.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
#
# 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 Keypoint

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:
keypoint: The keypoint. 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``.
"""

keypoint: Keypoint
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``.
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, ...] = ()
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, 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(
keypoint=Keypoint(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