diff --git a/crates/analysis/src/rasterops.rs b/crates/analysis/src/rasterops.rs index 3fe4c2968e..8bfd6d5a58 100644 --- a/crates/analysis/src/rasterops.rs +++ b/crates/analysis/src/rasterops.rs @@ -1030,17 +1030,16 @@ pub fn parse_bands_str(s: &str, total_bands: usize) -> Result, String } /// Projects a complete ring to the raster grid without dropping failed vertices. -fn project_ring(r: &Raster, ring: &[Coord]) -> Option> { +fn project_ring(tr: &Transformer, t: &GeoTransform, ring: &[Coord]) -> Option> { if ring.len() < 3 { return None; } - let tr = r.transformer(); ring.iter() .map(|&c| { if !c.is_finite() { return None; } - let pt = r.transform.to_pixel(tr.from_lonlat(c)?); + let pt = t.to_pixel(tr.from_lonlat(c)?); (pt.0.is_finite() && pt.1.is_finite()).then_some(pt) }) .collect() @@ -1065,76 +1064,159 @@ pub fn polygon_mask_with_failures( polygons: &[Vec>], failed_parts: &mut Vec, ) -> Result, Range, Vec)>, String> { - let projected: Vec>> = polygons - .iter() - .enumerate() - .filter_map(|(index, rings)| { - // Reject a complete part if any ring fails, so a lost hole cannot enlarge it. - let part = if rings.is_empty() { None } else { rings.iter().map(|ring| project_ring(r, ring)).collect::>>() }; - if part.is_none() { - failed_parts.push(index); - } - part - }) - .collect(); - let (mut c0, mut r0, mut c1, mut r1) = (f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY); - for &(x, y) in projected.iter().flatten().flatten() { - (c0, r0, c1, r1) = (c0.min(x), r0.min(y), c1.max(x), r1.max(y)); - } - if !(c0.is_finite() && r0.is_finite() && c1.is_finite() && r1.is_finite()) { + polygon_mask_on(r.transformer(), &r.transform, (r.width, r.height), polygons, failed_parts) +} + +/// [`polygon_mask_with_failures`] on a grid of `size` (columns, rows) cells placed by `t` in the +/// coordinate system of `tr`, with no raster on it yet. +pub(crate) fn polygon_mask_on( + tr: &Transformer, + t: &GeoTransform, + size: (u32, u32), + polygons: &[Vec>], + failed_parts: &mut Vec, +) -> Result, Range, Vec)>, String> { + let Some(placed) = Placed::new(tr, t, size, polygons, failed_parts) else { return Ok(None) }; + let (cols, rows) = (placed.cols.clone(), placed.rows.clone()); + let (w, h) = ((cols.end - cols.start) as usize, (rows.end - rows.start) as usize); + let mut mask = new_band(w, h, false)?; + // Trimmed to the cells inside: reprojected vertices on cell edges land a hair either side. + let (mut tc0, mut tr0, mut tc1, mut tr1) = (usize::MAX, usize::MAX, 0, 0); + placed.spans(|row, span| { + let rr = (row - rows.start) as usize; + let (c0, c1) = ((span.start - cols.start) as usize, (span.end - cols.start) as usize); + if let Some(cells) = mask.get_mut(rr * w + c0..rr * w + c1) { + cells.fill(true); + } + (tc0, tr0, tc1, tr1) = (tc0.min(c0), tr0.min(rr), tc1.max(c1), tr1.max(rr + 1)); + }); + if tc0 >= tc1 || tr0 >= tr1 { return Ok(None); } - let clamp = |v: f64, n: u32| v.clamp(0.0, f64::from(n)) as u32; - let cols = clamp(c0.floor(), r.width)..clamp(c1.ceil(), r.width); - let rows = clamp(r0.floor(), r.height)..clamp(r1.ceil(), r.height); - if cols.is_empty() || rows.is_empty() { - return Ok(None); + if (tc0, tr0, tc1, tr1) == (0, 0, w, h) { + return Ok(Some((cols, rows, mask))); } - let w = (cols.end - cols.start) as usize; - let mut mask = new_band(w, (rows.end - rows.start) as usize, false)?; - let mut xs: Vec = Vec::new(); - for (ri, row) in rows.clone().enumerate() { - let y = f64::from(row) + 0.5; - let line = mask.get_mut(ri * w..(ri + 1) * w).unwrap_or_default(); - // Even-odd within each polygon (holes cut out), any polygon over the others. - for rings in &projected { - xs.clear(); + let mut trimmed = grid(tc1 - tc0, tr1 - tr0)?; + for rr in tr0..tr1 { + trimmed.extend_from_slice(mask.get(rr * w + tc0..rr * w + tc1).unwrap_or_default()); + } + let cols = cols.start + tc0 as u32..cols.start + tc1 as u32; + let rows = rows.start + tr0 as u32..rows.start + tr1 as u32; + Ok(Some((cols, rows, trimmed))) +} + +/// Polygons (each an exterior ring and its holes, in longitude/latitude) projected to a grid's +/// pixels, with the window of the grid around them. +pub(crate) struct Placed { + parts: Vec>>, + width: u32, + cols: Range, + rows: Range, +} + +/// An edge of a ring, from `a` to `b` in pixels, crossing the centres of rows `first..end`. +#[derive(Clone, Copy)] +struct Edge { + first: u32, + end: u32, + a: (f64, f64), + b: (f64, f64), +} + +impl Placed { + /// `None` when no polygon can be placed or none reaches the grid of `size` (columns, rows). + /// The zero-based indices of the rejected parts are appended to `failed_parts`. + pub(crate) fn new( + tr: &Transformer, + t: &GeoTransform, + size: (u32, u32), + polygons: &[Vec>], + failed_parts: &mut Vec, + ) -> Option { + let (width, height) = size; + let parts: Vec>> = polygons + .iter() + .enumerate() + .filter_map(|(index, rings)| { + // Reject a complete part if any ring fails, so a lost hole cannot enlarge it. + let part = + if rings.is_empty() { None } else { rings.iter().map(|ring| project_ring(tr, t, ring)).collect::>>() }; + if part.is_none() { + failed_parts.push(index); + } + part + }) + .collect(); + let (mut c0, mut r0, mut c1, mut r1) = (f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY); + for &(x, y) in parts.iter().flatten().flatten() { + (c0, r0, c1, r1) = (c0.min(x), r0.min(y), c1.max(x), r1.max(y)); + } + if !(c0.is_finite() && r0.is_finite() && c1.is_finite() && r1.is_finite()) { + return None; + } + let clamp = |v: f64, n: u32| v.clamp(0.0, f64::from(n)) as u32; + let cols = clamp(c0.floor(), width)..clamp(c1.ceil(), width); + let rows = clamp(r0.floor(), height)..clamp(r1.ceil(), height); + (!cols.is_empty() && !rows.is_empty()).then_some(Self { parts, width, cols, rows }) + } + + /// Calls `span` with each row's runs of cells whose centres lie inside a polygon: even-odd + /// within each polygon (holes cut out), so polygons that overlap may give a cell twice. Each + /// edge is visited only on the rows it crosses, so a polygon's edges cost by their length + /// on the grid, not by the rows times all the edges. + pub(crate) fn spans(&self, mut span: impl FnMut(u32, Range)) { + let clamp = |v: f64| v.clamp(0.0, f64::from(self.width)) as u32; + let (mut edges, mut active, mut xs) = (Vec::new(), Vec::new(), Vec::new()); + for rings in &self.parts { + edges.clear(); for ring in rings { - for (i, &(ax, ay)) in ring.iter().enumerate() { - let (bx, by) = ring.get(i + 1).or(ring.first()).copied().unwrap_or((ax, ay)); - if (ay <= y) != (by <= y) { - xs.push(ax + (y - ay) * (bx - ax) / (by - ay)); + for (i, &a) in ring.iter().enumerate() { + let b = ring.get(i + 1).or(ring.first()).copied().unwrap_or(a); + let (first, end) = (first_row_from(a.1.min(b.1), &self.rows), first_row_from(a.1.max(b.1), &self.rows)); + if first < end { + edges.push(Edge { first, end, a, b }); } } } - xs.sort_by(f64::total_cmp); - for &[x0, x1] in xs.as_chunks::<2>().0 { - // Cells whose centre (col + 0.5) lies in [x0, x1). - let a = clamp((x0 - 0.5).ceil(), r.width).max(cols.start); - let b = clamp((x1 - 0.5).ceil(), r.width).min(cols.end); - for col in a..b { - if let Some(m) = line.get_mut((col - cols.start) as usize) { - *m = true; + edges.sort_unstable_by_key(|e: &Edge| e.first); + let (Some(start), Some(stop)) = (edges.first().map(|e| e.first), edges.iter().map(|e| e.end).max()) else { continue }; + let mut waiting = edges.iter().copied().peekable(); + active.clear(); + for row in start..stop { + while let Some(e) = waiting.next_if(|e| e.first == row) { + active.push(e); + } + active.retain(|e: &Edge| e.end > row); + let y = f64::from(row) + 0.5; + xs.clear(); + xs.extend(active.iter().map(|e| e.a.0 + (y - e.a.1) * (e.b.0 - e.a.0) / (e.b.1 - e.a.1))); + xs.sort_by(f64::total_cmp); + for &[x0, x1] in xs.as_chunks::<2>().0 { + // Cells whose centre (col + 0.5) lies in [x0, x1). + let a = clamp((x0 - 0.5).ceil()).max(self.cols.start); + let b = clamp((x1 - 0.5).ceil()).min(self.cols.end); + if a < b { + span(row, a..b); } } } } } - // Trimmed to the cells inside: reprojected vertices on cell edges land a hair either side. - let (mut tc0, mut tr0, mut tc1, mut tr1) = (usize::MAX, usize::MAX, 0, 0); - for (i, _) in mask.iter().enumerate().filter(|(_, m)| **m) { - let (c, rr) = (i % w, i / w); - (tc0, tr0, tc1, tr1) = (tc0.min(c), tr0.min(rr), tc1.max(c + 1), tr1.max(rr + 1)); +} + +/// The first of `rows` whose centre (row + 0.5) is at or past `v`, or the end of them. An edge +/// crosses a row's centre when its lower end is at or before it and its upper end past it. +fn first_row_from(v: f64, rows: &Range) -> u32 { + let centre = |r: u32| f64::from(r) + 0.5; + let mut r = (v - 0.5).ceil().clamp(f64::from(rows.start), f64::from(rows.end)) as u32; + // `v - 0.5` can round far from zero. + while r > rows.start && centre(r - 1) >= v { + r -= 1; } - if tc0 >= tc1 || tr0 >= tr1 { - return Ok(None); + while r < rows.end && centre(r) < v { + r += 1; } - let mut trimmed = grid(tc1 - tc0, tr1 - tr0)?; - trimmed - .extend((tr0..tr1).flat_map(|rr| (tc0..tc1).map(move |c| (rr, c))).map(|(rr, c)| mask.get(rr * w + c).copied().unwrap_or(false))); - let cols = cols.start + tc0 as u32..cols.start + tc1 as u32; - let rows = rows.start + tr0 as u32..rows.start + tr1 as u32; - Ok(Some((cols, rows, trimmed))) + r } /// Summary statistics of raster cells within a zone. @@ -1683,6 +1765,85 @@ mod tests { assert!(polygon_mask(&r, &[vec![sq(0.0051, 0.0051, 0.0052, 0.0052)]]).unwrap().is_none()); } + /// The mask equals one found the plain way, every edge on every row, for polygons of many + /// shapes: holes, several parts, edges on cell edges, crossing themselves, past the grid. + #[test] + fn polygon_mask_matches_a_scan_of_every_edge_on_every_row() { + let plain = |parts: &[Vec>], width: u32, height: u32| { + let mut mask = vec![false; (width * height) as usize]; + for row in 0..height { + let y = f64::from(row) + 0.5; + for rings in parts { + let mut xs = Vec::new(); + for ring in rings { + for (i, &(ax, ay)) in ring.iter().enumerate() { + let (bx, by) = ring.get(i + 1).or(ring.first()).copied().unwrap_or((ax, ay)); + if (ay <= y) != (by <= y) { + xs.push(ax + (y - ay) * (bx - ax) / (by - ay)); + } + } + } + xs.sort_by(f64::total_cmp); + for &[x0, x1] in xs.as_chunks::<2>().0 { + let at = |x: f64| (x - 0.5).ceil().clamp(0.0, f64::from(width)) as u32; + for col in at(x0)..at(x1) { + mask[(row * width + col) as usize] = true; + } + } + } + } + mask + }; + let (width, height) = (60u32, 40u32); + let g = crate::warp::Grid { crs: Crs::LonLat, min_x: 0.0, max_y: 40.0, cell_x: 1.0, cell_y: 1.0, width: 60, height: 40 }; + let t = g.transform(); + let tr = Crs::LonLat.transformer().unwrap(); + let mut state = 0x2545_F491_4F6C_DD1D_u64; + let mut next = move |n: f64| { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + (state >> 11) as f64 / (1u64 << 53) as f64 * n + }; + for case in 0..400 { + let mut polygons = Vec::new(); + for _ in 0..1 + case % 3 { + let mut rings = Vec::new(); + for _ in 0..1 + case % 2 { + let mut ring: Vec = (0..3 + case % 9) + .map(|_| { + // Whole numbers land on cell edges, halves on cell centres; the range + // goes past the grid. + let (x, y) = (next(80.0) - 10.0, next(60.0) - 10.0); + match case % 4 { + 0 => Coord::new(x.floor(), y.floor()), + 1 => Coord::new(x.floor() + 0.5, y.floor() + 0.5), + _ => Coord::new(x, y), + } + }) + .collect(); + ring.push(ring[0]); + rings.push(ring); + } + polygons.push(rings); + } + let found = polygon_mask_on(&tr, &t, (width, height), &polygons, &mut Vec::new()).unwrap(); + let parts: Vec>> = + polygons.iter().map(|rings| rings.iter().map(|ring| project_ring(&tr, &t, ring).unwrap()).collect()).collect(); + let want = plain(&parts, width, height); + let mut got = vec![false; want.len()]; + if let Some((cols, rows, mask)) = found { + let w = (cols.end - cols.start) as usize; + assert_eq!(mask.len(), w * (rows.end - rows.start) as usize); + for (i, inside) in mask.iter().enumerate() { + let (c, r) = (cols.start as usize + i % w, rows.start as usize + i / w); + got[r * width as usize + c] = *inside; + } + } + assert_eq!(got, want, "case {case}"); + } + } + /// A failed hole drops only its containing part and reports that part, even with no mask. #[test] fn polygon_mask_reports_rejected_parts_and_retains_valid_parts() { diff --git a/crates/analysis/src/warp.rs b/crates/analysis/src/warp.rs index b28ffe3452..910c14c319 100644 --- a/crates/analysis/src/warp.rs +++ b/crates/analysis/src/warp.rs @@ -379,7 +379,7 @@ impl Grid { } /// The top left corner's transform. - fn transform(&self) -> GeoTransform { + pub fn transform(&self) -> GeoTransform { GeoTransform { origin_x: self.min_x, origin_y: self.max_y, pixel_width: self.cell_x, pixel_height: -self.cell_y } } } @@ -487,6 +487,83 @@ fn project_on(threads: Option, r: &Raster, g: &Grid, method: Method, name } } +/// A polygon [`rasterize`] burns: its parts, each an exterior ring and its holes in +/// longitude/latitude, and the value its cells take. +#[derive(Clone, Debug, PartialEq)] +pub struct Shape { + pub parts: Vec>>, + pub value: f32, +} + +/// What [`rasterize`] made. +#[derive(Clone, Debug, PartialEq)] +pub struct Burned { + /// The band, row by row. + pub data: Vec, + /// The cells that took a value. + pub cells: usize, + /// The shapes that held a cell centre. + pub burned: usize, + /// The shapes with a part that couldn't be placed on the grid (their other parts are burned). + pub unplaced: Vec, + /// The shapes, all of them placed, that hold no cell centre: narrower than a cell, or off the grid. + pub missed: usize, +} + +/// Burns `shapes` onto `g` as one band: a cell whose centre falls inside a shape (its holes cut +/// out) takes the shape's value, a later shape over an earlier one, as GDAL burns; a cell under +/// none is `nodata`. Each shape is filled by scanline on the rows it crosses (as +/// [`crate::rasterops::polygon_mask`]), so a polygon narrower than a cell may hold no cell centre +/// and be missed (and counted). The band is held, 4 bytes a cell, and one shape's edges. A shape +/// whose value is `nodata` is refused: its cells couldn't be told from those under none. The time +/// 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 { + 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); + if g.width.checked_mul(g.height).is_none_or(|n| n > max) { + return Err(too_big()); + } + if shapes.iter().any(|s| s.value == nodata || (s.value.is_nan() && nodata.is_nan())) { + return Err("a shape's value is the no-data value: give another nodata".into()); + } + let size = (u32::try_from(g.width).map_err(|_| too_big())?, u32::try_from(g.height).map_err(|_| too_big())?); + let tr = g.crs.transformer()?; + let t = g.transform(); + let mut data = crate::rasterops::new_band(g.width, g.height, nodata)?; + let mut unplaced = Vec::new(); + let (mut burned, mut missed) = (0, 0); + let mut failed = Vec::new(); + crate::control::begin(shapes.len()); + for (i, shape) in shapes.iter().enumerate() { + crate::control::check()?; + crate::control::reached(i); + failed.clear(); + let placed = crate::rasterops::Placed::new(&tr, &t, size, &shape.parts, &mut failed); + if !failed.is_empty() { + unplaced.push(i); + } + let mut holds_a_cell = false; + if let Some(placed) = &placed { + placed.spans(|row, cols| { + let start = row as usize * g.width; + if let Some(cells) = data.get_mut(start + cols.start as usize..start + cols.end as usize) { + cells.fill(shape.value); + holds_a_cell = true; + } + }); + } + if holds_a_cell { + burned += 1; + } else { + missed += usize::from(failed.is_empty()); + } + } + let cells = data.iter().filter(|v| !(**v == nodata || (v.is_nan() && nodata.is_nan()))).count(); + Ok(Burned { data, cells, burned, unplaced, missed }) +} + /// How an output raster holds a source's bands. struct Canvas { /// The source's bands. @@ -1426,4 +1503,74 @@ mod tests { let b = bounds_in([-42.82, -5.12, -42.78, -5.08], utm23s).unwrap(); assert!((b[0] - bounds[0]).abs() < 1.0 && (b[3] - bounds[3]).abs() < 1.0, "{b:?} {bounds:?}"); } + + /// Burned by cell centre: holes cut out, a later shape over an earlier one, a sliver between + /// centres missed, a part that can't be placed reported, and a grid too large refused. + #[test] + fn rasterize_burns_by_cell_centre_with_holes_and_overlaps() { + let ring = |x0: f64, y0: f64, x1: f64, y1: f64| { + vec![Coord::new(x0, y0), Coord::new(x1, y0), Coord::new(x1, y1), Coord::new(x0, y1), Coord::new(x0, y0)] + }; + let g = Grid { crs: Crs::LonLat, min_x: 0.0, max_y: 10.0, cell_x: 1.0, cell_y: 1.0, width: 10, height: 10 }; + let shapes = [ + Shape { parts: vec![vec![ring(0.0, 0.0, 8.0, 8.0), ring(3.0, 3.0, 5.0, 5.0)]], value: 1.0 }, + Shape { parts: vec![vec![ring(5.0, 5.0, 7.0, 7.0)]], value: 2.0 }, + // Narrower than a cell, between two columns of centres. + Shape { parts: vec![vec![ring(8.6, 0.0, 8.9, 10.0)]], value: 3.0 }, + // One part placed, one not. + Shape { parts: vec![vec![ring(9.0, 9.0, 10.0, 10.0)], vec![vec![Coord::new(f64::NAN, 0.0); 4]]], value: 4.0 }, + ]; + let b = rasterize(&g, &shapes, -1.0).unwrap(); + let at = |x: f64, y: f64| b.data[(10.0 - y).floor() as usize * 10 + x.floor() as usize]; + assert_eq!((at(0.5, 0.5), at(7.5, 7.5), at(8.5, 8.5)), (1.0, 1.0, -1.0)); + assert_eq!((at(3.5, 3.5), at(4.5, 4.5)), (-1.0, -1.0), "the hole stays out"); + assert_eq!((at(5.5, 5.5), at(6.5, 6.5), at(4.5, 5.5)), (2.0, 2.0, 1.0), "the later shape wins where they overlap"); + assert!(!b.data.contains(&3.0) && (b.burned, b.missed) == (3, 1), "a sliver between cell centres is missed, and counted"); + assert_eq!((at(9.5, 9.5), b.unplaced.clone()), (4.0, vec![3])); + // 64 cells less the hole's 4, and the corner. + assert_eq!(b.cells, 64 - 4 + 1); + let huge = Grid { width: max_samples(), height: 2, ..g }; + assert!(rasterize(&huge, &shapes, -1.0).unwrap_err().contains("give a larger cellSize")); + } + + /// Two 1° squares on a 10 × 10 grid of 1° cells, valued `a` and `b`. + fn two_squares(a: f32, b: f32) -> (Grid, [Shape; 2]) { + let ring = |x0: f64, y0: f64, x1: f64, y1: f64| { + vec![Coord::new(x0, y0), Coord::new(x1, y0), Coord::new(x1, y1), Coord::new(x0, y1), Coord::new(x0, y0)] + }; + let g = Grid { crs: Crs::LonLat, min_x: 0.0, max_y: 10.0, cell_x: 1.0, cell_y: 1.0, width: 10, height: 10 }; + ( + g, + [ + Shape { parts: vec![vec![ring(0.0, 0.0, 1.0, 1.0)]], value: a }, + Shape { parts: vec![vec![ring(5.0, 5.0, 6.0, 6.0)]], value: b }, + ], + ) + } + + /// A shape valued as the no-data value is refused, a NaN one as NaN too: its cells couldn't be + /// told from those under none, and `cells` would leave them out. + #[test] + fn rasterize_refuses_a_shape_valued_as_no_data() { + let (g, shapes) = two_squares(1.0, -1.0); + assert!(rasterize(&g, &shapes, -1.0).unwrap_err().contains("no-data value")); + let (g, shapes) = two_squares(1.0, f32::NAN); + assert!(rasterize(&g, &shapes, f32::NAN).unwrap_err().contains("no-data value")); + // Any other value is burned and counted, under a NaN no-data value too. + let (g, shapes) = two_squares(1.0, 2.0); + assert_eq!((rasterize(&g, &shapes, -1.0).unwrap().cells, rasterize(&g, &shapes, f32::NAN).unwrap().cells), (2, 2)); + } + + /// A run under a control counts its shapes, and one cancelled stops with no band. + #[test] + fn rasterize_stops_when_cancelled_and_counts_its_shapes() { + let (g, shapes) = two_squares(1.0, 2.0); + let run = crate::control::Control::new(); + crate::run_under("Polygons to Raster", &run, || rasterize(&g, &shapes, -1.0)).unwrap(); + assert_eq!(run.progress(), Some((2, 2))); + let run = crate::control::Control::new(); + run.cancel(); + let _installed = crate::control::install(Some(run)); + assert_eq!(rasterize(&g, &shapes, -1.0).unwrap_err(), crate::control::CANCELLED); + } } diff --git a/crates/assistant/src/tests.rs b/crates/assistant/src/tests.rs index 17883012e9..ca9266a82a 100644 --- a/crates/assistant/src/tests.rs +++ b/crates/assistant/src/tests.rs @@ -364,6 +364,17 @@ fn gate_rules() { let mut file = project.clone(); file["path"] = json!("/tmp/x.tif"); assert!(g("run_command", json!({"command": "raster.project", "params": file})).is_some()); + // And rasterizing polygons. + let burn = json!({"layer": "Countries", "crs": 31983, "cellSize": 100}); + assert!(g("run_command", json!({"command": "raster.rasterize", "params": burn})).is_none()); + let mut file = burn.clone(); + file["path"] = json!("/tmp/x.tif"); + assert!(g("run_command", json!({"command": "raster.rasterize", "params": file})).is_some()); + // A null `path` is no path: no file is written. + for (command, mut params) in [("raster.georeference", pts), ("raster.project", project), ("raster.rasterize", burn)] { + params["path"] = Value::Null; + assert!(g("run_command", json!({"command": command, "params": params})).is_none(), "{command}"); + } } /// What a command says beside its result reaches the model (issue #85). diff --git a/crates/engine/src/cmd/imagery.rs b/crates/engine/src/cmd/imagery.rs index 0f7face0ff..a06df1919f 100644 --- a/crates/engine/src/cmd/imagery.rs +++ b/crates/engine/src/cmd/imagery.rs @@ -8,7 +8,7 @@ use rustgis_analysis::georef::{self, Gcp, Kind}; use rustgis_analysis::rasterops::{self, NODATA}; use rustgis_analysis::warp; use rustgis_data::raster::{self, ColorHint, Crs, GeoTransform, Raster}; -use rustgis_data::{Geometry, GeometryType}; +use rustgis_data::{FieldType, Geometry, GeometryType}; use rustgis_geom::{Coord, Extent}; use rustgis_map::RasterLayer; use serde::{Deserialize, Serialize}; @@ -44,6 +44,9 @@ pub fn commands() -> Vec { C::new("raster.project", "Project Raster", "Analyze › Alignment", project_raster).params( 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 › Alignment", rasterize).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}"#, + ), // A fit is a measurement of the points, not a project change: no undo step. C::new("raster.gcpFit", "Control Point Fit", "Analyze › Alignment", gcp_fit).view().params( r#"{"points": [[column, row, x, y, on?], …] (on: 1/0 or true/false, default on), "transform"?: "similarity"|"affine"|"projective"|"polynomial2"|"polynomial3"|"spline" (default: similarity under 3 points, else affine), "compare"?: bool (fit every transform and recommend one; transform and leaveOneOut are then ignored), "leaveOneOut"?: bool (default true)}"#, @@ -371,12 +374,272 @@ fn project_raster(s: &mut Session, p: &Value) -> CmdResult { None | Some(Value::Null) => warp::Method::Sample(warp::Resampling::Nearest), Some(v) => v.as_str().and_then(warp::Method::parse).ok_or("resampling is nearest, bilinear, cubic, average or mode")?, }; + let grid = grid_param(s, p, r.crs, |crs| warp::footprint_in(&r, crs).map(|(bounds, pixel)| (bounds, Some(pixel))))?; + let path = tif_path(p)?; + let out_name = name(p, format!("{} projected", r.name)); + let out = warp::project(&r, &grid, method, out_name.clone())?; + let mut info = json!({ + "name": out_name, "crs": grid.crs.label(), "resampling": method.used_on(&r).id(), "width": out.width, "height": out.height, "bands": out.band_count(), + "cellSize": [grid.cell_x, grid.cell_y], "corner": [grid.min_x, grid.max_y], + }); + if let Some((fw, fh)) = r.overview { + let note = + format!("{}: projected at reduced resolution, from its {} × {} overview of the {fw} × {fh} raster", r.name, r.width, r.height); + s.notify(note, false); + info["projectedFromOverview"] = json!({"width": r.width, "height": r.height, "of": [fw, fh]}); + } + add_output(s, out, path, false, info) +} + +/// The largest whole number a raster's 32-bit float pixels hold exactly. +const EXACT_WHOLE: f64 = 16_777_216.0; + +/// `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. +fn rasterize(s: &mut Session, p: &Value) -> CmdResult { + let ln = ps(p, "layer").ok_or("layer is required: a polygon layer")?; + let l = s.map().layer_by_name(ln).filter(|l| l.raster.is_none()).ok_or_else(|| format!("no vector layer '{ln}'"))?; + let ds = &l.dataset; + if ds.geometry_type != GeometryType::Polygon { + return Err(format!("{ln} is not a polygon layer")); + } + if ds.windowed { + return Err(format!("{ln}: load all its features first (Layers › Load All Features)")); + } + // What a polygon gives: a field's value (the field and its type), or one value. + let (field, value) = match (p.get("field").filter(|v| !v.is_null()), p.get("value").filter(|v| !v.is_null())) { + (Some(_), Some(_)) => return Err("give a field or a value, not both".into()), + (Some(f), None) => { + let f = f.as_str().ok_or("field is a field's name")?; + let i = ds.field_index(f).ok_or_else(|| format!("{ln}: no field '{f}'"))?; + let ty = ds.fields.get(i).map(|f| f.ty).ok_or_else(|| format!("{ln}: no field '{f}'"))?; + (Some((i, ty)), 1.0) + } + (None, Some(v)) => (None, v.as_f64().filter(|v| v.is_finite() && v.abs() <= f64::from(f32::MAX)).ok_or("value is a number")?), + (None, None) => (None, 1.0), + }; + let nodata = match p.get("nodata") { + None | Some(Value::Null) => 0.0, + Some(v) => v.as_f64().filter(|v| v.is_finite() && v.abs() <= f64::from(f32::MAX)).ok_or("nodata is a number")?, + }; + let path = tif_path(p)?; + let out_name = name(p, format!("{ln} raster")); + // The features burned: the selection, else all, in the layer's order (a later one wins). + let mut rows: Vec = if l.selection.is_empty() { (0..ds.features.len()).collect() } else { l.selection.clone() }; + rows.sort_unstable(); + rows.dedup(); + let (mut no_value, mut no_polygon) = (0, 0); + let mut burns: Vec<(Vec>>, rustgis_data::Value)> = Vec::new(); + 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, None).ok(), + _ => None, + }; + let Some(parts) = parts else { + no_polygon += 1; + continue; + }; + let v = match field { + Some((i, _)) => ds.value(row, i).clone(), + None => rustgis_data::Value::Float(value), + }; + burns.push((parts, v)); + } + // A text field's values become codes 1 to n, in sorted order. + let text = field.is_some_and(|(_, ty)| ty == FieldType::Text); + let classes: Vec = if text { + let set: std::collections::BTreeSet = burns.iter().filter_map(|(_, v)| text_of(v)).collect(); + set.into_iter().collect() + } else { + Vec::new() + }; + // Whole numbers: codes, one value, or a field that isn't a floating-point one. + let whole_field = field.is_none_or(|(_, ty)| ty != FieldType::Double); + let what = field.and_then(|(i, _)| ds.fields.get(i)).map_or("value", |f| f.name.as_str()).to_string(); + let mut shapes = Vec::with_capacity(burns.len()); + let mut rounded = 0; + for (parts, v) in burns { + let x = if text { text_of(&v).and_then(|t| classes.binary_search(&t).ok()).map(|i| i as f64 + 1.0) } else { v.as_f64() }; + let Some(x) = x else { + no_value += 1; + continue; + }; + if x.abs() > f64::from(f32::MAX) { + return Err(format!("{ln}: {what} {x} is past the range of a raster's 32-bit pixels")); + } + if whole_field && x.fract() == 0.0 && x.abs() > EXACT_WHOLE { + // Only a numeric field's numbers can be given as text instead. + let hint = if field.is_some() && !text { "; a text field gives codes instead" } else { "" }; + return Err(format!("{ln}: {what} {x} is more than a raster's pixels hold exactly ({EXACT_WHOLE}){hint}")); + } + // As a pixel holds them: a value that rounds to the no-data value would be lost. + if x as f32 == nodata as f32 { + let of = if text { format!(", the code of {:?},", text_of(&v).unwrap_or_default()) } else { String::new() }; + return Err(format!("{ln}: {what} {x}{of} is the no-data value: give another nodata")); + } + rounded += usize::from(f64::from(x as f32) != x); + shapes.push(warp::Shape { parts, value: x as f32 }); + } + 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| { + 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)))?; + // 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) { + "UInt8" + } else if whole(65_535.0) { + "UInt16" + } else { + "Float32" + }; + let burned = warp::rasterize(&grid, &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")); + } + let (w, h) = (u32::try_from(grid.width).map_err(|e| e.to_string())?, u32::try_from(grid.height).map_err(|e| e.to_string())?); + let out = Raster::new(&out_name, w, h, vec![burned.data], grid.transform(), grid.crs, Some(nodata), ColorHint::Gray, data_type) + .map_err(|e| e.to_string())?; + let mut info = json!({ + "name": out_name, "crs": grid.crs.label(), "width": out.width, "height": out.height, "dataType": data_type, "nodata": nodata, + "cellSize": [grid.cell_x, grid.cell_y], "corner": [grid.min_x, grid.max_y], "features": burned.burned, "cells": burned.cells, + }); + if rounded > 0 { + s.notify(format!("{ln}: {rounded} value(s) of {what} rounded to the raster's 32-bit pixels"), false); + } + let skipped = [("noValue", no_value), ("noPolygon", no_polygon), ("unplaced", burned.unplaced.len()), ("noCell", burned.missed)]; + if skipped.iter().any(|(_, n)| *n > 0) { + info["skipped"] = + skipped.iter().filter(|(_, n)| *n > 0).map(|(k, n)| (k.to_string(), json!(n))).collect::>().into(); + let mut why = Vec::new(); + if no_value > 0 { + why.push(format!("{no_value} with no value")); + } + if no_polygon > 0 { + why.push(format!("{no_polygon} with no valid polygon")); + } + if !burned.unplaced.is_empty() { + why.push(format!("{} with a part that can't be placed on the grid (any other parts were burned)", burned.unplaced.len())); + } + if burned.missed > 0 { + why.push(format!("{} that hold no cell centre (narrower than a cell, or off the grid)", burned.missed)); + } + s.notify(format!("{ln}: features skipped: {}", why.join(", ")), false); + } + // Whole numbers few enough to list are classes, drawn with unique values. + let distinct = out.bands.first().is_some_and(|b| b.stats.categories.is_some()); + let mut info = add_output(s, out, path, whole_field && distinct, info)?; + if text { + let layer = info.get("name").and_then(Value::as_str).unwrap_or(&out_name).to_string(); + let mut table = rustgis_data::Dataset::new( + free_table_name(s, &format!("{layer} classes")), + GeometryType::None, + vec![rustgis_data::Field::new("code", FieldType::Integer), rustgis_data::Field::new("value", FieldType::Text)], + ); + for (i, c) in classes.iter().enumerate() { + table.push_next(None, vec![rustgis_data::Value::Int(i as i64 + 1), rustgis_data::Value::Text(c.clone())]); + } + info["classTable"] = json!(table.name); + s.project.add_table(table); + info["classCount"] = json!(classes.len()); + // All the codes are in the table; here, as many as a unique-value legend shows. + info["classes"] = classes.iter().take(256).enumerate().map(|(i, c)| json!({"code": i + 1, "value": c})).collect(); + } + Ok(info) +} + +/// `base`, or `base (2)`, `base (3)`… : the first no table of the project has (whatever its case). +fn free_table_name(s: &Session, base: &str) -> String { + let taken = |n: &str| s.project.tables.iter().any(|t| t.name.eq_ignore_ascii_case(n)); + let mut name = base.to_string(); + let mut i = 1; + while taken(&name) { + i += 1; + name = format!("{base} ({i})"); + } + name +} + +/// A text field's value, `None` for null or blank. +fn text_of(v: &rustgis_data::Value) -> Option { + let t = match v { + rustgis_data::Value::Null => return None, + rustgis_data::Value::Text(t) => t.clone(), + rustgis_data::Value::Int(i) => i.to_string(), + rustgis_data::Value::Float(f) => f.to_string(), + rustgis_data::Value::Bool(b) => b.to_string(), + }; + (!t.trim().is_empty()).then_some(t) +} + +/// A `path` to write a GeoTIFF to, if one is given. +fn tif_path(p: &Value) -> Result, String> { + match p.get("path") { + None | Some(Value::Null) => Ok(None), + Some(v) => Ok(Some(v.as_str().filter(|t| is_tif(t)).ok_or("path is a *.tif or *.tiff file")?.to_string())), + } +} + +/// Adds `out` as a new layer, its classes drawn with unique values when `classes`; with a `path`, +/// written there first as a cloud-optimised GeoTIFF, which becomes the layer's source. `info`, +/// with the extent, the file and the name the layer got, is the result. +fn add_output(s: &mut Session, out: Raster, path: Option, classes: bool, mut info: Value) -> CmdResult { + let out_name = out.name.clone(); + let e = out.extent(); + info["extent"] = json!([e.min_x, e.min_y, e.max_x, e.max_y]); + // A file written is the layer's source; without one the pixels are kept in the project. + let mut rl = match &path { + Some(path) => { + let cog = + rustgis_data::raster::cogwrite::write_file(&out, 0, std::path::Path::new(path)).map_err(|e| format!("{path}: {e}"))?; + info["path"] = json!(path); + info["cog"] = json!({"overviews": cog.levels.len().saturating_sub(1), "bigTiff": cog.big, "bytes": cog.bytes}); + RasterLayer::from_path(out, path.clone()) + } + None => layer_of(out)?, + }; + if classes && let Some(d) = rl.data.clone() { + rl.style.renderer = rustgis_map::raster::unique_values(&d, 0, rustgis_map::Ramp::Harbour); + } + let v = super::raster::add_raster(s, &out_name, rl)?; + if let (Some(o), Some(i)) = (info.as_object_mut(), v.as_object()) { + for (k, val) in i { + o.entry(k.clone()).or_insert_with(|| val.clone()); + } + } + // The name the layer got (another may hold the one asked for: "… projected (2)"). + let id = v.get("layer").and_then(Value::as_u64).and_then(|id| u32::try_from(id).ok()); + if let Some(name) = id.and_then(|id| s.map().layer(id)).map(|l| l.name.clone()) { + info["name"] = json!(name); + } + Ok(info) +} + +/// The grid of `raster.project` and `raster.rasterize`: another raster's (`grid`), taken exactly, +/// or one of `crs` (by default `crs`), `cellSize`, `origin` and `extent`. `natural` gives, in the +/// grid's system, the bounds taken without an extent and the cell size taken without a cellSize +/// (`None`: a cellSize is required). +fn grid_param( + s: &mut Session, + p: &Value, + crs: Crs, + natural: impl FnOnce(Crs) -> Result<([f64; 4], Option), String>, +) -> Result { // A grid named as anything but a raster layer's name is refused rather than ignored. let template = match p.get("grid") { None | Some(Value::Null) => None, Some(v) => Some(v.as_str().ok_or("grid is a raster layer's name")?), }; - let grid = match template { + Ok(match template { Some(template) => { if ["crs", "cellSize", "origin", "extent"].iter().any(|k| p.get(*k).is_some_and(|v| !v.is_null())) { return Err( @@ -385,15 +648,20 @@ fn project_raster(s: &mut Session, p: &Value) -> CmdResult { } let t = raster_named(s, template)?; t.require_coordinates()?; + if let Some((fw, fh)) = t.overview { + s.notify(format!("{template}: the grid is its {} × {} overview's, of the {fw} × {fh} raster", t.width, t.height), false); + } warp::Grid::of(&t) } None => { - let crs = crs_param(p, "crs")?.unwrap_or(r.crs); - let (footprint, pixel) = warp::footprint_in(&r, crs)?; + let crs = crs_param(p, "crs")?.unwrap_or(crs); + let (footprint, pixel) = natural(crs)?; let positive = |v: &Value| v.as_f64().filter(|c| c.is_finite() && *c > 0.0); let bad_cell = "cellSize is a positive number, or [x, y], in the output's units"; let cell = match p.get("cellSize") { - None | Some(Value::Null) => (pixel, pixel), + None | Some(Value::Null) => { + pixel.map(|c| (c, c)).ok_or("cellSize is required: a number, or [x, y], in the output's units, or a grid")? + } Some(Value::Array(a)) => match a.as_slice() { [x, y] => (positive(x).ok_or(bad_cell)?, positive(y).ok_or(bad_cell)?), _ => return Err(bad_cell.into()), @@ -438,48 +706,7 @@ fn project_raster(s: &mut Session, p: &Value) -> CmdResult { }; warp::Grid::snapped(crs, bounds, cell, origin)? } - }; - let path = match p.get("path") { - None | Some(Value::Null) => None, - Some(v) => Some(v.as_str().filter(|t| is_tif(t)).ok_or("path is a *.tif or *.tiff file")?.to_string()), - }; - let out_name = name(p, format!("{} projected", r.name)); - let out = warp::project(&r, &grid, method, out_name.clone())?; - let mut info = json!({ - "name": out_name, "crs": grid.crs.label(), "resampling": method.used_on(&r).id(), "width": out.width, "height": out.height, "bands": out.band_count(), - "cellSize": [grid.cell_x, grid.cell_y], "corner": [grid.min_x, grid.max_y], - }); - if let Some((fw, fh)) = r.overview { - let note = - format!("{}: projected at reduced resolution, from its {} × {} overview of the {fw} × {fh} raster", r.name, r.width, r.height); - s.notify(note, false); - info["projectedFromOverview"] = json!({"width": r.width, "height": r.height, "of": [fw, fh]}); - } - let e = out.extent(); - info["extent"] = json!([e.min_x, e.min_y, e.max_x, e.max_y]); - // A file written is the layer's source; without one the pixels are kept in the project. - let rl = match &path { - Some(path) => { - let cog = - rustgis_data::raster::cogwrite::write_file(&out, 0, std::path::Path::new(path)).map_err(|e| format!("{path}: {e}"))?; - info["path"] = json!(path); - info["cog"] = json!({"overviews": cog.levels.len().saturating_sub(1), "bigTiff": cog.big, "bytes": cog.bytes}); - RasterLayer::from_path(out, path.clone()) - } - None => layer_of(out)?, - }; - let v = super::raster::add_raster(s, &out_name, rl)?; - if let (Some(o), Some(i)) = (info.as_object_mut(), v.as_object()) { - for (k, val) in i { - o.entry(k.clone()).or_insert_with(|| val.clone()); - } - } - // The name the layer got (another may hold the one asked for: "… projected (2)"). - let id = v.get("layer").and_then(Value::as_u64).and_then(|id| u32::try_from(id).ok()); - if let Some(name) = id.and_then(|id| s.map().layer(id)).map(|l| l.name.clone()) { - info["name"] = json!(name); - } - Ok(info) + }) } fn is_tif(path: &str) -> bool { diff --git a/crates/engine/src/cmd/plugins.rs b/crates/engine/src/cmd/plugins.rs index 2a6e156732..979fdb06eb 100644 --- a/crates/engine/src/cmd/plugins.rs +++ b/crates/engine/src/cmd/plugins.rs @@ -382,10 +382,14 @@ pub fn reaches(spec: &C, params: &Value) -> Option { if DATABASES.contains(&spec.id) { return Some(Reach::Files); } - // Georeferencing and projecting write a file only when given a `path`; the rest of them stays - // in the project. - if spec.id == "raster.georeference" || spec.id == "raster.project" { - return super::items::names_place(params, PLACE_KEYS, 0).then_some(Reach::Files); + // Georeferencing, projecting and rasterizing write a file only when given a `path` (they read + // a null one as none); the rest of them stays in the project. + if ["raster.georeference", "raster.project", "raster.rasterize"].contains(&spec.id) { + let mut given = params.clone(); + if let Some(o) = given.as_object_mut() { + o.retain(|_, v| !v.is_null()); + } + return super::items::names_place(&given, PLACE_KEYS, 0).then_some(Reach::Files); } // A built-in tool's output layer name stays in the session, as it does in a task. let params = super::items::layer_name_left_out(spec.id, params); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index c02e457b12..f422deab37 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -2773,6 +2773,9 @@ fn hostile_params_never_panic(shard: usize) { json!({"transform": "spline", "crs": "EPSG:999999999", "pointsCrs": [7], "resampling": 1, "cellSize": -1e308, "path": 5, "points": [[0, 0, 1, 1]]}), json!({"transform": "affine", "crs": 32613, "pointsCrs": 4326, "cellSize": 1e-300, "path": "/nonexistent/x.tif", "points": [[0, 0, 1, 1], [1, 0, 2, 1], [0, 1, 1, 2]]}), json!({"points": [[0, 0, f64::MAX, f64::MAX], [1, 0, -f64::MAX, f64::MAX], [0, 1, f64::MAX, -f64::MAX]], "compare": true}), + // Polygons burned: a layer, a value and a no-data that pass, then a grid that can't be made. + json!({"layer": "Countries", "value": 3, "nodata": -1e30, "cellSize": [1e-300, 1e300], "origin": [1e308, -1e308]}), + json!({"layer": "Countries", "field": "name", "nodata": f64::MAX, "grid": [], "extent": "view", "path": 7}), // Connections: junk kinds, options and secrets; no connection exists in a fresh session. json!({"id": "c1", "kind": "s3", "address": "http://127.0.0.1:9", "name": "\u{7}", "group": 5, "options": {"credentials": "nope", "buckets": "NO_", "region": [1]}, "password": 7, "remember": [true], "accessKeyId": "A", "secretAccessKey": 9}), json!({"id": "", "kind": "postgres", "address": "postgres:host=127.0.0.1 port=9 password=x", "options": "x"}), @@ -26418,6 +26421,284 @@ fn analysis_workflows_run_on_another_thread() { assert!(raster_start(&mut s, "analysis.lineOfSight", &p).is_err()); } +/// `raster.rasterize` burns a polygon layer onto a grid given as `raster.project`'s is: holes cut +/// out, a later polygon over an earlier one, a text field's codes in a table, numbers in the +/// smallest pixel type that holds them, the selection alone, another raster's grid exactly, and +/// bad parameters refused before anything is made. +#[test] +fn polygons_burned_onto_a_chosen_grid() { + use rustgis_data::raster::{ColorHint, Crs, GeoTransform, Raster}; + use rustgis_data::{Dataset, Field, FieldType, Geometry, GeometryType, Value as V}; + use rustgis_geom::Coord; + let mut s = world(); + let ring = |x0: f64, y0: f64, x1: f64, y1: f64| { + vec![Coord::new(x0, y0), Coord::new(x1, y0), Coord::new(x1, y1), Coord::new(x0, y1), Coord::new(x0, y0)] + }; + let fields = vec![Field::new("unit", FieldType::Text), Field::new("clay", FieldType::Double), Field::new("code", FieldType::Integer)]; + let mut soils = Dataset::new("soils", GeometryType::Polygon, fields.clone()); + // A square with a hole, a second square over part of it, and a polygon with no unit. + let holed = Geometry::Polygon(vec![vec![ring(0.0, 0.0, 8.0, 8.0), ring(3.0, 3.0, 5.0, 5.0)]]); + soils.push(Some(holed), vec![V::Text("Latossolo".into()), V::Float(35.5), V::Int(2)]); + soils.push( + Some(Geometry::Polygon(vec![vec![ring(4.0, 4.0, 10.0, 10.0)]])), + vec![V::Text("Argissolo".into()), V::Float(20.25), V::Int(7)], + ); + soils.push(Some(Geometry::Polygon(vec![vec![ring(20.0, 0.0, 21.0, 1.0)]])), vec![V::Null, V::Null, V::Null]); + crate::cmd::layer::add_dataset(&mut s, soils); + // The value of the cell whose centre is (x, y) on a raster of 1° cells whose top is at 10°. + let at = |r: &Raster, x: f64, y: f64| r.value(0, x.floor() as i64, (10.0 - y).floor() as i64); + + // A text field: codes 1 and 2 in sorted order, listed in a table; the polygon with no unit + // is skipped, so the grid covers the other two (10 × 10 cells of 1°). + let mark = s.notice_mark(); + let v = s.run("raster.rasterize", &json!({"layer": "soils", "field": "unit", "cellSize": 1})).unwrap(); + assert_eq!( + (v["name"].as_str(), v["crs"].as_str(), v["dataType"].as_str()), + (Some("soils raster"), Some("EPSG:4326"), Some("UInt8")), + "{v}" + ); + assert_eq!((v["width"].as_u64(), v["height"].as_u64(), v["corner"].clone()), (Some(10), Some(10), json!([0.0, 10.0])), "{v}"); + assert_eq!(v["classes"], json!([{"code": 1, "value": "Argissolo"}, {"code": 2, "value": "Latossolo"}])); + assert_eq!((v["features"].as_u64(), v["skipped"].clone()), (Some(2), json!({"noValue": 1}))); + assert!(s.notices_since(mark).iter().any(|n| n.text == "soils: features skipped: 1 with no value"), "lossy input is said"); + // 60 cells of the holed square and 36 of the other, 15 of them in both. + assert_eq!(v["cells"].as_u64(), Some(81)); + let r = out_raster(&s, &v); + assert_eq!(at(&r, 1.5, 1.5), Some(2.0)); + assert_eq!(at(&r, 3.5, 3.5), None, "the hole stays out"); + assert_eq!((at(&r, 4.5, 4.5), at(&r, 6.5, 6.5), at(&r, 9.5, 9.5)), (Some(1.0), Some(1.0), Some(1.0)), "the later polygon wins"); + assert_eq!(at(&r, 9.5, 0.5), None, "no polygon there"); + let table = s.project.tables.iter().find(|t| t.name == "soils raster classes").expect("the codes' table"); + assert_eq!((table.features.len(), table.value(1, 0), table.value(1, 1)), (2, &V::Int(2), &V::Text("Latossolo".into()))); + assert!(matches!( + s.map().layer(v["layer"].as_u64().unwrap() as u32).unwrap().raster.as_ref().unwrap().style.renderer, + rustgis_map::RasterRenderer::UniqueValues { .. } + )); + + // A floating-point field keeps its values; a whole-number one fits in bytes; one value gives + // a mask. + let clay = s.run("raster.rasterize", &json!({"layer": "soils", "field": "clay", "cellSize": 1, "name": "clay"})).unwrap(); + let r = out_raster(&s, &clay); + assert_eq!((clay["dataType"].as_str(), at(&r, 1.5, 1.5), at(&r, 9.5, 9.5)), (Some("Float32"), Some(35.5), Some(20.25))); + let code = + s.run("raster.rasterize", &json!({"layer": "soils", "field": "code", "cellSize": 1, "nodata": 300, "name": "code"})).unwrap(); + let r = out_raster(&s, &code); + assert_eq!((code["dataType"].as_str(), at(&r, 1.5, 1.5), at(&r, 3.5, 3.5)), (Some("UInt16"), Some(2.0), None), "{code}"); + let mask = s.run("raster.rasterize", &json!({"layer": "soils", "cellSize": 1, "name": "mask"})).unwrap(); + let r = out_raster(&s, &mask); + // With no field, the polygon with no unit is burned too: the grid reaches it. + assert_eq!((mask["dataType"].as_str(), mask["width"].as_u64(), at(&r, 20.5, 0.5)), (Some("UInt8"), Some(21), Some(1.0)), "{mask}"); + + // The selection alone: the second square, 6 × 6 cells. + s.run("select.byAttributes", &json!({"layer": "soils", "where": "unit = 'Argissolo'"})).unwrap(); + let mark = s.notice_mark(); + let sel = s.run("raster.rasterize", &json!({"layer": "soils", "field": "unit", "cellSize": 1, "name": "selected"})).unwrap(); + assert_eq!( + (sel["width"].as_u64(), sel["cells"].as_u64(), sel["classes"].clone()), + (Some(6), Some(36), json!([{"code": 1, "value": "Argissolo"}])) + ); + assert!(s.notices_since(mark).is_empty() && sel.get("skipped").is_none(), "clean input says nothing: {sel}"); + s.run("select.clear", &json!({})).unwrap(); + + // On a grid projected from a raster: exactly that grid, and the cells in place there. + let gt = GeoTransform { origin_x: 0.0, origin_y: 10.0, pixel_width: 0.5, pixel_height: -0.5 }; + let dem = Raster::new("dem", 20, 20, vec![vec![1.0; 400]], gt, Crs::LonLat, None, ColorHint::Gray, "Float32").unwrap(); + let bytes = rustgis_data::raster::geotiff::write(&dem, 0).unwrap(); + crate::cmd::raster::add_raster(&mut s, "dem", rustgis_map::RasterLayer::from_bytes(dem, "dem.tif", bytes)).unwrap(); + let merc = s.run("raster.project", &json!({"layer": "dem", "crs": 3857, "cellSize": 50_000, "name": "dem merc"})).unwrap(); + let on = s.run("raster.rasterize", &json!({"layer": "soils", "field": "unit", "grid": "dem merc", "name": "on dem"})).unwrap(); + let (t, r) = (out_raster(&s, &merc), out_raster(&s, &on)); + assert_eq!((r.width, r.height, r.transform, r.crs), (t.width, t.height, t.transform, t.crs)); + let cell = |lon: f64, lat: f64| { + let p = r.transform.to_pixel(r.transformer().from_lonlat(Coord::new(lon, lat)).unwrap()); + r.value(0, p.0.floor() as i64, p.1.floor() as i64) + }; + assert_eq!((cell(1.5, 1.5), cell(9.0, 9.0), cell(3.8, 3.8)), (Some(2.0), Some(1.0), None), "{on}"); + // The same crs and cellSize as a projection line up with it, without the template. + let same = s.run("raster.rasterize", &json!({"layer": "soils", "crs": 3857, "cellSize": 50_000, "name": "same"})).unwrap(); + assert_eq!((same["corner"][0].as_f64().unwrap() / 50_000.0).fract(), 0.0, "{same}"); + + // Written to a file, as bytes with 0 for no-data. + let dir = std::env::temp_dir().join(format!("rustgis-rasterize-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("soils.tif"); + let _ = std::fs::remove_file(&path); + let f = s + .run( + "raster.rasterize", + &json!({"layer": "soils", "field": "unit", "cellSize": 1, "path": path.display().to_string(), "name": "file"}), + ) + .unwrap(); + assert!(f["cog"]["bytes"].as_u64().is_some_and(|b| b > 0), "{f}"); + let back = rustgis_data::raster::read_bytes("soils.tif", &std::fs::read(&path).unwrap()).unwrap(); + assert_eq!((back.data_type.as_str(), back.nodata, at(&back, 1.5, 1.5), at(&back, 3.5, 3.5)), ("UInt8", Some(0.0), Some(2.0), None)); + let _ = std::fs::remove_dir_all(&dir); + + // A whole number past what a pixel holds exactly is refused; a decimal one is rounded, and + // said, and one that would round to the no-data value is refused. A polygon that holds no cell + // centre is said too. + let mut big = Dataset::new("big", GeometryType::Polygon, fields); + big.push(Some(Geometry::Polygon(vec![vec![ring(0.0, 0.0, 1.0, 1.0)]])), vec![V::Null, V::Float(35.1), V::Int(20_000_001)]); + big.push(Some(Geometry::Polygon(vec![vec![ring(5.6, 5.6, 5.7, 5.7)]])), vec![V::Null, V::Float(1e-50), V::Null]); + crate::cmd::layer::add_dataset(&mut s, big); + let e = s.run("raster.rasterize", &json!({"layer": "big", "field": "code", "cellSize": 1})).unwrap_err(); + assert!(e.contains("text field"), "{e}"); + let e = s.run("raster.rasterize", &json!({"layer": "big", "field": "clay", "cellSize": 1})).unwrap_err(); + assert!(e.contains("no-data value"), "{e}"); + let mark = s.notice_mark(); + let v = s.run("raster.rasterize", &json!({"layer": "big", "field": "clay", "nodata": -1, "cellSize": 1, "name": "rounded"})).unwrap(); + let said: Vec = s.notices_since(mark).iter().map(|n| n.text.clone()).collect(); + assert_eq!((v["features"].as_u64(), v["skipped"].clone()), (Some(1), json!({"noCell": 1})), "{v}"); + assert!(said.iter().any(|n| n == "big: 2 value(s) of clay rounded to the raster's 32-bit pixels"), "{said:?}"); + assert!( + said.iter().any(|n| n == "big: features skipped: 1 that hold no cell centre (narrower than a cell, or off the grid)"), + "{said:?}" + ); + // A template read from its overview: its grid is taken, and said. + let mut over = Raster::new("over", 20, 20, vec![vec![1.0; 400]], gt, Crs::LonLat, None, ColorHint::Gray, "Float32").unwrap(); + over.overview = Some((80, 80)); + let bytes = rustgis_data::raster::geotiff::write(&over, 0).unwrap(); + crate::cmd::raster::add_raster(&mut s, "over", rustgis_map::RasterLayer::from_bytes(over, "over.tif", bytes)).unwrap(); + let mark = s.notice_mark(); + s.run("raster.rasterize", &json!({"layer": "soils", "field": "unit", "grid": "over", "name": "on over"})).unwrap(); + let said: Vec = s.notices_since(mark).iter().map(|n| n.text.clone()).collect(); + assert!(said.iter().any(|n| n == "over: the grid is its 20 × 20 overview's, of the 80 × 80 raster"), "{said:?}"); + + // Refused before anything is made. + let bad = [ + json!({"cellSize": 1}), + json!({"layer": "dem", "cellSize": 1}), + json!({"layer": "Cities", "cellSize": 1}), + json!({"layer": "soils", "field": "unit", "value": 3, "cellSize": 1}), + json!({"layer": "soils", "field": "nope", "cellSize": 1}), + json!({"layer": "soils", "field": 5, "cellSize": 1}), + json!({"layer": "soils", "value": "x", "cellSize": 1}), + json!({"layer": "soils", "value": 1e300, "cellSize": 1}), + json!({"layer": "soils", "nodata": "x", "cellSize": 1}), + json!({"layer": "soils", "nodata": 1, "cellSize": 1}), + json!({"layer": "soils", "field": "code", "nodata": 7, "cellSize": 1}), + json!({"layer": "soils"}), + json!({"layer": "soils", "grid": "dem merc", "cellSize": 1}), + json!({"layer": "soils", "grid": "Countries"}), + json!({"layer": "soils", "cellSize": -1}), + json!({"layer": "soils", "cellSize": 1e-9}), + json!({"layer": "soils", "cellSize": 1, "extent": 5}), + json!({"layer": "soils", "cellSize": 1, "path": "out.png"}), + // No cell centre falls in any polygon. + json!({"layer": "soils", "cellSize": 1, "extent": [-30.0, -30.0, -29.0, -29.0]}), + ]; + let (layers, tables) = (s.map().layers.len(), s.project.tables.len()); + for p in bad { + assert!(s.run("raster.rasterize", &p).is_err(), "{p}"); + } + assert_eq!((s.map().layers.len(), s.project.tables.len()), (layers, tables), "nothing added by a refused run"); + let e = s.run("raster.rasterize", &json!({"layer": "soils"})).unwrap_err(); + assert!(e.contains("cellSize is required"), "{e}"); + let e = s.run("raster.rasterize", &json!({"layer": "soils", "nodata": 1, "cellSize": 1})).unwrap_err(); + assert!(e.contains("no-data value"), "{e}"); +} + +/// A whole number past what a pixel holds is refused with advice that applies: a numeric field can +/// be given as text instead, one `value` can't. +#[test] +fn a_whole_number_past_a_pixel_is_refused_with_advice_that_applies() { + use rustgis_data::{Dataset, Field, FieldType, Geometry, GeometryType, Value as V}; + use rustgis_geom::Coord; + let mut s = world(); + let ring = vec![Coord::new(0.0, 0.0), Coord::new(1.0, 0.0), Coord::new(1.0, 1.0), Coord::new(0.0, 1.0), Coord::new(0.0, 0.0)]; + let mut ids = Dataset::new("ids", GeometryType::Polygon, vec![Field::new("code", FieldType::Integer)]); + ids.push(Some(Geometry::Polygon(vec![vec![ring]])), vec![V::Int(20_000_001)]); + crate::cmd::layer::add_dataset(&mut s, ids); + let e = s.run("raster.rasterize", &json!({"layer": "ids", "value": 20_000_000, "cellSize": 1})).unwrap_err(); + assert_eq!(e, "ids: value 20000000 is more than a raster's pixels hold exactly (16777216)"); + let e = s.run("raster.rasterize", &json!({"layer": "ids", "field": "code", "cellSize": 1})).unwrap_err(); + assert_eq!(e, "ids: code 20000001 is more than a raster's pixels hold exactly (16777216); a text field gives codes instead"); +} + +/// A text field with more codes than the result lists: the first 256 there, all of them in the +/// table, `classCount` saying how many, and too many to draw with unique values. +#[test] +fn a_text_fields_codes_past_those_listed_are_all_in_its_table() { + use rustgis_data::{Dataset, Field, FieldType, Geometry, GeometryType, Value as V}; + use rustgis_geom::Coord; + let mut s = world(); + let mut many = Dataset::new("many", GeometryType::Polygon, vec![Field::new("unit", FieldType::Text)]); + for i in 0..257 { + let (x0, x1) = (f64::from(i) * 0.1, f64::from(i + 1) * 0.1); + let ring = vec![Coord::new(x0, 0.0), Coord::new(x1, 0.0), Coord::new(x1, 0.1), Coord::new(x0, 0.1), Coord::new(x0, 0.0)]; + many.push(Some(Geometry::Polygon(vec![vec![ring]])), vec![V::Text(format!("u{i:03}"))]); + } + crate::cmd::layer::add_dataset(&mut s, many); + let v = s.run("raster.rasterize", &json!({"layer": "many", "field": "unit", "cellSize": 0.1})).unwrap(); + assert_eq!( + (v["classCount"].as_u64(), v["classes"].as_array().map(Vec::len), v["dataType"].as_str()), + (Some(257), Some(256), Some("UInt16")) + ); + assert_eq!(v["classes"][255], json!({"code": 256, "value": "u255"})); + let name = v["classTable"].as_str().unwrap(); + let table = s.project.tables.iter().find(|t| t.name == name).expect("the codes' table"); + assert_eq!((table.features.len(), table.value(256, 0), table.value(256, 1)), (257, &V::Int(257), &V::Text("u256".into()))); + assert!(!matches!( + s.map().layer(v["layer"].as_u64().unwrap() as u32).unwrap().raster.as_ref().unwrap().style.renderer, + rustgis_map::RasterRenderer::UniqueValues { .. } + )); +} + +/// The codes' table doesn't take the place of a table of the user's with its name. +#[test] +fn a_text_fields_codes_leave_a_table_of_that_name_alone() { + use rustgis_data::{Dataset, Field, FieldType, Geometry, GeometryType, Value as V}; + use rustgis_geom::Coord; + let mut s = world(); + let mut soils = Dataset::new("soils", GeometryType::Polygon, vec![Field::new("unit", FieldType::Text)]); + let ring = vec![Coord::new(0.0, 0.0), Coord::new(1.0, 0.0), Coord::new(1.0, 1.0), Coord::new(0.0, 1.0), Coord::new(0.0, 0.0)]; + soils.push(Some(Geometry::Polygon(vec![vec![ring]])), vec![V::Text("clay".into())]); + crate::cmd::layer::add_dataset(&mut s, soils); + let v = s.run("raster.rasterize", &json!({"layer": "soils", "field": "unit", "cellSize": 1, "name": "free"})).unwrap(); + assert_eq!(v["classTable"], "free classes", "no table has the name"); + + let mut mine = Dataset::new("units classes", GeometryType::None, vec![Field::new("note", FieldType::Text)]); + mine.push_next(None, vec![V::Text("mine".into())]); + let id = s.project.add_table(mine); + let v = s.run("raster.rasterize", &json!({"layer": "soils", "field": "unit", "cellSize": 1, "name": "units"})).unwrap(); + assert_eq!(s.project.table(id).expect("the user's table").value(0, 0), &V::Text("mine".into())); + assert_eq!(v["classTable"], "units classes (2)"); + let table = s.project.tables.iter().find(|t| t.name == "units classes (2)").expect("the codes' table"); + assert_eq!(table.value(0, 1), &V::Text("clay".into())); +} + +/// Georeferencing, projecting and rasterizing need a plugin's `files` only when given a `path`: a +/// null one is no path, and writes no file. A place named another way still needs it. +#[test] +fn plugin_rasters_with_a_null_path_need_no_files() { + use rustgis_data::raster::{ColorHint, Crs, GeoTransform, Raster, geotiff}; + let mut s = world(); + let gt = GeoTransform { origin_x: 0.0, origin_y: 1.0, pixel_width: 0.1, pixel_height: -0.1 }; + let r = Raster::new("dem", 10, 10, vec![vec![1.0; 100]], gt, Crs::LonLat, None, ColorHint::Gray, "Float32").unwrap(); + let bytes = geotiff::write(&r, 0).unwrap(); + crate::cmd::raster::add_raster(&mut s, "dem", rustgis_map::RasterLayer::from_bytes(r, "dem.tif", bytes)).unwrap(); + let burn = json!({"layer": "Countries", "cellSize": 10, "name": "burned"}); + let project = json!({"layer": "dem", "crs": 3857, "cellSize": 50_000, "name": "projected"}); + let georeference = + json!({"layer": "dem", "points": [[0, 0, 1, 1], [9, 0, 2, 1], [0, 9, 1, 2]], "transform": "affine", "name": "warped"}); + plugin("eng-null-path", &["edit"]); + for (op, params) in [("raster.rasterize", burn), ("raster.project", project), ("raster.georeference", georeference)] { + let with = |key: &str, v: Value| { + let mut p = params.clone(); + p[key] = v; + p + }; + forward(&mut s, "eng-null-path", op, with("path", Value::Null)).unwrap(); + let name = params["name"].as_str().unwrap(); + assert!(s.map().layer_by_name(name).is_some_and(|l| l.is_raster()), "{op}"); + for refused in [with("path", json!("out.tif")), with("name", json!("../out"))] { + let e = forward(&mut s, "eng-null-path", op, refused.clone()).unwrap_err(); + assert!(e.contains("'files' permission"), "{refused}: {e}"); + } + } + rustgis_plugins::unload("eng-null-path"); +} + /// The Analysis pane's single-pass raster tools made on another thread (#1291 step 3): each raster /// handed over (`ran`) is the one its command makes here, bit for bit and with what the command /// says of it besides, and a cancelled run is an error saying so. diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index 3e9634422c..125f72676f 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -970,8 +970,9 @@ below the web app's fixed limits and never above a ceiling. So a computer with 16 GB reads rasters of up to about 500 million samples. A run that passes on one computer can be refused on a smaller one; the error names the limit there. Project Raster (`raster.project`) puts a raster -on a grid of any coordinate system, cell size and extent; Raster Functions › Resample matches a target -raster's grid. +on a grid of any coordinate system, cell size and extent, and Polygons to Raster +(`raster.rasterize`) burns polygons onto the same grids; Raster Functions › Resample matches a +target raster's grid. The **Script** pane runs commands from text, one per line (`id {json}`); its box grows with the script down to the bottom of the pane, short of the buttons, and then scrolls, so **Run** stays in view; Ctrl+Enter (⌘+Enter on macOS) @@ -1144,6 +1145,41 @@ The Analyze tab's imagery groups open their tools in the Workflows pane: - The result has to fit in memory (120 million values, cells times bands, or more on a computer with more memory; 32 million in the web app): a grid past that is refused, naming the limit. A raster read from its overview is projected at that resolution, and the result says so. +- **Polygons to Raster** (`raster.rasterize`) burns a polygon layer onto a grid, so soil, + geology or land-use units line up cell for cell with rasters put on that grid by Project Raster: + `{"layer": "Soils", "field": "unit", "grid": "ndvi_100m", "path": "soils_100m.tif"}`. It has no + pane yet: run it from the Script pane, the AI Assistant, the command line or Python. The result + 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). + - **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 + the project has a table of that name, holds every code; the result's `classTable` names it, + its `classes` lists the first 256, and `classCount` gives the total. With no field, every + polygon gives `value` (1 by default), a mask. + - Where polygons overlap, the later feature wins, as GDAL burns. With a selection, only the + selected features are burned. Features with no value in the field, with no valid polygon, or + holding no cell centre are skipped, and the result and a notice count them. + - Cells under no polygon take `nodata` (0 by default). A polygon whose value is the no-data + value is refused, so give another `nodata`, such as 255, when 0 is a class. + - **Pixel type:** bytes when every value and the no-data value are whole numbers from 0 to 255, + 16-bit when they are up to 65,535, and 32-bit floating point otherwise. Past 16,777,216, 32 bits + no longer hold every whole number, so a whole number past it is refused, from an Integer field, + a text field's codes or `value`; for an Integer field, a text field gives codes instead. Any + other value that 32 bits can't hold exactly, a Double field's included, is rounded, and a notice + counts them. Up to 256 whole-number values are drawn with unique values. + - **Limits:** a polygon narrower than a cell can hold no cell centre and be missed; there is no + "all touched" rule, and lines and points aren't burned. The grid has to fit in memory (120 + million cells, or more on a computer with more memory; 32 million in the web app): a grid past + that is refused before anything is burned. A layer read in place (only the part in view loaded) + is refused until all its features are loaded. Taken from a raster read from its overview, the + grid is the overview's, and a notice says so. The command runs where it is called, with no Cancel + yet and no cap on its work: each polygon fills the cells it covers, so many large polygons on a + fine grid take time in proportion. - **Classification Wizard** (unsupervised k-means) and **Classification Tools** (minimum distance from training polygons). - **Mensuration**: distances along the surface, heights between two points, areas, and volumes