diff --git a/dlccore/project/api/__init__.py b/dlccore/project/api/__init__.py new file mode 100644 index 0000000..4e5e5e7 --- /dev/null +++ b/dlccore/project/api/__init__.py @@ -0,0 +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 +# + +"""Public entry points of ``dlccore.project``; consumer helpers are in ``api.helpers``. Re-exports only.""" + +from dlccore.project.api import helpers +from dlccore.project.schemas.base.resources import FileResourceKind +from dlccore.project.schemas.scope import findings_in_scope + +__all__ = [ + "FileResourceKind", + "findings_in_scope", + "helpers", +] diff --git a/dlccore/project/api/helpers.py b/dlccore/project/api/helpers.py new file mode 100644 index 0000000..cb3cff6 --- /dev/null +++ b/dlccore/project/api/helpers.py @@ -0,0 +1,17 @@ +# +# 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 +# + +"""What a consumer composes with the entry points in ``dlccore.project.api``: scopes and its own finding policy.""" + +from dlccore.project.policy import get_blocking_findings, unhandled +from dlccore.project.schemas.scope import Scope + +__all__ = ["Scope", "get_blocking_findings", "unhandled"] diff --git a/dlccore/project/discovery/position.py b/dlccore/project/discovery/position.py new file mode 100644 index 0000000..ab33126 --- /dev/null +++ b/dlccore/project/discovery/position.py @@ -0,0 +1,113 @@ +# +# 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 +# + +"""Where a path outside a known project sits in the layout, scanned upward from the path. + +The anchor holds only what is certain: a segment counts when the chain above it reaches a directory with an exact +layout name, or a project root holding its required files. A segment that fits a node by position only is a +``CandidateNode``: returned beside the position, never in a finding. Reads names and the root's required files only. +""" + +from __future__ import annotations + +from dataclasses import dataclass +from pathlib import Path + +from dlccore.project.schemas.base.core import SchemaId +from dlccore.project.schemas.base.filesystem import FileSchema, LayoutIndex, NodeSchema +from dlccore.project.schemas.base.findings import Reach +from dlccore.project.schemas.locations import Location, node_location +from dlccore.project.schemas.project_layout.project import PROJECT_INDEX + + +@dataclass(frozen=True) +class CandidateNode: + """A path segment that fits a layout node by position only; nothing confirms it. + + Attributes: + segment: The segment as written. + fits: The node it would be. + """ + + segment: str + fits: SchemaId + + +@dataclass(frozen=True) +class LayoutPosition: + """Where a path sits in the layout, as far as it is certain. + + Attributes: + location: The finding anchor: ``ONE_OF`` or ``ONE_PER_PROJECT`` when the certain segments reach the project + root's children, ``UNROOTED`` with those segments otherwise. + project_root: The project root, when a parent holds its required files. + detached: Segments above the certain ones that fit a node by position only, nearest first. + """ + + location: Location + project_root: Path | None + detached: tuple[CandidateNode, ...] = () + + +def locate_in_layout(path: Path, *, index: LayoutIndex = PROJECT_INDEX) -> LayoutPosition: + """Place a file in the layout by matching its name, then its parents, against the node chain above it. + + Raises: + ValueError: If no file node of the layout, or more than one, matches the file's name. + """ + + path = path.absolute() + leaf = _file_node(path, index) + chain = index.ancestry(leaf) # the file's node, then each ancestor up to the root + certain, matched, project_root = 1, 1, None + + for depth, schema_id in enumerate(chain[1:], start=1): + if depth - 1 >= len(path.parents): + break + directory, node = path.parents[depth - 1], index.schemas[schema_id] + if index.parents[schema_id] is None: + if _holds_required_files(directory, node): + project_root, certain = directory, depth + break + if not node.name.matches(Path(directory.name)): + break + matched = depth + 1 + if node.name.exact is not None: + certain = depth + 1 + + segments = [path.name, *(parent.name for parent in path.parents)] + instance = tuple(reversed(segments[:certain])) + if certain == len(chain) - 1: + location = node_location(leaf, Path(*instance), index=index) + else: + location = Location(schema_id=leaf, reach=Reach.UNROOTED, instance=instance) + detached = tuple(CandidateNode(segments[depth], chain[depth]) for depth in range(certain, matched)) + return LayoutPosition(location, project_root, detached) + + +def _file_node(path: Path, index: LayoutIndex) -> SchemaId: + matches = [ + schema_id for schema_id in index.schema_ids_of(FileSchema) if index.schemas[schema_id].name.matches(path) + ] + if len(matches) != 1: + raise ValueError(f"{path.name!r} matches {len(matches)} file nodes of the layout {matches}; one is needed.") + return matches[0] + + +def _holds_required_files(directory: Path, root: NodeSchema) -> bool: + """Whether ``directory`` holds every required, exactly named file the root declares, and it declares one.""" + + required = [ + child.name.exact + for child in getattr(root, "children", ()) + if isinstance(child, FileSchema) and child.required and child.name.exact + ] + return bool(required) and all((directory / name).is_file() for name in required) diff --git a/dlccore/project/schemas/scope.py b/dlccore/project/schemas/scope.py new file mode 100644 index 0000000..f065873 --- /dev/null +++ b/dlccore/project/schemas/scope.py @@ -0,0 +1,139 @@ +# +# 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 +# + +"""What a consumer asks about a project: layout nodes, each within an instance prefix.""" + +from __future__ import annotations + +from dataclasses import dataclass + +from dlccore.project.schemas.base.core import LayoutInstance, SchemaId +from dlccore.project.schemas.base.filesystem import FileSchema, LayoutIndex, NodeSchema +from dlccore.project.schemas.base.findings import Finding +from dlccore.project.schemas.project_layout.project import PROJECT_CONFIG, PROJECT_INDEX +from dlccore.project.schemas.snapshots import ProjectSnapshot + + +@dataclass(frozen=True, init=False) +class Scope: + """What a consumer asks findings for: layout nodes, each within an instance prefix. + + ``Scope(node, within=...)`` asks for one node; ``a | b`` asks for both. + + Attributes: + parts: Each requested node with its instance prefix, in the order first asked. + """ + + parts: tuple[tuple[NodeSchema, LayoutInstance], ...] + + def __init__(self, node: NodeSchema, within: LayoutInstance = ()) -> None: + object.__setattr__(self, "parts", ((node, tuple(within)),)) + + def __or__(self, other: Scope) -> Scope: + """Ask for both scopes; a part asked twice is kept once, where it was first asked.""" + + added = tuple(part for part in other.parts if part not in self.parts) + combined = object.__new__(Scope) + object.__setattr__(combined, "parts", self.parts + added) + + return combined + + def file_schema_ids(self, *, index: LayoutIndex = PROJECT_INDEX) -> tuple[SchemaId, ...]: + """Return the file nodes in the subtree of any scoped node, in walk order. + + Only the subtrees: a file at a scoped node's ancestor is not covered, although its findings are in scope. + + Raises: + ValueError: If a scoped node is not the layout's own node. + """ + + roots = {declared_node(index, node).schema_id for node, _ in self.parts} + + return tuple( + schema_id for schema_id in index.schema_ids_of(FileSchema) if roots & set(index.ancestry(schema_id)) + ) + + def covers(self, schema_id: SchemaId, instance: LayoutInstance, *, index: LayoutIndex = PROJECT_INDEX) -> bool: + """Return whether the node ``schema_id`` at ``instance`` is covered: in a scoped subtree, within its prefix. + + Raises: + ValueError: If a scoped node is not the layout's own node. + KeyError: If the layout does not declare ``schema_id``. + """ + + ancestry = index.ancestry(schema_id) + + return any( + declared_node(index, node).schema_id in ancestry and instances_overlap(instance, within) + for node, within in self.parts + ) + + +def findings_in_scope( + snapshot: ProjectSnapshot, + scope: Scope, + *, + index: LayoutIndex = PROJECT_INDEX, +) -> tuple[Finding, ...]: + """Return the findings of ``snapshot`` that concern ``scope``, in snapshot order, each once. + + A finding concerns a scoped node when it is anchored in the node's subtree, at one of its + ancestors, or at the config: every node depends on the whole config until its fields are + verified against DeepLabCut. Its instance must also match the scope's ``within``: one is a + prefix of the other, so ``()`` matches everything and another dataset's instance matches nothing. + + Raises: + ValueError: If any finding names a ``schema_id`` the layout does not declare, whatever the scope: + such a finding cannot be placed, so leaving it out would be a silent accept. Also if + a scoped node is not the layout's own node. + """ + + undeclared = sorted({finding.schema_id for finding in snapshot.findings} - set(index.schemas)) + + if undeclared: + raise ValueError(f"Findings name schema IDs the layout does not declare: {undeclared}.") + + related = [(_related_schema_ids(index, node), within) for node, within in scope.parts] + + return tuple( + finding + for finding in snapshot.findings + if any(finding.schema_id in ids and instances_overlap(finding.instance, within) for ids, within in related) + ) + + +def declared_node(index: LayoutIndex, node: NodeSchema) -> NodeSchema: + """Return ``node`` if it is the layout's own node. + + Raises: + ValueError: If the layout does not declare this node. + """ + + if index.schemas.get(node.schema_id) != node: + raise ValueError(f"The layout does not declare this {node.schema_id!r} node.") + + return node + + +def instances_overlap(instance: LayoutInstance, within: LayoutInstance) -> bool: + """Return whether one instance is a prefix of the other.""" + + shorter = min(len(instance), len(within)) + + return tuple(instance[:shorter]) == tuple(within[:shorter]) + + +def _related_schema_ids(index: LayoutIndex, node: NodeSchema) -> frozenset[SchemaId]: + """Return the IDs whose findings concern ``node``: its subtree, its ancestors and the config.""" + + schema_id = declared_node(index, node).schema_id + + return frozenset({*index.subtree(schema_id), *index.ancestry(schema_id), PROJECT_CONFIG.schema_id}) diff --git a/tests/project/discovery/test_position.py b/tests/project/discovery/test_position.py new file mode 100644 index 0000000..e951958 --- /dev/null +++ b/tests/project/discovery/test_position.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 +# + +from pathlib import Path + +import pytest + +from dlccore.project.discovery.position import CandidateNode, locate_in_layout +from dlccore.project.schemas.base.findings import Reach +from dlccore.project.schemas.project_layout.labeled_data import HUMAN_LABELS, LABELED_DATASET + +NAME = "CollectedData_Sc.h5" +INSTANCE = ("labeled-data", "Sample1", NAME) + + +def test_a_file_in_a_project_is_anchored_from_the_project_root(valid_project: Path) -> None: + position = locate_in_layout(valid_project / "labeled-data" / "Sample1" / NAME) + + assert position.location == {"schema_id": HUMAN_LABELS.schema_id, "reach": Reach.ONE_OF, "instance": INSTANCE} + assert (position.project_root, position.detached) == (valid_project.absolute(), ()) + + +def test_a_dataset_outside_a_project_keeps_the_instance_it_has_inside_one(tmp_path: Path) -> None: + position = locate_in_layout(tmp_path / "backup" / "labeled-data" / "Sample1" / NAME) + + assert position.location == {"schema_id": HUMAN_LABELS.schema_id, "reach": Reach.ONE_OF, "instance": INSTANCE} + assert (position.project_root, position.detached) == (None, ()) + + +def test_a_folder_that_fits_a_dataset_by_position_only_is_a_detached_candidate(tmp_path: Path) -> None: + position = locate_in_layout(tmp_path / "Downloads" / "Sample1" / NAME) + + assert position.location == {"schema_id": HUMAN_LABELS.schema_id, "reach": Reach.UNROOTED, "instance": (NAME,)} + assert position.detached == (CandidateNode("Sample1", LABELED_DATASET.schema_id),) + + +def test_labeled_data_spelled_otherwise_is_not_trusted(tmp_path: Path) -> None: + # napari-deeplabcut v0.4.0 matches "labeled-data" anywhere, in any case; the layout matches it at its position. + position = locate_in_layout(tmp_path / "Labeled-Data" / "x" / "Sample1" / NAME) + + assert position.location["reach"] is Reach.UNROOTED + assert position.detached == (CandidateNode("Sample1", LABELED_DATASET.schema_id),) + + +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") diff --git a/tests/project/inspection/test_policy.py b/tests/project/inspection/test_policy.py new file mode 100644 index 0000000..98ed30a --- /dev/null +++ b/tests/project/inspection/test_policy.py @@ -0,0 +1,26 @@ +# +# 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 __future__ import annotations + +from dlccore.project import api, policy + + +def test_the_api_helpers_reexport_the_policy_helpers() -> None: + assert (api.helpers.get_blocking_findings, api.helpers.unhandled) == ( + policy.get_blocking_findings, + policy.unhandled, + ) + + +def test_the_api_helpers_hold_exactly_the_consumer_helpers() -> None: + assert sorted(api.helpers.__all__) == ["Scope", "get_blocking_findings", "unhandled"] + assert not {"get_blocking_findings", "unhandled"} & set(vars(api)) diff --git a/tests/project/inspection/test_scope_query.py b/tests/project/inspection/test_scope_query.py new file mode 100644 index 0000000..3356ec1 --- /dev/null +++ b/tests/project/inspection/test_scope_query.py @@ -0,0 +1,51 @@ +# +# 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 __future__ import annotations + +import pytest + +from dlccore.project import api +from dlccore.project.api import helpers +from dlccore.project.schemas.project_layout.labeled_data import LABELED_DATASET, LABELED_FRAME +from dlccore.project.schemas.project_layout.videos import VIDEOS + +_DS1 = ("labeled-data", "ds1") + + +def test_octopus_provides_the_scope_query() -> None: + assert hasattr(api, "findings_in_scope") + + +def test_a_scope_covers_the_file_nodes_of_its_subtrees_in_walk_order() -> None: + scope = helpers.Scope(VIDEOS) | helpers.Scope(LABELED_DATASET, within=_DS1) + + assert scope.file_schema_ids() == ( + "dlc.videos.source_video", + "dlc.labeled_data.napari_metadata", + "dlc.labeled_data.frame", + "dlc.labeled_data.human_labels", + "dlc.labeled_data.machine_labels", + "dlc.labeled_data.machine_labels_csv", + ) + + +def test_a_scope_does_not_cover_files_at_its_ancestors() -> None: + """Findings there are in scope; the files are not.""" + + assert "dlc.project.config" not in helpers.Scope(LABELED_DATASET).file_schema_ids() + + +def test_covered_files_refuse_a_node_the_layout_does_not_declare() -> None: + impostor = LABELED_FRAME.model_copy(update={"description": "not the layout's own"}) + + with pytest.raises(ValueError, match="does not declare"): + helpers.Scope(impostor).file_schema_ids() diff --git a/tests/upstream/test_napari_deeplabcut.py b/tests/upstream/test_napari_deeplabcut.py new file mode 100644 index 0000000..bdd94eb --- /dev/null +++ b/tests/upstream/test_napari_deeplabcut.py @@ -0,0 +1,178 @@ +# +# 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 +# + +"""Tests whose home is napari-deeplabcut. Imports ``napari_deeplabcut`` only.""" + +import sys +from pathlib import Path + +import numpy as np +import pandas as pd +import pytest + +from dlccore.io.labeled_data import LabeledData, read_labeled_data, write_labeled_data +from dlccore.project.discovery.position import locate_in_layout +from dlccore.project.schemas.base.findings import Reach + +pytestmark = pytest.mark.destination("napari-deeplabcut") + +FIXTURES_DIR = Path(__file__).parents[1] / "io" / "fixtures" / "labeled_data" +H5_FIXTURES = sorted(path.name for path in FIXTURES_DIR.glob("*.h5")) + +Point = tuple[str, str, str, float, float, float] + + +def _napari_points(path: Path) -> list[Point]: + """napari-deeplabcut's reading of one file, as (frame, individual, bodypart, x, y, likelihood).""" + + io = pytest.importorskip("napari_deeplabcut.core.io") + ((data, attributes, _kind),) = io.read_hdf_single(path) + paths = attributes["metadata"]["paths"] + properties = attributes["properties"] + + return sorted( + (paths[int(frame)], str(individual), str(bodypart), float(x), float(y), float(likelihood)) + for (frame, y, x), bodypart, individual, likelihood in zip( + data, properties["label"], properties["id"], properties["likelihood"], strict=True + ) + ) + + +def _dlccore_points(path: Path) -> list[Point]: + """Our labeled points, mapped onto napari's conventions where they deliberately differ. + + Three mappings, each a difference rather than a disagreement: napari writes a missing individual as ``""``, + a frame as one ``/``-joined string, and the likelihood of human labels as ``1.0``. + """ + + long = read_labeled_data(path).labeled_data.to_long_df() + labeled = long[long[["x", "y"]].notna().all(axis=1)] + individuals = labeled["individual"].astype(str) if "individual" in labeled else [""] * len(labeled) + likelihoods = labeled["likelihood"] if "likelihood" in labeled else [1.0] * len(labeled) + + return sorted( + ("/".join((folder, dataset, image)), individual, bodypart, float(x), float(y), float(likelihood)) + for folder, dataset, image, individual, bodypart, x, y, likelihood in zip( + labeled["folder"].astype(str), + labeled["dataset"].astype(str), + labeled["image"].astype(str), + individuals, + labeled["bodypart"].astype(str), + labeled["x"], + labeled["y"], + likelihoods, + strict=True, + ) + ) + + +def test_every_h5_fixture_is_found() -> None: + # Control: an empty glob would let the equivalence test pass by running nothing. + assert len(H5_FIXTURES) == 8 + + +@pytest.mark.parametrize("filename", H5_FIXTURES) +def test_napari_deeplabcut_reads_the_same_labeled_points(filename: str) -> None: + ours = _dlccore_points(FIXTURES_DIR / filename) + + assert ours, "a fixture without labeled points would make the comparison vacuous" + assert _napari_points(FIXTURES_DIR / filename) == ours + + +def _rewrite(table: LabeledData, tmp_path: Path) -> Path: + # Human labels never carry a likelihood, so labels that have one are rewritten as machine labels. + target = tmp_path / ("machinelabels-iter0.h5" if table.has_likelihood else "CollectedData_Sc.h5") + write_labeled_data(table, target, replaces=None) + return target + + +def _table(filename: str) -> LabeledData: + return read_labeled_data(FIXTURES_DIR / filename).labeled_data + + +@pytest.mark.parametrize("filename", H5_FIXTURES) +def test_napari_deeplabcut_reads_a_rewritten_file_as_the_original(tmp_path: Path, filename: str) -> None: + original = _napari_points(FIXTURES_DIR / filename) + + assert original, "a fixture without labeled points would make the comparison vacuous" + assert _napari_points(_rewrite(_table(filename), tmp_path)) == original + + +def test_napari_deeplabcut_sees_one_moved_point_in_a_rewritten_file(tmp_path: Path) -> None: + # Control: the comparison above can fail. + long = _table("single_animal_human.h5").to_long_df() + long.loc[np.flatnonzero(long["x"].notna())[0], "x"] += 1.0 + + rewritten = _rewrite(LabeledData.from_long_df(long), tmp_path) + + assert _napari_points(rewritten) != _napari_points(FIXTURES_DIR / "single_animal_human.h5") + + +def _hdf_reads_by_shared_io(monkeypatch: pytest.MonkeyPatch, read: object) -> list[bool]: + """Call ``read`` and return, for each ``pd.read_hdf`` it makes, whether ``dlccore.io`` made it.""" + + calls: list[bool] = [] + read_hdf = pd.read_hdf + + def spy(*args: object, **kwargs: object) -> object: + frame = sys._getframe(1) + while frame is not None and not frame.f_globals.get("__name__", "").startswith("dlccore.io."): + frame = frame.f_back + calls.append(frame is not None) + return read_hdf(*args, **kwargs) + + monkeypatch.setattr(pd, "read_hdf", spy) + read() + return calls + + +def test_the_shared_reader_is_recognised_as_shared(monkeypatch: pytest.MonkeyPatch) -> None: + from dlccore.io.labeled_data._wide.h5 import read_labeled_data_h5 + + calls = _hdf_reads_by_shared_io(monkeypatch, lambda: read_labeled_data_h5(FIXTURES_DIR / "single_animal_human.h5")) + + assert calls == [True] + + +@pytest.mark.xfail( + reason="napari-deeplabcut reads labeled-data H5 files with pandas itself; adopting the shared labeled-data " + "I/O in dlccore.io.labeled_data finishes when every read goes through it", + strict=True, + raises=AssertionError, +) +def test_napari_deeplabcut_reads_labeled_data_only_through_the_shared_reader( + monkeypatch: pytest.MonkeyPatch, +) -> None: + reader = pytest.importorskip("napari_deeplabcut._reader") + path = str(FIXTURES_DIR / "single_animal_human.h5") + + calls = _hdf_reads_by_shared_io(monkeypatch, lambda: reader.get_hdf_reader(path)(path)) + + assert calls + assert all(calls) + + +@pytest.mark.xfail( + reason="napari-deeplabcut v0.4.0 takes a folder as a dataset when 'labeled-data' appears anywhere above it, in " + "any case; the layout places a dataset only under labeled-data itself (dlccore.project.discovery.position). " + "Adopting the layout position in napari-deeplabcut makes them agree", + strict=True, + raises=AssertionError, +) +def test_napari_deeplabcut_takes_a_folder_as_a_dataset_only_where_the_layout_places_one(tmp_path: Path) -> None: + project_paths = pytest.importorskip("napari_deeplabcut.core.project_paths") + folder = tmp_path / "Labeled-Data" / "x" / "Sample1" + folder.mkdir(parents=True) + + layout_says_dataset = locate_in_layout(folder / "CollectedData_Sc.h5").location["reach"] is not Reach.UNROOTED + napari_says_dataset = project_paths.infer_labeled_data_folder_from_paths([], fallback_root=folder) is not None + + assert napari_says_dataset == layout_says_dataset