From 3506f410797e363b74e7fcc540718a88b4e7b209 Mon Sep 17 00:00:00 2001 From: mavrick Date: Wed, 25 Nov 2026 15:21:53 -0600 Subject: [PATCH 1/2] feat(analysis): geoprocessing tools give loss codes for what they leave out (#2371) Buffer, Clip, Simplify, Dissolve, Minimum Bounding Geometry, Points Along Lines, XY Table To Point, Update, Calculate Geometry Attributes, Spatial Join, Zonal Statistics, Tabulate Area, Check Geometry and Repair Geometry move their loss notices onto ToolResult.losses with a code. Each coded count holds only losses: features with no polygon or no area, rows without numbers, features without geometry to begin with, and features dissolved or hulled together are said apart, plain. --- crates/analysis/src/rasterops.rs | 6 + crates/analysis/src/tools.rs | 259 +++++++++++++----- crates/analysis/src/tools/check_geometry.rs | 44 +-- crates/analysis/src/tools/repair_geometry.rs | 54 ++-- crates/analysis/src/tools/tabulate_area.rs | 33 ++- .../tests/integration/check_geometry.rs | 17 +- .../tests/integration/repair_geometry.rs | 11 +- .../tests/integration/spatial_join_merge.rs | 44 +-- 8 files changed, 328 insertions(+), 140 deletions(-) diff --git a/crates/analysis/src/rasterops.rs b/crates/analysis/src/rasterops.rs index b4d99b3081..3796ee312e 100644 --- a/crates/analysis/src/rasterops.rs +++ b/crates/analysis/src/rasterops.rs @@ -1631,6 +1631,12 @@ pub fn transform_polygon_to_lonlat(rings: &[Vec], tr: Option<&Transformer Ok(out_rings) } +/// Whether a (multi-)polygon has a part whose exterior ring has three points or more: one without +/// has no area, so nothing is lost when it can't be read. +pub fn has_a_ring(polys: &[Vec>]) -> bool { + polys.iter().any(|part| part.first().is_some_and(|ring| ring.len() >= 3)) +} + /// The polygon parts of a (multi-)polygon feature, checked and taken apart into rings, in the /// system they are in: [`transform_feature_polygons_to_lonlat`] with no transformer. It doesn't /// look at Cancel: a caller looping over features does, between them. diff --git a/crates/analysis/src/tools.rs b/crates/analysis/src/tools.rs index 75eb9c8336..bd091e6b22 100644 --- a/crates/analysis/src/tools.rs +++ b/crates/analysis/src/tools.rs @@ -1787,17 +1787,23 @@ fn buffer_with_limits(inp: &dyn Inputs, p: &Json, limit: usize, bytes: usize) -> let units = if s(p, "units").is_empty() { "Kilometers" } else { s(p, "units") }; let mut r = result(out, format!("Buffer: {n} features at {d} {units}"))?; if without > 0 { - r.messages.push(format!("{without} of {} features lack geometry, so they have no buffer", picked.len())); + let text = format!("{without} of {} features lack geometry, so they have no buffer", picked.len()); + // Each feature has a row of its own, which these lose; dissolved, they add nothing. + if s(p, "dissolve") == "All" { + r.messages.push(text); + } else { + r.losses.push(rustgis_data::loss::LossMessage { code: rustgis_data::loss::LossCode::DroppedFeature, text }); + } } if empty > 0 { r.messages .push(format!("{empty} of {} features made no buffer at {d} {units} (nothing left, or no finite coordinates)", picked.len())); } if coarse > 0 { - r.messages.push(format!( + r.losses.push(rustgis_data::loss::LossMessage { code: rustgis_data::loss::LossCode::ApproximatedCurve, text: format!( "{coarse} of {} features' buffers have outline edges left with fewer points along them than they need (the points a ring may add ran out, as on a ring of thousands of long edges, or a very long edge was halved as many times as it may be): their sides there can stray from the distance by more than a buffer otherwise keeps to (0.012%, 0.05% along a line or outline buffered in stretches, or 1 cm)", picked.len() - )); + ) }); } Ok(r) } @@ -2373,7 +2379,10 @@ fn clip_on(inp: &dyn Inputs, p: &Json, threads: Option, cache_bytes: Opti let n = out.features.len(); let mut r = result(out, format!("Clip: {n} features kept"))?; if without > 0 { - r.messages.push(format!("Clip: {without} feature(s) of '{}' left out: they have no geometry to clip", ds.name)); + r.losses.push(rustgis_data::loss::LossMessage { + code: rustgis_data::loss::LossCode::DroppedFeature, + text: format!("Clip: {without} feature(s) of '{}' left out: they have no geometry to clip", ds.name), + }); } r.messages.extend(left.notes("Clip", &clip_ds.name)); if slivers > 0 { @@ -2934,18 +2943,25 @@ fn update_on(inp: &dyn Inputs, p: &Json, threads: Option) -> Result = Vec::new(); messages.extend(left_out.notes("Update", &up.name)); let features = |n: usize| if n == 1 { "1 update feature".to_string() } else { format!("{n} update features") }; for (f, (n, days)) in ds.fields.iter().zip(unfit) { if n > 0 { - messages.push(format!("Update: '{}' is null in {}, whose value isn't a {} value", f.name, features(n), f.ty.label())); + losses.push(rustgis_data::loss::LossMessage { + code: rustgis_data::loss::LossCode::DroppedValue, + text: format!("Update: '{}' is null in {}, whose value isn't a {} value", f.name, features(n), f.ty.label()), + }); } if days > 0 { let their = if days == 1 { "its" } else { "their" }; - messages.push(format!("Update: '{}' holds dates, so {} kept only {their} day", f.name, features(days))); + losses.push(rustgis_data::loss::LossMessage { + code: rustgis_data::loss::LossCode::DroppedTime, + text: format!("Update: '{}' holds dates, so {} kept only {their} day", f.name, features(days)), + }); } } - Ok(ToolResult { losses: Vec::new(), output: Output::Layer(out), messages }) + Ok(ToolResult { losses, output: Output::Layer(out), messages }) } /// The most split areas (split polygons, or values of the split field) Split takes: more is an @@ -3333,13 +3349,14 @@ fn dissolve(inp: &dyn Inputs, p: &Json) -> Result { )); } let mut messages = vec![format!("Dissolve: {n} features")]; + let mut losses: Vec = Vec::new(); if not_polygons > 0 { - messages.push(format!( + losses.push(rustgis_data::loss::LossMessage { code: rustgis_data::loss::LossCode::DroppedFeature, text: format!( "Dissolve: {not_polygons} feature(s) left out, with their values: no geometry, an empty polygon, or a point or line rather than a polygon" - )); + ) }); } messages.extend(rounded_notice(&rounded, out.fields.get(first_added..).unwrap_or_default())); - Ok(ToolResult { losses: Vec::new(), output: Output::Layer(out), messages }) + Ok(ToolResult { losses, output: Output::Layer(out), messages }) } /// The farthest (meters, either way) Minimum Bounding Geometry takes a point from the analysis @@ -3511,7 +3528,14 @@ fn convex_hull(inp: &dyn Inputs, p: &Json) -> Result { let n = out.features.len(); let mut r = result(out, format!("Minimum Bounding Geometry: {n} hulls"))?; if skipped > 0 { - r.messages.push(format!("Minimum Bounding Geometry: {skipped} feature(s) skipped: no geometry, or no point it can use")); + let text = format!("Minimum Bounding Geometry: {skipped} feature(s) skipped: no geometry, or no point it can use"); + // Each feature has a hull of its own, which these lose; hulled together, a feature without + // geometry adds nothing, and one whose points are passed over is said with them. + if each { + r.losses.push(rustgis_data::loss::LossMessage { code: rustgis_data::loss::LossCode::DroppedFeature, text }); + } else { + r.messages.push(text); + } } r.messages.extend(gaps_note.into_iter().chain(poles_note).map(|n| format!("Minimum Bounding Geometry: {n}"))); if flat > 0 { @@ -4326,7 +4350,10 @@ fn points_along_lines(inp: &dyn Inputs, p: &Json) -> Result let written = out.features.len(); let mut r = result(out, format!("{TOOL}: {written} points"))?; if missing > 0 { - r.messages.push(format!("{TOOL}: {missing} vertex(es) with a coordinate missing or infinite passed over")); + r.losses.push(rustgis_data::loss::LossMessage { + code: rustgis_data::loss::LossCode::DroppedGeometry, + text: format!("{TOOL}: {missing} vertex(es) with a coordinate missing or infinite passed over"), + }); } if past_pole > 0 { r.messages.push(format!( @@ -4334,7 +4361,10 @@ fn points_along_lines(inp: &dyn Inputs, p: &Json) -> Result )); } if without_geometry > 0 { - r.messages.push(format!("{TOOL}: {without_geometry} feature(s) without geometry skipped")); + r.losses.push(rustgis_data::loss::LossMessage { + code: rustgis_data::loss::LossCode::DroppedFeature, + text: format!("{TOOL}: {without_geometry} feature(s) without geometry skipped"), + }); } if point_features > 0 { r.messages.push(format!("{TOOL}: {point_features} point feature(s) skipped; only lines and polygon rings produce points")); @@ -4435,11 +4465,24 @@ fn xy_table_to_point(inp: &dyn Inputs, p: &Json) -> Result { }); } let mut messages = vec![format!("XY Table To Point: {placed} points")]; + let mut losses: Vec = Vec::new(); messages.extend(crs_note.map(|note| format!("XY Table To Point: its coordinate system: {note}"))); - if placed < total { - messages.push(format!("{} of {total} rows have no usable coordinates; they are in the table without a point", total - placed)); + // A row without numbers had no place to lose; one whose numbers have no place in the system + // has lost it. + if read < total { + messages.push(format!("{} of {total} rows have no numbers in both fields; they are in the table without a point", total - read)); + } + if placed < read { + losses.push(rustgis_data::loss::LossMessage { + code: rustgis_data::loss::LossCode::DroppedGeometry, + text: format!( + "{} of {total} rows have coordinates with no place in {}; they are in the table without a point", + read - placed, + crs.label() + ), + }); } - Ok(ToolResult { losses: Vec::new(), output: Output::Layer(out), messages }) + Ok(ToolResult { losses, output: Output::Layer(out), messages }) } /// The distances a Douglas–Peucker run of `n` vertices may measure, `n` times this: far more than @@ -4861,11 +4904,15 @@ fn simplify_on(inp: &dyn Inputs, p: &Json, threads: Option) -> Result = Vec::new(); messages.extend(notes.messages("Simplify")); if without > 0 { - messages.push(format!("Simplify: {without} feature(s) left out: they have no geometry to simplify")); + losses.push(rustgis_data::loss::LossMessage { + code: rustgis_data::loss::LossCode::DroppedFeature, + text: format!("Simplify: {without} feature(s) left out: they have no geometry to simplify"), + }); } - Ok(ToolResult { losses: Vec::new(), output: Output::Layer(out), messages }) + Ok(ToolResult { losses, output: Output::Layer(out), messages }) } /// A Select by Location selector: its shape and extent in the analysis plane, and the poles it @@ -6351,16 +6398,17 @@ fn calculate_geometry(inp: &dyn Inputs, p: &Json) -> Result } } } - let mut messages = vec![format!("Calculated geometry attributes for {}", ds.name)]; + let messages = vec![format!("Calculated geometry attributes for {}", ds.name)]; + let mut losses: Vec = Vec::new(); let unplaced = unplaced.into_inner(); if unplaced > 0 { - messages.push(format!( + losses.push(rustgis_data::loss::LossMessage { code: rustgis_data::loss::LossCode::DroppedCalculationResult, text: format!( "Calculate Geometry Attributes: {unplaced} feature(s) of {} have a place with no longitude/latitude (beyond the poles, or not convertible from {}), and weren't measured", ds.name, to.source().label() - )); + ) }); } - Ok(ToolResult { losses: Vec::new(), output: Output::Update { layer: ds.name.clone(), dataset: out }, messages }) + Ok(ToolResult { losses, output: Output::Update { layer: ds.name.clone(), dataset: out }, messages }) } /// The longest separator CONCATENATE joins values with, in bytes: each value adds one, so a long @@ -8312,6 +8360,7 @@ fn spatial_join_on(inp: &dyn Inputs, p: &Json, threads: Option) -> Result }) .collect(); let mut messages = vec![format!("Spatial Join: {written_features} features joined ({total_matches} matches)")]; + let mut losses: Vec = Vec::new(); // The total of `counts` and the output fields with some, or None without any. let counted = |counts: &[usize]| -> Option<(usize, String)> { let total: usize = counts.iter().sum(); @@ -8320,16 +8369,19 @@ fn spatial_join_on(inp: &dyn Inputs, p: &Json, threads: Option) -> Result }; if let Some((total, names)) = counted(&overflowed) { let (sums, are, were) = if total == 1 { ("sum", "is", "was") } else { ("sums", "are", "were") }; - messages.push(format!("{total} {sums} in {names} {are} past the 64-bit integer range and {were} left empty")); + losses.push(rustgis_data::loss::LossMessage { + code: rustgis_data::loss::LossCode::DroppedCalculationResult, + text: format!("{total} {sums} in {names} {are} past the 64-bit integer range and {were} left empty"), + }); } if let Some((total, names)) = counted(&left_out) { let (numbers, were) = if total == 1 { ("number", "was") } else { ("numbers", "were") }; - messages.push(format!( + losses.push(rustgis_data::loss::LossMessage { code: rustgis_data::loss::LossCode::DroppedValue, text: format!( "{total} matched {numbers} in {names} {were} left out: a whole-number sum takes whole numbers in the 64-bit range, the other rules numbers a decimal holds" - )); + ) }); } messages.extend(rounded_notice(&rounded, &merged_fields)); - Ok(ToolResult { losses: Vec::new(), output: Output::Layer(out), messages }) + Ok(ToolResult { losses, output: Output::Layer(out), messages }) } #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -8576,14 +8628,21 @@ fn zonal_stats_on(inp: &dyn Inputs, p: &Json, threads: Option) -> Result< }, )?; let mut skipped_features = 0usize; + let mut without_polygon = 0usize; let mut skipped_parts = 0usize; let mut failure_details = Vec::new(); for (&r_idx, (stats_by_band, feature_valid, failed_parts, detail)) in target_rows.iter().zip(worked) { let Some(f) = poly_ds.features.get(r_idx) else { continue }; skipped_parts += failed_parts; failure_details.extend(detail); + // A polygon that couldn't be read has lost its statistics; a feature with no polygon, or + // none with an area, has none to lose. if !feature_valid { - skipped_features += 1; + if matches!(&f.geometry, Some(Geometry::Polygon(polys)) if crate::rasterops::has_a_ring(polys)) { + skipped_features += 1; + } else { + without_polygon += 1; + } } let mut attrs = f.attrs.clone(); @@ -8606,11 +8665,21 @@ fn zonal_stats_on(inp: &dyn Inputs, p: &Json, threads: Option) -> Result< let n_features = out.features.len(); let mut messages = vec![format!("Calculated zonal statistics for {n_features} feature(s)")]; + let mut losses: Vec = Vec::new(); if skipped_features > 0 { - messages.push(format!("{skipped_features} feature(s) had invalid geometry")); + losses.push(rustgis_data::loss::LossMessage { + code: rustgis_data::loss::LossCode::DroppedGeometry, + text: format!("{skipped_features} feature(s) had invalid geometry, so their statistics are empty"), + }); + } + if without_polygon > 0 { + messages.push(format!("{without_polygon} feature(s) have no polygon with an area, so their statistics are empty")); } if skipped_parts > 0 { - messages.push(format!("{skipped_parts} polygon part(s) could not be projected onto the raster grid; valid parts were retained")); + losses.push(rustgis_data::loss::LossMessage { + code: rustgis_data::loss::LossCode::DroppedGeometry, + text: format!("{skipped_parts} polygon part(s) could not be projected onto the raster grid; valid parts were retained"), + }); } if !failure_details.is_empty() { for detail in failure_details.iter().take(5) { @@ -8620,7 +8689,7 @@ fn zonal_stats_on(inp: &dyn Inputs, p: &Json, threads: Option) -> Result< messages.push(format!("... and {} more feature failure(s)", failure_details.len() - 5)); } } - Ok(ToolResult { losses: Vec::new(), output: Output::Layer(out), messages }) + Ok(ToolResult { losses, output: Output::Layer(out), messages }) } /// Returns a borrowed dataset when rows match the full dataset in identity order, or a new dataset containing @@ -8918,6 +8987,11 @@ mod tests { Map(HashMap::from([("polys".to_string(), polys), ("pts".to_string(), pts)])) } + /// What a run says: its messages, then its losses, each after its code. + fn said(r: &ToolResult) -> Vec { + r.messages.iter().cloned().chain(r.losses.iter().map(|l| format!("{:?}: {}", l.code, l.text))).collect() + } + fn layer(r: ToolResult) -> Dataset { match r.output { Output::Layer(d) | Output::Table(d) | Output::Update { dataset: d, .. } => d, @@ -9390,7 +9464,7 @@ mod tests { let input: Vec = lines.features.iter().map(|f| format!("{:?}", f.geometry)).collect(); let m = Map(HashMap::from([("lines".to_string(), lines)])); let res = crate::run("simplify", &m, &serde_json::json!({"input": "lines", "tolerance": tolerance})).unwrap(); - let messages = res.messages.clone(); + let messages = said(&res); (layer(res), messages, input) }; let (out, messages, input) = run(true, 1.0); @@ -9420,7 +9494,10 @@ mod tests { assert_eq!(&format!("{:?}", f.geometry), before, "feature {k} at 0"); } assert!(!at_zero.iter().any(|m| m.contains("missing or infinite") || m.contains("past a pole")), "{at_zero:?}"); - assert!(messages.iter().any(|m| m == "Simplify: 1 feature(s) left out: they have no geometry to simplify"), "{messages:?}"); + assert!( + messages.iter().any(|m| m == "DroppedFeature: Simplify: 1 feature(s) left out: they have no geometry to simplify"), + "{messages:?}" + ); let (_, clean, _) = run(false, 1.0); assert_eq!(clean.len(), 1, "{clean:?}"); } @@ -9601,7 +9678,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 note = res.messages.iter().find(|m| m.contains("left out")).cloned(); + 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) }; @@ -9610,7 +9687,7 @@ mod tests { assert_eq!( note.as_deref(), Some( - "Dissolve: 4 feature(s) left out, with their values: no geometry, an empty polygon, or a point or line rather than a polygon" + "DroppedFeature: Dissolve: 4 feature(s) left out, with their values: no geometry, an empty polygon, or a point or line rather than a polygon" ) ); assert_eq!(notice(false), (1, Some(2.0), Some(3.0), None)); @@ -10162,10 +10239,10 @@ mod tests { // it, and the tool says both, each once. let r = run("polys"); assert_eq!( - r.messages[1..], + said(&r)[1..], [ - "Points Along Lines: 1 vertex(es) with a coordinate missing or infinite passed over", - "Points Along Lines: 1 vertex(es) with a latitude past a pole found (latitudes limited to the poles when measuring segments)" + "Points Along Lines: 1 vertex(es) with a latitude past a pole found (latitudes limited to the poles when measuring segments)", + "DroppedGeometry: Points Along Lines: 1 vertex(es) with a coordinate missing or infinite passed over" ], ); let v = layer(r); @@ -10178,7 +10255,10 @@ mod tests { Geometry::Line(vec![vec![c(0.0, 0.0), c(1.0, 0.0), c(f64::INFINITY, 5.0)]]), ]); let r = crate::run("pointsAlongLines", &lossy, &serde_json::json!({"input": "lines", "distance": 10})).unwrap(); - assert_eq!(r.messages[1], "Points Along Lines: 2 vertex(es) with a coordinate missing or infinite passed over"); + assert_eq!( + said(&r).last().map(String::as_str), + Some("DroppedGeometry: Points Along Lines: 2 vertex(es) with a coordinate missing or infinite passed over") + ); assert!(!layer(r).features.is_empty()); // A line whose ends are the same wild coordinate is a ring, closed without a geodesic. let wild = vec![c(1e308, 1e300), c(0.0, -95.0), c(-1e308, 0.0), c(1e308, 1e300)]; @@ -10195,10 +10275,10 @@ mod tests { let params = serde_json::json!({"input": "lines", "distance": 1}); let result = crate::run("pointsAlongLines", &inputs, ¶ms).unwrap(); assert_eq!( - result.messages[1..], + said(&result)[1..], [ - "Points Along Lines: 1 feature(s) without geometry skipped", "Points Along Lines: 2 point feature(s) skipped; only lines and polygon rings produce points", + "DroppedFeature: Points Along Lines: 1 feature(s) without geometry skipped", ] ); assert!(!layer(result).features.is_empty()); @@ -10971,7 +11051,12 @@ mod tests { // A latitude past 90° has no place: no measures, and a notice; a missing coordinate is // measured as before, and said nothing of. let beyond = bad.is_finite(); - assert_eq!(r.messages.iter().any(|m| m.contains("weren't measured")), beyond, "{bad:?}: {:?}", r.messages); + assert_eq!( + said(&r).iter().any(|m| m.starts_with("DroppedCalculationResult: ") && m.contains("weren't measured")), + beyond, + "{bad:?}: {:?}", + said(&r) + ); let out = layer(r); assert_eq!(out.value(0, 0).is_null(), beyond, "{bad:?}"); } @@ -11017,7 +11102,7 @@ mod tests { &serde_json::json!({"input": "parcels"}), ) .unwrap(); - let messages = r.messages.clone(); + let messages = said(&r); let out = layer(r); ((0..out.features.len()).map(|i| (out.value(i, 0).clone(), out.value(i, 1).clone())).collect::>(), messages) }; @@ -11389,8 +11474,7 @@ mod tests { pts.push(None, vec![Value::Int(-1)]); let m = Map(HashMap::from([("p".to_string(), pts)])); let r = crate::run("buffer", &m, &serde_json::json!({"input": "p", "distance": 5})).unwrap(); - assert_eq!(r.messages.len(), 2); - assert_eq!(r.messages.get(1).map(String::as_str), Some("1 of 301 features lack geometry, so they have no buffer")); + assert_eq!(said(&r)[1..], ["DroppedFeature: 1 of 301 features lack geometry, so they have no buffer"]); let b = layer(r); assert_eq!(b.features.len(), 300); for (k, f) in b.features.iter().enumerate() { @@ -11398,8 +11482,8 @@ mod tests { assert_eq!(f.geometry, geodesic_buffer(&Geometry::Point(at(k as i64)), 5_000.0), "feature {k}"); } let r = crate::run("buffer", &m, &serde_json::json!({"input": "p", "distance": 5, "dissolve": "All"})).unwrap(); - assert_eq!(r.messages.len(), 2); - assert_eq!(r.messages.get(1).map(String::as_str), Some("1 of 301 features lack geometry, so they have no buffer")); + // Dissolved, a feature without geometry adds nothing to lose. + assert_eq!(said(&r)[1..], ["1 of 301 features lack geometry, so they have no buffer"]); assert_eq!(layer(r).features.len(), 1); // Points at a negative distance have nothing left, and say so. let r = crate::run("buffer", &clean, &serde_json::json!({"input": "p", "distance": -5})).unwrap(); @@ -11872,20 +11956,26 @@ mod tests { let stations = Geometry::MultiPoint(vec![Coord::new(-75.0, 40.0), Coord::new(-74.99, 40.0), Coord::new(-75.0, 40.01), gap, far]); for group in ["All", "None"] { let res = run(vec![Some(stations.clone()), Some(Geometry::Point(gap)), None], group).unwrap_or_else(|e| panic!("{group}: {e}")); - let all = res.messages.join(" | "); + let all = said(&res).join(" | "); assert!( all.contains( "3 vertex(es) passed over: a coordinate missing or infinite, or so far out that the hull can't take it (past about 9 million degrees)" ), "{group}: {all}" ); - assert!(all.contains("2 feature(s) skipped: no geometry, or no point it can use"), "{group}: {all}"); + assert!( + // Coded only when each feature has a hull of its own to lose. + all.contains(&format!( + "{}Minimum Bounding Geometry: 2 feature(s) skipped: no geometry, or no point it can use", + if group == "None" { "DroppedFeature: " } else { "" } + )), + "{group}: {all}" + ); let Output::Layer(out) = res.output else { panic!("{group}: not a layer") }; assert_eq!(out.features.len(), 1, "{group}: a hull for the stations only"); let clean = run(vec![Some(Geometry::Point(Coord::new(0.0, 0.0))), Some(Geometry::Point(Coord::new(1.0, 1.0)))], group) - .unwrap_or_else(|e| panic!("{group}: {e}")) - .messages - .join(" | "); + .unwrap_or_else(|e| panic!("{group}: {e}")); + let clean = said(&clean).join(" | "); assert!(!clean.contains("passed over") && !clean.contains("skipped"), "{group}: {clean}"); } for group in ["All", "None"] { @@ -11964,9 +12054,15 @@ mod tests { for dissolve in ["None", "All"] { let params = serde_json::json!({"input": "l", "distance": 1, "units": "Meters", "dissolve": dissolve}); let res = crate::run("buffer", &m, ¶ms).unwrap_or_else(|e| panic!("{e}")); - let note = - res.messages.iter().find(|m| m.starts_with("1 of 1 features' buffers have outline edges left with fewer points")); - assert_eq!(note.is_some(), coarse, "dissolve {dissolve}: {:?}", res.messages); + let note = res + .losses + .iter() + .find(|l| { + l.code == rustgis_data::loss::LossCode::ApproximatedCurve + && l.text.starts_with("1 of 1 features' buffers have outline edges left with fewer points") + }) + .map(|l| &l.text); + assert_eq!(note.is_some(), coarse, "dissolve {dissolve}: {:?}", said(&res)); // The note names both reasons an edge can be left coarse. assert!( note.is_none_or(|m| m.contains("the points a ring may add ran out") && m.contains("halved as many times as it may be")), @@ -13048,7 +13144,14 @@ mod tests { let run = |p: serde_json::Value| crate::run("xyTableToPoint", &m, &p); let r = run(serde_json::json!({"input": "stops", "x": "lon", "y": "lat"})).unwrap(); - assert_eq!(r.messages.len(), 2, "{:?}", r.messages); + // Rows without numbers lose nothing; the one off the globe loses its place. + assert_eq!( + said(&r)[1..], + [ + "3 of 7 rows have no numbers in both fields; they are in the table without a point", + "DroppedGeometry: 1 of 7 rows have coordinates with no place in EPSG:4326; they are in the table without a point" + ] + ); let out = layer(r); assert_eq!((out.name.as_str(), out.geometry_type), ("stops_Points", GeometryType::Point)); assert_eq!((out.fields.len(), out.features.len()), (3, 7)); @@ -13083,7 +13186,7 @@ mod tests { polar.push(None, vec![Value::Float(0.0), Value::Float(3.0e7)]); let m2 = Map(HashMap::from([("polar".to_string(), polar)])); let r = crate::run("xyTableToPoint", &m2, &serde_json::json!({"input": "polar", "x": "e", "y": "n", "crs": "EPSG:3857"})).unwrap(); - assert!(r.messages.iter().any(|m| m.starts_with("1 of 2 rows")), "{:?}", r.messages); + assert!(said(&r).iter().any(|m| m.starts_with("DroppedGeometry: 1 of 2 rows")), "{:?}", said(&r)); assert!(layer(r).features[1].geometry.is_none()); // Points in longitude/latitude are held there, with no system of their own, as before. let lonlat = layer(run(serde_json::json!({"input": "stops", "x": "lon", "y": "lat", "crs": "EPSG:4326"})).unwrap()); @@ -14377,8 +14480,7 @@ mod tests { assert_eq!(res.messages.len(), 1, "{:?}", res.messages); zones.push(Some(sq(7.0, 0.0, 1.0)), vec![at("2026-03-05T14:30:00+02:00"), Value::Null]); let res = crate::run("update", &m(zones), &serde_json::json!({"input": "parcels", "update": "zones"})).unwrap(); - assert_eq!(res.messages.get(1).map(String::as_str), Some("Update: 'd' holds dates, so 1 update feature kept only its day")); - assert_eq!(res.messages.len(), 2); + assert_eq!(said(&res)[1..], ["DroppedTime: Update: 'd' holds dates, so 1 update feature kept only its day"]); } #[test] @@ -14411,11 +14513,7 @@ mod tests { let m = Map(HashMap::from([("parcels".to_string(), parcels), ("zones".to_string(), zones)])); let res = crate::run("update", &m, &serde_json::json!({"input": "parcels", "update": "zones"})).unwrap(); // "seven" isn't a whole number: null, and said. - assert_eq!( - res.messages.get(1).map(String::as_str), - Some("Update: 'n' is null in 1 update feature, whose value isn't a Long value") - ); - assert_eq!(res.messages.len(), 2); + assert_eq!(said(&res)[1..], ["DroppedValue: Update: 'n' is null in 1 update feature, whose value isn't a Long value"]); let out = layer(res); let attrs: Vec<&[Value]> = out.features.iter().skip(1).map(|f| f.attrs.as_slice()).collect(); assert_eq!( @@ -15022,9 +15120,9 @@ mod tests { let m = Map(HashMap::from([("input".to_string(), input), ("clean".to_string(), clean), ("masks".to_string(), masks)])); let lossy = clip(&m, &serde_json::json!({"input": "input", "clip": "masks"})).unwrap(); assert!( - lossy.messages.iter().any(|m| m == "Clip: 3 feature(s) of 'input' left out: they have no geometry to clip"), + said(&lossy).iter().any(|m| m == "DroppedFeature: Clip: 3 feature(s) of 'input' left out: they have no geometry to clip"), "{:?}", - lossy.messages + said(&lossy) ); let clean = clip(&m, &serde_json::json!({"input": "clean", "clip": "masks"})).unwrap(); assert!(!clean.messages.iter().any(|m| m.contains("no geometry")), "{:?}", clean.messages); @@ -16614,13 +16712,26 @@ mod tests { let mut zones = Dataset::new("zones", GeometryType::Polygon, vec![]); zones.push(Some(sq(0., 0., 2.)), vec![]); zones.push(None, vec![]); + // A ring of two points has no area; one with a point that isn't finite can't be read, and + // its area is lost. + zones.push(Some(Geometry::Polygon(vec![vec![vec![Coord::new(0., 0.), Coord::new(1., 0.)]]])), vec![]); + zones.push( + Some(Geometry::Polygon(vec![vec![vec![Coord::new(0., 0.), Coord::new(f64::NAN, 0.), Coord::new(1., 1.), Coord::new(0., 0.)]]])), + vec![], + ); let m = RasterMap { datasets: HashMap::from([("zones".into(), zones)]), rasters: HashMap::from([("cover".into(), &raster)]) }; let p = serde_json::json!({"raster":"cover", "zones":"zones", "unit":"m2"}); let one = tabulate_area::run_on(&m, &p, Some(1)).unwrap(); let many = tabulate_area::run_on(&m, &p, Some(3)).unwrap(); assert_eq!(one.messages, many.messages); assert!(!one.messages.iter().any(|m| m.contains("uses the raster projection"))); - assert!(one.messages.iter().any(|m| m.starts_with("1 zone feature(s)"))); + assert!(said(&one).iter().any(|m| m == "2 zone feature(s) had no polygon with an area and were excluded"), "{:?}", said(&one)); + assert!( + said(&one).iter().any(|m| m == "DroppedGeometry: 1 zone feature(s) had invalid polygon geometry and were excluded"), + "{:?}", + said(&one) + ); + assert_eq!(one.losses, many.losses); let (Output::Table(a), Output::Table(b)) = (one.output, many.output) else { panic!("tables") }; assert_eq!(a.features, b.features); let expected = @@ -17018,7 +17129,12 @@ mod tests { rasters: HashMap::from([("elev".to_string(), &raster)]), }; let res_drop_ext = crate::run("zonalStats", &m_drop_ext, &serde_json::json!({"raster": "elev", "polygons": "drop_ext"})).unwrap(); - assert!(res_drop_ext.messages.iter().any(|m| m.contains("failed coordinate transformation") || m.contains("invalid geometry"))); + // Its exterior has no area, so nothing is lost: said plain. + assert!( + said(&res_drop_ext).iter().any(|m| m == "1 feature(s) have no polygon with an area, so their statistics are empty"), + "{:?}", + said(&res_drop_ext) + ); let out_drop_ext = layer(res_drop_ext); let drop_count_idx = out_drop_ext.field_index("elev_count").unwrap(); let drop_mean_idx = out_drop_ext.field_index("elev_mean").unwrap(); @@ -17041,7 +17157,7 @@ mod tests { rasters: HashMap::from([("elev".to_string(), &raster)]), }; let res_nan_ext = crate::run("zonalStats", &m_nan_ext, &serde_json::json!({"raster": "elev", "polygons": "nan_ext"})).unwrap(); - assert!(res_nan_ext.messages.iter().any(|m| m.contains("failed coordinate transformation") || m.contains("invalid geometry"))); + assert!(said(&res_nan_ext).iter().any(|m| m.contains("failed coordinate transformation") || m.contains("invalid geometry"))); let out_nan_ext = layer(res_nan_ext); let nan_count_idx = out_nan_ext.field_index("elev_count").unwrap(); let nan_mean_idx = out_nan_ext.field_index("elev_mean").unwrap(); @@ -17228,7 +17344,7 @@ mod tests { }; let res = crate::run("zonalStats", &m, &serde_json::json!({"raster": "elev", "polygons": "mixed_zones"})).unwrap(); - let messages = res.messages.clone(); + let messages = said(&res); let out = layer(res); assert_eq!(out.features.len(), 3); @@ -17248,7 +17364,10 @@ mod tests { assert!(out.value(2, mean_idx).as_f64().is_some()); // Messages must explicitly report feature 102 failure - assert!(messages.iter().any(|m| m.contains("1 feature(s) had invalid geometry"))); + assert!( + messages.iter().any(|m| m == "DroppedGeometry: 1 feature(s) had invalid geometry, so their statistics are empty"), + "{messages:?}" + ); assert!(messages.iter().any(|m| m.contains("feature 102") && m.contains("fewer than 3 vertices"))); } diff --git a/crates/analysis/src/tools/check_geometry.rs b/crates/analysis/src/tools/check_geometry.rs index cf109466fc..cc2269e3a5 100644 --- a/crates/analysis/src/tools/check_geometry.rs +++ b/crates/analysis/src/tools/check_geometry.rs @@ -154,9 +154,9 @@ fn run_with_room( } out.features = list.into(); - let mut messages = notices(&tally, &problem_field); + let (mut messages, losses) = notices(&tally, &problem_field); messages.extend(notes); - Ok(ToolResult { losses: Vec::new(), output: Output::Layer(out), messages }) + Ok(ToolResult { losses, output: Output::Layer(out), messages }) } /// The memory an output row copying `attrs` (`width` of them, of `out_width` values in the @@ -183,17 +183,22 @@ pub(super) fn row_bytes(attrs: &[Value], width: usize, out_width: usize, texts: } /// The run's notices: the result in one line, then one notice per kind of feature not checked -/// fully or not copied whole. `problem` is the output's problem field. -fn notices(t: &Tally, problem: &str) -> Vec { +/// fully or not copied whole, and the losses among them. `problem` is the output's problem field. +fn notices(t: &Tally, problem: &str) -> (Vec, Vec) { + use rustgis_data::loss::{LossCode, LossMessage}; let mut messages = vec![summary(t.found, t.checked, &t.counts)]; + let mut losses = Vec::new(); let they = |n: usize| if n == 1 { "it is" } else { "they are" }; let non_finite = Code::ALL.iter().position(|c| *c == Code::NonFiniteCoordinate).and_then(|k| t.counts.get(k)).copied().unwrap_or(0); if non_finite > 0 { - messages.push(format!( - "{TOOL}: {} with non-finite coordinates {} written without geometry", - features(non_finite), - if non_finite == 1 { "is" } else { "are" } - )); + losses.push(LossMessage { + code: LossCode::DroppedGeometry, + text: format!( + "{TOOL}: {} with non-finite coordinates {} written without geometry", + features(non_finite), + if non_finite == 1 { "is" } else { "are" } + ), + }); } if t.work_limit > 0 { messages.push(format!( @@ -224,12 +229,15 @@ fn notices(t: &Tally, problem: &str) -> Vec { )); } if t.extra > 0 { - messages.push(format!( - "{TOOL}: {} had more attribute values than the layer has fields; the extra values aren't in the output", - features(t.extra) - )); + losses.push(LossMessage { + code: LossCode::DroppedExtraAttributes, + text: format!( + "{TOOL}: {} had more attribute values than the layer has fields; the extra values aren't in the output", + features(t.extra) + ), + }); } - messages + (messages, losses) } /// "1 feature", "2 features". @@ -308,14 +316,14 @@ mod tests { #[test] fn features_not_checked_fully_are_counted_by_reason() { assert_eq!( - notices(&too_complex(0, 1, 0), "problem"), + notices(&too_complex(0, 1, 0), "problem").0, [ "Check Geometry: 1 of 9 features has problems (too_complex: 1)", "Check Geometry: some rings or parts of 1 feature could not be checked against each other, because geo's relate operation failed on them; it is in the output as too_complex", ] ); assert_eq!( - notices(&too_complex(2, 3, 1), "problem"), + notices(&too_complex(2, 3, 1), "problem").0, [ "Check Geometry: 4 of 9 features have problems (too_complex: 4)", "Check Geometry: 2 features could not be checked fully (too complex for the work limit); they are in the output as too_complex", @@ -326,7 +334,7 @@ mod tests { for n in [1, 2] { memory.memory = n; assert_eq!( - notices(&memory, "problem").get(1).map(String::as_str), + notices(&memory, "problem").0.get(1).map(String::as_str), Some(if n == 1 { "Check Geometry: 1 feature could not be checked fully, because there wasn't enough memory to check it; it is in the output as too_complex" } else { @@ -336,7 +344,7 @@ mod tests { } let t = Tally { checked: 2, found: 2, unrelated: 2, ..Tally::default() }; assert_eq!( - notices(&t, "problem_2").last().map(String::as_str), + notices(&t, "problem_2").0.last().map(String::as_str), Some( "Check Geometry: the rings or parts of 2 features weren't all checked against each other, because some of their rings or parts already have problems of their own (see problem_2)" ) diff --git a/crates/analysis/src/tools/repair_geometry.rs b/crates/analysis/src/tools/repair_geometry.rs index bb240c43bf..c90324a10c 100644 --- a/crates/analysis/src/tools/repair_geometry.rs +++ b/crates/analysis/src/tools/repair_geometry.rs @@ -237,17 +237,44 @@ fn run_with_room( let units = if crs.is_geographic() { "degrees of longitude or latitude".to_string() } else { format!("units of {}", crs.label()) }; let mut messages = notices(&tally, &field, rule, &units); messages.extend(notes); - let losses = (tally.extra > 0) - .then(|| rustgis_data::loss::LossMessage { - code: rustgis_data::loss::LossCode::DroppedExtraAttributes, + let losses = losses(&tally); + Ok(ToolResult { output: Output::Layer(out), messages, losses }) +} + +/// The notice for features that couldn't be repaired and are written without geometry, of the +/// kinds `lost` picks, with the count of each: `None` when there are none. +fn without_geometry(t: &Tally, lost: bool) -> Option { + let kinds = Gone::ALL.iter().zip(t.gone).filter(|(g, n)| *n > 0 && (**g != Gone::Null) == lost); + let gone: usize = kinds.clone().map(|(_, n)| n).sum(); + let by: Vec = kinds.map(|(g, n)| format!("{}: {n}", g.as_str())).collect(); + (gone > 0).then(|| { + format!( + "{TOOL}: {} couldn't be repaired and {} written without geometry ({})", + features(gone), + if gone == 1 { "is" } else { "are" }, + by.join(", ") + ) + }) +} + +/// The run's losses: features whose geometry is left out, and attribute values past the layer's +/// fields. A feature without geometry to begin with loses none. +fn losses(t: &Tally) -> Vec { + use rustgis_data::loss::{LossCode, LossMessage}; + let mut losses = Vec::new(); + if let Some(text) = without_geometry(t, true) { + losses.push(LossMessage { code: LossCode::DroppedGeometry, text }); + } + if t.extra > 0 { + losses.push(LossMessage { + code: LossCode::DroppedExtraAttributes, text: format!( "{TOOL}: {} had more attribute values than the layer has fields; the extra values aren't in the output", - features(tally.extra) + features(t.extra) ), - }) - .into_iter() - .collect(); - Ok(ToolResult { output: Output::Layer(out), messages, losses }) + }); + } + losses } /// The run's notices: the result in one line, then one notice per kind of feature not repaired, @@ -256,18 +283,9 @@ fn run_with_room( /// split, coordinates moved. `field` is the output's repairs field. fn notices(t: &Tally, field: &str, rule: Rule, units: &str) -> Vec { let mut messages = vec![summary(t)]; + messages.extend(without_geometry(t, false)); let is = |n: usize| if n == 1 { "is" } else { "are" }; let was = |n: usize| if n == 1 { "was" } else { "were" }; - let gone: usize = t.gone.iter().sum(); - if gone > 0 { - let by: Vec = Gone::ALL.iter().zip(t.gone).filter(|(_, n)| *n > 0).map(|(g, n)| format!("{}: {n}", g.as_str())).collect(); - messages.push(format!( - "{TOOL}: {} couldn't be repaired and {} written without geometry ({})", - features(gone), - is(gone), - by.join(", ") - )); - } if t.work > 0 { messages.push(format!( "{TOOL}: {} {} too complex to repair within the work limit and {} written unchanged, with too_complex in {field}", diff --git a/crates/analysis/src/tools/tabulate_area.rs b/crates/analysis/src/tools/tabulate_area.rs index 1289cd46eb..dc8bd854f7 100644 --- a/crates/analysis/src/tools/tabulate_area.rs +++ b/crates/analysis/src/tools/tabulate_area.rs @@ -1,5 +1,6 @@ //! Class-by-zone tables on the same cell-centre masks as Zonal Statistics. use super::*; +use rustgis_data::loss::{LossCode, LossMessage}; use rustgis_data::{Measure, raster::Raster}; /// Counts or measures every class in each zone. One zone's mask is built as one step without @@ -88,11 +89,12 @@ pub(super) fn run_on(inp: &dyn Inputs, p: &Json, threads: Option) -> Resu let name = unique_field(&out, &format!("class_{class}")); out.fields.push(Field::new(name, if count { FieldType::Integer } else { FieldType::Double })); } - let (mut nodata, mut invalid, mut parts, mut empty) = (0u64, 0usize, 0usize, 0usize); + let (mut nodata, mut invalid, mut unreadable, mut parts, mut empty) = (0u64, 0usize, 0usize, 0usize, 0usize); for (group, total) in groups.into_iter().zip(totals) { crate::control::check()?; nodata += total.nodata; invalid += total.invalid; + unreadable += total.unreadable; parts += total.parts; empty += usize::from(total.values.iter().all(|v| *v == 0.0)); let mut attrs = group.key; @@ -111,15 +113,25 @@ pub(super) fn run_on(inp: &dyn Inputs, p: &Json, threads: Option) -> Resu messages.push(format!("{nodata} NoData or non-finite cell(s) inside zones were excluded (counted once per zone)")); } if invalid > 0 { - messages.push(format!("{invalid} zone feature(s) had missing or invalid polygon geometry and were excluded")); + messages.push(format!("{invalid} zone feature(s) had no polygon with an area and were excluded")); + } + let mut losses = Vec::new(); + if unreadable > 0 { + losses.push(LossMessage { + code: LossCode::DroppedGeometry, + text: format!("{unreadable} zone feature(s) had invalid polygon geometry and were excluded"), + }); } if parts > 0 { - messages.push(format!("{parts} polygon part(s) could not be projected onto the raster grid; valid parts were retained")); + losses.push(LossMessage { + code: LossCode::DroppedGeometry, + text: format!("{parts} polygon part(s) could not be projected onto the raster grid; valid parts were retained"), + }); } if empty > 0 { messages.push(format!("{empty} zone(s) contained no valid raster cell centres; their class values are zero")); } - Ok(ToolResult { losses: Vec::new(), output: Output::Table(out), messages }) + Ok(ToolResult { losses, output: Output::Table(out), messages }) } /// All finite valid band values, sorted numerically. The wide table has Pivot Table's column @@ -158,6 +170,8 @@ struct Totals { values: Vec, nodata: u64, invalid: usize, + /// Zone features whose polygon couldn't be read. + unreadable: usize, parts: usize, } @@ -172,7 +186,7 @@ fn summarize( classes: &HashMap, areas: &CellAreas<'_>, ) -> Result { - let mut total = Totals { values: vec![0.0; classes.len()], nodata: 0, invalid: 0, parts: 0 }; + let mut total = Totals { values: vec![0.0; classes.len()], nodata: 0, invalid: 0, unreadable: 0, parts: 0 }; let mut polygons = Vec::new(); for &row in rows { crate::control::check()?; @@ -181,9 +195,12 @@ fn summarize( Some(Geometry::Polygon(p)) => crate::rasterops::validated_polygon_parts(p).ok(), _ => None, }; - match valid { - Some(p) => polygons.extend(p), - None => total.invalid += 1, + // A polygon that can't be read is lost to its zone; a feature with no polygon, or none + // with an area, has no area to lose. + match (valid, shape) { + (Some(p), _) => polygons.extend(p), + (None, Some(Geometry::Polygon(p))) if crate::rasterops::has_a_ring(p) => total.unreadable += 1, + (None, _) => total.invalid += 1, } } let mut failures = Vec::new(); diff --git a/crates/analysis/tests/integration/check_geometry.rs b/crates/analysis/tests/integration/check_geometry.rs index d25182dea0..2ee008203a 100644 --- a/crates/analysis/tests/integration/check_geometry.rs +++ b/crates/analysis/tests/integration/check_geometry.rs @@ -20,6 +20,11 @@ impl Inputs for Layer { type Ring<'a> = &'a [(f64, f64)]; +/// What a run says: its messages, then its losses, each after its code. +fn said(r: &ToolResult) -> Vec { + r.messages.iter().cloned().chain(r.losses.iter().map(|l| format!("{:?}: {}", l.code, l.text))).collect() +} + fn layer(ty: GeometryType) -> Layer { Layer { ds: Dataset::new("input", ty, vec![Field::new("name", FieldType::Text)]), selected: vec![] } } @@ -323,10 +328,10 @@ fn non_finite_coordinates_are_written_without_geometry() { assert!(ds.extent().is_empty(), "nothing to spoil the extent"); assert_eq!(text(ds, 0, "detail"), "2 non-finite coordinates, the first in exterior ring of part 1; written without geometry"); assert_eq!( - r.messages, + said(&r), [ "Check Geometry: 1 of 1 feature has problems (non_finite_coordinate: 1)", - "Check Geometry: 1 feature with non-finite coordinates is written without geometry", + "DroppedGeometry: Check Geometry: 1 feature with non-finite coordinates is written without geometry", ] ); // Several: plural. A bowtie in another part is still found; the parts aren't related, which @@ -338,11 +343,11 @@ fn non_finite_coordinates_are_written_without_geometry() { assert!(ds.features.iter().all(|f| f.geometry.is_none())); assert_eq!(text(ds, 2, "problem"), "non_finite_coordinate, self_intersection"); assert_eq!( - r.messages, + said(&r), [ "Check Geometry: 3 of 3 features have problems (non_finite_coordinate: 3, self_intersection: 1)", - "Check Geometry: 3 features with non-finite coordinates are written without geometry", "Check Geometry: the rings or parts of 1 feature weren't all checked against each other, because some of their rings or parts already have problems of their own (see problem)", + "DroppedGeometry: Check Geometry: 3 features with non-finite coordinates are written without geometry", ] ); } @@ -494,8 +499,8 @@ fn extra_attribute_values_are_reported() { let ds = dataset(&r); assert_eq!(ds.features[0].attrs.len(), 3); assert_eq!( - r.messages[1], - "Check Geometry: 1 feature had more attribute values than the layer has fields; the extra values aren't in the output" + said(&r)[1], + "DroppedExtraAttributes: Check Geometry: 1 feature had more attribute values than the layer has fields; the extra values aren't in the output" ); } diff --git a/crates/analysis/tests/integration/repair_geometry.rs b/crates/analysis/tests/integration/repair_geometry.rs index 13ce598810..712d64bbc1 100644 --- a/crates/analysis/tests/integration/repair_geometry.rs +++ b/crates/analysis/tests/integration/repair_geometry.rs @@ -23,6 +23,11 @@ impl Inputs for Layer { type Ring<'a> = &'a [(f64, f64)]; +/// What a run says: its messages, then its losses, each after its code. +fn said(r: &ToolResult) -> Vec { + r.messages.iter().cloned().chain(r.losses.iter().map(|l| format!("{:?}: {}", l.code, l.text))).collect() +} + fn layer(ty: GeometryType) -> Layer { Layer { ds: Dataset::new("input", ty, vec![Field::new("name", FieldType::Text)]), selected: vec![] } } @@ -446,16 +451,18 @@ fn a_mixed_layer_says_what_was_done_with_counts() { let without: Vec = ds.features.iter().map(|f| f.geometry.is_none()).collect(); assert_eq!(without, [false, false, false, true, false, false, false, false, true, true]); assert_eq!( - r.messages, + said(&r), [ "Repair Geometry: repaired 6 of 10 features (too_few_points: 1, ring_not_closed: 1, self_intersection: 1, hole_outside_shell: 1, disconnected_interior: 1, parts_overlap: 1)", - "Repair Geometry: 3 features couldn't be repaired and are written without geometry (null_geometry: 1, non_finite_coordinate: 1, no_area: 1)", + // A feature without geometry to begin with loses none. + "Repair Geometry: 1 feature couldn't be repaired and is written without geometry (null_geometry: 1)", "Repair Geometry: 1 ring or part with too few distinct points or no area was dropped from 1 feature", "Repair Geometry: holes not inside their exterior ring were taken out of 1 feature; what of a hole is inside its exterior ring stays a hole", "Repair Geometry: the parts that overlapped or touched along a line were merged in 1 feature", "Repair Geometry: 1 feature whose interior was cut into pieces by rings touching at points is written with each piece as a part of its own", // The hole outside makes the largest extent, 21 across: a grid step of 2^-26, five of them. "Repair Geometry: 4 features were rebuilt by geo's boolean overlay, which rounds coordinates to a fine grid: they may have moved by up to 7.5e-8 degrees of longitude or latitude, and vertices in the middle of straight edges were left out", + "DroppedGeometry: Repair Geometry: 2 features couldn't be repaired and are written without geometry (non_finite_coordinate: 1, no_area: 1)", ] ); } diff --git a/crates/analysis/tests/integration/spatial_join_merge.rs b/crates/analysis/tests/integration/spatial_join_merge.rs index 8a9471974c..9154463434 100644 --- a/crates/analysis/tests/integration/spatial_join_merge.rs +++ b/crates/analysis/tests/integration/spatial_join_merge.rs @@ -41,6 +41,11 @@ fn column(ds: &Dataset, name: &str) -> Vec { let i = field(ds, name); ds.features.iter().map(|f| f.attrs[i].clone()).collect() } +/// What a run says: its messages, then its losses, each after its code. +fn said(r: &ToolResult) -> Vec { + r.messages.iter().cloned().chain(r.losses.iter().map(|l| format!("{:?}: {}", l.code, l.text))).collect() +} + fn layer(r: ToolResult) -> Dataset { match r.output { Output::Layer(d) => d, @@ -108,13 +113,13 @@ fn rounded(n: &str, fields: &str) -> String { fn min_and_max_pick_whole_numbers_exactly_in_any_order() { let layers = Layers::default().with(zones()).with(points()); let res = join(&layers, json!([{"field": "n", "rule": "max"}, {"field": "m", "rule": "max"}])); - assert_eq!(res.messages, [JOINED]); + assert_eq!(said(&res), [JOINED]); let out = layer(res); let big = Value::Int(TWO_53 + 1); assert_eq!(column(&out, "join_n"), [big.clone(), big.clone(), big.clone(), Value::Int(3)]); assert_eq!(column(&out, "join_m"), [Value::Int(i64::MAX), Value::Int(6), Value::Int(-1), Value::Int(4)]); let res = join(&layers, json!([{"field": "n", "rule": "min"}, {"field": "m", "rule": "min"}])); - assert_eq!(res.messages, [JOINED]); + assert_eq!(said(&res), [JOINED]); let out = layer(res); let low = Value::Int(TWO_53); assert_eq!(column(&out, "join_n"), [low.clone(), low, big, Value::Int(1)]); @@ -150,7 +155,7 @@ fn min_and_max_pick_whole_numbers_exactly_in_any_order() { fn an_integer_sum_past_the_64_bit_range_is_empty_and_said_so() { let layers = Layers::default().with(zones()).with(points()); let res = join(&layers, json!([{"field": "n", "rule": "sum"}, {"field": "m", "rule": "sum"}])); - assert_eq!(res.messages, [JOINED, "2 sums in join_m are past the 64-bit integer range and were left empty"]); + assert_eq!(said(&res), [JOINED, "DroppedCalculationResult: 2 sums in join_m are past the 64-bit integer range and were left empty"]); let out = layer(res); assert_eq!(column(&out, "join_m"), [Value::Null, Value::Int(11), Value::Null, Value::Int(6)]); // Sums past 2^53 that fit 64 bits are exact. @@ -160,13 +165,16 @@ fn an_integer_sum_past_the_64_bit_range_is_empty_and_said_so() { let p = json!({"target": "zones", "join": "points", "merge": [{"field": "m", "rule": "sum"}]}); let res = rustgis_analysis::run("spatialJoin", &only_a, &p).unwrap(); assert_eq!( - res.messages, - ["Spatial Join: 4 features joined (2 matches)", "1 sum in join_m is past the 64-bit integer range and was left empty"] + said(&res), + [ + "Spatial Join: 4 features joined (2 matches)", + "DroppedCalculationResult: 1 sum in join_m is past the 64-bit integer range and was left empty" + ] ); // Within the range, and the other rules: no notice. let clean = Layers::default().with(zones()).with(points()).select("points", &[2, 3, 6, 7]); let p = json!({"target": "zones", "join": "points", "merge": [{"field": "m", "rule": "sum"}, {"field": "n", "rule": "sum"}]}); - assert_eq!(rustgis_analysis::run("spatialJoin", &clean, &p).unwrap().messages, ["Spatial Join: 4 features joined (4 matches)"]); + assert_eq!(said(&rustgis_analysis::run("spatialJoin", &clean, &p).unwrap()), ["Spatial Join: 4 features joined (4 matches)"]); // Whole numbers written as text in the integer field are added exactly, not as decimals. let mut pts = points(); let m = field(&pts, "m"); @@ -204,11 +212,11 @@ fn an_integer_sum_is_checked_once_and_says_what_it_leaves_out() { let layers = Layers::default().with(zones()).with(pts); let res = join(&layers, json!([{"field": "n", "rule": "first"}, {"field": "m", "rule": "sum"}])); assert_eq!( - res.messages, + said(&res), [ "Spatial Join: 4 features joined (10 matches)", - "1 sum in join_m is past the 64-bit integer range and was left empty", - "3 matched numbers in join_m were left out: a whole-number sum takes whole numbers in the 64-bit range, the other rules numbers a decimal holds" + "DroppedCalculationResult: 1 sum in join_m is past the 64-bit integer range and was left empty", + "DroppedValue: 3 matched numbers in join_m were left out: a whole-number sum takes whole numbers in the 64-bit range, the other rules numbers a decimal holds" ] ); assert_eq!(column(&layer(res), "join_m"), [Value::Int(i64::MAX), Value::Null, Value::Null, Value::Int(4)]); @@ -216,10 +224,10 @@ fn an_integer_sum_is_checked_once_and_says_what_it_leaves_out() { let layers = layers.select("points", &[6, 7]); let p = json!({"target": "zones", "join": "points", "merge": [{"field": "m", "rule": "sum"}]}); assert_eq!( - rustgis_analysis::run("spatialJoin", &layers, &p).unwrap().messages, + said(&rustgis_analysis::run("spatialJoin", &layers, &p).unwrap()), [ "Spatial Join: 4 features joined (2 matches)", - "1 matched number in join_m was left out: a whole-number sum takes whole numbers in the 64-bit range, the other rules numbers a decimal holds" + "DroppedValue: 1 matched number in join_m was left out: a whole-number sum takes whole numbers in the 64-bit range, the other rules numbers a decimal holds" ] ); } @@ -229,7 +237,7 @@ fn a_whole_mean_a_decimal_cant_hold_is_said_to_be_rounded() { let layers = Layers::default().with(zones()).with(points()); // C's mean of n, 2^53 + 1, is whole and rounded; A's and B's, 2^53 + 0.5, are decimals anyway. let res = join(&layers, json!([{"field": "d", "rule": "mean"}, {"field": "m", "rule": "mean"}, {"field": "n", "rule": "mean"}])); - assert_eq!(res.messages, [JOINED.to_string(), rounded("1 result", "join_n")]); + assert_eq!(said(&res), [JOINED.to_string(), rounded("1 result", "join_n")]); let out = layer(res); let two_53 = Value::Float(9_007_199_254_740_992.0); assert_eq!(column(&out, "join_n"), [two_53.clone(), two_53.clone(), two_53, Value::Float(2.0)]); @@ -250,7 +258,7 @@ fn a_whole_mean_a_decimal_cant_hold_is_said_to_be_rounded() { } let layers = Layers::default().with(zones()).with(pts); let res = join(&layers, json!([{"field": "n", "rule": "mean"}])); - assert_eq!(res.messages, [JOINED.to_string(), rounded("2 results", "join_n")]); + assert_eq!(said(&res), [JOINED.to_string(), rounded("2 results", "join_n")]); // B's mean of 2^53 + 1 and 2^53 + 2, 2^53 + 1.5, isn't whole: no notice, though its decimal is // a whole number. C's of 2^53 + 1 three times is rounded once, to 2^53, not from a rounded sum // (3 * 2^53 + 4, over 3, would give 2^53 + 2). @@ -266,13 +274,13 @@ fn a_whole_mean_a_decimal_cant_hold_is_said_to_be_rounded() { pts.push(fourth.geometry, fourth.attrs); let layers = Layers::default().with(zones()).with(pts); let res = join(&layers, json!([{"field": "n", "rule": "mean"}])); - assert_eq!(res.messages, ["Spatial Join: 4 features joined (10 matches)".to_string(), rounded("1 result", "join_n")]); + assert_eq!(said(&res), ["Spatial Join: 4 features joined (10 matches)".to_string(), rounded("1 result", "join_n")]); let out = layer(res); assert_eq!(column(&out, "join_n")[1..3], [Value::Float(9_007_199_254_740_994.0), Value::Float(9_007_199_254_740_992.0)]); // Means within 2^53: no notice. let clean = Layers::default().with(zones()).with(points()).select("points", &[6, 7]); let p = json!({"target": "zones", "join": "points", "merge": [{"field": "n", "rule": "mean"}, {"field": "m", "rule": "mean"}]}); - assert_eq!(rustgis_analysis::run("spatialJoin", &clean, &p).unwrap().messages, ["Spatial Join: 4 features joined (2 matches)"]); + assert_eq!(said(&rustgis_analysis::run("spatialJoin", &clean, &p).unwrap()), ["Spatial Join: 4 features joined (2 matches)"]); } /// A number too large for a decimal, written as text ("1e309"), is a number past every range: `mean`, @@ -286,17 +294,17 @@ fn a_number_too_large_for_a_decimal_is_left_out_and_counted() { let layers = Layers::default().with(zones()).with(pts); let notice = |n: &str, fields: &str| { format!( - "{n} in {fields} were left out: a whole-number sum takes whole numbers in the 64-bit range, the other rules numbers a decimal holds" + "DroppedValue: {n} in {fields} were left out: a whole-number sum takes whole numbers in the 64-bit range, the other rules numbers a decimal holds" ) }; let res = join(&layers, json!([{"field": "n", "rule": "mean"}, {"field": "d", "rule": "sum"}])); // D's mean of n leaves out "1e309", and its sum of d "-1E400"; C's mean of n is still rounded. - assert_eq!(res.messages, [JOINED.to_string(), notice("2 matched numbers", "join_n, join_d"), rounded("1 result", "join_n")]); + assert_eq!(said(&res), [JOINED.to_string(), rounded("1 result", "join_n"), notice("2 matched numbers", "join_n, join_d")]); let out = layer(res); assert_eq!((column(&out, "join_n")[3].clone(), column(&out, "join_d")[3].clone()), (Value::Float(3.0), Value::Float(4.5))); for (n_rule, d_rule) in [("max", "min"), ("min", "max")] { let res = join(&layers, json!([{"field": "n", "rule": n_rule}, {"field": "d", "rule": d_rule}])); - assert_eq!(res.messages, [JOINED.to_string(), notice("2 matched numbers", "join_n, join_d")], "{n_rule}"); + assert_eq!(said(&res), [JOINED.to_string(), notice("2 matched numbers", "join_n, join_d")], "{n_rule}"); let out = layer(res); assert_eq!((column(&out, "join_n")[3].clone(), column(&out, "join_d")[3].clone()), (Value::Int(3), Value::Float(4.5))); } From 82d4cf322ef27f710d2e38ebc6162019b5c192fa Mon Sep 17 00:00:00 2001 From: mavrick Date: Wed, 25 Nov 2026 15:58:15 -0600 Subject: [PATCH 2/2] fix(analysis): Zonal Statistics reads a feature's geometry through its accessor (#2371) --- crates/analysis/src/tools.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/analysis/src/tools.rs b/crates/analysis/src/tools.rs index bd091e6b22..384218bd9e 100644 --- a/crates/analysis/src/tools.rs +++ b/crates/analysis/src/tools.rs @@ -8638,7 +8638,7 @@ fn zonal_stats_on(inp: &dyn Inputs, p: &Json, threads: Option) -> Result< // A polygon that couldn't be read has lost its statistics; a feature with no polygon, or // none with an area, has none to lose. if !feature_valid { - if matches!(&f.geometry, Some(Geometry::Polygon(polys)) if crate::rasterops::has_a_ring(polys)) { + if matches!(poly_ds.features.geometry(r_idx), Some(Geometry::Polygon(polys)) if crate::rasterops::has_a_ring(polys)) { skipped_features += 1; } else { without_polygon += 1;