-
Notifications
You must be signed in to change notification settings - Fork 141
/
lib.rs
3155 lines (3025 loc) · 112 KB
/
lib.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
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations
// under the License.
mod astar;
mod digraph;
mod dijkstra;
mod dot_utils;
mod generators;
mod graph;
mod isomorphism;
mod iterators;
mod k_shortest_path;
mod max_weight_matching;
mod union;
use std::cmp::{Ordering, Reverse};
use std::collections::{BTreeSet, BinaryHeap};
use hashbrown::{HashMap, HashSet};
use pyo3::create_exception;
use pyo3::exceptions::{PyException, PyValueError};
use pyo3::prelude::*;
use pyo3::types::{PyDict, PyList};
use pyo3::wrap_pyfunction;
use pyo3::wrap_pymodule;
use pyo3::Python;
use petgraph::algo;
use petgraph::graph::NodeIndex;
use petgraph::prelude::*;
use petgraph::visit::{
Bfs, Data, GraphBase, GraphProp, IntoEdgeReferences, IntoNeighbors,
IntoNodeIdentifiers, NodeCount, NodeIndexable, Reversed, VisitMap,
Visitable,
};
use petgraph::EdgeType;
use ndarray::prelude::*;
use numpy::IntoPyArray;
use rand::distributions::{Distribution, Uniform};
use rand::prelude::*;
use rand_pcg::Pcg64;
use rayon::prelude::*;
use crate::generators::PyInit_generators;
use crate::iterators::{EdgeList, NodeIndices};
trait NodesRemoved {
fn nodes_removed(&self) -> bool;
}
fn longest_path(graph: &digraph::PyDiGraph) -> PyResult<Vec<usize>> {
let dag = &graph.graph;
let mut path: Vec<usize> = Vec::new();
let nodes = match algo::toposort(graph, None) {
Ok(nodes) => nodes,
Err(_err) => {
return Err(DAGHasCycle::new_err("Sort encountered a cycle"))
}
};
if nodes.is_empty() {
return Ok(path);
}
let mut dist: HashMap<NodeIndex, (usize, NodeIndex)> = HashMap::new();
for node in nodes {
let parents =
dag.neighbors_directed(node, petgraph::Direction::Incoming);
let mut us: Vec<(usize, NodeIndex)> = Vec::new();
for p_node in parents {
let length = dist[&p_node].0 + 1;
us.push((length, p_node));
}
let maxu: (usize, NodeIndex);
if !us.is_empty() {
maxu = *us.iter().max_by_key(|x| x.0).unwrap();
} else {
maxu = (0, node);
};
dist.insert(node, maxu);
}
let first = match dist.keys().max_by_key(|index| dist[index]) {
Some(first) => first,
None => {
return Err(PyException::new_err(
"Encountered something unexpected",
))
}
};
let mut v = *first;
let mut u: Option<NodeIndex> = None;
while match u {
Some(u) => u != v,
None => true,
} {
path.push(v.index());
u = Some(v);
v = dist[&v].1;
}
path.reverse();
Ok(path)
}
/// Find the longest path in a DAG
///
/// :param PyDiGraph graph: The graph to find the longest path on. The input
/// object must be a DAG without a cycle.
///
/// :returns: The node indices of the longest path on the DAG
/// :rtype: NodeIndices
///
/// :raises Exception: If an unexpected error occurs or a path can't be found
/// :raises DAGHasCycle: If the input PyDiGraph has a cycle
#[pyfunction]
#[text_signature = "(graph, /)"]
fn dag_longest_path(graph: &digraph::PyDiGraph) -> PyResult<NodeIndices> {
Ok(NodeIndices {
nodes: longest_path(graph)?,
})
}
/// Find the length of the longest path in a DAG
///
/// :param PyDiGraph graph: The graph to find the longest path on. The input
/// object must be a DAG without a cycle.
///
/// :returns: The longest path length on the DAG
/// :rtype: int
///
/// :raises Exception: If an unexpected error occurs or a path can't be found
/// :raises DAGHasCycle: If the input PyDiGraph has a cycle
#[pyfunction]
#[text_signature = "(graph, /)"]
fn dag_longest_path_length(graph: &digraph::PyDiGraph) -> PyResult<usize> {
let path = longest_path(graph)?;
if path.is_empty() {
return Ok(0);
}
let path_length: usize = path.len() - 1;
Ok(path_length)
}
/// Find the number of weakly connected components in a DAG.
///
/// :param PyDiGraph graph: The graph to find the number of weakly connected
/// components on
///
/// :returns: The number of weakly connected components in the DAG
/// :rtype: int
#[pyfunction]
#[text_signature = "(graph, /)"]
fn number_weakly_connected_components(graph: &digraph::PyDiGraph) -> usize {
algo::connected_components(graph)
}
/// Find the weakly connected components in a directed graph
///
/// :param PyDiGraph graph: The graph to find the weakly connected components
/// in
///
/// :returns: A list of sets where each set it a weakly connected component of
/// the graph
/// :rtype: list
#[pyfunction]
#[text_signature = "(graph, /)"]
pub fn weakly_connected_components(
graph: &digraph::PyDiGraph,
) -> Vec<BTreeSet<usize>> {
let mut seen: HashSet<NodeIndex> =
HashSet::with_capacity(graph.node_count());
let mut out_vec: Vec<BTreeSet<usize>> = Vec::new();
for node in graph.graph.node_indices() {
if !seen.contains(&node) {
// BFS node generator
let mut component_set: BTreeSet<usize> = BTreeSet::new();
let mut bfs_seen: HashSet<NodeIndex> = HashSet::new();
let mut next_level: HashSet<NodeIndex> = HashSet::new();
next_level.insert(node);
while !next_level.is_empty() {
let this_level = next_level;
next_level = HashSet::new();
for bfs_node in this_level {
if !bfs_seen.contains(&bfs_node) {
component_set.insert(bfs_node.index());
bfs_seen.insert(bfs_node);
for neighbor in
graph.graph.neighbors_undirected(bfs_node)
{
next_level.insert(neighbor);
}
}
}
}
out_vec.push(component_set);
seen.extend(bfs_seen);
}
}
out_vec
}
/// Check if the graph is weakly connected
///
/// :param PyDiGraph graph: The graph to check if it is weakly connected
///
/// :returns: Whether the graph is weakly connected or not
/// :rtype: bool
///
/// :raises NullGraph: If an empty graph is passed in
#[pyfunction]
#[text_signature = "(graph, /)"]
pub fn is_weakly_connected(graph: &digraph::PyDiGraph) -> PyResult<bool> {
if graph.graph.node_count() == 0 {
return Err(NullGraph::new_err("Invalid operation on a NullGraph"));
}
Ok(weakly_connected_components(graph)[0].len() == graph.graph.node_count())
}
/// Check that the PyDiGraph or PyDAG doesn't have a cycle
///
/// :param PyDiGraph graph: The graph to check for cycles
///
/// :returns: ``True`` if there are no cycles in the input graph, ``False``
/// if there are cycles
/// :rtype: bool
#[pyfunction]
#[text_signature = "(graph, /)"]
fn is_directed_acyclic_graph(graph: &digraph::PyDiGraph) -> bool {
match algo::toposort(graph, None) {
Ok(_nodes) => true,
Err(_err) => false,
}
}
/// Return a new PyDiGraph by forming a union from two input PyDiGraph objects
///
/// The algorithm in this function operates in three phases:
///
/// 1. Add all the nodes from ``second`` into ``first``. operates in O(n),
/// with n being number of nodes in `b`.
/// 2. Merge nodes from ``second`` over ``first`` given that:
///
/// - The ``merge_nodes`` is ``True``. operates in O(n^2), with n being the
/// number of nodes in ``second``.
/// - The respective node in ``second`` and ``first`` share the same
/// weight/data payload.
///
/// 3. Adds all the edges from ``second`` to ``first``. If the ``merge_edges``
/// parameter is ``True`` and the respective edge in ``second`` and
/// first`` share the same weight/data payload they will be merged
/// together.
///
/// :param PyDiGraph first: The first directed graph object
/// :param PyDiGraph second: The second directed graph object
/// :param bool merge_nodes: If set to ``True`` nodes will be merged between
/// ``second`` and ``first`` if the weights are equal.
/// :param bool merge_edges: If set to ``True`` edges will be merged between
/// ``second`` and ``first`` if the weights are equal.
///
/// :returns: A new PyDiGraph object that is the union of ``second`` and
/// ``first``. It's worth noting the weight/data payload objects are
/// passed by reference from ``first`` and ``second`` to this new object.
/// :rtype: PyDiGraph
#[pyfunction]
#[text_signature = "(first, second, merge_nodes, merge_edges, /)"]
fn digraph_union(
py: Python,
first: &digraph::PyDiGraph,
second: &digraph::PyDiGraph,
merge_nodes: bool,
merge_edges: bool,
) -> PyResult<digraph::PyDiGraph> {
let res =
union::digraph_union(py, first, second, merge_nodes, merge_edges)?;
Ok(res)
}
/// Determine if 2 directed graphs are isomorphic
///
/// This checks if 2 graphs are isomorphic both structurally and also
/// comparing the node data and edge data using the provided matcher functions.
/// The matcher function takes in 2 data objects and will compare them. A simple
/// example that checks if they're just equal would be::
///
/// graph_a = retworkx.PyDiGraph()
/// graph_b = retworkx.PyDiGraph()
/// retworkx.is_isomorphic(graph_a, graph_b,
/// lambda x, y: x == y)
///
/// :param PyDiGraph first: The first graph to compare
/// :param PyDiGraph second: The second graph to compare
/// :param callable node_matcher: A python callable object that takes 2 positional
/// one for each node data object. If the return of this
/// function evaluates to True then the nodes passed to it are vieded
/// as matching.
/// :param callable edge_matcher: A python callable object that takes 2 positional
/// one for each edge data object. If the return of this
/// function evaluates to True then the edges passed to it are vieded
/// as matching.
///
/// :returns: ``True`` if the 2 graphs are isomorphic ``False`` if they are
/// not.
/// :rtype: bool
#[pyfunction]
#[text_signature = "(first, second, node_matcher=None, edge_matcher=None, /)"]
fn digraph_is_isomorphic(
py: Python,
first: &digraph::PyDiGraph,
second: &digraph::PyDiGraph,
node_matcher: Option<PyObject>,
edge_matcher: Option<PyObject>,
) -> PyResult<bool> {
let compare_nodes = node_matcher.map(|f| {
move |a: &PyObject, b: &PyObject| -> PyResult<bool> {
let res = f.call1(py, (a, b))?;
Ok(res.is_true(py).unwrap())
}
});
let compare_edges = edge_matcher.map(|f| {
move |a: &PyObject, b: &PyObject| -> PyResult<bool> {
let res = f.call1(py, (a, b))?;
Ok(res.is_true(py).unwrap())
}
});
let res = isomorphism::is_isomorphic(
py,
&first.graph,
&second.graph,
compare_nodes,
compare_edges,
)?;
Ok(res)
}
/// Determine if 2 undirected graphs are isomorphic
///
/// This checks if 2 graphs are isomorphic both structurally and also
/// comparing the node data and edge data using the provided matcher functions.
/// The matcher function takes in 2 data objects and will compare them. A simple
/// example that checks if they're just equal would be::
///
/// graph_a = retworkx.PyGraph()
/// graph_b = retworkx.PyGraph()
/// retworkx.is_isomorphic(graph_a, graph_b,
/// lambda x, y: x == y)
///
/// :param PyGraph first: The first graph to compare
/// :param PyGraph second: The second graph to compare
/// :param callable node_matcher: A python callable object that takes 2 positional
/// one for each node data object. If the return of this
/// function evaluates to True then the nodes passed to it are vieded
/// as matching.
/// :param callable edge_matcher: A python callable object that takes 2 positional
/// one for each edge data object. If the return of this
/// function evaluates to True then the edges passed to it are vieded
/// as matching.
///
/// :returns: ``True`` if the 2 graphs are isomorphic ``False`` if they are
/// not.
/// :rtype: bool
#[pyfunction]
#[text_signature = "(first, second, node_matcher=None, edge_matcher=None, /)"]
fn graph_is_isomorphic(
py: Python,
first: &graph::PyGraph,
second: &graph::PyGraph,
node_matcher: Option<PyObject>,
edge_matcher: Option<PyObject>,
) -> PyResult<bool> {
let compare_nodes = node_matcher.map(|f| {
move |a: &PyObject, b: &PyObject| -> PyResult<bool> {
let res = f.call1(py, (a, b))?;
Ok(res.is_true(py).unwrap())
}
});
let compare_edges = edge_matcher.map(|f| {
move |a: &PyObject, b: &PyObject| -> PyResult<bool> {
let res = f.call1(py, (a, b))?;
Ok(res.is_true(py).unwrap())
}
});
let res = isomorphism::is_isomorphic(
py,
&first.graph,
&second.graph,
compare_nodes,
compare_edges,
)?;
Ok(res)
}
/// Return the topological sort of node indexes from the provided graph
///
/// :param PyDiGraph graph: The DAG to get the topological sort on
///
/// :returns: A list of node indices topologically sorted.
/// :rtype: NodeIndices
///
/// :raises DAGHasCycle: if a cycle is encountered while sorting the graph
#[pyfunction]
#[text_signature = "(graph, /)"]
fn topological_sort(graph: &digraph::PyDiGraph) -> PyResult<NodeIndices> {
let nodes = match algo::toposort(graph, None) {
Ok(nodes) => nodes,
Err(_err) => {
return Err(DAGHasCycle::new_err("Sort encountered a cycle"))
}
};
Ok(NodeIndices {
nodes: nodes.iter().map(|node| node.index()).collect(),
})
}
fn dfs_edges<G>(
graph: G,
source: Option<usize>,
edge_count: usize,
) -> Vec<(usize, usize)>
where
G: GraphBase<NodeId = NodeIndex>
+ IntoNodeIdentifiers
+ NodeIndexable
+ IntoNeighbors
+ NodeCount
+ Visitable,
<G as Visitable>::Map: VisitMap<NodeIndex>,
{
let nodes: Vec<NodeIndex> = match source {
Some(start) => vec![NodeIndex::new(start)],
None => graph
.node_identifiers()
.map(|ind| NodeIndex::new(graph.to_index(ind)))
.collect(),
};
let node_count = graph.node_count();
let mut visited: HashSet<NodeIndex> = HashSet::with_capacity(node_count);
let mut out_vec: Vec<(usize, usize)> = Vec::with_capacity(edge_count);
for start in nodes {
if visited.contains(&start) {
continue;
}
visited.insert(start);
let mut children: Vec<NodeIndex> = graph.neighbors(start).collect();
children.reverse();
let mut stack: Vec<(NodeIndex, Vec<NodeIndex>)> =
vec![(start, children)];
// Used to track the last position in children vec across iterations
let mut index_map: HashMap<NodeIndex, usize> =
HashMap::with_capacity(node_count);
index_map.insert(start, 0);
while !stack.is_empty() {
let temp_parent = stack.last().unwrap();
let parent = temp_parent.0;
let children = temp_parent.1.clone();
let count = *index_map.get(&parent).unwrap();
let mut found = false;
let mut index = count;
for child in &children[index..] {
index += 1;
if !visited.contains(&child) {
out_vec.push((parent.index(), child.index()));
visited.insert(*child);
let mut grandchildren: Vec<NodeIndex> =
graph.neighbors(*child).collect();
grandchildren.reverse();
stack.push((*child, grandchildren));
index_map.insert(*child, 0);
*index_map.get_mut(&parent).unwrap() = index;
found = true;
break;
}
}
if !found || children.is_empty() {
stack.pop();
}
}
}
out_vec
}
/// Get edge list in depth first order
///
/// :param PyDiGraph graph: The graph to get the DFS edge list from
/// :param int source: An optional node index to use as the starting node
/// for the depth-first search. The edge list will only return edges in
/// the components reachable from this index. If this is not specified
/// then a source will be chosen arbitrarly and repeated until all
/// components of the graph are searched.
///
/// :returns: A list of edges as a tuple of the form ``(source, target)`` in
/// depth-first order
/// :rtype: EdgeList
#[pyfunction]
#[text_signature = "(graph, /, source=None)"]
fn digraph_dfs_edges(
graph: &digraph::PyDiGraph,
source: Option<usize>,
) -> EdgeList {
EdgeList {
edges: dfs_edges(graph, source, graph.graph.edge_count()),
}
}
/// Get edge list in depth first order
///
/// :param PyGraph graph: The graph to get the DFS edge list from
/// :param int source: An optional node index to use as the starting node
/// for the depth-first search. The edge list will only return edges in
/// the components reachable from this index. If this is not specified
/// then a source will be chosen arbitrarly and repeated until all
/// components of the graph are searched.
///
/// :returns: A list of edges as a tuple of the form ``(source, target)`` in
/// depth-first order
/// :rtype: EdgeList
#[pyfunction]
#[text_signature = "(graph, /, source=None)"]
fn graph_dfs_edges(graph: &graph::PyGraph, source: Option<usize>) -> EdgeList {
EdgeList {
edges: dfs_edges(graph, source, graph.graph.edge_count()),
}
}
/// Return successors in a breadth-first-search from a source node.
///
/// The return format is ``[(Parent Node, [Children Nodes])]`` in a bfs order
/// from the source node provided.
///
/// :param PyDiGraph graph: The DAG to get the bfs_successors from
/// :param int node: The index of the dag node to get the bfs successors for
///
/// :returns: A list of nodes's data and their children in bfs order. The
/// BFSSuccessors class that is returned is a custom container class that
/// implements the sequence protocol. This can be used as a python list
/// with index based access.
/// :rtype: BFSSuccessors
#[pyfunction]
#[text_signature = "(graph, node, /)"]
fn bfs_successors(
py: Python,
graph: &digraph::PyDiGraph,
node: usize,
) -> iterators::BFSSuccessors {
let index = NodeIndex::new(node);
let mut bfs = Bfs::new(graph, index);
let mut out_list: Vec<(PyObject, Vec<PyObject>)> =
Vec::with_capacity(graph.node_count());
while let Some(nx) = bfs.next(graph) {
let children = graph
.graph
.neighbors_directed(nx, petgraph::Direction::Outgoing);
let mut succesors: Vec<PyObject> = Vec::new();
for succ in children {
succesors
.push(graph.graph.node_weight(succ).unwrap().clone_ref(py));
}
if !succesors.is_empty() {
out_list.push((
graph.graph.node_weight(nx).unwrap().clone_ref(py),
succesors,
));
}
}
iterators::BFSSuccessors {
bfs_successors: out_list,
}
}
/// Return the ancestors of a node in a graph.
///
/// This differs from :meth:`PyDiGraph.predecessors` method in that
/// ``predecessors`` returns only nodes with a direct edge into the provided
/// node. While this function returns all nodes that have a path into the
/// provided node.
///
/// :param PyDiGraph graph: The graph to get the descendants from
/// :param int node: The index of the graph node to get the ancestors for
///
/// :returns: A list of node indexes of ancestors of provided node.
/// :rtype: list
#[pyfunction]
#[text_signature = "(graph, node, /)"]
fn ancestors(graph: &digraph::PyDiGraph, node: usize) -> HashSet<usize> {
let index = NodeIndex::new(node);
let mut out_set: HashSet<usize> = HashSet::new();
let reverse_graph = Reversed(graph);
let res = algo::dijkstra(reverse_graph, index, None, |_| 1);
for n in res.keys() {
let n_int = n.index();
out_set.insert(n_int);
}
out_set.remove(&node);
out_set
}
/// Return the descendants of a node in a graph.
///
/// This differs from :meth:`PyDiGraph.successors` method in that
/// ``successors``` returns only nodes with a direct edge out of the provided
/// node. While this function returns all nodes that have a path from the
/// provided node.
///
/// :param PyDiGraph graph: The graph to get the descendants from
/// :param int node: The index of the graph node to get the descendants for
///
/// :returns: A list of node indexes of descendants of provided node.
/// :rtype: list
#[pyfunction]
#[text_signature = "(graph, node, /)"]
fn descendants(graph: &digraph::PyDiGraph, node: usize) -> HashSet<usize> {
let index = NodeIndex::new(node);
let mut out_set: HashSet<usize> = HashSet::new();
let res = algo::dijkstra(graph, index, None, |_| 1);
for n in res.keys() {
let n_int = n.index();
out_set.insert(n_int);
}
out_set.remove(&node);
out_set
}
/// Get the lexicographical topological sorted nodes from the provided DAG
///
/// This function returns a list of nodes data in a graph lexicographically
/// topologically sorted using the provided key function.
///
/// :param PyDiGraph dag: The DAG to get the topological sorted nodes from
/// :param callable key: key is a python function or other callable that
/// gets passed a single argument the node data from the graph and is
/// expected to return a string which will be used for sorting.
///
/// :returns: A list of node's data lexicographically topologically sorted.
/// :rtype: list
#[pyfunction]
#[text_signature = "(dag, key, /)"]
fn lexicographical_topological_sort(
py: Python,
dag: &digraph::PyDiGraph,
key: PyObject,
) -> PyResult<PyObject> {
let key_callable = |a: &PyObject| -> PyResult<PyObject> {
let res = key.call1(py, (a,))?;
Ok(res.to_object(py))
};
// HashMap of node_index indegree
let node_count = dag.node_count();
let mut in_degree_map: HashMap<NodeIndex, usize> =
HashMap::with_capacity(node_count);
for node in dag.graph.node_indices() {
in_degree_map.insert(node, dag.in_degree(node.index()));
}
#[derive(Clone, Eq, PartialEq)]
struct State {
key: String,
node: NodeIndex,
}
impl Ord for State {
fn cmp(&self, other: &State) -> Ordering {
// Notice that the we flip the ordering on costs.
// In case of a tie we compare positions - this step is necessary
// to make implementations of `PartialEq` and `Ord` consistent.
other
.key
.cmp(&self.key)
.then_with(|| other.node.index().cmp(&self.node.index()))
}
}
// `PartialOrd` needs to be implemented as well.
impl PartialOrd for State {
fn partial_cmp(&self, other: &State) -> Option<Ordering> {
Some(self.cmp(other))
}
}
let mut zero_indegree = BinaryHeap::with_capacity(node_count);
for (node, degree) in in_degree_map.iter() {
if *degree == 0 {
let map_key_raw = key_callable(&dag.graph[*node])?;
let map_key: String = map_key_raw.extract(py)?;
zero_indegree.push(State {
key: map_key,
node: *node,
});
}
}
let mut out_list: Vec<&PyObject> = Vec::with_capacity(node_count);
let dir = petgraph::Direction::Outgoing;
while let Some(State { node, .. }) = zero_indegree.pop() {
let neighbors = dag.graph.neighbors_directed(node, dir);
for child in neighbors {
let child_degree = in_degree_map.get_mut(&child).unwrap();
*child_degree -= 1;
if *child_degree == 0 {
let map_key_raw = key_callable(&dag.graph[child])?;
let map_key: String = map_key_raw.extract(py)?;
zero_indegree.push(State {
key: map_key,
node: child,
});
in_degree_map.remove(&child);
}
}
out_list.push(&dag.graph[node])
}
Ok(PyList::new(py, out_list).into())
}
/// Color a PyGraph using a largest_first strategy greedy graph coloring.
///
/// :param PyGraph: The input PyGraph object to color
///
/// :returns: A dictionary where keys are node indices and the value is
/// the color
/// :rtype: dict
#[pyfunction]
#[text_signature = "(graph, /)"]
fn graph_greedy_color(
py: Python,
graph: &graph::PyGraph,
) -> PyResult<PyObject> {
let mut colors: HashMap<usize, usize> = HashMap::new();
let mut node_vec: Vec<NodeIndex> = graph.graph.node_indices().collect();
let mut sort_map: HashMap<NodeIndex, usize> =
HashMap::with_capacity(graph.node_count());
for k in node_vec.iter() {
sort_map.insert(*k, graph.graph.edges(*k).count());
}
node_vec.par_sort_by_key(|k| Reverse(sort_map.get(k)));
for u_index in node_vec {
let mut neighbor_colors: HashSet<usize> = HashSet::new();
for edge in graph.graph.edges(u_index) {
let target = edge.target().index();
let existing_color = match colors.get(&target) {
Some(node) => node,
None => continue,
};
neighbor_colors.insert(*existing_color);
}
let mut count: usize = 0;
loop {
if !neighbor_colors.contains(&count) {
break;
}
count += 1;
}
colors.insert(u_index.index(), count);
}
let out_dict = PyDict::new(py);
for (index, color) in colors {
out_dict.set_item(index, color)?;
}
Ok(out_dict.into())
}
/// Compute the length of the kth shortest path
///
/// Computes the lengths of the kth shortest path from ``start`` to every
/// reachable node.
///
/// Computes in :math:`O(k * (|E| + |V|*log(|V|)))` time (average).
///
/// :param PyGraph graph: The graph to find the shortest paths in
/// :param int start: The node index to find the shortest paths from
/// :param int k: The kth shortest path to find the lengths of
/// :param edge_cost: A python callable that will receive an edge payload and
/// return a float for the cost of that eedge
/// :param int goal: An optional goal node index, if specified the output
/// dictionary
///
/// :returns: A dict of lengths where the key is the destination node index and
/// the value is the length of the path.
/// :rtype: dict
#[pyfunction]
#[text_signature = "(graph, start, k, edge_cost, /, goal=None)"]
fn digraph_k_shortest_path_lengths(
py: Python,
graph: &digraph::PyDiGraph,
start: usize,
k: usize,
edge_cost: PyObject,
goal: Option<usize>,
) -> PyResult<PyObject> {
let out_goal = goal.map(NodeIndex::new);
let edge_cost_callable = |edge: &PyObject| -> PyResult<f64> {
let res = edge_cost.call1(py, (edge,))?;
res.extract(py)
};
let out_map = k_shortest_path::k_shortest_path(
graph,
NodeIndex::new(start),
out_goal,
k,
edge_cost_callable,
)?;
let out_dict = PyDict::new(py);
for (index, length) in out_map {
if (out_goal.is_some() && out_goal.unwrap() == index)
|| out_goal.is_none()
{
out_dict.set_item(index.index(), length)?;
}
}
Ok(out_dict.into())
}
/// Compute the length of the kth shortest path
///
/// Computes the lengths of the kth shortest path from ``start`` to every
/// reachable node.
///
/// Computes in :math:`O(k * (|E| + |V|*log(|V|)))` time (average).
///
/// :param PyGraph graph: The graph to find the shortest paths in
/// :param int start: The node index to find the shortest paths from
/// :param int k: The kth shortest path to find the lengths of
/// :param edge_cost: A python callable that will receive an edge payload and
/// return a float for the cost of that eedge
/// :param int goal: An optional goal node index, if specified the output
/// dictionary
///
/// :returns: A dict of lengths where the key is the destination node index and
/// the value is the length of the path.
/// :rtype: dict
#[pyfunction]
#[text_signature = "(graph, start, k, edge_cost, /, goal=None)"]
fn graph_k_shortest_path_lengths(
py: Python,
graph: &graph::PyGraph,
start: usize,
k: usize,
edge_cost: PyObject,
goal: Option<usize>,
) -> PyResult<PyObject> {
let out_goal = goal.map(NodeIndex::new);
let edge_cost_callable = |edge: &PyObject| -> PyResult<f64> {
let res = edge_cost.call1(py, (edge,))?;
res.extract(py)
};
let out_map = k_shortest_path::k_shortest_path(
graph,
NodeIndex::new(start),
out_goal,
k,
edge_cost_callable,
)?;
let out_dict = PyDict::new(py);
for (index, length) in out_map {
if (out_goal.is_some() && out_goal.unwrap() == index)
|| out_goal.is_none()
{
out_dict.set_item(index.index(), length)?;
}
}
Ok(out_dict.into())
}
/// Return the shortest path lengths between ever pair of nodes that has a
/// path connecting them
///
/// The runtime is :math:`O(|N|^3 + |E|)` where :math:`|N|` is the number
/// of nodes and :math:`|E|` is the number of edges.
///
/// This is done with the Floyd Warshall algorithm:
///
/// 1. Process all edges by setting the distance from the parent to
/// the child equal to the edge weight.
/// 2. Iterate through every pair of nodes (source, target) and an additional
/// itermediary node (w). If the distance from source :math:`\rightarrow` w
/// :math:`\rightarrow` target is less than the distance from source
/// :math:`\rightarrow` target, update the source :math:`\rightarrow` target
/// distance (to pass through w).
///
/// The return format is ``{Source Node: {Target Node: Distance}}``.
///
/// .. note::
///
/// Paths that do not exist are simply not found in the return dictionary,
/// rather than setting the distance to infinity, or -1.
///
/// .. note::
///
/// Edge weights are restricted to 1 in the current implementation.
///
/// :param PyDigraph graph: The DiGraph to get all shortest paths from
///
/// :returns: A dictionary of shortest paths
/// :rtype: dict
#[pyfunction]
#[text_signature = "(dag, /)"]
fn floyd_warshall(py: Python, dag: &digraph::PyDiGraph) -> PyResult<PyObject> {
let mut dist: HashMap<(usize, usize), usize> =
HashMap::with_capacity(dag.node_count());
for node in dag.graph.node_indices() {
// Distance from a node to itself is zero
dist.insert((node.index(), node.index()), 0);
}
for edge in dag.graph.edge_indices() {
// Distance between nodes that share an edge is 1
let source_target = dag.graph.edge_endpoints(edge).unwrap();
let u = source_target.0.index();
let v = source_target.1.index();
// Update dist only if the key hasn't been set to 0 already
// (i.e. in case edge is a self edge). Assumes edge weight = 1.
dist.entry((u, v)).or_insert(1);
}
// The shortest distance between any pair of nodes u, v is the min of the
// distance tracked so far from u->v and the distance from u to v thorough
// another node w, for any w.
for w in dag.graph.node_indices() {
for u in dag.graph.node_indices() {
for v in dag.graph.node_indices() {
let u_v_dist = match dist.get(&(u.index(), v.index())) {
Some(u_v_dist) => *u_v_dist,
None => std::usize::MAX,
};
let u_w_dist = match dist.get(&(u.index(), w.index())) {
Some(u_w_dist) => *u_w_dist,
None => std::usize::MAX,
};
let w_v_dist = match dist.get(&(w.index(), v.index())) {
Some(w_v_dist) => *w_v_dist,
None => std::usize::MAX,
};
if u_w_dist == std::usize::MAX || w_v_dist == std::usize::MAX {
// Avoid overflow!
continue;
}
if u_v_dist > u_w_dist + w_v_dist {
dist.insert((u.index(), v.index()), u_w_dist + w_v_dist);
}
}
}
}
// Some re-formatting for Python: Dict[int, Dict[int, int]]
let out_dict = PyDict::new(py);
for (nodes, distance) in dist {
let u_index = nodes.0;
let v_index = nodes.1;
if out_dict.contains(u_index)? {
let u_dict =
out_dict.get_item(u_index).unwrap().downcast::<PyDict>()?;
u_dict.set_item(v_index, distance)?;
out_dict.set_item(u_index, u_dict)?;
} else {
let u_dict = PyDict::new(py);
u_dict.set_item(v_index, distance)?;
out_dict.set_item(u_index, u_dict)?;
}
}
Ok(out_dict.into())
}
fn get_edge_iter_with_weights<G>(
graph: G,
) -> impl Iterator<Item = (usize, usize, PyObject)>
where
G: GraphBase
+ IntoEdgeReferences
+ IntoNodeIdentifiers
+ NodeIndexable
+ NodeCount
+ GraphProp
+ NodesRemoved,
G: Data<NodeWeight = PyObject, EdgeWeight = PyObject>,
{
let node_map: Option<HashMap<NodeIndex, usize>>;
if graph.nodes_removed() {
let mut node_hash_map: HashMap<NodeIndex, usize> =
HashMap::with_capacity(graph.node_count());
for (count, node) in graph.node_identifiers().enumerate() {
let index = NodeIndex::new(graph.to_index(node));
node_hash_map.insert(index, count);
}
node_map = Some(node_hash_map);
} else {
node_map = None;
}
graph.edge_references().map(move |edge| {
let i: usize;
let j: usize;
match &node_map {
Some(map) => {
let source_index =