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: 17 additions & 2 deletions dlccore/io/labeled_data/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,22 @@

"""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.
``__all__`` holds:
- Model and views
- Arrays view
- Identity types
``model`` holds concepts common to all formats.
``_wide``, DeepLabCut's stored table, and ``_checks`` are internal to dlccore.

Imports no format eagerly.
"""

# Future formats to consider:
# - NWB
# - NPZ

from dlccore.io.labeled_data.arrays.from_long import LabeledDataArrays
from dlccore.io.labeled_data.long.model import LABELED_DATA_LONG_VERSION, LabeledData
from dlccore.io.labeled_data.model import (
BodypartScope,
FramePath,
Expand All @@ -24,9 +36,12 @@
)

__all__ = [
"LABELED_DATA_LONG_VERSION",
"BodypartScope",
"FramePath",
"KeypointDataFields",
"KeypointIdentifier",
"KeypointIdentifiers",
"LabeledData",
"LabeledDataArrays",
]
19 changes: 19 additions & 0 deletions dlccore/io/labeled_data/_checks/__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
#

"""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.
"""
105 changes: 105 additions & 0 deletions dlccore/io/labeled_data/_checks/file.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
#
# 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 intermediate result of reading the file, e.g. the H5 key selection.
Any problematic items are returnedas as a truthy value.
When there is nothing to report, it returns a falsy value.
"""

from __future__ import annotations

import pandas as pd

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,
)
from dlccore.io.labeled_data.long.model import FRAME_COLUMNS
from dlccore.io.labeled_data.model import LIKELIHOOD_COORD, POSITION_COORDS

_COORDINATES = frozenset({*POSITION_COORDS, LIKELIHOOD_COORD})


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_missing_likelihood(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.

Empty columns are skipped.
"""

return tuple(label for label, column in df.items() if not (column.empty or _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)
)
57 changes: 57 additions & 0 deletions dlccore/io/labeled_data/_wide/from_long.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
#
# 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._wide.header import MULTI_ANIMAL_LEVELS, SINGLE_ANIMAL_LEVELS
from dlccore.io.labeled_data.long.model import FRAME_COLUMNS, LabeledData, identity_values


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()
identifiers = labels.identifiers
coords = labels.data_fields.names
n_frames, n_keypoints = long["frame_index"].nunique(), len(identifiers)

# The long table has one row per (frame, keypoint), all of a frame's keypoints together, in the same order for
# every frame.
frames = long.iloc[::n_keypoints] if n_keypoints else long.iloc[:0]

# The column header is built from the keypoints, not from the rows; labels with no frames
# are written as a header-only file.
columns = pd.MultiIndex.from_arrays(
[
*(
pd.Index(values).repeat(len(coords))
for values in identity_values(identifiers, multi_animal=identifiers.multi_animal).values()
),
list(coords) * n_keypoints,
],
names=MULTI_ANIMAL_LEVELS if identifiers.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)
34 changes: 34 additions & 0 deletions dlccore/io/labeled_data/_wide/table.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
#
# 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
#

"""The wide labeled-data table as any container returns it, and its classification.

Containers (``h5``, ``csv``) only open files; everything about the table itself is decided here and in the modules
this one calls, once for every container.
"""

from __future__ import annotations

import pandas as pd

from dlccore.io.labeled_data._wide.header import LabeledDataHeader, classify_labeled_data_header
from dlccore.io.labeled_data._wide.row_index import LabeledDataRowIndex, classify_labeled_data_row_index


def classify_wide_df(df: pd.DataFrame) -> tuple[LabeledDataHeader, LabeledDataRowIndex]:
"""Classify the header and row index of a wide table, whether read from a file or built in memory."""

columns = (column if isinstance(column, tuple) else (column,) for column in df.columns)

return (
classify_labeled_data_header(df.columns.names, columns),
classify_labeled_data_row_index(df.index.names, df.index, is_multi_index=isinstance(df.index, pd.MultiIndex)),
)
Loading
Loading