|
| 1 | +// Licensed under the Apache License, Version 2.0 (the "License"); you may |
| 2 | +// not use this file except in compliance with the License. You may obtain |
| 3 | +// a copy of the License at |
| 4 | +// |
| 5 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 6 | +// |
| 7 | +// Unless required by applicable law or agreed to in writing, software |
| 8 | +// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT |
| 9 | +// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the |
| 10 | +// License for the specific language governing permissions and limitations |
| 11 | +// under the License. |
| 12 | +use hashbrown::HashMap; |
| 13 | + |
| 14 | +use petgraph::algo; |
| 15 | +use petgraph::graph::NodeIndex; |
| 16 | +use petgraph::visit::{ |
| 17 | + EdgeRef, GraphBase, GraphProp, IntoEdgesDirected, IntoNeighborsDirected, IntoNodeIdentifiers, |
| 18 | + Visitable, |
| 19 | +}; |
| 20 | +use petgraph::Directed; |
| 21 | + |
| 22 | +use num_traits::{Num, Zero}; |
| 23 | + |
| 24 | +// Type aliases for readability |
| 25 | +type NodeId<G> = <G as GraphBase>::NodeId; |
| 26 | +type LongestPathResult<G, T, E> = Result<Option<(Vec<NodeId<G>>, T)>, E>; |
| 27 | + |
| 28 | +/// Calculates the longest path in a directed acyclic graph (DAG). |
| 29 | +/// |
| 30 | +/// This function computes the longest path by weight in a given DAG. It will return the longest path |
| 31 | +/// along with its total weight, or `None` if the graph contains cycles which make the longest path |
| 32 | +/// computation undefined. |
| 33 | +/// |
| 34 | +/// # Arguments |
| 35 | +/// * `graph`: Reference to a directed graph. |
| 36 | +/// * `weight_fn` - An input callable that will be passed the `EdgeRef` for each edge in the graph. |
| 37 | +/// The callable should return the weight of the edge as `Result<T, E>`. The weight must be a type that implements |
| 38 | +/// `Num`, `Zero`, `PartialOrd`, and `Copy`. |
| 39 | +/// |
| 40 | +/// # Type Parameters |
| 41 | +/// * `G`: Type of the graph. Must be a directed graph. |
| 42 | +/// * `F`: Type of the weight function. |
| 43 | +/// * `T`: The type of the edge weight. Must implement `Num`, `Zero`, `PartialOrd`, and `Copy`. |
| 44 | +/// * `E`: The type of the error that the weight function can return. |
| 45 | +/// |
| 46 | +/// # Returns |
| 47 | +/// * `None` if the graph contains a cycle. |
| 48 | +/// * `Some((Vec<NodeId<G>>, T))` representing the longest path as a sequence of nodes and its total weight. |
| 49 | +/// * `Err(E)` if there is an error computing the weight of any edge. |
| 50 | +/// |
| 51 | +/// # Example |
| 52 | +/// ``` |
| 53 | +/// use petgraph::graph::DiGraph; |
| 54 | +/// use petgraph::graph::NodeIndex; |
| 55 | +/// use petgraph::Directed; |
| 56 | +/// use rustworkx_core::dag_algo::longest_path; |
| 57 | +/// |
| 58 | +/// let mut graph: DiGraph<(), i32> = DiGraph::new(); |
| 59 | +/// let n0 = graph.add_node(()); |
| 60 | +/// let n1 = graph.add_node(()); |
| 61 | +/// let n2 = graph.add_node(()); |
| 62 | +/// graph.add_edge(n0, n1, 1); |
| 63 | +/// graph.add_edge(n0, n2, 3); |
| 64 | +/// graph.add_edge(n1, n2, 1); |
| 65 | +/// |
| 66 | +/// let weight_fn = |edge: petgraph::graph::EdgeReference<i32>| Ok::<i32, &str>(*edge.weight()); |
| 67 | +/// let result = longest_path(&graph, weight_fn).unwrap(); |
| 68 | +/// assert_eq!(result, Some((vec![n0, n2], 3))); |
| 69 | +/// ``` |
| 70 | +pub fn longest_path<G, F, T, E>(graph: G, mut weight_fn: F) -> LongestPathResult<G, T, E> |
| 71 | +where |
| 72 | + G: GraphProp<EdgeType = Directed> |
| 73 | + + IntoNodeIdentifiers |
| 74 | + + IntoNeighborsDirected |
| 75 | + + IntoEdgesDirected |
| 76 | + + Visitable |
| 77 | + + GraphBase<NodeId = NodeIndex>, |
| 78 | + F: FnMut(G::EdgeRef) -> Result<T, E>, |
| 79 | + T: Num + Zero + PartialOrd + Copy, |
| 80 | +{ |
| 81 | + let mut path: Vec<NodeId<G>> = Vec::new(); |
| 82 | + let nodes = match algo::toposort(graph, None) { |
| 83 | + Ok(nodes) => nodes, |
| 84 | + Err(_) => return Ok(None), // Return None if the graph contains a cycle |
| 85 | + }; |
| 86 | + |
| 87 | + if nodes.is_empty() { |
| 88 | + return Ok(Some((path, T::zero()))); |
| 89 | + } |
| 90 | + |
| 91 | + let mut dist: HashMap<NodeIndex, (T, NodeIndex)> = HashMap::with_capacity(nodes.len()); // Stores the distance and the previous node |
| 92 | + |
| 93 | + // Iterate over nodes in topological order |
| 94 | + for node in nodes { |
| 95 | + let parents = graph.edges_directed(node, petgraph::Direction::Incoming); |
| 96 | + let mut incoming_path: Vec<(T, NodeIndex)> = Vec::new(); // Stores the distance and the previous node for each parent |
| 97 | + for p_edge in parents { |
| 98 | + let p_node = p_edge.source(); |
| 99 | + let weight: T = weight_fn(p_edge)?; |
| 100 | + let length = dist[&p_node].0 + weight; |
| 101 | + incoming_path.push((length, p_node)); |
| 102 | + } |
| 103 | + // Determine the maximum distance and corresponding parent node |
| 104 | + let max_path: (T, NodeIndex) = incoming_path |
| 105 | + .into_iter() |
| 106 | + .max_by(|a, b| a.0.partial_cmp(&b.0).unwrap()) |
| 107 | + .unwrap_or((T::zero(), node)); // If there are no incoming edges, the distance is zero |
| 108 | + |
| 109 | + // Store the maximum distance and the corresponding parent node for the current node |
| 110 | + dist.insert(node, max_path); |
| 111 | + } |
| 112 | + let (first, _) = dist |
| 113 | + .iter() |
| 114 | + .max_by(|a, b| a.1.partial_cmp(b.1).unwrap()) |
| 115 | + .unwrap(); |
| 116 | + let mut v = *first; |
| 117 | + let mut u: Option<NodeIndex> = None; |
| 118 | + // Backtrack from this node to find the path |
| 119 | + while u.map_or(true, |u| u != v) { |
| 120 | + path.push(v); |
| 121 | + u = Some(v); |
| 122 | + v = dist[&v].1; |
| 123 | + } |
| 124 | + path.reverse(); // Reverse the path to get the correct order |
| 125 | + let path_weight = dist[first].0; // The total weight of the longest path |
| 126 | + |
| 127 | + Ok(Some((path, path_weight))) |
| 128 | +} |
| 129 | + |
| 130 | +#[cfg(test)] |
| 131 | +mod test_longest_path { |
| 132 | + use super::*; |
| 133 | + use petgraph::graph::DiGraph; |
| 134 | + use petgraph::stable_graph::StableDiGraph; |
| 135 | + |
| 136 | + #[test] |
| 137 | + fn test_empty_graph() { |
| 138 | + let graph: DiGraph<(), ()> = DiGraph::new(); |
| 139 | + let weight_fn = |_: petgraph::graph::EdgeReference<()>| Ok::<i32, &str>(0); |
| 140 | + let result = longest_path(&graph, weight_fn); |
| 141 | + assert_eq!(result, Ok(Some((vec![], 0)))); |
| 142 | + } |
| 143 | + |
| 144 | + #[test] |
| 145 | + fn test_single_node_graph() { |
| 146 | + let mut graph: DiGraph<(), ()> = DiGraph::new(); |
| 147 | + let n0 = graph.add_node(()); |
| 148 | + let weight_fn = |_: petgraph::graph::EdgeReference<()>| Ok::<i32, &str>(0); |
| 149 | + let result = longest_path(&graph, weight_fn); |
| 150 | + assert_eq!(result, Ok(Some((vec![n0], 0)))); |
| 151 | + } |
| 152 | + |
| 153 | + #[test] |
| 154 | + fn test_dag_with_multiple_paths() { |
| 155 | + let mut graph: DiGraph<(), i32> = DiGraph::new(); |
| 156 | + let n0 = graph.add_node(()); |
| 157 | + let n1 = graph.add_node(()); |
| 158 | + let n2 = graph.add_node(()); |
| 159 | + let n3 = graph.add_node(()); |
| 160 | + let n4 = graph.add_node(()); |
| 161 | + let n5 = graph.add_node(()); |
| 162 | + graph.add_edge(n0, n1, 3); |
| 163 | + graph.add_edge(n0, n2, 2); |
| 164 | + graph.add_edge(n1, n2, 1); |
| 165 | + graph.add_edge(n1, n3, 4); |
| 166 | + graph.add_edge(n2, n3, 2); |
| 167 | + graph.add_edge(n3, n4, 2); |
| 168 | + graph.add_edge(n2, n5, 1); |
| 169 | + graph.add_edge(n4, n5, 3); |
| 170 | + let weight_fn = |edge: petgraph::graph::EdgeReference<i32>| Ok::<i32, &str>(*edge.weight()); |
| 171 | + let result = longest_path(&graph, weight_fn); |
| 172 | + assert_eq!(result, Ok(Some((vec![n0, n1, n3, n4, n5], 12)))); |
| 173 | + } |
| 174 | + |
| 175 | + #[test] |
| 176 | + fn test_graph_with_cycle() { |
| 177 | + let mut graph: DiGraph<(), i32> = DiGraph::new(); |
| 178 | + let n0 = graph.add_node(()); |
| 179 | + let n1 = graph.add_node(()); |
| 180 | + graph.add_edge(n0, n1, 1); |
| 181 | + graph.add_edge(n1, n0, 1); // Creates a cycle |
| 182 | + |
| 183 | + let weight_fn = |edge: petgraph::graph::EdgeReference<i32>| Ok::<i32, &str>(*edge.weight()); |
| 184 | + let result = longest_path(&graph, weight_fn); |
| 185 | + assert_eq!(result, Ok(None)); |
| 186 | + } |
| 187 | + |
| 188 | + #[test] |
| 189 | + fn test_negative_weights() { |
| 190 | + let mut graph: DiGraph<(), i32> = DiGraph::new(); |
| 191 | + let n0 = graph.add_node(()); |
| 192 | + let n1 = graph.add_node(()); |
| 193 | + let n2 = graph.add_node(()); |
| 194 | + graph.add_edge(n0, n1, -1); |
| 195 | + graph.add_edge(n0, n2, 2); |
| 196 | + graph.add_edge(n1, n2, -2); |
| 197 | + let weight_fn = |edge: petgraph::graph::EdgeReference<i32>| Ok::<i32, &str>(*edge.weight()); |
| 198 | + let result = longest_path(&graph, weight_fn); |
| 199 | + assert_eq!(result, Ok(Some((vec![n0, n2], 2)))); |
| 200 | + } |
| 201 | + |
| 202 | + #[test] |
| 203 | + fn test_longest_path_in_stable_digraph() { |
| 204 | + let mut graph: StableDiGraph<(), i32> = StableDiGraph::new(); |
| 205 | + let n0 = graph.add_node(()); |
| 206 | + let n1 = graph.add_node(()); |
| 207 | + let n2 = graph.add_node(()); |
| 208 | + graph.add_edge(n0, n1, 1); |
| 209 | + graph.add_edge(n0, n2, 3); |
| 210 | + graph.add_edge(n1, n2, 1); |
| 211 | + let weight_fn = |
| 212 | + |edge: petgraph::stable_graph::EdgeReference<'_, i32>| Ok::<i32, &str>(*edge.weight()); |
| 213 | + let result = longest_path(&graph, weight_fn); |
| 214 | + assert_eq!(result, Ok(Some((vec![n0, n2], 3)))); |
| 215 | + } |
| 216 | + |
| 217 | + #[test] |
| 218 | + fn test_error_handling() { |
| 219 | + let mut graph: DiGraph<(), i32> = DiGraph::new(); |
| 220 | + let n0 = graph.add_node(()); |
| 221 | + let n1 = graph.add_node(()); |
| 222 | + let n2 = graph.add_node(()); |
| 223 | + graph.add_edge(n0, n1, 1); |
| 224 | + graph.add_edge(n0, n2, 2); |
| 225 | + graph.add_edge(n1, n2, 1); |
| 226 | + let weight_fn = |edge: petgraph::graph::EdgeReference<i32>| { |
| 227 | + if *edge.weight() == 2 { |
| 228 | + Err("Error: edge weight is 2") |
| 229 | + } else { |
| 230 | + Ok::<i32, &str>(*edge.weight()) |
| 231 | + } |
| 232 | + }; |
| 233 | + let result = longest_path(&graph, weight_fn); |
| 234 | + assert_eq!(result, Err("Error: edge weight is 2")); |
| 235 | + } |
| 236 | +} |
0 commit comments