From 01b135117b8d1a4b370df262091a95ab90f0e72b Mon Sep 17 00:00:00 2001 From: Cyril Achard Date: Thu, 26 Nov 2026 14:43:39 +0100 Subject: [PATCH 1/4] Copy project scope, layout position and the API package --- dlccore/project/api/__init__.py | 36 +++++ dlccore/project/api/helpers.py | 6 + dlccore/project/discovery/position.py | 102 ++++++++++++++ dlccore/project/schemas/scope.py | 128 +++++++++++++++++ tests/upstream/test_napari_deeplabcut.py | 167 +++++++++++++++++++++++ 5 files changed, 439 insertions(+) create mode 100644 dlccore/project/api/__init__.py create mode 100644 dlccore/project/api/helpers.py create mode 100644 dlccore/project/discovery/position.py create mode 100644 dlccore/project/schemas/scope.py create mode 100644 tests/upstream/test_napari_deeplabcut.py diff --git a/dlccore/project/api/__init__.py b/dlccore/project/api/__init__.py new file mode 100644 index 0000000..c9d69ff --- /dev/null +++ b/dlccore/project/api/__init__.py @@ -0,0 +1,36 @@ +"""Octopus's public entry points; consumer helpers are in ``dlc_octopus.api.helpers``. Re-exports only.""" + +from dlc_octopus.api import helpers +from dlc_octopus.content import ( + FailedRead, + FileFingerprint, + InspectedLabeledDataFile, + LabeledDataEntry, + ProjectLabeledData, + ResourcesFileFingerprint, + compare_file_fingerprints, + inspect_labeled_data_file, + read_project_labeled_data, + resources_file_fingerprint, +) +from dlc_octopus.inspection import inspect_project, project_name +from dlc_octopus.schemas.base.resources import FileResourceKind +from dlc_octopus.schemas.scope import findings_in_scope + +__all__ = [ + "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/api/helpers.py b/dlccore/project/api/helpers.py new file mode 100644 index 0000000..6aaf337 --- /dev/null +++ b/dlccore/project/api/helpers.py @@ -0,0 +1,6 @@ +"""What a consumer composes with the entry points in ``dlc_octopus.api``: scopes and its own finding policy.""" + +from dlc_octopus.policy import get_blocking_findings, unhandled +from dlc_octopus.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..9273391 --- /dev/null +++ b/dlccore/project/discovery/position.py @@ -0,0 +1,102 @@ +"""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 dlc_octopus.schemas.base.core import SchemaId +from dlc_octopus.schemas.base.filesystem import FileSchema, LayoutIndex, NodeSchema +from dlc_octopus.schemas.base.findings import Reach +from dlc_octopus.schemas.locations import Location, node_location +from dlc_octopus.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..40269e8 --- /dev/null +++ b/dlccore/project/schemas/scope.py @@ -0,0 +1,128 @@ +"""What a consumer asks Octopus about: layout nodes, each within an instance prefix.""" + +from __future__ import annotations + +from dataclasses import dataclass + +from dlc_octopus.schemas.base.core import LayoutInstance, SchemaId +from dlc_octopus.schemas.base.filesystem import FileSchema, LayoutIndex, NodeSchema +from dlc_octopus.schemas.base.findings import Finding +from dlc_octopus.schemas.project_layout.project import PROJECT_CONFIG, PROJECT_INDEX +from dlc_octopus.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/upstream/test_napari_deeplabcut.py b/tests/upstream/test_napari_deeplabcut.py new file mode 100644 index 0000000..423a7e5 --- /dev/null +++ b/tests/upstream/test_napari_deeplabcut.py @@ -0,0 +1,167 @@ +"""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 dlc_octopus.discovery.position import locate_in_layout +from dlc_octopus.io.labeled_data import LabeledData, read_labeled_data, write_labeled_data +from dlc_octopus.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 _octopus_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 = _octopus_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 ``dlc_octopus.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("dlc_octopus.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 dlc_octopus.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 dlc_octopus.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 (dlc_octopus.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 From c74e03a0eaab5efb4db010d3acb4e46209e6b4b3 Mon Sep 17 00:00:00 2001 From: Cyril Achard Date: Thu, 26 Nov 2026 15:06:59 +0100 Subject: [PATCH 2/4] Adapt project scope, layout position and the API package to dlccore - Rename the packages to dlccore.project and dlccore.io, and add the dlccore license header - Land the API package partially: helpers, findings_in_scope and FileResourceKind; inspect_project and project_name follow with inspection, the content entry points with content - Add the tests that run at this layer: five of tests/discovery/test_position.py, two of tests/inspection/test_policy.py, four of tests/inspection/test_scope_query.py; the rest need inspect_project, validation results or later finding codes - Port tests/upstream/test_napari_deeplabcut.py, marked destination("napari-deeplabcut") - Reword the scope module's docstring, which named Octopus --- dlccore/project/api/__init__.py | 44 ++++++---------- dlccore/project/api/helpers.py | 17 ++++-- dlccore/project/discovery/position.py | 21 ++++++-- dlccore/project/schemas/scope.py | 23 +++++--- tests/project/discovery/test_position.py | 55 ++++++++++++++++++++ tests/project/inspection/test_policy.py | 26 +++++++++ tests/project/inspection/test_scope_query.py | 51 ++++++++++++++++++ tests/upstream/test_napari_deeplabcut.py | 31 +++++++---- 8 files changed, 215 insertions(+), 53 deletions(-) create mode 100644 tests/project/discovery/test_position.py create mode 100644 tests/project/inspection/test_policy.py create mode 100644 tests/project/inspection/test_scope_query.py diff --git a/dlccore/project/api/__init__.py b/dlccore/project/api/__init__.py index c9d69ff..4e5e5e7 100644 --- a/dlccore/project/api/__init__.py +++ b/dlccore/project/api/__init__.py @@ -1,36 +1,22 @@ -"""Octopus's public entry points; consumer helpers are in ``dlc_octopus.api.helpers``. Re-exports only.""" +# +# 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 dlc_octopus.api import helpers -from dlc_octopus.content import ( - FailedRead, - FileFingerprint, - InspectedLabeledDataFile, - LabeledDataEntry, - ProjectLabeledData, - ResourcesFileFingerprint, - compare_file_fingerprints, - inspect_labeled_data_file, - read_project_labeled_data, - resources_file_fingerprint, -) -from dlc_octopus.inspection import inspect_project, project_name -from dlc_octopus.schemas.base.resources import FileResourceKind -from dlc_octopus.schemas.scope import findings_in_scope +"""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__ = [ - "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/api/helpers.py b/dlccore/project/api/helpers.py index 6aaf337..cb3cff6 100644 --- a/dlccore/project/api/helpers.py +++ b/dlccore/project/api/helpers.py @@ -1,6 +1,17 @@ -"""What a consumer composes with the entry points in ``dlc_octopus.api``: scopes and its own finding policy.""" +# +# 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 dlc_octopus.policy import get_blocking_findings, unhandled -from dlc_octopus.schemas.scope import Scope +"""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 index 9273391..ab33126 100644 --- a/dlccore/project/discovery/position.py +++ b/dlccore/project/discovery/position.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 +# + """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 @@ -10,11 +21,11 @@ from dataclasses import dataclass from pathlib import Path -from dlc_octopus.schemas.base.core import SchemaId -from dlc_octopus.schemas.base.filesystem import FileSchema, LayoutIndex, NodeSchema -from dlc_octopus.schemas.base.findings import Reach -from dlc_octopus.schemas.locations import Location, node_location -from dlc_octopus.schemas.project_layout.project import PROJECT_INDEX +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) diff --git a/dlccore/project/schemas/scope.py b/dlccore/project/schemas/scope.py index 40269e8..f065873 100644 --- a/dlccore/project/schemas/scope.py +++ b/dlccore/project/schemas/scope.py @@ -1,14 +1,25 @@ -"""What a consumer asks Octopus about: layout nodes, each within an instance prefix.""" +# +# 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 dlc_octopus.schemas.base.core import LayoutInstance, SchemaId -from dlc_octopus.schemas.base.filesystem import FileSchema, LayoutIndex, NodeSchema -from dlc_octopus.schemas.base.findings import Finding -from dlc_octopus.schemas.project_layout.project import PROJECT_CONFIG, PROJECT_INDEX -from dlc_octopus.schemas.snapshots import ProjectSnapshot +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) 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 index 423a7e5..02aaddc 100644 --- a/tests/upstream/test_napari_deeplabcut.py +++ b/tests/upstream/test_napari_deeplabcut.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 +# + """Tests whose home is napari-deeplabcut. Imports ``napari_deeplabcut`` only.""" import sys @@ -7,9 +18,9 @@ import pandas as pd import pytest -from dlc_octopus.discovery.position import locate_in_layout -from dlc_octopus.io.labeled_data import LabeledData, read_labeled_data, write_labeled_data -from dlc_octopus.schemas.base.findings import Reach +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") @@ -35,7 +46,7 @@ def _napari_points(path: Path) -> list[Point]: ) -def _octopus_points(path: Path) -> list[Point]: +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 ``""``, @@ -70,7 +81,7 @@ def test_every_h5_fixture_is_found() -> None: @pytest.mark.parametrize("filename", H5_FIXTURES) def test_napari_deeplabcut_reads_the_same_labeled_points(filename: str) -> None: - ours = _octopus_points(FIXTURES_DIR / filename) + 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 @@ -106,14 +117,14 @@ def test_napari_deeplabcut_sees_one_moved_point_in_a_rewritten_file(tmp_path: Pa 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 ``dlc_octopus.io`` made it.""" + """Call ``read`` and return, for each ``pd.read_hdf`` it makes, whether ``dlccore.project.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("dlc_octopus.io."): + 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) @@ -124,7 +135,7 @@ def spy(*args: object, **kwargs: object) -> object: def test_the_shared_reader_is_recognised_as_shared(monkeypatch: pytest.MonkeyPatch) -> None: - from dlc_octopus.io.labeled_data.wide.h5 import read_labeled_data_h5 + 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")) @@ -133,7 +144,7 @@ def test_the_shared_reader_is_recognised_as_shared(monkeypatch: pytest.MonkeyPat @pytest.mark.xfail( reason="napari-deeplabcut reads labeled-data H5 files with pandas itself; adopting the shared labeled-data " - "I/O in dlc_octopus.io.labeled_data finishes when every read goes through it", + "I/O in dlccore.io.labeled_data finishes when every read goes through it", strict=True, raises=AssertionError, ) @@ -151,7 +162,7 @@ def test_napari_deeplabcut_reads_labeled_data_only_through_the_shared_reader( @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 (dlc_octopus.discovery.position). " + "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, From f636e580597e3f2d820aa776a68701a0e6f775f3 Mon Sep 17 00:00:00 2001 From: Cyril Achard Date: Thu, 26 Nov 2026 15:27:07 +0100 Subject: [PATCH 3/4] Name dlccore.io in the napari-deeplabcut test's docstring --- tests/upstream/test_napari_deeplabcut.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/upstream/test_napari_deeplabcut.py b/tests/upstream/test_napari_deeplabcut.py index 02aaddc..758c2bd 100644 --- a/tests/upstream/test_napari_deeplabcut.py +++ b/tests/upstream/test_napari_deeplabcut.py @@ -117,7 +117,7 @@ def test_napari_deeplabcut_sees_one_moved_point_in_a_rewritten_file(tmp_path: Pa 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.project.io`` made it.""" + """Call ``read`` and return, for each ``pd.read_hdf`` it makes, whether ``dlccore.io`` made it.""" calls: list[bool] = [] read_hdf = pd.read_hdf From 6e8a7c9ecf3d04ef96701c524a8ec5719aaea727 Mon Sep 17 00:00:00 2001 From: Cyril Achard Date: Mon, 30 Nov 2026 16:06:31 +0100 Subject: [PATCH 4/4] private import refactor --- tests/upstream/test_napari_deeplabcut.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/upstream/test_napari_deeplabcut.py b/tests/upstream/test_napari_deeplabcut.py index 758c2bd..bdd94eb 100644 --- a/tests/upstream/test_napari_deeplabcut.py +++ b/tests/upstream/test_napari_deeplabcut.py @@ -135,7 +135,7 @@ def spy(*args: object, **kwargs: object) -> object: 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 + 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"))