From 5c05639124a4518601419aa67518bb0a9f1361ab Mon Sep 17 00:00:00 2001 From: mavrick Date: Wed, 25 Nov 2026 03:22:12 -0600 Subject: [PATCH 1/3] feat(raster): Classification Tools 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, Classification Tools now read it a block at a time at that size, as Raster Functions do: each class's mean is summed from rows of the file under the training polygons, then each block is classified. `rasterops::ClassMeans` sums each training polygon's pixels as the whole raster's are, row by row over its window then column by column, its cells' centres placed on the whole grid, so its means are the whole raster's to the last bit however the rows are cut; `class_means_in` is now its one part, the whole raster. In blocks, each polygon's window is found on the file's full grid (`ZoneIn::window_on`, read from a one-pixel part), as on the whole raster. The polygons' sums are planned before they are set aside and refused past what the computer can give, and Cancel is looked at between polygons as their windows are found. The result is drawn by the classes some pixel takes, as the whole raster's is, and its file's overviews take a class, never an average. --- crates/analysis/src/rasterops.rs | 249 ++++++++++++++++++++++--- crates/engine/src/cmd/imagery.rs | 88 ++++++++- crates/engine/src/cmd/in_blocks.rs | 17 +- crates/engine/src/cmd/workflows.rs | 15 +- crates/engine/src/tests/tiled_files.rs | 29 ++- docs/user-guide/data.md | 5 +- 6 files changed, 363 insertions(+), 40 deletions(-) diff --git a/crates/analysis/src/rasterops.rs b/crates/analysis/src/rasterops.rs index f6a5d91b67..fe2450cc0f 100644 --- a/crates/analysis/src/rasterops.rs +++ b/crates/analysis/src/rasterops.rs @@ -1114,10 +1114,16 @@ impl ZoneIn { /// raster when the box holds a pole ([`ZoneIn::holds_a_pole`]), else [`zone_window`], with its /// interior samples for a zone in a system of its own. pub(crate) fn window(&self, r: &Raster, e: &Extent) -> (Range, Range) { + self.window_on(r, &r.transform, (r.width, r.height), e) + } + + /// [`ZoneIn::window`] on a grid of `r`'s system placed by `gt`, `size` columns and rows: the + /// whole grid of a file `r` is an overview of. + pub(crate) fn window_on(&self, r: &Raster, gt: &GeoTransform, size: (u32, u32), e: &Extent) -> (Range, Range) { match self { - _ if self.holds_a_pole(e) => (0..r.width, 0..r.height), - Self::Own { .. } => zone_window(r, e, true, |c| self.grid(r, c)), - Self::LonLat => zone_window(r, e, false, |c| self.grid(r, c)), + _ if self.holds_a_pole(e) => (0..size.0, 0..size.1), + Self::Own { .. } => zone_window(gt, size, e, true, |c| self.grid(r, c)), + Self::LonLat => zone_window(gt, size, e, false, |c| self.grid(r, c)), } } @@ -1224,17 +1230,23 @@ fn means_under( /// the zone's box holds a place the raster's grid can't take in one piece, and the whole raster is /// read. (A box holding a pole, whose outline lands south of a Web Mercator raster's cells near /// it, is read whole before this: `means_under`.) -fn zone_window(r: &Raster, e: &Extent, interior: bool, to_grid: impl Fn(Coord) -> Option) -> (Range, Range) { +fn zone_window( + gt: &GeoTransform, + (width, height): (u32, u32), + e: &Extent, + interior: bool, + to_grid: impl Fn(Coord) -> Option, +) -> (Range, Range) { if e.is_empty() { return (0..0, 0..0); } const SAMPLES: u32 = 64; // Halvings of a stretch: past 2^-40 of a side it is far below a cell. const DEPTH: u32 = 40; - let whole = (0..r.width, 0..r.height); - let (w, h) = (f64::from(r.width), f64::from(r.height)); + let whole = (0..width, 0..height); + let (w, h) = (f64::from(width), f64::from(height)); let place = |ll: Coord| { - let (col, row) = r.transform.to_pixel(to_grid(ll)?); + let (col, row) = gt.to_pixel(to_grid(ll)?); (col.is_finite() && row.is_finite()).then_some((col, row)) }; let sides: [(Coord, Coord); 4] = [ @@ -1287,7 +1299,7 @@ fn zone_window(r: &Raster, e: &Extent, interior: bool, to_grid: impl Fn(Coord) - } } let clamp = |v: f64, n: u32| v.clamp(0.0, f64::from(n)) as u32; - ((clamp(c0, r.width)..clamp(c1, r.width)), (clamp(r0, r.height)..clamp(r1, r.height))) + ((clamp(c0, width)..clamp(c1, width)), (clamp(r0, height)..clamp(r1, height))) } /// Each class's mean of `bands` over the pixels under its training polygons (lon/lat rings, each @@ -1307,26 +1319,151 @@ pub fn class_means_in( bands: &[usize], polygons: &[(String, Vec>)], ) -> Result, usize)>, String> { - let zone = ZoneIn::new(r, from)?; + let mut means = ClassMeans::new(r, from, bands, polygons)?; crate::control::begin(polygons.len().saturating_mul(r.height as usize)); - let mut classes: Vec<(String, Vec, usize)> = Vec::new(); - for (key, rings) in polygons { - let counted = |rows: usize| { - crate::control::check()?; - crate::control::advance(rows); - Ok(()) + means.add(r, (0, 0), &r.transform)?; + Ok(means.means()) +} + +/// [`class_means_in`] made a part of a raster at a time (#2865): each training polygon's pixels +/// summed as the whole raster's are, row by row over its window then column by column, its cells' +/// centres placed on the whole grid, so its mean, and the class's, are the whole raster's to the +/// last bit, however the raster is cut into rows of parts. Give it the parts in the order of their +/// rows, each holding whole rows of all the columns of [`ClassMeans::window`]. +pub struct ClassMeans<'a> { + zone: ZoneIn, + bands: &'a [usize], + polygons: &'a [(String, Vec>)], + /// Each polygon's box in the zone's system, and the columns and rows of the whole grid its + /// cells' centres can fall in. + boxes: Vec, + windows: Vec<(Range, Range)>, + /// Each polygon's sums of `bands` over its pixels so far, and how many. + sums: Vec<(Vec, usize)>, +} + +impl<'a> ClassMeans<'a> { + /// The means of `polygons` (their rings in `from`) on `r`, the whole raster. + pub fn new(r: &Raster, from: Crs, bands: &'a [usize], polygons: &'a [(String, Vec>)]) -> Result, String> { + ClassMeans::on_grid(r, &r.transform, (r.width, r.height), from, bands, polygons) + } + + /// The means of `polygons` on the whole grid of a file placed by `grid`, `size` columns and + /// rows, of which `r` is an overview (or the whole raster): each polygon's window found on + /// that grid, as on the whole raster. Cancel is looked at between polygons. The sums of the + /// polygons whose window holds a cell are planned before they are set aside, and refused + /// past what the computer can give now, with a way out. + pub fn on_grid( + r: &Raster, + grid: &GeoTransform, + size: (u32, u32), + from: Crs, + bands: &'a [usize], + polygons: &'a [(String, Vec>)], + ) -> Result, String> { + let zone = ZoneIn::new(r, from)?; + let boxes = Self::boxes(polygons)?; + let windows = boxes + .iter() + .map(|e| { + crate::control::check()?; + Ok(zone.window_on(r, grid, size, e)) + }) + .collect::, String>>()?; + // A polygon with no cell under its box sums nothing: only the others are set aside, each + // with its sums and, as they are made into the classes' means, its mean. + let under = windows.iter().filter(|(c, r)| !c.is_empty() && !r.is_empty()).count(); + let per = (bands.len() as u64).saturating_mul(16).saturating_add(64); + let floor = ((256u64 << 20) / per.max(1)) as usize; + if under > rustgis_data::memory::planned(floor, usize::MAX, per) { + return Err(format!( + "its {under} training polygons over {} bands need {} MB for their sums and means, more than this computer can give now: use fewer training polygons or bands", + bands.len(), + (under as u64).saturating_mul(per) >> 20 + )); + } + let sums = + windows.iter().map(|(c, r)| (if c.is_empty() || r.is_empty() { Vec::new() } else { vec![0.0; bands.len()] }, 0)).collect(); + Ok(ClassMeans { zone, bands, polygons, boxes, windows, sums }) + } + + /// Each polygon's box: the extent of its rings' places. + fn boxes(polygons: &[(String, Vec>)]) -> Result, String> { + polygons + .iter() + .map(|(_, rings)| { + crate::control::check()?; + Ok(rings.iter().flatten().fold(Extent::EMPTY, |mut e, c| { + e.expand(*c); + e + })) + }) + .collect() + } + + /// The columns and rows of the whole grid every polygon's window covers together. + pub fn window(&self) -> (Range, Range) { + let cover = |a: Option>, b: &Range| match a { + _ if b.is_empty() => a, + None => Some(b.clone()), + Some(a) => Some(a.start.min(b.start)..a.end.max(b.end)), }; - let Some((m, n)) = means_under(r, &zone, bands, &[rings.as_slice()], counted)? else { continue }; - match classes.iter_mut().find(|c| c.0 == *key) { - Some(c) => { - let total = c.2 + n; - c.1 = c.1.iter().zip(&m).map(|(a, b)| (a * c.2 as f64 + b * n as f64) / total as f64).collect(); - c.2 = total; + let (cols, rows) = self.windows.iter().fold((None, None), |(c, r), (wc, wr)| (cover(c, wc), cover(r, wr))); + (cols.unwrap_or(0..0), rows.unwrap_or(0..0)) + } + + /// Adds the pixels of `part`, a part of the whole grid placed by `grid` whose first column and + /// row on it are `at`, holding whole rows of the columns of [`ClassMeans::window`]: each + /// polygon's, over the rows of its window the part holds. Each row counts toward the run's + /// progress, and a cancelled run stops. + pub fn add(&mut self, part: &Raster, at: (u32, u32), grid: &GeoTransform) -> Result<(), crate::control::Cancelled> { + let (r0, r1) = (at.1, at.1.saturating_add(part.height)); + for (k, (rings, e)) in self.polygons.iter().map(|(_, rings)| rings.as_slice()).zip(&self.boxes).enumerate() { + let (Some((cols, rows)), Some(sums)) = (self.windows.get(k), self.sums.get_mut(k)) else { continue }; + let rows = rows.start.max(r0)..rows.end.min(r1); + crate::control::check()?; + crate::control::advance((r1 - r0) as usize - rows.len()); + for row in rows { + crate::control::check()?; + crate::control::advance(1); + for col in cols.clone() { + let w = grid.to_world(f64::from(col) + 0.5, f64::from(row) + 0.5); + let Some(ll) = self.zone.zone(part, w) else { continue }; + if !(e.contains(ll) && rustgis_data::geometry::polygon_contains(rings, ll)) { + continue; + } + let (c, rr) = (i64::from(col) - i64::from(at.0), i64::from(row) - i64::from(at.1)); + let vals: Option> = self.bands.iter().map(|b| part.value(*b, c, rr).map(f64::from)).collect(); + if let Some(v) = vals { + sums.0.iter_mut().zip(&v).for_each(|(s, x)| *s += x); + sums.1 += 1; + } + } + } + } + Ok(()) + } + + /// Each class's mean and pixels, in the order its first polygon with pixels comes, a class + /// with none left out, as [`class_means_in`] gives them. + pub fn means(self) -> Vec<(String, Vec, usize)> { + let mut classes: Vec<(String, Vec, usize)> = Vec::new(); + for ((key, _), (s, n)) in self.polygons.iter().zip(self.sums) { + if n == 0 { + continue; + } + let m: Vec = s.into_iter().map(|s| s / n as f64).collect(); + match classes.iter_mut().find(|c| c.0 == *key) { + Some(c) => { + let total = c.2 + n; + c.1 = c.1.iter().zip(&m).map(|(a, b)| (a * c.2 as f64 + b * n as f64) / total as f64).collect(); + c.2 = total; + } + None => classes.push((key.clone(), m, n)), } - None => classes.push((key.clone(), m, n)), } + classes } - Ok(classes) } /// `bands` bands of `images` laid onto a north-up grid in `crs` of `cols` × `rows` cells of `cell` @@ -2345,6 +2482,72 @@ mod tests { assert_eq!(Some((c[0].1.clone(), c[0].2)), zonal_means(&r, &[0, 1], &polygons[0].1).unwrap()); } + /// Class means summed from rows of a raster cut unevenly, each polygon's window found on its + /// whole grid from an overview of it, are the whole raster's to the last bit (#2865): values + /// whose sums depend on their order, a no-data cell, polygons crossing the raster's edges, a + /// class made of two polygons, one outside the raster, and rings in another system. + #[test] + fn class_means_by_rows_are_the_whole_rasters() { + let (w, h) = (37u32, 29u32); + let gt = GeoTransform { origin_x: 10.0, origin_y: 46.0, pixel_width: 0.01, pixel_height: -0.01 }; + let band = |k: f32| -> Vec { (0..w * h).map(|i| ((i as f32 * 0.137 + k).sin() * 1000.3) + (i % 7) as f32 * 1e-3).collect() }; + let (mut b0, mut b1) = (band(0.0), band(0.5)); + // A no-data cell under the first polygon: its pixel isn't counted. + b1[(5 * w + 3) as usize] = -9999.0; + // Three cells down a column whose sum is 0 in the rows' order, 1 in any other or with the + // rows cut between them summed apart: 1 + 2^60 is 2^60 in a double. + for (row, v) in [(10u32, 1.0f32), (11, 2f32.powi(60)), (12, -(2f32.powi(60)))] { + b0[(row * w + 20) as usize] = v; + } + let r = Raster::new("r", w, h, vec![b0, b1], gt, Crs::LonLat, Some(-9999.0), ColorHint::Gray, "Float32").unwrap(); + // An overview of it, on the same ground. + let (ow, oh) = (w.div_ceil(2), h.div_ceil(2)); + let ogt = GeoTransform { + pixel_width: gt.pixel_width * f64::from(w) / f64::from(ow), + pixel_height: gt.pixel_height * f64::from(h) / f64::from(oh), + ..gt + }; + let coarse = + Raster::new("o", ow, oh, vec![vec![1.0; (ow * oh) as usize]; 2], ogt, Crs::LonLat, Some(-9999.0), ColorHint::Gray, "Float32") + .unwrap(); + let ring = |pts: &[(f64, f64)]| vec![pts.iter().map(|&(x, y)| Coord::new(x, y)).collect::>()]; + let lonlat = vec![ + ("a".to_string(), ring(&[(9.95, 45.99), (10.08, 45.97), (10.02, 45.90)])), + ("b".to_string(), ring(&[(10.15, 45.75), (10.30, 45.75), (10.30, 45.65), (10.15, 45.65)])), + ("a".to_string(), ring(&[(10.20, 45.95), (10.24, 45.95), (10.24, 45.91), (10.20, 45.91)])), + ("c".to_string(), ring(&[(20.0, 10.0), (21.0, 10.0), (21.0, 11.0)])), + ("z".to_string(), ring(&[(10.202, 45.872), (10.208, 45.872), (10.208, 45.898), (10.202, 45.898)])), + ]; + let mercator = Crs::Epsg(3857); + let to = mercator.transformer().unwrap(); + let projected: Vec<(String, Vec>)> = lonlat + .iter() + .map(|(k, rings)| (k.clone(), rings.iter().map(|ring| ring.iter().map(|c| to.from_lonlat(*c).unwrap()).collect()).collect())) + .collect(); + let bits = |c: Vec<(String, Vec, usize)>| { + c.into_iter().map(|(k, m, n)| (k, m.iter().map(|v| v.to_bits()).collect::>(), n)).collect::>() + }; + for (from, polygons) in [(Crs::LonLat, &lonlat), (mercator, &projected)] { + let whole = bits(class_means_in(&r, from, &[0, 1], polygons).unwrap()); + assert_eq!(whole.iter().map(|c| c.0.as_str()).collect::>(), ["a", "b", "z"], "{from:?}: {whole:?}"); + assert_eq!(whole.get(2).map(|z| (z.1[0], z.2)), Some((0f64.to_bits(), 3)), "{from:?}: the column's sum in its rows' order"); + for cuts in [vec![1u32, 5, 7, 3], vec![2], vec![11], vec![12], vec![h]] { + let mut means = ClassMeans::on_grid(&coarse, >, (w, h), from, &[0, 1], polygons).unwrap(); + let (_, rows) = means.window(); + let (mut r0, mut i) = (rows.start, 0); + while r0 < rows.end { + let r1 = (r0 + cuts.get(i).copied().unwrap_or(4)).min(rows.end); + let data = r.bands.iter().map(|b| b.data[(r0 * w) as usize..(r1 * w) as usize].to_vec()).collect(); + let part_gt = GeoTransform { origin_y: gt.origin_y + f64::from(r0) * gt.pixel_height, ..gt }; + let part = Raster::new("p", w, r1 - r0, data, part_gt, Crs::LonLat, Some(-9999.0), ColorHint::Gray, "Float32").unwrap(); + means.add(&part, (0, r0), >).unwrap(); + (r0, i) = (r1, i + 1); + } + assert_eq!(bits(means.means()), whole, "{from:?}, cut {cuts:?}"); + } + } + } + /// Band math and per-cell rows made on several threads give the same cells, bit for bit, as /// one thread (#1252): no-data, NaN and values that come out non-finite included. #[test] diff --git a/crates/engine/src/cmd/imagery.rs b/crates/engine/src/cmd/imagery.rs index c44a1271df..0370b24d2b 100644 --- a/crates/engine/src/cmd/imagery.rs +++ b/crates/engine/src/cmd/imagery.rs @@ -1558,16 +1558,77 @@ pub(crate) fn supervised_work(s: &Session, p: &Value) -> Result, Vec<(f32, Vec)>) = classes + .into_iter() + .enumerate() + .map(|(i, (class, m, pixels))| (json!({"value": i + 1, "class": class, "pixels": pixels}), ((i + 1) as f32, m))) + .unzip(); + let _means = rustgis_data::memory::Holding::of(ids.iter().map(|(_, m)| m.len() as u64 * 8 + 32).sum()); + let shape = super::in_blocks::Shape { classes: true, ..Default::default() }; + // The classes some pixel takes, which the whole raster's are drawn by. + let present = std::cell::RefCell::new(vec![false; ids.len()]); + let mut made = blocks.run( + |block, _| { + let v = rasterops::classify_min_distance(block, &bands, &ids)?; + let mut present = present.borrow_mut(); + for c in &v { + if let Some(p) = (c.is_finite() && *c >= 1.0).then(|| present.get_mut(*c as usize - 1)).flatten() { + *p = true; + } + } + Ok(v) + }, + shape, + )?; + // Drawn by class, as the whole raster's: each class some pixel takes, in order, while + // its statistics keep them (at most 256 classes), whatever an overview of it holds. + let taken: Vec = present.into_inner().iter().enumerate().filter(|(_, p)| **p).map(|(i, _)| (i + 1) as f64).collect(); + let ramp = rustgis_map::Ramp::Harbour; + let n = if taken.len() <= 256 { taken.len().min(rustgis_map::raster::MAX_UNIQUE_VALUES) } else { 0 }; + made.layer_mut().style.renderer = rustgis_map::RasterRenderer::UniqueValues { + band: 0, + ramp: ramp.clone(), + values: taken.into_iter().take(n).enumerate().map(|(i, v)| (v, ramp.pick(i, n))).collect(), + }; + let made = super::workflows::also(made, Box::new(move |s: &mut Session, _: &mut Value| unread.say(s))); + Ok(made.with_extra(json!({"classes": legend}))) + })); + } Ok(Box::new(move || { let r = r.read()?; let (ds, unread) = rows.read()?; let explain = |e: String| unread.explain(e); - let mut polygons = Vec::new(); - for (row, ft) in ds.features.iter().enumerate() { - let Some(Geometry::Polygon(polys)) = &ft.geometry else { continue }; - let key = ds.value(row, fi).to_string(); - polygons.extend(polys.iter().map(|rings| (key.clone(), rings.clone()))); - } + let polygons = training_polygons(&ds, fi)?; // Mean of each class's training pixels, tested in the system the polygons are held in. let classes = rasterops::class_means_in(&r, ds.coord_crs(), &bands, &polygons).map_err(explain)?; if classes.len() < 2 { @@ -2375,6 +2436,21 @@ fn edge_pixels_on(r: &Raster, gt: &GeoTransform, bounds: Extent, e: &Extent) -> }) } +/// The training polygons of `ds`, each with its class (field `fi`'s value), in the layer's +/// order: a polygon of several parts is a polygon each. Cancel is looked at as they are gathered. +fn training_polygons(ds: &rustgis_data::Dataset, fi: usize) -> Result>)>, String> { + let mut polygons = Vec::new(); + for (row, ft) in ds.features.iter().enumerate() { + if row % 4096 == 0 { + rustgis_data::progress::check().map_err(|e| e.to_string())?; + } + let Some(Geometry::Polygon(polys)) = &ft.geometry else { continue }; + let key = ds.value(row, fi).to_string(); + polygons.extend(polys.iter().map(|rings| (key.clone(), rings.clone()))); + } + Ok(polygons) +} + /// What [`pixel_window`] says of a polygon whose box misses the raster. const OUTSIDE_THE_RASTER: &str = "the polygon is outside the raster"; diff --git a/crates/engine/src/cmd/in_blocks.rs b/crates/engine/src/cmd/in_blocks.rs index 06961d3adc..30f0f02a3f 100644 --- a/crates/engine/src/cmd/in_blocks.rs +++ b/crates/engine/src/cmd/in_blocks.rs @@ -66,11 +66,11 @@ pub(crate) fn chain_halo(steps: &[Value]) -> Option { } /// 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`]). +/// Indices, Classification Tools, 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.index" | "raster.classifySupervised" => 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, @@ -263,6 +263,12 @@ impl Reading { self.input.held() } + /// The file's full grid, as a read of all of it places it: from a part of one pixel. + pub(crate) fn grid(&self) -> Result { + let source = Source { input: &self.input, layer: &self.layer, path: &self.path, full: self.full, nodata: Default::default() }; + Ok(source.block((0, 1), (0, 1))?.0.grid.0) + } + /// 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 @@ -333,6 +339,11 @@ fn folder(s: &Session) -> Option { } impl Blocks { + /// The input layer's file read a block at a time ([`Reading::each_block`]), as by this plan. + pub(crate) fn reading(&self) -> Reading { + Reading { input: self.input.clone(), layer: self.layer.clone(), path: self.path.clone(), full: self.full } + } + /// 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 { diff --git a/crates/engine/src/cmd/workflows.rs b/crates/engine/src/cmd/workflows.rs index 25d14a376e..3d7c1ffc18 100644 --- a/crates/engine/src/cmd/workflows.rs +++ b/crates/engine/src/cmd/workflows.rs @@ -379,6 +379,19 @@ pub struct Made { } impl Made { + /// With `extra` added to the command's answer. + #[cfg(not(target_arch = "wasm32"))] + pub(crate) fn with_extra(mut self, extra: Value) -> Made { + self.extra = Some(extra); + self + } + + /// The layer it adds, to style. + #[cfg(not(target_arch = "wasm32"))] + pub(crate) fn layer_mut(&mut self) -> &mut rustgis_map::RasterLayer { + &mut self.layer + } + /// With `file` to commit as it is added; `said`, what the run had to say, goes with the /// error when it can't be (its `then` doesn't run). pub(crate) fn committing(mut self, file: rustgis_data::io::StagedWrite, said: Vec) -> Made { @@ -1780,7 +1793,7 @@ fn hillshade_look(mut m: Made, defaults: &rustgis_map::RasterDefaults) -> Made { /// `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 { +pub(crate) 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 { diff --git a/crates/engine/src/tests/tiled_files.rs b/crates/engine/src/tests/tiled_files.rs index 9149ee082d..083384ca36 100644 --- a/crates/engine/src/tests/tiled_files.rs +++ b/crates/engine/src/tests/tiled_files.rs @@ -607,8 +607,16 @@ fn indices_over_a_file_too_large_to_read_whole_run_a_block_at_a_time() { fn raster_functions_and_resamples_run_a_block_at_a_time() { let d = dir("functions"); let path = thousandths(&d); + // Training polygons: two of one class, a triangle of another straddling the rows and columns + // of blocks, its edges across the grid's cells, and a third class's. + let training = r#"{"type":"FeatureCollection","features":[ + {"type":"Feature","properties":{"class":"low"},"geometry":{"type":"Polygon","coordinates":[[[10.1,45.1],[10.3,45.1],[10.3,45.3],[10.1,45.3],[10.1,45.1]]]}}, + {"type":"Feature","properties":{"class":"high"},"geometry":{"type":"Polygon","coordinates":[[[10.35,45.2],[10.9,45.6],[10.6,45.85],[10.35,45.2]]]}}, + {"type":"Feature","properties":{"class":"low"},"geometry":{"type":"Polygon","coordinates":[[[10.5,45.2],[10.55,45.2],[10.55,45.25],[10.5,45.25],[10.5,45.2]]]}}, + {"type":"Feature","properties":{"class":"mid"},"geometry":{"type":"Polygon","coordinates":[[[10.7,45.05],[10.95,45.05],[10.95,45.15],[10.7,45.15],[10.7,45.05]]]}}]}"#; let open = |s: &mut Session| { s.run("layer.addData", &json!({"path": path})).unwrap(); + s.run("layer.addDataText", &json!({"fileName": "train.geojson", "text": training})).unwrap(); }; let cases = [ ("raster.function", json!({"layer": "checks", "function": "slope", "band": 1, "name": "out"})), @@ -628,6 +636,10 @@ fn raster_functions_and_resamples_run_a_block_at_a_time() { 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"})), + ( + "raster.classifySupervised", + json!({"layer": "checks", "training": "train", "classField": "class", "bands": [1, 2, 3], "name": "out"}), + ), ]; let reads = || crate::cmd::gp::TILED_READS.with(std::cell::Cell::get); for (command, p) in &cases { @@ -635,7 +647,7 @@ fn raster_functions_and_resamples_run_a_block_at_a_time() { let mut whole = Session::new(Project::default()); open(&mut whole); let mark = whole.notice_mark(); - whole.run(command, p).unwrap(); + let answer = 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"); @@ -649,7 +661,7 @@ fn raster_functions_and_resamples_run_a_block_at_a_time() { open(&mut s); assert!(raster(&s, "checks").tiled); let (before, mark) = (reads(), s.notice_mark()); - s.run(command, p).unwrap(); + let got = 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}"); @@ -671,9 +683,16 @@ 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; 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")) { + // The same classes and legend, drawn by the classes some pixel takes. + if *command == "raster.classifySupervised" { + assert_eq!(got["classes"], answer["classes"], "{why}"); + let drawn = |s: &Session| format!("{:?}", raster(s, "out").style.renderer); + assert_eq!(drawn(&s), drawn(&whole), "{why}"); + assert!(answer["classes"].as_array().is_some_and(|c| c.len() == 3), "{why}: three classes"); + } + // A remap's, threshold's or classes' 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")) || *command == "raster.classifySupervised") { 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"); diff --git a/docs/user-guide/data.md b/docs/user-guide/data.md index c37bf0911d..18ff045bec 100644 --- a/docs/user-guide/data.md +++ b/docs/user-guide/data.md @@ -1689,8 +1689,9 @@ place too: the map draws the part in view at the level it needs. Commands that m 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**, **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 +block with the cells around it), the **Function Editor** with those steps, and **Classification +Tools** (each class's mean summed from the rows of the file under the training polygons, as +from the whole raster) 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 From 4f4d3c5244090cfa4e0eb47e307e34a67645eb5f Mon Sep 17 00:00:00 2001 From: mavrick Date: Wed, 25 Nov 2026 07:29:18 -0600 Subject: [PATCH 2/3] fix(raster): class training reads whole rows of tiles where it can, widens no window for a polygon beside the raster, and shares one no-data value with the classifying (#2865) --- crates/analysis/src/rasterops.rs | 18 +++++++--- crates/engine/src/cmd/imagery.rs | 15 +++++++-- crates/engine/src/cmd/in_blocks.rs | 53 ++++++++++++++++++++---------- docs/user-guide/data.md | 15 +++++---- 4 files changed, 69 insertions(+), 32 deletions(-) diff --git a/crates/analysis/src/rasterops.rs b/crates/analysis/src/rasterops.rs index fe2450cc0f..8c2b250e6d 100644 --- a/crates/analysis/src/rasterops.rs +++ b/crates/analysis/src/rasterops.rs @@ -1372,7 +1372,7 @@ impl<'a> ClassMeans<'a> { .collect::, String>>()?; // A polygon with no cell under its box sums nothing: only the others are set aside, each // with its sums and, as they are made into the classes' means, its mean. - let under = windows.iter().filter(|(c, r)| !c.is_empty() && !r.is_empty()).count(); + let under = windows.iter().filter(|(cols, rows)| !cols.is_empty() && !rows.is_empty()).count(); let per = (bands.len() as u64).saturating_mul(16).saturating_add(64); let floor = ((256u64 << 20) / per.max(1)) as usize; if under > rustgis_data::memory::planned(floor, usize::MAX, per) { @@ -1382,8 +1382,10 @@ impl<'a> ClassMeans<'a> { (under as u64).saturating_mul(per) >> 20 )); } - let sums = - windows.iter().map(|(c, r)| (if c.is_empty() || r.is_empty() { Vec::new() } else { vec![0.0; bands.len()] }, 0)).collect(); + let sums = windows + .iter() + .map(|(cols, rows)| (if cols.is_empty() || rows.is_empty() { Vec::new() } else { vec![0.0; bands.len()] }, 0)) + .collect(); Ok(ClassMeans { zone, bands, polygons, boxes, windows, sums }) } @@ -1404,11 +1406,13 @@ impl<'a> ClassMeans<'a> { /// The columns and rows of the whole grid every polygon's window covers together. pub fn window(&self) -> (Range, Range) { let cover = |a: Option>, b: &Range| match a { - _ if b.is_empty() => a, None => Some(b.clone()), Some(a) => Some(a.start.min(b.start)..a.end.max(b.end)), }; - let (cols, rows) = self.windows.iter().fold((None, None), |(c, r), (wc, wr)| (cover(c, wc), cover(r, wr))); + // A polygon with no cell under it (beside the raster: its columns or its rows none) adds + // nothing, not the side it does have. + let held = self.windows.iter().filter(|(wc, wr)| !wc.is_empty() && !wr.is_empty()); + let (cols, rows) = held.fold((None, None), |(c, r), (wc, wr)| (cover(c, wc), cover(r, wr))); (cols.unwrap_or(0..0), rows.unwrap_or(0..0)) } @@ -2527,6 +2531,10 @@ mod tests { let bits = |c: Vec<(String, Vec, usize)>| { c.into_iter().map(|(k, m, n)| (k, m.iter().map(|v| v.to_bits()).collect::>(), n)).collect::>() }; + // A polygon beside the raster, under its rows but east of its columns, widens no window. + let beside = vec![lonlat[1].clone(), ("e".to_string(), ring(&[(11.0, 45.8), (11.1, 45.8), (11.1, 45.9), (11.0, 45.9)]))]; + let window = |p: &[(String, Vec>)]| ClassMeans::on_grid(&coarse, >, (w, h), Crs::LonLat, &[0, 1], p).unwrap().window(); + assert_eq!(window(&beside), window(&beside[..1])); for (from, polygons) in [(Crs::LonLat, &lonlat), (mercator, &projected)] { let whole = bits(class_means_in(&r, from, &[0, 1], polygons).unwrap()); assert_eq!(whole.iter().map(|c| c.0.as_str()).collect::>(), ["a", "b", "z"], "{from:?}: {whole:?}"); diff --git a/crates/engine/src/cmd/imagery.rs b/crates/engine/src/cmd/imagery.rs index 0370b24d2b..51bb239a8d 100644 --- a/crates/engine/src/cmd/imagery.rs +++ b/crates/engine/src/cmd/imagery.rs @@ -1573,10 +1573,19 @@ pub(crate) fn supervised_work(s: &Session, p: &Value) -> Result 1 && !super::in_blocks::affordable(row.saturating_mul(u64::from(strip)).saturating_mul(2)) { + strip /= 2; + } reading .each_block((cols.start, cols.end), (under.start, under.end), (width, strip), |_, _, read| { means.add(&read.raster, read.at, &read.grid.0).map_err(String::from) diff --git a/crates/engine/src/cmd/in_blocks.rs b/crates/engine/src/cmd/in_blocks.rs index 30f0f02a3f..0cb7cb9722 100644 --- a/crates/engine/src/cmd/in_blocks.rs +++ b/crates/engine/src/cmd/in_blocks.rs @@ -91,8 +91,16 @@ pub(crate) struct Blocks { full: (u32, u32), /// The cells around each block read with it ([`Blocks::with_halo`]). halo: u32, + /// The no-data value its first block was read with, shared with its [`Blocks::reading`]. + nodata: Nodata, } +/// The no-data value of a run's first block, which every other block it reads must have: a +/// sidecar beside the file changed while it runs would give later blocks another. Shared by a +/// plan and the reading it gives, so a command that reads the file twice (training, then +/// classifying) reads it with one value. +type Nodata = std::sync::Arc>>; + /// 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 @@ -194,7 +202,16 @@ 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, halo: 0 })) + Ok(Some(Blocks { + input: input.clone(), + layer: layer.to_string(), + path: path.to_string(), + out: out.to_string(), + folder, + full, + halo: 0, + nodata: Nodata::default(), + })) } /// The full size of `input`'s file when a command reads it a block at a time ([`plan`]), for one @@ -203,7 +220,7 @@ pub(crate) fn plan(s: &Session, input: &Input, out: &str) -> Result Option { let (full, (layer, path)) = (too_large(input)?, input.file()?); - Some(Reading { input: input.clone(), layer: layer.to_string(), path: path.to_string(), full }) + Some(Reading { input: input.clone(), layer: layer.to_string(), path: path.to_string(), full, nodata: Nodata::default() }) } /// Whether the work can plan for `need` bytes more: within what a job may take now @@ -233,6 +250,7 @@ pub(crate) struct Reading { layer: String, path: String, full: (u32, u32), + nodata: Nodata, } impl Reading { @@ -265,7 +283,7 @@ impl Reading { /// The file's full grid, as a read of all of it places it: from a part of one pixel. pub(crate) fn grid(&self) -> Result { - let source = Source { input: &self.input, layer: &self.layer, path: &self.path, full: self.full, nodata: Default::default() }; + let source = Source { input: &self.input, layer: &self.layer, path: &self.path, full: self.full, nodata: &self.nodata }; Ok(source.block((0, 1), (0, 1))?.0.grid.0) } @@ -281,7 +299,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, nodata: Default::default() }; + let source = Source { input: &self.input, layer: &self.layer, path: &self.path, full: self.full, nodata: &self.nodata }; 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)); @@ -341,7 +359,13 @@ fn folder(s: &Session) -> Option { impl Blocks { /// The input layer's file read a block at a time ([`Reading::each_block`]), as by this plan. pub(crate) fn reading(&self) -> Reading { - Reading { input: self.input.clone(), layer: self.layer.clone(), path: self.path.clone(), full: self.full } + Reading { + input: self.input.clone(), + layer: self.layer.clone(), + path: self.path.clone(), + full: self.full, + nodata: self.nodata.clone(), + } } /// The plan reading `halo` cells around each block with it, for work over a cell's @@ -366,7 +390,7 @@ impl Blocks { cells: impl Fn(&Raster, &rustgis_geom::Extent) -> Result, String>, shape: Shape, ) -> Result { - let Blocks { input, layer, path, out, folder, full, halo } = self; + let Blocks { input, layer, path, out, folder, full, halo, nodata: first } = self; let (nodata, kind) = shape.nodata(); let cells = |r: &Raster, ground: &rustgis_geom::Extent| -> Result, String> { let mut v = cells(r, ground)?; @@ -405,7 +429,7 @@ impl Blocks { )); } let _held = rustgis_data::memory::Holding::of(need); - let blocks = Source { input: &input, layer: &layer, path: &path, full, nodata: Default::default() }; + let blocks = Source { input: &input, layer: &layer, path: &path, full, nodata: &first }; // 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. @@ -541,8 +565,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>>, + /// The no-data value the run's first block was read with, which every other one must have. + nodata: &'a Nodata, } impl Source<'_> { @@ -558,15 +582,10 @@ 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. + // One no-data value for every block of a run ([`Nodata`]). 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)), + if *self.nodata.get_or_init(|| nodata) != nodata { + return Err(format!("{}: its no-data value changed while it was read (Reload Data)", self.layer)); } 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 { diff --git a/docs/user-guide/data.md b/docs/user-guide/data.md index 18ff045bec..8ebb98ccd5 100644 --- a/docs/user-guide/data.md +++ b/docs/user-guide/data.md @@ -1691,13 +1691,14 @@ at the file's full resolution when that part fits. **Indices**, **Raster Functio NDVI, remap, threshold, slope, aspect and hillshade, those over a cell's neighbours reading each block with the cells around it), the **Function Editor** with those steps, and **Classification Tools** (each class's mean summed from the rows of the file under the training polygons, as -from the whole raster) 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 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. +from the whole raster) 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 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 at a time instead: its header, then only the tiles of the overview it opens from. A From 49484840c3b6a8a96b031ba6bc6a5de41111fb7f Mon Sep 17 00:00:00 2001 From: mavrick Date: Wed, 25 Nov 2026 08:09:09 -0600 Subject: [PATCH 3/3] fix(raster): class training strips start on a row of tiles; its sums are counted in what is held (#2865) --- crates/analysis/src/rasterops.rs | 6 +++++- crates/engine/src/cmd/imagery.rs | 6 +++++- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/crates/analysis/src/rasterops.rs b/crates/analysis/src/rasterops.rs index 8c2b250e6d..16e848c95d 100644 --- a/crates/analysis/src/rasterops.rs +++ b/crates/analysis/src/rasterops.rs @@ -1340,6 +1340,9 @@ pub struct ClassMeans<'a> { windows: Vec<(Range, Range)>, /// Each polygon's sums of `bands` over its pixels so far, and how many. sums: Vec<(Vec, usize)>, + /// What the sums hold, counted in what RustGIS holds while they live, so the reads they're + /// made from plan for them. + _held: rustgis_data::memory::Holding, } impl<'a> ClassMeans<'a> { @@ -1386,7 +1389,8 @@ impl<'a> ClassMeans<'a> { .iter() .map(|(cols, rows)| (if cols.is_empty() || rows.is_empty() { Vec::new() } else { vec![0.0; bands.len()] }, 0)) .collect(); - Ok(ClassMeans { zone, bands, polygons, boxes, windows, sums }) + let _held = rustgis_data::memory::Holding::of((under as u64).saturating_mul(per)); + Ok(ClassMeans { zone, bands, polygons, boxes, windows, sums, _held }) } /// Each polygon's box: the extent of its rings' places. diff --git a/crates/engine/src/cmd/imagery.rs b/crates/engine/src/cmd/imagery.rs index 51bb239a8d..c1ce509ada 100644 --- a/crates/engine/src/cmd/imagery.rs +++ b/crates/engine/src/cmd/imagery.rs @@ -1586,8 +1586,12 @@ pub(crate) fn supervised_work(s: &Session, p: &Value) -> Result 1 && !super::in_blocks::affordable(row.saturating_mul(u64::from(strip)).saturating_mul(2)) { strip /= 2; } + // From the start of the row of tiles the window begins in (a block's rows, which a + // file's tiles of 256 or 512 rows divide), so no row of tiles is read for two strips; + // the rows above the window are visited by no polygon. + let top = under.start / bh * bh; reading - .each_block((cols.start, cols.end), (under.start, under.end), (width, strip), |_, _, read| { + .each_block((cols.start, cols.end), (top, under.end), (width, strip), |_, _, read| { means.add(&read.raster, read.at, &read.grid.0).map_err(String::from) }) .map_err(explain)?;