Multiresolution

zarr_vectors_tools.multiresolution: build coarser levels. coarsen is the entry point; strategies holds the per-geometry rules. zvtools pyramid calls these; see Pyramids.

Pyramid building

Coarsen

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.

Points, graphs and lines use the per-object pyramid: each surviving object’s vertices are aggregated into bin centroids (metavertices), each object keeps its own row for a bin it shares with others, and per-object OIDs are preserved across levels. Other geometries are routed to their own coarseners (see select_coarsener_key()).

zarr_vectors_tools.multiresolution.coarsen.COARSENER_SPARSITY_STRATEGIES: dict[str, frozenset[str]] = {'mesh': frozenset({'attribute', 'random'}), 'mesh_decimate': frozenset({'random'}), 'per_fragment': frozenset({'attribute', 'random'}), 'per_object': frozenset({'attribute', 'group', 'length', 'point_thinning', 'random', 'spatial_coverage'}), 'polyline': frozenset({'attribute', 'group', 'length', 'random'}), 'skeleton': frozenset({'attribute', 'length', 'random'})}

The sparsity strategies each built-in coarsener selects by. The others lack the per-object signal a strategy ranks by (lengths, representative points, group labels) and would fail once their level is reached. A coarsener registered elsewhere is not listed and not checked.

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 LevelMetadata has no field for.

A sibling of core’s level zarr_vectors block rather than a key inside it. create_resolution_level rewrites that block wholesale from LevelMetadata.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 – and update_level_metadata refuses 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=1, cross_level_storage='explicit', coarsen_mode='rdp', compressor=None, executor=None, method=None, rdp_tolerances=None, start_level=0, on_level_done=None, sparsity_attribute=None, refinement='replace')[source]

Build a multi-resolution pyramid for an existing store.

Pass factors=[(coarsen_2, sparsity_3), ...] where factors[i] is applied to produce level i+1 from level i. Either factor at 1.0 opts out of that axis. Each level is written by the coarsener select_coarsener_key() picks for the store’s geometry (or method); object ids are preserved across levels.

Parameters:
  • store_path (str | Path) – Path to the store with level 0.

  • 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 via relative_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_shape to derive each target level’s chunk_shape. Aligned with factors (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 root chunk_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 ±N per pair (or +N only when cross_level_storage='implicit'), -1 = walk all available level pairs. Default 1.

  • 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". Each record links a vertex to the coarse vertex of the same object it was merged into. Only the per-object coarsener (points, graphs, lines) writes them; other geometries ignore both settings.

  • 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’s coarsen_factor is interpreted as the stride.

  • executor (Any) – Optional map-like (func, items, shared) -> list[result] callable forwarded to every level’s coarsen_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. Level i+1 is simplified so that no vertex of level i lies further than rdp_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 no longer decide how much is simplified; each level’s bin_shape (its NGFF scale) grows by its coarsen factor or its chunk scale, whichever is larger. Refused with coarsen_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 factors describes already exist and are complete; building starts at level start_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.

  • sparsity_attribute (str | None) – The object attribute sparsity_strategy= "attribute" ranks by; see coarsen_level().

  • refinement (str) – "replace" (default): every level is complete. "add": build the pyramid as usual, then make every level but the coarsest additive – holding only the objects (or points) no coarser level has – so each is stored once. Level 0 is rewritten in place and alone is no longer the whole dataset. Warns (AdditiveRefinementWarning) for a mesh, for any level that coarsens geometry, and for a level that drops nothing; streamline/polyline object sparsity with coarsen_factor 1 is exact and does not warn. See zarr_vectors_tools.multiresolution.additive.

  • compressor (Any)

  • method (str | None)

Returns:

Summary dict. method is the coarsener that built the levels (level_specs[i]["method"] per level). cross_level_depth and cross_level_storage describe the cross-level links actually written, as stamped on root metadata: only the per-object coarsener (points, graphs, lines) writes any, so other geometries report 0 and "none".

Return type:

dict[str, Any]

zarr_vectors_tools.multiresolution.coarsen.check_pyramid_request(store_path, *, factors, chunk_scale_factors=None, sparsity_strategy='random', sparsity_attribute=None, cross_level_depth=1, cross_level_storage='explicit', coarsen_mode='rdp', method=None, rdp_tolerances=None, start_level=0, refinement='replace')[source]

Refuse a build_pyramid() request before anything is written.

build_pyramid() runs this first. A caller that removes an old pyramid to make way for the new one runs it before removing anything, so a request that would be refused leaves the old pyramid where it was.

Returns the per-level RDP tolerances, checked, or None.

Parameters:
Return type:

list[float] | None

zarr_vectors_tools.multiresolution.coarsen.check_rdp_tolerance(value, *, name='rdp_tolerance')[source]

value as a float, or raise naming name if 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=1 for that, and a level recording a tolerance of 0 would read as though one applied.

Parameters:
Return type:

float

zarr_vectors_tools.multiresolution.coarsen.check_sparsity_strategy(key, strategy, factors)[source]

Refuse a sparsity strategy coarsener key cannot select by, when some level of factors drops objects. Needs no store, so a caller can run it before an ingest.

Parameters:
Return type:

None

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='none', coarsen_mode='rdp', compressor=None, executor=None, method=None, rdp_tolerance=None, sparsity_attribute=None)[source]

Coarsen a single level and write it to the store.

Per-object vertex aggregation with stable OIDs across levels. Points and paths (lines, polylines) merge every object’s vertices that share a bin into one centroid, which each of those objects stores as its own row. Graphs merge vertices only within one object and one connected component, and their coarse edges are exactly the images of the source level’s edges. See _per_object_coarsen().

Parameters:
  • store_path (str | Path) – Path to the zarr vectors store.

  • 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. For the per-object coarsener 1.0 still bins at the source level’s bin, which at level 1 is the root bin (the chunk shape unless bin_shape was set), so it is not the identity there.

  • sparsity_factor (float) – Object-dropping factor (≥ 1). Survivors keep their OIDs; dropped objects leave empty manifest slots. 1.0 is the identity (no drop).

  • chunk_scale_factor (int | tuple[int, ...]) – Per-axis multiplier applied to the source level’s chunk_shape to derive the target level’s chunk_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’s LevelMetadata.chunk_shape; otherwise the target inherits from root.

  • sparsity_strategy (str) – Object selection strategy.

  • sparsity_seed (int | None) – Random seed.

  • sparsity_attribute (str | None) – Name of a scalar object_attributes column on level 0 to rank objects by, keeping the highest values. Required with sparsity_strategy="attribute" and refused otherwise. Level 0 is read whatever the source level: object ids are kept across levels, so its column describes every level’s objects.

  • cross_level_storage (str) – When called via build_pyramid this is threaded through to enable inline ±1 cross-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 case coarsen_factor is 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. See zarr_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 when coarsen_factor <= 1. Only the polyline coarsener in rdp mode has a tolerance, so a value is refused with coarsen_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; see read_coarsening_record().

  • method (str | None)

Returns:

Summary dict. Always includes method, preserves_object_ids, vertex_count.

Return type:

dict[str, Any]

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 stores coarsen_factor is interpreted as the decimation stride (keep every k-th vertex) rather than a vertex aggregation factor.

zarr_vectors_tools.multiresolution.coarsen.coarsener_keys()[source]

The registered coarsener keys, sorted: what method= accepts.

Return type:

list[str]

zarr_vectors_tools.multiresolution.coarsen.get_coarsener(key)[source]

Look up a registered coarsener; raise if none is registered.

Parameters:

key (str)

Return type:

Callable[[…], dict[str, Any]]

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 rdp mode carry:

  • rdp_tolerance – the Douglas-Peucker tolerance the level was simplified at, in store coordinate units. None when nothing was simplified (a coarsen_factor <= 1 with 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 {}.

Parameters:
Return type:

dict[str, Any]

zarr_vectors_tools.multiresolution.coarsen.register_coarsener(key, fn)[source]

Register (or override) the coarsener used for a dispatch key.

Parameters:
Return type:

None

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_sequential with geometry_type "streamline") use the RDP polyline coarsener; everything else uses the per-object pyramid.

Parameters:

root_meta (Any)

Return type:

str

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.

Returns:

None for None, else the tolerances as floats.

Raises:

ValueError – Naming name and what is wrong with it.

Parameters:
Return type:

list[float] | None

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.

Six strategies:

  • Spatial coverage: greedy selection maximising spatial spread

  • Length: keep the longest objects (streamlines, skeletons) — ranks by whatever lengths array the caller supplies, which must actually BE a length (sum of segment Euclidean distances) for this to mean what it says; see strategies/polylines.py and strategies/skeletons.py for how each geometry kind sources it, and open-items.md item 11 for what went wrong when a caller passed something else instead.

  • Point thinning: ≤1 survivor per spatial bin

  • 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 the bin_shape instead.

  • strategy (str) – One of "random", "length", "attribute", "spatial_coverage", "point_thinning", "group".

  • seed (int | None) – Random seed (for "random" / "point_thinning").

  • lengths (NDArray | None) – Per-object lengths (for "length" strategy).

  • attribute_values (NDArray | None) – Per-object values (for "attribute" strategy).

  • attribute_mode (str) – "max" or "min" (for "attribute").

  • representative_points (NDArray | 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[bool] | None) – (n_objects,) boolean — True for 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 are False). 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 (default None) to consider every index a candidate, matching prior behavior.

  • relative_to (Literal['original', 'alive']) – What sparsity is a fraction of — the basis for the target survivor count. "original" (default) keeps target_count = round(n_objects * sparsity) — “keep N of the original population”, so with alive_mask a constant sparsity reselects the same absolute count every level and, once the alive pool has shrunk to it, keeps everything. "alive" computes round(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[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:

NDArray[int64]

zarr_vectors_tools.multiresolution.object_selection.compute_polyline_lengths(polylines)[source]

Compute Euclidean path length for each polyline.

Parameters:

polylines (list[NDArray[floating]]) – List of (N_k, D) arrays.

Returns:

(N,) float64 array of path lengths.

Return type:

NDArray[float64]

zarr_vectors_tools.multiresolution.object_selection.compute_representative_points(polylines)[source]

Compute the midpoint of each polyline (representative point).

Parameters:

polylines (list[NDArray[floating]]) – List of (N_k, D) arrays.

Returns:

(N, D) array of midpoints.

Return type:

NDArray[floating]

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:
  • attribute_values (NDArray[floating]) – (N,) array of per-object values.

  • target_count (int) – Number of objects to keep.

  • mode (str) – "max" keeps highest values, "min" keeps lowest.

Returns:

(target_count,) sorted array of kept object indices.

Raises:

ValueError – If mode is not "max" or "min".

Return type:

NDArray[int64]

zarr_vectors_tools.multiresolution.object_selection.select_by_length(lengths, target_count)[source]

Select objects with the greatest lengths.

For streamlines, length is the sum of segment Euclidean distances. For graphs, total edge length. For any geometry, a scalar measure of object size.

Parameters:
  • lengths (NDArray[floating]) – (N,) array of per-object length/size values.

  • target_count (int) – Number of objects to keep.

Returns:

(target_count,) sorted array of kept object indices.

Return type:

NDArray[int64]

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_count budget across bins proportional to each bin’s object density, ensuring every occupied bin keeps at least one representative.

Parameters:
  • representative_points (NDArray[floating]) – (N, D) — one point per object.

  • bin_shape (tuple[float, ...] | float) – Spatial bin edge lengths for coverage assessment.

  • target_count (int) – Number of objects to keep.

Returns:

(target_count,) sorted array of kept object indices.

Raises:

ValueError – If target_count is invalid.

Return type:

NDArray[int64]

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 fixed target_count budget 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[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:

NDArray[int64]

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.

Parameters:
  • n_objects (int) – Total number of objects.

  • target_count (int) – Number to keep.

  • seed (int | None) – Random seed for reproducibility.

Returns:

(target_count,) sorted array of kept object indices.

Return type:

NDArray[int64]

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_count whenever 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[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. 1 is what makes “no group is ever lost” true; 0 disables the guarantee.

Returns:

Sorted array of kept object indices.

Return type:

NDArray[int64]

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, cross_level_storage=None, cross_level_depth=None)[source]

Re-coarsen every level above source_level from scratch.

Reads each existing target level’s metadata (bin_ratio, object_sparsity, chunk_shape, coarsening_method, and the tools-owned coarsening record’s rdp_tolerance) and re-runs zarr_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/decimate mode 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. An rdp level 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.

  • cross_level_storage (str | None) – Cross-level links to write for the rebuilt levels, as build_pyramid() takes it. None keeps what the root records.

  • cross_level_depth (int | None) – Likewise for the link depth.

Return type:

list[dict[str, Any]]

Every cross-level family that reaches a rebuilt level is removed first and written again for the new levels, and the root’s cross-level stamp is refreshed to what the store then holds: otherwise the old families (source_level’s +N, and every lower level’s +N that reaches past it) kept pointing at vertices that had moved.

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.

Parameters:
  • root (Group)

  • source_level (int)

  • coarsen_factors (Mapping[int, float] | None)

  • sparsity_strategy (str)

  • sparsity_seed (int | None)

  • compressor (Any)

  • executor (Any)

  • cross_level_storage (str | None)

  • cross_level_depth (int | None)

Return type:

list[dict[str, Any]]

Strategies

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, refinement='replace')[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 only binning thins it. Binning also replaces points with bin means, and their per-vertex attributes with the bin’s mean (a float column) or one merged point’s value (any other column).

This builder instead keeps a uniformly random 1/divisor of its parent’s points per level, exact positions and exact attribute values, so any level can be rendered and coloured exactly like level 0.

Sampling is drawn from a seeded generator, so the same seed gives 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/divisor of 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 4 bytes.

  • 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.

  • refinement (str) – "replace" (default) or "add": after building, make every level but the coarsest hold only the points no coarser level has, so each point is stored once and a level’s complete content is the union over its chain. Exact for these nested subsets. Level 0 is rewritten in place. See zarr_vectors_tools.multiresolution.additive.

Returns:

Summary dict with levels_created and a level_specs list of per-level {level, vertex_count, chunk_count}.

Return type:

dict[str, Any]

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[floating]) – (N, D) vertex positions.

  • bin_size (float | tuple[float, ...]) – Spatial bin edge length.

  • attributes (dict[str, NDArray] | None) – Per-vertex attributes to aggregate.

  • object_ids (NDArray[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 positions

  • attributes: {name: array} aggregated attributes

  • object_ids: (M,) majority object IDs (if input had them)

  • children: list of M arrays of parent vertex indices

  • vertex_count: M

  • reduction_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 to target_level in 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:

dict[str, Any]

Polylines

Polyline and streamline coarsening strategies.

Two complementary approaches:

  1. Douglas-Peucker simplification: reduces vertex count within each polyline while preserving shape. Good for reducing per-streamline resolution while keeping all streamlines.

  2. 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, attribute_values=None)[source]

Coarsen one streamline/polyline level, chunk-local and executor-parallel.

Memory-bounded replacement for the whole-level _polyline_coarsen in coarsen.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 through executor (a map-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/decimate mode 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_epsilon is the explicit Douglas-Peucker tolerance in store coordinate units (coarsen_level’s rdp_tolerance); None derives 0.5 * min(target_bin_shape) when coarsen_factor > 1 and simplifies nothing otherwise. It is refused in decimate mode, which has no tolerance. In rdp mode the value used, and whether it was explicit or derived, is recorded on the target level (see zarr_vectors_tools.multiresolution.coarsen.read_coarsening_record()).

Parameters:
  • store_path (str)

  • source_level (int)

  • target_level (int)

  • coarsen_factor (float)

  • sparsity_factor (float)

  • chunk_scale_factor (int | tuple[int, ...])

  • sparsity_strategy (str)

  • sparsity_seed (int | None)

  • coarsen_mode (str)

  • simplify_epsilon (float | None)

  • compressor (Any)

  • executor (Any)

  • attribute_values (NDArray | None)

Return type:

dict[str, Any]

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[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 polylines

  • vertex_count: total vertices

  • polyline_count: number of polylines

  • simplification_ratio: vertex reduction from DP

  • subsampling_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:
  • vertices (NDArray[floating]) – (N, D) ordered vertex positions.

  • stride (int) – Keep every stride-th interior vertex, counted from the first vertex. stride <= 1 keeps every vertex.

Returns:

(M, D) decimated polyline with M ≤ N vertices. First and last vertices are always preserved.

Return type:

NDArray[floating]

zarr_vectors_tools.multiresolution.strategies.polylines.simplify_polyline(vertices, epsilon)[source]

Simplify a polyline using Douglas-Peucker algorithm.

Parameters:
  • vertices (NDArray[floating]) – (N, D) ordered vertex positions.

  • epsilon (float) – Maximum perpendicular distance threshold. Larger values produce more aggressive simplification.

Returns:

(M, D) simplified polyline with M ≤ N vertices. First and last vertices are always preserved.

Return type:

NDArray[floating]

zarr_vectors_tools.multiresolution.strategies.polylines.simplify_polylines(polylines, epsilon, *, min_vertices=2)[source]

Simplify a list of polylines using Douglas-Peucker.

Parameters:
  • polylines (list[NDArray[floating]]) – List of (N_k, D) arrays.

  • epsilon (float) – Distance threshold.

  • min_vertices (int) – Minimum vertices to keep per polyline.

Returns:

List of simplified polylines.

Return type:

list[NDArray[floating]]

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_bin representatives per bin.

Parameters:
  • polylines (list[NDArray[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 arrays

  • indices: original indices of kept polylines

  • polyline_count: number kept

  • reduction_ratio: original / kept

Return type:

Dict with

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 a links_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 from zarr_vectors_tools.multiresolution.coarsen.coarsen_level() when the store’s links convention is the skeleton convention.

Coarser chunk grids are nested (a target chunk is the union of chunk_scale source chunks per axis), so each target chunk is coarsened from its own source chunks alone: an object’s fragments there are merged into one forest, decimated, and written back as pieces that never straddle a target chunk boundary. What joins the pieces across target chunks depends on the store’s skeleton layout (zarr_vectors_tools.multiresolution.skeleton_layout):

  • linked (SWC): the stored cross-chunk link records, whose ends are force-kept and rejoined after every target chunk is written;

  • split (precomputed ingests): a level-0 cross-chunk link whose two endpoint chunks nest into the same target chunk becomes an ordinary intra-target edge; one whose endpoints land in different target chunks is carried forward as an identity-keyed anchor (source chunk, source vertex) -> (target chunk, target vertex) and rejoined in Phase B (_cross_edge_shard()), with a coincidence join on rounded (segment_id, position) as a fallback for records the identity join could not place. The coincidence join alone silently drops any link whose two sides are not bit-identical duplicate vertices – e.g. a precomputed source where a boundary is a phase-split pair of distinct nearby vertices.

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 level i+1 from level i. Optional per-level chunk_scale_factors (default 2 per axis) and sparsity_factors (default 1.0 = keep all) are aligned with strides. executor (a map-like callable) is threaded into each level to coarsen target chunks in parallel; levels stay sequential (level i+1 reads i). Default None → serial. progress is forwarded to every level.

Returns a summary with one entry per produced level.

Parameters:
Return type:

dict[str, Any]

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, attribute_values=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 (a implicit_sequential_with_branches store written by zarr_vectors.types.skeletons.write_skeleton_chunk()), decimates every surviving object with decimate_skeleton() (keep all branch points, endpoints, and chunk-boundary / cross-chunk vertices; otherwise keep every stride-th vertex), and writes target_level with stable object IDs (dropped objects leave empty manifest slots).

Both skeleton layouts are coarsened (see zarr_vectors_tools.multiresolution.skeleton_layout), each into a level of its own layout. The split layout is stitched by the coincident copies of each face vertex; the linked layout by its cross-chunk link records, whose ends are kept and joined by a coarse link record [child, parent] wherever the edge still crosses a target chunk.

Parameters:
  • store_path (str | Path) – Store path.

  • target_level (int) – Source and (new) target levels.

  • stride (int) – Keep every stride-th non-anchor vertex (~``stride``× reduction per level). 8 pairs with chunk_scale_factor=2 (8× volume) to hold per-chunk size roughly constant.

  • sparsity_factor (float) – Object-drop factor (≥1). 1.0 keeps 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, by real cable length (object_attributes/length or cable_length) when the source level has it, else by fragment (branch) count as a weaker fallback – see the sparsity keep-set logic below for when each applies.

  • sparsity_seed (int | None) – RNG seed.

  • attribute_values (NDArray | None) – Per-object values for the "attribute" sparsity strategy.

  • 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 under timings either way.

  • source_level (int)

  • target_level

  • drop_interior_below (int)

  • boundary_offset_nm (Sequence[float] | None)

  • compressor (Any)

  • executor (Any)

Returns:

Summary dict.

Return type:

dict[str, Any]

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_keep vertices (e.g. chunk-boundary / cross-chunk vertices); along each unbranched chain between two kept anchors, keep every stride-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 <= 1 is 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_level documents 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:

dict[str, Any]

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[floating]) – (N, D) vertex positions.

  • edges (NDArray[integer]) – (M, 2) [child, parent] tree edges (as stored for the skeleton convention).

  • tolerance (float) – RDP perpendicular-distance threshold in position units (nm). <= 0 is the identity (no decimation).

  • attributes (dict[str, NDArray] | 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), and kept_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_links helpers on it.

Return type:

dict[str, Any]

Skeleton bins

Skeleton coarsening by connected-bin metavertex contraction.

Where skeletons thins a skeleton by index (keep every k-th vertex along a chain), this strategy thins it by space: vertices sharing a spatial bin collapse onto one metavertex at their centroid. Two properties follow, and they are the whole point:

Connected components are preserved exactly. Edges are contracted only when both endpoints share a bin AND are joined in the graph — the union-find runs over edges, never over bin membership alone. Every cluster is therefore a connected subgraph, clusters are vertex-disjoint, and contracting vertex-disjoint connected subgraphs cannot change the number of connected components. This holds independently of geometry, bin size, chunk size, or how the work is distributed. Binning by proximity alone would instead weld two branches that merely pass close to each other, inventing a cycle.

Geometric error is bounded by the bin diagonal. No vertex can be further from its metavertex than the diagonal of the bin containing it, because the centroid of a point set lies inside that set’s bounding box. Index-stride decimation offers no such bound at any ratio: it never consults geometry, so a hairpin short in vertex count is cut straight across.

Coarsening is density-adaptive as an emergent property of a fixed lattice: a dense arbor puts many vertices in one bin and collapses hard, while a sparse axon puts one or two in each and barely changes.

Edge orientation is inherited rather than recomputed. Callers pass a rooted [child, parent] tree (as split_components() produces); a cluster is a connected subtree, so exactly one of its members has a parent outside it, and mapping the edges through owner_new yields a correctly-oriented forest with K - n_roots rows. No re-rooting pass is needed.

zarr_vectors_tools.multiresolution.strategies.skeleton_bins.contract_skeleton_bins(positions, edges, *, bin_shape, attributes=None, attr_agg=None)[source]

Contract a rooted skeleton onto a spatial lattice.

Parameters:
  • positions (NDArray[floating]) – (N, D) vertex positions.

  • edges (NDArray[integer]) – (M, 2) [child, parent] rows, as stored for the skeleton convention. Orientation is preserved through the contraction.

  • bin_shape (float | Sequence[float]) – Lattice cell size, scalar or per-axis, in position units. <= 0 is the identity (no contraction).

  • attributes (Mapping[str, NDArray] | None) – Optional {name: (N,) or (N, C)} per-vertex values.

  • attr_agg (str | Mapping[str, str] | None) – Aggregation mode, one for all attributes or per name. When omitted, default_attr_agg() picks per name and dtype.

Returns:

The decimate_skeleton() result shape — positions (K, D), edges (<=K-1, 2) in new indices, attributes, kept_source_indices (K,) — plus owner_new (N,) mapping every source vertex to its metavertex. owner_new is total, which is what lets a cross-chunk link endpoint always resolve after coarsening; index decimation has no equivalent, which is why it needs to force-keep boundary vertices instead.

Note positions[i] is the centroid of cluster i, not the position of kept_source_indices[i]; the latter names a representative member (lowest source index) for provenance only.

Return type:

dict[str, Any]

zarr_vectors_tools.multiresolution.strategies.skeleton_bins.default_attr_agg(attr_dtypes)[source]

Per-attribute aggregation modes, inferred from name then dtype.

Named continuous quantities and floating dtypes average; everything else (integer codes such as compartment) takes the value of the member nearest the metavertex, so the result is always a value that genuinely occurred in the data.

Parameters:

attr_dtypes (Mapping[str, Any])

Return type:

dict[str, str]

zarr_vectors_tools.multiresolution.strategies.skeleton_bins.heavy_path_relabel(positions, edges, attributes=None)[source]

Relabel a rooted forest in heavy-first DFS preorder.

Lengthens the implicit runs the writer produces, without touching the writer. zarr_vectors.types.skeletons.decompose_tree_to_paths() builds each node’s child list in ascending vertex index and continues the current path through kids[0] — the lowest-indexed child. Visiting the heaviest subtree first in a preorder walk gives that child the lowest index among its siblings, so the path decomposition follows the heavy path instead of an arbitrary one. The longest root-to-leaf run then comes back as a single fragment.

This cannot change how many fragments there are: #fragments == #leaves and #branch_links == #fragments - #roots regardless of ordering. What it changes is the run-length distribution — which is what a reader pays for, since each fragment costs a separate per-fragment link read.

“Heavy” is subtree cable length, not vertex count, so a long thin axon outranks a bushy but compact tuft.

Returns:

(positions, edges, attributes, new_of_old) in the new labelling.

Parameters:
Return type:

tuple[NDArray, NDArray, dict[str, NDArray], NDArray[int64]]

Meshes, clustering

Mesh coarsening strategies.

Two approaches:

  1. Vertex clustering: merge vertices within spatial bins into metanodes, remap face indices, remove degenerate faces (collapsed to edges or points), and merge duplicate faces.

  2. Quadric error decimation (simplified): iterative edge collapse using quadric error metrics for vertex placement. Falls back to vertex clustering when the optional pyfqmr is 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[floating]) – (V, D) vertex positions.

  • faces (NDArray[integer]) – (F, L) face index array.

  • bin_size (float | tuple[float, ...]) – Spatial bin edge length.

  • vertex_attributes (dict[str, NDArray] | None) – Per-vertex attributes to aggregate.

  • agg_mode (str) – Attribute aggregation mode.

Returns:

  • vertices: (K, D) metanode positions

  • faces: (E, L) remapped faces (non-degenerate only)

  • vertex_attributes: aggregated attributes

  • children: list of K arrays of original vertex indices

  • vertex_count, face_count

  • vertex_reduction: V / K

  • face_reduction: F / E

  • degenerate_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, attribute_values=None, **_ignored)[source]

Coarsen one mesh level by chunk-local vertex clustering.

Vertices within a bin of source bin_shape x coarsen_factor collapse 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.

Parameters:
  • source_level (int)

  • target_level (int)

  • coarsen_factor (float)

  • sparsity_factor (float)

  • sparsity_strategy (str)

  • sparsity_seed (int | None)

  • compressor (Any)

  • bin_size (float | None)

  • attribute_values (Any)

  • _ignored (Any)

Return type:

dict[str, Any]

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 pyfqmr if available; otherwise falls back to vertex clustering with an estimated bin size.

Parameters:
  • vertices (NDArray[floating]) – (V, 3) vertex positions (3D only).

  • faces (NDArray[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] | None) – Per-vertex attributes (interpolated if pyfqmr is used, aggregated otherwise).

Returns:

Dict with vertex/face arrays, counts, and method used.

Return type:

dict[str, Any]

Meshes, decimation

Quadric-error edge collapse for meshes, in batched rounds.

WHY NOT CLUSTERING

strategies.meshes.coarsen_mesh_level bins vertices and DELETES any face with two corners in one bin. Faces vanish faster than vertices, so the level fills with dust: measured on the 1720-neuron MICrONS store, 6.4 / 34.0 / 66.2 % of vertices at levels 1-3 are referenced by no face at all, and the vertex/face ratio climbs from 0.508 to 3.30 where a closed triangle mesh sits at ~0.5. Neuron axons are ~450 nm tubes against a ~93 nm edge length, so once the bin reaches the tube diameter both walls fall in one bin and the tube is erased rather than simplified.

An edge COLLAPSE cannot do that. It merges two vertices into one and removes only the faces that degenerate as a result; every surviving vertex keeps the faces around it. Orphans are impossible by construction rather than something to clean up afterwards, and the tube thins instead of vanishing because the link condition below refuses the collapse that would pinch it shut.

WHY ROUNDS AND NOT A PRIORITY QUEUE

Textbook QEM pops one edge at a time. The test cell is 25.2M faces, so a target of 100x is ~12.5M sequential collapses; in Python that is hours. Each round here instead scores every edge at once, takes a MUTUAL-BEST MATCHING (edge (u,v) is collapsed only if it is the cheapest incident edge of both u and v), and applies the whole matching in one vectorised step. A matching touches each vertex at most once, so the collapses within a round are independent and cannot interact. Rounds are O(F) numpy and the face count falls geometrically, so any reduction is reached in tens of rounds.

The cost is that a matching is not the greedy optimum – some cheap edges wait for a later round. Quality is measured, not assumed: see mesh_eval.py.

SAFETY

Two guards decide whether a matched edge may actually collapse.

Link condition (Dey et al. 1999): for edge (u,v) the collapse preserves topology iff the vertices adjacent to both u and v are exactly the vertices opposite (u,v) in the faces that contain it – 2 for a manifold interior edge, 1 on a boundary. Violate it and the surface pinches: two sheets that were apart get welded, or a tube closes into a disc. This is what protects the thin axon tubes, and it is why the tube diameter never appears as a parameter.

Normal flip: the collapse is rejected if it would turn any surviving incident face through more than max_normal_turn. This catches the geometric fold-overs the link condition permits.

Both are computed for all matched edges at once.

zarr_vectors_tools.multiresolution.strategies.mesh_decimate.canonical_faces(faces)[source]

Rotate each face so its smallest index leads, preserving cyclic order.

Winding-aware, unlike sorting the triple. On the test cell 11,084 of 27,738 duplicated triples are genuine opposite-wound double walls – two sheets of membrane back to back – and a winding-blind dedup deletes one of each, turning 252 boundary edges into 31,317.

Parameters:

faces (NDArray)

Return type:

NDArray

zarr_vectors_tools.multiresolution.strategies.mesh_decimate.cull_small_components(vertices, faces, min_faces)[source]

Drop connected components smaller than min_faces.

Segmentation leaves dust: the welded source of the test cell is 1,725 components of which 1,488 hold under 100 faces, together only 0.20% of the surface. Carrying them costs nothing at full resolution and everything at the coarse end, because a component cannot go below ~4 faces however tight the budget – so at a 223k-face target 941 fragments were still absorbing 2.58% of the budget and, more importantly, holding 18.1% of it outside the main arbour. MICrONS’s own decimator consolidates 1,725 -> 166 components and puts 95.8% of its faces in the largest, against 81.9% here; that gap is most of why this decimator collapsed three times as many tubes at matched face counts.

Parameters:
  • vertices (NDArray)

  • faces (NDArray)

  • min_faces (int)

Return type:

tuple[NDArray, NDArray, dict]

zarr_vectors_tools.multiresolution.strategies.mesh_decimate.decimate_mesh(vertices, faces, *, target_faces=None, target_ratio=None, max_normal_turn=100.0, max_rounds=200, max_passes=200, min_progress=0.005, do_weld=True, min_component_faces=0, verbose=False)[source]

Decimate to target_faces by batched quadric-error edge collapse.

Parameters:
  • vertices (NDArray) – (V, 3) positions.

  • faces (NDArray) – (F, 3) triangle indices.

  • target_faces (int | None) – stop once the face count is at or below this.

  • target_ratio (float | None) – alternative to target_faces; keep this fraction.

  • max_normal_turn (float) – degrees a surviving face may rotate. The default is deliberately permissive – these surfaces are noisy segmentation boundaries, and a tight bound stalls the collapse long before the target.

  • max_rounds (int) – safety stop.

  • max_passes (int) – safety cap on selection retries within one round. Each pass retires the edges the guards refused and re-selects from what is left, which is what stops a refused edge from permanently blocking its two endpoints (see the round body). This MUST NOT be the binding constraint: at the old default of 12 a round still accepted ~1000 collapses on its last allowed pass, so the run stopped with work left and reported hit_floor – a pyramid level came out at 2.71x instead of the requested 4x and the shortfall was read as a topological floor. Raising it to 100 reached 4.03x on the same input in FEWER rounds and less wall clock. pass_budget_bound in the result says whether this cap was ever reached, so a floor can be distinguished from a cap.

  • min_progress (float) – if a round removes a smaller fraction of faces than this, the mesh is at its topological floor and the run stops. This is what “as small as it can get and still be a mesh” means in practice – every remaining collapse is refused by the guards.

  • do_weld (bool) – weld coincident positions first. Required for chunk-fragmented input; harmless otherwise.

  • min_component_faces (int) – drop connected components below this many faces before decimating, so the budget is spent on the structure that matters rather than on segmentation dust. See cull_small_components(). 0 disables.

  • verbose (bool)

Returns:

dict with vertices, faces, and statistics including hit_floor (True if it stopped for lack of safe collapses rather than because the target was met).

Return type:

dict[str, Any]

zarr_vectors_tools.multiresolution.strategies.mesh_decimate.mesh_floor_report(vertices, faces)[source]

Is this still a mesh? The stop test for a pyramid.

“Still a mesh” is taken to mean: every vertex is used, every component still encloses something (a closed triangulated surface needs at least the 4 faces of a tetrahedron), and the surface has not shattered into isolated triangles. Reported rather than judged, so the caller sets the policy.

Parameters:
  • vertices (NDArray)

  • faces (NDArray)

Return type:

dict

zarr_vectors_tools.multiresolution.strategies.mesh_decimate.weld_vertices(vertices, faces)[source]

Merge bit-identical vertex positions.

The precomputed multi-LOD source arrives as one fragment per octree chunk with the boundary vertices duplicated in every fragment that touches them: on the test cell 218,441 duplicates across 39,515 index-disjoint pieces that are really 1,725 components. Decimating before welding treats every chunk seam as a free boundary and shreds it, so this runs first and always.

Exact float equality, deliberately: the duplicates are bitwise copies, so no tolerance is needed and none is offered – a tolerance would be a second parameter able to weld genuinely distinct surfaces.

Parameters:
  • vertices (NDArray)

  • faces (NDArray)

Return type:

tuple[NDArray, NDArray, NDArray]

Mesh decimation levels

Store-level mesh coarsening by quadric edge collapse, object by object.

WHY OBJECT-LOCAL AND NOT CHUNK-LOCAL

strategies.meshes is chunk-local because the generic per-object coarsener once OOM-killed a 251 GB machine, a 766x read amplification. That amplification was a property of the retired chunk-wide-fragment layout, not of the data: under the current one-fragment-per-(chunk, object) layout the measured amplification is 1.000x, the largest object in the 1720-neuron MICrONS store is 153,510 vertices (5.5 MB gathered), and all 1720 together are 2.35 GB. Every one of the 114,624,311 faces at level 0 has its three corners inside a single object, so objects are an exact partition of both vertices and faces.

Working per object rather than per chunk buys three things chunk-locality cannot: an edge collapse needs the ring of faces around a vertex, which a chunk boundary cuts; the surface can be welded (a chunk-wide weld would fuse two neurons that happen to touch, 0.22-0.32% of a chunk’s vertices are exact coincidences between DIFFERENT cells); and there are no seams to reconcile, because the object is re-split into chunks only after it has been simplified.

WHAT IT WRITES

One fragment per (target chunk, object), vertices contiguous within it, faces as links – the numpy path for the intra-chunk majority (98.2% at level 0) and the tuple path for the cross-chunk remainder, which is the split the incumbent already makes and the only one write_links supports for canonicalisation.

zarr_vectors_tools.multiresolution.strategies.mesh_decimate_level.BYTES_PER_VERTEX = 12.0

positions are 3 x float32 and a face is 3 x int64 plus ~0.7% index overhead.

Type:

Bytes per vertex and per face in the raw store layout, measured

zarr_vectors_tools.multiresolution.strategies.mesh_decimate_level.COARSENER_KEY: str = 'mesh_decimate'

Dispatch key for coarsen_level.

zarr_vectors_tools.multiresolution.strategies.mesh_decimate_level.COARSEN_MESH_DECIMATE: str = 'mesh_quadric_collapse'

Level-metadata tag recorded for levels this strategy produced.

zarr_vectors_tools.multiresolution.strategies.mesh_decimate_level.build_mesh_pyramid_to_floor(store_path, size_factor=4.0, *, max_levels=12, min_faces=256, tolerance=0.75, chunk_scale_factor=2, max_normal_turn=100.0, min_component_faces=0, tube_floor=None, object_floors=None, verbose=True)[source]

Add levels at size_factor-fold data-size reduction each, until the floor.

“The floor” is where the surface can no longer be reduced by the requested factor and still be a mesh. Four things stop the ladder, and which one fired is reported per level:

target_missed

The level came out more than tolerance short of the requested factor. Every remaining edge collapse is refused by the link condition or the normal-flip guard, so the geometry is as coarse as it can be without pinching a tube shut or folding a face over. This is the real floor and normally the one that fires.

min_faces

The absolute face budget is exhausted.

not_a_mesh

The level failed mesh_floor_report() – an orphan appeared, or a component fell below the 4 faces a closed surface needs. This should never fire; it is a backstop against a bug, not a design stop, and it deletes the offending level rather than publishing it.

tube_floor

The next level would fall below the face count at which the geometry can still be a surface at all – see tube_floor_faces(). Checked BEFORE the level is built, so a level that cannot look right is never written rather than written and judged. This is the stop that matters for thin neurites: the size-factor tests are blind to quality and happily emitted a level at 3.99x whose axon had disintegrated into 5:1 slivers.

The level that trips a stop is kept if it is still a valid mesh (it is the coarsest honest representation), and discarded only in the not_a_mesh case.

Parameters:
  • size_factor (float)

  • max_levels (int)

  • min_faces (int)

  • tolerance (float)

  • max_normal_turn (float)

  • min_component_faces (int)

  • tube_floor (int | None)

  • object_floors (dict | None)

  • verbose (bool)

Return type:

list[dict[str, Any]]

zarr_vectors_tools.multiresolution.strategies.mesh_decimate_level.coarsen_mesh_decimate_level(store_path, source_level, target_level, *, coarsen_factor=4.0, size_factor=None, chunk_scale_factor=1, sparsity_factor=1.0, compressor=None, max_normal_turn=100.0, max_passes=200, min_component_faces=0, object_floors=None, min_faces=4, verbose=False, **_ignored)[source]

Coarsen one mesh level by per-object quadric edge collapse.

size_factor (or coarsen_factor if it is not given) is the desired reduction in ON-DISK DATA SIZE for the level as a whole. It is converted to a per-object face target through predict_bytes(), which is linear and measured accurate to under a percent, so the requested factor is hit directly rather than searched for.

Parameters:
  • source_level (int)

  • target_level (int)

  • coarsen_factor (float)

  • size_factor (float | None)

  • sparsity_factor (float)

  • compressor (Any)

  • max_normal_turn (float)

  • max_passes (int)

  • min_component_faces (int)

  • object_floors (dict | None)

  • min_faces (int)

  • verbose (bool)

  • _ignored (Any)

Return type:

dict[str, Any]

zarr_vectors_tools.multiresolution.strategies.mesh_decimate_level.faces_for_byte_budget(budget, v_over_f)[source]

Invert predict_bytes() at a known vertex/face ratio.

Parameters:
Return type:

int

zarr_vectors_tools.multiresolution.strategies.mesh_decimate_level.predict_bytes(n_vertices, n_faces)[source]

On-disk bytes for a level, from its vertex and face counts.

Linear and accurate to under a percent on the real store, which is what lets a caller’s data size target be converted to a face target analytically instead of by trial decimation.

Parameters:
  • n_vertices (int)

  • n_faces (int)

Return type:

float

zarr_vectors_tools.multiresolution.strategies.mesh_decimate_level.tube_floor_faces(path_length_nm, radius_nm, *, n_radial=3, max_aspect=3.0)[source]

Fewest faces at which a tubular arbour is still a surface.

A tube of n_radial segments costs 2 * n_radial faces per longitudinal step, so a face budget FIXES the step length:

step = 2 * n_radial * path_length / faces

and the step divided by the tube diameter is the aspect ratio of the quads being laid down. Past roughly 3:1 the triangles are slivers lying along the centreline and the tube has stopped reading as a tube, however faithful the vertex positions are.

Measured on the 37.0 mm / 224 nm-radius test axon: 391k faces gives a 568 nm step (1.3:1, still round), while 97k gives 2292 nm (5.1:1, visibly collapsed). The floor at 3:1 is 165k faces. This is a property of the geometry, not of the simplifier – no algorithm renders 37 mm of 448 nm tube in 97k faces – which is why it belongs in the STOP rule rather than in the decimator.

Parameters:
Return type:

int

Graphs

Graph and skeleton coarsening strategies.

Two approaches:

  1. 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.

  2. 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[floating]) – (N, D) node positions.

  • edges (NDArray[integer]) – (M, 2) edge list.

  • bin_size (float | tuple[float, ...]) – Spatial bin edge length.

  • node_attributes (dict[str, NDArray] | None) – Per-node attributes to aggregate.

  • edge_weights (NDArray[floating] | None) – (M,) edge weights. Default: all 1.0.

  • agg_mode (str) – Node attribute aggregation mode.

Returns:

  • positions: (K, D) metanode positions

  • edges: (E, 2) metanode edge list

  • edge_weights: (E,) aggregated weights

  • node_attributes: aggregated node attributes

  • children: list of K arrays of original node indices

  • node_count, edge_count

  • reduction_ratio: original nodes / metanodes

Return type:

Dict with

zarr_vectors_tools.multiresolution.strategies.graphs.contract_edges(edges, node_to_meta, *, directed=False)[source]

The images of edges under a node -> metanode map.

An edge whose two ends land in one metanode disappears (it would be a self-loop), and edges landing on the same metanode pair merge into one. Nothing else is added: every returned edge is the image of at least one input edge, so contracting never joins two connected components.

Parameters:
  • edges (NDArray[integer]) – (M, 2) edge list.

  • node_to_meta (NDArray[integer]) – (N,) metanode of each node.

  • directed (bool) – Keep endpoint order, so a -> b and b -> a stay distinct. Otherwise each edge is stored (min, max).

Returns:

the (E, 2) metanode edges, sorted; the indices of the input edges that are not self-loops; and, for each of those, the row of meta_edges it became – the grouping a per-edge attribute is aggregated over.

Return type:

(meta_edges, kept, groups)

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 than min_branch_vertices nodes are removed.

Parameters:
  • positions (NDArray[floating]) – (N, D) node positions.

  • edges (NDArray[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] | None) – Per-node attributes to filter.

Returns:

  • positions: pruned positions

  • edges: pruned edges (remapped indices)

  • node_attributes: filtered attributes

  • node_count, edge_count

  • branches_removed: count of pruned branches

  • kept_indices: original indices of surviving nodes

Return type:

Dict with

Fragments

Per-fragment coarsening — the reuse-preserving pyramid.

The per-object coarsener bins vertices globally and then re-cuts every surviving object into per-(object, coarse-chunk) runs. That is correct for implicit_sequential geometry, where connectivity is the adjacency of consecutive vertices inside a fragment and no fragment can therefore carry two objects’ traversal orders — but it destroys fragment sharing. Two objects that referenced one fragment at level 0 get two private fragments at level 1, each holding its own copy of the shared metavertices, so the fragment count scales with object×chunk runs rather than with fragments and a coarse level can end up larger on disk than the level it coarsens.

This strategy takes the opposite trade. It never re-cuts anything:

  • each source fragment is thinned in place — coarsen_factor=2 keeps every second vertex, so a fragment of N vertices becomes ceil(N/2);

  • the (chunk, fragment_index) map is explicit and order-preserving, so a manifest entry rewrites 1:1;

  • two objects referencing one source fragment therefore reference the same coarsened fragment — reuse survives, and the fragment count can only shrink (unreferenced fragments are dropped), never spike.

Storage stays shared as well. Thinning is computed on each fragment’s own vertex indices, then the chunk’s kept indices are unioned into one coarsened vertex array and every fragment is rewritten as an index fragment into it. So a vertex two fragments have in common is stored once, exactly as at level 0 — the per-object path would have stored it twice.

Endpoints are always kept. Fragment ends are where cross-chunk seams attach, so dropping them would silently sever connectivity at chunk boundaries.

Trade-offs, stated plainly

  • Vertex count reduction is per fragment, so the level’s total reduction is only 1/coarsen_factor when fragments are disjoint. Where they overlap, the union keeps a vertex any fragment kept, so the realised reduction is weaker than the per-object binner’s — this strategy trades compression for structure.

  • There is no spatial re-binning: coarse vertices are a subset of the source positions, not bin centroids. Positions are therefore exact rather than averaged, which is what makes an index fragment into a shared array possible at all.

  • chunk_scale_factor merges source chunks into a coarser grid; fragments are concatenated in (source chunk, source fragment) order so the mapping stays deterministic.

  • No cross-level links are emitted. cross_level_depth / cross_level_storage are accepted and ignored, the same way the polyline and skeleton strategies ignore them — only the per-object coarsener emits inline ±1 arrays, and build_pyramid stamps root metadata with what was written (cross_level_storage="none" here). What this strategy does give you instead is a stable (chunk, fragment_index) identity across levels, which is a coarser-grained but cheaper way to relate a level to its parent.

zarr_vectors_tools.multiresolution.strategies.fragments.COARSENER_KEY: str = 'per_fragment'

Dispatch key for coarsen_level().

zarr_vectors_tools.multiresolution.strategies.fragments.COARSEN_PER_FRAGMENT: str = 'per_fragment'

Level-metadata tag recorded for levels this strategy produced.

zarr_vectors_tools.multiresolution.strategies.fragments.coarsen_fragments_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, compressor=None, coarsen_mode='decimate', attribute_values=None, **_ignored)[source]

Coarsen one level fragment-wise, preserving fragment identity and reuse.

See the module docstring for the contract. Returns the usual summary dict plus fragments_in / fragments_out / fragment_reuse so a caller can assert the count did not spike.

Parameters:
  • store_path (str | Path)

  • source_level (int)

  • target_level (int)

  • coarsen_factor (float)

  • sparsity_factor (float)

  • chunk_scale_factor (int | tuple[int, ...])

  • sparsity_strategy (str)

  • sparsity_seed (int | None)

  • compressor (Any)

  • coarsen_mode (str)

  • attribute_values (Any)

  • _ignored (Any)

Return type:

dict[str, Any]

Supporting modules

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[floating]) – (N, D) vertex positions.

  • bin_size (float | tuple[float, ...]) – Spatial bin edge length (scalar for isotropic, or per-dim).

  • attributes (dict[str, NDArray] | None) – Optional per-vertex attributes to aggregate.

  • agg_mode (str) – Aggregation for attributes: "mean", "sum", "first", "count".

Returns:

  • metanode_positions: (M, D) centroid positions

  • metanode_counts: (M,) int — vertices per metanode

  • children: list of M arrays, each containing global vertex indices belonging to that metanode

  • metanode_attributes: {name: (M, ...) array} aggregated

  • bin_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 (and, when the caller supplies it, object_attributes/length).

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.VERTEX_COUNT_ATTR = 'vertex_count'

The object attribute a viewer budgets each object by, per level.

zarr_vectors_tools.multiresolution.object_index.build_object_index(level_group, records, *, ndim, cable_lengths=None)[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) and object_attributes/segment_id (uint64) so skeletons can be pulled back out by original ID.

Parameters:
  • level_group – Level-0 group.

  • records (list[tuple[int, tuple[int, ...], int]]) – (segment_id, chunk_coords, fragment_index) from every chunk written.

  • ndim (int) – Spatial index dim count.

  • cable_lengths (dict[int, float] | None) – Optional {segment_id: cable_length} (sum of edge Euclidean distances), computed while vertices and edges were both still in memory at read time (see precomputed_plain_skeletons._read_batches). When given, written as object_attributes/length (float32), aligned to the same sorted-segment-id order as segment_id. This is the per-object signal sparsity_strategy="length" reads at level 0 (coarsen_skeleton_level); without it that strategy has no cheap per-object length and falls back to a weaker per-fragment proxy. A segment absent from the mapping gets 0.0, matching compute_cable_lengths’s own “no edges” convention.

Returns:

{segment_id: object_id}.

Return type:

dict[int, int]

zarr_vectors_tools.multiresolution.object_index.carry_object_columns(src_group, level_group, keep_oids, n_objects)[source]

Carry a level’s per-object columns to the coarser level just written.

Every object_attributes column is copied, in its own dtype, for the objects the level kept (the rest are marked absent); vertex_count is then recounted from this level’s fragments, and the fragment segment_id a viewer colours and picks by is stamped when the source level had one. Without these a coarse level could not be budgeted per object, and its fragments would be coloured by their chunk-local index.

Returns:

The object attribute names carried.

Parameters:

n_objects (int)

Return type:

list[str]

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 about rows_per_shard rows, 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 % shards into 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 [] when rows is empty.

Parameters:
Return type:

list[ndarray]

Skeleton graph

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, roots=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-1 local 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.

With roots, a component holding one of those vertices is rooted there instead, and those components come first, in the order of their root. A caller whose edges already form a rooted forest passes its roots to keep each tree’s orientation; BFS from the true root orients every edge as the forest does.

Parameters:
  • positions (NDArray[floating]) – (N, D) vertex positions.

  • edges (NDArray[integer]) – (M, 2) undirected edges (any orientation).

  • attributes (dict[str, NDArray] | None) – Optional {name: (N,) or (N, C)} per-vertex data.

  • vertex_ids (NDArray[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.

  • roots (NDArray[integer] | None) – Optional vertices to root components at, in ascending order.

Returns:

List of {"positions", "edges", "attributes"[, "vertex_ids"]} dicts, one per connected component.

Return type:

list[dict[str, Any]]

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.csgraph formulation 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

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 positions by target_chunk_shape. Returns an empty (0, D) array when positions is empty.

Parameters:
Return type:

NDArray[int64]

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:
  • n_fragments_per_chunk (dict[tuple[int, ...], int]) – count of fragments per chunk (used only to allocate the output list length).

  • fragment_lengths_per_chunk (dict[tuple[int, ...], list[int]]) – fragment vertex counts in fragment-index order, per chunk.

Returns:

{chunk_coords: [start_0, start_1, ...]}.

Return type:

dict[tuple[int, …], list[int]]

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 runs list returned by segment_object_by_coarse_chunk() is mirrored by these two arrays: runs[r][1][p] is the metavertex visited by every source vertex with run_idx == r and position_in_run == p.

Parameters:
  • n (int) – number of source vertices.

  • mv_per_vertex (NDArray[int64]) – (n,) int64.

  • coarse_chunk_per_vertex (NDArray[int64]) – (n, D) int64.

Returns:

Two (n,) int64 arrays.

Return type:

tuple[NDArray[int64], NDArray[int64]]

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) and coarse_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:
  • mv_per_vertex (NDArray[int64]) – (N,) int64 metavertex id per source vertex.

  • coarse_chunk_per_vertex (NDArray[int64]) – (N, D) int64 target chunk coord per source vertex.

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:

list[tuple[tuple[int, …], list[int]]]

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_SKELETON because 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.

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.

Additive pyramids

Additive pyramids: each object (or point) stored at one level only.

An ordinary pyramid stores a coarse level as a replacement for the finer one: the 1/2 of streamlines kept at level 1 are stored again at level 0, and a viewer zooming in throws level 1 away to draw level 0. An additive pyramid stores them once. Every level but the coarsest is marked refinement: "add" and holds only what the next coarser level does not; a level’s complete content is its own data plus the complete content of the next coarser level (zarr-vectors-py’s level_chain). Storage drops from about 1.14-1.33x of level 0 to about 1x, and a viewer that has drawn a coarse level fetches only the difference when it zooms in.

That union is only the same picture as the replacement level when the levels differ by which objects (or points) they keep, not by how those are drawn. It is exact for

  • object sparsity with the geometry unchanged – a streamline or polyline pyramid built with coarsen_factor 1 keeps every kept streamline byte-identical;

  • nested point subsets (build_point_subset_pyramid in zarr_vectors_tools.multiresolution.strategies.points).

It is not for meshes or for any level that spatially coarsens geometry (binning into metanodes, RDP or decimation, skeleton simplification, mesh clustering or decimation): an object kept at a coarse level is then drawn at the coarse resolution even in the finest view. Those builds still run, with an AdditiveRefinementWarning.

The pyramid is built as an ordinary one and then converted, finest level first, by zarr-vectors-py’s make_levels_additive – level 0 is rewritten in place.

zarr_vectors_tools.multiresolution.additive.ADDITIVE_CAPABILITY = 'additive_levels'

The root required_capabilities entry of a store with additive levels.

exception zarr_vectors_tools.multiresolution.additive.AdditiveRefinementWarning[source]

Bases: UserWarning

An additive pyramid was asked for where its union is not the picture the replacement pyramid draws, or where a level adds nothing.

zarr_vectors_tools.multiresolution.additive.additive_concerns(*, geometry_types, coarsener, factors, coarsen_mode='rdp', rdp_tolerances=None)[source]

Why an additive version of this pyramid would not draw what the replacement pyramid draws – empty when it would. Known before a level is built.

Parameters:
Return type:

list[str]

zarr_vectors_tools.multiresolution.additive.additive_support_error()[source]

Why refinement="add" cannot run here, or None when it can. Every entry point asks before it writes anything.

Return type:

str | None

zarr_vectors_tools.multiresolution.additive.check_refinement(refinement)[source]
Parameters:

refinement (str)

Return type:

str

zarr_vectors_tools.multiresolution.additive.level_zero_notice(store_path)[source]

The banner a CLI prints after converting: what changed about level 0.

Parameters:

store_path (Any)

Return type:

str

zarr_vectors_tools.multiresolution.additive.make_pyramid_additive(store_path, *, concerns=())[source]

Convert a finished replacement pyramid to an additive one, in place.

Level 0 is rewritten: afterwards it holds only the objects or points no coarser level has, and level 0 alone is no longer the whole dataset. zarr-vectors-py readers return a level’s complete content by default; own_level_only=True reads what one level stores.

Warns (AdditiveRefinementWarning) for each of concerns and for a level that keeps every object or point of the level below, whose additive level would be empty. Recounts each level’s object_attributes/vertex_count column, where there is one, to the vertices that level now stores.

Returns:

{"levels": [per-level report], "concerns": [...]}.

Parameters:
Return type:

dict[str, Any]

zarr_vectors_tools.multiresolution.additive.missing_additive_support()[source]

The zarr-vectors-py functions additive levels need that the installed version lacks, as dotted names – empty when it has them all.

Return type:

list[str]

zarr_vectors_tools.multiresolution.additive.refuse_additive(store_path, action)[source]

Raise if store_path already has additive levels: action rebuilds levels from one another, which an additive pyramid – each level holding only what the next one lacks – cannot survive.

zarr-vectors-py’s refuse_additive decides where it exists. Where it does not, the store’s root required_capabilities decides: a store with additive levels lists "additive_levels" there. Raises ValueError in that case.

Parameters:
  • store_path (Any)

  • action (str)

Return type:

None

zarr_vectors_tools.multiresolution.additive.supports_additive()[source]

Whether the installed zarr-vectors-py can write additive levels.

Return type:

bool

zarr_vectors_tools.multiresolution.additive.warn_concerns(concerns)[source]
Parameters:

concerns (Sequence[str])

Return type:

None

zarr_vectors_tools.multiresolution.additive.warnings_as_banner(stream=None)[source]

Collect AdditiveRefinementWarnings raised inside the block and print them as one banner on stream (stderr) at the end; every other warning is shown as usual. For command-line front ends, where a warning line is easy to miss.

Parameters:

stream (Any)

Return type:

Iterator[list[str]]

Face groups

Per-object face groups, so a reader can fetch one object’s faces.

A level stores each chunk’s intra-chunk links (a mesh’s faces) as flat rows plus a link_fragments sidecar giving the row range of each link group. The format lets groups be anything. The mesh coarseners write exactly one group per vertex fragment, in fragment order (empty where a fragment has no intra-chunk faces), so an object’s manifest – which names vertex fragments – also names its faces, and a reader drawing one object can range-read just its rows instead of the whole cell.

zarr-vectors-py owns the claim that a level is laid out this way: it checks every chunk and stamps LevelMetadata.fragment_link_groups (and the root fragment_link_groups capability) only where the layout holds, and any later write to the arrays it describes clears it. Against a zarr-vectors-py without that, the groups are still written – they are valid groups, and readers concatenate them – but nothing is stamped.

Whether the installed zarr-vectors-py can stamp fragment_link_groups.

zarr_vectors_tools.multiresolution.face_groups.face_groups_support_error()[source]

Why index_mesh_faces() cannot run here, or None when it can.

Return type:

str | None

zarr_vectors_tools.multiresolution.face_groups.index_mesh_faces(store_path, levels=None, *, dry_run=False, verify=False)[source]

Give an existing store’s levels one face group per vertex fragment and stamp them – zarr_vectors.building.index_fragment_link_groups(), which rewrites as little as it can (usually just the link_fragments sidecar) and leaves alone a level where a face joins two fragments.

Parameters:
Return type:

list[dict[str, Any]]

zarr_vectors_tools.multiresolution.face_groups.split_faces_by_fragment(faces, fragment_of, num_fragments)[source]

One group of rows per fragment, in fragment order (empty where a fragment has none), or None when some row’s corners do not all lie in one fragment – then no per-fragment grouping exists.

Parameters:
  • faces (NDArray[integer])

  • fragment_of (NDArray[int64])

  • num_fragments (int)

Return type:

list[NDArray[integer]] | None

zarr_vectors_tools.multiresolution.face_groups.stamp_face_groups(level_group, root)[source]

Have zarr-vectors-py check the level’s face groups and stamp it if they follow its vertex fragments. Call once the level’s writes are done: a later write clears the stamp. False when not stamped, including when the installed zarr-vectors-py cannot stamp at all.

Parameters:
  • level_group (Any)

  • root (Any)

Return type:

bool

Groups across levels

Carrying the group taxonomy across pyramid levels.

Groups name object ids — “these OIDs are the streamlines”, “this OID is the whole network” — and every coarsener in this package preserves object ids (CAP_PRESERVED_OBJECT_IDS). A group’s membership is therefore meaningful at a coarse level unchanged, minus whatever sparsification dropped.

The coarseners write <N>/groups/ with propagate_groupings(), so <N>/groups/<id> answers at every level the same way 0/groups/<id> does: a reader asking for “the network object” at level 2 finds it there, without reaching back to level 0 for the taxonomy.

Group attributes (group_attributes/<name>) ride along, since they are indexed by group id and are what carry human-readable group names.

zarr_vectors_tools.multiresolution.groupings.group_labels_for(src_group, n_objects)[source]

One group id per object, for the "group" sparsity strategy.

Objects in no group get -1 and form their own stratum — thinned at the same rate as everything else, which is what a store holding a whole-brain tractogram and a labelled atlas wants: the unlabelled bulk coarsens normally while every named bundle survives.

An object in more than one group is assigned to the highest-numbered one. Stratification needs a partition and groups are not one; picking a rule and saying so beats sampling the same object twice.

Lives here rather than in one strategy module because every coarsener that offers sparsity_strategy="group" needs it, and the CLI offers that strategy for every geometry.

Parameters:

n_objects (int)

Return type:

NDArray[int64]

zarr_vectors_tools.multiresolution.groupings.propagate_groupings(src_group, dst_group, *, surviving_oids=None)[source]

Copy src_group’s group taxonomy onto dst_group.

Parameters:
  • src_group – Source level group (the level being coarsened).

  • dst_group – Target level group (the level just written).

  • surviving_oids (Iterable[int] | None) – OIDs that still exist at the target level. None keeps every member — correct when sparsity_factor == 1. Members outside this set are dropped, because a group listing an OID that sparsification removed would hand readers an empty manifest and call it a member.

Returns:

{group_id: member_count} for what was written; {} when the source has no groupings (nothing to carry, not an error).

Return type:

dict[int, int]

Skeleton layouts

Which of the two skeleton layouts a store holds.

Two writers produce links_convention = "implicit_sequential_with_branches" stores, and they join a tree across a chunk boundary differently:

  • LAYOUT_SPLIT – the Neuroglancer precomputed ingests. A tree is cut at every chunk face into pieces; the vertex on the face is written into both chunks, and a cross-chunk link joins the two copies. A segment is read back by id (read_skeleton_by_segment_id) and the copies joined.

  • LAYOUT_LINKED – SWC ingest, through core’s write_graph(kind="skeleton"). Every vertex is stored once, and an edge whose ends sit in different chunks is a cross-chunk link record [child, parent] that replaces the parent the reader would otherwise imply – the rule read_graph applies.

The skeleton coarsener keeps the layout of the level it reads, and the exporters need it to pick a reader: the pull-by-segment-id reader is right for the first and wrong for the second, which has no duplicated vertices to join. segment_id cannot tell them apart, since both carry one.

The ingests record the layout on the root (mark_skeleton_layout()). skeleton_layout() falls back, for a store written before they did, on what each writer leaves behind: an SWC header or no per-fragment segment_id means linked, a per-fragment segment_id without an SWC header means split.

zarr_vectors_tools.multiresolution.skeleton_layout.LAYOUT_LINKED: str = 'linked_across_chunks'

Every vertex once, cross-chunk edges as link records (SWC).

zarr_vectors_tools.multiresolution.skeleton_layout.LAYOUT_SPLIT: str = 'split_at_chunk_faces'

Pieces split at chunk faces, the face vertex duplicated (precomputed).

zarr_vectors_tools.multiresolution.skeleton_layout.mark_skeleton_layout(store, layout)[source]

Record layout on the store’s root.

store is a path or an open root group. Pass the handle the writer already holds: a root’s attributes are written back whole from a handle’s in-memory copy, so a stale handle written to later would drop a marker set through another one.

Parameters:
Return type:

None

zarr_vectors_tools.multiresolution.skeleton_layout.skeleton_layout(store)[source]

The store’s skeleton layout, or None for a store of other geometry.

store is a path or an open root group.

Parameters:

store (Any)

Return type:

str | None