leiden-rs 0.7.0

High-performance Leiden community detection algorithm for graphs in Rust
Documentation
//! Utility functions for loading and evaluating graphs.

use crate::error::Result;
use crate::graph::GraphDataBuilder;
use crate::partition::Partition;
use crate::quality::{Modularity, QualityFunction};

/// Load an undirected unweighted graph from an edge-list string.
///
/// Input format: one edge per line as `source target` (0-indexed integer node IDs).
/// Blank lines and lines starting with `#` are skipped. Duplicate edges are
/// silently collapsed — only the first occurrence of each `(u, v)` pair is kept.
///
/// Returns a [`GraphData`](crate::graph::GraphData) with `node_count` vertices.
pub fn load_edgelist(data: &str, node_count: usize) -> Result<crate::graph::GraphData> {
    let mut builder = GraphDataBuilder::new(node_count);

    let mut seen = rustc_hash::FxHashSet::default();
    for line in data.lines() {
        let line = line.trim();
        if line.is_empty() || line.starts_with('#') {
            continue;
        }
        let parts: Vec<&str> = line.split_whitespace().collect();
        if parts.len() < 2 {
            continue;
        }
        let src: usize = match parts[0].parse() {
            Ok(v) => v,
            Err(_) => continue,
        };
        let dst: usize = match parts[1].parse() {
            Ok(v) => v,
            Err(_) => continue,
        };
        if src >= node_count || dst >= node_count || src == dst {
            continue;
        }
        let key = (src.min(dst), src.max(dst));
        if seen.insert(key) {
            builder.add_edge(src, dst, 1.0)?;
        }
    }
    builder.build()
}

/// Compute the Newman-Girvan modularity (γ = 1.0) of a partition.
pub fn modularity(data: &crate::graph::GraphData, partition: &Partition) -> f64 {
    Modularity::with_resolution(1.0).total_quality(data, partition)
}