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
use std::cmp::{Eq, Ord, Ordering, PartialEq, PartialOrd};
use std::convert::From;
use std::hash::{Hash, Hasher};
use std::ops::Index;

use crate::{IntoCanon, IsIdentical};

use petgraph::{
    data::DataMap,
    graph::{
        DefaultIx, Edge, EdgeIndex, EdgeIndices, EdgeReference, EdgeReferences,
        Edges, EdgesConnecting, Externals, Graph, IndexType, Neighbors, Node,
        NodeIndex, NodeIndices, NodeReferences,
    },
    stable_graph::StableGraph,
    visit::{
        Data, EdgeCount, EdgeIndexable, EdgeRef, GetAdjacencyMatrix, GraphBase,
        GraphProp, IntoEdgeReferences, IntoEdges, IntoEdgesDirected,
        IntoNeighbors, IntoNeighborsDirected, IntoNodeIdentifiers,
        IntoNodeReferences, NodeCount, NodeIndexable,
    },
    Directed, Direction, EdgeType, IntoWeightedEdge, Undirected,
};

pub type CanonDiGraph<N, E, Ix> = CanonGraph<N, E, Directed, Ix>;
pub type CanonUnGraph<N, E, Ix> = CanonGraph<N, E, Undirected, Ix>;

/// Canonically labelled graph
///
/// The interface closely mimics
/// [petgraph::Graph](https://docs.rs/petgraph/latest/petgraph/graph/struct.Graph.html).
/// The exception are mutating methods, which could potentially
/// be misused to destroy the canonical labelling.
///
/// # Example
///
/// ```rust
/// use std::collections::HashSet;
/// use petgraph::graph::UnGraph;
/// use nauty_pet::prelude::*;
///
/// let g = UnGraph::<(), ()>::from_edges([(0, 1), (1, 2)]);
///
/// // canonical labelling
/// let g = CanonGraph::from(g);
///
/// // we can now compare `g` to other canonically labelled graphs and
/// // use it in hash sets and tables.
/// assert_eq!(g, g);
/// let mut graphs = HashSet::new();
/// graphs.insert(g);
/// ```
///
#[cfg_attr(feature = "serde-1", derive(serde::Serialize, serde::Deserialize))]
#[derive(Clone, Debug, Default)]
pub struct CanonGraph<N, E, Ty: EdgeType = Directed, Ix: IndexType = DefaultIx>(
    Graph<N, E, Ty, Ix>,
);

impl<N, E, Ty, Ix> CanonGraph<N, E, Ty, Ix>
where
    Ty: EdgeType,
    Ix: IndexType,
{
    /// Gets a reference to the underlying `petgraph::Graph`
    pub fn get(&self) -> &Graph<N, E, Ty, Ix> {
        &self.0
    }

    pub fn node_count(&self) -> usize {
        self.0.node_count()
    }

    pub fn edge_count(&self) -> usize {
        self.0.edge_count()
    }

    pub fn is_directed(&self) -> bool {
        self.0.is_directed()
    }

    pub fn node_weight(&self, a: NodeIndex<Ix>) -> Option<&N> {
        self.0.node_weight(a)
    }

    pub fn edge_weight(&self, e: EdgeIndex<Ix>) -> Option<&E> {
        self.0.edge_weight(e)
    }

    pub fn edge_endpoints(&self, e: EdgeIndex<Ix>) -> Option<&E> {
        self.0.edge_weight(e)
    }

    pub fn neighbors(&self, a: NodeIndex<Ix>) -> Neighbors<'_, E, Ix> {
        self.0.neighbors(a)
    }

    pub fn neighbors_directed(
        &self,
        a: NodeIndex<Ix>,
        dir: Direction,
    ) -> Neighbors<'_, E, Ix> {
        self.0.neighbors_directed(a, dir)
    }

    pub fn neighbors_undirected(
        &self,
        a: NodeIndex<Ix>,
    ) -> Neighbors<'_, E, Ix> {
        self.0.neighbors_undirected(a)
    }

    pub fn edges(&self, a: NodeIndex<Ix>) -> Edges<'_, E, Ty, Ix> {
        self.0.edges(a)
    }

    pub fn edges_directed(
        &self,
        a: NodeIndex<Ix>,
        dir: Direction,
    ) -> Edges<'_, E, Ty, Ix> {
        self.0.edges_directed(a, dir)
    }

    pub fn edges_connecting(
        &self,
        a: NodeIndex<Ix>,
        b: NodeIndex<Ix>,
    ) -> EdgesConnecting<'_, E, Ty, Ix> {
        self.0.edges_connecting(a, b)
    }

    pub fn contains_edge(&self, a: NodeIndex<Ix>, b: NodeIndex<Ix>) -> bool {
        self.0.contains_edge(a, b)
    }

    pub fn find_edge_undirected(
        &self,
        a: NodeIndex<Ix>,
        b: NodeIndex<Ix>,
    ) -> Option<(EdgeIndex<Ix>, Direction)> {
        self.0.find_edge_undirected(a, b)
    }

    pub fn externals(&self, dir: Direction) -> Externals<'_, N, Ty, Ix> {
        self.0.externals(dir)
    }

    pub fn node_indices(&self) -> NodeIndices<Ix> {
        self.0.node_indices()
    }

    // TODO: return `NodeWeights<'_, N, Ix>`, but it's private in petgraph 0.6.0
    pub fn node_weights(&self) -> impl Iterator<Item = &N> {
        self.0.node_weights()
    }

    pub fn edge_indices(&self) -> EdgeIndices<Ix> {
        self.0.edge_indices()
    }

    pub fn edge_references(&self) -> EdgeReferences<'_, E, Ix> {
        self.0.edge_references()
    }

    // TODO: return `EdgeWeights<'_, E, Ix>`, but it's private in petgraph 0.6.0
    pub fn edge_weights(&self) -> impl Iterator<Item = &E> {
        self.0.edge_weights()
    }

    pub fn raw_nodes(&self) -> &[Node<N, Ix>] {
        self.0.raw_nodes()
    }

    pub fn raw_edges(&self) -> &[Edge<E, Ix>] {
        self.0.raw_edges()
    }

    pub fn into_nodes_edges(self) -> (Vec<Node<N, Ix>>, Vec<Edge<E, Ix>>) {
        self.0.into_nodes_edges()
    }

    pub fn next_edge(
        &self,
        e: EdgeIndex<Ix>,
        dir: Direction,
    ) -> Option<EdgeIndex<Ix>> {
        self.0.next_edge(e, dir)
    }

    pub fn capacity(&self) -> (usize, usize) {
        self.0.capacity()
    }
}

impl<N, E, Ty, Ix> CanonGraph<N, E, Ty, Ix>
where
    Ty: EdgeType,
    Ix: IndexType,
    Graph<N, E, Ty, Ix>: IntoCanon,
{
    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,
    {
        Self(Graph::from_edges(iterable).into_canon())
    }
}

impl<N, E, Ty, Ix> AsRef<Graph<N, E, Ty, Ix>> for CanonGraph<N, E, Ty, Ix>
where
    Ty: EdgeType,
    Ix: IndexType,
{
    fn as_ref(&self) -> &Graph<N, E, Ty, Ix> {
        &self.0
    }
}

impl<N, E, Ty, Ix> From<Graph<N, E, Ty, Ix>> for CanonGraph<N, E, Ty, Ix>
where
    Graph<N, E, Ty, Ix>: IntoCanon,
    Ty: EdgeType,
    Ix: IndexType,
{
    fn from(g: Graph<N, E, Ty, Ix>) -> Self {
        Self(g.into_canon())
    }
}

impl<N, E, Ty, Ix> From<CanonGraph<N, E, Ty, Ix>> for Graph<N, E, Ty, Ix>
where
    Ty: EdgeType,
    Ix: IndexType,
{
    fn from(g: CanonGraph<N, E, Ty, Ix>) -> Self {
        g.0
    }
}

impl<N, E, Ty, Ix> Data for CanonGraph<N, E, Ty, Ix>
where
    CanonGraph<N, E, Ty, Ix>: GraphBase,
    Graph<N, E, Ty, Ix>: Data,
    Ty: EdgeType,
    Ix: IndexType,
{
    type NodeWeight = N;
    type EdgeWeight = E;
}

impl<N, E, Ty, Ix> DataMap for CanonGraph<N, E, Ty, Ix>
where
    CanonGraph<N, E, Ty, Ix>:
        GraphBase<NodeId = NodeIndex<Ix>, EdgeId = EdgeIndex<Ix>>,
    CanonGraph<N, E, Ty, Ix>: Data<NodeWeight = N, EdgeWeight = E>,
    Ty: EdgeType,
    Ix: IndexType,
{
    fn node_weight(&self, id: Self::NodeId) -> Option<&Self::NodeWeight> {
        Self::node_weight(self, id)
    }
    fn edge_weight(&self, id: Self::EdgeId) -> Option<&Self::EdgeWeight> {
        Self::edge_weight(self, id)
    }
}

impl<N, E, Ty, Ix> EdgeCount for CanonGraph<N, E, Ty, Ix>
where
    CanonGraph<N, E, Ty, Ix>:
        GraphBase<NodeId = NodeIndex<Ix>, EdgeId = EdgeIndex<Ix>>,
    Ty: EdgeType,
    Ix: IndexType,
{
    fn edge_count(&self) -> usize {
        self.0.edge_count()
    }
}

impl<N, E, Ty, Ix> EdgeIndexable for CanonGraph<N, E, Ty, Ix>
where
    CanonGraph<N, E, Ty, Ix>:
        GraphBase<NodeId = NodeIndex<Ix>, EdgeId = EdgeIndex<Ix>>,
    Ty: EdgeType,
    Ix: IndexType,
{
    fn edge_bound(&self) -> usize {
        self.0.edge_bound()
    }

    fn to_index(&self, ix: EdgeIndex<Ix>) -> usize {
        EdgeIndexable::to_index(&self.0, ix)
    }

    fn from_index(&self, ix: usize) -> Self::EdgeId {
        EdgeIndexable::from_index(&self.0, ix)
    }
}

impl<N, E, Ty, Ix> From<CanonGraph<N, E, Ty, Ix>> for StableGraph<N, E, Ty, Ix>
where
    Ty: EdgeType,
    Ix: IndexType,
{
    fn from(g: CanonGraph<N, E, Ty, Ix>) -> Self {
        g.0.into()
    }
}

impl<N, E, Ty, Ix> From<StableGraph<N, E, Ty, Ix>> for CanonGraph<N, E, Ty, Ix>
where
    Graph<N, E, Ty, Ix>: IntoCanon,
    Ty: EdgeType,
    Ix: IndexType,
{
    fn from(g: StableGraph<N, E, Ty, Ix>) -> Self {
        let g: Graph<_, _, _, _> = g.into();
        Self(g.into_canon())
    }
}

impl<N, E, Ty, Ix> GetAdjacencyMatrix for CanonGraph<N, E, Ty, Ix>
where
    Ty: EdgeType,
    Ix: IndexType,
    CanonGraph<N, E, Ty, Ix>:
        GraphBase<NodeId = NodeIndex<Ix>, EdgeId = EdgeIndex<Ix>>,
    Graph<N, E, Ty, Ix>:
        GraphBase<NodeId = NodeIndex<Ix>, EdgeId = EdgeIndex<Ix>>,
    Graph<N, E, Ty, Ix>: GetAdjacencyMatrix,
{
    type AdjMatrix = <Graph<N, E, Ty, Ix> as GetAdjacencyMatrix>::AdjMatrix;

    fn adjacency_matrix(&self) -> Self::AdjMatrix {
        self.0.adjacency_matrix()
    }

    fn is_adjacent(
        &self,
        matrix: &Self::AdjMatrix,
        a: NodeIndex<Ix>,
        b: NodeIndex<Ix>,
    ) -> bool {
        self.0.is_adjacent(matrix, a, b)
    }
}

impl<N, E, Ty, Ix> GraphBase for CanonGraph<N, E, Ty, Ix>
where
    Ty: EdgeType,
    Ix: IndexType,
{
    type NodeId = NodeIndex<Ix>;

    type EdgeId = EdgeIndex<Ix>;
}

impl<N, E, Ty, Ix> GraphProp for CanonGraph<N, E, Ty, Ix>
where
    Ty: EdgeType,
    Ix: IndexType,
{
    type EdgeType = Ty;

    fn is_directed(&self) -> bool {
        self.0.is_directed()
    }
}

impl<N, E, Ty, Ix> Index<EdgeIndex<Ix>> for CanonGraph<N, E, Ty, Ix>
where
    Ty: EdgeType,
    Ix: IndexType,
{
    type Output = E;

    fn index(&self, index: EdgeIndex<Ix>) -> &E {
        self.0.index(index)
    }
}

impl<N, E, Ty, Ix> Index<NodeIndex<Ix>> for CanonGraph<N, E, Ty, Ix>
where
    Ty: EdgeType,
    Ix: IndexType,
{
    type Output = N;

    fn index(&self, index: NodeIndex<Ix>) -> &N {
        self.0.index(index)
    }
}

impl<'a, N: 'a, E: 'a, Ty, Ix> IntoEdgeReferences
    for &'a CanonGraph<N, E, Ty, Ix>
where
    Ty: EdgeType,
    Ix: IndexType,
{
    type EdgeRef = EdgeReference<'a, E, Ix>;
    type EdgeReferences = EdgeReferences<'a, E, Ix>;

    fn edge_references(self) -> Self::EdgeReferences {
        self.0.edge_references()
    }
}

impl<'a, N, E, Ty, Ix> IntoEdges for &'a CanonGraph<N, E, Ty, Ix>
where
    Ty: EdgeType,
    Ix: IndexType,
{
    type Edges = Edges<'a, E, Ty, Ix>;

    fn edges(self, a: Self::NodeId) -> Self::Edges {
        self.0.edges(a)
    }
}

impl<'a, N, E, Ty, Ix> IntoEdgesDirected for &'a CanonGraph<N, E, Ty, Ix>
where
    Ty: EdgeType,
    Ix: IndexType,
{
    type EdgesDirected = Edges<'a, E, Ty, Ix>;

    fn edges_directed(
        self,
        a: Self::NodeId,
        dir: Direction,
    ) -> Self::EdgesDirected {
        self.0.edges_directed(a, dir)
    }
}

impl<'a, N, E: 'a, Ty, Ix> IntoNeighbors for &'a CanonGraph<N, E, Ty, Ix>
where
    Ty: EdgeType,
    Ix: IndexType,
{
    type Neighbors = Neighbors<'a, E, Ix>;

    fn neighbors(self, n: NodeIndex<Ix>) -> Neighbors<'a, E, Ix> {
        self.neighbors(n)
    }
}

impl<'a, N, E: 'a, Ty, Ix> IntoNeighborsDirected
    for &'a CanonGraph<N, E, Ty, Ix>
where
    Ty: EdgeType,
    Ix: IndexType,
{
    type NeighborsDirected = Neighbors<'a, E, Ix>;

    fn neighbors_directed(
        self,
        n: NodeIndex<Ix>,
        d: Direction,
    ) -> Neighbors<'a, E, Ix> {
        self.neighbors_directed(n, d)
    }
}

impl<'a, N, E: 'a, Ty, Ix> IntoNodeIdentifiers for &'a CanonGraph<N, E, Ty, Ix>
where
    Ty: EdgeType,
    Ix: IndexType,
{
    type NodeIdentifiers = NodeIndices<Ix>;

    fn node_identifiers(self) -> NodeIndices<Ix> {
        self.0.node_identifiers()
    }
}

impl<'a, N, E, Ty, Ix> IntoNodeReferences for &'a CanonGraph<N, E, Ty, Ix>
where
    Ty: EdgeType,
    Ix: IndexType,
{
    type NodeRef = (NodeIndex<Ix>, &'a N);
    type NodeReferences = NodeReferences<'a, N, Ix>;

    fn node_references(self) -> Self::NodeReferences {
        self.0.node_references()
    }
}

impl<N, E, Ty, Ix> NodeCount for CanonGraph<N, E, Ty, Ix>
where
    Ty: EdgeType,
    Ix: IndexType,
{
    fn node_count(&self) -> usize {
        self.0.node_count()
    }
}

impl<N, E, Ty, Ix> NodeIndexable for CanonGraph<N, E, Ty, Ix>
where
    Ty: EdgeType,
    Ix: IndexType,
{
    fn node_bound(&self) -> usize {
        self.0.node_bound()
    }

    fn to_index(&self, ix: NodeIndex<Ix>) -> usize {
        NodeIndexable::to_index(&self.0, ix)
    }

    fn from_index(&self, ix: usize) -> Self::NodeId {
        NodeIndexable::from_index(&self.0, ix)
    }
}

impl<N, E, Ty, Ix> PartialEq for CanonGraph<N, E, Ty, Ix>
where
    N: PartialEq,
    E: PartialEq,
    Ty: EdgeType,
    Ix: IndexType,
{
    fn eq(&self, other: &Self) -> bool {
        self.0.is_identical(&other.0)
    }
}
impl<N: Eq, E: Eq, Ty: EdgeType, Ix: IndexType> Eq
    for CanonGraph<N, E, Ty, Ix>
{
}

impl<N: Hash, E: Hash, Ty: EdgeType, Ix: IndexType> Hash
    for CanonGraph<N, E, Ty, Ix>
{
    fn hash<H: Hasher>(&self, state: &mut H) {
        for w in self.0.node_weights() {
            w.hash(state)
        }
        for e in self.0.edge_references() {
            e.source().hash(state);
            e.target().hash(state);
            e.weight().hash(state);
        }
    }
}

// Doesn't have to make much sense, just give a reproducible ordering
impl<N: Ord, E: Ord, Ty: EdgeType, Ix: IndexType> Ord
    for CanonGraph<N, E, Ty, Ix>
{
    fn cmp(&self, other: &Self) -> Ordering {
        let cmp = self.0.node_weights().cmp(other.0.node_weights());
        if cmp == Ordering::Equal {
            let my_edges = self
                .0
                .edge_references()
                .map(|e| (e.source(), e.target(), e.weight()));
            let other_edges = self
                .0
                .edge_references()
                .map(|e| (e.source(), e.target(), e.weight()));
            my_edges.cmp(other_edges)
        } else {
            cmp
        }
    }
}

impl<N, E, Ty, Ix> PartialOrd for CanonGraph<N, E, Ty, Ix>
where
    N: PartialOrd,
    E: PartialOrd,
    Ty: EdgeType,
    Ix: IndexType,
{
    // TODO: code duplication
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        let cmp = self.0.node_weights().partial_cmp(other.0.node_weights());
        if cmp == Some(Ordering::Equal) {
            let my_edges = self
                .0
                .edge_references()
                .map(|e| (e.source(), e.target(), e.weight()));
            let other_edges = self
                .0
                .edge_references()
                .map(|e| (e.source(), e.target(), e.weight()));
            my_edges.partial_cmp(other_edges)
        } else {
            cmp
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    use log::debug;
    use rand::prelude::*;
    use rand_xoshiro::Xoshiro256Plus;
    use testing::{randomize_labels, GraphIter};

    fn log_init() {
        let _ = env_logger::builder().is_test(true).try_init();
    }

    #[test]
    fn random_canon_graph() {
        log_init();

        let mut rng = Xoshiro256Plus::seed_from_u64(0);
        let graphs = GraphIter::<Undirected>::default();

        for g in graphs.take(1000) {
            debug!("Initial graph: {g:#?}");
            let gg = randomize_labels(g.clone(), &mut rng);
            debug!("Randomised graph: {gg:#?}");
            let g = CanonGraph::from(g);
            debug!("Canonical graph (from initial): {g:#?}");
            let gg = CanonGraph::from(gg);
            debug!("Canonical graph (from randomised): {gg:#?}");
            assert_eq!(g, gg);
        }
    }
}