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
use crate::utils::haversine::haversine_km;
use std::f64::consts::PI;

use super::stvd_candidate_graph::CandidateGraphConfig;
use super::stvd_sparse_sinkhorn::sparse_stvd_emd_impl;

/// Sinkhorn solver knobs. The `wass` crate this module used to delegate to
/// hardcoded `reg=0.01, max_iter=200` with no convergence check; this
/// exposes those as real parameters instead, matching the defaults exactly
/// for callers that don't override them.
#[derive(Clone, Copy, Debug)]
pub struct SinkhornConfig {
    pub reg: f64,
    pub max_iter: usize,
    pub tol: Option<f64>,
}

impl Default for SinkhornConfig {
    fn default() -> Self {
        Self { reg: 0.01, max_iter: 200, tol: None }
    }
}

/// Shortest angular distance between two angles (radians), independent of winding direction.
fn angular_diff(theta1: f64, theta2: f64) -> f64 {
    let diff = (theta1 - theta2).abs() % (2.0 * PI);
    diff.min(2.0 * PI - diff)
}

/// Cyclical-time chordal distance (metres) between two timestamps, matching the
/// `r * (cos theta, sin theta)` embedding this module used before switching to an explicit
/// cost matrix: two points on a circle of radius `r` separated by angle `d_theta` are
/// `2 * r * sin(d_theta / 2)` apart in a straight line.
fn temporal_chord_m(t1: f64, t2: f64, cyclical_period: f64, r: f64) -> f64 {
    let theta1 = 2.0 * PI * (t1.rem_euclid(cyclical_period) / cyclical_period);
    let theta2 = 2.0 * PI * (t2.rem_euclid(cyclical_period) / cyclical_period);
    2.0 * r * (angular_diff(theta1, theta2) / 2.0).sin()
}

/// Cost (metres) between one point of distribution A and one of distribution
/// B: a Euclidean combination of great-circle spatial distance and cyclical-
/// time chordal distance. Shared by the dense complete-bipartite-graph path
/// (below) and the H3 candidate-graph path (`stvd_candidate_graph.rs`) so
/// the two can never numerically drift apart.
#[allow(clippy::too_many_arguments)]
pub(crate) fn pair_cost_m(
    lat_a: f64,
    lng_a: f64,
    t_a: f64,
    lat_b: f64,
    lng_b: f64,
    t_b: f64,
    cyclical_period: f64,
    r: f64,
) -> f32 {
    let spatial_m = haversine_km(lat_a, lng_a, lat_b, lng_b) * 1000.0;
    let temporal_m = temporal_chord_m(t_a, t_b, cyclical_period, r);
    (spatial_m.powi(2) + temporal_m.powi(2)).sqrt() as f32
}

#[allow(clippy::too_many_arguments)]
pub fn stvd_emd_impl(
    lats_a: &[f64],
    lngs_a: &[f64],
    ts_a: &[f64],
    ws_a: &[f64],
    lats_b: &[f64],
    lngs_b: &[f64],
    ts_b: &[f64],
    ws_b: &[f64],
    alpha: f64,
    cyclical_period: f64,
    sinkhorn: SinkhornConfig,
) -> Result<f64, String> {
    let n = lats_a.len();
    let m = lats_b.len();

    if n == 0 || m == 0 {
        return Err("distributions must be non-empty".to_string());
    }
    if lngs_a.len() != n || ts_a.len() != n || ws_a.len() != n {
        return Err("all arrays for distribution A must have the same length".to_string());
    }
    if lngs_b.len() != m || ts_b.len() != m || ws_b.len() != m {
        return Err("all arrays for distribution B must have the same length".to_string());
    }
    if cyclical_period <= 0.0 {
        return Err("cyclical_period must be positive".to_string());
    }
    if !alpha.is_finite() || !cyclical_period.is_finite() {
        return Err("alpha and cyclical_period must be finite".to_string());
    }
    if lats_a
        .iter()
        .chain(lngs_a)
        .chain(ts_a)
        .chain(lats_b)
        .chain(lngs_b)
        .chain(ts_b)
        .any(|value| !value.is_finite())
    {
        return Err("coordinates and times must be finite".to_string());
    }
    if ws_a
        .iter()
        .chain(ws_b)
        .any(|weight| !weight.is_finite() || *weight < 0.0)
    {
        return Err("weights must be finite and non-negative".to_string());
    }
    if sinkhorn.reg <= 0.0 || !sinkhorn.reg.is_finite() {
        return Err("sinkhorn reg must be positive and finite".to_string());
    }
    if sinkhorn.max_iter == 0 {
        return Err("sinkhorn max_iter must be positive".to_string());
    }
    if let Some(tol) = sinkhorn.tol
        && (tol <= 0.0 || !tol.is_finite())
    {
        return Err("sinkhorn tol must be positive and finite".to_string());
    }

    let sum_a: f64 = ws_a.iter().sum();
    let sum_b: f64 = ws_b.iter().sum();
    if sum_a <= 0.0 || sum_b <= 0.0 {
        return Err("weights must sum to a positive value".to_string());
    }

    sparse_stvd_emd_impl(
        lats_a, lngs_a, ts_a, ws_a, lats_b, lngs_b, ts_b, ws_b, alpha, cyclical_period, sinkhorn,
        CandidateGraphConfig::default(),
    )
}

/// The dense complete-bipartite-graph, `wass`-backed Sinkhorn this crate
/// used to run in production before the H3 candidate-graph sparse rewrite
/// (`stvd_candidate_graph.rs` / `stvd_sparse_sinkhorn.rs`). Kept **only** as
/// a differential-testing reference -- `wass` is a `[dev-dependencies]`-only
/// crate now, not linked into release builds at all. Callers are expected
/// to have already run `stvd_emd_impl`'s validation; this assumes valid
/// input and skips it, and (being test-only, always called at small scale)
/// has no memory guard.
#[cfg(test)]
#[allow(clippy::too_many_arguments)]
pub(crate) fn dense_reference_impl(
    lats_a: &[f64],
    lngs_a: &[f64],
    ts_a: &[f64],
    ws_a: &[f64],
    lats_b: &[f64],
    lngs_b: &[f64],
    ts_b: &[f64],
    ws_b: &[f64],
    alpha: f64,
    cyclical_period: f64,
    sinkhorn: SinkhornConfig,
) -> Result<f64, String> {
    use ndarray::{Array1, Array2};
    use rayon::prelude::*;
    use wass::{sinkhorn_log, sinkhorn_log_with_convergence};

    let n = lats_a.len();
    let m = lats_b.len();
    let r = (alpha * cyclical_period) / (2.0 * PI);

    let cost_len = n * m;
    let mut cost_values = vec![0.0_f32; cost_len];
    cost_values
        .par_chunks_mut(m)
        .enumerate()
        .for_each(|(i, row)| {
            for j in 0..m {
                row[j] = pair_cost_m(
                    lats_a[i], lngs_a[i], ts_a[i], lats_b[j], lngs_b[j], ts_b[j], cyclical_period, r,
                );
            }
        });
    let cost =
        Array2::from_shape_vec((n, m), cost_values).expect("cost buffer has exactly n * m entries");

    let a: Array1<f32> = ws_a.iter().map(|&w| w as f32).collect();
    let b: Array1<f32> = ws_b.iter().map(|&w| w as f32).collect();

    let reg = sinkhorn.reg as f32;
    let distance = if let Some(tol) = sinkhorn.tol {
        let (_, distance, _iterations) =
            sinkhorn_log_with_convergence(&a, &b, &cost, reg, sinkhorn.max_iter, tol as f32)
                .map_err(|err| err.to_string())?;
        distance
    } else {
        let (_, distance) = sinkhorn_log(&a, &b, &cost, reg, sinkhorn.max_iter);
        distance
    };
    Ok(distance as f64)
}

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

    #[test]
    fn identical_single_point_is_zero_distance() {
        let value = stvd_emd_impl(
            &[10.0],
            &[20.0],
            &[480.0],
            &[1.0],
            &[10.0],
            &[20.0],
            &[480.0],
            &[1.0],
            10.0,
            1440.0,
            SinkhornConfig::default(),
        )
        .unwrap();
        assert!(value.abs() < 1e-6, "got {value}");
    }

    #[test]
    fn spatial_displacement_matches_haversine_distance() {
        // Same time bin on both sides so only the spatial term contributes.
        let lat1 = 0.0;
        let lng1 = 0.0;
        let lat2 = 0.0;
        let lng2 = 1.0; // ~111.19 km at the equator
        let expected_m = haversine_km(lat1, lng1, lat2, lng2) * 1000.0;

        let value = stvd_emd_impl(
            &[lat1],
            &[lng1],
            &[480.0],
            &[1.0],
            &[lat2],
            &[lng2],
            &[480.0],
            &[1.0],
            10.0,
            1440.0,
            SinkhornConfig::default(),
        )
        .unwrap();
        // Sinkhorn is an entropy-regularised approximation, not exact, so allow slack.
        assert!(
            (value - expected_m).abs() / expected_m < 0.05,
            "got {value}, expected close to {expected_m}"
        );
    }

    #[test]
    fn cyclical_time_wraps_around() {
        // 1 minute before midnight vs 1 minute after midnight should be "close" (2 minutes
        // apart), not ~1438 minutes apart, when cyclical_period=1440.
        let near = stvd_emd_impl(
            &[0.0],
            &[0.0],
            &[1439.0],
            &[1.0],
            &[0.0],
            &[0.0],
            &[1.0],
            &[1.0],
            10.0,
            1440.0,
            SinkhornConfig::default(),
        )
        .unwrap();
        let far = stvd_emd_impl(
            &[0.0],
            &[0.0],
            &[1439.0],
            &[1.0],
            &[0.0],
            &[0.0],
            &[700.0],
            &[1.0],
            10.0,
            1440.0,
            SinkhornConfig::default(),
        )
        .unwrap();
        assert!(near < far, "near={near} far={far}");
    }

    #[test]
    fn empty_distribution_is_rejected() {
        assert!(stvd_emd_impl(
            &[],
            &[],
            &[],
            &[],
            &[0.0],
            &[0.0],
            &[0.0],
            &[1.0],
            10.0,
            1440.0,
            SinkhornConfig::default(),
        )
        .is_err());
    }

    #[test]
    fn large_input_completes_via_sparse_path() {
        // n*m = 576M would be ~4.6GB as a dense f32 cost matrix (plus
        // wass's internal coupling-matrix doubling) -- large enough that
        // this would have OOM'd the old dense-by-default path outright.
        // Points are spread across a city-sized bounding box (not all
        // colocated) so the candidate graph actually stays sparse; see
        // stvd_sparse_sinkhorn.rs's capstone test for real-world-shaped
        // scale (126,892 x 78,918 rows, 1,808 distinct locations).
        let n = 24_000;
        let m = 24_000;

        struct XorShift(u64);
        impl XorShift {
            fn next(&mut self) -> u64 {
                self.0 ^= self.0 << 13;
                self.0 ^= self.0 >> 7;
                self.0 ^= self.0 << 17;
                self.0
            }
            fn range_f64(&mut self, lo: f64, hi: f64) -> f64 {
                let frac = (self.next() % 1_000_000) as f64 / 1_000_000.0;
                lo + frac * (hi - lo)
            }
        }
        let mut rng = XorShift(7);
        let mut gen_side = |count: usize| -> (Vec<f64>, Vec<f64>, Vec<f64>, Vec<f64>) {
            let mut lats = Vec::with_capacity(count);
            let mut lngs = Vec::with_capacity(count);
            let mut ts = Vec::with_capacity(count);
            let mut ws = Vec::with_capacity(count);
            for _ in 0..count {
                lats.push(rng.range_f64(48.5, 49.1));
                lngs.push(rng.range_f64(2.0, 2.6));
                ts.push(rng.range_f64(0.0, 1439.0));
                ws.push(rng.range_f64(0.1, 1.0));
            }
            (lats, lngs, ts, ws)
        };
        let (lats_a, lngs_a, ts_a, ws_a) = gen_side(n);
        let (lats_b, lngs_b, ts_b, ws_b) = gen_side(m);

        let value = stvd_emd_impl(
            &lats_a,
            &lngs_a,
            &ts_a,
            &ws_a,
            &lats_b,
            &lngs_b,
            &ts_b,
            &ws_b,
            10.0,
            1440.0,
            SinkhornConfig::default(),
        )
        .unwrap();
        assert!(value.is_finite() && value >= 0.0, "got {value}");
    }

    #[test]
    fn non_positive_cyclical_period_is_rejected() {
        assert!(stvd_emd_impl(
            &[0.0],
            &[0.0],
            &[0.0],
            &[1.0],
            &[0.0],
            &[0.0],
            &[0.0],
            &[1.0],
            10.0,
            0.0,
            SinkhornConfig::default(),
        )
        .is_err());
    }

    #[test]
    fn zero_weight_sum_is_rejected() {
        assert!(stvd_emd_impl(
            &[0.0],
            &[0.0],
            &[0.0],
            &[0.0],
            &[0.0],
            &[0.0],
            &[0.0],
            &[1.0],
            10.0,
            1440.0,
            SinkhornConfig::default(),
        )
        .is_err());
    }

    #[test]
    fn invalid_weights_and_coordinates_are_rejected() {
        assert!(stvd_emd_impl(
            &[f64::NAN],
            &[0.0],
            &[0.0],
            &[1.0],
            &[0.0],
            &[0.0],
            &[0.0],
            &[1.0],
            10.0,
            1440.0,
            SinkhornConfig::default(),
        )
        .is_err());
        assert!(stvd_emd_impl(
            &[0.0],
            &[0.0],
            &[0.0],
            &[-1.0],
            &[0.0],
            &[0.0],
            &[0.0],
            &[1.0],
            10.0,
            1440.0,
            SinkhornConfig::default(),
        )
        .is_err());
    }

    #[test]
    fn invalid_sinkhorn_reg_is_rejected() {
        assert!(stvd_emd_impl(
            &[0.0],
            &[0.0],
            &[0.0],
            &[1.0],
            &[0.0],
            &[0.0],
            &[0.0],
            &[1.0],
            10.0,
            1440.0,
            SinkhornConfig { reg: 0.0, ..SinkhornConfig::default() },
        )
        .is_err());
        assert!(stvd_emd_impl(
            &[0.0],
            &[0.0],
            &[0.0],
            &[1.0],
            &[0.0],
            &[0.0],
            &[0.0],
            &[1.0],
            10.0,
            1440.0,
            SinkhornConfig { max_iter: 0, ..SinkhornConfig::default() },
        )
        .is_err());
        assert!(stvd_emd_impl(
            &[0.0],
            &[0.0],
            &[0.0],
            &[1.0],
            &[0.0],
            &[0.0],
            &[0.0],
            &[1.0],
            10.0,
            1440.0,
            SinkhornConfig { tol: Some(-1.0), ..SinkhornConfig::default() },
        )
        .is_err());
    }

    #[test]
    fn custom_sinkhorn_config_with_tolerance_converges() {
        let value = stvd_emd_impl(
            &[10.0],
            &[20.0],
            &[480.0],
            &[1.0],
            &[10.0],
            &[20.0],
            &[480.0],
            &[1.0],
            10.0,
            1440.0,
            SinkhornConfig { reg: 0.1, max_iter: 500, tol: Some(1e-6) },
        )
        .unwrap();
        assert!(value.abs() < 1e-3, "got {value}");
    }
}