|
| 1 | +// Licensed under the Apache License, Version 2.0 (the "License"); you may |
| 2 | +// not use this file except in compliance with the License. You may obtain |
| 3 | +// a copy of the License at |
| 4 | +// |
| 5 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 6 | +// |
| 7 | +// Unless required by applicable law or agreed to in writing, software |
| 8 | +// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT |
| 9 | +// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the |
| 10 | +// License for the specific language governing permissions and limitations |
| 11 | +// under the License. |
| 12 | + |
| 13 | +use std::hash::Hash; |
| 14 | + |
| 15 | +use hashbrown::HashMap; |
| 16 | + |
| 17 | +use fixedbitset::FixedBitSet; |
| 18 | +use ndarray::prelude::*; |
| 19 | +use petgraph::visit::{ |
| 20 | + GraphProp, IntoNeighborsDirected, IntoNodeIdentifiers, NodeCount, NodeIndexable, |
| 21 | +}; |
| 22 | +use petgraph::{Incoming, Outgoing}; |
| 23 | +use rayon::prelude::*; |
| 24 | + |
| 25 | +/// Get the distance matrix for a graph |
| 26 | +/// |
| 27 | +/// The generated distance matrix assumes the edge weight for all edges is |
| 28 | +/// 1.0 and returns a matrix. |
| 29 | +/// |
| 30 | +/// This function is also multithreaded and will run in parallel if the number |
| 31 | +/// of nodes in the graph is above the value of `parallel_threshold`. If the function |
| 32 | +/// will be running in parallel the env var |
| 33 | +/// `RAYON_NUM_THREADS` can be used to adjust how many threads will be used. |
| 34 | +/// |
| 35 | +/// # Arguments: |
| 36 | +/// |
| 37 | +/// * graph - The graph object to compute the distance matrix for. |
| 38 | +/// * parallel_threshold - The threshold in number of nodes to run this function in parallel. |
| 39 | +/// If `graph` has fewer nodes than this the algorithm will run serially. A good default |
| 40 | +/// to use for this is 300. |
| 41 | +/// * as_undirected - If the input graph is directed and this is set to true the output |
| 42 | +/// matrix generated |
| 43 | +/// * null_value - The value to use for the absence of a path in the graph. |
| 44 | +/// |
| 45 | +/// # Returns |
| 46 | +/// |
| 47 | +/// A 2d ndarray [`Array`] of the distance matrix |
| 48 | +/// |
| 49 | +/// # Example |
| 50 | +/// |
| 51 | +/// ```rust |
| 52 | +/// use rustworkx_core::petgraph; |
| 53 | +/// use rustworkx_core::shortest_path::distance_matrix; |
| 54 | +/// use ndarray::{array, Array2}; |
| 55 | +/// |
| 56 | +/// let graph = petgraph::graph::UnGraph::<(), ()>::from_edges(&[ |
| 57 | +/// (0, 1), (0, 6), (1, 2), (2, 3), (3, 4), (4, 5), (5, 6) |
| 58 | +/// ]); |
| 59 | +/// let distance_matrix = distance_matrix(&graph, 300, false, 0.); |
| 60 | +/// let expected: Array2<f64> = array![ |
| 61 | +/// [0.0, 1.0, 2.0, 3.0, 3.0, 2.0, 1.0], |
| 62 | +/// [1.0, 0.0, 1.0, 2.0, 3.0, 3.0, 2.0], |
| 63 | +/// [2.0, 1.0, 0.0, 1.0, 2.0, 3.0, 3.0], |
| 64 | +/// [3.0, 2.0, 1.0, 0.0, 1.0, 2.0, 3.0], |
| 65 | +/// [3.0, 3.0, 2.0, 1.0, 0.0, 1.0, 2.0], |
| 66 | +/// [2.0, 3.0, 3.0, 2.0, 1.0, 0.0, 1.0], |
| 67 | +/// [1.0, 2.0, 3.0, 3.0, 2.0, 1.0, 0.0], |
| 68 | +/// ]; |
| 69 | +/// assert_eq!(distance_matrix, expected) |
| 70 | +/// ``` |
| 71 | +pub fn distance_matrix<G>( |
| 72 | + graph: G, |
| 73 | + parallel_threshold: usize, |
| 74 | + as_undirected: bool, |
| 75 | + null_value: f64, |
| 76 | +) -> Array2<f64> |
| 77 | +where |
| 78 | + G: Sync + IntoNeighborsDirected + NodeCount + NodeIndexable + IntoNodeIdentifiers + GraphProp, |
| 79 | + G::NodeId: Hash + Eq + Sync, |
| 80 | +{ |
| 81 | + let n = graph.node_count(); |
| 82 | + let node_map: HashMap<G::NodeId, usize> = if n != graph.node_bound() { |
| 83 | + graph |
| 84 | + .node_identifiers() |
| 85 | + .enumerate() |
| 86 | + .map(|(i, v)| (v, i)) |
| 87 | + .collect() |
| 88 | + } else { |
| 89 | + HashMap::new() |
| 90 | + }; |
| 91 | + let node_map_inv: Vec<G::NodeId> = if n != graph.node_bound() { |
| 92 | + graph.node_identifiers().collect() |
| 93 | + } else { |
| 94 | + Vec::new() |
| 95 | + }; |
| 96 | + let mut node_map_fn: Box<dyn FnMut(G::NodeId) -> usize> = if n != graph.node_bound() { |
| 97 | + Box::new(|n: G::NodeId| -> usize { node_map[&n] }) |
| 98 | + } else { |
| 99 | + Box::new(|n: G::NodeId| -> usize { graph.to_index(n) }) |
| 100 | + }; |
| 101 | + let mut reverse_node_map: Box<dyn FnMut(usize) -> G::NodeId> = if n != graph.node_bound() { |
| 102 | + Box::new(|n: usize| -> G::NodeId { node_map_inv[n] }) |
| 103 | + } else { |
| 104 | + Box::new(|n: usize| -> G::NodeId { graph.from_index(n) }) |
| 105 | + }; |
| 106 | + let mut matrix = Array2::<f64>::from_elem((n, n), null_value); |
| 107 | + let neighbors = if as_undirected { |
| 108 | + (0..n) |
| 109 | + .map(|index| { |
| 110 | + graph |
| 111 | + .neighbors_directed(reverse_node_map(index), Incoming) |
| 112 | + .chain(graph.neighbors_directed(reverse_node_map(index), Outgoing)) |
| 113 | + .map(&mut node_map_fn) |
| 114 | + .collect::<FixedBitSet>() |
| 115 | + }) |
| 116 | + .collect::<Vec<_>>() |
| 117 | + } else { |
| 118 | + (0..n) |
| 119 | + .map(|index| { |
| 120 | + graph |
| 121 | + .neighbors(reverse_node_map(index)) |
| 122 | + .map(&mut node_map_fn) |
| 123 | + .collect::<FixedBitSet>() |
| 124 | + }) |
| 125 | + .collect::<Vec<_>>() |
| 126 | + }; |
| 127 | + let bfs_traversal = |start: usize, mut row: ArrayViewMut1<f64>| { |
| 128 | + let mut distance = 0.0; |
| 129 | + let mut seen = FixedBitSet::with_capacity(n); |
| 130 | + let mut next = FixedBitSet::with_capacity(n); |
| 131 | + let mut cur = FixedBitSet::with_capacity(n); |
| 132 | + cur.put(start); |
| 133 | + while !cur.is_clear() { |
| 134 | + next.clear(); |
| 135 | + for found in cur.ones() { |
| 136 | + row[[found]] = distance; |
| 137 | + next |= &neighbors[found]; |
| 138 | + } |
| 139 | + seen.union_with(&cur); |
| 140 | + next.difference_with(&seen); |
| 141 | + distance += 1.0; |
| 142 | + ::std::mem::swap(&mut cur, &mut next); |
| 143 | + } |
| 144 | + }; |
| 145 | + if n < parallel_threshold { |
| 146 | + matrix |
| 147 | + .axis_iter_mut(Axis(0)) |
| 148 | + .enumerate() |
| 149 | + .for_each(|(index, row)| bfs_traversal(index, row)); |
| 150 | + } else { |
| 151 | + // Parallelize by row and iterate from each row index in BFS order |
| 152 | + matrix |
| 153 | + .axis_iter_mut(Axis(0)) |
| 154 | + .into_par_iter() |
| 155 | + .enumerate() |
| 156 | + .for_each(|(index, row)| bfs_traversal(index, row)); |
| 157 | + } |
| 158 | + matrix |
| 159 | +} |
0 commit comments