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:
oracletests every segment, brute force. It is the ground truth.IndexedEnginefiles 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,DiskorMask)?modesays 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 withinradiusofcenter.box: the segment meets the axis-aligned boxmin..``max``.slab: the segment’s coordinate onaxistakes some value inmin..``max`` (a box unbounded on the other two axes; TrackVis’s slice filter).disk: the segment crosses the disk’s plane at a point withinradiusofcenter, and the angle between the segment and the disk’s normal axis lies withinangle(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 andceil(length / spacing) - 1evenly spaced between them; a point is in the voxel its coordinates round to.spacingdefaults to half the smallest voxel edge. This is the schemeselect_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:
NodeEvery streamline.
- __init__()¶
- Return type:
None
- class zarr_vectors_tools.filtering.predicates.And(*children)[source]¶
Bases:
_CombineStreamlines every operand accepts.
- Parameters:
children (Node)
- op = 'and'¶
- class zarr_vectors_tools.filtering.predicates.Box(min, max)[source]¶
Bases:
RegionAn axis-aligned box from corner
minto cornermax.- __init__(min, max)¶
- class zarr_vectors_tools.filtering.predicates.Column(name, cmp, value=None, channel=None)[source]¶
Bases:
NodeStreamlines whose
namecolumn passescmp value.channelpicks one channel of a multi-channel column.- __init__(name, cmp, value=None, channel=None)¶
- class zarr_vectors_tools.filtering.predicates.Disk(center, normal, radius, angle=(0.0, 90.0))[source]¶
Bases:
RegionA flat disk, crossed by segments whose angle to
normalis inangle.normalis normalised on construction.angleis(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))¶
- 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:
NodeStreamlines that belong to any of the groups
ids.
- class zarr_vectors_tools.filtering.predicates.Mask(voxels, affine, spacing=None)[source]¶
Bases:
RegionA voxel region: nonzero
voxelsplaced in the world byaffine.affinemaps 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)¶
- class zarr_vectors_tools.filtering.predicates.Node[source]¶
Bases:
objectBase class of every filter tree node.
- class zarr_vectors_tools.filtering.predicates.Not(child)[source]¶
Bases:
NodeStreamlines the operand rejects.
- Parameters:
child (Node)
- class zarr_vectors_tools.filtering.predicates.Or(*children)[source]¶
Bases:
_CombineStreamlines any operand accepts.
- Parameters:
children (Node)
- op = 'or'¶
- class zarr_vectors_tools.filtering.predicates.Passes(region, mode='path')[source]¶
Bases:
NodeStreamlines that meet
region, by path or by their ends.
- class zarr_vectors_tools.filtering.predicates.Region[source]¶
Bases:
objectBase class of the shapes a
Passesleaf tests against.
- class zarr_vectors_tools.filtering.predicates.Slab(axis, min, max)[source]¶
Bases:
RegionEverything whose coordinate on
axis(0, 1 or 2) is inmin..``max``.
- class zarr_vectors_tools.filtering.predicates.Sphere(center, radius)[source]¶
Bases:
RegionA ball:
centerandradiusin world millimetres.- __init__(center, radius)¶
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:
objectStreamlines 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; streamlinekisvertices[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) andn_verticesare 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).
- 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.
- endpoints()[source]¶
(first, last, has_vertices): each row’s end vertices.Rows without vertices get NaN ends and
has_verticesFalse.
- classmethod from_polylines(polylines, *, columns=None, present=None, groups=None)[source]¶
Build one from a list of
(n_k, 3)arrays (rowkis thek-th).- Parameters:
polylines (Sequence[_Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | complex | bytes | str | _NestedSequence[complex | bytes | str]])
columns (Mapping[str, _Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | complex | bytes | str | _NestedSequence[complex | bytes | str]] | None)
present (Mapping[str, _Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | complex | bytes | str | _NestedSequence[complex | bytes | str]] | None)
groups (Sequence[Sequence[int]] | Mapping[int, Sequence[int]] | None)
- Return type:
- 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
levelis for showing how much that changes the answer, not for answering.- Parameters:
- 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:
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).
- zarr_vectors_tools.filtering.oracle.evaluate(tree, tractogram)[source]¶
Which streamlines the filter accepts: an
(N,)bool array by row.
- 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:
- zarr_vectors_tools.filtering.oracle.passes(leaf, tractogram)[source]¶
Rows that meet the leaf’s region, by path or by their ends.
- 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),minandmax; NaN wherenis 0. Multi-channel columns are summarised per channel asname[c].
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:
objectFilter 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_cellsegments 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:
tractogram (Tractogram)
cell_size (float | None)
segments_per_cell (int)
cache_size (int)
long_cells (int)
- Return type:
None
- last_query: dict[str, int]¶
cells visited, cells wholly inside the region, segments accepted untested, candidates, tested.
- Type:
Counts from the last region query
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).
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]¶
nstreamlines 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_meanis absent (NaN).
- Return type:
- Columns:
lengthandn_vertices(computed),fa_mean(float32 in 0.15..0.75, some absent) andlabel(int32, the group).