diff --git a/crates/analysis/src/rasterops.rs b/crates/analysis/src/rasterops.rs index 1abe9657e3..43e529f967 100644 --- a/crates/analysis/src/rasterops.rs +++ b/crates/analysis/src/rasterops.rs @@ -1012,61 +1012,163 @@ 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`], `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`] 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(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(()) + })?) +} + +/// 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). A cell's centre goes into the zone's system as a point +/// ([`crate::tools::ToGrid::place`]): a cell centre the zone's system can't hold is outside the +/// zone, so it isn't counted. The zone's extent goes onto the raster's grid as a polygon's vertices do +/// ([`crate::tools::ToGrid::vertex`]), Web Mercator taking a latitude past 85.05° as 85.05°, as +/// it takes a place in longitude/latitude, so a zone reaching past it is still read within its +/// window. +pub(crate) enum ZoneIn { + LonLat, + Own { to_zone: Box, to_grid: Box }, +} + +impl ZoneIn { + pub(crate) fn new(r: &Raster, from: Crs) -> Result { + Ok(if from == Crs::LonLat { + Self::LonLat + } else { + Self::Own { + to_zone: Box::new(crate::tools::ToGrid::new(r.crs, from)?), + to_grid: Box::new(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.vertex(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`] 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 per part, 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 -/// 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); + // 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; - let (cols, rows) = zone_window(r, &e); - 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 }; - 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() { + 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 { + 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) + || 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(); + if let Some(v) = vals { + sums.iter_mut().zip(&v).for_each(|(s, x)| *s += x); + n += 1; + } } } } 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 -/// 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) -> (Range, Range) { +/// 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. +/// +/// 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, 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); } @@ -1076,7 +1178,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] = [ @@ -1113,11 +1215,23 @@ fn zone_window(r: &Raster, e: &Extent) -> (Range, Range) { 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 @@ -1133,7 +1247,7 @@ pub fn class_means(r: &Raster, bands: &[usize], polygons: &[(String, Vec { let total = c.2 + n; @@ -3069,4 +3183,40 @@ 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: squares of 1,000 km each way about the pole, + // their sides near 77°N to 81°N. + 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 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; + 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], &[vec![ring]]).unwrap_or_else(|e| panic!("{e}")); + assert_eq!(got, Some((vec![1.0], inside)), "{x0} {x1} {y0} {y1}"); + } + } } diff --git a/crates/analysis/src/tools.rs b/crates/analysis/src/tools.rs index 243ce94523..1260404844 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`]). @@ -5168,6 +5189,14 @@ 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)) } +/// 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, +} + /// 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 @@ -5193,15 +5222,34 @@ impl ToGrid { } pub(crate) fn place(&self, c: Coord) -> Option { + self.try_place(c).ok() + } + + /// [`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); + } 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))) + } + + /// 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| 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 @@ -5363,10 +5411,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 +5473,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/analysis/src/warp.rs b/crates/analysis/src/warp.rs index 5c2c0b6736..7317c4afed 100644 --- a/crates/analysis/src/warp.rs +++ b/crates/analysis/src/warp.rs @@ -524,6 +524,31 @@ 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) +} + +/// The bounds `[min x, min y, max x, max y]` in `crs` of `shapes`' vertices held in `from`, each +/// placed as [`rasterize_in`] places it (by the direct operation between two datums), so a grid +/// over them holds what it burns; `None` when none can be placed. Cancel is looked at every few +/// thousand vertices. +pub fn placed_bounds(from: Crs, crs: Crs, shapes: &[Shape]) -> 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. +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 +560,8 @@ pub fn rasterize(g: &Grid, shapes: &[Shape], nodata: f32) -> Result Result 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 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( @@ -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 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) @@ -453,23 +453,16 @@ fn report_resampled_classes(s: &mut Session, source: &Raster, out: &Raster, meth /// The largest whole number a raster's 32-bit float pixels hold exactly. const EXACT_WHOLE: f64 = 16_777_216.0; -/// The conversion of a layer's own coordinates to longitude/latitude, for polygons read one by -/// one ([`rasterops::transform_feature_polygons_to_lonlat`]): none while they are -/// longitude/latitude, as they are unless the layer holds another system. The same operation -/// as [`rustgis_data::Dataset::lonlat_conversion`]'s: a conversion to longitude/latitude is the -/// system's own, never a direct one between two others. -fn held_transformer(ds: &rustgis_data::Dataset) -> 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 /// for a text field a table of its codes. +/// +/// 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}'"))?; @@ -504,12 +497,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 +566,55 @@ 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 held_bounds = 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 mut unsized_by = 0usize; + let grid = grid_param(s, p, crs, |crs| { + 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)); + } + // 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; + // 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 { + rustgis_data::progress::check().map_err(|e| e.to_string())?; + } + match to.point(*c) { + Some(c) => lonlat.expand(c), + None => unsized_by += 1, + } + } + 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(q) = warp::placed_bounds(held, crs, &shapes).map_err(|e| format!("{ln}: {e}"))? + { + b = [b[0].min(q[0]), b[1].min(q[1]), b[2].max(q[2]), b[3].max(q[3])]; + } + Ok((b, None)) + })?; + 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: 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 { "its" } else { "their" } + ), + 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) { @@ -588,7 +624,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).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")); } @@ -1033,10 +1069,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).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")?); @@ -1045,34 +1081,32 @@ 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, 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); 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()) + 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 -/// 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, 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 +1121,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,7 +1143,8 @@ pub(crate) enum ZonesAhead { #[cfg(not(target_arch = "wasm32"))] pub(crate) struct ZoneMeans { raster: Arc, - rings: Vec>, + crs: Crs, + rings: Vec>>, means: Result, usize)>, String>, } @@ -1254,12 +1290,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,9 +1322,11 @@ pub(crate) fn process_work(s: &Session, p: &Value) -> Result 0 { diff --git a/crates/engine/src/tests/held_layers.rs b/crates/engine/src/tests/held_layers.rs index 9f12c055b8..50ed50048c 100644 --- a/crates/engine/src/tests/held_layers.rs +++ b/crates/engine/src/tests/held_layers.rs @@ -647,12 +647,18 @@ fn camera_over_parcels(projection: &str) -> 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,161 @@ 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}"); +} + +/// 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; 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 { + [(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}"); + // 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 +/// 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 +/// 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 = "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(); + 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:?}"); +} + +/// 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. +#[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:?}"); +} diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index b45412c83f..2526de3a10 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 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 + 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