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

A zarr-vectors store, addressed by what is in it.

Build one with open(), create() or open_or_create() rather than by calling the constructor.

Parameters:
__init__(group, *, storage=None)[source]
Parameters:
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.

Parameters:
  • positions (ArrayLike)

  • edges (ArrayLike)

  • attributes (Mapping[str, ArrayLike] | None)

  • edge_attributes (Mapping[str, ArrayLike] | None)

  • object_attributes (Mapping[str, ArrayLike] | None)

  • object_ids (ArrayLike | None)

  • tree (bool)

  • layout (Layout | None)

  • on_out_of_bounds (Literal['raise', 'ignore', 'expand'])

Return type:

dict[str, Any]

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_lines takes no groups; a line store’s objects are its lines and the writer has no grouping array. Write the groupings through zarr_vectors.building if you need them.

Parameters:
  • endpoints (ArrayLike)

  • attributes (Mapping[str, ArrayLike] | None)

  • object_attributes (Mapping[str, ArrayLike] | None)

  • layout (Layout | None)

  • on_out_of_bounds (Literal['raise', 'ignore', 'expand'])

Return type:

dict[str, Any]

add_mesh(vertices, faces, *, attributes=None, object_attributes=None, object_ids=None, layout=None, on_out_of_bounds='raise')[source]

Write a triangulated surface.

Parameters:
  • vertices (ArrayLike)

  • faces (ArrayLike)

  • attributes (Mapping[str, ArrayLike] | None)

  • object_attributes (Mapping[str, ArrayLike] | None)

  • object_ids (ArrayLike | None)

  • layout (Layout | None)

  • on_out_of_bounds (Literal['raise', 'ignore', 'expand'])

Return type:

dict[str, Any]

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:
  • positions (ArrayLike)

  • attributes (Mapping[str, ArrayLike] | None)

  • object_ids (ArrayLike | None)

  • object_attributes (Mapping[str, ArrayLike] | None)

  • groups (Mapping[int, Sequence[int]] | None)

  • layout (Layout | None)

  • on_out_of_bounds (Literal['raise', 'ignore', 'expand'])

Return type:

dict[str, Any]

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 attributes value is a list of one array per polyline.

Parameters:
Return type:

dict[str, Any]

async aread(**kw)[source]
Parameters:

kw (Any)

Return type:

ReadResult

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.

method selects the coarsener: "per_object" is core’s, and anything coarsen_methods() also lists comes from an installed strategy package. Pass that strategy’s own knobs as options={...}.

Parameters:
Return type:

dict[str, Any]

property capabilities: frozenset[str]

Optional format features this store declares.

commit(message='zarr-vectors write')[source]

Commit, for backends that have transactions. None otherwise.

Parameters:

message (str)

Return type:

str | None

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=True asks for overwrite instead, but object-bearing geometry may reallocate regardless – always check edit.renamed(), or the object you edited will appear unchanged.

Parameters:
Return type:

Any

property format_version: tuple[int, ...]

On-disk format version, parsed and comparable.

Downstream currently hard-codes REQUIRED_ZV_FORMAT = (0, 9) and reaches for constants.FORMAT_VERSION to check it, because the store never offered the number in a comparable form.

property groups: Any

Object groups at level 0, keyed by name.

property headers: Any

Opaque per-format header blocks.

kind_of(level=0)[source]

The geometry type a read at level should be decoded as.

level is 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.

Parameters:

level (int)

Return type:

str

property kinds: tuple[str, ...]

Geometry types present, e.g. ("streamline",).

level(index=0)[source]
Parameters:

index (int)

Return type:

Level

property levels: tuple[int, ...]
property metadata: Any

Namespaced application metadata stored in the root.

Replaces reaching for root.attrs directly, which three downstream modules do today and which has no protection against two writers of different keys losing each other’s.

property ndim: int
read(**kw)[source]
Parameters:

kw (Any)

Return type:

ReadResult

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.

Parameters:

scale (float)

Return type:

Level

select(**kw)[source]
Parameters:

kw (Any)

Return type:

Query

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.

supports(capability)[source]
Parameters:

capability (str)

Return type:

bool

property url: str

Where this dataset lives.

A string for every backend. Group.path raises for anything that is not a local store, which is why nothing here uses it.

validate(*, level=3)[source]
Parameters:

level (int)

Return type:

Any

exception zarr_vectors.api.dataset.FormatError[source]

Bases: ZVError

The 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:
Return type:

Dataset

zarr_vectors.api.dataset.create(target, *, schema, storage=None)[source]

Create a new dataset from a Schema.

Raises if something already exists at target — use open_or_create() when either outcome is acceptable.

Parameters:
Return type:

Dataset

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 zarr Store — 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:
Return type:

Dataset

zarr_vectors.api.dataset.open_or_create(target, *, schema, storage=None, on_conflict='raise')[source]

Open target if it exists, otherwise create it — idempotently.

When it exists, schema is checked against what is on disk and a disagreement raises SchemaConflict. That deliberately overturns the existing behaviour, in which _create_or_open_store silently drops bounds and chunk_shape for 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:
Return type:

Dataset

zarr_vectors.api.dataset.require_format(dataset, spec)[source]

Raise unless dataset’s on-disk format satisfies spec.

spec is 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 MetadataError from somewhere deep in the metadata parser. One consumer carries a hundred-and-eighteen-line module to turn that into a sentence.

Parameters:
Return type:

None

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

One attribute’s declared type.

channels is the trailing width: 1 for a scalar per vertex, 3 for an RGB colour, and so on.

Declaring one is load-bearing. dtype and channels are checked against the array a writer is actually handed, so a store cannot quietly disagree with what it says it holds; unit and description are written onto the attribute array itself, so the store can say what its intensity is measured in; and the whole declaration is recorded on the root, so Schema.from_store() reads it back and open_or_create() can tell you a store is missing something you declared.

Parameters:
  • dtype (str)

  • channels (int)

  • categorical (bool)

  • unit (str | None)

  • description (str | None)

__init__(dtype='float32', channels=1, categorical=False, unit=None, description=None)
Parameters:
  • dtype (str)

  • channels (int)

  • categorical (bool)

  • unit (str | None)

  • description (str | None)

Return type:

None

array_metadata()[source]

The fields that belong on the attribute array itself.

dtype and channel_names are 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.

Return type:

dict[str, Any]

categorical: bool
channels: int
description: str | None
dtype: str
classmethod from_dict(d)[source]
Parameters:

d (Mapping[str, Any])

Return type:

AttributeSpec

to_dict()[source]

JSON-ready form. Defaults are omitted, so the common declaration costs one key.

Return type:

dict[str, Any]

unit: str | None
class zarr_vectors.api.schema.Axis(name, unit=None, type='space')[source]

Bases: object

One spatial axis: what it is called and what it is measured in.

Parameters:
__init__(name, unit=None, type='space')
Parameters:
Return type:

None

name: str
to_ngff()[source]
Return type:

dict[str, str]

type: str
unit: str | None
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: object

How the data is physically stored. Every field has a working "auto".

cells is the data-shaped spelling — “cut the volume into about this many pieces per axis” — and is what most callers should use. cell_size is 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 figure zarr_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 — say cells= or fill in expected for 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 over pack, and None forces 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 consult store_kind and answer unsharded for every local store, including one deliberately built sharded.

compression="auto"

zstd, or $ZARR_VECTORS_COMPRESSION when set. It used to resolve to no compression, which is not what the word means.

octree=False

True (or the codec’s configuration, e.g. {"target": 100_000}) marks the store octree: its shards are written with zarr-octree’s zarr_octree_sharding codec instead of sharding_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:
__init__(cells='auto', cell_size=None, subcells='auto', pack='auto', shard_cells='auto', compression='auto', target_object_bytes=16777216, octree=False)
Parameters:
Return type:

None

cell_size: Sequence[float] | None
cells: int | Sequence[int] | Literal['auto']
compression: str | None | Literal['auto']
octree: bool | Mapping[str, Any]
pack: bool | Literal['auto']
resolve(schema, *, store_kind='local')[source]

Turn this into the four physical parameters.

store_kind decides packing: one object per cell is cheap on a local filesystem and expensive on an object store, so pack defaults on for the latter and off for the former.

Parameters:
Return type:

ResolvedLayout

shard_cells: int | Sequence[int] | None | Literal['auto']
subcells: int | Literal['auto']
target_object_bytes: int
class zarr_vectors.api.schema.ResolvedLayout(chunk_shape, bin_shape, shard_shape, compressor, bounds, octree=None)[source]

Bases: object

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

None

bin_shape: tuple[float, ...]
bounds: tuple[list[float], list[float]]
chunk_shape: tuple[float, ...]
compressor: Any
octree: dict[str, Any] | None
shard_shape: int | tuple[int, ...] | 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: object

What 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 and from_store() reads them back, so a schema round-trips and open_or_create() can report a store that is missing one.

(A profile field 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:
__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:
Return type:

None

axes: tuple[Axis, ...] | None
bounds: tuple[Sequence[float], Sequence[float]] | None
diff(other)[source]

Fields on which self and other disagree.

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.

Parameters:

other (Schema)

Return type:

list[str]

expected: SizeHints | None
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_create can compare intent against reality rather than silently ignoring the caller’s. Physical fields come back inside Layout as explicit overrides — a store already has a grid, and re-deriving one would be a different grid.

Parameters:
Return type:

Schema

kind: str
layout: Layout
ndim: int
object_attributes: Mapping[str, AttributeSpec]
position_dtype: str
spec_for(name, scope='vertex')[source]

The declaration for one attribute, or None if 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.

Return type:

dict[str, dict[str, Any]]

vertex_attributes: Mapping[str, AttributeSpec]
with_bounds(lo, hi)[source]
Parameters:
Return type:

Schema

exception zarr_vectors.api.schema.SchemaConflict[source]

Bases: MetadataError

An existing store disagrees with the schema it was opened with.

Raised rather than ignored. _create_or_open_store currently silently drops bounds / chunk_shape / axes when the path already exists, which is how write_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: object

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

Parameters:
  • n_vertices (int | None)

  • n_objects (int | None)

  • vertices_per_object (float | None)

__init__(n_vertices=None, n_objects=None, vertices_per_object=None)
Parameters:
  • n_vertices (int | None)

  • n_objects (int | None)

  • vertices_per_object (float | None)

Return type:

None

n_objects: int | None
n_vertices: int | None
vertices_per_object: float | None
class zarr_vectors.api.schema.StorageOptions(backend=None, options=<factory>, branch=None)[source]

Bases: object

Where the bytes live, and how to reach them.

Separate from Schema because 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.

Parameters:
__init__(backend=None, options=<factory>, branch=None)
Parameters:
Return type:

None

backend: str | None
branch: str | None

The icechunk branch to open (default "main"); any other backend raises.

options: Mapping[str, Any]
resolve_backend(url)[source]

Explicit, then $ZARR_VECTORS_BACKEND, then scheme detection.

Returns None when nothing is forced, which is the signal to let zarr_vectors.core.store.open_store() auto-detect.

Parameters:

url (str)

Return type:

str | None

resolve_options(url)[source]

options plus branch for opening url, or None.

Parameters:

url (str)

Return type:

dict[str, Any] | 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: object

A pending read. Nothing happens until a terminal is called.

Terminals are read(), aread(), count() and object_ids(). Everything else returns a new Query.

Parameters:
__init__(level, selection)[source]
Parameters:
Return type:

None

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:

ReadResult

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’s cells are (array, key) pairs across several families.

Deduplicated across families — vertices and vertex_fragments name the same cell of the same grid — and returned as a CellSet, so it feeds straight back into select(cells=...). Refused on a level with octree chunks, as cells() is.

Return type:

Any

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:

int

explain()[source]

A human-readable account of what this query will do.

Return type:

str

iter_cells()[source]

Stream the result one cell at a time, each cell read on its own.

  • yields (CellRef, ReadResult) pairs, one per cell that cells() names, in sorted key order;

  • each ReadResult covers exactly that cell, cut into parts the way Selection.cells_split asks 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 a bbox/near query on lines or polylines (the whole read keeps parts reaching outside the region’s cells);

  • a limit is shared across the cells.

Return type:

Any

limit(n)[source]
Parameters:

n (int)

Return type:

Query

object_ids()[source]

The distinct object ids this query touches.

Return type:

NDArray[Any]

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:

Any

read()[source]

Execute and return the whole answer.

Return type:

ReadResult

select(**kw)[source]

Narrow further. Returns a new query; this one is unchanged.

Parameters:

kw (Any)

Return type:

Query

property selection: Selection

What this query is asking for. Inspectable, comparable.

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

What 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

attributes: Sequence[str] | str
bbox: tuple[Sequence[float], Sequence[float]] | 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_split for the one place the replacement is not exact.

cells_pushed_down(*, supports)[source]

Whether cells reached the reader rather than the post-filter.

Parameters:

supports (Sequence[str])

Return type:

bool

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-assembled ReadResult instead 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 passing cells down as chunks= where the reader accepts it. False asks for the post-filtered reading.

groups: Sequence[int] | None
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.

Parameters:

other (Selection)

Return type:

Selection

level: int | None

Which resolution level, or None for “not specified”.

None, not 0. 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, and ds.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.

limit: int | None
near: tuple[Sequence[float], float] | None
property needs_post_filter: bool

Whether a term has to be applied after the read.

near always does — it degrades to its bounding box on the way down, and the corners of that box are outside the sphere.

objects: Sequence[int] | None
to_reader_kwargs(*, supports)[source]

Translate into the legacy reader’s keyword set.

supports names 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.

Parameters:

supports (Sequence[str])

Return type:

dict[str, Any]

where: Mapping[str, Any] | None

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 Mapping rather 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)

__init__(data=None)[source]
Parameters:

data (Mapping[str, NDArray[Any]] | None)

Return type:

None

names()[source]
Return type:

tuple[str, …]

class zarr_vectors.api.result.ReadError(cell, array, error)[source]

Bases: object

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

Parameters:
__init__(cell, array, error)
Parameters:
Return type:

None

array: str

Which array the failure was in, relative to the level.

cell: str

Chunk key, in the usual dotted form.

error: str

The exception’s message.

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

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

False means the reader did not look, so an empty attributes says 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

mesh and graph lose 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= is n/a for those two: the readers raise NotImplementedError for it rather than silently ignoring it. Closing the two gaps needs the resolver phase, which plans the attribute reads alongside everything else.

property complete: bool
edges: NDArray[Any] | None

(M, 2) vertex-index pairs, for graph-like geometry.

property endpoints: NDArray[Any]

(M, 2, D) line endpoints — the shape read_lines returns.

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.

errors: tuple[ReadError, ...]

Cells that failed. Empty means the answer is complete.

faces: NDArray[Any] | None

(F, L) vertex-index tuples, for mesh geometry.

classmethod from_graph(raw, *, kind)[source]

{positions, edges, node_count, edge_count}, plus a per-node object_ids on the object_ids= path.

Parameters:
Return type:

ReadResult

classmethod from_lines(raw, *, kind)[source]

{endpoints, vertex_attributes, line_count}.

endpoints is (M, 2, D). Flattening it to (2M, D) with one two-vertex part per line loses nothing (endpoints reverses it exactly) and gains the shared shape. The synthesised edges makes the connectivity explicit, which the tuple form left implicit in the axis layout.

vertex_attributes holds two rows per line in the same order, so it lines up with positions as 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 predates read_lines returning them, and attributes_read keeps the two apart rather than reporting “none” for both.

Parameters:
Return type:

ReadResult

classmethod from_mesh(raw, *, kind)[source]

{vertices, faces, vertex_count, face_count} — note vertices, not positions — plus a per-vertex object_ids on the object_ids= path.

Parameters:
Return type:

ReadResult

classmethod from_points(raw, *, kind)[source]

{positions, vertex_attributes, vertex_count}, plus object_ids on the object-id path.

Both of read_points’ paths now run the same attribute gather, so both report attributes_read. The object-id path used to return vertex_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:

ReadResult

classmethod from_polylines(raw, *, kind)[source]

{polylines, object_ids, polyline_count, vertex_count}.

object_ids here is one id per polyline, so it becomes part_objects. Reading it as per-vertex would misalign it against positions by 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].shape is wrong; there is no .shape on 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:

ReadResult

kind: str

Geometry type, one of zarr_vectors.constants’ GEOM_*.

property ndim: int
object_ids: NDArray[Any] | None

(N,) per-vertex object id, when the reader supplied one.

property part_count: int
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_polylines returns one id per polyline, while read_points’ object path returns one per vertex. Collapsing them would silently misalign one of the two.

parts: tuple[slice, ...]

One slice into positions per 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_polylines returns. Views, not copies.

positions: NDArray[Any]

(N, D) vertex coordinates. Always this name, for every kind.

restrict(keep, *, truncated=False)[source]

This result with only the vertices keep selects.

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:

ReadResult

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:

ReadResult

truncated: bool

A limit= cut the result short.

property vertex_count: int

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

One resolution level of a Dataset.

Parameters:
__init__(dataset, index)[source]
Parameters:
Return type:

None

async aread(**kw)[source]

Shorthand for select(**kw).aread().

Parameters:

kw (Any)

Return type:

ReadResult

attribute_names(kind='vertex')[source]

Names of the attributes of one family present at this level.

Downstream reaches into group.zarr_group[...] and unions array_keys() with group_keys() in at least six places because there was no way to ask this. There is now.

Parameters:

kind (str) – "vertex", "fragment", "object", "group" or "link".

Return type:

tuple[str, …]

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 – answers cells_in with 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”, and Grid.cells_in remains the right one for “what could be here”.

Refused on a level with octree chunks, whose chunks are leaves (see zarr_vectors.octree_chunks).

Parameters:

bbox (tuple[Sequence[float], Sequence[float]] | None)

Return type:

Any

property dataset: Dataset
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.shape is the spatial tail of their shape and grid.cells counts 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 groups: Any

The object groups at this level, keyed by name.

property index: int
property kind: str
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.

property objects: Any

The objects at this level, addressed by id.

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.

Parameters:

selection (Selection)

Return type:

Any

read(**kw)[source]

Shorthand for select(**kw).read().

Parameters:

kw (Any)

Return type:

ReadResult

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_shape only once it has been coarsened, while level 0 leaves it implicit in the root’s base_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.

select(**kw)[source]

Build a query against this level. Nothing is read yet.

Parameters:

kw (Any)

Return type:

Query

property store: Any

This LEVEL’s Group handle.

The same escape hatch Dataset.store offers, at the granularity every zarr_vectors.building function takes: those want a level group, so reaching them from an api Level otherwise meant get_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 a store that returned the root would look interchangeable with this one and hand every building writer a handle it reads as a level — allocating the array families at the store root.

property vertex_count: int

Vertices at this level, from metadata — no data is read.

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

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

__init__(level)[source]
Parameters:

level (Level)

Return type:

None

property count: int

How many objects are actually here.

Reads the stamped num_present where 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 gives vertex_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.

Parameters:

ids (Sequence[int] | None)

Return type:

dict[int, Any]

present_mask()[source]

Per-slot boolean: does this id hold any geometry?

Decodes the manifests — there is no cheaper exact answer per id. Use count when only the total is needed.

Return type:

NDArray[Any]

property slots: int

How many ids this level addresses, present or not.

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)

__init__(level)[source]
Parameters:

level (Level)

Return type:

None

by_id(group_id)[source]

A group by row index, for stores that carry no names.

Parameters:

group_id (int)

Return type:

ObjectGroup

name_rows(names)[source]

Give the existing rows names, in row order.

Purely additive: the rows and their members are untouched, and a reader that does not know about names sees exactly what it saw before.

Parameters:

names (Sequence[str])

Return type:

None

names()[source]
Return type:

tuple[str, …]

class zarr_vectors.api.groups.ObjectGroup(level, group_id, name)[source]

Bases: object

One named set of objects.

Parameters:
__init__(level, group_id, name)[source]
Parameters:
Return type:

None

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.

property members: NDArray[Any]

The object ids in this group.

property name: str
read(**kw)[source]

Read this group’s geometry.

Parameters:

kw (Any)

Return type:

ReadResult

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

One cell of the grid.

Opaque on purpose: a caller gets these from Grid.cells_in() or Grid.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: coords and key are 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.

Parameters:

coords (tuple[int, ...])

__init__(coords)
Parameters:

coords (tuple[int, ...])

Return type:

None

coords: tuple[int, ...]
property key: str

The on-disk chunk key. An escape hatch, not the interface.

class zarr_vectors.api.grid.CellSet[source]

Bases: frozenset

A set of CellRef, usable as a selection term.

keys()[source]
Return type:

tuple[str, …]

class zarr_vectors.api.grid.Grid(shape, cell_shape, origin=(), extent=())[source]

Bases: object

A level’s cell grid, in physical units.

Spatial: every axis is a physical axis, and cell_of(), cells_in() and holds() are spatial predicates. A level chunked by an attribute adds a leading bin axis to its keys that this grid does not model; a CellRef from it selects its cell in every bin of such a level.

Parameters:
__init__(shape, cell_shape, origin=(), extent=())
Parameters:
Return type:

None

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_origin attribute. Derived rather than stored, so it cannot contradict origin.

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:
  • n_vertices (int | None)

  • ndim (int)

  • bytes_per_coordinate (int)

  • target_cell_bytes (int)

Return type:

GridCapacity

cell_of(point)[source]

Which cell a coordinate falls in.

Absolute, as stored: floor(point / cell_shape). It used to subtract origin, which made it bounds-relative while cells_in() — and the chunk keys on disk, and the chunks= term a cell selection becomes — stayed absolute. The two agreed only for a store whose bounds began at zero; anywhere else select(cells=[cell_of(p)]) looked in a cell that does not hold p, and usually does not exist.

Parameters:

point (Sequence[float])

Return type:

CellRef

cell_shape: tuple[float, ...]

Physical size of one cell, in coordinate units.

property cells: int
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.

Parameters:

bbox (tuple[Sequence[float], Sequence[float]])

Return type:

CellSet

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 ref is inside this grid’s allocation.

In the same absolute frame cell_of() and cells_in() speak, so a reference either of them produced is tested against the allocation it actually names.

Parameters:

ref (CellRef)

Return type:

bool

origin: tuple[float, ...]

Coordinate of the grid’s lower corner, in the data’s own units.

Informational. Cells are addressed absolutely — cell_of() is floor(point / cell_shape), the same map assign_chunks() uses to decide where a vertex is written — so this is not a subtrahend. anchor is 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 spans floor(hi/size) - floor(lo/size) + 1 cells.

That makes target_cells=n produce n + 1 cells per axis when the upper bound lands exactly on a cell boundary: a vertex at hi has to be storable, and it lands in cell floor(hi/size). The extra plane is what the store really allocates; reporting n is the failure this method exists to prevent.

Parameters:
Return type:

Grid

shape: tuple[int, ...]

Cells per axis.

class zarr_vectors.api.grid.GridCapacity(cells, shape, est_bytes_per_cell, fits, reason=None)[source]

Bases: object

Whether a grid can hold what is planned for it.

Parameters:
__init__(cells, shape, est_bytes_per_cell, fits, reason=None)
Parameters:
Return type:

None

cells: int

Total cells the allocation provides.

est_bytes_per_cell: float

Expected payload per cell, from the size hints given.

fits: bool
reason: str | None
shape: tuple[int, ...]

Cells per axis.

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

A 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_position constructors.

Parameters:
__init__(dataset, *, level=0, in_place=False, **session_kw)[source]
Parameters:
Return type:

None

flush()[source]

Apply everything queued so far, without closing the plan.

Return type:

Any

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.

Parameters:
Return type:

None

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.

Parameters:

object_id (int)

Return type:

int

remove_object(object)[source]

Delete an object and everything belonging to it.

Parameters:

object (int)

Return type:

None

remove_vertex(*, object=None, index=0, at=None)[source]

Delete a vertex.

Parameters:
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.

Return type:

dict[int, int]

property report: Any

What the last flush did.

EditSession.report is 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.

set_attribute(name, value, *, object=None, index=0, at=None)[source]

Set a per-vertex attribute.

Parameters:
Return type:

None

set_object_attribute(name, object, value)[source]

Set a per-object attribute.

Parameters:
  • name (str)

  • object (int)

  • value (ArrayLike)

Return type:

None

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 calling build_pyramid with a name and finding out from the exception — the registry knew the answer and nothing asked it.

Return type:

tuple[str, …]