From cb493941421d36f87c7bcfea528b668abdb45c76 Mon Sep 17 00:00:00 2001 From: mavrick Date: Wed, 25 Nov 2026 02:24:34 -0600 Subject: [PATCH 1/3] feat(raster): Raster Functions, the Function Editor and resample work a block at a time on a large tiled GeoTIFF (#2865) Over a layer read in place from a file too large to read whole at its full size, these now read it a block at a time at that size, as Indices does (#2888): - Raster Functions: band math, NDVI, remap and threshold by cell; slope, aspect and hillshade over a cell's neighbours, each block read with the cells around it and its cells measured on the whole file's ground (`rasterops::slope_on` and the others). A hillshade is held and written as bytes and drawn as one; a remap's or threshold's file is of classes, its overviews taking a class, never an average (`cogwrite::Samples`). - The Function Editor, with those steps. A chain that remaps after a step over neighbours, or has a slope in percent before its last step, reads the file as before (`in_blocks::chain_halo`, shared with the permission check). - Process's resample, made from blocks whole multiples of its factor when its result can be held, its memory planned against a job's share (`in_blocks::affordable`); a larger one reads as before. A percent slope's cells past Float32's range are counted where the result keeps them, not in a block's margin. What remaps meet is said as of the whole raster, a count of values rounded as they were read says "at most" when blocks overlap, and a resample says its count. --- crates/analysis/src/rasterops.rs | 72 +++++-- crates/data/src/raster/cogwrite.rs | 140 +++++++++++-- crates/data/src/raster/mod.rs | 9 +- crates/engine/src/cmd/gp.rs | 19 +- crates/engine/src/cmd/imagery.rs | 129 +++++++++++- crates/engine/src/cmd/in_blocks.rs | 277 ++++++++++++++++++++++--- crates/engine/src/cmd/workflows.rs | 175 ++++++++++++++-- crates/engine/src/tests/tiled_files.rs | 124 +++++++++++ docs/user-guide/data.md | 16 +- 9 files changed, 870 insertions(+), 91 deletions(-) diff --git a/crates/analysis/src/rasterops.rs b/crates/analysis/src/rasterops.rs index 1fab346287..f6a5d91b67 100644 --- a/crates/analysis/src/rasterops.rs +++ b/crates/analysis/src/rasterops.rs @@ -132,16 +132,21 @@ pub fn per_index( /// The cells [`weighted_overlay`] makes at a time: its criteria carry no grid, so no rows. const OVERLAY_CHUNK: usize = 1 << 14; -/// Draw the interior from three borrowed rows; edges and no-data keep the scalar path. -fn terrain(r: &Raster, data: &[f32], zf: f64, f: impl Fn(f64, f64) -> f64 + Sync) -> Result, String> { - terrain_on(None, r, data, zf, f) -} - -/// [`terrain`] on `threads` threads (none: as many as pay off). Each output row is made from the +/// Draw the interior from three borrowed rows; edges and no-data keep the scalar path. On +/// `threads` threads (none: as many as pay off). Each output row is made from the /// three input rows around it and written where it lies, so rows go on several threads (#1252). -fn terrain_on(threads: Option, r: &Raster, data: &[f32], zf: f64, f: impl Fn(f64, f64) -> f64 + Sync) -> Result, String> { +/// Its cells measured on `ground` when given ([`Raster::cell_size_m_on`]), as the whole raster of +/// which `r` is a part measures them, else on `r`'s own. +fn terrain_on( + threads: Option, + r: &Raster, + data: &[f32], + zf: f64, + ground: Option<&Extent>, + f: impl Fn(f64, f64) -> f64 + Sync, +) -> Result, String> { let (w, h) = (r.width as usize, r.height as usize); - let cell = r.cell_size_m(); + let cell = ground.map_or_else(|| r.cell_size_m(), |g| r.cell_size_m_on(g)); let scalar = |c, row| { z(r, data, c, row)?; let (x, y) = gradient(r, data, c, row, zf, cell)?; @@ -199,41 +204,76 @@ fn terrain_on(threads: Option, r: &Raster, data: &[f32], zf: f64, f: impl /// Slope in degrees. pub fn slope(r: &Raster, b: usize, zf: f64) -> Result, String> { + slope_on(r, b, zf, None) +} + +/// [`slope`] of `r`, a part of a raster covering `ground`, its cells measured as the whole's are +/// ([`Raster::cell_size_m_on`]); `None`: `r` is the whole. +pub fn slope_on(r: &Raster, b: usize, zf: f64, ground: Option<&Extent>) -> Result, String> { let d = band(r, b)?; - terrain(r, d, zf, |gx, gy| gx.hypot(gy).atan().to_degrees()) + terrain_on(None, r, d, zf, ground, |gx, gy| gx.hypot(gy).atan().to_degrees()) } /// Slope as percent rise: 100 times the gradient magnitude, equivalent to 100 × tan(angle in radians). /// Uses the same Horn gradient, Z factor and no-data handling as [`slope`], without rounding /// through degree output first. Refuses output beyond Float32's range with a cell count. pub fn slope_percent(r: &Raster, b: usize, zf: f64) -> Result, String> { + slope_percent_on(r, b, zf, None) +} + +/// [`slope_percent`], as [`slope_on`]. +pub fn slope_percent_on(r: &Raster, b: usize, zf: f64, ground: Option<&Extent>) -> Result, String> { + let (pixels, n) = slope_percent_cells_on(r, b, zf, ground)?; + if n > 0 { Err(format!("{n} {PERCENT_OVERFLOW}")) } else { Ok(pixels) } +} + +/// What a percent slope says of its cells past Float32's range, after their count. +pub const PERCENT_OVERFLOW: &str = "percent slope cells exceed the Float32 range"; + +/// [`slope_percent_on`]'s cells, a cell past Float32's range infinite, and how many are: for a +/// part of a raster read with a margin, whose cells past the range the caller counts only where +/// it keeps them. +pub fn slope_percent_cells_on(r: &Raster, b: usize, zf: f64, ground: Option<&Extent>) -> Result<(Vec, usize), String> { use std::sync::atomic::{AtomicUsize, Ordering}; let d = band(r, b)?; let overflow = AtomicUsize::new(0); - let pixels = terrain(r, d, zf, |gx, gy| { + let pixels = terrain_on(None, r, d, zf, ground, |gx, gy| { let value = 100.0 * gx.hypot(gy); if !value.is_finite() || value > f64::from(f32::MAX) { overflow.fetch_add(1, Ordering::Relaxed); + // Finite, so it isn't taken for no value; infinite as a Float32. + return f64::MAX; } value })?; - let n = overflow.load(Ordering::Relaxed); - if n > 0 { Err(format!("{n} percent slope cells exceed the Float32 range")) } else { Ok(pixels) } + Ok((pixels, overflow.load(Ordering::Relaxed))) } /// Aspect: the compass direction the slope faces, in degrees (flat cells are -1). pub fn aspect(r: &Raster, b: usize) -> Result, String> { + aspect_on(r, b, None) +} + +/// [`aspect`], as [`slope_on`]. +pub fn aspect_on(r: &Raster, b: usize, ground: Option<&Extent>) -> Result, String> { let d = band(r, b)?; - terrain(r, d, 1.0, |gx, gy| if gx.abs() < 1e-12 && gy.abs() < 1e-12 { -1.0 } else { (-gx).atan2(-gy).to_degrees().rem_euclid(360.0) }) + terrain_on(None, r, d, 1.0, ground, |gx, gy| { + if gx.abs() < 1e-12 && gy.abs() < 1e-12 { -1.0 } else { (-gx).atan2(-gy).to_degrees().rem_euclid(360.0) } + }) } /// Hillshade (1–255) lit from `azimuth` and `altitude` degrees: a cell in full shadow is 1, so /// that 0 is left for the no-data of the bytes [`derive_hillshade`] makes of it. pub fn hillshade(r: &Raster, b: usize, azimuth: f64, altitude: f64, zf: f64) -> Result, String> { + hillshade_on(r, b, azimuth, altitude, zf, None) +} + +/// [`hillshade`], as [`slope_on`]. +pub fn hillshade_on(r: &Raster, b: usize, azimuth: f64, altitude: f64, zf: f64, ground: Option<&Extent>) -> Result, String> { let d = band(r, b)?; let (zen, az) = ((90.0 - altitude).to_radians(), azimuth.to_radians()); let (cos_zen, sin_zen) = (zen.cos(), zen.sin()); - terrain(r, d, zf, |gx, gy| { + terrain_on(None, r, d, zf, ground, |gx, gy| { let slope = gx.hypot(gy).atan(); let aspect = (-gx).atan2(-gy); let v = cos_zen * slope.cos() + sin_zen * slope.sin() * (az - aspect).cos(); @@ -2614,7 +2654,7 @@ mod tests { Some(f(x, y)) }); assert_eq!( - terrain(&r, data, zf, f), + terrain_on(None, &r, data, zf, None, f), expected, "{w}x{h}, {pixel_width}, {pixel_height}, holes={with_holes}, zf={zf}" ); @@ -2622,7 +2662,7 @@ mod tests { let bits = |v: Result, String>| v.map(|v| v.iter().map(|x| x.to_bits()).collect::>()); for threads in [1, 2, 7, 16] { assert_eq!( - bits(terrain_on(Some(threads), &r, data, zf, f)), + bits(terrain_on(Some(threads), &r, data, zf, None, f)), bits(expected.clone()), "{w}x{h}, {threads} threads" ); diff --git a/crates/data/src/raster/cogwrite.rs b/crates/data/src/raster/cogwrite.rs index fa16e6da48..db641e15c1 100644 --- a/crates/data/src/raster/cogwrite.rs +++ b/crates/data/src/raster/cogwrite.rs @@ -1111,18 +1111,38 @@ pub struct TileStream<'a, W: Write + Seek> { pos: u64, /// The value of a pixel with none, written for pixels past the image's edge too. nodata: f32, + /// Whole numbers 1 to 255 written as bytes, 0 for no value ([`Samples::Hillshade`]); floats + /// otherwise. + bytes: bool, + /// Classes, whose overviews take a pixel ([`Samples::Classes`]). + classes: bool, /// The level kept as it is written ([`TileStream::keeping`]), and its rows so far. kept: Option<(usize, Vec)>, /// What the kept level is made into: the template's name, place and no-data. template: Raster, } +/// What a [`TileStream`]'s band holds, which decides how it is stored and how its overviews are +/// made. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Samples { + /// Measures, as 32-bit floats; an overview pixel is the mean of the four it covers. + Floats, + /// Classes (a remap's, a threshold's), as 32-bit floats; an overview pixel takes one of the + /// four it covers, never an average no class has, as [`write_to`] makes a classes' overview. + Classes, + /// A hillshade's whole numbers 1 to 255, as bytes with 0 for no value; averaged, which never + /// gives 0 (no value) from pixels that have one. + Hillshade, +} + impl<'a, W: Write + Seek> TileStream<'a, W> { - /// A stream of a `width` × `height` raster into `out` (which must be empty: offsets are from - /// its start), placed, named and with the no-data value of `template` (its first band's name, - /// its transform's corner and pixel size, its system and rights holder; its own pixels and - /// size aren't written). A template without a no-data value marks pixels with none NaN. - pub fn new(template: &Raster, width: u32, height: u32, out: &'a mut W) -> Result> { + /// A stream of a `width` × `height` raster of `samples` into `out` (which must be empty: + /// offsets are from its start), placed, named and with the no-data value of `template` (its + /// first band's name, its transform's corner and pixel size, its system and rights holder; + /// its own pixels and size aren't written). A template without a no-data value marks pixels + /// with none NaN; a hillshade's no-data is 0. + pub fn new(template: &Raster, width: u32, height: u32, samples: Samples, out: &'a mut W) -> Result> { template.require_coordinates().map_err(err)?; let gt = template.transform; if gt.pixel_height > 0.0 || gt.pixel_width < 0.0 { @@ -1131,7 +1151,11 @@ impl<'a, W: Write + Seek> TileStream<'a, W> { if width == 0 || height == 0 { return Err(err("the raster has no pixels to write")); } - let plan = stream_plan(); + let bytes = samples == Samples::Hillshade; + if bytes && template.nodata != Some(0.0) { + return Err(err("a hillshade's pixels with no value are 0")); + } + let plan = stream_plan(bytes, template.nodata); let geo = geo_keys(template)?; let mut levels = vec![Level::new(width, height, 1)]; while let Some(last) = levels.last().filter(|l| l.w.max(l.h) > TILE) { @@ -1143,7 +1167,7 @@ impl<'a, W: Write + Seek> TileStream<'a, W> { } let tiles: usize = levels.iter().map(Level::tiles).sum(); // The worst a file can come to, as [`write_to`] reckons it. - let raw = (tiles as u64).saturating_mul(u64::from(TILE) * u64::from(TILE) * 4); + let raw = (tiles as u64).saturating_mul(u64::from(TILE) * u64::from(TILE) * if bytes { 1 } else { 4 }); let worst = raw.saturating_add(raw / 512).saturating_add(tiles as u64 * 64).saturating_add(1 << 20); let big = worst >= u64::from(u32::MAX); // A header past what a reader takes at a file's start couldn't be read in place: its @@ -1191,6 +1215,8 @@ impl<'a, W: Write + Seek> TileStream<'a, W> { patches: head.patches, big, nodata, + bytes, + classes: samples == Samples::Classes, kept: None, template: template.clone(), }) @@ -1296,26 +1322,31 @@ impl<'a, W: Write + Seek> TileStream<'a, W> { fn write_row(&mut self, i: usize, rows: &[f32]) -> Result<()> { let Some(lv) = self.levels.get(i) else { return Ok(()) }; let (w, across) = (lv.w as usize, lv.across as usize); - let (t, nodata) = (TILE as usize, self.nodata); - let plan = stream_plan(); - let line = t * 4; + let (t, nodata, bytes) = (TILE as usize, self.nodata, self.bytes); + let plan = stream_plan(bytes, Some(f64::from(nodata))); + let size = if bytes { 1 } else { 4 }; + let line = t * size; let make = |scratch: &mut Vec, tx: usize| -> Result> { - let mut raw = Vec::with_capacity(t * t * 4); + let mut raw = Vec::with_capacity(t * t * size); for y in 0..t { for x in 0..t { let col = tx * t + x; let v = if col < w { rows.get(y * w + col).copied().unwrap_or(nodata) } else { nodata }; let v = if v.is_nan() { nodata } else { v }; - raw.extend_from_slice(&v.to_le_bytes()); + if bytes { + raw.push(v.round().clamp(0.0, 255.0) as u8); + } else { + raw.extend_from_slice(&v.to_le_bytes()); + } } } - predict_rows(&mut raw, line, 1, Sample::Float, predictor(&plan), scratch); + predict_rows(&mut raw, line, 1, plan.sample, predictor(&plan), scratch); Ok(miniz_oxide::deflate::compress_to_vec_zlib(&raw, DEFLATE_FAST)) }; let (big, out, pos, places) = (self.big, &mut *self.out, &mut self.pos, &mut self.places); // The run's progress counts the caller's pieces, not these tiles. crate::progress::without_counting(|| { - in_order(across, t * t * 4, err, Vec::new, make, |_, zipped| { + in_order(across, t * t * size, err, Vec::new, make, |_, zipped| { if !big && *pos + zipped.len() as u64 > u64::from(u32::MAX) { return Err(err("the file is too large for classic TIFF")); } @@ -1330,7 +1361,7 @@ impl<'a, W: Write + Seek> TileStream<'a, W> { // The next level's rows: each the average of two of these (the last alone when they are // odd), two pixels across at a time. if i + 1 < self.levels.len() { - let half = average_rows(rows, w, nodata); + let half = if self.classes { pick_rows(rows, w, nodata) } else { average_rows(rows, w, nodata) }; self.put_level(i + 1, &half)?; } Ok(()) @@ -1363,7 +1394,12 @@ impl<'a, W: Write + Seek> TileStream<'a, W> { let (sx, sy) = (f64::from(full.w) / f64::from(lv.w.max(1)), f64::from(full.h) / f64::from(lv.h.max(1))); let gt = super::GeoTransform { pixel_width: t.transform.pixel_width * sx, pixel_height: t.transform.pixel_height * sy, ..t.transform }; - let mut r = Raster::new(t.name.clone(), lv.w, lv.h, vec![data], gt, t.crs, t.nodata, ColorHint::Gray, "Float32")?; + // As the file holds it: bytes rounded as they were written. + let (data, kind) = match self.bytes { + true => (data.into_iter().map(|v| if v.is_nan() { self.nodata } else { v.round().clamp(0.0, 255.0) }).collect(), "UInt8"), + false => (data, "Float32"), + }; + let mut r = Raster::new(t.name.clone(), lv.w, lv.h, vec![data], gt, t.crs, t.nodata, ColorHint::Gray, kind)?; if level > 0 { r.overview = Some((full.w, full.h)); } @@ -1374,9 +1410,35 @@ impl<'a, W: Write + Seek> TileStream<'a, W> { } } -/// What a [`TileStream`] writes: one band of 32-bit floats, averaged in its overviews. -fn stream_plan() -> Plan { - Plan { bands: vec![0], sample: Sample::Float, rgb: false, alpha: None, nodata_int: None, palette: None, categorical: false } +/// What a [`TileStream`] writes: one band of 32-bit floats, or with `bytes` of bytes whose +/// no-data value is `nodata`, averaged in its overviews. +fn stream_plan(bytes: bool, nodata: Option) -> Plan { + let (sample, nodata_int) = match bytes { + true => (Sample::Byte, nodata.filter(|d| (0.0..=255.0).contains(d)).map(|d| d as u16)), + false => (Sample::Float, None), + }; + Plan { bands: vec![0], sample, rgb: false, alpha: None, nodata_int, palette: None, categorical: false } +} + +/// `rows` of `w` pixels made half the size each way, for classes: each pixel the first of the up to +/// four it covers that has a value (not NaN, nor `nodata`), row by row, else `nodata`: always a +/// class one of them is, never one between them. +fn pick_rows(rows: &[f32], w: usize, nodata: f32) -> Vec { + let h = rows.len() / w.max(1); + let (hw, hh) = (w.div_ceil(2), h.div_ceil(2)); + let valid = |v: f32| v.is_finite() && v != nodata; + let mut out = Vec::with_capacity(hw * hh); + for y in 0..hh { + for x in 0..hw { + let first = [(0, 0), (0, 1), (1, 0), (1, 1)] + .into_iter() + .filter(|(dy, dx)| 2 * y + dy < h && 2 * x + dx < w) + .filter_map(|(dy, dx)| rows.get((2 * y + dy) * w + 2 * x + dx).copied()) + .find(|v| valid(*v)); + out.push(first.unwrap_or(nodata)); + } + } + out } /// `rows` of `w` pixels made half the size each way: each pixel the mean of the up to four it @@ -1435,6 +1497,42 @@ mod tests { assert_eq!(average_rows(&[nd, f32::NEG_INFINITY], 2, nd), [nd]); } + /// A classes' overview pixel is a class one of its four pixels is, the first with a value, + /// never an average between two. + #[test] + fn overview_rows_of_classes_take_a_class() { + let nd = -9999.0; + assert_eq!(pick_rows(&[1.0, 3.0, 3.0, 1.0], 2, nd), [1.0]); + assert_eq!(pick_rows(&[nd, f32::NAN, 2.0, 1.0], 2, nd), [2.0]); + assert_eq!(pick_rows(&[nd, nd, 4.0, nd, nd, nd], 3, nd), [nd, 4.0]); + } + + /// A hillshade's template (bytes, no-data 0) is streamed as bytes: it reads + /// back as `UInt8`, whole numbers, its no-data kept, and the overview kept is bytes too. + #[test] + fn a_stream_of_bytes_is_written_as_bytes() { + let (w, h) = (700u32, 600u32); + let value = |x: u32, y: u32| if (x + y).is_multiple_of(53) { 0.0 } else { f32::from(((x * 3 + y) % 254 + 1) as u8) }; + let data: Vec = (0..h).flat_map(|y| (0..w).map(move |x| value(x, y))).collect(); + let template = utm(1, 1, vec![vec![0.0]], ColorHint::Gray, "UInt8", Some(0.0)); + let mut out = Cursor::new(Vec::new()); + let mut stream = TileStream::new(&template, w, h, Samples::Hillshade, &mut out).unwrap().keeping(1 << 18); + stream.put(&data).unwrap(); + let (info, kept) = stream.finish().unwrap(); + assert_eq!(info.levels, vec![(700, 600), (350, 300)]); + let kept = kept.unwrap(); + assert_eq!((kept.width, kept.data_type.as_str(), kept.nodata), (350, "UInt8", Some(0.0))); + assert!(kept.bands[0].data.iter().all(|v| v.fract() == 0.0 && (0.0..=255.0).contains(v))); + let back = geotiff::read(Cursor::new(out.into_inner()), "back").unwrap(); + assert_eq!((back.width, back.height, back.data_type.as_str(), back.nodata), (w, h, "UInt8", Some(0.0))); + for y in 0..h { + for x in 0..w { + let v = value(x, y); + assert_eq!(back.value(0, i64::from(x), i64::from(y)), (v != 0.0).then_some(v), "{x},{y}"); + } + } + } + /// A raster streamed in pieces of uneven rows (#2865) reads back pixel for pixel, its no-data /// value kept, and each overview the average two by two of the level before; the layout's /// reader finds every level. @@ -1445,7 +1543,7 @@ mod tests { let data: Vec = (0..h).flat_map(|y| (0..w).map(move |x| value(x, y))).collect(); let template = utm(1, 1, vec![vec![0.0]], ColorHint::Gray, "Float32", Some(-9999.0)); let mut out = Cursor::new(Vec::new()); - let mut stream = TileStream::new(&template, w, h, &mut out).unwrap(); + let mut stream = TileStream::new(&template, w, h, Samples::Floats, &mut out).unwrap(); let mut at = 0usize; for rows in [1usize, 300, 511, 7, 281] { let n = rows * w as usize; @@ -1483,7 +1581,7 @@ mod tests { assert_eq!(layout.levels.len(), 3); // Rows that aren't whole rows, and an image left short, are errors. let mut out = Cursor::new(Vec::new()); - let mut stream = TileStream::new(&template, w, h, &mut out).unwrap(); + let mut stream = TileStream::new(&template, w, h, Samples::Floats, &mut out).unwrap(); assert!(stream.put(&data[..5]).is_err()); stream.put(&data[..w as usize]).unwrap(); assert!(stream.finish().is_err()); diff --git a/crates/data/src/raster/mod.rs b/crates/data/src/raster/mod.rs index 92f1936af3..33905bf3fa 100644 --- a/crates/data/src/raster/mod.rs +++ b/crates/data/src/raster/mod.rs @@ -1301,9 +1301,16 @@ impl Raster { /// Ground size of a pixel in metres (approximate for geographic rasters). pub fn cell_size_m(&self) -> (f64, f64) { + self.cell_size_m_on(&self.extent) + } + + /// [`Raster::cell_size_m`] as on `ground` (longitude/latitude): a cell of a geographic raster + /// measured at its middle's latitude, as a raster covering that ground measures its cells. A + /// part of a raster measures its cells so as the whole of it does. + pub fn cell_size_m_on(&self, ground: &Extent) -> (f64, f64) { let (x, y) = self.cell_size(); if self.crs.is_geographic() { - let lat = self.extent.center().y.to_radians().cos().abs().max(0.01); + let lat = ground.center().y.to_radians().cos().abs().max(0.01); (x * 111_320.0 * lat, y * 110_574.0) } else { (x, y) diff --git a/crates/engine/src/cmd/gp.rs b/crates/engine/src/cmd/gp.rs index 857c8a2894..75e90a93ed 100644 --- a/crates/engine/src/cmd/gp.rs +++ b/crates/engine/src/cmd/gp.rs @@ -1666,25 +1666,34 @@ pub(crate) struct ReadNote { rounded: u64, overview: Option<((u32, u32), (u32, u32))>, part: Option<(u32, u32)>, + /// The count of values rounded is at most `rounded`: some were read twice or more. + at_most: bool, } #[cfg(not(target_arch = "wasm32"))] impl ReadNote { pub(crate) fn of(name: &str, r: &rustgis_data::raster::Raster) -> ReadNote { let overview = r.overview.map(|full| ((r.width, r.height), full)); - ReadNote { name: name.to_string(), rounded: r.rounded.iter().sum(), overview, part: None } + ReadNote { name: name.to_string(), rounded: r.rounded.iter().sum(), overview, part: None, at_most: false } } /// Of a part of a file ([`read_tiled_part`]): read from a level `level` pixels in size of the /// file's `full` image. pub(crate) fn of_part(name: &str, r: &rustgis_data::raster::Raster, level: (u32, u32), full: (u32, u32)) -> ReadNote { let overview = r.overview.map(|_| (level, full)); - ReadNote { name: name.to_string(), rounded: r.rounded.iter().sum(), overview, part: Some((r.width, r.height)) } + ReadNote { name: name.to_string(), rounded: r.rounded.iter().sum(), overview, part: Some((r.width, r.height)), at_most: false } } /// Of a file read at its full size in pieces, `rounded` of its values rounded as they were. pub(crate) fn rounded(name: &str, rounded: u64) -> ReadNote { - ReadNote { name: name.to_string(), rounded, overview: None, part: None } + ReadNote { name: name.to_string(), rounded, overview: None, part: None, at_most: false } + } + + /// Its count of values rounded is at most the one said when `at_most`: a block read with a + /// margin reads some values twice. + pub(crate) fn at_most(mut self, at_most: bool) -> ReadNote { + self.at_most = at_most; + self } } @@ -1694,9 +1703,9 @@ impl ReadNote { #[cfg(not(target_arch = "wasm32"))] pub(crate) fn tiled_read_notes(read: &[ReadNote], whose: &str) -> Vec { let (mut rounded, mut overviews) = (Vec::new(), Vec::new()); - for ReadNote { name, rounded: n, overview, part } in read { + for ReadNote { name, rounded: n, overview, part, at_most } in read { if *n > 0 { - rounded.push(format!("{name} {n}")); + rounded.push(if *at_most { format!("{name} at most {n}") } else { format!("{name} {n}") }); } if let Some(((w, h), (fw, fh))) = overview { let part = part.map_or_else(String::new, |(pw, ph)| format!(", a {pw} × {ph} part of it")); diff --git a/crates/engine/src/cmd/imagery.rs b/crates/engine/src/cmd/imagery.rs index 38994d087e..5b59a35c7f 100644 --- a/crates/engine/src/cmd/imagery.rs +++ b/crates/engine/src/cmd/imagery.rs @@ -1611,7 +1611,7 @@ pub(crate) fn index_work(s: &Session, p: &Value) -> Result Result Result Result { + let (fw, fh) = reading.full(); + let (w, h) = ((fw / k).max(1), (fh / k).max(1)); + let (bw, bh) = super::in_blocks::BLOCK; + let size = ((bw / k).max(1) * k, (bh / k).max(1) * k); + // The result's bands and its file, and for several bands the copy of them interleaved that + // the file is made from (one band is written from itself), planned before they are set aside. + let held = reading.held(); + let copies = if held.band_count() > 1 { 3 } else { 2 }; + let need = u64::from(w).saturating_mul(u64::from(h)).saturating_mul(held.band_count() as u64).saturating_mul(4 * copies); + if !super::in_blocks::affordable(need) { + return Err(format!( + "{}: its resample by {k}, {w} × {h}, needs {} MB at once, more than this computer can give now: clip it to a smaller area first, or resample by more", + reading.layer(), + need >> 20 + )); + } + let _held = rustgis_data::memory::Holding::of(need); + let mut bands: Vec> = Vec::new(); + let mut first: Option = None; + let mut marks: Vec = Vec::new(); + let rounded = reading.each_block((0, w * k), (0, h * k), size, |cols, rows, read| { + let r = &read.raster; + let (ax, ay) = read.at; + if bands.is_empty() { + bands = (0..r.band_count()).map(|_| rasterops::new_band(w as usize, h as usize, NODATA)).collect::>()?; + marks = vec![false; r.band_count()]; + } + marks.iter_mut().enumerate().for_each(|(b, m)| *m |= r.band_rounded(b)); + // This block's output pixels: columns and rows of the output. + let (ox0, ox1, oy0, oy1) = (cols.0 / k, cols.1 / k, rows.0 / k, rows.1 / k); + let ow = (ox1 - ox0) as usize; + for (band, dst) in r.bands.iter().zip(bands.iter_mut()) { + let means = rasterops::per_index( + ow * (oy1 - oy0) as usize, + ow, + (k * k) as usize, + || (), + |_, i| { + let (ox, oy) = (ox0 + (i % ow.max(1)) as u32, oy0 + (i / ow.max(1)) as u32); + let (mut sum, mut n) = (0.0f64, 0u32); + for dy in 0..k { + for dx in 0..k { + let (x, y) = (ox * k + dx - ax, oy * k + dy - ay); + if let Some(v) = band.data.get((y * r.width + x) as usize).copied().filter(|v| r.is_valid(*v)) { + sum += f64::from(v); + n += 1; + } + } + } + if n > 0 { (sum / f64::from(n)) as f32 } else { NODATA } + }, + )?; + for (row, line) in means.chunks(ow.max(1)).enumerate() { + let at = (oy0 as usize + row) * w as usize + ox0 as usize; + if let Some(d) = dst.get_mut(at..at + line.len()) { + d.copy_from_slice(line); + } + } + } + if first.is_none() { + // Its bands, place and kind, as a whole read gives them. + let mut meta = Raster::new( + r.name.clone(), + 1, + 1, + vec![vec![0.0]; r.band_count()], + read.grid.0, + r.crs, + r.nodata, + r.color.clone(), + r.data_type.clone(), + ) + .map_err(|e| e.to_string())?; + meta.bands.iter_mut().zip(&r.bands).for_each(|(o, i)| { + o.name.clone_from(&i.name); + o.wavelength = i.wavelength; + }); + first = Some(meta); + } + Ok(()) + })?; + let meta = first.ok_or_else(|| format!("{}: it has no pixels", reading.layer()))?; + let gt = GeoTransform { + pixel_width: meta.transform.pixel_width * f64::from(k), + pixel_height: meta.transform.pixel_height * f64::from(k), + ..meta.transform + }; + let nodata = meta.nodata.or(Some(NODATA as f64)); + let color = if matches!(meta.color, ColorHint::Palette(_)) { ColorHint::Gray } else { meta.color.clone() }; + let mut res = Raster::new(out, w, h, bands, gt, meta.crs, nodata, color, meta.data_type.clone()).map_err(|e| e.to_string())?; + res.bands.iter_mut().zip(&meta.bands).for_each(|(o, i)| { + o.name.clone_from(&i.name); + o.wavelength = i.wavelength; + }); + // The blocks average values rounded when the file was read, some or all of them. + res.rounded = Vec::new(); + res.rounded_some = if marks.contains(&true) { marks } else { Vec::new() }; + let notes = super::gp::tiled_read_notes(&[super::gp::ReadNote::rounded(reading.layer(), rounded)], "its"); + let then: super::workflows::Then = Box::new(move |s: &mut Session, _: &mut Value| { + for note in notes { + s.notify(note, false); + } + }); + super::workflows::made_then(res, None, Some(then)) +} + /// The pixel window of `r` covering extent `e`'s edges (columns, rows); an error when it can't be /// placed on the raster or doesn't overlap it. fn extent_window(r: &Raster, e: &Extent) -> Result<(std::ops::Range, std::ops::Range), String> { diff --git a/crates/engine/src/cmd/in_blocks.rs b/crates/engine/src/cmd/in_blocks.rs index 8351bad7ae..ddb0cfe819 100644 --- a/crates/engine/src/cmd/in_blocks.rs +++ b/crates/engine/src/cmd/in_blocks.rs @@ -1,6 +1,7 @@ //! A raster made a block at a time from a large raster file read in place (#2865). A command that -//! works cell by cell (an index) reads its input a block of tiles at a time, at the file's full -//! size, where reading it whole would read the finest level of it that fits. A result that fits +//! works cell by cell, or over a cell's neighbours (an index, a raster function), reads its input a block of tiles at a time, at the file's full size, where +//! reading it whole would read the finest level of it that fits; one over its neighbours reads +//! each block with a margin of the cells around it. A result that fits //! is held and saved with the project as any other; one too large to hold is written a row of //! tiles at a time to a tiled GeoTIFF in the project's results folder //! ([`rustgis_data::raster::cogwrite::TileStream`]), which its layer then reads in place, as a @@ -25,13 +26,54 @@ use crate::Session; /// megabytes for an image of a few bands. const BLOCK_COLUMNS: u32 = if cfg!(test) { 384 } else { 4096 }; +/// The columns and rows of a block ([`BLOCK_COLUMNS`], and the tiles' rows). +pub(crate) const BLOCK: (u32, u32) = (BLOCK_COLUMNS, cogwrite::TILE); + /// The most samples, tiles' padding included, of the overview the result's layer holds: what a /// layer reading a file in place holds of it (`rustgis_tiles::cog::raster::overview_level`), so /// it holds the same overview once the project is opened again. const OVERVIEW_SAMPLES: usize = if cfg!(test) { 1 << 16 } else { 2 << 20 }; -/// The commands that make their raster a block at a time from a large file read in place. -const IN_BLOCKS: &[&str] = &["raster.index"]; +/// The cells around a block a raster function reads with it (`function`): none for one that works +/// cell by cell, one for one over a cell's eight neighbours. `None` for one that doesn't work in +/// blocks (a resample, onto another grid). +pub(crate) fn function_halo(function: &str) -> Option { + match function { + "ndvi" | "bandMath" | "remap" | "threshold" => Some(0), + "slope" | "aspect" | "hillshade" => Some(1), + _ => None, + } +} + +/// The cells around a block a chain of raster functions (`steps`) reads with it: what each step +/// reads, added, as each works on the one before. `None` when a step doesn't work in blocks; when +/// it remaps after a step over neighbours, which would meet the margin's cells, made from too few +/// neighbours, and say what they met; or when a slope in percent, whose cells past Float32's +/// range are counted where they're kept, isn't its last step. +pub(crate) fn chain_halo(steps: &[Value]) -> Option { + let function = |st: &Value| st.get("function").and_then(Value::as_str).unwrap_or_default().to_string(); + let after = steps.iter().skip_while(|st| function_halo(&function(st)) == Some(0)); + if after.into_iter().any(|st| matches!(function(st).as_str(), "remap" | "threshold")) { + return None; + } + let percent = |st: &Value| function(st) == "slope" && st.get("units").and_then(Value::as_str) == Some("percent"); + if steps.iter().rev().skip(1).any(percent) { + return None; + } + steps.iter().try_fold(0u32, |h, st| Some(h + function_halo(&function(st))?)) +} + +/// Whether command `id` with `params` works in blocks over a large file, and makes one band: +/// Indices, and Raster Functions and the Function Editor whose functions do ([`function_halo`], +/// [`chain_halo`]). +fn in_blocks(id: &str, params: &Value) -> bool { + match id { + "raster.index" => true, + "raster.function" => params.get("function").and_then(Value::as_str).and_then(function_halo).is_some(), + "raster.functionChain" => params.get("steps").and_then(Value::as_array).is_some_and(|s| !s.is_empty() && chain_halo(s).is_some()), + _ => false, + } +} /// The plan to make a raster a block at a time ([`plan`]): its input, what the result is called, /// and, for a result too large to hold, the folder its file goes in. @@ -45,6 +87,38 @@ pub(crate) struct Blocks { folder: Option, /// The full image's columns and rows. full: (u32, u32), + /// The cells around each block read with it ([`Blocks::with_halo`]). + halo: u32, +} + +/// What a raster made a block at a time is: its band's name (none: the band's number); whether +/// it is a hillshade's whole numbers 1 to 255, held and written as bytes with 0 for no value +/// ([`rustgis_analysis::rasterops::derive_hillshade`]), rather than floats; whether it holds +/// classes (a remap's, a threshold's), whose overviews take a pixel rather than an average; and, +/// for a function whose values can pass a float's range (a slope in percent), what to say of the +/// cells that do, an error counting them. +#[derive(Default)] +pub(crate) struct Shape { + pub(crate) band: Option, + pub(crate) bytes: bool, + pub(crate) classes: bool, + pub(crate) overflow: Option<&'static str>, +} + +impl Shape { + /// The value a cell with none takes, and the type its values are held as. + fn nodata(&self) -> (f32, &'static str) { + if self.bytes { (0.0, "UInt8") } else { (NODATA, "Float32") } + } + + /// How its file stores its band. + fn samples(&self) -> cogwrite::Samples { + match (self.bytes, self.classes) { + (true, _) => cogwrite::Samples::Hillshade, + (false, true) => cogwrite::Samples::Classes, + (false, false) => cogwrite::Samples::Floats, + } + } } /// The most samples a cell-by-cell command reads whole of a file, and holds of a result: @@ -77,6 +151,13 @@ fn too_large(input: &Input) -> Option<(u32, u32)> { (samples.saturating_mul(8) > (whole_limit() as u64).saturating_mul(4)).then_some(full) } +/// Whether a result of `samples` samples is held as any other, rather than written to a file +/// ([`written`]): one made from blocks of a larger file that only works held (a resample's) is +/// made so only then. +pub(crate) fn holds(samples: u64) -> bool { + samples <= whole_limit() as u64 +} + /// Whether a result `full` pixels in size, one band, is too large to hold: it is then written to /// a file and read in place, as a file that size added from this computer is. fn written(full: (u32, u32)) -> bool { @@ -84,10 +165,10 @@ fn written(full: (u32, u32)) -> bool { } /// Whether command `id` with `params` writes its result to a file in the results folder: a -/// command that works in blocks ([`IN_BLOCKS`]) over a layer too large to read whole, whose +/// command that works in blocks ([`in_blocks`]) over a layer too large to read whole, whose /// result is too large to hold. The permission check adds that it writes files. pub(crate) fn writes_file(context: &impl super::InputSource, id: &str, params: &Value) -> bool { - if !IN_BLOCKS.contains(&id) { + if !in_blocks(id, params) { return false; } let Some(name) = params.get("layer").and_then(Value::as_str) else { return false }; @@ -111,7 +192,95 @@ pub(crate) fn plan(s: &Session, input: &Input, out: &str) -> Result Some(folder(s).ok_or("this computer gives RustGIS no folder to write the result to: save the project first")?), false => None, }; - Ok(Some(Blocks { input: input.clone(), layer: layer.to_string(), path: path.to_string(), out: out.to_string(), folder, full })) + Ok(Some(Blocks { input: input.clone(), layer: layer.to_string(), path: path.to_string(), out: out.to_string(), folder, full, halo: 0 })) +} + +/// The full size of `input`'s file when a command reads it a block at a time ([`plan`]), for one +/// whose result is held whatever its size (a resample's, smaller than the file): `None` when the +/// file isn't too large to read whole at its full size. The command that goes on to read it so +/// asks [`Reading::refused_in_script`] first, as [`plan`] does. +pub(crate) fn plan_read(input: &Input) -> Option { + let (full, (layer, path)) = (too_large(input)?, input.file()?); + Some(Reading { input: input.clone(), layer: layer.to_string(), path: path.to_string(), full }) +} + +/// Whether the work can plan for `need` bytes more: within what a job may take now +/// ([`rustgis_data::memory::share`], with what RustGIS holds and the computer has free), or, where +/// that isn't known, within the floor's worth of samples. +pub(crate) fn affordable(need: u64) -> bool { + use rustgis_data::memory; + let budget = memory::share(memory::physical(), memory::held(), memory::available()); + need <= budget.unwrap_or((rustgis_data::raster::SAMPLES_FLOOR as u64).saturating_mul(4)) +} + +/// A large file read in place, read a block at a time by a command that makes its own result +/// ([`plan_read`]): its layer's input, name and file, and its full size. +pub(crate) struct Reading { + input: Input, + layer: String, + path: String, + full: (u32, u32), +} + +impl Reading { + /// An error for a step of a script on the app's window thread, which reading the file a block + /// at a time would hold, as [`plan`] refuses one. + pub(crate) fn refused_in_script(&self, s: &Session) -> Result<(), String> { + if s.steps_running > 0 && s.on_window_thread { + return Err(format!( + "{}: its full {} × {} pixels are read a block at a time, which a script step can't do without holding the window: run it on its own", + self.layer, self.full.0, self.full.1 + )); + } + Ok(()) + } + + /// The file's full columns and rows. + pub(crate) fn full(&self) -> (u32, u32) { + self.full + } + + /// The input layer's name. + pub(crate) fn layer(&self) -> &str { + &self.layer + } + + /// The raster the layer holds: the file's overview, with its bands, extent and system. + pub(crate) fn held(&self) -> &Raster { + self.input.held() + } + + /// Reads the blocks of columns `cols` and rows `rows` (half-open, at the full size), each of + /// `size` columns and rows from their start, in turn, and gives each to `each` with its + /// columns and rows: at the file's full size, holding all of them, counted as the run's + /// progress (its own steps not), Cancel looked at between them. Gives how many values were + /// rounded as they were read. + pub(crate) fn each_block( + &self, + cols: (u32, u32), + rows: (u32, u32), + size: (u32, u32), + mut each: impl FnMut((u32, u32), (u32, u32), &rustgis_data::raster::PartRead) -> Result<(), String>, + ) -> Result { + let source = Source { input: &self.input, layer: &self.layer, path: &self.path, full: self.full }; + let (bw, bh) = (size.0.max(1), size.1.max(1)); + let (across, down) = (cols.1.saturating_sub(cols.0).div_ceil(bw), rows.1.saturating_sub(rows.0).div_ceil(bh)); + rustgis_data::progress::begin((across as usize).saturating_mul(down as usize)); + let mut rounded = 0u64; + for by in 0..down { + let (r0, r1) = (rows.0 + by * bh, (rows.0 + (by + 1) * bh).min(rows.1)); + for bx in 0..across { + let (c0, c1) = (cols.0 + bx * bw, (cols.0 + (bx + 1) * bw).min(cols.1)); + rustgis_analysis::control::uncounted(|| -> Result<_, String> { + let (read, _count) = source.block((c0, c1), (r0, r1))?; + rounded = rounded.saturating_add(read.raster.rounded.iter().sum::()); + each((c0, c1), (r0, r1), &read) + })?; + rustgis_data::progress::step(1).map_err(|e| e.to_string())?; + } + } + Ok(rounded) + } } /// The file name, before its extension, of a result called `name`: its safe form @@ -151,6 +320,13 @@ fn folder(s: &Session) -> Option { } impl Blocks { + /// The plan reading `halo` cells around each block with it, for work over a cell's + /// neighbours: a block's cells are made from the cells around them as from the whole raster's. + pub(crate) fn with_halo(mut self, halo: u32) -> Blocks { + self.halo = halo; + self + } + /// Makes the raster: `cells` turns a block of the input (all its bands, at the file's full /// size) into the result's values for its cells, row by row, `NODATA` for none. Each block is /// read and made in turn, counted as the run's progress, Cancel looked at between them. A @@ -160,8 +336,30 @@ impl Blocks { /// it (not the folders around it, the project's own when it is saved) while /// nothing else is in it (one another run wrote into too can stay, empty, once both their /// results are gone). - pub(crate) fn run(self, cells: impl Fn(&Raster) -> Result, String>) -> Result { - let Blocks { input, layer, path, out, folder, full } = self; + /// It is of `shape`: a hillshade's values below 1 have no value, as a whole hillshade's. + pub(crate) fn run( + self, + cells: impl Fn(&Raster, &rustgis_geom::Extent) -> Result, String>, + shape: Shape, + ) -> Result { + let Blocks { input, layer, path, out, folder, full, halo } = self; + let (nodata, kind) = shape.nodata(); + let cells = |r: &Raster, ground: &rustgis_geom::Extent| -> Result, String> { + let mut v = cells(r, ground)?; + if shape.bytes { + v.iter_mut().filter(|v| !v.is_finite() || **v < 1.0).for_each(|v| *v = 0.0); + } + Ok(v) + }; + // A margin read with each block reads its cells twice or more: a count of those rounded + // is at most that. + let note = |rounded: u64| super::gp::ReadNote::rounded(&layer, rounded).at_most(halo > 0); + let named = |mut r: Raster| { + if let (Some(b), Some(name)) = (r.bands.first_mut(), &shape.band) { + b.name.clone_from(name); + } + r + }; let (fw, fh) = full; let tile = cogwrite::TILE; // What a row of blocks holds of the result and of its file's levels as they are written, @@ -174,8 +372,9 @@ impl Blocks { Some(_) => cogwrite::TileStream::>>::peak(fw, fh, OVERVIEW_SAMPLES).saturating_add(row_bytes), None => u64::from(fw).saturating_mul(u64::from(fh)).saturating_mul(4).saturating_add(row_bytes), }; - let can = (rustgis_data::raster::max_samples() as u64).saturating_mul(8); - if need > can { + // Within what any run of rasters plans for ([`rustgis_data::raster::max_samples`]), + // floor included, as a whole read plans. + if need > (rustgis_data::raster::max_samples() as u64).saturating_mul(8) { return Err(format!( "{layer}: making it a block at a time at its full {fw} × {fh} needs {} MB at once, more than this computer can give now: clip it to a smaller area first", need >> 20 @@ -183,19 +382,35 @@ impl Blocks { } let _held = rustgis_data::memory::Holding::of(need); let blocks = Source { input: &input, layer: &layer, path: &path, full }; + // The kept cells whose values pass a float's range (none for most functions): counted in + // the rows made, which hold no margin, so a margin's cell, made from too few neighbours, + // isn't counted. + let over = std::cell::Cell::new(0u64); + let count = |rows: &[f32]| { + if shape.overflow.is_some() { + over.set(over.get() + rows.iter().filter(|v| v.is_infinite()).count() as u64); + } + }; + let overflowed = || match shape.overflow { + Some(what) if over.get() > 0 => Err(format!("{layer}: {} {what}", over.get())), + _ => Ok(()), + }; let Some(folder) = folder else { // A result that fits: held whole, made a block at a time. - let mut whole = rustgis_analysis::rasterops::new_band(fw as usize, fh as usize, NODATA)?; - let (grid, crs, rounded) = blocks.each_row(&cells, |r0, rows, _| { + let mut whole = rustgis_analysis::rasterops::new_band(fw as usize, fh as usize, nodata)?; + let (grid, crs, rounded) = blocks.each_row(&cells, halo, |r0, rows, _| { + count(rows); let at = r0 as usize * fw as usize; if let Some(d) = whole.get_mut(at..at + rows.len()) { d.copy_from_slice(rows); } Ok(()) })?; - let r = Raster::new(out.clone(), fw, fh, vec![whole], grid, crs, Some(f64::from(NODATA)), ColorHint::Gray, "Float32") + overflowed()?; + let r = Raster::new(out.clone(), fw, fh, vec![whole], grid, crs, Some(f64::from(nodata)), ColorHint::Gray, kind) .map_err(|e| e.to_string())?; - let notes = super::gp::tiled_read_notes(&[super::gp::ReadNote::rounded(&layer, rounded)], "its"); + let r = named(r); + let notes = super::gp::tiled_read_notes(&[note(rounded)], "its"); let then: super::workflows::Then = Box::new(move |s: &mut Session, _: &mut Value| { for note in notes { s.notify(note, false); @@ -214,23 +429,29 @@ impl Blocks { let wrote = rustgis_data::io::stage_streamed_new(&dest, made_folder.then_some(folder.as_path()), |w| { let (mut sink, mut stream) = (Some(w), None); let (_, _, rounded) = blocks - .each_row(&cells, |_, rows, (grid, crs)| { + .each_row(&cells, halo, |_, rows, (grid, crs)| { + count(rows); // Placed on the file's full grid, as a read of all of it places it. if stream.is_none() { let t = Raster::new( out.clone(), 1, 1, - vec![vec![NODATA]], + vec![vec![nodata]], grid, crs, - Some(f64::from(NODATA)), + Some(f64::from(nodata)), ColorHint::Gray, - "Float32", + kind, ) .map_err(|e| e.to_string())?; + let t = named(t); let w = sink.take().ok_or("the result's file was started twice")?; - stream = Some(cogwrite::TileStream::new(&t, fw, fh, w).map_err(|e| e.to_string())?.keeping(OVERVIEW_SAMPLES)); + stream = Some( + cogwrite::TileStream::new(&t, fw, fh, shape.samples(), w) + .map_err(|e| e.to_string())? + .keeping(OVERVIEW_SAMPLES), + ); } stream.as_mut().map_or(Ok(()), |s: &mut cogwrite::TileStream<_>| s.put(rows).map_err(|e| e.to_string())) }) @@ -265,6 +486,8 @@ impl Blocks { } let (dest, (staged, (info, overview, rounded))) = taken.ok_or_else(|| format!("{}: every name for {out} is taken", folder.display()))?; + // Refused, its file goes with it. + overflowed()?; rustgis_data::progress::check().map_err(|e| e.to_string())?; // The layer holds an overview of the file, as one added from it would. let overview = overview.ok_or("the result's overview wasn't kept")?; @@ -274,7 +497,7 @@ impl Blocks { let mut notes = vec![format!( "{out}: made a block at a time from {layer} at its full {w} × {h}, and written to {file}, where the layer reads it from" )]; - notes.extend(super::gp::tiled_read_notes(&[super::gp::ReadNote::rounded(&layer, rounded)], "its")); + notes.extend(super::gp::tiled_read_notes(&[note(rounded)], "its")); let then: super::workflows::Then = Box::new(move |s: &mut Session, v: &mut Value| { for note in notes { s.notify(note, false); @@ -316,14 +539,16 @@ impl Source<'_> { Ok((read, count)) } - /// Makes the result a row of blocks at a time: `cells` makes each block's values, and `row` + /// Makes the result a row of blocks at a time: `cells` makes each block's values (read with + /// `halo` cells around it, whose values it makes too, and which are left out), and `row` /// is given each full row of blocks (its first row, its rows of the full width, and the /// file's full grid and system) as it is made. Each block is counted as the run's progress, its own steps not /// ([`rustgis_analysis::control::uncounted`]), and Cancel is looked at between them. Gives the /// full grid, its system, and how many values were rounded as they were read. fn each_row( &self, - cells: &impl Fn(&Raster) -> Result, String>, + cells: &impl Fn(&Raster, &rustgis_geom::Extent) -> Result, String>, + halo: u32, mut row: impl FnMut(u32, &[f32], (rustgis_data::raster::GeoTransform, rustgis_data::raster::Crs)) -> Result<(), String>, ) -> Result<(rustgis_data::raster::GeoTransform, rustgis_data::raster::Crs, u64), String> { let (fw, fh) = self.full; @@ -339,8 +564,10 @@ impl Source<'_> { // The block's own steps don't count: the run counts blocks. // The block's count in what is held lasts until its values are copied into the row. let ((read, _count), values) = rustgis_analysis::control::uncounted(|| -> Result<_, String> { - let read = self.block((c0, c1), (r0, r1))?; - let values = cells(&read.0.raster)?; + // With the cells around it, within the image. + let around = |(a, b): (u32, u32), n: u32| (a.saturating_sub(halo), b.saturating_add(halo).min(n)); + let read = self.block(around((c0, c1), fw), around((r0, r1), fh))?; + let values = cells(&read.0.raster, &read.0.bounds)?; Ok((read, values)) })?; let r = &read.raster; diff --git a/crates/engine/src/cmd/workflows.rs b/crates/engine/src/cmd/workflows.rs index c00def6cfd..d8b4f8f32a 100644 --- a/crates/engine/src/cmd/workflows.rs +++ b/crates/engine/src/cmd/workflows.rs @@ -1583,20 +1583,38 @@ fn json_error_column(line: &str) -> Option { /// One raster function's output pixels on `r`'s grid, or a resample's on `target`'s (from /// [`resample_target`]). A remap adds its ranges that match nothing to `remaps`, and whether it /// left any cell with a value. -fn apply_function(r: &Raster, p: &Value, target: Option<&Raster>, remaps: &mut Remaps) -> Result, String> { +/// `ground`, for `r` a part of a larger raster read a block at a time, is the whole's: a function +/// over a cell's neighbours measures its cells as on the whole (`rasterops::slope_on`). +fn apply_function( + r: &Raster, + p: &Value, + target: Option<&Raster>, + remaps: &mut Remaps, + ground: Option<&rustgis_geom::Extent>, +) -> Result, String> { let band = band_of(p, r)?; let zf = f(p, "zFactor").unwrap_or(1.0).clamp(0.0001, 100_000.0); match ps(p, "function").ok_or("function is required")? { "slope" => match p.get("units") { - None => rasterops::slope(r, band, zf), - Some(Value::String(units)) if units == "degrees" => rasterops::slope(r, band, zf), - Some(Value::String(units)) if units == "percent" => rasterops::slope_percent(r, band, zf), + None => rasterops::slope_on(r, band, zf, ground), + Some(Value::String(units)) if units == "degrees" => rasterops::slope_on(r, band, zf, ground), + // A part read with a margin: its cells past Float32's range are counted where they're + // kept ([`super::in_blocks::Shape::overflow`]). + Some(Value::String(units)) if units == "percent" && ground.is_some() => { + rasterops::slope_percent_cells_on(r, band, zf, ground).map(|(p, _)| p) + } + Some(Value::String(units)) if units == "percent" => rasterops::slope_percent_on(r, band, zf, ground), _ => Err("slope units must be degrees or percent".into()), }, - "aspect" => rasterops::aspect(r, band), - "hillshade" => { - rasterops::hillshade(r, band, f(p, "azimuth").unwrap_or(315.0), f(p, "altitude").unwrap_or(45.0).clamp(0.0, 90.0), zf) - } + "aspect" => rasterops::aspect_on(r, band, ground), + "hillshade" => rasterops::hillshade_on( + r, + band, + f(p, "azimuth").unwrap_or(315.0), + f(p, "altitude").unwrap_or(45.0).clamp(0.0, 90.0), + zf, + ground, + ), "ndvi" => { let (nir, red) = (p.get("nir").and_then(Value::as_u64).unwrap_or(4), p.get("red").and_then(Value::as_u64).unwrap_or(3)); rasterops::band_math(r, &format!("(b{nir} - b{red}) / (b{nir} + b{red})")) @@ -1668,11 +1686,33 @@ fn function_work(s: &Session, p: &Value) -> Result { if matches!(ps(&p, "function"), Some("remap" | "threshold")) { super::settle_bool(&mut p, "keep"); } + // A file too large to read whole at its full size: a block at a time, with the cells around + // each that a function over a cell's neighbours reads (#2865). + #[cfg(not(target_arch = "wasm32"))] + if let Some(halo) = ps(&p, "function").and_then(super::in_blocks::function_halo) + && let Some(blocks) = super::in_blocks::plan(s, &src, &name)? + { + let shape = function_shape(&p); + return Ok(Box::new(move || { + let met = std::cell::RefCell::new(BlockRemaps::default()); + let made = blocks.with_halo(halo).run( + |block, ground| { + let mut remaps = Remaps::default(); + let pixels = apply_function(block, &p, None, &mut remaps, Some(ground))?; + met.borrow_mut().add(remaps); + Ok(pixels) + }, + shape, + )?; + let made = also(made, met.into_inner().met().then()); + Ok(if is_hillshade(&p) { hillshade_look(made, &defaults) } else { made }) + })); + } Ok(Box::new(move || { let src = src.read()?; let target = read_target(target.as_ref())?; let mut remaps = Remaps::default(); - let pixels = apply_function(&src, &p, target.as_deref(), &mut remaps)?; + let pixels = apply_function(&src, &p, target.as_deref(), &mut remaps, None)?; // Only a resample takes another raster's grid. let raster = derive_function(target.as_deref().unwrap_or(&src), &name, &p, pixels)?; if is_hillshade(&p) { made_hillshade(raster, &defaults) } else { made_then(raster, None, Some(remaps.then())) } @@ -1686,14 +1726,31 @@ fn derive_function(r: &Raster, name: &str, p: &Value, pixels: Vec) -> Resul return rasterops::derive_hillshade(r, name, pixels); } let mut out = rasterops::derive(r, name, vec![pixels])?; - if ps(p, "function") == Some("slope") - && let Some(band) = out.bands.first_mut() - { - band.name = if ps(p, "units") == Some("percent") { "Slope (percent)" } else { "Slope (degrees)" }.into(); + if let (Some(name), Some(band)) = (function_band(p), out.bands.first_mut()) { + band.name = name; } Ok(out) } +/// What a raster function step `p` makes, as a raster made a block at a time holds it: its band's +/// name, a hillshade's bytes, a remap's or threshold's classes, and a percent slope's cells past +/// Float32's range counted. +#[cfg(not(target_arch = "wasm32"))] +fn function_shape(p: &Value) -> super::in_blocks::Shape { + super::in_blocks::Shape { + band: function_band(p), + bytes: is_hillshade(p), + classes: matches!(ps(p, "function"), Some("remap" | "threshold")), + overflow: (ps(p, "function") == Some("slope") && ps(p, "units") == Some("percent")).then_some(rasterops::PERCENT_OVERFLOW), + } +} + +/// The name a raster function step `p` gives its band: a slope's says its unit; none otherwise. +fn function_band(p: &Value) -> Option { + (ps(p, "function") == Some("slope")) + .then(|| if ps(p, "units") == Some("percent") { "Slope (percent)" } else { "Slope (degrees)" }.to_string()) +} + /// Whether raster function step `p` is a hillshade, whose pixels are bytes /// ([`rasterops::derive_hillshade`]). fn is_hillshade(p: &Value) -> bool { @@ -1704,12 +1761,64 @@ fn is_hillshade(p: &Value) -> bool { /// shades it holds: as whole numbers, 16 or fewer (a gentle slope) would otherwise be drawn as /// classes (Unique Values). fn made_hillshade(raster: Raster, defaults: &rustgis_map::RasterDefaults) -> Result { - let mut m = made(raster, None)?; + Ok(hillshade_look(made(raster, None)?, defaults)) +} + +/// A hillshade made, drawn as one: stretched in grey, as the raster defaults have it. +fn hillshade_look(mut m: Made, defaults: &rustgis_map::RasterDefaults) -> Made { let style = &mut m.layer.style; style.renderer = rustgis_map::RasterRenderer::Stretch { band: 0, ramp: defaults.ramp.clone(), invert: defaults.invert }; style.stretch = defaults.stretch; style.resampling = defaults.resampling; - Ok(m) + m +} + +/// `m`, doing `then` too once it is added, after what it did already. +#[cfg(not(target_arch = "wasm32"))] +fn also(mut m: Made, then: Then) -> Made { + let before = m.then.take(); + m.then = Some(Box::new(move |s: &mut Session, v: &mut Value| { + if let Some(before) = before { + before(s, v); + } + then(s, v); + })); + m +} + +/// What the remaps of a function made a block at a time met ([`Remaps`]), gathered block by +/// block: the ranges that match nothing (a low end not below its high end, the same in every +/// block), and a remap leaving no cell with a value only when it leaves none in every block. +#[cfg(not(target_arch = "wasm32"))] +#[derive(Default)] +struct BlockRemaps { + /// The ranges that match nothing, as every block so far found them; `None` before the first. + empty: Option>, + /// Whether every block so far was left with no value, and the raster it was said of. + emptied: Option>, +} + +#[cfg(not(target_arch = "wasm32"))] +impl BlockRemaps { + /// Adds what one block's remaps met. + fn add(&mut self, r: Remaps) { + self.empty = Some(match self.empty.take() { + None => r.empty, + Some(mut e) => { + e.retain(|x| r.empty.contains(x)); + e + } + }); + self.emptied = Some(match self.emptied.take() { + None => r.emptied, + Some(all) => all.and(r.emptied), + }); + } + + /// What every block's remaps met together. + fn met(self) -> Remaps { + Remaps { empty: self.empty.unwrap_or_default(), emptied: self.emptied.flatten() } + } } /// Runs raster functions one after another, each on the previous one's output. @@ -1737,6 +1846,39 @@ fn function_chain_work(s: &Session, p: &Value) -> Result { .collect::>()?; let named = Some(out_name(p, String::new())?).filter(|n| !n.is_empty()); let defaults = s.raster_defaults.clone(); + // A file too large to read whole at its full size: a block at a time (#2865), with the cells + // around each that its steps over a cell's neighbours read, one each; a chain that can't be + // made so ([`super::in_blocks::chain_halo`]) reads the file as before. + #[cfg(not(target_arch = "wasm32"))] + if let Some(halo) = super::in_blocks::chain_halo(&steps) { + let names: Vec = steps.iter().map(func).collect(); + let out = named.clone().unwrap_or_else(|| format!("{}_{}", src.held().name, names.join("_"))); + if let Some(blocks) = super::in_blocks::plan(s, &src, &out)? { + let last = steps.last().cloned().unwrap_or_default(); + let shape = function_shape(&last); + return Ok(Box::new(move || { + let met = std::cell::RefCell::new(BlockRemaps::default()); + let made = blocks.with_halo(halo).run( + |block, ground| { + let mut remaps = Remaps::default(); + let mut cur: Option = None; + for (i, st) in steps.iter().enumerate() { + let input = cur.as_ref().unwrap_or(block); + let pixels = apply_function(input, st, None, &mut remaps, Some(ground)) + .map_err(|e| format!("step {} ({}): {e}", i + 1, func(st)))?; + cur = Some(derive_function(input, &input.name, st, pixels)?); + } + met.borrow_mut().add(remaps); + let cur = cur.ok_or("the chain made no raster")?; + Ok(cur.bands.into_iter().next().map(|b| b.data).unwrap_or_default()) + }, + shape, + )?; + let made = also(made, met.into_inner().met().then()); + Ok(if is_hillshade(&last) { hillshade_look(made, &defaults) } else { made }) + })); + } + } Ok(Box::new(move || { let src = src.read()?; // Each step's output, the next step's input; the first step reads the raster itself, not @@ -1748,7 +1890,8 @@ fn function_chain_work(s: &Session, p: &Value) -> Result { let f = func(st); let target = read_target(target.as_ref()).map_err(|e| format!("step {} ({f}): {e}", i + 1))?; let input = cur.as_ref().unwrap_or(&src); - let pixels = apply_function(input, st, target.as_deref(), &mut remaps).map_err(|e| format!("step {} ({f}): {e}", i + 1))?; + let pixels = + apply_function(input, st, target.as_deref(), &mut remaps, None).map_err(|e| format!("step {} ({f}): {e}", i + 1))?; // Only a resample takes another raster's grid; otherwise the grid is the current one. let next = derive_function(target.as_deref().unwrap_or(input), &input.name, st, pixels)?; cur = Some(next); diff --git a/crates/engine/src/tests/tiled_files.rs b/crates/engine/src/tests/tiled_files.rs index 29c8ff6575..fb021defcf 100644 --- a/crates/engine/src/tests/tiled_files.rs +++ b/crates/engine/src/tests/tiled_files.rs @@ -593,3 +593,127 @@ fn indices_over_a_file_too_large_to_read_whole_run_a_block_at_a_time() { s.run("script.run", &json!({"script": format!("raster.index {scripted}")})).unwrap(); assert!(folder.join("scripted.tif").is_file()); } + +/// The other commands that work cell by cell, or over a cell's neighbours, run a block at a time +/// over a file too large to read whole too (#2865), each making the raster it makes of the file +/// held whole, held or written to the results folder: Raster Functions by cell and over a cell's +/// neighbours (the cells around each block read with it; a hillshade held and written as bytes; +/// a remap's or threshold's overview of its classes), the Function Editor, and Process's +/// resample, which is made a block at a time when it can be held. What a remap meets is said as +/// of the whole raster. A chain that remaps after a step over neighbours reads the file as before, +/// and asks for no files. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn raster_functions_and_resamples_run_a_block_at_a_time() { + let d = dir("functions"); + let path = thousandths(&d); + let open = |s: &mut Session| { + s.run("layer.addData", &json!({"path": path})).unwrap(); + }; + let cases = [ + ("raster.function", json!({"layer": "checks", "function": "slope", "band": 1, "name": "out"})), + ("raster.function", json!({"layer": "checks", "function": "hillshade", "band": 2, "name": "out"})), + ( + "raster.function", + json!({"layer": "checks", "function": "remap", "band": 1, "ranges": [[0, 100, 1], [100, 300, 2], [7, 7, 3]], "name": "out"}), + ), + ("raster.function", json!({"layer": "checks", "function": "threshold", "band": 3, "value": 128, "name": "out"})), + ("raster.function", json!({"layer": "checks", "function": "bandMath", "expression": "b1 * 2 - b3", "name": "out"})), + ( + "raster.functionChain", + json!({"layer": "checks", "steps": [{"function": "bandMath", "expression": "b1 + b2"}, {"function": "aspect"}, {"function": "slope"}], "name": "out"}), + ), + ("raster.process", json!({"layer": "checks", "operation": "resample", "factor": 3, "name": "out"})), + ]; + let reads = || crate::cmd::gp::TILED_READS.with(std::cell::Cell::get); + for (command, p) in &cases { + // Of the file held whole. + let mut whole = Session::new(Project::default()); + open(&mut whole); + let mark = whole.notice_mark(); + whole.run(command, p).unwrap(); + let want = raster(&whole, "out").data.clone().unwrap(); + let said_whole: Vec = said(&whole, mark).into_iter().filter(|n| n.contains("matches no")).collect(); + assert_eq!(said_whole.is_empty(), p["function"] != "remap", "{command}: a range of the remap is empty, and said"); + // Held, then (one band past the limit) written, a block at a time. + let resample = *command == "raster.process"; + for (past, written) in [(1_000_000, false), (900_000, !resample)] { + let why = format!("{command} {p}, written {written}"); + let (_held, _blocks) = (HeldWhole::at(1_000_000), BlocksPast::at(past)); + let mut s = Session::new(Project::default()); + s.path = Some(d.join("Survey.rgis")); + open(&mut s); + assert!(raster(&s, "checks").tiled); + let (before, mark) = (reads(), s.notice_mark()); + s.run(command, p).unwrap(); + assert_eq!(reads(), before, "{why}: the file isn't read whole"); + let rl = raster(&s, "out"); + assert_eq!(rl.tiled, written, "{why}"); + let got_raster = if written { + rustgis_data::raster::read_path(std::path::Path::new(rl.path.as_deref().unwrap())).unwrap() + } else { + rl.data.as_deref().unwrap().clone() + }; + assert_eq!( + (got_raster.width, got_raster.height, got_raster.transform, got_raster.nodata, got_raster.data_type.as_str()), + (want.width, want.height, want.transform, want.nodata, want.data_type.as_str()), + "{why}" + ); + for (g, w) in got_raster.bands.iter().zip(&want.bands) { + assert!(g.data == w.data, "{why}: band {} is the whole raster's", w.name); + assert_eq!(g.name, w.name, "{why}"); + } + // What a remap met is said as of the whole raster. + let said_blocks: Vec = said(&s, mark).into_iter().filter(|n| n.contains("matches no")).collect(); + assert_eq!(said_blocks, said_whole, "{why}"); + // A remap's or threshold's overview held is of its classes, never an average of two. + if written && matches!(p["function"].as_str(), Some("remap" | "threshold")) { + let classes: std::collections::BTreeSet = want.bands[0].data.iter().map(|v| v.to_bits()).collect(); + let held = rl.data.as_deref().unwrap(); + assert!(held.overview.is_some(), "{why}: an overview held"); + assert!(held.bands[0].data.iter().all(|v| classes.contains(&v.to_bits())), "{why}: the overview holds only its classes"); + } + if p["function"] == "hillshade" { + assert_eq!(rl.style.renderer, raster(&whole, "out").style.renderer, "{why}: drawn as a hillshade"); + } + // Cancelled at its checks (a spread of them), it leaves nothing behind. + let files = || std::fs::read_dir(d.join("Survey.rgis.data")).map(|r| r.count()).unwrap_or(0); + let (before, count) = (files(), rustgis_analysis::control::Control::cancelled_at_look(u64::MAX)); + let run = crate::cmd::workflows::raster_start(&mut s, command, p).unwrap(); + let id = run.id; + drop(run.run(&count)); + crate::cmd::workflows::raster_abandon(&mut s, id); + assert!(count.looked() > 6, "{why}: it looks at Cancel between its blocks"); + for n in (1..=count.looked()).step_by((count.looked() as usize / 8).max(1)) { + let control = rustgis_analysis::control::Control::cancelled_at_look(n); + let run = crate::cmd::workflows::raster_start(&mut s, command, p).unwrap(); + let id = run.id; + match run.run(&control) { + Err(e) => assert!(e.contains("was cancelled"), "{why}, check {n}: {e}"), + Ok(_) => assert!(control.looked() < n, "{why}, check {n}: not cancelled"), + } + crate::cmd::workflows::raster_abandon(&mut s, id); + assert_eq!(files(), before, "{why}, check {n}: left a file"); + } + } + } + // A chain that remaps after a step over neighbours reads the file as before, writing nothing, + // and the Assistant isn't asked for files for it. + struct Live; + impl crate::policy::Revocation for Live { + fn allows(&self, _: crate::policy::Effects) -> bool { + true + } + } + let (_held, _blocks) = (HeldWhole::at(1_000_000), BlocksPast::at(900_000)); + let mut s = Session::new(Project::default()); + s.path = Some(d.join("Fallback.rgis")); + open(&mut s); + let p = json!({"layer": "checks", "steps": [{"function": "slope"}, {"function": "threshold", "value": 5}], "name": "out"}); + let scope = crate::policy::Scope::assistant(8, std::sync::Arc::new(Live)); + assert!(matches!(s.review(&scope, &crate::policy::Call::command("raster.functionChain", p.clone())), crate::policy::Outcome::Allowed)); + let before = reads(); + s.run("raster.functionChain", &p).unwrap(); + assert_eq!(reads(), before + 1, "read as before"); + assert!(!d.join("Fallback.rgis.data").exists()); +} diff --git a/docs/user-guide/data.md b/docs/user-guide/data.md index 0020635867..051d17dffe 100644 --- a/docs/user-guide/data.md +++ b/docs/user-guide/data.md @@ -1687,12 +1687,16 @@ web](data-formats.md#files-on-the-web)). On the desktop, a tiled GeoTIFF on this computer too large to hold, with overviews, is read in place too: the map draws the part in view at the level it needs. Commands that make a raster from it read the file again as they run. **Clip** by an extent reads only the part under the extent, -at the file's full resolution when that part fits. **Indices** work a block of tiles at a time at -the file's full resolution. A result of up to 120 million pixels is held, as any other; a larger -one is written to a tiled GeoTIFF in the project's results folder beside it (`Survey.rgis.data` -for `Survey.rgis`), or in RustGIS's own folder for a project not saved yet, and the new layer -reads it in place; a notice says where it is. The other commands read the finest level of the file -they can hold, and say which. +at the file's full resolution when that part fits. **Indices**, **Raster Functions** (band math, +NDVI, remap, threshold, slope, aspect and hillshade, those over a cell's neighbours reading each +block with the cells around it) and the **Function Editor** with those steps work a block of +tiles at a time at the file's full resolution. A result of up to 120 million pixels is +held, as any other; a larger one is written to a tiled GeoTIFF in the project's results folder +beside it (`Survey.rgis.data` for `Survey.rgis`), or in RustGIS's own folder for a project not +saved yet, and the new layer reads it in place; a notice says where it is. **Process**'s resample +is made from the file a block at a time when its result fits. A chain that remaps after a step +over neighbours, or has a slope in percent before its last step, the other commands, and a +larger resample read the finest level of the file they can hold, and say which. The web app opens a picked or dropped file of up to 256 MB whole. A larger GeoTIFF is read a part at a time instead: its header, then only the tiles of the overview it opens from. A From c60a5dc71610c52c8ac62caadb7862ac2a19fe7e Mon Sep 17 00:00:00 2001 From: mavrick Date: Wed, 25 Nov 2026 04:28:52 -0600 Subject: [PATCH 2/3] fix(raster): review fixes for raster functions and resample in blocks (#2865) A resample this computer can't give the memory for now reads the file as before. A remap keeping the values it doesn't match averages its overviews. A resampled pixel covering none with a value takes the result's no-data value, held whole or in blocks. Every block of a run has the no-data value of its first, and a copy that doesn't fit its place is an error. --- crates/engine/src/cmd/imagery.rs | 45 +++++++++++++-------- crates/engine/src/cmd/in_blocks.rs | 41 +++++++++++++++---- crates/engine/src/cmd/workflows.rs | 11 ++++-- crates/engine/src/tests/tiled_files.rs | 55 +++++++++++++++++++++++++- docs/user-guide/data.md | 4 +- 5 files changed, 125 insertions(+), 31 deletions(-) diff --git a/crates/engine/src/cmd/imagery.rs b/crates/engine/src/cmd/imagery.rs index 5b59a35c7f..7cf0eaabcc 100644 --- a/crates/engine/src/cmd/imagery.rs +++ b/crates/engine/src/cmd/imagery.rs @@ -1795,16 +1795,18 @@ pub(crate) fn process_work(s: &Session, p: &Value) -> Result Result Result 0 { (sum / n as f64) as f32 } else { NODATA } + if n > 0 { (sum / n as f64) as f32 } else { empty } }, ) }) @@ -1872,17 +1877,23 @@ pub(crate) fn process_work(s: &Session, p: &Value) -> Result u64 { + let copies = if bands > 1 { 3 } else { 2 }; + u64::from(w).saturating_mul(u64::from(h)).saturating_mul(bands as u64).saturating_mul(4 * copies) +} + #[cfg(not(target_arch = "wasm32"))] fn resample_in_blocks(reading: &super::in_blocks::Reading, k: u32, out: String) -> Result { let (fw, fh) = reading.full(); let (w, h) = ((fw / k).max(1), (fh / k).max(1)); let (bw, bh) = super::in_blocks::BLOCK; let size = ((bw / k).max(1) * k, (bh / k).max(1) * k); - // The result's bands and its file, and for several bands the copy of them interleaved that - // the file is made from (one band is written from itself), planned before they are set aside. let held = reading.held(); - let copies = if held.band_count() > 1 { 3 } else { 2 }; - let need = u64::from(w).saturating_mul(u64::from(h)).saturating_mul(held.band_count() as u64).saturating_mul(4 * copies); + let need = resample_need(w, h, held.band_count()); if !super::in_blocks::affordable(need) { return Err(format!( "{}: its resample by {k}, {w} × {h}, needs {} MB at once, more than this computer can give now: clip it to a smaller area first, or resample by more", @@ -1897,8 +1908,10 @@ fn resample_in_blocks(reading: &super::in_blocks::Reading, k: u32, out: String) let rounded = reading.each_block((0, w * k), (0, h * k), size, |cols, rows, read| { let r = &read.raster; let (ax, ay) = read.at; + // A pixel with no value takes the result's no-data value, as a whole raster's resample. + let empty = r.nodata.map_or(NODATA, |d| d as f32); if bands.is_empty() { - bands = (0..r.band_count()).map(|_| rasterops::new_band(w as usize, h as usize, NODATA)).collect::>()?; + bands = (0..r.band_count()).map(|_| rasterops::new_band(w as usize, h as usize, empty)).collect::>()?; marks = vec![false; r.band_count()]; } marks.iter_mut().enumerate().for_each(|(b, m)| *m |= r.band_rounded(b)); @@ -1923,14 +1936,14 @@ fn resample_in_blocks(reading: &super::in_blocks::Reading, k: u32, out: String) } } } - if n > 0 { (sum / f64::from(n)) as f32 } else { NODATA } + if n > 0 { (sum / f64::from(n)) as f32 } else { empty } }, )?; for (row, line) in means.chunks(ow.max(1)).enumerate() { let at = (oy0 as usize + row) * w as usize + ox0 as usize; - if let Some(d) = dst.get_mut(at..at + line.len()) { - d.copy_from_slice(line); - } + let d = + dst.get_mut(at..at + line.len()).ok_or_else(|| format!("{}: a block's means don't fit the result", reading.layer()))?; + d.copy_from_slice(line); } } if first.is_none() { diff --git a/crates/engine/src/cmd/in_blocks.rs b/crates/engine/src/cmd/in_blocks.rs index ddb0cfe819..b17552b1bc 100644 --- a/crates/engine/src/cmd/in_blocks.rs +++ b/crates/engine/src/cmd/in_blocks.rs @@ -1,7 +1,8 @@ //! A raster made a block at a time from a large raster file read in place (#2865). A command that -//! works cell by cell, or over a cell's neighbours (an index, a raster function), reads its input a block of tiles at a time, at the file's full size, where -//! reading it whole would read the finest level of it that fits; one over its neighbours reads -//! each block with a margin of the cells around it. A result that fits +//! works cell by cell, or over a cell's neighbours (an index, a raster function), reads its input +//! a block of tiles at a time, at the file's full size, where reading it whole would read the +//! finest level of it that fits; one over its neighbours reads each block with a margin of the +//! cells around it. A result that fits //! is held and saved with the project as any other; one too large to hold is written a row of //! tiles at a time to a tiled GeoTIFF in the project's results folder //! ([`rustgis_data::raster::cogwrite::TileStream`]), which its layer then reads in place, as a @@ -209,10 +210,21 @@ pub(crate) fn plan_read(input: &Input) -> Option { /// that isn't known, within the floor's worth of samples. pub(crate) fn affordable(need: u64) -> bool { use rustgis_data::memory; + #[cfg(test)] + if let Some(max) = AFFORDS.with(std::cell::Cell::get) { + return need <= max; + } let budget = memory::share(memory::physical(), memory::held(), memory::available()); need <= budget.unwrap_or((rustgis_data::raster::SAMPLES_FLOOR as u64).saturating_mul(4)) } +#[cfg(test)] +thread_local! { + /// What [`affordable`] lets a run plan for on this thread, under test: a computer short of + /// memory, which no test can make. + pub(crate) static AFFORDS: std::cell::Cell> = const { std::cell::Cell::new(None) }; +} + /// A large file read in place, read a block at a time by a command that makes its own result /// ([`plan_read`]): its layer's input, name and file, and its full size. pub(crate) struct Reading { @@ -262,7 +274,7 @@ impl Reading { size: (u32, u32), mut each: impl FnMut((u32, u32), (u32, u32), &rustgis_data::raster::PartRead) -> Result<(), String>, ) -> Result { - let source = Source { input: &self.input, layer: &self.layer, path: &self.path, full: self.full }; + let source = Source { input: &self.input, layer: &self.layer, path: &self.path, full: self.full, nodata: Default::default() }; let (bw, bh) = (size.0.max(1), size.1.max(1)); let (across, down) = (cols.1.saturating_sub(cols.0).div_ceil(bw), rows.1.saturating_sub(rows.0).div_ceil(bh)); rustgis_data::progress::begin((across as usize).saturating_mul(down as usize)); @@ -381,7 +393,7 @@ impl Blocks { )); } let _held = rustgis_data::memory::Holding::of(need); - let blocks = Source { input: &input, layer: &layer, path: &path, full }; + let blocks = Source { input: &input, layer: &layer, path: &path, full, nodata: Default::default() }; // The kept cells whose values pass a float's range (none for most functions): counted in // the rows made, which hold no margin, so a margin's cell, made from too few neighbours, // isn't counted. @@ -517,6 +529,8 @@ struct Source<'a> { layer: &'a str, path: &'a str, full: (u32, u32), + /// The no-data value its first block was read with, which every other one must have. + nodata: std::cell::Cell>>, } impl Source<'_> { @@ -532,6 +546,16 @@ impl Source<'_> { format!("{}: its file can't be read in blocks: it isn't the file the layer was read from any more (Reload Data)", self.layer) })?; let r = &read.raster; + // One no-data value for every block of a run: a sidecar beside the file changed while it + // runs would give later blocks another. + let nodata = r.nodata.map(f64::to_bits); + match self.nodata.get() { + Some(first) if first != nodata => { + return Err(format!("{}: its no-data value changed while it was read (Reload Data)", self.layer)); + } + Some(_) => {} + None => self.nodata.set(Some(nodata)), + } let (ax, ay) = read.at; if r.overview.is_some() || ax > cols.0 || ay > rows.0 || ax + r.width < cols.1 || ay + r.height < rows.1 { return Err(format!("{}: a block of its file couldn't be read at its full size", self.layer)); @@ -582,9 +606,10 @@ impl Source<'_> { let src = (y - ay) as usize * pw + (c0 - ax) as usize; let dst = (y - r0) as usize * fw as usize + c0 as usize; let n = (c1 - c0) as usize; - if let (Some(s), Some(d)) = (values.get(src..src + n), rows.get_mut(dst..dst + n)) { - d.copy_from_slice(s); - } + let (Some(s), Some(d)) = (values.get(src..src + n), rows.get_mut(dst..dst + n)) else { + return Err(format!("{}: a block's values don't fit its place in the result", self.layer)); + }; + d.copy_from_slice(s); } rustgis_data::progress::step(1).map_err(|e| e.to_string())?; } diff --git a/crates/engine/src/cmd/workflows.rs b/crates/engine/src/cmd/workflows.rs index d8b4f8f32a..473740f0d0 100644 --- a/crates/engine/src/cmd/workflows.rs +++ b/crates/engine/src/cmd/workflows.rs @@ -1733,14 +1733,19 @@ fn derive_function(r: &Raster, name: &str, p: &Value, pixels: Vec) -> Resul } /// What a raster function step `p` makes, as a raster made a block at a time holds it: its band's -/// name, a hillshade's bytes, a remap's or threshold's classes, and a percent slope's cells past -/// Float32's range counted. +/// name, a hillshade's bytes, a threshold's classes and a remap's (not one that keeps the cells it +/// doesn't match, which keep their measures), and a percent slope's cells past Float32's range +/// counted. #[cfg(not(target_arch = "wasm32"))] fn function_shape(p: &Value) -> super::in_blocks::Shape { super::in_blocks::Shape { band: function_band(p), bytes: is_hillshade(p), - classes: matches!(ps(p, "function"), Some("remap" | "threshold")), + classes: match ps(p, "function") { + Some("threshold") => true, + Some("remap") => !b(p, "keep").unwrap_or(false), + _ => false, + }, overflow: (ps(p, "function") == Some("slope") && ps(p, "units") == Some("percent")).then_some(rasterops::PERCENT_OVERFLOW), } } diff --git a/crates/engine/src/tests/tiled_files.rs b/crates/engine/src/tests/tiled_files.rs index fb021defcf..9149ee082d 100644 --- a/crates/engine/src/tests/tiled_files.rs +++ b/crates/engine/src/tests/tiled_files.rs @@ -617,6 +617,10 @@ fn raster_functions_and_resamples_run_a_block_at_a_time() { "raster.function", json!({"layer": "checks", "function": "remap", "band": 1, "ranges": [[0, 100, 1], [100, 300, 2], [7, 7, 3]], "name": "out"}), ), + ( + "raster.function", + json!({"layer": "checks", "function": "remap", "band": 1, "ranges": [[0, 100, 1], [7, 7, 3]], "keep": true, "name": "out"}), + ), ("raster.function", json!({"layer": "checks", "function": "threshold", "band": 3, "value": 128, "name": "out"})), ("raster.function", json!({"layer": "checks", "function": "bandMath", "expression": "b1 * 2 - b3", "name": "out"})), ( @@ -659,6 +663,7 @@ fn raster_functions_and_resamples_run_a_block_at_a_time() { (want.width, want.height, want.transform, want.nodata, want.data_type.as_str()), "{why}" ); + assert_eq!(got_raster.bands.len(), want.bands.len(), "{why}: its bands"); for (g, w) in got_raster.bands.iter().zip(&want.bands) { assert!(g.data == w.data, "{why}: band {} is the whole raster's", w.name); assert_eq!(g.name, w.name, "{why}"); @@ -666,12 +671,14 @@ fn raster_functions_and_resamples_run_a_block_at_a_time() { // What a remap met is said as of the whole raster. let said_blocks: Vec = said(&s, mark).into_iter().filter(|n| n.contains("matches no")).collect(); assert_eq!(said_blocks, said_whole, "{why}"); - // A remap's or threshold's overview held is of its classes, never an average of two. + // A remap's or threshold's overview held is of its classes, never an average of two; one + // of a remap keeping the values it doesn't match averages them, as measures. if written && matches!(p["function"].as_str(), Some("remap" | "threshold")) { let classes: std::collections::BTreeSet = want.bands[0].data.iter().map(|v| v.to_bits()).collect(); let held = rl.data.as_deref().unwrap(); assert!(held.overview.is_some(), "{why}: an overview held"); - assert!(held.bands[0].data.iter().all(|v| classes.contains(&v.to_bits())), "{why}: the overview holds only its classes"); + let only = held.bands[0].data.iter().all(|v| classes.contains(&v.to_bits())); + assert_eq!(only, p["keep"] != true, "{why}: the overview holds only its values"); } if p["function"] == "hillshade" { assert_eq!(rl.style.renderer, raster(&whole, "out").style.renderer, "{why}: drawn as a hillshade"); @@ -697,6 +704,19 @@ fn raster_functions_and_resamples_run_a_block_at_a_time() { } } } + // A resample this computer can't give the memory for now reads the file as before. + { + let (_held, _blocks) = (HeldWhole::at(1_000_000), BlocksPast::at(1_000_000)); + crate::cmd::in_blocks::AFFORDS.with(|c| c.set(Some(1 << 20))); + let mut s = Session::new(Project::default()); + open(&mut s); + let before = reads(); + let done = s.run("raster.process", &json!({"layer": "checks", "operation": "resample", "factor": 3, "name": "out"})); + crate::cmd::in_blocks::AFFORDS.with(|c| c.set(None)); + done.unwrap(); + assert_eq!(reads(), before + 1, "read as before"); + assert!(!raster(&s, "out").tiled, "held, from the file read as before"); + } // A chain that remaps after a step over neighbours reads the file as before, writing nothing, // and the Assistant isn't asked for files for it. struct Live; @@ -717,3 +737,34 @@ fn raster_functions_and_resamples_run_a_block_at_a_time() { assert_eq!(reads(), before + 1, "read as before"); assert!(!d.join("Fallback.rgis.data").exists()); } + +/// A resample's pixel covering no pixel with a value takes the result's no-data value, the +/// file's, and one covering some averages those alone, whether the file is held whole or read a +/// block at a time. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_resampled_pixel_with_no_value_takes_the_no_data_value() { + let d = dir("resample-nodata"); + const N: u32 = 600; + let mut band: Vec = (0..N * N).map(|i| (i % 50) as f32).collect(); + for (x, y, v) in + [(0, 0, -9999.0), (1, 0, -9999.0), (0, 1, -9999.0), (1, 1, -9999.0), (2, 0, 5.0), (3, 0, -9999.0), (2, 1, -9999.0), (3, 1, 7.0)] + { + band[(y * N + x) as usize] = v; + } + let gt = GeoTransform { origin_x: 10.0, origin_y: 46.0, pixel_width: 0.001, pixel_height: -0.001 }; + let r = Raster::new("gaps", N, N, vec![band], gt, Crs::LonLat, Some(-9999.0), ColorHint::Gray, "Float32").unwrap(); + let path = d.join("gaps.tif"); + rustgis_data::raster::cogwrite::write_file(&r, 0, &path).unwrap(); + let p = json!({"layer": "gaps", "operation": "resample", "factor": 2, "name": "out"}); + for in_blocks in [false, true] { + let (_held, _blocks) = (HeldWhole::at(if in_blocks { 1000 } else { 1_000_000 }), BlocksPast::at(100_000)); + let mut s = Session::new(Project::default()); + s.run("layer.addData", &json!({"path": path.display().to_string()})).unwrap(); + assert_eq!(raster(&s, "gaps").tiled, in_blocks); + s.run("raster.process", &p).unwrap(); + let out = raster(&s, "out").data.clone().unwrap(); + assert_eq!((out.width, out.nodata), (N / 2, Some(-9999.0)), "in blocks {in_blocks}"); + assert_eq!(out.bands[0].data[..2], [-9999.0, 6.0], "in blocks {in_blocks}"); + } +} diff --git a/docs/user-guide/data.md b/docs/user-guide/data.md index 051d17dffe..c37bf0911d 100644 --- a/docs/user-guide/data.md +++ b/docs/user-guide/data.md @@ -1694,8 +1694,8 @@ tiles at a time at the file's full resolution. A result of up to 120 million pix held, as any other; a larger one is written to a tiled GeoTIFF in the project's results folder beside it (`Survey.rgis.data` for `Survey.rgis`), or in RustGIS's own folder for a project not saved yet, and the new layer reads it in place; a notice says where it is. **Process**'s resample -is made from the file a block at a time when its result fits. A chain that remaps after a step -over neighbours, or has a slope in percent before its last step, the other commands, and a +is made from the file a block at a time when its result fits. A chain that remaps or thresholds +after a step over neighbours, or has a slope in percent before its last step, the other commands, and a larger resample read the finest level of the file they can hold, and say which. The web app opens a picked or dropped file of up to 256 MB whole. A larger GeoTIFF is read a part From ecda5e7e87de6abe5ba47ef320b1d8a865e73999 Mon Sep 17 00:00:00 2001 From: mavrick Date: Wed, 25 Nov 2026 05:27:45 -0600 Subject: [PATCH 3/3] fix(raster): a resample short of memory when it runs reads as before; remap ranges met by bits (#2865) --- crates/engine/src/cmd/imagery.rs | 140 ++++++++++++++--------------- crates/engine/src/cmd/in_blocks.rs | 7 +- crates/engine/src/cmd/workflows.rs | 5 +- 3 files changed, 77 insertions(+), 75 deletions(-) diff --git a/crates/engine/src/cmd/imagery.rs b/crates/engine/src/cmd/imagery.rs index 7cf0eaabcc..c44a1271df 100644 --- a/crates/engine/src/cmd/imagery.rs +++ b/crates/engine/src/cmd/imagery.rs @@ -1808,75 +1808,19 @@ pub(crate) fn process_work(s: &Session, p: &Value) -> Result resample_in_blocks(&reading, k, out), + // Short of it since then: the file read as before. + false => resample_whole(&r, factor, out), + })); } } - Ok(Box::new(move || { - let r = r.read()?; - let k = factor.min(r.width.min(r.height)).max(1); - let (w, h) = ((r.width / k).max(1), (r.height / k).max(1)); - // Each output pixel is the mean of the valid pixels it covers; one covering none - // takes the result's no-data value (the raster's, else the one cells with no value - // take). - let empty = r.nodata.map_or(NODATA, |d| d as f32); - let bands = r - .bands - .iter() - .map(|b| { - // A cell reads its k × k block; the cells are counted and cancellable. - let cost = (k * k) as usize; - rasterops::per_index( - w as usize * h as usize, - w as usize, - cost, - || (), - |_, i| { - let (row, col) = ((i / w as usize) as u32, (i % w as usize) as u32); - let (mut sum, mut n) = (0.0f64, 0u32); - for dy in 0..k { - for dx in 0..k { - let (x, y) = (col * k + dx, row * k + dy); - if x >= r.width || y >= r.height { - continue; - } - if let Some(v) = b.data.get((y * r.width + x) as usize).copied().filter(|v| r.is_valid(*v)) { - sum += v as f64; - n += 1; - } - } - } - if n > 0 { (sum / n as f64) as f32 } else { empty } - }, - ) - }) - .collect::, _>>()?; - let gt = GeoTransform { - pixel_width: r.transform.pixel_width * k as f64, - pixel_height: r.transform.pixel_height * k as f64, - ..r.transform - }; - let nodata = r.nodata.or(Some(NODATA as f64)); - let color = if matches!(r.color, ColorHint::Palette(_)) { ColorHint::Gray } else { r.color.clone() }; - let mut out = Raster::new(out, w, h, bands, gt, r.crs, nodata, color, r.data_type.clone()).map_err(|e| e.to_string())?; - // A block's mean is of the same band: its name and wavelength are the input's. - out.bands.iter_mut().zip(&r.bands).for_each(|(o, i)| { - o.name = i.name.clone(); - o.wavelength = i.wavelength; - }); - // The blocks average values rounded when the file was read, some or all of them. - out.keep_rounded_mark(&r); - super::workflows::made(out, None) - })) + Ok(Box::new(move || resample_whole(&r, factor, out))) } o => Err(format!("unknown operation '{o}'")), } } -/// A resample by `k` of a large file read in place, made a block at a time from the file at its -/// full size ([`super::in_blocks::Reading::each_block`]): each output pixel the mean of the valid -/// pixels of the `k` × `k` it covers, as a whole raster's resample makes it, its trailing columns -/// and rows short of a full block left out. Blocks are whole multiples of `k` each way, so no -/// output pixel spans two. /// What a resample `w` × `h` of `bands` bands made a block at a time holds: its bands and its /// file, and for several bands the copy of them interleaved that the file is made from (one band /// is written from itself), planned before they are set aside. @@ -1886,21 +1830,75 @@ fn resample_need(w: u32, h: u32, bands: usize) -> u64 { u64::from(w).saturating_mul(u64::from(h)).saturating_mul(bands as u64).saturating_mul(4 * copies) } +/// A resample by `factor` of `r` read whole (the finest level of a file read in place that +/// fits), called `out`: each output pixel the mean of the valid pixels of the block it covers. +fn resample_whole(r: &super::workflows::Input, factor: u32, out: String) -> Result { + let r = r.read()?; + let k = factor.min(r.width.min(r.height)).max(1); + let (w, h) = ((r.width / k).max(1), (r.height / k).max(1)); + // Each output pixel is the mean of the valid pixels it covers; one covering none + // takes the result's no-data value (the raster's, else the one cells with no value + // take). + let empty = r.nodata.map_or(NODATA, |d| d as f32); + let bands = r + .bands + .iter() + .map(|b| { + // A cell reads its k × k block; the cells are counted and cancellable. + let cost = (k * k) as usize; + rasterops::per_index( + w as usize * h as usize, + w as usize, + cost, + || (), + |_, i| { + let (row, col) = ((i / w as usize) as u32, (i % w as usize) as u32); + let (mut sum, mut n) = (0.0f64, 0u32); + for dy in 0..k { + for dx in 0..k { + let (x, y) = (col * k + dx, row * k + dy); + if x >= r.width || y >= r.height { + continue; + } + if let Some(v) = b.data.get((y * r.width + x) as usize).copied().filter(|v| r.is_valid(*v)) { + sum += v as f64; + n += 1; + } + } + } + if n > 0 { (sum / n as f64) as f32 } else { empty } + }, + ) + }) + .collect::, _>>()?; + let gt = + GeoTransform { pixel_width: r.transform.pixel_width * k as f64, pixel_height: r.transform.pixel_height * k as f64, ..r.transform }; + let nodata = r.nodata.or(Some(NODATA as f64)); + let color = if matches!(r.color, ColorHint::Palette(_)) { ColorHint::Gray } else { r.color.clone() }; + let mut out = Raster::new(out, w, h, bands, gt, r.crs, nodata, color, r.data_type.clone()).map_err(|e| e.to_string())?; + // A block's mean is of the same band: its name and wavelength are the input's. + out.bands.iter_mut().zip(&r.bands).for_each(|(o, i)| { + o.name = i.name.clone(); + o.wavelength = i.wavelength; + }); + // The blocks average values rounded when the file was read, some or all of them. + out.keep_rounded_mark(&r); + super::workflows::made(out, None) +} + +/// A resample by `k` of a large file read in place, made a block at a time from the file at its +/// full size ([`super::in_blocks::Reading::each_block`]): each output pixel the mean of the valid +/// pixels of the `k` × `k` it covers, as a whole raster's resample makes it, its trailing columns +/// and rows short of a full block left out. Blocks are whole multiples of `k` each way, so no +/// output pixel spans two. Its memory ([`resample_need`]) is planned by the caller, which reads +/// the file as before when the computer can't give it. #[cfg(not(target_arch = "wasm32"))] fn resample_in_blocks(reading: &super::in_blocks::Reading, k: u32, out: String) -> Result { let (fw, fh) = reading.full(); let (w, h) = ((fw / k).max(1), (fh / k).max(1)); let (bw, bh) = super::in_blocks::BLOCK; let size = ((bw / k).max(1) * k, (bh / k).max(1) * k); - let held = reading.held(); - let need = resample_need(w, h, held.band_count()); - if !super::in_blocks::affordable(need) { - return Err(format!( - "{}: its resample by {k}, {w} × {h}, needs {} MB at once, more than this computer can give now: clip it to a smaller area first, or resample by more", - reading.layer(), - need >> 20 - )); - } + let need = resample_need(w, h, reading.held().band_count()); let _held = rustgis_data::memory::Holding::of(need); let mut bands: Vec> = Vec::new(); let mut first: Option = None; diff --git a/crates/engine/src/cmd/in_blocks.rs b/crates/engine/src/cmd/in_blocks.rs index b17552b1bc..06961d3adc 100644 --- a/crates/engine/src/cmd/in_blocks.rs +++ b/crates/engine/src/cmd/in_blocks.rs @@ -48,9 +48,10 @@ pub(crate) fn function_halo(function: &str) -> Option { /// The cells around a block a chain of raster functions (`steps`) reads with it: what each step /// reads, added, as each works on the one before. `None` when a step doesn't work in blocks; when -/// it remaps after a step over neighbours, which would meet the margin's cells, made from too few -/// neighbours, and say what they met; or when a slope in percent, whose cells past Float32's -/// range are counted where they're kept, isn't its last step. +/// it remaps or thresholds after a step over neighbours, as its ranges would then be tested on +/// a block's margin too, whose cells are made from fewer neighbours than in the whole raster; or +/// when a slope in percent, whose cells past Float32's range are counted where they're kept, +/// isn't its last step. pub(crate) fn chain_halo(steps: &[Value]) -> Option { let function = |st: &Value| st.get("function").and_then(Value::as_str).unwrap_or_default().to_string(); let after = steps.iter().skip_while(|st| function_halo(&function(st)) == Some(0)); diff --git a/crates/engine/src/cmd/workflows.rs b/crates/engine/src/cmd/workflows.rs index 473740f0d0..25d14a376e 100644 --- a/crates/engine/src/cmd/workflows.rs +++ b/crates/engine/src/cmd/workflows.rs @@ -1810,7 +1810,10 @@ impl BlockRemaps { self.empty = Some(match self.empty.take() { None => r.empty, Some(mut e) => { - e.retain(|x| r.empty.contains(x)); + // Looked up by their bits, so a remap of many ranges isn't compared range by range. + let key = |(name, lo, hi): &(String, f64, f64)| (name.clone(), lo.to_bits(), hi.to_bits()); + let here: std::collections::HashSet<_> = r.empty.iter().map(key).collect(); + e.retain(|x| here.contains(&key(x))); e } });