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.

  • FORMAT_VERSION

  • VERTICES

  • VERTEX_ATTRIBUTES

  • VERTEX_FRAGMENTS

  • FRAGMENT_ATTRIBUTES

  • OBJECT_INDEX

  • OBJECT_ATTRIBUTES

  • GROUPS

  • GROUP_ATTRIBUTES

  • LINKS

  • LINK_FRAGMENTS

  • LINK_ATTRIBUTES

  • OBJECT_INDEX_LAYOUT_V1, OBJECT_INDEX_LAYOUT_V2, OBJECT_INDEX_LAYOUT_DENSE

  • OBJECT_INDEX_MANIFEST_BUCKET

  • LINKS_IMPLICIT_SEQUENTIAL

  • LINKS_IMPLICIT_BRANCHES

  • XLEVEL_NONE

  • XLEVEL_EXPLICIT

  • DEFAULT_CROSS_LEVEL_DEPTH

  • DEFAULT_CROSS_LEVEL_STORAGE

  • COARSEN_PER_OBJECT

  • CAP_FRAGMENT_INDEX

  • CAP_MULTISCALE_LINKS

  • CAP_PRESERVED_OBJECT_IDS

  • CAP_SHARED_FRAGMENTS

  • OBJECT_SHARD_ROW_MULTIPLE

  • SOURCE_AXIS

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: object

A ZV group wrapping an underlying zarr.Group.

Parameters:

zarr_group (zarr.Group)

__init__(zarr_group)[source]
Parameters:

zarr_group (Group)

Return type:

None

apply_presence(pending)[source]

Apply stamps collected by collect_presence().

One read-modify-write of nonempty_chunks per array; entries fold in order, so the last stamp for a chunk key wins. Arrays are re-resolved by name. An empty pending is a no-op.

Returns:

How many arrays were stamped. An array with no manifest (a deferred level) is skipped and not counted.

Raises:

StoreError – If an array named in pending is gone.

Parameters:

pending (list[tuple[str, str, bool]])

Return type:

int

array_exists(array_name)[source]
Parameters:

array_name (str)

Return type:

bool

property attrs: _Attrs
property backend: _BackendShim
batched_range_reads(requests)[source]

Fetch every (array_name, chunk_key, start, stop) range in one go and serve read_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.

Parameters:

requests (Sequence[tuple[str, str, int, int]])

Return type:

Iterator[None]

batched_reads(plan, *, tolerant=False)[source]

Prefetch every chunk in plan via one asyncio.gather() and serve subsequent read_bytes() calls from the resulting in-memory cache.

plan is a list of (array_name, [chunk_keys, ...]) pairs — typically (VERTICES, list_chunk_keys(group, VERTICES)) plus the parallel vertex_fragments and 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 N round-trips.

Nesting is not supported and raises StoreError. Writes inside the block are unaffected.

tolerant=True keeps 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, ...)
Parameters:
Return type:

Iterator[None]

batched_writes(compressor=None, *, durable=False)[source]

Defer every write_bytes() and write_array_meta() call inside the block and flush them in a single asyncio.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.json PUT becomes one async task instead of one serial sync call, so the total wall time approaches one round-trip rather than N round-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 default None resolves 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 with zarr_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 a zarr.json GET, and against a store holding a single point that was the whole cost of the query: a one-point read_points issued 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 – one zarr.json read 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.

Return type:

list[str]

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> and link_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.

Return type:

list[str]

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_writes is 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 every nonempty_chunks stamp 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"/False means 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_exists(array_name, chunk_key)[source]
Parameters:
  • array_name (str)

  • chunk_key (str)

Return type:

bool

chunk_grid_bounds(array_name)[source]

(origin, shape) of array_name’s cell grid, or None.

The grid the chunk keys live in: cell i of the array holds absolute chunk coord i + origin (origin is None for a zero origin, which is how it is stored). A box resolver needs this to clamp — chunks_intersecting_bbox speaks 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.

None when the path holds no chunk array.

Parameters:

array_name (str)

Return type:

tuple[tuple[int, …] | None, tuple[int, …]] | None

chunk_index_by_spatial(array_name, nd)[source]

Present coordinates grouped by their trailing nd axes.

See _ChunkListing.by_spatial().

Parameters:
Return type:

dict[tuple[int, …], list[tuple[int, …]]]

chunk_present_set(array_name)[source]

list_chunk_coords() as a set, for membership tests.

See _ChunkListing.present() for why a reader wants it.

Parameters:

array_name (str)

Return type:

frozenset[tuple[int, …]]

collect_presence()[source]

Defer the nonempty_chunks stamps 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 to apply_presence(). record_presence=False is still honoured. The list and this Group belong to one thread. Nesting or use inside batched_writes() raises StoreError. See docs/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)
Return type:

Iterator[list[tuple[str, str, bool]]]

create_group(name, **_kwargs)[source]
Parameters:
Return type:

Group

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_shape is provided the sharding_indexed codec 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 bytes serializer, i.e. the create_array compressors= form). None leaves 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.json attributes block (the standard Zarr v3 location for user metadata).

  • octree (Any) – The zarr_octree_sharding configuration, or None for sharding_indexed (for zarr_vectors.sharding.set_octree()); omitted, the store’s marker decides (_store_octree()).

  • origin (tuple[int, ...] | None)

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.json per array still has to be written, but they are independent, so they go out in one gather rather than through a blocking sync() each – which is the difference between allocating a links family of 1,700 offsets arrays in a second and in a minute.

arrays is [(array_name, attributes), ...]; replace names those whose existing node must be dropped first (the caller has looked, so this does not look again).

Parameters:
Return type:

None

delete_subtree(name)[source]
Parameters:

name (str)

Return type:

None

derive_nonempty_chunks(array_name, *, on_sharded='derive')[source]

Rebuild array_name’s nonempty_chunks from 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 (see docs/spec/chunking/sharding.md). Not reported to observe_presence_writes().

Parameters:
  • on_sharded (Literal['derive', 'skip', 'raise']) – For a natively sharded array: "derive" rebuilds it, "skip" returns the recorded manifest unchanged, "raise" raises ShardedPresenceError.

  • array_name (str)

Return type:

list[str]

Returns the sorted keys now recorded; raises StoreError if array_name is not a chunk array.

extend_array(path, rows, *, attributes=None, _node=None)[source]

Append rows along 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 why write_object_attributes() gives its arrays a bounded row chunk when it creates them.

Parameters:
  • path (str) – Logical path of an existing array.

  • rows (Any) – Rows to append. Tail dimensions must match the array’s.

  • attributes (dict[str, Any] | None) – Merged into the array’s attributes block after the write.

  • _node (Any)

Returns:

The array’s new length along axis 0.

Return type:

int

Notes

An array whose attributes block records its own shape (what write_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.

Raises:
  • StoreError – If path does not exist or is not an array.

  • ValueError – If the tail dimensions do not match.

Parameters:
Return type:

int

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 int calls, paid on every read no matter how few chunks the query goes on to touch. Inside a cached_nodes() block the parse happens once; outside it, every call parses, exactly as before.

Parameters:

array_name (str)

Return type:

list[tuple[int, …]]

list_chunks(array_name)[source]

The dotted chunk keys this array holds data for, sorted.

Parameters:

array_name (str)

Return type:

list[str]

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 by zarr_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 match grid_shape and the Zarr v3 sharding_indexed codec 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().

  • origin (tuple[int, ...] | None)

Return type:

Iterator[None]

Nesting is not supported; an inner call raises StoreError. The batched_writes context can be active concurrently — cell writes are queued and flushed together (see zarr_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 every vertices cell 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.

Parameters:
  • chunk_key (str)

  • n_rows (int)

Return type:

None

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 with await; inside this block the ordinary synchronous read_* 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.misses and raises StoreError rather 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 inspects misses to decide what to fetch next — see read_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]

property path: Path
property prefix: str
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:

bool

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 serial zarr.json reads 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), under offline_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.

Parameters:

paths (Sequence[str]) – Node paths relative to this Group. Order is irrelevant; duplicates are collapsed.

Return type:

None

range_readable(array_name)[source]

Can read_cell_range() fetch part of a cell of array_name without 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.

Parameters:

array_name (str)

Return type:

bool

read_array(path)[source]

Read a chunked Zarr array at path as a numpy array.

Parameters:

path (str)

Return type:

ndarray

read_array_attrs(path)[source]

Read the attributes block of a Zarr array at path.

Returns {} for missing paths or paths that point at a group rather than an array.

Parameters:

path (str)

Return type:

dict[str, Any]

read_array_fill_value(path)[source]

Return the fill_value of the standard Zarr array at path.

fill_value lives at the top level of the array’s zarr.json (not in the user attributes block), so this helper exists alongside read_array_attrs() rather than being folded into it. Raises StoreError if path is missing or points at a group.

Parameters:

path (str)

Return type:

Any

read_array_meta(array_name)[source]
Parameters:

array_name (str)

Return type:

dict[str, Any]

read_bytes(array_name, chunk_key)[source]
Parameters:
  • array_name (str)

  • chunk_key (str)

Return type:

bytes

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 (see fetch_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) or batched_range_reads() (this range) when either holds it.

Parameters:
Return type:

bytes

read_vlen_array(path)[source]

Read a vlen-bytes Zarr array at path as a list of bytes.

Parameters:

path (str)

Return type:

list[bytes]

read_vlen_array_raw(path, stop=None)[source]

Rows [0, stop) of a vlen-bytes array as zarr returns them: an object array, without read_vlen_array()’s per-row bytes() conversion.

Parameters:
  • path (str)

  • stop (int | None)

Return type:

Any

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/manifests has 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.

Parameters:
Return type:

bytes

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.

Parameters:
Return type:

list[bytes]

require_group(name)[source]
Parameters:

name (str)

Return type:

Group

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_txn and zarr_vectors.building.shard_transaction().

Parameters:
Return type:

Iterator[Any]

standalone_array_exists(path)[source]

True when path points at a Zarr array (not a group).

Counterpart to array_exists(), which reports True for either node type — so it also answers “does this family group exist” for a path like links/<delta>.

Parameters:

path (str)

Return type:

bool

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.

Return type:

dict[str, int]

property url: str
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. dtype and shape set 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 attributes block in its own zarr.json — the spec-blessed location for per-array user metadata.

  • compressors (Any) – Override the codec pipeline. None uses the active session codec (from batched_writes()) or zarr v3’s default (bytes + zstd).

  • shards (tuple[int, ...] | None) – Outer chunk (shard) shape, a multiple of chunks; None for one object per chunk. Zarr’s own sharding_indexed, so any Zarr v3 reader reads it.

Return type:

None

write_array_meta(array_name, meta)[source]
Parameters:
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, source 0: a source is never written through it.

array_name must 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 by zarr_vectors.core.arrays._ensure_array_dir().

Parameters:
  • record_presence (bool) – When False, skip the nonempty_chunks update. 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’s derive_nonempty_chunks() (see zarr_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.

Parameters:
Return type:

int

write_vlen_array(path, blobs, *, chunks=None, attributes=None)[source]

Write a 1D variable-length-bytes Zarr v3 array at path.

Each element of blobs becomes one row of the resulting array. Mirrors the layout used by object_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 attributes block.

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.

Group is 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 commit is deliberately absent: it is a module-level function in core.store (re-exported here), not a Group method.

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 + default bounds, a 0/ sub-group, and the empty ragged-vertex pair 0/vertices/ + 0/vertex_fragments/.

bounds is mandatory for every ZV store; when the caller does not pass one, the default ([0,...,0], [128,...,128]) is stamped (using ndim if given, otherwise inferred from axes / chunk_shape / bounds, defaulting to 3D). Subsequent writes must fit within these bounds unless the caller passes out_of_bounds="expand" (which grows the bounds in-place) or calls set_bounds() first.

The /parametric sub-group is not created here; it is created lazily on first use via get_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_fragments arrays — and therefore for the life of the store, since a chunk array’s codecs are fixed at creation and every later create_vertices_array reuses the existing array. None (default) stores raw. See zarr_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 as links_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 by build_pyramid. 0 disables cross-level link arrays.

  • cross_level_storage (str | None) – "none" / "implicit" / "explicit" — see zarr_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.constants CAP_*.

  • 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. An int broadcasts 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.json remains 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_sharding codec with this configuration ({} for its defaults) instead of sharding_indexed. Needs shard_shape and the zarr-octree package, both checked here, before the store exists. None (the default) writes nothing. See zarr_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; None or "vlen" (the default) for blobs. Recorded on the root as the default for every index created later; an index that exists keeps its layout. See zarr_vectors.core.dense_manifests.

  • manifest_block_dtype (str | None) – "int32" to create dense indexes’ manifest_blocks as 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; None or "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 raises ArrayError on 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 ome node 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 (axes as given, or the generated defaults), so it is recorded in the root zarr_vectors.axes and written into the world coordinate system of the root ome scene. 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. Raises MetadataError for a non-NGFF spelling or a conflict with a unit already on axes; see zarr_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 – raises TypeError rather than discarding them, so a misspelled parameter fails here instead of being silently ignored. Structured storage_options= is always accepted.

  • storage_options (dict[str, Any] | None)

  • **backend_kwargs

Returns:

The root Group.

Raises:
  • StoreError – If a store already exists at path.

  • MetadataError – If kwargs are inconsistent (mismatched ndim).

Return type:

Group

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-opened Group. 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 (see Group.offline_reads()) and then drive an otherwise synchronous read_* with no store I/O at all. When a Group is passed, mode and the backend kwargs are ignored — the handle’s existing mode stands.

  • mode (str) – "r" (read-only — writes will raise), "r+" (read-write), "a" (append). For mode="r" the underlying Zarr store is wrapped via store.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 with mode="r+".

  • backend (str | None) – Force a particular backend (auto-detect by default).

  • require_zv (bool) – When True (the default), a root with no zarr_vectors attribute block raises StoreError. Pass False to get the handle anyway — for zarr_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.

  • storage_options (dict[str, Any] | None)

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:

Group

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 inside batched_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 next commit(group, ...) call.

Parameters:
  • group (Group) – A Group returned by create_store() or open_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, else None.

Return type:

str | None

zarr_vectors.building.session_for(group)[source]

Return the underlying icechunk.Session if any, else None.

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

Parameters:

group (Group)

Return type:

Any | None

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 multiscales layout via zarr_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’s bin_shape and bin_ratio go in its own level zarr_vectors object, where read_level_metadata() reads them.

Parameters:
Return type:

Group

zarr_vectors.building.get_resolution_level(root, level)[source]

Get an existing resolution level group.

Raises:

StoreError – If the level does not exist.

Parameters:
Return type:

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 multiscales layout entry and every links/+k / link_attributes/<name>/+k family pointing at it go with it.

Raises:

StoreError – If the level does not exist, is level 0, or is not the coarsest level.

Parameters:
Return type:

None

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 (formerly resolution_0 / resolution_1). Top-level groups whose name doesn’t parse as int are some other entity (e.g. parametric/) and are silently skipped.

Parameters:

root (Group)

Return type:

list[int]

zarr_vectors.building.list_available_ratios(root)[source]

Return bin ratios for all existing resolution levels.

Parameters:

root (Group)

Return type:

list[tuple[int, …]]

zarr_vectors.building.read_root_metadata(root)[source]

Read and parse root metadata from the store.

Parameters:

root (Group)

Return type:

RootMetadata

zarr_vectors.building.update_root_metadata(root, *, add_capabilities=(), **fields)[source]

Read-modify-write the root zarr_vectors block.

Same contract and same warning as update_level_metadata(). add_capabilities is separated out because stamping one is the common case and appending to a list through **fields would mean reading it first – which is the read-modify-write this exists to own.

Raises:

MetadataError – On an unknown field.

Parameters:
Return type:

RootMetadata

zarr_vectors.building.read_level_metadata(root, level)[source]

Read and parse level metadata.

A coarse level’s bin_shape and bin_ratio are read from its own zarr_vectors object. A coarse level that records none gets level 0’s (bin_ratio 1, bin_shape the root base_bin_shape); at level 0 both are None.

Raises:
  • StoreError – If the level does not exist.

  • MetadataError – If metadata is malformed.

Parameters:
Return type:

LevelMetadata

zarr_vectors.building.update_level_metadata(level_group, *, arrays_present=None, add_arrays_present=None, **fields)[source]

Read-modify-write one level’s zarr_vectors object (kind: "level").

There was nothing between create_resolution_level() and read_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 an except 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_chunks does. Call it once, after a parallel phase, not from inside one.

Parameters:
  • arrays_present (list[str] | None) – Replace the family list outright.

  • add_arrays_present (str | list[str] | None) – Add one or more families, keeping the rest.

  • **fields (Any) – Any other LevelMetadata field. Derived fields are refused – see _DERIVED_LEVEL_FIELDS.

  • level_group (Group)

Returns:

The level metadata as it now stands.

Raises:

MetadataError – On an unknown field, or a derived one.

Return type:

LevelMetadata

zarr_vectors.building.stamp_ome_node(store, *, name=None)[source]

Add (or refresh) the RFC 8 ome node on an existing store.

What makes a store nameable by an OME collection: a resolver following {"type": "zarr", "path": "./x.zarrvectors"} fetches the root zarr.json and looks for a legal node under ome. 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:
  • store (str | Path | Group) – Store path, URL, or an open root group. A path or URL is opened mode="r+".

  • name (str | None) – Store name for the node. None keeps the name already recorded, and otherwise derives one from the store URL.

Returns:

The ome block as written.

Return type:

dict[str, Any]

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: object

Root-level metadata for a ZV store.

Parameters:
zv_version

ZV specification version (renamed from format_version in 0.5.0 to disambiguate from Zarr v3’s zarr_format field).

Type:

str

spatial_index_dims

Axes definitions (NGFF / OME-Zarr style). On disk (format 0.10.0), axes live in the root zarr_vectors.axes.

Type:

list[dict[str, str]]

chunk_shape

Spatial chunk size per dimension.

Type:

tuple[float, …]

bounds

Global bounding box as (min_corner, max_corner).

Type:

tuple[list[float], list[float]]

geometry_types

List of geometry types in the store.

Type:

list[str]

crs

Coordinate reference system dict (or None).

Type:

dict[str, Any] | None

How intra-chunk links are stored.

Type:

str

object_index_convention

How object→vertex-group mapping works.

Type:

str

cross_chunk_strategy

How cross-chunk connectivity is handled.

Type:

str

reduction_factor

Multi-resolution threshold factor.

Type:

int

__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)
Parameters:
Return type:

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: object

Per-resolution-level metadata.

Parameters:
  • level (int)

  • vertex_count (int)

  • arrays_present (list[str])

  • bin_shape (tuple[float, ...] | None)

  • bin_ratio (tuple[float, ...] | None)

  • chunk_shape (tuple[float, ...] | None)

  • object_sparsity (float)

  • coarsening_method (str)

  • parent_level (int | None)

  • chunk_dims (list[str] | None)

  • chunk_attribute_name (str | None)

  • chunk_attribute_values (list[Any] | None)

  • chunk_sources (list[dict[str, Any]] | None)

  • preserves_object_ids (bool)

  • inherited_num_objects (int | None)

  • shared_fragments (bool)

  • fragments_tile (bool)

  • link_fragments_aligned (bool)

  • octree_chunks (dict[str, Any] | None)

level

Integer level index (0 = full resolution).

Type:

int

vertex_count

Total vertices at this level.

Type:

int

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_store long declared [vertices] while also creating vertex_fragments); prefer zarr_vectors.building.refresh_arrays_present(), which derives it from what is actually on disk.

Type:

list[str]

bin_shape

Supervoxel edge lengths at this level (None for level 0, which inherits base_bin_shape from root).

Type:

tuple[float, …] | None

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_ratio keeps its integer contract for callers that want a whole fold. (1,1,1) for level 0, (2,2,2) for 2× coarser bins, etc.

Type:

tuple[float, …] | None

object_sparsity

Fraction of objects retained at this level (0,1].

Type:

float

coarsening_method

How this level was generated.

Type:

str

parent_level

Index of the source level (None for level 0).

Type:

int | None

chunk_dims

Names of chunk-key axes, leading axis first. When None (the default), chunk keys are spatial-only and have sid_ndim axes (e.g. ["dim0", "dim1", "dim2"]). When set, the first entries name non-spatial leading axes (e.g. ["gene", "dim0", "dim1", "dim2"]).

Type:

list[str] | None

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). None for 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’s attribute_filter names to select the chunks with leading coord i, 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 (-1 for ungrouped objects, the last bin). None for 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 (see zarr_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 cell spatial read through its transform. None for an ordinary level.

Type:

list[dict[str, Any]] | None

__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:
  • level (int)

  • vertex_count (int)

  • arrays_present (list[str])

  • bin_shape (tuple[float, ...] | None)

  • bin_ratio (tuple[float, ...] | None)

  • chunk_shape (tuple[float, ...] | None)

  • object_sparsity (float)

  • coarsening_method (str)

  • parent_level (int | None)

  • chunk_dims (list[str] | None)

  • chunk_attribute_name (str | None)

  • chunk_attribute_values (list[Any] | None)

  • chunk_sources (list[dict[str, Any]] | None)

  • preserves_object_ids (bool)

  • inherited_num_objects (int | None)

  • shared_fragments (bool)

  • fragments_tile (bool)

  • link_fragments_aligned (bool)

  • octree_chunks (dict[str, Any] | None)

Return type:

None

zarr_vectors.building.compute_bin_shape(base_bin_shape, bin_ratio)[source]

Compute the bin shape at a coarser level.

Parameters:
  • base_bin_shape (tuple[float, ...]) – Supervoxel edge lengths at level 0.

  • bin_ratio (tuple[int, ...]) – Integer fold-change per dimension.

Returns:

tuple(base * ratio for each dimension).

Raises:

MetadataError – If lengths don’t match.

Return type:

tuple[float, …]

zarr_vectors.building.compute_bin_ratio(base_bin_shape, level_bin_shape)[source]

Compute the bin ratio from base and level bin shapes.

Parameters:
  • base_bin_shape (tuple[float, ...]) – Supervoxel edge lengths at level 0.

  • level_bin_shape (tuple[float, ...]) – Supervoxel edge lengths at this level.

Returns:

Integer ratio per dimension.

Raises:

MetadataError – If the ratio is not integer in any dimension.

Return type:

tuple[int, …]

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:

  1. level_meta.bin_shape when set – the authoritative absolute value;

  2. 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;

  3. else the root’s effective bin (level 0, or a level that does not bin).

bin_shape is preferred over bin_ratio deliberately: the ratio is the level-0-relative view and reconstructing an absolute from it is one multiplication further from the source of truth.

Parameters:
Return type:

tuple[float, …]

zarr_vectors.building.get_level_chunk_shape(root_meta, level_meta)[source]

Return the effective chunk_shape for a level.

Resolves the v0.7 per-level override: when level_meta carries a non-None chunk_shape, that value wins. Otherwise the level inherits RootMetadata.chunk_shape. Pass level_meta=None to get the root chunk_shape (useful when only the level index is known but the LevelMetadata hasn’t been read yet).

Parameters:
Return type:

tuple[float, …]

zarr_vectors.building.chunk_scale_factor(root_meta, level_meta)[source]

Deprecated alias for chunk_scale_from_root().

Parameters:
Return type:

tuple[int, …]

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_shape is r_i × root_chunk_shape[i] along axis i, returns (r_0, r_1, ..., r_{ndim-1}). A level that inherits root returns all-ones. Raises MetadataError when the per-level chunk_shape isn’t an integer multiple of root along some axis (nesting violation).

Root-relative, and named so. coarsen_level’s chunk_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 called chunk_scale_factor nothing at the call site distinguished them, and reading one as the other compounds silently. The old name remains as a deprecated alias.

Parameters:
Return type:

tuple[int, …]

zarr_vectors.building.level_chunk_scale(root_meta, level_meta, parent_meta)[source]

The PARENT-relative chunk factor – what chunk_scale_factor means.

The chunk counterpart of level_factor(). Contrast chunk_scale_from_root(), which answers the level-0-relative question and is what LevelMetadata records.

Parameters:
Return type:

tuple[int, …]

zarr_vectors.building.level_factor(root_meta, level_meta, parent_meta)[source]

The PARENT-relative bin factor – what coarsen_factor means.

bin_ratio is level-0-relative and bin_shape is absolute, so neither is the number coarsen_level wants. This is that number.

parent_meta is None for 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_level takes one), so letting axis 0 speak for the rest would silently discard the others.

Parameters:
Return type:

tuple[float, …]

zarr_vectors.building.validate_bin_shape_divides_chunk(chunk_shape, bin_shape)[source]

Validate that chunk_shape is an integer multiple of bin_shape.

Raises:

MetadataError – If any dimension is not evenly divisible.

Parameters:
Return type:

None

zarr_vectors.building.validate_level_chunk_shape_against_root(root_meta, level_meta)[source]

Cross-level invariants for a per-level chunk_shape override.

Validates:

  1. Per-axis positive integer multiple of root chunk_shape (nested chunk grids).

  2. Per-axis divisibility by the effective per-level bin_shape so 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_shape looks like it would close a gap – a coarse level takes its bin_shape from 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:
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 coord floor(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 at origin = floor(min_corner / chunk_shape) (per axis) and store that offset on the array, so cell index = coord - origin and the array only needs to span floor(max_corner / chunk_shape) - origin + 1 cells. Using ceil(max_corner / chunk_shape) would also be one short whenever a point lands exactly on a chunk boundary — floor(..) + 1 is exact.

Parameters:
Return type:

tuple[tuple[int, …], tuple[int, …]]

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 spans floor(hi/c) - floor(lo/c) + 1 cells, which is larger whenever hi lands on a cell boundary or lo does not. Use grid_layout() to predict what a store will allocate.

Parameters:
  • bounds (tuple[NDArray[floating], NDArray[floating]]) – (min_corner, max_corner).

  • chunk_shape (tuple[float, ...]) – Physical chunk size per dimension.

Returns:

Tuple of chunk counts per dimension. Each value is at least 1.

Return type:

tuple[int, …]

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 multiscales block, or None if it has none.

Parameters:

root (FsGroup)

Return type:

dict[str, Any] | None

zarr_vectors.building.write_multiscale_metadata(root)[source]

Rewrite the layout to list exactly the store’s resolution levels.

Returns:

The multiscales block written to the root attributes.

Parameters:

root (FsGroup)

Return type:

dict[str, Any]

zarr_vectors.building.upsert_level_transform(root, level, *, scale=None, translation=None)[source]

Ensure level is listed in the multiscales layout.

scale and translation are 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’s base_bin_shape (see the module docstring).

Parameters:
Return type:

None

zarr_vectors.building.get_level_scale(root, level)[source]

A level’s scale (level 0’s, [1.0] * ndim), or None if unlisted.

Parameters:
  • root (FsGroup)

  • level (int)

Return type:

list[float] | None

zarr_vectors.building.get_level_translation(root, level)[source]

A level’s translation (base_bin_shape / 2), or None if unlisted.

Parameters:
  • root (FsGroup)

  • level (int)

Return type:

list[float] | None

zarr_vectors.building.register_coarsen_strategy(name, fn)[source]

Register a whole-pyramid coarsening method under name.

Called by zarr-vectors-tools on import. name must not shadow a core built-in ("binning").

Parameters:
Return type:

None

zarr_vectors.building.register_selection_strategy(name, fn)[source]

Register an object-selection strategy under name.

Called by zarr-vectors-tools on import. name must not shadow a core built-in ("random").

Parameters:
Return type:

None

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.

Parameters:
  • level_group (Group) – The resolution level FsGroup.

  • dtype (str) – Numpy dtype string for vertex positions.

  • encoding (str) – "raw" or "draco".

  • exist_ok (bool) – When True (default), no-op if the array already exists. When False, raise ArrayError on conflict.

Return type:

None

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; ncols is only needed for a multi-column attribute whose channels are unnamed.

  • ncols (int | None) – Columns per row. None (default) infers from channel_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 attribute object_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; ncols is only needed for a multi-column attribute whose channels are unnamed.

  • ncols (int | None) – Columns per row. None (default) infers from channel_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 race record_presence=False exists to avoid. Coordinators should prefer zarr_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 ArrayError on conflict.

Return type:

None

zarr_vectors.building.create_object_index_array(level_group, *, exist_ok=True)[source]

Create the object_index/ array.

Parameters:
  • level_group (Group) – Resolution level group.

  • exist_ok (bool) – When True (default), no-op if the array already exists. When False, raise ArrayError on conflict.

Return type:

None

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 the exist_ok conflict check — dtype and num_channels are 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 ArrayError on 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 the exist_ok conflict check.

Parameters:
  • level_group (Group) – Resolution level group.

  • exist_ok (bool) – When True (default), no-op if the array already exists. When False, raise ArrayError on conflict.

Return type:

None

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 the exist_ok conflict check.

Parameters:
  • level_group (Group) – Resolution level group.

  • name (str) – Attribute name.

  • dtype (str) – Informational only in 0.8.1.

  • num_channels (int) – Informational only in 0.8.1.

  • exist_ok (bool) – When True (default), no-op if the array already exists. When False, raise ArrayError on conflict.

Return type:

None

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. offsets all-zero is the intra-chunk array (what was a standalone links/<delta>/ array before the offset layout); non-zero offsets hold records whose other endpoints sit that far away — what used to be cross_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 offsets is None so the intra segment can be derived.

  • offsets (Sequence[tuple[int, ...]] | None) – The link_width - 1 relative 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 ArrayError on conflict.

Return type:

None

Stamp the links/<delta>/ family group’s policy, nothing else.

directed / store / link_width / sid_ndim are family-wide: every offsets array under the delta decodes against them, which is why they live on the group and why write_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 store is 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

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; pass exist_ok=False to raise ArrayError on conflict.

row_shape is the tail shape of one row ([] for a scalar column, [k] for k channels). 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.

Parameters:
Return type:

None

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, one links/0/<offsets> array per neighbour offset (positive half for an undirected canonical family), the intra segment and its fragment sidecar with include_intra, and the parallel link_attributes arrays for attributes / intra_attributes ({name: dtype} or {name: (dtype, row_shape)}).

Returns:

links first, then attributes.

Return type:

Every array path ensured

Parameters:
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; then len(channel_names); then 1. dtype comes 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 own ncols = 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.

Parameters:
  • scope (str) – "vertex" or "fragment".

  • level_group (Group)

  • name (str)

Return type:

tuple[dtype, int]

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 concurrent set_coordinate_selection().

bounds and chunk_shape are 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 the sharding_indexed codec so many chunks pack into one storage object. None means explicitly unsharded, one storage object per spatial chunk.

    The "inherit" sentinel keeps “I did not say” apart from “I said no”: only an explicit None asks 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 bounds for 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 with zarr_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.

Parameters:
  • level_group (Group) – Resolution level group.

  • array_name (str) – Array name (default: "vertices").

Returns:

Sorted list of chunk coordinate tuples.

Return type:

list[tuple[int, …]]

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) + 1 over the chunk’s fragment index — the length per-vertex attribute cells must be written at, and the row count read_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.

Parameters:
Return type:

int

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 via fi.indices(f) gather.

Parameters:
  • level_group (Group) – Resolution level group.

  • chunk_coords (tuple[int, ...]) – Spatial chunk coordinates.

  • dtype (dtype | str | None) – Numpy dtype. None (the default) reads the dtype the store declares — see vertices_dtype(). Pass one only to override, and only knowing that a wrong value does not raise: a float64 cell read as float32 decodes 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:

list[NDArray[floating]]

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.

  • chunk_coords (tuple[int, ...]) – Spatial chunk coordinates.

  • dtype (dtype | str | None) – Element dtype. None (the default) reads the dtype the store declares — see vertices_dtype().

  • ndim (int) – Number of coordinate dimensions (D).

  • default (Any) – When supplied, returned instead of raising when the vertices array cannot be read at all. Pass None for 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,) when ndim == 1), or default.

Raises:

ArrayError – If the array cannot be read and no default is given.

Return type:

NDArray[floating] | Any

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 via fi.indices(fragment_index).

Parameters:
  • level_group (Group) – Resolution level group.

  • chunk_coords (tuple[int, ...]) – Spatial chunk coordinates.

  • fragment_index (int) – Index of the fragment within the chunk.

  • dtype (dtype | str) – Numpy dtype.

  • 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. Pass None for the common “soft-fail with None” pattern. Only ArrayError and StoreError are caught; programming errors propagate.

Returns:

Array of shape (N, D) (or (N,) when ndim == 1), or default when supplied and the read fails.

Return type:

NDArray[floating] | Any

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() at fragment_index: rows are gathered by vertex index from the shared per-vertex buffer (range fragments as a contiguous slice, explicit fragments via fi.indices), flattened, then reshaped to honour ncols.

Parameters:
  • level_group (Group) – Resolution level group.

  • attr_name (str) – Attribute name.

  • chunk_coords (tuple[int, ...]) – Spatial chunk coordinates.

  • fragment_index (int) – Index of the fragment within the chunk.

  • dtype (dtype | str | None) – Numpy dtype of the attribute.

  • 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. Only ArrayError and StoreError are caught; programming errors propagate.

Returns:

Array of shape (N, ncols) (or (N,) when ncols == 1), or default when 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 vertices buffer (Core-1’s fragment 0). Each fragment is gathered by vertex index from the shared attribute buffer via the vertex_fragments/<chunk> index — range fragments as contiguous slices, explicit fragments via fi.indices(f) — exactly as read_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.

  • chunk_coords (tuple[int, ...]) – Spatial chunk coordinates.

  • dtype (dtype | str | None) – Numpy dtype of the attribute.

  • 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,) when ncols == 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 to vertex_fragments is needed.

Parameters:
  • level_group (Group) – Resolution level group.

  • attr_name (str) – Attribute name.

  • chunk_coords (tuple[int, ...]) – Spatial chunk coordinates.

  • 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, else len(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 None for the common “soft-fail with None” pattern. Only ArrayError and StoreError are caught; programming errors propagate.

  • device (str | None)

Returns:

Array of shape (F,) (when ncols == 1) or (F, ncols) (when ncols > 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 ChunkFragmentIndex view describing how rows of vertices/<chunk> partition into fragments.

Parameters:
Return type:

ChunkFragmentIndex

zarr_vectors.building.decode_fragment_index(blob)[source]

Decode a vertex_fragments / link_fragments cell’s bytes.

The decode half of read_vertex_fragment_index(), for bytes already held; returns the same ChunkFragmentIndex.

Parameters:

blob (bytes)

Return type:

Any

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 to vertex_fragments/ describing each group as a contiguous range of vertex rows in source order.

Parameters:
  • level_group (Group) – Resolution level group.

  • chunk_coords (tuple[int, ...]) – Spatial chunk coordinates.

  • groups (list[NDArray[floating]]) – List of arrays, each (N_k, D).

  • dtype (dtype | str) – Numpy dtype for serialisation.

  • record_presence (bool)

Returns:

(K,) int64 array of vertex byte offsets (kept for backwards- compatible signature; callers that need the v0.6 fragment-index should use read_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/ or link_fragments/.

Fragments come as new_fragments ((start, count) tuples and 1-D index arrays) or csr=(indices, offsets); bytes match encode_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 inside batched_reads.

Returns:

the new fragment indices ([] for an empty append, which leaves the blob alone). csr form: (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_fragments and the attribute dtype/ncols. No sibling _offsets blob is written.

Parameters:
  • level_group (Group) – Resolution level group.

  • attr_name (str) – Attribute name (e.g. "radius").

  • chunk_coords (tuple[int, ...]) – Spatial chunk coordinates.

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

  • dtype (dtype | str) – Numpy dtype.

  • record_presence (bool) – Whether to stamp this cell into the array’s nonempty_chunks manifest. Pass False when fanning per-chunk writes out concurrently, then rebuild the manifest once with Group.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 against vertex_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").

  • chunk_coords (tuple[int, ...]) – Spatial chunk coordinates.

  • data (NDArray) – (F,) for scalar or (F, C) for multi-channel, where F is the number of fragments in this chunk.

  • dtype (dtype | str) – Numpy dtype to cast data to before writing.

  • record_presence (bool) – Whether to stamp this cell into the array’s nonempty_chunks manifest. Pass False from 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 via FsGroup.derive_nonempty_chunks(). See write_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.

Raises:

StoreError – array_name is not a per-chunk array here.

Parameters:
Return type:

list[str]

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: object

Stream 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 (close runs 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.

__init__(level_group, base_oid, sid_ndim, fragment_group_oids, length_attr='length')[source]
Parameters:
  • level_group (FsGroup)

  • base_oid (int)

  • sid_ndim (int)

  • fragment_group_oids (Sequence[int])

  • length_attr (str)

Return type:

None

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 shape write_object_index accepts per object — encoded internally as mode-0 single-fragment blocks. lengths[i] is that object’s int length. len(manifests) == len(lengths).

Parameters:
Return type:

None

close()[source]

Flush everything and write object_index meta, length, groupings.

Returns:

total_objects = base_oid + (total appended).

Return type:

int

zarr_vectors.building.object_count(level_group)[source]

How many objects this level declares, without decoding any of them.

Parameters:

level_group (Group)

Return type:

int

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_ref may be:

    • an int (single fragment index, mode 0),

    • a (start, count) tuple (contiguous range, mode 1), or

    • a 1-D integer array (auto-detected: arange → range, otherwise explicit list).

  • sid_ndim (int) – Rank of the chunk-coordinate space. All chunk_coords tuples 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 B per-block payloads. An empty list returns 4 bytes (B=0).

Return type:

bytes

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_ref is one of:

  • int for 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.

Parameters:
Return type:

list[tuple[tuple[int, …], int | tuple[int, int] | NDArray[int64]]]

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 use zarr_vectors.encoding.fragments.decode_object_manifest_blocks() directly.

Parameters:

blocks (list[tuple[tuple[int, ...], Any]])

Return type:

list[tuple[tuple[int, …], int]]

zarr_vectors.building.read_object_manifests(level_group, *, ids=None)[source]

Read the manifests of specific objects.

read_all_object_manifests decodes 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, the OBJECT_INDEX_LAYOUT_V1 sentinel and a raw zarr_group[...].get_coordinate_selection to do this, which means a consumer pinned to three internals purely to avoid an O(N) decode.

Parameters:
  • level_group (Group) – Resolution level group.

  • ids (Sequence[int] | None) – Object ids to read. None reads them all, which is the same work as read_all_object_manifests and is offered so a caller need not branch.

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:

dict[int, list[tuple[tuple[int, …], int]]]

zarr_vectors.building.read_object_manifests_csr(level_group, ids)[source]

The manifests of the objects ids, as a ManifestCSR.

Row o is the o-th id found, in the order asked; unknown ids are left out, as in read_object_manifests().

Parameters:
Return type:

ManifestCSR

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 later at=num_objects append 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.

Returns:

The metadata keys written.

Parameters:
  • level_group (Group)

  • num_objects (int)

  • sid_ndim (int | None)

  • num_present (int | None)

  • object_ids_sorted (bool | None)

Return type:

dict[str, Any]

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_objects rows, 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, dense manifest_blocks to n_blocks rows (every worker’s aligned region), and each of columns ({name: dtype | (dtype, row_shape[, fill])}). shard_rows (a multiple of 65,536) shards new arrays, refused if the layer has another; dense block_dtype must match existing blocks. Leaves num_objects to commit_object_index().

Returns:

{"rows", "layout", "arrays", "at_alignment", "block_alignment"}.

Parameters:
  • level_group (Group)

  • n_objects (int)

  • sid_ndim (int | None)

  • layout (str | None)

  • n_blocks (int | None)

  • columns (Mapping[str, Any] | None)

  • shard_rows (int | None)

  • block_dtype (Any)

Return type:

dict[str, Any]

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 one reserve_object_rows(), the object layer may be filled by mode="place" ranges [at, at + n) at multiples of at_alignment (the last may end at the reserved end); then one commit_object_index.

  • at_alignment / block_alignment: those multiples, for rows and dense block_at (a new unsharded layer’s without level_group).

Not covered: at= appends, metadata writes, and two processes writing one link cell.

Parameters:

level_group (Group | None)

Return type:

dict[str, Any]

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 i gets [starts[i], starts[i] + counts[i]), and the total to reserve is starts[-1].

Parameters:
  • counts (Any)

  • alignment (int)

Return type:

NDArray[int64]

zarr_vectors.building.is_dense_index(level_group)[source]

Whether the level’s object index uses the dense layout.

Decided by the layout stamp, else the arrays on disk; False when the level has no object index.

Parameters:

level_group (Group)

Return type:

bool

zarr_vectors.building.read_all_object_manifests(level_group)[source]

Read all object manifests at once.

Returns:

List indexed by object_id, each a list of (chunk_coords, fragment_index).

Parameters:

level_group (Group)

Return type:

list[list[tuple[tuple[int, …], int]]]

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.

Parameters:
  • level_group (Group) – Resolution level group.

  • object_id (int) – Object ID.

  • dtype (dtype | str) – Numpy dtype.

  • ndim (int) – Number of coordinate dimensions.

Returns:

List of fragment arrays in reconstruction order.

Return type:

list[NDArray[floating]]

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. When None (default), there is one row per id in manifests.

  • layout (str | None) – "vlen" or "dense" (see zarr_vectors.core.dense_manifests). None keeps the index’s current layout, or takes the store’s manifest_layout for a new one.

  • block_dtype (Any) – Dense only: "int64" or "int32" for manifest_blocks. None keeps a dense index’s current dtype, or takes the store’s manifest_block_dtype. This rewrites every array, so it may change it.

Raises:

ArrayError – When total_objects would add more than OBJECT_INDEX_MAX_ROWS rows with no object in them, or a block does not fit an int32 index.

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 with encode_object_manifest_blocks());

  • as arrays: object o owns blocks manifest_offsets[o]:manifest_offsets[o + 1], block b naming fragment fragment_idx[b] of chunk chunk_coords[b]. Without manifest_offsets every 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 takes layout, or the store’s manifest_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_objects and the rest) stays the caller’s step, which commit_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 by reserve_object_rows() and nothing else – no resize, no padding, no metadata – so several processes may place disjoint, aligned ranges at once (see concurrency_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; None appends 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 of manifest_blocks this call’s fragments occupy.

  • block_dtype (Any) – Dense only: "int64" or "int32", the dtype of the manifest_blocks this call creates (default: the store’s manifest_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 raises ArrayError before anything is written. Ignored for a vlen index.

Return type:

tuple[int, int]

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.

Returns:

where the written manifests start, and how many.

Return type:

(first_row, n)

Parameters:
  • level_group (Group)

  • manifest_blobs (Any)

  • chunk_coords (Any)

  • fragment_idx (Any)

  • manifest_offsets (Any)

  • ids (Any)

  • mode (str)

  • at (int | None)

  • layout (str | None)

  • block_at (int | None)

  • block_dtype (Any)

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 single edit_vertex spent 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_present is 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 against level_group.read_array_fill_value(...).

Parameters:
  • level_group (Group) – Resolution level group.

  • attr_name (str) – Attribute name.

  • dtype (dtype | str | None) – Optional override applied via astype after read.

Returns:

Array of shape (O,) or (O, C).

Return type:

NDArray

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_value rather than as a sibling present_mask array, 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.

Returns:

uint8 mask (1 = present, 0 = absent), or None when every row is present (so callers can skip allocating a full mask). Also returns None when the attribute is missing.

Parameters:
Return type:

NDArray[uint8] | None

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 by present_mask) are encoded in-band using fill_value — no sibling present_mask child array is written. Stock Zarr v3 tooling can read the array without library-specific decoding; absent positions are visible as the array’s fill_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. In mode="append" this is the NEW rows to append.

  • present_mask (NDArray | None) – Optional (O,) byte array (0/1 per object) marking real rows. When provided, absent rows (mask[i] == 0) are overwritten with fill_value before write; callers that already encoded sentinels in data should leave this None.

  • 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 persisted fill_value.

  • mode (Literal['replace', 'append', 'place']) – "replace" (default) writes data as the full array. "append" reads the existing array, concatenates data along 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 of write_object_manifests()’s at, and the reason to pass it is the same: nothing on disk ties a row to an object, so row i means object i by position alone, and a column that drifted from the index silently rebinds every later append to the wrong object. A column short of at is padded with fill_value; a column reaching past it (the residue of a flush killed before it committed, whose rows no reader can address) is truncated back to at. None appends at the current end. With mode="place", the first of the reserved rows [at, at + n) to write in place (see write_object_attribute_columns()).

Raises:

ArrayError – If mode is invalid, at is negative or given with mode="replace", present_mask length mismatches data, the dtype has no default sentinel and no fill_value is 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. at makes 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); None appends 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_objects as the last write’s end (commit_object_index()).

  • block_dtype (Any) – "int64" or "int32", as write_object_manifests takes it; every write’s blocks are checked against the index’s dtype.

  • level_group (Any)

Returns:

An ObjectManifestWriter; its write takes what write_object_manifests takes, less mode/at/layout.

Return type:

ObjectManifestWriter

class zarr_vectors.building.ObjectManifestWriter(level_group, at=None, *, layout=None, commit=False, block_dtype=None)[source]

Bases: object

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

Parameters:
  • level_group (Any)

  • at (int | None)

  • layout (str | None)

  • commit (bool)

  • block_dtype (Any)

__init__(level_group, at=None, *, layout=None, commit=False, block_dtype=None)[source]
Parameters:
  • level_group (Any)

  • at (int | None)

  • layout (str | None)

  • commit (bool)

  • block_dtype (Any)

Return type:

None

close()[source]

Write what is held, then commit if asked. Returns (first_row, rows written), or None if nothing was written.

Return type:

tuple[int, int] | None

property end: int

The row the next write starts at.

property first_row: int | None

The row the first write started at (None before it).

flush()[source]

Write every held row now, whole storage objects or not.

Return type:

None

write(manifest_blobs=None, *, chunk_coords=None, fragment_idx=None, manifest_offsets=None, ids=None)[source]

Write the next objects; returns (first_row, n) as write_object_manifests does.

Parameters:
  • manifest_blobs (Any)

  • chunk_coords (Any)

  • fragment_idx (Any)

  • manifest_offsets (Any)

  • ids (Any)

Return type:

tuple[int, int]

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.

Parameters:
  • store_path – Store path, URL or open group.

  • level (int | None) – Only this resolution level. None does every level.

Returns:

How many fragments were recorded.

Return type:

int

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 a range for an implicitly-stored contiguous group (see write_groupings()).

Parameters:

level_group (Group)

Return type:

list[Sequence[int]]

zarr_vectors.building.read_group_object_ids(level_group, group_id)[source]

Read the object IDs belonging to a group.

Parameters:
  • level_group (Group) – Resolution level group.

  • group_id (int) – Group ID.

Returns:

The member object IDs. A group written from a range (see write_groupings()) is returned as a range — O(1) rather than materialising up to a billion ints. Explicit groups are returned as a list[int]. Both support len(), indexing and iteration.

Return type:

Sequence[int]

zarr_vectors.building.read_groupings_attributes(level_group, attr_name, dtype=None)[source]

Read dense G×C groupings attribute data.

Parameters:
Return type:

NDArray

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 legacy groups/data + groups/offsets CSR pair with the same vlen layout already used by object_index/manifests.

A group whose members form a contiguous range(start, stop) may be passed as a range object. It is stored implicitly as a [start, stop) descriptor in the array’s group_ranges attribute (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.

Parameters:
  • level_group (Group) – Resolution level group.

  • groups (dict[int, list[int] | range]) – {group_id: [object_id, ...] | range, ...}. Group IDs must be contiguous starting from 0. A range value must have step == 1.

Return type:

None

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. Unlike write_object_attributes(), no sentinel / present-mask handling — groupings attributes are always fully populated.

Parameters:
  • level_group (Group) – Resolution level group.

  • attr_name (str) – Attribute name.

  • data (NDArray) – (G,) or (G, C) array.

Return type:

None

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_chunks is 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, whatever record_presence says. Readers ask the store instead, except offline-read sessions, stores that cannot list and zarr-vectors older than 0.9.3, which see nothing until rebuild_presence() (or set_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.

Returns:

Every per-chunk array path in the level.

Parameters:

level_group (Group)

Return type:

list[str]

zarr_vectors.building.refresh_arrays_present(level_group)[source]

Re-derive the level’s arrays_present from what is on disk.

arrays_present is hand-listed at every write site, so it drifts: an ordinary write_points declared ["vertices", "vertex_attributes"] while vertex_fragments sat 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.

Parameters:

level_group (Group)

Return type:

list[str]

zarr_vectors.building.rebuild_presence(level_group, array_name=None, *, on_sharded='derive')[source]

Rebuild nonempty_chunks from the store — one array, or the level.

The coordinator half of decentralised writing: workers writing disjoint cells pass record_presence=False because 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:

list[str]

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. cells maps 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: StoreError for an array that is not per-chunk here, ArrayError for 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" raises PresenceMismatchError before writing; "derive" takes the failing arrays from the store. end_deferral then calls end_presence_deferral(). Returns the array names written, sorted.

Parameters:
Return type:

list[str]

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:
  • missing (str) – For per-chunk arrays still without a manifest, which would otherwise stay store-derived for good: "raise" (default) names them and changes nothing; "derive" rebuilds each first.

  • level_group (Group)

Returns:

The arrays derived under missing="derive" (empty otherwise).

Return type:

list[str]

exception zarr_vectors.building.PresenceMismatchError(mismatches)[source]

Bases: StoreError

Supplied presence does not match what the store holds.

Raised by set_presence(..., verify=...) before anything is written. mismatches maps 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

__init__(mismatches)[source]
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’s array_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.

Parameters:

level_group (Group)

Return type:

list[str]

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 spelled is_sharded a caller who swapped one import line for the other got no error: the path went in as level_group, the lookup failed, and the old bare except returned False. For a whole store that is a plausible answer, so nothing surfaced. Use get_shard_info() for the store-wide question; it is already exported here.

Raises:

StoreError – If level_group is not a Group. A missing or non-array path is still False — that is a real answer, unlike being handed the wrong kind of object.

Parameters:
Return type:

bool

zarr_vectors.building.is_sharded(level_group, array_name)[source]

Deprecated alias for array_is_sharded().

Parameters:
Return type:

bool

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.

Parameters:
  • chunk_coords (Iterable[Any]) – Absolute chunk coordinates, as tuples or rows of a (C, K) array.

  • level_group (Group)

  • array_name (str)

Raises:
  • StoreError – array_name is not a per-chunk array here.

  • ArrayError – A cell lies outside the array’s grid.

Return type:

list[str]

zarr_vectors.building.shard_object_layer(level_group, shard_rows)[source]

Repack a level’s object layer into shards of shard_rows rows.

The object layer (object_index’s arrays and every object_attributes/<name> column) is chunked in fixed row buckets (16,384 index rows, 65,536 attribute rows); sharding packs shard_rows // bucket buckets per storage object. shard_rows must be a multiple of 65,536; None unshards. Sharding is zarr’s own sharding_indexed codec, 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.

Returns:

{"arrays_repacked": [...], "shard_rows": shard_rows}.

Parameters:
  • level_group (Group)

  • shard_rows (int | None)

Return type:

dict[str, Any]

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()) of arrays (default: every per-chunk array), else ShardOwnershipError. 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 (from io_threads threads) and renamed into place once all are written; an exception publishes nothing. durable=True fsyncs every partial (all together, after the writes) before the renames, then the directories; durable="deferred" does not, leaving it to a later sync_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.written feeds set_presence()). sweep removes a failed attempt’s .partial files 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. See zarr_vectors.core.shard_txn.

Parameters:
Return type:

Any

zarr_vectors.building.shard_of(level_group, chunk_coords, array_name='vertices')[source]

The index of the shard holding cell chunk_coords of array_name.

What shard_transaction() takes. A level’s arrays normally share grid origin and shard shape, so one answer serves them all.

Parameters:
Return type:

tuple[int, …]

exception zarr_vectors.building.ShardOwnershipError[source]

Bases: StoreError

A 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 None if 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.

Parameters:

level_group (Group)

Return type:

int | None

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 moved FORMAT_VERSION.

Parameters:
Return type:

StoreLayout

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: object

How a store’s bytes are laid out, as read from the store.

Parameters:
created_by

zv_version stamped at creation (never updated).

Type:

str | None

format_capabilities

Capability tokens the store declares.

Type:

tuple[str, …]

shard_shape

Declared cells per shard; None for one object per cell.

Type:

tuple[int, …] | int | None

object_index

The level’s object-index layout, or None.

Type:

str | None

{delta: (directed, store)} for each link family.

Type:

dict[int, tuple[bool, str]]

presence_deferred

The level is under defer_presence().

Type:

bool

min_reader

Oldest zarr-vectors format that reads this layout.

Type:

str

object_shard_rows

Rows per shard of the object layer (shard_object_layer()); None if 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)
Parameters:
Return type:

None

zarr_vectors.building.user_metadata(group)[source]

The user-metadata namespaces on group.

The object zarr_vectors.api.Dataset.metadata returns: user_metadata(g)["ns"] is one application’s MutableMapping, kept apart from the format’s own attributes; names() lists them.

Parameters:

group (Group)

Return type:

Any

zarr_vectors.building.observe_presence_writes(callback)[source]

Call callback for every incremental nonempty_chunks stamp.

A test instrument for asserting where a stamp happened (inside a lock, on which thread). callback runs synchronously on the writing thread as the stamp lands; keep it cheap, since an exception propagates into the writer. Covers Group.write_bytes(), Group.write_cells(), Group.apply_presence() and the Group.batched_writes() flush, not Group.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"]
Parameters:

callback (Callable[[PresenceEvent], None])

Return type:

Iterator[None]

Note

observe_presence_writes is a debugging instrument, not a data API. To read the manifest, use Group.list_chunks.

Sharding and rechunking

Re-layout of an existing store. These are coordinator operations: never run one while workers are writing. See Sharding and Rechunking.

zarr_vectors.building.get_shard_info(store_path)[source]

Return a summary of the store’s sharding state.

The result has keys:

  • sharded — bool, mirrors is_sharded().

  • arrays — list of {name, shard_shape, grid_shape} dicts, one per native-sharded array, ordered by level then array path.

  • shard_count — total shard files across all arrays.

Parameters:

store_path (str | Path | Group)

Return type:

dict[str, Any]

zarr_vectors.building.shard_store(store_path, *, shard_shape=8, arrays=None, object_shard_rows=None)[source]

Repack every per-chunk array in the store with the sharding_indexed codec.

The new layout uses Zarr v3’s built-in sharding_indexed codec — readable by any standards-compliant Zarr v3 implementation (zarrs, tensorstore, neuroglancer-precomputed/zarr3, …). No ZV-specific metadata is needed; the sharding configuration lives in each array’s zarr.json.

Parameters:
  • store_path (str | Path | Group) – Path or URL to the ZV store.

  • shard_shape (int | Sequence[int]) – Outer-chunk shape in inner-chunk units (one inner chunk == one Zarr Vectors spatial chunk). An int is broadcast to every axis (e.g. 8 → (8,8,8) for a 3-D store). A tuple sets the per-axis shard shape explicitly. Default 8 ≈ 512 inner chunks per shard, a reasonable cloud default per Sharding.

  • arrays (list[str] | None) – Optional list of logical array names to migrate. When omitted, every per-array container under every resolution level is converted.

  • object_shard_rows (int | None) – Also repack every level’s object layer into shards of this many rows (a multiple of 65,536); see shard_object_layer(). None leaves it alone.

Returns:

Stats dict with arrays_sharded, chunks_packed, shard_shape, and with object_shard_rows the object_arrays_repacked count.

Return type:

dict[str, Any]

zarr_vectors.building.unshard_store(store_path, *, arrays=None)[source]

Reverse of shard_store(): rewrite every native-sharded per-chunk array as an unsharded single vlen-bytes array — one storage object per spatial chunk (<array>/c/i/j/k).

The logical single-array layout is unchanged; only the Zarr v3 sharding_indexed packing is removed; with arrays=None the root shard_shape is cleared too. Useful for write-heavy workflows where shard read-modify-write contention hurts throughput, or when a reader prefers one file per chunk. On a store marked octree (set_octree()) the marker and its capability are removed once no zarr_octree_sharding array is left.

Parameters:
Return type:

dict[str, Any]

zarr_vectors.building.reshard(store_path, shard_shape, *, arrays=None)[source]

Re-layout a ZV store between unsharded and sharded packings.

Parameters:
  • store_path (str | Path | Group) – Path or URL to the store.

  • shard_shape (int | Sequence[int] | None) – None → unshard (one object per chunk); int or tuple → shard with that outer-chunk shape.

  • arrays (list[str] | None) – Optional list of logical array names to limit the operation to.

Returns:

Stats dict from the underlying shard_store() or unshard_store() call, plus action describing what ran.

Return type:

dict[str, Any]

class zarr_vectors.building.RechunkSpec(by, bins=None, spatial_chunk_shape=None, prefix_dim_name=None, categorical=False)[source]

Bases: object

Specification for rechunking a store along a non-spatial dimension.

The output’s bins are numbered densely from 0; a bin no object falls in is not allocated. Each bin’s label – the value a reader’s attribute_filter names to select it – is recorded in chunk_attribute_values: a categorical value, a bin’s lower edge, an object id, or a group index. Ungrouped objects under by="group" are the last bin, labelled -1.

Parameters:
  • by (str) – Dimension to rechunk by. One of: - "group" — chunk by group membership - "object_id" — chunk by object ID ranges - "attribute:<name>" — chunk by attribute value bins - "spatial" — re-spatial-chunk only (change chunk_shape)

  • bins (list[float] | None) – Explicit bin edges for continuous values. For by="object_id", these are ID boundaries. For by="attribute:length", these are value boundaries. If None and categorical is False, the legacy quartile-based auto-binning is used for attributes with >10 unique values.

  • spatial_chunk_shape (tuple[float, ...] | None) – Override spatial chunk shape for the output store. If None, keeps the source chunk shape.

  • prefix_dim_name (str | None) – Name of the leading axis: chunk_dims[0] and chunk_attribute_name, the key a reader’s attribute_filter uses. Defaults to the attribute’s name for "attribute:<name>" and to by otherwise.

  • categorical (bool) – If True, treat the binning dimension as categorical — every unique value gets its own bin regardless of how many unique values there are. Set this for gene labels, bundle labels, etc. Ignored when bins is also set.

__init__(by, bins=None, spatial_chunk_shape=None, prefix_dim_name=None, categorical=False)
Parameters:
Return type:

None

bins: list[float] | None = None
by: str
categorical: bool = False
property dimension_name: str

The leading axis’s name, recorded as both chunk_dims[0] and chunk_attribute_name.

For "attribute:<name>" it is <name>, as for a store written with chunk_by_attribute; it used to be "attribute", so the axis and the filter key disagreed.

prefix_dim_name: str | None = None
spatial_chunk_shape: tuple[float, ...] | None = None
zarr_vectors.building.rechunk(store_path, spec, output=None, *, overwrite=False)[source]

Rechunk a store along a non-spatial dimension.

Reads object data from the source store, assigns each object to a rechunk bin via DimensionMapper, and writes the result to an output store where chunk keys have a prefix dimension (bin, z, y, x).

Object ids are preserved, so object attributes, groupings and group attributes copy verbatim. Vertex attributes follow their vertices, shared fragments stay shared, and links/0 is re-addressed onto the new keys whatever its link_width (a link may join two bins). Under implicit_sequential, a fragment the new grid cuts gets a bridge link across each cut. Levels above 0, link/fragment attributes, a fragment shared by objects in different bins, and vertices no object names raise NotImplementedError before anything is written. by="spatial" is handed to rechunk_spatial().

Parameters:
  • store_path (str | Path) – Source store path.

  • spec (RechunkSpec) – Rechunk specification.

  • output (str | Path | None) – Output store path. If None, rechunks in-place by writing to a temporary store then replacing the source.

  • overwrite (bool) – Replace an existing output instead of raising.

Returns:

Summary dict with objects_rechunked, bins_created, total_vertices, rechunk_dims, output_path, links (records written to links/0) and dropped_links (source records naming no vertex, which cannot be carried).

Return type:

dict[str, Any]

zarr_vectors.building.rechunk_by_attribute(store_path, attribute_name, *, output=None, spatial_chunk_shape=None)[source]

Rechunk a store so that one chunk == one attribute value.

Categorical only — every unique value of the named per-object attribute becomes its own bin, regardless of how many unique values there are. Resulting chunk keys gain a leading dim: (attr_bin, z, y, x).

Parameters:
  • store_path (str) – Source store path or URL.

  • attribute_name (str) – Name of a per-object attribute already present on the source store (under object_attributes/<name>).

  • output (str | None) – Output path; if None, rechunks in place.

  • spatial_chunk_shape (tuple[float, ...] | None) – Optional new spatial chunk shape for the output store.

Returns:

The summary dict produced by rechunk().

Return type:

dict[str, Any]

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:
  • positions (NDArray[floating]) – (N, D) array of vertex positions.

  • chunk_shape (tuple[float, ...]) – Physical size per dimension. Length must equal D.

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:

dict[tuple[int, …], NDArray[int64]]

zarr_vectors.building.chunks_intersecting_bbox(bbox_min, bbox_max, chunk_shape)[source]

Return all chunk coordinates that intersect a bounding box.

Parameters:
  • bbox_min (NDArray[floating]) – (D,) minimum corner of query box.

  • bbox_max (NDArray[floating]) – (D,) maximum corner of query box.

  • chunk_shape (tuple[float, ...]) – Physical chunk size per dimension.

Returns:

Sorted list of chunk coordinate tuples.

Return type:

list[tuple[int, …]]

zarr_vectors.building.neighbouring_chunk_keys(key, *, halo=1, occupied_keys=None, include_self=False)[source]

Return chunk keys within halo of key along 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:
  • key (tuple[int, ...]) – The reference chunk coord.

  • halo (int) – Maximum per-axis distance. halo=1 returns the (3^ndim - 1) chunks adjacent on at least one face, edge, or corner; halo=2 widens 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, include key itself in the output.

Returns:

Sorted list of unique ChunkCoords tuples.

Return type:

list[tuple[int, …]]

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:
  • vertices (NDArray[floating]) – (N, D) ordered vertex positions.

  • chunk_shape (tuple[float, ...]) – Physical chunk size per dimension.

Returns:

List of (chunk_coords, segment_vertices) in polyline order. Each segment_vertices is (N_k, D).

Raises:

ChunkingError – If vertices is empty or dimensions mismatch.

Return type:

list[tuple[tuple[int, …], NDArray[floating]]]

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 of edges) are interpreted against src_vertex_chunks / src_vertex_local_indices / src_chunk_coords_list; target-side endpoint indices (column 1) use the tgt_* 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 in cross. Callers persist both through the merged links/<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 CrossChunkLink for 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.

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 by ndim * dtype.itemsize.

Parameters:
  • level_group – An open FsGroup for one resolution level.

  • ndim (int | None) – Coordinate columns per vertex. None derives 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_keys is the sorted lexicographic order used.

  • total_vertices is 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_vals of length L and the perm_idx produced by canonical_sort(), returns the values in their original input order.

Parameters:
Return type:

list

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 deprecated attributes kwarg.)

  • 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 as object_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.

  • bounds (tuple[list[float], list[float]] | None)

  • backend (str | None)

  • compressor (Any)

  • shard_shape (int | tuple[int, ...] | None | Literal['inherit'])

  • attributes (dict[str, npt.NDArray] | None)

Returns:

Summary dict.

Return type:

dict[str, Any]

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; replaces attributes.)

  • object_attributes (dict[str, npt.NDArray] | None) – Per-line (per-object) attributes as {name: (N,) or (N, C)}. (Spec name; replaces line_attributes.)

  • dtype (str) – Numpy dtype string for positions.

  • bin_shape (BinShape | None)

  • bounds (tuple[list[float], list[float]] | None)

  • backend (str | None)

  • chunk_by_attribute (str | None)

  • out_of_bounds (str)

  • compressor (Any)

  • shard_shape (int | tuple[int, ...] | None | Literal['inherit'])

  • attributes (dict[str, npt.NDArray] | None)

  • line_attributes (dict[str, npt.NDArray] | None)

Returns:

Summary dict with line_count, chunk_count, cross_chunk_count.

Return type:

dict[str, Any]

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 (see create_store()); only used when this call creates the store.

  • bin_shape (BinShape | None)

  • bounds (tuple[list[float], list[float]] | 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:

dict[str, Any]

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 boolean is_tree kwarg.

  • vertex_attributes (dict[str, npt.NDArray] | None) – Per-node attributes {name: (N,) or (N,C)}. (Spec name; replaces node_attributes.)

  • link_attributes (dict[str, npt.NDArray] | None) – Per-edge attributes {name: (M,) or (M,C)}. (Spec name; replaces edge_attributes.) With kind="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)

  • bounds (tuple[list[float], list[float]] | None)

  • object_attributes (dict[str, npt.NDArray] | 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)

  • node_attributes (dict[str, npt.NDArray] | None)

  • edge_attributes (dict[str, npt.NDArray] | None)

Returns:

Summary dict.

Return type:

dict[str, Any]

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)

  • bounds (tuple[list[float], list[float]] | None)

  • object_attributes (dict[str, npt.NDArray] | 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:

dict[str, Any]

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 be world - coordinate_offset so the spec’s origin-0 chunk grid aligns to the source grid. It is recorded in the root zarr_vectors.coordinate_offset.

shard_shape (optional, in units of spatial chunks) wraps each per-chunk array’s cells in Zarr v3’s sharding_indexed codec, so many chunks share one storage object — the same knob the whole-store writers (write_points, write_graph, …) take. compressor sets 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 own open_write_session() with the SAME shard_shape / bounds / chunk_shape passed here.

Returns (root, level0_group). Callers then stream write_skeleton_chunk() over chunks, reduce the records into an object index (zarr_vectors_tools.multiresolution.object_index), and finish with finalize_skeleton_store().

Parameters:
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 False from concurrent per-chunk writers — nonempty_chunks is 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()).

  • chunk_coords (tuple[int, ...]) – Spatial chunk coordinates.

  • pieces (list[dict[str, Any]]) – One dict per fragment with keys segment_id (int), positions (n, D), edges (m, 2) [child, parent] (root omitted), and attributes {name: (n, ...)}. Pieces should already be single rooted trees (use split_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.

  • dtype (dtype | str) – Vertex position dtype.

Returns:

(records, anchor_locs) where records is [(segment_id, chunk_coords, fragment_index), ...] for the object-index reduce and anchor_locs maps each anchor tag to (chunk_coords, chunk_local_index).

Return type:

tuple[list[tuple[int, tuple[int, …], int]], dict[Any, tuple[tuple[int, …], int]]]

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 in write_skeleton_chunk(). Stored directed=True so a canonical sort cannot swap them.

Parameters:
Return type:

None

zarr_vectors.building.finalize_skeleton_store(root)[source]

Finish a streamed skeleton store: stamp each level’s vertex_count and arrays_present from 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_branches skeleton 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 explicit links entries 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) where frag_ranges is a list of (start, count) over the reordered vertex array (one per path), branch_links are (child_order_idx, parent_order_idx) over the reordered indices (one per non-root path), and new_of_old[i] is the reordered index of input vertex i.

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.

Parameters:

offset (Sequence[float])

Return type:

None

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 via object_attributes/segment_id (sorted, binary search), follows the manifest, and reconstructs the merged skeleton (fragments concatenated; edges offset per fragment).

Returns None when the segment ID is absent. Otherwise a dict with positions (N, D), edges (M, 2) [child, parent], attributes {name: (N, ...)}, and fragment_count.

Parameters:
  • store_path (ReadSource)

  • segment_id (int)

  • level (int)

  • backend (str | None)

  • attributes (list[str] | None)

Return type:

dict[str, Any] | None

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_coords of every array in arrays at 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) or link_attributes/<name>/<delta>/<offsets>.

  • ndim (int | None) – Vertex coordinate width; None reads 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 in errors, with no rows; "raise" re-raises.

  • device (str | None) – "cpu", "cuda" or None (where chunk_coords lives).

  • 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, else zarr_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:

CellBatch

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 one read_cells().

The centre comes first, then the neighbours in sorted order. With present_only (the default), neighbours present_array holds 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.

Parameters:
  • level_group (Group)

  • chunk_coords (Sequence[int])

  • arrays (Sequence[str])

  • halo (int)

  • present_only (bool)

  • present_array (str)

  • read_cells_kw (Any)

Return type:

CellBatch

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(): one CellColumn per array.

chunk_coords is the requested cells in request order, on the host; the columns are on device. fragments is the vertices’ fragment index with fragments=True, else None. io says how each array read was served (ArrayRead), including vertices read only to size an unstamped attribute and vertex_fragments last. io_seconds holds fetch and decode (device) and host times. Neither takes part in equality.

Parameters:
__init__(chunk_coords, columns, errors=(), device='cpu', fragments=None, io=(), io_seconds=<factory>)
Parameters:
Return type:

None

chunk_coords: NDArray[int64]
columns: dict[str, CellColumn]
device: str = 'cpu'
errors: tuple[CellReadError, ...] = ()
fragments: FragmentColumn | None = None
io: tuple[ArrayRead, ...] = ()
io_seconds: dict[str, float]
to_device(device)[source]

The same batch on device: one copy per data/offsets array.

Parameters:

device (str)

Return type:

CellBatch

class zarr_vectors.building.CellColumn(data, offsets, _host_offsets)[source]

Bases: object

One array’s rows across the requested cells.

data[offsets[i]:offsets[i + 1]] are cell i’s rows. Both live on the batch’s device.

Parameters:
  • data (Any)

  • offsets (Any)

  • _host_offsets (NDArray[int64])

__init__(data, offsets, _host_offsets)
Parameters:
  • data (Any)

  • offsets (Any)

  • _host_offsets (NDArray[int64])

Return type:

None

property cell: Any

The cell index of every row, on data’s device (int32).

data: Any
property num_cells: int
offsets: Any
rows(i)[source]

Cell i’s rows (a view of data).

Parameters:

i (int)

Return type:

Any

class zarr_vectors.building.CellReadError(array, chunk_key, message)[source]

Bases: object

A cell that could not be read; the rest of the batch still was.

Parameters:
__init__(array, chunk_key, message)
Parameters:
Return type:

None

array: str
chunk_key: str
message: str
class zarr_vectors.building.ArrayRead(array, path, cells, stored_bytes)[source]

Bases: object

How one array’s cells reached a CellBatch.

path is gds (kvikio, GPUDirect Storage on), kvikio-compat (kvikio through cuFile’s bounce buffer), pinned-host (pinned host reads, one copy up) or store (byte-range gets from a non-local store, one copy up), all decoded on the device; or host (read and decoded on the host). stored_bytes is what was read from storage, before decompression; None for host.

Parameters:
  • array (str)

  • path (str)

  • cells (int)

  • stored_bytes (int | None)

__init__(array, path, cells, stored_bytes)
Parameters:
  • array (str)

  • path (str)

  • cells (int)

  • stored_bytes (int | None)

Return type:

None

array: str
cells: int
path: str
stored_bytes: int | None
class zarr_vectors.building.FragmentColumn(cell_offsets, starts, counts, index_offsets, indices)[source]

Bases: object

The vertex fragments of every requested cell, as flat arrays.

Cell i’s fragments are cell_offsets[i]:cell_offsets[i + 1], in fragment-index order. Fragment f holds counts[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.

Parameters:
  • cell_offsets (Any)

  • starts (Any)

  • counts (Any)

  • index_offsets (Any)

  • indices (Any)

__init__(cell_offsets, starts, counts, index_offsets, indices)
Parameters:
  • cell_offsets (Any)

  • starts (Any)

  • counts (Any)

  • index_offsets (Any)

  • indices (Any)

Return type:

None

cell_offsets: Any
counts: Any
index_offsets: Any
indices: Any
starts: Any
to_device(device)[source]
Parameters:

device (str)

Return type:

FragmentColumn

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, where read_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:
  • level_group (Group)

  • device (str | None)

Return type:

ManifestCSR

class zarr_vectors.building.ManifestCSR(offsets, chunk_coords, fragment_idx, object_ids=None)[source]

Bases: object

Every object’s manifest as flat arrays.

Object row o owns rows offsets[o]:offsets[o + 1] of chunk_coords and fragment_idx. object_ids[o] is its id, or object_ids is None when rows are the ids. Unpacks as offsets, chunk_coords, fragment_idx = read_all_object_manifests_csr(lg).

Parameters:
  • offsets (Any)

  • chunk_coords (Any)

  • fragment_idx (Any)

  • object_ids (Any)

__init__(offsets, chunk_coords, fragment_idx, object_ids=None)
Parameters:
  • offsets (Any)

  • chunk_coords (Any)

  • fragment_idx (Any)

  • object_ids (Any)

Return type:

None

chunk_coords: Any
fragment_idx: Any
object_ids: Any = None
offsets: Any
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 o owns the blocks manifest_offsets[o]:manifest_offsets[o+1]; block b names chunk chunk_coords[b] and fragment fragment_idx[b] in it (a single-fragment, mode-0 block). With manifest_offsets=None every object owns exactly one block. The blobs are the ones encode_object_manifest_blocks() writes for [(chunk_coords, int(fragment_idx)), ...], byte for byte.

Returns:

An object array of bytes, one per object, ready to store.

Parameters:
  • chunk_coords (Any)

  • fragment_idx (Any)

  • manifest_offsets (Any)

  • sid_ndim (int | None)

Return type:

NDArray[object_]

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 rows offsets[o]:offsets[o+1] of chunk_coords ((M, sid_ndim)) and fragment_idx ((M,)), in manifest order, with range and explicit-list blocks expanded to one row per fragment – the pairs decode_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 None blob is an object with no fragments.

Parameters:
Return type:

tuple[NDArray[int64], NDArray[int64], NDArray[int64]]

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 by reserve_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: object

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

__init__(source, *, level=0)[source]
Parameters:
Return type:

None

close()[source]
Return type:

None

read(chunks, *, max_bytes=None)[source]

Return complete faces owned by chunks and 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_bytes rejects 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 verified fragments_tile level claim; otherwise the index cannot bound unused physical rows in the buffer.

Parameters:
Return type:

dict[str, Any]

class zarr_vectors.building.MeshChunkInfo(key, bounds)[source]

Bases: object

An owner cell and conservative bounds of all its face endpoints.

Parameters:
__init__(key, bounds)
Parameters:
Return type:

None

bounds: tuple[tuple[float, ...], tuple[float, ...]]
key: tuple[int, ...]

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.path resolves against this store’s root. With fingerprint, each source’s source_fingerprint() is merged into its entry (caller’s keys win).

Parameters:
Return type:

list

zarr_vectors.building.chunk_sources(level_group)[source]

The level’s source table, or None for an ordinary level.

Return type:

list[dict] | None

zarr_vectors.building.is_composite(level_group)[source]
Return type:

bool

zarr_vectors.building.source_fingerprint(level_group)[source]

What identifies a source level’s content for a composite that references it.

Return type:

dict

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 StoreError for a source that cannot be opened and ArrayError for a fingerprint mismatch. Returns the table, or None for an ordinary level.

Return type:

list[dict] | None