Algorithms

zarr_vectors_tools.algorithms: measure and query a store in place. See Algorithms for usage.

Graph components

Connected components for graph stores.

The level’s link family is read once as arrays, and the components are found by a union-find over the whole edge list at a time (see component_roots()), so the cost is a handful of numpy passes over the edges rather than a Python call per edge. Memory holds the edge list: two int64 per edge plus the reader’s own arrays. On a skeleton store the edge list includes the parent links its links convention implies rather than stores.

write_back=True persists the component labels via write_vertex_attribute() under <level>/vertex_attributes/component_label.

zarr_vectors_tools.algorithms.graph_components.compute_connected_components(store_path, *, level=0, write_back=False)[source]

Compute 0-indexed connected-component labels for a graph store.

Components are numbered in order of their lowest vertex, so vertex 0 is always in component 0 and the labels do not depend on the order edges are stored in.

Parameters:
  • store_path (str | Path) – Path to a zarr-vectors graph (or skeleton) store.

  • level (int) – Resolution level to operate on.

  • write_back (bool) – When True, persist the labels under vertex_attributes/component_label via write_vertex_attribute().

Returns:

  • labels: (N,) uint32, component label per node in global ordering (matches read_graph’s position order).

  • n_components (int)

  • largest_component_size (int)

  • component_sizes (np.ndarray): count of nodes per label, indexed by component id.

Return type:

Dict with

Graph clustering

Graph clustering / community detection for chunked stores.

Three algorithms covering the common “what are the modules in this network?” question:

All three read the level’s links once as arrays into a compressed sparse row adjacency (_graph_edges). k-core peels every vertex at the current core number in one numpy step, and a label-propagation round is one sort over the edge ends. Louvain’s local moves are sequential by definition, so its inner loop still visits one vertex at a time, over plain lists; its modularity and contraction are array operations. On a skeleton store the adjacency includes the parent links its links convention implies rather than stores.

Cross-chunk edges are not a special case: connectivity is one family, so they take per-edge weights from the same link_attributes/<weight>/0/ family as intra-chunk edges. A store with no such family falls back to unit weights silently.

zarr_vectors_tools.algorithms.graph_clustering.compute_k_core(store_path, *, level=0)[source]

Per-vertex k-coreness by degree peeling.

The k-coreness of vertex v is the largest k such that v belongs to a subgraph where every vertex has degree ≥ k. Returns a vector aligned with the global vertex ordering used by zarr_vectors.types.graphs.read_graph().

Parameters:
  • store_path (str | Path) – Path to a graph (or skeleton) store.

  • level (int) – Resolution level.

Returns:

  • coreness ((N,) uint32): per-vertex coreness.

  • max_core (int): the largest coreness present in the graph.

  • core_sizes ((max_core+1,) int64): how many vertices have each coreness value.

Return type:

Dict with

zarr_vectors_tools.algorithms.graph_clustering.compute_label_propagation(store_path, *, level=0, max_iter=20, seed=0)[source]

Synchronous label propagation (Raghavan-Albert-Kumara 2007).

Each vertex starts in its own community. Per round, every vertex’s new label is the most frequent label among its neighbours (ties broken using a seeded RNG). Convergence: usually 5-20 rounds.

Parameters:
  • store_path (str | Path) – Path to a graph (or skeleton) store.

  • level (int) – Resolution level.

  • max_iter (int) – Maximum number of synchronous rounds.

  • seed (int) – RNG seed for breaking neighbour-label ties.

Returns:

  • labels ((N,) uint32): 0-indexed community labels, numbered in order of each community’s lowest vertex.

  • n_communities (int).

  • iterations (int): number of rounds actually executed.

  • converged (bool): True if labels stabilised before max_iter.

  • community_sizes ((n_communities,) int64).

Return type:

Dict with

zarr_vectors_tools.algorithms.graph_clustering.compute_louvain(store_path, *, level=0, weight=None, max_iter=10, seed=0)[source]

Greedy modularity optimisation (Blondel et al. 2008).

Two-phase loop: local moves to maximise modularity gain, then contract each community into a super-node and recurse. Stops when a full Phase-2 round yields modularity gain < 1e-6 or max_iter outer rounds elapsed.

Parameters:
  • store_path (str | Path) – Path to a graph (or skeleton) store.

  • level (int) – Resolution level.

  • weight (str | None) – Optional edge-attribute name. None means unit weights. Every edge, intra- or cross-chunk, takes its weight from link_attributes/<weight>/0/; a store without that family uses unit weight (silent fallback).

  • max_iter (int) – Maximum number of Phase-1+Phase-2 outer rounds.

  • seed (int) – RNG seed for tie-breaking in the local-move order.

Returns:

  • labels ((N,) uint32): 0-indexed level-0 community labels (the dendrogram from Phase-2 levels is collapsed back to the original vertices), numbered in order of each community’s lowest vertex.

  • modularity (float): final modularity Q.

  • n_communities (int).

  • iterations (int): outer rounds executed.

  • community_sizes ((n_communities,) int64).

Return type:

Dict with

Mesh summary

Streaming surface area / volume / Euler characteristic for mesh stores.

Streams the level chunk by chunk. Each chunk’s own faces contribute their area, signed-tetrahedron volume and edges as the chunk is read. Faces whose corners lie in more than one chunk are read once, up front, from the link family’s cross-chunk cells; their corner positions are collected as the chunks stream past and they are added at the end (see SpanningFaces). The result does not depend on the chunk shape.

per_object=True walks the object manifests instead of the chunk grid: every face is credited to the object owning its first corner.

Faces of four or more corners are split into a fan of triangles for area and volume, and counted once as faces, with their boundary edges, for the Euler characteristic.

zarr_vectors_tools.algorithms.mesh_summary.compute_mesh_summary(store_path, *, level=0, per_object=False)[source]

Streaming surface area / volume / Euler characteristic.

Parameters:
  • store_path (str | Path) – Path to a zarr-vectors mesh store.

  • level (int) – Resolution level to summarise.

  • per_object (bool) – When True, the returned dict gains a per_object list keyed by object_id with the same area / volume / face / vertex stats restricted to each object.

Returns:

  • surface_area (float): sum of face areas.

  • volume (float): signed-tetrahedron sum; meaningful only for closed meshes with consistent winding.

  • face_count (int): stored faces; a quad counts once.

  • vertex_count (int): vertices at the level.

  • edge_count (int): distinct face-boundary edges.

  • euler_characteristic (int): V - E + F.

  • excluded_cross_face_edges (int): always 0, since every face is counted; kept for callers that read it.

  • per_object (list[dict], only when per_object=True): one dict per object_id with object_id, surface_area, volume, face_count, vertex_count.

Return type:

Dict with keys

Raises:
  • FileNotFoundError – If the store cannot be opened.

  • NotImplementedError – If the level holds no faces of three or more corners (a graph or skeleton level).

  • ValueError – If a face spanning chunks names a vertex the level does not hold.

Mesh attributes

Post-hoc per-vertex mesh attributes (normals, mean curvature).

Streaming accumulation. Each chunk’s own faces are accumulated as the chunk is read. Faces whose corners lie in more than one chunk are read once, up front; their corner positions are collected as the chunks stream past and they are accumulated at the end (see SpanningFaces), so a vertex on a chunk boundary gets every face around it and the result does not depend on the chunk shape. Faces of four or more corners are split into a fan of triangles first.

write_back=True persists the result via zarr_vectors_tools._attributes.write_vertex_attribute() under attributes/<name>/ (vertex_normal for normals, mean_curvature for curvature).

zarr_vectors_tools.algorithms.mesh_attributes.compute_mean_curvature(store_path, *, level=0, write_back=False)[source]

Cotangent Laplace–Beltrami mean curvature per vertex.

Implements Meyer et al. 2003. Per-vertex output is ‖H(i)‖ / 2 where H(i) = (1/(2A_i)) Σ_j (cot α_ij + cot β_ij)(x_i − x_j).

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

  • level (int) – Resolution level.

  • write_back (bool) – When True, persist the result under attributes/mean_curvature/ via write_vertex_attribute().

Returns:

  • mean_curvature: (N,) float32.

  • incomplete_boundary_vertices (int): always 0, since every face is used; kept for callers that read it.

Return type:

Dict with

Raises:
  • NotImplementedError – If the level holds no faces of three or more corners.

  • ValueError – If a face spanning chunks names a vertex the level does not hold.

zarr_vectors_tools.algorithms.mesh_attributes.compute_vertex_normals(store_path, *, level=0, weighting='area', write_back=False)[source]

Compute per-vertex normals over a chunked mesh store.

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

  • level (int) – Resolution level.

  • weighting (str) – "area" (default) or "uniform". Area-weighted sums each incident triangle’s un-normalised normal; uniform sums unit triangle normals.

  • write_back (bool) – When True, persist the result under attributes/vertex_normal/ via write_vertex_attribute().

Returns:

  • normals: (N, 3) float32 — per-vertex unit normal in the store’s global vertex ordering.

  • incomplete_boundary_vertices (int): always 0, since every face is used; kept for callers that read it.

Return type:

Dict with

Raises:
  • NotImplementedError – If the level holds no faces of three or more corners.

  • ValueError – If weighting is unknown, or a face spanning chunks names a vertex the level does not hold.

Mesh queries

Spatial queries on chunked mesh stores: closest-point and ray-cast.

Both localise the search to chunks – rings of chunks around the query, or the chunks a ray walks through – and test the faces each one holds, plus the faces that span chunks and may pass through it (see faces_through()). Every face is tested, whichever chunks its corners lie in, so the answer does not depend on the chunk shape. Faces of four or more corners are split into a fan of triangles.

zarr_vectors_tools.algorithms.mesh_query.cast_ray(store_path, origin, direction, *, level=0, max_distance=None)[source]

First-hit intersection of a ray with a chunked mesh.

Walks the chunk grid via 3D DDA along direction, testing each visited chunk’s faces, and the faces spanning chunks that pass through it, via Möller–Trumbore. Stops once the nearest hit so far lies no further than where the ray leaves the current chunk, or at max_distance.

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

  • origin (ndarray) – (3,) ray origin.

  • direction (ndarray) – (3,) direction; will be normalised internally.

  • level (int) – Resolution level.

  • max_distance (float | None) – Optional upper bound on hit distance.

Returns:

  • hit (bool)

  • t (float): ray parameter at the hit; inf for miss.

  • position (np.ndarray (3,)): hit position.

  • chunk_key (tuple | None): chunk holding the hit face’s first corner.

  • face_index (int | None): the hit face’s index among chunk_key’s own faces; None for a face whose corners lie in more than one chunk.

  • corners (tuple | None): the hit face’s corners, each (chunk, index in chunk), in its stored winding.

Return type:

Dict with

Raises:
zarr_vectors_tools.algorithms.mesh_query.closest_point(store_path, query, *, level=0, max_distance=None, max_expansion_rings=4)[source]

Closest point on a chunked mesh to a query point.

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

  • query (ndarray) – (3,) query point.

  • level (int) – Resolution level.

  • max_distance (float | None) – Optional upper bound on the search radius. When None, the search expands rings of neighbouring chunks until a hit is found or all chunks have been checked.

  • max_expansion_rings (int) – Safety cap on the number of halo expansions (each ring widens the search bbox by one chunk size).

Returns:

  • found (bool): True if a candidate face was found.

  • position (np.ndarray (3,)): the closest point on the mesh, or query if no face was found.

  • distance (float): Euclidean distance.

  • chunk_key (tuple | None): chunk holding the winning face’s first corner.

  • face_index (int | None): the winning face’s index among chunk_key’s own faces; None for a face whose corners lie in more than one chunk.

  • corners (tuple | None): the winning face’s corners, each (chunk, index in chunk), in its stored winding.

Return type:

Dict with

Raises:

NotImplementedError – If the level holds no faces of three or more corners.

Streamline selection

Select streamlines by region: through a mask, or ending in one.

“Streamlines that pass through this ROI” is the core query of tractography. A store answers it without reading the tractogram: the region’s bounding box names the few chunks near it, and only those are read. Every vertex read is tested against the region, and so are points sampled along each segment, so a coarse level whose simplified segments step over a small ROI still finds the streamlines that cross it.

Reading only the chunks the region touches is not enough. A segment can cross the region with neither end inside it and one end in a chunk the region does not touch – a streamline passing just inside the region near a chunk face – and a read cropped to the touched chunks drops that segment. So the chunks within reach of the region are read too. By default that is one chunk on every side, which tests whole every segment shorter than a chunk; passing the store’s step length reads fewer chunks for the same answer. What can still be missed is a segment longer than reach jumping clean over the region. At level 0 vertices are far closer together than a chunk; at a heavily simplified coarse level, select at a finer level if the region is smaller than a chunk.

Regions are in world (RAS millimetre) coordinates – a NIfTI mask with its own affine, or a box. A TRK store kept in TrackVis voxel millimetres is mapped through its header’s affine first, so the same mask selects the same streamlines whichever way the store was ingested.

zarr_vectors_tools.algorithms.streamline_select.select_streamlines(store_path, *, mask=None, mask_affine=None, box=None, mode='path', level=0, sample_spacing=None, reach=None)[source]

Object ids of the streamlines that meet a region.

Parameters:
  • store_path (str | Path) – A streamline (or polyline) store.

  • mask (Any) – The region as a NIfTI file path, a nibabel image, or a boolean (or nonzero-valued) 3-D array with mask_affine.

  • mask_affine (ArrayLike | None) – Voxel-to-RAS affine for an array mask.

  • box (tuple[Sequence[float], Sequence[float]] | None) – The region as (min_corner, max_corner) in RAS millimetres, instead of a mask.

  • mode (str) – "path" – any part of the streamline is inside; "endpoints" – either end is; "both_endpoints" – both are.

  • level (int) – Resolution level to select at.

  • sample_spacing (float | None) – Distance between the points tested along each segment, in millimetres. Default: half the mask’s smallest voxel edge, or half the box’s smallest side.

  • reach (float | None) – How far past the region’s bounding box, in store units, the chunks read extend. A segment that meets the region and is no longer than reach is tested whole, wherever its ends lie. Default: one chunk edge per axis – the touched chunks and their neighbours – which covers every segment shorter than a chunk. A store’s step length is enough and reads fewer chunks; 0 reads only the chunks the region touches, and can then miss a streamline whose segment crosses the region with neither end inside it and one end outside those chunks.

Returns:

Sorted, unique object ids.

Raises:

ValueError – If neither or both of mask and box are given, the mode is unknown, or the store does not hold streamlines.

Return type:

NDArray[int64]

Bundle summaries

Per-bundle summaries of a streamline store, stored as group attributes.

A tract analysis starts from a handful of numbers per bundle: how many streamlines it holds, how long they are, how far they wander from a straight line, and where they begin and end. The per-object enrichments (length, start, end; see zarr_vectors_tools.convert.ingest._polyline_enrichments) give those per streamline, and nothing aggregated them per group. bundle_summary() does, and writes one row per group under group_attributes/bundle_* so the numbers travel with the store: TRX export carries them as dpg, a pyramid build carries them up the levels, and read_bundle_summary() reads them back at any level.

Which level the numbers describe

By default the statistics are computed once, from level 0, and the same rows are written to every level. A coarse level is a sparsified, simplified view of the same bundles, and a viewer showing level 3 still wants to say “this is the arcuate, 2,400 streamlines, 94 mm on average” rather than quote whatever survived thinning. The cost of that choice is that a coarse level’s bundle_streamline_count is the level-0 count, not the number of members that level lists. Pass level=k to summarise level k from its own membership and its own geometry instead; those rows are written to level k only. Which level a level’s rows came from is recorded on its groups array metadata under bundle_summary, and read_bundle_summary() reports it.

zarr_vectors_tools.algorithms.bundles.ATTRIBUTE_PREFIX = 'bundle_'

Prefix of every group attribute this module writes. Ingested per-group data (a TRX file’s dpg) lands in the same group_attributes/ namespace under the file’s own key names, so an unprefixed length_mean could overwrite a column the user brought with them.

zarr_vectors_tools.algorithms.bundles.bundle_summary(store_path, *, level=None, write=True, orient_endpoints=True, use_stored_attributes=True, batch_size=4096)[source]

Summarise every object group of a streamline store, one row per group.

Per group: the streamline count; path length mean, standard deviation, minimum, median and maximum; mean tortuosity (path length over the straight-line distance between the endpoints, 1.0 for a streamline whose endpoints coincide, as in tortuosity_from_endpoints()); and the centroid of the streamlines’ start points and of their end points.

The standard deviation is the population one (ddof=0), so a one-streamline bundle reports 0 rather than NaN. A group with no members reports a count of 0 and NaN for everything else. A streamline in several groups counts toward each of them; one listed twice in the same group counts once.

Endpoint orientation. Tractography does not give a streamline a direction: half of a bundle’s streamlines may be stored running from cortex to brainstem and half the other way, and averaging start points as stored puts both centroids near the middle of the bundle. With orient_endpoints=True (the default) each bundle’s streamlines are first turned to agree: the bundle’s axis is the principal eigenvector of the scatter of its end - start vectors (a statistic that does not depend on how each streamline happens to be stored), its sign is chosen so that its largest-magnitude component is positive, and any streamline whose end - start points against it is reversed. start_* is therefore the end of the bundle lying lower along its dominant axis – for a bundle running mostly along z, the inferior end. A streamline whose endpoints coincide, or that lies exactly perpendicular to the axis, is left as stored; a bundle whose endpoint vectors have no dominant direction gets a split that is well defined but not anatomically meaningful. Pass orient_endpoints=False for directed streamlines, whose stored start is the real one.

Where the per-streamline numbers come from. At level 0, when the store holds the length, start and end object attributes the ingest enrichments write (compute_length=True, compute_endpoints=True), those are used and no geometry is read; rows those attributes mark absent are measured from geometry. Everywhere else lengths and endpoints are measured from the level’s own vertices. Stored attributes are not consulted above level 0 because the coarseners carry object attributes up the pyramid verbatim: a length at level 2 is a level-0 length, and using it would describe level-0 geometry while claiming level 2.

Memory. With stored attributes: the three object-attribute columns, read whole (about 28 bytes per object for float32 columns). From geometry: one batch of batch_size streamlines at a time plus every chunk that batch touches, decoded once per batch. A bundle is spatially compact, so a batch drawn from one touches few chunks; a group spanning the whole store (a “whole brain” group) can touch most chunks in every batch, which is slow rather than large, but in the worst case one batch decodes the whole level. Either way, each group’s per-streamline lengths and endpoints (8 * (2D + 1) bytes a member) are held while that group is aggregated, because the median needs all of them; and the memberships of every group are held as core’s read_all_groupings() returns them. A streamline in several groups is measured once per group.

Parameters:
  • store_path (str | Path) – Path to a streamline or polyline store with object groups.

  • level (int | None) – None (default) computes from level 0 and, with write, writes the rows to every level of the store. An integer computes from that level’s own membership and geometry and writes to that level only.

  • write (bool) – When True, store the rows as group_attributes/bundle_* (see Returns for the names) and record the source level on the groups array metadata. Re-running overwrites them.

  • orient_endpoints (bool) – Orient each bundle’s streamlines consistently before averaging endpoints (see above). False averages them as stored.

  • use_stored_attributes (bool) – Use level 0’s length / start / end object attributes when all three are present. False always measures geometry – for a store whose length attribute means something else, such as one carried in from a file’s own per-streamline data.

  • batch_size (int) – Streamlines read per batch when measuring geometry.

Returns:

A pandas.DataFrame with one row per group, in group-id order, indexed by group name (group_<id> for an unnamed group, as core’s group catalogue names it) and with columns group_id, streamline_count, length_mean, length_std, length_min, length_median, length_max, tortuosity_mean, then start_<axis> and end_<axis> for each spatial axis. DataFrame.attrs holds source_level, endpoint_orientation ("principal_axis" or "as_stored"), measured_from ("attributes", "geometry" or both) and levels_written. The group attributes written are bundle_streamline_count (int64), bundle_length_mean, bundle_length_std, bundle_length_min, bundle_length_median, bundle_length_max, bundle_tortuosity_mean (float64, (G,)) and bundle_start_centroid, bundle_end_centroid (float64, (G, D)).

Raises:

ValueError – If the store is not a streamline or polyline store, the level does not exist, the level has no object groups, a group lists an object the level does not hold, a stored length / start / end attribute has the wrong shape, batch_size is below 1, or – with level=None and write=True – some level does not carry the same groups as level 0.

Return type:

pd.DataFrame

zarr_vectors_tools.algorithms.bundles.read_bundle_summary(store_path, *, level=0)[source]

Read back the rows bundle_summary() wrote at one level.

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

  • level (int) – Resolution level to read.

Returns:

The same table bundle_summary() returns. DataFrame.attrs holds source_level and endpoint_orientation as recorded when the rows were written, or None for each when the level’s rows were carried there by a pyramid build, which copies group attributes but not the groups array’s other metadata.

Raises:

ValueError – If the level does not exist, has no object groups, holds no bundle summary, or holds one whose row count no longer matches its groups.

Return type:

pd.DataFrame

Skeleton metrics

Per-object skeleton metrics, written as object attributes.

compute_skeleton_metrics() walks one level of a skeleton store and returns, for every object, the metrics below. With write=True (the default) each metric is also stored as object_attributes/<name>, one row per object id, so it can drive the "attribute" sparsity strategy or be exported alongside the geometry.

Metrics (all in the store’s coordinate units, at the level asked for):

cable_length (float64)

Sum of Euclidean edge lengths over the whole object, cross-chunk edges included. A coarse level’s decimation shortens it; it is a per-level value, not a property of the neuron.

node_count (int64)

Distinct vertices. The boundary vertex igneous duplicates into both chunks it borders counts once.

leaf_count (int64)

Vertices with at most one neighbour: path ends, plus an isolated vertex. Undirected, so an unbranched root is a tip like any other end.

branch_count (int64)

Vertices with three or more neighbours. A soma with three primary neurites counts once.

component_count (int64)

Connected pieces. An object is a forest when a cutout or a sparse source separates it; a single tree reports 1.

max_strahler (int64)

Horton-Strahler order at the root of the object’s highest-order component: tips are 1 and a vertex whose two highest-order children tie is one higher. Strahler order depends on the root, so the root is fixed by rule: the object’s stored root where the store records one (the write_graph layout, e.g. SWC ingest — this matches the per-node strahler the SWC ingester writes), otherwise the tip with the smallest (x, y, z). Decimation keeps tips and their coordinates, so that rule picks the same vertex at every pyramid level and on any chunk grid.

extent (float64, (O, D))

Per-axis size of the object’s axis-aligned bounding box. Being a vector it cannot rank objects on its own; the other six are scalars.

An object a coarser level’s sparsity drop has emptied reads 0 for every count, cable_length and max_strahler, and NaN for extent — there is no box around nothing.

Two skeleton layouts share links_convention = "implicit_sequential_with_branches" and are told apart by the links family’s directed flag:

  • chunked (directed=True) — written chunk by chunk by zarr_vectors.types.skeletons.write_skeleton_chunk(): the precomputed EM ingesters and every level the skeleton coarsener writes. Each fragment is a path, a branch link attaches a path’s first vertex, and cross-chunk links are undirected coincidence matches, so they are added as edges and never re-parent anything.

  • graph (directed=False) — written whole by zarr_vectors.types.graphs.write_graph() with kind="skeleton". One fragment per object per chunk, parents implied as the previous row, and every stored [child, parent] record, cross-chunk ones included, replaces the implied parent — exactly the rule read_graph applies.

Cost. One read of every chunk the level holds (vertices, fragment index, intra-chunk links) plus the cross-chunk link cells touching it, each cell read by both of its chunks; nothing is re-read per object. Chunks are summarised independently — so executor can fan them out — into per-object totals and a compressed topology that keeps only tips, branch points, cross-chunk endpoints and piece roots, with each unbranched run collapsed to one edge. Strahler order is unchanged by that collapse, and the compressed graph is what the coordinator holds: a few percent of the vertices for a neuron. Object ownership comes from the chunked layout’s per-fragment object_id attribute when present; otherwise, and whenever object_ids is given, from the object manifests.

compute_tree_metrics_vectorized() is the same machinery exposed as a drop-in for convert.ingest._tree_enrichments.compute_tree_metrics: per node depth, Strahler order and node kind, from a parent array, without a per-node Python loop.

zarr_vectors_tools.algorithms.skeleton_metrics.SKELETON_METRICS: tuple[str, ...] = ('cable_length', 'node_count', 'leaf_count', 'branch_count', 'component_count', 'max_strahler', 'extent')

Every metric compute_skeleton_metrics() knows, in column order.

zarr_vectors_tools.algorithms.skeleton_metrics.compute_skeleton_metrics(store_path, *, level=0, metrics=None, write=True, object_ids=None, executor=None)[source]

Per-object skeleton metrics for one level, optionally stored.

See the module docstring for what each metric measures, how the root Strahler order is taken from is chosen, and what the pass costs.

Parameters:
  • store_path (str | Path) – Path to a skeleton store (links_convention = "implicit_sequential_with_branches").

  • level (int) – Resolution level to measure.

  • metrics (Sequence[str] | None) – Names from SKELETON_METRICS. None computes all.

  • write (bool) – Store each metric as object_attributes/<name> on level, replacing an existing array of that name. An extent attribute is (O, D); the rest are (O,).

  • object_ids (Sequence[int] | None) – Restrict the pass to these objects (and the chunks their manifests name). Cannot be combined with write=True: a partial column would leave every other object a fabricated 0.

  • executor (Callable[..., list] | None) – Optional map-like (func, items, shared) -> list callable (e.g. dask_executor) that summarises chunks in parallel. None runs serially in-process.

Returns:

a segment_id column when the level carries object_attributes/segment_id, then one column per requested metric, with extent split into extent_<axis>.

Return type:

DataFrame indexed by object_id

Raises:

ValueError – The store is not a skeleton store, a metric name is unknown, object_ids names an object the level does not hold or is combined with write=True, or the level’s links are not two-endpoint records.

zarr_vectors_tools.algorithms.skeleton_metrics.compute_tree_metrics_vectorized(parents, root_idx=0)[source]

Topological depth, Strahler order and node kind, without a per-node loop.

A drop-in for convert.ingest._tree_enrichments.compute_tree_metrics (same arguments, dtypes and codes), which walks child lists in Python and costs about 0.2 s per 100k nodes. For a parents array that encodes a single tree rooted at root_idx the two agree exactly; nodes outside root_idx’s tree get depth and Strahler 0 in both.

Parameters:
  • parents (ArrayLike) – (N,) parent index per node, -1 (or the node itself) at a root.

  • root_idx (int) – Root of the tree to measure.

Returns:

(topological_depth uint16, strahler uint8, node_kind uint8).

Raises:

ValueError – A parent index is out of range, or the parents loop.

Return type:

tuple[ndarray, ndarray, ndarray]

Surfaces

Read one hemisphere back out of a cortical surface store.

A surface store chunks one surface per hemisphere as its geometry and keeps the others – white, pial, inflated, sphere – as coords_<surface> vertex attributes sharing its topology. The store orders vertices by chunk; the tools that made the surfaces number them. Every vertex carries the join key hemisphere << 32 | source vertex, so read_hemisphere() can put them back in the source file’s order, and asking for a different surface is only a question of which column supplies the coordinates.

zarr_vectors_tools.algorithms.surfaces.read_hemisphere(store_path, hemisphere, *, coords=None, attributes=(), level=0)[source]

One hemisphere’s mesh, indexed like the file it came from.

Parameters:
  • store_path (str | Path) – A store written by the GIFTI or FreeSurfer ingest.

  • hemisphere (str) – "left" / "right" (or "lh" / "rh").

  • coords (str | None) – The surface to return coordinates for: None or the geometry’s own name for the chunked surface, or any alternate the store kept ("inflated", or its attribute name "coords_inflated"). The faces are the same either way.

  • attributes (Sequence[str]) – Per-vertex attributes to return alongside, in the same vertex order ("thickness", "aparc"…).

  • level (int) – Resolution level. At level 0 vertex i is source vertex i. A coarser level holds fewer vertices; they come back ordered by the source vertex each one stands for, and source_vertex says which.

Returns:

Dict with vertices (V, 3), faces (F, 3) indexing vertices, source_vertex (V,), attributes {name: (V,) or (V, C)} and surface, the name of the surface the coordinates are.

Raises:

ValueError – If the store is not a surface store, lacks the hemisphere, or does not have the surface or an attribute asked for. Each message lists what the store does have.

Return type:

dict[str, Any]

Parcels

Per-parcel summaries of a cortical surface store, and the parcel at a point.

A parcellation is stored as a code per vertex with a label table in the surface header, which is enough to answer the questions a surface analysis starts with: how big is each region, and what is its mean thickness? parcel_summary() computes them the way FreeSurfer’s mris_anatomical_stats does, so a table built from a store matches the ?h.aparc.stats of the same subject:

  • vertex_count – vertices carrying the code (NumVert);

  • surface_area – the sum of the vertices’ areas on the white surface, each vertex taking a third of every triangle it belongs to (SurfArea);

  • <map>_mean and <map>_std – the plain mean and population standard deviation over those vertices (ThickAvg, ThickStd for thickness), plus <map>_area_weighted_mean, which FreeSurfer does not report.

parcel_at() answers the other direction: which parcel is nearest to a point, for example the hit of a ray cast or a streamline’s endpoint.

zarr_vectors_tools.algorithms.parcels.parcel_at(store_path, points, parcellation, *, surface='white', hemispheres=None, max_distance=None, level=0)[source]

The parcel of the vertex nearest to each point.

Parameters:
  • store_path (str | Path) – A surface store.

  • points (ArrayLike) – (N, 3) points in the store’s coordinates, such as closest_point() or cast_ray hits, or streamline endpoints.

  • parcellation (str) – The parcellation attribute.

  • surface (str | None) – The surface whose vertices are searched; None for the geometry. Use the surface the points were measured against.

  • hemispheres (Iterable[str] | None) – Hemispheres to search; default all.

  • max_distance (float | None) – Points further than this from every vertex get no parcel.

  • level (int) – Resolution level.

Returns:

hemisphere, parcel, code, vertex (the source vertex number) and distance.

Return type:

A pandas DataFrame with one row per point

zarr_vectors_tools.algorithms.parcels.parcel_summary(store_path, parcellation, *, metrics=None, surface='white', hemispheres=None, include_unassigned=False, level=0)[source]

One row per parcel per hemisphere.

Parameters:
  • store_path (str | Path) – A surface store (GIFTI or FreeSurfer ingest).

  • parcellation (str) – The parcellation attribute, e.g. "aparc".

  • metrics (Sequence[str] | None) – Continuous maps to summarise per parcel. None means every scalar map the store’s header lists; [] none.

  • surface (str | None) – The surface areas are measured on. "white" matches FreeSurfer’s stats; None uses the store’s geometry.

  • hemispheres (Iterable[str] | None) – "left"/"right" (or "lh"/"rh"); default all.

  • include_unassigned (bool) – Also report vertices no parcel covers, as the row named "unassigned".

  • level (int) – Resolution level. Areas at a coarser level are the coarse mesh’s; counts are its vertices.

Returns:

A pandas DataFrame indexed by (hemisphere, parcel) with columns code, vertex_count, surface_area and, per metric, <metric>_mean, <metric>_std and <metric>_area_weighted_mean. Parcels in the label table that no vertex carries are left out, as FreeSurfer leaves them out of its stats.

Raises:

ValueError – If the store is not a surface store, or lacks the parcellation, a metric, the surface or a hemisphere – each named.

Return type:

Any

zarr_vectors_tools.algorithms.parcels.vertex_areas(vertices, faces)[source]

Each vertex’s area: a third of every triangle that uses it.

FreeSurfer’s ?h.area convention; the parcel sums match its stats.

Parameters:
  • vertices (NDArray)

  • faces (NDArray)

Return type:

NDArray[float64]