diff --git a/crates/analysis/src/density.rs b/crates/analysis/src/density.rs index ccfeeeb6fd..b7f7e1bd91 100644 --- a/crates/analysis/src/density.rs +++ b/crates/analysis/src/density.rs @@ -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 => { @@ -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() { diff --git a/crates/analysis/src/rasterops.rs b/crates/analysis/src/rasterops.rs index 3261174b6b..22d98a3c15 100644 --- a/crates/analysis/src/rasterops.rs +++ b/crates/analysis/src/rasterops.rs @@ -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(w: usize, h: usize) -> Result, 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(w: usize, h: usize, fill: T) -> Result, 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. @@ -812,7 +806,7 @@ fn project_ring(r: &Raster, ring: &[Coord]) -> Option> { /// 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>]) -> Option<(Range, Range, Vec)> { +pub fn polygon_mask(r: &Raster, polygons: &[Vec>]) -> Result, Range, Vec)>, String> { polygon_mask_with_failures(r, polygons, &mut Vec::new()) } @@ -822,7 +816,7 @@ pub fn polygon_mask_with_failures( r: &Raster, polygons: &[Vec>], failed_parts: &mut Vec, -) -> Option<(Range, Range, Vec)> { +) -> Result, Range, Vec)>, String> { let projected: Vec>> = polygons .iter() .enumerate() @@ -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 = Vec::new(); for (ri, row) in rows.clone().enumerate() { let y = f64::from(row) + 0.5; @@ -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 = - (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. @@ -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()]); }; @@ -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]; @@ -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. @@ -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]); } @@ -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![ @@ -1602,14 +1597,14 @@ 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()); @@ -1617,7 +1612,7 @@ mod tests { 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] diff --git a/crates/data/src/raster/ascii.rs b/crates/data/src/raster/ascii.rs index b1f744db58..b9d6d31240 100644 --- a/crates/data/src/raster/ascii.rs +++ b/crates/data/src/raster/ascii.rs @@ -72,7 +72,7 @@ pub(super) fn read_with_nodata(text: &str, name: &str, crs: Option, 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() { diff --git a/crates/data/src/raster/mod.rs b/crates/data/src/raster/mod.rs index 442c09290d..ab7e24d2e8 100644 --- a/crates/data/src/raster/mod.rs +++ b/crates/data/src/raster/mod.rs @@ -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(w: usize, h: usize) -> Result> { + 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(w: usize, h: usize, fill: T) -> Result> { + 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(n: usize, w: usize, h: usize) -> Result> { + 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"))] @@ -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>(raw: &[T], w: u32, h: u32, ch: usize, k: u32) -> Vec> { +fn deinterleave>(raw: &[T], w: u32, h: u32, ch: usize, k: u32) -> Result>> { let step = k.max(1) as usize; - let mut bands: Vec> = (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> = (0..ch).map(|_| grid(ow, oh)).collect::>()?; 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; @@ -744,7 +770,7 @@ fn deinterleave>(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 @@ -804,14 +830,14 @@ fn read_scan_limited(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); @@ -1001,6 +1027,20 @@ pub fn read_prj(path: &Path) -> Option { 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::(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::(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::(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 { let img = diff --git a/crates/data/src/raster/zarr.rs b/crates/data/src/raster/zarr.rs index 54f78d649d..73809b387f 100644 --- a/crates/data/src/raster/zarr.rs +++ b/crates/data/src/raster/zarr.rs @@ -1155,7 +1155,7 @@ fn axis(v: &[f64]) -> Option<(f64, f64)> { pub fn assemble(store: &Store, plan: &Plan, chunks: &HashMap>, name: &str, crs: Option) -> Result { 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 @@ -1270,7 +1270,7 @@ pub fn assemble(store: &Store, plan: &Plan, chunks: &HashMap>, 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()); } diff --git a/crates/engine/src/cmd/imagery.rs b/crates/engine/src/cmd/imagery.rs index f53c9b94e8..cf254d4950 100644 --- a/crates/engine/src/cmd/imagery.rs +++ b/crates/engine/src/cmd/imagery.rs @@ -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)))?;