torsh-nn 0.1.2

Neural network modules for ToRSh with PyTorch-compatible API
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
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
//! Network architecture visualization tools
//!
//! This module provides tools for visualizing neural network architectures,
//! including graph representations, layer diagrams, and model flow charts.

use crate::Module;
use std::collections::{HashMap, HashSet};
use std::fmt::{self, Display};
use torsh_core::error::{Result, TorshError};

/// Represents a node in the network graph
#[derive(Debug, Clone)]
pub struct GraphNode {
    /// Unique identifier for the node
    pub id: String,
    /// Display name for the node
    pub name: String,
    /// Type of the layer/module
    pub layer_type: String,
    /// Input shape
    pub input_shape: Vec<usize>,
    /// Output shape
    pub output_shape: Vec<usize>,
    /// Number of parameters
    pub parameter_count: usize,
    /// Position in the graph (x, y)
    pub position: Option<(f32, f32)>,
    /// Additional metadata
    pub metadata: HashMap<String, String>,
}

impl GraphNode {
    /// Create a new graph node
    pub fn new(
        id: String,
        name: String,
        layer_type: String,
        input_shape: Vec<usize>,
        output_shape: Vec<usize>,
        parameter_count: usize,
    ) -> Self {
        Self {
            id,
            name,
            layer_type,
            input_shape,
            output_shape,
            parameter_count,
            position: None,
            metadata: HashMap::new(),
        }
    }

    /// Set the position of the node
    pub fn with_position(mut self, x: f32, y: f32) -> Self {
        self.position = Some((x, y));
        self
    }

    /// Add metadata to the node
    pub fn with_metadata(mut self, key: String, value: String) -> Self {
        self.metadata.insert(key, value);
        self
    }

    /// Get a short description of the node
    pub fn short_description(&self) -> String {
        format!("{} ({})", self.name, self.layer_type)
    }

    /// Get a detailed description of the node
    pub fn detailed_description(&self) -> String {
        format!(
            "{}\nType: {}\nInput: {:?}\nOutput: {:?}\nParams: {}",
            self.name,
            self.layer_type,
            self.input_shape,
            self.output_shape,
            format_number(self.parameter_count)
        )
    }
}

/// Represents an edge connecting two nodes
#[derive(Debug, Clone)]
pub struct GraphEdge {
    /// Source node ID
    pub from: String,
    /// Target node ID
    pub to: String,
    /// Data shape flowing through this edge
    pub shape: Vec<usize>,
    /// Edge weight or importance
    pub weight: f32,
    /// Edge style
    pub style: EdgeStyle,
}

/// Edge styling options
#[derive(Debug, Clone, PartialEq)]
pub enum EdgeStyle {
    /// Regular connection
    Normal,
    /// Skip connection (residual)
    Skip,
    /// Attention connection
    Attention,
    /// Recurrent connection
    Recurrent,
}

impl GraphEdge {
    /// Create a new graph edge
    pub fn new(from: String, to: String, shape: Vec<usize>) -> Self {
        Self {
            from,
            to,
            shape,
            weight: 1.0,
            style: EdgeStyle::Normal,
        }
    }

    /// Set the edge style
    pub fn with_style(mut self, style: EdgeStyle) -> Self {
        self.style = style;
        self
    }

    /// Set the edge weight
    pub fn with_weight(mut self, weight: f32) -> Self {
        self.weight = weight;
        self
    }
}

/// Complete network graph representation
#[derive(Debug, Clone)]
pub struct NetworkGraph {
    /// All nodes in the graph
    pub nodes: HashMap<String, GraphNode>,
    /// All edges in the graph
    pub edges: Vec<GraphEdge>,
    /// Input node IDs
    pub inputs: Vec<String>,
    /// Output node IDs
    pub outputs: Vec<String>,
    /// Graph metadata
    pub metadata: HashMap<String, String>,
}

impl NetworkGraph {
    /// Create a new empty network graph
    pub fn new() -> Self {
        Self {
            nodes: HashMap::new(),
            edges: Vec::new(),
            inputs: Vec::new(),
            outputs: Vec::new(),
            metadata: HashMap::new(),
        }
    }

    /// Add a node to the graph
    pub fn add_node(&mut self, node: GraphNode) {
        self.nodes.insert(node.id.clone(), node);
    }

    /// Add an edge to the graph
    pub fn add_edge(&mut self, edge: GraphEdge) {
        self.edges.push(edge);
    }

    /// Set input nodes
    pub fn set_inputs(&mut self, inputs: Vec<String>) {
        self.inputs = inputs;
    }

    /// Set output nodes
    pub fn set_outputs(&mut self, outputs: Vec<String>) {
        self.outputs = outputs;
    }

    /// Get topological ordering of nodes
    pub fn topological_sort(&self) -> Result<Vec<String>> {
        let mut in_degree: HashMap<String, usize> = HashMap::new();
        let mut adj_list: HashMap<String, Vec<String>> = HashMap::new();

        // Initialize
        for node_id in self.nodes.keys() {
            in_degree.insert(node_id.clone(), 0);
            adj_list.insert(node_id.clone(), Vec::new());
        }

        // Build adjacency list and calculate in-degrees
        for edge in &self.edges {
            adj_list
                .get_mut(&edge.from)
                .expect("edge.from should exist in adj_list")
                .push(edge.to.clone());
            *in_degree
                .get_mut(&edge.to)
                .expect("edge.to should exist in in_degree") += 1;
        }

        // Kahn's algorithm
        let mut queue = Vec::new();
        let mut result = Vec::new();

        // Start with nodes that have no incoming edges
        for (node_id, &degree) in &in_degree {
            if degree == 0 {
                queue.push(node_id.clone());
            }
        }

        while let Some(node_id) = queue.pop() {
            result.push(node_id.clone());

            if let Some(neighbors) = adj_list.get(&node_id) {
                for neighbor in neighbors {
                    let degree = in_degree
                        .get_mut(neighbor)
                        .expect("neighbor should exist in in_degree");
                    *degree -= 1;
                    if *degree == 0 {
                        queue.push(neighbor.clone());
                    }
                }
            }
        }

        if result.len() != self.nodes.len() {
            return Err(TorshError::InvalidArgument(
                "Graph contains cycles".to_string(),
            ));
        }

        Ok(result)
    }

    /// Calculate graph statistics
    pub fn calculate_statistics(&self) -> GraphStatistics {
        let total_params: usize = self.nodes.values().map(|n| n.parameter_count).sum();
        let total_nodes = self.nodes.len();
        let total_edges = self.edges.len();

        let layer_types: HashSet<String> =
            self.nodes.values().map(|n| n.layer_type.clone()).collect();

        let max_depth = self.calculate_depth();

        GraphStatistics {
            total_nodes,
            total_edges,
            total_parameters: total_params,
            unique_layer_types: layer_types.len(),
            max_depth,
            layer_type_counts: self.count_layer_types(),
        }
    }

    /// Calculate the maximum depth of the graph
    fn calculate_depth(&self) -> usize {
        // Simplified depth calculation
        if self.inputs.is_empty() {
            return 0;
        }

        let mut depths: HashMap<String, usize> = HashMap::new();

        // Set input depths to 0
        for input_id in &self.inputs {
            depths.insert(input_id.clone(), 0);
        }

        // Calculate depths using BFS
        if let Ok(sorted_nodes) = self.topological_sort() {
            for node_id in sorted_nodes {
                let mut max_input_depth = 0;

                // Find maximum depth of incoming edges
                for edge in &self.edges {
                    if edge.to == node_id {
                        if let Some(&depth) = depths.get(&edge.from) {
                            max_input_depth = max_input_depth.max(depth);
                        }
                    }
                }

                depths.insert(node_id, max_input_depth + 1);
            }
        }

        depths.values().max().copied().unwrap_or(0)
    }

    /// Count occurrences of each layer type
    fn count_layer_types(&self) -> HashMap<String, usize> {
        let mut counts = HashMap::new();
        for node in self.nodes.values() {
            *counts.entry(node.layer_type.clone()).or_insert(0) += 1;
        }
        counts
    }
}

impl Default for NetworkGraph {
    fn default() -> Self {
        Self::new()
    }
}

/// Statistics about the network graph
#[derive(Debug, Clone)]
pub struct GraphStatistics {
    /// Total number of nodes
    pub total_nodes: usize,
    /// Total number of edges
    pub total_edges: usize,
    /// Total number of parameters
    pub total_parameters: usize,
    /// Number of unique layer types
    pub unique_layer_types: usize,
    /// Maximum depth of the graph
    pub max_depth: usize,
    /// Count of each layer type
    pub layer_type_counts: HashMap<String, usize>,
}

impl Display for GraphStatistics {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        writeln!(f, "Graph Statistics:")?;
        writeln!(f, "  Total Nodes: {}", self.total_nodes)?;
        writeln!(f, "  Total Edges: {}", self.total_edges)?;
        writeln!(
            f,
            "  Total Parameters: {}",
            format_number(self.total_parameters)
        )?;
        writeln!(f, "  Unique Layer Types: {}", self.unique_layer_types)?;
        writeln!(f, "  Maximum Depth: {}", self.max_depth)?;
        writeln!(f, "  Layer Type Distribution:")?;

        for (layer_type, count) in &self.layer_type_counts {
            writeln!(f, "    {}: {}", layer_type, count)?;
        }

        Ok(())
    }
}

/// Configuration for graph visualization
#[derive(Debug, Clone)]
pub struct VisualizationConfig {
    /// Width of the output
    pub width: usize,
    /// Height of the output
    pub height: usize,
    /// Whether to show parameter counts
    pub show_parameters: bool,
    /// Whether to show shapes
    pub show_shapes: bool,
    /// Whether to show layer types
    pub show_layer_types: bool,
    /// Layout algorithm to use
    pub layout: LayoutAlgorithm,
    /// Color scheme
    pub color_scheme: ColorScheme,
}

impl Default for VisualizationConfig {
    fn default() -> Self {
        Self {
            width: 800,
            height: 600,
            show_parameters: true,
            show_shapes: true,
            show_layer_types: true,
            layout: LayoutAlgorithm::Hierarchical,
            color_scheme: ColorScheme::Default,
        }
    }
}

/// Layout algorithms for graph visualization
#[derive(Debug, Clone, PartialEq)]
pub enum LayoutAlgorithm {
    /// Hierarchical top-down layout
    Hierarchical,
    /// Force-directed layout
    ForceDirected,
    /// Circular layout
    Circular,
    /// Grid layout
    Grid,
}

/// Color schemes for visualization
#[derive(Debug, Clone, PartialEq)]
pub enum ColorScheme {
    /// Default colors
    Default,
    /// Grayscale
    Grayscale,
    /// Colorful
    Colorful,
    /// High contrast
    HighContrast,
}

/// Generate a network graph from a model
pub fn create_graph_from_model<M: Module>(
    model: &M,
    input_shape: &[usize],
) -> Result<NetworkGraph> {
    let mut graph = NetworkGraph::new();

    // Create input node
    let input_node = GraphNode::new(
        "input".to_string(),
        "Input".to_string(),
        "Input".to_string(),
        vec![],
        input_shape.to_vec(),
        0,
    );
    graph.add_node(input_node);
    graph.set_inputs(vec!["input".to_string()]);

    // Create model node (simplified)
    let params = model.parameters();
    let param_count: usize = params
        .values()
        .map(|p| p.tensor().read().shape().dims().iter().product::<usize>())
        .sum();

    let model_node = GraphNode::new(
        "model".to_string(),
        "Model".to_string(),
        "Model".to_string(),
        input_shape.to_vec(),
        input_shape.to_vec(), // Simplified - would compute actual output shape
        param_count,
    );
    graph.add_node(model_node);

    // Create edge from input to model
    let edge = GraphEdge::new(
        "input".to_string(),
        "model".to_string(),
        input_shape.to_vec(),
    );
    graph.add_edge(edge);

    graph.set_outputs(vec!["model".to_string()]);

    Ok(graph)
}

/// Text-based graph renderer
pub struct TextRenderer {
    config: VisualizationConfig,
}

impl TextRenderer {
    /// Create a new text renderer
    pub fn new(config: VisualizationConfig) -> Self {
        Self { config }
    }

    /// Render a graph as text
    pub fn render(&self, graph: &NetworkGraph) -> String {
        let mut output = String::new();

        output.push_str("Network Architecture Visualization\n");
        output.push_str("==================================\n\n");

        // Show statistics
        let stats = graph.calculate_statistics();
        output.push_str(&format!("{}\n", stats));

        // Show nodes
        output.push_str("Nodes:\n");
        output.push_str("------\n");

        for (id, node) in &graph.nodes {
            output.push_str(&format!("{}:\n", id));
            output.push_str(&format!("  Name: {}\n", node.name));
            output.push_str(&format!("  Type: {}\n", node.layer_type));

            if self.config.show_shapes {
                output.push_str(&format!("  Input Shape: {:?}\n", node.input_shape));
                output.push_str(&format!("  Output Shape: {:?}\n", node.output_shape));
            }

            if self.config.show_parameters && node.parameter_count > 0 {
                output.push_str(&format!(
                    "  Parameters: {}\n",
                    format_number(node.parameter_count)
                ));
            }

            output.push('\n');
        }

        // Show edges
        output.push_str("Connections:\n");
        output.push_str("------------\n");

        for edge in &graph.edges {
            let style_indicator = match edge.style {
                EdgeStyle::Normal => "->",
                EdgeStyle::Skip => "~~>",
                EdgeStyle::Attention => "==>",
                EdgeStyle::Recurrent => "<->",
            };

            output.push_str(&format!(
                "{} {} {} (shape: {:?})\n",
                edge.from, style_indicator, edge.to, edge.shape
            ));
        }

        output
    }
}

/// ASCII art graph renderer
pub struct AsciiRenderer {
    config: VisualizationConfig,
}

impl AsciiRenderer {
    /// Create a new ASCII renderer
    pub fn new(config: VisualizationConfig) -> Self {
        Self { config }
    }

    /// Render a graph as ASCII art
    pub fn render(&self, graph: &NetworkGraph) -> String {
        let mut output = String::new();

        // Simple ASCII representation
        if let Ok(sorted_nodes) = graph.topological_sort() {
            for (i, node_id) in sorted_nodes.iter().enumerate() {
                if let Some(node) = graph.nodes.get(node_id) {
                    // Add indentation based on depth
                    let indent = "  ".repeat(i.min(10));

                    // Node representation
                    let node_repr = if self.config.show_parameters && node.parameter_count > 0 {
                        format!(
                            "[{}] {} ({})",
                            node.layer_type,
                            node.name,
                            format_number(node.parameter_count)
                        )
                    } else {
                        format!("[{}] {}", node.layer_type, node.name)
                    };

                    output.push_str(&format!("{}{}\n", indent, node_repr));

                    if self.config.show_shapes && !node.output_shape.is_empty() {
                        output
                            .push_str(&format!("{}  └─ Output: {:?}\n", indent, node.output_shape));
                    }

                    // Add connection lines
                    if i < sorted_nodes.len() - 1 {
                        output.push_str(&format!("{}  |\n", indent));
                    }
                }
            }
        }

        output
    }
}

/// DOT format renderer for Graphviz
pub struct DotRenderer {
    config: VisualizationConfig,
}

impl DotRenderer {
    /// Create a new DOT renderer
    pub fn new(config: VisualizationConfig) -> Self {
        Self { config }
    }

    /// Render a graph in DOT format
    pub fn render(&self, graph: &NetworkGraph) -> String {
        let mut output = String::new();

        output.push_str("digraph NetworkGraph {\n");
        output.push_str("  rankdir=TB;\n");
        output.push_str("  node [shape=box, style=filled];\n\n");

        // Add nodes
        for (id, node) in &graph.nodes {
            let label = if self.config.show_parameters && node.parameter_count > 0 {
                format!(
                    "{}\\n{}\\n{} params",
                    node.name,
                    node.layer_type,
                    format_number(node.parameter_count)
                )
            } else {
                format!("{}\\n{}", node.name, node.layer_type)
            };

            let color = self.get_node_color(&node.layer_type);

            output.push_str(&format!(
                "  \"{}\" [label=\"{}\", fillcolor=\"{}\"];\n",
                id, label, color
            ));
        }

        output.push('\n');

        // Add edges
        for edge in &graph.edges {
            let style = match edge.style {
                EdgeStyle::Normal => "solid",
                EdgeStyle::Skip => "dashed",
                EdgeStyle::Attention => "bold",
                EdgeStyle::Recurrent => "dotted",
            };

            output.push_str(&format!(
                "  \"{}\" -> \"{}\" [style={}];\n",
                edge.from, edge.to, style
            ));
        }

        output.push_str("}\n");
        output
    }

    /// Get color for a layer type
    fn get_node_color(&self, layer_type: &str) -> &'static str {
        match self.config.color_scheme {
            ColorScheme::Default => match layer_type {
                "Input" => "lightblue",
                "Linear" => "lightgreen",
                "Conv2d" => "orange",
                "ReLU" => "yellow",
                "BatchNorm2d" => "pink",
                _ => "lightgray",
            },
            ColorScheme::Grayscale => "lightgray",
            ColorScheme::Colorful => match layer_type {
                "Input" => "cyan",
                "Linear" => "green",
                "Conv2d" => "red",
                "ReLU" => "yellow",
                "BatchNorm2d" => "magenta",
                _ => "white",
            },
            ColorScheme::HighContrast => match layer_type {
                "Input" => "black",
                "Linear" => "white",
                "Conv2d" => "black",
                "ReLU" => "white",
                "BatchNorm2d" => "black",
                _ => "gray",
            },
        }
    }
}

/// Helper function to format numbers with appropriate units
fn format_number(num: usize) -> String {
    if num >= 1_000_000_000 {
        format!("{:.1}B", num as f64 / 1_000_000_000.0)
    } else if num >= 1_000_000 {
        format!("{:.1}M", num as f64 / 1_000_000.0)
    } else if num >= 1_000 {
        format!("{:.1}K", num as f64 / 1_000.0)
    } else {
        num.to_string()
    }
}

/// Utility functions for common visualization tasks
pub mod utils {
    use super::*;

    /// Quick text visualization of a model
    pub fn quick_text_viz<M: Module>(model: &M, input_shape: &[usize]) -> Result<String> {
        let graph = create_graph_from_model(model, input_shape)?;
        let renderer = TextRenderer::new(VisualizationConfig::default());
        Ok(renderer.render(&graph))
    }

    /// Quick ASCII art visualization of a model
    pub fn quick_ascii_viz<M: Module>(model: &M, input_shape: &[usize]) -> Result<String> {
        let graph = create_graph_from_model(model, input_shape)?;
        let renderer = AsciiRenderer::new(VisualizationConfig::default());
        Ok(renderer.render(&graph))
    }

    /// Generate DOT format for Graphviz
    pub fn generate_dot<M: Module>(model: &M, input_shape: &[usize]) -> Result<String> {
        let graph = create_graph_from_model(model, input_shape)?;
        let renderer = DotRenderer::new(VisualizationConfig::default());
        Ok(renderer.render(&graph))
    }

    /// Print a quick visualization to stdout
    pub fn print_model_viz<M: Module>(model: &M, input_shape: &[usize]) -> Result<()> {
        let viz = quick_text_viz(model, input_shape)?;
        println!("{}", viz);
        Ok(())
    }
}

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

    #[test]
    fn test_graph_node_creation() {
        let node = GraphNode::new(
            "linear1".to_string(),
            "Linear Layer 1".to_string(),
            "Linear".to_string(),
            vec![10, 20],
            vec![10, 30],
            630,
        );

        assert_eq!(node.id, "linear1");
        assert_eq!(node.layer_type, "Linear");
        assert_eq!(node.parameter_count, 630);
    }

    #[test]
    fn test_graph_edge_creation() {
        let edge = GraphEdge::new("input".to_string(), "linear1".to_string(), vec![10, 20])
            .with_style(EdgeStyle::Skip);

        assert_eq!(edge.from, "input");
        assert_eq!(edge.to, "linear1");
        assert_eq!(edge.style, EdgeStyle::Skip);
    }

    #[test]
    fn test_network_graph() {
        let mut graph = NetworkGraph::new();

        let node1 = GraphNode::new(
            "input".to_string(),
            "Input".to_string(),
            "Input".to_string(),
            vec![],
            vec![10, 20],
            0,
        );

        let node2 = GraphNode::new(
            "linear".to_string(),
            "Linear".to_string(),
            "Linear".to_string(),
            vec![10, 20],
            vec![10, 30],
            630,
        );

        graph.add_node(node1);
        graph.add_node(node2);

        let edge = GraphEdge::new("input".to_string(), "linear".to_string(), vec![10, 20]);
        graph.add_edge(edge);

        assert_eq!(graph.nodes.len(), 2);
        assert_eq!(graph.edges.len(), 1);
    }

    #[test]
    fn test_topological_sort() -> Result<()> {
        let mut graph = NetworkGraph::new();

        // Create linear chain: A -> B -> C
        for (id, name) in [("A", "Node A"), ("B", "Node B"), ("C", "Node C")] {
            let node = GraphNode::new(
                id.to_string(),
                name.to_string(),
                "Test".to_string(),
                vec![10],
                vec![10],
                0,
            );
            graph.add_node(node);
        }

        graph.add_edge(GraphEdge::new("A".to_string(), "B".to_string(), vec![10]));
        graph.add_edge(GraphEdge::new("B".to_string(), "C".to_string(), vec![10]));

        let sorted = graph.topological_sort()?;
        assert_eq!(
            sorted,
            vec!["A".to_string(), "B".to_string(), "C".to_string()]
        );

        Ok(())
    }

    #[test]
    fn test_graph_statistics() -> Result<()> {
        let mut graph = NetworkGraph::new();

        let node1 = GraphNode::new(
            "linear1".to_string(),
            "Linear 1".to_string(),
            "Linear".to_string(),
            vec![10],
            vec![20],
            210,
        );

        let node2 = GraphNode::new(
            "linear2".to_string(),
            "Linear 2".to_string(),
            "Linear".to_string(),
            vec![20],
            vec![30],
            630,
        );

        graph.add_node(node1);
        graph.add_node(node2);

        let stats = graph.calculate_statistics();
        assert_eq!(stats.total_nodes, 2);
        assert_eq!(stats.total_parameters, 840);
        assert_eq!(stats.unique_layer_types, 1);

        Ok(())
    }

    #[test]
    fn test_text_renderer() -> Result<()> {
        let model = Linear::new(64, 32, true);
        let graph = create_graph_from_model(&model, &[10, 64])?;

        let config = VisualizationConfig::default();
        let renderer = TextRenderer::new(config);
        let output = renderer.render(&graph);

        assert!(output.contains("Network Architecture Visualization"));
        assert!(output.contains("Nodes:"));
        assert!(output.contains("Connections:"));

        Ok(())
    }

    #[test]
    fn test_ascii_renderer() -> Result<()> {
        let model = Linear::new(32, 16, true);
        let graph = create_graph_from_model(&model, &[5, 32])?;

        let config = VisualizationConfig::default();
        let renderer = AsciiRenderer::new(config);
        let output = renderer.render(&graph);

        assert!(!output.is_empty());

        Ok(())
    }

    #[test]
    fn test_dot_renderer() -> Result<()> {
        let model = Linear::new(16, 8, true);
        let graph = create_graph_from_model(&model, &[3, 16])?;

        let config = VisualizationConfig::default();
        let renderer = DotRenderer::new(config);
        let output = renderer.render(&graph);

        assert!(output.contains("digraph NetworkGraph"));
        assert!(output.contains("->"));

        Ok(())
    }

    #[test]
    fn test_utils_functions() -> Result<()> {
        let model = Linear::new(128, 64, true);

        let text_viz = utils::quick_text_viz(&model, &[8, 128])?;
        assert!(!text_viz.is_empty());

        let ascii_viz = utils::quick_ascii_viz(&model, &[8, 128])?;
        assert!(!ascii_viz.is_empty());

        let dot_viz = utils::generate_dot(&model, &[8, 128])?;
        assert!(dot_viz.contains("digraph"));

        Ok(())
    }
}