diff --git a/crates/analysis/src/geodesic.rs b/crates/analysis/src/geodesic.rs index 784d58a059..64ee49b0fe 100644 --- a/crates/analysis/src/geodesic.rs +++ b/crates/analysis/src/geodesic.rs @@ -61,7 +61,8 @@ const STRAY_MARGIN: f64 = 1.6; /// by 1/x − cot x per radian across it), so two leaves a wide margin; /// [`tests::an_edge_let_pass_by_its_latitude_does_not_stray`] fails at a tenth. const PLANE_TURN: f64 = 2.0; -/// The Earth's mean radius (metres), for [`may_stray`]: the one distances are measured with. +/// The Earth's mean radius (metres), for [`may_stray`]'s sphere: the radius `haversine_m` and the +/// planes use. const EARTH_R_M: f64 = rustgis_geom::EARTH_RADIUS_M; /// What [`may_stray`] adds to tan φ for the ellipsoid and near the equator, where tan φ is near 0: /// a tenth of the turn at 45°, as at about 5.7° of latitude. @@ -127,12 +128,7 @@ pub(crate) fn geodesic_buffer_with_limit(g: &Geometry, metres: f64, max_vertices } /// Buffers of this many features or more are made on several threads. -const PARALLEL_FEATURES: usize = 256; -/// The features a thread takes at a time: few enough that expensive features lying together are -/// shared out, enough that taking them costs nothing. -const BATCH: usize = 16; -/// Each buffering thread's stack, as large as the main thread's usually is. -const STACK_BYTES: usize = 8 << 20; +pub(crate) const PARALLEL_FEATURES: usize = 256; /// The buffers of `geoms` at `metres`, in their order, as [`geodesic_buffer`] makes them: on /// several threads when there are many (one in the browser), since each is made alone. @@ -141,72 +137,44 @@ pub fn geodesic_buffers(geoms: &[&Geometry], metres: f64) -> Vec Result>, &'static str> { - let threads = if cfg!(target_arch = "wasm32") || geoms.len() < PARALLEL_FEATURES { - 1 - } else { - std::thread::available_parallelism().map_or(1, |n| n.get()).min(16) - }; - buffers_on(geoms, metres, threads, limit) + buffers_on(geoms, metres, crate::parallel::threads_for(geoms.len(), PARALLEL_FEATURES), limit) } -/// [`geodesic_buffers_with_limit`] on `threads` threads, this one among them. Each takes the next -/// [`BATCH`] of features until none are left, and results go back in their places. The shared -/// remaining budget is charged before a worker retains an outline. A thread that cannot start -/// leaves its work to the others; a worker panic is passed on as in a buffer made here. +/// [`geodesic_buffers_with_limit`] on `threads` threads, through [`crate::parallel::try_map_on`]: +/// a buffer past the budget stops the others. fn buffers_on(geoms: &[&Geometry], metres: f64, threads: usize, limit: usize) -> Result>, &'static str> { - use std::sync::atomic::{AtomicUsize, Ordering}; - let next = AtomicUsize::new(0); - let remaining = AtomicUsize::new(limit); - let work = || { - let mut made = Vec::new(); - loop { - let from = next.fetch_add(BATCH, Ordering::Relaxed); - let Some(batch) = geoms.get(from..geoms.len().min(from + BATCH)).filter(|b| !b.is_empty()) else { break }; - for (i, g) in batch.iter().enumerate() { - let buffered = geodesic_buffer_with_limit(g, metres, remaining.load(Ordering::Relaxed))?; - if limit != usize::MAX { - let mut left = remaining.load(Ordering::Relaxed); - loop { - let next = left.checked_sub(buffered.charged_vertices).ok_or(VERTEX_BUDGET_ERROR)?; - match remaining.compare_exchange_weak(left, next, Ordering::Relaxed, Ordering::Relaxed) { - Ok(_) => break, - Err(current) => left = current, - } - } - } - made.push((from + i, buffered.geometry)); - } - } - Ok::<_, &'static str>(made) - }; - let mut out: Vec> = vec![None; geoms.len()]; - let mut place = |made: Vec<(usize, Option)>| { - for (i, b) in made { - if let Some(slot) = out.get_mut(i) { - *slot = b; - } + let remaining = std::sync::atomic::AtomicUsize::new(limit); + crate::parallel::try_map_on( + geoms, + threads, + || (), + |_, _, g| { + let buffered = geodesic_buffer_with_limit(g, metres, remaining.load(std::sync::atomic::Ordering::Relaxed))?; + charge(&remaining, limit, buffered.charged_vertices)?; + Ok(buffered.geometry) + }, + ) +} + +/// Takes `vertices` from the `remaining` budget that threads share, or says it is spent; nothing +/// when the `limit` is `usize::MAX`. +pub(crate) fn charge(remaining: &std::sync::atomic::AtomicUsize, limit: usize, vertices: usize) -> Result<(), &'static str> { + use std::sync::atomic::Ordering; + if limit == usize::MAX { + return Ok(()); + } + let mut left = remaining.load(Ordering::Relaxed); + loop { + let next = left.checked_sub(vertices).ok_or(VERTEX_BUDGET_ERROR)?; + match remaining.compare_exchange_weak(left, next, Ordering::Relaxed, Ordering::Relaxed) { + Ok(_) => return Ok(()), + Err(current) => left = current, } - }; - if threads <= 1 { - place(work()?); - } else { - std::thread::scope(|scope| { - let others: Vec<_> = - (1..threads).filter_map(|_| std::thread::Builder::new().stack_size(STACK_BYTES).spawn_scoped(scope, work).ok()).collect(); - place(work()?); - for h in others { - // Not a new panic but the worker's, raised again here as a serial run would raise it, - // for `analysis::run` to catch (AGENTS.md's never-crash rule is about new ones). - place(h.join().unwrap_or_else(|e| std::panic::resume_unwind(e))?); - } - Ok::<_, &'static str>(()) - })?; } - Ok(out) } /// An azimuthal equidistant plane whose centre's longitude is within 180° of `reference`, a @@ -528,6 +496,7 @@ fn to_geometry(mp: &MultiPolygon) -> Option { #[cfg(test)] mod tests { use super::*; + use crate::parallel::BATCH; /// Samples the actual projected outlines: shallow turns exercise a rounded-down join, /// while larger turns would fail this bound at the old default arc density. diff --git a/crates/analysis/src/lib.rs b/crates/analysis/src/lib.rs index 7c8e54c061..5e118b339e 100644 --- a/crates/analysis/src/lib.rs +++ b/crates/analysis/src/lib.rs @@ -21,6 +21,7 @@ pub mod kriging; mod merge; pub mod network; pub mod neural; +mod parallel; mod parameters; pub mod rasterops; pub mod selection; diff --git a/crates/analysis/src/parallel.rs b/crates/analysis/src/parallel.rs new file mode 100644 index 0000000000..16215eefe9 --- /dev/null +++ b/crates/analysis/src/parallel.rs @@ -0,0 +1,226 @@ +//! Work spread over the machine's cores (#1252): a tool's independent items (features, raster +//! rows) made on several threads, in their order, as one thread would make them. +//! +//! The browser has no threads, so there everything runs on the calling thread, as it does below +//! a tool's threshold, where starting threads costs more than they save. + +/// The most threads a tool uses. +const MAX_THREADS: usize = 16; +/// The items a thread takes at a time: few enough that expensive items lying together are shared +/// out, enough that taking them costs nothing. +pub(crate) const BATCH: usize = 16; +/// Each worker's stack, as large as the main thread's usually is. +const STACK_BYTES: usize = 8 << 20; + +/// How many threads to make `items` items on: one below `min_items`, always one in the browser, +/// and no more than there are batches. +pub(crate) fn threads_for(items: usize, min_items: usize) -> usize { + if cfg!(target_arch = "wasm32") || items < min_items { + return 1; + } + std::thread::available_parallelism().map_or(1, |n| n.get()).min(MAX_THREADS).min(items.div_ceil(BATCH)).max(1) +} + +/// `f` on each of `items` with its index, the results in their order: on several threads when +/// there are at least `min_items` of them (one in the browser). Each thread makes its own +/// `scratch()` once and passes it to every `f` it runs, for buffers to reuse; the index lets a +/// raster tool map over its rows' numbers. The first error stops the threads after the items +/// they are making, and comes back instead of the results: on one thread the first in input +/// order, on several the earliest of those found before they stopped. +pub(crate) fn try_map( + items: &[T], + min_items: usize, + scratch: impl Fn() -> S + Sync, + f: impl Fn(&mut S, usize, &T) -> Result + Sync, +) -> Result, E> { + try_map_on(items, threads_for(items.len(), min_items), scratch, f) +} + +/// [`try_map`] on `threads` threads, this one among them. Each takes the next [`BATCH`] of items +/// until none are left or one has failed, so the work is shared however it is spread, and the +/// results go back in their places. A thread that can't start (a limit on threads, say) leaves +/// its share to the others; one that panics passes its panic on, as an item made here would. +pub(crate) fn try_map_on( + items: &[T], + threads: usize, + scratch: impl Fn() -> S + Sync, + f: impl Fn(&mut S, usize, &T) -> Result + Sync, +) -> Result, E> { + use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; + if threads <= 1 || items.len() <= 1 { + let mut s = scratch(); + return items.iter().enumerate().map(|(i, item)| f(&mut s, i, item)).collect(); + } + let next = AtomicUsize::new(0); + let failed = AtomicBool::new(false); + let work = || { + let mut s = scratch(); + let mut made = Vec::new(); + while !failed.load(Ordering::Relaxed) { + let from = next.fetch_add(BATCH, Ordering::Relaxed); + let Some(batch) = items.get(from..items.len().min(from + BATCH)).filter(|b| !b.is_empty()) else { break }; + for (k, item) in batch.iter().enumerate() { + match f(&mut s, from + k, item) { + Ok(r) => made.push((from + k, r)), + Err(e) => { + failed.store(true, Ordering::Relaxed); + return Err((from + k, e)); + } + } + } + } + Ok(made) + }; + let mut parts = Vec::with_capacity(threads); + std::thread::scope(|scope| { + let others: Vec<_> = + (1..threads).filter_map(|_| std::thread::Builder::new().stack_size(STACK_BYTES).spawn_scoped(scope, work).ok()).collect(); + parts.push(work()); + for h in others { + // The worker's panic, raised again here as a serial run would raise it, for + // `analysis::run` to catch. + parts.push(h.join().unwrap_or_else(|e| std::panic::resume_unwind(e))); + } + }); + let mut made: Vec<(usize, R)> = Vec::with_capacity(items.len()); + let mut first: Option<(usize, E)> = None; + for part in parts { + match part { + Ok(m) => made.extend(m), + Err((i, e)) => { + if first.as_ref().is_none_or(|(j, _)| i < *j) { + first = Some((i, e)); + } + } + } + } + if let Some((_, e)) = first { + return Err(e); + } + made.sort_unstable_by_key(|(i, _)| *i); + Ok(made.into_iter().map(|(_, r)| r).collect()) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The infallible case, for the tests. + fn map_on( + items: &[T], + threads: usize, + scratch: impl Fn() -> S + Sync, + f: impl Fn(&mut S, usize, &T) -> R + Sync, + ) -> Vec { + try_map_on(items, threads, scratch, |s, i, item| Ok::(f(s, i, item))).unwrap_or_default() + } + + fn map( + items: &[T], + min_items: usize, + scratch: impl Fn() -> S + Sync, + f: impl Fn(&mut S, usize, &T) -> R + Sync, + ) -> Vec { + try_map(items, min_items, scratch, |s, i, item| Ok::(f(s, i, item))).unwrap_or_default() + } + + #[test] + fn items_made_on_several_threads_come_back_in_their_order() { + let items: Vec = (0..1_000).collect(); + let alone: Vec = items.iter().map(|x| x * x + 1).collect(); + // Each item comes with its index, here equal to its value. + let square = |_: &mut (), i: usize, x: &u64| { + assert_eq!(i as u64, *x); + x * x + 1 + }; + for threads in [1, 2, 3, 16, 64] { + assert_eq!(map_on(&items, threads, || (), square), alone, "{threads} threads"); + assert_eq!(map_on(&items[..3], threads, || (), square), alone[..3], "{threads} threads, 3 items"); + assert!(map_on(&items[..0], threads, || (), square).is_empty()); + } + // Below the threshold, and in the browser, one thread. + assert_eq!(threads_for(10, 256), 1); + assert_eq!(map(&items, 256, || (), square), alone); + } + + #[test] + fn each_thread_makes_its_scratch_once() { + let made = std::sync::atomic::AtomicUsize::new(0); + let items: Vec = (0..1_000).collect(); + // Each item records how many it saw before it on its thread, from that thread's scratch. + let seen = map_on( + &items, + 4, + || { + made.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + 0usize + }, + |count, _, _| { + *count += 1; + *count + }, + ); + let scratches = made.load(std::sync::atomic::Ordering::Relaxed); + assert!((1..=4).contains(&scratches), "{scratches}"); + // A thread's first item sees 1; a thread that found nothing left has no first item. + let firsts = seen.iter().filter(|c| **c == 1).count(); + assert!((1..=scratches).contains(&firsts), "{firsts} of {scratches}"); + } + + #[test] + fn a_workers_panic_reaches_the_caller() { + // Only the workers panic, not this thread. Each item takes a moment, so workers get some, + // unless none could start: then nothing panics, which is right too. + let items: Vec = (0..200).collect(); + let caller = std::thread::current().id(); + let on_worker = std::sync::atomic::AtomicBool::new(false); + let r = std::panic::catch_unwind(|| { + map_on( + &items, + 4, + || (), + |_, _, x| { + std::thread::sleep(std::time::Duration::from_millis(1)); + if std::thread::current().id() != caller { + on_worker.store(true, std::sync::atomic::Ordering::Relaxed); + panic!("a worker's panic"); + } + *x + }, + ) + }); + assert_eq!(r.is_err(), on_worker.load(std::sync::atomic::Ordering::Relaxed)); + } + + #[test] + fn a_failing_item_stops_the_threads_and_its_error_comes_back() { + let items: Vec = (0..1_000).collect(); + let f = |_: &mut (), _: usize, x: &u32| if *x == 500 || *x == 700 { Err(*x) } else { Ok(*x) }; + // On one thread, the first in input order. + assert_eq!(try_map_on(&items, 1, || (), f), Err(500)); + for threads in [2, 3, 16] { + assert!(matches!(try_map_on(&items, threads, || (), f), Err(500 | 700)), "{threads} threads"); + assert_eq!(try_map_on(&items, threads, || (), |_, _, x| Ok::<_, ()>(*x)), Ok(items.clone()), "{threads} threads"); + } + // Items still waiting when one fails are left: far fewer than all of them run. + let ran = std::sync::atomic::AtomicUsize::new(0); + let r = try_map_on( + &items, + 4, + || (), + |_, _, x| { + ran.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + if *x == 0 { Err(()) } else { Ok(()) } + }, + ); + assert!(r.is_err()); + assert!(ran.load(std::sync::atomic::Ordering::Relaxed) < items.len()); + } + + #[test] + fn no_more_threads_than_batches() { + assert_eq!(threads_for(10, 256), 1); + assert!(threads_for(20, 1) <= 2); + assert!(threads_for(300, 1) <= 300usize.div_ceil(BATCH)); + } +} diff --git a/crates/analysis/src/tools.rs b/crates/analysis/src/tools.rs index 135eb3d58c..875781d3ee 100644 --- a/crates/analysis/src/tools.rs +++ b/crates/analysis/src/tools.rs @@ -11,7 +11,7 @@ use std::borrow::Cow; use std::collections::{HashMap, HashSet, TryReserveError}; use crate::convert::{from_line, from_multipolygon, from_point, to_geo, to_multiline, to_multipolygon}; -use crate::geodesic::{VERTEX_BUDGET_ERROR, geodesic_buffer_with_limit, geodesic_buffers_with_limit}; +use crate::geodesic::{PARALLEL_FEATURES, VERTEX_BUDGET_ERROR, charge, geodesic_buffer_with_limit, geodesic_buffers_with_limit}; use crate::{Inputs, Output, OutputLayer, ParamKind as K, ParamSpec as P, ToolResult, ToolSpec}; const UNITS: &[&str] = &["Kilometers", "Meters", "Miles", "Feet"]; @@ -1191,10 +1191,11 @@ fn buffer_with_vertex_limit(inp: &dyn Inputs, p: &Json, limit: usize) -> Result< let units = if s(p, "units").is_empty() { "Kilometers" } else { s(p, "units") }; let mut r = result(out, format!("Buffer: {n} features at {d} {units}"))?; if without > 0 { - r.messages.push(format!("{without} of {} features have no geometry, so they have no buffer", picked.len())); + r.messages.push(format!("{without} of {} features lack geometry, so they have no buffer", picked.len())); } if empty > 0 { - r.messages.push(format!("{empty} of {} features have nothing left at {d} {units}, so they have no buffer", picked.len())); + r.messages + .push(format!("{empty} of {} features made no buffer at {d} {units} (nothing left, or no finite coordinates)", picked.len())); } Ok(r) } @@ -2211,21 +2212,28 @@ fn select_by_location_with_vertex_limit(inp: &dyn Inputs, p: &Json, limit: usize if dist > 5_000_000.0 { return Err("Distance is too large (limit 5000 km)".into()); } - let mut remaining = limit; - let mut selectors = Vec::new(); - for r in rows(inp, p, "select", sel_ds) { - let Some(g) = sel_ds.features.get(r).and_then(|f| f.geometry.as_ref()) else { continue }; - let b = if dist > 0.0 { - let buffered = geodesic_buffer_with_limit(g, dist, remaining)?; - remaining = remaining.saturating_sub(buffered.charged_vertices); - buffered.geometry - } else { - None - }; - let gg = to_geo(b.as_ref().unwrap_or(g)); - let ext = merc_extent(&gg); - selectors.push((gg, ext)); - } + let chosen = rows(inp, p, "select", sel_ds); + let picked: Vec<&Geometry> = chosen.iter().filter_map(|r| sel_ds.features.get(*r)?.geometry.as_ref()).collect(); + // Buffered, charged to the budget and converted in one step, on several cores when there are + // many, so each buffer is dropped once converted. + let remaining = std::sync::atomic::AtomicUsize::new(limit); + let selectors: Vec<(geo::Geometry, Extent)> = crate::parallel::try_map( + &picked, + PARALLEL_FEATURES, + || (), + |_, _, g| { + let b = if dist > 0.0 { + let buffered = geodesic_buffer_with_limit(g, dist, remaining.load(std::sync::atomic::Ordering::Relaxed))?; + charge(&remaining, limit, buffered.charged_vertices)?; + buffered.geometry + } else { + None + }; + let gg = to_geo(b.as_ref().unwrap_or(g)); + let ext = merc_extent(&gg); + Ok::<_, &'static str>((gg, ext)) + }, + )?; let index = ExtentIndex::new(selectors.iter().map(|(_, ext)| *ext)); let invert = s(p, "invert") == "Yes"; let hits: Vec = (0..ds.features.len()) @@ -2240,10 +2248,19 @@ fn select_by_location_with_vertex_limit(inp: &dyn Inputs, p: &Json, limit: usize }) .collect(); let n = hits.len(); - Ok(ToolResult { - output: Output::Selection { layer: ds.name.clone(), rows: hits }, - messages: vec![format!("Selected {n} features in {}", ds.name)], - }) + let mut messages = vec![format!("Selected {n} features in {}", ds.name)]; + let without = ds.features.iter().filter(|f| f.geometry.is_none()).count(); + if without > 0 { + messages.push(format!("{without} of {} features lack geometry, so they are not selected", ds.features.len())); + } + if picked.len() < chosen.len() { + messages.push(format!( + "{} of {} selecting features lack geometry, so they select nothing", + chosen.len() - picked.len(), + chosen.len() + )); + } + Ok(ToolResult { output: Output::Selection { layer: ds.name.clone(), rows: hits }, messages }) } fn select_by_attributes(inp: &dyn Inputs, p: &Json) -> Result { @@ -4966,10 +4983,21 @@ mod tests { } let clean = Map(HashMap::from([("p".to_string(), pts.clone())])); assert_eq!(crate::run("buffer", &clean, &serde_json::json!({"input": "p", "distance": 5})).unwrap().messages.len(), 1); + // A point with no finite coordinates makes no buffer either, and says so. + let mut odd = pts.clone(); + odd.push(Some(Geometry::Point(Coord::new(f64::NAN, 0.0))), vec![Value::Int(-2)]); + let odd = Map(HashMap::from([("p".to_string(), odd)])); + let r = crate::run("buffer", &odd, &serde_json::json!({"input": "p", "distance": 5})).unwrap(); + assert_eq!(r.messages.len(), 2); + assert_eq!( + r.messages.get(1).map(String::as_str), + Some("1 of 301 features made no buffer at 5 Kilometers (nothing left, or no finite coordinates)") + ); pts.push(None, vec![Value::Int(-1)]); let m = Map(HashMap::from([("p".to_string(), pts)])); let r = crate::run("buffer", &m, &serde_json::json!({"input": "p", "distance": 5})).unwrap(); - assert_eq!(r.messages.get(1).map(String::as_str), Some("1 of 301 features have no geometry, so they have no buffer")); + assert_eq!(r.messages.len(), 2); + assert_eq!(r.messages.get(1).map(String::as_str), Some("1 of 301 features lack geometry, so they have no buffer")); let b = layer(r); assert_eq!(b.features.len(), 300); for (k, f) in b.features.iter().enumerate() { @@ -4977,14 +5005,16 @@ mod tests { assert_eq!(f.geometry, geodesic_buffer(&Geometry::Point(at(k as i64)), 5_000.0), "feature {k}"); } let r = crate::run("buffer", &m, &serde_json::json!({"input": "p", "distance": 5, "dissolve": "All"})).unwrap(); - assert_eq!(r.messages.get(1).map(String::as_str), Some("1 of 301 features have no geometry, so they have no buffer")); + assert_eq!(r.messages.len(), 2); + assert_eq!(r.messages.get(1).map(String::as_str), Some("1 of 301 features lack geometry, so they have no buffer")); assert_eq!(layer(r).features.len(), 1); // Points at a negative distance have nothing left, and say so. let r = crate::run("buffer", &clean, &serde_json::json!({"input": "p", "distance": -5})).unwrap(); assert_eq!( r.messages.get(1).map(String::as_str), - Some("300 of 300 features have nothing left at -5 Kilometers, so they have no buffer") + Some("300 of 300 features made no buffer at -5 Kilometers (nothing left, or no finite coordinates)") ); + assert_eq!(r.messages.len(), 2); assert!(layer(r).features.is_empty()); } @@ -7276,6 +7306,9 @@ mod tests { let m = Map(HashMap::from([("polys".to_string(), polys), ("pts".to_string(), pts)])); let res_normal = crate::run("selectByLocation", &m, &serde_json::json!({"input": "pts", "select": "polys"})).unwrap(); + // The point without geometry is said, once; a selecting layer with geometry everywhere isn't. + assert_eq!(res_normal.messages.len(), 2); + assert_eq!(res_normal.messages.get(1).map(String::as_str), Some("1 of 3 features lack geometry, so they are not selected")); match res_normal.output { Output::Selection { rows, .. } => assert_eq!(rows, vec![0], "normal select should only select intersecting feature"), _ => panic!("expected selection"),