diff --git a/pyproject.toml b/pyproject.toml index c6a4b909..a1113c4b 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -38,10 +38,11 @@ dependencies =[ "dask>=2025.5.0", "pandas>=2.3.3", "zarr>=2.18,<4", - # rc11 is the first release whose sqlalchemy dependency carries the asyncio - # extra. Without it, sqlalchemy 2.1 installs without greenlet and every - # SQLGraph test fails to import. See .claude/tracksdata_sqla.md. - "tracksdata>=0.1.0rc11", + # TEMPORARY pin: GraphView(root_fallback=True) (royerlab/tracksdata#340) and + # GraphArrayView(downscale=...) (royerlab/tracksdata#341), on the branch that + # carries both. + # Restore "tracksdata>=" once those land in a release. + "tracksdata @ git+https://github.com/TeunHuijben/tracksdata.git@49388d69810effad92581302d94785a2708d6703", "tqdm>=4.66.1", # zarr 2.x's util.py imports cbuffer_sizes/cbuffer_metainfo from # numcodecs.blosc, which numcodecs >= 0.16 removed. Pin numcodecs per diff --git a/src/funtracks/data_model/tracks.py b/src/funtracks/data_model/tracks.py index 8c1666fc..4a04266f 100644 --- a/src/funtracks/data_model/tracks.py +++ b/src/funtracks/data_model/tracks.py @@ -30,6 +30,8 @@ Time, ) from funtracks.utils.tracksdata_utils import ( + all_node_attr_keys, + solution_view, to_polars_dtype, ) @@ -87,6 +89,7 @@ def __init__( features: FeatureDict | None = None, intensity_images: Sequence[IntensityImage] | None = None, channel_names: Sequence[str] | None = None, + lean_solution_view: bool | None = None, _segmentation: GraphArrayView | None = None, ): """Initialize a Tracks object. @@ -125,6 +128,11 @@ def __init__( set_intensity_images. channel_names (Sequence[str] | None): Display names, one per intensity image. Defaults to channel_0, channel_1, ... for multichannel input. + lean_solution_view (bool | None): Whether graph_solution leaves out the + blob columns nothing reads from it, reading those through to + graph_full on demand. None (default) decides by backend - see + funtracks.utils.tracksdata_utils.solution_view. PROVISIONAL: may be + removed without deprecation once leanness is unconditional. _segmentation (GraphArrayView | None): Internal parameter for reusing an existing GraphArrayView instance. Not intended for public use. """ @@ -145,17 +153,15 @@ def __init__( if "solution" not in graph.edge_attr_keys(): graph.add_edge_attr_key("solution", default_value=True, dtype=pl.Boolean) self.graph_full = graph - # ViewMode.LIVE: the root pushes its attribute writes (and new attr keys) - # back into this view. funtracks writes values/schema on graph_full and reads - # them via graph_solution, so the view must stay live. Since tracksdata rc10, - # views default to WRITE_THROUGH (no root->view propagation), so this is required. - self.graph_solution = graph.filter( - td.NodeAttr("solution") == True, # noqa: E712 - td.EdgeAttr("solution") == True, # noqa: E712 - ).subgraph(mode=td.graph.ViewMode.LIVE) + self.graph_solution = solution_view(graph, lean_solution_view) # Highest node id handed out so far, filled in on first use by # get_next_node_id and kept up to date from there. self._max_node_id: int | None = None + self._segmentation_array: GraphArrayView | None = None + # Reduced-resolution, display-only views, keyed by normalized downscale + # factors. Cached so that repeated requests for the same factor (every + # 2D/3D toggle in a viewer) keep their chunk cache warm. + self._display_views: dict[tuple[int, ...], GraphArrayView] = {} if _segmentation is not None: # Reuse provided segmentation instance (internal use only) self.segmentation = _segmentation @@ -250,6 +256,136 @@ def __init__( # and computed. A provided FeatureDict that omitted them is completed here. self._ensure_track_features() + def _solution_view_all_attrs(self) -> td.graph.GraphView: + """A solution view holding every node attribute column, not just the lean set. + + Private escape hatch for funtracks' own export paths; it goes away with the + lean/non-lean distinction. ``graph_solution`` may be lean, which is right for + reading - excluded columns fall back to graph_full - but wrong for code that + copies the view's columns rather than querying them (``detach()``, a nested + ``subgraph()``). + + Returns: + ``graph_solution`` itself when it already holds every column, otherwise a + freshly built non-lean view (LIVE like the original, so writes through it + still reach graph_full). + """ + if not set(self.graph_full.node_attr_keys()) - set( + self.graph_solution.node_attr_keys() + ): + return self.graph_solution + return solution_view(self.graph_full, lean=False) + + @property + def segmentation(self) -> GraphArrayView | None: + """Full-resolution label array rendered from ``graph_solution``, or None. + + This is the authoritative segmentation: segmentation export, intensity image + validation and IoU all read it, so it always lives on the full-resolution + grid. For a cheaper array to *render*, use :meth:`display_segmentation`. + """ + return self._segmentation_array + + @segmentation.setter + def segmentation(self, value: GraphArrayView | None) -> None: + downscale = getattr(value, "downscale", None) + if downscale is not None and any(f != 1 for f in downscale): + raise ValueError( + f"Cannot assign a downscaled GraphArrayView (downscale={downscale}) " + "to tracks.segmentation: it is the full-resolution array that " + "segmentation export and feature computation read, and a coarse " + "shape there renders full-resolution masks into an undersized array " + "without erroring. Hold the view returned by display_segmentation() " + "at the call site instead." + ) + self._segmentation_array = value + self._display_views = {} + + def _normalize_downscale(self, downscale: int | Sequence[int]) -> tuple[int, ...]: + """Validate ``downscale`` and broadcast it to one factor per spatial axis.""" + n_spatial = self.ndim - 1 + if isinstance(downscale, (int, np.integer)): + factors = (int(downscale),) * n_spatial + else: + values = list(downscale) + if not all(isinstance(f, (int, np.integer)) for f in values): + raise ValueError(f"`downscale` must be integer, got {downscale!r}") + if len(values) != n_spatial: + hint = ( + ", which looks like a time-first sequence (as in Tracks.scale)" + if len(values) == self.ndim + else "" + ) + raise ValueError( + f"`downscale` is spatial-only, expected length {n_spatial} for " + f"ndim={self.ndim}; got {len(values)}{hint}." + ) + factors = tuple(int(f) for f in values) + if any(f < 1 for f in factors): + raise ValueError(f"`downscale` factors must be >= 1, got {factors}") + return factors + + def display_segmentation( + self, downscale: int | Sequence[int] + ) -> GraphArrayView | None: + """A reduced-resolution view of the segmentation, for rendering only. + + Rendering a full-resolution 3D timepoint materializes the whole volume; a + downscaled view shrinks both the buffer and the paint cost, while still + drawing every object (anything thinner than the factor becomes a single + voxel, so it stays visible and selectable). + + Args: + downscale: One integer factor per *spatial* axis (length ``ndim - 1``), + or a single int broadcast to all of them. Prefer the explicit tuple + and pick factors that equalize physical voxel size, i.e. keep + ``scale[i] * downscale[i]`` roughly constant: on anisotropic data an + isotropic factor coarsens the axis with the least to give. + + Returns: + A ``GraphArrayView`` over the same graph at the requested resolution, or + None when this Tracks has no segmentation. Returns ``self.segmentation`` + itself when every factor is 1. Views are cached per factor, so asking + repeatedly keeps the chunk cache rather than rebuilding it. + + Note: + Coordinates read out of a coarse view are in downscaled coordinates, and + the shape and size of what it paints are not quantitative. Never feed + them back into an edit or a metric without checking ``view.downscale``. + """ + if self.segmentation is None: + return None + factors = self._normalize_downscale(downscale) + if all(f == 1 for f in factors): + return self.segmentation + if factors not in self._display_views: + self._display_views[factors] = GraphArrayView( + graph=self.graph_solution, + shape=self.segmentation.full_shape, + attr_key="node_id", + offset=0, + downscale=factors, + # Inherit the dtype rather than letting GraphArrayView infer it: + # the probe is a full node_id column read, and the authoritative + # view has already paid for it once. + dtype=self.segmentation.dtype, + ) + return self._display_views[factors] + + def display_scale(self, downscale: int | Sequence[int]) -> list[float] | None: + """Voxel spacing of ``display_segmentation(downscale)``, or None if unknown. + + A coarse array needs a proportionally larger voxel size, or it renders at a + fraction of its true extent. This mirrors :attr:`scale` (time first, and + None when the graph carries no scale metadata) rather than manufacturing a + scale out of the factors alone, which would look valid but mean nothing. + """ + scale = self.scale + if scale is None: + return None + factors = self._normalize_downscale(downscale) + return [scale[0], *(s * f for s, f in zip(scale[1:], factors, strict=True))] + @property def scale(self) -> list[float] | None: """Segmentation voxel spacing (time first, dummy 1.0), or None if unknown. @@ -449,9 +585,10 @@ def _check_existing_feature(self, key: str) -> bool: if self.graph_solution.num_nodes() == 0: return True - # Check which attributes exist - node_attrs = set(self.graph_solution.node_attr_keys()) - return key in node_attrs + # all_node_attr_keys, not node_attr_keys: a lean solution view does not list + # the columns it reads through to graph_full, and a feature that lives in one + # of them exists all the same - reporting it missing would recompute it. + return key in set(all_node_attr_keys(self.graph_solution)) def _setup_core_computed_features(self) -> None: """Sets up core computed position features. diff --git a/src/funtracks/import_export/_export_segmentation.py b/src/funtracks/import_export/_export_segmentation.py index 97f9e146..2445c98a 100644 --- a/src/funtracks/import_export/_export_segmentation.py +++ b/src/funtracks/import_export/_export_segmentation.py @@ -96,6 +96,8 @@ def export_segmentation( shape = tracks.segmentation.shape if label_attr is not None: + # A subgraph of a lean solution view inherits its key list and its root + # fallback, so the masks this renders are fetched from graph_full per chunk. graph = ( tracks.graph_solution.filter(node_ids=list(node_ids)).subgraph() if node_ids is not None diff --git a/src/funtracks/import_export/geff/_export.py b/src/funtracks/import_export/geff/_export.py index 0662dfab..5ca9ea71 100644 --- a/src/funtracks/import_export/geff/_export.py +++ b/src/funtracks/import_export/geff/_export.py @@ -240,9 +240,15 @@ def split_position_attr(tracks: Tracks) -> tuple[td.graph.GraphView, list[str] | """ pos_key = tracks.features.position_key + # Not graph_solution: that view may be lean (built without the mask column, which + # it reads through to graph_full on demand), and both `detach()` and `to_geff()` + # copy the columns the view itself holds rather than querying for the rest - so a + # lean view would write a geff whose masks are all null. + solution = tracks._solution_view_all_attrs() + if isinstance(pos_key, str): # Position is stored as a single attribute, need to split - new_graph = tracks.graph_solution.detach() + new_graph = solution.detach() new_graph = new_graph.filter().subgraph() # Register new attribute keys @@ -275,6 +281,6 @@ def split_position_attr(tracks: Tracks) -> tuple[td.graph.GraphView, list[str] | return new_graph, new_keys elif pos_key is not None: # Position is already split into separate attributes - return tracks.graph_solution, list(pos_key) + return solution, list(pos_key) else: - return tracks.graph_solution, None + return solution, None diff --git a/src/funtracks/utils/tracksdata_utils.py b/src/funtracks/utils/tracksdata_utils.py index e4287006..bf9ab71f 100644 --- a/src/funtracks/utils/tracksdata_utils.py +++ b/src/funtracks/utils/tracksdata_utils.py @@ -234,6 +234,101 @@ def create_empty_graphview_graph(*args: Any, **kwargs: Any) -> td.graph.GraphVie ).subgraph() +# Node attribute columns a lean solution view leaves out (see `solution_view`). +# `mask` is pickled blob data - gigabytes on a multi-million-node database - that +# nothing reads from the view: the segmentation is rendered by `GraphArrayView`, which +# fetches masks from the root per chunk. `bbox` stays local on purpose: the R-tree +# GraphArrayView queries is built on the view, and keeping that spatial index local is +# what makes each root lookup cheap (one chunk, not a whole timepoint). +_LEAN_VIEW_EXCLUDED = frozenset({td.DEFAULT_ATTR_KEYS.MASK}) + + +def solution_view( + graph: td.graph.BaseGraph, lean: bool | None = None +) -> td.graph.GraphView: + """Build the ``solution == True`` view of a base graph. + + ViewMode.LIVE: the root pushes its attribute writes (and new attr keys) back into + the view. funtracks writes values/schema on graph_full and reads them via + graph_solution, so the view must stay live. Views default to WRITE_THROUGH (no + root->view propagation) since tracksdata rc10, so this is required. + + A *lean* view is built without ``_LEAN_VIEW_EXCLUDED`` and with + ``root_fallback=True``, so a read for one of those keys is served from the root + instead of raising. That skips reading and unpickling every mask into the view, + which is most of the cost of building it on a database-backed graph. + + Args: + graph: The base graph to view. + lean: Whether to leave the excluded columns out. None decides by backend: a + rustworkx-backed view shares the root's attribute dicts, so leaving a + column out of it frees nothing and only adds a root lookup per read; a + view over a graph with its own storage (e.g. SQLGraph) does not share. + + Returns: + The live solution view. + """ + if lean is None: + lean = not isinstance(graph, td.graph.RustWorkXGraph) + keys = [key for key in graph.node_attr_keys() if key not in _LEAN_VIEW_EXCLUDED] + solution = graph.filter( + td.NodeAttr("solution") == True, # noqa: E712 + td.EdgeAttr("solution") == True, # noqa: E712 + ) + if not lean or len(keys) == len(graph.node_attr_keys()): + return solution.subgraph(mode=td.graph.ViewMode.LIVE) + # Name the keys to *keep*, never the ones to drop: a live view materialises any + # attr key later added to the root, so a column can only be left out at + # construction. Later additions (e.g. from enable_features) join the view + # regardless, which is fine - they are small scalars. + return solution.subgraph( + mode=td.graph.ViewMode.LIVE, node_attr_keys=keys, root_fallback=True + ) + + +def all_node_attr_keys(graph: td.graph.BaseGraph) -> list[str]: + """Every node attribute key a graph can serve, not just the ones it stores. + + ``graph.node_attr_keys()`` on a lean view (see ``solution_view``) lists only its + local columns, so a membership test like ``"mask" in graph.node_attr_keys()`` is + False even though reading ``mask`` works - the danger being that such a test takes + a "no masks here" branch silently rather than raising. + + A shim for a gap in tracksdata: a view knows which keys it can serve (its own plus + its root's) but has no API that says so. Expected to collapse into an upstream + accessor (``available_node_attr_keys()``). + + Args: + graph: The graph or view to inspect. + + Returns: + The view's own keys plus any it reads through to its root, ids included. + """ + keys = graph.node_attr_keys(return_ids=True) + if getattr(graph, "_root_fallback", False): + root_keys = graph._root.node_attr_keys(return_ids=True) + keys = list(dict.fromkeys([*keys, *root_keys])) + return keys + + +def all_node_attrs(graph: td.graph.BaseGraph) -> pl.DataFrame: + """Every node attribute of a graph, as a DataFrame. + + Like ``graph.node_attrs()``, except that a bare ``node_attrs()`` on a lean view + returns only the columns it holds locally - deliberately, since a fallback would + undo the point of leaving them out - so the excluded ones have to be asked for by + name. See ``all_node_attr_keys``. + + Args: + graph: The graph or view to read. + + Returns: + A DataFrame with one row per node, holding the view's own columns plus any + the view reads through to its root. + """ + return graph.node_attrs(attr_keys=all_node_attr_keys(graph)) + + def assert_node_attrs_equal_with_masks( object1, object2, check_column_order: bool = False, check_row_order: bool = False ): @@ -244,8 +339,8 @@ def assert_node_attrs_equal_with_masks( if isinstance(object1, td.graph.BaseGraph) and ( isinstance(object2, td.graph.BaseGraph) ): - node_attrs1 = object1.node_attrs() - node_attrs2 = object2.node_attrs() + node_attrs1 = all_node_attrs(object1) + node_attrs2 = all_node_attrs(object2) elif isinstance(object1, pl.DataFrame) and isinstance(object2, pl.DataFrame): node_attrs1 = object1 node_attrs2 = object2 diff --git a/tests/actions/test_add_delete_nodes.py b/tests/actions/test_add_delete_nodes.py index b716355c..dd0105c1 100644 --- a/tests/actions/test_add_delete_nodes.py +++ b/tests/actions/test_add_delete_nodes.py @@ -10,6 +10,7 @@ AddNode, ) from funtracks.utils.tracksdata_utils import ( + all_node_attrs, assert_node_attrs_equal_with_masks, create_empty_graph, ) @@ -89,8 +90,10 @@ def test_add_delete_nodes(get_tracks, ndim, with_seg): action = ActionGroup(tracks=tracks, actions=actions) assert set(tracks.graph_solution.node_ids()) == set(reference_graph.node_ids()) - data_tracks = tracks.graph_solution.node_attrs() - data_reference = reference_graph.node_attrs() + # all_node_attrs, not node_attrs: on a database-backed graph the solution view is + # lean and leaves the mask column to graph_full. + data_tracks = all_node_attrs(tracks.graph_solution) + data_reference = all_node_attrs(reference_graph) if with_seg: assert_array_almost_equal(tracks.segmentation, reference_seg) assert_node_attrs_equal_with_masks(data_tracks, data_reference) @@ -113,8 +116,8 @@ def test_add_delete_nodes(get_tracks, ndim, with_seg): # Re-invert the action to add back all the nodes and their attributes del_nodes.inverse() assert set(tracks.graph_solution.node_ids()) == set(reference_graph.node_ids()) - data_tracks = tracks.graph_solution.node_attrs() - data_reference = reference_graph.node_attrs() + data_tracks = all_node_attrs(tracks.graph_solution) + data_reference = all_node_attrs(reference_graph) if with_seg: assert_array_almost_equal(tracks.segmentation, reference_seg) assert_node_attrs_equal_with_masks(data_tracks, data_reference) diff --git a/tests/data_model/test_display_segmentation.py b/tests/data_model/test_display_segmentation.py new file mode 100644 index 00000000..1cc06905 --- /dev/null +++ b/tests/data_model/test_display_segmentation.py @@ -0,0 +1,175 @@ +import numpy as np +import pytest +import tracksdata as td +from tracksdata.array import GraphArrayView +from tracksdata.nodes import Mask + +from funtracks.data_model import Tracks +from funtracks.utils.tracksdata_utils import create_empty_graph + + +@pytest.fixture +def thin_mask_tracks(tmp_path, backend) -> Tracks: + """Tracks whose masks are single voxels, thinner than any downscale factor. + + The "every node renders" property only has teeth when the single-voxel fallback + in ``Mask.paint_buffer`` actually fires, which chunky fixture masks never do. + + Nodes are spaced so that no two share an output voxel at the factors tested: a + voxel covered by more than one object takes an unspecified value, so overlap + would exercise tie-breaking rather than the fallback. + """ + graph = create_empty_graph( + node_attributes=[td.DEFAULT_ATTR_KEYS.MASK, td.DEFAULT_ATTR_KEYS.BBOX], + node_default_values=[0.0, 0.0], + database=":memory:" if backend == "sql" else str(tmp_path / "thin.db"), + ndim=3, + backend=backend, + ) + node_ids, node_attrs = [], [] + for node_id, (t, y, x) in enumerate( + [(0, 3, 3), (0, 40, 41), (0, 60, 61), (1, 3, 3), (1, 90, 90)], start=1 + ): + mask = Mask(np.ones((1, 1), dtype=bool), bbox=np.array([y, x, y + 1, x + 1])) + node_ids.append(node_id) + node_attrs.append( + { + "t": t, + "solution": True, + td.DEFAULT_ATTR_KEYS.MASK: mask, + td.DEFAULT_ATTR_KEYS.BBOX: mask.bbox, + } + ) + graph.bulk_add_nodes(nodes=node_attrs, indices=node_ids) + graph.metadata["shape"] = (2, 100, 100) + return Tracks(graph, ndim=3, time_attr="t") + + +def _labels_at(array, t: int) -> set[int]: + return set(np.unique(np.array(array[t]))) - {0} + + +@pytest.mark.parametrize("downscale", [(2, 2), (4, 4), (1, 8), (16, 16)]) +def test_every_node_renders_at_any_factor(thin_mask_tracks, downscale): + """The coarse view draws every node, which is what keeps cells selectable.""" + tracks = thin_mask_tracks + view = tracks.display_segmentation(downscale) + for t in range(2): + expected = { + node + for node in tracks.graph_solution.node_ids() + if tracks.get_time(node) == t + } + assert _labels_at(view, t) == expected + + +def test_coarse_shape(get_tracks): + tracks = get_tracks(ndim=4, with_seg=True) + view = tracks.display_segmentation((1, 4, 4)) + assert tracks.segmentation.shape == (5, 100, 100, 100) + assert view.shape == (5, 100, 25, 25) + assert view.downscale == (1, 4, 4) + + +def test_scalar_factor_broadcasts(get_tracks): + tracks = get_tracks(ndim=4, with_seg=True) + assert tracks.display_segmentation(4).downscale == (4, 4, 4) + + +def test_views_are_cached_per_factor(get_tracks): + tracks = get_tracks(ndim=3, with_seg=True) + assert tracks.display_segmentation((4, 4)) is tracks.display_segmentation(4) + assert tracks.display_segmentation((4, 4)) is not tracks.display_segmentation((2, 2)) + + +def test_unit_factor_returns_the_full_resolution_array(get_tracks): + """`view is tracks.segmentation` is the cheapest form of the "am I coarse" check.""" + tracks = get_tracks(ndim=3, with_seg=True) + assert tracks.display_segmentation((1, 1)) is tracks.segmentation + assert tracks.display_segmentation(1) is tracks.segmentation + + +def test_none_without_segmentation(get_tracks): + tracks = get_tracks(ndim=3, with_seg=False) + assert tracks.segmentation is None + assert tracks.display_segmentation((4, 4)) is None + + +def test_time_first_length_is_rejected_with_a_hint(get_tracks): + tracks = get_tracks(ndim=4, with_seg=True) + with pytest.raises(ValueError, match="time-first"): + tracks.display_segmentation((1, 1, 4, 4)) + + +@pytest.mark.parametrize("bad", [(4, 4, 4, 4, 4), (4,), (1.5, 2, 2), (1, 0, 2)]) +def test_invalid_factors_rejected(get_tracks, bad): + tracks = get_tracks(ndim=4, with_seg=True) + with pytest.raises(ValueError): + tracks.display_segmentation(bad) + + +def test_full_resolution_array_is_untouched(get_tracks): + """§4.1: requesting a display view must not change the authoritative array.""" + tracks = get_tracks(ndim=3, with_seg=True) + before = np.array(tracks.segmentation[0]) + seg = tracks.segmentation + tracks.display_segmentation((8, 8)) + assert tracks.segmentation is seg + assert tracks.segmentation.shape == (5, 100, 100) + assert tracks.segmentation.dtype == before.dtype + np.testing.assert_array_equal(np.array(tracks.segmentation[0]), before) + + +def test_assigning_a_coarse_view_to_segmentation_is_rejected(get_tracks): + """The one failure mode in this design that would otherwise be silent.""" + tracks = get_tracks(ndim=3, with_seg=True) + coarse = tracks.display_segmentation((4, 4)) + with pytest.raises(ValueError, match="downscaled"): + tracks.segmentation = coarse + assert tracks.segmentation.shape == (5, 100, 100) + + +def test_assigning_a_full_resolution_view_is_allowed(get_tracks): + tracks = get_tracks(ndim=3, with_seg=True) + tracks.segmentation = GraphArrayView( + graph=tracks.graph_solution, + shape=(5, 100, 100), + attr_key="node_id", + offset=0, + ) + assert tracks.segmentation.downscale == (1, 1) + + +def test_display_view_inherits_the_dtype(get_tracks): + """Inherited rather than re-inferred: the probe is a full node_id column read.""" + tracks = get_tracks(ndim=3, with_seg=True) + assert tracks.display_segmentation((4, 4)).dtype == tracks.segmentation.dtype + + +def test_display_scale(get_tracks): + tracks = get_tracks(ndim=4, with_seg=True) + tracks.scale = [1.0, 1.97, 0.485, 0.485] + assert tracks.display_scale((1, 4, 4)) == pytest.approx([1.0, 1.97, 1.94, 1.94]) + assert tracks.display_scale((1, 1, 1)) == pytest.approx(tracks.scale) + + +def test_display_scale_is_none_without_scale_metadata(get_tracks): + """Never manufacture a scale out of the factors alone: it would look valid.""" + tracks = get_tracks(ndim=4, with_seg=True) + assert tracks.scale is None + assert tracks.display_scale((1, 4, 4)) is None + + +def test_export_is_unaffected_by_an_existing_display_view(get_tracks, tmp_path): + """§4.1's silent failure: a coarse shape sizing a full-resolution render.""" + import zarr + + from funtracks.import_export._export_segmentation import export_segmentation + + tracks = get_tracks(ndim=3, with_seg=True) + tracks.display_segmentation((8, 8)) + out = tmp_path / "seg.zarr" + export_segmentation(tracks, out, file_format="zarr") + exported = zarr.open(str(out), mode="r") + assert exported.shape == (5, 100, 100) + np.testing.assert_array_equal(exported[0], np.array(tracks.segmentation[0])) diff --git a/tests/data_model/test_lean_solution_view.py b/tests/data_model/test_lean_solution_view.py new file mode 100644 index 00000000..85650e91 --- /dev/null +++ b/tests/data_model/test_lean_solution_view.py @@ -0,0 +1,185 @@ +"""The lean ``graph_solution``: built without the blob columns nothing reads from it +(currently ``mask``), which are read through to ``graph_full`` on demand +(``root_fallback=True``, royerlab/tracksdata#340).""" + +import numpy as np +import tracksdata as td + +from funtracks.data_model import Tracks +from funtracks.utils.tracksdata_utils import ( + _LEAN_VIEW_EXCLUDED, + all_node_attr_keys, + create_empty_graph, +) + +track_attrs = {"time_attr": "t", "tracklet_attr": "track_id"} + + +def test_lean_by_backend(graph_2d_with_segmentation): + """Auto mode is lean only where it saves something: a rustworkx-backed view shares + the root's attribute dicts, so leaving a column out of it frees nothing.""" + graph = graph_2d_with_segmentation + tracks = Tracks(graph, ndim=3, **track_attrs) + + rx_rooted = isinstance(graph, td.graph.RustWorkXGraph) + assert ("mask" in tracks.graph_solution.node_attr_keys()) is rx_rooted + # graph_full always holds it, whichever view was built. + assert "mask" in tracks.graph_full.node_attr_keys() + + +def test_membership_tests_need_all_node_attr_keys(graph_2d_with_segmentation): + """The trap a lean view sets: `"mask" in graph_solution.node_attr_keys()` is False + while reading mask works, so a membership test takes a "no masks" branch silently. + + all_node_attr_keys is the answer to "what can I ask this graph for", and feature + detection uses it - otherwise a feature stored in an excluded column looks missing + and gets recomputed. + """ + tracks = Tracks( + graph_2d_with_segmentation, ndim=3, **track_attrs, lean_solution_view=True + ) + + assert "mask" not in tracks.graph_solution.node_attr_keys() + assert "mask" in all_node_attr_keys(tracks.graph_solution) + assert tracks._check_existing_feature("mask") + # A key on neither the view nor its root is still absent, and still raises on read. + assert "nope" not in all_node_attr_keys(tracks.graph_solution) + assert not tracks._check_existing_feature("nope") + + +def test_lean_view_reads_masks_from_graph_full(graph_2d_with_segmentation): + """The claim: the view does not hold the column, but the masks still read.""" + tracks = Tracks( + graph_2d_with_segmentation, ndim=3, **track_attrs, lean_solution_view=True + ) + assert "mask" not in tracks.graph_solution.node_attr_keys() + + for node in tracks.graph_solution.node_ids(): + through_view = ( + tracks.graph_solution.filter(node_ids=[node]) + .node_attrs(attr_keys=["mask"])["mask"] + .item() + ) + on_root = tracks.graph_full.nodes[node]["mask"] + assert np.array_equal(through_view.mask, on_root.mask) + assert np.array_equal(through_view.bbox, on_root.bbox) + assert np.array_equal(tracks.get_mask(node).mask, on_root.mask) + + +def test_lean_view_reads_only_the_views_nodes(graph_2d_with_segmentation): + """A fallback read must not leak the soft-deleted nodes graph_full still has.""" + tracks = Tracks( + graph_2d_with_segmentation, ndim=3, **track_attrs, lean_solution_view=True + ) + deleted = int(tracks.graph_solution.node_ids()[0]) + tracks.graph_full.update_node_attrs(attrs={"solution": [False]}, node_ids=[deleted]) + tracks.graph_solution.remove_node_from_view(deleted) + + df = tracks.graph_solution.node_attrs(attr_keys=["node_id", "mask"]) + assert set(df["node_id"]) == set(tracks.graph_solution.node_ids()) + assert deleted not in set(df["node_id"]) + + +def test_lean_view_renders_the_same_segmentation(graph_2d_with_segmentation): + """The end-to-end assertion: identical arrays with and without a lean view.""" + graph = graph_2d_with_segmentation + lean = Tracks(graph, ndim=3, **track_attrs, lean_solution_view=True) + full = Tracks(graph, ndim=3, **track_attrs, lean_solution_view=False) + + assert lean.segmentation is not None and full.segmentation is not None + for t in range(lean.segmentation.shape[0]): + np.testing.assert_array_equal( + np.asarray(lean.segmentation[t]), np.asarray(full.segmentation[t]) + ) + + +def test_lean_view_mask_edit_reads_back(graph_2d_with_segmentation): + """A mask written through the lean view lands on graph_full, reads back through the + view, and shows up in the rendered array. There is no local copy to go stale.""" + tracks = Tracks( + graph_2d_with_segmentation, ndim=3, **track_attrs, lean_solution_view=True + ) + node = int(tracks.graph_solution.node_ids()[0]) + time = tracks.get_time(node) + + old_mask = tracks.get_mask(node) + new_array = np.zeros_like(old_mask.mask) + new_array[0, 0] = True + tracks.update_mask(node, td.nodes.Mask(new_array, bbox=old_mask.bbox)) + + read_back = ( + tracks.graph_solution.filter(node_ids=[node]) + .node_attrs(attr_keys=["mask"])["mask"] + .item() + ) + assert np.array_equal(read_back.mask, new_array) + assert np.array_equal(tracks.graph_full.nodes[node]["mask"].mask, new_array) + assert (np.asarray(tracks.segmentation[time]) == node).sum() == 1 + + +def test_no_mask_column_is_never_lean(): + """Points-only tracks have nothing to exclude, so the flag stays False even on a + backend where a lean view would otherwise pay off.""" + graph = create_empty_graph( + node_attributes=["pos"], node_default_values=[0.0], backend="sql" + ) + graph.bulk_add_nodes([{"t": 0, "pos": [1.0, 2.0]}, {"t": 1, "pos": [3.0, 4.0]}]) + tracks = Tracks(graph, ndim=3, time_attr="t") + + assert set(tracks.graph_solution.node_attr_keys()) == set( + tracks.graph_full.node_attr_keys() + ) + + +def test_features_added_later_join_the_lean_view(graph_2d_with_segmentation): + """Only the excluded columns stay out. A column added after construction is + materialised in the live view like any other - they are small scalars.""" + tracks = Tracks( + graph_2d_with_segmentation, ndim=3, **track_attrs, lean_solution_view=True + ) + tracks.enable_features(["circularity"]) + + assert "circularity" in tracks.graph_solution.node_attr_keys() + assert _LEAN_VIEW_EXCLUDED.isdisjoint(tracks.graph_solution.node_attr_keys()) + + +def test_nested_subgraph_of_a_lean_view_serves_masks(graph_2d_with_segmentation): + """A subgraph of a lean view inherits its key list and its fallback, so it neither + claims the mask column nor serves schema defaults for it. + + Guards the tracksdata side of the pin: before that fix a nested view advertised the + root's columns while its payloads came from the lean parent, so masks read back as + null - silently, which is worse than the KeyError the fallback replaced. + """ + tracks = Tracks( + graph_2d_with_segmentation, ndim=3, **track_attrs, lean_solution_view=True + ) + subset = [int(node) for node in tracks.graph_solution.node_ids()[:2]] + + nested = tracks.graph_solution.filter(node_ids=subset).subgraph() + + assert "mask" not in nested.node_attr_keys() + assert set(nested.node_ids()) == set(subset) + masks = nested.node_attrs(attr_keys=["node_id", "mask"]) + for node, mask in zip(masks["node_id"], masks["mask"], strict=True): + assert mask is not None + assert np.array_equal(mask.mask, tracks.get_mask(node).mask) + + +def test_private_solution_view_all_attrs(graph_2d_with_segmentation): + """The export escape hatch: a view that holds every column, for code that copies + the view's own storage (detach, nested subgraph) rather than querying it.""" + graph = graph_2d_with_segmentation + tracks = Tracks(graph, ndim=3, **track_attrs, lean_solution_view=True) + + full_view = tracks._solution_view_all_attrs() + assert "mask" in full_view.node_attr_keys() + assert set(full_view.node_ids()) == set(tracks.graph_solution.node_ids()) + detached = full_view.detach() + for node in detached.node_ids(): + assert np.array_equal( + detached.nodes[node]["mask"].mask, tracks.get_mask(node).mask + ) + + not_lean = Tracks(graph, ndim=3, **track_attrs, lean_solution_view=False) + assert not_lean._solution_view_all_attrs() is not_lean.graph_solution diff --git a/tests/data_model/test_tracks.py b/tests/data_model/test_tracks.py index 73e4e10f..1df9010e 100644 --- a/tests/data_model/test_tracks.py +++ b/tests/data_model/test_tracks.py @@ -349,13 +349,17 @@ def test_delete_feature_mask_removes_both_columns( assert "mask" in tracks.features assert "bbox" in tracks.features - assert "mask" in tracks.graph_solution.node_attr_keys() - assert "bbox" in tracks.graph_solution.node_attr_keys() + # graph_full, not graph_solution: the solution view is lean on a database-backed + # graph and never holds the mask column itself. + assert "mask" in tracks.graph_full.node_attr_keys() + assert "bbox" in tracks.graph_full.node_attr_keys() tracks.delete_feature("mask") assert "mask" not in tracks.features assert "bbox" not in tracks.features + assert "mask" not in tracks.graph_full.node_attr_keys() + assert "bbox" not in tracks.graph_full.node_attr_keys() assert "mask" not in tracks.graph_solution.node_attr_keys() assert "bbox" not in tracks.graph_solution.node_attr_keys() diff --git a/tests/import_export/test_internal_format.py b/tests/import_export/test_internal_format.py index 8e9871b3..22510072 100644 --- a/tests/import_export/test_internal_format.py +++ b/tests/import_export/test_internal_format.py @@ -69,9 +69,12 @@ def test_save_load( else: assert loaded.segmentation is None - # graphs_equal doesn't exist for TracksData, so we check properties - assert set(loaded.graph_solution.node_attr_keys()) == set( - tracks.graph_solution.node_attr_keys() + # graphs_equal doesn't exist for TracksData, so we check properties. + # Node attr keys are compared on graph_full: the solution view is lean on a + # database-backed graph (no local mask column) and not on the loaded, in-memory + # one, so the views legitimately disagree while the data does not. + assert set(loaded.graph_full.node_attr_keys()) == set( + tracks.graph_full.node_attr_keys() ) assert set(loaded.graph_solution.edge_attr_keys()) == set( tracks.graph_solution.edge_attr_keys()