Multiresolution¶
Pyramid construction and the coarsening layer. coarsen is the
orchestrator; the per-geometry coarsening rules live in
multiresolution.strategies.
Pyramid construction¶
Coarsening orchestrator¶
Multi-resolution pyramid construction orchestrator.
Two entry points (use one):
build_pyramid(store, factors=[(cf_1, sf_1), ...])builds every coarser level in sequence, optionally emitting cross-level link arrays (cross_level_storage="implicit"or"explicit").coarsen_level(store, source, target, coarsen_factor=..., sparsity_factor=...)writes a single coarser level for callers that want manual control.
Both use the per-object pyramid: each surviving object’s vertices are aggregated into bin centroids (metavertices) that may be shared between objects, and per-object OIDs are preserved across levels.
- zarr_vectors_tools.multiresolution.coarsen.TOOLS_LEVEL_ATTRS_KEY: str = 'zarr_vectors_tools'¶
Level-group attribute key under which this package records coarsening parameters that core’s
LevelMetadatahas no field for.A sibling of core’s
zarr_vectors_levelblock rather than a key inside it.create_resolution_levelrewrites that block wholesale fromLevelMetadata.to_dict(), so an unknown key inside it is dropped the next time a writer restamps the level – which the polyline coarsener itself does once Phase A knows the vertex count – andupdate_level_metadatarefuses fields the dataclass does not declare. A separate top-level key is left alone by both, and core’s validation does not inspect it.
- zarr_vectors_tools.multiresolution.coarsen.build_pyramid(store_path, *, factors, chunk_scale_factors=None, sparsity_strategy='random', sparsity_seed=None, cross_level_depth=zarr_vectors.constants.DEFAULT_CROSS_LEVEL_DEPTH, cross_level_storage=zarr_vectors.constants.DEFAULT_CROSS_LEVEL_STORAGE, coarsen_mode='rdp', compressor=None, executor=None, method=None, rdp_tolerances=None, start_level=0, on_level_done=None)[source]¶
Build a multi-resolution pyramid for an existing store.
Pass
factors=[(coarsen_2, sparsity_3), ...]wherefactors[i]is applied to produce leveli+1from leveli. Either factor at1.0opts out of that axis. Uses the per-object pyramid: each surviving object’s vertices are aggregated into bin centroids (metavertices); metavertices may be shared between objects and OIDs are preserved across levels.- Parameters:
factors (list[tuple[float, float]]) – List of
(coarsen_factor, sparsity_factor)tuples, one per coarser level. Both are per-level ratios against the level below, so they compound:[(2, 1), (2, 1), (2, 1)]bins at 2x, 4x and 8x the root bin. (Sparsity was already cumulative viarelative_to="alive"; coarsening now matches it.)chunk_scale_factors (list[int | tuple[int, ...]] | None) – Optional per-level multipliers applied to the source level’s
chunk_shapeto derive each target level’schunk_shape. Aligned withfactors(same length). Each entry is either a scalar int (uniform per axis) or a per-axis tuple.None(default) means all-ones: every level inherits rootchunk_shape.sparsity_strategy (str) – Object selection strategy.
sparsity_seed (int | None) – Random seed.
cross_level_depth (int) – Maximum absolute level delta for materialized cross-pyramid-level link arrays.
0= none,N= up to±Nper pair (or+Nonly whencross_level_storage='implicit'),-1= walk all available level pairs. Default1.cross_level_storage (str) –
"none"/"implicit"/"explicit"."explicit"materializes both+N(at the finer level) and-N(at the coarser level);"implicit"writes only+N. Default"explicit".coarsen_mode (str) – Only consulted for streamline/polyline stores:
"rdp"(default) does Douglas-Peucker simplification;"decimate"does uniform stride decimation, in which case each level’scoarsen_factoris interpreted as the stride.executor (Any) – Optional
map-like(func, items, shared) -> list[result]callable forwarded to every level’scoarsen_level()call, parallelizing the chunk-local skeleton/polyline coarseners.None(default) runs serially.rdp_tolerances (Sequence[float] | None) – Explicit Douglas-Peucker tolerance per coarser level, aligned with
factors(same length), in store coordinate units – millimetres for a tractogram in RAS mm. Leveli+1is simplified so that no vertex of levelilies further thanrdp_tolerances[i]from it; deviation from level 0 is therefore bounded by the sum of the tolerances up to that level.None(default) keeps the derived tolerance, half the smallest edge of each level’s bin, which compounds with the factors. With explicit tolerances the coarsen factors still set each level’sbin_shape(its NGFF scale) but no longer decide how much is simplified. Refused withcoarsen_mode="decimate"and for stores not coarsened by the polyline coarsener – points, meshes, skeletons, graphs – before any level is written.start_level (int) – How many of the levels
factorsdescribes already exist and are complete; building starts at levelstart_level + 1. For resuming a pyramid that stopped partway – the caller removes any half-written level first.on_level_done (Callable[[int, dict[str, Any]], None] | None) – Called as
on_level_done(level, summary)after each level is written, so a caller can record progress.compressor (Any)
method (str | None)
- Returns:
Summary dict.
- Return type:
- zarr_vectors_tools.multiresolution.coarsen.check_rdp_tolerance(value, *, name='rdp_tolerance')[source]¶
valueas a float, or raise namingnameif it is no tolerance.Zero and negative values are refused rather than read as “simplify nothing”. The worker does treat a non-positive epsilon as a no-op, but a caller who wants no simplification has
coarsen_factor=1for that, and a level recording a tolerance of 0 would read as though one applied.
- zarr_vectors_tools.multiresolution.coarsen.coarsen_level(store_path, source_level, target_level, *, coarsen_factor=1.0, sparsity_factor=1.0, chunk_scale_factor=1, sparsity_strategy='random', sparsity_seed=None, cross_level_storage=zarr_vectors.constants.XLEVEL_NONE, coarsen_mode='rdp', compressor=None, executor=None, method=None, rdp_tolerance=None)[source]¶
Coarsen a single level and write it to the store.
Per-object vertex aggregation with stable OIDs across levels. A metavertex’s source vertices may come from multiple source objects; the resulting metavertex appears in each of those objects’ manifests at the coarser level.
- Parameters:
source_level (int) – Level to read from.
target_level (int) – Level to write to (must not exist).
coarsen_factor (float) – Per-object vertex aggregation factor (>= 1), expressed as a ratio against the source level’s bin, not the root’s: the target bin is
source_level.bin_shape * coarsen_factor, seeded from the root’s effective bin at level 0. Factors therefore compound down a pyramid.1.0is the identity (no aggregation).sparsity_factor (float) – Object-dropping factor (≥ 1). Survivors keep their OIDs; dropped objects leave empty manifest slots.
1.0is the identity (no drop).chunk_scale_factor (int | tuple[int, ...]) – Per-axis multiplier applied to the source level’s
chunk_shapeto derive the target level’schunk_shape.1(default) keeps the chunk grid unchanged. Scalar values apply uniformly to every axis; tuples set per-axis multipliers. Each multiplier must be a positive integer (nested chunk grids). When the resulting target chunk_shape differs from the root chunk_shape it is stamped on the target level’sLevelMetadata.chunk_shape; otherwise the target inherits from root.sparsity_strategy (str) – Object selection strategy.
sparsity_seed (int | None) – Random seed.
cross_level_storage (str) – When called via
build_pyramidthis is threaded through to enable inline±1cross-level link emission. Standalone callers should leave it at the"none"default.coarsen_mode (str) – Only consulted by the polyline (streamline) coarsener:
"rdp"(default) does Douglas-Peucker simplification;"decimate"does uniform stride decimation, in which casecoarsen_factoris interpreted as the stride. Ignored by the other coarseners.compressor (Any) – Codec for the TARGET level’s per-chunk arrays.
None(default) stores raw. Each level’s codec is independent — a chunk array’s pipeline is fixed when it is created — so pass the same value the level-0 ingest used to keep a store uniform. Seezarr_vectors.encoding.compression.resolve_compressor().executor (Any) – Optional
map-like(func, items, shared) -> list[result]callable (e.g.dask_executor) used by the chunk-local skeleton and polyline coarseners to parallelize per-target-chunk work.None(default) runs serially in-process. Ignored by the per-object coarsener.rdp_tolerance (float | None) – Explicit Douglas-Peucker tolerance for this level, in store coordinate units: every SOURCE-level vertex lies within this distance of the target level’s simplified line.
None(default) derives it as half the smallest edge of the target bin (source_level.bin_shape * coarsen_factor), or simplifies nothing whencoarsen_factor <= 1. Only the polyline coarsener inrdpmode has a tolerance, so a value is refused withcoarsen_mode="decimate"and for any store routed to another coarsener. Forwarded to the coarsener only when set, so coarseners registered without the keyword keep working. The tolerance used is recorded on the level; seeread_coarsening_record().method (str | None)
- Returns:
Summary dict. Always includes
method,preserves_object_ids,vertex_count.- Return type:
Skeleton stores (
links_convention = "implicit_sequential_with_branches") are routed to the skeleton-aware decimator (zarr_vectors_tools.multiresolution.strategies.skeletons.coarsen_skeleton_level()); for those storescoarsen_factoris interpreted as the decimationstride(keep every k-th vertex) rather than a vertex aggregation factor, andchunk_scale_factordefaults to 2.
- zarr_vectors_tools.multiresolution.coarsen.get_coarsener(key)[source]¶
Look up a registered coarsener; raise if none is registered.
- zarr_vectors_tools.multiresolution.coarsen.read_coarsening_record(root, level)[source]¶
The tools-owned coarsening record of one level, or
{}if it has none.Polyline levels built in
rdpmode carry:rdp_tolerance– the Douglas-Peucker tolerance the level was simplified at, in store coordinate units.Nonewhen nothing was simplified (acoarsen_factor <= 1with no explicit tolerance).rdp_tolerance_source–"explicit"when the caller supplied the tolerance,"derived"when it came from the level’s bin.
Levels written by other strategies, and stores written before the record existed, return
{}.
- zarr_vectors_tools.multiresolution.coarsen.register_coarsener(key, fn)[source]¶
Register (or override) the coarsener used for a dispatch
key.
- zarr_vectors_tools.multiresolution.coarsen.select_coarsener_key(root_meta)[source]¶
Pick the coarsener key for a store from its root metadata.
Skeleton stores (
implicit_sequential_with_branches) use the skeleton-aware decimator; mesh stores use chunk-local vertex clustering; streamline stores (implicit_sequentialwith geometry_type"streamline") use the RDP polyline coarsener; everything else uses the per-object pyramid.
- zarr_vectors_tools.multiresolution.coarsen.validate_rdp_tolerances(rdp_tolerances, *, n_levels, coarsen_mode, name='rdp_tolerances')[source]¶
Check a per-level explicit RDP tolerance list, without touching a store.
What can be checked from the arguments alone: one entry per coarser level, every entry a positive distance, and a coarsen mode that has a tolerance at all. Whether the store’s geometry goes through the RDP coarsener is checked by
build_pyramid(), which has the store. Ingesters that build the pyramid inline call this before their own (expensive) level-0 write, so a bad list fails before any work is done.
Object selection¶
Object selection strategies for multi-resolution sparsity.
Each strategy selects a subset of objects to retain at a coarser
resolution level. All functions return kept_indices — an array
of integer indices into the original object list.
Five strategies:
Spatial coverage: greedy selection maximising spatial spread
Length: keep the longest objects (streamlines, skeletons)
Attribute: keep objects with highest/lowest attribute values
Random: uniform random selection (reproducible with seed)
Group: stratified — a fraction of each group, floored at one, so no group is ever emptied
- zarr_vectors_tools.multiresolution.object_selection.apply_sparsity(n_objects, sparsity, strategy='random', *, seed=None, lengths=None, attribute_values=None, attribute_mode='max', representative_points=None, bin_shape=None, alive_mask=None, relative_to='original', group_labels=None, min_per_group=1)[source]¶
Convenience wrapper: compute target count from sparsity and dispatch.
- Parameters:
n_objects (int) – Total number of objects.
sparsity (float) – Fraction to keep, in (0, 1]. Ignored by the
"point_thinning"strategy, which derives the survivor count from thebin_shapeinstead.strategy (str) – One of
"random","length","attribute","spatial_coverage","point_thinning","group".seed (int | None) – Random seed (for
"random"/"point_thinning").lengths (ndarray[tuple[Any, ...], dtype[_ScalarT]] | None) – Per-object lengths (for
"length"strategy).attribute_values (ndarray[tuple[Any, ...], dtype[_ScalarT]] | None) – Per-object values (for
"attribute"strategy).attribute_mode (str) –
"max"or"min"(for"attribute").representative_points (ndarray[tuple[Any, ...], dtype[_ScalarT]] | None) –
(N, D)points (for"spatial_coverage"and"point_thinning").bin_shape (tuple[float, ...] | float | None) – Bin shape for spatial coverage / point thinning.
alive_mask (ndarray[tuple[Any, ...], dtype[bool]] | None) –
(n_objects,)boolean —Truefor object indices that still have data at the source level (e.g. object IDs preserved but emptied by an earlier pyramid level’s sparsity drop areFalse). When given, every strategy’s candidate pool is restricted to alive objects — without this,"random"selection has no way to avoid re-“keeping” already-empty objects, silently wasting most of its budget on them once enough earlier levels have dropped objects (the ranking-based strategies —"length"etc. — happen to dodge this only because a dead object’s length/attribute value is degenerate and never wins a top-N rank; that’s incidental, not guaranteed for every factor sequence). Omit (defaultNone) to consider every index a candidate, matching prior behavior.relative_to (Literal['original', 'alive']) – What
sparsityis a fraction of — the basis for the target survivor count."original"(default) keepstarget_count = round(n_objects * sparsity)— “keep N of the original population”, so withalive_maska constantsparsityreselects the same absolute count every level and, once the alive pool has shrunk to it, keeps everything."alive"computesround(len(candidates) * sparsity)instead — “keep that fraction of the surviving pool”, which makes repeated application cumulative (each level a fixed fraction of the previous). Pyramids want"alive"; direct callers that mean an absolute-of-original target keep the default.group_labels (ndarray[tuple[Any, ...], dtype[integer]] | None)
min_per_group (int)
- Returns:
Sorted array of kept object indices.
- Raises:
ValueError – If required data for the strategy is missing.
- Return type:
- zarr_vectors_tools.multiresolution.object_selection.compute_polyline_lengths(polylines)[source]¶
Compute Euclidean path length for each polyline.
- zarr_vectors_tools.multiresolution.object_selection.compute_representative_points(polylines)[source]¶
Compute the midpoint of each polyline (representative point).
- zarr_vectors_tools.multiresolution.object_selection.select_by_attribute(attribute_values, target_count, *, mode='max')[source]¶
Select objects with the highest or lowest attribute values.
Generic selection by any scalar per-object attribute (FA, volume, importance score, etc.).
- Parameters:
- Returns:
(target_count,)sorted array of kept object indices.- Raises:
ValueError – If mode is not
"max"or"min".- Return type:
- zarr_vectors_tools.multiresolution.object_selection.select_by_length(lengths, target_count)[source]¶
Select objects with the greatest lengths.
For streamlines,
lengthis the sum of segment Euclidean distances. For graphs, total edge length. For any geometry, a scalar measure of object size.
- zarr_vectors_tools.multiresolution.object_selection.select_by_spatial_coverage(representative_points, bin_shape, target_count)[source]¶
Select objects that maximise spatial coverage.
Assigns each object to a spatial bin by its representative point (e.g. midpoint for polylines, centroid for meshes). Distributes the
target_countbudget across bins proportional to each bin’s object density, ensuring every occupied bin keeps at least one representative.- Parameters:
- Returns:
(target_count,)sorted array of kept object indices.- Raises:
ValueError – If target_count is invalid.
- Return type:
- zarr_vectors_tools.multiresolution.object_selection.select_point_thinning(positions, bin_shape, *, seed=None)[source]¶
Spatially-aware point thinning: ≤1 point retained per spatial bin.
Distinct from
select_by_spatial_coverage(): that function distributes a fixedtarget_countbudget proportionally to each bin’s density; this one enforces a max of one survivor per bin and the resulting count is determined by the bin layout (≤ number of occupied bins). Useful for point-cloud levels where the goal is uniform density, not a target object count.- Parameters:
positions (ndarray[tuple[Any, ...], dtype[floating]]) –
(N, D)point positions.bin_shape (tuple[float, ...] | float) – Spatial bin edge lengths. Larger bins → fewer survivors.
seed (int | None) – Optional seed for selecting the survivor when a bin contains multiple candidates. When
None, the lowest-index candidate is kept (deterministic).
- Returns:
Sorted array of kept point indices, one per occupied bin.
- Return type:
- zarr_vectors_tools.multiresolution.object_selection.select_random(n_objects, target_count, *, seed=None)[source]¶
Select objects uniformly at random.
Reproducible with a fixed seed.
- zarr_vectors_tools.multiresolution.object_selection.select_stratified_by_group(group_labels, sparsity, *, seed=None, min_per_group=1)[source]¶
Keep a fraction of each group, never fewer than
min_per_group.Every other strategy draws from one global pool, which is fine when the population is homogeneous and destructive when it is not. A bundle atlas is the destructive case: sampling 1/4 of 85,989 streamlines four times over leaves ~336, and a bundle of four streamlines is gone long before that — measured on the Maffei BG pathways, sixteen of forty-three bundles disappeared by level 4. The taxonomy is the point of such a store, so a coarse level that has silently lost a third of it is not a coarse view of the data, it is different data.
Stratifying fixes that: each group is thinned by the same factor, so the proportions coarsen while the set of groups does not. The floor is what guarantees the second half — without it, a group of one rounds to zero at any factor above 1.
The survivor count therefore exceeds a global
target_countwhenever small groups are present, by roughly the number of groups that hit the floor. That is the cost of the guarantee, and it is bounded: at most one extra object per group per level.- Parameters:
group_labels (ndarray[tuple[Any, ...], dtype[integer]]) –
(N,)group id per object. Objects sharing an id are thinned together;-1(or any id) for the ungrouped forms its own stratum and is thinned like the rest.sparsity (float) – Fraction of each group to keep, in (0, 1].
seed (int | None) – Random seed. Groups are walked in sorted id order, so a fixed seed gives the same survivors every run.
min_per_group (int) – Floor per non-empty group.
1is what makes “no group is ever lost” true;0disables the guarantee.
- Returns:
Sorted array of kept object indices.
- Return type:
Pyramid refresh¶
Pyramid refresh after edits.
rebuild_pyramid_from_level() re-runs the existing
zarr_vectors_tools.multiresolution.coarsen.coarsen_level() engine for
every level above source_level, reusing each level’s existing
bin_ratio / object_sparsity / chunk_shape settings so the
post-refresh pyramid is byte-for-byte equivalent to a from-scratch
build_pyramid call.
Note: coarsen_level re-opens the store from a path/URL internally
and spawns its own backend session. When called inside an
EditSession the caller must have
already committed pending edits (otherwise the refresh will coarsen
the pre-edit state). EditSession.flush() handles this by
issuing a pre-refresh commit on icechunk-backed stores.
- zarr_vectors_tools.multiresolution.refresh.rebuild_pyramid_from_level(root, source_level, *, coarsen_factors=None, sparsity_strategy='random', sparsity_seed=None, compressor=None, executor=None)[source]¶
Re-coarsen every level above
source_levelfrom scratch.Reads each existing target level’s metadata (
bin_ratio,object_sparsity,chunk_shape,coarsening_method, and the tools-owned coarsening record’srdp_tolerance) and re-runszarr_vectors_tools.multiresolution.coarsen.coarsen_level()with the same parameters, replacing the old level data in place.The method each level was built with is re-applied, including the
rdp/decimatemode for polylines: recovering only the numeric factors rebuilt a decimated streamline pyramid with Douglas-Peucker instead (measured: 114 vertices became 42), which is a different level, not a refreshed one. Anrdplevel built with an explicit tolerance is rebuilt at that tolerance, read back from the level’s coarsening record (read_coarsening_record()); a derived one is derived again from the recovered bin, which gives the same value.- Parameters:
root (Group) – Open store handle.
source_level (int) – Every level ABOVE this one is rebuilt from it.
coarsen_factors (Mapping[int, float] | None) – Per-level override of the vertex-reduction factor,
{level: factor}. Required for levels whose factor the store does not record – today that is skeleton levels, where the factor is the decimation stride.sparsity_strategy (str) – Object-selection strategy, as
build_pyramid()takes it. The per-level fraction is recovered from the store; the strategy is not recorded there, so pass the one the pyramid was built with.sparsity_seed (int | None) – Seed for the random strategies. Advanced per level to match
build_pyramid.compressor (Any) – Codec for the rebuilt levels’ arrays. Each level’s codec is fixed when its arrays are created, so a refresh without this leaves raw levels under a compressed level 0.
executor (Any) –
map-like callable for the chunk-local coarseners.
- Returns:
The list of per-level coarsening summaries.
- Raises:
EditError – If a level cannot be faithfully reproduced – an unknown coarsening method, or one whose factor is unrecoverable and not supplied via
coarsen_factors.- Return type:
Supporting machinery¶
Metanodes¶
Metanode generation for multi-resolution pyramids.
A metanode represents a group of vertices within a coarser spatial bin. Its position is the centroid of the vertices it contains, and it carries aggregated attributes (mean, sum, or first value).
- zarr_vectors_tools.multiresolution.metanodes.generate_metanodes(positions, bin_size, *, attributes=None, agg_mode='mean')[source]¶
Group vertices into spatial bins and compute metanodes.
- Parameters:
positions (ndarray[tuple[Any, ...], dtype[floating]]) –
(N, D)vertex positions.bin_size (float | tuple[float, ...]) – Spatial bin edge length (scalar for isotropic, or per-dim).
attributes (dict[str, ndarray[tuple[Any, ...], dtype[_ScalarT]]] | None) – Optional per-vertex attributes to aggregate.
agg_mode (str) – Aggregation for attributes:
"mean","sum","first","count".
- Returns:
metanode_positions:(M, D)centroid positionsmetanode_counts:(M,)int — vertices per metanodechildren: list of M arrays, each containing global vertex indices belonging to that metanodemetanode_attributes:{name: (M, ...) array}aggregatedbin_coords:(M, D)int — grid coordinates of each bin
- Return type:
Dict with
Object index¶
Object-index reduce step (coordination).
build_object_index() groups the per-chunk (segment_id, chunk, fragment)
records emitted by the level-0 skeleton writer into a segment-id-preserving dense
object index, writing object_index + object_attributes/segment_id.
This is coordination, not a per-chunk IO primitive (it gathers every chunk’s
records to assign the global dense OID space), so it lives in zarr-vectors-tools
alongside the pyramid coordinators rather than in the core data-access SDK. It
calls only core IO primitives (write_object_index /
write_object_attributes).
- zarr_vectors_tools.multiresolution.object_index.build_object_index(level_group, records, *, ndim)[source]¶
Group per-chunk records by segment_id → dense object index.
Writes
object_index(one manifest per object, dense IDs in sorted-segment-id order) andobject_attributes/segment_id(uint64) so skeletons can be pulled back out by original ID.
- zarr_vectors_tools.multiresolution.object_index.shard_rows_by_object(rows, *, rows_per_shard=250000)[source]¶
Cut object-index rows into shards of whole objects, in object-id order.
rows[:, 0]is the object id; the remaining columns are whatever the reducer needs (fragment index, chunk coords, …). Every row of an object lands in the same shard – a reducer needs all of an object’s fragments to write its manifest – and each shard is a contiguous, ascending id range of aboutrows_per_shardrows, the working set of one Phase C task. Rows of one object keep their input order.This is how the parallel coarseners hand their gathered rows to the object-index reduce. They used to bucket rows by
oid % shardsinto one temp file per (target chunk, shard) and read those back one by one; at 250k rows a shard the whole level’s rows are a few tens of megabytes of int64, which is the same order as the cross-chunk anchor arrays the same coordinators already gather inline.Returns
[]whenrowsis empty.
Skeleton graph preprocessing¶
Skeleton graph-preprocessing algorithms for the downsampling layer.
These are algorithmic helpers (not on-disk format access): they massage a
vertex set + undirected edges into the rooted-tree pieces that the format
writer (zarr_vectors.types.skeletons.write_skeleton_chunk(), via
zarr_vectors.types.skeletons.decompose_tree_to_paths()) then encodes.
split_components is consumed by skeleton coarsening
(zarr_vectors_tools.multiresolution.strategies.skeletons) and by foreign-format
ingest pipelines (e.g. precomputed .frags ingest in zarr-vectors-tools).
It deliberately lives in the multiresolution (downsampling) layer rather than
in the format-access types modules, which stay free of graph algorithms.
- zarr_vectors_tools.multiresolution.skeleton_graph.split_components(positions, edges, attributes=None, vertex_ids=None)[source]¶
Split a vertex set + undirected edges into rooted-tree pieces.
Each connected component becomes one piece, re-indexed to a compact
0..k-1local range and oriented as[child, parent]edges (BFS from the component’s lowest-index node as root; the root has no edge row). Components are returned in ascending order of their lowest-index member.- Parameters:
positions (ndarray[tuple[Any, ...], dtype[floating]]) –
(N, D)vertex positions.edges (ndarray[tuple[Any, ...], dtype[integer]]) –
(M, 2)undirected edges (any orientation).attributes (dict[str, ndarray[tuple[Any, ...], dtype[_ScalarT]]] | None) – Optional
{name: (N,) or (N, C)}per-vertex data.vertex_ids (ndarray[tuple[Any, ...], dtype[integer]] | None) – Optional
(N,)opaque ids carried through the re-indexing; each piece gets"vertex_ids"aligned to its local vertex order, so callers can locate a specific input vertex (e.g. a cross-chunk endpoint) within its component.
- Returns:
List of
{"positions", "edges", "attributes"[, "vertex_ids"]}dicts, one per connected component.- Return type:
Note: a pure-Python adjacency-list BFS is intentional here. Each call operates on one object’s (small) merged skeleton, and this runs ~1M times per coarsen level; a per-call
scipy.sparse.csgraphformulation is dominated by its constant setup cost on tiny graphs and benchmarks ~1.75× slower end-to-end. Vectorization for this layer must instead batch a whole chunk’s components into one graph (see the batched coarsener).
Implicit sequential coarsening¶
Per-(object, coarsened-chunk) fragment construction for the
implicit_sequential coarsening path.
The streamline / polyline pyramid keeps each surviving object’s path intact at the coarse level by walking the object’s source-level vertex sequence in order, splitting only when the coarsened-chunk-of-the-vertex changes. Within each per-chunk run, consecutive source vertices that fall in the same target bin collapse to a single metavertex (“bin reduction”). The result is a sequence of runs — one per contiguous coarsened-chunk visit by the object — that become the fragments at the next level.
Source-level cross-chunk edges whose endpoints both fall in the same coarsened chunk are absorbed into the merged run for that chunk; ones that still cross are handled later by remapping endpoints to the new chunk-local indices.
Pure-functions only — no zarr/store I/O — so the segmentation logic can be unit-tested directly.
- zarr_vectors_tools.multiresolution.coarsen_implicit.coarse_chunks_of(positions, target_chunk_shape)[source]¶
Return
(N, D)int64 array of coarsened-chunk coords per vertex.Floor-divides
positionsbytarget_chunk_shape. Returns an empty(0, D)array whenpositionsis empty.
- zarr_vectors_tools.multiresolution.coarsen_implicit.compute_chunk_fragment_starts(n_fragments_per_chunk, fragment_lengths_per_chunk)[source]¶
Cumulative starts of each fragment in its chunk’s flat vertex array.
Given how many vertices each fragment contributes (in fragment-index order), return per-chunk lists of starting offsets so that
chunk_local_vi(fragment_idx, position_in_fragment) = starts[chunk][fragment_idx] + position_in_fragment.- Parameters:
- Returns:
{chunk_coords: [start_0, start_1, ...]}.- Return type:
- zarr_vectors_tools.multiresolution.coarsen_implicit.positions_in_run(n, mv_per_vertex, coarse_chunk_per_vertex)[source]¶
Return
(run_idx_per_vertex, position_in_run_per_vertex).For each source vertex, report:
the index of the run it falls in (0-based, within the object’s ordered run list), and
its position inside that run after consecutive-duplicate deduplication (so duplicates in a row share the same position).
The
runslist returned bysegment_object_by_coarse_chunk()is mirrored by these two arrays:runs[r][1][p]is the metavertex visited by every source vertex withrun_idx == randposition_in_run == p.
- zarr_vectors_tools.multiresolution.coarsen_implicit.segment_object_by_coarse_chunk(mv_per_vertex, coarse_chunk_per_vertex)[source]¶
Split one object’s vertex walk into per-coarsened-chunk runs.
Walks the parallel arrays
mv_per_vertex(length N) andcoarse_chunk_per_vertex(shape(N, D)) in source-path order. Every change in the chunk coord starts a new run. Within each run, consecutive duplicate metavertex ids are collapsed.A path that re-enters the same coarsened chunk (e.g. A → B → A) produces two runs in A — they become two separate fragments at the coarse level.
- Parameters:
- Returns:
List of
(chunk_coords, [mv_id, ...])tuples in object-path order. Each list of mv ids is non-empty and has no consecutive duplicates. An empty input returns an empty list.- Return type:
Constants¶
Tools-owned constants for the multiresolution layer.
These are values the coarsening strategies agree on but core has no
opinion about — they describe how this package schedules and tags its
work, not anything on disk. They live here rather than in a strategy
module because both strategies and coarsen read them, and a shared
module is what keeps that from becoming a strategy↔strategy import.
- zarr_vectors_tools.multiresolution.constants.COARSEN_SKELETON: str = 'skeleton_simplify'¶
Coarsening-method tag for skeleton-aware pyramids. Recorded in level metadata so a reader can tell how a level was produced. Skeleton coarsening is a tools-owned strategy, so the tag is tools-owned too.
- zarr_vectors_tools.multiresolution.constants.COARSEN_SKELETON_BINS: str = 'skeleton_bin_contract'¶
Coarsening-method tag for the connected-bin metavertex strategy. Kept distinct from
COARSEN_SKELETONbecause the two produce materially different levels — stride decimation severs cross-chunk connectivity and bounds nothing, bin contraction preserves components and bounds error by the bin diagonal — and a reader must be able to tell which one made a level.
- zarr_vectors_tools.multiresolution.constants.CROSS_LINK_TASK_SHARD_AXIS: int = 4¶
Outer width per axis used to group cross-link cell writes into race-safe task partitions — one worker owns each partition.
Purely a task-granularity knob: it is NOT an on-disk value and has nothing to do with zarr sharding. Under the merged links layout a cell is (offsets_segment, source_chunk) and that maps 1:1 to the endpoint pair, so any partition of pairs across workers is already race-safe; this only bounds how many pairs one task takes.
Coarsening strategies¶
Skeletons¶
Skeleton-aware coarsening (path simplification).
Unlike the generic per-object metavertex binning in
zarr_vectors_tools.multiresolution.coarsen, skeletons need a
topology-preserving downsample: branch points and endpoints must
survive every level so the tree’s shape is recognizable, while the
many degree-2 vertices along smooth runs are decimated.
This module provides:
simplify_skeleton()— pure function: simplify one rooted tree (positions +[child, parent]edges) with Ramer–Douglas–Peucker along each unbranched chain, always keeping endpoints + branch points, aggregating per-vertex attributes (e.g.radius,cross_sectional_area) onto the survivors.coarsen_skeleton_level()— read one resolution level of alinks_convention="implicit_sequential_with_branches"store, simplify every (surviving) object’s per-chunk skeleton pieces, and write the coarser level with stable object IDs. Routed to fromzarr_vectors_tools.multiresolution.coarsen.coarsen_level()when the store’s links convention is the skeleton convention.
The coarsener treats each stored fragment as one connected skeleton
piece living entirely within a single chunk. Because coarser chunk
grids are nested (a target chunk is the union of chunk_scale source
chunks per axis), a simplified piece never straddles a target chunk
boundary, so each piece maps to exactly one fragment in one target
chunk. Cross-chunk links are intentionally not reconstructed (the
ingest convention is “ignore cross-chunk edges if missing”).
- zarr_vectors_tools.multiresolution.strategies.skeletons.build_skeleton_pyramid(store_path, *, strides, chunk_scale_factors=None, sparsity_factors=None, sparsity_strategy='length', sparsity_seed=None, attr_agg='max', drop_interior_below=0, boundary_offset_nm=None, compressor=None, executor=None, progress=False)[source]¶
Build a skeleton pyramid by repeated
coarsen_skeleton_level().strides[i](keep-every-kth) produces leveli+1from leveli. Optional per-levelchunk_scale_factors(default 2 per axis) andsparsity_factors(default 1.0 = keep all) are aligned withstrides.executor(amap-like callable) is threaded into each level to coarsen target chunks in parallel; levels stay sequential (leveli+1readsi). DefaultNone→ serial.progressis forwarded to every level.Returns a summary with one entry per produced level.
- zarr_vectors_tools.multiresolution.strategies.skeletons.coarsen_skeleton_level(store_path, source_level, target_level, *, stride=8, sparsity_factor=1.0, chunk_scale_factor=2, sparsity_strategy='length', sparsity_seed=None, attr_agg='max', drop_interior_below=0, boundary_offset_nm=None, compressor=None, executor=None, progress=False)[source]¶
Coarsen one skeleton level by uniform per-path decimation.
Reads
source_level(aimplicit_sequential_with_branchesstore written byzarr_vectors.types.skeletons.write_skeleton_chunk()), decimates every surviving object withdecimate_skeleton()(keep all branch points, endpoints, and chunk-boundary / cross-chunk vertices; otherwise keep everystride-th vertex), and writestarget_levelwith stable object IDs (dropped objects leave empty manifest slots).- Parameters:
target_level (int) – Source and (new) target levels.
stride (int) – Keep every
stride-th non-anchor vertex (~``stride``× reduction per level).8pairs withchunk_scale_factor=2(8× volume) to hold per-chunk size roughly constant.sparsity_factor (float) – Object-drop factor (≥1).
1.0keeps all objects. Survivors keep their OIDs.chunk_scale_factor (int | tuple[int, ...]) – Per-axis chunk-grid multiplier (target chunk_shape = source × factor). Default 2 (nested 2× grid).
sparsity_strategy (str) – Object-selection strategy (see
zarr_vectors_tools.multiresolution.object_selection)."length"drops shortest skeletons first.sparsity_seed (int | None) – RNG seed.
attr_agg (str) – Per-vertex attribute aggregation over collapsed runs.
progress (bool) – Print
[coarsen Lx->Ly]phase lines as the level is built. Off by default; the per-phase durations are returned undertimingseither way.source_level (int)
target_level
drop_interior_below (int)
compressor (Any)
executor (Any)
- Returns:
Summary dict.
- Return type:
- zarr_vectors_tools.multiresolution.strategies.skeletons.decimate_skeleton(positions, edges, *, stride=8, forced_keep=None, attributes=None, attr_agg='max')[source]¶
Uniformly decimate a rooted tree, keeping topology + anchors.
Simpler and more predictable than RDP: ALWAYS keep branch points, endpoints (leaves), roots, and any
forced_keepvertices (e.g. chunk-boundary / cross-chunk vertices); along each unbranched chain between two kept anchors, keep everystride-th vertex. This yields a ~``stride``× reduction per call regardless of geometry — and keeps reducing at deeper pyramid levels (RDP bottoms out once a skeleton is near-minimal).stride <= 1is the IDENTITY: every vertex is kept. It used to mean “keep anchors only”, the most aggressive setting this function has, which is the opposite of what a factor of 1 means everywhere else in the package (coarsen_leveldocuments 1.0 as “no aggregation”) and turned a pyramid refresh that could not recover the stride into a level with the interior of every chain deleted.Same return shape as
simplify_skeleton().- Parameters:
- Return type:
- zarr_vectors_tools.multiresolution.strategies.skeletons.simplify_skeleton(positions, edges, *, tolerance, attributes=None, attr_agg='max')[source]¶
Simplify one rooted tree, preserving endpoints and branch points.
- Parameters:
positions (ndarray[tuple[Any, ...], dtype[floating]]) –
(N, D)vertex positions.edges (ndarray[tuple[Any, ...], dtype[integer]]) –
(M, 2)[child, parent]tree edges (as stored for the skeleton convention).tolerance (float) – RDP perpendicular-distance threshold in position units (nm).
<= 0is the identity (no decimation).attributes (dict[str, ndarray[tuple[Any, ...], dtype[_ScalarT]]] | None) – Optional per-vertex attributes
{name: (N,) or (N, C)}. Each survivor aggregates the values of the source vertices that collapse onto it.attr_agg (str) – Aggregation for collapsed runs —
"max"(default),"mean","min", or"first".
- Returns:
Dict with
positions(K, D),edges(K-1 or fewer, 2)[child, parent]over the new indices,attributes(aggregated, same keys as input), andkept_source_indices(K,)mapping new index → original index. The result is NOT re-rooted/re-ordered here — callers that need DFS order + branch-link extraction run the existing_reorder_tree/_extract_branch_linkshelpers on it.- Return type:
Polylines¶
Polyline and streamline coarsening strategies.
Two complementary approaches:
Douglas-Peucker simplification: reduces vertex count within each polyline while preserving shape. Good for reducing per-streamline resolution while keeping all streamlines.
Spatial subsampling: selects a representative subset of streamlines per spatial bin. Good for reducing total streamline count while keeping full vertex resolution on survivors.
Both can be composed: simplify first, then subsample.
- zarr_vectors_tools.multiresolution.strategies.polylines.coarsen_polyline_level(store_path, source_level, target_level, *, coarsen_factor=1.0, sparsity_factor=1.0, chunk_scale_factor=1, sparsity_strategy='random', sparsity_seed=None, coarsen_mode='rdp', simplify_epsilon=None, compressor=None, executor=None)[source]¶
Coarsen one streamline/polyline level, chunk-local and executor-parallel.
Memory-bounded replacement for the whole-level
_polyline_coarsenincoarsen.py(which loaded every fragment, manifest, and per-object vertex sequence of the source level into memory at once — fine at 100K streamlines, an OOM at 5M). Peak memory here is O(one target chunk’s source fan-in), independent of dataset size; per-target-chunk work is dispatched throughexecutor(amap-like(func, items, shared)callable) so it can run on a dask worker pool. The default executor runs serially in-process, so serial output is identical to the parallel path by construction.Preserves every existing streamline-specific behavior: dense, stable object ids across levels (survivors keep their OID; dropped objects leave empty manifest slots),
rdp/decimatemode selection, and directed (predecessor -> successor) cross-chunk links so walk-order tangents stay correct after coarsening.Args: see
zarr_vectors_tools.multiresolution.coarsen.coarsen_level()for the shared parameter semantics.simplify_epsilonis the explicit Douglas-Peucker tolerance in store coordinate units (coarsen_level’srdp_tolerance);Nonederives0.5 * min(target_bin_shape)whencoarsen_factor > 1and simplifies nothing otherwise. It is refused indecimatemode, which has no tolerance. Inrdpmode the value used, and whether it was explicit or derived, is recorded on the target level (seezarr_vectors_tools.multiresolution.coarsen.read_coarsening_record()).- Parameters:
- Return type:
- zarr_vectors_tools.multiresolution.strategies.polylines.coarsen_polylines(polylines, *, simplify_epsilon=None, subsample_bin_size=None, max_per_bin=1, min_vertices=2, selection='longest')[source]¶
Combined polyline coarsening: simplify then subsample.
- Parameters:
polylines (list[ndarray[tuple[Any, ...], dtype[floating]]]) – Input polylines.
simplify_epsilon (float | None) – Douglas-Peucker epsilon. None to skip.
subsample_bin_size (float | None) – Spatial subsampling bin size. None to skip.
max_per_bin (int) – Polylines to keep per bin (for subsampling).
min_vertices (int) – Minimum vertices per polyline (for simplification).
selection (str) – Subsampling selection mode.
- Returns:
polylines: coarsened polylinesvertex_count: total verticespolyline_count: number of polylinessimplification_ratio: vertex reduction from DPsubsampling_ratio: polyline reduction from subsampling
- Return type:
Dict with
- zarr_vectors_tools.multiresolution.strategies.polylines.decimate_polyline(vertices, stride)[source]¶
Uniformly decimate a polyline, keeping every
stride-th vertex.The linear-path equivalent of skeleton decimation (
zarr_vectors_tools.multiresolution.strategies.skeletons.decimate_skeleton()): since a polyline has no branch points, its only anchors are the two endpoints, which are always kept.- Parameters:
- Returns:
(M, D)decimated polyline with M ≤ N vertices. First and last vertices are always preserved.- Return type:
- zarr_vectors_tools.multiresolution.strategies.polylines.simplify_polyline(vertices, epsilon)[source]¶
Simplify a polyline using Douglas-Peucker algorithm.
- Parameters:
- Returns:
(M, D)simplified polyline with M ≤ N vertices. First and last vertices are always preserved.- Return type:
- zarr_vectors_tools.multiresolution.strategies.polylines.simplify_polylines(polylines, epsilon, *, min_vertices=2)[source]¶
Simplify a list of polylines using Douglas-Peucker.
- zarr_vectors_tools.multiresolution.strategies.polylines.subsample_polylines(polylines, bin_size, *, max_per_bin=1, selection='longest')[source]¶
Spatially subsample polylines, keeping representatives per bin.
Assigns each polyline to the spatial bin containing its midpoint, then selects up to
max_per_binrepresentatives per bin.- Parameters:
polylines (list[ndarray[tuple[Any, ...], dtype[floating]]]) – List of
(N_k, D)arrays.bin_size (float | tuple[float, ...]) – Spatial bin edge length.
max_per_bin (int) – How many polylines to keep per bin.
selection (str) – How to pick representatives:
"longest": keep the longest polyline(s)."random": keep random polyline(s)."first": keep the first polyline(s) by index.
- Returns:
polylines: subsampled list of arraysindices: original indices of kept polylinespolyline_count: number keptreduction_ratio: original / kept
- Return type:
Dict with
Points¶
Point cloud coarsening strategy for multi-resolution pyramids.
Point clouds are the simplest case: metanodes are centroids of vertices within each spatial bin. Attributes are aggregated (mean, sum, or first). Object identity is preserved — if points carry object IDs, each metanode inherits the majority object ID of its children.
This strategy also supports density-preserving mode: instead of centroids, it selects the vertex closest to the centroid (medoid), which preserves the original coordinate precision.
- zarr_vectors_tools.multiresolution.strategies.points.build_point_subset_pyramid(store_path, *, levels=5, divisor=8.0, seed=0, source_level=0, attributes=True, attribute_names=None, attribute_batch=100, shard_shape=None, resume=False, progress=False)[source]¶
Build coarser levels, each a random subset of the level above.
The general
build_pyramid()does not fit an object-less point cloud: its sparsity factor drops objects, so a store whose points carry no object IDs is treated as a single object and every level comes out identical. Its coarseners also writevertices(and object attributes) only — per-vertex attributes are dropped, which for a cell atlas means the coarse levels cannot be coloured by gene or metadata.This builder addresses both: each level keeps a uniformly random
1/divisorof its parent’s points, and carries every per-vertex attribute across, so any level can be rendered and coloured exactly like level 0.Sampling is drawn from a seeded generator, so the same
seedgives the same pyramid. Levels nest — level n+1 is a subset of level n — which keeps a point’s appearance/disappearance monotonic as a viewer changes zoom.- Parameters:
store_path (str) – Store to add levels to (modified in place).
levels (int) – How many coarser levels to create.
divisor (float) – Keep
1/divisorof the parent’s points per level.seed (int) – Seed for the subset draw.
source_level (int) – Level to coarsen from.
attributes (bool) – Carry per-vertex attributes across. Turning this off makes the build dramatically faster but leaves the coarse levels geometry-only.
attribute_names (list[str] | None) – Attributes to carry (default: all at
source_level).attribute_batch (int) – Attributes read per pass. Bounds peak memory to roughly
batch x source_points x 4bytes.shard_shape (int | tuple[int, ...] | None) – Shard the new levels’ arrays (chunks per axis per file). Strongly recommended — an unsharded level costs one file per chunk per attribute.
resume (bool) – Keep levels that already exist and fill in only the attributes that are missing or partially written. The subsets are a pure function of
seed/divisor, so a resumed run reproduces them exactly; the level’s point count is checked against that reproduction before anything is written. Without this, an existing level is an error.progress (bool) – Print per-level and per-batch progress.
- Returns:
Summary dict with
levels_createdand alevel_specslist of per-level{level, vertex_count, chunk_count}.- Return type:
- zarr_vectors_tools.multiresolution.strategies.points.coarsen_points(positions, bin_size, *, attributes=None, object_ids=None, agg_mode='mean', use_medoid=False)[source]¶
Coarsen a point cloud to a lower resolution.
- Parameters:
positions (ndarray[tuple[Any, ...], dtype[floating]]) –
(N, D)vertex positions.bin_size (float | tuple[float, ...]) – Spatial bin edge length.
attributes (dict[str, ndarray[tuple[Any, ...], dtype[_ScalarT]]] | None) – Per-vertex attributes to aggregate.
object_ids (ndarray[tuple[Any, ...], dtype[integer]] | None) –
(N,)per-vertex object IDs. If provided, each metanode inherits the majority object ID.agg_mode (str) – Attribute aggregation mode.
use_medoid (bool) – If True, select the closest-to-centroid vertex instead of using the centroid itself.
- Returns:
positions:(M, D)coarsened positionsattributes:{name: array}aggregated attributesobject_ids:(M,)majority object IDs (if input had them)children: list of M arrays of parent vertex indicesvertex_count: Mreduction_ratio: N / M
- Return type:
Dict with
- zarr_vectors_tools.multiresolution.strategies.points.coarsen_points_store(store_path, target_level, bin_size, *, source_level=0, agg_mode='mean', use_medoid=False)[source]¶
Coarsen a point cloud store and write the result as a new level.
Reads positions from
source_level, coarsens, and writes totarget_levelin the same store.- Parameters:
store_path (str) – Path to the zarr vectors store.
target_level (int) – Resolution level to write (must not exist).
bin_size (float | tuple[float, ...]) – Spatial bin size for coarsening.
source_level (int) – Resolution level to read from.
agg_mode (str) – Attribute aggregation mode.
use_medoid (bool) – Use medoid instead of centroid.
- Returns:
Summary dict.
- Return type:
Meshes¶
Mesh coarsening strategies.
Two approaches:
Vertex clustering: merge vertices within spatial bins into metanodes, remap face indices, remove degenerate faces (collapsed to edges or points), and merge duplicate faces.
Quadric error decimation (simplified): iterative edge collapse using quadric error metrics for vertex placement. Falls back to vertex clustering when the optional
pyfqmris not available.
- zarr_vectors_tools.multiresolution.strategies.meshes.COARSENER_KEY: str = 'mesh'¶
Dispatch key for
coarsen_level().
- zarr_vectors_tools.multiresolution.strategies.meshes.COARSEN_MESH_CLUSTER: str = 'mesh_cluster'¶
Level-metadata tag recorded for levels this strategy produced.
- zarr_vectors_tools.multiresolution.strategies.meshes.coarsen_mesh_cluster(vertices, faces, bin_size, *, vertex_attributes=None, agg_mode='mean')[source]¶
Coarsen a mesh by clustering vertices within spatial bins.
Vertices in the same bin merge into a metanode (centroid). Face indices are remapped; faces that collapse to degenerate triangles (two or more vertices in the same bin) are removed.
- Parameters:
vertices (ndarray[tuple[Any, ...], dtype[floating]]) –
(V, D)vertex positions.faces (ndarray[tuple[Any, ...], dtype[integer]]) –
(F, L)face index array.bin_size (float | tuple[float, ...]) – Spatial bin edge length.
vertex_attributes (dict[str, ndarray[tuple[Any, ...], dtype[_ScalarT]]] | None) – Per-vertex attributes to aggregate.
agg_mode (str) – Attribute aggregation mode.
- Returns:
vertices:(K, D)metanode positionsfaces:(E, L)remapped faces (non-degenerate only)vertex_attributes: aggregated attributeschildren: list of K arrays of original vertex indicesvertex_count,face_countvertex_reduction: V / Kface_reduction: F / Edegenerate_faces_removed: count
- Return type:
Dict with
- zarr_vectors_tools.multiresolution.strategies.meshes.coarsen_mesh_level(store_path, source_level, target_level, *, coarsen_factor=2.0, sparsity_factor=1.0, chunk_scale_factor=1, sparsity_strategy='random', sparsity_seed=None, compressor=None, bin_size=None, **_ignored)[source]¶
Coarsen one mesh level by chunk-local vertex clustering.
Vertices within a bin of
source bin_shape x coarsen_factorcollapse to their centroid; faces are remapped onto the centroids and dropped when two or more of their corners land in the same bin. Object ids and the group taxonomy carry across unchanged, and each surviving object keeps one fragment per target chunk.
- zarr_vectors_tools.multiresolution.strategies.meshes.coarsen_mesh_quadric(vertices, faces, target_face_count=None, target_ratio=None, *, vertex_attributes=None)[source]¶
Coarsen a mesh using quadric error edge collapse.
Uses
pyfqmrif available; otherwise falls back to vertex clustering with an estimated bin size.- Parameters:
vertices (ndarray[tuple[Any, ...], dtype[floating]]) –
(V, 3)vertex positions (3D only).faces (ndarray[tuple[Any, ...], dtype[integer]]) –
(F, 3)triangle face indices.target_face_count (int | None) – Desired face count. Mutually exclusive with
target_ratio.target_ratio (float | None) – Fraction of faces to keep (0–1).
vertex_attributes (dict[str, ndarray[tuple[Any, ...], dtype[_ScalarT]]] | None) – Per-vertex attributes (interpolated if pyfqmr is used, aggregated otherwise).
- Returns:
Dict with vertex/face arrays, counts, and method used.
- Return type:
Graphs¶
Graph and skeleton coarsening strategies.
Two approaches:
Grid contraction: merge nodes in the same spatial bin into a metanode. Intra-bin edges collapse; inter-bin edges become metanode edges. Edge weights are summed or averaged.
Skeleton pruning: for tree-structured graphs, remove short terminal branches below a length threshold while preserving branch topology.
- zarr_vectors_tools.multiresolution.strategies.graphs.coarsen_graph(positions, edges, bin_size, *, node_attributes=None, edge_weights=None, agg_mode='mean')[source]¶
Coarsen a graph by contracting nodes within spatial bins.
Nodes in the same bin merge into a metanode (centroid position). Edges between different bins become metanode edges. Self-loops (intra-bin edges) are removed. Parallel edges are merged by summing weights.
- Parameters:
positions (ndarray[tuple[Any, ...], dtype[floating]]) –
(N, D)node positions.edges (ndarray[tuple[Any, ...], dtype[integer]]) –
(M, 2)edge list.bin_size (float | tuple[float, ...]) – Spatial bin edge length.
node_attributes (dict[str, ndarray[tuple[Any, ...], dtype[_ScalarT]]] | None) – Per-node attributes to aggregate.
edge_weights (ndarray[tuple[Any, ...], dtype[floating]] | None) –
(M,)edge weights. Default: all 1.0.agg_mode (str) – Node attribute aggregation mode.
- Returns:
positions:(K, D)metanode positionsedges:(E, 2)metanode edge listedge_weights:(E,)aggregated weightsnode_attributes: aggregated node attributeschildren: list of K arrays of original node indicesnode_count,edge_countreduction_ratio: original nodes / metanodes
- Return type:
Dict with
- zarr_vectors_tools.multiresolution.strategies.graphs.prune_skeleton(positions, edges, *, min_branch_length=0.0, min_branch_vertices=0, node_attributes=None)[source]¶
Remove short terminal branches from a skeleton tree.
A terminal branch is a path from a leaf to the nearest branch point (node with degree ≥ 3). Branches shorter than
min_branch_length(Euclidean path length) or with fewer thanmin_branch_verticesnodes are removed.- Parameters:
positions (ndarray[tuple[Any, ...], dtype[floating]]) –
(N, D)node positions.edges (ndarray[tuple[Any, ...], dtype[integer]]) –
(M, 2)edge list.min_branch_length (float) – Minimum Euclidean path length to keep.
min_branch_vertices (int) – Minimum node count to keep.
node_attributes (dict[str, ndarray[tuple[Any, ...], dtype[_ScalarT]]] | None) – Per-node attributes to filter.
- Returns:
positions: pruned positionsedges: pruned edges (remapped indices)node_attributes: filtered attributesnode_count,edge_countbranches_removed: count of pruned brancheskept_indices: original indices of surviving nodes
- Return type:
Dict with