diff --git a/.github/workflows/test_package.yml b/.github/workflows/test_package.yml index 930e21f..aa60865 100644 --- a/.github/workflows/test_package.yml +++ b/.github/workflows/test_package.yml @@ -61,7 +61,7 @@ jobs: run: sudo apt-get update && sudo apt-get install -y ffmpeg - name: Install the lowest version each dependency declares - run: uv pip install --resolution lowest-direct ".[video]" "pytest>=8" + run: uv pip install --resolution lowest-direct ".[hdf5,video]" "pytest>=8" - name: Test run: pytest tests diff --git a/dlccore/io/labeled_data/wide/csv.py b/dlccore/io/labeled_data/wide/csv.py new file mode 100644 index 0000000..be7b769 --- /dev/null +++ b/dlccore/io/labeled_data/wide/csv.py @@ -0,0 +1,102 @@ +# +# 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 CSV files: which rows hold the header and which columns the row index, and the read itself. + +Returns the shared ``table.LabeledDataRead``; classification is the same for every container. Imported explicitly, +so pandas loads only when it is used. +""" + +from __future__ import annotations + +import csv +from itertools import islice +from pathlib import Path + +import pandas as pd + +from dlccore.io.errors import UnreadableFileError +from dlccore.io.labeled_data.wide.header import HEADER_DEPTHS, LabeledDataHeaderShape, header_shape +from dlccore.io.labeled_data.wide.table import LabeledDataRead + + +def _header_rows_and_index_columns(rows: list[list[str]]) -> tuple[int, int]: + """Return how many rows hold the header and how many columns hold the row index. + + Each header row starts with its level name, followed by one empty cell per further index column. The deepest + recognised header wins; with none, both are ``0`` and the file is read without a header. A header deeper than + the file is never recognised, so a file holding only its header reads as having no frames. + """ + + level_names = [row[0] if row else "" for row in rows] + + for depth in HEADER_DEPTHS: + if depth <= len(rows) and header_shape(level_names[:depth]) is not LabeledDataHeaderShape.UNRECOGNISED: + after_name = rows[0][1:] + empty = next((position for position, cell in enumerate(after_name) if cell), len(after_name)) + return depth, 1 + empty + + return 0, 0 + + +def _path_parts_as_text(path: Path, df: pd.DataFrame, header_rows: int) -> pd.MultiIndex: + """Return a path-parts row index as stored.""" + + names = df.index.names + if len(df.index) == 0: # only a header: no rows left to read the parts from + return pd.MultiIndex.from_arrays([[] for _ in names], names=names) + parts = pd.read_csv( + path, + header=None, + skiprows=header_rows + any(name is not None for name in names), + usecols=range(len(names)), + dtype=str, + ) + return pd.MultiIndex.from_frame(parts, names=names) + + +def read_labeled_data_csv(path: Path) -> LabeledDataRead: + """Read a labeled-data CSV as pandas parses it, with the layout detected from the file. + + Values are parsed as ``pandas.read_csv`` parses them, as DeepLabCut's ``convertcsv2h5`` does. Path parts stay + text, as ``convertcsv2h5`` restores them: a folder named ``2019`` or ``007`` is not a number. + + Args: + path: A ``CollectedData_*.csv`` or ``machinelabels*.csv`` file. + + Raises: + UnreadableFileError: If the file cannot be opened or parsed as CSV. + """ + + try: + # utf-8-sig drops the byte-order mark Excel writes in "CSV UTF-8", as pandas does + with path.open(newline="", encoding="utf-8-sig") as stream: + header_rows, index_columns = _header_rows_and_index_columns( + list(islice(csv.reader(stream), max(HEADER_DEPTHS))) + ) + + df = pd.read_csv(path, header=list(range(header_rows)) or None, index_col=list(range(index_columns)) or None) + if index_columns > 1: + df.index = _path_parts_as_text(path, df, header_rows) + except (OSError, ValueError, csv.Error) as error: + raise UnreadableFileError(f"{path}: cannot be read as CSV: {error}") from error + + return LabeledDataRead(path=path, dataframe=df, key_selection=None) + + +def write_labeled_data_csv(df: pd.DataFrame, path: Path) -> None: + """Write a wide table as DeepLabCut's human-readable CSV; the H5 stays authoritative. + + Values are written as pandas formats them, so a float can differ in its last digits after a round trip, and + the frames ``checks.file.frames_lost_to_csv`` returns are written but read back as something else. + """ + + df.to_csv(path) diff --git a/dlccore/io/labeled_data/wide/h5.py b/dlccore/io/labeled_data/wide/h5.py new file mode 100644 index 0000000..946d530 --- /dev/null +++ b/dlccore/io/labeled_data/wide/h5.py @@ -0,0 +1,229 @@ +# +# 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 HDF5 files: which key to read, and the read itself. + +Returns the shared ``table.LabeledDataRead``; classification is the same for every container. Imported explicitly, +so pandas and PyTables load only when it is used. +""" + +from __future__ import annotations + +from dataclasses import dataclass +from enum import Enum +from pathlib import Path + +import pandas as pd + +from dlccore.io.errors import UnreadableFileError +from dlccore.io.labeled_data.wide.table import LabeledDataRead +from dlccore.io.stamp import WRITER_KEY, WRITER_VERSION_KEY, WriterStamp + +# Observed from a payload pandas cannot rebuild: TypeError (unknown storer), NoSuchNodeError +# (LookupError, AttributeError) for a missing child node, HDF5ExtError (RuntimeError), OSError. +_PAYLOAD_READ_ERRORS = (OSError, RuntimeError, TypeError, ValueError, LookupError, AttributeError) + + +class H5KeyStatus(str, Enum): + """Confidence level for a key found in a labeled-data HDF5 file.""" + + CURRENT = "current" + LEGACY = "legacy" + UNKNOWN = "unknown" + + +# The key DeepLabCut and napari-deeplabcut write today, and the one this package writes. +CURRENT_H5_KEY = "df_with_missing" + +H5_KEY_REGISTRY: dict[str, H5KeyStatus] = { + CURRENT_H5_KEY: H5KeyStatus.CURRENT, + "keypoints": H5KeyStatus.LEGACY, +} + + +H5_KEY_PRECEDENCE: tuple[H5KeyStatus, ...] = ( + H5KeyStatus.CURRENT, + H5KeyStatus.LEGACY, + H5KeyStatus.UNKNOWN, +) + + +class H5KeySelectionOutcome(str, Enum): + """Closed set of key-selection results, describing the file rather than our reaction. + + Every outcome but ``EMPTY`` names a readable file: DeepLabCut and + napari-deeplabcut both read any single key, so refusing one is a + backwards-compatibility defect here. + """ + + SINGLE_CURRENT = "single_current" + SINGLE_LEGACY = "single_legacy" + SINGLE_UNKNOWN = "single_unknown" + MULTI_KEY = "multi_key" + EMPTY = "empty" + + +_SINGLE_KEY_OUTCOMES: dict[H5KeyStatus, H5KeySelectionOutcome] = { + H5KeyStatus.CURRENT: H5KeySelectionOutcome.SINGLE_CURRENT, + H5KeyStatus.LEGACY: H5KeySelectionOutcome.SINGLE_LEGACY, + H5KeyStatus.UNKNOWN: H5KeySelectionOutcome.SINGLE_UNKNOWN, +} + + +@dataclass(frozen=True) +class H5KeySelection: + """Result of enumerating and selecting among a file's HDF5 keys. + + Attributes: + keys_found: Keys pandas lists, in the file's order, without the leading ``/``. + selected_key: The key read, ``None`` exactly when ``outcome`` is ``EMPTY``. + outcome: What the keys found say about the file. + """ + + keys_found: tuple[str, ...] + selected_key: str | None + outcome: H5KeySelectionOutcome + + def __post_init__(self) -> None: + """Refuse a selection that names a key for an empty file, or none for a non-empty one. + + Raises: + ValueError: If ``selected_key`` is ``None`` and ``outcome`` is not ``EMPTY``, or the reverse. + """ + + if (self.selected_key is None) != (self.outcome is H5KeySelectionOutcome.EMPTY): + raise ValueError("An H5KeySelection selects no key exactly when its outcome is EMPTY.") + + +def select_by_precedence( + keys_found: tuple[str, ...], + statuses: dict[str, H5KeyStatus], +) -> str: + """Return the highest-precedence key; within one status, the file's own order wins. + + Declared rather than incidental: selecting among several keys without a + stated order is the silent first-match the key contract forbids. + + Raises: + ValueError: If no key carries a status listed in the precedence order. + """ + + for status in H5_KEY_PRECEDENCE: + for key in keys_found: + if statuses[key] is status: + return key + + raise ValueError(f"No key among {keys_found} carries a status in {H5_KEY_PRECEDENCE}.") + + +def select_h5_key(path: Path) -> H5KeySelection: + """Enumerate the pandas keys in an HDF5 file and select one per the key-selection policy. + + A single key is selected whatever its name; several keys select by declared precedence. + + Raises: + UnreadableFileError: If the file cannot be opened as HDF5. + """ + + try: + with pd.HDFStore(str(path), mode="r") as store: + keys_found = tuple(key.lstrip("/") for key in store) + except (OSError, RuntimeError) as error: + raise UnreadableFileError(f"{path}: cannot be opened as HDF5: {error}") from error + + if not keys_found: + return H5KeySelection(keys_found=keys_found, selected_key=None, outcome=H5KeySelectionOutcome.EMPTY) + + statuses = {key: H5_KEY_REGISTRY.get(key, H5KeyStatus.UNKNOWN) for key in keys_found} + + if len(keys_found) == 1: + return H5KeySelection( + keys_found=keys_found, + selected_key=keys_found[0], + outcome=_SINGLE_KEY_OUTCOMES[statuses[keys_found[0]]], + ) + + return H5KeySelection( + keys_found=keys_found, + selected_key=select_by_precedence(keys_found, statuses), + outcome=H5KeySelectionOutcome.MULTI_KEY, + ) + + +def read_labeled_data_h5(path: Path) -> LabeledDataRead: + """Read the selected key of a labeled-data HDF5 file as stored. + + Args: + path: A ``CollectedData_*.h5`` or ``machinelabels*.h5`` file. + + Raises: + UnreadableFileError: If the file cannot be opened, holds no pandas key, or its selected key does not + read back as a DataFrame. + """ + + key_selection = select_h5_key(path) + key = key_selection.selected_key + + if key is None: + raise UnreadableFileError(f"{path}: holds no pandas key, so there is nothing to read.") + + try: + payload = pd.read_hdf(path, key=key, mode="r") + except _PAYLOAD_READ_ERRORS as error: + raise UnreadableFileError(f"{path}: key {key!r} cannot be read: {error}") from error + + if not isinstance(payload, pd.DataFrame): + raise UnreadableFileError(f"{path}: key {key!r} holds a {type(payload).__name__}, not a DataFrame.") + + stamp, stamp_error = _writer_stamp(path, key) + return LabeledDataRead( + path=path, + dataframe=payload, + key_selection=key_selection, + writer_stamp=stamp, + writer_stamp_error=stamp_error, + ) + + +def write_labeled_data_h5(df: pd.DataFrame, path: Path, stamp: WriterStamp) -> None: + """Write a wide table whole under the current key, and stamp its node with who wrote it. + + The stamp is stored as plain string attributes, which HDF5 holds natively. Never appends: ``path`` is created + or overwritten. Callers write to a temporary path and replace. + """ + + df.to_hdf(path, key=CURRENT_H5_KEY, mode="w") + with pd.HDFStore(str(path), mode="a") as store: + attributes = store.get_storer(CURRENT_H5_KEY).attrs + for name, value in stamp.as_metadata().items(): + setattr(attributes, name, value) + + +def _writer_stamp(path: Path, key: str) -> tuple[WriterStamp | None, str | None]: + """Return the writer stamp on ``key``'s node, or why a stamp that is present is malformed. + + A malformed stamp leaves the table readable, as it is to pandas and DeepLabCut. + + Raises: + UnreadableFileError: If the attributes cannot be read. + """ + + try: + with pd.HDFStore(str(path), mode="r") as store: + attributes = store.get_storer(key).attrs + names = set(attributes._v_attrnamesuser) + metadata = {name: getattr(attributes, name) for name in (WRITER_KEY, WRITER_VERSION_KEY) if name in names} + except _PAYLOAD_READ_ERRORS as error: + raise UnreadableFileError(f"{path}: key {key!r} attributes cannot be read: {error}") from error + try: + return WriterStamp.from_metadata(metadata), None + except ValueError as error: + return None, f"{path}: key {key!r}: {error}" diff --git a/dlccore/io/labeled_data/wide/table.py b/dlccore/io/labeled_data/wide/table.py new file mode 100644 index 0000000..23bc175 --- /dev/null +++ b/dlccore/io/labeled_data/wide/table.py @@ -0,0 +1,70 @@ +# +# 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 + +from dataclasses import dataclass +from pathlib import Path +from typing import TYPE_CHECKING + +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 + +if TYPE_CHECKING: + from dlccore.io.labeled_data.wide.h5 import H5KeySelection + from dlccore.io.stamp import WriterStamp + + +@dataclass(frozen=True) +class LabeledDataRead: + """The raw content of one labeled-data file, whatever container stored it. + + Attributes: + path: The path as given; never resolved. + dataframe: The table as the container returned it, unmodified. + key_selection: For a container holding several tables, the keys found and the one read; ``None`` for a + container with one table, such as CSV. + writer_stamp: Who wrote the file, when this package's writer did; ``None`` otherwise, as for every file + written by anything else and every CSV. + writer_stamp_error: Why a stamp that is present could not be read, naming the file; the table is read + regardless. + """ + + path: Path + dataframe: pd.DataFrame + key_selection: H5KeySelection | None + writer_stamp: WriterStamp | None = None + writer_stamp_error: str | None = None + + +def classify_labeled_data_read(read: LabeledDataRead) -> tuple[LabeledDataHeader, LabeledDataRowIndex]: + """Classify the header and row index of a raw read, leaving the DataFrame untouched.""" + + return classify_wide_df(read.dataframe) + + +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)), + ) diff --git a/pyproject.toml b/pyproject.toml index 2fab704..debf6c6 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -23,11 +23,13 @@ classifiers = [ dynamic = [ "version" ] dependencies = [ "numpy>=1.22.4", + "pandas>=2.3.3", "pydantic>=2.1,<3", "ruamel-yaml>=0.16", "typing-extensions", ] -optional-dependencies.all = [ "dlccore[video]" ] +optional-dependencies.all = [ "dlccore[hdf5,video]" ] +optional-dependencies.hdf5 = [ "pandas[hdf5]", "tables>=3.10.1", "typing-extensions>=4.7" ] optional-dependencies.video = [ "opencv-python-headless>=4.10.0.84" ] urls.Homepage = "https://github.com/DeepLabCut/dlccore" urls.Repository = "https://github.com/DeepLabCut/dlccore" @@ -87,3 +89,7 @@ max_supported_python = "3.12" [tool.pytest] ini_options.addopts = "--strict-markers" ini_options.xfail_strict = true +ini_options.filterwarnings = [ + # A categorical groupby must state observed=; the default changes in pandas 3. + "error:The default of observed=False is deprecated:FutureWarning", +] diff --git a/tests/io/fixtures/labeled_data/README.md b/tests/io/fixtures/labeled_data/README.md new file mode 100644 index 0000000..60199b6 --- /dev/null +++ b/tests/io/fixtures/labeled_data/README.md @@ -0,0 +1,46 @@ +# Labeled-data fixtures + +Samples of what two specific writers produce. They are not a reference for valid labeled data, and they do not represent the historical DeepLabCut data in use. Not covered, among others: files written by DeepLabCut's labeling, `merge_annotateddatasets`, `convertcsv2h5` or outlier extraction; files written by DeepLabCut 2.x; multi-animal conversions that append keys; several scorers in one file; napari's frame-extraction writer. + +The fixtures are committed bytes, so nothing at test time needs a producer installed. Each producer is an exact tree or release, and regenerating anywhere else changes the bytes. + +## Written by napari-deeplabcut + +Written with a local napari-deeplabcut checkout at the producer commit below. + +- **Producer**: napari-deeplabcut commit `d50015d0dd4762ed2ff20e2fb51de590df297cdb` (version `0.3.1.2.dev5+g17d14f36e`), captured 2026-09-02. +- **Write primitive used**: `napari_deeplabcut.core.io._atomic_to_hdf` with the real `DLC_CANONICAL_H5_KEY` ("df_with_missing") — the same function `write_hdf` calls internally. This does **not** exercise the full NPE2 `write_hdf` contract (Points-layer/provenance validation), nor napari's other writer, frame extraction in `ui/cropping.py`. +- **Shapes**: verified against napari-deeplabcut's own conventions (its `conftest.py` fixture builders, and `restore_dlc_on_disk_header_shape`'s single-animal column collapse), not invented. + +| File | Animals | Source | Row index | Notes | +|---|---|---|---|---| +| `single_animal_human.h5` | single (no `individuals` level) | human (no likelihood) | modern MultiIndex | One genuinely missing keypoint (x and y both NaN) | +| `single_animal_machine.h5` | single | machine (with likelihood) | modern MultiIndex | " | +| `multi_animal_human.h5` | 2 named individuals | human | modern MultiIndex | " | +| `multi_animal_machine.h5` | 2 named individuals | machine | modern MultiIndex | " | +| `single_animal_human_legacy_index.h5` | single | human | flat POSIX-style string | For row-index tests | +| `ambiguous_multi_key.h5` | single | human | modern MultiIndex | Carries **two** keys (`df_with_missing` + legacy `keypoints`) for key-selection tests | + +## Written by DeepLabCut + +- **Producer**: `deeplabcut` 3.0.2, the registry release installed by `uv` (no local source), on Linux; Python 3.12.14, pandas 2.3.3, PyTables 3.11.1, numpy 2.5.3. `multi_animal_unique_bodyparts.h5` captured 2026-10-10, every other file 2026-10-12. +- **Write paths**, each on a project config written by `auxiliaryfunctions.write_config`, each call writing an `.h5` and its `.csv` twin: + - `deeplabcut.utils.auxfun_multianimal.convert_single2multiplelegacyAM(config, userfeedback=False, target="multi")`, from a hand-built 3-level single-animal file whose multi-animal bodyparts are named `_`. Nothing in DeepLabCut calls this function; the header shape it writes is the one labeling writes; + - `deeplabcut.generate_training_dataset.trainingsetmanipulation.dropduplicatesinannotatinfiles(config)`, from a hand-built single-animal file with a flat string row index and one row twice. +- **Only these paths**: DeepLabCut's labeling and `convert2_maDLC` write the same header shapes by other code; neither is exercised here. +- **Bytes are not reproducible**: HDF5 stamps every object with its write time, so a rerun writes a different `.h5` holding an equal table. The 2026-10-10 and 2026-10-12 runs differ in 72 bytes across 24 objects, all timestamps. Each `.csv` reads back equal to its `.h5` twin (`tests/io/labeled_data/wide/test_csv.py`). + +| File | Animals | Source | Row index | Notes | +|---|---|---|---|---| +| `multi_animal_unique_bodyparts.h5`, `.csv` | `animalA`, `animalB` × `snout`, `tail`, plus `single` × `feeder` | human | modern MultiIndex | Not a grid: 5 (individual, bodypart) pairs, not 3 × 3. animalA's tail is NaN in the second frame | +| `single_animal_legacy_index_dlc.h5`, `.csv` | single | human | flat POSIX-style string | Duplicate row dropped; 3 frames | + +Rerun 2026-10-16 with deeplabcut 3.0.2, pandas 2.3.3, PyTables 3.11.1 and numpy 1.26.4 on Linux: every `.h5` holds a table equal to its committed copy, and every `.csv` is byte-identical. + +## Why `keypoints` appears here + +`keypoints` is not a hypothetical legacy key. It is **napari-deeplabcut's own write key**, used from its first functional release (2022-05-12) until it switched to `df_with_missing` (2026-04-27). DeepLabCut has written `df_with_missing` since its first commit (2018-04-10). + +**Both projects read keyless**; `pd.read_hdf(path)` with no key succeeds for any single-key file. So a project labeled with both tools in that period legitimately holds both keys, one per video folder. + +A `keypoints` file is therefore real labeled data produced by the GUI DeepLabCut ships for labelling, not a corrupt or exotic file. Fixtures covering it exist so that stays true. The registry entry asserting it is `LEGACY` is pinned by `tests/io/labeled_data/wide/test_h5.py`. diff --git a/tests/io/fixtures/labeled_data/ambiguous_multi_key.h5 b/tests/io/fixtures/labeled_data/ambiguous_multi_key.h5 new file mode 100644 index 0000000..dd69d2d Binary files /dev/null and b/tests/io/fixtures/labeled_data/ambiguous_multi_key.h5 differ diff --git a/tests/io/fixtures/labeled_data/multi_animal_human.h5 b/tests/io/fixtures/labeled_data/multi_animal_human.h5 new file mode 100644 index 0000000..86937ee Binary files /dev/null and b/tests/io/fixtures/labeled_data/multi_animal_human.h5 differ diff --git a/tests/io/fixtures/labeled_data/multi_animal_machine.h5 b/tests/io/fixtures/labeled_data/multi_animal_machine.h5 new file mode 100644 index 0000000..e435340 Binary files /dev/null and b/tests/io/fixtures/labeled_data/multi_animal_machine.h5 differ diff --git a/tests/io/fixtures/labeled_data/multi_animal_unique_bodyparts.csv b/tests/io/fixtures/labeled_data/multi_animal_unique_bodyparts.csv new file mode 100644 index 0000000..0a7166e --- /dev/null +++ b/tests/io/fixtures/labeled_data/multi_animal_unique_bodyparts.csv @@ -0,0 +1,7 @@ +scorer,,,Sc,Sc,Sc,Sc,Sc,Sc,Sc,Sc,Sc,Sc +individuals,,,animalA,animalA,animalA,animalA,animalB,animalB,animalB,animalB,single,single +bodyparts,,,snout,snout,tail,tail,snout,snout,tail,tail,feeder,feeder +coords,,,x,y,x,y,x,y,x,y,x,y +labeled-data,session-01,img000.png,0.0,1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0,9.0 +labeled-data,session-01,img001.png,10.0,11.0,,,14.0,15.0,16.0,17.0,18.0,19.0 +labeled-data,session-01,img002.png,20.0,21.0,22.0,23.0,24.0,25.0,26.0,27.0,28.0,29.0 diff --git a/tests/io/fixtures/labeled_data/multi_animal_unique_bodyparts.h5 b/tests/io/fixtures/labeled_data/multi_animal_unique_bodyparts.h5 new file mode 100644 index 0000000..4276117 Binary files /dev/null and b/tests/io/fixtures/labeled_data/multi_animal_unique_bodyparts.h5 differ diff --git a/tests/io/fixtures/labeled_data/single_animal_human.h5 b/tests/io/fixtures/labeled_data/single_animal_human.h5 new file mode 100644 index 0000000..76cc6d8 Binary files /dev/null and b/tests/io/fixtures/labeled_data/single_animal_human.h5 differ diff --git a/tests/io/fixtures/labeled_data/single_animal_human_legacy_index.h5 b/tests/io/fixtures/labeled_data/single_animal_human_legacy_index.h5 new file mode 100644 index 0000000..4c77815 Binary files /dev/null and b/tests/io/fixtures/labeled_data/single_animal_human_legacy_index.h5 differ diff --git a/tests/io/fixtures/labeled_data/single_animal_legacy_index_dlc.csv b/tests/io/fixtures/labeled_data/single_animal_legacy_index_dlc.csv new file mode 100644 index 0000000..d315285 --- /dev/null +++ b/tests/io/fixtures/labeled_data/single_animal_legacy_index_dlc.csv @@ -0,0 +1,6 @@ +scorer,Sc,Sc,Sc,Sc +bodyparts,nose,nose,tail,tail +coords,x,y,x,y +labeled-data/session-01/img000.png,0.0,1.0,2.0,3.0 +labeled-data/session-01/img001.png,4.0,5.0,6.0,7.0 +labeled-data/session-01/img002.png,12.0,13.0,14.0,15.0 diff --git a/tests/io/fixtures/labeled_data/single_animal_legacy_index_dlc.h5 b/tests/io/fixtures/labeled_data/single_animal_legacy_index_dlc.h5 new file mode 100644 index 0000000..181a770 Binary files /dev/null and b/tests/io/fixtures/labeled_data/single_animal_legacy_index_dlc.h5 differ diff --git a/tests/io/fixtures/labeled_data/single_animal_machine.h5 b/tests/io/fixtures/labeled_data/single_animal_machine.h5 new file mode 100644 index 0000000..134d631 Binary files /dev/null and b/tests/io/fixtures/labeled_data/single_animal_machine.h5 differ diff --git a/tests/io/labeled_data/wide/test_csv.py b/tests/io/labeled_data/wide/test_csv.py new file mode 100644 index 0000000..b714fe8 --- /dev/null +++ b/tests/io/labeled_data/wide/test_csv.py @@ -0,0 +1,149 @@ +# +# 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 +# + +import codecs +from pathlib import Path + +import pandas as pd +import pytest + +from dlccore.io.errors import UnreadableFileError +from dlccore.io.labeled_data.wide.csv import read_labeled_data_csv +from dlccore.io.labeled_data.wide.h5 import read_labeled_data_h5 +from dlccore.io.labeled_data.wide.header import LabeledDataHeaderShape +from dlccore.io.labeled_data.wide.table import classify_labeled_data_read + +FIXTURES_DIR = Path(__file__).parents[2] / "fixtures" / "labeled_data" +CSV_FIXTURES = sorted(path.name for path in FIXTURES_DIR.glob("*.csv")) + + +def test_the_csv_fixtures_are_all_found_with_their_h5_twins() -> None: + # Control: an empty glob would let the parametrized parity tests pass by running nothing. + assert len(CSV_FIXTURES) == 2 + assert all((FIXTURES_DIR / name).with_suffix(".h5").exists() for name in CSV_FIXTURES) + + +@pytest.mark.parametrize("filename", CSV_FIXTURES) +def test_a_csv_reads_and_classifies_as_its_h5_twin(filename: str) -> None: + csv_read = read_labeled_data_csv(FIXTURES_DIR / filename) + h5_read = read_labeled_data_h5((FIXTURES_DIR / filename).with_suffix(".h5")) + + pd.testing.assert_frame_equal(csv_read.dataframe, h5_read.dataframe) + assert classify_labeled_data_read(csv_read) == classify_labeled_data_read(h5_read) + + +def test_the_parity_check_sees_a_changed_header(tmp_path: Path) -> None: + # Control: classifications that ignored the header would compare equal above whatever the file held. + path = tmp_path / "CollectedData_Sc.csv" + path.write_text((FIXTURES_DIR / "multi_animal_unique_bodyparts.csv").read_text().replace("feeder", "lever")) + h5_read = read_labeled_data_h5(FIXTURES_DIR / "multi_animal_unique_bodyparts.h5") + + assert classify_labeled_data_read(read_labeled_data_csv(path)) != classify_labeled_data_read(h5_read) + + +@pytest.mark.parametrize( + ("filename", "header_rows", "index_columns"), + [ + ("multi_animal_unique_bodyparts.csv", 4, 3), + ("single_animal_legacy_index_dlc.csv", 3, 1), + ], +) +def test_the_layout_is_read_from_the_file(filename: str, header_rows: int, index_columns: int) -> None: + df = read_labeled_data_csv(FIXTURES_DIR / filename).dataframe + + assert (df.columns.nlevels, df.index.nlevels) == (header_rows, index_columns) + + +@pytest.mark.parametrize("filename", CSV_FIXTURES) +def test_a_csv_with_a_byte_order_mark_reads_as_without(tmp_path: Path, filename: str) -> None: + # Excel's "CSV UTF-8" starts the file with a byte-order mark, which pandas drops. + path = tmp_path / filename + path.write_bytes(codecs.BOM_UTF8 + (FIXTURES_DIR / filename).read_bytes()) + + with_mark = read_labeled_data_csv(path) + without = read_labeled_data_csv(FIXTURES_DIR / filename) + + pd.testing.assert_frame_equal(with_mark.dataframe, without.dataframe) + assert classify_labeled_data_read(with_mark) == classify_labeled_data_read(without) + + +@pytest.mark.parametrize( + ("filename", "header_rows", "index_columns"), + [ + ("multi_animal_unique_bodyparts.csv", 4, 3), + ("single_animal_legacy_index_dlc.csv", 3, 1), + ], +) +def test_a_csv_holding_only_its_header_reads_as_no_frames( + tmp_path: Path, filename: str, header_rows: int, index_columns: int +) -> None: + path = tmp_path / filename + lines = (FIXTURES_DIR / filename).read_text().splitlines(keepends=True) + path.write_text("".join(lines[:header_rows])) + + read = read_labeled_data_csv(path) + header, _row_index = classify_labeled_data_read(read) + full_header, _full_row_index = classify_labeled_data_read(read_labeled_data_csv(FIXTURES_DIR / filename)) + + assert len(read.dataframe) == 0 + assert (read.dataframe.columns.nlevels, read.dataframe.index.nlevels) == (header_rows, index_columns) + assert header == full_header + + +def test_an_unrecognised_header_is_read_without_one(tmp_path: Path) -> None: + path = tmp_path / "CollectedData_Sc.csv" + path.write_text("frame,nose_x,nose_y\nimg0.png,1.0,2.0\n") + + read = read_labeled_data_csv(path) + header, _row_index = classify_labeled_data_read(read) + + assert read.key_selection is None + assert header.shape is LabeledDataHeaderShape.UNRECOGNISED + assert len(read.dataframe) == 2 + + +@pytest.mark.parametrize( + ("label", "content", "cause"), + [("missing", None, FileNotFoundError), ("not_utf8", b"\xff\xfe\x00scorer", UnicodeDecodeError)], + ids=str, +) +def test_an_unreadable_csv_raises_from_the_original( + tmp_path: Path, label: str, content: bytes | None, cause: type[Exception] +) -> None: + path = tmp_path / f"{label}.csv" + if content is not None: + path.write_bytes(content) + + with pytest.raises(UnreadableFileError, match=label) as raised: + read_labeled_data_csv(path) + + assert isinstance(raised.value.__cause__, cause) + + +@pytest.mark.parametrize("index_names", [None, ["root", "folder", "image"]], ids=["unnamed", "named"]) +def test_numeric_looking_path_parts_read_as_text_as_in_h5(tmp_path: Path, index_names: list[str] | None) -> None: + # A named index adds a row of names below the header, which the text read must skip. + columns = pd.MultiIndex.from_tuples([("Sc", "nose", "x")], names=["scorer", "bodyparts", "coords"]) + index = pd.MultiIndex.from_tuples( + [("labeled-data", "2019", "img0.png"), ("labeled-data", "007", "img1.png")], names=index_names + ) + df = pd.DataFrame([[1.0], [2.0]], index=index, columns=columns) + df.to_hdf(tmp_path / "CollectedData_Sc.h5", key="df_with_missing", mode="w") + df.to_csv(tmp_path / "CollectedData_Sc.csv") + + h5_read = read_labeled_data_h5(tmp_path / "CollectedData_Sc.h5") + csv_read = read_labeled_data_csv(tmp_path / "CollectedData_Sc.csv") + _h5_header, h5_row_index = classify_labeled_data_read(h5_read) + _csv_header, csv_row_index = classify_labeled_data_read(csv_read) + + pd.testing.assert_frame_equal(csv_read.dataframe, h5_read.dataframe) + assert h5_row_index.frames == tuple(index) + assert csv_row_index.frames == tuple(index) diff --git a/tests/io/labeled_data/wide/test_h5.py b/tests/io/labeled_data/wide/test_h5.py new file mode 100644 index 0000000..38941e9 --- /dev/null +++ b/tests/io/labeled_data/wide/test_h5.py @@ -0,0 +1,303 @@ +# +# 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 +# + +from pathlib import Path + +import pandas as pd +import pytest +import tables + +from dlccore.io.errors import UnreadableFileError +from dlccore.io.labeled_data.wide.h5 import ( + H5_KEY_REGISTRY, + H5KeySelection, + H5KeySelectionOutcome, + H5KeyStatus, + read_labeled_data_h5, + select_h5_key, +) + +FIXTURES_DIR = Path(__file__).parents[2] / "fixtures" / "labeled_data" +FIXTURES = sorted(path.name for path in FIXTURES_DIR.glob("*.h5")) + + +def _wide_columns() -> pd.MultiIndex: + return pd.MultiIndex.from_product( + [["Sc"], ["nose", "tail"], ["x", "y"]], + names=["scorer", "bodyparts", "coords"], + ) + + +def _write(path: Path, key: str, df: pd.DataFrame | None = None) -> Path: + (pd.DataFrame([[1.0, 2.0]]) if df is None else df).to_hdf(path, key=key, mode="w") + return path + + +# --- select_h5_key ----------------------------------------------------------------- + + +def test_select_h5_key_single_current(tmp_path: Path) -> None: + result = select_h5_key(_write(tmp_path / "CollectedData_Sc.h5", "df_with_missing")) + + assert result == H5KeySelection( + keys_found=("df_with_missing",), + selected_key="df_with_missing", + outcome=H5KeySelectionOutcome.SINGLE_CURRENT, + ) + + +def test_select_h5_key_single_legacy(tmp_path: Path) -> None: + result = select_h5_key(_write(tmp_path / "CollectedData_Sc.h5", "keypoints")) + + assert result.outcome == H5KeySelectionOutcome.SINGLE_LEGACY + assert result.selected_key == "keypoints" + + +def test_select_h5_key_multi_key_selects_current_over_legacy(tmp_path: Path) -> None: + path = _write(tmp_path / "CollectedData_Sc.h5", "keypoints") + with pd.HDFStore(path, mode="a") as store: + store.put("df_with_missing", pd.DataFrame([[1.0, 2.0]])) + + result = select_h5_key(path) + + assert result.outcome == H5KeySelectionOutcome.MULTI_KEY + assert result.selected_key == "df_with_missing" + assert set(result.keys_found) == {"df_with_missing", "keypoints"} + + +def test_select_h5_key_multi_key_selects_legacy_over_unknown(tmp_path: Path) -> None: + path = _write(tmp_path / "CollectedData_Sc.h5", "some_other_key") + with pd.HDFStore(path, mode="a") as store: + store.put("keypoints", pd.DataFrame([[1.0, 2.0]])) + + result = select_h5_key(path) + + assert result.outcome == H5KeySelectionOutcome.MULTI_KEY + assert result.selected_key == "keypoints" + + +def test_select_h5_key_single_unknown_key_is_still_selected(tmp_path: Path) -> None: + """DeepLabCut's merge reads any single key, so refusing one is our defect.""" + + result = select_h5_key(_write(tmp_path / "CollectedData_Sc.h5", "some_other_key")) + + assert result.outcome == H5KeySelectionOutcome.SINGLE_UNKNOWN + assert result.selected_key == "some_other_key" + + +def test_h5_key_registry_status_matches_design() -> None: + assert H5_KEY_REGISTRY["df_with_missing"] == H5KeyStatus.CURRENT, ( + "DeepLabCut has written this key since its first commit, 2018-04-10." + ) + assert H5_KEY_REGISTRY["keypoints"] == H5KeyStatus.LEGACY, ( + "DO NOT DROP THIS KEY UNLESS YOU HAVE A VERY GOOD REASON TO DO SO. " + "Not a defensive guess: napari-deeplabcut wrote this key itself from 2022-05-12 " + "until 2026-04-27. Both tools read keyless, so no divergence was noticed. " + "Files carrying it are labeled data produced by " + "the GUI DeepLabCut ships for labelling, and a single project may hold both keys, " + "one per video folder, depending on which tool labeled it." + ) + + +@pytest.mark.parametrize( + ("selected_key", "outcome"), + [(None, H5KeySelectionOutcome.SINGLE_CURRENT), ("df_with_missing", H5KeySelectionOutcome.EMPTY)], +) +def test_a_key_selection_names_a_key_exactly_when_the_file_has_one( + selected_key: str | None, + outcome: H5KeySelectionOutcome, +) -> None: + with pytest.raises(ValueError, match="EMPTY"): + H5KeySelection(keys_found=(), selected_key=selected_key, outcome=outcome) + + +# --- read_labeled_data_h5: the raw read -------------------------------------------- + + +@pytest.mark.parametrize("filename", FIXTURES) +def test_the_raw_read_equals_pandas_on_the_selected_key(filename: str) -> None: + path = FIXTURES_DIR / filename + + result = read_labeled_data_h5(path) + + pd.testing.assert_frame_equal(result.dataframe, pd.read_hdf(path, key=result.key_selection.selected_key)) + + +def test_the_fixtures_are_all_found() -> None: + # Control: an empty glob would let the parametrized equality test pass by running nothing. + assert len(FIXTURES) == 8 + + +def test_the_equality_check_sees_a_modified_frame() -> None: + # Control: assert_frame_equal must fail on a DataFrame differing in one value, or equality proves nothing. + path = FIXTURES_DIR / "single_animal_human.h5" + modified = read_labeled_data_h5(path).dataframe.copy() + modified.iloc[0, 0] += 1 + + with pytest.raises(AssertionError): + pd.testing.assert_frame_equal(modified, pd.read_hdf(path, key="df_with_missing")) + + +def test_the_legacy_flat_row_index_is_returned_as_stored() -> None: + result = read_labeled_data_h5(FIXTURES_DIR / "single_animal_human_legacy_index.h5") + + assert not isinstance(result.dataframe.index, pd.MultiIndex) + assert all(isinstance(entry, str) for entry in result.dataframe.index) + + +def test_a_multi_animal_header_with_unique_bodyparts_is_returned_as_stored_not_as_a_grid() -> None: + columns = read_labeled_data_h5(FIXTURES_DIR / "multi_animal_unique_bodyparts.h5").dataframe.columns + + individuals = columns.get_level_values("individuals") + bodyparts = columns.get_level_values("bodyparts") + pairs = list(dict.fromkeys(zip(individuals, bodyparts, strict=True))) + + assert pairs == [ + ("animalA", "snout"), + ("animalA", "tail"), + ("animalB", "snout"), + ("animalB", "tail"), + ("single", "feeder"), + ] + assert len(columns) < columns.levshape[1] * columns.levshape[2] * columns.levshape[3] + + +@pytest.mark.parametrize("filename", FIXTURES) +def test_reading_leaves_the_file_unchanged(filename: str) -> None: + path = FIXTURES_DIR / filename + before = (path.read_bytes(), path.stat().st_mtime_ns) + + read_labeled_data_h5(path) + + assert (path.read_bytes(), path.stat().st_mtime_ns) == before + + +def test_a_multi_key_fixture_is_read_by_precedence_and_reported() -> None: + result = read_labeled_data_h5(FIXTURES_DIR / "ambiguous_multi_key.h5") + + assert result.dataframe is not None + assert result.key_selection.outcome == H5KeySelectionOutcome.MULTI_KEY + assert result.key_selection.selected_key == "df_with_missing" + assert set(result.key_selection.keys_found) == {"df_with_missing", "keypoints"} + + +def test_a_single_unrecognised_key_is_read(tmp_path: Path) -> None: + path = _write(tmp_path / "CollectedData_Sc.h5", "some_other_key") + + result = read_labeled_data_h5(path) + + assert result.dataframe is not None + assert result.key_selection.outcome == H5KeySelectionOutcome.SINGLE_UNKNOWN + + +def test_missing_values_are_preserved(tmp_path: Path) -> None: + index = pd.MultiIndex.from_tuples([("labeled-data", "session-01", "img001.png")]) + df = pd.DataFrame([[1.0, 2.0, float("nan"), float("nan")]], index=index, columns=_wide_columns()) + + result = read_labeled_data_h5(_write(tmp_path / "CollectedData_Sc.h5", "df_with_missing", df)) + + assert pd.isna(result.dataframe.loc[("labeled-data", "session-01", "img001.png"), ("Sc", "tail", "x")]) + + +def test_an_empty_dataframe_is_read(tmp_path: Path) -> None: + df = pd.DataFrame(columns=_wide_columns()) + + result = read_labeled_data_h5(_write(tmp_path / "CollectedData_Sc.h5", "df_with_missing", df)) + + assert result.dataframe.empty + + +# --- read_labeled_data_h5: one exception for a file that cannot be read ----------- + + +@pytest.mark.parametrize( + ("label", "content"), + [("missing", None), ("not_hdf5", b"not an hdf5 file at all"), ("zero_bytes", b"")], + ids=str, +) +def test_an_unreadable_file_raises_from_the_original(tmp_path: Path, label: str, content: bytes | None) -> None: + path = tmp_path / f"{label}.h5" + if content is not None: + path.write_bytes(content) + + with pytest.raises(UnreadableFileError, match=label) as raised: + read_labeled_data_h5(path) + + assert isinstance(raised.value.__cause__, (OSError, RuntimeError)) + + +def test_a_directory_is_unreadable(tmp_path: Path) -> None: + path = tmp_path / "CollectedData_Sc.h5" + path.mkdir() + + with pytest.raises(UnreadableFileError): + read_labeled_data_h5(path) + + +def test_a_truncated_file_is_unreadable(tmp_path: Path) -> None: + path = _write(tmp_path / "CollectedData_Sc.h5", "df_with_missing", pd.DataFrame([[1.0] * 100] * 100)) + content = path.read_bytes() + path.write_bytes(content[: len(content) // 2]) + + with pytest.raises(UnreadableFileError): + read_labeled_data_h5(path) + + +def test_an_empty_store_is_selected_as_empty_and_raises_on_read(tmp_path: Path) -> None: + path = tmp_path / "CollectedData_Sc.h5" + with pd.HDFStore(path, mode="w"): + pass + + assert select_h5_key(path) == H5KeySelection(keys_found=(), selected_key=None, outcome=H5KeySelectionOutcome.EMPTY) + + with pytest.raises(UnreadableFileError, match="no pandas key") as raised: + read_labeled_data_h5(path) + + assert raised.value.__cause__ is None + + +def test_a_file_holding_only_non_pandas_nodes_has_no_keys(tmp_path: Path) -> None: + path = tmp_path / "CollectedData_Sc.h5" + with tables.open_file(path, "w") as h5: + h5.create_array("/", "values", [1, 2, 3]) + + with pytest.raises(UnreadableFileError, match="no pandas key"): + read_labeled_data_h5(path) + + +def test_a_payload_pandas_cannot_rebuild_raises_from_the_original(tmp_path: Path) -> None: + path = _write(tmp_path / "CollectedData_Sc.h5", "df_with_missing") + with tables.open_file(path, "a") as h5: + h5.get_node("/df_with_missing")._v_attrs.pandas_type = "not_a_pandas_type" + + with pytest.raises(UnreadableFileError, match="'df_with_missing'") as raised: + read_labeled_data_h5(path) + + assert isinstance(raised.value.__cause__, TypeError) + + +def test_a_payload_missing_a_node_raises_from_the_original(tmp_path: Path) -> None: + path = _write(tmp_path / "CollectedData_Sc.h5", "df_with_missing") + with tables.open_file(path, "a") as h5: + h5.remove_node("/df_with_missing", "block0_values") + + with pytest.raises(UnreadableFileError) as raised: + read_labeled_data_h5(path) + + assert isinstance(raised.value.__cause__, tables.NoSuchNodeError) + + +def test_a_stored_series_is_not_a_dataframe(tmp_path: Path) -> None: + path = tmp_path / "CollectedData_Sc.h5" + pd.Series([1.0, 2.0]).to_hdf(path, key="df_with_missing", mode="w") + + with pytest.raises(UnreadableFileError, match="holds a Series"): + read_labeled_data_h5(path) diff --git a/tests/io/labeled_data/wide/test_header.py b/tests/io/labeled_data/wide/test_header.py new file mode 100644 index 0000000..a758783 --- /dev/null +++ b/tests/io/labeled_data/wide/test_header.py @@ -0,0 +1,144 @@ +# +# 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 +# + +from dataclasses import replace +from pathlib import Path + +import pytest + +from dlccore.io.labeled_data.model import BodypartScope +from dlccore.io.labeled_data.wide.h5 import read_labeled_data_h5 +from dlccore.io.labeled_data.wide.header import ( + LabeledDataHeader, + LabeledDataHeaderShape, + classify_labeled_data_header, +) +from dlccore.io.labeled_data.wide.table import classify_labeled_data_read + +FIXTURES_DIR = Path(__file__).parents[2] / "fixtures" / "labeled_data" +FIXTURES = sorted(path.name for path in FIXTURES_DIR.glob("*.h5")) +MULTI_ANIMAL = ("scorer", "individuals", "bodyparts", "coords") + + +def _rebuilt_columns(header: LabeledDataHeader) -> list[tuple[str, ...]]: + columns: dict[int, tuple[str, ...]] = {} + + for placed in header.keypoints: + keypoint = placed.keypoint + + for coord, position in zip(placed.coords, placed.positions, strict=True): + if header.shape is LabeledDataHeaderShape.SINGLE_ANIMAL: + columns[position] = (keypoint.scorer, keypoint.bodypart, coord) + else: + columns[position] = (keypoint.scorer, keypoint.individual, keypoint.bodypart, coord) + + return [columns[position] for position in sorted(columns)] + + +def _multi_animal(columns: list[tuple[str, str, str, str]]) -> LabeledDataHeader: + return classify_labeled_data_header(MULTI_ANIMAL, columns) + + +@pytest.mark.parametrize("filename", FIXTURES) +def test_every_fixture_header_is_rebuilt_from_its_keypoints(filename: str) -> None: + df = read_labeled_data_h5(FIXTURES_DIR / filename).dataframe + + header, _row_index = classify_labeled_data_read(read_labeled_data_h5(FIXTURES_DIR / filename)) + + assert header.shape is not LabeledDataHeaderShape.UNRECOGNISED + assert _rebuilt_columns(header) == list(df.columns) + + +def test_the_rebuild_sees_a_tampered_keypoint() -> None: + # Control: a rebuild that ignored the keypoints would pass every fixture above. + header, _row_index = classify_labeled_data_read(read_labeled_data_h5(FIXTURES_DIR / "single_animal_human.h5")) + first = header.keypoints[0] + moved = replace(first, keypoint=replace(first.keypoint, bodypart="elsewhere")) + tampered = replace(header, keypoints=(moved, *header.keypoints[1:])) + + assert _rebuilt_columns(tampered) != _rebuilt_columns(header) + + +def test_unique_bodyparts_are_unique_and_never_an_individual() -> None: + header, _row_index = classify_labeled_data_read( + read_labeled_data_h5(FIXTURES_DIR / "multi_animal_unique_bodyparts.h5") + ) + + keypoints = [placed.keypoint for placed in header.keypoints] + + assert [(keypoint.individual, keypoint.bodypart, keypoint.scope) for keypoint in keypoints] == [ + ("animalA", "snout", BodypartScope.INDIVIDUAL), + ("animalA", "tail", BodypartScope.INDIVIDUAL), + ("animalB", "snout", BodypartScope.INDIVIDUAL), + ("animalB", "tail", BodypartScope.INDIVIDUAL), + ("single", "feeder", BodypartScope.UNIQUE), + ] + + +def test_a_name_containing_single_is_an_individual() -> None: + header = _multi_animal([("Sc", "single_mouse", "nose", "x"), ("Sc", "single_mouse", "nose", "y")]) + + assert header.keypoints[0].keypoint.scope is BodypartScope.INDIVIDUAL + + +def test_a_single_animal_header_has_individual_keypoints_without_a_name() -> None: + header, _row_index = classify_labeled_data_read(read_labeled_data_h5(FIXTURES_DIR / "single_animal_human.h5")) + + assert header.shape is LabeledDataHeaderShape.SINGLE_ANIMAL + assert {(placed.keypoint.individual, placed.keypoint.scope) for placed in header.keypoints} == { + (None, BodypartScope.INDIVIDUAL) + } + + +def test_reordered_columns_give_the_same_keypoints_at_other_positions() -> None: + columns = [("Sc", "a", "nose", "x"), ("Sc", "a", "nose", "y"), ("Sc", "b", "nose", "x"), ("Sc", "b", "nose", "y")] + reordered = [columns[2], columns[0], columns[3], columns[1]] + + in_order, shuffled = _multi_animal(columns), _multi_animal(reordered) + + assert {(k.keypoint, k.coords) for k in in_order.keypoints} == {(k.keypoint, k.coords) for k in shuffled.keypoints} + assert [k.positions for k in in_order.keypoints] != [k.positions for k in shuffled.keypoints] + + +def test_a_missing_pair_is_absent_not_padded() -> None: + header = _multi_animal([("Sc", "a", "nose", "x"), ("Sc", "a", "tail", "x"), ("Sc", "b", "nose", "x")]) + + assert [(placed.keypoint.individual, placed.keypoint.bodypart) for placed in header.keypoints] == [ + ("a", "nose"), + ("a", "tail"), + ("b", "nose"), + ] + + +def test_a_duplicated_column_is_kept() -> None: + header = _multi_animal([("Sc", "a", "nose", "x"), ("Sc", "a", "nose", "x")]) + + (keypoint,) = header.keypoints + + assert (keypoint.coords, keypoint.positions) == (("x", "x"), (0, 1)) + + +def test_coordinates_are_classified_whatever_they_are() -> None: + header = _multi_animal([("Sc", "a", "nose", "z")]) + + assert header.keypoints[0].coords == ("z",) + + +def test_unrecognised_level_names_keep_the_columns_and_raise_nothing() -> None: + columns = [("Sc", "nose", "x", "extra")] + + header = classify_labeled_data_header(("scorer", "bodyparts", "coords", "extra"), columns) + + assert (header.shape, header.keypoints, header.columns) == ( + LabeledDataHeaderShape.UNRECOGNISED, + (), + (("Sc", "nose", "x", "extra"),), + ) diff --git a/tests/io/labeled_data/wide/test_row_index.py b/tests/io/labeled_data/wide/test_row_index.py new file mode 100644 index 0000000..b2ca445 --- /dev/null +++ b/tests/io/labeled_data/wide/test_row_index.py @@ -0,0 +1,119 @@ +# +# 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 +# + +from pathlib import Path + +import numpy as np +import pandas as pd +import pytest + +from dlccore.io.labeled_data.wide.h5 import read_labeled_data_h5 +from dlccore.io.labeled_data.wide.row_index import ( + RowIndexShape, + classify_labeled_data_row_index, + frame_part_as_text, + split_frame_path, +) +from dlccore.io.labeled_data.wide.table import classify_labeled_data_read + +FIXTURES_DIR = Path(__file__).parents[2] / "fixtures" / "labeled_data" +FIXTURES = sorted(path.name for path in FIXTURES_DIR.glob("*.h5")) + + +@pytest.mark.parametrize("filename", FIXTURES) +def test_every_fixture_row_index_is_kept_and_split(filename: str) -> None: + df = read_labeled_data_h5(FIXTURES_DIR / filename).dataframe + + _header, row_index = classify_labeled_data_read(read_labeled_data_h5(FIXTURES_DIR / filename)) + + assert (row_index.names, row_index.entries) == (tuple(df.index.names), tuple(df.index)) + assert all(len(parts) == 3 for parts in row_index.frames) + assert len(row_index.frames) == len(df.index) + + +def test_the_legacy_flat_index_is_flat_paths() -> None: + _header, row_index = classify_labeled_data_read( + read_labeled_data_h5(FIXTURES_DIR / "single_animal_human_legacy_index.h5") + ) + + assert row_index.shape is RowIndexShape.FLAT_PATHS + + +def test_both_separators_split_alike() -> None: + row_index = classify_labeled_data_row_index( + [None], [r"labeled-data\vid1\img1.png", "labeled-data/vid1/img2.png"], is_multi_index=False + ) + + assert row_index.frames == (("labeled-data", "vid1", "img1.png"), ("labeled-data", "vid1", "img2.png")) + + +def test_a_ragged_index_stays_ragged() -> None: + row_index = classify_labeled_data_row_index( + [None], ["labeled-data/vid1/img1.png", "img2.png"], is_multi_index=False + ) + + assert row_index.frames == (("labeled-data", "vid1", "img1.png"), ("img2.png",)) + + +def test_a_numeric_index_is_unrecognised_and_kept() -> None: + row_index = classify_labeled_data_row_index([None], [0, 1], is_multi_index=False) + + assert (row_index.shape, row_index.entries, row_index.frames) == (RowIndexShape.UNRECOGNISED, (0, 1), ()) + + +@pytest.mark.parametrize( + "index", + [pd.RangeIndex(0), pd.Index([], dtype=object), pd.MultiIndex.from_tuples([], names=[None, None, None])], + ids=["range", "object", "multi"], +) +def test_an_index_without_entries_is_empty_whatever_its_type(index: pd.Index) -> None: + row_index = classify_labeled_data_row_index(index.names, index, is_multi_index=isinstance(index, pd.MultiIndex)) + + assert (row_index.shape, row_index.entries, row_index.frames) == (RowIndexShape.EMPTY, (), ()) + + +def test_a_numeric_folder_is_not_stringified() -> None: + index = pd.MultiIndex.from_tuples([("labeled-data", 2019, "img1.png")]) + + row_index = classify_labeled_data_row_index(index.names, index, is_multi_index=True) + + assert row_index.frames == (("labeled-data", 2019, "img1.png"),) + + +def test_level_names_are_kept_as_stored(tmp_path: Path) -> None: + # DeepLabCut's convertcsv2h5 stores a CSV's first frame without values as these names. + columns = pd.MultiIndex.from_product([["Sc"], ["nose"], ["x", "y"]], names=["scorer", "bodyparts", "coords"]) + index = pd.MultiIndex.from_tuples([("labeled-data", "s1", "img1.png")], names=["labeled-data", "s1", "img0.png"]) + pd.DataFrame([[1.0, 2.0]], index=index, columns=columns).to_hdf(tmp_path / "labels.h5", key="df_with_missing") + + _header, row_index = classify_labeled_data_read(read_labeled_data_h5(tmp_path / "labels.h5")) + + assert row_index.names == ("labeled-data", "s1", "img0.png") + assert row_index.frames == (("labeled-data", "s1", "img1.png"),) + + +def test_split_frame_path_keeps_empty_components() -> None: + assert split_frame_path("labeled-data//img1.png") == ("labeled-data", "", "img1.png") + + +@pytest.mark.parametrize( + ("part", "text"), + [("s1", "s1"), ("007", "007"), (2019, "2019"), (np.int64(2019), "2019")], + ids=["text", "zero_padded_text", "int", "numpy_int"], +) +def test_a_frame_part_with_a_name_is_read_as_that_text(part: object, text: str) -> None: + assert frame_part_as_text(part) == text + + +@pytest.mark.parametrize("part", [2019.0, True, np.True_, None], ids=["float", "bool", "numpy_bool", "none"]) +def test_a_frame_part_naming_no_folder_has_no_text(part: object) -> None: + # A float or bool would become a folder name that never existed. + assert frame_part_as_text(part) is None