From c6de4d7a91da7bd6d14854a04bdf091a31e1ee48 Mon Sep 17 00:00:00 2001 From: mavrick Date: Sun, 1 Nov 2026 15:38:59 -0600 Subject: [PATCH 01/12] feat(analysis): add a Tabulate Intersection tool tabulateIntersection measures how much of each zone each class of polygons covers and shares the classes' sum fields out to the zones by area: a row for each zone and class that overlap, with area_km2, percentage of the zone and each sum field's share (value times the part of the feature's area in the zone). Class features overlapping each other count once in the area. area_km2 is measured on the ellipsoid through a helper now shared with Calculate Geometry (unchanged); percentages and shares compare areas on the sphere, which add up when the overlay cuts along parallels and meridians, so totals are kept. The tool counts features without geometry, zones with no rows, missing sum values and value outside the zones in its messages. Lands the roadmap item: tests, hostile parameters, the user guide, the assistant's geoprocessing skill, ROADMAP.md and README.md. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- ROADMAP.md | 4 +- crates/analysis/src/tools.rs | 325 ++++++++++++++++-- .../analysis/tests/tabulate_intersection.rs | 213 ++++++++++++ .../assistant/skills/geoprocessing/SKILL.md | 4 +- docs/user-guide/analysis.md | 42 +++ 6 files changed, 556 insertions(+), 34 deletions(-) create mode 100644 crates/analysis/tests/tabulate_intersection.rs diff --git a/README.md b/README.md index e3abb982ef..87abaf7545 100644 --- a/README.md +++ b/README.md @@ -99,7 +99,7 @@ Every screenshot is RustGIS itself, rendered offscreen by `cargo run -p rustgis- | **Web tiles** | XYZ/TMS/WMS raster tiles, Mapbox Vector Tiles and MapLibre styles (sprites, patterns, expressions), cached and fetched in the background | | **Cartography** | Single symbol, unique values, graduated colours, proportional symbols; label classes with SQL queries, straight and curved line placement, installed font families, scale ranges and annotation; stacked and dashed line strokes, symbol levels, reference scales and polygons without fill; masking, display filters, aggregation bins, 2.5D extrusion; graphics and dynamic text | | **Editing** | Create, move, rotate, scale, merge, split and explode features; snapping, templates, elevation, traverse, topology rules; domains, subtypes, attribute rules, relationships, archiving; undo for everything | -| **Analysis** | Selection by attributes (SQL) and location; Buffer, Near, Clip, Erase, Split, Intersect, Identity, Union, Symmetrical Difference, Update, Dissolve, Summarize Within, Summary Statistics, Pivot Table, Spatial Join, Zonal Statistics, A5 grids and a geometry calculator; viewshed, line of sight, IDW, ordinary kriging, shortest path, suitability modelling; ModelBuilder on a node canvas and scripts with command, parameter and value completion; 1,000+ [GeoLibre](https://github.com/opengeos/geolibre-rust) and Whitebox raster, vector, LiDAR, hydrology and terrain tools | +| **Analysis** | Selection by attributes (SQL) and location; Buffer, Near, Clip, Erase, Split, Intersect, Identity, Union, Symmetrical Difference, Update, Dissolve, Summarize Within, Summary Statistics, Pivot Table, Tabulate Intersection, Spatial Join, Zonal Statistics, A5 grids and a geometry calculator; viewshed, line of sight, IDW, ordinary kriging, shortest path, suitability modelling; ModelBuilder on a node canvas and scripts with command, parameter and value completion; 1,000+ [GeoLibre](https://github.com/opengeos/geolibre-rust) and Whitebox raster, vector, LiDAR, hydrology and terrain tools | | **Imagery** | Ortho and reality mapping, pixel classification (k-means, minimum distance, a trainable neural network), mensuration, hosted imagery tiles | | **Layouts and reports** | Page layouts with map frames, legends, scale bars, grids and map series; publication sheets and figures in one command, format panes, guides, snapping and element locks; reports with groups, statistics, charts and subreports; presentations (HTML slideshow, PDF); notebooks (Jupyter in and out) | | **Sharing** | PNG export at any DPI; PDF; web map pages, OGC API Features collections, MapLibre styles, glTF scenes, locators; project, map and mobile map packages; offline areas with sync | diff --git a/ROADMAP.md b/ROADMAP.md index 6cb659c5b9..9fca4e2bdc 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -114,7 +114,6 @@ And alongside it: a line layer). - Hot-spot statistics (Getis-Ord Gi\*), and emerging hot spots on the time slider. - Charts linked to the selection: histogram, scatter, bar and box plots of a layer's fields. -- Tabulate intersection: one layer's counts and totals shared out to another by area overlap. - Reverse geocoding, and the US Census geocoder beside Nominatim and Photon; a DEM downloader so viewshed works without a loaded elevation raster _(open)_. @@ -217,7 +216,8 @@ Open questions rather than plans; discuss before building. relationships, archiving. - Analysis: selection by attributes and location; polygon, lasso and radius on the map; overlay (clip, erase, split, intersect, identity, union, symmetrical difference, update), proximity - (buffer, near) and summary tools, pivot tables, spatial join by intersection, centre, largest + (buffer, near) and summary tools, pivot tables, tabulate intersection (class areas and totals + shared out to zones by overlap), spatial join by intersection, centre, largest overlap, closest and distance with merge rules, join field (non-spatial attribute join), feature vertices to points, zonal statistics, kernel density, A5 grids, kriging, Calculate Field with an expression language, Calculate Geometry with metric or imperial units, Project Raster, and diff --git a/crates/analysis/src/tools.rs b/crates/analysis/src/tools.rs index 08cd2a77fe..87cd4b71fc 100644 --- a/crates/analysis/src/tools.rs +++ b/crates/analysis/src/tools.rs @@ -503,6 +503,42 @@ pub static TOOLS: &[ToolSpec] = &[ ], run: pivot_table, }, + ToolSpec { + id: "tabulateIntersection", + name: "Tabulate Intersection", + toolbox: "Analysis › Statistics", + summary: "How much of each zone each class of polygons covers, with the classes' totals shared out to the zones by area.", + params: &[ + P { name: "zones", label: "Input Zone Features", kind: K::PolygonLayer, required: true, default: "", help: "" }, + P { + name: "zoneFields", + label: "Zone Fields", + kind: K::Fields { input: "zones" }, + required: true, + default: "", + help: "Zones sharing these fields' values make one zone. Scripts and the AI Assistant can give several fields as a list.", + }, + P { name: "classes", label: "Input Class Features", kind: K::PolygonLayer, required: true, default: "", help: "" }, + P { + name: "classFields", + label: "Class Fields", + kind: K::Fields { input: "classes" }, + required: false, + default: "", + help: "Class features sharing these fields' values make one class. Leave empty to treat them all as one class.", + }, + P { + name: "sumFields", + label: "Sum Fields", + kind: K::Fields { input: "classes" }, + required: false, + default: "", + help: "Numeric fields of the class features whose values are shared out to the zones by the part of each feature's area in them.", + }, + P { name: "output", label: "Output Name", kind: K::Text, required: false, default: "", help: "" }, + ], + run: tabulate_intersection, + }, ToolSpec { id: "exportFeatures", name: "Export Features", @@ -2743,9 +2779,50 @@ fn count_points(inp: &dyn Inputs, p: &Json) -> Result { result(out, format!("Summarize Within: {total} points counted")) } +/// A lon/lat line or ring as a `geo` line string, in degrees. +fn lonlat_line(coords: &[Coord]) -> geo::LineString { + geo::LineString::new(coords.iter().map(|c| geo::Coord { x: c.x, y: c.y }).collect()) +} + +/// The ground area (square metres, holes taken out) and perimeter (metres, holes included) of a +/// lon/lat polygon geometry on the WGS 84 ellipsoid, as Calculate Geometry Attributes gives them; +/// zero for any other geometry. +fn ground_area_perimeter(g: &Geometry) -> (f64, f64) { + use geo::GeodesicArea; + let (mut a, mut per) = (0.0, 0.0); + let Geometry::Polygon(polys) = g else { return (a, per) }; + for rings in polys { + for (i, r) in rings.iter().enumerate() { + let mut ring = lonlat_line(r); + ring.close(); + // Orient in continuous longitude space, including small dateline crossings. + let mut longitude = ring.0.first().map_or(0.0, |c| c.x); + for c in &mut ring.0 { + longitude += (c.x - longitude + 180.0).rem_euclid(360.0) - 180.0; + c.x = longitude; + } + let polar = ring.0.first().zip(ring.0.last()).is_some_and(|(a, b)| (a.x - b.x).abs() > 180.0); + let orientable = !polar && ring.0.iter().all(|c| c.x.is_finite() && (-90.0..=90.0).contains(&c.y)); + let polygon = geo::Polygon::new(ring, vec![]); + let (rp, ra) = if orientable { + polygon.orient(Direction::Default).geodesic_perimeter_area_unsigned() + } else { + // Keep smaller polar caps; invalid coordinates bypass planar orientation. + let (perimeter, area) = polygon.geodesic_perimeter_area_signed(); + (perimeter, area.abs()) + }; + a += if i == 0 { ra } else { -ra }; + per += rp; + } + } + (a, per) +} + +/// Calculate Geometry Attributes: adds `area_km2` and `perimeter_km` to a polygon layer (see +/// [`ground_area_perimeter`]), `length_km` to a line layer, and `point_x`/`point_y` (a label point) +/// to any other, updating the layer in place. fn calculate_geometry(inp: &dyn Inputs, p: &Json) -> Result { - use geo::{Geodesic, GeodesicArea, Length}; - let line = |coords: &[Coord]| geo::LineString::new(coords.iter().map(|c| geo::Coord { x: c.x, y: c.y }).collect()); + use geo::{Geodesic, Length}; let ds = input(inp, p, "input")?; let mut out = ds.clone(); match ds.geometry_type { @@ -2753,33 +2830,7 @@ fn calculate_geometry(inp: &dyn Inputs, p: &Json) -> Result let fa = out.ensure_field("area_km2", FieldType::Double); let fp = out.ensure_field("perimeter_km", FieldType::Double); for f in &mut out.features { - let (mut a, mut per) = (0.0, 0.0); - if let Some(Geometry::Polygon(polys)) = &f.geometry { - for rings in polys { - for (i, r) in rings.iter().enumerate() { - let mut ring = line(r); - ring.close(); - // Orient in continuous longitude space, including small dateline crossings. - let mut longitude = ring.0.first().map_or(0.0, |c| c.x); - for c in &mut ring.0 { - longitude += (c.x - longitude + 180.0).rem_euclid(360.0) - 180.0; - c.x = longitude; - } - let polar = ring.0.first().zip(ring.0.last()).is_some_and(|(a, b)| (a.x - b.x).abs() > 180.0); - let orientable = !polar && ring.0.iter().all(|c| c.x.is_finite() && (-90.0..=90.0).contains(&c.y)); - let polygon = geo::Polygon::new(ring, vec![]); - let (rp, ra) = if orientable { - polygon.orient(Direction::Default).geodesic_perimeter_area_unsigned() - } else { - // Keep smaller polar caps; invalid coordinates bypass planar orientation. - let (perimeter, area) = polygon.geodesic_perimeter_area_signed(); - (perimeter, area.abs()) - }; - a += if i == 0 { ra } else { -ra }; - per += rp; - } - } - } + let (a, per) = f.geometry.as_ref().map_or((0.0, 0.0), ground_area_perimeter); if let Some(v) = f.attrs.get_mut(fa) { *v = Value::Float(a / 1e6); } @@ -2792,7 +2843,7 @@ fn calculate_geometry(inp: &dyn Inputs, p: &Json) -> Result let fl = out.ensure_field("length_km", FieldType::Double); for f in &mut out.features { let len: f64 = match &f.geometry { - Some(Geometry::Line(parts)) => parts.iter().map(|p| Geodesic.length(&line(p))).sum(), + Some(Geometry::Line(parts)) => parts.iter().map(|p| Geodesic.length(&lonlat_line(p))).sum(), _ => 0.0, }; if let Some(v) = f.attrs.get_mut(fl) { @@ -3099,6 +3150,216 @@ fn pivot_column_name(field: &str, v: &Value) -> String { if !text || name.is_empty() || name.starts_with(char::is_numeric) { format!("{field}{name}") } else { name } } +/// A zone of Tabulate Intersection: the zone features sharing the zone fields' values, as one mask. +struct TabulateZone { + /// The zone fields' values. + key: Vec, + /// The lon/lat extent of its features, for the index. + ext: Extent, + /// Its features' polygons in Web Mercator, unioned when there are several, as [`mask_of`] does. + mask: MultiPolygon, + /// Its area in square metres on the sphere, as [`tabulate_intersection`] compares areas (see + /// there), overlaps between its features counted once. + sphere_area_m2: f64, +} + +/// What one class covers of one zone: its class features' parts in the zone, and the shares of +/// their sum fields' values, in the order of the sum fields. +struct TabulateCell { + parts: Vec, + sums: Vec, +} + +/// Tabulate Intersection: a row for each zone and class that overlap, holding the zone fields, the +/// class fields, `area_km2` (the ground area of the class in the zone, class features overlapping +/// each other counted once), `percentage` (that area as a percentage of the zone's) and each sum +/// field's share: the sum, over the class's features, of the field's value times the part of the +/// feature's area inside the zone. Rows follow the zones, then the classes, in record order; pairs +/// that only touch get none. Only selected features are used when a layer has a selection. The +/// messages count features without geometry (left out), zones with no rows, class features with no +/// value in a sum field and, with sum fields, class features not wholly inside the zones, whose +/// values are not wholly shared out. +/// +/// `area_km2` is measured on the ellipsoid, as Calculate Geometry Attributes measures it. The +/// percentages and shares compare areas measured on the sphere instead ([`crate::join::area_m2`]): +/// the overlay cuts along straight lines on the map, and that measure adds up exactly when a +/// polygon is cut along a parallel or a meridian, where the ellipsoid's geodesic edges don't, so a +/// feature's shares in zones that cover it without overlapping each other add up to its whole value. +fn tabulate_intersection(inp: &dyn Inputs, p: &Json) -> Result { + use crate::join::area_m2; + let zones = input(inp, p, "zones")?; + let classes = input(inp, p, "classes")?; + for ds in [zones, classes] { + if ds.geometry_type != GeometryType::Polygon { + return Err(format!("'{}' is not a polygon layer", ds.name)); + } + } + let zone_keys = key_fields(zones, p.get("zoneFields"), "Zone Field")?; + if zone_keys.is_empty() { + return Err("'Zone Fields' is required".into()); + } + let class_keys = key_fields(classes, p.get("classFields"), "Class Field")?; + let sum_fields = key_fields(classes, p.get("sumFields"), "Sum Field")?; + for &f in &sum_fields { + let Some(field) = classes.fields.get(f) else { continue }; + if !field.ty.is_numeric() { + return Err(format!("the sum field '{}' is not numeric", field.name)); + } + if class_keys.contains(&f) { + return Err(format!("the sum field '{}' can't also be a class field", field.name)); + } + } + // Record order, each record once, whatever order a selection lists them in. + let sorted_rows = |k: &str, ds: &Dataset| { + let mut rs = rows(inp, p, k, ds); + rs.sort_unstable(); + rs.dedup(); + rs + }; + let shapeless = |ds: &Dataset, rs: &[usize]| rs.iter().filter(|&&r| ds.features.get(r).is_none_or(|f| f.geometry.is_none())).count(); + let zone_rows = sorted_rows("zones", zones); + let class_rows = sorted_rows("classes", classes); + let (zones_shapeless, classes_shapeless) = (shapeless(zones, &zone_rows), shapeless(classes, &class_rows)); + let zone_list: Vec = crate::stats::group_rows(zones, &zone_rows, &zone_keys) + .into_iter() + .map(|group| { + let shapes: Vec<&Geometry> = group.rows.iter().filter_map(|&r| zones.features.get(r)?.geometry.as_ref()).collect(); + let ext = shapes.iter().fold(Extent::EMPTY, |e, g| e.union(&g.extent())); + let mask = mask_of(MultiPolygon::new(shapes.iter().filter_map(|g| to_multipolygon(g)).flat_map(|m| m.0).collect())); + let sphere_area_m2 = from_multipolygon(&mask).map_or(0.0, |g| area_m2(&g)); + TabulateZone { key: group.key, ext, mask, sphere_area_m2 } + }) + .collect(); + let class_groups = crate::stats::group_rows(classes, &class_rows, &class_keys); + let index = ExtentIndex::new(zone_list.iter().map(|z| z.ext)); + let mut cells: std::collections::BTreeMap<(usize, usize), TabulateCell> = std::collections::BTreeMap::new(); + // For each sum field, the class features in some zone whose value isn't a number. + let mut missing = vec![0usize; sum_fields.len()]; + // With sum fields, the class features whose shares come to less than their whole value. + let mut outside = 0usize; + for (ci, group) in class_groups.iter().enumerate() { + for &r in &group.rows { + let Some(g) = classes.features.get(r).and_then(|f| f.geometry.as_ref()) else { continue }; + let ext = g.extent(); + let near: Vec = + index.candidates(&ext).into_iter().filter(|&zi| zone_list.get(zi).is_some_and(|z| z.ext.intersects(&ext))).collect(); + if near.is_empty() { + outside += usize::from(!sum_fields.is_empty()); + continue; + } + // Overlapping parts of one feature are unioned once, so they count once. + let whole = dissolved(g); + let values: Vec> = sum_fields.iter().map(|&f| classes.value(r, f).as_f64()).collect(); + let mut whole_area: Option = None; + let mut inside = false; + // The part of the feature's area its shares took, over all zones. + let mut shared = 0.0; + for zi in near { + let Some(piece) = zone_list.get(zi).and_then(|z| part(&whole, &z.mask, true)) else { continue }; + let piece_area = area_m2(&piece); + if piece_area <= 0.0 || !piece_area.is_finite() { + continue; + } + inside = true; + let cell = cells.entry((zi, ci)).or_insert_with(|| TabulateCell { parts: Vec::new(), sums: vec![0.0; sum_fields.len()] }); + if !sum_fields.is_empty() { + let total = *whole_area.get_or_insert_with(|| area_m2(&whole)); + // The part inside can come out a rounding error larger than the whole. + let share = if total > 0.0 { (piece_area / total).min(1.0) } else { 0.0 }; + shared += share; + for (sum, v) in cell.sums.iter_mut().zip(&values) { + if let Some(v) = v { + *sum += v * share; + } + } + } + cell.parts.push(piece); + } + if inside { + for (m, v) in missing.iter_mut().zip(&values) { + *m += usize::from(v.is_none()); + } + } + // A share is a rounding error short of the whole when zones cover the feature. + if !sum_fields.is_empty() && shared < 1.0 - 1e-6 { + outside += 1; + } + } + } + let mut out = Dataset::new( + out_name(p, format!("{}_Tabulate", zones.name)), + GeometryType::None, + zone_keys.iter().filter_map(|&k| zones.fields.get(k).cloned()).collect(), + ); + out.crs_incomplete = zones.crs_incomplete || classes.crs_incomplete; + // A class field, or an output field, whose name is taken gets a suffix (`name_2`). + for f in class_keys.iter().filter_map(|&k| classes.fields.get(k)) { + let name = unique_field(&out, &f.name); + out.fields.push(Field { name, ..f.clone() }); + } + for base in + ["area_km2", "percentage"].into_iter().chain(sum_fields.iter().filter_map(|&f| classes.fields.get(f).map(|f| f.name.as_str()))) + { + let name = unique_field(&out, base); + out.fields.push(Field::new(name, FieldType::Double)); + } + let mut zones_hit: HashSet = HashSet::new(); + for ((zi, ci), cell) in cells { + let (Some(zone), Some(class)) = (zone_list.get(zi), class_groups.get(ci)) else { continue }; + zones_hit.insert(zi); + // Parts of a class's features that overlap each other are unioned, so they count once. + let union; + let covered = match cell.parts.as_slice() { + [one] => one, + parts => { + let polys: Vec> = parts.iter().filter_map(to_multipolygon).collect(); + let Some(g) = from_multipolygon(&union_all(polys.iter().flat_map(|m| m.0.iter()))) else { + return Err(format!("Tabulate Intersection: the parts of a class in the zone {:?} could not be combined", zone.key)); + }; + union = g; + &union + } + }; + let mut row = zone.key.clone(); + row.extend(class.key.iter().cloned()); + row.push(Value::Float(ground_area_perimeter(covered).0 / 1e6)); + let sphere_area_m2 = area_m2(covered); + row.push(if zone.sphere_area_m2 > 0.0 { Value::Float(sphere_area_m2 / zone.sphere_area_m2 * 100.0) } else { Value::Null }); + row.extend(cell.sums.into_iter().map(Value::Float)); + // One past the last id: `push` would search them all for each row. + out.push_next(None, row); + } + let mut messages = vec![match out.features.len() { + 1 => "Tabulate Intersection: 1 row".to_string(), + n => format!("Tabulate Intersection: {n} rows"), + }]; + for (n, layer) in [(zones_shapeless, "zone"), (classes_shapeless, "class")] { + match n { + 0 => {} + 1 => messages.push(format!("1 {layer} feature has no geometry and was left out")), + n => messages.push(format!("{n} {layer} features have no geometry and were left out")), + } + } + match zone_list.len().saturating_sub(zones_hit.len()) { + 0 => {} + 1 => messages.push("1 zone overlaps no class feature, so it has no rows".into()), + n => messages.push(format!("{n} zones overlap no class feature, so they have no rows")), + } + for (&f, n) in sum_fields.iter().zip(missing) { + if n > 0 { + let name = classes.fields.get(f).map_or("", |f| f.name.as_str()); + let features = if n == 1 { "1 class feature has".to_string() } else { format!("{n} class features have") }; + messages.push(format!("{features} no value in '{name}', left out of its shares")); + } + } + match outside { + 0 => {} + 1 => messages.push("1 class feature lies partly or wholly outside the zones: its value outside isn't shared out".into()), + n => messages.push(format!("{n} class features lie partly or wholly outside the zones: their values outside aren't shared out")), + } + Ok(ToolResult { output: Output::Table(out), messages }) +} + fn export_features(inp: &dyn Inputs, p: &Json) -> Result { let ds = input(inp, p, "input")?; let mut rs = rows(inp, p, "input", ds); @@ -5972,6 +6233,10 @@ mod tests { serde_json::json!({"input": "pts", "fields": ["k", 3], "pivot": "k", "value": "v", "statistic": "P100"}), serde_json::json!({"input": "polys", "fields": {"k": 1}, "pivot": 5, "value": ["v"], "statistic": 7, "separator": []}), serde_json::json!({"input": "pts", "fields": "", "pivot": "v", "value": "k", "statistic": "concatenate", "output": ""}), + serde_json::json!({"zones": "polys", "zoneFields": ["k", 3], "classes": "polys", "classFields": "k", "sumFields": {"v": 1}}), + serde_json::json!({"zones": "polys", "zoneFields": "k", "classes": "polys", "classFields": ["k", "K"], "sumFields": ["v", "k"]}), + serde_json::json!({"zones": "pts", "zoneFields": "k", "classes": "polys", "sumFields": "v", "output": 7}), + serde_json::json!({"zones": "polys", "zoneFields": "k", "classes": "polys", "classFields": "k", "output": ""}), ]; for t in TOOLS { for p in &junk { diff --git a/crates/analysis/tests/tabulate_intersection.rs b/crates/analysis/tests/tabulate_intersection.rs new file mode 100644 index 0000000000..115263c2a9 --- /dev/null +++ b/crates/analysis/tests/tabulate_intersection.rs @@ -0,0 +1,213 @@ +//! Tabulate Intersection through `rustgis_analysis::run`: class areas and sums shared out to zones. + +use rustgis_analysis::{Inputs, Output, ToolResult}; +use rustgis_data::{Coord, Dataset, Field, FieldType, Geometry, GeometryType, Value}; +use serde_json::json; +use std::collections::HashMap; + +/// The tool's inputs: layers by name, and each layer's selected rows. +#[derive(Default)] +struct Layers { + data: HashMap, + selected: HashMap>, +} +impl Inputs for Layers { + /// The layer of this name. + fn dataset(&self, name: &str) -> Option<&Dataset> { + self.data.get(name) + } + /// The layer's selected rows; none selects nothing, so every row is used. + fn selection(&self, name: &str) -> &[usize] { + self.selected.get(name).map(Vec::as_slice).unwrap_or(&[]) + } +} + +/// A lon/lat rectangle from `x0` to `x1` and the equator to 1°N. +fn rect(x0: f64, x1: f64) -> Option { + let ring = [(x0, 0.0), (x1, 0.0), (x1, 1.0), (x0, 1.0), (x0, 0.0)].map(|(x, y)| Coord::new(x, y)).to_vec(); + Some(Geometry::Polygon(vec![vec![ring]])) +} + +/// Zones `A` (0°–1°E), `B` (1°–2°E) and `C` (10°–11°E), named by `zone`. +fn zones() -> Dataset { + let mut ds = Dataset::new("zones", GeometryType::Polygon, vec![Field::new("zone", FieldType::Text)]); + for (name, x0) in [("A", 0.0), ("B", 1.0), ("C", 10.0)] { + ds.push_next(rect(x0, x0 + 1.0), vec![Value::Text(name.into())]); + } + ds +} + +/// Classes by `kind`, with a population `pop`: a forest across A and B, a second forest over the +/// first one's half in A, and water over A's other half with no population. +fn classes() -> Dataset { + let mut ds = Dataset::new( + "classes", + GeometryType::Polygon, + vec![Field::new("kind", FieldType::Text), Field::new("pop", FieldType::Integer), Field::new("zone", FieldType::Text)], + ); + let rows = [(0.5, 1.5, "forest", Value::Int(100)), (0.5, 1.0, "forest", Value::Int(10)), (0.0, 0.5, "water", Value::Null)]; + for (x0, x1, kind, pop) in rows { + ds.push_next(rect(x0, x1), vec![Value::Text(kind.into()), pop, Value::Text("x".into())]); + } + ds +} + +/// The two layers as the tool's inputs, under their own names, with nothing selected. +fn layers(zones: Dataset, classes: Dataset) -> Layers { + let mut l = Layers::default(); + l.data.insert(zones.name.clone(), zones); + l.data.insert(classes.name.clone(), classes); + l +} + +/// The standalone table a run made. +fn table(result: ToolResult) -> Dataset { + match result.output { + Output::Table(ds) => ds, + _ => panic!("expected a table"), + } +} + +/// Each row's text fields, then its numbers rounded to 3 decimals (empty as NaN). +fn rows(ds: &Dataset) -> Vec<(Vec, Vec)> { + ds.features + .iter() + .map(|f| { + let text = f.attrs.iter().filter_map(|v| if let Value::Text(t) = v { Some(t.clone()) } else { None }).collect(); + let nums = f + .attrs + .iter() + .filter(|v| !matches!(v, Value::Text(_))) + .map(|v| v.as_f64().map_or(f64::NAN, |n| (n * 1000.0).round() / 1000.0)) + .collect(); + (text, nums) + }) + .collect() +} + +/// The `area_km2` Calculate Geometry Attributes gives a polygon, rounded as [`rows`] rounds. +fn calculated_area_km2(g: Option) -> f64 { + let mut ds = Dataset::new("one", GeometryType::Polygon, vec![]); + ds.push_next(g, vec![]); + let l = layers(ds, Dataset::new("none", GeometryType::Polygon, vec![])); + let Output::Update { dataset, .. } = rustgis_analysis::run("calculateGeometry", &l, &json!({"input": "one"})).unwrap().output else { + panic!("expected an update") + }; + let area = dataset.field_index("area_km2").map(|i| dataset.value(0, i).clone()); + area.and_then(|v| v.as_f64()).map(|a| (a * 1000.0).round() / 1000.0).unwrap() +} + +#[test] +fn shares_class_areas_and_sums_out_to_zones() { + let l = layers(zones(), classes()); + let params = json!({"zones": "zones", "zoneFields": "zone", "classes": "classes", "classFields": "kind", "sumFields": ["pop"]}); + let result = rustgis_analysis::run("tabulateIntersection", &l, ¶ms).unwrap(); + let messages = result.messages.clone(); + let out = table(result); + let names: Vec<&str> = out.fields.iter().map(|f| f.name.as_str()).collect(); + assert_eq!(names, ["zone", "kind", "area_km2", "percentage", "pop"]); + assert!(out.fields.iter().skip(2).all(|f| f.ty == FieldType::Double)); + let got = rows(&out); + let text: Vec> = got.iter().map(|(t, _)| t.clone()).collect(); + assert_eq!(text, [["A", "forest"], ["A", "water"], ["B", "forest"]].map(|r| r.map(String::from).to_vec())); + // Half of A, measured as Calculate Geometry Attributes measures it: the two forests over that + // half count once. + let expected = calculated_area_km2(rect(0.5, 1.0)); + let half = got.first().and_then(|(_, n)| n.first()).copied().unwrap(); + assert!((half - expected).abs() < 0.01 && (6100.0..6200.0).contains(&half), "{half} km², not {expected}"); + for (_, nums) in &got { + assert!((nums[0] - half).abs() < 0.01 && (nums[1] - 50.0).abs() < 0.001, "{nums:?}"); + } + // A gets half the first forest's 100 and all the second's 10; B the other half of 100. Water + // has no population, so its share is 0 and a notice says so. + let pops: Vec = got.iter().map(|(_, n)| n[2]).collect(); + assert_eq!(pops, [60.0, 0.0, 50.0]); + assert_eq!( + messages, + [ + "Tabulate Intersection: 3 rows", + "1 zone overlaps no class feature, so it has no rows", + "1 class feature has no value in 'pop', left out of its shares", + ] + ); +} + +#[test] +fn clean_input_gives_no_notices() { + let mut l = layers(zones(), classes()); + // Zones A and B only, and the forests, which all have a population. + l.selected.insert("zones".into(), vec![1, 0]); + l.selected.insert("classes".into(), vec![0, 1]); + let params = json!({"zones": "zones", "zoneFields": ["zone"], "classes": "classes", "sumFields": "pop"}); + let result = rustgis_analysis::run("tabulateIntersection", &l, ¶ms).unwrap(); + assert_eq!(result.messages, ["Tabulate Intersection: 2 rows"]); + let out = table(result); + // Without class fields every class feature is one class. + let names: Vec<&str> = out.fields.iter().map(|f| f.name.as_str()).collect(); + assert_eq!(names, ["zone", "area_km2", "percentage", "pop"]); + let got = rows(&out); + assert_eq!(got.iter().map(|(t, _)| t.join("")).collect::>(), ["A", "B"]); + assert_eq!(got.iter().map(|(_, n)| (n[1], n[2])).collect::>(), [(50.0, 60.0), (50.0, 50.0)]); +} + +#[test] +fn says_what_it_leaves_out() { + let mut z = zones(); + z.push_next(None, vec![Value::Text("D".into())]); + let mut c = Dataset::new("classes", GeometryType::Polygon, vec![Field::new("pop", FieldType::Integer)]); + // Half in B, half outside every zone; then one without geometry. + c.push_next(rect(1.5, 2.5), vec![Value::Int(100)]); + c.push_next(None, vec![Value::Int(7)]); + let l = layers(z, c); + let params = json!({"zones": "zones", "zoneFields": "zone", "classes": "classes", "sumFields": "pop"}); + let result = rustgis_analysis::run("tabulateIntersection", &l, ¶ms).unwrap(); + assert_eq!( + result.messages, + [ + "Tabulate Intersection: 1 row", + "1 zone feature has no geometry and was left out", + "1 class feature has no geometry and was left out", + "3 zones overlap no class feature, so they have no rows", + "1 class feature lies partly or wholly outside the zones: its value outside isn't shared out", + ] + ); + let got = rows(&table(result)); + assert_eq!(got.iter().map(|(t, n)| (t.join(""), n[1], n[2])).collect::>(), [("B".into(), 50.0, 50.0)]); +} + +#[test] +fn zones_sharing_a_value_are_one_zone() { + let mut z = zones(); + for f in &mut z.features { + f.attrs[0] = Value::Text("all".into()); + } + let l = layers(z, classes()); + let params = json!({"zones": "zones", "zoneFields": "zone", "classes": "classes", "classFields": "kind"}); + let result = rustgis_analysis::run("tabulateIntersection", &l, ¶ms).unwrap(); + assert_eq!(result.messages, ["Tabulate Intersection: 2 rows"]); + // The forests cover 1° of the zone's 3°, the water half a degree. + let got = rows(&table(result)); + assert_eq!( + got.iter().map(|(t, n)| (t.join(" "), n[1])).collect::>(), + [("all forest".into(), 33.333), ("all water".into(), 16.667)] + ); +} + +#[test] +fn refuses_inputs_it_cannot_tabulate() { + let mut lines = Dataset::new("lines", GeometryType::Polyline, vec![Field::new("zone", FieldType::Text)]); + lines.push_next(Some(Geometry::Line(vec![vec![Coord::new(0.0, 0.0), Coord::new(1.0, 1.0)]])), vec![Value::Text("A".into())]); + let mut l = layers(zones(), classes()); + l.data.insert("lines".into(), lines); + let run = |params: serde_json::Value| rustgis_analysis::run("tabulateIntersection", &l, ¶ms).unwrap_err(); + assert_eq!(run(json!({"zones": "zones", "zoneFields": "zone", "classes": "lines"})), "'lines' is not a polygon layer"); + assert_eq!(run(json!({"zones": "zones", "zoneFields": [], "classes": "classes"})), "'Zone Fields' is required"); + assert_eq!( + run(json!({"zones": "zones", "zoneFields": "zone", "classes": "classes", "sumFields": "kind"})), + "the sum field 'kind' is not numeric" + ); + assert_eq!( + run(json!({"zones": "zones", "zoneFields": "zone", "classes": "classes", "classFields": "pop", "sumFields": "pop"})), + "the sum field 'pop' can't also be a class field" + ); +} diff --git a/crates/assistant/skills/geoprocessing/SKILL.md b/crates/assistant/skills/geoprocessing/SKILL.md index 93b52c0735..158abd6546 100644 --- a/crates/assistant/skills/geoprocessing/SKILL.md +++ b/crates/assistant/skills/geoprocessing/SKILL.md @@ -25,7 +25,9 @@ Based on the RustGIS user guide, Analysis › Geoprocessing tools - selection: `selectByLocation` (`input`, `select`, `distance`, `invert`), `selectByAttributes` (`input`, `where`) - statistics: `countPoints` (Summarize Within: `polygons`, `points`), `summaryStatistics` - (`input`, `statistics`, `case`), `pivotTable` (`input`, `fields`, `pivot`, `value`, `statistic`) + (`input`, `statistics`, `case`), `pivotTable` (`input`, `fields`, `pivot`, `value`, `statistic`), + `tabulateIntersection` (`zones`, `zoneFields`, `classes`, `classFields`, `sumFields`: class + areas and totals shared out to zones by overlap) - joins: `spatialJoin` (`target`, `join`, `match`), `joinField` (`target`, `targetField`, `joinTable`, `joinField`, `fields`, `prefix`, `duplicates`) - conversion: `exportFeatures` (`input`, `where`) diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index 3cdee526e0..52bd48df04 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -112,6 +112,7 @@ Use these ids in `gp.run`'s `tool` parameter (`gp.tools` lists the available too | Summarize Within | `countPoints` | Analysis › Summarize | | Summary Statistics | `summaryStatistics` | Analysis › Statistics | | Pivot Table | `pivotTable` | Analysis › Statistics | +| Tabulate Intersection | `tabulateIntersection` | Analysis › Statistics | | Export Features | `exportFeatures` | Conversion | | Vector to PMTiles | `vectorToPmtiles` | Analyze › Tools | | Raster to PMTiles | `rasterToPmtiles` | Analyze › Tools | @@ -553,6 +554,47 @@ output is named `_Pivot` unless `output` names it. The AI Assistant uses Pivot Table for questions such as "mean household income by county and year": it runs the tool with `county` as the row field, `year` as the pivot field and `MEAN`, then reads the table it names with `read_features`, a row per county. + +**Tabulate Intersection** (`tabulateIntersection`) measures how much of each zone each class of +polygons covers, and shares the classes' totals out to the zones by area. Both layers are polygon +layers. Zone features sharing the values of the `zoneFields` (one field, or several as a list) make +one zone, and class features sharing the values of the `classFields` make one class; with no class +fields, all the class features are one class. The tool makes a standalone table with a row for each +zone and class that overlap (pairs that only touch get none), in the order of the zones, then the +classes, as they first appear in the layers: + +| Field | Holds | +| --- | --- | +| The zone fields | The zone's values | +| The class fields | The class's values | +| `area_km2` | The ground area of the class in the zone, in km², where class features overlap each other counted once | +| `percentage` | That area as a percentage of the zone's ground area (empty for a zone with no area) | +| Each of `sumFields` | The sum, over the class's features, of the field's value times the part of the feature's area inside the zone | + +A field name already used in the table, ignoring case, gets `_2` (`_3` and so on), as when a +class field and a zone field are both called `name`. + +The sum fields share a total out by area, as for population counted by census block and wanted by +school district: a block half inside a district gives it half its population. They must be numeric, +and can't also be class fields. Zones that overlap each other each get their share, so a value can +be shared out more than once; the value of a feature's part outside every zone isn't shared out. + +`area_km2` is measured on the ellipsoid, as Calculate Geometry Attributes measures it. The +percentages and shares compare areas measured on a sphere, which add up exactly when a polygon is +cut along a parallel or a meridian, so the shares of a feature that zones cover without overlapping +each other add up to its whole value. The percentages of classes that overlap each other can add up +to more than 100. + +The tool says how many zone and class features have no geometry (they are left out), how many zones +overlap no class feature and so have no rows, how many class features have no value in a sum field +(they add nothing to its shares) and, with sum fields, how many class features lie partly or wholly +outside the zones. Only selected features are used when a layer has a selection, and the table is named +`_Tabulate` unless `output` names it. + +```text +gp.run={"tool":"tabulateIntersection","params":{"zones":"districts","zoneFields":"district","classes":"blocks","sumFields":["population"]}} +gp.run={"tool":"tabulateIntersection","params":{"zones":"counties","zoneFields":"county","classes":"landcover","classFields":"class"}} +```
![Tissot's indicatrix on the Robinson projection: circles of 800 km every 30°, stretched and sheared toward the poles](https://assets.rustgis.app/images/tissot.webp)
Tissot's indicatrix on Robinson: equal circles, stretched and sheared by the projection.
From 9946f48c61076a69a255ad25451529bada153067 Mon Sep 17 00:00:00 2001 From: mavrick Date: Sun, 1 Nov 2026 16:56:35 -0600 Subject: [PATCH 02/12] fix(analysis): measure Tabulate Intersection's shares as the map draws polygons MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The overlay cuts along straight lines on the map (rhumb lines), but the shares were measured with edges straight in longitude and latitude, so a cut partway along a slanted edge lost or gained area: 1,000,000 shared across two zones came to 1,105,069. Percentages and shares now use map_area_m2, the sphere area of each rhumb-line edge in closed form, which splits exactly under such a cut. - With overlapping zones, measure what they cover of a class feature as the union of its parts, so the outside notice isn't masked by shares that add up to the whole. - A zone without geometry is no longer also counted as overlapping no class feature. - Docs: rows are sorted by zone then class values, the percentage's basis, and the 85.05° map limit (#1033). Co-Authored-By: Claude Opus 5.5 --- crates/analysis/src/tools.rs | 91 +++++++++++++++---- .../analysis/tests/tabulate_intersection.rs | 47 +++++++++- docs/user-guide/analysis.md | 16 ++-- 3 files changed, 126 insertions(+), 28 deletions(-) diff --git a/crates/analysis/src/tools.rs b/crates/analysis/src/tools.rs index 87cd4b71fc..856b227b48 100644 --- a/crates/analysis/src/tools.rs +++ b/crates/analysis/src/tools.rs @@ -2818,6 +2818,43 @@ fn ground_area_perimeter(g: &Geometry) -> (f64, f64) { (a, per) } +/// The area (square metres, holes taken out) of a lon/lat polygon geometry on a sphere of the +/// Earth's radius, as the map draws it: each edge a straight line in Web Mercator, which is a rhumb +/// line, and latitudes clamped to the map's limit, as the overlay takes them. A polygon cut along +/// any straight line on the map splits this area exactly, up to rounding, so the parts' areas add +/// up to the whole's. Zero for any other geometry. +fn map_area_m2(g: &Geometry) -> f64 { + let Geometry::Polygon(polys) = g else { return 0.0 }; + let r2 = rustgis_geom::EARTH_RADIUS_M * rustgis_geom::EARTH_RADIUS_M; + polys.iter().flat_map(|rings| rings.iter().enumerate()).map(|(i, r)| if i == 0 { 1.0 } else { -1.0 } * rhumb_ring_area(r) * r2).sum() +} + +/// The area of a ring of rhumb lines on the unit sphere, |∮ sin φ dλ|, for [`map_area_m2`]. Along a +/// rhumb line the isometric latitude ψ (the Mercator y over the radius) changes linearly with the +/// longitude λ and sin φ = tanh ψ, so an edge's integral is Δλ/Δψ × (ln cosh ψ₂ − ln cosh ψ₁); for a +/// short Δψ, where that difference cancels, its Taylor series about the middle. An edge that jumps +/// across the antimeridian is the short hop, as [`rustgis_geom::geodesic_ring_area_m2`] takes it. +fn rhumb_ring_area(ring: &[Coord]) -> f64 { + let iso = |c: &Coord| c.y.clamp(-rustgis_geom::MAX_LAT, rustgis_geom::MAX_LAT).to_radians().tan().asinh(); + let ln_cosh = |x: f64| x.abs() + (-2.0 * x.abs()).exp().ln_1p() - std::f64::consts::LN_2; + let mut total = 0.0; + for (a, b) in ring.iter().zip(ring.iter().cycle().skip(1)) { + let dlon = b.x - a.x; + let dlon = if dlon.abs() > 180.0 && dlon.abs() < 360.0 { dlon - 360.0 * dlon.signum() } else { dlon }; + let (p1, p2) = (iso(a), iso(b)); + let dpsi = p2 - p1; + let mean_sin = if dpsi.abs() < 1e-4 { + // tanh over the edge, averaged: tanh m + Δψ²/24 × tanh″ m, with tanh″ = −2 tanh sech². + let t = ((p1 + p2) / 2.0).tanh(); + t - dpsi * dpsi / 12.0 * t * (1.0 - t * t) + } else { + (ln_cosh(p2) - ln_cosh(p1)) / dpsi + }; + total += dlon.to_radians() * mean_sin; + } + total.abs() +} + /// Calculate Geometry Attributes: adds `area_km2` and `perimeter_km` to a polygon layer (see /// [`ground_area_perimeter`]), `length_km` to a line layer, and `point_x`/`point_y` (a label point) /// to any other, updating the layer in place. @@ -3158,9 +3195,9 @@ struct TabulateZone { ext: Extent, /// Its features' polygons in Web Mercator, unioned when there are several, as [`mask_of`] does. mask: MultiPolygon, - /// Its area in square metres on the sphere, as [`tabulate_intersection`] compares areas (see - /// there), overlaps between its features counted once. - sphere_area_m2: f64, + /// Its area in square metres as the map draws it ([`map_area_m2`]), overlaps between its + /// features counted once. + map_area_m2: f64, } /// What one class covers of one zone: its class features' parts in the zone, and the shares of @@ -3174,19 +3211,18 @@ struct TabulateCell { /// class fields, `area_km2` (the ground area of the class in the zone, class features overlapping /// each other counted once), `percentage` (that area as a percentage of the zone's) and each sum /// field's share: the sum, over the class's features, of the field's value times the part of the -/// feature's area inside the zone. Rows follow the zones, then the classes, in record order; pairs -/// that only touch get none. Only selected features are used when a layer has a selection. The +/// feature's area inside the zone. Rows are sorted by the zone fields' values, then the class +/// fields', as Summary Statistics sorts its groups; pairs that only touch get none. Only selected features are used when a layer has a selection. The /// messages count features without geometry (left out), zones with no rows, class features with no /// value in a sum field and, with sum fields, class features not wholly inside the zones, whose /// values are not wholly shared out. /// /// `area_km2` is measured on the ellipsoid, as Calculate Geometry Attributes measures it. The -/// percentages and shares compare areas measured on the sphere instead ([`crate::join::area_m2`]): -/// the overlay cuts along straight lines on the map, and that measure adds up exactly when a -/// polygon is cut along a parallel or a meridian, where the ellipsoid's geodesic edges don't, so a -/// feature's shares in zones that cover it without overlapping each other add up to its whole value. +/// percentages and shares compare areas measured as the map draws the polygons instead +/// ([`map_area_m2`]): the overlay cuts along straight lines on the map, which that measure splits +/// exactly and the ellipsoid's geodesic edges don't, so a feature's shares in zones that cover it +/// without overlapping each other add up to its whole value. fn tabulate_intersection(inp: &dyn Inputs, p: &Json) -> Result { - use crate::join::area_m2; let zones = input(inp, p, "zones")?; let classes = input(inp, p, "classes")?; for ds in [zones, classes] { @@ -3226,8 +3262,8 @@ fn tabulate_intersection(inp: &dyn Inputs, p: &Json) -> Result = group.rows.iter().filter_map(|&r| zones.features.get(r)?.geometry.as_ref()).collect(); let ext = shapes.iter().fold(Extent::EMPTY, |e, g| e.union(&g.extent())); let mask = mask_of(MultiPolygon::new(shapes.iter().filter_map(|g| to_multipolygon(g)).flat_map(|m| m.0).collect())); - let sphere_area_m2 = from_multipolygon(&mask).map_or(0.0, |g| area_m2(&g)); - TabulateZone { key: group.key, ext, mask, sphere_area_m2 } + let map_area = from_multipolygon(&mask).map_or(0.0, |g| map_area_m2(&g)); + TabulateZone { key: group.key, ext, mask, map_area_m2: map_area } }) .collect(); let class_groups = crate::stats::group_rows(classes, &class_rows, &class_keys); @@ -3252,18 +3288,21 @@ fn tabulate_intersection(inp: &dyn Inputs, p: &Json) -> Result> = sum_fields.iter().map(|&f| classes.value(r, f).as_f64()).collect(); let mut whole_area: Option = None; let mut inside = false; - // The part of the feature's area its shares took, over all zones. + // The part of the feature's area its shares took, over all zones, and with sum fields + // and several zones near, its parts, for when overlapping zones make that sum misleading. let mut shared = 0.0; + let mut own_parts: Vec> = Vec::new(); + let keep_parts = !sum_fields.is_empty() && near.len() > 1; for zi in near { let Some(piece) = zone_list.get(zi).and_then(|z| part(&whole, &z.mask, true)) else { continue }; - let piece_area = area_m2(&piece); + let piece_area = map_area_m2(&piece); if piece_area <= 0.0 || !piece_area.is_finite() { continue; } inside = true; let cell = cells.entry((zi, ci)).or_insert_with(|| TabulateCell { parts: Vec::new(), sums: vec![0.0; sum_fields.len()] }); if !sum_fields.is_empty() { - let total = *whole_area.get_or_insert_with(|| area_m2(&whole)); + let total = *whole_area.get_or_insert_with(|| map_area_m2(&whole)); // The part inside can come out a rounding error larger than the whole. let share = if total > 0.0 { (piece_area / total).min(1.0) } else { 0.0 }; shared += share; @@ -3273,6 +3312,9 @@ fn tabulate_intersection(inp: &dyn Inputs, p: &Json) -> Result Result 1) { + (Some(total), true) if total > 0.0 && shared >= 1.0 - 1e-6 => { + from_multipolygon(&union_all(own_parts.iter().flat_map(|m| m.0.iter()))).map_or(0.0, |g| map_area_m2(&g)) / total + } + _ => shared, + }; + // What zones cover is a rounding error short of the whole when they cover the feature. + if !sum_fields.is_empty() && covered < 1.0 - 1e-6 { outside += 1; } } @@ -3323,8 +3373,8 @@ fn tabulate_intersection(inp: &dyn Inputs, p: &Json) -> Result 0.0 { Value::Float(sphere_area_m2 / zone.sphere_area_m2 * 100.0) } else { Value::Null }); + let covered_area = map_area_m2(covered); + row.push(if zone.map_area_m2 > 0.0 { Value::Float(covered_area / zone.map_area_m2 * 100.0) } else { Value::Null }); row.extend(cell.sums.into_iter().map(Value::Float)); // One past the last id: `push` would search them all for each row. out.push_next(None, row); @@ -3340,7 +3390,8 @@ fn tabulate_intersection(inp: &dyn Inputs, p: &Json) -> Result messages.push(format!("{n} {layer} features have no geometry and were left out")), } } - match zone_list.len().saturating_sub(zones_hit.len()) { + // Zones without geometry are counted above, not again here. + match zone_list.iter().enumerate().filter(|(zi, z)| !z.mask.0.is_empty() && !zones_hit.contains(zi)).count() { 0 => {} 1 => messages.push("1 zone overlaps no class feature, so it has no rows".into()), n => messages.push(format!("{n} zones overlap no class feature, so they have no rows")), diff --git a/crates/analysis/tests/tabulate_intersection.rs b/crates/analysis/tests/tabulate_intersection.rs index 115263c2a9..b4553a5dbe 100644 --- a/crates/analysis/tests/tabulate_intersection.rs +++ b/crates/analysis/tests/tabulate_intersection.rs @@ -167,7 +167,7 @@ fn says_what_it_leaves_out() { "Tabulate Intersection: 1 row", "1 zone feature has no geometry and was left out", "1 class feature has no geometry and was left out", - "3 zones overlap no class feature, so they have no rows", + "2 zones overlap no class feature, so they have no rows", "1 class feature lies partly or wholly outside the zones: its value outside isn't shared out", ] ); @@ -175,6 +175,51 @@ fn says_what_it_leaves_out() { assert_eq!(got.iter().map(|(t, n)| (t.join(""), n[1], n[2])).collect::>(), [("B".into(), 50.0, 50.0)]); } +/// A class feature with a long slanted edge, cut by a meridian between two zones: the cut point lies +/// partway along the slanted edge, and its value still shares out in full. +#[test] +fn shares_add_up_where_a_cut_crosses_a_slanted_edge() { + let square = |x0: f64, x1: f64| { + let ring = [(x0, 40.0), (x1, 40.0), (x1, 60.0), (x0, 60.0), (x0, 40.0)].map(|(x, y)| Coord::new(x, y)).to_vec(); + Some(Geometry::Polygon(vec![vec![ring]])) + }; + let mut z = Dataset::new("zones", GeometryType::Polygon, vec![Field::new("zone", FieldType::Text)]); + z.push_next(square(0.0, 10.0), vec![Value::Text("A".into())]); + z.push_next(square(10.0, 20.0), vec![Value::Text("B".into())]); + let mut c = Dataset::new("classes", GeometryType::Polygon, vec![Field::new("pop", FieldType::Integer)]); + let triangle = [(0.0, 40.0), (20.0, 40.0), (0.0, 60.0), (0.0, 40.0)].map(|(x, y)| Coord::new(x, y)).to_vec(); + c.push_next(Some(Geometry::Polygon(vec![vec![triangle]])), vec![Value::Int(1_000_000)]); + let l = layers(z, c); + let params = json!({"zones": "zones", "zoneFields": "zone", "classes": "classes", "sumFields": "pop"}); + let result = rustgis_analysis::run("tabulateIntersection", &l, ¶ms).unwrap(); + assert_eq!(result.messages, ["Tabulate Intersection: 2 rows"]); + let out = table(result); + let pops: Vec = out.features.iter().filter_map(|f| f.attrs.get(3).and_then(Value::as_f64)).collect(); + assert_eq!(pops.len(), 2); + let total: f64 = pops.iter().sum(); + assert!((total / 1_000_000.0 - 1.0).abs() < 1e-6, "{pops:?} add up to {total}"); +} + +/// Zones that overlap each other give a feature shares adding up to its whole value while half of +/// it lies outside them both: the notice still says so. +#[test] +fn overlapping_zones_still_say_what_lies_outside() { + let mut z = Dataset::new("zones", GeometryType::Polygon, vec![Field::new("zone", FieldType::Text)]); + z.push_next(rect(0.0, 1.0), vec![Value::Text("A".into())]); + z.push_next(rect(0.5, 1.5), vec![Value::Text("B".into())]); + let mut c = Dataset::new("classes", GeometryType::Polygon, vec![Field::new("pop", FieldType::Integer)]); + c.push_next(rect(0.0, 2.0), vec![Value::Int(100)]); + let l = layers(z, c); + let params = json!({"zones": "zones", "zoneFields": "zone", "classes": "classes", "sumFields": "pop"}); + let result = rustgis_analysis::run("tabulateIntersection", &l, ¶ms).unwrap(); + assert_eq!( + result.messages, + ["Tabulate Intersection: 2 rows", "1 class feature lies partly or wholly outside the zones: its value outside isn't shared out"] + ); + let got = rows(&table(result)); + assert_eq!(got.iter().map(|(_, n)| n[2]).collect::>(), [50.0, 50.0]); +} + #[test] fn zones_sharing_a_value_are_one_zone() { let mut z = zones(); diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index 52bd48df04..6013368ed0 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -560,15 +560,15 @@ polygons covers, and shares the classes' totals out to the zones by area. Both l layers. Zone features sharing the values of the `zoneFields` (one field, or several as a list) make one zone, and class features sharing the values of the `classFields` make one class; with no class fields, all the class features are one class. The tool makes a standalone table with a row for each -zone and class that overlap (pairs that only touch get none), in the order of the zones, then the -classes, as they first appear in the layers: +zone and class that overlap (pairs that only touch get none), sorted by the zone fields' values, +then the class fields', with empty values first, as Summary Statistics sorts its rows: | Field | Holds | | --- | --- | | The zone fields | The zone's values | | The class fields | The class's values | | `area_km2` | The ground area of the class in the zone, in km², where class features overlap each other counted once | -| `percentage` | That area as a percentage of the zone's ground area (empty for a zone with no area) | +| `percentage` | The class's area in the zone as a percentage of the zone's area, both measured as the map draws them (below; empty for a zone with no area) | | Each of `sumFields` | The sum, over the class's features, of the field's value times the part of the feature's area inside the zone | A field name already used in the table, ignoring case, gets `_2` (`_3` and so on), as when a @@ -580,10 +580,12 @@ and can't also be class fields. Zones that overlap each other each get their sha be shared out more than once; the value of a feature's part outside every zone isn't shared out. `area_km2` is measured on the ellipsoid, as Calculate Geometry Attributes measures it. The -percentages and shares compare areas measured on a sphere, which add up exactly when a polygon is -cut along a parallel or a meridian, so the shares of a feature that zones cover without overlapping -each other add up to its whole value. The percentages of classes that overlap each other can add up -to more than 100. +percentages and shares compare areas measured on a sphere with each edge as the map draws it (a +straight line on the map), the lines the tool cuts along, so the shares of a feature that zones +cover without overlapping each other add up to its whole value. The percentages of classes that +overlap each other can add up to more than 100. Like the other overlay tools, it works on the map, +which ends at 85.05° north and south: parts of polygons beyond that are taken as lying along it, so +overlaps there have no area ([#1033](https://github.com/opengeos/RustGIS/issues/1033)). The tool says how many zone and class features have no geometry (they are left out), how many zones overlap no class feature and so have no rows, how many class features have no value in a sum field From 0ce507a80acc8f50932dd6b34a2cca6d04bf33cc Mon Sep 17 00:00:00 2001 From: mavrick Date: Sun, 1 Nov 2026 17:34:13 -0600 Subject: [PATCH 03/12] fix(analysis): take Tabulate Intersection's map area exactly as the map draws rings MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The overlay doesn't fold longitudes, so an edge jumping across the antimeridian runs across the whole map there, and a ring stored around a pole is drawn flat. map_area_m2 now takes longitudes as they are too, so the totals it measures match the pieces the overlay cuts: no winding term can arise and edges wider than 180° are no longer measured as short hops. - Count a zone or class geometry with no polygon (GeoJSON's empty coordinates) as having no geometry, so it is reported, not dropped. - Count a zone whose polygons collapse on the map among zones with no rows, testing its extent rather than its mask. - Tests: the map measure on a world-wide band and a ring around a pole, and each zone's share at a slanted edge against Simpson's rule. Co-Authored-By: Claude Opus 5.5 --- crates/analysis/src/tools.rs | 39 +++++++++++++++---- .../analysis/tests/tabulate_intersection.rs | 32 ++++++++++++++- 2 files changed, 62 insertions(+), 9 deletions(-) diff --git a/crates/analysis/src/tools.rs b/crates/analysis/src/tools.rs index 856b227b48..b9aa122e26 100644 --- a/crates/analysis/src/tools.rs +++ b/crates/analysis/src/tools.rs @@ -2820,7 +2820,8 @@ fn ground_area_perimeter(g: &Geometry) -> (f64, f64) { /// The area (square metres, holes taken out) of a lon/lat polygon geometry on a sphere of the /// Earth's radius, as the map draws it: each edge a straight line in Web Mercator, which is a rhumb -/// line, and latitudes clamped to the map's limit, as the overlay takes them. A polygon cut along +/// line, with longitudes as they are (not folded across the antimeridian) and latitudes clamped to +/// the map's limit, as the overlay takes them. A polygon cut along /// any straight line on the map splits this area exactly, up to rounding, so the parts' areas add /// up to the whole's. Zero for any other geometry. fn map_area_m2(g: &Geometry) -> f64 { @@ -2832,15 +2833,15 @@ fn map_area_m2(g: &Geometry) -> f64 { /// The area of a ring of rhumb lines on the unit sphere, |∮ sin φ dλ|, for [`map_area_m2`]. Along a /// rhumb line the isometric latitude ψ (the Mercator y over the radius) changes linearly with the /// longitude λ and sin φ = tanh ψ, so an edge's integral is Δλ/Δψ × (ln cosh ψ₂ − ln cosh ψ₁); for a -/// short Δψ, where that difference cancels, its Taylor series about the middle. An edge that jumps -/// across the antimeridian is the short hop, as [`rustgis_geom::geodesic_ring_area_m2`] takes it. +/// short Δψ, where that difference cancels, its Taylor series about the middle. Longitudes are not +/// folded, as on the map, so the ring's Δλ add up to 0 and no ring winds around a pole: a ring +/// stored around one with a jump across the antimeridian is the flat shape the map draws for it. fn rhumb_ring_area(ring: &[Coord]) -> f64 { let iso = |c: &Coord| c.y.clamp(-rustgis_geom::MAX_LAT, rustgis_geom::MAX_LAT).to_radians().tan().asinh(); let ln_cosh = |x: f64| x.abs() + (-2.0 * x.abs()).exp().ln_1p() - std::f64::consts::LN_2; let mut total = 0.0; for (a, b) in ring.iter().zip(ring.iter().cycle().skip(1)) { let dlon = b.x - a.x; - let dlon = if dlon.abs() > 180.0 && dlon.abs() < 360.0 { dlon - 360.0 * dlon.signum() } else { dlon }; let (p1, p2) = (iso(a), iso(b)); let dpsi = p2 - p1; let mean_sin = if dpsi.abs() < 1e-4 { @@ -3252,14 +3253,21 @@ fn tabulate_intersection(inp: &dyn Inputs, p: &Json) -> Result = crate::stats::group_rows(zones, &zone_rows, &zone_keys) .into_iter() .map(|group| { - let shapes: Vec<&Geometry> = group.rows.iter().filter_map(|&r| zones.features.get(r)?.geometry.as_ref()).collect(); + let shapes: Vec<&Geometry> = + group.rows.iter().filter_map(|&r| zones.features.get(r)?.geometry.as_ref()).filter(|g| has_shape(g)).collect(); let ext = shapes.iter().fold(Extent::EMPTY, |e, g| e.union(&g.extent())); let mask = mask_of(MultiPolygon::new(shapes.iter().filter_map(|g| to_multipolygon(g)).flat_map(|m| m.0).collect())); let map_area = from_multipolygon(&mask).map_or(0.0, |g| map_area_m2(&g)); @@ -3275,7 +3283,7 @@ fn tabulate_intersection(inp: &dyn Inputs, p: &Json) -> Result = index.candidates(&ext).into_iter().filter(|&zi| zone_list.get(zi).is_some_and(|z| z.ext.intersects(&ext))).collect(); @@ -3391,7 +3399,7 @@ fn tabulate_intersection(inp: &dyn Inputs, p: &Json) -> Result {} 1 => messages.push("1 zone overlaps no class feature, so it has no rows".into()), n => messages.push(format!("{n} zones overlap no class feature, so they have no rows")), @@ -6298,6 +6306,21 @@ mod tests { } } + /// The map measure takes rings as the map draws them: a band around the world stored as a + /// rectangle from −180° to 180° has its whole area, and a ring stored around a pole with a jump + /// across the antimeridian, which the map draws flat, has none. + #[test] + fn map_area_measures_rings_as_the_map_draws_them() { + let ring = |pts: &[(f64, f64)]| Geometry::Polygon(vec![vec![pts.iter().map(|&(x, y)| Coord::new(x, y)).collect()]]); + let r2 = rustgis_geom::EARTH_RADIUS_M * rustgis_geom::EARTH_RADIUS_M; + let band = map_area_m2(&ring(&[(-180.0, 0.0), (180.0, 0.0), (180.0, 60.0), (-180.0, 60.0), (-180.0, 0.0)])); + let expected = r2 * std::f64::consts::TAU * 60f64.to_radians().sin(); + assert!((band / expected - 1.0).abs() < 1e-12, "{band} m², not {expected}"); + let around_pole = map_area_m2(&ring(&[(0.0, 60.0), (90.0, 60.0), (180.0, 60.0), (-90.0, 60.0), (0.0, 60.0)])); + // Zero, up to rounding on the scale of the Earth's radius squared. + assert!(around_pole.abs() < 1.0, "{around_pole} m²"); + } + /// Parcels and zones for Intersect: `p1` is a 2° square that zone `z1` covers the right half of; /// `z2` overlaps `z1` but only touches `p1` along its right edge, and `p2` along its left. /// Both layers have an `id` field. diff --git a/crates/analysis/tests/tabulate_intersection.rs b/crates/analysis/tests/tabulate_intersection.rs index b4553a5dbe..63f0ddd723 100644 --- a/crates/analysis/tests/tabulate_intersection.rs +++ b/crates/analysis/tests/tabulate_intersection.rs @@ -154,6 +154,8 @@ fn clean_input_gives_no_notices() { fn says_what_it_leaves_out() { let mut z = zones(); z.push_next(None, vec![Value::Text("D".into())]); + // A geometry with no polygon, as GeoJSON's `"coordinates": []` reads. + z.push_next(Some(Geometry::Polygon(vec![])), vec![Value::Text("E".into())]); let mut c = Dataset::new("classes", GeometryType::Polygon, vec![Field::new("pop", FieldType::Integer)]); // Half in B, half outside every zone; then one without geometry. c.push_next(rect(1.5, 2.5), vec![Value::Int(100)]); @@ -165,7 +167,7 @@ fn says_what_it_leaves_out() { result.messages, [ "Tabulate Intersection: 1 row", - "1 zone feature has no geometry and was left out", + "2 zone features have no geometry and were left out", "1 class feature has no geometry and was left out", "2 zones overlap no class feature, so they have no rows", "1 class feature lies partly or wholly outside the zones: its value outside isn't shared out", @@ -198,6 +200,34 @@ fn shares_add_up_where_a_cut_crosses_a_slanted_edge() { assert_eq!(pops.len(), 2); let total: f64 = pops.iter().sum(); assert!((total / 1_000_000.0 - 1.0).abs() < 1e-6, "{pops:?} add up to {total}"); + // Each zone's share is its part of the triangle's area, worked out here by Simpson's rule on the + // sphere: the slanted edge is straight on the map, so its isometric latitude ψ changes linearly + // with longitude, and the triangle's area at each longitude runs from 40° up to that edge. + let psi = |lat: f64| lat.to_radians().tan().asinh(); + let above_40 = |lon: f64| (psi(60.0) + (psi(40.0) - psi(60.0)) * lon / 20.0).tanh() - 40f64.to_radians().sin(); + let simpson = |a: f64, b: f64| { + let n = 2000; + let h = (b - a) / n as f64; + (0..=n) + .map(|i| { + above_40(a + h * i as f64) + * if i == 0 || i == n { + 1.0 + } else if i % 2 == 1 { + 4.0 + } else { + 2.0 + } + }) + .sum::() + * h + / 3.0 + }; + let (in_a, in_b) = (simpson(0.0, 10.0), simpson(10.0, 20.0)); + let expected = [in_a, in_b].map(|part| 1_000_000.0 * part / (in_a + in_b)); + for (got, want) in pops.iter().zip(expected) { + assert!((got / want - 1.0).abs() < 1e-6, "{pops:?}, not {expected:?}"); + } } /// Zones that overlap each other give a feature shares adding up to its whole value while half of From fd6372e7b826083523ccc51fb35bf23bef3c2539 Mon Sep 17 00:00:00 2001 From: mavrick Date: Sun, 1 Nov 2026 20:13:09 -0600 Subject: [PATCH 04/12] fix(analysis): say a feature has no polygon, not no geometry A polygon layer can hold a line or point feature; Tabulate Intersection leaves it out with the features without geometry, but its notice said "has no geometry". The notice now says "has no polygon", and the guide lists the cases (no geometry, an empty one, a line or a point). The test adds a line feature to the class layer. The tool's doc comment is rewrapped. Co-Authored-By: Claude Opus 5.5 --- crates/analysis/src/tools.rs | 17 +++++++++-------- crates/analysis/tests/tabulate_intersection.rs | 6 ++++-- docs/user-guide/analysis.md | 10 +++++----- 3 files changed, 18 insertions(+), 15 deletions(-) diff --git a/crates/analysis/src/tools.rs b/crates/analysis/src/tools.rs index b9aa122e26..875be447f1 100644 --- a/crates/analysis/src/tools.rs +++ b/crates/analysis/src/tools.rs @@ -3213,10 +3213,11 @@ struct TabulateCell { /// each other counted once), `percentage` (that area as a percentage of the zone's) and each sum /// field's share: the sum, over the class's features, of the field's value times the part of the /// feature's area inside the zone. Rows are sorted by the zone fields' values, then the class -/// fields', as Summary Statistics sorts its groups; pairs that only touch get none. Only selected features are used when a layer has a selection. The -/// messages count features without geometry (left out), zones with no rows, class features with no -/// value in a sum field and, with sum fields, class features not wholly inside the zones, whose -/// values are not wholly shared out. +/// fields', as Summary Statistics sorts its groups; pairs that only touch get none. Only selected +/// features are used when a layer has a selection. The messages count features without a polygon +/// (left out: no geometry, an empty one, a line or a point), zones with no rows, class features +/// with no value in a sum field and, with sum fields, class features not wholly inside the zones, +/// whose values are not wholly shared out. /// /// `area_km2` is measured on the ellipsoid, as Calculate Geometry Attributes measures it. The /// percentages and shares compare areas measured as the map draws the polygons instead @@ -3253,8 +3254,8 @@ fn tabulate_intersection(inp: &dyn Inputs, p: &Json) -> Result Result {} - 1 => messages.push(format!("1 {layer} feature has no geometry and was left out")), - n => messages.push(format!("{n} {layer} features have no geometry and were left out")), + 1 => messages.push(format!("1 {layer} feature has no polygon and was left out")), + n => messages.push(format!("{n} {layer} features have no polygon and were left out")), } } // Zones without geometry are counted above, not again here. diff --git a/crates/analysis/tests/tabulate_intersection.rs b/crates/analysis/tests/tabulate_intersection.rs index 63f0ddd723..aa194026bc 100644 --- a/crates/analysis/tests/tabulate_intersection.rs +++ b/crates/analysis/tests/tabulate_intersection.rs @@ -160,6 +160,8 @@ fn says_what_it_leaves_out() { // Half in B, half outside every zone; then one without geometry. c.push_next(rect(1.5, 2.5), vec![Value::Int(100)]); c.push_next(None, vec![Value::Int(7)]); + // A line in a polygon layer: it has geometry, but no polygon. + c.push_next(Some(Geometry::Line(vec![vec![Coord::new(1.2, 0.2), Coord::new(1.8, 0.8)]])), vec![Value::Int(9)]); let l = layers(z, c); let params = json!({"zones": "zones", "zoneFields": "zone", "classes": "classes", "sumFields": "pop"}); let result = rustgis_analysis::run("tabulateIntersection", &l, ¶ms).unwrap(); @@ -167,8 +169,8 @@ fn says_what_it_leaves_out() { result.messages, [ "Tabulate Intersection: 1 row", - "2 zone features have no geometry and were left out", - "1 class feature has no geometry and was left out", + "2 zone features have no polygon and were left out", + "2 class features have no polygon and were left out", "2 zones overlap no class feature, so they have no rows", "1 class feature lies partly or wholly outside the zones: its value outside isn't shared out", ] diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index 6013368ed0..1ddf8d2ed2 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -587,11 +587,11 @@ overlap each other can add up to more than 100. Like the other overlay tools, it which ends at 85.05° north and south: parts of polygons beyond that are taken as lying along it, so overlaps there have no area ([#1033](https://github.com/opengeos/RustGIS/issues/1033)). -The tool says how many zone and class features have no geometry (they are left out), how many zones -overlap no class feature and so have no rows, how many class features have no value in a sum field -(they add nothing to its shares) and, with sum fields, how many class features lie partly or wholly -outside the zones. Only selected features are used when a layer has a selection, and the table is named -`_Tabulate` unless `output` names it. +The tool says how many zone and class features have no polygon (no geometry, an empty one, or a line +or point; they are left out), how many zones overlap no class feature and so have no rows, how many +class features have no value in a sum field (they add nothing to its shares) and, with sum fields, +how many class features lie partly or wholly outside the zones. Only selected features are used when +a layer has a selection, and the table is named `_Tabulate` unless `output` names it. ```text gp.run={"tool":"tabulateIntersection","params":{"zones":"districts","zoneFields":"district","classes":"blocks","sumFields":["population"]}} From 0701d6454ab22310e9e9b24012cb32d4656af649 Mon Sep 17 00:00:00 2001 From: mavrick Date: Sun, 1 Nov 2026 20:44:24 -0600 Subject: [PATCH 05/12] fix(analysis): one Tabulate Intersection notice per kind, including the latitude limit MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Say how many zone and class features reach beyond 85.05° latitude, where the map ends and the overlay takes their parts as lying along it: a class wholly beyond it otherwise vanished without a notice. - Report missing sum-field values in one notice, naming each field and its count, rather than one message per field. - Guide: say the tool reports the latitude limit; a blank line before the next section's figure. Co-Authored-By: Claude Opus 5.5 --- crates/analysis/src/tools.rs | 41 ++++++++++++++++--- .../analysis/tests/tabulate_intersection.rs | 33 +++++++++++++++ docs/user-guide/analysis.md | 4 +- 3 files changed, 72 insertions(+), 6 deletions(-) diff --git a/crates/analysis/src/tools.rs b/crates/analysis/src/tools.rs index 875be447f1..7a91cb58c1 100644 --- a/crates/analysis/src/tools.rs +++ b/crates/analysis/src/tools.rs @@ -3264,6 +3264,15 @@ fn tabulate_intersection(inp: &dyn Inputs, p: &Json) -> Result rustgis_geom::MAX_LAT || e.min_y < -rustgis_geom::MAX_LAT) + }; + rs.iter().filter(|&&r| ds.features.get(r).and_then(|f| f.geometry.as_ref()).is_some_and(beyond)).count() + }; + let (zones_beyond, classes_beyond) = (beyond_limit(zones, &zone_rows), beyond_limit(classes, &class_rows)); let zone_list: Vec = crate::stats::group_rows(zones, &zone_rows, &zone_keys) .into_iter() .map(|group| { @@ -3405,13 +3414,35 @@ fn tabulate_intersection(inp: &dyn Inputs, p: &Json) -> Result messages.push("1 zone overlaps no class feature, so it has no rows".into()), n => messages.push(format!("{n} zones overlap no class feature, so they have no rows")), } - for (&f, n) in sum_fields.iter().zip(missing) { - if n > 0 { - let name = classes.fields.get(f).map_or("", |f| f.name.as_str()); - let features = if n == 1 { "1 class feature has".to_string() } else { format!("{n} class features have") }; - messages.push(format!("{features} no value in '{name}', left out of its shares")); + let features = |n: usize, layer: &str| if n == 1 { format!("1 {layer} feature") } else { format!("{n} {layer} features") }; + // One notice for the sum fields' missing values, naming each field that has some. + let missing: Vec<(usize, &str)> = sum_fields + .iter() + .zip(missing) + .filter(|(_, n)| *n > 0) + .map(|(&f, n)| (n, classes.fields.get(f).map_or("", |f| f.name.as_str()))) + .collect(); + match missing.as_slice() { + [] => {} + [(1, name)] => messages.push(format!("1 class feature has no value in '{name}', left out of its shares")), + [(n, name)] => messages.push(format!("{n} class features have no value in '{name}', left out of its shares")), + several => { + let list: Vec = several.iter().map(|(n, name)| format!("{} in '{name}'", features(*n, "class"))).collect(); + messages.push(format!("class features with no value in a sum field are left out of its shares: {}", list.join(", "))); } } + let beyond: Vec = [(zones_beyond, "zone"), (classes_beyond, "class")] + .into_iter() + .filter(|(n, _)| *n > 0) + .map(|(n, layer)| features(n, layer)) + .collect(); + if !beyond.is_empty() { + let verb = if zones_beyond + classes_beyond == 1 { "reaches" } else { "reach" }; + messages.push(format!( + "{} {verb} beyond 85.05° latitude, where the map ends: parts there are taken as lying along it, with no area", + beyond.join(" and ") + )); + } match outside { 0 => {} 1 => messages.push("1 class feature lies partly or wholly outside the zones: its value outside isn't shared out".into()), diff --git a/crates/analysis/tests/tabulate_intersection.rs b/crates/analysis/tests/tabulate_intersection.rs index aa194026bc..f4e70557bf 100644 --- a/crates/analysis/tests/tabulate_intersection.rs +++ b/crates/analysis/tests/tabulate_intersection.rs @@ -252,6 +252,39 @@ fn overlapping_zones_still_say_what_lies_outside() { assert_eq!(got.iter().map(|(_, n)| n[2]).collect::>(), [50.0, 50.0]); } +/// A class feature reaching beyond the map's latitude limit, and features lacking values in two sum +/// fields: one notice for each kind. +#[test] +fn one_notice_per_kind_for_missing_values_and_the_latitude_limit() { + let polar = |x0: f64, x1: f64, y0: f64, y1: f64| { + let ring = [(x0, y0), (x1, y0), (x1, y1), (x0, y1), (x0, y0)].map(|(x, y)| Coord::new(x, y)).to_vec(); + Some(Geometry::Polygon(vec![vec![ring]])) + }; + let mut z = Dataset::new("zones", GeometryType::Polygon, vec![Field::new("zone", FieldType::Text)]); + z.push_next(polar(0.0, 10.0, 80.0, 84.0), vec![Value::Text("A".into())]); + let mut c = Dataset::new( + "classes", + GeometryType::Polygon, + vec![Field::new("pop", FieldType::Integer), Field::new("income", FieldType::Double)], + ); + c.push_next(polar(0.0, 5.0, 80.0, 84.0), vec![Value::Null, Value::Null]); + c.push_next(polar(5.0, 10.0, 80.0, 84.0), vec![Value::Null, Value::Float(1.0)]); + // Reaches 88°N; its part in the zone, below 84°N, is measured as usual. + c.push_next(polar(2.0, 3.0, 82.0, 88.0), vec![Value::Int(1), Value::Float(2.0)]); + let l = layers(z, c); + let params = json!({"zones": "zones", "zoneFields": "zone", "classes": "classes", "sumFields": ["pop", "income"]}); + let result = rustgis_analysis::run("tabulateIntersection", &l, ¶ms).unwrap(); + assert_eq!( + result.messages, + [ + "Tabulate Intersection: 1 row", + "class features with no value in a sum field are left out of its shares: 2 class features in 'pop', 1 class feature in 'income'", + "1 class feature reaches beyond 85.05° latitude, where the map ends: parts there are taken as lying along it, with no area", + "1 class feature lies partly or wholly outside the zones: its value outside isn't shared out", + ] + ); +} + #[test] fn zones_sharing_a_value_are_one_zone() { let mut z = zones(); diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index 1ddf8d2ed2..ad50ef03f7 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -585,7 +585,8 @@ straight line on the map), the lines the tool cuts along, so the shares of a fea cover without overlapping each other add up to its whole value. The percentages of classes that overlap each other can add up to more than 100. Like the other overlay tools, it works on the map, which ends at 85.05° north and south: parts of polygons beyond that are taken as lying along it, so -overlaps there have no area ([#1033](https://github.com/opengeos/RustGIS/issues/1033)). +overlaps there have no area ([#1033](https://github.com/opengeos/RustGIS/issues/1033)); the tool +says how many features reach beyond it. The tool says how many zone and class features have no polygon (no geometry, an empty one, or a line or point; they are left out), how many zones overlap no class feature and so have no rows, how many @@ -597,6 +598,7 @@ a layer has a selection, and the table is named `_Tabulate` unless `outpu gp.run={"tool":"tabulateIntersection","params":{"zones":"districts","zoneFields":"district","classes":"blocks","sumFields":["population"]}} gp.run={"tool":"tabulateIntersection","params":{"zones":"counties","zoneFields":"county","classes":"landcover","classFields":"class"}} ``` +
![Tissot's indicatrix on the Robinson projection: circles of 800 km every 30°, stretched and sheared toward the poles](https://assets.rustgis.app/images/tissot.webp)
Tissot's indicatrix on Robinson: equal circles, stretched and sheared by the projection.
From 5cb65954295c92ba89dcaacf3993572bc179bdd5 Mon Sep 17 00:00:00 2001 From: mavrick Date: Sun, 1 Nov 2026 21:13:27 -0600 Subject: [PATCH 06/12] fix(analysis): judge Tabulate Intersection's coverage within the overlay's rounding MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The overlay rounds a cut part to a grid scaled to its operands' extent, while the whole feature was measured unrounded and compared with a fixed relative tolerance of 1e-6. A 10 m feature inside a 1° zone then got a false "partly outside" notice in 80 of 200 positions, its share up to 1.7e-5 short. overlay_rounding now gives the rounding the overlay's grid allows for a feature's perimeter, relative to its area. A part within it of the whole feature counts as the whole (share 1, area of the whole), and coverage is judged with the same tolerance. - Name a zone by its values in the union error, not Rust debug output. - Format the latitude limit in its notice from MAX_LAT. - Tests: small features inside and across zones of half a degree, and a zone reaching beyond the latitude limit. Co-Authored-By: Claude Opus 5.5 --- crates/analysis/src/tools.rs | 65 ++++++++++++++----- .../analysis/tests/tabulate_intersection.rs | 42 +++++++++++- docs/user-guide/analysis.md | 12 ++-- 3 files changed, 98 insertions(+), 21 deletions(-) diff --git a/crates/analysis/src/tools.rs b/crates/analysis/src/tools.rs index 7a91cb58c1..fe2a4956ff 100644 --- a/crates/analysis/src/tools.rs +++ b/crates/analysis/src/tools.rs @@ -2821,9 +2821,9 @@ fn ground_area_perimeter(g: &Geometry) -> (f64, f64) { /// The area (square metres, holes taken out) of a lon/lat polygon geometry on a sphere of the /// Earth's radius, as the map draws it: each edge a straight line in Web Mercator, which is a rhumb /// line, with longitudes as they are (not folded across the antimeridian) and latitudes clamped to -/// the map's limit, as the overlay takes them. A polygon cut along -/// any straight line on the map splits this area exactly, up to rounding, so the parts' areas add -/// up to the whole's. Zero for any other geometry. +/// the map's limit, as the overlay takes them. A polygon cut along any straight line on the map +/// splits this area exactly, so the parts' areas add up to the whole's, up to the overlay's +/// rounding of the cut ([`overlay_rounding`]). Zero for any other geometry. fn map_area_m2(g: &Geometry) -> f64 { let Geometry::Polygon(polys) = g else { return 0.0 }; let r2 = rustgis_geom::EARTH_RADIUS_M * rustgis_geom::EARTH_RADIUS_M; @@ -2856,6 +2856,20 @@ fn rhumb_ring_area(ring: &[Coord]) -> f64 { total.abs() } +/// How far the overlay's rounding can move the area of a feature cut by masks within `domain` (a +/// Web Mercator extent), relative to the feature's area. The overlay keeps 29 integer bits about the +/// centre of its operands' extent (see [`clip`]), so a vertex moves by up to half a grid step and +/// the area by up to the perimeter times a step; this allows four steps, and at least 1e-9. +fn overlay_rounding(g: &Geometry, domain: &Extent) -> f64 { + use geo::{Area, Euclidean, Length}; + let Some(mp) = to_multipolygon(g) else { return 1e-9 }; + let ext = domain.union(&merc_extent(&mp)); + let step = ext.width().max(ext.height()) / f64::from(1_u32 << 28); + let perimeter: f64 = mp.0.iter().flat_map(|p| std::iter::once(p.exterior()).chain(p.interiors())).map(|r| Euclidean.length(r)).sum(); + let area = mp.unsigned_area(); + if area > 0.0 && step.is_finite() { (4.0 * perimeter * step / area).max(1e-9) } else { 1e-9 } +} + /// Calculate Geometry Attributes: adds `area_km2` and `perimeter_km` to a polygon layer (see /// [`ground_area_perimeter`]), `length_km` to a line layer, and `point_x`/`point_y` (a label point) /// to any other, updating the layer in place. @@ -3196,6 +3210,8 @@ struct TabulateZone { ext: Extent, /// Its features' polygons in Web Mercator, unioned when there are several, as [`mask_of`] does. mask: MultiPolygon, + /// The Web Mercator extent of its mask, for [`overlay_rounding`]. + merc_ext: Extent, /// Its area in square metres as the map draws it ([`map_area_m2`]), overlaps between its /// features counted once. map_area_m2: f64, @@ -3223,7 +3239,8 @@ struct TabulateCell { /// percentages and shares compare areas measured as the map draws the polygons instead /// ([`map_area_m2`]): the overlay cuts along straight lines on the map, which that measure splits /// exactly and the ellipsoid's geodesic edges don't, so a feature's shares in zones that cover it -/// without overlapping each other add up to its whole value. +/// without overlapping each other add up to its whole value, up to the overlay's rounding: a part +/// within that rounding of the whole feature counts as the whole ([`overlay_rounding`]). fn tabulate_intersection(inp: &dyn Inputs, p: &Json) -> Result { let zones = input(inp, p, "zones")?; let classes = input(inp, p, "classes")?; @@ -3281,7 +3298,8 @@ fn tabulate_intersection(inp: &dyn Inputs, p: &Json) -> Result Result> = sum_fields.iter().map(|&f| classes.value(r, f).as_f64()).collect(); let mut whole_area: Option = None; + // The overlay's rounding of this feature's parts, relative to its area. + let mut rounding: Option = None; + let near_merc = near.iter().filter_map(|&zi| zone_list.get(zi)).fold(Extent::EMPTY, |e, z| e.union(&z.merc_ext)); let mut inside = false; // The part of the feature's area its shares took, over all zones, and with sum fields // and several zones near, its parts, for when overlapping zones make that sum misleading. @@ -3312,15 +3333,22 @@ fn tabulate_intersection(inp: &dyn Inputs, p: &Json) -> Result> = Vec::new(); let keep_parts = !sum_fields.is_empty() && near.len() > 1; for zi in near { - let Some(piece) = zone_list.get(zi).and_then(|z| part(&whole, &z.mask, true)) else { continue }; - let piece_area = map_area_m2(&piece); + let Some(mut piece) = zone_list.get(zi).and_then(|z| part(&whole, &z.mask, true)) else { continue }; + let mut piece_area = map_area_m2(&piece); if piece_area <= 0.0 || !piece_area.is_finite() { continue; } inside = true; + let total = *whole_area.get_or_insert_with(|| map_area_m2(&whole)); + let tolerance = *rounding.get_or_insert_with(|| overlay_rounding(&whole, &near_merc)); + // A part within the overlay's rounding of the whole feature is the whole: the + // feature lies inside the zone, and the cut only moved its vertices onto the grid. + if total > 0.0 && piece_area >= total * (1.0 - tolerance) { + piece = whole.as_ref().clone(); + piece_area = total; + } let cell = cells.entry((zi, ci)).or_insert_with(|| TabulateCell { parts: Vec::new(), sums: vec![0.0; sum_fields.len()] }); if !sum_fields.is_empty() { - let total = *whole_area.get_or_insert_with(|| map_area_m2(&whole)); // The part inside can come out a rounding error larger than the whole. let share = if total > 0.0 { (piece_area / total).min(1.0) } else { 0.0 }; shared += share; @@ -3341,15 +3369,17 @@ fn tabulate_intersection(inp: &dyn Inputs, p: &Json) -> Result 1) { - (Some(total), true) if total > 0.0 && shared >= 1.0 - 1e-6 => { + (Some(total), true) if total > 0.0 && shared >= 1.0 - tolerance => { from_multipolygon(&union_all(own_parts.iter().flat_map(|m| m.0.iter()))).map_or(0.0, |g| map_area_m2(&g)) / total } _ => shared, }; - // What zones cover is a rounding error short of the whole when they cover the feature. - if !sum_fields.is_empty() && covered < 1.0 - 1e-6 { + // What zones cover is within the overlay's rounding of the whole when they cover it. + if !sum_fields.is_empty() && covered < 1.0 - tolerance { outside += 1; } } @@ -3382,7 +3412,11 @@ fn tabulate_intersection(inp: &dyn Inputs, p: &Json) -> Result { let polys: Vec> = parts.iter().filter_map(to_multipolygon).collect(); let Some(g) = from_multipolygon(&union_all(polys.iter().flat_map(|m| m.0.iter()))) else { - return Err(format!("Tabulate Intersection: the parts of a class in the zone {:?} could not be combined", zone.key)); + let key: Vec = zone.key.iter().map(ToString::to_string).collect(); + return Err(format!( + "Tabulate Intersection: the parts of a class in the zone '{}' could not be combined", + key.join(", ") + )); }; union = g; &union @@ -3439,8 +3473,9 @@ fn tabulate_intersection(inp: &dyn Inputs, p: &Json) -> Result = HashMap::new(); + for f in &table(result).features { + let (Some(Value::Int(id)), Some(pop)) = (f.attrs.get(1), f.attrs.get(4).and_then(Value::as_f64)) else { panic!("{:?}", f.attrs) }; + *shared.entry(*id).or_default() += pop; + } + for (id, pop) in shared { + if id < 20 { + assert_eq!(pop, 1_000_000.0, "feature {id} wholly inside A"); + } else { + assert!((pop / 1_000_000.0 - 1.0).abs() < 1e-3, "feature {id} across the border shares {pop}"); + } + } +} + #[test] fn zones_sharing_a_value_are_one_zone() { let mut z = zones(); diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index ad50ef03f7..538a714667 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -582,11 +582,13 @@ be shared out more than once; the value of a feature's part outside every zone i `area_km2` is measured on the ellipsoid, as Calculate Geometry Attributes measures it. The percentages and shares compare areas measured on a sphere with each edge as the map draws it (a straight line on the map), the lines the tool cuts along, so the shares of a feature that zones -cover without overlapping each other add up to its whole value. The percentages of classes that -overlap each other can add up to more than 100. Like the other overlay tools, it works on the map, -which ends at 85.05° north and south: parts of polygons beyond that are taken as lying along it, so -overlaps there have no area ([#1033](https://github.com/opengeos/RustGIS/issues/1033)); the tool -says how many features reach beyond it. +cover without overlapping each other add up to its whole value, up to the overlay's rounding of the +cut (a few billionths of the zones' size per vertex); a feature wholly inside a zone counts whole. +The percentages of classes that overlap each other can add up to more than 100. Like the other +overlay tools, it works on the map, which ends at 85.05° north and south: parts of polygons beyond +that are taken as lying along it, so overlaps there have no area +([#1033](https://github.com/opengeos/RustGIS/issues/1033)); the tool says how many features reach +beyond it. The tool says how many zone and class features have no polygon (no geometry, an empty one, or a line or point; they are left out), how many zones overlap no class feature and so have no rows, how many From e89a12db48b2c122dc2665d7c7fc5fa7797b9781 Mon Sep 17 00:00:00 2001 From: mavrick Date: Sun, 1 Nov 2026 22:01:00 -0600 Subject: [PATCH 07/12] fix(analysis): cap Tabulate Intersection's rounding tolerance at 1e-3 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit overlay_rounding had only a floor, so for a feature thin next to its zones' extent (1 cm by 2°) it reached about 0.6, and a part half outside the zone counted as the whole: its value went to the zone in full and the outside notice was hidden. Clamp it to at most 1e-3, so so thin a feature is measured as cut and a part outside is reported, never taken as inside. Co-Authored-By: Claude Opus 5.5 --- crates/analysis/src/tools.rs | 6 +++-- .../analysis/tests/tabulate_intersection.rs | 24 +++++++++++++++++++ 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/crates/analysis/src/tools.rs b/crates/analysis/src/tools.rs index fe2a4956ff..6842a1fbd5 100644 --- a/crates/analysis/src/tools.rs +++ b/crates/analysis/src/tools.rs @@ -2859,7 +2859,9 @@ fn rhumb_ring_area(ring: &[Coord]) -> f64 { /// How far the overlay's rounding can move the area of a feature cut by masks within `domain` (a /// Web Mercator extent), relative to the feature's area. The overlay keeps 29 integer bits about the /// centre of its operands' extent (see [`clip`]), so a vertex moves by up to half a grid step and -/// the area by up to the perimeter times a step; this allows four steps, and at least 1e-9. +/// the area by up to the perimeter times a step; this allows four steps, at least 1e-9 and at most +/// 1e-3. A feature so thin that the overlay rounds it by more than that is measured as cut, so a +/// part of it outside its zones is never taken as inside, at worst reported as outside. fn overlay_rounding(g: &Geometry, domain: &Extent) -> f64 { use geo::{Area, Euclidean, Length}; let Some(mp) = to_multipolygon(g) else { return 1e-9 }; @@ -2867,7 +2869,7 @@ fn overlay_rounding(g: &Geometry, domain: &Extent) -> f64 { let step = ext.width().max(ext.height()) / f64::from(1_u32 << 28); let perimeter: f64 = mp.0.iter().flat_map(|p| std::iter::once(p.exterior()).chain(p.interiors())).map(|r| Euclidean.length(r)).sum(); let area = mp.unsigned_area(); - if area > 0.0 && step.is_finite() { (4.0 * perimeter * step / area).max(1e-9) } else { 1e-9 } + if area > 0.0 && step.is_finite() { (4.0 * perimeter * step / area).clamp(1e-9, 1e-3) } else { 1e-9 } } /// Calculate Geometry Attributes: adds `area_km2` and `perimeter_km` to a polygon layer (see diff --git a/crates/analysis/tests/tabulate_intersection.rs b/crates/analysis/tests/tabulate_intersection.rs index af5469a29c..219d0f97a5 100644 --- a/crates/analysis/tests/tabulate_intersection.rs +++ b/crates/analysis/tests/tabulate_intersection.rs @@ -325,6 +325,30 @@ fn small_features_in_large_zones_share_out_in_full() { } } +/// A strip about 1 cm wide and 2° long, half inside a zone: the overlay's rounding of so thin a +/// feature is large next to its area, but its half outside still isn't counted as inside. +#[test] +fn a_thin_strip_half_outside_a_zone_shares_out_half() { + let rect = |x0: f64, y0: f64, x1: f64, y1: f64| { + let ring = [(x0, y0), (x1, y0), (x1, y1), (x0, y1), (x0, y0)].map(|(x, y)| Coord::new(x, y)).to_vec(); + Some(Geometry::Polygon(vec![vec![ring]])) + }; + let mut z = Dataset::new("zones", GeometryType::Polygon, vec![Field::new("zone", FieldType::Text)]); + z.push_next(rect(-91.0, 34.0, -90.0, 36.0), vec![Value::Text("A".into())]); + let mut c = Dataset::new("classes", GeometryType::Polygon, vec![Field::new("pop", FieldType::Integer)]); + c.push_next(rect(-91.0, 35.0, -89.0, 35.0000001), vec![Value::Int(1_000_000)]); + let l = layers(z, c); + let params = json!({"zones": "zones", "zoneFields": "zone", "classes": "classes", "sumFields": "pop"}); + let result = rustgis_analysis::run("tabulateIntersection", &l, ¶ms).unwrap(); + assert_eq!( + result.messages, + ["Tabulate Intersection: 1 row", "1 class feature lies partly or wholly outside the zones: its value outside isn't shared out"] + ); + let pop = table(result).features.first().and_then(|f| f.attrs.get(3)).and_then(Value::as_f64).unwrap(); + // About half: so thin a strip is rounded by about a percent, but not taken as wholly inside. + assert!((pop / 500_000.0 - 1.0).abs() < 0.05, "{pop}"); +} + #[test] fn zones_sharing_a_value_are_one_zone() { let mut z = zones(); From 2903561e0c0729de4bcba36fc304994db7c8695c Mon Sep 17 00:00:00 2001 From: mavrick Date: Sun, 1 Nov 2026 23:11:15 -0600 Subject: [PATCH 08/12] fix(analysis): decide Tabulate Intersection's coverage from what lies outside An area tolerance can't tell rounding from a real part outside: capped, it absorbed slivers up to 0.1% outside and flagged a thin feature wholly inside; with separate thresholds for a part counting whole (1x) and the outside notice (2x), a 10 m parcel 0.15% across an edge got a short share and no notice; and the bound was 8x looser than the grid. OverlayGrid now gives the overlay's grid step (the extent of a feature and its zones over 2^30) and the rounding it allows. A part is the whole feature when what lies outside its zone is nothing or no wider than the grid (area over perimeter against the step). A feature is reported as partly outside when what is left after taking its zones away in turn is wider than the grid, so overlapping zones can't hide such a part. Tests: a 10 m parcel 0.15% across a zone edge is reported; a strip 1 cm wide counts whole inside a zone and half when half outside. Co-Authored-By: Claude Opus 5.5 --- crates/analysis/src/tools.rs | 118 +++++++++++------- .../analysis/tests/tabulate_intersection.rs | 39 +++++- docs/user-guide/analysis.md | 13 +- 3 files changed, 115 insertions(+), 55 deletions(-) diff --git a/crates/analysis/src/tools.rs b/crates/analysis/src/tools.rs index 6842a1fbd5..acf10cace8 100644 --- a/crates/analysis/src/tools.rs +++ b/crates/analysis/src/tools.rs @@ -2823,7 +2823,7 @@ fn ground_area_perimeter(g: &Geometry) -> (f64, f64) { /// line, with longitudes as they are (not folded across the antimeridian) and latitudes clamped to /// the map's limit, as the overlay takes them. A polygon cut along any straight line on the map /// splits this area exactly, so the parts' areas add up to the whole's, up to the overlay's -/// rounding of the cut ([`overlay_rounding`]). Zero for any other geometry. +/// rounding of the cut ([`OverlayGrid`]). Zero for any other geometry. fn map_area_m2(g: &Geometry) -> f64 { let Geometry::Polygon(polys) = g else { return 0.0 }; let r2 = rustgis_geom::EARTH_RADIUS_M * rustgis_geom::EARTH_RADIUS_M; @@ -2856,20 +2856,45 @@ fn rhumb_ring_area(ring: &[Coord]) -> f64 { total.abs() } -/// How far the overlay's rounding can move the area of a feature cut by masks within `domain` (a -/// Web Mercator extent), relative to the feature's area. The overlay keeps 29 integer bits about the -/// centre of its operands' extent (see [`clip`]), so a vertex moves by up to half a grid step and -/// the area by up to the perimeter times a step; this allows four steps, at least 1e-9 and at most -/// 1e-3. A feature so thin that the overlay rounds it by more than that is measured as cut, so a -/// part of it outside its zones is never taken as inside, at worst reported as outside. -fn overlay_rounding(g: &Geometry, domain: &Extent) -> f64 { +/// The overlay's grid for a feature cut by masks within a Web Mercator extent. The overlay keeps 29 +/// integer bits about the centre of its operands' extent (see [`clip`]), a grid step of the extent +/// over 2^30, so it moves each vertex by less than a step: the area by less than the perimeter times +/// a step, and a sliver it leaves along an edge is no wider than a step. +struct OverlayGrid { + /// The grid step, in Web Mercator metres, taken over the feature and all its masks. + step: f64, + /// How far rounding can move the feature's area, relative to it: twice the perimeter times the + /// step over the area, from 1e-9 to 1. A part closer than this to the whole may be the whole. + rounding: f64, +} + +impl OverlayGrid { + /// The grid for the polygon feature `g` cut by masks within `domain`. + fn new(g: &Geometry, domain: &Extent) -> Self { + let mp = to_multipolygon(g).unwrap_or_else(|| MultiPolygon::new(vec![])); + let ext = domain.union(&merc_extent(&mp)); + let step = ext.width().max(ext.height()) / f64::from(1_u32 << 30); + let (area, perimeter) = merc_area_perimeter(&mp); + let rounding = if area > 0.0 && step.is_finite() { (2.0 * perimeter * step / area).clamp(1e-9, 1.0) } else { 1e-9 }; + OverlayGrid { step: if step.is_finite() { step } else { 0.0 }, rounding } + } + + /// Whether a polygon part is wider on average (its area over its perimeter) than the grid step: + /// more than the slivers rounding leaves along an edge, which are at most a step wide and so + /// half a step on average. + fn wider(&self, g: &Geometry) -> bool { + to_multipolygon(g).is_some_and(|mp| { + let (area, perimeter) = merc_area_perimeter(&mp); + area > perimeter * self.step + }) + } +} + +/// The planar area and perimeter (holes included) of polygons in Web Mercator metres. +fn merc_area_perimeter(mp: &MultiPolygon) -> (f64, f64) { use geo::{Area, Euclidean, Length}; - let Some(mp) = to_multipolygon(g) else { return 1e-9 }; - let ext = domain.union(&merc_extent(&mp)); - let step = ext.width().max(ext.height()) / f64::from(1_u32 << 28); - let perimeter: f64 = mp.0.iter().flat_map(|p| std::iter::once(p.exterior()).chain(p.interiors())).map(|r| Euclidean.length(r)).sum(); - let area = mp.unsigned_area(); - if area > 0.0 && step.is_finite() { (4.0 * perimeter * step / area).clamp(1e-9, 1e-3) } else { 1e-9 } + let perimeter = mp.0.iter().flat_map(|p| std::iter::once(p.exterior()).chain(p.interiors())).map(|r| Euclidean.length(r)).sum(); + (mp.unsigned_area(), perimeter) } /// Calculate Geometry Attributes: adds `area_km2` and `perimeter_km` to a polygon layer (see @@ -3212,7 +3237,7 @@ struct TabulateZone { ext: Extent, /// Its features' polygons in Web Mercator, unioned when there are several, as [`mask_of`] does. mask: MultiPolygon, - /// The Web Mercator extent of its mask, for [`overlay_rounding`]. + /// The Web Mercator extent of its mask, for [`OverlayGrid`]. merc_ext: Extent, /// Its area in square metres as the map draws it ([`map_area_m2`]), overlaps between its /// features counted once. @@ -3242,7 +3267,7 @@ struct TabulateCell { /// ([`map_area_m2`]): the overlay cuts along straight lines on the map, which that measure splits /// exactly and the ellipsoid's geodesic edges don't, so a feature's shares in zones that cover it /// without overlapping each other add up to its whole value, up to the overlay's rounding: a part -/// within that rounding of the whole feature counts as the whole ([`overlay_rounding`]). +/// that leaves nothing outside its zone wider than the overlay's grid is the whole ([`OverlayGrid`]). fn tabulate_intersection(inp: &dyn Inputs, p: &Json) -> Result { let zones = input(inp, p, "zones")?; let classes = input(inp, p, "classes")?; @@ -3325,44 +3350,44 @@ fn tabulate_intersection(inp: &dyn Inputs, p: &Json) -> Result> = sum_fields.iter().map(|&f| classes.value(r, f).as_f64()).collect(); let mut whole_area: Option = None; - // The overlay's rounding of this feature's parts, relative to its area. - let mut rounding: Option = None; + // The overlay's grid for this feature and its zones, and how far rounding can move the + // feature's area relative to it: see [`OverlayGrid`]. let near_merc = near.iter().filter_map(|&zi| zone_list.get(zi)).fold(Extent::EMPTY, |e, z| e.union(&z.merc_ext)); + let mut grid: Option = None; let mut inside = false; - // The part of the feature's area its shares took, over all zones, and with sum fields - // and several zones near, its parts, for when overlapping zones make that sum misleading. - let mut shared = 0.0; - let mut own_parts: Vec> = Vec::new(); - let keep_parts = !sum_fields.is_empty() && near.len() > 1; - for zi in near { - let Some(mut piece) = zone_list.get(zi).and_then(|z| part(&whole, &z.mask, true)) else { continue }; + // Whether one zone holds the whole feature, so none of it lies outside them all. + let mut held = false; + for &zi in &near { + let Some(zone) = zone_list.get(zi) else { continue }; + let Some(mut piece) = part(&whole, &zone.mask, true) else { continue }; let mut piece_area = map_area_m2(&piece); if piece_area <= 0.0 || !piece_area.is_finite() { continue; } inside = true; let total = *whole_area.get_or_insert_with(|| map_area_m2(&whole)); - let tolerance = *rounding.get_or_insert_with(|| overlay_rounding(&whole, &near_merc)); - // A part within the overlay's rounding of the whole feature is the whole: the - // feature lies inside the zone, and the cut only moved its vertices onto the grid. - if total > 0.0 && piece_area >= total * (1.0 - tolerance) { + let grid = grid.get_or_insert_with(|| OverlayGrid::new(&whole, &near_merc)); + // A part within the overlay's rounding of the whole may be the whole feature, the cut + // only moving its vertices onto the grid: it is when what lies outside the zone, if + // anything, is no wider than the grid. Then the part is the whole, unrounded. + if total > 0.0 + && piece_area >= total * (1.0 - grid.rounding) + && part(&whole, &zone.mask, false).is_none_or(|rest| !grid.wider(&rest)) + { piece = whole.as_ref().clone(); piece_area = total; + held = true; } let cell = cells.entry((zi, ci)).or_insert_with(|| TabulateCell { parts: Vec::new(), sums: vec![0.0; sum_fields.len()] }); if !sum_fields.is_empty() { // The part inside can come out a rounding error larger than the whole. let share = if total > 0.0 { (piece_area / total).min(1.0) } else { 0.0 }; - shared += share; for (sum, v) in cell.sums.iter_mut().zip(&values) { if let Some(v) = v { *sum += v * share; } } } - if keep_parts { - own_parts.extend(to_multipolygon(&piece)); - } cell.parts.push(piece); } if inside { @@ -3370,19 +3395,20 @@ fn tabulate_intersection(inp: &dyn Inputs, p: &Json) -> Result 1) { - (Some(total), true) if total > 0.0 && shared >= 1.0 - tolerance => { - from_multipolygon(&union_all(own_parts.iter().flat_map(|m| m.0.iter()))).map_or(0.0, |g| map_area_m2(&g)) / total - } - _ => shared, - }; - // What zones cover is within the overlay's rounding of the whole when they cover it. - if !sum_fields.is_empty() && covered < 1.0 - tolerance { - outside += 1; + // With sum fields, a feature none of whose value is shared out, or with a part outside + // every zone wider than the overlay's grid, isn't wholly shared out: what is left of it + // once each zone near it is taken away in turn. Zones that overlap each other can't hide + // such a part, as shares adding up to the whole could. + if !sum_fields.is_empty() && !held { + let lies_outside = !inside || { + let grid = grid.get_or_insert_with(|| OverlayGrid::new(&whole, &near_merc)); + let mut rest = Some(whole.as_ref().clone()); + for zone in near.iter().filter_map(|&zi| zone_list.get(zi)) { + rest = rest.and_then(|r| part(&r, &zone.mask, false)); + } + rest.is_some_and(|r| grid.wider(&r)) + }; + outside += usize::from(lies_outside); } } } diff --git a/crates/analysis/tests/tabulate_intersection.rs b/crates/analysis/tests/tabulate_intersection.rs index 219d0f97a5..be71472044 100644 --- a/crates/analysis/tests/tabulate_intersection.rs +++ b/crates/analysis/tests/tabulate_intersection.rs @@ -325,10 +325,11 @@ fn small_features_in_large_zones_share_out_in_full() { } } -/// A strip about 1 cm wide and 2° long, half inside a zone: the overlay's rounding of so thin a -/// feature is large next to its area, but its half outside still isn't counted as inside. +/// A strip about 1 cm wide and 2° long: the overlay's rounding of so thin a feature is large next to +/// its area, yet half outside a zone it is reported and shares out half, and wholly inside one it +/// counts whole. #[test] -fn a_thin_strip_half_outside_a_zone_shares_out_half() { +fn a_thin_strip_shares_out_half_when_half_outside_and_all_when_inside() { let rect = |x0: f64, y0: f64, x1: f64, y1: f64| { let ring = [(x0, y0), (x1, y0), (x1, y1), (x0, y1), (x0, y0)].map(|(x, y)| Coord::new(x, y)).to_vec(); Some(Geometry::Polygon(vec![vec![ring]])) @@ -347,6 +348,38 @@ fn a_thin_strip_half_outside_a_zone_shares_out_half() { let pop = table(result).features.first().and_then(|f| f.attrs.get(3)).and_then(Value::as_f64).unwrap(); // About half: so thin a strip is rounded by about a percent, but not taken as wholly inside. assert!((pop / 500_000.0 - 1.0).abs() < 0.05, "{pop}"); + + // The same strip wholly inside the zone counts whole, unrounded, with no notice. + let mut z = Dataset::new("zones", GeometryType::Polygon, vec![Field::new("zone", FieldType::Text)]); + z.push_next(rect(-91.0, 34.0, -88.0, 36.0), vec![Value::Text("A".into())]); + let mut c = Dataset::new("classes", GeometryType::Polygon, vec![Field::new("pop", FieldType::Integer)]); + c.push_next(rect(-90.5, 35.0, -88.5, 35.0000001), vec![Value::Int(1_000_000)]); + let result = rustgis_analysis::run("tabulateIntersection", &layers(z, c), ¶ms).unwrap(); + assert_eq!(result.messages, ["Tabulate Intersection: 1 row"]); + let pop = table(result).features.first().and_then(|f| f.attrs.get(3)).and_then(Value::as_f64).unwrap(); + assert_eq!(pop, 1_000_000.0); +} + +/// A feature of about 10 m in a zone 10° wide, with 0.15% of its area across the zone's edge: more +/// than the overlay's rounding of it, so it is reported as partly outside rather than counted whole. +#[test] +fn a_small_feature_just_across_a_zone_edge_is_reported() { + let rect = |x0: f64, y0: f64, x1: f64, y1: f64| { + let ring = [(x0, y0), (x1, y0), (x1, y1), (x0, y1), (x0, y0)].map(|(x, y)| Coord::new(x, y)).to_vec(); + Some(Geometry::Polygon(vec![vec![ring]])) + }; + let mut z = Dataset::new("zones", GeometryType::Polygon, vec![Field::new("zone", FieldType::Text)]); + z.push_next(rect(-100.0, 30.0, -90.0, 40.0), vec![Value::Text("A".into())]); + let mut c = Dataset::new("classes", GeometryType::Polygon, vec![Field::new("pop", FieldType::Integer)]); + let (side, across) = (0.00009, 0.00009 * 0.0015); + c.push_next(rect(-90.0 - side + across, 35.0, -90.0 + across, 35.0 + side), vec![Value::Int(1_000_000)]); + let l = layers(z, c); + let params = json!({"zones": "zones", "zoneFields": "zone", "classes": "classes", "sumFields": "pop"}); + let result = rustgis_analysis::run("tabulateIntersection", &l, ¶ms).unwrap(); + assert_eq!( + result.messages, + ["Tabulate Intersection: 1 row", "1 class feature lies partly or wholly outside the zones: its value outside isn't shared out"] + ); } #[test] diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index 538a714667..6e84b1071c 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -583,12 +583,13 @@ be shared out more than once; the value of a feature's part outside every zone i percentages and shares compare areas measured on a sphere with each edge as the map draws it (a straight line on the map), the lines the tool cuts along, so the shares of a feature that zones cover without overlapping each other add up to its whole value, up to the overlay's rounding of the -cut (a few billionths of the zones' size per vertex); a feature wholly inside a zone counts whole. -The percentages of classes that overlap each other can add up to more than 100. Like the other -overlay tools, it works on the map, which ends at 85.05° north and south: parts of polygons beyond -that are taken as lying along it, so overlaps there have no area -([#1033](https://github.com/opengeos/RustGIS/issues/1033)); the tool says how many features reach -beyond it. +cut. The overlay rounds coordinates to a grid (the size of the zones near a feature over about a +billion), so a part that leaves nothing outside its zone wider than that grid is the whole feature, +and only parts outside every zone wider than the grid are reported. The percentages of classes that +overlap each other can add up to more than 100. Like the other overlay tools, it works on the map, +which ends at 85.05° north and south: parts of polygons beyond that are taken as lying along it, so +overlaps there have no area ([#1033](https://github.com/opengeos/RustGIS/issues/1033)); the tool +says how many features reach beyond it. The tool says how many zone and class features have no polygon (no geometry, an empty one, or a line or point; they are left out), how many zones overlap no class feature and so have no rows, how many From 4a738c5604e6ab41c6a0325708b01f3b8d26c424 Mon Sep 17 00:00:00 2001 From: mavrick Date: Mon, 2 Nov 2026 00:52:51 -0600 Subject: [PATCH 09/12] fix(analysis): never take a part as whole where the grid can't resolve the feature MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A feature so narrow next to its zones that the overlay's rounding can move its area by more than 1% was taken as whole in each zone it straddled when what lay outside was as narrow as itself: slivers 1 to 2 mm wide across two zones 5° wide shared out twice their value, and strips 3 to 5 mm wide came out 4% to 20% short, both without a notice. - A part is the whole only when nothing lies outside its zone, or the grid resolves the feature (rounding of at most 1%) and nothing wider than the grid lies outside. Features it doesn't resolve get a notice that their parts are measured only roughly. - Judge a part's width as twice its area over its perimeter, its average width, against the grid step. - Judge a part against the grid of its own zone, so a wide zone nearby doesn't coarsen it. - Take what lies outside from one union of the zones near a feature, cached for neighbours, rather than cutting by each zone in turn. - Tests: slivers 0.5 to 5 mm wide across two zones; the share of a feature just across a zone edge. Co-Authored-By: Claude Opus 5.5 --- crates/analysis/src/tools.rs | 77 ++++++++++++++----- .../analysis/tests/tabulate_intersection.rs | 35 ++++++++- docs/user-guide/analysis.md | 8 +- 3 files changed, 98 insertions(+), 22 deletions(-) diff --git a/crates/analysis/src/tools.rs b/crates/analysis/src/tools.rs index acf10cace8..57b282c386 100644 --- a/crates/analysis/src/tools.rs +++ b/crates/analysis/src/tools.rs @@ -2879,13 +2879,18 @@ impl OverlayGrid { OverlayGrid { step: if step.is_finite() { step } else { 0.0 }, rounding } } - /// Whether a polygon part is wider on average (its area over its perimeter) than the grid step: - /// more than the slivers rounding leaves along an edge, which are at most a step wide and so - /// half a step on average. + /// Whether the grid measures the feature finely: rounding can move its area by at most 1%. + fn resolves(&self) -> bool { + self.rounding <= 0.01 + } + + /// Whether a polygon part is wider on average than the grid step: more than the slivers + /// rounding leaves along an edge, which are less than a step wide. A part's average width is + /// twice its area over its perimeter (a long strip's perimeter is twice its length). fn wider(&self, g: &Geometry) -> bool { to_multipolygon(g).is_some_and(|mp| { let (area, perimeter) = merc_area_perimeter(&mp); - area > perimeter * self.step + 2.0 * area > perimeter * self.step }) } } @@ -3336,6 +3341,13 @@ fn tabulate_intersection(inp: &dyn Inputs, p: &Json) -> Result, MultiPolygon)> = std::collections::VecDeque::new(); for (ci, group) in class_groups.iter().enumerate() { for &r in &group.rows { let Some(g) = classes.features.get(r).and_then(|f| f.geometry.as_ref()).filter(|g| has_shape(g)) else { continue }; @@ -3350,8 +3362,8 @@ fn tabulate_intersection(inp: &dyn Inputs, p: &Json) -> Result> = sum_fields.iter().map(|&f| classes.value(r, f).as_f64()).collect(); let mut whole_area: Option = None; - // The overlay's grid for this feature and its zones, and how far rounding can move the - // feature's area relative to it: see [`OverlayGrid`]. + // The overlay's grid for this feature and all the zones near it, for the outside check, + // which cuts it by their union: see [`OverlayGrid`]. let near_merc = near.iter().filter_map(|&zi| zone_list.get(zi)).fold(Extent::EMPTY, |e, z| e.union(&z.merc_ext)); let mut grid: Option = None; let mut inside = false; @@ -3366,13 +3378,16 @@ fn tabulate_intersection(inp: &dyn Inputs, p: &Json) -> Result 0.0 - && piece_area >= total * (1.0 - grid.rounding) - && part(&whole, &zone.mask, false).is_none_or(|rest| !grid.wider(&rest)) + && piece_area >= total * (1.0 - zone_grid.rounding) + && part(&whole, &zone.mask, false).is_none_or(|rest| zone_grid.resolves() && !zone_grid.wider(&rest)) { piece = whole.as_ref().clone(); piece_area = total; @@ -3397,15 +3412,31 @@ fn tabulate_intersection(inp: &dyn Inputs, p: &Json) -> Result Result {} + 1 => messages.push( + "1 class feature is so narrow next to its zones that the overlay's rounding can move its area by more than 1%: its parts are measured only roughly" + .into(), + ), + n => messages.push(format!( + "{n} class features are so narrow next to their zones that the overlay's rounding can move their areas by more than 1%: their parts are measured only roughly" + )), + } match outside { 0 => {} 1 => messages.push("1 class feature lies partly or wholly outside the zones: its value outside isn't shared out".into()), diff --git a/crates/analysis/tests/tabulate_intersection.rs b/crates/analysis/tests/tabulate_intersection.rs index be71472044..532aa91aea 100644 --- a/crates/analysis/tests/tabulate_intersection.rs +++ b/crates/analysis/tests/tabulate_intersection.rs @@ -341,9 +341,14 @@ fn a_thin_strip_shares_out_half_when_half_outside_and_all_when_inside() { let l = layers(z, c); let params = json!({"zones": "zones", "zoneFields": "zone", "classes": "classes", "sumFields": "pop"}); let result = rustgis_analysis::run("tabulateIntersection", &l, ¶ms).unwrap(); + // Half outside, and so thin that rounding moves its area by more than 1%: both are said. assert_eq!( result.messages, - ["Tabulate Intersection: 1 row", "1 class feature lies partly or wholly outside the zones: its value outside isn't shared out"] + [ + "Tabulate Intersection: 1 row", + "1 class feature is so narrow next to its zones that the overlay's rounding can move its area by more than 1%: its parts are measured only roughly", + "1 class feature lies partly or wholly outside the zones: its value outside isn't shared out", + ] ); let pop = table(result).features.first().and_then(|f| f.attrs.get(3)).and_then(Value::as_f64).unwrap(); // About half: so thin a strip is rounded by about a percent, but not taken as wholly inside. @@ -380,6 +385,34 @@ fn a_small_feature_just_across_a_zone_edge_is_reported() { result.messages, ["Tabulate Intersection: 1 row", "1 class feature lies partly or wholly outside the zones: its value outside isn't shared out"] ); + // The 99.85% inside the zone. + let pop = table(result).features.first().and_then(|f| f.attrs.get(3)).and_then(Value::as_f64).unwrap(); + assert!((pop / 998_500.0 - 1.0).abs() < 1e-4, "{pop}"); +} + +/// Slivers 1 m long and 0.5 to 5 mm wide across the border of two zones 5° wide, so narrow that +/// the overlay's rounding moves their areas by more than 1%: never taken as whole in both zones, +/// and a notice says they are measured only roughly. +#[test] +fn slivers_too_narrow_to_measure_finely_are_reported_not_counted_twice() { + let rect = |x0: f64, y0: f64, x1: f64, y1: f64| { + let ring = [(x0, y0), (x1, y0), (x1, y1), (x0, y1), (x0, y0)].map(|(x, y)| Coord::new(x, y)).to_vec(); + Some(Geometry::Polygon(vec![vec![ring]])) + }; + let mut z = Dataset::new("zones", GeometryType::Polygon, vec![Field::new("zone", FieldType::Text)]); + z.push_next(rect(-100.0, 30.0, -95.0, 40.0), vec![Value::Text("A".into())]); + z.push_next(rect(-95.0, 30.0, -90.0, 40.0), vec![Value::Text("B".into())]); + let params = json!({"zones": "zones", "zoneFields": "zone", "classes": "classes", "sumFields": "pop"}); + // From 0.5 mm wide, about half a grid step there, to 5 mm. + for width_m in [0.0005, 0.001, 0.002, 0.003, 0.005] { + let mut c = Dataset::new("classes", GeometryType::Polygon, vec![Field::new("pop", FieldType::Integer)]); + c.push_next(rect(-95.0000045, 35.0, -94.9999955, 35.0 + width_m / 111_000.0), vec![Value::Int(1_000_000)]); + let result = rustgis_analysis::run("tabulateIntersection", &layers(z.clone(), c), ¶ms).unwrap(); + let rough = result.messages.iter().any(|m| m.starts_with("1 class feature is so narrow next to its zones")); + assert!(rough, "{width_m} m: {:?}", result.messages); + let total: f64 = table(result).features.iter().filter_map(|f| f.attrs.get(3).and_then(Value::as_f64)).sum(); + assert!(total <= 1_000_000.0 * 1.01, "{width_m} m wide shared out {total}"); + } } #[test] diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index 6e84b1071c..6b921612f6 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -585,9 +585,11 @@ straight line on the map), the lines the tool cuts along, so the shares of a fea cover without overlapping each other add up to its whole value, up to the overlay's rounding of the cut. The overlay rounds coordinates to a grid (the size of the zones near a feature over about a billion), so a part that leaves nothing outside its zone wider than that grid is the whole feature, -and only parts outside every zone wider than the grid are reported. The percentages of classes that -overlap each other can add up to more than 100. Like the other overlay tools, it works on the map, -which ends at 85.05° north and south: parts of polygons beyond that are taken as lying along it, so +and only parts outside every zone wider than the grid are reported. A feature so narrow next to its +zones that the rounding can move its area by more than 1% is measured only roughly, unless it lies +wholly inside a zone, and the tool says how many there are. The percentages of classes that overlap +each other can add up to more than 100. Like the other overlay tools, it works on the map, which +ends at 85.05° north and south: parts of polygons beyond that are taken as lying along it, so overlaps there have no area ([#1033](https://github.com/opengeos/RustGIS/issues/1033)); the tool says how many features reach beyond it. From 23c9506e87c7bbb0def803dacd1b8ccc07d49d17 Mon Sep 17 00:00:00 2001 From: mavrick Date: Mon, 2 Nov 2026 01:40:15 -0600 Subject: [PATCH 10/12] fix(analysis): report rough parts only of features that meet a zone, in every zone - Decide whether a class feature's interior meets a zone's by the exact predicate, not its extent: a thin feature near a zone only by its extent no longer gets the "measured only roughly" notice, and lies wholly outside; one that meets a zone but has no part surviving the cut gets that notice. - Count a feature as roughly measured when any zone got a part of it as cut, even if another zone holds it whole. - Tests: a thin feature in the notch of an L-shaped zone; a thin strip whole in one zone and cut by another overlapping it. Co-Authored-By: Claude Opus 5.5 --- crates/analysis/src/tools.rs | 26 +++++++++++++++---- .../analysis/tests/tabulate_intersection.rs | 25 ++++++++++++++++++ 2 files changed, 46 insertions(+), 5 deletions(-) diff --git a/crates/analysis/src/tools.rs b/crates/analysis/src/tools.rs index 57b282c386..51d15c61ff 100644 --- a/crates/analysis/src/tools.rs +++ b/crates/analysis/src/tools.rs @@ -3367,8 +3367,10 @@ fn tabulate_intersection(inp: &dyn Inputs, p: &Json) -> Result = None; let mut inside = false; - // Whether one zone holds the whole feature, so none of it lies outside them all. + // Whether one zone holds the whole feature, so none of it lies outside them all; and + // whether a zone got a part of it as cut, rounded, not the whole. let mut held = false; + let mut cut_part = false; for &zi in &near { let Some(zone) = zone_list.get(zi) else { continue }; let Some(mut piece) = part(&whole, &zone.mask, true) else { continue }; @@ -3392,6 +3394,8 @@ fn tabulate_intersection(inp: &dyn Inputs, p: &Json) -> Result Result Date: Mon, 2 Nov 2026 02:35:15 -0600 Subject: [PATCH 11/12] fix(analysis): report collapsed rings, unsplit antimeridian rings and lost overlaps - A polygon with no area in longitude and latitude (a ring collapsed onto a line) has no polygon: it is counted with the features left out, rather than dropped silently. The area is taken from the ring's first vertex, so a sliver far from the origin keeps its precision. - Count zone and class features with a ring that jumps across the antimeridian unsplit, in one notice: the map, and so the percentages and shares, take them the long way round, while area_km2 takes their ground shape. - A feature the grid doesn't resolve counts as roughly measured when a zone meeting it loses its part to rounding, even if another zone holds it whole. The exact check runs only for such features. - Tests: a collapsed ring, a zone crossing the antimeridian unsplit, and each zone's share of a thin strip held whole by one zone and cut by another. Co-Authored-By: Claude Opus 5.5 --- crates/analysis/src/tools.rs | 64 ++++++++++++++++--- .../analysis/tests/tabulate_intersection.rs | 33 +++++++++- docs/user-guide/analysis.md | 13 ++-- 3 files changed, 96 insertions(+), 14 deletions(-) diff --git a/crates/analysis/src/tools.rs b/crates/analysis/src/tools.rs index 51d15c61ff..5f583f7702 100644 --- a/crates/analysis/src/tools.rs +++ b/crates/analysis/src/tools.rs @@ -2818,6 +2818,15 @@ fn ground_area_perimeter(g: &Geometry) -> (f64, f64) { (a, per) } +/// The area of a ring in square degrees of longitude and latitude, by the shoelace formula: zero +/// for a ring that has collapsed onto a line or point. Coordinates are taken from the first +/// vertex, so a ring far from the origin keeps the precision of its own size. +fn lonlat_ring_area(ring: &[Coord]) -> f64 { + let Some(o) = ring.first() else { return 0.0 }; + let d = |c: &Coord| (c.x - o.x, c.y - o.y); + (ring.iter().zip(ring.iter().cycle().skip(1)).map(|(a, b)| d(a).0 * d(b).1 - d(b).0 * d(a).1).sum::() / 2.0).abs() +} + /// The area (square metres, holes taken out) of a lon/lat polygon geometry on a sphere of the /// Earth's radius, as the map draws it: each edge a straight line in Web Mercator, which is a rhumb /// line, with longitudes as they are (not folded across the antimeridian) and latitudes clamped to @@ -3303,10 +3312,11 @@ fn tabulate_intersection(inp: &dyn Inputs, p: &Json) -> Result 0.0))); let shapeless = |ds: &Dataset, rs: &[usize]| { rs.iter().filter(|&&r| ds.features.get(r).and_then(|f| f.geometry.as_ref()).is_none_or(|g| !has_shape(g))).count() }; @@ -3322,6 +3332,18 @@ fn tabulate_intersection(inp: &dyn Inputs, p: &Json) -> Result 180.0) + })) + }; + rs.iter().filter(|&&r| ds.features.get(r).and_then(|f| f.geometry.as_ref()).is_some_and(jumps)).count() + }; + let (zones_unsplit, classes_unsplit) = (unsplit(zones, &zone_rows), unsplit(classes, &class_rows)); let zone_list: Vec = crate::stats::group_rows(zones, &zone_rows, &zone_keys) .into_iter() .map(|group| { @@ -3366,6 +3388,7 @@ fn tabulate_intersection(inp: &dyn Inputs, p: &Json) -> Result = None; + let resolved = grid.get_or_insert_with(|| OverlayGrid::new(&whole, &near_merc)).resolves(); let mut inside = false; // Whether one zone holds the whole feature, so none of it lies outside them all; and // whether a zone got a part of it as cut, rounded, not the whole. @@ -3373,9 +3396,23 @@ fn tabulate_intersection(inp: &dyn Inputs, p: &Json) -> Result Result Result = [(zones_unsplit, "zone"), (classes_unsplit, "class")] + .into_iter() + .filter(|(n, _)| *n > 0) + .map(|(n, layer)| features(n, layer)) + .collect(); + if !unsplit.is_empty() { + let verb = if zones_unsplit + classes_unsplit == 1 { "crosses" } else { "cross" }; + messages.push(format!( + "{} {verb} the antimeridian without being split there: the map draws them the long way round, and their percentages and shares follow the map, while area_km2 follows the ground", + unsplit.join(" and ") + )); + } match unresolved { 0 => {} 1 => messages.push( diff --git a/crates/analysis/tests/tabulate_intersection.rs b/crates/analysis/tests/tabulate_intersection.rs index 6105512514..fb754fb207 100644 --- a/crates/analysis/tests/tabulate_intersection.rs +++ b/crates/analysis/tests/tabulate_intersection.rs @@ -162,6 +162,9 @@ fn says_what_it_leaves_out() { c.push_next(None, vec![Value::Int(7)]); // A line in a polygon layer: it has geometry, but no polygon. c.push_next(Some(Geometry::Line(vec![vec![Coord::new(1.2, 0.2), Coord::new(1.8, 0.8)]])), vec![Value::Int(9)]); + // A ring collapsed onto a parallel inside B: a polygon with no area. + let collapsed = [(1.2, 0.5), (1.8, 0.5), (1.5, 0.5), (1.2, 0.5)].map(|(x, y)| Coord::new(x, y)).to_vec(); + c.push_next(Some(Geometry::Polygon(vec![vec![collapsed]])), vec![Value::Int(11)]); let l = layers(z, c); let params = json!({"zones": "zones", "zoneFields": "zone", "classes": "classes", "sumFields": "pop"}); let result = rustgis_analysis::run("tabulateIntersection", &l, ¶ms).unwrap(); @@ -170,7 +173,7 @@ fn says_what_it_leaves_out() { [ "Tabulate Intersection: 1 row", "2 zone features have no polygon and were left out", - "2 class features have no polygon and were left out", + "3 class features have no polygon and were left out", "2 zones overlap no class feature, so they have no rows", "1 class feature lies partly or wholly outside the zones: its value outside isn't shared out", ] @@ -363,6 +366,10 @@ fn a_thin_strip_shares_out_half_when_half_outside_and_all_when_inside() { c.push_next(rect(-90.5, 35.0, -88.5, 35.0000001), vec![Value::Int(1_000_000)]); let result = rustgis_analysis::run("tabulateIntersection", &layers(z, c), ¶ms).unwrap(); assert!(result.messages.iter().any(|m| m.starts_with("1 class feature is so narrow next to its zones")), "{:?}", result.messages); + // A holds it whole; B gets the half from 89.5°W, roughly measured. + let pops: Vec = table(result).features.iter().filter_map(|f| f.attrs.get(3).and_then(Value::as_f64)).collect(); + assert_eq!(pops.first(), Some(&1_000_000.0), "{pops:?}"); + assert!(pops.get(1).is_some_and(|b| (b / 500_000.0 - 1.0).abs() < 0.05), "{pops:?}"); // The same strip wholly inside the zone counts whole, unrounded, with no notice. let mut z = Dataset::new("zones", GeometryType::Polygon, vec![Field::new("zone", FieldType::Text)]); @@ -440,6 +447,30 @@ fn a_thin_feature_near_a_zone_only_by_its_extent_gets_no_notice() { assert_eq!(result.messages, ["Tabulate Intersection: 0 rows", "1 zone overlaps no class feature, so it has no rows"]); } +/// A zone stored with a jump across the antimeridian, unsplit: the map draws it the long way round, +/// so a class feature at 0° falls in it, and a notice says its percentages follow the map. +#[test] +fn a_zone_crossing_the_antimeridian_unsplit_is_reported() { + let ring = |pts: &[(f64, f64)]| Some(Geometry::Polygon(vec![vec![pts.iter().map(|&(x, y)| Coord::new(x, y)).collect()]])); + let mut z = Dataset::new("zones", GeometryType::Polygon, vec![Field::new("zone", FieldType::Text)]); + z.push_next(ring(&[(179.0, 0.0), (-179.0, 0.0), (-179.0, 1.0), (179.0, 1.0), (179.0, 0.0)]), vec![Value::Text("A".into())]); + let mut c = Dataset::new("classes", GeometryType::Polygon, vec![Field::new("kind", FieldType::Text)]); + c.push_next(ring(&[(0.0, 0.2), (0.5, 0.2), (0.5, 0.8), (0.0, 0.8), (0.0, 0.2)]), vec![Value::Text("x".into())]); + let result = rustgis_analysis::run( + "tabulateIntersection", + &layers(z, c), + &json!({"zones": "zones", "zoneFields": "zone", "classes": "classes"}), + ) + .unwrap(); + assert_eq!( + result.messages, + [ + "Tabulate Intersection: 1 row", + "1 zone feature crosses the antimeridian without being split there: the map draws them the long way round, and their percentages and shares follow the map, while area_km2 follows the ground", + ] + ); +} + #[test] fn zones_sharing_a_value_are_one_zone() { let mut z = zones(); diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index 6b921612f6..2795ac000d 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -593,11 +593,14 @@ ends at 85.05° north and south: parts of polygons beyond that are taken as lyin overlaps there have no area ([#1033](https://github.com/opengeos/RustGIS/issues/1033)); the tool says how many features reach beyond it. -The tool says how many zone and class features have no polygon (no geometry, an empty one, or a line -or point; they are left out), how many zones overlap no class feature and so have no rows, how many -class features have no value in a sum field (they add nothing to its shares) and, with sum fields, -how many class features lie partly or wholly outside the zones. Only selected features are used when -a layer has a selection, and the table is named `_Tabulate` unless `output` names it. +The tool says how many zone and class features have no polygon (no geometry, an empty one, a line or +point, or a ring collapsed to no area; they are left out), how many cross the antimeridian without +being split there (the map, and with it the percentages and shares, takes them the long way round, +while area_km2 takes their ground shape), how many zones overlap no class feature and so have no +rows, how many class features have no value in a sum field (they add nothing to its shares) and, +with sum fields, how many class features lie partly or wholly outside the zones. Only selected +features are used when a layer has a selection, and the table is named `_Tabulate` unless +`output` names it. ```text gp.run={"tool":"tabulateIntersection","params":{"zones":"districts","zoneFields":"district","classes":"blocks","sumFields":["population"]}} From 9129a2f68e5c72661b59c524e879261859a3eef4 Mon Sep 17 00:00:00 2001 From: mavrick Date: Mon, 2 Nov 2026 03:35:25 -0600 Subject: [PATCH 12/12] fix(analysis): count a covered feature whole when its cut snaps away; cite the area integral MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - A feature the grid doesn't resolve, which a zone covers by the exact predicate, counts whole in that zone even when the overlay's cut leaves nothing of it: a 0.5 mm sliver inside a zone now shares out its whole value rather than a zero share with only the roughness notice. - Cite the sources of the rhumb-line area: the integral of sin φ dλ that Chamberlain & Duquette (JPL, 2007) evaluate with straight lon/lat edges, and the isometric latitude of the Mercator projection from Snyder, Map Projections: A Working Manual (USGS PP 1395, 1987). Co-Authored-By: Claude Opus 5.5 --- crates/analysis/src/tools.rs | 57 +++++++++++-------- .../analysis/tests/tabulate_intersection.rs | 7 +++ 2 files changed, 40 insertions(+), 24 deletions(-) diff --git a/crates/analysis/src/tools.rs b/crates/analysis/src/tools.rs index 5f583f7702..f5a4457609 100644 --- a/crates/analysis/src/tools.rs +++ b/crates/analysis/src/tools.rs @@ -2839,12 +2839,16 @@ fn map_area_m2(g: &Geometry) -> f64 { polys.iter().flat_map(|rings| rings.iter().enumerate()).map(|(i, r)| if i == 0 { 1.0 } else { -1.0 } * rhumb_ring_area(r) * r2).sum() } -/// The area of a ring of rhumb lines on the unit sphere, |∮ sin φ dλ|, for [`map_area_m2`]. Along a -/// rhumb line the isometric latitude ψ (the Mercator y over the radius) changes linearly with the -/// longitude λ and sin φ = tanh ψ, so an edge's integral is Δλ/Δψ × (ln cosh ψ₂ − ln cosh ψ₁); for a -/// short Δψ, where that difference cancels, its Taylor series about the middle. Longitudes are not -/// folded, as on the map, so the ring's Δλ add up to 0 and no ring winds around a pole: a ring -/// stored around one with a jump across the antimeridian is the flat shape the map draws for it. +/// The area of a ring of rhumb lines on the unit sphere, |∮ sin φ dλ|, for [`map_area_m2`]. The +/// integral is the area element cos φ dφ dλ taken round the ring by Green's theorem, the one +/// Chamberlain & Duquette (JPL, 2007) evaluate with edges straight in longitude and latitude +/// ([`rustgis_geom::geodesic_ring_area_m2`]). Along a rhumb line the isometric latitude +/// ψ = ln tan(π/4 + φ/2), the Mercator y over the radius (Snyder, *Map Projections: A Working +/// Manual*, USGS Professional Paper 1395, 1987, on the Mercator projection), changes linearly with +/// the longitude λ, and sin φ = tanh ψ, so an edge's integral is Δλ/Δψ × (ln cosh ψ₂ − ln cosh ψ₁); +/// for a short Δψ, where that difference cancels, its Taylor series about the middle. Longitudes +/// are not folded, as on the map, so the ring's Δλ add up to 0 and no ring winds around a pole: a +/// ring stored around one with a jump across the antimeridian is the flat shape the map draws. fn rhumb_ring_area(ring: &[Coord]) -> f64 { let iso = |c: &Coord| c.y.clamp(-rustgis_geom::MAX_LAT, rustgis_geom::MAX_LAT).to_radians().tan().asinh(); let ln_cosh = |x: f64| x.abs() + (-2.0 * x.abs()).exp().ln_1p() - std::f64::consts::LN_2; @@ -3396,27 +3400,32 @@ fn tabulate_intersection(inp: &dyn Inputs, p: &Json) -> Result Option { + if resolved { + return None; + } + let m = to_multipolygon(&whole).map(|w| zone.mask.relate(&w))?; + if m.is_covers() && total > 0.0 { + return Some(whole.as_ref().clone()); + } + *cut_part |= m.is_intersects() && !m.is_touches(); + None }; - let Some(mut piece) = part(&whole, &zone.mask, true) else { - cut_part |= meets_zone(); - continue; + let cut = part(&whole, &zone.mask, true).map(|p| (map_area_m2(&p), p)).filter(|(a, _)| *a > 0.0 && a.is_finite()); + let (mut piece, mut piece_area) = match cut { + Some((a, p)) => (p, a), + None => match lost(&mut cut_part) { + Some(w) => (w, total), + None => continue, + }, }; - let mut piece_area = map_area_m2(&piece); - if piece_area <= 0.0 || !piece_area.is_finite() { - cut_part |= meets_zone(); - continue; - } inside = true; - let total = *whole_area.get_or_insert_with(|| map_area_m2(&whole)); // A part within the overlay's rounding of the whole may be the whole feature, the cut // only moving its vertices onto the grid: it is when nothing lies outside the zone, // or, for a feature the grid resolves, nothing wider than the grid. (For one it diff --git a/crates/analysis/tests/tabulate_intersection.rs b/crates/analysis/tests/tabulate_intersection.rs index fb754fb207..0325934e1b 100644 --- a/crates/analysis/tests/tabulate_intersection.rs +++ b/crates/analysis/tests/tabulate_intersection.rs @@ -430,6 +430,13 @@ fn slivers_too_narrow_to_measure_finely_are_reported_not_counted_twice() { let total: f64 = table(result).features.iter().filter_map(|f| f.attrs.get(3).and_then(Value::as_f64)).sum(); assert!(total <= 1_000_000.0 * 1.01, "{width_m} m wide shared out {total}"); } + // The narrowest wholly inside A: whatever the cut leaves of it, A covers it, so it counts whole. + let mut c = Dataset::new("classes", GeometryType::Polygon, vec![Field::new("pop", FieldType::Integer)]); + c.push_next(rect(-96.0000045, 35.0, -95.9999955, 35.0 + 0.0005 / 111_000.0), vec![Value::Int(1_000_000)]); + let result = rustgis_analysis::run("tabulateIntersection", &layers(z, c), ¶ms).unwrap(); + assert_eq!(result.messages, ["Tabulate Intersection: 1 row", "1 zone overlaps no class feature, so it has no rows"]); + let pop = table(result).features.first().and_then(|f| f.attrs.get(3)).and_then(Value::as_f64); + assert_eq!(pop, Some(1_000_000.0)); } /// A thin feature in the notch of an L-shaped zone: within the zone's extent but touching none of