From c4f23a82b1102ed1af824291ecc0f4ac628b494b Mon Sep 17 00:00:00 2001 From: C-Achard Date: Tue, 24 Nov 2026 10:56:18 +0100 Subject: [PATCH 1/6] Copy wide labeled-data readers --- dlccore/io/labeled_data/wide/csv.py | 87 ++++++ dlccore/io/labeled_data/wide/h5.py | 218 +++++++++++++ dlccore/io/labeled_data/wide/table.py | 61 ++++ tests/io/fixtures/labeled_data/README.md | 60 ++++ .../labeled_data/ambiguous_multi_key.h5 | Bin 0 -> 31064 bytes .../labeled_data/multi_animal_human.h5 | Bin 0 -> 18280 bytes .../labeled_data/multi_animal_machine.h5 | Bin 0 -> 18280 bytes .../multi_animal_unique_bodyparts.csv | 7 + .../multi_animal_unique_bodyparts.h5 | Bin 0 -> 18768 bytes .../labeled_data/single_animal_human.h5 | Bin 0 -> 16192 bytes .../single_animal_human_legacy_index.h5 | Bin 0 -> 12952 bytes .../single_animal_legacy_index_dlc.csv | 6 + .../single_animal_legacy_index_dlc.h5 | Bin 0 -> 12952 bytes .../labeled_data/single_animal_machine.h5 | Bin 0 -> 16192 bytes tests/io/labeled_data/wide/test_csv.py | 101 ++++++ tests/io/labeled_data/wide/test_h5.py | 292 ++++++++++++++++++ tests/io/labeled_data/wide/test_header.py | 133 ++++++++ tests/io/labeled_data/wide/test_row_index.py | 108 +++++++ 18 files changed, 1073 insertions(+) create mode 100644 dlccore/io/labeled_data/wide/csv.py create mode 100644 dlccore/io/labeled_data/wide/h5.py create mode 100644 dlccore/io/labeled_data/wide/table.py create mode 100644 tests/io/fixtures/labeled_data/README.md create mode 100644 tests/io/fixtures/labeled_data/ambiguous_multi_key.h5 create mode 100644 tests/io/fixtures/labeled_data/multi_animal_human.h5 create mode 100644 tests/io/fixtures/labeled_data/multi_animal_machine.h5 create mode 100644 tests/io/fixtures/labeled_data/multi_animal_unique_bodyparts.csv create mode 100644 tests/io/fixtures/labeled_data/multi_animal_unique_bodyparts.h5 create mode 100644 tests/io/fixtures/labeled_data/single_animal_human.h5 create mode 100644 tests/io/fixtures/labeled_data/single_animal_human_legacy_index.h5 create mode 100644 tests/io/fixtures/labeled_data/single_animal_legacy_index_dlc.csv create mode 100644 tests/io/fixtures/labeled_data/single_animal_legacy_index_dlc.h5 create mode 100644 tests/io/fixtures/labeled_data/single_animal_machine.h5 create mode 100644 tests/io/labeled_data/wide/test_csv.py create mode 100644 tests/io/labeled_data/wide/test_h5.py create mode 100644 tests/io/labeled_data/wide/test_header.py create mode 100644 tests/io/labeled_data/wide/test_row_index.py diff --git a/dlccore/io/labeled_data/wide/csv.py b/dlccore/io/labeled_data/wide/csv.py new file mode 100644 index 0000000..c02ec83 --- /dev/null +++ b/dlccore/io/labeled_data/wide/csv.py @@ -0,0 +1,87 @@ +"""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 dlc_octopus.io.errors import UnreadableFileError +from dlc_octopus.io.labeled_data.wide.header import HEADER_DEPTHS, LabeledDataHeaderShape, header_shape +from dlc_octopus.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 columns the row index, as pandas writes a wide table. + + 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. + """ + + level_names = [row[0] if row else "" for row in rows] + + for depth in HEADER_DEPTHS: + if 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, frame: pd.DataFrame, header_rows: int) -> pd.MultiIndex: + """Return a path-parts row index as stored: ``read_csv`` infers ``index_col`` types whatever ``dtype`` says.""" + + names = frame.index.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: + with path.open(newline="", encoding="utf-8") as stream: + header_rows, index_columns = _header_rows_and_index_columns( + list(islice(csv.reader(stream), max(HEADER_DEPTHS))) + ) + + frame = pd.read_csv(path, header=list(range(header_rows)) or None, index_col=list(range(index_columns)) or None) + if index_columns > 1: + frame.index = _path_parts_as_text(path, frame, 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=frame, key_selection=None) + + +def write_labeled_data_csv(frame: pd.DataFrame, path: Path) -> None: + """Write a wide table as DeepLabCut's human-readable CSV twin; 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. + """ + + frame.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..54c4818 --- /dev/null +++ b/dlccore/io/labeled_data/wide/h5.py @@ -0,0 +1,218 @@ +"""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 dlc_octopus.io.errors import UnreadableFileError +from dlc_octopus.io.labeled_data.wide.table import LabeledDataRead +from dlc_octopus.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(frame: 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. + """ + + frame.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..fc924bf --- /dev/null +++ b/dlccore/io/labeled_data/wide/table.py @@ -0,0 +1,61 @@ +"""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 dlc_octopus.io.labeled_data.wide.header import LabeledDataHeader, classify_labeled_data_header +from dlc_octopus.io.labeled_data.wide.row_index import LabeledDataRowIndex, classify_labeled_data_row_index + +if TYPE_CHECKING: + from dlc_octopus.io.labeled_data.wide.h5 import H5KeySelection + from dlc_octopus.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_frame(read.dataframe) + + +def classify_wide_frame(frame: 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 frame.columns) + + return ( + classify_labeled_data_header(frame.columns.names, columns), + classify_labeled_data_row_index( + frame.index.names, frame.index, is_multi_index=isinstance(frame.index, pd.MultiIndex) + ), + ) diff --git a/tests/io/fixtures/labeled_data/README.md b/tests/io/fixtures/labeled_data/README.md new file mode 100644 index 0000000..821007a --- /dev/null +++ b/tests/io/fixtures/labeled_data/README.md @@ -0,0 +1,60 @@ +# 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 + +Generated by a script run against a local napari-deeplabcut checkout. + +- **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 | + +Regenerate with: + +``` +"/.venv/Scripts/python.exe" tests/io/fixtures/labeled_data/generate_napari_golden_fixtures.py +``` + +The script writes into its own folder, with that checkout at the producer commit. + +## 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 | + +Regenerate with: + +``` + tests/io/fixtures/labeled_data/generate_dlc_labeled_data_fixtures.py +``` + +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 0000000000000000000000000000000000000000..dd69d2d833996108b522ad5647da77ef71458410 GIT binary patch literal 31064 zcmeGlZERat^}eLtyf*FJwH09$=4pJGZ3#~4Ac#(T?vl)d(u5={85?t)*h#!Pwr9H` z0g3e&m<>(+nIC|nX+jp_M}Hs`q5de9089KS|H{AaAAf)e2`NH?a_>Fo_`dh-`y9K8 z`yPEyYR~x?mh006Jrxc4n2N|i6<0d2Uu9X(x1Ed%xypprKx-#Ukrp* zgtb0+G1x;)lnr8j7~7BZL&hDXoxFFXF51 zPeGdGSn>PAl7A=8$1hG!gB)4qBY%0dh)a--P%{@M#|$oN#CKd2cwcc8$RL&Oiz-NLrh+ksEBhL+=w$^(@*30A<3u&>S;N$G?mD!0Qp^2URoGFzG zCBFCwd}}}DN-4WovG#LN&McqKu8JqL0=9`MXV%^oRr}63O_^Z5*!gpU! zPY<6F-EjPfgzeUKiNyba{yEUFZ?{iUNoy#0L_G5!2dMi?`f=x!4g>N@@5R7^cSrVc z>CB=ST)t42;#^5(a|kB(0+ix8* zf0MfYufNTv&2wizy#D^5m(1MoGp9b9eZ&0SSn}yVo?S2>{n_)$rQz4i^}E+=YxB$I z!GFBFww6ho;h+9~^yUvg#C2rnZ81v5cHaK_6F0yAr{@>UsoL#d)vw0Qb~A-~!QX%a z0R;jI1QZA;@E}k?_%Fm`7}6{R8&jlZuGNm)-9Ay-xre2lTPdaT4HmQxf=K2^#E}Y#;4#UaO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8va~Gefe?ayVH=b?)|&+-D${Ik+Lhlnogu^+n4E@_9?&G z9_72!HSJTrYM<841uJ*PF3CaHtfRVF55L;HhhJ5LhY#|qJ05E)p`ZeP92zEj;*!|u5Qk6?H;zN-$Txmp b$!Gsf7n8jE@8;cC8fh!M(eu@u{o(%r-EhJ5 literal 0 HcmV?d00001 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 0000000000000000000000000000000000000000..e4353405284d169b5dac5b198d5174dba8d80f0f GIT binary patch literal 18280 zcmeGjZERdeai1N>7spAQ#DvZS9;LC%DAYy-Q>Fik#T^oX9Cr&u8Bye&jyP z-NkhvD6}Z;r3k4FElni^p#jONipZZ*|0t46D%C+yArO*F3yJ^%LTRqLymNG=y!!fNCr{mfw+z6&svC;9+B zXb95?$IIYBV@sK!twVeb)?Z%^h>M8t>+R@ZoRjJ&h-5ao6rNm!D8cJW0=^D!k9gsJ zd~4FDDbzC(M(AMRJ|i_8h#JYH5j!MxPtbH?xI(xZ_0_J|)vR9DB=lQYP2b&pU0i|L zT5di<-+8xW&#GC2h0n$A?DG2k$XCH3+09+O-Fw9gn*1(auZ!*L==I;-y+_t7OosTI zo7_An_}e7ZxP=M+p8b8^on0ONKxcRFZf{>eRlcRE8OznmI!T^npWGG5)PV8@`>asf zr@kEc#{jVYo8e&?^V5y+Kyn=WJmg34h0;4AKZE=wP+Srq`4 z`|Wf>J3QKL`F!;~r1=xshNj6ifzEM@Pc4r^4@A_2pn97!{OiM&(vn%Z-K; zNh2NuJrk-y`r>YC-qzG&Ew@aT3&)1yAu*v~vbVRlud`8jV!J+v6Nz{tncGe>l`w`< z)^;l7o5ey#R5Ve;6&h5xUSu==7&N@L>l-MK-Dk#N7qIb2jIt$+;*cgU!ha|L)IP!V@5O>@dDTh z6iudBJSh!66*MA)LHW$_oP+;HjKkrGF&vMFNGgn(bB0#NGJlcaU^o&EHHLzzpr}0= z=Fwt2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Wfny7<+))^-*GqJq3?*^tC)wU9l)J}l zrW+4KJX&o3p^?ICQMC?~YtImC+sFUhf%9g6LXVr-n$lPFyEcitgz-iB2EAPH(Ly)< zQaLUm`iU?7YI(j}R6LLH&@y|dy>5Iit>x<=zTsE2EUI9Ui`zJ|K3Xm3A#4wIehPaT zOznOOh)$2|PYKst6XoUFLzKhn?P05`SjryS{S>}8Ue-?`MyH>`_19|mZajnYTi)(n zswumNvl0T|zo~yiQ5J~O@ao^5hJRC0FaB-i_B50$%V{gmr-R|b_GP-DeJanlN9Fc( zLHks$+9!W?Dv~%GgEvG4{;SokBR}80BR@Y)M?UbY;W+a1!*b*UKQ1I>j>RxXSnw`g HmjwO;ln>l( literal 0 HcmV?d00001 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 0000000000000000000000000000000000000000..4c77815957e90dabbf5655382f01a5f9a83c8bc6 GIT binary patch literal 12952 zcmeHNL2Oh-7@pTsSW1C~(pV9tsL?8R*%nB8fbbS+Em~=_T?j`~-EF1u zpeL=67>+%tA;d!u9*74*3X!cBI(z@E7D2rnpK~yPqt6#3RG$*{i1!=``V|u3HjMRzkd?*vq;3{ z2tMQ}ACUi+2G~A_37}!3x1YiHWL#Z;4D+Yy^)=o%DE#*J$4(8z(T?2q;Y?2CrmLuI z=)}M=Ln4@QCrwc$wv%?s_tE-MrHi0QYJle_yc^X4z6jFl@pI_!3@H)#xt!&stU|Il zowJpk;CJ148OvJ}P}3y1-Bx$IDLY?CXC1^DK!foTjdUK2$XG|W+o;;v&S*9T3koIg zcqbFR9pH(*c((KTY`#!APNA4jj~3nIG^jUoQt1g8A}j%o&~1ZkNj`GNF8Q`7`KIw)$EKajnF@^y7}iZeu!VZAZagiZJjF}GdvLjvYMJ7!vTl-?@LdN zN2Ae5&Ka-C(YYu`*PS&w!>c~Rp^*0*L zYu1h5eomy!qlfO^xbnl8nThP(^=sla^N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;m#hQ{8e$UisRJ?vmK zE=P*E+P+^9alF_SDEa_D4%-hIhv(pj6Dcbt@F5a3*h)D+#^HQa8Zm&*8SlehgOy8K zlSr_Wf3)2tSc-AG*jL!st&hi#VmwYW06oPTk1PHcMm`L-Lh^AfZdaWAr(Fy|`#wlW zoSyH;kndd3Y>&%#V21k6^VLh*|IgIR<$Oxg_kl#@a59w2h&`})Dw!#v!KxklnTsj( zGv7Q9UQds^dMdxv>~@^=)T7Z;%4;a7@)crBt=H4fknfn#lr%8r>M1Z{;d)vp2O5&& z9;Wl3;Y1=8;YzCapM(K)IQ=K}iaes!{dxLN%5x2&J8Z-6t(TAQ7L{J=;sf;^3*%Rj zt#blBy%bm7Tii$A`Q%n0p$jQdd1RGuZMesLYeR4$`BsQC;51SAtNd}YJsb{&?aF@;x_^U#xt`%5 zz+^a%CL4#{s`tC_u@T1T;P@(F609gY*;Q?vIkme#rKy0S-w@x$tU#b*C1^2Tjs zwFr_w_h6Vlh617Yi#HaP{nOcZ_5BJXFN;Ob7D^}WA9e8;$r(X={FUF{|B7-(mJ=u| zR(oG)c~b8yHv5x5?@Dq&P^X`I`{P{!l0Y-Kav?ZCVHMePFQoO@abOSM%~PJw!^=E> zFc3?G52m&ES!lkjeq)0{_ch^qN;ZzBEI54?suMkZ&jKN*kRAg1?_7=Fd6G~iEVTaf zOW!%~r~53l4*!;%?irOKY&nki#%3U31NmM5lR6A&pTO?gXY%6}dv7V9)AB<+K;j}FclIPx;DLvQArLPcoEn~M)#;5ol^n6b(8qm?_^Iw8g)B0Hw2yPgX72X%H`=}BSYD6)sTIECUF1?PM2{3pt_d+sbG1;s22 z)p!1H;}kkKo-=W51jqa~vc?CTxv*=0J~1->N5(VivC(Jt`8k&vGBQGpom!u#UDzgr##t^fc4 literal 0 HcmV?d00001 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..98fd4f0 --- /dev/null +++ b/tests/io/labeled_data/wide/test_csv.py @@ -0,0 +1,101 @@ +from pathlib import Path + +import pandas as pd +import pytest + +from dlc_octopus.io.errors import UnreadableFileError +from dlc_octopus.io.labeled_data.wide.csv import read_labeled_data_csv +from dlc_octopus.io.labeled_data.wide.h5 import read_labeled_data_h5 +from dlc_octopus.io.labeled_data.wide.header import LabeledDataHeaderShape +from dlc_octopus.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: + frame = read_labeled_data_csv(FIXTURES_DIR / filename).dataframe + + assert (frame.columns.nlevels, frame.index.nlevels) == (header_rows, index_columns) + + +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 + ) + frame = pd.DataFrame([[1.0], [2.0]], index=index, columns=columns) + frame.to_hdf(tmp_path / "CollectedData_Sc.h5", key="df_with_missing", mode="w") + frame.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..2ef2464 --- /dev/null +++ b/tests/io/labeled_data/wide/test_h5.py @@ -0,0 +1,292 @@ +from pathlib import Path + +import pandas as pd +import pytest +import tables + +from dlc_octopus.io.errors import UnreadableFileError +from dlc_octopus.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, frame: pd.DataFrame | None = None) -> Path: + (pd.DataFrame([[1.0, 2.0]]) if frame is None else frame).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 frame 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")]) + frame = 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", frame)) + + 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: + frame = pd.DataFrame(columns=_wide_columns()) + + result = read_labeled_data_h5(_write(tmp_path / "CollectedData_Sc.h5", "df_with_missing", frame)) + + 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..93761be --- /dev/null +++ b/tests/io/labeled_data/wide/test_header.py @@ -0,0 +1,133 @@ +from dataclasses import replace +from pathlib import Path + +import pytest + +from dlc_octopus.io.labeled_data.model import BodypartScope +from dlc_octopus.io.labeled_data.wide.h5 import read_labeled_data_h5 +from dlc_octopus.io.labeled_data.wide.header import ( + LabeledDataHeader, + LabeledDataHeaderShape, + classify_labeled_data_header, +) +from dlc_octopus.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: + frame = 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(frame.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..f5f0f1e --- /dev/null +++ b/tests/io/labeled_data/wide/test_row_index.py @@ -0,0 +1,108 @@ +from pathlib import Path + +import numpy as np +import pandas as pd +import pytest + +from dlc_octopus.io.labeled_data.wide.h5 import read_labeled_data_h5 +from dlc_octopus.io.labeled_data.wide.row_index import ( + RowIndexShape, + classify_labeled_data_row_index, + frame_part_as_text, + split_frame_path, +) +from dlc_octopus.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: + frame = 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(frame.index.names), tuple(frame.index)) + assert all(len(parts) == 3 for parts in row_index.frames) + assert len(row_index.frames) == len(frame.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 From e2006db5f19856b0007a076d61fddc7bd6426658 Mon Sep 17 00:00:00 2001 From: C-Achard Date: Tue, 24 Nov 2026 13:46:56 +0100 Subject: [PATCH 2/6] Adapt wide labeled-data readers to dlccore - Rename the package to dlccore.io and add the dlccore license header - Add pandas>=2.3.3 as a core dependency and an `hdf5` extra (tables>=3.10.1, the newest PyTables supporting Python 3.10), included in `all` - Error on pandas' observed= FutureWarning in tests - Name DataFrames `df`, never `frame`; classify_wide_frame becomes classify_wide_df - Drop the fixture README's regenerate commands, keeping the producer provenance - Fix lint in the edited header and CSV docstrings --- dlccore/io/labeled_data/wide/csv.py | 37 +++++++++++++------- dlccore/io/labeled_data/wide/h5.py | 21 ++++++++--- dlccore/io/labeled_data/wide/table.py | 31 ++++++++++------ pyproject.toml | 8 ++++- tests/io/fixtures/labeled_data/README.md | 16 +-------- tests/io/labeled_data/wide/test_csv.py | 31 ++++++++++------ tests/io/labeled_data/wide/test_h5.py | 29 ++++++++++----- tests/io/labeled_data/wide/test_header.py | 23 ++++++++---- tests/io/labeled_data/wide/test_row_index.py | 23 ++++++++---- 9 files changed, 143 insertions(+), 76 deletions(-) diff --git a/dlccore/io/labeled_data/wide/csv.py b/dlccore/io/labeled_data/wide/csv.py index c02ec83..e0a3d13 100644 --- a/dlccore/io/labeled_data/wide/csv.py +++ b/dlccore/io/labeled_data/wide/csv.py @@ -1,3 +1,14 @@ +# +# 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, @@ -12,13 +23,13 @@ import pandas as pd -from dlc_octopus.io.errors import UnreadableFileError -from dlc_octopus.io.labeled_data.wide.header import HEADER_DEPTHS, LabeledDataHeaderShape, header_shape -from dlc_octopus.io.labeled_data.wide.table import LabeledDataRead +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 columns the row index, as pandas writes a wide table. + """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. @@ -35,10 +46,10 @@ def _header_rows_and_index_columns(rows: list[list[str]]) -> tuple[int, int]: return 0, 0 -def _path_parts_as_text(path: Path, frame: pd.DataFrame, header_rows: int) -> pd.MultiIndex: - """Return a path-parts row index as stored: ``read_csv`` infers ``index_col`` types whatever ``dtype`` says.""" +def _path_parts_as_text(path: Path, df: pd.DataFrame, header_rows: int) -> pd.MultiIndex: + """Return a path-parts row index as stored.""" - names = frame.index.names + names = df.index.names parts = pd.read_csv( path, header=None, @@ -68,20 +79,20 @@ def read_labeled_data_csv(path: Path) -> LabeledDataRead: list(islice(csv.reader(stream), max(HEADER_DEPTHS))) ) - frame = pd.read_csv(path, header=list(range(header_rows)) or None, index_col=list(range(index_columns)) or None) + df = pd.read_csv(path, header=list(range(header_rows)) or None, index_col=list(range(index_columns)) or None) if index_columns > 1: - frame.index = _path_parts_as_text(path, frame, header_rows) + 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=frame, key_selection=None) + return LabeledDataRead(path=path, dataframe=df, key_selection=None) -def write_labeled_data_csv(frame: pd.DataFrame, path: Path) -> None: - """Write a wide table as DeepLabCut's human-readable CSV twin; the H5 stays authoritative. +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. """ - frame.to_csv(path) + df.to_csv(path) diff --git a/dlccore/io/labeled_data/wide/h5.py b/dlccore/io/labeled_data/wide/h5.py index 54c4818..946d530 100644 --- a/dlccore/io/labeled_data/wide/h5.py +++ b/dlccore/io/labeled_data/wide/h5.py @@ -1,3 +1,14 @@ +# +# 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, @@ -12,9 +23,9 @@ import pandas as pd -from dlc_octopus.io.errors import UnreadableFileError -from dlc_octopus.io.labeled_data.wide.table import LabeledDataRead -from dlc_octopus.io.stamp import WRITER_KEY, WRITER_VERSION_KEY, WriterStamp +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. @@ -182,14 +193,14 @@ def read_labeled_data_h5(path: Path) -> LabeledDataRead: ) -def write_labeled_data_h5(frame: pd.DataFrame, path: Path, stamp: WriterStamp) -> None: +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. """ - frame.to_hdf(path, key=CURRENT_H5_KEY, mode="w") + 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(): diff --git a/dlccore/io/labeled_data/wide/table.py b/dlccore/io/labeled_data/wide/table.py index fc924bf..23bc175 100644 --- a/dlccore/io/labeled_data/wide/table.py +++ b/dlccore/io/labeled_data/wide/table.py @@ -1,3 +1,14 @@ +# +# 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 @@ -12,12 +23,12 @@ import pandas as pd -from dlc_octopus.io.labeled_data.wide.header import LabeledDataHeader, classify_labeled_data_header -from dlc_octopus.io.labeled_data.wide.row_index import LabeledDataRowIndex, classify_labeled_data_row_index +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 dlc_octopus.io.labeled_data.wide.h5 import H5KeySelection - from dlc_octopus.io.stamp import WriterStamp + from dlccore.io.labeled_data.wide.h5 import H5KeySelection + from dlccore.io.stamp import WriterStamp @dataclass(frozen=True) @@ -45,17 +56,15 @@ class LabeledDataRead: 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_frame(read.dataframe) + return classify_wide_df(read.dataframe) -def classify_wide_frame(frame: pd.DataFrame) -> tuple[LabeledDataHeader, LabeledDataRowIndex]: +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 frame.columns) + columns = (column if isinstance(column, tuple) else (column,) for column in df.columns) return ( - classify_labeled_data_header(frame.columns.names, columns), - classify_labeled_data_row_index( - frame.index.names, frame.index, is_multi_index=isinstance(frame.index, pd.MultiIndex) - ), + 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..2cb0674 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 = [ "tables>=3.10.1" ] 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 index 821007a..60199b6 100644 --- a/tests/io/fixtures/labeled_data/README.md +++ b/tests/io/fixtures/labeled_data/README.md @@ -6,7 +6,7 @@ The fixtures are committed bytes, so nothing at test time needs a producer insta ## Written by napari-deeplabcut -Generated by a script run against a local napari-deeplabcut checkout. +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`. @@ -21,14 +21,6 @@ Generated by a script run against a local napari-deeplabcut checkout. | `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 | -Regenerate with: - -``` -"/.venv/Scripts/python.exe" tests/io/fixtures/labeled_data/generate_napari_golden_fixtures.py -``` - -The script writes into its own folder, with that checkout at the producer commit. - ## 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. @@ -43,12 +35,6 @@ The script writes into its own folder, with that checkout at the producer commit | `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 | -Regenerate with: - -``` - tests/io/fixtures/labeled_data/generate_dlc_labeled_data_fixtures.py -``` - 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 diff --git a/tests/io/labeled_data/wide/test_csv.py b/tests/io/labeled_data/wide/test_csv.py index 98fd4f0..b68f9d9 100644 --- a/tests/io/labeled_data/wide/test_csv.py +++ b/tests/io/labeled_data/wide/test_csv.py @@ -1,13 +1,24 @@ +# +# 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 -from dlc_octopus.io.errors import UnreadableFileError -from dlc_octopus.io.labeled_data.wide.csv import read_labeled_data_csv -from dlc_octopus.io.labeled_data.wide.h5 import read_labeled_data_h5 -from dlc_octopus.io.labeled_data.wide.header import LabeledDataHeaderShape -from dlc_octopus.io.labeled_data.wide.table import classify_labeled_data_read +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")) @@ -45,9 +56,9 @@ def test_the_parity_check_sees_a_changed_header(tmp_path: Path) -> None: ], ) def test_the_layout_is_read_from_the_file(filename: str, header_rows: int, index_columns: int) -> None: - frame = read_labeled_data_csv(FIXTURES_DIR / filename).dataframe + df = read_labeled_data_csv(FIXTURES_DIR / filename).dataframe - assert (frame.columns.nlevels, frame.index.nlevels) == (header_rows, index_columns) + assert (df.columns.nlevels, df.index.nlevels) == (header_rows, index_columns) def test_an_unrecognised_header_is_read_without_one(tmp_path: Path) -> None: @@ -87,9 +98,9 @@ def test_numeric_looking_path_parts_read_as_text_as_in_h5(tmp_path: Path, index_ index = pd.MultiIndex.from_tuples( [("labeled-data", "2019", "img0.png"), ("labeled-data", "007", "img1.png")], names=index_names ) - frame = pd.DataFrame([[1.0], [2.0]], index=index, columns=columns) - frame.to_hdf(tmp_path / "CollectedData_Sc.h5", key="df_with_missing", mode="w") - frame.to_csv(tmp_path / "CollectedData_Sc.csv") + 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") diff --git a/tests/io/labeled_data/wide/test_h5.py b/tests/io/labeled_data/wide/test_h5.py index 2ef2464..38941e9 100644 --- a/tests/io/labeled_data/wide/test_h5.py +++ b/tests/io/labeled_data/wide/test_h5.py @@ -1,11 +1,22 @@ +# +# 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 dlc_octopus.io.errors import UnreadableFileError -from dlc_octopus.io.labeled_data.wide.h5 import ( +from dlccore.io.errors import UnreadableFileError +from dlccore.io.labeled_data.wide.h5 import ( H5_KEY_REGISTRY, H5KeySelection, H5KeySelectionOutcome, @@ -25,8 +36,8 @@ def _wide_columns() -> pd.MultiIndex: ) -def _write(path: Path, key: str, frame: pd.DataFrame | None = None) -> Path: - (pd.DataFrame([[1.0, 2.0]]) if frame is None else frame).to_hdf(path, key=key, mode="w") +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 @@ -126,7 +137,7 @@ def test_the_fixtures_are_all_found() -> None: def test_the_equality_check_sees_a_modified_frame() -> None: - # Control: assert_frame_equal must fail on a frame differing in one value, or equality proves nothing. + # 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 @@ -189,17 +200,17 @@ def test_a_single_unrecognised_key_is_read(tmp_path: Path) -> None: def test_missing_values_are_preserved(tmp_path: Path) -> None: index = pd.MultiIndex.from_tuples([("labeled-data", "session-01", "img001.png")]) - frame = pd.DataFrame([[1.0, 2.0, float("nan"), float("nan")]], index=index, columns=_wide_columns()) + 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", frame)) + 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: - frame = pd.DataFrame(columns=_wide_columns()) + df = pd.DataFrame(columns=_wide_columns()) - result = read_labeled_data_h5(_write(tmp_path / "CollectedData_Sc.h5", "df_with_missing", frame)) + result = read_labeled_data_h5(_write(tmp_path / "CollectedData_Sc.h5", "df_with_missing", df)) assert result.dataframe.empty diff --git a/tests/io/labeled_data/wide/test_header.py b/tests/io/labeled_data/wide/test_header.py index 93761be..a758783 100644 --- a/tests/io/labeled_data/wide/test_header.py +++ b/tests/io/labeled_data/wide/test_header.py @@ -1,16 +1,27 @@ +# +# 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 dlc_octopus.io.labeled_data.model import BodypartScope -from dlc_octopus.io.labeled_data.wide.h5 import read_labeled_data_h5 -from dlc_octopus.io.labeled_data.wide.header import ( +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 dlc_octopus.io.labeled_data.wide.table import classify_labeled_data_read +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")) @@ -38,12 +49,12 @@ def _multi_animal(columns: list[tuple[str, str, str, str]]) -> LabeledDataHeader @pytest.mark.parametrize("filename", FIXTURES) def test_every_fixture_header_is_rebuilt_from_its_keypoints(filename: str) -> None: - frame = read_labeled_data_h5(FIXTURES_DIR / filename).dataframe + 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(frame.columns) + assert _rebuilt_columns(header) == list(df.columns) def test_the_rebuild_sees_a_tampered_keypoint() -> None: diff --git a/tests/io/labeled_data/wide/test_row_index.py b/tests/io/labeled_data/wide/test_row_index.py index f5f0f1e..b2ca445 100644 --- a/tests/io/labeled_data/wide/test_row_index.py +++ b/tests/io/labeled_data/wide/test_row_index.py @@ -1,17 +1,28 @@ +# +# 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 dlc_octopus.io.labeled_data.wide.h5 import read_labeled_data_h5 -from dlc_octopus.io.labeled_data.wide.row_index import ( +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 dlc_octopus.io.labeled_data.wide.table import classify_labeled_data_read +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")) @@ -19,13 +30,13 @@ @pytest.mark.parametrize("filename", FIXTURES) def test_every_fixture_row_index_is_kept_and_split(filename: str) -> None: - frame = read_labeled_data_h5(FIXTURES_DIR / filename).dataframe + 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(frame.index.names), tuple(frame.index)) + 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(frame.index) + assert len(row_index.frames) == len(df.index) def test_the_legacy_flat_index_is_flat_paths() -> None: From 87ab2adc882861da85f743b2d5dba9b09a2a3c56 Mon Sep 17 00:00:00 2001 From: C-Achard Date: Tue, 24 Nov 2026 14:54:07 +0100 Subject: [PATCH 3/6] Install the hdf5 extra in the dependency-floor job --- .github/workflows/test_package.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 From 1efecadd024e2567ce6229863a9c4e9e20397859 Mon Sep 17 00:00:00 2001 From: C-Achard Date: Tue, 24 Nov 2026 17:34:41 +0100 Subject: [PATCH 4/6] Raise the typing-extensions floor with the hdf5 extra tables 3.10.1 imports typing_extensions.Callable, added in 4.7, but allows older versions. --- pyproject.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pyproject.toml b/pyproject.toml index 2cb0674..1dafbfe 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -29,7 +29,7 @@ dependencies = [ "typing-extensions", ] optional-dependencies.all = [ "dlccore[hdf5,video]" ] -optional-dependencies.hdf5 = [ "tables>=3.10.1" ] +optional-dependencies.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" From 8f00b14e23692a138060043484655d25fc78fed4 Mon Sep 17 00:00:00 2001 From: Cyril Achard Date: Fri, 27 Nov 2026 14:34:21 +0100 Subject: [PATCH 5/6] Fix no using hdf5 pandas extras, to avoid drift in tables version --- pyproject.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pyproject.toml b/pyproject.toml index 1dafbfe..debf6c6 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -29,7 +29,7 @@ dependencies = [ "typing-extensions", ] optional-dependencies.all = [ "dlccore[hdf5,video]" ] -optional-dependencies.hdf5 = [ "tables>=3.10.1", "typing-extensions>=4.7" ] +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" From b361454d9df75a35d780e1614befe178dda2c70b Mon Sep 17 00:00:00 2001 From: Cyril Achard Date: Fri, 27 Nov 2026 14:34:49 +0100 Subject: [PATCH 6/6] Fix CSV imports with BOM or header only Recognize UTF-8 byte-order marks in headers and preserve header and index structure when a CSV contains no frames. --- dlccore/io/labeled_data/wide/csv.py | 10 ++++--- tests/io/labeled_data/wide/test_csv.py | 37 ++++++++++++++++++++++++++ 2 files changed, 44 insertions(+), 3 deletions(-) diff --git a/dlccore/io/labeled_data/wide/csv.py b/dlccore/io/labeled_data/wide/csv.py index e0a3d13..be7b769 100644 --- a/dlccore/io/labeled_data/wide/csv.py +++ b/dlccore/io/labeled_data/wide/csv.py @@ -32,13 +32,14 @@ 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. + 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 header_shape(level_names[:depth]) is not LabeledDataHeaderShape.UNRECOGNISED: + 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 @@ -50,6 +51,8 @@ def _path_parts_as_text(path: Path, df: pd.DataFrame, header_rows: int) -> pd.Mu """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, @@ -74,7 +77,8 @@ def read_labeled_data_csv(path: Path) -> LabeledDataRead: """ try: - with path.open(newline="", encoding="utf-8") as stream: + # 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))) ) diff --git a/tests/io/labeled_data/wide/test_csv.py b/tests/io/labeled_data/wide/test_csv.py index b68f9d9..b714fe8 100644 --- a/tests/io/labeled_data/wide/test_csv.py +++ b/tests/io/labeled_data/wide/test_csv.py @@ -9,6 +9,7 @@ # Licensed under GNU Lesser General Public License v3.0 # +import codecs from pathlib import Path import pandas as pd @@ -61,6 +62,42 @@ def test_the_layout_is_read_from_the_file(filename: str, header_rows: int, index 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")