Building stores¶
The supported surface for code that writes stores: ingest converters, pyramid builders, exporters, repair tools. It names the physical layout (chunks, fragments, shards, manifests). Code that only reads should use Data API.
The supported low-level surface, for tools that build stores.
Two audiences, two contracts.
zarr_vectors.api is for reading and querying data. It says
nothing about chunks or fragments, and it is where an application
belongs.
This module is for the other audience: ingest converters, pyramid builders, exporters — code whose job is the physical layout, and for which “hide the storage” would be hiding the thing they are working on. Forcing them onto the data-oriented API would be wrong, so instead they get an honest promise about a smaller surface.
The distinction this makes real. zarr_vectors.core,
zarr_vectors.lazy, zarr_vectors.ops, zarr_vectors.encoding
and zarr_vectors.spatial are internal. They change without notice;
they always did, and saying so is the only honest description of a
package whose recent history includes three breaking layout refactors.
What is re-exported here does not.
The contents are not a guess. They are the symbols the two consuming
repositories actually import from core.arrays and core.store,
counted — every name imported at three or more sites, plus the handful
below that threshold that have no alternative. Migration is therefore a
change of import line and nothing else:
-from zarr_vectors.core.arrays import list_chunk_keys, read_fragment
+from zarr_vectors.building import list_chunk_keys, read_fragment
If something you need is missing, that is a bug in this list rather than
an invitation to import from core — say so and it will be added,
because a name used from core is a name nobody knows is load-bearing.
Format constants and array names¶
Array names and layout values of the on-disk format. The
OBJECT_INDEX_LAYOUT_*, OBJECT_INDEX_MANIFEST_BUCKET,
OBJECT_SHARD_ROW_MULTIPLE and SOURCE_AXIS names are defined here;
the others are also in Constants.
|
|
|
Stores, resolution levels and transactions¶
Opening and creating stores, managing levels, and reading or updating
metadata. Group is the storage handle the
other functions take; only the methods in
GROUP_SUPPORTED_METHODS are supported.
- class zarr_vectors.building.Group(zarr_group)[source]¶
Bases:
objectA ZV group wrapping an underlying
zarr.Group.- Parameters:
zarr_group (zarr.Group)
- apply_presence(pending)[source]¶
Apply stamps collected by
collect_presence().One read-modify-write of
nonempty_chunksper array; entries fold in order, so the last stamp for a chunk key wins. Arrays are re-resolved by name. An emptypendingis a no-op.
- property attrs: _Attrs¶
- property backend: _BackendShim¶
- batched_range_reads(requests)[source]¶
Fetch every
(array_name, chunk_key, start, stop)range in one go and serveread_cell_range()from the result.batched_reads()for ranges: a reader that has read its fragment indices knows every row it needs, and asking for them together costs one gather rather than a round-trip each. A range the store cannot serve on its own is simply not cached;read_cell_range()then reads its whole cell, as it would have outside the block.Offline, every planned range is recorded as a miss of its whole cell – the snapshot is cell-granular – exactly as
batched_reads()records its plan.Nesting is not supported and raises
StoreError.
- batched_reads(plan, *, tolerant=False)[source]¶
Prefetch every chunk in
planvia oneasyncio.gather()and serve subsequentread_bytes()calls from the resulting in-memory cache.planis a list of(array_name, [chunk_keys, ...])pairs — typically(VERTICES, list_chunk_keys(group, VERTICES))plus the parallelvertex_fragmentsand per-attribute arrays. On entry every (array_name, chunk_key) pair is fetched in a single async gather; on exit the cache is dropped.Reads for a key NOT in the plan fall through to the sync
read_bytes()path, so under-specifying the plan degrades performance gracefully (still correct).Use for chunk-heavy read loops against high-latency object stores (GCS / S3 / Azure). Each per-chunk GET becomes one async task instead of one serial sync call, so the total wall time approaches one round-trip rather than
Nround-trips.Nesting is not supported and raises
StoreError. Writes inside the block are unaffected.tolerant=Truekeeps one failing cell from failing the whole prefetch: it is left uncached, and reading it inside the block raises its own error while every other cell is served.Example:
chunk_keys = list_chunk_keys(level_group, VERTICES) with level_group.batched_reads([ (VERTICES, chunk_keys), (VERTEX_FRAGMENTS, chunk_keys), *((f"{VERTEX_ATTRIBUTES}/{a}", chunk_keys) for a in attrs), ]): for cc in chunk_keys: fragments = read_chunk_vertices(level_group, cc, ...)
- batched_writes(compressor=None, *, durable=False)[source]¶
Defer every
write_bytes()andwrite_array_meta()call inside the block and flush them in a singleasyncio.gather()on exit.Use for chunk-heavy write loops against high-latency object stores (GCS / S3 / Azure). Each per-chunk PUT and each per-array
zarr.jsonPUT becomes one async task instead of one serial sync call, so the total wall time approaches one round-trip rather thanNround-trips.- Parameters:
compressor (Any) – Codec selection applied to every chunk array written inside the block. See
zarr_vectors.encoding.compression.resolve_compressor()for accepted values; the defaultNoneresolves to zarr v3’s default (bytes+zstd). # TODO: per-array-type codec dict (vertices vs fragments # vs links) — future work; today every chunk gets the # same codec.durable (bool | str) – On a local store, have everything the block wrote on disk when it returns: each cell object (a shard, when sharded) is fsynced before its rename, then the metadata documents written and every directory changed. For a caller whose own record of “done” is durable. A no-op on an object store, where a returned PUT already is.
"deferred": written atomically but not fsynced; the caller makes them durable later withzarr_vectors.building.sync_store().
- Return type:
Iterator[None]
Nesting is not supported and raises
StoreError. Reads inside the block are unaffected and execute synchronously.Example:
with level_group.batched_writes(): create_vertices_array(level_group, dtype="float32") create_attribute_array(level_group, "intensity") for cc in chunk_coords: write_chunk_vertices(level_group, cc, ...) write_chunk_attributes(level_group, "intensity", cc, ...) # exit point: every PUT scheduled above flushes in parallel
- cached_nodes()[source]¶
Resolve each node at most once for the duration of one read.
A reader resolves the same handful of nodes over and over: the level group,
vertices,vertex_fragments, one array per requested attribute – once to read its metadata, again to list its chunk keys, again per chunk read that misses the prefetch. Every one of those is azarr.jsonGET, and against a store holding a single point that was the whole cost of the query: a one-pointread_pointsissued nine metadata reads to fetch two chunk objects.Read-only by contract, which is what lets it cache more than
batched_writes()can. Nothing inside the block creates or deletes a node, so a negative result cannot go stale and Groups are as cacheable as Arrays; and because the cache is keyed root-relative it is shared with every Group derived inside the block, so the level handle a reader opens on entry hits the same cache the root does.Writes inside the block are not supported – a mutation would leave a handle cached past the node it points at. Nesting is a no-op: the outer block already covers the inner one.
Example:
root = open_store(store_path) with root.cached_nodes(): level_group = get_resolution_level(root, level) ...
- Return type:
Iterator[None]
- child_names()[source]¶
children()from one store listing, reading no child’s metadata.children()resolves every child node to sort arrays from groups – onezarr.jsonread per child, twice over – and a caller that only wants the names pays for all of it. The links family is that caller: a mesh at 10^6 vertices has ~170 offsets arrays, and listing them that way was 24 ms of a 34 ms one-object read. Every directory under a node is a node in Zarr v3, so the listing is the answer.Falls back to
children()offline (the snapshot carries the listing, not the store) and on any store that cannot list.
- children()[source]¶
Return every immediate child name — both arrays and groups.
Use this wherever a parent path’s children may be arrays rather than groups:
links/<delta>andlink_attributes/<name>/ <delta>hold one array per offsets segment, and object / group attributes are flat arrays.__iter__yields sub-groups only, so it sees none of those.
- chunk_array_codecs(compressor)[source]¶
Set the codec pipeline for chunk arrays created inside the block.
The creation half of
batched_writes()on its own: it selects the codecs new per-chunk arrays are stamped with and changes nothing else. Writes inside the block stay synchronous and immediate.That separation is the point.
batched_writesis the only other way to reach the session codec, and it also defers every write to a single flush on exit — which a caller that read-modify-writes a cell cannot use, because the read would not see what the same block just wrote (write_chunk_fragments(mode="append")and everynonempty_chunksstamp do exactly that). A writer that wants compression but not deferral had no way to ask.Only creation is affected, and only for arrays that do not exist yet: an array already on disk keeps the pipeline it was stamped with, since its written cells are encoded under it. To change an existing store’s codecs, delete the arrays and rewrite them.
- Parameters:
compressor (Any) – See
zarr_vectors.encoding.compression.resolve_compressor().None/"none"/Falsemeans no compression,"zstd"is zarr v3’s default (level 0),"blosc"is Blosc(Zstd, BitShuffle, l5), or pass an explicit codec list such as[{"name": "zstd", "configuration": {"level": 5}}].- Return type:
Iterator[None]
Example:
with level_group.chunk_array_codecs("zstd"): create_vertices_array(level_group, dtype="float32") write_chunk_vertices(level_group, cc, [positions])
- chunk_grid_bounds(array_name)[source]¶
(origin, shape)ofarray_name’s cell grid, or None.The grid the chunk keys live in: cell
iof the array holds absolute chunk coordi + origin(originisNonefor a zero origin, which is how it is stored). A box resolver needs this to clamp —chunks_intersecting_bboxspeaks absolute coords and knows nothing of the store’s extent, so an unclamped box can name vastly more cells than the grid could ever hold.Nonewhen the path holds no chunk array.
- chunk_index_by_spatial(array_name, nd)[source]¶
Present coordinates grouped by their trailing
ndaxes.See
_ChunkListing.by_spatial().
- chunk_present_set(array_name)[source]¶
list_chunk_coords()as a set, for membership tests.See
_ChunkListing.present()for why a reader wants it.
- collect_presence()[source]¶
Defer the
nonempty_chunksstamps inside the block, so the caller decides when, and under what lock, to apply them.Writes that would stamp instead append
(array_name, chunk_key, present)to the yielded list; payloads still go out inline. Leaving the block does not apply them, even on error; pass the list toapply_presence().record_presence=Falseis still honoured. The list and this Group belong to one thread. Nesting or use insidebatched_writes()raisesStoreError. Seedocs/how_to/hpc_pipelines.md:with level_group.collect_presence() as pending: flush(level_group) # payloads, no lock held with store_write_lock(path): level_group.apply_presence(pending)
- create_sharded_chunk_array(array_name, grid_shape, *, shard_shape=None, origin=None, compressors=None, attributes=None, octree=<object object>)[source]¶
Allocate a vlen-bytes Zarr array for per-chunk blobs.
A single Zarr v3 array whose shape equals the level’s chunk grid; each cell holds one Zarr Vectors spatial chunk’s payload. When
shard_shapeis provided thesharding_indexedcodec packs many cells into a single storage object — the standard cloud layout described in Sharding.- Parameters:
array_name (str) – Logical path of the array, e.g.
"vertices"or"links/0/0.0.+1". Intermediate path segments become Zarr sub-groups if absent.grid_shape (tuple[int, ...]) – Number of chunks along each spatial axis at this level. Computed via
zarr_vectors.spatial.chunking.compute_grid_shape().shard_shape (tuple[int, ...] | None) – Outer-chunk shape in inner-chunk units.
None(default) creates an unsharded array — one storage object per Zarr Vectors chunk, same I/O cost as the legacy layout but already in the new structural form. A typical cloud workload uses(8, 8, 8): 512 Zarr Vectors chunks per storage object.compressors (list[dict[str, Any]] | None) – BytesBytes compressor list (already stripped of the
bytesserializer, i.e. thecreate_arraycompressors=form).Noneleaves the codec pipeline at vlen-bytes only (no compression) — matching the historical no-compression default of the earlier per-chunk-array writer. Pass[]for the same effect explicitly, or a[{"name": "zstd", ...}]-style list to compress.attributes (dict[str, Any] | None) – Per-array metadata merged into the array’s
zarr.jsonattributesblock (the standard Zarr v3 location for user metadata).octree (Any) – The
zarr_octree_shardingconfiguration, orNoneforsharding_indexed(forzarr_vectors.sharding.set_octree()); omitted, the store’s marker decides (_store_octree()).
- Return type:
None
- create_sharded_chunk_arrays(arrays, grid_shape, *, shard_shape=None, origin=None, compressors=None, replace=())[source]¶
create_sharded_chunk_array()for several arrays at once.One
zarr.jsonper array still has to be written, but they are independent, so they go out in one gather rather than through a blockingsync()each – which is the difference between allocating a links family of 1,700 offsets arrays in a second and in a minute.arraysis[(array_name, attributes), ...];replacenames those whose existing node must be dropped first (the caller has looked, so this does not look again).
- derive_nonempty_chunks(array_name, *, on_sharded='derive')[source]¶
Rebuild
array_name’snonempty_chunksfrom what is on disk.The coordinator half of
write_bytes(..., record_presence=False). Candidate cells come from one store listing and are read in one batch, so cells holding an empty payload are not recorded. For a sharded array each listed shard is answered from its index (seedocs/spec/chunking/sharding.md). Not reported toobserve_presence_writes().- Parameters:
- Return type:
Returns the sorted keys now recorded; raises
StoreErrorifarray_nameis not a chunk array.
- extend_array(path, rows, *, attributes=None, _node=None)[source]¶
Append
rowsalong axis 0, leaving existing rows untouched.The cheap half of an append.
write_array()recreates the array from a full in-memory copy, so growing one by read → concatenate → write costs the whole array on every call; a writer that appends once per spatial chunk therefore pays O(chunks x rows) over a build, and each call is slower than the last. This resizes in place and writes only the new region, so the cost is the rows actually added — provided the array is chunked along axis 0, which is whywrite_object_attributes()gives its arrays a bounded row chunk when it creates them.- Parameters:
- Returns:
The array’s new length along axis 0.
- Return type:
Notes
An array whose attributes block records its own
shape(whatwrite_array()stamps, and what the O(1) length readers key on) has it restamped from the resized array — so the recorded shape cannot drift from the real one across an append.
- list_chunk_coords(array_name)[source]¶
list_chunks(), parsed to coordinate tuples and sorted.The form every reader actually wants, and the one worth caching: the strings come off the presence manifest already, but turning 125 of them into tuples is 125 splits and 375
intcalls, paid on every read no matter how few chunks the query goes on to touch. Inside acached_nodes()block the parse happens once; outside it, every call parses, exactly as before.
- native_sharded_arrays(shard_shape, grid_shape, *, origin=None)[source]¶
Pin the chunk grid subsequent per-chunk-array creations use.
Inside this block, every
zarr_vectors.core.arrays._ensure_array_dir()call for a per-spatial-chunk array (vertices, vertex_fragments, links/<delta>/<offsets>, link_fragments, vertex_attributes/<name>, fragment_attributes/<name>) allocates its vlen-bytes array against THIS grid and sharding, rather than the one derived from the store’s metadata. Opened byzarr_vectors.core.arrays.open_write_session(); without it the derived config applies, so the layout is the same either way.- Parameters:
shard_shape (tuple[int, ...] | None) – Outer-chunk shape in inner-chunk units, e.g.
(8, 8, 8).None(the default) means unsharded — one storage object per spatial chunk. When set, its length must matchgrid_shapeand the Zarr v3sharding_indexedcodec packs many cells per shard.grid_shape (tuple[int, ...]) – Number of spatial chunks along each axis at this level. Compute via
zarr_vectors.spatial.chunking.compute_grid_shape().
- Return type:
Iterator[None]
Nesting is not supported; an inner call raises
StoreError. Thebatched_writescontext can be active concurrently — cell writes are queued and flushed together (seezarr_vectors.core._batch_writer).
- note_vertex_rows(chunk_key, n_rows)[source]¶
Record how many vertex rows a cell was just given.
stamp_fragments_tile()has to know each cell’s row count to check the fragment index against it, and it used to get that by re-reading everyverticescell it had just written – measured at 1.00x the bytes written, so a bulk write downloaded its own output in full before returning. The writer already knows the number, so it says so.Only a hint: a key with no recorded count is read back as before, which is what keeps the stamp correct for a level whose cells this session did not write.
- offline_reads(session)[source]¶
Serve every read inside the block from
session, touching the store not at all.This is the replay half of the async read path. The snapshot is built by
zarr_vectors.core.aio, which resolves the nodes and fetches the chunk cells withawait; inside this block the ordinary synchronousread_*functions then run to completion against it. The decode, filtering and assembly work they do is pure computation, so it needs no async treatment — it only ever needed its I/O supplied up front.That is why there is no async mirror of each
read_*: given a primed handle, the sync ones are the async ones.Any lookup or chunk read the snapshot does not cover records itself in
session.missesand raisesStoreErrorrather than falling back to the store: a gap must surface, since the silent alternative is the synchronous round-trip this path exists to avoid. The caller inspectsmissesto decide what to fetch next — seeread_async().Nesting is not supported and raises
StoreError. The block is read-only by construction; writes inside it are not supported.- Parameters:
session (_OfflineSession)
- Return type:
Iterator[None]
- presence_deferred()[source]¶
Whether this level declares its presence deferred.
See
zarr_vectors.building.defer_presence(). Read from the handle’s metadata, so only as fresh as the handle: open the level after the coordinator declares.- Return type:
- prime_nodes(paths)[source]¶
Resolve several nodes in one round-trip, into the active cache.
cached_nodes()stops a node being resolved twice; this stops the first resolutions being paid one after another. A point read needs three nodes — the level group,vertices,vertex_fragments— and resolving them as they come up is three serialzarr.jsonreads before any data moves, which on a single-chunk query was most of the query. Asked for together they cost one gather.A no-op outside a
cached_nodes()block (there is nowhere to put the result), underoffline_reads()(the snapshot is already primed, and its misses are the caller’s signal), and for any path already cached. Speculative by design: a path that does not exist caches as absent, which is an answer the reader wants just as much.
- range_readable(array_name)[source]¶
Can
read_cell_range()fetch part of a cell ofarray_namewithout reading all of it?True for an uncompressed vlen-bytes array, sharded or not, on a store that serves byte ranges; False offline and on icechunk, whose reads are cell-granular. A reader uses it to decide whether reading an index first and the rows second is worth the extra round-trip over reading both whole in one gather.
- read_array_attrs(path)[source]¶
Read the
attributesblock of a Zarr array atpath.Returns
{}for missing paths or paths that point at a group rather than an array.
- read_array_fill_value(path)[source]¶
Return the
fill_valueof the standard Zarr array atpath.fill_valuelives at the top level of the array’szarr.json(not in the userattributesblock), so this helper exists alongsideread_array_attrs()rather than being folded into it. RaisesStoreErrorifpathis missing or points at a group.
- read_cell_range(array_name, chunk_key, start, stop)[source]¶
Payload bytes
[start, stop)of one cell.read_bytes(array_name, chunk_key)[start:stop], without fetching the rest of the cell where the array allows it: an uncompressed cell is read as just those bytes (seefetch_ranges()). Anything else – a compressed array, an offline read, a range the store cannot serve – reads the whole cell and slices it, so the answer is the same either way and only its cost differs.Served from
batched_reads()(whole cells) orbatched_range_reads()(this range) when either holds it.
- read_vlen_array_raw(path, stop=None)[source]¶
Rows
[0, stop)of a vlen-bytes array as zarr returns them: an object array, withoutread_vlen_array()’s per-rowbytes()conversion.
- read_vlen_element(path, index)[source]¶
Read ONE element of the vlen-bytes array at
path.Kept distinct from
read_vlen_array()so the online path still fetches a single element rather than the whole array —object_index/manifestshas one row per object, so reading it whole to answer a by-id lookup would not scale. Offline the distinction is moot: the snapshot holds the array entire, and this just indexes into it.
- read_vlen_elements(path, indices)[source]¶
Read MANY elements of the vlen-bytes array at
path, at once.The plural form exists because the singular one, called in a loop, is one request per element — which is exactly the shape a selective read is trying to avoid. One coordinate selection fetches only the zarr chunks the wanted rows actually fall in, so reading a hundred of twenty-one million object manifests costs a handful of reads rather than a hundred, or than all of them.
Results are returned in the order of
indices, so a caller can zip them against the ids that produced them without re-sorting.
- shard_transaction(shard_coords, *, arrays=None, mode='replace', durable=True, io_threads=None, sweep=True, prefetch=False)[source]¶
Stage one shard’s cell writes, and publish them on exit.
See
zarr_vectors.core.shard_txnandzarr_vectors.building.shard_transaction().
- standalone_array_exists(path)[source]¶
Truewhenpathpoints at a Zarr array (not a group).Counterpart to
array_exists(), which reportsTruefor either node type — so it also answers “does this family group exist” for a path likelinks/<delta>.
- take_vertex_rows()[source]¶
Consume and clear the recorded counts.
Cleared on read so a later stamp cannot trust a count from before an intervening edit.
- write_array(path, data, *, chunks=None, fill_value=None, attributes=None, compressors=None, shards=None)[source]¶
Write a chunked Zarr v3 array at
path.- Parameters:
path (str) – Logical path of the array within this group, e.g.
"object_attributes/intensity". Intermediate path segments become Zarr groups if absent.data (Any) – Numpy-coercible array.
dtypeandshapeset the array’s dtype and shape.chunks (tuple[int, ...] | None) – Chunk shape. Defaults to
data.shape(single chunk).fill_value (Any) – Value Zarr returns for unwritten chunk positions. Special floats are JSON-string-encoded per spec (
"NaN","Infinity","-Infinity").attributes (dict[str, Any] | None) – Dict applied to the array’s
attributesblock in its ownzarr.json— the spec-blessed location for per-array user metadata.compressors (Any) – Override the codec pipeline.
Noneuses the active session codec (frombatched_writes()) or zarr v3’s default (bytes+zstd).shards (tuple[int, ...] | None) – Outer chunk (shard) shape, a multiple of
chunks;Nonefor one object per chunk. Zarr’s ownsharding_indexed, so any Zarr v3 reader reads it.
- Return type:
None
- write_bytes(array_name, chunk_key, data, *, record_presence=True)[source]¶
Write one spatial chunk’s payload into
array_name’s cell.A composite level (
zarr_vectors.core.sources) writes only its own cells, source0: a source is never written through it.array_namemust already hold the multidim vlen-bytes Zarr array whose shape is the level’s chunk grid — every ZV per-spatial-chunk array (vertices, fragments,links/<delta>/ <offsets>, attributes) is one, allocated byzarr_vectors.core.arrays._ensure_array_dir().- Parameters:
record_presence (bool) – When False, skip the
nonempty_chunksupdate. That manifest is ONE attribute shared by every cell of the array, so stamping it is a read-modify-write of state outside the cell being written: two workers writing disjoint cells concurrently still race, and the loser’s key vanishes from the manifest even though its payload is on disk. Decentralized writers therefore pass False and leave the manifest to a coordinator’sderive_nonempty_chunks()(seezarr_vectors.core.arrays.finalize_links()), which rebuilds it from the store listing after all workers finish. Cell payloads themselves are independent objects and never race.array_name (str)
chunk_key (str)
data (bytes)
- Return type:
None
- write_cells(array_name, cells, *, record_presence=True)[source]¶
write_bytes()for many cells of one array.The node is resolved and the grid read once for the whole batch; each cell then costs its coordinate check and, inside a
batched_writes()block, one append to the queue. A links family writes a hundred thousand cells of a few rows each, and the per-call overhead of the singular form was most of that write. Returns how many cells were written.
- write_vlen_array(path, blobs, *, chunks=None, attributes=None)[source]¶
Write a 1D variable-length-bytes Zarr v3 array at
path.Each element of
blobsbecomes one row of the resulting array. Mirrors the layout used byobject_index/manifests.- Parameters:
path (str) – Logical path of the array.
blobs (Sequence[bytes]) – Iterable of bytes blobs. Empty input writes no array (caller’s responsibility to check).
chunks (int | None) – Elements per chunk. Defaults to
len(blobs)(single chunk).attributes (dict[str, Any] | None) – Dict applied to the array’s
attributesblock.
- Return type:
None
- property zarr_group: Group¶
The underlying
zarr.Group.
- zarr_vectors.building.GROUP_SUPPORTED_METHODS: frozenset[str] = frozenset({'apply_presence', 'array_exists', 'attrs', 'batched_reads', 'batched_writes', 'cached_nodes', 'children', 'chunk_array_codecs', 'chunk_exists', 'collect_presence', 'create_group', 'create_sharded_chunk_array', 'delete_subtree', 'derive_nonempty_chunks', 'list_chunks', 'native_sharded_arrays', 'offline_reads', 'path', 'prefix', 'presence_deferred', 'prime_nodes', 'read_array', 'read_array_attrs', 'read_array_fill_value', 'read_array_meta', 'read_bytes', 'read_vlen_array', 'read_vlen_element', 'read_vlen_elements', 'require_group', 'shard_transaction', 'standalone_array_exists', 'url', 'write_array', 'write_array_meta', 'write_bytes', 'write_cells', 'write_vlen_array'})¶
The subset of
Group’s methods this module promises.Groupis re-exported here, but it carries ~40 public methods and a consumer cannot tell which are contract and which are the storage layer’s own working surface. These are the ones a builder needs and that will not change without a deprecation path; everything else on the class –zarr_group,_lookup_node, the offline-session plumbing – is internal even though Python cannot say so.Note
commitis deliberately absent: it is a module-level function incore.store(re-exported here), not aGroupmethod.
- zarr_vectors.building.create_store(path, *, bounds=None, chunk_shape=None, axes=None, geometry_types=None, crs=None, ndim=None, vertex_dtype='float32', vertex_encoding='raw', compressor=None, links_convention=None, object_index_convention=None, cross_chunk_strategy=None, cross_level_depth=None, cross_level_storage=None, reduction_factor=None, base_bin_shape=None, format_capabilities=None, attribute_specs=None, shard_shape=None, octree_sharding=None, manifest_layout=None, manifest_block_dtype=None, name=None, unit=None, backend=None, storage_options=None, **backend_kwargs)[source]¶
Create a new ZV store.
create_store(path)produces a structurally valid “warm” shell: root group with format markers + defaultbounds, a0/sub-group, and the empty ragged-vertex pair0/vertices/+0/vertex_fragments/.boundsis mandatory for every ZV store; when the caller does not pass one, the default([0,...,0], [128,...,128])is stamped (usingndimif given, otherwise inferred fromaxes/chunk_shape/bounds, defaulting to 3D). Subsequent writes must fit within these bounds unless the caller passesout_of_bounds="expand"(which grows the bounds in-place) or callsset_bounds()first.The
/parametricsub-group is not created here; it is created lazily on first use viaget_parametric_group().- Parameters:
path (StoreLike) – URL or filesystem path for the new store.
bounds (tuple[list[float], list[float]] | None) –
(min_corner, max_corner). When omitted, defaults to([0]*ndim, [128]*ndim).chunk_shape (tuple[float, ...] | None) – Spatial chunk size per dimension. When omitted, defaults to a single chunk covering
bounds.axes (list[NgffAxis] | None) – OME-Zarr-style axes list. When omitted, generated from
DEFAULT_AXES_NAMES.geometry_types (list[str] | None) – List of geometry types the store will contain. Defaults to
[].crs (dict[str, Any] | None) – Coordinate reference system as a PROJJSON object, stored as the root’s
proj:projjson(the proj convention).ndim (int | None) – Number of spatial index dimensions. Useful when no other ndim-bearing kwarg is supplied (
axes/bounds/chunk_shape). Defaults to 3.vertex_dtype (str) – dtype for the level-0 vertices array.
vertex_encoding (str) –
"raw"or"draco".compressor (Any) – Codec pipeline for the warm-created
vertices/vertex_fragmentsarrays — and therefore for the life of the store, since a chunk array’s codecs are fixed at creation and every latercreate_vertices_arrayreuses the existing array.None(default) stores raw. Seezarr_vectors.encoding.compression.resolve_compressor()for accepted values ("zstd","blosc", or a codec list). Writers that create their own arrays (links, attributes) still need the same compressor passed to their own write session.links_convention (str | None) – How edges are encoded (
"explicit"/"implicit_sequential"/"implicit_sequential_with_branches"). When omitted the store has no convention stamped at create time; the first type writer (write_graph,write_polyline, …) fills it in via_ensure_root_metadata_for_write.object_index_convention (str | None) – How
object_index/is encoded ("standard"/"identity"). Same lazy-fill rule aslinks_convention.cross_chunk_strategy (str | None) – Cross-chunk connectivity strategy (
"boundary_deduplication"/"explicit_links"/"both"). Lazy-filled by type writers.cross_level_depth (int | None) – Maximum
|delta|materialised bybuild_pyramid.0disables cross-level link arrays.cross_level_storage (str | None) –
"none"/"implicit"/"explicit"— seezarr_vectors.constants.VALID_XLEVEL_STORAGE.reduction_factor (int | None) – Default vertex-count fold per pyramid step.
base_bin_shape (tuple[float, ...] | None) – Level-0 supervoxel bin edge lengths. When omitted, defaults to
chunk_shape(one bin per chunk).format_capabilities (list[str] | None) – Optional capability tokens to stamp on the root. See
zarr_vectors.constantsCAP_*.attribute_specs (dict[str, dict[str, Any]] | None) – What the store declares its attributes to be, by scope –
{"vertex": {name: {...}}, "object": ..., "link": ...}. Optional and additive; a reader that does not know about it is unaffected. Declaring an attribute does not create it.shard_shape (int | Sequence[int] | None) –
Cells per shard per axis, or
None(the default) for one storage object per cell. Anintbroadcasts to every axis; a per-axis sequence must have one entry per spatial dimension.Recorded on the root, which is what makes it reach the arrays nobody passes it to – an attribute array or links segment allocated on first write, in a worker that never saw this call. Per-call
shard_shape=on a writer reaches only the arrays that writer creates, which is how a store ends up sharded in some arrays and flat in the rest.The units are grid cells, not coordinates, so one declaration stays meaningful at every level of a pyramid even though their grids differ. It is a writer default rather than a claim about what is on disk: each array’s own
zarr.jsonremains the truth about that array.octree_sharding (dict[str, Any] | None) – Mark the store octree: its sharded per-chunk arrays use zarr-octree’s
zarr_octree_shardingcodec with this configuration ({}for its defaults) instead ofsharding_indexed. Needsshard_shapeand the zarr-octree package, both checked here, before the store exists.None(the default) writes nothing. Seezarr_vectors.sharding.set_octree()to convert.manifest_layout (str | None) –
"dense"to write object indexes as fixed-width integer arrays (manifest_spans+manifest_blocks) rather than one vlen blob per object;Noneor"vlen"(the default) for blobs. Recorded on the root as the default for every index created later; an index that exists keeps its layout. Seezarr_vectors.core.dense_manifests.manifest_block_dtype (str | None) –
"int32"to create dense indexes’manifest_blocksas int32, which halves the bytes a chunk decodes to (stored, under zstd, a few percent less), for a store whose chunk coordinates and fragment indices all fit in it;Noneor"int64"(the default) for int64. Recorded on the root as the default for every dense index created later (block_dtype=on a writer overrides it); an index keeps the dtype it was created with, and every write into an int32 one raisesArrayErroron a value that does not fit rather than wrapping it. Spans and ids stay int64, and every reader returns int64.name (str | None) – Human-readable store name, recorded on the RFC 8
omenode so an OME collection can present it. Defaults to the store path’s last segment with its extension stripped. Not an identifier: a collection referencing this store supplies its own name for the node, which is what addresses it there.unit (str | None) – What vertex coordinates are measured in – an NGFF space unit such as
"micrometer". Declared on every space axis (axesas given, or the generated defaults), so it is recorded in the rootzarr_vectors.axesand written into theworldcoordinate system of the rootomescene.None(the default) declares nothing and writes exactly what a store created without it always has: a unit is a claim, and a store that does not know one must not make it. RaisesMetadataErrorfor a non-NGFF spelling or a conflict with a unit already onaxes; seezarr_vectors.core.metadata.axes_with_unit().backend (str | None) – Force a particular backend (
"local"/"icechunk").**backend_kwargs (Any) – Forwarded to the backend constructor. A backend that takes no options –
local, or a store you built yourself – raisesTypeErrorrather than discarding them, so a misspelled parameter fails here instead of being silently ignored. Structuredstorage_options=is always accepted.**backend_kwargs
- Returns:
The root
Group.- Raises:
StoreError – If a store already exists at
path.MetadataError – If kwargs are inconsistent (mismatched ndim).
- Return type:
- zarr_vectors.building.open_store(path, mode='r', *, backend=None, storage_options=None, require_zv=True, **backend_kwargs)[source]¶
Open an existing ZV store.
- Parameters:
path (StoreLike | Group) – URL or filesystem path to the store, a pre-built
zarr.abc.store.Store, or an already-openedGroup. A Group is returned unchanged — mirroring_create_or_open_store()on the write side, so a caller holding a handle can read through it without reopening. This is what lets a caller prime the handle’s caches (seeGroup.offline_reads()) and then drive an otherwise synchronousread_*with no store I/O at all. When a Group is passed,modeand the backend kwargs are ignored — the handle’s existing mode stands.mode (str) –
"r"(read-only — writes will raise),"r+"(read-write),"a"(append). Formode="r"the underlying Zarr store is wrapped viastore.with_read_only(True)when the store implementation supports it (the LocalStore and FsspecStore do; icechunk readonly sessions enforce read-only at the transaction layer). Callers that need to mutate must open withmode="r+".backend (str | None) – Force a particular backend (auto-detect by default).
require_zv (bool) – When True (the default), a root with no
zarr_vectorsattribute block raisesStoreError. Pass False to get the handle anyway — forzarr_vectors.validate.structure.validate_structure(), whose job is to report that condition rather than be stopped by it.**backend_kwargs (Any) – Forwarded to the backend constructor.
- Returns:
The root
Group.- Raises:
StoreError – If the store does not exist or is structurally invalid.
MetadataError – If root metadata cannot be parsed.
- Return type:
- zarr_vectors.building.commit(group, message='zarr-vectors write')[source]¶
Commit pending changes when the store is backed by a transactional backend (currently
icechunk).For non-transactional backends this is a no-op and returns
None: each write is visible as soon as it lands. On an object store a returned PUT is also durable; on a local filesystem it is atomic (renamed into place) but not fsynced unless written insidebatched_writes(durable=True)/open_write_session(durable=True).For icechunk-backed stores this calls
session.commit(message)and returns the new snapshot id (a hex string). The same session continues to be writable after the commit — subsequent ZV writes accumulate uncommitted state until the nextcommit(group, ...)call.- Parameters:
group (Group) – A
Groupreturned bycreate_store()oropen_store()(or any sub-group of one).message (str) – Commit message; defaults to a placeholder. Empty strings are rejected by icechunk.
- Returns:
Snapshot id (
str) for icechunk-backed groups, elseNone.- Return type:
str | None
- zarr_vectors.building.session_for(group)[source]¶
Return the underlying
icechunk.Sessionif any, elseNone.Looks up the session stashed on the group’s Zarr store at construction time (see
create_store()/open_store()). Works for root groups and any sub-group reached viaroot.create_group(...)/root[name]— they all share the same underlying Zarr store.Useful when callers need branch / snapshot operations that aren’t surfaced by the zarr-vectors API (creating branches, tagging, listing snapshots, etc.).
- zarr_vectors.building.create_resolution_level(root, level, level_metadata, *, strict=True)[source]¶
Create a new resolution level group within the store.
The level is listed in the root’s
multiscaleslayout viazarr_vectors.core.multiscale.upsert_level_transform(). Every level stores its vertices in level-0 coordinates, so the layout entry carries no transform; a coarse level’sbin_shapeandbin_ratiogo in its own levelzarr_vectorsobject, whereread_level_metadata()reads them.- Parameters:
root (Group)
level (int)
level_metadata (LevelMetadata)
strict (bool)
- Return type:
- zarr_vectors.building.get_resolution_level(root, level)[source]¶
Get an existing resolution level group.
- zarr_vectors.building.remove_resolution_level(root, level_index)[source]¶
Remove the coarsest resolution level from the store.
Level 0 cannot be removed. Nor can a level with a coarser one above it (levels must stay contiguous). Its
multiscaleslayout entry and everylinks/+k/link_attributes/<name>/+kfamily pointing at it go with it.
- zarr_vectors.building.list_resolution_levels(root)[source]¶
Return sorted level indices present in the store.
Resolution-level group names are bare integers (
0,1, …) under the 0.4.1+ layout (formerlyresolution_0/resolution_1). Top-level groups whose name doesn’t parse asintare some other entity (e.g.parametric/) and are silently skipped.
- zarr_vectors.building.list_available_ratios(root)[source]¶
Return bin ratios for all existing resolution levels.
- zarr_vectors.building.read_root_metadata(root)[source]¶
Read and parse root metadata from the store.
- Parameters:
root (Group)
- Return type:
- zarr_vectors.building.update_root_metadata(root, *, add_capabilities=(), **fields)[source]¶
Read-modify-write the root
zarr_vectorsblock.Same contract and same warning as
update_level_metadata().add_capabilitiesis separated out because stamping one is the common case and appending to a list through**fieldswould mean reading it first – which is the read-modify-write this exists to own.- Raises:
MetadataError – On an unknown field.
- Parameters:
- Return type:
- zarr_vectors.building.read_level_metadata(root, level)[source]¶
Read and parse level metadata.
A coarse level’s
bin_shapeandbin_ratioare read from its ownzarr_vectorsobject. A coarse level that records none gets level 0’s (bin_ratio1,bin_shapethe rootbase_bin_shape); at level 0 both are None.- Raises:
StoreError – If the level does not exist.
MetadataError – If metadata is malformed.
- Parameters:
- Return type:
- zarr_vectors.building.update_level_metadata(level_group, *, arrays_present=None, add_arrays_present=None, **fields)[source]¶
Read-modify-write one level’s
zarr_vectorsobject (kind: "level").There was nothing between
create_resolution_level()andread_level_metadata(), so a caller needing to correct a count or advertise an array after the fact reached around the API entirely – one consumer opened the store with raw zarr inside anexcept Exception: pass. This is the supported spelling.Coordinator-side: the level’s attrs are ONE blob shared by every array in it, so two concurrent callers race exactly the way
nonempty_chunksdoes. Call it once, after a parallel phase, not from inside one.- Parameters:
- Returns:
The level metadata as it now stands.
- Raises:
MetadataError – On an unknown field, or a derived one.
- Return type:
- zarr_vectors.building.stamp_ome_node(store, *, name=None)[source]¶
Add (or refresh) the RFC 8
omenode on an existing store.What makes a store nameable by an OME collection: a resolver following
{"type": "zarr", "path": "./x.zarrvectors"}fetches the rootzarr.jsonand looks for a legal node underome. Stores written before 0.9.2 carry none, and stores written since carry one already – calling this on either leaves a correct block, so it is safe to run over a whole directory of stores.Metadata-only, and the one upgrade in this format’s history that can be applied in place. Every prior version bump moved bytes, so the migration story was “rewrite from source”; this one only adds a root attribute, so a store is brought up to date without its data being read, let alone rewritten.
- Parameters:
- Returns:
The
omeblock as written.- Return type:
Metadata records and grid arithmetic¶
The metadata records, and functions that derive a level’s chunk shape, bin shape and grid from them.
- class zarr_vectors.building.RootMetadata(spatial_index_dims, chunk_shape, bounds, geometry_types, zv_version='0.10.0', crs=None, links_convention='implicit_sequential', object_index_convention='standard', cross_chunk_strategy='explicit_links', reduction_factor=8, base_bin_shape=None, cross_level_depth=1, cross_level_storage='explicit', format_capabilities=<factory>, required_capabilities=<factory>, attribute_specs=None, shard_shape=None, octree_sharding=None, manifest_layout=None, manifest_block_dtype=None)[source]¶
Bases:
objectRoot-level metadata for a ZV store.
- Parameters:
- zv_version¶
ZV specification version (renamed from
format_versionin 0.5.0 to disambiguate from Zarr v3’szarr_formatfield).- Type:
- spatial_index_dims¶
Axes definitions (NGFF / OME-Zarr style). On disk (format 0.10.0), axes live in the root
zarr_vectors.axes.
- __init__(spatial_index_dims, chunk_shape, bounds, geometry_types, zv_version='0.10.0', crs=None, links_convention='implicit_sequential', object_index_convention='standard', cross_chunk_strategy='explicit_links', reduction_factor=8, base_bin_shape=None, cross_level_depth=1, cross_level_storage='explicit', format_capabilities=<factory>, required_capabilities=<factory>, attribute_specs=None, shard_shape=None, octree_sharding=None, manifest_layout=None, manifest_block_dtype=None)¶
- class zarr_vectors.building.LevelMetadata(level, vertex_count, arrays_present, bin_shape=None, bin_ratio=None, chunk_shape=None, object_sparsity=1.0, coarsening_method='none', parent_level=None, chunk_dims=None, chunk_attribute_name=None, chunk_attribute_values=None, chunk_sources=None, preserves_object_ids=False, inherited_num_objects=None, shared_fragments=False, fragments_tile=False, link_fragments_aligned=False, octree_chunks=None)[source]¶
Bases:
objectPer-resolution-level metadata.
- Parameters:
- arrays_present¶
FAMILY names present at this level –
"vertices","vertex_attributes","links","object_index"– never"<family>/<name>". Readers gate on the family, so a per-name entry advertises nothing. Hand-maintaining this list is how it drifts (create_storelong declared[vertices]while also creatingvertex_fragments); preferzarr_vectors.building.refresh_arrays_present(), which derives it from what is actually on disk.
- bin_shape¶
Supervoxel edge lengths at this level (None for level 0, which inherits base_bin_shape from root).
- bin_ratio¶
Fold-change per axis relative to level 0. Float, not int: a coarsen factor may be fractional, and this is what becomes the NGFF
scale.compute_bin_ratiokeeps its integer contract for callers that want a whole fold.(1,1,1)for level 0,(2,2,2)for 2× coarser bins, etc.
- chunk_dims¶
Names of chunk-key axes, leading axis first. When
None(the default), chunk keys are spatial-only and havesid_ndimaxes (e.g.["dim0", "dim1", "dim2"]). When set, the first entries name non-spatial leading axes (e.g.["gene", "dim0", "dim1", "dim2"]).
- chunk_attribute_name¶
Name of the per-vertex attribute that is used as the leading chunk axis (single-axis attribute chunking; v1 supports only one).
Nonefor spatial-only.- Type:
str | None
- chunk_attribute_values¶
One label per leading-axis bin, in bin order.
chunk_attribute_values[i]is what a reader’sattribute_filternames to select the chunks with leading coordi, so its length is the bin count. A writer’s categorical bin is labelled by its value. A rechunk bin cut by edges is labelled by its lower edge, and a group bin by its group index (-1for ungrouped objects, the last bin).Nonefor spatial-only.- Type:
list[Any] | None
- chunk_sources¶
Where each value of a leading
"source"chunk axis lives, for a composite level whose objects reference fragments of other stores (seezarr_vectors.core.sources). Entry 0 is{"self": true}: this store’s own cells. Every other entry names a source –{"ref": {"path", "id"}, "level", "transform", "fingerprint"}– and a cell(s, *spatial)is the source’s cellspatialread through its transform.Nonefor an ordinary level.
- __init__(level, vertex_count, arrays_present, bin_shape=None, bin_ratio=None, chunk_shape=None, object_sparsity=1.0, coarsening_method='none', parent_level=None, chunk_dims=None, chunk_attribute_name=None, chunk_attribute_values=None, chunk_sources=None, preserves_object_ids=False, inherited_num_objects=None, shared_fragments=False, fragments_tile=False, link_fragments_aligned=False, octree_chunks=None)¶
- Parameters:
- Return type:
None
- zarr_vectors.building.compute_bin_shape(base_bin_shape, bin_ratio)[source]¶
Compute the bin shape at a coarser level.
- zarr_vectors.building.compute_bin_ratio(base_bin_shape, level_bin_shape)[source]¶
Compute the bin ratio from base and level bin shapes.
- zarr_vectors.building.get_level_bin_shape(root_meta, level_meta)[source]¶
This level’s ABSOLUTE bin shape.
The bin counterpart of
get_level_chunk_shape(), resolved in the order the store actually records things:level_meta.bin_shapewhen set – the authoritative absolute value;else
root.effective_bin_shape * level_meta.bin_ratio, because a level round-tripped through a store that had no NGFF translation keeps its ratio but loses its shape;else the root’s effective bin (level 0, or a level that does not bin).
bin_shapeis preferred overbin_ratiodeliberately: the ratio is the level-0-relative view and reconstructing an absolute from it is one multiplication further from the source of truth.- Parameters:
root_meta (RootMetadata)
level_meta (LevelMetadata | None)
- Return type:
- zarr_vectors.building.get_level_chunk_shape(root_meta, level_meta)[source]¶
Return the effective
chunk_shapefor a level.Resolves the v0.7 per-level override: when
level_metacarries a non-Nonechunk_shape, that value wins. Otherwise the level inheritsRootMetadata.chunk_shape. Passlevel_meta=Noneto get the root chunk_shape (useful when only the level index is known but the LevelMetadata hasn’t been read yet).- Parameters:
root_meta (RootMetadata)
level_meta (LevelMetadata | None)
- Return type:
- zarr_vectors.building.chunk_scale_factor(root_meta, level_meta)[source]¶
Deprecated alias for
chunk_scale_from_root().- Parameters:
root_meta (RootMetadata)
level_meta (LevelMetadata | None)
- Return type:
- zarr_vectors.building.chunk_scale_from_root(root_meta, level_meta)[source]¶
Return the per-axis integer multiple of ROOT
chunk_shape.For a level whose
chunk_shapeisr_i × root_chunk_shape[i]along axisi, returns(r_0, r_1, ..., r_{ndim-1}). A level that inherits root returns all-ones. RaisesMetadataErrorwhen the per-level chunk_shape isn’t an integer multiple of root along some axis (nesting violation).Root-relative, and named so.
coarsen_level’schunk_scale_factor=keyword is parent-relative — it multiplies the SOURCE level’s chunk_shape — so on a pyramid built with a repeated factor the two quantities diverge ([2, 2]gives parent-factors 2 and 2, but root-scales 2 and 4). While both were calledchunk_scale_factornothing at the call site distinguished them, and reading one as the other compounds silently. The old name remains as a deprecated alias.- Parameters:
root_meta (RootMetadata)
level_meta (LevelMetadata | None)
- Return type:
- zarr_vectors.building.level_chunk_scale(root_meta, level_meta, parent_meta)[source]¶
The PARENT-relative chunk factor – what
chunk_scale_factormeans.The chunk counterpart of
level_factor(). Contrastchunk_scale_from_root(), which answers the level-0-relative question and is whatLevelMetadatarecords.- Parameters:
root_meta (RootMetadata)
level_meta (LevelMetadata)
parent_meta (LevelMetadata | None)
- Return type:
- zarr_vectors.building.level_factor(root_meta, level_meta, parent_meta)[source]¶
The PARENT-relative bin factor – what
coarsen_factormeans.bin_ratiois level-0-relative andbin_shapeis absolute, so neither is the numbercoarsen_levelwants. This is that number.parent_metaisNonefor a level whose parent is level 0.- Raises:
MetadataError – If the per-axis factors are not uniform. The caller reduces this to a scalar (
coarsen_leveltakes one), so letting axis 0 speak for the rest would silently discard the others.- Parameters:
root_meta (RootMetadata)
level_meta (LevelMetadata)
parent_meta (LevelMetadata | None)
- Return type:
- zarr_vectors.building.validate_bin_shape_divides_chunk(chunk_shape, bin_shape)[source]¶
Validate that chunk_shape is an integer multiple of bin_shape.
- zarr_vectors.building.validate_level_chunk_shape_against_root(root_meta, level_meta)[source]¶
Cross-level invariants for a per-level
chunk_shapeoverride.Validates:
Per-axis positive integer multiple of root
chunk_shape(nested chunk grids).Per-axis divisibility by the effective per-level
bin_shapeso bins still tile chunks cleanly at the level’s resolution.
Self-consistency (positivity, rank match against root) is checked independently by
LevelMetadata.validate().Both this helper and that method are no-ops when
level_meta.chunk_shape is None.The no-op is deliberate and must stay. Extending the divisibility check to levels that INHERIT root’s
chunk_shapelooks like it would close a gap – a coarse level takes itsbin_shapefrom the coarsen factor while keeping root’s grid – but it rejects the normal case: a coarse level’s bin is routinely LARGER than the chunk it sits in (bin 200 in a chunk of 100), and “bins tile chunks” is only an invariant while bins are the finer of the two.- Parameters:
root_meta (RootMetadata)
level_meta (LevelMetadata)
- Return type:
None
- zarr_vectors.building.level_grid_layout(bounds, chunk_shape)[source]¶
Return
(origin, grid_shape)for a level’s single vlen arrays.zarr_vectors.spatial.chunking.assign_chunks()maps a position to the absolute coordfloor(pos / chunk_shape). When the data extends below the origin (negative positions), those coords are negative — which a 0-indexed Zarr array cannot hold directly. We therefore anchor the array atorigin = floor(min_corner / chunk_shape)(per axis) and store that offset on the array, so cellindex = coord - originand the array only needs to spanfloor(max_corner / chunk_shape) - origin + 1cells. Usingceil(max_corner / chunk_shape)would also be one short whenever a point lands exactly on a chunk boundary —floor(..) + 1is exact.
- zarr_vectors.building.compute_grid_shape(bounds, chunk_shape)[source]¶
Compute number of chunks per dimension.
Warning
This counts cell-widths across the extent (
ceil((hi-lo)/c)). It is not the allocation: bounds are inclusive, so a store spansfloor(hi/c) - floor(lo/c) + 1cells, which is larger wheneverhilands on a cell boundary orlodoes not. Usegrid_layout()to predict what a store will allocate.
Multiscale metadata and coarsening strategies¶
The NGFF multiscale metadata, and the registries for coarsening and selection strategies.
- zarr_vectors.building.read_multiscale_metadata(root)[source]¶
The root’s
multiscalesblock, or None if it has none.
- zarr_vectors.building.write_multiscale_metadata(root)[source]¶
Rewrite the layout to list exactly the store’s resolution levels.
- zarr_vectors.building.upsert_level_transform(root, level, *, scale=None, translation=None)[source]¶
Ensure
levelis listed in the multiscales layout.scaleandtranslationare accepted for compatibility and not stored: in format 0.10.0 every level’s transform is level 0’s, which is derived from the root’sbase_bin_shape(see the module docstring).
- zarr_vectors.building.get_level_scale(root, level)[source]¶
A level’s scale (level 0’s,
[1.0] * ndim), or None if unlisted.
- zarr_vectors.building.get_level_translation(root, level)[source]¶
A level’s translation (
base_bin_shape / 2), or None if unlisted.
Array allocation¶
Creating a level’s arrays before writing to them.
- zarr_vectors.building.create_vertices_array(level_group, dtype='float32', encoding='raw', *, exist_ok=True)[source]¶
Create the
vertices/array within a resolution level.
- zarr_vectors.building.create_attribute_array(level_group, name, dtype='float32', channel_names=None, ncols=None, extra_meta=None, *, exist_ok=True, register_family=False)[source]¶
Create a vertex attribute array
attributes/<name>/.- Parameters:
level_group (Group) – The resolution level FsGroup.
name (str) – Attribute name (e.g.
"radius","gene_expression").dtype (str) – Numpy dtype string.
channel_names (list[str] | None) – Optional list of channel names. Supplying these declares the width;
ncolsis only needed for a multi-column attribute whose channels are unnamed.ncols (int | None) – Columns per row.
None(default) infers fromchannel_names, else 1.extra_meta (dict[str, Any] | None) – Additional JSON-serialisable fields merged into the array metadata. Used for the dictionary-encoding convention (
encoding="dictionary",categories,ordered,_FillValue) and other userspace extensions. Keys collide-check against the core fields (zv_array,name,dtype,channel_names).exist_ok (bool)
register_family (bool)
- Return type:
None
- zarr_vectors.building.create_fragment_attribute_array(level_group, name, dtype='float32', channel_names=None, ncols=None, extra_meta=None, *, exist_ok=True, register_family=False)[source]¶
Create a fragment attribute array
fragment_attributes/<name>/.Per-chunk dense byte blob storing one row per fragment in the chunk; row count is derived from
vertex_fragments/<chunk>at read time. Optional storage layer — the common opt-in use case is materializing parent-IDs as attributes (e.g. the OID owning each fragment as a fragment attributeobject_id).- Parameters:
level_group (Group) – The resolution level FsGroup.
name (str) – Attribute name (e.g.
"object_id").dtype (str) – Numpy dtype string.
channel_names (list[str] | None) – Optional list of channel names. Supplying these declares the width;
ncolsis only needed for a multi-column attribute whose channels are unnamed.ncols (int | None) – Columns per row.
None(default) infers fromchannel_names, else 1. When provided, row shape becomes(num_fragments, len(channel_names)); otherwise rows are scalar.extra_meta (dict[str, Any] | None) – Additional JSON-serialisable fields merged into the array metadata. Same collision rules as
create_attribute_array().register_family (bool) – Add the family to the level’s
arrays_present. Off by default and deliberately so: that list lives in the level’s single shared attrs blob, so writing it from an allocator puts a read-modify-write of shared state inside the worker path – the same racerecord_presence=Falseexists to avoid. Coordinators should preferzarr_vectors.building.refresh_arrays_present(), which derives the whole list once. Use this only for a serial writer that wants allocation and advertisement to stay in step.exist_ok (bool) – When True (default), no-op if the array already exists. When False, raise
ArrayErroron conflict.
- Return type:
None
- zarr_vectors.building.create_object_index_array(level_group, *, exist_ok=True)[source]¶
Create the
object_index/array.
- zarr_vectors.building.create_object_attributes_array(level_group, name, dtype='float32', num_channels=1, *, exist_ok=True)[source]¶
Reserve the
object_attributes/<name>/slot.Under the 0.8.1 layout
write_object_attributes()creates the Zarr array on first write (it needs the shape and dtype of the data in hand), so this function only performs theexist_okconflict check —dtypeandnum_channelsare accepted for API compatibility but not persisted at create-time.- Parameters:
level_group (Group) – The resolution level FsGroup.
name (str) – Attribute name.
dtype (str) – Numpy dtype string (informational only in 0.8.1).
num_channels (int) – Number of channels (informational only in 0.8.1).
exist_ok (bool) – When True (default), no-op if the array already exists. When False, raise
ArrayErroron conflict.
- Return type:
None
- zarr_vectors.building.create_groupings_array(level_group, *, exist_ok=True)[source]¶
Reserve the
groups/slot.Under the 0.8.1 layout
write_groupings()creates the vlen Zarr array on first write, so this function only performs theexist_okconflict check.
- zarr_vectors.building.create_groupings_attributes_array(level_group, name, dtype='float32', num_channels=1, *, exist_ok=True)[source]¶
Reserve the
group_attributes/<name>/slot.Under the 0.8.1 layout
write_groupings_attributes()creates the Zarr array on first write, so this function only performs theexist_okconflict check.- Parameters:
- Return type:
None
- zarr_vectors.building.create_links_array(level_group, link_width, dtype='int64', *, delta=0, sid_ndim=None, offsets=None, directed=False, store='canonical', exist_ok=True)[source]¶
Create a
links/<delta>/<offsets>/array and its family group.To stamp the family policy without materialising any offsets array — a cross-only family, or a coordinator fixing policy before workers run — use
create_links_family()instead.Each
<delta>segment is a group; its children are one rank-D vlen array per distinct relative-offset segment, each cell holding the records whose source chunk is that cell.offsetsall-zero is the intra-chunk array (what was a standalonelinks/<delta>/array before the offset layout); non-zero offsets hold records whose other endpoints sit that far away — what used to becross_chunk_links/.Family-wide policy (
directed,store,sid_ndim,link_width) is stamped on the<delta>group, since several arrays now live under it and must agree. Per-array meta carries only what is needed to decode that array’s own cells.- Parameters:
level_group (Group) – The resolution level FsGroup.
link_width (int) – Number of vertex indices per link entry (L). 1 for skeleton parents, 2 for edges, 3 for triangle faces.
dtype (str) – Integer dtype.
delta (int) – Level delta; see
zarr_vectors.core.paths.sid_ndim (int | None) – Spatial index dims. Required when
offsetsis None so the intra segment can be derived.offsets (Sequence[tuple[int, ...]] | None) – The
link_width - 1relative offsets naming this array. Defaults to the all-zero (intra-chunk) offsets.directed (bool) – Endpoint order is data; see
zarr_vectors.spatial.boundary._cell_placements().store (str) –
"canonical"or"duplicate".exist_ok (bool) – When True (default), no-op if the array already exists. When False, raise
ArrayErroron conflict.
- Return type:
None
- zarr_vectors.building.create_links_family(level_group, *, delta=0, link_width=2, sid_ndim=None, directed=False, store='canonical')[source]¶
Stamp the
links/<delta>/family group’s policy, nothing else.directed/store/link_width/sid_ndimare family-wide: every offsets array under the delta decodes against them, which is why they live on the group and whywrite_links()refuses to flip them under surviving siblings.Use this when the policy must exist before any offsets array does — principally the decentralized flow, where a coordinator fixes the policy up front and workers then create only the offsets arrays their own records land in.
create_links_array()would otherwise force a family to materialise an arbitrary (usually intra) array purely to carry the group stamp, which a cross-only family does not want.Idempotent, and merges rather than overwrites: an existing group keeps any counts
finalize_links()left on it.- Raises:
ArrayError – If
storeis not"canonical"or"duplicate", or if the family already exists with a conflicting policy — silently re-stamping would strand every array already written under the old one.- Parameters:
- Return type:
None
- zarr_vectors.building.create_link_attributes_array(level_group, name, dtype='float32', *, delta=0, sid_ndim=None, link_width=2, offsets=None, exist_ok=True, row_shape=None)[source]¶
Create a
link_attributes/<name>/<delta>/<offsets>/array.Mirrors the matching
links/<delta>/<offsets>/array exactly — same delta, same offsets segment, same cells, same per-cell row order — so attribute rows align 1:1 with link records without storing a row id. There is no separate cross-chunk attribute family: an intra-chunk link’s attributes live under the all-zero offsets segment, just like the links themselves.exist_ok=True(default) makes the call idempotent; passexist_ok=Falseto raiseArrayErroron conflict.row_shapeis the tail shape of one row ([]for a scalar column,[k]forkchannels). Readers need it to reshape a bare cell, and the cell writers stamp it if it is missing; passing it here settles the array’s metadata in the one write that creates it, so later writes have nothing to restamp.
- zarr_vectors.building.create_link_segments(level_group, *, sid_ndim, directed=False, store='canonical', dtype='int64', include_intra=True, intra_dtype=None, attributes=None, intra_attributes=None)[source]¶
Allocate every segment a delta-0, two-endpoint link family writes.
Run by a coordinator before workers start, since concurrent array creation races on
zarr.json. Idempotently creates the family policy, onelinks/0/<offsets>array per neighbour offset (positive half for an undirected canonical family), the intra segment and its fragment sidecar withinclude_intra, and the parallellink_attributesarrays forattributes/intra_attributes({name: dtype}or{name: (dtype, row_shape)}).
- zarr_vectors.building.attribute_layout(level_group, name, *, scope='vertex')[source]¶
The
(dtype, ncols)an attribute array was written with.Resolution order, most authoritative first: the stamped
row_shape; thenlen(channel_names); then 1.dtypecomes from the stamped field, defaulting to float32.Offered because the column count was previously recoverable only by counting
channel_names, so every consumer carried its ownncols = len(channel_names) if channel_names else 1— and any consumer that forgot read a C-column attribute as C times as many scalar rows, silently.
Chunk I/O: vertices, fragments and attributes¶
Reading and writing one grid cell at a time, as an ingest worker does.
- zarr_vectors.building.open_write_session(level_group, *, compressor=None, shard_shape='inherit', bounds=None, chunk_shape=None, bin_count=None, durable=False)[source]¶
Open the write session used by every type writer.
Always activates the single-array layout: each per-spatial-chunk array (vertices, vertex_fragments, links/<delta>, link_fragments, vertex_attributes/<name>, …) is one multidim vlen-bytes Zarr array whose cells are spatial chunks (files at
<array>/c/i/j/k), and a batched-write context flushes every cell of an array in one concurrentset_coordinate_selection().boundsandchunk_shapeare required so the chunk-grid extent (and origin offset, for data with negative coords) can be sized upfront — that’s the shape of each vlen array.- Parameters:
level_group (Group) – The resolution-level group.
compressor (Any) – Forwarded to
Group.batched_writes(); also determines each array’s on-disk codec pipeline (None→ no compression, the default).shard_shape (int | tuple[int, ...] | None | Literal['inherit']) –
"inherit"(the default) takes the store’s own declaration, so a session opened against a sharded store stays sharded without every caller having to repeat the argument. An int (broadcast to every axis) or a per-axis tuple wraps the cells in thesharding_indexedcodec so many chunks pack into one storage object.Nonemeans explicitly unsharded, one storage object per spatial chunk.The
"inherit"sentinel keeps “I did not say” apart from “I said no”: only an explicitNoneasks for an unsharded array.bounds (tuple[list[float], list[float]] | None) –
(min_corner, max_corner)for the level — used to compute the chunk grid extent and origin.chunk_shape (tuple[float, ...] | None) – Physical chunk size per axis — paired with
boundsfor the grid extent.bin_count (int | None) – When the writer chunks by an attribute, every chunk key gains a leading attr-bin axis; pass the number of bins so the vlen array grid gets that extra leading axis (origin 0, extent
bin_count).durable (bool | str) – Forwarded to
Group.batched_writes(): on a local store, everything the session wrote is fsynced – each cell object before its rename – before the block returns."deferred"writes atomically without fsyncing; the caller makes the writes durable later withzarr_vectors.building.sync_store().
- zarr_vectors.building.list_chunk_keys(level_group, array_name='vertices')[source]¶
List all chunk coordinates that have data for an array.
- zarr_vectors.building.chunk_vertex_count(level_group, chunk_coords, *, default=0)[source]¶
How many vertex rows a chunk spans, without decoding any of them.
max(referenced row) + 1over the chunk’s fragment index — the length per-vertex attribute cells must be written at, and the row countread_chunk_vertex_buffer()returns for a buffer every row of which some fragment references.Reads only the fragment index, which is kilobytes; the alternative every consumer reaches for first — decode the vertices and call
len— decompresses the whole chunk for a number the index already carries, and via the plural readers it decodes each fragment’s rows again on top.Returns
default(0) when the chunk has no fragment index.
- zarr_vectors.building.read_chunk_vertices(level_group, chunk_coords, dtype=None, ndim=3, *, _leaf=False)[source]¶
Read all fragments from a spatial chunk.
Handles both range and explicit fragments: the full chunk buffer is read once and dispatched per fragment based on the
vertex_fragments/<chunk>index — range fragments are returned as contiguous slices, explicit fragments viafi.indices(f)gather.- Parameters:
level_group (Group) – Resolution level group.
dtype (dtype | str | None) – Numpy dtype.
None(the default) reads the dtype the store declares — seevertices_dtype(). Pass one only to override, and only knowing that a wrong value does not raise: afloat64cell read asfloat32decodes to garbage at twice the row count, silently.ndim (int) – Number of coordinate dimensions (D).
_leaf (bool)
- Returns:
List of arrays, each
(N_k, D).- Raises:
ArrayError – If the chunk does not exist or data is malformed.
- Return type:
- zarr_vectors.building.read_chunk_vertex_buffer(level_group, chunk_coords, dtype=None, ndim=3, *, default=<object object>, device=None)[source]¶
A chunk’s whole
(N, D)vertex buffer, in stored row order.The array every other per-chunk index is expressed against: fragments are row ranges or row gathers into it, links name row numbers in it, and per-vertex attributes align to it 1:1. Reading it is what a caller wants whenever the unit of work is the chunk rather than one object — a metric over every vertex, a position lookup by row number, a repack of the row order.
Not
read_fragment(level_group, chunk_coords, 0). That happens to be the same array whenever fragment 0 is a range covering the chunk, which is how a bulk vertex writer lays a level out — so the substitution works until it meets a level written per object, where fragment 0 is one object’s rows and the rest of the buffer is invisible through it. The failure is silent: short positions, short attribute cells, and a level that reads back as though it were never written.- Parameters:
level_group (Group) – Resolution level group.
dtype (dtype | str | None) – Element dtype.
None(the default) reads the dtype the store declares — seevertices_dtype().ndim (int) – Number of coordinate dimensions (D).
default (Any) – When supplied, returned instead of raising when the
verticesarray cannot be read at all. PassNonefor the common “soft-fail with None” pattern. A chunk nobody wrote is NOT a failure — it reads back as(0, D).device (str | None)
- Returns:
(N, D)array ((N,)whenndim == 1), ordefault.- Raises:
ArrayError – If the array cannot be read and no
defaultis given.- Return type:
- zarr_vectors.building.read_fragment(level_group, chunk_coords, fragment_index, dtype=<class 'numpy.float32'>, ndim=3, *, default=<object object>)[source]¶
Read a single vertex fragment from a chunk.
Dispatches on the
vertex_fragments/<chunk>index: range fragments use a byte-slice fast path – on an uncompressed array a byte-range read of just the fragment’s rows (Group.read_cell_range()), otherwise a slice of the whole chunk buffer; explicit fragments reshape the full chunk buffer and gather rows viafi.indices(fragment_index).- Parameters:
level_group (Group) – Resolution level group.
fragment_index (int) – Index of the fragment within the chunk.
ndim (int) – Number of coordinate dimensions.
default (Any) – When supplied, returned on read failure (missing chunk or out-of-range
fragment_index) instead of raising. PassNonefor the common “soft-fail with None” pattern. OnlyArrayErrorandStoreErrorare caught; programming errors propagate.
- Returns:
Array of shape
(N, D)(or(N,)whenndim == 1), ordefaultwhen supplied and the read fails.- Return type:
- zarr_vectors.building.read_attribute_fragment(level_group, attr_name, chunk_coords, fragment_index, dtype=None, ncols=None, *, default=<object object>)[source]¶
Read a single fragment’s per-vertex attribute rows from a chunk.
The attribute counterpart to
read_fragment(), and the same reason to prefer it:read_chunk_attributes(...)[k]decodes and copies every fragment in the chunk to hand back one of them, so a caller that wants only Core-1’s fragment 0 pays for every path-fragment twin appended after it. That cost grows as the store is written, which turns a fixed-size read into one that scales with how much of the surrounding volume has already been built.Semantics are identical to indexing
read_chunk_attributes()atfragment_index: rows are gathered by vertex index from the shared per-vertex buffer (range fragments as a contiguous slice, explicit fragments viafi.indices), flattened, then reshaped to honourncols.- Parameters:
level_group (Group) – Resolution level group.
attr_name (str) – Attribute name.
fragment_index (int) – Index of the fragment within the chunk.
ncols (int | None) – Number of columns (channels). Use 1 for scalars.
default (Any) – When supplied, returned on read failure (missing chunk or out-of-range
fragment_index) instead of raising. OnlyArrayErrorandStoreErrorare caught; programming errors propagate.
- Returns:
Array of shape
(N, ncols)(or(N,)whenncols == 1), ordefaultwhen supplied and the read fails.- Return type:
NDArray | Any
- zarr_vectors.building.read_chunk_attributes(level_group, attr_name, chunk_coords, dtype=None, ncols=None, *, vert_dtype=None, vert_ndim=None)[source]¶
Read vertex attribute data for a chunk.
Per-vertex attributes are stored one row per vertex, aligned 1:1 with the
verticesbuffer (Core-1’s fragment 0). Each fragment is gathered by vertex index from the shared attribute buffer via thevertex_fragments/<chunk>index — range fragments as contiguous slices, explicit fragments viafi.indices(f)— exactly asread_chunk_vertices()does. There is no contiguity requirement, so explicit path-fragment vertex-fragments (e.g. a downstream pipeline’s polyline twins appended on top of Core-1’s range) read correctly.- Parameters:
level_group (Group) – Resolution level group.
attr_name (str) – Attribute name.
ncols (int | None) – Number of columns (channels). Use 1 for scalars.
vert_dtype (dtype | str | None) – Retained for backward compatibility; ignored. Per-fragment sizes now come from the fragment index directly.
vert_ndim (int | None) – Retained for backward compatibility; ignored.
- Returns:
List of arrays aligned with fragments, each
(N_k, ncols)(or(N_k,)whenncols == 1).groups[0]is Core-1’s fragment 0 — the full per-vertex buffer for the chunk.- Return type:
list[NDArray]
- zarr_vectors.building.read_chunk_fragment_attributes(level_group, attr_name, chunk_coords, dtype=None, ncols=None, *, default=<object object>, device=None)[source]¶
Read per-fragment attribute data for a spatial chunk.
The on-disk layout is a dense per-chunk byte blob;
F(number of fragments) is derived from the byte length and the row stride (dtype.itemsize * ncols). No round-trip tovertex_fragmentsis needed.- Parameters:
level_group (Group) – Resolution level group.
attr_name (str) – Attribute name.
dtype (dtype | str | None) – Numpy dtype of the attribute.
None(the default) reads the dtype the array was written with.ncols (int | None) – Number of columns (channels).
None(the default) reads the stored width –row_shape, elselen(channel_names), else 1. An explicit value that contradicts the stored one raises.default (Any) – When supplied, returned on read failure (missing chunk, byte-length mismatch) instead of raising. Pass
Nonefor the common “soft-fail with None” pattern. OnlyArrayErrorandStoreErrorare caught; programming errors propagate.device (str | None)
- Returns:
Array of shape
(F,)(whenncols == 1) or(F, ncols)(whenncols > 1). Empty 1-D array when the blob is empty.- Return type:
NDArray | Any
- zarr_vectors.building.read_vertex_fragment_index(level_group, chunk_coords)[source]¶
Read and decode the
vertex_fragments/<chunk>blob.Returns the v0.6
ChunkFragmentIndexview describing how rows ofvertices/<chunk>partition into fragments.
- zarr_vectors.building.decode_fragment_index(blob)[source]¶
Decode a
vertex_fragments/link_fragmentscell’s bytes.The decode half of
read_vertex_fragment_index(), for bytes already held; returns the sameChunkFragmentIndex.
- zarr_vectors.building.write_chunk_vertices(level_group, chunk_coords, groups, dtype=<class 'numpy.float32'>, *, record_presence=True)[source]¶
Write fragments to a spatial chunk.
Encodes the groups as a contiguous byte buffer in
vertices/and writes a v0.6 fragment-index tovertex_fragments/describing each group as a contiguous range of vertex rows in source order.- Parameters:
- Returns:
(K,)int64 array of vertex byte offsets (kept for backwards- compatible signature; callers that need the v0.6 fragment-index should useread_vertex_fragment_index()).- Return type:
NDArray[int64]
- zarr_vectors.building.write_chunk_fragments(level_group, chunk_coords, new_fragments=None, *, csr=None, target='vertex', mode='replace', force_explicit=False, record_presence=True)[source]¶
Write fragment-index entries to
vertex_fragments/orlink_fragments/.Fragments come as
new_fragments((start, count)tuples and 1-D index arrays) orcsr=(indices, offsets); bytes matchencode_fragments().mode="append"concatenates after the stored fragments without re-encoding them ("replace"if none exist). Read-modify-write, last writer wins: serialise appends per chunk, and not insidebatched_reads.- Returns:
the new fragment indices (
[]for an empty append, which leaves the blob alone).csrform:(n_existing, n_new).- Return type:
List form
- Raises:
ArrayError – Invalid
target/mode, not exactly one fragment form, or malformed fragments.- Parameters:
- zarr_vectors.building.write_chunk_attributes(level_group, attr_name, chunk_coords, attr_groups, dtype=<class 'numpy.float32'>, *, record_presence=True)[source]¶
Write vertex attribute data for groups in a spatial chunk.
Attribute groups align 1:1 with fragments, so per-group byte offsets are derived at read time from
vertex_fragmentsand the attribute dtype/ncols. No sibling_offsetsblob is written.- Parameters:
level_group (Group) – Resolution level group.
attr_name (str) – Attribute name (e.g.
"radius").attr_groups (list[NDArray]) – List of arrays aligned with fragments. Each array is
(N_k,)for scalar or(N_k, C)for multi-channel attributes.record_presence (bool) – Whether to stamp this cell into the array’s
nonempty_chunksmanifest. Pass False when fanning per-chunk writes out concurrently, then rebuild the manifest once withGroup.derive_nonempty_chunks().
- Return type:
None
- zarr_vectors.building.write_chunk_fragment_attributes(level_group, attr_name, chunk_coords, data, dtype=<class 'numpy.float32'>, *, record_presence=True)[source]¶
Write per-fragment attribute data for a spatial chunk.
The on-disk layout is a single dense byte blob whose row count equals
num_fragments_in_chunk. Fragment count is not validated againstvertex_fragments/<chunk>at write time — the read side fails loudly on byte-length mismatch, so callers are trusted to pass a correctly-sized array. Replace-only at the chunk level.- Parameters:
level_group (Group) – Resolution level group.
attr_name (str) – Attribute name (e.g.
"object_id").data (NDArray) –
(F,)for scalar or(F, C)for multi-channel, whereFis the number of fragments in this chunk.dtype (dtype | str) – Numpy dtype to cast
datato before writing.record_presence (bool) – Whether to stamp this cell into the array’s
nonempty_chunksmanifest. PassFalsefrom concurrent per-chunk writers (the manifest is one array-wide attribute, so stamping it is a read-modify-write that races across processes) and re-derive it once afterwards viaFsGroup.derive_nonempty_chunks(). Seewrite_chunk_vertices()for the same pattern.
- Return type:
None
- zarr_vectors.building.stored_objects(level_group, array_name)[source]¶
The store keys of the objects a per-chunk array holds, sorted.
One per stored cell, or per shard when sharded, from a prefix listing on any store that lists; no object is read. The keys are those
cell_objects()names, so the two compare directly.
Links¶
Link paths (links/<delta>/<offsets>), per-cell readers and writers,
and the finalisation pass.
- zarr_vectors.building.links_path(delta, offsets)[source]¶
Path of a
links/<delta>/<offsets>/array within a level.offsetsis required: under the offset layout there is no single array atlinks/<delta>/to address, only the group (links_group_path()).
- zarr_vectors.building.links_group_path(delta=0)[source]¶
Path of the
links/<delta>/group within a resolution level.The group’s children are one rank-D vlen array per distinct offsets segment; see
links_path().
- zarr_vectors.building.link_attributes_path(name, delta, offsets)[source]¶
Path of a
link_attributes/<name>/<delta>/<offsets>/array.Mirrors
links_path()exactly — same delta, same offsets segment — so attribute cells align 1:1 with link cells.
- zarr_vectors.building.link_attributes_group_path(name, delta=0)[source]¶
Path of the
link_attributes/<name>/<delta>/group.
- zarr_vectors.building.intra_offsets(sid_ndim, link_width)[source]¶
The all-zero offsets identifying the intra-chunk array.
links/<delta>/<intra_offsets(...)>/is the array holding records whose endpoints all live in the same chunk — the family that was a standalonelinks/<delta>/array before the offset layout.
- zarr_vectors.building.is_intra(offsets)[source]¶
Whether every offset is zero (all endpoints in the source chunk).
link_width == 1(empty offsets) counts as intra: the single endpoint is by definition in the source chunk.
- zarr_vectors.building.parse_offsets(segment, *, sid_ndim, link_width)[source]¶
Inverse of
format_offsets().Returns the
link_width - 1offset tuples. RaisesValueErrorwhen the segment’s arity does not matchsid_ndim/link_width, so a malformed on-disk listing fails fast rather than decoding to the wrong geometry.
- zarr_vectors.building.link_family_policy(level_group, delta)[source]¶
(link_width, sid_ndim, directed, store)from the family group.Returns
Nonewhen the family carries no policy — an absent family, or one whose group attributes were never stamped — which callers treat as “nothing to read”.
- zarr_vectors.building.links_has_perm(offsets, *, delta, directed, store)[source]¶
Whether
links/<delta>/<offsets>/rows carry aperm_idxcolumn.perm_idxexists only to undo a canonical sort, so it is needed exactly whenzarr_vectors.spatial.boundary._cell_placements()may return a non-identity permutation. Storing it unconditionally would add 8 bytes to every intra-chunk link — the overwhelming majority of rows — for a value that is always 0.Keep this in lockstep with
_cell_placements: it is the single definition the writer and reader both consult to agree on the record width (Lcolumns, or1 + Lwhen this returns True).
- zarr_vectors.building.list_link_deltas(level_group)[source]¶
Sorted list of
<delta>values present underlinks/in a level.
- zarr_vectors.building.list_link_offsets(level_group, delta=0)[source]¶
Sorted offsets segments present under
links/<delta>/.links/<delta>is a group whose children are one array per distinct relative-offset segment, so this enumerates the whole family — the all-zero (intra-chunk) array included, since it is not a separate family any more.Uses
FsGroup.child_names(), not iteration:__iter__yields sub-groups only and these children are arrays – and notFsGroup.children(), which reads every segment array’s metadata to return names a store listing already has.
- zarr_vectors.building.list_link_attribute_offsets(level_group, name, delta=0)[source]¶
Sorted offsets segments under
link_attributes/<name>/<delta>/.Mirrors
list_link_offsets(); the attribute family is required to carry the same segments as the link family it parallels.
- zarr_vectors.building.iter_link_cells(level_group, delta)[source]¶
Yield
(segment, offsets, source_chunk, groups)for every cell.Enumeration order is the canonical one every reader shares: offsets segments sorted, then cells sorted within each.
groupsare the decoded physical row blocks — still carrying anyperm_idxcolumn, since callers differ on whether they want it.Offsets come from each array’s own
offsetsmeta when present, falling back to parsing the path segment; the two agree, but the meta needs nosid_ndimto decode.has_permlikewise comes from the array’s stamp, withlinks_has_perm()as the fallback.
- zarr_vectors.building.link_cells_within(level_group, within, *, delta=0, touching=False)[source]¶
The cells of
links/<delta>/whose records lie wholly inwithin.A reader scoped to some chunks – a bbox, a
chunks=whitelist, the chunks one object’s manifest names – keeps a record only if every endpoint is in a chunk it read, so a cell is worth fetching only when all of its endpoint chunks are inwithin. Which cells those are follows from the cell’s source chunk and its offsets segment alone (cell_endpoint_chunks()), so the answer costs no reads beyond the family listing and the presence manifest of each segment that survives.Without this a scoped read had nothing to go on but the whole family: one mesh patch at 10^6 vertices read every face in the level and spent 2.5 s of a 2.6 s read deduplicating their endpoints, to keep 242 of them.
- Parameters:
level_group (Group) – Resolution level group.
within (Iterable[tuple[int, ...]]) – Chunk coordinates, in the family’s
sid_ndimarity.delta (int) – Level delta. Only
0: a cross-level record’s endpoints sit on two different chunk grids, and one set of chunk coordinates cannot scope both.touching (bool) – Keep a cell when any of its endpoint chunks is in
within, not all of them. A skeleton reader needs this: a record whose child was read but whose parent was not is what tells it the child is a root there, and without the record the child silently inherits its fragment predecessor as parent. The source of such a cell may lie outsidewithin(canonical placement files a record under its lowest endpoint chunk), so candidates arewithinshifted back by each offset.
- Returns:
{offsets_segment: [cell_key, ...]}naming only cells that are present, cell keys sorted asread_link_arrays()visits them. Pass it toread_link_arrays(cells=...)and use it to build the prefetch plan, so the two agree on what is read.- Return type:
- zarr_vectors.building.cell_endpoint_chunks(src, offsets, scale_src, scale_trg)[source]¶
Reconstruct a cell’s L endpoint chunks from its source and offsets.
The inverse of the placement arithmetic in
partition_records_by_offset(): endpoint 0 is the source (its offset is the implicit zero and is never encoded), and endpoint k>0 isanchor(src) + o_k. The anchor makes this exact across levels whose chunk grids differ; it is the identity when they do not.
- zarr_vectors.building.link_endpoint_scales(level_group, delta, sid_ndim)[source]¶
The
(scale_src, scale_trg)pair the link placement arithmetic takes.Each is the per-axis integer multiple of the root
chunk_shapethat a level’s ownchunk_shaperepresents:scale_srcfor the levellevel_groupnames,scale_trgforlevel + delta. They exist because two levels of a pyramid built withchunk_scale_factor > 1index grids of different cell sizes, so their chunk coordinates cannot be differenced directly.Promoted because
cell_endpoint_chunks()is exported and needs these two, and until now the only way to obtain them was a private helper — an argument on a supported function with no supported provenance. Reconstructing them fromread_root_metadata()andchunk_scale_from_root()is possible but gets the padding rule wrong: a store chunked by an attribute prepends a bin axis to every chunk key, so the scales must be padded with leading 1s tosid_ndimor the rank check rejects the store. This is the same value the readers and writers anchor through, so a caller reconstructing a cell agrees with the code that placed it.- Parameters:
level_group (Group) – The level the source endpoint lives at.
delta (int) – Level delta of the link family —
0for links within one level, non-zero for cross-level ones.sid_ndim (int) – Rank of the chunk keys in this family, which is
link_family_policy(level_group, delta)[1]and may exceed the spatial rank on an attribute-binned store.
- Returns:
(scale_src, scale_trg), eachsid_ndimints. Both are all-ones when the metadata cannot be read or the target level does not exist yet. That is exactly right for a default pyramid and makes the anchor a no-op; it is wrong for one built withchunk_scale_factor > 1, so call this only once the target level and itsLevelMetadataare on disk.- Return type:
- zarr_vectors.building.read_links(level_group, *, delta=0, include_intra=True, select=None)[source]¶
Read every link record under
links/<delta>/.The whole-family counterpart to
write_links(), and the inverse of its placement: each cell’s source chunk plus the array’s offsets segment reconstruct the record’s endpoint chunks, andperm_idx(where present) reverses the canonical sort — so callers see the same record shape they wrote. Intra-chunk links are included by default; they are the all-zero-offsets array, not a separate family.Records are returned in (offsets segment, cell) sorted order, and within a cell in write order.
read_link_attributes()enumerates identically — that shared order is the only thing aligning attribute rows to link records, so the two must not drift.For a
store="duplicate"family each logical record was filed in several cells, so it is returned once per copy — dedupe, or query a single location withread_links_for_tuple().- Parameters:
level_group (Group) – Resolution level group.
delta (int) – Level delta.
include_intra (bool) – When False, skip the all-zero-offsets array — the per-chunk intra links — and return only records that cross chunks. A producer that keeps two populations in the one merged family (a per-chunk graph plus boundary crossings) wants only the second, and writes its attributes from that path alone: the attribute family then holds exactly the non-intra segments, so
include_intra=Falseis what restores row-for-row alignment withread_link_attributes().select (Sequence[int] | NDArray[integer] | None) – Sorted row indices to materialise, numbered over the rows this call returns — so
select=[i]names the same record asread_links(...)[i]under the sameinclude_intra. The arrays are decoded either way; what this skips is the per-record Python tuple construction, which is the whole cost of a large family (tens of millions of records take minutes to build, and a caller sampling a handful of them was paying all of it).Nonereturns every record.
- Return type:
Returns
[]when the<delta>family is absent or empty.
- zarr_vectors.building.read_links_for_tuple(level_group, chunk_tuple, *, delta=0)[source]¶
Read records that span exactly the L chunks in
chunk_tuple.The single-cell counterpart to
read_links(): the tuple resolves to exactly one(offsets, source)cell, so only that cell is fetched. See_link_tuple_cell()for how the tuple maps to it — in particular an undirected canonical family sorts the tuple internally (pass the chunks in any order), while a directed or duplicate family reads it as input order ((A, B)and(B, A)are different cells). An all-equal tuple reads that chunk’s intra-chunk links, which are no longer a separate family.len(chunk_tuple)must equal the family’slink_width.Returns
[]if no records exist for that exact L-tuple. Records are returned in write order, each in original input endpoint order (perm_idxis reversed for the caller).
- zarr_vectors.building.read_link_arrays(level_group, *, delta=0, include_intra=True, cells=None, link_fragments=None, device=None)[source]¶
Every link record under
links/<delta>/as two arrays.read_links()in array form:(chunks, vi)of shapes(M, L, sid_ndim)and(M, L), one row per record in exactly the orderread_links()returns them – offsets segments sorted, cells sorted within each, rows in write order – and with the input endpoint order restored fromperm_idx. Soread_links(...)[i]istuple(zip(map(tuple, chunks[i]), vi[i])).Offered because the per-record tuples are the cost of a large family: half a million faces took 8 s to build as tuples and a further 2 s to take apart again, for arithmetic – a chunk offset plus a local index – that is one gather over these arrays. A
store="duplicate"family returns each record once per copy, likeread_links().cellsrestricts the read to{offsets_segment: [cell_key, ...]}– typicallylink_cells_within()– and is what lets a scoped reader touch only the cells its chunks can reach.None(the default) reads every cell of every segment.link_fragmentsnarrows the intra-chunk cell at delta 0 further:{cell_key: [fragment, ...]}keeps only those link fragments of that cell, in the order given; cells it does not name are read whole. Only meaningful where the fragments partition the cell usefully – one per vertex fragment, on a level claiminglink_fragments_aligned– which is the caller’s to check.Returns empty
(0, 0, 0)/(0, 0)arrays when the family is absent or holds no rows.
- zarr_vectors.building.link_endpoints_to_rows(chunks, vi, chunk_offsets)[source]¶
Global row of every endpoint:
chunk_offsets[chunk] + vi.chunksandviare whatread_link_arrays()returns;chunk_offsetsis where each chunk’s rows start in a reader’s concatenation. An endpoint whose chunk the reader did not take is-1, which is how a bbox or cells filter reaches the records.
- zarr_vectors.building.read_link_attributes(level_group, attr_name, dtype=None, *, delta=0, device=None)[source]¶
Read every per-link attribute row under
link_attributes/<name>/<delta>/.The whole-family counterpart to
write_link_attributes(), and the attribute-side mirror ofread_links(): rows come back in (offsets segment, cell) sorted order, which is exactly the orderread_links()returns records, so attribute rowibelongs to link recordi. That shared enumeration is the ONLY thing aligning the two — nothing on disk ties a row to a record — so the two functions must not drift.- Parameters:
- Returns:
Array of shape
(num_links,)or(num_links, *row_shape); empty when the family is absent or holds no rows.- Return type:
NDArray
- zarr_vectors.building.read_chunk_links(level_group, chunk_coords, dtype=<class 'numpy.int64'>, link_width=None, *, delta=0, offsets=None)[source]¶
Read link groups from one cell of
links/<delta>/<offsets>/.The per-cell counterpart to
write_chunk_links(), and it mirrors its encoding rule exactly:chunk_coordsis the source chunk (the cell) andoffsetsnames the array. Defaults to the all-zero (intra-chunk) offsets — the array holding records whose endpoints all share the source chunk.Rows come back as stored, in placement order: this reader does not reverse a canonical sort. Where the array carries a
perm_idxcolumn (seelinks_has_perm()) the returned rows are1 + Lwide, withperm_idxin column 0 and theLvertex indices after it — and those indices are in the placement’s endpoint order, not the order they were written in. Useread_links()orread_links_for_tuple()for whole records in input order.- Parameters:
level_group (Group) – Resolution level group.
chunk_coords (tuple[int, ...]) – Source chunk coordinates (the array cell).
link_width (int | None) – The logical width L. If None, read from the family group’s metadata. Note the stored width may be
1 + L; this argument never changes how the bytes are decoded, which is governed by the array’s ownhas_permstamp.delta (int) – Level delta;
0is the intra-level family.offsets (Sequence[tuple[int, ...]] | None) – Relative offsets naming the array.
None(default) means the all-zero intra-chunk offsets.
- Returns:
List of arrays, each
(M_k, L)— or(M_k, 1 + L)when the array carriesperm_idx.- Return type:
- zarr_vectors.building.read_chunk_link_attributes(level_group, attr_name, chunk_coords, dtype=None, ncols=None, *, delta=0)[source]¶
Read per-link attribute data for a chunk’s intra-chunk links.
Mirrors
read_chunk_attributes()for the per-link case: the ragged bytes live underlink_attributes/<name>/<delta>/<all-zero offsets>/<chunk>and align 1:1 with the link fragments underlink_fragments/<chunk>.Intra-chunk at
delta == 0only, and not by omission: the fragment sidecar is keyed by chunk alone, so the all-zero-offsets array is the only one it partitions. Attributes on any other offsets array have no fragment structure to align to — read those withread_link_attributes(). Per-link groupkhas the same row count as link groupkinlinks/<delta>/<chunk>.- Parameters:
level_group (Group) – Resolution level group.
attr_name (str) – Attribute name (e.g.
"weight").dtype (dtype | str | None) – Numpy dtype of the attribute.
None(the default) reads the dtype the array was written with.ncols (int | None) – Number of columns (channels).
None(the default) reads the stored width –row_shape, elselen(channel_names), else 1. An explicit value that contradicts the stored one raises.delta (int) – Level delta; cross-level link attributes are stored differently and must be read via the whole-family
read_link_attributes()— this helper handles only the per-chunkdelta == 0case.
- Returns:
List of arrays aligned with the link fragments in the chunk.
- Return type:
list[NDArray]
- zarr_vectors.building.write_links(level_group, links, sid_ndim, *, delta=0, link_width=None, dtype=<class 'numpy.int64'>, mode='replace', directed=False, store='canonical', fragment_starts=None, _prepartitioned=None, _link_width=None, _num_records=None, _arrays=None)[source]¶
Write whole link records into
links/<delta>/<offsets>/._arraysis the same input aslinksin array form –(chunks, vi)of shapes(M, L, sid_ndim)and(M, L)– for a writer that holds its records that way already (the mesh and graph writers do); it saves building and taking apart one Python list per record. Passlinks=[]with it.The whole-family counterpart to
write_chunk_links(): it takes records in global(chunk_coords, vertex_idx)form, decides where each one belongs, and fans them out across the offset arrays. There is no separate cross-chunk family — a record whose endpoints all share one chunk lands in the all-zero-offsets array, one whose endpoints straddle chunks lands in the array named by the offsets between them.Each record is
link_widthendpoints.link_width=2(the default) encodes an edge,3a triangle face,1a parent→child reference used by pyramid metanode drill-down. Records may be passed as legacy 2-tuples or as endpoint lists.For
delta != 0, endpoint 0 is at the owning resolution level and endpoints k>0 are atthis_level + delta; the source is always endpoint 0 so offsets anchor against the owning level’s chunk grid (seeanchor_chunk()).- Parameters:
level_group (Group) – Resolution level group.
links (list[list[tuple[tuple[int, ...], int]]] | list[tuple[tuple[tuple[int, ...], int], tuple[tuple[int, ...], int]]]) – List of records; each a list of
(chunk_coords, vertex_idx)tuples of lengthlink_width.sid_ndim (int) – Number of spatial index dimensions.
delta (int) – Level delta; see
zarr_vectors.core.paths.link_width (int | None) – Endpoints per record. Defaults to the arity of the first record.
mode (Literal['replace', 'append']) –
"replace"(default) rewrites, from scratch, exactly the offset arrays this call’s records land in — see the warning below."append"adds the records as a new group in each target cell, leaving existing rows in place.directed (bool) – When
Trueendpoint order is data (streamline predecessor→successor, skeleton child→parent): records are NOT canonical-sorted, soA→BandB→Afile under opposite offsets (0.0.+1vs0.0.-1) and carry noperm_idx.store (Literal['canonical', 'duplicate']) –
"canonical"(default) files each record once, under the lexicographically-positive offset."duplicate"files it once per distinct incident chunk, so every record incident to a chunk can be found by scanning that chunk’s cell alone. Duplicated records are returned once per copy byread_links(); the parallel attribute family replicates identically via the returned partition.fragment_starts (Mapping[tuple[int, ...], NDArray[integer]] | None) – Per chunk, the first row of each of its vertex fragments, for a writer whose fragments are contiguous row ranges tiling the chunk. Each intra-chunk cell is then written as one link fragment per vertex fragment – fragment
kholding the records whose first stored endpoint is a row of vertex fragmentk, empty ones included – which is the partition spec §7.5 giveslink_fragments. Rows keep their input order within a fragment, and the returned partition follows the reordering, so link attributes still align.delta=0andmode="replace"only.None(default) writes each cell as a single fragment._prepartitioned (dict[tuple[str, tuple[int, ...]], Any] | None)
_link_width (int | None)
_num_records (int | None)
- Returns:
LinkPartitiondescribing where each input record landed.- Return type:
LinkPartition
Warning
mode="replace"scopes its delete to the offset arrays this call’s records actually target. It deliberately does not clear the wholelinks/<delta>/family: intra-chunk links live under it now, so a family-wide wipe would silently destroy everythingwrite_chunk_links()wrote. The corollary is that an offset array populated by an earlier call that this call’s records do not reach survives untouched — enumerate withlist_link_offsets()and delete explicitly if you need a broader wipe.- Concurrency:
mode="append"is read-modify-write per cell — safe across disjoint cells, unsafe within a single cell.
- zarr_vectors.building.write_link_cells(level_group, links=None, sid_ndim=None, *, chunks=None, vids=None, attributes=None, delta=0, link_width=None, dtype=<class 'numpy.int64'>, directed=False, store='canonical', allocate=True, record_presence=False)[source]¶
Write a batch of records into only the cells they touch.
Records come one of two ways:
links, a list with a Python object per endpoint, or as arrays –chunks(R, L, sid_ndim)andvids(R, L)– optionally with per-recordattributes{name: (R, *row_shape)}. The array form places records with array arithmetic and reads every cell it touches (links, their fragment sidecar, and each attribute) in one prefetch, then writes each array’s cells in one call: one read-modify-write per cell for the links and all their attributes together, where the list form pluswrite_link_attribute_cells()makes one per attribute. The store it leaves is the one those two calls leave. Device arrays are copied to the host once each.The decentralized counterpart to
write_links(): it leaves every other cell untouched and does not maintain the family-widenum_links/num_physical_recordscounts — callfinalize_links()once, after all workers finish, to reconcile them (and shard separately if desired).Placement routes through
_partition_links(), the same choke pointwrite_links()uses, so a batch lands in exactly the cells the whole-family writer would have chosen. That is what makes disjoint per-cell writes plus onefinalize_linksequivalent to a singlewrite_linksover the union of the batches.A coordinator must pre-create the family with matching
directed/store/sid_ndimviacreate_links_array()when workers run concurrently, and passallocate=Falseto assert it did. Withallocate=True(the default, and the historical behaviour) this creates the segment array idempotently from inside the per-bucket loop — so two workers whose records land in the same<offsets>segment race on the samezarr.json. Serial callers are unaffected and need change nothing.- Parameters:
allocate (bool) – When True (default) create each segment array on demand. When False, require it to exist already and raise
ArrayErrornaming the missing segment instead — the spelling for a worker whose coordinator pre-created the family.level_group (Group)
links (list[list[tuple[tuple[int, ...], int]]] | list[tuple[tuple[tuple[int, ...], int], tuple[tuple[int, ...], int]]] | None)
sid_ndim (int | None)
chunks (Any)
vids (Any)
delta (int)
link_width (int | None)
directed (bool)
store (Literal['canonical', 'duplicate'])
record_presence (bool)
- Return type:
LinkPartition
Returns the
LinkPartitionfor THIS batch — itsnum_linksis the batch’s logical record count, not the family’s — for use withwrite_link_attribute_cells().- Concurrency:
Per-cell read-modify-write. Safe only while workers own disjoint source chunks; two workers appending to one cell lose rows.
- zarr_vectors.building.write_link_attributes(level_group, attr_name, attr_data, *, num_links, delta=0, mode='replace', partition=None)[source]¶
Write per-link attribute data parallel to
links/<delta>/.The whole-family counterpart to
write_chunk_link_attributes(). Attribute rows are stored per(offsets, cell), one row per link record, in the same order the link writer used — that positional alignment is the whole contract.attr_datais in input order — the same ordering passed to the matchingwrite_links()call, whose returnedpartitionsupplies the mapping. Without apartitionthe writer re-derives one by reading the link records back, which only recovers on-disk order, soattr_datamust then already be in the enumeration orderread_links()returns (each offsets segment sorted, then each cell sorted).- Parameters:
level_group (Group) – Resolution level group.
attr_name (str) – Attribute name.
attr_data (NDArray) –
(num_links,)or(num_links, C)array in input order. Inmode="append"this is the NEW rows; the post-append total must equalnum_links.num_links (int) – Expected post-write logical record count (matches
LinkPartition.num_links).delta (int) – Level delta.
mode (Literal['replace', 'append']) –
"replace"(default) rewrites exactly the offset arrays the partition targets — same scoping rule, and same caveat, aswrite_links()."append"per-cell RMW.partition (LinkPartition | None) –
LinkPartitionfrom the matchingwrite_links()call. Required forappendand for anystore="duplicate"family.
- Raises:
ArrayError – If
modeis invalid, if the row count ofattr_datadoes not matchnum_links(replace) or the new-row count derived frompartition(append), or if the appended row shape does not match an existing array.- Return type:
None
- Concurrency:
mode="append"is read-modify-write per cell — safe across disjoint cells, unsafe within a single cell.
- zarr_vectors.building.write_link_attribute_cells(level_group, attr_name, attr_data, *, partition, delta=0, allocate=True, record_presence=True)[source]¶
Append attribute rows for the cells one batch wrote.
record_presence=Falseskips stamping each cell into the segment’s presence manifest, as the link writers do;finalize_links()rebuilds it.attr_dataholds one row per logical record in the SAME batch, in the input order used for the matchingwrite_link_cells()call;partitionis that call’s return value. Rows are appended per(offsets, cell), replicating automatically induplicatemode where one input index appears under several cells.Only
dtype/row_shapeare stamped here (idempotent across workers). The attribute family’snum_linksis deliberately left unstamped: a worker sees only its own batch, andread_link_attributes()derives the row count from the cells themselves.- Parameters:
allocate (bool) – As on
write_link_cells()— True (default) creates each segment array from inside the loop, which two concurrent workers hitting the same segment race on; False requires the coordinator to have pre-created it and raises otherwise. Note a pre-create loop written for thelinks/family does not cover this one:link_attributes/<name>/<delta>/…is a separate family and needs its own pass.level_group (Group)
attr_name (str)
attr_data (NDArray)
partition (LinkPartition)
delta (int)
record_presence (bool)
- Return type:
None
- zarr_vectors.building.write_chunk_links(level_group, chunk_coords, link_groups, dtype=<class 'numpy.int64'>, *, delta=0, offsets=None, link_width=None, record_presence=True)[source]¶
Write link rows to one cell of
links/<delta>/<offsets>/.chunk_coordsis the source chunk — the cell — andoffsetsnames which array underlinks/<delta>/receives them. Defaults to the all-zero (intra-chunk) offsets, which is the array that holds records whose endpoints all share the source chunk.This is the low-level per-cell writer:
link_groupsrows are written as given. Choosing the source chunk, computing the offsets and prepending anyperm_idxcolumn is the caller’s job — seezarr_vectors.spatial.boundary.partition_records_by_offset().Two encodings, selected by
delta == 0 and is_intra(offsets):flat + ``link_fragments/`` sidecar for intra-chunk links at delta 0. Readers derive per-group byte offsets from the cumulative group sizes (see
read_chunk_links()); link groups need not be 1:1 with the chunk’s vertex fragments.inline self-describing ragged blob otherwise — cross-offset records at any delta, and every cross-level record. These carry no fragment sidecar.
That condition reproduces both pre-merge layouts exactly: the intra array is byte-identical to the old
links/<delta>/, and every other offset array matches the oldcross_chunk_links/<delta>/cells.- Parameters:
level_group (Group) – Resolution level group.
chunk_coords (tuple[int, ...]) – Source chunk coordinates (the array cell).
link_groups (list[NDArray[integer]]) – List of arrays, each
(M_k, L).delta (int) – Level delta; see
zarr_vectors.core.paths.offsets (Sequence[tuple[int, ...]] | None) – Relative offsets naming the target array.
None(default) means the all-zero intra-chunk offsets.link_width (int | None) – Only used to derive the intra offsets segment when
offsetsis None andlink_groupsis empty.record_presence (bool) – Whether to stamp this cell into the array’s
nonempty_chunksmanifest. Decentralized workers pass False: the manifest is array-wide state, so stamping it is a read-modify-write that two workers racing on disjoint cells still lose keys to. They leave it to a coordinator’sfinalize_links(), which rebuilds it from the store listing once every worker has finished.
- Returns:
(K,)int64 array of link byte offsets.- Return type:
NDArray[int64]
- zarr_vectors.building.write_chunk_link_attributes(level_group, attr_name, chunk_coords, attr_groups, dtype=<class 'numpy.float32'>, *, delta=0, offsets=None, link_width=2)[source]¶
Write one cell of
link_attributes/<name>/<delta>/<offsets>/.Mirrors
write_chunk_links()cell-for-cell:chunk_coordsis the source chunk andoffsetsnames the same array underlink_attributes/<name>/<delta>/thatlinks/<delta>/receives the parallel records in. Rows are written as given, in the same order — that positional alignment is the whole contract, so there is no row id.Unlike the link cell there is no encoding branch: the payload is always a flat dense blob of
sum(M_k)rows. Per-group boundaries are recovered at read time from the parallel link cell — thelink_fragments/<chunk>sidecar for the intra array at delta 0, the links blob’s own inline header otherwise (seeread_chunk_link_attributes()).- Parameters:
level_group (Group) – Resolution level group.
attr_name (str) – Attribute name (e.g.
"weight").chunk_coords (tuple[int, ...]) – Source chunk coordinates (the array cell).
attr_groups (list[NDArray]) – List of arrays, each
(M_k,)or(M_k, C), aligned with the link groups in the parallel links cell.delta (int) – Level delta; see
zarr_vectors.core.paths.offsets (Sequence[tuple[int, ...]] | None) – Relative offsets naming the target array.
None(default) means the all-zero intra-chunk offsets.link_width (int) – Only used to derive the intra offsets segment when
offsetsis None.
- Return type:
None
- zarr_vectors.building.finalize_links(level_group, *, delta=0, attributes=True)[source]¶
Reconcile a
links/<delta>/family’s counts after decentralized per-cell writes.Scans every offsets array and every cell under the family to recompute
num_physical_records(total on-disk rows) andnum_links(the logical record count). For acanonicalfamily the two are equal; for aduplicateone the logical count is recovered by deduplicating decoded records, since every physical copy of a record decodes to the same input-order endpoints.Sharding is a separate coordinator step — run
zarr_vectors.sharding.shard_store()after finalizing, once all cells are on disk.Returns the re-derived
LinkPartitioninread_links()enumeration order (each offsets segment sorted, then each cell sorted).num_linksis the logical count andnum_physical_recordsthe physical one — the same two numbers stamped on the family group, which the returned partition must agree with.cell_indicesis positional over the physical rows, so understore="duplicate"its indices are row positions, not input indices, and must not be fed towrite_link_attributes().
Object index, manifests and object attributes¶
The index of which fragments belong to each object, and per-object attributes.
- class zarr_vectors.building.ObjectIndexAppender(level_group, base_oid, sid_ndim, fragment_group_oids, length_attr='length')[source]¶
Bases:
objectStream path objects onto an existing level group in batches.
See the module docstring for the why. Lifecycle:
app = ObjectIndexAppender(level_group, base_oid, sid_ndim, frag_oids) for manifests, lengths in batches: app.append(manifests, lengths) total_objects = app.close()
or as a context manager (
closeruns on exit):with ObjectIndexAppender(level_group, base_oid, sid_ndim, frag_oids) as app: app.append(manifests, lengths)
- Parameters:
level_group (FsGroup) – Resolution-level group to append into.
base_oid (int) – Truncate the object index + length array to this many objects on open, keeping object blobs
[0, base_oid)(the fragments) intact. New path objects are appended at OIDs>= base_oid.sid_ndim (int) – Number of spatial index dimensions (manifest encoding + object_index meta).
fragment_group_oids (Sequence[int]) – Object IDs for group 0 (the fragments). Written at
close().length_attr (str) – Name of the per-object length attribute.
- append(manifests, lengths)[source]¶
Append a batch of path objects.
Each
manifests[i]is one object’s ordered list of(chunk_coords, fragment_index)references — the shapewrite_object_indexaccepts per object — encoded internally as mode-0 single-fragment blocks.lengths[i]is that object’s int length.len(manifests) == len(lengths).
- zarr_vectors.building.object_count(level_group)[source]¶
How many objects this level declares, without decoding any of them.
- zarr_vectors.building.encode_object_manifest_blocks(blocks, sid_ndim, *, force_explicit=False)[source]¶
Encode one object’s manifest into the v0.6 block format.
- Parameters:
blocks (Sequence[tuple[tuple[int, ...], NDArray[integer] | tuple[int, int] | int]]) –
List of
(chunk_coords, fragment_ref)pairs. Each block names one spatial chunk and the fragment(s) the object owns inside that chunk.fragment_refmay be:an
int(single fragment index, mode 0),a
(start, count)tuple (contiguous range, mode 1), ora 1-D integer array (auto-detected: arange → range, otherwise explicit list).
sid_ndim (int) – Rank of the chunk-coordinate space. All
chunk_coordstuples must be of this length.force_explicit (bool) – If True, never auto-promote arrays to range.
- Returns:
The manifest bytes — a 4-byte block count followed by
Bper-block payloads. An empty list returns 4 bytes (B=0).- Return type:
- zarr_vectors.building.decode_object_manifest_blocks(raw, sid_ndim)[source]¶
Decode a v0.6 manifest blob into
(chunk_coords, fragment_ref)pairs.Each returned
fragment_refis one of:intfor mode-0 blocks,(start, count)tuple for mode-1 blocks,np.ndarray[int64]for mode-2 blocks.
Callers that prefer a uniform shape (e.g. always an array of indices) should map over the result.
- zarr_vectors.building.expand_manifest_blocks(blocks)[source]¶
Expand v0.6 manifest blocks to the legacy
[(chunk_coords, fragment_index), ...]tuple list.Mode-1 (range) and mode-2 (explicit list) blocks expand to one tuple per fragment so existing call sites that iterate
(chunk_coords, fragment_index)keep working unchanged. Callers that want the raw block representation can usezarr_vectors.encoding.fragments.decode_object_manifest_blocks()directly.
- zarr_vectors.building.read_object_manifests(level_group, *, ids=None)[source]¶
Read the manifests of specific objects.
read_all_object_manifestsdecodes every manifest in the store, which is the step that hangs on a large one: at twenty-one million objects it materialises and decodes twenty-one million Python manifests even when the caller needs a hundred. Naming the ids turns that into one coordinate selection.Downstream had to reach for the private
_expand_blocks, theOBJECT_INDEX_LAYOUT_V1sentinel and a rawzarr_group[...].get_coordinate_selectionto do this, which means a consumer pinned to three internals purely to avoid an O(N) decode.- Parameters:
- Returns:
{object_id: [(chunk_coords, fragment_index), ...]}. Ids that do not exist are simply absent, so a caller can pass a superset without pre-filtering.- Return type:
- zarr_vectors.building.read_object_manifests_csr(level_group, ids)[source]¶
The manifests of the objects
ids, as aManifestCSR.Row
ois theo-th id found, in the order asked; unknown ids are left out, as inread_object_manifests().- Parameters:
- Return type:
- zarr_vectors.building.commit_object_index(level_group, num_objects, *, sid_ndim=None, num_present=None, object_ids_sorted=None)[source]¶
Commit the object index’s metadata after manifest writes.
Merges into the existing metadata (see
write_object_manifests()):num_objects: the committed prefix (rows past it are residue a laterat=num_objectsappend replaces); may not exceed the rows written.layout: kept; an unstamped vlen index is stamped V1.sid_ndim: the argument, else the stamp, else the level’s.num_present: counted over committed rows unless given.object_ids_sorted: computed from the committed ids for an index that stores ids (V2 or dense), unless given.
- zarr_vectors.building.reserve_object_rows(level_group, n_objects, *, sid_ndim=None, layout=None, n_blocks=None, columns=None, shard_rows=None, block_dtype=None)[source]¶
Size the object layer for
n_objectsrows, once, before workers write.Creates empty, or grows (never shrinks), the object index in its layout (new:
layout, default the store’s), its id table, densemanifest_blockston_blocksrows (every worker’s aligned region), and each ofcolumns({name: dtype | (dtype, row_shape[, fill])}).shard_rows(a multiple of 65,536) shards new arrays, refused if the layer has another; denseblock_dtypemust match existing blocks. Leavesnum_objectstocommit_object_index().
- zarr_vectors.building.concurrency_contract(level_group=None)[source]¶
What several processes may write into one store at once.
shard_is_unit: per-chunk arrays may be written concurrently if each storage object (cell or shard) has one writer at a time; presence must be deferred (defer_presence) and recorded once afterwards.concurrent_at_ranges: after onereserve_object_rows(), the object layer may be filled bymode="place"ranges[at, at + n)at multiples ofat_alignment(the last may end at the reserved end); then onecommit_object_index.at_alignment/block_alignment: those multiples, for rows and denseblock_at(a new unsharded layer’s withoutlevel_group).
Not covered:
at=appends, metadata writes, and two processes writing one link cell.
- zarr_vectors.building.aligned_regions(counts, alignment)[source]¶
Start of each of several writers’ regions, each aligned.
For a coordinator assigning dense-index block regions (or row ranges of uneven size): writer
igets[starts[i], starts[i] + counts[i]), and the total to reserve isstarts[-1].
- zarr_vectors.building.is_dense_index(level_group)[source]¶
Whether the level’s object index uses the dense layout.
Decided by the
layoutstamp, else the arrays on disk;Falsewhen the level has no object index.
- zarr_vectors.building.read_all_object_manifests(level_group)[source]¶
Read all object manifests at once.
- zarr_vectors.building.read_object_vertices(level_group, object_id, dtype=<class 'numpy.float32'>, ndim=3)[source]¶
Read all vertex data for an object by following its manifest.
- zarr_vectors.building.write_object_index(level_group, manifests, sid_ndim, *, total_objects=None, layout=None, block_dtype=None)[source]¶
Write object index: object_id → ordered fragment references.
- Parameters:
level_group (Group) – Resolution level group.
manifests (dict[int, list[tuple[tuple[int, ...], int]]]) –
{object_id: [(chunk_coords, fragment_index), ...], ...}. Sparse — OIDs absent from the dict get empty manifests.sid_ndim (int) – Number of spatial index dimensions.
total_objects (int | None) – Number of OID slots to write. When provided, the dense manifest list spans
range(total_objects)even if the largest OID present is smaller — used by the ID-preserving pyramid regime, where surviving OIDs are a sparse subset of the parent’s OID space. WhenNone(default), there is one row per id inmanifests.layout (str | None) –
"vlen"or"dense"(seezarr_vectors.core.dense_manifests).Nonekeeps the index’s current layout, or takes the store’smanifest_layoutfor a new one.block_dtype (Any) – Dense only:
"int64"or"int32"formanifest_blocks.Nonekeeps a dense index’s current dtype, or takes the store’smanifest_block_dtype. This rewrites every array, so it may change it.
- Raises:
ArrayError – When
total_objectswould add more thanOBJECT_INDEX_MAX_ROWSrows with no object in them, or a block does not fit anint32index.- Return type:
None
- zarr_vectors.building.write_object_manifests(level_group, manifest_blobs=None, *, chunk_coords=None, fragment_idx=None, manifest_offsets=None, ids=None, mode='replace', at=None, layout=None, block_at=None, block_dtype=None)[source]¶
Write object manifests to the level’s object index.
Give the manifests one of two ways:
manifest_blobs: already-encoded blobs, one per object, in object order (encode them withencode_object_manifest_blocks());as arrays: object
oowns blocksmanifest_offsets[o]:manifest_offsets[o + 1], blockbnaming fragmentfragment_idx[b]of chunkchunk_coords[b]. Withoutmanifest_offsetsevery object owns one block. Encoded with no Python object per object, to the same bytes; device arrays are copied to the host once each.
The index is vlen (one blob per object) or dense (fixed-width integer arrays; see
zarr_vectors.core.dense_manifests). An existing index keeps its layout; a new one takeslayout, or the store’smanifest_layout. On a dense index the array form is written as it is – no blob per object is ever built, and device arrays are copied to the host once each.Only the manifests (and, on an index that stores ids, the id table) are written: committing the index’s metadata (
num_objectsand the rest) stays the caller’s step, whichcommit_object_index()is.- Parameters:
level_group (Group) – Resolution level group.
manifest_blobs (Any) – Encoded manifests (list of bytes or object array).
chunk_coords (Any) –
(M, sid_ndim)block chunk coordinates.fragment_idx (Any) –
(M,)block fragment indices.manifest_offsets (Any) –
(n + 1,)CSR offsets of blocks per object.ids (Any) – Object ids of the rows written, for an index that stores ids rather than using rows as ids; see below.
mode (str) –
"replace"rewrites every row."append"extends the existing array, touching only the zarr chunks the new rows fall in — the write a per-chunk emitter wants, since replacing costs the whole index once per chunk."place"writes rows[at, at + n)of an index sized byreserve_object_rows()and nothing else – no resize, no padding, no metadata – so several processes may place disjoint, aligned ranges at once (seeconcurrency_contract()).at (int | None) – Row index the appended blobs must start at (
mode="append"only). Pass the object-id being claimed so a torn previous flush cannot shift ids;Noneappends at the current end.layout (str | None) –
"vlen"or"dense"for an index this call creates.block_at (int | None) –
mode="place"on a dense index: the first row ofmanifest_blocksthis call’s fragments occupy.block_dtype (Any) – Dense only:
"int64"or"int32", the dtype of themanifest_blocksthis call creates (default: the store’smanifest_block_dtype, else int64). An index keeps the dtype it was created with: an append or a placement into it refuses another value,mode="replace"rewrites it in the one given (else the one it had). Every block written into an int32 index is checked, and one that does not fit raisesArrayErrorbefore anything is written. Ignored for a vlen index.
- Return type:
On an index that stores its object ids (layout V2), an append extends the id table with
ids, or with the rows when the table is simply the rows; otherwise it raises, where it used to add rows with no id that a read by id could not find.
- zarr_vectors.building.patch_object_manifests(level_group, updates, sid_ndim)[source]¶
Replace named rows of
object_index/manifests, leaving the rest.write_object_index()rewrites every row, so changing one object’s manifest costs the whole index: on a 400,000-object store a singleedit_vertexspent 3.3s and 414 MB doing it, and both figures grow with the object count rather than with the edit. This touches only the zarr chunks the named rows fall in.num_presentis adjusted by the difference between the rows being replaced and the rows replacing them, so it stays exact without a full decode. The array grows when an id runs past the end, padded with empty manifests exactly as a full rewrite would.- Parameters:
level_group (Group) – Resolution level group.
updates (dict[int, list[tuple[tuple[int, ...], int]]]) –
{object_id: [(chunk_coords, fragment_index), ...]}for the objects whose manifests changed. An empty list blanks that object, which is how a removal is recorded.sid_ndim (int) – Number of spatial index dimensions.
- Return type:
None
- zarr_vectors.building.read_object_attributes(level_group, attr_name, dtype=None)[source]¶
Read dense O×C object attribute data.
Returns the raw array values, including any sentinel positions for absent rows. Use
read_object_attribute_present_mask()to reconstruct a 0/1 mask, or compare directly againstlevel_group.read_array_fill_value(...).
- zarr_vectors.building.read_object_attribute_present_mask(level_group, attr_name)[source]¶
Reconstruct the
(O,)byte present-mask for an object attribute.The 0.8.1 layout stores absence in-band via
fill_valuerather than as a siblingpresent_maskarray, so this reader compares each row against the stored fill on the fly. A row counts as “absent” only if every channel equals the sentinel.
- zarr_vectors.building.write_object_attributes(level_group, attr_name, data, *, present_mask=None, fill_value=None, mode='replace', at=None)[source]¶
Write dense O×C object attribute data as a single Zarr v3 array.
The array is stored at
object_attributes/<attr_name>as a standard chunked Zarr v3 array. Absent rows (selected bypresent_mask) are encoded in-band usingfill_value— no siblingpresent_maskchild array is written. Stock Zarr v3 tooling can read the array without library-specific decoding; absent positions are visible as the array’sfill_value(also returned for any chunk that was never written).- Parameters:
level_group (Group) – Resolution level group.
attr_name (str) – Attribute name.
data (NDArray) –
(O,)or(O, C)array. Inmode="append"this is the NEW rows to append.present_mask (NDArray | None) – Optional
(O,)byte array (0/1per object) marking real rows. When provided, absent rows (mask[i] == 0) are overwritten withfill_valuebefore write; callers that already encoded sentinels indatashould leave thisNone.fill_value (Any) – Sentinel for absent positions. Defaults to NaN for floats, dtype-min for signed ints, dtype-max for unsigned ints (see
_default_fill_value_for_dtype()). Used both as the in-array sentinel for masked rows and as the array’s persistedfill_value.mode (Literal['replace', 'append', 'place']) –
"replace"(default) writesdataas the full array."append"reads the existing array, concatenatesdataalong axis 0, writes back. Existing dtype wins on dtype mismatch (new rows are cast)."append"against a missing attribute behaves like"replace".at (int | None) – Row index the appended rows must start at (
mode="append"only) — the object-id being claimed. The attribute-side twin ofwrite_object_manifests()’sat, and the reason to pass it is the same: nothing on disk ties a row to an object, so rowimeans objectiby position alone, and a column that drifted from the index silently rebinds every later append to the wrong object. A column short ofatis padded withfill_value; a column reaching past it (the residue of a flush killed before it committed, whose rows no reader can address) is truncated back toat.Noneappends at the current end. Withmode="place", the first of the reserved rows[at, at + n)to write in place (seewrite_object_attribute_columns()).
- Raises:
ArrayError – If
modeis invalid,atis negative or given withmode="replace",present_masklength mismatchesdata, the dtype has no default sentinel and nofill_valueis given, or the appended row shape (everything beyond axis 0) does not match the existing array.- Return type:
None
- Concurrency:
mode="append"is read-modify-write and NOT cross-writer-safe. Callers must serialise concurrent appends to the same attribute.atmakes a serialised writer idempotent — a retry lands on the same rows — it does not make concurrent writers safe.
- zarr_vectors.building.object_manifest_writer(level_group, at=None, *, layout=None, commit=False, block_dtype=None)[source]¶
A context that writes object manifests as a stream.
- Parameters:
at (int | None) – The first write’s row, with
at=’s append meaning (pads a short index, truncates residue past it, even on an empty first write);Noneappends at the current end.layout (str | None) –
"vlen"or"dense", for an index the first write creates.commit (bool) – On a clean exit, commit
num_objectsas the last write’s end (commit_object_index()).block_dtype (Any) –
"int64"or"int32", aswrite_object_manifeststakes it; every write’s blocks are checked against the index’s dtype.level_group (Any)
- Returns:
An
ObjectManifestWriter; itswritetakes whatwrite_object_manifeststakes, lessmode/at/layout.- Return type:
- class zarr_vectors.building.ObjectManifestWriter(level_group, at=None, *, layout=None, commit=False, block_dtype=None)[source]¶
Bases:
objectStream object manifests into a level’s object index.
Made by
object_manifest_writer(); use it as a context:with object_manifest_writer(level, at=committed) as w: for block in blocks: w.write(chunk_coords=..., fragment_idx=..., manifest_offsets=...)
Leaving the block writes what is held and, with
commit=True, commits the count; leaving it by an exception writes nothing more, so rows already written stay past the committed count, as a torn flush’s do, for the next append at that count to replace.- close()[source]¶
Write what is held, then commit if asked. Returns
(first_row, rows written), orNoneif nothing was written.
- zarr_vectors.building.build_fragment_owner_index(store_path, *, level=None)[source]¶
Record which object owns each fragment, as a readable column.
Writes
fragment_attributes/object_id, the slot the format already reserves for it. With the column in place “which objects reference this fragment” is one cell read; without it, the only way to answer is to decode every manifest in the level, which is what an edit session does on its first lookup and what four other places in this package each reinvent.Offered as a maintenance verb rather than run by the writers, because building it costs a full manifest scan and every consumer falls back cleanly when it is absent. Re-running it is safe; it rewrites whatever it finds.
Object groups¶
Named sets of object ids and their names.
- zarr_vectors.building.read_all_groupings(level_group)[source]¶
Read all group memberships.
- Returns:
List indexed by group_id. Each entry is a
list[int]for an explicit group, or arangefor an implicitly-stored contiguous group (seewrite_groupings()).- Parameters:
level_group (Group)
- Return type:
- zarr_vectors.building.read_group_object_ids(level_group, group_id)[source]¶
Read the object IDs belonging to a group.
- Parameters:
- Returns:
The member object IDs. A group written from a
range(seewrite_groupings()) is returned as arange— O(1) rather than materialising up to a billion ints. Explicit groups are returned as alist[int]. Both supportlen(), indexing and iteration.- Return type:
- zarr_vectors.building.read_groupings_attributes(level_group, attr_name, dtype=None)[source]¶
Read dense G×C groupings attribute data.
- zarr_vectors.building.write_groupings(level_group, groups)[source]¶
Write group memberships as a single vlen-bytes Zarr v3 array.
Each row of the array at
groups/is the byte-serialised int64 member list of one group, addressable by integer index. This replaces the legacygroups/data+groups/offsetsCSR pair with the same vlen layout already used byobject_index/manifests.A group whose members form a contiguous
range(start, stop)may be passed as arangeobject. It is stored implicitly as a[start, stop)descriptor in the array’sgroup_rangesattribute (with an empty placeholder row), so a billion-member contiguous group costs O(1) on disk and in memory instead of an 8-byte-per-member int64 list. Explicit (non-range) groups keep their exact byte layout, so older stores remain readable.
- zarr_vectors.building.write_groupings_attributes(level_group, attr_name, data)[source]¶
Write dense G×C groupings attribute data as a single Zarr v3 array.
Stored at
group_attributes/<attr_name>as a standard chunked Zarr v3 array. Unlikewrite_object_attributes(), no sentinel / present-mask handling — groupings attributes are always fully populated.
Presence manifests and array inventory¶
Coordinator functions: what is on disk, and rebuilding the
nonempty_chunks and arrays_present records after a parallel write.
defer_presence() declares a level deferred
before workers start; rebuild_presence()
writes the records and ends the deferral. Workers can instead use
Group.collect_presence
and apply_presence(). See
HPC pipelines.
- zarr_vectors.building.defer_presence(level_group)[source]¶
Declare this level’s presence deferred to one coordinator rebuild.
For many workers writing one level:
nonempty_chunksis one attribute per array, so concurrent stamps race. Every per-chunk array drops its manifest, arrays allocated later are born without one, and writes into them stamp nothing, whateverrecord_presencesays. Readers ask the store instead, except offline-read sessions, stores that cannot list and zarr-vectors older than 0.9.3, which see nothing untilrebuild_presence()(orset_presence()) writes the manifests and clears the declaration. Call it before workers open the level: a handle opened earlier still allocates arrays with a manifest.
- zarr_vectors.building.refresh_arrays_present(level_group)[source]¶
Re-derive the level’s
arrays_presentfrom what is on disk.arrays_presentis hand-listed at every write site, so it drifts: an ordinarywrite_pointsdeclared["vertices", "vertex_attributes"]whilevertex_fragmentssat on disk undeclared, and no allocation function registers anything at all. A reader that gates on the list therefore cannot see arrays that exist.This walks the level instead and writes back the FAMILY names found – the granularity every reader actually tests. The single owner of the field; a coordinator calls it once after a parallel phase, alongside
rebuild_presence().Returns the sorted family names now recorded.
- zarr_vectors.building.rebuild_presence(level_group, array_name=None, *, on_sharded='derive')[source]¶
Rebuild
nonempty_chunksfrom the store — one array, or the level.The coordinator half of decentralised writing: workers writing disjoint cells pass
record_presence=Falsebecause the manifest is one attribute shared by every cell, so stamping it races. This rebuilds it once, afterwards.Covers sharded arrays. It did not, and defaulted to
"skip", while a sharded array’s manifest could not be rebuilt from a per-cell listing — safe then, because sharding ran after the rebuild by contract, so anything sharded was already correct. A store can now be born sharded, and under that premise “skip” quietly declined to repair the arrays most in need of it.The level-wide form also ends a
defer_presence()declaration, once every manifest is written: arrays allocated afterwards get a manifest again, and stamps resume. The single-array form leaves the declaration alone.- Parameters:
array_name (str | None) – One array’s path, or
None(the default) to walk every per-chunk array in the level — the shape a coordinator actually needs after a parallel phase.on_sharded (str) – Forwarded to
Group.derive_nonempty_chunks()."derive"(the default) rebuilds sharded arrays like any other;"skip"leaves them alone;"raise"asserts none are sharded.level_group (Group)
- Returns:
The sorted keys recorded, for the single-array form; for the level-wide form, every per-chunk array path walked. Under
on_sharded="skip"a sharded array is left alone and therefore absent, so the return still says what was actually rebuilt.- Return type:
- zarr_vectors.building.set_presence(level_group, cells, *, end_deferral=False, verify=None, on_mismatch='raise')[source]¶
Record each named array’s presence as exactly the cells given.
For a coordinator that knows which cells its workers filled, instead of
rebuild_presence()reading the store back.cellsmaps array name to"i.j.k"keys or tuples, in absolute chunk coordinates; it must be the union over all workers, name every array they wrote and be passed once they finish. Unnamed arrays are left alone. Every key is validated before anything is written:StoreErrorfor an array that is not per-chunk here,ArrayErrorfor a key outside its grid.verify="objects"first checks one listing per array: claimed objects are stored, every stored object holds a claimed cell, and a partly claimed shard’s other cells are empty."index"also requires each claimed cell of a shard to hold a payload. On a mismatch,on_mismatch="raise"raisesPresenceMismatchErrorbefore writing;"derive"takes the failing arrays from the store.end_deferralthen callsend_presence_deferral(). Returns the array names written, sorted.
- zarr_vectors.building.end_presence_deferral(level_group, *, missing='raise')[source]¶
End the level’s
defer_presence()declaration.For a coordinator that recorded presence itself (
set_presence(), or a rebuild split across processes);rebuild_presence()ends it on its own. Arrays allocated afterwards get a manifest, and stamps resume.- Parameters:
- Returns:
The arrays derived under
missing="derive"(empty otherwise).- Return type:
- exception zarr_vectors.building.PresenceMismatchError(mismatches)[source]¶
Bases:
StoreErrorSupplied presence does not match what the store holds.
Raised by
set_presence(..., verify=...)before anything is written.mismatchesmaps each array that failed to what was found:{"missing": [...], "extra": [...], "extra_objects": [...]}– claimed cells the store does not hold, held cells no claim names (chunk keys), and stored objects holding no claimed cell (store keys).- Parameters:
mismatches (dict)
- Return type:
None
- zarr_vectors.building.per_chunk_array_paths(level_group)[source]¶
Every per-spatial-chunk array path in
level_group, recursively.Walks the hierarchy rather than guessing names: the link families nest two levels deeper than everything else, and their
<offsets>segments are discoverable only by listing. Excludes the arrays with no spatial chunk grid —object_index,object_attributes/…,groups,group_attributes/…— which have no presence manifest.Walks via
Group.children()/Group.standalone_array_exists()rather than the underlying zarr group’sarray_keys/group_keys: those go straight to the backing store, missing the node cache and the offline-read snapshot every other read here passes through.Offered because a consumer that needs it otherwise re-implements both this walk and the private
_is_per_chunk_array()it depends on, and a fork of a private predicate is a fork nobody diffs.
- zarr_vectors.building.array_is_sharded(level_group, array_name)[source]¶
Whether ONE ARRAY is stored with the native sharding codec.
Takes a name, not a resolved zarr node. The internal helper takes the node, which means a caller has to obtain one — and obtaining one is exactly the reach past the API that this module exists to remove.
Named for the array, not for the store, because
zarr_vectors.sharding.io.is_sharded()answers a different question — “does any array in this store shard?” — over a store path. While both were spelledis_shardeda caller who swapped one import line for the other got no error: the path went in aslevel_group, the lookup failed, and the old bareexceptreturnedFalse. For a whole store that is a plausible answer, so nothing surfaced. Useget_shard_info()for the store-wide question; it is already exported here.
- zarr_vectors.building.is_sharded(level_group, array_name)[source]¶
Deprecated alias for
array_is_sharded().
- zarr_vectors.building.cell_objects(level_group, array_name, chunk_coords)[source]¶
The store key of the object holding each of these cells.
One key per cell, in order: the cell’s own object when unsharded, the shard holding it when sharded. Keys are relative to the store root.
- zarr_vectors.building.shard_object_layer(level_group, shard_rows)[source]¶
Repack a level’s object layer into shards of
shard_rowsrows.The object layer (
object_index’s arrays and everyobject_attributes/<name>column) is chunked in fixed row buckets (16,384 index rows, 65,536 attribute rows); sharding packsshard_rows // bucketbuckets per storage object.shard_rowsmust be a multiple of 65,536;Noneunshards. Sharding is zarr’s ownsharding_indexedcodec, and later columns follow the existing layout (zarr_vectors.core.arrays.object_shard_rows()).Each array is streamed block by block into a sibling that then replaces it. A coordinator operation: nothing else may write the object layer meanwhile.
- zarr_vectors.building.shard_transaction(level_group, shard_coords, *, arrays=None, mode='replace', durable=True, io_threads=None, sweep=True, prefetch=False)[source]¶
Stage one shard’s cell writes privately, and publish them on exit.
A context manager. Every cell written inside it must lie in shard
shard_coords(shard_of()) ofarrays(default: every per-chunk array), elseShardOwnershipError.mode="replace"rebuilds each owned shard from the staged cells alone (unwritten owned cells read empty);"merge"merges into what is stored. On exit each changed shard is written as a.partial(fromio_threadsthreads) and renamed into place once all are written; an exception publishes nothing.durable=Truefsyncs every partial (all together, after the writes) before the renames, then the directories;durable="deferred"does not, leaving it to a latersync_store(). Atomic per object: after a crash, re-running the task converges. Needs presence deferred (defer_presence()) and every array allocated and sharded first; writes no metadata (tx.writtenfeedsset_presence()).sweepremoves a failed attempt’s.partialfiles on entry.prefetch(mode="merge") reads every owned shard whole in the background on entry and serves owned-cell reads and the publish’s merge from it; a shard whose every cell is rewritten is not read. Same bytes either way. Seezarr_vectors.core.shard_txn.
- zarr_vectors.building.shard_of(level_group, chunk_coords, array_name='vertices')[source]¶
The index of the shard holding cell
chunk_coordsofarray_name.What
shard_transaction()takes. A level’s arrays normally share grid origin and shard shape, so one answer serves them all.
- exception zarr_vectors.building.ShardOwnershipError[source]¶
Bases:
StoreErrorA shard transaction was asked to write a cell outside its shard.
Raised by
zarr_vectors.building.shard_transaction()for a cell of another shard, or of an array the transaction was not opened over.
- zarr_vectors.building.object_shard_rows(level_group)[source]¶
Rows per shard of the level’s object layer, or
Noneif unsharded.Read from the arrays’ own
zarr.json(sharding_indexed). Writers ask this first so a newly created object-layer array follows the level’s existing layout.
- zarr_vectors.building.store_layout(root_or_level, *, level=0)[source]¶
The layout of a store, and of one of its levels, as one object.
Given a level group, describes that level; given the root, level
level. Read structure by structure, since not every layout change movedFORMAT_VERSION.- Parameters:
- Return type:
- class zarr_vectors.building.StoreLayout(created_by, format_capabilities, shard_shape, object_index, link_policy=<factory>, presence_deferred=False, min_reader='0.9.0', object_shard_rows=None)[source]¶
Bases:
objectHow a store’s bytes are laid out, as read from the store.
- Parameters:
- shard_shape¶
Declared cells per shard;
Nonefor one object per cell.
- presence_deferred¶
The level is under
defer_presence().- Type:
- object_shard_rows¶
Rows per shard of the object layer (
shard_object_layer());Noneif unsharded.- Type:
int | None
- __init__(created_by, format_capabilities, shard_shape, object_index, link_policy=<factory>, presence_deferred=False, min_reader='0.9.0', object_shard_rows=None)¶
- zarr_vectors.building.user_metadata(group)[source]¶
The user-metadata namespaces on
group.The object
zarr_vectors.api.Dataset.metadatareturns:user_metadata(g)["ns"]is one application’sMutableMapping, kept apart from the format’s own attributes;names()lists them.
- zarr_vectors.building.observe_presence_writes(callback)[source]¶
Call
callbackfor every incrementalnonempty_chunksstamp.A test instrument for asserting where a stamp happened (inside a lock, on which thread).
callbackruns synchronously on the writing thread as the stamp lands; keep it cheap, since an exception propagates into the writer. CoversGroup.write_bytes(),Group.write_cells(),Group.apply_presence()and theGroup.batched_writes()flush, notGroup.derive_nonempty_chunks(). Blocks nest.Example:
seen = [] with observe_presence_writes(seen.append): write_chunk_vertices(level_group, (0, 0, 0), positions) assert [e.chunk_key for e in seen] == ["0.0.0"]
Note
observe_presence_writes is a debugging instrument, not a data API.
To read the manifest, use
Group.list_chunks.
Spatial partitioning¶
Assigning geometry to cells, and handling what crosses cell boundaries.
- zarr_vectors.building.assign_chunks(positions, chunk_shape)[source]¶
Assign each vertex to a spatial chunk.
- Parameters:
- Returns:
Dict mapping
chunk_coords→(N_k,)array of vertex indices belonging to that chunk. Indices are into the original positions array.- Raises:
ChunkingError – If dimensions are inconsistent.
- Return type:
- zarr_vectors.building.chunks_intersecting_bbox(bbox_min, bbox_max, chunk_shape)[source]¶
Return all chunk coordinates that intersect a bounding box.
- zarr_vectors.building.neighbouring_chunk_keys(key, *, halo=1, occupied_keys=None, include_self=False)[source]¶
Return chunk keys within
haloofkeyalong every axis.Pure integer-tuple work — no store I/O — so it composes with any chunk-key arity (3D, 4D when attribute-chunked, etc.).
- Parameters:
halo (int) – Maximum per-axis distance.
halo=1returns the (3^ndim - 1) chunks adjacent on at least one face, edge, or corner;halo=2widens to a 5^ndim cube.occupied_keys (Iterable[tuple[int, ...]] | None) – If given, restrict the output to keys that actually exist in the store. Pass
set(level.chunk_keys)to filter to occupied chunks.include_self (bool) – If
True, includekeyitself in the output.
- Returns:
Sorted list of unique
ChunkCoordstuples.- Return type:
- zarr_vectors.building.split_polyline_at_boundaries(vertices, chunk_shape)[source]¶
Split an ordered polyline into segments at chunk boundaries.
Consecutive vertices in the same chunk form one segment. The returned list preserves the original vertex order — concatenating all segment arrays recovers the input.
- Parameters:
- Returns:
List of
(chunk_coords, segment_vertices)in polyline order. Eachsegment_verticesis(N_k, D).- Raises:
ChunkingError – If vertices is empty or dimensions mismatch.
- Return type:
- zarr_vectors.building.partition_cross_level_edges(edges, src_vertex_chunks, src_vertex_local_indices, src_chunk_coords_list, tgt_vertex_chunks, tgt_vertex_local_indices, tgt_chunk_coords_list)[source]¶
Partition cross-pyramid-level edges into chunk-aligned + cross-chunk.
Unlike
partition_edges()(which operates within a single resolution level), this helper classifies edges whose endpoints live in different resolution levels. Source-side endpoint indices (column 0 ofedges) are interpreted againstsrc_vertex_chunks/src_vertex_local_indices/src_chunk_coords_list; target-side endpoint indices (column 1) use thetgt_*tables.An edge is classified as chunk-aligned when its source chunk coordinates equal its target chunk coordinates; those rows are bucketed by source chunk and returned in
aligned. Otherwise the edge is cross-chunk and returned incross. Callers persist both through the mergedlinks/<delta>/<offsets>/family at the source level (aligned rows at the all-zero offset, cross rows at the relative offset between the endpoints’ chunks); this helper only partitions and never writes.- Parameters:
edges (NDArray[integer]) –
(M, 2)integer pairs. Column 0 is the source-level global vertex index; column 1 is the target-level global vertex index.src_vertex_chunks (NDArray[int64]) – Source-level chunk-mapping tables, in the same shape as the arguments to
partition_edges().src_vertex_local_indices (NDArray[int64]) – Source-level chunk-mapping tables, in the same shape as the arguments to
partition_edges().src_chunk_coords_list (list[tuple[int, ...]]) – Source-level chunk-mapping tables, in the same shape as the arguments to
partition_edges().tgt_vertex_chunks (NDArray[int64]) – Same triple for the target level.
tgt_vertex_local_indices (NDArray[int64]) – Same triple for the target level.
tgt_chunk_coords_list (list[tuple[int, ...]]) – Same triple for the target level.
- Returns:
- Dict mapping source
chunk_coords→(M_aligned, 2) array of
(src_local_idx, tgt_local_idx)rows.- cross: List of
CrossChunkLinkfor edges where the source and target chunk_keys differ. Endpoint A is the source side at the owning level; endpoint B is the target side at
this_level + delta.
- Dict mapping source
- Return type:
aligned
- zarr_vectors.building.chunk_local_to_global_offsets(level_group, ndim=None)[source]¶
Build the per-chunk → global vertex-index offset table.
For each chunk in a level (sorted lexicographically), returns the cumulative starting vertex index in a hypothetical concatenation of all chunks. This is the standard input shape needed by algorithms that need to map
(chunk_key, local_idx)to a global vertex ID without rebuilding the mapping themselves.Per-chunk vertex counts are derived from the size of each
vertices/<chunk_key>blob divided byndim * dtype.itemsize.- Parameters:
level_group – An open
FsGroupfor one resolution level.ndim (int | None) – Coordinate columns per vertex.
Nonederives it from the store’s NGFF axes. Passing the wrong value here does not fail – it silently scales every offset, which is why this used to be hardcoded to 3 and gave wrong answers on any 2D store.
- Returns:
offsets[chunk_key]= cumulative global start index for that chunk.chunk_keysis the sorted lexicographic order used.total_verticesis the sum of all per-chunk counts.
- Return type:
(offsets, chunk_keys, total_vertices)where
- zarr_vectors.building.apply_perm_inverse(sorted_vals, perm_idx, L)[source]¶
Recover the original input order from canonical-sorted values.
Given
sorted_valsof length L and theperm_idxproduced bycanonical_sort(), returns the values in their original input order.
Note
zarr_vectors.building.build_vertex_chunk_mapping is supported but not
rendered here; read its docstring in the source.
Store-creating writers¶
One call writes one store, with full control of chunk_shape,
bin_shape, shard_shape, compressor and dtype. To read,
use ReadResult.
- zarr_vectors.building.write_points(store_path, positions, *, chunk_shape=None, bin_shape=None, bounds=None, vertex_attributes=None, object_ids=None, object_attributes=None, fragment_attributes=None, groups=None, group_attributes=None, dtype='float32', backend=None, chunk_by_attribute=None, out_of_bounds='raise', compressor=None, shard_shape='inherit', attributes=None)[source]¶
Write a point cloud to a new ZV store.
- Parameters:
store_path (WriteTarget) – Path for the new store (must not exist).
positions (npt.NDArray[np.floating]) –
(N, D)vertex positions.chunk_shape (ChunkShape | None) – Spatial chunk size per dimension. If None, a single chunk containing all points is used.
bin_shape (BinShape | None) – Supervoxel bin edge lengths. If None, defaults to
chunk_shape(one bin per chunk — backward compatible).vertex_attributes (dict[str, npt.NDArray] | None) – Per-vertex attributes
{name: array}. (Spec name; replaces the deprecatedattributeskwarg.)object_ids (npt.NDArray[np.integer] | None) –
(N,)integer per-point object assignment.object_attributes (dict[str, npt.NDArray] | None) – Per-object attributes
{name: array}.fragment_attributes (dict[str, dict[ChunkCoords, npt.NDArray]] | None) – Per-fragment attributes, keyed per chunk:
{name: {chunk_coords: ndarray}}. Each per-chunk ndarray has shape(num_fragments_in_chunk,)or(num_fragments_in_chunk, C)and is aligned with the fragment ordering this writer produces for that chunk. Use case (opt-in): materialize per-fragment parent-IDs (e.g. the OID owning each fragment asobject_id).groups (dict[int, list[int]] | None) – Group memberships
{group_id: [object_id, ...]}.group_attributes (dict[str, npt.NDArray] | None) – Per-group attributes
{name: array}.dtype (str) – Numpy dtype string for vertex positions.
chunk_by_attribute (str | None) – If set, the named per-vertex categorical attribute (which must appear in
vertex_attributes) becomes the leading chunk axis. Chunk keys gain a prefix, e.g.gene_bin.z.y.x. Vertices with mixed values within the same object are split across multiple attribute chunks. v1 supports integer / string dtypes only.out_of_bounds (str) – Policy for vertices outside the store’s current
bounds."raise"(default) rejects the write,"ignore"drops out-of-bounds vertices (and their aligned per-vertex data),"expand"grows the store’s bounds to include all input vertices.backend (str | None)
compressor (Any)
shard_shape (int | tuple[int, ...] | None | Literal['inherit'])
- Returns:
Summary dict.
- Return type:
- zarr_vectors.building.write_lines(store_path, endpoints, *, chunk_shape, bin_shape=None, bounds=None, vertex_attributes=None, object_attributes=None, dtype='float32', backend=None, chunk_by_attribute=None, out_of_bounds='raise', compressor=None, shard_shape='inherit', attributes=None, line_attributes=None)[source]¶
Write finite line segments to a new zarr vectors store.
- Parameters:
store_path (WriteTarget) – Path for the new store.
endpoints (npt.NDArray[np.floating]) –
(N, 2, D)array — N lines, each with 2 endpoints of D dimensions.chunk_shape (ChunkShape) – Spatial chunk size per dimension.
vertex_attributes (dict[str, npt.NDArray] | None) – Per-vertex attributes as
{name: (N, 2) or (N, 2, C)}. Two values per line (one per endpoint). (Spec name; replacesattributes.)object_attributes (dict[str, npt.NDArray] | None) – Per-line (per-object) attributes as
{name: (N,) or (N, C)}. (Spec name; replacesline_attributes.)dtype (str) – Numpy dtype string for positions.
bin_shape (BinShape | None)
backend (str | None)
chunk_by_attribute (str | None)
out_of_bounds (str)
compressor (Any)
shard_shape (int | tuple[int, ...] | None | Literal['inherit'])
- Returns:
Summary dict with
line_count,chunk_count,cross_chunk_count.- Return type:
- zarr_vectors.building.write_polylines(store_path, polylines, *, chunk_shape, bin_shape=None, bounds=None, vertex_attributes=None, object_attributes=None, fragment_attributes=None, groups=None, group_attributes=None, dtype='float32', geometry_type='streamline', backend=None, chunk_by_attribute=None, out_of_bounds='raise', compressor=None, shard_shape='inherit', manifest_layout=None)[source]¶
Write polylines/streamlines to a new zarr vectors store.
- Parameters:
store_path (WriteTarget) – Path for the new store.
polylines (list[npt.NDArray[np.floating]]) – List of arrays, each
(N_k, D)— one per polyline.chunk_shape (ChunkShape) – Spatial chunk size per dimension.
vertex_attributes (dict[str, list[npt.NDArray]] | None) – Per-vertex attributes aligned with polylines.
{name: [array_for_polyline_0, array_for_polyline_1, ...]}where each array is(N_k,)or(N_k, C).object_attributes (dict[str, npt.NDArray] | None) – Per-polyline attributes.
{name: (O,) or (O, C)}where O = number of polylines.fragment_attributes (dict[str, dict[ChunkCoords, npt.NDArray]] | None) – Per-fragment attributes, keyed per chunk:
{name: {chunk_coords: ndarray}}. Each per-chunk ndarray has shape(num_fragments_in_chunk,)or(num_fragments_in_chunk, C)and is aligned with the fragment ordering this writer produces for that chunk.groups (dict[int, list[int]] | None) – Group memberships
{group_id: [polyline_indices]}.group_attributes (dict[str, npt.NDArray] | None) – Per-group attributes
{name: (G,) or (G,C)}.dtype (str) – Numpy dtype for positions.
geometry_type (str) –
"streamline"or"polyline".manifest_layout (str | None) –
"dense"for a fixed-width object index (seecreate_store()); only used when this call creates the store.bin_shape (BinShape | None)
backend (str | None)
chunk_by_attribute (str | None)
out_of_bounds (str)
compressor (Any)
shard_shape (int | tuple[int, ...] | None | Literal['inherit'])
- Returns:
Summary dict.
- Return type:
- zarr_vectors.building.write_graph(store_path, positions, edges, *, chunk_shape, bin_shape=None, bounds=None, kind='graph', vertex_attributes=None, link_attributes=None, object_attributes=None, fragment_attributes=None, object_ids=None, dtype='float32', backend=None, chunk_by_attribute=None, out_of_bounds='raise', compressor=None, shard_shape='inherit', is_tree=None, node_attributes=None, edge_attributes=None)[source]¶
Write a graph or skeleton to a new zarr vectors store.
- Parameters:
store_path (WriteTarget) – Path for the new store.
positions (npt.NDArray[np.floating]) –
(N, D)node positions.edges (npt.NDArray[np.integer]) –
(M, 2)edge list (global vertex indices). For a skeleton each row is[child, parent], and a parent of-1(SWC style) marks the child a root – no edge.chunk_shape (ChunkShape) – Spatial chunk size per dimension.
kind (str) –
"graph"(default — general graph, explicit links convention) or"skeleton"(depth-first reorder, implicit sequential with branches convention). Replaces the booleanis_treekwarg.vertex_attributes (dict[str, npt.NDArray] | None) – Per-node attributes
{name: (N,) or (N,C)}. (Spec name; replacesnode_attributes.)link_attributes (dict[str, npt.NDArray] | None) – Per-edge attributes
{name: (M,) or (M,C)}. (Spec name; replacesedge_attributes.) Withkind="skeleton"every edge is then stored explicitly.fragment_attributes (dict[str, dict[ChunkCoords, npt.NDArray]] | None) – Per-fragment attributes, keyed per chunk:
{name: {chunk_coords: ndarray}}. Each per-chunk ndarray has shape(num_fragments_in_chunk,)or(num_fragments_in_chunk, C)and is aligned with the fragment ordering this writer produces for that chunk.object_ids (npt.NDArray[np.integer] | None) –
(N,)array assigning nodes to objects. If None, all nodes belong to object 0.dtype (str) – Numpy dtype for positions.
bin_shape (BinShape | None)
backend (str | None)
chunk_by_attribute (str | None)
out_of_bounds (str)
compressor (Any)
shard_shape (int | tuple[int, ...] | None | Literal['inherit'])
is_tree (bool | None)
- Returns:
Summary dict.
- Return type:
- zarr_vectors.building.write_mesh(store_path, vertices, faces, *, chunk_shape, bin_shape=None, bounds=None, encoding='raw', vertex_attributes=None, object_attributes=None, object_ids=None, dtype='float32', draco_quantization_bits=11, backend=None, chunk_by_attribute=None, out_of_bounds='raise', compressor=None, shard_shape='inherit')[source]¶
Write a mesh to a new zarr vectors store.
- Parameters:
store_path (WriteTarget) – Path for the new store.
vertices (npt.NDArray[np.floating]) –
(V, D)vertex positions.faces (npt.NDArray[np.integer]) –
(F, L)face index array (L=3 triangles, L=4 quads).chunk_shape (ChunkShape) – Spatial chunk size per dimension.
encoding (str) –
"raw"or"draco"(3-D triangles only; other vertices are written raw).vertex_attributes (dict[str, npt.NDArray] | None) – Per-vertex attributes
{name: (V,) or (V,C)}.object_ids (npt.NDArray[np.integer] | None) –
(V,)array assigning vertices to mesh objects. If None, all vertices belong to object 0.dtype (str) – Numpy dtype for positions.
draco_quantization_bits (int) – For Draco encoding only.
bin_shape (BinShape | None)
backend (str | None)
chunk_by_attribute (str | None)
out_of_bounds (str)
compressor (Any)
shard_shape (int | tuple[int, ...] | None | Literal['inherit'])
- Returns:
Summary dict.
- Return type:
Skeletons: the streaming writer¶
Streaming writes of tree-structured morphology.
- zarr_vectors.building.init_skeleton_store(store_path, *, chunk_shape, bounds, ndim, attribute_dtypes, backend=None, coordinate_offset=None, compressor=None, shard_shape='inherit')[source]¶
Create a new skeleton store + an empty level 0 with its arrays.
coordinate_offset(optional) is the world position of the stored coordinate origin: stored vertices are expected to beworld - coordinate_offsetso the spec’s origin-0 chunk grid aligns to the source grid. It is recorded in the rootzarr_vectors.coordinate_offset.shard_shape(optional, in units of spatial chunks) wraps each per-chunk array’s cells in Zarr v3’ssharding_indexedcodec, so many chunks share one storage object — the same knob the whole-store writers (write_points,write_graph, …) take.compressorsets the codec pipeline for those arrays.Skeletons are written by streaming rather than in one call, so the arrays are allocated here and the caller’s subsequent
write_skeleton_chunk()calls reuse them as-is — an existing array is never re-created out from under a streaming writer. A caller that wants its streamed writes batched should open its ownopen_write_session()with the SAMEshard_shape/bounds/chunk_shapepassed here.Returns
(root, level0_group). Callers then streamwrite_skeleton_chunk()over chunks, reduce the records into an object index (zarr_vectors_tools.multiresolution.object_index), and finish withfinalize_skeleton_store().
- zarr_vectors.building.write_skeleton_chunk(level_group, chunk_coords, pieces, *, attr_dtypes=None, dtype=<class 'numpy.float32'>, record_presence=True)[source]¶
Write one spatial chunk’s skeleton fragments.
- Parameters:
record_presence (bool) – Threaded into every per-chunk write this makes (vertices, links, attributes, fragment attributes). Pass
Falsefrom concurrent per-chunk writers —nonempty_chunksis array-wide state, so stamping it is a read-modify-write that two workers writing disjoint chunks still race on — and re-derive the manifests once afterwards from the coordinator (derive_nonempty_chunks/finalize_links).level_group – Target resolution-level group (arrays must already be created — see
init_skeleton_store()).pieces (list[dict[str, Any]]) – One dict per fragment with keys
segment_id(int),positions(n, D),edges(m, 2)[child, parent](root omitted), andattributes{name: (n, ...)}. Pieces should already be single rooted trees (usesplit_components()). An optional"anchors"dict{tag: input_local_idx}requests the final chunk-local index of those input vertices back in the return value (used to resolve cross-chunk-link endpoints).attr_dtypes (dict[str, dtype] | None) – Per-attribute numpy dtypes; defaults to each piece’s array dtype.
- Returns:
(records, anchor_locs)whererecordsis[(segment_id, chunk_coords, fragment_index), ...]for the object-index reduce andanchor_locsmaps each anchortagto(chunk_coords, chunk_local_index).- Return type:
tuple[list[tuple[int, tuple[int, …], int]], dict[Any, tuple[tuple[int, …], int]]]
- zarr_vectors.building.write_skeleton_cross_chunk_links(level_group, links, *, ndim)[source]¶
Write
[child, parent]edges that cross a chunk boundary.Each link is
((chunkA, viA), (chunkB, viB))with chunk-local vertex indices, endpoint 0 the child and endpoint 1 its parent, as inwrite_skeleton_chunk(). Storeddirected=Trueso a canonical sort cannot swap them.
- zarr_vectors.building.finalize_skeleton_store(root)[source]¶
Finish a streamed skeleton store: stamp each level’s
vertex_countandarrays_presentfrom disk, then commit.- Return type:
None
- zarr_vectors.building.decompose_tree_to_paths(piece)[source]¶
Decompose a rooted tree into maximal linear paths + branch links.
This is the layout the
implicit_sequential_with_branchesskeleton convention expects (and that neuroglancer reconstructs): each fragment is a linear chain whose consecutive vertices are connected implicitly (i, i+1); the points where the tree branches are stored as explicitlinksentries connecting a new path’s first vertex to the branch vertex in the path it left.- Parameters:
piece (dict[str, Any]) –
{"positions": (N, D), "edges": (M, 2) [child, parent] (root omitted), "attributes": {name: (N, ...)}}.- Returns:
(ordered_positions, ordered_attributes, frag_ranges, branch_links, new_of_old)wherefrag_rangesis a list of(start, count)over the reordered vertex array (one per path),branch_linksare(child_order_idx, parent_order_idx)over the reordered indices (one per non-root path), andnew_of_old[i]is the reordered index of input vertexi.- Return type:
tuple[NDArray, dict[str, NDArray], list[tuple[int, int]], list[tuple[int, int]], NDArray]
- zarr_vectors.building.get_coordinate_offset(root, ndim)[source]¶
Per-axis world offset of the stored coordinate frame (zeros if none).
- Parameters:
ndim (int)
- Return type:
NDArray[float64]
- zarr_vectors.building.set_coordinate_offset(root, offset)[source]¶
Record the stored→world coordinate offset in the root object.
- zarr_vectors.building.read_skeleton_by_segment_id(store_path, segment_id, *, level=0, backend=None, attributes=None)[source]¶
Read one skeleton by its original (flywire) segment ID.
Resolves
segment_id→ object viaobject_attributes/segment_id(sorted, binary search), follows the manifest, and reconstructs the merged skeleton (fragments concatenated; edges offset per fragment).Returns
Nonewhen the segment ID is absent. Otherwise a dict withpositions(N, D),edges(M, 2)[child, parent],attributes{name: (N, ...)}, andfragment_count.
Array-form I/O and device arrays¶
Many cells, objects or records per call, as flat arrays. Each writer
writes the same bytes as its per-object counterpart and accepts cupy
arrays; the readers return them with device="cuda". See
GPU arrays and array-form I/O.
- zarr_vectors.building.read_cells(level_group, chunk_coords, arrays=('vertices',), *, ndim=None, missing_arrays='raise', on_error='record', device=None, decode='auto', io='auto', fragments=False)[source]¶
Read the cells
chunk_coordsof every array inarraysat once.- Parameters:
chunk_coords (Any) –
(C, K)chunk coordinates; the result keeps this order, duplicates included.arrays (Sequence[str]) –
vertices,vertex_attributes/<name>,fragment_attributes/<name>,links/<delta>/<offsets>(physical rows, perm column included) orlink_attributes/<name>/<delta>/<offsets>.ndim (int | None) – Vertex coordinate width;
Nonereads it from the store.missing_arrays (Literal['raise', 'skip']) –
"skip"omits arrays that do not exist.on_error (Literal['record', 'raise']) –
"record"puts unreadable cells inerrors, with no rows;"raise"re-raises.device (str | None) –
"cpu","cuda"orNone(wherechunk_coordslives).decode (Literal['auto', 'host', 'device']) – Where a cuda read decodes (same result):
"auto"uncompressed arrays on the device;"device"zstd too, via nvCOMP, raising if it cannot (nvCOMP trusts its input: corrupt cells can crash the CUDA context, so trusted stores only);"host".io (Literal['auto', 'kvikio', 'host']) – How a device read reads local files:
"kvikio","host"(pinned), or"auto"($ZARR_VECTORS_GPU_IO, elsezarr_vectors._gds.choose_io()).fragments (bool) – Also return
batch.fragments(FragmentColumn).level_group (Group)
- Returns:
A
CellBatch; a cell nobody wrote, or outside an array’s grid, has no rows.- Return type:
- zarr_vectors.building.read_neighbourhood(level_group, chunk_coords, arrays=('vertices',), *, halo=1, present_only=True, present_array='vertices', **read_cells_kw)[source]¶
A cell and its neighbours within
halo, in oneread_cells().The centre comes first, then the neighbours in sorted order. With
present_only(the default), neighbourspresent_arrayholds no data for are left out rather than read as empty. Filtering rows to an overlap band is the caller’s business.Refused on a level with octree chunks; use
zarr_vectors.octree_chunks.read_octree()there.
- class zarr_vectors.building.CellBatch(chunk_coords, columns, errors=(), device='cpu', fragments=None, io=(), io_seconds=<factory>)[source]¶
Bases:
Mapping[str,CellColumn]The result of
read_cells(): oneCellColumnper array.chunk_coordsis the requested cells in request order, on the host; the columns are ondevice.fragmentsis the vertices’ fragment index withfragments=True, else None.iosays how each array read was served (ArrayRead), includingverticesread only to size an unstamped attribute andvertex_fragmentslast.io_secondsholdsfetchanddecode(device) andhosttimes. Neither takes part in equality.- Parameters:
chunk_coords (NDArray[int64])
columns (dict[str, CellColumn])
errors (tuple[CellReadError, ...])
device (str)
fragments (FragmentColumn | None)
- __init__(chunk_coords, columns, errors=(), device='cpu', fragments=None, io=(), io_seconds=<factory>)¶
- Parameters:
chunk_coords (NDArray[int64])
columns (dict[str, CellColumn])
errors (tuple[CellReadError, ...])
device (str)
fragments (FragmentColumn | None)
- Return type:
None
- chunk_coords: NDArray[int64]¶
- columns: dict[str, CellColumn]¶
- errors: tuple[CellReadError, ...] = ()¶
- fragments: FragmentColumn | None = None¶
- class zarr_vectors.building.CellColumn(data, offsets, _host_offsets)[source]¶
Bases:
objectOne array’s rows across the requested cells.
data[offsets[i]:offsets[i + 1]]are celli’s rows. Both live on the batch’s device.- __init__(data, offsets, _host_offsets)¶
- class zarr_vectors.building.CellReadError(array, chunk_key, message)[source]¶
Bases:
objectA cell that could not be read; the rest of the batch still was.
- __init__(array, chunk_key, message)¶
- class zarr_vectors.building.ArrayRead(array, path, cells, stored_bytes)[source]¶
Bases:
objectHow one array’s cells reached a
CellBatch.pathisgds(kvikio, GPUDirect Storage on),kvikio-compat(kvikio through cuFile’s bounce buffer),pinned-host(pinned host reads, one copy up) orstore(byte-range gets from a non-local store, one copy up), all decoded on the device; orhost(read and decoded on the host).stored_bytesis what was read from storage, before decompression;Noneforhost.- __init__(array, path, cells, stored_bytes)¶
- class zarr_vectors.building.FragmentColumn(cell_offsets, starts, counts, index_offsets, indices)[source]¶
Bases:
objectThe vertex fragments of every requested cell, as flat arrays.
Cell
i’s fragments arecell_offsets[i]:cell_offsets[i + 1], in fragment-index order. Fragmentfholdscounts[f]of the cell’s vertex rows, numbered from its first row:starts[f]onward for a range, else (starts[f] == -1)indices[index_offsets[f]:index_offsets[f + 1]]. All on the batch’s device. A store written bin by bin has fragments tiling each cell’s rows in bin order, empty bins included.- __init__(cell_offsets, starts, counts, index_offsets, indices)¶
- zarr_vectors.building.read_all_object_manifests_csr(level_group, *, device=None)[source]¶
Every committed manifest as CSR arrays, decoded without per-object Python.
Reads rows
[0, num_objects): the committed prefix, whereread_all_object_manifests()also decodes any rows a torn flush left past it. Range and explicit-list blocks are expanded to one row per fragment, in manifest order.device="cuda"returns the three arrays on the device (ids stay on the host).- Parameters:
- Return type:
- class zarr_vectors.building.ManifestCSR(offsets, chunk_coords, fragment_idx, object_ids=None)[source]¶
Bases:
objectEvery object’s manifest as flat arrays.
Object row
oowns rowsoffsets[o]:offsets[o + 1]ofchunk_coordsandfragment_idx.object_ids[o]is its id, orobject_idsisNonewhen rows are the ids. Unpacks asoffsets, chunk_coords, fragment_idx = read_all_object_manifests_csr(lg).- __init__(offsets, chunk_coords, fragment_idx, object_ids=None)¶
- zarr_vectors.building.encode_object_manifests_csr(chunk_coords, fragment_idx, manifest_offsets=None, *, sid_ndim=None)[source]¶
Manifest blobs for objects held as CSR arrays, with no per-object Python.
Object
oowns the blocksmanifest_offsets[o]:manifest_offsets[o+1]; blockbnames chunkchunk_coords[b]and fragmentfragment_idx[b]in it (a single-fragment, mode-0 block). Withmanifest_offsets=Noneevery object owns exactly one block. The blobs are the onesencode_object_manifest_blocks()writes for[(chunk_coords, int(fragment_idx)), ...], byte for byte.
- zarr_vectors.building.decode_object_manifests_csr(blobs, sid_ndim)[source]¶
Every manifest as CSR:
(offsets, chunk_coords, fragment_idx).Object
o’s fragments are rowsoffsets[o]:offsets[o+1]ofchunk_coords((M, sid_ndim)) andfragment_idx((M,)), in manifest order, with range and explicit-list blocks expanded to one row per fragment – the pairsdecode_object_manifest_blocks()followed by the usual expansion would give.A blob made only of single-fragment blocks – what every bulk writer produces – is parsed with array operations. That test is exact, not a guess from the length: if a blob’s first block is single-fragment, the next block starts where a single-fragment block ends, and so on, so checking every such position’s mode byte proves the whole blob. Anything else is decoded blob by blob and merged in place. An empty or
Noneblob is an object with no fragments.
- zarr_vectors.building.write_object_attribute_columns(level_group, columns, *, mode='append', at=None, fill_values=None)[source]¶
Write several object attribute columns in one call.
Leaves the store as one
write_object_attributes()call per column would, but columns that grow in place are extended concurrently.- Parameters:
columns (Mapping[str, Any]) –
{name: rows}; device arrays are copied to the host once.mode (Literal['replace', 'append', 'place']) –
"append"(default),"replace", or"place"(rows[at, at + n)of columns sized byreserve_object_rows(), for processes writing disjoint ranges at once).at (int | None) – Row the new rows start at, as for
write_object_attributes().fill_values (Any) – Absent-row sentinel: one value, or a mapping by name (missing names use the dtype default).
level_group (Group)
- Return type:
None
Meshes by ownership cell¶
Reading a raw mesh cell by cell, with the vertices its faces reference.
- class zarr_vectors.building.MeshReader(source, *, level=0)[source]¶
Bases:
objectRead a raw mesh by ownership cells, fetching referenced vertices.
Construct one reader per stored surface level. Metadata discovery lists the connectivity cells once; reads fetch only selected connectivity and referenced vertex chunks. Missing dependencies and invalid indices raise rather than returning a surface with silently missing triangles.
Draco is explicitly unsupported: its intra-cell faces require a separate decode path and boundary indices need validation against decoder ordering. A reader is not thread safe; serialize calls or construct independent ones. Metadata is a read-only snapshot for the lifetime of this reader. Construct a fresh reader after any store mutation, and close it when finished.
- Parameters:
source (Any)
level (int)
- read(chunks, *, max_bytes=None)[source]¶
Return complete faces owned by
chunksand their vertices.The result uses the same four keys as
read_mesh. Vertex indices are local to this result. Vertices shared by independently read owners may be duplicated; each face belongs to exactly one owner.max_bytesrejects reads whose decoded dependency vertices plus output faces exceed the limit, before fetching vertex payloads. Owned connectivity and fragment indices are read to discover that size; their I/O/decode scratch is additional to the limit. Budgeted reads require a verifiedfragments_tilelevel claim; otherwise the index cannot bound unused physical rows in the buffer.
Composite levels¶
Levels that reference cells of other stores. See Chunk sources (composite levels).
- zarr_vectors.building.set_chunk_sources(level_group, sources, *, fingerprint=True)[source]¶
Make level_group a composite level of sources; returns the stored table.
Call before the level’s arrays are allocated, then allocate them with
open_write_session(..., bin_count=len(sources)).ref.pathresolves against this store’s root. With fingerprint, each source’ssource_fingerprint()is merged into its entry (caller’s keys win).
- zarr_vectors.building.chunk_sources(level_group)[source]¶
The level’s source table, or
Nonefor an ordinary level.
- zarr_vectors.building.source_fingerprint(level_group)[source]¶
What identifies a source level’s content for a composite that references it.
- Return type:
- zarr_vectors.building.verify_chunk_sources(level_group)[source]¶
Open every source of a composite level now, raising if one cannot be read as recorded.
For readers that tolerate unreadable cells and so would not notice a rebuilt source. Raises
StoreErrorfor a source that cannot be opened andArrayErrorfor a fingerprint mismatch. Returns the table, orNonefor an ordinary level.