use crate::edge::EdgeKind;
use crate::graph::{ArborGraph, NodeId};
use petgraph::visit::{EdgeRef, IntoEdgeReferences};
use std::collections::HashMap;
const CONVERGENCE_EPSILON: f64 = 1e-9;
#[derive(Debug, Default, Clone)]
pub struct CentralityScores {
raw: HashMap<NodeId, f64>,
percentile: HashMap<NodeId, f64>,
}
impl CentralityScores {
pub fn get(&self, id: NodeId) -> f64 {
self.percentile.get(&id).copied().unwrap_or(0.0)
}
pub fn get_raw(&self, id: NodeId) -> f64 {
self.raw.get(&id).copied().unwrap_or(0.0)
}
pub fn into_map(self) -> HashMap<NodeId, f64> {
self.percentile
}
pub fn into_raw_map(self) -> HashMap<NodeId, f64> {
self.raw
}
pub fn into_parts(self) -> (HashMap<NodeId, f64>, HashMap<NodeId, f64>) {
(self.raw, self.percentile)
}
fn from_raw(nodes: Vec<NodeId>, scores: Vec<f64>) -> Self {
let n = scores.len();
let mut percentile = vec![0.0f64; n];
if n == 1 {
percentile[0] = 1.0;
} else if n > 1 {
let mut order: Vec<usize> = (0..n).collect();
order.sort_by(|&a, &b| {
scores[a]
.partial_cmp(&scores[b])
.unwrap_or(std::cmp::Ordering::Equal)
.then_with(|| a.cmp(&b))
});
let denom = (n - 1) as f64;
let mut i = 0;
while i < n {
let mut j = i;
while j + 1 < n && scores[order[j + 1]] == scores[order[i]] {
j += 1;
}
let rank = i as f64 / denom;
for slot in &order[i..=j] {
percentile[*slot] = rank;
}
i = j + 1;
}
}
Self {
raw: nodes.iter().copied().zip(scores).collect(),
percentile: nodes.into_iter().zip(percentile).collect(),
}
}
}
fn is_test_file(file: &str) -> bool {
let lower = file.to_lowercase();
lower.contains("/test")
|| lower.contains("\\test")
|| lower.contains("/spec")
|| lower.contains("\\spec")
|| lower.contains("__test__")
|| lower.contains("_test.")
|| lower.contains(".test.")
|| lower.contains(".spec.")
|| lower.contains("/fixture")
|| lower.contains("/mock")
|| lower.contains("/stub")
|| lower.contains("/fake")
|| lower.ends_with("_test.go")
|| lower.ends_with("_test.py")
|| lower.ends_with("_test.rs")
|| lower.ends_with("test.ts")
|| lower.ends_with("test.js")
}
pub fn compute_centrality(graph: &ArborGraph, iterations: usize, damping: f64) -> CentralityScores {
compute_centrality_warm(graph, iterations, damping, None)
}
pub fn compute_centrality_warm(
graph: &ArborGraph,
iterations: usize,
damping: f64,
previous: Option<&HashMap<NodeId, f64>>,
) -> CentralityScores {
let node_count = graph.node_count();
if node_count == 0 {
return CentralityScores::default();
}
let nodes: Vec<NodeId> = graph.node_indexes().collect();
let n = nodes.len();
let pos: HashMap<NodeId, usize> = nodes.iter().enumerate().map(|(i, &id)| (id, i)).collect();
let weights: Vec<f64> = nodes
.iter()
.map(|&id| match graph.get(id) {
Some(node) if is_test_file(&node.file) => 0.1,
_ => 1.0,
})
.collect();
let mut out_degree: Vec<usize> = vec![0; n];
let mut in_edges: Vec<Vec<u32>> = vec![Vec::new(); n];
for edge in graph.graph.edge_references() {
if edge.weight().kind != EdgeKind::Calls {
continue;
}
let (Some(&source), Some(&target)) = (pos.get(&edge.source()), pos.get(&edge.target()))
else {
continue;
};
out_degree[source] += 1;
in_edges[target].push(source as u32);
}
for degree in out_degree.iter_mut() {
*degree = (*degree).max(1);
}
let initial_score = 1.0 / n as f64;
let base = (1.0 - damping) / n as f64;
let gather = |scores: &[f64], target: usize| -> f64 {
in_edges[target]
.iter()
.map(|&source| {
let source = source as usize;
weights[source] * scores[source] / out_degree[source] as f64
})
.sum()
};
let mut scores: Vec<f64> = match previous {
Some(prev) if !prev.is_empty() => {
let mut warm: Vec<f64> = nodes
.iter()
.map(|id| prev.get(id).copied().unwrap_or(initial_score))
.collect();
let sum_v: f64 = warm.iter().sum();
let f_v: f64 =
n as f64 * base + damping * (0..n).map(|t| gather(&warm, t)).sum::<f64>();
let c = 1.0 - (f_v - sum_v) / (n as f64 * base);
if c.is_finite() && c > f64::EPSILON {
for score in warm.iter_mut() {
*score /= c;
}
}
warm
}
_ => vec![initial_score; n],
};
let mut next: Vec<f64> = vec![0.0; n];
for _ in 0..iterations {
let mut max_delta = 0.0f64;
for target in 0..n {
let score = base + damping * gather(&scores, target);
max_delta = max_delta.max((score - scores[target]).abs());
next[target] = score;
}
std::mem::swap(&mut scores, &mut next);
if max_delta < CONVERGENCE_EPSILON {
break;
}
}
CentralityScores::from_raw(nodes, scores)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::edge::{Edge, EdgeKind};
use arbor_core::{CodeNode, NodeKind};
#[test]
fn test_centrality_empty_graph() {
let graph = ArborGraph::new();
let scores = compute_centrality(&graph, 10, 0.85);
assert!(scores.percentile.is_empty());
}
#[test]
fn test_centrality_single_node() {
let mut graph = ArborGraph::new();
let node = CodeNode::new("foo", "foo", NodeKind::Function, "test.rs");
graph.add_node(node);
let scores = compute_centrality(&graph, 10, 0.85);
assert_eq!(scores.percentile.len(), 1);
}
#[test]
fn test_centrality_popular_node_ranks_higher() {
let mut graph = ArborGraph::new();
let popular = CodeNode::new("popular", "popular", NodeKind::Function, "test.rs");
let popular_idx = graph.add_node(popular);
for i in 0..5 {
let caller = CodeNode::new(
format!("caller{}", i),
format!("caller{}", i),
NodeKind::Function,
"test.rs",
);
let caller_idx = graph.add_node(caller);
graph.add_edge(caller_idx, popular_idx, Edge::new(EdgeKind::Calls));
}
let scores = compute_centrality(&graph, 20, 0.85);
let popular_score = scores.get(popular_idx);
assert!(popular_score > 0.5, "Popular node should rank high");
}
#[test]
fn test_centrality_test_callers_deweighted() {
let mut graph = ArborGraph::new();
let prod_target = CodeNode::new("prod_target", "prod_target", NodeKind::Function, "a.rs");
let prod_target_idx = graph.add_node(prod_target);
let test_target = CodeNode::new("test_target", "test_target", NodeKind::Function, "a.rs");
let test_target_idx = graph.add_node(test_target);
let prod_caller = CodeNode::new("prod_caller", "prod_caller", NodeKind::Function, "b.rs");
let prod_caller_idx = graph.add_node(prod_caller);
graph.add_edge(prod_caller_idx, prod_target_idx, Edge::new(EdgeKind::Calls));
let test_caller = CodeNode::new(
"test_caller",
"test_caller",
NodeKind::Function,
"tests/b_test.rs",
);
let test_caller_idx = graph.add_node(test_caller);
graph.add_edge(test_caller_idx, test_target_idx, Edge::new(EdgeKind::Calls));
let scores = compute_centrality(&graph, 20, 0.85);
assert!(
scores.get(prod_target_idx) > scores.get(test_target_idx),
"production callers must outweigh test callers"
);
}
#[test]
fn test_warm_start_matches_cold_start() {
let mut graph = ArborGraph::new();
let hub = graph.add_node(CodeNode::new("hub", "hub", NodeKind::Function, "hub.rs"));
let mut previous = std::collections::HashMap::new();
for i in 0..10 {
let caller = graph.add_node(CodeNode::new(
format!("c{}", i),
format!("c{}", i),
NodeKind::Function,
"c.rs",
));
graph.add_edge(caller, hub, Edge::new(EdgeKind::Calls));
previous.insert(caller, 0.3);
}
previous.insert(hub, 1.0);
let cold = compute_centrality(&graph, 50, 0.85);
let warm = compute_centrality_warm(&graph, 50, 0.85, Some(&previous));
for idx in graph.node_indexes() {
assert!(
(cold.get(idx) - warm.get(idx)).abs() < 1e-6,
"warm start must converge to the same fixed point"
);
}
}
#[test]
fn test_only_calls_edges_contribute() {
let mut graph = ArborGraph::new();
let a = graph.add_node(CodeNode::new("a", "a", NodeKind::Function, "a.rs"));
let b = graph.add_node(CodeNode::new("b", "b", NodeKind::Function, "b.rs"));
let c = graph.add_node(CodeNode::new("c", "c", NodeKind::Function, "c.rs"));
graph.add_edge(a, b, Edge::new(EdgeKind::Calls));
graph.add_edge(a, c, Edge::new(EdgeKind::Imports));
let scores = compute_centrality(&graph, 20, 0.85);
assert!(
scores.get(b) > scores.get(c),
"import edges must not count as calls"
);
}
fn star(spokes: usize) -> (ArborGraph, NodeId) {
let mut graph = ArborGraph::new();
let hub = graph.add_node(CodeNode::new("hub", "hub", NodeKind::Function, "hub.rs"));
for i in 0..spokes {
let name = format!("s{i}");
let s = graph.add_node(CodeNode::new(
name.clone(),
name,
NodeKind::Function,
format!("s{i}.rs"),
));
graph.add_edge(s, hub, Edge::new(EdgeKind::Calls));
}
(graph, hub)
}
#[test]
fn percentile_is_comparable_across_graph_shapes() {
let (small, small_hub) = star(3);
let (large, large_hub) = star(60);
let small_scores = compute_centrality(&small, 20, 0.85);
let large_scores = compute_centrality(&large, 20, 0.85);
assert_eq!(small_scores.get(small_hub), 1.0);
assert_eq!(large_scores.get(large_hub), 1.0);
for (graph, scores) in [(&small, &small_scores), (&large, &large_scores)] {
for idx in graph.node_indexes() {
let is_hub = graph.get(idx).map(|n| n.name == "hub").unwrap_or(false);
if !is_hub {
assert_eq!(scores.get(idx), 0.0, "tied spokes share the bottom rank");
}
}
}
}
#[test]
fn adding_a_hub_does_not_rescale_unrelated_nodes() {
let mut graph = ArborGraph::new();
let a = graph.add_node(CodeNode::new("a", "a", NodeKind::Function, "a.rs"));
let b = graph.add_node(CodeNode::new("b", "b", NodeKind::Function, "b.rs"));
let c = graph.add_node(CodeNode::new("c", "c", NodeKind::Function, "c.rs"));
graph.add_edge(a, b, Edge::new(EdgeKind::Calls));
graph.add_edge(c, b, Edge::new(EdgeKind::Calls));
let before = compute_centrality(&graph, 20, 0.85).get(b);
let hub = graph.add_node(CodeNode::new("hub", "hub", NodeKind::Function, "hub.rs"));
for i in 0..20 {
let name = format!("x{i}");
let x = graph.add_node(CodeNode::new(
name.clone(),
name,
NodeKind::Function,
format!("x{i}.rs"),
));
graph.add_edge(x, hub, Edge::new(EdgeKind::Calls));
}
let after = compute_centrality(&graph, 20, 0.85).get(b);
assert!(
after > 0.5,
"b should remain in the upper half, got {after} (was {before})"
);
}
#[test]
fn percentile_ties_are_stable_and_ordering_preserved() {
let (graph, hub) = star(5);
let scores = compute_centrality(&graph, 20, 0.85);
let again = compute_centrality(&graph, 20, 0.85);
for idx in graph.node_indexes() {
assert_eq!(scores.get(idx), again.get(idx));
assert_eq!(scores.get_raw(idx), again.get_raw(idx));
}
for idx in graph.node_indexes() {
if idx != hub {
assert!(scores.get_raw(hub) > scores.get_raw(idx));
assert!(scores.get(hub) > scores.get(idx));
}
}
}
#[test]
fn single_node_graph_is_top_ranked() {
let mut graph = ArborGraph::new();
let only = graph.add_node(CodeNode::new("solo", "solo", NodeKind::Function, "a.rs"));
let scores = compute_centrality(&graph, 20, 0.85);
assert_eq!(scores.get(only), 1.0);
}
#[test]
fn warm_start_from_raw_matches_cold_result() {
let (graph, _) = star(30);
let cold = compute_centrality(&graph, 20, 0.85);
let warm = compute_centrality_warm(&graph, 20, 0.85, Some(&cold.clone().into_raw_map()));
for idx in graph.node_indexes() {
assert!(
(cold.get_raw(idx) - warm.get_raw(idx)).abs() < 1e-9,
"warm start must converge to the same fixed point"
);
}
}
}