Repository navigation
feat(analysis): Texture Shading tool writes the texture of an elevation model (#3146 part 2) #3363
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
elpidioassinaturas
merged 3 commits into
opengeos:main
from
elpidioassinaturas:feat/3146-texture-tool
Nov 29, 2026
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
25c3185
feat(analysis): Texture Shading tool writes the texture of an elevati…
elpidiofilho 337bbfb
feat(analysis): Texture Shading says when it measures degrees, and it…
elpidiofilho aaa2b14
fix(analysis): Texture Shading refuses percentiles that fall on one v…
elpidiofilho File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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<f64, String> { | ||
| 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<ToolResult, String> { | ||
| 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<usize>) -> Result<ToolResult, String> { | ||
| 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<f32> = cells.iter().copied().filter(|v| *v != crate::rasterops::NODATA).collect(); | ||
|
elpidioassinaturas marked this conversation as resolved.
Resolved
|
||
| 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<f32>| { | ||
| 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<crate::RasterInput<'_>> { | ||
| (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<String>) { | ||
| 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}"); | ||
| } | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.