Compose¶
zarr_vectors_tools.compose: add objects to an existing store, or cut a
store into several. zvtools merge and zvtools split call these; see
Merge and split stores.
Merge¶
Putting one dataset into another.
convert builds a store from a file. attach joins columns onto
vertices a store already has. Neither adds objects to a store that
exists, which is what a second tractogram, a second imaging run or a
bundle atlas actually needs.
The obvious approach does not work. Dataset.add_polylines reads like
an append and is a replace: called twice on one store, the second call
leaves the first call’s objects gone, its object-attribute columns
overwritten, and no error anywhere. (Measured, not assumed: two writes
of two and one polylines leave a store with one object.) The append
primitive is instead EditSession.add_object(), which allocates an
id past the existing ones, splits the vertices across the chunks they
land in, and appends a fragment to each — leaving everything already
written byte-intact.
So this module is that primitive plus the four things around it that are
lost if nobody carries them — ids, groups, attributes, headers — and the
pyramid, which is derived from the level being changed and is wrong the
moment it changes. See zarr_vectors_tools.compose._carry.
The grid is the target’s. A merge never re-bins the store it writes
into: incoming geometry is assigned to the target’s existing cells, which
is what keeps the write proportional to what is added rather than to what
is already there. Geometry that lands outside those cells is checked for
up front, against the grid the arrays were allocated with rather than
the bounds they declare — the two can disagree, and it is the allocation
a write is checked against. That grid need not start at coordinate 0:
each array records the chunk coordinate of its first cell
(chunk_grid_origin), so a store over negative coordinates is as
mergeable as any other. on_out_of_bounds="expand" then grows the
grid upwards, which costs nothing because a chunk key is an absolute cell
index and adding cells at the top leaves every existing key meaning what
it meant. Downwards is refused: that moves the first cell, and every
cell already written is stored relative to it.
- zarr_vectors_tools.compose.merge.merge_stores(target, sources, *, create=False, cell_size=None, bounds=None, pyramid='rebuild', pyramid_factors=None, pyramid_options=None, groups=True, group_prefix=None, source_attribute=None, on_out_of_bounds='raise', max_objects=20000, max_vertices=4000000, progress=False, source_options=None)[source]¶
Merge one or more sources into
target.- Parameters:
target (Any) – Store to merge into — a path, URL or open
Dataset.sources (Sequence[Any] | Any) – What to merge. Each may be a store path, an open
Dataset, a path to a file in any supported format, or an already-constructedSource(which is how a coordinate transform is supplied).create (bool) – Create
targetwhen it does not exist, sizing its grid from the union of the sources’ bounds. Off by default: a typo in a store path should not silently produce a new store.cell_size (Sequence[float] | None) – Grid cell size for a created target. Defaults to the first source store’s, or a 64-cell-per-axis split of the union bounds when no source is a store.
bounds (tuple[Sequence[float], Sequence[float]] | None) – Pin a created target’s extent instead of using the union.
pyramid (Literal['rebuild', 'drop', 'keep']) – What to do with coarse levels, which every merge invalidates. See
handle_pyramid().pyramid_factors (Sequence[tuple[float, float]] | None) – Per-level
(coarsen, sparsity)for a rebuild. When omitted, each existing coarse level is rebuilt with the parameters it records.groups (bool) – Carry each source’s named object groups across.
group_prefix (str | Mapping[str, str] | None) – Namespace incoming group names — a single string applied to all, or
{source_label: prefix}. Without it, a name the target already has is extended rather than duplicated.source_attribute (str | None) – Name of a per-object attribute to stamp with each source’s index, so the merged objects stay separable.
on_out_of_bounds (Literal['raise', 'skip', 'expand']) – What to do when a source does not fit the target’s grid.
"raise"(default) refuses;"skip"drops the offending objects and counts them;"expand"grows the grid upwards to cover them, which is safe because chunk keys are absolute and adding cells at the top renumbers nothing. Geometry below the grid’s first cell is always refused — moving that cell would renumber every cell in the store.max_objects (int) – Objects per write batch.
max_vertices (int) – Vertices per write batch.
progress (bool) – Print per-batch progress.
source_options (Mapping[str, Any] | None) – Extra keyword arguments passed to
open_source()for any source given as a path.
- Returns:
per-source object counts, the id offsets applied, the group taxonomy as written, and what happened to the pyramid.
- Return type:
A summary dict
- zarr_vectors_tools.compose.merge.plan_merge(target, sources, **source_options)[source]¶
Everything a merge would do, without doing any of it.
Answers the question that actually blocks a merge — does the incoming geometry fit the target’s grid — before a single vertex is written.
Cheap on a store source, which is read through its metadata. A file source is opened the way the merge would open it, which for a format with no header-level object count means parsing it; budget for that rather than assuming this is free on any input.
Split¶
Taking one store apart along the lines already in it.
The inverse of merge, and useful for
the same reason: a store that holds a whole-brain tractogram plus
forty-three labelled bundles is the right thing to serve and the wrong
thing to hand someone who wants one bundle. Splitting it should not mean
re-running the conversion with a filter.
A split is a merge, run N times. Each output is a new store fed by
the source restricted to one set of object ids, which means it inherits
everything merge_stores() already
does correctly — id allocation, attribute columns, group taxonomy,
headers, provenance, pyramid — rather than reimplementing five of them
slightly differently. The parts differ only in how the id sets are
chosen, which is what split_store() is really about.
Grids stay aligned. Each output keeps the parent’s cell size, so a
bundle store’s cells are the same cells as the tractogram’s. That is what
lets the pieces be read together, compared cell-for-cell, or merged back.
By default each output also keeps the parent’s bounds; bounds="fit"
tightens each output to its own contents instead, which allocates fewer
cells. The cells it keeps are still the parent’s, because a chunk key is
an absolute cell index whatever the bounds.
Pyramids are the parent’s. pyramid="rebuild" gives each part the
coarse levels its parent has, built again from the part’s own objects with
the parameters each parent level records — the same rebuild a merge runs.
- zarr_vectors_tools.compose.split.plan_split(source, **kw)[source]¶
The parts a split would produce, and how big each is.
- zarr_vectors_tools.compose.split.split_parts(source, *, by='groups', attribute=None, names=None, parts=None, level=0)[source]¶
Work out which object ids belong to which output.
Separated from the writing so a caller can inspect, filter or reorder the parts before committing to N stores — and so a split that would produce four hundred single-object outputs can be noticed first.
- Parameters:
source (Any) – Store path or open
Dataset.by (Literal['groups', 'attribute', 'objects', 'provenance']) – How to cut.
"groups"uses the named object groups;"attribute"uses the distinct values of a per-object attribute;"objects"takes explicit id lists;"provenance"uses the id offsets a previous merge recorded, which is what makes a merge reversible.attribute (str | None) – Object attribute to cut on, for
by="attribute".names (Mapping[Any, str] | None) – Optional
{value: name}lookup forby="attribute".parts (Mapping[str, Sequence[int]] | None) – Explicit
{name: [ids]}, forby="objects".level (int) – Level to read the taxonomy from.
- Returns:
{part_name: object_ids}, insertion-ordered.- Return type:
- zarr_vectors_tools.compose.split.split_store(source, output, *, by='groups', attribute=None, names=None, parts=None, level=0, bounds='source', suffix='.zv', stem=None, pyramid='drop', pyramid_factors=None, pyramid_options=None, overwrite=False, min_objects=1, progress=False, **merge_options)[source]¶
Split
sourceinto one store per part, underoutput.- Parameters:
source (Any) – Store path or open
Dataset.output (str | Path) – Directory to write the parts into; created if absent.
by (Literal['groups', 'attribute', 'objects', 'provenance']) – How to cut — see
split_parts().attribute (str | None) – Object attribute to cut on, for
by="attribute".names (Mapping[Any, str] | None) –
{value: name}lookup for naming attribute parts.parts (Mapping[str, Sequence[int]] | None) – Explicit
{name: [ids]}, forby="objects".level (int) – Level to read from. Splitting a coarse level gives stores of coarse geometry, which is occasionally what you want and usually not.
bounds (Literal['source', 'fit']) –
"source"keeps the parent’s grid, so the outputs stay cell-aligned with it and with each other."fit"sizes each output to its own contents; its cells are still the parent’s, only fewer of them.suffix (str) – Extension for each output store.
stem (str | None) – Filename prefix; defaults to the source store’s own name. Each output is
<stem>_<part><suffix>, with the part name reduced to letters, digits,.,-and_and numbered when two parts would share a file.pyramid (Literal['rebuild', 'drop']) – What pyramid each output gets.
"drop"by default — a split usually produces many small stores, and building a pyramid on each is rarely wanted and never cheap."rebuild"builds one from the part’s own level 0: withpyramid_factors, those levels; without, the parent’s levels, each with the parameters it records (coarsening method, bin and chunk scale, tolerance, per-level sparsity). The parent’s levels can only be reproduced for a split of level 0. A part is a new store, so it has no coarse levels to keep; copying the parent’s restricted to the part’s objects is not supported.pyramid_factors (Sequence[tuple[float, float]] | None) – Per-level
(coarsen, sparsity)for an explicit pyramid, asmerge_stores()takes them. Needspyramid="rebuild".pyramid_options (Mapping[str, Any] | None) –
sparsity_strategy(both ways of rebuilding),coarsen_mode(explicit factors) andexecutor.overwrite (bool) – Replace an output that already exists.
min_objects (int) – Skip parts with fewer objects than this.
progress (bool) – Print each part as it is written.
merge_options (Any)
- Returns:
A summary dict with one entry per part written, and the names of any that were skipped.
- Return type:
Sources¶
One shape for “geometry coming from somewhere else”.
ingest reads a file and creates a store; the two steps are welded
together in every one of its fifteen modules, so there is no way to ask a
TRK file for its streamlines without also asking for a store to be built.
That is fine while a store has exactly one source. It stops being fine
the moment a second dataset has to land in a store that already exists —
an atlas of labelled bundles joining a whole-brain tractogram, a second
imaging run joining the first — because the only tool on offer builds a
separate store and leaves the caller to reconcile two object-id spaces,
two group taxonomies and two pyramids by hand.
A Source is the missing half: geometry, its attributes and its
group taxonomy, read in bounded batches, with no opinion about where it
is going. Two implementations cover everything:
StoreSource— another zarr-vectors store, at any level.FileSource— an external file, throughzarr_vectors_tools.compose.readers.
Both answer the same three questions (info,
iter_batches(), groups()), so
merge_stores() never learns which
kind it was handed.
Batches, not everything. A whole-brain level-0 store is 900 million
vertices; materialising it to merge 86 thousand more would be absurd.
Sources yield ObjectBatch values sized by object and vertex
count, so peak memory is a batch rather than a dataset. Objects are the
batching unit because an object is the smallest thing that can be written
without being torn: a polyline split across two batches would be written
as two polylines.
Transforms belong here. Bringing an external file into a store’s coordinate frame is the common case, not the exception — the two files that motivated this module differ by a rigid re-orientation that lives in their headers. Applying it at the source, before anything is binned, means the target’s grid, bounds check and spatial index all see final coordinates. Applying it afterwards would mean rewriting them.
- class zarr_vectors_tools.compose.sources.FileSource(path, *, format=None, transform=None, scratch_dir=None, label=None, **reader_options)[source]¶
Bases:
SourceAn external file, read through
compose.readers.Formats with a native reader are read straight into memory. Anything else is ingested into a scratch store first and then read back as a
StoreSource— slower and it costs disk, but it means every formatzvtools convertaccepts can be merged today rather than once someone writes a reader for it. Which route was taken is onstaged, since the difference is worth reporting and not worth hiding.- Parameters:
- __init__(path, *, format=None, transform=None, scratch_dir=None, label=None, **reader_options)[source]¶
- groups()[source]¶
Group name -> member object ids, in the source’s own numbering.
Empty by default: most file formats have no grouping concept, and a source that does overrides this.
- property info: SourceInfo¶
What this source holds. Cheap; safe to call repeatedly.
- class zarr_vectors_tools.compose.sources.GeometrySource(geometry, *, transform=None, label='<memory>')[source]¶
Bases:
SourceGeometry already in memory, wrapped so a merge can take it.
What
FileSourcebecomes once its reader has run, and the thing to reach for when geometry was produced in Python rather than read from anywhere.- groups()[source]¶
Group name -> member object ids, in the source’s own numbering.
Empty by default: most file formats have no grouping concept, and a source that does overrides this.
- property info: SourceInfo¶
What this source holds. Cheap; safe to call repeatedly.
- class zarr_vectors_tools.compose.sources.ObjectBatch(parts, object_ids, object_attributes=<factory>, vertex_attributes=<factory>)[source]¶
Bases:
objectA bounded run of whole objects.
parts[i],object_ids[i]and every column ofobject_attributesshare an index.vertex_attributescolumns are aligned withconcatenate(parts)— the same convention the writers use, so a batch can be handed toadd_polylinesunmodified.- Parameters:
- __init__(parts, object_ids, object_attributes=<factory>, vertex_attributes=<factory>)¶
- object_ids: ndarray[tuple[Any, ...], dtype[int64]]¶
Ids in the source’s own numbering; the merge remaps them.
- class zarr_vectors_tools.compose.sources.Source[source]¶
Bases:
ABCGeometry from somewhere, in a shape a merge can consume.
- groups()[source]¶
Group name -> member object ids, in the source’s own numbering.
Empty by default: most file formats have no grouping concept, and a source that does overrides this.
- abstract property info: SourceInfo¶
What this source holds. Cheap; safe to call repeatedly.
- abstractmethod iter_batches(*, max_objects=20000, max_vertices=4000000)[source]¶
Yield whole objects in batches no larger than the given bounds.
A single object larger than
max_verticesis still emitted whole, in a batch of its own — truncating it would corrupt it.- Parameters:
- Return type:
- property name: str¶
its file or store name, no extension.
What a carried header is filed under and what a part made by
split --by provenanceis called.SourceInfo.labelstays the full origin, for errors and the provenance record.- Type:
A short name for this source
- class zarr_vectors_tools.compose.sources.SourceInfo(label, kind, ndim, bounds, object_count=None, vertex_count=None, vertex_attributes=(), object_attributes=(), group_names=(), headers=<factory>, bounds_exact=True)[source]¶
Bases:
objectWhat a source holds, known before any geometry is read.
Everything here is cheap: metadata for a store, a header for a file.
merge_stores()plans the whole merge — bounds, id allocation, attribute reconciliation — from these alone, so a merge can be rejected before a single vertex moves.- Parameters:
- __init__(label, kind, ndim, bounds, object_count=None, vertex_count=None, vertex_attributes=(), object_attributes=(), group_names=(), headers=<factory>, bounds_exact=True)¶
- bounds: tuple[tuple[float, ...], tuple[float, ...]] | None¶
Extent after any transform, or
Nonewhen not known cheaply.
- bounds_exact: bool¶
Whether
boundsis the data’s extent or only a box around it.A subset of a store reports the whole store’s box, and a rotated box is larger than the rotated data, so neither can be the reason to refuse a merge: when such a box overhangs the target, the merge measures the data first.
- class zarr_vectors_tools.compose.sources.StoreSource(store, *, level=0, objects=None, transform=None, with_vertex_attributes=True, with_object_attributes=True, label=None, bounds=None)[source]¶
Bases:
SourceAnother zarr-vectors store, read one object batch at a time.
Why not just ``level.read()``. The facade’s polyline reader returns positions and object ids but never vertex attributes —
ReadResult.from_polylineshardcodesattributes_read=False, andLevel._gather_attributescan only repair that for an unnarrowed read, because a level-ordered attribute column cannot be aligned to a subset without knowing which vertices survived. Batching is exactly such a narrowing, so going through the facade would silently drop every per-vertex attribute in the store.This class gathers attributes the same way the reader gathers vertices: an object’s manifest lists
(chunk, fragment_index)pairs, and the attribute arrays are fragmented identically, soread_chunk_attributes(g, name, cc)[fi]is the column for the fragmentread_chunk_vertices(g, cc)[fi]holds. Same manifest, same order, so they cannot drift.Bounds.
boundsis the store’s declared box, which for a subset (objects=) or under atransformis only a box around what is emitted. Passbounds=— the measured extent, after any transform — when it is known; it is then reported as exact.- Parameters:
- __init__(store, *, level=0, objects=None, transform=None, with_vertex_attributes=True, with_object_attributes=True, label=None, bounds=None)[source]¶
- groups()[source]¶
Named groups, restricted to the objects this source emits.
A member this source is not carrying is dropped rather than emitted: a group naming an id the target never received would resolve to an empty manifest and be reported as a member, which is the same silent lie
propagate_groupingsexists to avoid.
- property info: SourceInfo¶
What this source holds. Cheap; safe to call repeatedly.
- iter_batches(*, max_objects=20000, max_vertices=4000000)[source]¶
Yield whole objects in batches no larger than the given bounds.
A single object larger than
max_verticesis still emitted whole, in a batch of its own — truncating it would corrupt it.- Parameters:
- Return type:
- property name: str¶
its file or store name, no extension.
What a carried header is filed under and what a part made by
split --by provenanceis called.SourceInfo.labelstays the full origin, for errors and the provenance record.- Type:
A short name for this source
- zarr_vectors_tools.compose.sources.as_transform(spec)[source]¶
Coerce
specinto a positions-in, positions-out callable.Accepts
None(identity, returned asNoneso callers can skip the call entirely), a callable, a(D+1, D+1)homogeneous affine, or a(D, D+1)affine without its bottom row.A square matrix is always read as homogeneous, so for three- dimensional data the transform is
4x4and a bare3x3is a two-dimensional affine — not a 3-D rotation. That reading is deliberate and it fails loudly: applying a 2-D affine to(N, 3)points raises on the matmul rather than silently projecting them. A rotation with no translation still needs its translation column.
- zarr_vectors_tools.compose.sources.open_source(spec, **kw)[source]¶
Open
specas aSource, whatever it is.A store path, a store URL, an open
Dataset, an already-builtSource, or a path to a file in any formatzvtoolsunderstands. The distinction that matters is store-versus-file, and it is decided by looking for the store’s root metadata rather than by the extension —.zarrvectorsis a convention, not a guarantee, and a store handed over under another name should still work.
Readers¶
Readers that return geometry instead of building a store.
Every module in zarr_vectors_tools.convert.ingest ends in a write_*
call. That is the right shape for “turn this file into a store” and the
wrong shape for “put this file into the store I already have”: the
caller wants the streamlines, not a second store to reconcile. These
readers are the ingest modules cut in half — the parsing, without the
writing.
Native, or staged. Writing a reader per format is work, and most of
that work already exists inside the ingesters. So the registry has two
tiers: formats with a native reader here, and everything else, which
FileSource stages through a
throwaway store. Staging costs a full write and a full read; a native
reader costs neither. Formats get promoted as they earn it, and nothing
is unsupported in the meantime.
On TRK. The native TRK reader parses the container directly rather
than going through nibabel, for two reasons. It makes positions,
per-point scalars and per-streamline properties available without
materialising a whole Tractogram — the file that motivated this is
22 million points — and it reads n_properties from byte 238,
where the TrackVis spec puts it. The parallel ingester reads it from
byte 236, which is inside the scalar_name table; for a file with no
properties both give zero and nothing is wrong, and for a file with
them the stride is short by four bytes per streamline and the parse walks
off the data.
- class zarr_vectors_tools.compose.readers.Geometry(kind, parts, vertex_attributes=<factory>, object_attributes=<factory>, groups=<factory>, headers=<factory>, edges=None, faces=None)[source]¶
Bases:
objectGeometry in memory, in the shape a merge consumes.
partsis one array per object for object-bearing geometry, and a single array for a point cloud.vertex_attributescolumns align withconcatenate(parts);object_attributescolumns align withpartsitself.- Parameters:
- __init__(kind, parts, vertex_attributes=<factory>, object_attributes=<factory>, groups=<factory>, headers=<factory>, edges=None, faces=None)¶
- zarr_vectors_tools.compose.readers.derive_groups(geometry, attribute, *, names=None, drop_attribute=False)[source]¶
Turn a per-object label column into named object groups.
A bundle atlas usually arrives as one tractogram plus an integer code per streamline plus a lookup table mapping codes to names — three artefacts that only mean something together, and that a store can hold as one thing. Groups are that one thing: named, first-class, and readable without the writing application’s source next to them, which is exactly what a bare
label_idcolumn is not.- Parameters:
geometry (Geometry) – The geometry to group; modified in place and returned.
attribute (str) – Name of the per-object attribute holding the labels.
names (Mapping[Any, str] | None) – Optional
{code: name}lookup. A code with no entry keeps a"<attribute>_<code>"name rather than being dropped — an unlabelled bundle is still a bundle.drop_attribute (bool) – Remove the label column once grouped. Off by default: the column is the only thing that survives an export back to a format with no group concept.
- Returns:
geometry, withGeometry.groupspopulated.- Return type:
- zarr_vectors_tools.compose.readers.ingest_to_store(path, fmt, target, **options)[source]¶
Ingest
pathinto a scratch store and return its path.The staging half of the two-tier registry. The grid this store gets is irrelevant to the merge — the merge re-bins everything onto the target’s grid — so a caller who has no opinion should not have to invent one, but the ingesters that require
chunk_shapegenuinely require it and inventing a number in their units would be worse than saying so.
- zarr_vectors_tools.compose.readers.native_formats()[source]¶
Formats with an in-memory reader, so no staging is needed.
- zarr_vectors_tools.compose.readers.read_geometry(path, fmt, **options)[source]¶
Read
pathwith the native reader forfmt.
- zarr_vectors_tools.compose.readers.read_tck(path, *, dtype='float32')[source]¶
Read an MRtrix
.tckfile. Positions only — TCK carries no per-point or per-streamline data.
- zarr_vectors_tools.compose.readers.read_trk(path, *, space='voxmm', dtype='float32', scalars=True, properties=True, limit=None)[source]¶
Read a TrackVis
.trkfile into memory.- Parameters:
space (str) –
"voxmm"(default) keeps the coordinates exactly as stored;"ras"applies the header’s affine to reach RAS millimetres. The default is the stored space because that is what a store built byzvtools convertwithout--apply-affineis already in, and matching it is what lets a second file land on the same grid.scalars (bool) – Carry per-point scalars as vertex attributes.
properties (bool) – Carry per-streamline properties as object attributes.
limit (int | None) – Stop after this many streamlines. For inspection.
dtype (str)
- Returns:
A
Geometryof streamlines, with the parsed header underheaders["trk"].- Return type: