portgraph 0.16.1

Data structure library for directed graphs with first-level ports.
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
//! Petgraph's trait implementations for portgraphs.

use std::iter::FusedIterator;

use bitvec::vec::BitVec;

use crate::index::IndexBase;
use crate::multiportgraph::MultiPortGraph;
use crate::view::filter::{LinkFilter, NodeFilter};
use crate::view::flat_region::FlatRegion;
use crate::view::region::Region;
use crate::view::subgraph::Subgraph;
use crate::{LinkView, NodeIndex, PortGraph, PortIndex, PortView, SecondaryMap};

use super::FilteredGraph;

impl From<petgraph::Direction> for crate::Direction {
    fn from(d: petgraph::Direction) -> Self {
        match d {
            petgraph::Direction::Incoming => crate::Direction::Incoming,
            petgraph::Direction::Outgoing => crate::Direction::Outgoing,
        }
    }
}

impl From<crate::Direction> for petgraph::Direction {
    fn from(d: crate::Direction) -> Self {
        match d {
            crate::Direction::Incoming => petgraph::Direction::Incoming,
            crate::Direction::Outgoing => petgraph::Direction::Outgoing,
        }
    }
}

impl<N: IndexBase> petgraph::visit::NodeRef for NodeIndex<N> {
    type NodeId = NodeIndex<N>;
    type Weight = ();

    fn id(&self) -> Self::NodeId {
        *self
    }

    fn weight(&self) -> &Self::Weight {
        &()
    }
}

/// Implement petgraph traits for a portgraph type or wrapper.
///
/// Can be called simply as `impl_petgraph_traits!(MyGraph)` for non-generic
/// graphs, or
/// ```ignore
/// impl_petgraph_traits!(MyGraph<T, G>, [T, G] where T: Bound, G: OtherBound);
/// ```
/// for generic types with bounds.
macro_rules! impl_petgraph_traits {
    ($graph:ty) => {impl_petgraph_traits!($graph, []);};
    ($graph:ty, [$($args:tt)*]) => {impl_petgraph_traits!($graph, [$($args)*] where );};
    ($graph:ty, [$($args:tt)*] where $($where:tt)*) => {
        impl<$($args)*> petgraph::visit::GraphBase for $graph where $($where)* {
            type NodeId = NodeIndex<<$graph as PortView>::NodeIndexBase>;
            type EdgeId = (
                <$graph as LinkView>::LinkEndpoint,
                <$graph as LinkView>::LinkEndpoint,
            );
        }

        impl<$($args)*> petgraph::visit::GraphProp for $graph where $($where)* {
            type EdgeType = petgraph::Directed;
        }

        impl<$($args)*> petgraph::visit::NodeCount for $graph where $($where)* {
            fn node_count(&self) -> usize {
                PortView::node_count(self)
            }
        }

        impl<$($args)*> petgraph::visit::NodeIndexable for $graph where $($where)* {
            fn node_bound(&self) -> usize {
                PortView::node_count(self)
            }

            fn to_index(&self, ix: Self::NodeId) -> usize {
                ix.index()
            }

            fn from_index(&self, ix: usize) -> Self::NodeId {
                NodeIndex::new(ix)
            }
        }

        impl<$($args)*> petgraph::visit::EdgeCount for $graph where $($where)* {
            fn edge_count(&self) -> usize {
                LinkView::link_count(self)
            }
        }

        impl<$($args)*> petgraph::visit::Data for $graph where $($where)* {
            type NodeWeight = ();
            type EdgeWeight = ();
        }

        impl<'g, $($args)*> petgraph::visit::IntoNodeIdentifiers for &'g $graph where $($where)* {
            type NodeIdentifiers = Box<dyn Iterator<Item = NodeIndex<<$graph as PortView>::NodeIndexBase>> + 'g>;

            fn node_identifiers(self) -> Self::NodeIdentifiers {
                Box::new(self.nodes_iter())
            }
        }

        impl<'g, $($args)*> petgraph::visit::IntoNodeReferences for &'g $graph where $($where)* {
            type NodeRef = NodeIndex<<$graph as PortView>::NodeIndexBase>;
            type NodeReferences = Box<dyn Iterator<Item = NodeIndex<<$graph as PortView>::NodeIndexBase>> + 'g>;

            fn node_references(self) -> Self::NodeReferences {
                Box::new(self.nodes_iter())
            }
        }

        impl<'g, $($args)*> petgraph::visit::IntoNeighbors for &'g $graph where $($where)* {
            type Neighbors = Box<dyn Iterator<Item = NodeIndex<<$graph as PortView>::NodeIndexBase>> + 'g>;

            fn neighbors(self, n: Self::NodeId) -> Self::Neighbors {
                Box::new(self.output_neighbours(n))
            }
        }

        impl<'g, $($args)*> petgraph::visit::IntoNeighborsDirected for &'g $graph where $($where)* {
            type NeighborsDirected = Box<dyn Iterator<Item = NodeIndex<<$graph as PortView>::NodeIndexBase>> + 'g>;

            fn neighbors_directed(
                self,
                n: Self::NodeId,
                d: petgraph::Direction,
            ) -> Self::NeighborsDirected {
                Box::new(self.neighbours(n, d.into()))
            }
        }

        impl<'g, $($args)*> petgraph::visit::IntoEdgeReferences for &'g $graph where $($where)* {
            type EdgeRef = EdgeRef<<$graph as PortView>::NodeIndexBase, <$graph as LinkView>::LinkEndpoint>;
            type EdgeReferences = EdgeRefs<'g, $graph>;

            fn edge_references(self) -> Self::EdgeReferences {
                EdgeRefs::new(self)
            }
        }

        impl<'g, $($args)*> petgraph::visit::IntoEdges for &'g $graph where $($where)* {
            type Edges = NodeEdgeRefs<'g, $graph>;

            fn edges(self, n: Self::NodeId) -> Self::Edges {
                NodeEdgeRefs::new(self, n)
            }
        }

        impl<'g, $($args)*> petgraph::visit::IntoEdgesDirected for &'g $graph where $($where)* {
            type EdgesDirected = NodeEdgeRefs<'g, $graph>;

            fn edges_directed(
                self,
                n: Self::NodeId,
                d: petgraph::Direction,
            ) -> Self::EdgesDirected {
                NodeEdgeRefs::new_directed(self, n, d.into())
            }
        }
    };
}

/// Implement petgraph's `Visitable` and `GetAdjacencyMatrix` traits for a portgraph type or wrapper.
///
/// Assumes that the node indices are dense and start at 0, and uses internal containers that consume O(#nodes) memory.
macro_rules! impl_visit_dense {
    ($graph:ty) => {impl_visit_dense!($graph, []);};
    ($graph:ty, [$($args:tt)*]) => {impl_visit_dense!($graph, [$($args)*] where );};
    ($graph:ty, [$($args:tt)*] where $($where:tt)*) => {
        impl<$($args)*> petgraph::visit::Visitable for $graph $($where)* {
            type Map = bitvec::vec::BitVec;

            fn visit_map(&self) -> Self::Map {
                BitVec::with_capacity(self.node_capacity())
            }

            fn reset_map(&self, map: &mut Self::Map) {
                map.clear();
            }
        }

        impl<$($args)*> petgraph::visit::GetAdjacencyMatrix for $graph $($where)* {
            type AdjMatrix = (bitvec::vec::BitVec, usize);

            fn adjacency_matrix(&self) -> Self::AdjMatrix {
                let row_size = self.node_capacity();
                let mut matrix = bitvec::bitvec![0; row_size * row_size];
                for node in self.nodes_iter() {
                    for neighbour in self.output_neighbours(node) {
                        let row = node.index();
                        let column = neighbour.index();
                        matrix.set(row * row_size + column, true);
                    }
                }
                (matrix, row_size)
            }

            fn is_adjacent(
                &self,
                matrix: &Self::AdjMatrix,
                a: Self::NodeId,
                b: Self::NodeId,
            ) -> bool {
                let (matrix, row_size) = matrix;
                let row = a.index();
                let column = b.index();
                matrix[row * row_size + column]
            }
        }
    };
}

/// Implement petgraph's `Visitable` and `GetAdjacencyMatrix` traits for a sparse portgraph type or wrapper.
///
/// Uses sparse containers to keep track of visited nodes.
macro_rules! impl_visit_sparse {
    ($graph:ty) => {impl_visit_sparse!($graph, []);};
    ($graph:ty, [$($args:tt)*]) => {impl_visit_sparse!($graph, [$($args)*] where );};
    ($graph:ty, [$($args:tt)*] where $($where:tt)*) => {
        impl<$($args)*> petgraph::visit::Visitable for $graph where $($where)* {
            type Map = std::collections::HashSet<Self::NodeId>;

            fn visit_map(&self) -> Self::Map {
                std::collections::HashSet::new()
            }

            fn reset_map(&self, map: &mut Self::Map) {
                map.clear();
            }
        }

        impl<$($args)*> petgraph::visit::GetAdjacencyMatrix for $graph where $($where)* {
            type AdjMatrix = std::collections::HashSet<(Self::NodeId, Self::NodeId)>;

            fn adjacency_matrix(&self) -> Self::AdjMatrix {
                let mut matrix = std::collections::HashSet::new();
                for node in self.nodes_iter() {
                    for neighbour in self.output_neighbours(node) {
                        matrix.insert((node, neighbour));
                    }
                }
                matrix
            }

            fn is_adjacent(
                &self,
                matrix: &Self::AdjMatrix,
                a: Self::NodeId,
                b: Self::NodeId,
            ) -> bool {
                matrix.contains(&(a, b))
            }
        }
    };
}

impl_petgraph_traits!(PortGraph<N, P, PO>, [N: IndexBase, P: IndexBase, PO: IndexBase]);
impl_petgraph_traits!(MultiPortGraph<N, P, PO>, [N: IndexBase, P: IndexBase, PO: IndexBase]);
impl_petgraph_traits!(FilteredGraph<G, NodeFilter<Ctx, G::NodeIndexBase>, LinkFilter<Ctx, G::PortIndexBase>, Ctx>, [G, Ctx]
    where
        G: LinkView + Clone,
        <G as LinkView>::LinkEndpoint: Eq
);
impl_petgraph_traits!(Region<'graph, G>, ['graph, G]
    where
        G: LinkView + Clone,
        <G as LinkView>::LinkEndpoint: Eq
);
impl_petgraph_traits!(FlatRegion<'graph, G>, ['graph, G]
    where
        G: LinkView + Clone,
        <G as LinkView>::LinkEndpoint: Eq
);
impl_petgraph_traits!(Subgraph<G>, [G]
    where
        G: LinkView + Clone,
        <G as LinkView>::LinkEndpoint: Eq
);

impl_visit_dense!(PortGraph<N, P, PO>, [N: IndexBase, P: IndexBase, PO: IndexBase]);
impl_visit_dense!(MultiPortGraph<N, P, PO>, [N: IndexBase, P: IndexBase, PO: IndexBase]);
impl_visit_sparse!(FilteredGraph<G, NodeFilter<Ctx, G::NodeIndexBase>, LinkFilter<Ctx, G::PortIndexBase>, Ctx>, [G, Ctx]
    where
        G: LinkView + Clone,
        <G as LinkView>::LinkEndpoint: Eq
);
impl_visit_sparse!(Region<'graph, G>, ['graph, G]
    where
        G: LinkView + Clone,
        <G as LinkView>::LinkEndpoint: Eq
);
impl_visit_sparse!(FlatRegion<'graph, G>, ['graph, G]
    where
        G: LinkView + Clone,
        <G as LinkView>::LinkEndpoint: Eq
);
impl_visit_sparse!(Subgraph<G>, [G]
    where
        G: LinkView + Clone,
        <G as LinkView>::LinkEndpoint: Eq
);

impl<N: IndexBase> petgraph::visit::VisitMap<NodeIndex<N>> for BitVec {
    fn visit(&mut self, a: NodeIndex<N>) -> bool {
        let is_visited = self.is_visited(&a);
        <Self as SecondaryMap<NodeIndex<N>, bool>>::set(self, a, true);
        is_visited
    }

    fn is_visited(&self, a: &NodeIndex<N>) -> bool {
        *<Self as SecondaryMap<NodeIndex<N>, bool>>::get(self, *a)
    }

    fn unvisit(&mut self, a: NodeIndex<N>) -> bool {
        let is_visited = self.is_visited(&a);
        <Self as SecondaryMap<NodeIndex<N>, bool>>::set(self, a, false);
        is_visited
    }
}

/// A reference to an edge in a portgraph, with information about the nodes it
/// connects.
///
/// Used to implement petgraph's `EdgeRef` trait.
#[derive(Debug, Clone, Copy)]
pub struct EdgeRef<N: IndexBase, P> {
    from_node: NodeIndex<N>,
    to_node: NodeIndex<N>,
    edge: (P, P),
}

impl<N: IndexBase, P> petgraph::visit::EdgeRef for EdgeRef<N, P>
where
    P: Copy,
{
    type NodeId = NodeIndex<N>;
    type EdgeId = (P, P);
    type Weight = ();

    fn source(&self) -> Self::NodeId {
        self.from_node
    }

    fn target(&self) -> Self::NodeId {
        self.to_node
    }

    fn weight(&self) -> &Self::Weight {
        &()
    }

    fn id(&self) -> Self::EdgeId {
        self.edge
    }
}

/// Iterator over the edges of a portgraph.
///
/// Used for compatibility with petgraph.
#[allow(clippy::type_complexity)]
pub struct EdgeRefs<'g, G: LinkView> {
    graph: &'g G,
    ports: Box<dyn Iterator<Item = PortIndex<G::PortIndexBase>> + 'g>,
    links: Option<Box<dyn Iterator<Item = (G::LinkEndpoint, G::LinkEndpoint)> + 'g>>,
    count: usize,
}

impl<'g, G> EdgeRefs<'g, G>
where
    G: LinkView,
{
    /// Create a new iterator over the edges of a portgraph.
    pub fn new(graph: &'g G) -> Self {
        Self {
            graph,
            ports: Box::new(graph.ports_iter()),
            links: None,
            count: graph.link_count(),
        }
    }
}

impl<G> Iterator for EdgeRefs<'_, G>
where
    G: LinkView,
{
    type Item = EdgeRef<G::NodeIndexBase, G::LinkEndpoint>;

    fn next(&mut self) -> Option<Self::Item> {
        loop {
            if let Some((from, to)) = self.links.as_mut().and_then(|links| links.next()) {
                return Some(EdgeRef {
                    from_node: self.graph.port_node(from).unwrap(),
                    to_node: self.graph.port_node(to).unwrap(),
                    edge: (from, to),
                });
            }

            let port = self.ports.next()?;
            self.links = Some(Box::new(self.graph.port_links(port)));
        }
    }

    #[inline]
    fn count(self) -> usize
    where
        Self: Sized,
    {
        self.count
    }

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

impl<G: LinkView> ExactSizeIterator for EdgeRefs<'_, G> {
    #[inline]
    fn len(&self) -> usize {
        self.count
    }
}

impl<G: LinkView> FusedIterator for EdgeRefs<'_, G> {}

/// Iterator over the edges of a node.
///
/// Used for compatibility with petgraph.
pub struct NodeEdgeRefs<'g, G: LinkView> {
    graph: &'g G,
    links: Box<dyn Iterator<Item = (G::LinkEndpoint, G::LinkEndpoint)> + 'g>,
}

impl<'g, G> NodeEdgeRefs<'g, G>
where
    G: LinkView,
{
    /// Create a new iterator over the edges of a portgraph.
    pub fn new(graph: &'g G, node: NodeIndex<G::NodeIndexBase>) -> Self {
        Self {
            graph,
            links: Box::new(graph.all_links(node)),
        }
    }

    /// Create a new iterator over the edges of a portgraph.
    pub fn new_directed(
        graph: &'g G,
        node: NodeIndex<G::NodeIndexBase>,
        dir: crate::Direction,
    ) -> Self {
        Self {
            graph,
            links: Box::new(graph.links(node, dir)),
        }
    }
}

impl<G> Iterator for NodeEdgeRefs<'_, G>
where
    G: LinkView,
{
    type Item = EdgeRef<G::NodeIndexBase, G::LinkEndpoint>;

    fn next(&mut self) -> Option<Self::Item> {
        let (from, to) = self.links.next()?;
        Some(EdgeRef {
            from_node: self.graph.port_node(from).unwrap(),
            to_node: self.graph.port_node(to).unwrap(),
            edge: (from, to),
        })
    }

    #[inline]
    fn count(self) -> usize
    where
        Self: Sized,
    {
        self.links.count()
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        self.links.size_hint()
    }
}