Skip to content

Commit

Permalink
Adding degree centrality function
Browse files Browse the repository at this point in the history
  • Loading branch information
TheMLEngineer committed Mar 17, 2024
1 parent b5ac124 commit 065bffc
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 0 deletions.
30 changes: 30 additions & 0 deletions rustworkx-core/src/centrality.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<f64>` containing the degree centrality of each node in the graph.
pub fn degree_centrality<G>(graph: G) -> Result<Option<Vec<f64>>, 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:
Expand Down
20 changes: 20 additions & 0 deletions src/centrality.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<CentralityMapping> {
// Convert Python object to Rust type
let graph_rust = match graph.extract::<SomeRustGraphType>() {
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
Expand Down

0 comments on commit 065bffc

Please sign in to comment.