Skip to content

Commit ead81c2

Browse files
Mavrick-Fclaude
andcommitted
fix(analysis): measure nearest points in a plane centred on them; prune segment pairs
- distance_m finds the nearest pair in a plane between the features' first vertices, then again in one centred between the pair found, so the distance is true however large the features are (a polygon's far side was 0.06% long before). - Segment pairs whose boxes are farther apart than the best pair so far are skipped. - An integer field's sum takes decimals over the whole i64 range. - The merge rules' paragraph in the guide is wrapped like its neighbours. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent c9ec777 commit ead81c2

2 files changed

Lines changed: 84 additions & 24 deletions

File tree

‎crates/analysis/src/join.rs‎

Lines changed: 80 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,8 @@
33
//! rules that roll the values of several matches up into one.
44
//!
55
//! Distances are on the sphere buffers use. The nearest points of two features are found in an
6-
//! azimuthal equidistant plane centred between them, then measured along the great circle, so the
7-
//! distance is true for those points and the points themselves are within a few metres of the
8-
//! nearest pair for features up to a few hundred kilometres apart.
6+
//! azimuthal equidistant plane, centred first between the features and then between the points
7+
//! found, and measured along the great circle between them.
98
109
use rustgis_data::{Coord, Dataset, FieldType, Geometry, Value};
1110
use rustgis_geom::{Aeqd, EARTH_RADIUS_M, Extent, geodesic_interpolate, geodesic_length_m, geodesic_ring_area_m2, haversine_m};
@@ -24,28 +23,44 @@ pub fn first_coord(g: &Geometry) -> Option<Coord> {
2423

2524
/// The ground distance (metres) between two features that don't intersect: between their nearest
2625
/// points, edges and vertices alike. `None` for a geometry without a finite coordinate.
26+
///
27+
/// The nearest pair is found in a plane centred between the features' first vertices, then again
28+
/// in one centred between the pair found, where the plane is true near the answer however large
29+
/// the features are.
2730
pub fn distance_m(a: &Geometry, b: &Geometry) -> Option<f64> {
28-
let plane = Aeqd::new(geodesic_interpolate(first_coord(a)?, first_coord(b)?, 0.5));
29-
let (sa, sb) = (segments(a, &plane), segments(b, &plane));
30-
// Two segments that don't cross are nearest at an end of one of them.
31-
let mut best: Option<(f64, Coord, Coord)> = None;
32-
let mut consider = |p: Coord, q: Coord| {
33-
let d = (p.x - q.x).hypot(p.y - q.y);
34-
if best.is_none_or(|(b, _, _)| d < b) {
35-
best = Some((d, p, q));
36-
}
31+
let (p, q) = nearest_pair(a, b, &Aeqd::new(geodesic_interpolate(first_coord(a)?, first_coord(b)?, 0.5)))?;
32+
let (p, q) = nearest_pair(a, b, &Aeqd::new(geodesic_interpolate(p, q, 0.5))).unwrap_or((p, q));
33+
let d = haversine_m(p, q);
34+
d.is_finite().then_some(d)
35+
}
36+
37+
/// The nearest points of two geometries (lon/lat) as found in `plane`: a point of `a`, one of `b`.
38+
fn nearest_pair(a: &Geometry, b: &Geometry, plane: &Aeqd) -> Option<(Coord, Coord)> {
39+
let boxed = |segs: Vec<(Coord, Coord)>| -> Vec<((Coord, Coord), [f64; 4])> {
40+
segs.into_iter().map(|(s, e)| ((s, e), [s.x.min(e.x), s.y.min(e.y), s.x.max(e.x), s.y.max(e.y)])).collect()
3741
};
38-
for &(a0, a1) in &sa {
39-
for &(b0, b1) in &sb {
40-
consider(a0, closest_on(a0, b0, b1));
41-
consider(a1, closest_on(a1, b0, b1));
42-
consider(closest_on(b0, a0, a1), b0);
43-
consider(closest_on(b1, a0, a1), b1);
42+
let (sa, sb) = (boxed(segments(a, plane)), boxed(segments(b, plane)));
43+
// Two segments that don't cross are nearest at an end of one of them. A pair whose boxes are
44+
// already farther apart than the best pair so far can't hold a nearer one.
45+
let mut best: Option<(f64, Coord, Coord)> = None;
46+
for &((a0, a1), ba) in &sa {
47+
for &((b0, b1), bb) in &sb {
48+
let gap = (bb[0] - ba[2]).max(ba[0] - bb[2]).max(0.0).hypot((bb[1] - ba[3]).max(ba[1] - bb[3]).max(0.0));
49+
if best.is_some_and(|(d, _, _)| gap >= d) {
50+
continue;
51+
}
52+
for (p, q) in
53+
[(a0, closest_on(a0, b0, b1)), (a1, closest_on(a1, b0, b1)), (closest_on(b0, a0, a1), b0), (closest_on(b1, a0, a1), b1)]
54+
{
55+
let d = (p.x - q.x).hypot(p.y - q.y);
56+
if best.is_none_or(|(b, _, _)| d < b) {
57+
best = Some((d, p, q));
58+
}
59+
}
4460
}
4561
}
4662
let (_, p, q) = best?;
47-
let d = haversine_m(plane.inverse(p), plane.inverse(q));
48-
d.is_finite().then_some(d)
63+
Some((plane.inverse(p), plane.inverse(q)))
4964
}
5065

5166
/// A geometry's edges in the plane; a point is an edge of no length.
@@ -214,7 +229,8 @@ impl Merge {
214229
// Whole numbers, however they are held (a whole decimal counts; 2.5 can't be one).
215230
let whole = |v: &Value| match v {
216231
Value::Int(i) => Some(*i),
217-
v => v.as_f64().filter(|f| f.fract() == 0.0 && f.abs() < 9.2e18).map(|f| f as i64),
232+
// i64::MIN is exactly a float; i64::MAX rounds up to 2^63, which is out of range.
233+
v => v.as_f64().filter(|f| f.fract() == 0.0 && *f >= i64::MIN as f64 && *f < -(i64::MIN as f64)).map(|f| f as i64),
218234
};
219235
let ints: Vec<i64> = present().filter_map(whole).collect();
220236
if ints.is_empty() {
@@ -297,3 +313,46 @@ pub fn parse_merge(join: &Dataset, v: Option<&Json>) -> Result<Vec<Merge>, Strin
297313
}
298314
Ok(out)
299315
}
316+
317+
#[cfg(test)]
318+
mod tests {
319+
use super::*;
320+
321+
/// The ground distance from `p` to a line, by sampling each edge finely along its great circle.
322+
fn brute(p: Coord, line: &[Coord]) -> f64 {
323+
line.windows(2)
324+
.flat_map(|w| (0..=400).map(move |k| geodesic_interpolate(w[0], w[1], f64::from(k) / 400.0)))
325+
.map(|c| haversine_m(p, c))
326+
.fold(f64::INFINITY, f64::min)
327+
}
328+
329+
#[test]
330+
fn an_integer_sum_takes_decimals_over_the_whole_i64_range() {
331+
let sum = Merge { field: 0, rule: Rule::Sum, delimiter: String::new() };
332+
let (min, past_max) = (Value::Float(i64::MIN as f64), Value::Float(9_223_372_036_854_775_808.0));
333+
assert_eq!(sum.apply(FieldType::Integer, &[&min]), Value::Int(i64::MIN));
334+
// 2^63 is one past i64::MAX: not a whole number the field holds, so it's left out.
335+
assert_eq!(sum.apply(FieldType::Integer, &[&past_max, &Value::Int(3)]), Value::Int(3));
336+
assert_eq!(sum.apply(FieldType::Integer, &[&Value::Float(2.5)]), Value::Null);
337+
}
338+
339+
#[test]
340+
fn distances_are_true_far_from_the_features_first_vertices() {
341+
// A line 90° of longitude long at 60°N, measured from beside its far end: the nearest
342+
// points are about 4,500 km from the line's first vertex.
343+
let line: Vec<Coord> = (0..=90).map(|x| Coord::new(f64::from(x), 60.0)).collect();
344+
for p in [Coord::new(89.5, 60.5), Coord::new(45.3, 59.2), Coord::new(91.0, 61.0)] {
345+
let d = distance_m(&Geometry::Point(p), &Geometry::Line(vec![line.clone()])).unwrap();
346+
let truth = brute(p, &line);
347+
assert!((d - truth).abs() < 1e-4 * truth, "{p:?}: {d} vs {truth}");
348+
}
349+
// A polygon's far side, from outside it.
350+
let mut ring: Vec<Coord> = (-80..=80).map(|x| Coord::new(f64::from(x), 50.0)).collect();
351+
ring.extend((-80..=80).rev().map(|x| Coord::new(f64::from(x), 70.0)));
352+
ring.push(Coord::new(-80.0, 50.0));
353+
let p = Coord::new(79.0, 49.0);
354+
let d = distance_m(&Geometry::Point(p), &Geometry::Polygon(vec![vec![ring.clone()]])).unwrap();
355+
let truth = brute(p, &ring);
356+
assert!((d - truth).abs() < 1e-4 * truth, "{d} vs {truth}");
357+
}
358+
}

‎docs/user-guide/analysis.md‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -167,9 +167,10 @@ first: a list such as `[{"field": "units", "rule": "sum"}, {"field": "name", "ru
167167
"delimiter": "; "}]` naming join fields. The rules are `first` (the default for fields without a
168168
rule), `last`, `sum` and `mean` (numeric fields), `min` and `max` (numbers or text), `count` (the
169169
matches with a value) and `join` (the values as text, separated by `delimiter`, `, ` by default).
170-
Every rule but `first` and `last` skips empty values. A target without matches gets empty values, except a `count` of 0. `mean` writes a decimal field, `count` a
171-
whole number and `join` text; a whole-number `sum` too large to hold is empty. For example, the
172-
total units permitted in each district:
170+
Every rule but `first` and `last` skips empty values. A target without matches gets empty
171+
values, except a `count` of 0. `mean` writes a decimal field, `count` a whole number and `join`
172+
text. The `sum` of a whole-number field adds its whole numbers, and is empty when too large to
173+
hold. For example, the total units permitted in each district:
173174

174175
```text
175176
gp.run={"tool":"spatialJoin","params":{"target":"districts","join":"permits","merge":[{"field":"units","rule":"sum"}]}}

0 commit comments

Comments
 (0)