From d35d537b009f52cb9e93ad54873e458d45b495e5 Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Sun, 22 Nov 2026 14:31:06 -0300 Subject: [PATCH 1/4] feat(cube): cube.reduce takes several bands into one RGB layer (#2585 part 2) "assets": ["B04", "B03", "B02"] reads a STAC collection's bands from the same items into one slice of a band each, masked alike, and summarises them together: a cell goes in at a date only with a value in every band (a partial one is left out and said), first takes all its bands from one date, and median from the date whose bands' sum is the middle. One layer a group, drawn as RGB when three bands. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/cube.rs | 177 +++++++++++++++++---- crates/engine/src/cmd/stac.rs | 230 ++++++++++++++++++++++------ crates/engine/src/tests.rs | 2 + crates/engine/src/tests/cube_rgb.rs | 147 ++++++++++++++++++ docs/user-guide/analysis.md | 11 ++ 5 files changed, 485 insertions(+), 82 deletions(-) create mode 100644 crates/engine/src/tests/cube_rgb.rs diff --git a/crates/engine/src/cmd/cube.rs b/crates/engine/src/cmd/cube.rs index e27618a1d0..374c2e39fe 100644 --- a/crates/engine/src/cmd/cube.rs +++ b/crates/engine/src/cmd/cube.rs @@ -29,7 +29,7 @@ pub fn commands() -> Vec { r#"{"cube"?: an entry of cube.catalog (its STAC API, collection, band, cell size and cloud cap, or its Zarr store and variable) | "layers"?: [raster layers, a date each; one on another grid is resampled (nearest) onto the first's] | "layer"?: a Zarr layer (or "path" | "url", "variable", "index", "crs" as for zarr.reduce) or a raster of several bands, a date each (default: the active layer) | "collection": a STAC collection (desktop; read in place over an area, in pieces when large; with url, asset, bbox, maxCloud, cellSize and resampling below, and "start", "end"), "url"?: the collection's STAC API (as for stac.addCube), "asset"?: the collection's band, such as NDVI, "mask"?: a collection's quality band (as for cube.reduce), "bbox"?: [w, s, e, n] | "view" (the collection's area), "maxCloud"?: a collection's cloud cover cap, "cellSize"?: a collection's cell size in the files' units (the overview level nearest it is read), "resampling"?: "nearest" (default: that overview's pixels as stored) | "average" (each cell the mean of the full images' pixels in it, which reads them), "band"?: 1-based (a stack's band), "dates"?: [dates] (a stack's or the bands' dates, in their order; default: read from the layers' names or files, or the bands' names), "start"?, "end"?: dates (a whole number from 1000 to 9999 is a year; an end given as a year or a month takes all of it), "months"?: [1–12] (one season across years), "test"?: "hamedRao" (default) | "yueWang" | "seasonal" | "original", "seasons"?: parts of a year for the seasonal test (default 12), "alpha"?: 0.05 (above 0, below 0.5), "minValid"?: dates a cell needs (default: half of them, at least 4; the seasonal test also needs 4 in seasons of two or more), "per"?: "year" (default) | "decade", "name"?: text, "ran"?: (internal: a trend the app has worked out)} → four raster layers: Sen's slope, the test's Z and p-value, and the slope where p < alpha"#, ), C::new("cube.reduce", "Summarise a Data Cube over Time", "Analyze › Workflows", reduce_cmd).inputs(cube_inputs).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Network).with(crate::policy::Effect::Files)).params( - r#"{"cube"?: an entry of cube.catalog (as for cube.trend) | "layers"?: [raster layers, a date each; one on another grid is resampled (nearest) onto the first's] | "layer"?: a Zarr layer or a raster of several bands, a date each (default: the active layer) | "path"?: a Zarr store's folder | "url"?: a Zarr store's address, or a STAC collection's API (as for stac.addCube) | "collection": a STAC collection (desktop; read in place over an area, in pieces when large; with url, asset, bbox, maxCloud, cellSize and resampling below, and "start", "end"), "variable"?, "index"?, "crs"?: a Zarr variable's (as for zarr.reduce), "asset"?: the collection's band, such as NDVI, "mask"?: {"asset": the items' quality band, such as SCL, Fmask, qa_pixel or CMASK, and one of "keep": [classes] | "drop": [classes] | "bits": {"set"?: [bits on], "unset"?: [bits off]} (bits 0–63)} (a collection's: a cell is taken at a date only where the same item's quality band lets it through, read onto the band's grid by nearest neighbour; items without it are left out), "bbox"?: [w, s, e, n] | "view" (the collection's area), "maxCloud"?: a collection's cloud cover cap, "cellSize"?: a collection's cell size in the files' units (the overview level nearest it is read), "resampling"?: "nearest" (default) | "average" (as for cube.trend), "band"?: 1-based (a stack's band), "dates"?: [dates] (a stack's or the bands' dates, in their order; default: read from the layers' names or files, or the bands' names), "stat": "mean"|"median"|"min"|"max"|"sum"|"std" (the population standard deviation, n)|"count"|"countAbove"|"first" (the value at the cell's first date with one, in "order": the best pixel)|"mode" or "majority" (a categorical cube's most frequent class; the least of those tied)|"modeCount" (how many dates had the mode)|"variety" (how many classes)|"changes" (how many times the class changed from one valued date to the next)|"longestRun" (the class of the longest run of dates in one class; the least of those tied)|"longestRunLength" (how many dates that run lasted)|"frequency" (a layer for each class met: its count of dates)|"countIn" (how many dates in the classes given), "order"?: first's order of the dates: "clear" (the default with a mask: by the share of the area the mask lets through, the clearest first) | "date" (the default without one: the earliest first) | "-date" (the latest first), "above"?: number (countAbove's threshold), "classes"?: [whole numbers 0–255, at most 256] (countIn's classes), "by"?: "all" (default: one layer) | "year" (a layer for each calendar year) | "month" (a layer for each month of the year, across years), "start"?, "end"?: dates (as for cube.trend), "months"?: [1–12] (a season across years), "minValid"?: 0–1 (a cell with a smaller share of its group's dates is left empty; default 0), "name"?: text} → raster layers of the statistic, one for each group (frequency: one for each class of each group)"#, + r#"{"cube"?: an entry of cube.catalog (as for cube.trend) | "layers"?: [raster layers, a date each; one on another grid is resampled (nearest) onto the first's] | "layer"?: a Zarr layer or a raster of several bands, a date each (default: the active layer) | "path"?: a Zarr store's folder | "url"?: a Zarr store's address, or a STAC collection's API (as for stac.addCube) | "collection": a STAC collection (desktop; read in place over an area, in pieces when large; with url, asset, bbox, maxCloud, cellSize and resampling below, and "start", "end"), "variable"?, "index"?, "crs"?: a Zarr variable's (as for zarr.reduce), "asset"?: the collection's band, such as NDVI, "assets"?: [2–16 of the collection's bands, such as ["B04", "B03", "B02"]] (instead of asset, for mean, median or first: one layer a group with a band for each, drawn as RGB when three; a cell goes in at a date only with a value in every band, and median takes each cell's bands from one date, the one whose bands' sum is the middle (the lower of two); items without all of them are left out), "mask"?: {"asset": the items' quality band, such as SCL, Fmask, qa_pixel or CMASK, and one of "keep": [classes] | "drop": [classes] | "bits": {"set"?: [bits on], "unset"?: [bits off]} (bits 0–63)} (a collection's: a cell is taken at a date only where the same item's quality band lets it through, read onto the band's grid by nearest neighbour; items without it are left out), "bbox"?: [w, s, e, n] | "view" (the collection's area), "maxCloud"?: a collection's cloud cover cap, "cellSize"?: a collection's cell size in the files' units (the overview level nearest it is read), "resampling"?: "nearest" (default) | "average" (as for cube.trend), "band"?: 1-based (a stack's band), "dates"?: [dates] (a stack's or the bands' dates, in their order; default: read from the layers' names or files, or the bands' names), "stat": "mean"|"median"|"min"|"max"|"sum"|"std" (the population standard deviation, n)|"count"|"countAbove"|"first" (the value at the cell's first date with one, in "order": the best pixel)|"mode" or "majority" (a categorical cube's most frequent class; the least of those tied)|"modeCount" (how many dates had the mode)|"variety" (how many classes)|"changes" (how many times the class changed from one valued date to the next)|"longestRun" (the class of the longest run of dates in one class; the least of those tied)|"longestRunLength" (how many dates that run lasted)|"frequency" (a layer for each class met: its count of dates)|"countIn" (how many dates in the classes given), "order"?: first's order of the dates: "clear" (the default with a mask: by the share of the area the mask lets through, the clearest first) | "date" (the default without one: the earliest first) | "-date" (the latest first), "above"?: number (countAbove's threshold), "classes"?: [whole numbers 0–255, at most 256] (countIn's classes), "by"?: "all" (default: one layer) | "year" (a layer for each calendar year) | "month" (a layer for each month of the year, across years), "start"?, "end"?: dates (as for cube.trend), "months"?: [1–12] (a season across years), "minValid"?: 0–1 (a cell with a smaller share of its group's dates is left empty; default 0), "name"?: text} → raster layers of the statistic, one for each group (frequency: one for each class of each group)"#, )] } @@ -113,6 +113,11 @@ pub trait TimeCube: Send + Sync { let _ = (i, cancel); Ok(None) } + /// The bands a slice holds, when several (a STAC collection's `"assets"`), from the slice's + /// band on: empty for a cube of one band. + fn assets(&self) -> &[String] { + &[] + } } /// `outputs` with what reading the cube's slices said ([`TimeCube::lost`]) on the first of them: @@ -316,6 +321,15 @@ pub fn cube_from(s: &mut Session, p: &Value, needs: Needs) -> Result Result, String> { let outputs = self.groups.len(); + // A slot for each band of each group (one band but for "assets"): group `g`'s are + // `g * nb..(g + 1) * nb`, folded together so a cell's bands take the same dates. + let nb = self.cube.assets().len().max(1); + let slots = outputs * nb; let too_many = |cells: usize| { - let values = (cells as u64).saturating_mul(outputs as u64); + let values = (cells as u64).saturating_mul(slots as u64); (values > MAX_REDUCED).then(|| { - format!("{cells} cells × {outputs} outputs is {values} values, more than {MAX_REDUCED}: take a smaller area, a coarser cell size or fewer outputs") + format!("{cells} cells × {slots} output bands is {values} values, more than {MAX_REDUCED}: take a smaller area, a coarser cell size or fewer outputs") }) }; // A cube that knows its size is refused before it reads anything. @@ -1765,8 +1783,8 @@ impl ReduceRun { let mut stitch = Stitch::default(); // Each group's columns so far, by class for frequency; and for frequency each group's // value where a class is missing, for a class met first in a later piece. - let mut bands: Vec = vec![Vec::new(); outputs]; - let mut masks: Vec> = vec![Vec::new(); outputs]; + let mut bands: Vec = vec![Vec::new(); slots]; + let mut masks: Vec> = vec![Vec::new(); slots]; let frequency = self.stat == Stat::Frequency; // The cells of the pieces read so far, for a cube that didn't know its size. let mut read_cells = 0usize; @@ -1778,23 +1796,27 @@ impl ReduceRun { // cube's) they come as read, and the groups open are those of the dates in flight, a // couple of years' for 16-day composites. Totals are f64 and the outputs f32, so the // order of arrival can move an output's last bit at most, and only then. - let mut totals: Vec> = (0..outputs).map(|_| None).collect(); + let mut totals: Vec> = (0..slots).map(|_| None).collect(); let mut seen = vec![0usize; outputs]; - let mut finished: Vec)>> = vec![None; outputs]; + let mut finished: Vec)>> = vec![None; slots]; let mut place = |k: usize, slice: Option<(Arc, usize)>| -> Result<(), String> { let g = self.group_of.get(k).copied().filter(|g| *g < outputs).ok_or("a date in no group")?; + let span = g * nb..(g + 1) * nb; // A date with nothing written only lowers the counts. if let Some((r, b)) = slice { let i = self.steps.get(k).copied().unwrap_or(0); - let vals = &r.bands.get(b).ok_or("the slice has no such band")?.data; + let layers: Vec<&[f32]> = (b..b + nb) + .map(|j| r.bands.get(j).map(|x| x.data.as_slice()).ok_or("the slice has no such band")) + .collect::>()?; + let vals = layers.first().copied().unwrap_or_default(); match &grid { None => { if let Some(e) = too_many(vals.len()) { return Err(e); } - // The median holds every date's value of the piece's cells. + // The median holds every date's value of the piece's cells, each band's. if self.stat == Stat::Median - && let Some(e) = too_many_values(vals.len(), self.steps.len()) + && let Some(e) = too_many_values(vals.len().saturating_mul(nb), self.steps.len()) { return Err(e); } @@ -1802,20 +1824,27 @@ impl ReduceRun { } Some(first) => off_grid(self.cube.as_ref(), i, first, &r)?, } - let slot = totals.get_mut(g).ok_or("a date in no group")?; - if slot.is_none() { - let dates = self.groups.get(g).map_or(0, |(_, d)| *d); + let group = totals.get_mut(span.clone()).ok_or("a date in no group")?; + let dates = self.groups.get(g).map_or(0, |(_, d)| *d); + for slot in group.iter_mut().filter(|t| t.is_none()) { *slot = Some(Totals::new(self.stat, vals.len(), dates)?); } - let t = slot.as_mut().ok_or("a date in no group")?; - t.at(rank.get(k).copied().unwrap_or(0)); + let mut ts: Vec<&mut Totals> = group.iter_mut().flatten().collect(); + let cells = ts.first().map_or(0, |t| t.cells()); + for t in &mut ts { + t.at(rank.get(k).copied().unwrap_or(0)); + } let nodata = r.nodata.map(|v| v as f32); - for (c, v) in vals.iter().enumerate().take(t.cells()) { - if v.is_finite() && Some(*v) != nodata { - t.add(c, f64::from(*v)); + let valued = |v: Option<&f32>| v.is_some_and(|v| v.is_finite() && Some(*v) != nodata); + // A cell goes in at a date only with a value in every band, so they keep together. + for c in 0..cells { + if layers.iter().all(|l| valued(l.get(c))) { + for (t, l) in ts.iter_mut().zip(&layers) { + t.add(c, f64::from(l.get(c).copied().unwrap_or(f32::NAN))); + } } } - if let Some(e) = t.refused() { + if let Some(e) = ts.iter().find_map(|t| t.refused()) { return Err(e.to_string()); } // The groups being read at once (every month's, by month) share the cap. @@ -1827,9 +1856,11 @@ impl ReduceRun { *n += 1; let dates = self.groups.get(g).map_or(0, |(_, d)| *d); if *n >= dates - && let (Some(t), Some(out)) = (totals.get_mut(g).and_then(Option::take), finished.get_mut(g)) + && let Some(outs) = finish_group(totals.get_mut(span.clone()).unwrap_or_default(), self.min_share, dates, frequency) { - *out = Some(finish(&t, self.min_share, dates, frequency)); + for (out, slot) in outs.into_iter().zip(finished.get_mut(span).unwrap_or_default()) { + *slot = Some(out); + } if let Some(e) = classes_over(&totals, &finished, class_cap(self.stat)) { return Err(e); } @@ -1848,22 +1879,33 @@ impl ReduceRun { { return Err(e); } - for (g, (band, mask)) in bands.iter_mut().zip(&mut masks).enumerate() { + for g in 0..outputs { let dates = self.groups.get(g).map_or(0, |(_, d)| *d); + let span = g * nb..(g + 1) * nb; + let done_before: Vec<_> = finished.get_mut(span.clone()).unwrap_or_default().iter_mut().filter_map(Option::take).collect(); // A group with no data written in this piece: no values, as its totals would give. - let (columns, piece_mask) = match (finished.get_mut(g).and_then(Option::take), totals.get_mut(g).and_then(Option::take)) { - (Some(out), _) => out, - (None, Some(t)) => finish(&t, self.min_share, dates, frequency), - (None, None) => finish(&Totals::new(self.stat, cells, 0)?, self.min_share, dates, frequency), + let outs = if done_before.len() == nb { + done_before + } else if let Some(outs) = finish_group(totals.get_mut(span.clone()).unwrap_or_default(), self.min_share, dates, frequency) + { + outs + } else { + let none = finish(&Totals::new(self.stat, cells, 0)?, self.min_share, dates, frequency); + vec![none; nb] }; - // Their full length when the cube knows it, so they don't grow by doubling. - stack_columns(band, mask, columns, &piece_mask, whole)?; - if let (0, Some(total)) = (piece, whole) - && frequency + for ((columns, piece_mask), (band, mask)) in outs + .into_iter() + .zip(bands.get_mut(span.clone()).unwrap_or_default().iter_mut().zip(masks.get_mut(span).unwrap_or_default())) { - reserve(mask, total)?; + // Their full length when the cube knows it, so they don't grow by doubling. + stack_columns(band, mask, columns, &piece_mask, whole)?; + if let (0, Some(total)) = (piece, whole) + && frequency + { + reserve(mask, total)?; + } + mask.extend(piece_mask); } - mask.extend(piece_mask); } // Frequency's columns are known as they are met: their values within the outputs' cap. let columns: usize = bands.iter().map(Vec::len).sum(); @@ -1884,6 +1926,25 @@ impl ReduceRun { } done.store(self.total(), Ordering::Relaxed); let grid = &grid; + // Several bands: one raster a group, a band for each asset (drawn as RGB when three). + if nb > 1 { + let mut slots = bands.into_iter(); + let outputs = self + .groups + .iter() + .map(|(name, _)| { + let columns: Vec> = slots.by_ref().take(nb).filter_map(|c| c.into_iter().next().map(|(_, b)| b)).collect(); + let hint = if nb == 3 { raster::ColorHint::Rgb { alpha: false } } else { raster::ColorHint::Gray }; + let mut r = Raster::new(name.clone(), grid.width, height, columns, grid.transform, grid.crs, None, hint, "Float32") + .map_err(|e| e.to_string())?; + for (band, asset) in r.bands.iter_mut().zip(self.cube.assets()) { + band.name.clone_from(asset); + } + Ok(r) + }) + .collect(); + return with_lost(outputs, self.cube.as_ref()); + } let outputs = self .groups .iter() @@ -1912,6 +1973,51 @@ fn finish(t: &Totals, min_share: f64, dates: usize, frequency: bool) -> (Columns (t.columns(min_share, dates), mask) } +/// A group's slots' columns (a slot for each band), their totals taken: `None` when the group has +/// none yet. Several bands' median is taken whole ([`median_of_dates`]). +fn finish_group(slots: &mut [Option], min_share: f64, dates: usize, frequency: bool) -> Option)>> { + let ts: Vec = slots.iter_mut().filter_map(Option::take).collect(); + if ts.is_empty() { + return None; + } + if ts.len() > 1 && ts.first().is_some_and(|t| t.stat == Stat::Median) { + return Some(median_of_dates(&ts, min_share, dates).into_iter().map(|b| (vec![(None, b)], Vec::new())).collect()); + } + Some(ts.iter().map(|t| finish(t, min_share, dates, frequency)).collect()) +} + +/// Several bands' median (`ts`, a band each over the same cells, each cell's values of the same +/// dates in the same order): each cell's bands from one date, the one whose bands' sum is the +/// middle (the lower of the two for an even count; ties by the bands' values), so a cell is +/// one date's pixel rather than each band's own middle, which can mix dates into a colour no +/// date had. +fn median_of_dates(ts: &[Totals], min_share: f64, dates: usize) -> Vec> { + let need = (min_share.clamp(0.0, 1.0) * dates as f64 - 1e-9).ceil().max(1.0) as u32; + let Some(t0) = ts.first() else { return Vec::new() }; + let per = t0.per; + let mut out: Vec> = ts.iter().map(|_| Vec::with_capacity(t0.n.len())).collect(); + let mut keys: Vec<(f64, usize)> = Vec::new(); + for (c, k) in t0.n.iter().enumerate() { + let value = |t: &Totals, j: usize| t.values.get(c * per + j).copied().unwrap_or(f32::NAN); + keys.clear(); + if *k >= need { + keys.extend((0..(*k as usize).min(per)).map(|j| (ts.iter().map(|t| f64::from(value(t, j))).sum(), j))); + } + let pick = keys.len().checked_sub(1).map(|n| n / 2).map(|m| { + let by = |a: &(f64, usize), b: &(f64, usize)| { + a.0.total_cmp(&b.0).then_with(|| { + ts.iter().map(|t| value(t, a.1).total_cmp(&value(t, b.1))).find(|o| o.is_ne()).unwrap_or(std::cmp::Ordering::Equal) + }) + }; + keys.select_nth_unstable_by(m, by).1.1 + }); + for (o, t) in out.iter_mut().zip(ts) { + o.push(pick.map_or(f32::NAN, |j| value(t, j))); + } + } + out +} + /// The most cells × classes the groups being read count at once: [`MAX_VALUES`], or for frequency, /// whose classes are each an output column, the outputs' cap [`MAX_REDUCED`], so it is refused /// before its counts and columns are made rather than after. @@ -1981,6 +2087,13 @@ pub fn reduce_start(s: &mut Session, p: &Value) -> Result { let merged = super::cube_catalog::with_entry(p)?; let p: &Value = &merged; let stat = Stat::parse(p)?; + // Several bands keep a cell's bands together: from the same dates (mean), or one date's. + if p.get("assets").is_some_and(|a| !a.is_null()) && !matches!(stat, Stat::Mean | Stat::Median | Stat::First) { + return Err(format!( + "assets takes mean, median or first, which keep each cell's bands of the same dates, not {}: give one \"asset\" for it", + stat.code() + )); + } let min_share = min_share(p)?; let by = match ps(p, "by").map(str::trim) { None | Some("") => By::All, diff --git a/crates/engine/src/cmd/stac.rs b/crates/engine/src/cmd/stac.rs index 78efa23cca..188c147088 100644 --- a/crates/engine/src/cmd/stac.rs +++ b/crates/engine/src/cmd/stac.rs @@ -459,10 +459,18 @@ pub struct CubeFiles { /// values, by the file's tile and day (one item each): only when a mask is asked for /// (`cube.reduce`'s `"mask"`). pub masks: std::collections::HashMap<(String, i64), (String, Vec)>, + /// Each file's item's other bands, in the order asked, by the file's tile and day: only when + /// several are asked for (`cube.reduce`'s `"assets"`). + pub bands: std::collections::HashMap<(String, i64), Vec>, pub collection: String, pub asset: String, } +/// One of an item's other bands: its address, (scale, offset), and the stored values its metadata +/// says aren't values. +#[cfg(not(target_arch = "wasm32"))] +pub type Band = (String, (f64, f64), Vec); + /// The first moment after a period given as a year (`"2024"`) or a month (`"2024-03"`), so an /// end given so takes all of it; `None` for a date (an end on that day) or anything else. pub(crate) fn period_after(v: &Value) -> Option { @@ -483,9 +491,11 @@ pub(crate) fn period_after(v: &Value) -> Option { /// Searches a collection over an area and period, every page up to `max_items`, and /// groups the items' asset by tile and day: `{"url"?, "collection", "asset", "bbox"? | "view", /// "start", "end", "maxCloud"?}`. With `mask`, an asset key, each file's mask is the same item's -/// asset of that key, and an item without one is left out (and said). +/// asset of that key, and an item without one is left out (and said). With `others`, more band +/// keys (`cube.reduce`'s `"assets"` after the first), each file's item's assets of those keys go +/// in [`CubeFiles::bands`], and an item without one of them is left out (and said). #[cfg(not(target_arch = "wasm32"))] -pub fn cube_files(s: &mut Session, p: &Value, max_items: usize, mask: Option<&str>) -> Result { +pub fn cube_files(s: &mut Session, p: &Value, max_items: usize, mask: Option<&str>, others: &[String]) -> Result { let api = request_api(s, p)?; let collection = ps(p, "collection").map(str::trim).filter(|c| !c.is_empty()).ok_or("collection is required")?; let asset = ps(p, "asset").map(str::trim).filter(|a| !a.is_empty()).ok_or("asset is required (a band, such as NDVI)")?; @@ -587,6 +597,8 @@ pub fn cube_files(s: &mut Session, p: &Value, max_items: usize, mask: Option<&st let mut without = 0usize; let mut masks: std::collections::HashMap<(String, i64), (String, Vec)> = Default::default(); let mut unmasked = 0usize; + let mut bands: std::collections::HashMap<(String, i64), Vec> = Default::default(); + let mut lacking = 0usize; // Each public bucket's region, found once ([`public_web`]). let mut regions: std::collections::HashMap> = Default::default(); for i in &items { @@ -616,8 +628,16 @@ pub fn cube_files(s: &mut Session, p: &Value, max_items: usize, mask: Option<&st } }, }; + // Its other bands: an item without one of them would give some cells' bands from + // another date's item. + let more: Option> = others.iter().map(|k| i.assets.iter().find(|b| b.key.eq_ignore_ascii_case(k))).collect(); + let Some(more) = more else { + lacking += 1; + without += 1; + continue; + }; // Its codes for a failed retrieval not read whole: its values can't be told from them. - if a.codes_unread { + if a.codes_unread || more.iter().any(|b| b.codes_unread) { codes_unread += 1; without += 1; continue; @@ -642,7 +662,17 @@ pub fn cube_files(s: &mut Session, p: &Value, max_items: usize, mask: Option<&st let mh = crate::render::rustgis_tiles::logins::inherit(&api, m.href.split('#').next().unwrap_or(&m.href)); let mh = if s3::is_s3(&mh) { public_web(&mh, &mut regions)? } else { mh }; let stored = m.nodata.iter().chain(&m.invalid).copied().collect(); - masks.insert((key, d), (mh, stored)); + masks.insert((key.clone(), d), (mh, stored)); + } + if !more.is_empty() { + let mut these = Vec::with_capacity(more.len()); + for b in more { + let bh = crate::render::rustgis_tiles::logins::inherit(&api, b.href.split('#').next().unwrap_or(&b.href)); + let bh = if s3::is_s3(&bh) { public_web(&bh, &mut regions)? } else { bh }; + let stored = b.nodata.iter().chain(&b.invalid).copied().collect(); + these.push((bh, (b.scale.unwrap_or(1.0), b.offset.unwrap_or(0.0)), stored)); + } + bands.insert((key, d), these); } // No scale or offset in the metadata reads as 1 and 0, the values as stored. let this = (a.scale.unwrap_or(1.0), a.offset.unwrap_or(0.0)); @@ -665,14 +695,17 @@ pub fn cube_files(s: &mut Session, p: &Value, max_items: usize, mask: Option<&st }); let no_mask = mask.filter(|_| unmasked > 0).map(|key| format!("{unmasked} item(s) left out, as they have no asset {key} to mask them by")); + let all_of = std::iter::once(asset).chain(others.iter().map(String::as_str)).collect::>().join(", "); + let no_band = (lacking > 0).then(|| format!("{lacking} item(s) left out, as they don't have all the assets {all_of}")); if tiles.is_empty() { + let has = if others.is_empty() { format!("an asset {asset}") } else { format!("all the assets {all_of}") }; return Err(match (unread_codes, no_mask) { (Some(why), _) => format!("{collection}: {why}"), - (None, Some(_)) => format!("no item of {collection} has both an asset {asset} and the mask's {}", mask.unwrap_or_default()), - (None, None) => format!("no item of {collection} has an asset {asset}"), + (None, Some(_)) => format!("no item of {collection} has both {has} and the mask's {}", mask.unwrap_or_default()), + (None, None) => format!("no item of {collection} has {has}"), }); } - for why in unread_codes.into_iter().chain(no_mask) { + for why in unread_codes.into_iter().chain(no_mask).chain(no_band) { s.warn(format!("{collection}: {why}")); } // Files reached through signed addresses (Planetary Computer's) expire within hours, so a @@ -680,7 +713,13 @@ pub fn cube_files(s: &mut Session, p: &Value, max_items: usize, mask: Option<&st // The files' addresses come from the API's answer: each is checked as one that answer points // to (http or https, never a forbidden address, and not into the local network from a public // API), before a cube on the map or a trend reads it. - let all = || tiles.values().flat_map(|by_day| by_day.values()).chain(masks.values().map(|(m, _)| m)); + let all = || { + tiles + .values() + .flat_map(|by_day| by_day.values()) + .chain(masks.values().map(|(m, _)| m)) + .chain(bands.values().flatten().map(|(b, ..)| b)) + }; if let Some(e) = all().find_map(|href| crate::render::rustgis_tiles::address::check(href, Some(&api)).err()) { return Err(e); } @@ -701,6 +740,7 @@ pub fn cube_files(s: &mut Session, p: &Value, max_items: usize, mask: Option<&st scales_differ, coded, masks, + bands, collection: collection.to_string(), asset: asset.to_string(), }) @@ -764,8 +804,14 @@ pub struct StacCube { dates: Vec, /// Each date's files, with their (scale, offset), the stored values their metadata says /// aren't values, and when masked their mask (the same item's quality asset): its address and - /// the stored values its metadata says aren't values. - files: Vec, Option)>>, + /// the stored values its metadata says aren't values; and its item's other bands, when several + /// are asked for (`"assets"`). + files: Vec, Option, Vec)>>, + /// The bands asked for, when several (`"assets"`): a slice holds one band for each. + assets: Vec, + /// Cells with a value in some of the bands but not all at a date, left out of it (so each + /// cell's bands are of one date): said once the run has read its slices. + partial: std::sync::atomic::AtomicU64, /// The quality values that let a cell through, for a cube masked by its items' quality band. mask: Option, /// Band pixels read that their item's mask file doesn't cover, left out as not clear, and the @@ -871,16 +917,22 @@ pub fn stac_cube(s: &mut Session, p: &Value) -> Result { if let Some(o) = searched.as_object_mut() { o.insert("bbox".into(), json!(bbox)); } + // Several bands: the first read as `asset`, the others from the same items. + let assets = assets(p)?; + if let (Some(first), Some(o)) = (assets.first(), searched.as_object_mut()) { + o.insert("asset".into(), json!(first)); + } let max_items = if s.long_runs.is_some() { MAX_SERIES_ITEMS } else { MAX_CUBE_ITEMS }; - let CubeFiles { tiles, scales, nodata, masks, collection, asset, .. } = - cube_files(s, &searched, max_items, mask.as_ref().map(|m| m.asset.as_str()))?; + let CubeFiles { tiles, scales, nodata, masks, mut bands, collection, asset, .. } = + cube_files(s, &searched, max_items, mask.as_ref().map(|m| m.asset.as_str()), assets.get(1..).unwrap_or_default())?; // Every tile's file for a date, by day. - let mut by_day: std::collections::BTreeMap, Option)>> = Default::default(); + let mut by_day: std::collections::BTreeMap, Option, Vec)>> = Default::default(); for (tile, days) in &tiles { for (d, href) in days { let scale = scales.get(href).copied().unwrap_or((1.0, 0.0)); let mask = masks.get(&(tile.clone(), *d)).map(|(m, stored)| (m.clone(), stored.iter().map(|v| *v as f32).collect())); - let file = (href.clone(), scale, nodata.get(href).cloned().unwrap_or_default(), mask); + let more = bands.remove(&(tile.clone(), *d)).unwrap_or_default(); + let file = (href.clone(), scale, nodata.get(href).cloned().unwrap_or_default(), mask, more); by_day.entry(*d).or_default().push(file); } } @@ -977,11 +1029,13 @@ pub fn stac_cube(s: &mut Session, p: &Value) -> Result { return Err(format!("no file of {collection}'s {asset} covers the area, only comes near it: take another bbox")); } // Within a run's block, and each slice within what a reader holds. - let per_slice = (MAX_PIECE_PIXELS / u64::from(factor).pow(2)).max(1); + // Several bands share both: a slice holds one of each. + let nb = assets.len().max(1) as u64; + let per_slice = (MAX_PIECE_PIXELS / u64::from(factor).pow(2) / nb).max(1); #[cfg(test)] - let block = PIECE_VALUES.with(|v| v.get()).unwrap_or(super::cube::MAX_VALUES); + let block = PIECE_VALUES.with(|v| v.get()).unwrap_or(super::cube::MAX_VALUES) / nb; #[cfg(not(test))] - let block = super::cube::MAX_VALUES; + let block = super::cube::MAX_VALUES / nb; let max = block.min(per_slice.saturating_mul(by_day.len() as u64)); let rows = piece_rows(width, height, by_day.len(), read_tile_rows, max).ok_or_else(|| { format!( @@ -1002,12 +1056,38 @@ pub fn stac_cube(s: &mut Session, p: &Value) -> Result { crs: layout.crs, rows, met: Default::default(), - label: format!("{collection} {asset}"), + label: if assets.is_empty() { format!("{collection} {asset}") } else { format!("{collection} {}", assets.join("-")) }, mask: mask.map(|m| m.test), uncovered: Default::default(), + assets, + partial: Default::default(), }) } +/// The most bands `"assets"` takes. +#[cfg(not(target_arch = "wasm32"))] +const MAX_ASSETS: usize = 16; + +/// `cube.reduce`'s `"assets"`: two or more of a collection's bands, read from the same items into +/// one slice of a band each; empty when not given (one `"asset"`). +#[cfg(not(target_arch = "wasm32"))] +fn assets(p: &Value) -> Result, String> { + let Some(v) = p.get("assets").filter(|v| !v.is_null()) else { return Ok(Vec::new()) }; + if p.get("asset").is_some_and(|a| !a.is_null()) { + return Err("give asset (one band) or assets (several), not both".into()); + } + let keys: Option> = + v.as_array().and_then(|a| a.iter().map(|k| k.as_str().map(str::trim).filter(|k| !k.is_empty()).map(str::to_string)).collect()); + let keys = keys.ok_or("assets is a list of the collection's bands, such as [\"B04\", \"B03\", \"B02\"]")?; + if !(2..=MAX_ASSETS).contains(&keys.len()) { + return Err(format!("assets takes 2 to {MAX_ASSETS} bands (one band is \"asset\"), not {}", keys.len())); + } + if let Some(k) = keys.iter().enumerate().find_map(|(n, k)| keys[..n].iter().any(|o| o.eq_ignore_ascii_case(k)).then_some(k)) { + return Err(format!("assets names {k} twice")); + } + Ok(keys) +} + /// The pixels of a clear share's mask read at once, and about the most over an area: its /// overview level is the one nearest that many pixels over the area. #[cfg(not(target_arch = "wasm32"))] @@ -1126,10 +1206,14 @@ impl super::cube::TimeCube for StacCube { fn masked(&self) -> bool { self.mask.is_some() } + fn assets(&self) -> &[String] { + &self.assets + } /// Band pixels their item's mask file doesn't cover: left out as not clear, and said with - /// their count and the first such mask. + /// their count and the first such mask; and cells left out at a date for a value in only some + /// of the bands asked for. fn lost(&self) -> Vec { - match self.uncovered.lock().map(|u| u.clone()) { + let mut said = match self.uncovered.lock().map(|u| u.clone()) { Ok((n, Some(href))) if n > 0 => vec![crate::sources::message_with_address( &href, &format!( @@ -1137,7 +1221,16 @@ impl super::cube::TimeCube for StacCube { ), )], _ => Vec::new(), + }; + let partial = self.partial.load(std::sync::atomic::Ordering::Relaxed); + if partial > 0 { + said.push(format!( + "{}: {partial} cell(s) had a value in some of the bands {} but not all at a date, so they were left out at that date (each cell's bands are of one date)", + self.label, + self.assets.join(", ") + )); } + said } /// The part of the area date `i`'s masks let through: a grid over the area of about /// [`SHARE_PIXELS`] cells (coarser than the band's for a large area), each cell clear when a @@ -1215,9 +1308,11 @@ impl super::cube::TimeCube for StacCube { let h = self.rows.min(self.height - top); let w = self.width; let f = self.factor.max(1); - // Each cell's sum and count of the pixels read in it. - let mut sum = vec![0.0f64; w as usize * h as usize]; - let mut count = vec![0u32; w as usize * h as usize]; + // Each band's cells' sum and count of the pixels read in them. + let nb = self.assets.len().max(1); + let cells = w as usize * h as usize; + let mut sums = vec![vec![0.0f64; cells]; nb]; + let mut counts = vec![vec![0u32; cells]; nb]; // The area's grid at the level read: a cell is `f` × `f` of its pixels. let grid = rustgis_data::raster::GeoTransform { pixel_width: self.transform.pixel_width / f64::from(f), @@ -1225,8 +1320,7 @@ impl super::cube::TimeCube for StacCube { ..self.transform }; let (wf, top_f, hf) = (i64::from(w) * i64::from(f), i64::from(top) * i64::from(f), i64::from(h) * i64::from(f)); - for (href, (k, o), fill, mask) in files { - let fill: Vec = fill.iter().map(|v| *v as f32).collect(); + for (href, scale, fill, mask, more) in files { // Cached per address for the process (`with_info`, a failure too, for a while), so a // file's header is fetched once however many pieces and dates read it. let info = cog::info_blocking(href)?; @@ -1258,7 +1352,6 @@ impl super::cube::TimeCube for StacCube { self.met.store(true, std::sync::atomic::Ordering::Relaxed); let cols = (fc0 as u32, fc1 as u32); let rows = (fr0 as u32, fr1 as u32); - let read = cog::read_values_blocking(&info, href, self.level, 0, cols, rows)?; // A masked cube's pixels go in only where the same item's mask lets them through. let keep = match (&self.mask, mask) { (Some(test), Some(m)) => Some(self.mask_window(m, test, <, cols, rows)?), @@ -1267,30 +1360,51 @@ impl super::cube::TimeCube for StacCube { (Some(_), None) => return Err(crate::sources::message_with_address(href, "has no quality band to mask its cells by")), _ => None, }; - // The band pixels with a value that the mask file doesn't cover. + // The band pixels with a value that the mask file doesn't cover (the first band's). let mut outside = 0u64; let across = (fc1 - fc0) as usize; - for (r, line) in read.chunks(across).enumerate() { - let row = ((fr0 - dy - top_f) as usize + r) / f as usize; - for (c, v) in line.iter().enumerate() { - let col = ((fc0 - dx) as usize + c) / f as usize; - let cell = row * w as usize + col; - if !v.is_finite() || fill.contains(v) { - continue; + let bands = std::iter::once((href, scale, fill)).chain(more.iter().map(|(h, s, f)| (h, s, f))); + for (b, ((bh, (k, o), fill), (sum, count))) in bands.zip(sums.iter_mut().zip(&mut counts)).enumerate() { + let fill: Vec = fill.iter().map(|v| *v as f32).collect(); + // The item's other bands are read on its first band's pixels, the same window. + let read = if b == 0 { + cog::read_values_blocking(&info, href, self.level, 0, cols, rows)? + } else { + let bi = cog::info_blocking(bh)?; + let same = bi.layout.crs == self.crs + && bi.layout.levels.get(self.level).is_some_and(|l| { + (l.width, l.height) == (lv.width, lv.height) && offset_in(&grid, &bi.layout.transform_of(l)) == Some((dx, dy)) + }); + if !same { + return Err(crate::sources::message_with_address( + bh, + &format!("not on the pixels of its item's {}: assets takes bands of one cell size", self.assets.join(", ")), + )); } - let clear = match &keep { - None => true, - Some(kept) => match kept.get(r * across + c).copied().flatten() { - Some(clear) => clear, - None => { - outside += 1; - false - } - }, - }; - if clear && let (Some(s), Some(n)) = (sum.get_mut(cell), count.get_mut(cell)) { - *s += f64::from(*v) * k + o; - *n += 1; + cog::read_values_blocking(&bi, bh, self.level, 0, cols, rows)? + }; + for (r, line) in read.chunks(across).enumerate() { + let row = ((fr0 - dy - top_f) as usize + r) / f as usize; + for (c, v) in line.iter().enumerate() { + let col = ((fc0 - dx) as usize + c) / f as usize; + let cell = row * w as usize + col; + if !v.is_finite() || fill.contains(v) { + continue; + } + let clear = match &keep { + None => true, + Some(kept) => match kept.get(r * across + c).copied().flatten() { + Some(clear) => clear, + None => { + outside += u64::from(b == 0); + false + } + }, + }; + if clear && let (Some(s), Some(n)) = (sum.get_mut(cell), count.get_mut(cell)) { + *s += f64::from(*v) * k + o; + *n += 1; + } } } } @@ -1301,7 +1415,23 @@ impl super::cube::TimeCube for StacCube { u.1.get_or_insert_with(|| m.clone()); } } - let vals: Vec = sum.iter().zip(&count).map(|(s, n)| if *n > 0 { (s / f64::from(*n)) as f32 } else { f32::NAN }).collect(); + let mut bands: Vec> = sums + .iter() + .zip(&counts) + .map(|(sum, count)| sum.iter().zip(count).map(|(s, n)| if *n > 0 { (s / f64::from(*n)) as f32 } else { f32::NAN }).collect()) + .collect(); + // A cell's bands are of one date: one with a value in only some of them is left out (said). + if nb > 1 { + let mut partial = 0u64; + for c in 0..cells { + let valued = bands.iter().filter(|b| b.get(c).is_some_and(|v| v.is_finite())).count(); + if valued > 0 && valued < nb { + partial += 1; + bands.iter_mut().filter_map(|b| b.get_mut(c)).for_each(|v| *v = f32::NAN); + } + } + self.partial.fetch_add(partial, std::sync::atomic::Ordering::Relaxed); + } let transform = rustgis_data::raster::GeoTransform { origin_y: self.transform.origin_y + f64::from(top) * self.transform.pixel_height, ..self.transform @@ -1310,7 +1440,7 @@ impl super::cube::TimeCube for StacCube { &self.label, w, h, - vec![vals], + bands, transform, self.crs, None, @@ -1376,7 +1506,7 @@ fn add_cube(s: &mut Session, p: &Value) -> CmdResult { collection, asset, .. - } = cube_files(s, p, MAX_CUBE_ITEMS, None)?; + } = cube_files(s, p, MAX_CUBE_ITEMS, None, &[])?; // A tile layer's look has no way to name them, so on the map they are values. if coded > 0 { s.warn(format!( diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index abfdd7b115..09d3d38c46 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -19,6 +19,8 @@ mod cancellation; #[cfg(not(target_arch = "wasm32"))] #[path = "tests/cube_mask.rs"] mod cube_mask; +#[path = "tests/cube_rgb.rs"] +mod cube_rgb; #[path = "tests/permission_policy.rs"] mod permission_policy; diff --git a/crates/engine/src/tests/cube_rgb.rs b/crates/engine/src/tests/cube_rgb.rs new file mode 100644 index 0000000000..7f68f9d4b6 --- /dev/null +++ b/crates/engine/src/tests/cube_rgb.rs @@ -0,0 +1,147 @@ +//! Several bands of a STAC collection summarised together into one layer (`cube.reduce`'s +//! `"assets"`, part 2 of #2585): the same mask and the same dates for each cell's bands, the median +//! and the first clear date taken as one date's pixel. +use super::*; + +/// `size` × `size` cells over [10, 11] × [45, 46], in degrees, as `values` (row by row) say. +fn cog(values: Vec, size: u32, nodata: Option) -> Vec { + use rustgis_data::raster::{ColorHint, Crs, GeoTransform, Raster}; + let px = 1.0 / f64::from(size); + let t = GeoTransform { origin_x: 10.0, origin_y: 46.0, pixel_width: px, pixel_height: -px }; + let r = Raster::new("r", size, size, vec![values], t, Crs::LonLat, nodata, ColorHint::Gray, "Float32").unwrap(); + rustgis_data::raster::cogwrite::write(&r, 0).unwrap() +} + +/// Each date's red, green and blue: ranked by their sums 80 (date 2), 90 (date 0), 100 (date 1), +/// while each band alone ranks the dates otherwise, so a band-by-band median mixes dates. +const RGB: [[f32; 3]; 3] = [[10.0, 50.0, 30.0], [20.0, 10.0, 70.0], [30.0, 40.0, 10.0]]; + +/// Three dates of B04, B03 and B02 (and B05 at half their cells) with an SCL-like mask (4 clear, +/// 9 cloud): the first cloudy in column 0, the second clear everywhere, the third cloudy in +/// column 7. The second's B02 has no value at (3, 3). A fourth item has no B02 and is left out. +fn collection() -> String { + let flat = |v: f32| cog(vec![v; 64], 8, None); + let mask = |cloudy: Option| cog((0..64).map(|c| if Some(c % 8) == cloudy { 9.0 } else { 4.0 }).collect(), 8, None); + let mut files: Vec<(String, Vec)> = Vec::new(); + for (k, rgb) in RGB.iter().enumerate() { + for (j, key) in ["B04", "B03", "B02"].iter().enumerate() { + let file = if (k, j) == (1, 2) { + cog((0..64).map(|c| if c == 27 { -1.0 } else { rgb[j] }).collect(), 8, Some(-1.0)) + } else { + flat(rgb[j]) + }; + files.push((format!("/{key}_{k}.tif"), file)); + } + files.push((format!("/B05_{k}.tif"), cog(vec![1.0; 16], 4, None))); + files.push((format!("/m{k}.tif"), mask([Some(0), None, Some(7)][k]))); + } + files.push(("/B04_3.tif".into(), flat(99.0))); + files.push(("/m3.tif".into(), mask(None))); + let (files, _) = serve_ranged_files(files); + let features: Vec = ["2024-01-01", "2024-01-17", "2024-02-02", "2024-02-18"] + .iter() + .enumerate() + .map(|(k, d)| { + let keys: &[&str] = if k < 3 { &["B04", "B03", "B02", "B05"] } else { &["B04"] }; + let mut assets: Vec = keys.iter().map(|a| format!(r#""{a}": {{"href": "{files}/{a}_{k}.tif"}}"#)).collect(); + assets.push(format!(r#""SCL": {{"href": "{files}/m{k}.tif"}}"#)); + format!( + r#"{{"type": "Feature", "id": "s{k}", "collection": "s2", "bbox": [10, 45, 11, 46], "geometry": null, + "properties": {{"datetime": "{d}T00:00:00Z", "bdc:tiles": ["t1"]}}, "assets": {{{}}}}}"#, + assets.join(", ") + ) + }) + .collect(); + let search = format!(r#"{{"type": "FeatureCollection", "features": [{}]}}"#, features.join(",")); + format!("{}/v1", serve_routes(vec![("/v1/search", search)], 64)) +} + +#[test] +fn several_bands_summarised_as_one_rgb_layer() { + let api = collection(); + let mut s = Session::new(Project::default()); + let base = json!({"url": api, "collection": "s2", "assets": ["B04", "B03", "B02"], "bbox": [10, 45, 11, 46], + "start": "2024-01-01", "end": "2024-02-29", "mask": {"asset": "SCL", "keep": [4]}}); + let with = |extra: Value| { + let mut p = base.clone(); + for (k, v) in extra.as_object().unwrap() { + p[k] = v.clone(); + } + p + }; + // The layer's bands, and what the run said. + let reduce = |s: &mut Session, p: &Value| -> (Vec>, Vec) { + let mark = s.notice_mark(); + let r = s.run("cube.reduce", p).unwrap_or_else(|e| panic!("{p}: {e}")); + assert_eq!(r["layers"].as_array().unwrap().len(), 1, "{r}"); + let l = s.map().layer(r["layers"][0].as_u64().unwrap() as u32).unwrap(); + let raster = l.raster.as_ref().unwrap().data.clone().unwrap(); + let names: Vec<&str> = raster.bands.iter().map(|b| b.name.as_str()).collect(); + let assets: Vec<&str> = p["assets"].as_array().unwrap().iter().map(|a| a.as_str().unwrap()).collect(); + assert_eq!(names, assets); + let said = s.notices_since(mark).iter().map(|n| n.text.clone()).collect(); + (raster.bands.iter().map(|b| b.data.clone()).collect(), said) + }; + // Each cell's bands as `want` says, at (col, row). + let check = |got: &[Vec], want: &dyn Fn(usize, usize) -> [f32; 3], what: &str| { + for c in 0..64 { + let (col, row) = (c % 8, c / 8); + let w = want(col, row); + for (j, band) in got.iter().enumerate() { + assert!((band[c] - w[j]).abs() < 1e-3, "{what} ({col}, {row}) band {j}: {} vs {}", band[c], w[j]); + } + } + }; + // The dates clear at a cell with a value in every band, in date order. + let clear = |col: usize, row: usize| -> Vec { + (0..3).filter(|k| !(*k == 0 && col == 0 || *k == 2 && col == 7 || *k == 1 && (col, row) == (3, 3))).collect() + }; + // The median: the date whose bands' sum is the middle, the lower of two: one date's colour. + let (median, said) = reduce(&mut s, &with(json!({"stat": "median"}))); + let middle = |col: usize, row: usize| { + let mut dates = clear(col, row); + dates.sort_by(|a, b| RGB[*a].iter().sum::().total_cmp(&RGB[*b].iter().sum())); + RGB[dates[(dates.len() - 1) / 2]] + }; + check(&median, &middle, "median"); + assert_eq!(median[0][9], 10.0, "three dates: date 0's, not the band's own middle (20)"); + assert!(said.iter().any(|t| t.contains("1 item(s) left out") && t.contains("B04, B03, B02")), "{said:?}"); + assert!(said.iter().any(|t| t.contains("1 cell(s) had a value in some of the bands")), "{said:?}"); + // First, the clearest date first (the second, then the first and third, tied, by date). + let (first, _) = reduce(&mut s, &with(json!({"stat": "first"}))); + check(&first, &|col, row| RGB[*[1, 0, 2].iter().find(|k| clear(col, row).contains(k)).unwrap()], "first, clearest"); + let (first, _) = reduce(&mut s, &with(json!({"stat": "first", "order": "date"}))); + check(&first, &|col, row| RGB[clear(col, row)[0]], "first, by date"); + // The mean of each band over the same dates. + let (mean, _) = reduce(&mut s, &with(json!({"stat": "mean"}))); + let average = |col: usize, row: usize| { + let d = clear(col, row); + [0, 1, 2].map(|j| d.iter().map(|k| RGB[*k][j]).sum::() / d.len() as f32) + }; + check(&mean, &average, "mean"); + // Two bands without the missing value: nothing left out, nothing said of it. + let (_, said) = reduce(&mut s, &with(json!({"stat": "median", "assets": ["B04", "B03"]}))); + assert!(!said.iter().any(|t| t.contains("cell(s) had a value")), "{said:?}"); + // What can't be asked. + for (bad, why) in [ + (json!({"stat": "max"}), "assets takes mean, median or first"), + (json!({"stat": "first", "asset": "B04"}), "not both"), + (json!({"stat": "first", "assets": ["B04"]}), "2 to 16"), + (json!({"stat": "first", "assets": ["B04", "b04"]}), "names b04 twice"), + (json!({"stat": "first", "assets": ["B04", "B05"]}), "not on the pixels"), + (json!({"stat": "first", "assets": ["B04", "B09"]}), "no item of s2 has all the assets B04, B09"), + ] { + let e = s.run("cube.reduce", &with(bad.clone())).unwrap_err(); + assert!(e.contains(why), "{bad}: {e}"); + } + let e = s.run("cube.trend", &with(json!({}))).unwrap_err(); + assert!(e.contains("of one band"), "{e}"); +} + +/// A stack of layers has no assets to read together: refused. +#[test] +fn assets_are_a_collections() { + let mut s = Session::new(Project::default()); + let e = s.run("cube.reduce", &json!({"layers": ["a", "b"], "assets": ["B04", "B03"], "stat": "median"})).unwrap_err(); + assert!(e.contains("STAC collection's bands"), "{e}"); +} diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index 417003521b..88f79bc868 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -2209,6 +2209,16 @@ is the data cube summary's only. values below). The example below keeps SCL's dark areas (2) and unclassified pixels (7), which a hilly area needs (they can hold shadows or low cloud): drop them for a stricter mask. +- **Several bands:** `"assets": ["B04", "B03", "B02"]` (instead of `"asset"`) reads 2 to 16 of a + collection's bands from the same items and makes one layer of a band for each, drawn as RGB when + there are three. It takes **mean**, **median** and **first**, which keep each cell's bands + together: a cell goes in at a date only with a value in every band (one with a value in only + some is left out at that date, and said with how many), so first takes all its bands from the + same date, and median takes them from one date too, the one whose bands' sum is the middle (the + lower of the two middle ones for an even count), not each band's own middle, which can mix dates + into a colour no date had. The bands have to be on one grid of pixels (one cell size); a + band on another is refused, and an item without all of them is left out and said. + - **Classes:** a series of categorical rasters, such as yearly land-cover maps (MapBiomas, ESA WorldCover), is summarised as classes with eight more statistics: - **mode**, each cell's most frequent class, the least of those tied (`"majority"` too); @@ -2261,6 +2271,7 @@ rustgis-cli run --cmd 'cube.reduce={"layers":["ndvi_2015","ndvi_2016","ndvi_2017 rustgis-cli run --data cobertura_1985.tif --data cobertura_1986.tif --data cobertura_1987.tif --cmd 'cube.reduce={"layers":["cobertura_1985","cobertura_1986","cobertura_1987"],"stat":"changes"}' rustgis-cli run --cmd 'cube.reduce={"url":"https://data.inpe.br/bdc/stac/v1","collection":"mod13q1-6.1","asset":"NDVI","bbox":[-44.8,-7.5,-44.3,-7.0],"start":"2001","end":"2025","cellSize":1000,"stat":"mean","by":"year","minValid":0.5,"name":"NDVI"}' --save urucui.rgis rustgis-cli run --cmd 'cube.reduce={"url":"https://data.inpe.br/bdc/stac/v1","collection":"S2-16D-2","asset":"B04","mask":{"asset":"SCL","keep":[2,4,5,6,7]},"bbox":[-43.003,-20.838,-42.754,-20.655],"start":"2025-06-01","end":"2025-08-31","stat":"first","name":"B04 cloud-free"}' --save vicosa.rgis +rustgis-cli run --cmd 'cube.reduce={"url":"https://data.inpe.br/bdc/stac/v1","collection":"S2-16D-2","assets":["B04","B03","B02"],"mask":{"asset":"SCL","keep":[2,4,5,6,7]},"bbox":[-43.003,-20.838,-42.754,-20.655],"start":"2025-06-01","end":"2025-08-31","stat":"median","name":"RGB cloud-free"}' --save vicosa_rgb.rgis ``` ## Categorical raster area by zone From 4207af90e48fa731705ce81b982f898c871852d4 Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Sun, 22 Nov 2026 15:04:47 -0300 Subject: [PATCH 2/4] fix(cube): cube.trend's params name the assets key it refuses Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/cube.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/cube.rs b/crates/engine/src/cmd/cube.rs index 374c2e39fe..08a9928942 100644 --- a/crates/engine/src/cmd/cube.rs +++ b/crates/engine/src/cmd/cube.rs @@ -26,7 +26,7 @@ use crate::{CmdResult, CommandSpec as C, Session}; pub fn commands() -> Vec { vec![C::new("cube.trend", "Trend Analysis", "Analyze › Workflows", trend_cmd).inputs(cube_inputs).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Network).with(crate::policy::Effect::Files)).params( - r#"{"cube"?: an entry of cube.catalog (its STAC API, collection, band, cell size and cloud cap, or its Zarr store and variable) | "layers"?: [raster layers, a date each; one on another grid is resampled (nearest) onto the first's] | "layer"?: a Zarr layer (or "path" | "url", "variable", "index", "crs" as for zarr.reduce) or a raster of several bands, a date each (default: the active layer) | "collection": a STAC collection (desktop; read in place over an area, in pieces when large; with url, asset, bbox, maxCloud, cellSize and resampling below, and "start", "end"), "url"?: the collection's STAC API (as for stac.addCube), "asset"?: the collection's band, such as NDVI, "mask"?: a collection's quality band (as for cube.reduce), "bbox"?: [w, s, e, n] | "view" (the collection's area), "maxCloud"?: a collection's cloud cover cap, "cellSize"?: a collection's cell size in the files' units (the overview level nearest it is read), "resampling"?: "nearest" (default: that overview's pixels as stored) | "average" (each cell the mean of the full images' pixels in it, which reads them), "band"?: 1-based (a stack's band), "dates"?: [dates] (a stack's or the bands' dates, in their order; default: read from the layers' names or files, or the bands' names), "start"?, "end"?: dates (a whole number from 1000 to 9999 is a year; an end given as a year or a month takes all of it), "months"?: [1–12] (one season across years), "test"?: "hamedRao" (default) | "yueWang" | "seasonal" | "original", "seasons"?: parts of a year for the seasonal test (default 12), "alpha"?: 0.05 (above 0, below 0.5), "minValid"?: dates a cell needs (default: half of them, at least 4; the seasonal test also needs 4 in seasons of two or more), "per"?: "year" (default) | "decade", "name"?: text, "ran"?: (internal: a trend the app has worked out)} → four raster layers: Sen's slope, the test's Z and p-value, and the slope where p < alpha"#, + r#"{"cube"?: an entry of cube.catalog (its STAC API, collection, band, cell size and cloud cap, or its Zarr store and variable) | "layers"?: [raster layers, a date each; one on another grid is resampled (nearest) onto the first's] | "layer"?: a Zarr layer (or "path" | "url", "variable", "index", "crs" as for zarr.reduce) or a raster of several bands, a date each (default: the active layer) | "collection": a STAC collection (desktop; read in place over an area, in pieces when large; with url, asset, bbox, maxCloud, cellSize and resampling below, and "start", "end"), "url"?: the collection's STAC API (as for stac.addCube), "asset"?: the collection's band, such as NDVI ("assets", several bands, is cube.reduce's: a trend refuses it), "mask"?: a collection's quality band (as for cube.reduce), "bbox"?: [w, s, e, n] | "view" (the collection's area), "maxCloud"?: a collection's cloud cover cap, "cellSize"?: a collection's cell size in the files' units (the overview level nearest it is read), "resampling"?: "nearest" (default: that overview's pixels as stored) | "average" (each cell the mean of the full images' pixels in it, which reads them), "band"?: 1-based (a stack's band), "dates"?: [dates] (a stack's or the bands' dates, in their order; default: read from the layers' names or files, or the bands' names), "start"?, "end"?: dates (a whole number from 1000 to 9999 is a year; an end given as a year or a month takes all of it), "months"?: [1–12] (one season across years), "test"?: "hamedRao" (default) | "yueWang" | "seasonal" | "original", "seasons"?: parts of a year for the seasonal test (default 12), "alpha"?: 0.05 (above 0, below 0.5), "minValid"?: dates a cell needs (default: half of them, at least 4; the seasonal test also needs 4 in seasons of two or more), "per"?: "year" (default) | "decade", "name"?: text, "ran"?: (internal: a trend the app has worked out)} → four raster layers: Sen's slope, the test's Z and p-value, and the slope where p < alpha"#, ), C::new("cube.reduce", "Summarise a Data Cube over Time", "Analyze › Workflows", reduce_cmd).inputs(cube_inputs).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Network).with(crate::policy::Effect::Files)).params( r#"{"cube"?: an entry of cube.catalog (as for cube.trend) | "layers"?: [raster layers, a date each; one on another grid is resampled (nearest) onto the first's] | "layer"?: a Zarr layer or a raster of several bands, a date each (default: the active layer) | "path"?: a Zarr store's folder | "url"?: a Zarr store's address, or a STAC collection's API (as for stac.addCube) | "collection": a STAC collection (desktop; read in place over an area, in pieces when large; with url, asset, bbox, maxCloud, cellSize and resampling below, and "start", "end"), "variable"?, "index"?, "crs"?: a Zarr variable's (as for zarr.reduce), "asset"?: the collection's band, such as NDVI, "assets"?: [2–16 of the collection's bands, such as ["B04", "B03", "B02"]] (instead of asset, for mean, median or first: one layer a group with a band for each, drawn as RGB when three; a cell goes in at a date only with a value in every band, and median takes each cell's bands from one date, the one whose bands' sum is the middle (the lower of two); items without all of them are left out), "mask"?: {"asset": the items' quality band, such as SCL, Fmask, qa_pixel or CMASK, and one of "keep": [classes] | "drop": [classes] | "bits": {"set"?: [bits on], "unset"?: [bits off]} (bits 0–63)} (a collection's: a cell is taken at a date only where the same item's quality band lets it through, read onto the band's grid by nearest neighbour; items without it are left out), "bbox"?: [w, s, e, n] | "view" (the collection's area), "maxCloud"?: a collection's cloud cover cap, "cellSize"?: a collection's cell size in the files' units (the overview level nearest it is read), "resampling"?: "nearest" (default) | "average" (as for cube.trend), "band"?: 1-based (a stack's band), "dates"?: [dates] (a stack's or the bands' dates, in their order; default: read from the layers' names or files, or the bands' names), "stat": "mean"|"median"|"min"|"max"|"sum"|"std" (the population standard deviation, n)|"count"|"countAbove"|"first" (the value at the cell's first date with one, in "order": the best pixel)|"mode" or "majority" (a categorical cube's most frequent class; the least of those tied)|"modeCount" (how many dates had the mode)|"variety" (how many classes)|"changes" (how many times the class changed from one valued date to the next)|"longestRun" (the class of the longest run of dates in one class; the least of those tied)|"longestRunLength" (how many dates that run lasted)|"frequency" (a layer for each class met: its count of dates)|"countIn" (how many dates in the classes given), "order"?: first's order of the dates: "clear" (the default with a mask: by the share of the area the mask lets through, the clearest first) | "date" (the default without one: the earliest first) | "-date" (the latest first), "above"?: number (countAbove's threshold), "classes"?: [whole numbers 0–255, at most 256] (countIn's classes), "by"?: "all" (default: one layer) | "year" (a layer for each calendar year) | "month" (a layer for each month of the year, across years), "start"?, "end"?: dates (as for cube.trend), "months"?: [1–12] (a season across years), "minValid"?: 0–1 (a cell with a smaller share of its group's dates is left empty; default 0), "name"?: text} → raster layers of the statistic, one for each group (frequency: one for each class of each group)"#, From 1eeefb2120aba49c16dca725056d86025217de7a Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Sun, 22 Nov 2026 16:47:53 -0300 Subject: [PATCH 3/4] fix(cube): review round 1 for several bands (#2585 part 2) - A catalog entry's band gives way to "assets" (with_entry), an explicit asset alongside them still refused. - Items without the first band are said with those lacking the others. - A band with no values is an error, not a shifted layer. - cube_rgb gated off wasm32 like cube_mask; the test checks the RGB hint and both kinds of item left out. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/cube.rs | 6 +++++- crates/engine/src/cmd/cube_catalog.rs | 5 ++++- crates/engine/src/cmd/stac.rs | 2 ++ crates/engine/src/tests.rs | 1 + crates/engine/src/tests/cube_rgb.rs | 25 +++++++++++++++++++++---- 5 files changed, 33 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/cube.rs b/crates/engine/src/cmd/cube.rs index 08a9928942..05540f9458 100644 --- a/crates/engine/src/cmd/cube.rs +++ b/crates/engine/src/cmd/cube.rs @@ -1933,7 +1933,11 @@ impl ReduceRun { .groups .iter() .map(|(name, _)| { - let columns: Vec> = slots.by_ref().take(nb).filter_map(|c| c.into_iter().next().map(|(_, b)| b)).collect(); + let columns: Vec> = slots + .by_ref() + .take(nb) + .map(|c| c.into_iter().next().map(|(_, b)| b).ok_or_else(|| format!("{name}: a band came out with no values"))) + .collect::>()?; let hint = if nb == 3 { raster::ColorHint::Rgb { alpha: false } } else { raster::ColorHint::Gray }; let mut r = Raster::new(name.clone(), grid.width, height, columns, grid.transform, grid.crs, None, hint, "Float32") .map_err(|e| e.to_string())?; diff --git a/crates/engine/src/cmd/cube_catalog.rs b/crates/engine/src/cmd/cube_catalog.rs index 87103e0863..52de1a5682 100644 --- a/crates/engine/src/cmd/cube_catalog.rs +++ b/crates/engine/src/cmd/cube_catalog.rs @@ -219,7 +219,10 @@ pub fn with_entry(p: &Value) -> Result, String> { match &e.source { Source::Stac { collection, asset } => { o.insert("collection".into(), json!(collection)); - o.insert("asset".into(), json!(asset)); + // Its band, unless the call reads several of the collection's own ("assets"). + if p.get("assets").is_none_or(Value::is_null) { + o.insert("asset".into(), json!(asset)); + } for (k, v) in [("cellSize", e.cell_size), ("maxCloud", e.max_cloud)] { if let Some(v) = v.filter(|_| o.get(k).is_none_or(Value::is_null)) { o.insert(k.into(), json!(v)); diff --git a/crates/engine/src/cmd/stac.rs b/crates/engine/src/cmd/stac.rs index 188c147088..389f254744 100644 --- a/crates/engine/src/cmd/stac.rs +++ b/crates/engine/src/cmd/stac.rs @@ -607,6 +607,8 @@ pub fn cube_files(s: &mut Session, p: &Value, max_items: usize, mask: Option<&st continue; }; let Some(a) = i.assets.iter().find(|a| a.key.eq_ignore_ascii_case(asset)) else { + // With several bands asked for, said with the items lacking one of the others. + lacking += usize::from(!others.is_empty()); without += 1; continue; }; diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 09d3d38c46..4051d28f1c 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -19,6 +19,7 @@ mod cancellation; #[cfg(not(target_arch = "wasm32"))] #[path = "tests/cube_mask.rs"] mod cube_mask; +#[cfg(not(target_arch = "wasm32"))] #[path = "tests/cube_rgb.rs"] mod cube_rgb; diff --git a/crates/engine/src/tests/cube_rgb.rs b/crates/engine/src/tests/cube_rgb.rs index 7f68f9d4b6..dec7ec8831 100644 --- a/crates/engine/src/tests/cube_rgb.rs +++ b/crates/engine/src/tests/cube_rgb.rs @@ -18,7 +18,8 @@ const RGB: [[f32; 3]; 3] = [[10.0, 50.0, 30.0], [20.0, 10.0, 70.0], [30.0, 40.0, /// Three dates of B04, B03 and B02 (and B05 at half their cells) with an SCL-like mask (4 clear, /// 9 cloud): the first cloudy in column 0, the second clear everywhere, the third cloudy in -/// column 7. The second's B02 has no value at (3, 3). A fourth item has no B02 and is left out. +/// column 7. The second's B02 has no value at (3, 3). A fourth item has only B04 and a fifth no +/// B04: both are left out. fn collection() -> String { let flat = |v: f32| cog(vec![v; 64], 8, None); let mask = |cloudy: Option| cog((0..64).map(|c| if Some(c % 8) == cloudy { 9.0 } else { 4.0 }).collect(), 8, None); @@ -37,12 +38,19 @@ fn collection() -> String { } files.push(("/B04_3.tif".into(), flat(99.0))); files.push(("/m3.tif".into(), mask(None))); + files.push(("/B03_4.tif".into(), flat(99.0))); + files.push(("/B02_4.tif".into(), flat(99.0))); + files.push(("/m4.tif".into(), mask(None))); let (files, _) = serve_ranged_files(files); - let features: Vec = ["2024-01-01", "2024-01-17", "2024-02-02", "2024-02-18"] + let features: Vec = ["2024-01-01", "2024-01-17", "2024-02-02", "2024-02-18", "2024-02-20"] .iter() .enumerate() .map(|(k, d)| { - let keys: &[&str] = if k < 3 { &["B04", "B03", "B02", "B05"] } else { &["B04"] }; + let keys: &[&str] = match k { + 0..3 => &["B04", "B03", "B02", "B05"], + 3 => &["B04"], + _ => &["B03", "B02"], + }; let mut assets: Vec = keys.iter().map(|a| format!(r#""{a}": {{"href": "{files}/{a}_{k}.tif"}}"#)).collect(); assets.push(format!(r#""SCL": {{"href": "{files}/m{k}.tif"}}"#)); format!( @@ -79,6 +87,8 @@ fn several_bands_summarised_as_one_rgb_layer() { let names: Vec<&str> = raster.bands.iter().map(|b| b.name.as_str()).collect(); let assets: Vec<&str> = p["assets"].as_array().unwrap().iter().map(|a| a.as_str().unwrap()).collect(); assert_eq!(names, assets); + // Three bands are drawn as RGB, other counts not. + assert_eq!(matches!(raster.color, rustgis_data::raster::ColorHint::Rgb { alpha: false }), assets.len() == 3, "{p}"); let said = s.notices_since(mark).iter().map(|n| n.text.clone()).collect(); (raster.bands.iter().map(|b| b.data.clone()).collect(), said) }; @@ -105,7 +115,7 @@ fn several_bands_summarised_as_one_rgb_layer() { }; check(&median, &middle, "median"); assert_eq!(median[0][9], 10.0, "three dates: date 0's, not the band's own middle (20)"); - assert!(said.iter().any(|t| t.contains("1 item(s) left out") && t.contains("B04, B03, B02")), "{said:?}"); + assert!(said.iter().any(|t| t.contains("2 item(s) left out") && t.contains("B04, B03, B02")), "{said:?}"); assert!(said.iter().any(|t| t.contains("1 cell(s) had a value in some of the bands")), "{said:?}"); // First, the clearest date first (the second, then the first and third, tied, by date). let (first, _) = reduce(&mut s, &with(json!({"stat": "first"}))); @@ -136,6 +146,13 @@ fn several_bands_summarised_as_one_rgb_layer() { } let e = s.run("cube.trend", &with(json!({}))).unwrap_err(); assert!(e.contains("of one band"), "{e}"); + // A catalog entry's band gives way to the bands asked for; one asked for alongside it doesn't. + let entry = json!({"cube": "bdc-s2-16d-ndvi", "assets": ["B04", "B03"]}); + let q = crate::cmd::cube_catalog::with_entry(&entry).unwrap(); + assert_eq!((q["collection"].as_str(), q.get("asset")), (Some("S2-16D-2"), None)); + let e = + crate::cmd::cube_catalog::with_entry(&json!({"cube": "bdc-s2-16d-ndvi", "asset": "B04", "assets": ["B04", "B03"]})).unwrap_err(); + assert!(e.contains("leave out asset"), "{e}"); } /// A stack of layers has no assets to read together: refused. From 6d22d4ade9362052db3a220e685a939e3052dc6d Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Thu, 26 Nov 2026 19:38:04 -0300 Subject: [PATCH 4/4] fix(cube): an averaged cell's bands are the mean of the same pixels (#2585 part 2) With "resampling": "average", each band summed its own valid pixels, so a cell could average B04's pixels beside B03's other pixels when their nodata differ. An item's bands are now read before any pixel goes in, and a pixel goes in only with a value in every band; one with a value in only some is left out and counted in the notice, now of pixels. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/stac.rs | 85 +++++++++++++++-------------- crates/engine/src/tests/cube_rgb.rs | 39 ++++++++++++- docs/user-guide/analysis.md | 5 +- 3 files changed, 85 insertions(+), 44 deletions(-) diff --git a/crates/engine/src/cmd/stac.rs b/crates/engine/src/cmd/stac.rs index 3e74b13b67..c0a163b4fe 100644 --- a/crates/engine/src/cmd/stac.rs +++ b/crates/engine/src/cmd/stac.rs @@ -811,8 +811,8 @@ pub struct StacCube { files: Vec, Option, Vec)>>, /// The bands asked for, when several (`"assets"`): a slice holds one band for each. assets: Vec, - /// Cells with a value in some of the bands but not all at a date, left out of it (so each - /// cell's bands are of one date): said once the run has read its slices. + /// Pixels with a value in some of the bands but not all at a date, left out of it (so each + /// cell's bands are the mean of the same pixels): said once the run has read its slices. partial: std::sync::atomic::AtomicU64, /// The quality values that let a cell through, for a cube masked by its items' quality band. mask: Option, @@ -1212,7 +1212,7 @@ impl super::cube::TimeCube for StacCube { &self.assets } /// Band pixels their item's mask file doesn't cover: left out as not clear, and said with - /// their count and the first such mask; and cells left out at a date for a value in only some + /// their count and the first such mask; and pixels left out at a date for a value in only some /// of the bands asked for. fn lost(&self) -> Vec { // Pixels with a value left out as not clear: a value lost. @@ -1234,7 +1234,7 @@ impl super::cube::TimeCube for StacCube { said.push(rustgis_data::loss::Note::loss( rustgis_data::loss::LossCode::DroppedValue, format!( - "{}: {partial} cell(s) had a value in some of the bands {} but not all at a date, so they were left out at that date (each cell's bands are of one date)", + "{}: {partial} pixel(s) had a value in some of the bands {} but not all at a date, so they were left out at that date (each cell's bands are of the same pixels)", self.label, self.assets.join(", ") ), @@ -1370,11 +1370,16 @@ impl super::cube::TimeCube for StacCube { (Some(_), None) => return Err(crate::sources::message_with_address(href, "has no quality band to mask its cells by")), _ => None, }; - // The band pixels with a value that the mask file doesn't cover (the first band's). + // The item's pixels with a value that the mask file doesn't cover, and those with a value + // in only some of the bands asked for. let mut outside = 0u64; let across = (fc1 - fc0) as usize; + let mut partial = 0u64; let bands = std::iter::once((href, scale, fill)).chain(more.iter().map(|(h, s, f)| (h, s, f))); - for (b, ((bh, (k, o), fill), (sum, count))) in bands.zip(sums.iter_mut().zip(&mut counts)).enumerate() { + // Every band's window is read before any pixel goes in, so a cell's bands are the mean of + // the same pixels: one with a value in only some of them goes in none (said). + let mut reads: Vec<(Vec, Vec, (f64, f64))> = Vec::with_capacity(nb); + for (b, (bh, (k, o), fill)) in bands.enumerate() { let fill: Vec = fill.iter().map(|v| *v as f32).collect(); // The item's other bands are read on its first band's pixels, the same window. let read = if b == 0 { @@ -1393,31 +1398,43 @@ impl super::cube::TimeCube for StacCube { } cog::read_values_blocking(&bi, bh, self.level, 0, cols, rows)? }; - for (r, line) in read.chunks(across).enumerate() { - let row = ((fr0 - dy - top_f) as usize + r) / f as usize; - for (c, v) in line.iter().enumerate() { - let col = ((fc0 - dx) as usize + c) / f as usize; - let cell = row * w as usize + col; - if !v.is_finite() || fill.contains(v) { - continue; - } - let clear = match &keep { - None => true, - Some(kept) => match kept.get(r * across + c).copied().flatten() { - Some(clear) => clear, - None => { - outside += u64::from(b == 0); - false - } - }, - }; - if clear && let (Some(s), Some(n)) = (sum.get_mut(cell), count.get_mut(cell)) { - *s += f64::from(*v) * k + o; - *n += 1; + reads.push((read, fill, (*k, *o))); + } + let pixels = reads.iter().map(|(r, ..)| r.len()).min().unwrap_or(0); + for i in 0..pixels { + let valued = reads.iter().filter(|(read, fill, _)| read[i].is_finite() && !fill.contains(&read[i])).count(); + if valued == 0 { + continue; + } + let clear = match &keep { + None => true, + Some(kept) => match kept.get(i).copied().flatten() { + Some(clear) => clear, + None => { + outside += 1; + false } + }, + }; + if !clear { + continue; + } + if valued < reads.len() { + partial += 1; + continue; + } + let (r, c) = (i / across, i % across); + let row = ((fr0 - dy - top_f) as usize + r) / f as usize; + let col = ((fc0 - dx) as usize + c) / f as usize; + let cell = row * w as usize + col; + for ((read, _, (k, o)), (sum, count)) in reads.iter().zip(sums.iter_mut().zip(&mut counts)) { + if let (Some(s), Some(n)) = (sum.get_mut(cell), count.get_mut(cell)) { + *s += f64::from(read[i]) * k + o; + *n += 1; } } } + self.partial.fetch_add(partial, std::sync::atomic::Ordering::Relaxed); if outside > 0 && let (Ok(mut u), Some((m, _))) = (self.uncovered.lock(), mask) { @@ -1425,23 +1442,11 @@ impl super::cube::TimeCube for StacCube { u.1.get_or_insert_with(|| m.clone()); } } - let mut bands: Vec> = sums + let bands: Vec> = sums .iter() .zip(&counts) .map(|(sum, count)| sum.iter().zip(count).map(|(s, n)| if *n > 0 { (s / f64::from(*n)) as f32 } else { f32::NAN }).collect()) .collect(); - // A cell's bands are of one date: one with a value in only some of them is left out (said). - if nb > 1 { - let mut partial = 0u64; - for c in 0..cells { - let valued = bands.iter().filter(|b| b.get(c).is_some_and(|v| v.is_finite())).count(); - if valued > 0 && valued < nb { - partial += 1; - bands.iter_mut().filter_map(|b| b.get_mut(c)).for_each(|v| *v = f32::NAN); - } - } - self.partial.fetch_add(partial, std::sync::atomic::Ordering::Relaxed); - } let transform = rustgis_data::raster::GeoTransform { origin_y: self.transform.origin_y + f64::from(top) * self.transform.pixel_height, ..self.transform diff --git a/crates/engine/src/tests/cube_rgb.rs b/crates/engine/src/tests/cube_rgb.rs index dec7ec8831..853a0464b2 100644 --- a/crates/engine/src/tests/cube_rgb.rs +++ b/crates/engine/src/tests/cube_rgb.rs @@ -116,7 +116,7 @@ fn several_bands_summarised_as_one_rgb_layer() { check(&median, &middle, "median"); assert_eq!(median[0][9], 10.0, "three dates: date 0's, not the band's own middle (20)"); assert!(said.iter().any(|t| t.contains("2 item(s) left out") && t.contains("B04, B03, B02")), "{said:?}"); - assert!(said.iter().any(|t| t.contains("1 cell(s) had a value in some of the bands")), "{said:?}"); + assert!(said.iter().any(|t| t.contains("1 pixel(s) had a value in some of the bands")), "{said:?}"); // First, the clearest date first (the second, then the first and third, tied, by date). let (first, _) = reduce(&mut s, &with(json!({"stat": "first"}))); check(&first, &|col, row| RGB[*[1, 0, 2].iter().find(|k| clear(col, row).contains(k)).unwrap()], "first, clearest"); @@ -131,7 +131,7 @@ fn several_bands_summarised_as_one_rgb_layer() { check(&mean, &average, "mean"); // Two bands without the missing value: nothing left out, nothing said of it. let (_, said) = reduce(&mut s, &with(json!({"stat": "median", "assets": ["B04", "B03"]}))); - assert!(!said.iter().any(|t| t.contains("cell(s) had a value")), "{said:?}"); + assert!(!said.iter().any(|t| t.contains("pixel(s) had a value")), "{said:?}"); // What can't be asked. for (bad, why) in [ (json!({"stat": "max"}), "assets takes mean, median or first"), @@ -162,3 +162,38 @@ fn assets_are_a_collections() { let e = s.run("cube.reduce", &json!({"layers": ["a", "b"], "assets": ["B04", "B03"], "stat": "median"})).unwrap_err(); assert!(e.contains("STAC collection's bands"), "{e}"); } + +/// Averaged cells (`"resampling": "average"`) take each pixel with all its bands or not at all: +/// in the bottom half B04 has a value only in even columns and B03 only in odd ones, so no pixel +/// there has both and its cells are left out (said), not B04's even pixels' mean beside B03's +/// odd pixels' (#2712 review). +#[test] +fn an_averaged_cell_takes_its_bands_from_the_same_pixels() { + let n = 1024u32; + let band = |v: f32, even: bool| { + cog((0..n * n).map(|c| if c / n < n / 2 || (c % n).is_multiple_of(2) == even { v } else { -1.0 }).collect(), n, Some(-1.0)) + }; + let (files, _) = serve_ranged_files(vec![("/B04.tif".into(), band(10.0, true)), ("/B03.tif".into(), band(20.0, false))]); + let search = format!( + r#"{{"type": "FeatureCollection", "features": [{{"type": "Feature", "id": "s0", "collection": "s2", "bbox": [10, 45, 11, 46], + "geometry": null, "properties": {{"datetime": "2024-01-01T00:00:00Z"}}, + "assets": {{"B04": {{"href": "{files}/B04.tif"}}, "B03": {{"href": "{files}/B03.tif"}}}}}}]}}"# + ); + let api = format!("{}/v1", serve_routes(vec![("/v1/search", search)], 64)); + let mut s = Session::new(Project::default()); + let mark = s.notice_mark(); + let p = json!({"url": api, "collection": "s2", "assets": ["B04", "B03"], "bbox": [10, 45, 11, 46], "start": "2024-01-01", + "end": "2024-01-31", "stat": "first", "cellSize": 2.0 / f64::from(n), "resampling": "average"}); + let r = s.run("cube.reduce", &p).unwrap_or_else(|e| panic!("{e}")); + let l = s.map().layer(r["layers"][0].as_u64().unwrap() as u32).unwrap(); + let raster = l.raster.as_ref().unwrap().data.clone().unwrap(); + let half = n as usize / 2; + assert_eq!((raster.width, raster.height), (half as u32, half as u32)); + let said: Vec = s.notices_since(mark).iter().map(|n| n.text.clone()).collect(); + for (j, want) in [10.0f32, 20.0].into_iter().enumerate() { + let b = &raster.bands[j].data; + assert!(b[..half * half / 2].iter().all(|v| (v - want).abs() < 1e-3), "band {j}, top half"); + assert!(b[half * half / 2..].iter().all(|v| v.is_nan()), "band {j}, bottom half: {:?} ({said:?})", &b[half * half / 2..][..4]); + } + assert!(said.iter().any(|t| t.contains("had a value in some of the bands")), "{said:?}"); +} diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index f7d8598b4d..1502d4dbee 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -2286,8 +2286,9 @@ is the data cube summary's only. - **Several bands:** `"assets": ["B04", "B03", "B02"]` (instead of `"asset"`) reads 2 to 16 of a collection's bands from the same items and makes one layer of a band for each, drawn as RGB when there are three. It takes **mean**, **median** and **first**, which keep each cell's bands - together: a cell goes in at a date only with a value in every band (one with a value in only - some is left out at that date, and said with how many), so first takes all its bands from the + together: a pixel goes in at a date only with a value in every band (one with a value in only + some is left out at that date, and said with how many), so an averaged cell's bands are the mean + of the same pixels, first takes all its bands from the same date, and median takes them from one date too, the one whose bands' sum is the middle (the lower of the two middle ones for an even count), not each band's own middle, which can mix dates into a colour no date had. The bands have to be on one grid of pixels (one cell size); a