Data API¶
The data-oriented public API.
Everything here is stable surface. zarr_vectors.core,
zarr_vectors.lazy, zarr_vectors.ops, zarr_vectors.encoding and
zarr_vectors.spatial are internal and may change between releases;
this package and zarr_vectors.building are the two that will not.
The names are re-exported from zarr_vectors itself, so the usual
spelling is:
import zarr_vectors as zv
ds = zv.open("scan.zarrvectors")
result = ds.select(bbox=(lo, hi)).read()
Every name in zarr_vectors.api.__all__ is also importable from
zarr_vectors. ResolvedLayout, GroupCatalog and ObjectGroup
are returned by other objects and importable only from their submodule.
Datasets¶
open() and
create() return a
Dataset, the entry point to everything
else. open_dataset and create_dataset are aliases.
The entry point: a dataset you can ask questions of.
zarr_vectors’ top-level namespace currently exports ten names, all of
them store-shaped — Group, create_store, open_store,
rebind. Not one of them is about the data. The consequence shows up
downstream: across four consuming repositories only three import sites go
through the top-level package, while core.store is imported in
seventy-seven files and core.arrays in sixty-seven. Every internal
change breaks them, because the internals are the interface they were
given.
Dataset is the interface they should have been given. It talks
about bounds, axes, geometry kinds and resolution levels; it never
mentions a chunk, a bin, a shard, a compressor or a backend. Underneath,
in this phase, it delegates to exactly the readers and writers that exist
today — so adopting it is safe before any internals move, which is the
whole point of introducing it first.
- class zarr_vectors.api.dataset.Dataset(group, *, storage=None)[source]¶
Bases:
objectA zarr-vectors store, addressed by what is in it.
Build one with
open(),create()oropen_or_create()rather than by calling the constructor.- Parameters:
group (Group)
storage (StorageOptions | None)
- __init__(group, *, storage=None)[source]¶
- Parameters:
group (Group)
storage (StorageOptions | None)
- Return type:
None
- add_graph(positions, edges, *, attributes=None, edge_attributes=None, object_attributes=None, object_ids=None, tree=False, layout=None, on_out_of_bounds='raise')[source]¶
Write a graph, or a skeleton when
tree=True.
- add_lines(endpoints, *, attributes=None, object_attributes=None, layout=None, on_out_of_bounds='raise')[source]¶
Write line segments, as an
(M, 2, D)array.write_linestakes nogroups; a line store’s objects are its lines and the writer has no grouping array. Write the groupings throughzarr_vectors.buildingif you need them.
- add_mesh(vertices, faces, *, attributes=None, object_attributes=None, object_ids=None, layout=None, on_out_of_bounds='raise')[source]¶
Write a triangulated surface.
- add_points(positions, *, attributes=None, object_ids=None, object_attributes=None, groups=None, layout=None, on_out_of_bounds='raise')[source]¶
Write a point cloud.
- Parameters:
- Return type:
- add_polylines(polylines, *, attributes=None, object_attributes=None, groups=None, layout=None, streamlines=False, on_out_of_bounds='raise')[source]¶
Write polylines, or streamlines when
streamlines=True.Each
attributesvalue is a list of one array per polyline.- Parameters:
- Return type:
- property axes: tuple[dict[str, str], ...]¶
name, type, and unit where declared.
- Type:
Axis descriptors
- property bounds: tuple[NDArray[Any], NDArray[Any]]¶
(min_corner, max_corner)in coordinate units.Downstream reads this today as
root.attrs.to_dict()["zarr_vectors"]["bounds"]in at least three repositories. That expression encodes the attribute layout, so it breaks whenever the layout moves.
- build_pyramid(*, factors, method='per_object', **kw)[source]¶
Build coarser levels.
methodselects the coarsener:"per_object"is core’s, and anythingcoarsen_methods()also lists comes from an installed strategy package. Pass that strategy’s own knobs asoptions={...}.
- commit(message='zarr-vectors write')[source]¶
Commit, for backends that have transactions.
Noneotherwise.
- editing(*, level=0, in_place=False, **kw)[source]¶
Open a batch of edits addressed by intent.
with ds.editing() as edit: edit.move_vertex(object=7, index=3, to=...)– no chunk coordinates, no fragment indices.Edits are copy-on-write by default: the edited object is reallocated under a new id and the original is left readable.
in_place=Trueasks for overwrite instead, but object-bearing geometry may reallocate regardless – always checkedit.renamed(), or the object you edited will appear unchanged.
- property format_version: tuple[int, ...]¶
On-disk format version, parsed and comparable.
Downstream currently hard-codes
REQUIRED_ZV_FORMAT = (0, 9)and reaches forconstants.FORMAT_VERSIONto check it, because the store never offered the number in a comparable form.
- kind_of(level=0)[source]¶
The geometry type a read at
levelshould be decoded as.levelis accepted and currently ignored: geometry type is a store-wide declaration, and a pyramid’s coarser levels hold the same kind as level 0. It stays in the signature because a composite store’s levels could differ, and a caller should not have to change their call when that lands.
- property metadata: Any¶
Namespaced application metadata stored in the root.
Replaces reaching for
root.attrsdirectly, which three downstream modules do today and which has no protection against two writers of different keys losing each other’s.
- resolution(*, scale)[source]¶
The level whose cell size is closest to
scale.What a viewer actually wants: not “level 2” but “roughly this many units per cell”, so the choice survives a change in how many levels the pyramid has.
- property store: Group¶
The underlying storage handle.
Deliberately named as an escape hatch and deliberately present: pretending the layer below does not exist would only mean consumers reach past the facade in ways nobody can find later. Reaching for this is a signal that something is missing here.
- exception zarr_vectors.api.dataset.FormatError[source]¶
Bases:
ZVErrorThe store’s on-disk format is not one this code can serve.
- async zarr_vectors.api.dataset.aopen(source, *, storage=None)[source]¶
Open without ever entering zarr’s blocking
sync()bridge.For Pyodide, where a synchronous zarr call needs WebAssembly stack switching and deadlocks the JS event loop under concurrency. Pair it with
Query.aread().- Parameters:
source (Any)
storage (StorageOptions | None)
- Return type:
- zarr_vectors.api.dataset.create(target, *, schema, storage=None)[source]¶
Create a new dataset from a
Schema.Raises if something already exists at
target— useopen_or_create()when either outcome is acceptable.- Parameters:
target (Any)
schema (Schema)
storage (StorageOptions | None)
- Return type:
- zarr_vectors.api.dataset.open(source, *, mode='r', storage=None)[source]¶
Open an existing dataset.
Accepts a path, a URL, an already-open store handle, or a pre-constructed
zarrStore — the last of which is what a browser host supplies, since a fetch-backed Store is the only way in there.The backend is resolved, never asked for: explicit
StorageOptions.backend, then$ZARR_VECTORS_BACKEND, then the URL scheme.- Parameters:
source (Any)
mode (Literal['r', 'r+'])
storage (StorageOptions | None)
- Return type:
- zarr_vectors.api.dataset.open_or_create(target, *, schema, storage=None, on_conflict='raise')[source]¶
Open
targetif it exists, otherwise create it — idempotently.When it exists,
schemais checked against what is on disk and a disagreement raisesSchemaConflict. That deliberately overturns the existing behaviour, in which_create_or_open_storesilently dropsboundsandchunk_shapefor an existing path: that silence is how a store ends up with a declared grid that contradicts its own chunk keys, after which a bbox read looks for coordinates that were never written and returns nothing, with no error raised anywhere.Pass
on_conflict="keep"to accept what is on disk instead.- Parameters:
target (Any)
schema (Schema)
storage (StorageOptions | None)
on_conflict (Literal['raise', 'keep'])
- Return type:
- zarr_vectors.api.dataset.require_format(dataset, spec)[source]¶
Raise unless
dataset’s on-disk format satisfiesspec.specis a comma-separated list of>=/>/<=/</==clauses, e.g.">=0.9,<0.11".This exists because there is no backward-compatible reader: a store written before 0.9.0 does not raise a clear error, it raises a
MetadataErrorfrom somewhere deep in the metadata parser. One consumer carries a hundred-and-eighteen-line module to turn that into a sentence.
Schema and layout¶
A Schema describes the data and is all a
new store needs. Layout sets the grid when
you need to fix it.
Declaring what the data is, and — separately — how it is stored.
Today a caller who wants a point cloud must also decide a chunk shape, a bin shape, a shard shape, a compressor and a backend, in the same call, with no defaults that work. Four of those five are storage decisions that depend on the store’s size and location, not on the data; the fifth is not a decision at all, since the backend is derivable from the URL.
So they are split. Schema says what the data is and carries no
storage term. Layout says how to store it, every field has a
working "auto", and it is the single place the four physical
parameters are computed. A caller who never touches Layout gets a
sensible store; a caller with an externally fixed grid sets one field.
The precedence rule for StorageOptions mirrors
zarr_vectors.core.backends.resolve_backend_name() — explicit
argument, then $ZARR_VECTORS_BACKEND, then scheme detection. Keeping
the environment variable as the second step is what lets backend=
disappear from every public signature without any capability being lost.
- class zarr_vectors.api.schema.AttributeSpec(dtype='float32', channels=1, categorical=False, unit=None, description=None)[source]¶
Bases:
objectOne attribute’s declared type.
channelsis the trailing width: 1 for a scalar per vertex, 3 for an RGB colour, and so on.Declaring one is load-bearing.
dtypeandchannelsare checked against the array a writer is actually handed, so a store cannot quietly disagree with what it says it holds;unitanddescriptionare written onto the attribute array itself, so the store can say what itsintensityis measured in; and the whole declaration is recorded on the root, soSchema.from_store()reads it back andopen_or_create()can tell you a store is missing something you declared.- Parameters:
- __init__(dtype='float32', channels=1, categorical=False, unit=None, description=None)¶
- array_metadata()[source]¶
The fields that belong on the attribute array itself.
dtypeandchannel_namesare the writer’s to stamp – it knows the real array – so this carries only what the declaration adds. Empty when nothing was declared beyond the type, which is why a caller can check it before paying for a write.
- class zarr_vectors.api.schema.Axis(name, unit=None, type='space')[source]¶
Bases:
objectOne spatial axis: what it is called and what it is measured in.
- __init__(name, unit=None, type='space')¶
- class zarr_vectors.api.schema.Layout(cells='auto', cell_size=None, subcells='auto', pack='auto', shard_cells='auto', compression='auto', target_object_bytes=16777216, octree=False)[source]¶
Bases:
objectHow the data is physically stored. Every field has a working
"auto".cellsis the data-shaped spelling — “cut the volume into about this many pieces per axis” — and is what most callers should use.cell_sizeis the escape hatch for a grid fixed from outside, such as a pipeline whose chunks must line up with an image volume’s.What the defaults actually do:
cells="auto"Derived from
Schema.expected— enough cells that each one holds roughly 64 MB, the figurezarr_vectors.api.grid.Grid.capacity()judges against. With no hint it is one cell per axis: a single chunk holding everything. That is the honest answer when nothing is known, not a good default — saycells=or fill inexpectedfor anything you intend to query spatially.subcells="auto"Four per axis, so a bbox read touches about 1/64th of a 3-D chunk.
pack="auto"On for object stores, off for local ones.
shard_cells="auto"Derived from
pack. Set it to take the decision directly — an explicit value wins overpack, andNoneforces one object per cell.Schema.from_store()fills it in from what a store declared, so re-resolving a layout against an existing store does not silently contradict it: “auto” would consultstore_kindand answer unsharded for every local store, including one deliberately built sharded.compression="auto"zstd, or$ZARR_VECTORS_COMPRESSIONwhen set. It used to resolve to no compression, which is not what the word means.octree=FalseTrue(or the codec’s configuration, e.g.{"target": 100_000}) marks the store octree: its shards are written with zarr-octree’szarr_octree_shardingcodec instead ofsharding_indexed. It shards the store (shard_cells="auto"then packs whatever the store kind), and needs the zarr-octree package.zarr_vectors.sharding.set_octree()converts an existing store either way.
- Parameters:
target_object_bytes (int)
- __init__(cells='auto', cell_size=None, subcells='auto', pack='auto', shard_cells='auto', compression='auto', target_object_bytes=16777216, octree=False)¶
- Parameters:
target_object_bytes (int)
- Return type:
None
- class zarr_vectors.api.schema.ResolvedLayout(chunk_shape, bin_shape, shard_shape, compressor, bounds, octree=None)[source]¶
Bases:
objectThe physical parameters, computed.
This is the only object in the package that carries all four of
chunk_shape/bin_shape/shard_shape/compressor, and it is internal: the public surface never names them.- Parameters:
- __init__(chunk_shape, bin_shape, shard_shape, compressor, bounds, octree=None)¶
- class zarr_vectors.api.schema.Schema(ndim=3, bounds=None, axes=None, kind='point_cloud', position_dtype='float32', vertex_attributes=<factory>, object_attributes=<factory>, link_attributes=<factory>, expected=None, layout=<factory>)[source]¶
Bases:
objectWhat the data is. No storage term appears here.
The three attribute maps are declarations, and they are recorded:
to_root_block()writes them onto the store andfrom_store()reads them back, so a schema round-trips andopen_or_create()can report a store that is missing one.(A
profilefield used to sit here, standing in for the three convention strings. Nothing read it, and the type writers fill those in from the geometry anyway, so it named a concept that did not exist. It was removed rather than left looking like a promise.)- Parameters:
ndim (int)
kind (str)
position_dtype (str)
vertex_attributes (Mapping[str, AttributeSpec])
object_attributes (Mapping[str, AttributeSpec])
link_attributes (Mapping[str, AttributeSpec])
expected (SizeHints | None)
layout (Layout)
- __init__(ndim=3, bounds=None, axes=None, kind='point_cloud', position_dtype='float32', vertex_attributes=<factory>, object_attributes=<factory>, link_attributes=<factory>, expected=None, layout=<factory>)¶
- Parameters:
ndim (int)
kind (str)
position_dtype (str)
vertex_attributes (Mapping[str, AttributeSpec])
object_attributes (Mapping[str, AttributeSpec])
link_attributes (Mapping[str, AttributeSpec])
expected (SizeHints | None)
layout (Layout)
- Return type:
None
- diff(other)[source]¶
Fields on which
selfandotherdisagree.Only the fields a store actually pins are compared: declaring an attribute the store does not yet have is a legitimate way to extend it, not a conflict.
- classmethod from_store(root_meta, level_meta=None)[source]¶
Reconstruct what a store on disk declares itself to be.
The inverse of using a Schema to create one, so
open_or_createcan compare intent against reality rather than silently ignoring the caller’s. Physical fields come back insideLayoutas explicit overrides — a store already has a grid, and re-deriving one would be a different grid.- Parameters:
root_meta (RootMetadata)
level_meta (LevelMetadata | None)
- Return type:
- link_attributes: Mapping[str, AttributeSpec]¶
- object_attributes: Mapping[str, AttributeSpec]¶
- spec_for(name, scope='vertex')[source]¶
The declaration for one attribute, or
Noneif undeclared.- Parameters:
- Return type:
AttributeSpec | None
- to_root_block()[source]¶
The declaration, in the shape the root attrs record it.
Scopes with nothing declared are omitted entirely, so a schema that declares no attributes writes no key.
- vertex_attributes: Mapping[str, AttributeSpec]¶
- exception zarr_vectors.api.schema.SchemaConflict[source]¶
Bases:
MetadataErrorAn existing store disagrees with the schema it was opened with.
Raised rather than ignored.
_create_or_open_storecurrently silently dropsbounds/chunk_shape/axeswhen the path already exists, which is howwrite_polylines(path, chunk_shape=X)can produce a store whose declared grid contradicts its own chunk keys — and then a later bbox read looks for coordinates that were never written and returns nothing, with no error anywhere.
- class zarr_vectors.api.schema.SizeHints(n_vertices=None, n_objects=None, vertices_per_object=None)[source]¶
Bases:
objectRoughly how much data is coming.
Only used to pick a layout. Wrong hints cost performance, never correctness, so a caller who does not know should leave them unset rather than guess.
- __init__(n_vertices=None, n_objects=None, vertices_per_object=None)¶
- class zarr_vectors.api.schema.StorageOptions(backend=None, options=<factory>, branch=None)[source]¶
Bases:
objectWhere the bytes live, and how to reach them.
Separate from
Schemabecause it is not a property of the data: the same dataset can be moved between a local disk and a bucket without its schema changing at all.- __init__(backend=None, options=<factory>, branch=None)¶
Selections and queries¶
A Selection describes a read (a bbox,
object ids, an attribute filter). A Query
is a lazy handle on one; nothing is read until you ask.
Asking for data by what it is, not by where it is stored.
The five readers already share a selection vocabulary — level,
bbox, object_ids, group_ids, attribute_filter — but they
expose it inconsistently (only read_points takes attribute_names;
only read_lines lacks chunks) and two of the terms are storage,
not data: chunks=[(3, 1, 2), ...] is a list of grid coordinates that
the caller has to know the grid to construct.
Selection is that vocabulary said once, with the storage terms
removed. Query is a lazy, chainable handle on one — nothing is
read until a terminal is called, and intersecting two selections is a
value operation, so a caller can build a query up in one place and run it
in another.
Laziness is not decoration. It is what lets this phase delegate to
the eager readers and a later phase run resolvers against the batching
engine, with no visible difference. If select() did I/O, that switch
would be a behaviour change and every caller would have to be revisited.
- class zarr_vectors.api.select.Query(level, selection)[source]¶
Bases:
objectA pending read. Nothing happens until a terminal is called.
Terminals are
read(),aread(),count()andobject_ids(). Everything else returns a newQuery.- async aread()[source]¶
Execute without ever blocking on zarr’s
sync()bridge.For hosts where a synchronous zarr call cannot work — Pyodide, where it needs WebAssembly stack switching and deadlocks the JS event loop under concurrency.
- Return type:
- cells()[source]¶
The grid cells this query touches — from metadata, reading nothing.
What a caller shards work across processes on: each worker takes a slice of these and reads only its own.
plan()already computes the answer (it is pure metadata arithmetic); this is the cell-shaped view of it, without the array paths and without a caller having to know that a plan’scellsare(array, key)pairs across several families.Deduplicated across families —
verticesandvertex_fragmentsname the same cell of the same grid — and returned as aCellSet, so it feeds straight back intoselect(cells=...). Refused on a level with octree chunks, ascells()is.- Return type:
- count()[source]¶
How many vertices this query would return.
An unnarrowed count comes from the level’s stamped vertex count without reading a chunk. Anything narrowed has to be read, because what survives a filter is a property of the data.
- Return type:
- iter_cells()[source]¶
Stream the result one cell at a time, each cell read on its own.
yields
(CellRef, ReadResult)pairs, one per cell thatcells()names, in sorted key order;each
ReadResultcovers exactly that cell, cut intopartsthe waySelection.cells_splitasks for — so the same object spanning two cells appears as one part in each, and summing part counts is not the same as reading the whole query;per-cell failures arrive in that result’s
errors, not as an exception, so one unreadable cell does not end the stream;sum(r.vertex_count for _, r in q.iter_cells()) == q.count(), except for abbox/nearquery on lines or polylines (the whole read keeps parts reaching outside the region’s cells);a
limitis shared across the cells.
- Return type:
- plan()[source]¶
The I/O this query would perform, without performing any of it.
Both a debugging tool and the decoupling test: an internal change that alters the shape of a read shows up here, in one comparable value, rather than as a performance mystery downstream.
- Return type:
- class zarr_vectors.api.select.Selection(level=None, bbox=None, near=None, objects=None, groups=None, where=None, cells=None, cells_split=True, attributes='all', limit=None)[source]¶
Bases:
objectWhat to read. A value: no store, no I/O, comparable and mergeable.
Every field narrows. Combining two selections intersects them, so
level.select(bbox=b).select(objects=ids)means “in that box and among those objects” — the reading a caller expects from chaining.- Parameters:
- __init__(level=None, bbox=None, near=None, objects=None, groups=None, where=None, cells=None, cells_split=True, attributes='all', limit=None)¶
- Parameters:
- Return type:
None
- cells: Any¶
Opaque cell references, from
level.grid.cells_in(bbox).The honest replacement for
chunks=[(3, 1, 2), ...]: a caller who genuinely needs to target storage regions gets the references from the grid rather than constructing coordinates they had to derive.See
cells_splitfor the one place the replacement is not exact.
- cells_pushed_down(*, supports)[source]¶
Whether
cellsreached the reader rather than the post-filter.
- cells_split: bool¶
Whether a partly-kept object is SPLIT at the cell boundary.
read_*(chunks=...)emits each surviving contiguous run of a polyline as its own polyline, so an object re-entering the region comes back as several parts. Filtering an already-assembledReadResultinstead keeps it as one part with the outside vertices dropped. Both are defensible; they are not the same answer, and exporters depend on the split one (a TRK streamline count legitimately exceeds the source object count).True(the default) preserves the reader’s behaviour by passingcellsdown aschunks=where the reader accepts it.Falseasks for the post-filtered reading.
- intersect(other)[source]¶
Narrow by
other.Two bboxes intersect geometrically; two id sets intersect as sets. A field set on only one side is simply adopted — there is nothing to reconcile.
- level: int | None¶
Which resolution level, or
Nonefor “not specified”.None, not0. Level 0 is a real level – the full-resolution one – so using it as the unset sentinel made asking for it indistinguishable from not asking, andds.level(1).select(...).select(level=0)silently stayed on 1.Level.select()fills this in, so a Selection reaching a reader always has a concrete level.
- property needs_post_filter: bool¶
Whether a term has to be applied after the read.
nearalways does — it degrades to its bounding box on the way down, and the corners of that box are outside the sphere.
- to_reader_kwargs(*, supports)[source]¶
Translate into the legacy reader’s keyword set.
supportsnames the kwargs that reader actually accepts — they differ per reader, which is one of the inconsistencies this class exists to hide. A term the reader cannot express is dropped here and applied afterwards in Python, so the answer is the same either way and only the amount of data read differs.
Read results¶
One result type for every geometry kind, with per-geometry views such as
result.polylines.
One result type for every geometry.
The five readers in zarr_vectors.types return five differently
shaped dicts. They use four names for the vertex array
(positions / vertices / endpoints / polylines), seven
distinct count keys, and only one of them carries attributes on every
path. A caller who wants to handle two geometry types therefore writes
two code paths for what is, structurally, the same answer: some vertices,
optionally cut into parts, optionally connected.
ReadResult is that answer said once. The per-geometry shapes
survive as derived properties, so a polyline user still writes
res.polylines and gets the list they had before — but a tool that
does not care which geometry it is given can read res.positions and
be correct for all of them.
Parts, not per-type containers. A “part” is one emitted run of
consecutive vertices: a polyline, a line segment, a mesh (whole), a point
cloud (whole). Storing them as slices into one contiguous positions
array rather than as a list of arrays means the common case — “give me
all the coordinates” — needs no concatenation, and the per-part view
costs a slice rather than a copy. It is also what makes the mapping from
each legacy reader total: every one of them can be expressed as
positions plus a cut, and every one can be read back out unchanged.
Errors are values. The lazy layer swallows per-chunk failures in
bare except Exception: continue blocks, so a corrupt chunk and an
absent one are indistinguishable and both look like “no data here”. A
read that partially failed reports which cells failed in errors
rather than quietly returning less than was asked for.
- class zarr_vectors.api.result.Attributes(data=None)[source]¶
Bases:
Mapping[str, npt.NDArray[Any]]Per-vertex attribute arrays, keyed by name.
A real
Mappingrather than a bare dict so that a later phase can make it lazy — reading an attribute only when it is asked for — without changing a single call site. Today every value is already materialised.- Parameters:
data (Mapping[str, npt.NDArray[Any]] | None)
- class zarr_vectors.api.result.ReadError(cell, array, error)[source]¶
Bases:
objectOne cell that could not be read, and why.
Carried rather than raised because a partial answer is usually more useful than none — but only if the caller can tell it apart from a complete one.
- class zarr_vectors.api.result.ReadResult(kind, positions, parts=(), part_objects=None, object_ids=None, edges=None, faces=None, attributes=<factory>, attributes_read=True, truncated=False, errors=())[source]¶
Bases:
objectWhat a read returned, independent of which geometry it was.
Construct via the
from_*adapters rather than directly; they are the total mapping from each legacy reader’s output, and keeping them in one place is what makes that mapping checkable.- Parameters:
- __init__(kind, positions, parts=(), part_objects=None, object_ids=None, edges=None, faces=None, attributes=<factory>, attributes_read=True, truncated=False, errors=())¶
- Parameters:
- Return type:
None
- attributes: Attributes¶
Per-vertex attributes. Empty is not the same as unavailable — see
attributes_read.
- attributes_read: bool¶
Whether attributes were even attempted.
Falsemeans the reader did not look, so an emptyattributessays nothing about the store. A caller that cannot tell those apart will conclude a store has none when it has plenty.Where they are available today, by geometry and query shape:
kind
whole
bbox
objects
limit
points
yes
yes
yes
yes
polyline
yes
yes
yes
yes
line
yes
yes
yes
yes
mesh
yes
no
n/a
yes
graph
yes
no
n/a
yes
meshandgraphlose them on a narrowed read because their readers return no attributes at all and the facade’s fallback gather is level-ordered, which cannot be aligned to a cut-down result.objects=isn/afor those two: the readers raiseNotImplementedErrorfor it rather than silently ignoring it. Closing the two gaps needs the resolver phase, which plans the attribute reads alongside everything else.
- property endpoints: NDArray[Any]¶
(M, 2, D)line endpoints — the shaperead_linesreturns.Raises when the parts are not uniformly two vertices long, since a “line” that is not a pair is a polyline and the caller has reached for the wrong view.
- classmethod from_graph(raw, *, kind)[source]¶
{positions, edges, node_count, edge_count}, plus a per-nodeobject_idson theobject_ids=path.- Parameters:
- Return type:
- classmethod from_lines(raw, *, kind)[source]¶
{endpoints, vertex_attributes, line_count}.endpointsis(M, 2, D). Flattening it to(2M, D)with one two-vertex part per line loses nothing (endpointsreverses it exactly) and gains the shared shape. The synthesisededgesmakes the connectivity explicit, which the tuple form left implicit in the axis layout.vertex_attributesholds two rows per line in the same order, so it lines up withpositionsas flattened here. A dict that is present but empty means the reader looked and the store had none; a dict that is absent means the read predatesread_linesreturning them, andattributes_readkeeps the two apart rather than reporting “none” for both.- Parameters:
- Return type:
- classmethod from_mesh(raw, *, kind)[source]¶
{vertices, faces, vertex_count, face_count}— notevertices, notpositions— plus a per-vertexobject_idson theobject_ids=path.- Parameters:
- Return type:
- classmethod from_points(raw, *, kind)[source]¶
{positions, vertex_attributes, vertex_count}, plusobject_idson the object-id path.Both of
read_points’ paths now run the same attribute gather, so both reportattributes_read. The object-id path used to returnvertex_attributes={}unconditionally — not because there were none, but because it never looked — which is why this adapter had to special-case it.- Parameters:
- Return type:
- classmethod from_polylines(raw, *, kind)[source]¶
{polylines, object_ids, polyline_count, vertex_count}.object_idshere is one id per polyline, so it becomespart_objects. Reading it as per-vertex would misalign it againstpositionsby the length of every polyline.Each element is a list of per-chunk segments, not a single array — even for a polyline that fits in one chunk, which comes back as a list of one. (The quickstart’s
result["polylines"][0].shapeis wrong; there is no.shapeon a list.) Concatenating the segments reconstructs the polyline exactly: measured across single- and multi-chunk stores, the segment lengths sum to the input length with no vertex duplicated at a boundary.- Parameters:
- Return type:
- kind: str¶
Geometry type, one of
zarr_vectors.constants’GEOM_*.
- part_objects: NDArray[Any] | None¶
(P,)source object id of each part, when the store tracks them.Distinct from
object_ids, and the distinction is load-bearing:read_polylinesreturns one id per polyline, whileread_points’ object path returns one per vertex. Collapsing them would silently misalign one of the two.
- parts: tuple[slice, ...]¶
One slice into
positionsper emitted part.A point cloud, mesh or graph is one part covering everything; a polyline store has one per polyline; a line store has one per segment. Empty only when there are no vertices.
- property polylines: list[NDArray[Any]]¶
Each part as its own
(N_k, D)array.The shape
read_polylinesreturns. Views, not copies.
- restrict(keep, *, truncated=False)[source]¶
This result with only the vertices
keepselects.Every index-bearing field is repaired, not merely sliced. Edges and faces are renumbered into the new positions array and any that reference a dropped vertex are removed — a filtered mesh whose faces still point at the old row numbers is silently corrupt, and silently corrupt geometry is the worst thing this layer could hand back.
Parts are re-cut from what survives, so a partly-kept polyline stays one part and simply gets shorter.
- Parameters:
- Return type:
- to_device(device)[source]¶
This result with its arrays on
device("cpu"or"cuda").One copy per array: positions, part objects, object ids, edges, faces and every attribute. Terminal: filter first, because
restrict()works on host arrays."cuda"needs the optional GPU extension (pip install "zarr-vectors[gpu]").- Parameters:
device (str)
- Return type:
Resolution levels¶
A Level is one resolution of a dataset,
and the handle for its objects, groups and grid.
One resolution level, addressed by what is in it.
A Level is where reads actually happen. It knows which legacy
reader serves this store’s geometry, which of that reader’s keyword
arguments exist, and how to repair the difference between what the
caller asked for and what the reader could express.
Nothing here mentions a chunk, a bin, a shard or a backend. Where a
selection term has no equivalent in the reader — near has none, and
attribute_names exists on exactly one of the five — the term is
applied afterwards in Python. That costs reading more than was needed;
it never costs a wrong answer, and it is temporary: once the facade
drives its own reads, the same public behaviour is served by a plan that
asks for less.
- class zarr_vectors.api.level.Level(dataset, index)[source]¶
Bases:
objectOne resolution level of a
Dataset.- attribute_names(kind='vertex')[source]¶
Names of the attributes of one family present at this level.
Downstream reaches into
group.zarr_group[...]and unionsarray_keys()withgroup_keys()in at least six places because there was no way to ask this. There is now.
- cells(bbox=None)[source]¶
The cells this level actually holds, optionally within a box.
The counterpart to
Grid.cells_in(), which enumerates the allocation: a grid is a pure value and cannot know what is in the store, so a sparse level – a specimen bounding box with data in part of it – answerscells_inwith a reference per allocated cell. Building a million of those takes about nine seconds before any read happens, and all but a thousand of them name nothing.This asks the level instead, so the answer is proportional to the data. It is the better argument to
select(cells=...)whenever the caller wants “what is here”, andGrid.cells_inremains the right one for “what could be here”.Refused on a level with octree chunks, whose chunks are leaves (see
zarr_vectors.octree_chunks).
- property grid: Any¶
This level’s cell grid, in physical units.
Exposed because two questions about it are genuinely a caller’s business — “will my data fit this allocation” and “which cells is this region” — and answering them by hand means re-deriving the allocator, which one consumer does and documents as fragile.
The grid is spatial. On a level chunked by an attribute the arrays carry a leading bin axis as well, so
grid.shapeis the spatial tail of their shape andgrid.cellscounts spatial cells, not keys. A cell from the grid selects that cell in every bin;cells()lists the keys the level actually holds, bin included, and one of those selects one bin’s cell.
- property metadata: Any¶
Namespaced application metadata stored beside this level.
A sanctioned home for what consumers currently put directly in the level’s
attrs, where it can collide with the format’s own keys and where two writers clobber each other.
- plan(selection)[source]¶
The I/O this selection implies, before any of it is performed.
Metadata arithmetic: the level’s attrs and its presence manifest are read so a narrowed plan can name the cells that actually hold data, and no chunk is fetched. Inside a
cached_nodes()block those reads are already paid for.
- property resolution: tuple[float, ...]¶
Physical size of one spatial-query cell — the finest region a bbox read can isolate without over-reading.
Assembled rather than read from one place, because it is not stored in one place: a level carries its own
bin_shapeonly once it has been coarsened, while level 0 leaves it implicit in the root’sbase_bin_shape. A caller should not have to know which of the two a given store happens to have.
- property scale: tuple[float, ...]¶
Physical size of one grid cell at this level.
The honest data-shaped reading of what the storage layer calls a chunk shape: it is a length in the same units as the coordinates, and it is what a caller needs to write a compatible store or to choose a level for a viewport.
- property store: Any¶
This LEVEL’s
Grouphandle.The same escape hatch
Dataset.storeoffers, at the granularity everyzarr_vectors.buildingfunction takes: those want a level group, so reaching them from an apiLevelotherwise meantget_resolution_level(level._dataset._group, level.index)— two internal reaches to express “read through the api, patch through building”.Deliberately the level group and not the root: the legacy readers take a root handle plus
level=, so astorethat returned the root would look interchangeable with this one and hand everybuildingwriter a handle it reads as a level — allocating the array families at the store root.
Objects¶
Objects by id, as level.objects. Indexing it reads only what you ask
for.
Objects, addressed by id rather than by where their pieces landed.
An object — a streamline, a skeleton, a mesh — is stored as fragments scattered across the chunks it passes through, plus a manifest naming them. Reading one therefore means decoding its manifest and gathering what it points at.
The existing entry point decodes every manifest in the store. On a whole-brain tractography store that is twenty-one million Python objects built to answer a question about a hundred, and it is the step that hangs. Downstream worked around it by importing a private block expander, a layout sentinel and a raw coordinate selection — three internals pinned purely to avoid an O(N) decode.
ObjectCatalog is the question they were trying to ask.
- class zarr_vectors.api.objects.ObjectCatalog(level)[source]¶
Bases:
objectThe objects at one level.
Indexing reads only what was asked for:
level.objects[7] # one object's geometry level.objects[[7, 9, 11]] # three, in one gather len(level.objects) # from metadata; reads nothing
- Parameters:
level (Level)
- property count: int¶
How many objects are actually here.
Reads the stamped
num_presentwhere available and decodes the manifests otherwise, so it is correct on stores written before that field existed and merely slower.
- ids(*, present=True)[source]¶
Object ids at this level.
- Parameters:
present (bool) – When True (the default), only ids that actually hold geometry. When False, every addressable slot.
- Return type:
NDArray[Any]
This used to return
arange(slot_count)unconditionally, which is wrong for exactly the stores this package builds: a sparsified level reports every dropped id as present, and reading one givesvertex_count == 0— indistinguishable from an empty region.
- manifests(ids=None)[source]¶
Where each object’s fragments live.
The physical answer, offered because a tool that builds its own gather plan genuinely needs it — and because the alternative was that such a tool imported three private names to get it.
Object groups¶
Named sets of object ids, as level.groups.
Object groups, addressed by name.
A grouping is stored as a row of object ids. Nothing on disk says what the row means, so every reader has to hard-code the integer — and a store cannot be understood without the writing application’s source next to it. One downstream module exists solely to paper over this, and its docstring is the clearest statement of the problem: “nothing on disk says that row 3 means ‘the network’. Every reader therefore had to hard-code the integer.”
Naming them is a small addition — a list of names on the groupings
array’s own attributes, parallel to the rows — and it makes the store
self-describing. Stores written before it are still readable: an
unnamed row answers to "group_3", so nothing has to be migrated to
be usable.
- class zarr_vectors.api.groups.GroupCatalog(level)[source]¶
Bases:
Mapping[str,ObjectGroup]The object groups at one level, keyed by name.
- Parameters:
level (Level)
- by_id(group_id)[source]¶
A group by row index, for stores that carry no names.
- Parameters:
group_id (int)
- Return type:
- class zarr_vectors.api.groups.ObjectGroup(level, group_id, name)[source]¶
Bases:
objectOne named set of objects.
- property id: int¶
The row index this group occupies. An implementation detail, exposed because a store written by other tools may only be addressable this way.
The chunk grid¶
Grid questions in physical units: will this fit, and which region is this. Most callers do not need it.
The chunk grid, exposed as geometry rather than as coordinates.
The grid is a storage concept, and most callers should never meet it. Two questions about it are nonetheless real:
“Will this fit?” A store allocates a fixed number of cells per axis
from its bounds and cell size, and a write whose coordinates fall outside
that allocation is rejected. One consumer predicts the allocation by
calling level_grid_layout and compute_grid_shape itself, with a
comment noting that the guard “stays in lockstep with the real array
shape” — which is to say, it does not, and cannot.
“Which region is this?” A caller with an externally fixed grid needs to name a region in grid terms.
Both are answered here, in physical units, with the grid coordinates
wrapped in an opaque CellRef that a caller receives but never
constructs. Grid.plan answers the first question before the store
exists, which is the only time the answer is useful.
- class zarr_vectors.api.grid.CellRef(coords)[source]¶
Bases:
objectOne cell of the grid.
Opaque on purpose: a caller gets these from
Grid.cells_in()orGrid.cell_of()and passes them back, but never builds one from integers. That is what keeps a change in how cells are addressed from being a downstream break.When the escape hatch is taken:
coordsandkeyare absolute chunk coordinates, identical to the keys on disk — which is what lets a reference be handed straight to the readers’chunks=term and to the engine’s cell requests.
- class zarr_vectors.api.grid.CellSet[source]¶
Bases:
frozensetA set of
CellRef, usable as a selection term.
- class zarr_vectors.api.grid.Grid(shape, cell_shape, origin=(), extent=())[source]¶
Bases:
objectA level’s cell grid, in physical units.
Spatial: every axis is a physical axis, and
cell_of(),cells_in()andholds()are spatial predicates. A level chunked by an attribute adds a leading bin axis to its keys that this grid does not model; aCellReffrom it selects its cell in every bin of such a level.- Parameters:
- __init__(shape, cell_shape, origin=(), extent=())¶
- property anchor: tuple[int, ...]¶
Absolute chunk coord of cell 0 —
floor(origin / cell_shape).The same value the store writes as an array’s
chunk_grid_originattribute. Derived rather than stored, so it cannot contradictorigin.
- capacity(*, n_vertices=None, ndim=3, bytes_per_coordinate=4, target_cell_bytes=67108864)[source]¶
Whether this grid is a sensible shape for the data planned.
Two ways a grid goes wrong: too few cells, so each one is an unwieldy object; or so many that the per-cell overhead dominates.
- Parameters:
- Return type:
- cell_of(point)[source]¶
Which cell a coordinate falls in.
Absolute, as stored:
floor(point / cell_shape). It used to subtractorigin, which made it bounds-relative whilecells_in()— and the chunk keys on disk, and thechunks=term a cell selection becomes — stayed absolute. The two agreed only for a store whose bounds began at zero; anywhere elseselect(cells=[cell_of(p)])looked in a cell that does not holdp, and usually does not exist.
- cells_in(bbox)[source]¶
Every cell a bounding box touches.
The replacement for
chunks=[(3, 1, 2), ...]: the caller states a region and receives opaque references, rather than stating grid coordinates they had to derive themselves.This is the allocation, not the occupancy: a grid is a value and holds no store handle, so it answers what the declared grid covers whether or not anything was written there. On a sparse store the two differ by orders of magnitude, and a reference per allocated cell is a cost paid before any read. Use
zarr_vectors.api.level.Level.cells()for the cells a level actually holds.
- extent: tuple[float, ...]¶
Physical span of the planned bounds per axis (empty if unknown), so
capacity()divides by covered rather than allocated cells.
- holds(ref)[source]¶
Whether
refis inside this grid’s allocation.In the same absolute frame
cell_of()andcells_in()speak, so a reference either of them produced is tested against the allocation it actually names.
- origin: tuple[float, ...]¶
Coordinate of the grid’s lower corner, in the data’s own units.
Informational. Cells are addressed absolutely —
cell_of()isfloor(point / cell_shape), the same mapassign_chunks()uses to decide where a vertex is written — so this is not a subtrahend.anchoris the cell this corner falls in.
- classmethod plan(bounds, *, cell_size=None, target_cells=None)[source]¶
The grid a store with these bounds would get — without one.
Callable before anything is written, which is the only moment the answer can change a decision. A consumer that discovers after the fact that its chunk ids exceed the allocation has already written a store it must throw away.
The shape comes from
grid_layout()— the function the allocator itself calls — rather than from a restatement of it. A restatement is what this used to be, and it was one plane short:ceil((hi - lo) / size)counts cell-widths across the extent, but bounds are inclusive, so a store spansfloor(hi/size) - floor(lo/size) + 1cells.That makes
target_cells=nproducen + 1cells per axis when the upper bound lands exactly on a cell boundary: a vertex athihas to be storable, and it lands in cellfloor(hi/size). The extra plane is what the store really allocates; reportingnis the failure this method exists to prevent.
Editing¶
Edits addressed by object and vertex rather than by storage location. Read the copy-on-write warning below before assuming an edit failed.
Editing, addressed by what a thing is rather than where it landed.
The editing layer underneath is physical by design, and rightly so: a
surgical edit has to name the exact fragment row it is changing, and
VertexRef(level, chunk, fragment, local) says that precisely. Its
own module docstring calls these “physical addresses”.
The problem is that a caller rarely has one. What a caller has is “the third vertex of object 7”, or “whatever is at this coordinate”, and turning that into four grid numbers means knowing the chunking, the fragment layout, and where the object’s pieces were scattered.
The resolution already exists — VertexRef.from_object and
VertexRef.from_position — but only for vertices, and only if you know
to look. EditPlan makes it the normal way in, and leaves the
physical constructors available for the cases that genuinely need them.
Nothing here reimplements the edit semantics. Manifest propagation, object-id allocation and the flush are the existing session’s, unchanged.
Edits are copy-on-write by default, and this surprises people.
atomic=True — the underlying default — appends a new fragment and
rewrites the referring manifests under a new object id, leaving the
original object exactly as it was. So after moving a vertex of object 7,
object 7 still reads back unchanged and the edited geometry lives under
some other id. That is deliberate: a concurrent reader never sees a
half-written object. But a caller who does not know it concludes the
edit silently failed.
EditPlan.renamed() reports the mapping, so the surprise is at
least visible. in_place=True asks for overwrite-in-place instead,
but it is a request: object-bearing geometry has its manifest rewritten
either way, and measurement shows a polyline edit reallocates under both
settings. So do not branch on the flag — read renamed() and act on
what actually happened.
- class zarr_vectors.api.edit.EditPlan(dataset, *, level=0, in_place=False, **session_kw)[source]¶
Bases:
objectA batch of edits, applied on exit.
Used as a context manager:
with dataset.editing() as edit: edit.move_vertex(object=7, index=3, to=[10.0, 20.0, 30.0]) edit.set_attribute("intensity", object=7, index=3, value=0.5)
Every method takes intent — an object id and an index within it, or a coordinate — and resolves it to a physical reference through the existing
from_object/from_positionconstructors.- move_vertex(*, to, object=None, index=0, at=None)[source]¶
Move a vertex to a new position.
Under the default copy-on-write mode the object this vertex belongs to is reallocated;
new_id_of()says where it went.
- new_id_of(object_id)[source]¶
Where
object_id’s edited geometry ended up.Returns the id unchanged when nothing moved, so a caller can apply it unconditionally.
- remove_object(object)[source]¶
Delete an object and everything belonging to it.
- Parameters:
object (int)
- Return type:
None
- renamed()[source]¶
Old object id to new, for edits that copied rather than overwrote.
Empty under
atomic=False. Non-empty means the objects you edited now live under different ids, and reading the old ones returns the pre-edit geometry.
- property report: Any¶
What the last flush did.
EditSession.reportis a property, not a method – calling it raises'EditReport' object is not callable, which is an unhelpful way to learn that.
- property session: Any¶
The underlying edit session.
An escape hatch, and a deliberate one: the physical layer has operations this wrapper does not cover, and a caller reaching for it is a signal about what to add here rather than something to prevent.
Coarsening methods¶
The method names build_pyramid(method=...) accepts in this
installation, including any a strategy package registered.
- zarr_vectors.api.coarsen_methods()[source]¶
Every coarsening method
build_pyramid(method=...)will accept.Core’s
"per_object"plus whatever a strategy package registered on import. Offered because the alternative was callingbuild_pyramidwith a name and finding out from the exception — the registry knew the answer and nothing asked it.