fastmob-core 0.2.0

Rust compute kernels for fastmob mobility analysis.
Documentation
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
//! Road/rail routing over a graph using contraction hierarchies
//! (`fast_paths`): the graph is prepared once per session, then every
//! shortest-path query is a fast bidirectional search instead of a fresh
//! Dijkstra.

use crate::utils::haversine::haversine_km;
use rayon::prelude::*;
use rustc_hash::FxHashMap;

#[derive(Clone, Copy)]
struct SpherePoint {
    xyz: [f64; 3],
    index: usize,
}

struct KdNode {
    point: SpherePoint,
    axis: usize,
    left: Option<Box<KdNode>>,
    right: Option<Box<KdNode>>,
}

fn unit_sphere(lat: f64, lng: f64) -> [f64; 3] {
    let lat = lat.to_radians();
    let lng = lng.to_radians();
    let cos_lat = lat.cos();
    [cos_lat * lng.cos(), cos_lat * lng.sin(), lat.sin()]
}

fn build_kd_tree(points: &mut [SpherePoint], depth: usize) -> Option<Box<KdNode>> {
    if points.is_empty() {
        return None;
    }
    let axis = depth % 3;
    let mid = points.len() / 2;
    points.select_nth_unstable_by(mid, |left, right| {
        left.xyz[axis]
            .total_cmp(&right.xyz[axis])
            .then_with(|| left.index.cmp(&right.index))
    });
    let (left, middle_and_right) = points.split_at_mut(mid);
    let (point, right) = middle_and_right
        .split_first_mut()
        .expect("non-empty midpoint");
    Some(Box::new(KdNode {
        point: *point,
        axis,
        left: build_kd_tree(left, depth + 1),
        right: build_kd_tree(right, depth + 1),
    }))
}

fn squared_distance(left: [f64; 3], right: [f64; 3]) -> f64 {
    (left[0] - right[0]).mul_add(
        left[0] - right[0],
        (left[1] - right[1]).mul_add(
            left[1] - right[1],
            (left[2] - right[2]) * (left[2] - right[2]),
        ),
    )
}

fn nearest_kd(node: &KdNode, query: [f64; 3], best: &mut (usize, f64)) {
    let distance = squared_distance(query, node.point.xyz);
    if distance < best.1 || (distance == best.1 && node.point.index < best.0) {
        *best = (node.point.index, distance);
    }
    let delta = query[node.axis] - node.point.xyz[node.axis];
    let (near, far) = if delta <= 0.0 {
        (&node.left, &node.right)
    } else {
        (&node.right, &node.left)
    };
    if let Some(child) = near {
        nearest_kd(child, query, best);
    }
    if delta * delta <= best.1
        && let Some(child) = far
    {
        nearest_kd(child, query, best);
    }
}

pub struct RoadGraph {
    fast_graph: fast_paths::FastGraph,
    edge_weight_ds: FxHashMap<(usize, usize), i64>,
    edge_length_m: FxHashMap<(usize, usize), f64>,
    node_lat: Vec<f64>,
    node_lng: Vec<f64>,
}

/// Arrow bindings use this for standalone snapping when callers have a node
/// table but have not prepared a full routing graph yet.
pub fn batch_nearest_coordinates(
    query_lat: &[f64],
    query_lng: &[f64],
    reference_lat: &[f64],
    reference_lng: &[f64],
) -> (Vec<i64>, Vec<f64>) {
    let mut reference_points: Vec<SpherePoint> = reference_lat
        .iter()
        .zip(reference_lng.iter())
        .enumerate()
        .filter(|&(_, (&lat, &lng))| lat.is_finite() && lng.is_finite())
        .map(|(index, (&lat, &lng))| SpherePoint {
            xyz: unit_sphere(lat, lng),
            index,
        })
        .collect();
    let Some(tree) = build_kd_tree(&mut reference_points, 0) else {
        return (
            vec![-1; query_lat.len()],
            vec![f64::INFINITY; query_lat.len()],
        );
    };
    query_lat
        .par_iter()
        .zip(query_lng.par_iter())
        .map(|(&lat, &lng)| {
            if !lat.is_finite() || !lng.is_finite() {
                return (-1, f64::INFINITY);
            }
            let mut best = (usize::MAX, f64::INFINITY);
            nearest_kd(&tree, unit_sphere(lat, lng), &mut best);
            let distance_m =
                haversine_km(lat, lng, reference_lat[best.0], reference_lng[best.0]) * 1000.0;
            (best.0 as i64, distance_m)
        })
        .unzip()
}

impl RoadGraph {
    /// Builds and prepares the contraction hierarchy from directed edges.
    /// Parallel edges between the same (from, to) pair are deduped, keeping
    /// the smallest weight; self-loops are dropped (`fast_paths` disallows them).
    pub fn build(edge_from: &[usize], edge_to: &[usize], edge_weight_ds: &[usize]) -> Self {
        Self::build_with_length(edge_from, edge_to, edge_weight_ds, &[])
    }

    /// Same as `build`, but also carries each edge's physical length (metres)
    /// alongside its travel-time weight, so a caller can later ask "how far
    /// (in metres) does the time-optimal route between these two nodes run"
    /// via `batch_road_distances`, without changing which route is chosen.
    /// `edge_length_m[i]` is missing/short (e.g. `&[]`, as `build` passes) ->
    /// treated as `0.0`, which is fine since a caller that only needs
    /// shortest-path weight never reads `edge_length_m()`.
    pub fn build_with_length(
        edge_from: &[usize],
        edge_to: &[usize],
        edge_weight_ds: &[usize],
        edge_length_m: &[f64],
    ) -> Self {
        Self::build_with_length_and_coords(
            edge_from,
            edge_to,
            edge_weight_ds,
            edge_length_m,
            &[],
            &[],
        )
    }

    /// Same as `build_with_length`, but also carries each node's (lat, lng),
    /// so `batch_road_routes` can emit route geometry (waypoint coordinates)
    /// alongside the time-optimal path, not just its total distance. A node
    /// id `>= node_lat.len()` (or when `node_lat`/`node_lng` are empty, as
    /// `build`/`build_with_length` pass) has no known coordinate; `node_coord`
    /// reports `None` for it and `batch_road_routes` drops it from the
    /// emitted waypoints while still accounting for its travel-time weight.
    pub fn build_with_length_and_coords(
        edge_from: &[usize],
        edge_to: &[usize],
        edge_weight_ds: &[usize],
        edge_length_m: &[f64],
        node_lat: &[f64],
        node_lng: &[f64],
    ) -> Self {
        let mut deduped: FxHashMap<(usize, usize), (usize, f64)> =
            FxHashMap::with_capacity_and_hasher(edge_from.len(), Default::default());
        for i in 0..edge_from.len() {
            let (from, to) = (edge_from[i], edge_to[i]);
            if from == to {
                continue;
            }
            let w = edge_weight_ds[i].max(1);
            let len = edge_length_m.get(i).copied().unwrap_or(0.0);
            deduped
                .entry((from, to))
                .and_modify(|existing| {
                    if w < existing.0 {
                        *existing = (w, len);
                    }
                })
                .or_insert((w, len));
        }

        let mut input_graph = fast_paths::InputGraph::new();
        for (&(from, to), &(w, _)) in &deduped {
            input_graph.add_edge(from, to, w);
        }
        input_graph.freeze();
        let fast_graph = fast_paths::prepare(&input_graph);

        let mut edge_weight_ds =
            FxHashMap::with_capacity_and_hasher(deduped.len(), Default::default());
        let mut edge_length_m =
            FxHashMap::with_capacity_and_hasher(deduped.len(), Default::default());
        for ((from, to), (w, len)) in deduped {
            edge_weight_ds.insert((from, to), w as i64);
            edge_length_m.insert((from, to), len);
        }

        Self {
            fast_graph,
            edge_weight_ds,
            edge_length_m,
            node_lat: node_lat.to_vec(),
            node_lng: node_lng.to_vec(),
        }
    }

    pub fn new_calculator(&self) -> fast_paths::PathCalculator {
        fast_paths::create_calculator(&self.fast_graph)
    }

    /// Returns (total_weight_ds, node_path including endpoints) or `None` if
    /// `from`/`to` are in disconnected components of the graph.
    pub fn shortest_path(
        &self,
        calc: &mut fast_paths::PathCalculator,
        from: usize,
        to: usize,
    ) -> Option<(usize, Vec<usize>)> {
        let path = calc.calc_path(&self.fast_graph, from, to)?;
        Some((path.get_weight(), path.get_nodes().clone()))
    }

    pub fn edge_weight_ds(&self, from: usize, to: usize) -> i64 {
        *self.edge_weight_ds.get(&(from, to)).unwrap_or(&0)
    }

    pub fn edge_length_m(&self, from: usize, to: usize) -> f64 {
        *self.edge_length_m.get(&(from, to)).unwrap_or(&0.0)
    }

    /// Returns `(lat, lng)` for `node`, or `None` if the graph was built
    /// without coordinates (`build`/`build_with_length`) or `node` is out of
    /// range for the coordinate arrays supplied to `build_with_length_and_coords`.
    pub fn node_coord(&self, node: usize) -> Option<(f64, f64)> {
        if node < self.node_lat.len() {
            Some((self.node_lat[node], self.node_lng[node]))
        } else {
            None
        }
    }

    /// Find the nearest prepared graph node for every coordinate.  This is
    /// deliberately kept on the prepared graph so Python callers do not have
    /// to rebuild a sklearn index for every snap operation.  Queries are
    /// independent and therefore parallelised with Rayon.  The exact
    /// Haversine score is used for both selection and the returned distance.
    pub fn batch_nearest_nodes(
        &self,
        latitudes: &[f64],
        longitudes: &[f64],
    ) -> (Vec<i64>, Vec<f64>) {
        batch_nearest_coordinates(latitudes, longitudes, &self.node_lat, &self.node_lng)
    }
}

/// Batch shortest-path distance (physical length, metres) for a set of
/// (from_node, to_node) queries against one prepared contraction hierarchy.
/// The batch is split into a handful of chunks per worker thread (not one
/// chunk per query -- `PathCalculator` allocates state sized to the graph's
/// node count, so building a fresh one per query, or even per rayon
/// work-stealing split under `map_init`, dwarfed the actual per-query
/// routing cost in practice); each chunk builds exactly one `PathCalculator`
/// and reuses it for every query in that chunk. Preparing the CH itself,
/// done once in `RoadGraph::build*`, remains the expensive one-time step.
/// Negative node ids (an "unsnapped" sentinel, e.g. from
/// `snap_locations_to_graph`) and CH-disconnected pairs both report
/// `(0.0, false)`, leaving the straight-line Haversine fallback decision to
/// the caller.
pub fn batch_road_distances(
    graph: &RoadGraph,
    from_nodes: &[i64],
    to_nodes: &[i64],
) -> (Vec<f64>, Vec<bool>) {
    let threads = rayon::current_num_threads().max(1);
    // 4 chunks per thread: enough chunks to balance load across workers even
    // when per-chunk routing cost varies, without driving the per-chunk
    // PathCalculator count high enough to matter.
    let chunk_size = (from_nodes.len() / (threads * 4)).max(1);

    from_nodes
        .par_chunks(chunk_size)
        .zip(to_nodes.par_chunks(chunk_size))
        .flat_map_iter(|(from_chunk, to_chunk)| {
            let mut calc = graph.new_calculator();
            from_chunk
                .iter()
                .zip(to_chunk.iter())
                .map(move |(&from, &to)| {
                    if from < 0 || to < 0 {
                        return (0.0, false);
                    }
                    match graph.shortest_path(&mut calc, from as usize, to as usize) {
                        Some((_weight_ds, nodes)) => {
                            let d: f64 = nodes
                                .windows(2)
                                .map(|w| graph.edge_length_m(w[0], w[1]))
                                .sum();
                            (d, true)
                        }
                        None => (0.0, false),
                    }
                })
                .collect::<Vec<_>>()
        })
        .unzip()
}

/// Batch shortest-path route geometry: for each (from_node, to_node) query,
/// walks the same time-optimal node path `batch_road_distances` uses to sum
/// distance, but instead emits the path's waypoint coordinates (decimated to
/// at most `max_waypoints` via `subsample_waypoints`) and per-waypoint
/// cumulative travel-time weight. Nodes with no known coordinate (see
/// `RoadGraph::node_coord`) are dropped from the emitted waypoints but still
/// contribute their edge weight to the cumulative total, keeping later
/// waypoints' cumulative values correct.
///
/// Results are flattened across all queries: `lats`/`lngs`/`cum_weight_ds`
/// hold every query's waypoints back-to-back, and `starts[i]..ends[i]` is
/// query `i`'s slice into those flat arrays (the same flat-output +
/// user-boundary convention used elsewhere for variable-length-per-group
/// kernels). A disconnected pair or an unsnapped (negative) node id reports
/// `connected[i] == false` and an empty `starts[i]..ends[i]` slice.
type RouteBatch = (
    Vec<f64>,
    Vec<f64>,
    Vec<i64>,
    Vec<bool>,
    Vec<usize>,
    Vec<usize>,
);
type RouteQueryResult = (Vec<f64>, Vec<f64>, Vec<i64>, bool);

pub fn batch_road_routes(
    graph: &RoadGraph,
    from_nodes: &[i64],
    to_nodes: &[i64],
    max_waypoints: usize,
) -> RouteBatch {
    let threads = rayon::current_num_threads().max(1);
    let chunk_size = (from_nodes.len() / (threads * 4)).max(1);

    let per_query: Vec<RouteQueryResult> = from_nodes
        .par_chunks(chunk_size)
        .zip(to_nodes.par_chunks(chunk_size))
        .flat_map_iter(|(from_chunk, to_chunk)| {
            let mut calc = graph.new_calculator();
            from_chunk
                .iter()
                .zip(to_chunk.iter())
                .map(move |(&from, &to)| {
                    if from < 0 || to < 0 {
                        return (Vec::new(), Vec::new(), Vec::new(), false);
                    }
                    match graph.shortest_path(&mut calc, from as usize, to as usize) {
                        Some((_weight_ds, nodes)) => {
                            let mut lats_full = Vec::with_capacity(nodes.len());
                            let mut lngs_full = Vec::with_capacity(nodes.len());
                            let mut cum_full: Vec<i64> = Vec::with_capacity(nodes.len());
                            let mut cum = 0i64;
                            for (i, &node) in nodes.iter().enumerate() {
                                if i > 0 {
                                    cum += graph.edge_weight_ds(nodes[i - 1], node);
                                }
                                if let Some((lat, lng)) = graph.node_coord(node) {
                                    lats_full.push(lat);
                                    lngs_full.push(lng);
                                    cum_full.push(cum);
                                }
                            }
                            let (lat_d, lng_d, cum_d) = subsample_waypoints(
                                &lats_full,
                                &lngs_full,
                                &cum_full,
                                max_waypoints,
                            );
                            (lat_d, lng_d, cum_d, true)
                        }
                        None => (Vec::new(), Vec::new(), Vec::new(), false),
                    }
                })
                .collect::<Vec<_>>()
        })
        .collect();

    let mut out_lats = Vec::new();
    let mut out_lngs = Vec::new();
    let mut out_cum = Vec::new();
    let mut connected = Vec::with_capacity(per_query.len());
    let mut starts = Vec::with_capacity(per_query.len());
    let mut ends = Vec::with_capacity(per_query.len());
    for (lat_d, lng_d, cum_d, is_connected) in per_query {
        let start = out_lats.len();
        out_lats.extend(lat_d);
        out_lngs.extend(lng_d);
        out_cum.extend(cum_d);
        starts.push(start);
        ends.push(out_lats.len());
        connected.push(is_connected);
    }

    (out_lats, out_lngs, out_cum, connected, starts, ends)
}

/// Batch OD (origin-destination) desire-line aggregation: for each
/// (from_node, to_node, flow) triple, walks the time-optimal path and adds
/// `flow` to every edge the path crosses, so many OD pairs' flows can be
/// aggregated onto a shared road-graph edge (the Overture-native analogue of
/// stplanr's `overline`/`overline2`). Disconnected pairs and unsnapped
/// (negative) node ids contribute their flow to the returned `dropped_flow`
/// total instead of any edge. Edges are returned sorted by descending total
/// flow.
type EdgeFlowMap = FxHashMap<(usize, usize), f64>;

pub fn batch_route_edge_flows(
    graph: &RoadGraph,
    from_nodes: &[i64],
    to_nodes: &[i64],
    flows: &[f64],
) -> (Vec<usize>, Vec<usize>, Vec<f64>, f64) {
    let threads = rayon::current_num_threads().max(1);
    let chunk_size = (from_nodes.len() / (threads * 4)).max(1);

    let (edge_maps, dropped): (Vec<EdgeFlowMap>, Vec<f64>) = from_nodes
        .par_chunks(chunk_size)
        .zip(to_nodes.par_chunks(chunk_size))
        .zip(flows.par_chunks(chunk_size))
        .map(|((from_chunk, to_chunk), flow_chunk)| {
            let mut calc = graph.new_calculator();
            let mut local: FxHashMap<(usize, usize), f64> = FxHashMap::default();
            let mut local_dropped = 0.0;
            for ((&from, &to), &flow) in from_chunk
                .iter()
                .zip(to_chunk.iter())
                .zip(flow_chunk.iter())
            {
                if from < 0 || to < 0 {
                    local_dropped += flow;
                    continue;
                }
                match graph.shortest_path(&mut calc, from as usize, to as usize) {
                    Some((_weight_ds, nodes)) => {
                        for w in nodes.windows(2) {
                            *local.entry((w[0], w[1])).or_insert(0.0) += flow;
                        }
                    }
                    None => {
                        local_dropped += flow;
                    }
                }
            }
            (local, local_dropped)
        })
        .unzip();

    let mut merged: FxHashMap<(usize, usize), f64> = FxHashMap::default();
    for m in edge_maps {
        for (k, v) in m {
            *merged.entry(k).or_insert(0.0) += v;
        }
    }
    let dropped_flow: f64 = dropped.iter().sum();

    let mut entries: Vec<((usize, usize), f64)> = merged.into_iter().collect();
    entries.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal));

    let mut edge_from_out = Vec::with_capacity(entries.len());
    let mut edge_to_out = Vec::with_capacity(entries.len());
    let mut flow_out = Vec::with_capacity(entries.len());
    for ((f, t), flow) in entries {
        edge_from_out.push(f);
        edge_to_out.push(t);
        flow_out.push(flow);
    }

    (edge_from_out, edge_to_out, flow_out, dropped_flow)
}

/// Given the full node path and per-node cumulative time, subsample down to
/// at most `max_points`, always keeping the first and last point.
pub fn subsample_waypoints(
    lats: &[f64],
    lngs: &[f64],
    times: &[i64],
    max_points: usize,
) -> (Vec<f64>, Vec<f64>, Vec<i64>) {
    let n = lats.len();
    if n <= max_points || max_points < 2 {
        return (lats.to_vec(), lngs.to_vec(), times.to_vec());
    }
    let mut idxs = Vec::with_capacity(max_points);
    let step = (n - 1) as f64 / (max_points - 1) as f64;
    for i in 0..max_points {
        let idx = ((i as f64) * step).round() as usize;
        idxs.push(idx.min(n - 1));
    }
    idxs.dedup();
    (
        idxs.iter().map(|&i| lats[i]).collect(),
        idxs.iter().map(|&i| lngs[i]).collect(),
        idxs.iter().map(|&i| times[i]).collect(),
    )
}

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

    #[test]
    fn shortest_path_over_a_chain() {
        // 0 -> 1 -> 2 -> 3, plus a direct but slower 0 -> 3 edge.
        let edge_from = vec![0, 1, 2, 0];
        let edge_to = vec![1, 2, 3, 3];
        let edge_weight = vec![10, 10, 10, 100];
        let graph = RoadGraph::build(&edge_from, &edge_to, &edge_weight);
        let mut calc = graph.new_calculator();
        let (weight, nodes) = graph.shortest_path(&mut calc, 0, 3).expect("path exists");
        assert_eq!(weight, 30);
        assert_eq!(nodes, vec![0, 1, 2, 3]);
    }

    #[test]
    fn disconnected_pair_returns_none() {
        let edge_from = vec![0, 2];
        let edge_to = vec![1, 3];
        let edge_weight = vec![5, 5];
        let graph = RoadGraph::build(&edge_from, &edge_to, &edge_weight);
        let mut calc = graph.new_calculator();
        assert!(graph.shortest_path(&mut calc, 0, 3).is_none());
    }

    #[test]
    fn shortest_path_length_over_a_chain() {
        // Same topology as `shortest_path_over_a_chain`: 0 -> 1 -> 2 -> 3 is
        // faster by weight (30 vs 100) but the direct 0 -> 3 edge is shorter
        // by length (50 vs 600). Distance must be summed along the
        // time-optimal path, not looked up per query pair directly.
        let edge_from = vec![0, 1, 2, 0];
        let edge_to = vec![1, 2, 3, 3];
        let edge_weight = vec![10, 10, 10, 100];
        let edge_length = vec![100.0, 200.0, 300.0, 50.0];
        let graph = RoadGraph::build_with_length(&edge_from, &edge_to, &edge_weight, &edge_length);
        let (distances, connected) = batch_road_distances(&graph, &[0], &[3]);
        assert_eq!(connected, vec![true]);
        assert_eq!(distances, vec![600.0]);
    }

    #[test]
    fn disconnected_pair_reports_not_connected() {
        let edge_from = vec![0, 2];
        let edge_to = vec![1, 3];
        let edge_weight = vec![5, 5];
        let edge_length = vec![10.0, 10.0];
        let graph = RoadGraph::build_with_length(&edge_from, &edge_to, &edge_weight, &edge_length);
        let (distances, connected) = batch_road_distances(&graph, &[0], &[3]);
        assert_eq!(connected, vec![false]);
        assert_eq!(distances, vec![0.0]);
    }

    #[test]
    fn negative_node_id_reports_not_connected() {
        let edge_from = vec![0, 1];
        let edge_to = vec![1, 2];
        let edge_weight = vec![5, 5];
        let edge_length = vec![10.0, 10.0];
        let graph = RoadGraph::build_with_length(&edge_from, &edge_to, &edge_weight, &edge_length);
        let (distances, connected) = batch_road_distances(&graph, &[-1], &[2]);
        assert_eq!(connected, vec![false]);
        assert_eq!(distances, vec![0.0]);
    }

    #[test]
    fn batch_reuses_one_calculator_across_mixed_queries() {
        // 0 -> 1 -> 2 -> 3 chain (connected), plus an isolated 4 -> 5 edge
        // (disconnected from the chain), queried in one batch alongside a
        // negative "unsnapped" node id, to prove per-index correctness when
        // several query kinds are interleaved against one shared calculator.
        let edge_from = vec![0, 1, 2, 4];
        let edge_to = vec![1, 2, 3, 5];
        let edge_weight = vec![10, 10, 10, 10];
        let edge_length = vec![100.0, 200.0, 300.0, 400.0];
        let graph = RoadGraph::build_with_length(&edge_from, &edge_to, &edge_weight, &edge_length);
        let (distances, connected) = batch_road_distances(&graph, &[0, 0, -1, 4], &[3, 5, 2, 5]);
        assert_eq!(connected, vec![true, false, false, true]);
        assert_eq!(distances, vec![600.0, 0.0, 0.0, 400.0]);
    }

    #[test]
    fn subsample_keeps_endpoints_and_caps_length() {
        let lats: Vec<f64> = (0..20).map(|i| i as f64).collect();
        let lngs: Vec<f64> = (0..20).map(|i| i as f64).collect();
        let times: Vec<i64> = (0..20).collect();
        let (lat, lng, t) = subsample_waypoints(&lats, &lngs, &times, 5);
        assert!(lat.len() <= 5);
        assert_eq!(lat.first(), Some(&0.0));
        assert_eq!(lat.last(), Some(&19.0));
        assert_eq!(lng.first(), Some(&0.0));
        assert_eq!(t.last(), Some(&19));
    }

    #[test]
    fn batch_routes_returns_full_chain_geometry_under_cap() {
        let edge_from = vec![0, 1, 2];
        let edge_to = vec![1, 2, 3];
        let edge_weight = vec![10, 10, 10];
        let edge_length = vec![100.0, 100.0, 100.0];
        let node_lat = vec![0.0, 1.0, 2.0, 3.0];
        let node_lng = vec![0.0, 1.0, 2.0, 3.0];
        let graph = RoadGraph::build_with_length_and_coords(
            &edge_from,
            &edge_to,
            &edge_weight,
            &edge_length,
            &node_lat,
            &node_lng,
        );
        let (lats, lngs, cum, connected, starts, ends) = batch_road_routes(&graph, &[0], &[3], 10);
        assert_eq!(connected, vec![true]);
        assert_eq!(starts, vec![0]);
        assert_eq!(ends, vec![4]);
        assert_eq!(lats, vec![0.0, 1.0, 2.0, 3.0]);
        assert_eq!(lngs, vec![0.0, 1.0, 2.0, 3.0]);
        assert_eq!(cum, vec![0, 10, 20, 30]);
    }

    #[test]
    fn batch_routes_decimates_a_long_chain() {
        let n = 20;
        let edge_from: Vec<usize> = (0..n - 1).collect();
        let edge_to: Vec<usize> = (1..n).collect();
        let edge_weight = vec![10; n - 1];
        let edge_length = vec![100.0; n - 1];
        let node_lat: Vec<f64> = (0..n).map(|i| i as f64).collect();
        let node_lng: Vec<f64> = (0..n).map(|i| i as f64).collect();
        let graph = RoadGraph::build_with_length_and_coords(
            &edge_from,
            &edge_to,
            &edge_weight,
            &edge_length,
            &node_lat,
            &node_lng,
        );
        let (lats, lngs, cum, connected, starts, ends) =
            batch_road_routes(&graph, &[0], &[(n - 1) as i64], 5);
        assert_eq!(connected, vec![true]);
        let len = ends[0] - starts[0];
        assert!(len <= 5);
        assert_eq!(lats.first(), Some(&0.0));
        assert_eq!(lats.last(), Some(&((n - 1) as f64)));
        assert_eq!(lngs.first(), Some(&0.0));
        assert_eq!(cum.first(), Some(&0));
        assert_eq!(cum.last(), Some(&(((n - 1) * 10) as i64)));
    }

    #[test]
    fn batch_routes_reports_disconnected_and_unsnapped_as_zero_waypoints() {
        let edge_from = vec![0, 2];
        let edge_to = vec![1, 3];
        let edge_weight = vec![5, 5];
        let edge_length = vec![10.0, 10.0];
        let node_lat = vec![0.0, 1.0, 2.0, 3.0];
        let node_lng = vec![0.0, 1.0, 2.0, 3.0];
        let graph = RoadGraph::build_with_length_and_coords(
            &edge_from,
            &edge_to,
            &edge_weight,
            &edge_length,
            &node_lat,
            &node_lng,
        );
        let (lats, _lngs, _cum, connected, starts, ends) =
            batch_road_routes(&graph, &[0, -1], &[3, 2], 10);
        assert_eq!(connected, vec![false, false]);
        assert_eq!(starts, vec![0, 0]);
        assert_eq!(ends, vec![0, 0]);
        assert!(lats.is_empty());
    }

    #[test]
    fn batch_route_edge_flows_accumulates_along_shared_path() {
        // 0 -> 1 -> 2 -> 3 chain; queries (0,3), (1,3), (2,3) share
        // increasingly short suffixes of the chain, plus one unsnapped query
        // whose flow must land in `dropped_flow` instead of any edge.
        let edge_from = vec![0, 1, 2];
        let edge_to = vec![1, 2, 3];
        let edge_weight = vec![10, 10, 10];
        let graph = RoadGraph::build(&edge_from, &edge_to, &edge_weight);
        let (edge_from_out, edge_to_out, flow_out, dropped_flow) =
            batch_route_edge_flows(&graph, &[0, 1, 2, -1], &[3, 3, 3, 2], &[5.0, 3.0, 0.5, 1.0]);
        assert_eq!(edge_from_out, vec![2, 1, 0]);
        assert_eq!(edge_to_out, vec![3, 2, 1]);
        assert_eq!(flow_out, vec![8.5, 8.0, 5.0]);
        assert_eq!(dropped_flow, 1.0);
    }
}