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
use traitgraph::implementation::incremental_subgraph::IncrementalSubgraph;
use traitgraph::interface::subgraph::DecoratingSubgraph;
use traitgraph::interface::{GraphBase, NodeOrEdge, StaticGraph};
use traitgraph_algo::traversal::{
    BackwardNeighborStrategy, BfsQueueStrategy, ForbiddenEdge, ForbiddenNode,
    ForwardNeighborStrategy, PreOrderTraversal, TraversalNeighborStrategy,
};

/// Returns the reachable subgraph from a node without using an edge.
pub fn compute_restricted_edge_reachability<
    'a,
    Graph: StaticGraph,
    NeighborStrategy: TraversalNeighborStrategy<'a, SubgraphType::ParentGraph>,
    SubgraphType: DecoratingSubgraph<ParentGraph = Graph, ParentGraphRef = &'a Graph>,
>(
    graph: SubgraphType::ParentGraphRef,
    start_node: <SubgraphType as GraphBase>::NodeIndex,
    forbidden_edge: <SubgraphType as GraphBase>::EdgeIndex,
) -> SubgraphType {
    let mut subgraph = SubgraphType::new_empty(graph);
    let mut traversal = PreOrderTraversal::<
        _,
        NeighborStrategy,
        BfsQueueStrategy,
        std::collections::VecDeque<_>,
    >::new(graph, start_node);
    let forbidden_edge = ForbiddenEdge::new(forbidden_edge);

    while let Some(node_or_edge) = traversal.next_with_forbidden_subgraph(&forbidden_edge) {
        match node_or_edge {
            NodeOrEdge::Node(node) => subgraph.add_node(node),
            NodeOrEdge::Edge(edge) => subgraph.add_edge(edge),
        }
    }

    subgraph
}

/// Returns the reachable subgraph from a node without using an edge incrementally.
pub fn compute_incremental_restricted_forward_edge_reachability<'a, Graph: StaticGraph>(
    graph: &'a Graph,
    walk: &[Graph::EdgeIndex],
) -> IncrementalSubgraph<'a, Graph> {
    let mut subgraph = IncrementalSubgraph::new_with_incremental_steps(graph, walk.len());
    let mut traversal = PreOrderTraversal::<
        _,
        ForwardNeighborStrategy,
        BfsQueueStrategy,
        std::collections::VecDeque<_>,
    >::new_without_start(graph);

    let mut start_edge = *walk
        .first()
        .expect("Cannot compute hydrostructure from empty walk");
    for (edge_number, &edge) in walk.iter().enumerate().skip(1) {
        let start_node = graph.edge_endpoints(start_edge).to_node;
        traversal.continue_traversal_from(start_node);
        subgraph.set_current_step(edge_number);
        let forbidden_edge = ForbiddenEdge::new(edge);
        subgraph.add_edge(start_edge);
        start_edge = edge;

        while let Some(node_or_edge) = traversal.next_with_forbidden_subgraph(&forbidden_edge) {
            match node_or_edge {
                NodeOrEdge::Node(node) => subgraph.add_node(node),
                NodeOrEdge::Edge(edge) => subgraph.add_edge(edge),
            }
        }
    }

    subgraph
}

/// Returns the backwards reachable subgraph from a node without using an edge incrementally.
pub fn compute_incremental_restricted_backward_edge_reachability<'a, Graph: StaticGraph>(
    graph: &'a Graph,
    walk: &[Graph::EdgeIndex],
) -> IncrementalSubgraph<'a, Graph> {
    let mut subgraph = IncrementalSubgraph::new_with_incremental_steps(graph, walk.len());
    let mut traversal = PreOrderTraversal::<
        _,
        BackwardNeighborStrategy,
        BfsQueueStrategy,
        std::collections::VecDeque<_>,
    >::new_without_start(graph);

    let mut start_edge = *walk
        .last()
        .expect("Cannot compute hydrostructure from empty walk");
    for (edge_number, &edge) in walk.iter().rev().enumerate().skip(1) {
        let start_node = graph.edge_endpoints(start_edge).from_node;
        traversal.continue_traversal_from(start_node);
        subgraph.set_current_step(edge_number);
        let forbidden_edge = ForbiddenEdge::new(edge);
        subgraph.add_edge(start_edge);
        start_edge = edge;

        while let Some(node_or_edge) = traversal.next_with_forbidden_subgraph(&forbidden_edge) {
            match node_or_edge {
                NodeOrEdge::Node(node) => subgraph.add_node(node),
                NodeOrEdge::Edge(edge) => subgraph.add_edge(edge),
            }
        }
    }

    subgraph
}

/// Returns the reachable subgraph from a node without using a node.
pub fn compute_restricted_node_reachability<
    'a,
    Graph: StaticGraph,
    NeighborStrategy: TraversalNeighborStrategy<'a, SubgraphType::ParentGraph>,
    SubgraphType: DecoratingSubgraph<ParentGraph = Graph, ParentGraphRef = &'a Graph>,
>(
    graph: SubgraphType::ParentGraphRef,
    start_node: <SubgraphType as GraphBase>::NodeIndex,
    forbidden_node: <SubgraphType as GraphBase>::NodeIndex,
) -> SubgraphType {
    let mut subgraph = SubgraphType::new_empty(graph);
    let mut traversal = PreOrderTraversal::<
        _,
        NeighborStrategy,
        BfsQueueStrategy,
        std::collections::VecDeque<_>,
    >::new(graph, start_node);
    let forbidden_node = ForbiddenNode::new(forbidden_node);

    while let Some(node_or_edge) = traversal.next_with_forbidden_subgraph(&forbidden_node) {
        match node_or_edge {
            NodeOrEdge::Node(node) => subgraph.add_node(node),
            NodeOrEdge::Edge(edge) => subgraph.add_edge(edge),
        }
    }

    subgraph
}

/// Returns the forwards reachable subgraph from the tail of `edge` without using `edge`.
pub fn compute_restricted_forward_reachability<
    'a,
    Graph: StaticGraph,
    SubgraphType: DecoratingSubgraph<ParentGraph = Graph, ParentGraphRef = &'a Graph>,
>(
    graph: SubgraphType::ParentGraphRef,
    edge: <SubgraphType as GraphBase>::EdgeIndex,
) -> SubgraphType {
    let start_node = graph.edge_endpoints(edge).from_node;
    compute_restricted_edge_reachability::<_, ForwardNeighborStrategy, _>(graph, start_node, edge)
}

/// Returns the backwards reachable subgraph from the head of `edge` without using `edge`.
pub fn compute_restricted_backward_reachability<
    'a,
    Graph: StaticGraph,
    SubgraphType: DecoratingSubgraph<ParentGraph = Graph, ParentGraphRef = &'a Graph>,
>(
    graph: SubgraphType::ParentGraphRef,
    edge: <SubgraphType as GraphBase>::EdgeIndex,
) -> SubgraphType {
    let start_node = graph.edge_endpoints(edge).to_node;
    compute_restricted_edge_reachability::<_, BackwardNeighborStrategy, _>(graph, start_node, edge)
}

/// Returns the forwards reachable subgraph from `edge` without using the tail of `edge`.
pub fn compute_inverse_restricted_forward_reachability<
    'a,
    Graph: StaticGraph,
    SubgraphType: DecoratingSubgraph<ParentGraph = Graph, ParentGraphRef = &'a Graph>,
>(
    graph: SubgraphType::ParentGraphRef,
    edge: <SubgraphType as GraphBase>::EdgeIndex,
) -> SubgraphType {
    let forbidden_node = graph.edge_endpoints(edge).from_node;
    let start_node = graph.edge_endpoints(edge).to_node;

    // If the edge is a self loop.
    let mut result = if start_node == forbidden_node {
        SubgraphType::new_empty(graph)
    } else {
        compute_restricted_node_reachability::<_, ForwardNeighborStrategy, _>(
            graph,
            start_node,
            forbidden_node,
        )
    };

    result.add_edge(edge);
    result
}

/// Returns the backwards reachable subgraph from `edge` without using the head of `edge`.
pub fn compute_inverse_restricted_backward_reachability<
    'a,
    Graph: StaticGraph,
    SubgraphType: DecoratingSubgraph<ParentGraph = Graph, ParentGraphRef = &'a Graph>,
>(
    graph: SubgraphType::ParentGraphRef,
    edge: <SubgraphType as GraphBase>::EdgeIndex,
) -> SubgraphType {
    let forbidden_node = graph.edge_endpoints(edge).to_node;
    let start_node = graph.edge_endpoints(edge).from_node;

    // If the edge is a self loop.
    let mut result = if start_node == forbidden_node {
        SubgraphType::new_empty(graph)
    } else {
        compute_restricted_node_reachability::<_, BackwardNeighborStrategy, _>(
            graph,
            start_node,
            forbidden_node,
        )
    };

    result.add_edge(edge);
    result
}

/// Returns either the set of nodes and edges reachable from the first edge of aZb without using aZb as a subwalk,
/// or None, if the whole graph can be reached this way.
///
/// This computes `R⁺(aZb)` as defined in the hydrostructure paper.
/// If `Some` is returned, `aZb` is _bridge-like_, and otherwise it is _avertible_.
pub fn compute_hydrostructure_forward_reachability<
    'a,
    Graph: StaticGraph,
    SubgraphType: DecoratingSubgraph<ParentGraph = Graph, ParentGraphRef = &'a Graph>,
>(
    graph: SubgraphType::ParentGraphRef,
    azb: &[<<SubgraphType as DecoratingSubgraph>::ParentGraph as GraphBase>::EdgeIndex],
) -> Option<SubgraphType> {
    let a = *azb.iter().next().unwrap();
    let b = *azb.iter().last().unwrap();
    let start_node = graph.edge_endpoints(a).to_node;
    let mut subgraph =
        compute_restricted_edge_reachability::<_, ForwardNeighborStrategy, SubgraphType>(
            graph, start_node, b,
        );

    for &edge in azb.iter().take(azb.len() - 1) {
        let node = graph.edge_endpoints(edge).to_node;
        for incoming in graph.in_neighbors(node) {
            let incoming = incoming.edge_id;
            if incoming != edge && subgraph.contains_edge(incoming) {
                return None;
            }
        }
    }

    subgraph.add_edge(a);
    Some(subgraph)
}

/// Returns either the set of nodes and edges backwards reachable from the last edge of aZb without using aZb as a subwalk,
/// or None, if the whole graph can be reached this way.
///
/// This computes `R⁻(aZb)` as defined in the hydrostructure paper.
/// If `Some` is returned, `aZb` is _bridge-like_, and otherwise it is _avertible_.
pub fn compute_hydrostructure_backward_reachability<
    'a,
    Graph: StaticGraph,
    SubgraphType: DecoratingSubgraph<ParentGraph = Graph, ParentGraphRef = &'a Graph>,
>(
    graph: SubgraphType::ParentGraphRef,
    azb: &[<<SubgraphType as DecoratingSubgraph>::ParentGraph as GraphBase>::EdgeIndex],
) -> Option<SubgraphType> {
    let a = *azb.iter().next().unwrap();
    let b = *azb.iter().last().unwrap();
    let start_node = graph.edge_endpoints(b).from_node;
    let mut subgraph =
        compute_restricted_edge_reachability::<_, BackwardNeighborStrategy, SubgraphType>(
            graph, start_node, a,
        );

    for &edge in azb.iter().skip(1) {
        let node = graph.edge_endpoints(edge).from_node;
        for outgoing in graph.out_neighbors(node) {
            let outgoing = outgoing.edge_id;
            if outgoing != edge && subgraph.contains_edge(outgoing) {
                return None;
            }
        }
    }

    subgraph.add_edge(b);
    Some(subgraph)
}

#[cfg(test)]
mod tests {
    use crate::restricted_reachability::compute_restricted_backward_reachability;
    use crate::restricted_reachability::compute_restricted_forward_reachability;
    use traitgraph::implementation::bit_vector_subgraph::BitVectorSubgraph;
    use traitgraph::interface::subgraph::DecoratingSubgraph;
    use traitgraph::interface::MutableGraphContainer;

    #[test]
    fn test_restricted_forward_reachability_simple() {
        let mut graph = traitgraph::implementation::petgraph_impl::new();
        let n0 = graph.add_node(0);
        let n1 = graph.add_node(1);
        let n2 = graph.add_node(2);
        let e1 = graph.add_edge(n0, n1, -1);
        let _e2 = graph.add_edge(n1, n1, -2);
        let e3 = graph.add_edge(n0, n0, -3);
        let _e4 = graph.add_edge(n1, n0, -4);
        let e5 = graph.add_edge(n0, n2, -5);
        let _e6 = graph.add_edge(n1, n2, -6);
        let subgraph: BitVectorSubgraph<_> = compute_restricted_forward_reachability(&graph, e1);

        debug_assert_eq!(subgraph.node_count(), 2);
        debug_assert!(subgraph.contains_node(n0));
        debug_assert!(subgraph.contains_node(n2));

        debug_assert_eq!(subgraph.edge_count(), 2);
        debug_assert!(subgraph.contains_edge(e3));
        debug_assert!(subgraph.contains_edge(e5));
    }

    #[test]
    fn test_restricted_backward_reachability_simple() {
        let mut graph = traitgraph::implementation::petgraph_impl::new();
        let n0 = graph.add_node(0);
        let n1 = graph.add_node(1);
        let n2 = graph.add_node(2);
        let e1 = graph.add_edge(n1, n0, -1);
        let _e2 = graph.add_edge(n1, n1, -2);
        let e3 = graph.add_edge(n0, n0, -3);
        let _e4 = graph.add_edge(n0, n1, -4);
        let e5 = graph.add_edge(n2, n0, -5);
        let _e6 = graph.add_edge(n2, n1, -6);
        let subgraph: BitVectorSubgraph<_> = compute_restricted_backward_reachability(&graph, e1);

        debug_assert_eq!(subgraph.node_count(), 2);
        debug_assert!(subgraph.contains_node(n0));
        debug_assert!(subgraph.contains_node(n2));

        debug_assert_eq!(subgraph.edge_count(), 2);
        debug_assert!(subgraph.contains_edge(e3));
        debug_assert!(subgraph.contains_edge(e5));
    }
}