solverforge_maps/routing/
matrix.rs1use rayon::prelude::*;
4use std::collections::HashMap;
5use tokio::sync::mpsc::{self, Sender};
6
7use super::algo::dijkstra_with_secondary;
8use super::coord::Coord;
9use super::graph::NodeIdx;
10use super::network::{RoadNetwork, SnapAccess, SnappedCoord};
11use super::progress::RoutingProgress;
12
13pub const UNREACHABLE: i64 = i64::MAX;
14
15#[derive(Debug, Clone, Default)]
16pub struct TravelTimeMatrix {
17 data: Vec<i64>,
18 distance_data: Vec<i64>,
19 size: usize,
20 locations: Vec<SnappedCoord>,
21}
22
23impl TravelTimeMatrix {
24 pub(crate) fn new(
25 data: Vec<i64>,
26 distance_data: Vec<i64>,
27 size: usize,
28 locations: Vec<SnappedCoord>,
29 ) -> Self {
30 debug_assert_eq!(data.len(), size * size);
31 debug_assert_eq!(distance_data.len(), size * size);
32 debug_assert_eq!(locations.len(), size);
33 Self {
34 data,
35 distance_data,
36 size,
37 locations,
38 }
39 }
40
41 #[inline]
46 pub fn get(&self, from: usize, to: usize) -> Option<i64> {
47 if from < self.size && to < self.size {
48 Some(self.data[from * self.size + to])
49 } else {
50 None
51 }
52 }
53
54 #[inline]
55 pub fn is_reachable(&self, from: usize, to: usize) -> bool {
56 self.get(from, to)
57 .map(|v| v != UNREACHABLE)
58 .unwrap_or(false)
59 }
60
61 #[inline]
66 pub fn distance_meters(&self, from: usize, to: usize) -> Option<i64> {
67 if from < self.size && to < self.size {
68 Some(self.distance_data[from * self.size + to])
69 } else {
70 None
71 }
72 }
73
74 #[inline]
75 pub fn size(&self) -> usize {
76 self.size
77 }
78
79 #[inline]
80 pub fn locations(&self) -> &[SnappedCoord] {
81 &self.locations
82 }
83
84 #[inline]
85 pub fn row(&self, i: usize) -> Option<&[i64]> {
86 if i < self.size {
87 let start = i * self.size;
88 Some(&self.data[start..start + self.size])
89 } else {
90 None
91 }
92 }
93
94 #[inline]
95 pub fn row_distances(&self, i: usize) -> Option<&[i64]> {
96 if i < self.size {
97 let start = i * self.size;
98 Some(&self.distance_data[start..start + self.size])
99 } else {
100 None
101 }
102 }
103
104 pub fn min(&self) -> Option<i64> {
105 let mut min_val = None;
106 for i in 0..self.size {
107 for j in 0..self.size {
108 if i == j {
109 continue;
110 }
111 let val = self.data[i * self.size + j];
112 if val != UNREACHABLE {
113 min_val = Some(min_val.map(|m: i64| m.min(val)).unwrap_or(val));
114 }
115 }
116 }
117 min_val
118 }
119
120 pub fn max(&self) -> Option<i64> {
121 let mut max_val = None;
122 for i in 0..self.size {
123 for j in 0..self.size {
124 if i == j {
125 continue;
126 }
127 let val = self.data[i * self.size + j];
128 if val != UNREACHABLE {
129 max_val = Some(max_val.map(|m: i64| m.max(val)).unwrap_or(val));
130 }
131 }
132 }
133 max_val
134 }
135
136 pub fn mean(&self) -> Option<f64> {
137 let mut sum = 0i64;
138 let mut count = 0usize;
139 for i in 0..self.size {
140 for j in 0..self.size {
141 if i == j {
142 continue;
143 }
144 let val = self.data[i * self.size + j];
145 if val != UNREACHABLE {
146 sum = sum.saturating_add(val);
147 count += 1;
148 }
149 }
150 }
151 if count > 0 {
152 Some(sum as f64 / count as f64)
153 } else {
154 None
155 }
156 }
157
158 pub fn reachability_ratio(&self) -> f64 {
159 if self.size <= 1 {
160 return 1.0;
161 }
162 let total_pairs = self.size * (self.size - 1);
163 let reachable = self.count_reachable();
164 reachable as f64 / total_pairs as f64
165 }
166
167 fn count_reachable(&self) -> usize {
168 let mut count = 0;
169 for i in 0..self.size {
170 for j in 0..self.size {
171 if i != j && self.data[i * self.size + j] != UNREACHABLE {
172 count += 1;
173 }
174 }
175 }
176 count
177 }
178
179 pub fn unreachable_pairs(&self) -> Vec<(usize, usize)> {
180 let mut pairs = Vec::new();
181 for i in 0..self.size {
182 for j in 0..self.size {
183 if i != j && self.data[i * self.size + j] == UNREACHABLE {
184 pairs.push((i, j));
185 }
186 }
187 }
188 pairs
189 }
190
191 pub fn as_slice(&self) -> &[i64] {
192 &self.data
193 }
194
195 pub fn distances_as_slice(&self) -> &[i64] {
196 &self.distance_data
197 }
198}
199
200impl RoadNetwork {
201 pub async fn compute_matrix(
202 &self,
203 locations: &[Coord],
204 progress: Option<&Sender<RoutingProgress>>,
205 ) -> TravelTimeMatrix {
206 let node_snapped: Vec<Option<SnappedCoord>> = locations
207 .iter()
208 .map(|&coord| self.snap_to_road_detailed(coord).ok())
209 .collect();
210 self.matrix_from_snaps(locations, node_snapped, progress)
211 .await
212 }
213
214 pub async fn compute_matrix_with_access(
222 &self,
223 locations: &[Coord],
224 access: &[SnapAccess],
225 progress: Option<&Sender<RoutingProgress>>,
226 ) -> TravelTimeMatrix {
227 debug_assert_eq!(locations.len(), access.len());
228 let node_snapped: Vec<Option<SnappedCoord>> = locations
229 .iter()
230 .zip(access.iter())
231 .map(|(&coord, &access)| self.snap_road_index_with_access(coord, access).ok())
232 .collect();
233 self.matrix_from_snaps(locations, node_snapped, progress)
234 .await
235 }
236
237 async fn matrix_from_snaps(
238 &self,
239 locations: &[Coord],
240 node_snapped: Vec<Option<SnappedCoord>>,
241 progress: Option<&Sender<RoutingProgress>>,
242 ) -> TravelTimeMatrix {
243 let n = locations.len();
244 if n == 0 {
245 return TravelTimeMatrix::new(vec![], vec![], 0, vec![]);
246 }
247
248 let snapped_locations: Vec<SnappedCoord> = locations
249 .iter()
250 .zip(node_snapped.iter())
251 .map(|(&coord, edge_snap)| {
252 if let Some(snapped) = edge_snap {
253 *snapped
254 } else {
255 SnappedCoord {
256 original: coord,
257 snapped: coord,
258 snap_distance_m: f64::INFINITY,
259 node_index: NodeIdx::new(0),
260 }
261 }
262 })
263 .collect();
264
265 let row_progress = progress.map(|tx| {
266 let (progress_tx, mut progress_rx) = mpsc::unbounded_channel::<usize>();
267 let tx = tx.clone();
268 let handle = tokio::spawn(async move {
269 let mut completed_rows = 0usize;
270 while progress_rx.recv().await.is_some() {
271 completed_rows += 1;
272 let percent = 55 + ((completed_rows * 44) / n.max(1)) as u8;
273 let _ = tx
274 .send(RoutingProgress::ComputingMatrix {
275 percent,
276 row: completed_rows,
277 total: n,
278 })
279 .await;
280 }
281 });
282 (progress_tx, handle)
283 });
284
285 let graph = &self.graph;
287 let progress_tx = row_progress.as_ref().map(|(tx, _)| tx.clone());
288 let rows: Vec<(Vec<i64>, Vec<i64>)> = (0..n)
289 .into_par_iter()
290 .map(|i| {
291 let mut row = vec![0i64; n];
292 let mut distance_row = vec![0i64; n];
293
294 let Some(from) = &node_snapped[i] else {
295 for (j, cell) in row.iter_mut().enumerate() {
296 if i != j {
297 *cell = UNREACHABLE;
298 distance_row[j] = UNREACHABLE;
299 }
300 }
301 if let Some(tx) = &progress_tx {
302 let _ = tx.send(i);
303 }
304 return (row, distance_row);
305 };
306
307 let costs = dijkstra_with_secondary(
308 graph,
309 from.node_index,
310 None,
311 |e| e.travel_time_s,
312 |e| e.distance_m,
313 );
314
315 for j in 0..n {
316 if i == j {
317 continue;
318 }
319
320 let Some(to) = &node_snapped[j] else {
321 row[j] = UNREACHABLE;
322 distance_row[j] = UNREACHABLE;
323 continue;
324 };
325
326 if let Some(&(duration, distance)) = costs.get(&to.node_index) {
327 row[j] = duration.round() as i64;
328 distance_row[j] = distance.round() as i64;
329 } else {
330 row[j] = UNREACHABLE;
331 distance_row[j] = UNREACHABLE;
332 }
333 }
334
335 if let Some(tx) = &progress_tx {
336 let _ = tx.send(i);
337 }
338 (row, distance_row)
339 })
340 .collect();
341
342 if let Some((progress_tx, handle)) = row_progress {
343 drop(progress_tx);
344 let _ = handle.await;
345 }
346
347 if let Some(tx) = progress {
348 let _ = tx.send(RoutingProgress::Complete).await;
349 }
350
351 let mut data = Vec::with_capacity(n * n);
352 let mut distance_data = Vec::with_capacity(n * n);
353 for (row, distance_row) in rows {
354 data.extend(row);
355 distance_data.extend(distance_row);
356 }
357 TravelTimeMatrix::new(data, distance_data, n, snapped_locations)
358 }
359
360 pub async fn compute_geometries(
361 &self,
362 locations: &[Coord],
363 progress: Option<&Sender<RoutingProgress>>,
364 ) -> HashMap<(usize, usize), Vec<Coord>> {
365 let n = locations.len();
366 let total_pairs = n * (n - 1);
367 let mut geometries = HashMap::new();
368 let mut pair_count = 0usize;
369
370 for i in 0..n {
371 for j in 0..n {
372 if i == j {
373 continue;
374 }
375 if let Ok(result) = self.route(locations[i], locations[j]) {
376 geometries.insert((i, j), result.geometry);
377 }
378 pair_count += 1;
379
380 if let Some(tx) = progress {
381 if pair_count.is_multiple_of(10) || pair_count == total_pairs {
382 let percent = 80 + (pair_count * 15 / total_pairs.max(1)) as u8;
383 let _ = tx
384 .send(RoutingProgress::ComputingGeometries {
385 percent,
386 pair: pair_count,
387 total: total_pairs,
388 })
389 .await;
390 }
391 }
392 }
393 }
394
395 if let Some(tx) = progress {
396 let _ = tx.send(RoutingProgress::Complete).await;
397 }
398
399 geometries
400 }
401}