diff --git a/crates/analysis/src/texture.rs b/crates/analysis/src/texture.rs index 75e576e177..8a2db044d0 100644 --- a/crates/analysis/src/texture.rs +++ b/crates/analysis/src/texture.rs @@ -29,7 +29,8 @@ const BLOCK_CELLS: usize = 1 << 16; /// The fractional Laplacian of band `b` of `r` with exponent `alpha`: positive on ridges, negative /// in valleys, in the band's unit per metre^α, [`NODATA`] where the band has none. Cells are /// measured in metres ([`Raster::cell_size_m`]: a geographic model at its middle's latitude, a -/// projected one's unit converted). An alpha the cells overflow Float32 with is an error. +/// projected one's unit converted). A texture that overflows Float32 is an error: an alpha too +/// large for the cells, or values near Float32's limit. /// /// A cell with no value is taken at the model's mean, so a hole stays level: the texture next to /// it is of the ground around it and a flat hole. @@ -152,9 +153,12 @@ pub(crate) fn texture_on(threads: Option, r: &Raster, b: usize, alpha: f6 } }, )?; - // |k|^α past Float32 (a large alpha on fine cells) turns every cell to NaN. + // |k|^α past Float32 (a large alpha on fine cells), or values near its limit, turn cells to NaN. if out.iter().any(|v| !v.is_finite()) { - return Err(format!("alpha {alpha} is too large for {}'s cells: the texture overflows", r.name)); + return Err(format!( + "the texture of {} overflows Float32: alpha {alpha} is too large for its cells, or the band holds values near Float32's limit (a no-data value it doesn't declare?)", + r.name + )); } Ok(out) } @@ -223,12 +227,21 @@ mod tests { } /// An alpha that overflows the filter on fine cells (4.4 rad/m to the 100th is 1e64, past - /// Float32) is refused, not written as cells of NaN. + /// Float32) is refused, not written as cells of NaN, and so is a no-data value near Float32's + /// limit that the model doesn't declare; the error names both. #[test] fn an_alpha_that_overflows_is_refused() { - let r = dem_in(Crs::Epsg(32723), (1., 1.), 20, 20, |c, rr| 100.0 + (c / 3.0).sin() + (rr / 2.0).cos()); - assert_eq!(texture(&r, 0, 100.0), Err("alpha 100 is too large for dem's cells: the texture overflows".into())); + let z = |c: f64, rr: f64| 100.0 + (c / 3.0).sin() + (rr / 2.0).cos(); + let r = dem_in(Crs::Epsg(32723), (1., 1.), 20, 20, z); + let overflow = |alpha: &str| { + format!( + "the texture of dem overflows Float32: alpha {alpha} is too large for its cells, or the band holds values near Float32's limit (a no-data value it doesn't declare?)" + ) + }; + assert_eq!(texture(&r, 0, 100.0), Err(overflow("100"))); assert!(texture(&r, 0, 2.0).unwrap().iter().all(|v| v.is_finite())); + let r = dem_in(Crs::Epsg(32723), (30., 30.), 20, 20, |c, rr| if c == 4.0 && rr == 7.0 { 3.4e38 } else { z(c, rr) }); + assert_eq!(texture(&r, 0, 0.5), Err(overflow("0.5"))); } #[test] diff --git a/crates/analysis/src/tools.rs b/crates/analysis/src/tools.rs index e919e334aa..501ea9a95b 100644 --- a/crates/analysis/src/tools.rs +++ b/crates/analysis/src/tools.rs @@ -7,6 +7,7 @@ mod geometry; mod network_analysis; mod repair_geometry; mod tabulate_area; +mod texture_shading; use geo::{BooleanOps, Contains, ConvexHull, CoordsIter, InteriorPoint, Intersects, MultiPolygon, Orient, Relate, orient::Direction}; use rustgis_data::raster::{Crs, Transformer}; @@ -1205,6 +1206,49 @@ pub static TOOLS: &[ToolSpec] = &[ ], run: check_dem::run, }, + ToolSpec { + id: "textureShading", + name: "Texture Shading", + toolbox: "Analysis › Terrain", + summary: "Writes the texture of an elevation model (Leland Brown's texture shading, a fractional Laplacian): ridges light and valleys dark at every scale, with no light direction, stretched to 0–1.", + params: &[ + P { + name: "input", + label: "Elevation Raster", + kind: K::RasterLayer, + required: true, + default: "", + help: "The elevation model to shade.", + }, + P { name: "band", label: "Band", kind: K::Number, required: false, default: "1", help: "1-based band of elevations." }, + P { + name: "alpha", + label: "Detail (Alpha)", + kind: K::Number, + required: false, + default: "0.5", + help: "More than 0, at most 1: the power of the spatial frequency the elevations are multiplied by. Higher sharpens the small valleys; lower keeps more of the large ones.", + }, + P { + name: "lowPercent", + label: "Low Percentile", + kind: K::Number, + required: false, + default: "0.5", + help: "The share of the cells, in percent, at or below which the texture is 0.", + }, + P { + name: "highPercent", + label: "High Percentile", + kind: K::Number, + required: false, + default: "99.5", + help: "The share of the cells, in percent, at or below which the texture is under 1.", + }, + P { name: "output", label: "Output Name", kind: K::Text, required: false, default: "", help: "Output raster name." }, + ], + run: texture_shading::run, + }, ToolSpec { id: "zonalStats", name: "Zonal Statistics", @@ -11916,10 +11960,10 @@ mod tests { if !spec.params.iter().any(|p| p.name.eq_ignore_ascii_case("output") && matches!(p.kind, K::Text)) { continue; } - // 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"); + // Check DEM and Texture Shading read only a raster, which `inputs()` doesn't hold, so + // they stop before they make anything: they are still run, to write nothing, but + // aren't counted among those expected to run (with them, fewer than half would). + tested += usize::from(!matches!(spec.id, "checkDem" | "textureShading")); 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/texture_shading.rs b/crates/analysis/src/tools/texture_shading.rs new file mode 100644 index 0000000000..6eeaa5c470 --- /dev/null +++ b/crates/analysis/src/tools/texture_shading.rs @@ -0,0 +1,201 @@ +//! Texture Shading (#3146): the fractional Laplacian of an elevation model +//! ([`crate::texture::texture`]) stretched to 0–1 between two percentiles, as a raster to draw +//! in grey, blend with a hillshade or classify. +use super::*; + +/// A number from the parameters: `default` when left out or empty. +fn number(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")), + } +} + +pub(super) fn run(inp: &dyn Inputs, p: &Json) -> Result { + run_on(inp, p, None) +} + +/// [`run`] on `threads` threads (as many as pay off when `None`): the same raster on any. +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 alpha = number(p, "alpha", 0.5)?; + if !(alpha > 0.0 && alpha <= 1.0) { + return Err("alpha must be more than 0 and at most 1".into()); + } + let (low, high) = (number(p, "lowPercent", 0.5)?, number(p, "highPercent", 99.5)?); + if !(0.0..100.0).contains(&low) || !(low < high && high <= 100.0) { + return Err("lowPercent and highPercent must be percentages, the low one below the high one".into()); + } + let mut cells = crate::texture::texture_on(threads, r, *band, alpha)?; + let mut values: Vec = cells.iter().copied().filter(|v| *v != crate::rasterops::NODATA).collect(); + let Some(last) = values.len().checked_sub(1) else { return Err(format!("band {} of '{name}' has no values", band + 1)) }; + let holes = cells.len() - values.len(); + let flat = values.iter().all(|v| *v == values[0]); + let at = |share: f64, values: &mut Vec| { + let i = ((share / 100.0) * last as f64).round() as usize; + *values.select_nth_unstable_by(i.min(last), f32::total_cmp).1 + }; + let (lo, hi) = (at(low, &mut values), at(high, &mut values)); + drop(values); + if !flat && hi <= lo { + return Err(format!( + "the texture of '{name}' is {lo:.3e} at both {low}% and {high}% of its cells: widen lowPercent and highPercent (0 and 100 take its whole range)" + )); + } + for v in cells.iter_mut().filter(|v| **v != crate::rasterops::NODATA) { + *v = if flat { 0.5 } else { ((*v - lo) / (hi - lo)).clamp(0.0, 1.0) }; + } + let out = crate::rasterops::derive(r, &out_name(p, format!("{name}_texture")), vec![cells])?; + let bytes = rustgis_data::raster::geotiff::write(&out, 0).map_err(|e| e.to_string())?; + let mut messages = vec![if !flat { + format!( + "Texture Shading: band {} of '{name}', alpha {alpha}, stretched to 0–1 from {lo:.3e} at {low}% to {hi:.3e} at {high}% of the cells; {} × {} cells", + band + 1, + r.width, + r.height + ) + } else { + format!("Texture Shading: band {} of '{name}' is flat, so every cell is 0.5", band + 1) + }]; + if holes > 0 { + messages.push(format!( + "{holes} cell(s) with no value stay without one; the texture around them takes them at the model's mean elevation, as level ground" + )); + } + if r.crs.is_geographic() { + let (cx, cy) = r.cell_size_m(); + messages.push(format!( + "'{name}' is in degrees: its cells are measured as {cx:.1} m × {cy:.1} m, at its middle latitude ({:.2}°), so the texture's scale drifts a little toward its north and south edges", + r.extent().center().y + )); + } + let name = out.name.clone(); + Ok(ToolResult { + losses: Vec::new(), + output: Output::Layers(vec![OutputLayer::Raster { file_name: format!("{name}.tif"), name, bytes }]), + messages, + }) +} + +#[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)`, -9999 its no-data. + fn dem(width: u32, height: u32, z: impl Fn(f64, f64) -> f64) -> Raster { + let values = (0..height).flat_map(|row| (0..width).map(move |col| (col, row))).map(|(c, r)| z(c.into(), r.into()) as f32).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() + } + + /// The raster written, read back, and what was said. + fn shade(r: &Raster, p: Json) -> (Raster, Vec) { + let mut p = p; + p["input"] = Json::from("dem"); + let result = run_on(&One(r), &p, Some(2)).unwrap(); + let Output::Layers(layers) = &result.output else { panic!("a raster") }; + let [OutputLayer::Raster { file_name, bytes, .. }] = layers.as_slice() else { panic!("one raster: {layers:?}") }; + (rustgis_data::raster::read_bytes(file_name, bytes).unwrap(), result.messages) + } + + /// Two ridges and the valley between them, each running north to south. + fn ridges(c: f64, _: f64) -> f64 { + 600.0 + 150.0 * (std::f64::consts::TAU * c / 40.0).cos() + } + + #[test] + fn ridges_are_light_and_valleys_dark_from_0_to_1() { + let (out, said) = shade(&dem(80, 30, ridges), serde_json::json!({})); + assert_eq!((out.width, out.height, out.transform), (80, 30, dem(1, 1, ridges).transform)); + let at = |c: usize| out.bands[0].data[15 * 80 + c]; + assert!(at(40) > 0.9 && at(20) < 0.1, "ridge {}, valley {}", at(40), at(20)); + assert!(out.bands[0].data.iter().all(|v| (0.0..=1.0).contains(v))); + assert!( + said.len() == 1 && said[0].contains("alpha 0.5") && said[0].contains("at 0.5%") && said[0].contains("at 99.5%"), + "{said:?}" + ); + let (wide, _) = + shade(&dem(80, 30, ridges), serde_json::json!({"lowPercent": 10, "highPercent": 90, "alpha": "0.8", "output": "t"})); + assert!(wide.name == "t" && wide.bands[0].data.iter().filter(|v| **v == 1.0).count() > 80 * 30 / 20); + } + + #[test] + fn holes_stay_holes_and_are_said() { + let r = dem(40, 20, |c, rr| if c == 5.0 && rr < 3.0 { -9999.0 } else { ridges(c, rr) }); + let (out, said) = shade(&r, serde_json::json!({})); + assert_eq!(out.bands[0].data.iter().filter(|v| !out.is_valid(**v)).count(), 3); + assert!(said.iter().any(|s| s.starts_with("3 cell(s) with no value")), "{said:?}"); + let (flat, said) = shade(&dem(20, 20, |_, _| 812.0), serde_json::json!({})); + assert!(flat.bands[0].data.iter().all(|v| *v == 0.5) && said[0].contains("is flat"), "{said:?}"); + } + + /// Percentiles that both fall on one value of a texture with relief are refused, saying how + /// to widen them, not taken for a flat model. + #[test] + fn percentiles_on_one_value_are_refused_not_said_flat() { + let r = dem(80, 30, ridges); + let e = run(&One(&r), &serde_json::json!({"input": "dem", "lowPercent": 50, "highPercent": 50.001})).err().unwrap_or_default(); + assert!( + e.starts_with("the texture of 'dem' is ") + && e.ends_with(" at both 50% and 50.001% of its cells: widen lowPercent and highPercent (0 and 100 take its whole range)"), + "{e}" + ); + } + + /// A model in degrees is measured at its middle latitude, and the message says so. + #[test] + fn a_model_in_degrees_says_where_its_cells_are_measured() { + let values = dem(40, 20, ridges).bands.remove(0).data; + let transform = GeoTransform { origin_x: -44.0, origin_y: -19.99, pixel_width: 0.001, pixel_height: -0.001 }; + let r = Raster::new("dem", 40, 20, vec![values], transform, Crs::Epsg(4326), None, ColorHint::Gray, "Float32").unwrap(); + let (_, said) = shade(&r, serde_json::json!({})); + assert!( + said.iter().any(|s| s + == "'dem' is in degrees: its cells are measured as 104.6 m × 110.6 m, at its middle latitude (-20.00°), so the texture's scale drifts a little toward its north and south edges"), + "{said:?}" + ); + assert!(!shade(&dem(40, 20, ridges), serde_json::json!({})).1.iter().any(|s| s.contains("in degrees"))); + } + + #[test] + fn bad_parameters_are_refused() { + let r = dem(10, 10, ridges); + for (p, e) in [ + (serde_json::json!({"alpha": 0}), "alpha must be more than 0 and at most 1"), + (serde_json::json!({"alpha": 1.5}), "alpha must be more than 0 and at most 1"), + (serde_json::json!({"alpha": "steep"}), "alpha must be a number"), + ( + serde_json::json!({"lowPercent": 99.5, "highPercent": 0.5}), + "lowPercent and highPercent must be percentages, the low one below the high one", + ), + (serde_json::json!({"highPercent": 101}), "lowPercent and highPercent must be percentages, the low one below the high one"), + (serde_json::json!({"input": "nothing"}), "choose an elevation raster"), + ] { + let mut p = p; + if p.get("input").is_none() { + p["input"] = Json::from("dem"); + } + assert_eq!(run(&One(&r), &p).err().as_deref(), Some(e), "{p}"); + } + } +} diff --git a/crates/engine/src/tests/cancellation.rs b/crates/engine/src/tests/cancellation.rs index 21af6097d5..c02f322faf 100644 --- a/crates/engine/src/tests/cancellation.rs +++ b/crates/engine/src/tests/cancellation.rs @@ -374,6 +374,7 @@ pub(super) fn long_commands(boundaries: bool) { ("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})), + ("textureShading", 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 836f3671a0..6f3296216a 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -475,6 +475,7 @@ Use these ids in `gp.run`'s `tool` parameter (`gp.tools` lists the available too | Zonal Statistics | `zonalStats` | Analysis › Raster | | Tabulate Area | `tabulateArea` | Analysis › Raster | | Check DEM | `checkDem` | Analysis › Terrain | +| Texture Shading | `textureShading` | Analysis › Terrain | | Kernel Density | `kernelDensity` | Analysis › Density | **Raster to PMTiles** (`rasterToPmtiles`) writes Web Mercator PNG tiles using the raster's current @@ -2520,6 +2521,26 @@ of where SRTM and the Copernicus 30 m model differ by more than 10 m, and 88% of 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. +## Texture shading + +**Texture Shading** (`textureShading`) draws the drainage network and the ridges between the +valleys at every scale at once, with no light direction: Leland Brown's texture shading, the +fractional Laplacian of the elevation model. In frequency it multiplies the elevations by `|k|^α`, +with `alpha` (default 0.5) more than 0 and at most 1: 0.8 sharpens the small valleys, lower values +keep more of the large ones. Ridges come out light and valleys dark. The result is stretched to 0–1 +between the `lowPercent` and `highPercent` percentiles of its cells (defaults 0.5 and 99.5), and +written as a 32-bit raster on the model's grid, to draw in grey, multiply with a hillshade or +classify. The model's mean is removed and its edges are mirrored 64 cells out before the filter, +so one edge doesn't bleed onto the other. Cells are measured in metres, a geographic model at its +middle's latitude, as the hillshade does, and the tool says so. A cell with no value stays without +one; the texture around it takes it as level ground at the model's mean, and the tool says how many +there are. A no-data value near Float32's limit that the model doesn't declare overflows the +texture and is refused: set it as the file's no-data value first. Percentiles that both fall on +one value of a texture that isn't flat are refused too: widen them. At its peak it holds two +working grids of 16 bytes for each cell of the model and its margins, about 8 times a Float32 model +and more by its margins; the stretch after them holds 8 bytes a cell. 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.