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
94 changes: 91 additions & 3 deletions crates/analysis/src/rasterops.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -43,14 +43,64 @@ pub fn derive(r: &Raster, name: &str, bands: Vec<Vec<f32>>) -> Result<Raster, St

/// [`derive`] for a [`hillshade`]'s pixels: one band of whole numbers 1–255 stored as bytes
/// (`UInt8`), with 0 as no-data, so it is written as 8-bit samples, not 32-bit floats.
///
/// Its statistics come from how many cells hold each value, counted on several threads
/// ([`BandStats::of_byte_counts`]), the same as [`Raster::new`] makes by reading the cells twice,
/// one of the passes on one thread; cells that aren't whole numbers to 255 take that way instead.
pub fn derive_hillshade(r: &Raster, name: &str, mut shade: Vec<f32>) -> Result<Raster, String> {
r.require_coordinates()?;
for v in &mut shade {
if !v.is_finite() || *v < 1.0 {
*v = 0.0;
}
}
Raster::new(name, r.width, r.height, vec![shade], r.transform, r.crs, Some(0.0), ColorHint::Gray, "UInt8").map_err(|e| e.to_string())
let Some(stats) = byte_stats(&shade)? else {
return Raster::new(name, r.width, r.height, vec![shade], r.transform, r.crs, Some(0.0), ColorHint::Gray, "UInt8")
.map_err(|e| e.to_string());
};
let mut out = Raster::unmeasured(name, r.width, r.height, vec![shade], r.transform, r.crs, Some(0.0), ColorHint::Gray, "UInt8")
.map_err(|e| e.to_string())?;
if let Some(band) = out.bands.first_mut() {
band.stats = stats;
}
Ok(out)
}

/// The cells [`byte_stats`] counts at a time: its 2 KB of counts for each are 0.05% of their cells.
const BYTE_COUNT_CHUNK: usize = 1 << 20;

/// The statistics of `cells` with 0 as no-data, from how many hold each value, when every one is
/// a whole number from 0 to 255; `None` when one isn't.
fn byte_stats(cells: &[f32]) -> Result<Option<BandStats>, 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; each thread takes one at a time, as

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The threshold is two chunks, and a chunk is 1 << 20 cells, so two chunks is anything over a million cells (1,048,577 at least), not two million. The count is right and the comment misstates it. Suggested wording:

Suggested change
// Two chunks, two million cells, before threads pay off; each thread takes one at a time, as
// Two chunks (over a million cells) before threads pay off; each thread takes one chunk at a time, as

Category: quality

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Right, two chunks is anything past a million cells. Left for the release quality pass, as it changes only the comment.

// 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,
threads,
|| (),
|_, _, 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> {
Expand Down Expand Up @@ -291,7 +341,7 @@ 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)
rustgis_data::raster::round_positive(v.max(0.0) * 255.0).max(1.0)
})
}

Expand Down Expand Up @@ -3093,6 +3143,44 @@ 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<f32> = (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<f32>| {
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_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}"));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This assertion can't tell the counted path from the fallback. derive_hillshade returns Raster::new's statistics whenever byte_stats gives None, so if the new wiring silently fell back on every input, this test would still pass. The hillshade output here is whole numbers 0 to 255, so byte_stats should return Some. Asserting that directly would pin the wiring. For example, before this line: assert!(byte_stats(&shade).is_ok_and(|s| s.is_some()), "azimuth {azimuth}: not counted as bytes");, with shade cloned for the call. Also, unwrap_or_default() on the line above discards the hillshade's error message. unwrap_or_else(|e| panic!("{e}")) would keep it, matching the lines around it.

Category: quality

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added in 2539377: the test now asserts byte_stats counts each hillshade (and refuses the fractions), and it fails with "not counted as bytes" when byte_stats always gives None. Whether derive_hillshade then uses the counts can't be seen from its output, since both paths make the same statistics by design. A miswiring would cost speed, not change a result. The hillshade's error is kept too (unwrap_or_else).

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));
}

/// 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]
Expand Down
78 changes: 76 additions & 2 deletions crates/data/src/raster/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
Expand Down Expand Up @@ -368,6 +368,40 @@ 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), 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<u8>) -> Option<BandStats> {
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 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();
// 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, 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();
Expand Down Expand Up @@ -411,6 +445,21 @@ struct Tally {
/// million.
const PARALLEL_VALUES: usize = 1 << 20;

/// 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.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⁵², 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 }
}

/// `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 }
Expand Down Expand Up @@ -479,7 +528,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;
}
Expand Down Expand Up @@ -2316,6 +2365,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::<Vec<f32>>();
let three = (0..1000).map(|i| [0.0, 1.0, 255.0][i % 3]).collect::<Vec<f32>>();
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
Expand Down
Loading