From 4c70ed13ccc443ca160aea94800ac7700de14e23 Mon Sep 17 00:00:00 2001 From: mavrick Date: Tue, 17 Nov 2026 12:09:15 -0600 Subject: [PATCH 01/12] feat(analysis): Service Area and OD Cost Matrix over a line network (#2344) Two geoprocessing tools search a line layer as a network, on the graph a route already builds and caches: - Service Area: the lines reachable within one or more breaks of the nearest facility, cut where a break or the nearest facility changes, keeping the lines' attributes. - OD Cost Matrix: a table of the cheapest cost and length from each origin to each destination, with an optional cutoff and number of destinations, the origins searched on several threads. A shared Search runs Dijkstra from several starts with a cost limit and reuses its scratch between searches. A point in the middle of a line is reached from where it stands, both ways along it. Points too far from the network, lines with no cost or closed by it, and unconnected pairs are counted in notices. Co-Authored-By: Claude Opus 5.5 --- crates/analysis/src/network.rs | 345 ++++++++-- crates/analysis/src/tools.rs | 119 ++++ crates/analysis/src/tools/network_analysis.rs | 620 ++++++++++++++++++ crates/engine/src/tests/cancellation.rs | 4 +- docs/user-guide/analysis.md | 32 + 5 files changed, 1079 insertions(+), 41 deletions(-) create mode 100644 crates/analysis/src/tools/network_analysis.rs diff --git a/crates/analysis/src/network.rs b/crates/analysis/src/network.rs index 3c2daf3f43..fbe196a1bc 100644 --- a/crates/analysis/src/network.rs +++ b/crates/analysis/src/network.rs @@ -205,6 +205,69 @@ fn shortest_route_with( route_on(&graph, ds, from, to, snap_m) } +/// The closest point on any of `segs` to `p`: (segment, fraction along it, the point, metres +/// away). With `within`, only segments whose box comes within about that many metres of `p` are +/// measured; one farther can't be within it, so a nearer one is never missed. +fn nearest_segment(segs: &[Segment], nodes: &[Coord], p: Coord, within: Option) -> Result, String> { + crate::control::check()?; + let window = within.and_then(|m| snap_window(p, m)); + let k = p.y.to_radians().cos().max(0.01); + let mut stopped = false; + let mut pace = crate::control::Pace::default(); + let nearest = segs + .iter() + .enumerate() + .take_while(|_| { + stopped = pace.stop(4096); + !stopped + }) + .filter_map(|(i, (a, b, _, _))| { + let (a, b) = (*nodes.get(*a)?, *nodes.get(*b)?); + if let Some([x0, x1, y0, y1]) = window + && (a.x.max(b.x) < x0 || a.x.min(b.x) > x1 || a.y.max(b.y) < y0 || a.y.min(b.y) > y1) + { + return None; + } + let (dx, dy) = ((b.x - a.x) * k, b.y - a.y); + let len2 = dx * dx + dy * dy; + let t = if len2 > 0.0 { (((p.x - a.x) * k * dx + (p.y - a.y) * dy) / len2).clamp(0.0, 1.0) } else { 0.0 }; + let q = Coord::new(a.x + t * (b.x - a.x), a.y + t * (b.y - a.y)); + Some((i, t, q, haversine_m(q, p))) + }) + .fold(None, |best: Option<(usize, f64, Coord, f64)>, (i, t, q, sphere)| { + // The minimum WGS 84 radius gives a lower bound, so a farther spherical + // candidate cannot be discarded merely because the two metrics rank it differently. + let lower = if (-90.0..=90.0).contains(&p.y) && (-90.0..=90.0).contains(&q.y) { + sphere * WGS84_MIN_RADIUS_M / EARTH_RADIUS_M + } else { + 0.0 // The inverse solver clamps latitudes; the spherical bound would not apply. + }; + if best.as_ref().is_some_and(|b| lower > b.3) { + return best; + } + let distance = wgs84_distance_m(q, p); + if distance.is_finite() && best.as_ref().is_none_or(|b| distance < b.3) { Some((i, t, q, distance)) } else { best } + }); + if stopped { + return Err(crate::control::Cancelled.into()); + } + Ok(nearest) +} + +/// The longitudes and latitudes `[west, east, south, north]` holding every place within `m` +/// metres of `p`, with room to spare: a degree of latitude is at least 110.5 km long, and a degree +/// of longitude at least that times the cosine of the latitude. None near a pole or ±180°, where a +/// box doesn't hold them; then every segment is measured. +fn snap_window(p: Coord, m: f64) -> Option<[f64; 4]> { + let dlat = m / 110_000.0 * 1.5; + let top = p.y.abs() + dlat; + if !dlat.is_finite() || top.is_nan() || top >= 80.0 { + return None; + } + let dlon = dlat / top.to_radians().cos(); + (p.x - dlon > -180.0 && p.x + dlon < 180.0).then_some([p.x - dlon, p.x + dlon, p.y - dlat, p.y + dlat]) +} + /// Runs the original search on a private copy, so endpoint attachments never leak across calls. /// Cloning the node and adjacency vectors is one step without a Cancel check inside it. fn route_on(graph: &Network, ds: &Dataset, from: Coord, to: Coord, snap_m: f64) -> Result { @@ -214,46 +277,7 @@ fn route_on(graph: &Network, ds: &Dataset, from: Coord, to: Coord, snap_m: f64) let segs = &graph.segs; let skipped_segments = graph.skipped_segments; let route_error = |reason, skipped| route_error(ds, reason, skipped); - // The closest point on any segment: (segment, fraction along it, the point, metres away). - let nearest = |p: Coord, nodes: &[Coord]| -> Result, String> { - crate::control::check()?; - let k = p.y.to_radians().cos().max(0.01); - let mut stopped = false; - let mut pace = crate::control::Pace::default(); - let nearest = segs - .iter() - .enumerate() - .take_while(|_| { - stopped = pace.stop(4096); - !stopped - }) - .filter_map(|(i, (a, b, _, _))| { - let (a, b) = (*nodes.get(*a)?, *nodes.get(*b)?); - let (dx, dy) = ((b.x - a.x) * k, b.y - a.y); - let len2 = dx * dx + dy * dy; - let t = if len2 > 0.0 { (((p.x - a.x) * k * dx + (p.y - a.y) * dy) / len2).clamp(0.0, 1.0) } else { 0.0 }; - let q = Coord::new(a.x + t * (b.x - a.x), a.y + t * (b.y - a.y)); - Some((i, t, q, haversine_m(q, p))) - }) - .fold(None, |best: Option<(usize, f64, Coord, f64)>, (i, t, q, sphere)| { - // The minimum WGS 84 radius gives a lower bound, so a farther spherical - // candidate cannot be discarded merely because the two metrics rank it differently. - let lower = if (-90.0..=90.0).contains(&p.y) && (-90.0..=90.0).contains(&q.y) { - sphere * WGS84_MIN_RADIUS_M / EARTH_RADIUS_M - } else { - 0.0 // The inverse solver clamps latitudes; the spherical bound would not apply. - }; - if best.as_ref().is_some_and(|b| lower > b.3) { - return best; - } - let distance = wgs84_distance_m(q, p); - if distance.is_finite() && best.as_ref().is_none_or(|b| distance < b.3) { Some((i, t, q, distance)) } else { best } - }); - if stopped { - return Err(crate::control::Cancelled.into()); - } - Ok(nearest) - }; + let nearest = |p: Coord, nodes: &[Coord]| nearest_segment(segs, nodes, p, None); // Each end becomes a node on its segment, joined to the segment's two ends. let attach = |p: Coord, nodes: &mut Vec, adj: &mut Vec>| -> Result<(usize, usize, f64), String> { let (si, t, q, d) = nearest(p, nodes)?.ok_or_else(|| route_error("the layer has no lines".into(), skipped_segments))?; @@ -361,6 +385,247 @@ fn route_on(graph: &Network, ds: &Dataset, from: Coord, to: Coord, snap_m: f64) Ok(Route { path, length_m: length, cost, rows: used, skipped_segments }) } +// --------------------------------------------------------------------------------------------- +// Searches from several places at once, for service areas and cost matrices (#2344) + +/// A line network for searches from many places: the route's graph, shared through the same +/// cache, so a route, a service area and a cost matrix over unchanged lines build it once. +pub(crate) struct Graph(Arc); + +/// A point moved onto the network: onto segment `seg`, at `at`, `to_a` and `to_b` metres along +/// the segment from its two ends. +#[derive(Clone, Copy, Debug)] +pub(crate) struct Placed { + pub(crate) seg: usize, + pub(crate) at: Coord, + pub(crate) to_a: f64, + to_b: f64, +} + +/// One segment of the network: its two ends (nodes), their places, the weight its length is +/// multiplied by, and the row of the line it belongs to. +pub(crate) struct SegmentInfo { + pub(crate) a: usize, + pub(crate) b: usize, + pub(crate) from: Coord, + pub(crate) to: Coord, + pub(crate) weight: f64, + pub(crate) row: usize, +} + +impl Graph { + /// The network over `rows` of `ds` (in that order), each line's length multiplied by its + /// `cost_field` value as for [`shortest_route`]. Reused while the lines don't change. + pub(crate) fn of(ds: &Dataset, rows: &[usize], cost_field: Option) -> Result { + network_for(&NETWORK, ds, rows, cost_field).map(Self) + } + + pub(crate) fn nodes(&self) -> usize { + self.0.nodes.len() + } + + pub(crate) fn segments(&self) -> usize { + self.0.segs.len() + } + + /// Segments left out of the network for invalid coordinates. + pub(crate) fn skipped_segments(&self) -> usize { + self.0.skipped_segments + } + + /// Segment `i`, in the order the lines and their vertices were read; None past the last. + pub(crate) fn segment(&self, i: usize) -> Option { + let &(a, b, weight, row) = self.0.segs.get(i)?; + Some(SegmentInfo { a, b, from: *self.0.nodes.get(a)?, to: *self.0.nodes.get(b)?, weight, row }) + } + + /// `p` moved onto the nearest segment, or None when none is within `snap_m` metres (or there + /// are no segments). Measured as a route's ends are. + pub(crate) fn place(&self, p: Coord, snap_m: f64) -> Result, String> { + if !p.is_finite() || p.y.abs() > 90.0 { + return Ok(None); + } + let Some((seg, _, at, moved_m)) = nearest_segment(&self.0.segs, &self.0.nodes, p, Some(snap_m))? else { return Ok(None) }; + if moved_m > snap_m { + return Ok(None); + } + let Some(s) = self.segment(seg) else { return Ok(None) }; + Ok(Some(Placed { seg, at, to_a: wgs84_distance_m(at, s.from), to_b: wgs84_distance_m(at, s.to) })) + } + + /// Where a search from `p` starts: both ends of its segment, at the cost and length of the + /// way along it, labelled `source`. + pub(crate) fn starts(&self, p: &Placed, source: usize) -> [Start; 2] { + let (a, b, w) = self.0.segs.get(p.seg).map_or((0, 0, 1.0), |s| (s.0, s.1, s.2)); + [Start { node: a, cost: p.to_a * w, length: p.to_a, source }, Start { node: b, cost: p.to_b * w, length: p.to_b, source }] + } + + /// The cheapest way to `to` found by `search`, as (cost, length): through either end of its + /// segment, or straight along it from `from` when both lie on the same segment. Infinite when + /// the search didn't reach it. + pub(crate) fn reach(&self, search: &Search, from: &Placed, to: &Placed) -> (f64, f64) { + let Some(&(a, b, w, _)) = self.0.segs.get(to.seg) else { return (f64::INFINITY, f64::INFINITY) }; + let mut best = (f64::INFINITY, f64::INFINITY); + for (node, along) in [(a, to.to_a), (b, to.to_b)] { + let cost = search.cost(node) + along * w; + if cost < best.0 { + best = (cost, search.length(node) + along); + } + } + if from.seg == to.seg { + let along = wgs84_distance_m(from.at, to.at); + if along * w <= best.0 { + best = (along * w, along); + } + } + best + } +} + +/// Where a search starts: a node, the cost and length of reaching it from the start's own place, +/// and the start's label (a facility's or an origin's number). +#[derive(Clone, Copy, Debug)] +pub(crate) struct Start { + pub(crate) node: usize, + pub(crate) cost: f64, + pub(crate) length: f64, + pub(crate) source: usize, +} + +/// A search's working state, made once per thread and reused: each search resets only the nodes +/// the last one reached, so many short searches over a large network don't each clear it all. +pub(crate) struct Search { + cost: Vec, + length: Vec, + source: Vec, + settled: Vec, + touched: Vec, + heap: BinaryHeap, +} + +impl Search { + /// The bytes a search over `nodes` nodes holds, for sharing memory between threads. + pub(crate) fn bytes(nodes: usize) -> usize { + nodes.saturating_mul(3 * size_of::() + 1 + 2 * size_of::()) + } + + pub(crate) fn new(graph: &Graph) -> Self { + let n = graph.nodes(); + Self { + cost: vec![f64::INFINITY; n], + length: vec![f64::INFINITY; n], + source: vec![usize::MAX; n], + settled: vec![false; n], + touched: Vec::new(), + heap: BinaryHeap::new(), + } + } + + /// The least cost of reaching `node` in the last search: exact for every node it settled, + /// above `limit` (or infinite) for the rest. + pub(crate) fn cost(&self, node: usize) -> f64 { + self.cost.get(node).copied().unwrap_or(f64::INFINITY) + } + + /// The length of the way to `node` that [`Search::cost`] costs. + pub(crate) fn length(&self, node: usize) -> f64 { + self.length.get(node).copied().unwrap_or(f64::INFINITY) + } + + /// The start `node` is reached from most cheaply (the first given, of equally cheap ones). + pub(crate) fn source(&self, node: usize) -> Option { + self.source.get(node).copied().filter(|s| *s != usize::MAX) + } + + /// Settles nodes in order of their cost from the nearest of `starts`, every node costing up to + /// `limit`, and calls `settled` with each; the search ends early when it returns true. With + /// `progress`, counts the nodes settled for the run's progress (a search on its own, not one + /// of many made on several threads, which count theirs). + pub(crate) fn run( + &mut self, + graph: &Graph, + starts: &[Start], + limit: f64, + progress: bool, + mut settled: impl FnMut(usize) -> bool, + ) -> Result<(), String> { + for &n in &self.touched { + if let Some(c) = self.cost.get_mut(n) { + *c = f64::INFINITY; + } + if let Some(l) = self.length.get_mut(n) { + *l = f64::INFINITY; + } + if let Some(s) = self.source.get_mut(n) { + *s = usize::MAX; + } + if let Some(s) = self.settled.get_mut(n) { + *s = false; + } + } + self.touched.clear(); + self.heap.clear(); + crate::control::check()?; + for s in starts { + self.improve(s.node, s.cost, s.length, s.source); + } + let adj = &graph.0.adj; + if progress { + crate::control::begin(adj.len()); + } + let mut visited = 0; + let mut pace = crate::control::Pace::default(); + while let Some(State(d, u)) = self.heap.pop() { + if pace.stop(1) { + return Err(crate::control::Cancelled.into()); + } + if d > self.cost(u) || self.settled.get(u).copied().unwrap_or(true) { + continue; + } + if d > limit { + break; + } + if let Some(s) = self.settled.get_mut(u) { + *s = true; + } + visited += 1; + if progress { + crate::control::reached(visited); + } + if settled(u) { + break; + } + let (length, source) = (self.length(u), self.source.get(u).copied().unwrap_or(usize::MAX)); + for &(v, c, len, _) in adj.get(u).map(Vec::as_slice).unwrap_or(&[]) { + self.improve(v, d + c, length + len, source); + } + } + if progress { + crate::control::finish(); + } + Ok(()) + } + + /// Records a cheaper way to `node`, if this is one. + fn improve(&mut self, node: usize, cost: f64, length: f64, source: usize) { + let Some(old) = self.cost.get_mut(node) else { return }; + if cost.is_nan() || cost >= *old { + return; + } + if old.is_infinite() { + self.touched.push(node); + } + *old = cost; + if let Some(l) = self.length.get_mut(node) { + *l = length; + } + if let Some(s) = self.source.get_mut(node) { + *s = source; + } + self.heap.push(State(cost, node)); + } +} + /// Most random points made in one call, and point-in-polygon tries spent making them. pub const MAX_POINTS: usize = 1_000_000; const MAX_TRIES: usize = 50_000_000; diff --git a/crates/analysis/src/tools.rs b/crates/analysis/src/tools.rs index 617b919d3b..c03c2e9926 100644 --- a/crates/analysis/src/tools.rs +++ b/crates/analysis/src/tools.rs @@ -2,6 +2,7 @@ mod check_geometry; mod geometry; +mod network_analysis; mod repair_geometry; mod tabulate_area; @@ -271,6 +272,124 @@ pub static TOOLS: &[ToolSpec] = &[ ], run: near, }, + ToolSpec { + id: "serviceArea", + name: "Service Area", + toolbox: "Analysis › Network", + summary: "Finds the lines reachable within one or more travel costs of points, along a line network.", + params: &[ + P { + name: "network", + label: "Network Lines", + kind: K::VectorLayer, + required: true, + default: "", + help: "A line layer. Lines join where their vertices meet.", + }, + P { + name: "facilities", + label: "Facilities", + kind: K::PointLayer, + required: true, + default: "", + help: "The points to measure from. Each is moved onto the nearest line.", + }, + P { + name: "breaks", + label: "Breaks", + kind: K::Text, + required: true, + default: "\"1, 2, 5\"", + help: "Costs to stop at, separated by commas, in the units below. Each part of a line is labelled with the band it lies in and the facility nearest to it.", + }, + P { name: "units", label: "Units", kind: K::Choice(UNITS), required: false, default: "\"Kilometers\"", help: "" }, + P { + name: "costField", + label: "Cost Field", + kind: K::NumericField, + required: false, + default: "", + help: "Multiplies each line's length, so breaks count weighted distance. Empty counts the length alone; 0 or less closes a line.", + }, + P { + name: "snapDistance", + label: "Snap Distance (m)", + kind: K::Number, + required: false, + default: "1000", + help: "How far a facility may be moved onto the network, in metres. Farther ones are left out.", + }, + P { name: "output", label: "Output Name", kind: K::Text, required: false, default: "", help: "" }, + ], + run: network_analysis::service_area, + }, + ToolSpec { + id: "odCostMatrix", + name: "OD Cost Matrix", + toolbox: "Analysis › Network", + summary: "Measures the cost and length of the cheapest way along a line network from each origin to each destination.", + params: &[ + P { + name: "network", + label: "Network Lines", + kind: K::VectorLayer, + required: true, + default: "", + help: "A line layer. Lines join where their vertices meet.", + }, + P { + name: "origins", + label: "Origins", + kind: K::PointLayer, + required: true, + default: "", + help: "Each is moved onto the nearest line.", + }, + P { + name: "destinations", + label: "Destinations", + kind: K::PointLayer, + required: true, + default: "", + help: "Each is moved onto the nearest line.", + }, + P { name: "units", label: "Units", kind: K::Choice(UNITS), required: false, default: "\"Kilometers\"", help: "" }, + P { + name: "costField", + label: "Cost Field", + kind: K::NumericField, + required: false, + default: "", + help: "Multiplies each line's length. Empty counts the length alone; 0 or less closes a line.", + }, + P { + name: "cutoff", + label: "Cutoff", + kind: K::Number, + required: false, + default: "", + help: "Leaves out destinations costing more than this, in the units above. Empty: no limit.", + }, + P { + name: "count", + label: "Destinations to Find", + kind: K::Number, + required: false, + default: "", + help: "Keeps only this many of the cheapest destinations from each origin. Empty: all.", + }, + P { + name: "snapDistance", + label: "Snap Distance (m)", + kind: K::Number, + required: false, + default: "1000", + help: "How far an origin or destination may be moved onto the network, in metres. Farther ones are left out.", + }, + P { name: "output", label: "Output Name", kind: K::Text, required: false, default: "", help: "" }, + ], + run: network_analysis::od_cost_matrix, + }, ToolSpec { id: "convexHull", name: "Minimum Bounding Geometry", diff --git a/crates/analysis/src/tools/network_analysis.rs b/crates/analysis/src/tools/network_analysis.rs new file mode 100644 index 0000000000..5eea175fdc --- /dev/null +++ b/crates/analysis/src/tools/network_analysis.rs @@ -0,0 +1,620 @@ +//! Service areas and origin–destination cost matrices over a line layer (#2344), searched on the +//! network a route uses ([`crate::network::Graph`]): lines join where their vertices coincide, and +//! each line's length, on the WGS 84 ellipsoid, is multiplied by its cost field's value. +use super::*; +use crate::network::{Graph, Placed, Search, Start}; +use std::collections::BTreeMap; +use std::sync::atomic::{AtomicUsize, Ordering}; + +/// The most breaks a service area takes. +const MAX_BREAKS: usize = 32; +/// The most rows a cost matrix may hold. +const MAX_PAIRS: usize = 10_000_000; +/// How far a point may be moved onto the network when no snap distance is given, in metres. +const SNAP_M: f64 = 1000.0; + +/// What both tools read first: the network's layer and graph, the unit costs are given and +/// written in, how far points may be moved onto the network, and the notices about the network. +struct Network<'a> { + ds: &'a Dataset, + graph: Graph, + unit_m: f64, + snap_m: f64, + notes: Vec, +} + +/// Reads the `network`, `costField`, `units` and `snapDistance` parameters and builds (or reuses) +/// the graph over the network's selected lines, counting lines with no cost or closed by it, and +/// segments with invalid coordinates, in notices. An error when no line is left to search. +fn network<'a>(inp: &'a dyn Inputs, p: &Json, tool: &str) -> Result, String> { + let ds = input(inp, p, "network")?; + if ds.geometry_type != GeometryType::Polyline { + return Err(format!("{tool} searches a line layer; '{}' holds no lines", ds.name)); + } + let cost_field = match s(p, "costField").trim() { + "" => None, + name => Some(ds.field_index(name).ok_or_else(|| format!("'{}' has no field named '{name}'", ds.name))?), + }; + let unit_m = to_metres(1.0, s(p, "units"))?; + let snap_m = match p.get("snapDistance").filter(|v| !v.is_null() && v.as_str().is_none_or(|t| !t.trim().is_empty())) { + None => SNAP_M, + Some(_) => num(p, "snapDistance").filter(|d| *d >= 0.0).ok_or("Snap Distance must be a number of metres, 0 or more")?, + }; + let mut rows = rows(inp, p, "network", ds); + rows.sort_unstable(); + rows.dedup(); + let mut notes = Vec::new(); + if let Some(fi) = cost_field { + // As a route reads them: no number costs the length alone, zero or less closes the line. + let (mut missing, mut closed) = (0usize, 0usize); + for &r in &rows { + crate::control::check()?; + match ds.value(r, fi).as_f64() { + Some(w) if w.is_finite() && w > 0.0 => {} + Some(_) => closed += 1, + None => missing += 1, + } + } + let field = ds.fields.get(fi).map_or("", |f| f.name.as_str()); + if missing > 0 { + notes.push(format!("{tool}: {missing} line(s) of '{}' have no number in {field}, and cost their length", ds.name)); + } + if closed > 0 { + notes.push(format!("{tool}: {closed} line(s) of '{}' cost zero or less in {field}, and are closed", ds.name)); + } + } + let graph = Graph::of(ds, &rows, cost_field)?; + if graph.skipped_segments() > 0 { + notes.push(format!( + "{tool}: {} segment(s) of '{}' with invalid coordinates were left out of the network", + graph.skipped_segments(), + ds.name + )); + } + if graph.segments() == 0 { + return Err(format!("'{}' has no lines to search", ds.name)); + } + Ok(Network { ds, graph, unit_m, snap_m, notes }) +} + +/// The features of a point layer moved onto the network, in layer order, as (feature id, place), +/// with a notice for each kind left out: no point, several points, or too far from the network. +/// An error when none is left. +fn place(inp: &dyn Inputs, p: &Json, key: &str, net: &mut Network<'_>, tool: &str) -> Result, String> { + let ds = input(inp, p, key)?; + if ds.geometry_type != GeometryType::Point { + return Err(format!("{tool} places points; '{}' holds no points", ds.name)); + } + let mut rows = rows(inp, p, key, ds); + rows.sort_unstable(); + rows.dedup(); + enum Got { + Placed(u64, Placed), + NoPoint, + Several, + Far, + } + let (graph, snap_m) = (&net.graph, net.snap_m); + crate::control::begin(rows.len()); + let got = crate::parallel::try_map( + &rows, + 64, + || (), + |_, _, &r| { + let Some(f) = ds.features.get(r) else { return Ok(Got::NoPoint) }; + let at = match &f.geometry { + Some(Geometry::Point(c)) => *c, + Some(Geometry::MultiPoint(v)) => match v.as_slice() { + [] => return Ok(Got::NoPoint), + [c] => *c, + _ => return Ok(Got::Several), + }, + _ => return Ok(Got::NoPoint), + }; + if !at.is_finite() || at.y.abs() > 90.0 { + return Ok(Got::NoPoint); + } + Ok::<_, String>(graph.place(at, snap_m)?.map_or(Got::Far, |placed| Got::Placed(f.id, placed))) + }, + )?; + let (mut placed, mut no_point, mut several, mut far) = (Vec::new(), 0usize, 0usize, 0usize); + for g in got { + match g { + Got::Placed(id, at) => placed.push((id, at)), + Got::NoPoint => no_point += 1, + Got::Several => several += 1, + Got::Far => far += 1, + } + } + let name = &ds.name; + if no_point > 0 { + net.notes.push(format!("{tool}: {no_point} feature(s) of '{name}' have no usable point, and were left out")); + } + if several > 0 { + net.notes.push(format!("{tool}: {several} feature(s) of '{name}' hold several points, and were left out")); + } + if far > 0 { + let snap = rustgis_geom::format_distance(snap_m); + net.notes.push(format!("{tool}: {far} feature(s) of '{name}' lie more than {snap} from '{}', and were left out", net.ds.name)); + } + if placed.is_empty() { + let mut why = format!("none of the {} feature(s) of '{name}' could be placed on '{}'", rows.len(), net.ds.name); + if far > 0 { + why.push_str("; a larger Snap Distance may reach them"); + } + return Err(why); + } + Ok(placed) +} + +/// The service area's breaks, ascending, in the tool's units: numbers separated by commas or +/// spaces, a number, or a list of them. +fn breaks(p: &Json) -> Result, String> { + let bad = || "Breaks must be numbers above 0, such as 5, 10, 15".to_string(); + let mut out = match p.get("breaks") { + Some(Json::Number(n)) => vec![n.as_f64().ok_or_else(bad)?], + Some(Json::String(t)) => t + .split([',', ' ', ';']) + .filter(|v| !v.trim().is_empty()) + .map(|v| v.trim().parse::().map_err(|_| bad())) + .collect::>()?, + Some(Json::Array(a)) => a.iter().map(|v| v.as_f64().ok_or_else(bad)).collect::>()?, + _ => return Err("Breaks are required, such as 5, 10, 15".into()), + }; + if out.is_empty() || out.iter().any(|b| !b.is_finite() || *b <= 0.0) { + return Err(bad()); + } + out.sort_by(f64::total_cmp); + out.dedup(); + if out.len() > MAX_BREAKS { + return Err(format!("Service Area takes at most {MAX_BREAKS} breaks")); + } + Ok(out) +} + +/// The parts of a stretch of network from `p` (reached at cost `cp`, from start `lp`) to `q` +/// (`cq`, `lq`), costing `c` from end to end, that each band of `limits` reaches: (band, start, +/// from, to), `from` and `to` being fractions of the way from `p` to `q`. A place on it costs the +/// lesser of reaching it from either end, so the cost rises from each end to a peak between them; +/// a part is reached from the end it lies on the side of. +fn bands(cp: f64, cq: f64, c: f64, lp: Option, lq: Option, limits: &[f64]) -> Vec<(usize, usize, f64, f64)> { + let peak = match (cp.is_finite(), cq.is_finite()) { + (false, false) => return Vec::new(), + (true, false) => 1.0, + (false, true) => 0.0, + (true, true) => ((cq - cp + c) / (2.0 * c)).clamp(0.0, 1.0), + }; + let mut out = Vec::new(); + let mut lo = 0.0; + for (k, &hi) in limits.iter().enumerate() { + if let Some(lp) = lp.filter(|_| cp.is_finite()) { + let (from, to) = (((lo - cp) / c).max(0.0), ((hi - cp) / c).min(peak)); + if to > from { + out.push((k, lp, from, to)); + } + } + if let Some(lq) = lq.filter(|_| cq.is_finite()) { + let (from, to) = ((1.0 - (hi - cq) / c).max(peak), (1.0 - (lo - cq) / c).min(1.0)); + if to > from { + out.push((k, lq, from, to)); + } + } + lo = hi; + } + out.sort_by(|a, b| a.2.total_cmp(&b.2)); + out +} + +/// The place a fraction `t` of the way from `a` to `b`, exactly `a` and `b` at the ends. +fn along(a: Coord, b: Coord, t: f64) -> Coord { + if t <= 0.0 { + a + } else if t >= 1.0 { + b + } else { + Coord::new(a.x + t * (b.x - a.x), a.y + t * (b.y - a.y)) + } +} + +/// Service Area: the lines reached within each break from the nearest facility, each line cut +/// where a break or the facility it is nearest changes. One search from every facility at once, +/// then one pass over the network's segments. +pub(super) fn service_area(inp: &dyn Inputs, p: &Json) -> Result { + const TOOL: &str = "Service Area"; + let mut net = network(inp, p, TOOL)?; + let breaks = breaks(p)?; + let limits: Vec = breaks.iter().map(|b| b * net.unit_m).collect(); + let facilities = place(inp, p, "facilities", &mut net, TOOL)?; + let graph = &net.graph; + let starts: Vec = facilities.iter().enumerate().flat_map(|(i, (_, at))| graph.starts(at, i)).collect(); + let mut search = Search::new(graph); + search.run(graph, &starts, limits.last().copied().unwrap_or(0.0), true, |_| false)?; + + // A facility's own segment is reached from the facility itself, at no cost, as well as from + // its ends: the segment is cut there. + let mut on: HashMap> = HashMap::new(); + for (i, (_, at)) in facilities.iter().enumerate() { + on.entry(at.seg).or_default().push((at.to_a, at.at, i)); + } + for v in on.values_mut() { + v.sort_by(|a, b| a.0.total_cmp(&b.0)); + } + // Each line's parts in each band, from each facility, joined where they meet. + let mut parts: BTreeMap<(usize, usize, usize), Vec>> = BTreeMap::new(); + crate::control::begin(graph.segments()); + for i in 0..graph.segments() { + crate::control::check()?; + crate::control::reached(i); + let Some(sg) = graph.segment(i) else { continue }; + let mut stops = vec![(sg.from, search.cost(sg.a), search.source(sg.a))]; + stops.extend(on.get(&i).into_iter().flatten().map(|&(_, at, f)| (at, 0.0, Some(f)))); + stops.push((sg.to, search.cost(sg.b), search.source(sg.b))); + for w in stops.windows(2) { + let &[(a, ca, la), (b, cb, lb)] = w else { continue }; + let c = rustgis_geom::wgs84_distance_m(a, b) * sg.weight; + if c.is_nan() || c <= 0.0 { + continue; + } + for (band, facility, from, to) in bands(ca, cb, c, la, lb, &limits) { + let (start, end) = (along(a, b, from), along(a, b, to)); + let lines = parts.entry((sg.row, band, facility)).or_default(); + match lines.last_mut() { + Some(line) if line.last() == Some(&start) => line.push(end), + _ => lines.push(vec![start, end]), + } + } + } + } + crate::control::finish(); + + let ds = net.ds; + let mut out = copy_schema(ds, out_name(p, format!("{}_ServiceArea", ds.name)), GeometryType::Polyline); + out.crs = ds.crs; + for (name, ty) in [("facility_fid", FieldType::Integer), ("from_break", FieldType::Double), ("to_break", FieldType::Double)] { + let name = unique_field(&out, name); + out.fields.push(Field::new(name, ty)); + } + let mut reached = HashSet::new(); + for ((row, band, facility), lines) in parts { + crate::control::check()?; + let Some(f) = ds.features.get(row) else { continue }; + reached.insert(facility); + let mut attrs: Vec = (0..ds.fields.len()).map(|i| f.attrs.get(i).cloned().unwrap_or(Value::Null)).collect(); + let fid = facilities.get(facility).map_or(Value::Null, |(id, _)| i64::try_from(*id).map_or(Value::Null, Value::Int)); + let from = if band == 0 { 0.0 } else { breaks.get(band - 1).copied().unwrap_or(0.0) }; + attrs.extend([fid, Value::Float(from), Value::Float(breaks.get(band).copied().unwrap_or(0.0))]); + out.push(Some(Geometry::Line(lines)), attrs); + } + let units = if s(p, "units").is_empty() { "Kilometers" } else { s(p, "units") }; + let mut messages = vec![format!( + "{TOOL}: {} line part(s) reached from {} of {} facilities, in {units}", + out.features.len(), + reached.len(), + facilities.len() + )]; + messages.append(&mut net.notes); + Ok(ToolResult { output: Output::Layer(out), messages }) +} + +/// OD Cost Matrix: the cost and length of the cheapest way from each origin to each destination, +/// one search per origin, the origins on several threads. A search ends once it has settled both +/// ends of every destination's segment, or passed the cutoff. +pub(super) fn od_cost_matrix(inp: &dyn Inputs, p: &Json) -> Result { + od_cost_matrix_on(inp, p, None) +} + +/// [`od_cost_matrix`] on `threads` threads (none: as many as the memory and origins allow). +pub(super) fn od_cost_matrix_on(inp: &dyn Inputs, p: &Json, threads: Option) -> Result { + const TOOL: &str = "OD Cost Matrix"; + let mut net = network(inp, p, TOOL)?; + let given = |k: &str| p.get(k).filter(|v| !v.is_null() && v.as_str().is_none_or(|t| !t.trim().is_empty())).is_some(); + let cutoff = match given("cutoff") { + false => None, + true => Some(num(p, "cutoff").filter(|c| *c >= 0.0).ok_or("Cutoff must be a number, 0 or more")?), + }; + let count = match given("count") { + false => None, + true => Some( + num(p, "count") + .filter(|n| *n >= 1.0 && n.fract() == 0.0) + .map(|n| n.min(MAX_PAIRS as f64) as usize) + .ok_or("Destinations to Find must be a whole number, 1 or more")?, + ), + }; + let origins = place(inp, p, "origins", &mut net, TOOL)?; + let destinations = place(inp, p, "destinations", &mut net, TOOL)?; + let per_origin = count.map_or(destinations.len(), |n| n.min(destinations.len())); + if cutoff.is_none() && origins.len().saturating_mul(per_origin) > MAX_PAIRS { + return Err(format!( + "{TOOL}: {} origins by {per_origin} destinations is more than {MAX_PAIRS} rows; set a Cutoff or Destinations to Find", + origins.len() + )); + } + let (graph, unit_m) = (&net.graph, net.unit_m); + let limit = cutoff.map_or(f64::INFINITY, |c| c * unit_m); + // Both ends of every destination's segment: once all are settled, nothing nearer is left. + let mut target = vec![false; graph.nodes()]; + let mut targets = 0usize; + for (_, d) in &destinations { + let Some(sg) = graph.segment(d.seg) else { continue }; + for n in [sg.a, sg.b] { + if let Some(t) = target.get_mut(n).filter(|t| !**t) { + *t = true; + targets += 1; + } + } + } + let rows = AtomicUsize::new(0); + let threads = threads.unwrap_or_else(|| crate::parallel::threads_for_each(origins.len(), 2, Search::bytes(graph.nodes()))); + crate::control::begin(origins.len()); + let found = crate::parallel::try_map_each_on( + &origins, + threads, + || Search::new(graph), + |search, _, (_, o)| { + let mut settled = 0usize; + search.run(graph, &graph.starts(o, 0), limit, false, |u| { + if target.get(u).copied().unwrap_or(false) { + settled += 1; + } + settled == targets + })?; + let mut row: Vec<(usize, f64, f64)> = destinations + .iter() + .enumerate() + .filter_map(|(j, (_, d))| { + let (cost, length) = graph.reach(search, o, d); + (cost.is_finite() && cost <= limit).then_some((j, cost, length)) + }) + .collect(); + row.sort_by(|a, b| a.1.total_cmp(&b.1).then(a.0.cmp(&b.0))); + row.truncate(per_origin); + if rows.fetch_add(row.len(), Ordering::Relaxed).saturating_add(row.len()) > MAX_PAIRS { + return Err(format!( + "{TOOL}: the matrix would hold more than {MAX_PAIRS} rows; set a lower Cutoff or Destinations to Find" + )); + } + Ok(row) + }, + )?; + crate::control::finish(); + + let fields = ["origin_fid", "destination_fid", "rank"].map(|n| Field::new(n, FieldType::Integer)); + let mut out = Dataset::new( + out_name(p, format!("{}_ODCostMatrix", net.ds.name)), + GeometryType::None, + fields.into_iter().chain(["cost", "length"].map(|n| Field::new(n, FieldType::Double))).collect(), + ); + let id = |v: u64| i64::try_from(v).map_or(Value::Null, Value::Int); + let mut unreached = 0usize; + for ((oid, _), row) in origins.iter().zip(&found) { + crate::control::check()?; + unreached += per_origin - row.len(); + for (rank, &(j, cost, length)) in row.iter().enumerate() { + let did = destinations.get(j).map_or(Value::Null, |(d, _)| id(*d)); + out.push(None, vec![id(*oid), did, Value::Int(rank as i64 + 1), Value::Float(cost / unit_m), Value::Float(length / unit_m)]); + } + } + let units = if s(p, "units").is_empty() { "Kilometers" } else { s(p, "units") }; + let mut messages = vec![format!( + "{TOOL}: {} pair(s) from {} origin(s) to {} destination(s), in {units}", + out.features.len(), + origins.len(), + destinations.len() + )]; + if unreached > 0 { + messages.push(match cutoff { + None => format!("{TOOL}: {unreached} origin–destination pair(s) aren't connected by '{}', and have no row", net.ds.name), + Some(c) => { + format!("{TOOL}: {unreached} origin–destination pair(s) cost more than {c} {units} or aren't connected, and have no row") + } + }); + } + messages.append(&mut net.notes); + Ok(ToolResult { output: Output::Table(out), messages }) +} + +#[cfg(test)] +mod tests { + use super::*; + use rustgis_geom::wgs84_distance_m as dist; + use serde_json::json; + + struct Map(HashMap); + impl Inputs for Map { + fn dataset(&self, layer: &str) -> Option<&Dataset> { + self.0.get(layer) + } + fn selection(&self, _: &str) -> &[usize] { + &[] + } + } + + fn c(x: f64, y: f64) -> Coord { + Coord::new(x, y) + } + + /// Roads near the equator, about 1.1 km a hundredth of a degree: a line east from (0, 0) to + /// (0.02, 0) with a vertex at 0.01, a line north from that vertex, a line on east to 0.03 + /// costing twice its length, and a line far away that touches none of them. + fn roads() -> Dataset { + let mut ds = Dataset::new("roads", GeometryType::Polyline, vec![Field::new("cost", FieldType::Double)]); + for (line, cost) in [ + (vec![c(0.0, 0.0), c(0.01, 0.0), c(0.02, 0.0)], 1.0), + (vec![c(0.01, 0.0), c(0.01, 0.01)], 1.0), + (vec![c(0.02, 0.0), c(0.03, 0.0)], 2.0), + (vec![c(1.0, 1.0), c(1.01, 1.0)], 1.0), + ] { + ds.push(Some(Geometry::Line(vec![line])), vec![Value::Float(cost)]); + } + ds + } + + /// A point layer with a feature for each place, one with no geometry for each `None`. + fn points(name: &str, at: &[Option]) -> Dataset { + let mut ds = Dataset::new(name, GeometryType::Point, vec![]); + for p in at { + ds.push(p.map(Geometry::Point), vec![]); + } + ds + } + + fn map(layers: Vec) -> Map { + Map(layers.into_iter().map(|d| (d.name.clone(), d)).collect()) + } + + /// The layer or table a tool made. + fn dataset(r: &ToolResult) -> &Dataset { + match &r.output { + Output::Layer(d) | Output::Table(d) => d, + _ => panic!("expected a layer or table"), + } + } + + /// Metres along every part of a feature's lines. + fn length(f: &Feature) -> f64 { + let Some(Geometry::Line(parts)) = &f.geometry else { return 0.0 }; + parts.iter().flat_map(|p| p.windows(2)).map(|w| dist(w[0], w[1])).sum() + } + + fn field(ds: &Dataset, f: &Feature, name: &str) -> f64 { + ds.value(ds.features.iter().position(|g| std::ptr::eq(g, f)).unwrap(), ds.field_index(name).unwrap()).as_f64().unwrap() + } + + /// A facility in the middle of a line reaches both ways along it from where it stands, not + /// from the line's ends (the fault opengeos/whitebox-wasm#41 found elsewhere), and each break's + /// band holds the length expected of it, the far line none. + #[test] + fn service_area_measures_each_band_from_the_facility_itself() { + let shops = points("shops", &[Some(c(0.005, 0.0001))]); + let shop = shops.features[0].id as f64; + let inputs = map(vec![roads(), shops]); + let r = service_area(&inputs, &json!({"network": "roads", "facilities": "shops", "breaks": "0.3, 0.8"})).unwrap(); + assert_eq!(r.messages.len(), 1, "clean input, no notices: {:?}", r.messages); + let out = dataset(&r); + let band = |to: f64| -> f64 { out.features.iter().filter(|f| field(out, f, "to_break") == to).map(length).sum() }; + // Half the first segment lies on each side of the shop; 300 m each way, then 800 m: west + // to the dead end, east to the vertex and on along both lines that leave it. + let half = dist(c(0.005, 0.0), c(0.0, 0.0)); + assert!((band(0.3) - 600.0).abs() < 0.5, "{}", band(0.3)); + let second = 2.0 * (half - 300.0) + 2.0 * (800.0 - half); + assert!((band(0.8) - second).abs() < 0.5, "{} vs {second}", band(0.8)); + // West of the shop, on its own segment, within the first band. + let west = out.features.iter().any(|f| { + field(out, f, "to_break") == 0.3 && matches!(&f.geometry, Some(Geometry::Line(p)) if p.iter().flatten().any(|q| q.x < 0.004)) + }); + assert!(west, "the facility's own segment is reached westward"); + assert!( + out.features.iter().all(|f| field(out, f, "facility_fid") == shop && field(out, f, "from_break") < field(out, f, "to_break")) + ); + assert!(out.features.iter().all(|f| matches!(&f.geometry, Some(Geometry::Line(p)) if p.iter().flatten().all(|q| q.x < 0.5)))); + assert!(out.fields.iter().any(|f| f.name == "cost"), "the network's own fields are kept"); + } + + /// Each part of a line goes to the facility nearest along the network, cut where they are + /// equally near. + #[test] + fn service_area_gives_each_part_to_the_nearest_facility() { + let shops = points("shops", &[Some(c(0.0, 0.0)), Some(c(0.016, 0.0))]); + let (first, second) = (shops.features[0].id as f64, shops.features[1].id as f64); + let inputs = map(vec![roads(), shops]); + let r = service_area(&inputs, &json!({"network": "roads", "facilities": "shops", "breaks": 5})).unwrap(); + let out = dataset(&r); + let east_end = |fid: f64| -> f64 { + out.features + .iter() + .filter(|f| field(out, f, "facility_fid") == fid) + .filter_map(|f| match &f.geometry { + Some(Geometry::Line(p)) => p.iter().flatten().filter(|q| q.y == 0.0).map(|q| q.x).reduce(f64::max), + _ => None, + }) + .fold(f64::MIN, f64::max) + }; + assert!((east_end(first) - 0.008).abs() < 1e-6, "{}", east_end(first)); + assert!(east_end(second) > 0.029, "the second shop reaches the end of the costly line: {}", east_end(second)); + } + + /// Costs and lengths through the network, with the cost field doubling one line; along one + /// segment directly; nothing to a separate network, said with a count; the nearest only, and + /// within a cutoff. + #[test] + fn od_cost_matrix_measures_the_cheapest_way() { + let origins = points("from", &[Some(c(0.0, 0.0)), Some(c(1.005, 1.0)), Some(c(0.002, 0.0))]); + let destinations = points("to", &[Some(c(0.03, 0.0)), Some(c(0.01, 0.01)), Some(c(0.004, 0.0))]); + let o: Vec = origins.features.iter().map(|f| f.id as f64).collect(); + let d: Vec = destinations.features.iter().map(|f| f.id as f64).collect(); + let inputs = map(vec![roads(), origins, destinations]); + let run = |extra: Json| { + let mut p = json!({"network": "roads", "origins": "from", "destinations": "to", "costField": "cost", "units": "Meters"}); + p.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone()); + od_cost_matrix(&inputs, &p).unwrap() + }; + let r = run(json!({})); + let out = dataset(&r); + let row = |i: usize, j: usize| { + out.features + .iter() + .find(|f| field(out, f, "origin_fid") == o[i] && field(out, f, "destination_fid") == d[j]) + .map(|f| (field(out, f, "cost"), field(out, f, "length"))) + }; + let (a, b, cc) = (dist(c(0.0, 0.0), c(0.01, 0.0)), dist(c(0.01, 0.0), c(0.02, 0.0)), dist(c(0.02, 0.0), c(0.03, 0.0))); + let (cost, len) = row(0, 0).unwrap(); + assert!((cost - (a + b + 2.0 * cc)).abs() < 1e-6 && (len - (a + b + cc)).abs() < 1e-6, "{cost} {len}"); + let (cost, _) = row(0, 1).unwrap(); + assert!((cost - (a + dist(c(0.01, 0.0), c(0.01, 0.01)))).abs() < 1e-6); + let (cost, _) = row(2, 2).unwrap(); + assert!((cost - dist(c(0.002, 0.0), c(0.004, 0.0))).abs() < 1e-6, "straight along the segment: {cost}"); + assert!(row(1, 0).is_none()); + assert_eq!(out.features.len(), 6); + assert!(r.messages.iter().any(|m| m.contains("3 origin–destination pair(s) aren't connected")), "{:?}", r.messages); + + let nearest = run(json!({"count": 1})); + let out = dataset(&nearest); + assert_eq!(out.features.len(), 2); + assert!(out.features.iter().all(|f| field(out, f, "rank") == 1.0)); + let within = run(json!({"cutoff": 1500})); + assert!(dataset(&within).features.iter().all(|f| field(dataset(&within), f, "cost") <= 1500.0)); + assert_eq!(dataset(&within).features.len(), 2, "each of the two connected origins to its nearest destination"); + } + + /// What's left out is said, one notice per kind with a count; when nothing is left, an error. + #[test] + fn points_left_out_are_counted() { + let shops = points("shops", &[Some(c(0.005, 0.0)), None, Some(c(0.5, 0.5))]); + let inputs = map(vec![roads(), shops, points("nowhere", &[Some(c(0.5, 0.5))])]); + let r = service_area(&inputs, &json!({"network": "roads", "facilities": "shops", "breaks": "1"})).unwrap(); + assert!(r.messages.iter().any(|m| m.contains("1 feature(s) of 'shops' have no usable point")), "{:?}", r.messages); + assert!(r.messages.iter().any(|m| m.contains("1 feature(s) of 'shops' lie more than 1.0 km")), "{:?}", r.messages); + let e = service_area(&inputs, &json!({"network": "roads", "facilities": "nowhere", "breaks": "1"})).unwrap_err(); + assert!(e.contains("Snap Distance"), "{e}"); + for bad in [json!("0"), json!("-1, 2"), json!("a"), json!([])] { + assert!(service_area(&inputs, &json!({"network": "roads", "facilities": "shops", "breaks": bad})).is_err(), "{bad}"); + } + let mut costs = roads(); + costs.features[3].attrs[0] = Value::Null; + costs.features[2].attrs[0] = Value::Float(0.0); + let inputs = map(vec![costs, points("shops", &[Some(c(0.005, 0.0))])]); + let r = service_area(&inputs, &json!({"network": "roads", "facilities": "shops", "breaks": "5", "costField": "cost"})).unwrap(); + assert!(r.messages.iter().any(|m| m.contains("1 line(s) of 'roads' have no number in cost")), "{:?}", r.messages); + assert!( + r.messages.iter().any(|m| m.contains("1 line(s) of 'roads' cost zero or less in cost, and are closed")), + "{:?}", + r.messages + ); + } + + /// Every origin's row the same, bit for bit, on one thread or several. + #[test] + fn od_cost_matrix_is_the_same_on_any_thread_count() { + let at: Vec> = (0..40).map(|i| Some(c(f64::from(i) * 0.00075, if i % 3 == 0 { 0.0 } else { 0.001 }))).collect(); + let inputs = map(vec![roads(), points("pts", &at)]); + let p = json!({"network": "roads", "origins": "pts", "destinations": "pts", "snapDistance": 200}); + let rows = |threads| { + let r = od_cost_matrix_on(&inputs, &p, Some(threads)).unwrap(); + dataset(&r).features.iter().map(|f| f.attrs.iter().map(|v| format!("{v:?}")).collect::>()).collect::>() + }; + let one = rows(1); + assert!(one.len() > 100); + assert_eq!(one, rows(4)); + } +} diff --git a/crates/engine/src/tests/cancellation.rs b/crates/engine/src/tests/cancellation.rs index ec4cd115b2..ba24cc4423 100644 --- a/crates/engine/src/tests/cancellation.rs +++ b/crates/engine/src/tests/cancellation.rs @@ -217,7 +217,7 @@ pub(super) fn long_commands(boundaries: bool) { std::fs::remove_file(replacement).unwrap(); // The tools whose work grows past a second or two on real data: buffers, overlays, joins, - // hulls, densities and interpolation. Run in the background as the Analysis pane runs them; a + // hulls, densities, interpolation and network searches. Run in the background as the Analysis pane runs them; a // new long tool is added here (AGENTS.md › Never hold the window). let tools = [ ("buffer", json!({"input": "Cities", "distance": 100})), @@ -240,6 +240,8 @@ pub(super) fn long_commands(boundaries: bool) { ("kernelDensity", json!({"input": "Cities", "crs": "EPSG:3857", "pixelSize": if boundaries { 2000 } else { 1000000 }})), ("kriging", json!({"input": "Cities", "field": "pop_max", "pixelSize": if boundaries { 0.01 } else { 1.0 }})), ("tabulateArea", json!({"raster": dem, "zones": "Countries"})), + ("serviceArea", json!({"network": "Rivers", "facilities": "Cities", "breaks": "50", "snapDistance": 100000})), + ("odCostMatrix", json!({"network": "Rivers", "origins": "Cities", "destinations": "Cities", "count": 1, "snapDistance": 100000})), ]; for (tool, params) in &tools { exercise(&s, tool, params, Kind::Tool, &dir.0, boundaries); diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index a0fc941e12..b66c2e01f2 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -346,6 +346,8 @@ Use these ids in `gp.run`'s `tool` parameter (`gp.tools` lists the available too | --- | --- | --- | | Buffer | `buffer` | Analysis › Proximity | | Near | `near` | Analysis › Proximity | +| Service Area | `serviceArea` | Analysis › Network | +| OD Cost Matrix | `odCostMatrix` | Analysis › Network | | Clip | `clip` | Analysis › Extract | | Split | `split` | Analysis › Extract | | Erase | `erase` | Analysis › Overlay | @@ -1153,6 +1155,36 @@ with latitude or the map's projection. Python's `pya5`, R), `resolution` and `area_km2`. A cell across the antimeridian, or round a pole, is split at ±180° into two parts of one polygon, each within −180° to 180°. +### Network tools + +**Service Area** (`serviceArea`) and **OD Cost Matrix** (`odCostMatrix`) search a line layer as a +network, as the Network Analysis workflow's route does: lines join where their vertices meet, each +line's length is measured on the WGS 84 ellipsoid, and a **Cost Field** multiplies it (a line with +no number there costs its length, and one costing 0 or less is closed; each is counted in a +notice). Every line can be travelled both ways. The network's selection is honoured, and the graph +is reused while the lines don't change, shared with routes. + +Points are moved onto the nearest line, at most **Snap Distance** metres (1,000 by default). A +feature farther away, with no point, or with several (a multipoint) is left out and counted in a +notice. A point in the middle of a line is reached from there, both ways along it. + +Service Area takes **Breaks**, costs in **Units** such as `1, 2, 5`, and makes the lines reachable +within the largest. Each line is cut where it passes a break and where another facility becomes +nearer, so each part keeps the line's attributes and adds `facility_fid` (the nearest facility), +`from_break` and `to_break`. With several facilities, each part belongs to the nearest one only. + +OD Cost Matrix makes a table with a row for each origin and destination the network connects: +`origin_fid`, `destination_fid`, `rank` (1 for the cheapest from that origin), `cost` and +`length` in **Units** (they differ only with a cost field). **Cutoff** leaves out destinations +costing more, and **Destinations to Find** keeps only the cheapest few from each origin. Pairs the +network doesn't connect have no row, and a notice counts them. The origins are searched on several +threads on the desktop; a matrix may hold up to 10 million rows. + +```text +gp.run={"tool":"serviceArea","params":{"network":"streets","facilities":"fire_stations","breaks":"1, 2, 3","units":"Miles"}} +gp.run={"tool":"odCostMatrix","params":{"network":"streets","origins":"homes","destinations":"clinics","count":1}} +``` + ### Geometry conversions These tools write new layers, honor selected features, and retain source fields, attributes and From dadeacf857ca6359b01501f61bfcd7f1f36dd09d Mon Sep 17 00:00:00 2001 From: mavrick Date: Tue, 17 Nov 2026 12:44:33 -0600 Subject: [PATCH 02/12] fix(analysis): count network features with no line; visit only reached destinations (#2344) Service Area and OD Cost Matrix now say how many features of the network layer have no line and were left out. An OD search visits only the destinations at the nodes it reached within the cutoff, or on the origin's own segment, so a cutoff bounds the work as well as the rows. The roadmap's network item now lists what's built in and what's next. Co-Authored-By: Claude Opus 5.5 --- ROADMAP.md | 9 +-- crates/analysis/src/network.rs | 5 ++ crates/analysis/src/tools/network_analysis.rs | 61 +++++++++++++------ 3 files changed, 54 insertions(+), 21 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 36cb06ccc4..08e18e93f3 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -239,10 +239,11 @@ And alongside it: Before adding a tool, check whether the GeoLibre suite already has it (`gp.tools`); a built-in version must justify itself: no runner download, the selection honoured, geodesic distances and attributes kept. -- Network analysis: service areas, isochrones (also from a point on the map, through its - right-click menu) and an origin–destination matrix over a line layer, in a guided workflow over - the GeoLibre suite's network tools, once their results are checked against known answers - (today: shortest path over a line layer, and online Directions). Follow the +- Network analysis over a line layer, built in (#2344): one-way travel and travel time, closest + facility, service-area polygons and isochrones (also from a point on the map, through its + right-click menu), barriers and turns; location-allocation and vehicle routing as a guided + workflow over the GeoLibre suite's network tools, once their results are checked against known + answers (today: shortest path, Service Area, OD Cost Matrix, and online Directions). Follow the [ribbon guidelines](docs/contributing.md#ribbon-guidelines) for where it goes. - Hot-spot statistics (Getis-Ord Gi\*), and emerging hot spots on the time slider. - Kriging with a fitted variogram and leave-one-out cross-validation (the variogram is a default diff --git a/crates/analysis/src/network.rs b/crates/analysis/src/network.rs index fbe196a1bc..99bb970a73 100644 --- a/crates/analysis/src/network.rs +++ b/crates/analysis/src/network.rs @@ -532,6 +532,11 @@ impl Search { self.length.get(node).copied().unwrap_or(f64::INFINITY) } + /// The nodes the last search gave a cost: every node it settled, and some beyond `limit`. + pub(crate) fn reached(&self) -> impl Iterator + '_ { + self.touched.iter().copied() + } + /// The start `node` is reached from most cheaply (the first given, of equally cheap ones). pub(crate) fn source(&self, node: usize) -> Option { self.source.get(node).copied().filter(|s| *s != usize::MAX) diff --git a/crates/analysis/src/tools/network_analysis.rs b/crates/analysis/src/tools/network_analysis.rs index 5eea175fdc..bac3cd3d88 100644 --- a/crates/analysis/src/tools/network_analysis.rs +++ b/crates/analysis/src/tools/network_analysis.rs @@ -44,6 +44,11 @@ fn network<'a>(inp: &'a dyn Inputs, p: &Json, tool: &str) -> Result, rows.sort_unstable(); rows.dedup(); let mut notes = Vec::new(); + let no_line = + rows.iter().filter(|&&r| !matches!(ds.features.get(r).and_then(|f| f.geometry.as_ref()), Some(Geometry::Line(_)))).count(); + if no_line > 0 { + notes.push(format!("{tool}: {no_line} feature(s) of '{}' have no line, and were left out of the network", ds.name)); + } if let Some(fi) = cost_field { // As a route reads them: no number costs the length alone, zero or less closes the line. let (mut missing, mut closed) = (0usize, 0usize); @@ -332,38 +337,54 @@ pub(super) fn od_cost_matrix_on(inp: &dyn Inputs, p: &Json, threads: Option> = HashMap::new(); + let mut on_segment: HashMap> = HashMap::new(); + for (j, (_, d)) in destinations.iter().enumerate() { let Some(sg) = graph.segment(d.seg) else { continue }; - for n in [sg.a, sg.b] { - if let Some(t) = target.get_mut(n).filter(|t| !**t) { - *t = true; - targets += 1; - } + at_node.entry(sg.a).or_default().push(j); + if sg.b != sg.a { + at_node.entry(sg.b).or_default().push(j); } + on_segment.entry(d.seg).or_default().push(j); } + let targets = at_node.len(); let rows = AtomicUsize::new(0); let threads = threads.unwrap_or_else(|| crate::parallel::threads_for_each(origins.len(), 2, Search::bytes(graph.nodes()))); crate::control::begin(origins.len()); let found = crate::parallel::try_map_each_on( &origins, threads, - || Search::new(graph), - |search, _, (_, o)| { + || (Search::new(graph), vec![false; destinations.len()]), + |(search, seen), _, (_, o)| { let mut settled = 0usize; search.run(graph, &graph.starts(o, 0), limit, false, |u| { - if target.get(u).copied().unwrap_or(false) { + if at_node.contains_key(&u) { settled += 1; } settled == targets })?; - let mut row: Vec<(usize, f64, f64)> = destinations - .iter() - .enumerate() - .filter_map(|(j, (_, d))| { - let (cost, length) = graph.reach(search, o, d); + // A destination within the limit is reached through an end of its segment that costs + // no more, or lies on the origin's own segment. + let near = search.reached().filter(|&n| search.cost(n) <= limit).filter_map(|n| at_node.get(&n)); + let mut candidates = Vec::new(); + for &j in near.chain(on_segment.get(&o.seg)).flatten() { + if let Some(s) = seen.get_mut(j).filter(|s| !**s) { + *s = true; + candidates.push(j); + } + } + for &j in &candidates { + if let Some(s) = seen.get_mut(j) { + *s = false; + } + } + let mut row: Vec<(usize, f64, f64)> = candidates + .into_iter() + .filter_map(|j| { + let (cost, length) = graph.reach(search, o, &destinations.get(j)?.1); (cost.is_finite() && cost <= limit).then_some((j, cost, length)) }) .collect(); @@ -590,6 +611,12 @@ mod tests { for bad in [json!("0"), json!("-1, 2"), json!("a"), json!([])] { assert!(service_area(&inputs, &json!({"network": "roads", "facilities": "shops", "breaks": bad})).is_err(), "{bad}"); } + let mut gaps = roads(); + gaps.push(None, vec![Value::Float(1.0)]); + gaps.push(Some(Geometry::Point(c(0.0, 0.0))), vec![Value::Float(1.0)]); + let inputs = map(vec![gaps, points("shops", &[Some(c(0.005, 0.0))])]); + let r = service_area(&inputs, &json!({"network": "roads", "facilities": "shops", "breaks": "1"})).unwrap(); + assert!(r.messages.iter().any(|m| m.contains("2 feature(s) of 'roads' have no line, and were left out")), "{:?}", r.messages); let mut costs = roads(); costs.features[3].attrs[0] = Value::Null; costs.features[2].attrs[0] = Value::Float(0.0); From 649a73d029a32e3b1574dd78dd907d6236113317 Mon Sep 17 00:00:00 2001 From: mavrick Date: Tue, 17 Nov 2026 12:50:45 -0600 Subject: [PATCH 03/12] =?UTF-8?q?fix(analysis):=20snap=20across=20=C2=B118?= =?UTF-8?q?0=C2=B0,=20keep=20negative=20ids,=20limit=20matrices=20by=20the?= =?UTF-8?q?ir=20rows=20(#2344)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - A point just across the antimeridian from a segment is projected on the segment's side, so it snaps to it instead of being left out. - facility_fid, origin_fid and destination_fid keep ids stored wrapped (a GeoPackage's negative ones), as the vertex tools do. - OD Cost Matrix is limited by the rows it makes, not by origins times destinations, so a sparse matrix isn't refused before it runs. - Pairs that aren't connected are counted before Destinations to Find keeps the cheapest, so the notice appears with a count set too. Co-Authored-By: Claude Opus 5.5 --- crates/analysis/src/network.rs | 5 +- crates/analysis/src/tools/network_analysis.rs | 57 +++++++++++++++---- 2 files changed, 50 insertions(+), 12 deletions(-) diff --git a/crates/analysis/src/network.rs b/crates/analysis/src/network.rs index 99bb970a73..3c124d62fb 100644 --- a/crates/analysis/src/network.rs +++ b/crates/analysis/src/network.rs @@ -228,9 +228,12 @@ fn nearest_segment(segs: &[Segment], nodes: &[Coord], p: Coord, within: Option 0.0 { (((p.x - a.x) * k * dx + (p.y - a.y) * dy) / len2).clamp(0.0, 1.0) } else { 0.0 }; + let t = if len2 > 0.0 { (((px - a.x) * k * dx + (p.y - a.y) * dy) / len2).clamp(0.0, 1.0) } else { 0.0 }; let q = Coord::new(a.x + t * (b.x - a.x), a.y + t * (b.y - a.y)); Some((i, t, q, haversine_m(q, p))) }) diff --git a/crates/analysis/src/tools/network_analysis.rs b/crates/analysis/src/tools/network_analysis.rs index bac3cd3d88..d5d44dd7f6 100644 --- a/crates/analysis/src/tools/network_analysis.rs +++ b/crates/analysis/src/tools/network_analysis.rs @@ -285,7 +285,7 @@ pub(super) fn service_area(inp: &dyn Inputs, p: &Json) -> Result = (0..ds.fields.len()).map(|i| f.attrs.get(i).cloned().unwrap_or(Value::Null)).collect(); - let fid = facilities.get(facility).map_or(Value::Null, |(id, _)| i64::try_from(*id).map_or(Value::Null, Value::Int)); + let fid = facilities.get(facility).map_or(Value::Null, |(id, _)| Value::Int(id.cast_signed())); let from = if band == 0 { 0.0 } else { breaks.get(band - 1).copied().unwrap_or(0.0) }; attrs.extend([fid, Value::Float(from), Value::Float(breaks.get(band).copied().unwrap_or(0.0))]); out.push(Some(Geometry::Line(lines)), attrs); @@ -329,12 +329,6 @@ pub(super) fn od_cost_matrix_on(inp: &dyn Inputs, p: &Json, threads: Option MAX_PAIRS { - return Err(format!( - "{TOOL}: {} origins by {per_origin} destinations is more than {MAX_PAIRS} rows; set a Cutoff or Destinations to Find", - origins.len() - )); - } let (graph, unit_m) = (&net.graph, net.unit_m); let limit = cutoff.map_or(f64::INFINITY, |c| c * unit_m); // The destinations at each end of their segments, and on each segment: a search visits only @@ -388,6 +382,8 @@ pub(super) fn od_cost_matrix_on(inp: &dyn Inputs, p: &Json, threads: Option MAX_PAIRS { @@ -395,7 +391,7 @@ pub(super) fn od_cost_matrix_on(inp: &dyn Inputs, p: &Json, threads: Option Date: Tue, 17 Nov 2026 13:37:31 -0600 Subject: [PATCH 04/12] =?UTF-8?q?fix(analysis):=20test=20a=20segment's=20s?= =?UTF-8?q?nap=20window=20on=20the=20point's=20side=20of=20=C2=B1180=C2=B0?= =?UTF-8?q?=20(#2344)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The window test compared a segment's stored longitudes with a window around the point before moving them by whole turns, so a segment stored past ±180° was passed over when placing a point, though a route snapped to it. The turn is now worked out first and used for both. Co-Authored-By: Claude Opus 5.5 --- crates/analysis/src/network.rs | 21 +++++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) diff --git a/crates/analysis/src/network.rs b/crates/analysis/src/network.rs index 3c124d62fb..61a0182b96 100644 --- a/crates/analysis/src/network.rs +++ b/crates/analysis/src/network.rs @@ -223,14 +223,16 @@ fn nearest_segment(segs: &[Segment], nodes: &[Coord], p: Coord, within: Option x1 || a.y.max(b.y) < y0 || a.y.min(b.y) > y1) + && (a.x.max(b.x) - turn < x0 || a.x.min(b.x) - turn > x1 || a.y.max(b.y) < y0 || a.y.min(b.y) > y1) { return None; } - // The point's longitude on the segment's side of ±180°: unchanged within 180° of its - // middle, so only segments near the antimeridian see a point just across it. - let px = p.x + 360.0 * ((0.5 * (a.x + b.x) - p.x) / 360.0).round(); + let px = p.x + turn; let (dx, dy) = ((b.x - a.x) * k, b.y - a.y); let len2 = dx * dx + dy * dy; let t = if len2 > 0.0 { (((px - a.x) * k * dx + (p.y - a.y) * dy) / len2).clamp(0.0, 1.0) } else { 0.0 }; @@ -1341,6 +1343,17 @@ mod tests { assert!(found.len() == 1 && bounded == 0, "{found:?} {bounded}"); } + /// A point is placed on a segment stored past ±180° (at 370°, the same meridian as 10°), as a + /// route's end is, not passed over by the snap window. + #[test] + fn a_segment_stored_past_180_degrees_is_found_by_the_window() { + let mut ds = Dataset::new("roads", GeometryType::Polyline, vec![]); + ds.push(Some(Geometry::Line(vec![vec![Coord::new(370.0, 0.0), Coord::new(370.01, 0.0)]])), vec![]); + let graph = Graph(Arc::new(Network::build(&ds, &[0], None).unwrap())); + let placed = graph.place(Coord::new(10.005, 0.0001), 100.0).unwrap(); + assert!(placed.is_some_and(|p| p.seg == 0), "{placed:?}"); + } + /// Repeated pairs reuse topology without retaining endpoint edits; every graph input /// invalidates it, even an attribute/geometry mutation with no other strong feature owner. #[test] From 399de80edc2641a01ea2556f33fcb8000954d3f7 Mon Sep 17 00:00:00 2001 From: mavrick Date: Tue, 17 Nov 2026 14:17:19 -0600 Subject: [PATCH 05/12] docs(analysis): say what's built and what's next for network analysis; correct the search's contracts (#2344) - The roadmap's network item separates what's built in from what's to come. - Graph::starts returns no starts for a place not on the graph instead of starting from node 0. - Search::cost and Search::source say what holds after a search ended early and between equally cheap starts. Co-Authored-By: Claude Opus 5.5 --- ROADMAP.md | 9 +++++---- crates/analysis/src/network.rs | 16 +++++++++------- 2 files changed, 14 insertions(+), 11 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 08e18e93f3..dc311386c9 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -239,12 +239,13 @@ And alongside it: Before adding a tool, check whether the GeoLibre suite already has it (`gp.tools`); a built-in version must justify itself: no runner download, the selection honoured, geodesic distances and attributes kept. -- Network analysis over a line layer, built in (#2344): one-way travel and travel time, closest - facility, service-area polygons and isochrones (also from a point on the map, through its +- Network analysis over a line layer (#2344). Built in today: shortest path, Service Area (lines) + and OD Cost Matrix, and online Directions. Still to come: one-way travel and travel time, + closest facility, service-area polygons and isochrones (also from a point on the map, through its right-click menu), barriers and turns; location-allocation and vehicle routing as a guided workflow over the GeoLibre suite's network tools, once their results are checked against known - answers (today: shortest path, Service Area, OD Cost Matrix, and online Directions). Follow the - [ribbon guidelines](docs/contributing.md#ribbon-guidelines) for where it goes. + answers. Follow the [ribbon guidelines](docs/contributing.md#ribbon-guidelines) for where it + goes. - Hot-spot statistics (Getis-Ord Gi\*), and emerging hot spots on the time slider. - Kriging with a fitted variogram and leave-one-out cross-validation (the variogram is a default estimated from the points and extent today, not fitted; `kriging.rs`). diff --git a/crates/analysis/src/network.rs b/crates/analysis/src/network.rs index 61a0182b96..6a81cd1e16 100644 --- a/crates/analysis/src/network.rs +++ b/crates/analysis/src/network.rs @@ -459,10 +459,10 @@ impl Graph { } /// Where a search from `p` starts: both ends of its segment, at the cost and length of the - /// way along it, labelled `source`. - pub(crate) fn starts(&self, p: &Placed, source: usize) -> [Start; 2] { - let (a, b, w) = self.0.segs.get(p.seg).map_or((0, 0, 1.0), |s| (s.0, s.1, s.2)); - [Start { node: a, cost: p.to_a * w, length: p.to_a, source }, Start { node: b, cost: p.to_b * w, length: p.to_b, source }] + /// way along it, labelled `source`. None for a place not on this graph, so it reaches nothing. + pub(crate) fn starts(&self, p: &Placed, source: usize) -> Vec { + let Some(&(a, b, w, _)) = self.0.segs.get(p.seg) else { return Vec::new() }; + vec![Start { node: a, cost: p.to_a * w, length: p.to_a, source }, Start { node: b, cost: p.to_b * w, length: p.to_b, source }] } /// The cheapest way to `to` found by `search`, as (cost, length): through either end of its @@ -526,8 +526,9 @@ impl Search { } } - /// The least cost of reaching `node` in the last search: exact for every node it settled, - /// above `limit` (or infinite) for the rest. + /// The least cost of reaching `node` in the last search: exact for every node it settled. When + /// `settled` ended the search early, the others keep tentative costs; otherwise they are above + /// `limit` (or infinite). pub(crate) fn cost(&self, node: usize) -> f64 { self.cost.get(node).copied().unwrap_or(f64::INFINITY) } @@ -542,7 +543,8 @@ impl Search { self.touched.iter().copied() } - /// The start `node` is reached from most cheaply (the first given, of equally cheap ones). + /// The start `node` is reached from most cheaply (of equally cheap ones, whichever the search + /// reached first, which depends on the network, not on the order the starts were given). pub(crate) fn source(&self, node: usize) -> Option { self.source.get(node).copied().filter(|s| *s != usize::MAX) } From 1071e0c403deecdbeb9301a5ede9daaf5f2f2266 Mon Sep 17 00:00:00 2001 From: mavrick Date: Tue, 17 Nov 2026 15:06:51 -0600 Subject: [PATCH 06/12] fix(analysis): count a feature with no line once; size each search with its queue (#2344) - The cost-field notices look only at features with a line, so a point or empty feature in the network is counted once, as having no line; the closed-line notice also names costs that aren't finite numbers. - Search::bytes counts the search's queue, which grows with the segments and keeps its capacity between searches, so the OD matrix's threads stay within the scratch budget. - Search::source says how equally cheap starts at one node are chosen. Co-Authored-By: Claude Opus 5.5 --- crates/analysis/src/network.rs | 14 +++++++++----- crates/analysis/src/tools/network_analysis.rs | 18 +++++++++++++----- 2 files changed, 22 insertions(+), 10 deletions(-) diff --git a/crates/analysis/src/network.rs b/crates/analysis/src/network.rs index 6a81cd1e16..0a961e1cdd 100644 --- a/crates/analysis/src/network.rs +++ b/crates/analysis/src/network.rs @@ -509,9 +509,13 @@ pub(crate) struct Search { } impl Search { - /// The bytes a search over `nodes` nodes holds, for sharing memory between threads. - pub(crate) fn bytes(nodes: usize) -> usize { - nodes.saturating_mul(3 * size_of::() + 1 + 2 * size_of::()) + /// The most bytes a search over `graph` holds, for sharing memory between threads: its arrays + /// by node, and its queue, which may take an entry for each way along each segment and for + /// each start, kept between searches at up to twice that as it grows. + pub(crate) fn bytes(graph: &Graph) -> usize { + let per_node = graph.nodes().saturating_mul(3 * size_of::() + 1 + 2 * size_of::()); + let queue = graph.segments().saturating_mul(2).saturating_add(2).saturating_mul(2 * size_of::()); + per_node.saturating_add(queue) } pub(crate) fn new(graph: &Graph) -> Self { @@ -543,8 +547,8 @@ impl Search { self.touched.iter().copied() } - /// The start `node` is reached from most cheaply (of equally cheap ones, whichever the search - /// reached first, which depends on the network, not on the order the starts were given). + /// The start `node` is reached from most cheaply: of equally cheap ones, the first to reach it, + /// which depends on the network, and for starts at one node on the order they were given. pub(crate) fn source(&self, node: usize) -> Option { self.source.get(node).copied().filter(|s| *s != usize::MAX) } diff --git a/crates/analysis/src/tools/network_analysis.rs b/crates/analysis/src/tools/network_analysis.rs index d5d44dd7f6..4915cfdff8 100644 --- a/crates/analysis/src/tools/network_analysis.rs +++ b/crates/analysis/src/tools/network_analysis.rs @@ -54,6 +54,10 @@ fn network<'a>(inp: &'a dyn Inputs, p: &Json, tool: &str) -> Result, let (mut missing, mut closed) = (0usize, 0usize); for &r in &rows { crate::control::check()?; + // Only lines join the network; what has no line is counted once, above. + if !matches!(ds.features.get(r).and_then(|f| f.geometry.as_ref()), Some(Geometry::Line(_))) { + continue; + } match ds.value(r, fi).as_f64() { Some(w) if w.is_finite() && w > 0.0 => {} Some(_) => closed += 1, @@ -65,7 +69,10 @@ fn network<'a>(inp: &'a dyn Inputs, p: &Json, tool: &str) -> Result, notes.push(format!("{tool}: {missing} line(s) of '{}' have no number in {field}, and cost their length", ds.name)); } if closed > 0 { - notes.push(format!("{tool}: {closed} line(s) of '{}' cost zero or less in {field}, and are closed", ds.name)); + notes.push(format!( + "{tool}: {closed} line(s) of '{}' cost zero or less (or no finite number) in {field}, and are closed", + ds.name + )); } } let graph = Graph::of(ds, &rows, cost_field)?; @@ -346,7 +353,7 @@ pub(super) fn od_cost_matrix_on(inp: &dyn Inputs, p: &Json, threads: Option Date: Tue, 17 Nov 2026 15:58:46 -0600 Subject: [PATCH 07/12] fix(analysis): keep coincident facilities together; bound an OD worker's memory (#2344) - Facilities at one place in the middle of a line: the first has the parts reached from there on both sides, not one side each. - Each origin's row gives back the room the destinations it dropped took, and a thread's memory estimate counts its rows, candidates and marks over every destination as well as its search. Co-Authored-By: Claude Opus 5.5 --- crates/analysis/src/tools/network_analysis.rs | 25 ++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/crates/analysis/src/tools/network_analysis.rs b/crates/analysis/src/tools/network_analysis.rs index 4915cfdff8..0b1553f4f4 100644 --- a/crates/analysis/src/tools/network_analysis.rs +++ b/crates/analysis/src/tools/network_analysis.rs @@ -260,6 +260,8 @@ pub(super) fn service_area(inp: &dyn Inputs, p: &Json) -> Result() + size_of::() + 1; + let scratch = Search::bytes(graph).saturating_add(destinations.len().saturating_mul(per_destination)); + let threads = threads.unwrap_or_else(|| crate::parallel::threads_for_each(origins.len(), 2, scratch)); crate::control::begin(origins.len()); let found = crate::parallel::try_map_each_on( &origins, @@ -393,6 +398,8 @@ pub(super) fn od_cost_matrix_on(inp: &dyn Inputs, p: &Json, threads: Option MAX_PAIRS { return Err(format!( "{TOOL}: the matrix would hold more than {MAX_PAIRS} rows; set a lower Cutoff or Destinations to Find" @@ -559,6 +566,22 @@ mod tests { assert!(east_end(second) > 0.029, "the second shop reaches the end of the costly line: {}", east_end(second)); } + /// Two facilities at one place in the middle of a line: the first has every part reached from + /// there, on both sides, not one side each. + #[test] + fn coincident_facilities_go_to_the_first() { + let shops = points("shops", &[Some(c(0.005, 0.0)), Some(c(0.005, 0.0))]); + let first = shops.features[0].id as f64; + let inputs = map(vec![roads(), shops]); + let r = service_area(&inputs, &json!({"network": "roads", "facilities": "shops", "breaks": "5"})).unwrap(); + let out = dataset(&r); + assert!( + out.features.iter().all(|f| field(out, f, "facility_fid") == first), + "{:?}", + out.features.iter().map(|f| field(out, f, "facility_fid")).collect::>() + ); + } + /// Costs and lengths through the network, with the cost field doubling one line; along one /// segment directly; nothing to a separate network, said with a count; the nearest only, and /// within a cutoff. From 2a1d09b71a1f33000c0d77434e748dd02d4f8c24 Mon Sep 17 00:00:00 2001 From: mavrick Date: Tue, 17 Nov 2026 16:42:02 -0600 Subject: [PATCH 08/12] fix(analysis): count lines with no segment; count growth and sort scratch in an OD worker's estimate (#2344) - A line with no part of two vertices joins nothing, and is now counted with the features that have no line, rather than dropped without a word. - An OD thread's estimate allows for vector growth and the sort's scratch. Co-Authored-By: Claude Opus 5.5 --- crates/analysis/src/tools/network_analysis.rs | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/crates/analysis/src/tools/network_analysis.rs b/crates/analysis/src/tools/network_analysis.rs index 0b1553f4f4..2ec888a083 100644 --- a/crates/analysis/src/tools/network_analysis.rs +++ b/crates/analysis/src/tools/network_analysis.rs @@ -44,8 +44,12 @@ fn network<'a>(inp: &'a dyn Inputs, p: &Json, tool: &str) -> Result, rows.sort_unstable(); rows.dedup(); let mut notes = Vec::new(); - let no_line = - rows.iter().filter(|&&r| !matches!(ds.features.get(r).and_then(|f| f.geometry.as_ref()), Some(Geometry::Line(_)))).count(); + // A line joins the network through its segments: one with no part of two vertices has none. + let has_segment = |r: usize| match ds.features.get(r).and_then(|f| f.geometry.as_ref()) { + Some(Geometry::Line(parts)) => parts.iter().any(|part| part.len() >= 2), + _ => false, + }; + let no_line = rows.iter().filter(|&&r| !has_segment(r)).count(); if no_line > 0 { notes.push(format!("{tool}: {no_line} feature(s) of '{}' have no line, and were left out of the network", ds.name)); } @@ -55,7 +59,7 @@ fn network<'a>(inp: &'a dyn Inputs, p: &Json, tool: &str) -> Result, for &r in &rows { crate::control::check()?; // Only lines join the network; what has no line is counted once, above. - if !matches!(ds.features.get(r).and_then(|f| f.geometry.as_ref()), Some(Geometry::Line(_))) { + if !has_segment(r) { continue; } match ds.value(r, fi).as_f64() { @@ -355,8 +359,10 @@ pub(super) fn od_cost_matrix_on(inp: &dyn Inputs, p: &Json, threads: Option() + size_of::() + 1; + // Each thread's search, and at most its rows, candidates and marks over every destination: + // twice the rows and candidates for the room a growing vector takes, and half the rows again + // for the sort's scratch. + let per_destination = 5 * size_of::<(usize, f64, f64)>() / 2 + 2 * size_of::() + 1; let scratch = Search::bytes(graph).saturating_add(destinations.len().saturating_mul(per_destination)); let threads = threads.unwrap_or_else(|| crate::parallel::threads_for_each(origins.len(), 2, scratch)); crate::control::begin(origins.len()); @@ -641,9 +647,10 @@ mod tests { let mut gaps = roads(); gaps.push(None, vec![Value::Float(1.0)]); gaps.push(Some(Geometry::Point(c(0.0, 0.0))), vec![Value::Null]); + gaps.push(Some(Geometry::Line(vec![vec![c(0.5, 0.5)]])), vec![Value::Null]); let inputs = map(vec![gaps, points("shops", &[Some(c(0.005, 0.0))])]); let r = service_area(&inputs, &json!({"network": "roads", "facilities": "shops", "breaks": "1", "costField": "cost"})).unwrap(); - assert!(r.messages.iter().any(|m| m.contains("2 feature(s) of 'roads' have no line, and were left out")), "{:?}", r.messages); + assert!(r.messages.iter().any(|m| m.contains("3 feature(s) of 'roads' have no line, and were left out")), "{:?}", r.messages); assert!(!r.messages.iter().any(|m| m.contains("no number in cost")), "a feature with no line is counted once: {:?}", r.messages); let mut costs = roads(); costs.features[3].attrs[0] = Value::Null; From d2e468715fe81ec0354769b0b309ff75bdcb9879 Mon Sep 17 00:00:00 2001 From: mavrick Date: Tue, 17 Nov 2026 17:44:25 -0600 Subject: [PATCH 09/12] =?UTF-8?q?fix(analysis):=20cut=20a=20segment=20acro?= =?UTF-8?q?ss=20=C2=B1180=C2=B0=20the=20short=20way;=20sum=20unconnected?= =?UTF-8?q?=20pairs=20wide=20(#2344)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - A Service Area part on a segment across the antimeridian is interpolated the short way, as the segment is measured, each place written within -180° to 180° as the line's own vertices are. - OD Cost Matrix sums unconnected pairs in a saturating u64, so origins by destinations past a 32-bit count in the browser can't overflow. Co-Authored-By: Claude Opus 5.5 --- crates/analysis/src/tools/network_analysis.rs | 39 +++++++++++++++++-- 1 file changed, 35 insertions(+), 4 deletions(-) diff --git a/crates/analysis/src/tools/network_analysis.rs b/crates/analysis/src/tools/network_analysis.rs index 2ec888a083..30f57a4f88 100644 --- a/crates/analysis/src/tools/network_analysis.rs +++ b/crates/analysis/src/tools/network_analysis.rs @@ -221,14 +221,20 @@ fn bands(cp: f64, cq: f64, c: f64, lp: Option, lq: Option, limits: out } -/// The place a fraction `t` of the way from `a` to `b`, exactly `a` and `b` at the ends. +/// The place a fraction `t` of the way from `a` to `b`, exactly `a` and `b` at the ends. A segment +/// across ±180° is followed the short way, as it is measured, and each place written within +/// −180° to 180°, as the line's own vertices are. fn along(a: Coord, b: Coord, t: f64) -> Coord { if t <= 0.0 { a } else if t >= 1.0 { b } else { - Coord::new(a.x + t * (b.x - a.x), a.y + t * (b.y - a.y)) + let dx = b.x - a.x; + let dx = if dx.abs() > 180.0 { (dx + 180.0).rem_euclid(360.0) - 180.0 } else { dx }; + let x = a.x + t * dx; + let x = if (-180.0..=180.0).contains(&x) { x } else { (x + 180.0).rem_euclid(360.0) - 180.0 }; + Coord::new(x, a.y + t * (b.y - a.y)) } } @@ -424,10 +430,11 @@ pub(super) fn od_cost_matrix_on(inp: &dyn Inputs, p: &Json, threads: Option 0.029, "the second shop reaches the end of the costly line: {}", east_end(second)); } + /// A part of a segment across ±180° runs the short way, near the antimeridian, not round the + /// world; segments elsewhere are interpolated as before. + #[test] + fn a_segment_across_the_antimeridian_is_cut_the_short_way() { + let mid = along(c(179.99, 0.0), c(-179.99, 0.0), 0.25); + assert!((mid.x - 179.995).abs() < 1e-9, "{mid:?}"); + let over = along(c(179.99, 0.0), c(-179.99, 0.0), 0.75); + assert!((over.x + 179.995).abs() < 1e-9, "{over:?}"); + assert_eq!(along(c(1.0, 2.0), c(3.0, 4.0), 0.5), c(2.0, 3.0)); + let mut lines = Dataset::new("roads", GeometryType::Polyline, vec![]); + lines.push(Some(Geometry::Line(vec![vec![c(179.99, 0.0), c(-179.99, 0.0)]])), vec![]); + let inputs = map(vec![lines, points("shops", &[Some(c(179.99, 0.0))])]); + let r = service_area(&inputs, &json!({"network": "roads", "facilities": "shops", "breaks": "0.5"})).unwrap(); + let xs: Vec = dataset(&r) + .features + .iter() + .flat_map(|f| match &f.geometry { + Some(Geometry::Line(p)) => p.iter().flatten().map(|q| q.x).collect(), + _ => Vec::new(), + }) + .collect(); + assert!(!xs.is_empty() && xs.iter().all(|x| x.abs() > 179.98), "{xs:?}"); + } + /// Two facilities at one place in the middle of a line: the first has every part reached from /// there, on both sides, not one side each. #[test] From 2dfffa70e9e43dd30a2956d141627370127d7315 Mon Sep 17 00:00:00 2001 From: mavrick Date: Tue, 17 Nov 2026 18:18:39 -0600 Subject: [PATCH 10/12] =?UTF-8?q?fix(analysis):=20place=20points=20on=20a?= =?UTF-8?q?=20segment=20across=20=C2=B1180=C2=B0=20the=20short=20way=20(#2?= =?UTF-8?q?344)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A segment whose ends are stored either side of the antimeridian was projected the long way round, so a point on the far side of the world could be placed on it and a point on it was moved to an end. The far end is now moved by a whole turn beside the other before the window test and the projection, and the placed point is written within -180° to 180°. Shortest Route shares this search. Co-Authored-By: Claude Opus 5.5 --- crates/analysis/src/network.rs | 23 ++++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/crates/analysis/src/network.rs b/crates/analysis/src/network.rs index 0a961e1cdd..1c53252038 100644 --- a/crates/analysis/src/network.rs +++ b/crates/analysis/src/network.rs @@ -223,6 +223,10 @@ fn nearest_segment(segs: &[Segment], nodes: &[Coord], p: Coord, within: Option 180.0 { Coord::new(a.x + (gap + 180.0).rem_euclid(360.0) - 180.0, b.y) } else { b }; // The whole turns between the point and the segment's middle: none within 180° of it, // so only a segment near the antimeridian (or stored past ±180°) sees the point moved // to its side, for the window test as for the projection. @@ -236,7 +240,10 @@ fn nearest_segment(segs: &[Segment], nodes: &[Coord], p: Coord, within: Option 0.0 { (((px - a.x) * k * dx + (p.y - a.y) * dy) / len2).clamp(0.0, 1.0) } else { 0.0 }; - let q = Coord::new(a.x + t * (b.x - a.x), a.y + t * (b.y - a.y)); + let x = a.x + t * (b.x - a.x); + // Written within −180° to 180°, as a line's vertices are; unchanged when it is. + let x = if (-180.0..=180.0).contains(&x) { x } else { (x + 180.0).rem_euclid(360.0) - 180.0 }; + let q = Coord::new(x, a.y + t * (b.y - a.y)); Some((i, t, q, haversine_m(q, p))) }) .fold(None, |best: Option<(usize, f64, Coord, f64)>, (i, t, q, sphere)| { @@ -1349,6 +1356,20 @@ mod tests { assert!(found.len() == 1 && bounded == 0, "{found:?} {bounded}"); } + /// A segment across ±180° runs the short way: a point on it is placed there, and a point on + /// the far side of the world isn't placed on it at all. + #[test] + fn a_segment_across_the_antimeridian_is_measured_the_short_way() { + let mut ds = Dataset::new("roads", GeometryType::Polyline, vec![]); + ds.push(Some(Geometry::Line(vec![vec![Coord::new(179.99, 0.0), Coord::new(-179.99, 0.0)]])), vec![]); + let graph = Graph(Arc::new(Network::build(&ds, &[0], None).unwrap())); + assert!(graph.place(Coord::new(0.0, 0.0), 1000.0).unwrap().is_none(), "nowhere near it"); + let on = graph.place(Coord::new(179.995, 0.0), 10.0).unwrap(); + assert!(on.is_some_and(|p| (p.at.x - 179.995).abs() < 1e-9), "{on:?}"); + let across = graph.place(Coord::new(-179.995, 0.0001), 50.0).unwrap(); + assert!(across.is_some_and(|p| (p.at.x + 179.995).abs() < 1e-9), "{across:?}"); + } + /// A point is placed on a segment stored past ±180° (at 370°, the same meridian as 10°), as a /// route's end is, not passed over by the snap window. #[test] From 29c991e3ed8a65b036638f807bdfc510b5fb8591 Mon Sep 17 00:00:00 2001 From: mavrick Date: Tue, 17 Nov 2026 18:27:35 -0600 Subject: [PATCH 11/12] fix(analysis): look at Cancel while an OD matrix's rows are made (#2344) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit One origin may have millions of rows; the table's loop now looks at Cancel between them, so a cancelled run is refused rather than finishing the table. The antimeridian placement test also covers a point at 180°. Co-Authored-By: Claude Opus 5.5 --- crates/analysis/src/network.rs | 2 ++ crates/analysis/src/tools/network_analysis.rs | 5 +++++ 2 files changed, 7 insertions(+) diff --git a/crates/analysis/src/network.rs b/crates/analysis/src/network.rs index 1c53252038..c80a8651db 100644 --- a/crates/analysis/src/network.rs +++ b/crates/analysis/src/network.rs @@ -1368,6 +1368,8 @@ mod tests { assert!(on.is_some_and(|p| (p.at.x - 179.995).abs() < 1e-9), "{on:?}"); let across = graph.place(Coord::new(-179.995, 0.0001), 50.0).unwrap(); assert!(across.is_some_and(|p| (p.at.x + 179.995).abs() < 1e-9), "{across:?}"); + let middle = graph.place(Coord::new(180.0, 0.0), 1000.0).unwrap(); + assert!(middle.is_some_and(|p| p.at.x.abs() > 179.999 && p.at.y.abs() < 1e-9), "{middle:?}"); } /// A point is placed on a segment stored past ±180° (at 370°, the same meridian as 10°), as a diff --git a/crates/analysis/src/tools/network_analysis.rs b/crates/analysis/src/tools/network_analysis.rs index 30f57a4f88..e31439a641 100644 --- a/crates/analysis/src/tools/network_analysis.rs +++ b/crates/analysis/src/tools/network_analysis.rs @@ -432,10 +432,15 @@ pub(super) fn od_cost_matrix_on(inp: &dyn Inputs, p: &Json, threads: Option Date: Tue, 17 Nov 2026 19:24:30 -0600 Subject: [PATCH 12/12] fix(analysis): look at Cancel between an OD matrix's destinations and rows (#2344) Each origin's candidate destinations, and the table's rows, look at Cancel item by item, rather than through a pace that looks only every few million. Co-Authored-By: Claude Opus 5.5 --- crates/analysis/src/tools/network_analysis.rs | 22 +++++++++---------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/crates/analysis/src/tools/network_analysis.rs b/crates/analysis/src/tools/network_analysis.rs index e31439a641..508745ff69 100644 --- a/crates/analysis/src/tools/network_analysis.rs +++ b/crates/analysis/src/tools/network_analysis.rs @@ -399,13 +399,16 @@ pub(super) fn od_cost_matrix_on(inp: &dyn Inputs, p: &Json, threads: Option = candidates - .into_iter() - .filter_map(|j| { - let (cost, length) = graph.reach(search, o, &destinations.get(j)?.1); - (cost.is_finite() && cost <= limit).then_some((j, cost, length)) - }) - .collect(); + // Millions of destinations may be reached: Cancel is looked at between them. + let mut row: Vec<(usize, f64, f64)> = Vec::new(); + for j in candidates { + crate::control::check()?; + let Some((_, d)) = destinations.get(j) else { continue }; + let (cost, length) = graph.reach(search, o, d); + if cost.is_finite() && cost <= limit { + row.push((j, cost, length)); + } + } // Counted before the cheapest few are kept: those beyond them are reached. let unreached = destinations.len() - row.len(); row.sort_by(|a, b| a.1.total_cmp(&b.1).then(a.0.cmp(&b.0))); @@ -433,14 +436,11 @@ pub(super) fn od_cost_matrix_on(inp: &dyn Inputs, p: &Json, threads: Option