Skip to content

ordito.neighbors

Point-set acceleration structures (BVH/HashGrid) and raw neighbor queries.

The accelerator is a keyword, not a function name. There are two questions here -- "everything within r" and "the k nearest" -- and each is one function: query_ball (with query_ball_count and query_ball_with_offsets for the count alone and the flat CSR form) and query_nearest. Which broad phase runs is a QueryBackend keyword -- "hashgrid" or "bvh" -- or is inferred from a prebuilt structure passed as accelerator. Both backends are exact and return the same answer; the choice is a cost one, and query_nearest's docstring carries guidance on which to pick. The kernel side is one warp-uniform kernel branching on an ACCEL_* selector.

The BVH-only queries keep the structure in their names, because naming it is informative rather than redundant there: these index arbitrary bounds rather than points, which a hash grid cannot, and they are broad phase only -- every bound the query region reaches is returned, with no narrow-phase filter on the primitive's own geometry. query_bvh_ball is the ball and query_bvh_box the per-query box; both return the same flat (indices, offsets) pair, so neither carries a _with_offsets suffix -- unlike query_ball_with_offsets, which needs one to separate it from query_ball's dense form. Prefer the ball whenever the predicate is a ball: it is not merely tighter, its traversal is substantially cheaper per candidate than the box one (see query_bvh_ball).

Also home to geodesic_ball, the surface-aware counterpart to the spatial ball queries here: it returns the same CSR (indices, offsets) shape but walks the mesh edge graph, so it excludes vertices that are close in space yet across a fold of the surface.

nearest_neighbor_distance is the one derived quantity rather than a raw query: the per-point distance to the closest other point, which is what a cloud's scale is normally estimated from.

Classes:

Name Description
GeodesicBallWalk

Every vertex's geodesic ball, walked a chunk of sources at a time into reused rows.

EdgePathBallWalk

Every vertex's shortest-edge-path ball, walked a chunk of sources at a time into reused rows.

Functions:

Name Description
bvh_from_points

Build a bounding-volume hierarchy over points for radius queries.

hashgrid_from_points

Build a 3D hash grid over points for radius queries.

bvh_from_bounds

Build a bounding-volume hierarchy over axis-aligned bounds.

query_bvh_ball

Low-level BVH ball query: primitive indices in one flat buffer plus offsets.

query_bvh_box

Primitives overlapping one axis-aligned box per query, in the same CSR packing.

query_ball

Find all data points within distance r of each query center (per-query arrays).

query_ball_count

Count neighbors of each query within Euclidean distance r.

query_ball_sum

Sum a per-neighbor term over each query's ball of radius r, with the neighbor count.

query_ball_with_offsets

Low-level ball query: neighbors in one concatenated pair plus per-query offsets.

knn_initial_radius

Radius at which a k-nearest search is expected to succeed on the first try.

query_nearest

For each query center, find the k nearest data points.

query_weighted_nearest

Nearest site under the weighted distance |p - q| - w(p).

nearest_neighbor_distance

Distance from each point to the closest other point of the same cloud.

closest_pair

Find the two closest points of a cloud, and the distance between them.

mutual_nearest

Pairs of points of two clouds that are each other's nearest neighbour, and their distances.

geodesic_ball

Per-vertex geodesic-ball neighborhoods, and the reference neighbor that frames each one.

QueryBackend module-attribute

QueryBackend = Literal['hashgrid', 'bvh']

GeodesicBallWalk

GeodesicBallWalk(
    vertices: array[vec3],
    faces: array[int32],
    radius: float,
    min_count: int = 6,
)

Every vertex's geodesic ball, walked a chunk of sources at a time into reused rows.

The streaming form of geodesic_ball, for a consumer that reads each ball once (a per-vertex fit): chunks walks chunk sources at a time and yields (start, m) once sources start .. start + m hold their balls in rows[t, : counts[start + t]]: the walk's queue in visit order, which is geodesic_ball's packed row entry for entry. The next chunk reuses the rows, so a consumer launches on a chunk before resuming the iterator, and never holds more than one chunk of neighbours, where the packed list is up to max_neighbors entries a vertex: on a scan of millions of vertices at a radius of a few percent of its diagonal that list is past both the device's memory and int32 offsets.

Parameters:

Name Type Description Default
vertices array[vec3]

(n_vertices,) vertex positions.

required
faces array[int32]

(3 * n_faces,) flat triangle index buffer; its edges are the graph the walk follows.

required
radius float

Geodesic-ball radius in world units.

required
min_count int

Minimum neighbors per vertex; the nearest out-of-ball vertices backfill any shortfall.

6

Attributes:

Name Type Description
rows Array2dInt32

(chunk, max_neighbors) the current chunk's balls, row t for source start + t.

counts array[int32]

(n_vertices,) each source's ball size, written as its chunk is walked.

reference array[int32]

(n_vertices,) each vertex's reference neighbour (the smallest adjacent vertex), as geodesic_ball returns it.

chunk int

Sources a chunk holds at most.

Raises:

Type Description
RuntimeError

If vertices and faces are not all on one device.

Warns:

Type Description
UserWarning

Once, after the first full walk, if any ball exceeded max_neighbors entries; its surplus neighbours were dropped.

Notes

The adjacency rows are sorted, so a ball's visit order, and with it any fit accumulated along the row, does not depend on the face order's permutation of each vertex's neighbours. Per-source scratch lives in pools sized for one chunk, not in per-thread local arrays.

See Also

geodesic_ball EdgePathBallWalk

Examples:

The ball sizes of an icosahedron at a radius just past its edge length, one chunk at a time:

import ordito as od

vertices, faces = od.creation.icosahedron()
walk = od.neighbors.GeodesicBallWalk(vertices, faces, radius=1.1)
for start, m in walk.chunks():
    rows = walk.rows.numpy()[:m]
    print(start, m, sorted(rows[0, :6].tolist()))  # 0 12 [0, 1, 5, 7, 10, 11]
print(walk.counts.numpy()[:4].tolist())  # [6, 6, 6, 6]

Build the sorted adjacency and the chunk's pools; no ball is walked yet.

Methods:

Name Description
chunks

Walk the sources a chunk at a time, yielding (start, m) with each chunk's rows.

Source code in ordito/neighbors.py
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
def __init__(
    self,
    vertices: wp.array[wp.vec3],
    faces: wp.array[wp.int32],
    radius: float,
    min_count: int = 6,
) -> None:
    """Build the sorted adjacency and the chunk's pools; no ball is walked yet."""
    require_same_device(vertices=vertices, faces=faces)
    self._setup(vertices, faces, radius, min_count, None)

reference instance-attribute

reference: array[int32]

counts instance-attribute

counts: array[int32]

rows instance-attribute

rows: Array2dInt32

chunk instance-attribute

chunk: int

chunks

chunks() -> Iterator[tuple[int, int]]

Walk the sources a chunk at a time, yielding (start, m) with each chunk's rows.

Yields:

Type Description
tuple[int, int]

(start, m): sources start .. start + m hold their balls in rows[:m], until the iterator resumes.

Warns:

Type Description
UserWarning

Once, after the first full walk, if any ball exceeded max_neighbors entries.

Source code in ordito/neighbors.py
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
def chunks(self) -> Iterator[tuple[int, int]]:
    """
    Walk the sources a chunk at a time, yielding ``(start, m)`` with each chunk's rows.

    Yields
    ------
    tuple[int, int]
        ``(start, m)``: sources ``start .. start + m`` hold their balls in ``rows[:m]``, until
        the iterator resumes.

    Warns
    -----
    UserWarning
        Once, after the first full walk, if any ball exceeded ``max_neighbors`` entries.
    """
    for start in range(0, self._n, self.chunk):
        m = min(self.chunk, self._n - start)
        # The pool is allocated holding -1; a chunk past the last epoch, a second walk's
        # included, clears what the earlier ones left and starts the epochs over.
        if self._epoch >= max(self._max_epoch, 1):
            _launch.fill_(self._visited_pool, -1)
            self._epoch = 0
        self._epoch += 1
        if self._max_epoch > 0:
            tag, tag_mask = self._epoch << self._tag_shift, -(1 << self._tag_shift)
        else:
            tag = tag_mask = 0
        _launch.launch(
            kernel_neighbors.query_geodesic_ball_collect,
            dim=m,
            inputs=[
                self._vertices,
                self._offsets,
                self._columns,
                self._radius,
                self._min_count,
                wp.int32(start),
                self.rows,
                self._visited_pool,
                self._ext_dist_pool,
                self._ext_idx_pool,
                tag,
                tag_mask,
                self.counts,
                self._overflow,
            ],
            device=self._vertices.device,
        )
        yield start, m
    self._warn_clipped(stacklevel=4)

EdgePathBallWalk

EdgePathBallWalk(
    faces: array[int32], n_vertices: int, radius: float
)

Every vertex's shortest-edge-path ball, walked a chunk of sources at a time into reused rows.

The ball of a vertex is every vertex reachable along mesh edges by a path of total length at most radius. The adjacency is built once; the balls follow whatever positions each chunks call is handed, so a caller moving the mesh (a smoothing pass) walks again over the moved positions. Each call yields (start, m) once sources start .. start + m hold their balls in rows[t, : counts[start + t]], the layout of GeodesicBallWalk; the next chunk reuses the rows.

Parameters:

Name Type Description Default
faces array[int32]

(3 * n_faces,) flat triangle index buffer; its edges are the paths' steps.

required
n_vertices int

Number of vertices the faces index.

required
radius float

Largest path length a ball reaches, in world units (inclusive).

required

Attributes:

Name Type Description
rows Array2dInt32

(chunk, max_neighbors) the current chunk's balls, row t for source start + t.

counts array[int32]

(n_vertices,) each source's ball size, written as its chunk is walked.

chunk int

Sources a chunk holds at most.

Warns:

Type Description
UserWarning

Once, after the first full walk, if any ball exceeded max_neighbors entries; its surplus neighbours were dropped.

See Also

GeodesicBallWalk

Examples:

On an icosahedron inscribed in the unit sphere the edges are about 1.05 long, so a path budget of 1.1 reaches each vertex's five edge neighbours:

import ordito as od

vertices, faces = od.creation.icosahedron()
walk = od.neighbors.EdgePathBallWalk(faces, vertices.size, radius=1.1)
for start, m in walk.chunks(vertices):
    print(start, m, int(walk.counts.numpy()[start : start + m].sum()))  # 0 12 72

Build the sorted adjacency and the chunk's pools; no ball is walked yet.

Methods:

Name Description
chunks

Walk the balls over positions a chunk at a time, yielding (start, m).

Source code in ordito/neighbors.py
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
def __init__(self, faces: wp.array[wp.int32], n_vertices: int, radius: float) -> None:
    """Build the sorted adjacency and the chunk's pools; no ball is walked yet."""
    device = faces.device
    self._faces = faces
    self._radius = wp.float32(radius)
    self._n = n_vertices
    self._columns, self._offsets, _reference = _sorted_vertex_adjacency(faces, n_vertices)
    self.chunk = max(1, min(n_vertices, _EDGE_PATH_BALL_CHUNK))
    stride = kernel_bfs.PER_SOURCE_MAX_NEIGHBORS
    rows_flat, self.counts, pending_flat = _launch.carve(
        wp.int32, [self.chunk * stride, n_vertices, self.chunk * stride], device
    )
    self.rows = odt.as_array2d(rows_flat.reshape((self.chunk, stride)), wp.int32)
    self._pending = odt.as_array2d(pending_flat.reshape((self.chunk, stride)), wp.int32)
    # A walk leaves its keys behind; filling the table before the next chunk costs less than
    # clearing them, which would probe every ball vertex once more.
    self._table = _launch.full(
        (self.chunk, kernel_neighbors.EDGE_PATH_HASH_CAPACITY),
        wp.vec2i(-1, -1),
        dtype=wp.vec2i,
        device=device,
    )
    self._table_dirty = False
    self._overflow = _launch.zeros(1, dtype=wp.int32, device=device)
    self._warned = False

counts instance-attribute

counts: array[int32]

chunk instance-attribute

chunk: int = max(1, min(n_vertices, _EDGE_PATH_BALL_CHUNK))

rows instance-attribute

rows: Array2dInt32 = odt.as_array2d(
    rows_flat.reshape((self.chunk, stride)), wp.int32
)

chunks

chunks(positions: array[vec3]) -> Iterator[tuple[int, int]]

Walk the balls over positions a chunk at a time, yielding (start, m).

Parameters:

Name Type Description Default
positions array[vec3]

(n_vertices,) the vertex positions the path lengths are measured on.

required

Yields:

Type Description
tuple[int, int]

(start, m): sources start .. start + m hold their balls in rows[:m], until the iterator resumes.

Raises:

Type Description
RuntimeError

If positions is not on the device of the walk's faces.

Warns:

Type Description
UserWarning

Once, after the first full walk, if any ball exceeded max_neighbors entries.

Source code in ordito/neighbors.py
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
def chunks(self, positions: wp.array[wp.vec3]) -> Iterator[tuple[int, int]]:
    """
    Walk the balls over ``positions`` a chunk at a time, yielding ``(start, m)``.

    Parameters
    ----------
    positions
        ``(n_vertices,)`` the vertex positions the path lengths are measured on.

    Yields
    ------
    tuple[int, int]
        ``(start, m)``: sources ``start .. start + m`` hold their balls in ``rows[:m]``, until
        the iterator resumes.

    Raises
    ------
    RuntimeError
        If ``positions`` is not on the device of the walk's faces.

    Warns
    -----
    UserWarning
        Once, after the first full walk, if any ball exceeded ``max_neighbors`` entries.
    """
    require_same_device(positions=positions, faces=self._faces)
    for start in range(0, self._n, self.chunk):
        m = min(self.chunk, self._n - start)
        if self._table_dirty:
            _launch.fill_(self._table, wp.vec2i(-1, -1))
        self._table_dirty = True
        _launch.launch(
            kernel_neighbors.query_edge_path_ball_collect,
            dim=m,
            inputs=[
                positions,
                self._offsets,
                self._columns,
                self._radius,
                wp.int32(start),
                self.rows,
                self._pending,
                self._table,
                self.counts,
                self._overflow,
            ],
            device=positions.device,
        )
        yield start, m
    self._warn_clipped()

bvh_from_points

bvh_from_points(
    points: array[vec3], leaf_size: int = 4
) -> wp.Bvh

Build a bounding-volume hierarchy over points for radius queries.

Each point is its own degenerate box (points serves as both bounds, aliased rather than copied, so do not mutate it while the tree is in use), matching the broad-phase pattern used by query_ball and query_nearest.

Parameters:

Name Type Description Default
points array[vec3]

(n,) positions.

required
leaf_size int

Maximum primitives per leaf; forwarded to warp.Bvh. The query families want different leaves: the ball queries and the k = 1 nearest query are fastest at one to four points a leaf, the k > 1 nearest queries at larger leaves the larger the cloud (what query_nearest picks when it builds its own tree). The default sits between them, for a tree shared by all of them.

4

Returns:

Type Description
Bvh

BVH suited for the query_ball* and query_nearest family; pass it as their accelerator, which selects backend="bvh" by its type.

See Also

query_ball query_nearest

Examples:

One tree over a 5 x 5 grid of unit spacing, shared by a ball count and a nearest query. The centre has four neighbours at distance 1, a corner two:

import warp as wp

import ordito as od

points, _ = od.creation.grid(count=(5, 5), extents=(4.0, 4.0))  # unit spacing, 25 points
bvh = od.neighbors.bvh_from_points(points)
queries = wp.array([[0.0, 0.0, 0.0], [-2.0, -2.0, 0.0]], dtype=wp.vec3)
counts = od.neighbors.query_ball_count(points, queries, 1.0, accelerator=bvh)
print(counts.numpy().tolist())  # [5, 3]
indices, distances = od.neighbors.query_nearest(points, queries, k=2, accelerator=bvh)
print(distances.numpy().tolist())  # [[0.0, 1.0], [0.0, 1.0]]
Source code in ordito/neighbors.py
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
def bvh_from_points(points: wp.array[wp.vec3], leaf_size: int = 4) -> wp.Bvh:
    """
    Build a bounding-volume hierarchy over ``points`` for radius queries.

    Each point is its own degenerate box (``points`` serves as both bounds, aliased rather than
    copied, so do not mutate it while the tree is in use), matching the broad-phase pattern used
    by
    [`query_ball`][ordito.neighbors.query_ball] and
    [`query_nearest`][ordito.neighbors.query_nearest].

    Parameters
    ----------
    points
        ``(n,)`` positions.
    leaf_size
        Maximum primitives per leaf; forwarded to ``warp.Bvh``. The query families want different
        leaves: the ball queries and the ``k = 1`` nearest query are fastest at one to four points
        a leaf, the ``k > 1`` nearest queries at larger leaves the larger the cloud (what
        [`query_nearest`][ordito.neighbors.query_nearest] picks when it builds its own tree). The
        default sits between them, for a tree shared by all of them.

    Returns
    -------
    warp.Bvh
        BVH suited for the ``query_ball*`` and ``query_nearest`` family; pass it as their
        ``accelerator``, which selects ``backend="bvh"`` by its type.

    See Also
    --------
    [`query_ball`][ordito.neighbors.query_ball]
    [`query_nearest`][ordito.neighbors.query_nearest]

    Examples
    --------
    One tree over a 5 x 5 grid of unit spacing, shared by a ball count and a nearest query. The
    centre has four neighbours at distance 1, a corner two:

    ```python
    import warp as wp

    import ordito as od

    points, _ = od.creation.grid(count=(5, 5), extents=(4.0, 4.0))  # unit spacing, 25 points
    bvh = od.neighbors.bvh_from_points(points)
    queries = wp.array([[0.0, 0.0, 0.0], [-2.0, -2.0, 0.0]], dtype=wp.vec3)
    counts = od.neighbors.query_ball_count(points, queries, 1.0, accelerator=bvh)
    print(counts.numpy().tolist())  # [5, 3]
    indices, distances = od.neighbors.query_nearest(points, queries, k=2, accelerator=bvh)
    print(distances.numpy().tolist())  # [[0.0, 1.0], [0.0, 1.0]]
    ```
    """
    return wp.Bvh(points, points, leaf_size=leaf_size)

hashgrid_from_points

hashgrid_from_points(
    points: array[vec3],
    radius: float,
    grid_bins: int | None = None,
) -> wp.HashGrid

Build a 3D hash grid over points for radius queries.

Parameters:

Name Type Description Default
points array[vec3]

(n,) positions.

required
radius float

Cell size passed to warp.HashGrid.build and used by the query_ball* and query_nearest kernels under backend="hashgrid".

required
grid_bins int | None

Resolution of the hash grid along each axis. None (the default) sizes it from the point count: 128 up to about a million points, then growing with the cube root of the count so the table keeps at least two bins a point, up to 384. The grid wraps cell coordinates modulo this resolution, so a cloud spanning more cells than it has bins shares buckets between distant cells; the answer of every query is unaffected, only its cost.

None

Returns:

Type Description
HashGrid

Hash grid suited for the query_ball* and query_nearest family, and related kernels. The cell width is recorded on the returned object as cell_width, which query_nearest reads back to size its search, and the resolution along each axis as resolution (warp.HashGrid itself keeps neither).

See Also

query_ball_count query_ball query_nearest

Examples:

import warp as wp

import ordito as od

points, _ = od.creation.grid(count=(5, 5), extents=(4.0, 4.0))  # unit spacing, 25 points
grid = od.neighbors.hashgrid_from_points(points, radius=1.0)
print(grid.cell_width)  # 1.0
queries = wp.array([[0.0, 0.0, 0.0], [-2.0, -2.0, 0.0]], dtype=wp.vec3)
counts = od.neighbors.query_ball_count(points, queries, 1.0, accelerator=grid)
print(counts.numpy().tolist())  # [5, 3]
Source code in ordito/neighbors.py
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
def hashgrid_from_points(
    points: wp.array[wp.vec3], radius: float, grid_bins: int | None = None
) -> wp.HashGrid:
    """
    Build a 3D hash grid over ``points`` for radius queries.

    Parameters
    ----------
    points
        ``(n,)`` positions.
    radius
        Cell size passed to ``warp.HashGrid.build`` and used by
        the ``query_ball*`` and ``query_nearest`` kernels under ``backend="hashgrid"``.
    grid_bins
        Resolution of the hash grid along each axis. ``None`` (the default) sizes it from the point
        count: 128 up to about a million points, then growing with the cube root of the count so
        the table keeps at least two bins a point, up to 384. The grid wraps cell coordinates
        modulo this resolution, so a cloud spanning more cells than it has bins shares buckets
        between distant cells; the answer of every query is unaffected, only its cost.

    Returns
    -------
    warp.HashGrid
        Hash grid suited for the ``query_ball*`` and ``query_nearest`` family,
        and related kernels. The cell width is recorded on the returned object as
        ``cell_width``, which
        [`query_nearest`][ordito.neighbors.query_nearest] reads back to size its
        search, and the resolution along each axis as ``resolution`` (``warp.HashGrid`` itself
        keeps neither).

    See Also
    --------
    [`query_ball_count`][ordito.neighbors.query_ball_count]
    [`query_ball`][ordito.neighbors.query_ball]
    [`query_nearest`][ordito.neighbors.query_nearest]

    Examples
    --------
    ```python
    import warp as wp

    import ordito as od

    points, _ = od.creation.grid(count=(5, 5), extents=(4.0, 4.0))  # unit spacing, 25 points
    grid = od.neighbors.hashgrid_from_points(points, radius=1.0)
    print(grid.cell_width)  # 1.0
    queries = wp.array([[0.0, 0.0, 0.0], [-2.0, -2.0, 0.0]], dtype=wp.vec3)
    counts = od.neighbors.query_ball_count(points, queries, 1.0, accelerator=grid)
    print(counts.numpy().tolist())  # [5, 3]
    ```
    """
    n = points.size
    bins = _resolve_grid_bins(grid_bins, n)
    grid = wp.HashGrid(bins, bins, bins, device=points.device)
    grid.reserve(n)
    grid.build(points, radius)
    # Documented on the returned object; ``warp.HashGrid`` declares no such attribute.
    grid.cell_width = float(radius)  # pyright: ignore[reportAttributeAccessIssue]
    grid.resolution = bins  # pyright: ignore[reportAttributeAccessIssue]
    return grid

bvh_from_bounds

bvh_from_bounds(
    lower: array[vec3],
    upper: array[vec3],
    leaf_size: int = 4,
) -> wp.Bvh

Build a bounding-volume hierarchy over axis-aligned bounds.

Each primitive i is represented by lower[i] and upper[i] corner positions, suitable for query_bvh_ball and query_bvh_box broad-phase intersection tests.

Parameters:

Name Type Description Default
lower array[vec3]

(n,) minimum corner of each bound.

required
upper array[vec3]

(n,) maximum corner of each bound.

required
leaf_size int

Maximum primitives per leaf; forwarded to warp.Bvh.

4

Returns:

Type Description
Bvh

BVH suited for AABB intersection queries.

Raises:

Type Description
RuntimeError

If lower and upper are not all on one device.

Examples:

Three unit boxes in a row along x; a ball between the first two reaches both:

import warp as wp

import ordito as od

lower = wp.array([[0.0, 0.0, 0.0], [2.0, 0.0, 0.0], [4.0, 0.0, 0.0]], dtype=wp.vec3)
upper = wp.array([[1.0, 1.0, 1.0], [3.0, 1.0, 1.0], [5.0, 1.0, 1.0]], dtype=wp.vec3)
bvh = od.neighbors.bvh_from_bounds(lower, upper)
queries = wp.array([[1.5, 0.5, 0.5]], dtype=wp.vec3)
hits, offsets = od.neighbors.query_bvh_ball(bvh, queries, 0.6)
print(sorted(hits.numpy().tolist()))  # [0, 1]
Source code in ordito/neighbors.py
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
def bvh_from_bounds(
    lower: wp.array[wp.vec3], upper: wp.array[wp.vec3], leaf_size: int = 4
) -> wp.Bvh:
    """
    Build a bounding-volume hierarchy over axis-aligned bounds.

    Each primitive ``i`` is represented by ``lower[i]`` and ``upper[i]`` corner
    positions, suitable for
    [`query_bvh_ball`][ordito.neighbors.query_bvh_ball] and
    [`query_bvh_box`][ordito.neighbors.query_bvh_box]
    broad-phase intersection tests.

    Parameters
    ----------
    lower
        ``(n,)`` minimum corner of each bound.
    upper
        ``(n,)`` maximum corner of each bound.
    leaf_size
        Maximum primitives per leaf; forwarded to ``warp.Bvh``.

    Returns
    -------
    warp.Bvh
        BVH suited for AABB intersection queries.

    Raises
    ------
    RuntimeError
        If ``lower`` and ``upper`` are not all on one device.

    Examples
    --------
    Three unit boxes in a row along ``x``; a ball between the first two reaches both:

    ```python
    import warp as wp

    import ordito as od

    lower = wp.array([[0.0, 0.0, 0.0], [2.0, 0.0, 0.0], [4.0, 0.0, 0.0]], dtype=wp.vec3)
    upper = wp.array([[1.0, 1.0, 1.0], [3.0, 1.0, 1.0], [5.0, 1.0, 1.0]], dtype=wp.vec3)
    bvh = od.neighbors.bvh_from_bounds(lower, upper)
    queries = wp.array([[1.5, 0.5, 0.5]], dtype=wp.vec3)
    hits, offsets = od.neighbors.query_bvh_ball(bvh, queries, 0.6)
    print(sorted(hits.numpy().tolist()))  # [0, 1]
    ```
    """
    require_same_device(lower=lower, upper=upper)
    return wp.Bvh(lower, upper, leaf_size=leaf_size)

query_bvh_ball

query_bvh_ball(
    bvh: Bvh, queries: array[vec3], radius: float
) -> tuple[wp.array[wp.int32], wp.array[wp.int32]]

Low-level BVH ball query: primitive indices in one flat buffer plus offsets.

For each query center q, tests whether every primitive bound in bvh comes within radius of q -- the exact bound-to-point distance, so the returned set is the ball's and not its enclosing cube's. Like query_bvh_box and unlike query_ball_with_offsets, there is no narrow-phase filter on the primitive's own geometry: every bound the ball reaches is returned.

Parameters:

Name Type Description Default
bvh Bvh

Pre-built BVH from bvh_from_bounds or bvh_from_points.

required
queries array[vec3]

(m,) query centers.

required
radius float

Ball radius about each query center.

required

Returns:

Type Description
(candidate_indices_flat, offsets)

(n_hits,) candidate indices and (m + 1,) offsets, exactly the packing query_bvh_box returns: offsets is the total-terminated prefix sum of per-query hit counts, and query k owns candidate_indices_flat[offsets[k] : offsets[k + 1]].

Raises:

Type Description
RuntimeError

If bvh and queries are not all on one device.

Notes

Prefer this over the cube query wherever the caller's predicate is a ball, and not only for the candidates it does not return: the ball traversal is substantially cheaper per candidate than the box one, enough that the cube query loses even when handed the inscribed cube and therefore strictly fewer candidates. The margin grows with the radius, which is where a cube broad phase hurts most.

See Also

query_bvh_box The same packing for an axis-aligned box, given per query. A box is a different predicate and not a looser ball -- it admits corners the ball excludes -- so reach for it when the neighbourhood really is axis-aligned, and for this when it is a ball. query_ball_with_offsets The same ball, over a point cloud and with a narrow-phase distance filter.

Examples:

Three unit boxes in a row along x. The first query sits in the gap between the first two, 0.5 from each; the second is 2.5 from the nearest box and finds nothing:

import warp as wp

import ordito as od

lower = wp.array([[0.0, 0.0, 0.0], [2.0, 0.0, 0.0], [4.0, 0.0, 0.0]], dtype=wp.vec3)
upper = wp.array([[1.0, 1.0, 1.0], [3.0, 1.0, 1.0], [5.0, 1.0, 1.0]], dtype=wp.vec3)
bvh = od.neighbors.bvh_from_bounds(lower, upper)
queries = wp.array([[1.5, 0.5, 0.5], [3.5, 3.5, 0.5]], dtype=wp.vec3)
hits, offsets = od.neighbors.query_bvh_ball(bvh, queries, 1.0)
print(offsets.numpy().tolist())  # [0, 2, 2]
print(sorted(hits.numpy().tolist()))  # [0, 1]
Source code in ordito/neighbors.py
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
def query_bvh_ball(
    bvh: wp.Bvh, queries: wp.array[wp.vec3], radius: float
) -> tuple[wp.array[wp.int32], wp.array[wp.int32]]:
    """
    Low-level BVH ball query: primitive indices in one flat buffer plus offsets.

    For each query center ``q``, tests whether every primitive bound in ``bvh`` comes within
    ``radius`` of ``q`` -- the exact bound-to-point distance, so the returned set is the ball's and
    not its enclosing cube's. Like
    [`query_bvh_box`][ordito.neighbors.query_bvh_box] and unlike
    [`query_ball_with_offsets`][ordito.neighbors.query_ball_with_offsets], there is no
    narrow-phase filter on the primitive's own geometry: every bound the ball reaches is returned.

    Parameters
    ----------
    bvh
        Pre-built BVH from [`bvh_from_bounds`][ordito.neighbors.bvh_from_bounds]
        or [`bvh_from_points`][ordito.neighbors.bvh_from_points].
    queries
        ``(m,)`` query centers.
    radius
        Ball radius about each query center.

    Returns
    -------
    candidate_indices_flat, offsets
        ``(n_hits,)`` candidate indices and ``(m + 1,)`` offsets, exactly the packing
        [`query_bvh_box`][ordito.neighbors.query_bvh_box] returns: ``offsets`` is the
        total-terminated prefix sum of per-query hit counts, and query ``k`` owns
        ``candidate_indices_flat[offsets[k] : offsets[k + 1]]``.

    Raises
    ------
    RuntimeError
        If ``bvh`` and ``queries`` are not all on one device.

    Notes
    -----
    Prefer this over the cube query wherever the caller's predicate is a ball, and not only for the
    candidates it does not return: the ball traversal is *substantially cheaper per candidate* than
    the box one, enough that the cube query loses even when handed the inscribed cube and therefore
    strictly fewer candidates. The margin grows with the radius, which is where a cube broad phase
    hurts most.

    See Also
    --------
    [`query_bvh_box`][ordito.neighbors.query_bvh_box]
        The same packing for an axis-aligned **box**, given per query. A box is a different
        predicate and not a looser ball -- it admits corners the ball excludes -- so reach for it
        when the neighbourhood really is axis-aligned, and for this when it is a ball.
    [`query_ball_with_offsets`][ordito.neighbors.query_ball_with_offsets]
        The same ball, over a **point** cloud and with a narrow-phase distance filter.

    Examples
    --------
    Three unit boxes in a row along ``x``. The first query sits in the gap between the first two,
    ``0.5`` from each; the second is ``2.5`` from the nearest box and finds nothing:

    ```python
    import warp as wp

    import ordito as od

    lower = wp.array([[0.0, 0.0, 0.0], [2.0, 0.0, 0.0], [4.0, 0.0, 0.0]], dtype=wp.vec3)
    upper = wp.array([[1.0, 1.0, 1.0], [3.0, 1.0, 1.0], [5.0, 1.0, 1.0]], dtype=wp.vec3)
    bvh = od.neighbors.bvh_from_bounds(lower, upper)
    queries = wp.array([[1.5, 0.5, 0.5], [3.5, 3.5, 0.5]], dtype=wp.vec3)
    hits, offsets = od.neighbors.query_bvh_ball(bvh, queries, 1.0)
    print(offsets.numpy().tolist())  # [0, 2, 2]
    print(sorted(hits.numpy().tolist()))  # [0, 1]
    ```
    """
    require_same_device(bvh=bvh, queries=queries)
    device = queries.device
    m = queries.size

    if m == 0:
        return _launch.empty_packed(wp.int32, device)

    # The counts land behind the leading zero of the ``m + 1`` offsets buffer and are scanned there
    # in place, so no separate count buffer is allocated.
    offsets, hit_counts = offsets_buffer(m, device)
    # ``wp.uint64(bvh.id)`` explicitly: unlike ``wp.launch``, ``wp.map`` infers a bare Python int
    # scalar's dtype as ``wp.int32`` rather than matching the mapped @wp.func's declared parameter
    # type, and a mismatched dtype is a codegen-time TypeError, not a silent truncation.
    _launch.map(
        kernel_neighbors.ball_count_in_bounds,
        wp.uint64(bvh.id),
        queries,
        wp.float32(radius),
        out=hit_counts,
    )

    # The total sizes the candidate buffer.
    total_hits = scan_count(hit_counts)
    if total_hits == 0:
        return _launch.empty(0, dtype=wp.int32, device=device), offsets

    candidate_indices_flat = _launch.empty(total_hits, dtype=wp.int32, device=device)
    _launch.launch(
        kernel_neighbors.query_bvh_ball_neighbors,
        dim=m,
        inputs=[queries, bvh.id, wp.float32(radius), offsets, candidate_indices_flat],
        device=device,
    )

    return candidate_indices_flat, offsets

query_bvh_box

query_bvh_box(
    bvh: Bvh,
    query_lower: array[vec3],
    query_upper: array[vec3],
) -> tuple[wp.array[wp.int32], wp.array[wp.int32]]

Primitives overlapping one axis-aligned box per query, in the same CSR packing.

The box counterpart of the ball queries, and the per-query generalization of query_bvh_ball: each query carries its own (lower, upper) corners rather than sharing one cube size. On a BVH built by bvh_from_points, whose leaf bounds are degenerate, a hit means the point is inside the box, so the answer is exact and no narrow phase is needed; on one built by bvh_from_bounds it is box-versus-box overlap, like every other broad phase here.

Parameters:

Name Type Description Default
bvh Bvh

Pre-built BVH over points or bounds.

required
query_lower array[vec3]

(m,) corners of the query boxes, one pair per query.

required
query_upper array[vec3]

(m,) corners of the query boxes, one pair per query.

required

Returns:

Type Description
(candidate_indices_flat, offsets)

(n_hits,) candidate indices and (m + 1,) offsets: query k owns candidate_indices_flat[offsets[k] : offsets[k + 1]], with offsets the total-terminated prefix sum of per-query hit counts.

Raises:

Type Description
ValueError

If query_lower and query_upper do not have the same length.

RuntimeError

If bvh, query_lower and query_upper are not all on one device.

Notes

The test is inclusive on every face: a point exactly on a box face (lower or upper) is inside it. A box with any upper < lower component matches nothing, and that is not checked -- the check would cost a host readback per call to reject a caller error whose answer is already empty.

There is no list-returning sibling, so the name carries no _with_offsets suffix: this query's consumers are kernels that recover the owning query from offsets, and a Python list of per-query arrays would add O(m) host slicing to a query whose whole point is that it is batched.

See Also

query_bvh_ball The same packing over the same bounds for a ball, and the one to prefer wherever the predicate is a ball rather than an axis-aligned region -- not only because the box admits corners the ball excludes, but because the box traversal is itself several times more expensive per candidate returned: the cost is dominated by the node test itself, not by how many candidates come back. ordito.points.half_space_mask The unbounded counterpart: selection by one plane rather than by a box.

Examples:

On a point tree a hit means the point lies inside the box, faces included: the second box has the four grid points (-2..-1, -2..-1) on its corners:

import warp as wp

import ordito as od

points, _ = od.creation.grid(count=(5, 5), extents=(4.0, 4.0))  # unit spacing, 25 points
bvh = od.neighbors.bvh_from_points(points)
query_lower = wp.array([[-0.5, -0.5, -1.0], [-2.0, -2.0, 0.0]], dtype=wp.vec3)
query_upper = wp.array([[1.5, 0.5, 1.0], [-1.0, -1.0, 0.0]], dtype=wp.vec3)
hits, offsets = od.neighbors.query_bvh_box(bvh, query_lower, query_upper)
print(offsets.numpy().tolist())  # [0, 2, 6]
print(sorted(hits.numpy()[:2].tolist()))  # [12, 17]
Source code in ordito/neighbors.py
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
def query_bvh_box(
    bvh: wp.Bvh, query_lower: wp.array[wp.vec3], query_upper: wp.array[wp.vec3]
) -> tuple[wp.array[wp.int32], wp.array[wp.int32]]:
    """
    Primitives overlapping one axis-aligned box **per query**, in the same CSR packing.

    The box counterpart of the ball queries, and the per-query generalization of
    [`query_bvh_ball`][ordito.neighbors.query_bvh_ball]: each query
    carries its own ``(lower, upper)`` corners rather than sharing one cube size. On a BVH built by
    [`bvh_from_points`][ordito.neighbors.bvh_from_points], whose leaf bounds are degenerate, a hit
    means the point is **inside** the box, so the answer is exact and no narrow phase is needed; on
    one built by [`bvh_from_bounds`][ordito.neighbors.bvh_from_bounds] it is box-versus-box
    overlap, like every other broad phase here.

    Parameters
    ----------
    bvh
        Pre-built BVH over points or bounds.
    query_lower, query_upper
        ``(m,)`` corners of the query boxes, one pair per query.

    Returns
    -------
    candidate_indices_flat, offsets
        ``(n_hits,)`` candidate indices and ``(m + 1,)`` offsets: query ``k`` owns
        ``candidate_indices_flat[offsets[k] : offsets[k + 1]]``, with ``offsets`` the
        total-terminated prefix sum of per-query hit counts.

    Raises
    ------
    ValueError
        If ``query_lower`` and ``query_upper`` do not have the same length.
    RuntimeError
        If ``bvh``, ``query_lower`` and ``query_upper`` are not all on one device.

    Notes
    -----
    The test is **inclusive** on every face: a point exactly on a box face (lower or upper) is
    inside it. A box with any ``upper < lower`` component matches nothing, and that is not checked
    -- the check would cost a host readback per call to reject a caller error whose answer is
    already empty.

    There is no list-returning sibling, so the name carries no ``_with_offsets`` suffix: this
    query's consumers are kernels that recover the owning query from ``offsets``, and a Python list
    of per-query arrays would add ``O(m)`` host slicing to a query whose whole point is that it is
    batched.

    See Also
    --------
    [`query_bvh_ball`][ordito.neighbors.query_bvh_ball]
        The same packing over the same bounds for a **ball**, and the one to prefer wherever the
        predicate is a ball rather than an axis-aligned region -- not only because the box admits
        corners the ball excludes, but because the box *traversal* is itself several times more
        expensive per candidate returned: the cost is dominated by the node test itself, not by
        how many candidates come back.
    [`ordito.points.half_space_mask`][ordito.points.half_space_mask]
        The unbounded counterpart: selection by one plane rather than by a box.

    Examples
    --------
    On a point tree a hit means the point lies inside the box, faces included: the second box has
    the four grid points ``(-2..-1, -2..-1)`` on its corners:

    ```python
    import warp as wp

    import ordito as od

    points, _ = od.creation.grid(count=(5, 5), extents=(4.0, 4.0))  # unit spacing, 25 points
    bvh = od.neighbors.bvh_from_points(points)
    query_lower = wp.array([[-0.5, -0.5, -1.0], [-2.0, -2.0, 0.0]], dtype=wp.vec3)
    query_upper = wp.array([[1.5, 0.5, 1.0], [-1.0, -1.0, 0.0]], dtype=wp.vec3)
    hits, offsets = od.neighbors.query_bvh_box(bvh, query_lower, query_upper)
    print(offsets.numpy().tolist())  # [0, 2, 6]
    print(sorted(hits.numpy()[:2].tolist()))  # [12, 17]
    ```
    """
    require_same_device(bvh=bvh, query_lower=query_lower, query_upper=query_upper)
    device = query_lower.device
    m = query_lower.size
    if query_upper.size != m:
        raise ValueError("query_lower and query_upper must have the same length")

    if m == 0:
        return _launch.empty_packed(wp.int32, device)

    offsets, hit_counts = offsets_buffer(m, device)
    # ``wp.uint64(bvh.id)`` explicitly -- see the same cast in ``query_bvh_ball``
    # above.
    _launch.map(
        kernel_neighbors.aabb_count_in_bounds,
        wp.uint64(bvh.id),
        query_lower,
        query_upper,
        out=hit_counts,
    )

    # The total sizes the candidate buffer.
    total_hits = scan_count(hit_counts)
    if total_hits == 0:
        return _launch.empty(0, dtype=wp.int32, device=device), offsets

    candidate_indices_flat = _launch.empty(total_hits, dtype=wp.int32, device=device)
    _launch.launch(
        kernel_neighbors.query_bvh_box_neighbors,
        dim=m,
        inputs=[query_lower, query_upper, bvh.id, offsets, candidate_indices_flat],
        device=device,
    )

    return candidate_indices_flat, offsets

query_ball

query_ball(
    points: array[vec3],
    queries: array[vec3],
    r: float,
    *,
    accelerator: HashGrid | Bvh | None = ...,
    backend: QueryBackend | None = ...,
    grid_bins: int | None = ...,
    leaf_size: int = ...,
    return_sorted: bool = ...,
    copy: bool = ...,
) -> tuple[
    list[wp.array[wp.int32]], list[wp.array[wp.float32]]
]
query_ball(
    points: array[vec3],
    queries: vec3,
    r: float,
    *,
    accelerator: HashGrid | Bvh | None = ...,
    backend: QueryBackend | None = ...,
    grid_bins: int | None = ...,
    leaf_size: int = ...,
    return_sorted: bool = ...,
    copy: bool = ...,
) -> tuple[wp.array[wp.int32], wp.array[wp.float32]]
query_ball(
    points: array[vec3],
    queries: array[vec3] | vec3,
    r: float,
    *,
    accelerator: HashGrid | Bvh | None = None,
    backend: QueryBackend | None = None,
    grid_bins: int | None = None,
    leaf_size: int = _BALL_LEAF_SIZE,
    return_sorted: bool = False,
    copy: bool = False,
) -> (
    tuple[
        list[wp.array[wp.int32]], list[wp.array[wp.float32]]
    ]
    | tuple[wp.array[wp.int32], wp.array[wp.float32]]
)

Find all data points within distance r of each query center (per-query arrays).

Same exact search as scipy.spatial.KDTree.query_ball_point with p=2 and eps=0; only the spatial index differs, and which index is a keyword rather than a function name (see backend). High-level wrapper around query_ball_with_offsets.

Unlike SciPy's object array of lists, multi-query results are two Python lists of length m, each element a rank-1 wp.array for that query. A single wp.vec3 query returns one (indices, distances) pair directly (not wrapped in lists). This is split over query_ball_with_offsets's packed result; call that instead for one flat buffer plus offsets on device.

The returned arrays are views

Each query's arrays slice the two flat buffers the packed query produced, which costs no device memory and no launches. Holding on to one query's arrays keeps the whole buffers alive, and writing into one writes into the shared allocation. Pass copy=True for independent buffers.

Parameters:

Name Type Description Default
points array[vec3]

(n,) data points.

required
queries array[vec3] | vec3

(m,) query centers as wp.array[wp.vec3], or a single wp.vec3 (treated as one query).

required
r float

Inclusion radius; cast to float32 in kernels (non-negative).

required
accelerator HashGrid | Bvh | None

A prebuilt warp.HashGrid or warp.Bvh over points, to reuse across queries. It selects the backend by its own type, so backend is redundant when this is given and raises if it names the other one.

None
backend QueryBackend | None

Which broad phase to use when accelerator is None: "hashgrid" (the default) enumerates the cells overlapping the query cube, "bvh" descends an AABB tree. The narrow phase and the answer are identical -- this is a cost choice, not a semantic one.

None
grid_bins int | None

Grid resolution when building a hash grid; None sizes it from the point count, as in hashgrid_from_points. Ignored under backend="bvh" and whenever accelerator is given.

None
leaf_size int

Maximum primitives per leaf when building a BVH; one point a leaf is the fastest walk for a ball query. Ignored under backend="hashgrid" and whenever accelerator is given.

_BALL_LEAF_SIZE
return_sorted bool

If True, neighbors within each query are ordered by increasing distance. If False, order follows the broad phase's traversal (undefined ordering).

False
copy bool

Return independent buffers instead of views into the packed result.

False

Returns:

Type Description
(neighbor_indices, neighbor_distances)

If queries has m rows: list[wp.array[wp.int32]] and list[wp.array[wp.float32]], each of length m. Element k lists neighbors of queries[k] (indices into points and distances ‖points[i] - q‖₂).

If queries is a single wp.vec3: two (n_neighbors,) arrays (possibly empty), not lists.

Empty points yields empty neighbor arrays and per-query empty slices; duplicate neighbors are not produced.

Raises:

Type Description
ValueError

If backend is neither name, or contradicts the type of accelerator.

RuntimeError

If points, queries and accelerator are not all on one device.

Notes

SciPy may sort indices when return_sorted is left default on multi-point queries; here sorting only occurs when return_sorted=True, and sorts by distance, not by index. Ball boundaries use float32 arithmetic; extremely tight radii near representable limits may disagree slightly with pure float64 SciPy runs.

See Also

query_ball_with_offsets The flat CSR form, without cloning a segment per query. query_ball_count The counts alone, when the neighbors themselves are not wanted. hashgrid_from_points bvh_from_points scipy.spatial.KDTree.query_ball_point

Examples:

On a 5 x 5 grid of unit spacing the ball of radius 1 (inclusive) about the centre, index 12, holds it and its four axis neighbours; about a corner, three points:

import warp as wp

import ordito as od

points, _ = od.creation.grid(count=(5, 5), extents=(4.0, 4.0))  # unit spacing, 25 points
queries = wp.array([[0.0, 0.0, 0.0], [-2.0, -2.0, 0.0]], dtype=wp.vec3)
indices, distances = od.neighbors.query_ball(points, queries, 1.0)
print(len(indices))  # 2
print(sorted(indices[0].numpy().tolist()))  # [7, 11, 12, 13, 17]
print(sorted(indices[1].numpy().tolist()))  # [0, 1, 5]

A single wp.vec3 query returns its arrays directly, here sorted by distance:

import warp as wp

import ordito as od

points, _ = od.creation.grid(count=(5, 5), extents=(4.0, 4.0))  # unit spacing, 25 points
query = wp.vec3(0.0, 0.0, 0.0)
indices, distances = od.neighbors.query_ball(points, query, 1.0, return_sorted=True)
print(indices.numpy()[0])  # 12
print(distances.numpy().tolist())  # [0.0, 1.0, 1.0, 1.0, 1.0]
Source code in ordito/neighbors.py
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
def query_ball(
    points: wp.array[wp.vec3],
    queries: wp.array[wp.vec3] | wp.vec3,
    r: float,
    *,
    accelerator: wp.HashGrid | wp.Bvh | None = None,
    backend: QueryBackend | None = None,
    grid_bins: int | None = None,
    leaf_size: int = _BALL_LEAF_SIZE,
    return_sorted: bool = False,
    copy: bool = False,
) -> (
    tuple[list[wp.array[wp.int32]], list[wp.array[wp.float32]]]
    | tuple[wp.array[wp.int32], wp.array[wp.float32]]
):
    """
    Find all data points within distance ``r`` of each query center (per-query arrays).

    Same exact search as [`scipy.spatial.KDTree.query_ball_point`][] with ``p=2`` and ``eps=0``;
    only the spatial index differs, and which index is a keyword rather than a function name (see
    ``backend``). High-level wrapper around
    [`query_ball_with_offsets`][ordito.neighbors.query_ball_with_offsets].

    Unlike SciPy's object array of lists, multi-query results are two Python lists of length ``m``,
    each element a rank-1 ``wp.array`` for that query. A single ``wp.vec3`` query returns one
    ``(indices, distances)`` pair directly (not wrapped in lists). This is
    [`split`][ordito.array.split] over
    [`query_ball_with_offsets`][ordito.neighbors.query_ball_with_offsets]'s packed result; call
    that instead for one flat buffer plus offsets on device.

    !!! note "The returned arrays are views"
        Each query's arrays slice the two flat buffers the packed query produced, which costs no
        device memory and no launches. Holding on to one query's arrays keeps the *whole* buffers
        alive, and writing into one writes into the shared allocation. Pass ``copy=True`` for
        independent buffers.

    Parameters
    ----------
    points
        ``(n,)`` data points.
    queries
        ``(m,)`` query centers as ``wp.array[wp.vec3]``, or a single ``wp.vec3`` (treated as one
        query).
    r
        Inclusion radius; cast to ``float32`` in kernels (non-negative).
    accelerator
        A prebuilt ``warp.HashGrid`` or ``warp.Bvh`` over ``points``, to reuse across queries. It
        selects the backend by its own type, so ``backend`` is redundant when this is given and
        raises if it names the other one.
    backend
        Which broad phase to use when ``accelerator`` is ``None``: ``"hashgrid"`` (the default)
        enumerates the cells overlapping the query cube, ``"bvh"`` descends an AABB tree. The
        narrow phase and the answer are identical -- this is a cost choice, not a semantic one.
    grid_bins
        Grid resolution when building a hash grid; ``None`` sizes it from the point count, as in
        [`hashgrid_from_points`][ordito.neighbors.hashgrid_from_points]. Ignored under
        ``backend="bvh"`` and whenever ``accelerator`` is given.
    leaf_size
        Maximum primitives per leaf when building a BVH; one point a leaf is the fastest walk for
        a ball query. Ignored under ``backend="hashgrid"`` and whenever ``accelerator`` is given.
    return_sorted
        If ``True``, neighbors within each query are ordered by increasing distance. If ``False``,
        order follows the broad phase's traversal (undefined ordering).
    copy
        Return independent buffers instead of views into the packed result.

    Returns
    -------
    neighbor_indices, neighbor_distances
        If ``queries`` has ``m`` rows: ``list[wp.array[wp.int32]]`` and
        ``list[wp.array[wp.float32]]``, each of length ``m``. Element ``k`` lists neighbors
        of ``queries[k]`` (indices into ``points`` and distances ``‖points[i] - q‖₂``).

        If ``queries`` is a single ``wp.vec3``: two ``(n_neighbors,)`` arrays (possibly empty), not
        lists.

        Empty ``points`` yields empty neighbor arrays and per-query empty slices; duplicate
        neighbors are not produced.

    Raises
    ------
    ValueError
        If ``backend`` is neither name, or contradicts the type of ``accelerator``.
    RuntimeError
        If ``points``, ``queries`` and ``accelerator`` are not all on one device.

    Notes
    -----
    SciPy may sort indices when ``return_sorted`` is left default on multi-point queries; here
    sorting only occurs when ``return_sorted=True``, and sorts by distance, not by index. Ball
    boundaries use ``float32`` arithmetic; extremely tight radii near representable limits may
    disagree slightly with pure ``float64`` SciPy runs.

    See Also
    --------
    [`query_ball_with_offsets`][ordito.neighbors.query_ball_with_offsets]
        The flat CSR form, without cloning a segment per query.
    [`query_ball_count`][ordito.neighbors.query_ball_count]
        The counts alone, when the neighbors themselves are not wanted.
    [`hashgrid_from_points`][ordito.neighbors.hashgrid_from_points]
    [`bvh_from_points`][ordito.neighbors.bvh_from_points]
    [`scipy.spatial.KDTree.query_ball_point`][]

    Examples
    --------
    On a 5 x 5 grid of unit spacing the ball of radius 1 (inclusive) about the centre, index 12,
    holds it and its four axis neighbours; about a corner, three points:

    ```python
    import warp as wp

    import ordito as od

    points, _ = od.creation.grid(count=(5, 5), extents=(4.0, 4.0))  # unit spacing, 25 points
    queries = wp.array([[0.0, 0.0, 0.0], [-2.0, -2.0, 0.0]], dtype=wp.vec3)
    indices, distances = od.neighbors.query_ball(points, queries, 1.0)
    print(len(indices))  # 2
    print(sorted(indices[0].numpy().tolist()))  # [7, 11, 12, 13, 17]
    print(sorted(indices[1].numpy().tolist()))  # [0, 1, 5]
    ```

    A single ``wp.vec3`` query returns its arrays directly, here sorted by distance:

    ```python
    import warp as wp

    import ordito as od

    points, _ = od.creation.grid(count=(5, 5), extents=(4.0, 4.0))  # unit spacing, 25 points
    query = wp.vec3(0.0, 0.0, 0.0)
    indices, distances = od.neighbors.query_ball(points, query, 1.0, return_sorted=True)
    print(indices.numpy()[0])  # 12
    print(distances.numpy().tolist())  # [0.0, 1.0, 1.0, 1.0, 1.0]
    ```
    """
    require_same_device(points=points, queries=queries, accelerator=accelerator)
    device = points.device

    single_query = not isinstance(queries, wp.array)
    if single_query:
        queries = _launch.array([queries], dtype=wp.vec3, device=device)

    # The per-query views need host bounds: read once, in place of the total the query would
    # read to size its buffers, and shared by both splits.
    neighbor_indices_flat, neighbor_distances_flat, _, bounds = _ball_query(
        points, queries, r, accelerator, backend, grid_bins, leaf_size, return_sorted, True
    )
    assert bounds is not None
    neighbor_indices = od.array.split(neighbor_indices_flat, bounds, copy=copy)
    neighbor_distances = od.array.split(neighbor_distances_flat, bounds, copy=copy)

    if single_query:
        return neighbor_indices[0], neighbor_distances[0]
    return neighbor_indices, neighbor_distances

query_ball_count

query_ball_count(
    points: array[vec3],
    queries: array[vec3],
    r: float,
    *,
    accelerator: HashGrid | Bvh | None = None,
    backend: QueryBackend | None = None,
    grid_bins: int | None = None,
    leaf_size: int = _BALL_LEAF_SIZE,
) -> wp.array[wp.int32]

Count neighbors of each query within Euclidean distance r.

For each query center q, returns how many entries p in points satisfy ‖p - q‖₂ ≤ r. This matches scipy.spatial.KDTree.query_ball_point with p=2, eps=0, and return_length=True (exact search; only the spatial index differs).

The narrow phase keeps points with float32 Euclidean distance at most r whichever broad phase ran, so the count does not depend on backend.

Parameters:

Name Type Description Default
points array[vec3]

(n,) data points.

required
queries array[vec3]

(m,) query centers.

required
r float

Inclusion radius; cast to float32 in kernels (non-negative).

required
accelerator HashGrid | Bvh | None

As in query_ball.

None
backend HashGrid | Bvh | None

As in query_ball.

None
grid_bins HashGrid | Bvh | None

As in query_ball.

None
leaf_size HashGrid | Bvh | None

As in query_ball.

None

Returns:

Type Description
array[int32]

(m,) device array whose k-th element is the neighbor count for queries[k]. If n == 0, returns zeros.

Raises:

Type Description
ValueError

If backend is neither name, or contradicts the type of accelerator.

RuntimeError

If points, queries and accelerator are not all on one device.

See Also

query_ball hashgrid_from_points bvh_from_points scipy.spatial.KDTree.query_ball_point

Examples:

The centre, a corner and a point above the grid; the counts do not depend on the backend:

import warp as wp

import ordito as od

points, _ = od.creation.grid(count=(5, 5), extents=(4.0, 4.0))  # unit spacing, 25 points
queries = wp.array([[0.0, 0.0, 0.0], [-2.0, -2.0, 0.0], [0.0, 0.0, 5.0]], dtype=wp.vec3)
print(od.neighbors.query_ball_count(points, queries, 1.0).numpy().tolist())  # [5, 3, 0]
counts = od.neighbors.query_ball_count(points, queries, 1.5, backend="bvh")
print(counts.numpy().tolist())  # [9, 4, 0]
Source code in ordito/neighbors.py
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
def query_ball_count(
    points: wp.array[wp.vec3],
    queries: wp.array[wp.vec3],
    r: float,
    *,
    accelerator: wp.HashGrid | wp.Bvh | None = None,
    backend: QueryBackend | None = None,
    grid_bins: int | None = None,
    leaf_size: int = _BALL_LEAF_SIZE,
) -> wp.array[wp.int32]:
    """
    Count neighbors of each query within Euclidean distance ``r``.

    For each query center ``q``, returns how many entries ``p`` in ``points`` satisfy
    ``‖p - q‖₂ ≤ r``. This matches [`scipy.spatial.KDTree.query_ball_point`][] with ``p=2``,
    ``eps=0``, and ``return_length=True`` (exact search; only the spatial index differs).

    The narrow phase keeps points with ``float32`` Euclidean distance at most ``r`` whichever
    broad phase ran, so the count does not depend on ``backend``.

    Parameters
    ----------
    points
        ``(n,)`` data points.
    queries
        ``(m,)`` query centers.
    r
        Inclusion radius; cast to ``float32`` in kernels (non-negative).
    accelerator, backend, grid_bins, leaf_size
        As in [`query_ball`][ordito.neighbors.query_ball].

    Returns
    -------
    wp.array[wp.int32]
        ``(m,)`` device array whose ``k``-th element is the neighbor count for
        ``queries[k]``. If ``n == 0``, returns zeros.

    Raises
    ------
    ValueError
        If ``backend`` is neither name, or contradicts the type of ``accelerator``.
    RuntimeError
        If ``points``, ``queries`` and ``accelerator`` are not all on one device.

    See Also
    --------
    [`query_ball`][ordito.neighbors.query_ball]
    [`hashgrid_from_points`][ordito.neighbors.hashgrid_from_points]
    [`bvh_from_points`][ordito.neighbors.bvh_from_points]
    [`scipy.spatial.KDTree.query_ball_point`][]

    Examples
    --------
    The centre, a corner and a point above the grid; the counts do not depend on the backend:

    ```python
    import warp as wp

    import ordito as od

    points, _ = od.creation.grid(count=(5, 5), extents=(4.0, 4.0))  # unit spacing, 25 points
    queries = wp.array([[0.0, 0.0, 0.0], [-2.0, -2.0, 0.0], [0.0, 0.0, 5.0]], dtype=wp.vec3)
    print(od.neighbors.query_ball_count(points, queries, 1.0).numpy().tolist())  # [5, 3, 0]
    counts = od.neighbors.query_ball_count(points, queries, 1.5, backend="bvh")
    print(counts.numpy().tolist())  # [9, 4, 0]
    ```
    """
    require_same_device(points=points, queries=queries, accelerator=accelerator)
    kind, accelerator = _resolve_accelerator(accelerator, backend)
    device = points.device
    n = points.size
    m = queries.size
    if n == 0:
        return _launch.zeros(m, dtype=wp.int32, device=device)

    neighbor_counts = _launch.empty(m, dtype=wp.int32, device=device)
    if kind == "hashgrid":
        if accelerator is None:
            accelerator = hashgrid_from_points(points, r, grid_bins)
        walk = tiled_ball_walk(accelerator, m, device, kernel_neighbors.TILED_BALL_WALK_MAX_QUERIES)
        if walk is not None and r > 0.0:
            # Few queries: a block a query, its lanes counting the query's cells side by side.
            _launch.launch_tiled(
                kernel_neighbors.query_ball_count_tiled,
                dim=[m],
                inputs=[points, queries, accelerator.id, wp.float32(r), *walk],
                outputs=[neighbor_counts],
                device=device,
                block_dim=kernel_neighbors.TILED_BALL_WALK_BLOCK_DIM,
            )
            return neighbor_counts
        accel_selector = kernel_neighbors.ACCEL_HASHGRID
    else:
        if accelerator is None:
            accelerator = bvh_from_points(points, leaf_size)
        accel_selector = kernel_neighbors.ACCEL_BVH

    _launch.launch(
        kernel_neighbors.query_ball_count,
        dim=m,
        inputs=[points, queries, accel_selector, accelerator.id, wp.float32(r), neighbor_counts],
        device=device,
    )
    return neighbor_counts

query_ball_sum

query_ball_sum(
    points: array[vec3],
    queries: array[vec3],
    r: float,
    values: array[float32] | None = None,
    *,
    directions: array[vec3] | None = None,
    accelerator: HashGrid | Bvh | None = None,
    backend: QueryBackend | None = None,
    grid_bins: int | None = None,
    leaf_size: int = _BALL_LEAF_SIZE,
) -> tuple[wp.array[wp.float32], wp.array[wp.int32]]

Sum a per-neighbor term over each query's ball of radius r, with the neighbor count.

For each query center q, the neighbors are the points[j] with ‖points[j] - q‖₂ ≤ r, exactly those query_ball_count counts, and the sum is over one of two terms:

  • values[j], a value carried by each data point (pass values): the ball's total, or its mean once divided by the count;
  • (points[j] - q) · directions[k], each neighbor's offset from query k along that query's own direction (pass directions): with unit normals at the queries, how far the neighborhood sits above or below each query's tangent plane, in total.

It is query_ball_with_offsets followed by the term and a per-query sum, without storing a single neighbor pair: memory stays proportional to the queries whatever the neighborhoods hold.

Parameters:

Name Type Description Default
points array[vec3]

(n,) data points.

required
queries array[vec3]

(m,) query centers. A query that is itself one of points counts itself, at offset zero.

required
r float

Inclusion radius; cast to float32 in kernels (non-negative).

required
values array[float32] | None

(n,) the value of each data point. Exactly one of values and directions.

None
directions array[vec3] | None

(m,) a direction at each query; need not be unit length (the offset is scaled by its length). Exactly one of values and directions.

None
accelerator HashGrid | Bvh | None

As in query_ball.

None
backend HashGrid | Bvh | None

As in query_ball.

None
grid_bins HashGrid | Bvh | None

As in query_ball.

None
leaf_size HashGrid | Bvh | None

As in query_ball.

None

Returns:

Name Type Description
sums array[float32]

(m,) the term summed over each query's neighbors, in float32; 0 for a query with none.

counts array[int32]

(m,) the number of neighbors of each query, equal to query_ball_count's.

Raises:

Type Description
ValueError

If neither or both of values and directions are given, if values does not hold one entry per point or directions one per query, or if backend is neither name or contradicts the type of accelerator.

RuntimeError

If points, queries, values, directions and accelerator are not all on one device.

See Also

query_ball_count query_ball_with_offsets segment_sum

Notes

Each query's terms are added one after another in the accelerator's walk order, so a call repeats bit for bit over one accelerator; the two backends add in different orders and may differ by rounding.

Examples:

On a flat grid every neighbor lies in the plane, so the offsets along the normal sum to zero; lifting the centre point shows up at its neighbors:

import numpy as np
import warp as wp

import ordito as od

points, _ = od.creation.grid(count=(5, 5), extents=(4.0, 4.0))  # unit spacing, 25 points
normals = wp.array(np.tile([0.0, 0.0, 1.0], (25, 1)), dtype=wp.vec3)
sums, counts = od.neighbors.query_ball_sum(points, points, 1.2, directions=normals)
print(counts.numpy()[12], float(np.abs(sums.numpy()).max()))  # 5 0.0
lifted_np = points.numpy()
lifted_np[12, 2] = 0.5  # the centre point, whose four nearest neighbors are 7, 11, 13, 17
lifted = wp.array(lifted_np, dtype=wp.vec3)
sums, _ = od.neighbors.query_ball_sum(lifted, lifted, 1.2, directions=normals)
print(sums.numpy()[[0, 7, 12]].tolist())  # [0.0, 0.5, -2.0]
heights = wp.array(lifted_np[:, 2], dtype=wp.float32)
totals, _ = od.neighbors.query_ball_sum(lifted, lifted, 1.2, heights)
print(totals.numpy()[[0, 7]].tolist())  # [0.0, 0.5]
Source code in ordito/neighbors.py
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
def query_ball_sum(
    points: wp.array[wp.vec3],
    queries: wp.array[wp.vec3],
    r: float,
    values: wp.array[wp.float32] | None = None,
    *,
    directions: wp.array[wp.vec3] | None = None,
    accelerator: wp.HashGrid | wp.Bvh | None = None,
    backend: QueryBackend | None = None,
    grid_bins: int | None = None,
    leaf_size: int = _BALL_LEAF_SIZE,
) -> tuple[wp.array[wp.float32], wp.array[wp.int32]]:
    """
    Sum a per-neighbor term over each query's ball of radius ``r``, with the neighbor count.

    For each query center ``q``, the neighbors are the ``points[j]`` with ``‖points[j] - q‖₂ ≤ r``,
    exactly those [`query_ball_count`][ordito.neighbors.query_ball_count] counts, and the sum is
    over one of two terms:

    - ``values[j]``, a value carried by each data point (pass ``values``): the ball's total, or
      its mean once divided by the count;
    - ``(points[j] - q) · directions[k]``, each neighbor's offset from query ``k`` along that
      query's own direction (pass ``directions``): with unit normals at the queries, how far the
      neighborhood sits above or below each query's tangent plane, in total.

    It is [`query_ball_with_offsets`][ordito.neighbors.query_ball_with_offsets] followed by the
    term and a per-query sum, without storing a single neighbor pair: memory stays proportional
    to the queries whatever the neighborhoods hold.

    Parameters
    ----------
    points
        ``(n,)`` data points.
    queries
        ``(m,)`` query centers. A query that is itself one of ``points`` counts itself, at offset
        zero.
    r
        Inclusion radius; cast to ``float32`` in kernels (non-negative).
    values
        ``(n,)`` the value of each data point. Exactly one of ``values`` and ``directions``.
    directions
        ``(m,)`` a direction at each query; need not be unit length (the offset is scaled by its
        length). Exactly one of ``values`` and ``directions``.
    accelerator, backend, grid_bins, leaf_size
        As in [`query_ball`][ordito.neighbors.query_ball].

    Returns
    -------
    sums : wp.array[wp.float32]
        ``(m,)`` the term summed over each query's neighbors, in ``float32``; ``0`` for a query
        with none.
    counts : wp.array[wp.int32]
        ``(m,)`` the number of neighbors of each query, equal to
        [`query_ball_count`][ordito.neighbors.query_ball_count]'s.

    Raises
    ------
    ValueError
        If neither or both of ``values`` and ``directions`` are given, if ``values`` does not
        hold one entry per point or ``directions`` one per query, or if ``backend`` is neither
        name or contradicts the type of ``accelerator``.
    RuntimeError
        If ``points``, ``queries``, ``values``, ``directions`` and ``accelerator`` are not all on
        one device.

    See Also
    --------
    [`query_ball_count`][ordito.neighbors.query_ball_count]
    [`query_ball_with_offsets`][ordito.neighbors.query_ball_with_offsets]
    [`segment_sum`][ordito.reduce.segment_sum]

    Notes
    -----
    Each query's terms are added one after another in the accelerator's walk order, so a call
    repeats bit for bit over one accelerator; the two backends add in different orders and may
    differ by rounding.

    Examples
    --------
    On a flat grid every neighbor lies in the plane, so the offsets along the normal sum to zero;
    lifting the centre point shows up at its neighbors:

    ```python
    import numpy as np
    import warp as wp

    import ordito as od

    points, _ = od.creation.grid(count=(5, 5), extents=(4.0, 4.0))  # unit spacing, 25 points
    normals = wp.array(np.tile([0.0, 0.0, 1.0], (25, 1)), dtype=wp.vec3)
    sums, counts = od.neighbors.query_ball_sum(points, points, 1.2, directions=normals)
    print(counts.numpy()[12], float(np.abs(sums.numpy()).max()))  # 5 0.0
    lifted_np = points.numpy()
    lifted_np[12, 2] = 0.5  # the centre point, whose four nearest neighbors are 7, 11, 13, 17
    lifted = wp.array(lifted_np, dtype=wp.vec3)
    sums, _ = od.neighbors.query_ball_sum(lifted, lifted, 1.2, directions=normals)
    print(sums.numpy()[[0, 7, 12]].tolist())  # [0.0, 0.5, -2.0]
    heights = wp.array(lifted_np[:, 2], dtype=wp.float32)
    totals, _ = od.neighbors.query_ball_sum(lifted, lifted, 1.2, heights)
    print(totals.numpy()[[0, 7]].tolist())  # [0.0, 0.5]
    ```
    """
    require_same_device(
        points=points,
        queries=queries,
        values=values,
        directions=directions,
        accelerator=accelerator,
    )
    if (values is None) == (directions is None):
        raise ValueError("query_ball_sum takes exactly one of values and directions.")
    if values is not None and values.size != points.size:
        raise ValueError(
            f"values must hold one entry per point ({points.size}), got {values.size}."
        )
    if directions is not None and directions.size != queries.size:
        raise ValueError(
            f"directions must hold one entry per query ({queries.size}), got {directions.size}."
        )
    kind, accelerator = _resolve_accelerator(accelerator, backend)
    device = points.device
    m = queries.size
    if points.size == 0:
        return (
            _launch.zeros(m, dtype=wp.float32, device=device),
            _launch.zeros(m, dtype=wp.int32, device=device),
        )
    sums = _launch.empty(m, dtype=wp.float32, device=device)
    counts = _launch.empty(m, dtype=wp.int32, device=device)
    if m == 0:
        return sums, counts
    if kind == "hashgrid":
        if accelerator is None:
            accelerator = hashgrid_from_points(points, r, grid_bins)
        accel_selector = kernel_neighbors.ACCEL_HASHGRID
    else:
        if accelerator is None:
            accelerator = bvh_from_points(points, leaf_size)
        accel_selector = kernel_neighbors.ACCEL_BVH
    if values is not None:
        term = kernel_neighbors.BALL_TERM_VALUES
        values_in, directions_in = values, _launch.empty(0, dtype=wp.vec3, device=device)
    else:
        assert directions is not None
        term = kernel_neighbors.BALL_TERM_OFFSET
        values_in, directions_in = _launch.empty(0, dtype=wp.float32, device=device), directions
    _launch.launch(
        kernel_neighbors.query_ball_sum,
        dim=m,
        inputs=[
            points,
            queries,
            accel_selector,
            accelerator.id,
            wp.float32(r),
            term,
            values_in,
            directions_in,
        ],
        outputs=[sums, counts],
        device=device,
    )
    return sums, counts

query_ball_with_offsets

query_ball_with_offsets(
    points: array[vec3],
    queries: array[vec3] | vec3,
    r: float,
    *,
    accelerator: HashGrid | Bvh | None = None,
    backend: QueryBackend | None = None,
    grid_bins: int | None = None,
    leaf_size: int = _BALL_LEAF_SIZE,
    return_sorted: bool = False,
) -> tuple[
    wp.array[wp.int32],
    wp.array[wp.float32],
    wp.array[wp.int32],
]

Low-level ball query: neighbors in one concatenated pair plus per-query offsets.

Same geometry as query_ball (broad phase out to r, float32 test ‖points[i] - q‖₂ ≤ r). Semantics match scipy.spatial.KDTree.query_ball_point with p=2 and eps=0.

Prefer query_ball for a Python list of one array per query; use this when you want a single flat buffer on device (e.g. fused downstream kernels) and CSR-style boundaries without cloning each segment.

Parameters:

Name Type Description Default
points array[vec3]

(n,) data points.

required
queries array[vec3] | vec3

(m,) query centers as wp.array[wp.vec3], or a single wp.vec3 (treated as one query).

required
r float

Inclusion radius; cast to float32 in kernels (non-negative).

required
accelerator HashGrid | Bvh | None

As in query_ball.

None
backend HashGrid | Bvh | None

As in query_ball.

None
grid_bins HashGrid | Bvh | None

As in query_ball.

None
leaf_size HashGrid | Bvh | None

As in query_ball.

None
return_sorted bool

If True, neighbors within each query are ordered by increasing distance.

False

Returns:

Type Description
(neighbor_indices_flat, neighbor_distances_flat, offsets)

(n_total,), (n_total,) and (m + 1,) arrays, with m = queries.shape[0] after any wp.vec3 wrap and n_total the total neighbor count.

offsets is the total-terminated prefix sum of per-query neighbor counts: query k owns neighbor_indices_flat[offsets[k] : offsets[k + 1]], and offsets[m] is neighbor_indices_flat.shape[0] (the total neighbor count).

neighbor_indices_flat and neighbor_distances_flat have that total length and list point indices and distances ‖points[i] - q‖₂ in parallel. Empty points still returns zero offsets; empty neighbor sets yield length-0 flat arrays and zero offsets.

Raises:

Type Description
ValueError

If backend is neither name, or contradicts the type of accelerator.

RuntimeError

If points, queries and accelerator are not all on one device.

Notes

SciPy may sort indices when return_sorted is left default on multi-point queries; here sorting only occurs when return_sorted=True, and sorts by distance, not by index. Ball boundaries use float32 arithmetic; extremely tight radii near representable limits may disagree slightly with pure float64 SciPy runs.

See Also

query_ball query_ball_count hashgrid_from_points bvh_from_points scipy.spatial.KDTree.query_ball_point

Examples:

The centre's five neighbours come first, then the corner's three:

import warp as wp

import ordito as od

points, _ = od.creation.grid(count=(5, 5), extents=(4.0, 4.0))  # unit spacing, 25 points
queries = wp.array([[0.0, 0.0, 0.0], [-2.0, -2.0, 0.0]], dtype=wp.vec3)
indices, distances, offsets = od.neighbors.query_ball_with_offsets(
    points, queries, 1.0, return_sorted=True
)
print(offsets.numpy().tolist())  # [0, 5, 8]
print(distances.numpy()[5:8].tolist())  # [0.0, 1.0, 1.0]
Source code in ordito/neighbors.py
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
def query_ball_with_offsets(
    points: wp.array[wp.vec3],
    queries: wp.array[wp.vec3] | wp.vec3,
    r: float,
    *,
    accelerator: wp.HashGrid | wp.Bvh | None = None,
    backend: QueryBackend | None = None,
    grid_bins: int | None = None,
    leaf_size: int = _BALL_LEAF_SIZE,
    return_sorted: bool = False,
) -> tuple[wp.array[wp.int32], wp.array[wp.float32], wp.array[wp.int32]]:
    """
    Low-level ball query: neighbors in one concatenated pair plus per-query offsets.

    Same geometry as [`query_ball`][ordito.neighbors.query_ball] (broad phase out to ``r``,
    ``float32`` test ``‖points[i] - q‖₂ ≤ r``). Semantics match
    [`scipy.spatial.KDTree.query_ball_point`][] with ``p=2`` and ``eps=0``.

    Prefer [`query_ball`][ordito.neighbors.query_ball] for a Python list of one array per query;
    use this when you want a single flat buffer on device (e.g. fused downstream kernels) and
    CSR-style boundaries without cloning each segment.

    Parameters
    ----------
    points
        ``(n,)`` data points.
    queries
        ``(m,)`` query centers as ``wp.array[wp.vec3]``, or a single ``wp.vec3`` (treated as one
        query).
    r
        Inclusion radius; cast to ``float32`` in kernels (non-negative).
    accelerator, backend, grid_bins, leaf_size
        As in [`query_ball`][ordito.neighbors.query_ball].
    return_sorted
        If ``True``, neighbors within each query are ordered by increasing distance.

    Returns
    -------
    neighbor_indices_flat, neighbor_distances_flat, offsets
        ``(n_total,)``, ``(n_total,)`` and ``(m + 1,)`` arrays, with ``m = queries.shape[0]`` after
        any ``wp.vec3`` wrap and ``n_total`` the total neighbor count.

        ``offsets`` is the total-terminated prefix sum of per-query
        neighbor counts: query ``k`` owns ``neighbor_indices_flat[offsets[k] : offsets[k + 1]]``,
        and ``offsets[m]`` is ``neighbor_indices_flat.shape[0]`` (the total neighbor count).

        ``neighbor_indices_flat`` and ``neighbor_distances_flat`` have that total length
        and list point indices and distances ``‖points[i] - q‖₂`` in parallel. Empty
        ``points`` still returns zero ``offsets``; empty neighbor sets yield
        length-0 flat arrays and zero ``offsets``.

    Raises
    ------
    ValueError
        If ``backend`` is neither name, or contradicts the type of ``accelerator``.
    RuntimeError
        If ``points``, ``queries`` and ``accelerator`` are not all on one device.

    Notes
    -----
    SciPy may sort indices when ``return_sorted`` is left default on multi-point queries; here
    sorting only occurs when ``return_sorted=True``, and sorts by distance, not by index. Ball
    boundaries use ``float32`` arithmetic; extremely tight radii near representable limits may
    disagree slightly with pure ``float64`` SciPy runs.

    See Also
    --------
    [`query_ball`][ordito.neighbors.query_ball]
    [`query_ball_count`][ordito.neighbors.query_ball_count]
    [`hashgrid_from_points`][ordito.neighbors.hashgrid_from_points]
    [`bvh_from_points`][ordito.neighbors.bvh_from_points]
    [`scipy.spatial.KDTree.query_ball_point`][]

    Examples
    --------
    The centre's five neighbours come first, then the corner's three:

    ```python
    import warp as wp

    import ordito as od

    points, _ = od.creation.grid(count=(5, 5), extents=(4.0, 4.0))  # unit spacing, 25 points
    queries = wp.array([[0.0, 0.0, 0.0], [-2.0, -2.0, 0.0]], dtype=wp.vec3)
    indices, distances, offsets = od.neighbors.query_ball_with_offsets(
        points, queries, 1.0, return_sorted=True
    )
    print(offsets.numpy().tolist())  # [0, 5, 8]
    print(distances.numpy()[5:8].tolist())  # [0.0, 1.0, 1.0]
    ```
    """
    require_same_device(points=points, queries=queries, accelerator=accelerator)
    indices, distances, offsets, _ = _ball_query(
        points, queries, r, accelerator, backend, grid_bins, leaf_size, return_sorted, False
    )
    return indices, distances, offsets

knn_initial_radius

knn_initial_radius(
    points: array[vec3],
    k: int,
    *,
    bounds: tuple[vec3, vec3] | None = None,
) -> float

Radius at which a k-nearest search is expected to succeed on the first try.

Inverts a uniform-density model of points: the smallest ball expected to hold k of n points is the one whose volume is k / n of the bounding box's. This is the default initial_radius of query_nearest, which deepens from it until each row certifies itself, so the value affects speed only and never the result.

A cloud that is flat or collinear has a (near-)zero box volume, which the 3-D formula would invert into a useless radius, so the effective dimension d is taken to be the number of axes whose extent is non-negligible against the largest, and the matching formula is used: d = 3 gives (3 f V / 4pi)^(1/3), d = 2 gives (f A / pi)^(1/2) and d = 1 gives f L / 2, with fill fraction f = k / n.

Parameters:

Name Type Description Default
points array[vec3]

(n,) data points.

required
k int

Number of neighbors the search will ask for; must be >= 1.

required
bounds tuple[vec3, vec3] | None

Optional (min_bound, max_bound) from aabb. Pass it to reuse a reduction you already ran; otherwise it is computed here (one device reduction plus one readback). Trusted, not validated — but only the estimate depends on it, so a wrong box costs speed and not correctness, unlike the identically named argument of query_nearest.

None

Returns:

Type Description
float

The estimated radius, or math.inf when no finite estimate is meaningful — n == 0, k >= n (every point is a neighbor) or a degenerate box (all points coincident). The query kernels read math.inf as "one complete scan", which is the right answer in each of those cases.

See Also

query_nearest aabb

Examples:

The grid is flat, so the 2-D formula applies: sqrt((4 / 25) * 16 / pi). Asking for every point gives inf, one complete scan:

import ordito as od

points, _ = od.creation.grid(count=(5, 5), extents=(4.0, 4.0))  # unit spacing, 25 points
print(f"{od.neighbors.knn_initial_radius(points, 4):.3f}")  # 0.903
print(od.neighbors.knn_initial_radius(points, 25))  # inf
Source code in ordito/neighbors.py
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
def knn_initial_radius(
    points: wp.array[wp.vec3], k: int, *, bounds: tuple[wp.vec3, wp.vec3] | None = None
) -> float:
    """
    Radius at which a ``k``-nearest search is expected to succeed on the first try.

    Inverts a uniform-density model of ``points``: the smallest ball expected to hold ``k`` of
    ``n`` points is the one whose volume is ``k / n`` of the bounding box's. This is the default
    ``initial_radius`` of [`query_nearest`][ordito.neighbors.query_nearest], which deepens from it
    until each row certifies itself, so the value affects **speed only** and never the result.

    A cloud that is flat or collinear has a (near-)zero box volume, which the 3-D formula would
    invert into a useless radius, so the effective dimension ``d`` is taken to be the number of
    axes whose extent is non-negligible against the largest, and the matching formula is used:
    ``d = 3`` gives ``(3 f V / 4pi)^(1/3)``, ``d = 2`` gives ``(f A / pi)^(1/2)`` and ``d = 1``
    gives ``f L / 2``, with fill fraction ``f = k / n``.

    Parameters
    ----------
    points
        ``(n,)`` data points.
    k
        Number of neighbors the search will ask for; must be ``>= 1``.
    bounds
        Optional ``(min_bound, max_bound)`` from
        [`aabb`][ordito.bounds.aabb]. Pass it to reuse a reduction you already ran;
        otherwise it is computed here (one device reduction plus one readback). Trusted, not
        validated — but only the estimate depends on it, so a wrong box costs speed and not
        correctness, unlike the identically named argument of
        [`query_nearest`][ordito.neighbors.query_nearest].

    Returns
    -------
    float
        The estimated radius, or ``math.inf`` when no finite estimate is meaningful — ``n == 0``,
        ``k >= n`` (every point is a neighbor) or a degenerate box (all points coincident). The
        query kernels read ``math.inf`` as "one complete scan", which is the right answer in each
        of those cases.

    See Also
    --------
    [`query_nearest`][ordito.neighbors.query_nearest]
    [`aabb`][ordito.bounds.aabb]

    Examples
    --------
    The grid is flat, so the 2-D formula applies: ``sqrt((4 / 25) * 16 / pi)``. Asking for every
    point gives ``inf``, one complete scan:

    ```python
    import ordito as od

    points, _ = od.creation.grid(count=(5, 5), extents=(4.0, 4.0))  # unit spacing, 25 points
    print(f"{od.neighbors.knn_initial_radius(points, 4):.3f}")  # 0.903
    print(od.neighbors.knn_initial_radius(points, 25))  # inf
    ```
    """
    n = points.size
    if n == 0 or k >= n:
        return math.inf

    if bounds is None:
        bounds = od.bounds.aabb(points)
    lower, upper = (odt.vec3_floats(corner) for corner in bounds)
    extents = sorted((upper[axis] - lower[axis] for axis in range(3)), reverse=True)
    if extents[0] <= 0.0:
        return math.inf

    fill = k / n
    dimension = sum(extent > _FLAT_AXIS_FRACTION * extents[0] for extent in extents)
    if dimension == 3:
        volume = extents[0] * extents[1] * extents[2]
        return (3.0 * fill * volume / (4.0 * math.pi)) ** (1.0 / 3.0)
    if dimension == 2:
        return math.sqrt(fill * extents[0] * extents[1] / math.pi)
    return 0.5 * fill * extents[0]

query_nearest

query_nearest(
    points: array[vec3],
    queries: vec3,
    k: int,
    *,
    accelerator: HashGrid | Bvh | None = ...,
    backend: QueryBackend | None = ...,
    max_radius: float | array[float32] = ...,
    grid_bins: int | None = ...,
    leaf_size: int | None = ...,
    initial_radius: float | None = ...,
    bounds: tuple[vec3, vec3] | None = ...,
) -> tuple[odt.Array1dInt32, odt.Array1dFloat32]
query_nearest(
    points: array[vec3],
    queries: array[vec3] | vec3,
    k: Literal[1] = 1,
    *,
    accelerator: HashGrid | Bvh | None = ...,
    backend: QueryBackend | None = ...,
    max_radius: float | array[float32] = ...,
    grid_bins: int | None = ...,
    leaf_size: int | None = ...,
    initial_radius: float | None = ...,
    bounds: tuple[vec3, vec3] | None = ...,
) -> tuple[odt.Array1dInt32, odt.Array1dFloat32]
query_nearest(
    points: array[vec3],
    queries: array[vec3],
    k: int,
    *,
    accelerator: HashGrid | Bvh | None = ...,
    backend: QueryBackend | None = ...,
    max_radius: float | array[float32] = ...,
    grid_bins: int | None = ...,
    leaf_size: int | None = ...,
    initial_radius: float | None = ...,
    bounds: tuple[vec3, vec3] | None = ...,
) -> tuple[odt.Array2dInt32, odt.Array2dFloat32]
query_nearest(
    points: array[vec3],
    queries: array[vec3] | vec3,
    k: int = 1,
    *,
    accelerator: HashGrid | Bvh | None = None,
    backend: QueryBackend | None = None,
    max_radius: float | array[float32] = math.inf,
    grid_bins: int | None = None,
    leaf_size: int | None = None,
    initial_radius: float | None = None,
    bounds: tuple[vec3, vec3] | None = None,
) -> tuple[
    odt.Array2dInt32 | odt.Array1dInt32,
    odt.Array2dFloat32 | odt.Array1dFloat32,
]

For each query center, find the k nearest data points.

Iterative deepening: each query grows a search radius from initial_radius until its k-th neighbour is closer than the radius, which certifies the row -- so the answer is exact and does not depend on backend. The candidate row is register-resident for k <= 64.

Which backend to use

With neither backend nor accelerator given, k == 1 takes "bvh"'s nearest-point descent on a cloud of up to about a million points (CUDA) or sixteen thousand (CPU), unless initial_radius or grid_bins is given; everything else takes "hashgrid".

"hashgrid" is the faster broad phase for k > 1 when the query scale matches the cloud's density, because initial_radius sets the cell width: the walk visits (2 ceil(r / cell) + 1) ** 3 cells, so a radius f times too large costs f ** 3. A row the walk cannot certify within a few cells is finished by a tree over the cloud rather than by a scan of every point. A row whose walk found points goes to the BVH's radius search, started where the walk stopped; a row whose first walks found nothing goes to a nearest-point descent of a point tree, whose cost does not grow with how far the query is from the cloud -- the answer itself at k == 1, and the radius search's starting distance above it. So a query beside a sparse patch of the cloud, or far from it, costs a tree search. Clouds under 8192 points, and k above 64, finish such rows with an exact linear scan of the cloud instead.

"bvh" has no cell width to get wrong, so it is the one to reach for when the query scale is far from the cloud's own density and no initial_radius can say it. Its own cost grows with k faster than the grid's. At k == 1 it is not a radius search at all but a nearest-point descent of the tree, whose cost does not grow with the queries' distance from the cloud.

Both are exact; this is a cost choice only. Reuse the structure across calls by passing it as accelerator when several queries share one cloud.

Parameters:

Name Type Description Default
points array[vec3]

(n,) data points.

required
queries array[vec3] | vec3

(m,) query centers as wp.array[wp.vec3], or a single wp.vec3.

required
k int

Number of neighbours per query, >= 1.

1
accelerator HashGrid | Bvh | None

A prebuilt warp.HashGrid or warp.Bvh over points, to reuse across queries. It selects the backend by its own type, so backend is redundant when this is given and raises if it names the other one. A hash grid passed here keeps its own cell_width rather than one derived from initial_radius.

None
backend QueryBackend | None

"hashgrid" or "bvh", when accelerator is None; None (the default) chooses by k and the cloud's size, as the note above says.

None
max_radius float | array[float32]

Stop deepening past this distance and leave the remaining slots unfilled (index -1, distance inf). Defaults to unbounded. A (m,) float32 array gives each query its own ((1,) for a single wp.vec3 query); a negative entry fills nothing in its row. The rows inside a smaller radius are those a larger one finds, cut there.

inf
grid_bins int | None

Grid resolution when building a hash grid; None sizes it from the point count, as in hashgrid_from_points. Ignored under backend="bvh" and whenever accelerator is given.

None
leaf_size int | None

Maximum primitives per leaf when building a BVH; None picks it from the point count (larger leaves for larger clouds, where the walk is faster with them). Ignored whenever accelerator is given and at k == 1 under backend="bvh", where the tree has one point a leaf. The "hashgrid" backend builds a BVH only to finish the rows its cell walk cannot certify.

None
initial_radius float | None

First search radius. Defaults to knn_initial_radius, which estimates it from the cloud's density -- so pass it explicitly when the queries are at a different scale, since under "hashgrid" this also sets the cell width. With the default, "hashgrid" and a million queries or more, the first walk starts instead at the fraction of the estimate that a sample of the queries needs, which is smaller on a surface sample; the cell width stays the estimate's. Either way the value affects speed only.

None
bounds tuple[vec3, vec3] | None

(min_bound, max_bound) of points, to skip ordito.bounds.aabb and its readback. Trusted, not validated, and not only a shortcut: it also fixes the per-query radius at which a scan is provably complete, so a box that does not contain points can end the search early and leave slots unfilled (-1 and inf) rather than merely running slower. Pass the real bounding box, or leave it None. Neither this nor initial_radius is read by the k == 1 BVH-backend query, which has no radius to deepen.

None

Returns:

Type Description
(neighbor_indices, neighbor_distances)

(m, k) indices into points and (m, k) distances, each row sorted by increasing distance. A slot no neighbour was found for holds -1 and inf.

The trailing axis collapses when there is only one of it, as scipy.spatial.KDTree.query does: at k == 1 the two are (m,), and for a single wp.vec3 query they are (k,). The rank depends only on k and the form of queries, never on whether an answer was found — an empty points or an empty queries returns the same rank a populated one would.

Raises:

Type Description
TypeError

If max_radius is an array but not float32.

ValueError

If k < 1, max_radius < 0, initial_radius < 0, backend is neither name or contradicts the type of accelerator, or max_radius is an array but not (m,).

RuntimeError

If points, queries, accelerator and a max_radius array are not all on one device.

See Also

knn_initial_radius The default first radius, and the one parameter worth passing by hand. query_ball A fixed radius rather than a fixed count. nearest_neighbor_distance The k=2 self-query, which is the cloud's spacing. hashgrid_from_points bvh_from_points scipy.spatial.KDTree.query

Examples:

At k == 1 the result is (m,); the grid's centre is index 12 and its far corner 24:

import warp as wp

import ordito as od

points, _ = od.creation.grid(count=(5, 5), extents=(4.0, 4.0))  # unit spacing, 25 points
queries = wp.array([[0.1, 0.2, 0.0], [2.0, 2.0, 1.0]], dtype=wp.vec3)
indices, distances = od.neighbors.query_nearest(points, queries)
print(indices.numpy().tolist())  # [12, 24]
print(f"{distances.numpy()[0]:.4f}")  # 0.2236

A larger k adds a trailing axis, and max_radius leaves the slots it cannot fill at -1 and inf:

import warp as wp

import ordito as od

points, _ = od.creation.grid(count=(5, 5), extents=(4.0, 4.0))  # unit spacing, 25 points
queries = wp.array([[0.1, 0.2, 0.0], [2.0, 2.0, 1.0]], dtype=wp.vec3)
indices, distances = od.neighbors.query_nearest(points, queries, k=3, max_radius=1.2)
print(indices.shape)  # (2, 3)
print(distances.numpy()[1].tolist())  # [1.0, inf, inf]
Source code in ordito/neighbors.py
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
def query_nearest(
    points: wp.array[wp.vec3],
    queries: wp.array[wp.vec3] | wp.vec3,
    k: int = 1,
    *,
    accelerator: wp.HashGrid | wp.Bvh | None = None,
    backend: QueryBackend | None = None,
    max_radius: float | wp.array[wp.float32] = math.inf,
    grid_bins: int | None = None,
    leaf_size: int | None = None,
    initial_radius: float | None = None,
    bounds: tuple[wp.vec3, wp.vec3] | None = None,
) -> tuple[odt.Array2dInt32 | odt.Array1dInt32, odt.Array2dFloat32 | odt.Array1dFloat32]:
    """
    For each query center, find the ``k`` nearest data points.

    Iterative deepening: each query grows a search radius from ``initial_radius`` until its ``k``-th
    neighbour is closer than the radius, which certifies the row -- so the answer is exact and does
    not depend on ``backend``. The candidate row is register-resident for ``k <= 64``.

    !!! note "Which backend to use"
        With neither ``backend`` nor ``accelerator`` given, ``k == 1`` takes ``"bvh"``'s
        nearest-point descent on a cloud of up to about a million points (CUDA) or sixteen
        thousand (CPU), unless ``initial_radius`` or ``grid_bins`` is given; everything else takes
        ``"hashgrid"``.

        ``"hashgrid"`` is the faster broad phase for ``k > 1`` when the query scale matches the
        cloud's density, because ``initial_radius`` sets the cell width: the walk visits
        ``(2 ceil(r / cell) + 1) ** 3`` cells, so a radius **f** times too large costs ``f ** 3``.
        A row the walk cannot certify within a few cells is finished by a tree over the cloud
        rather than by a scan of every point. A row whose walk found points goes to the BVH's
        radius search, started where the walk stopped; a row whose first walks found nothing goes
        to a nearest-point descent of a point tree, whose cost does not grow with how far the query
        is from the cloud -- the answer itself at ``k == 1``, and the radius search's starting
        distance above it. So a query beside a sparse
        patch of the cloud, or far from it, costs a tree search. Clouds under 8192 points, and
        ``k`` above 64, finish such rows with an exact linear scan of the cloud instead.

        ``"bvh"`` has no cell width to get wrong, so it is the one to reach for when the query scale
        is far from the cloud's own density and no ``initial_radius`` can say it. Its own cost
        grows with ``k`` faster than the grid's. At ``k == 1`` it is not a radius search at all but
        a nearest-point descent of the tree, whose cost does not grow with the queries' distance
        from the cloud.

        Both are exact; this is a cost choice only. Reuse the structure across calls by passing it
        as ``accelerator`` when several queries share one cloud.

    Parameters
    ----------
    points
        ``(n,)`` data points.
    queries
        ``(m,)`` query centers as ``wp.array[wp.vec3]``, or a single ``wp.vec3``.
    k
        Number of neighbours per query, ``>= 1``.
    accelerator
        A prebuilt ``warp.HashGrid`` or ``warp.Bvh`` over ``points``, to reuse across queries. It
        selects the backend by its own type, so ``backend`` is redundant when this is given and
        raises if it names the other one. A hash grid passed here keeps its own ``cell_width``
        rather than one derived from ``initial_radius``.
    backend
        ``"hashgrid"`` or ``"bvh"``, when ``accelerator`` is ``None``; ``None`` (the default)
        chooses by ``k`` and the cloud's size, as the note above says.
    max_radius
        Stop deepening past this distance and leave the remaining slots unfilled (index ``-1``,
        distance ``inf``). Defaults to unbounded. A ``(m,)`` ``float32`` array gives each query
        its own (``(1,)`` for a single ``wp.vec3`` query); a negative entry fills nothing in its
        row. The rows inside a smaller radius are those a larger one finds, cut there.
    grid_bins
        Grid resolution when building a hash grid; ``None`` sizes it from the point count, as in
        [`hashgrid_from_points`][ordito.neighbors.hashgrid_from_points]. Ignored under
        ``backend="bvh"`` and whenever ``accelerator`` is given.
    leaf_size
        Maximum primitives per leaf when building a BVH; ``None`` picks it from the point count
        (larger leaves for larger clouds, where the walk is faster with them). Ignored whenever
        ``accelerator`` is given and at ``k == 1`` under ``backend="bvh"``, where the tree has one
        point a leaf. The ``"hashgrid"`` backend builds a BVH only to finish the rows its cell walk
        cannot certify.
    initial_radius
        First search radius. Defaults to
        [`knn_initial_radius`][ordito.neighbors.knn_initial_radius], which estimates it from the
        *cloud's* density -- so pass it explicitly when the queries are at a different scale, since
        under ``"hashgrid"`` this also sets the cell width. With the default, ``"hashgrid"`` and
        a million queries or more, the first walk starts instead at the fraction of the estimate
        that a sample of the queries needs, which is smaller on a surface sample; the cell width
        stays the estimate's. Either way the value affects speed only.
    bounds
        ``(min_bound, max_bound)`` of ``points``, to skip
        [`ordito.bounds.aabb`][ordito.bounds.aabb] and its readback. **Trusted, not validated, and
        not only a shortcut**: it also fixes the per-query radius at which a scan is provably
        complete, so a box that does not contain ``points`` can end the search early and leave
        slots unfilled (``-1`` and ``inf``) rather than merely running slower. Pass the real
        bounding box, or leave it ``None``. Neither this nor ``initial_radius`` is read by the
        ``k == 1`` BVH-backend query, which has no radius to deepen.

    Returns
    -------
    neighbor_indices, neighbor_distances
        ``(m, k)`` indices into ``points`` and ``(m, k)`` distances, each row sorted by increasing
        distance. A slot no neighbour was found for holds ``-1`` and
        ``inf``.

        The trailing axis collapses when there is only one of it, as
        [`scipy.spatial.KDTree.query`][] does: at ``k == 1`` the two are ``(m,)``, and for a single
        ``wp.vec3`` query they are ``(k,)``. The rank depends only on
        ``k`` and the form of ``queries``, never on whether an answer was found — an empty
        ``points`` or an empty ``queries`` returns the same rank a populated one would.

    Raises
    ------
    TypeError
        If ``max_radius`` is an array but not ``float32``.
    ValueError
        If ``k < 1``, ``max_radius < 0``, ``initial_radius < 0``, ``backend`` is neither name or
        contradicts the type of ``accelerator``, or ``max_radius`` is an array but not ``(m,)``.
    RuntimeError
        If ``points``, ``queries``, ``accelerator`` and a ``max_radius`` array are not all on one
        device.

    See Also
    --------
    [`knn_initial_radius`][ordito.neighbors.knn_initial_radius]
        The default first radius, and the one parameter worth passing by hand.
    [`query_ball`][ordito.neighbors.query_ball]
        A fixed radius rather than a fixed count.
    [`nearest_neighbor_distance`][ordito.neighbors.nearest_neighbor_distance]
        The ``k=2`` self-query, which is the cloud's spacing.
    [`hashgrid_from_points`][ordito.neighbors.hashgrid_from_points]
    [`bvh_from_points`][ordito.neighbors.bvh_from_points]
    [`scipy.spatial.KDTree.query`][]

    Examples
    --------
    At ``k == 1`` the result is ``(m,)``; the grid's centre is index 12 and its far corner 24:

    ```python
    import warp as wp

    import ordito as od

    points, _ = od.creation.grid(count=(5, 5), extents=(4.0, 4.0))  # unit spacing, 25 points
    queries = wp.array([[0.1, 0.2, 0.0], [2.0, 2.0, 1.0]], dtype=wp.vec3)
    indices, distances = od.neighbors.query_nearest(points, queries)
    print(indices.numpy().tolist())  # [12, 24]
    print(f"{distances.numpy()[0]:.4f}")  # 0.2236
    ```

    A larger ``k`` adds a trailing axis, and ``max_radius`` leaves the slots it cannot fill at
    ``-1`` and ``inf``:

    ```python
    import warp as wp

    import ordito as od

    points, _ = od.creation.grid(count=(5, 5), extents=(4.0, 4.0))  # unit spacing, 25 points
    queries = wp.array([[0.1, 0.2, 0.0], [2.0, 2.0, 1.0]], dtype=wp.vec3)
    indices, distances = od.neighbors.query_nearest(points, queries, k=3, max_radius=1.2)
    print(indices.shape)  # (2, 3)
    print(distances.numpy()[1].tolist())  # [1.0, inf, inf]
    ```
    """
    # Every kernel takes the radius as a bound and, per row, the smaller of it and the row's entry
    # (``kernel_neighbors.row_max_radius``); ``None`` is the empty array that leaves the bound.
    row_radii = max_radius if isinstance(max_radius, wp.array) else None
    bound = math.inf if isinstance(max_radius, wp.array) else float(max_radius)
    require_same_device(
        points=points, queries=queries, accelerator=accelerator, max_radius=row_radii
    )
    kind, resolved = _resolve_accelerator(accelerator, backend)
    _validate_nearest(k, bound, initial_radius)
    if (
        k == 1
        and backend is None
        and accelerator is None
        and initial_radius is None
        and grid_bins is None
        and _nearest_descends(points, _NEAREST_DESCENT_MAX_POINTS_CPU)
    ):
        # With nothing chosen for the grid, one nearest point is the point tree's descent below
        # the size where its build is the call (``_DESCENT_MAX_POINTS_CUDA``).
        kind = "bvh"

    device = points.device
    single_query = not isinstance(queries, wp.array)
    if single_query:
        queries = _launch.array([queries], dtype=wp.vec3, device=device)

    m = queries.size
    n = points.size
    if row_radii is not None:
        if row_radii.dtype != wp.float32:
            raise TypeError(f"a max_radius array must be float32, got {row_radii.dtype}")
        if row_radii.ndim != 1 or row_radii.size != m:
            raise ValueError(f"a max_radius array must be ({m},), got {row_radii.shape}")

    # Both degenerate inputs answer "every slot unfilled" over `(m, k)`, which is empty of its own
    # accord when there are no queries -- and both must go through the same shaping as the general
    # path, or `k == 1` comes back rank-2 here and rank-1 everywhere else.
    if m == 0 or n == 0:
        return _empty_nearest(m, k, single_query, device)

    # ``wp.empty``, not ``wp.full``: every row is written in full by the kernel, so pre-filling
    # here would be two wasted launches.
    neighbor_indices = odt.empty_2d((m, k), wp.int32, device=device)
    neighbor_distances = odt.empty_2d((m, k), wp.float32, device=device)
    if kind == "bvh" and k == 1:
        # One nearest point is a nearest-point descent of the tree: it needs no radius to deepen,
        # so neither the bounding box nor the density estimate (two reductions and their
        # readbacks) is computed, and a query far off the cloud costs what an on-surface one does.
        # The distances are the radius search's to the bit. One point a leaf when the call builds
        # the tree; a caller's tree is searched with whatever leaves it has.
        # The order is chosen before the tree is built, so the read it may take waits on no build.
        order = search_order(queries)
        tree = resolved if resolved is not None else bvh_from_points(points, leaf_size=1)
        _launch.launch(
            kernel_neighbors.query_nearest_via_bvh,
            dim=m,
            inputs=[tree.id, points, queries, wp.float32(bound), row_radii, order],
            outputs=[neighbor_indices, neighbor_distances],
            device=device,
            block_dim=kernel_neighbors.descent_block_dim(m, device),
        )
        return _shape_nearest(neighbor_indices, neighbor_distances, k, single_query)

    # The cell walks and the ball searches take scattered queries in a Hilbert order too, and from
    # fewer queries than the descent (``_KNN_ORDER_MIN_QUERIES``); the order's test rides on the
    # box's readback when the call reads the box.
    if bounds is None:
        bounds, order = bounds_and_search_order(
            points, queries, _KNN_ORDER_MIN_QUERIES, _KNN_ORDER_ALWAYS_QUERIES_CUDA
        )
    else:
        order = search_order(queries, _KNN_ORDER_MIN_QUERIES, _KNN_ORDER_ALWAYS_QUERIES_CUDA)
    min_bound, max_bound = bounds
    estimated = initial_radius is None
    if initial_radius is None:
        initial_radius = knn_initial_radius(points, k, bounds=bounds)
    search = [points, queries]
    shared = [wp.int32(k), wp.float32(bound), row_radii, wp.float32(initial_radius)]
    outputs = [neighbor_indices, neighbor_distances]
    if kind == "bvh":
        bvh = resolved if resolved is not None else _nearest_bvh(points, leaf_size)
        # The BVH follows an unbounded radius, so it needs no linear-scan cutover argument.
        _launch.launch(
            kernel_neighbors.bvh_nearest_kernel(k, per_row=row_radii is not None),
            dim=m,
            inputs=[*search, bvh.id, *shared, min_bound, max_bound, wp.int32(0), order, *outputs],
            device=device,
        )
        return _shape_nearest(neighbor_indices, neighbor_distances, k, single_query)

    if resolved is None:
        bins = _resolve_grid_bins(grid_bins, n)
        cell_size = _knn_cell_size(initial_radius, min_bound, max_bound, bins)
        if grid_bins is None and k > 1:
            cell_size, bins = _knn_unfolded_grid(cell_size, min_bound, max_bound, bins, n)
        grid = hashgrid_from_points(points, cell_size, bins)
    else:
        grid = resolved
        cell_size = float(getattr(grid, "cell_width", initial_radius))
    # A row the cell walk cannot certify is *deferred* to a tree rather than finished by a linear
    # scan over the whole cloud. That scan runs on the row's one thread, so even a single such row
    # -- a query beside a sparse patch of a scanned cloud -- holds the launch for ``n`` point
    # tests, while a tree answers it in time that grows with the size of its answer's ball. So the
    # walk stays the fast path for queries on or near the cloud, and only the rows it gives up on
    # pay for a tree. The walk gives up at the same radius it hands over to the scan at: bringing
    # that in shortens a displaced row's walk, but it also defers the odd outlier of an on-surface
    # query set, and one deferred row pays for the whole tree. Above ``k == 1`` a row whose first
    # walks all came back empty is handed over before the costly widest ones
    # (``kernel_neighbors.FAR_AFTER_EMPTY_WALKS``).
    #
    # The tree's ball starts from what the walk learned, or from the nearest distance when it
    # learned nothing (``kernel_neighbors.DEFERRED_ROW``): grown from the query instead, a row off
    # the cloud doubles past the surface and encloses a cap of it several times the answer's. A
    # cloud smaller than ``_KNN_DEFER_MIN_POINTS`` and the global-row kernel past the largest
    # register bucket never defer above ``k == 1``.
    defer = k == 1 or (k <= kernel_neighbors.KNN_ROW_BUCKETS[-1] and n >= _KNN_DEFER_MIN_POINTS)
    # The deferral counters exist only when rows may be deferred; otherwise the kernel never
    # touches them and takes a null descriptor. Slot 0 counts ``DEFERRED_FAR_ROW`` rows, the only
    # kind at ``k == 1``, slot 1 ``DEFERRED_ROW`` rows.
    counters = (1 if k == 1 else 2) if defer else 0
    # The estimated initial radius models a solid cloud; a surface sample's neighbours sit several
    # times closer. So when the radius is the estimate, the walk's start is measured instead: one
    # short launch counts the neighbours of a strided sample of the rows, and the main launch
    # starts each row from a quantile of their histogram, read on the device
    # (``kernel_neighbors.knn_start_sample``). The cell width stays the estimate's. The histogram
    # takes the deferral counters' zeroed buffer, after them.
    sample = (
        estimated
        and 1 < k <= kernel_neighbors.KNN_ROW_BUCKETS[-1]
        and m >= _KNN_START_SAMPLE_MIN_QUERIES
    )
    deferred = None
    start_histogram = None
    if sample:
        scratch = _launch.zeros(
            counters + kernel_neighbors.START_BEYOND + 1, dtype=wp.int32, device=device
        )
        deferred = odt.as_dense(scratch[:counters]) if defer else None
        start_histogram = odt.as_dense(scratch[counters:])
        sample_rows = kernel_neighbors.START_SAMPLE_ROWS
        _launch.launch(
            kernel_neighbors.knn_start_sample,
            dim=sample_rows,
            inputs=[
                points,
                queries,
                grid.id,
                wp.int32(k),
                wp.float32(initial_radius),
                wp.int32(m // sample_rows),
                start_histogram,
            ],
            device=device,
        )
    elif defer:
        deferred = _launch.zeros(counters, dtype=wp.int32, device=device)
    kernel = kernel_neighbors.hashgrid_nearest_kernel(k)
    # The global-row kernel (``k`` past the register buckets) spreads few queries a warp apiece:
    # 182 queries at ``k = 101`` (a crown cloud's grown fans) 4.5 -> 0.9 ms on CUDA.
    lanes = (
        []
        if kernel is not kernel_neighbors.query_hashgrid_nearest_neighbors
        else [wp.int32(_launch.walk_lanes(m, device))]
    )
    _launch.launch(
        kernel,
        dim=m * (int(lanes[0]) if lanes else 1),
        inputs=[
            *search,
            grid.id,
            *shared,
            wp.float32(_knn_widest_grid_radius(cell_size, n)),
            min_bound,
            max_bound,
            wp.int32(1 if defer else 0),
            kernel_neighbors.START_OFF
            if start_histogram is None
            else kernel_neighbors.START_SCALED,
            start_histogram,
            *lanes,
            order,
            deferred,
            *outputs,
        ],
        device=device,
    )
    if deferred is not None:
        _finish_deferred_nearest(
            points,
            queries,
            k,
            bound,
            row_radii,
            initial_radius,
            (min_bound, max_bound),
            leaf_size,
            order,
            deferred,
            neighbor_indices,
            neighbor_distances,
        )
    return _shape_nearest(neighbor_indices, neighbor_distances, k, single_query)

query_weighted_nearest

query_weighted_nearest(
    points: array[vec3],
    weights: array[float32],
    queries: array[vec3],
    *,
    max_weight: float | None = None,
    accelerator: Bvh | None = None,
    leaf_size: int | None = None,
) -> tuple[wp.array[wp.int32], wp.array[wp.float32]]

Nearest site under the weighted distance |p - q| - w(p).

Each site carries a radius, and the winner is the one whose surface is closest rather than whose centre is -- the additively weighted (Apollonius) nearest-neighbour query, which is what picks the influencing site when the sites have different scales: a sphere set, a level-of-detail cluster, a set of samples with per-sample confidence. Plain query_nearest is the w = 0 case, and the two genuinely differ -- on a random 40-site cloud, 1 query in 6 had a different winner.

Parameters:

Name Type Description Default
points array[vec3]

(n,) site positions.

required
weights array[float32]

(n,) per-site weights, subtracted from the distance. Larger wins ties of distance; may be negative, which pushes a site away.

required
queries array[vec3]

(m,) query positions.

required
max_weight float | None

An upper bound on weights, which is what makes the search prunable. None reduces weights on the device and reads the maximum back (one readback), so pass it when the bound is already known -- a radius cap, or a previous call's reduction.

None
accelerator Bvh | None

A prebuilt wp.Bvh over points, to reuse across queries. Spelled the way the four query_ball / query_nearest entry points spell it, but with no backend beside it: this query has only the BVH broad phase, so there is nothing to select between.

None
leaf_size int | None

Maximum primitives per BVH leaf when one is built here; None picks it from the point count, as query_nearest does.

None

Returns:

Type Description
(index, weighted_distance)

(m,) winning site per query and its |p - q| - w(p), which is negative wherever a query lies inside a site's radius. A query with no site at all (an empty cloud) reports -1 and inf.

Raises:

Type Description
ValueError

If weights does not have one entry per point.

RuntimeError

If points, weights, queries and accelerator are not all on one device.

Notes

max_weight is trusted, not checked: a bound smaller than some weight can silently prune the true winner, and verifying it would cost the very reduction the parameter exists to avoid. The default is therefore the safe one.

Exactness is the same argument the k-NN queries use, with the weight folded in: a site outside the cube of half-extent r is farther than r, so it scores worse than r - max_weight, and a best score at or below that bound cannot be beaten. Unlike a plain nearest query this means the search radius must exceed the answer's distance by the weight range, so a wide weight distribution costs more scans than a narrow one.

See Also

query_nearest The unweighted query, and the k > 1 form. This one answers k = 1 only, because no caller has needed more.

Examples:

The site at x = 3 has weight 2.5, so from x = 1 it scores 2 - 2.5 = -0.5 and beats the unweighted site at distance 1; from x = -1 it does not:

import warp as wp

import ordito as od

points = wp.array([[0.0, 0.0, 0.0], [3.0, 0.0, 0.0]], dtype=wp.vec3)
weights = wp.array([0.0, 2.5], dtype=wp.float32)
queries = wp.array([[1.0, 0.0, 0.0], [-1.0, 0.0, 0.0]], dtype=wp.vec3)
index, weighted_distance = od.neighbors.query_weighted_nearest(points, weights, queries)
print(index.numpy().tolist())  # [1, 0]
print(weighted_distance.numpy().tolist())  # [-0.5, 1.0]
print(od.neighbors.query_nearest(points, queries)[0].numpy().tolist())  # [0, 0]
Source code in ordito/neighbors.py
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
def query_weighted_nearest(
    points: wp.array[wp.vec3],
    weights: wp.array[wp.float32],
    queries: wp.array[wp.vec3],
    *,
    max_weight: float | None = None,
    accelerator: wp.Bvh | None = None,
    leaf_size: int | None = None,
) -> tuple[wp.array[wp.int32], wp.array[wp.float32]]:
    """
    Nearest site under the weighted distance ``|p - q| - w(p)``.

    Each site carries a radius, and the winner is the one whose *surface* is closest rather than
    whose centre is -- the additively weighted (Apollonius) nearest-neighbour query, which is what
    picks the influencing site when the sites have different scales: a sphere set, a level-of-detail
    cluster, a set of samples with per-sample confidence. Plain
    [`query_nearest`][ordito.neighbors.query_nearest] is the ``w = 0`` case, and the two
    genuinely differ -- on a random 40-site cloud, 1 query in 6 had a different winner.

    Parameters
    ----------
    points
        ``(n,)`` site positions.
    weights
        ``(n,)`` per-site weights, subtracted from the distance. Larger wins ties of distance; may
        be negative, which pushes a site away.
    queries
        ``(m,)`` query positions.
    max_weight
        An **upper bound** on ``weights``, which is what makes the search prunable. ``None`` reduces
        ``weights`` on the device and reads the maximum back (one readback), so pass it when the
        bound is already known -- a radius cap, or a previous call's reduction.
    accelerator
        A prebuilt ``wp.Bvh`` over ``points``, to reuse across queries. Spelled the way the four
        [`query_ball`][ordito.neighbors.query_ball] /
        [`query_nearest`][ordito.neighbors.query_nearest] entry points spell it, but with no
        ``backend`` beside it: this query has only the BVH broad phase, so there is nothing to
        select between.
    leaf_size
        Maximum primitives per BVH leaf when one is built here; ``None`` picks it from the point
        count, as [`query_nearest`][ordito.neighbors.query_nearest] does.

    Returns
    -------
    index, weighted_distance
        ``(m,)`` winning site per query and its ``|p - q| - w(p)``, which is **negative** wherever a
        query lies inside a site's radius. A query with no site at all (an empty cloud) reports
        ``-1`` and ``inf``.

    Raises
    ------
    ValueError
        If ``weights`` does not have one entry per point.
    RuntimeError
        If ``points``, ``weights``, ``queries`` and ``accelerator`` are not all on one device.

    Notes
    -----
    ``max_weight`` is trusted, not checked: a bound *smaller* than some weight can silently prune
    the true winner, and verifying it would cost the very reduction the parameter exists to avoid.
    The default is therefore the safe one.

    Exactness is the same argument the k-NN queries use, with the weight folded in: a site outside
    the cube of half-extent ``r`` is farther than ``r``, so it scores worse than ``r - max_weight``,
    and a best score at or below that bound cannot be beaten. Unlike a plain nearest query this
    means the search radius must exceed the answer's distance *by the weight range*, so a wide
    weight distribution costs more scans than a narrow one.

    See Also
    --------
    [`query_nearest`][ordito.neighbors.query_nearest]
        The unweighted query, and the ``k > 1`` form. This one answers ``k = 1`` only, because no
        caller has needed more.

    Examples
    --------
    The site at ``x = 3`` has weight ``2.5``, so from ``x = 1`` it scores ``2 - 2.5 = -0.5`` and
    beats the unweighted site at distance 1; from ``x = -1`` it does not:

    ```python
    import warp as wp

    import ordito as od

    points = wp.array([[0.0, 0.0, 0.0], [3.0, 0.0, 0.0]], dtype=wp.vec3)
    weights = wp.array([0.0, 2.5], dtype=wp.float32)
    queries = wp.array([[1.0, 0.0, 0.0], [-1.0, 0.0, 0.0]], dtype=wp.vec3)
    index, weighted_distance = od.neighbors.query_weighted_nearest(points, weights, queries)
    print(index.numpy().tolist())  # [1, 0]
    print(weighted_distance.numpy().tolist())  # [-0.5, 1.0]
    print(od.neighbors.query_nearest(points, queries)[0].numpy().tolist())  # [0, 0]
    ```
    """
    require_same_device(points=points, weights=weights, queries=queries, accelerator=accelerator)
    device = points.device
    n = points.size
    m = queries.size
    if weights.size != n:
        raise ValueError("weights must have one entry per point")

    if m == 0:
        return (
            _launch.empty(0, dtype=wp.int32, device=device),
            _launch.empty(0, dtype=wp.float32, device=device),
        )
    if n == 0:
        return (
            _launch.full(m, -1, dtype=wp.int32, device=device),
            _launch.full(m, float("inf"), dtype=wp.float32, device=device),
        )

    if accelerator is None:
        accelerator = _nearest_bvh(points, leaf_size)
    if max_weight is None:
        max_weight = float(od.reduce.max(weights))
    min_bound, max_bound = od.bounds.aabb(points)
    # First radius: the mean spacing's own estimate plus the weight bound, since a query cannot be
    # certified below it however close its winner is.
    initial_radius = knn_initial_radius(points, 1, bounds=(min_bound, max_bound)) + max(
        max_weight, 0.0
    )

    out_indices = _launch.empty(m, dtype=wp.int32, device=device)
    out_distances = _launch.empty(m, dtype=wp.float32, device=device)
    _launch.launch(
        kernel_neighbors.query_weighted_nearest_neighbors,
        dim=m,
        inputs=[
            points,
            weights,
            queries,
            accelerator.id,
            wp.float32(max_weight),
            wp.float32(initial_radius),
            min_bound,
            max_bound,
            out_indices,
            out_distances,
        ],
        device=device,
    )
    return out_indices, out_distances

nearest_neighbor_distance

nearest_neighbor_distance(
    points: array[vec3],
) -> wp.array[wp.float32]

Distance from each point to the closest other point of the same cloud.

The standard scale estimate for an unstructured cloud, and what a sampling-driven parameter is normally derived from: the mean of this array is the cloud's mean spacing, which is how ball_pivoting guesses its ball radius and how screened_poisson caps its octree depth. The k=2 self-query's second column: each point's nearest neighbour other than itself.

Parameters:

Name Type Description Default
points array[vec3]

(n,) point positions.

required

Returns:

Type Description
array[float32]

(n,) distances on points.device. Zero where two points coincide exactly.

Notes

A cloud of fewer than two points has no answer, and this reports inf for every entry — the value query_nearest already uses for a slot it could not fill. Open3D's compute_nearest_neighbor_distance reports 0.0 in that one case; on any cloud of two or more points the two agree, because every point then has a nearest neighbour. The distances are float32 (wp.length), so they can differ from a float64 reference in the last digits.

See Also

query_nearest The underlying query; call it directly to reuse a BVH across several queries of one cloud. ordito.points.farthest_point_sample

Examples:

Two pairs of points, one unit and one half unit apart:

import warp as wp

import ordito as od

points = wp.array(
    [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [3.0, 0.0, 0.0], [3.0, 0.0, 0.5]], dtype=wp.vec3
)
print(od.neighbors.nearest_neighbor_distance(points).numpy().tolist())  # [1.0, 1.0, 0.5, 0.5]
Source code in ordito/neighbors.py
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
def nearest_neighbor_distance(points: wp.array[wp.vec3]) -> wp.array[wp.float32]:
    """
    Distance from each point to the closest *other* point of the same cloud.

    The standard scale estimate for an unstructured cloud, and what a sampling-driven parameter is
    normally derived from: the mean of this array is the cloud's mean spacing, which is how
    [`ball_pivoting`][ordito.reconstruction.ball_pivoting] guesses its ball radius and how
    [`screened_poisson`][ordito.reconstruction.screened_poisson] caps its octree depth. The
    ``k=2`` self-query's second column: each point's nearest neighbour other than itself.

    Parameters
    ----------
    points
        ``(n,)`` point positions.

    Returns
    -------
    wp.array[wp.float32]
        ``(n,)`` distances on ``points.device``. Zero where two points coincide exactly.

    Notes
    -----
    A cloud of fewer than two points has no answer, and this reports ``inf`` for every entry —
    the value [`query_nearest`][ordito.neighbors.query_nearest] already uses for a slot it
    could not fill. Open3D's ``compute_nearest_neighbor_distance`` reports ``0.0`` in that one
    case; on any cloud of two or more points the two agree, because every point then has a nearest
    neighbour. The distances are ``float32`` (``wp.length``), so they can differ from a
    ``float64`` reference in the last digits.

    See Also
    --------
    [`query_nearest`][ordito.neighbors.query_nearest]
        The underlying query; call it directly to reuse a BVH across several queries of one cloud.
    [`ordito.points.farthest_point_sample`][ordito.points.farthest_point_sample]

    Examples
    --------
    Two pairs of points, one unit and one half unit apart:

    ```python
    import warp as wp

    import ordito as od

    points = wp.array(
        [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [3.0, 0.0, 0.0], [3.0, 0.0, 0.5]], dtype=wp.vec3
    )
    print(od.neighbors.nearest_neighbor_distance(points).numpy().tolist())  # [1.0, 1.0, 0.5, 0.5]
    ```
    """
    device = points.device
    n = points.size
    if n < 2:
        return _launch.full(n, math.inf, dtype=wp.float32, device=device)

    if _nearest_descends(points, _SELF_DESCENT_MAX_POINTS_CPU):
        distances, _tree = _nearest_other_distances(points)
        return distances
    _indices, distances = query_nearest(points, points, k=2)
    # Column 1 of the ``(n, 2)`` table, which is a *strided* view -- so it is copied into a dense
    # buffer rather than returned, both because callers expect a plain ``wp.array`` and because a
    # strided array is the shape that silently corrupts a downstream Python-scope gather.
    nearest = _launch.empty(n, dtype=wp.float32, device=device)
    _launch.copy(nearest, distances[:, 1])
    return nearest

closest_pair

closest_pair(points: array[vec3]) -> tuple[int, int, float]

Find the two closest points of a cloud, and the distance between them.

The global minimum of nearest_neighbor_distance, with the partner recovered: the same per-point search, reduced instead of returned. Answers "does this cloud contain a near-duplicate, and where" in one call, which is the question a tolerance for ordito.points.point_duplicate_mask is normally chosen from.

Parameters:

Name Type Description Default
points array[vec3]

(n,) point positions, n >= 2.

required

Returns:

Type Description
(index_a, index_b, distance)

The two point indices — index_a < n, index_b its nearest neighbour — and their Euclidean distance, all as Python scalars.

Raises:

Type Description
ValueError

If points holds fewer than two points, which have no pair.

Notes

Ties are broken toward the lowest index_a: the reduction is a min over one int64 per point holding the distance in the high half and the index in the low, so a shorter distance wins and an equal distance defers to the smaller index. Exact duplicates therefore report the first duplicated point at distance 0.0.

One host readback, of two elements: the reduction's result and index_b. No per-point table is written or moved across the bus. index_b differs from index_a even where the two coincide.

See Also

nearest_neighbor_distance The per-point form, when every distance is wanted rather than the smallest. ordito.points.point_duplicate_mask Exact coincidence rather than proximity, and a mask rather than one pair.

Examples:

import warp as wp

import ordito as od

points = wp.array(
    [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [3.0, 0.0, 0.0], [3.0, 0.0, 0.5]], dtype=wp.vec3
)
print(od.neighbors.closest_pair(points))  # (2, 3, 0.5)
Source code in ordito/neighbors.py
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
def closest_pair(points: wp.array[wp.vec3]) -> tuple[int, int, float]:
    """
    Find the two closest points of a cloud, and the distance between them.

    The global minimum of
    [`nearest_neighbor_distance`][ordito.neighbors.nearest_neighbor_distance], with the partner
    recovered: the same per-point search, reduced instead of returned.
    Answers "does this cloud contain a near-duplicate, and where" in one call, which is the question
    a tolerance for
    [`ordito.points.point_duplicate_mask`][ordito.points.point_duplicate_mask] is normally chosen
    from.

    Parameters
    ----------
    points
        ``(n,)`` point positions, ``n >= 2``.

    Returns
    -------
    index_a, index_b, distance
        The two point indices — ``index_a < n``, ``index_b`` its nearest neighbour — and their
        Euclidean distance, all as Python scalars.

    Raises
    ------
    ValueError
        If ``points`` holds fewer than two points, which have no pair.

    Notes
    -----
    Ties are broken toward the **lowest** ``index_a``: the reduction is a ``min`` over one ``int64``
    per point holding the distance in the high half and the index in the low, so a shorter distance
    wins and an equal distance defers to the smaller index. Exact duplicates therefore report the
    first duplicated point at distance ``0.0``.

    One host readback, of two elements: the reduction's result and ``index_b``. No per-point
    table is written or moved across the bus. ``index_b`` differs from ``index_a`` even where
    the two coincide.

    See Also
    --------
    [`nearest_neighbor_distance`][ordito.neighbors.nearest_neighbor_distance]
        The per-point form, when every distance is wanted rather than the smallest.
    [`ordito.points.point_duplicate_mask`][ordito.points.point_duplicate_mask]
        Exact coincidence rather than proximity, and a mask rather than one pair.

    Examples
    --------
    ```python
    import warp as wp

    import ordito as od

    points = wp.array(
        [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [3.0, 0.0, 0.0], [3.0, 0.0, 0.5]], dtype=wp.vec3
    )
    print(od.neighbors.closest_pair(points))  # (2, 3, 0.5)
    ```
    """
    n = points.size
    if n < 2:
        raise ValueError("closest_pair needs at least two points")

    device = points.device
    n_blocks = kernel_reduce.blocks_1d(n)
    result = _launch.full(3, INT64_MAX, dtype=wp.int64, device=device)
    if _nearest_descends(points, _SELF_DESCENT_MAX_POINTS_CPU):
        distances, tree = _nearest_other_distances(points)
        kernel = kernel_neighbors.closest_pair_key
        inputs = [tree.id, points, distances]
    else:
        indices, distances = query_nearest(points, points, k=2)
        # Column 1 of the table, as strided views -- column 0 is each point itself. The kernel
        # only indexes them, so neither needs a dense copy.
        kernel = kernel_neighbors.nearest_key_pair
        inputs = [distances[:, 1], indices[:, 1]]
    _launch.launch_tiled(
        kernel, dim=n_blocks, inputs=[*inputs, n_blocks, result], block_dim=TILE_1D, device=device
    )
    key, index_b = (int(value) for value in read_values(result, 0, 2))
    # The key's high half is the distance's own float32 bits, so it decodes on the host for free.
    distance = float(np.array([key >> 32], dtype=np.uint32).view(np.float32)[0])
    return key & 0xFFFFFFFF, index_b, distance

mutual_nearest

mutual_nearest(
    a: array[vec3], b: array[vec3]
) -> tuple[
    odt.Array1dInt32, odt.Array1dInt32, odt.Array1dFloat32
]

Pairs of points of two clouds that are each other's nearest neighbour, and their distances.

Point a[i] and point b[j] pair when b[j] is the nearest point of b to a[i] and a[i] the nearest point of a to b[j]. Each point is in at most one pair, so the pairs are a one-to-one correspondence between subsets of the two clouds: the usual filter on putative matches before a rigid fit (mutual, or reciprocal, nearest neighbours).

Parameters:

Name Type Description Default
a array[vec3]

(n_a,) first cloud.

required
b array[vec3]

(n_b,) second cloud.

required

Returns:

Type Description
(a_indices, b_indices, distances)

(n_pairs,) wp.int32 indices into a (ascending) and into b, and the (n_pairs,) wp.float32 Euclidean distance of each pair. Empty when either cloud is.

Raises:

Type Description
RuntimeError

If a and b are not on one device.

Notes

Two nearest-neighbour searches, one each way (the k=1 search of query_nearest), then one pass keeping the pairs that agree. Where a point's nearest neighbour is tied, the query's choice among the tied points decides whether it pairs.

See Also

query_nearest The one-way nearest neighbours. ordito.registration.procrustes The rigid fit to the pairs.

Examples:

import warp as wp

import ordito as od

a = wp.array([[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [5.0, 0.0, 0.0]], dtype=wp.vec3)
b = wp.array([[0.1, 0.0, 0.0], [4.0, 0.0, 0.0]], dtype=wp.vec3)
a_indices, b_indices, distances = od.neighbors.mutual_nearest(a, b)
print(a_indices.numpy().tolist(), b_indices.numpy().tolist())  # [0, 2] [0, 1]
print([round(float(d), 3) for d in distances.numpy()])  # [0.1, 1.0]
Source code in ordito/neighbors.py
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
def mutual_nearest(
    a: wp.array[wp.vec3], b: wp.array[wp.vec3]
) -> tuple[odt.Array1dInt32, odt.Array1dInt32, odt.Array1dFloat32]:
    """
    Pairs of points of two clouds that are each other's nearest neighbour, and their distances.

    Point ``a[i]`` and point ``b[j]`` pair when ``b[j]`` is the nearest point of ``b`` to
    ``a[i]`` and ``a[i]`` the nearest point of ``a`` to ``b[j]``. Each point is in at most one
    pair, so the pairs are a one-to-one correspondence between subsets of the two clouds: the
    usual filter on putative matches before a rigid fit (mutual, or reciprocal, nearest
    neighbours).

    Parameters
    ----------
    a
        ``(n_a,)`` first cloud.
    b
        ``(n_b,)`` second cloud.

    Returns
    -------
    a_indices, b_indices, distances
        ``(n_pairs,)`` ``wp.int32`` indices into ``a`` (ascending) and into ``b``, and the
        ``(n_pairs,)`` ``wp.float32`` Euclidean distance of each pair. Empty when either cloud
        is.

    Raises
    ------
    RuntimeError
        If ``a`` and ``b`` are not on one device.

    Notes
    -----
    Two nearest-neighbour searches, one each way (the ``k=1`` search of
    [`query_nearest`][ordito.neighbors.query_nearest]), then one pass keeping the pairs that
    agree. Where a point's nearest neighbour is tied, the query's choice among the tied points
    decides whether it pairs.

    See Also
    --------
    [`query_nearest`][ordito.neighbors.query_nearest]
        The one-way nearest neighbours.
    [`ordito.registration.procrustes`][ordito.registration.procrustes]
        The rigid fit to the pairs.

    Examples
    --------
    ```python
    import warp as wp

    import ordito as od

    a = wp.array([[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [5.0, 0.0, 0.0]], dtype=wp.vec3)
    b = wp.array([[0.1, 0.0, 0.0], [4.0, 0.0, 0.0]], dtype=wp.vec3)
    a_indices, b_indices, distances = od.neighbors.mutual_nearest(a, b)
    print(a_indices.numpy().tolist(), b_indices.numpy().tolist())  # [0, 2] [0, 1]
    print([round(float(d), 3) for d in distances.numpy()])  # [0.1, 1.0]
    ```
    """
    require_same_device(a=a, b=b)
    device = a.device
    n_a = a.size
    if n_a == 0 or b.size == 0:
        return (
            _launch.empty(0, dtype=wp.int32, device=device),
            _launch.empty(0, dtype=wp.int32, device=device),
            _launch.empty(0, dtype=wp.float32, device=device),
        )
    if _nearest_descends(a, 0) and _nearest_descends(b, 0):
        # Both directions in one launch over two point trees, ``a``'s rows first: two nearest
        # searches launched apart are each too few threads to fill the device. The leading rows
        # serve as ``a``'s answer as they stand, the kernels reading only their own index.
        # The orders are chosen before the trees are built, as ``metrics``' pairs choose them.
        order_a, order_b = search_order(a), search_order(b)
        tree_a = bvh_from_points(a, leaf_size=1)
        tree_b = bvh_from_points(b, leaf_size=1)
        n_rows = n_a + b.size
        nearest_in_b = _launch.empty(n_rows, dtype=wp.int32, device=device)
        distances = _launch.empty(n_rows, dtype=wp.float32, device=device)
        _launch.launch(
            kernel_neighbors.nearest_points_both_ways,
            dim=n_rows,
            inputs=[tree_a.id, a, tree_b.id, b, order_a, order_b],
            outputs=[nearest_in_b, distances],
            device=device,
            block_dim=kernel_neighbors.descent_block_dim(n_rows, device),
        )
        nearest_in_a = _launch.view(nearest_in_b, n_a, n_rows)
    else:
        # Past the size where the trees' builds are the call, the grid's two searches.
        nearest_in_b, distances = query_nearest(b, a)
        nearest_in_a, _ = query_nearest(a, b)
    flags = _launch.empty(n_a, dtype=wp.int32, device=device)
    _launch.launch(
        kernel_array.round_trip_flags,
        dim=n_a,
        inputs=[nearest_in_b, nearest_in_a, flags],
        device=device,
    )
    n_pairs = scan_count(flags)
    a_indices = _launch.empty(n_pairs, dtype=wp.int32, device=device)
    b_indices = _launch.empty(n_pairs, dtype=wp.int32, device=device)
    pair_distances = _launch.empty(n_pairs, dtype=wp.float32, device=device)
    if n_pairs > 0:
        _launch.launch(
            kernel_neighbors.emit_mutual_pairs,
            dim=n_a,
            inputs=[flags, nearest_in_b, distances, a_indices, b_indices, pair_distances],
            device=device,
        )
    return a_indices, b_indices, pair_distances

geodesic_ball

geodesic_ball(
    vertices: array[vec3],
    faces: array[int32],
    radius: float,
    min_count: int = 6,
) -> tuple[
    wp.array[wp.int32],
    wp.array[wp.int32],
    wp.array[wp.int32],
]

Per-vertex geodesic-ball neighborhoods, and the reference neighbor that frames each one.

For each vertex this is a breadth-first traversal of the mesh edge graph, enqueueing a neighbor only when it lies within Euclidean radius of the center — i.e. the connected component of the center within the radius ball. This is a geodesic ball rather than a pure Euclidean one, so it excludes vertices that are spatially close but lie across a fold of the surface (e.g. the opposite wall of a torus tube), which a Euclidean hash-grid query would wrongly include and which corrupts the quadric fit. When fewer than min_count vertices are reachable, the nearest out-of-ball vertices are appended (libigl's extra_candidates path).

Also returns the per-vertex reference neighbor used to build the tangent frame: the lowest-indexed edge neighbor, matching libigl's adjacency_list[i][0]. libigl's symmetrized shape operator is frame-dependent, so reproducing its principal values ( principal_curvature with frame_independent=False) requires this exact frame; the default frame-independent computation does not depend on it. Isolated vertices reference themselves.

The traversal runs entirely on device. Vertex adjacency is built as a CSR graph with sorted rows -- the buffer edges_unique + edges_to_neighbor_lists would give -- from one radix sort of both directions of every face edge, then a single-pass BFS collects each ball into its per-source queue row (the queue prefix is the result) and a scan + gather compacts the rows into the CSR neighbor buffer. Each source uses fixed-capacity scratch of PER_SOURCE_MAX_NEIGHBORS neighbors (ordito.kernels.algorithms.bfs, currently 512); if a vertex collects more than that the surplus is dropped and a warning reports how many vertices' neighborhoods were clipped.

Note

Distances and tie-breaking are computed in float32 (set-equivalent to the libigl reference; borderline ties between equidistant neighbors may resolve differently but leave the order-independent quadric fit unchanged).

Parameters:

Name Type Description Default
vertices array[vec3]

(n_vertices,) mesh vertex positions.

required
faces array[int32]

(3 * n_faces,) flat triangle index buffer.

required
radius float

Geodesic-ball radius in world units.

required
min_count int

Minimum neighbors per vertex; the nearest out-of-ball vertices backfill any shortfall.

6

Returns:

Type Description
tuple[array[int32], array[int32], array[int32]]

(n_total,), (n_vertices + 1,) and (n_vertices,) arrays (neighbor_indices, offsets, reference_neighbors). offsets is the exclusive prefix sum of per-vertex neighbor counts (CSR row bounds); vertex i owns neighbor_indices[offsets[i] : offsets[i + 1]] and offsets[n_vertices] is the total n_total.

Raises:

Type Description
ValueError

If the neighborhoods hold more than 2**31 - 1 entries in total, past the range of the int32 offsets.

RuntimeError

If vertices and faces are not all on one device.

Examples:

On an icosahedron inscribed in the unit sphere the edges are about 1.05 long, so a radius of 1.1 reaches each vertex's five edge neighbours and the ball holds six vertices, the centre included. At 1.8 it holds every vertex but the antipode:

import ordito as od

vertices, faces = od.creation.icosahedron()
neighbors, offsets, reference = od.neighbors.geodesic_ball(vertices, faces, radius=1.1)
print(offsets.numpy()[:4].tolist())  # [0, 6, 12, 18]
print(sorted(neighbors.numpy()[:6].tolist()))  # [0, 1, 5, 7, 10, 11]
_, offsets, _ = od.neighbors.geodesic_ball(vertices, faces, radius=1.8)
print(offsets.numpy()[:4].tolist())  # [0, 11, 22, 33]
Source code in ordito/neighbors.py
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
def geodesic_ball(
    vertices: wp.array[wp.vec3], faces: wp.array[wp.int32], radius: float, min_count: int = 6
) -> tuple[wp.array[wp.int32], wp.array[wp.int32], wp.array[wp.int32]]:
    """
    Per-vertex geodesic-ball neighborhoods, and the reference neighbor that frames each one.

    For each vertex this is a breadth-first traversal of the mesh edge graph, enqueueing a neighbor
    only when it lies within Euclidean ``radius`` of the center — i.e. the connected component of
    the center within the radius ball. This is a *geodesic* ball rather than a pure Euclidean one,
    so it excludes vertices that are spatially close but lie across a fold of the surface (e.g. the
    opposite wall of a torus tube), which a Euclidean hash-grid query would wrongly include and
    which corrupts the quadric fit. When fewer than ``min_count`` vertices are reachable, the
    nearest out-of-ball vertices are appended (libigl's ``extra_candidates`` path).

    Also returns the per-vertex reference neighbor used to build the tangent frame: the
    lowest-indexed edge neighbor, matching libigl's ``adjacency_list[i][0]``. libigl's symmetrized
    shape operator is frame-dependent, so reproducing its principal values (
    [`principal_curvature`][ordito.curvature.principal_curvature] with ``frame_independent=False``)
    requires this exact frame; the default frame-independent computation does not depend on it.
    Isolated vertices reference themselves.

    The traversal runs entirely on device. Vertex adjacency is built as a CSR graph with sorted
    rows -- the buffer [`edges_unique`][ordito.edges.edges_unique] +
    [`edges_to_neighbor_lists`][ordito.graph.edges_to_neighbor_lists] would give -- from one radix
    sort of both directions of every face edge, then a single-pass BFS collects each ball into its
    per-source queue row (the queue prefix *is* the result) and a scan + gather compacts the rows
    into the CSR neighbor buffer. Each source uses fixed-capacity scratch of
    ``PER_SOURCE_MAX_NEIGHBORS`` neighbors (``ordito.kernels.algorithms.bfs``, currently 512); if a
    vertex collects more than that the surplus is dropped and a warning reports how many vertices'
    neighborhoods were clipped.

    !!! note

        Distances and tie-breaking are computed in ``float32`` (set-equivalent to the libigl
        reference; borderline ties between equidistant neighbors may resolve differently but leave
        the order-independent quadric fit unchanged).

    Parameters
    ----------
    vertices
        ``(n_vertices,)`` mesh vertex positions.
    faces
        ``(3 * n_faces,)`` flat triangle index buffer.
    radius
        Geodesic-ball radius in world units.
    min_count
        Minimum neighbors per vertex; the nearest out-of-ball vertices backfill any shortfall.

    Returns
    -------
    tuple[wp.array[wp.int32], wp.array[wp.int32], wp.array[wp.int32]]
        ``(n_total,)``, ``(n_vertices + 1,)`` and ``(n_vertices,)`` arrays
        ``(neighbor_indices, offsets, reference_neighbors)``. ``offsets`` is the exclusive prefix
        sum of per-vertex neighbor counts (CSR row bounds); vertex ``i`` owns
        ``neighbor_indices[offsets[i] : offsets[i + 1]]`` and ``offsets[n_vertices]`` is the total
        ``n_total``.

    Raises
    ------
    ValueError
        If the neighborhoods hold more than ``2**31 - 1`` entries in total, past the range of the
        ``int32`` offsets.
    RuntimeError
        If ``vertices`` and ``faces`` are not all on one device.

    Examples
    --------
    On an icosahedron inscribed in the unit sphere the edges are about ``1.05`` long, so a radius of
    ``1.1`` reaches each vertex's five edge neighbours and the ball holds six vertices, the centre
    included. At ``1.8`` it holds every vertex but the antipode:

    ```python
    import ordito as od

    vertices, faces = od.creation.icosahedron()
    neighbors, offsets, reference = od.neighbors.geodesic_ball(vertices, faces, radius=1.1)
    print(offsets.numpy()[:4].tolist())  # [0, 6, 12, 18]
    print(sorted(neighbors.numpy()[:6].tolist()))  # [0, 1, 5, 7, 10, 11]
    _, offsets, _ = od.neighbors.geodesic_ball(vertices, faces, radius=1.8)
    print(offsets.numpy()[:4].tolist())  # [0, 11, 22, 33]
    ```
    """
    require_same_device(vertices=vertices, faces=faces)
    device = vertices.device
    n = vertices.size
    if n == 0:
        # A single zero rather than an empty buffer: the CSR row-bounds form is ``n + 1`` long.
        return (
            *_launch.empty_packed(wp.int32, device),
            _launch.empty(0, dtype=wp.int32, device=device),
        )

    # Per-source scratch is sized for one chunk of sources (``GeodesicBallWalk``); this packs each
    # chunk's queue rows into its own flat buffer before the next chunk reuses them.
    chunk = min(n, _GEODESIC_BALL_CHUNK)
    # CSR row bounds in the length-``n + 1`` form. The leading zero from ``wp.zeros`` is the first
    # exclusive offset and the inclusive scan fills the rest, so ``offsets[n]`` holds the total --
    # ``array.counts_to_offsets``' convention, open-coded here because that helper reads the total
    # back to the host and no caller here wants it. The terminator belongs at this producer rather
    # than in each consumer's kernel: both of them read ``offsets[i + 1]`` as the row end.
    single_chunk = n <= chunk
    # With one chunk the global scan *is* the chunk's: its prefix is the exclusive offsets and its
    # terminator the total, so no chunk-local scan or total buffer is needed. The overflow counter
    # sits right after the total -- in the offsets' own buffer on one chunk, beside the chunk total
    # on several -- so the last chunk reads both in one copy.
    if single_chunk:
        totals = _launch.zeros(n + 2, dtype=wp.int32, device=device)
        total_at = n
        offsets = odt.as_dense(totals[: n + 1])
        local_offsets = odt.as_dense(offsets[:n])
    else:
        totals = _launch.zeros(2, dtype=wp.int32, device=device)
        total_at = 0
        offsets = _launch.zeros(n + 1, dtype=wp.int32, device=device)
        local_offsets = _launch.empty(chunk, dtype=wp.int32, device=device)
    # The walk's clip counter sits beside the totals, so the last chunk reads both in one copy: a
    # constructor argument no public caller should see, hence the module's own access.
    walk = GeodesicBallWalk.__new__(GeodesicBallWalk)
    walk._setup(  # pyright: ignore[reportPrivateUsage]
        vertices, faces, radius, min_count, odt.as_dense(totals[total_at + 1 : total_at + 2])
    )
    counts = walk.counts
    chunk_flats: list[wp.array[wp.int32]] = []
    n_overflow = 0
    n_total = 0
    for start, m in walk.chunks():
        # Gather this chunk's queue rows before the next chunk reuses the pools: chunk-local
        # exclusive scan of counts, one 4-byte readback for the chunk total, then a coalesced
        # 2D copy into the chunk's flat buffer.
        if single_chunk:
            _launch.array_scan(counts, out_array=offsets[1:], inclusive=True)
        else:
            _launch.array_scan(
                counts[start : start + m], out_array=local_offsets[:m], inclusive=False
            )
            _launch.map(
                wp.add, local_offsets[m - 1 : m], counts[start + m - 1 : start + m], out=totals[:1]
            )
        if start + m == n:
            chunk_total, n_overflow = read_values(totals, total_at, 2)
        else:
            chunk_total = int(read_scalar(totals, 0))
        # The offsets are ``int32``: a list past their range would wrap them silently, so it is
        # refused here, on the totals already read back, before the next chunk is walked.
        n_total += chunk_total
        if n_total > _PACKED_ENTRIES_MAX:
            raise ValueError(
                f"geodesic_ball: the packed neighbor list passes {_PACKED_ENTRIES_MAX} entries "
                f"after {start + m} of {n} vertices; radius {radius} is too large for int32 "
                "offsets on this mesh"
            )
        if start + m == n:
            # Before the walk resumes, so its own end-of-walk check finds the warning given.
            walk._warn_clipped(n_overflow, stacklevel=3)  # pyright: ignore[reportPrivateUsage]
        flat_chunk = _launch.empty(chunk_total, dtype=wp.int32, device=device)
        if chunk_total > 0:
            _launch.launch(
                kernel_neighbors.gather_queue_rows,
                dim=(m, kernel_bfs.PER_SOURCE_MAX_NEIGHBORS),
                inputs=[walk.rows, counts, local_offsets, wp.int32(start), flat_chunk],
                device=device,
            )
        chunk_flats.append(flat_chunk)

    if single_chunk:
        # Single chunk (n <= chunk): the chunk buffer already is the global CSR neighbor buffer.
        return chunk_flats[0], offsets, walk.reference

    _launch.array_scan(counts, out_array=offsets[1:], inclusive=True)

    # Chunk order equals ascending source order, so concatenation lines up with the global scan.
    # Same per-segment ``wp.copy`` loop either way -- that is the packing floor -- one call for it.
    return od.array.concatenate(chunk_flats), offsets, walk.reference