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
9 changes: 5 additions & 4 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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>=<release>" 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
Expand Down
159 changes: 148 additions & 11 deletions src/funtracks/data_model/tracks.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@
Time,
)
from funtracks.utils.tracksdata_utils import (
all_node_attr_keys,
solution_view,
to_polars_dtype,
)

Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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.
"""
Expand All @@ -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
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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.
Expand Down
2 changes: 2 additions & 0 deletions src/funtracks/import_export/_export_segmentation.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
12 changes: 9 additions & 3 deletions src/funtracks/import_export/geff/_export.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
99 changes: 97 additions & 2 deletions src/funtracks/utils/tracksdata_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
):
Expand All @@ -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
Expand Down
11 changes: 7 additions & 4 deletions tests/actions/test_add_delete_nodes.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
AddNode,
)
from funtracks.utils.tracksdata_utils import (
all_node_attrs,
assert_node_attrs_equal_with_masks,
create_empty_graph,
)
Expand Down Expand Up @@ -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)
Expand All @@ -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)
Expand Down
Loading
Loading