Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions dlccore/project/api/__init__.py
Original file line number Diff line number Diff line change
@@ -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",
]
17 changes: 17 additions & 0 deletions dlccore/project/api/helpers.py
Original file line number Diff line number Diff line change
@@ -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"]
113 changes: 113 additions & 0 deletions dlccore/project/discovery/position.py
Original file line number Diff line number Diff line change
@@ -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)
139 changes: 139 additions & 0 deletions dlccore/project/schemas/scope.py
Original file line number Diff line number Diff line change
@@ -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})
55 changes: 55 additions & 0 deletions tests/project/discovery/test_position.py
Original file line number Diff line number Diff line change
@@ -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")
26 changes: 26 additions & 0 deletions tests/project/inspection/test_policy.py
Original file line number Diff line number Diff line change
@@ -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))
Loading
Loading