From ae4a359790e076939f71cded01fe5a25d59715c9 Mon Sep 17 00:00:00 2001 From: mavrick Date: Wed, 25 Nov 2026 17:43:39 -0600 Subject: [PATCH 1/3] perf(raster): a hillshade counts its statistics, and rounding skips the C library A hillshade's bytes took their statistics from Raster::new, which reads every cell twice, one of the passes (the sums, in the band's order) on one thread. Its cells are whole numbers from 0 to 255, so derive_hillshade now counts how many hold each value, on several threads, and BandStats::of_byte_counts makes the same statistics from the counts: sums of whole numbers are exact in f64 below 2^53, so the mean and spread are the same to the bit, and the histogram and categories are binned as Tally::run bins them. Cells that aren't whole numbers to 255 take Raster::new's statistics as before. On x86-64's baseline, f64::round and f64::fract call the C library. The hillshade's rounding, a band's histogram bin and the whole-number test in its statistics now use a conversion to an integer instead, with the same results for the values they take. --- crates/analysis/src/rasterops.rs | 95 +++++++++++++++++++++++++++++++- crates/data/src/raster/mod.rs | 75 ++++++++++++++++++++++++- 2 files changed, 165 insertions(+), 5 deletions(-) diff --git a/crates/analysis/src/rasterops.rs b/crates/analysis/src/rasterops.rs index 1fcceac7b6..010888b5c6 100644 --- a/crates/analysis/src/rasterops.rs +++ b/crates/analysis/src/rasterops.rs @@ -4,7 +4,7 @@ use std::ops::Range; -use rustgis_data::raster::{ColorHint, Crs, GeoTransform, Raster, Transformer}; +use rustgis_data::raster::{BandStats, ColorHint, Crs, GeoTransform, Raster, Transformer}; use rustgis_geom::{Coord, Extent}; /// The no-data value written by these operations. @@ -43,6 +43,10 @@ pub fn derive(r: &Raster, name: &str, bands: Vec>) -> Result) -> Result { r.require_coordinates()?; for v in &mut shade { @@ -50,7 +54,51 @@ pub fn derive_hillshade(r: &Raster, name: &str, mut shade: Vec) -> Result Result, String> { + let chunks: Vec<&[f32]> = cells.chunks(BYTE_COUNT_CHUNK).collect(); + crate::control::begin(chunks.len()); + // Sixteen chunks, a million cells, before threads pay off. + let counted = crate::parallel::try_map( + &chunks, + 16, + || (), + |_, _, chunk: &&[f32]| { + let mut counts = [0u64; 256]; + for &v in *chunk { + let byte = v as u8; + if f32::from(byte) != v { + return Ok::<_, String>(None); + } + if let Some(c) = counts.get_mut(usize::from(byte)) { + *c += 1; + } + } + Ok(Some(counts)) + }, + )?; + let mut counts = [0u64; 256]; + for chunk in counted { + let Some(chunk) = chunk else { return Ok(None) }; + counts.iter_mut().zip(chunk).for_each(|(a, b)| *a += b); + } + Ok(BandStats::of_byte_counts(&counts, Some(0))) } fn band(r: &Raster, b: usize) -> Result<&[f32], String> { @@ -291,10 +339,17 @@ pub fn hillshade_on(r: &Raster, b: usize, azimuth: f64, altitude: f64, zf: f64, let aspect = (-gx).atan2(-gy); cos_zen * slope.cos() + sin_zen * slope.sin() * (az - aspect).cos() }; - (v.max(0.0) * 255.0).round().max(1.0) + round_positive(v.max(0.0) * 255.0).max(1.0) }) } +/// `x.round()` for `x` from 0 to 2⁵², halves away from zero, without the call to the C library +/// that `round` makes where the processor has no instruction for it (x86-64's baseline). +fn round_positive(x: f64) -> f64 { + let whole = x as u64 as f64; + if x - whole >= 0.5 { whole + 1.0 } else { whole } +} + /// A band arithmetic expression over `b1`, `b2`… (+ - * / and parentheses, numbers). pub fn band_math(r: &Raster, expr: &str) -> Result, String> { band_math_on(None, r, expr) @@ -3093,6 +3148,40 @@ mod tests { ); } + /// A hillshade's bytes take the statistics [`Raster::new`] makes of them, counted instead of + /// read twice: over a ridged surface lit from several sides, with no-data in it, past a million + /// cells (on several threads); cells that aren't whole numbers to 255 take [`Raster::new`]'s. + #[test] + fn hillshade_bytes_take_the_statistics_of_their_cells() { + let gt = GeoTransform { origin_x: 500_000.0, origin_y: 4_800_000.0, pixel_width: 10.0, pixel_height: -10.0 }; + let utm = Crs::Epsg(32616); + let (w, h) = (1200usize, 1000usize); + let cells: Vec = (0..w * h) + .map(|i| { + let (x, y) = ((i % w) as f32, (i / w) as f32); + if (x - 600.0).hypot(y - 500.0) < 40.0 { -9999.0 } else { (x / 37.0).sin() * 80.0 + (y / 23.0).cos() * 50.0 } + }) + .collect(); + let dem = Raster::new("dem", w as u32, h as u32, vec![cells], gt, utm, Some(-9999.0), ColorHint::Gray, "Float32") + .unwrap_or_else(|e| panic!("{e}")); + let measured = |cells: Vec| { + Raster::new("shade", dem.width, dem.height, vec![cells], gt, utm, Some(0.0), ColorHint::Gray, "UInt8") + .unwrap_or_else(|e| panic!("{e}")) + .bands[0] + .stats + .clone() + }; + for azimuth in [0.0, 135.0, 315.0] { + let shade = hillshade(&dem, 0, azimuth, 45.0, 1.0).unwrap_or_default(); + let out = derive_hillshade(&dem, "shade", shade).unwrap_or_else(|e| panic!("{e}")); + assert_eq!(out.bands[0].stats, measured(out.bands[0].data.clone()), "azimuth {azimuth}"); + } + let mut fractions = vec![3.5_f32; w * h]; + fractions[0] = 300.0; + let out = derive_hillshade(&dem, "shade", fractions.clone()).unwrap_or_else(|e| panic!("{e}")); + assert_eq!(out.bands[0].stats, measured(fractions)); + } + /// A cell in full shadow is 1, not 0, so that the bytes made of a hillshade keep 0 for its /// no-data cells. #[test] diff --git a/crates/data/src/raster/mod.rs b/crates/data/src/raster/mod.rs index 33905bf3fa..bf3f0da1f7 100644 --- a/crates/data/src/raster/mod.rs +++ b/crates/data/src/raster/mod.rs @@ -308,7 +308,7 @@ impl BandStats { let x = v as f64; n += 1; (min, max) = (lower(min, x), higher(max, x)); - whole &= x.fract() == 0.0; + whole &= is_whole(x); if sum { sums = (sums.0 + x, sums.1 + x * x); } @@ -368,6 +368,38 @@ impl BandStats { BandStats { count: n, min, max, mean, std_dev, histogram, categories } } + /// Statistics of a band of whole numbers from 0 to 255, from how many of its cells hold each + /// (`counts`, by value), leaving out `nodata`: the same, to the bit, as [`Raster::new`] makes + /// by reading the cells, for a caller that counted them as it made them. The sums of whole + /// numbers are exact in `f64` as long as they stay below 2⁵³, so a pass over the cells in any + /// order makes the same mean and spread; `None` past that (some 1.4 × 10¹¹ cells). + pub fn of_byte_counts(counts: &[u64; 256], nodata: Option) -> Option { + let kept = || counts.iter().enumerate().filter(|&(v, &c)| c > 0 && nodata != Some(v as u8)).map(|(v, &c)| (v as u64, c)); + let n: u64 = kept().map(|(_, c)| c).sum(); + if n == 0 { + return Some(BandStats::default()); + } + if n > (1u64 << 53) / (255 * 255) { + return None; + } + let (sum, sum2) = kept().fold((0u64, 0u64), |(s, s2), (v, c)| (s + v * c, s2 + v * v * c)); + let (min, max) = (kept().next()?.0 as f64, kept().next_back()?.0 as f64); + let mean = sum as f64 / n as f64; + let std_dev = (sum2 as f64 / n as f64 - mean * mean).max(0.0).sqrt(); + // The bins as [`Tally::run`] makes them, for whole numbers within 16 bits. + let span = max - min; + let k = (HISTOGRAM_BINS as f64 - 1.0) / if span > 0.0 { span } else { 1.0 }; + let mut histogram = vec![0u64; HISTOGRAM_BINS]; + for (v, c) in kept() { + let bin = round_positive((v as f64 - min) * k) as usize; + if let Some(h) = histogram.get_mut(bin.min(HISTOGRAM_BINS - 1)) { + *h += c; + } + } + let categories = Some(kept().map(|(v, _)| v as f64).collect()); + Some(BandStats { count: n as usize, min, max, mean, std_dev, histogram, categories }) + } + /// The value below which `p` (0–100) percent of pixels fall, from the histogram. pub fn percentile(&self, p: f64) -> f64 { let total: u64 = self.histogram.iter().sum(); @@ -411,6 +443,20 @@ struct Tally { /// million. const PARALLEL_VALUES: usize = 1 << 20; +/// Whether finite `x` is a whole number: `x.fract() == 0.0`, without the call to the C library +/// that `fract` makes where the processor has no instruction for it (x86-64's baseline). From 2⁵² +/// up every `f64` is whole. +fn is_whole(x: f64) -> bool { + x.abs() >= 4_503_599_627_370_496.0 || x == x as i64 as f64 +} + +/// `x.round()` for `x` from 0 to 2⁵² (a histogram bin), halves away from zero, without the call +/// to the C library that `round` makes there. +fn round_positive(x: f64) -> f64 { + let whole = x as u64 as f64; + if x - whole >= 0.5 { whole + 1.0 } else { whole } +} + /// `x` when it is below `min`, else `min`: equal values (−0 and 0) keep the first. fn lower(min: f64, x: f64) -> f64 { if x < min { x } else { min } @@ -479,7 +525,7 @@ impl Tally { continue; } let x = v as f64; - let bin = ((x - b.min) * b.k).round() as usize; + let bin = round_positive((x - b.min) * b.k) as usize; if let Some(h) = histogram.get_mut(bin.min(HISTOGRAM_BINS - 1)) { *h += 1; } @@ -2316,6 +2362,31 @@ pub(crate) mod tests { assert_eq!(BandStats::compute_on(&vec![f32::NAN; n], valid, None, 4), BandStats::default()); } + /// A band of whole numbers to 255 has the same statistics, to the bit, from how many cells + /// hold each value as from the cells: on one thread and on several (past a million cells), with + /// no-data among them, one value, three, and nothing but no-data. + #[test] + fn byte_counts_make_the_statistics_of_the_cells() { + let gt = GeoTransform { origin_x: 500_000.0, origin_y: 4_800_000.0, pixel_width: 1.0, pixel_height: -1.0 }; + let utm = Crs::from_epsg(32611).unwrap(); + let spread = |n: u32| (0..n).map(|i| (i.wrapping_mul(2_654_435_761) >> 24) as f32).collect::>(); + let three = (0..1000).map(|i| [0.0, 1.0, 255.0][i % 3]).collect::>(); + for (w, h, cells) in [ + (1000, 100, spread(100_000)), + (1500, 1000, spread(1_500_000)), + (10, 10, vec![7.0; 100]), + (100, 10, three), + (5, 2, vec![0.0; 10]), + ] { + let mut counts = [0u64; 256]; + for v in &cells { + counts[*v as usize] += 1; + } + let r = Raster::new("bytes", w, h, vec![cells], gt, utm, Some(0.0), ColorHint::Gray, "UInt8").unwrap(); + assert_eq!(BandStats::of_byte_counts(&counts, Some(0)), Some(r.bands[0].stats.clone()), "{w} × {h}"); + } + } + /// Cells a raster's alpha draws see-through are left out of its colour bands' statistics, /// whatever their values (#1810): −3.4e38 in a Float32 image, a stray byte in an 8-bit one. An /// opaque black cell counts, the alpha band counts every cell, and a raster without alpha (or From 9efc94dd362de83df23c92f431afcab0ee199d38 Mon Sep 17 00:00:00 2001 From: mavrick Date: Wed, 25 Nov 2026 19:37:43 -0600 Subject: [PATCH 2/3] fix(raster): byte-count statistics refuse a count past usize, and share one rounding BandStats::of_byte_counts took its count as `n as usize`, which a count past 2^32 truncates where usize is 32 bits (the browser); it now refuses one that doesn't fit. The whole-number test is false for infinities, as fract's was; the hillshade rounds with rustgis_data::raster::round_positive rather than a copy of it; and a hillshade's bytes are counted a million cells at a time, so the counts held come to 0.05% of the cells. --- crates/analysis/src/rasterops.rs | 17 +++++------------ crates/data/src/raster/mod.rs | 17 ++++++++++------- 2 files changed, 15 insertions(+), 19 deletions(-) diff --git a/crates/analysis/src/rasterops.rs b/crates/analysis/src/rasterops.rs index 010888b5c6..41563b71c1 100644 --- a/crates/analysis/src/rasterops.rs +++ b/crates/analysis/src/rasterops.rs @@ -66,18 +66,18 @@ pub fn derive_hillshade(r: &Raster, name: &str, mut shade: Vec) -> Result Result, String> { let chunks: Vec<&[f32]> = cells.chunks(BYTE_COUNT_CHUNK).collect(); crate::control::begin(chunks.len()); - // Sixteen chunks, a million cells, before threads pay off. + // Two chunks, two million cells, before threads pay off. let counted = crate::parallel::try_map( &chunks, - 16, + 2, || (), |_, _, chunk: &&[f32]| { let mut counts = [0u64; 256]; @@ -339,17 +339,10 @@ pub fn hillshade_on(r: &Raster, b: usize, azimuth: f64, altitude: f64, zf: f64, let aspect = (-gx).atan2(-gy); cos_zen * slope.cos() + sin_zen * slope.sin() * (az - aspect).cos() }; - round_positive(v.max(0.0) * 255.0).max(1.0) + rustgis_data::raster::round_positive(v.max(0.0) * 255.0).max(1.0) }) } -/// `x.round()` for `x` from 0 to 2⁵², halves away from zero, without the call to the C library -/// that `round` makes where the processor has no instruction for it (x86-64's baseline). -fn round_positive(x: f64) -> f64 { - let whole = x as u64 as f64; - if x - whole >= 0.5 { whole + 1.0 } else { whole } -} - /// A band arithmetic expression over `b1`, `b2`… (+ - * / and parentheses, numbers). pub fn band_math(r: &Raster, expr: &str) -> Result, String> { band_math_on(None, r, expr) diff --git a/crates/data/src/raster/mod.rs b/crates/data/src/raster/mod.rs index bf3f0da1f7..96d4e7bc89 100644 --- a/crates/data/src/raster/mod.rs +++ b/crates/data/src/raster/mod.rs @@ -372,7 +372,8 @@ impl BandStats { /// (`counts`, by value), leaving out `nodata`: the same, to the bit, as [`Raster::new`] makes /// by reading the cells, for a caller that counted them as it made them. The sums of whole /// numbers are exact in `f64` as long as they stay below 2⁵³, so a pass over the cells in any - /// order makes the same mean and spread; `None` past that (some 1.4 × 10¹¹ cells). + /// order makes the same mean and spread; `None` past that (some 1.4 × 10¹¹ cells), or past + /// what a count of cells holds here (`usize`, 32 bits in the browser). pub fn of_byte_counts(counts: &[u64; 256], nodata: Option) -> Option { let kept = || counts.iter().enumerate().filter(|&(v, &c)| c > 0 && nodata != Some(v as u8)).map(|(v, &c)| (v as u64, c)); let n: u64 = kept().map(|(_, c)| c).sum(); @@ -383,6 +384,7 @@ impl BandStats { return None; } let (sum, sum2) = kept().fold((0u64, 0u64), |(s, s2), (v, c)| (s + v * c, s2 + v * v * c)); + let count = usize::try_from(n).ok()?; let (min, max) = (kept().next()?.0 as f64, kept().next_back()?.0 as f64); let mean = sum as f64 / n as f64; let std_dev = (sum2 as f64 / n as f64 - mean * mean).max(0.0).sqrt(); @@ -397,7 +399,7 @@ impl BandStats { } } let categories = Some(kept().map(|(v, _)| v as f64).collect()); - Some(BandStats { count: n as usize, min, max, mean, std_dev, histogram, categories }) + Some(BandStats { count, min, max, mean, std_dev, histogram, categories }) } /// The value below which `p` (0–100) percent of pixels fall, from the histogram. @@ -443,16 +445,17 @@ struct Tally { /// million. const PARALLEL_VALUES: usize = 1 << 20; -/// Whether finite `x` is a whole number: `x.fract() == 0.0`, without the call to the C library +/// Whether `x` is a whole number: `x.fract() == 0.0`, without the call to the C library /// that `fract` makes where the processor has no instruction for it (x86-64's baseline). From 2⁵² /// up every `f64` is whole. fn is_whole(x: f64) -> bool { - x.abs() >= 4_503_599_627_370_496.0 || x == x as i64 as f64 + x.is_finite() && (x.abs() >= 4_503_599_627_370_496.0 || x == x as i64 as f64) } -/// `x.round()` for `x` from 0 to 2⁵² (a histogram bin), halves away from zero, without the call -/// to the C library that `round` makes there. -fn round_positive(x: f64) -> f64 { +/// `x.round()` for `x` from 0 to 2⁵², halves away from zero, without the call to the C library +/// that `round` makes where the processor has no instruction for it (x86-64's baseline): for a +/// histogram's bins here, and a hillshade's cells. +pub fn round_positive(x: f64) -> f64 { let whole = x as u64 as f64; if x - whole >= 0.5 { whole + 1.0 } else { whole } } From 25393777f95e37c0e8d5bb7d85d0f874d5e3bb2d Mon Sep 17 00:00:00 2001 From: mavrick Date: Wed, 25 Nov 2026 20:23:27 -0600 Subject: [PATCH 3/3] fix(raster): a hillshade's byte counts go a chunk at a time to each thread Counted a million cells at a time, the chunks were too few for try_map's batches of 16: two of them, or seventeen, left the work on one or two threads. Each thread now takes one chunk at a time (try_map_each_on). The test also checks that a hillshade's bytes are counted, rather than only that their statistics are Raster::new's, which a fallback gives too. --- crates/analysis/src/rasterops.rs | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/crates/analysis/src/rasterops.rs b/crates/analysis/src/rasterops.rs index 41563b71c1..e47063c084 100644 --- a/crates/analysis/src/rasterops.rs +++ b/crates/analysis/src/rasterops.rs @@ -74,10 +74,12 @@ const BYTE_COUNT_CHUNK: usize = 1 << 20; fn byte_stats(cells: &[f32]) -> Result, String> { let chunks: Vec<&[f32]> = cells.chunks(BYTE_COUNT_CHUNK).collect(); crate::control::begin(chunks.len()); - // Two chunks, two million cells, before threads pay off. - let counted = crate::parallel::try_map( + // Two chunks, two million cells, before threads pay off; each thread takes one at a time, as + // there are few of them. + let threads = crate::parallel::threads_for_each(chunks.len(), 2, 0); + let counted = crate::parallel::try_map_each_on( &chunks, - 2, + threads, || (), |_, _, chunk: &&[f32]| { let mut counts = [0u64; 256]; @@ -3165,12 +3167,16 @@ mod tests { .clone() }; for azimuth in [0.0, 135.0, 315.0] { - let shade = hillshade(&dem, 0, azimuth, 45.0, 1.0).unwrap_or_default(); + let shade = hillshade(&dem, 0, azimuth, 45.0, 1.0).unwrap_or_else(|e| panic!("{e}")); + let mut bytes = shade.clone(); + bytes.iter_mut().filter(|v| !v.is_finite() || **v < 1.0).for_each(|v| *v = 0.0); + assert!(matches!(byte_stats(&bytes), Ok(Some(_))), "azimuth {azimuth}: not counted as bytes"); let out = derive_hillshade(&dem, "shade", shade).unwrap_or_else(|e| panic!("{e}")); assert_eq!(out.bands[0].stats, measured(out.bands[0].data.clone()), "azimuth {azimuth}"); } let mut fractions = vec![3.5_f32; w * h]; fractions[0] = 300.0; + assert!(matches!(byte_stats(&fractions), Ok(None)), "fractions counted as bytes"); let out = derive_hillshade(&dem, "shade", fractions.clone()).unwrap_or_else(|e| panic!("{e}")); assert_eq!(out.bands[0].stats, measured(fractions)); }