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
|
//! This file implements a labelled graph that can index vertices by
//! labels and each node knows about its parents.
use super::*;
use crate::{Parent, ParentsGraph};
use std::{
collections::{hash_map::Iter as MapIter, HashMap as Map},
slice::Iter,
};
use crate::builder::BuilderMut;
/// An ad-hoc `IndexSet` for children.
#[derive(Debug, Clone, Default)]
struct PLChildren {
children: Vec<usize>,
indices: Map<usize, usize>,
}
impl PLChildren {
fn iter(&self) -> Iter<'_, usize> {
self.children.iter()
}
fn len(&self) -> usize {
self.children.len()
}
fn is_empty(&self) -> bool {
self.children.is_empty()
}
fn contains(&self, key: &usize) -> bool {
self.indices.contains_key(key)
}
// The return value matters not for me.
fn insert(&mut self, key: usize) {
if let Some(key_index) = self.indices.get(&key) {
debug_assert!(*key_index < self.children.len());
*self.children.get_mut(*key_index).unwrap() = key;
} else {
let key_index = self.children.len();
self.indices.insert(key, key_index);
self.children.push(key);
}
}
/// Remove an element from children.
///
/// We must preserve the order of elements, so we have to shift
/// every element that follows it, which leads to a slow
/// performance. So try to avoid removing edges, if possible.
fn remove(&mut self, key: usize) {
let key_index = if let Some(key_index_result) = self.indices.get(&key) {
*key_index_result
} else {
// If the key is not contained in children, we have
// nothing to do.
return;
};
let children_len = self.children.len();
debug_assert!(key_index < children_len);
for i in (key_index + 1)..children_len {
let key = self.children.get(i).unwrap();
*self.indices.get_mut(key).unwrap() -= 1;
}
self.children.remove(key_index);
}
}
/// A node has some children, some parents, and a label.
#[derive(Debug, Clone)]
struct PLNode<T: GraphLabel> {
children: PLChildren,
parents: Map<usize, usize>,
label: T,
}
impl<T: GraphLabel> PLNode<T> {
fn new(children: PLChildren, parents: Map<usize, usize>, label: T) -> Self {
Self {
children,
parents,
label,
}
}
}
impl<T: GraphLabel + Default> Default for PLNode<T> {
#[inline]
fn default() -> Self {
let children = Default::default();
let parents = Default::default();
let label = Default::default();
Self {
children,
label,
parents,
}
}
}
/// A Parents-knowing, vertex-Labelled Graph.
#[derive(Debug, Clone)]
pub struct PLGraph<T: GraphLabel> {
nodes: Vec<PLNode<T>>,
label_index_map: Map<T, usize>,
}
impl<T: GraphLabel> Default for PLGraph<T> {
#[inline]
fn default() -> Self {
let nodes = Default::default();
let label_index_map = Default::default();
Self {
nodes,
label_index_map,
}
}
}
impl<T: GraphLabel> Graph for PLGraph<T> {
type Iter<'a> = std::iter::Copied<Iter<'a, usize>>
where
Self: 'a;
#[inline]
fn is_empty(&self) -> bool {
self.nodes.is_empty()
}
#[inline]
fn nodes_len(&self) -> usize {
self.nodes.len()
}
#[inline]
fn children_of(&self, node_id: usize) -> Result<Self::Iter<'_>, Error> {
if let Some(node) = self.nodes.get(node_id) {
Ok(node.children.iter().copied())
} else {
Err(Error::IndexOutOfBounds(node_id, self.nodes.len()))
}
}
#[inline]
fn degree(&self, node_id: usize) -> Result<usize, Error> {
if let Some(node) = self.nodes.get(node_id) {
Ok(node.children.len())
} else {
Err(Error::IndexOutOfBounds(node_id, self.nodes.len()))
}
}
#[inline]
fn is_empty_node(&self, node_id: usize) -> Result<bool, Error> {
if let Some(node) = self.nodes.get(node_id) {
Ok(node.children.is_empty())
} else {
Err(Error::IndexOutOfBounds(node_id, self.nodes.len()))
}
}
#[inline]
fn has_edge(&self, source: usize, target: usize) -> Result<bool, Error> {
if let Some(node) = self.nodes.get(source) {
if !self.has_node(target) {
return Err(Error::IndexOutOfBounds(target, self.nodes.len()));
}
Ok(node.children.contains(&target))
} else {
Err(Error::IndexOutOfBounds(source, self.nodes.len()))
}
}
fn replace_by_builder(&mut self, _builder: impl Builder<Result = Self>) {
todo!()
}
fn print_viz(&self, _filename: &str) -> Result<(), std::io::Error> {
todo!()
}
}
/// An iterator of parents.
///
/// This is to avoid a boxed allocation.
#[derive(Debug, Clone)]
pub struct ParentIter<'a> {
/// MapIter yields (&usize, &usize), so we need to dereference
/// that.
parents: MapIter<'a, usize, usize>,
}
impl<'a> ParentIter<'a> {
fn new(parents: MapIter<'a, usize, usize>) -> Self {
Self { parents }
}
}
impl<'a> Iterator for ParentIter<'a> {
type Item = Parent;
#[inline]
fn next(&mut self) -> Option<Self::Item> {
self.parents
.next()
.map(|(key, value)| Parent::new(*key, *value))
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
self.parents.size_hint()
}
}
impl<'a> ExactSizeIterator for ParentIter<'a> {
#[inline]
fn len(&self) -> usize {
self.parents.len()
}
}
impl<T: GraphLabel> ParentsGraph for PLGraph<T> {
type Iter<'a> = ParentIter<'a>
where Self: 'a;
#[inline]
fn parents_of(&self, node_id: usize) -> Result<<Self as ParentsGraph>::Iter<'_>, Error> {
if let Some(node) = self.nodes.get(node_id) {
Ok(ParentIter::new(node.parents.iter()))
} else {
Err(Error::IndexOutOfBounds(node_id, self.nodes.len()))
}
}
}
impl<T: GraphLabel> LabelGraph<T> for PLGraph<T> {
type Iter<'a> = std::iter::Empty<usize>
where
Self: 'a;
type LabelIter<'a> = std::iter::Empty<(&'a T, <Self as LabelGraph<T>>::Iter<'a>)>
where
Self: 'a,
T: 'a;
type EdgeLabelIter<'a> = std::iter::Empty<T>
where
Self: 'a,
T: 'a;
#[inline]
fn query_label(&self, label: T) -> Option<usize> {
self.label_index_map.get(&label).copied()
}
#[inline]
fn vertex_label(&self, node_id: usize) -> Result<Option<T>, Error> {
if let Some(node) = self.nodes.get(node_id) {
Ok(Some(node.label))
} else {
Err(Error::IndexOutOfBounds(node_id, self.nodes.len()))
}
}
fn edge_label(&self, _source: usize, _target: usize) -> Result<Self::EdgeLabelIter<'_>, Error> {
unimplemented!("Edges have no labels")
}
fn find_children_with_label(
&self,
_node_id: usize,
_label: &T,
) -> Result<<Self as LabelGraph<T>>::Iter<'_>, Error> {
unimplemented!("Edges have no labels")
}
fn labels_of(&self, _node_id: usize) -> Result<Self::LabelIter<'_>, Error> {
unimplemented!("Edges have no labels")
}
fn has_edge_label(&self, _node_id: usize, _label: &T, _target: usize) -> Result<bool, Error> {
unimplemented!("Edges have no labels")
}
}
/// A builder that modifies PLGraph in place.
#[derive(Debug)]
pub struct PLGBuilderMut<'a, T: GraphLabel> {
graph: &'a mut PLGraph<T>,
}
impl<'a, T: GraphLabel> BuilderMut for PLGBuilderMut<'a, T> {
type Label = T;
type Graph = PLGraph<T>;
type ResultBuilder<'b> = PLGBuilderMut<'b, T>
where
Self::Label: 'b;
#[inline]
fn from_graph_mut(graph: &mut Self::Graph) -> Self::ResultBuilder<'_> {
PLGBuilderMut { graph }
}
#[inline]
fn add_vertex(&mut self, label: Self::Label) -> usize {
if let Some(old) = self.graph.label_index_map.get(&label) {
*old
} else {
let new_node = PLNode::new(Default::default(), Default::default(), label);
self.graph.nodes.push(new_node);
let new_index = self.graph.nodes.len() - 1;
self.graph.label_index_map.insert(label, new_index);
new_index
}
}
#[inline]
fn add_edge(&mut self, source: usize, target: usize, _label: Self::Label) -> Result<(), Error> {
if self.graph.has_edge(source, target)? {
return Ok(());
}
// The validity of source and target is guaranteed now.
let parent_child_index = self.graph.degree(source).unwrap();
self.graph
.nodes
.get_mut(source)
.unwrap()
.children
.insert(target);
self.graph
.nodes
.get_mut(target)
.unwrap()
.parents
.insert(source, parent_child_index);
Ok(())
}
/// Remove an edge from the source to the target.
///
/// Since some graphs are labelled, the users are allowed to pass
/// a predicate to determine if an edge from the source to the
/// target should be removed.
///
/// # Performance
///
/// Removal is slow since we need to keep the order of the elements.
fn remove_edge<F>(&mut self, source: usize, target: usize, _predicate: F) -> Result<(), Error>
where
F: FnMut(Self::Label) -> bool,
{
if !self.graph.has_edge(source, target)? {
return Ok(());
}
// Both source and target are valid indices now.
let child_index = *self
.graph
.nodes
.get(target)
.unwrap()
.parents
.get(&source)
.unwrap();
let source_degree = self.graph.degree(source).unwrap();
// Decrement the relevant children's parents index.
for i in (child_index + 1)..source_degree {
let child = *self
.graph
.nodes
.get(source)
.unwrap()
.children
.children
.get(i)
.unwrap();
*self
.graph
.nodes
.get_mut(child)
.unwrap()
.parents
.get_mut(&source)
.unwrap() -= 1;
}
self.graph
.nodes
.get_mut(source)
.unwrap()
.children
.remove(target);
self.graph
.nodes
.get_mut(target)
.unwrap()
.parents
.remove(&source);
Ok(())
}
}
#[cfg(test)]
mod binary_test {
use super::*;
use std::collections::HashSet as Set;
macro_rules! set {
($type:tt) => { Set::<$type>::default() };
($($num:expr),*) => {
{
let mut set: Set<_> = Set::default();
$(set.insert($num);)*
set
}
};
}
#[test]
fn test_graph_apis() -> Result<(), Error> {
let mut graph: PLGraph<usize> = Default::default();
// testing empty graph
assert!(graph.is_empty());
let mut builder = PLGBuilderMut::from_graph_mut(&mut graph);
// testing adding an empty node
assert_eq!(builder.add_vertex(0), 0);
// testing nodes_len
assert_eq!(graph.nodes_len(), 1);
let mut builder = PLGBuilderMut::from_graph_mut(&mut graph);
// testing more vertices and edges
builder.add_vertex(1);
builder.add_vertex(2);
builder.add_vertex(3);
builder.add_vertex(4);
builder.add_vertex(5);
builder.add_edge(1, 0, 0)?;
builder.add_edge(2, 0, 0)?;
builder.add_edge(2, 1, 0)?;
builder.add_edge(3, 0, 0)?;
builder.add_edge(3, 2, 0)?;
builder.add_edge(4, 1, 0)?;
builder.add_edge(4, 2, 0)?;
builder.add_edge(5, 2, 0)?;
builder.add_edge(5, 3, 0)?;
builder.add_edge(5, 1, 0)?;
// testing adding a duplicatedly labelled node
assert_eq!(builder.add_vertex(0), 0);
let graph = graph;
// ensuring the correct length
assert_eq!(graph.nodes_len(), 6);
// testing children_of
assert_eq!(graph.children_of(5)?.collect::<Set<_>>(), set!(1, 3, 2));
// testing parents_of
assert_eq!(
graph.parents_of(0)?.collect::<Set<_>>(),
set!(Parent::new(1, 0), Parent::new(2, 0), Parent::new(3, 0))
);
assert_eq!(
graph.parents_of(1)?.collect::<Set<_>>(),
set!(Parent::new(2, 1), Parent::new(4, 0), Parent::new(5, 2))
);
assert_eq!(graph.parents_of(5)?.len(), 0);
// testing degree
assert_eq!(graph.degree(4)?, 2);
// testing is_empty_node
assert!(graph.is_empty_node(0)?);
assert!(!graph.is_empty_node(1)?);
// testing has_edge
assert!(graph.has_edge(3, 2)?);
assert!(!graph.has_edge(3, 1)?);
assert!(matches!(
graph.has_edge(3, 6),
Err(Error::IndexOutOfBounds(6, 6))
));
Ok(())
}
}
#[cfg(test)]
mod test_plgraph_builder {
use super::*;
#[test]
fn test_builder() -> Result<(), Box<dyn std::error::Error>> {
let mut graph = PLGraph::<usize>::default();
let mut builder = PLGBuilderMut::from_graph_mut(&mut graph);
// Add five nodes
builder.add_vertex(0);
builder.add_vertex(1);
builder.add_vertex(2);
builder.add_vertex(3);
builder.add_vertex(4);
// println!("five empty nodes: {builder:?}");
// Link each node to its successor and link the last node with
// the first one to form a cycle.
for i in 0..5 {
builder.add_edge(i, if i < 4 { i + 1 } else { 0 }, 0)?;
}
// println!("a cycle of five nodes: {builder:?}");
// Remove the link from the last node to the first node.
builder.remove_edge(4, 0, |_| true)?;
// println!("a line of five nodes: {builder:?}");
// build a graph
let graph = graph;
println!("final graph: {graph:?}");
Ok(())
}
#[test]
fn test_errors() -> Result<(), Box<dyn std::error::Error>> {
let mut graph = PLGraph::<usize>::default();
let mut builder = PLGBuilderMut::from_graph_mut(&mut graph);
// Add five nodes
builder.add_vertex(0);
builder.add_vertex(1);
builder.add_vertex(2);
builder.add_vertex(3);
builder.add_vertex(4);
// println!("five empty nodes: {builder:?}");
// Errors in add_edge
// println!();
// println!("Testing errors in add_edge:");
// println!();
assert!(matches!(
builder.add_edge(0, 5, 0),
Err(Error::IndexOutOfBounds(5, 5))
));
// println!("Right error for an index out of bounds as the target");
assert!(matches!(
builder.add_edge(10, 5, 0),
Err(Error::IndexOutOfBounds(10, 5))
));
// println!("Right error for an index out of bounds as the source");
assert!(matches!(
builder.add_edge(10, 50, 0),
Err(Error::IndexOutOfBounds(10, 5))
));
// println!("Right error for both indices out of bounds");
// Errors in remove_edge
// println!();
// println!("Testing errors in remove_edge:");
// println!();
assert!(matches!(
builder.remove_edge(0, 5, |_| true),
Err(Error::IndexOutOfBounds(5, 5))
));
// println!("Right error for an index out of bounds as the target");
assert!(matches!(
builder.remove_edge(10, 5, |_| true),
Err(Error::IndexOutOfBounds(10, 5))
));
// println!("Right error for an index out of bounds as the source");
assert!(matches!(
builder.remove_edge(10, 50, |_| true),
Err(Error::IndexOutOfBounds(10, 5))
));
// println!("Right error for both indices out of bounds");
assert!(builder.remove_edge(0, 1, |_| true).is_ok());
// println!("No errors for removing a non-existing edge");
// println!();
let graph = graph;
println!("final graph: {graph:?}");
Ok(())
}
}
|