From 065bffca3f3acd4804b581436b65c1bb7a0d5ef1 Mon Sep 17 00:00:00 2001 From: KARTHIKEYAN MUTHU Date: Sun, 17 Mar 2024 15:35:33 -0400 Subject: [PATCH] Adding degree centrality function --- rustworkx-core/src/centrality.rs | 30 ++++++++++++++++++++++++++++++ src/centrality.rs | 20 ++++++++++++++++++++ 2 files changed, 50 insertions(+) diff --git a/rustworkx-core/src/centrality.rs b/rustworkx-core/src/centrality.rs index 35683bbc8..baf44a762 100644 --- a/rustworkx-core/src/centrality.rs +++ b/rustworkx-core/src/centrality.rs @@ -140,6 +140,36 @@ where betweenness } +/// Computes the degree centrality of nodes in a graph. +/// +/// Degree centrality is defined as the number of edges incident upon a node +/// normalized by the maximum possible degree in a simple graph (n - 1, where n is the number of nodes). +/// +/// Arguments: +/// * `graph` - The graph object to compute degree centrality for. +/// +/// Returns: +/// A `Vec` containing the degree centrality of each node in the graph. +pub fn degree_centrality(graph: G) -> Result>, E> + where + G: IntoNodeIdentifiers + NodeCount, + { + let num_nodes = graph.node_count() as f64; + let mut centrality_values = vec![0.0; graph.node_count()]; + { + let degree = graph.edges(node).count() as f64; + let centrality = if num_nodes <= 1.0 { + 0.0 + } else { + degree / (num_nodes - 1.0) + }; + centrality_values[graph.to_index(node)] = centrality; + } + + Ok(Some(centrality_values)) + } + + /// Compute the edge betweenness centrality of all edges in a graph. /// /// The algorithm used in this function is based on: diff --git a/src/centrality.rs b/src/centrality.rs index ca055cec3..c4b2a2ab7 100644 --- a/src/centrality.rs +++ b/src/centrality.rs @@ -97,6 +97,26 @@ pub fn graph_betweenness_centrality( } } +/// A Python function wrapper for degree_centrality + +fn degree_centrality_py( + py: Python, + graph: &digraph::PyDiGraph, +) -> PyResult { + // Convert Python object to Rust type + let graph_rust = match graph.extract::() { + Ok(g) => g, + Err(e) => return Err(e.into()), + }; + // Call the Rust function + match degree_centrality(graph_rust) { + Ok(Some(values)) => Ok(Some(values)), + Ok(None) => Ok(None), + Err(e) => Err(e.into()), + } +} + + /// Compute the betweenness centrality of all nodes in a PyDiGraph. /// /// Betweenness centrality of a node :math:`v` is the sum of the