1use std::collections::HashMap;
7use chrono::{DateTime, Utc};
8
9use crate::optimized::{OptimizedDiscoveryEngine, SignificantPattern};
10use crate::ruvector_native::{Domain, PatternType};
11
12const COLOR_CLIMATE: &str = "\x1b[34m"; const COLOR_FINANCE: &str = "\x1b[32m"; const COLOR_RESEARCH: &str = "\x1b[33m"; const COLOR_MEDICAL: &str = "\x1b[36m"; const COLOR_CROSS: &str = "\x1b[35m"; const COLOR_RESET: &str = "\x1b[0m";
19const COLOR_BRIGHT: &str = "\x1b[1m";
20const COLOR_DIM: &str = "\x1b[2m";
21
22const BOX_H: char = '─';
24const BOX_V: char = '│';
25const BOX_TL: char = '┌';
26const BOX_TR: char = '┐';
27const BOX_BL: char = '└';
28const BOX_BR: char = '┘';
29const BOX_CROSS: char = '┼';
30const BOX_T_DOWN: char = '┬';
31const BOX_T_UP: char = '┴';
32const BOX_T_RIGHT: char = '├';
33const BOX_T_LEFT: char = '┤';
34
35fn domain_color(domain: Domain) -> &'static str {
37 match domain {
38 Domain::Climate => COLOR_CLIMATE,
39 Domain::Finance => COLOR_FINANCE,
40 Domain::Research => COLOR_RESEARCH,
41 Domain::Medical => COLOR_MEDICAL,
42 Domain::Economic => "\x1b[38;5;214m", Domain::Genomics => "\x1b[38;5;46m", Domain::Physics => "\x1b[38;5;33m", Domain::Seismic => "\x1b[38;5;130m", Domain::Ocean => "\x1b[38;5;39m", Domain::Space => "\x1b[38;5;141m", Domain::Transportation => "\x1b[38;5;208m", Domain::Geospatial => "\x1b[38;5;118m", Domain::Government => "\x1b[38;5;243m", Domain::CrossDomain => COLOR_CROSS,
52 }
53}
54
55fn domain_char(domain: Domain) -> char {
57 match domain {
58 Domain::Climate => 'C',
59 Domain::Finance => 'F',
60 Domain::Research => 'R',
61 Domain::Medical => 'M',
62 Domain::Economic => 'E',
63 Domain::Genomics => 'G',
64 Domain::Physics => 'P',
65 Domain::Seismic => 'S',
66 Domain::Ocean => 'O',
67 Domain::Space => 'A', Domain::Transportation => 'T',
69 Domain::Geospatial => 'L', Domain::Government => 'V', Domain::CrossDomain => 'X',
72 }
73}
74
75pub fn render_graph_ascii(engine: &OptimizedDiscoveryEngine, width: usize, height: usize) -> String {
85 let stats = engine.stats();
86 let mut output = String::new();
87
88 output.push_str(&format!("{}{}", COLOR_BRIGHT, BOX_TL));
90 output.push_str(&BOX_H.to_string().repeat(width - 2));
91 output.push_str(&format!("{}{}\n", BOX_TR, COLOR_RESET));
92
93 let title = format!(" Discovery Graph ({} nodes, {} edges) ", stats.total_nodes, stats.total_edges);
94 output.push_str(&format!("{}{}", COLOR_BRIGHT, BOX_V));
95 output.push_str(&format!("{:^width$}", title, width = width - 2));
96 output.push_str(&format!("{}{}\n", BOX_V, COLOR_RESET));
97
98 output.push_str(&format!("{}{}", COLOR_BRIGHT, BOX_BL));
99 output.push_str(&BOX_H.to_string().repeat(width - 2));
100 output.push_str(&format!("{}{}\n\n", BOX_BR, COLOR_RESET));
101
102 if stats.total_nodes == 0 {
104 output.push_str(&format!("{} (empty graph){}\n", COLOR_DIM, COLOR_RESET));
105 return output;
106 }
107
108 let mut domain_positions: HashMap<Domain, Vec<(usize, usize)>> = HashMap::new();
110
111 let mid_x = width / 2;
113 let mid_y = height / 2;
114
115 let domain_regions = [
117 (Domain::Climate, 10, 2), (Domain::Finance, mid_x + 10, 2), (Domain::Research, 10, mid_y + 2), ];
121
122 for (domain, count) in &stats.domain_counts {
123 let (_, base_x, base_y) = domain_regions.iter()
124 .find(|(d, _, _)| d == domain)
125 .unwrap_or(&(Domain::Research, 10, 2));
126
127 let mut positions = Vec::new();
128
129 let nodes_per_row = ((*count as f64).sqrt().ceil() as usize).max(1);
131 for i in 0..*count {
132 let row = i / nodes_per_row;
133 let col = i % nodes_per_row;
134 let x = base_x + col * 3;
135 let y = base_y + row * 2;
136
137 if x < width - 5 && y < height - 2 {
138 positions.push((x, y));
139 }
140 }
141
142 domain_positions.insert(*domain, positions);
143 }
144
145 let mut canvas: Vec<Vec<String>> = vec![vec![" ".to_string(); width]; height];
147
148 for (domain, positions) in &domain_positions {
150 let color = domain_color(*domain);
151 let ch = domain_char(*domain);
152
153 for (x, y) in positions {
154 if *x < width && *y < height {
155 canvas[*y][*x] = format!("{}{}{}", color, ch, COLOR_RESET);
156 }
157 }
158 }
159
160 if stats.cross_domain_edges > 0 {
162 for (domain_a, positions_a) in &domain_positions {
164 for (domain_b, positions_b) in &domain_positions {
165 if domain_a == domain_b {
166 continue;
167 }
168
169 if let (Some(pos_a), Some(pos_b)) = (positions_a.first(), positions_b.first()) {
171 let (x1, y1) = pos_a;
172 let (x2, y2) = pos_b;
173
174 let color = COLOR_DIM;
176
177 let (min_x, max_x) = if x1 < x2 { (*x1, *x2) } else { (*x2, *x1) };
179 for x in min_x..=max_x {
180 if x < width && *y1 < height && canvas[*y1][x] == " " {
181 canvas[*y1][x] = format!("{}{}{}", color, BOX_H, COLOR_RESET);
182 }
183 }
184
185 let (min_y, max_y) = if y1 < y2 { (*y1, *y2) } else { (*y2, *y1) };
187 for y in min_y..=max_y {
188 if *x2 < width && y < height && canvas[y][*x2] == " " {
189 canvas[y][*x2] = format!("{}{}{}", color, BOX_V, COLOR_RESET);
190 }
191 }
192 }
193 }
194 }
195 }
196
197 for row in canvas {
199 for cell in row {
200 output.push_str(&cell);
201 }
202 output.push('\n');
203 }
204
205 output.push('\n');
206
207 output.push_str(&format!("{}Legend:{}\n", COLOR_BRIGHT, COLOR_RESET));
209 output.push_str(&format!(" {}C{} = Climate ", COLOR_CLIMATE, COLOR_RESET));
210 output.push_str(&format!("{}F{} = Finance ", COLOR_FINANCE, COLOR_RESET));
211 output.push_str(&format!("{}R{} = Research\n", COLOR_RESEARCH, COLOR_RESET));
212 output.push_str(&format!(" Cross-domain bridges: {}\n", stats.cross_domain_edges));
213
214 output
215}
216
217pub fn render_domain_matrix(engine: &OptimizedDiscoveryEngine) -> String {
221 let stats = engine.stats();
222 let mut output = String::new();
223
224 output.push_str(&format!("\n{}{}Domain Connectivity Matrix{}{}\n",
225 COLOR_BRIGHT, BOX_TL, BOX_TR, COLOR_RESET));
226 output.push_str(&format!("{}\n", BOX_H.to_string().repeat(50)));
227
228 let domains = [Domain::Climate, Domain::Finance, Domain::Research];
230 let mut matrix: HashMap<(Domain, Domain), usize> = HashMap::new();
231
232 for &d1 in &domains {
234 for &d2 in &domains {
235 matrix.insert((d1, d2), 0);
236 }
237 }
238
239 output.push_str(&format!(" {}Climate{} {}Finance{} {}Research{}\n",
242 COLOR_CLIMATE, COLOR_RESET,
243 COLOR_FINANCE, COLOR_RESET,
244 COLOR_RESEARCH, COLOR_RESET));
245
246 for &domain_a in &domains {
247 let color_a = domain_color(domain_a);
248 output.push_str(&format!("{}{:9}{} ", color_a, format!("{:?}", domain_a), COLOR_RESET));
249
250 for &domain_b in &domains {
251 let count = matrix.get(&(domain_a, domain_b)).unwrap_or(&0);
252 let display = if domain_a == domain_b {
253 format!("{}[{:3}]{}", COLOR_BRIGHT, stats.domain_counts.get(&domain_a).unwrap_or(&0), COLOR_RESET)
254 } else {
255 format!(" {:3} ", count)
256 };
257 output.push_str(&display);
258 }
259 output.push('\n');
260 }
261
262 output.push_str(&format!("\n{}Note:{} Diagonal = node count, Off-diagonal = cross-domain edges\n",
263 COLOR_DIM, COLOR_RESET));
264 output.push_str(&format!("Total cross-domain edges: {}\n", stats.cross_domain_edges));
265
266 output
267}
268
269pub fn render_coherence_timeline(history: &[(DateTime<Utc>, f64)]) -> String {
274 let mut output = String::new();
275
276 output.push_str(&format!("\n{}{}Coherence Timeline{}{}\n",
277 COLOR_BRIGHT, BOX_TL, BOX_TR, COLOR_RESET));
278 output.push_str(&format!("{}\n", BOX_H.to_string().repeat(70)));
279
280 if history.is_empty() {
281 output.push_str(&format!("{} (no coherence history){}\n", COLOR_DIM, COLOR_RESET));
282 return output;
283 }
284
285 let values: Vec<f64> = history.iter().map(|(_, v)| *v).collect();
286 let min_val = values.iter().cloned().fold(f64::INFINITY, f64::min);
287 let max_val = values.iter().cloned().fold(f64::NEG_INFINITY, f64::max);
288
289 output.push_str(&format!(" Coherence range: {:.4} - {:.4}\n", min_val, max_val));
290 output.push_str(&format!(" Data points: {}\n\n", history.len()));
291
292 let chart_height = 10;
294 let chart_width = 60.min(history.len());
295
296 let step = if history.len() > chart_width {
298 history.len() / chart_width
299 } else {
300 1
301 };
302
303 let sampled: Vec<f64> = history.iter()
304 .step_by(step)
305 .take(chart_width)
306 .map(|(_, v)| *v)
307 .collect();
308
309 let range = max_val - min_val;
311 let normalized: Vec<usize> = if range > 1e-10 {
312 sampled.iter()
313 .map(|v| {
314 let normalized = ((v - min_val) / range * (chart_height - 1) as f64) as usize;
315 normalized.min(chart_height - 1)
316 })
317 .collect()
318 } else {
319 vec![chart_height / 2; sampled.len()]
320 };
321
322 for row in (0..chart_height).rev() {
324 let value = min_val + (row as f64 / (chart_height - 1) as f64) * range;
325 output.push_str(&format!("{:6.3} {} ", value, BOX_V));
326
327 for &height in &normalized {
328 let ch = if height >= row {
329 format!("{}▓{}", COLOR_CLIMATE, COLOR_RESET)
330 } else if height + 1 == row {
331 format!("{}▒{}", COLOR_DIM, COLOR_RESET)
332 } else {
333 " ".to_string()
334 };
335 output.push_str(&ch);
336 }
337 output.push('\n');
338 }
339
340 output.push_str(" ");
342 output.push_str(&BOX_BL.to_string());
343 output.push_str(&BOX_H.to_string().repeat(chart_width));
344 output.push('\n');
345
346 if let (Some(first), Some(last)) = (history.first(), history.last()) {
348 let duration = last.0.signed_duration_since(first.0);
349 let width_val = if chart_width > 12 { chart_width - 12 } else { 0 };
350 output.push_str(&format!(" {} {:>width$}\n",
351 first.0.format("%Y-%m-%d"),
352 last.0.format("%Y-%m-%d"),
353 width = width_val));
354 output.push_str(&format!(" {}Duration: {}{}\n",
355 COLOR_DIM,
356 if duration.num_days() > 0 {
357 format!("{} days", duration.num_days())
358 } else if duration.num_hours() > 0 {
359 format!("{} hours", duration.num_hours())
360 } else {
361 format!("{} minutes", duration.num_minutes())
362 },
363 COLOR_RESET));
364 }
365
366 output
367}
368
369pub fn render_pattern_summary(patterns: &[SignificantPattern]) -> String {
374 let mut output = String::new();
375
376 output.push_str(&format!("\n{}{}Pattern Discovery Summary{}{}\n",
377 COLOR_BRIGHT, BOX_TL, BOX_TR, COLOR_RESET));
378 output.push_str(&format!("{}\n", BOX_H.to_string().repeat(80)));
379
380 if patterns.is_empty() {
381 output.push_str(&format!("{} No patterns discovered yet{}\n", COLOR_DIM, COLOR_RESET));
382 return output;
383 }
384
385 output.push_str(&format!(" Total patterns detected: {}\n", patterns.len()));
386
387 let mut type_counts: HashMap<PatternType, usize> = HashMap::new();
389 let mut significant_count = 0;
390
391 for pattern in patterns {
392 *type_counts.entry(pattern.pattern.pattern_type).or_default() += 1;
393 if pattern.is_significant {
394 significant_count += 1;
395 }
396 }
397
398 output.push_str(&format!(" Statistically significant: {} ({:.1}%)\n\n",
399 significant_count,
400 (significant_count as f64 / patterns.len() as f64) * 100.0));
401
402 output.push_str(&format!("{}Pattern Types:{}\n", COLOR_BRIGHT, COLOR_RESET));
404 for (pattern_type, count) in type_counts.iter() {
405 let icon = match pattern_type {
406 PatternType::CoherenceBreak => "⚠️ ",
407 PatternType::Consolidation => "📈",
408 PatternType::EmergingCluster => "🌟",
409 PatternType::DissolvingCluster => "💫",
410 PatternType::BridgeFormation => "🌉",
411 PatternType::AnomalousNode => "🔴",
412 PatternType::TemporalShift => "⏰",
413 PatternType::Cascade => "🌊",
414 };
415
416 let bar_length = ((*count as f64 / patterns.len() as f64) * 30.0) as usize;
417 let bar = "█".repeat(bar_length);
418
419 output.push_str(&format!(" {} {:20} {:3} {}{}{}\n",
420 icon,
421 format!("{:?}", pattern_type),
422 count,
423 COLOR_CLIMATE,
424 bar,
425 COLOR_RESET));
426 }
427
428 output.push('\n');
429
430 output.push_str(&format!("{}Top Patterns (by confidence):{}\n", COLOR_BRIGHT, COLOR_RESET));
432
433 let mut sorted_patterns: Vec<_> = patterns.iter().collect();
434 sorted_patterns.sort_by(|a, b| b.pattern.confidence.partial_cmp(&a.pattern.confidence).unwrap());
435
436 for (i, pattern) in sorted_patterns.iter().take(5).enumerate() {
437 let significance_marker = if pattern.is_significant {
438 format!("{}*{}", COLOR_BRIGHT, COLOR_RESET)
439 } else {
440 " ".to_string()
441 };
442
443 let color = if pattern.pattern.confidence > 0.8 {
444 COLOR_CLIMATE
445 } else if pattern.pattern.confidence > 0.5 {
446 COLOR_FINANCE
447 } else {
448 COLOR_DIM
449 };
450
451 output.push_str(&format!(" {}{}.{} {}{:?}{} (p={:.4}, effect={:.3}, conf={:.2})\n",
452 significance_marker,
453 i + 1,
454 COLOR_RESET,
455 color,
456 pattern.pattern.pattern_type,
457 COLOR_RESET,
458 pattern.p_value,
459 pattern.effect_size,
460 pattern.pattern.confidence));
461
462 output.push_str(&format!(" {}{}{}\n",
463 COLOR_DIM,
464 pattern.pattern.description,
465 COLOR_RESET));
466 }
467
468 output.push_str(&format!("\n{}Note:{} * = statistically significant (p < 0.05)\n",
469 COLOR_DIM, COLOR_RESET));
470
471 output
472}
473
474pub fn render_dashboard(
476 engine: &OptimizedDiscoveryEngine,
477 patterns: &[SignificantPattern],
478 coherence_history: &[(DateTime<Utc>, f64)],
479) -> String {
480 let mut output = String::new();
481
482 output.push_str(&format!("\n{}{}═══════════════════════════════════════════════════════════════════════════════{}\n",
484 COLOR_BRIGHT, BOX_TL, COLOR_RESET));
485 output.push_str(&format!("{}{} RuVector Discovery Framework - Live Dashboard {}\n",
486 COLOR_BRIGHT, BOX_V, COLOR_RESET));
487 output.push_str(&format!("{}{}═══════════════════════════════════════════════════════════════════════════════{}\n\n",
488 COLOR_BRIGHT, BOX_BL, COLOR_RESET));
489
490 let stats = engine.stats();
492 output.push_str(&format!("{}Quick Stats:{}\n", COLOR_BRIGHT, COLOR_RESET));
493 output.push_str(&format!(" Nodes: {} │ Edges: {} │ Vectors: {} │ Cross-domain: {}\n",
494 stats.total_nodes,
495 stats.total_edges,
496 stats.total_vectors,
497 stats.cross_domain_edges));
498 output.push_str(&format!(" Patterns: {} │ Coherence samples: {} │ Cache hit rate: {:.1}%\n\n",
499 patterns.len(),
500 coherence_history.len(),
501 stats.cache_hit_rate * 100.0));
502
503 output.push_str(&render_graph_ascii(engine, 80, 20));
505 output.push('\n');
506
507 output.push_str(&render_domain_matrix(engine));
509 output.push('\n');
510
511 output.push_str(&render_coherence_timeline(coherence_history));
513 output.push('\n');
514
515 output.push_str(&render_pattern_summary(patterns));
517
518 output.push_str(&format!("\n{}{}═══════════════════════════════════════════════════════════════════════════════{}\n",
519 COLOR_DIM, BOX_BL, COLOR_RESET));
520
521 output
522}
523
524#[cfg(test)]
525mod tests {
526 use super::*;
527 use crate::optimized::{OptimizedConfig, OptimizedDiscoveryEngine};
528 use crate::ruvector_native::SemanticVector;
529 use chrono::Utc;
530
531 #[test]
532 fn test_domain_color() {
533 assert_eq!(domain_color(Domain::Climate), COLOR_CLIMATE);
534 assert_eq!(domain_color(Domain::Finance), COLOR_FINANCE);
535 }
536
537 #[test]
538 fn test_domain_char() {
539 assert_eq!(domain_char(Domain::Climate), 'C');
540 assert_eq!(domain_char(Domain::Finance), 'F');
541 assert_eq!(domain_char(Domain::Research), 'R');
542 }
543
544 #[test]
545 fn test_render_empty_graph() {
546 let config = OptimizedConfig::default();
547 let engine = OptimizedDiscoveryEngine::new(config);
548 let output = render_graph_ascii(&engine, 80, 20);
549 assert!(output.contains("empty graph"));
550 }
551
552 #[test]
553 fn test_render_pattern_summary_empty() {
554 let output = render_pattern_summary(&[]);
555 assert!(output.contains("No patterns"));
556 }
557
558 #[test]
559 fn test_render_coherence_timeline_empty() {
560 let output = render_coherence_timeline(&[]);
561 assert!(output.contains("no coherence history"));
562 }
563
564 #[test]
565 fn test_render_coherence_timeline_with_data() {
566 let now = Utc::now();
567 let history = vec![
568 (now, 0.5),
569 (now + chrono::Duration::hours(1), 0.6),
570 (now + chrono::Duration::hours(2), 0.7),
571 ];
572 let output = render_coherence_timeline(&history);
573 assert!(output.contains("Coherence Timeline"));
574 assert!(output.contains("Data points: 3"));
575 }
576}