Ingest

zarr_vectors_tools.convert.ingest: one module per input format. Each reads a file and writes a store. zvtools convert FILE STORE calls these.

Points and tables

CSV / XYZ points

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

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

Whether the first row is a header is read from the row itself (a row that is not all numbers is a header), and so is the delimiter (a comma if the row has one, otherwise runs of whitespace), unless the caller says. The position columns’ names are kept in the store’s CSV header, so a CSV export writes the header the file came with.

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

With object_ids, each object’s vertex_count and each fragment’s segment_id are written too (see _object_columns).

zarr_vectors_tools.convert.ingest.csv_points.WHITESPACE = 'whitespace'

delimiter value meaning “runs of spaces or tabs”, the usual XYZ layout.

zarr_vectors_tools.convert.ingest.csv_points.ingest_csv(input_path, output_path, chunk_shape, *, bin_shape=None, ndim=3, delimiter=None, has_header=None, 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=None)[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 | None) – Column delimiter. None (default) reads it from the first row: a comma if it has one, otherwise whitespace. "whitespace" (or a space) splits on runs of spaces and tabs.

  • has_header (bool | None) – Whether the first row is a header. None (default) decides from the row: a header is a row that is not all numbers.

  • 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 | None) – Write per-object vertex counts to object_attributes["vertex_count"]. None (default): whenever object_ids is given; True requires it.

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

zarr_vectors_tools.convert.ingest.csv_points.is_whitespace_delimiter(delimiter)[source]

Whether delimiter means runs of whitespace rather than one character.

A literal space counts: no point file separates its columns by exactly one space and means two spaces to be an empty column between them.

Parameters:

delimiter (str | None)

Return type:

bool

Keyed tables

Ingest a delimited table of identified points, and stage columns from more.

This is the CSV ingester for tables whose rows carry a stable identifier alongside their coordinates — the Allen Brain Cell Atlas MERFISH releases being the motivating case, where ccf_coordinates.csv holds cell_label, x, y, z and the rest of the per-cell metadata lives in sibling files keyed by that same cell_label.

It differs from zarr_vectors_tools.convert.ingest.csv_points in exactly the ways that matter for staged imports:

  • A key column. The identifier is hashed into the zv_join_key attribute, so later files can be joined onto these points by identity rather than by row position. Identifiers stay usable even when they do not fit a numeric column — the atlas’s are 39-digit values.

  • Mixed column types. It reads through pandas, so string and categorical metadata columns come through as dictionary-encoded codes (the array carries its labels, so a viewer shows them), where csv_points’ numpy.loadtxt path requires everything be numeric.

  • A header. Column labels and categories are recorded so export_h5ad() can reconstitute the table.

Ingest the coordinate table once with ingest_table(), then stage in each remaining file with attach_table() or attach_h5ad().

zarr_vectors_tools.convert.ingest.cell_table.attach_table(store_path, input_path, *, key_column, columns=None, delimiter=',', key_attribute='zv_join_key', level=0, missing='fill', fill_value=nan, overwrite=False, shard_shape=None, progress=False)[source]

Stage columns from a delimited table into an existing store.

Rows are matched to points on key_column, so the table needs neither the same order nor the same row set as the store.

Parameters:
  • store_path (str | Path) – Zarr Vectors store to add attributes to (modified in place).

  • input_path (str | Path) – Table to read.

  • key_column (str) – Column holding the identifier to join on.

  • columns (list[str] | None) – Columns to stage in. Default (None) takes every column except the key.

  • delimiter (str) – Column delimiter.

  • key_attribute (str) – Store attribute holding the join key.

  • level (int) – Resolution level to write into.

  • missing (str) – "fill" or "error" for points absent from the table.

  • fill_value (Any) – Value written for unmatched points.

  • overwrite (bool) – Allow replacing attributes that already exist.

  • shard_shape (int | tuple[int, ...] | None) – Create the new attribute arrays sharded (chunks per axis per storage object). See attach_attributes().

  • progress (bool) – Print progress while writing.

Returns:

The attach_attributes() summary, plus columns_attached.

Raises:

IngestError – If the file or the named columns cannot be read.

Return type:

dict[str, Any]

zarr_vectors_tools.convert.ingest.cell_table.ingest_table(input_path, output_path, chunk_shape, *, position_columns, key_column=None, columns=None, bin_shape=None, dtype='float32', delimiter=',', object_id_column=None, drop_na=True, preserve_index=True, max_index=200000)[source]

Ingest a delimited table of identified points into a Zarr Vectors store.

Parameters:
  • input_path (str | Path) – Path to the input table (CSV/TSV).

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

  • chunk_shape (ChunkShape) – Spatial chunk size, one entry per position column.

  • position_columns (list[str]) – Column names holding the coordinates, in axis order (e.g. ["x", "y", "z"]).

  • key_column (str | None) – Column holding the row identifier. Hashed into the zv_join_key attribute so later files can be staged in against it. Strongly recommended — without it the store cannot be joined to.

  • columns (list[str] | None) – Metadata columns to store as vertex attributes. Default (None) stores every column that is neither a position nor the key; pass [] for none.

  • bin_shape (BinShape | None) – Optional intra-chunk sub-binning.

  • dtype (str) – Dtype for position data.

  • delimiter (str) – Column delimiter; "whitespace" splits on runs of spaces and tabs.

  • object_id_column (str | None) – Column grouping rows into Zarr Vectors objects. Each object’s vertex_count and each fragment’s segment_id are written with them (see _object_columns).

  • drop_na (bool) – Drop rows whose coordinates contain NaN. On by default — coordinate tables routinely carry unregistered rows, and NaN coordinates cannot be assigned to a chunk.

  • preserve_index (bool) – Inline the key column’s values into the store header so export can restore the original identifiers.

  • max_index (int) – Skip inlining above this many rows.

Returns:

Summary dict from write_points(), plus columns_stored, dropped_na and index_stored.

Raises:

IngestError – If the file or the named columns cannot be read.

Return type:

dict[str, Any]

AnnData (h5ad)

Ingest AnnData .h5ad files into Zarr Vectors point clouds.

An .h5ad file is a cell-by-gene table with side tables; the only part of it that is spatial is an obsm embedding — obsm["spatial"] for spatial transcriptomics (Visium, Xenium, MERFISH, CosMx), or a dimensionality reduction such as obsm["X_umap"] for dissociated data. That embedding becomes the Zarr Vectors point cloud: one point per cell.

Everything else rides along as per-vertex attributes:

  • obs columns. Numeric columns are stored as-is; categorical/string columns are stored as integer codes, dictionary-encoded (the array carries its labels, which is what lets a viewer show them), with the labels also recorded in the H5ADHeader so export can rebuild the pandas.Categorical.

  • Selected genes. Expression is a wide matrix (often 20k+ columns) and a Zarr Vectors attribute is one array per name, so genes are opt-in via genes= and pulled from X or from layers[layer].

Two details make the round-trip exact. Zarr Vectors orders vertices by spatial chunk rather than by source row, so the source row index is stored as its own attribute and export sorts on it. And attribute names must be valid Zarr path segments, so labels are sanitised and the originals kept in the header.

Requires the anndata package:

pip install 'zarr-vectors-tools[h5ad]'
zarr_vectors_tools.convert.ingest.h5ad.attach_h5ad(store_path, h5ad_path, *, genes=None, obs_columns=None, layer=None, gene_by=None, key_obs_column=None, key_attribute='zv_join_key', level=0, missing='fill', fill_value=nan, overwrite=False, shard_shape=None, progress=False)[source]

Stage gene expression and obs columns from an .h5ad into a store.

The store is modified in place. Cells are matched on the join key, so the .h5ad needs neither the same row order nor the same cell subset as the store — which is what lets a whole-brain expression matrix be staged onto a store built from a coordinate table covering only part of it. Neither X nor the unused obs columns are read in full.

Parameters:
  • store_path (str | Path) – Zarr Vectors store to add attributes to.

  • h5ad_path (str | Path) – Source .h5ad.

  • genes (list[str] | None) – var names (or symbols, see gene_by) to stage in.

  • obs_columns (list[str] | None) – obs columns to stage in.

  • layer (str | None) – Read expression from layers[layer] instead of X.

  • gene_by (str | None) – var column to match genes against. Default tries the var index first, then gene_symbol — so Ensembl IDs and gene symbols both work without the caller converting.

  • key_obs_column (str | None) – obs column holding the join key. Default is the obs index, which is where cell identifiers normally live.

  • key_attribute (str) – Store attribute holding the join key.

  • level (int) – Resolution level to write into.

  • missing (str) – "fill" or "error" for cells absent from this file.

  • fill_value (Any) – Value written for unmatched cells.

  • overwrite (bool) – Allow replacing attributes that already exist.

  • shard_shape (int | tuple[int, ...] | None) – Create the new attribute arrays sharded (chunks per axis per storage object). Strongly recommended when staging a wide gene panel – see attach_attributes().

  • progress (bool) – Print progress while reading and writing.

Returns:

The attach_attributes() summary, plus genes_attached and obs_columns_attached.

Raises:

IngestError – If the file, keys, genes or columns cannot be resolved.

Return type:

dict[str, Any]

zarr_vectors_tools.convert.ingest.h5ad.ingest_h5ad(input_path, output_path, chunk_shape, *, bin_shape=None, dtype='float32', spatial_key='auto', spatial_columns=None, obs_columns=None, genes=None, layer=None, object_id_column=None, backed=False, drop_na=False, store_row_index=True, store_join_key=True, preserve_obs_index=True, max_obs_index=200000, knn_distance_k=None, per_object_vertex_count=None)[source]

Ingest an AnnData .h5ad file into a Zarr Vectors point cloud store.

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

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

  • chunk_shape (ChunkShape) – Spatial chunk size per dimension. Must have one entry per spatial dimension (2 for a 2D embedding, 3 for 3D).

  • bin_shape (BinShape | None) – Optional intra-chunk sub-binning.

  • dtype (str) – Dtype for position data.

  • spatial_key (str) – obsm key holding the coordinates. "auto" (default) tries spatial, X_spatial, spatial_fov, X_umap, X_tsne, X_pca in that order.

  • spatial_columns (list[int] | None) – Which columns of the embedding to use, e.g. [0, 1] to take the first two of a 3-column array. Default: all columns (capped at 3).

  • obs_columns (list[str] | None) – obs columns to store as vertex attributes. Default (None) stores every column; pass [] for none.

  • genes (list[str] | None) – var names whose expression to store as vertex attributes. Default (None) stores none — expression is wide and each gene costs one array.

  • layer (str | None) – Pull expression from adata.layers[layer] instead of adata.X.

  • object_id_column (str | None) – obs column grouping cells into Zarr Vectors objects (e.g. "cell_type" or "sample"). Categorical labels are encoded as integer codes; the labels go in the header.

  • backed (bool) – Open the file in AnnData’s backed mode, leaving X on disk. Worth it for large files when genes selects few columns; obs/obsm are read into memory either way.

  • drop_na (bool) – Drop cells whose coordinates contain NaN. Off by default; with NaN coordinates present the write will fail instead.

  • store_row_index (bool) – Store each cell’s source obs row index as an attribute so export can restore the original ordering. Leave on unless you never intend to export back.

  • store_join_key (bool) – Store the hashed obs index as the zv_join_key attribute, so further files covering the same cells can be staged in later with attach_h5ad() or attach_table().

  • preserve_obs_index (bool) – Inline the obs index (cell barcodes) into the stored header so export can restore obs_names.

  • max_obs_index (int) – Skip inlining the index above this many cells, to keep store metadata small. Reported as obs_index_stored.

  • knn_distance_k (int | None) – If an int, store each cell’s mean distance to its k nearest neighbours as knn_distance. Requires scipy.

  • per_object_vertex_count (bool | None) – Store per-object cell counts as object_attributes["vertex_count"]. None (default): whenever object_id_column is set; True requires it. With objects, each fragment’s segment_id is written too (see _object_columns).

Returns:

Summary dict from write_points(), plus spatial_key, n_obs, n_vars, obs_columns_stored, genes_stored, obs_index_stored and dropped_na.

Raises:

IngestError – If anndata is missing, the file is unreadable, or the requested keys/columns/genes do not exist.

Return type:

dict[str, Any]

Attach by key

Attach attributes to an existing Zarr Vectors store, joined by key.

Ingest normally builds a store from one file. That breaks down when a dataset is split across files that share cells but not rows — the Allen Brain Cell Atlas MERFISH releases are the motivating case: coordinates in one CSV, per-cell metadata in another, expression in a multi-gigabyte .h5ad with no obsm at all, and each file covering a different subset of cells in a different order. Materialising one combined file first is the expensive thing this module exists to avoid.

Instead the store is created once from whichever file carries the coordinates, and every other file is staged in afterwards as additional per-vertex attributes:

ccf_coordinates.csv  --ingest-->  store.zarr
cell_metadata.csv    --attach-->  store.zarr   (join on cell_label)
...-log2.h5ad        --attach-->  store.zarr   (join on cell_label)

Two properties make this work at scale.

The join. Zarr Vectors orders vertices by spatial chunk, not by source row, and the incoming file has its own order and its own cell subset. So each vertex carries a join key attribute written at ingest, and attach maps incoming rows onto vertices through it. Keys that are absent from the incoming file get a fill value rather than failing the whole import. hash_keys() reduces string identifiers to int64 because Zarr Vectors attributes are numeric — and because the atlas’s own cell_label is a 39-digit (128-bit) value that does not fit an integer column anyway.

The memory bound. Values are written one spatial chunk at a time via core’s per-chunk attribute API, so peak memory is one column of the incoming file plus one chunk, never the whole store.

Attached columns are registered in the store’s H5ADHeader, so export_h5ad() emits staged data alongside data written at ingest, with categorical levels and original column labels intact.

zarr_vectors_tools.convert.ingest.attach.attach_attributes(store_path, values, *, keys=None, level=0, key_attribute='zv_join_key', missing='fill', fill_value=nan, overwrite=False, shard_shape=None, progress=False, _own_level=False)[source]

Write new per-vertex attributes into an existing store.

Parameters:
  • store_path (str | Path) – Path to the Zarr Vectors store to add to (modified in place).

  • values (dict[str, ndarray]) – Attribute name -> (M,) or (M, C) array of incoming values, all sharing the row order of keys.

  • keys (Any | None) – (M,) join keys for the rows of values. Strings are hashed via hash_keys(). When None, the store’s key_attribute is treated as a direct row index into values — the positional mode, for adding more columns from the file the store was built from.

  • level (int) – Resolution level to write into. On an additive level (refinement: "add"), whose complete content spans the coarser levels of its chain, every level of the chain is written, each matching its own vertices – otherwise the vertices stored at the coarser levels would have no value and the attribute would drop out of the level’s complete content.

  • key_attribute (str) – Per-vertex attribute holding the join key (or the row index when keys is None).

  • missing (str) – "fill" (default) writes fill_value for vertices absent from the incoming file; "error" raises instead.

  • fill_value (Any) – Value for unmatched vertices. Defaults to NaN for float attributes and -1 for integer ones.

  • overwrite (bool) – Allow replacing attributes that already exist.

  • shard_shape (int | tuple[int, ...] | None) – Create the new attribute arrays sharded, packing this many spatial chunks per axis into each storage object (an int broadcasts to every axis). Decide this here rather than resharding later: unsharded, a store costs one file per chunk per attribute, so staging a wide panel produces millions of files and repacking them means rereading every one. Match the value across attaches to keep the store uniform.

  • progress (bool) – Print per-chunk progress — worth it on stores with many thousands of chunks.

  • _own_level (bool)

Returns:

Summary dict with attributes_written, vertices_matched, vertices_unmatched, chunk_count, duplicate_keys and sharded.

Raises:

IngestError – If the store, level or key attribute is missing, the shapes disagree, or missing="error" and a vertex is unmatched.

Return type:

dict[str, Any]

zarr_vectors_tools.convert.ingest.attach.hash_keys(keys)[source]

Reduce join keys to a stable int64 array.

Integer keys pass through unchanged. Everything else is hashed with FNV-1a over the UTF-8 bytes, vectorised across the whole array.

The hash deliberately ignores the fixed-width zero padding that numpy byte-string arrays carry, so the same logical key hashes identically whether it arrived in an S39 column or an S64 one — otherwise two files describing the same cells would refuse to join.

Parameters:

keys (Any) – Array-like of identifiers (strings, bytes, or integers).

Returns:

(N,) int64 array of keys.

Return type:

ndarray

zarr_vectors_tools.convert.ingest.attach.register_attached(store_path, *, obs_names=None, gene_names=None, categories=None, dtypes=None)[source]

Record attached columns in the store’s h5ad header.

Keeps export_h5ad() able to emit staged columns under their original labels — with categorical levels decoded and genes routed into X rather than obs — exactly as it does for columns written at ingest. Creates the header if the store has none (a store built from a CSV will not).

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

  • obs_names (dict[str, str] | None) – Attribute name -> original obs column label.

  • gene_names (dict[str, str] | None) – Attribute name -> original var (gene) name.

  • categories (dict[str, list[str]] | None) – Original column label -> ordered category labels.

  • dtypes (dict[str, str] | None) – Original column label -> source pandas dtype.

Return type:

None

LAS / LAZ

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

Requires the laspy package: pip install 'zarr-vectors-tools[las]' (which also installs lazrs, the .laz decompressor).

Each dimension is stored in a dtype that holds every value it can take: intensity, colour and classification are 8- and 16-bit integers, which float32 holds exactly; GPS time is float64, which it does not.

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=None)[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 | None) – Write per-object vertex counts to object_attributes["vertex_count"]. None (default): whenever object_ids is given; True requires it. With objects, each fragment’s segment_id is written too (see _object_columns).

  • 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

Ingest point clouds from PLY files into Zarr Vectors.

Requires the plyfile package: pip install 'zarr-vectors-tools[ply]'. 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=None)[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 | None) – Write per-object vertex counts to object_attributes["vertex_count"]. None (default): whenever object_ids is given; True requires it. With objects, each fragment’s segment_id is written too (see _object_columns).

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

Streamlines and lines

TrackVis TRK

Ingest streamlines from TrackVis TRK files into zarr vectors.

Requires nibabel: pip install 'zarr-vectors-tools[trk]'.

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]

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
         each streamline's first, middle and last vertex 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) sample_points float32 (O, 3, 3) first, middle, last 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 (set by executor). Defaults to max(4 x workers, 16), capped at the streamline count.

  • workers (int | None) – Sizes n_parts and the batches; it does not start any processes itself.

  • executor (Any) – The executor that runs the parts in parallel, e.g. zarr_vectors_tools.parallel.process_pool_executor(). Without one the ingest 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_count is always written, in place of a file property of that name.

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

LINC TRK

Ingest LINC/atlas-labelled TRK files into zarr vectors.

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

Ingest a LINC-labelled TRK file into a zarr vectors store.

The input TRK must contain data_per_streamline["label_id"]. Each streamline’s label_id determines which group it belongs to. Integral floating-point label IDs are accepted and converted to int64.

The LUT (text file) maps atlas label IDs to group metadata, including the group name and RGBA color. A group is created for each unique label ID present in the TRK.

The mapping JSON is optional. When supplied, it maps the input TRK filename to its expected atlas label ID and is used only as a consistency check. When omitted, the group information is taken entirely from the TRK label_id attribute and the LUT.

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

  • lut_path (str | Path) – Path to the label lookup table containing label IDs, names, and RGBA colors.

  • mapping_path (str | Path | None) – Optional path to the JSON file mapping TRK filenames to their expected atlas label IDs. If None, no filename/label cross-check is performed.

  • 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 object_attributes["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 as dropped_by_length.

Returns:

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

Raises:
  • IngestError – If the TRK does not contain label_id, a label ID is invalid, or a TRK label is missing from the LUT. When mapping_path is given, also if the input filename is missing from the mapping or the mapped label does not occur in the TRK.

  • FileNotFoundError – If the input TRK file does not exist.

Return type:

dict[str, Any]

MRtrix TCK

Ingest streamlines from MRtrix TCK files into zarr vectors.

Requires nibabel: pip install 'zarr-vectors-tools[trk]'.

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. The store’s axes record the millimetres.

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]

TRX

Ingest streamlines from TRX files into zarr vectors.

Requires trx-python: pip install 'zarr-vectors-tools[trx]'.

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). Positions are RAS millimetres by definition, and the store’s axes say so.

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]

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]

Skeletons

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"].

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

  • compute_node_kind (bool) – If True, write per-node kind label to node_attributes["node_kind"] (0=soma, 1=branch, 2=continuation, 3=terminal). All three are stored as float32.

  • bin_shape (BinShape | None)

Return type:

dict[str, Any]

Each tree is one object, and object_attributes/segment_id numbers them from 1 in root order, the id precomputed export and zvtools synapses use; each fragment carries its object_id and segment_id too, which the skeleton pyramid groups by.

Returns:

Summary dict from write_graph().

Parameters:
  • input_path (str | Path)

  • output_path (str | Path)

  • chunk_shape (ChunkShape)

  • bin_shape (BinShape | None)

  • dtype (str)

  • preserve_header (bool)

  • compute_topological_depth (bool)

  • compute_strahler (bool)

  • compute_node_kind (bool)

Return type:

dict[str, Any]

Precomputed layers

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, 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. Intra-chunk connectivity is split into rooted components, one fragment per component.

Without fixed_cell this writes the linked layout (LAYOUT_LINKED): every vertex once, and a cross-chunk edge whose record stands for its child’s parent. So each segment is rooted as a whole first, each piece is rooted at its vertex whose parent sits in another chunk, and each cross edge is (child gid, parent gid). A skeletonizer promises neither a vertex order nor an edge orientation, and rooting each piece at its lowest index instead gave a piece two parents wherever the two disagreed.

Returns (by_chunk, cross_edges, next_gid) where cross_edges is a list of (gid_child, gid_parent) 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]

zarr_vectors_tools.convert.ingest.precomputed_skeletons.stamp_level_vertex_count(level_group)[source]

Record a level’s vertex count in its metadata, and return it.

The per-chunk skeleton writer leaves the level’s vertex_count at 0, and a viewer budgets levels by it. Summed from each chunk’s fragment index, which is kilobytes per chunk, not from the vertices.

Parameters:

level_group (Any)

Return type:

int

Precomputed, 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]

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]

Meshes

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", the only encoding a store can be read back in. "draco" is refused: core writes Draco meshes but has no decoder to read them.

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

zarr_vectors_tools.convert.ingest.obj.refuse_unreadable_encoding(encoding)[source]

Refuse a mesh encoding the store could not be read back in.

Core’s write_mesh writes Draco-encoded chunks, but read_mesh has no Draco decoder and fails on them (“buffer size must be a multiple of element size”), as does every exporter and the pyramid. Lift this when core reads Draco.

Parameters:

encoding (str)

Return type:

None

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", the only encoding a store can be read back in. "draco" is refused: core writes Draco meshes but has no decoder to read them.

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

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]

Cortical surfaces

GIFTI

Ingest GIFTI cortical surfaces, metrics and parcellations.

GIFTI is how HCP, fMRIPrep and Connectome Workbench exchange surfaces, and a subject is always a SET of files rather than one:

sub-01_hemi-L_midthickness.surf.gii     geometry
sub-01_hemi-L_inflated.surf.gii         same mesh, another shape
sub-01_hemi-L_thickness.shape.gii       per-vertex scalar
sub-01_hemi-L_desc-aparc.label.gii      per-vertex parcellation
... and the same for hemi-R

ingest_gifti() takes that set – a directory, a list of files, or a single surface – sorts every file by what it is and which hemisphere it describes, and writes one surface store (see _surface_store for the layout).

How each file is classified

  • Kind. A file with a POINTSET array is a surface; one with a LABEL array is a parcellation; anything else holding per-vertex values (SHAPE, NONE, statistics, TIME_SERIES) is a scalar map.

  • Hemisphere. From AnatomicalStructurePrimary, in the file’s metadata or an array’s, falling back to the filename (hemi-L, .L., lh.…).

  • Surface. GeometricType first for the shapes that are not anatomy (inflated, sphere, flat), because HCP writes an inflated surface with AnatomicalStructureSecondary=MidThickness – it was inflated FROM the midthickness – and reading that field first would chunk a balloon. Then the filename, then AnatomicalStructureSecondary.

Coordinate systems

A surface’s positions are in the array’s dataspace, and the file may carry a matrix, CoordinateSystemTransformMatrix, from there to a transformed space. FreeSurfer’s mris_convert writes exactly that: positions in surface RAS (dataspace unknown), and a translation by c_ras to scanner. Read as stored, such a surface sits c_ras away from the same subject’s T1 and tractography.

space="auto" (the default) applies the matrix when it leads to a named space and is not the identity, and records that space; otherwise positions are kept and the dataspace is recorded. "scanner" requires the result to be scanner RAS, and "surface" keeps every position as the file stores it. Only anatomical surfaces are moved: inflated, spherical and flat ones are in no anatomical space. Each matrix applied is recorded in the header, as is c_ras when the matrices are one translation into scanner RAS, so the change can be undone.

Requires nibabel:

pip install 'zarr-vectors-tools[surfaces]'
zarr_vectors_tools.convert.ingest.gifti.ANATOMICAL_PREFERENCE: tuple[str, ...] = ('midthickness', 'pial', 'white', 'smoothwm', 'orig', 'surface')

Surfaces that describe cortex in anatomical space, in the order they are preferred as the chunked geometry. Midthickness first: it lies between the white and pial boundaries, so it is the least biased surface to project volume data onto and the one HCP analyses use.

class zarr_vectors_tools.convert.ingest.gifti.GiftiFile(path, kind, hemisphere, surface, image=None)[source]

Bases: object

One classified GIFTI file.

Parameters:
  • path (Path)

  • kind (str)

  • hemisphere (str | None)

  • surface (str | None)

  • image (Any)

__init__(path, kind, hemisphere, surface, image=None)
Parameters:
  • path (Path)

  • kind (str)

  • hemisphere (str | None)

  • surface (str | None)

  • image (Any)

Return type:

None

hemisphere: str | None
image: Any = None
kind: str
path: Path
surface: str | None
zarr_vectors_tools.convert.ingest.gifti.SPACES = ('auto', 'scanner', 'surface')

space values ingest_gifti() takes, as ingest_freesurfer does.

zarr_vectors_tools.convert.ingest.gifti.classify_gifti(path)[source]

Read one GIFTI file and say what it is.

Parameters:

path (str | Path) – A .gii file.

Returns:

A GiftiFile with the loaded image attached.

Raises:

IngestError – If the file cannot be read or holds no per-vertex data.

Return type:

GiftiFile

zarr_vectors_tools.convert.ingest.gifti.ingest_gifti(input_path, output_path, chunk_shape, *, bin_shape=None, dtype='float32', geometry=None, hemisphere=None, space='auto')[source]

Ingest a set of GIFTI files into one cortical surface store.

Parameters:
  • input_path (str | Path | list[str | Path]) – A directory of .gii files, a list of files, or a single surface file.

  • output_path (str | Path) – Store to create.

  • chunk_shape (ChunkShape) – Spatial chunk size in mm (e.g. (20, 20, 20): a whole cortex is roughly 140 x 180 x 120 mm).

  • bin_shape (BinShape | None) – Optional intra-chunk sub-binning.

  • dtype (str) – Position dtype.

  • geometry (str | None) – Which surface to chunk ("pial", "white"…). Default: the first available of midthickness, pial, white, smoothwm, orig. Every other surface of the same hemisphere becomes a coords_<name> attribute.

  • hemisphere (str | None) – Assign every file with no hemisphere information to this one ("left"/"right"). Only needed for files that carry neither AnatomicalStructurePrimary nor a hemisphere token in their name.

  • space (str) – "auto" (apply each surface file’s matrix when it leads to a named space), "scanner" (require scanner RAS) or "surface" (keep positions as the files store them). See the module notes.

Returns:

mesh counts plus hemispheres, geometry, space, c_ras, transformed (the files whose matrix was applied), scalars, labels, alternates, filled and files (how each input was classified).

Return type:

The surface-store summary

Raises:

IngestError – If a file’s hemisphere cannot be determined, a map does not match its surface’s vertex count, a hemisphere has no surface to use as geometry, or space="scanner" is asked of a surface that does not lead to scanner RAS.

FreeSurfer

Ingest a FreeSurfer subject’s cortical surfaces into a surface store.

A recon-all subject directory holds each hemisphere as separate, extensionless files that share one vertex numbering:

subject/
  surf/   lh.white  lh.pial  lh.inflated  lh.sphere     surfaces
          lh.thickness  lh.curv  lh.sulc  lh.area        morphometry
  label/  lh.aparc.annot  lh.aparc.a2009s.annot          parcellations
  ... and rh.* for the right hemisphere

ingest_freesurfer() reads the ones asked for and writes one surface store (layout in _surface_store).

Coordinates

FreeSurfer writes surfaces in surface RAS (“tkregister” space), which is centred on the conformed volume rather than on the scanner. Everything else in a neuroimaging pipeline – the T1, the DWI, tractography in TRK or TRX, fMRIPrep’s GIFTI surfaces – is in scanner RAS. The two differ by one translation, c_ras, recorded in each surface file’s footer.

space="auto" (the default) adds c_ras to the anatomical surfaces when it is known, so the store lines up with tracts and volumes of the same subject. It is taken from the surface footer when the footer is marked valid, and otherwise from the subject’s mri/orig.mgz (or T1.mgz), which is where FreeSurfer’s own tools read it. An invalid footer’s cras is never used: fsaverage ships footers marked valid = 0 whose cras is a 2 mm artefact, while its volumes record an offset of zero.

Inflated and spherical surfaces are left alone: they are not in any anatomical space, and shifting them means nothing. c_ras is recorded in the header either way, so the shift can always be undone.

Midthickness

recon-all does not write a midthickness surface, but it is the most useful geometry: it lies halfway through cortex, so it is the least biased surface for projecting volume data and the one HCP-style analyses use. When no ?h.midthickness file exists it is computed as the vertex-wise mean of white and pial, which is how Connectome Workbench builds it too.

Requires nibabel:

pip install 'zarr-vectors-tools[surfaces]'
zarr_vectors_tools.convert.ingest.freesurfer.DEFAULT_ALTERNATES: tuple[str, ...] = ('white', 'pial', 'inflated', 'sphere')

Other surfaces carried as coords_<name> attributes when present.

zarr_vectors_tools.convert.ingest.freesurfer.DEFAULT_ANNOTATIONS: tuple[str, ...] = ('aparc',)

Parcellations read from label/ when present.

zarr_vectors_tools.convert.ingest.freesurfer.DEFAULT_MORPHOMETRY: tuple[str, ...] = ('thickness', 'curv', 'sulc', 'area')

Per-vertex morphometry maps read from surf/ when present.

zarr_vectors_tools.convert.ingest.freesurfer.find_freesurfer_surf_dir(path)[source]

The surf/ directory for a subject directory or a surf/ path.

Returns None when path does not look like FreeSurfer output, so callers (the CLI’s format detection) can ask without catching errors.

Parameters:

path (str | Path)

Return type:

Path | None

zarr_vectors_tools.convert.ingest.freesurfer.ingest_freesurfer(input_path, output_path, chunk_shape, *, bin_shape=None, dtype='float32', geometry='midthickness', alternates=None, morphometry=None, annotations=None, hemispheres=None, space='auto')[source]

Ingest a FreeSurfer subject into one cortical surface store.

Parameters:
  • input_path (str | Path) – The subject directory (holding surf/ and label/) or its surf/ directory.

  • output_path (str | Path) – Store to create.

  • chunk_shape (ChunkShape) – Spatial chunk size in mm.

  • bin_shape (BinShape | None) – Optional intra-chunk sub-binning.

  • dtype (str) – Position dtype.

  • geometry (str) – Surface to chunk: midthickness (default; computed from white and pial when there is no file), white, pial, smoothwm or orig.

  • alternates (tuple[str, ...] | list[str] | None) – Other surfaces to carry as coords_<name>. Default white, pial, inflated, sphere, each only if present; named explicitly, each must exist.

  • morphometry (tuple[str, ...] | list[str] | None) – Per-vertex maps from surf/. Default thickness, curv, sulc, area, each only if present.

  • annotations (tuple[str, ...] | list[str] | None) – Parcellations from label/ (aparc, aparc.a2009s, aparc.DKTatlas…). Default aparc if present. Stored as int32 codes; the names and colours go in the header’s label table.

  • hemispheres (tuple[str, ...] | list[str] | None) – lh/rh (or left/right). Default: both, whichever exist.

  • space (str) – "auto" (scanner RAS when c_ras is known from a valid surface footer or mri/orig.mgz, else surface RAS), "scanner" (require c_ras) or "surface" (leave FreeSurfer’s coordinates untouched).

Returns:

The surface-store summary plus subject, c_ras and c_ras_source ("surface footer", "mri/orig.mgz"… or None).

Raises:

IngestError – If the directory is not FreeSurfer output, a requested file is missing, space="scanner" is asked for without c_ras, or the hemispheres record different c_ras.

Return type:

dict[str, Any]

CIFTI

Attach CIFTI-2 surface data to an existing cortical surface store.

CIFTI is how HCP-style pipelines ship results: one .dscalar.nii holds myelin, thickness and curvature for both hemispheres; a .dlabel.nii holds a parcellation such as the HCP multi-modal atlas; a .dtseries.nii holds a resting-state run. None of them carry geometry – they index the vertices of a surface the analyst already has, which is exactly what a surface store is for. So CIFTI is an attach, not an ingest: build the store from the GIFTI or FreeSurfer surfaces first, then add CIFTI maps onto it.

How values find their vertex

A CIFTI brain-model axis lists, per structure, the SOURCE vertex numbers it has data for. Cortex rarely covers every vertex: the medial wall is left out, so a 32k fs_LR hemisphere has 32,492 vertices but about 29,700 values. Each value’s key is surface_keys(hemisphere, vertex), the same key the surface store stamped on every vertex when it was written, and the streaming join in attach_attributes() does the rest. Vertices with no value – the medial wall – get NaN (scalars) or -1 (labels).

Subcortical voxels in the same file have no vertex to land on and are skipped; the summary reports how many.

Requires nibabel:

pip install 'zarr-vectors-tools[surfaces]'
zarr_vectors_tools.convert.ingest.cifti.CIFTI_SUFFIXES: tuple[str, ...] = ('.dscalar.nii', '.dlabel.nii', '.dtseries.nii')

Dense CIFTI kinds that map values onto surface vertices.

zarr_vectors_tools.convert.ingest.cifti.attach_cifti(store_path, cifti_path, *, name=None, missing='fill', overwrite=False, shard_shape=None)[source]

Attach a dense CIFTI file’s cortical maps to a surface store.

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

  • cifti_path (str | Path) – A .dscalar.nii, .dlabel.nii or .dtseries.nii.

  • name (str | None) – Attribute name. For a time series or a single map it names the one attribute written (default: from the filename). For a multi-map dscalar it keeps the maps together as one (V, M) attribute under this name instead of one attribute per map.

  • missing (str) – "fill" (default) gives vertices without a value – the medial wall, a hemisphere the file lacks – NaN or -1; "error" refuses the attach instead.

  • overwrite (bool) – Replace attributes that already exist.

  • shard_shape (int | tuple[int, ...] | None) – Passed to attach_attributes().

Returns:

The attach summary plus attributes, kind, hemispheres (values per hemisphere), skipped_structures and voxels_skipped.

Raises:

IngestError – If the store is not a surface store, the file’s mesh resolution differs from the store’s, or it has no cortical data for the store’s hemispheres.

Return type:

dict[str, Any]

Note

Attributes are written to level 0. Attach before building a pyramid, or rebuild it afterwards so coarse levels carry the maps.

zarr_vectors_tools.convert.ingest.cifti.is_cifti_path(path)[source]

Whether path names a dense CIFTI file this module can attach.

Parameters:

path (str | Path)

Return type:

bool

Graphs

GraphML

Ingest graphs from GraphML files into zarr vectors.

Requires networkx: pip install 'zarr-vectors-tools[graph]'. 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]

Edge list

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 and dropped_edges_missing_node: the edges dropped because an endpoint is not in the node table. When that is not zero it also warns, and warnings says so.

Raises:

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

Return type:

dict[str, Any]

Running ingests

Parallel executors

Executors for the parallel ingest and pyramid paths.

Pass one as executor= to an ingest or to build_pyramid():

from zarr_vectors_tools.parallel import process_pool_executor

with process_pool_executor(8) as ex:
    build_pyramid("cells.zv", factors=[(2, 2)], executor=ex)

process_pool_executor needs nothing beyond the standard library; dask_executor needs the parallel extra. Both are what zvtools --workers N [--workers-backend dask] uses.

zarr_vectors_tools.parallel.dask_executor(workers=None)[source]

Context manager yielding an executor(func, items) callable backed by a local Dask cluster of workers process workers (default: cores-1).

Usage:

with dask_executor(12) as ex:
    run_ingest(..., executor=ex)

Requires the parallel extra (pip install 'zarr-vectors-tools[parallel]').

Parameters:

workers (int | None)

zarr_vectors_tools.parallel.process_pool_executor(workers=None)[source]

Context manager yielding an executor(func, items, shared) callable backed by ONE stdlib concurrent.futures.ProcessPoolExecutor of workers processes (default: cores-1). No extra dependency.

Usage:

with process_pool_executor(8) as ex:
    build_pyramid(..., executor=ex)

One pool for the life of the context. It used to open a fresh pool for every distinct shared payload – one per phase, three phases per pyramid level – and keep them all open until the context closed, so a five-level TRK run with --workers 12 spawned the interpreter (and re-imported numpy, zarr and this package) some 200 times and held every idle worker’s memory to the end. Spawn is what Windows and macOS use, and at a second or two per process it was a visible share of a small run and the largest resident-memory item of a large one.

shared still reaches each worker ONCE per phase rather than being re-pickled into every task: the coordinator writes it to a temp file and tags every task with a token; a worker loads the file the first time it sees the token and keeps the payload until the token changes. The coarseners’ shared payload carries a per-object keep mask, so sending it per task pushed tens of gigabytes through the pipe on a 5M-object store.

Suitable for the coarsener’s per-chunk workers, which already write their cells with record_presence=False and rely on a coordinator manifest rebuild.

An exception leaving the context – Ctrl-C included – stops the pool at once: queued tasks are cancelled and the workers terminated, then the exception propagates. A plain shutdown would wait for every queued task to finish first, which on a large ingest is the rest of the run.

Parameters:

workers (int | None)

Virtual stores

A file read as a store on request, without converting it. zvtools virtual serve serves these; see Visualise in Neuroglancer.

Virtual zarr-vectors stores: a standard file read as a zarr-vectors store on demand, without converting it.

The file is read once and binned into spatial cells; every key of the store (zarr.json, 0/vertices/c/1/0/2, …) is then made when asked. The layout matches, chunk for chunk, the one the browser makes from the same file (ngplatform’s Zarr Vectors plugin reads local tractograms this way), and is a valid format 0.10.0 store (zarr_vectors.validate(level=3)).

Tractograms (TrackVis .trk, MRtrix .tck, .trx), meshes (.obj by object, .stl, .ply, GIFTI .gii and FreeSurfer surfaces such as lh.pial, anatomical ones in scanner RAS), SWC neurons (skeletons, one object per tree; folder/@all.swc reads every SWC file in a folder as one store) and point tables (.csv, .tsv, .xyz):

from zarr_vectors_tools.virtual import open_virtual
store = open_virtual("tracts.trk")
store.get("zarr.json"), store.list("0/object_attributes/")

zvtools virtual serve tracts.trk serves them over HTTP to any Neuroglancer with the zarr-vectors data source (ranges, CORS and folder listings included).

class zarr_vectors_tools.virtual.CellStore(kind, positions, object_rows, vertex_attributes, object_columns, links, unit, name, cells_across=None, text_columns=())[source]

Bases: object

Points or a skeleton in one cell, as a read-only zarr-vectors store.

Reads with get(key), list(prefix) and keys().

__init__(kind, positions, object_rows, vertex_attributes, object_columns, links, unit, name, cells_across=None, text_columns=())[source]
get(key)[source]
Parameters:

key (str)

keys()[source]
list(prefix)[source]
Parameters:

prefix (str)

class zarr_vectors_tools.virtual.MeshStore(path, name=None)[source]

Bases: object

A mesh file as a read-only zarr-vectors mesh store.

Reads with get(key), list(prefix) and keys().

Parameters:
  • path (str | Path)

  • name (str | None)

__init__(path, name=None)[source]
Parameters:
get(key)[source]
Parameters:

key (str)

keys()[source]
list(prefix)[source]
Parameters:

prefix (str)

class zarr_vectors_tools.virtual.StreamlineStore(tractogram, name=None)[source]

Bases: object

A tractogram as a read-only zarr-vectors store: get(key) and list(prefix).

Parameters:
__init__(tractogram, name=None)[source]
Parameters:
  • tractogram (Tractogram)

  • name (str | None)

get(key)[source]
Parameters:

key (str)

Return type:

bytes | None

keys()[source]

Every key of the store.

list(prefix)[source]

Names in a directory (”” or ending in “/”), sub-directories ending in “/”.

Parameters:

prefix (str)

Return type:

list[str] | None

zarr_vectors_tools.virtual.cell_size(extent)[source]

A round cell size, mm, giving about 10 cells across extent.

Parameters:

extent (float)

Return type:

float

zarr_vectors_tools.virtual.fragment_index(counts)[source]

fragment_index_v1 for fragments that are all ranges tiling the cell’s rows.

Return type:

bytes

zarr_vectors_tools.virtual.open_point_file(path, name=None)[source]
Parameters:
Return type:

CellStore

zarr_vectors_tools.virtual.open_tck(path, per_batch=100000)[source]
Parameters:
Return type:

Tractogram

zarr_vectors_tools.virtual.open_tractogram(path)[source]

A .trk, .tck or .trx, by its extension.

Parameters:

path (str | Path)

Return type:

Tractogram

zarr_vectors_tools.virtual.open_trk(path, per_batch=100000)[source]
Parameters:
Return type:

Tractogram

zarr_vectors_tools.virtual.open_trx(path, per_batch=100000)[source]
Parameters:
Return type:

Tractogram

zarr_vectors_tools.virtual.open_virtual(path)[source]

A file as a virtual zarr-vectors store, read once now.

Parameters:

path (str | Path)

Return type:

StreamlineStore | MeshStore | CellStore

zarr_vectors_tools.virtual.parse_point_table(text)[source]

Positions (float64, n x 3), the other numeric columns, and the unit.

The other columns are [(name, float32 values)]; the unit is set if the names say it.

Parameters:

text (str)

zarr_vectors_tools.virtual.parse_swc(text)[source]

Nodes (id, type, position, radius, parent).

Short lines are skipped; a node whose parent is not in the file is a root.

Parameters:

text (str)

Return type:

list[dict]

zarr_vectors_tools.virtual.parse_swc_collection(text)[source]

Several SWC files as one (a folder’s @all.swc): each file’s text after a # @file <name> line, its ids numbered apart. Files that do not parse are left out. Returns (nodes, file names, each node’s file index, skipped names).

Parameters:

text (str)

zarr_vectors_tools.virtual.point_store(positions, columns, unit, name)[source]

A point table: each point an object, the other columns its values.

Points are objects up to MAX_POINT_OBJECTS.

Parameters:

name (str)

Return type:

CellStore

zarr_vectors_tools.virtual.skeleton_store(nodes, name, files=None)[source]

An SWC file’s trees: one object each, its nodes depth-first from the root.

Parameters:
Return type:

CellStore

Serves virtual zarr-vectors stores over HTTP, for any Neuroglancer with the zarr-vectors data source: http://host:port/<file name>/|zarr-vectors:.

Byte ranges, CORS and HTML folder listings (which Neuroglancer’s http store reads, for object attribute columns) are answered.

zarr_vectors_tools.virtual.serve.make_handler(stores)[source]
Parameters:

stores (dict)

zarr_vectors_tools.virtual.serve.serve(paths, host='127.0.0.1', port=8000)[source]

Opens each file (reading it once) and serves them until interrupted.

Parameters:
Return type:

None