Export¶
zarr_vectors_tools.convert.export: one module per output format. Each
reads a store and writes a file. zvtools convert STORE FILE calls these.
CSV / XYZ points¶
Export Zarr Vectors point clouds to CSV/XYZ text files.
- zarr_vectors_tools.convert.export.csv_points.export_csv(store_path, output_path, *, level=0, bbox=None, object_ids=None, chunks=None, delimiter=None, header=None, attribute_names=None, vertex_budget=4000000)[source]¶
Export a Zarr Vectors point cloud to a CSV file.
The level is read and written a batch of chunks (or objects) at a time, so memory holds one batch whatever the level’s size; the file is the same as a whole-level read would give.
The position columns are named as the source file named them when the store recorded it (a CSV’s header, a table’s coordinate columns), else after the store’s axes (
x, y, z). A dictionary-encoded attribute (a category column from a table or.h5ad) is written as its labels.- Parameters:
level (int) – Resolution level to export.
bbox (tuple[NDArray[floating], NDArray[floating]] | None) – Optional bounding box filter.
chunks (list[tuple[int, ...]] | None) – Optional whitelist of chunk coordinate tuples; only data stored in those chunks is exported. AND-ed with
bboxandobject_ids.delimiter (str | None) – Column delimiter;
"whitespace"writes one space. Default: a space for a.xyzoutput, else a comma.header (bool | None) – Whether to write a header row. Default: yes, except for a
.xyzoutput, which by convention has none.attribute_names (list[str] | None) – Attributes to include. None = positions only.
vertex_budget (int) – Points to aim for per batch.
- Returns:
Summary dict with
vertex_count.- Raises:
ExportError – If export fails.
- Return type:
PLY¶
Export Zarr Vectors point clouds to PLY files.
Requires the plyfile package: pip install 'zarr-vectors-tools[ply]'.
- zarr_vectors_tools.convert.export.ply.export_ply(store_path, output_path, *, level=0, bbox=None, object_ids=None, chunks=None, attribute_names=None, binary=True, vertex_budget=4000000)[source]¶
Export a Zarr Vectors point cloud to a PLY file.
PLY states its vertex count in the header, before the data, so the vertices are written a batch at a time to a scratch file beside the output, counted, and the header written in front of them. Memory holds one batch whatever the level’s size.
- Parameters:
level (int) – Resolution level to export.
bbox (tuple[NDArray[floating], NDArray[floating]] | None) – Optional bounding box filter.
chunks (list[tuple[int, ...]] | None) – Optional whitelist of chunk coordinate tuples; only data stored in those chunks is exported. AND-ed with
bboxandobject_ids.attribute_names (list[str] | None) – Attributes to include. A float64 attribute (a LAS
gps_time, say) is written as adoubleproperty, every other one asfloat.binary (bool) – Write binary PLY (default) or ASCII.
vertex_budget (int) – Points to aim for per batch.
- Returns:
Summary dict with
vertex_count.- Raises:
ExportError – If plyfile is not installed or export fails.
- Return type:
AnnData (h5ad)¶
Export Zarr Vectors point clouds to AnnData .h5ad files.
The inverse of zarr_vectors_tools.convert.ingest.h5ad: positions become
obsm[spatial_key], per-vertex attributes become obs columns, and
attributes that were ingested as gene expression are rebuilt into X
with the matching var_names.
When the store carries an
H5ADHeader (any store written
by this package’s h5ad ingest does), the original column labels, gene
names, categorical levels, cell barcodes and row order are all restored.
Without one, the export still works — every attribute becomes a numeric
obs column under its stored name.
Requires the anndata package:
pip install 'zarr-vectors-tools[h5ad]'
- zarr_vectors_tools.convert.export.h5ad.export_h5ad(store_path, output_path, *, level=0, bbox=None, object_ids=None, chunks=None, attribute_names=None, spatial_key=None, restore_order=True, decode_categoricals=True, compression='gzip')[source]¶
Export a Zarr Vectors point cloud to an AnnData
.h5adfile.- Parameters:
level (int) – Resolution level to export.
bbox (tuple[NDArray[floating], NDArray[floating]] | None) – Optional bounding box filter.
chunks (list[tuple[int, ...]] | None) – Optional whitelist of chunk coordinate tuples. AND-ed with
bboxandobject_ids.attribute_names (list[str] | None) – Attributes to export. Default (None) exports every attribute present at
level; pass[]for positions only.spatial_key (str | None) –
obsmkey to write the positions under. Defaults to the key recorded in the store header, else"spatial".restore_order (bool) – Sort cells back into their original
obsorder using the row-index attribute recorded at ingest. Silently skipped when that attribute is absent or was filtered out.decode_categoricals (bool) – Rebuild
pandas.Categoricalobs columns from their integer codes using the header’s category labels.compression (str | None) – HDF5 compression for the output (“gzip”, “lzf”, or None).
- Returns:
Summary dict with
vertex_count,n_vars,obs_columns,spatial_keyandorder_restored.- Raises:
ExportError – If
anndatais missing, the store cannot be read, or a requested attribute is not stored atlevel.- Return type:
TrackVis TRK¶
Export zarr vectors streamlines to TrackVis TRK format.
Requires nibabel: pip install 'zarr-vectors-tools[trk]'.
- zarr_vectors_tools.convert.export.trk.export_trk(store_path, output_path, *, level=0, object_ids=None, group_ids=None, chunks=None, affine=None, attribute_names=None, object_attribute_names=None)[source]¶
Export zarr vectors streamlines to a TRK file.
Writes back what the ingest kept: per-vertex attributes as TRK scalars, per-object attributes as TRK properties, and the reference image (
vox_to_ras, voxel size, dimensions, voxel order) from the store’s TRK header. Positions are converted from the space the store holds them in, so a store ingested in TrackVis voxel millimetres and one registered to RAS both write a file that loads in the same place.- Parameters:
level (int) – Resolution level to export.
chunks (list[tuple[int, ...]] | None) – Optional whitelist of chunk coordinate tuples. Filters at the segment level: only vertex groups stored in listed chunks are emitted, and each surviving contiguous run is written as its own streamline. The output
streamline_countcan therefore exceed the source object count.affine (ndarray | None) – 4×4 voxel-to-RAS affine for a store with no TRK header, with the positions taken as voxel coordinates. When given it overrides the stored header;
None(default) uses the header, or the identity when there is none.attribute_names (Sequence[str] | None) – Per-vertex attributes to write as scalars.
None(default) writes every numeric one;[]writes none.object_attribute_names (Sequence[str] | None) – Per-object attributes to write as properties, with the same
None/[]meaning.
- Returns:
Summary dict with
streamline_count,vertex_count,attributes_carried,object_attributes_carried,space(of the stored positions) andattributes_skipped(non-numeric attributes left out, when there were any).- Raises:
ExportError – If nibabel is not installed, a requested attribute is missing or not numeric, TRK cannot hold what was asked (it takes ten scalar and ten property names of up to 20 characters), or the write fails.
- Return type:
TRX¶
Export zarr vectors streamlines to TRX format.
Requires trx-python: pip install 'zarr-vectors-tools[trx]'.
- zarr_vectors_tools.convert.export.trx.export_trx(store_path, output_path, *, level=0, object_ids=None, group_ids=None, chunks=None, attribute_names=None, object_attribute_names=None)[source]¶
Export zarr vectors streamlines to a TRX file.
Writes what a TRX file can hold beside the positions: per-vertex attributes as
dpv, per-object attributes asdps, the level’s named object groups asgroupswith their group attributes asdpg, and the reference image from the store’s TRX (or TRK) header. TRX positions are RAS millimetres, so a store still in TrackVis voxel millimetres is converted on the way out.- Parameters:
level (int) – Resolution level to export.
group_ids (list[int] | None) – Optional group ID filter. Also limits the groups written to these.
chunks (list[tuple[int, ...]] | None) – Optional whitelist of chunk coordinate tuples. Filters at the segment level: only vertex groups stored in listed chunks are emitted, and each surviving contiguous run is written as its own streamline. The output
streamline_countcan therefore exceed the source object count.attribute_names (Sequence[str] | None) – Per-vertex attributes to write.
None(default) writes every numeric one;[]writes none.object_attribute_names (Sequence[str] | None) – Per-object attributes to write, with the same
None/[]meaning.
- Returns:
Summary dict with
streamline_count,vertex_count,attributes_carried,object_attributes_carried,groups_carried,space(of the stored positions), andattributes_skippedwhen non-numeric attributes were left out.- Raises:
ExportError – If trx-python is not installed, a requested attribute is missing or not numeric, or export fails.
- Return type:
SWC¶
Export zarr vectors skeletons to SWC format.
- zarr_vectors_tools.convert.export.swc.export_swc(store_path, output_path, *, level=0, chunks=None, object_ids=None)[source]¶
Export a zarr vectors skeleton to SWC.
Reconstructs the parent array from the edge list and writes the 7-column SWC format. The
#lines of an ingested SWC come first, then# SWC exported by zarr-vectors. Each tree is written from its root in depth-first order, ids numbered 1.. in that order, so every parent comes before its children and a root’s parent is-1.Without
object_idsthe whole level is one file. With them,output_pathis a directory and each object gets its own single-tree file, named after its segment id when the store has one (EM and SWC skeleton stores do) and its object id otherwise.- Parameters:
output_path (str | Path) – The .swc file to write, or with
object_idsthe directory to write one file per object into.level (int) – Resolution level to export.
chunks (list[tuple[int, ...]] | None) – Optional whitelist of chunk coordinate tuples; only nodes (and intra-chunk edges) in those chunks are exported. Edges spanning a listed and an unlisted chunk are dropped, which can orphan child nodes — each surviving connected piece is still written as a valid SWC tree (with its own root). Whole-level export only.
object_ids (list[int] | None) – Objects to write, one file each.
- Returns:
Summary dict with
node_count,root_countandattributes_carried(the per-vertex columns that came from the store rather than from the defaults). Withobject_idsalsoobject_countandfiles, the paths written in the order asked.- Return type:
Wavefront OBJ¶
Export zarr vectors meshes to Wavefront OBJ format.
- zarr_vectors_tools.convert.export.obj.export_obj(store_path, output_path, *, level=0, bbox=None, object_ids=None, chunks=None)[source]¶
Export a zarr vectors mesh to a Wavefront OBJ file.
- Parameters:
level (int) – Resolution level to export.
bbox (tuple[NDArray[floating], NDArray[floating]] | None) – Optional bounding box filter.
chunks (list[tuple[int, ...]] | None) – Optional whitelist of chunk coordinate tuples; only data stored in those chunks is exported. AND-ed with
bboxandobject_ids. Faces spanning a listed and an unlisted chunk are dropped.
- Returns:
Summary dict with
vertex_count,face_count.- Raises:
ExportError – If export fails.
- Return type:
GIFTI¶
Export a cortical surface store back to GIFTI.
A surface store (written by
ingest_gifti() or
ingest_freesurfer())
goes back out as the set of files Connectome Workbench, FreeView, fMRIPrep
and nilearn read, one directory per store:
out/
hemi-L_midthickness.surf.gii the geometry
hemi-L_pial.surf.gii every alternate surface, same triangles
hemi-L_inflated.surf.gii
hemi-L_thickness.shape.gii morphometry
hemi-L_MyelinMap.func.gii any other continuous map
hemi-L_aparc.label.gii a parcellation, with its label table
... and the same for hemi-R
Every vertex is written in the SOURCE mesh’s numbering (the store’s join key
restores it), so vertex i of every file is vertex i of the files the
store was ingested from, and CIFTI data for that mesh still applies.
File names¶
[<prefix>_]hemi-<L|R>_<name>.<kind>.gii. A BIDS label may only hold
letters and digits, so a name that is not one (aparc.a2009s,
MyelinMap_BC) is written after a dot instead, the way FreeSurfer and HCP
write it: hemi-L.aparc.a2009s.label.gii. Either way
map_name() reads the
attribute name back unchanged, so ingesting the directory again rebuilds the
same store. Any file for which that is not true (a prefix that is not a
BIDS entity combined with a dotted name, say) is listed in the summary’s
warnings.
Which kind of file¶
Surfaces are
.surf.gii: a float32POINTSETand an int32TRIANGLEarray, withGeometricType(Anatomical,Inflated,VeryInflated,Spherical,Flat) and, for the three surfaces Workbench names,AnatomicalStructureSecondary(MidThickness,Pial,GrayWhite).Parcellations – attributes with a label table in the header – are
.label.gii: int32 codes underNIFTI_INTENT_LABELand the table’s names and RGBA colours.Continuous maps are
.shape.giiwithNIFTI_INTENT_SHAPEwhen they describe the shape of cortex, and.func.giiwithNIFTI_INTENT_NONEotherwise, following HCP, which writes thickness, curvature, sulcal depth and areal distortion as shape files and myelin and functional maps as func files.metric_kind()decides, from the file the map was ingested from first and its name second. A CIFTI time series keepsNIFTI_INTENT_TIME_SERIESand itsTimeStep. A map with several columns is one data array per column.
Every file carries AnatomicalStructurePrimary (CortexLeft /
CortexRight, from the CIFTI structure the header records for the
hemisphere), which is how Workbench assigns a file to a hemisphere.
Coordinates¶
Positions are written exactly as the store holds them, in the space its
header records, and that space goes into each anatomical surface’s
coordinate system (scanner as NIFTI_XFORM_SCANNER_ANAT, a GIFTI
dataspace such as talairach as itself). A FreeSurfer store ingested in
scanner RAS therefore exports in scanner RAS, lined up with the T1 and any
tractogram of the subject, which is also how fMRIPrep writes its GIFTI
surfaces. c_ras is not re-applied or removed, and FreeSurfer’s
VolGeom* metadata is deliberately not written: FreeSurfer tools read
those as “these coordinates are surface RAS, add c_ras”, which would
shift scanner-space coordinates a second time. A store kept in FreeSurfer
surface RAS has no NIfTI code for that space and is written as
NIFTI_XFORM_UNKNOWN. Inflated, spherical and flat surfaces are in no
anatomical space and are always written as unknown.
Levels¶
level=0 is the mesh as ingested. A coarser level can be exported too:
it is a decimated mesh with fewer vertices, and its files are consistent
with each other (surfaces, maps and labels share its vertices), but its
vertex numbering is its own – metrics, CIFTI files and label files made
for the full-resolution mesh do not apply to it.
What does not round trip¶
GIFTI holds float32 and int32 only, so a float64 map is written as float32.
Triangles come back as the same set of triangles, with the same winding,
but not necessarily in the source file’s order. The store does not record
a map’s original intent, so a GIFTI time series (other than one attached
from CIFTI) is written as NIFTI_INTENT_NONE.
Requires nibabel:
pip install 'zarr-vectors-tools[surfaces]'
- zarr_vectors_tools.convert.export.gifti.export_gifti(store_path, output_dir, *, level=0, hemispheres=None, surfaces=None, attribute_names=None, prefix=None)[source]¶
Write a cortical surface store as a directory of GIFTI files.
- Parameters:
store_path (str | Path) – A store written by the GIFTI or FreeSurfer ingest.
output_dir (str | Path) – Directory to write into; created if missing. Files of the same name are replaced, and nothing else in it is touched.
level (int) – Resolution level.
0is the mesh as ingested; a coarser level is a decimated mesh with its own vertex numbering.hemispheres (Sequence[str] | str | None) –
left/right(orlh/rh). Default: every hemisphere in the store.surfaces (Sequence[str] | str | None) – Surfaces to write, by name (
"pial") or attribute ("coords_pial"). Default: the geometry and every alternate.attribute_names (Sequence[str] | str | None) – Per-vertex maps and parcellations to write. Default: every vertex attribute at the level except the join key and the surface coordinates.
prefix (str | None) – Leading file-name part, e.g.
"sub-01"givessub-01_hemi-L_pial.surf.gii.
- Returns:
Summary dict with
files(paths written, in order),file_count,hemispheres,geometry,surfaces,scalars,labels,level,space,vertex_countandface_count(summed over hemispheres),skipped({hemisphere: [names]}of maps and surfaces that are only fill on that hemisphere, so were not written) andwarnings.- Raises:
ExportError – If the store is not a surface store, the level, a hemisphere, surface or attribute asked for is not in it, an attribute cannot be stored as GIFTI, or
output_diris a file.- Return type:
- zarr_vectors_tools.convert.export.gifti.gifti_filename(hemisphere, name, kind, prefix=None)[source]¶
The file name one surface or map is written under.
- Parameters:
- Returns:
[<prefix>_]hemi-<L|R>_<name>.<kind>.gii, or with a dot before a name that is not a valid BIDS label (letters and digits only).- Return type:
- zarr_vectors_tools.convert.export.gifti.metric_kind(name, source=None, *, series=False)[source]¶
The file kind and NIfTI intent a continuous map is written with.
The file the map came from decides first, because it records what the producing tool thought the map was: a
.shape.giistays a shape file and a.func.giia func file, and a FreeSurfer?h.<map>file is morphometry by definition. With no such evidence (a CIFTIdscalar, or a map attached by key) the name decides: thickness, curvature, sulcal depth, area, volume and Jacobian maps are shape, everything else is func.- Parameters:
- Returns:
("shape", "NIFTI_INTENT_SHAPE"),("func", "NIFTI_INTENT_NONE")or("func", "NIFTI_INTENT_TIME_SERIES").- Return type:
(kind, intent)
Neuroglancer precomputed¶
Export skeleton and mesh stores as Neuroglancer precomputed layers.
The way back into Neuroglancer, CloudVolume and igneous. An export writes one kind of object into a segmentation layer: a directory or bucket prefix laid out the way CloudVolume opens one:
<layer>/info segmentation volume info
<layer>/skeletons/info "@type": "neuroglancer_skeletons"
<layer>/skeletons/<segment id> one skeleton per segment
<layer>/skeletons/segment_properties/info ids, labels and numbers
<layer>/mesh/info "@type": "neuroglancer_legacy_mesh"
<layer>/mesh/<segment id>:0 manifest naming the fragment
<layer>/mesh/<segment id>.frag the segment's triangles
<layer>/mesh/segment_properties/info
What the format forces, and what this module does about it:
The layer’s own info.
CloudVolume(url)refuses a layer whoseinfohas noscales, and a bareneuroglancer_skeletonsdirectory has none. So a new layer gets a segmentationinfowith one placeholder scale – one voxel per level-0 chunk over the store’s bounds, no image chunks written, keyedplaceholder, which is CloudVolume’s own marker for a scale without image data – that names theskeletonsormeshsubdirectory. Exporting into an existing segmentation layer keeps its scales and writes into the subdirectory it already names, provided that subdirectory is a format this module writes. Neuroglancer can also open either subdirectory on its own, asprecomputed://<layer>/skeletons.Coordinates are nanometres, the unit both formats are read in, under an identity
transform. A store whose axes record a length unit is scaled from it; a cortical surface store is in millimetres; any other store that records no unit is taken to be in nanometres unlessunit=says otherwise. The store’s coordinate offset is added back.Segment ids. A store written by the precomputed ingesters keeps a
segment_idper object, and that is the id; the SWC ingest storesobject id + 1. Any other store numbers its objects from 0, and Neuroglancer treats segment 0 as background – it never asks for its skeleton or mesh – so those are exported asobject id + 1too. A stored segment id of 0 is refused for the same reason.Meshes are single-resolution (
neuroglancer_legacy_mesh), one fragment per segment. The multi-resolution Draco format and sharding are not written; export a coarser level to a second layer instead. The legacy manifest is named<id>:0, which Windows cannot hold as a file name, so on Windows a mesh layer goes to a bucket (gs://,s3://), not to a local directory.
output may be a URL (gs://, s3://, file://, optionally
behind Neuroglancer’s precomputed://) or a local directory. Writing
needs cloud-files, the precomputed extra.
- zarr_vectors_tools.convert.export.precomputed.export_precomputed(store_path, output, *, level=0, object_ids=None, segment_ids=None, attribute_names=None, object_attribute_names=None, unit=None, compress=None)[source]¶
Export a store as a Neuroglancer precomputed layer, by its geometry.
Skeleton and graph stores become skeletons (
export_precomputed_skeletons()); mesh stores become legacy meshes (export_precomputed_meshes()). Every other geometry is refused.- Parameters:
level (int) – Resolution level to export.
object_ids (Sequence[int] | None) – Objects to export, by the store’s object id.
segment_ids (Sequence[int] | None) – Objects to export, by segment id. Not with
object_ids.attribute_names (Sequence[str] | None) – Per-vertex attributes to carry (skeletons only).
object_attribute_names (Sequence[str] | None) – Per-object attributes to write as segment properties. Default: every one that has a precomputed spelling.
unit (str | None) – The store’s coordinate unit, when its metadata does not say.
compress (str | None) – CloudFiles compression for the object files (
"gzip","br"…). Default none, which any static file server can serve to Neuroglancer.
- Returns:
The summary of the exporter that ran.
- Return type:
- zarr_vectors_tools.convert.export.precomputed.export_precomputed_meshes(store_path, output, *, level=0, object_ids=None, segment_ids=None, object_attribute_names=None, unit=None, compress=None)[source]¶
Write a mesh store’s objects as Neuroglancer legacy meshes.
Each object becomes one fragment file –
uint32vertex count, thefloat32vertices in nanometres, theuint32triangle corners – and a<segment id>:0manifest naming it. Quads and larger polygons are fan-triangulated. The level is read once and split by the object manifests.- Parameters:
store_path (str | Path) – Path to the zarr vectors mesh store.
output (str | Path) – Layer URL or local directory (not a local directory on Windows; see the module docstring).
level (int) – Resolution level to export.
object_ids (Sequence[int] | None) – Objects to export, by the store’s object id. Default: every object with geometry at
level.segment_ids (Sequence[int] | None) – Objects to export, by segment id. Not with
object_ids.object_attribute_names (Sequence[str] | None) – Per-object attributes to write as segment properties. Default: every scalar or string one.
unit (str | None) – The store’s coordinate unit, when its metadata does not say.
compress (str | None) – CloudFiles compression for the fragment files.
- Returns:
Summary dict with
layer,directory,object_count,segment_ids,vertex_count,face_count(triangles written),properties,unitandnm_per_unit, andunit_assumedwhen the store did not say.- Raises:
ExportError – For a store that is not a mesh, a Draco-encoded store, an object that is not at
level, a local output on Windows, or a layer that already holds meshes in another format.- Return type:
- zarr_vectors_tools.convert.export.precomputed.export_precomputed_skeletons(store_path, output, *, level=0, object_ids=None, segment_ids=None, attribute_names=None, object_attribute_names=None, unit=None, compress=None)[source]¶
Write a skeleton (or graph) store’s objects as precomputed skeletons.
Each object becomes one
neuroglancer_skeletonsfile: its vertices in nanometres, its edges, and one block per carried vertex attribute, in the order the layer’sinfolists them.An EM skeleton store (one the precomputed ingesters wrote; see
zarr_vectors_tools.multiresolution.skeleton_layout) is read one segment at a time, touching only the chunks each segment lives in, and the boundary-crossing edges between its fragments are added back from the cross-chunk links – without them a neuron that crosses a chunk comes out in pieces. Any other store is read once and split by its object manifests.- Parameters:
level (int) – Resolution level to export.
object_ids (Sequence[int] | None) – Objects to export, by the store’s object id. Default: every object with geometry at
level.segment_ids (Sequence[int] | None) – Objects to export, by segment id (see the module docstring for how ids are assigned). Not with
object_ids.attribute_names (Sequence[str] | None) – Per-vertex attributes to carry. Default: every one with a precomputed type (float32, or an integer of at most 32 bits). A named attribute without one is refused.
object_attribute_names (Sequence[str] | None) – Per-object attributes to write as segment properties. Default: every scalar or string one.
unit (str | None) – The store’s coordinate unit, when its metadata does not say.
compress (str | None) – CloudFiles compression for the skeleton files.
- Returns:
Summary dict with
layer(the URL written),directory,object_count,segment_ids(in the order written),node_count,edge_count,attributes_carried,attributes_skipped,properties,unitandnm_per_unit, andunit_assumedwhen the store did not say.- Raises:
ExportError – For a store that is not a skeleton or graph, an object that is not at
level, a segment id of 0, or a layer that already holds skeletons in a form this module does not write.- Return type: