From b789268b152aef7a9ab3633214b24c57f1f4f344 Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Sat, 28 Nov 2026 13:56:32 -0300 Subject: [PATCH 1/5] feat(analysis): Check DEM finds steps, spikes, pits and implausible values; Shaded Relief names them (#3151) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Check DEM (`checkDem`, Analysis › Terrain) writes a point per finding, with kind, size, unit and elevation, and a summary of counts and the share of the model affected. It reports and changes nothing. - step: a drop to a neighbour above 20 m and above 5 times the drops just before and after it on the same line, so a cliff face is not one; - spike/pit: more than 30 m off the median of the 8 neighbours; - out of range: runs below -500 or above 9,000 (left out of the neighbourhood rules); - flat run: 100+ cells along a row at the band's lowest or highest value. Three passes in blocks of rows on the shared threads, Cancel along each row; at most 100,000 points, the rest counted with a dropped.over-limit loss and the same first findings on any thread count. raster.symbology shadedRelief now notifies when the band's statistics fall outside -500 to 9,000, naming the values and pointing to Check DEM. Co-Authored-By: Claude Opus 5.5 --- crates/analysis/src/lib.rs | 5 +- crates/analysis/src/tools.rs | 74 +++ crates/analysis/src/tools/check_dem.rs | 676 ++++++++++++++++++++++++ crates/engine/src/cmd/raster.rs | 31 +- crates/engine/src/tests.rs | 75 +++ crates/engine/src/tests/cancellation.rs | 1 + docs/user-guide/analysis.md | 43 ++ docs/user-guide/data.md | 5 + 8 files changed, 907 insertions(+), 3 deletions(-) create mode 100644 crates/analysis/src/tools/check_dem.rs diff --git a/crates/analysis/src/lib.rs b/crates/analysis/src/lib.rs index 3d112a3576..5cce7f9396 100644 --- a/crates/analysis/src/lib.rs +++ b/crates/analysis/src/lib.rs @@ -48,8 +48,9 @@ pub use density::{ pub use parallel::scratch_budget; pub use parameters::StatisticList; pub use tools::{ - SimplifyNotes, TOOLS, find_field_case_insensitive, holds_coordinates, in_its_units, layer_raster_crs, max_buffer_bytes, min_pad, - param_applies, past_pole, points_from, points_in, projected_crs, raster_crs, raster_crs_in, simplify_geometry, zonal_bands, + PLAUSIBLE_ELEVATION, SimplifyNotes, TOOLS, find_field_case_insensitive, holds_coordinates, in_its_units, layer_raster_crs, + max_buffer_bytes, min_pad, param_applies, past_pole, points_from, points_in, projected_crs, raster_crs, raster_crs_in, + simplify_geometry, zonal_bands, }; use rustgis_data::Dataset; diff --git a/crates/analysis/src/tools.rs b/crates/analysis/src/tools.rs index b35730f4ae..bcbcb75785 100644 --- a/crates/analysis/src/tools.rs +++ b/crates/analysis/src/tools.rs @@ -1,5 +1,7 @@ //! The tools. +mod check_dem; +pub use check_dem::PLAUSIBLE_ELEVATION; mod check_geometry; mod geometry; mod network_analysis; @@ -1136,6 +1138,73 @@ pub static TOOLS: &[ToolSpec] = &[ ], run: tabulate_area::run, }, + ToolSpec { + id: "checkDem", + name: "Check DEM", + toolbox: "Analysis › Terrain", + summary: "Finds steps, spikes, pits and implausible values in an elevation model, as points with a summary; it changes nothing.", + params: &[ + P { + name: "input", + label: "Elevation Raster", + kind: K::RasterLayer, + required: true, + default: "", + help: "The elevation model to check. Thresholds are in its elevation unit (metres by default).", + }, + P { name: "band", label: "Band", kind: K::Number, required: false, default: "1", help: "1-based band of elevations." }, + P { + name: "stepRatio", + label: "Step Ratio", + kind: K::Number, + required: false, + default: "5", + help: "A step is a drop to a neighbour more than this many times the drops just before and after it on the same line, so a cliff whose face goes on dropping is not one.", + }, + P { + name: "stepHeight", + label: "Step Height", + kind: K::Number, + required: false, + default: "20", + help: "The least drop that is a step.", + }, + P { + name: "spikeHeight", + label: "Spike Height", + kind: K::Number, + required: false, + default: "30", + help: "A cell this far above the median of its eight neighbours is a spike, this far below a pit.", + }, + P { + name: "lowest", + label: "Lowest Elevation", + kind: K::Number, + required: false, + default: "-500", + help: "Values below this are out of range (a no-data such as -32768 or -9999 the file doesn't declare).", + }, + P { + name: "highest", + label: "Highest Elevation", + kind: K::Number, + required: false, + default: "9000", + help: "Values above this are out of range.", + }, + P { + name: "runLength", + label: "Flat Run Length", + kind: K::Number, + required: false, + default: "100", + help: "A run of this many cells along a row holding the band's lowest or highest value is a flat run: an undeclared no-data, or water held level at the edge of the range.", + }, + P { name: "output", label: "Output Name", kind: K::Text, required: false, default: "", help: "Output point layer name." }, + ], + run: check_dem::run, + }, ToolSpec { id: "zonalStats", name: "Zonal Statistics", @@ -11446,6 +11515,11 @@ mod tests { if !spec.params.iter().any(|p| p.name.eq_ignore_ascii_case("output") && matches!(p.kind, K::Text)) { continue; } + // `inputs()` holds no raster, so a tool that reads one stops before it makes anything: + // it isn't counted among those expected to run here. + if spec.params.iter().any(|p| p.required && matches!(p.kind, K::RasterLayer)) { + continue; + } tested += 1; let mut p = serde_json::Map::new(); for param in spec.params { diff --git a/crates/analysis/src/tools/check_dem.rs b/crates/analysis/src/tools/check_dem.rs new file mode 100644 index 0000000000..b79c3280d2 --- /dev/null +++ b/crates/analysis/src/tools/check_dem.rs @@ -0,0 +1,676 @@ +//! Check DEM (#3151): a point for each step, spike, pit and implausible value an elevation model +//! holds, and a summary of them. It reports and changes nothing: filling or smoothing is the +//! user's choice, with the tools made for it. +//! +//! A step is measured against the terrain on either side of it, on the same line: a drop between +//! two neighbours far larger than the drops just before and just after it is a break the slope +//! doesn't explain (a seam, a void filled at another level, a reservoir's edge in a surface +//! model), where a cliff, whose face goes on dropping, is not. Measured on real models: on a +//! 1-second SRTM tile of the Quadrilátero Ferrífero (S21W044), 82% of the 1,740 steps found lie +//! within a cell of where SRTM and the Copernicus 30 m model differ by more than 10 m (12% of all +//! cells do); on the ANADEM terrain model of the Serra do Brigadeiro (Mantiqueira) there are 16 a +//! million cells, on rock walls. Comparing with the eight neighbours' median drop instead flagged +//! 438 a million there. +use super::*; +use rustgis_data::loss::{LossCode, LossMessage}; +use rustgis_data::raster::Raster; +use std::ops::Range; +use std::sync::atomic::{AtomicUsize, Ordering}; + +/// The lowest and highest values an elevation model can hold, in metres: Check DEM's defaults, +/// and what a Shaded Relief's notice looks for in a band's statistics. Below the Dead Sea's shore +/// and the deepest mine, above Everest. +pub const PLAUSIBLE_ELEVATION: (f64, f64) = (-500.0, 9000.0); +/// The most findings written as points. The rest are counted in the summary only, so a model +/// covered with them still gives a layer that can be drawn and listed. +const MAX_POINTS: usize = 100_000; +/// About how many cells one item of the scan reads: enough to share out on threads, few enough +/// items that a small model is checked in a few looks at Cancel. +const BLOCK_CELLS: usize = 1 << 16; +/// The eight neighbours, as (column, row) steps. +const AROUND: [(i64, i64); 8] = [(-1, -1), (0, -1), (1, -1), (-1, 0), (1, 0), (-1, 1), (0, 1), (1, 1)]; + +/// What a finding is, as its `kind` field says it. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Kind { + Step, + Spike, + Pit, + OutOfRange, + FlatRun, +} + +impl Kind { + fn name(self) -> &'static str { + match self { + Kind::Step => "step", + Kind::Spike => "spike", + Kind::Pit => "pit", + Kind::OutOfRange => "out of range", + Kind::FlatRun => "flat run", + } + } + + /// The unit of its size: a height for the cells compared with their neighbours, a count of + /// cells for a run along a row. + fn unit(self) -> &'static str { + match self { + Kind::Step | Kind::Spike | Kind::Pit => "elevation", + Kind::OutOfRange | Kind::FlatRun => "cells", + } + } +} + +/// One finding: the cell it is placed on (a run's middle cell), what it is, its size and the +/// elevation there (a run's first value). +#[derive(Clone, Copy, Debug, PartialEq)] +struct Finding { + col: u32, + row: u32, + kind: Kind, + size: f64, + elevation: f64, +} + +/// The thresholds, as the parameters give them. +#[derive(Clone, Copy, Debug)] +struct Rules { + ratio: f64, + step: f64, + spike: f64, + low: f64, + high: f64, + run: usize, +} + +impl Rules { + fn read(p: &Json) -> Result { + let get = |key: &str, default: f64| -> Result { + match p.get(key) { + None | Some(Json::Null) => Ok(default), + Some(Json::String(s)) if s.trim().is_empty() => Ok(default), + Some(_) => num(p, key).ok_or_else(|| format!("{key} must be a number")), + } + }; + let ratio = get("stepRatio", 5.0)?; + let step = get("stepHeight", 20.0)?; + let spike = get("spikeHeight", 30.0)?; + let low = get("lowest", PLAUSIBLE_ELEVATION.0)?; + let high = get("highest", PLAUSIBLE_ELEVATION.1)?; + let run = get("runLength", 100.0)?; + if ratio < 1.0 { + return Err("stepRatio must be 1 or more: a step is a drop that many times the drops beside it".into()); + } + if step <= 0.0 || spike <= 0.0 { + return Err("stepHeight and spikeHeight must be more than 0".into()); + } + if low >= high { + return Err("lowest must be below highest".into()); + } + if run < 2.0 || run.fract() != 0.0 || run > f64::from(u32::MAX) { + return Err("runLength must be a whole number of cells, 2 or more".into()); + } + Ok(Rules { ratio, step, spike, low, high, run: run as usize }) + } + + /// Whether `v` is an elevation the model can hold. + fn holds(&self, v: f64) -> bool { + (self.low..=self.high).contains(&v) + } +} + +/// One band of the model, read through the rules. +struct Dem<'a> { + r: &'a Raster, + band: usize, + rules: Rules, +} + +impl Dem<'_> { + /// The value at a cell: `None` off the grid and for no-data. + fn value(&self, col: i64, row: i64) -> Option { + self.r.value(self.band, col, row).map(f64::from) + } + + /// The value at a cell when it is an elevation the model can hold: the neighbourhood rules + /// compare only these, so a hole of undeclared no-data isn't also a field of pits. + fn level(&self, col: i64, row: i64) -> Option { + self.value(col, row).filter(|v| self.rules.holds(*v)) + } + + /// How far `v`, at a cell, stands above (positive) or below the median of its eight + /// neighbours; `None` when one of them has no value it can hold. + fn above_median(&self, col: i64, row: i64, v: f64) -> Option { + let mut around = [0.0; 8]; + for (slot, (dc, dr)) in around.iter_mut().zip(AROUND) { + *slot = self.level(col + dc, row + dr)?; + } + around.sort_unstable_by(f64::total_cmp); + let [_, _, _, below, above, ..] = around; + Some(v - (below + above) / 2.0) + } + + /// The largest drop from a cell, at `v`, to a neighbour that is a step: more than the step + /// height and more than `ratio` times the drops beside it on the same line (from the cell + /// behind to this one, and from the neighbour to the one beyond it). + fn step(&self, col: i64, row: i64, v: f64) -> Option { + let mut largest: Option = None; + for (dc, dr) in AROUND { + let Some(next) = self.level(col + dc, row + dr) else { continue }; + let drop = v - next; + if drop <= self.rules.step { + continue; + } + let (Some(behind), Some(beyond)) = (self.level(col - dc, row - dr), self.level(col + 2 * dc, row + 2 * dr)) else { + continue; + }; + let beside = (behind - v).abs().max((next - beyond).abs()); + if drop > self.rules.ratio * beside && largest.is_none_or(|l| drop > l) { + largest = Some(drop); + } + } + largest + } +} + +/// What one block of rows holds, counted. +#[derive(Clone, Copy, Debug, Default)] +struct Counts { + /// Cells with a value, whether it can be held or not. + cells: u64, + /// Cells with a value the model can hold that lack a neighbour to compare with (at the edge, + /// or next to no-data or a value out of range): the spike and pit rule skips them. + unchecked: u64, + steps: u64, + spikes: u64, + pits: u64, + /// Cells found a step, a spike or a pit, each counted once. + compared: u64, + out_runs: u64, + out_cells: u64, + flat_runs: u64, + flat_cells: u64, +} + +impl Counts { + fn add(&mut self, o: &Counts) { + self.cells += o.cells; + self.unchecked += o.unchecked; + self.steps += o.steps; + self.spikes += o.spikes; + self.pits += o.pits; + self.compared += o.compared; + self.out_runs += o.out_runs; + self.out_cells += o.out_cells; + self.flat_runs += o.flat_runs; + self.flat_cells += o.flat_cells; + } + + fn findings(&self) -> u64 { + self.steps + self.spikes + self.pits + self.out_runs + self.flat_runs + } +} + +/// The lowest and highest values of `rows` the model can hold. +fn extremes(dem: &Dem<'_>, rows: Range) -> Result, String> { + let mut found: Option<(f64, f64)> = None; + let mut pace = crate::control::Pace::default(); + for row in rows { + for col in 0..dem.r.width { + if pace.stop(1) { + return Err(crate::control::Cancelled.into()); + } + if let Some(v) = dem.level(i64::from(col), i64::from(row)) { + found = Some(found.map_or((v, v), |(lo, hi)| (lo.min(v), hi.max(v)))); + } + } + } + Ok(found) +} + +/// A run along a row going on: where it started, and its first value. +type Run = Option<(u32, f64)>; + +/// Ends a run of values out of range at column `end`: always a finding. +fn close_out(run: &mut Run, end: u32, row: u32, n: &mut Counts, keep: &mut dyn FnMut(Finding)) { + if let Some((start, v)) = run.take() { + let len = end.saturating_sub(start); + n.out_runs += 1; + n.out_cells += u64::from(len); + keep(Finding { col: start + len / 2, row, kind: Kind::OutOfRange, size: f64::from(len), elevation: v }); + } +} + +/// Ends a run of one value at column `end`: a finding when it is as long as the rules ask and its +/// value is the band's lowest or highest (`ends`), where an undeclared no-data lies. A lake held +/// level, at any other value, is not one. +fn close_flat(run: &mut Run, end: u32, row: u32, at_least: usize, ends: Option<(f64, f64)>, n: &mut Counts, keep: &mut dyn FnMut(Finding)) { + if let Some((start, v)) = run.take() { + let len = end.saturating_sub(start); + if len as usize >= at_least && ends.is_some_and(|(lo, hi)| v == lo || v == hi) { + n.flat_runs += 1; + n.flat_cells += u64::from(len); + keep(Finding { col: start + len / 2, row, kind: Kind::FlatRun, size: f64::from(len), elevation: v }); + } + } +} + +/// Checks `rows`, counting what it finds and handing each finding to `keep`, in row order and +/// along each row. +fn scan(dem: &Dem<'_>, rows: Range, ends: Option<(f64, f64)>, keep: &mut dyn FnMut(Finding)) -> Result { + let mut n = Counts::default(); + let mut pace = crate::control::Pace::default(); + let rules = dem.rules; + for row in rows { + let r = i64::from(row); + let (mut out, mut flat): (Run, Run) = (None, None); + for col in 0..dem.r.width { + if pace.stop(1) { + return Err(crate::control::Cancelled.into()); + } + let c = i64::from(col); + let Some(v) = dem.value(c, r) else { + close_out(&mut out, col, row, &mut n, keep); + close_flat(&mut flat, col, row, rules.run, ends, &mut n, keep); + continue; + }; + n.cells += 1; + if !rules.holds(v) { + close_flat(&mut flat, col, row, rules.run, ends, &mut n, keep); + out.get_or_insert((col, v)); + continue; + } + close_out(&mut out, col, row, &mut n, keep); + if flat.is_some_and(|(_, f)| f != v) { + close_flat(&mut flat, col, row, rules.run, ends, &mut n, keep); + } + flat.get_or_insert((col, v)); + let mut hit = false; + match dem.above_median(c, r, v) { + None => n.unchecked += 1, + Some(d) if d > rules.spike => { + n.spikes += 1; + hit = true; + keep(Finding { col, row, kind: Kind::Spike, size: d, elevation: v }); + } + Some(d) if -d > rules.spike => { + n.pits += 1; + hit = true; + keep(Finding { col, row, kind: Kind::Pit, size: -d, elevation: v }); + } + Some(_) => {} + } + if let Some(drop) = dem.step(c, r, v) { + n.steps += 1; + hit = true; + keep(Finding { col, row, kind: Kind::Step, size: drop, elevation: v }); + } + n.compared += u64::from(hit); + } + close_out(&mut out, dem.r.width, row, &mut n, keep); + close_flat(&mut flat, dem.r.width, row, rules.run, ends, &mut n, keep); + } + Ok(n) +} + +/// Checks a band of an elevation model and writes a point for each finding. +pub(super) fn run(inp: &dyn Inputs, p: &Json) -> Result { + run_on(inp, p, None) +} + +/// [`run`] on `threads` threads (the shared count when `None`): the same layer and summary on any. +/// +/// Three passes over the rows, each in blocks of about [`BLOCK_CELLS`] cells on the threads, +/// looking at Cancel along each row: the band's lowest and highest values (for the flat runs), +/// then the findings, counted, kept as they come while fewer than [`MAX_POINTS`] are. Past that +/// many, which ones were kept depends on the threads, so a third pass takes the first +/// [`MAX_POINTS`] again, block by block from the top. Beyond the raster as it is held, memory is +/// the counts of each block and at most [`MAX_POINTS`] findings and their points. +pub(super) fn run_on(inp: &dyn Inputs, p: &Json, threads: Option) -> Result { + let name = s(p, "input"); + let r = inp.raster(name).ok_or("choose an elevation raster")?.raster; + r.require_coordinates()?; + let bands = zonal_bands(p.get("band").unwrap_or(&Json::Null), r.band_count())?; + let [band] = bands.as_slice() else { return Err("choose one band of elevations".into()) }; + let rules = Rules::read(p)?; + let dem = Dem { r, band: *band, rules }; + let per = (BLOCK_CELLS / (r.width as usize).max(1)).clamp(1, u32::MAX as usize) as u32; + let blocks: Vec> = (0..r.height).step_by(per as usize).map(|top| top..top.saturating_add(per).min(r.height)).collect(); + let cells = (r.width as usize).saturating_mul(r.height as usize); + let threads = threads.unwrap_or_else(|| crate::parallel::threads_for_rows(blocks.len(), cells, 0)); + crate::control::begin(blocks.len().saturating_mul(3)); + let ends = crate::parallel::try_map_on(&blocks, threads, || (), |_, _, rows| extremes(&dem, rows.clone()))? + .into_iter() + .flatten() + .reduce(|(lo, hi), (l, h)| (lo.min(l), hi.max(h))); + let taken = AtomicUsize::new(0); + let scanned = crate::parallel::try_map_on( + &blocks, + threads, + || (), + |_, _, rows| { + let mut kept = Vec::new(); + let n = scan(&dem, rows.clone(), ends, &mut |f| { + if taken.fetch_add(1, Ordering::Relaxed) < MAX_POINTS { + kept.push(f); + } + })?; + Ok::<_, String>((n, kept)) + }, + )?; + let mut total = Counts::default(); + for (n, _) in &scanned { + total.add(n); + } + let found = usize::try_from(total.findings()).unwrap_or(usize::MAX); + let findings: Vec = if found <= MAX_POINTS { + scanned.into_iter().flat_map(|(_, kept)| kept).collect() + } else { + // The first MAX_POINTS findings by block, scanned again for them alone. + let mut left = MAX_POINTS; + let mut plan = Vec::new(); + for (rows, (n, _)) in blocks.iter().zip(&scanned) { + let here = usize::try_from(n.findings()).unwrap_or(usize::MAX).min(left); + if here > 0 { + plan.push((rows.clone(), here)); + left -= here; + } + if left == 0 { + break; + } + } + drop(scanned); + let parts = crate::parallel::try_map_on( + &plan, + threads, + || (), + |_, _, (rows, take)| { + let mut kept = Vec::with_capacity(*take); + scan(&dem, rows.clone(), ends, &mut |f| { + if kept.len() < *take { + kept.push(f); + } + })?; + Ok::<_, String>(kept) + }, + )?; + parts.into_iter().flatten().collect() + }; + crate::control::finish(); + if total.cells == 0 { + return Err(format!("band {} of '{name}' has no values to check", band + 1)); + } + let fields = vec![ + Field::new("kind", FieldType::Text), + Field::new("size", FieldType::Double), + Field::new("unit", FieldType::Text), + Field::new("elevation", FieldType::Double), + ]; + let mut out = Dataset::new(out_name(p, format!("{name}_CheckDEM")), GeometryType::Point, fields); + let mut placeless = 0usize; + let mut pace = crate::control::Pace::default(); + for f in &findings { + if pace.stop(64) { + return Err(crate::control::Cancelled.into()); + } + let centre = r.transform.to_world(f64::from(f.col) + 0.5, f64::from(f.row) + 0.5); + let Some(at) = r.transformer().to_lonlat(centre) else { + placeless += 1; + continue; + }; + out.push_next( + Some(Geometry::Point(at)), + vec![Value::Text(f.kind.name().into()), Value::Float(f.size), Value::Text(f.kind.unit().into()), Value::Float(f.elevation)], + ); + } + let affected = total.compared + total.out_cells + total.flat_cells; + let mut messages = vec![format!( + "Checked {} cell(s) of band {} of '{name}': {} step(s), {} spike(s), {} pit(s), {} run(s) of values out of range ({} cells), {} flat run(s) at the band's lowest or highest value ({} cells); {:.3}% of the cells with a value are affected", + total.cells, + band + 1, + total.steps, + total.spikes, + total.pits, + total.out_runs, + total.out_cells, + total.flat_runs, + total.flat_cells, + affected as f64 * 100.0 / total.cells as f64, + )]; + if total.unchecked > 0 { + messages.push(format!( + "{} cell(s) at the edge, or next to no-data or a value out of range, lack a neighbour to compare with: the spike and pit rule skips them, and the step rule the directions it can't follow", + total.unchecked + )); + } + if let Some((fw, fh)) = r.overview { + messages.push(format!( + "'{name}' is held as an overview of its file ({} × {} of its {fw} × {fh} cells): a step or spike a cell or two wide at full resolution may not show in it", + r.width, r.height + )); + } + let mut losses = Vec::new(); + if found > findings.len() { + losses.push(LossMessage { + code: LossCode::DroppedOverLimit, + text: format!( + "{} of the {found} findings are counted but not written as points: the layer holds the first {}, from the top row down. Raise the thresholds, or check part of the model, to see the rest", + found - findings.len(), + findings.len() + ), + }); + } + if placeless > 0 { + losses.push(LossMessage { + code: LossCode::DroppedFeature, + text: format!("{placeless} finding(s) whose cell couldn't be placed in longitude and latitude were left out of the layer"), + }); + } + Ok(ToolResult { output: Output::Layer(out), messages, losses }) +} + +#[cfg(test)] +mod tests { + use super::*; + use rustgis_data::raster::{ColorHint, GeoTransform}; + + struct One<'a>(&'a Raster); + + impl Inputs for One<'_> { + fn dataset(&self, _: &str) -> Option<&Dataset> { + None + } + fn selection(&self, _: &str) -> &[usize] { + &[] + } + fn raster(&self, layer: &str) -> Option> { + (layer == "dem").then_some(crate::RasterInput { raster: self.0, path: None, embedded: None }) + } + } + + /// A 30 m grid in UTM 23S of `width × height` cells, each `z(col, row)`. + fn dem(width: u32, height: u32, z: impl Fn(u32, u32) -> f32) -> Raster { + let values = (0..height).flat_map(|row| (0..width).map(move |col| (col, row))).map(|(c, r)| z(c, r)).collect(); + let transform = GeoTransform { origin_x: 600_000., origin_y: 7_750_000., pixel_width: 30., pixel_height: -30. }; + Raster::new("dem", width, height, vec![values], transform, Crs::Epsg(32723), Some(-9999.), ColorHint::Gray, "Float32").unwrap() + } + + /// A slope with a little roughness. + fn rough(col: u32, row: u32) -> f32 { + 800.0 + 3.0 * row as f32 + ((col * 7 + row * 13) % 5) as f32 + } + + /// Mountain-like ground with no defect: [`rough`] with a round hill and a steep face (a 40 m + /// drop a cell for six cells). + fn clean(col: u32, row: u32) -> f32 { + let (x, y) = (col as f32, row as f32); + let hill = 300.0 * (-((x - 20.0).powi(2) + (y - 20.0).powi(2)) / 60.0).exp(); + let face = 40.0 * (x - 30.0).clamp(0.0, 6.0); + rough(col, row) + hill - face + } + + type Row = (String, f64, f64, Coord); + + fn check(r: &Raster, p: Json) -> (ToolResult, Vec) { + let mut p = p; + p["input"] = Json::from("dem"); + let result = run(&One(r), &p).unwrap(); + let Output::Layer(out) = &result.output else { panic!("a point layer") }; + let rows = out + .features + .iter() + .map(|f| { + let Value::Text(kind) = &f.attrs[0] else { panic!("a kind") }; + let (Value::Float(size), Value::Float(z)) = (&f.attrs[1], &f.attrs[3]) else { panic!("numbers") }; + let Some(Geometry::Point(at)) = f.geometry else { panic!("a point") }; + (kind.clone(), *size, *z, at) + }) + .collect(); + (result, rows) + } + + fn kinds(rows: &[Row], kind: &str) -> usize { + rows.iter().filter(|r| r.0 == kind).count() + } + + #[test] + fn clean_mountain_ground_has_no_findings() { + let r = dem(60, 50, clean); + let (result, rows) = check(&r, serde_json::json!({})); + assert_eq!(rows.len(), 0, "{rows:?}"); + assert!(result.losses.is_empty()); + let summary = &result.messages[0]; + assert!(summary.starts_with("Checked 3000 cell(s) of band 1 of 'dem': 0 step(s), 0 spike(s), 0 pit(s)"), "{summary}"); + assert!(summary.ends_with("0.000% of the cells with a value are affected"), "{summary}"); + // The 216 cells of the edge lack neighbours, and that is said. + assert!(result.messages[1].starts_with("216 cell(s) at the edge"), "{:?}", result.messages); + } + + #[test] + fn a_seam_is_a_line_of_steps_on_its_high_side() { + // The right part 25 m lower than the left, as two tiles mosaicked at different levels. + let r = dem(40, 30, |c, r| rough(c, r) - if c >= 12 { 25.0 } else { 0.0 }); + let (result, rows) = check(&r, serde_json::json!({})); + // Every row but the first and last, whose diagonals go off the grid: those still have + // the step across the row, so all 30 are found. + assert_eq!(kinds(&rows, "step"), 30, "{rows:?}"); + assert_eq!(rows.len(), 30, "{rows:?}"); + // Each on the last cell of the high side, one a row. + let cells: Vec<_> = rows.iter().map(|(_, _, _, at)| r.pixel_at(*at).unwrap()).collect(); + assert_eq!(cells, (0..30).map(|row| (11, row)).collect::>()); + assert!(rows.iter().all(|(_, size, _, _)| (20.0..33.0).contains(size)), "{rows:?}"); + assert!(result.messages[0].contains(": 30 step(s), 0 spike(s)"), "{}", result.messages[0]); + // Below the step height, it isn't one. + let (_, rows) = check(&r, serde_json::json!({"stepHeight": 40})); + assert_eq!(rows.len(), 0); + } + + #[test] + fn spikes_and_pits_stand_off_the_median_of_their_neighbours() { + let r = dem(30, 30, |c, r| match (c, r) { + (10, 10) => clean(c, r) + 50.0, + (20, 15) => clean(c, r) - 45.0, + _ => clean(c, r), + }); + let (_, rows) = check(&r, serde_json::json!({})); + assert_eq!(kinds(&rows, "spike"), 1, "{rows:?}"); + assert_eq!(kinds(&rows, "pit"), 1, "{rows:?}"); + // Neither is also a step, nor are its neighbours: the drops beside them are as large. + assert_eq!(rows.len(), 2, "{rows:?}"); + let spike = rows.iter().find(|r| r.0 == "spike").unwrap(); + assert!((45.0..55.0).contains(&spike.1), "{spike:?}"); + assert!(rows.iter().find(|r| r.0 == "pit").is_some_and(|p| (40.0..50.0).contains(&p.1)), "{rows:?}"); + let (_, rows) = check(&r, serde_json::json!({"spikeHeight": 60})); + assert_eq!(rows.len(), 0); + } + + #[test] + fn values_out_of_range_and_flat_runs_at_the_ends_are_runs() { + // An undeclared no-data of -32768 five cells long, a sea at 0 (the band's lowest) along + // the last row, and a lake held level at 809 (inside the range): only the first two count. + let r = dem(120, 12, |c, r| match (c, r) { + (40..45, 5) => -32768.0, + (_, 11) => 0.0, + (60..120, 3) => 809.0, + _ => rough(c, r), + }); + let (result, rows) = check(&r, serde_json::json!({})); + let out: Vec<_> = rows.iter().filter(|r| r.0 == "out of range").collect(); + assert_eq!(out.len(), 1, "{rows:?}"); + assert_eq!((out[0].1, out[0].2), (5.0, -32768.0)); + let flat: Vec<_> = rows.iter().filter(|r| r.0 == "flat run").collect(); + assert_eq!(flat.len(), 1, "{rows:?}"); + assert_eq!((flat[0].1, flat[0].2), (120.0, 0.0)); + // The out-of-range cells aren't compared, so their neighbours aren't spikes or pits. + assert_eq!(kinds(&rows, "spike") + kinds(&rows, "pit"), 0, "{rows:?}"); + assert!(result.messages[0].contains("1 run(s) of values out of range (5 cells), 1 flat run(s)"), "{}", result.messages[0]); + // A run shorter than asked is not one, nor a value inside a wider range. + let (_, rows) = check(&r, serde_json::json!({"runLength": 121})); + assert_eq!(kinds(&rows, "flat run"), 0); + let (_, rows) = check(&r, serde_json::json!({"lowest": -40000})); + assert_eq!(kinds(&rows, "out of range"), 0); + } + + #[test] + fn past_the_point_limit_the_first_findings_are_kept_alike_on_any_threads() { + // A checkerboard of 0 and 100 m: every cell inside the edge a spike or a pit. + let r = dem(400, 400, |c, r| if (c + r) % 2 == 0 { 100.0 } else { 0.0 }); + let p = serde_json::json!({"input": "dem"}); + let layers: Vec<_> = [1, 2, 7] + .into_iter() + .map(|threads| { + let result = run_on(&One(&r), &p, Some(threads)).unwrap(); + assert_eq!(result.losses.len(), 1); + assert!(result.losses[0].text.starts_with("58404 of the 158404 findings"), "{}", result.losses[0].text); + let Output::Layer(out) = result.output else { panic!("a layer") }; + out.features + }) + .collect(); + assert_eq!(layers[0].len(), MAX_POINTS); + assert!(layers.iter().all(|l| *l == layers[0])); + } + + #[test] + fn the_same_findings_on_any_threads_below_the_limit() { + let r = + dem(300, 260, |c, r| clean(c % 60, r % 50) - if c >= 150 { 30.0 } else { 0.0 } + if (c * r) % 997 == 3 { 60.0 } else { 0.0 }); + let p = serde_json::json!({"input": "dem"}); + let runs: Vec<_> = [1, 3, 8] + .into_iter() + .map(|threads| { + let result = run_on(&One(&r), &p, Some(threads)).unwrap(); + let Output::Layer(out) = result.output else { panic!("a layer") }; + (out.features, result.messages) + }) + .collect(); + assert!(!runs[0].0.is_empty()); + assert!(runs.iter().all(|r| *r == runs[0])); + } + + #[test] + fn the_range_s_defaults_are_the_plausible_elevations() { + let spec = crate::tool("checkDem").unwrap(); + let default = |n: &str| spec.params.iter().find(|p| p.name == n).unwrap().default.parse::().unwrap(); + assert_eq!((default("lowest"), default("highest")), PLAUSIBLE_ELEVATION); + } + + #[test] + fn thresholds_that_make_no_sense_are_refused() { + let r = dem(10, 10, clean); + for (p, says) in [ + (serde_json::json!({"stepRatio": 0.5}), "stepRatio must be 1 or more"), + (serde_json::json!({"stepHeight": 0}), "must be more than 0"), + (serde_json::json!({"lowest": 10, "highest": 10}), "lowest must be below highest"), + (serde_json::json!({"runLength": 1.5}), "runLength must be a whole number"), + (serde_json::json!({"spikeHeight": "high"}), "spikeHeight must be a number"), + (serde_json::json!({"band": 2}), "band"), + ] { + let mut p = p; + p["input"] = Json::from("dem"); + let e = run(&One(&r), &p).unwrap_err(); + assert!(e.contains(says), "{e}"); + } + let empty = dem(5, 5, |_, _| -9999.0); + assert!(run(&One(&empty), &serde_json::json!({"input": "dem"})).unwrap_err().contains("has no values to check")); + } +} diff --git a/crates/engine/src/cmd/raster.rs b/crates/engine/src/cmd/raster.rs index 20a63d8b7f..edc99855f7 100644 --- a/crates/engine/src/cmd/raster.rs +++ b/crates/engine/src/cmd/raster.rs @@ -1077,7 +1077,36 @@ fn symbology(s: &mut Session, p: &Value) -> CmdResult { rl.style.stretch = Stretch::default(); } Ok(()) - }) + })?; + relief_notice(s, id, &r); + Ok(Value::Null) +} + +/// Says when a Shaded Relief is drawn from a band holding values no elevation has (#3151): below +/// or above [`rustgis_analysis::PLAUSIBLE_ELEVATION`], such as a no-data of -32768 the file +/// doesn't declare, which the relief draws as cliffs. A look at the band's statistics; Check DEM +/// says where the values are. +fn relief_notice(s: &mut Session, id: u32, r: &Raster) { + let (lowest, highest) = rustgis_analysis::PLAUSIBLE_ELEVATION; + let Some(l) = s.map().layer(id) else { return }; + let Some(RasterRenderer::ShadedRelief { band, .. }) = l.raster.as_ref().map(|rl| &rl.style.renderer) else { return }; + let Some(stats) = r.bands.get(*band).map(|b| &b.stats).filter(|st| st.count > 0) else { return }; + let mut odd = Vec::new(); + if stats.min < lowest { + odd.push(format!("as low as {}", stats.min)); + } + if stats.max > highest { + odd.push(format!("as high as {}", stats.max)); + } + if odd.is_empty() { + return; + } + let text = format!( + "'{}' holds values no elevation has ({}, outside {lowest} to {highest}): its relief draws them as cliffs. Check DEM (checkDem) finds where they are; declare them as no-data, or hide them with raster.mask", + l.name, + odd.join(" and ") + ); + s.notify(text, false); } /// A Shaded Relief's `"shadowSoftness"` (see `raster.symbology`), `v` being the number given, if diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 228a95f994..32c16f8ccc 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -7702,6 +7702,81 @@ fn custom_projections_switch_keep_scale_query_and_render() { } } +/// A Shaded Relief drawn from a band holding values no elevation has (an undeclared no-data of +/// -32768, a height of 65535) says so and names them; a clean band, or one whose no-data is +/// declared, says nothing (#3151). +#[test] +fn shaded_relief_names_values_no_elevation_has() { + let dir = std::env::temp_dir().join(format!("rustgis-engine-relief-values-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let mut s = Session::new(Project::default()); + for (name, head, values, said) in [ + ( + "hole.asc", + "", + "812 815 -32768 +809 811 814 +806 808 810", + Some("as low as -32768"), + ), + ( + "high.asc", + "", + "812 815 65535 +809 811 814 +806 808 810", + Some("as high as 65535"), + ), + ( + "clean.asc", + "", + "812 815 818 +809 811 814 +806 808 810", + None, + ), + ( + "declared.asc", + "NODATA_value -32768 +", + "812 815 -32768 +809 811 814 +806 808 810", + None, + ), + ] { + let path = dir.join(name); + std::fs::write( + &path, + format!( + "ncols 3 +nrows 3 +xllcorner 10 +yllcorner 40 +cellsize 0.001 +{head}{values}" + ), + ) + .unwrap(); + let id = s.run("layer.addData", &json!({"path": path})).unwrap()["layer"].as_u64().unwrap(); + let mark = s.notice_mark(); + s.run("raster.symbology", &json!({"layer": id, "type": "shadedRelief"})).unwrap(); + let notice = s.notices_since(mark).iter().find(|n| n.text.contains("holds values no elevation has")).map(|n| n.text.clone()); + match said { + Some(values) => { + let notice = notice.unwrap_or_else(|| panic!("{name}: {:?}", s.notices_since(mark))); + assert!(notice.contains(values) && notice.contains("Check DEM (checkDem)"), "{notice}"); + } + None => assert_eq!(notice, None, "{name}"), + } + // Another symbology says nothing of it. + let mark = s.notice_mark(); + s.run("raster.symbology", &json!({"layer": id, "type": "stretch"})).unwrap(); + assert!(!s.notices_since(mark).iter().any(|n| n.text.contains("no elevation has")), "{name}"); + } + std::fs::remove_dir_all(dir).unwrap(); +} + /// Shaded Relief's cast shadows: set, kept when left out, clamped, a new one without; saved with /// the project only when there are some, and drawn in an export (waited for). #[test] diff --git a/crates/engine/src/tests/cancellation.rs b/crates/engine/src/tests/cancellation.rs index d53a184630..bf5d801319 100644 --- a/crates/engine/src/tests/cancellation.rs +++ b/crates/engine/src/tests/cancellation.rs @@ -372,6 +372,7 @@ pub(super) fn long_commands(boundaries: bool) { ("kernelDensity", json!({"input": "Cities", "crs": "EPSG:3857", "pixelSize": if boundaries { 2000 } else { 1000000 }})), ("kriging", json!({"input": "Cities", "field": "pop_max", "pixelSize": if boundaries { 0.01 } else { 1.0 }})), ("tabulateArea", json!({"raster": dem, "zones": "Countries"})), + ("checkDem", json!({"input": dem})), ("tabulateIntersection", json!({"zones": "Countries", "classes": "Squares", "includeEmptyZones": true})), ("serviceArea", json!({"network": "Rivers", "facilities": "Cities", "breaks": "50", "snapDistance": 100000})), ("odCostMatrix", json!({"network": "Rivers", "origins": "Cities", "destinations": "Cities", "count": 1, "snapDistance": 100000})), diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index 260edd831d..44f1b34d77 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -469,6 +469,7 @@ Use these ids in `gp.run`'s `tool` parameter (`gp.tools` lists the available too | Ordinary Kriging | `kriging` | Analysis › Interpolation | | Zonal Statistics | `zonalStats` | Analysis › Raster | | Tabulate Area | `tabulateArea` | Analysis › Raster | +| Check DEM | `checkDem` | Analysis › Terrain | | Kernel Density | `kernelDensity` | Analysis › Density | **Raster to PMTiles** (`rasterToPmtiles`) writes Web Mercator PNG tiles using the raster's current @@ -2476,6 +2477,48 @@ the background with progress and Cancel; independent zones use several threads w mask memory budget. Each zone's mask is filled as one step before its cells are scanned, so Cancel can wait for that mask fill to finish. +## Checking an elevation model + +**Check DEM** (`checkDem`) looks for what a relief shading would show glaring and a stretched grey +raster hides: seams, stripes, spikes and pits, cliffs at the edge of a reservoir in a surface +model, and no-data the file doesn't declare. It writes a point layer, one point per finding, with +`kind`, `size`, `unit` (`elevation` for a height, `cells` for a run) and the `elevation` there, +and a summary of the counts per kind and the share of the model's cells affected. It reports and +changes nothing: fill or smooth with the tools made for that, or mask the values with +`raster.mask`. + +- **step**: a cell whose drop to a neighbour is more than `stepHeight` (default 20) and more than + `stepRatio` (default 5) times the drops just before and just after it on the same line (from + the cell behind it, and from the neighbour to the one beyond). A cliff, whose face goes on + dropping, is not one; a seam between two tiles at different levels is. Its `size` is the drop. +- **spike** and **pit**: a cell more than `spikeHeight` (default 30) above or below the median of + its eight neighbours. Its `size` is how far. +- **out of range**: a run along a row of values below `lowest` (default −500) or above `highest` + (default 9,000), such as −32768 or −9999 written for no-data. Its `size` is the run's length in + cells. Those values aren't compared with their neighbours, so a hole of them isn't also a field + of pits. +- **flat run**: a run of at least `runLength` (default 100) cells along a row holding the band's + lowest or highest value: a no-data of 0, or the sea held at 0. A lake held level at any other + value is not one. + +Thresholds are in the model's elevation unit; the defaults are metres. Cells at the edge, or next +to no-data or a value out of range, lack the neighbours the spike and pit rule compares, and the +summary says how many. The layer holds the first 100,000 findings, from the top row down; past +that the rest are counted in the summary and a notice. A model held as an overview of a larger +file is checked as it is held, and a notice says so. + +The defaults were set on real models (#3151): on a 1-second SRTM tile of the Quadrilátero +Ferrífero, 82% of the steps and 88% of the spikes and pits found lie within a cell of where SRTM +and the Copernicus 30 m model differ by more than 10 m (12% of all cells do), and the Copernicus tile shows its steps +along a reservoir's shore; on the ANADEM terrain model of the Serra do Brigadeiro there are 16 +steps a million cells, on rock walls, and no spikes or pits. + +```json +{"tool":"checkDem","params":{"input":"srtm","stepHeight":10,"output":"srtm_findings"}} +``` + +On the desktop it runs in the background with progress and Cancel, on several threads. + ## Zonal statistics and polygon clipping Open **Zonal Statistics** through Command Search, or choose it in the Workflows pane. diff --git a/docs/user-guide/data.md b/docs/user-guide/data.md index b930ff1f48..fc37fb8f9a 100644 --- a/docs/user-guide/data.md +++ b/docs/user-guide/data.md @@ -1733,6 +1733,11 @@ stretch, and an opaque black cell still counts. The alpha band's own statistics alpha with a value, see-through ones included. **Change Detection** gives no-data where either image is see-through. +**Shaded Relief** names the values its band holds that no elevation has, below −500 or above +9,000 (from the band's statistics), such as a no-data of −32768 the file doesn't declare, which the +relief draws as cliffs. Check DEM (`checkDem`, see +[Checking an elevation model](analysis.md#checking-an-elevation-model)) finds where they are. + **Cast shadows**, on a Shaded Relief layer (`raster.symbology` `"shadow"`, 0 to 1), darkens the slopes the terrain hides from the sun as well as those facing away from it: a valley behind a ridge is in shadow, with a soft edge. Only the direct light is darkened: a slope in full shadow keeps the From fb0fb102345ad172e980f10ce5aa0e10d016c966 Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Sat, 28 Nov 2026 15:24:57 -0300 Subject: [PATCH 2/5] refactor(analysis): keep Check DEM to its steps in this part (#3151) The pull request is split to stay near 400 changed lines. This part keeps the tool with its step rule, the point cap and the threads. Spikes and pits, implausible values and flat runs, and the Shaded Relief notice come in their own pull requests. Co-Authored-By: Claude Opus 5.5 --- crates/analysis/src/lib.rs | 5 +- crates/analysis/src/tools.rs | 37 +- crates/analysis/src/tools/check_dem.rs | 594 ++++++------------------- crates/engine/src/cmd/raster.rs | 31 +- crates/engine/src/tests.rs | 75 ---- docs/user-guide/analysis.md | 53 +-- docs/user-guide/data.md | 5 - 7 files changed, 152 insertions(+), 648 deletions(-) diff --git a/crates/analysis/src/lib.rs b/crates/analysis/src/lib.rs index 5cce7f9396..3d112a3576 100644 --- a/crates/analysis/src/lib.rs +++ b/crates/analysis/src/lib.rs @@ -48,9 +48,8 @@ pub use density::{ pub use parallel::scratch_budget; pub use parameters::StatisticList; pub use tools::{ - PLAUSIBLE_ELEVATION, SimplifyNotes, TOOLS, find_field_case_insensitive, holds_coordinates, in_its_units, layer_raster_crs, - max_buffer_bytes, min_pad, param_applies, past_pole, points_from, points_in, projected_crs, raster_crs, raster_crs_in, - simplify_geometry, zonal_bands, + SimplifyNotes, TOOLS, find_field_case_insensitive, holds_coordinates, in_its_units, layer_raster_crs, max_buffer_bytes, min_pad, + param_applies, past_pole, points_from, points_in, projected_crs, raster_crs, raster_crs_in, simplify_geometry, zonal_bands, }; use rustgis_data::Dataset; diff --git a/crates/analysis/src/tools.rs b/crates/analysis/src/tools.rs index bcbcb75785..806062a371 100644 --- a/crates/analysis/src/tools.rs +++ b/crates/analysis/src/tools.rs @@ -1,7 +1,6 @@ //! The tools. mod check_dem; -pub use check_dem::PLAUSIBLE_ELEVATION; mod check_geometry; mod geometry; mod network_analysis; @@ -1142,7 +1141,7 @@ pub static TOOLS: &[ToolSpec] = &[ id: "checkDem", name: "Check DEM", toolbox: "Analysis › Terrain", - summary: "Finds steps, spikes, pits and implausible values in an elevation model, as points with a summary; it changes nothing.", + summary: "Finds steps in an elevation model (seams, voids filled at another level, reservoir edges), as points with a summary; it changes nothing.", params: &[ P { name: "input", @@ -1150,7 +1149,7 @@ pub static TOOLS: &[ToolSpec] = &[ kind: K::RasterLayer, required: true, default: "", - help: "The elevation model to check. Thresholds are in its elevation unit (metres by default).", + help: "The elevation model to check. Heights are in its elevation unit (metres by default).", }, P { name: "band", label: "Band", kind: K::Number, required: false, default: "1", help: "1-based band of elevations." }, P { @@ -1169,38 +1168,6 @@ pub static TOOLS: &[ToolSpec] = &[ default: "20", help: "The least drop that is a step.", }, - P { - name: "spikeHeight", - label: "Spike Height", - kind: K::Number, - required: false, - default: "30", - help: "A cell this far above the median of its eight neighbours is a spike, this far below a pit.", - }, - P { - name: "lowest", - label: "Lowest Elevation", - kind: K::Number, - required: false, - default: "-500", - help: "Values below this are out of range (a no-data such as -32768 or -9999 the file doesn't declare).", - }, - P { - name: "highest", - label: "Highest Elevation", - kind: K::Number, - required: false, - default: "9000", - help: "Values above this are out of range.", - }, - P { - name: "runLength", - label: "Flat Run Length", - kind: K::Number, - required: false, - default: "100", - help: "A run of this many cells along a row holding the band's lowest or highest value is a flat run: an undeclared no-data, or water held level at the edge of the range.", - }, P { name: "output", label: "Output Name", kind: K::Text, required: false, default: "", help: "Output point layer name." }, ], run: check_dem::run, diff --git a/crates/analysis/src/tools/check_dem.rs b/crates/analysis/src/tools/check_dem.rs index b79c3280d2..1e93aab6cd 100644 --- a/crates/analysis/src/tools/check_dem.rs +++ b/crates/analysis/src/tools/check_dem.rs @@ -1,26 +1,19 @@ -//! Check DEM (#3151): a point for each step, spike, pit and implausible value an elevation model -//! holds, and a summary of them. It reports and changes nothing: filling or smoothing is the -//! user's choice, with the tools made for it. +//! Check DEM (#3151): a point for each step in an elevation model, and a summary of them. It +//! reports and changes nothing: filling or smoothing is the user's choice. //! -//! A step is measured against the terrain on either side of it, on the same line: a drop between +//! A step is measured against the ground on either side of it, on the same line: a drop between //! two neighbours far larger than the drops just before and just after it is a break the slope //! doesn't explain (a seam, a void filled at another level, a reservoir's edge in a surface -//! model), where a cliff, whose face goes on dropping, is not. Measured on real models: on a -//! 1-second SRTM tile of the Quadrilátero Ferrífero (S21W044), 82% of the 1,740 steps found lie -//! within a cell of where SRTM and the Copernicus 30 m model differ by more than 10 m (12% of all -//! cells do); on the ANADEM terrain model of the Serra do Brigadeiro (Mantiqueira) there are 16 a -//! million cells, on rock walls. Comparing with the eight neighbours' median drop instead flagged -//! 438 a million there. +//! model), where a cliff, whose face goes on dropping, is not. On a 1-second SRTM tile of the +//! Quadrilátero Ferrífero (S21W044), 82% of its 1,740 steps lie within a cell of where SRTM and +//! the Copernicus 30 m model differ by more than 10 m (12% of all cells do); the ANADEM terrain +//! model of the Serra do Brigadeiro has 16 a million cells, on rock walls, where comparing with +//! the eight neighbours' median drop instead flagged 438. use super::*; use rustgis_data::loss::{LossCode, LossMessage}; -use rustgis_data::raster::Raster; use std::ops::Range; use std::sync::atomic::{AtomicUsize, Ordering}; -/// The lowest and highest values an elevation model can hold, in metres: Check DEM's defaults, -/// and what a Shaded Relief's notice looks for in a band's statistics. Below the Dead Sea's shore -/// and the deepest mine, above Everest. -pub const PLAUSIBLE_ELEVATION: (f64, f64) = (-500.0, 9000.0); /// The most findings written as points. The rest are counted in the summary only, so a model /// covered with them still gives a layer that can be drawn and listed. const MAX_POINTS: usize = 100_000; @@ -30,285 +23,84 @@ const BLOCK_CELLS: usize = 1 << 16; /// The eight neighbours, as (column, row) steps. const AROUND: [(i64, i64); 8] = [(-1, -1), (0, -1), (1, -1), (-1, 0), (1, 0), (-1, 1), (0, 1), (1, 1)]; -/// What a finding is, as its `kind` field says it. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum Kind { - Step, - Spike, - Pit, - OutOfRange, - FlatRun, -} - -impl Kind { - fn name(self) -> &'static str { - match self { - Kind::Step => "step", - Kind::Spike => "spike", - Kind::Pit => "pit", - Kind::OutOfRange => "out of range", - Kind::FlatRun => "flat run", - } - } - - /// The unit of its size: a height for the cells compared with their neighbours, a count of - /// cells for a run along a row. - fn unit(self) -> &'static str { - match self { - Kind::Step | Kind::Spike | Kind::Pit => "elevation", - Kind::OutOfRange | Kind::FlatRun => "cells", - } - } -} - -/// One finding: the cell it is placed on (a run's middle cell), what it is, its size and the -/// elevation there (a run's first value). +/// One finding: its cell, its size (the drop) and the elevation there. #[derive(Clone, Copy, Debug, PartialEq)] struct Finding { col: u32, row: u32, - kind: Kind, size: f64, elevation: f64, } -/// The thresholds, as the parameters give them. -#[derive(Clone, Copy, Debug)] -struct Rules { - ratio: f64, - step: f64, - spike: f64, - low: f64, - high: f64, - run: usize, -} - -impl Rules { - fn read(p: &Json) -> Result { - let get = |key: &str, default: f64| -> Result { - match p.get(key) { - None | Some(Json::Null) => Ok(default), - Some(Json::String(s)) if s.trim().is_empty() => Ok(default), - Some(_) => num(p, key).ok_or_else(|| format!("{key} must be a number")), - } - }; - let ratio = get("stepRatio", 5.0)?; - let step = get("stepHeight", 20.0)?; - let spike = get("spikeHeight", 30.0)?; - let low = get("lowest", PLAUSIBLE_ELEVATION.0)?; - let high = get("highest", PLAUSIBLE_ELEVATION.1)?; - let run = get("runLength", 100.0)?; - if ratio < 1.0 { - return Err("stepRatio must be 1 or more: a step is a drop that many times the drops beside it".into()); - } - if step <= 0.0 || spike <= 0.0 { - return Err("stepHeight and spikeHeight must be more than 0".into()); - } - if low >= high { - return Err("lowest must be below highest".into()); - } - if run < 2.0 || run.fract() != 0.0 || run > f64::from(u32::MAX) { - return Err("runLength must be a whole number of cells, 2 or more".into()); - } - Ok(Rules { ratio, step, spike, low, high, run: run as usize }) - } - - /// Whether `v` is an elevation the model can hold. - fn holds(&self, v: f64) -> bool { - (self.low..=self.high).contains(&v) - } -} - -/// One band of the model, read through the rules. +/// One band of the model, and the step thresholds the parameters give. struct Dem<'a> { - r: &'a Raster, + r: &'a rustgis_data::raster::Raster, band: usize, - rules: Rules, + ratio: f64, + height: f64, } impl Dem<'_> { /// The value at a cell: `None` off the grid and for no-data. - fn value(&self, col: i64, row: i64) -> Option { - self.r.value(self.band, col, row).map(f64::from) - } - - /// The value at a cell when it is an elevation the model can hold: the neighbourhood rules - /// compare only these, so a hole of undeclared no-data isn't also a field of pits. fn level(&self, col: i64, row: i64) -> Option { - self.value(col, row).filter(|v| self.rules.holds(*v)) - } - - /// How far `v`, at a cell, stands above (positive) or below the median of its eight - /// neighbours; `None` when one of them has no value it can hold. - fn above_median(&self, col: i64, row: i64, v: f64) -> Option { - let mut around = [0.0; 8]; - for (slot, (dc, dr)) in around.iter_mut().zip(AROUND) { - *slot = self.level(col + dc, row + dr)?; - } - around.sort_unstable_by(f64::total_cmp); - let [_, _, _, below, above, ..] = around; - Some(v - (below + above) / 2.0) + self.r.value(self.band, col, row).map(f64::from) } /// The largest drop from a cell, at `v`, to a neighbour that is a step: more than the step /// height and more than `ratio` times the drops beside it on the same line (from the cell - /// behind to this one, and from the neighbour to the one beyond it). - fn step(&self, col: i64, row: i64, v: f64) -> Option { - let mut largest: Option = None; + /// behind to this one, and from the neighbour to the one beyond it). With it, whether every + /// line could be followed: `false` at the edge and next to no-data. + fn step(&self, col: i64, row: i64, v: f64) -> (Option, bool) { + let (mut largest, mut whole): (Option, bool) = (None, true); for (dc, dr) in AROUND { - let Some(next) = self.level(col + dc, row + dr) else { continue }; - let drop = v - next; - if drop <= self.rules.step { - continue; - } - let (Some(behind), Some(beyond)) = (self.level(col - dc, row - dr), self.level(col + 2 * dc, row + 2 * dr)) else { + let (Some(next), Some(behind), Some(beyond)) = + (self.level(col + dc, row + dr), self.level(col - dc, row - dr), self.level(col + 2 * dc, row + 2 * dr)) + else { + whole = false; continue; }; - let beside = (behind - v).abs().max((next - beyond).abs()); - if drop > self.rules.ratio * beside && largest.is_none_or(|l| drop > l) { + let (drop, beside) = (v - next, (behind - v).abs().max((next - beyond).abs())); + if drop > self.height && drop > self.ratio * beside && largest.is_none_or(|l| drop > l) { largest = Some(drop); } } - largest + (largest, whole) } } -/// What one block of rows holds, counted. +/// What one block of rows holds, counted: cells with a value, those with a line that couldn't be +/// followed, and steps. #[derive(Clone, Copy, Debug, Default)] struct Counts { - /// Cells with a value, whether it can be held or not. cells: u64, - /// Cells with a value the model can hold that lack a neighbour to compare with (at the edge, - /// or next to no-data or a value out of range): the spike and pit rule skips them. - unchecked: u64, + partial: u64, steps: u64, - spikes: u64, - pits: u64, - /// Cells found a step, a spike or a pit, each counted once. - compared: u64, - out_runs: u64, - out_cells: u64, - flat_runs: u64, - flat_cells: u64, } impl Counts { - fn add(&mut self, o: &Counts) { - self.cells += o.cells; - self.unchecked += o.unchecked; - self.steps += o.steps; - self.spikes += o.spikes; - self.pits += o.pits; - self.compared += o.compared; - self.out_runs += o.out_runs; - self.out_cells += o.out_cells; - self.flat_runs += o.flat_runs; - self.flat_cells += o.flat_cells; - } - - fn findings(&self) -> u64 { - self.steps + self.spikes + self.pits + self.out_runs + self.flat_runs - } -} - -/// The lowest and highest values of `rows` the model can hold. -fn extremes(dem: &Dem<'_>, rows: Range) -> Result, String> { - let mut found: Option<(f64, f64)> = None; - let mut pace = crate::control::Pace::default(); - for row in rows { - for col in 0..dem.r.width { - if pace.stop(1) { - return Err(crate::control::Cancelled.into()); - } - if let Some(v) = dem.level(i64::from(col), i64::from(row)) { - found = Some(found.map_or((v, v), |(lo, hi)| (lo.min(v), hi.max(v)))); - } - } + fn steps(&self) -> usize { + usize::try_from(self.steps).unwrap_or(usize::MAX) } - Ok(found) } -/// A run along a row going on: where it started, and its first value. -type Run = Option<(u32, f64)>; - -/// Ends a run of values out of range at column `end`: always a finding. -fn close_out(run: &mut Run, end: u32, row: u32, n: &mut Counts, keep: &mut dyn FnMut(Finding)) { - if let Some((start, v)) = run.take() { - let len = end.saturating_sub(start); - n.out_runs += 1; - n.out_cells += u64::from(len); - keep(Finding { col: start + len / 2, row, kind: Kind::OutOfRange, size: f64::from(len), elevation: v }); - } -} - -/// Ends a run of one value at column `end`: a finding when it is as long as the rules ask and its -/// value is the band's lowest or highest (`ends`), where an undeclared no-data lies. A lake held -/// level, at any other value, is not one. -fn close_flat(run: &mut Run, end: u32, row: u32, at_least: usize, ends: Option<(f64, f64)>, n: &mut Counts, keep: &mut dyn FnMut(Finding)) { - if let Some((start, v)) = run.take() { - let len = end.saturating_sub(start); - if len as usize >= at_least && ends.is_some_and(|(lo, hi)| v == lo || v == hi) { - n.flat_runs += 1; - n.flat_cells += u64::from(len); - keep(Finding { col: start + len / 2, row, kind: Kind::FlatRun, size: f64::from(len), elevation: v }); - } - } -} - -/// Checks `rows`, counting what it finds and handing each finding to `keep`, in row order and -/// along each row. -fn scan(dem: &Dem<'_>, rows: Range, ends: Option<(f64, f64)>, keep: &mut dyn FnMut(Finding)) -> Result { +/// Checks `rows`, counting what it finds and handing each step to `keep`, in row order. +fn scan(dem: &Dem<'_>, rows: Range, keep: &mut dyn FnMut(Finding)) -> Result { let mut n = Counts::default(); let mut pace = crate::control::Pace::default(); - let rules = dem.rules; for row in rows { - let r = i64::from(row); - let (mut out, mut flat): (Run, Run) = (None, None); for col in 0..dem.r.width { if pace.stop(1) { return Err(crate::control::Cancelled.into()); } - let c = i64::from(col); - let Some(v) = dem.value(c, r) else { - close_out(&mut out, col, row, &mut n, keep); - close_flat(&mut flat, col, row, rules.run, ends, &mut n, keep); - continue; - }; + let Some(v) = dem.level(i64::from(col), i64::from(row)) else { continue }; + let (step, whole) = dem.step(i64::from(col), i64::from(row), v); n.cells += 1; - if !rules.holds(v) { - close_flat(&mut flat, col, row, rules.run, ends, &mut n, keep); - out.get_or_insert((col, v)); - continue; - } - close_out(&mut out, col, row, &mut n, keep); - if flat.is_some_and(|(_, f)| f != v) { - close_flat(&mut flat, col, row, rules.run, ends, &mut n, keep); - } - flat.get_or_insert((col, v)); - let mut hit = false; - match dem.above_median(c, r, v) { - None => n.unchecked += 1, - Some(d) if d > rules.spike => { - n.spikes += 1; - hit = true; - keep(Finding { col, row, kind: Kind::Spike, size: d, elevation: v }); - } - Some(d) if -d > rules.spike => { - n.pits += 1; - hit = true; - keep(Finding { col, row, kind: Kind::Pit, size: -d, elevation: v }); - } - Some(_) => {} - } - if let Some(drop) = dem.step(c, r, v) { + n.partial += u64::from(!whole); + if let Some(size) = step { n.steps += 1; - hit = true; - keep(Finding { col, row, kind: Kind::Step, size: drop, elevation: v }); + keep(Finding { col, row, size, elevation: v }); } - n.compared += u64::from(hit); } - close_out(&mut out, dem.r.width, row, &mut n, keep); - close_flat(&mut flat, dem.r.width, row, rules.run, ends, &mut n, keep); } Ok(n) } @@ -318,31 +110,41 @@ pub(super) fn run(inp: &dyn Inputs, p: &Json) -> Result { run_on(inp, p, None) } +/// A threshold from the parameters: `default` when left out or empty. +fn threshold(p: &Json, key: &str, default: f64) -> Result { + match p.get(key) { + None | Some(Json::Null) => Ok(default), + Some(Json::String(s)) if s.trim().is_empty() => Ok(default), + Some(_) => num(p, key).ok_or_else(|| format!("{key} must be a number")), + } +} + /// [`run`] on `threads` threads (the shared count when `None`): the same layer and summary on any. /// -/// Three passes over the rows, each in blocks of about [`BLOCK_CELLS`] cells on the threads, -/// looking at Cancel along each row: the band's lowest and highest values (for the flat runs), -/// then the findings, counted, kept as they come while fewer than [`MAX_POINTS`] are. Past that -/// many, which ones were kept depends on the threads, so a third pass takes the first -/// [`MAX_POINTS`] again, block by block from the top. Beyond the raster as it is held, memory is -/// the counts of each block and at most [`MAX_POINTS`] findings and their points. +/// The rows are scanned in blocks of about [`BLOCK_CELLS`] cells on the threads, looking at +/// Cancel along each row, the findings counted and kept as they come while fewer than +/// [`MAX_POINTS`] are. Past that many, which ones were kept depends on the threads, so a second +/// pass takes the first [`MAX_POINTS`] again, block by block from the top. Beyond the raster as it +/// is held, memory is the counts of each block and at most [`MAX_POINTS`] findings and points. pub(super) fn run_on(inp: &dyn Inputs, p: &Json, threads: Option) -> Result { let name = s(p, "input"); let r = inp.raster(name).ok_or("choose an elevation raster")?.raster; r.require_coordinates()?; let bands = zonal_bands(p.get("band").unwrap_or(&Json::Null), r.band_count())?; let [band] = bands.as_slice() else { return Err("choose one band of elevations".into()) }; - let rules = Rules::read(p)?; - let dem = Dem { r, band: *band, rules }; + let (ratio, height) = (threshold(p, "stepRatio", 5.0)?, threshold(p, "stepHeight", 20.0)?); + if ratio < 1.0 { + return Err("stepRatio must be 1 or more: a step is a drop that many times the drops beside it".into()); + } + if height <= 0.0 { + return Err("stepHeight must be more than 0".into()); + } + let dem = Dem { r, band: *band, ratio, height }; let per = (BLOCK_CELLS / (r.width as usize).max(1)).clamp(1, u32::MAX as usize) as u32; let blocks: Vec> = (0..r.height).step_by(per as usize).map(|top| top..top.saturating_add(per).min(r.height)).collect(); let cells = (r.width as usize).saturating_mul(r.height as usize); let threads = threads.unwrap_or_else(|| crate::parallel::threads_for_rows(blocks.len(), cells, 0)); - crate::control::begin(blocks.len().saturating_mul(3)); - let ends = crate::parallel::try_map_on(&blocks, threads, || (), |_, _, rows| extremes(&dem, rows.clone()))? - .into_iter() - .flatten() - .reduce(|(lo, hi), (l, h)| (lo.min(l), hi.max(h))); + crate::control::begin(blocks.len().saturating_mul(2)); let taken = AtomicUsize::new(0); let scanned = crate::parallel::try_map_on( &blocks, @@ -350,7 +152,7 @@ pub(super) fn run_on(inp: &dyn Inputs, p: &Json, threads: Option) -> Resu || (), |_, _, rows| { let mut kept = Vec::new(); - let n = scan(&dem, rows.clone(), ends, &mut |f| { + let n = scan(&dem, rows.clone(), &mut |f| { if taken.fetch_add(1, Ordering::Relaxed) < MAX_POINTS { kept.push(f); } @@ -358,26 +160,23 @@ pub(super) fn run_on(inp: &dyn Inputs, p: &Json, threads: Option) -> Resu Ok::<_, String>((n, kept)) }, )?; - let mut total = Counts::default(); - for (n, _) in &scanned { - total.add(n); - } - let found = usize::try_from(total.findings()).unwrap_or(usize::MAX); - let findings: Vec = if found <= MAX_POINTS { + let total = scanned.iter().fold(Counts::default(), |t, (n, _)| Counts { + cells: t.cells + n.cells, + partial: t.partial + n.partial, + steps: t.steps + n.steps, + }); + let findings: Vec = if total.steps() <= MAX_POINTS { scanned.into_iter().flat_map(|(_, kept)| kept).collect() } else { // The first MAX_POINTS findings by block, scanned again for them alone. let mut left = MAX_POINTS; let mut plan = Vec::new(); for (rows, (n, _)) in blocks.iter().zip(&scanned) { - let here = usize::try_from(n.findings()).unwrap_or(usize::MAX).min(left); + let here = n.steps().min(left); if here > 0 { plan.push((rows.clone(), here)); left -= here; } - if left == 0 { - break; - } } drop(scanned); let parts = crate::parallel::try_map_on( @@ -386,11 +185,7 @@ pub(super) fn run_on(inp: &dyn Inputs, p: &Json, threads: Option) -> Resu || (), |_, _, (rows, take)| { let mut kept = Vec::with_capacity(*take); - scan(&dem, rows.clone(), ends, &mut |f| { - if kept.len() < *take { - kept.push(f); - } - })?; + scan(&dem, rows.clone(), &mut |f| kept.extend((kept.len() < *take).then_some(f)))?; Ok::<_, String>(kept) }, )?; @@ -400,12 +195,8 @@ pub(super) fn run_on(inp: &dyn Inputs, p: &Json, threads: Option) -> Resu if total.cells == 0 { return Err(format!("band {} of '{name}' has no values to check", band + 1)); } - let fields = vec![ - Field::new("kind", FieldType::Text), - Field::new("size", FieldType::Double), - Field::new("unit", FieldType::Text), - Field::new("elevation", FieldType::Double), - ]; + let fields = + vec![Field::new("kind", FieldType::Text), Field::new("size", FieldType::Double), Field::new("elevation", FieldType::Double)]; let mut out = Dataset::new(out_name(p, format!("{name}_CheckDEM")), GeometryType::Point, fields); let mut placeless = 0usize; let mut pace = crate::control::Pace::default(); @@ -413,58 +204,45 @@ pub(super) fn run_on(inp: &dyn Inputs, p: &Json, threads: Option) -> Resu if pace.stop(64) { return Err(crate::control::Cancelled.into()); } - let centre = r.transform.to_world(f64::from(f.col) + 0.5, f64::from(f.row) + 0.5); - let Some(at) = r.transformer().to_lonlat(centre) else { - placeless += 1; - continue; - }; - out.push_next( - Some(Geometry::Point(at)), - vec![Value::Text(f.kind.name().into()), Value::Float(f.size), Value::Text(f.kind.unit().into()), Value::Float(f.elevation)], - ); + match r.transformer().to_lonlat(r.transform.to_world(f64::from(f.col) + 0.5, f64::from(f.row) + 0.5)) { + Some(at) => { + out.push_next(Some(Geometry::Point(at)), vec![Value::Text("step".into()), Value::Float(f.size), Value::Float(f.elevation)]) + } + None => placeless += 1, + } } - let affected = total.compared + total.out_cells + total.flat_cells; let mut messages = vec![format!( - "Checked {} cell(s) of band {} of '{name}': {} step(s), {} spike(s), {} pit(s), {} run(s) of values out of range ({} cells), {} flat run(s) at the band's lowest or highest value ({} cells); {:.3}% of the cells with a value are affected", + "Checked {} cell(s) of band {} of '{name}': {} step(s); {:.3}% of the cells with a value are affected", total.cells, band + 1, total.steps, - total.spikes, - total.pits, - total.out_runs, - total.out_cells, - total.flat_runs, - total.flat_cells, - affected as f64 * 100.0 / total.cells as f64, + total.steps as f64 * 100.0 / total.cells as f64, )]; - if total.unchecked > 0 { + if total.partial > 0 { messages.push(format!( - "{} cell(s) at the edge, or next to no-data or a value out of range, lack a neighbour to compare with: the spike and pit rule skips them, and the step rule the directions it can't follow", - total.unchecked + "{} cell(s) at the edge or next to no-data lack a neighbour to compare with on some line: the step rule skips those lines", + total.partial )); } if let Some((fw, fh)) = r.overview { messages.push(format!( - "'{name}' is held as an overview of its file ({} × {} of its {fw} × {fh} cells): a step or spike a cell or two wide at full resolution may not show in it", + "'{name}' is held as an overview of its file ({} × {} of its {fw} × {fh} cells): a step a cell or two wide at full resolution may not show in it", r.width, r.height )); } let mut losses = Vec::new(); + let found = total.steps(); if found > findings.len() { - losses.push(LossMessage { - code: LossCode::DroppedOverLimit, - text: format!( - "{} of the {found} findings are counted but not written as points: the layer holds the first {}, from the top row down. Raise the thresholds, or check part of the model, to see the rest", - found - findings.len(), - findings.len() - ), - }); + let text = format!( + "{} of the {found} findings are counted but not written as points: the layer holds the first {}, from the top row down. Raise the thresholds, or check part of the model, to see the rest", + found - findings.len(), + findings.len() + ); + losses.push(LossMessage { code: LossCode::DroppedOverLimit, text }); } if placeless > 0 { - losses.push(LossMessage { - code: LossCode::DroppedFeature, - text: format!("{placeless} finding(s) whose cell couldn't be placed in longitude and latitude were left out of the layer"), - }); + let text = format!("{placeless} finding(s) whose cell couldn't be placed in longitude and latitude were left out of the layer"); + losses.push(LossMessage { code: LossCode::DroppedFeature, text }); } Ok(ToolResult { output: Output::Layer(out), messages, losses }) } @@ -472,7 +250,7 @@ pub(super) fn run_on(inp: &dyn Inputs, p: &Json, threads: Option) -> Resu #[cfg(test)] mod tests { use super::*; - use rustgis_data::raster::{ColorHint, GeoTransform}; + use rustgis_data::raster::{ColorHint, GeoTransform, Raster}; struct One<'a>(&'a Raster); @@ -500,175 +278,69 @@ mod tests { 800.0 + 3.0 * row as f32 + ((col * 7 + row * 13) % 5) as f32 } - /// Mountain-like ground with no defect: [`rough`] with a round hill and a steep face (a 40 m - /// drop a cell for six cells). - fn clean(col: u32, row: u32) -> f32 { - let (x, y) = (col as f32, row as f32); - let hill = 300.0 * (-((x - 20.0).powi(2) + (y - 20.0).powi(2)) / 60.0).exp(); - let face = 40.0 * (x - 30.0).clamp(0.0, 6.0); - rough(col, row) + hill - face - } - - type Row = (String, f64, f64, Coord); - - fn check(r: &Raster, p: Json) -> (ToolResult, Vec) { + /// The steps as (size, cell), and what was said. + fn check(r: &Raster, p: Json, threads: usize) -> (Vec<(f64, (i64, i64))>, Vec) { let mut p = p; p["input"] = Json::from("dem"); - let result = run(&One(r), &p).unwrap(); + let result = run_on(&One(r), &p, Some(threads)).unwrap(); let Output::Layer(out) = &result.output else { panic!("a point layer") }; - let rows = out - .features - .iter() - .map(|f| { - let Value::Text(kind) = &f.attrs[0] else { panic!("a kind") }; - let (Value::Float(size), Value::Float(z)) = (&f.attrs[1], &f.attrs[3]) else { panic!("numbers") }; - let Some(Geometry::Point(at)) = f.geometry else { panic!("a point") }; - (kind.clone(), *size, *z, at) - }) - .collect(); - (result, rows) - } - - fn kinds(rows: &[Row], kind: &str) -> usize { - rows.iter().filter(|r| r.0 == kind).count() - } - - #[test] - fn clean_mountain_ground_has_no_findings() { - let r = dem(60, 50, clean); - let (result, rows) = check(&r, serde_json::json!({})); - assert_eq!(rows.len(), 0, "{rows:?}"); - assert!(result.losses.is_empty()); - let summary = &result.messages[0]; - assert!(summary.starts_with("Checked 3000 cell(s) of band 1 of 'dem': 0 step(s), 0 spike(s), 0 pit(s)"), "{summary}"); - assert!(summary.ends_with("0.000% of the cells with a value are affected"), "{summary}"); - // The 216 cells of the edge lack neighbours, and that is said. - assert!(result.messages[1].starts_with("216 cell(s) at the edge"), "{:?}", result.messages); - } - - #[test] - fn a_seam_is_a_line_of_steps_on_its_high_side() { - // The right part 25 m lower than the left, as two tiles mosaicked at different levels. - let r = dem(40, 30, |c, r| rough(c, r) - if c >= 12 { 25.0 } else { 0.0 }); - let (result, rows) = check(&r, serde_json::json!({})); - // Every row but the first and last, whose diagonals go off the grid: those still have - // the step across the row, so all 30 are found. - assert_eq!(kinds(&rows, "step"), 30, "{rows:?}"); - assert_eq!(rows.len(), 30, "{rows:?}"); - // Each on the last cell of the high side, one a row. - let cells: Vec<_> = rows.iter().map(|(_, _, _, at)| r.pixel_at(*at).unwrap()).collect(); - assert_eq!(cells, (0..30).map(|row| (11, row)).collect::>()); - assert!(rows.iter().all(|(_, size, _, _)| (20.0..33.0).contains(size)), "{rows:?}"); - assert!(result.messages[0].contains(": 30 step(s), 0 spike(s)"), "{}", result.messages[0]); - // Below the step height, it isn't one. - let (_, rows) = check(&r, serde_json::json!({"stepHeight": 40})); - assert_eq!(rows.len(), 0); - } - - #[test] - fn spikes_and_pits_stand_off_the_median_of_their_neighbours() { - let r = dem(30, 30, |c, r| match (c, r) { - (10, 10) => clean(c, r) + 50.0, - (20, 15) => clean(c, r) - 45.0, - _ => clean(c, r), + let rows = out.features.iter().map(|f| match (&f.attrs[..], &f.geometry) { + ([Value::Text(kind), Value::Float(size), _], Some(Geometry::Point(at))) if kind == "step" => (*size, r.pixel_at(*at).unwrap()), + _ => panic!("{f:?}"), }); - let (_, rows) = check(&r, serde_json::json!({})); - assert_eq!(kinds(&rows, "spike"), 1, "{rows:?}"); - assert_eq!(kinds(&rows, "pit"), 1, "{rows:?}"); - // Neither is also a step, nor are its neighbours: the drops beside them are as large. - assert_eq!(rows.len(), 2, "{rows:?}"); - let spike = rows.iter().find(|r| r.0 == "spike").unwrap(); - assert!((45.0..55.0).contains(&spike.1), "{spike:?}"); - assert!(rows.iter().find(|r| r.0 == "pit").is_some_and(|p| (40.0..50.0).contains(&p.1)), "{rows:?}"); - let (_, rows) = check(&r, serde_json::json!({"spikeHeight": 60})); - assert_eq!(rows.len(), 0); + (rows.collect(), result.messages.into_iter().chain(result.losses.into_iter().map(|l| l.text)).collect()) } #[test] - fn values_out_of_range_and_flat_runs_at_the_ends_are_runs() { - // An undeclared no-data of -32768 five cells long, a sea at 0 (the band's lowest) along - // the last row, and a lake held level at 809 (inside the range): only the first two count. - let r = dem(120, 12, |c, r| match (c, r) { - (40..45, 5) => -32768.0, - (_, 11) => 0.0, - (60..120, 3) => 809.0, - _ => rough(c, r), - }); - let (result, rows) = check(&r, serde_json::json!({})); - let out: Vec<_> = rows.iter().filter(|r| r.0 == "out of range").collect(); - assert_eq!(out.len(), 1, "{rows:?}"); - assert_eq!((out[0].1, out[0].2), (5.0, -32768.0)); - let flat: Vec<_> = rows.iter().filter(|r| r.0 == "flat run").collect(); - assert_eq!(flat.len(), 1, "{rows:?}"); - assert_eq!((flat[0].1, flat[0].2), (120.0, 0.0)); - // The out-of-range cells aren't compared, so their neighbours aren't spikes or pits. - assert_eq!(kinds(&rows, "spike") + kinds(&rows, "pit"), 0, "{rows:?}"); - assert!(result.messages[0].contains("1 run(s) of values out of range (5 cells), 1 flat run(s)"), "{}", result.messages[0]); - // A run shorter than asked is not one, nor a value inside a wider range. - let (_, rows) = check(&r, serde_json::json!({"runLength": 121})); - assert_eq!(kinds(&rows, "flat run"), 0); - let (_, rows) = check(&r, serde_json::json!({"lowest": -40000})); - assert_eq!(kinds(&rows, "out of range"), 0); - } - - #[test] - fn past_the_point_limit_the_first_findings_are_kept_alike_on_any_threads() { - // A checkerboard of 0 and 100 m: every cell inside the edge a spike or a pit. - let r = dem(400, 400, |c, r| if (c + r) % 2 == 0 { 100.0 } else { 0.0 }); - let p = serde_json::json!({"input": "dem"}); - let layers: Vec<_> = [1, 2, 7] - .into_iter() - .map(|threads| { - let result = run_on(&One(&r), &p, Some(threads)).unwrap(); - assert_eq!(result.losses.len(), 1); - assert!(result.losses[0].text.starts_with("58404 of the 158404 findings"), "{}", result.losses[0].text); - let Output::Layer(out) = result.output else { panic!("a layer") }; - out.features - }) - .collect(); - assert_eq!(layers[0].len(), MAX_POINTS); - assert!(layers.iter().all(|l| *l == layers[0])); + fn mountain_ground_with_a_cliff_has_no_steps() { + // A round hill and a face dropping 40 m a cell for six cells: slopes, not breaks. + let ground = |c: u32, r: u32| { + let (x, y) = (c as f32, r as f32); + rough(c, r) + 300.0 * (-((x - 20.0).powi(2) + (y - 20.0).powi(2)) / 60.0).exp() - 40.0 * (x - 30.0).clamp(0.0, 6.0) + }; + let (rows, said) = check(&dem(60, 50, ground), serde_json::json!({}), 1); + assert_eq!(rows, []); + assert_eq!(said[0], "Checked 3000 cell(s) of band 1 of 'dem': 0 step(s); 0.000% of the cells with a value are affected"); + // The two outer rings of cells can't follow every line, and that is said. + assert!(said[1].starts_with("424 cell(s) at the edge"), "{said:?}"); } #[test] - fn the_same_findings_on_any_threads_below_the_limit() { - let r = - dem(300, 260, |c, r| clean(c % 60, r % 50) - if c >= 150 { 30.0 } else { 0.0 } + if (c * r) % 997 == 3 { 60.0 } else { 0.0 }); - let p = serde_json::json!({"input": "dem"}); - let runs: Vec<_> = [1, 3, 8] - .into_iter() - .map(|threads| { - let result = run_on(&One(&r), &p, Some(threads)).unwrap(); - let Output::Layer(out) = result.output else { panic!("a layer") }; - (out.features, result.messages) - }) - .collect(); - assert!(!runs[0].0.is_empty()); - assert!(runs.iter().all(|r| *r == runs[0])); + fn a_seam_is_a_line_of_steps_on_its_high_side_on_any_threads() { + // The right part 25 m lower than the left, as two tiles mosaicked at different levels. + let r = dem(40, 300, |c, r| rough(c, r) - if c >= 12 { 25.0 } else { 0.0 }); + let (rows, said) = check(&r, serde_json::json!({}), 1); + assert_eq!(rows.iter().map(|f| f.1).collect::>(), (0..300).map(|row| (11, row)).collect::>()); + assert!(rows.iter().all(|f| (20.0..33.0).contains(&f.0)), "{rows:?}"); + assert!(said[0].contains(": 300 step(s)"), "{said:?}"); + assert_eq!(check(&r, serde_json::json!({}), 4), (rows, said)); + // Below the step height, or with a ratio its sides reach, it isn't one. + assert_eq!(check(&r, serde_json::json!({"stepHeight": 40}), 1).0, []); + assert_eq!(check(&r, serde_json::json!({"stepRatio": 100}), 1).0, []); } #[test] - fn the_range_s_defaults_are_the_plausible_elevations() { - let spec = crate::tool("checkDem").unwrap(); - let default = |n: &str| spec.params.iter().find(|p| p.name == n).unwrap().default.parse::().unwrap(); - assert_eq!((default("lowest"), default("highest")), PLAUSIBLE_ELEVATION); + fn past_the_point_limit_the_first_steps_are_kept_alike_on_any_threads() { + // Terraces two cells wide, 100 m apart: each high terrace's edge cell is a step. + let r = dem(500, 500, |c, _| if (c / 2) % 2 == 0 { 100.0 } else { 0.0 }); + let (rows, said) = check(&r, serde_json::json!({}), 1); + assert_eq!(rows.len(), MAX_POINTS); + assert!(said.iter().any(|s| s.starts_with("24500 of the 124500 findings")), "{said:?}"); + assert_eq!(check(&r, serde_json::json!({}), 7).0, rows); } #[test] fn thresholds_that_make_no_sense_are_refused() { - let r = dem(10, 10, clean); + let r = dem(10, 10, rough); for (p, says) in [ (serde_json::json!({"stepRatio": 0.5}), "stepRatio must be 1 or more"), - (serde_json::json!({"stepHeight": 0}), "must be more than 0"), - (serde_json::json!({"lowest": 10, "highest": 10}), "lowest must be below highest"), - (serde_json::json!({"runLength": 1.5}), "runLength must be a whole number"), - (serde_json::json!({"spikeHeight": "high"}), "spikeHeight must be a number"), + (serde_json::json!({"stepHeight": 0}), "stepHeight must be more than 0"), + (serde_json::json!({"stepHeight": "high"}), "stepHeight must be a number"), (serde_json::json!({"band": 2}), "band"), ] { let mut p = p; p["input"] = Json::from("dem"); - let e = run(&One(&r), &p).unwrap_err(); - assert!(e.contains(says), "{e}"); + assert!(run(&One(&r), &p).unwrap_err().contains(says), "{p}"); } let empty = dem(5, 5, |_, _| -9999.0); assert!(run(&One(&empty), &serde_json::json!({"input": "dem"})).unwrap_err().contains("has no values to check")); diff --git a/crates/engine/src/cmd/raster.rs b/crates/engine/src/cmd/raster.rs index edc99855f7..20a63d8b7f 100644 --- a/crates/engine/src/cmd/raster.rs +++ b/crates/engine/src/cmd/raster.rs @@ -1077,36 +1077,7 @@ fn symbology(s: &mut Session, p: &Value) -> CmdResult { rl.style.stretch = Stretch::default(); } Ok(()) - })?; - relief_notice(s, id, &r); - Ok(Value::Null) -} - -/// Says when a Shaded Relief is drawn from a band holding values no elevation has (#3151): below -/// or above [`rustgis_analysis::PLAUSIBLE_ELEVATION`], such as a no-data of -32768 the file -/// doesn't declare, which the relief draws as cliffs. A look at the band's statistics; Check DEM -/// says where the values are. -fn relief_notice(s: &mut Session, id: u32, r: &Raster) { - let (lowest, highest) = rustgis_analysis::PLAUSIBLE_ELEVATION; - let Some(l) = s.map().layer(id) else { return }; - let Some(RasterRenderer::ShadedRelief { band, .. }) = l.raster.as_ref().map(|rl| &rl.style.renderer) else { return }; - let Some(stats) = r.bands.get(*band).map(|b| &b.stats).filter(|st| st.count > 0) else { return }; - let mut odd = Vec::new(); - if stats.min < lowest { - odd.push(format!("as low as {}", stats.min)); - } - if stats.max > highest { - odd.push(format!("as high as {}", stats.max)); - } - if odd.is_empty() { - return; - } - let text = format!( - "'{}' holds values no elevation has ({}, outside {lowest} to {highest}): its relief draws them as cliffs. Check DEM (checkDem) finds where they are; declare them as no-data, or hide them with raster.mask", - l.name, - odd.join(" and ") - ); - s.notify(text, false); + }) } /// A Shaded Relief's `"shadowSoftness"` (see `raster.symbology`), `v` being the number given, if diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 32c16f8ccc..228a95f994 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -7702,81 +7702,6 @@ fn custom_projections_switch_keep_scale_query_and_render() { } } -/// A Shaded Relief drawn from a band holding values no elevation has (an undeclared no-data of -/// -32768, a height of 65535) says so and names them; a clean band, or one whose no-data is -/// declared, says nothing (#3151). -#[test] -fn shaded_relief_names_values_no_elevation_has() { - let dir = std::env::temp_dir().join(format!("rustgis-engine-relief-values-{}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); - let mut s = Session::new(Project::default()); - for (name, head, values, said) in [ - ( - "hole.asc", - "", - "812 815 -32768 -809 811 814 -806 808 810", - Some("as low as -32768"), - ), - ( - "high.asc", - "", - "812 815 65535 -809 811 814 -806 808 810", - Some("as high as 65535"), - ), - ( - "clean.asc", - "", - "812 815 818 -809 811 814 -806 808 810", - None, - ), - ( - "declared.asc", - "NODATA_value -32768 -", - "812 815 -32768 -809 811 814 -806 808 810", - None, - ), - ] { - let path = dir.join(name); - std::fs::write( - &path, - format!( - "ncols 3 -nrows 3 -xllcorner 10 -yllcorner 40 -cellsize 0.001 -{head}{values}" - ), - ) - .unwrap(); - let id = s.run("layer.addData", &json!({"path": path})).unwrap()["layer"].as_u64().unwrap(); - let mark = s.notice_mark(); - s.run("raster.symbology", &json!({"layer": id, "type": "shadedRelief"})).unwrap(); - let notice = s.notices_since(mark).iter().find(|n| n.text.contains("holds values no elevation has")).map(|n| n.text.clone()); - match said { - Some(values) => { - let notice = notice.unwrap_or_else(|| panic!("{name}: {:?}", s.notices_since(mark))); - assert!(notice.contains(values) && notice.contains("Check DEM (checkDem)"), "{notice}"); - } - None => assert_eq!(notice, None, "{name}"), - } - // Another symbology says nothing of it. - let mark = s.notice_mark(); - s.run("raster.symbology", &json!({"layer": id, "type": "stretch"})).unwrap(); - assert!(!s.notices_since(mark).iter().any(|n| n.text.contains("no elevation has")), "{name}"); - } - std::fs::remove_dir_all(dir).unwrap(); -} - /// Shaded Relief's cast shadows: set, kept when left out, clamped, a new one without; saved with /// the project only when there are some, and drawn in an export (waited for). #[test] diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index 44f1b34d77..922235134a 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -2479,45 +2479,20 @@ Cancel can wait for that mask fill to finish. ## Checking an elevation model -**Check DEM** (`checkDem`) looks for what a relief shading would show glaring and a stretched grey -raster hides: seams, stripes, spikes and pits, cliffs at the edge of a reservoir in a surface -model, and no-data the file doesn't declare. It writes a point layer, one point per finding, with -`kind`, `size`, `unit` (`elevation` for a height, `cells` for a run) and the `elevation` there, -and a summary of the counts per kind and the share of the model's cells affected. It reports and -changes nothing: fill or smooth with the tools made for that, or mask the values with -`raster.mask`. - -- **step**: a cell whose drop to a neighbour is more than `stepHeight` (default 20) and more than - `stepRatio` (default 5) times the drops just before and just after it on the same line (from - the cell behind it, and from the neighbour to the one beyond). A cliff, whose face goes on - dropping, is not one; a seam between two tiles at different levels is. Its `size` is the drop. -- **spike** and **pit**: a cell more than `spikeHeight` (default 30) above or below the median of - its eight neighbours. Its `size` is how far. -- **out of range**: a run along a row of values below `lowest` (default −500) or above `highest` - (default 9,000), such as −32768 or −9999 written for no-data. Its `size` is the run's length in - cells. Those values aren't compared with their neighbours, so a hole of them isn't also a field - of pits. -- **flat run**: a run of at least `runLength` (default 100) cells along a row holding the band's - lowest or highest value: a no-data of 0, or the sea held at 0. A lake held level at any other - value is not one. - -Thresholds are in the model's elevation unit; the defaults are metres. Cells at the edge, or next -to no-data or a value out of range, lack the neighbours the spike and pit rule compares, and the -summary says how many. The layer holds the first 100,000 findings, from the top row down; past -that the rest are counted in the summary and a notice. A model held as an overview of a larger -file is checked as it is held, and a notice says so. - -The defaults were set on real models (#3151): on a 1-second SRTM tile of the Quadrilátero -Ferrífero, 82% of the steps and 88% of the spikes and pits found lie within a cell of where SRTM -and the Copernicus 30 m model differ by more than 10 m (12% of all cells do), and the Copernicus tile shows its steps -along a reservoir's shore; on the ANADEM terrain model of the Serra do Brigadeiro there are 16 -steps a million cells, on rock walls, and no spikes or pits. - -```json -{"tool":"checkDem","params":{"input":"srtm","stepHeight":10,"output":"srtm_findings"}} -``` - -On the desktop it runs in the background with progress and Cancel, on several threads. +**Check DEM** (`checkDem`) finds the steps a relief shading shows glaring and a stretched grey +raster hides: seams between tiles, voids filled at another level, cliffs at a reservoir's edge in a +surface model. It writes a point per step, with `kind`, `size` (the drop) and the `elevation` +there, and a summary of the count and the share of the model affected. It reports and changes +nothing. + +A **step** is a drop to a neighbour of more than `stepHeight` (default 20) and more than +`stepRatio` (default 5) times the drops just before and after it on the same line. A cliff, whose +face goes on dropping, is not one. Heights are in the model's elevation unit. Cells at the edge or +next to no-data can't follow every line, and the summary says how many. The layer holds the first +100,000 steps, from the top row down; the rest are counted. On a 1-second SRTM tile of the +Quadrilátero Ferrífero, 82% of the steps lie within a cell of where SRTM and the Copernicus 30 m +model differ by more than 10 m; the clean ANADEM terrain model of the Serra do Brigadeiro has 16 a +million cells. On the desktop it runs in the background with progress and Cancel. ## Zonal statistics and polygon clipping diff --git a/docs/user-guide/data.md b/docs/user-guide/data.md index fc37fb8f9a..b930ff1f48 100644 --- a/docs/user-guide/data.md +++ b/docs/user-guide/data.md @@ -1733,11 +1733,6 @@ stretch, and an opaque black cell still counts. The alpha band's own statistics alpha with a value, see-through ones included. **Change Detection** gives no-data where either image is see-through. -**Shaded Relief** names the values its band holds that no elevation has, below −500 or above -9,000 (from the band's statistics), such as a no-data of −32768 the file doesn't declare, which the -relief draws as cliffs. Check DEM (`checkDem`, see -[Checking an elevation model](analysis.md#checking-an-elevation-model)) finds where they are. - **Cast shadows**, on a Shaded Relief layer (`raster.symbology` `"shadow"`, 0 to 1), darkens the slopes the terrain hides from the sun as well as those facing away from it: a valley behind a ridge is in shadow, with a soft edge. Only the direct light is darkened: a slope in full shadow keeps the From 63be552a8a0b25968d58b2dd44f8919e3a58502c Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Sat, 28 Nov 2026 18:41:38 -0300 Subject: [PATCH 3/5] fix(analysis): Check DEM's over-limit notice counts the points written (#3151) When some of the first 100,000 steps can't be placed in longitude and latitude, the layer holds fewer than that, and the notice now says so. Also: "16 per million" in the module doc and the guide, a plain `if` in the second pass, the step's ratio stated as the larger of the drops beside it, and where Cancel is looked at. Co-Authored-By: Claude Opus 5.5 --- crates/analysis/src/tools/check_dem.rs | 58 ++++++++++++++++++-------- docs/user-guide/analysis.md | 9 ++-- 2 files changed, 46 insertions(+), 21 deletions(-) diff --git a/crates/analysis/src/tools/check_dem.rs b/crates/analysis/src/tools/check_dem.rs index 1e93aab6cd..57029d810f 100644 --- a/crates/analysis/src/tools/check_dem.rs +++ b/crates/analysis/src/tools/check_dem.rs @@ -2,13 +2,13 @@ //! reports and changes nothing: filling or smoothing is the user's choice. //! //! A step is measured against the ground on either side of it, on the same line: a drop between -//! two neighbours far larger than the drops just before and just after it is a break the slope -//! doesn't explain (a seam, a void filled at another level, a reservoir's edge in a surface -//! model), where a cliff, whose face goes on dropping, is not. On a 1-second SRTM tile of the -//! Quadrilátero Ferrífero (S21W044), 82% of its 1,740 steps lie within a cell of where SRTM and -//! the Copernicus 30 m model differ by more than 10 m (12% of all cells do); the ANADEM terrain -//! model of the Serra do Brigadeiro has 16 a million cells, on rock walls, where comparing with -//! the eight neighbours' median drop instead flagged 438. +//! two neighbours far larger than both the drop just before it and the one just after it is a +//! break the slope doesn't explain (a seam, a void filled at another level, a reservoir's edge in +//! a surface model), where a cliff, whose face goes on dropping, is not. On a 1-second SRTM tile +//! of the Quadrilátero Ferrífero (S21W044), 82% of its 1,740 steps lie within a cell of where SRTM +//! and the Copernicus 30 m model differ by more than 10 m (12% of all cells do); the ANADEM +//! terrain model of the Serra do Brigadeiro has 16 per million cells, on rock walls, where +//! comparing with the eight neighbours' median drop instead flagged 438. use super::*; use rustgis_data::loss::{LossCode, LossMessage}; use std::ops::Range; @@ -48,8 +48,9 @@ impl Dem<'_> { /// The largest drop from a cell, at `v`, to a neighbour that is a step: more than the step /// height and more than `ratio` times the drops beside it on the same line (from the cell - /// behind to this one, and from the neighbour to the one beyond it). With it, whether every - /// line could be followed: `false` at the edge and next to no-data. + /// behind to this one, and from the neighbour to the one beyond it, the larger of the two). + /// With it, `false` when a line lacks one of those cells (at the edge and next to no-data), so + /// the rule skipped that line. fn step(&self, col: i64, row: i64, v: f64) -> (Option, bool) { let (mut largest, mut whole): (Option, bool) = (None, true); for (dc, dr) in AROUND { @@ -122,10 +123,11 @@ fn threshold(p: &Json, key: &str, default: f64) -> Result { /// [`run`] on `threads` threads (the shared count when `None`): the same layer and summary on any. /// /// The rows are scanned in blocks of about [`BLOCK_CELLS`] cells on the threads, looking at -/// Cancel along each row, the findings counted and kept as they come while fewer than -/// [`MAX_POINTS`] are. Past that many, which ones were kept depends on the threads, so a second -/// pass takes the first [`MAX_POINTS`] again, block by block from the top. Beyond the raster as it -/// is held, memory is the counts of each block and at most [`MAX_POINTS`] findings and points. +/// Cancel between blocks (and along a row of millions of cells), the findings counted and kept as +/// they come while fewer than [`MAX_POINTS`] are. Past that many, which ones were kept depends on +/// the threads, so a second pass takes the first [`MAX_POINTS`] again, block by block from the +/// top. Beyond the raster as it is held, memory is the counts of each block and at most +/// [`MAX_POINTS`] findings and points. pub(super) fn run_on(inp: &dyn Inputs, p: &Json, threads: Option) -> Result { let name = s(p, "input"); let r = inp.raster(name).ok_or("choose an elevation raster")?.raster; @@ -185,7 +187,11 @@ pub(super) fn run_on(inp: &dyn Inputs, p: &Json, threads: Option) -> Resu || (), |_, _, (rows, take)| { let mut kept = Vec::with_capacity(*take); - scan(&dem, rows.clone(), &mut |f| kept.extend((kept.len() < *take).then_some(f)))?; + scan(&dem, rows.clone(), &mut |f| { + if kept.len() < *take { + kept.push(f); + } + })?; Ok::<_, String>(kept) }, )?; @@ -233,10 +239,12 @@ pub(super) fn run_on(inp: &dyn Inputs, p: &Json, threads: Option) -> Resu let mut losses = Vec::new(); let found = total.steps(); if found > findings.len() { + // Those that couldn't be placed are left out of the first ones too, and said apart. + let (kept, written) = (findings.len(), out.features.len()); + let holds = if written == kept { format!("the first {kept}") } else { format!("{written} of the first {kept}") }; let text = format!( - "{} of the {found} findings are counted but not written as points: the layer holds the first {}, from the top row down. Raise the thresholds, or check part of the model, to see the rest", - found - findings.len(), - findings.len() + "{} of the {found} findings are counted but not written as points: the layer holds {holds}, from the top row down. Raise the thresholds, or check part of the model, to see the rest", + found - kept ); losses.push(LossMessage { code: LossCode::DroppedOverLimit, text }); } @@ -329,6 +337,22 @@ mod tests { assert_eq!(check(&r, serde_json::json!({}), 7).0, rows); } + #[test] + fn past_the_point_limit_the_notice_counts_only_the_points_written() { + // The same terraces in SIRGAS 2000 degrees, the top 100 rows past the pole: their 24,900 + // steps are found but can't be placed, so the layer holds fewer than the first 100,000. + let values = (0..500u32).flat_map(|_| (0..500u32).map(|c| if (c / 2) % 2 == 0 { 100.0 } else { 0.0 })).collect(); + let transform = GeoTransform { origin_x: -45.0, origin_y: 90.1, pixel_width: 0.001, pixel_height: -0.001 }; + let r = Raster::new("dem", 500, 500, vec![values], transform, Crs::Epsg(4674), Some(-9999.), ColorHint::Gray, "Float32").unwrap(); + let result = run_on(&One(&r), &serde_json::json!({"input": "dem"}), Some(1)).unwrap(); + let Output::Layer(out) = &result.output else { panic!("a point layer") }; + assert_eq!(out.features.len(), MAX_POINTS - 24_900); + let said: Vec<&str> = result.losses.iter().map(|l| l.text.as_str()).collect(); + assert!(said[0].starts_with("24500 of the 124500 findings"), "{said:?}"); + assert!(said[0].contains(&format!("the layer holds {} of the first {MAX_POINTS}", MAX_POINTS - 24_900)), "{said:?}"); + assert!(said[1].starts_with("24900 finding(s) whose cell couldn't be placed"), "{said:?}"); + } + #[test] fn thresholds_that_make_no_sense_are_refused() { let r = dem(10, 10, rough); diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index 922235134a..8a5209e109 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -2486,13 +2486,14 @@ there, and a summary of the count and the share of the model affected. It report nothing. A **step** is a drop to a neighbour of more than `stepHeight` (default 20) and more than -`stepRatio` (default 5) times the drops just before and after it on the same line. A cliff, whose -face goes on dropping, is not one. Heights are in the model's elevation unit. Cells at the edge or +`stepRatio` (default 5) times the larger of the drops just before and after it on the same line. A +cliff whose face goes on dropping, cell after cell, is not one; a face one cell high between +flatter ground is. Heights are in the model's elevation unit. Cells at the edge or next to no-data can't follow every line, and the summary says how many. The layer holds the first 100,000 steps, from the top row down; the rest are counted. On a 1-second SRTM tile of the Quadrilátero Ferrífero, 82% of the steps lie within a cell of where SRTM and the Copernicus 30 m -model differ by more than 10 m; the clean ANADEM terrain model of the Serra do Brigadeiro has 16 a -million cells. On the desktop it runs in the background with progress and Cancel. +model differ by more than 10 m; the clean ANADEM terrain model of the Serra do Brigadeiro has 16 +per million cells. On the desktop it runs in the background with progress and Cancel. ## Zonal statistics and polygon clipping From e26836acab29cb6ba246d7be30197547a771d5ac Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Sat, 28 Nov 2026 19:41:27 -0300 Subject: [PATCH 4/5] fix(analysis): Check DEM's progress ends with its scan; raster tools stay in the output-file test (#3151) The scan counted half the step when no second pass runs, so the bar stopped near 50% until the end. The second pass is now a step of its own. The output-file test runs the raster tools again, leaving them out of the "half of them run" count only. Co-Authored-By: Claude Opus 5.5 --- crates/analysis/src/tools.rs | 7 ++----- crates/analysis/src/tools/check_dem.rs | 15 ++++++++++++++- 2 files changed, 16 insertions(+), 6 deletions(-) diff --git a/crates/analysis/src/tools.rs b/crates/analysis/src/tools.rs index 806062a371..3127876bc5 100644 --- a/crates/analysis/src/tools.rs +++ b/crates/analysis/src/tools.rs @@ -11483,11 +11483,8 @@ mod tests { continue; } // `inputs()` holds no raster, so a tool that reads one stops before it makes anything: - // it isn't counted among those expected to run here. - if spec.params.iter().any(|p| p.required && matches!(p.kind, K::RasterLayer)) { - continue; - } - tested += 1; + // it is still run, to write nothing, but isn't counted among those expected to run. + tested += usize::from(!spec.params.iter().any(|p| p.required && matches!(p.kind, K::RasterLayer))); let mut p = serde_json::Map::new(); for param in spec.params { let value = match serde_json::from_str::(param.default) { diff --git a/crates/analysis/src/tools/check_dem.rs b/crates/analysis/src/tools/check_dem.rs index 57029d810f..cd6b8560e2 100644 --- a/crates/analysis/src/tools/check_dem.rs +++ b/crates/analysis/src/tools/check_dem.rs @@ -146,7 +146,7 @@ pub(super) fn run_on(inp: &dyn Inputs, p: &Json, threads: Option) -> Resu let blocks: Vec> = (0..r.height).step_by(per as usize).map(|top| top..top.saturating_add(per).min(r.height)).collect(); let cells = (r.width as usize).saturating_mul(r.height as usize); let threads = threads.unwrap_or_else(|| crate::parallel::threads_for_rows(blocks.len(), cells, 0)); - crate::control::begin(blocks.len().saturating_mul(2)); + crate::control::begin(blocks.len()); let taken = AtomicUsize::new(0); let scanned = crate::parallel::try_map_on( &blocks, @@ -181,6 +181,8 @@ pub(super) fn run_on(inp: &dyn Inputs, p: &Json, threads: Option) -> Resu } } drop(scanned); + // A step of its own: the progress starts again for it. + crate::control::begin(plan.len()); let parts = crate::parallel::try_map_on( &plan, threads, @@ -353,6 +355,17 @@ mod tests { assert!(said[1].starts_with("24900 finding(s) whose cell couldn't be placed"), "{said:?}"); } + #[test] + fn the_progress_counts_the_scan_as_the_whole_step_when_no_second_pass_runs() { + // Four blocks of 256 rows, on one thread: stopped at its look before the last block, three + // of the four are done. + let r = dem(256, 1024, rough); + let run = crate::control::Control::cancelled_at_look(4); + let _installed = crate::control::install(Some(run.clone())); + assert!(run_on(&One(&r), &serde_json::json!({"input": "dem"}), Some(1)).is_err()); + assert_eq!(run.progress(), Some((3, 4))); + } + #[test] fn thresholds_that_make_no_sense_are_refused() { let r = dem(10, 10, rough); From 6ed7702f6926151c493ec9be05a03962e91a2e71 Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Sat, 28 Nov 2026 19:53:00 -0300 Subject: [PATCH 5/5] test(analysis): leave only Check DEM out of the output-file test's count (#3151) The other raster tools count as they do on main (20 of 40 run), so the "half of them run" guard is as strict as before. Co-Authored-By: Claude Opus 5.5 --- crates/analysis/src/tools.rs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/crates/analysis/src/tools.rs b/crates/analysis/src/tools.rs index 3127876bc5..2d6879a08a 100644 --- a/crates/analysis/src/tools.rs +++ b/crates/analysis/src/tools.rs @@ -11482,9 +11482,10 @@ mod tests { if !spec.params.iter().any(|p| p.name.eq_ignore_ascii_case("output") && matches!(p.kind, K::Text)) { continue; } - // `inputs()` holds no raster, so a tool that reads one stops before it makes anything: - // it is still run, to write nothing, but isn't counted among those expected to run. - tested += usize::from(!spec.params.iter().any(|p| p.required && matches!(p.kind, K::RasterLayer))); + // Check DEM reads only a raster, which `inputs()` doesn't hold, so it stops before it + // makes anything: it is still run, to write nothing, but isn't counted among those + // expected to run (with it, fewer than half of them would). + tested += usize::from(spec.id != "checkDem"); let mut p = serde_json::Map::new(); for param in spec.params { let value = match serde_json::from_str::(param.default) {