spatio 0.3.6

A high-performance, embedded spatio-temporal database for modern applications
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
//! Validation for geographic coordinates.

use crate::error::{Result, SpatioError};
use spatio_types::geo::Point;
use spatio_types::point::Point3d;

/// Validates a 2D point has valid longitude and latitude.
///
/// Longitude: [-180.0, 180.0], Latitude: [-90.0, 90.0]
///
/// # Examples
///
/// ```
/// use spatio::compute::validation::validate_geographic_point;
/// use spatio_types::geo::Point;
///
/// // Valid point
/// let nyc = Point::new(-74.0060, 40.7128);
/// assert!(validate_geographic_point(&nyc).is_ok());
///
/// // Invalid longitude
/// let invalid = Point::new(200.0, 40.0);
/// assert!(validate_geographic_point(&invalid).is_err());
///
/// // Invalid latitude
/// let invalid = Point::new(-74.0, 95.0);
/// assert!(validate_geographic_point(&invalid).is_err());
/// ```
pub fn validate_geographic_point(point: &Point) -> Result<()> {
    let (x, y) = (point.x(), point.y());

    if !x.is_finite() {
        return Err(SpatioError::InvalidInput(format!(
            "Longitude must be finite, got: {}",
            x
        )));
    }

    if !y.is_finite() {
        return Err(SpatioError::InvalidInput(format!(
            "Latitude must be finite, got: {}",
            y
        )));
    }

    if !(-180.0..=180.0).contains(&x) {
        return Err(SpatioError::InvalidInput(format!(
            "Longitude out of range [-180.0, 180.0]: {}",
            x
        )));
    }

    if !(-90.0..=90.0).contains(&y) {
        return Err(SpatioError::InvalidInput(format!(
            "Latitude out of range [-90.0, 90.0]: {}",
            y
        )));
    }

    Ok(())
}

/// Validates a 3D point including altitude.
///
/// Altitude range: [-11000, 100000] meters (Mariana Trench to Kármán line)
///
/// # Examples
///
/// ```
/// use spatio::compute::validation::validate_geographic_point_3d;
/// use spatio_types::point::Point3d;
///
/// // Valid 3D point (drone at 100m altitude)
/// let drone = Point3d::new(-74.0060, 40.7128, 100.0);
/// assert!(validate_geographic_point_3d(&drone).is_ok());
///
/// // Invalid altitude (too high)
/// let invalid = Point3d::new(-74.0, 40.7, 200000.0);
/// assert!(validate_geographic_point_3d(&invalid).is_err());
/// ```
pub fn validate_geographic_point_3d(point: &Point3d) -> Result<()> {
    validate_geographic_point(&point.to_2d())?;

    let z = point.z();

    if !z.is_finite() {
        return Err(SpatioError::InvalidInput(format!(
            "Altitude must be finite, got: {}",
            z
        )));
    }

    const MIN_ALTITUDE: f64 = -11000.0;
    const MAX_ALTITUDE: f64 = 100000.0;

    if !(MIN_ALTITUDE..=MAX_ALTITUDE).contains(&z) {
        return Err(SpatioError::InvalidInput(format!(
            "Altitude out of reasonable range [{}, {}] meters: {}",
            MIN_ALTITUDE, MAX_ALTITUDE, z
        )));
    }

    Ok(())
}

/// Validates multiple points.
///
/// # Examples
///
/// ```
/// use spatio::compute::validation::validate_points;
/// use spatio_types::geo::Point;
///
/// let points = vec![
///     Point::new(-74.0, 40.7),
///     Point::new(-73.9, 40.8),
///     Point::new(999.0, 40.0), // Invalid
/// ];
///
/// let result = validate_points(&points);
/// assert!(result.is_err());
/// ```
pub fn validate_points(points: &[Point]) -> Result<()> {
    for (idx, point) in points.iter().enumerate() {
        validate_geographic_point(point)
            .map_err(|e| SpatioError::InvalidInput(format!("Point at index {}: {}", idx, e)))?;
    }
    Ok(())
}

/// Validates multiple 3D points.
pub fn validate_points_3d(points: &[Point3d]) -> Result<()> {
    for (idx, point) in points.iter().enumerate() {
        validate_geographic_point_3d(point)
            .map_err(|e| SpatioError::InvalidInput(format!("Point at index {}: {}", idx, e)))?;
    }
    Ok(())
}

/// Validates all polygon coordinates (exterior and interior rings).
///
/// # Examples
///
/// ```
/// use spatio::compute::validation::validate_polygon;
/// use spatio::Polygon;
/// use geo::polygon;
///
/// let poly = polygon![
///     (x: -80.0, y: 35.0),
///     (x: -70.0, y: 35.0),
///     (x: -70.0, y: 45.0),
///     (x: -80.0, y: 45.0),
///     (x: -80.0, y: 35.0),
/// ];
/// let poly: Polygon = poly.into();
///
/// assert!(validate_polygon(&poly).is_ok());
/// ```
pub fn validate_polygon(polygon: &spatio_types::geo::Polygon) -> Result<()> {
    for (idx, coord) in polygon.exterior().coords().enumerate() {
        let point = Point::new(coord.x, coord.y);
        validate_geographic_point(&point).map_err(|e| {
            SpatioError::InvalidInput(format!("Exterior ring point at index {}: {}", idx, e))
        })?;
    }

    for (ring_idx, interior) in polygon.interiors().iter().enumerate() {
        for (idx, coord) in interior.coords().enumerate() {
            let point = Point::new(coord.x, coord.y);
            validate_geographic_point(&point).map_err(|e| {
                SpatioError::InvalidInput(format!(
                    "Interior ring {} point at index {}: {}",
                    ring_idx, idx, e
                ))
            })?;
        }
    }

    Ok(())
}

/// Validates a radius for spatial queries.
///
/// Ensures radius is positive, finite, and not exceeding Earth's circumference.
///
/// # Examples
///
/// ```
/// use spatio::compute::validation::validate_radius;
///
/// assert!(validate_radius(1000.0).is_ok());
/// assert!(validate_radius(0.0).is_err());
/// assert!(validate_radius(-100.0).is_err());
/// assert!(validate_radius(f64::NAN).is_err());
/// ```
pub fn validate_radius(radius: f64) -> Result<()> {
    if !radius.is_finite() {
        return Err(SpatioError::InvalidInput(format!(
            "Radius must be finite, got: {}",
            radius
        )));
    }
    if radius <= 0.0 {
        return Err(SpatioError::InvalidInput(format!(
            "Radius must be positive, got: {}",
            radius
        )));
    }
    const EARTH_CIRCUMFERENCE: f64 = 40_075_000.0; // meters
    if radius > EARTH_CIRCUMFERENCE {
        return Err(SpatioError::InvalidInput(format!(
            "Radius {} exceeds Earth's circumference ({} meters)",
            radius, EARTH_CIRCUMFERENCE
        )));
    }
    Ok(())
}

/// Validates a bounding box.
///
/// Ensures coordinates are valid and min < max for both dimensions.
///
/// # Examples
///
/// ```
/// use spatio::compute::validation::validate_bbox;
///
/// assert!(validate_bbox(-10.0, -10.0, 10.0, 10.0).is_ok());
/// assert!(validate_bbox(10.0, -10.0, -10.0, 10.0).is_err()); // min > max
/// ```
pub fn validate_bbox(min_lon: f64, min_lat: f64, max_lon: f64, max_lat: f64) -> Result<()> {
    // Validate all coordinates
    let min_point = Point::new(min_lon, min_lat);
    let max_point = Point::new(max_lon, max_lat);
    validate_geographic_point(&min_point)?;
    validate_geographic_point(&max_point)?;

    // Ensure min < max
    if min_lon >= max_lon {
        return Err(SpatioError::InvalidInput(format!(
            "min_lon ({}) must be < max_lon ({})",
            min_lon, max_lon
        )));
    }
    if min_lat >= max_lat {
        return Err(SpatioError::InvalidInput(format!(
            "min_lat ({}) must be < max_lat ({})",
            min_lat, max_lat
        )));
    }

    Ok(())
}

/// Validates a 3D bounding box.
pub fn validate_bbox_3d(
    min_lon: f64,
    min_lat: f64,
    min_alt: f64,
    max_lon: f64,
    max_lat: f64,
    max_alt: f64,
) -> Result<()> {
    let min_point = Point3d::new(min_lon, min_lat, min_alt);
    let max_point = Point3d::new(max_lon, max_lat, max_alt);
    validate_geographic_point_3d(&min_point)?;
    validate_geographic_point_3d(&max_point)?;

    if min_lon >= max_lon {
        return Err(SpatioError::InvalidInput(format!(
            "min_lon ({}) must be < max_lon ({})",
            min_lon, max_lon
        )));
    }
    if min_lat >= max_lat {
        return Err(SpatioError::InvalidInput(format!(
            "min_lat ({}) must be < max_lat ({})",
            min_lat, max_lat
        )));
    }
    if min_alt >= max_alt {
        return Err(SpatioError::InvalidInput(format!(
            "min_alt ({}) must be < max_alt ({})",
            min_alt, max_alt
        )));
    }

    Ok(())
}

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

    #[test]
    fn test_valid_geographic_point() {
        let nyc = Point::new(-74.0060, 40.7128);
        assert!(validate_geographic_point(&nyc).is_ok());

        let london = Point::new(-0.1278, 51.5074);
        assert!(validate_geographic_point(&london).is_ok());

        let tokyo = Point::new(139.6917, 35.6895);
        assert!(validate_geographic_point(&tokyo).is_ok());

        // Edge cases
        let max_lon = Point::new(180.0, 0.0);
        assert!(validate_geographic_point(&max_lon).is_ok());

        let min_lon = Point::new(-180.0, 0.0);
        assert!(validate_geographic_point(&min_lon).is_ok());

        let max_lat = Point::new(0.0, 90.0);
        assert!(validate_geographic_point(&max_lat).is_ok());

        let min_lat = Point::new(0.0, -90.0);
        assert!(validate_geographic_point(&min_lat).is_ok());
    }

    #[test]
    fn test_invalid_longitude() {
        let invalid = Point::new(200.0, 40.0);
        assert!(validate_geographic_point(&invalid).is_err());

        let invalid = Point::new(-200.0, 40.0);
        assert!(validate_geographic_point(&invalid).is_err());

        let invalid = Point::new(180.1, 40.0);
        assert!(validate_geographic_point(&invalid).is_err());
    }

    #[test]
    fn test_invalid_latitude() {
        let invalid = Point::new(-74.0, 95.0);
        assert!(validate_geographic_point(&invalid).is_err());

        let invalid = Point::new(-74.0, -95.0);
        assert!(validate_geographic_point(&invalid).is_err());

        let invalid = Point::new(-74.0, 90.1);
        assert!(validate_geographic_point(&invalid).is_err());
    }

    #[test]
    fn test_non_finite_coordinates() {
        let nan_lon = Point::new(f64::NAN, 40.0);
        assert!(validate_geographic_point(&nan_lon).is_err());

        let nan_lat = Point::new(-74.0, f64::NAN);
        assert!(validate_geographic_point(&nan_lat).is_err());

        let inf_lon = Point::new(f64::INFINITY, 40.0);
        assert!(validate_geographic_point(&inf_lon).is_err());

        let inf_lat = Point::new(-74.0, f64::INFINITY);
        assert!(validate_geographic_point(&inf_lat).is_err());
    }

    #[test]
    fn test_valid_3d_point() {
        let drone = Point3d::new(-74.0060, 40.7128, 100.0);
        assert!(validate_geographic_point_3d(&drone).is_ok());

        let sea_level = Point3d::new(-74.0, 40.7, 0.0);
        assert!(validate_geographic_point_3d(&sea_level).is_ok());

        let underwater = Point3d::new(-74.0, 40.7, -100.0);
        assert!(validate_geographic_point_3d(&underwater).is_ok());

        let airplane = Point3d::new(-74.0, 40.7, 10000.0);
        assert!(validate_geographic_point_3d(&airplane).is_ok());
    }

    #[test]
    fn test_invalid_altitude() {
        let too_high = Point3d::new(-74.0, 40.7, 200000.0);
        assert!(validate_geographic_point_3d(&too_high).is_err());

        let too_low = Point3d::new(-74.0, 40.7, -20000.0);
        assert!(validate_geographic_point_3d(&too_low).is_err());

        let nan_alt = Point3d::new(-74.0, 40.7, f64::NAN);
        assert!(validate_geographic_point_3d(&nan_alt).is_err());
    }

    #[test]
    fn test_validate_multiple_points() {
        let valid_points = vec![
            Point::new(-74.0, 40.7),
            Point::new(-73.9, 40.8),
            Point::new(-74.1, 40.6),
        ];
        assert!(validate_points(&valid_points).is_ok());

        let invalid_points = vec![
            Point::new(-74.0, 40.7),
            Point::new(999.0, 40.0), // Invalid
            Point::new(-74.1, 40.6),
        ];
        assert!(validate_points(&invalid_points).is_err());
    }

    #[test]
    fn test_validate_polygon() {
        use geo::polygon;
        use spatio_types::geo::Polygon;

        let valid_poly = polygon![
            (x: -80.0, y: 35.0),
            (x: -70.0, y: 35.0),
            (x: -70.0, y: 45.0),
            (x: -80.0, y: 45.0),
            (x: -80.0, y: 35.0),
        ];
        assert!(validate_polygon(&Polygon::from(valid_poly)).is_ok());

        let invalid_poly = polygon![
            (x: -80.0, y: 35.0),
            (x: 200.0, y: 35.0),  // Invalid longitude
            (x: -70.0, y: 45.0),
            (x: -80.0, y: 45.0),
        ];
        assert!(validate_polygon(&Polygon::from(invalid_poly)).is_err());
    }

    #[test]
    fn test_validate_radius() {
        assert!(validate_radius(1000.0).is_ok());
        assert!(validate_radius(0.1).is_ok());
        assert!(validate_radius(1_000_000.0).is_ok());

        assert!(validate_radius(0.0).is_err());
        assert!(validate_radius(-100.0).is_err());
        assert!(validate_radius(f64::NAN).is_err());
        assert!(validate_radius(f64::INFINITY).is_err());
        assert!(validate_radius(50_000_000.0).is_err()); // > Earth circumference
    }

    #[test]
    fn test_validate_bbox() {
        assert!(validate_bbox(-10.0, -10.0, 10.0, 10.0).is_ok());
        assert!(validate_bbox(-180.0, -90.0, 180.0, 90.0).is_ok());

        // min >= max errors
        assert!(validate_bbox(10.0, -10.0, -10.0, 10.0).is_err());
        assert!(validate_bbox(-10.0, 10.0, 10.0, -10.0).is_err());
        assert!(validate_bbox(10.0, 10.0, 10.0, 10.0).is_err());

        // Invalid coordinates
        assert!(validate_bbox(-200.0, -10.0, 10.0, 10.0).is_err());
        assert!(validate_bbox(-10.0, -100.0, 10.0, 10.0).is_err());
    }

    #[test]
    fn test_validate_bbox_3d() {
        assert!(validate_bbox_3d(-10.0, -10.0, 0.0, 10.0, 10.0, 1000.0).is_ok());

        // Altitude validation
        assert!(validate_bbox_3d(-10.0, -10.0, 1000.0, 10.0, 10.0, 0.0).is_err());
        assert!(validate_bbox_3d(-10.0, -10.0, -20000.0, 10.0, 10.0, 0.0).is_err());
    }
}