"""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.
"""
from __future__ import annotations
import pickle
from collections import defaultdict
from contextlib import nullcontext
from typing import Any
import numpy as np
import numpy.typing as npt
from zarr_vectors.building import rebuild_presence
[docs]
def simplify_polyline(
vertices: npt.NDArray[np.floating],
epsilon: float,
) -> npt.NDArray[np.floating]:
"""Simplify a polyline using Douglas-Peucker algorithm.
Args:
vertices: ``(N, D)`` ordered vertex positions.
epsilon: 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.
"""
n = len(vertices)
if n <= 2:
return vertices.copy()
keep = np.zeros(n, dtype=bool)
keep[0] = True
keep[-1] = True
_dp_recurse(vertices, 0, n - 1, epsilon, keep)
return vertices[keep].copy()
[docs]
def decimate_polyline(
vertices: npt.NDArray[np.floating],
stride: int,
) -> npt.NDArray[np.floating]:
"""Uniformly decimate a polyline, keeping every ``stride``-th vertex.
The linear-path equivalent of skeleton decimation
(:func:`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.
Args:
vertices: ``(N, D)`` ordered vertex positions.
stride: 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.
"""
n = len(vertices)
if n <= 2 or stride <= 1:
return vertices.copy()
keep = np.zeros(n, dtype=bool)
keep[0] = True
keep[-1] = True
keep[0:n:stride] = True
return vertices[keep].copy()
def _dp_recurse(
vertices: npt.NDArray,
start: int,
end: int,
epsilon: float,
keep: npt.NDArray[np.bool_],
) -> None:
"""Recursive Douglas-Peucker step."""
if end - start <= 1:
return
# Line segment from vertices[start] to vertices[end]
line_start = vertices[start]
line_end = vertices[end]
line_vec = line_end - line_start
line_len_sq = np.dot(line_vec, line_vec)
if line_len_sq < 1e-30:
# Degenerate segment — keep the farthest point
dists = np.sum((vertices[start + 1 : end] - line_start) ** 2, axis=1)
max_idx = start + 1 + np.argmax(dists)
if np.sqrt(dists[max_idx - start - 1]) > epsilon:
keep[max_idx] = True
_dp_recurse(vertices, start, max_idx, epsilon, keep)
_dp_recurse(vertices, max_idx, end, epsilon, keep)
return
# Perpendicular distances from each interior point to the line
points = vertices[start + 1 : end]
t = np.clip(
np.dot(points - line_start, line_vec) / line_len_sq,
0.0, 1.0,
)
projections = line_start + t[:, np.newaxis] * line_vec
dists = np.sqrt(np.sum((points - projections) ** 2, axis=1))
max_local = np.argmax(dists)
max_dist = dists[max_local]
max_idx = start + 1 + max_local
if max_dist > epsilon:
keep[max_idx] = True
_dp_recurse(vertices, start, max_idx, epsilon, keep)
_dp_recurse(vertices, max_idx, end, epsilon, keep)
[docs]
def simplify_polylines(
polylines: list[npt.NDArray[np.floating]],
epsilon: float,
*,
min_vertices: int = 2,
) -> list[npt.NDArray[np.floating]]:
"""Simplify a list of polylines using Douglas-Peucker.
Args:
polylines: List of ``(N_k, D)`` arrays.
epsilon: Distance threshold.
min_vertices: Minimum vertices to keep per polyline.
Returns:
List of simplified polylines.
"""
result: list[npt.NDArray] = []
for poly in polylines:
simplified = simplify_polyline(poly, epsilon)
if len(simplified) < min_vertices:
# Keep first and last at minimum
if len(poly) >= min_vertices:
indices = np.linspace(0, len(poly) - 1, min_vertices, dtype=int)
simplified = poly[indices]
else:
simplified = poly.copy()
result.append(simplified)
return result
def _coarsen_keep_indices(
vertices: npt.NDArray[np.floating],
*,
coarsen_mode: str,
stride: int,
simplify_epsilon: float | None,
min_vertices: int = 2,
) -> npt.NDArray[np.int64]:
"""Indices of the vertices a coarsen pass keeps, for aligning attributes.
Returns the same subset that ``decimate_polyline`` (decimate mode) or
``simplify_polylines([v], eps, min_vertices=2)`` (rdp mode) would keep,
but as indices into ``vertices`` — so a companion per-vertex attribute
array can be reduced identically to the positions (``vertices[idx]`` is
byte-for-byte what those helpers return).
"""
n = len(vertices)
if coarsen_mode == "decimate":
if n <= 2 or stride <= 1:
return np.arange(n, dtype=np.int64)
keep = np.zeros(n, dtype=bool)
keep[0] = True
keep[-1] = True
keep[0:n:stride] = True
return np.flatnonzero(keep).astype(np.int64)
# rdp — a None/≤0 epsilon is the "coarsen_factor ≤ 1" no-op: keep all
# vertices (matches the worker's ``rpos = merged`` branch), and never let a
# None epsilon reach _dp_recurse.
if simplify_epsilon is None or simplify_epsilon <= 0:
return np.arange(n, dtype=np.int64)
if n <= 2:
idx = np.arange(n, dtype=np.int64)
else:
keep = np.zeros(n, dtype=bool)
keep[0] = True
keep[-1] = True
_dp_recurse(vertices, 0, n - 1, simplify_epsilon, keep)
idx = np.flatnonzero(keep).astype(np.int64)
if len(idx) < min_vertices:
idx = (
np.linspace(0, n - 1, min_vertices, dtype=np.int64)
if n >= min_vertices else np.arange(n, dtype=np.int64)
)
return idx
[docs]
def subsample_polylines(
polylines: list[npt.NDArray[np.floating]],
bin_size: float | tuple[float, ...],
*,
max_per_bin: int = 1,
selection: str = "longest",
) -> dict[str, Any]:
"""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.
Args:
polylines: List of ``(N_k, D)`` arrays.
bin_size: Spatial bin edge length.
max_per_bin: How many polylines to keep per bin.
selection: How to pick representatives:
``"longest"``: keep the longest polyline(s).
``"random"``: keep random polyline(s).
``"first"``: keep the first polyline(s) by index.
Returns:
Dict with:
- ``polylines``: subsampled list of arrays
- ``indices``: original indices of kept polylines
- ``polyline_count``: number kept
- ``reduction_ratio``: original / kept
"""
n_total = len(polylines)
if n_total == 0:
return {
"polylines": [],
"indices": np.array([], dtype=np.int64),
"polyline_count": 0,
"reduction_ratio": 0,
}
ndim = polylines[0].shape[1]
if isinstance(bin_size, (int, float)):
bin_sizes = np.array([float(bin_size)] * ndim)
else:
bin_sizes = np.array(bin_size, dtype=np.float64)
# Compute midpoint for each polyline
midpoints = np.array([
poly[len(poly) // 2] for poly in polylines
], dtype=np.float64)
# Assign to bins
bin_indices = np.floor(midpoints / bin_sizes).astype(np.int64)
# Group by bin
bin_to_polys: dict[tuple, list[int]] = {}
for i in range(n_total):
key = tuple(bin_indices[i].tolist())
if key not in bin_to_polys:
bin_to_polys[key] = []
bin_to_polys[key].append(i)
# Select representatives
kept_indices: list[int] = []
for bin_key, members in bin_to_polys.items():
if len(members) <= max_per_bin:
kept_indices.extend(members)
continue
if selection == "longest":
lengths = [len(polylines[m]) for m in members]
sorted_members = [m for _, m in sorted(
zip(lengths, members), reverse=True
)]
kept_indices.extend(sorted_members[:max_per_bin])
elif selection == "random":
rng = np.random.default_rng()
chosen = rng.choice(members, size=max_per_bin, replace=False)
kept_indices.extend(chosen.tolist())
elif selection == "first":
kept_indices.extend(members[:max_per_bin])
else:
kept_indices.extend(members[:max_per_bin])
kept_indices.sort()
kept_polys = [polylines[i] for i in kept_indices]
return {
"polylines": kept_polys,
"indices": np.array(kept_indices, dtype=np.int64),
"polyline_count": len(kept_polys),
"reduction_ratio": n_total / max(len(kept_polys), 1),
}
[docs]
def coarsen_polylines(
polylines: list[npt.NDArray[np.floating]],
*,
simplify_epsilon: float | None = None,
subsample_bin_size: float | None = None,
max_per_bin: int = 1,
min_vertices: int = 2,
selection: str = "longest",
) -> dict[str, Any]:
"""Combined polyline coarsening: simplify then subsample.
Args:
polylines: Input polylines.
simplify_epsilon: Douglas-Peucker epsilon. None to skip.
subsample_bin_size: Spatial subsampling bin size. None to skip.
max_per_bin: Polylines to keep per bin (for subsampling).
min_vertices: Minimum vertices per polyline (for simplification).
selection: Subsampling selection mode.
Returns:
Dict with:
- ``polylines``: coarsened polylines
- ``vertex_count``: total vertices
- ``polyline_count``: number of polylines
- ``simplification_ratio``: vertex reduction from DP
- ``subsampling_ratio``: polyline reduction from subsampling
"""
v_input = sum(len(p) for p in polylines)
current = polylines
simplification_ratio = 1.0
subsampling_ratio = 1.0
# Step 1: simplify
if simplify_epsilon is not None:
current = simplify_polylines(
current, simplify_epsilon, min_vertices=min_vertices,
)
v_after = sum(len(p) for p in current)
simplification_ratio = v_input / max(v_after, 1)
# Step 2: subsample
kept_indices: npt.NDArray | None = None
if subsample_bin_size is not None:
sub_result = subsample_polylines(
current, subsample_bin_size,
max_per_bin=max_per_bin,
selection=selection,
)
current = sub_result["polylines"]
kept_indices = sub_result["indices"]
subsampling_ratio = sub_result["reduction_ratio"]
return {
"polylines": current,
"vertex_count": sum(len(p) for p in current),
"polyline_count": len(current),
"simplification_ratio": simplification_ratio,
"subsampling_ratio": subsampling_ratio,
"kept_indices": kept_indices,
}
# ===================================================================
# Chunk-local, executor-parallel pyramid coarsening
# ===================================================================
#
# Unlike the two helpers above (pure functions operating on in-memory
# polyline lists), everything below reads/writes a zarr-vectors store
# directly, one TARGET chunk at a time, so peak memory is O(one target
# chunk's fan-in) instead of O(the whole source level) — the fix for the
# OOM the whole-level ``_polyline_coarsen`` in ``coarsen.py`` hit on a
# 5M-streamline TRK file. Structure mirrors
# :func:`zarr_vectors_tools.multiresolution.strategies.skeletons.coarsen_skeleton_level`
# (Phase A per-target-chunk decimate+write+sidecar, Phase B cross-target
# link stitching by shard, Phase C sharded object-index reduce), but
# simplified for the streamline convention:
#
# - One streamline == one object; its per-chunk ``segment_id`` fragment
# attribute *is* the (stable, dense) object id — no separate
# ``object_id`` attribute needed.
# - Streamlines carry no branch structure, so intra-object connectivity
# is a simple chain, not a general graph.
# - Every fragment boundary (source-level ``_build_manifests_and_cross_links``)
# is stored as an EXPLICIT, DIRECTED links/0 record with a non-zero
# offsets segment (predecessor endpoint 0 -> successor endpoint 1). This lets a
# target-chunk worker recover object order (and walk direction) purely
# from local reads, without ever touching a global object manifest —
# geometric boundary-vertex coincidence (as skeletons.py falls back to)
# is not needed at all, and direction (which geometric coincidence
# alone cannot supply) is read straight off the source link.
def _read_polyline_children(
src,
child_ccs: list[tuple[int, ...]],
*,
ndim: int,
attr_names: list[str],
attr_dtypes: dict[str, Any],
attr_ncols: dict[str, int],
ccl_cells: list,
ccl_segments: list | None = None,
link_spec: dict | None = None,
) -> tuple[list[tuple], list[list]]:
"""One prefetch for everything a target chunk's plan reads from the source.
Returns ``(children, cell_records)``: ``children`` holds ``(scc, vgroups,
segs, attr_cells)`` for every child chunk with vertices -- ``segs`` is the
per-fragment ``segment_id`` column or None, ``attr_cells`` maps each
per-vertex attribute to its per-fragment groups or None -- and
``cell_records`` holds the decoded records of each entry of ``ccl_cells``,
in order, ``[]`` where the cell could not be read.
Every read here used to resolve its array node -- a ``zarr.json`` read --
afresh, and a link-cell read did so several times over: on a 100k-
streamline store the 21k cell reads of one pyramid level opened 400k
files and took 300 of the level's 500 seconds. ``cached_nodes`` resolves
each node once per task and ``batched_reads`` fetches every cell the plan
names in one pass. The plan covers the children's vertices, fragment
index, segment ids and per-vertex attributes, plus exactly the link
cells handed to this task.
Those cells arrive with the index of their offsets array
(``ccl_segments``, into ``link_spec`` from
:func:`zarr_vectors_tools.algorithms._links.link_cell_reads`), so they
are fetched and decoded with no per-task segment enumeration and no
per-cell metadata lookup. ``read_links_for_tuple`` re-resolved the
family policy, the level scales (re-opening the root group each time)
and the presence manifest for every cell, and the plan used to read
every offsets array's metadata to prefetch cells that were mostly never
decoded -- on a 20k-streamline pyramid that was most of its ``open()``
calls. Without ``link_spec`` each cell falls back to
``read_links_for_tuple``.
"""
from zarr_vectors.building import (
read_chunk_attributes,
read_chunk_fragment_attributes,
read_chunk_vertices,
read_links_for_tuple,
)
from zarr_vectors.constants import (
FRAGMENT_ATTRIBUTES,
VERTEX_ATTRIBUTES,
VERTEX_FRAGMENTS,
VERTICES,
)
from zarr_vectors.exceptions import ArrayError
from zarr_vectors_tools.algorithms._links import (
chunk_key_str,
link_cell_prefetch_plan,
prune_prefetch_plan,
read_link_cell_records,
)
child_keys = [chunk_key_str(c) for c in child_ccs]
plan: list[tuple[str, list[str]]] = [
(VERTICES, child_keys),
(VERTEX_FRAGMENTS, child_keys),
(f"{FRAGMENT_ATTRIBUTES}/segment_id", child_keys),
*((f"{VERTEX_ATTRIBUTES}/{name}", child_keys) for name in attr_names),
]
use_spec = link_spec is not None and ccl_segments is not None
children: list[tuple] = []
cell_records: list[list] = []
with src.cached_nodes():
# Only child cells that exist: on a local filesystem each absent cell
# would cost a failed open(). The link cells need no pruning -- the
# coordinator listed them.
plan = prune_prefetch_plan(src, plan)
if use_spec:
plan.extend(link_cell_prefetch_plan(ccl_cells, ccl_segments, link_spec))
with src.batched_reads(plan):
for scc in child_ccs:
try:
vgroups = read_chunk_vertices(src, scc, dtype=np.float32, ndim=ndim)
except ArrayError:
continue
if not vgroups:
continue
try:
segs = read_chunk_fragment_attributes(
src, "segment_id", scc, dtype=np.uint64,
)
except ArrayError:
segs = None
attr_cells: dict[str, Any] = {}
for name in attr_names:
try:
attr_cells[name] = read_chunk_attributes(
src, name, scc,
dtype=attr_dtypes.get(name, np.float32),
ncols=int(attr_ncols.get(name, 1)),
)
except ArrayError:
attr_cells[name] = None
children.append((scc, vgroups, segs, attr_cells))
for i, cell in enumerate(ccl_cells):
try:
if use_spec:
recs = read_link_cell_records(src, cell, ccl_segments[i], link_spec)
else:
recs = read_links_for_tuple(src, cell, delta=0)
except Exception:
recs = []
cell_records.append(recs)
return children, cell_records
def _build_local_polyline_plan(
src,
tcc: tuple[int, ...],
*,
scale: tuple[int, ...],
ndim: int,
keep_mask: npt.NDArray[np.uint8] | None,
ccl_cells: list | None = None,
attr_names: list[str] | None = None,
attr_dtypes: dict[str, Any] | None = None,
attr_ncols: dict[str, int] | None = None,
ccl_segments: list | None = None,
link_spec: dict | None = None,
) -> tuple[list[dict], dict, dict]:
"""Build ONE target chunk's coarsen plan by reading only its source children.
Reads the source children ``scc ∈ [tcc·scale, (tcc+1)·scale)``: per-fragment
vertices + ``segment_id`` (the object id), and the source-level directed
cross-chunk links (delta=0) incident on those children. A link whose both
endpoints resolve inside this target chunk chains two fragments of the same
object into one run (in predecessor -> successor order); a link with only
one endpoint inside is a genuine cross-target transition, and the inside
fragment's role (predecessor = about to exit, successor = just entered)
comes straight from which side of the record it was on.
Returns ``(groups, vcache)``: ``groups`` is one dict per surviving *run*
(an object may contribute more than one run to a target chunk if it visits
and leaves more than once) with keys ``oid``, ``members`` (ordered list of
``(chunk_coords, fragment_idx)``), ``head_cross``/``tail_cross`` (whether
the run's first/last vertex is a cross-target anchor Phase B must stitch).
``vcache`` is the per-fragment vertex read cache (reused by the caller, no
double read). ``acache`` mirrors ``vcache`` for each per-vertex attribute
in ``attr_names`` (``acache[name][(scc, fidx)]`` aligned 1:1 with the
fragment's vertices), so the caller can reduce attributes with the same
keep-mask it applies to positions; it is empty when ``attr_names`` is falsy.
"""
from itertools import product
attr_names = list(attr_names or [])
attr_dtypes = attr_dtypes or {}
attr_ncols = attr_ncols or {}
tcc = tuple(int(x) for x in tcc)
child_ccs = [
tuple(tcc[a] * scale[a] + d[a] for a in range(ndim))
for d in product(*[range(scale[a]) for a in range(ndim)])
]
children, cell_records = _read_polyline_children(
src, child_ccs, ndim=ndim, attr_names=attr_names, attr_dtypes=attr_dtypes,
attr_ncols=attr_ncols, ccl_cells=list(ccl_cells or ()),
ccl_segments=ccl_segments, link_spec=link_spec,
)
vcache: dict = {}
acache: dict = {name: {} for name in attr_names}
fragoid: dict = {}
child_ranges: dict = {} # scc -> (starts, ends, fidxs) for local->fragment resolve
for scc, vgroups, segs, attr_cells in children:
starts = []
st = 0
kept_fidx: list[int] = []
for fidx in range(len(vgroups)):
cnt = len(vgroups[fidx])
starts.append((st, st + cnt, fidx))
st += cnt
oid = int(segs[fidx]) if segs is not None and fidx < len(segs) else -1
if oid < 0:
continue
if keep_mask is not None:
if oid >= len(keep_mask) or int(keep_mask[oid]) == 0:
continue
vcache[(scc, fidx)] = vgroups[fidx]
fragoid[(scc, fidx)] = oid
kept_fidx.append(fidx)
# Per-vertex attribute cells for the kept fragments, sliced by the same
# fragment index the vertices use (read_chunk_attributes aligns 1:1).
if kept_fidx and attr_names:
for name in attr_names:
ag = attr_cells.get(name)
if ag is not None:
for fidx in kept_fidx:
if fidx < len(ag):
acache[name][(scc, fidx)] = ag[fidx]
child_ranges[scc] = (
np.asarray([r[0] for r in starts], np.int64),
np.asarray([r[1] for r in starts], np.int64),
np.asarray([r[2] for r in starts], np.int64),
)
def _resolve(scc, vi):
ranges = child_ranges.get(scc)
if ranges is None:
return None
s, e, f = ranges
if len(s) == 0:
return None
i = int(np.searchsorted(s, vi, side="right")) - 1
if i < 0 or vi >= int(e[i]):
return None
return int(f[i]), int(vi - s[i])
# Directed intra/cross classification from stored source cross-chunk
# links: both endpoints resolve inside this target chunk -> intra-target
# chain edge; exactly one resolves inside -> that fragment's matching end
# (last vertex if it was the predecessor slot, first vertex if it was the
# successor slot) is a cross-target anchor for Phase B, tagged with the
# OTHER target chunk it connects to AND the source link's own identity
# (``link_key``). ``split_polyline_at_boundaries`` does not duplicate a
# coincident vertex at a chunk crossing — a fragment boundary is simply
# wherever an ORIGINAL vertex happens to fall — so, unlike skeletons.py's
# Phase B, there is no shared coordinate for two independent workers to
# match on. What they CAN both compute identically is the exact source
# record ``((ccA, viA), (ccB, viB))``: cross-chunk-link storage is keyed
# by the sorted-unique chunk set, so a query from either side's own
# children reads the identical physical record — that raw tuple is the
# join key Phase B stitches on. It also means a transition can land in
# ANY other chunk, not just a face neighbor, so Phase B is told the exact
# partner chunk rather than discovering it via a grid-adjacency scan.
child_set = set(child_ranges)
intra_next: dict = {}
cross_out: dict = {} # member -> (partner tcc, link_key) its LAST vertex exits via
cross_in: dict = {} # member -> (partner tcc, link_key) its FIRST vertex entered via
# ``ccl_cells`` are the source cross-chunk-link cells touching this target's
# children (enumerated once by the coordinator and bucketed per target);
# their records were read above, one list per cell.
for recs in cell_records:
for rec in recs:
if len(rec) != 2:
continue
(ccA, viA), (ccB, viB) = rec
ccA = tuple(int(x) for x in ccA)
ccB = tuple(int(x) for x in ccB)
viA = int(viA)
viB = int(viB)
inA = ccA in child_set
inB = ccB in child_set
if not inA and not inB:
continue
rA = _resolve(ccA, viA) if inA else None
rB = _resolve(ccB, viB) if inB else None
memberA = (ccA, rA[0]) if rA is not None else None
memberB = (ccB, rB[0]) if rB is not None else None
if memberA is not None and memberA not in vcache:
memberA = None
if memberB is not None and memberB not in vcache:
memberB = None
if memberA is None and memberB is None:
continue
if memberA is not None and memberB is not None:
if fragoid.get(memberA) != fragoid.get(memberB):
continue
intra_next[memberA] = memberB
elif memberA is not None:
partner_tcc = tuple(int(ccB[a]) // scale[a] for a in range(ndim))
link_key = (ccA, viA, ccB, viB)
cross_out[memberA] = (partner_tcc, link_key)
else:
partner_tcc = tuple(int(ccA[a]) // scale[a] for a in range(ndim))
link_key = (ccA, viA, ccB, viB)
cross_in[memberB] = (partner_tcc, link_key)
members_by_oid: dict[int, list] = defaultdict(list)
for m, oid in fragoid.items():
if m in vcache:
members_by_oid[oid].append(m)
intra_targets = set(intra_next.values())
groups: list[dict] = []
for oid in sorted(members_by_oid):
members = set(members_by_oid[oid])
visited: set = set()
heads = [m for m in sorted(members) if m not in intra_targets]
for head in heads:
if head in visited:
continue
chain = [head]
visited.add(head)
cur = head
while (
cur in intra_next
and intra_next[cur] in members
and intra_next[cur] not in visited
):
cur = intra_next[cur]
chain.append(cur)
visited.add(cur)
head_in = cross_in.get(chain[0])
tail_out = cross_out.get(chain[-1])
groups.append({
"oid": int(oid),
"members": chain,
"head_partner": head_in[0] if head_in else None,
"head_link": head_in[1] if head_in else None,
"tail_partner": tail_out[0] if tail_out else None,
"tail_link": tail_out[1] if tail_out else None,
})
# Defensive: a cycle in (corrupt) source data would leave members
# unreached by the head walk above; emit them as singleton runs
# rather than silently dropping vertices.
for m in sorted(members - visited):
head_in = cross_in.get(m)
tail_out = cross_out.get(m)
groups.append({
"oid": int(oid),
"members": [m],
"head_partner": head_in[0] if head_in else None,
"head_link": head_in[1] if head_in else None,
"tail_partner": tail_out[0] if tail_out else None,
"tail_link": tail_out[1] if tail_out else None,
})
return groups, vcache, acache
def _coarsen_polyline_target_chunk(payload: dict, shared: dict | None = None) -> dict:
"""Coarsen ONE target chunk — a picklable worker for parallel pyramiding.
Reads only this target chunk's source children (via
:func:`_build_local_polyline_plan`), decimates/simplifies each surviving
run, writes the target chunk's vertices + ``segment_id``, and spills (a)
object-index rows sharded by OID for Phase C and (b) cross-target anchor
rows (with role + resolved local vertex index) for Phase B — all without
ever holding more than one target chunk's fan-in in memory.
"""
from zarr_vectors.building import (
get_resolution_level,
open_store,
write_chunk_attributes,
write_chunk_fragment_attributes,
write_chunk_vertices,
)
shared = shared or {}
ndim = int(shared["ndim"])
scale = tuple(int(s) for s in shared["scale"])
tcc = tuple(int(x) for x in payload["tcc"])
keep_mask = shared.get("keep_mask")
coarsen_mode = shared["coarsen_mode"]
stride = int(shared.get("stride", 1))
simplify_epsilon = shared.get("simplify_epsilon")
attr_names = list(shared.get("attr_names", []))
attr_dtypes = shared.get("attr_dtypes", {})
attr_ncols = shared.get("attr_ncols", {})
root = open_store(shared["store_path"], mode="r+")
src = get_resolution_level(root, shared["source_level"])
level_group = get_resolution_level(root, shared["target_level"])
groups, vcache, acache = _build_local_polyline_plan(
src, tcc, scale=scale, ndim=ndim, keep_mask=keep_mask,
ccl_cells=payload.get("ccl_cells"),
attr_names=attr_names, attr_dtypes=attr_dtypes, attr_ncols=attr_ncols,
ccl_segments=payload.get("ccl_segments"),
link_spec=shared.get("link_spec"),
)
input_fragments = int(len(vcache))
input_vertices = int(sum(len(v) for v in vcache.values()))
input_objects = int(len({g["oid"] for g in groups}))
# (oid, positions, head source chunk, head source fragment index). The
# head member is the run's earliest fragment in WALK order (the chain is
# built predecessor -> successor), so its position in the object's source
# manifest is what orders the runs along the streamline -- see
# ``_reduce_polyline_object_index_shard``.
pieces: list[tuple[int, npt.NDArray, tuple[int, ...], int]] = []
# Per-vertex attribute pieces, aligned 1:1 with ``pieces`` (one array per
# surviving run, reduced by the same keep-mask as the positions).
attr_pieces: dict[str, list[npt.NDArray]] = {name: [] for name in attr_names}
# sidecar row = (*ccA, viA, *ccB, viB, role, local_vi); role 0=pred(exit)
# 1=succ(entry). (ccA, viA, ccB, viB) is the SOURCE link's own identity
# (see _build_local_polyline_plan) — the join key Phase B stitches two
# target chunks' sidecars on, since polyline fragments have no shared
# coincident coordinate at a boundary to match on geometrically.
sc_rows: list[tuple[int, ...]] = []
partners: set[tuple[int, ...]] = set()
total_out_vertices = 0
chunk_offset = 0
for g in groups:
parts = [vcache[m] for m in g["members"]]
merged = parts[0] if len(parts) == 1 else np.concatenate(parts, axis=0)
if len(merged) == 0:
continue
# One keep-mask drives BOTH the positions and every per-vertex
# attribute, so a surviving vertex keeps its own attribute value.
# _coarsen_keep_indices reproduces exactly what decimate_polyline /
# simplify_polylines(min_vertices=2) / the rdp-no-op branch would keep.
keep_idx = _coarsen_keep_indices(
merged, coarsen_mode=coarsen_mode, stride=stride,
simplify_epsilon=simplify_epsilon,
)
rpos = merged[keep_idx]
if len(rpos) == 0:
continue
local_first = chunk_offset
local_last = chunk_offset + len(rpos) - 1
if g["head_link"] is not None:
ccA, viA, ccB, viB = g["head_link"]
sc_rows.append((*ccA, viA, *ccB, viB, 1, local_first))
partners.add(g["head_partner"])
if g["tail_link"] is not None:
ccA, viA, ccB, viB = g["tail_link"]
sc_rows.append((*ccA, viA, *ccB, viB, 0, local_last))
partners.add(g["tail_partner"])
_head_cc, _head_fidx = g["members"][0]
pieces.append((
g["oid"], rpos,
tuple(int(x) for x in _head_cc), int(_head_fidx),
))
# Reduce each attribute with the identical keep-mask. A member missing
# a cell (unreadable attr chunk) falls back to zeros so attr_pieces stays
# 1:1 with pieces — the write path requires that alignment.
for name in attr_names:
aparts = [acache[name].get(m) for m in g["members"]]
if any(a is None for a in aparts):
ncols = int(attr_ncols.get(name, 1))
shape = (len(rpos),) if ncols == 1 else (len(rpos), ncols)
attr_pieces[name].append(
np.zeros(shape, dtype=attr_dtypes.get(name, np.float32))
)
else:
merged_a = aparts[0] if len(aparts) == 1 else np.concatenate(aparts, axis=0)
attr_pieces[name].append(merged_a[keep_idx])
chunk_offset += len(rpos)
total_out_vertices += len(rpos)
recs: list[tuple[int, int, tuple[int, ...], int]] = []
if pieces:
# record_presence=False: these run in parallel worker PROCESSES, and
# nonempty_chunks is an array-wide attribute, so stamping it here would
# race across workers (a Windows hard-fail on the zarr.json rename).
# The coordinator's rebuild_nonempty_manifests pass re-derives the
# manifests once, after Phase A, from the on-disk cells.
write_chunk_vertices(
level_group, tcc, [p[1] for p in pieces], dtype=np.float32,
record_presence=False,
)
seg_ids = np.array([p[0] for p in pieces], dtype=np.uint64)
write_chunk_fragment_attributes(
level_group, "segment_id", tcc, seg_ids, dtype=np.uint64,
record_presence=False,
)
# Per-vertex attributes: one ragged group per fragment, same order as
# the vertex pieces above. Manifests are rebuilt by the coordinator.
for name in attr_names:
write_chunk_attributes(
level_group, name, tcc, attr_pieces[name],
dtype=attr_dtypes.get(name, np.float32), record_presence=False,
)
recs = [
(int(p[0]), fidx, p[2], p[3]) for fidx, p in enumerate(pieces)
]
# Object-index rows travel back inline, one compact int64 array per
# target chunk: (oid, fragment_idx, *head source chunk, head fragment_idx).
# They used to be spilled to one .npy per (target chunk, oid shard) -- 64
# to 4096 shards -- and read back file by file in Phase C, so a
# 5000-chunk level put a million tiny files through the filesystem on
# its way to the object index (measured: the spill and its rmtree were
# most of a level's serial time on NTFS). The rows are O(fragments),
# the same order as the anchor rows below -- a streamline has one more
# fragment than it has crossings -- and at 48 bytes each they are a
# rounding error next to the vertices.
oid_rows = (
np.asarray(
[(oid, fidx, *head_cc, head_fidx) for oid, fidx, head_cc, head_fidx in recs],
dtype=np.int64,
).reshape(-1, 3 + ndim)
if recs else None
)
# Cross-target anchor rows travel back inline in the result dict rather
# than through a per-chunk .npy sidecar: the coordinator forwards them
# straight into the Phase B payloads. The total is O(cross-chunk
# crossings) — far smaller than vertex volume — so it fits in RAM, and
# this removes thousands of tiny-file writes/reads/deletes (a real
# serial cost, and a Windows handle-churn hazard).
anchors = (
np.asarray(sc_rows, dtype=np.int64).reshape(-1, 2 * ndim + 4)
if sc_rows else None
)
return {
"tcc": tcc,
"input_fragments": input_fragments,
"input_vertices": input_vertices,
"input_objects": input_objects,
"fragment_count": int(len(recs)),
"oid_rows": oid_rows,
"anchors": anchors,
"partners": [list(p) for p in partners],
"vertex_count": int(total_out_vertices),
}
def _reduce_polyline_object_index_shard(
payload: dict, shared: dict | None = None,
) -> dict:
"""Reduce one OID shard's chunk spills into manifest blobs, in WALK ORDER.
The skeleton reducer this replaces
(:func:`...strategies.skeletons._reduce_object_index_shard`) sorts each
object's fragments by ``(chunk, fragment_index)``. For a skeleton that is
only a deterministic tie-break -- its pieces are independently rooted trees
joined by explicit links, so their order carries nothing. For a polyline
the manifest order **is** the path: every reader concatenates the fragments
in manifest order, so a chunk-sorted manifest hands back a streamline whose
segments are shuffled into chunk-coordinate order. A tract running from
high x to low x came back reversed in pieces (measured: level 0 walked
25 -> 5 while level 1 walked 9 -> 5, 19 -> 10, 25 -> 20), which silently
corrupts every tangent, length and endpoint computed above level 0.
Each row carries the run's head SOURCE fragment. Its position in the
object's source manifest is the run's position along the path, so the
correct order is recovered by reading only this shard's objects' manifests
-- ``read_object_manifests(ids=...)`` is one coordinate selection, never
the whole level's O(objects) decode.
``payload["rows"]`` is one int64 array for the whole shard, ``(oid,
fragment_idx, *target chunk, *head source chunk, head fragment_idx)``,
cut from the Phase A results by the coordinator so every row of an object
is in the same shard -- see
:func:`zarr_vectors_tools.multiresolution.object_index.shard_rows_by_object`.
"""
from zarr_vectors.building import (
encode_object_manifest_blocks,
get_resolution_level,
open_store,
read_object_manifests,
)
shared = shared or {}
sid_ndim = int(shared["sid_ndim"])
width = 3 + 2 * sid_ndim
rows = np.asarray(
payload.get("rows", np.zeros((0, width), np.int64)), dtype=np.int64,
).reshape(-1, width)
rows_by_oid: dict[int, list[tuple[tuple[int, ...], int, tuple[int, ...], int]]]
rows_by_oid = defaultdict(list)
for row in rows.tolist():
rows_by_oid[row[0]].append((
tuple(row[2:2 + sid_ndim]),
row[1],
tuple(row[2 + sid_ndim:2 + 2 * sid_ndim]),
row[2 + 2 * sid_ndim],
))
oids = np.asarray(sorted(rows_by_oid), dtype=np.int64)
walk_pos: dict[int, dict[tuple[tuple[int, ...], int], int]] = {}
if len(oids):
src = get_resolution_level(
open_store(str(shared["store_path"]), mode="r"),
int(shared["source_level"]),
)
for oid, manifest in read_object_manifests(src, ids=oids.tolist()).items():
walk_pos[int(oid)] = {
(tuple(int(c) for c in cc), int(f)): i
for i, (cc, f) in enumerate(manifest)
}
blobs: list[bytes] = []
for oid in oids.tolist():
positions = walk_pos.get(int(oid), {})
entries = rows_by_oid[int(oid)]
# Runs whose head is missing from the source manifest (which cannot
# happen for a store this coarsener accepts) sort last rather than
# first, and stay deterministic via the chunk/fragment tie-break.
entries.sort(
key=lambda r: (positions.get((r[2], r[3]), len(positions)), r[0], r[1])
)
blobs.append(encode_object_manifest_blocks(
[(cc, fidx) for cc, fidx, _h, _hf in entries], sid_ndim=sid_ndim,
))
return {
"oid": oids,
"blobs": pickle.dumps(blobs, protocol=pickle.HIGHEST_PROTOCOL),
}
def _polyline_cross_edge_shard(payload: dict, shared: dict | None = None) -> dict:
"""Phase B worker: write directed cross-target-chunk links for ONE ccl shard.
Each task owns the adjacent target-chunk pairs whose ``k2`` cells fall in a
single outer shard (the coordinator partitions pairs by shard, so writers
never collide). For each pair it matches coincident ``(segment_id, coord)``
anchors from the two chunks' sidecars, using the ``role`` each anchor was
tagged with in Phase A (0=predecessor/exit, 1=successor/entry) to orient
the written link — this is what a plain undirected coincidence match
(as skeletons.py Phase B does) cannot supply on its own.
"""
from zarr_vectors.building import get_resolution_level, open_store, write_link_cells
shared = shared or {}
ndim = int(shared["ndim"])
# Anchor rows arrive inline (see _coarsen_polyline_target_chunk), keyed by
# source target-chunk; no per-chunk .npy sidecar to load.
sidecar_arrays = {
tuple(int(x) for x in e["tcc"]): e["arr"]
for e in payload.get("anchors", [])
}
pairs = payload["pairs"]
link_w = 2 * ndim + 2
# Sorted-key equi-join, entirely in NumPy — no per-row Python objects.
# A single chunk's sidecar can hold MILLIONS of rows at whole-brain
# scale; a `dict[tuple -> list]` keymap there costs ~500-600 bytes of
# pure Python object overhead per row (measured ~1.2GB for 2M rows),
# enough alone to blow a worker's memory budget. Each row's key (the
# source link's own identity, see _build_local_polyline_plan) is
# unique within one chunk's sidecar by construction — a chunk only
# emits ONE endpoint per source cross-chunk-link record — so this is a
# simple sorted-array equi-join: sort both chunks' keys (viewed as
# opaque fixed-width blobs, ~30 bytes/row including the sort's working
# arrays), binary-search one into the other, keep exact hits.
sorted_cache: dict[tuple[int, ...], tuple | None] = {}
def _load_sorted(cc: tuple[int, ...]):
if cc in sorted_cache:
return sorted_cache[cc]
raw = sidecar_arrays.get(cc)
if raw is None:
sorted_cache[cc] = None
return None
arr = np.asarray(raw, dtype=np.int64)
if arr.size == 0:
sorted_cache[cc] = None
return None
keys = np.ascontiguousarray(arr[:, :link_w])
void_keys = keys.view(np.dtype((np.void, keys.dtype.itemsize * link_w))).reshape(-1)
order = np.argsort(void_keys, kind="stable")
result = (void_keys[order], arr[order, link_w], arr[order, link_w + 1])
sorted_cache[cc] = result
return result
links: list = []
for A_, B_ in pairs:
A = tuple(int(x) for x in A_)
B = tuple(int(x) for x in B_)
da = _load_sorted(A)
db = _load_sorted(B)
if da is None or db is None:
continue
keysA, rolesA, visA = da
keysB, rolesB, visB = db
pos = np.searchsorted(keysB, keysA)
in_range = pos < len(keysB)
pos_clamped = np.where(in_range, pos, 0)
hit = in_range & (keysB[pos_clamped] == keysA)
if not np.any(hit):
continue
idxA = np.flatnonzero(hit)
idxB = pos[idxA]
ra, va = rolesA[idxA], visA[idxA]
rb, vb = rolesB[idxB], visB[idxB]
stitch = ra != rb # same-role anchors can't stitch (data anomaly)
idxA, idxB = idxA[stitch], idxB[stitch]
ra, va = ra[stitch], va[stitch]
vb = vb[stitch]
a_is_pred = ra == 0
for i in range(len(idxA)):
if a_is_pred[i]:
links.append([(A, int(va[i])), (B, int(vb[i]))])
else:
links.append([(B, int(vb[i])), (A, int(va[i]))])
if links:
root = open_store(shared["store_path"], mode="r+")
level_group = get_resolution_level(root, shared["target_level"])
# Writes only the cells these records touch and does NOT maintain
# the family-wide counts; the coordinator's finalize_links pass
# reconciles them once every worker is done.
#
# directed=True is load-bearing here: endpoint order IS the data
# (predecessor -> successor, chosen by role above), so a canonical
# sort would destroy it.
write_link_cells(
level_group, links, ndim, delta=0, link_width=2, directed=True,
)
return {"n_links": len(links)}
[docs]
def coarsen_polyline_level(
store_path: str,
source_level: int,
target_level: int,
*,
coarsen_factor: float = 1.0,
sparsity_factor: float = 1.0,
chunk_scale_factor: int | tuple[int, ...] = 1,
sparsity_strategy: str = "random",
sparsity_seed: int | None = None,
coarsen_mode: str = "rdp",
simplify_epsilon: float | None = None,
compressor: Any = None,
executor: Any = None,
attribute_values: npt.NDArray | None = None,
) -> dict[str, Any]:
"""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 :func:`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
:func:`zarr_vectors_tools.multiresolution.coarsen.read_coarsening_record`).
"""
from zarr_vectors.building import (
OBJECT_INDEX,
OBJECT_INDEX_LAYOUT_V1,
VERTEX_ATTRIBUTES,
VERTICES,
LevelMetadata,
create_attribute_array,
create_fragment_attribute_array,
create_links_array,
create_links_family,
create_object_attributes_array,
create_object_index_array,
create_resolution_level,
create_vertices_array,
finalize_links,
get_level_chunk_shape,
get_resolution_level,
list_chunk_keys,
open_store,
read_all_object_manifests,
read_chunk_fragment_attributes,
read_level_metadata,
read_object_attributes,
read_root_metadata,
write_object_attributes,
write_object_manifests,
)
from zarr_vectors.constants import CAP_PRESERVED_OBJECT_IDS
from zarr_vectors.exceptions import ArrayError
from zarr_vectors_tools.multiresolution.coarsen import (
_rdp_mode_refusal,
_stamp_root_capability,
_write_coarsening_record,
check_rdp_tolerance,
)
from zarr_vectors_tools.multiresolution.constants import (
CROSS_LINK_TASK_SHARD_AXIS,
)
from zarr_vectors_tools.multiresolution.groupings import group_labels_for
from zarr_vectors_tools.multiresolution.object_index import shard_rows_by_object
from zarr_vectors_tools.multiresolution.object_selection import apply_sparsity
# An explicit tolerance is checked before the store is opened. Decimate
# mode used to ignore it without a word, which let a caller believe a
# stride pyramid had been simplified to a distance.
if simplify_epsilon is not None:
refusal = _rdp_mode_refusal(coarsen_mode)
if refusal is not None:
raise ValueError(f"simplify_epsilon does not apply: {refusal}")
simplify_epsilon = check_rdp_tolerance(
simplify_epsilon, name="simplify_epsilon",
)
tolerance_source = "explicit" if simplify_epsilon is not None else "derived"
# Per-target-chunk work is dispatched through ``executor``; the default
# runs serially in-process (mirrors coarsen_skeleton_level's contract).
if executor is None:
def executor(func, items, shared=None):
return [func(it, shared=shared) for it in items]
root = open_store(str(store_path), mode="r+")
root_meta = read_root_metadata(root)
ndim = root_meta.sid_ndim
src = get_resolution_level(root, source_level)
# Per-vertex attributes present on the source: carry each forward, reduced
# by the same keep-mask as the positions and re-written per target chunk.
vattr_names: list[str] = []
vattr_dtypes: dict[str, str] = {}
vattr_ncols: dict[str, int] = {}
vattr_channels: dict[str, list[str] | None] = {}
if VERTEX_ATTRIBUTES in src:
# ``.children()`` (not iterating the group) — each vertex attribute is a
# flat ARRAY node, which plain iteration (group_keys only) misses, the
# same reason the object_attributes carry-forward below uses children().
for _name in src[VERTEX_ATTRIBUTES].children():
try:
_meta = src.read_array_meta(f"{VERTEX_ATTRIBUTES}/{_name}")
except ArrayError:
continue
_cn = _meta.get("channel_names")
vattr_names.append(_name)
vattr_dtypes[_name] = _meta.get("dtype", "float32")
vattr_ncols[_name] = len(_cn) if _cn else 1
vattr_channels[_name] = _cn
try:
src_level_meta = read_level_metadata(root, source_level)
except Exception:
src_level_meta = None
src_chunk_shape = get_level_chunk_shape(root_meta, src_level_meta)
# ``coarsen_factor`` is a ratio against the SOURCE level's bin, not the
# root's, matching coarsen_level and the fragment coarsener — so factors
# compound down the pyramid. Level 0 carries no bin_shape of its own,
# so the root's effective bin seeds the chain.
_root_bin = tuple(float(b) for b in root_meta.effective_bin_shape)
_src_bin = getattr(src_level_meta, "bin_shape", None) if src_level_meta else None
source_bin = tuple(float(b) for b in _src_bin) if _src_bin else _root_bin
target_bin_shape = tuple(b * float(coarsen_factor) for b in source_bin)
if isinstance(chunk_scale_factor, (tuple, list)):
scale = tuple(int(s) for s in chunk_scale_factor)
else:
scale = tuple(int(chunk_scale_factor) for _ in range(ndim))
target_chunk_shape = tuple(float(s) * int(r) for s, r in zip(src_chunk_shape, scale))
same_as_root = all(
abs(t - r) < 1e-9 for t, r in zip(target_chunk_shape, root_meta.chunk_shape)
)
chunk_shape_override = None if same_as_root else target_chunk_shape
# ``coarsen_factor <= 1`` is the documented identity (no vertex reduction)
# for BOTH modes — see coarsen_level's "1.0 is the identity" contract.
# Decimate already collapses to stride 1 (a straight copy); rdp must match
# rather than simplify at a chunk-derived epsilon, so leave the epsilon
# unset (the worker treats an unset/non-positive epsilon as a no-op) and
# only derive one when the factor genuinely asks for reduction.
#
# The tolerance scales with the TARGET BIN, which is the source level's
# bin times the factor and therefore compounds down the pyramid, exactly
# as ``coarsen_factor`` is documented to. It used to scale with the
# source level's CHUNK, which only grows when chunk_scale_factor does:
# with the default scaling every level got the same tolerance, so the
# second application removed nothing and ``--coarsen 8,8`` produced a
# level 2 that was a copy of level 1 (measured 360 -> 42 -> 42 vertices).
#
# An explicit tolerance replaces the derivation outright, including at a
# factor of 1: the caller asked for a distance, and the factor is then
# only the level's bin (its NGFF scale).
if coarsen_mode == "rdp" and simplify_epsilon is None and coarsen_factor > 1.0:
simplify_epsilon = 0.5 * float(min(target_bin_shape))
stride = max(1, int(round(coarsen_factor)))
# The bin the level records, which is also its scale in the store's OME
# ``multiscales`` block. With an explicit tolerance the factor decides
# nothing else, and the recommended recipe leaves it at 1 while the
# chunks double -- so every level declared scale 1, the same as level 0.
# Such a level is at least as coarse as its chunks are wide, so its bin
# grows by the chunk scale where that is the larger. A derived tolerance
# and a decimation stride are read back from the bin by a pyramid
# refresh, so those levels keep the factor's bin.
level_bin_shape = target_bin_shape
if tolerance_source == "explicit" and coarsen_mode == "rdp":
level_bin_shape = tuple(
b * max(float(coarsen_factor), float(s))
for b, s in zip(source_bin, scale)
)
coarsening_method = "polyline_decimate" if coarsen_mode == "decimate" else "polyline_rdp"
src_index_meta = src.read_array_meta(OBJECT_INDEX)
n_src = int(src_index_meta.get("num_objects", 0))
if n_src == 0:
return {"vertex_count": 0, "object_count": 0, "method": coarsening_method}
src_vertex_chunks = list_chunk_keys(src, VERTICES)
if not src_vertex_chunks:
return {"vertex_count": 0, "object_count": 0, "method": coarsening_method}
# Every fragment boundary must be reconstructable locally, which needs
# fragment_attributes/segment_id on the source. Core's write_polylines
# does not write it, so a store written directly by core gets it here,
# from its own object manifests, rather than a refusal. The dense id,
# whatever source ids the store has: it is what objects are rebuilt from.
probe_seg = read_chunk_fragment_attributes(
src, "segment_id", tuple(int(x) for x in src_vertex_chunks[0]),
dtype=np.uint64, default=None,
)
if probe_seg is None:
from zarr_vectors.building import refresh_arrays_present
from zarr_vectors_tools.convert.ingest._object_columns import (
stamp_level_object_columns,
)
stamp_level_object_columns(src, vertex_count=False, dense_ids=True)
# So a reader gating on ``arrays_present`` sees the new column.
refresh_arrays_present(src)
# --- Phase 0: sparsity keep-set (O(objects), never O(fragments) unless
# no cheap per-object signal exists at a coarser source level) ---------
if sparsity_factor > 1.0 and n_src > 1:
# A missing object attribute raises StoreError on current core (older
# cores raised KeyError); treat both as "length not present".
from zarr_vectors.exceptions import StoreError
length_arr = None
try:
length_arr = np.asarray(read_object_attributes(src, "length"), dtype=np.float64)
except (KeyError, StoreError):
length_arr = None
if length_arr is not None:
alive_mask = length_arr > 0
lengths = length_arr if sparsity_strategy == "length" else None
elif source_level == 0:
alive_mask = np.ones(n_src, dtype=bool)
lengths = None
if sparsity_strategy == "length":
raise ValueError(
"'length' sparsity strategy requires object_attributes/"
"length (enable compute_length at ingest)"
)
else:
# No cheap per-object signal at this coarser source level — fall
# back to an O(fragments) manifest read, exactly like
# coarsen_skeleton_level's "length" fallback. Only paid when
# sparsity is active, not on the unconditional hot path.
manifest_lens = np.array(
[len(m) for m in read_all_object_manifests(src)], dtype=np.float64,
)
alive_mask = manifest_lens > 0
lengths = manifest_lens if sparsity_strategy == "length" else None
group_labels = (
group_labels_for(src, n_src)
if sparsity_strategy == "group" else None
)
kept = apply_sparsity(
n_src, 1.0 / sparsity_factor, sparsity_strategy,
seed=sparsity_seed, lengths=lengths, alive_mask=alive_mask,
group_labels=group_labels, attribute_values=attribute_values,
# Cumulative: keep 1/sparsity_factor of the SURVIVING objects, so
# a repeated factor sparsifies each level relative to the previous
# one (503k -> 50k -> 5k -> ...), not relative to the original.
relative_to="alive",
)
keep_mask = np.zeros(n_src, dtype=np.uint8)
keep_mask[np.asarray(kept, dtype=np.int64)] = 1
else:
keep_mask = None
target_chunks = sorted({
tuple(int(cc[a] // scale[a]) for a in range(ndim))
for cc in src_vertex_chunks
})
if not target_chunks:
return {"vertex_count": 0, "object_count": 0, "method": coarsening_method}
level_meta = LevelMetadata(
level=target_level,
vertex_count=0,
# "fragment_attributes" must be listed: this coarsener always writes
# fragment_attributes/segment_id (needed to reconstruct object
# connectivity locally — see the module docstring). Omitting it here
# previously made neuroglancer's reader treat coarsened levels as
# lacking per-fragment segment ids (gated on this exact list, see
# datasource/zarr-vectors/frontend.ts's hasFragmentSegmentIds), so it
# silently fell back to a meaningless chunk-local fragment index for
# picking/selection at every level except the finest.
arrays_present=(
["vertices", "object_index", "fragment_attributes"]
+ (["vertex_attributes"] if vattr_names else [])
),
bin_shape=level_bin_shape,
# Fold-change relative to LEVEL 0, not to the source level: this is
# what becomes the NGFF ``scale`` transform. With per-level coarsen
# factors the two differ — [2, 2] is ratio 2 then 4 — so it has to be
# derived from the bin shapes rather than echoing coarsen_factor.
bin_ratio=tuple(
max(1, int(round(float(t) / float(r))))
for t, r in zip(level_bin_shape, _root_bin)
),
chunk_shape=chunk_shape_override,
object_sparsity=(1.0 / sparsity_factor),
coarsening_method=coarsening_method,
parent_level=source_level,
preserves_object_ids=True,
inherited_num_objects=n_src,
shared_fragments=False,
)
level_group = create_resolution_level(root, target_level, level_meta)
# A chunk array's codec pipeline is fixed when it is created, so the
# compressor only has to be active around the create_* calls — every later
# per-cell write (Phase A/B workers included, in their own processes)
# encodes to match via zarr's array API. The `with` block must CLOSE
# before any worker dispatch: batched_writes defers array metas to its
# flush, and a worker that reads an unflushed meta would see nothing.
_codec_ctx = (
level_group.batched_writes(compressor=compressor)
if compressor else nullcontext()
)
with _codec_ctx:
create_vertices_array(level_group, dtype="float32")
create_object_index_array(level_group)
create_fragment_attribute_array(
level_group, "segment_id", dtype="uint64",
)
# Pre-create each carried per-vertex attribute array once, single
# process, so the concurrent Phase A workers only WRITE cells.
for _name in vattr_names:
create_attribute_array(
level_group, _name, dtype=vattr_dtypes[_name],
channel_names=vattr_channels[_name],
)
# Pre-create the kN cross-chunk-link arrays with LEVEL-WIDE dims so
# Phase-B workers only WRITE cells (no create-race).
tc_arr = np.asarray(target_chunks, dtype=np.int64)
cmin = tc_arr.min(axis=0)
cmax = tc_arr.max(axis=0)
chunk_origin = tuple(int(min(0, int(cmin[a]))) for a in range(ndim))
chunk_grid_shape = tuple(
int(max(1, int(cmax[a]) - chunk_origin[a] + 1)) for a in range(ndim)
)
# Fix the family policy up front so the decentralized Phase-B workers
# agree on it rather than racing to establish it. This stamps the
# links/0 GROUP only and materialises no offsets array, which is what
# this family wants: polyline connectivity is implicit-sequential
# within a fragment, so there are no intra records and the only arrays
# that should ever appear here are the ones Phase B's records land in.
# (An empty-but-existing array — zarr.json present, zero cells — makes
# neuroglancer's reader 404 and fail the whole chunk download instead
# of treating it as "no records", which cascades into the LOD picker
# falling back to level 0.)
#
# directed=True because endpoint order is the data here: a record is
# predecessor -> successor, and a canonical sort would destroy it.
create_links_family(
level_group, delta=0, link_width=2, sid_ndim=ndim, directed=True,
)
sharedA = {
"store_path": str(store_path),
"source_level": int(source_level),
"target_level": int(target_level),
"scale": list(scale),
"ndim": int(ndim),
"keep_mask": keep_mask,
"coarsen_mode": coarsen_mode,
"stride": int(stride),
"simplify_epsilon": simplify_epsilon,
"attr_names": vattr_names,
"attr_dtypes": vattr_dtypes,
"attr_ncols": vattr_ncols,
}
# Enumerate the source cross-chunk-link cells ONCE and bucket each cell to
# the target chunk(s) that own its endpoint chunks (chunk // scale). Replaces
# a per-target-per-child cell scan (O(target_chunks × children × cells))
# with a single O(cells) pass; workers then read only their bucket's cells.
#
# The same pass records which offsets array each cell lives in; the
# arrays' decode parameters travel once in ``sharedA``, so a worker reads
# its cells without re-deriving any of that per task or per cell.
from zarr_vectors_tools.algorithms._links import link_cell_reads
link_cells, link_segments, link_spec = link_cell_reads(src, delta=0)
sharedA["link_spec"] = link_spec
cells_by_target: dict[tuple[int, ...], list] = defaultdict(list)
segs_by_target: dict[tuple[int, ...], list] = defaultdict(list)
for cell, seg in zip(link_cells, link_segments):
seen_t: set = set()
for c in cell:
t = tuple(int(c[a]) // scale[a] for a in range(ndim))
if t in seen_t:
continue
seen_t.add(t)
cells_by_target[t].append(cell)
segs_by_target[t].append(seg)
payloadsA = [
{
"tcc": list(tcc),
"ccl_cells": cells_by_target.get(tuple(tcc), []),
"ccl_segments": segs_by_target.get(tuple(tcc), []),
}
for tcc in target_chunks
]
empty_blob = b"\x00\x00\x00\x00"
resultsA = list(executor(_coarsen_polyline_target_chunk, payloadsA, sharedA))
total_out_vertices = 0
total_fragments = 0
sidecar_arrays: dict[tuple[int, ...], np.ndarray] = {}
# Object-index rows from every target chunk, each block prefixed with
# the chunk it came from so the reducer can name the fragment. Gathered
# inline like the anchors: the whole level's rows are the same order of
# magnitude as the anchor arrays collected alongside them.
row_blocks: list[np.ndarray] = []
cross_target_pairs: set[tuple[tuple[int, ...], tuple[int, ...]]] = set()
for res in resultsA:
total_fragments += int(res["fragment_count"])
total_out_vertices += int(res["vertex_count"])
tcc = tuple(int(x) for x in res["tcc"])
anchors = res.get("anchors")
if anchors is not None and len(anchors):
sidecar_arrays[tcc] = anchors
rows = res.get("oid_rows")
if rows is not None and len(rows):
tcc_cols = np.broadcast_to(np.asarray(tcc, dtype=np.int64), (len(rows), ndim))
row_blocks.append(
np.concatenate([rows[:, :2], tcc_cols, rows[:, 2:]], axis=1),
)
# Cross-target anchors report their OTHER target chunk directly —
# a source-level transition can land in ANY other chunk, not just
# a face neighbor (split_polyline_at_boundaries does not
# decompose multi-axis crossings into single-axis hops) — so
# Phase B's shard pairs come from what Phase A actually observed,
# not a grid-adjacency scan.
for p in res.get("partners", []):
partner = tuple(int(x) for x in p)
cross_target_pairs.add(tuple(sorted((tcc, partner))))
resultsA = []
level_meta.vertex_count = int(total_out_vertices)
create_resolution_level(root, target_level, level_meta)
# --- Phase C: shard-parallel object-index reduce + one-shot commit ---
# Shards are contiguous object-id ranges cut from the gathered rows, so
# each task owns whole objects and there is no spill directory to
# populate, scan and remove.
all_rows = (
np.concatenate(row_blocks, axis=0) if row_blocks
else np.zeros((0, 3 + 2 * ndim), dtype=np.int64)
)
row_blocks = []
manifest_blobs: list[bytes] = [empty_blob] * int(n_src)
payloadsC = [{"rows": shard} for shard in shard_rows_by_object(all_rows)]
sharedC = {
"sid_ndim": int(ndim),
"store_path": str(store_path),
"source_level": int(source_level),
}
if payloadsC:
for rc in executor(
_reduce_polyline_object_index_shard, payloadsC, sharedC,
):
oids = np.asarray(rc.get("oid", np.zeros((0,), np.int64)), np.int64)
blobs = pickle.loads(rc.get("blobs", b"")) if len(oids) else []
for i, oid in enumerate(oids.tolist()):
if 0 <= int(oid) < int(n_src):
manifest_blobs[int(oid)] = blobs[i]
write_object_manifests(level_group, manifest_blobs)
level_group.write_array_meta(OBJECT_INDEX, {
"zv_array": "object_index",
"num_objects": int(n_src),
"sid_ndim": int(ndim),
"layout": OBJECT_INDEX_LAYOUT_V1,
})
# Carry object attributes forward; "present" = objects with geometry here.
present_oids = np.flatnonzero(
np.fromiter((1 if b != empty_blob else 0 for b in manifest_blobs), np.uint8)
).astype(np.int64)
mask = np.zeros(n_src, dtype=np.uint8)
if len(present_oids):
mask[present_oids] = 1
# object attributes are flat arrays; enumerate via children() (iterating the
# group yields only sub-group names, missing every flat-array attribute).
src_attr_names = (
list(src["object_attributes"].children()) if "object_attributes" in src else []
)
for aname in src_attr_names:
try:
src_data = read_object_attributes(src, aname)
except KeyError:
continue
out = np.zeros_like(src_data)
if len(present_oids):
out[present_oids] = src_data[present_oids]
create_object_attributes_array(level_group, aname, dtype=str(src_data.dtype))
write_object_attributes(level_group, aname, out, present_mask=mask)
if "vertex_count" in src_attr_names:
# Copied above as level 0's counts; this level's are different.
from zarr_vectors_tools.convert.ingest._object_columns import (
stamp_level_object_columns,
)
stamp_level_object_columns(level_group, segment_id=False, recount=True)
# Phase A wrote the vertices / fragment-attribute cells from separate
# processes, whose per-array ``nonempty_chunks`` manifest RMWs race and can
# under-report. Re-derive them single-process from the on-disk cells so the
# next level's coarsening source scan and the algorithms readers see every
# chunk. Phase B's link cells are NOT covered here — under the merged
# layout they are ordinary chunk-grid arrays that carry (and race on) the
# same manifest, so their rebuild belongs to the ``finalize_links`` call
# after Phase B, which re-derives it per offsets segment.
rebuild_presence(level_group)
# --- Phase B: cross-target links, decentralized per ccl shard ---------
# ``cross_target_pairs`` (gathered above from Phase A's actual reports)
# already IS the set of chunk pairs needing a stitch — no grid-adjacency
# scan needed (and none would suffice; see the comment above).
#
# Pre-create every offsets ARRAY the Phase B workers will write into,
# serially, up front. The shard partition gives each worker disjoint
# CELLS, but two workers in different shards can still land records in the
# SAME offsets array (same displacement, different source chunk) — and
# ``create_links_array`` is not concurrency-safe on the array's zarr.json
# (a Windows atomic-rename hard-fail). A cross-target pair (A, B) yields
# a record sourced at A with offset B-A or sourced at B with offset A-B
# (the direction is the streamline's), so both displacement arrays are
# possible; creating both here (empty ones are harmless — finalize_links
# counts them as zero) means workers only ever WRITE cells, never create.
cross_offsets: set[tuple[int, ...]] = set()
for A, B in cross_target_pairs:
off = tuple(int(B[i]) - int(A[i]) for i in range(ndim))
cross_offsets.add(off)
cross_offsets.add(tuple(-x for x in off))
# Same codec session as the level's other arrays: these are created here,
# after Phase A, so they need their own block — and it must close before
# the Phase B dispatch below.
_link_codec_ctx = (
level_group.batched_writes(compressor=compressor)
if compressor else nullcontext()
)
with _link_codec_ctx:
for off in sorted(cross_offsets):
create_links_array(
level_group, link_width=2, delta=0, sid_ndim=ndim,
offsets=(off,), directed=True,
)
shard_shape = tuple(
min(CROSS_LINK_TASK_SHARD_AXIS, chunk_grid_shape[i % ndim])
for i in range(2 * ndim)
)
shard_pairs: dict[tuple[int, ...], list] = defaultdict(list)
for tcc, nb in cross_target_pairs:
su = tuple(sorted((tcc, nb)))
cell = [su[k][ax] - chunk_origin[ax] for k in range(2) for ax in range(ndim)]
shard = tuple((cell[i] // shard_shape[i]) * shard_shape[i] for i in range(2 * ndim))
shard_pairs[shard].append((tcc, nb))
n_cross = 0
if shard_pairs:
payloadsB = []
for _shard, sps in shard_pairs.items():
need: set = set()
for A, B in sps:
need.add(A)
need.add(B)
# Forward each needed chunk's anchor array inline; only the chunks
# this shard's pairs touch are carried, so a worker never receives
# the whole level's anchors.
sc_sub = [
{"tcc": list(c), "arr": sidecar_arrays[c]}
for c in need if c in sidecar_arrays
]
payloadsB.append({
"pairs": [(list(A), list(B)) for A, B in sps],
"anchors": sc_sub,
})
sharedB = {
"store_path": str(store_path),
"target_level": int(target_level),
"ndim": int(ndim),
"chunk_grid_shape": list(chunk_grid_shape),
"chunk_origin": list(chunk_origin),
}
for rb in executor(_polyline_cross_edge_shard, payloadsB, sharedB):
n_cross += int(rb.get("n_links", 0))
# Reconcile the links/0 family after the decentralized per-cell writes:
# recompute num_links and re-derive each offsets array's nonempty_chunks
# from the store listing. Runs after every Phase-B worker has finished,
# once, and must be the last writer of family meta.
#
# Unconditional, not gated on n_cross: a level with zero cross-target
# transitions (a coarse level can collapse to a single chunk) still needs
# its counts stamped, and write_link_cells creates an offsets array only
# for records that exist — so zero links leaves zero arrays and there is
# nothing empty for a reader to 404 on. create_links_family above already
# left the group meta readers expect to find on an empty level.
finalize_links(level_group, delta=0)
# Carry the group taxonomy, restricted to what survived.
#
# The per-object and per-fragment coarseners have always done this; this
# one never did, so a streamline pyramid came out with object indices at
# every level and a way to say what an object *is* at only level 0. For a
# labelled atlas that is the whole payload: ``level(2).groups["cst"]``
# raised KeyError, and a viewer asking for one bundle above the finest
# level got nothing back.
#
# ``present_oids`` — objects that actually hold geometry here — is the
# right filter rather than the sparsifier's keep list: an object can be
# kept and still land no fragments, and a group naming it would hand
# readers an empty manifest and call it a member.
from zarr_vectors_tools.multiresolution.groupings import propagate_groupings
groups_written = propagate_groupings(
src, level_group, surviving_oids=present_oids,
)
_stamp_root_capability(root, CAP_PRESERVED_OBJECT_IDS)
# Record the tolerance this level was simplified at. Neither the bin
# nor the method tag can say it once it is explicit, and a refresh has
# to reproduce it rather than fall back to the derived one. Recorded
# when derived too, so a reader can ask any rdp level the same question.
# Written last and from the coordinator: the level's attributes are one
# blob shared with every writer above.
if coarsen_mode != "decimate":
_write_coarsening_record(
root, target_level,
rdp_tolerance=simplify_epsilon,
rdp_tolerance_source=tolerance_source,
)
summary = {
"vertex_count": int(total_out_vertices),
"object_count": int(len(present_oids)),
"groups": len(groups_written),
"objects_kept": int(len(present_oids)),
"source_objects": n_src,
"cross_chunk_edges": int(n_cross),
"method": coarsening_method,
"preserves_object_ids": True,
}
if coarsen_mode == "decimate":
summary["stride"] = stride
else:
summary["simplify_epsilon"] = simplify_epsilon
summary["rdp_tolerance_source"] = tolerance_source
return summary