Skip to main content

nearest_neighbor_graph

Function nearest_neighbor_graph 

Source
pub fn nearest_neighbor_graph(
    points: &[Vec<f64>],
    metric: DistanceMetric,
    k: i64,
    cutoff: f64,
    directed: bool,
) -> IgraphResult<Graph>
Expand description

Build the k-nearest-neighbor graph of a point set.

points holds one row per point with a shared, arbitrary dimensionality (inferred from the first row). For each point the k nearest other points within cutoff are connected by an outgoing arc.

  • metricDistanceMetric::Euclidean (L2) or DistanceMetric::Manhattan (L1).
  • k — maximum neighbours per point; a negative value means “no limit” (every point within cutoff). k == 0 produces an edgeless graph.
  • cutoff — maximum connection distance; a negative value (or f64::INFINITY) means “no cutoff”. The comparison is strict, so a point exactly at distance cutoff is excluded.
  • directed — when false, the directed neighbour graph is collapsed to undirected, merging reciprocal arcs into one edge.

§Errors

§Examples

use rust_igraph::{nearest_neighbor_graph, DistanceMetric};

// Three points on a line: each links to its single nearest neighbour.
let pts = vec![vec![0.0], vec![1.0], vec![5.0]];
let g = nearest_neighbor_graph(&pts, DistanceMetric::Euclidean, 1, -1.0, true).unwrap();
assert!(g.is_directed());
assert_eq!(g.vcount(), 3);
// 0→1, 1→0, 2→1
assert_eq!(g.ecount(), 3);