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
87 changes: 81 additions & 6 deletions crates/analysis/src/convert.rs
Original file line number Diff line number Diff line change
@@ -1,25 +1,85 @@
//! Conversions between RustGIS geometry and `geo` types, in the analysis plane
//! ([`rustgis_geom::lonlat_to_plane`]): Web Mercator meters within ±85.05°, carried on to the poles
//! beyond, so polar geometry isn't clamped onto 85.05° (#1033).
//! Conversions between RustGIS geometry and `geo` types, in the plane a run works in
//! ([`Plane`]): for a run in longitude/latitude, the analysis plane
//! ([`rustgis_geom::lonlat_to_plane`]), Web Mercator meters within ±85.05°, carried on to the poles
//! beyond, so polar geometry isn't clamped onto 85.05° (#1033); for a run in its first input's own
//! projected system (#2032 C2e), that system's own coordinates, as they are.

use geo::{Coord as GC, LineString, MultiLineString, MultiPoint, MultiPolygon, Point, Polygon};
use rustgis_data::Geometry;
use rustgis_geom::{Coord, lonlat_to_plane, plane_to_lonlat};

/// The plane a run's geometry is worked on in.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Plane {
/// Longitude/latitude, worked on in the analysis plane ([`rustgis_geom::lonlat_to_plane`]),
/// with the poles and the antimeridian where they are in it.
#[default]
Analysis,
/// A projected system's own coordinates, worked on as they are: a plane with no poles or
/// antimeridian in it (#2032 C2e).
Own,
}

thread_local! {
static PLANE: std::cell::Cell<Plane> = const { std::cell::Cell::new(Plane::Analysis) };
}

/// The plane of the run on this thread ([`install_plane`]): [`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 {
PLANE.with(std::cell::Cell::get)
}

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

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)))
}

/// A place of a run's geometry in its plane ([`plane`]): in the analysis plane for
/// longitude/latitude, as it is in a projected system's own.
pub fn to_plane(c: Coord) -> Coord {
match plane() {
Plane::Analysis => lonlat_to_plane(c),
Plane::Own => c,
}
}

/// A place in the run's plane back in its geometry's coordinates, undoing [`to_plane`].
pub fn from_plane(c: Coord) -> Coord {
match plane() {
Plane::Analysis => plane_to_lonlat(c),
Plane::Own => c,
}
}

/// Projects without folding the longitude: a ring kept unwrapped across the antimeridian (as a
/// geodesic buffer is) stays one piece, rather than folding its far vertex across the world.
fn gc(c: Coord) -> GC<f64> {
let m = lonlat_to_plane(c);
let m = to_plane(c);
GC { x: m.x, y: m.y }
}

fn back(c: &GC<f64>) -> Coord {
plane_to_lonlat(Coord::new(c.x, c.y))
from_plane(Coord::new(c.x, c.y))
}

/// The poles something spanning latitudes `south` to `north` reaches (to within
/// [`rustgis_geom::POLE_TOLERANCE`]): the North Pole, then the South Pole.
/// [`rustgis_geom::POLE_TOLERANCE`]): the North Pole, then the South Pole. None in a projected
/// system's own plane ([`Plane::Own`]), whose y is no latitude.
pub(crate) fn reaches_poles(south: f64, north: f64) -> (bool, bool) {
if plane() == Plane::Own {
return (false, false);
}
(north >= 90.0 - rustgis_geom::POLE_TOLERANCE, south <= -90.0 + rustgis_geom::POLE_TOLERANCE)
}

Expand Down Expand Up @@ -94,6 +154,21 @@ pub fn from_point(p: &Point<f64>) -> Geometry {
mod tests {
use super::*;

/// 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]
fn a_projected_systems_plane_is_its_own_coordinates() {
let c = Coord::new(683_944.533_251, 5_397_122.834_867);
{
let _own = install_plane(Plane::Own);
assert_eq!((to_plane(c), from_plane(c)), (c, c));
assert_eq!(reaches_poles(-10_000_000.0, 10_000_000.0), (false, false));
}
assert_eq!(plane(), Plane::Analysis);
assert_eq!(reaches_poles(-90.0, 90.0), (true, true));
assert_ne!(to_plane(Coord::new(10.0, 10.0)), Coord::new(10.0, 10.0));
}

#[test]
fn an_antimeridian_ring_stays_a_sliver_through_geo() {
// Unwrapped across the antimeridian (179.9° to 180.1°): about 22 km wide in Mercator, not
Expand Down
97 changes: 82 additions & 15 deletions crates/analysis/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,12 @@ pub trait Inputs {
/// for a tool that works in its first input's own system ([`ToolSpec::works_in_own_system`]),
/// that system when it is a projected one. Its outputs are made in the same system.
fn dataset(&self, layer: &str) -> Option<&Dataset>;
/// The system the run works in: the one [`Inputs::dataset`] gives layers in, and its outputs
/// are made in. Longitude/latitude unless the tool works in its first input's own projected
/// system ([`ToolSpec::works_in_own_system`]); the run's plane follows it ([`convert::Plane`]).
fn work_crs(&self) -> rustgis_data::raster::Crs {
rustgis_data::raster::Crs::LonLat
}
/// A standalone table by its id: an input given as a number, which no name is taken for.
fn table(&self, _id: u32) -> Option<&Dataset> {
None
Expand Down Expand Up @@ -233,7 +239,9 @@ 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).
/// 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.
const OWN_SYSTEM_TOOLS: &[&str] = &[
"summaryStatistics",
"pivotTable",
Expand All @@ -248,15 +256,54 @@ const OWN_SYSTEM_TOOLS: &[&str] = &[
"merge",
"checkGeometry",
"repairGeometry",
// Overlays and spatial relations, worked on in the system's plane (#2032 C2e-2).
"clip",
"erase",
"intersect",
"identity",
"union",
"symmetricalDifference",
"update",
"split",
"dissolve",
"convexHull",
"featureToPoint",
"countPoints",
"selectByLocation",
"spatialJoin",
];

impl ToolSpec {
/// Whether the tool works in its first input's own coordinate system when that is a projected
/// one: its inputs are given to it in that system ([`Inputs::dataset`]), the others converted
/// into it, and its outputs are held there. Every other tool, and every external one, works in
/// longitude/latitude.
pub fn works_in_own_system(&self) -> bool {
OWN_SYSTEM_TOOLS.contains(&self.id) && TOOLS.iter().any(|t| std::ptr::eq(t, self))
///
/// 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)
}

/// 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.
pub fn reads_edges(&self) -> bool {
matches!(
self.id,
"clip"
| "erase"
| "intersect"
| "identity"
| "union"
| "symmetricalDifference"
| "update"
| "split"
| "countPoints"
| "selectByLocation"
| "spatialJoin"
)
}

/// Whether the tool reads the geometry of the layer its parameter `param` names, rather than
Expand Down Expand Up @@ -680,23 +727,37 @@ pub fn run(id: &str, inputs: &dyn Inputs, params: &Value) -> Result<ToolResult,
let p = resolve_params(spec, params)?;
// A bug in a tool must not take the app down.
std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
validate_pole_inputs(spec, inputs, &p)?;
let result = match source_of(spec) {
Some((_, runner)) => runner(spec, inputs, &p),
None => (spec.run)(inputs, &p),
};
with_pole_loop_notes(result, spec, inputs, &p)
in_plane(inputs, || {
validate_pole_inputs(spec, inputs, &p)?;
let result = match source_of(spec) {
Some((_, runner)) => runner(spec, inputs, &p),
None => (spec.run)(inputs, &p),
};
with_pole_loop_notes(result, spec, inputs, &p)
})
}))
.unwrap_or_else(|_| Err(format!("{} failed unexpectedly", spec.name)))
}

/// `work` in the plane of the system `inputs` are given in ([`Inputs::work_crs`]): the analysis
/// 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);
work()
}

/// A tool's result with [`pole_loop_note`] added: to its messages, or to a refusal of polygons
/// with no area (Clip's `none of the 1 feature(s) of 'loop' covers anything: a polygon with no
/// area`) that names a layer with such rings, which they may be the reason for; then only those
/// layers are read. Another error (`no layer named 'study_area'`, `no field named 'area'`) is left
/// as it is.
fn with_pole_loop_notes(result: Result<ToolResult, String>, spec: &ToolSpec, inputs: &dyn Inputs, p: &Value) -> Result<ToolResult, String> {
match result {
// No pole in a projected system's own plane for a ring to loop around.
Ok(r) if convert::plane() == convert::Plane::Own => Ok(r),
Err(e) if convert::plane() == convert::Plane::Own => Err(e),
Ok(mut r) => {
r.messages.extend(pole_loop_note(spec, inputs, p, |_| true));
Ok(r)
Expand Down Expand Up @@ -802,6 +863,10 @@ fn pole_loop_note(spec: &ToolSpec, inputs: &dyn Inputs, p: &Value, read: impl Fn

/// Validates the rows a pole-aware tool reads, on either execution path.
fn validate_pole_inputs(spec: &ToolSpec, inputs: &dyn Inputs, p: &Value) -> Result<(), String> {
// A projected system's y is no latitude, and its plane has no poles.
if convert::plane() == convert::Plane::Own {
return Ok(());
}
if matches!(
spec.id,
"clip"
Expand Down Expand Up @@ -878,12 +943,14 @@ pub fn run_resolved(
run_under(tool.spec.name, control, || {
let params = tool.resolve_params(params)?;
std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
validate_pole_inputs(tool.spec, inputs, &params)?;
let result = match tool.runner {
Some(runner) => runner(tool.spec, inputs, &params),
None => (tool.spec.run)(inputs, &params),
};
with_pole_loop_notes(result, tool.spec, inputs, &params)
in_plane(inputs, || {
validate_pole_inputs(tool.spec, inputs, &params)?;
let result = match tool.runner {
Some(runner) => runner(tool.spec, inputs, &params),
None => (tool.spec.run)(inputs, &params),
};
with_pole_loop_notes(result, tool.spec, inputs, &params)
})
}))
.unwrap_or_else(|_| Err(format!("{} failed unexpectedly", tool.spec.name)))
})
Expand Down
19 changes: 19 additions & 0 deletions crates/analysis/src/parallel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -106,13 +106,15 @@ pub(crate) fn for_each_row<T: Send, S>(
return Ok(());
}
let run = control::current();
let plane = crate::convert::plane();
let still = rustgis_data::source::remote::current_still();
let rows = std::sync::Mutex::new(rows.enumerate());
let failed = AtomicBool::new(false);
let work = || {
rustgis_data::source::remote::with_optional_still(still.clone(), || {
let _stop = StopOnPanic(&failed);
let _run = control::install(run.clone());
let _plane = crate::convert::install_plane(plane);
let mut s = scratch();
let mut taken = Vec::with_capacity(BATCH);
while !failed.load(Ordering::Relaxed) && !control::cancelled() {
Expand Down Expand Up @@ -209,13 +211,15 @@ fn try_map_by<T: Sync, S, R: Send, E: Send + From<Cancelled>>(
.collect();
}
let run = control::current();
let plane = crate::convert::plane();
let still = rustgis_data::source::remote::current_still();
let next = AtomicUsize::new(0);
let failed = AtomicBool::new(false);
let work = || {
rustgis_data::source::remote::with_optional_still(still.clone(), || {
let _stop = StopOnPanic(&failed);
let _run = control::install(run.clone());
let _plane = crate::convert::install_plane(plane);
let mut s = scratch();
let mut made = Vec::new();
while !failed.load(Ordering::Relaxed) {
Expand Down Expand Up @@ -500,6 +504,21 @@ mod tests {
assert!(ran.load(std::sync::atomic::Ordering::Relaxed) < items.len() / 2, "{}", ran.load(std::sync::atomic::Ordering::Relaxed));
}

/// The threads a run starts work in its plane (#2032 C2e-2): a run in a projected system's own
/// plane isn't worked on in the analysis plane on the threads it hands rows or items to.
#[test]
fn the_threads_work_in_the_runs_plane() {
use crate::convert::{Plane, install_plane, plane};
let _own = install_plane(Plane::Own);
let items: Vec<u32> = (0..5_000).collect();
let planes = try_map_on(&items, 4, || (), |_, _, _| Ok::<_, Cancelled>(plane())).unwrap();
assert!(planes.iter().all(|p| *p == Plane::Own));
let seen = std::sync::Mutex::new(Vec::new());
let mut rows = vec![0u8; 5_000];
for_each_row(rows.chunks_mut(1), 4, || (), |_, _, _| seen.lock().unwrap().push(plane())).unwrap();
assert!(seen.lock().unwrap().iter().all(|p| *p == Plane::Own));
}

#[test]
fn a_cancelled_run_stops_its_threads_and_counts_what_they_made() {
for threads in [1, 4] {
Expand Down
Loading
Loading