From 780ef1ba10d9d4d5f9271c7865610bd843ae0147 Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Sun, 22 Nov 2026 13:19:15 +0100 Subject: [PATCH 01/14] Rasterize, raster clip and spectral zones work from a held polygon layer's own coordinates (#2032 C2e-4b) --- crates/analysis/src/rasterops.rs | 85 +++++++++++++++++++++++--- crates/analysis/src/warp.rs | 11 +++- crates/engine/src/cmd/imagery.rs | 81 ++++++++++++------------ crates/engine/src/tests/held_layers.rs | 81 ++++++++++++++++++++---- docs/user-guide/analysis.md | 9 ++- 5 files changed, 201 insertions(+), 66 deletions(-) diff --git a/crates/analysis/src/rasterops.rs b/crates/analysis/src/rasterops.rs index 1abe9657e3..f0c7e4242c 100644 --- a/crates/analysis/src/rasterops.rs +++ b/crates/analysis/src/rasterops.rs @@ -1012,21 +1012,85 @@ pub fn classify_min_distance(r: &Raster, bands: &[usize], means: &[(f32, Vec]) -> Result, usize)>, crate::control::Cancelled> { crate::control::begin(r.height as usize); - means_under(r, bands, rings, |rows| { + means_under(r, &ZoneIn::LonLat, bands, rings, |rows| { crate::control::check()?; crate::control::advance(rows); Ok(()) }) } +/// [`zonal_means`] of a polygon whose rings are in `from`: longitude/latitude, or the system its +/// layer holds its coordinates in. A cell's centre is converted into that system to be tested +/// (none of it when it is the raster's own), by the direct operation between two datums. +pub fn zonal_means_in(r: &Raster, from: Crs, bands: &[usize], rings: &[Vec]) -> Result, usize)>, String> { + let zone = ZoneIn::new(r, from)?; + crate::control::begin(r.height as usize); + Ok(means_under(r, &zone, bands, rings, |rows| { + crate::control::check()?; + crate::control::advance(rows); + Ok(()) + })?) +} + +/// The system a zone's rings are in, and how a raster's cells and the zone meet there: in +/// longitude/latitude through the raster's transformer, or in a layer's own system +/// ([`crate::tools::ToGrid`] both ways). +pub(crate) enum ZoneIn { + LonLat, + Own { to_zone: crate::tools::ToGrid, to_grid: crate::tools::ToGrid }, +} + +impl ZoneIn { + pub(crate) fn new(r: &Raster, from: Crs) -> Result { + Ok(if from == Crs::LonLat { + Self::LonLat + } else { + Self::Own { to_zone: crate::tools::ToGrid::new(r.crs, from)?, to_grid: crate::tools::ToGrid::new(from, r.crs)? } + }) + } + + /// A place in the raster's system in the zone's. + fn zone(&self, r: &Raster, w: Coord) -> Option { + match self { + Self::LonLat => r.transformer().to_lonlat(w), + Self::Own { to_zone, .. } => to_zone.place(w), + } + } + + /// A place in the zone's system in the raster's. + fn grid(&self, r: &Raster, c: Coord) -> Option { + match self { + Self::LonLat => r.transformer().from_lonlat(c), + Self::Own { to_grid, .. } => to_grid.place(c), + } + } +} + +/// [`polygon_mask_with_failures`] for polygons in `from`: longitude/latitude, or the system their +/// layer holds its coordinates in, converted into the raster's (none of it when that is the +/// raster's own), by the direct operation between two datums. +pub fn polygon_mask_in( + r: &Raster, + from: Crs, + polygons: &[Vec>], + failed_parts: &mut Vec, +) -> Result, Range, Vec)>, String> { + if from == Crs::LonLat { + return polygon_mask_with_failures(r, polygons, failed_parts); + } + let to = crate::tools::ToGrid::new(from, r.crs)?; + polygon_mask_on(ToWorld::Own(&to), &r.transform, (r.width, r.height), polygons, failed_parts) +} + /// [`zonal_means`], `each_rows(n)` asked as the raster's rows go by, `n` at a time (each row /// once, all of them): an error stops it. /// -/// A cell counts when its centre, in longitude/latitude, lies in the zone (inside the outer ring -/// and in no hole). Only the cells in the zone's window are tested ([`zone_window`]), not every +/// A cell counts when its centre, in the zone's system (`zone`), lies in the zone (inside the +/// outer ring and in no hole). Only the cells in the zone's window are tested ([`zone_window`]), not every /// cell of the raster, in the same row-major order, so the sums are those of testing them all. fn means_under( r: &Raster, + zone: &ZoneIn, bands: &[usize], rings: &[Vec], mut each_rows: impl FnMut(usize) -> Result<(), crate::control::Cancelled>, @@ -1037,13 +1101,13 @@ fn means_under( } let mut sums = vec![0.0; bands.len()]; let mut n = 0usize; - let (cols, rows) = zone_window(r, &e); + let (cols, rows) = zone_window(r, &e, |c| zone.grid(r, c)); each_rows((r.height - (rows.end - rows.start)) as usize)?; for row in rows { each_rows(1)?; for col in cols.clone() { let w = r.transform.to_world(f64::from(col) + 0.5, f64::from(row) + 0.5); - let Some(ll) = r.transformer().to_lonlat(w) else { continue }; + let Some(ll) = zone.zone(r, w) else { continue }; if !e.contains(ll) || !rustgis_data::geometry::polygon_contains(rings, ll) { continue; } @@ -1057,8 +1121,9 @@ fn means_under( Ok((n > 0).then(|| (sums.into_iter().map(|s| s / n as f64).collect(), n))) } -/// The columns and rows of `r` whose cell centres can fall in the longitude/latitude extent `e`: -/// its outline placed on the raster's grid, with two cells to spare. Each side is sampled, and +/// The columns and rows of `r` whose cell centres can fall in the extent `e`, in the zone's system +/// (`to_grid` places it in the raster's): its outline placed on the raster's grid, with two cells +/// to spare. Each side is sampled, and /// each stretch between samples near the raster is halved until its ends are at most a cell /// apart, so a side that curves on the grid (a parallel on a polar raster) bows only a fraction /// of a cell between them, whatever the zone's size. A stretch whose ends are farther from the @@ -1066,7 +1131,7 @@ fn means_under( /// within one stretch (a sixty-fourth of the side at first), which a projection's smooth image of /// a parallel or meridian doesn't. The whole raster when a point can't be placed; none when `e` is /// empty. -fn zone_window(r: &Raster, e: &Extent) -> (Range, Range) { +fn zone_window(r: &Raster, e: &Extent, to_grid: impl Fn(Coord) -> Option) -> (Range, Range) { if e.is_empty() { return (0..0, 0..0); } @@ -1076,7 +1141,7 @@ fn zone_window(r: &Raster, e: &Extent) -> (Range, Range) { let whole = (0..r.width, 0..r.height); let (w, h) = (f64::from(r.width), f64::from(r.height)); let place = |ll: Coord| { - let (col, row) = r.transform.to_pixel(r.transformer().from_lonlat(ll)?); + let (col, row) = r.transform.to_pixel(to_grid(ll)?); (col.is_finite() && row.is_finite()).then_some((col, row)) }; let sides: [(Coord, Coord); 4] = [ @@ -1133,7 +1198,7 @@ pub fn class_means(r: &Raster, bands: &[usize], polygons: &[(String, Vec { let total = c.2 + n; diff --git a/crates/analysis/src/warp.rs b/crates/analysis/src/warp.rs index 5c2c0b6736..0bb691480f 100644 --- a/crates/analysis/src/warp.rs +++ b/crates/analysis/src/warp.rs @@ -524,6 +524,13 @@ pub struct Burned { /// goes by each shape's cells and crossings, with no cap on their total; a run under a /// [`crate::control::Control`] stops between shapes and counts them. pub fn rasterize(g: &Grid, shapes: &[Shape], nodata: f32) -> Result { + rasterize_in(g, Crs::LonLat, shapes, nodata) +} + +/// [`rasterize`] of shapes in `from`: longitude/latitude, or the system their layer holds its +/// coordinates in, converted into the grid's (none of it when that is the grid's own), by the +/// direct operation between two datums. +pub fn rasterize_in(g: &Grid, from: Crs, shapes: &[Shape], nodata: f32) -> Result { let max = max_samples(); let too_big = || format!("{} × {} cells are more than this computer's {max}: give a larger cellSize or a smaller extent", g.width, g.height); @@ -535,6 +542,8 @@ pub fn rasterize(g: &Grid, shapes: &[Shape], nodata: f32) -> Result Result Result, String> { - let crs = ds.coord_crs(); - if crs == Crs::LonLat { - return Ok(None); - } - crs.transformer().map(Some).map_err(|e| format!("{}: {e}", ds.name)) -} - /// `raster.rasterize`: a polygon layer's selected (or all) features burned onto a grid given as /// `raster.project`'s is, each cell whose centre falls in a polygon taking its field's value, a /// text field's code or one `value` (see `rustgis_analysis::warp::rasterize`). A new layer, and @@ -504,12 +491,13 @@ fn rasterize(s: &mut Session, p: &Value) -> CmdResult { rows.dedup(); let (mut no_value, mut no_polygon) = (0, 0); let mut burns: Vec<(Vec>>, rustgis_data::Value)> = Vec::new(); - // Burned from longitude/latitude, whatever system the layer holds its coordinates in. - let own = held_transformer(ds)?; + // Burned from the system the layer holds its coordinates in (none of it converted when the + // grid is in it too). + let held = ds.coord_crs(); for row in rows { let Some(feature) = ds.features.get(row) else { continue }; let parts = match &feature.geometry { - Some(Geometry::Polygon(polys)) => rasterops::transform_feature_polygons_to_lonlat(polys, own.as_ref()).ok(), + Some(Geometry::Polygon(polys)) => rasterops::transform_feature_polygons_to_lonlat(polys, None).ok(), _ => None, }; let Some(parts) = parts else { @@ -572,13 +560,26 @@ fn rasterize(s: &mut Session, p: &Value) -> CmdResult { if shapes.is_empty() { return Err(format!("{ln} has no polygons with a value to burn")); } - // By default, the layer's coordinate system and the polygons' bounds. - let lonlat = shapes.iter().flat_map(|s| s.parts.iter().flatten().flatten()).fold(Extent::EMPTY, |mut e, c| { + // By default, the system the layer holds its coordinates in (else the one it was read in) and + // the polygons' bounds. + let own = shapes.iter().flat_map(|s| s.parts.iter().flatten().flatten()).fold(Extent::EMPTY, |mut e, c| { e.expand(*c); e }); - let crs = ds.crs.unwrap_or(Crs::LonLat); - let grid = grid_param(s, p, crs, |crs| Ok((warp::bounds_in([lonlat.min_x, lonlat.min_y, lonlat.max_x, lonlat.max_y], crs)?, None)))?; + let crs = if held == Crs::LonLat { ds.crs.unwrap_or(Crs::LonLat) } else { held }; + let grid = grid_param(s, p, crs, |crs| { + if crs == held { + return Ok(([own.min_x, own.min_y, own.max_x, own.max_y], None)); + } + // In another system, the bounds of the polygons' box in longitude/latitude, as before. + let to = held.to(Crs::LonLat)?; + let lonlat = + shapes.iter().flat_map(|s| s.parts.iter().flatten().flatten()).filter_map(|c| to.point(*c)).fold(Extent::EMPTY, |mut e, c| { + e.expand(c); + e + }); + Ok((warp::bounds_in([lonlat.min_x, lonlat.min_y, lonlat.max_x, lonlat.max_y], crs)?, None)) + })?; // The smallest pixel type the GeoTIFF writer keeps that holds every value and the no-data. let whole = |max: f64| shapes.iter().map(|s| f64::from(s.value)).chain([nodata]).all(|v| v.fract() == 0.0 && (0.0..=max).contains(&v)); let data_type = if whole(255.0) { @@ -588,7 +589,7 @@ fn rasterize(s: &mut Session, p: &Value) -> CmdResult { } else { "Float32" }; - let burned = warp::rasterize(&grid, &shapes, nodata as f32)?; + let burned = warp::rasterize_in(&grid, held, &shapes, nodata as f32)?; if burned.cells == 0 { return Err(format!("no cell centre of the grid falls inside {ln}'s polygons: give a smaller cellSize, or a grid over them")); } @@ -1033,10 +1034,10 @@ fn spectral_read(s: &mut Session, p: &Value, r: &Arc, zone: Option<&str> return answer(json!({"bands": names, "profiles": profiles})); } if let Some(z) = zone { - let rings = zone_rings(s, z)?; + let (crs, rings) = zone_rings(s, z)?; // Read on a thread of its own as the app sent the command, when still of this raster and // this polygon; here otherwise. - let (means, n) = zone_means(s, r, rings)?.ok_or("no pixels fall in the zone")?; + let (means, n) = zone_means(s, r, crs, rings)?.ok_or("no pixels fall in the zone")?; return answer(json!({"bands": names, "values": means, "pixels": n})); } let c = Coord::new(f(p, "lon").ok_or("give lon and lat, points or a zone")?, f(p, "lat").ok_or("lat is required")?); @@ -1045,24 +1046,19 @@ fn spectral_read(s: &mut Session, p: &Value, r: &Arc, zone: Option<&str> answer(json!({"bands": names, "values": vals, "pixel": [col, row]})) } -/// The polygon a spectral zone names: the polygon layer `z`'s selected feature, or its first. -fn zone_rings(s: &Session, z: &str) -> Result>, String> { +/// The polygon a spectral zone names: the polygon layer `z`'s selected feature, or its first, in +/// the system the layer holds its coordinates in. +fn zone_rings(s: &Session, z: &str) -> Result<(Crs, Vec>), String> { let l = s.map().layer_by_name(z).filter(|l| l.geometry_type() == GeometryType::Polygon).ok_or_else(|| format!("no polygon layer '{z}'"))?; let row = l.selection.first().copied().unwrap_or(0); let Some(g) = l.dataset.features.get(row).and_then(|f| f.geometry.as_ref()) else { return Err("the zone has no polygon".into()); }; - // In longitude/latitude, whatever system the layer holds its coordinates in. - let Geometry::Polygon(polys) = &*l - .dataset - .lonlat_conversion() - .and_then(|to| rustgis_data::Dataset::geometry_to_lonlat_by(&to, g)) - .map_err(|e| format!("{z}: {e}"))? - else { + let Geometry::Polygon(polys) = g else { return Err("the zone has no polygon".into()); }; - polys.first().cloned().ok_or_else(|| "the zone has no polygon".into()) + Ok((l.dataset.coord_crs(), polys.first().cloned().ok_or("the zone has no polygon")?)) } /// A zone's means, every band's: those a script's copy of the session read, when of this raster @@ -1070,9 +1066,9 @@ fn zone_rings(s: &Session, z: &str) -> Result>, String> { /// take). A raster a tool made earlier in the script is decoded apart on each side, so its zones /// are read again here. #[cfg_attr(target_arch = "wasm32", expect(unused_variables, reason = "zones are read ahead on the desktop only"))] -fn zone_means(s: &mut Session, r: &Arc, rings: Vec>) -> Result, usize)>, String> { +fn zone_means(s: &mut Session, r: &Arc, crs: Crs, rings: Vec>) -> Result, usize)>, String> { #[cfg(not(target_arch = "wasm32"))] - let same = |z: &ZoneMeans| Arc::ptr_eq(&z.raster, r) && z.rings == rings; + let same = |z: &ZoneMeans| Arc::ptr_eq(&z.raster, r) && z.crs == crs && z.rings == rings; #[cfg(not(target_arch = "wasm32"))] if let Some(ZonesAhead::Taking(zones)) = &mut s.zones_ahead { match zones.pop_front() { @@ -1087,10 +1083,11 @@ fn zone_means(s: &mut Session, r: &Arc, rings: Vec>) -> Resul } } let all: Vec = (0..r.band_count()).collect(); - let means = rasterops::zonal_means(r, &all, &rings).map_err(String::from); + // The cells are tested in the zone's own system: none of it converted when it is the raster's. + let means = rasterops::zonal_means_in(r, crs, &all, &rings); #[cfg(not(target_arch = "wasm32"))] if let Some(ZonesAhead::Recording(zones)) = &mut s.zones_ahead { - zones.push(ZoneMeans { raster: r.clone(), rings, means: means.clone() }); + zones.push(ZoneMeans { raster: r.clone(), crs, rings, means: means.clone() }); } means } @@ -1108,6 +1105,7 @@ pub(crate) enum ZonesAhead { #[cfg(not(target_arch = "wasm32"))] pub(crate) struct ZoneMeans { raster: Arc, + crs: Crs, rings: Vec>, means: Result, usize)>, String>, } @@ -1254,12 +1252,13 @@ pub(crate) fn process_work(s: &Session, p: &Value) -> Result>> = Vec::new(); let mut failed_features = Vec::new(); - // In longitude/latitude, whatever system the layer holds its coordinates in. - let own = held_transformer(&l.dataset)?; + // In the system the layer holds its coordinates in, converted onto the raster's grid + // (none of it when it is the raster's own). + let held = l.dataset.coord_crs(); for &row in &rows { let Some(f) = l.dataset.features.get(row) else { continue }; match &f.geometry { - Some(Geometry::Polygon(polys)) => match rasterops::transform_feature_polygons_to_lonlat(polys, own.as_ref()) { + Some(Geometry::Polygon(polys)) => match rasterops::transform_feature_polygons_to_lonlat(polys, None) { Ok(transformed) => { polygons.extend(transformed); } @@ -1285,7 +1284,7 @@ pub(crate) fn process_work(s: &Session, p: &Value) -> Result rustgis_map::Camera { s.map().camera } -/// Rasterizing a held layer gives the grid of the same layer held in longitude/latitude (cells -/// off the parcels' edges, which may read a hair either side of a cell's through UTM). +/// Rasterizing a held layer onto a grid in longitude/latitude gives the grid of the same layer held +/// in longitude/latitude (cells off the parcels' edges, which may read a hair either side of a +/// cell's through UTM). Without a `crs`, a held layer is burned in its own system +/// (`a_held_layer_is_burned_in_its_own_system`). #[test] fn a_held_layer_is_rasterized_alike() { let mut ss = both(); - let [a, b] = run_both(&mut ss, "raster.rasterize", &json!({"layer": "Parcels", "field": "n", "cellSize": 0.0007, "nodata": -1})); + let [a, b] = run_both( + &mut ss, + "raster.rasterize", + &json!({"layer": "Parcels", "field": "n", "cellSize": 0.0007, "nodata": -1, "crs": "EPSG:4326"}), + ); assert_eq!(a, b); // And the same cells: every value, the no-data ones too. let [ga, gb] = [(&ss[0], &a), (&ss[1], &b)] @@ -945,7 +951,7 @@ fn raster_cells(s: &Session, answer: &Value) -> (u32, u32, Vec>) { #[test] fn a_held_polygon_layer_reads_rasters_alike() { let mut ss = both(); - run_both(&mut ss, "raster.rasterize", &json!({"layer": "Parcels", "field": "n", "cellSize": 0.0007, "nodata": -1})); + run_both(&mut ss, "raster.rasterize", &json!({"layer": "Parcels", "field": "n", "cellSize": 0.0007, "nodata": -1, "crs": "EPSG:4326"})); let raster = "Parcels raster"; let [a, b] = run_both(&mut ss, "raster.spectral", &json!({"layer": raster, "zone": "Parcels"})); assert_eq!(a["pixels"], b["pixels"], "spectral zone"); @@ -2122,13 +2128,12 @@ fn a_grid_in_another_system_takes_the_direct_operation() { 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() { +/// A session with rasters `grid` (10 m by 10 m of 10 cm cells in UTM 32N on ETRS89, each holding +/// its column and row, col + 1000 × row) and `blocks` (the same cells in 100 classes of a metre +/// square), and two layers of one 6 m square: `Zone`, held in Gauss-Krüger zone 3 on DHDN, and +/// `Converted`, the same square converted into UTM by [`Crs::to`] and held there. Through WGS 84 +/// the square lands 0.44 m from where the direct operation puts it. +fn datum_pair() -> Session { 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). @@ -2149,6 +2154,17 @@ fn zones_reach_a_raster_by_the_direct_operation() { 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); + s +} + +/// 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() { + let mut s = datum_pair(); let mut stats = Vec::new(); let mut tables = Vec::new(); for zone in ["Zone", "Converted"] { @@ -2245,3 +2261,46 @@ fn a_held_layers_places_another_system_cant_hold_are_said() { } assert!(field_numbers(&s, "SplitStats", "south_count")[0] > 100.0, "{:?}", field_numbers(&s, "SplitStats", "south_count")); } + +/// Rasterize, raster clip and a spectral zone burn, cut and read a polygon held in its own system +/// from its coordinates there: a square held in Gauss-Krüger zone 3 on DHDN burned onto, cut out +/// of and read on a raster in UTM 32N on ETRS89 gives the cells the same square converted there +/// by [`Crs::to`] gives, on cells of 10 cm, where the way through WGS 84 is 0.44 m off. +#[test] +fn a_raster_takes_a_held_polygon_by_the_direct_operation() { + let mut s = datum_pair(); + let mut got = Vec::new(); + for zone in ["Zone", "Converted"] { + let burned = s + .run("raster.rasterize", &json!({"layer": zone, "value": 5, "grid": "grid", "nodata": 0, "name": format!("{zone} burned")})) + .unwrap(); + let clipped = s + .run("raster.process", &json!({"layer": "grid", "operation": "clip", "polygon": zone, "name": format!("{zone} clip")})) + .unwrap(); + let read = s.run("raster.spectral", &json!({"layer": "grid", "zone": zone})).unwrap(); + got.push((raster_cells(&s, &burned), raster_cells(&s, &clipped), read["pixels"].clone(), read["values"].clone())); + } + // About 60 × 60 cells. + assert!(got[0].2.as_u64().unwrap() > 3000, "{:?}", got[0].2); + assert!(got[0].0.2.iter().filter(|v| v.is_some()).count() > 3000); + assert_eq!(got[0], got[1]); +} + +/// A held layer is burned in its own system by default, from its coordinates as they are: a +/// 100 m square whose edges run through cell centres (a cell's west and south edge taken in, its +/// east and north left out) covers exactly 10 × 10 cells of 10 m, in UTM, where a run through +/// longitude/latitude moved its edges a hair off those centres. The square lies 1500 km east of +/// the zone's central meridian, where that round trip doesn't come back to the same bits. +#[test] +fn a_held_layer_is_burned_in_its_own_system() { + let (x0, y0) = (2_000_005.0, 5_401_305.0); + let ring: Vec = + [(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0), (0.0, 0.0)].iter().map(|(x, y)| Coord::new(x0 + x, y0 + y)).collect(); + let mut s = Session::new(Project::default()); + add_in(&mut s, "Square", GeometryType::Polygon, vec![Geometry::Polygon(vec![vec![ring]])], UTM); + let a = s.run("raster.rasterize", &json!({"layer": "Square", "cellSize": 10, "name": "Burned"})).unwrap(); + let g = grid_of(&s, "Burned"); + assert_eq!(g.crs, UTM); + assert_eq!((g.transform.origin_x, g.transform.origin_y), (2_000_000.0, 5_401_410.0), "{:?}", g.transform); + assert_eq!(a["cells"], 100, "{a}"); +} diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index b45412c83f..ff3fe7a57d 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -2050,9 +2050,12 @@ The Imagery tab's groups open their tools in the Workflows pane. The tab belongs is a new layer (`name`, by default the layer's name with "raster"), and with `path` a cloud-optimised GeoTIFF too. - **The grid** is given as for Project Raster: `"grid"`, another raster's grid taken exactly, or - `crs` (by default the layer's), `cellSize` (required), `origin` (`[0, 0]` by default, so the - result lines up with any raster projected with the same `crs` and `cellSize`) and `extent` (by - default the polygons' bounds). + `crs` (by default the system the layer holds its coordinates in, or else the one it was read + in), `cellSize` (required), `origin` (`[0, 0]` by default, so the result lines up with any + raster projected with the same `crs` and `cellSize`) and `extent` (by default the polygons' + bounds). The polygons are burned from their own coordinates: as they are on a grid in their + layer's system, else converted straight into the grid's, by the transformation between the + two datums where they differ. Raster clip and a spectral zone take a polygon the same way. - **What a cell takes:** a cell takes a polygon's value when its centre falls inside it, holes cut out. A numeric `field` gives its values; a text `field` gives codes 1 to n, in sorted order of its values. A table named after the result with "classes" (`code`, `value`), numbered if From 2ca7c56cfe09fcc1757bf85cf0a183bbcea9d5d3 Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Sun, 22 Nov 2026 13:26:25 +0100 Subject: [PATCH 02/14] Review: rasterize says vertices left out of its extent, errors name the layer, lon/lat layers keep the old extent, crs help names the held system --- crates/analysis/src/rasterops.rs | 27 ++++++++++-------- crates/engine/src/cmd/imagery.rs | 47 ++++++++++++++++++++------------ 2 files changed, 45 insertions(+), 29 deletions(-) diff --git a/crates/analysis/src/rasterops.rs b/crates/analysis/src/rasterops.rs index f0c7e4242c..927d76bfe7 100644 --- a/crates/analysis/src/rasterops.rs +++ b/crates/analysis/src/rasterops.rs @@ -1037,7 +1037,7 @@ pub fn zonal_means_in(r: &Raster, from: Crs, bands: &[usize], rings: &[Vec, to_grid: Box }, } impl ZoneIn { @@ -1045,7 +1045,10 @@ impl ZoneIn { Ok(if from == Crs::LonLat { Self::LonLat } else { - Self::Own { to_zone: crate::tools::ToGrid::new(r.crs, from)?, to_grid: crate::tools::ToGrid::new(from, r.crs)? } + Self::Own { + to_zone: Box::new(crate::tools::ToGrid::new(r.crs, from)?), + to_grid: Box::new(crate::tools::ToGrid::new(from, r.crs)?), + } }) } @@ -1086,8 +1089,9 @@ pub fn polygon_mask_in( /// once, all of them): an error stops it. /// /// A cell counts when its centre, in the zone's system (`zone`), lies in the zone (inside the -/// outer ring and in no hole). Only the cells in the zone's window are tested ([`zone_window`]), not every -/// cell of the raster, in the same row-major order, so the sums are those of testing them all. +/// outer ring and in no hole). Only the cells in the zone's window are tested ([`zone_window`]), +/// not every cell of the raster, in the same row-major order, so the sums are those of testing +/// them all. fn means_under( r: &Raster, zone: &ZoneIn, @@ -1123,14 +1127,13 @@ fn means_under( /// The columns and rows of `r` whose cell centres can fall in the extent `e`, in the zone's system /// (`to_grid` places it in the raster's): its outline placed on the raster's grid, with two cells -/// to spare. Each side is sampled, and -/// each stretch between samples near the raster is halved until its ends are at most a cell -/// apart, so a side that curves on the grid (a parallel on a polar raster) bows only a fraction -/// of a cell between them, whatever the zone's size. A stretch whose ends are farther from the -/// raster than the distance between them isn't halved: that takes the side not to fold back -/// within one stretch (a sixty-fourth of the side at first), which a projection's smooth image of -/// a parallel or meridian doesn't. The whole raster when a point can't be placed; none when `e` is -/// empty. +/// to spare. Each side is sampled, and each stretch between samples near the raster is halved until +/// its ends are at most a cell apart, so a side that curves on the grid (a parallel on a polar +/// raster) bows only a fraction of a cell between them, whatever the zone's size. A stretch whose +/// ends are farther from the raster than the distance between them isn't halved: that takes the +/// side not to fold back within one stretch (a sixty-fourth of the side at first), which a +/// projection's smooth image of a parallel or meridian doesn't. The whole raster when a point can't +/// be placed; none when `e` is empty. fn zone_window(r: &Raster, e: &Extent, to_grid: impl Fn(Coord) -> Option) -> (Range, Range) { if e.is_empty() { return (0..0, 0..0); diff --git a/crates/engine/src/cmd/imagery.rs b/crates/engine/src/cmd/imagery.rs index 3c340bdb54..6ddf0c67d6 100644 --- a/crates/engine/src/cmd/imagery.rs +++ b/crates/engine/src/cmd/imagery.rs @@ -53,7 +53,7 @@ pub fn commands() -> Vec { r#"{"layer": raster, "crs"?: EPSG code or "EPSG:n" of the output (default the layer's), "cellSize"?: number or [x, y] in the output's units (default about the layer's pixel there), "origin"?: [x, y] a cell corner falls on (default [0, 0], so grids of the same cellSize line up), "extent"?: polygon layer (its selected or all features' bounds) | [west, south, east, north] in degrees | "view" (default the layer's footprint), "grid"?: raster layer whose coordinate system, cells and extent are taken exactly (instead of crs, cellSize, origin and extent), "resampling"?: "nearest" (default) | "bilinear" | "cubic" | "average" (the mean of the pixels whose centres fall in a cell) | "mode" (their most frequent value, the least of those tied), "name"?: new layer (default " projected"), "path"?: GeoTIFF to write it to}"#, ), C::new("raster.rasterize", "Polygons to Raster", "Analyze › Raster", rasterize).inputs(rasterize_inputs).roles(&[]).effects(crate::policy::Effects::NONE).params( - r#"{"layer": polygon layer (its selected or all features; a later one over an earlier), "field"?: numeric field (its values) or text field (codes 1 to n in sorted order of its values, listed in a table named after the result with classes), "value"?: number every polygon gives when there is no field (default 1), "nodata"?: number of the cells under no polygon (default 0), "crs"?: EPSG code or "EPSG:n" of the output (default the layer's), "cellSize"?: number or [x, y] in the output's units (required without grid), "origin"?: [x, y] a cell corner falls on (default [0, 0], so grids of the same cellSize line up), "extent"?: polygon layer (its selected or all features' bounds) | [west, south, east, north] in degrees | "view"; default the polygons' bounds, "grid"?: raster layer whose coordinate system, cells and extent are taken exactly (instead of crs, cellSize, origin and extent), "name"?: new layer (default " raster"), "path"?: GeoTIFF to write it to}"#, + r#"{"layer": polygon layer (its selected or all features; a later one over an earlier), "field"?: numeric field (its values) or text field (codes 1 to n in sorted order of its values, listed in a table named after the result with classes), "value"?: number every polygon gives when there is no field (default 1), "nodata"?: number of the cells under no polygon (default 0), "crs"?: EPSG code or "EPSG:n" of the output (default the system the layer holds its coordinates in), "cellSize"?: number or [x, y] in the output's units (required without grid), "origin"?: [x, y] a cell corner falls on (default [0, 0], so grids of the same cellSize line up), "extent"?: polygon layer (its selected or all features' bounds) | [west, south, east, north] in degrees | "view"; default the polygons' bounds, "grid"?: raster layer whose coordinate system, cells and extent are taken exactly (instead of crs, cellSize, origin and extent), "name"?: new layer (default " raster"), "path"?: GeoTIFF to write it to}"#, ), // A fit is a measurement of the points, not a project change: no undo step. C::new("raster.gcpFit", "Control Point Fit", "Imagery › Alignment", gcp_fit).roles(&[]).effects(crate::policy::Effects::NONE).view().params( @@ -562,24 +562,35 @@ fn rasterize(s: &mut Session, p: &Value) -> CmdResult { } // By default, the system the layer holds its coordinates in (else the one it was read in) and // the polygons' bounds. - let own = shapes.iter().flat_map(|s| s.parts.iter().flatten().flatten()).fold(Extent::EMPTY, |mut e, c| { + let held_bounds = shapes.iter().flat_map(|s| s.parts.iter().flatten().flatten()).fold(Extent::EMPTY, |mut e, c| { e.expand(*c); e }); let crs = if held == Crs::LonLat { ds.crs.unwrap_or(Crs::LonLat) } else { held }; + let mut unsized_by = 0usize; let grid = grid_param(s, p, crs, |crs| { - if crs == held { - return Ok(([own.min_x, own.min_y, own.max_x, own.max_y], None)); + if crs == held && held != Crs::LonLat { + return Ok(([held_bounds.min_x, held_bounds.min_y, held_bounds.max_x, held_bounds.max_y], None)); } - // In another system, the bounds of the polygons' box in longitude/latitude, as before. - let to = held.to(Crs::LonLat)?; - let lonlat = - shapes.iter().flat_map(|s| s.parts.iter().flatten().flatten()).filter_map(|c| to.point(*c)).fold(Extent::EMPTY, |mut e, c| { - e.expand(c); - e - }); - Ok((warp::bounds_in([lonlat.min_x, lonlat.min_y, lonlat.max_x, lonlat.max_y], crs)?, None)) + // Otherwise the bounds of the polygons' box in longitude/latitude, as before. A place the + // layer's system can't give there (a missing one aside) doesn't size the grid, and is + // said when the grid takes these bounds (no extent given). + let to = held.to(Crs::LonLat).map_err(|e| format!("{ln}: {e}"))?; + let mut lonlat = Extent::EMPTY; + for c in shapes.iter().flat_map(|s| s.parts.iter().flatten().flatten()).filter(|c| c.is_finite()) { + match to.point(*c) { + Some(c) => lonlat.expand(c), + None => unsized_by += 1, + } + } + Ok((warp::bounds_in([lonlat.min_x, lonlat.min_y, lonlat.max_x, lonlat.max_y], crs).map_err(|e| format!("{ln}: {e}"))?, None)) })?; + if unsized_by > 0 && p.get("extent").is_none_or(Value::is_null) { + s.notify( + format!("{ln}: {unsized_by} vertices that can't be placed in longitude/latitude were left out of the grid's extent: give an extent to take them in"), + false, + ); + } // The smallest pixel type the GeoTIFF writer keeps that holds every value and the no-data. let whole = |max: f64| shapes.iter().map(|s| f64::from(s.value)).chain([nodata]).all(|v| v.fract() == 0.0 && (0.0..=max).contains(&v)); let data_type = if whole(255.0) { @@ -589,7 +600,7 @@ fn rasterize(s: &mut Session, p: &Value) -> CmdResult { } else { "Float32" }; - let burned = warp::rasterize_in(&grid, held, &shapes, nodata as f32)?; + let burned = warp::rasterize_in(&grid, held, &shapes, nodata as f32).map_err(|e| format!("{ln}: {e}"))?; if burned.cells == 0 { return Err(format!("no cell centre of the grid falls inside {ln}'s polygons: give a smaller cellSize, or a grid over them")); } @@ -1037,7 +1048,7 @@ fn spectral_read(s: &mut Session, p: &Value, r: &Arc, zone: Option<&str> let (crs, rings) = zone_rings(s, z)?; // Read on a thread of its own as the app sent the command, when still of this raster and // this polygon; here otherwise. - let (means, n) = zone_means(s, r, crs, rings)?.ok_or("no pixels fall in the zone")?; + let (means, n) = zone_means(s, r, crs, rings).map_err(|e| format!("{z}: {e}"))?.ok_or("no pixels fall in the zone")?; return answer(json!({"bands": names, "values": means, "pixels": n})); } let c = Coord::new(f(p, "lon").ok_or("give lon and lat, points or a zone")?, f(p, "lat").ok_or("lat is required")?); @@ -1284,9 +1295,11 @@ pub(crate) fn process_work(s: &Session, p: &Value) -> Result 0 { From 0b41ab09d31404048698d825e424fee41766122e Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Sun, 22 Nov 2026 14:16:28 +0100 Subject: [PATCH 03/14] Review: a spectral zone's window clamps at Web Mercator's limit as its vertices do; rasterize's extent notice tested both ways --- crates/analysis/src/rasterops.rs | 9 +++++++-- crates/engine/src/tests/held_layers.rs | 28 ++++++++++++++++++++++++++ 2 files changed, 35 insertions(+), 2 deletions(-) diff --git a/crates/analysis/src/rasterops.rs b/crates/analysis/src/rasterops.rs index 927d76bfe7..c044515549 100644 --- a/crates/analysis/src/rasterops.rs +++ b/crates/analysis/src/rasterops.rs @@ -1034,7 +1034,12 @@ pub fn zonal_means_in(r: &Raster, from: Crs, bands: &[usize], rings: &[Vec, to_grid: Box }, @@ -1064,7 +1069,7 @@ impl ZoneIn { fn grid(&self, r: &Raster, c: Coord) -> Option { match self { Self::LonLat => r.transformer().from_lonlat(c), - Self::Own { to_grid, .. } => to_grid.place(c), + Self::Own { to_grid, .. } => to_grid.vertex(c), } } } diff --git a/crates/engine/src/tests/held_layers.rs b/crates/engine/src/tests/held_layers.rs index 19aa0f6955..dc2340765d 100644 --- a/crates/engine/src/tests/held_layers.rs +++ b/crates/engine/src/tests/held_layers.rs @@ -2304,3 +2304,31 @@ fn a_held_layer_is_burned_in_its_own_system() { assert_eq!((g.transform.origin_x, g.transform.origin_y), (2_000_000.0, 5_401_410.0), "{:?}", g.transform); assert_eq!(a["cells"], 100, "{a}"); } + +/// Rasterize sizes its default grid in another system by the polygons' box in longitude/latitude, +/// and says how many vertices it couldn't place there, left out of that box: a polygon held in UTM +/// with a vertex far beyond any place UTM holds, burned onto a grid in degrees. With an extent +/// given, the box isn't used, and nothing is said of it. +#[test] +fn rasterize_says_the_vertices_left_out_of_its_extent() { + let (x0, y0) = (784_000.0, 5_401_300.0); + let square: Vec = + [(0.0, 0.0), (1000.0, 0.0), (1000.0, 1000.0), (0.0, 1000.0), (0.0, 0.0)].iter().map(|(x, y)| Coord::new(x0 + x, y0 + y)).collect(); + let far = vec![Coord::new(x0, y0), Coord::new(1e12, 1e12), Coord::new(x0, y0 + 500.0), Coord::new(x0, y0)]; + let mut s = Session::new(Project::default()); + add_in(&mut s, "Plots", GeometryType::Polygon, vec![Geometry::Polygon(vec![vec![square]]), Geometry::Polygon(vec![vec![far]])], UTM); + let left_out = "vertices that can't be placed in longitude/latitude were left out of the grid's extent"; + let said = |s: &Session, mark| s.notices_since(mark).iter().map(|n| n.text.clone()).collect::>(); + let mark = s.notice_mark(); + s.run("raster.rasterize", &json!({"layer": "Plots", "crs": "EPSG:4326", "cellSize": 0.001, "name": "A"})).unwrap(); + let a = said(&s, mark); + assert!(a.iter().any(|t| t.contains(&format!("Plots: 1 {left_out}"))), "{a:?}"); + let mark = s.notice_mark(); + s.run( + "raster.rasterize", + &json!({"layer": "Plots", "crs": "EPSG:4326", "cellSize": 0.001, "extent": [12.8, 48.6, 12.9, 48.8], "name": "B"}), + ) + .unwrap(); + let b = said(&s, mark); + assert!(!b.iter().any(|t| t.contains(left_out)), "{b:?}"); +} From ecb1e5b53829c57b826e9bf0990ce57c0f69843d Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Sun, 22 Nov 2026 14:33:46 +0100 Subject: [PATCH 04/14] Review: rasterize's extent loop looks at Cancel; points their own system can't give are said apart (tested); crs help and raster_crs doc name both defaults --- crates/analysis/src/tools.rs | 78 ++++++++++++++++++++------ crates/engine/src/cmd/imagery.rs | 8 ++- crates/engine/src/tests/held_layers.rs | 21 +++++++ 3 files changed, 89 insertions(+), 18 deletions(-) diff --git a/crates/analysis/src/tools.rs b/crates/analysis/src/tools.rs index 243ce94523..397dc1ccd2 100644 --- a/crates/analysis/src/tools.rs +++ b/crates/analysis/src/tools.rs @@ -5047,9 +5047,10 @@ pub fn layer_raster_crs(crs: Option) -> Option> { /// The coordinate system an interpolation (`tool`) makes its grid in: the projected system given as /// `p`'s `crs`; degrees for `EPSG:4326`; else [`layer_raster_crs`], the projected system `ds` was -/// read in, as Kernel Density uses, and degrees for a layer read in degrees. The note says what the -/// run used where that could surprise: the system it took from the layer, or the compatibility note -/// on the one given. +/// read in, and degrees for a layer read in degrees. The Geostatistical Wizard and a run in +/// longitude/latitude take it so; the interpolations and Kernel Density, in a run in a layer's own +/// projected system, take that one ([`raster_crs_in`]). The note says what the 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, "was read in", &ds.name, p, tool) } @@ -5127,7 +5128,7 @@ fn points_from(from: Crs, crs: Crs, pts: Vec<(Coord, f64)>) -> Result<(Vec<(Coor return Ok((pts, None)); } let to = ToGrid::new(from, crs)?; - let n = pts.len(); + let (mut beyond, mut unplaced) = (0usize, 0usize); // (In the points' own storage, as a filtered collect of the same kind reuses it.) let kept: Vec<(Coord, f64)> = pts .into_iter() @@ -5138,11 +5139,31 @@ fn points_from(from: Crs, crs: Crs, pts: Vec<(Coord, f64)>) -> Result<(Vec<(Coor { return Some(Err(cancelled)); } - to.place(c).map(|c| Ok((c, v))) + match to.try_place(c) { + Ok(c) => Some(Ok((c, v))), + Err(Miss::Source) => { + unplaced += 1; + None + } + Err(Miss::Grid) => { + beyond += 1; + None + } + } }) .collect::>()?; - let beyond = n - kept.len(); - Ok((kept, beyond_note(crs, beyond))) + Ok((kept, left_out_note(from, crs, unplaced, beyond))) +} + +/// The note on the points left out: `unplaced` that their own system `from` can't give in +/// longitude/latitude, and `beyond` that the grid's `crs` can't hold ([`beyond_note`]). +fn left_out_note(from: Crs, crs: Crs, unplaced: usize, beyond: usize) -> Option { + let unplaced = + (unplaced > 0).then(|| format!("{unplaced} point(s) that {} can't give in longitude/latitude were left out", from.label())); + match (unplaced, beyond_note(crs, beyond)) { + (Some(a), Some(b)) => Some(format!("{a}; {b}")), + (a, b) => a.or(b), + } } /// The note on `beyond` points left out because `crs` can't hold them (see [`in_projected`]). @@ -5175,6 +5196,14 @@ fn in_projected(crs: Crs, to: &Transformer, c: Coord) -> Option { /// near that ([`Reprojection::point_near`]), so a datum pair takes its best operation. /// /// [`Reprojection::point_near`]: rustgis_data::raster::Reprojection::point_near +/// Which system a place failed in ([`ToGrid::try_place`]). +pub(crate) enum Miss { + /// The run's own: it can't give the place in longitude/latitude. + Source, + /// The grid's: it can't hold the place. + Grid, +} + pub(crate) struct ToGrid { crs: Crs, same: bool, @@ -5193,15 +5222,24 @@ impl ToGrid { } pub(crate) fn place(&self, c: Coord) -> Option { + self.try_place(c).ok() + } + + /// [`ToGrid::place`], with whose system failed: the run's, which can't give the place in + /// longitude/latitude (or a place that isn't finite), or the grid's, which can't hold it. + pub(crate) fn try_place(&self, c: Coord) -> Result { + if !c.is_finite() { + return Err(Miss::Source); + } if self.same { - return c.is_finite().then_some(c); + return Ok(c); } let lonlat = match &self.from { - Some(t) => t.to_lonlat(c)?, + Some(t) => t.to_lonlat(c).ok_or(Miss::Source)?, 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))) + let via = in_projected(self.crs, &self.to, lonlat).ok_or(Miss::Grid)?; + Ok(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 @@ -5363,10 +5401,18 @@ fn kernel_density_tool(inp: &dyn Inputs, p: &Json) -> Result // A multipoint's members with non-finite coordinates, in the features with finite ones (a // 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 = to_grid.place(c); - *beyond += usize::from(p.is_none()); - p + // And a point the layer's own system can't give in longitude/latitude, counted apart. + let mut unplaced = 0usize; + let mut project = |c: Coord, beyond: &mut usize| match to_grid.try_place(c) { + Ok(p) => Some(p), + Err(Miss::Source) => { + unplaced += 1; + None + } + Err(Miss::Grid) => { + *beyond += 1; + None + } }; for r in rows(inp, p, "input", ds) { let Some(g) = ds.features.get(r).and_then(|f| f.geometry.as_ref()) else { @@ -5417,7 +5463,7 @@ fn kernel_density_tool(inp: &dyn Inputs, p: &Json) -> Result } } - let beyond_note = beyond_note(crs, beyond); + let beyond_note = left_out_note(inp.work_crs(), crs, unplaced, beyond); let non_finite_note = (non_finite > 0).then(|| { format!("{non_finite} point(s) with non-finite coordinates were left out of {non_finite_features} multipoint feature(s) that have other points") }); diff --git a/crates/engine/src/cmd/imagery.rs b/crates/engine/src/cmd/imagery.rs index 6ddf0c67d6..b8a52627bd 100644 --- a/crates/engine/src/cmd/imagery.rs +++ b/crates/engine/src/cmd/imagery.rs @@ -53,7 +53,7 @@ pub fn commands() -> Vec { r#"{"layer": raster, "crs"?: EPSG code or "EPSG:n" of the output (default the layer's), "cellSize"?: number or [x, y] in the output's units (default about the layer's pixel there), "origin"?: [x, y] a cell corner falls on (default [0, 0], so grids of the same cellSize line up), "extent"?: polygon layer (its selected or all features' bounds) | [west, south, east, north] in degrees | "view" (default the layer's footprint), "grid"?: raster layer whose coordinate system, cells and extent are taken exactly (instead of crs, cellSize, origin and extent), "resampling"?: "nearest" (default) | "bilinear" | "cubic" | "average" (the mean of the pixels whose centres fall in a cell) | "mode" (their most frequent value, the least of those tied), "name"?: new layer (default " projected"), "path"?: GeoTIFF to write it to}"#, ), C::new("raster.rasterize", "Polygons to Raster", "Analyze › Raster", rasterize).inputs(rasterize_inputs).roles(&[]).effects(crate::policy::Effects::NONE).params( - r#"{"layer": polygon layer (its selected or all features; a later one over an earlier), "field"?: numeric field (its values) or text field (codes 1 to n in sorted order of its values, listed in a table named after the result with classes), "value"?: number every polygon gives when there is no field (default 1), "nodata"?: number of the cells under no polygon (default 0), "crs"?: EPSG code or "EPSG:n" of the output (default the system the layer holds its coordinates in), "cellSize"?: number or [x, y] in the output's units (required without grid), "origin"?: [x, y] a cell corner falls on (default [0, 0], so grids of the same cellSize line up), "extent"?: polygon layer (its selected or all features' bounds) | [west, south, east, north] in degrees | "view"; default the polygons' bounds, "grid"?: raster layer whose coordinate system, cells and extent are taken exactly (instead of crs, cellSize, origin and extent), "name"?: new layer (default " raster"), "path"?: GeoTIFF to write it to}"#, + r#"{"layer": polygon layer (its selected or all features; a later one over an earlier), "field"?: numeric field (its values) or text field (codes 1 to n in sorted order of its values, listed in a table named after the result with classes), "value"?: number every polygon gives when there is no field (default 1), "nodata"?: number of the cells under no polygon (default 0), "crs"?: EPSG code or "EPSG:n" of the output (default the system the layer holds its coordinates in, or else the one it was read in), "cellSize"?: number or [x, y] in the output's units (required without grid), "origin"?: [x, y] a cell corner falls on (default [0, 0], so grids of the same cellSize line up), "extent"?: polygon layer (its selected or all features' bounds) | [west, south, east, north] in degrees | "view"; default the polygons' bounds, "grid"?: raster layer whose coordinate system, cells and extent are taken exactly (instead of crs, cellSize, origin and extent), "name"?: new layer (default " raster"), "path"?: GeoTIFF to write it to}"#, ), // A fit is a measurement of the points, not a project change: no undo step. C::new("raster.gcpFit", "Control Point Fit", "Imagery › Alignment", gcp_fit).roles(&[]).effects(crate::policy::Effects::NONE).view().params( @@ -577,7 +577,11 @@ fn rasterize(s: &mut Session, p: &Value) -> CmdResult { // said when the grid takes these bounds (no extent given). let to = held.to(Crs::LonLat).map_err(|e| format!("{ln}: {e}"))?; let mut lonlat = Extent::EMPTY; - for c in shapes.iter().flat_map(|s| s.parts.iter().flatten().flatten()).filter(|c| c.is_finite()) { + // A conversion a vertex: Cancel is looked at every few thousand. + for (i, c) in shapes.iter().flat_map(|s| s.parts.iter().flatten().flatten()).filter(|c| c.is_finite()).enumerate() { + if i % 4096 == 0 { + rustgis_data::progress::check().map_err(|e| e.to_string())?; + } match to.point(*c) { Some(c) => lonlat.expand(c), None => unsized_by += 1, diff --git a/crates/engine/src/tests/held_layers.rs b/crates/engine/src/tests/held_layers.rs index dc2340765d..f209f3f401 100644 --- a/crates/engine/src/tests/held_layers.rs +++ b/crates/engine/src/tests/held_layers.rs @@ -2332,3 +2332,24 @@ fn rasterize_says_the_vertices_left_out_of_its_extent() { let b = said(&s, mark); assert!(!b.iter().any(|t| t.contains(left_out)), "{b:?}"); } + +/// A point the layer's own system can't give in longitude/latitude is counted apart from one the +/// grid's system can't hold: IDW from points held in UTM, one far beyond any place UTM holds, +/// says that UTM can't give it, not that the grid can't hold it. +#[test] +fn a_point_its_own_system_cant_give_is_said_as_such() { + let mut s = Session::new(Project::default()); + let at = [Coord::new(784_000.0, 5_401_300.0), Coord::new(785_000.0, 5_402_300.0), Coord::new(1e12, 1e12)]; + add_in(&mut s, "Samples", GeometryType::Point, at.iter().map(|c| Geometry::Point(*c)).collect(), UTM); + let mark = s.notice_mark(); + let answer = s + .run( + "gp.run", + &json!({"tool": "idwInterpolation", "params": {"input": "Samples", "field": "v", "pixelSize": 100, "crs": "EPSG:3857", "output": "Idw"}}), + ) + .unwrap(); + let said: Vec = s.notices_since(mark).iter().map(|n| n.text.clone()).chain([answer.to_string()]).collect(); + let own = format!("1 point(s) that {} can't give in longitude/latitude were left out", UTM.label()); + assert!(said.iter().any(|t| t.contains(&own)), "{said:?}"); + assert!(!said.iter().any(|t| t.contains("beyond what")), "{said:?}"); +} From da074aaf0d74d0dadf1eafbd4ed75a24f0cbba1f Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Sun, 22 Nov 2026 14:40:04 +0100 Subject: [PATCH 05/14] Review: ToGrid keeps its doc; rasterize's crs help says projected; try_place doc --- crates/analysis/src/tools.rs | 19 ++++++++++--------- crates/engine/src/cmd/imagery.rs | 2 +- docs/user-guide/analysis.md | 4 ++-- 3 files changed, 13 insertions(+), 12 deletions(-) diff --git a/crates/analysis/src/tools.rs b/crates/analysis/src/tools.rs index 397dc1ccd2..efdf65e4e1 100644 --- a/crates/analysis/src/tools.rs +++ b/crates/analysis/src/tools.rs @@ -5189,13 +5189,6 @@ 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 /// Which system a place failed in ([`ToGrid::try_place`]). pub(crate) enum Miss { /// The run's own: it can't give the place in longitude/latitude. @@ -5204,6 +5197,13 @@ pub(crate) enum Miss { Grid, } +/// 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, @@ -5225,8 +5225,9 @@ impl ToGrid { self.try_place(c).ok() } - /// [`ToGrid::place`], with whose system failed: the run's, which can't give the place in - /// longitude/latitude (or a place that isn't finite), or the grid's, which can't hold it. + /// [`ToGrid::place`], saying which system failed: the run's, which can't give the place in + /// longitude/latitude (a place that isn't finite counts as such, in any run), or the grid's, + /// which can't hold it. pub(crate) fn try_place(&self, c: Coord) -> Result { if !c.is_finite() { return Err(Miss::Source); diff --git a/crates/engine/src/cmd/imagery.rs b/crates/engine/src/cmd/imagery.rs index b8a52627bd..639026e734 100644 --- a/crates/engine/src/cmd/imagery.rs +++ b/crates/engine/src/cmd/imagery.rs @@ -53,7 +53,7 @@ pub fn commands() -> Vec { r#"{"layer": raster, "crs"?: EPSG code or "EPSG:n" of the output (default the layer's), "cellSize"?: number or [x, y] in the output's units (default about the layer's pixel there), "origin"?: [x, y] a cell corner falls on (default [0, 0], so grids of the same cellSize line up), "extent"?: polygon layer (its selected or all features' bounds) | [west, south, east, north] in degrees | "view" (default the layer's footprint), "grid"?: raster layer whose coordinate system, cells and extent are taken exactly (instead of crs, cellSize, origin and extent), "resampling"?: "nearest" (default) | "bilinear" | "cubic" | "average" (the mean of the pixels whose centres fall in a cell) | "mode" (their most frequent value, the least of those tied), "name"?: new layer (default " projected"), "path"?: GeoTIFF to write it to}"#, ), C::new("raster.rasterize", "Polygons to Raster", "Analyze › Raster", rasterize).inputs(rasterize_inputs).roles(&[]).effects(crate::policy::Effects::NONE).params( - r#"{"layer": polygon layer (its selected or all features; a later one over an earlier), "field"?: numeric field (its values) or text field (codes 1 to n in sorted order of its values, listed in a table named after the result with classes), "value"?: number every polygon gives when there is no field (default 1), "nodata"?: number of the cells under no polygon (default 0), "crs"?: EPSG code or "EPSG:n" of the output (default the system the layer holds its coordinates in, or else the one it was read in), "cellSize"?: number or [x, y] in the output's units (required without grid), "origin"?: [x, y] a cell corner falls on (default [0, 0], so grids of the same cellSize line up), "extent"?: polygon layer (its selected or all features' bounds) | [west, south, east, north] in degrees | "view"; default the polygons' bounds, "grid"?: raster layer whose coordinate system, cells and extent are taken exactly (instead of crs, cellSize, origin and extent), "name"?: new layer (default " raster"), "path"?: GeoTIFF to write it to}"#, + r#"{"layer": polygon layer (its selected or all features; a later one over an earlier), "field"?: numeric field (its values) or text field (codes 1 to n in sorted order of its values, listed in a table named after the result with classes), "value"?: number every polygon gives when there is no field (default 1), "nodata"?: number of the cells under no polygon (default 0), "crs"?: EPSG code or "EPSG:n" of the output (default the projected system the layer holds its coordinates in, else the one it was read in; degrees for a layer in degrees with neither), "cellSize"?: number or [x, y] in the output's units (required without grid), "origin"?: [x, y] a cell corner falls on (default [0, 0], so grids of the same cellSize line up), "extent"?: polygon layer (its selected or all features' bounds) | [west, south, east, north] in degrees | "view"; default the polygons' bounds, "grid"?: raster layer whose coordinate system, cells and extent are taken exactly (instead of crs, cellSize, origin and extent), "name"?: new layer (default " raster"), "path"?: GeoTIFF to write it to}"#, ), // A fit is a measurement of the points, not a project change: no undo step. C::new("raster.gcpFit", "Control Point Fit", "Imagery › Alignment", gcp_fit).roles(&[]).effects(crate::policy::Effects::NONE).view().params( diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index ff3fe7a57d..2526de3a10 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -2050,8 +2050,8 @@ The Imagery tab's groups open their tools in the Workflows pane. The tab belongs is a new layer (`name`, by default the layer's name with "raster"), and with `path` a cloud-optimised GeoTIFF too. - **The grid** is given as for Project Raster: `"grid"`, another raster's grid taken exactly, or - `crs` (by default the system the layer holds its coordinates in, or else the one it was read - in), `cellSize` (required), `origin` (`[0, 0]` by default, so the result lines up with any + `crs` (by default the projected system the layer holds its coordinates in, else the one it was + read in), `cellSize` (required), `origin` (`[0, 0]` by default, so the result lines up with any raster projected with the same `crs` and `cellSize`) and `extent` (by default the polygons' bounds). The polygons are burned from their own coordinates: as they are on a grid in their layer's system, else converted straight into the grid's, by the transformation between the From f5f063259cd0838913a7d7b0d204097f67d0809a Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Sun, 22 Nov 2026 16:09:50 +0100 Subject: [PATCH 06/14] Review: a polar zone's window takes in the inside beyond its outline; rasterize's default grid takes in the vertices as burned; rasterize says it runs on the calling thread --- crates/analysis/src/rasterops.rs | 62 +++++++++++++++++++++++--- crates/analysis/src/warp.rs | 18 ++++++++ crates/engine/src/cmd/imagery.rs | 21 ++++++++- crates/engine/src/tests/held_layers.rs | 15 +++++++ 4 files changed, 108 insertions(+), 8 deletions(-) diff --git a/crates/analysis/src/rasterops.rs b/crates/analysis/src/rasterops.rs index c044515549..32941ab2bc 100644 --- a/crates/analysis/src/rasterops.rs +++ b/crates/analysis/src/rasterops.rs @@ -1110,7 +1110,7 @@ fn means_under( } let mut sums = vec![0.0; bands.len()]; let mut n = 0usize; - let (cols, rows) = zone_window(r, &e, |c| zone.grid(r, c)); + let (cols, rows) = zone_window(r, &e, matches!(zone, ZoneIn::Own { .. }), |c| zone.grid(r, c)); each_rows((r.height - (rows.end - rows.start)) as usize)?; for row in rows { each_rows(1)?; @@ -1139,7 +1139,12 @@ fn means_under( /// side not to fold back within one stretch (a sixty-fourth of the side at first), which a /// projection's smooth image of a parallel or meridian doesn't. The whole raster when a point can't /// be placed; none when `e` is empty. -fn zone_window(r: &Raster, e: &Extent, to_grid: impl Fn(Coord) -> Option) -> (Range, Range) { +/// +/// With `interior` (a zone in a system of its own), places inside `e` are placed too, a sixteenth +/// of it apart: when one can't be, or lands outside the outline's window, the zone's box holds a +/// place the raster's grid can't take in one piece (a polar zone on a Web Mercator raster, whose +/// outline lands south of the cells near the pole), and the whole raster is read. +fn zone_window(r: &Raster, e: &Extent, interior: bool, to_grid: impl Fn(Coord) -> Option) -> (Range, Range) { if e.is_empty() { return (0..0, 0..0); } @@ -1186,11 +1191,23 @@ fn zone_window(r: &Raster, e: &Extent, to_grid: impl Fn(Coord) -> Option) stretches.push((tm, pm, t1, p1, depth + 1)); } } + let (c0, r0, c1, r1) = (c0.floor() - 2.0, r0.floor() - 2.0, c1.ceil() + 2.0, r1.ceil() + 2.0); + if interior { + const INSIDE: u32 = 16; + for i in 1..INSIDE { + for j in 1..INSIDE { + let (u, v) = (f64::from(i) / f64::from(INSIDE), f64::from(j) / f64::from(INSIDE)); + let Some((col, row)) = place(Coord::new(e.min_x + u * (e.max_x - e.min_x), e.min_y + v * (e.max_y - e.min_y))) else { + return whole; + }; + if !(c0..=c1).contains(&col) || !(r0..=r1).contains(&row) { + return whole; + } + } + } + } let clamp = |v: f64, n: u32| v.clamp(0.0, f64::from(n)) as u32; - ( - (clamp(c0.floor() - 2.0, r.width)..clamp(c1.ceil() + 2.0, r.width)), - (clamp(r0.floor() - 2.0, r.height)..clamp(r1.ceil() + 2.0, r.height)), - ) + ((clamp(c0, r.width)..clamp(c1, r.width)), (clamp(r0, r.height)..clamp(r1, r.height))) } /// Each class's mean of `bands` over the pixels under its training polygons (lon/lat rings, each @@ -3142,4 +3159,37 @@ mod tests { assert!(parse_bands_str(",", total).is_err(), "standalone comma is invalid"); assert!(parse_bands_str(";", total).is_err(), "standalone semicolon is invalid"); } + + /// A polar zone held in its own system on a Web Mercator raster near the pole: the zone's + /// outline lands south of the raster, its inside on it. Every cell whose centre is in the zone + /// counts, as a scan of them all finds. + #[test] + fn a_polar_zone_counts_the_cells_inside_it_beyond_its_outline() { + let merc = Crs::WebMercator.transformer().unwrap_or_else(|e| panic!("{e}")); + let (Some(sw), Some(ne)) = (merc.from_lonlat(Coord::new(-10.0, 84.0)), merc.from_lonlat(Coord::new(10.0, 85.0))) else { + panic!("the corners are in Web Mercator") + }; + let cell = 5_000.0; + let (w, h) = (((ne.x - sw.x) / cell).ceil() as u32, ((ne.y - sw.y) / cell).ceil() as u32); + let gt = GeoTransform { origin_x: sw.x, origin_y: ne.y, pixel_width: cell, pixel_height: -cell }; + let r = Raster::new("polar", w, h, vec![vec![1.0; (w * h) as usize]], gt, Crs::WebMercator, None, ColorHint::Gray, "Float32") + .unwrap_or_else(|e| panic!("{e}")); + // NSIDC Sea Ice Polar Stereographic North: a square of 1,000 km each way about the pole, + // its sides near 77°N to 81°N. + let polar = Crs::Epsg(3413); + let d = 1_000_000.0; + let ring = vec![Coord::new(-d, -d), Coord::new(d, -d), Coord::new(d, d), Coord::new(-d, d), Coord::new(-d, -d)]; + let to_polar = polar.transformer().unwrap_or_else(|e| panic!("{e}")); + let mut inside = 0; + for row in 0..h { + for col in 0..w { + let c = r.transform.to_world(f64::from(col) + 0.5, f64::from(row) + 0.5); + let p = merc.to_lonlat(c).and_then(|ll| to_polar.from_lonlat(ll)).unwrap_or_else(|| panic!("{c:?} is in EPSG:3413")); + inside += usize::from(p.x.abs() < d && p.y.abs() < d); + } + } + assert!(inside > 1000, "{inside} cells are in the zone"); + let (means, n) = zonal_means_in(&r, polar, &[0], &[ring]).unwrap_or_else(|e| panic!("{e}")).unwrap_or_else(|| panic!("no cell")); + assert_eq!((means, n), (vec![1.0], inside)); + } } diff --git a/crates/analysis/src/warp.rs b/crates/analysis/src/warp.rs index 0bb691480f..7317c4afed 100644 --- a/crates/analysis/src/warp.rs +++ b/crates/analysis/src/warp.rs @@ -527,6 +527,24 @@ pub fn rasterize(g: &Grid, shapes: &[Shape], nodata: f32) -> Result Result, String> { + let to = crate::tools::ToGrid::new(from, crs)?; + let mut b = [f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY]; + for (i, c) in shapes.iter().flat_map(|s| s.parts.iter().flatten().flatten()).enumerate() { + if i % 4096 == 0 { + crate::control::check()?; + } + if let Some(p) = to.vertex(*c) { + b = [b[0].min(p.x), b[1].min(p.y), b[2].max(p.x), b[3].max(p.y)]; + } + } + Ok((b[0] <= b[2]).then_some(b)) +} + /// [`rasterize`] of shapes in `from`: longitude/latitude, or the system their layer holds its /// coordinates in, converted into the grid's (none of it when that is the grid's own), by the /// direct operation between two datums. diff --git a/crates/engine/src/cmd/imagery.rs b/crates/engine/src/cmd/imagery.rs index 639026e734..e81f29e43b 100644 --- a/crates/engine/src/cmd/imagery.rs +++ b/crates/engine/src/cmd/imagery.rs @@ -457,6 +457,14 @@ const EXACT_WHOLE: f64 = 16_777_216.0; /// `raster.project`'s is, each cell whose centre falls in a polygon taking its field's value, a /// text field's code or one `value` (see `rustgis_analysis::warp::rasterize`). A new layer, and /// for a text field a table of its codes. +/// +/// It runs on the thread that calls it, the app's own on the desktop, as it did before layers +/// held their own coordinates: it isn't yet one of the commands that make their raster on a thread +/// of their own (`workflows::IN_BACKGROUND`), since it writes its GeoTIFF to `path` and adds its +/// class table itself, which a move there has to carry over. Its loops look at Cancel (sizing the +/// grid, and between shapes in the burn), which stops a run only where a probe is installed (a +/// model or script run ahead on a copy of the session, `workflows::ahead_on_copy`); run by itself +/// in the app, nothing installs one, so there it runs to the end. fn rasterize(s: &mut Session, p: &Value) -> CmdResult { let ln = rasterize_name(p)?; let l = s.map().layer_by_name(ln).filter(|l| l.raster.is_none()).ok_or_else(|| format!("no vector layer '{ln}'"))?; @@ -577,7 +585,8 @@ fn rasterize(s: &mut Session, p: &Value) -> CmdResult { // said when the grid takes these bounds (no extent given). let to = held.to(Crs::LonLat).map_err(|e| format!("{ln}: {e}"))?; let mut lonlat = Extent::EMPTY; - // A conversion a vertex: Cancel is looked at every few thousand. + // A conversion a vertex: Cancel is looked at every few thousand (where a probe is + // installed, see above). for (i, c) in shapes.iter().flat_map(|s| s.parts.iter().flatten().flatten()).filter(|c| c.is_finite()).enumerate() { if i % 4096 == 0 { rustgis_data::progress::check().map_err(|e| e.to_string())?; @@ -587,7 +596,15 @@ fn rasterize(s: &mut Session, p: &Value) -> CmdResult { None => unsized_by += 1, } } - Ok((warp::bounds_in([lonlat.min_x, lonlat.min_y, lonlat.max_x, lonlat.max_y], crs).map_err(|e| format!("{ln}: {e}"))?, None)) + let mut b = warp::bounds_in([lonlat.min_x, lonlat.min_y, lonlat.max_x, lonlat.max_y], crs).map_err(|e| format!("{ln}: {e}"))?; + // Taking in the vertices as the burn places them: between two datums the direct operation + // lands apart from the route through WGS 84 (half a metre for DHDN and ETRS89). + if held != Crs::LonLat + && let Some(p) = warp::placed_bounds(held, crs, &shapes).map_err(|e| format!("{ln}: {e}"))? + { + b = [b[0].min(p[0]), b[1].min(p[1]), b[2].max(p[2]), b[3].max(p[3])]; + } + Ok((b, None)) })?; if unsized_by > 0 && p.get("extent").is_none_or(Value::is_null) { s.notify( diff --git a/crates/engine/src/tests/held_layers.rs b/crates/engine/src/tests/held_layers.rs index f209f3f401..58864536b8 100644 --- a/crates/engine/src/tests/held_layers.rs +++ b/crates/engine/src/tests/held_layers.rs @@ -2305,6 +2305,21 @@ fn a_held_layer_is_burned_in_its_own_system() { assert_eq!(a["cells"], 100, "{a}"); } +/// Rasterize's default grid in another system takes in the polygons as they are burned, by the +/// direct operation: a 5 cm square held in Gauss-Krüger zone 3 (DHDN), burned onto 1 cm cells in +/// ETRS89 / UTM 32N, lands 0.44 m from where the route through WGS 84 puts it, so a grid sized +/// by that route alone holds none of it. +#[test] +fn rasterize_sizes_its_grid_by_the_operation_that_burns() { + let (x0, y0) = (3_456_000.0, 5_430_000.0); + let ring: Vec = + [(0.0, 0.0), (0.05, 0.0), (0.05, 0.05), (0.0, 0.05), (0.0, 0.0)].iter().map(|(x, y)| Coord::new(x0 + x, y0 + y)).collect(); + let mut s = Session::new(Project::default()); + add_in(&mut s, "Tiny", GeometryType::Polygon, vec![Geometry::Polygon(vec![vec![ring]])], GK3); + let a = s.run("raster.rasterize", &json!({"layer": "Tiny", "crs": "EPSG:25832", "cellSize": 0.01, "name": "Burned"})).unwrap(); + assert!((16..=36).contains(&a["cells"].as_u64().unwrap()), "{a}"); +} + /// Rasterize sizes its default grid in another system by the polygons' box in longitude/latitude, /// and says how many vertices it couldn't place there, left out of that box: a polygon held in UTM /// with a vertex far beyond any place UTM holds, burned onto a grid in degrees. With an extent From 70be9e03b384f14051dbabf3f31cd36f9cf2c02c Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Sun, 22 Nov 2026 16:17:07 +0100 Subject: [PATCH 07/14] Review: rasterize's doc says Cancel doesn't reach it yet; polar zone tested off the pole too --- crates/analysis/src/rasterops.rs | 30 ++++++++++++++++-------------- crates/engine/src/cmd/imagery.rs | 18 ++++++++---------- 2 files changed, 24 insertions(+), 24 deletions(-) diff --git a/crates/analysis/src/rasterops.rs b/crates/analysis/src/rasterops.rs index 32941ab2bc..02b90f0508 100644 --- a/crates/analysis/src/rasterops.rs +++ b/crates/analysis/src/rasterops.rs @@ -1140,7 +1140,7 @@ fn means_under( /// projection's smooth image of a parallel or meridian doesn't. The whole raster when a point can't /// be placed; none when `e` is empty. /// -/// With `interior` (a zone in a system of its own), places inside `e` are placed too, a sixteenth +/// With `interior` (a zone held in a system other than longitude/latitude), places inside `e` are placed too, a sixteenth /// of it apart: when one can't be, or lands outside the outline's window, the zone's box holds a /// place the raster's grid can't take in one piece (a polar zone on a Web Mercator raster, whose /// outline lands south of the cells near the pole), and the whole raster is read. @@ -3174,22 +3174,24 @@ mod tests { let gt = GeoTransform { origin_x: sw.x, origin_y: ne.y, pixel_width: cell, pixel_height: -cell }; let r = Raster::new("polar", w, h, vec![vec![1.0; (w * h) as usize]], gt, Crs::WebMercator, None, ColorHint::Gray, "Float32") .unwrap_or_else(|e| panic!("{e}")); - // NSIDC Sea Ice Polar Stereographic North: a square of 1,000 km each way about the pole, - // its sides near 77°N to 81°N. + // NSIDC Sea Ice Polar Stereographic North: squares of 1,000 km each way about the pole, + // their sides near 77°N to 81°N. let polar = Crs::Epsg(3413); - let d = 1_000_000.0; - let ring = vec![Coord::new(-d, -d), Coord::new(d, -d), Coord::new(d, d), Coord::new(-d, d), Coord::new(-d, -d)]; + // Centred on the pole, and off it. let to_polar = polar.transformer().unwrap_or_else(|e| panic!("{e}")); - let mut inside = 0; - for row in 0..h { - for col in 0..w { - let c = r.transform.to_world(f64::from(col) + 0.5, f64::from(row) + 0.5); - let p = merc.to_lonlat(c).and_then(|ll| to_polar.from_lonlat(ll)).unwrap_or_else(|| panic!("{c:?} is in EPSG:3413")); - inside += usize::from(p.x.abs() < d && p.y.abs() < d); + for (x0, x1, y0, y1) in [(-1e6, 1e6, -1e6, 1e6), (-0.9e6, 1.1e6, -1.05e6, 0.95e6)] { + let ring = vec![Coord::new(x0, y0), Coord::new(x1, y0), Coord::new(x1, y1), Coord::new(x0, y1), Coord::new(x0, y0)]; + let mut inside = 0; + for row in 0..h { + for col in 0..w { + let c = r.transform.to_world(f64::from(col) + 0.5, f64::from(row) + 0.5); + let p = merc.to_lonlat(c).and_then(|ll| to_polar.from_lonlat(ll)).unwrap_or_else(|| panic!("{c:?} is in EPSG:3413")); + inside += usize::from(p.x > x0 && p.x < x1 && p.y > y0 && p.y < y1); + } } + assert!(inside > 1000, "{inside} cells are in the zone"); + let got = zonal_means_in(&r, polar, &[0], &[ring]).unwrap_or_else(|e| panic!("{e}")); + assert_eq!(got, Some((vec![1.0], inside)), "{x0} {x1} {y0} {y1}"); } - assert!(inside > 1000, "{inside} cells are in the zone"); - let (means, n) = zonal_means_in(&r, polar, &[0], &[ring]).unwrap_or_else(|e| panic!("{e}")).unwrap_or_else(|| panic!("no cell")); - assert_eq!((means, n), (vec![1.0], inside)); } } diff --git a/crates/engine/src/cmd/imagery.rs b/crates/engine/src/cmd/imagery.rs index e81f29e43b..a32195cd75 100644 --- a/crates/engine/src/cmd/imagery.rs +++ b/crates/engine/src/cmd/imagery.rs @@ -458,13 +458,11 @@ const EXACT_WHOLE: f64 = 16_777_216.0; /// text field's code or one `value` (see `rustgis_analysis::warp::rasterize`). A new layer, and /// for a text field a table of its codes. /// -/// It runs on the thread that calls it, the app's own on the desktop, as it did before layers -/// held their own coordinates: it isn't yet one of the commands that make their raster on a thread -/// of their own (`workflows::IN_BACKGROUND`), since it writes its GeoTIFF to `path` and adds its -/// class table itself, which a move there has to carry over. Its loops look at Cancel (sizing the -/// grid, and between shapes in the burn), which stops a run only where a probe is installed (a -/// model or script run ahead on a copy of the session, `workflows::ahead_on_copy`); run by itself -/// in the app, nothing installs one, so there it runs to the end. +/// It runs on the thread that calls it, the app's own on the desktop: it isn't one of the commands +/// that make their raster on a thread of their own (`workflows::IN_BACKGROUND`) yet, and nothing +/// installs a probe around it, so Cancel doesn't reach it and it runs to the end. Its grid sizing +/// and burn look at Cancel (`progress::check`, `control::check`) for when it moves there, which +/// has to carry over the GeoTIFF it writes to `path` and the class table it adds. fn rasterize(s: &mut Session, p: &Value) -> CmdResult { let ln = rasterize_name(p)?; let l = s.map().layer_by_name(ln).filter(|l| l.raster.is_none()).ok_or_else(|| format!("no vector layer '{ln}'"))?; @@ -585,7 +583,7 @@ fn rasterize(s: &mut Session, p: &Value) -> CmdResult { // said when the grid takes these bounds (no extent given). let to = held.to(Crs::LonLat).map_err(|e| format!("{ln}: {e}"))?; let mut lonlat = Extent::EMPTY; - // A conversion a vertex: Cancel is looked at every few thousand (where a probe is + // A conversion a vertex: Cancel is looked at every few thousand (once a probe is // installed, see above). for (i, c) in shapes.iter().flat_map(|s| s.parts.iter().flatten().flatten()).filter(|c| c.is_finite()).enumerate() { if i % 4096 == 0 { @@ -600,9 +598,9 @@ fn rasterize(s: &mut Session, p: &Value) -> CmdResult { // Taking in the vertices as the burn places them: between two datums the direct operation // lands apart from the route through WGS 84 (half a metre for DHDN and ETRS89). if held != Crs::LonLat - && let Some(p) = warp::placed_bounds(held, crs, &shapes).map_err(|e| format!("{ln}: {e}"))? + && let Some(q) = warp::placed_bounds(held, crs, &shapes).map_err(|e| format!("{ln}: {e}"))? { - b = [b[0].min(p[0]), b[1].min(p[1]), b[2].max(p[2]), b[3].max(p[3])]; + b = [b[0].min(q[0]), b[1].min(q[1]), b[2].max(q[2]), b[3].max(q[3])]; } Ok((b, None)) })?; From b258e8928bf4545da248445d94ebbc75624a006a Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Sun, 22 Nov 2026 16:37:49 +0100 Subject: [PATCH 08/14] Review: a zone whose box holds a pole is read over the whole raster --- crates/analysis/src/rasterops.rs | 20 ++++++++++++++------ crates/analysis/src/tools.rs | 9 +++++++++ 2 files changed, 23 insertions(+), 6 deletions(-) diff --git a/crates/analysis/src/rasterops.rs b/crates/analysis/src/rasterops.rs index 02b90f0508..caa48e7201 100644 --- a/crates/analysis/src/rasterops.rs +++ b/crates/analysis/src/rasterops.rs @@ -1110,7 +1110,13 @@ fn means_under( } let mut sums = vec![0.0; bands.len()]; let mut n = 0usize; - let (cols, rows) = zone_window(r, &e, matches!(zone, ZoneIn::Own { .. }), |c| zone.grid(r, c)); + // A pole inside the zone's box, in a system other than the raster's: there a projection's grid + // tears or runs off without end (a Web Mercator raster's), so the outline bounds nothing. + let (cols, rows) = match zone { + ZoneIn::Own { to_zone, .. } if to_zone.poles().iter().any(|p| e.contains(*p)) => (0..r.width, 0..r.height), + ZoneIn::Own { .. } => zone_window(r, &e, true, |c| zone.grid(r, c)), + ZoneIn::LonLat => zone_window(r, &e, false, |c| zone.grid(r, c)), + }; each_rows((r.height - (rows.end - rows.start)) as usize)?; for row in rows { each_rows(1)?; @@ -1140,10 +1146,11 @@ fn means_under( /// projection's smooth image of a parallel or meridian doesn't. The whole raster when a point can't /// be placed; none when `e` is empty. /// -/// With `interior` (a zone held in a system other than longitude/latitude), places inside `e` are placed too, a sixteenth -/// of it apart: when one can't be, or lands outside the outline's window, the zone's box holds a -/// place the raster's grid can't take in one piece (a polar zone on a Web Mercator raster, whose -/// outline lands south of the cells near the pole), and the whole raster is read. +/// With `interior` (a zone held in a system other than longitude/latitude), places inside `e` are +/// placed too, a sixteenth of it apart: when one can't be, or lands outside the outline's window, +/// the zone's box holds a place the raster's grid can't take in one piece, and the whole raster is +/// read. (A box holding a pole, where a Web Mercator raster's grid runs off, is read whole before +/// this: `means_under`.) fn zone_window(r: &Raster, e: &Extent, interior: bool, to_grid: impl Fn(Coord) -> Option) -> (Range, Range) { if e.is_empty() { return (0..0, 0..0); @@ -3179,7 +3186,8 @@ mod tests { let polar = Crs::Epsg(3413); // Centred on the pole, and off it. let to_polar = polar.transformer().unwrap_or_else(|e| panic!("{e}")); - for (x0, x1, y0, y1) in [(-1e6, 1e6, -1e6, 1e6), (-0.9e6, 1.1e6, -1.05e6, 0.95e6)] { + // The last reaches far south: no sample inside it lands near the pole. + for (x0, x1, y0, y1) in [(-1e6, 1e6, -1e6, 1e6), (-0.9e6, 1.1e6, -1.05e6, 0.95e6), (-1e6, 31e6, -1e6, 31e6)] { let ring = vec![Coord::new(x0, y0), Coord::new(x1, y0), Coord::new(x1, y1), Coord::new(x0, y1), Coord::new(x0, y0)]; let mut inside = 0; for row in 0..h { diff --git a/crates/analysis/src/tools.rs b/crates/analysis/src/tools.rs index efdf65e4e1..1f7bfbf3dd 100644 --- a/crates/analysis/src/tools.rs +++ b/crates/analysis/src/tools.rs @@ -5243,6 +5243,15 @@ impl ToGrid { Ok(self.direct.as_ref().map_or(via, |d| d.point_near(c, via))) } + /// The places of the North and South Pole in the grid's system, those it holds: none when the + /// systems are the same. + pub(crate) fn poles(&self) -> Vec { + if self.same { + return Vec::new(); + } + [90.0, -90.0].into_iter().filter_map(|lat| self.to.from_lonlat(Coord::new(0.0, lat)).filter(|p| p.is_finite())).collect() + } + /// 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 From a9935af09f19550f704b1a82b58fff558ddd8c1f Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Sun, 22 Nov 2026 16:42:31 +0100 Subject: [PATCH 09/14] Review: a pole is said in a zone's system only where it holds it; window docs --- crates/analysis/src/rasterops.rs | 10 +++++----- crates/analysis/src/tools.rs | 2 +- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/crates/analysis/src/rasterops.rs b/crates/analysis/src/rasterops.rs index caa48e7201..e8457c710c 100644 --- a/crates/analysis/src/rasterops.rs +++ b/crates/analysis/src/rasterops.rs @@ -1110,8 +1110,8 @@ fn means_under( } let mut sums = vec![0.0; bands.len()]; let mut n = 0usize; - // A pole inside the zone's box, in a system other than the raster's: there a projection's grid - // tears or runs off without end (a Web Mercator raster's), so the outline bounds nothing. + // A pole inside the zone's box, in a system other than the raster's: the outline bounds nothing + // there (on a Web Mercator raster it lands south of the cells near the pole). let (cols, rows) = match zone { ZoneIn::Own { to_zone, .. } if to_zone.poles().iter().any(|p| e.contains(*p)) => (0..r.width, 0..r.height), ZoneIn::Own { .. } => zone_window(r, &e, true, |c| zone.grid(r, c)), @@ -1149,8 +1149,8 @@ fn means_under( /// With `interior` (a zone held in a system other than longitude/latitude), places inside `e` are /// placed too, a sixteenth of it apart: when one can't be, or lands outside the outline's window, /// the zone's box holds a place the raster's grid can't take in one piece, and the whole raster is -/// read. (A box holding a pole, where a Web Mercator raster's grid runs off, is read whole before -/// this: `means_under`.) +/// read. (A box holding a pole, whose outline lands south of a Web Mercator raster's cells near +/// it, is read whole before this: `means_under`.) fn zone_window(r: &Raster, e: &Extent, interior: bool, to_grid: impl Fn(Coord) -> Option) -> (Range, Range) { if e.is_empty() { return (0..0, 0..0); @@ -3186,7 +3186,7 @@ mod tests { let polar = Crs::Epsg(3413); // Centred on the pole, and off it. let to_polar = polar.transformer().unwrap_or_else(|e| panic!("{e}")); - // The last reaches far south: no sample inside it lands near the pole. + // The last reaches far north and east: no sample inside it lands near the pole. for (x0, x1, y0, y1) in [(-1e6, 1e6, -1e6, 1e6), (-0.9e6, 1.1e6, -1.05e6, 0.95e6), (-1e6, 31e6, -1e6, 31e6)] { let ring = vec![Coord::new(x0, y0), Coord::new(x1, y0), Coord::new(x1, y1), Coord::new(x0, y1), Coord::new(x0, y0)]; let mut inside = 0; diff --git a/crates/analysis/src/tools.rs b/crates/analysis/src/tools.rs index 1f7bfbf3dd..1260404844 100644 --- a/crates/analysis/src/tools.rs +++ b/crates/analysis/src/tools.rs @@ -5249,7 +5249,7 @@ impl ToGrid { if self.same { return Vec::new(); } - [90.0, -90.0].into_iter().filter_map(|lat| self.to.from_lonlat(Coord::new(0.0, lat)).filter(|p| p.is_finite())).collect() + [90.0, -90.0].into_iter().filter_map(|lat| in_projected(self.crs, &self.to, Coord::new(0.0, lat))).collect() } /// A polygon's vertex in the grid's system, as the grid's transformer takes a place in From 7e590a1456d9b17a71d5c46f04e22aefef1c0e04 Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Sun, 22 Nov 2026 17:16:09 +0100 Subject: [PATCH 10/14] Review: a spectral zone reads every part of its polygon (tested) --- crates/engine/src/cmd/imagery.rs | 31 ++++++++++++++++++-------- crates/engine/src/tests/held_layers.rs | 17 ++++++++++++++ 2 files changed, 39 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/cmd/imagery.rs b/crates/engine/src/cmd/imagery.rs index a32195cd75..b7abaee1dd 100644 --- a/crates/engine/src/cmd/imagery.rs +++ b/crates/engine/src/cmd/imagery.rs @@ -63,7 +63,7 @@ pub fn commands() -> Vec { .params(r#"{"before": raster, "after": raster, "band"?: 1-based, "method"?: "difference"|"ratio"|"percent", "name"?, "ran"?: (internal: a raster the app has worked out)}"#), C::new("raster.spectral", "Spectral Analysis", "Imagery › Image Analysis", spectral).inputs(spectral_inputs).roles(&[]).effects(crate::policy::Effects::NONE) .view() - .params(r#"{"layer": raster, "lon"?, "lat"?, "points"?: [[lon, lat], …] (up to 1000: a profile each, in "profiles"; one off the raster has a null pixel and values, and is said), "zone"?: polygon layer (the mean of its selected or first polygon's pixels)}"#), + .params(r#"{"layer": raster, "lon"?, "lat"?, "points"?: [[lon, lat], …] (up to 1000: a profile each, in "profiles"; one off the raster has a null pixel and values, and is said), "zone"?: polygon layer (the mean of its selected or first polygon's pixels, every part of it)}"#), C::new("raster.classify", "Classification Wizard", "Imagery › Image Classification", |s, p| { super::workflows::made_or_ran(s, p, "raster.classify") }).inputs(raster_inputs).roles(&[]).effects(crate::policy::Effects::NONE) @@ -1076,9 +1076,9 @@ fn spectral_read(s: &mut Session, p: &Value, r: &Arc, zone: Option<&str> answer(json!({"bands": names, "values": vals, "pixel": [col, row]})) } -/// The polygon a spectral zone names: the polygon layer `z`'s selected feature, or its first, in -/// the system the layer holds its coordinates in. -fn zone_rings(s: &Session, z: &str) -> Result<(Crs, Vec>), String> { +/// The polygon a spectral zone names, every part of it (each its rings): the polygon layer `z`'s +/// selected feature, or its first, in the system the layer holds its coordinates in. +fn zone_rings(s: &Session, z: &str) -> Result<(Crs, Vec>>), String> { let l = s.map().layer_by_name(z).filter(|l| l.geometry_type() == GeometryType::Polygon).ok_or_else(|| format!("no polygon layer '{z}'"))?; let row = l.selection.first().copied().unwrap_or(0); @@ -1088,15 +1088,19 @@ fn zone_rings(s: &Session, z: &str) -> Result<(Crs, Vec>), String> { let Geometry::Polygon(polys) = g else { return Err("the zone has no polygon".into()); }; - Ok((l.dataset.coord_crs(), polys.first().cloned().ok_or("the zone has no polygon")?)) + if polys.is_empty() { + return Err("the zone has no polygon".into()); + } + Ok((l.dataset.coord_crs(), polys.clone())) } -/// A zone's means, every band's: those a script's copy of the session read, when of this raster +/// A zone's means, every band's, over all its parts (which don't overlap, so each pixel counts +/// once): those a script's copy of the session read, when of this raster /// and this polygon; read here otherwise (and recorded, on that copy, for the script's run here to /// take). A raster a tool made earlier in the script is decoded apart on each side, so its zones /// are read again here. #[cfg_attr(target_arch = "wasm32", expect(unused_variables, reason = "zones are read ahead on the desktop only"))] -fn zone_means(s: &mut Session, r: &Arc, crs: Crs, rings: Vec>) -> Result, usize)>, String> { +fn zone_means(s: &mut Session, r: &Arc, crs: Crs, rings: Vec>>) -> Result, usize)>, String> { #[cfg(not(target_arch = "wasm32"))] let same = |z: &ZoneMeans| Arc::ptr_eq(&z.raster, r) && z.crs == crs && z.rings == rings; #[cfg(not(target_arch = "wasm32"))] @@ -1114,7 +1118,16 @@ fn zone_means(s: &mut Session, r: &Arc, crs: Crs, rings: Vec> } let all: Vec = (0..r.band_count()).collect(); // The cells are tested in the zone's own system: none of it converted when it is the raster's. - let means = rasterops::zonal_means_in(r, crs, &all, &rings); + let means = (|| { + let (mut sums, mut n) = (vec![0.0; all.len()], 0usize); + for part in &rings { + if let Some((m, k)) = rasterops::zonal_means_in(r, crs, &all, part)? { + sums.iter_mut().zip(&m).for_each(|(s, v)| *s += v * k as f64); + n += k; + } + } + Ok((n > 0).then(|| (sums.into_iter().map(|s| s / n as f64).collect(), n))) + })(); #[cfg(not(target_arch = "wasm32"))] if let Some(ZonesAhead::Recording(zones)) = &mut s.zones_ahead { zones.push(ZoneMeans { raster: r.clone(), crs, rings, means: means.clone() }); @@ -1136,7 +1149,7 @@ pub(crate) enum ZonesAhead { pub(crate) struct ZoneMeans { raster: Arc, crs: Crs, - rings: Vec>, + rings: Vec>>, means: Result, usize)>, String>, } diff --git a/crates/engine/src/tests/held_layers.rs b/crates/engine/src/tests/held_layers.rs index 58864536b8..581131e219 100644 --- a/crates/engine/src/tests/held_layers.rs +++ b/crates/engine/src/tests/held_layers.rs @@ -2305,6 +2305,23 @@ fn a_held_layer_is_burned_in_its_own_system() { assert_eq!(a["cells"], 100, "{a}"); } +/// A spectral zone of two parts reads both: two 100 m squares of one feature, held in UTM, each +/// holding 10 × 10 centres of 10 m cells (none on an edge), burned and then read as the zone, give +/// 200 pixels. +#[test] +fn a_spectral_zone_reads_every_part() { + let square = |x0: f64, y0: f64| -> Vec { + [(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0), (0.0, 0.0)].iter().map(|(x, y)| Coord::new(x0 + x, y0 + y)).collect() + }; + let parts = vec![vec![square(2_000_002.0, 5_401_302.0)], vec![square(2_000_502.0, 5_401_302.0)]]; + let mut s = Session::new(Project::default()); + add_in(&mut s, "Two", GeometryType::Polygon, vec![Geometry::Polygon(parts)], UTM); + let burned = s.run("raster.rasterize", &json!({"layer": "Two", "value": 3, "cellSize": 10, "name": "Burned"})).unwrap(); + assert_eq!(burned["cells"], 200, "{burned}"); + let read = s.run("raster.spectral", &json!({"layer": "Burned", "zone": "Two"})).unwrap(); + assert_eq!((read["pixels"].clone(), read["values"].clone()), (json!(200), json!([3.0])), "{read}"); +} + /// Rasterize's default grid in another system takes in the polygons as they are burned, by the /// direct operation: a 5 cm square held in Gauss-Krüger zone 3 (DHDN), burned onto 1 cm cells in /// ETRS89 / UTM 32N, lands 0.44 m from where the route through WGS 84 puts it, so a grid sized From 7732f227df6f85869bd50622ab835d3c0e4cb50b Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Sun, 22 Nov 2026 17:20:36 +0100 Subject: [PATCH 11/14] Review: a zone's parts are read in one count, a pixel two parts hold counted once --- crates/analysis/src/rasterops.rs | 91 +++++++++++++++----------- crates/engine/src/cmd/imagery.rs | 20 ++---- crates/engine/src/tests/held_layers.rs | 8 ++- 3 files changed, 63 insertions(+), 56 deletions(-) diff --git a/crates/analysis/src/rasterops.rs b/crates/analysis/src/rasterops.rs index e8457c710c..6e69fa73b3 100644 --- a/crates/analysis/src/rasterops.rs +++ b/crates/analysis/src/rasterops.rs @@ -1012,20 +1012,22 @@ pub fn classify_min_distance(r: &Raster, bands: &[usize], means: &[(f32, Vec]) -> Result, usize)>, crate::control::Cancelled> { crate::control::begin(r.height as usize); - means_under(r, &ZoneIn::LonLat, bands, rings, |rows| { + means_under(r, &ZoneIn::LonLat, bands, &[rings], |rows| { crate::control::check()?; crate::control::advance(rows); Ok(()) }) } -/// [`zonal_means`] of a polygon whose rings are in `from`: longitude/latitude, or the system its -/// layer holds its coordinates in. A cell's centre is converted into that system to be tested -/// (none of it when it is the raster's own), by the direct operation between two datums. -pub fn zonal_means_in(r: &Raster, from: Crs, bands: &[usize], rings: &[Vec]) -> Result, usize)>, String> { +/// [`zonal_means`] of a polygon's `parts` (each its rings, a pixel in two parts counted once) in +/// `from`: longitude/latitude, or the system its layer holds its coordinates in. A cell's centre is +/// converted into that system to be tested (none of it when it is the raster's own), by the direct +/// operation between two datums. Each part's rows count toward the progress. +pub fn zonal_means_in(r: &Raster, from: Crs, bands: &[usize], parts: &[Vec>]) -> Result, usize)>, String> { let zone = ZoneIn::new(r, from)?; - crate::control::begin(r.height as usize); - Ok(means_under(r, &zone, bands, rings, |rows| { + crate::control::begin(parts.len().saturating_mul(r.height as usize)); + let parts: Vec<&[Vec]> = parts.iter().map(Vec::as_slice).collect(); + Ok(means_under(r, &zone, bands, &parts, |rows| { crate::control::check()?; crate::control::advance(rows); Ok(()) @@ -1090,46 +1092,55 @@ pub fn polygon_mask_in( polygon_mask_on(ToWorld::Own(&to), &r.transform, (r.width, r.height), polygons, failed_parts) } -/// [`zonal_means`], `each_rows(n)` asked as the raster's rows go by, `n` at a time (each row -/// once, all of them): an error stops it. +/// [`zonal_means`] over a zone's `parts` (each its rings), `each_rows(n)` asked as the raster's +/// rows go by, `n` at a time (each row once a part, all of them): an error stops it. /// -/// A cell counts when its centre, in the zone's system (`zone`), lies in the zone (inside the -/// outer ring and in no hole). Only the cells in the zone's window are tested ([`zone_window`]), -/// not every cell of the raster, in the same row-major order, so the sums are those of testing -/// them all. +/// A cell counts when its centre, in the zone's system (`zone`), lies in a part (inside its outer +/// ring and in none of its holes), once however many parts hold it. Each part's cells are tested in +/// its window ([`zone_window`]), not every cell of the raster, in the same row-major order, so for +/// one part the sums are those of testing them all. fn means_under( r: &Raster, zone: &ZoneIn, bands: &[usize], - rings: &[Vec], + parts: &[&[Vec]], mut each_rows: impl FnMut(usize) -> Result<(), crate::control::Cancelled>, ) -> Result, usize)>, crate::control::Cancelled> { - let mut e = Extent::EMPTY; - for c in rings.iter().flatten() { - e.expand(*c); - } + let boxes: Vec = parts + .iter() + .map(|rings| { + rings.iter().flatten().fold(Extent::EMPTY, |mut e, c| { + e.expand(*c); + e + }) + }) + .collect(); + let in_part = |k: usize, ll: Coord| boxes[k].contains(ll) && rustgis_data::geometry::polygon_contains(parts[k], ll); let mut sums = vec![0.0; bands.len()]; let mut n = 0usize; - // A pole inside the zone's box, in a system other than the raster's: the outline bounds nothing - // there (on a Web Mercator raster it lands south of the cells near the pole). - let (cols, rows) = match zone { - ZoneIn::Own { to_zone, .. } if to_zone.poles().iter().any(|p| e.contains(*p)) => (0..r.width, 0..r.height), - ZoneIn::Own { .. } => zone_window(r, &e, true, |c| zone.grid(r, c)), - ZoneIn::LonLat => zone_window(r, &e, false, |c| zone.grid(r, c)), - }; - each_rows((r.height - (rows.end - rows.start)) as usize)?; - for row in rows { - each_rows(1)?; - for col in cols.clone() { - let w = r.transform.to_world(f64::from(col) + 0.5, f64::from(row) + 0.5); - let Some(ll) = zone.zone(r, w) else { continue }; - if !e.contains(ll) || !rustgis_data::geometry::polygon_contains(rings, ll) { - continue; - } - let vals: Option> = bands.iter().map(|b| r.value(*b, i64::from(col), i64::from(row)).map(f64::from)).collect(); - if let Some(v) = vals { - sums.iter_mut().zip(&v).for_each(|(s, x)| *s += x); - n += 1; + for (k, e) in boxes.iter().enumerate() { + // A pole inside the zone's box, in a system other than the raster's: the outline bounds + // nothing there (on a Web Mercator raster it lands south of the cells near the pole). + let (cols, rows) = match zone { + ZoneIn::Own { to_zone, .. } if to_zone.poles().iter().any(|p| e.contains(*p)) => (0..r.width, 0..r.height), + ZoneIn::Own { .. } => zone_window(r, e, true, |c| zone.grid(r, c)), + ZoneIn::LonLat => zone_window(r, e, false, |c| zone.grid(r, c)), + }; + each_rows((r.height - (rows.end - rows.start)) as usize)?; + for row in rows { + each_rows(1)?; + for col in cols.clone() { + let w = r.transform.to_world(f64::from(col) + 0.5, f64::from(row) + 0.5); + let Some(ll) = zone.zone(r, w) else { continue }; + // Counted for the first part that holds it, so parts that overlap count it once. + if !in_part(k, ll) || (0..k).any(|j| in_part(j, ll)) { + continue; + } + let vals: Option> = bands.iter().map(|b| r.value(*b, i64::from(col), i64::from(row)).map(f64::from)).collect(); + if let Some(v) = vals { + sums.iter_mut().zip(&v).for_each(|(s, x)| *s += x); + n += 1; + } } } } @@ -1230,7 +1241,7 @@ pub fn class_means(r: &Raster, bands: &[usize], polygons: &[(String, Vec { let total = c.2 + n; @@ -3198,7 +3209,7 @@ mod tests { } } assert!(inside > 1000, "{inside} cells are in the zone"); - let got = zonal_means_in(&r, polar, &[0], &[ring]).unwrap_or_else(|e| panic!("{e}")); + let got = zonal_means_in(&r, polar, &[0], &[vec![ring]]).unwrap_or_else(|e| panic!("{e}")); assert_eq!(got, Some((vec![1.0], inside)), "{x0} {x1} {y0} {y1}"); } } diff --git a/crates/engine/src/cmd/imagery.rs b/crates/engine/src/cmd/imagery.rs index b7abaee1dd..d136545fbb 100644 --- a/crates/engine/src/cmd/imagery.rs +++ b/crates/engine/src/cmd/imagery.rs @@ -1094,11 +1094,10 @@ fn zone_rings(s: &Session, z: &str) -> Result<(Crs, Vec>>), Strin Ok((l.dataset.coord_crs(), polys.clone())) } -/// A zone's means, every band's, over all its parts (which don't overlap, so each pixel counts -/// once): those a script's copy of the session read, when of this raster -/// and this polygon; read here otherwise (and recorded, on that copy, for the script's run here to -/// take). A raster a tool made earlier in the script is decoded apart on each side, so its zones -/// are read again here. +/// A zone's means, every band's, over all its parts (a pixel in two parts counted once): those a +/// script's copy of the session read, when of this raster and this polygon; read here otherwise +/// (and recorded, on that copy, for the script's run here to take). A raster a tool made earlier in +/// the script is decoded apart on each side, so its zones are read again here. #[cfg_attr(target_arch = "wasm32", expect(unused_variables, reason = "zones are read ahead on the desktop only"))] fn zone_means(s: &mut Session, r: &Arc, crs: Crs, rings: Vec>>) -> Result, usize)>, String> { #[cfg(not(target_arch = "wasm32"))] @@ -1118,16 +1117,7 @@ fn zone_means(s: &mut Session, r: &Arc, crs: Crs, rings: Vec = (0..r.band_count()).collect(); // The cells are tested in the zone's own system: none of it converted when it is the raster's. - let means = (|| { - let (mut sums, mut n) = (vec![0.0; all.len()], 0usize); - for part in &rings { - if let Some((m, k)) = rasterops::zonal_means_in(r, crs, &all, part)? { - sums.iter_mut().zip(&m).for_each(|(s, v)| *s += v * k as f64); - n += k; - } - } - Ok((n > 0).then(|| (sums.into_iter().map(|s| s / n as f64).collect(), n))) - })(); + let means = rasterops::zonal_means_in(r, crs, &all, &rings); #[cfg(not(target_arch = "wasm32"))] if let Some(ZonesAhead::Recording(zones)) = &mut s.zones_ahead { zones.push(ZoneMeans { raster: r.clone(), crs, rings, means: means.clone() }); diff --git a/crates/engine/src/tests/held_layers.rs b/crates/engine/src/tests/held_layers.rs index 581131e219..4a5c64f1f5 100644 --- a/crates/engine/src/tests/held_layers.rs +++ b/crates/engine/src/tests/held_layers.rs @@ -2307,7 +2307,7 @@ fn a_held_layer_is_burned_in_its_own_system() { /// A spectral zone of two parts reads both: two 100 m squares of one feature, held in UTM, each /// holding 10 × 10 centres of 10 m cells (none on an edge), burned and then read as the zone, give -/// 200 pixels. +/// 200 pixels; a part over another's pixels doesn't count them twice. #[test] fn a_spectral_zone_reads_every_part() { let square = |x0: f64, y0: f64| -> Vec { @@ -2320,6 +2320,12 @@ fn a_spectral_zone_reads_every_part() { assert_eq!(burned["cells"], 200, "{burned}"); let read = s.run("raster.spectral", &json!({"layer": "Burned", "zone": "Two"})).unwrap(); assert_eq!((read["pixels"].clone(), read["values"].clone()), (json!(200), json!([3.0])), "{read}"); + // A third part over half of the first: its 50 shared pixels count once. + let parts = + vec![vec![square(2_000_002.0, 5_401_302.0)], vec![square(2_000_502.0, 5_401_302.0)], vec![square(2_000_052.0, 5_401_302.0)]]; + add_in(&mut s, "Three", GeometryType::Polygon, vec![Geometry::Polygon(parts)], UTM); + let read = s.run("raster.spectral", &json!({"layer": "Burned", "zone": "Three"})).unwrap(); + assert_eq!(read["pixels"], 200, "{read}"); } /// Rasterize's default grid in another system takes in the polygons as they are burned, by the From 376709a598c2064b2f7d0a737c4e67b1d65f10a3 Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Sun, 22 Nov 2026 17:52:38 +0100 Subject: [PATCH 12/14] Review: a zone's part tests only the earlier parts its box meets (through ExtentIndex); rasterize's notice says one vertex as such --- crates/analysis/src/rasterops.rs | 10 ++++++++-- crates/engine/src/cmd/imagery.rs | 9 +++++++-- crates/engine/src/tests/held_layers.rs | 2 +- 3 files changed, 16 insertions(+), 5 deletions(-) diff --git a/crates/analysis/src/rasterops.rs b/crates/analysis/src/rasterops.rs index 6e69fa73b3..43e529f967 100644 --- a/crates/analysis/src/rasterops.rs +++ b/crates/analysis/src/rasterops.rs @@ -1093,7 +1093,7 @@ pub fn polygon_mask_in( } /// [`zonal_means`] over a zone's `parts` (each its rings), `each_rows(n)` asked as the raster's -/// rows go by, `n` at a time (each row once a part, all of them): an error stops it. +/// rows go by, `n` at a time (each row once per part, all of them): an error stops it. /// /// A cell counts when its centre, in the zone's system (`zone`), lies in a part (inside its outer /// ring and in none of its holes), once however many parts hold it. Each part's cells are tested in @@ -1116,9 +1116,13 @@ fn means_under( }) .collect(); let in_part = |k: usize, ll: Coord| boxes[k].contains(ll) && rustgis_data::geometry::polygon_contains(parts[k], ll); + // The earlier parts a cell of a part may also lie in are found by their boxes: a part whose box + // meets no earlier one's tests none of them. + let index = (parts.len() > 1).then(|| crate::tools::ExtentIndex::new(boxes.iter().copied())); let mut sums = vec![0.0; bands.len()]; let mut n = 0usize; for (k, e) in boxes.iter().enumerate() { + let earlier = index.as_ref().filter(|ix| ix.any_candidate(e, |j| j < k && boxes[j].intersects(e))); // A pole inside the zone's box, in a system other than the raster's: the outline bounds // nothing there (on a Web Mercator raster it lands south of the cells near the pole). let (cols, rows) = match zone { @@ -1133,7 +1137,9 @@ fn means_under( let w = r.transform.to_world(f64::from(col) + 0.5, f64::from(row) + 0.5); let Some(ll) = zone.zone(r, w) else { continue }; // Counted for the first part that holds it, so parts that overlap count it once. - if !in_part(k, ll) || (0..k).any(|j| in_part(j, ll)) { + if !in_part(k, ll) + || earlier.is_some_and(|ix| ix.any_candidate(&Extent::new(ll.x, ll.y, ll.x, ll.y), |j| j < k && in_part(j, ll))) + { continue; } let vals: Option> = bands.iter().map(|b| r.value(*b, i64::from(col), i64::from(row)).map(f64::from)).collect(); diff --git a/crates/engine/src/cmd/imagery.rs b/crates/engine/src/cmd/imagery.rs index d136545fbb..1be77ae3da 100644 --- a/crates/engine/src/cmd/imagery.rs +++ b/crates/engine/src/cmd/imagery.rs @@ -63,7 +63,7 @@ pub fn commands() -> Vec { .params(r#"{"before": raster, "after": raster, "band"?: 1-based, "method"?: "difference"|"ratio"|"percent", "name"?, "ran"?: (internal: a raster the app has worked out)}"#), C::new("raster.spectral", "Spectral Analysis", "Imagery › Image Analysis", spectral).inputs(spectral_inputs).roles(&[]).effects(crate::policy::Effects::NONE) .view() - .params(r#"{"layer": raster, "lon"?, "lat"?, "points"?: [[lon, lat], …] (up to 1000: a profile each, in "profiles"; one off the raster has a null pixel and values, and is said), "zone"?: polygon layer (the mean of its selected or first polygon's pixels, every part of it)}"#), + .params(r#"{"layer": raster, "lon"?, "lat"?, "points"?: [[lon, lat], …] (up to 1000: a profile each, in "profiles"; one off the raster has a null pixel and values, and is said), "zone"?: polygon layer (the mean of the pixels in every part of its selected or first polygon)}"#), C::new("raster.classify", "Classification Wizard", "Imagery › Image Classification", |s, p| { super::workflows::made_or_ran(s, p, "raster.classify") }).inputs(raster_inputs).roles(&[]).effects(crate::policy::Effects::NONE) @@ -606,7 +606,12 @@ fn rasterize(s: &mut Session, p: &Value) -> CmdResult { })?; if unsized_by > 0 && p.get("extent").is_none_or(Value::is_null) { s.notify( - format!("{ln}: {unsized_by} vertices that can't be placed in longitude/latitude were left out of the grid's extent: give an extent to take them in"), + format!( + "{ln}: {unsized_by} {} that can't be placed in longitude/latitude {} left out of the grid's extent: give an extent to take {} in", + if unsized_by == 1 { "vertex" } else { "vertices" }, + if unsized_by == 1 { "was" } else { "were" }, + if unsized_by == 1 { "it" } else { "them" } + ), false, ); } diff --git a/crates/engine/src/tests/held_layers.rs b/crates/engine/src/tests/held_layers.rs index 4a5c64f1f5..54b75590b2 100644 --- a/crates/engine/src/tests/held_layers.rs +++ b/crates/engine/src/tests/held_layers.rs @@ -2355,7 +2355,7 @@ fn rasterize_says_the_vertices_left_out_of_its_extent() { let far = vec![Coord::new(x0, y0), Coord::new(1e12, 1e12), Coord::new(x0, y0 + 500.0), Coord::new(x0, y0)]; let mut s = Session::new(Project::default()); add_in(&mut s, "Plots", GeometryType::Polygon, vec![Geometry::Polygon(vec![vec![square]]), Geometry::Polygon(vec![vec![far]])], UTM); - let left_out = "vertices that can't be placed in longitude/latitude were left out of the grid's extent"; + let left_out = "vertex that can't be placed in longitude/latitude was left out of the grid's extent: give an extent to take it in"; let said = |s: &Session, mark| s.notices_since(mark).iter().map(|n| n.text.clone()).collect::>(); let mark = s.notice_mark(); s.run("raster.rasterize", &json!({"layer": "Plots", "crs": "EPSG:4326", "cellSize": 0.001, "name": "A"})).unwrap(); From 0054e05ce258a5149446eb851ec30c3fd2d54063 Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Sun, 22 Nov 2026 18:13:45 +0100 Subject: [PATCH 13/14] Review: clean held input says nothing left out (IDW, Kriging, Kernel Density, Rasterize) --- crates/engine/src/tests/held_layers.rs | 28 ++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/crates/engine/src/tests/held_layers.rs b/crates/engine/src/tests/held_layers.rs index 54b75590b2..a680b343e3 100644 --- a/crates/engine/src/tests/held_layers.rs +++ b/crates/engine/src/tests/held_layers.rs @@ -2371,6 +2371,34 @@ fn rasterize_says_the_vertices_left_out_of_its_extent() { assert!(!b.iter().any(|t| t.contains(left_out)), "{b:?}"); } +/// Clean input says nothing of places left out: points and a polygon held in UTM, all of which the +/// systems on each side hold, interpolated and smoothed onto Web Mercator and burned onto a grid +/// in degrees with no extent given. +#[test] +fn clean_held_input_says_nothing_left_out() { + let mut s = Session::new(Project::default()); + let at = [(784_000.0, 5_401_300.0), (785_000.0, 5_402_300.0), (786_000.0, 5_401_800.0), (784_500.0, 5_402_900.0)]; + add_in(&mut s, "Samples", GeometryType::Point, at.iter().map(|(x, y)| Geometry::Point(Coord::new(*x, *y))).collect(), UTM); + let square: Vec = [(0.0, 0.0), (500.0, 0.0), (500.0, 500.0), (0.0, 500.0), (0.0, 0.0)] + .iter() + .map(|(x, y)| Coord::new(784_000.0 + x, 5_401_300.0 + y)) + .collect(); + add_in(&mut s, "Plot", GeometryType::Polygon, vec![Geometry::Polygon(vec![vec![square]])], UTM); + let mark = s.notice_mark(); + let mut answers = Vec::new(); + for (tool, out) in [("idwInterpolation", "Idw"), ("kriging", "Krig")] { + let p = json!({"tool": tool, "params": {"input": "Samples", "field": "v", "pixelSize": 100, "crs": "EPSG:3857", "output": out}}); + answers.push(s.run("gp.run", &p).unwrap().to_string()); + } + let p = json!({"tool": "kernelDensity", "params": {"input": "Samples", "radius": 500, "pixelSize": 50, "crs": "EPSG:3857", "output": "Kde"}}); + answers.push(s.run("gp.run", &p).unwrap().to_string()); + s.run("raster.rasterize", &json!({"layer": "Plot", "crs": "EPSG:4326", "cellSize": 0.001, "name": "Burned"})).unwrap(); + let said: Vec = s.notices_since(mark).iter().map(|n| n.text.clone()).chain(answers).collect(); + for left_out in ["can't give in longitude/latitude", "beyond what", "left out of the grid's extent"] { + assert!(!said.iter().any(|t| t.contains(left_out)), "{left_out}: {said:?}"); + } +} + /// A point the layer's own system can't give in longitude/latitude is counted apart from one the /// grid's system can't hold: IDW from points held in UTM, one far beyond any place UTM holds, /// says that UTM can't give it, not that the grid can't hold it. From 68e508eca26d84fe9140ef20caa2e6f9cb222cb7 Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Sun, 22 Nov 2026 18:22:58 +0100 Subject: [PATCH 14/14] Review: rasterize's unplaced-vertex notice points to the coordinates and the layer's system, not an extent --- crates/engine/src/cmd/imagery.rs | 4 ++-- crates/engine/src/tests/held_layers.rs | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/imagery.rs b/crates/engine/src/cmd/imagery.rs index 1be77ae3da..7bd2f0ab02 100644 --- a/crates/engine/src/cmd/imagery.rs +++ b/crates/engine/src/cmd/imagery.rs @@ -607,10 +607,10 @@ fn rasterize(s: &mut Session, p: &Value) -> CmdResult { if unsized_by > 0 && p.get("extent").is_none_or(Value::is_null) { s.notify( format!( - "{ln}: {unsized_by} {} that can't be placed in longitude/latitude {} left out of the grid's extent: give an extent to take {} in", + "{ln}: {unsized_by} {} that can't be placed in longitude/latitude {} left out of the grid's extent: check {} coordinates and the layer's coordinate system", if unsized_by == 1 { "vertex" } else { "vertices" }, if unsized_by == 1 { "was" } else { "were" }, - if unsized_by == 1 { "it" } else { "them" } + if unsized_by == 1 { "its" } else { "their" } ), false, ); diff --git a/crates/engine/src/tests/held_layers.rs b/crates/engine/src/tests/held_layers.rs index a680b343e3..50ed50048c 100644 --- a/crates/engine/src/tests/held_layers.rs +++ b/crates/engine/src/tests/held_layers.rs @@ -2355,7 +2355,7 @@ fn rasterize_says_the_vertices_left_out_of_its_extent() { let far = vec![Coord::new(x0, y0), Coord::new(1e12, 1e12), Coord::new(x0, y0 + 500.0), Coord::new(x0, y0)]; let mut s = Session::new(Project::default()); add_in(&mut s, "Plots", GeometryType::Polygon, vec![Geometry::Polygon(vec![vec![square]]), Geometry::Polygon(vec![vec![far]])], UTM); - let left_out = "vertex that can't be placed in longitude/latitude was left out of the grid's extent: give an extent to take it in"; + let left_out = "vertex that can't be placed in longitude/latitude was left out of the grid's extent: check its coordinates and the layer's coordinate system"; let said = |s: &Session, mark| s.notices_since(mark).iter().map(|n| n.text.clone()).collect::>(); let mark = s.notice_mark(); s.run("raster.rasterize", &json!({"layer": "Plots", "crs": "EPSG:4326", "cellSize": 0.001, "name": "A"})).unwrap();