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
use std::convert::TryInto;

use geo::{Geometry, Line, LineString, Point, Polygon, Rect, Triangle};
use thiserror::Error;

#[cfg(feature = "parallel")]
use rayon::prelude::*;

#[derive(Error, Debug, PartialEq, Clone)]
pub enum Error {
    #[error("Inifinite or NaN coordinate value in geo at index {0:?}: {1:?}")]
    BadCoordinateValue(usize, Geometry<f64>),

    #[error("max_distance must be finite and greater than or equal to zero: {0:?}")]
    BadMaxDistance(f64),

    #[error("LineString at index {0:?} must have at least two points")]
    LineStringTooSmall(usize),

    #[error("Polygon at index {0:?} must have an exterior with at least three points")]
    PolygonExteriorTooSmall(usize),
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Interaction {
    Intersects,
    Within,
    Contains,
}

#[derive(Default, Debug, PartialEq, Clone)]
pub struct Config {
    pub max_distance: f64,
}

impl Config {
    pub fn new() -> Config {
        Default::default()
    }

    pub fn max_distance(self, value: f64) -> Config {
        Config {
            max_distance: value,
            ..self
        }
    }

    pub fn validate(&self) -> Option<Error> {
        if !(self.max_distance.is_finite() && self.max_distance >= 0.) {
            return Some(Error::BadMaxDistance(self.max_distance));
        }

        None
    }

    pub fn serial<T, U>(self, small: T) -> Result<super::SpatialIndex, Error>
    where
        T: TryInto<SplitGeoSeq, Error = U>,
        U: std::any::Any,
    {
        if let Some(error) = self.validate() {
            return Err(error);
        }
        super::SpatialIndex::new(small, self)
    }

    #[cfg(feature = "parallel")]
    pub fn parallel<T, U>(self, small: T) -> Result<super::ParSpatialIndex, Error>
    where
        T: TryInto<Par<SplitGeoSeq>, Error = U>,
        U: std::any::Any,
    {
        if let Some(error) = self.validate() {
            return Err(error);
        }
        super::ParSpatialIndex::new(small, self)
    }
}

pub struct Par<T>(pub T);

#[derive(Default, PartialEq, Debug, Clone)]
pub(crate) struct SplitGeo {
    pub points: Vec<Point<f64>>,
    pub lines: Vec<Line<f64>>,
    pub polys: Vec<Polygon<f64>>,
    pub line_strings: Vec<LineString<f64>>,
    pub rects: Vec<Rect<f64>>,
    pub tris: Vec<Triangle<f64>>,
}

// just to make testing easier
impl SplitGeoSeq {
    // FIXME: move to_vec into naive::
    pub fn to_vec(&self) -> Vec<Geometry<f64>> {
        let mut result = vec![
            Geometry::Point(Point::new(0., 0.));
            self.geos.points.len()
                + self.geos.lines.len()
                + self.geos.polys.len()
                + self.geos.line_strings.len()
                + self.geos.rects.len()
                + self.geos.tris.len()
        ];
        for (i, g) in self
            .indexes
            .points
            .iter()
            .zip(self.geos.points.iter().cloned())
        {
            result[i] = g.into();
        }
        for (i, g) in self
            .indexes
            .lines
            .iter()
            .zip(self.geos.lines.iter().cloned())
        {
            result[i] = g.into();
        }
        for (i, g) in self
            .indexes
            .polys
            .iter()
            .zip(self.geos.polys.iter().cloned())
        {
            result[i] = g.into();
        }
        for (i, g) in self
            .indexes
            .line_strings
            .iter()
            .zip(self.geos.line_strings.iter().cloned())
        {
            result[i] = g.into();
        }
        for (i, g) in self
            .indexes
            .rects
            .iter()
            .zip(self.geos.rects.iter().cloned())
        {
            result[i] = g.into();
        }
        for (i, g) in self.indexes.tris.iter().zip(self.geos.tris.iter().cloned()) {
            result[i] = g.into();
        }
        result
    }

    pub fn merge(mut a: SplitGeoSeq, mut b: SplitGeoSeq) -> SplitGeoSeq {
        a.geos.points.append(&mut b.geos.points);
        a.geos.lines.append(&mut b.geos.lines);
        a.geos.polys.append(&mut b.geos.polys);
        a.geos.line_strings.append(&mut b.geos.line_strings);
        a.geos.rects.append(&mut b.geos.rects);
        a.geos.tris.append(&mut b.geos.tris);

        a.indexes.points = a.indexes.points.merge(b.indexes.points);
        a.indexes.lines = a.indexes.lines.merge(b.indexes.lines);
        a.indexes.line_strings = a.indexes.line_strings.merge(b.indexes.line_strings);
        a.indexes.polys = a.indexes.polys.merge(b.indexes.polys);
        a.indexes.rects = a.indexes.rects.merge(b.indexes.rects);
        a.indexes.tris = a.indexes.tris.merge(b.indexes.tris);

        a
    }

    pub fn fixup(&mut self) {
        // because parallel reductions might not
    }
}

lazy_static::lazy_static! {
    static ref EMPTY_VEC: Vec<usize> = vec![];
}

// Sigh...maybe we should just replace this with IDLBitRange
#[derive(PartialEq, Debug, Clone)]
pub(crate) enum Indexes {
    Explicit(Vec<usize>),
    Range(std::ops::Range<usize>),
}

impl Default for Indexes {
    fn default() -> Self {
        Indexes::Range(0..0)
    }
}
impl Indexes {
    pub fn push(&mut self, index: usize) {
        match self {
            Indexes::Explicit(v) => {
                if let Some(last) = v.last() {
                    assert!(*last <= index);
                }
                v.push(index);
            }
            Indexes::Range(r) => {
                if r.end == index {
                    r.end = index + 1;
                } else {
                    let mut v: Vec<usize> = r.collect();
                    v.push(index);
                    *self = Indexes::Explicit(v);
                }
            }
        }
    }

    fn range(&self) -> std::ops::Range<usize> {
        match self {
            Indexes::Range(r) => r.clone(),
            _ => std::ops::Range {
                start: 0 as usize,
                end: 0 as usize,
            },
        }
    }

    pub fn into_iter(self) -> impl Iterator<Item = usize> {
        self.range().chain(match self {
            Indexes::Range(_) => vec![].into_iter(),
            Indexes::Explicit(v) => v.into_iter(),
        })
    }

    pub fn iter(&self) -> impl Iterator<Item = usize> + '_ {
        self.range().chain(match self {
            Indexes::Range(_) => EMPTY_VEC.iter().copied(),
            Indexes::Explicit(v) => v.iter().copied(),
        })
    }

    #[cfg(feature = "parallel")]
    pub fn into_par_iter(self) -> impl rayon::iter::IndexedParallelIterator<Item = usize> {
        self.range().into_par_iter().chain(match self {
            Indexes::Range(_) => vec![].into_par_iter(),
            Indexes::Explicit(v) => v.into_par_iter(),
        })
    }

    pub fn get(&self, index: usize) -> usize {
        match self {
            Indexes::Range(r) => index + r.start,
            Indexes::Explicit(v) => v[index],
        }
    }

    pub fn add_offset(&self, offset: usize) -> Self {
        match self {
            Indexes::Range(r) => Indexes::Range(std::ops::Range {
                start: r.start + offset,
                end: r.end + offset,
            }),
            Indexes::Explicit(v) => {
                Indexes::Explicit(v.iter().map(|value| value + offset).collect())
            }
        }
    }

    pub fn merge(self, other: Indexes) -> Indexes {
        // This is more complicated than it should be because rayon's
        // reduce makes no guarantees about order.
        fn maybe_range(seq: &Vec<usize>) -> Option<std::ops::Range<usize>> {
            if !seq.is_empty() {
                // hmmm...by construction, min,max should always be seq[0],seq[len-1]
                let min = seq.iter().min().unwrap();
                let max = seq.iter().max().unwrap();
                if (max - min) + 1 == seq.len() {
                    return Some(*min..(max + 1));
                }
            }
            None
        }

        fn is_empty(r: &std::ops::Range<usize>) -> bool {
            // not in stable yet, sigh
            r.start == r.end
        }

        fn join_ranges(a: std::ops::Range<usize>, b: std::ops::Range<usize>) -> Indexes {
            if is_empty(&a) {
                return Indexes::Range(b);
            };
            if is_empty(&b) {
                return Indexes::Range(a);
            };

            if a.end == b.start {
                Indexes::Range(a.start..b.end + 1)
            } else if b.end == a.start {
                Indexes::Range(b.start..a.end + 1)
            } else {
                let (a, b) = if a.end < b.start { (a, b) } else { (b, a) };
                Indexes::Explicit(a.chain(b).collect())
            }
        }

        fn join_vec(mut a: Vec<usize>, mut b: Vec<usize>) -> Indexes {
            if a.is_empty() {
                return Indexes::Explicit(b);
            }
            if b.is_empty() {
                return Indexes::Explicit(a);
            }

            // Hmmm...the duplication here suggests that we should be
            // recursing down.
            match (maybe_range(&a), maybe_range(&b)) {
                (Some(a), Some(b)) => join_ranges(a, b),
                (Some(a), None) => join_range_vec(a, b),
                (None, Some(b)) => join_range_vec(b, a),
                (None, None) => Indexes::Explicit(if a[0] <= b[0] {
                    a.append(&mut b);
                    a
                } else {
                    b.append(&mut a);
                    b
                }),
            }
        }

        fn join_range_vec(a: std::ops::Range<usize>, b: Vec<usize>) -> Indexes {
            if b.is_empty() {
                // Do b first because if they're both empty, we prefer
                // a Range representation.
                return Indexes::Range(a);
            }
            if is_empty(&a) {
                return Indexes::Explicit(b);
            }

            match maybe_range(&b) {
                Some(b) => join_ranges(a, b),
                None => Indexes::Explicit(if a.end < b[0] {
                    a.chain(b.into_iter()).collect()
                } else {
                    b.into_iter().chain(a).collect()
                }),
            }
        }

        match (self, other) {
            (Indexes::Range(a), Indexes::Range(b)) => join_ranges(a, b),
            (Indexes::Range(a), Indexes::Explicit(b)) => join_range_vec(a, b),
            (Indexes::Explicit(a), Indexes::Range(b)) => join_range_vec(b, a),
            (Indexes::Explicit(a), Indexes::Explicit(b)) => join_vec(a, b),
        }
    }
}

#[derive(Default, PartialEq, Debug, Clone)]
pub(crate) struct SplitGeoIndexes {
    pub points: Indexes,
    pub lines: Indexes,
    pub polys: Indexes,
    pub line_strings: Indexes,
    pub rects: Indexes,
    pub tris: Indexes,
}

#[derive(Default, PartialEq, Debug, Clone)]
pub struct SplitGeoSeq {
    pub(crate) geos: SplitGeo,
    pub(crate) indexes: SplitGeoIndexes,
}

#[derive(Clone, Copy, Debug)]
pub struct ProxMapRow {
    pub big_index: usize,
    pub small_index: usize,
    pub distance: f64,
}

impl Eq for ProxMapRow {}

impl PartialEq for ProxMapRow {
    fn eq(&self, other: &Self) -> bool {
        (self.big_index, self.small_index) == (other.big_index, other.small_index)
    }
}

impl PartialOrd for ProxMapRow {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for ProxMapRow {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        (self.big_index, self.small_index).cmp(&(other.big_index, other.small_index))
    }
}

#[derive(Clone, Debug)]
pub struct ProxMapGeoRow {
    pub big_index: usize,
    pub small_index: usize,
    pub big: Geometry<f64>,
    pub small: Geometry<f64>,
    pub distance: f64,
}

impl Eq for ProxMapGeoRow {}

impl PartialEq for ProxMapGeoRow {
    fn eq(&self, other: &Self) -> bool {
        (self.big_index, self.small_index) == (other.big_index, other.small_index)
    }
}

impl PartialOrd for ProxMapGeoRow {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for ProxMapGeoRow {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        (self.big_index, self.small_index).cmp(&(other.big_index, other.small_index))
    }
}

#[derive(Clone, Copy, PartialEq, Eq, Debug, PartialOrd, Ord)]
pub struct SJoinRow {
    pub big_index: usize,
    pub small_index: usize,
}

#[derive(Clone, Debug)]
pub struct SJoinGeoRow {
    pub big_index: usize,
    pub small_index: usize,
    pub big: Geometry<f64>,
    pub small: Geometry<f64>,
}

impl Eq for SJoinGeoRow {}

impl PartialEq for SJoinGeoRow {
    fn eq(&self, other: &Self) -> bool {
        (self.big_index, self.small_index) == (other.big_index, other.small_index)
    }
}

impl PartialOrd for SJoinGeoRow {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for SJoinGeoRow {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        (self.big_index, self.small_index).cmp(&(other.big_index, other.small_index))
    }
}