Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 55 additions & 6 deletions crates/analysis/src/convert.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,29 +20,70 @@ pub enum Plane {
Own,
}

/// The plane of a run and the length of its unit on the ground: what [`install`] puts in place.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct RunPlane {
pub plane: Plane,
/// Metres per unit of a projected system's own plane ([`Plane::Own`]): 1 for one in metres,
/// 0.3048 for one in feet. 1 in the analysis plane, whose metres are Web Mercator's.
pub unit_m: f64,
/// Which way a projected system's x and y point: the (east, north) of a step of one along
/// each ([`rustgis_data::raster::Crs::axis_directions`]); east, then north, otherwise.
pub axes: [(f64, f64); 2],
}

/// East, then north: the axes of a plane whose x points east and y north.
pub const EAST_NORTH: [(f64, f64); 2] = [(1.0, 0.0), (0.0, 1.0)];

thread_local! {
static PLANE: std::cell::Cell<Plane> = const { std::cell::Cell::new(Plane::Analysis) };
static PLANE: std::cell::Cell<RunPlane> =
const { std::cell::Cell::new(RunPlane { plane: Plane::Analysis, unit_m: 1.0, axes: EAST_NORTH }) };
}

/// The plane of the run on this thread ([`install_plane`]): [`Plane::Analysis`] unless a run in a
/// The plane of the run on this thread ([`install`]): [`Plane::Analysis`] unless a run in a
/// projected system installed [`Plane::Own`]. The threads of [`crate::parallel`] take it over from
/// the thread that starts them.
pub fn plane() -> Plane {
run_plane().plane
}

/// The plane of the run on this thread with its unit ([`install`]).
pub fn run_plane() -> RunPlane {
PLANE.with(std::cell::Cell::get)
}

/// A distance on the ground in metres as a length in a projected system's own plane, for a run
/// there ([`Plane::Own`]): measured flat, as in a projected system tools measure (#2032 C2e-3).
/// `None` in a run in longitude/latitude, which measures on the ellipsoid.
pub fn own_length(metres: f64) -> Option<f64> {
own_unit_m().map(|u| metres / u)
}

/// Metres per unit of a projected system's own plane, for a run there ([`Plane::Own`]).
pub fn own_unit_m() -> Option<f64> {
let r = run_plane();
(r.plane == Plane::Own).then_some(r.unit_m)
}

/// Puts the plane back as it was when dropped.
pub struct PlaneInstalled(Plane);
pub struct PlaneInstalled(RunPlane);

impl Drop for PlaneInstalled {
fn drop(&mut self) {
PLANE.with(|p| p.set(self.0));
}
}

/// Makes `plane` the plane of the work on this thread until the guard is dropped.
pub fn install_plane(plane: Plane) -> PlaneInstalled {
PlaneInstalled(PLANE.with(|p| p.replace(plane)))
/// Makes `run` the plane of the work on this thread until the guard is dropped.
pub fn install(run: RunPlane) -> PlaneInstalled {
PlaneInstalled(PLANE.with(|p| p.replace(run)))
}

/// A step `(dx, dy)` in a projected system's own plane as (east, north), by the order and
/// direction of its axes ([`RunPlane::axes`]): for a direction from grid north.
pub fn own_east_north(dx: f64, dy: f64) -> (f64, f64) {
let [(xe, xn), (ye, yn)] = run_plane().axes;
(dx * xe + dy * ye, dx * xn + dy * yn)
}

/// A place of a run's geometry in its plane ([`plane`]): in the analysis plane for
Expand Down Expand Up @@ -83,6 +124,8 @@ pub(crate) fn reaches_poles(south: f64, north: f64) -> (bool, bool) {
(north >= 90.0 - rustgis_geom::POLE_TOLERANCE, south <= -90.0 + rustgis_geom::POLE_TOLERANCE)
}

/// A run of coordinates as a `LineString` in the run's plane: a ring's (closed when its coordinates
/// close it) or a line's, which it doesn't close.
pub fn ring(r: &[Coord]) -> LineString<f64> {
LineString::new(r.iter().map(|c| gc(*c)).collect())
}
Expand Down Expand Up @@ -154,6 +197,12 @@ pub fn from_point(p: &Point<f64>) -> Geometry {
mod tests {
use super::*;

/// Makes `plane` the plane of the work on this thread until the guard is dropped, its unit a
/// metre and its axes east and north, as a run installs its own ([`install`]).
fn install_plane(plane: Plane) -> PlaneInstalled {
install(RunPlane { plane, unit_m: 1.0, axes: EAST_NORTH })
}

/// In a projected system's own plane a place is worked on as it is, and nothing reaches a
/// pole however large its y; the analysis plane is put back after.
#[test]
Expand Down
15 changes: 14 additions & 1 deletion crates/analysis/src/geodesic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,10 @@
//! Between vertices, those edges cut at most 0.031% of the distance inside the circle in the
//! projection plane. A short corner can have a step approaching 5.625° when the backend rounds
//! its segment count down, cutting at most 0.125% inside, on top of the projection error.
//!
//! In a run in a projected system's own plane ([`crate::convert::Plane::Own`], #2032 C2e-3), a
//! feature is buffered there as it is, the distance measured flat in the system's unit
//! ([`crate::convert::own_length`]), as distances are in a projected system.

use geo::{
BooleanOps, Buffer, Contains, Coord as GC, CoordsIter, LineString, MultiLineString, MultiPolygon, Orient, Point, Polygon,
Expand Down Expand Up @@ -431,12 +435,18 @@ fn point(c: Coord, metres: f64) -> MultiPolygon<f64> {
if !c.is_finite() {
return MultiPolygon::new(vec![]);
}
if let Some(d) = crate::convert::own_length(metres) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The own-plane branches of point, lines and polygons hand coordinates straight to geo's buffer with no bound. The lon/lat path folds and clamps first, and Simplify refuses coordinates past 1e150. The PR says a run that fails is caught by analysis::run, but a caught panic still counts as a crash under the Never-crash rule. I could not confirm whether geo panics or returns garbage for coordinates near or above 1e150 in a feet or km system, so this is unverified. No test in held_layers.rs uses absurd projected coordinates: distance_tools_take_junk_in_the_held_system covers only NaN and a normal UTM place. Suggest either refusing such coordinates with a notice, as Simplify does, or adding a hostile-coordinate test on these paths.

Category: bug

return Point::new(c.x, c.y).buffer_with_style(buffer_style(d));
}
let plane = Plane::new(c, c.x);
plane.back(&Point::new(0.0, 0.0).buffer_with_style(buffer_style(metres)), metres)
}

/// A line's buffer: in one projection centred on it when it fits, else in stretches.
fn lines(parts: &[Vec<Coord>], metres: f64) -> MultiPolygon<f64> {
if let Some(d) = crate::convert::own_length(metres) {
return MultiLineString::new(parts.iter().map(|p| crate::convert::ring(p)).collect()).buffer_with_style(buffer_style(d));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

convert::ring builds an open LineString here, not a closed ring, so the name misleads readers of this branch. Suggest a neutral name such as convert::linestring, or a note on ring's doc that it doesn't close.

Category: quality

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 4a4732b: convert::ring's doc says it makes a ring's LineString (closed when its coordinates close it) or a line's, which it doesn't close.

}
let all: Vec<Coord> = parts.iter().flatten().copied().collect();
let Some(centre) = spherical_centre(&all) else { return MultiPolygon::new(vec![]) };
if fits(&all, centre) {
Expand All @@ -451,7 +461,6 @@ fn lines(parts: &[Vec<Coord>], metres: f64) -> MultiPolygon<f64> {
/// outline's buffer (in stretches) added or, inward, taken away.
fn polygons(polys: &[Vec<Vec<Coord>>], metres: f64) -> MultiPolygon<f64> {
let all: Vec<Coord> = polys.iter().flatten().flatten().copied().collect();
let Some(centre) = spherical_centre(&all) else { return MultiPolygon::new(vec![]) };
let shape = |ring: &dyn Fn(&[Coord]) -> LineString<f64>| {
MultiPolygon::new(
polys
Expand All @@ -464,6 +473,10 @@ fn polygons(polys: &[Vec<Vec<Coord>>], metres: f64) -> MultiPolygon<f64> {
.collect(),
)
};
if let Some(d) = crate::convert::own_length(metres) {
return shape(&|r| crate::convert::ring(r)).buffer_with_style(buffer_style(d));
}
let Some(centre) = spherical_centre(&all) else { return MultiPolygon::new(vec![]) };
if fits(&all, centre) {
let plane = Plane::new(centre, all.first().map_or(centre.x, |c| c.x));
return plane.back(&shape(&|r| plane.line(r)).buffer_with_style(buffer_style(metres)), metres);
Expand Down
61 changes: 51 additions & 10 deletions crates/analysis/src/join.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,11 @@
//! the overlap a feature has with a polygon, and the rules that roll the values of several matches
//! up into one.
//!
//! Distances are on the WGS 84 ellipsoid, as buffers' are. The nearest points of two features are
//! found in an azimuthal equidistant plane, centred first between the features and then between
//! the points found, and measured along the geodesic between them.
//! In a run in longitude/latitude, distances are on the WGS 84 ellipsoid, as buffers' are. The
//! nearest points of two features are found in an azimuthal equidistant plane, centred first
//! between the features and then between the points found, and measured along the geodesic between
//! them. In a run in a projected system's own plane ([`crate::convert::Plane::Own`], #2032 C2e-3),
//! they are found there and measured straight, in the system's unit times its length.

use rustgis_data::{Coord, Dataset, FieldType, Geometry, Value};
use rustgis_geom::{Aeqd, Extent, WGS84_MIN_RADIUS_M, geodesic_interpolate, geodesic_length_m, geodesic_ring_area_m2, wgs84_distance_m};
Expand All @@ -15,7 +17,29 @@ use serde_json::Value as Json;
/// and a longitude within 540° of the meridian (a shape across the antimeridian goes past 180°).
/// Distances leave other coordinates out, as places they can't measure from.
fn on_earth(c: &Coord) -> bool {
c.is_finite() && c.x.abs() <= 540.0 && c.y.abs() <= 90.0
c.is_finite() && (crate::convert::plane() == crate::convert::Plane::Own || (c.x.abs() <= 540.0 && c.y.abs() <= 90.0))
}

/// The plane nearest points are found in: an azimuthal equidistant one, or a projected system's
/// own as it is.
enum Flat {
Aeqd(Aeqd),
Own,
}

impl Flat {
fn forward(&self, c: Coord) -> Coord {
match self {
Flat::Aeqd(p) => p.forward(c),
Flat::Own => c,
}
}
fn inverse(&self, c: Coord) -> Coord {
match self {
Flat::Aeqd(p) => p.inverse(c),
Flat::Own => c,
}
}
}

/// The first coordinate of a geometry that is a place on the Earth.
Expand All @@ -29,15 +53,19 @@ pub fn first_coord(g: &Geometry) -> Option<Coord> {
first
}

/// The ground distance (metres) between two features that don't intersect: between their nearest
/// The distance (metres) between two features that don't intersect, on the ground (flat in a
/// projected system's own plane, see the module's docs): between their nearest
/// points, edges and vertices alike. `None` for a geometry without a finite coordinate.
///
/// The nearest pair is found in a plane centred between the features' first vertices, then again
/// in one centred between the pair found, where the plane is true near the answer however large
/// the features are.
pub fn distance_m(a: &Geometry, b: &Geometry) -> Option<f64> {
let (p, q) = nearest_points(a, b)?;
let d = wgs84_distance_m(p, q);
let d = match crate::convert::own_unit_m() {
Some(unit) => (p.x - q.x).hypot(p.y - q.y) * unit,
None => wgs84_distance_m(p, q),
};
d.is_finite().then_some(d)
}

Expand All @@ -46,13 +74,16 @@ pub fn distance_m(a: &Geometry, b: &Geometry) -> Option<f64> {
pub fn nearest_points(a: &Geometry, b: &Geometry) -> Option<(Coord, Coord)> {
// The features' first vertices are a pair of their points: the search starts from them.
let (fa, fb) = (first_coord(a)?, first_coord(b)?);
let (p, q) = nearest_pair(a, b, &Aeqd::new(geodesic_interpolate(fa, fb, 0.5)), Some((fa, fb)))?;
Some(nearest_pair(a, b, &Aeqd::new(geodesic_interpolate(p, q, 0.5)), Some((p, q))).unwrap_or((p, q)))
if crate::convert::plane() == crate::convert::Plane::Own {
return nearest_pair(a, b, &Flat::Own, Some((fa, fb)));
}
let (p, q) = nearest_pair(a, b, &Flat::Aeqd(Aeqd::new(geodesic_interpolate(fa, fb, 0.5))), Some((fa, fb)))?;
Some(nearest_pair(a, b, &Flat::Aeqd(Aeqd::new(geodesic_interpolate(p, q, 0.5))), Some((p, q))).unwrap_or((p, q)))
}

/// The nearest points of two geometries (lon/lat) as found in `plane`: a point of `a`, one of `b`.
/// `seed`, a pair already found, starts the search, so pairs no nearer than it are skipped.
fn nearest_pair(a: &Geometry, b: &Geometry, plane: &Aeqd, seed: Option<(Coord, Coord)>) -> Option<(Coord, Coord)> {
fn nearest_pair(a: &Geometry, b: &Geometry, plane: &Flat, seed: Option<(Coord, Coord)>) -> Option<(Coord, Coord)> {
let boxed = |segs: Vec<(Coord, Coord)>| -> Vec<((Coord, Coord), [f64; 4])> {
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()
};
Expand Down Expand Up @@ -94,7 +125,7 @@ fn nearest_pair(a: &Geometry, b: &Geometry, plane: &Aeqd, seed: Option<(Coord, C
}

/// A geometry's edges in the plane; a point is an edge of no length.
fn segments(g: &Geometry, plane: &Aeqd) -> Vec<(Coord, Coord)> {
fn segments(g: &Geometry, plane: &Flat) -> Vec<(Coord, Coord)> {
let mut out = Vec::new();
let mut path = |pts: &[Coord], closed: bool| {
// A coordinate left out ends a run: no edge joins the runs on either side of it, and a
Expand Down Expand Up @@ -159,6 +190,11 @@ pub fn may_be_within(a: &Extent, b: &Extent, metres: f64) -> bool {
if a.is_empty() || b.is_empty() {
return false;
}
// In a projected system's own plane, extents there: their gap measured straight.
if let Some(d) = crate::convert::own_length(metres) {
let gap = (b.min_x - a.max_x).max(a.min_x - b.max_x).max(0.0).hypot((b.min_y - a.max_y).max(a.min_y - b.max_y).max(0.0));
return gap <= d.max(0.0) * (1.0 + 1e-9) + 1e-9;
}
let (dlat, dlon) = spread(a.min_y.abs().max(a.max_y.abs()), metres);
let lat_gap = (b.min_y - a.max_y).max(a.min_y - b.max_y).max(0.0);
if lat_gap > dlat {
Expand All @@ -174,6 +210,11 @@ pub fn search_box(ext: &Extent, metres: f64) -> Option<Extent> {
if ext.is_empty() || !metres.is_finite() {
return None;
}
// In a projected system's own plane, the extent there widened by the distance in its unit.
if let Some(d) = crate::convert::own_length(metres) {
let d = d.max(0.0) * (1.0 + 1e-9) + 1e-9;
return Some(Extent::new(ext.min_x - d, ext.min_y - d, ext.max_x + d, ext.max_y + d));
}
let (dlat, dlon) = spread(ext.min_y.abs().max(ext.max_y.abs()), metres);
let dlon = dlon?;
let (x0, x1) = (ext.min_x - dlon, ext.max_x + dlon);
Expand Down
37 changes: 25 additions & 12 deletions crates/analysis/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -239,9 +239,10 @@ pub struct ToolSpec {
/// The built-in tools that work in their first input's own coordinate system when it is a
/// projected one, rather than in longitude/latitude ([`ToolSpec::works_in_own_system`]): those
/// whose results don't depend on the system's units or shape beyond what the input's own
/// coordinates give (attributes, vertices, envelopes, validity), and the overlays and spatial
/// relations, worked on in its plane rather than the analysis plane. Areas they report are
/// still measured on the ground.
/// coordinates give (attributes, vertices, envelopes, validity), the overlays and spatial
/// relations, worked on in its plane rather than the analysis plane, and the tools that measure
/// distances in metres, measured flat there in its unit ([`convert::own_length`]). Areas they
/// report are still measured on the ground.
const OWN_SYSTEM_TOOLS: &[&str] = &[
"summaryStatistics",
"pivotTable",
Expand Down Expand Up @@ -271,6 +272,11 @@ const OWN_SYSTEM_TOOLS: &[&str] = &[
"countPoints",
"selectByLocation",
"spatialJoin",
// Distances in metres, measured flat in the system's unit (#2032 C2e-3).
"buffer",
"simplify",
"pointsAlongLines",
"near",
];

impl ToolSpec {
Expand All @@ -279,16 +285,16 @@ impl ToolSpec {
/// into it, and its outputs are held there. Every other tool, and every external one, works in
/// longitude/latitude.
///
/// For some it depends on `params`: Select Layer By Location and Spatial Join measure no
/// distance only without a search distance, or with a match that measures none.
pub fn works_in_own_system(&self, params: &Value) -> bool {
OWN_SYSTEM_TOOLS.contains(&self.id) && TOOLS.iter().any(|t| std::ptr::eq(t, self)) && !tools::measures_distance(self.id, params)
/// Distances in metres are measured flat there, in the system's unit (#2032 C2e-3).
pub fn works_in_own_system(&self) -> bool {
OWN_SYSTEM_TOOLS.contains(&self.id) && TOOLS.iter().any(|t| std::ptr::eq(t, self))
}

/// Whether the tool crosses its inputs' edges with each other's (overlays and spatial
/// relations), where how an edge runs between its vertices decides the result, not only where
/// they are: a run in its first input's own system then says when another input's edges,
/// converted into it, run far from where a run in longitude/latitude takes them.
/// relations) or measures to them (Near), where how an edge runs between its vertices decides
/// the result, not only where they are: a run in its first input's own system then says when
/// another input's edges, converted into it, run far from where a run in longitude/latitude
/// takes them.
pub fn reads_edges(&self) -> bool {
matches!(
self.id,
Expand All @@ -303,6 +309,7 @@ impl ToolSpec {
| "countPoints"
| "selectByLocation"
| "spatialJoin"
| "near"
)
}

Expand Down Expand Up @@ -743,8 +750,14 @@ pub fn run(id: &str, inputs: &dyn Inputs, params: &Value) -> Result<ToolResult,
/// plane for longitude/latitude, a projected system's own coordinates otherwise
/// ([`convert::Plane::Own`]).
fn in_plane<T>(inputs: &dyn Inputs, work: impl FnOnce() -> T) -> T {
let plane = if inputs.work_crs() == rustgis_data::raster::Crs::LonLat { convert::Plane::Analysis } else { convert::Plane::Own };
let _plane = convert::install_plane(plane);
let crs = inputs.work_crs();
let run = if crs == rustgis_data::raster::Crs::LonLat {
convert::RunPlane { plane: convert::Plane::Analysis, unit_m: 1.0, axes: convert::EAST_NORTH }
} else {
let (unit_m, axes) = crs.unit_and_axes();
convert::RunPlane { plane: convert::Plane::Own, unit_m, axes }
};
let _plane = convert::install(run);
work()
}

Expand Down
Loading
Loading