Skip to content

Commit

Permalink
feat: add a method to visualize the network graph
Browse files Browse the repository at this point in the history
Signed-off-by: Tarek <[email protected]>
  • Loading branch information
tareknaser committed May 31, 2024
1 parent ebec429 commit 18424a2
Show file tree
Hide file tree
Showing 3 changed files with 66 additions and 0 deletions.
39 changes: 39 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions barq-common/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,6 @@ edition = "2021"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
log = "0.4"

# Dependencies to visualize the graph
petgraph = "0.6"
24 changes: 24 additions & 0 deletions barq-common/src/graph.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

use petgraph::{
dot::{Config, Dot},
graph::{DiGraph, NodeIndex},
};

/// Represents a node in the network graph.
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Node {
Expand Down Expand Up @@ -113,6 +118,25 @@ impl NetworkGraph {

// TODO: Add methods for updating nodes and edges.
// TODO: Add methods for removing nodes and edges.

/// Returns a DOT representation of the network graph.
pub fn to_dot(&self) -> String {
let mut graph = DiGraph::new();
let mut node_indices: HashMap<String, NodeIndex> = HashMap::new();

for node in self.nodes.values() {
let node_index = graph.add_node(node.id.clone());
node_indices.insert(node.id.clone(), node_index);
}

for edge in self.edges.values() {
let source_index = node_indices.get(&edge.source).unwrap();
let destination_index = node_indices.get(&edge.destination).unwrap();
graph.add_edge(*source_index, *destination_index, edge.capacity);
}

format!("{:?}", Dot::with_config(&graph, &[Config::EdgeNoLabel]))
}
}

#[cfg(test)]
Expand Down

0 comments on commit 18424a2

Please sign in to comment.