aprender-viz 0.39.0

SIMD/GPU/WASM-accelerated visualization library for data science and ML
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
//! trueno-graph library integration.
//!
//! Provides visualization extensions for trueno-graph types (CsrGraph, NodeId).
//!
//! # Examples
//!
//! ```rust,ignore
//! use trueno_graph::{CsrGraph, NodeId};
//! use trueno_viz::interop::trueno_graph::GraphViz;
//!
//! let mut graph = CsrGraph::new();
//! graph.add_edge(NodeId(0), NodeId(1), 1.0)?;
//! graph.add_edge(NodeId(1), NodeId(2), 1.0)?;
//!
//! // Visualize as force-directed graph
//! let fb = graph.to_force_graph()?;
//! ```

use batuta_common::display::WithDimensions;
use trueno_graph::{louvain, pagerank, CommunityDetectionResult, CsrGraph, NodeId};

use crate::color::Rgba;
use crate::error::Result;
use crate::framebuffer::Framebuffer;
use crate::plots::{ForceGraph, GraphEdge, GraphNode, Histogram, ScatterPlot};

/// Default community colors (distinct, colorblind-friendly palette).
const COMMUNITY_COLORS: &[Rgba] = &[
    Rgba::new(66, 133, 244, 255),  // Blue
    Rgba::new(234, 67, 53, 255),   // Red
    Rgba::new(52, 168, 83, 255),   // Green
    Rgba::new(251, 188, 5, 255),   // Yellow
    Rgba::new(154, 160, 166, 255), // Gray
    Rgba::new(171, 71, 188, 255),  // Purple
    Rgba::new(255, 112, 67, 255),  // Orange
    Rgba::new(0, 172, 193, 255),   // Cyan
];

// ============================================================================
// CsrGraph Visualization Extensions
// ============================================================================

/// Visualization extensions for trueno-graph CsrGraph.
pub trait GraphViz {
    /// Create a force-directed graph visualization.
    fn to_force_graph(&self) -> Result<Framebuffer>;

    /// Create a force-directed graph with custom dimensions.
    fn to_force_graph_with(&self, width: u32, height: u32) -> Result<Framebuffer>;

    /// Create a force-directed graph with nodes colored by community.
    fn to_community_graph(&self) -> Result<Framebuffer>;

    /// Create a force-directed graph with nodes sized by PageRank.
    fn to_pagerank_graph(&self) -> Result<Framebuffer>;

    /// Create a force-directed graph with both community colors and PageRank sizing.
    fn to_analysis_graph(&self) -> Result<Framebuffer>;

    /// Create a histogram of node degrees (outgoing).
    fn degree_histogram(&self) -> Result<Framebuffer>;

    /// Create a scatter plot of in-degree vs out-degree.
    fn degree_scatter(&self) -> Result<Framebuffer>;
}

impl GraphViz for CsrGraph {
    fn to_force_graph(&self) -> Result<Framebuffer> {
        self.to_force_graph_with(600, 500)
    }

    fn to_force_graph_with(&self, width: u32, height: u32) -> Result<Framebuffer> {
        let mut fg = ForceGraph::new().dimensions(width, height).iterations(100);

        // Add nodes
        for i in 0..self.num_nodes() {
            let mut node = GraphNode::new(i);
            if let Some(name) = self.get_node_name(NodeId(i as u32)) {
                node = node.label(name);
            }
            fg = fg.add_node(node);
        }

        // Add edges
        for (src, targets, weights) in self.iter_adjacency() {
            for (dst, weight) in targets.iter().zip(weights.iter()) {
                fg = fg.add_edge(GraphEdge::new(src.0 as usize, *dst as usize).weight(*weight));
            }
        }

        let built = fg.build()?;
        built.to_framebuffer()
    }

    fn to_community_graph(&self) -> Result<Framebuffer> {
        let communities = louvain(self)
            .map_err(|e| crate::error::Error::Rendering(format!("Louvain failed: {e}")))?;

        graph_with_communities(self, &communities, 600, 500)
    }

    fn to_pagerank_graph(&self) -> Result<Framebuffer> {
        let scores = pagerank(self, 20, 1e-6)
            .map_err(|e| crate::error::Error::Rendering(format!("PageRank failed: {e}")))?;

        graph_with_pagerank(self, &scores, 600, 500)
    }

    fn to_analysis_graph(&self) -> Result<Framebuffer> {
        let communities = louvain(self)
            .map_err(|e| crate::error::Error::Rendering(format!("Louvain failed: {e}")))?;

        let scores = pagerank(self, 20, 1e-6)
            .map_err(|e| crate::error::Error::Rendering(format!("PageRank failed: {e}")))?;

        graph_with_analysis(self, &communities, &scores, 600, 500)
    }

    fn degree_histogram(&self) -> Result<Framebuffer> {
        let degrees: Vec<f32> = (0..self.num_nodes())
            .map(|i| {
                self.outgoing_neighbors(NodeId(i as u32)).map(|n| n.len() as f32).unwrap_or(0.0)
            })
            .collect();

        let plot = Histogram::new()
            .data(&degrees)
            .color(Rgba::new(66, 133, 244, 255))
            .dimensions(600, 400)
            .build()?;

        plot.to_framebuffer()
    }

    fn degree_scatter(&self) -> Result<Framebuffer> {
        let n = self.num_nodes();
        let mut in_degrees = vec![0.0f32; n];
        let mut out_degrees = vec![0.0f32; n];

        for i in 0..n {
            out_degrees[i] =
                self.outgoing_neighbors(NodeId(i as u32)).map(|n| n.len() as f32).unwrap_or(0.0);

            in_degrees[i] =
                self.incoming_neighbors(NodeId(i as u32)).map(|n| n.len() as f32).unwrap_or(0.0);
        }

        let plot = ScatterPlot::new()
            .x(&in_degrees)
            .y(&out_degrees)
            .color(Rgba::new(66, 133, 244, 255))
            .size(6.0)
            .dimensions(600, 500)
            .build()?;

        plot.to_framebuffer()
    }
}

// ============================================================================
// Internal Helper Functions
// ============================================================================

fn graph_with_communities(
    graph: &CsrGraph,
    communities: &CommunityDetectionResult,
    width: u32,
    height: u32,
) -> Result<Framebuffer> {
    let mut fg = ForceGraph::new().dimensions(width, height).iterations(100);

    // Add nodes with community colors
    for i in 0..graph.num_nodes() {
        let node_id = NodeId(i as u32);
        let comm_id = communities.get_community(node_id).unwrap_or(0);
        let color = COMMUNITY_COLORS[comm_id % COMMUNITY_COLORS.len()];

        let mut node = GraphNode::new(i).color(color);
        if let Some(name) = graph.get_node_name(node_id) {
            node = node.label(name);
        }
        fg = fg.add_node(node);
    }

    // Add edges
    for (src, targets, weights) in graph.iter_adjacency() {
        for (dst, weight) in targets.iter().zip(weights.iter()) {
            fg = fg.add_edge(GraphEdge::new(src.0 as usize, *dst as usize).weight(*weight));
        }
    }

    let built = fg.build()?;
    built.to_framebuffer()
}

fn graph_with_pagerank(
    graph: &CsrGraph,
    scores: &[f32],
    width: u32,
    height: u32,
) -> Result<Framebuffer> {
    let mut fg = ForceGraph::new().dimensions(width, height).iterations(100);

    // Find min/max for normalization
    let max_score = scores.iter().copied().fold(0.0f32, f32::max);
    let min_score = scores.iter().copied().fold(f32::MAX, f32::min);
    let score_range = (max_score - min_score).max(0.001);

    // Add nodes with PageRank-based sizing
    for i in 0..graph.num_nodes() {
        let score = scores.get(i).copied().unwrap_or(0.0);
        let normalized = (score - min_score) / score_range;
        let radius = 5.0 + normalized * 20.0; // 5-25 pixel radius

        let mut node = GraphNode::new(i).radius(radius);
        if let Some(name) = graph.get_node_name(NodeId(i as u32)) {
            node = node.label(name);
        }
        fg = fg.add_node(node);
    }

    // Add edges
    for (src, targets, weights) in graph.iter_adjacency() {
        for (dst, weight) in targets.iter().zip(weights.iter()) {
            fg = fg.add_edge(GraphEdge::new(src.0 as usize, *dst as usize).weight(*weight));
        }
    }

    let built = fg.build()?;
    built.to_framebuffer()
}

fn graph_with_analysis(
    graph: &CsrGraph,
    communities: &CommunityDetectionResult,
    scores: &[f32],
    width: u32,
    height: u32,
) -> Result<Framebuffer> {
    let mut fg = ForceGraph::new().dimensions(width, height).iterations(100);

    // Find min/max for normalization
    let max_score = scores.iter().copied().fold(0.0f32, f32::max);
    let min_score = scores.iter().copied().fold(f32::MAX, f32::min);
    let score_range = (max_score - min_score).max(0.001);

    // Add nodes with both community colors and PageRank sizing
    for i in 0..graph.num_nodes() {
        let node_id = NodeId(i as u32);

        // Community color
        let comm_id = communities.get_community(node_id).unwrap_or(0);
        let color = COMMUNITY_COLORS[comm_id % COMMUNITY_COLORS.len()];

        // PageRank size
        let score = scores.get(i).copied().unwrap_or(0.0);
        let normalized = (score - min_score) / score_range;
        let radius = 5.0 + normalized * 20.0;

        let mut node = GraphNode::new(i).color(color).radius(radius);
        if let Some(name) = graph.get_node_name(node_id) {
            node = node.label(name);
        }
        fg = fg.add_node(node);
    }

    // Add edges
    for (src, targets, weights) in graph.iter_adjacency() {
        for (dst, weight) in targets.iter().zip(weights.iter()) {
            fg = fg.add_edge(GraphEdge::new(src.0 as usize, *dst as usize).weight(*weight));
        }
    }

    let built = fg.build()?;
    built.to_framebuffer()
}

// ============================================================================
// PageRank Visualization
// ============================================================================

/// Visualization extensions for PageRank results.
pub trait PageRankViz {
    /// Create a histogram of PageRank scores.
    fn to_histogram(&self) -> Result<Framebuffer>;

    /// Create a bar chart of top N PageRank scores.
    fn top_n_bar(&self, n: usize) -> Result<Framebuffer>;
}

impl PageRankViz for Vec<f32> {
    fn to_histogram(&self) -> Result<Framebuffer> {
        let plot = Histogram::new()
            .data(self)
            .color(Rgba::new(66, 133, 244, 255))
            .dimensions(600, 400)
            .build()?;

        plot.to_framebuffer()
    }

    fn top_n_bar(&self, n: usize) -> Result<Framebuffer> {
        // Get indices sorted by score descending
        let mut indexed: Vec<(usize, f32)> = self.iter().copied().enumerate().collect();
        indexed.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal));

        let top_n: Vec<f32> = indexed.iter().take(n).map(|(_, s)| *s).collect();
        let x: Vec<f32> = (0..top_n.len()).map(|i| i as f32).collect();

        let plot = ScatterPlot::new()
            .x(&x)
            .y(&top_n)
            .color(Rgba::new(66, 133, 244, 255))
            .size(10.0)
            .dimensions(600, 400)
            .build()?;

        plot.to_framebuffer()
    }
}

// ============================================================================
// Community Visualization
// ============================================================================

/// Visualization extensions for community detection results.
pub trait CommunityViz {
    /// Create a histogram of community sizes.
    fn size_histogram(&self) -> Result<Framebuffer>;

    /// Get the modularity score.
    fn modularity_score(&self) -> f64;
}

impl CommunityViz for CommunityDetectionResult {
    fn size_histogram(&self) -> Result<Framebuffer> {
        let sizes: Vec<f32> = self.communities.iter().map(|c| c.len() as f32).collect();

        let plot = Histogram::new()
            .data(&sizes)
            .color(Rgba::new(52, 168, 83, 255))
            .dimensions(600, 400)
            .build()?;

        plot.to_framebuffer()
    }

    fn modularity_score(&self) -> f64 {
        self.modularity
    }
}

// ============================================================================
// Convenience Functions
// ============================================================================

/// Visualize a graph using force-directed layout.
pub fn visualize_graph(graph: &CsrGraph) -> Result<Framebuffer> {
    graph.to_force_graph()
}

/// Visualize a graph with community detection coloring.
pub fn visualize_communities(graph: &CsrGraph) -> Result<Framebuffer> {
    graph.to_community_graph()
}

/// Visualize a graph with PageRank-based node sizing.
pub fn visualize_pagerank(graph: &CsrGraph) -> Result<Framebuffer> {
    graph.to_pagerank_graph()
}

/// Full analysis visualization (communities + PageRank).
pub fn visualize_analysis(graph: &CsrGraph) -> Result<Framebuffer> {
    graph.to_analysis_graph()
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;

    fn create_test_graph() -> CsrGraph {
        let edges = vec![
            (NodeId(0), NodeId(1), 1.0),
            (NodeId(1), NodeId(2), 1.0),
            (NodeId(2), NodeId(0), 1.0),
            (NodeId(2), NodeId(3), 1.0),
            (NodeId(3), NodeId(4), 1.0),
            (NodeId(4), NodeId(3), 1.0),
        ];
        CsrGraph::from_edge_list(&edges).expect("Failed to create graph")
    }

    #[test]
    fn test_to_force_graph() {
        let graph = create_test_graph();
        let fb = graph.to_force_graph().expect("operation should succeed");
        assert_eq!(fb.width(), 600);
        assert_eq!(fb.height(), 500);
    }

    #[test]
    fn test_to_force_graph_with() {
        let graph = create_test_graph();
        let fb = graph.to_force_graph_with(800, 600).expect("operation should succeed");
        assert_eq!(fb.width(), 800);
        assert_eq!(fb.height(), 600);
    }

    #[test]
    fn test_to_community_graph() {
        let graph = create_test_graph();
        let fb = graph.to_community_graph().expect("operation should succeed");
        assert!(fb.width() > 0);
    }

    #[test]
    fn test_to_pagerank_graph() {
        let graph = create_test_graph();
        let fb = graph.to_pagerank_graph().expect("operation should succeed");
        assert!(fb.width() > 0);
    }

    #[test]
    fn test_to_analysis_graph() {
        let graph = create_test_graph();
        let fb = graph.to_analysis_graph().expect("operation should succeed");
        assert!(fb.width() > 0);
    }

    #[test]
    fn test_degree_histogram() {
        let graph = create_test_graph();
        let fb = graph.degree_histogram().expect("operation should succeed");
        assert_eq!(fb.width(), 600);
        assert_eq!(fb.height(), 400);
    }

    #[test]
    fn test_degree_scatter() {
        let graph = create_test_graph();
        let fb = graph.degree_scatter().expect("operation should succeed");
        assert_eq!(fb.width(), 600);
        assert_eq!(fb.height(), 500);
    }

    #[test]
    fn test_pagerank_histogram() {
        let graph = create_test_graph();
        let scores = pagerank(&graph, 20, 1e-6).expect("operation should succeed");
        let fb = scores.to_histogram().expect("operation should succeed");
        assert!(fb.width() > 0);
    }

    #[test]
    fn test_pagerank_top_n() {
        let graph = create_test_graph();
        let scores = pagerank(&graph, 20, 1e-6).expect("operation should succeed");
        let fb = scores.top_n_bar(3).expect("operation should succeed");
        assert!(fb.width() > 0);
    }

    #[test]
    fn test_community_size_histogram() {
        let graph = create_test_graph();
        let communities = louvain(&graph).expect("operation should succeed");
        let fb = communities.size_histogram().expect("operation should succeed");
        assert!(fb.width() > 0);
    }

    #[test]
    fn test_convenience_functions() {
        let graph = create_test_graph();

        let fb = visualize_graph(&graph).expect("operation should succeed");
        assert!(fb.width() > 0);

        let fb = visualize_communities(&graph).expect("operation should succeed");
        assert!(fb.width() > 0);

        let fb = visualize_pagerank(&graph).expect("operation should succeed");
        assert!(fb.width() > 0);

        let fb = visualize_analysis(&graph).expect("operation should succeed");
        assert!(fb.width() > 0);
    }
}