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
use std::iter::FusedIterator;

use bitvec::vec::BitVec;

use crate::{Direction, NodeIndex, PortGraph, PortIndex};

/// Returns an iterator doing a post-order traversal of a spanning tree in a
/// [`PortGraph`].
///
/// The iterator will visit all nodes reachable from the `source`s, returning
/// the nodes in each subtree following the port order before returning the
/// root.
///
/// # Example
///
/// We create the following tree:
///
/// a ━▸ b ┳━▸ c
///        ┣━▸ d ━▸ e
///        ┗━▸ f
///
/// And traverse it in post-order:
///
/// ```
/// # use portgraph::{algorithms::postorder, Direction, PortGraph};
/// let mut graph = PortGraph::new();
///
/// let a = graph.add_node(0, 1);
/// let b = graph.add_node(1, 3);
/// let c = graph.add_node(1, 1);
/// let d = graph.add_node(1, 1);
/// let e = graph.add_node(1, 0);
/// let f = graph.add_node(1, 0);
///
/// graph.link_nodes(a, 0, b, 0).unwrap();
/// graph.link_nodes(b, 0, c, 0).unwrap();
/// graph.link_nodes(b, 1, d, 0).unwrap();
/// graph.link_nodes(b, 2, f, 0).unwrap();
/// graph.link_nodes(d, 0, e, 0).unwrap();
///
/// // Forward starting from `a`
/// let order = postorder(&graph, vec![a], Direction::Outgoing).collect::<Vec<_>>();
/// assert_eq!(order, vec![c, e, d, f, b, a]);
///
/// // Reverse starting from `e`
/// let order = postorder(&graph, vec![e], Direction::Incoming).collect::<Vec<_>>();
/// assert_eq!(order, vec![a, b, d, e]);
/// ```
///
///
pub fn postorder(
    graph: &PortGraph,
    source: impl IntoIterator<Item = NodeIndex>,
    direction: Direction,
) -> PostOrder {
    PostOrder::new(graph, source, direction, None, None)
}

/// Returns an iterator doing a post-order traversal of a spanning tree in a
/// [`PortGraph`], applying a filter to the nodes and ports. No filtered nodes
/// are returned, and neither are any nodes only accessible via filtered nodes
/// or filtered ports.
///
/// If the filter closures return false for a node or port, it is skipped.
///
/// The iterator will visit all nodes reachable from the `source`s, returning
/// the nodes in each subtree following the port order before returning the
/// root.
///
/// # Example
///
/// We create the following tree:
///
/// a ━▸ b ┳━▸ c
///        ┣━▸ d ━▸ e
///        ┗━▸ f
///
/// And traverse it in post-order:
///
/// ```
/// # use portgraph::{algorithms::postorder_filtered, Direction, PortGraph};
/// let mut graph = PortGraph::new();
///
/// let a = graph.add_node(0, 1);
/// let b = graph.add_node(1, 3);
/// let c = graph.add_node(1, 1);
/// let d = graph.add_node(1, 1);
/// let e = graph.add_node(1, 0);
/// let f = graph.add_node(1, 0);
///
/// graph.link_nodes(a, 0, b, 0).unwrap();
/// graph.link_nodes(b, 0, c, 0).unwrap();
/// graph.link_nodes(b, 1, d, 0).unwrap();
/// graph.link_nodes(b, 2, f, 0).unwrap();
/// graph.link_nodes(d, 0, e, 0).unwrap();
///
/// // Forward starting from `a`
/// let order = postorder_filtered(
///     &graph,
///     vec![a],
///     Direction::Outgoing,
///     |_| true,
///     |_node, port| ![graph.output(b, 2), graph.input(d, 0)].contains(&Some(port))
/// ).collect::<Vec<_>>();
/// assert_eq!(order, vec![c, b, a]);
///
/// // Reverse starting from `e`
/// let order = postorder_filtered(
///     &graph,
///     vec![e],
///     Direction::Incoming,
///     |n| n != b,
///     |_,_| true
/// ).collect::<Vec<_>>();
/// assert_eq!(order, vec![d, e]);
/// ```
///
///
pub fn postorder_filtered<'graph>(
    graph: &'graph PortGraph,
    source: impl IntoIterator<Item = NodeIndex>,
    direction: Direction,
    node_filter: impl FnMut(NodeIndex) -> bool + 'graph,
    port_filter: impl FnMut(NodeIndex, PortIndex) -> bool + 'graph,
) -> PostOrder {
    PostOrder::new(
        graph,
        source,
        direction,
        Some(Box::new(node_filter)),
        Some(Box::new(port_filter)),
    )
}

/// Iterator over a [`PortGraph`] in post-order.
///
/// See [`postorder`] for more information.
pub struct PostOrder<'graph> {
    graph: &'graph PortGraph,
    stack: Vec<NodeIndex>,
    visited: BitVec,
    finished: BitVec,
    direction: Direction,
    /// The number of nodes already returned from the iterator.
    /// This is used to calculate the upper bound for the iterator's `size_hint`.
    nodes_seen: usize,
    /// A filter closure for the nodes to visit. If the closure returns false,
    /// the node is skipped.
    node_filter: Option<Box<dyn FnMut(NodeIndex) -> bool + 'graph>>,
    /// A filter closure for the ports to visit. If the closure returns false,
    /// the port is skipped.
    port_filter: Option<Box<dyn FnMut(NodeIndex, PortIndex) -> bool + 'graph>>,
}

impl<'graph> PostOrder<'graph> {
    fn new(
        graph: &'graph PortGraph,
        source: impl IntoIterator<Item = NodeIndex>,
        direction: Direction,
        mut node_filter: Option<Box<dyn FnMut(NodeIndex) -> bool + 'graph>>,
        port_filter: Option<Box<dyn FnMut(NodeIndex, PortIndex) -> bool + 'graph>>,
    ) -> Self {
        let mut visited = BitVec::with_capacity(graph.node_capacity());
        visited.resize(graph.node_capacity(), false);
        let mut finished = BitVec::with_capacity(graph.node_capacity());
        finished.resize(graph.node_capacity(), false);

        let mut source: Vec<_> = if let Some(node_filter) = node_filter.as_mut() {
            source.into_iter().filter(|&n| node_filter(n)).collect()
        } else {
            source.into_iter().collect()
        };
        source.reverse();

        Self {
            graph,
            stack: source,
            visited,
            finished,
            direction,
            nodes_seen: 0,
            node_filter,
            port_filter,
        }
    }

    /// Returns `true` if the node should be ignored.
    #[inline]
    fn ignore_node(&mut self, node: NodeIndex) -> bool {
        !self
            .node_filter
            .as_mut()
            .map_or(true, |filter| filter(node))
    }

    /// Returns `true` if the port should be ignored.
    #[inline]
    fn ignore_port(&mut self, node: NodeIndex, port: PortIndex) -> bool {
        !self
            .port_filter
            .as_mut()
            .map_or(true, |filter| filter(node, port))
    }
}

impl<'graph> Iterator for PostOrder<'graph> {
    type Item = NodeIndex;

    fn next(&mut self) -> Option<Self::Item> {
        while let Some(next) = self.stack.last().copied() {
            if !self.visited.replace(next.index(), true) {
                // The node is visited for the first time. We leave the node on the stack and push
                // all of its neighbours in the traversal direction.
                for port in self.graph.ports(next, self.direction).rev() {
                    if self.ignore_port(next, port) {
                        continue;
                    }

                    let Some(link) = self.graph.port_link(port) else {
                        continue;
                    };
                    let link_node = self.graph.port_node(link).unwrap();

                    if self.ignore_node(link_node) || self.ignore_port(link_node, link) {
                        continue;
                    }

                    if !self.visited[link_node.index()] {
                        self.stack.push(link_node);
                    }
                }
            } else if !self.finished.replace(next.index(), true) {
                // The node is visited for the second time. We remove it from the stack and return
                // as the next node in the traversal.
                self.stack.pop();
                self.nodes_seen += 1;
                return Some(next);
            } else {
                // The node has already been visited at least twice, so we ignore it.
                self.stack.pop();
            }
        }

        None
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        (0, Some(self.graph.node_count() - self.nodes_seen))
    }
}

impl<'graph> FusedIterator for PostOrder<'graph> {}

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

    #[test]
    fn postorder_tree() {
        let mut graph = PortGraph::new();
        // a ━▸ b ┳━▸ c
        //        ┣━▸
        //        ┣━▸ d ━▸ e
        //        ┗━▸ f
        let a = graph.add_node(0, 1);
        let b = graph.add_node(1, 4);
        let c = graph.add_node(1, 1);
        let d = graph.add_node(1, 1);
        let e = graph.add_node(2, 0);
        let f = graph.add_node(1, 0);

        graph.link_nodes(a, 0, b, 0).unwrap();
        graph.link_nodes(b, 0, c, 0).unwrap();
        graph.link_nodes(b, 2, d, 0).unwrap();
        graph.link_nodes(b, 3, f, 0).unwrap();
        graph.link_nodes(d, 0, e, 1).unwrap();

        // Forward starting from `a`
        let order = postorder(&graph, vec![a], Direction::Outgoing).collect::<Vec<_>>();
        assert_eq!(order, vec![c, e, d, f, b, a]);

        // Skipping `a`, starting from `b`
        let order = postorder(&graph, vec![b], Direction::Outgoing).collect::<Vec<_>>();
        assert_eq!(order, vec![c, e, d, f, b]);

        // Exploring `d` before `b`
        let order = postorder(&graph, vec![d, b], Direction::Outgoing).collect::<Vec<_>>();
        assert_eq!(order, vec![e, d, c, f, b]);

        // Reverse starting from `e`
        let order = postorder(&graph, vec![e], Direction::Incoming).collect::<Vec<_>>();
        assert_eq!(order, vec![a, b, d, e]);
    }

    #[test]
    fn postorder_dag() {
        let mut graph = PortGraph::new();
        // a -> b -> c
        //       \     \
        //        \--------> d
        let a = graph.add_node(0, 1);
        let b = graph.add_node(1, 2);
        let c = graph.add_node(1, 1);
        let d = graph.add_node(2, 0);

        graph.link_nodes(a, 0, b, 0).unwrap();
        graph.link_nodes(b, 0, c, 0).unwrap();
        graph.link_nodes(b, 1, d, 0).unwrap();
        graph.link_nodes(c, 0, d, 1).unwrap();

        // Forward starting from `a`
        let order = postorder(&graph, vec![a], Direction::Outgoing).collect::<Vec<_>>();
        assert_eq!(order, vec![d, c, b, a]);

        // Backwards starting from `d`
        let order = postorder(&graph, vec![d], Direction::Incoming).collect::<Vec<_>>();
        assert_eq!(order, vec![a, b, c, d]);
    }

    #[test]
    fn postorder_cycle() {
        let mut graph = PortGraph::new();
        // a -> b -> c -> d -> b -> ...
        let a = graph.add_node(0, 1);
        let b = graph.add_node(3, 2);
        let c = graph.add_node(1, 1);
        let d = graph.add_node(1, 1);

        graph.link_nodes(a, 0, b, 0).unwrap();
        graph.link_nodes(b, 0, c, 0).unwrap();
        graph.link_nodes(c, 0, d, 0).unwrap();
        graph.link_nodes(d, 0, b, 2).unwrap();

        // Forward starting from `a`
        let order = postorder(&graph, vec![a], Direction::Outgoing).collect::<Vec<_>>();
        assert_eq!(order, vec![d, c, b, a]);

        // Backwards starting from `c`
        let order = postorder(&graph, vec![c], Direction::Incoming).collect::<Vec<_>>();
        assert_eq!(order, vec![a, d, b, c]);
    }

    #[test]
    fn postorder_with_filters() {
        let mut graph = PortGraph::new();
        // a -> b -> c
        //       \     \
        //        \--2-----> d
        let a = graph.add_node(0, 1);
        let b = graph.add_node(1, 3);
        let c = graph.add_node(1, 1);
        let d = graph.add_node(3, 0);

        graph.link_nodes(a, 0, b, 0).unwrap();
        graph.link_nodes(b, 0, c, 0).unwrap();
        graph.link_nodes(b, 1, d, 0).unwrap();
        graph.link_nodes(c, 0, d, 1).unwrap();
        graph.link_nodes(b, 2, d, 2).unwrap(); // Double link

        // Completely node-filtered
        let order =
            postorder_filtered(&graph, vec![a], Direction::Outgoing, |_| false, |_, _| true)
                .collect::<Vec<_>>();
        assert_eq!(order, vec![]);

        // Completely edge-filtered
        let order =
            postorder_filtered(&graph, vec![a], Direction::Outgoing, |_| true, |_, _| false)
                .collect::<Vec<_>>();
        assert_eq!(order, vec![a]);

        // Backwards starting from `d`. Filtering one of the double links from `b`, and node `c`.
        let order = postorder_filtered(
            &graph,
            vec![d],
            Direction::Incoming,
            |n| n != c,
            |_, p| Some(p) != graph.output(b, 2),
        )
        .collect::<Vec<_>>();
        assert_eq!(order, vec![a, b, d]);
    }
}