diff --git a/dlccore/project/api/__init__.py b/dlccore/project/api/__init__.py index 0282b27..149f32e 100644 --- a/dlccore/project/api/__init__.py +++ b/dlccore/project/api/__init__.py @@ -15,8 +15,13 @@ from dlccore.project.content import ( FailedRead, FileFingerprint, + InspectedLabeledDataFile, + LabeledDataEntry, + ProjectLabeledData, ResourcesFileFingerprint, compare_file_fingerprints, + inspect_labeled_data_file, + read_project_labeled_data, resources_file_fingerprint, ) from dlccore.project.inspection import inspect_project, project_name @@ -27,11 +32,16 @@ "FailedRead", "FileFingerprint", "FileResourceKind", + "InspectedLabeledDataFile", + "LabeledDataEntry", + "ProjectLabeledData", "ResourcesFileFingerprint", "compare_file_fingerprints", "findings_in_scope", "helpers", + "inspect_labeled_data_file", "inspect_project", "project_name", + "read_project_labeled_data", "resources_file_fingerprint", ] diff --git a/dlccore/project/content/__init__.py b/dlccore/project/content/__init__.py index 5deb6b8..7746aa2 100644 --- a/dlccore/project/content/__init__.py +++ b/dlccore/project/content/__init__.py @@ -17,12 +17,24 @@ compare_file_fingerprints, resources_file_fingerprint, ) +from dlccore.project.content.labeled_data import ( + InspectedLabeledDataFile, + LabeledDataEntry, + ProjectLabeledData, + inspect_labeled_data_file, + read_project_labeled_data, +) from dlccore.project.content.reads import FailedRead __all__ = [ "FailedRead", "FileFingerprint", + "InspectedLabeledDataFile", + "LabeledDataEntry", + "ProjectLabeledData", "ResourcesFileFingerprint", "compare_file_fingerprints", + "inspect_labeled_data_file", + "read_project_labeled_data", "resources_file_fingerprint", ] diff --git a/dlccore/project/content/labeled_data/__init__.py b/dlccore/project/content/labeled_data/__init__.py new file mode 100644 index 0000000..1b92f06 --- /dev/null +++ b/dlccore/project/content/labeled_data/__init__.py @@ -0,0 +1,172 @@ +# +# DeepLabCut Toolbox (deeplabcut.org) +# © A. & M.W. Mathis Labs +# https://github.com/DeepLabCut/dlccore +# +# Contributors: +# https://github.com/DeepLabCut/dlccore/graphs/contributors +# +# Licensed under GNU Lesser General Public License v3.0 +# + +"""Labeled-data files, of a snapshot or at a path, read through ``dlccore.io`` with findings about each one.""" + +from __future__ import annotations + +from dataclasses import dataclass +from pathlib import Path + +from pydantic import JsonValue + +from dlccore.io import UnreadableFileError +from dlccore.io.labeled_data import LabeledDataFile, read_labeled_data +from dlccore.project.content.labeled_data.validate import validate_labeled_data_file +from dlccore.project.content.reads import FailedRead, present_files_in_scope +from dlccore.project.discovery.position import LayoutPosition, locate_in_layout +from dlccore.project.inspection import inspect_project +from dlccore.project.schemas.base.core import ProjectRelativePath, SchemaId +from dlccore.project.schemas.base.filesystem import LayoutIndex +from dlccore.project.schemas.base.finding_codes import LabeledDataFindingCode +from dlccore.project.schemas.base.findings import Finding +from dlccore.project.schemas.locations import Location, node_location +from dlccore.project.schemas.project_layout.labeled_data import HUMAN_LABELS, MACHINE_LABELS, MACHINE_LABELS_CSV +from dlccore.project.schemas.project_layout.project import PROJECT_INDEX +from dlccore.project.schemas.scope import Scope, findings_in_scope +from dlccore.project.schemas.snapshots import ProjectSnapshot +from dlccore.project.validation.results import ValidationResult + +_LABELS = frozenset({HUMAN_LABELS.schema_id, MACHINE_LABELS.schema_id, MACHINE_LABELS_CSV.schema_id}) + + +@dataclass(frozen=True) +class LabeledDataEntry: + """One labels file read through the project layer, with its layout anchor. + + Attributes: + schema_id: The layout node of the file. + project_relative_path: The path as the snapshot observed it. + data: The file as ``dlccore.io`` read it. + """ + + schema_id: SchemaId + project_relative_path: ProjectRelativePath + data: LabeledDataFile + + +@dataclass(frozen=True) +class ProjectLabeledData: + """The labels files read, those that could not be, and the snapshot with their findings merged. + + Attributes: + snapshot: The input snapshot with the findings about the files requested merged in, those read and those + not; use it, not the input, for any policy decision about them. + read: One entry per requested file that could be read. + failed: One entry per requested file that could not be read. + """ + + snapshot: ProjectSnapshot + read: tuple[LabeledDataEntry, ...] = () + failed: tuple[FailedRead, ...] = () + + +@dataclass(frozen=True) +class InspectedLabeledDataFile: + """One labels file inspected from its path, inside a project or not. + + Attributes: + position: Where the path sits in the layout, as far as it is certain. + data: The file as ``dlccore.io`` read it; ``None`` exactly when it could not be read. + findings: Every finding in scope of the file, anchored at ``position.location``. + snapshot: The project's snapshot, when ``position`` found a project root. + """ + + position: LayoutPosition + data: LabeledDataFile | None + findings: tuple[Finding, ...] + snapshot: ProjectSnapshot | None = None + + +def read_project_labeled_data( + snapshot: ProjectSnapshot, + scope: Scope, + *, + index: LayoutIndex = PROJECT_INDEX, +) -> ProjectLabeledData: + """Read every present human or machine labels file ``scope`` covers in ``snapshot``, without rediscovering. + + Each such file is in ``read`` or in ``failed``, never both. A file that cannot be read yields a + ``LABELED_DATA_UNREADABLE`` finding, carried by its ``FailedRead``; a file read yields its findings from + ``validate_labeled_data_file``. Both are merged into the returned snapshot; the input is not modified. + + Args: + snapshot: A snapshot from ``inspect_project``. + scope: The nodes whose labels files to read, each within its instance prefix; see ``Scope.covers``. + index: The layout the snapshot was observed against. + + Raises: + ValueError: If ``scope`` names a node the layout does not declare. + """ + + read: list[LabeledDataEntry] = [] + failed: list[FailedRead] = [] + about_read: list[Finding] = [] + + for node in present_files_in_scope(snapshot, scope, _LABELS & set(scope.file_schema_ids(index=index)), index=index): + at = node_location(node.schema_id, node.project_relative_path, index=index) + data, findings = _read(snapshot.project_root / node.project_relative_path, node.kind.value, at) + + if data is None: + failed.append(FailedRead(node.schema_id, node.project_relative_path, findings)) + continue + + read.append(LabeledDataEntry(node.schema_id, node.project_relative_path, data)) + about_read += findings + + findings = (*(finding for failure in failed for finding in failure.findings), *about_read) + + return ProjectLabeledData( + snapshot=snapshot.with_validation_result(ValidationResult(findings=findings)), + read=tuple(read), + failed=tuple(failed), + ) + + +def inspect_labeled_data_file(path: Path, *, index: LayoutIndex = PROJECT_INDEX) -> InspectedLabeledDataFile: + """Read one labels file from its path and report it, placing it in the layout by scanning upward. + + Inside a project, the project is inspected and the file read as ``read_project_labeled_data`` reads it, so + project-level findings in its scope are included. Outside one, the file gets the same per-file findings. + + Raises: + ValueError: If the file's name matches no labels node of the layout, or several. + """ + + position = locate_in_layout(path, index=index) + at = position.location + node = index.schemas[at["schema_id"]] + if node.schema_id not in _LABELS: + raise ValueError(f"{path.name!r} is a {node.schema_id} file, not a labels file.") + + if position.project_root is None: + data, findings = _read(path, node.kind.value, at) + return InspectedLabeledDataFile(position, data, findings) + + scope = Scope(node, within=at["instance"]) + result = read_project_labeled_data(inspect_project(position.project_root), scope, index=index) + data = next((entry.data for entry in result.read), None) + return InspectedLabeledDataFile(position, data, findings_in_scope(result.snapshot, scope), result.snapshot) + + +def _read(path: Path, resource_kind: str, at: Location) -> tuple[LabeledDataFile | None, tuple[Finding, ...]]: + """Read one labels file and return it with its findings, or ``None`` with the finding that it is unreadable.""" + + try: + data = read_labeled_data(path) + except UnreadableFileError as error: + evidence: dict[str, JsonValue] = { + "resource_kind": resource_kind, + "error_type": type(error.__cause__ or error).__name__, + "error_message": str(error), + } + return None, (Finding(code=LabeledDataFindingCode.LABELED_DATA_UNREADABLE, **at, path=path, evidence=evidence),) + return data, validate_labeled_data_file(data, at) diff --git a/dlccore/project/content/labeled_data/file.py b/dlccore/project/content/labeled_data/file.py new file mode 100644 index 0000000..ea1ec14 --- /dev/null +++ b/dlccore/project/content/labeled_data/file.py @@ -0,0 +1,142 @@ +# +# 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 +# + +"""Findings about a labeled-data file as stored, one report per code, each turning one check's fact into findings.""" + +from __future__ import annotations + +from pydantic import JsonValue + +from dlccore.io.labeled_data import Keypoint, LabeledDataFile +from dlccore.io.labeled_data._checks.file import ( + frame_absorbed_into_index_names, + frames_of_other_depth, + frames_with_unnamed_parts, + has_no_frames, + header_is_unrecognised, + keypoints_with_unrecognised_coords, + keypoints_without_the_likelihood_others_store, + legacy_h5_key, + non_numeric_columns, + row_index_is_unrecognised, + unknown_h5_key, + unread_h5_keys, +) +from dlccore.project.content.labeled_data.report import Report, finding +from dlccore.project.schemas.base.finding_codes import LabeledDataFindingCode as Code +from dlccore.project.schemas.base.findings import Finding +from dlccore.project.schemas.locations import Location + + +def keypoint_evidence(keypoint: Keypoint) -> dict[str, JsonValue]: + """A keypoint as evidence: its scorer, individual (``None`` without an individuals level) and bodypart.""" + + return {"scorer": keypoint.scorer, "individual": keypoint.individual, "bodypart": keypoint.bodypart} + + +def _multi_key(data: LabeledDataFile, at: Location) -> tuple[Finding, ...]: + selection = data.key_selection + if selection is None or not unread_h5_keys(selection): + return () + keys_found: list[JsonValue] = list(selection.keys_found) + return finding(Code.LABELED_DATA_H5_MULTI_KEY, data, at, keys_found=keys_found, selected_key=selection.selected_key) + + +def _legacy_key(data: LabeledDataFile, at: Location) -> tuple[Finding, ...]: + key = legacy_h5_key(data.key_selection) + return finding(Code.LABELED_DATA_H5_LEGACY_KEY, data, at, key=key) if key else () + + +def _unknown_key(data: LabeledDataFile, at: Location) -> tuple[Finding, ...]: + key = unknown_h5_key(data.key_selection) + return finding(Code.LABELED_DATA_H5_UNKNOWN_KEY, data, at, key=key) if key else () + + +def _header(data: LabeledDataFile, at: Location) -> tuple[Finding, ...]: + if not header_is_unrecognised(data.raw_header): + return () + level_names: list[JsonValue] = [None if name is None else str(name) for name in data.raw_header.level_names] + return finding(Code.LABELED_DATA_HEADER_UNRECOGNISED, data, at, level_names=level_names) + + +def _coords(data: LabeledDataFile, at: Location) -> tuple[Finding, ...]: + found = keypoints_with_unrecognised_coords(data.raw_header) + keypoints: list[JsonValue] = [{**keypoint_evidence(c.keypoint), "coords": list(c.coords)} for c in found] + return finding(Code.LABELED_DATA_COORDS_UNRECOGNISED, data, at, keypoints=keypoints) if found else () + + +def _partial_likelihood(data: LabeledDataFile, at: Location) -> tuple[Finding, ...]: + found = keypoints_without_the_likelihood_others_store(data.raw_header) + keypoints: list[JsonValue] = [keypoint_evidence(columns.keypoint) for columns in found] + return finding(Code.LABELED_DATA_LIKELIHOOD_PARTIAL, data, at, keypoints=keypoints) if found else () + + +def _not_numeric(data: LabeledDataFile, at: Location) -> tuple[Finding, ...]: + found = non_numeric_columns(data.to_raw_wide_df()) + columns: list[JsonValue] = [ + [str(level) for level in label] if isinstance(label, tuple) else str(label) for label in found + ] + return finding(Code.LABELED_DATA_VALUES_NOT_NUMERIC, data, at, columns=columns) if found else () + + +def _no_frames(data: LabeledDataFile, at: Location) -> tuple[Finding, ...]: + return finding(Code.LABELED_DATA_NO_FRAMES, data, at) if has_no_frames(data.raw_row_index) else () + + +def _row_index(data: LabeledDataFile, at: Location) -> tuple[Finding, ...]: + row_index = data.raw_row_index + if not row_index_is_unrecognised(row_index): + return () + first = next(entry for entry in row_index.entries if not isinstance(entry, str)) + return finding(Code.LABELED_DATA_ROW_INDEX_UNRECOGNISED, data, at, first_entry=repr(first)) + + +def _frame_rows(code: Code, rows: tuple[int, ...], data: LabeledDataFile, at: Location) -> tuple[Finding, ...]: + if not rows: + return () + first_frame: list[JsonValue] = [repr(part) for part in data.raw_row_index.frames[rows[0]]] + return finding(code, data, at, row_count=len(rows), first_frame=first_frame) + + +def _frame_depth(data: LabeledDataFile, at: Location) -> tuple[Finding, ...]: + return _frame_rows(Code.LABELED_DATA_FRAME_DEPTH, frames_of_other_depth(data.raw_row_index), data, at) + + +def _frame_part(data: LabeledDataFile, at: Location) -> tuple[Finding, ...]: + return _frame_rows(Code.LABELED_DATA_FRAME_PART_UNNAMED, frames_with_unnamed_parts(data.raw_row_index), data, at) + + +def _absorbed(data: LabeledDataFile, at: Location) -> tuple[Finding, ...]: + frame: list[JsonValue] = list(frame_absorbed_into_index_names(data.raw_row_index)) + return finding(Code.LABELED_DATA_CSV_FRAME_ABSORBED, data, at, frame=frame) if frame else () + + +def _stamp(data: LabeledDataFile, at: Location) -> tuple[Finding, ...]: + error = data.writer_stamp_error + return finding(Code.LABELED_DATA_WRITER_STAMP_MALFORMED, data, at, error_message=error) if error else () + + +# Each emits as ``emit(data: LabeledDataFile, at: Location)``. +REPORTS: tuple[Report, ...] = ( + Report(unread_h5_keys, Code.LABELED_DATA_H5_MULTI_KEY, _multi_key), + Report(legacy_h5_key, Code.LABELED_DATA_H5_LEGACY_KEY, _legacy_key), + Report(unknown_h5_key, Code.LABELED_DATA_H5_UNKNOWN_KEY, _unknown_key), + Report(header_is_unrecognised, Code.LABELED_DATA_HEADER_UNRECOGNISED, _header), + Report(keypoints_with_unrecognised_coords, Code.LABELED_DATA_COORDS_UNRECOGNISED, _coords), + Report(keypoints_without_the_likelihood_others_store, Code.LABELED_DATA_LIKELIHOOD_PARTIAL, _partial_likelihood), + Report(non_numeric_columns, Code.LABELED_DATA_VALUES_NOT_NUMERIC, _not_numeric), + Report(has_no_frames, Code.LABELED_DATA_NO_FRAMES, _no_frames), + Report(row_index_is_unrecognised, Code.LABELED_DATA_ROW_INDEX_UNRECOGNISED, _row_index), + Report(frames_of_other_depth, Code.LABELED_DATA_FRAME_DEPTH, _frame_depth), + Report(frames_with_unnamed_parts, Code.LABELED_DATA_FRAME_PART_UNNAMED, _frame_part), + Report(frame_absorbed_into_index_names, Code.LABELED_DATA_CSV_FRAME_ABSORBED, _absorbed), + Report(None, Code.LABELED_DATA_WRITER_STAMP_MALFORMED, _stamp), +) diff --git a/dlccore/project/content/labeled_data/model.py b/dlccore/project/content/labeled_data/model.py new file mode 100644 index 0000000..dd24ea0 --- /dev/null +++ b/dlccore/project/content/labeled_data/model.py @@ -0,0 +1,52 @@ +# +# 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 +# + +"""Findings about the labels a file holds, one report per code; run only on a file that has a model.""" + +from __future__ import annotations + +from pydantic import JsonValue + +from dlccore.io.labeled_data import LabeledData, LabeledDataFile +from dlccore.io.labeled_data._checks.model import ( + keypoints_with_empty_individual, + likelihood_in_human_labels, + missing_keypoints, +) +from dlccore.project.content.labeled_data.file import keypoint_evidence +from dlccore.project.content.labeled_data.report import Report, finding +from dlccore.project.schemas.base.finding_codes import LabeledDataFindingCode as Code +from dlccore.project.schemas.base.findings import Finding +from dlccore.project.schemas.locations import Location + + +def _human_likelihood(data: LabeledDataFile, labels: LabeledData, at: Location) -> tuple[Finding, ...]: + return ( + finding(Code.LABELED_DATA_HUMAN_LIKELIHOOD, data, at) if likelihood_in_human_labels(labels, data.path) else () + ) + + +def _missing(data: LabeledDataFile, labels: LabeledData, at: Location) -> tuple[Finding, ...]: + missing: list[JsonValue] = [keypoint_evidence(keypoint) for keypoint in missing_keypoints(labels)] + return finding(Code.LABELED_DATA_KEYPOINT_MISSING, data, at, missing=missing) if missing else () + + +def _empty_individual(data: LabeledDataFile, labels: LabeledData, at: Location) -> tuple[Finding, ...]: + keypoints: list[JsonValue] = [keypoint_evidence(keypoint) for keypoint in keypoints_with_empty_individual(labels)] + return finding(Code.LABELED_DATA_INDIVIDUAL_EMPTY, data, at, keypoints=keypoints) if keypoints else () + + +# Each emits as ``emit(data: LabeledDataFile, labels: LabeledData, at: Location)``. +REPORTS: tuple[Report, ...] = ( + Report(likelihood_in_human_labels, Code.LABELED_DATA_HUMAN_LIKELIHOOD, _human_likelihood), + Report(missing_keypoints, Code.LABELED_DATA_KEYPOINT_MISSING, _missing), + Report(keypoints_with_empty_individual, Code.LABELED_DATA_INDIVIDUAL_EMPTY, _empty_individual), +) diff --git a/dlccore/project/content/labeled_data/report.py b/dlccore/project/content/labeled_data/report.py new file mode 100644 index 0000000..8173b4a --- /dev/null +++ b/dlccore/project/content/labeled_data/report.py @@ -0,0 +1,55 @@ +# +# 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 +# + +"""A report: which check it reads, which code it emits, and how. Every public check has one, or is not reported.""" + +from __future__ import annotations + +from collections.abc import Callable +from dataclasses import dataclass + +from pydantic import JsonValue + +from dlccore.io.labeled_data import LabeledDataFile +from dlccore.io.labeled_data._checks.file import frames_lost_to_csv +from dlccore.project.schemas.base.finding_codes import LabeledDataFindingCode +from dlccore.project.schemas.base.findings import Finding +from dlccore.project.schemas.locations import Location + + +@dataclass(frozen=True) +class Report: + """One code's report of one check. + + Attributes: + check: The check whose fact it reports; ``None`` when it reports a fact the file exposes directly. + code: The code it emits, and no other. + emit: Returns its findings: ``emit(data, at)`` for a file report, ``emit(data, labels, at)`` for a model one. + """ + + check: Callable[..., object] | None + code: LabeledDataFindingCode + emit: Callable[..., tuple[Finding, ...]] + + +def finding(code: LabeledDataFindingCode, data: LabeledDataFile, at: Location, **evidence: JsonValue) -> tuple[Finding]: + """One finding with ``code`` about ``data``, anchored at ``at``.""" + + return (Finding(code=code, **at, path=data.path, evidence=evidence),) + + +# Checks a write acts on that the project layer never reports, because another check reports the same fact. +NOT_REPORTED: frozenset[Callable[..., object]] = frozenset( + { + # The writer's prediction; a CSV that did lose its frame reports frame_absorbed_into_index_names. + frames_lost_to_csv, + } +) diff --git a/dlccore/project/content/labeled_data/validate.py b/dlccore/project/content/labeled_data/validate.py new file mode 100644 index 0000000..4a09fe9 --- /dev/null +++ b/dlccore/project/content/labeled_data/validate.py @@ -0,0 +1,34 @@ +# +# DeepLabCut Toolbox (deeplabcut.org) +# © A. & M.W. Mathis Labs +# https://github.com/DeepLabCut/dlccore +# +# Contributors: +# https://github.com/DeepLabCut/dlccore/graphs/contributors +# +# Licensed under GNU Lesser General Public License v3.0 +# + +"""One labeled-data file's findings: the file reports, then the model reports when the file has a model.""" + +from __future__ import annotations + +from dlccore.io.labeled_data import LabeledDataFile +from dlccore.project.content.labeled_data import file, model +from dlccore.project.schemas.base.findings import Finding +from dlccore.project.schemas.locations import Location + + +def validate_labeled_data_file(data: LabeledDataFile, at: Location) -> tuple[Finding, ...]: + """Return every finding about one file that was read, anchored at ``at``. + + A file with no model gets only its file findings: those say why it has none. + """ + + findings = [finding for report in file.REPORTS for finding in report.emit(data, at)] + try: + labels = data.labeled_data + except ValueError: + return tuple(findings) + findings += [finding for report in model.REPORTS for finding in report.emit(data, labels, at)] + return tuple(findings) diff --git a/dlccore/project/schemas/base/finding_codes.py b/dlccore/project/schemas/base/finding_codes.py index 7db20f0..ff560df 100644 --- a/dlccore/project/schemas/base/finding_codes.py +++ b/dlccore/project/schemas/base/finding_codes.py @@ -237,6 +237,115 @@ class FingerprintFindingCode(FindingCode): ) +class LabeledDataFindingCode(FindingCode): + """Findings about the content of labeled-data files.""" + + LABELED_DATA_UNREADABLE = ( + "LABELED_DATA_UNREADABLE", + "A labeled-data file could not be read.", + Severity.ERROR, + ("resource_kind", "error_type", "error_message"), + ) + LABELED_DATA_H5_MULTI_KEY = ( + "LABELED_DATA_H5_MULTI_KEY", + "An H5 labels file holds several tables; one was read by declared precedence and the others were not.", + Severity.ERROR, + ("keys_found", "selected_key"), + ) + LABELED_DATA_H5_LEGACY_KEY = ( + "LABELED_DATA_H5_LEGACY_KEY", + "An H5 labels file stores its table under a key older DeepLabCut releases wrote.", + Severity.WARNING, + ("key",), + ) + LABELED_DATA_H5_UNKNOWN_KEY = ( + "LABELED_DATA_H5_UNKNOWN_KEY", + "An H5 labels file stores its table under a key no DeepLabCut release is known to write.", + Severity.WARNING, + ("key",), + ) + LABELED_DATA_HEADER_UNRECOGNISED = ( + "LABELED_DATA_HEADER_UNRECOGNISED", + "A labels file's column levels are neither of the headers DeepLabCut writes, so no labels can be read from it.", + Severity.ERROR, + ("level_names",), + ) + LABELED_DATA_COORDS_UNRECOGNISED = ( + "LABELED_DATA_COORDS_UNRECOGNISED", + "Keypoints whose coordinates are not exactly x, y and optionally likelihood, so no labels can be read from " + "the file.", + Severity.ERROR, + ("keypoints",), + ) + LABELED_DATA_LIKELIHOOD_PARTIAL = ( + "LABELED_DATA_LIKELIHOOD_PARTIAL", + "Some keypoints store a likelihood and these do not, so no labels can be read from the file.", + Severity.ERROR, + ("keypoints",), + ) + LABELED_DATA_VALUES_NOT_NUMERIC = ( + "LABELED_DATA_VALUES_NOT_NUMERIC", + "Value columns hold something other than real numbers, so no labels can be read from the file.", + Severity.ERROR, + ("columns",), + ) + LABELED_DATA_NO_FRAMES = ( + "LABELED_DATA_NO_FRAMES", + "A labels file has a header and no frames, so it holds no labels.", + Severity.WARNING, + (), + ) + LABELED_DATA_ROW_INDEX_UNRECOGNISED = ( + "LABELED_DATA_ROW_INDEX_UNRECOGNISED", + "A labels file's row index is neither frame path parts nor path strings, so no labels can be read from it.", + Severity.ERROR, + ("first_entry",), + ) + LABELED_DATA_FRAME_DEPTH = ( + "LABELED_DATA_FRAME_DEPTH", + "Frames whose path has other than three parts, so no labels can be read from the file.", + Severity.ERROR, + ("row_count", "first_frame"), + ) + LABELED_DATA_FRAME_PART_UNNAMED = ( + "LABELED_DATA_FRAME_PART_UNNAMED", + "Frames with a path part that is neither text nor an integer, so no labels can be read from the file.", + Severity.ERROR, + ("row_count", "first_frame"), + ) + LABELED_DATA_CSV_FRAME_ABSORBED = ( + "LABELED_DATA_CSV_FRAME_ABSORBED", + "A CSV labels file's first frame has no values, so a CSV read takes it as the row index's names and the " + "file reads back without that frame.", + Severity.WARNING, + ("frame",), + ) + LABELED_DATA_WRITER_STAMP_MALFORMED = ( + "LABELED_DATA_WRITER_STAMP_MALFORMED", + "A labels file carries a writer stamp that could not be read.", + Severity.NOTE, + ("error_message",), + ) + LABELED_DATA_HUMAN_LIKELIHOOD = ( + "LABELED_DATA_HUMAN_LIKELIHOOD", + "Human labels store a likelihood, which ground truth never carries.", + Severity.WARNING, + (), + ) + LABELED_DATA_KEYPOINT_MISSING = ( + "LABELED_DATA_KEYPOINT_MISSING", + "Individuals lack a bodypart another individual of the same scorer has.", + Severity.WARNING, + ("missing",), + ) + LABELED_DATA_INDIVIDUAL_EMPTY = ( + "LABELED_DATA_INDIVIDUAL_EMPTY", + "Keypoints whose individual is named with an empty string, which names no individual.", + Severity.ERROR, + ("keypoints",), + ) + + def iter_finding_codes() -> tuple[FindingCode, ...]: """Return every declared finding code, namespace by namespace.""" diff --git a/tests/io/test_boundaries.py b/tests/io/test_boundaries.py index 1aefb1b..8b30cbd 100644 --- a/tests/io/test_boundaries.py +++ b/tests/io/test_boundaries.py @@ -87,11 +87,18 @@ def _private_labeled_data_imports() -> dict[str, list[str]]: } -def test_only_io_imports_the_private_labeled_data_modules() -> None: +def test_only_io_and_content_import_the_private_labeled_data_modules() -> None: + # Content turns the checks into findings, so it is the one importer outside io found = _private_labeled_data_imports() assert found[f"{IO}.labeled_data.file"] # control: the file class reads through _wide - assert {module: names for module, names in found.items() if names and not _within(module, IO)} == {} + assert found[f"{CONTENT}.labeled_data.file"] # control: content reports the file checks + outside = { + module: names + for module, names in found.items() + if names and not (_within(module, IO) or _within(module, CONTENT)) + } + assert outside == {} def _may_import_from_io(module: str, name: str) -> bool: diff --git a/tests/project/content/test_inspect_labeled_data_file.py b/tests/project/content/test_inspect_labeled_data_file.py new file mode 100644 index 0000000..59673c2 --- /dev/null +++ b/tests/project/content/test_inspect_labeled_data_file.py @@ -0,0 +1,75 @@ +# +# 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 shutil +from pathlib import Path + +import pandas as pd + +from dlccore.project.api import inspect_labeled_data_file +from dlccore.project.schemas.base.finding_codes import LabeledDataFindingCode as Code +from dlccore.project.schemas.base.findings import Reach + +FIXTURES_DIR = Path(__file__).parents[2] / "io" / "fixtures" / "labeled_data" +NAME = "CollectedData_test-scorer.h5" + + +def _uninterpretable(path: Path) -> Path: + path.parent.mkdir(parents=True, exist_ok=True) + frame = pd.DataFrame([[1.0, 2.0]], columns=["nose_x", "nose_y"], index=["labeled-data/session-01/img000.png"]) + frame.to_hdf(path, key="df_with_missing", mode="w") + return path + + +def test_a_file_and_its_copy_outside_the_project_get_the_same_findings(valid_project: Path, tmp_path: Path) -> None: + inside = _uninterpretable(valid_project / "labeled-data" / "session-01" / NAME) + copy = tmp_path / "backup" / "labeled-data" / "session-01" / NAME + copy.parent.mkdir(parents=True) + shutil.copy(inside, copy) + + found_inside, found_copy = inspect_labeled_data_file(inside), inspect_labeled_data_file(copy) + + assert found_inside.snapshot is not None + assert found_copy.snapshot is None + assert [(f.code, f.reach, f.instance) for f in found_copy.findings] == [ + (f.code, f.reach, f.instance) for f in found_inside.findings + ] + assert [f.code for f in found_copy.findings] == [Code.LABELED_DATA_HEADER_UNRECOGNISED] # control: not vacuous + + +def test_a_detached_copy_gets_the_same_codes_and_its_guess_never_reaches_a_finding(tmp_path: Path) -> None: + path = _uninterpretable(tmp_path / "Downloads" / "session-01" / NAME) + + inspected = inspect_labeled_data_file(path) + + assert [f.code for f in inspected.findings] == [Code.LABELED_DATA_HEADER_UNRECOGNISED] + assert {(f.reach, f.instance) for f in inspected.findings} == {(Reach.UNROOTED, (NAME,))} + assert inspected.position.detached # control: there was a guess to leak + + +def test_an_unreadable_file_outside_a_project_has_no_data_and_says_why(tmp_path: Path) -> None: + path = tmp_path / NAME + path.write_bytes(b"not an HDF5 file") + + inspected = inspect_labeled_data_file(path) + + assert inspected.data is None + assert [f.code for f in inspected.findings] == [Code.LABELED_DATA_UNREADABLE] + + +def test_a_readable_file_outside_a_project_is_returned(tmp_path: Path) -> None: + path = tmp_path / NAME + shutil.copy(FIXTURES_DIR / "single_animal_human.h5", path) + + inspected = inspect_labeled_data_file(path) + + assert inspected.data is not None + assert inspected.findings == () diff --git a/tests/project/content/test_labeled_data_engine.py b/tests/project/content/test_labeled_data_engine.py new file mode 100644 index 0000000..ccd926c --- /dev/null +++ b/tests/project/content/test_labeled_data_engine.py @@ -0,0 +1,217 @@ +# +# 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 inspect +import shutil +from collections.abc import Callable +from pathlib import Path + +import pandas as pd +import pytest + +from dlccore.io.labeled_data import LabeledData, LabeledDataFile, read_labeled_data +from dlccore.io.labeled_data._checks import file as file_checks +from dlccore.io.labeled_data._checks import model as model_checks +from dlccore.project.api import findings_in_scope, inspect_project +from dlccore.project.content import read_project_labeled_data +from dlccore.project.content.labeled_data import file, model +from dlccore.project.content.labeled_data.report import NOT_REPORTED, Report +from dlccore.project.content.labeled_data.validate import validate_labeled_data_file +from dlccore.project.schemas.base.finding_codes import LabeledDataFindingCode +from dlccore.project.schemas.base.finding_codes import LabeledDataFindingCode as Code +from dlccore.project.schemas.base.findings import Finding +from dlccore.project.schemas.locations import Location, node_location +from dlccore.project.schemas.project_layout.labeled_data import HUMAN_LABELS, LABELED_DATASET +from dlccore.project.schemas.scope import Scope + +FIXTURES_DIR = Path(__file__).parents[2] / "io" / "fixtures" / "labeled_data" +HUMAN_H5 = "CollectedData_test-scorer.h5" +STAND_IN = LabeledDataFindingCode.LABELED_DATA_UNREADABLE # any declared code no report emits + + +def _project_with(project: Path, write: Callable[[Path], None]) -> Path: + folder = project / "labeled-data" / "session-01" + folder.mkdir() + write(folder / HUMAN_H5) + return project + + +def _readable(path: Path) -> None: + shutil.copy(FIXTURES_DIR / "single_animal_human.h5", path) + + +def _without_model(path: Path) -> None: + frame = pd.DataFrame([[1.0, 2.0]], columns=["nose_x", "nose_y"], index=["labeled-data/session-01/img000.png"]) + frame.to_hdf(path, key="df_with_missing", mode="w") + + +def _stand_in(at: Location, data: LabeledDataFile) -> tuple[Finding, ...]: + evidence = {"resource_kind": "stand_in", "error_type": "none", "error_message": str(data.path.name)} + return (Finding(code=STAND_IN, **at, path=data.path, evidence=evidence),) + + +def _codes(project: Path) -> list[str]: + result = read_project_labeled_data(inspect_project(project), Scope(LABELED_DATASET)) + scope = Scope(HUMAN_LABELS, within=("labeled-data", "session-01", HUMAN_H5)) + return [finding.evidence["resource_kind"] for finding in findings_in_scope(result.snapshot, scope)] + + +@pytest.mark.parametrize( + ("write", "model_runs"), [(_readable, True), (_without_model, False)], ids=["model", "no_model"] +) +def test_every_file_read_is_reported_and_only_a_file_with_a_model_gets_model_reports( + valid_project: Path, monkeypatch: pytest.MonkeyPatch, write: Callable[[Path], None], *, model_runs: bool +) -> None: + def file_report(data: LabeledDataFile, at: Location) -> tuple[Finding, ...]: + return _stand_in(at, data) + + def model_report(data: LabeledDataFile, labels: LabeledData, at: Location) -> tuple[Finding, ...]: + assert labels.to_arrays().keypoints + return _stand_in(at, data) + + monkeypatch.setattr(file, "REPORTS", (Report(file_checks.unread_h5_keys, STAND_IN, file_report),)) + monkeypatch.setattr(model, "REPORTS", (Report(model_checks.missing_keypoints, STAND_IN, model_report),)) + + assert _codes(_project_with(valid_project, write)) == ["stand_in"] * (2 if model_runs else 1) + + +def test_a_file_a_deeplabcut_writer_produced_gets_no_finding(valid_project: Path) -> None: + assert _codes(_project_with(valid_project, _readable)) == [] + + +def _public_checks() -> list[Callable[..., object]]: + return [ + function + for module in (file_checks, model_checks) + for name, function in inspect.getmembers(module, inspect.isfunction) + if function.__module__ == module.__name__ and not name.startswith("_") + ] + + +def test_the_public_checks_are_found() -> None: + # Control: an empty list would let the completeness test below pass by checking nothing. + assert {file_checks.unread_h5_keys, model_checks.missing_keypoints} <= set(_public_checks()) + + +def test_every_check_is_reported_by_exactly_one_code() -> None: + reports = (*file.REPORTS, *model.REPORTS) + reported = [report.check for report in reports] + unreported = [check.__name__ for check in _public_checks() if check not in {*reported, *NOT_REPORTED}] + codes = [report.code for report in reports] + shared = [check.__name__ for check in set(reported) if reported.count(check) > 1] + shared += [str(code) for code in set(codes) if codes.count(code) > 1] + + assert (unreported, shared) == ([], []) + + +def test_a_check_is_either_reported_or_listed_as_not_reported_never_both() -> None: + assert {report.check for report in (*file.REPORTS, *model.REPORTS)} & NOT_REPORTED == set() + + +SINGLE = ["scorer", "bodyparts", "coords"] +MULTI = ["scorer", "individuals", "bodyparts", "coords"] +ROWS = pd.MultiIndex.from_tuples([("labeled-data", "s1", "img0.png"), ("labeled-data", "s1", "img1.png")]) + + +def _h5(path: Path, frame: pd.DataFrame, key: str = "df_with_missing") -> None: + frame.to_hdf(path, key=key, mode="w") + + +def _frame( + columns: list[tuple[str, ...]], *, levels: list[str] = SINGLE, index: object = ROWS, value: object = 1.0 +) -> pd.DataFrame: + header = pd.MultiIndex.from_tuples(columns, names=levels) + return pd.DataFrame([[value] * len(columns)] * len(index), index=index, columns=header) # type: ignore[arg-type] + + +XY = [("Sc", "nose", "x"), ("Sc", "nose", "y")] + +CASES: list[tuple[str, Callable[[Path], None], LabeledDataFindingCode]] = [ + ("multi_key", lambda p: shutil.copy(FIXTURES_DIR / "ambiguous_multi_key.h5", p), Code.LABELED_DATA_H5_MULTI_KEY), + ("legacy_key", lambda p: _h5(p, _frame(XY), key="keypoints"), Code.LABELED_DATA_H5_LEGACY_KEY), + ("unknown_key", lambda p: _h5(p, _frame(XY), key="labels"), Code.LABELED_DATA_H5_UNKNOWN_KEY), + ("coords", lambda p: _h5(p, _frame([*XY, ("Sc", "nose", "z")])), Code.LABELED_DATA_COORDS_UNRECOGNISED), + ( + "partial_likelihood", + lambda p: _h5(p, _frame([*XY, ("Sc", "nose", "likelihood"), ("Sc", "tail", "x"), ("Sc", "tail", "y")])), + Code.LABELED_DATA_LIKELIHOOD_PARTIAL, + ), + ("not_numeric", lambda p: _h5(p, _frame(XY, value="a")), Code.LABELED_DATA_VALUES_NOT_NUMERIC), + ("row_index", lambda p: _h5(p, _frame(XY, index=pd.Index([0, 1]))), Code.LABELED_DATA_ROW_INDEX_UNRECOGNISED), + ( + "frame_depth", + lambda p: _h5(p, _frame(XY, index=pd.MultiIndex.from_tuples([("s1", "img0.png"), ("s1", "img1.png")]))), + Code.LABELED_DATA_FRAME_DEPTH, + ), + ( + "frame_part", + lambda p: _h5(p, _frame(XY, index=pd.MultiIndex.from_tuples([("labeled-data", 1.5, "a.png")]))), + Code.LABELED_DATA_FRAME_PART_UNNAMED, + ), + ( + "empty_individual", + lambda p: _h5(p, _frame([("Sc", "", "nose", "x"), ("Sc", "", "nose", "y")], levels=MULTI)), + Code.LABELED_DATA_INDIVIDUAL_EMPTY, + ), +] + + +@pytest.mark.parametrize(("write", "code"), [(write, code) for _id, write, code in CASES], ids=[c[0] for c in CASES]) +def test_each_condition_is_reported_by_its_code_and_no_other( + tmp_path: Path, write: Callable[[Path], None], code: LabeledDataFindingCode +) -> None: + path = tmp_path / "CollectedData_Sc.h5" + write(path) + at = node_location(HUMAN_LABELS.schema_id, Path("labeled-data", "s1", path.name)) + + findings = validate_labeled_data_file(read_labeled_data(path), at) + + assert [finding.code for finding in findings] == [code] + assert set(findings[0].evidence) == set(code.evidence_keys) + + +def test_every_code_reported_in_this_package_is_tested() -> None: + # The six codes the read-through-Octopus tests flip are not repeated here. + tested = {code for _id, _write, code in CASES} + flipped = { + Code.LABELED_DATA_HEADER_UNRECOGNISED, + Code.LABELED_DATA_NO_FRAMES, + Code.LABELED_DATA_WRITER_STAMP_MALFORMED, + Code.LABELED_DATA_HUMAN_LIKELIHOOD, + Code.LABELED_DATA_KEYPOINT_MISSING, + Code.LABELED_DATA_CSV_FRAME_ABSORBED, + } + + assert {report.code for report in (*file.REPORTS, *model.REPORTS)} == tested | flipped + + +@pytest.mark.xfail( + reason="not every way the model can fail to build is a file check: a bodypart level that is not text passes " + "every check, the model raises, and validate_labeled_data_file returns no finding saying why", + raises=AssertionError, + strict=True, +) +def test_a_file_whose_model_cannot_be_built_has_a_file_check_saying_why(tmp_path: Path) -> None: + stored = pd.read_hdf(FIXTURES_DIR / "single_animal_human.h5") + numbered = {name: i for i, name in enumerate(stored.columns.get_level_values("bodyparts").unique())} + stored.columns = pd.MultiIndex.from_tuples( + [(scorer, numbered[bodypart], coord) for scorer, bodypart, coord in stored.columns], + names=stored.columns.names, + ) + path = tmp_path / "CollectedData_Sc.h5" + stored.to_hdf(path, key="df_with_missing", mode="w") + data = read_labeled_data(path) + with pytest.raises(ValueError, match="bodypart"): # control: the model cannot be built + _ = data.labeled_data + + at = node_location(HUMAN_LABELS.schema_id, Path("labeled-data", "s1", path.name)) + + assert validate_labeled_data_file(data, at) diff --git a/tests/project/content/test_project_labeled_data.py b/tests/project/content/test_project_labeled_data.py new file mode 100644 index 0000000..5874ca6 --- /dev/null +++ b/tests/project/content/test_project_labeled_data.py @@ -0,0 +1,344 @@ +# +# 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 shutil +from collections.abc import Callable +from pathlib import Path + +import numpy as np +import pandas as pd +import pytest +import tables + +from dlccore.io.labeled_data import LabeledData, read_labeled_data, write_labeled_data +from dlccore.io.stamp import WRITER_VERSION_KEY +from dlccore.project.api import findings_in_scope, inspect_project +from dlccore.project.content import ProjectLabeledData, read_project_labeled_data +from dlccore.project.schemas.base.finding_codes import LabeledDataFindingCode, Severity +from dlccore.project.schemas.base.findings import Reach +from dlccore.project.schemas.project_layout.labeled_data import HUMAN_LABELS, LABELED_DATASET +from dlccore.project.schemas.project_layout.videos import VIDEOS +from dlccore.project.schemas.scope import Scope +from dlccore.project.schemas.snapshots import ProjectSnapshot + +FIXTURES_DIR = Path(__file__).parents[2] / "io" / "fixtures" / "labeled_data" +UNREADABLE = LabeledDataFindingCode.LABELED_DATA_UNREADABLE +HUMAN_H5 = "CollectedData_test-scorer.h5" +HUMAN_CSV = "CollectedData_test-scorer.csv" +MACHINE_H5 = "machinelabels-iter0.h5" + + +def _session(project: Path, name: str = "session-01") -> Path: + folder = project / "labeled-data" / name + folder.mkdir() + shutil.copy(FIXTURES_DIR / "single_animal_legacy_index_dlc.h5", folder / HUMAN_H5) + shutil.copy(FIXTURES_DIR / "single_animal_legacy_index_dlc.csv", folder / HUMAN_CSV) + shutil.copy(FIXTURES_DIR / "single_animal_machine.h5", folder / MACHINE_H5) + (folder / "img000.png").write_bytes(b"not read: a frame, not labels") + return folder + + +def _uninterpretable(path: Path) -> None: + frame = pd.DataFrame([[1.0, 2.0]], columns=["nose_x", "nose_y"], index=["labeled-data/session-01/img000.png"]) + frame.to_hdf(path, key="df_with_missing", mode="w") + + +def _names(result: ProjectLabeledData) -> tuple[list[str], list[str]]: + return ( + sorted(entry.project_relative_path.name for entry in result.read), + sorted(failure.project_relative_path.name for failure in result.failed), + ) + + +def test_every_present_labels_file_in_scope_is_read_and_nothing_else(valid_project: Path) -> None: + _session(valid_project) + snapshot = inspect_project(valid_project) + + result = read_project_labeled_data(snapshot, Scope(LABELED_DATASET)) + + assert sorted((entry.schema_id, entry.project_relative_path.name) for entry in result.read) == [ + ("dlc.labeled_data.human_labels", HUMAN_CSV), + ("dlc.labeled_data.human_labels", HUMAN_H5), + ("dlc.labeled_data.machine_labels", MACHINE_H5), + ] + assert result.failed == () + assert result.snapshot == snapshot + for entry in result.read: + direct = read_labeled_data(valid_project / entry.project_relative_path) + assert (entry.data.keypoints, entry.data.frames) == (direct.keypoints, direct.frames) + + +def test_an_unreadable_file_is_one_failed_read_with_a_merged_finding_and_the_rest_are_read( + valid_project: Path, +) -> None: + (_session(valid_project) / HUMAN_H5).write_bytes(b"not an hdf5 file") + snapshot = inspect_project(valid_project) + + result = read_project_labeled_data(snapshot, Scope(LABELED_DATASET)) + + assert _names(result) == ([HUMAN_CSV, MACHINE_H5], [HUMAN_H5]) + (failure,) = result.failed + (finding,) = failure.findings + assert failure.project_relative_path == Path("labeled-data", "session-01", HUMAN_H5) + assert (finding.code, finding.severity, finding.reach, finding.instance) == ( + UNREADABLE, + Severity.ERROR, + Reach.ONE_OF, + ("labeled-data", "session-01", HUMAN_H5), + ) + assert finding.path == valid_project / "labeled-data" / "session-01" / HUMAN_H5 + assert finding.evidence["resource_kind"] == "human_labels" + assert finding.evidence["error_type"] == "HDF5ExtError" + assert HUMAN_H5 in finding.evidence["error_message"] + assert result.snapshot.findings == (*snapshot.findings, finding) + + +def test_a_labels_file_with_an_upper_case_suffix_is_read_with_the_rest(valid_project: Path) -> None: + folder = _session(valid_project) + upper = (folder / HUMAN_H5).rename(folder / f"{Path(HUMAN_H5).stem}.H5") + snapshot = inspect_project(valid_project) + + result = read_project_labeled_data(snapshot, Scope(LABELED_DATASET)) + + assert _names(result) == (sorted([HUMAN_CSV, upper.name, MACHINE_H5]), []) + (entry,) = [entry for entry in result.read if entry.project_relative_path.name == upper.name] + assert entry.schema_id == HUMAN_LABELS.schema_id + assert entry.data.keypoints is not None + + +def test_the_merged_finding_is_in_the_returned_snapshot_only(valid_project: Path) -> None: + (_session(valid_project) / HUMAN_H5).write_bytes(b"not an hdf5 file") + snapshot = inspect_project(valid_project) + file_scope = Scope(HUMAN_LABELS, within=("labeled-data", "session-01", HUMAN_H5)) + + result = read_project_labeled_data(snapshot, Scope(LABELED_DATASET)) + + assert UNREADABLE in [finding.code for finding in findings_in_scope(result.snapshot, file_scope)] + assert UNREADABLE not in [finding.code for finding in findings_in_scope(snapshot, file_scope)] + + +def test_an_uninterpretable_file_is_read_and_reported_not_failed(valid_project: Path) -> None: + _uninterpretable(_session(valid_project) / HUMAN_H5) + snapshot = inspect_project(valid_project) + + result = read_project_labeled_data(snapshot, Scope(LABELED_DATASET)) + + (entry,) = [entry for entry in result.read if entry.project_relative_path.name == HUMAN_H5] + assert entry.data.keypoints is None + assert entry.data.frames is not None + assert result.failed == () + assert _human_labels_findings(valid_project) == [LabeledDataFindingCode.LABELED_DATA_HEADER_UNRECOGNISED] + + +def test_a_scope_within_one_dataset_reads_that_dataset_only(valid_project: Path) -> None: + _session(valid_project, "session-01") + _session(valid_project, "session-02") + snapshot = inspect_project(valid_project) + assert len(read_project_labeled_data(snapshot, Scope(LABELED_DATASET)).read) == 6 # control: both are read + + result = read_project_labeled_data(snapshot, Scope(LABELED_DATASET, within=("labeled-data", "session-02"))) + + assert {entry.project_relative_path.parent.name for entry in result.read} == {"session-02"} + assert len(result.read) == 3 + + +def test_a_scope_holding_no_labels_files_reads_nothing(valid_project: Path) -> None: + _session(valid_project) + snapshot = inspect_project(valid_project) + + result = read_project_labeled_data(snapshot, Scope(VIDEOS)) + + assert (result.read, result.failed, result.snapshot) == ((), (), snapshot) + + +def test_a_node_the_layout_does_not_declare_is_refused(valid_project: Path) -> None: + impostor = HUMAN_LABELS.model_copy(update={"description": "not the layout's own"}) + + with pytest.raises(ValueError, match="does not declare"): + read_project_labeled_data(inspect_project(valid_project), Scope(impostor)) + + +def test_the_public_api_reexports_labeled_data_reading() -> None: + import dlccore.project.api as api + import dlccore.project.content as content + + assert (api.read_project_labeled_data, api.ProjectLabeledData, api.LabeledDataEntry, api.FailedRead) == ( + content.read_project_labeled_data, + content.ProjectLabeledData, + content.LabeledDataEntry, + content.FailedRead, + ) + + +def test_an_uninterpretable_labels_file_read_through_octopus_is_reported(valid_project: Path) -> None: + _uninterpretable(_session(valid_project) / HUMAN_H5) + + result = read_project_labeled_data(inspect_project(valid_project), Scope(LABELED_DATASET)) + + file_scope = Scope(HUMAN_LABELS, within=("labeled-data", "session-01", HUMAN_H5)) + codes = [finding.code for finding in findings_in_scope(result.snapshot, file_scope)] + assert [code for code in codes if code is not UNREADABLE] + + +def _without_frames(path: Path) -> pd.DataFrame: + columns = pd.MultiIndex.from_product( + [["test-scorer"], ["nose"], ["x", "y"]], names=["scorer", "bodyparts", "coords"] + ) + frame = pd.DataFrame([], columns=columns, index=pd.MultiIndex.from_tuples([], names=[None] * 3), dtype=float) + frame.to_hdf(path, key="df_with_missing", mode="w") + return frame + + +def test_a_labels_file_without_frames_is_read_through_octopus_as_found(valid_project: Path) -> None: + # DeepLabCut v3.0.2 and napari-deeplabcut v0.4.0 read such a file; only the model is refused. + path = _session(valid_project) / HUMAN_H5 + stored = _without_frames(path) + + result = read_project_labeled_data(inspect_project(valid_project), Scope(LABELED_DATASET)) + + (entry,) = [entry for entry in result.read if entry.project_relative_path.name == HUMAN_H5] + pd.testing.assert_frame_equal(entry.data.to_raw_wide_df(), stored) + with pytest.raises(ValueError, match="no frames"): + _ = entry.data.labeled_data + + +def test_a_labels_file_without_frames_read_through_octopus_is_reported(valid_project: Path) -> None: + _without_frames(_session(valid_project) / HUMAN_H5) + + result = read_project_labeled_data(inspect_project(valid_project), Scope(LABELED_DATASET)) + + file_scope = Scope(HUMAN_LABELS, within=("labeled-data", "session-01", HUMAN_H5)) + codes = [finding.code for finding in findings_in_scope(result.snapshot, file_scope)] + assert [code for code in codes if code is not UNREADABLE] + + +def test_a_labels_file_with_a_malformed_writer_stamp_read_through_octopus_is_reported(valid_project: Path) -> None: + path = _session(valid_project) / HUMAN_H5 + table = read_labeled_data(path).labeled_data + path.unlink() + write_labeled_data(table, path, replaces=None) + with tables.open_file(str(path), mode="a") as h5: + h5.get_node("/df_with_missing")._v_attrs[WRITER_VERSION_KEY] = 1 + + result = read_project_labeled_data(inspect_project(valid_project), Scope(LABELED_DATASET)) + + assert HUMAN_H5 in [entry.project_relative_path.name for entry in result.read] + file_scope = Scope(HUMAN_LABELS, within=("labeled-data", "session-01", HUMAN_H5)) + codes = [finding.code for finding in findings_in_scope(result.snapshot, file_scope)] + assert [code for code in codes if code is not UNREADABLE] + + +def _human_labels_findings(project: Path, name: str = HUMAN_H5) -> list[LabeledDataFindingCode]: + result = read_project_labeled_data(inspect_project(project), Scope(LABELED_DATASET)) + + assert name in [entry.project_relative_path.name for entry in result.read] + file_scope = Scope(HUMAN_LABELS, within=("labeled-data", "session-01", name)) + codes = [finding.code for finding in findings_in_scope(result.snapshot, file_scope)] + return [code for code in codes if code is not UNREADABLE] + + +def test_human_labels_carrying_a_likelihood_read_through_octopus_are_reported(valid_project: Path) -> None: + path = _session(valid_project) / HUMAN_H5 + shutil.copy(FIXTURES_DIR / "single_animal_machine.h5", path) + assert read_labeled_data(path).labeled_data.to_arrays().likelihood is not None + + assert _human_labels_findings(valid_project) + + +def test_a_missing_keypoint_pair_read_through_octopus_is_reported(valid_project: Path) -> None: + path = _session(valid_project) / HUMAN_H5 + frame = pd.read_hdf(FIXTURES_DIR / "multi_animal_human.h5") + pair = (frame.columns.get_level_values("individuals") == "animalB") & ( + frame.columns.get_level_values("bodyparts") == "tailbase" + ) + frame.loc[:, ~pair].to_hdf(path, key="df_with_missing", mode="w") + assert len(read_labeled_data(path).keypoints) == 3 + + assert _human_labels_findings(valid_project) + + +def test_a_csv_twin_missing_a_frame_of_its_h5_read_through_octopus_is_reported(valid_project: Path) -> None: + path = _session(valid_project) / HUMAN_H5 + long = read_labeled_data(path).labeled_data.to_long_df() + long.loc[long["frame_index"] == 0, ["x", "y"]] = np.nan + with pytest.warns(UserWarning, match="reads back without it"): + write_labeled_data(LabeledData.from_long_df(long), path, replaces=read_labeled_data(path).stat) + assert len(read_labeled_data(path.with_name(HUMAN_CSV)).frames) == long["frame_index"].nunique() - 1 + + assert _human_labels_findings(valid_project, HUMAN_CSV) + + +def _flat_row_index(path: Path) -> None: + shutil.copy(FIXTURES_DIR / "single_animal_human_legacy_index.h5", path) + + +def _integer_frame_part(path: Path) -> None: + frame = pd.read_hdf(FIXTURES_DIR / "single_animal_human.h5") + frame.index = pd.MultiIndex.from_tuples([(folder, 2019, image) for folder, _, image in frame.index]) + frame.to_hdf(path, key="df_with_missing", mode="w") + + +def _codes_at(snapshot: ProjectSnapshot, dataset: str) -> list[LabeledDataFindingCode]: + file_scope = Scope(HUMAN_LABELS, within=("labeled-data", dataset, HUMAN_H5)) + return sorted(finding.code for finding in findings_in_scope(snapshot, file_scope)) + + +@pytest.mark.xfail( + reason="normalisation changes are to surface as findings at FULL depth (octopus-contracts.md, 'Normalisation is " + "allowed only at FULL depth'); deferred past PR E2 (decided 2026-10-20): a file the model reads only after " + "normalising it reports nothing the same labels in DeepLabCut's current form do not", + strict=True, + raises=AssertionError, +) +@pytest.mark.parametrize("legacy", [_flat_row_index, _integer_frame_part], ids=["flat_row_index", "integer_part"]) +def test_a_normalisation_on_read_through_octopus_is_reported( + valid_project: Path, legacy: Callable[[Path], None] +) -> None: + found = _session(valid_project, "session-01") / HUMAN_H5 + legacy(found) + current = _session(valid_project, "session-02") / HUMAN_H5 + current.unlink() + write_labeled_data(read_labeled_data(found).labeled_data, current, replaces=None) + + result = read_project_labeled_data(inspect_project(valid_project), Scope(LABELED_DATASET)) + + assert _codes_at(result.snapshot, "session-01") != _codes_at(result.snapshot, "session-02") + + +@pytest.mark.xfail( + reason="an infinite coordinate has no meaning in a labels file and is always reported at FULL depth (design, " + "canonical data model, decided 2026-10-14); no check or code reports it yet", + strict=True, + raises=AssertionError, +) +def test_an_infinite_coordinate_read_through_octopus_is_reported(valid_project: Path) -> None: + path = _session(valid_project) / HUMAN_H5 + frame = pd.read_hdf(path) + frame.iloc[0, 0] = np.inf + frame.to_hdf(path, key="df_with_missing", mode="w") + + assert _human_labels_findings(valid_project) + + +@pytest.mark.xfail( + reason="whether a frame's first path part is labeled-data is a project rule, reported by Octopus, never " + "checked by the model (design, canonical data model, decided 2026-10-16); no check or code reports it yet", + strict=True, + raises=AssertionError, +) +def test_a_frame_outside_labeled_data_read_through_octopus_is_reported(valid_project: Path) -> None: + path = _session(valid_project) / HUMAN_H5 + frame = pd.read_hdf(path) + frame.index = [entry.replace("labeled-data", "images", 1) for entry in frame.index] + frame.to_hdf(path, key="df_with_missing", mode="w") + assert read_labeled_data(path).labeled_data # control: the file still has a model + + assert _human_labels_findings(valid_project) diff --git a/tests/project/discovery/test_position.py b/tests/project/discovery/test_position.py index e951958..702265e 100644 --- a/tests/project/discovery/test_position.py +++ b/tests/project/discovery/test_position.py @@ -13,9 +13,12 @@ import pytest +from dlccore.project.api import inspect_project from dlccore.project.discovery.position import CandidateNode, locate_in_layout -from dlccore.project.schemas.base.findings import Reach +from dlccore.project.schemas.base.finding_codes import LabeledDataFindingCode +from dlccore.project.schemas.base.findings import Finding, Reach from dlccore.project.schemas.project_layout.labeled_data import HUMAN_LABELS, LABELED_DATASET +from dlccore.project.validation.results import ValidationResult NAME = "CollectedData_Sc.h5" INSTANCE = ("labeled-data", "Sample1", NAME) @@ -53,3 +56,21 @@ def test_labeled_data_spelled_otherwise_is_not_trusted(tmp_path: Path) -> None: def test_a_name_no_file_node_matches_is_refused(tmp_path: Path) -> None: with pytest.raises(ValueError, match="matches 0 file nodes"): locate_in_layout(tmp_path / "labels.h5") + + +def test_a_snapshot_refuses_an_unrooted_finding(valid_project: Path) -> None: + snapshot = inspect_project(valid_project) + evidence = {"resource_kind": "human_labels", "error_type": "OSError", "error_message": "unreadable"} + finding = Finding( + code=LabeledDataFindingCode.LABELED_DATA_UNREADABLE, + schema_id=HUMAN_LABELS.schema_id, + reach=Reach.UNROOTED, + instance=(NAME,), + evidence=evidence, + ) + + with pytest.raises(ValueError, match="UNROOTED"): + snapshot.with_validation_result(ValidationResult(findings=(finding,))) + # Control: the same finding anchored in the project is accepted. + rooted = finding.model_copy(update={"reach": Reach.ONE_OF, "instance": INSTANCE}) + assert snapshot.with_validation_result(ValidationResult(findings=(rooted,))).findings[-1] == rooted diff --git a/tests/project/schemas/test_finding_codes.py b/tests/project/schemas/test_finding_codes.py index f080831..c496f56 100644 --- a/tests/project/schemas/test_finding_codes.py +++ b/tests/project/schemas/test_finding_codes.py @@ -22,6 +22,7 @@ ConfiguredVideoFindingCode, FindingCode, FingerprintFindingCode, + LabeledDataFindingCode, Severity, StructureFindingCode, iter_finding_codes, @@ -209,6 +210,7 @@ def test_the_finding_code_catalogue_is_closed() -> None: ConfigFindingCode, ConfiguredVideoFindingCode, FingerprintFindingCode, + LabeledDataFindingCode, }