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
// src/ops/simplify_vw.rs
//! Visvalingam–Whyatt simplification, vouched.
//!
//! # The method
//!
//! Visvalingam and Whyatt (*Line generalisation by repeated elimination of
//! points*, The Cartographic Journal 30(1), 1993) rank every vertex by its
//! **effective area**: the area of the triangle it forms with its two
//! current neighbors. The vertex with the smallest effective area is
//! removed, its two neighbors' areas are recomputed against their new
//! neighbors, and the elimination repeats. [`simplify_vw`] stops when the
//! smallest effective area is at or above the threshold.
//!
//! The elimination, exactly:
//!
//! 1. **Fixed vertices.** A line's two endpoints are never removed. A closed
//! line (first vertex equal to the last) keeps at least one vertex
//! between them, so it stays two distinct points; unlike the
//! Douglas–Peucker `simplify`, which treats a closed line as a ring, a
//! line's endpoints are fixed here whether or not they coincide. A ring
//! keeps at least three vertices: once it has three, none is removed.
//! 2. **The effective area** of a vertex `b` with current neighbors `a`
//! (before) and `c` (after) is `|(b − a) × (c − a)| / 2`, computed in
//! `f64` exactly as written: `((b.x − a.x)·(c.y − a.y) − (b.y − a.y)·(c.x −
//! a.x)).abs() · 0.5`. A non-finite value (products overflowing at
//! coordinates above about `1e154`) counts as `+∞`, so the vertex is kept.
//! A ring's vertices all have neighbors, cyclically.
//! 3. **A vertex whose two neighbors are the same point is not removable**
//! while they are: removing it would leave two equal consecutive
//! vertices, which no line or ring may have. (Its area is then 0, so
//! without this rule it would be the first to go.) It becomes removable
//! again if a neighbor changes.
//! 4. **Selection.** Among the removable vertices, the one with the smallest
//! effective area is taken; ties go to the vertex earlier in the input,
//! so the result is deterministic.
//! 5. **Stop or remove.** The selected vertex is removed if its area is
//! below the threshold, or is exactly `0.0`; otherwise the elimination
//! stops, since every other removable vertex has at least that area.
//! 6. **After a removal,** the two neighbors' areas are recomputed against
//! their new neighbors.
//!
//! **Zero areas.** The paper's step 2 deletes every point of zero area
//! first. Here zero-area vertices go through the same queue, which takes
//! them first because 0 is the smallest area; a vertex made collinear by an
//! earlier removal is then removed too. So a threshold of 0 removes exactly
//! the vertices whose effective area computes as `0.0` in `f64`: collinear
//! ones, or ones within rounding of collinear.
//!
//! **The paper's monotone rule.** When a point is selected, "if its
//! calculated area is less than that of the last point to be eliminated,
//! use the latter's area instead. This ensures that the current point
//! cannot be eliminated without eliminating previously eliminated points"
//! (Visvalingam & Whyatt 1993, the algorithm's step 3). The rule fixes the
//! area *recorded* for the eliminated point, the rank the paper stores for
//! filtering at run time; the selection itself is on the calculated areas.
//! The internal routine records exactly that. For a threshold run it never
//! changes which vertices are removed: by induction, every recorded area so
//! far is below the threshold (or 0 at a threshold of 0), so the *recorded*
//! area `max(calculated, last)` is below the threshold exactly when the
//! calculated one is.
//!
//! # Selection rule, and the vouch
//!
//! **The effective areas are a selection rule, computed in `f64`.** They decide
//! which vertices are removed. Comparing triangle areas exactly needs exact
//! triangle-area comparisons that `arithmetica` does not yet offer. An area
//! within rounding of the threshold, or tied with another, may go either way.
//! That choice is never a correctness claim, because of the vouch.
//!
//! **The result is vouched, or refused.** Each line and ring is simplified
//! independently, as [`simplify`](crate::types::Polygon::simplify) does,
//! and the result is built through the checked constructors and then judged
//! by [`validity_issues`]: the same exact checks
//! [`validate`](super::validate()) makes. A result with any issue is
//! refused with [`UnvouchedReason::SimplifiedInvalid`]. A result that
//! cannot be built at all (a ring left with three collinear vertices) is
//! refused with its constructor's error. Visvalingam–Whyatt does **not**
//! preserve topology: rings can come to cross, holes to escape, parts to
//! overlap. For topology preserved by construction, use
//! [`simplify_preserve_topology`](super::simplify_preserve_topology), or
//! `coverage_simplify` for a coverage.
//!
//! # The threshold
//!
//! The threshold is an **area**, in the coordinates' units squared: the
//! quantity the method compares. It must be finite and at least 0.
//!
//! JTS's `VWSimplifier` (`org.locationtech.jts.simplify`) takes a distance
//! tolerance instead, and its documentation states that "this is converted
//! to an area tolerance by squaring it". To match a JTS call with distance
//! tolerance `t`, pass `t * t`.
//!
//! Every vertex of the result is a vertex of the input; nothing is
//! constructed.
use Reverse;
use BinaryHeap;
use check_tolerance;
use ;
use validity_issues;
use crateGeometryError;
use crateRelatable;
use crate;
// ===========================================================================
// The public entry point
// ===========================================================================
/// The geometry types [`simplify_vw`] accepts: those with vertices to
/// remove. Sealed.
///
/// Implemented for [`LineString`], [`MultiLineString`], [`Polygon`],
/// [`MultiPolygon`] and [`GeometryCollection`]. A collection's points and
/// multipoints are kept unchanged.
/// Visvalingam–Whyatt simplification, vouched: repeatedly remove the vertex
/// whose effective area (the triangle it forms with its two current
/// neighbors) is smallest, while that area is below `threshold`. See the
/// [module documentation](self) for the elimination, the selection rule and
/// the vouch.
///
/// The result has the same type as `g`, and every one of its vertices is a
/// vertex of `g`. Each line and ring is simplified independently. Line
/// endpoints are kept; rings keep at least three vertices.
///
/// `threshold` is an area (the coordinates' units squared).
///
/// ```
/// use geometres::ops::simplify_vw;
/// use geometres::types::{Coord2d, CoordSeq, LineString};
///
/// let line = LineString::new(CoordSeq::new(vec![
/// Coord2d::new(0.0, 0.0),
/// Coord2d::new(5.0, 0.1), // effective area 0.5
/// Coord2d::new(10.0, 0.0),
/// Coord2d::new(10.0, 10.0),
/// ]))?;
/// let out = simplify_vw(&line, 1.0)?;
/// assert_eq!(out.num_points(), 3);
/// # Ok::<(), geometres::GeometryError>(())
/// ```
///
/// # Errors
///
/// - [`GeometryError::InvalidTolerance`] for a negative or non-finite
/// threshold.
/// - [`GeometryError::Unvouched`] with
/// [`UnvouchedReason::SimplifiedInvalid`] when the simplified geometry
/// has a validity issue (a ring that crosses or touches itself, a hole
/// outside its exterior, overlapping parts, and so on).
/// - A constructor's error when the simplified geometry cannot be built: a
/// ring left with three collinear vertices
/// ([`GeometryError::DegenerateRing`]), or an inverted one.
/// Flatten, eliminate on every chain, rebuild through the constructors. No
/// validity check beyond the constructors'.
pub
/// The kept vertices of every chain of `flat`, in order.
pub
// ===========================================================================
// The elimination core (crate-private; `coverage_simplify` adds a veto)
// ===========================================================================
/// How a chain's ends behave.
pub
/// What the elimination did to one chain.
pub
/// The effective area of `b` between `a` and `c`: `|(b − a) × (c − a)| / 2`
/// in `f64`, in exactly this order of operations (the Python reference
/// recomputes it bit for bit), with a non-finite value read as `+∞`.
pub
/// Visvalingam–Whyatt elimination of one chain (module documentation,
/// steps 1–6), with a veto.
///
/// Before each removal, `allow(i, before, after)` is asked, with the
/// vertex's index and its current neighbors' indices. If it answers
/// `false`, the vertex is fixed for the rest of the elimination and the next
/// one is tried. [`simplify_vw`] passes a veto that always allows.
///
/// A priority queue keyed by `(area, index)`, with stale entries skipped by
/// a per-vertex stamp: `O(n log n)`. It selects exactly what a scan over
/// every removable vertex would, in the same order.
pub