diff --git a/crates/analysis/src/tools.rs b/crates/analysis/src/tools.rs index 457003c733..97f3ab4462 100644 --- a/crates/analysis/src/tools.rs +++ b/crates/analysis/src/tools.rs @@ -1141,7 +1141,7 @@ pub static TOOLS: &[ToolSpec] = &[ id: "checkDem", name: "Check DEM", toolbox: "Analysis › Terrain", - summary: "Finds steps (seams, voids filled at another level, reservoir edges), spikes and pits in an elevation model, as points with a summary; it changes nothing.", + summary: "Finds steps (seams, voids filled at another level, reservoir edges), spikes, pits and runs of values no elevation has in an elevation model, as points with a summary; it changes nothing.", params: &[ P { name: "input", @@ -1176,6 +1176,30 @@ pub static TOOLS: &[ToolSpec] = &[ 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 3fe35bba3d..9b0711383d 100644 --- a/crates/analysis/src/tools/check_dem.rs +++ b/crates/analysis/src/tools/check_dem.rs @@ -1,5 +1,6 @@ -//! Check DEM (#3151): a point for each step, spike and pit in an elevation model, and a summary -//! of them. It reports and changes nothing: filling or smoothing is the user's choice. +//! Check DEM (#3151): a point for each step, spike, pit and run of implausible values 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 @@ -13,6 +14,12 @@ //! A spike or a pit is a cell far above or below the median of its eight neighbours: a radar //! artefact, or a hole filled at another level. On the SRTM tile, 88% of its 127 spikes and 105 //! pits lie where SRTM and Copernicus differ by more than 10 m; the clean ANADEM has none. +//! +//! Values no elevation has (below −500 or above 9,000 m by default: a no-data the file doesn't +//! declare) are runs along a row, left out of the rules above, so a hole of them isn't also a +//! ring of pits. A long run of one value is one only at the band's lowest or highest value, where +//! such a no-data sits: on SRTM S10W041 the Sobradinho reservoir, held level at 385 m, would +//! otherwise give 606 runs. use super::*; use rustgis_data::loss::{LossCode, LossMessage}; use std::ops::Range; @@ -24,6 +31,9 @@ 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 lowest and highest values an elevation model can hold, in metres: below the Dead Sea's +/// shore and the deepest mine, above Everest. +pub(crate) const PLAUSIBLE_ELEVATION: (f64, f64) = (-500.0, 9000.0); /// 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)]; @@ -33,6 +43,8 @@ enum Kind { Step, Spike, Pit, + OutOfRange, + FlatRun, } impl Kind { @@ -41,12 +53,14 @@ impl Kind { Kind::Step => "step", Kind::Spike => "spike", Kind::Pit => "pit", + Kind::OutOfRange => "out of range", + Kind::FlatRun => "flat run", } } } -/// One finding: its cell, what it is, its size (the drop, or the height off the median) and the -/// elevation there. +/// One finding: its cell (a run's middle one), what it is, its size (the drop, the height off the +/// median, or a run's length in cells) and the elevation there (a run's first value). #[derive(Clone, Copy, Debug, PartialEq)] struct Finding { col: u32, @@ -63,14 +77,22 @@ struct Dem<'a> { ratio: f64, height: f64, spike: f64, + low: f64, + high: f64, + run: u32, } impl Dem<'_> { /// The value at a cell: `None` off the grid and for no-data. - fn level(&self, col: i64, row: i64) -> Option { + 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 one an elevation can have: the rules compare only these. + fn level(&self, col: i64, row: i64) -> Option { + self.value(col, row).filter(|v| (self.low..=self.high).contains(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. fn above_median(&self, col: i64, row: i64, v: f64) -> Option { @@ -115,6 +137,10 @@ struct Counts { steps: u64, spikes: u64, pits: u64, + out_runs: u64, + out_cells: u64, + flat_runs: u64, + flat_cells: u64, affected: u64, } @@ -126,26 +152,91 @@ impl Counts { steps: self.steps + o.steps, spikes: self.spikes + o.spikes, pits: self.pits + o.pits, + out_runs: self.out_runs + o.out_runs, + out_cells: self.out_cells + o.out_cells, + flat_runs: self.flat_runs + o.flat_runs, + flat_cells: self.flat_cells + o.flat_cells, affected: self.affected + o.affected, } } fn findings(&self) -> usize { - usize::try_from(self.steps + self.spikes + self.pits).unwrap_or(usize::MAX) + usize::try_from(self.steps + self.spikes + self.pits + self.out_runs + self.flat_runs).unwrap_or(usize::MAX) + } +} + +/// The lowest and highest values of `rows` an elevation can have. +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: its first column and value, and how many of its cells the other +/// rules found something in. +type Run = Option<(u32, f64, u64)>; + +/// Ends the 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, n.out_cells, n.affected) = (n.out_runs + 1, n.out_cells + u64::from(len), n.affected + u64::from(len)); + keep(Finding { col: start + len / 2, row, kind: Kind::OutOfRange, size: f64::from(len), elevation: v }); + } +} + +/// Ends the run of one value at column `end`: a finding when it is `dem.run` cells or more at the +/// band's lowest or highest value (`ends`), where an undeclared no-data lies. A lake held level at +/// any other value is not one. +fn close_flat(dem: &Dem<'_>, run: &mut Run, end: u32, row: u32, ends: Option<(f64, f64)>, n: &mut Counts, keep: &mut dyn FnMut(Finding)) { + if let Some((start, v, hits)) = run.take() { + let len = end.saturating_sub(start); + if len >= dem.run && ends.is_some_and(|(lo, hi)| v == lo || v == hi) { + (n.flat_runs, n.flat_cells) = (n.flat_runs + 1, n.flat_cells + u64::from(len)); + // Its cells found something already are affected once. + n.affected += u64::from(len).saturating_sub(hits); + 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. -fn scan(dem: &Dem<'_>, rows: Range, keep: &mut dyn FnMut(Finding)) -> Result { +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(); for row in rows { + 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, r) = (i64::from(col), i64::from(row)); - let Some(v) = dem.level(c, r) else { continue }; + let Some(v) = dem.value(c, r) else { + close_out(&mut out, col, row, &mut n, keep); + close_flat(dem, &mut flat, col, row, ends, &mut n, keep); + continue; + }; + if dem.level(c, r).is_none() { + n.cells += 1; + close_flat(dem, &mut flat, col, row, ends, &mut n, keep); + out.get_or_insert((col, v, 0)); + continue; + } + close_out(&mut out, col, row, &mut n, keep); + if flat.is_some_and(|(_, f, _)| f != v) { + close_flat(dem, &mut flat, col, row, ends, &mut n, keep); + } + flat.get_or_insert((col, v, 0)); let (step, whole) = dem.step(c, r, v); n.cells += 1; n.partial += u64::from(!whole); @@ -167,7 +258,12 @@ fn scan(dem: &Dem<'_>, rows: Range, keep: &mut dyn FnMut(Finding)) -> Resul keep(Finding { col, row, kind: Kind::Step, size, elevation: v }); } n.affected += u64::from(hit); + if let Some((_, _, hits)) = flat.as_mut() { + *hits += u64::from(hit); + } } + close_out(&mut out, dem.r.width, row, &mut n, keep); + close_flat(dem, &mut flat, dem.r.width, row, ends, &mut n, keep); } Ok(n) } @@ -211,11 +307,25 @@ pub(super) fn run_on(inp: &dyn Inputs, p: &Json, threads: Option) -> Resu if spike <= 0.0 { return Err("spikeHeight must be more than 0".into()); } - let dem = Dem { r, band: *band, ratio, height, spike }; + let (low, high) = (threshold(p, "lowest", PLAUSIBLE_ELEVATION.0)?, threshold(p, "highest", PLAUSIBLE_ELEVATION.1)?); + if low >= high { + return Err("lowest must be below highest".into()); + } + let run = threshold(p, "runLength", 100.0)?; + 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()); + } + let dem = Dem { r, band: *band, ratio, height, spike, low, high, run: run as u32 }; 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)); + // A first pass for the band's lowest and highest values, the ends a flat run is looked for at. + crate::control::begin(blocks.len()); + 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()); let taken = AtomicUsize::new(0); let scanned = crate::parallel::try_map_on( @@ -224,7 +334,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(), &mut |f| { + let n = scan(&dem, rows.clone(), ends, &mut |f| { if taken.fetch_add(1, Ordering::Relaxed) < MAX_POINTS { kept.push(f); } @@ -255,7 +365,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(), &mut |f| { + scan(&dem, rows.clone(), ends, &mut |f| { if kept.len() < *take { kept.push(f); } @@ -287,20 +397,30 @@ pub(super) fn run_on(inp: &dyn Inputs, p: &Json, threads: Option) -> Resu } } let mut messages = vec![format!( - "Checked {} cell(s) of band {} of '{name}': {} step(s), {} spike(s), {} pit(s); {:.3}% of the cells with a value are affected", + "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, total.affected 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, and the spike and pit rule a cell missing one of its eight neighbours", + "{} cell(s) at the edge, or next to no-data or a value out of range, lack a neighbour to compare with on some line: the step rule skips those lines, and the spike and pit rule skips a cell missing one of its eight neighbours", total.partial )); } + if total.flat_runs > 0 { + messages.push(format!( + "The {} flat run(s) hold the band's lowest or highest value in range: a no-data the file doesn't declare, or water held at that level, such as the sea at 0. Look at them before masking them", + total.flat_runs + )); + } 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, spike or pit a cell or two wide at full resolution may not show in it", @@ -388,7 +508,7 @@ mod tests { assert_eq!(rows, []); assert_eq!( said[0], - "Checked 3000 cell(s) of band 1 of 'dem': 0 step(s), 0 spike(s), 0 pit(s); 0.000% of the cells with a value are affected" + "Checked 3000 cell(s) of band 1 of 'dem': 0 step(s), 0 spike(s), 0 pit(s), 0 run(s) of values out of range (0 cells), 0 flat run(s) at the band's lowest or highest value (0 cells); 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:?}"); @@ -420,7 +540,7 @@ mod tests { let [(spike, up, (10, 10)), (pit, down, (20, 15))] = &rows[..] else { panic!("{rows:?}") }; assert_eq!((spike.as_str(), pit.as_str()), ("spike", "pit")); assert!((45.0..55.0).contains(up) && (40.0..50.0).contains(down), "{rows:?}"); - assert!(said[0].contains(": 0 step(s), 1 spike(s), 1 pit(s); 0.222%"), "{said:?}"); + assert!(said[0].contains(": 0 step(s), 1 spike(s), 1 pit(s), 0 run(s)") && said[0].contains("; 0.222%"), "{said:?}"); assert_eq!(found(&r, serde_json::json!({"spikeHeight": 60}), 1).0, []); } @@ -432,10 +552,46 @@ mod tests { assert_eq!(rows.len(), 40); assert_eq!( said[0], - "Checked 900 cell(s) of band 1 of 'dem': 36 step(s), 4 spike(s), 0 pit(s); 4.000% of the cells with a value are affected" + "Checked 900 cell(s) of band 1 of 'dem': 36 step(s), 4 spike(s), 0 pit(s), 0 run(s) of values out of range (0 cells), 0 flat run(s) at the band's lowest or highest value (0 cells); 4.000% of the cells with a value are affected" ); } + #[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 (rows, said) = found(&r, serde_json::json!({}), 1); + // A run is placed on its middle cell. The out-of-range cells aren't compared, so their + // neighbours aren't spikes or pits. + let want = [("out of range".to_string(), 5.0, (42, 5)), ("flat run".to_string(), 120.0, (60, 11))]; + assert_eq!(rows, want); + assert!( + said[0].contains("1 run(s) of values out of range (5 cells), 1 flat run(s) at the band's lowest or highest value (120 cells)"), + "{said:?}" + ); + // Water at the band's lowest value is counted too, and the summary says so. + assert!(said.iter().any(|s| s.starts_with("The 1 flat run(s) hold") && s.contains("the sea at 0")), "{said:?}"); + // A run shorter than asked is not one, nor a value inside a wider range. + assert!(found(&r, serde_json::json!({"runLength": 121}), 1).0.iter().all(|f| f.0 != "flat run")); + assert!(found(&r, serde_json::json!({"lowest": -40000}), 1).0.iter().all(|f| f.0 != "out of range")); + } + + #[test] + fn a_flat_run_of_pits_is_affected_once() { + // A row of 0 (the band's lowest) between rows near 100: its 118 inner cells are pits, and + // all 120 a flat run. + let r = dem(120, 9, |c, r| if r == 4 { 0.0 } else { 100.0 + ((c * 7 + r * 13) % 5) as f32 }); + let (rows, said) = found(&r, serde_json::json!({}), 1); + assert_eq!(rows.len(), 119); + assert!(said[0].ends_with("118 pit(s), 0 run(s) of values out of range (0 cells), 1 flat run(s) at the band's lowest or highest value (120 cells); 11.111% of the cells with a value are affected"), "{said:?}"); + } + #[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. @@ -464,10 +620,10 @@ mod tests { #[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. + // Four blocks of 256 rows, on one thread: stopped at the scan's look before its last block + // (after the four of the pass for the band's ends), three of the four are done. let r = dem(256, 1024, rough); - let run = crate::control::Control::cancelled_at_look(4); + let run = crate::control::Control::cancelled_at_look(8); 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))); @@ -480,6 +636,8 @@ mod tests { (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!({"spikeHeight": -5}), "spikeHeight 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!({"stepHeight": "high"}), "stepHeight must be a number"), (serde_json::json!({"band": 2}), "band"), ] { diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index a888f4c8ed..18dfc93b03 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -2486,18 +2486,26 @@ Cancel can wait for that mask fill to finish. **Check DEM** (`checkDem`) finds what 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, spikes and pits. It writes a point per finding, with `kind` (`step`, `spike` or -`pit`), `size` and the `elevation` there, and a summary of the counts and the share of the model's -cells affected, each cell once. It reports and changes nothing. +surface model, spikes, pits, and no-data the file doesn't declare. It writes a point per finding, +with `kind` (`step`, `spike`, `pit`, `out of range` or `flat run`), `size` and the `elevation` +there, and a summary of the counts and the share of the cells with a value affected, each cell +once. 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. Its `size` is the drop. A **spike** or a **pit** is a cell more than `spikeHeight` (default 30) above or below the median of its eight neighbours; its `size` is how -far. 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 spike and pit rule skips a cell missing one of its -eight neighbours. The layer holds the first 100,000 findings, from the top row down; the rest are +far. A run of **out of range** values along a row lies below `lowest` (default −500) or above +`highest` (default 9,000), such as −32768 or −9999 written for no-data; those values are left out +of the rules above, so a hole of them isn't also a ring of pits. A **flat run** is a run of at +least `runLength` (default 100) cells along a row at the band's lowest or highest value in range: a +no-data of 0, or the sea held at 0, which the summary names so that you look before masking it. A +lake held level at any other value is not one. A run is placed on its middle cell; its `size` is +its length in cells, and its `elevation` the run's first value. Heights are in the model's +elevation unit. Cells at the edge, or next to no-data or a value out of range, can't follow every +line, and the summary says how many; the spike and pit rule skips a cell missing one of its eight +neighbours. The layer holds the first 100,000 findings, 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, and 88% of the spikes and pits; the clean ANADEM terrain model of the Serra do Brigadeiro has 16 steps per million cells, and