tracematch 0.0.2

High-performance GPS route matching and activity 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
//! FFI bindings for mobile platforms (iOS/Android).
//!
//! This module provides the UniFFI bindings that expose Rust functionality
//! to Kotlin and Swift. All FFI functions are prefixed with `ffi_` to avoid
//! naming conflicts with the internal API.

use crate::{
    compare_routes, init_logging, GpsPoint, MatchConfig, MatchResult, RouteGroup, RouteSignature,
};
use log::{debug, info};

#[cfg(feature = "parallel")]
use crate::grouping::{group_incremental, group_signatures_parallel};

#[cfg(not(feature = "parallel"))]
use crate::group_signatures;

// ============================================================================
// Core Route Functions
// ============================================================================

/// Create a route signature from GPS points.
#[uniffi::export]
pub fn create_signature(activity_id: String, points: Vec<GpsPoint>) -> Option<RouteSignature> {
    init_logging();
    info!(
        "[RouteMatcherRust] create_signature called for {} with {} points",
        activity_id,
        points.len()
    );
    let result = RouteSignature::from_points(&activity_id, &points, &MatchConfig::default());
    if let Some(ref sig) = result {
        info!(
            "[RouteMatcherRust] Created signature: {} points, {:.0}m distance",
            sig.points.len(),
            sig.total_distance
        );
    }
    result
}

/// Create a route signature with custom configuration.
#[uniffi::export]
pub fn create_signature_with_config(
    activity_id: String,
    points: Vec<GpsPoint>,
    config: MatchConfig,
) -> Option<RouteSignature> {
    init_logging();
    info!(
        "[RouteMatcherRust] create_signature_with_config for {} ({} points)",
        activity_id,
        points.len()
    );
    RouteSignature::from_points(&activity_id, &points, &config)
}

/// Compare two routes and return match result.
#[uniffi::export]
pub fn ffi_compare_routes(
    sig1: &RouteSignature,
    sig2: &RouteSignature,
    config: MatchConfig,
) -> Option<MatchResult> {
    init_logging();
    debug!(
        "[RouteMatcherRust] Comparing {} vs {}",
        sig1.activity_id, sig2.activity_id
    );
    let result = compare_routes(sig1, sig2, &config);
    if let Some(ref r) = result {
        info!(
            "[RouteMatcherRust] Match found: {:.1}% ({})",
            r.match_percentage, r.direction
        );
    }
    result
}

/// Group signatures into route groups.
#[uniffi::export]
pub fn ffi_group_signatures(
    signatures: Vec<RouteSignature>,
    config: MatchConfig,
) -> Vec<RouteGroup> {
    init_logging();
    info!(
        "[RouteMatcherRust] RUST groupSignatures called with {} signatures",
        signatures.len()
    );

    let start = std::time::Instant::now();

    #[cfg(feature = "parallel")]
    let groups = {
        info!("[RouteMatcherRust] Using PARALLEL processing (rayon)");
        group_signatures_parallel(&signatures, &config)
    };

    #[cfg(not(feature = "parallel"))]
    let groups = {
        info!("[RouteMatcherRust] Using sequential processing");
        group_signatures(&signatures, &config)
    };

    let elapsed = start.elapsed();
    info!(
        "[RouteMatcherRust] Grouped into {} groups in {:?}",
        groups.len(),
        elapsed
    );

    groups
}

/// Incremental grouping: efficiently add new signatures to existing groups.
/// Only compares new vs existing and new vs new - O(n×m) instead of O(n²).
#[uniffi::export]
pub fn ffi_group_incremental(
    new_signatures: Vec<RouteSignature>,
    existing_groups: Vec<RouteGroup>,
    existing_signatures: Vec<RouteSignature>,
    config: MatchConfig,
) -> Vec<RouteGroup> {
    init_logging();
    info!(
        "[RouteMatcherRust] INCREMENTAL grouping: {} new + {} existing signatures",
        new_signatures.len(),
        existing_signatures.len()
    );

    let start = std::time::Instant::now();

    #[cfg(feature = "parallel")]
    let groups = group_incremental(
        &new_signatures,
        &existing_groups,
        &existing_signatures,
        &config,
    );

    #[cfg(not(feature = "parallel"))]
    let groups = {
        // Fallback to full re-grouping if parallel feature not enabled
        let all_sigs: Vec<RouteSignature> = existing_signatures
            .into_iter()
            .chain(new_signatures.into_iter())
            .collect();
        group_signatures(&all_sigs, &config)
    };

    let elapsed = start.elapsed();
    info!(
        "[RouteMatcherRust] Incremental grouped into {} groups in {:?}",
        groups.len(),
        elapsed
    );

    groups
}

/// Get default configuration.
#[uniffi::export]
pub fn default_config() -> MatchConfig {
    init_logging();
    info!("[RouteMatcherRust] default_config called - Rust is active!");
    MatchConfig::default()
}

// ============================================================================
// Flat Buffer Processing (optimized for TypedArray input)
// ============================================================================

/// Input for flat buffer processing (zero-copy from JS TypedArray)
#[derive(Debug, Clone, uniffi::Record)]
pub struct FlatGpsTrack {
    pub activity_id: String,
    /// Flat array of coordinates: [lat1, lng1, lat2, lng2, ...]
    pub coords: Vec<f64>,
}

/// Create signatures from flat coordinate buffers (optimized for TypedArray input).
/// Each track's coords array contains [lat1, lng1, lat2, lng2, ...].
/// This avoids the overhead of deserializing GpsPoint objects.
#[uniffi::export]
pub fn create_signatures_from_flat(
    tracks: Vec<FlatGpsTrack>,
    config: MatchConfig,
) -> Vec<RouteSignature> {
    init_logging();
    info!(
        "[RouteMatcherRust] FLAT BUFFER createSignatures called with {} tracks",
        tracks.len()
    );

    let start = std::time::Instant::now();

    #[cfg(feature = "parallel")]
    let signatures: Vec<RouteSignature> = {
        use rayon::prelude::*;
        info!("[RouteMatcherRust] Using PARALLEL flat buffer processing (rayon)");
        tracks
            .par_iter()
            .filter_map(|track| {
                // Convert flat coords to GpsPoints
                let points: Vec<GpsPoint> = track
                    .coords
                    .chunks_exact(2)
                    .map(|chunk| GpsPoint::new(chunk[0], chunk[1]))
                    .collect();
                RouteSignature::from_points(&track.activity_id, &points, &config)
            })
            .collect()
    };

    #[cfg(not(feature = "parallel"))]
    let signatures: Vec<RouteSignature> = {
        info!("[RouteMatcherRust] Using sequential flat buffer processing");
        tracks
            .iter()
            .filter_map(|track| {
                let points: Vec<GpsPoint> = track
                    .coords
                    .chunks_exact(2)
                    .map(|chunk| GpsPoint::new(chunk[0], chunk[1]))
                    .collect();
                RouteSignature::from_points(&track.activity_id, &points, &config)
            })
            .collect()
    };

    let elapsed = start.elapsed();
    info!(
        "[RouteMatcherRust] FLAT created {} signatures from {} tracks in {:?}",
        signatures.len(),
        tracks.len(),
        elapsed
    );

    signatures
}

/// Process routes end-to-end from flat buffers: create signatures AND group them.
/// Most efficient way to process many activities from TypedArray input.
#[uniffi::export]
pub fn process_routes_from_flat(tracks: Vec<FlatGpsTrack>, config: MatchConfig) -> Vec<RouteGroup> {
    init_logging();
    info!(
        "[RouteMatcherRust] FLAT BATCH process_routes called with {} tracks",
        tracks.len()
    );

    let start = std::time::Instant::now();

    // Step 1: Create all signatures from flat buffers
    let signatures = create_signatures_from_flat(tracks.clone(), config.clone());

    // Step 2: Group signatures
    #[cfg(feature = "parallel")]
    let groups = group_signatures_parallel(&signatures, &config);

    #[cfg(not(feature = "parallel"))]
    let groups = group_signatures(&signatures, &config);

    let elapsed = start.elapsed();
    info!(
        "[RouteMatcherRust] FLAT batch processing: {} signatures -> {} groups in {:?}",
        signatures.len(),
        groups.len(),
        elapsed
    );

    groups
}

// ============================================================================
// Frequent Sections Detection
// ============================================================================

/// Input mapping activity IDs to sport types
#[derive(Debug, Clone, uniffi::Record)]
pub struct ActivitySportType {
    pub activity_id: String,
    pub sport_type: String,
}

/// Get conservative section config (fewer sections, higher confidence)
#[uniffi::export]
pub fn conservative_section_config() -> crate::SectionConfig {
    crate::SectionConfig::conservative()
}

/// Get legacy section config (backward compatible single-scale)
#[uniffi::export]
pub fn legacy_section_config() -> crate::SectionConfig {
    crate::SectionConfig::legacy()
}

/// Get default scale presets for multi-scale detection
#[uniffi::export]
pub fn default_scale_presets() -> Vec<crate::ScalePreset> {
    crate::ScalePreset::default_presets()
}

/// Detect sections at multiple scales with potential section suggestions.
/// This is the flagship entry point for section detection.
///
/// Returns a MultiScaleSectionResult with:
/// - sections: Confirmed sections (meeting min_activities threshold)
/// - potentials: Suggested sections from 1-2 activity overlaps
/// - stats: Detection statistics
#[uniffi::export]
pub fn ffi_detect_sections_multiscale(
    activity_ids: Vec<String>,
    all_coords: Vec<f64>,
    offsets: Vec<u32>,
    sport_types: Vec<ActivitySportType>,
    groups: Vec<RouteGroup>,
    config: crate::SectionConfig,
) -> crate::MultiScaleSectionResult {
    init_logging();
    info!(
        "[RouteMatcherRust] detect_sections_multiscale: {} activities, {} coords, {} scales",
        activity_ids.len(),
        all_coords.len() / 2,
        config.scale_presets.len()
    );

    let start = std::time::Instant::now();

    // Convert flat coordinates to tracks
    let mut tracks: Vec<(String, Vec<GpsPoint>)> = Vec::with_capacity(activity_ids.len());

    for (i, activity_id) in activity_ids.iter().enumerate() {
        let start_offset = offsets[i] as usize;
        let end_offset = offsets
            .get(i + 1)
            .map(|&o| o as usize)
            .unwrap_or(all_coords.len() / 2);

        let mut points = Vec::with_capacity(end_offset - start_offset);
        for j in start_offset..end_offset {
            let coord_idx = j * 2;
            if coord_idx + 1 < all_coords.len() {
                points.push(GpsPoint::new(
                    all_coords[coord_idx],
                    all_coords[coord_idx + 1],
                ));
            }
        }

        if !points.is_empty() {
            tracks.push((activity_id.clone(), points));
        }
    }

    info!(
        "[RouteMatcherRust] Converted to {} tracks with full GPS data",
        tracks.len()
    );

    // Convert sport types to HashMap
    let sport_map: std::collections::HashMap<String, String> = sport_types
        .into_iter()
        .map(|st| (st.activity_id, st.sport_type))
        .collect();

    let result = crate::sections::detect_sections_multiscale(&tracks, &sport_map, &groups, &config);

    let elapsed = start.elapsed();
    info!(
        "[RouteMatcherRust] Multi-scale detection: {} sections, {} potentials in {:?}",
        result.sections.len(),
        result.potentials.len(),
        elapsed
    );

    result
}

/// Optimized section detection using downsampling and grid partitioning.
/// 20-50x faster than full resolution detection, suitable for mobile devices.
#[uniffi::export]
pub fn ffi_detect_sections_optimized(
    activity_ids: Vec<String>,
    all_coords: Vec<f64>,
    offsets: Vec<u32>,
    sport_types: Vec<ActivitySportType>,
    config: crate::SectionConfig,
) -> Vec<crate::FrequentSection> {
    init_logging();
    info!(
        "[RouteMatcherRust] detect_sections_optimized: {} activities, {} coords",
        activity_ids.len(),
        all_coords.len() / 2,
    );

    let start = std::time::Instant::now();

    let mut tracks: Vec<(String, Vec<GpsPoint>)> = Vec::with_capacity(activity_ids.len());

    for (i, activity_id) in activity_ids.iter().enumerate() {
        let start_offset = offsets[i] as usize;
        let end_offset = offsets
            .get(i + 1)
            .map(|&o| o as usize)
            .unwrap_or(all_coords.len() / 2);

        let mut points = Vec::with_capacity(end_offset - start_offset);
        for j in start_offset..end_offset {
            let coord_idx = j * 2;
            if coord_idx + 1 < all_coords.len() {
                points.push(GpsPoint::new(
                    all_coords[coord_idx],
                    all_coords[coord_idx + 1],
                ));
            }
        }

        if !points.is_empty() {
            tracks.push((activity_id.clone(), points));
        }
    }

    let sport_map: std::collections::HashMap<String, String> = sport_types
        .into_iter()
        .map(|st| (st.activity_id, st.sport_type))
        .collect();

    let result = crate::sections::detect_sections_optimized(&tracks, &sport_map, &config);

    let elapsed = start.elapsed();
    info!(
        "[RouteMatcherRust] Optimized detection: {} sections in {:?}",
        result.len(),
        elapsed
    );

    result
}

// ============================================================================
// Heatmap Generation FFI
// ============================================================================

/// Generate a heatmap from route signatures.
/// Uses the simplified GPS traces (~100 points each) for efficient generation.
#[uniffi::export]
pub fn ffi_generate_heatmap(
    signatures: Vec<RouteSignature>,
    activity_data: Vec<crate::ActivityHeatmapData>,
    config: crate::HeatmapConfig,
) -> crate::HeatmapResult {
    init_logging();
    info!(
        "[RouteMatcherRust] generate_heatmap: {} signatures, {}m cells",
        signatures.len(),
        config.cell_size_meters
    );

    let start = std::time::Instant::now();

    // Convert Vec to HashMap for efficient lookup
    let data_map: std::collections::HashMap<String, crate::ActivityHeatmapData> = activity_data
        .into_iter()
        .map(|d| (d.activity_id.clone(), d))
        .collect();

    let result = crate::generate_heatmap(&signatures, &data_map, &config);

    let elapsed = start.elapsed();
    info!(
        "[RouteMatcherRust] Heatmap generated: {} cells, {} routes, {} activities in {:?}",
        result.cells.len(),
        result.total_routes,
        result.total_activities,
        elapsed
    );

    result
}

/// Query the heatmap at a specific location.
#[uniffi::export]
pub fn ffi_query_heatmap_cell(
    heatmap: crate::HeatmapResult,
    lat: f64,
    lng: f64,
) -> Option<crate::CellQueryResult> {
    crate::query_heatmap_cell(&heatmap, lat, lng, heatmap.cell_size_meters)
}

// =============================================================================
// Section Manipulation FFI Functions
// =============================================================================

/// Find all sections that exist within a given GPS route.
///
/// Returns a list of section matches with their positions in the route.
#[uniffi::export]
pub fn ffi_find_sections_in_route(
    route: Vec<crate::GpsPoint>,
    sections: Vec<crate::FrequentSection>,
    config: crate::SectionConfig,
) -> Vec<crate::SectionMatch> {
    crate::find_sections_in_route(&route, &sections, &config)
}

/// Split a section at a geographic point.
///
/// Returns two new sections if the point is close enough to the section's polyline.
#[uniffi::export]
pub fn ffi_split_section_at_point(
    section: crate::FrequentSection,
    lat: f64,
    lng: f64,
    max_distance_meters: f64,
) -> Option<crate::SplitResult> {
    let point = crate::GpsPoint::new(lat, lng);
    crate::split_section_at_point(&section, &point, max_distance_meters)
}

/// Split a section at a specific polyline index.
///
/// Returns two new sections split at the given index.
#[uniffi::export]
pub fn ffi_split_section_at_index(
    section: crate::FrequentSection,
    split_index: u32,
) -> Option<crate::SplitResult> {
    crate::split_section_at_index(&section, split_index as usize)
}

/// Recalculate a section's polyline based on its activity traces.
///
/// Useful when a section's polyline has drifted or is biased.
#[uniffi::export]
pub fn ffi_recalculate_section_polyline(
    section: crate::FrequentSection,
    config: crate::SectionConfig,
) -> crate::FrequentSection {
    crate::recalculate_section_polyline(&section, &config)
}