use petgraph::prelude::*;
use std::collections::{HashMap, HashSet};
#[derive(Debug, Clone)]
pub struct LayoutOptions {
pub rank_dir: RankDir,
pub node_sep: f32,
pub rank_sep: f32,
pub max_iterations: usize,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RankDir {
TopToBottom,
LeftToRight,
}
impl Default for LayoutOptions {
fn default() -> Self {
Self {
rank_dir: RankDir::TopToBottom,
node_sep: 50.0,
rank_sep: 100.0,
max_iterations: 24,
}
}
}
#[derive(Debug, Clone)]
pub struct LayoutResult {
pub node_positions: HashMap<NodeIndex, (f32, f32)>,
pub layers: Vec<Vec<NodeIndex>>,
pub width: f32,
pub height: f32,
}
pub struct DagreLayout {
pub options: LayoutOptions,
}
impl DagreLayout {
pub fn new() -> Self {
Self {
options: LayoutOptions::default(),
}
}
pub fn with_options(options: LayoutOptions) -> Self {
Self { options }
}
pub fn compute<N, E>(&self, graph: &DiGraph<N, E>) -> LayoutResult {
let mut layers = self.assign_layers_longest_path(graph);
self.reduce_crossings(graph, &mut layers);
let (node_positions, width, height) = self.assign_coordinates(&layers);
LayoutResult {
node_positions,
layers,
width,
height,
}
}
fn assign_layers_longest_path<N, E>(&self, graph: &DiGraph<N, E>) -> Vec<Vec<NodeIndex>> {
let mut distances = HashMap::new();
let mut visited = HashSet::new();
let sources: Vec<_> = graph
.node_indices()
.filter(|&n| graph.neighbors_directed(n, Incoming).count() == 0)
.collect();
let sources = if sources.is_empty() {
graph.node_indices().take(1).collect()
} else {
sources
};
for &source in &sources {
self.dfs_longest_path(graph, source, 0, &mut distances, &mut visited);
}
for node in graph.node_indices() {
if !distances.contains_key(&node) {
self.dfs_longest_path(graph, node, 0, &mut distances, &mut visited);
}
}
let max_layer = distances.values().copied().max().unwrap_or(0);
let mut layers = vec![Vec::new(); max_layer + 1];
for (&node, &layer) in &distances {
layers[layer].push(node);
}
layers
.into_iter()
.filter(|layer| !layer.is_empty())
.collect()
}
fn dfs_longest_path<N, E>(
&self,
graph: &DiGraph<N, E>,
node: NodeIndex,
current_distance: usize,
distances: &mut HashMap<NodeIndex, usize>,
visited: &mut HashSet<NodeIndex>,
) {
if visited.contains(&node) {
return;
}
visited.insert(node);
let best_distance = distances.get(&node).copied().unwrap_or(0);
let new_distance = current_distance.max(best_distance);
distances.insert(node, new_distance);
for successor in graph.neighbors_directed(node, Outgoing) {
self.dfs_longest_path(graph, successor, new_distance + 1, distances, visited);
}
}
fn reduce_crossings<N, E>(&self, graph: &DiGraph<N, E>, layers: &mut Vec<Vec<NodeIndex>>) {
if layers.len() < 2 {
return;
}
for _ in 0..self.options.max_iterations {
let mut improved = false;
for i in 1..layers.len() {
let new_order = self.order_by_barycenter(graph, &layers[i], &layers[i - 1], true);
if new_order != layers[i] {
layers[i] = new_order;
improved = true;
}
}
for i in (0..layers.len() - 1).rev() {
let new_order = self.order_by_barycenter(graph, &layers[i], &layers[i + 1], false);
if new_order != layers[i] {
layers[i] = new_order;
improved = true;
}
}
if !improved {
break;
}
}
}
fn order_by_barycenter<N, E>(
&self,
graph: &DiGraph<N, E>,
layer: &[NodeIndex],
adjacent_layer: &[NodeIndex],
use_predecessors: bool,
) -> Vec<NodeIndex> {
let positions: HashMap<NodeIndex, usize> = adjacent_layer
.iter()
.enumerate()
.map(|(pos, &node)| (node, pos))
.collect();
let mut node_barycenters: Vec<(NodeIndex, f32)> = layer
.iter()
.map(|&node| {
let connected_positions: Vec<usize> = if use_predecessors {
graph
.neighbors_directed(node, Incoming)
.filter_map(|pred| positions.get(&pred))
.copied()
.collect()
} else {
graph
.neighbors_directed(node, Outgoing)
.filter_map(|succ| positions.get(&succ))
.copied()
.collect()
};
let barycenter = if connected_positions.is_empty() {
layer.iter().position(|&n| n == node).unwrap() as f32
} else {
connected_positions.iter().sum::<usize>() as f32
/ connected_positions.len() as f32
};
(node, barycenter)
})
.collect();
node_barycenters.sort_by(|a, b| {
a.1.partial_cmp(&b.1)
.unwrap_or(std::cmp::Ordering::Equal)
.then_with(|| a.0.cmp(&b.0))
});
node_barycenters.into_iter().map(|(node, _)| node).collect()
}
fn assign_coordinates(
&self,
layers: &[Vec<NodeIndex>],
) -> (HashMap<NodeIndex, (f32, f32)>, f32, f32) {
let mut positions = HashMap::new();
let LayoutOptions {
rank_dir,
node_sep,
rank_sep,
..
} = &self.options;
let max_layer_width = layers.iter().map(|layer| layer.len()).max().unwrap_or(0) as f32;
for (layer_idx, layer) in layers.iter().enumerate() {
let layer_width = layer.len() as f32;
let start_offset = (max_layer_width - layer_width) * node_sep * 0.5;
for (node_idx, &node) in layer.iter().enumerate() {
let (x, y) = match rank_dir {
RankDir::TopToBottom => (
start_offset + node_idx as f32 * node_sep,
layer_idx as f32 * rank_sep,
),
RankDir::LeftToRight => (
layer_idx as f32 * rank_sep,
start_offset + node_idx as f32 * node_sep,
),
};
positions.insert(node, (x, y));
}
}
let (width, height) = match rank_dir {
RankDir::TopToBottom => (max_layer_width * node_sep, layers.len() as f32 * rank_sep),
RankDir::LeftToRight => (layers.len() as f32 * rank_sep, max_layer_width * node_sep),
};
(positions, width, height)
}
}
impl Default for DagreLayout {
fn default() -> Self {
Self::new()
}
}
#[cfg(test)]
mod tests {
use super::*;
use petgraph::Graph;
#[test]
fn test_simple_chain() {
let mut graph = Graph::new();
let a = graph.add_node("A");
let b = graph.add_node("B");
let c = graph.add_node("C");
graph.add_edge(a, b, ());
graph.add_edge(b, c, ());
let layout = DagreLayout::new();
let result = layout.compute(&graph);
assert_eq!(result.layers.len(), 3);
assert_eq!(result.layers[0], vec![a]);
assert_eq!(result.layers[1], vec![b]);
assert_eq!(result.layers[2], vec![c]);
}
#[test]
fn test_diamond_pattern() {
let mut graph = Graph::new();
let start = graph.add_node("start");
let left = graph.add_node("left");
let right = graph.add_node("right");
let end = graph.add_node("end");
graph.add_edge(start, left, ());
graph.add_edge(start, right, ());
graph.add_edge(left, end, ());
graph.add_edge(right, end, ());
let layout = DagreLayout::new();
let result = layout.compute(&graph);
assert_eq!(result.layers.len(), 3);
assert_eq!(result.layers[0], vec![start]);
assert_eq!(result.layers[1].len(), 2);
assert!(result.layers[1].contains(&left));
assert!(result.layers[1].contains(&right));
assert_eq!(result.layers[2], vec![end]);
}
#[test]
fn test_left_to_right_layout() {
let mut graph = Graph::new();
let a = graph.add_node("A");
let b = graph.add_node("B");
graph.add_edge(a, b, ());
let options = LayoutOptions {
rank_dir: RankDir::LeftToRight,
..Default::default()
};
let layout = DagreLayout::with_options(options);
let result = layout.compute(&graph);
let pos_a = result.node_positions[&a];
let pos_b = result.node_positions[&b];
assert!(pos_b.0 > pos_a.0);
}
#[test]
fn test_empty_graph() {
let graph: Graph<&str, (), petgraph::Directed> = Graph::new();
let layout = DagreLayout::new();
let result = layout.compute(&graph);
assert!(result.layers.is_empty());
assert!(result.node_positions.is_empty());
}
#[test]
fn test_single_node() {
let mut graph: Graph<&str, (), petgraph::Directed> = Graph::new();
let node = graph.add_node("single");
let layout = DagreLayout::new();
let result = layout.compute(&graph);
assert_eq!(result.layers.len(), 1);
assert_eq!(result.layers[0], vec![node]);
assert_eq!(result.node_positions[&node], (0.0, 0.0));
}
#[test]
fn test_layer_ordering_properties() {
let mut graph = Graph::new();
let a = graph.add_node("A");
let b = graph.add_node("B");
let c = graph.add_node("C");
let d = graph.add_node("D");
graph.add_edge(a, b, ());
graph.add_edge(a, c, ());
graph.add_edge(b, d, ());
graph.add_edge(c, d, ());
let layout = DagreLayout::new();
let result = layout.compute(&graph);
let mut node_to_layer = std::collections::HashMap::new();
for (layer_idx, layer) in result.layers.iter().enumerate() {
for &node in layer {
node_to_layer.insert(node, layer_idx);
}
}
for edge in graph.edge_indices() {
if let Some((source, target)) = graph.edge_endpoints(edge) {
let source_layer = node_to_layer[&source];
let target_layer = node_to_layer[&target];
assert!(
source_layer < target_layer,
"Edge from layer {} to layer {} violates hierarchy",
source_layer,
target_layer
);
}
}
}
#[test]
fn test_coordinate_consistency() {
let mut graph = Graph::new();
let a = graph.add_node("A");
let b = graph.add_node("B");
let c = graph.add_node("C");
graph.add_edge(a, b, ());
graph.add_edge(b, c, ());
let layout = DagreLayout::new();
let result = layout.compute(&graph);
let pos_a = result.node_positions[&a];
let pos_b = result.node_positions[&b];
let pos_c = result.node_positions[&c];
assert!(pos_a.1 < pos_b.1, "A should be above B");
assert!(pos_b.1 < pos_c.1, "B should be above C");
}
#[test]
fn test_spacing_configuration() {
let mut graph = Graph::new();
let a = graph.add_node("A");
let b = graph.add_node("B");
let c = graph.add_node("C");
graph.add_edge(a, b, ());
graph.add_edge(a, c, ());
let options = LayoutOptions {
node_sep: 100.0,
rank_sep: 200.0,
..Default::default()
};
let layout = DagreLayout::with_options(options);
let result = layout.compute(&graph);
let pos_a = result.node_positions[&a];
let pos_b = result.node_positions[&b];
let pos_c = result.node_positions[&c];
let horizontal_distance = (pos_b.0 - pos_c.0).abs();
assert_eq!(horizontal_distance, 100.0, "Node separation not applied correctly");
let vertical_distance = pos_b.1 - pos_a.1;
assert_eq!(vertical_distance, 200.0, "Rank separation not applied correctly");
}
#[test]
fn test_disconnected_components() {
let mut graph = Graph::new();
let a = graph.add_node("A");
let b = graph.add_node("B");
graph.add_edge(a, b, ());
let c = graph.add_node("C");
let d = graph.add_node("D");
graph.add_edge(c, d, ());
let layout = DagreLayout::new();
let result = layout.compute(&graph);
assert!(result.layers.len() >= 2);
assert_eq!(result.node_positions.len(), 4);
for &node in &[a, b, c, d] {
assert!(result.node_positions.contains_key(&node));
}
}
#[test]
fn test_layout_determinism() {
let mut graph = Graph::new();
let nodes: Vec<_> = (0..5).map(|i| graph.add_node(format!("Node{}", i))).collect();
graph.add_edge(nodes[0], nodes[1], ());
graph.add_edge(nodes[0], nodes[2], ());
graph.add_edge(nodes[1], nodes[3], ());
graph.add_edge(nodes[2], nodes[4], ());
let layout = DagreLayout::new();
let result1 = layout.compute(&graph);
let result2 = layout.compute(&graph);
assert_eq!(result1.layers, result2.layers);
assert_eq!(result1.node_positions, result2.node_positions);
assert_eq!(result1.width, result2.width);
assert_eq!(result1.height, result2.height);
}
#[test]
fn test_crossing_reduction_effectiveness() {
let mut graph = Graph::new();
let top = graph.add_node("Top");
let left1 = graph.add_node("L1");
let left2 = graph.add_node("L2");
let right1 = graph.add_node("R1");
let right2 = graph.add_node("R2");
graph.add_edge(top, left1, ());
graph.add_edge(top, left2, ());
graph.add_edge(left1, right2, ());
graph.add_edge(left2, right1, ());
let layout = DagreLayout::new();
let result = layout.compute(&graph);
assert_eq!(result.layers.len(), 3);
let middle_layer = &result.layers[1];
assert_eq!(middle_layer.len(), 2);
assert!(middle_layer.contains(&left1));
assert!(middle_layer.contains(&left2));
}
#[test]
fn test_longest_path_layer_assignment() {
let mut graph = Graph::new();
let a = graph.add_node("A");
let b = graph.add_node("B");
let c = graph.add_node("C");
let d = graph.add_node("D");
graph.add_edge(a, b, ());
graph.add_edge(b, d, ());
graph.add_edge(a, c, ());
graph.add_edge(c, d, ());
let layout = DagreLayout::new();
let result = layout.compute(&graph);
assert_eq!(result.layers.len(), 3);
assert_eq!(result.layers[0], vec![a]);
let middle_layer = &result.layers[1];
assert_eq!(middle_layer.len(), 2);
assert!(middle_layer.contains(&b));
assert!(middle_layer.contains(&c));
assert_eq!(result.layers[2], vec![d]);
}
}