dagre-rs 0.1.0

Hierarchical Layout Calculation for directed graphs
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
use petgraph::prelude::*;
use std::collections::{HashMap, HashSet};

/// Configuration options for graph layout calculation
#[derive(Debug, Clone)]
pub struct LayoutOptions {
    /// Primary layout direction
    pub rank_dir: RankDir,
    /// Minimum horizontal separation between nodes in the same layer (pixels)
    pub node_sep: f32,
    /// Minimum vertical separation between layers (pixels)
    pub rank_sep: f32,
    /// Maximum number of iterations for crossing reduction
    pub max_iterations: usize,
}

/// Layout direction for the graph
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RankDir {
    /// Nodes flow from top to bottom
    TopToBottom,
    /// Nodes flow from left to right
    LeftToRight,
}

impl Default for LayoutOptions {
    fn default() -> Self {
        Self {
            rank_dir: RankDir::TopToBottom,
            node_sep: 50.0,
            rank_sep: 100.0,
            max_iterations: 24,
        }
    }
}

/// Result of layout calculation containing node positions and layer information
#[derive(Debug, Clone)]
pub struct LayoutResult {
    /// Final positions for each node as (x, y) coordinates
    pub node_positions: HashMap<NodeIndex, (f32, f32)>,
    /// Nodes organized by layers, from first to last
    pub layers: Vec<Vec<NodeIndex>>,
    /// Total width of the layout
    pub width: f32,
    /// Total height of the layout
    pub height: f32,
}

/// Main layout engine implementing the Sugiyama method
pub struct DagreLayout {
    /// Layout configuration options
    pub options: LayoutOptions,
}

impl DagreLayout {
    /// Create a new layout engine with default options
    pub fn new() -> Self {
        Self {
            options: LayoutOptions::default(),
        }
    }

    /// Create a new layout engine with custom options
    pub fn with_options(options: LayoutOptions) -> Self {
        Self { options }
    }

    /// Compute the layout for a directed graph using the Sugiyama method
    ///
    /// This method implements the four phases of the Sugiyama algorithm:
    /// 1. Cycle removal (assumes DAG input for now)
    /// 2. Layer assignment using longest path
    /// 3. Crossing reduction using barycenter heuristic
    /// 4. Coordinate assignment with proper spacing
    ///
    /// # Arguments
    /// * `graph` - The directed graph to layout
    ///
    /// # Returns
    /// A `LayoutResult` containing node positions and metadata
    ///
    /// # Example
    /// ```
    /// use dagrers::{DagreLayout, LayoutOptions, RankDir};
    /// use petgraph::Graph;
    ///
    /// let mut graph = Graph::new();
    /// let a = graph.add_node("A");
    /// let b = graph.add_node("B");
    /// graph.add_edge(a, b, ());
    ///
    /// let layout = DagreLayout::new();
    /// let result = layout.compute(&graph);
    /// ```
    pub fn compute<N, E>(&self, graph: &DiGraph<N, E>) -> LayoutResult {
        // Phase 1: Cycle removal (assume DAG for now)
        // TODO: Implement cycle detection and removal

        // Phase 2: Layer assignment
        let mut layers = self.assign_layers_longest_path(graph);

        // Phase 3: Crossing reduction
        self.reduce_crossings(graph, &mut layers);

        // Phase 4: Coordinate assignment
        let (node_positions, width, height) = self.assign_coordinates(&layers);

        LayoutResult {
            node_positions,
            layers,
            width,
            height,
        }
    }

    /// Assign nodes to layers using longest path algorithm
    /// This creates more balanced layouts than simple topological sorting
    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();

        // Find all source nodes (no incoming edges)
        let sources: Vec<_> = graph
            .node_indices()
            .filter(|&n| graph.neighbors_directed(n, Incoming).count() == 0)
            .collect();

        // If no sources found, pick an arbitrary starting node
        let sources = if sources.is_empty() {
            graph.node_indices().take(1).collect()
        } else {
            sources
        };

        // Calculate longest paths from sources using DFS
        for &source in &sources {
            self.dfs_longest_path(graph, source, 0, &mut distances, &mut visited);
        }

        // Handle any remaining unvisited nodes (disconnected components)
        for node in graph.node_indices() {
            if !distances.contains_key(&node) {
                self.dfs_longest_path(graph, node, 0, &mut distances, &mut visited);
            }
        }

        // Group nodes by their layer (distance)
        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);
        }

        // Remove empty layers
        layers
            .into_iter()
            .filter(|layer| !layer.is_empty())
            .collect()
    }

    /// Depth-first search to calculate longest path distances
    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);

        // Update distance if we found a longer path
        let best_distance = distances.get(&node).copied().unwrap_or(0);
        let new_distance = current_distance.max(best_distance);
        distances.insert(node, new_distance);

        // Recursively visit successors
        for successor in graph.neighbors_directed(node, Outgoing) {
            self.dfs_longest_path(graph, successor, new_distance + 1, distances, visited);
        }
    }

    /// Reduce edge crossings using the barycenter heuristic
    /// This iteratively reorders nodes within layers to minimize crossings
    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;

            // Forward pass: order layers 1..n based on their predecessors
            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;
                }
            }

            // Backward pass: order layers n-1..0 based on their successors
            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 no improvement, we can stop early
            if !improved {
                break;
            }
        }
    }

    /// Order nodes in a layer based on barycenter of connected nodes in adjacent layer
    fn order_by_barycenter<N, E>(
        &self,
        graph: &DiGraph<N, E>,
        layer: &[NodeIndex],
        adjacent_layer: &[NodeIndex],
        use_predecessors: bool,
    ) -> Vec<NodeIndex> {
        // Create position map for adjacent layer
        let positions: HashMap<NodeIndex, usize> = adjacent_layer
            .iter()
            .enumerate()
            .map(|(pos, &node)| (node, pos))
            .collect();

        // Calculate barycenter for each node in current layer
        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() {
                    // No connections, maintain relative position
                    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();

        // Sort by barycenter, maintaining stable order for ties
        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()
    }

    /// Assign final coordinates to nodes with proper spacing
    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;

            // Center the layer
            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));
            }
        }

        // Calculate total dimensions
        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];

        // In left-to-right layout, B should be to the right of A
        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() {
        // Test that edges only go from lower layer indices to higher layer indices
        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);

        // Create a mapping from node to layer index
        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);
            }
        }

        // Verify all edges respect layer ordering
        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);

        // In top-to-bottom layout, Y coordinates should increase with layer depth
        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];

        // Nodes B and C should be separated by node_sep horizontally
        let horizontal_distance = (pos_b.0 - pos_c.0).abs();
        assert_eq!(horizontal_distance, 100.0, "Node separation not applied correctly");

        // A should be separated from B/C by rank_sep vertically
        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();
        
        // First component: A -> B
        let a = graph.add_node("A");
        let b = graph.add_node("B");
        graph.add_edge(a, b, ());

        // Second component: C -> D
        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);

        // Should handle disconnected components gracefully
        assert!(result.layers.len() >= 2);
        assert_eq!(result.node_positions.len(), 4);

        // All nodes should have valid positions
        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();
        
        // Create a specific edge pattern
        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();
        
        // Run layout multiple times and verify results are identical
        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() {
        // Create a graph that should have crossings if not optimized
        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");

        // Create crossing pattern: Top -> L1, L2 and L1 -> R2, L2 -> R1
        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);

        // After crossing reduction, nodes should be reordered to minimize crossings
        assert_eq!(result.layers.len(), 3);
        
        // The middle layer should contain L1 and L2
        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() {
        // Create a graph where simple topological sort vs longest path would differ
        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");

        // A -> B -> D and A -> C -> D, where B -> D path is longer
        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);

        // Should have 3 layers: {A}, {B, C}, {D}
        assert_eq!(result.layers.len(), 3);
        assert_eq!(result.layers[0], vec![a]);
        
        // B and C should be in the same layer (layer 1)
        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]);
    }
}