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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
use std::collections::{HashMap, HashSet};
use std::collections::hash_map::Entry;
use std::fmt;
use std::fmt::{Debug, Formatter};
use std::hash::Hash;
type Pair<U> = (U, U);
/// Struct used to represent a relation.
/// The relation can be defined on any set of types,
/// as long as the type implements
/// `Eq`, `Hash`, `Clone`, and `Debug`.
///
/// Instances of the struct can either be created
/// using the `relation!` macro, or by using the
/// `from_iter` method:
///
/// ```
/// use relations::{relation, Relation};
///
/// let relation_1 = relation!(
/// 0 => 1,
/// 1 => 2,
/// 2 => 3
/// );
///
/// let relation_2 = Relation::from_iter(
/// [(0, 1), (1, 2), (2, 3)]
/// );
///
/// assert_eq!(relation_1, relation_2);
/// ```
#[derive(Debug)]
#[derive(Clone)]
pub struct Relation<U: Eq + Hash + Clone + Debug> {
forward_map: HashMap<U, usize>,
backward_map: Vec<U>,
relation: HashSet<Pair<usize>>
}
impl<U: Eq + Hash + Clone + Debug> fmt::Display for Relation<U> {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
let pairs = self.relation
.iter()
.map(
|(x, y)|
format!("({:?}, {:?})", self.backward_map[*x], self.backward_map[*y]));
let content = pairs.collect::<Vec<String>>().join(", ");
write!(f, "{{{}}}", content)
}
}
impl<U: Eq + Hash + Clone + Debug> Relation<U> {
fn new(forward_map: HashMap<U, usize>,
backward_map: Vec<U>,
relation: HashSet<Pair<usize>>) -> Self {
Relation{forward_map, backward_map, relation}
}
/// Create an empty relation
pub fn empty() -> Self {
Self::new(HashMap::new(), Vec::new(), HashSet::new())
}
/// Test whether two items x and y are related.
///
/// This is equivalent to checking whether (x, y)
/// is contained in the relation.
///
/// This also works for x and y not contained in the
/// relation, as long as x and y have the correct type.
///
/// ```
/// use relations::{relation, Relation};
///
/// let relation = relation!(0 => 1, 1 => 2, 2 => 3);
///
/// assert!(relation.are_related(&0, &1));
/// assert!(!relation.are_related(&0, &3));
/// ```
pub fn are_related(&self, x: &U, y: &U) -> bool {
if !self.forward_map.contains_key(x) || !self.forward_map.contains_key(y) {
return false;
}
self.relation.contains(&(self.forward_map[x], self.forward_map[y]))
}
/// Test whether the point y is reachable from point x.
///
/// y is reachable from x if there exists
/// x_1, x_2, ..., x_n such that
/// (x, x_1), (x_1, x_2), ..., (x_n, y)
/// are all contained in R.
///
/// ```
/// use relations::{relation, Relation};
///
/// let rel = relation!(
/// 1 => 2, 2 => 3, 3 => 1,
/// 4 => 5,
/// 6 => 7, 7 => 8,
/// 9 => 9
/// );
///
/// assert!(rel.reachable_from(&1, &2));
/// assert!(rel.reachable_from(&1, &3));
/// assert!(rel.reachable_from(&2, &3));
/// assert!(rel.reachable_from(&1, &1));
/// assert!(rel.reachable_from(&4, &5));
/// assert!(rel.reachable_from(&9, &9));
/// assert!(!rel.reachable_from(&1, &9));
/// assert!(!rel.reachable_from(&5, &4));
/// ```
pub fn reachable_from(&self, x: &U, y: &U) -> bool {
let u = self.forward_map[x];
let v = self.forward_map[y];
let mut graph = self.as_map();
let mut stack: Vec<usize> = Vec::with_capacity(self.backward_map.len());
let mut visited = vec![false; self.backward_map.len()];
stack.push(u);
while !stack.is_empty() {
let current = unsafe { stack.pop().unwrap_unchecked() };
if visited[current] {
continue;
}
visited[current] = true;
if current == v {
return true;
}
if let Entry::Occupied(o) = graph.entry(current) {
stack.extend(o.get());
}
}
false
}
/// Test whether the relation is reflexive.
///
/// The relation is reflexive if for every x contained
/// in any pair (x, y) or (y, x) in the relation, (x, x)
/// is also contained in the relation.
///
/// ```
/// use relations::{relation, Relation};
///
/// let relation = relation!(0 => 1, 1 => 2, 2 => 3);
///
/// assert!(!relation.is_reflexive());
/// ```
pub fn is_reflexive(&self) -> bool {
(0..self.backward_map.len())
.all(|x| self.relation.contains(&(x, x)))
}
/// Test whether the relation is irreflexive.
///
/// The relation is irreflexive if for every x contained
/// in any pair (x, y) or (y, x) in the relation, (x, x)
/// is not contained in the relation.
///
/// ```
/// use relations::{relation, Relation};
///
/// let relation = relation!(0 => 1, 1 => 2, 2 => 3);
///
/// assert!(relation.is_irreflexive());
/// ```
pub fn is_irreflexive(&self) -> bool {
(0..self.backward_map.len())
.all(|x| !self.relation.contains(&(x, x)))
}
/// Test whether the relation is symmetric
///
/// The relation is symmetric if for every pair (x, y)
/// contained in the relation, (y, x) is also contained
/// in the relation.
///
/// ```
/// use relations::{relation, Relation};
///
/// let relation = relation!(0 => 1, 1 => 2, 2 => 3);
///
/// assert!(!relation.is_symmetric());
/// ```
pub fn is_symmetric(&self) -> bool {
self.relation
.iter()
.copied()
.all(|(x, y)| self.relation.contains(&(y, x)))
}
/// Test whether the relation is transitive.
///
/// The relation is transitive if for every combination
/// of pairs (x, y) and (y, z) contained in the relation,
/// (x, z) is also contained in the relation.
///
/// ```
/// use relations::{relation, Relation};
///
/// let relation = relation!(0 => 1, 1 => 2, 2 => 3);
///
/// assert!(!relation.is_transitive());
/// ```
pub fn is_transitive(&self) -> bool {
for (x, y) in self.relation.iter().copied() {
for (u, v) in self.relation.iter().copied() {
if y != u {
continue;
}
if !self.relation.contains(&(x, v)) {
return false;
}
}
}
true
}
/// Test whether the relation is asymmetric.
///
/// The relation is asymmetric if for every
/// pair (x, y) contained in the relation,
/// (y, x) is not contained in the relation.
///
/// ```
/// use relations::{relation, Relation};
///
/// let relation = relation!(0 => 1, 1 => 2, 2 => 3);
///
/// assert!(relation.is_asymmetric());
/// ```
pub fn is_asymmetric(&self) -> bool {
// Note: this is equivalent to
// self.is_irreflexive() && self.is_antisymmetric()
self.relation
.iter()
.copied()
.all(|(x, y)| !self.relation.contains(&(y, x)))
}
/// Test whether the relation is antisymmetric.
///
/// The relation is antisymmetric if for every
/// pair (x, y) contained in the relation,
/// either x == y or (y, x) is not contained
/// in the relation.
///
/// ```
/// use relations::{relation, Relation};
///
/// let relation = relation!(0 => 1, 1 => 2, 2 => 3, 3 => 3);
///
/// assert!(relation.is_antisymmetric());
/// ```
pub fn is_antisymmetric(&self) -> bool {
self.relation
.iter()
.copied()
.all(|(x, y)| x == y || !self.relation.contains(&(y, x)))
}
/// Test whether the relation is an equivalence relation.
///
/// An equivalence relation is a relation which is
/// reflexive, symmetric, and transitive.
pub fn is_equivalence(&self) -> bool {
self.is_symmetric() && self.is_reflexive() && self.is_transitive()
}
/// Test whether the relation is a non-strict partial order.
///
/// A non strict partial order is reflexive, anti-symmetric,
/// and transitive.
pub fn is_non_strict_partial_order(&self) -> bool {
self.is_reflexive() && self.is_antisymmetric() && self.is_transitive()
}
/// Test whether the relation is a strict partial order.
///
/// A non strict partial order is reflexive, asymmetric,
/// and transitive.
pub fn is_strict_partial_order(&self) -> bool {
self.is_irreflexive() && self.is_asymmetric() && self.is_transitive()
}
/// Check whether the relation defines a function.
///
/// A function is a relation such that for all y and z
/// such that (x, y) and (x, z) are both contained in the
/// relation, y == z.
/// With other words, a function is a relation where for all
/// x, there is at most one tuple (x, _).
///
/// ```
/// use relations::{relation, Relation};
///
/// let rel_1 = relation!(1 => 2, 2 => 3, 1 => 3, 3 => 4);
/// let rel_2 = relation!(1 => 2, 2 => 3, 3 => 4);
///
/// assert!(!rel_1.is_function());
/// assert!(rel_2.is_function());
/// ```
pub fn is_function(&self) -> bool {
let mut counts = vec![0; self.backward_map.len()];
for (x, _) in self.relation.iter() {
counts[*x] += 1;
if counts[*x] > 1 {
return false;
}
}
true
}
/// Compute the reflexive closure of the relation.
///
/// The reflexive closure of the relation is the
/// relation itself, with all missing pairs (x, x)
/// added to it.
///
/// ```
/// use relations::{relation, Relation};
///
/// let relation = relation!(0 => 1, 1 => 2, 2 => 3);
///
/// assert_eq!(
/// relation.reflexive_closure(),
/// relation!(0 => 1, 1 => 2, 2 => 3, 0 => 0, 1 => 1, 2 => 2, 3 => 3)
/// );
/// ```
pub fn reflexive_closure(&self) -> Self {
let mut new_relation = self.relation.clone();
for x in 0..self.backward_map.len() {
let key = (x, x);
if !new_relation.contains(&key) {
new_relation.insert(key);
}
}
Self::new(self.forward_map.clone(),
self.backward_map.clone(),
new_relation)
}
/// Compute the symmetric closure of the relation.
///
/// The symmetric closure of the relation is the
/// relation itself, where for each pair (x, y),
/// we added the pair (y, x) if it not already
/// contained in the relation.
///
/// ```
/// use relations::{relation, Relation};
///
/// let relation = relation!(0 => 1, 1 => 2, 2 => 3);
///
/// assert_eq!(
/// relation.symmetric_closure(),
/// relation!(0 => 1, 1 => 2, 2 => 3, 3 => 2, 2 => 1, 1 => 0)
/// );
/// ```
pub fn symmetric_closure(&self) -> Self {
let mut new_relation = self.relation.clone();
for (x, y) in self.relation.iter().copied() {
let key = (y, x);
if !new_relation.contains(&key) {
new_relation.insert(key);
}
}
Self::new(self.forward_map.clone(),
self.backward_map.clone(),
new_relation)
}
/// Compute the transitive closure of the relation.
///
/// The transitive closure of the relation is the
/// relation itself, where, for all pairs
/// (x, y) and (y, z), we added the missing pairs
/// (x, z).
///
/// ```
/// use relations::{relation, Relation};
///
/// let relation = relation!(0 => 1, 1 => 2, 2 => 3);
///
/// assert_eq!(
/// relation.transitive_closure(),
/// relation!(
/// 0 => 1, 0 => 2, 0 => 3,
/// 1 => 2, 1 => 3,
/// 2 => 3
/// )
/// );
/// ```
pub fn transitive_closure(&self) -> Self {
let mut new_relation = self.relation.clone();
for k in 0..self.backward_map.len() {
for i in 0..self.backward_map.len() {
for j in 0..self.backward_map.len() {
let key_1 = (i, k);
let key_2 = (k, j);
if new_relation.contains(&key_1) && new_relation.contains(&key_2) {
new_relation.insert((i, j));
}
}
}
}
Self::new(self.forward_map.clone(),
self.backward_map.clone(),
new_relation)
}
/// Test whether the relation (self) is a subset of the
/// other relation.
///
/// This is equivalent to testing that:
/// self.are_related(x, y) ==> other.are_related(x, y)
///
/// ```
/// use relations::{relation, Relation};
///
/// let a = relation!(1 => 2, 2 => 3);
/// let b = relation!(1 => 2, 2 => 3);
/// let c = relation!(1 => 2, 2 => 3, 3 => 4);
///
/// assert!(a.is_subset(&b));
/// assert!(a.is_subset(&c));
/// assert!(!c.is_subset(&a));
/// ```
pub fn is_subset(&self, other: &Relation<U>) -> bool {
for (x, y) in self.relation.iter() {
let u = &self.backward_map[*x];
let v = &self.backward_map[*y];
if !other.are_related(u, v) {
return false;
}
}
true
}
/// Test whether the relation (self) is a proper subset of the
/// other relation.
///
/// self is a proper subset of other if self.is_subset(other),
/// and self != other.
///
/// ```
/// use relations::{relation, Relation};
///
/// let a = relation!(1 => 2, 2 => 3);
/// let b = relation!(1 => 2, 2 => 3);
/// let c = relation!(1 => 2, 2 => 3, 3 => 4);
///
/// assert!(!a.is_proper_subset(&b));
/// assert!(a.is_proper_subset(&c));
/// assert!(!c.is_proper_subset(&a));
/// ```
pub fn is_proper_subset(&self, other: &Relation<U>) -> bool {
self.is_subset(other) & !other.is_subset(self)
}
/// Compute the relative set for some given element x.
///
/// The relative set of x is the set of all elements
/// y such that (x, y) is contained in the relation.
///
/// ```
/// use std::collections::HashSet;
/// use relations::{relation, Relation};
///
/// let rel = relation!(1 => 2, 1 => 3, 2 => 3);
///
/// assert_eq!(rel.relative_set(&1), HashSet::from([2, 3]));
/// ```
pub fn relative_set(&self, x: &U) -> HashSet<U> {
if !self.forward_map.contains_key(x) {
return HashSet::new();
}
let target = self.forward_map[x];
let indices = self.relation
.iter()
.filter(|(p, _)| p == &target)
.map(|(_, q)| q);
HashSet::from_iter(indices.map(|y| self.backward_map[*y].clone()))
}
/// Compute the transpose relation of this relation.
///
/// The transposed relation is obtained by taking
/// the original relation containing pairs (x, y),
/// and constructing a new relation containing
/// all pairs (y, x).
///
/// ```
/// use relations::{relation, Relation};
///
/// let rel = relation!(1 => 2, 1 => 3, 2 => 3);
///
/// assert_eq!(
/// rel.transpose(),
/// relation!(2 => 1, 3 => 1, 3 => 2)
/// );
/// ```
pub fn transpose(&self) -> Relation<U> {
Self::new(
self.forward_map.clone(),
self.backward_map.clone(),
self.relation.iter().copied().map(|(x, y)| (y, x)).collect()
)
}
/// Alias for the `transpose` method.
#[inline(always)]
pub fn inverse(&self) -> Relation<U> {
self.transpose()
}
/// Compute the complement of the relation.
///
/// The complement contains all pairs (x, y)
/// such that x and y are not related in the original
/// relation.
///
/// ```
/// use relations::{relation, Relation};
///
/// let rel = relation!(1 => 2, 2 => 3, 3 => 4, 4 => 1);
///
/// assert_eq!(
/// rel.complement(),
/// relation!(
/// 1 => 1, 2 => 2, 3 => 3, 4 => 4,
/// 1 => 3, 1 => 4,
/// 2 => 1, 2 => 4,
/// 3 => 1, 3 => 2,
/// 4 => 2, 4 => 3
/// )
/// );
/// assert_eq!(rel.complement().complement(), rel);
/// ```
pub fn complement(&self) -> Relation<U> {
let mut pairs: HashSet<Pair<&U>> = HashSet::new();
for x in self.backward_map.iter() {
for y in self.backward_map.iter() {
if !self.are_related(x, y) {
pairs.insert((x, y));
}
}
}
Self::from_iter(pairs)
}
/// Compute the equivalence classes of the relation.
/// This method can only be called if the relation is
/// an equivalence relation.
///
/// Equivalence classes are sets of elements which
/// are considered "equal" or equivalent according
/// to the relation.
///
/// ```
/// use std::collections::HashSet;
/// use relations::{relation, Relation};
///
/// let relation = relation!(
/// 1 => 2, 2 => 1, 1 => 1, 2 => 2,
///
/// 3 => 4, 4 => 5, 3 => 5, 5 => 3, 5 => 4, 4 => 3,
/// 3 => 3, 4 => 4, 5 => 5,
///
/// 6 => 6
/// );
///
/// assert_eq!(
/// relation.equivalence_classes(),
/// vec![
/// HashSet::from([1, 2]),
/// HashSet::from([3, 4, 5]),
/// HashSet::from([6]),
/// ]
/// );
/// ```
pub fn equivalence_classes(&self) -> Vec<HashSet<U>> {
if !self.is_equivalence() {
panic!(".equivalence_classes() can only be called on an equivalence");
}
let mut classes: Vec<HashSet<usize>> = Vec::new();
let mut class_indices: HashMap<usize, usize> = HashMap::new();
let mut pairs = self.relation.iter().copied().collect::<Vec<(usize, usize)>>();
pairs.sort();
for (from, to) in pairs {
if let Entry::Vacant(e) = class_indices.entry(from) {
e.insert(classes.len());
classes.push(HashSet::from([from]));
}
classes[class_indices[&from]].insert(to);
class_indices.insert(to, class_indices[&from]);
}
classes
.into_iter()
.map(|cls|
cls
.into_iter()
.map(|x| self.backward_map[x].clone()).collect())
.collect()
}
/// Compute the strongly connected components of the relation.
///
/// Strongly connected components are groups of elements
/// where there exists a "path" from any element to any
/// other element.
///
/// ```
/// use std::collections::HashSet;
/// use relations::{relation, Relation};
///
/// let rel_2 = relation!(
/// 1 => 2,
/// 2 => 3, 2 => 5,
/// 3 => 4, 3 => 7,
/// 4 => 3, 4 => 8,
/// 5 => 6, 5 => 1,
/// 6 => 7,
/// 7 => 6,
/// 8 => 4, 8 => 7
/// );
/// assert_eq!(
/// rel_2.strongly_connected_components(),
/// vec![
/// HashSet::from([1, 2, 5]),
/// HashSet::from([3, 4, 8]),
/// HashSet::from([6, 7]),
/// ]
/// );
/// ```
pub fn strongly_connected_components(&self) -> Vec<HashSet<U>> {
let mut stack: Vec<usize> = Vec::with_capacity(self.forward_map.len());
// First round of DFS
let mut visited: Vec<bool> = vec![false; self.forward_map.len()];
let mut graph = self.as_map();
for v in 0..self.forward_map.len() {
Self::dfs_1(v, &mut graph, &mut visited, &mut stack);
}
// Second round of DFS
let mut groups = Vec::new();
let mut transposed_graph = self.transpose().as_map();
visited = vec![false; self.forward_map.len()];
stack.reverse();
for v in stack.into_iter() {
let mut current_group: HashSet<U> = HashSet::new();
self.dfs_2(v, &mut transposed_graph, &mut visited, &mut current_group);
if !current_group.is_empty() {
groups.push(current_group);
}
}
groups
}
fn dfs_1(v: usize,
graph: &mut HashMap<usize, HashSet<usize>>,
visited: &mut Vec<bool>,
stack: &mut Vec<usize>)
{
if !visited[v] {
visited[v] = true;
let children = graph
.entry(v)
.or_insert_with(HashSet::new);
for child in children.iter().copied().collect::<Vec<_>>() {
Self::dfs_1(child, graph, visited, stack);
}
stack.push(v);
}
}
fn dfs_2(&self,
v: usize,
graph: &mut HashMap<usize, HashSet<usize>>,
visited: &mut Vec<bool>,
group: &mut HashSet<U>)
{
if !visited[v] {
visited[v] = true;
group.insert(self.backward_map[v].clone());
let children = graph
.entry(v)
.or_insert_with(HashSet::new);
for child in children.iter().copied().collect::<Vec<_>>() {
self.dfs_2(child, graph, visited, group);
}
}
}
/// Build the connectivity relation of the relation.
///
/// The connectivity relation contains all pairs (x, y)
/// such that there exists a path from x to y in the
/// original relation.
/// With other words, the connectivity relation contains
/// all pairs (x, y) such that for the original relation
/// `r`, r.reachable_from(&x, &y) == true.
///
/// ```
/// use relations::{relation, Relation};
///
/// let rel = relation!(
/// 1 => 2, 2 => 3, 3 => 4,
/// 4 => 2,
/// 5 => 6, 6 => 5
/// );
///
/// let conn_rel = rel.connectivity_relation();
///
/// assert_eq!(
/// conn_rel,
/// relation!(
/// 1 => 2, 1 => 3, 1 => 4,
/// 2 => 3, 2 => 4, 2 => 2,
/// 3 => 4, 3 => 2, 3 => 3,
/// 4 => 2, 4 => 3, 4 => 4,
/// 5 => 6, 6 => 5, 5 => 5, 6 => 6
/// )
/// );
/// ```
pub fn connectivity_relation(&self) -> Relation<U> {
let mut connected_pairs: HashSet<Pair<usize>> = HashSet::new();
let mut graph = self.as_map();
for start in 0..self.backward_map.len() {
let mut stack = Vec::with_capacity(self.backward_map.len());
let mut visited = vec![false; self.backward_map.len()];
stack.push(start);
while !stack.is_empty() {
let current = unsafe { stack.pop().unwrap_unchecked() };
if visited[current] {
continue;
}
visited[current] = true;
let children = graph
.entry(current)
.or_insert_with(HashSet::new);
for child in children.iter().copied().collect::<Vec<_>>() {
connected_pairs.insert((start, child));
stack.push(child);
}
}
}
Self::new(
self.forward_map.clone(),
self.backward_map.clone(),
connected_pairs
)
}
/// Multiply two relations.
///
/// The product of two relations is defined in the
/// following way:
/// if the LHS contains (x, y) and the RHS contains
/// (y, z), then the product contains (x, z).
///
/// Note that this is a non-commutative product.
///
/// ```
/// use relations::{relation, Relation};
///
/// let rel = relation!(1 => 2, 2 => 3, 3 => 4);
///
/// assert_eq!(rel.product(&rel), relation!(1 => 3, 2 => 4));
/// ```
pub fn product(&self, other: &Relation<U>) -> Relation<U> {
let mut pairs: HashSet<Pair<U>> = HashSet::new();
for (x, y) in self.relation.iter().copied() {
for (u, v) in other.relation.iter().copied() {
if self.backward_map[y] != other.backward_map[u] {
continue;
}
let pair = (self.backward_map[x].clone(), other.backward_map[v].clone());
pairs.insert(pair);
}
}
Relation::from_iter(pairs)
}
/// Optimized function for computing R^2.
fn pow2(&self) -> Relation<U> {
let graph = self.as_map();
let mut pairs: HashSet<Pair<usize>> = HashSet::new();
for (from, targets) in graph.iter() {
for target in targets.iter() {
if graph.contains_key(target) {
for new_target in graph[target].iter() {
pairs.insert((*from, *new_target));
}
}
}
}
Self::new(self.forward_map.clone(),
self.backward_map.clone(),
pairs)
}
/// Compute the n-th power of the relation.
///
/// Here, the n-th power of the relation by multiplying
/// the relation n times with itself, using the
/// `.product` function.
/// Note that R^1 = R, and R^0 is the identity relation.
///
/// We can interpret R^n as the relation of all pairs
/// (x, y) where we can move in n steps from x to y
/// in the original relation R.
///
/// ```
/// use relations::{relation, Relation};
///
/// let rel = relation!(1 => 2, 2 => 3, 3 => 4);
///
/// assert_eq!(rel.pow(0), relation!(1 => 1, 2 => 2, 3 => 3, 4 => 4));
/// assert_eq!(rel.pow(1), rel);
/// assert_eq!(rel.pow(2), relation!(1 => 3, 2 => 4));
/// assert_eq!(rel.pow(3), relation!(1 => 4));
/// assert_eq!(rel.pow(4), relation!());
/// ```
pub fn pow(&self, n: u64) -> Relation<U> {
// We can use the well-known divide and conquer
// algorithm for exponentiation.
// This is because the product of relations
// is equivalent/isomorphic to the multiplication
// of matrices representing the relations.
if n == 0 {
let identity = (0..self.backward_map.len()).map(|x| (x, x));
return Self::new(
self.forward_map.clone(),
self.backward_map.clone(),
HashSet::from_iter(identity)
);
} else if n == 1 {
return self.clone();
}
let half = self.pow(n / 2);
let prod = half.pow2();
if n % 2 == 1 {
return self.product(&prod);
}
prod
}
/// Return a boolean indicating whether the relation
/// represents a DAG (directed acyclic graph).
///
/// ```
/// use relations::relation;
///
/// let loopy = relation!(1 => 2, 2 => 1);
/// assert!(!loopy.is_dag());
///
/// let linear = relation!(1 => 2, 2 => 3, 3 => 4);
/// assert!(linear.is_dag());
/// ```
pub fn is_dag(&self) -> bool {
self.topological_sort().is_some()
}
/// Topologically sort the relation, or return None if the
/// relation contains a cycle.
///
/// ```
/// use relations::relation;
///
/// let linear = relation!(1 => 2, 2 => 3, 3 => 4, 4 => 5);
/// let sort = linear.topological_sort();
/// assert!(sort.is_some());
/// let order = sort.unwrap();
/// assert!(
/// order == vec![1, 2, 3, 4, 5] ||
/// order == vec![5, 4, 3, 2, 1],
/// "simple: {:?}", order
/// );
///
/// let complex = relation!(1 => 2, 1 => 3, 2 => 5, 2 => 4, 3 => 6, 3 => 4, 4 => 5, 4 => 6);
/// let sort = complex.topological_sort();
/// assert!(sort.is_some());
/// let order = sort.unwrap();
/// assert!(
/// order == vec![1, 2, 3, 4, 5, 6] ||
/// order == vec![1, 3, 2, 4, 5, 6] ||
/// order == vec![1, 2, 3, 4, 6, 5] ||
/// order == vec![1, 3, 2, 4, 6, 5],
/// "complex: {:?}", order
/// );
///
/// let cyclic = relation!(1 => 2, 2 => 3, 3 => 1);
/// let sort = cyclic.topological_sort();
/// assert!(sort.is_none());
///
/// let self_loop = relation!(1 => 2, 2 => 2);
/// let sort = self_loop.topological_sort();
/// assert!(sort.is_none());
/// ```
pub fn topological_sort(&self) -> Option<Vec<U>> {
let mut incoming: Vec<usize> = (0..self.backward_map.len())
.map(|_| 0).collect();
let mut order: Vec<usize> = Vec::new();
let graph = self.as_map();
for (_, destinations) in graph.iter() {
for destination in destinations {
incoming[*destination] += 1;
}
}
let mut todo = incoming.iter()
.enumerate()
.filter(|(_, c)| **c == 0)
.map(|(i, _)| i)
.collect::<Vec<_>>();
let empty = HashSet::new();
while !todo.is_empty() {
let current = todo.pop().unwrap();
order.push(current);
for to in graph.get(¤t).unwrap_or(&empty).iter().copied() {
incoming[to] -= 1;
if incoming[to] == 0 {
todo.push(to);
}
}
}
if incoming.iter().any(|c| *c > 0) {
None
} else {
let result = order
.into_iter()
.map(|i| self.backward_map[i].clone())
.collect();
Some(result)
}
}
/// Compute all cycles in the graph represented by the relation.
///
/// ```
/// use relations::relation;
///
/// let linear = relation!(1 => 2, 2 => 3, 3 => 4);
/// assert_eq!(linear.find_cycles(), Vec::<Vec<i32>>::new());
///
/// let loopy = relation!(1 => 2, 2 => 1);
/// let cycles = loopy.find_cycles();
/// assert!(
/// cycles == vec![vec![1, 2]] || cycles == vec![vec![2, 1]],
/// "loopy: {:?}", cycles
/// );
/// ```
pub fn find_cycles(&self) -> Vec<Vec<U>> {
let graph = self.as_map();
let mut cycles = Vec::new();
let mut visited = (0..self.backward_map.len())
.into_iter()
.map(|_| false)
.collect::<Vec<_>>();
for start in 0..self.backward_map.len() {
if visited[start] {
continue;
}
let mut path = vec![start];
self.find_cycles_dfs(start, &graph, &mut visited, &mut path, &mut cycles);
}
cycles.into_iter().map(
|path|
path.into_iter().map(|i| self.backward_map[i].clone()).collect()
).collect()
}
fn find_cycles_dfs(&self,
current: usize,
graph: &HashMap<usize, HashSet<usize>>,
visited: &mut Vec<bool>,
path: &mut Vec<usize>,
cycles: &mut Vec<Vec<usize>>) {
visited[current] = true;
let empty = HashSet::new();
for to in graph.get(¤t).unwrap_or(&empty).iter().copied() {
if visited[to] {
if let Some(index) = path.iter().position(|&x| x == to) {
cycles.push(path[index..].to_vec());
}
} else if !visited[to] {
path.push(to);
self.find_cycles_dfs(to, graph, visited, path, cycles);
path.remove(path.len() - 1);
}
}
}
fn as_map(&self) -> HashMap<usize, HashSet<usize>> {
let mut map: HashMap<usize, HashSet<usize>> = HashMap::new();
for (x, y) in self.relation.iter().copied() {
map.entry(x).or_insert_with(HashSet::new).insert(y);
}
map
}
/// Convert the relation into a hashmap, where for
/// every key-value entry, the key is related
/// to all the items in the value (which is a hashset).
///
/// ```
/// use std::collections::{HashMap, HashSet};
/// use relations::{relation, Relation};
///
/// let rel = relation!(
/// 1 => 2, 1 => 3, 2 => 3,
/// 4 => 4,
/// 5 => 6, 6 => 5
/// );
///
/// let map = HashMap::from_iter(
/// [
/// (1, HashSet::from([2, 3])),
/// (2, HashSet::from([3])),
/// (4, HashSet::from([4])),
/// (5, HashSet::from([6])),
/// (6, HashSet::from([5])),
/// ]
/// );
///
/// assert_eq!(rel.to_hashmap(), map);
/// ```
pub fn to_hashmap(&self) -> HashMap<U, HashSet<U>> {
HashMap::from_iter(
self.as_map().into_iter().map(|(from, tos)|
(
self.backward_map[from].clone(),
HashSet::from_iter(tos.into_iter().map(|x| self.backward_map[x].clone()))
)
)
)
}
}
impl<U: Eq + Hash + Clone + Debug> FromIterator<Pair<U>> for Relation<U> {
fn from_iter<T: IntoIterator<Item=Pair<U>>>(iter: T) -> Self {
let mut forward_map = HashMap::new();
let mut backward_map = Vec::new();
let mut relation = HashSet::new();
for (x, y) in iter {
[&x, &y].into_iter().for_each(|z| {
let item = z.clone();
if !forward_map.contains_key(&item) {
let id = forward_map.len();
forward_map.insert(item.clone(), id);
backward_map.push(item);
}
});
relation.insert((forward_map[&x], forward_map[&y]));
}
Self::new(forward_map, backward_map, relation)
}
}
impl<'a, U: Eq + Hash + Clone + Debug> FromIterator<Pair<&'a U>> for Relation<U> {
fn from_iter<T: IntoIterator<Item=Pair<&'a U>>>(iter: T) -> Self {
let mut forward_map = HashMap::new();
let mut backward_map = Vec::new();
let mut relation = HashSet::new();
for (x, y) in iter {
[&x, &y].into_iter().for_each(|z| {
let item = *z;
if !forward_map.contains_key(item) {
let id = forward_map.len();
forward_map.insert(item.clone(), id);
backward_map.push(item.clone());
}
});
relation.insert((forward_map[x], forward_map[y]));
}
Self::new(forward_map, backward_map, relation)
}
}
impl<U: Eq + Hash + Clone + Debug> PartialEq for Relation<U> {
fn eq(&self, other: &Self) -> bool {
self.is_subset(other) && other.is_subset(self)
}
}
impl<U: Eq + Hash + Clone + Debug> Eq for Relation<U> {}
/// Convenience macro for defining a relation with
/// a static set of pairs.
///
/// Example usage:
/// ```
/// use relations::{relation, Relation};
///
/// let my_relation = relation!(1 => 2, 2 => 3, 3 => 4);
/// ```
#[macro_export]
macro_rules! relation {
() => {
{
$crate::Relation::empty()
}
};
($($from:expr => $to:expr),*) => {
{
$crate::Relation::from_iter(
[
$(
($from, $to),
)*
]
)
}
};
}