From e66d87790bbc2a9a867a5d2059b15d32d75de751 Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Sun, 22 Nov 2026 12:08:38 +0100 Subject: [PATCH 1/5] Interpolations, Kernel Density, Zonal Statistics and Tabulate Area work from a layer's own projected coordinates (#2032 C2e-4) --- crates/analysis/src/lib.rs | 6 + crates/analysis/src/rasterops.rs | 53 +++++++-- crates/analysis/src/tools.rs | 92 ++++++++++++--- crates/analysis/src/tools/tabulate_area.rs | 11 +- crates/analysis/src/warp.rs | 2 +- crates/engine/src/tests/held_layers.rs | 125 +++++++++++++++++++++ docs/user-guide/analysis.md | 11 +- 7 files changed, 266 insertions(+), 34 deletions(-) diff --git a/crates/analysis/src/lib.rs b/crates/analysis/src/lib.rs index 42036ef78f..1e3d5fd4e0 100644 --- a/crates/analysis/src/lib.rs +++ b/crates/analysis/src/lib.rs @@ -277,6 +277,12 @@ const OWN_SYSTEM_TOOLS: &[&str] = &[ "simplify", "pointsAlongLines", "near", + // Grids and zones on rasters, from the system's own coordinates (#2032 C2e-4). + "idwInterpolation", + "kriging", + "kernelDensity", + "zonalStats", + "tabulateArea", ]; impl ToolSpec { diff --git a/crates/analysis/src/rasterops.rs b/crates/analysis/src/rasterops.rs index 8774045604..5e1c4695b5 100644 --- a/crates/analysis/src/rasterops.rs +++ b/crates/analysis/src/rasterops.rs @@ -1389,8 +1389,26 @@ pub fn parse_bands_str(s: &str, total_bands: usize) -> Result, String Ok(out) } +/// How polygons' places reach a grid's coordinate system: from longitude/latitude through its +/// transformer, or from a run's own system ([`crate::tools::ToGrid`]: as they are when the grid is +/// in it too). +#[derive(Clone, Copy)] +pub(crate) enum ToWorld<'a> { + LonLat(&'a Transformer), + Own(&'a crate::tools::ToGrid), +} + +impl ToWorld<'_> { + fn world(&self, c: Coord) -> Option { + match self { + Self::LonLat(tr) => tr.from_lonlat(c), + Self::Own(to) => to.place(c), + } + } +} + /// Projects a complete ring to the raster grid without dropping failed vertices. -fn project_ring(tr: &Transformer, t: &GeoTransform, ring: &[Coord]) -> Option> { +fn project_ring(tr: ToWorld<'_>, t: &GeoTransform, ring: &[Coord]) -> Option> { if ring.len() < 3 { return None; } @@ -1399,7 +1417,7 @@ fn project_ring(tr: &Transformer, t: &GeoTransform, ring: &[Coord]) -> Option>], failed_parts: &mut Vec, ) -> Result, Range, Vec)>, String> { - polygon_mask_on(r.transformer(), &r.transform, (r.width, r.height), polygons, failed_parts) + polygon_mask_on(ToWorld::LonLat(r.transformer()), &r.transform, (r.width, r.height), polygons, failed_parts) } /// [`polygon_mask_with_failures`] on a grid of `size` (columns, rows) cells placed by `t` in the /// coordinate system of `tr`, with no raster on it yet. pub(crate) fn polygon_mask_on( - tr: &Transformer, + tr: ToWorld<'_>, t: &GeoTransform, size: (u32, u32), polygons: &[Vec>], @@ -1465,8 +1483,8 @@ pub(crate) fn polygon_mask_on( Ok(Some((cols, rows, trimmed))) } -/// Polygons (each an exterior ring and its holes, in longitude/latitude) projected to a grid's -/// pixels, with the window of the grid around them. +/// Polygons (each an exterior ring and its holes, their places reaching the grid's system by a +/// [`ToWorld`]) projected to a grid's pixels, with the window of the grid around them. pub(crate) struct Placed { parts: Vec>>, width: u32, @@ -1487,7 +1505,7 @@ impl Placed { /// `None` when no polygon can be placed or none reaches the grid of `size` (columns, rows). /// The zero-based indices of the rejected parts are appended to `failed_parts`. pub(crate) fn new( - tr: &Transformer, + tr: ToWorld<'_>, t: &GeoTransform, size: (u32, u32), polygons: &[Vec>], @@ -1682,6 +1700,17 @@ pub(crate) fn zonal_statistics_with_failures( bands: &[usize], polygons: &[Vec>], failed_parts: &mut Vec, +) -> Result, String> { + zonal_statistics_from(r, ToWorld::LonLat(r.transformer()), bands, polygons, failed_parts) +} + +/// [`zonal_statistics_with_failures`] for polygons whose places reach the raster's system by `to`. +pub(crate) fn zonal_statistics_from( + r: &Raster, + to: ToWorld<'_>, + bands: &[usize], + polygons: &[Vec>], + failed_parts: &mut Vec, ) -> Result, String> { r.require_coordinates()?; for &b in bands { @@ -1693,7 +1722,7 @@ pub(crate) fn zonal_statistics_with_failures( return Ok(Vec::new()); } - let Some((cols, rows, mask)) = polygon_mask_with_failures(r, polygons, failed_parts)? else { + let Some((cols, rows, mask)) = polygon_mask_on(to, &r.transform, (r.width, r.height), polygons, failed_parts)? else { return Ok(vec![ZoneStats::default(); bands.len()]); }; @@ -2586,9 +2615,11 @@ mod tests { } polygons.push(rings); } - let found = polygon_mask_on(&tr, &t, (width, height), &polygons, &mut Vec::new()).unwrap(); - let parts: Vec>> = - polygons.iter().map(|rings| rings.iter().map(|ring| project_ring(&tr, &t, ring).unwrap()).collect()).collect(); + let found = polygon_mask_on(ToWorld::LonLat(&tr), &t, (width, height), &polygons, &mut Vec::new()).unwrap(); + let parts: Vec>> = polygons + .iter() + .map(|rings| rings.iter().map(|ring| project_ring(ToWorld::LonLat(&tr), &t, ring).unwrap()).collect()) + .collect(); let want = plain(&parts, width, height); let mut got = vec![false; want.len()]; if let Some((cols, rows, mask)) = found { diff --git a/crates/analysis/src/tools.rs b/crates/analysis/src/tools.rs index 39ee5962b3..58d2b89d27 100644 --- a/crates/analysis/src/tools.rs +++ b/crates/analysis/src/tools.rs @@ -4761,8 +4761,8 @@ fn idw_interpolation(inp: &dyn Inputs, p: &Json) -> Result { } }); } - let (crs, crs_note) = raster_crs(ds, p, "IDW Interpolation")?; - let (pts, beyond_note) = points_in(crs, pts)?; + let (crs, crs_note) = raster_crs_in(ds, inp.work_crs(), p, "IDW Interpolation")?; + let (pts, beyond_note) = points_from(inp.work_crs(), crs, pts)?; let extent = match s(p, "extent").trim() { "" => { let mut e = Extent::EMPTY; @@ -4854,8 +4854,8 @@ fn kriging_interpolation(inp: &dyn Inputs, p: &Json) -> Result) -> Option> { /// run used where that could surprise: the system it took from the layer, or the compatibility note /// on the one given. pub fn raster_crs(ds: &Dataset, p: &Json, tool: &str) -> Result<(Crs, Option), String> { + raster_crs_of(ds.crs, &ds.name, p, tool) +} + +/// [`raster_crs`] for a run in `work` ([`Inputs::work_crs`]): a layer held in its own projected +/// system makes its grid there unless `p` names another. +fn raster_crs_in(ds: &Dataset, work: Crs, p: &Json, tool: &str) -> Result<(Crs, Option), String> { + raster_crs_of(if work == Crs::LonLat { ds.crs } else { Some(work) }, &ds.name, p, tool) +} + +/// [`raster_crs`] for a layer named `name` read in `layer_crs`. +fn raster_crs_of(layer_crs: Option, name: &str, p: &Json, tool: &str) -> Result<(Crs, Option), String> { if p.get("crs").is_some_and(|v| !v.is_null() && !v.is_string()) { return Err("crs must be text".into()); } match s(p, "crs").trim() { - "" => Ok(match layer_raster_crs(ds.crs) { + "" => Ok(match layer_raster_crs(layer_crs) { // A system that can't hold a raster's cells (geocentric), or one this version can't // project to: degrees, as before, and said why. Some(Err(why)) => ( Crs::LonLat, Some(format!( "{tool}: made in degrees of longitude and latitude, though {} was read in {why}; give a projected crs to make it in metres or feet", - ds.name + name )), ), Some(Ok(c)) => ( @@ -5070,7 +5081,7 @@ pub fn raster_crs(ds: &Dataset, p: &Json, tool: &str) -> Result<(Crs, Option (Crs::LonLat, None), @@ -5104,10 +5115,16 @@ pub fn projected_crs(text: &str) -> Result<(Crs, Option), String> { /// can't hold them (see [`in_projected`]). A point costs a projection and its round trip: Cancel is /// looked at every [`LOOK_EVERY`] points. pub fn points_in(crs: Crs, pts: Vec<(Coord, f64)>) -> Result<(Vec<(Coord, f64)>, Option), String> { - if crs == Crs::LonLat { + points_from(Crs::LonLat, crs, pts) +} + +/// [`points_in`] for points in `from`, a run's own system ([`Inputs::work_crs`]): as they are +/// when the grid is in it too, else through [`ToGrid`]. +fn points_from(from: Crs, crs: Crs, pts: Vec<(Coord, f64)>) -> Result<(Vec<(Coord, f64)>, Option), String> { + if from == crs { return Ok((pts, None)); } - let to = crs.transformer()?; + let to = ToGrid::new(from, crs)?; let n = pts.len(); // (In the points' own storage, as a filtered collect of the same kind reuses it.) let kept: Vec<(Coord, f64)> = pts @@ -5119,7 +5136,7 @@ pub fn points_in(crs: Crs, pts: Vec<(Coord, f64)>) -> Result<(Vec<(Coord, f64)>, { return Some(Err(cancelled)); } - in_projected(crs, &to, c).map(|c| Ok((c, v))) + to.place(c).map(|c| Ok((c, v))) }) .collect::>()?; let beyond = n - kept.len(); @@ -5149,6 +5166,43 @@ fn in_projected(crs: Crs, to: &Transformer, c: Coord) -> Option { held.then(|| to.from_lonlat(c)).flatten().filter(|p| p.is_finite() && to.to_lonlat(*p).is_some_and(|back| (back.y - c.y).abs() < 1e-4)) } +/// Places in a run's own system converted to a grid's system `crs`, as [`in_projected`] takes +/// them from longitude/latitude: a place `crs` can't hold is `None`. From longitude/latitude, that +/// conversion; from the grid's own system, the place as it is; from another, through +/// longitude/latitude for the check, then the direct operation between the two where it lands +/// near that ([`Reprojection::point_near`]), so a datum pair takes its best operation. +/// +/// [`Reprojection::point_near`]: rustgis_data::raster::Reprojection::point_near +pub(crate) struct ToGrid { + crs: Crs, + same: bool, + /// The run's system's transformer, `None` from longitude/latitude. + from: Option, + to: Transformer, + direct: Option, +} + +impl ToGrid { + pub(crate) fn new(from: Crs, crs: Crs) -> Result { + let same = from == crs; + let unproject = if same || from == Crs::LonLat { None } else { Some(from.transformer()?) }; + let direct = if unproject.is_some() { Some(from.to(crs)?) } else { None }; + Ok(Self { crs, same, from: unproject, to: crs.transformer()?, direct }) + } + + pub(crate) fn place(&self, c: Coord) -> Option { + if self.same { + return c.is_finite().then_some(c); + } + let lonlat = match &self.from { + Some(t) => t.to_lonlat(c)?, + None => c, + }; + let via = in_projected(self.crs, &self.to, lonlat)?; + Some(self.direct.as_ref().map_or(via, |d| d.point_near(c, via))) + } +} + /// The note on a system an interpolation took from the layer (`p`'s `crs` empty), naming the values /// among `keys` that `p` gives, read in its units: a script written when these tools worked in /// degrees is told, not answered in metres without a word (#1743). An `extent` that holds none of @@ -5238,7 +5292,7 @@ fn kernel_density_tool(inp: &dyn Inputs, p: &Json) -> Result let crs_text = s(p, "crs").trim(); let (crs, crs_note) = if !crs_text.is_empty() { crs_with_compatibility_note(crs_text)? - } else if let Some(c) = ds.crs { + } else if let Some(c) = Some(inp.work_crs()).filter(|c| *c != Crs::LonLat).or(ds.crs) { (c, None) } else { return Err(format!( @@ -5260,7 +5314,9 @@ fn kernel_density_tool(inp: &dyn Inputs, p: &Json) -> Result )); } - let transformer = crs.transformer()?; + // From the layer's own system when it is held in one (straight through when that is the + // grid's), else from longitude/latitude. + let to_grid = ToGrid::new(inp.work_crs(), crs)?; if p.get("field").is_some_and(|v| !v.is_null() && !v.is_string()) { return Err("field must be text".into()); @@ -5288,7 +5344,7 @@ fn kernel_density_tool(inp: &dyn Inputs, p: &Json) -> Result // feature with none is counted in `skipped`). let (mut non_finite, mut non_finite_features) = (0usize, 0usize); let project = |c: Coord, beyond: &mut usize| { - let p = in_projected(crs, &transformer, c); + let p = to_grid.place(c); *beyond += usize::from(p.is_none()); p }; @@ -8011,6 +8067,10 @@ fn zonal_stats_on(inp: &dyn Inputs, p: &Json, threads: Option) -> Result< // bounds the threads too. let mask_bytes = (r.width as usize).saturating_mul(r.height as usize).saturating_mul(2); let threads = threads.unwrap_or_else(|| crate::parallel::threads_for_scratch(target_rows.len(), PARALLEL_FEATURES, mask_bytes)); + // The polygons are in the run's system: their own projected one, converted to the raster's + // (none of it when that is the raster's too), else longitude/latitude. + let own = (inp.work_crs() != Crs::LonLat).then(|| ToGrid::new(inp.work_crs(), r.crs)).transpose()?; + let to = own.as_ref().map_or(crate::rasterops::ToWorld::LonLat(r.transformer()), crate::rasterops::ToWorld::Own); crate::control::begin(target_rows.len()); // A feature's statistics by band, whether its geometry was read, its parts that couldn't be // projected and what went wrong. @@ -8023,11 +8083,11 @@ fn zonal_stats_on(inp: &dyn Inputs, p: &Json, threads: Option) -> Result< let Some(f) = poly_ds.features.get(r_idx) else { return Ok((none(), false, 0, None)) }; Ok::<_, String>(match &f.geometry { Some(Geometry::Polygon(polys)) if !polys.is_empty() => { - // Dataset geometry is already lon/lat; crs records the source system. + // Checked and taken apart into rings, in the run's system as they are. match crate::rasterops::transform_feature_polygons_to_lonlat(polys, None) { - Ok(polys_lonlat) => { + Ok(rings) => { let mut failed_parts = Vec::new(); - let st = crate::rasterops::zonal_statistics_with_failures(r, &bands, &polys_lonlat, &mut failed_parts)?; + let st = crate::rasterops::zonal_statistics_from(r, to, &bands, &rings, &mut failed_parts)?; let detail = (!failed_parts.is_empty()) .then(|| format!("feature {}: raster projection failed for polygon part(s) {failed_parts:?}", f.id)); (st, true, failed_parts.len(), detail) diff --git a/crates/analysis/src/tools/tabulate_area.rs b/crates/analysis/src/tools/tabulate_area.rs index 05f7400fae..c5a63187cc 100644 --- a/crates/analysis/src/tools/tabulate_area.rs +++ b/crates/analysis/src/tools/tabulate_area.rs @@ -74,8 +74,12 @@ pub(super) fn run_on(inp: &dyn Inputs, p: &Json, threads: Option) -> Resu .saturating_add(areas.cache_bytes) .saturating_add(geometry_bytes); let threads = threads.unwrap_or_else(|| crate::parallel::threads_for_scratch(groups.len(), PARALLEL_FEATURES, scratch)); + // The zones are in the run's system: their own projected one, converted to the raster's + // (none of it when that is the raster's too), else longitude/latitude. + let own = (inp.work_crs() != Crs::LonLat).then(|| crate::tools::ToGrid::new(inp.work_crs(), r.crs)).transpose()?; + let to = own.as_ref().map_or(crate::rasterops::ToWorld::LonLat(r.transformer()), crate::rasterops::ToWorld::Own); let totals = - crate::parallel::try_map_on(&groups, threads, || (), |_, _, group| summarize(r, *band, zones, &group.rows, &index, &areas))?; + crate::parallel::try_map_on(&groups, threads, || (), |_, _, group| summarize(r, to, *band, zones, &group.rows, &index, &areas))?; let zone_field = keys.first().and_then(|&i| zones.fields.get(i)).cloned().unwrap_or_else(|| Field::new("zone_id", FieldType::Text)); let mut out = Dataset::new(out_name(p, format!("{}_TabulateArea", zones.name)), GeometryType::None, vec![zone_field]); for &class in &classes { @@ -157,9 +161,10 @@ struct Totals { } /// Masks a whole group together: a cell in overlapping features or parts of the same zone -/// counts once. Dataset geometry is stored in WGS 84 regardless of its source CRS metadata. +/// counts once. The zones' places reach the raster's system by `to`. fn summarize( r: &Raster, + to: crate::rasterops::ToWorld<'_>, band: usize, zones: &Dataset, rows: &[usize], @@ -181,7 +186,7 @@ fn summarize( } } let mut failures = Vec::new(); - let mask = crate::rasterops::polygon_mask_with_failures(r, &polygons, &mut failures)?; + let mask = crate::rasterops::polygon_mask_on(to, &r.transform, (r.width, r.height), &polygons, &mut failures)?; total.parts = failures.len(); crate::control::check()?; let Some((cols, rows, mask)) = mask else { return Ok(total) }; diff --git a/crates/analysis/src/warp.rs b/crates/analysis/src/warp.rs index 62babd6960..5c2c0b6736 100644 --- a/crates/analysis/src/warp.rs +++ b/crates/analysis/src/warp.rs @@ -545,7 +545,7 @@ pub fn rasterize(g: &Grid, shapes: &[Shape], nodata: f32) -> Result, crs: Crs) { + let mut d = Dataset::new(name, kind, vec![Field::new("v", FieldType::Double)]); + for (i, g) in geoms.into_iter().enumerate() { + d.push(Some(g), vec![Cell::Float(i as f64 + 1.0)]); + } + d.held_in = crs; + d.crs = Some(crs); + s.map_mut().add_dataset(d); +} + +/// A raster layer's grid. +fn grid_of(s: &Session, layer: &str) -> std::sync::Arc { + let l = s.map().layer_by_name(layer).unwrap_or_else(|| panic!("no layer {layer}")); + l.raster.as_ref().and_then(|r| r.data.clone()).unwrap_or_else(|| panic!("{layer} is no raster")) +} + +/// IDW, Kriging and Kernel Density make their grid in the system a layer is held in from its own +/// coordinates, as they are: the grid's corner is the points' own westmost and northmost +/// coordinates, exactly, where a run in longitude/latitude converted them there and back. The +/// points lie 1500 km east of the zone's central meridian, where that round trip doesn't come back +/// to the same bits. +#[test] +fn a_grid_is_made_from_the_held_systems_own_coordinates() { + let (x0, y0) = (2_000_000.25, 5_401_300.75); + let at = [(0.0, 0.0), (1234.5, 310.25), (410.125, 2045.5), (2500.75, 1800.0)]; + let mut s = session(UTM); + add_in(&mut s, "Samples", GeometryType::Point, at.iter().map(|(x, y)| Geometry::Point(Coord::new(x0 + x, y0 + y))).collect(), UTM); + let (west, north) = (x0, y0 + 2045.5); + for (tool, out) in [("idwInterpolation", "Idw"), ("kriging", "Krig")] { + s.run("gp.run", &json!({"tool": tool, "params": {"input": "Samples", "field": "v", "pixelSize": 100, "output": out}})).unwrap(); + let g = grid_of(&s, out); + assert_eq!(g.crs, UTM, "{tool}"); + assert_eq!( + (g.transform.origin_x.to_bits(), g.transform.origin_y.to_bits()), + (west.to_bits(), north.to_bits()), + "{tool}: {:?}", + g.transform + ); + } + s.run("gp.run", &json!({"tool": "kernelDensity", "params": {"input": "Samples", "radius": 500, "pixelSize": 50, "output": "Kde"}})) + .unwrap(); + let g = grid_of(&s, "Kde"); + assert_eq!(g.crs, UTM); + // Its grid reaches the radius past the points, on whole cells from the westmost point. + let (dx, dy) = (west - g.transform.origin_x, g.transform.origin_y - north); + assert!(dx > 0.0 && dy > 0.0 && (dx / 50.0).fract() == 0.0 && (dy / 50.0).fract() == 0.0, "{:?}", g.transform); +} + +/// Gauss-Krüger zone 3 on DHDN (EPSG:31467) to UTM 32N on ETRS89 (EPSG:25832). +const GK3: Crs = Crs::Epsg(31467); +const ETRS_UTM: Crs = Crs::Epsg(25832); + +/// A grid in another system than the points' own takes the direct operation between the two, as +/// [`Crs::to`] converts: between DHDN and ETRS89, 0.44 m from the way through WGS 84 a run in +/// longitude/latitude took (`a_conversion_between_two_datums_takes_their_transformation`). +#[test] +fn a_grid_in_another_system_takes_the_direct_operation() { + let mut s = Session::new(Project::default()); + let at = [Coord::new(3_500_000.0, 5_400_000.0), Coord::new(3_501_200.0, 5_400_900.0), Coord::new(3_500_700.0, 5_401_500.0)]; + add_in(&mut s, "Samples", GeometryType::Point, at.iter().map(|c| Geometry::Point(*c)).collect(), GK3); + s.run( + "gp.run", + &json!({"tool": "idwInterpolation", "params": {"input": "Samples", "field": "v", "pixelSize": 10, "crs": "EPSG:25832", "output": "Idw"}}), + ) + .unwrap(); + let to = GK3.to(ETRS_UTM).unwrap(); + let placed: Vec = at.iter().map(|c| to.point(*c).unwrap()).collect(); + let west = placed.iter().map(|c| c.x).fold(f64::INFINITY, f64::min); + let north = placed.iter().map(|c| c.y).fold(f64::NEG_INFINITY, f64::max); + let g = grid_of(&s, "Idw"); + assert_eq!(g.crs, ETRS_UTM); + assert_eq!((g.transform.origin_x, g.transform.origin_y), (west, north)); +} + +/// Zonal Statistics and Tabulate Area place zones held in another system than the raster's by the +/// direct operation between the two: a square held in Gauss-Krüger zone 3 on DHDN covers the cells +/// of a raster in UTM 32N on ETRS89 that the same square converted there by [`Crs::to`] covers, +/// on cells of 10 cm (and in their metre-square classes), where the way through WGS 84 is 0.44 m +/// off. +#[test] +fn zones_reach_a_raster_by_the_direct_operation() { + use rustgis_data::raster::{ColorHint, GeoTransform, Raster}; + let mut s = Session::new(Project::default()); + // 10 m by 10 m of 10 cm cells, each holding its column and row (col + 1000 × row). + let (w, h) = (100u32, 100u32); + let values: Vec = (0..w * h).map(|i| (i % w + 1000 * (i / w)) as f32).collect(); + let gt = GeoTransform { origin_x: 499_920.0, origin_y: 5_398_285.0, pixel_width: 0.1, pixel_height: -0.1 }; + let r = Raster::new("grid", w, h, vec![values], gt, ETRS_UTM, None, ColorHint::Gray, "Float32").unwrap(); + s.map_mut().add_raster("grid", rustgis_map::raster::RasterLayer::from_path(r, "grid.tif")); + // The same cells in 100 classes of a metre square, for Tabulate Area. + let classes: Vec = (0..w * h).map(|i| (i % w / 10 + 10 * (i / w / 10)) as f32).collect(); + let r = Raster::new("blocks", w, h, vec![classes], gt, ETRS_UTM, None, ColorHint::Gray, "Float32").unwrap(); + s.map_mut().add_raster("blocks", rustgis_map::raster::RasterLayer::from_path(r, "blocks.tif")); + // A 6 m square round (3,500,000, 5,400,000) in GK3, 499,924.54, 5,398,279.54 in UTM. + let (cx, cy) = (3_500_000.0, 5_400_000.0); + let ring: Vec = + [(-3.0, -3.0), (3.0, -3.0), (3.0, 3.0), (-3.0, 3.0), (-3.0, -3.0)].iter().map(|(dx, dy)| Coord::new(cx + dx, cy + dy)).collect(); + let to = GK3.to(ETRS_UTM).unwrap(); + let there: Vec = ring.iter().map(|c| to.point(*c).unwrap()).collect(); + add_in(&mut s, "Zone", GeometryType::Polygon, vec![Geometry::Polygon(vec![vec![ring]])], GK3); + add_in(&mut s, "Converted", GeometryType::Polygon, vec![Geometry::Polygon(vec![vec![there]])], ETRS_UTM); + let mut stats = Vec::new(); + let mut tables = Vec::new(); + for zone in ["Zone", "Converted"] { + let out = format!("{zone}Stats"); + s.run("gp.run", &json!({"tool": "zonalStats", "params": {"raster": "grid", "polygons": zone, "output": out}})).unwrap(); + stats.push((field_numbers(&s, &out, "grid_count"), field_numbers(&s, &out, "grid_mean"))); + let table = format!("{zone}Classes"); + s.run( + "gp.run", + &json!({"tool": "tabulateArea", "params": {"raster": "blocks", "zones": zone, "measure": "Count", "output": table}}), + ) + .unwrap(); + let t = s.project.tables.iter().find(|t| t.name == table).unwrap_or_else(|| panic!("no table {table}")); + let row: Vec = (1..t.fields.len()).filter_map(|f| t.value(0, f).as_f64()).collect(); + tables.push((t.fields.iter().skip(1).map(|f| f.name.clone()).collect::>(), row)); + } + // About 60 × 60 cells. + assert!(stats[0].0[0] > 3000.0, "{stats:?}"); + assert_eq!(stats[0], stats[1]); + assert_eq!(tables[0], tables[1]); +} diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index cb1f1f5ddc..06ed3b0ef0 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -181,8 +181,9 @@ Statistics, Pivot Table, Join Field, Select Layer By Attribute, Export Features, Line, Split Line At Vertices, Feature Envelope To Polygon, Unsplit Line, Feature Vertices To Points, Check Geometry and Repair Geometry; the overlays Clip, Erase, Intersect, Identity, Union, Symmetrical Difference, Update, Split and Dissolve; Minimum Bounding Geometry (convex hull), -Feature To Point and Summarize Within; Select Layer By Location and Spatial Join; and Buffer, -Simplify, Points Along Lines and Near. Their other inputs are converted into that system for the +Feature To Point and Summarize Within; Select Layer By Location and Spatial Join; Buffer, +Simplify, Points Along Lines and Near; and IDW Interpolation, Kriging, Kernel Density, Zonal +Statistics and Tabulate Area. Their other inputs are converted into that system for the run, and their new layers are kept in it, so the coordinates of what they copy stay exactly as they were. An overlay there takes each edge as straight in that system, not in Web Mercator as it does in longitude/latitude, so where an edge crosses another can differ from the same tool's result in @@ -204,7 +205,11 @@ metre is not quite a metre on the ground: in a UTM zone, from 1.0004 m on its ce about 0.999 m at its edges on the equator (0.9998 m at 48.7°N), so a buffer of 100 km around a point 2.5° east of the central meridian at 48.7°N reaches 100,017 m on the ground on its west side and 99,972 m on its east side. Near's nearest point is that system's x and y, and Points Along Lines' -angle is from grid north. Area, length and perimeter fields stay on the ellipsoid. +angle is from grid north. An interpolation or density surface is made in that system unless +another is given, from its points' own coordinates; one given another system, and Zonal Statistics +and Tabulate Area on a raster in another system, convert the points or zones straight into it, with +the transformation between the two datums where they differ. Area, length and perimeter fields +stay on the ellipsoid. In the desktop app a tool runs in the background, so the map and the rest of the window stay in use. While it runs, the Tools pane shows its name, a **Cancel** button and, for the tools that From d5bdbaf62518198517cdefb83c7aa6be167beb36 Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Sun, 22 Nov 2026 12:16:29 +0100 Subject: [PATCH 2/5] Review: notes say a held layer's system is held in; help texts and guide name the held system; ring check documented --- crates/analysis/src/rasterops.rs | 2 ++ crates/analysis/src/tools.rs | 26 ++++++++++++++------------ docs/user-guide/analysis.md | 32 +++++++++++++++++--------------- 3 files changed, 33 insertions(+), 27 deletions(-) diff --git a/crates/analysis/src/rasterops.rs b/crates/analysis/src/rasterops.rs index 5e1c4695b5..a90dbf9f17 100644 --- a/crates/analysis/src/rasterops.rs +++ b/crates/analysis/src/rasterops.rs @@ -1290,6 +1290,8 @@ pub fn transform_polygon_to_lonlat(rings: &[Vec], tr: Option<&Transformer } /// Transforms and validates all polygon parts of a (multi-)polygon feature to WGS 84 lon/lat coordinates. +/// With no transformer (`tr` `None`), it only checks the parts and takes them apart into rings, +/// in whatever system they are in. pub fn transform_feature_polygons_to_lonlat( polys: &[Vec>], tr: Option<&Transformer>, diff --git a/crates/analysis/src/tools.rs b/crates/analysis/src/tools.rs index 58d2b89d27..ad464a9e9e 100644 --- a/crates/analysis/src/tools.rs +++ b/crates/analysis/src/tools.rs @@ -901,7 +901,7 @@ pub static TOOLS: &[ToolSpec] = &[ kind: K::Text, required: false, default: "", - help: "A projected coordinate system (e.g. EPSG:32618) to make the raster in, its units for the extent and pixel size; when empty, the one the layer was read in if projected, else degrees; EPSG:4326 for degrees.", + help: "A projected coordinate system (e.g. EPSG:32618) to make the raster in, its units for the extent and pixel size; when empty, the projected one the layer is held in, or else was read in, else degrees; EPSG:4326 for degrees.", }, P { name: "output", label: "Output Name", kind: K::Text, required: false, default: "", help: "" }, ], @@ -1067,7 +1067,7 @@ pub static TOOLS: &[ToolSpec] = &[ kind: K::Text, required: false, default: "", - help: "A projected coordinate system (e.g. EPSG:32618) to make the raster in, its units for the extent, pixel size and range; when empty, the one the layer was read in if projected, else degrees; EPSG:4326 for degrees.", + help: "A projected coordinate system (e.g. EPSG:32618) to make the raster in, its units for the extent, pixel size and range; when empty, the projected one the layer is held in, or else was read in, else degrees; EPSG:4326 for degrees.", }, P { name: "output", label: "Output Name", kind: K::Text, required: false, default: "", help: "" }, ], @@ -5051,17 +5051,21 @@ pub fn layer_raster_crs(crs: Option) -> Option> { /// run used where that could surprise: the system it took from the layer, or the compatibility note /// on the one given. pub fn raster_crs(ds: &Dataset, p: &Json, tool: &str) -> Result<(Crs, Option), String> { - raster_crs_of(ds.crs, &ds.name, p, tool) + raster_crs_of(ds.crs, "was read in", &ds.name, p, tool) } /// [`raster_crs`] for a run in `work` ([`Inputs::work_crs`]): a layer held in its own projected /// system makes its grid there unless `p` names another. fn raster_crs_in(ds: &Dataset, work: Crs, p: &Json, tool: &str) -> Result<(Crs, Option), String> { - raster_crs_of(if work == Crs::LonLat { ds.crs } else { Some(work) }, &ds.name, p, tool) + if work == Crs::LonLat { + raster_crs_of(ds.crs, "was read in", &ds.name, p, tool) + } else { + raster_crs_of(Some(work), "is held in", &ds.name, p, tool) + } } -/// [`raster_crs`] for a layer named `name` read in `layer_crs`. -fn raster_crs_of(layer_crs: Option, name: &str, p: &Json, tool: &str) -> Result<(Crs, Option), String> { +/// [`raster_crs`] for a layer named `name` that `how` ("was read in", "is held in") `layer_crs`. +fn raster_crs_of(layer_crs: Option, how: &str, name: &str, p: &Json, tool: &str) -> Result<(Crs, Option), String> { if p.get("crs").is_some_and(|v| !v.is_null() && !v.is_string()) { return Err("crs must be text".into()); } @@ -5072,16 +5076,14 @@ fn raster_crs_of(layer_crs: Option, name: &str, p: &Json, tool: &str) -> Re Some(Err(why)) => ( Crs::LonLat, Some(format!( - "{tool}: made in degrees of longitude and latitude, though {} was read in {why}; give a projected crs to make it in metres or feet", - name + "{tool}: made in degrees of longitude and latitude, though {name} {how} {why}; give a projected crs to make it in metres or feet" )), ), Some(Ok(c)) => ( c, Some(format!( - "{tool}: made in {}, the coordinate system {} was read in, with its units for the extent and sizes; set crs to EPSG:4326 to make it in degrees", - c.label(), - name + "{tool}: made in {}, the coordinate system {name} {how}, with its units for the extent and sizes; set crs to EPSG:4326 to make it in degrees", + c.label() )), ), None => (Crs::LonLat, None), @@ -5292,7 +5294,7 @@ fn kernel_density_tool(inp: &dyn Inputs, p: &Json) -> Result let crs_text = s(p, "crs").trim(); let (crs, crs_note) = if !crs_text.is_empty() { crs_with_compatibility_note(crs_text)? - } else if let Some(c) = Some(inp.work_crs()).filter(|c| *c != Crs::LonLat).or(ds.crs) { + } else if let Some(c) = if inp.work_crs() == Crs::LonLat { ds.crs } else { Some(inp.work_crs()) } { (c, None) } else { return Err(format!( diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index 06ed3b0ef0..7cf4d4358a 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -183,16 +183,16 @@ Points, Check Geometry and Repair Geometry; the overlays Clip, Erase, Intersect, Symmetrical Difference, Update, Split and Dissolve; Minimum Bounding Geometry (convex hull), Feature To Point and Summarize Within; Select Layer By Location and Spatial Join; Buffer, Simplify, Points Along Lines and Near; and IDW Interpolation, Kriging, Kernel Density, Zonal -Statistics and Tabulate Area. Their other inputs are converted into that system for the -run, and their new layers are kept in it, so the coordinates of what they copy stay exactly as they -were. An overlay there takes each edge as straight in that system, not in Web Mercator as it does in -longitude/latitude, so where an edge crosses another can differ from the same tool's result in -longitude/latitude, by up to about L² tan φ / 8R for an edge L long at latitude φ: some 20 cm for a -3 km edge at 48°N, 2 m for a 10 km one, 220 m for a 100 km one. An input in another system is -converted vertex by vertex, as the map draws it in that system, and its long edges can run much -farther from where they run in longitude/latitude: a degree-wide box's east-west edges, which follow -their parallels there, are chords in UTM up to 120 m away. The tool then says how many edges of -which layer run more than a metre away, and how far the farthest does. A world projection (World +Statistics and Tabulate Area (the last five as said below). Their other inputs are converted into +that system for the run, and their new layers are kept in it, so the coordinates of what they copy +stay exactly as they were. An overlay there takes each edge as straight in that system, not in Web +Mercator as it does in longitude/latitude, so where an edge crosses another can differ from the same +tool's result in longitude/latitude, by up to about L² tan φ / 8R for an edge L long at latitude φ: +some 20 cm for a 3 km edge at 48°N, 2 m for a 10 km one, 220 m for a 100 km one. An input in another +system is converted vertex by vertex, as the map draws it in that system, and its long edges can run +much farther from where they run in longitude/latitude: a degree-wide box's east-west edges, which +follow their parallels there, are chords in UTM up to 120 m away. The tool then says how many edges +of which layer run more than a metre away, and how far the farthest does. A world projection (World Mercator, Plate Carrée, Robinson, Equal Earth and the like), whose plane has the antimeridian as a seam and the poles as lines, is worked on in longitude/latitude, as Web Mercator is. If another input has a place that system can't hold, the tool works in longitude/latitude instead, and its @@ -205,11 +205,13 @@ metre is not quite a metre on the ground: in a UTM zone, from 1.0004 m on its ce about 0.999 m at its edges on the equator (0.9998 m at 48.7°N), so a buffer of 100 km around a point 2.5° east of the central meridian at 48.7°N reaches 100,017 m on the ground on its west side and 99,972 m on its east side. Near's nearest point is that system's x and y, and Points Along Lines' -angle is from grid north. An interpolation or density surface is made in that system unless -another is given, from its points' own coordinates; one given another system, and Zonal Statistics -and Tabulate Area on a raster in another system, convert the points or zones straight into it, with -the transformation between the two datums where they differ. Area, length and perimeter fields -stay on the ellipsoid. +angle is from grid north. IDW Interpolation, Kriging and Kernel Density make their surface in that +system, from its points' own coordinates, unless another system is given; Zonal Statistics and +Tabulate Area place their zones on a raster in that system as they are. A surface given another +projected system, or a raster in one, gets the points or zones converted straight into it, by the +transformation between the two datums where they differ; a raster in longitude/latitude or Web +Mercator gets them through WGS 84. Their rasters aren't converted, and they don't count bent edges. +Area, length and perimeter fields stay on the ellipsoid. In the desktop app a tool runs in the background, so the map and the rest of the window stay in use. While it runs, the Tools pane shows its name, a **Cancel** button and, for the tools that From b82049c3eb47e8a345e0c9e10240fd03e37e7717 Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Sun, 22 Nov 2026 12:20:14 +0100 Subject: [PATCH 3/5] Review: the guide's Tabulate Area, Zonal Statistics and interpolation passages and Kernel Density's help name the held system --- crates/analysis/src/tools.rs | 2 +- docs/user-guide/analysis.md | 72 ++++++++++++++++++------------------ 2 files changed, 38 insertions(+), 36 deletions(-) diff --git a/crates/analysis/src/tools.rs b/crates/analysis/src/tools.rs index ad464a9e9e..d826d119ef 100644 --- a/crates/analysis/src/tools.rs +++ b/crates/analysis/src/tools.rs @@ -1317,7 +1317,7 @@ pub static TOOLS: &[ToolSpec] = &[ kind: K::Text, required: false, default: "", - help: "Projected coordinate system (e.g. EPSG:32618); defaults to the layer's CRS when projected, or required when the layer has none or is in degrees.", + help: "Projected coordinate system (e.g. EPSG:32618); defaults to the projected system the layer is held in, or else was read in; required when the layer has none or is in degrees.", }, P { name: "output", label: "Output Name", kind: K::Text, required: false, default: "", help: "Output raster layer name." }, ], diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index 7cf4d4358a..092bad5e4f 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -183,35 +183,35 @@ Points, Check Geometry and Repair Geometry; the overlays Clip, Erase, Intersect, Symmetrical Difference, Update, Split and Dissolve; Minimum Bounding Geometry (convex hull), Feature To Point and Summarize Within; Select Layer By Location and Spatial Join; Buffer, Simplify, Points Along Lines and Near; and IDW Interpolation, Kriging, Kernel Density, Zonal -Statistics and Tabulate Area (the last five as said below). Their other inputs are converted into -that system for the run, and their new layers are kept in it, so the coordinates of what they copy -stay exactly as they were. An overlay there takes each edge as straight in that system, not in Web -Mercator as it does in longitude/latitude, so where an edge crosses another can differ from the same -tool's result in longitude/latitude, by up to about L² tan φ / 8R for an edge L long at latitude φ: -some 20 cm for a 3 km edge at 48°N, 2 m for a 10 km one, 220 m for a 100 km one. An input in another -system is converted vertex by vertex, as the map draws it in that system, and its long edges can run -much farther from where they run in longitude/latitude: a degree-wide box's east-west edges, which -follow their parallels there, are chords in UTM up to 120 m away. The tool then says how many edges -of which layer run more than a metre away, and how far the farthest does. A world projection (World -Mercator, Plate Carrée, Robinson, Equal Earth and the like), whose plane has the antimeridian as a -seam and the poles as lines, is worked on in longitude/latitude, as Web Mercator is. If another -input has a place that system can't hold, the tool works in longitude/latitude instead, and its -message says so. A layer in longitude/latitude, Web Mercator or another geographic system is worked -on in longitude/latitude, as before. In a projected system a tool works in, distances in metres -(Buffer's, Simplify's tolerance, Points Along Lines' spacing, Near's, and the search distances of -Select Layer By Location and Spatial Join) are measured flat there, in its unit, as distances in a -projected system are: a kilometre is 1000 of its metres, or 3280.833 of its US survey feet. A flat -metre is not quite a metre on the ground: in a UTM zone, from 1.0004 m on its central meridian to -about 0.999 m at its edges on the equator (0.9998 m at 48.7°N), so a buffer of 100 km around a point -2.5° east of the central meridian at 48.7°N reaches 100,017 m on the ground on its west side and -99,972 m on its east side. Near's nearest point is that system's x and y, and Points Along Lines' -angle is from grid north. IDW Interpolation, Kriging and Kernel Density make their surface in that -system, from its points' own coordinates, unless another system is given; Zonal Statistics and -Tabulate Area place their zones on a raster in that system as they are. A surface given another -projected system, or a raster in one, gets the points or zones converted straight into it, by the -transformation between the two datums where they differ; a raster in longitude/latitude or Web -Mercator gets them through WGS 84. Their rasters aren't converted, and they don't count bent edges. -Area, length and perimeter fields stay on the ellipsoid. +Statistics and Tabulate Area (the last five as said below). Their other vector inputs are converted +into that system for the run, and their new layers are kept in it, so the coordinates of what they +copy stay exactly as they were. An overlay there takes each edge as straight in that system, not in +Web Mercator as it does in longitude/latitude, so where an edge crosses another can differ from the +same tool's result in longitude/latitude, by up to about L² tan φ / 8R for an edge L long at +latitude φ: some 20 cm for a 3 km edge at 48°N, 2 m for a 10 km one, 220 m for a 100 km one. An +input in another system is converted vertex by vertex, as the map draws it in that system, and its +long edges can run much farther from where they run in longitude/latitude: a degree-wide box's +east-west edges, which follow their parallels there, are chords in UTM up to 120 m away. The tool +then says how many edges of which layer run more than a metre away, and how far the farthest does. A +world projection (World Mercator, Plate Carrée, Robinson, Equal Earth and the like), whose plane has +the antimeridian as a seam and the poles as lines, is worked on in longitude/latitude, as Web +Mercator is. If another input has a place that system can't hold, the tool works in +longitude/latitude instead, and its message says so. A layer in longitude/latitude, Web Mercator or +another geographic system is worked on in longitude/latitude, as before. In a projected system a +tool works in, distances in metres (Buffer's, Simplify's tolerance, Points Along Lines' spacing, +Near's, and the search distances of Select Layer By Location and Spatial Join) are measured flat +there, in its unit, as distances in a projected system are: a kilometre is 1000 of its metres, or +3280.833 of its US survey feet. A flat metre is not quite a metre on the ground: in a UTM zone, from +1.0004 m on its central meridian to about 0.999 m at its edges on the equator (0.9998 m at 48.7°N), +so a buffer of 100 km around a point 2.5° east of the central meridian at 48.7°N reaches 100,017 m +on the ground on its west side and 99,972 m on its east side. Near's nearest point is that system's +x and y, and Points Along Lines' angle is from grid north. IDW Interpolation, Kriging and Kernel +Density make their surface in that system, from its points' own coordinates, unless another system +is given; Zonal Statistics and Tabulate Area place their zones on a raster in that system as they +are. A surface given another projected system, or a raster in one, gets the points or zones +converted straight into it, by the transformation between the two datums where they differ; a raster +in longitude/latitude or Web Mercator gets them through WGS 84. Their rasters aren't converted, and +they don't count bent edges. Area, length and perimeter fields stay on the ellipsoid. In the desktop app a tool runs in the background, so the map and the rest of the window stay in use. While it runs, the Tools pane shows its name, a **Cancel** button and, for the tools that @@ -734,8 +734,9 @@ across the extent and coarsens for large inputs. The result is a Float32 GeoTIFF IDW Interpolation and Ordinary Kriging make their raster in the projected coordinate system given as `crs` (such as `EPSG:32616` for UTM zone 16N, or a State Plane code), and then take the extent, pixel size and Kriging's `range` in its units, usually metres or feet. Without `crs` -they use the projected system the layer was read in, as Kernel Density does, and say so, naming -it; a layer read in longitude and latitude gives a raster in degrees, with all three in degrees. +they use the projected system the layer is held in (or else was read in), as Kernel Density +does, and say so, naming it; a layer read in longitude and latitude gives a raster in degrees, +with all three in degrees. `crs: "EPSG:4326"` makes it in degrees whatever the layer was read in, as these tools always did before `crs` was there; so does a layer read in a system that can't hold a raster's cells (a geocentric one) or that this version can't project to, with a notice saying which. A script @@ -2279,9 +2280,10 @@ zone; overlapping zones can therefore report the same missing cell more than onc `measure: "Count"` instead puts integer cell counts in the class columns. Cells are counted by **centre**, as in Zonal Statistics: a cell whose centre is inside a zone -contributes its whole area; there is no partial-cell weighting. Polygon coordinates are stored -in WGS 84 and transformed onto the raster's grid; the polygon layer's original CRS metadata -is not applied again. Invalid features and parts that cannot be placed on the raster are +contributes its whole area; there is no partial-cell weighting. Zones held in a projected +system are placed on the raster's grid from their own coordinates (converted straight into the +raster's system when it is another); other zones are placed from longitude/latitude. Invalid +features and parts that cannot be placed on the raster are counted in notices, with valid features and grid-projected parts retained. For geographic and **Web Mercator** rasters, cell corners are transformed to WGS 84 and @@ -2315,7 +2317,7 @@ Open **Zonal Statistics** through Command Search, or choose it in the Workflows Zonal Statistics uses the selected polygon features when the layer has a selection. It keeps original geometries and fields, and reports features with missing or rejected polygon parts. -If any polygon part fails validation or transformation to WGS 84, the feature receives count 0 and null +If any polygon part fails validation, the feature receives count 0 and null statistics. If a part subsequently fails projection onto the raster grid, it is omitted and reported; statistics cover the remaining valid parts. Large overlapping zones each require a separate pass over their raster window. From 08b6cbebb49ff7a94ca8a33c80657bb10a6214d4 Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Sun, 22 Nov 2026 12:26:35 +0100 Subject: [PATCH 4/5] Review: Kernel Density's guide paragraph names the held system --- docs/user-guide/analysis.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index 092bad5e4f..bdabd0fea8 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -524,7 +524,7 @@ Points can optionally be weighted by a numeric population field (invalid or non- are excluded and reported in the tool messages; for multipoint features, each constituent point part receives the feature's weight, a part with a coordinate missing or infinite is left out and counted, and a feature with no finite part is skipped). Calculations are performed in the linear units -of a projected coordinate system (defaults to the layer's projected system; if the input layer lacks a +of a projected coordinate system (defaults to the projected system the layer is held in, or else was read in; if the input layer lacks a coordinate system or is in degrees, or to project into a specific system, supply a projected system via `crs`, e.g. `EPSG:32618`). Geocentric systems such as `EPSG:4978` (X, Y and Z from the Earth's centre) are refused, whether supplied via `crs` or inherited from the layer: their three axes do not From 241ada323a02d8173a74719d259acaa635479a1e Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Sun, 22 Nov 2026 13:49:41 +0100 Subject: [PATCH 5/5] Review: zone vertices past Web Mercator's limit clamp as before; a held layer's places another system can't hold are said (tested); Kernel Density's default named; guide and comments --- crates/analysis/src/rasterops.rs | 2 +- crates/analysis/src/tools.rs | 20 +++++- crates/analysis/src/tools/tabulate_area.rs | 7 +- crates/engine/src/tests/held_layers.rs | 75 ++++++++++++++++++++++ docs/user-guide/analysis.md | 4 +- 5 files changed, 101 insertions(+), 7 deletions(-) diff --git a/crates/analysis/src/rasterops.rs b/crates/analysis/src/rasterops.rs index a90dbf9f17..1abe9657e3 100644 --- a/crates/analysis/src/rasterops.rs +++ b/crates/analysis/src/rasterops.rs @@ -1404,7 +1404,7 @@ impl ToWorld<'_> { fn world(&self, c: Coord) -> Option { match self { Self::LonLat(tr) => tr.from_lonlat(c), - Self::Own(to) => to.place(c), + Self::Own(to) => to.vertex(c), } } } diff --git a/crates/analysis/src/tools.rs b/crates/analysis/src/tools.rs index d826d119ef..243ce94523 100644 --- a/crates/analysis/src/tools.rs +++ b/crates/analysis/src/tools.rs @@ -5203,6 +5203,22 @@ impl ToGrid { let via = in_projected(self.crs, &self.to, lonlat)?; Some(self.direct.as_ref().map_or(via, |d| d.point_near(c, via))) } + + /// A polygon's vertex in the grid's system, as the grid's transformer takes a place in + /// longitude/latitude, with no check: Web Mercator takes a latitude past 85.05° as 85.05°, so a + /// zone reaching past it keeps its part below, as zones in longitude/latitude always did. Then + /// the direct operation's coordinates where it lands near that, as [`ToGrid::place`]. + pub(crate) fn vertex(&self, c: Coord) -> Option { + if self.same { + return c.is_finite().then_some(c); + } + let lonlat = match &self.from { + Some(t) => t.to_lonlat(c)?, + None => c, + }; + let via = self.to.from_lonlat(lonlat).filter(|p| p.is_finite())?; + Some(self.direct.as_ref().map_or(via, |d| d.point_near(c, via))) + } } /// The note on a system an interpolation took from the layer (`p`'s `crs` empty), naming the values @@ -5292,9 +5308,11 @@ fn kernel_density_tool(inp: &dyn Inputs, p: &Json) -> Result } let crs_text = s(p, "crs").trim(); + // The system the layer is held in, in a run in its own; else the one it was read in. + let layer_crs = if inp.work_crs() == Crs::LonLat { ds.crs } else { Some(inp.work_crs()) }; let (crs, crs_note) = if !crs_text.is_empty() { crs_with_compatibility_note(crs_text)? - } else if let Some(c) = if inp.work_crs() == Crs::LonLat { ds.crs } else { Some(inp.work_crs()) } { + } else if let Some(c) = layer_crs { (c, None) } else { return Err(format!( diff --git a/crates/analysis/src/tools/tabulate_area.rs b/crates/analysis/src/tools/tabulate_area.rs index c5a63187cc..64ecd2150b 100644 --- a/crates/analysis/src/tools/tabulate_area.rs +++ b/crates/analysis/src/tools/tabulate_area.rs @@ -52,9 +52,10 @@ pub(super) fn run_on(inp: &dyn Inputs, p: &Json, threads: Option) -> Resu } let index: HashMap = classes.iter().enumerate().map(|(i, &v)| (class_key(v), i)).collect(); let areas = CellAreas::new(r, count); - // The largest grouped geometry's copies in lon/lat and on the grid, the largest raster - // mask and its trimmed copy, plus each zone's dense class totals. Conservatively include - // the shared row cache in each worker's estimate so it stays within the scratch allowance. + // The largest grouped geometry's copies (taken as four, in any system) and on the grid, the + // largest raster mask and its trimmed copy, plus each zone's dense class totals. + // Conservatively include the shared row cache in each worker's estimate so it stays within + // the scratch allowance. let geometry_bytes = groups .iter() .map(|group| { diff --git a/crates/engine/src/tests/held_layers.rs b/crates/engine/src/tests/held_layers.rs index 017ce4e701..9f12c055b8 100644 --- a/crates/engine/src/tests/held_layers.rs +++ b/crates/engine/src/tests/held_layers.rs @@ -2170,3 +2170,78 @@ fn zones_reach_a_raster_by_the_direct_operation() { assert_eq!(stats[0], stats[1]); assert_eq!(tables[0], tables[1]); } + +/// NSIDC Sea Ice Polar Stereographic North, a projected system that holds the pole. +const POLAR: Crs = Crs::Epsg(3413); + +/// The places a layer's points or zones are taken to in another system are said when that system +/// can't hold them: IDW from points held in a polar system, on a grid in Web Mercator, leaves out +/// the one at the pole and counts it. A zone held there that reaches past Web Mercator's 85.05° +/// keeps its part below the limit on a Web Mercator raster, as a zone in longitude/latitude +/// always did (its vertices beyond are taken as on the limit): Zonal Statistics counts its cells +/// and says no part was left out. A part that reaches a place the raster's system can't hold at +/// all is left out and said, by Zonal Statistics and Tabulate Area, its other parts counted. +#[test] +fn a_held_layers_places_another_system_cant_hold_are_said() { + use rustgis_data::raster::{ColorHint, GeoTransform, Raster}; + let to = Crs::LonLat.to(POLAR).unwrap(); + let mut s = Session::new(Project::default()); + let pts = [Coord::new(0.0, 90.0), Coord::new(5.0, 70.0), Coord::new(8.0, 72.0)]; + add_in(&mut s, "Ice", GeometryType::Point, pts.iter().map(|c| Geometry::Point(to.point(*c).unwrap())).collect(), POLAR); + let mark = s.notice_mark(); + let answer = s + .run( + "gp.run", + &json!({"tool": "idwInterpolation", "params": {"input": "Ice", "field": "v", "pixelSize": 10000, "crs": "EPSG:3857", "output": "Idw"}}), + ) + .unwrap(); + let said: Vec = s.notices_since(mark).iter().map(|n| n.text.clone()).chain([answer.to_string()]).collect(); + assert!(said.iter().any(|t| t.contains("1 point(s) beyond what") && t.contains("85.05")), "{said:?}"); + assert!(said.iter().any(|t| t.contains("from 2 points")), "{said:?}"); + + // Web Mercator from 0° to 10°E, 80°N to its limit, in cells of 10 km, all 1. + let (top, bottom): (f64, f64) = (20_037_508.342_789_244, 15_538_711.096_309_224); + let (w, h) = (112u32, ((top - bottom) / 10_000.0).ceil() as u32); + let gt = GeoTransform { origin_x: 0.0, origin_y: top, pixel_width: 10_000.0, pixel_height: -10_000.0 }; + let r = Raster::new("merc", w, h, vec![vec![1.0; (w * h) as usize]], gt, Crs::WebMercator, None, ColorHint::Gray, "Float32").unwrap(); + s.map_mut().add_raster("merc", rustgis_map::raster::RasterLayer::from_path(r, "merc.tif")); + // From 2°E to 8°E, 83°N to 87°N, its edges followed in steps of a degree. + let mut ring: Vec = (2..=8).map(|x| Coord::new(f64::from(x), 83.0)).collect(); + ring.extend((84..=87).map(|y| Coord::new(8.0, f64::from(y)))); + ring.extend((2..8).rev().map(|x| Coord::new(f64::from(x), 87.0))); + ring.extend((83..87).rev().map(|y| Coord::new(2.0, f64::from(y)))); + let ring: Vec = ring.iter().map(|c| to.point(*c).unwrap()).collect(); + add_in(&mut s, "Cap", GeometryType::Polygon, vec![Geometry::Polygon(vec![vec![ring]])], POLAR); + let mark = s.notice_mark(); + let answer = + s.run("gp.run", &json!({"tool": "zonalStats", "params": {"raster": "merc", "polygons": "Cap", "output": "CapStats"}})).unwrap(); + let said: Vec = s.notices_since(mark).iter().map(|n| n.text.clone()).chain([answer.to_string()]).collect(); + assert!(!said.iter().any(|t| t.contains("could not be projected") || t.contains("invalid geometry")), "{said:?}"); + assert!(field_numbers(&s, "CapStats", "merc_count")[0] > 100.0, "{:?}", field_numbers(&s, "CapStats", "merc_count")); + + // A zone of two parts on a raster in Antarctic Polar Stereographic (EPSG:3031), which can't + // hold the North Pole: the part reaching it is left out and said, the other one counted. + let south = Crs::Epsg(3031); + let into = Crs::LonLat.to(south).unwrap(); + let near: Vec = + [(10.0, 0.0), (11.0, 0.0), (11.0, 1.0), (10.0, 1.0), (10.0, 0.0)].iter().map(|(x, y)| Coord::new(*x, *y)).collect(); + let mut bounds = rustgis_geom::Extent::EMPTY; + near.iter().for_each(|c| bounds.expand(into.point(*c).unwrap())); + let (w, h) = (((bounds.max_x - bounds.min_x) / 1000.0).ceil() as u32 + 2, ((bounds.max_y - bounds.min_y) / 1000.0).ceil() as u32 + 2); + let gt = GeoTransform { origin_x: bounds.min_x - 1000.0, origin_y: bounds.max_y + 1000.0, pixel_width: 1000.0, pixel_height: -1000.0 }; + let r = Raster::new("south", w, h, vec![vec![1.0; (w * h) as usize]], gt, south, None, ColorHint::Gray, "Float32").unwrap(); + s.map_mut().add_raster("south", rustgis_map::raster::RasterLayer::from_path(r, "south.tif")); + let pole: Vec = [(0.0, 89.0), (90.0, 89.0), (0.0, 90.0), (0.0, 89.0)].iter().map(|(x, y)| Coord::new(*x, *y)).collect(); + let parts = [near, pole].map(|ring| vec![ring.iter().map(|c| to.point(*c).unwrap()).collect::>()]); + add_in(&mut s, "Split", GeometryType::Polygon, vec![Geometry::Polygon(parts.to_vec())], POLAR); + for (tool, params) in [ + ("zonalStats", json!({"raster": "south", "polygons": "Split", "output": "SplitStats"})), + ("tabulateArea", json!({"raster": "south", "zones": "Split", "measure": "Count", "output": "SplitClasses"})), + ] { + let mark = s.notice_mark(); + let answer = s.run("gp.run", &json!({"tool": tool, "params": params})).unwrap(); + let said: Vec = s.notices_since(mark).iter().map(|n| n.text.clone()).chain([answer.to_string()]).collect(); + assert!(said.iter().any(|t| t.contains("1 polygon part(s) could not be projected onto the raster grid")), "{tool}: {said:?}"); + } + assert!(field_numbers(&s, "SplitStats", "south_count")[0] > 100.0, "{:?}", field_numbers(&s, "SplitStats", "south_count")); +} diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index bdabd0fea8..aed8f5cf36 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -735,8 +735,8 @@ IDW Interpolation and Ordinary Kriging make their raster in the projected coordi as `crs` (such as `EPSG:32616` for UTM zone 16N, or a State Plane code), and then take the extent, pixel size and Kriging's `range` in its units, usually metres or feet. Without `crs` they use the projected system the layer is held in (or else was read in), as Kernel Density -does, and say so, naming it; a layer read in longitude and latitude gives a raster in degrees, -with all three in degrees. +does without a note, and say so, naming it; a layer read in longitude and latitude gives a +raster in degrees, with all three in degrees. `crs: "EPSG:4326"` makes it in degrees whatever the layer was read in, as these tools always did before `crs` was there; so does a layer read in a system that can't hold a raster's cells (a geocentric one) or that this version can't project to, with a notice saying which. A script