lean_ctx_ext/core/graph_analysis/
surprising.rs1use std::collections::{HashMap, HashSet};
13
14use serde::Serialize;
15
16use super::dependency_edges;
17use crate::core::graph_provider::EdgeInfo;
18
19#[derive(Debug, Clone, Serialize, PartialEq)]
21pub struct SurprisingConnection {
22 pub from: String,
23 pub to: String,
24 pub score: f64,
25 pub cross_community: bool,
26 pub shared_neighbors: usize,
27}
28
29pub fn find_surprising_connections(
32 edges: &[EdgeInfo],
33 community: &HashMap<String, usize>,
34 limit: usize,
35) -> Vec<SurprisingConnection> {
36 let deps = dependency_edges(edges);
37 if deps.is_empty() {
38 return Vec::new();
39 }
40
41 let mut adj: HashMap<&str, HashSet<&str>> = HashMap::new();
43 for (u, v) in &deps {
44 adj.entry(*u).or_default().insert(*v);
45 adj.entry(*v).or_default().insert(*u);
46 }
47
48 let empty: HashSet<&str> = HashSet::new();
49 let mut seen: HashSet<(&str, &str)> = HashSet::new();
50 let mut out: Vec<SurprisingConnection> = Vec::new();
51
52 for (u, v) in &deps {
53 let key = if u <= v { (*u, *v) } else { (*v, *u) };
55 if !seen.insert(key) {
56 continue;
57 }
58
59 let nu = adj.get(*u).unwrap_or(&empty);
60 let nv = adj.get(*v).unwrap_or(&empty);
61 if nu.len() < 2 || nv.len() < 2 {
62 continue; }
64
65 let shared = nu
66 .intersection(nv)
67 .filter(|n| **n != *u && **n != *v)
68 .count();
69 let mut union: HashSet<&str> = nu.iter().copied().collect();
70 union.extend(nv.iter().copied());
71 union.remove(*u);
72 union.remove(*v);
73 let union_len = union.len().max(1);
74 let jaccard = shared as f64 / union_len as f64;
75
76 let cross = match (community.get(*u), community.get(*v)) {
77 (Some(a), Some(b)) => a != b,
78 _ => true,
79 };
80
81 let deg = (nu.len() + nv.len()) as f64;
82 let score = (1.0 - jaccard) * (if cross { 1.0 } else { 0.35 }) * (1.0 + deg).ln();
83
84 out.push(SurprisingConnection {
85 from: (*u).to_string(),
86 to: (*v).to_string(),
87 score: (score * 1000.0).round() / 1000.0,
88 cross_community: cross,
89 shared_neighbors: shared,
90 });
91 }
92
93 out.sort_by(|a, b| {
94 b.score
95 .partial_cmp(&a.score)
96 .unwrap_or(std::cmp::Ordering::Equal)
97 .then_with(|| a.from.cmp(&b.from))
98 .then_with(|| a.to.cmp(&b.to))
99 });
100 out.truncate(limit);
101 out
102}
103
104#[cfg(test)]
105mod tests {
106 use super::*;
107
108 fn e(from: &str, to: &str) -> EdgeInfo {
109 EdgeInfo {
110 from: from.into(),
111 to: to.into(),
112 kind: "import".into(),
113 weight: 1.0,
114 }
115 }
116
117 #[test]
118 fn bridge_edge_ranks_above_intra_cluster_edge() {
119 let edges = vec![
121 e("a", "b"),
122 e("b", "c"),
123 e("a", "c"),
124 e("x", "y"),
125 e("y", "z"),
126 e("x", "z"),
127 e("c", "x"), ];
129 let mut community = HashMap::new();
130 for n in ["a", "b", "c"] {
131 community.insert(n.to_string(), 0);
132 }
133 for n in ["x", "y", "z"] {
134 community.insert(n.to_string(), 1);
135 }
136
137 let surprising = find_surprising_connections(&edges, &community, 10);
138 assert!(!surprising.is_empty(), "`surprising` is empty");
139 let top = &surprising[0];
140 assert_eq!((top.from.as_str(), top.to.as_str()), ("c", "x"));
141 assert!(top.cross_community);
142 }
143
144 #[test]
145 fn empty_without_dependency_edges() {
146 let edges = vec![EdgeInfo {
147 from: "a".into(),
148 to: "b".into(),
149 kind: "sibling".into(),
150 weight: 1.0,
151 }];
152 {
153 let found = &find_surprising_connections(&edges, &HashMap::new(), 10);
154 assert!(found.is_empty(), "{found:?}");
155 }
156 }
157}