leiden-rs 0.7.0

High-performance Leiden community detection algorithm for graphs in Rust
Documentation
//! WebAssembly bindings for the Leiden community detection algorithm.
//!
//! Enable with the `wasm` feature flag. Provides a JavaScript-friendly API
//! that takes a flat edge list and returns community assignments.

use crate::graph::GraphDataBuilder;
use crate::{run_multiplex, MultiplexConfig, QualityType};

/// Run Leiden community detection from a flat edge list.
///
/// # Arguments
/// * `edges` - Flat array of `[src0, dst0, weight0, src1, dst1, weight1, ...]`
/// * `num_nodes` - Total number of nodes (IDs must be in `0..num_nodes`)
/// * `seed` - Optional RNG seed for reproducibility
///
/// # Returns
/// Community assignment vector where `result[i]` is the community ID of node `i`.
#[cfg_attr(feature = "wasm", wasm_bindgen::prelude::wasm_bindgen)]
pub fn leiden_from_edgelist(edges: &[f64], num_nodes: usize, seed: Option<u64>) -> Vec<usize> {
    let edge_tuples: Vec<(usize, usize, f64)> = edges
        .chunks_exact(3)
        .map(|c| (c[0] as usize, c[1] as usize, c[2]))
        .collect();

    let mut builder = GraphDataBuilder::new(num_nodes);
    for &(u, v, w) in &edge_tuples {
        if builder.add_edge(u, v, w).is_err() {
            return (0..num_nodes).collect();
        }
    }
    let graph_data = match builder.build() {
        Ok(g) => g,
        Err(_) => return (0..num_nodes).collect(),
    };

    let config = MultiplexConfig {
        seed,
        max_iterations: 100,
        resolution: 1.0,
        quality: QualityType::Modularity,
        epsilon: 1e-10,
        max_comm_size: 0,
        layer_weights: vec![1.0],
    };

    match run_multiplex(&[graph_data], &config) {
        Ok(result) => {
            let membership: Vec<usize> = (0..num_nodes)
                .map(|i| result.partition.community_of(i))
                .collect();
            membership
        }
        Err(_) => (0..num_nodes).collect(),
    }
}