forked from Qiskit/rustworkx
-
Notifications
You must be signed in to change notification settings - Fork 3
/
lib.rs
1488 lines (1427 loc) · 52.2 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.
extern crate fixedbitset;
extern crate hashbrown;
extern crate ndarray;
extern crate numpy;
extern crate petgraph;
extern crate pyo3;
extern crate rand;
extern crate rand_pcg;
extern crate rayon;
mod astar;
mod dag_isomorphism;
mod digraph;
mod dijkstra;
mod dot_utils;
mod generators;
mod graph;
use std::cmp::{Ordering, Reverse};
use std::collections::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, IntoEdgeReferences, NodeIndexable, Reversed};
use ndarray::prelude::*;
use numpy::IntoPyArray;
use rand::prelude::*;
use rand_pcg::Pcg64;
use rayon::prelude::*;
use generators::PyInit_generators;
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: list
///
/// :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<Vec<usize>> {
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)
}
/// 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 {
let cycle_detected = algo::is_cyclic_directed(graph);
!cycle_detected
}
/// Determine if 2 graphs are structurally isomorphic
///
/// This checks if 2 graphs are structurally isomorphic (it doesn't match
/// the contents of the nodes or edges on the graphs).
///
/// :param PyDiGraph first: The first graph to compare
/// :param PyDiGraph second: The second graph to compare
///
/// :returns: ``True`` if the 2 graphs are structurally isomorphic, ``False``
/// if they are not
/// :rtype: bool
#[pyfunction]
#[text_signature = "(first, second, /)"]
fn is_isomorphic(
first: &digraph::PyDiGraph,
second: &digraph::PyDiGraph,
) -> PyResult<bool> {
let res = dag_isomorphism::is_isomorphic(first, second)?;
Ok(res)
}
/// Determine if 2 DAGs are isomorphic
///
/// This checks if 2 graphs are isomorphic both structurally and also
/// comparing the node data using the provided matcher function. The matcher
/// function takes in 2 node data objects and will compare them. A simple
/// example that checks if they're just equal would be::
///
/// graph_a = retworkx.PyDAG()
/// graph_b = retworkx.PyDAG()
/// retworkx.is_isomorphic_node_match(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 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.
///
/// :returns: ``True`` if the 2 graphs are isomorphic ``False`` if they are
/// not.
/// :rtype: bool
#[pyfunction]
#[text_signature = "(first, second, matcher, /)"]
fn is_isomorphic_node_match(
py: Python,
first: &digraph::PyDiGraph,
second: &digraph::PyDiGraph,
matcher: PyObject,
) -> PyResult<bool> {
let compare_nodes = |a: &PyObject, b: &PyObject| -> PyResult<bool> {
let res = matcher.call1(py, (a, b))?;
Ok(res.is_true(py).unwrap())
};
fn compare_edges(_a: &PyObject, _b: &PyObject) -> PyResult<bool> {
Ok(true)
}
let res = dag_isomorphism::is_isomorphic_matching(
py,
first,
second,
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: list
///
/// :raises DAGHasCycle: if a cycle is encountered while sorting the graph
#[pyfunction]
#[text_signature = "(graph, /)"]
fn topological_sort(graph: &digraph::PyDiGraph) -> PyResult<Vec<usize>> {
let nodes = match algo::toposort(graph, None) {
Ok(nodes) => nodes,
Err(_err) => {
return Err(DAGHasCycle::new_err("Sort encountered a cycle"))
}
};
Ok(nodes.iter().map(|node| node.index()).collect())
}
/// 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
/// :rtype: list
#[pyfunction]
#[text_signature = "(graph, node, /)"]
fn bfs_successors(
py: Python,
graph: &digraph::PyDiGraph,
node: usize,
) -> PyResult<PyObject> {
let index = NodeIndex::new(node);
let mut bfs = Bfs::new(graph, index);
let mut out_list: Vec<(&PyObject, Vec<&PyObject>)> = Vec::new();
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());
}
if !succesors.is_empty() {
out_list.push((graph.graph.node_weight(nx).unwrap(), succesors));
}
}
Ok(PyList::new(py, out_list).into())
}
/// 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 mut in_degree_map: HashMap<NodeIndex, usize> = HashMap::new();
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::new();
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::new();
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(graph: &graph::PyGraph) -> PyResult<HashMap<usize, usize>> {
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::new();
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);
}
Ok(colors)
}
/// 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::new();
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())
}
/// Return a list of layers
///
/// A layer is a subgraph whose nodes are disjoint, i.e.,
/// a layer has depth 1. The layers are constructed using a greedy algorithm.
///
/// :param PyDiGraph graph: The DAG to get the layers from
/// :param list first_layer: A list of node ids for the first layer. This
/// will be the first layer in the output
///
/// :returns: A list of layers, each layer is a list of node data
/// :rtype: list
#[pyfunction]
#[text_signature = "(dag, first_layer, /)"]
fn layers(
py: Python,
dag: &digraph::PyDiGraph,
first_layer: Vec<usize>,
) -> PyResult<PyObject> {
let mut output: Vec<Vec<&PyObject>> = Vec::new();
// Convert usize to NodeIndex
let mut first_layer_index: Vec<NodeIndex> = Vec::new();
for index in first_layer {
first_layer_index.push(NodeIndex::new(index));
}
let mut cur_layer = first_layer_index;
let mut next_layer: Vec<NodeIndex> = Vec::new();
let mut predecessor_count: HashMap<NodeIndex, usize> = HashMap::new();
let mut layer_node_data: Vec<&PyObject> = Vec::new();
for layer_node in &cur_layer {
layer_node_data.push(&dag[*layer_node]);
}
output.push(layer_node_data);
// Iterate until there are no more
while !cur_layer.is_empty() {
for node in &cur_layer {
let children = dag
.graph
.neighbors_directed(*node, petgraph::Direction::Outgoing);
let mut used_indexes: HashSet<NodeIndex> = HashSet::new();
for succ in children {
// Skip duplicate successors
if used_indexes.contains(&succ) {
continue;
}
used_indexes.insert(succ);
let mut multiplicity: usize = 0;
let raw_edges = dag
.graph
.edges_directed(*node, petgraph::Direction::Outgoing);
for edge in raw_edges {
if edge.target() == succ {
multiplicity += 1;
}
}
predecessor_count
.entry(succ)
.and_modify(|e| *e -= multiplicity)
.or_insert(dag.in_degree(succ.index()) - multiplicity);
if *predecessor_count.get(&succ).unwrap() == 0 {
next_layer.push(succ);
predecessor_count.remove(&succ);
}
}
}
let mut layer_node_data: Vec<&PyObject> = Vec::new();
for layer_node in &next_layer {
layer_node_data.push(&dag[*layer_node]);
}
if !layer_node_data.is_empty() {
output.push(layer_node_data);
}
cur_layer = next_layer;
next_layer = Vec::new();
}
Ok(PyList::new(py, output).into())
}
/// Return the adjacency matrix for a PyDiGraph object
///
/// In the case where there are multiple edges between nodes the value in the
/// output matrix will be the sum of the edges' weights.
///
/// :param PyDiGraph graph: The DiGraph used to generate the adjacency matrix
/// from
/// :param weight_fn callable: A callable object (function, lambda, etc) which
/// will be passed the edge object and expected to return a ``float``. This
/// tells retworkx/rust how to extract a numerical weight as a ``float``
/// for edge object. Some simple examples are::
///
/// dag_adjacency_matrix(dag, weight_fn: lambda x: 1)
///
/// to return a weight of 1 for all edges. Also::
///
/// dag_adjacency_matrix(dag, weight_fn: lambda x: float(x))
///
/// to cast the edge object as a float as the weight.
///
/// :return: The adjacency matrix for the input dag as a numpy array
/// :rtype: numpy.ndarray
#[pyfunction]
#[text_signature = "(graph, weight_fn, /)"]
fn digraph_adjacency_matrix(
py: Python,
graph: &digraph::PyDiGraph,
weight_fn: PyObject,
) -> PyResult<PyObject> {
let node_map: Option<HashMap<NodeIndex, usize>>;
let n: usize;
if graph.node_removed {
let mut node_hash_map: HashMap<NodeIndex, usize> = HashMap::new();
let mut count = 0;
for node in graph.graph.node_indices() {
node_hash_map.insert(node, count);
count += 1;
}
n = count;
node_map = Some(node_hash_map);
} else {
n = graph.graph.node_bound();
node_map = None;
}
let mut matrix = Array::<f64, _>::zeros((n, n).f());
let weight_callable = |a: &PyObject| -> PyResult<PyObject> {
let res = weight_fn.call1(py, (a,))?;
Ok(res.to_object(py))
};
for edge in graph.graph.edge_references() {
let edge_weight_raw = weight_callable(&edge.weight())?;
let edge_weight: f64 = edge_weight_raw.extract(py)?;
let source = edge.source();
let target = edge.target();
let i: usize;
let j: usize;
match &node_map {
Some(map) => {
i = *map.get(&source).unwrap();
j = *map.get(&target).unwrap();
}
None => {
i = source.index();
j = target.index();
}
}
matrix[[i, j]] += edge_weight;
}
Ok(matrix.into_pyarray(py).into())
}
/// Return the adjacency matrix for a PyGraph class
///
/// In the case where there are multiple edges between nodes the value in the
/// output matrix will be the sum of the edges' weights.
///
/// :param PyGraph graph: The graph used to generate the adjacency matrix from
/// :param weight_fn callable: A callable object (function, lambda, etc) which
/// will be passed the edge object and expected to return a ``float``. This
/// tells retworkx/rust how to extract a numerical weight as a ``float``
/// for edge object. Some simple examples are::
///
/// graph_adjacency_matrix(graph, weight_fn: lambda x: 1)
///
/// to return a weight of 1 for all edges. Also::
///
/// graph_adjacency_matrix(graph, weight_fn: lambda x: float(x))
///
/// to cast the edge object as a float as the weight.
///
/// :return: The adjacency matrix for the input dag as a numpy array
/// :rtype: numpy.ndarray
#[pyfunction]
#[text_signature = "(graph, weight_fn, /)"]
fn graph_adjacency_matrix(
py: Python,
graph: &graph::PyGraph,
weight_fn: PyObject,
) -> PyResult<PyObject> {
let node_map: Option<HashMap<NodeIndex, usize>>;
let n: usize;
if graph.node_removed {
let mut node_hash_map: HashMap<NodeIndex, usize> = HashMap::new();
let mut count = 0;
for node in graph.graph.node_indices() {
node_hash_map.insert(node, count);
count += 1;
}
n = count;
node_map = Some(node_hash_map);
} else {
n = graph.graph.node_bound();
node_map = None;
}
let mut matrix = Array::<f64, _>::zeros((n, n).f());
let weight_callable = |a: &PyObject| -> PyResult<PyObject> {
let res = weight_fn.call1(py, (a,))?;
Ok(res.to_object(py))
};
for edge in graph.graph.edge_references() {
let edge_weight_raw = weight_callable(&edge.weight())?;
let edge_weight: f64 = edge_weight_raw.extract(py)?;
let source = edge.source();
let target = edge.target();
let i: usize;
let j: usize;
match &node_map {
Some(map) => {
i = *map.get(&source).unwrap();
j = *map.get(&target).unwrap();
}
None => {
i = source.index();
j = target.index();
}
}
matrix[[i, j]] += edge_weight;
matrix[[j, i]] += edge_weight;
}
Ok(matrix.into_pyarray(py).into())
}
/// Return all simple paths between 2 nodes in a PyGraph object
///
/// A simple path is a path with no repeated nodes.
///
/// :param PyGraph graph: The graph to find the path in
/// :param int from: The node index to find the paths from
/// :param int to: The node index to find the paths to
/// :param int min_depth: The minimum depth of the path to include in the output
/// list of paths. By default all paths are included regardless of depth,
/// setting to 0 will behave like the default.
/// :param int cutoff: The maximum depth of path to include in the output list
/// of paths. By default includes all paths regardless of depth, setting to
/// 0 will behave like default.
///
/// :returns: A list of lists where each inner list is a path of node indices
/// :rtype: list
#[pyfunction]
#[text_signature = "(graph, from, to, /, min=None, cutoff=None)"]
fn graph_all_simple_paths(
graph: &graph::PyGraph,
from: usize,
to: usize,
min_depth: Option<usize>,
cutoff: Option<usize>,
) -> PyResult<Vec<Vec<usize>>> {
let from_index = NodeIndex::new(from);
if !graph.graph.contains_node(from_index) {
return Err(InvalidNode::new_err(
"The input index for 'from' is not a valid node index",
));
}
let to_index = NodeIndex::new(to);
if !graph.graph.contains_node(to_index) {
return Err(InvalidNode::new_err(
"The input index for 'to' is not a valid node index",
));
}
let min_intermediate_nodes: usize = match min_depth {
Some(depth) => depth - 2,
None => 0,
};
let cutoff_petgraph: Option<usize> = match cutoff {
Some(depth) => Some(depth - 2),
None => None,
};
let result: Vec<Vec<usize>> = algo::all_simple_paths(
graph,
from_index,
to_index,
min_intermediate_nodes,
cutoff_petgraph,
)
.map(|v: Vec<NodeIndex>| v.into_iter().map(|i| i.index()).collect())
.collect();
Ok(result)
}
/// Return all simple paths between 2 nodes in a PyDiGraph object
///
/// A simple path is a path with no repeated nodes.
///
/// :param PyDiGraph graph: The graph to find the path in
/// :param int from: The node index to find the paths from
/// :param int to: The node index to find the paths to
/// :param int min_depth: The minimum depth of the path to include in the output
/// list of paths. By default all paths are included regardless of depth,
/// sett to 0 will behave like the default.
/// :param int cutoff: The maximum depth of path to include in the output list
/// of paths. By default includes all paths regardless of depth, setting to
/// 0 will behave like default.
///
/// :returns: A list of lists where each inner list is a path
/// :rtype: list
#[pyfunction]
#[text_signature = "(graph, from, to, /, min_depth=None, cutoff=None)"]
fn digraph_all_simple_paths(
graph: &digraph::PyDiGraph,
from: usize,
to: usize,
min_depth: Option<usize>,
cutoff: Option<usize>,
) -> PyResult<Vec<Vec<usize>>> {
let from_index = NodeIndex::new(from);
if !graph.graph.contains_node(from_index) {
return Err(InvalidNode::new_err(
"The input index for 'from' is not a valid node index",
));
}
let to_index = NodeIndex::new(to);
if !graph.graph.contains_node(to_index) {
return Err(InvalidNode::new_err(
"The input index for 'to' is not a valid node index",
));
}
let min_intermediate_nodes: usize = match min_depth {
Some(depth) => depth - 2,
None => 0,
};
let cutoff_petgraph: Option<usize> = match cutoff {
Some(depth) => Some(depth - 2),
None => None,
};
let result: Vec<Vec<usize>> = algo::all_simple_paths(
graph,
from_index,
to_index,
min_intermediate_nodes,
cutoff_petgraph,
)
.map(|v: Vec<NodeIndex>| v.into_iter().map(|i| i.index()).collect())
.collect();
Ok(result)
}
/// Compute the lengths of the shortest paths for a PyGraph object using
/// Dijkstra's algorithm
///
/// :param PyGraph graph: The input graph to use
/// :param int node: The node index to use as the source for finding the
/// shortest paths from
/// :param edge_cost_fn: A python callable that will take in 1 parameter, an
/// edge's data object and will return a float that represents the
/// cost/weight of that edge. It must be non-negative
/// :param int goal: An optional node index to use as the end of the path.
/// When specified the traversal will stop when the goal is reached and
/// the output dictionary will only have a single entry with the length
/// of the shortest path to the goal node.
///
/// :returns: A dictionary of the shortest paths from the provided node where
/// the key is the node index of the end of the path and the value is the
/// cost/sum of the weights of path
/// :rtype: dict
#[pyfunction]
#[text_signature = "(graph, node, edge_cost_fn, /, goal=None)"]
fn graph_dijkstra_shortest_path_lengths(
py: Python,
graph: &graph::PyGraph,
node: usize,
edge_cost_fn: PyObject,
goal: Option<usize>,
) -> PyResult<PyObject> {
let edge_cost_callable = |a: &PyObject| -> PyResult<f64> {
let res = edge_cost_fn.call1(py, (a,))?;
let raw = res.to_object(py);
Ok(raw.extract(py)?)
};
let start = NodeIndex::new(node);
let goal_index: Option<NodeIndex> = match goal {
Some(node) => Some(NodeIndex::new(node)),
None => None,
};
let res = dijkstra::dijkstra(graph, start, goal_index, |e| {
edge_cost_callable(e.weight())
})?;
let out_dict = PyDict::new(py);
for (index, value) in res {
let int_index = index.index();
if int_index == node {
continue;
}
if (goal.is_some() && goal.unwrap() == int_index) || goal.is_none() {
out_dict.set_item(int_index, value)?;
}
}
Ok(out_dict.into())
}
/// Compute the lengths of the shortest paths for a PyDiGraph object using
/// Dijkstra's algorithm
///
/// :param PyDiGraph graph: The input graph to use
/// :param int node: The node index to use as the source for finding the
/// shortest paths from
/// :param edge_cost_fn: A python callable that will take in 1 parameter, an
/// edge's data object and will return a float that represents the
/// cost/weight of that edge. It must be non-negative
/// :param int goal: An optional node index to use as the end of the path.
/// When specified the traversal will stop when the goal is reached and
/// the output dictionary will only have a single entry with the length
/// of the shortest path to the goal node.
///
/// :returns: A dictionary of the shortest paths from the provided node where
/// the key is the node index of the end of the path and the value is the
/// cost/sum of the weights of path
/// :rtype: dict
#[pyfunction]
#[text_signature = "(graph, node, edge_cost_fn, /, goal=None)"]
fn digraph_dijkstra_shortest_path_lengths(
py: Python,
graph: &digraph::PyDiGraph,
node: usize,
edge_cost_fn: PyObject,
goal: Option<usize>,
) -> PyResult<PyObject> {
let edge_cost_callable = |a: &PyObject| -> PyResult<f64> {
let res = edge_cost_fn.call1(py, (a,))?;
let raw = res.to_object(py);
Ok(raw.extract(py)?)
};
let start = NodeIndex::new(node);
let goal_index: Option<NodeIndex> = match goal {