Skip to main content

KnnGraph

Struct KnnGraph 

Source
pub struct KnnGraph {
    pub adjacency: CscMatrix<f32>,
    pub edges: Vec<(usize, usize)>,
    pub distances: Vec<f32>,
    pub n_nodes: usize,
}

Fields§

§adjacency: CscMatrix<f32>

Symmetric CSC adjacency matrix (n_nodes x n_nodes)

§edges: Vec<(usize, usize)>

Sorted edge list (i < j), deduplicated

§distances: Vec<f32>

Edge distances/weights, parallel to edges

§n_nodes: usize

Number of nodes

Implementations§

Source§

impl KnnGraph

Source

pub fn from_columns( points: &DMatrix<f32>, args: KnnGraphArgs, ) -> Result<KnnGraph>

Build a KNN graph from column vectors.

  • points - transposed coordinate matrix (d x n), where each column is a point
  • args - KNN graph construction parameters
Source

pub fn from_rows(data: &DMatrix<f32>, args: KnnGraphArgs) -> Result<KnnGraph>

Build a KNN graph from row vectors (cells × features).

  • data - matrix (n x d), where each row is a point
  • args - KNN graph construction parameters
Source

pub fn from_rows_fuzzy( data: &DMatrix<f32>, args: KnnGraphArgs, ) -> Result<(KnnGraph, Vec<f32>)>

KnnGraph::from_columns_fuzzy over row vectors.

Source

pub fn from_columns_fuzzy( points: &DMatrix<f32>, args: KnnGraphArgs, ) -> Result<(KnnGraph, Vec<f32>)>

The kNN graph of the columns of points, and UMAP’s fuzzy membership of each edge (parallel to edges), as umap-learn and uwot compute it:

  1. each point’s weights over its OWN knn neighbours only: exp(-(d - ρ) / σ), ρ its nearest distance, σ set so they sum to log2(knn + 1) (UMAP counts the point itself among its n_neighbors, so knn others is n_neighbors = knn + 1);
  2. zero toward a point it did not list;
  3. the fuzzy union of the two directions, a + b - a·b.

KnnGraph::fuzzy_kernel_weights instead calibrates each point over every edge touching it after the union, so a point many others list gets a wider kernel and a one-sided edge a weight from both ends.

Source

pub fn union_with( &self, other: &KnnGraph, policy: DistanceMerge, ) -> Result<(KnnGraph, Vec<EdgeSource>)>

Merge two graphs over the same nodes, keeping every pair exactly once and reporting which input each came from.

Borrows both inputs: a caller that unions a spatial graph with an expression one generally still needs the spatial graph afterwards, as the topology for anything that reasons about physical adjacency.

Neither input is assumed sorted, nor assumed to store i < j. Edge order is a constructor invariant here, not a type invariant, and a hand-built KnnGraph can violate both.

distances after a union are NOT a metric. Under DistanceMerge::SourceRank they are within-source quantile ranks, which keeps them comparable across sources without pretending the two measurements are the same quantity. When an edge is in both inputs the smaller value wins, matching the reciprocal: false convention in build_from_dict.

Source

pub fn neighbors(&self, node: usize) -> &[usize]

Get neighbors of a node from the CSC adjacency matrix

Source

pub fn num_edges(&self) -> usize

Source

pub fn num_nodes(&self) -> usize

Source

pub fn exp_kernel_weights(&self) -> Vec<f32>

Convert distances to similarity weights using an exponential kernel: w = exp(-d / σ) where σ = median distance.

Returns weights parallel to self.edges, all in (0, 1]. Consistent with the softmax(-d) pattern used in counterfactual inference (data_beans::alg) but with a global bandwidth.

Source

pub fn fuzzy_kernel_weights(&self) -> Vec<f32>

Adaptive-bandwidth kernel weights with local connectivity.

Per-point sigma calibration (originated in t-SNE, van der Maaten & Hinton 2008) ensures every node has the same effective number of neighbors, preventing isolated singletons in sparse regions. The rho subtraction and fuzzy-union symmetrization follow UMAP (McInnes et al. 2018), matching the scanpy default for Leiden.

Algorithm:

  1. rho_i = distance to nearest neighbor (local connectivity)
  2. sigma_i via binary search: sum_j exp(-(d_ij - rho_i)/sigma_i) = log2(k)
  3. Directed weight: w(i→j) = exp(-(d_ij - rho_i) / sigma_i)
  4. Symmetrize: w_sym = w(i→j) + w(j→i) - w(i→j) * w(j→i)

Returns weights parallel to self.edges, all in (0, 1].

Source§

impl KnnGraph

Source

pub fn to_leiden_network(&self) -> (Network, f64)

Convert this KNN graph to a Leiden Network with modularity objective.

Node weights = weighted degree, edge weights = fuzzy kernel weights. Returns (network, total_edge_weight). Pass total_edge_weight to modularity_to_cpm_resolution to get a CPM-scale resolution.

Source

pub fn to_leiden_network_with(&self, weights: &[f32]) -> (Network, f64)

KnnGraph::to_leiden_network with the edge weights given, parallel to edges (e.g. from KnnGraph::from_rows_fuzzy).

Trait Implementations§

Source§

impl WeightedGraph for KnnGraph

Source§

fn num_nodes(&self) -> usize

Source§

fn num_edges(&self) -> usize

Source§

fn neighbors_with_weight<'a>( &'a self, node: usize, ) -> Box<dyn Iterator<Item = (usize, f32)> + 'a>

Source§

fn degree(&self, node: usize) -> usize

Source§

fn weighted_degree(&self, node: usize) -> f32

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Allocation for T
where T: RefUnwindSafe + Send + Sync,

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> ErasedDestructor for T
where T: 'static,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<SS, SP> SupersetOf<SS> for SP
where SS: SubsetOf<SP>,

Source§

fn to_subset(&self) -> Option<SS>

The inverse inclusion map: attempts to construct self from the equivalent element of its superset. Read more
Source§

fn is_in_subset(&self) -> bool

Checks if self is actually part of its subset T (and can be converted to it).
Source§

fn to_subset_unchecked(&self) -> SS

Use with care! Same as self.to_subset but without any property checks. Always succeeds.
Source§

fn from_subset(element: &SS) -> SP

The inclusion map: converts self to the equivalent element of its superset.
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V