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— writeattributes["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'¶
delimitervalue 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:
output_path (str | Path) – Path for output Zarr Vectors store.
chunk_shape (tuple[float, ...]) – 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 (ndarray | None) – Optional
(N,)integer array of per-vertex object IDs. Required forper_object_vertex_count.auto_detect_columns (bool) – If True and
position_columnsis None, detectx/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"]. Requiresscipy.per_object_vertex_count (bool | None) – Write per-object vertex counts to
object_attributes["vertex_count"].None(default): wheneverobject_idsis given;Truerequires it.
- 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:
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_keyattribute, 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.loadtxtpath 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).
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, pluscolumns_attached.- Raises:
IngestError – If the file or the named columns cannot be read.
- Return type:
- 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 (tuple[float, ...]) – 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_keyattribute 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 (tuple[float, ...] | 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_countand each fragment’ssegment_idare 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(), pluscolumns_stored,dropped_naandindex_stored.- Raises:
IngestError – If the file or the named columns cannot be read.
- Return type:
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:
obscolumns. 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 theH5ADHeaderso export can rebuild thepandas.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 fromXor fromlayers[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
obscolumns from an.h5adinto a store.The store is modified in place. Cells are matched on the join key, so the
.h5adneeds 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. NeitherXnor the unusedobscolumns are read in full.- Parameters:
store_path (str | Path) – Zarr Vectors store to add attributes to.
genes (list[str] | None) –
varnames (or symbols, seegene_by) to stage in.layer (str | None) – Read expression from
layers[layer]instead ofX.gene_by (str | None) –
varcolumn to matchgenesagainst. Default tries thevarindex first, thengene_symbol— so Ensembl IDs and gene symbols both work without the caller converting.key_obs_column (str | None) –
obscolumn holding the join key. Default is theobsindex, 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, plusgenes_attachedandobs_columns_attached.- Raises:
IngestError – If the file, keys, genes or columns cannot be resolved.
- Return type:
- 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
.h5adfile into a Zarr Vectors point cloud store.- Parameters:
output_path (str | Path) – Path for the output Zarr Vectors store.
chunk_shape (tuple[float, ...]) – Spatial chunk size per dimension. Must have one entry per spatial dimension (2 for a 2D embedding, 3 for 3D).
bin_shape (tuple[float, ...] | None) – Optional intra-chunk sub-binning.
dtype (str) – Dtype for position data.
spatial_key (str) –
obsmkey holding the coordinates."auto"(default) triesspatial,X_spatial,spatial_fov,X_umap,X_tsne,X_pcain 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) –
obscolumns to store as vertex attributes. Default (None) stores every column; pass[]for none.genes (list[str] | None) –
varnames 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 ofadata.X.object_id_column (str | None) –
obscolumn 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
Xon disk. Worth it for large files whengenesselects few columns;obs/obsmare 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
obsrow 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
obsindex as thezv_join_keyattribute, so further files covering the same cells can be staged in later withattach_h5ad()orattach_table().preserve_obs_index (bool) – Inline the
obsindex (cell barcodes) into the stored header so export can restoreobs_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. Requiresscipy.per_object_vertex_count (bool | None) – Store per-object cell counts as
object_attributes["vertex_count"].None(default): wheneverobject_id_columnis set;Truerequires it. With objects, each fragment’ssegment_idis written too (see_object_columns).
- Returns:
Summary dict from
write_points(), plusspatial_key,n_obs,n_vars,obs_columns_stored,genes_stored,obs_index_storedanddropped_na.- Raises:
IngestError – If
anndatais missing, the file is unreadable, or the requested keys/columns/genes do not exist.- Return type:
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 ofkeys.keys (Any | None) –
(M,)join keys for the rows ofvalues. Strings are hashed viahash_keys(). When None, the store’skey_attributeis treated as a direct row index intovalues— 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
keysis None).missing (str) –
"fill"(default) writesfill_valuefor vertices absent from the incoming file;"error"raises instead.fill_value (Any) – Value for unmatched vertices. Defaults to NaN for float attributes and
-1for 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_keysandsharded.- Raises:
IngestError – If the store, level or key attribute is missing, the shapes disagree, or
missing="error"and a vertex is unmatched.- Return type:
- zarr_vectors_tools.convert.ingest.attach.hash_keys(keys)[source]¶
Reduce join keys to a stable
int64array.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
S39column or anS64one — otherwise two files describing the same cells would refuse to join.
- 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 intoXrather thanobs— 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:
obs_names (dict[str, str] | None) – Attribute name -> original
obscolumn 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:
output_path (str | Path) – Path for the output Zarr Vectors store.
chunk_shape (tuple[float, ...]) – 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 (ndarray | None) – Optional
(N,)integer array of per-vertex object IDs. Required forper_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"]. Requiresscipy.per_object_vertex_count (bool | None) – Write per-object vertex counts to
object_attributes["vertex_count"].None(default): wheneverobject_idsis given;Truerequires it. With objects, each fragment’ssegment_idis written too (see_object_columns).
- Returns:
Summary dict from
write_points().- Raises:
IngestError – If laspy is not installed or the file is unreadable.
- Return type:
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:
output_path (str | Path) – Path for the output Zarr Vectors store.
chunk_shape (tuple[float, ...]) – 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 (ndarray | None) – Optional
(N,)integer array of per-vertex object IDs. Required forper_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"]. Requiresscipy.per_object_vertex_count (bool | None) – Write per-object vertex counts to
object_attributes["vertex_count"].None(default): wheneverobject_idsis given;Truerequires it. With objects, each fragment’ssegment_idis written too (see_object_columns).
- Returns:
Summary dict from
write_points().- Raises:
IngestError – If plyfile is not installed, the file has no vertex element, or reading fails.
- Return type:
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:
output_path (str | Path) – Path for the output zarr vectors store.
chunk_shape (tuple[float, ...]) – Spatial chunk size per dimension (3D).
bin_shape (tuple[float, ...] | 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 asdropped_by_length.
- Returns:
Summary dict from
write_polylines(), plus any enrichment counters such asdropped_by_length.- Raises:
IngestError – If nibabel is not installed or the file is unreadable.
- Return type:
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
- 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:
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_partsand 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 exactlyn_vertices * ndim * itemsizebytes, 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. Seezarr_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_endpointsare folded in aslength/endpoints.vertex_countis 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 undervertex_attributes/<name>and carried through the pyramid to every level.attr_seed (int) – Seed for the
randomvertex 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_rasaffine 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 perpyramid_factorsentry. None (default) derives each from the level’s bin. Refused, before anything is read, in “decimate” mode, withoutbuild_multiscale, or when the count does not match. Seezarr_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. Needsintermediate_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:
- 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), ...], seedecode_trk_names()), vox_to_ras (4×4 float32 array), voxel_order (str), n_count, version, hdr_size.
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’slabel_iddetermines which group it belongs to. Integral floating-point label IDs are accepted and converted toint64.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_idattribute and the LUT.- Parameters:
output_path (str | Path) – Path for the output zarr vectors store.
chunk_shape (tuple[float, ...]) – 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 (tuple[float, ...] | 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"]andobject_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 asdropped_by_length.
- Returns:
Summary dict from
write_polylines(), plus any enrichment counters such asdropped_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. Whenmapping_pathis 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:
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:
output_path (str | Path) – Path for the output zarr vectors store.
chunk_shape (tuple[float, ...]) – 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.
- Returns:
Summary dict from
write_polylines(), plus any enrichment counters such asdropped_by_length.- Raises:
IngestError – If nibabel is not installed or the file is unreadable.
- Return type:
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→verticesoffsets→ vertex group boundariesdpv/*→attributes/*(per-vertex)dps/*→object_attributes/*(per-streamline)groups/*→groupingsdpg/*→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 (tuple[float, ...]) – 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.
- Returns:
Summary dict from
write_polylines(), plus any enrichment counters such asdropped_by_length.- Raises:
IngestError – If trx-python is not installed or the file is unreadable.
- Return type:
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 * ndimcolumns hold endpoint coordinates in(x0, y0, z0, x1, y1, z1)order. Remaining columns are treated as per-line attributes (or filtered toattribute_columnswhen supplied).- Parameters:
output_path (str | Path) – Path for the output Zarr Vectors store.
chunk_shape (tuple[float, ...]) – 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.
- Returns:
Summary dict from
write_lines(), plus enrichment counters.- Raises:
IngestError – If the file is missing or unparseable.
- Return type:
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:
output_path (str | Path) – Path for the output zarr vectors store.
chunk_shape (tuple[float, ...]) – 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.
- Return type:
Each tree is one object, and
object_attributes/segment_idnumbers them from 1 in root order, the id precomputed export andzvtools synapsesuse; each fragment carries itsobject_idandsegment_idtoo, which the skeleton pyramid groups by.- Returns:
Summary dict from
write_graph().- Parameters:
- Return type:
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
spatial_indexblock →precomputed_skeletons.run_ingest(), one.fragschunk at a time. Level-0 chunks are the spatial index’s own, sochunk_shapeis not needed. Withoutanchorevery.fragsfile in the layer is listed and ingested; with it, just the block it names.no spatial index →
precomputed_plain_skeletons.run_ingest_plain(), one read per segment. There is no source grid to inherit, sochunk_shape(in the layer’s units, nanometres) is required.a mesh layer (legacy or multi-resolution) →
precomputed_meshes.ingest_precomputed_meshes(), one object per segment.chunk_shapeis required, and the pyramid is built afterwards withbuild_pyramid(), as for any other mesh store.
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.fragsgrid.run_ingestaligns 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.
- 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:
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
.fragsfiles (spatial index).anchor (Sequence[int] | None) – Voxel corner of one
.fragschunk; ingest the block ofcountschunks 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
executorisNone.executor (Any) – A
map-like(func, items, shared)callable.progress (bool) – Print progress.
chunk_scale_factors (Sequence[int | tuple[int, ...]] | None)
sparsity_strategy (str)
drop_interior_below (int)
- Return type:
The stride, sparsity and
drop_interior_belowoptions build a skeleton pyramid inside the ingest, andworkers/executorrun it; a mesh layer refuses them, since its pyramid is built afterwards.- Returns:
The ingester’s summary, plus
layer("spatial_index"or"plain") andbounds_nmwhen known. For a mesh layer,precomputed_meshes.ingest_precomputed_meshes()’s summary, whoselayeris the URL read.- Parameters:
- Return type:
- zarr_vectors_tools.convert.ingest.precomputed.is_url(source)[source]¶
Does
sourcename a remote (orfile://) location, not a local path?
- zarr_vectors_tools.convert.ingest.precomputed.layer_kind(info)[source]¶
"mesh"or"skeleton"for aninforead_layer_info()accepted.
- 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 becomesfile://plus its absolute POSIX path – the spelling both libraries accept on Windows as well.
- zarr_vectors_tools.convert.ingest.precomputed.list_frag_keys(url, frags_dir='')[source]¶
Every
.fragskey infrags_dir(non-recursive), sorted.
- 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
infopoints at: the volume’s voxels are not converted, and which of its layers to read is the caller’s choice.
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):
Extract one
.fragschunk →{segment_id: piece}(PrecomputedFragsReader, cloud-volume + mapbuffer).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.Reduce the records into a segment-id-preserving object index (
build_object_index).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:
objectOffline reader for tests: holds
{key: {seg_id: piece}}.
- class zarr_vectors_tools.convert.ingest.precomputed_skeletons.PrecomputedFragsReader(base_url, *, frags_dir='')[source]¶
Bases:
objectRead
.fragschunks from a precomputed skeleton layer.Requires the optional
ingestextras (cloud-volume,mapbuffer,cloud-files).
- 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:
objectSpatial-index geometry of a precomputed skeleton layer.
- Parameters:
- __init__(base_url, resolution_nm, chunk_size_nm, vertex_attributes=<factory>, bounds_nm=None, frags_dir='')¶
- zarr_vectors_tools.convert.ingest.precomputed_skeletons.enumerate_frag_keys(info, anchor_voxel, counts)[source]¶
Enumerate a block of
.fragskeys from an anchor corner.anchor_voxelis one valid chunk’s voxel start (e.g. from a known filename);countsis the per-axis number of chunks. Keys step bychunk_size_voxelsper axis. Avoids bucket-wide listing for test cutouts.
- zarr_vectors_tools.convert.ingest.precomputed_skeletons.frag_key(info, voxel_start)[source]¶
Build a
.fragsfilename from a per-axis voxel start corner.<x0>-<x1>_<y0>-<y1>_<z0>-<z1>.fragswherex1 = x0 + chunk_size_voxels(matches igneousSpatialIndexnaming).- Parameters:
info (SkeletonInfo)
- Return type:
- zarr_vectors_tools.convert.ingest.precomputed_skeletons.main(argv=None)[source]¶
python -m zarr_vectors.ingest.precomputed_skeletonsCLI.Ingests a rectangular block of
.fragschunks (anchored at a known chunk’s voxel corner) into a multiscale zarr-vectors skeleton store.
- zarr_vectors_tools.convert.ingest.precomputed_skeletons.parse_frag_key(key)[source]¶
Parse a
.fragskey back to its per-axis voxel start corner.[dir/]x0-x1_y0-y1_z0-z1.frags→(x0, y0, z0).
- 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
.fragschunk 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_cellthis 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)wherecross_edgesis a list of(gid_child, gid_parent)and each emitted piece carries an"anchors"map{gid: local_vertex_index}for its endpoints.
- 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) andread_chunk(key).keys (Iterable[str]) –
.fragskeys 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_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:
- 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_countat 0, and a viewer budgets levels by it. Summed from each chunk’s fragment index, which is kilobytes per chunk, not from the vertices.
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:
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.
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.
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.Write – write each zarr chunk with
write_skeleton_chunk().Object index – build the segment-id → dense-OID map and fragment manifests via
build_object_index.Segment properties → object attributes – convert the precomputed inline property table to per-object zarr-vectors arrays (
write_object_attributes).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:
objectRead plain (non-
.frags) precomputed skeleton segments.Each skeleton is fetched individually via the cloud-volume library. Requires the optional
ingestextras (cloud-volume,cloud-files).- Parameters:
base_url (str) – Layer URL, e.g.
"precomputed://gs://allen_neuroglancer_ccf/Mouselight".
- 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
Noneif the segment has no skeleton in the store.
- class zarr_vectors_tools.convert.ingest.precomputed_plain_skeletons.PlainSkeletonInfo(base_url, transform, vertex_attributes=<factory>, seg_props_path=None, sharding=None)[source]¶
Bases:
objectMetadata parsed from a plain precomputed skeleton
infofile.- Parameters:
- __init__(base_url, transform, vertex_attributes=<factory>, seg_props_path=None, sharding=None)¶
- 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¶
stored_nm = transform @ [x, y, z, 1].- Type:
4×4 float64 homogeneous affine
- zarr_vectors_tools.convert.ingest.precomputed_plain_skeletons.parse_segment_properties(inline)[source]¶
Parse the
inlineblock of a segment-propertiesinfofile.- Parameters:
inline (dict[str, Any]) – The
inlinevalue from the segment-propertiesinfoJSON — must contain"ids"and"properties"keys.- Returns:
seg_idsis a sorted list ofintsegment IDs.propsis a dict mappingprop_id → (type, values, meta)where:typeis the precomputed property type string ("label","string","description","number","tags").valuesis a list of raw values aligned withseg_ids.metais 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.fragsspatially- indexed chunk files. Instead it:Reads all (or a subset of) skeletons
batch_sizeat a time, in parallel usingread_workersthreads, spilling each batch to scratch disk so memory holds one batch rather than the dataset.Computes bounds from the vertex data if
bounds_nmis not supplied.Distributes vertices across zarr chunks, preserving cross-chunk connectivity via the standard
pieces_from_chunk()mechanism, and writes each chunk from its spilled pieces.Writes the zarr-vectors store, object index, and segment-property-based object attributes.
Builds a multi-LOD pyramid if
stridesis non-empty.
- Parameters:
reader (PlainPrecomputedReader) – A
PlainPrecomputedReader(or any object exposing.info(PlainSkeletonInfo) and.read_skeleton(seg_id),.segment_ids,.segment_properties_raw).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. IfNone, 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, orexecutorwhen given.executor (Any) – A
map-like(func, items, shared)callable for the pyramid build, used whenpyramid_workersis 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 optionallypyramid.- Return type:
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_countandsynapse_post_count;the synapse store’s objects carry the same
segment_idattribute (0 for the object holding unmatched synapses), soSegmentLinkfinds 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 whenpyarrowis installed.skeleton_store (str | Path) – A store with
object_attributes/segment_idat level 0, as the precomputed skeleton ingesters write.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;
Nonewhen 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_countto 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, orNone) and the point writer’s own counts.- Raises:
IngestError – For a skeleton store without segment ids, a table missing a named column, an unknown
sideorunmatched, or unmatched synapses withunmatched="error".- Return type:
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:
output_path (str | Path) – Path for the output zarr vectors store.
chunk_shape (tuple[float, ...]) – 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 inOBJHeader.object_names.
- Returns:
Summary dict from
write_mesh().- Return type:
- 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_meshwrites Draco-encoded chunks, butread_meshhas 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 withinmerge_tolerance.- Parameters:
output_path (str | Path) – Path for the output zarr vectors store.
chunk_shape (tuple[float, ...]) – 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.
- Returns:
Summary dict from
write_mesh().- Return type:
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>:0JSON manifest naming fragment files, each a vertex count,float32vertices anduint32triangles. One level of detail.neuroglancer_multilod_draco: a<segment id>.indexmanifest and a<segment id>file of Draco-encoded fragments, several levels of detail.the same,
sharded: manifests and fragments packed into.shardfiles.
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 behindprecomputed://) or a local directory. Not the segmentation layer above it.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
infonames 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 atlod),vertex_count,face_count,vertices_welded,faces_droppedandproperties, pluswrite_mesh()’s own.- Raises:
FileNotFoundError – No
infoatsource.ValueError –
sourceis not a mesh layer, a segment asked for has no mesh,lodis out of range, or nothing is left to write.
- Return type:
- 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
.shardfile.
- zarr_vectors_tools.convert.ingest.precomputed_meshes.mesh_layout(info)[source]¶
"legacy","multilod"or"multilod_sharded"for a meshinfo.
- zarr_vectors_tools.convert.ingest.precomputed_meshes.mesh_source(url)[source]¶
A cloud-volume mesh source for the mesh directory at
url.PrecomputedMeshSource.from_cloudpathdoes not build its configuration with every argument cloud-volume 12 requires, so the source is assembled here the way the skeleton source’sfrom_cloudpathdoes it.
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
POINTSETarray is a surface; one with aLABELarray 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.
GeometricTypefirst for the shapes that are not anatomy (inflated, sphere, flat), because HCP writes an inflated surface withAnatomicalStructureSecondary=MidThickness– it was inflated FROM the midthickness – and reading that field first would chunk a balloon. Then the filename, thenAnatomicalStructureSecondary.
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:
objectOne classified GIFTI file.
- __init__(path, kind, hemisphere, surface, image=None)¶
- zarr_vectors_tools.convert.ingest.gifti.SPACES = ('auto', 'scanner', 'surface')¶
spacevaluesingest_gifti()takes, asingest_freesurferdoes.
- zarr_vectors_tools.convert.ingest.gifti.classify_gifti(path)[source]¶
Read one GIFTI file and say what it is.
- 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
.giifiles, a list of files, or a single surface file.chunk_shape (tuple[float, ...]) – Spatial chunk size in mm (e.g.
(20, 20, 20): a whole cortex is roughly 140 x 180 x 120 mm).bin_shape (tuple[float, ...] | None) – Optional intra-chunk sub-binning.
dtype (str) – Position dtype.
geometry (str | None) – Which surface to chunk (
"pial","white"…). Default: the first available ofmidthickness,pial,white,smoothwm,orig. Every other surface of the same hemisphere becomes acoords_<name>attribute.hemisphere (str | None) – Assign every file with no hemisphere information to this one (
"left"/"right"). Only needed for files that carry neitherAnatomicalStructurePrimarynor 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,filledandfiles(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 asurf/path.Returns
Nonewhenpathdoes not look like FreeSurfer output, so callers (the CLI’s format detection) can ask without catching errors.
- 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/andlabel/) or itssurf/directory.bin_shape (tuple[float, ...] | 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,smoothwmororig.alternates (tuple[str, ...] | list[str] | None) – Other surfaces to carry as
coords_<name>. Defaultwhite, pial, inflated, sphere, each only if present; named explicitly, each must exist.morphometry (tuple[str, ...] | list[str] | None) – Per-vertex maps from
surf/. Defaultthickness, curv, sulc, area, each only if present.annotations (tuple[str, ...] | list[str] | None) – Parcellations from
label/(aparc,aparc.a2009s,aparc.DKTatlas…). Defaultaparcif present. Stored as int32 codes; the names and colours go in the header’s label table.hemispheres (tuple[str, ...] | list[str] | None) –
lh/rh(orleft/right). Default: both, whichever exist.space (str) –
"auto"(scanner RAS whenc_rasis known from a valid surface footer ormri/orig.mgz, else surface RAS),"scanner"(requirec_ras) or"surface"(leave FreeSurfer’s coordinates untouched).
- Returns:
The surface-store summary plus
subject,c_rasandc_ras_source("surface footer","mri/orig.mgz"… orNone).- Raises:
IngestError – If the directory is not FreeSurfer output, a requested file is missing,
space="scanner"is asked for withoutc_ras, or the hemispheres record differentc_ras.- Return type:
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.niior.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
dscalarit 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 –NaNor-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_structuresandvoxels_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:
Note
Attributes are written to level 0. Attach before building a pyramid, or rebuild it afterwards so coarse levels carry the maps.
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:
output_path (str | Path) – Path for the output zarr vectors store.
chunk_shape (tuple[float, ...]) – 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
GraphHeadercontaining 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.
- Returns:
Summary dict from
write_graph().- Return type:
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_colandtarget_colcolumns. Extra columns become edge attributes (filterable viaedge_attribute_columns).nodes_path (str | Path) – CSV with at least
node_id_colandposition_columns. Extra columns become node attributes.output_path (str | Path) – Path for the output Zarr Vectors store.
chunk_shape (tuple[float, ...]) – 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_colandtarget_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().
- Returns:
Summary dict from
write_graph(), plus enrichment counters anddropped_edges_missing_node: the edges dropped because an endpoint is not in the node table. When that is not zero it also warns, andwarningssays so.- Raises:
IngestError – For missing files, cuDF errors, or empty results.
- Return type:
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 ofworkersprocess workers (default: cores-1).Usage:
with dask_executor(12) as ex: run_ingest(..., executor=ex)
Requires the
parallelextra (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 stdlibconcurrent.futures.ProcessPoolExecutorofworkersprocesses (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
sharedpayload – 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 12spawned 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.sharedstill 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=Falseand 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:
objectPoints or a skeleton in one cell, as a read-only zarr-vectors store.
Reads with
get(key),list(prefix)andkeys().
- class zarr_vectors_tools.virtual.MeshStore(path, name=None)[source]¶
Bases:
objectA mesh file as a read-only zarr-vectors mesh store.
Reads with
get(key),list(prefix)andkeys().
- class zarr_vectors_tools.virtual.StreamlineStore(tractogram, name=None)[source]¶
Bases:
objectA tractogram as a read-only zarr-vectors store:
get(key)andlist(prefix).- Parameters:
tractogram (Tractogram)
name (str | None)
- zarr_vectors_tools.virtual.cell_size(extent)[source]¶
A round cell size, mm, giving about 10 cells across
extent.
- zarr_vectors_tools.virtual.fragment_index(counts)[source]¶
fragment_index_v1 for fragments that are all ranges tiling the cell’s rows.
- Return type:
- zarr_vectors_tools.virtual.open_virtual(path)[source]¶
A file as a virtual zarr-vectors store, read once now.
- Parameters:
- Return type:
- 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.
- 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.
- 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.
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.