diff --git a/crates/engine/src/cmd/cube.rs b/crates/engine/src/cmd/cube.rs index 8f6982c18a..83b46ece2d 100644 --- a/crates/engine/src/cmd/cube.rs +++ b/crates/engine/src/cmd/cube.rs @@ -26,10 +26,10 @@ 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 ("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"#, + 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; a GeoTIFF in strips without one near it takes it with "resampling": "average"), "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, first or firstDate: one layer a group with a band for each, drawn as RGB when three (firstDate: one band, the date all of them were taken at); 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)|"firstDate" (the date of the value first takes, as days since 1970-01-01, its legend the dates)|"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 and firstDate'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, first or firstDate: one layer a group with a band for each, drawn as RGB when three (firstDate: one band, the date all of them were taken at); 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; a GeoTIFF in strips without one near it takes it with "resampling": "average"), "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)|"firstDate" (the date of the value first takes, as days since 1970-01-01, its legend the dates)|"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 and firstDate'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)"#, )] } diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 844744fc1d..02e4f06e21 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -51,7 +51,7 @@ pub fn commands() -> Vec { .params(r#"{"layer"?: name|id, "crs": "EPSG:… or WKT; reinterpret native coordinates, without rewriting the source file"}"#), C::new("layer.loadAll", "Load All Features", "Layers", load_all).roles(&[]).effects(crate::policy::Effects::NONE).when(need_streamed).params(r#"{"layer"?: name|id}"#), C::new("layer.addUrl", "Add Data From URL", "Home › Add › Add Data", add_url).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Network)).params( - r#"{"url": "https://…/data.geojson|.csv|.parquet|.fgb|.gpkg|.zip|.shp (its .dbf fetched beside it, and its .shx, .prj and .cpg when there)|.kml|.kmz|.gpx|.tif|.grb|.grib|.grb2|.grib2 (GRIB)|.jp2 (JPEG 2000: desktop, through GDAL) (the format from the address, else the contents) | a .pmtiles archive", "bytes"?: "[first, last]: only these octets of a GRIB file (counted from 0, both included, as HTTP's Range and curl -r write them; at most 64 MB), read as the file (desktop and command line): a record found in its wgrib inventory; with bbox (desktop and command line), only the rows of the box are downloaded from a record of simple packing without a bitmap, and any other record is downloaded whole and cut to the box, with a notice", "format"?: "grib: with bytes, the address is a GRIB file whatever its name says", "name"?: text, "layer"?: "one layer of a zip, KML or GPX", "zoom"?: "bool: true frames everything added; false keeps the view, even on an empty map; omitted, the first content on an empty map is framed (a GeoParquet, FlatGeobuf or cloud-optimised GeoTIFF read in place likewise; a PMTiles or MBTiles archive ignores zoom and is framed on its bounds unless it covers the whole world)", "x"?, "y"?, "wkt"?, "crs"?, "delimiter"?, "paperSpace"?, "blocks"?, "stream"?, "as"? (as layer.addData), "whole"?: "bool: download a cloud-optimised GeoTIFF whole (as a raster layer) instead of reading it in place (an address without a file name is read in place when its first bytes are a cloud-optimised GeoTIFF)", "cog"?: "bool: the address is a cloud-optimised GeoTIFF whatever its name says (the app's probe found it so)", "bbox"?: "[west, south, east, north] in degrees | "view": a cloud-optimised GeoTIFF's window as a raster layer (desktop and command line), read by range at full resolution, in the file's coordinate system, with its colour table and class names; at most 64 million values (all bands); with bytes, the cells of a GRIB record the box touches", "cellSize"?: "with bbox: the coarsest overview whose cells are at most this size is read (the file's units; metres for longitude/latitude, a degree taken as 111.32 km); a GeoTIFF in strips, which has no overviews, takes one strip and column in as many as that size holds", "cube"?: "bool: a data cube's file: a tile layer that follows the time slider (stac.addCube adds them), kept one when the project opens again", "start"?, "end"?, "unit"?, "interval"?, "dates"?: "a GeoTIFF address with date placeholders ({date:YYYY}, {YYYY}{MM}{DD}), one file per date: the dates it spans and steps through (as time.set), turning the time slider on", "connection"?: "the id of the saved web-service connection it comes from (as service.add)", "service"?: "bool: a web service's features (an ArcGIS query, OGC API Features items): read in pages as service.add reads them, known by the address as its layers are, and an ArcGIS layer drawn as its description says", "bounds"?: "with service: [west, south, east, north], the layer's longitude/latitude bounds its axes are checked against", "from"?: "the web document address that named url (internal: enforces public-address reach)", "fromDocument"?: bool, "anonymous"?: bool (internal: a plugin-origin download must never adopt a saved login), "coverage"?: bool (a WCS coverage's GetCoverage address, service.coverage's: a GeoTIFF, else the service's error; one that doesn't say its system is read in the one the address asks for), "coverageCrs"?: "EPSG: (with coverage: the system it was asked in, service.coverage's coverageCrs, when the address doesn't say it)", "request"?: "number (internal: the download a plugin command left to the app, #1202)"}"#, + r#"{"url": "https://…/data.geojson|.csv|.parquet|.fgb|.gpkg|.zip|.shp (its .dbf fetched beside it, and its .shx, .prj and .cpg when there)|.kml|.kmz|.gpx|.tif|.grb|.grib|.grb2|.grib2 (GRIB)|.jp2 (JPEG 2000: desktop, through GDAL) (the format from the address, else the contents) | a .pmtiles archive", "bytes"?: "[first, last]: only these octets of a GRIB file (counted from 0, both included, as HTTP's Range and curl -r write them; at most 64 MB), read as the file (desktop and command line): a record found in its wgrib inventory; with bbox (desktop and command line), only the rows of the box are downloaded from a record of simple packing without a bitmap, and any other record is downloaded whole and cut to the box, with a notice", "format"?: "grib: with bytes, the address is a GRIB file whatever its name says", "name"?: text, "layer"?: "one layer of a zip, KML or GPX", "zoom"?: "bool: true frames everything added; false keeps the view, even on an empty map; omitted, the first content on an empty map is framed (a GeoParquet, FlatGeobuf or cloud-optimised GeoTIFF read in place likewise; a PMTiles or MBTiles archive ignores zoom and is framed on its bounds unless it covers the whole world)", "x"?, "y"?, "wkt"?, "crs"?, "delimiter"?, "paperSpace"?, "blocks"?, "stream"?, "as"? (as layer.addData), "whole"?: "bool: download a cloud-optimised GeoTIFF whole (as a raster layer) instead of reading it in place (an address without a file name is read in place when its first bytes are a cloud-optimised GeoTIFF)", "cog"?: "bool: the address is a cloud-optimised GeoTIFF whatever its name says (the app's probe found it so)", "bbox"?: "[west, south, east, north] in degrees | "view": a cloud-optimised GeoTIFF's window as a raster layer (desktop and command line), read by range at full resolution, in the file's coordinate system, with its colour table and class names; at most 64 million values (all bands); with bytes, the cells of a GRIB record the box touches", "cellSize"?: "with bbox: the coarsest overview whose cells are at most this size is read (the file's units; metres for longitude/latitude, a degree taken as 111.32 km); a GeoTIFF in strips, its overviews in strips too when it has some, then takes one strip and column in as many as that size holds on that level", "cube"?: "bool: a data cube's file: a tile layer that follows the time slider (stac.addCube adds them), kept one when the project opens again", "start"?, "end"?, "unit"?, "interval"?, "dates"?: "a GeoTIFF address with date placeholders ({date:YYYY}, {YYYY}{MM}{DD}), one file per date: the dates it spans and steps through (as time.set), turning the time slider on", "connection"?: "the id of the saved web-service connection it comes from (as service.add)", "service"?: "bool: a web service's features (an ArcGIS query, OGC API Features items): read in pages as service.add reads them, known by the address as its layers are, and an ArcGIS layer drawn as its description says", "bounds"?: "with service: [west, south, east, north], the layer's longitude/latitude bounds its axes are checked against", "from"?: "the web document address that named url (internal: enforces public-address reach)", "fromDocument"?: bool, "anonymous"?: bool (internal: a plugin-origin download must never adopt a saved login), "coverage"?: bool (a WCS coverage's GetCoverage address, service.coverage's: a GeoTIFF, else the service's error; one that doesn't say its system is read in the one the address asks for), "coverageCrs"?: "EPSG: (with coverage: the system it was asked in, service.coverage's coverageCrs, when the address doesn't say it)", "request"?: "number (internal: the download a plugin command left to the app, #1202)"}"#, ), C::new("layer.addDownload", "Add Downloaded Data", "Home › Add", add_download).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Reserved).with(crate::policy::Effect::Files)) .params(r#"{"id": a download the app finished (Home › Add › Add Data › From URL), "url": its address, "name"?: text, "layer"?: text, "zoom"?: bool, "x"?, "y"?, "wkt"?, "crs"?, "delimiter"?, "paperSpace"?, "blocks"?, "stream"?, "as"? (as layer.addData), "service"?: bool (a service's features: their axes (when they came as GeoJSON) and paging are checked, and the address is kept as the layer's source), "bounds"?: [west, south, east, north] (with service: the layer's longitude/latitude bounds from its capabilities, which its axes are checked against; without bounds they are left as they come; ignored without service), "coverage"?: bool (a WCS coverage: a GeoTIFF, else the service's error, and its request kept as the layer's source), "coverageCrs"?: "EPSG:" (internal, with coverage: the system service.coverage's request asks it in (its coverageCrs), for an answer that doesn't say its own, when the address doesn't say it), "drawingInfo"?: object (internal, with service: an ArcGIS layer's drawingInfo from its description, which the layer is drawn with), "geolibreProject"?: bool (internal: downloaded project JSON), "geolibreLayer"?: {"token", "record"} (internal: reserved imported layer and its saved style), "geolibreZarr"?: bool (internal: an imported Zarr slice as GeoTIFF), "connection"?: "as layer.addUrl", "anonymous"?: bool (internal: preserves a plugin-origin download's anonymous reads), "request"?: number (internal: the download a plugin command left to the app, #1202), "window"?: {"bbox", "cellSize"?, "cog"?} (internal: what a cloud-optimised GeoTIFF's window the app read off the frame asked for, for a task to read it again, #1330)}"#), @@ -6742,8 +6742,9 @@ pub(crate) fn read_window_raster(asked: &WindowAsked, stop: &std::sync::atomic:: if c1 <= c0 || r1 <= r0 { return Err(named("the box is outside the file".into())); } - // A file in strips has no overviews to read coarser cells from: a cellSize coarser than the - // level's cells takes every n-th strip and column instead, as GDAL does (#2592). + // A file in strips takes a cellSize coarser than the level read's cells by stepping over its + // strips and columns on that level, as GDAL does (its overviews, when it has some, are chosen + // as a tiled file's are; #2592). let step = match cell { Some(c) if layout.strips => (c * (1.0 + 1e-9) / size_of(lv)).floor().clamp(1.0, f64::from(u32::MAX)) as u32, _ => 1, diff --git a/crates/engine/src/cmd/stac.rs b/crates/engine/src/cmd/stac.rs index b144bd09e6..ded3c22717 100644 --- a/crates/engine/src/cmd/stac.rs +++ b/crates/engine/src/cmd/stac.rs @@ -950,7 +950,7 @@ pub fn stac_cube(s: &mut Session, p: &Value) -> Result { } // The first file's header gives the coordinate system, the grid and its overviews. let first = by_day.values().flatten().next().map(|(h, ..)| h.clone()).ok_or("no file to read")?; - let info = cog::info_blocking(&first)?; + let info = values_header(&first)?; let layout = &info.layout; if layout.transform.pixel_height > 0.0 { return Err(crate::sources::message_with_address(&first, "stored bottom up, which a trend doesn't read yet")); @@ -959,9 +959,30 @@ pub fn stac_cube(s: &mut Session, p: &Value) -> Result { // overview, not its 463 m one); the full images by default. let level = size.map_or(0, |size| level_near(layout, size)); let lv = layout.levels.get(level).ok_or("the file has no image")?; - let lt = layout.transform_of(lv); + let mut lt = layout.transform_of(lv); let full = layout.levels.first().ok_or("the file has no image")?; - let (read, factor) = if average && level > 0 { + // A file in strips with no overview near the size (#2592): its full image's blocks of `f` × + // `f` pixels are the cells, averaged; nearest would read every pixel to keep one in each, so + // it is refused, saying what to take. + let blocks = size.map(|size| (size / lt.pixel_width.abs()).round()).filter(|f| layout.strips && level == 0 && *f >= 2.0); + if let Some(f) = blocks { + if !average { + return Err(crate::sources::message_with_address( + &first, + "a GeoTIFF in strips with no overview near that cellSize: take \"resampling\": \"average\" (each cell the mean of its pixels)", + )); + } + if f > 64.0 { + return Err(crate::sources::message_with_address( + &first, + &format!("a cellSize of {f} of its cells; averaging takes 64 at most"), + )); + } + lt = rustgis_data::raster::GeoTransform { pixel_width: lt.pixel_width * f, pixel_height: lt.pixel_height * f, ..lt }; + } + let (read, factor) = if let Some(f) = blocks { + (0, f as u32) + } else if average && level > 0 { let f = (f64::from(full.width) / f64::from(lv.width.max(1))).round(); // Averaging takes `f` × `f` full pixels a cell: the overview has to be exactly the full // image's size divided by `f` (rounded up), or its cells aren't those blocks. @@ -1030,7 +1051,7 @@ pub fn stac_cube(s: &mut Session, p: &Value) -> Result { let mut probed = 0; while !covered && probed < COVER_PROBES { let Some(h) = others.next() else { break }; - covered = covers(&*cog::info_blocking(h)?); + covered = covers(&*values_header(h)?); probed += 1; } // Tiles beyond the probes are left to the reading, which leaves what none covers empty. @@ -1139,6 +1160,14 @@ fn mask_values( Ok(values) } +/// A file's header for reading its values (a cube's windows, its range's sample): a GeoTIFF in +/// strips too, whose windows are read strip by strip (#2592). Cached per address, as +/// [`info_blocking`](crate::render::rustgis_tiles::cog::info_blocking) caches it. +#[cfg(not(target_arch = "wasm32"))] +fn values_header(href: &str) -> Result, String> { + crate::render::rustgis_tiles::cog::window_info_until(href, &std::sync::atomic::AtomicBool::new(false)) +} + /// The level of a file whose pixels are nearest `size` across, by ratio. #[cfg(not(target_arch = "wasm32"))] fn level_near(layout: &rustgis_data::raster::cog::Layout, size: f64) -> usize { @@ -1159,8 +1188,7 @@ impl StacCube { rows: (u32, u32), ) -> Result { use super::cube_mask::nearest; - use crate::render::rustgis_tiles::cog; - let info = cog::info_blocking(href)?; + let info = values_header(href)?; if info.layout.crs != self.crs { return Err(crate::sources::message_with_address(href, "a mask in another coordinate system than its band")); } @@ -1280,7 +1308,6 @@ impl super::cube::TimeCube for StacCube { /// as not clear. fn clear_share(&self, i: usize, cancel: &std::sync::atomic::AtomicBool) -> Result, String> { use super::cube_mask::{nearest, span}; - use crate::render::rustgis_tiles::cog; use std::sync::atomic::Ordering::Relaxed; let Some(test) = &self.mask else { return Ok(None) }; let files = self.files.get(i).ok_or_else(|| format!("no date {i}"))?; @@ -1294,7 +1321,7 @@ impl super::cube::TimeCube for StacCube { let (sx, sy) = ((x1 - x0) / f64::from(gw), (y1 - y0).abs() / f64::from(gh)); let mut clear = vec![false; gw as usize * gh as usize]; for (href, stored) in files.iter().filter_map(|f| f.3.as_ref()) { - let info = cog::info_blocking(href)?; + let info = values_header(href)?; if info.layout.crs != self.crs { return Err(crate::sources::message_with_address(href, "a mask in another coordinate system than its band")); } @@ -1390,7 +1417,7 @@ impl StacCube { 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)?; + let info = values_header(href)?; if info.layout.crs != self.crs { return Err(crate::sources::message_with_address(href, "in another coordinate system than the first file")); } @@ -1402,9 +1429,11 @@ impl StacCube { let lt = info.layout.transform_of(lv); let (dx, dy) = offset_in(&grid, <) .ok_or_else(|| crate::sources::message_with_address(href, "on another grid of pixels than the first file"))?; - // Averaged, a cell is a block of `f` × `f` of the file's pixels: the file's corner - // has to fall on a block's, or the blocks would straddle cells. - if dx.rem_euclid(i64::from(f)) != 0 || dy.rem_euclid(i64::from(f)) != 0 { + // Averaged, a cell is a block of `f` × `f` of the file's pixels: a tiled file's corner + // has to fall on a block's, or the blocks would straddle cells ("nearest" reads its + // overview instead). A file in strips has none to take (#2592): a block its corner + // cuts takes its pixels from the files on both sides, each counted in the cell's mean. + if !info.layout.strips && (dx.rem_euclid(i64::from(f)) != 0 || dy.rem_euclid(i64::from(f)) != 0) { return Err(crate::sources::message_with_address( href, "its pixels don't fall in whole cells of the area: take \"resampling\": \"nearest\"", @@ -1475,7 +1504,7 @@ impl StacCube { let read = if b == 0 { cog::read_values_blocking(&info, href, self.level, 0, cols, rows)? } else { - let bi = cog::info_blocking(bh)?; + let bi = values_header(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)) @@ -1897,7 +1926,7 @@ fn sample_range( let picked: Vec<&String> = (0..n.min(SAMPLE_FILES)).filter_map(|i| newest.get(i * n / n.min(SAMPLE_FILES))).copied().collect(); let mut values = Vec::new(); for href in picked { - let info = cog::info_blocking(href)?; + let info = values_header(href)?; let l = &info.layout; if l.palette.is_some() { return Ok(Sample::Classes); diff --git a/crates/engine/src/cmd/stac_bands.rs b/crates/engine/src/cmd/stac_bands.rs index 97bce98d47..71fe9c2814 100644 --- a/crates/engine/src/cmd/stac_bands.rs +++ b/crates/engine/src/cmd/stac_bands.rs @@ -17,10 +17,10 @@ use crate::{CmdResult, CommandSpec as C, Session}; pub fn commands() -> Vec { vec![C::new("stac.addBands", "Add STAC Bands", "Home › Add › Web Data › STAC Search", add_bands).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Network)).params( - r#"{"item": a STAC item (from stac.search), "combination"?: "trueColor"|"colorInfrared"|"shortwaveInfrared"|"falseColorUrban"|"agriculture"|"geology"|"bathymetric" (default trueColor), "red"?, "green"?, "blue"?: band names (red, nir, swir16… or an asset's key) used instead of a combination, "bbox"?: [west, south, east, north] in degrees | "view" (default), "cellSize"?: the coarsest overview whose cells are at most this size is read (default: about 2,048 cells across the box), "name"?: text, "ran"?: (internal: a raster the app has worked out)}"#, + r#"{"item": a STAC item (from stac.search), "combination"?: "trueColor"|"colorInfrared"|"shortwaveInfrared"|"falseColorUrban"|"agriculture"|"geology"|"bathymetric" (default trueColor), "red"?, "green"?, "blue"?: band names (red, nir, swir16… or an asset's key) used instead of a combination, "bbox"?: [west, south, east, north] in degrees | "view" (default), "cellSize"?: the coarsest overview whose cells are at most this size is read, and of a GeoTIFF in strips one strip and column in as many as that size holds on it (default: about 2,048 cells across the box), "name"?: text, "ran"?: (internal: a raster the app has worked out)}"#, ), C::new("stac.addIndex", "Add STAC Index", "Home › Add › Web Data › STAC Search", add_index).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Network)).params( - r#"{"item": a STAC item (from stac.search), "index": "ndvi"|"ndwi"|"savi"|"nbr"|"ndbi"|"evi" (the Indices section's formulas, on the item's bands: NDVI nir and red, NDWI green and nir, SAVI nir and red, NBR nir and swir22, NDBI swir16 and nir, EVI nir, red and blue; their scale and offset applied), "bbox"?: [west, south, east, north] in degrees | "view" (default), "cellSize"?: the coarsest overview whose cells are at most this size is read (default: about 2,048 cells across the box), "name"?: text, "ran"?: (internal: a raster the app has worked out)} → a raster layer of one band"#, + r#"{"item": a STAC item (from stac.search), "index": "ndvi"|"ndwi"|"savi"|"nbr"|"ndbi"|"evi" (the Indices section's formulas, on the item's bands: NDVI nir and red, NDWI green and nir, SAVI nir and red, NBR nir and swir22, NDBI swir16 and nir, EVI nir, red and blue; their scale and offset applied), "bbox"?: [west, south, east, north] in degrees | "view" (default), "cellSize"?: the coarsest overview whose cells are at most this size is read, and of a GeoTIFF in strips one strip and column in as many as that size holds on it (default: about 2,048 cells across the box), "name"?: text, "ran"?: (internal: a raster the app has worked out)} → a raster layer of one band"#, )] } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index deeca22ce0..5ea673fb13 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -52,6 +52,9 @@ mod cube_mask; #[path = "tests/cube_rgb.rs"] mod cube_rgb; #[cfg(not(target_arch = "wasm32"))] +#[path = "tests/cube_strips.rs"] +mod cube_strips; +#[cfg(not(target_arch = "wasm32"))] #[path = "tests/plugin_summaries.rs"] mod plugin_summaries; @@ -53931,9 +53934,9 @@ fn a_window_of_a_geotiff_in_strips_comes_in_as_a_raster() { assert_eq!((whole.width, whole.height), (300, 200)); } -/// A file in strips has no overviews: a cellSize coarser than its cells takes one strip and column -/// in so many (#2592), each value the middle cell of its block, the raster's cells that much -/// larger, and says so. +/// A file in strips without overviews: a cellSize coarser than its cells takes one strip and +/// column in so many (#2592), each value the middle cell of its block, the raster's cells that +/// much larger, and says so. #[test] fn a_cell_size_steps_over_the_strips_of_a_file_in_strips() { // 300 × 200 cells of 0.01° (1,113.2 m) from 10° E, 46° N, a row a strip; cell (x, y) is diff --git a/crates/engine/src/tests/cube_strips.rs b/crates/engine/src/tests/cube_strips.rs new file mode 100644 index 0000000000..9883528d41 --- /dev/null +++ b/crates/engine/src/tests/cube_strips.rs @@ -0,0 +1,121 @@ +//! `cube.reduce` over a STAC collection of GeoTIFFs in strips (#2592), as the Brazil Data Cube +//! serves its CBERS and Amazonia scenes: each date's window read strip by strip, at the full +//! cells or averaged in blocks, over a small collection served here. +use super::*; + +/// Two dates of a 300 × 200 file of 0.01° cells from 10° E, 46° N, a row a strip, cell (x, y) +/// 7 x − 3 y: the API's address. +fn collection() -> String { + let file = rustgis_data::raster::cog::example_strips(300, 200, 1); + let (files, _) = serve_ranged_files(vec![("/a.tif".into(), file.clone()), ("/b.tif".into(), file)]); + let features: Vec = [("a", "2026-04-02"), ("b", "2026-05-04")] + .iter() + .map(|(id, d)| { + format!( + r#"{{"type": "Feature", "id": "{id}", "collection": "wpm", "bbox": [10, 44, 13, 46], "geometry": null, + "properties": {{"datetime": "{d}T00:00:00Z", "bdc:tiles": ["t1"]}}, + "assets": {{"BAND0": {{"href": "{files}/{id}.tif"}}}}}}"# + ) + }) + .collect(); + let search = format!(r#"{{"type": "FeatureCollection", "features": [{}]}}"#, features.join(",")); + format!("{}/v1", serve_routes(vec![("/v1/search", search)], 64)) +} + +/// The first raster `cube.reduce` adds for `p`. +fn reduce(s: &mut Session, p: &Value) -> std::sync::Arc { + let r = s.run("cube.reduce", p).unwrap_or_else(|e| panic!("{p}: {e}")); + let l = s.map().layer(r["layers"][0].as_u64().unwrap() as u32).unwrap(); + l.raster.as_ref().unwrap().data.clone().unwrap() +} + +/// The mean of a collection in strips: its full cells, and with `"resampling": "average"` and a +/// cellSize of three cells each the mean of a block of 3 × 3. Nearest at that size would read +/// every strip to keep one cell in nine, with no overview to take it from: refused, saying what to +/// take. +#[test] +fn a_cube_of_geotiffs_in_strips_is_reduced_from_their_windows() { + let api = collection(); + let mut s = Session::new(Project::default()); + let p = json!({"url": api, "collection": "wpm", "asset": "BAND0", "bbox": [10.5, 45.0, 10.8, 45.3], "start": "2026-04-01", + "end": "2026-05-31", "stat": "mean"}); + let full = reduce(&mut s, &p); + assert!( + (full.transform.pixel_width - 0.01).abs() < 1e-9 && (30..=31).contains(&full.width) && (30..=31).contains(&full.height), + "{} × {}", + full.width, + full.height + ); + let (c0, r0) = ((full.transform.origin_x - 10.0) / 0.01, (46.0 - full.transform.origin_y) / 0.01); + let (c0, r0) = (c0.round() as i64, r0.round() as i64); + assert_eq!((c0, r0), (50, 70)); + for (x, y) in [(0, 0), (7, 3), (29, 29)] { + assert_eq!(full.value(0, x, y), Some((7 * (c0 + x) - 3 * (r0 + y)) as f32), "cell ({x}, {y})"); + } + let mut averaged = p.clone(); + averaged["cellSize"] = json!(0.03); + averaged["resampling"] = json!("average"); + let blocks = reduce(&mut s, &averaged); + assert!( + (blocks.transform.pixel_width - 0.03).abs() < 1e-9 && (10..=11).contains(&blocks.width) && (10..=11).contains(&blocks.height), + "{} × {}", + blocks.width, + blocks.height + ); + let (b0, q0) = ((blocks.transform.origin_x - 10.0) / 0.03, (46.0 - blocks.transform.origin_y) / 0.03); + let (b0, q0) = (b0.round() as i64, q0.round() as i64); + // A block's mean is its middle cell's value, the values being linear. + for (x, y) in [(0, 0), (4, 6), (9, 9)] { + let (cx, cy) = (3 * (b0 + x) + 1, 3 * (q0 + y) + 1); + assert_eq!(blocks.value(0, x, y), Some((7 * cx - 3 * cy) as f32), "block ({x}, {y})"); + } + let mut nearest = p.clone(); + nearest["cellSize"] = json!(0.03); + let e = s.run("cube.reduce", &nearest).unwrap_err(); + assert!(e.contains(r#"take "resampling": "average""#), "{e}"); +} + +/// Two neighbouring files in strips, 100 columns each, cell (x, y) of both x² + 3 y counted from +/// the first's corner: averaged in blocks of 3 × 3, a cell across their seam (columns 99 to 101) +/// takes its pixels from both, the second's corner falling inside a block, and each cell is the +/// mean of its block's pixels, which values that aren't linear tell from its middle one. +#[test] +fn averaged_blocks_cross_the_seam_of_two_files_in_strips() { + use rustgis_data::raster::{ColorHint, Crs, GeoTransform, Raster}; + let value = |x: u32, y: u32| (x * x + 3 * y) as f32; + let file = |first: u32| { + let values = (0..60 * 100).map(|i| value(first + i % 100, i / 100)).collect(); + let t = GeoTransform { origin_x: 10.0 + 0.01 * f64::from(first), origin_y: 46.0, pixel_width: 0.01, pixel_height: -0.01 }; + let r = Raster::new("r", 100, 60, vec![values], t, Crs::LonLat, None, ColorHint::Gray, "Float32").unwrap(); + rustgis_data::raster::geotiff::write(&r, 0).unwrap() + }; + let (files, _) = serve_ranged_files(vec![("/a.tif".into(), file(0)), ("/b.tif".into(), file(100))]); + let item = |id: &str, west: u32| { + format!( + r#"{{"type": "Feature", "id": "{id}", "collection": "wpm", "bbox": [{}, 45.4, {}, 46], "geometry": null, + "properties": {{"datetime": "2026-04-02T00:00:00Z", "bdc:tiles": ["{id}"]}}, + "assets": {{"BAND0": {{"href": "{files}/{id}.tif"}}}}}}"#, + 10.0 + 0.01 * f64::from(west), + 11.0 + 0.01 * f64::from(west) + ) + }; + let search = format!(r#"{{"type": "FeatureCollection", "features": [{}, {}]}}"#, item("a", 0), item("b", 100)); + let api = format!("{}/v1", serve_routes(vec![("/v1/search", search)], 64)); + let mut s = Session::new(Project::default()); + let p = json!({"url": api, "collection": "wpm", "asset": "BAND0", "bbox": [10.9, 45.55, 11.1, 45.85], "start": "2026-04-01", + "end": "2026-04-30", "stat": "mean", "cellSize": 0.03, "resampling": "average"}); + let blocks = reduce(&mut s, &p); + // The blocks start at the western file's corner, the first: the seam, column 100, cuts one. + let (x0, y0) = ((blocks.transform.origin_x - 10.0) / 0.01, (46.0 - blocks.transform.origin_y) / 0.01); + let (x0, y0) = (x0.round() as u32, y0.round() as u32); + assert!(x0 % 3 == 0 && (100 - x0) % 3 != 0, "a block straddles the seam: columns {x0} on"); + assert!(x0 < 99 && x0 + 3 * blocks.width > 102, "the area crosses the seam: columns {x0} on"); + for y in 0..blocks.height { + for x in 0..blocks.width { + let (cx, cy) = (x0 + 3 * x, y0 + 3 * y); + let mean = (0..9).map(|k| f64::from(value(cx + k % 3, cy + k / 3))).sum::() / 9.0; + let got = blocks.value(0, x.into(), y.into()).unwrap(); + assert!((f64::from(got) - mean).abs() < 1e-3, "block ({x}, {y}) of columns {cx}–{}: {got}, not {mean}", cx + 2); + } + } +}