lean_ctx_ext/core/community/
mod.rs1use std::collections::HashMap;
12
13use rusqlite::Connection;
14use serde::Serialize;
15
16use crate::core::graph_provider::GraphProvider;
17use crate::core::property_graph::GraphSource;
18
19pub mod graph;
20pub mod hardening;
21pub mod leiden;
22pub mod stable_ids;
23#[cfg(test)]
24pub mod tests;
25
26use graph::{AdjGraph, edge_counts};
27
28#[derive(Debug, Clone, Serialize)]
29pub struct Community {
30 pub id: usize,
31 pub files: Vec<String>,
32 pub internal_edges: usize,
33 pub external_edges: usize,
34 pub cohesion: f64,
35}
36
37#[derive(Debug, Clone, Serialize)]
38pub struct CommunityResult {
39 pub communities: Vec<Community>,
40 pub modularity: f64,
41 pub node_count: usize,
42 pub edge_count: usize,
43}
44
45impl CommunityResult {
46 fn empty() -> Self {
47 Self {
48 communities: Vec::new(),
49 modularity: 0.0,
50 node_count: 0,
51 edge_count: 0,
52 }
53 }
54
55 pub fn assignment(&self) -> HashMap<String, usize> {
57 self.assignment_min_size(1)
58 }
59
60 pub fn assignment_min_size(&self, min_size: usize) -> HashMap<String, usize> {
65 let mut map = HashMap::new();
66 for community in &self.communities {
67 if community.files.len() < min_size {
68 continue;
69 }
70 for file in &community.files {
71 map.insert(file.clone(), community.id);
72 }
73 }
74 map
75 }
76}
77
78pub fn detect_communities(conn: &Connection) -> CommunityResult {
82 let graph = AdjGraph::from_property_graph(conn);
83 analyze(&graph, None).1
84}
85
86pub fn detect_communities_stable<S: GraphSource + ?Sized>(
93 source: &S,
94 project_root: &str,
95) -> CommunityResult {
96 let graph = AdjGraph::from_property_graph(source);
97 detect_stable(&graph, project_root)
98}
99
100pub fn detect_communities_for_provider(gp: &GraphProvider, project_root: &str) -> CommunityResult {
103 let graph = AdjGraph::from_provider(gp);
104 detect_stable(&graph, project_root)
105}
106
107fn detect_stable(graph: &AdjGraph, project_root: &str) -> CommunityResult {
108 if graph.node_count() == 0 {
109 return CommunityResult::empty();
110 }
111 let previous = stable_ids::load_previous(project_root).map(|mut previous| {
115 previous.retain(|file, _| graph.node_to_idx.contains_key(file));
116 previous
117 });
118 let (assignment, result) = analyze(graph, previous.as_ref());
119 stable_ids::save_assignment(project_root, &graph.node_ids, &assignment);
120 result
121}
122
123fn analyze(
127 graph: &AdjGraph,
128 previous: Option<&HashMap<String, usize>>,
129) -> (Vec<usize>, CommunityResult) {
130 let n = graph.node_count();
131 if n == 0 {
132 return (Vec::new(), CommunityResult::empty());
133 }
134
135 let mut assignment = hardening::partition_with_hub_exclusion(graph);
136 hardening::split_oversized_and_incohesive(graph, &mut assignment);
137 let mut assignment = stable_ids::canonicalize(graph, &assignment);
138 if let Some(prev) = previous
139 && !prev.is_empty()
140 {
141 assignment = stable_ids::remap_to_previous(graph, &assignment, prev);
142 }
143
144 let result = build_result(graph, &assignment);
145 (assignment, result)
146}
147
148fn build_result(graph: &AdjGraph, assignment: &[usize]) -> CommunityResult {
149 let mut groups: HashMap<usize, Vec<usize>> = HashMap::new();
150 for (i, &c) in assignment.iter().enumerate() {
151 groups.entry(c).or_default().push(i);
152 }
153
154 let mut communities: Vec<Community> = groups
155 .into_iter()
156 .map(|(id, mut members)| {
157 members.sort_unstable();
158 let (internal, external) = edge_counts(graph, &members);
159 let total = (internal + external).max(1) as f64;
160 Community {
161 id,
162 files: members.iter().map(|&i| graph.node_ids[i].clone()).collect(),
163 internal_edges: internal,
164 external_edges: external,
165 cohesion: internal as f64 / total,
166 }
167 })
168 .collect();
169
170 communities.sort_by(|a, b| {
172 b.files
173 .len()
174 .cmp(&a.files.len())
175 .then(
176 b.cohesion
177 .partial_cmp(&a.cohesion)
178 .unwrap_or(std::cmp::Ordering::Equal),
179 )
180 .then(a.id.cmp(&b.id))
181 });
182
183 CommunityResult {
184 communities,
185 modularity: leiden::compute_modularity(graph, assignment),
186 node_count: graph.node_count(),
187 edge_count: graph.edge_count(),
188 }
189}