forked from petgraph/petgraph
-
Notifications
You must be signed in to change notification settings - Fork 0
/
matrix_graph.rs
1786 lines (1539 loc) · 51.8 KB
/
matrix_graph.rs
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
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! `MatrixGraph<N, E, Ty, NullN, NullE, Ix>` is a graph datastructure backed by an adjacency matrix.
use std::marker::PhantomData;
use std::ops::{Index, IndexMut};
use std::cmp;
use std::mem;
use indexmap::IndexSet;
use fixedbitset::FixedBitSet;
use crate::{Directed, Direction, EdgeType, IntoWeightedEdge, Outgoing, Undirected};
use crate::graph::NodeIndex as GraphNodeIndex;
use crate::visit::{
Data, EdgeCount, GetAdjacencyMatrix, GraphBase, GraphProp, IntoEdgeReferences, IntoEdges,
IntoEdgesDirected, IntoNeighbors, IntoNeighborsDirected, IntoNodeIdentifiers,
IntoNodeReferences, NodeCount, NodeIndexable, Visitable,
};
use crate::data::Build;
pub use crate::graph::IndexType;
// The following types are used to control the max size of the adjacency matrix. Since the maximum
// size of the matrix vector's is the square of the maximum number of nodes, the number of nodes
// should be reasonably picked.
type DefaultIx = u16;
/// Node identifier.
pub type NodeIndex<Ix = DefaultIx> = GraphNodeIndex<Ix>;
mod private {
pub trait Sealed {}
impl<T> Sealed for super::NotZero<T> {}
impl<T> Sealed for Option<T> {}
}
/// Wrapper trait for an `Option`, allowing user-defined structs to be input as containers when
/// defining a null element.
///
/// Note: this trait is currently *sealed* and cannot be implemented for types outside this crate.
pub trait Nullable: Default + Into<Option<<Self as Nullable>::Wrapped>> + private::Sealed {
#[doc(hidden)]
type Wrapped;
#[doc(hidden)]
fn new(value: Self::Wrapped) -> Self;
#[doc(hidden)]
fn as_ref(&self) -> Option<&Self::Wrapped>;
#[doc(hidden)]
fn as_mut(&mut self) -> Option<&mut Self::Wrapped>;
#[doc(hidden)]
fn is_null(&self) -> bool {
self.as_ref().is_none()
}
}
impl<T> Nullable for Option<T> {
type Wrapped = T;
fn new(value: T) -> Self {
Some(value)
}
fn as_ref(&self) -> Option<&Self::Wrapped> {
self.as_ref()
}
fn as_mut(&mut self) -> Option<&mut Self::Wrapped> {
self.as_mut()
}
}
/// `NotZero` is used to optimize the memory usage of edge weights `E` in a
/// [`MatrixGraph`](struct.MatrixGraph.html), replacing the default `Option<E>` sentinel.
///
/// Pre-requisite: edge weight should implement [`Zero`](trait.Zero.html).
///
/// Note that if you're already using the standard non-zero types (such as `NonZeroU32`), you don't
/// have to use this wrapper and can leave the default `Null` type argument.
pub struct NotZero<T>(T);
impl<T: Zero> Default for NotZero<T> {
fn default() -> Self {
NotZero(T::zero())
}
}
impl<T: Zero> Nullable for NotZero<T> {
#[doc(hidden)]
type Wrapped = T;
#[doc(hidden)]
fn new(value: T) -> Self {
assert!(!value.is_zero());
NotZero(value)
}
// implemented here for optimization purposes
#[doc(hidden)]
fn is_null(&self) -> bool {
self.0.is_zero()
}
#[doc(hidden)]
fn as_ref(&self) -> Option<&Self::Wrapped> {
if !self.is_null() {
Some(&self.0)
} else {
None
}
}
#[doc(hidden)]
fn as_mut(&mut self) -> Option<&mut Self::Wrapped> {
if !self.is_null() {
Some(&mut self.0)
} else {
None
}
}
}
impl<T: Zero> From<NotZero<T>> for Option<T> {
fn from(not_zero: NotZero<T>) -> Self {
if !not_zero.is_null() {
Some(not_zero.0)
} else {
None
}
}
}
/// Base trait for types that can be wrapped in a [`NotZero`](struct.NotZero.html).
///
/// Implementors must provide a singleton object that will be used to mark empty edges in a
/// [`MatrixGraph`](struct.MatrixGraph.html).
///
/// Note that this trait is already implemented for the base numeric types.
pub trait Zero {
/// Return the singleton object which can be used as a sentinel value.
fn zero() -> Self;
/// Return true if `self` is equal to the sentinel value.
fn is_zero(&self) -> bool;
}
macro_rules! not_zero_impl {
($t:ty,$z:expr) => {
impl Zero for $t {
fn zero() -> Self {
$z as $t
}
#[allow(clippy::float_cmp)]
fn is_zero(&self) -> bool {
self == &Self::zero()
}
}
};
}
macro_rules! not_zero_impls {
($($t:ty),*) => {
$(
not_zero_impl!($t, 0);
)*
}
}
not_zero_impls!(u8, u16, u32, u64, usize);
not_zero_impls!(i8, i16, i32, i64, isize);
not_zero_impls!(f32, f64);
/// Short version of `NodeIndex::new` (with Ix = `DefaultIx`)
#[inline]
pub fn node_index(ax: usize) -> NodeIndex {
NodeIndex::new(ax)
}
/// `MatrixGraph<N, E, Ty, Null>` is a graph datastructure using an adjacency matrix
/// representation.
///
/// `MatrixGraph` is parameterized over:
///
/// - Associated data `N` for nodes and `E` for edges, called *weights*.
/// The associated data can be of arbitrary type.
/// - Edge type `Ty` that determines whether the graph edges are directed or undirected.
/// - Nullable type `Null`, which denotes the edges' presence (defaults to `Option<E>`). You may
/// specify [`NotZero<E>`](struct.NotZero.html) if you want to use a sentinel value (such as 0)
/// to mark the absence of an edge.
/// - Index type `Ix` that sets the maximum size for the graph (defaults to `DefaultIx`).
///
/// The graph uses **O(|V^2|)** space, with fast edge insertion & amortized node insertion, as well
/// as efficient graph search and graph algorithms on dense graphs.
///
/// This graph is backed by a flattened 2D array. For undirected graphs, only the lower triangular
/// matrix is stored. Since the backing array stores edge weights, it is recommended to box large
/// edge weights.
#[derive(Clone)]
pub struct MatrixGraph<N, E, Ty = Directed, Null: Nullable<Wrapped = E> = Option<E>, Ix = DefaultIx>
{
node_adjacencies: Vec<Null>,
node_capacity: usize,
nodes: IdStorage<N>,
nb_edges: usize,
ty: PhantomData<Ty>,
ix: PhantomData<Ix>,
}
/// A `MatrixGraph` with directed edges.
pub type DiMatrix<N, E, Null = Option<E>, Ix = DefaultIx> = MatrixGraph<N, E, Directed, Null, Ix>;
/// A `MatrixGraph` with undirected edges.
pub type UnMatrix<N, E, Null = Option<E>, Ix = DefaultIx> = MatrixGraph<N, E, Undirected, Null, Ix>;
impl<N, E, Ty: EdgeType, Null: Nullable<Wrapped = E>, Ix: IndexType>
MatrixGraph<N, E, Ty, Null, Ix>
{
/// Create a new `MatrixGraph` with estimated capacity for nodes.
pub fn with_capacity(node_capacity: usize) -> Self {
let mut m = Self {
node_adjacencies: vec![],
node_capacity: 0,
nodes: IdStorage::with_capacity(node_capacity),
nb_edges: 0,
ty: PhantomData,
ix: PhantomData,
};
debug_assert!(node_capacity <= <Ix as IndexType>::max().index());
if node_capacity > 0 {
m.extend_capacity_for_node(NodeIndex::new(node_capacity - 1), true);
}
m
}
#[inline]
fn to_edge_position(&self, a: NodeIndex<Ix>, b: NodeIndex<Ix>) -> Option<usize> {
if cmp::max(a.index(), b.index()) >= self.node_capacity {
return None;
}
Some(self.to_edge_position_unchecked(a, b))
}
#[inline]
fn to_edge_position_unchecked(&self, a: NodeIndex<Ix>, b: NodeIndex<Ix>) -> usize {
to_linearized_matrix_position::<Ty>(a.index(), b.index(), self.node_capacity)
}
/// Remove all nodes and edges.
pub fn clear(&mut self) {
for edge in self.node_adjacencies.iter_mut() {
*edge = Default::default();
}
self.nodes.clear();
self.nb_edges = 0;
}
/// Return the number of nodes (vertices) in the graph.
///
/// Computes in **O(1)** time.
#[inline]
pub fn node_count(&self) -> usize {
self.nodes.len()
}
/// Return the number of edges in the graph.
///
/// Computes in **O(1)** time.
#[inline]
pub fn edge_count(&self) -> usize {
self.nb_edges
}
/// Return whether the graph has directed edges or not.
#[inline]
pub fn is_directed(&self) -> bool {
Ty::is_directed()
}
/// Add a node (also called vertex) with associated data `weight` to the graph.
///
/// Computes in **O(1)** time.
///
/// Return the index of the new node.
///
/// **Panics** if the MatrixGraph is at the maximum number of nodes for its index type.
pub fn add_node(&mut self, weight: N) -> NodeIndex<Ix> {
NodeIndex::new(self.nodes.add(weight))
}
/// Remove `a` from the graph.
///
/// Computes in **O(V)** time, due to the removal of edges with other nodes.
///
/// **Panics** if the node `a` does not exist.
pub fn remove_node(&mut self, a: NodeIndex<Ix>) -> N {
for id in self.nodes.iter_ids() {
let position = self.to_edge_position(a, NodeIndex::new(id));
if let Some(pos) = position {
self.node_adjacencies[pos] = Default::default();
}
if Ty::is_directed() {
let position = self.to_edge_position(NodeIndex::new(id), a);
if let Some(pos) = position {
self.node_adjacencies[pos] = Default::default();
}
}
}
self.nodes.remove(a.index())
}
#[inline]
fn extend_capacity_for_node(&mut self, min_node: NodeIndex<Ix>, exact: bool) {
self.node_capacity = extend_linearized_matrix::<Ty, _>(
&mut self.node_adjacencies,
self.node_capacity,
min_node.index() + 1,
exact,
);
}
#[inline]
fn extend_capacity_for_edge(&mut self, a: NodeIndex<Ix>, b: NodeIndex<Ix>) {
let min_node = cmp::max(a, b);
if min_node.index() >= self.node_capacity {
self.extend_capacity_for_node(min_node, false);
}
}
/// Update the edge from `a` to `b` to the graph, with its associated data `weight`.
///
/// Return the previous data, if any.
///
/// Computes in **O(1)** time, best case.
/// Computes in **O(|V|^2)** time, worst case (matrix needs to be re-allocated).
///
/// **Panics** if any of the nodes don't exist.
pub fn update_edge(&mut self, a: NodeIndex<Ix>, b: NodeIndex<Ix>, weight: E) -> Option<E> {
self.extend_capacity_for_edge(a, b);
let p = self.to_edge_position_unchecked(a, b);
let old_weight = mem::replace(&mut self.node_adjacencies[p], Null::new(weight));
if old_weight.is_null() {
self.nb_edges += 1;
}
old_weight.into()
}
/// Add an edge from `a` to `b` to the graph, with its associated
/// data `weight`.
///
/// Computes in **O(1)** time, best case.
/// Computes in **O(|V|^2)** time, worst case (matrix needs to be re-allocated).
///
/// **Panics** if any of the nodes don't exist.
/// **Panics** if an edge already exists from `a` to `b`.
///
/// **Note:** `MatrixGraph` does not allow adding parallel (“duplicate”) edges. If you want to avoid
/// this, use [`.update_edge(a, b, weight)`](#method.update_edge) instead.
pub fn add_edge(&mut self, a: NodeIndex<Ix>, b: NodeIndex<Ix>, weight: E) {
let old_edge_id = self.update_edge(a, b, weight);
assert!(old_edge_id.is_none());
}
/// Remove the edge from `a` to `b` to the graph.
///
/// **Panics** if any of the nodes don't exist.
/// **Panics** if no edge exists between `a` and `b`.
pub fn remove_edge(&mut self, a: NodeIndex<Ix>, b: NodeIndex<Ix>) -> E {
let p = self
.to_edge_position(a, b)
.expect("No edge found between the nodes.");
let old_weight = mem::take(&mut self.node_adjacencies[p]).into().unwrap();
let old_weight: Option<_> = old_weight.into();
self.nb_edges -= 1;
old_weight.unwrap()
}
/// Return true if there is an edge between `a` and `b`.
///
/// **Panics** if any of the nodes don't exist.
pub fn has_edge(&self, a: NodeIndex<Ix>, b: NodeIndex<Ix>) -> bool {
if let Some(p) = self.to_edge_position(a, b) {
return !self.node_adjacencies[p].is_null();
}
false
}
/// Access the weight for node `a`.
///
/// Also available with indexing syntax: `&graph[a]`.
///
/// **Panics** if the node doesn't exist.
pub fn node_weight(&self, a: NodeIndex<Ix>) -> &N {
&self.nodes[a.index()]
}
/// Access the weight for node `a`, mutably.
///
/// Also available with indexing syntax: `&mut graph[a]`.
///
/// **Panics** if the node doesn't exist.
pub fn node_weight_mut(&mut self, a: NodeIndex<Ix>) -> &mut N {
&mut self.nodes[a.index()]
}
/// Access the weight for edge `e`.
///
/// Also available with indexing syntax: `&graph[e]`.
///
/// **Panics** if no edge exists between `a` and `b`.
pub fn edge_weight(&self, a: NodeIndex<Ix>, b: NodeIndex<Ix>) -> &E {
let p = self
.to_edge_position(a, b)
.expect("No edge found between the nodes.");
self.node_adjacencies[p]
.as_ref()
.expect("No edge found between the nodes.")
}
/// Access the weight for edge `e`, mutably.
///
/// Also available with indexing syntax: `&mut graph[e]`.
///
/// **Panics** if no edge exists between `a` and `b`.
pub fn edge_weight_mut(&mut self, a: NodeIndex<Ix>, b: NodeIndex<Ix>) -> &mut E {
let p = self
.to_edge_position(a, b)
.expect("No edge found between the nodes.");
self.node_adjacencies[p]
.as_mut()
.expect("No edge found between the nodes.")
}
/// Return an iterator of all nodes with an edge starting from `a`.
///
/// - `Directed`: Outgoing edges from `a`.
/// - `Undirected`: All edges from or to `a`.
///
/// Produces an empty iterator if the node doesn't exist.<br>
/// Iterator element type is [`NodeIndex<Ix>`](../graph/struct.NodeIndex.html).
pub fn neighbors(&self, a: NodeIndex<Ix>) -> Neighbors<Ty, Null, Ix> {
Neighbors(Edges::on_columns(
a.index(),
&self.node_adjacencies,
self.node_capacity,
))
}
/// Return an iterator of all edges of `a`.
///
/// - `Directed`: Outgoing edges from `a`.
/// - `Undirected`: All edges connected to `a`.
///
/// Produces an empty iterator if the node doesn't exist.<br>
/// Iterator element type is [`Edges<E, Ix>`](../graph/struct.Edges.html).
pub fn edges(&self, a: NodeIndex<Ix>) -> Edges<Ty, Null, Ix> {
Edges::on_columns(a.index(), &self.node_adjacencies, self.node_capacity)
}
/// Create a new `MatrixGraph` from an iterable of edges.
///
/// Node weights `N` are set to default values.
/// Edge weights `E` may either be specified in the list,
/// or they are filled with default values.
///
/// Nodes are inserted automatically to match the edges.
///
/// ```
/// use petgraph::matrix_graph::MatrixGraph;
///
/// let gr = MatrixGraph::<(), i32>::from_edges(&[
/// (0, 1), (0, 2), (0, 3),
/// (1, 2), (1, 3),
/// (2, 3),
/// ]);
/// ```
pub fn from_edges<I>(iterable: I) -> Self
where
I: IntoIterator,
I::Item: IntoWeightedEdge<E>,
<I::Item as IntoWeightedEdge<E>>::NodeId: Into<NodeIndex<Ix>>,
N: Default,
{
let mut g = Self::default();
g.extend_with_edges(iterable);
g
}
/// Extend the graph from an iterable of edges.
///
/// Node weights `N` are set to default values.
/// Edge weights `E` may either be specified in the list,
/// or they are filled with default values.
///
/// Nodes are inserted automatically to match the edges.
pub fn extend_with_edges<I>(&mut self, iterable: I)
where
I: IntoIterator,
I::Item: IntoWeightedEdge<E>,
<I::Item as IntoWeightedEdge<E>>::NodeId: Into<NodeIndex<Ix>>,
N: Default,
{
for elt in iterable {
let (source, target, weight) = elt.into_weighted_edge();
let (source, target) = (source.into(), target.into());
let nx = cmp::max(source, target);
while nx.index() >= self.node_count() {
self.add_node(N::default());
}
self.add_edge(source, target, weight);
}
}
}
impl<N, E, Null: Nullable<Wrapped = E>, Ix: IndexType> MatrixGraph<N, E, Directed, Null, Ix> {
/// Return an iterator of all neighbors that have an edge between them and
/// `a`, in the specified direction.
/// If the graph's edges are undirected, this is equivalent to *.neighbors(a)*.
///
/// - `Outgoing`: All edges from `a`.
/// - `Incoming`: All edges to `a`.
///
/// Produces an empty iterator if the node doesn't exist.<br>
/// Iterator element type is [`NodeIndex<Ix>`](../graph/struct.NodeIndex.html).
pub fn neighbors_directed(
&self,
a: NodeIndex<Ix>,
d: Direction,
) -> Neighbors<Directed, Null, Ix> {
if d == Outgoing {
self.neighbors(a)
} else {
Neighbors(Edges::on_rows(
a.index(),
&self.node_adjacencies,
self.node_capacity,
))
}
}
/// Return an iterator of all edges of `a`, in the specified direction.
///
/// - `Outgoing`: All edges from `a`.
/// - `Incoming`: All edges to `a`.
///
/// Produces an empty iterator if the node `a` doesn't exist.<br>
/// Iterator element type is [`EdgeReference<E, Ix>`](../graph/struct.EdgeReference.html).
pub fn edges_directed(&self, a: NodeIndex<Ix>, d: Direction) -> Edges<Directed, Null, Ix> {
if d == Outgoing {
self.edges(a)
} else {
Edges::on_rows(a.index(), &self.node_adjacencies, self.node_capacity)
}
}
}
/// Iterator over the node identifiers of a graph.
///
/// Created from a call to [`.node_identifiers()`][1] on a [`MatrixGraph`][2].
///
/// [1]: ../visit/trait.IntoNodeIdentifiers.html#tymethod.node_identifiers
/// [2]: struct.MatrixGraph.html
#[derive(Debug, Clone)]
pub struct NodeIdentifiers<'a, Ix> {
iter: IdIterator<'a>,
ix: PhantomData<Ix>,
}
impl<'a, Ix: IndexType> NodeIdentifiers<'a, Ix> {
fn new(iter: IdIterator<'a>) -> Self {
Self {
iter,
ix: PhantomData,
}
}
}
impl<'a, Ix: IndexType> Iterator for NodeIdentifiers<'a, Ix> {
type Item = NodeIndex<Ix>;
fn next(&mut self) -> Option<Self::Item> {
self.iter.next().map(NodeIndex::new)
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.iter.size_hint()
}
}
/// Iterator over all nodes of a graph.
///
/// Created from a call to [`.node_references()`][1] on a [`MatrixGraph`][2].
///
/// [1]: ../visit/trait.IntoNodeReferences.html#tymethod.node_references
/// [2]: struct.MatrixGraph.html
#[derive(Debug, Clone)]
pub struct NodeReferences<'a, N: 'a, Ix> {
nodes: &'a IdStorage<N>,
iter: IdIterator<'a>,
ix: PhantomData<Ix>,
}
impl<'a, N: 'a, Ix> NodeReferences<'a, N, Ix> {
fn new(nodes: &'a IdStorage<N>) -> Self {
NodeReferences {
nodes,
iter: nodes.iter_ids(),
ix: PhantomData,
}
}
}
impl<'a, N: 'a, Ix: IndexType> Iterator for NodeReferences<'a, N, Ix> {
type Item = (NodeIndex<Ix>, &'a N);
fn next(&mut self) -> Option<Self::Item> {
self.iter
.next()
.map(|i| (NodeIndex::new(i), &self.nodes[i]))
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.iter.size_hint()
}
}
/// Iterator over all edges of a graph.
///
/// Created from a call to [`.edge_references()`][1] on a [`MatrixGraph`][2].
///
/// [1]: ../visit/trait.IntoEdgeReferences.html#tymethod.edge_references
/// [2]: struct.MatrixGraph.html
#[derive(Debug, Clone)]
pub struct EdgeReferences<'a, Ty: EdgeType, Null: 'a + Nullable, Ix> {
row: usize,
column: usize,
node_adjacencies: &'a [Null],
node_capacity: usize,
ty: PhantomData<Ty>,
ix: PhantomData<Ix>,
}
impl<'a, Ty: EdgeType, Null: 'a + Nullable, Ix> EdgeReferences<'a, Ty, Null, Ix> {
fn new(node_adjacencies: &'a [Null], node_capacity: usize) -> Self {
EdgeReferences {
row: 0,
column: 0,
node_adjacencies,
node_capacity,
ty: PhantomData,
ix: PhantomData,
}
}
}
impl<'a, Ty: EdgeType, Null: Nullable, Ix: IndexType> Iterator
for EdgeReferences<'a, Ty, Null, Ix>
{
type Item = (NodeIndex<Ix>, NodeIndex<Ix>, &'a Null::Wrapped);
fn next(&mut self) -> Option<Self::Item> {
loop {
let (row, column) = (self.row, self.column);
if row >= self.node_capacity {
return None;
}
// By default, advance the column. Reset and advance the row if the column overflows.
//
// Note that for undirected graphs, we don't want to yield the same edge twice,
// therefore the maximum column length should be the index new after the row index.
self.column += 1;
let max_column_len = if !Ty::is_directed() {
row + 1
} else {
self.node_capacity
};
if self.column >= max_column_len {
self.column = 0;
self.row += 1;
}
let p = to_linearized_matrix_position::<Ty>(row, column, self.node_capacity);
if let Some(e) = self.node_adjacencies[p].as_ref() {
return Some((NodeIndex::new(row), NodeIndex::new(column), e));
}
}
}
}
/// Iterator over the neighbors of a node.
///
/// Iterator element type is `NodeIndex<Ix>`.
///
/// Created with [`.neighbors()`][1], [`.neighbors_directed()`][2].
///
/// [1]: struct.MatrixGraph.html#method.neighbors
/// [2]: struct.MatrixGraph.html#method.neighbors_directed
#[derive(Debug, Clone)]
pub struct Neighbors<'a, Ty: EdgeType, Null: 'a + Nullable, Ix>(Edges<'a, Ty, Null, Ix>);
impl<'a, Ty: EdgeType, Null: Nullable, Ix: IndexType> Iterator for Neighbors<'a, Ty, Null, Ix> {
type Item = NodeIndex<Ix>;
fn next(&mut self) -> Option<Self::Item> {
self.0.next().map(|(_, b, _)| b)
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.0.size_hint()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum NeighborIterDirection {
Rows,
Columns,
}
/// Iterator over the edges of from or to a node
///
/// Created with [`.edges()`][1], [`.edges_directed()`][2].
///
/// [1]: struct.MatrixGraph.html#method.edges
/// [2]: struct.MatrixGraph.html#method.edges_directed
#[derive(Debug, Clone)]
pub struct Edges<'a, Ty: EdgeType, Null: 'a + Nullable, Ix> {
iter_direction: NeighborIterDirection,
node_adjacencies: &'a [Null],
node_capacity: usize,
row: usize,
column: usize,
ty: PhantomData<Ty>,
ix: PhantomData<Ix>,
}
impl<'a, Ty: EdgeType, Null: 'a + Nullable, Ix> Edges<'a, Ty, Null, Ix> {
fn on_columns(row: usize, node_adjacencies: &'a [Null], node_capacity: usize) -> Self {
Edges {
iter_direction: NeighborIterDirection::Columns,
node_adjacencies,
node_capacity,
row,
column: 0,
ty: PhantomData,
ix: PhantomData,
}
}
fn on_rows(column: usize, node_adjacencies: &'a [Null], node_capacity: usize) -> Self {
Edges {
iter_direction: NeighborIterDirection::Rows,
node_adjacencies,
node_capacity,
row: 0,
column,
ty: PhantomData,
ix: PhantomData,
}
}
}
impl<'a, Ty: EdgeType, Null: Nullable, Ix: IndexType> Iterator for Edges<'a, Ty, Null, Ix> {
type Item = (NodeIndex<Ix>, NodeIndex<Ix>, &'a Null::Wrapped);
fn next(&mut self) -> Option<Self::Item> {
use self::NeighborIterDirection::*;
loop {
let (row, column) = (self.row, self.column);
if row >= self.node_capacity || column >= self.node_capacity {
return None;
}
match self.iter_direction {
Rows => self.row += 1,
Columns => self.column += 1,
}
let p = to_linearized_matrix_position::<Ty>(row, column, self.node_capacity);
if let Some(e) = self.node_adjacencies[p].as_ref() {
let (a, b) = match self.iter_direction {
Rows => (column, row),
Columns => (row, column),
};
return Some((NodeIndex::new(a), NodeIndex::new(b), e));
}
}
}
}
#[inline]
fn to_linearized_matrix_position<Ty: EdgeType>(row: usize, column: usize, width: usize) -> usize {
if Ty::is_directed() {
to_flat_square_matrix_position(row, column, width)
} else {
to_lower_triangular_matrix_position(row, column)
}
}
#[inline]
fn extend_linearized_matrix<Ty: EdgeType, T: Default>(
node_adjacencies: &mut Vec<T>,
old_node_capacity: usize,
new_capacity: usize,
exact: bool,
) -> usize {
if old_node_capacity >= new_capacity {
return old_node_capacity;
}
if Ty::is_directed() {
extend_flat_square_matrix(node_adjacencies, old_node_capacity, new_capacity, exact)
} else {
extend_lower_triangular_matrix(node_adjacencies, new_capacity)
}
}
#[inline]
fn to_flat_square_matrix_position(row: usize, column: usize, width: usize) -> usize {
row * width + column
}
#[inline]
fn extend_flat_square_matrix<T: Default>(
node_adjacencies: &mut Vec<T>,
old_node_capacity: usize,
new_node_capacity: usize,
exact: bool,
) -> usize {
// Grow the capacity by exponential steps to avoid repeated allocations.
// Disabled for the with_capacity constructor.
let new_node_capacity = if exact {
new_node_capacity
} else {
const MIN_CAPACITY: usize = 4;
cmp::max(new_node_capacity.next_power_of_two(), MIN_CAPACITY)
};
// Optimization: when resizing the matrix this way we skip the first few grows to make
// small matrices a bit faster to work with.
ensure_len(node_adjacencies, new_node_capacity.pow(2));
for c in (1..old_node_capacity).rev() {
let pos = c * old_node_capacity;
let new_pos = c * new_node_capacity;
// Move the slices directly if they do not overlap with their new position
if pos + old_node_capacity <= new_pos {
debug_assert!(pos + old_node_capacity < node_adjacencies.len());
debug_assert!(new_pos + old_node_capacity < node_adjacencies.len());
let ptr = node_adjacencies.as_mut_ptr();
// SAFETY: pos + old_node_capacity <= new_pos, so this won't overlap
unsafe {
let old = ptr.add(pos);
let new = ptr.add(new_pos);
core::ptr::swap_nonoverlapping(old, new, old_node_capacity);
}
} else {
for i in (0..old_node_capacity).rev() {
node_adjacencies.as_mut_slice().swap(pos + i, new_pos + i);
}
}
}
new_node_capacity
}
#[inline]
fn to_lower_triangular_matrix_position(row: usize, column: usize) -> usize {
let (row, column) = if row > column {
(row, column)
} else {
(column, row)
};
(row * (row + 1)) / 2 + column
}
#[inline]
fn extend_lower_triangular_matrix<T: Default>(
node_adjacencies: &mut Vec<T>,
new_capacity: usize,
) -> usize {
let max_node = new_capacity - 1;
let max_pos = to_lower_triangular_matrix_position(max_node, max_node);
ensure_len(node_adjacencies, max_pos + 1);
new_capacity
}
/// Grow a Vec by appending the type's default value until the `size` is reached.
fn ensure_len<T: Default>(v: &mut Vec<T>, size: usize) {
if let Some(n) = size.checked_sub(v.len()) {
v.reserve(n);
for _ in 0..n {
v.push(T::default());
}
}
}
#[derive(Debug, Clone)]
struct IdStorage<T> {
elements: Vec<Option<T>>,
upper_bound: usize,
removed_ids: IndexSet<usize>,
}
impl<T> IdStorage<T> {
fn with_capacity(capacity: usize) -> Self {
IdStorage {
elements: Vec::with_capacity(capacity),
upper_bound: 0,
removed_ids: IndexSet::new(),
}
}
fn add(&mut self, element: T) -> usize {
let id = if let Some(id) = self.removed_ids.pop() {
id
} else {
let id = self.upper_bound;
self.upper_bound += 1;
ensure_len(&mut self.elements, id + 1);
id
};
self.elements[id] = Some(element);
id
}
fn remove(&mut self, id: usize) -> T {
let data = self.elements[id].take().unwrap();
if self.upper_bound - id == 1 {
self.upper_bound -= 1;
} else {
self.removed_ids.insert(id);
}
data
}
fn clear(&mut self) {
self.upper_bound = 0;
self.elements.clear();
self.removed_ids.clear();
}
#[inline]
fn len(&self) -> usize {
self.upper_bound - self.removed_ids.len()
}
fn iter_ids(&self) -> IdIterator {
IdIterator {
upper_bound: self.upper_bound,
removed_ids: &self.removed_ids,
current: None,
}
}
}
impl<T> Index<usize> for IdStorage<T> {
type Output = T;
fn index(&self, index: usize) -> &T {
self.elements[index].as_ref().unwrap()
}
}
impl<T> IndexMut<usize> for IdStorage<T> {
fn index_mut(&mut self, index: usize) -> &mut T {
self.elements[index].as_mut().unwrap()
}
}
#[derive(Debug, Clone)]
struct IdIterator<'a> {
upper_bound: usize,
removed_ids: &'a IndexSet<usize>,
current: Option<usize>,
}
impl<'a> Iterator for IdIterator<'a> {
type Item = usize;
fn next(&mut self) -> Option<Self::Item> {
// initialize / advance
let current = {
if self.current.is_none() {
self.current = Some(0);
self.current.as_mut().unwrap()
} else {