Skip to content
Merged
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
3 changes: 3 additions & 0 deletions src/funtracks/actions/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from ._base import Action, ActionGroup, BasicAction
from .add_delete_edge import AddEdge, DeleteEdge
from .add_delete_feature import AddFeature, DeleteFeature
from .add_delete_node import AddNode, DeleteNode
from .update_node_attrs import UpdateNodeAttrs
from .update_segmentation import UpdateNodeSeg
Expand All @@ -9,9 +10,11 @@
"Action",
"ActionGroup",
"AddEdge",
"AddFeature",
"AddNode",
"BasicAction",
"DeleteEdge",
"DeleteFeature",
"DeleteNode",
"UpdateNodeAttrs",
"UpdateNodeSeg",
Expand Down
135 changes: 135 additions & 0 deletions src/funtracks/actions/add_delete_feature.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
from __future__ import annotations

from typing import TYPE_CHECKING, Any

import tracksdata as td

from ._base import BasicAction

if TYPE_CHECKING:
from funtracks.data_model import Tracks
from funtracks.features import Feature

# Column values: the node ids and their values, in the same order. Stored densely
# (every node). If undo memory becomes a problem on large graphs, store only the
# values that differ from the feature's default.
FeatureValues = tuple[list[int], list[Any]]


class AddFeature(BasicAction):
"""Action for adding a new node feature (an attribute column) to the Tracks.

Meant for user-created features such as groups. Features computed by an
annotator are switched on with ``Tracks.enable_features`` instead, which is not
an action and is not undoable.
"""

def __init__(
self,
tracks: Tracks,
key: str,
feature: Feature,
values: FeatureValues | None = None,
):
"""Create an action to add a new node feature.

Args:
tracks (Tracks): The Tracks to add the feature to.
key (str): The key of the new feature.
feature (Feature): The feature metadata. Only node features are supported.
values (tuple[list[int], list] | None): Optional node ids and their
values. Used by the inverse of DeleteFeature to restore a column.

Raises:
NotImplementedError: If the feature is not a node feature.
ValueError: If the key is already a feature, or is owned by an annotator.
"""
super().__init__(tracks)
if feature["feature_type"] != "node":
raise NotImplementedError(f"Only node features are supported, not {key!r}")
if key in tracks.features:
raise ValueError(f"Feature {key!r} already exists")
if key in tracks.annotators.all_features:
raise ValueError(
f"Feature {key!r} is computed by an annotator; use enable_features"
)
# A column that exists without being a registered feature (e.g. loaded from
# a geff) would keep its values here, and the inverse would then drop them.
if key in tracks.graph_full.node_attr_keys():
raise ValueError(f"Node attribute {key!r} already exists in the graph")
self.key = key
# Copy: add_feature stores the dict by reference
self.feature = feature.copy()
self.values = values
self._apply()

def inverse(self) -> BasicAction:
"""Invert the action to delete the feature again."""
return DeleteFeature(self.tracks, self.key)

def _apply(self) -> None:
self.tracks.add_feature(self.key, self.feature)
if self.values is not None and len(self.values[0]) > 0:
node_ids, values = self.values
self.tracks.graph_full.update_node_attrs(
attrs={self.key: values}, node_ids=node_ids
)
self.tracks.notify_annotators(self)


class DeleteFeature(BasicAction):
"""Action for deleting a user-created node feature (an attribute column).

Saves the column's values for every node in graph_full (soft-deleted candidates
included), so the action can be inverted.
"""

def __init__(self, tracks: Tracks, key: str):
"""Create an action to delete a node feature.

Args:
tracks (Tracks): The Tracks to delete the feature from.
key (str): The key of the feature to delete.

Raises:
NotImplementedError: If the feature is not a node feature.
ValueError: If the key is not a feature, is a core feature of the Tracks,
is owned by an annotator, or has derived features.
"""
super().__init__(tracks)
if key not in tracks.features:
raise ValueError(f"Feature {key!r} does not exist")
# Track ids are always annotator-owned, so caught by the next check
pos_key = tracks.features.position_key
core_keys = {
tracks.features.time_key,
td.DEFAULT_ATTR_KEYS.MASK,
td.DEFAULT_ATTR_KEYS.BBOX,
"solution",
}
core_keys.update(pos_key if isinstance(pos_key, list) else [pos_key])
if key in core_keys:
raise ValueError(f"Cannot delete core feature {key!r}")
if key in tracks.annotators.all_features:
raise ValueError(
f"Feature {key!r} is computed by an annotator; use disable_features"
)
feature = tracks.features[key]
if feature["feature_type"] != "node":
raise NotImplementedError(f"Only node features are supported, not {key!r}")
if feature.get("derived_features"):
raise ValueError(f"Cannot delete feature {key!r}, it has derived features")
self.key = key
self.feature = feature
node_id = td.DEFAULT_ATTR_KEYS.NODE_ID
df = tracks.graph_full.node_attrs(attr_keys=[node_id, key])
self.values = (df[node_id].to_list(), df[key].to_list())
self._apply()

def inverse(self) -> BasicAction:
"""Invert the action to re-add the feature with its saved values."""
return AddFeature(self.tracks, self.key, self.feature, values=self.values)

def _apply(self) -> None:
self.tracks.delete_feature(self.key)
self.tracks.notify_annotators(self)
3 changes: 3 additions & 0 deletions src/funtracks/user_actions/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from ._connect_utils import is_connected_chain
from ._user_swap_predecessors import UserSwapPredecessors
from .user_add_delete_feature import UserAddFeature, UserDeleteFeature
from .user_add_edge import UserAddEdge
from .user_add_node import UserAddNode
from .user_connect_nodes import UserConnectNodes
Expand All @@ -19,9 +20,11 @@

__all__ = [
"UserAddEdge",
"UserAddFeature",
"UserAddNode",
"UserConnectNodes",
"UserDeleteEdge",
"UserDeleteFeature",
"UserDeleteNode",
"UserDeleteNodes",
"UserDisconnectNodes",
Expand Down
72 changes: 72 additions & 0 deletions src/funtracks/user_actions/user_add_delete_feature.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
from __future__ import annotations

from typing import TYPE_CHECKING

from ..actions._base import ActionGroup
from ..actions.add_delete_feature import AddFeature, DeleteFeature

if TYPE_CHECKING:
from funtracks.data_model import Tracks
from funtracks.features import Feature


class UserAddFeature(ActionGroup):
"""User action for adding a new node feature, e.g. a group.

Wraps the basic AddFeature action and adds it to the action history, so creating
the feature can be undone.
"""

def __init__(
self,
tracks: Tracks,
key: str,
feature: Feature,
_top_level: bool = True,
):
"""
Args:
tracks (Tracks): The tracks to add the feature to.
key (str): The key of the new feature.
feature (Feature): The feature metadata. Only node features are supported.
_top_level (bool): If True, add this action to the history and emit
refresh. Set to False when used as a sub-action inside a compound
action. Defaults to True.
"""
super().__init__(tracks, actions=[])
self.tracks: Tracks # Narrow type from base class
self.actions.append(AddFeature(tracks, key, feature))

if _top_level:
self.tracks.action_history.add_new_action(self)
self.tracks.refresh.emit()


class UserDeleteFeature(ActionGroup):
"""User action for deleting a user-created node feature, e.g. a group.

Wraps the basic DeleteFeature action and adds it to the action history, so the
feature and its values can be restored by undo.
"""

def __init__(
self,
tracks: Tracks,
key: str,
_top_level: bool = True,
):
"""
Args:
tracks (Tracks): The tracks to delete the feature from.
key (str): The key of the feature to delete.
_top_level (bool): If True, add this action to the history and emit
refresh. Set to False when used as a sub-action inside a compound
action. Defaults to True.
"""
super().__init__(tracks, actions=[])
self.tracks: Tracks # Narrow type from base class
self.actions.append(DeleteFeature(tracks, key))

if _top_level:
self.tracks.action_history.add_new_action(self)
self.tracks.refresh.emit()
147 changes: 147 additions & 0 deletions tests/actions/test_add_delete_feature.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
import polars as pl
import pytest

from funtracks.actions import AddFeature, DeleteFeature, UpdateNodeAttrs
from funtracks.features import Feature
from funtracks.user_actions import UserDeleteNode


def _group_feature() -> Feature:
return Feature(
feature_type="node",
value_type="bool",
num_values=1,
display_name="group",
default_value=False,
)


@pytest.mark.parametrize("ndim", [3, 4])
@pytest.mark.parametrize("with_seg", [True, False])
def test_add_feature(get_tracks, ndim, with_seg):
tracks = get_tracks(ndim=ndim, with_seg=with_seg, prefill_track_ids=True)
action = AddFeature(tracks, "group", _group_feature())
assert "group" in tracks.features
assert "group" in tracks.graph_full.node_attr_keys()
assert tracks.get_node_attr(1, "group") is False

inverse = action.inverse()
assert "group" not in tracks.features
assert "group" not in tracks.graph_full.node_attr_keys()

inverse.inverse()
assert "group" in tracks.features
assert tracks.get_node_attr(1, "group") is False


@pytest.mark.parametrize("ndim", [3, 4])
@pytest.mark.parametrize("with_seg", [True, False])
def test_delete_feature_restores_values(get_tracks, ndim, with_seg):
tracks = get_tracks(ndim=ndim, with_seg=with_seg, prefill_track_ids=True)
feature = _group_feature()
AddFeature(tracks, "group", feature)
UpdateNodeAttrs(tracks, 1, {"group": True})
UpdateNodeAttrs(tracks, 2, {"group": True})
# A soft-deleted node keeps its value in graph_full, and must get it back
UserDeleteNode(tracks, 2)
assert not tracks.graph_solution.has_node(2)

action = DeleteFeature(tracks, "group")
assert "group" not in tracks.features
assert "group" not in tracks.graph_full.node_attr_keys()
assert set(action.values[0]) == set(tracks.graph_full.node_ids())

inverse = action.inverse()
assert tracks.features["group"] == feature
assert tracks.get_node_attr(1, "group") is True
assert tracks.get_node_attr(2, "group") is True
assert tracks.get_node_attr(3, "group") is False

inverse.inverse()
assert "group" not in tracks.features
assert "group" not in tracks.graph_full.node_attr_keys()


def test_delete_feature_str_values(get_tracks):
tracks = get_tracks(ndim=3, with_seg=False, prefill_track_ids=True)
feature = Feature(
feature_type="node",
value_type="str",
num_values=1,
display_name="label",
default_value="",
)
AddFeature(tracks, "label", feature)
UpdateNodeAttrs(tracks, 3, {"label": "a"})

action = DeleteFeature(tracks, "label")
action.inverse()
assert tracks.get_node_attr(3, "label") == "a"
assert tracks.get_node_attr(1, "label") == ""


def test_add_existing_feature_raises(get_tracks):
tracks = get_tracks(ndim=3, with_seg=True, prefill_track_ids=True)
AddFeature(tracks, "group", _group_feature())
with pytest.raises(ValueError, match="already exists"):
AddFeature(tracks, "group", _group_feature())


def test_add_feature_over_unregistered_column_raises(get_tracks):
# A column in the graph that is not a registered feature, e.g. loaded from a
# geff: adding it as a feature would let the inverse drop its values.
tracks = get_tracks(ndim=3, with_seg=True, prefill_track_ids=True)
tracks.graph_full.add_node_attr_key("group", default_value=False, dtype=pl.Boolean)
tracks.graph_full.update_node_attrs(attrs={"group": [True]}, node_ids=[1])
with pytest.raises(ValueError, match="already exists in the graph"):
AddFeature(tracks, "group", _group_feature())
assert "group" not in tracks.features
assert tracks.get_node_attr(1, "group") is True


def test_add_feature_copies_feature_dict(get_tracks):
tracks = get_tracks(ndim=3, with_seg=True, prefill_track_ids=True)
feature = _group_feature()
action = AddFeature(tracks, "group", feature)
feature["display_name"] = "renamed"
action.inverse().inverse()
assert tracks.features["group"]["display_name"] == "group"


def test_add_annotator_feature_raises(get_tracks):
tracks = get_tracks(ndim=3, with_seg=True, prefill_track_ids=True)
tracks.disable_features(["area"])
with pytest.raises(ValueError, match="computed by an annotator"):
AddFeature(tracks, "area", _group_feature())


@pytest.mark.parametrize("key", ["t", "pos", "mask", "bbox", "solution"])
def test_delete_core_feature_raises(get_tracks, key):
tracks = get_tracks(ndim=3, with_seg=True, prefill_track_ids=True)
with pytest.raises(ValueError, match="core feature"):
DeleteFeature(tracks, key)


@pytest.mark.parametrize("key", ["area", "track_id"])
def test_delete_annotator_feature_raises(get_tracks, key):
tracks = get_tracks(ndim=3, with_seg=True, prefill_track_ids=True)
with pytest.raises(ValueError, match="computed by an annotator"):
DeleteFeature(tracks, key)


def test_delete_missing_feature_raises(get_tracks):
tracks = get_tracks(ndim=3, with_seg=True, prefill_track_ids=True)
with pytest.raises(ValueError, match="does not exist"):
DeleteFeature(tracks, "group")


def test_edge_feature_raises(get_tracks):
tracks = get_tracks(ndim=3, with_seg=True, prefill_track_ids=True)
feature = _group_feature()
feature["feature_type"] = "edge"
with pytest.raises(NotImplementedError):
AddFeature(tracks, "edge_group", feature)

tracks.add_feature("edge_group", feature)
with pytest.raises(NotImplementedError):
DeleteFeature(tracks, "edge_group")
Loading
Loading