diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 75055baee5..3dfbe5f7ad 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -34,6 +34,7 @@ of use. | CityGML test mesh (`crates/data/tests/data/rocking-chair.gml`), read only by tests | 97 faces of the rocking chair in OGC's CityGML 3.0 sample `Building_LOD3-EPSG25832.gml` ([CityGML-3.0Encodings](https://github.com/opengeospatial/CityGML-3.0Encodings/blob/master/Moved_to_CITYGML-3.0Encoding_CityGML/Examples/Examples-from-CityGML-2.0/building/CityGMLv3/Building_LOD3-EPSG25832.gml)), copyright (c) 2013 3DXScape, copied on 2026-11-12 and rewritten as a CityGML 2.0 object, coordinates unchanged | MIT | | Datum grid test files (`crates/data/tests/data/grids/us_noaa_conus.tif`, `us_noaa_ethpgn.tif`), read only by the datum grid tests | NOAA's NADCON and HARN grids as converted by [PROJ-data](https://github.com/OSGeo/PROJ-data) (`us_noaa`), copied unchanged from [cdn.proj.org](https://cdn.proj.org) | Public domain | | LERC GeoTIFF test files (`crates/data/tests/data/lerc/*.tif`), read only by the LERC tests | Written for the RustGIS project by `make_lerc.py` there with [GDAL](https://gdal.org) 3.9.3 through [rasterio](https://rasterio.readthedocs.io) 1.4.3, run only to write them; the values are made up | Apache-2.0 | +| Dissolve contour regression (`crates/analysis/testdata/dissolve-contours.json`), read only by tests | Three polygons reduced to ten vertices from the U.S. Census Bureau's [2024 TIGER/Line Census Blocks for Oregon](https://www2.census.gov/geo/tiger/TIGER2024/TABBLOCK20/tl_2024_41_tabblock20.zip) | Public domain | | Analysis reference corpus (`crates/analysis/tests/reference/`: layers and expected results) | Written for the RustGIS project from `generate.py` there: the layers are made up; the expected results were computed by [GEOS](https://libgeos.org) 3.13.1 through [Shapely](https://shapely.readthedocs.io) 2.1.2, and distances, buffers, areas and lengths by GeographicLib in [PROJ](https://proj.org) 9.5.1 through [pyproj](https://pyproj4.github.io/pyproj/) 3.7.2, run only to write them (GEOS is LGPL-2.1, Shapely BSD-3-Clause, PROJ and pyproj MIT; none is included in or linked into RustGIS) | Apache-2.0 | Coordinate systems are looked up by EPSG and ESRI code in the catalog of diff --git a/Cargo.lock b/Cargo.lock index 6764cffdeb..005124c500 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2209,7 +2209,7 @@ dependencies = [ "float_next_after 2.0.0", "geo-types", "geographiclib-rs", - "i_overlay", + "i_overlay 4.5.2", "log", "num-traits", "rand 0.10.3", @@ -2768,6 +2768,15 @@ dependencies = [ "libm", ] +[[package]] +name = "i_float" +version = "5.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ecaff1ce29bcacd72cdf581ba6fce636ef4c4e0b2da7e7846dd0137d98141e2" +dependencies = [ + "libm", +] + [[package]] name = "i_key_sort" version = "0.10.3" @@ -2777,26 +2786,53 @@ dependencies = [ "rayon", ] +[[package]] +name = "i_key_sort" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "14269ee362009550495e20650ff3c2bca14a8147fe251e216760381ffed90b6f" + [[package]] name = "i_overlay" version = "4.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8dd314b4668e2b3a12508f2e125558c82a6c0a8636fa5107a900f79ce414e450" dependencies = [ - "i_float", - "i_key_sort", - "i_shape", - "i_tree", + "i_float 1.16.0", + "i_key_sort 0.10.3", + "i_shape 1.18.0", + "i_tree 0.18.0", "rayon", ] +[[package]] +name = "i_overlay" +version = "9.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c72f9301c5ab9d2c207a4bdfefbc0b22b7a9750816e49585d4e44904b76390c9" +dependencies = [ + "i_float 5.0.0", + "i_key_sort 0.12.0", + "i_shape 5.0.0", + "i_tree 0.20.0", +] + [[package]] name = "i_shape" version = "1.18.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bfa9eac533d7509a8ab87672b60ac610c17240f9ea4851d26227689fdfe349c8" dependencies = [ - "i_float", + "i_float 1.16.0", +] + +[[package]] +name = "i_shape" +version = "5.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa1878f91ef7921feaf1b2346253ebc5e661878b22d5715195c1d5dcf0f20ae5" +dependencies = [ + "i_float 5.0.0", ] [[package]] @@ -2805,6 +2841,12 @@ version = "0.18.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4804bdc1dc124eb7e1aa9e144ecc04096bcf787a10a15fa44af682b51f0f6cce" +[[package]] +name = "i_tree" +version = "0.20.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "048af31de955890c62a8506fec511335a5089e91e1c516537add16f96c507d84" + [[package]] name = "iana-time-zone" version = "0.1.65" @@ -5179,6 +5221,7 @@ dependencies = [ "a5", "geo", "h3o", + "i_overlay 9.2.1", "log", "proptest", "rustgis-data", diff --git a/crates/analysis/Cargo.toml b/crates/analysis/Cargo.toml index e5d7b8c064..d4d33413e7 100644 --- a/crates/analysis/Cargo.toml +++ b/crates/analysis/Cargo.toml @@ -12,6 +12,9 @@ workspace = true rustgis-geom = { workspace = true } rustgis-data = { workspace = true } geo = { workspace = true } +# Not 9.2.0: of 8,674 random groups it wrote invalid polygons for 5 (one of valid input), and 9.2.1 +# for none. +i_overlay9 = { package = "i_overlay", version = "9.2.1" } a5 = { workspace = true } h3o = { workspace = true } s2 = { workspace = true } diff --git a/crates/analysis/src/tools.rs b/crates/analysis/src/tools.rs index b35730f4ae..6d6c997e2c 100644 --- a/crates/analysis/src/tools.rs +++ b/crates/analysis/src/tools.rs @@ -1603,13 +1603,91 @@ pub fn find_field_case_insensitive(ds: &Dataset, name: &str) -> Result(polys: impl IntoIterator>) -> MultiPolygon { +/// Geo's polygon union, with consistent ring orientation so the fill rule follows the first ring. +fn geo_union_all<'a>(polys: impl IntoIterator>) -> MultiPolygon { let oriented: Vec> = polys.into_iter().map(|p| p.orient(Direction::Default)).collect(); geo::unary_union(oriented.iter()) } +/// Union a Dissolve group using consistently oriented rings and OGC extraction. Each ring is +/// oriented by its signed area: geo reads the turn at its least vertex, which a spike there leaves +/// missing and nearly coincident vertices there can leave wrong. At exactly zero (a collapsed +/// ring, or lobes that cancel out) it keeps geo's direction, and the positive fill keeps only what +/// it goes around counterclockwise. An exterior that encloses nothing is taken without its holes. +/// A group uses Geo's union if any coordinate is outside the finite range ±2^500 (about +/// ±3.27e150). The i_overlay 9 stopgap uses its serial build on desktop and in the browser. Its +/// optional parallel build would require integrating the sort and split workers with RustGIS's +/// thread setting. The union is one step with no Cancel check inside it. +fn dissolve_union<'a, P>(polys: P) -> MultiPolygon +where + P: IntoIterator>, + P::IntoIter: Clone, +{ + use geo::Area; + use i_overlay9::core::{fill_rule::FillRule, overlay_rule::OverlayRule}; + use i_overlay9::float::overlay::{FloatOverlay, OverlayOptions}; + use i_overlay9::i_float::float::compatible::FloatPointCompatible; + + // i_overlay 4.5 can loop forever during contour extraction. Once geo ships with i_overlay 9, + // drop the direct dependency, but keep the orientation and the positive fill: geo's own main + // still picks the fill from the first ring with a winding, which loses other polygons. + let polys = polys.into_iter(); + let mut supported = true; + let mut subject = Vec::new(); + for poly in polys.clone() { + let (exterior, interiors) = poly.orient(Direction::Default).into_inner(); + for (hole, mut ring) in std::iter::once((false, exterior)).chain(interiors.into_iter().map(|r| (true, r))) { + // Taken from the ring's first vertex, so large coordinates don't cancel out. + let area = geo::Polygon::new(ring.clone(), vec![]).signed_area(); + let backwards = if hole { area > 0.0 } else { area < 0.0 }; + if backwards { + ring.0.reverse(); + } + // Overlay closes paths implicitly. Polygon::new closes them again on output. + let path: Vec<_> = ring + .0 + .split_last() + .map_or(&[][..], |(_, open)| open) + .iter() + .map(|c| { + let point = [c.x, c.y]; + supported &= point.is_in_safe_range(); + point + }) + .collect(); + // The holes of an exterior that encloses nothing would cut its neighbors. + let nothing = !hole + && supported + && !poly.interiors().is_empty() + && FloatOverlay::with_subj_custom(&path, OverlayOptions::::ogc(), Default::default()) + .overlay(OverlayRule::Subject, FillRule::NonZero) + .is_empty(); + subject.push(path); + if nothing { + break; + } + } + } + // Out-of-range groups still use Geo's contour extraction, which can hang. + if !supported { + drop(subject); + return geo_union_all(polys); + } + // Exteriors run counterclockwise and holes clockwise, by area, except rings of zero area. The + // fill is positive whichever ring comes first. + let shapes = FloatOverlay::with_subj_custom(&subject, OverlayOptions::::ogc(), Default::default()) + .overlay(OverlayRule::Subject, FillRule::Positive); + MultiPolygon::new( + shapes + .into_iter() + .map(|shape| { + let mut rings = shape.into_iter().map(|path| path.into_iter().map(|[x, y]| (x, y)).collect()); + geo::Polygon::new(rings.next().unwrap_or_else(geo::LineString::empty), rings.collect()) + }) + .collect(), + ) +} + // --------------------------------------------------------------------------------------------- // tools @@ -1778,7 +1856,7 @@ fn buffer_with_limits(inp: &dyn Inputs, p: &Json, limit: usize, bytes: usize) -> crate::control::check()?; // The union isn't counted: the buffers' count ends here rather than stand at its end. crate::control::begin(0); - let u = union_all(all.iter().flat_map(|m| m.0.iter())); + let u = geo_union_all(all.iter().flat_map(|m| m.0.iter())); if u.coords_count() > limit { return Err(VERTEX_BUDGET_ERROR.into()); } @@ -1818,7 +1896,7 @@ fn buffer_with_limits(inp: &dyn Inputs, p: &Json, limit: usize, bytes: usize) -> fn dissolved(g: &Geometry) -> std::borrow::Cow<'_, Geometry> { match g { Geometry::Polygon(polys) if polys.len() > 1 => to_multipolygon(g) - .and_then(|m| from_multipolygon(&union_all(m.0.iter()))) + .and_then(|m| from_multipolygon(&geo_union_all(m.0.iter()))) .map_or(std::borrow::Cow::Borrowed(g), std::borrow::Cow::Owned), _ => std::borrow::Cow::Borrowed(g), } @@ -1828,7 +1906,7 @@ fn dissolved(g: &Geometry) -> std::borrow::Cow<'_, Geometry> { /// overlap with it, a line's stretches in it, the points in it or on its edge; outside, the rest. /// `None` when nothing is left, or only a shared edge or corner. /// -/// The mask's polygons are in the run's plane ([`crate::convert::plane`]), oriented as `union_all` +/// The mask's polygons are in the run's plane ([`crate::convert::plane`]), oriented as `geo_union_all` /// leaves them. The feature's may wind either way (the reference corpus has a clockwise parcel), /// but must not overlap each other: pass a feature of several polygons through [`dissolved`] first, /// once for all its masks. @@ -2151,7 +2229,7 @@ impl MaskCache { /// The union of the masks `near` names, from the cache, or made and kept there. fn union_of(&mut self, near: &[usize], masks: &[(MultiPolygon, Extent)]) -> Cow<'_, MultiPolygon> { - let make = || union_all(near.iter().filter_map(|i| masks.get(*i)).flat_map(|(m, _)| m.0.iter())); + let make = || geo_union_all(near.iter().filter_map(|i| masks.get(*i)).flat_map(|(m, _)| m.0.iter())); if self.big.as_ref().is_some_and(|(ids, _)| ids.as_slice() == near) { return match &self.big { Some((_, mask)) => Cow::Borrowed(mask), @@ -2231,7 +2309,7 @@ fn clip_on(inp: &dyn Inputs, p: &Json, threads: Option, cache_bytes: Opti let ext = merc_extent(&m); // Union even one polygon: collapsed rings have no filled area. Keep the original // bounds too: rounding an edge must not hide a line the boolean overlay clips to it. - let mask = union_all(m.0.iter()); + let mask = geo_union_all(m.0.iter()); let ext = ext.union(&merc_extent(&mask)); Ok(if mask.0.is_empty() { ClipMask::NoArea } else { ClipMask::Mask(mask, ext) }) }, @@ -2462,7 +2540,7 @@ struct Zone { /// overlay can't take as they are, so several are unioned; one polygon is only oriented, so its /// edges stay exactly where they are. fn mask_of(poly: MultiPolygon) -> MultiPolygon { - if poly.0.len() > 1 { union_all(poly.0.iter()) } else { poly.orient(Direction::Default) } + if poly.0.len() > 1 { geo_union_all(poly.0.iter()) } else { poly.orient(Direction::Default) } } /// How an overlay tool uses its overlay polygons, for [`overlay_zones_on`]. @@ -2655,7 +2733,7 @@ fn rest_outside(g: &Geometry, whole: &Geometry, hit: &[&Zone]) -> Option Some(g.clone()), [only] => part(whole, &only.poly, false), - _ => part(whole, &union_all(hit.iter().flat_map(|z| z.poly.0.iter())), false), + _ => part(whole, &geo_union_all(hit.iter().flat_map(|z| z.poly.0.iter())), false), } } @@ -3274,7 +3352,7 @@ fn split_on(inp: &dyn Inputs, p: &Json, threads: Option) -> Result(match polys.as_slice() { [only] => std::borrow::Cow::Borrowed(&only.poly), - _ => std::borrow::Cow::Owned(union_all(polys.iter().flat_map(|z| z.poly.0.iter()))), + _ => std::borrow::Cow::Owned(geo_union_all(polys.iter().flat_map(|z| z.poly.0.iter()))), }) }, )?; @@ -3394,13 +3472,15 @@ fn dissolve(inp: &dyn Inputs, p: &Json) -> Result { fields.extend(added); let mut out = Dataset::new(out_name(p, format!("{}_Dissolve", ds.name)), GeometryType::Polygon, fields); let mut rounded = Rounded::new(requests.len()); + // Groups written without a geometry, as their union is empty. + let mut no_shape = 0usize; // The unions are the work: counted, and Cancel looked at, group by group. crate::control::begin(groups.len()); for (done, (key, parts, mut records)) in groups.into_iter().enumerate() { crate::control::check()?; crate::control::reached(done); let n = parts.len() as i64; - let u = union_all(parts.iter().flat_map(|m| m.0.iter())); + let u = dissolve_union(parts.iter().flat_map(|m| m.0.iter())); let mut attrs = if fi.is_some() { vec![key, Value::Int(n)] } else { vec![Value::Int(n)] }; if !requests.is_empty() { record_order(&mut records); @@ -3408,7 +3488,9 @@ fn dissolve(inp: &dyn Inputs, p: &Json) -> Result { rounded.count_texts(ds, &records, &requests, false)?; attrs.extend(statistic_values(ds, &records, &requests, false, separator, &mut rounded)?); } - out.push(from_multipolygon(&u), attrs); + let shape = from_multipolygon(&u); + no_shape += usize::from(shape.is_none()); + out.push(shape, attrs); } let n = out.features.len(); // Features read, none with a polygon: an unusable result, so an error saying why. @@ -3424,6 +3506,11 @@ fn dissolve(inp: &dyn Inputs, p: &Json) -> Result { "Dissolve: {not_polygons} feature(s) left out, with their values: no geometry, an empty polygon, or a point or line rather than a polygon" ) }); } + if no_shape > 0 { + losses.push(rustgis_data::loss::LossMessage { code: rustgis_data::loss::LossCode::DroppedGeometry, text: format!( + "Dissolve: {no_shape} feature(s) written without geometry: merging their polygons left no area (none to begin with, too small or thin beside the group's extent, or coordinates too large to merge)" + ) }); + } let (said, rounded) = rounded_notice(&rounded, out.fields.get(first_added..).unwrap_or_default()); messages.extend(said); losses.extend(rounded); @@ -7229,7 +7316,7 @@ fn tabulate_intersection(inp: &dyn Inputs, p: &Json) -> Result Result 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 Some(g) = from_multipolygon(&geo_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", @@ -9801,6 +9888,162 @@ mod tests { } } + /// What `union` returns, failing the test after 15 s: a contour loop would hang CI. + fn finishes(union: impl FnOnce() -> T + Send + 'static) -> T { + let (send, received) = std::sync::mpsc::channel(); + let worker = std::thread::Builder::new().spawn(move || send.send(union()).unwrap()).unwrap(); + // test-wait: bound the wait so a contour loop fails the test instead of hanging CI. + let result = received.recv_timeout(std::time::Duration::from_secs(15)); + assert_ne!(result.as_ref().err(), Some(&std::sync::mpsc::RecvTimeoutError::Timeout), "polygon union did not finish"); + worker.join().unwrap_or_else(|panic| std::panic::resume_unwind(panic)); + result.unwrap() + } + + #[test] + fn dissolve_union_finishes_extracting_contours() { + use geo::Validation; + + let paths: Vec> = serde_json::from_str(include_str!("../testdata/dissolve-contours.json")).unwrap(); + let mut polys: Vec<_> = paths.into_iter().map(|path| geo::Polygon::new(path.into(), vec![])).collect(); + + // The grid must exceed both fragment solver thresholds (16,000 segments in i_overlay + // 4.5.2 and 32,000 in 9.2.1). A separate rectangle covers it, so the squares add no area. + let (x, y, width, height) = (-123.796, 42.736, 0.013, 0.004); + let rectangle = |x, y, w, h| geo::Polygon::new(vec![(x, y), (x + w, y), (x + w, y + h), (x, y + h)].into(), vec![]); + const SIDE: i32 = 128; + let (dx, dy) = (width / f64::from(SIDE), height / f64::from(SIDE)); + for row in 0..SIDE { + for col in 0..SIDE { + polys.push(rectangle(x + f64::from(col) * dx + dx / 4.0, y + f64::from(row) * dy + dy / 4.0, dx / 2.0, dy / 2.0)); + } + } + polys.push(rectangle(x, y, width, height)); + + let union = finishes(move || dissolve_union(&polys)); + assert!(union.is_valid()); + let mut areas: Vec<_> = union.0.iter().map(geo::Area::unsigned_area).collect(); + areas.sort_by(f64::total_cmp); + assert_eq!(areas.len(), 2); + // Areas of the merged Census polygons and the separate rectangle, computed with GEOS. + for (area, expected) in areas.into_iter().zip([1.575_209_1e-5, 5.2e-5]) { + assert!((area - expected).abs() < 1e-10, "area {area}, expected {expected}"); + } + } + + #[test] + fn dissolve_union_keeps_shells_after_a_collapsed_exterior() { + finishes(|| { + let hole = geo::Rect::new((0.0, 0.0), (2.0, 2.0)).to_polygon(); + let collapsed = geo::Polygon::new(vec![(0.0, 0.0), (1.0, 0.0), (2.0, 0.0)].into(), vec![hole.exterior().clone()]); + let a = geo::Rect::new((3.0, 0.0), (4.0, 1.0)).to_polygon(); + let b = geo::Rect::new((5.0, 0.0), (6.0, 1.0)).to_polygon(); + + let union = dissolve_union([&collapsed, &a, &b]); + assert_eq!(union.0.len(), 2); + assert!((geo::Area::unsigned_area(&union) - 2.0).abs() < 1e-9); + }); + } + + /// An exterior that encloses nothing doesn't cut the polygons its hole covers: it has no + /// vertices, they lie on one line, or it goes out and back along two, whichever comes first. + #[test] + fn dissolve_union_leaves_a_collapsed_exteriors_holes_out() { + finishes(|| { + let hole = geo::Rect::new((0.0, 0.0), (2.0, 2.0)).to_polygon().exterior().clone(); + let square = geo::Rect::new((0.5, 0.5), (1.5, 1.5)).to_polygon(); + // Its area rounds to -1.1e-16, not zero. + let there_and_back = vec![(0.1, 0.1), (0.5, 0.7), (2.2, 1.4), (2.8, 0.8), (2.2, 1.4), (0.5, 0.7)]; + for flat in [vec![], vec![(0.0, 0.0), (1.0, 0.0), (2.0, 0.0)], there_and_back] { + let collapsed = geo::Polygon::new(flat.into(), vec![hole.clone()]); + for group in [[&collapsed, &square], [&square, &collapsed]] { + let union = dissolve_union(group); + assert!((geo::Area::unsigned_area(&union) - 1.0).abs() < 1e-9, "{union:?}"); + } + } + }); + } + + /// A ring with a spike at its lexicographically least vertex has no winding there, and one + /// that comes back through that vertex can have the wrong one. Both keep their area whichever + /// way they go around: alone, beside other polygons, as a hole, with a hole, and millimetres + /// across at projected coordinates, where products of them would swallow their area. + #[test] + fn dissolve_union_keeps_rings_with_a_spike_at_their_least_vertex() { + finishes(|| { + use geo::{Area, MapCoords, Winding}; + type Ring = geo::LineString; + + let clockwise: Ring = + vec![(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (30.0, 10.0), (30.0, -10.0), (10.0, -10.0), (10.0, 0.0), (0.0, 0.0)].into(); + let reversed = |r: &Ring| Ring::new(r.0.iter().rev().copied().collect()); + let rect = |x, y, w, h| geo::Rect::new((x, y), (x + w, y + h)).to_polygon(); + let solid = |r: &Ring| geo::Polygon::new(r.clone(), vec![]); + let square = rect(50.0, 0.0, 1.0, 1.0); + let window = rect(15.0, -5.0, 5.0, 10.0).exterior().clone(); + assert_eq!(clockwise.winding_order(), None); + // Closed through a point on either side, so it passes its least vertex twice. + let through = + |y| Ring::new([(2.0, y).into()].into_iter().chain(clockwise.0.iter().copied()).chain([(2.0, y).into()]).collect()); + let rings = [clockwise.clone(), through(-3.0), through(3.0)]; + for ring in rings.iter().flat_map(|r| [r.clone(), reversed(r)]) { + let spiked = solid(&ring); + let away = Ring::new(clockwise.0.iter().map(|c| geo::Coord { x: c.x + 100.0, y: c.y }).collect()); + let mut groups = vec![ + (vec![spiked.clone()], 400.0), + (vec![spiked.clone(), square.clone()], 401.0), + (vec![square.clone(), spiked.clone()], 401.0), + (vec![spiked.clone(), solid(&away)], 800.0), + (vec![spiked.clone(), solid(&reversed(&away))], 800.0), + (vec![geo::Polygon::new(rect(-5.0, -20.0, 45.0, 40.0).exterior().clone(), vec![ring.clone()])], 1400.0), + ]; + for hole in [window.clone(), reversed(&window)] { + groups.push((vec![geo::Polygon::new(ring.clone(), vec![hole])], 350.0)); + } + for (polys, expected) in groups { + for (scale, x, y) in [(1.0, 0.0, 0.0), (0.001, 500_000.0, 5_000_000.0)] { + let placed: Vec<_> = + polys.iter().map(|p| p.map_coords(|c| geo::Coord { x: x + c.x * scale, y: y + c.y * scale })).collect(); + let area = dissolve_union(&placed).unsigned_area() / (scale * scale); + assert!((area - expected).abs() < 0.01, "area {area}, expected {expected}: {placed:?}"); + } + } + } + }); + } + + /// A 100 m parcel whose westmost corner has three vertices within four micrometres, where + /// its edges cross: the turn at its least vertex says the wrong way around. + #[test] + fn dissolve_union_keeps_a_ring_that_crosses_itself_at_near_duplicate_vertices() { + finishes(|| { + let (e, n) = (500_000.0, 5_000_000.0); + let mut ring = vec![(e + 100.0, n), (e + 100.0, n + 100.0), (e, n + 50.0 - 2e-6), (e - 1e-6, n + 50.0), (e, n + 50.0 + 2e-6)]; + for _ in 0..2 { + let area = geo::Area::unsigned_area(&dissolve_union([&geo::Polygon::new(ring.clone().into(), vec![])])); + assert!((area - 5000.0).abs() < 0.01, "area {area}"); + ring.reverse(); + } + }); + } + + #[test] + fn dissolve_union_falls_back_for_out_of_range_exteriors_and_holes() { + finishes(|| { + let shell = geo::Rect::new((-1.0, -1.0), (2.0, 2.0)).to_polygon(); + let window = geo::Rect::new((15.0, -5.0), (20.0, 5.0)).to_polygon(); + for x in [1e160, f64::INFINITY] { + let wide = geo::LineString::from(vec![(0.0, 0.0), (x, 1.0), (1.0, 1.0), (0.0, 1.0)]); + let wide_shell = geo::Polygon::new(wide.clone(), vec![]); + let wide_hole = geo::Polygon::new(shell.exterior().clone(), vec![wide]); + let spiked = vec![(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (x, 10.0), (30.0, -10.0), (10.0, -10.0), (10.0, 0.0)]; + let spiked = geo::Polygon::new(spiked.into(), vec![window.exterior().clone()]); + for poly in [&wide_shell, &wide_hole, &spiked] { + assert_eq!(dissolve_union([poly]), geo_union_all([poly])); + } + } + }); + } + /// Dissolve says how many features it left out for having no polygon: a point and a line in a /// polygon layer (as Minimum Bounding Geometry's flat hulls are), an empty polygon and a /// feature without geometry. Those in a group add nothing to its count or statistics. A layer @@ -9821,7 +10064,7 @@ mod tests { } let m = Map(HashMap::from([("polys".to_string(), polys)])); let params = serde_json::json!({"input": "polys", "field": "k", "statistics": [{"field": "v", "statistic": "SUM"}]}); - let res = crate::run("dissolve", &m, ¶ms).unwrap(); + let res = finishes(move || crate::run("dissolve", &m, ¶ms).unwrap()); let note = said(&res).into_iter().find(|m| m.contains("left out")); let out = layer(res); (out.features.len(), out.value(0, 1).as_f64(), out.value(0, 2).as_f64(), note) @@ -10002,6 +10245,52 @@ mod tests { ); } + /// Dissolve counts the groups whose polygons merge to nothing, and still writes their feature + /// with its count and statistics: coordinates out of range, every vertex in one place, and a + /// unit square that the overlay's grid has no room for beside a triangle 1e12° wide. A layer + /// whose groups all have an area says nothing. + #[test] + fn dissolve_counts_groups_left_without_geometry() { + finishes(|| { + let triangle = |far: f64| { + let at = |x, y| Coord::new(x, y); + Geometry::Polygon(vec![vec![vec![at(0.0, 0.0), at(far, 1.0), at(1.0, 1.0), at(0.0, 1.0), at(0.0, 0.0)]]]) + }; + let empty = [vec![triangle(1e160)], vec![sq(3.0, 3.0, 0.0)], vec![sq(2.0, 0.0, 1.0), triangle(1e12)]]; + let run = |groups: &[Vec]| { + let fields = vec![Field::new("k", FieldType::Integer), Field::new("v", FieldType::Double)]; + let mut polys = Dataset::new("polys", GeometryType::Polygon, fields); + for (k, group) in groups.iter().enumerate() { + for g in group { + polys.push(Some(g.clone()), vec![Value::Int(k as i64), Value::Float(2.0)]); + } + } + let m = Map(HashMap::from([("polys".to_string(), polys)])); + let params = serde_json::json!({"input": "polys", "field": "k", "statistics": [{"field": "v", "statistic": "SUM"}]}); + let res = crate::run("dissolve", &m, ¶ms).unwrap(); + let note = said(&res).into_iter().find(|m| m.contains("without geometry")); + let out = layer(res); + let rows: Vec<_> = (0..out.features.len()) + .map(|r| (out.features.row(r).unwrap().geometry().is_some(), out.value(r, 1).as_f64(), out.value(r, 2).as_f64())) + .collect(); + (rows, note) + }; + let notice = |n: usize| { + format!( + "DroppedGeometry: Dissolve: {n} feature(s) written without geometry: merging their polygons left no area (none to begin with, too small or thin beside the group's extent, or coordinates too large to merge)" + ) + }; + let clean = vec![sq(0.0, 0.0, 1.0), sq(1.0, 0.0, 1.0)]; + let row = |geometry: bool, group: &[Geometry]| (geometry, Some(group.len() as f64), Some(2.0 * group.len() as f64)); + for group in &empty { + assert_eq!(run(&[clean.clone(), group.clone()]), (vec![row(true, &clean), row(false, group)], Some(notice(1)))); + } + let rows = empty.iter().map(|g| row(false, g)).collect(); + assert_eq!(run(&empty), (rows, Some(notice(3)))); + assert_eq!(run(std::slice::from_ref(&clean)), (vec![row(true, &clean)], None)); + }); + } + /// Dissolve's groups, found by their keys' hash: in the order first met, −0 with 0, each NaN /// on its own (it equals no value), and a number apart from the same text and a whole number /// apart from the same fraction. @@ -10025,7 +10314,7 @@ mod tests { polys.push(Some(sq(i as f64 * 3.0, 0.0, 1.0)), vec![k]); } let m = Map(HashMap::from([("polys".to_string(), polys)])); - let d = layer(crate::run("dissolve", &m, &serde_json::json!({"input": "polys", "field": "k"})).unwrap()); + let d = layer(finishes(move || crate::run("dissolve", &m, &serde_json::json!({"input": "polys", "field": "k"})).unwrap())); let got: Vec = (0..d.features.len()).map(|r| format!("{:?}×{:?}", d.value(r, 0), d.value(r, 1))).collect(); assert_eq!( got, @@ -13815,7 +14104,7 @@ mod tests { .iter() .filter_map(|r| masks.features[*r].geometry.as_ref().and_then(to_multipolygon)) .collect(); - let whole = union_all(polys.iter().flat_map(|m| m.0.iter())); + let whole = geo_union_all(polys.iter().flat_map(|m| m.0.iter())); let features = &inp.0.0["features"]; let expected: Vec<_> = rows(&inp, &p, "input", features) .into_iter() @@ -13962,7 +14251,7 @@ mod tests { /// no area or a coordinate that isn't finite, whatever the mask. #[test] fn a_feature_is_placed_without_an_overlay_only_clear_of_the_mask_edges() { - let mask = union_all(to_multipolygon(&sq(0.0, 0.0, 1.0)).unwrap().0.iter()); + let mask = geo_union_all(to_multipolygon(&sq(0.0, 0.0, 1.0)).unwrap().0.iter()); let edges = MaskEdges::new(&mask); let place = |g: &Geometry| { let whole = to_multipolygon(g).unwrap(); @@ -14124,7 +14413,7 @@ mod tests { for y in [-1e-12, -0.01] { lines.push(Some(Geometry::Line(vec![vec![Coord::new(0.1, y), Coord::new(0.9, y)]])), vec![]); } - let whole = union_all(to_multipolygon(masks.features[0].geometry.as_ref().unwrap()).unwrap().0.iter()); + let whole = geo_union_all(to_multipolygon(masks.features[0].geometry.as_ref().unwrap()).unwrap().0.iter()); let expected: Vec<_> = lines.features.iter().filter_map(|f| part(f.geometry.as_ref().unwrap(), &whole, true)).collect(); // The integer overlay snaps the near line onto the edge, but leaves the far line out. assert_eq!(expected.len(), 1); @@ -15323,7 +15612,7 @@ mod tests { let (x, y, d) = (-89.7, 35.05, 0.01); let tract = poly(&[(x, y), (x + d, y + d), (x - d, y + d), (x, y)]); let town = poly(&[(x, y), (x + d, y + d), (x + 6.0 * d, y - 0.3 * d), (x, y)]); - let mask = union_all(to_multipolygon(&town).unwrap().0.iter()); + let mask = geo_union_all(to_multipolygon(&town).unwrap().0.iter()); // The old part path keeps this sliver: exactly-zero checks miss it. Keep its coordinates // bit for bit, and count the two output features rather than dropped boundary contacts. let expected = part(&tract, &mask, true).unwrap(); diff --git a/crates/analysis/testdata/dissolve-contours.json b/crates/analysis/testdata/dissolve-contours.json new file mode 100644 index 0000000000..b5a9bfe6ca --- /dev/null +++ b/crates/analysis/testdata/dissolve-contours.json @@ -0,0 +1,5 @@ +[ + [[-123.532095, 42.829254], [-123.532042, 42.822733], [-123.536802, 42.822733], [-123.53683, 42.822779]], + [[-123.53683, 42.822779], [-123.536802, 42.822733], [-123.538032, 42.822733]], + [[-123.540574, 42.822733], [-123.532042, 42.822733], [-123.531443, 42.822732]] +]