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
3 changes: 2 additions & 1 deletion crates/analysis/src/density.rs
Original file line number Diff line number Diff line change
Expand Up @@ -283,6 +283,8 @@ pub fn kernel_density(

// Accumulate in f64 to avoid precision loss when many point contributions overlap
let mut grid = crate::rasterops::new_band(w, h_rows, 0.0f64)?;
// (The output's room too, before the work: a grid that can't be held fails first.)
let mut grid_f32 = crate::rasterops::grid(w, h_rows)?;

match kernel {
KernelType::Quartic => {
Expand Down Expand Up @@ -313,7 +315,6 @@ pub fn kernel_density(
}
}

let mut grid_f32 = crate::rasterops::grid(w, h_rows)?;
for d in grid {
let val = d as f32;
if !val.is_finite() {
Expand Down
51 changes: 23 additions & 28 deletions crates/analysis/src/rasterops.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,21 +13,15 @@ pub const NODATA: f32 = -3.4e38;
pub const MAX_PIXELS: usize = 64_000_000;

/// Room for a grid of `w × h` cells of `T` (an output band, or a working grid of one), empty: a
/// grid the machine can't hold is an error saying so, instead of ending the program. (In the
/// browser and on Windows the check is reliable; Linux may promise memory it can't give later.)
/// grid the machine can't hold is an error saying so, instead of ending the program
/// ([`rustgis_data::raster::grid`]).
pub fn grid<T>(w: usize, h: usize) -> Result<Vec<T>, String> {
let no_memory = || format!("not enough memory for a {w} × {h} raster");
let n = w.checked_mul(h).ok_or_else(no_memory)?;
let mut v = Vec::new();
v.try_reserve_exact(n).map_err(|_| no_memory())?;
Ok(v)
rustgis_data::raster::grid(w, h).map_err(|e| e.to_string())
}

/// A `w × h` band filled with `fill` ([`grid`]).
pub fn new_band<T: Clone>(w: usize, h: usize, fill: T) -> Result<Vec<T>, String> {
let mut v = grid(w, h)?;
v.resize(w * h, fill);
Ok(v)
rustgis_data::raster::filled(w, h, fill).map_err(|e| e.to_string())
}

/// A new single- or multi-band raster on `r`'s grid.
Expand Down Expand Up @@ -812,7 +806,7 @@ fn project_ring(r: &Raster, ring: &[Coord]) -> Option<Vec<(f64, f64)>> {
/// The rings are projected onto the raster's own grid once and filled by scanline, so a large
/// raster costs a pass over the polygon edges per row rather than a point test per cell.
/// A malformed ring or a failed projection rejects the entire polygon part, including its holes.
pub fn polygon_mask(r: &Raster, polygons: &[Vec<Vec<Coord>>]) -> Option<(Range<u32>, Range<u32>, Vec<bool>)> {
pub fn polygon_mask(r: &Raster, polygons: &[Vec<Vec<Coord>>]) -> Result<Option<(Range<u32>, Range<u32>, Vec<bool>)>, String> {
Comment thread
pick2510 marked this conversation as resolved.
Resolved
polygon_mask_with_failures(r, polygons, &mut Vec::new())
}

Expand All @@ -822,7 +816,7 @@ pub fn polygon_mask_with_failures(
r: &Raster,
polygons: &[Vec<Vec<Coord>>],
failed_parts: &mut Vec<usize>,
) -> Option<(Range<u32>, Range<u32>, Vec<bool>)> {
) -> Result<Option<(Range<u32>, Range<u32>, Vec<bool>)>, String> {
let projected: Vec<Vec<Vec<(f64, f64)>>> = polygons
.iter()
.enumerate()
Expand All @@ -840,16 +834,16 @@ pub fn polygon_mask_with_failures(
(c0, r0, c1, r1) = (c0.min(x), r0.min(y), c1.max(x), r1.max(y));
}
if !(c0.is_finite() && r0.is_finite() && c1.is_finite() && r1.is_finite()) {
return None;
return Ok(None);
}
let clamp = |v: f64, n: u32| v.clamp(0.0, f64::from(n)) as u32;
let cols = clamp(c0.floor(), r.width)..clamp(c1.ceil(), r.width);
let rows = clamp(r0.floor(), r.height)..clamp(r1.ceil(), r.height);
if cols.is_empty() || rows.is_empty() {
return None;
return Ok(None);
}
let w = (cols.end - cols.start) as usize;
let mut mask = vec![false; w * (rows.end - rows.start) as usize];
let mut mask = new_band(w, (rows.end - rows.start) as usize, false)?;
let mut xs: Vec<f64> = Vec::new();
for (ri, row) in rows.clone().enumerate() {
let y = f64::from(row) + 0.5;
Expand Down Expand Up @@ -885,13 +879,14 @@ pub fn polygon_mask_with_failures(
(tc0, tr0, tc1, tr1) = (tc0.min(c), tr0.min(rr), tc1.max(c + 1), tr1.max(rr + 1));
}
if tc0 >= tc1 || tr0 >= tr1 {
return None;
return Ok(None);
}
let trimmed: Vec<bool> =
(tr0..tr1).flat_map(|rr| (tc0..tc1).map(move |c| (rr, c))).map(|(rr, c)| mask.get(rr * w + c).copied().unwrap_or(false)).collect();
let mut trimmed = grid(tc1 - tc0, tr1 - tr0)?;
trimmed
.extend((tr0..tr1).flat_map(|rr| (tc0..tc1).map(move |c| (rr, c))).map(|(rr, c)| mask.get(rr * w + c).copied().unwrap_or(false)));
let cols = cols.start + tc0 as u32..cols.start + tc1 as u32;
let rows = rows.start + tr0 as u32..rows.start + tr1 as u32;
Some((cols, rows, trimmed))
Ok(Some((cols, rows, trimmed)))
}

/// Summary statistics of raster cells within a zone.
Expand Down Expand Up @@ -1008,7 +1003,7 @@ pub(crate) fn zonal_statistics_with_failures(
return Ok(Vec::new());
}

let Some((cols, rows, mask)) = polygon_mask_with_failures(r, polygons, failed_parts) else {
let Some((cols, rows, mask)) = polygon_mask_with_failures(r, polygons, failed_parts)? else {
return Ok(vec![ZoneStats::default(); bands.len()]);
};

Expand Down Expand Up @@ -1281,7 +1276,7 @@ mod tests {
};
// A square with a hole, and a second polygon in the south-west corner.
let polys = vec![vec![sq(0.005, 0.005, 0.015, 0.015), sq(0.009, 0.009, 0.011, 0.011)], vec![sq(0.0, 0.0, 0.002, 0.002)]];
let (cols, rows, mask) = polygon_mask(&r, &polys).unwrap_or_else(|| panic!("no mask"));
let (cols, rows, mask) = polygon_mask(&r, &polys).unwrap().unwrap_or_else(|| panic!("no mask"));
assert_eq!((cols.clone(), rows.clone()), (0..15, 5..20));
assert_eq!(mask.iter().filter(|m| **m).count(), 100 - 4 + 4);
let at = |col: u32, row: u32| mask[((row - rows.start) * 15 + col - cols.start) as usize];
Expand All @@ -1290,8 +1285,8 @@ mod tests {
assert!(!at(9, 9) && !at(10, 10), "the hole stays out");
assert!(at(0, 19) && at(1, 18) && !at(2, 18));
// Outside the raster, or too small to hold a cell centre: nothing.
assert!(polygon_mask(&r, &[vec![sq(1.0, 1.0, 2.0, 2.0)]]).is_none());
assert!(polygon_mask(&r, &[vec![sq(0.0051, 0.0051, 0.0052, 0.0052)]]).is_none());
assert!(polygon_mask(&r, &[vec![sq(1.0, 1.0, 2.0, 2.0)]]).unwrap().is_none());
assert!(polygon_mask(&r, &[vec![sq(0.0051, 0.0051, 0.0052, 0.0052)]]).unwrap().is_none());
}

/// A failed hole drops only its containing part and reports that part, even with no mask.
Expand All @@ -1311,7 +1306,7 @@ mod tests {
assert_eq!(stats[0].count, 4);
assert_eq!(failures, vec![0]);
failures.clear();
assert!(polygon_mask_with_failures(&r, &[invalid], &mut failures).is_none());
assert!(polygon_mask_with_failures(&r, &[invalid], &mut failures).unwrap().is_none());
assert_eq!(failures, vec![0]);
}

Expand Down Expand Up @@ -1593,7 +1588,7 @@ mod tests {
]];
let bad_ext_stats = zonal_statistics(&r, &[0], &bad_ext_with_hole).unwrap();
assert_eq!(bad_ext_stats[0], ZoneStats::default());
assert!(polygon_mask(&r, &bad_ext_with_hole).is_none());
assert!(polygon_mask(&r, &bad_ext_with_hole).unwrap().is_none());

// 8. Exterior ring with non-finite/unprojectable coordinate is rejected
let nan_ext_with_hole = vec![vec![
Expand All @@ -1602,22 +1597,22 @@ mod tests {
]];
let nan_ext_stats = zonal_statistics(&r, &[0], &nan_ext_with_hole).unwrap();
assert_eq!(nan_ext_stats[0], ZoneStats::default());
assert!(polygon_mask(&r, &nan_ext_with_hole).is_none());
assert!(polygon_mask(&r, &nan_ext_with_hole).unwrap().is_none());

// 9. Polygon with defective hole (< 3 vertices or non-finite) is rejected rather than silently discarding the hole
let bad_hole_poly = vec![vec![
sq(0.005, 0.005, 0.015, 0.015), // valid exterior (5 points)
vec![Coord::new(0.009, 0.009), Coord::new(0.011, 0.011)], // invalid hole: only 2 points!
]];
assert!(polygon_mask(&r, &bad_hole_poly).is_none(), "polygon with defective hole must be rejected");
assert!(polygon_mask(&r, &bad_hole_poly).unwrap().is_none(), "polygon with defective hole must be rejected");
let bad_hole_stats = zonal_statistics(&r, &[0], &bad_hole_poly).unwrap();
assert_eq!(bad_hole_stats[0], ZoneStats::default());

let nan_hole_poly = vec![vec![
sq(0.005, 0.005, 0.015, 0.015),
vec![Coord::new(f64::NAN, 0.009), Coord::new(0.011, 0.009), Coord::new(0.011, 0.011), Coord::new(f64::NAN, 0.009)],
]];
assert!(polygon_mask(&r, &nan_hole_poly).is_none(), "polygon with non-finite hole must be rejected");
assert!(polygon_mask(&r, &nan_hole_poly).unwrap().is_none(), "polygon with non-finite hole must be rejected");
}

#[test]
Expand Down
2 changes: 1 addition & 1 deletion crates/data/src/raster/ascii.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ pub(super) fn read_with_nodata(text: &str, name: &str, crs: Option<Crs>, sidecar
y -= dy / 2.0;
}
// Each value takes at least two characters, so the text bounds what to reserve.
let mut data = Vec::with_capacity(n.min(text.len() / 2 + 1));
let mut data = super::room(n.min(text.len() / 2 + 1), w as usize, h as usize)?;
let mut rounded = 0u64;
let uncounted = Uncounted::new(nodata_exact, sidecar_nodata);
for (i, t) in tokens.take(n).enumerate() {
Expand Down
62 changes: 51 additions & 11 deletions crates/data/src/raster/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,31 @@ use serde::{Deserialize, Serialize};

use crate::{DataError, Result};

/// Room for a band of `w × h` samples of `T`, empty: a band the machine can't hold is an error
/// saying so, instead of ending the program (#1291). (In the browser and on Windows the check is
/// reliable; Linux may promise memory it can't give later.)
pub fn grid<T>(w: usize, h: usize) -> Result<Vec<T>> {
room(w.checked_mul(h).ok_or_else(|| no_memory(w, h))?, w, h)
}

/// A `w × h` band filled with `fill` ([`grid`]).
pub fn filled<T: Clone>(w: usize, h: usize, fill: T) -> Result<Vec<T>> {
let mut v = grid(w, h)?;
v.resize(w * h, fill);
Ok(v)
}

/// Room for `n` samples of a `w × h` band (fewer than all of them, when fewer can come).
pub(crate) fn room<T>(n: usize, w: usize, h: usize) -> Result<Vec<T>> {
let mut v = Vec::new();
v.try_reserve_exact(n).map_err(|_| no_memory(w, h))?;
Ok(v)
}

fn no_memory(w: usize, h: usize) -> DataError {
DataError::Format(format!("not enough memory for a {w} × {h} raster"))
}

/// Most samples (pixels × bands) held in memory: 120 million (480 MB), or 32 million in the
/// browser, whose memory is much tighter. Reading briefly needs about twice this.
#[cfg(not(target_arch = "wasm32"))]
Expand Down Expand Up @@ -733,9 +758,10 @@ pub(crate) fn unreferenced(w: u32, h: u32) -> GeoTransform {
}

/// Every `k`-th pixel of interleaved `ch`-sample pixels, one vector per band.
fn deinterleave<T: Copy + Into<f32>>(raw: &[T], w: u32, h: u32, ch: usize, k: u32) -> Vec<Vec<f32>> {
fn deinterleave<T: Copy + Into<f32>>(raw: &[T], w: u32, h: u32, ch: usize, k: u32) -> Result<Vec<Vec<f32>>> {
let step = k.max(1) as usize;
let mut bands: Vec<Vec<f32>> = (0..ch).map(|_| Vec::with_capacity((w as usize).div_ceil(step) * (h as usize).div_ceil(step))).collect();
let (ow, oh) = ((w as usize).div_ceil(step), (h as usize).div_ceil(step));
let mut bands: Vec<Vec<f32>> = (0..ch).map(|_| grid(ow, oh)).collect::<Result<_>>()?;
for row in (0..h as usize).step_by(step) {
for col in (0..w as usize).step_by(step) {
let at = (row * w as usize + col) * ch;
Expand All @@ -744,7 +770,7 @@ fn deinterleave<T: Copy + Into<f32>>(raw: &[T], w: u32, h: u32, ch: usize, k: u3
}
}
}
bands
Ok(bands)
}

/// Reads a PNG or JPEG as a raster with no coordinates (`georeferenced` is false): its bands as
Expand Down Expand Up @@ -804,14 +830,14 @@ fn read_scan_limited<R: std::io::BufRead + std::io::Seek>(name: &str, mut source
}
}
let (bands, color, data_type) = match &img {
D::ImageLuma8(i) => (deinterleave(i.as_raw(), w, h, ch, k), ColorHint::Gray, "UInt8"),
D::ImageLumaA8(i) => (deinterleave(i.as_raw(), w, h, ch, k), ColorHint::GrayAlpha, "UInt8"),
D::ImageRgb8(i) => (deinterleave(i.as_raw(), w, h, ch, k), ColorHint::Rgb { alpha: false }, "UInt8"),
D::ImageRgba8(i) => (deinterleave(i.as_raw(), w, h, ch, k), ColorHint::Rgb { alpha: true }, "UInt8"),
D::ImageLuma16(i) => (deinterleave(i.as_raw(), w, h, ch, k), ColorHint::Gray, "UInt16"),
D::ImageLumaA16(i) => (deinterleave(i.as_raw(), w, h, ch, k), ColorHint::GrayAlpha, "UInt16"),
D::ImageRgb16(i) => (deinterleave(i.as_raw(), w, h, ch, k), ColorHint::Rgb { alpha: false }, "UInt16"),
D::ImageRgba16(i) => (deinterleave(i.as_raw(), w, h, ch, k), ColorHint::Rgb { alpha: true }, "UInt16"),
D::ImageLuma8(i) => (deinterleave(i.as_raw(), w, h, ch, k)?, ColorHint::Gray, "UInt8"),
D::ImageLumaA8(i) => (deinterleave(i.as_raw(), w, h, ch, k)?, ColorHint::GrayAlpha, "UInt8"),
D::ImageRgb8(i) => (deinterleave(i.as_raw(), w, h, ch, k)?, ColorHint::Rgb { alpha: false }, "UInt8"),
D::ImageRgba8(i) => (deinterleave(i.as_raw(), w, h, ch, k)?, ColorHint::Rgb { alpha: true }, "UInt8"),
D::ImageLuma16(i) => (deinterleave(i.as_raw(), w, h, ch, k)?, ColorHint::Gray, "UInt16"),
D::ImageLumaA16(i) => (deinterleave(i.as_raw(), w, h, ch, k)?, ColorHint::GrayAlpha, "UInt16"),
D::ImageRgb16(i) => (deinterleave(i.as_raw(), w, h, ch, k)?, ColorHint::Rgb { alpha: false }, "UInt16"),
D::ImageRgba16(i) => (deinterleave(i.as_raw(), w, h, ch, k)?, ColorHint::Rgb { alpha: true }, "UInt16"),
_ => return Err(fail(&"this pixel format isn't supported")),
};
drop(img);
Expand Down Expand Up @@ -1001,6 +1027,20 @@ pub fn read_prj(path: &Path) -> Option<String> {
pub(crate) mod tests {
use super::*;

/// A band the machine can't hold is an error naming its size, not the end of the program
/// (#1291), on 64-bit (the reservation fails) and wasm32 (the size overflows) alike; one it can
/// is the size asked for.
#[test]
fn a_band_too_large_to_hold_is_an_error() {
let huge = 1usize << 31;
let err = grid::<f32>(huge, huge).unwrap_err().to_string();
assert_eq!(err, format!("not enough memory for a {huge} × {huge} raster"));
assert!(filled(usize::MAX, 2, 0u8).is_err());
assert!(room::<f64>(usize::MAX / 2, 1, 1).is_err(), "too many bytes to ask for");
assert_eq!(filled(3, 2, f32::NAN).map(|v| v.len()).ok(), Some(6));
assert!(grid::<u16>(4, 5).is_ok_and(|g| g.is_empty() && g.capacity() >= 20));
}

/// A PNG of `w`×`h` pixels, red in its top half and blue below.
pub(crate) fn png(w: u32, h: u32) -> Vec<u8> {
let img =
Expand Down
4 changes: 2 additions & 2 deletions crates/data/src/raster/zarr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1155,7 +1155,7 @@ fn axis(v: &[f64]) -> Option<(f64, f64)> {
pub fn assemble(store: &Store, plan: &Plan, chunks: &HashMap<String, Vec<u8>>, name: &str, crs: Option<Crs>) -> Result<Raster> {
let a = store.array(&plan.var).ok_or_else(|| bad("the variable is gone"))?;
let (h, w) = (a.shape.get(plan.y).copied().unwrap_or(0) as usize, a.shape.get(plan.x).copied().unwrap_or(0) as usize);
let mut grid = vec![f32::NAN; h * w];
let mut grid = super::filled(w, h, f32::NAN)?;
let (cy, cx) = (a.chunks.get(plan.y).copied().unwrap_or(1).max(1), a.chunks.get(plan.x).copied().unwrap_or(1).max(1));
let nd = a.shape.len();
// Values meaning "no data", before any scaling, as xarray reads them: the CF attributes, and a
Expand Down Expand Up @@ -1270,7 +1270,7 @@ pub fn assemble(store: &Store, plan: &Plan, chunks: &HashMap<String, Vec<u8>>, n
};
// North up and west to east: flip rows (or columns) as needed.
if dy > 0.0 {
let mut flipped = Vec::with_capacity(grid.len());
let mut flipped = super::grid(w, h)?;
for r in (0..h).rev() {
flipped.extend_from_slice(grid.get(r * w..(r + 1) * w).unwrap_or_default());
}
Expand Down
2 changes: 1 addition & 1 deletion crates/engine/src/cmd/imagery.rs
Original file line number Diff line number Diff line change
Expand Up @@ -731,7 +731,7 @@ fn process(s: &mut Session, p: &Value) -> CmdResult {
log::warn!("{pl}: {} feature(s) failed polygon validation during clipping", failed_features.len());
}
let mut failed_parts = Vec::new();
let (cols, rows, mask) = rasterops::polygon_mask_with_failures(&r, &polygons, &mut failed_parts).ok_or_else(|| {
let (cols, rows, mask) = rasterops::polygon_mask_with_failures(&r, &polygons, &mut failed_parts)?.ok_or_else(|| {
format!("no cell of {} falls inside {pl} ({} polygon part(s) failed raster projection)", r.name, failed_parts.len())
})?;
let out = clip_window(&r, cols, rows, Some(&mask), name(p, format!("{}_clip", r.name)))?;
Expand Down
Loading