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
use crate::{
    Contains, ConvexHull, Coord, CoordNum, GeoFloat, Intersects, LineString, MultiPoint, Point,
    Polygon,
};
use num_traits::Float;
use rstar::RTreeNum;
use std::cmp::max;

const K_MULTIPLIER: f32 = 1.5;

/// Another approach for [concave hull](trait.algorithm.ConcaveHull.html). This algorithm is based
/// on a [k nearest neighbours approach](https://pdfs.semanticscholar.org/2397/17005c3ebd5d6a42fc833daf97a0edee1ce4.pdf)
/// by Adriano Moreira and Maribel Santos.
///
/// The idea of the algorithm is simple:
/// 1. Find a point on a future hull (e. g. a point with the smallest Y coordinate).
/// 2. Find K nearest neighbours to the chosen point.
/// 3. As the next point on the hull chose one of the nearest points, that would make the largest
///    left hand turn from the previous segment.
/// 4. Repeat 2-4.
///
/// In cases when the hull cannot be calculated for the given K, a larger value is chosen and
/// calculation starts from the beginning.
///
/// In the worst case scenario, when no K can be found to build a correct hull, the convex hull is
/// returned.
///
/// This algorithm is generally several times slower then the one used in the
/// [ConcaveHull](trait.algorithm.ConcaveHull.html) trait, but gives better results and
/// does not require manual coefficient adjustment.
///
/// The larger K is given to the algorithm, the more "smooth" the hull will generally be, but the
/// longer calculation may take. If performance is not critical, K=3 is a safe value to set
/// (lower values do not make sense for this algorithm). If K is equal or larger than the number of
/// input points, the convex hull will be produced.
pub trait KNearestConcaveHull {
    type Scalar: CoordNum;
    fn k_nearest_concave_hull(&self, k: u32) -> Polygon<Self::Scalar>;
}

impl<T> KNearestConcaveHull for Vec<Point<T>>
where
    T: GeoFloat + RTreeNum,
{
    type Scalar = T;
    fn k_nearest_concave_hull(&self, k: u32) -> Polygon<Self::Scalar> {
        concave_hull(self.iter().map(|point| &point.0), k)
    }
}

impl<T> KNearestConcaveHull for [Point<T>]
where
    T: GeoFloat + RTreeNum,
{
    type Scalar = T;
    fn k_nearest_concave_hull(&self, k: u32) -> Polygon<Self::Scalar> {
        concave_hull(self.iter().map(|point| &point.0), k)
    }
}

impl<T> KNearestConcaveHull for Vec<Coord<T>>
where
    T: GeoFloat + RTreeNum,
{
    type Scalar = T;
    fn k_nearest_concave_hull(&self, k: u32) -> Polygon<Self::Scalar> {
        concave_hull(self.iter(), k)
    }
}

impl<T> KNearestConcaveHull for [Coord<T>]
where
    T: GeoFloat + RTreeNum,
{
    type Scalar = T;
    fn k_nearest_concave_hull(&self, k: u32) -> Polygon<Self::Scalar> {
        concave_hull(self.iter(), k)
    }
}

impl<T> KNearestConcaveHull for MultiPoint<T>
where
    T: GeoFloat + RTreeNum,
{
    type Scalar = T;
    fn k_nearest_concave_hull(&self, k: u32) -> Polygon<Self::Scalar> {
        concave_hull(self.iter().map(|point| &point.0), k)
    }
}

fn concave_hull<'a, T: 'a>(coords: impl Iterator<Item = &'a Coord<T>>, k: u32) -> Polygon<T>
where
    T: GeoFloat + RTreeNum,
{
    let dataset = prepare_dataset(coords);
    concave_hull_inner(dataset, k)
}

const DELTA: f32 = 0.000000001;

/// Removes duplicate coords from the dataset.
fn prepare_dataset<'a, T: 'a>(coords: impl Iterator<Item = &'a Coord<T>>) -> rstar::RTree<Coord<T>>
where
    T: GeoFloat + RTreeNum,
{
    let mut dataset: rstar::RTree<Coord<T>> = rstar::RTree::new();
    for coord in coords {
        let closest = dataset.nearest_neighbor(coord);
        if let Some(closest) = closest {
            if coords_are_equal(coord, closest) {
                continue;
            }
        }

        dataset.insert(*coord)
    }

    dataset
}

/// The points are considered equal, if both coordinate values are same with 0.0000001% range
/// (see the value of DELTA constant).
fn coords_are_equal<T>(c1: &Coord<T>, c2: &Coord<T>) -> bool
where
    T: GeoFloat + RTreeNum,
{
    float_equal(c1.x, c2.x) && float_equal(c1.y, c2.y)
}

fn float_equal<T>(a: T, b: T) -> bool
where
    T: GeoFloat,
{
    let da = a * T::from(DELTA)
        .expect("Conversion from constant is always valid.")
        .abs();
    b > (a - da) && b < (a + da)
}

fn polygon_from_tree<T>(dataset: &rstar::RTree<Coord<T>>) -> Polygon<T>
where
    T: GeoFloat + RTreeNum,
{
    assert!(dataset.size() <= 3);

    let mut coords: Vec<Coord<T>> = dataset.iter().cloned().collect();
    if !coords.is_empty() {
        // close the linestring provided it's not empty
        coords.push(coords[0]);
    }

    Polygon::new(LineString::from(coords), vec![])
}

fn concave_hull_inner<T>(original_dataset: rstar::RTree<Coord<T>>, k: u32) -> Polygon<T>
where
    T: GeoFloat + RTreeNum,
{
    let set_length = original_dataset.size();
    if set_length <= 3 {
        return polygon_from_tree(&original_dataset);
    }
    if k >= set_length as u32 {
        return fall_back_hull(&original_dataset);
    }

    let k_adjusted = adjust_k(k);
    let mut dataset = original_dataset.clone();

    let first_coord = get_first_coord(&dataset);
    let mut hull = vec![first_coord];

    let mut current_coord = first_coord;
    dataset.remove(&first_coord);

    let mut prev_coord = current_coord;
    let mut curr_step = 2;
    while (current_coord != first_coord || curr_step == 2) && dataset.size() > 0 {
        if curr_step == 5 {
            dataset.insert(first_coord);
        }

        let mut nearest_coords: Vec<_> =
            get_nearest_coords(&dataset, &current_coord, k_adjusted).collect();
        sort_by_angle(&mut nearest_coords, &current_coord, &prev_coord);

        let selected = nearest_coords
            .iter()
            .find(|x| !intersects(&hull, &[&current_coord, x]));

        if let Some(sel) = selected {
            prev_coord = current_coord;
            current_coord = **sel;
            hull.push(current_coord);
            dataset.remove(&current_coord);

            curr_step += 1;
        } else {
            return concave_hull_inner(original_dataset, get_next_k(k_adjusted));
        }
    }

    let poly = Polygon::new(LineString::from(hull), vec![]);

    if original_dataset
        .iter()
        .any(|&coord| !coord_inside(&coord, &poly))
    {
        return concave_hull_inner(original_dataset, get_next_k(k_adjusted));
    }

    poly
}

fn fall_back_hull<T>(dataset: &rstar::RTree<Coord<T>>) -> Polygon<T>
where
    T: GeoFloat + RTreeNum,
{
    let multipoint = MultiPoint::from(dataset.iter().cloned().collect::<Vec<Coord<T>>>());
    multipoint.convex_hull()
}

fn get_next_k(curr_k: u32) -> u32 {
    max(curr_k + 1, ((curr_k as f32) * K_MULTIPLIER) as u32)
}

fn adjust_k(k: u32) -> u32 {
    max(k, 3)
}

fn get_first_coord<T>(coord_set: &rstar::RTree<Coord<T>>) -> Coord<T>
where
    T: GeoFloat + RTreeNum,
{
    let mut min_y = Float::max_value();
    let mut result = coord_set
        .iter()
        .next()
        .expect("We checked that there are more then 3 coords in the set before.");

    for coord in coord_set.iter() {
        if coord.y < min_y {
            min_y = coord.y;
            result = coord;
        }
    }

    *result
}

fn get_nearest_coords<'a, T>(
    dataset: &'a rstar::RTree<Coord<T>>,
    base_coord: &Coord<T>,
    candidate_no: u32,
) -> impl Iterator<Item = &'a Coord<T>>
where
    T: GeoFloat + RTreeNum,
{
    dataset
        .nearest_neighbor_iter(base_coord)
        .take(candidate_no as usize)
}

fn sort_by_angle<T>(coords: &mut [&Coord<T>], curr_coord: &Coord<T>, prev_coord: &Coord<T>)
where
    T: GeoFloat,
{
    let base_angle = pseudo_angle(prev_coord.x - curr_coord.x, prev_coord.y - curr_coord.y);
    coords.sort_by(|a, b| {
        let mut angle_a = pseudo_angle(a.x - curr_coord.x, a.y - curr_coord.y) - base_angle;
        if angle_a < T::zero() {
            angle_a = angle_a + T::from(4.0).unwrap();
        }

        let mut angle_b = pseudo_angle(b.x - curr_coord.x, b.y - curr_coord.y) - base_angle;
        if angle_b < T::zero() {
            angle_b = angle_b + T::from(4.0).unwrap();
        }

        angle_a.partial_cmp(&angle_b).unwrap().reverse()
    });
}

fn pseudo_angle<T>(dx: T, dy: T) -> T
where
    T: GeoFloat,
{
    if dx == T::zero() && dy == T::zero() {
        return T::zero();
    }

    let p = dx / (dx.abs() + dy.abs());
    if dy < T::zero() {
        T::from(3.).unwrap() + p
    } else {
        T::from(1.).unwrap() - p
    }
}

fn intersects<T>(hull: &[Coord<T>], line: &[&Coord<T>; 2]) -> bool
where
    T: GeoFloat,
{
    // This is the case of finishing the contour.
    if *line[1] == hull[0] {
        return false;
    }

    let coords = hull.iter().take(hull.len() - 1).cloned().collect();
    let linestring = LineString::new(coords);
    let line = crate::Line::new(*line[0], *line[1]);
    linestring.intersects(&line)
}

fn coord_inside<T>(coord: &Coord<T>, poly: &Polygon<T>) -> bool
where
    T: GeoFloat,
{
    poly.contains(coord) || poly.exterior().contains(coord)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::coords_iter::CoordsIter;
    use crate::geo_types::coord;

    #[test]
    fn coord_ordering() {
        let coords = vec![
            coord!(x: 1.0, y: 1.0),
            coord!(x: -1.0, y: 0.0),
            coord!(x: 0.0, y: 1.0),
            coord!(x: 1.0, y: 0.0),
        ];

        let mut coords_mapped: Vec<&Coord<f32>> = coords.iter().collect();

        let center = coord!(x: 0.0, y: 0.0);
        let prev_coord = coord!(x: 1.0, y: 1.0);

        let expected = vec![&coords[3], &coords[1], &coords[2], &coords[0]];

        sort_by_angle(&mut coords_mapped, &center, &prev_coord);
        assert_eq!(coords_mapped, expected);

        let expected = vec![&coords[1], &coords[2], &coords[0], &coords[3]];

        let prev_coord = coord!(x: 1.0, y: -1.0);
        sort_by_angle(&mut coords_mapped, &center, &prev_coord);
        assert_eq!(coords_mapped, expected);
    }

    #[test]
    fn get_first_coord_test() {
        let coords = vec![
            coord!(x: 1.0, y: 1.0),
            coord!(x: -1.0, y: 0.0),
            coord!(x: 0.0, y: 1.0),
            coord!(x: 0.0, y: 0.5),
        ];
        let tree = rstar::RTree::bulk_load(coords);
        let first = coord!(x: -1.0, y: 0.0);

        assert_eq!(get_first_coord(&tree), first);
    }

    #[test]
    fn concave_hull_test() {
        let coords = vec![
            coord!(x: 0.0, y: 0.0),
            coord!(x: 1.0, y: 0.0),
            coord!(x: 2.0, y: 0.0),
            coord!(x: 3.0, y: 0.0),
            coord!(x: 0.0, y: 1.0),
            coord!(x: 1.0, y: 1.0),
            coord!(x: 2.0, y: 1.0),
            coord!(x: 3.0, y: 1.0),
            coord!(x: 0.0, y: 2.0),
            coord!(x: 1.0, y: 2.5),
            coord!(x: 2.0, y: 2.5),
            coord!(x: 3.0, y: 2.0),
            coord!(x: 0.0, y: 3.0),
            coord!(x: 3.0, y: 3.0),
        ];

        let poly = concave_hull(coords.iter(), 3);
        assert_eq!(poly.exterior().coords_count(), 12);

        let must_not_be_in = vec![&coords[6]];
        for coord in poly.exterior().coords_iter() {
            for not_coord in must_not_be_in.iter() {
                assert_ne!(&coord, *not_coord);
            }
        }
    }

    #[test]
    fn empty_hull() {
        let actual: Polygon<f64> = concave_hull(vec![].iter(), 3);
        let expected = Polygon::new(LineString::new(vec![]), vec![]);
        assert_eq!(actual, expected);
    }
}