diff --git a/crates/analysis/src/tools.rs b/crates/analysis/src/tools.rs index b35730f4ae..2d6879a08a 100644 --- a/crates/analysis/src/tools.rs +++ b/crates/analysis/src/tools.rs @@ -1,5 +1,6 @@ //! The tools. +mod check_dem; mod check_geometry; mod geometry; mod network_analysis; @@ -1136,6 +1137,41 @@ pub static TOOLS: &[ToolSpec] = &[ ], run: tabulate_area::run, }, + ToolSpec { + id: "checkDem", + name: "Check DEM", + toolbox: "Analysis › Terrain", + 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", + label: "Elevation Raster", + kind: K::RasterLayer, + required: true, + 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 { + 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: "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,7 +11482,10 @@ mod tests { if !spec.params.iter().any(|p| p.name.eq_ignore_ascii_case("output") && matches!(p.kind, K::Text)) { continue; } - tested += 1; + // 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) { diff --git a/crates/analysis/src/tools/check_dem.rs b/crates/analysis/src/tools/check_dem.rs new file mode 100644 index 0000000000..cd6b8560e2 --- /dev/null +++ b/crates/analysis/src/tools/check_dem.rs @@ -0,0 +1,385 @@ +//! 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 ground on either side of it, on the same line: a drop between +//! 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; +use std::sync::atomic::{AtomicUsize, Ordering}; + +/// 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)]; + +/// One finding: its cell, its size (the drop) and the elevation there. +#[derive(Clone, Copy, Debug, PartialEq)] +struct Finding { + col: u32, + row: u32, + size: f64, + elevation: f64, +} + +/// One band of the model, and the step thresholds the parameters give. +struct Dem<'a> { + r: &'a rustgis_data::raster::Raster, + band: usize, + ratio: f64, + height: f64, +} + +impl Dem<'_> { + /// The value at a cell: `None` off the grid and for no-data. + fn level(&self, col: i64, row: i64) -> Option { + 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, 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 { + 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 (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, whole) + } +} + +/// 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: u64, + partial: u64, + steps: u64, +} + +impl Counts { + fn steps(&self) -> usize { + usize::try_from(self.steps).unwrap_or(usize::MAX) + } +} + +/// 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(); + for row in rows { + for col in 0..dem.r.width { + if pace.stop(1) { + return Err(crate::control::Cancelled.into()); + } + 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; + n.partial += u64::from(!whole); + if let Some(size) = step { + n.steps += 1; + keep(Finding { col, row, size, elevation: v }); + } + } + } + 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) +} + +/// 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. +/// +/// The rows are scanned in blocks of about [`BLOCK_CELLS`] cells on the threads, looking at +/// 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; + 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 (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()); + 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(), &mut |f| { + if taken.fetch_add(1, Ordering::Relaxed) < MAX_POINTS { + kept.push(f); + } + })?; + Ok::<_, String>((n, kept)) + }, + )?; + 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 = n.steps().min(left); + if here > 0 { + plan.push((rows.clone(), here)); + left -= here; + } + } + 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, + || (), + |_, _, (rows, take)| { + let mut kept = Vec::with_capacity(*take); + scan(&dem, rows.clone(), &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("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()); + } + 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 mut messages = vec![format!( + "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.steps as f64 * 100.0 / total.cells as f64, + )]; + if total.partial > 0 { + messages.push(format!( + "{} 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 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() { + // 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 {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 }); + } + if placeless > 0 { + 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 }) +} + +#[cfg(test)] +mod tests { + use super::*; + use rustgis_data::raster::{ColorHint, GeoTransform, Raster}; + + 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 + } + + /// 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_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| 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:?}"), + }); + (rows.collect(), result.messages.into_iter().chain(result.losses.into_iter().map(|l| l.text)).collect()) + } + + #[test] + 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 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 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 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 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); + for (p, says) in [ + (serde_json::json!({"stepRatio": 0.5}), "stepRatio must be 1 or more"), + (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"); + 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/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..8a5209e109 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,24 @@ 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`) 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 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 +per million cells. On the desktop it runs in the background with progress and Cancel. + ## Zonal statistics and polygon clipping Open **Zonal Statistics** through Command Search, or choose it in the Workflows pane.