Ingest

File-format ingestion functions. Each one reads a single source file and writes a Zarr Vectors store.

CSV / XYZ point clouds

Ingest point clouds from CSV/XYZ text files into Zarr Vectors.

Supports: - XYZ files (3 columns: x, y, z) - CSV with header row (columns identified by name) - CSV without header (first D columns are coordinates, rest are attributes)

Optional enrichments (all default off):

  • auto_detect_columns — heuristic detection of x/y/z, r/g/b, intensity, label.

  • drop_na — drop rows with NaN positions.

  • drop_duplicates — drop rows with duplicate position triples.

  • normalise — centre + scale positions to [-1, 1]; offset and scale are stored in the CSV header for round-trip export.

  • knn_distance_k — write attributes["knn_distance"] (requires scipy).

  • per_object_vertex_count — write object_attributes["vertex_count"] when object_ids is supplied.

zarr_vectors_tools.convert.ingest.csv_points.ingest_csv(input_path, output_path, chunk_shape, *, bin_shape=None, ndim=3, delimiter=',', has_header=True, position_columns=None, attribute_columns=None, dtype='float32', skip_rows=0, object_ids=None, auto_detect_columns=False, drop_na=False, drop_duplicates=False, normalise=False, knn_distance_k=None, per_object_vertex_count=False)[source]

Ingest a CSV or XYZ file into a Zarr Vectors point cloud store.

Parameters:
  • input_path (str | Path) – Path to input CSV/XYZ file.

  • output_path (str | Path) – Path for output Zarr Vectors store.

  • chunk_shape (ChunkShape) – Spatial chunk size per dimension.

  • ndim (int) – Number of spatial dimensions (default 3).

  • delimiter (str) – Column delimiter (default ,).

  • has_header (bool) – Whether the first row is a header.

  • position_columns (list[str] | list[int] | None) – Column names or indices for positions. Default: first ndim columns (or auto-detected when auto_detect_columns=True).

  • attribute_columns (list[str] | list[int] | None) – Column names or indices for attributes. Default: all remaining columns.

  • dtype (str) – Dtype for position data.

  • skip_rows (int) – Number of rows to skip before data (after header).

  • object_ids (np.ndarray | None) – Optional (N,) integer array of per-vertex object IDs. Required for per_object_vertex_count.

  • auto_detect_columns (bool) – If True and position_columns is None, detect x/y/z (case-insensitive) and common attribute columns (r/g/b, intensity, label, …).

  • drop_na (bool) – Drop rows with NaN in any position column.

  • drop_duplicates (bool) – Drop rows whose position triple matches a previous row.

  • normalise (bool) – Subtract centroid and divide by max-abs-coord so positions sit in [-1, 1]. The applied offset and scale are stored in the CSV header (CSVHeader.normalise_offset, normalise_scale) so export can invert the transform.

  • knn_distance_k (int | None) – If an int, compute each point’s mean Euclidean distance to its k nearest neighbours and store as attributes["knn_distance"]. Requires scipy.

  • per_object_vertex_count (bool) – If True and object_ids is provided, write per-object vertex counts to object_attributes["vertex_count"].

  • bin_shape (BinShape | None)

Returns:

Summary dict from write_points(), plus enrichment counters (dropped_na, dropped_duplicates).

Raises:

IngestError – If the file cannot be read or parsed.

Return type:

dict[str, Any]

LAS / LAZ

Ingest point clouds from LAS/LAZ files into Zarr Vectors.

Requires the laspy package: pip install laspy.

zarr_vectors_tools.convert.ingest.las.ingest_las(input_path, output_path, chunk_shape, *, bin_shape=None, dtype='float32', include_attributes=True, object_ids=None, knn_distance_k=None, per_object_vertex_count=False)[source]

Ingest a LAS or LAZ file into a Zarr Vectors point cloud store.

Parameters:
  • input_path (str | Path) – Path to the input LAS/LAZ file.

  • output_path (str | Path) – Path for the output Zarr Vectors store.

  • chunk_shape (ChunkShape) – Spatial chunk size per dimension (3D).

  • dtype (str) – Dtype for position data.

  • include_attributes (bool) – Whether to include intensity, classification, RGB, etc. as vertex attributes.

  • object_ids (np.ndarray | None) – Optional (N,) integer array of per-vertex object IDs. Required for per_object_vertex_count.

  • knn_distance_k (int | None) – If an int, compute each point’s mean Euclidean distance to its k nearest neighbours and store as attributes["knn_distance"]. Requires scipy.

  • per_object_vertex_count (bool) – If True and object_ids is provided, write per-object vertex counts to object_attributes["vertex_count"].

  • bin_shape (BinShape | None)

Returns:

Summary dict from write_points().

Raises:

IngestError – If laspy is not installed or the file is unreadable.

Return type:

dict[str, Any]

PLY (points)

Ingest point clouds from PLY files into Zarr Vectors.

Requires the plyfile package: pip install plyfile. Detects whether the PLY contains mesh faces or just points and dispatches accordingly. This module handles point clouds only; mesh PLY ingest is in ingest.ply_mesh (future).

zarr_vectors_tools.convert.ingest.ply.ingest_ply(input_path, output_path, chunk_shape, *, bin_shape=None, dtype='float32', include_attributes=True, object_ids=None, knn_distance_k=None, per_object_vertex_count=False)[source]

Ingest a PLY file as a Zarr Vectors point cloud.

Parameters:
  • input_path (str | Path) – Path to the input PLY file.

  • output_path (str | Path) – Path for the output Zarr Vectors store.

  • chunk_shape (ChunkShape) – Spatial chunk size per dimension.

  • dtype (str) – Dtype for position data.

  • include_attributes (bool) – Whether to include non-position vertex properties (normals, colours, etc.).

  • object_ids (np.ndarray | None) – Optional (N,) integer array of per-vertex object IDs. Required for per_object_vertex_count.

  • knn_distance_k (int | None) – If an int, compute each point’s mean Euclidean distance to its k nearest neighbours and store as attributes["knn_distance"]. Requires scipy.

  • per_object_vertex_count (bool) – If True and object_ids is provided, write per-object vertex counts to object_attributes["vertex_count"].

  • bin_shape (BinShape | None)

Returns:

Summary dict from write_points().

Raises:

IngestError – If plyfile is not installed, the file has no vertex element, or reading fails.

Return type:

dict[str, Any]

Line segments

Ingest line segments from CSV text files into Zarr Vectors.

Six-column CSV format: x0,y0,z0,x1,y1,z1 (one row per segment), plus optional per-line attribute columns. Mirrors ingest_csv for points.

zarr_vectors_tools.convert.ingest.lines.ingest_lines_csv(input_path, output_path, chunk_shape, *, bin_shape=None, ndim=3, delimiter=',', has_header=True, dtype='float32', attribute_columns=None, compute_length=False, drop_zero_length=False, drop_na=False, drop_duplicates=False)[source]

Ingest a CSV of line segments into a Zarr Vectors line store.

Expected layout: the first 2 * ndim columns hold endpoint coordinates in (x0, y0, z0, x1, y1, z1) order. Remaining columns are treated as per-line attributes (or filtered to attribute_columns when supplied).

Parameters:
  • input_path (str | Path) – Path to the CSV file.

  • output_path (str | Path) – Path for the output Zarr Vectors store.

  • chunk_shape (ChunkShape) – Spatial chunk size per dimension.

  • ndim (int) – Spatial dimensionality (default 3).

  • delimiter (str) – Column delimiter.

  • has_header (bool) – Whether the first row is a header.

  • dtype (str) – Dtype for position data.

  • attribute_columns (list[str] | None) – Names (when has_header=True) of columns to keep as per-line attributes. Default: every non-position column.

  • compute_length (bool) – If True, write line_attributes["length"].

  • drop_zero_length (bool) – If True, drop segments shorter than 1e-9.

  • drop_na (bool) – Drop rows with NaN in any endpoint coordinate.

  • drop_duplicates (bool) – Drop rows with identical endpoint pairs.

  • bin_shape (BinShape | None)

Returns:

Summary dict from write_lines(), plus enrichment counters.

Raises:

IngestError – If the file is missing or unparseable.

Return type:

dict[str, Any]

MRtrix TCK

Ingest streamlines from MRtrix TCK files into zarr vectors.

Requires nibabel: pip install nibabel.

zarr_vectors_tools.convert.ingest.tck.ingest_tck(input_path, output_path, chunk_shape, *, bin_shape=None, dtype='float32', compute_length=False, compute_endpoints=False, length_range=None)[source]

Ingest a TCK file into a zarr vectors streamline store.

TCK files store streamlines in scanner (RAS) millimetre coordinates with no per-vertex attributes — only positions.

Parameters:
  • input_path (str | Path) – Path to the input .tck file.

  • output_path (str | Path) – Path for the output zarr vectors store.

  • chunk_shape (ChunkShape) – Spatial chunk size per dimension (3D).

  • dtype (str) – Dtype for position data.

  • compute_length (bool) – If True, write per-streamline path length to object_attributes["length"].

  • compute_endpoints (bool) – If True, write per-streamline start and end points to object_attributes["start"] and ["end"].

  • length_range (tuple[float, float] | None) – Optional (min, max) length bounds; streamlines outside the range are dropped before writing.

  • bin_shape (BinShape | None)

Returns:

Summary dict from write_polylines(), plus any enrichment counters such as dropped_by_length.

Raises:

IngestError – If nibabel is not installed or the file is unreadable.

Return type:

dict[str, Any]

TrackVis TRK

Ingest streamlines from TrackVis TRK files into zarr vectors.

Requires nibabel: pip install nibabel.

zarr_vectors_tools.convert.ingest.trk.ingest_trk(input_path, output_path, chunk_shape, *, bin_shape=None, dtype='float32', preserve_header=True, compute_length=False, compute_endpoints=False, length_range=None)[source]

Ingest a TRK file into a zarr vectors streamline store.

Parameters:
  • input_path (str | Path) – Path to the input .trk file.

  • output_path (str | Path) – Path for the output zarr vectors store.

  • chunk_shape (ChunkShape) – Spatial chunk size per dimension (3D).

  • bin_shape (BinShape | None) – Optional spatial bin size.

  • dtype (str) – Dtype for position data.

  • preserve_header (bool) – If True, store the TRK header in /headers/trk/ for round-trip export.

  • compute_length (bool) – If True, write per-streamline path length to object_attributes["length"].

  • compute_endpoints (bool) – If True, write per-streamline start and end points to object_attributes["start"] and ["end"].

  • length_range (tuple[float, float] | None) – Optional (min, max) length bounds; streamlines outside the range are dropped before writing. The dropped count is reported in the summary dict as dropped_by_length.

Returns:

Summary dict from write_polylines(), plus any enrichment counters such as dropped_by_length.

Raises:

IngestError – If nibabel is not installed or the file is unreadable.

Return type:

dict[str, Any]

TrackVis TRK (parallel)

Memory-bounded parallel TRK → zarr-vectors ingest.

Processes large TRK (TrackVis) files without loading them whole into RAM. Coordinate convention: by default the raw TrackVis voxmm coordinates are stored as-is and the vox_to_ras affine is recorded in CRS metadata (a viewer that understands the affine renders it registered). Pass register_to_rasmm=True to instead bake that affine into the vertices at ingest — matching nibabel.streamlines.load(...).streamlines — and store an identity CRS affine. That is the layout viewers which can only scale/translate (not rotate), e.g. neuroglancer, need: NGFF transforms can’t undo the affine’s axis flips, so the geometry itself must carry them.

Pipeline

Phase 0 Parse 1000-byte header; resolve the registration affine. Phase 1 Offset-index scan (~6 s for 5.6M streamlines), also sampling one

vertex per streamline to size chunk_shape from num_chunks; partition into N parts.

Phase A Parallel over N parts: bin streamlines → spatial chunks, a block of

streamlines at a time, write .npz, report each part’s exact bbox.

Grid Single-process: union those bboxes into the store bounds and lay out

the chunk grid, then create the store. The grid comes from the geometry, not the header’s declared FOV — see ingest_trk_parallel.

Phase B Parallel over batches of the S chunks: assemble from all N parts →

write level-0.

Coord Single-process: reconstruct manifests + cross-chunk links from the

part directories; the links are written in parallel, whole offsets arrays per task.

Phase 5 Store CRS/affine metadata + TRKHeader for round-trip. Phase 6 Build multiscale pyramid via coarsen.build_pyramid.

zarr_vectors_tools.convert.ingest.trk_parallel.build_offset_index(path, header)[source]

Scan the TRK file and record each streamline’s byte offset.

Returns dict with:

byte_offset int64 (O,) byte position of each streamline’s n_points int32 n_points int32 (O,) point count per streamline nbytes int64 (O,) byte span of each streamline record (4 + n_pts*pt_stride + props) first_point float32 (O, 3) each streamline’s first vertex, on-disk voxmm

Parameters:
Return type:

dict[str, ndarray[tuple[Any, …], dtype[_ScalarT]]]

zarr_vectors_tools.convert.ingest.trk_parallel.ingest_trk_parallel(input_path, output_path, *, num_chunks=None, n_parts=None, workers=None, executor=None, dtype='float32', compressor=None, max_streamlines=None, compute_length=False, compute_endpoints=False, object_attrs=None, vertex_attrs=None, attr_seed=0, keep_scalars=True, keep_properties=True, preserve_header=True, register_to_rasmm=False, build_multiscale=True, pyramid_factors=None, chunk_scale_factors=None, sparsity_strategy='length', pyramid_coarsen_mode='rdp', pyramid_rdp_tolerances=None, intermediate_dir=None, keep_intermediate=False, resume=False, progress=True)[source]

Ingest a large TRK file into a zarr-vectors streamline store.

Memory-bounded: processes the file in parallel byte-range parts, binning streamlines into spatial chunks without loading the whole file into RAM.

Parameters:
  • input_path (str | Path) – Path to the .trk file.

  • output_path (str | Path) – Path for the new zarr-vectors store.

  • num_chunks (int | tuple[int, int, int] | None) – Target total chunk count (integer, near-isotropic default), or explicit (nx, ny, nz) 3-tuple, or None (uses 125).

  • n_parts (int | None) – Number of file parts for Phase A parallelism. Controls how finely the input file is sliced — does NOT affect how many processes run simultaneously (that is workers). Defaults to 4× workers (fine-grained enough for good load balancing).

  • workers (int | None) – Number of Dask worker processes. None = cpu_count-1.

  • executor (Any) – Injected executor (func, items, shared) callable. If None, either uses dask_executor (when workers>1) or runs serially.

  • dtype (str) – Numpy dtype for vertex positions.

  • compressor (Any) – Codec for the level-0 per-chunk arrays. None (default) stores raw — vertices then cost exactly n_vertices * ndim * itemsize bytes, the same payload a .trk holds. "zstd" / "blosc" roughly halve that (measured ~2.4x on HCP tract coordinates) at the cost of a slower, sync codec-encoding write path. See zarr_vectors.encoding.compression.resolve_compressor() for accepted values (a full codec list also works). The codec pipeline is fixed when each array is created, so every later per-cell write — including from parallel workers — encodes to match automatically.

  • max_streamlines (int | None) – If set, only ingest the first N streamlines from the file (in on-disk order). Useful for quick test runs on a subset of a large tractogram; leave None to ingest all streamlines.

  • compute_length (bool) – Write per-streamline path length to object_attributes.

  • compute_endpoints (bool) – Write start/end points to object_attributes.

  • object_attrs (set[str] | None) – Synthetic per-object (per-streamline) attributes to generate for color-by-object testing. Any of length, endpoints, orientation (start→end unit vector, 3ch), tortuosity, vertex_count. compute_length / compute_endpoints are folded in as length / endpoints.

  • vertex_attrs (set[str] | None) – Synthetic per-vertex (per-point) attributes to generate for color-by-vertex testing. Any of arc_length (0→1 along the streamline), x / y / z (coordinate), random, index (0→1 within the streamline), tangent (unit direction, 3ch). Stored under vertex_attributes/<name> and carried through the pyramid to every level.

  • attr_seed (int) – Seed for the random vertex generator (default 0).

  • keep_scalars (bool) – Store the file’s own per-point scalars as vertex attributes, one per name in the header (a multi-column scalar stays one attribute). Carried through the pyramid like the synthetic ones.

  • keep_properties (bool) – Store the file’s per-streamline properties as object attributes.

  • preserve_header (bool) – Store TRKHeader (affine, dims) in the zarr store.

  • register_to_rasmm (bool) – When True, bake the trackvis-voxmm→RASmm affine into the stored vertex positions (and chunk grid) and record an identity CRS affine, so the store is in registered world space with no transform left for the viewer to apply — the layout neuroglancer needs. When False (default) the raw voxmm coordinates are kept and the real vox_to_ras affine is recorded in CRS metadata instead.

  • build_multiscale (bool) – Build coarser pyramid levels after level 0.

  • pyramid_factors (list[tuple[float, float]] | None) – List of (coarsen_factor, sparsity_factor) per level. Default: [(8.0, 1.0), (8.0, 1.0)] for two coarser levels. In “decimate” mode, coarsen_factor is the decimation stride rather than an RDP epsilon multiplier.

  • chunk_scale_factors (list[int] | None) – Per-axis chunk multiplier per level. Default [1, 1].

  • sparsity_strategy (str) – “length” or “random” for object dropping.

  • pyramid_coarsen_mode (str) – “rdp” (default, Douglas-Peucker simplification) or “decimate” (uniform per-object stride decimation, keeping every stride-th vertex plus endpoints).

  • pyramid_rdp_tolerances (list[float] | None) – Explicit Douglas-Peucker tolerance per coarser level, in the stored coordinates’ units (voxmm, or RAS mm with register_to_rasmm), one per pyramid_factors entry. None (default) derives each from the level’s bin. Refused, before anything is read, in “decimate” mode, without build_multiscale, or when the count does not match. See zarr_vectors_tools.multiresolution.coarsen.build_pyramid().

  • intermediate_dir (str | Path | None) – Directory for .npz scratch files. Default: temp dir.

  • keep_intermediate (bool) – If True, don’t delete the intermediate dir on exit.

  • resume (bool) – Reuse what an earlier run with the same options finished in intermediate_dir: the offset scan, Phase A’s part files, a complete level 0, and the pyramid levels already built. Needs intermediate_dir, which a run given one always keeps and records its progress in. A run whose options differ from the recorded ones is refused rather than mixed with them; a half-written level 0 or pyramid level is removed and rebuilt.

  • progress (bool) – Print progress messages to stdout.

Returns:

Summary dict with vertex_count, streamline_count, chunk_count, etc.

Return type:

dict[str, Any]

zarr_vectors_tools.convert.ingest.trk_parallel.parse_trk_header(path)[source]

Parse the 1000-byte TRK header using struct.

Returns a dict with keys: dim, voxel_size, origin, n_scalars, n_properties, scalar_names and property_names ([(name, columns), ...], see decode_trk_names()), vox_to_ras (4×4 float32 array), voxel_order (str), n_count, version, hdr_size.

Parameters:

path (str | Path)

Return type:

dict[str, Any]

zarr_vectors_tools.convert.ingest.trk_parallel.partition_offset_index(offset_index, n_parts)[source]

Split offset index into N byte-balanced, non-overlapping parts.

Each part dict has: byte_offset, n_points (arrays for that part), poly_id_base (global index of first streamline in part).

Parameters:
Return type:

list[dict[str, Any]]

TRX

Ingest streamlines from TRX files into zarr vectors.

Requires trx-python: pip install trx-python.

TRX is the closest format to zarr vectors for streamlines — it uses separate arrays for positions, offsets, per-vertex data (dpv), per-streamline data (dps), groups, and per-group data (dpg).

zarr_vectors_tools.convert.ingest.trx.ingest_trx(input_path, output_path, chunk_shape, *, bin_shape=None, dtype='float32', compute_length=False, compute_endpoints=False, length_range=None, mean_scalar=None)[source]

Ingest a TRX file into a zarr vectors streamline store.

Maps TRX arrays to zarr vectors:

  • positions → vertices

  • offsets → vertex group boundaries

  • dpv/* → attributes/* (per-vertex)

  • dps/* → object_attributes/* (per-streamline)

  • groups/* → groupings

  • dpg/* → groupings_attributes

Parameters:
  • input_path (str | Path) – Path to the input .trx file/directory.

  • output_path (str | Path) – Path for the output zarr vectors store.

  • chunk_shape (ChunkShape) – Spatial chunk size per dimension (3D).

  • dtype (str) – Dtype for position data.

  • compute_length (bool) – If True, write per-streamline path length to object_attributes["length"].

  • compute_endpoints (bool) – If True, write per-streamline start and end points to object_attributes["start"] and ["end"].

  • length_range (tuple[float, float] | None) – Optional (min, max) length bounds; streamlines outside the range are dropped before writing.

  • mean_scalar (str | list[str] | None) – Name or list of names of per-vertex (dpv) scalars to aggregate. For each, write its per-streamline mean to object_attributes["mean_<name>"]. Names not found in the TRX file are skipped silently.

  • bin_shape (BinShape | None)

Returns:

Summary dict from write_polylines(), plus any enrichment counters such as dropped_by_length.

Raises:

IngestError – If trx-python is not installed or the file is unreadable.

Return type:

dict[str, Any]

Edge-list CSV

Ingest graphs from CSV edge-lists into Zarr Vectors.

Two input CSVs: - edges_path: rows are source,target plus optional weight/attr columns. - nodes_path: rows are node_id,x,y,z plus optional node-attr columns.

Optional use_cudf=True reads both CSVs on GPU via RAPIDS cuDF. Falls back to pandas otherwise (pandas is a top-level dependency).

zarr_vectors_tools.convert.ingest.edgelist.ingest_edgelist(edges_path, nodes_path, output_path, chunk_shape, *, bin_shape=None, use_cudf=False, source_col='source', target_col='target', node_id_col='node_id', position_columns=('x', 'y', 'z'), edge_attribute_columns=None, node_attribute_columns=None, dtype='float32', drop_na=False, drop_duplicates=False, compute_degree=False, compute_component=False, compute_clustering=False, compute_summary=False)[source]

Ingest a CSV edge-list (plus a node-position CSV) into a graph store.

Parameters:
  • edges_path (str | Path) – CSV with at least source_col and target_col columns. Extra columns become edge attributes (filterable via edge_attribute_columns).

  • nodes_path (str | Path) – CSV with at least node_id_col and position_columns. Extra columns become node attributes.

  • output_path (str | Path) – Path for the output Zarr Vectors store.

  • chunk_shape (ChunkShape) – Spatial chunk size per dimension.

  • use_cudf (bool) – Read both CSVs via cuDF on GPU. Requires a RAPIDS install.

  • source_col (str) – Column names in the edge CSV.

  • target_col (str) – Column names in the edge CSV.

  • node_id_col (str) – Column name in the node CSV linking to source_col and target_col.

  • position_columns (tuple[str, ...]) – Column names in the node CSV holding coordinates.

  • edge_attribute_columns (list[str] | None) – Names of edge-CSV columns to retain. Default: every non-source/non-target column.

  • node_attribute_columns (list[str] | None) – Names of node-CSV columns to retain. Default: every non-id/non-position column.

  • dtype (str) – Dtype for position data.

  • drop_na (bool) – Drop edge rows with NaN source/target and node rows with NaN positions. Reports drop counts in summary.

  • drop_duplicates (bool) – Drop duplicate edge rows (and duplicate node IDs, keeping the first).

  • compute_degree (bool) – Same semantics as ingest_graphml().

  • compute_component (bool) – Same semantics as ingest_graphml().

  • compute_clustering (bool) – Same semantics as ingest_graphml().

  • compute_summary (bool) – Same semantics as ingest_graphml().

  • bin_shape (BinShape | None)

Returns:

Summary dict from write_graph(), plus enrichment counters.

Raises:

IngestError – For missing files, cuDF errors, or empty results.

Return type:

dict[str, Any]

GraphML

Ingest graphs from GraphML files into zarr vectors.

Requires networkx: pip install networkx. Node positions must be stored as node attributes (e.g. x, y, z).

zarr_vectors_tools.convert.ingest.graphml.ingest_graphml(input_path, output_path, chunk_shape, *, bin_shape=None, position_attrs=('x', 'y', 'z'), dtype='float32', compute_degree=False, compute_component=False, compute_clustering=False, compute_summary=False)[source]

Ingest a GraphML file into a zarr vectors graph store.

Parameters:
  • input_path (str | Path) – Path to the input .graphml file.

  • output_path (str | Path) – Path for the output zarr vectors store.

  • chunk_shape (ChunkShape) – Spatial chunk size per dimension.

  • position_attrs (tuple[str, ...]) – Node attribute names for coordinates.

  • dtype (str) – Dtype for position data.

  • compute_degree (bool) – If True, write per-node degree (total in+out for directed graphs) to node_attributes["degree"].

  • compute_component (bool) – If True, write 0-indexed connected-component label to node_attributes["component"]. Uses weakly- connected components for directed graphs.

  • compute_clustering (bool) – If True, write per-node clustering coefficient to node_attributes["clustering"].

  • compute_summary (bool) – If True, write a GraphHeader containing node/edge counts, mean degree, and connected-component stats. Blocked on a core API that supports per-graph attributes; the header is the workaround until that lands.

  • bin_shape (BinShape | None)

Returns:

Summary dict from write_graph().

Return type:

dict[str, Any]

SWC

Ingest neuronal morphology from SWC files into zarr vectors.

SWC is a 7-column text format: ID type X Y Z radius parent_ID.

zarr_vectors_tools.convert.ingest.swc.ingest_swc(input_path, output_path, chunk_shape, *, bin_shape=None, dtype='float32', preserve_header=True, compute_topological_depth=False, compute_strahler=False, compute_node_kind=False)[source]

Ingest an SWC file into a zarr vectors skeleton store.

Parameters:
  • input_path (str | Path) – Path to the input .swc file.

  • output_path (str | Path) – Path for the output zarr vectors store.

  • chunk_shape (ChunkShape) – Spatial chunk size per dimension (3D).

  • dtype (str) – Dtype for position data.

  • preserve_header (bool) – If True, store SWC comment lines in /headers/swc/ for round-trip export.

  • compute_topological_depth (bool) – If True, write per-node edge count from soma to node_attributes["topological_depth"] (uint16).

  • compute_strahler (bool) – If True, write per-node Strahler stream order to node_attributes["strahler"] (uint8).

  • compute_node_kind (bool) – If True, write per-node kind label to node_attributes["node_kind"] (uint8: 0=soma, 1=branch, 2=continuation, 3=terminal).

  • bin_shape (BinShape | None)

Returns:

Summary dict from write_graph().

Return type:

dict[str, Any]

Precomputed layers (skeletons or meshes)

Neuroglancer precomputed skeleton or mesh layer → zarr-vectors store, in one call.

The two precomputed ingesters take a reader object and their own option names, which is right for scripts that tune a FlyWire-scale run and wrong for zvtools convert, whose registry calls every ingester the same way: func(source, out_store, chunk_shape, **options). This module is that call.

Which ingester runs is decided by the layer’s info, not by the caller:

A layer is a directory or a bucket prefix, never a single file. source may be a URL (gs://, s3://, https://, file://, optionally behind Neuroglancer’s precomputed://) or a local directory.

zarr_vectors_tools.convert.ingest.precomputed.frag_bounds(info, keys)[source]

The nanometre box covering keys, snapped to the .frags grid.

run_ingest aligns the store’s chunk grid to the box’s minimum corner, so every key has to lie on the grid through it; one that does not would be written into the wrong chunk, and is refused.

Parameters:
Return type:

tuple[list[float], list[float]]

zarr_vectors_tools.convert.ingest.precomputed.has_spatial_index(info)[source]
Parameters:

info (dict[str, Any])

Return type:

bool

zarr_vectors_tools.convert.ingest.precomputed.ingest_precomputed(source, out_store, chunk_shape=None, *, frags_dir='', anchor=None, counts=None, segment_ids=None, lod=0, strides=(), chunk_scale_factors=None, sparsity_factors=None, sparsity_strategy='length', drop_interior_below=0, workers=None, executor=None, progress=True)[source]

Ingest a precomputed skeleton or mesh layer, choosing the path from its info.

Parameters:
  • source (str | Path) – Layer URL or local directory.

  • out_store (str | Path) – Output store path.

  • chunk_shape (Sequence[float] | None) – Level-0 chunk size in nm. Required for a mesh layer and a skeleton layer with no spatial index; for one with, it may only repeat the index’s own.

  • frags_dir (str) – Subdirectory holding the .frags files (spatial index).

  • anchor (Sequence[int] | None) – Voxel corner of one .frags chunk; ingest the block of counts chunks from there instead of listing the layer.

  • counts (Sequence[int] | None) – Chunks per axis from anchor (default (1, 1, 1)).

  • segment_ids (Sequence[int] | None) – Only these segments (a mesh layer, or a skeleton layer with no spatial index).

  • lod (int) – Level of detail to read from a multi-resolution mesh layer.

  • strides (Sequence[int]) – Per-level decimation strides; empty builds level 0 only.

  • / (chunk_scale_factors / sparsity_factors / sparsity_strategy) – drop_interior_below: As for the underlying ingester.

  • workers (int | None) – Dask worker processes, used when executor is None.

  • executor (Any) – A map-like (func, items, shared) callable.

  • progress (bool) – Print progress.

  • chunk_scale_factors (Sequence[int | tuple[int, ...]] | None)

  • sparsity_factors (Sequence[float] | None)

  • sparsity_strategy (str)

  • drop_interior_below (int)

Return type:

dict[str, Any]

The stride, sparsity and drop_interior_below options build a skeleton pyramid inside the ingest, and workers / executor run it; a mesh layer refuses them, since its pyramid is built afterwards.

Returns:

The ingester’s summary, plus layer ("spatial_index" or "plain") and bounds_nm when known. For a mesh layer, precomputed_meshes.ingest_precomputed_meshes()’s summary, whose layer is the URL read.

Parameters:
Return type:

dict[str, Any]

zarr_vectors_tools.convert.ingest.precomputed.is_url(source)[source]

Does source name a remote (or file://) location, not a local path?

Parameters:

source (str | Path)

Return type:

bool

zarr_vectors_tools.convert.ingest.precomputed.layer_kind(info)[source]

"mesh" or "skeleton" for an info read_layer_info() accepted.

Parameters:

info (dict[str, Any])

Return type:

str

zarr_vectors_tools.convert.ingest.precomputed.layer_url(source)[source]

The CloudFiles / CloudVolume path for source.

Neuroglancer’s precomputed:// prefix is dropped (CloudFiles does not take it), and a local directory becomes file:// plus its absolute POSIX path – the spelling both libraries accept on Windows as well.

Parameters:

source (str | Path)

Return type:

str

zarr_vectors_tools.convert.ingest.precomputed.list_frag_keys(url, frags_dir='')[source]

Every .frags key in frags_dir (non-recursive), sorted.

Parameters:
Return type:

list[str]

zarr_vectors_tools.convert.ingest.precomputed.read_layer_info(url)[source]

Read and check a layer’s info; refuse anything but a skeleton or mesh layer.

A segmentation volume is refused too, naming the skeleton and mesh directories its info points at: the volume’s voxels are not converted, and which of its layers to read is the caller’s choice.

Parameters:

url (str)

Return type:

dict[str, Any]

Precomputed skeletons (spatial index)

ETL: precomputed spatial-index .frags skeletons → multiscale zarr-vectors store.

Source: a precomputed skeleton layer whose info carries a spatial_index block. Per spatial chunk, a <bbox>.frags file is a seung-lab MapBuffer keyed by uint64 segment id; each value is a precomputed skeleton piece (vertices in nm, edges, per-vertex attributes such as radius / cross_sectional_area).

Pipeline (all per-chunk, bounded RAM):

  1. Extract one .frags chunk → {segment_id: piece} (PrecomputedFragsReader, cloud-volume + mapbuffer).

  2. Partition + write each segment’s geometry into origin-aligned zarr chunks, dropping cross-chunk edges, one fragment per connected piece (pieces_from_chunk() → write_skeleton_chunk). Emits (segment_id, chunk, fragment) records.

  3. Reduce the records into a segment-id-preserving object index (build_object_index).

  4. Pyramid: skeleton-aware path-simplification levels (build_skeleton_pyramid).

The reader is dependency-injected: run_ingest() accepts any object exposing info and read_chunk(key), so the whole pipeline is testable offline with InMemoryFragsReader.

class zarr_vectors_tools.convert.ingest.precomputed_skeletons.InMemoryFragsReader(info, chunks)[source]

Bases: object

Offline reader for tests: holds {key: {seg_id: piece}}.

Parameters:
__init__(info, chunks)[source]
Parameters:
read_chunk(key)[source]
Parameters:

key (str)

Return type:

dict[int, dict[str, ndarray[tuple[Any, …], dtype[_ScalarT]]]]

class zarr_vectors_tools.convert.ingest.precomputed_skeletons.PrecomputedFragsReader(base_url, *, frags_dir='')[source]

Bases: object

Read .frags chunks from a precomputed skeleton layer.

Requires the optional ingest extras (cloud-volume, mapbuffer, cloud-files).

Parameters:
  • base_url (str)

  • frags_dir (str)

__init__(base_url, *, frags_dir='')[source]
Parameters:
  • base_url (str)

  • frags_dir (str)

read_chunk(key)[source]
Parameters:

key (str)

Return type:

dict[int, dict[str, ndarray[tuple[Any, …], dtype[_ScalarT]]]]

class zarr_vectors_tools.convert.ingest.precomputed_skeletons.SkeletonInfo(base_url, resolution_nm, chunk_size_nm, vertex_attributes=<factory>, bounds_nm=None, frags_dir='')[source]

Bases: object

Spatial-index geometry of a precomputed skeleton layer.

Parameters:
__init__(base_url, resolution_nm, chunk_size_nm, vertex_attributes=<factory>, bounds_nm=None, frags_dir='')
Parameters:
Return type:

None

property attribute_dtypes: dict[str, str]
property attribute_names: list[str]
base_url: str
bounds_nm: tuple[list[float], list[float]] | None = None
chunk_size_nm: tuple[float, ...]
property chunk_size_voxels: tuple[int, ...]
frags_dir: str = ''
resolution_nm: tuple[float, ...]
vertex_attributes: list[dict[str, Any]]
zarr_vectors_tools.convert.ingest.precomputed_skeletons.enumerate_frag_keys(info, anchor_voxel, counts)[source]

Enumerate a block of .frags keys from an anchor corner.

anchor_voxel is one valid chunk’s voxel start (e.g. from a known filename); counts is the per-axis number of chunks. Keys step by chunk_size_voxels per axis. Avoids bucket-wide listing for test cutouts.

Parameters:
Return type:

list[str]

zarr_vectors_tools.convert.ingest.precomputed_skeletons.frag_key(info, voxel_start)[source]

Build a .frags filename from a per-axis voxel start corner.

<x0>-<x1>_<y0>-<y1>_<z0>-<z1>.frags where x1 = x0 + chunk_size_voxels (matches igneous SpatialIndex naming).

Parameters:
Return type:

str

zarr_vectors_tools.convert.ingest.precomputed_skeletons.main(argv=None)[source]

python -m zarr_vectors.ingest.precomputed_skeletons CLI.

Ingests a rectangular block of .frags chunks (anchored at a known chunk’s voxel corner) into a multiscale zarr-vectors skeleton store.

Parameters:

argv (Sequence[str] | None)

Return type:

int

zarr_vectors_tools.convert.ingest.precomputed_skeletons.parse_frag_key(key)[source]

Parse a .frags key back to its per-axis voxel start corner.

[dir/]x0-x1_y0-y1_z0-z1.frags → (x0, y0, z0).

Parameters:

key (str)

Return type:

tuple[int, …]

zarr_vectors_tools.convert.ingest.precomputed_skeletons.pieces_from_chunk(chunk, *, chunk_shape_nm, attribute_names, gid_start=0, origin=None, fixed_cell=None)[source]

Turn one .frags chunk into per-(origin-aligned)-zarr-chunk pieces.

For each segment, edges that cross a zarr-chunk boundary are split out as cross-chunk edges (rather than dropped): each such edge’s two endpoints get a global id and the edge is recorded so the level-0 writer can store it in cross_chunk_links. The coarsener later uses those links to merge the object’s pieces once both endpoints land in the same coarser chunk. Intra-chunk connectivity is split into rooted components, one fragment per component.

Returns (by_chunk, cross_edges, next_gid) where cross_edges is a list of (gid_a, gid_b) and each emitted piece carries an "anchors" map {gid: local_vertex_index} for its endpoints.

Parameters:
  • chunk (dict[int, dict[str, npt.NDArray]])

  • chunk_shape_nm (tuple[float, ...])

  • attribute_names (Sequence[str])

  • gid_start (int)

  • origin (npt.NDArray | None)

  • fixed_cell (ChunkCoords | None)

Return type:

tuple[dict[ChunkCoords, list[dict[str, Any]]], list[tuple[int, int]], int]

zarr_vectors_tools.convert.ingest.precomputed_skeletons.run_ingest(reader, out_store, keys, *, bounds_nm, attribute_names=None, attribute_dtypes=None, strides=(), chunk_scale_factors=None, sparsity_factors=None, sparsity_strategy='length', drop_interior_below=0, backend=None, align=True, progress=True, workers=None, executor=None)[source]

Run the full ETL: extract + level-0 write + object index + pyramid.

Parameters:
  • reader (Any) – Object with .info (SkeletonInfo) and read_chunk(key).

  • out_store (str | Path) – Output zarr-vectors store path.

  • keys (Iterable[str]) – .frags keys to ingest (the test cutout, or all chunks).

  • bounds_nm (tuple[list[float], list[float]]) – (min_corner, max_corner) in nm for the store.

  • attribute_dtypes (dict[str, str] | None) – Per-vertex attributes to carry (defaults from reader.info).

  • strides (Sequence[int]) – Per-pyramid-level decimation strides (keep every k-th vertex). Empty → level 0 only.

  • sparsity_factors (Sequence[float] | None) – Aligned with strides (defaults: 2 per axis, 1.0 = keep all).

  • attribute_names (Sequence[str] | None)

  • attribute_dtypes

  • chunk_scale_factors (Sequence[int | tuple[int, ...]] | None)

  • sparsity_factors

  • sparsity_strategy (str)

  • drop_interior_below (int)

  • backend (str | None)

  • align (bool)

  • progress (bool)

  • workers (int | None)

  • executor (Any)

Returns:

Summary dict (level-0 counts + pyramid summary).

Return type:

dict[str, Any]

Precomputed skeletons (plain)

ETL: plain precomputed skeletons (no .frags spatial index) → multiscale zarr-vectors store.

Source: a precomputed skeleton layer whose info does not carry a spatial_index block. Each segment’s skeleton is stored as a separate file <segment-id> (or via sharding) under the layer root. The full list of segment IDs is discovered from the layer’s segment_properties sub-directory (inline ids array in segment_properties/info).

Pipeline:

  1. Read – parallel cloud reads of all (or a subset of) segment skeletons using the cloud-volume library. Applies the layer transform so all coordinates are in physical nanometre space.

  2. Bounds – if not supplied by the caller, compute the axis-aligned bounding box of all vertex positions and round outward to the target chunk grid.

  3. Spatial distribute – assign each neuron’s vertices to origin-aligned zarr chunks using the existing pieces_from_chunk() helper. Cross-chunk edges (neurites that span a chunk boundary) are preserved and recorded.

  4. Write – write each zarr chunk with write_skeleton_chunk().

  5. Object index – build the segment-id → dense-OID map and fragment manifests via build_object_index.

  6. Segment properties → object attributes – convert the precomputed inline property table to per-object zarr-vectors arrays (write_object_attributes).

  7. Pyramid – optionally coarsen to multiple LOD levels (build_skeleton_pyramid).

Example:

from zarr_vectors_tools.convert.ingest.precomputed_plain_skeletons import (
    PlainPrecomputedReader, run_ingest_plain,
)

reader = PlainPrecomputedReader("precomputed://gs://allen_neuroglancer_ccf/Mouselight")
summary = run_ingest_plain(
    reader,
    "/tmp/mouselight.zv",
    chunk_shape_nm=(1_000_000, 1_000_000, 1_000_000),
    strides=[8, 8, 8],
    chunk_scale_factors=[2, 2, 2],
    sparsity_factors=[1.0, 1.0, 4.0],
    read_workers=16,
    pyramid_workers=8,
)
print(summary)
class zarr_vectors_tools.convert.ingest.precomputed_plain_skeletons.PlainPrecomputedReader(base_url)[source]

Bases: object

Read plain (non-.frags) precomputed skeleton segments.

Each skeleton is fetched individually via the cloud-volume library. Requires the optional ingest extras (cloud-volume, cloud-files).

Parameters:

base_url (str) – Layer URL, e.g. "precomputed://gs://allen_neuroglancer_ccf/Mouselight".

__init__(base_url)[source]
Parameters:

base_url (str)

Return type:

None

read_skeleton(seg_id)[source]

Read one segment’s skeleton, returning coordinates in nanometres.

Uses cloud-volume’s skeleton source, which handles both sharded and unsharded layers transparently.

Returns a dict with keys:

  • "vertices" – (N, 3) float32 in nm

  • "edges" – (M, 2) int64 [child, parent]

  • plus one array per vertex attribute in self.info.vertex_attributes

Returns None if the segment has no skeleton in the store.

Parameters:

seg_id (int)

Return type:

dict[str, ndarray[tuple[Any, …], dtype[_ScalarT]]] | None

property segment_ids: list[int]

Sorted list of segment IDs from the segment_properties sub-dir.

property segment_properties_raw: dict[str, Any] | None

Raw inline dict from segment_properties/info, or None.

class zarr_vectors_tools.convert.ingest.precomputed_plain_skeletons.PlainSkeletonInfo(base_url, transform, vertex_attributes=<factory>, seg_props_path=None, sharding=None)[source]

Bases: object

Metadata parsed from a plain precomputed skeleton info file.

Parameters:
__init__(base_url, transform, vertex_attributes=<factory>, seg_props_path=None, sharding=None)
Parameters:
Return type:

None

property attribute_dtypes: dict[str, str]
property attribute_names: list[str]
base_url: str

Layer URL (no trailing slash).

seg_props_path: str | None = None

Relative path to the segment-properties sub-directory, e.g. "segment_properties".

sharding: dict[str, Any] | None = None

Sharding spec if the layer uses the sharded format, else None.

transform: ndarray[tuple[Any, ...], dtype[_ScalarT]]

stored_nm = transform @ [x, y, z, 1].

Type:

4×4 float64 homogeneous affine

vertex_attributes: list[dict[str, Any]]

Per-vertex attribute descriptors (same schema as precomputed vertex_attributes).

zarr_vectors_tools.convert.ingest.precomputed_plain_skeletons.parse_segment_properties(inline)[source]

Parse the inline block of a segment-properties info file.

Parameters:

inline (dict[str, Any]) – The inline value from the segment-properties info JSON — must contain "ids" and "properties" keys.

Returns:

  • seg_ids is a sorted list of int segment IDs.

  • props is a dict mapping prop_id → (type, values, meta) where:

    • type is the precomputed property type string ("label", "string", "description", "number", "tags").

    • values is a list of raw values aligned with seg_ids.

    • meta is extra info: {"data_type": ...} for numbers, {"tags": [...]} for tags, empty dict otherwise.

Return type:

A 2-tuple (seg_ids, props) where

zarr_vectors_tools.convert.ingest.precomputed_plain_skeletons.run_ingest_plain(reader, out_store, *, chunk_shape_nm=(1000000.0, 1000000.0, 1000000.0), bounds_nm=None, seg_ids=None, attribute_names=None, attribute_dtypes=None, strides=(), chunk_scale_factors=None, sparsity_factors=None, sparsity_strategy='length', drop_interior_below=0, backend=None, progress=True, read_workers=8, pyramid_workers=None, executor=None, batch_size=256, scratch_dir=None)[source]

Ingest a plain precomputed skeleton layer to a multiscale zarr-vectors store.

Unlike zarr_vectors_tools.convert.ingest.precomputed_skeletons.run_ingest(), this function does not assume the existence of .frags spatially- indexed chunk files. Instead it:

  1. Reads all (or a subset of) skeletons batch_size at a time, in parallel using read_workers threads, spilling each batch to scratch disk so memory holds one batch rather than the dataset.

  2. Computes bounds from the vertex data if bounds_nm is not supplied.

  3. Distributes vertices across zarr chunks, preserving cross-chunk connectivity via the standard pieces_from_chunk() mechanism, and writes each chunk from its spilled pieces.

  4. Writes the zarr-vectors store, object index, and segment-property-based object attributes.

  5. Builds a multi-LOD pyramid if strides is non-empty.

Parameters:
  • reader (PlainPrecomputedReader) – A PlainPrecomputedReader (or any object exposing .info (PlainSkeletonInfo) and .read_skeleton(seg_id), .segment_ids, .segment_properties_raw).

  • out_store (str | Path) – Output zarr-vectors store path.

  • chunk_shape_nm (tuple[float, ...]) – Target spatial chunk size in nm per axis. Defaults to 1 mm³ (1_000_000, 1_000_000, 1_000_000).

  • bounds_nm (tuple[list[float], list[float]] | None) – Optional (min_corner, max_corner) in nm. If None, computed from the vertex data and rounded outward to the chunk grid.

  • seg_ids (list[int] | None) – Optional explicit list of segment IDs to ingest. Defaults to all IDs in the layer’s segment_properties.

  • attribute_names (Sequence[str] | None) – Per-vertex attributes to carry. Defaults to all attributes in reader.info.vertex_attributes.

  • attribute_dtypes (dict[str, str] | None) – Override dtype map for per-vertex attributes.

  • strides (Sequence[int]) – Per-pyramid-level decimation strides (keep every k-th vertex). Empty → level 0 only.

  • chunk_scale_factors (Sequence[int | tuple[int, ...]] | None) – Per-level spatial coarsening (default: 2 per axis).

  • sparsity_factors (Sequence[float] | None) – Per-level fraction of objects to keep (default: 1.0).

  • sparsity_strategy (str) – Sparsification strategy ("length" or other).

  • drop_interior_below (int) – LOD: drop fully-interior objects with ≤ N vertices.

  • backend (str | None) – zarr-vectors storage backend override.

  • progress (bool) – If True, print progress messages.

  • read_workers (int) – Number of threads for parallel skeleton reads (IO-bound).

  • pyramid_workers (int | None) – Number of Dask process workers for pyramid building (CPU-bound). None → serial, or executor when given.

  • executor (Any) – A map-like (func, items, shared) callable for the pyramid build, used when pyramid_workers is not set.

  • batch_size (int) – Skeletons read and held at once. Peak memory scales with it; the store does not depend on it.

  • scratch_dir (str | Path | None) – Where the spilled batches and chunk pieces go (a temporary directory, removed afterwards). Default: the system temp directory; point it at a large disk for a big layer.

Returns:

Summary dict with keys objects, level0_fragments, level0_cross_chunk_edges, batches, and optionally pyramid.

Return type:

dict[str, Any]

Precomputed meshes

Neuroglancer precomputed mesh layer → zarr-vectors mesh store.

A mesh layer holds one mesh per segment, in one of three layouts, told apart by the @type (and sharding) of the layer’s info:

  • neuroglancer_legacy_mesh: a <segment id>:0 JSON manifest naming fragment files, each a vertex count, float32 vertices and uint32 triangles. One level of detail.

  • neuroglancer_multilod_draco: a <segment id>.index manifest and a <segment id> file of Draco-encoded fragments, several levels of detail.

  • the same, sharded: manifests and fragments packed into .shard files.

Each segment becomes one object. Objects are numbered by the rank of their segment id, and the ids are stored ascending as the segment_id object attribute – the convention the EM skeleton ingests use, so export_precomputed() and lookups by segment id work on the result.

Meshing pipelines (igneous, zmesh) mesh each chunk of the volume separately, so a vertex on a chunk face is written once per fragment that touches it. weld=True merges vertices with identical coordinates within a segment, then drops the faces that collapse or repeat; without it an object’s fragments do not share vertices across their seams. Multi-resolution fragments are quantised to a grid whose ends lie on the fragment’s faces, so their seam vertices coincide exactly as well.

Memory holds every ingested segment’s vertices and faces at once (about 20 bytes per vertex and 24 per triangle after welding), since the store is written in one call. Select segments with segment_ids to bound it.

Needs cloud-volume (and DracoPy for multi-resolution layers), from the precomputed extra.

zarr_vectors_tools.convert.ingest.precomputed_meshes.ingest_precomputed_meshes(source, out_store, chunk_shape, *, segment_ids=None, lod=0, weld=True, batch_size=64, read_workers=4, segment_properties=True, progress=True)[source]

Ingest a precomputed mesh layer, one object per segment.

Parameters:
  • source (str | Path) – The mesh directory: a URL (gs://, s3://, https://, file://, mem://, optionally behind precomputed://) or a local directory. Not the segmentation layer above it.

  • out_store (str | Path) – Output store path.

  • chunk_shape (Sequence[float]) – Level-0 chunk size, in the layer’s units (nanometres).

  • segment_ids (Sequence[int] | None) – Only these segments. Default: every segment in the layer.

  • lod (int) – Level of detail to read from a multi-resolution layer; 0 is the finest. A legacy layer has only level 0.

  • weld (bool) – Merge coincident vertices across fragment seams.

  • batch_size (int) – Segments per read.

  • read_workers (int) – Threads reading batches.

  • segment_properties (bool) – Copy the layer’s inline segment properties, when its info names them, as object attributes.

  • progress (bool) – Print progress.

Returns:

Summary dict with layer, layout, lod, object_count, empty_segments (ids asked for whose mesh has no faces at lod), vertex_count, face_count, vertices_welded, faces_dropped and properties, plus write_mesh()’s own.

Raises:
  • FileNotFoundError – No info at source.

  • ValueError – source is not a mesh layer, a segment asked for has no mesh, lod is out of range, or nothing is left to write.

Return type:

dict[str, Any]

zarr_vectors_tools.convert.ingest.precomputed_meshes.list_mesh_segment_ids(url, info)[source]

Every segment id with a mesh in the layer, ascending.

Unsharded layers are listed by their manifest names; a sharded layer by reading the minishard indices of each .shard file.

Parameters:
Return type:

list[int]

zarr_vectors_tools.convert.ingest.precomputed_meshes.mesh_layout(info)[source]

"legacy", "multilod" or "multilod_sharded" for a mesh info.

Parameters:

info (dict[str, Any])

Return type:

str

zarr_vectors_tools.convert.ingest.precomputed_meshes.mesh_source(url)[source]

A cloud-volume mesh source for the mesh directory at url.

PrecomputedMeshSource.from_cloudpath does not build its configuration with every argument cloud-volume 12 requires, so the source is assembled here the way the skeleton source’s from_cloudpath does it.

Parameters:

url (str)

Return type:

Any

zarr_vectors_tools.convert.ingest.precomputed_meshes.weld_vertices(vertices, faces)[source]

Merge coincident vertices; drop the faces that collapse or repeat.

Returns (vertices, faces, faces dropped). Vertices no face uses are dropped too, and the survivors keep the order of their first use.

Parameters:
Return type:

tuple[ndarray[tuple[Any, …], dtype[float32]], ndarray[tuple[Any, …], dtype[int64]], int]

Wavefront OBJ

Ingest meshes from Wavefront OBJ files into zarr vectors.

The parser is numpy only – no external dependencies needed. Lines are tokenised with numpy and face indices decoded without a Python loop; text it cannot parse exactly falls back to a line-by-line reader (see zarr_vectors_tools.convert.ingest._text_tokens).

zarr_vectors_tools.convert.ingest.obj.ingest_obj(input_path, output_path, chunk_shape, *, bin_shape=None, dtype='float32', encoding='raw', draco_quantization_bits=11, auto_object_id=False)[source]

Ingest an OBJ file into a zarr vectors mesh store.

Supports triangular and quad faces. Polygon faces with more than 4 vertices are fan-triangulated.

Parameters:
  • input_path (str | Path) – Path to the input .obj file.

  • output_path (str | Path) – Path for the output zarr vectors store.

  • chunk_shape (ChunkShape) – Spatial chunk size per dimension (3D).

  • dtype (str) – Dtype for position data.

  • encoding (str) – "raw" or "draco".

  • draco_quantization_bits (int) – For Draco encoding.

  • auto_object_id (bool) – If True, parse o <name> / g <name> directives and assign each vertex an integer object ID based on the most recently declared group. Object names are stored in OBJHeader.object_names.

  • bin_shape (BinShape | None)

Returns:

Summary dict from write_mesh().

Return type:

dict[str, Any]

STL

Ingest meshes from STL files (ASCII and binary) into zarr vectors.

Both parsers are numpy only – no external dependencies needed. Binary STL is read as blocks of fixed 50-byte records; ASCII STL is tokenised with numpy and falls back to a line-by-line reader for text it cannot parse exactly (see zarr_vectors_tools.convert.ingest._text_tokens).

zarr_vectors_tools.convert.ingest.stl.ingest_stl(input_path, output_path, chunk_shape, *, bin_shape=None, dtype='float32', encoding='raw', merge_vertices=True, merge_tolerance=1e-06)[source]

Ingest an STL file into a zarr vectors mesh store.

STL stores each triangle with 3 independent vertices (no sharing), so merge_vertices=True (default) deduplicates vertices that are within merge_tolerance.

Parameters:
  • input_path (str | Path) – Path to the input .stl file.

  • output_path (str | Path) – Path for the output zarr vectors store.

  • chunk_shape (ChunkShape) – Spatial chunk size per dimension (3D).

  • dtype (str) – Dtype for position data.

  • encoding (str) – "raw" or "draco".

  • merge_vertices (bool) – If True, merge duplicate vertices.

  • merge_tolerance (float) – Distance threshold for merging.

  • bin_shape (BinShape | None)

Returns:

Summary dict from write_mesh().

Return type:

dict[str, Any]

Synapse tables

Synapse tables joined to an EM skeleton store by segment id.

CAVE exports a connectome’s synapses as a table: one row per synapse, with the pre- and post-synaptic segment (pre_pt_root_id, post_pt_root_id) and positions in voxels (ctr_pt_position and friends). A skeleton store built by the precomputed ingesters keeps each object’s segment id, so the two join without any spatial matching:

  • the synapses become a point store whose object ids are the skeleton store’s – synapse object 12 is skeleton object 12, the same neuron – so picking either in a viewer names the same segment;

  • each skeleton object gains synapse_pre_count and synapse_post_count;

  • the synapse store’s objects carry the same segment_id attribute (0 for the object holding unmatched synapses), so SegmentLink finds a segment in either store.

A synapse has two segments and a point store gives each point one object, so side chooses which one owns it (the post-synaptic side by default: “the inputs of this neuron”). The other side’s segment id is kept on every point as pre_segment_id or post_segment_id, and the synapse id as the join key, so later tables can be attached to the synapses with zvtools attach.

zarr_vectors_tools.convert.ingest.synapses.ingest_synapses(table_path, skeleton_store, output_path, chunk_shape=None, *, side='post', position='ctr_pt_position', resolution=(1.0, 1.0, 1.0), pre_column='pre_pt_root_id', post_column='post_pt_root_id', id_column='id', columns=None, unmatched='keep', write_counts=True, chunksize=1000000)[source]

Write a synapse table as a point store keyed to a skeleton store’s objects.

Parameters:
  • table_path (str | Path) – The synapse table: CSV/TSV (.csv, .tsv, .txt), or Parquet / Feather when pyarrow is installed.

  • skeleton_store (str | Path) – A store with object_attributes/segment_id at level 0, as the precomputed skeleton ingesters write.

  • output_path (str | Path) – The point store to create.

  • chunk_shape (Sequence[float] | None) – Chunk size, in nanometres. Default: the skeleton store’s, so the two stores’ chunks line up.

  • side (str) – "post" or "pre" – whose segment owns each synapse.

  • position (str) – The position column: either one column holding "[x y z]" strings, or three columns <position>_x/_y/_z.

  • resolution (Sequence[float]) – Nanometres per voxel of the position columns (FlyWire and MICrONS tables are 4, 4, 40).

  • pre_column (str) – The segment id columns.

  • post_column (str) – The segment id columns.

  • id_column (str | None) – The synapse id column, stored as the join key; None when the table has none.

  • columns (Sequence[str] | None) – Further numeric columns to keep as point attributes, e.g. ["size"].

  • unmatched (str) – What to do with a synapse whose owning segment is not in the skeleton store: "keep" it as one extra object (id one past the skeleton store’s last), "drop" it, or raise ("error").

  • write_counts (bool) – Write synapse_pre_count / synapse_post_count to every level of the skeleton store, replacing earlier counts.

  • chunksize (int) – Table rows read at a time.

Returns:

Summary with rows_read, synapses_written, unmatched, dropped, objects (skeleton objects with at least one synapse), unassigned_object (the extra object id, or None) and the point writer’s own counts.

Raises:

IngestError – For a skeleton store without segment ids, a table missing a named column, an unknown side or unmatched, or unmatched synapses with unmatched="error".

Return type:

dict[str, Any]