1use petgraph::graph::{DiGraph, NodeIndex};
32
33use petgraph::visit::{Bfs, Reversed};
34
35use serde::{Deserialize, Serialize};
36
37use std::collections::HashMap;
38
39#[derive(Debug, Clone, Serialize, Deserialize)]
42
43pub struct CascadeResult {
44 pub defeated_node: String,
45
46 pub affected_nodes: Vec<String>,
47
48 pub cascade_depth: u32,
49
50 pub defeasibility_scores: HashMap<String, f64>,
51
52 pub total_affected: usize,
53}
54
55struct EpistemicGraph<'a> {
64 graph: DiGraph<&'a str, ()>,
65
66 node_map: HashMap<&'a str, NodeIndex>,
67}
68
69impl<'a> EpistemicGraph<'a> {
70 fn from_adjacency(adjacency: &'a HashMap<String, Vec<String>>) -> Result<Self, String> {
73 let mut graph = DiGraph::<&'a str, ()>::new();
74
75 let mut node_map: HashMap<&'a str, NodeIndex> = HashMap::new();
76
77 for (parent, children) in adjacency {
79 node_map
80 .entry(parent.as_str())
81 .or_insert_with(|| graph.add_node(parent.as_str()));
82
83 for child in children {
84 node_map
85 .entry(child.as_str())
86 .or_insert_with(|| graph.add_node(child.as_str()));
87 }
88 }
89
90 for (parent, children) in adjacency {
92 let &parent_idx = node_map
93 .get(parent.as_str())
94 .ok_or_else(|| format!("Parent node {} not found", parent))?;
95
96 for child in children {
97 let &child_idx = node_map
98 .get(child.as_str())
99 .ok_or_else(|| format!("Child node {} not found", child))?;
100
101 graph.add_edge(parent_idx, child_idx, ());
102 }
103 }
104
105 Ok(Self { graph, node_map })
106 }
107
108 fn reversed_view(&self) -> Reversed<&DiGraph<&'a str, ()>> {
113 Reversed(&self.graph)
114 }
115}
116
117pub struct BlastRadiusCalculator;
128
129impl BlastRadiusCalculator {
130 pub fn calculate_blast_radius(
139 defeated_node_cid: &str,
140
141 adjacency: &HashMap<String, Vec<String>>,
142 ) -> CascadeResult {
143 let eg = match EpistemicGraph::from_adjacency(adjacency) {
144 Ok(graph) => graph,
145 Err(_) => {
146 return CascadeResult {
147 defeated_node: defeated_node_cid.to_string(),
148 affected_nodes: Vec::new(),
149 cascade_depth: 0,
150 defeasibility_scores: HashMap::new(),
151 total_affected: 0,
152 }
153 }
154 };
155
156 let start_idx = match eg.node_map.get(defeated_node_cid) {
157 Some(&idx) => idx,
158
159 None => {
160 return CascadeResult {
161 defeated_node: defeated_node_cid.to_string(),
162
163 affected_nodes: Vec::new(),
164
165 cascade_depth: 0,
166
167 defeasibility_scores: HashMap::new(),
168
169 total_affected: 0,
170 };
171 }
172 };
173
174 let mut bfs = Bfs::new(&eg.graph, start_idx);
177
178 let mut depth_map: HashMap<NodeIndex, u32> = HashMap::new();
179
180 depth_map.insert(start_idx, 0);
181
182 let mut affected: Vec<String> = Vec::new();
183
184 let mut defeasibility: HashMap<String, f64> = HashMap::new();
185
186 let mut max_depth: u32 = 0;
187
188 while let Some(node_idx) = bfs.next(&eg.graph) {
189 let node_label = eg.graph[node_idx];
190
191 let depth = if node_idx == start_idx {
194 0
195 } else {
196 eg.graph
199 .neighbors_directed(node_idx, petgraph::Direction::Incoming)
200 .filter_map(|pred| depth_map.get(&pred))
201 .min()
202 .map(|d| d + 1)
203 .unwrap_or(0)
204 };
205
206 depth_map.insert(node_idx, depth);
207
208 max_depth = max_depth.max(depth);
209
210 if node_label != defeated_node_cid {
211 affected.push(node_label.to_string());
212 }
213
214 defeasibility.insert(node_label.to_string(), 1.0 / (1.0 + depth as f64));
217 }
218
219 CascadeResult {
220 defeated_node: defeated_node_cid.to_string(),
221
222 affected_nodes: affected.clone(),
223
224 cascade_depth: max_depth,
225
226 defeasibility_scores: defeasibility,
227
228 total_affected: affected.len(),
229 }
230 }
231
232 pub fn compute_defeasibility_score(
243 node_cid: &str,
244
245 adjacency: &HashMap<String, Vec<String>>,
246 ) -> f64 {
247 let eg = match EpistemicGraph::from_adjacency(adjacency) {
248 Ok(graph) => graph,
249 Err(_) => return 0.0,
250 };
251
252 let start_idx = match eg.node_map.get(node_cid) {
253 Some(&idx) => idx,
254
255 None => return 0.0,
256 };
257
258 let rev = eg.reversed_view();
261
262 let mut bfs = Bfs::new(&rev, start_idx);
263
264 let mut ancestor_count: usize = 0;
265
266 while let Some(node_idx) = bfs.next(&rev) {
267 if node_idx != start_idx {
268 ancestor_count += 1;
269 }
270 }
271
272 let total_nodes = adjacency.len().max(1);
273
274 (ancestor_count as f64 / total_nodes as f64).min(1.0)
275 }
276}
277
278#[cfg(test)]
279
280mod tests {
281
282 use super::*;
283
284 fn sample_graph() -> HashMap<String, Vec<String>> {
285 let mut g = HashMap::new();
286
287 g.insert("root".to_string(), vec!["a".to_string(), "b".to_string()]);
288
289 g.insert("a".to_string(), vec!["c".to_string(), "d".to_string()]);
290
291 g.insert("b".to_string(), vec!["d".to_string(), "e".to_string()]);
292
293 g.insert("c".to_string(), vec![]);
294
295 g.insert("d".to_string(), vec!["f".to_string()]);
296
297 g.insert("e".to_string(), vec![]);
298
299 g.insert("f".to_string(), vec![]);
300
301 g
302 }
303
304 #[test]
305
306 fn test_blast_radius_from_root() {
307 let graph = sample_graph();
308
309 let result = BlastRadiusCalculator::calculate_blast_radius("root", &graph);
310
311 assert_eq!(result.defeated_node, "root");
312
313 assert!(result.total_affected >= 5);
316
317 assert!(result.cascade_depth >= 2);
318
319 assert_eq!(result.defeasibility_scores["root"], 1.0);
320 }
321
322 #[test]
323
324 fn test_blast_radius_leaf_node() {
325 let graph = sample_graph();
326
327 let result = BlastRadiusCalculator::calculate_blast_radius("f", &graph);
328
329 assert_eq!(result.total_affected, 0);
330
331 assert_eq!(result.cascade_depth, 0);
332 }
333
334 #[test]
335
336 fn test_blast_radius_missing_node() {
337 let graph = sample_graph();
338
339 let result = BlastRadiusCalculator::calculate_blast_radius("nonexistent", &graph);
340
341 assert_eq!(result.total_affected, 0);
342
343 assert_eq!(result.cascade_depth, 0);
344 }
345
346 #[test]
347
348 fn test_defeasibility_score_root_has_no_ancestors() {
349 let graph = sample_graph();
350
351 let score = BlastRadiusCalculator::compute_defeasibility_score("root", &graph);
352
353 assert_eq!(score, 0.0);
354 }
355
356 #[test]
357
358 fn test_defeasibility_score_deep_node_has_ancestors() {
359 let graph = sample_graph();
360
361 let score = BlastRadiusCalculator::compute_defeasibility_score("f", &graph);
362
363 assert!(score > 0.0);
364 }
365}