Filtering

zarr_vectors_tools.filtering: TrackVis-style filter trees, the brute-force oracle that defines their answers, and an indexed engine for interactive use. See Streamlines, skeletons and surfaces for usage.

TrackVis-style streamline filtering: a filter-tree format and its reference engines.

A filter is a tree of leaves – passes through a region, a column comparison, group membership – combined with AND, OR and NOT (predicates, which also defines the JSON form engines exchange). Two engines evaluate it over a Tractogram held in memory:

  • oracle tests every segment, brute force. It is the ground truth.

  • IndexedEngine files segments under a grid, tests only the segments near a region, and caches each leaf, so an operator change is only boolean algebra. Tested to agree with the oracle exactly.

load_tractogram() reads a store’s level 0 into a Tractogram in the RAS millimetres select_streamlines() uses, and synthetic makes whole-brain-sized test sets.

The subpackage imports only numpy (the store reader is imported when load_tractogram() is called), and its modules import one another relatively, so it can be copied into a Pyodide worker as it is.

Filter trees and regions

Filter trees for streamlines: regions, leaves, operators, and their JSON.

A TrackVis-style filter is a tree. Each leaf asks one question of every streamline and answers yes or no:

  • Passes – does the streamline meet a region (Sphere, Box, Slab, Disk or Mask)? mode says which part of it counts: "path" (any segment), "endpoints" (either end) or "both_endpoints".

  • Column – does a per-streamline value pass a comparison?

  • InGroup – is the streamline a member of any of these groups?

  • All – yes, always (the default group before any filter).

And, Or and Not combine them, and so do the operators &, |, ~ and - (and-not) on any node.

The JSON form (to_json() / from_json()) is the contract between engines: the brute-force oracle here, the indexed numpy engine, and the browser engines that are tested against them all read the same document. Coordinates are world millimetres, the same space select_streamlines() takes regions in.

What each region means, exactly

Every set is closed, so a segment that just touches a region meets it.

  • sphere: some point of the segment is within radius of center.

  • box: the segment meets the axis-aligned box min..``max``.

  • slab: the segment’s coordinate on axis takes some value in min..``max`` (a box unbounded on the other two axes; TrackVis’s slice filter).

  • disk: the segment crosses the disk’s plane at a point within radius of center, and the angle between the segment and the disk’s normal axis lies within angle (degrees, 0..90; direction does not matter). A segment lying in the plane does not cross it.

  • mask: a point sampled along the segment falls in a nonzero voxel. The points are the segment’s two vertices and ceil(length / spacing) - 1 evenly spaced between them; a point is in the voxel its coordinates round to. spacing defaults to half the smallest voxel edge. This is the scheme select_streamlines() uses, so the two agree point for point.

A streamline with one vertex is that point; one with none meets nothing. The endpoint modes test the first and last vertex as points, so they do not apply to a disk, which has no interior.

Column comparisons

cmp is one of <  <=  >  >=  ==  !=, between (value is [lo, hi], inclusive), in (value is a list) or absent. An absent value – a row the store marks absent, or a NaN – passes no comparison, != included, and passes only absent.

class zarr_vectors_tools.filtering.predicates.All[source]

Bases: Node

Every streamline.

__init__()
Return type:

None

to_json()[source]
Return type:

dict[str, Any]

class zarr_vectors_tools.filtering.predicates.And(*children)[source]

Bases: _Combine

Streamlines every operand accepts.

Parameters:

children (Node)

op = 'and'
class zarr_vectors_tools.filtering.predicates.Box(min, max)[source]

Bases: Region

An axis-aligned box from corner min to corner max.

Parameters:
__init__(min, max)
Parameters:
Return type:

None

kind: str = 'box'
max: tuple[float, float, float]
min: tuple[float, float, float]
to_json()[source]
Return type:

dict[str, Any]

class zarr_vectors_tools.filtering.predicates.Column(name, cmp, value=None, channel=None)[source]

Bases: Node

Streamlines whose name column passes cmp value.

channel picks one channel of a multi-channel column.

Parameters:
__init__(name, cmp, value=None, channel=None)
Parameters:
Return type:

None

channel: int | None = None
cmp: str
name: str
to_json()[source]
Return type:

dict[str, Any]

value: Any = None
class zarr_vectors_tools.filtering.predicates.Disk(center, normal, radius, angle=(0.0, 90.0))[source]

Bases: Region

A flat disk, crossed by segments whose angle to normal is in angle.

normal is normalised on construction. angle is (lo, hi) in degrees between the segment and the normal axis: (0, 90) accepts any crossing, (0, 30) only segments within 30 degrees of the normal.

Parameters:
__init__(center, normal, radius, angle=(0.0, 90.0))
Parameters:
Return type:

None

angle: tuple[float, float] = (0.0, 90.0)
center: tuple[float, float, float]
kind: str = 'disk'
normal: tuple[float, float, float]
radius: float
to_json()[source]
Return type:

dict[str, Any]

zarr_vectors_tools.filtering.predicates.FORMAT = 'zvf-predicate'

Name and version written into every JSON document. A reader refuses a version it does not know.

class zarr_vectors_tools.filtering.predicates.InGroup(ids)[source]

Bases: Node

Streamlines that belong to any of the groups ids.

Parameters:

ids (tuple[int, ...])

__init__(ids)
Parameters:

ids (tuple[int, ...])

Return type:

None

ids: tuple[int, ...]
to_json()[source]
Return type:

dict[str, Any]

class zarr_vectors_tools.filtering.predicates.Mask(voxels, affine, spacing=None)[source]

Bases: Region

A voxel region: nonzero voxels placed in the world by affine.

affine maps voxel indices to world millimetres (a NIfTI affine). Two masks are equal when their voxels, affine and spacing are.

Parameters:
__init__(voxels, affine, spacing=None)
Parameters:
Return type:

None

affine: ndarray[tuple[Any, ...], dtype[float64]]
contains(points)[source]

Whether each world point falls in a nonzero voxel.

Parameters:

points (ndarray[tuple[Any, ...], dtype[_ScalarT]])

Return type:

ndarray[tuple[Any, …], dtype[bool]]

kind: str = 'mask'
property sample_spacing: float

Distance between points tested along a segment.

spacing: float | None = None
to_json()[source]
Return type:

dict[str, Any]

voxels: ndarray[tuple[Any, ...], dtype[bool]]
world_bounds()[source]

World box around every nonzero voxel (each voxel +/- half a voxel).

Return type:

tuple[ndarray[tuple[Any, …], dtype[float64]], ndarray[tuple[Any, …], dtype[float64]]]

class zarr_vectors_tools.filtering.predicates.Node[source]

Bases: object

Base class of every filter tree node.

key()[source]

A stable digest of the node, for caching its result.

Return type:

str

leaves()[source]

The leaves under this node, left to right.

Return type:

list[Node]

to_json()[source]
Return type:

dict[str, Any]

class zarr_vectors_tools.filtering.predicates.Not(child)[source]

Bases: Node

Streamlines the operand rejects.

Parameters:

child (Node)

__init__(child)[source]
Parameters:

child (Node)

Return type:

None

leaves()[source]

The leaves under this node, left to right.

Return type:

list[Node]

to_json()[source]
Return type:

dict[str, Any]

class zarr_vectors_tools.filtering.predicates.Or(*children)[source]

Bases: _Combine

Streamlines any operand accepts.

Parameters:

children (Node)

op = 'or'
class zarr_vectors_tools.filtering.predicates.Passes(region, mode='path')[source]

Bases: Node

Streamlines that meet region, by path or by their ends.

Parameters:
__init__(region, mode='path')
Parameters:
Return type:

None

mode: str = 'path'
region: Region
to_json()[source]
Return type:

dict[str, Any]

class zarr_vectors_tools.filtering.predicates.Region[source]

Bases: object

Base class of the shapes a Passes leaf tests against.

kind: str = ''
to_json()[source]
Return type:

dict[str, Any]

class zarr_vectors_tools.filtering.predicates.Slab(axis, min, max)[source]

Bases: Region

Everything whose coordinate on axis (0, 1 or 2) is in min..``max``.

Parameters:
__init__(axis, min, max)
Parameters:
Return type:

None

axis: int
kind: str = 'slab'
max: float
min: float
to_json()[source]
Return type:

dict[str, Any]

class zarr_vectors_tools.filtering.predicates.Sphere(center, radius)[source]

Bases: Region

A ball: center and radius in world millimetres.

Parameters:
__init__(center, radius)
Parameters:
Return type:

None

center: tuple[float, float, float]
kind: str = 'sphere'
radius: float
to_json()[source]
Return type:

dict[str, Any]

zarr_vectors_tools.filtering.predicates.from_json(doc)[source]

The tree a to_json() document (or its text) describes.

Raises:

ValueError – If the document is not a filter tree, is a version this reader does not know, or names an unknown node or region.

Parameters:

doc (dict[str, Any] | str | bytes)

Return type:

Node

zarr_vectors_tools.filtering.predicates.to_json(tree)[source]

The JSON document for tree: {"format", "version", "tree"}.

Parameters:

tree (Node)

Return type:

dict[str, Any]

Tractograms

A streamline set held whole in memory, the input to both engines.

Tractogram is deliberately plain: one (V, 3) float64 vertex array, offsets cutting it into N streamlines, a dict of per-streamline columns, and the group memberships. Row k is object id k, as in the store. Nothing here imports the store layer, so the class (and the engines on top of it) also runs where zarr does not, such as a Pyodide worker handed arrays from JavaScript.

load_tractogram() fills one from a store’s level 0.

class zarr_vectors_tools.filtering.tractogram.Tractogram(vertices, offsets, columns=<factory>, present=<factory>, groups=<factory>)[source]

Bases: object

Streamlines as flat arrays.

Parameters:
vertices

(V, 3) world positions, streamline after streamline. Kept float32 when given float32 (as stores hold them); every test widens to float64 first, so the answer is the same.

Type:

numpy.ndarray[tuple[Any, …], numpy.dtype[numpy.floating]]

offsets

(N + 1,) int64; streamline k is vertices[offsets[k]:offsets[k + 1]]. A streamline may be empty (an object id with no geometry).

Type:

numpy.ndarray[tuple[Any, …], numpy.dtype[numpy.int64]]

columns

Per-streamline values, (N,) or (N, C). length (path length) and n_vertices are computed from the geometry when not supplied.

Type:

dict[str, numpy.ndarray[tuple[Any, …], numpy.dtype[Any]]]

present

For a column with absent rows, a (N,) bool mask that is False where the value is absent. NaNs count as absent too.

Type:

dict[str, numpy.ndarray[tuple[Any, …], numpy.dtype[numpy.bool]]]

groups

Member rows of each group, indexed by group id.

Type:

list[numpy.ndarray[tuple[Any, …], numpy.dtype[numpy.int64]]]

__init__(vertices, offsets, columns=<factory>, present=<factory>, groups=<factory>)
Parameters:
Return type:

None

column(name, channel=None)[source]

(values, present) for a column (one channel of a multi-channel one).

Raises:

KeyError – If there is no such column.

Parameters:
  • name (str)

  • channel (int | None)

Return type:

tuple[ndarray[tuple[Any, …], dtype[Any]], ndarray[tuple[Any, …], dtype[bool]]]

edges()[source]

(start, end, owner): vertex indices and row of every segment.

A one-vertex streamline contributes one zero-length segment, so it is tested as the point it is. The arrays are int32 while the counts fit, which halves them on a whole-brain tractogram.

Return type:

tuple[ndarray[tuple[Any, …], dtype[int64]], ndarray[tuple[Any, …], dtype[int64]], ndarray[tuple[Any, …], dtype[int64]]]

endpoints()[source]

(first, last, has_vertices): each row’s end vertices.

Rows without vertices get NaN ends and has_vertices False.

Return type:

tuple[ndarray[tuple[Any, …], dtype[float64]], ndarray[tuple[Any, …], dtype[float64]], ndarray[tuple[Any, …], dtype[bool]]]

classmethod from_polylines(polylines, *, columns=None, present=None, groups=None)[source]

Build one from a list of (n_k, 3) arrays (row k is the k-th).

Parameters:
Return type:

Tractogram

group_mask(ids)[source]

Rows in any of the groups ids (a group the set lacks has no rows).

Parameters:

ids (Sequence[int])

Return type:

ndarray[tuple[Any, …], dtype[bool]]

property n_objects: int
polyline(row)[source]
Parameters:

row (int)

Return type:

ndarray[tuple[Any, …], dtype[float64]]

zarr_vectors_tools.filtering.tractogram.load_tractogram(store_path, *, level=0, columns=None)[source]

Read a streamline store’s level into a Tractogram, in RAS mm.

Positions are mapped to RAS millimetres exactly as select_streamlines() maps them (a TRK store kept in voxel millimetres goes through its header’s affine), so regions mean the same thing to both.

Filtering is defined at level 0. A coarse level drops streamlines and moves vertices, so level is for showing how much that changes the answer, not for answering.

Parameters:
  • store_path (str | Path) – A streamline (or polyline) store.

  • level (int) – Resolution level to read.

  • columns (Sequence[str] | None) – Object attributes to load; default all of them.

Raises:
  • ValueError – If the store does not hold streamlines.

  • NotImplementedError – If the level is part of an additive pyramid, whose complete content spans several levels.

Return type:

Tractogram

Oracle

The brute-force reference: every predicate, tested on every segment.

This is the ground truth the faster engines are measured against – the indexed numpy engine here, and the browser engines built later. It keeps nothing between calls and prunes nothing: a region leaf runs the exact segment test of geometry over all of the tractogram’s segments, a batch at a time. Slow on purpose, and simple enough to check by reading.

zarr_vectors_tools.filtering.oracle.column_mask(leaf, tractogram)[source]

Rows whose column value passes the comparison (absent values never do).

Parameters:
Return type:

ndarray[tuple[Any, …], dtype[bool]]

zarr_vectors_tools.filtering.oracle.evaluate(tree, tractogram)[source]

Which streamlines the filter accepts: an (N,) bool array by row.

Parameters:
Return type:

ndarray[tuple[Any, …], dtype[bool]]

zarr_vectors_tools.filtering.oracle.histogram(accepted, tractogram, column, bins, channel=None)[source]

Counts of accepted rows’ values in bins (edges, as numpy.histogram).

Parameters:
Return type:

ndarray[tuple[Any, …], dtype[int64]]

zarr_vectors_tools.filtering.oracle.passes(leaf, tractogram)[source]

Rows that meet the leaf’s region, by path or by their ends.

Parameters:
Return type:

ndarray[tuple[Any, …], dtype[bool]]

zarr_vectors_tools.filtering.oracle.summarize(accepted, tractogram, columns=('length',))[source]

Count of accepted rows and, per column, statistics over them.

Each column reports n (accepted rows with a value), mean, std (population, ddof 0), min and max; NaN where n is 0. Multi-channel columns are summarised per channel as name[c].

Parameters:
Return type:

dict[str, Any]

Indexed engine

An interactive filter engine in numpy: a spatial index plus cached leaves.

This is the design the platform plan proposes for the browser (zarr_vectors_filtering_wasm_plan.md, part B), built from numpy alone so that it runs unchanged under Pyodide and can be timed there (gate G1 of the build guide). It answers exactly what the oracle answers – the tests hold it to that – but does far less work per question:

  • A region leaf tests only the segments filed under the grid cells the region’s bounding box touches. Each segment is filed under every cell its own bounding box overlaps, so a segment that crosses a cell face, or skips over a whole cell, is still found from any cell it passes through. (A rare long segment spanning many cells goes on a short list tested every time instead.)

  • A segment that lies in one cell, where that cell lies wholly inside the region, meets the region without being tested; and a segment is not tested once its streamline has been accepted.

  • Endpoint modes test only the two ends of each streamline.

  • Every leaf’s answer is cached by the leaf’s content, so changing an operator, or toggling one leaf, re-runs only the boolean algebra.

Unlike the browser design, it holds level 0 whole in memory: the question it answers is how fast numpy computes the filters, not how they are fetched.

class zarr_vectors_tools.filtering.indexed.IndexedEngine(tractogram, *, cell_size=None, segments_per_cell=64, cache_size=256, long_cells=64)[source]

Bases: object

Filter one tractogram, interactively.

Parameters:
  • tractogram (Tractogram) – The streamlines; held, not copied.

  • cell_size (float | None) – Edge of the index’s cubic cells, in millimetres. The default aims for about segments_per_cell segments per cell and never goes below twice the median segment length.

  • segments_per_cell (int) – Target occupancy for the default cell size.

  • cache_size (int) – Leaf answers kept (least recently used are dropped).

  • long_cells (int) – A segment whose bounding box spans more cells than this is not filed under each of them but kept on a short list that every region query tests.

__init__(tractogram, *, cell_size=None, segments_per_cell=64, cache_size=256, long_cells=64)[source]
Parameters:
Return type:

None

clear()[source]

Forget every cached leaf (after the tractogram changes).

Return type:

None

evaluate(tree)[source]

Which streamlines the filter accepts: an (N,) bool array by row.

Parameters:

tree (Node)

Return type:

ndarray[tuple[Any, …], dtype[bool]]

property index_bytes: int

Bytes the index adds on top of the tractogram.

last_query: dict[str, int]

cells visited, cells wholly inside the region, segments accepted untested, candidates, tested.

Type:

Counts from the last region query

leaf(node)[source]

A leaf’s answer, from the cache when the same leaf was asked before.

Parameters:

node (Node)

Return type:

ndarray[tuple[Any, …], dtype[bool]]

static publish(groups)[source]

One byte per row for the viewer: 0 hidden, else 1 + the first group showing it.

Groups are in draw order; at most 255 fit a byte.

Parameters:

groups (Sequence[ndarray[tuple[Any, ...], dtype[bool]]])

Return type:

ndarray[tuple[Any, …], dtype[uint8]]

Segment tests

Exact segment and point tests against each region type.

Every function here is vectorised over a batch of segments a[i] -> b[i] (each (E, 3) float64) or points, and implements the meaning predicates defines for the region. The oracle and the indexed engine both call these, so they differ only in which segments they hand over: all of them, or the ones a spatial index says can matter.

zarr_vectors_tools.filtering.geometry.contains(points, region)[source]

Whether each point lies in region (for the endpoint modes).

Parameters:
Return type:

ndarray[tuple[Any, …], dtype[bool]]

zarr_vectors_tools.filtering.geometry.region_bounds(region)[source]

World box that every segment meeting region must reach into.

Unbounded axes (a slab’s other two) are infinite. An empty mask gives an empty box (min above max).

Parameters:

region (Region)

Return type:

tuple[ndarray[tuple[Any, …], dtype[float64]], ndarray[tuple[Any, …], dtype[float64]]]

zarr_vectors_tools.filtering.geometry.segment_hits(a, b, region)[source]

Whether each segment a[i] -> b[i] meets region.

Parameters:
Return type:

ndarray[tuple[Any, …], dtype[bool]]

Synthetic tractograms

Synthetic tractograms for tests and benchmarks.

whole_brain_like() makes smooth, randomly curving streamlines with a whole-brain’s spread of lengths, filling an ellipsoid of brain size. It is not anatomy – there are no bundles to speak of – but it has what filtering cost depends on: the number of streamlines, the vertex spacing, how long they run and how densely they pack space. Generation is vectorised and seeded, and uses numpy alone, so the same call builds the same set under CPython and under Pyodide.

zarr_vectors_tools.filtering.synthetic.whole_brain_like(n, *, seed=0, step=1.0, mean_length=60.0, length_range=(20.0, 200.0), semi_axes=(70.0, 85.0, 60.0), curvature=0.08, n_groups=8, absent_fraction=0.01)[source]

n streamlines in float32, with columns and groups to filter on.

Every vertex lies inside the ellipsoid semi_axes: a streamline that reaches its wall is reflected back in.

Parameters:
  • n (int) – Number of streamlines.

  • seed (int) – Seed for numpy’s PCG64 generator.

  • step (float) – Distance between consecutive vertices, in millimetres.

  • mean_length (float) – Mean streamline length before clipping to length_range (lengths are log-normal).

  • length_range (tuple[float, float]) – Shortest and longest streamline.

  • semi_axes (tuple[float, float, float]) – The ellipsoid the streamlines fill, centred on the origin.

  • curvature (float) – How quickly the direction wanders, per step.

  • n_groups (int) – Groups to assign rows to, round-robin by start octant and row; 0 for none.

  • absent_fraction (float) – Share of rows whose fa_mean is absent (NaN).

Return type:

Tractogram

Columns:

length and n_vertices (computed), fa_mean (float32 in 0.15..0.75, some absent) and label (int32, the group).