Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion crates/analysis/src/tools.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1141,7 +1141,7 @@ pub static TOOLS: &[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.",
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.",
params: &[
P {
name: "input",
Expand All @@ -1168,6 +1168,14 @@ 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: "output", label: "Output Name", kind: K::Text, required: false, default: "", help: "Output point layer name." },
],
run: check_dem::run,
Expand Down
172 changes: 140 additions & 32 deletions crates/analysis/src/tools/check_dem.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
//! 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.
//! 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.
//!
//! 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
Expand All @@ -9,6 +9,10 @@
//! 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.
//!
//! 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.
use super::*;
use rustgis_data::loss::{LossCode, LossMessage};
use std::ops::Range;
Expand All @@ -23,21 +27,42 @@ 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.
/// What a finding is, as its `kind` field says it.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Kind {
Step,
Spike,
Pit,
}

impl Kind {
fn name(self) -> &'static str {
match self {
Kind::Step => "step",
Kind::Spike => "spike",
Kind::Pit => "pit",
}
}
}

/// One finding: its cell, what it is, its size (the drop, or the height off the median) and the
/// elevation there.
#[derive(Clone, Copy, Debug, PartialEq)]
struct Finding {
col: u32,
row: u32,
kind: Kind,
size: f64,
elevation: f64,
}

/// One band of the model, and the step thresholds the parameters give.
/// One band of the model, and the thresholds the parameters give.
struct Dem<'a> {
r: &'a rustgis_data::raster::Raster,
band: usize,
ratio: f64,
height: f64,
spike: f64,
}

impl Dem<'_> {
Expand All @@ -46,6 +71,18 @@ impl Dem<'_> {
self.r.value(self.band, col, row).map(f64::from)
}

/// 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<f64> {
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);
Comment thread
elpidioassinaturas marked this conversation as resolved.
Resolved
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, the larger of the two).
Expand All @@ -70,21 +107,35 @@ impl Dem<'_> {
}

/// What one block of rows holds, counted: cells with a value, those with a line that couldn't be
/// followed, and steps.
/// followed, each kind of finding, and the cells found something, each once.
#[derive(Clone, Copy, Debug, Default)]
struct Counts {
cells: u64,
partial: u64,
steps: u64,
spikes: u64,
pits: u64,
affected: u64,
}

impl Counts {
fn steps(&self) -> usize {
usize::try_from(self.steps).unwrap_or(usize::MAX)
fn add(self, o: &Counts) -> Counts {
Counts {
cells: self.cells + o.cells,
partial: self.partial + o.partial,
steps: self.steps + o.steps,
spikes: self.spikes + o.spikes,
pits: self.pits + o.pits,
affected: self.affected + o.affected,
}
}

fn findings(&self) -> usize {
usize::try_from(self.steps + self.spikes + self.pits).unwrap_or(usize::MAX)
}
}

/// Checks `rows`, counting what it finds and handing each step to `keep`, in row order.
/// Checks `rows`, counting what it finds and handing each finding to `keep`, in row order.
fn scan(dem: &Dem<'_>, rows: Range<u32>, keep: &mut dyn FnMut(Finding)) -> Result<Counts, String> {
let mut n = Counts::default();
let mut pace = crate::control::Pace::default();
Expand All @@ -93,14 +144,29 @@ fn scan(dem: &Dem<'_>, rows: Range<u32>, keep: &mut dyn FnMut(Finding)) -> Resul
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);
let (c, r) = (i64::from(col), i64::from(row));
let Some(v) = dem.level(c, r) else { continue };
let (step, whole) = dem.step(c, r, v);
n.cells += 1;
n.partial += u64::from(!whole);
// A cell can be a step and a spike at once (a plateau's corner): affected once.
let mut hit = false;
match dem.above_median(c, r, v) {
Some(d) if d > dem.spike => {
(n.spikes, hit) = (n.spikes + 1, true);
keep(Finding { col, row, kind: Kind::Spike, size: d, elevation: v });
}
Some(d) if -d > dem.spike => {
(n.pits, hit) = (n.pits + 1, true);
keep(Finding { col, row, kind: Kind::Pit, size: -d, elevation: v });
}
_ => {}
}
if let Some(size) = step {
n.steps += 1;
keep(Finding { col, row, size, elevation: v });
(n.steps, hit) = (n.steps + 1, true);
keep(Finding { col, row, kind: Kind::Step, size, elevation: v });
}
n.affected += u64::from(hit);
}
}
Ok(n)
Expand Down Expand Up @@ -141,7 +207,11 @@ pub(super) fn run_on(inp: &dyn Inputs, p: &Json, threads: Option<usize>) -> Resu
if height <= 0.0 {
return Err("stepHeight must be more than 0".into());
}
let dem = Dem { r, band: *band, ratio, height };
let spike = threshold(p, "spikeHeight", 30.0)?;
if spike <= 0.0 {
return Err("spikeHeight must be more than 0".into());
}
let dem = Dem { r, band: *band, ratio, height, spike };
let per = (BLOCK_CELLS / (r.width as usize).max(1)).clamp(1, u32::MAX as usize) as u32;
let blocks: Vec<Range<u32>> = (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);
Expand All @@ -162,19 +232,15 @@ pub(super) fn run_on(inp: &dyn Inputs, p: &Json, threads: Option<usize>) -> Resu
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<Finding> = if total.steps() <= MAX_POINTS {
let total = scanned.iter().fold(Counts::default(), |t, (n, _)| t.add(n));
let findings: Vec<Finding> = if total.findings() <= 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);
let here = n.findings().min(left);
if here > 0 {
plan.push((rows.clone(), here));
left -= here;
Expand Down Expand Up @@ -213,33 +279,36 @@ pub(super) fn run_on(inp: &dyn Inputs, p: &Json, threads: Option<usize>) -> Resu
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)])
}
Some(at) => out.push_next(
Some(Geometry::Point(at)),
vec![Value::Text(f.kind.name().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",
"Checked {} cell(s) of band {} of '{name}': {} step(s), {} spike(s), {} pit(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,
total.spikes,
total.pits,
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",
"{} 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",
Comment thread
elpidioassinaturas marked this conversation as resolved.
Resolved
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",
"'{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",
r.width, r.height
));
}
let mut losses = Vec::new();
let found = total.steps();
let found = total.findings();
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());
Expand Down Expand Up @@ -288,19 +357,26 @@ mod tests {
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<String>) {
/// The findings as (kind, size, cell), and what was said.
fn found(r: &Raster, p: Json, threads: usize) -> (Vec<(String, f64, (i64, i64))>, Vec<String>) {
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()),
([Value::Text(kind), Value::Float(size), _], Some(Geometry::Point(at))) => (kind.clone(), *size, r.pixel_at(*at).unwrap()),
_ => panic!("{f:?}"),
});
(rows.collect(), result.messages.into_iter().chain(result.losses.into_iter().map(|l| l.text)).collect())
}

/// The findings, all steps, as (size, cell), and what was said.
fn check(r: &Raster, p: Json, threads: usize) -> (Vec<(f64, (i64, i64))>, Vec<String>) {
let (rows, said) = found(r, p, threads);
assert!(rows.iter().all(|f| f.0 == "step"), "{rows:?}");
(rows.into_iter().map(|(_, size, at)| (size, at)).collect(), said)
}

#[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.
Expand All @@ -310,7 +386,10 @@ mod tests {
};
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");
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"
);
// 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:?}");
}
Expand All @@ -329,6 +408,34 @@ mod tests {
assert_eq!(check(&r, serde_json::json!({"stepRatio": 100}), 1).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) => rough(c, r) + 50.0,
(20, 15) => rough(c, r) - 45.0,
_ => rough(c, r),
});
let (rows, said) = found(&r, serde_json::json!({}), 1);
// Neither is also a step, nor are its neighbours: the drops beside them are as large.
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_eq!(found(&r, serde_json::json!({"spikeHeight": 60}), 1).0, []);
}

#[test]
fn a_cell_both_a_step_and_a_spike_is_affected_once() {
// A plateau 100 m high: its 36 edge cells are steps, and its 4 corners spikes as well.
let r = dem(30, 30, |c, r| if (10..20).contains(&c) && (10..20).contains(&r) { 100.0 } else { 0.0 });
let (rows, said) = found(&r, serde_json::json!({}), 1);
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"
);
}

#[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.
Expand Down Expand Up @@ -372,6 +479,7 @@ mod tests {
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!({"spikeHeight": -5}), "spikeHeight must be more than 0"),
(serde_json::json!({"stepHeight": "high"}), "stepHeight must be a number"),
(serde_json::json!({"band": 2}), "band"),
] {
Expand Down
25 changes: 14 additions & 11 deletions docs/user-guide/analysis.md
Original file line number Diff line number Diff line change
Expand Up @@ -2484,21 +2484,24 @@ 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.
**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.
Comment thread
elpidioassinaturas marked this conversation as resolved.
Resolved

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.
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
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
no spikes or pits. On the desktop it runs in the background with progress and Cancel.

## Zonal statistics and polygon clipping

Expand Down
Loading