Skip to content

Top level

Module-level helpers, re-exported from the compiled core.

Vector search for single-cell and computational biology, in Rust.

Every index is a scikit-learn style estimator: parameters go in the constructor, data goes into fit, results come out of kneighbors.

>>> import numpy as np, ann_search as ann
>>> X = np.random.default_rng(0).standard_normal((5000, 50)).astype("float32")
>>> index = ann.HnswIndex(n_neighbors=15, metric="cosine").fit(X)
>>> distances, indices = index.kneighbors()        # self-kNN, fast path
>>> distances, indices = index.kneighbors(X[:100]) # cross-set

kneighbors returns distances first, matching scikit-learn and FAISS. A query that came back with fewer than k neighbours is padded with -1 indices and infinite distances, and kneighbors_graph drops those slots.

Indices are immutable. There's no incremental add, so rebuild instead.

AnnSearchError

Bases: Exception

Base class for every error raised by the Rust core.

IndexIoError

Bases: AnnSearchError

An index bundle is missing, truncated, or of the wrong kind or dtype.

gpu_available builtin

gpu_available() -> bool

Whether the GPU indices can be used here.

Returns

True only when this build has the gpu feature and wgpu resolves an adapter. Safe to call on any machine.

Note

Acquiring a client panics rather than erroring when no adapter is found, so the probe catches it. That is sound here because the release profile is pinned to panic = "unwind", which pyo3 requires anyway. The panic hook is silenced for the duration, otherwise merely asking the question prints a backtrace to stderr.

knn_graph_nndescent

knn_graph_nndescent(
    X: Any,
    n_neighbors: int = 15,
    *,
    metric: str = "euclidean",
    include_self: bool = True,
    return_distance: bool = True,
    delta: float = 0.001,
    max_iter: int | None = None,
    max_candidates: int | None = None,
    n_trees: int | None = None,
    seed: int = 42,
    verbose: int = 0,
) -> tuple[ndarray, ndarray] | ndarray

Self-kNN graph by NN-Descent, without building an index.

Parameters:

Name Type Description Default
X Any

Samples by features. float32 and float64 are used as they are, other numeric types are promoted to float64.

required
n_neighbors int

Row length, the self-edge included when include_self is set, matching kneighbors.

15
metric str

"euclidean"/"l2", "sqeuclidean", "cosine" or "manhattan"/"l1".

'euclidean'
include_self bool

Whether row i starts with i at distance zero.

True
return_distance bool

Whether to return distances alongside indices.

True
delta float

Convergence threshold. Descent stops once the fraction of updated edges falls below it.

0.001
max_iter int | None

Descent iteration cap. None defaults to max(round(log2(n)), 5).

None
max_candidates int | None

Neighbours sampled per node per local join. None defaults to min(k, 60).

None
n_trees int | None

Random projection trees seeding the graph. None defaults to min(5 + round(sqrt(n) / 20), 64).

None
seed int

Fixes the seed graph and the sampling.

42
verbose int

0 quiet, 1 normal, 2 detailed. Prints to the process stdout, not sys.stdout.

0

Returns:

Type Description
tuple[ndarray, ndarray] | ndarray

(distances, indices) of shape (n, n_neighbors), or just

tuple[ndarray, ndarray] | ndarray

indices when return_distance is False.

num_threads builtin

num_threads() -> int

Number of threads currently available for index builds and queries.

Returns

The configured pool's size, or rayon's global pool size when no override is in place.

set_num_threads builtin

set_num_threads(n: int) -> None

Set the number of threads used for index builds and queries.

Rayon worker threads do not survive fork, so a multiprocessing child using the default fork start method on Linux will hang if it touches the pool. Use the spawn start method there.

Params
  • n - Thread count. 0 clears the override and returns to rayon's global pool, which honours RAYON_NUM_THREADS.
Returns

Nothing, or a RuntimeError if the pool could not be built.