diff --git a/crates/analysis/src/rasterops.rs b/crates/analysis/src/rasterops.rs index 54c3583ac6..bff3ab6e21 100644 --- a/crates/analysis/src/rasterops.rs +++ b/crates/analysis/src/rasterops.rs @@ -115,6 +115,8 @@ fn z(r: &Raster, data: &[f32], col: i64, row: i64) -> Option { } /// The surface gradient (dz/dx east, dz/dy north) at a cell (Horn's method), in metres per metre. +/// Outside-grid neighbours use the nearest edge cell; an invalid sampled neighbour uses the +/// centre elevation. A missing centre is rejected by the terrain traversal before this call. fn gradient(r: &Raster, data: &[f32], col: i64, row: i64, zf: f64, (cx, cy): (f64, f64)) -> Option<(f64, f64)> { let g = |dc: i64, dr: i64| z(r, data, col + dc, row + dr).or_else(|| z(r, data, col, row)).map(|v| v as f64 * zf); let (a, b, c) = (g(-1, -1)?, g(0, -1)?, g(1, -1)?); @@ -182,29 +184,84 @@ pub fn per_index( /// The cells [`weighted_overlay`] makes at a time: its criteria carry no grid, so no rows. const OVERLAY_CHUNK: usize = 1 << 14; +/// Output cells that needed a boundary clamp or a centre-filled invalid neighbour. One cell +/// may be in both counts; missing centres are excluded. The counts describe a caller's kept +/// rectangle, so tiled runs do not count their disposable margins again. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct TerrainEdges { + pub clamped: usize, + pub filled: usize, + /// Repeated intermediate tile-margin evaluations make these counts upper bounds. + pub at_most: bool, +} + +/// A counted traversal's accumulators. Only scalar fallback cells can need either treatment; +/// the fast path already proved that all eight neighbours are valid and in bounds. +struct TerrainCounter { + core: Option<[usize; 4]>, + clamped: std::sync::atomic::AtomicUsize, + filled: std::sync::atomic::AtomicUsize, +} + +impl TerrainCounter { + fn new(core: Option<[usize; 4]>) -> Self { + Self { core, clamped: Default::default(), filled: Default::default() } + } + + /// Observes a valid scalar output in the same pass that made it. Eight bounded lookups + /// distinguish actual NoData substitution from a clamped but valid edge neighbour. + fn observe(&self, r: &Raster, data: &[f32], col: i64, row: i64) { + use std::sync::atomic::Ordering; + let Some([x0, y0, x1, y1]) = self.core else { return }; + if col < x0 as i64 || row < y0 as i64 || col >= x1 as i64 || row >= y1 as i64 { + return; + } + if col == 0 || row == 0 || col + 1 == i64::from(r.width) || row + 1 == i64::from(r.height) { + self.clamped.fetch_add(1, Ordering::Relaxed); + } + if [(-1, -1), (0, -1), (1, -1), (-1, 0), (1, 0), (-1, 1), (0, 1), (1, 1)] + .iter() + .any(|(dc, dr)| z(r, data, col + dc, row + dr).is_none()) + { + self.filled.fetch_add(1, Ordering::Relaxed); + } + } + + fn finish(&self) -> TerrainEdges { + use std::sync::atomic::Ordering; + TerrainEdges { clamped: self.clamped.load(Ordering::Relaxed), filled: self.filled.load(Ordering::Relaxed), at_most: false } + } +} + /// Draw the interior from three borrowed rows; edges and no-data keep the scalar path. On /// `threads` threads (none: as many as pay off). Each output row is made from the /// three input rows around it and written where it lies, so rows go on several threads (#1252). /// Its cells measured on `ground` when given ([`Raster::cell_size_m_on`]), as the whole raster of /// which `r` is a part measures them, else on `r`'s own. -fn terrain_on( +fn terrain_counted_on( threads: Option, r: &Raster, data: &[f32], zf: f64, ground: Option<&Extent>, + core: Option<[usize; 4]>, f: impl Fn(f64, f64) -> f64 + Sync, -) -> Result, String> { +) -> Result<(Vec, TerrainEdges), String> { let (w, h) = (r.width as usize, r.height as usize); let cell = ground.map_or_else(|| r.cell_size_m(), |g| r.cell_size_m_on(g)); + let counts = TerrainCounter::new(core); let scalar = |c, row| { z(r, data, c, row)?; let (x, y) = gradient(r, data, c, row, zf, cell)?; - Some(f(x, y)) + let value = f(x, y); + if value.is_finite() { + counts.observe(r, data, c, row); + } + Some(value) }; - let Some(len) = w.checked_mul(h) else { return per_cell(r, 1, scalar) }; + let Some(len) = w.checked_mul(h) else { return per_cell(r, 1, scalar).map(|pixels| (pixels, counts.finish())) }; if w < 3 || h < 3 || data.len() != len { - return per_cell(r, 1, scalar); + return per_cell(r, 1, scalar).map(|pixels| (pixels, counts.finish())); } let value = |v: Option| v.filter(|v| v.is_finite()).map(|v| v as f32).unwrap_or(NODATA); let mut out = new_band(w, h, NODATA)?; @@ -249,7 +306,68 @@ fn terrain_on( } }, )?; - Ok(out) + Ok((out, counts.finish())) +} + +/// The terrain operation, with the same defaults and formulas as its standalone entrypoint. +#[derive(Clone, Copy, Debug)] +pub enum TerrainFunction { + Slope, + SlopePercent, + Aspect, + Hillshade { azimuth: f64, altitude: f64 }, +} + +/// Terrain pixels with boundary-treatment counts and percent-slope overflow count. `core` is +/// the half-open rectangle [left, top, right, bottom] whose outputs the caller retains; None +/// disables boundary counting. Counts are made while traversing, without another raster pass. +pub fn terrain_reported( + r: &Raster, + b: usize, + zf: f64, + ground: Option<&Extent>, + core: Option<[usize; 4]>, + function: TerrainFunction, +) -> Result<(Vec, TerrainEdges, usize), String> { + use std::sync::atomic::{AtomicUsize, Ordering}; + let data = band(r, b)?; + let overflow = AtomicUsize::new(0); + let (zen, az) = match function { + TerrainFunction::Hillshade { azimuth, altitude } => ((90.0 - altitude).to_radians(), azimuth.to_radians()), + _ => (0.0, 0.0), + }; + let (cos_zen, sin_zen, cos_az, sin_az) = (zen.cos(), zen.sin(), az.cos(), az.sin()); + let (pixels, edges) = terrain_counted_on(None, r, data, zf, ground, core, |gx, gy| match function { + TerrainFunction::Slope => gx.hypot(gy).atan().to_degrees(), + TerrainFunction::SlopePercent => { + let value = 100.0 * gx.hypot(gy); + if !value.is_finite() || value > f64::from(f32::MAX) { + overflow.fetch_add(1, Ordering::Relaxed); + f64::MAX + } else { + value + } + } + TerrainFunction::Aspect => { + if gx.abs() < 1e-12 && gy.abs() < 1e-12 { + -1.0 + } else { + (-gx).atan2(-gy).to_degrees().rem_euclid(360.0) + } + } + TerrainFunction::Hillshade { .. } => { + let q = 1.0 + gx * gx + gy * gy; + let value = if q.is_finite() { + (cos_zen - sin_zen * (gy * cos_az + gx * sin_az)) / q.sqrt() + } else { + let slope = gx.hypot(gy).atan(); + let aspect = (-gx).atan2(-gy); + cos_zen * slope.cos() + sin_zen * slope.sin() * (az - aspect).cos() + }; + rustgis_data::raster::round_positive(value.max(0.0) * 255.0).max(1.0) + } + })?; + Ok((pixels, edges, overflow.load(Ordering::Relaxed))) } /// Slope in degrees. @@ -260,8 +378,7 @@ pub fn slope(r: &Raster, b: usize, zf: f64) -> Result, String> { /// [`slope`] of `r`, a part of a raster covering `ground`, its cells measured as the whole's are /// ([`Raster::cell_size_m_on`]); `None`: `r` is the whole. pub fn slope_on(r: &Raster, b: usize, zf: f64, ground: Option<&Extent>) -> Result, String> { - let d = band(r, b)?; - terrain_on(None, r, d, zf, ground, |gx, gy| gx.hypot(gy).atan().to_degrees()) + terrain_reported(r, b, zf, ground, None, TerrainFunction::Slope).map(|(pixels, _, _)| pixels) } /// Slope as percent rise: 100 times the gradient magnitude, equivalent to 100 × tan(angle in radians). @@ -284,19 +401,7 @@ pub const PERCENT_OVERFLOW: &str = "percent slope cells exceed the Float32 range /// part of a raster read with a margin, whose cells past the range the caller counts only where /// it keeps them. pub fn slope_percent_cells_on(r: &Raster, b: usize, zf: f64, ground: Option<&Extent>) -> Result<(Vec, usize), String> { - use std::sync::atomic::{AtomicUsize, Ordering}; - let d = band(r, b)?; - let overflow = AtomicUsize::new(0); - let pixels = terrain_on(None, r, d, zf, ground, |gx, gy| { - let value = 100.0 * gx.hypot(gy); - if !value.is_finite() || value > f64::from(f32::MAX) { - overflow.fetch_add(1, Ordering::Relaxed); - // Finite, so it isn't taken for no value; infinite as a Float32. - return f64::MAX; - } - value - })?; - Ok((pixels, overflow.load(Ordering::Relaxed))) + terrain_reported(r, b, zf, ground, None, TerrainFunction::SlopePercent).map(|(pixels, _, overflow)| (pixels, overflow)) } /// Aspect: the compass direction the slope faces, in degrees (flat cells are -1). @@ -306,10 +411,7 @@ pub fn aspect(r: &Raster, b: usize) -> Result, String> { /// [`aspect`], as [`slope_on`]. pub fn aspect_on(r: &Raster, b: usize, ground: Option<&Extent>) -> Result, String> { - let d = band(r, b)?; - terrain_on(None, r, d, 1.0, ground, |gx, gy| { - if gx.abs() < 1e-12 && gy.abs() < 1e-12 { -1.0 } else { (-gx).atan2(-gy).to_degrees().rem_euclid(360.0) } - }) + terrain_reported(r, b, 1.0, ground, None, TerrainFunction::Aspect).map(|(pixels, _, _)| pixels) } /// Hillshade (1–255) lit from `azimuth` and `altitude` degrees: a cell in full shadow is 1, so @@ -328,21 +430,7 @@ pub fn hillshade(r: &Raster, b: usize, azimuth: f64, altitude: f64, zf: f64) -> /// (cos zenith − sin zenith · (gy · cos azimuth + gx · sin azimuth)) / √(1 + p²): a square root a /// cell and no trigonometry. Where 1 + p² overflows, the angles are taken instead. pub fn hillshade_on(r: &Raster, b: usize, azimuth: f64, altitude: f64, zf: f64, ground: Option<&Extent>) -> Result, String> { - let d = band(r, b)?; - let (zen, az) = ((90.0 - altitude).to_radians(), azimuth.to_radians()); - let (cos_zen, sin_zen) = (zen.cos(), zen.sin()); - let (cos_az, sin_az) = (az.cos(), az.sin()); - terrain_on(None, r, d, zf, ground, |gx, gy| { - let q = 1.0 + gx * gx + gy * gy; - let v = if q.is_finite() { - (cos_zen - sin_zen * (gy * cos_az + gx * sin_az)) / q.sqrt() - } else { - let slope = gx.hypot(gy).atan(); - let aspect = (-gx).atan2(-gy); - cos_zen * slope.cos() + sin_zen * slope.sin() * (az - aspect).cos() - }; - rustgis_data::raster::round_positive(v.max(0.0) * 255.0).max(1.0) - }) + terrain_reported(r, b, zf, ground, None, TerrainFunction::Hillshade { azimuth, altitude }).map(|(pixels, _, _)| pixels) } /// A band arithmetic expression over `b1`, `b2`… (+ - * / and parentheses, numbers). @@ -2465,6 +2553,18 @@ impl Expr { mod tests { use super::*; + /// Uncounted traversal used by the scalar/parallel equivalence regressions. + fn terrain_on( + threads: Option, + r: &Raster, + data: &[f32], + zf: f64, + ground: Option<&Extent>, + f: impl Fn(f64, f64) -> f64 + Sync, + ) -> Result, String> { + terrain_counted_on(threads, r, data, zf, ground, None, f).map(|(pixels, _)| pixels) + } + /// A grid the machine can't hold is an error naming its size, not the end of the program /// (#1291); one it can is the size asked for. #[test] @@ -3138,6 +3238,32 @@ mod tests { } } + /// Counts belong to valid outputs in the kept rectangle, including at most one of each + /// treatment per output. The interior clean control never enters either count. + #[test] + fn terrain_counts_keep_the_output_basis_and_thread_parity() { + let mut values = vec![10.0; 25]; + values[12] = -9999.0; + let gt = GeoTransform { origin_x: 0.0, origin_y: 5.0, pixel_width: 1.0, pixel_height: -1.0 }; + let mut r = Raster::new("height", 5, 5, vec![values], gt, Crs::WebMercator, Some(-9999.0), ColorHint::Gray, "Float32").unwrap(); + let f = |x: f64, y: f64| x.hypot(y).atan().to_degrees(); + let data = band(&r, 0).unwrap(); + let (want, full) = terrain_counted_on(Some(1), &r, data, 1.0, None, Some([0, 0, 5, 5]), f).unwrap(); + assert_eq!(full, TerrainEdges { clamped: 16, filled: 8, at_most: false }); + assert_eq!(want[12], NODATA); + for threads in [2, 7] { + let (got, counts) = terrain_counted_on(Some(threads), &r, data, 1.0, None, Some([0, 0, 5, 5]), f).unwrap(); + assert_eq!(got, want); + assert_eq!(counts, full); + } + let (got, inner) = terrain_counted_on(Some(1), &r, data, 1.0, None, Some([1, 1, 4, 4]), f).unwrap(); + assert_eq!(got, want, "counting a core does not clip the computed raster"); + assert_eq!(inner, TerrainEdges { clamped: 0, filled: 8, at_most: false }); + r.bands[0].data[12] = 10.0; + let (_, clean) = terrain_counted_on(Some(1), &r, band(&r, 0).unwrap(), 1.0, None, Some([1, 1, 4, 4]), f).unwrap(); + assert_eq!(clean, TerrainEdges::default()); + } + #[test] fn terrain_rows_match_scalar_edges_nodata_and_orientations() { for (w, h) in [(1, 1), (1, 5), (2, 3), (3, 2), (3, 3), (9, 7), (60, 41)] { diff --git a/crates/engine/src/cmd/in_blocks.rs b/crates/engine/src/cmd/in_blocks.rs index e2fc3b9f66..2941e3661f 100644 --- a/crates/engine/src/cmd/in_blocks.rs +++ b/crates/engine/src/cmd/in_blocks.rs @@ -435,11 +435,21 @@ impl Blocks { self, cells: impl Fn(&Raster, &rustgis_geom::Extent) -> Result, String>, shape: Shape, + ) -> Result { + self.run_window(|r, ground, _| cells(r, ground), shape) + } + + /// Like run, exposing the kept rectangle in each block's grid so diagnostics do not + /// count disposable margin cells again. + pub(crate) fn run_window( + self, + cells: impl Fn(&Raster, &rustgis_geom::Extent, [usize; 4]) -> Result, String>, + shape: Shape, ) -> Result { let Blocks { input, layer, path, out, folder, full, halo, nodata: first } = self; let (nodata, kind) = shape.nodata(); - let cells = |r: &Raster, ground: &rustgis_geom::Extent| -> Result, String> { - let mut v = cells(r, ground)?; + let cells = |r: &Raster, ground: &rustgis_geom::Extent, core: [usize; 4]| -> Result, String> { + let mut v = cells(r, ground, core)?; if shape.bytes { v.iter_mut().filter(|v| !v.is_finite() || **v < 1.0).for_each(|v| *v = 0.0); } @@ -680,7 +690,7 @@ impl Source<'_> { /// full grid, its system, and how many values were rounded as they were read. fn each_row( &self, - cells: &impl Fn(&Raster, &rustgis_geom::Extent) -> Result, String>, + cells: &impl Fn(&Raster, &rustgis_geom::Extent, [usize; 4]) -> Result, String>, halo: u32, mut row: impl FnMut(u32, &[f32], (rustgis_data::raster::GeoTransform, rustgis_data::raster::Crs)) -> Result<(), String>, ) -> Result<(rustgis_data::raster::GeoTransform, rustgis_data::raster::Crs, u64), String> { @@ -700,7 +710,9 @@ impl Source<'_> { // With the cells around it, within the image. let around = |(a, b): (u32, u32), n: u32| (a.saturating_sub(halo), b.saturating_add(halo).min(n)); let read = self.block(around((c0, c1), fw), around((r0, r1), fh))?; - let values = cells(&read.0.raster, &read.0.bounds)?; + let (ax, ay) = read.0.at; + let core = [(c0 - ax) as usize, (r0 - ay) as usize, (c1 - ax) as usize, (r1 - ay) as usize]; + let values = cells(&read.0.raster, &read.0.bounds, core)?; Ok((read, values)) })?; let r = &read.raster; diff --git a/crates/engine/src/cmd/workflows.rs b/crates/engine/src/cmd/workflows.rs index 3bedf52e8c..9514ba94d5 100644 --- a/crates/engine/src/cmd/workflows.rs +++ b/crates/engine/src/cmd/workflows.rs @@ -473,6 +473,7 @@ fn installed(mut layer: rustgis_map::RasterLayer, dest: &std::path::Path) -> rus /// cell with a value. #[derive(Default)] struct Remaps { + terrain: Vec<(String, rasterops::TerrainEdges)>, empty: Vec<(String, f64, f64)>, emptied: Option, } @@ -483,6 +484,13 @@ impl Remaps { fn then(self) -> Then { let mut notes: Vec = rasterops::empty_ranges_note(&self.empty).into_iter().collect(); notes.extend(self.emptied.map(|name| format!("{name}: the remap left no cells with values"))); + for (stage, (name, edges)) in self.terrain.into_iter().enumerate() { + if edges.clamped > 0 || edges.filled > 0 { + let limit = if edges.at_most { "at most " } else { "" }; + let margin = if edges.at_most { "; counts include repeated intermediate tile margins" } else { "" }; + notes.push(format!("{name}, terrain step {}: {limit}{} output cells used clamped boundary neighbours; {limit}{} output cells used the centre height for invalid neighbours{margin}", stage + 1, edges.clamped, edges.filled)); + } + } notices(notes) } } @@ -1606,30 +1614,37 @@ fn apply_function( target: Option<&Raster>, remaps: &mut Remaps, ground: Option<&rustgis_geom::Extent>, + core: Option<([usize; 4], bool)>, ) -> Result, String> { let band = band_of(p, r)?; let zf = f(p, "zFactor").unwrap_or(1.0).clamp(0.0001, 100_000.0); - match ps(p, "function").ok_or("function is required")? { - "slope" => match p.get("units") { - None => rasterops::slope_on(r, band, zf, ground), - Some(Value::String(units)) if units == "degrees" => rasterops::slope_on(r, band, zf, ground), - // A part read with a margin: its cells past Float32's range are counted where they're - // kept ([`super::in_blocks::Shape::overflow`]). - Some(Value::String(units)) if units == "percent" && ground.is_some() => { - rasterops::slope_percent_cells_on(r, band, zf, ground).map(|(p, _)| p) - } - Some(Value::String(units)) if units == "percent" => rasterops::slope_percent_on(r, band, zf, ground), - _ => Err("slope units must be degrees or percent".into()), - }, - "aspect" => rasterops::aspect_on(r, band, ground), - "hillshade" => rasterops::hillshade_on( - r, - band, - f(p, "azimuth").unwrap_or(315.0), - f(p, "altitude").unwrap_or(45.0).clamp(0.0, 90.0), - zf, - ground, - ), + let function = ps(p, "function").ok_or("function is required")?; + let terrain = match function { + "slope" => Some(match p.get("units") { + None => rasterops::TerrainFunction::Slope, + Some(Value::String(units)) if units == "degrees" => rasterops::TerrainFunction::Slope, + Some(Value::String(units)) if units == "percent" => rasterops::TerrainFunction::SlopePercent, + _ => return Err("slope units must be degrees or percent".into()), + }), + "aspect" => Some(rasterops::TerrainFunction::Aspect), + "hillshade" => Some(rasterops::TerrainFunction::Hillshade { + azimuth: f(p, "azimuth").unwrap_or(315.0), + altitude: f(p, "altitude").unwrap_or(45.0).clamp(0.0, 90.0), + }), + _ => None, + }; + if let Some(terrain) = terrain { + let (core, at_most) = core.unwrap_or(([0, 0, r.width as usize, r.height as usize], false)); + let zf = if function == "aspect" { 1.0 } else { zf }; + let (pixels, mut edges, overflow) = rasterops::terrain_reported(r, band, zf, ground, Some(core), terrain)?; + if overflow > 0 && ground.is_none() { + return Err(format!("{overflow} {}", rasterops::PERCENT_OVERFLOW)); + } + edges.at_most = at_most; + remaps.terrain.push((format!("{} ({function})", r.name), edges)); + return Ok(pixels); + } + match function { "ndvi" => { let (nir, red) = (p.get("nir").and_then(Value::as_u64).unwrap_or(4), p.get("red").and_then(Value::as_u64).unwrap_or(3)); rasterops::band_math(r, &format!("(b{nir} - b{red}) / (b{nir} + b{red})")) @@ -1710,10 +1725,10 @@ fn function_work(s: &Session, p: &Value) -> Result { let shape = function_shape(&p); return Ok(Box::new(move || { let met = std::cell::RefCell::new(BlockRemaps::default()); - let made = blocks.with_halo(halo).run( - |block, ground| { + let made = blocks.with_halo(halo).run_window( + |block, ground, core| { let mut remaps = Remaps::default(); - let pixels = apply_function(block, &p, None, &mut remaps, Some(ground))?; + let pixels = apply_function(block, &p, None, &mut remaps, Some(ground), Some((core, false)))?; met.borrow_mut().add(remaps); Ok(pixels) }, @@ -1727,10 +1742,11 @@ fn function_work(s: &Session, p: &Value) -> Result { let src = src.read()?; let target = read_target(target.as_ref())?; let mut remaps = Remaps::default(); - let pixels = apply_function(&src, &p, target.as_deref(), &mut remaps, None)?; + let pixels = apply_function(&src, &p, target.as_deref(), &mut remaps, None, None)?; // Only a resample takes another raster's grid. let raster = derive_function(target.as_deref().unwrap_or(&src), &name, &p, pixels)?; - if is_hillshade(&p) { made_hillshade(raster, &defaults) } else { made_then(raster, None, Some(remaps.then())) } + let made = made_then(raster, None, Some(remaps.then()))?; + Ok(if is_hillshade(&p) { hillshade_look(made, &defaults) } else { made }) })) } @@ -1812,6 +1828,7 @@ pub(crate) fn also(mut m: Made, then: Then) -> Made { #[cfg(not(target_arch = "wasm32"))] #[derive(Default)] struct BlockRemaps { + terrain: Vec<(String, rasterops::TerrainEdges)>, /// The ranges that match nothing, as every block so far found them; `None` before the first. empty: Option>, /// Whether every block so far was left with no value, and the raster it was said of. @@ -1822,6 +1839,15 @@ struct BlockRemaps { impl BlockRemaps { /// Adds what one block's remaps met. fn add(&mut self, r: Remaps) { + for (i, (name, edges)) in r.terrain.into_iter().enumerate() { + if let Some((_, total)) = self.terrain.get_mut(i) { + total.clamped = total.clamped.saturating_add(edges.clamped); + total.filled = total.filled.saturating_add(edges.filled); + total.at_most |= edges.at_most; + } else { + self.terrain.push((name, edges)); + } + } self.empty = Some(match self.empty.take() { None => r.empty, Some(mut e) => { @@ -1840,7 +1866,7 @@ impl BlockRemaps { /// What every block's remaps met together. fn met(self) -> Remaps { - Remaps { empty: self.empty.unwrap_or_default(), emptied: self.emptied.flatten() } + Remaps { terrain: self.terrain, empty: self.empty.unwrap_or_default(), emptied: self.emptied.flatten() } } } @@ -1881,13 +1907,26 @@ fn function_chain_work(s: &Session, p: &Value) -> Result { let shape = function_shape(&last); return Ok(Box::new(move || { let met = std::cell::RefCell::new(BlockRemaps::default()); - let made = blocks.with_halo(halo).run( - |block, ground| { + let made = blocks.with_halo(halo).run_window( + |block, ground, core| { let mut remaps = Remaps::default(); let mut cur: Option = None; for (i, st) in steps.iter().enumerate() { let input = cur.as_ref().unwrap_or(block); - let pixels = apply_function(input, st, None, &mut remaps, Some(ground)) + // Earlier outputs in the remaining halo feed later terrain steps. + let halo: usize = steps + .iter() + .skip(i + 1) + .filter_map(|st| ps(st, "function").and_then(super::in_blocks::function_halo)) + .map(|v| v as usize) + .sum(); + let kept = [ + core[0].saturating_sub(halo), + core[1].saturating_sub(halo), + core[2].saturating_add(halo).min(input.width as usize), + core[3].saturating_add(halo).min(input.height as usize), + ]; + let pixels = apply_function(input, st, None, &mut remaps, Some(ground), Some((kept, halo > 0))) .map_err(|e| format!("step {} ({}): {e}", i + 1, func(st)))?; cur = Some(derive_function(input, &input.name, st, pixels)?); } @@ -1914,7 +1953,7 @@ fn function_chain_work(s: &Session, p: &Value) -> Result { let target = read_target(target.as_ref()).map_err(|e| format!("step {} ({f}): {e}", i + 1))?; let input = cur.as_ref().unwrap_or(&src); let pixels = - apply_function(input, st, target.as_deref(), &mut remaps, None).map_err(|e| format!("step {} ({f}): {e}", i + 1))?; + apply_function(input, st, target.as_deref(), &mut remaps, None, None).map_err(|e| format!("step {} ({f}): {e}", i + 1))?; // Only a resample takes another raster's grid; otherwise the grid is the current one. let next = derive_function(target.as_deref().unwrap_or(input), &input.name, st, pixels)?; cur = Some(next); diff --git a/crates/engine/src/tests/tiled_files.rs b/crates/engine/src/tests/tiled_files.rs index ad8dd5c036..35b357d16d 100644 --- a/crates/engine/src/tests/tiled_files.rs +++ b/crates/engine/src/tests/tiled_files.rs @@ -594,6 +594,104 @@ fn indices_over_a_file_too_large_to_read_whole_run_a_block_at_a_time() { assert!(folder.join("scripted.tif").is_file()); } +/// Notices count affected output cells, not missing samples or skipped centre cells. +#[test] +fn terrain_functions_report_clamped_edges_and_filled_nodata_neighbours() { + let d = dir("terrain-edge-notes"); + let path = d.join("height.tif"); + let mut heights = vec![10.0; 25]; + heights[12] = -9999.0; + let dem = Raster::new( + "height", + 5, + 5, + vec![heights], + GeoTransform { origin_x: 0.0, origin_y: 5.0, pixel_width: 1.0, pixel_height: -1.0 }, + Crs::WebMercator, + Some(-9999.0), + ColorHint::Gray, + "Float32", + ) + .unwrap(); + std::fs::write(&path, rustgis_data::raster::geotiff::write(&dem, 0).unwrap()).unwrap(); + for function in ["slope", "aspect", "hillshade"] { + let mut s = Session::new(Project::default()); + s.run("layer.addData", &json!({"path": path})).unwrap(); + let mark = s.notice_mark(); + s.run("raster.function", &json!({"layer": "height", "function": function, "name": "out"})).unwrap(); + let notes = said(&s, mark); + let edge = notes.iter().filter(|n| n.contains("clamped") && n.contains("neighbour")).collect::>(); + assert_eq!(edge.len(), 1, "{function}: {notes:?}"); + assert!(edge[0].contains("16 output cells"), "{}", edge[0]); + assert!(edge[0].contains("8 output cells"), "{}", edge[0]); + assert!(edge[0].contains(function), "{}", edge[0]); + } +} + +/// A missing centre at four block corners must be counted once for the kept outputs, +/// not once per read margin. A chained stage also says when its margin counts are bounds. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn terrain_notices_and_pixels_agree_across_block_margins() { + let d = dir("terrain-block-notes"); + let path = d.join("height.tif"); + let (w, h) = (1025, 1025); + let mut values = vec![10.0; (w * h) as usize]; + values[511 * w as usize + 383] = -9999.0; + let dem = Raster::new( + "height", + w, + h, + vec![values], + GeoTransform { origin_x: 0.0, origin_y: h as f64, pixel_width: 1.0, pixel_height: -1.0 }, + Crs::WebMercator, + Some(-9999.0), + ColorHint::Gray, + "Float32", + ) + .unwrap(); + let info = rustgis_data::raster::cogwrite::write_file(&dem, 0, &path).unwrap(); + assert_eq!(info.levels, vec![(1025, 1025), (513, 513), (257, 257)]); + for (command, p) in [ + ("raster.function", json!({"layer": "height", "function": "slope", "name": "out"})), + ("raster.functionChain", json!({"layer": "height", "steps": [{"function": "slope"}, {"function": "slope"}], "name": "out"})), + ] { + let mut whole = Session::new(Project::default()); + whole.run("layer.addData", &json!({"path": path})).unwrap(); + let mark = whole.notice_mark(); + whole.run(command, &p).unwrap(); + let want = raster(&whole, "out").data.clone().unwrap(); + let whole_notes: Vec<_> = said(&whole, mark).into_iter().filter(|n| n.contains("clamped boundary")).collect(); + // Nine padded 512-pixel tiles exceed the reader's overview budget; the + // 513-pixel overview fits. Planning budgets input at 8 bytes per sample, + // while its Float32 output still fits this threshold. + let (_held, _blocks) = (HeldWhole::at(1000), BlocksPast::at(1_100_000)); + let mut blocked = Session::new(Project::default()); + blocked.run("layer.addData", &json!({"path": path})).unwrap(); + assert!(raster(&blocked, "height").tiled); + assert_eq!(raster(&blocked, "height").data.as_ref().unwrap().overview, Some((w, h))); + let mark = blocked.notice_mark(); + let reads = crate::cmd::gp::TILED_READS.with(std::cell::Cell::get); + blocked.run(command, &p).unwrap(); + assert_eq!(crate::cmd::gp::TILED_READS.with(std::cell::Cell::get), reads, "{command}: no whole-file fallback"); + let got = raster(&blocked, "out").data.as_ref().unwrap(); + assert_eq!(got.bands[0].data, want.bands[0].data, "{command}"); + let notes: Vec<_> = said(&blocked, mark).into_iter().filter(|n| n.contains("clamped boundary")).collect(); + assert_eq!(notes.len(), whole_notes.len(), "{command}: {notes:?}"); + if command == "raster.function" { + assert_eq!(notes, whole_notes); + assert!( + notes[0].contains("4096 output cells used clamped") && notes[0].contains("8 output cells used the centre"), + "{notes:?}" + ); + } else { + assert_eq!(notes.len(), 2); + assert!(notes[0].contains("at most") && notes[0].contains("repeated intermediate tile margins"), "{notes:?}"); + assert_eq!(notes[1], whole_notes[1], "the last stage counts only kept outputs"); + } + } +} + /// The other commands that work cell by cell, or over a cell's neighbours, run a block at a time /// over a file too large to read whole too (#2865), each making the raster it makes of the file /// held whole, held or written to the results folder: Raster Functions by cell and over a cell's diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index 9d13f07ca7..d07c9afdb6 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -1693,6 +1693,14 @@ statistics; converting a mean angle would not give the mean percent. The result' named **Slope (degrees)** or **Slope (percent)**, which `raster.info` shows and a saved project or GeoTIFF export keeps; a later step in a chain names it again. +Slope, aspect and hillshade keep a missing centre cell as NoData. At the raster boundary, +they use the nearest edge cell for a neighbour outside the grid. An invalid neighbour inside +the grid is replaced by the centre cell's elevation. A notice names the function and counts +the valid output cells using each treatment; a cell can appear in both counts. These choices +also apply in the Function Editor. A function run in blocks counts only kept output cells. +For an intermediate terrain step in a tiled chain, the notice gives an upper bound that can +include repeated margin evaluations needed by later steps; it says when this applies. + Slope, aspect and hillshade need the cell size in the elevation's unit. On a projected DEM the cell size is taken as it is, so elevations must be in the same unit as the coordinates (feet aren't converted). On a geographic DEM the cell size is worked out in metres once for the whole