leiden-rs 0.7.0

High-performance Leiden community detection algorithm for graphs in Rust
Documentation
//! Adapter for converting a [`petgraph::Graph`] into a [`crate::graph::GraphData`].

use petgraph::visit::EdgeRef;

use crate::error::Result;
use crate::graph::GraphDataBuilder;

/// Convert a petgraph graph into a [`crate::graph::GraphData`].
///
/// Automatically detects whether the graph is directed or undirected and
/// constructs the appropriate CSR representation. Supports arbitrary edge
/// weight types via `E: Into<f64>`.
pub fn from_petgraph<N, E, Ty, Ix>(
    graph: &petgraph::Graph<N, E, Ty, Ix>,
) -> Result<crate::graph::GraphData>
where
    E: Into<f64> + Copy,
    Ty: petgraph::EdgeType,
    Ix: petgraph::graph::IndexType,
{
    let n = graph.node_count();
    let mut builder = GraphDataBuilder::new(n);

    if Ty::is_directed() {
        builder = builder.directed();
    }

    for edge in graph.edge_references() {
        let (u, v) = graph.edge_endpoints(edge.id()).unwrap();
        let weight: f64 = (*edge.weight()).into();
        builder.add_edge(u.index(), v.index(), weight)?;
    }

    builder.build()
}