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..f5a4457609 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,147 @@ 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) +} + +/// 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 +/// 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 ([`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; + 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`]. 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; + let mut total = 0.0; + for (a, b) in ring.iter().zip(ring.iter().cycle().skip(1)) { + let dlon = b.x - a.x; + 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() +} + +/// 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 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); + 2.0 * 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 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 +/// [`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 +2927,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 +2940,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 +3247,387 @@ 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, + /// 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. + map_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 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 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 +/// ([`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 +/// 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")?; + 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 + }; + // A feature without geometry, with an empty one (`"coordinates": []`), with a line or point in + // a polygon layer, or whose polygons have no area in its own coordinates (a collapsed ring) has + // no polygon, so no area to tabulate. The area is taken in longitude and latitude, so a polygon + // the map's latitude limit flattens still counts as one. + let has_shape = |g: &Geometry| matches!(g, Geometry::Polygon(polys) if polys.iter().any(|rings| rings.first().is_some_and(|r| lonlat_ring_area(r) > 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() + }; + 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)); + // The map ends at the latitude limit: the overlay takes parts beyond it as lying along it. + let beyond_limit = |ds: &Dataset, rs: &[usize]| { + let beyond = |g: &Geometry| { + let e = g.extent(); + has_shape(g) && (e.max_y > 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)); + // Features with a ring that jumps across the antimeridian unsplit: the overlay, like the map, + // takes such a ring the long way round, while `area_km2` takes its ground shape. + let unsplit = |ds: &Dataset, rs: &[usize]| { + let jumps = |g: &Geometry| { + has_shape(g) + && matches!(g, Geometry::Polygon(polys) if polys.iter().flatten().any(|r| { + r.iter().zip(r.iter().cycle().skip(1)).any(|(a, b)| (b.x - a.x).abs() > 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| { + 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)); + let merc_ext = merc_extent(&mask); + TabulateZone { key: group.key, ext, mask, merc_ext, map_area_m2: map_area } + }) + .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; + // The class features meeting a zone, not wholly inside one, whose area the overlay's rounding + // can move by more than 1%: their parts are measured only roughly. + let mut unresolved = 0usize; + // The unions of the masks of the zones near a feature, for the outside check, by the zones' + // indices: neighbouring features near the same zones reuse them, as Clip reuses its masks. + const MAX_CACHED_UNIONS: usize = 8; + let mut near_unions: std::collections::VecDeque<(Vec, 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 }; + 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; + // 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 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. + let mut held = false; + let mut cut_part = false; + for &zi in &near { + let Some(zone) = zone_list.get(zi) else { continue }; + // A cut that leaves nothing, or nothing with area, when the feature's interior meets + // the zone's lost that part to rounding. Only a feature the grid doesn't resolve can + // lose more than that rounding allows, so only for one is the zone asked, by the + // exact predicate: if it covers the feature, the part is the whole feature; if it + // only meets it, the feature is measured roughly, as for a part as cut. + let total = *whole_area.get_or_insert_with(|| map_area_m2(&whole)); + let lost = |cut_part: &mut bool| -> 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 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, + }, + }; + inside = true; + // 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 + // doesn't, what lies outside can be as narrow as the feature itself.) Then the part + // is the whole, unrounded. The grid is the one this cut used, over the feature and + // this zone alone, so a wide zone nearby doesn't coarsen it. + let zone_grid = OverlayGrid::new(&whole, &zone.merc_ext); + if total > 0.0 + && 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; + held = true; + } else { + cut_part = 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 }; + 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()); + } + } + // 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 the zones near it, unioned, are taken away. Zones that overlap each other can't + // hide such a part, as shares adding up to the whole could. + // Whether the feature's interior meets a zone's, by the exact predicate rather than the + // overlay: one near a zone only by its extent meets none, and one too narrow for the + // grid can meet a zone with no part surviving the cut. + let meets = inside + || to_multipolygon(&whole).is_some_and(|w| { + near.iter().filter_map(|&zi| zone_list.get(zi)).any(|z| { + let m = z.mask.relate(&w); + m.is_intersects() && !m.is_touches() + }) + }); + // Rough when a zone got a part of it as cut, or lost one to rounding, even if another + // zone holds it whole, or when it meets a zone but no part of it survived the cut. + unresolved += usize::from(!resolved && (cut_part || (meets && !inside))); + if !sum_fields.is_empty() && !held { + // A feature meeting no zone lies wholly outside them; one whose parts didn't + // survive the cut is reported as roughly measured, above. + let lies_outside = !meets || { + let grid = grid.get_or_insert_with(|| OverlayGrid::new(&whole, &near_merc)); + let rest = if let [zi] = near.as_slice() { + zone_list.get(*zi).and_then(|z| part(&whole, &z.mask, false)) + } else { + if let Some(pos) = near_unions.iter().position(|(ids, _)| *ids == near) { + if let Some(entry) = near_unions.remove(pos) { + near_unions.push_back(entry); + } + } else { + if near_unions.len() == MAX_CACHED_UNIONS { + near_unions.pop_front(); + } + let union = union_all(near.iter().filter_map(|&zi| zone_list.get(zi)).flat_map(|z| z.mask.0.iter())); + near_unions.push_back((near.clone(), union)); + } + near_unions.back().and_then(|(_, union)| part(&whole, union, false)) + }; + rest.is_some_and(|r| grid.wider(&r)) + }; + outside += usize::from(lies_outside); + } + } + } + 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 { + 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 + } + }; + let mut row = zone.key.clone(); + row.extend(class.key.iter().cloned()); + row.push(Value::Float(ground_area_perimeter(covered).0 / 1e6)); + 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); + } + 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 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. + match zone_list.iter().enumerate().filter(|(zi, z)| !z.ext.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")), + } + 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 {:.2}° latitude, where the map ends: parts there are taken as lying along it, with no area", + beyond.join(" and "), + rustgis_geom::MAX_LAT + )); + } + let unsplit: Vec = [(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( + "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()), + 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 +6501,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 { @@ -5982,6 +6515,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 new file mode 100644 index 0000000000..0325934e1b --- /dev/null +++ b/crates/analysis/tests/tabulate_intersection.rs @@ -0,0 +1,516 @@ +//! 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())]); + // 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)]); + 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(); + assert_eq!( + result.messages, + [ + "Tabulate Intersection: 1 row", + "2 zone 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", + ] + ); + 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)]); +} + +/// 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}"); + // 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 +/// 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]); +} + +/// 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())]); + // A zone reaching 87°N, beyond the class features. + z.push_next(polar(20.0, 30.0, 80.0, 87.0), vec![Value::Text("B".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", + "1 zone overlaps no class feature, so it has no rows", + "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 zone feature and 1 class feature reach 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", + ] + ); +} + +/// Features of about 10 m in zones of half a degree: the overlay rounds their parts to a grid +/// scaled to the zones, so a feature wholly inside a zone still counts whole, and one across the +/// border between two zones shares its value out in full within that rounding, with no notice. +#[test] +fn small_features_in_large_zones_share_out_in_full() { + let sq = |x0: f64, y0: f64, w: f64, h: f64| { + let ring = [(x0, y0), (x0 + w, y0), (x0 + w, y0 + h), (x0, y0 + h), (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(sq(-90.3, 34.9, 0.5, 1.0), vec![Value::Text("A".into())]); + z.push_next(sq(-89.8, 34.9, 0.5, 1.0), vec![Value::Text("B".into())]); + let mut c = + Dataset::new("classes", GeometryType::Polygon, vec![Field::new("id", FieldType::Integer), Field::new("pop", FieldType::Integer)]); + for i in 0..40 { + // Twenty wholly inside A, then twenty across the border at 89.8°W. + let x = if i < 20 { -90.2 + 0.0173 * f64::from(i) } else { -89.80005 + 0.000001 * f64::from(i - 20) }; + c.push_next(sq(x, 35.0 + 0.0211 * f64::from(i), 0.00009, 0.00009), vec![Value::Int(i64::from(i)), Value::Int(1_000_000)]); + } + let l = layers(z, c); + let params = json!({"zones": "zones", "zoneFields": "zone", "classes": "classes", "classFields": "id", "sumFields": "pop"}); + let result = rustgis_analysis::run("tabulateIntersection", &l, ¶ms).unwrap(); + assert_eq!(result.messages, ["Tabulate Intersection: 60 rows"]); + let mut shared: HashMap = 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}"); + } + } +} + +/// 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_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]])) + }; + 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(); + // 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 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. + assert!((pop / 500_000.0 - 1.0).abs() < 0.05, "{pop}"); + + // The same strip wholly inside one zone, and half inside another overlapping it: whole in the + // first, but the second's part is cut and rounded, which the notice still says. + 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())]); + z.push_next(rect(-89.5, 34.0, -88.0, 36.0), vec![Value::Text("B".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!(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)]); + 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"] + ); + // 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}"); + } + // 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 +/// it, so it has no parts to measure, roughly or not, and no sum fields to share out. +#[test] +fn a_thin_feature_near_a_zone_only_by_its_extent_gets_no_notice() { + 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(&[(0.0, 0.0), (2.0, 0.0), (2.0, 1.0), (1.0, 1.0), (1.0, 2.0), (0.0, 2.0), (0.0, 0.0)]), vec![Value::Text("L".into())]); + let mut c = Dataset::new("classes", GeometryType::Polygon, vec![Field::new("kind", FieldType::Text)]); + c.push_next(ring(&[(1.5, 1.5), (1.9, 1.5), (1.9, 1.50000001), (1.5, 1.50000001), (1.5, 1.5)]), vec![Value::Text("river".into())]); + let l = layers(z, c); + let result = + rustgis_analysis::run("tabulateIntersection", &l, &json!({"zones": "zones", "zoneFields": "zone", "classes": "classes"})).unwrap(); + 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(); + 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..2795ac000d 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,59 @@ 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), 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` | 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 +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 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. 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. 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. + +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"]}} +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.