diff --git a/crates/analysis/src/rasterops.rs b/crates/analysis/src/rasterops.rs index 68dd220612..1fab346287 100644 --- a/crates/analysis/src/rasterops.rs +++ b/crates/analysis/src/rasterops.rs @@ -1433,7 +1433,8 @@ pub fn transform_polygon_to_lonlat(rings: &[Vec], tr: Option<&Transformer } /// The polygon parts of a (multi-)polygon feature, checked and taken apart into rings, in the -/// system they are in: [`transform_feature_polygons_to_lonlat`] with no transformer. +/// system they are in: [`transform_feature_polygons_to_lonlat`] with no transformer. It doesn't +/// look at Cancel: a caller looping over features does, between them. pub fn validated_polygon_parts(polys: &[Vec>]) -> Result>>, PolygonTransformError> { transform_feature_polygons_to_lonlat(polys, None) } diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index c5a60512d5..a6433ea013 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -1173,7 +1173,17 @@ pub fn replace_atomic_with>( /// [`StagedWrite::commit`] installs them. Dropping the result discards the staged file. pub fn stage_atomic(path: &Path, bytes: &[u8]) -> std::io::Result { use std::io::Write; - stage_at(link_target(path)?, |w| w.write_all(bytes)).map(|(staged, ())| staged) + stage_at(link_target(path)?, 8 << 10, |w| w.write_all(bytes)).map(|(staged, ())| staged) +} + +/// [`stage_atomic`] for a write that streams: `write` fills the file beside the destination (a +/// symbolic link's target), which [`StagedWrite::commit`] installs; dropping the result discards it. +pub fn stage_streamed>( + path: &Path, + write: impl FnOnce(&mut std::io::BufWriter) -> std::result::Result, +) -> std::result::Result<(StagedWrite, T), E> { + // A streamed write (a raster's tiles) goes through a buffer of a megabyte. + stage_at(link_target(path)?, 1 << 20, write) } /// Stages and installs a write, retaining the old file on error or cancellation. @@ -1181,7 +1191,7 @@ fn atomic_write_at>( path: std::path::PathBuf, write: impl FnOnce(&mut std::io::BufWriter) -> std::result::Result, ) -> std::result::Result { - let (staged, value) = stage_at(path, write)?; + let (staged, value) = stage_at(path, 8 << 10, write)?; staged.commit()?; Ok(value) } @@ -1190,6 +1200,7 @@ fn atomic_write_at>( /// and a directory sync. fn stage_at>( path: std::path::PathBuf, + buffer: usize, write: impl FnOnce(&mut std::io::BufWriter) -> std::result::Result, ) -> std::result::Result<(StagedWrite, T), E> { use std::io::Write; @@ -1215,7 +1226,7 @@ fn stage_at>( Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} Err(error) => return Err(error.into()), } - let mut out = std::io::BufWriter::new(file); + let mut out = std::io::BufWriter::with_capacity(buffer, file); let value = write(&mut out)?; out.flush()?; out.get_ref().sync_all()?; diff --git a/crates/data/src/raster/cogwrite.rs b/crates/data/src/raster/cogwrite.rs index ce78a846b2..6ddb3823cf 100644 --- a/crates/data/src/raster/cogwrite.rs +++ b/crates/data/src/raster/cogwrite.rs @@ -1065,6 +1065,16 @@ pub fn write_file(r: &Raster, band: usize, path: &Path) -> Result { res } +/// [`write_file`]'s file, written and synced beside `path` but not yet in its place: the caller +/// installs it ([`crate::io::StagedWrite::commit`]) once nothing can cancel the result any more, +/// and dropping it leaves `path` as it was. +pub fn write_staged(r: &Raster, band: usize, path: &Path) -> Result<(CogInfo, crate::io::StagedWrite)> { + let (staged, info) = crate::io::stage_streamed(path, |w| write_to(r, band, Flavour::Auto, w))?; + // The last look while it is written: a Cancel that came meanwhile leaves `path` as it was. + crate::progress::check()?; + Ok((info, staged)) +} + #[cfg(test)] mod tests { use std::io::Cursor; diff --git a/crates/engine/command-surface.txt b/crates/engine/command-surface.txt index d0f5f8118d..8e7148c2ed 100644 --- a/crates/engine/command-surface.txt +++ b/crates/engine/command-surface.txt @@ -477,7 +477,7 @@ raster.measurements clear? raster.mosaic inputs name? path? raster.process layer operation extent? polygon? selectedOnly? factor? name? ran? raster.project layer crs? cellSize? origin? extent? grid? resampling? name? path? -raster.rasterize layer field? value? nodata? crs? cellSize? origin? extent? grid? name? path? +raster.rasterize layer field? value? nodata? crs? cellSize? origin? extent? grid? name? path? ran? raster.resampling layer? type raster.rotation layer? angle raster.setDefaultStyle fromLayer? layer? ramp? invert? stretch? low? high? n? resampling? reset? diff --git a/crates/engine/src/cmd/imagery.rs b/crates/engine/src/cmd/imagery.rs index 7cc5f9a639..0755ac7bb9 100644 --- a/crates/engine/src/cmd/imagery.rs +++ b/crates/engine/src/cmd/imagery.rs @@ -53,7 +53,7 @@ pub fn commands() -> Vec { r#"{"layer": raster, "crs"?: EPSG code or "EPSG:n" of the output (default the layer's), "cellSize"?: number or [x, y] in the output's units (default about the layer's pixel there), "origin"?: [x, y] a cell corner falls on (default [0, 0], so grids of the same cellSize line up), "extent"?: polygon layer (its selected or all features' bounds) | [west, south, east, north] in degrees | "view" (default the layer's footprint), "grid"?: raster layer whose coordinate system, cells and extent are taken exactly (instead of crs, cellSize, origin and extent), "resampling"?: "nearest" (default) | "bilinear" | "cubic" | "average" (the mean of the pixels whose centres fall in a cell) | "mode" (their most frequent value, the least of those tied), "name"?: new layer (default " projected"), "path"?: GeoTIFF to write it to}"#, ), C::new("raster.rasterize", "Polygons to Raster", "Analyze › Raster", rasterize).inputs(rasterize_inputs).roles(&[]).effects(crate::policy::Effects::NONE).params( - r#"{"layer": polygon layer (its selected or all features; a later one over an earlier), "field"?: numeric field (its values) or text field (codes 1 to n in sorted order of its values, listed in a table named after the result with classes), "value"?: number every polygon gives when there is no field (default 1), "nodata"?: number of the cells under no polygon (default 0), "crs"?: EPSG code or "EPSG:n" of the output (default the projected system the layer holds its coordinates in, else the one it was read in; degrees for a layer in degrees with neither), "cellSize"?: number or [x, y] in the output's units (required without grid), "origin"?: [x, y] a cell corner falls on (default [0, 0], so grids of the same cellSize line up), "extent"?: polygon layer (its selected or all features' bounds) | [west, south, east, north] in degrees | "view"; default the polygons' bounds, "grid"?: raster layer whose coordinate system, cells and extent are taken exactly (instead of crs, cellSize, origin and extent), "name"?: new layer (default " raster"), "path"?: GeoTIFF to write it to}"#, + r#"{"layer": polygon layer (its selected or all features; a later one over an earlier), "field"?: numeric field (its values) or text field (codes 1 to n in sorted order of its values, listed in a table named after the result with classes), "value"?: number every polygon gives when there is no field (default 1), "nodata"?: number of the cells under no polygon (default 0), "crs"?: EPSG code or "EPSG:n" of the output (default the projected system the layer holds its coordinates in, else the one it was read in; degrees for a layer in degrees with neither), "cellSize"?: number or [x, y] in the output's units (required without grid), "origin"?: [x, y] a cell corner falls on (default [0, 0], so grids of the same cellSize line up), "extent"?: polygon layer (its selected or all features' bounds) | [west, south, east, north] in degrees | "view"; default the polygons' bounds, "grid"?: raster layer whose coordinate system, cells and extent are taken exactly (instead of crs, cellSize, origin and extent), "name"?: new layer (default " raster"), "path"?: GeoTIFF to write it to, "ran"?: (internal: a raster the app has worked out)}"#, ), // A fit is a measurement of the points, not a project change: no undo step. C::new("raster.gcpFit", "Control Point Fit", "Imagery › Alignment", gcp_fit).roles(&[]).effects(crate::policy::Effects::NONE).view().params( @@ -311,13 +311,27 @@ fn georeference(s: &mut Session, p: &Value) -> CmdResult { /// A coordinate system given as an EPSG code or any text [`Crs::parse`] reads. fn crs_param(s: &mut Session, p: &Value, key: &str) -> Result, String> { + let (crs, warning) = crs_param_read(p, key)?; + if let Some(w) = warning { + s.warn(w); + } + Ok(crs) +} + +/// [`crs_param`] without the session: the system, and the warning to give of a typed one +/// ([`super::parse_crs`]'s). +fn crs_param_read(p: &Value, key: &str) -> Result<(Option, Option), String> { let bad = || format!("{key} is an EPSG code such as 32613 or \"EPSG:32613\""); match p.get(key) { - None | Some(Value::Null) => Ok(None), - Some(Value::String(t)) => super::parse_crs(s, t).map(Some), + None | Some(Value::Null) => Ok((None, None)), + Some(Value::String(t)) => { + let crs = Crs::parse(t)?; + let warning = rustgis_data::raster::wkt::typed_crs_note(t, crs).map(|note| format!("crs: {note}")); + Ok((Some(crs), warning)) + } Some(v) => { let code = v.as_u64().filter(|c| *c <= u64::from(u32::MAX)).ok_or_else(bad)?; - Crs::from_epsg(code as u32).map(Some).ok_or_else(|| format!("unknown coordinate system EPSG:{code}")) + Crs::from_epsg(code as u32).map(|c| (Some(c), None)).ok_or_else(|| format!("unknown coordinate system EPSG:{code}")) } } } @@ -458,12 +472,17 @@ const EXACT_WHOLE: f64 = 16_777_216.0; /// text field's code or one `value` (see `rustgis_analysis::warp::rasterize`). A new layer, and /// for a text field a table of its codes. /// -/// It runs on the thread that calls it, the app's own on the desktop: it isn't one of the commands -/// that make their raster on a thread of their own (`workflows::IN_BACKGROUND`) yet, and nothing -/// installs a probe around it, so Cancel doesn't reach it and it runs to the end. Its grid sizing -/// and burn look at Cancel (`progress::check`, `control::check`) for when it moves there, which -/// has to carry over the GeoTIFF it writes to `path` and the class table it adds. +/// Made on another thread from the app (`workflows::IN_BACKGROUND`), with progress and Cancel: +/// its grid's sizing and the burn look at Cancel ([`rasterize_work`]). fn rasterize(s: &mut Session, p: &Value) -> CmdResult { + super::workflows::made_or_ran(s, p, "raster.rasterize") +} + +/// What `raster.rasterize` reads of the session (the polygons and their values, the grid as its +/// parameters give it), and the work that sizes the grid, burns the polygons, writes the GeoTIFF to +/// `path` when given and makes the layer; once it is added, its notices are said and a text +/// field's class table is added. +pub(crate) fn rasterize_work(s: &Session, p: &Value) -> Result { let ln = rasterize_name(p)?; let l = s.map().layer_by_name(ln).filter(|l| l.raster.is_none()).ok_or_else(|| format!("no vector layer '{ln}'"))?; let ds = &l.dataset; @@ -491,197 +510,297 @@ fn rasterize(s: &mut Session, p: &Value) -> CmdResult { }; let path = tif_path(p)?; let out_name = name(p, format!("{ln} raster"))?; - // The features burned: the selection, else all, in the layer's order (a later one wins). - let mut rows: Vec = if l.selection.is_empty() { (0..ds.features.len()).collect() } else { l.selection.clone() }; - rows.sort_unstable(); - rows.dedup(); - let (mut no_value, mut no_polygon) = (0, 0); - let mut burns: Vec<(Vec>>, rustgis_data::Value)> = Vec::new(); + let selection = l.selection.clone(); // Burned from the system the layer holds its coordinates in (none of it converted when the - // grid is in it too). + // grid is in it too), by default onto a grid in it when it is a projected one: a geographic or + // geocentric one (an ECEF layer) has no plane for a grid, so it takes the one the layer was read + // in. Web Mercator and the world projections are planes a grid is laid on, unlike the analysis + // plane `works_in` excludes them from. let held = ds.coord_crs(); - for row in rows { - let Some(feature) = ds.features.get(row) else { continue }; - let parts = match &feature.geometry { - Some(Geometry::Polygon(polys)) => rasterops::validated_polygon_parts(polys).ok(), - _ => None, - }; - let Some(parts) = parts else { - no_polygon += 1; - continue; - }; - let v = match field { - Some((i, _)) => ds.value(row, i).clone(), - None => rustgis_data::Value::Float(value), - }; - burns.push((parts, v)); - } - // A text or date field's values become codes 1 to n, in sorted order: text by its text, dates - // and date-times by instant (one moment at two offsets is one class, labelled as first seen). - let text = field.is_some_and(|(_, ty)| ty == FieldType::Text || ty.is_temporal()); - let temporal = field.is_some_and(|(_, ty)| ty.is_temporal()); - #[derive(Clone, PartialEq, Eq, PartialOrd, Ord)] - enum ClassKey { - Instant(i64), - Text(String), - } - let key = |v: &rustgis_data::Value| if temporal { v.temporal_key().map(ClassKey::Instant) } else { text_of(v).map(ClassKey::Text) }; - let mut labels = std::collections::BTreeMap::new(); - if text { - for (_, v) in &burns { - if let (Some(k), Some(label)) = (key(v), text_of(v)) { - labels.entry(k).or_insert(label); - } - } - } - let keys: Vec = labels.keys().cloned().collect(); - let classes: Vec = labels.into_values().collect(); - // Whole numbers: codes, one value, or a field that isn't a floating-point one. - let whole_field = field.is_none_or(|(_, ty)| ty != FieldType::Double); - let what = field.and_then(|(i, _)| ds.fields.get(i)).map_or("value", |f| f.name.as_str()).to_string(); - let mut shapes = Vec::with_capacity(burns.len()); - let mut rounded = 0; - for (parts, v) in burns { - let x = if text { key(&v).and_then(|k| keys.binary_search(&k).ok()).map(|i| i as f64 + 1.0) } else { v.as_f64() }; - let Some(x) = x else { - no_value += 1; - continue; - }; - if x.abs() > f64::from(f32::MAX) { - return Err(format!("{ln}: {what} {x} is past the range of a raster's 32-bit pixels")); - } - if whole_field && x.fract() == 0.0 && x.abs() > EXACT_WHOLE { - // Only a numeric field's numbers can be given as text instead. - let hint = if field.is_some() && !text { "; a text field gives codes instead" } else { "" }; - return Err(format!("{ln}: {what} {x} is more than a raster's pixels hold exactly ({EXACT_WHOLE}){hint}")); - } - // As a pixel holds them: a value that rounds to the no-data value would be lost. - if x as f32 == nodata as f32 { - let of = if text { format!(", the code of {:?},", text_of(&v).unwrap_or_default()) } else { String::new() }; - return Err(format!("{ln}: {what} {x}{of} is the no-data value: give another nodata")); - } - rounded += usize::from(f64::from(x as f32) != x); - shapes.push(warp::Shape { parts, value: x as f32 }); - } - if shapes.is_empty() { - return Err(format!("{ln} has no polygons with a value to burn")); - } - // By default, the projected system the layer holds its coordinates in (else the one it was read in) and - // the polygons' bounds. - let held_bounds = shapes.iter().flat_map(|s| s.parts.iter().flatten().flatten()).fold(Extent::EMPTY, |mut e, c| { - e.expand(*c); - e - }); - // A projected system the layer holds it in: a geographic or geocentric one (an ECEF layer) has - // no plane for a grid, so it takes the one the layer was read in. Web Mercator and the world - // projections are planes a grid is laid on, unlike the analysis plane `works_in` excludes them - // from. let projected = held != Crs::LonLat && !held.is_geographic() && !held.is_geocentric(); let crs = if projected { held } else { ds.crs.unwrap_or(Crs::LonLat) }; - let mut unsized_by = 0usize; - let grid = grid_param(s, p, crs, |crs| { - if crs == held && projected { - return Ok(([held_bounds.min_x, held_bounds.min_y, held_bounds.max_x, held_bounds.max_y], None)); - } - // Otherwise the bounds of the polygons' box in longitude/latitude, as before. A place the - // layer's system can't give there (a missing one aside) doesn't size the grid, and is - // said when the grid takes these bounds (no extent given). - let to = held.to(Crs::LonLat).map_err(|e| format!("{ln}: {e}"))?; - let mut lonlat = Extent::EMPTY; - // A conversion a vertex: Cancel is looked at every few thousand (once a probe is - // installed, see above). - for (i, c) in shapes.iter().flat_map(|s| s.parts.iter().flatten().flatten()).filter(|c| c.is_finite()).enumerate() { - if i % 4096 == 0 { - rustgis_data::progress::check().map_err(|e| e.to_string())?; + let (spec, notes) = grid_spec(s, p, crs)?; + // Without a grid, its cells are given: no polygon sets a cell size. + if matches!(spec, GridSpec::Build { cell: None, .. }) { + return Err(with_notes("cellSize is required: a number, or [x, y], in the output's units, or a grid".into(), ¬es)); + } + let extent_given = p.get("extent").is_some_and(|v| !v.is_null()); + // The layer's rows are shared, not copied: every pass over the polygons runs on the work's + // thread, which looks at Cancel every few thousand features or vertices in each, and between + // shapes as it burns. + let ds = ds.clone(); + let ln = ln.to_string(); + Ok(Box::new(move || { + let mut notes = notes; + // What a run that fails had to say goes with its error. + // Taken by the work, so the layer's rows are let go of once its polygons are collected + // (an edit meanwhile then copies them only while they're still read). + let mut ds = Some(ds); + let made = (|| -> Result { + let ds = ds.take().ok_or("the work ran twice")?; + // The features burned: the selection, else all, in the layer's order (a later one wins). + let mut rows: Vec = if selection.is_empty() { (0..ds.features.len()).collect() } else { selection }; + rows.sort_unstable(); + rows.dedup(); + let (mut no_value, mut no_polygon) = (0, 0); + let mut burns: Vec<(Vec>>, rustgis_data::Value)> = Vec::new(); + for (k, row) in rows.into_iter().enumerate() { + // Each checked and copied: Cancel is looked at every few thousand. + if k % 4096 == 0 { + rustgis_data::progress::check().map_err(|e| e.to_string())?; + } + let Some(feature) = ds.features.get(row) else { continue }; + let parts = match &feature.geometry { + Some(Geometry::Polygon(polys)) => rasterops::validated_polygon_parts(polys).ok(), + _ => None, + }; + let Some(parts) = parts else { + no_polygon += 1; + continue; + }; + let v = match field { + Some((i, _)) => ds.value(row, i).clone(), + None => rustgis_data::Value::Float(value), + }; + burns.push((parts, v)); } - match to.point(*c) { - Some(c) => lonlat.expand(c), - None => unsized_by += 1, + // A text or date field's values become codes 1 to n, in sorted order: text by its text, dates + // and date-times by instant (one moment at two offsets is one class, labelled as first seen). + let text = field.is_some_and(|(_, ty)| ty == FieldType::Text || ty.is_temporal()); + let temporal = field.is_some_and(|(_, ty)| ty.is_temporal()); + #[derive(Clone, PartialEq, Eq, PartialOrd, Ord)] + enum ClassKey { + Instant(i64), + Text(String), } - } - let mut b = warp::bounds_in([lonlat.min_x, lonlat.min_y, lonlat.max_x, lonlat.max_y], crs).map_err(|e| format!("{ln}: {e}"))?; - // Taking in the vertices as the burn places them: between two datums the direct operation - // lands apart from the route through WGS 84 (half a metre for DHDN and ETRS89). - if held != Crs::LonLat - && let Some(q) = warp::placed_bounds(held, crs, &shapes).map_err(|e| format!("{ln}: {e}"))? - { - b = [b[0].min(q[0]), b[1].min(q[1]), b[2].max(q[2]), b[3].max(q[3])]; - } - Ok((b, None)) - })?; - if unsized_by > 0 && p.get("extent").is_none_or(Value::is_null) { - s.notify( - format!( - "{ln}: {unsized_by} {} that can't be placed in longitude/latitude {} left out of the grid's extent: check {} coordinates and the layer's coordinate system", - if unsized_by == 1 { "vertex" } else { "vertices" }, - if unsized_by == 1 { "was" } else { "were" }, - if unsized_by == 1 { "its" } else { "their" } - ), - false, - ); - } - // The smallest pixel type the GeoTIFF writer keeps that holds every value and the no-data. - let whole = |max: f64| shapes.iter().map(|s| f64::from(s.value)).chain([nodata]).all(|v| v.fract() == 0.0 && (0.0..=max).contains(&v)); - let data_type = if whole(255.0) { - "UInt8" - } else if whole(65_535.0) { - "UInt16" - } else { - "Float32" - }; - let burned = warp::rasterize_in(&grid, held, &shapes, nodata as f32).map_err(|e| format!("{ln}: {e}"))?; - if burned.cells == 0 { - return Err(format!("no cell centre of the grid falls inside {ln}'s polygons: give a smaller cellSize, or a grid over them")); - } - let (w, h) = (u32::try_from(grid.width).map_err(|e| e.to_string())?, u32::try_from(grid.height).map_err(|e| e.to_string())?); - let out = Raster::new(&out_name, w, h, vec![burned.data], grid.transform(), grid.crs, Some(nodata), ColorHint::Gray, data_type) - .map_err(|e| e.to_string())?; - let mut info = json!({ - "name": out_name, "crs": grid.crs.label(), "width": out.width, "height": out.height, "dataType": data_type, "nodata": nodata, - "cellSize": [grid.cell_x, grid.cell_y], "corner": [grid.min_x, grid.max_y], "features": burned.burned, "cells": burned.cells, - }); - if rounded > 0 { - s.notify(format!("{ln}: {rounded} value(s) of {what} rounded to the raster's 32-bit pixels"), false); - } - let skipped = [("noValue", no_value), ("noPolygon", no_polygon), ("unplaced", burned.unplaced.len()), ("noCell", burned.missed)]; - if skipped.iter().any(|(_, n)| *n > 0) { - info["skipped"] = - skipped.iter().filter(|(_, n)| *n > 0).map(|(k, n)| (k.to_string(), json!(n))).collect::>().into(); - let mut why = Vec::new(); - if no_value > 0 { - why.push(format!("{no_value} with no value")); - } - if no_polygon > 0 { - why.push(format!("{no_polygon} with no valid polygon")); - } - if !burned.unplaced.is_empty() { - why.push(format!("{} with a part that can't be placed on the grid (any other parts were burned)", burned.unplaced.len())); - } - if burned.missed > 0 { - why.push(format!("{} that hold no cell centre (narrower than a cell, or off the grid)", burned.missed)); - } - s.notify(format!("{ln}: features skipped: {}", why.join(", ")), false); - } - // Whole numbers few enough to list are classes, drawn with unique values. - let distinct = out.bands.first().is_some_and(|b| b.stats.categories.is_some()); - let mut info = add_output(s, out, path, whole_field && distinct, info)?; - if text { - let layer = info.get("name").and_then(Value::as_str).unwrap_or(&out_name).to_string(); - let mut table = rustgis_data::Dataset::new( - free_table_name(s, &format!("{layer} classes")), - GeometryType::None, - vec![rustgis_data::Field::new("code", FieldType::Integer), rustgis_data::Field::new("value", FieldType::Text)], - ); - for (i, c) in classes.iter().enumerate() { - table.push_next(None, vec![rustgis_data::Value::Int(i as i64 + 1), rustgis_data::Value::Text(c.clone())]); - } - info["classTable"] = json!(table.name); - s.project.add_table(table); - info["classCount"] = json!(classes.len()); - // All the codes are in the table; here, as many as a unique-value legend shows. - info["classes"] = classes.iter().take(256).enumerate().map(|(i, c)| json!({"code": i + 1, "value": c})).collect(); - } - Ok(info) + let key = + |v: &rustgis_data::Value| if temporal { v.temporal_key().map(ClassKey::Instant) } else { text_of(v).map(ClassKey::Text) }; + let mut labels = std::collections::BTreeMap::new(); + // Each pass over the features looks at Cancel every few thousand, as the first. + let look = |k: usize| if k.is_multiple_of(4096) { rustgis_data::progress::check().map_err(|e| e.to_string()) } else { Ok(()) }; + if text { + for (n, (_, v)) in burns.iter().enumerate() { + look(n)?; + if let (Some(k), Some(label)) = (key(v), text_of(v)) { + labels.entry(k).or_insert(label); + } + } + } + let keys: Vec = labels.keys().cloned().collect(); + let classes: Vec = labels.into_values().collect(); + // Whole numbers: codes, one value, or a field that isn't a floating-point one. + let whole_field = field.is_none_or(|(_, ty)| ty != FieldType::Double); + let what = field.and_then(|(i, _)| ds.fields.get(i)).map_or("value", |f| f.name.as_str()).to_string(); + drop(ds); + let mut shapes = Vec::with_capacity(burns.len()); + let mut rounded = 0; + for (k, (parts, v)) in burns.into_iter().enumerate() { + look(k)?; + let x = if text { key(&v).and_then(|k| keys.binary_search(&k).ok()).map(|i| i as f64 + 1.0) } else { v.as_f64() }; + let Some(x) = x else { + no_value += 1; + continue; + }; + if x.abs() > f64::from(f32::MAX) { + return Err(format!("{ln}: {what} {x} is past the range of a raster's 32-bit pixels")); + } + if whole_field && x.fract() == 0.0 && x.abs() > EXACT_WHOLE { + // Only a numeric field's numbers can be given as text instead. + let hint = if field.is_some() && !text { "; a text field gives codes instead" } else { "" }; + return Err(format!("{ln}: {what} {x} is more than a raster's pixels hold exactly ({EXACT_WHOLE}){hint}")); + } + // As a pixel holds them: a value that rounds to the no-data value would be lost. + if x as f32 == nodata as f32 { + let of = if text { format!(", the code of {:?},", text_of(&v).unwrap_or_default()) } else { String::new() }; + return Err(format!("{ln}: {what} {x}{of} is the no-data value: give another nodata")); + } + rounded += usize::from(f64::from(x as f32) != x); + shapes.push(warp::Shape { parts, value: x as f32 }); + } + if shapes.is_empty() { + return Err(format!("{ln} has no polygons with a value to burn")); + } + // By default, the projected system the layer holds its coordinates in (else the one it was read in) and + // the polygons' bounds. + let mut unsized_by = 0usize; + let grid = spec.finish(&mut notes, |crs| { + // (Asked for only when the grid's bounds aren't given.) + if crs == held && projected { + let mut held_bounds = Extent::EMPTY; + for (k, c) in shapes.iter().flat_map(|s| s.parts.iter().flatten().flatten()).enumerate() { + look(k)?; + held_bounds.expand(*c); + } + return Ok(([held_bounds.min_x, held_bounds.min_y, held_bounds.max_x, held_bounds.max_y], None)); + } + // Otherwise the bounds of the polygons' box in longitude/latitude, as before. A place the + // layer's system can't give there (a missing one aside) doesn't size the grid, and is + // said when the grid takes these bounds (no extent given). + let to = held.to(Crs::LonLat).map_err(|e| format!("{ln}: {e}"))?; + let mut lonlat = Extent::EMPTY; + // A conversion a vertex: Cancel is looked at every few thousand (once a probe is + // installed, see above). + for (i, c) in shapes.iter().flat_map(|s| s.parts.iter().flatten().flatten()).filter(|c| c.is_finite()).enumerate() { + if i % 4096 == 0 { + rustgis_data::progress::check().map_err(|e| e.to_string())?; + } + match to.point(*c) { + Some(c) => lonlat.expand(c), + None => unsized_by += 1, + } + } + let mut b = + warp::bounds_in([lonlat.min_x, lonlat.min_y, lonlat.max_x, lonlat.max_y], crs).map_err(|e| format!("{ln}: {e}"))?; + // Taking in the vertices as the burn places them: between two datums the direct operation + // lands apart from the route through WGS 84 (half a metre for DHDN and ETRS89). + if held != Crs::LonLat + && let Some(q) = warp::placed_bounds(held, crs, &shapes).map_err(|e| format!("{ln}: {e}"))? + { + b = [b[0].min(q[0]), b[1].min(q[1]), b[2].max(q[2]), b[3].max(q[3])]; + } + Ok((b, None)) + })?; + if unsized_by > 0 && !extent_given { + notes.push(( + format!( + "{ln}: {unsized_by} {} that can't be placed in longitude/latitude {} left out of the grid's extent: check {} coordinates and the layer's coordinate system", + if unsized_by == 1 { "vertex" } else { "vertices" }, + if unsized_by == 1 { "was" } else { "were" }, + if unsized_by == 1 { "its" } else { "their" } + ), + false, + )); + } + // The smallest pixel type the GeoTIFF writer keeps that holds every value and the no-data. + let whole = + |max: f64| shapes.iter().map(|s| f64::from(s.value)).chain([nodata]).all(|v| v.fract() == 0.0 && (0.0..=max).contains(&v)); + let data_type = if whole(255.0) { + "UInt8" + } else if whole(65_535.0) { + "UInt16" + } else { + "Float32" + }; + let burned = warp::rasterize_in(&grid, held, &shapes, nodata as f32).map_err(|e| format!("{ln}: {e}"))?; + if burned.cells == 0 { + return Err(format!( + "no cell centre of the grid falls inside {ln}'s polygons: give a smaller cellSize, or a grid over them" + )); + } + let (w, h) = (u32::try_from(grid.width).map_err(|e| e.to_string())?, u32::try_from(grid.height).map_err(|e| e.to_string())?); + let out = Raster::new(&out_name, w, h, vec![burned.data], grid.transform(), grid.crs, Some(nodata), ColorHint::Gray, data_type) + .map_err(|e| e.to_string())?; + let mut info = json!({ + "name": out_name, "crs": grid.crs.label(), "width": out.width, "height": out.height, "dataType": data_type, "nodata": nodata, + "cellSize": [grid.cell_x, grid.cell_y], "corner": [grid.min_x, grid.max_y], "features": burned.burned, "cells": burned.cells, + }); + if rounded > 0 { + notes.push((format!("{ln}: {rounded} value(s) of {what} rounded to the raster's 32-bit pixels"), false)); + } + let skipped = + [("noValue", no_value), ("noPolygon", no_polygon), ("unplaced", burned.unplaced.len()), ("noCell", burned.missed)]; + if skipped.iter().any(|(_, n)| *n > 0) { + info["skipped"] = skipped + .iter() + .filter(|(_, n)| *n > 0) + .map(|(k, n)| (k.to_string(), json!(n))) + .collect::>() + .into(); + let mut why = Vec::new(); + if no_value > 0 { + why.push(format!("{no_value} with no value")); + } + if no_polygon > 0 { + why.push(format!("{no_polygon} with no valid polygon")); + } + if !burned.unplaced.is_empty() { + why.push(format!( + "{} with a part that can't be placed on the grid (any other parts were burned)", + burned.unplaced.len() + )); + } + if burned.missed > 0 { + why.push(format!("{} that hold no cell centre (narrower than a cell, or off the grid)", burned.missed)); + } + notes.push((format!("{ln}: features skipped: {}", why.join(", ")), false)); + } + // Whole numbers few enough to list are classes, drawn with unique values. + let distinct = out.bands.first().is_some_and(|b| b.stats.categories.is_some()); + let e = out.extent(); + info["extent"] = json!([e.min_x, e.min_y, e.max_x, e.max_y]); + // A file written is the layer's source; without one the pixels are kept in the project. + // Written beside it, the file is put in its place as the layer is added: a run cancelled + // before then leaves the file there as it was. + let (mut written, mut staged) = (rustgis_data::loss::Notes::new(), None); + let mut rl = match &path { + Some(path) => { + let (wrote, file) = super::raster::write_cog_staged( + &out, + 0, + path, + "export the resulting layer with share.exportRaster and give \"band\" for another", + )?; + written = wrote.notes; + staged = Some(file); + info["path"] = json!(path); + info["cog"] = wrote.answer.get("cog").cloned().unwrap_or(Value::Null); + RasterLayer::from_path(out, path.clone()) + } + None => layer_of(out)?, + }; + if whole_field + && distinct + && let Some(d) = rl.data.clone() + { + rl.style.renderer = rustgis_map::raster::unique_values(&d, 0, rustgis_map::Ramp::Harbour); + } + // A text field's table of codes, made here (one row a class); named as it is added. + let table = if text { + let mut table = rustgis_data::Dataset::new( + String::new(), + GeometryType::None, + vec![rustgis_data::Field::new("code", FieldType::Integer), rustgis_data::Field::new("value", FieldType::Text)], + ); + for (i, c) in classes.iter().enumerate() { + look(i)?; + table.push_next(None, vec![rustgis_data::Value::Int(i as i64 + 1), rustgis_data::Value::Text(c.clone())]); + } + Some(table) + } else { + None + }; + // All the codes are in the table; in the answer, as many as a unique-value legend shows. + let listed: Vec = classes.iter().take(256).enumerate().map(|(i, c)| json!({"code": i + 1, "value": c})).collect(); + let class_count = classes.len(); + let notes = std::mem::take(&mut notes); + // Said with the error should its file not go in place. + let said: Vec = notes.iter().map(|(n, _)| n.clone()).chain(written.texts().map(str::to_string)).collect(); + let then: super::workflows::Then = Box::new(move |s: &mut Session, v: &mut Value| { + say(s, notes); + for note in written { + s.say_written(note); + } + // The name the layer got (another may hold the one asked for: "… raster (2)"). + let id = v.get("layer").and_then(Value::as_u64).and_then(|id| u32::try_from(id).ok()); + let layer = id.and_then(|id| s.map().layer(id)).map(|l| l.name.clone()).unwrap_or(out_name.clone()); + v["name"] = json!(layer); + if let Some(mut table) = table { + table.name = free_table_name(s, &format!("{layer} classes")); + v["classTable"] = json!(table.name); + s.project.add_table(table); + v["classCount"] = json!(class_count); + v["classes"] = listed.into(); + } + }); + let name = info.get("name").and_then(Value::as_str).unwrap_or_default().to_string(); + let made = super::workflows::made_layer(name, rl, Some(info), Some(then)); + Ok(match staged { + Some(file) => made.committing(file, said), + None => made, + }) + })(); + made.map_err(|e| with_notes(e, ¬es)) + })) } /// `base`, or `base (2)`, `base (3)`… : the first no table of the project has (whatever its case). @@ -765,9 +884,169 @@ fn grid_param( crs: Crs, natural: impl FnOnce(Crs) -> Result<([f64; 4], Option), String>, ) -> Result { + let (spec, mut notes) = grid_spec(s, p, crs)?; + let grid = spec.finish(&mut notes, natural); + say(s, notes); + grid +} + +/// What to say: a notice, or a warning (`true`). +type Notes = Vec<(String, bool)>; + +/// `error`, with what a run had to say before it failed (`notes`). +fn with_notes(error: String, notes: &Notes) -> String { + if notes.is_empty() { + return error; + } + let said: Vec<&str> = notes.iter().map(|(n, _)| n.as_str()).collect(); + format!("{error} ({})", said.join("; ")) +} + +/// Says `notes`. +fn say(s: &mut Session, notes: Notes) { + for (note, warning) in notes { + if warning { + s.warn(note); + } else { + s.notify(note, false); + } + } +} + +/// A grid as its parameters give it, read of the session ([`grid_spec`]); what isn't given (the +/// bounds without an extent, the cell size without a cellSize) is worked out by [`GridSpec::finish`], +/// which reads nothing of the session, so a command can do it where its work runs. +enum GridSpec { + /// Another raster's grid, taken exactly. + Fixed(warp::Grid), + Build { + crs: Crs, + cell: Option<(f64, f64)>, + origin: (f64, f64), + bounds: Option, + }, +} + +/// A grid's extent as given: a box in its system, or a polygon layer's features, whose bounds are +/// worked out by [`GridSpec::finish`] (where the command's work runs: they grow with the layer). +enum Bounds { + Given([f64; 4]), + /// Its selected features (`rows`), or all of them (`None`). + Layer { + name: String, + dataset: rustgis_data::Dataset, + rows: Option>, + }, +} + +impl Bounds { + /// In `crs`; what it has to say (an extent layer's vertices that can't be placed) goes to + /// `notes`. + fn in_crs(self, crs: Crs, notes: &mut Notes) -> Result<[f64; 4], String> { + match self { + Bounds::Given(b) => Ok(b), + Bounds::Layer { name, dataset, rows } => { + let rows: Box> = match rows { + Some(rows) => Box::new(rows.into_iter()), + None => Box::new(0..dataset.features.len()), + }; + // Each vertex converted as `lonlat_extent_of` does it, Cancel looked at every few + // thousand features and vertices. + let to = dataset.lonlat_conversion()?; + let (mut e, mut seen, mut unplaced) = (Extent::EMPTY, 0usize, 0usize); + let mut cancelled = None; + for row in rows { + if seen.is_multiple_of(4096) { + rustgis_data::progress::check().map_err(|e| e.to_string())?; + } + seen += 1; + let Some(g) = dataset.features.geometry(row) else { continue }; + if to.is_identity() { + e = e.union(&g.extent()); + continue; + } + g.for_each_coord(|c| { + seen += 1; + if cancelled.is_some() + || (seen.is_multiple_of(4096) + && rustgis_data::progress::check().map_err(|e| cancelled = Some(e.to_string())).is_err()) + { + return; + } + // A missing coordinate (NaN) is no vertex to place. + match to.point(c) { + Some(l) => e.expand(l), + None if c.is_finite() => unplaced += 1, + None => {} + } + }); + if let Some(c) = cancelled { + return Err(c); + } + } + if unplaced > 0 { + notes.push(( + format!( + "{name}: {unplaced} {} that can't be placed in longitude/latitude {} left out of the grid's extent: check {} coordinates and the layer's coordinate system", + if unplaced == 1 { "vertex" } else { "vertices" }, + if unplaced == 1 { "was" } else { "were" }, + if unplaced == 1 { "its" } else { "their" } + ), + false, + )); + } + if e.is_empty() { + return Err(if unplaced > 0 { + format!("{name} has no vertex that can be placed in longitude/latitude to take an extent from") + } else { + format!("{name} has no features to take an extent from") + }); + } + warp::bounds_in([e.min_x, e.min_y, e.max_x, e.max_y], crs) + } + } + } +} + +impl GridSpec { + /// The grid: `natural` gives, in its system, the bounds taken without an extent and the cell + /// size taken without a cellSize (`None`: a cellSize is required); it is asked only when one of + /// them is missing. + fn finish(self, notes: &mut Notes, natural: impl FnOnce(Crs) -> Result<([f64; 4], Option), String>) -> Result { + match self { + GridSpec::Fixed(g) => Ok(g), + GridSpec::Build { crs, cell, origin, bounds } => { + let bounds = bounds.map(|b| b.in_crs(crs, notes)).transpose()?; + let (bounds, cell) = match (bounds, cell) { + (Some(b), Some(c)) => (b, c), + (b, c) => { + let (footprint, pixel) = natural(crs)?; + let cell = c + .or(pixel.map(|c| (c, c))) + .ok_or("cellSize is required: a number, or [x, y], in the output's units, or a grid")?; + (b.unwrap_or(footprint), cell) + } + }; + warp::Grid::snapped(crs, bounds, cell, origin) + } + } + } +} + +/// The grid `p` gives ([`grid_param`]), with what to say of it (a template read from its overview). +fn grid_spec(s: &Session, p: &Value, crs: Crs) -> Result<(GridSpec, Notes), String> { + let mut notes = Vec::new(); + // A refusal says what was to be said before it (a typed system's warning). + match grid_spec_noting(s, p, crs, &mut notes) { + Ok(spec) => Ok((spec, notes)), + Err(e) => Err(with_notes(e, ¬es)), + } +} + +fn grid_spec_noting(s: &Session, p: &Value, crs: Crs, notes: &mut Notes) -> Result { // A grid named as anything but a raster layer's name is refused rather than ignored. let template = project_grid(p)?; - Ok(match template { + let spec = match template { Some(template) => { if ["crs", "cellSize", "origin", "extent"].iter().any(|k| p.get(*k).is_some_and(|v| !v.is_null())) { return Err( @@ -777,24 +1056,24 @@ fn grid_param( let t = raster_named(s, template)?; t.require_coordinates()?; if let Some((fw, fh)) = t.overview { - s.notify(format!("{template}: the grid is its {} × {} overview's, of the {fw} × {fh} raster", t.width, t.height), false); + notes + .push((format!("{template}: the grid is its {} × {} overview's, of the {fw} × {fh} raster", t.width, t.height), false)); } - warp::Grid::of(&t) + GridSpec::Fixed(warp::Grid::of(&t)) } None => { - let crs = crs_param(s, p, "crs")?.unwrap_or(crs); - let (footprint, pixel) = natural(crs)?; + let (given, warning) = crs_param_read(p, "crs")?; + notes.extend(warning.map(|w| (w, true))); + let crs = given.unwrap_or(crs); let positive = |v: &Value| v.as_f64().filter(|c| c.is_finite() && *c > 0.0); let bad_cell = "cellSize is a positive number, or [x, y], in the output's units"; let cell = match p.get("cellSize") { - None | Some(Value::Null) => { - pixel.map(|c| (c, c)).ok_or("cellSize is required: a number, or [x, y], in the output's units, or a grid")? - } + None | Some(Value::Null) => None, Some(Value::Array(a)) => match a.as_slice() { - [x, y] => (positive(x).ok_or(bad_cell)?, positive(y).ok_or(bad_cell)?), + [x, y] => Some((positive(x).ok_or(bad_cell)?, positive(y).ok_or(bad_cell)?)), _ => return Err(bad_cell.into()), }, - Some(v) => positive(v).map(|c| (c, c)).ok_or(bad_cell)?, + Some(v) => Some(positive(v).map(|c| (c, c)).ok_or(bad_cell)?), }; let origin = match p.get("origin") { None | Some(Value::Null) => (0.0, 0.0), @@ -808,31 +1087,32 @@ fn grid_param( } }; let bounds = match p.get("extent") { - None | Some(Value::Null) => footprint, + None | Some(Value::Null) => None, Some(Value::String(_)) if project_extent_name(p).is_some() => { let l = project_extent_name(p).ok_or("extent layer is required")?; let layer = s.map().layer_by_name(l).filter(|l| l.raster.is_none()).ok_or_else(|| format!("no vector layer '{l}'"))?; - let rows: Vec = - if layer.selection.is_empty() { (0..layer.dataset.features.len()).collect() } else { layer.selection.clone() }; - let e = layer.rows_extent(rows); - if e.is_empty() { - return Err(format!("{l} has no features to take an extent from")); + // Read in place, it holds only the part in view: its bounds wouldn't be the layer's. + if layer.dataset.windowed { + return Err(format!("{l}: load all its features first (Layers › Load All Features)")); } - warp::bounds_in([e.min_x, e.min_y, e.max_x, e.max_y], crs)? + let rows = (!layer.selection.is_empty()).then(|| layer.selection.clone()); + // Its rows shared, not copied ([`Bounds::in_crs`] reads them). + Some(Bounds::Layer { name: l.to_string(), dataset: layer.dataset.clone(), rows }) } Some(v @ (Value::Array(_) | Value::String(_))) => { let area = super::catalogs::area(s, &json!({"bbox": v})).map_err(|e| e.replacen("bbox", "extent", 1))?; if area[0] > area[2] { return Err("an extent across the antimeridian: give it one side at a time".into()); } - warp::bounds_in(area, crs)? + Some(Bounds::Given(warp::bounds_in(area, crs)?)) } // A number, a flag or an object isn't an extent: refused, not read as the view. Some(_) => return Err(EXTENT.into()), }; - warp::Grid::snapped(crs, bounds, cell, origin)? + GridSpec::Build { crs, cell, origin, bounds } } - }) + }; + Ok(spec) } fn is_tif(path: &str) -> bool { diff --git a/crates/engine/src/cmd/raster.rs b/crates/engine/src/cmd/raster.rs index c62ef7ecfa..c7a430b938 100644 --- a/crates/engine/src/cmd/raster.rs +++ b/crates/engine/src/cmd/raster.rs @@ -1167,7 +1167,13 @@ pub(super) fn write_geotiff(r: &Raster, bi: usize, cog: bool, path: &str) -> Res } /// Builds the band instruction before combining the note with any caller-supplied path or name. -fn write_geotiff_with_guidance(r: &Raster, bi: usize, cog: bool, path: &str, band_hint: &str) -> Result { +pub(super) fn write_geotiff_with_guidance( + r: &Raster, + bi: usize, + cog: bool, + path: &str, + band_hint: &str, +) -> Result { let cog = if cog { // Tiles go to the file as they are made: the whole file is never held in memory. Some(raster::cogwrite::write_file(r, bi, Path::new(path)).map_err(|e| format!("{path}: {e}"))?) @@ -1176,6 +1182,29 @@ fn write_geotiff_with_guidance(r: &Raster, bi: usize, cog: bool, path: &str, ban rustgis_data::io::write_atomic(Path::new(path), &bytes).map_err(|e| format!("{path}: {e}"))?; None }; + wrote_geotiff(r, bi, path, cog, band_hint) +} + +/// [`write_geotiff_with_guidance`]'s Cloud Optimized GeoTIFF, written beside `path` and put in +/// its place when the returned file is committed (as a background run's raster is added). +pub(super) fn write_cog_staged( + r: &Raster, + bi: usize, + path: &str, + band_hint: &str, +) -> Result<(super::exports::Wrote, rustgis_data::io::StagedWrite), String> { + let (cog, staged) = raster::cogwrite::write_staged(r, bi, Path::new(path)).map_err(|e| format!("{path}: {e}"))?; + Ok((wrote_geotiff(r, bi, path, Some(cog), band_hint)?, staged)) +} + +/// What writing `r`'s band `bi` to `path` says. +fn wrote_geotiff( + r: &Raster, + bi: usize, + path: &str, + cog: Option, + band_hint: &str, +) -> Result { let note = geotiff_note(r, bi, cog.is_some(), band_hint)?; let mut v = match r.overview { Some((fw, fh)) => json!({"path": path, "width": r.width, "height": r.height, "overviewOf": [fw, fh]}), diff --git a/crates/engine/src/cmd/workflows.rs b/crates/engine/src/cmd/workflows.rs index b5c3e85dd4..456b7e43e8 100644 --- a/crates/engine/src/cmd/workflows.rs +++ b/crates/engine/src/cmd/workflows.rs @@ -143,6 +143,18 @@ pub struct Made { /// Made on another thread: the command's name and the map it was started on. ran: Option<(&'static str, u64)>, pub(crate) continuation: Option, + /// The file the work wrote, put in its place as the raster is added: a run cancelled or + /// abandoned before then leaves the file there as it was. + staged: Option<(rustgis_data::io::StagedWrite, Vec)>, +} + +impl Made { + /// With `file` to commit as it is added; `said`, what the run had to say, goes with the + /// error when it can't be (its `then` doesn't run). + pub(crate) fn committing(mut self, file: rustgis_data::io::StagedWrite, said: Vec) -> Made { + self.staged = Some((file, said)); + self + } } /// A workflow's work once its inputs are read: it reads nothing more of the session, so it runs on @@ -170,13 +182,17 @@ pub(crate) fn made_then(raster: Raster, extra: Option, then: Option /// A layer made (styled, say), to be added as `name`. pub(crate) fn made_layer(name: String, layer: rustgis_map::RasterLayer, extra: Option, then: Option) -> Made { - Made { name, layer, extra, then, ran: None, continuation: None, inputs: Vec::new() } + Made { name, layer, extra, then, ran: None, continuation: None, inputs: Vec::new(), staged: None } } /// Adds a made raster as a layer: the command's answer is the layer's (its id, size and bands) and /// what the command says besides (`extra`), and what it does then. pub(crate) fn add_made(s: &mut Session, m: Made) -> CmdResult { - let Made { name, layer, extra, then, inputs, .. } = m; + let Made { name, layer, extra, then, inputs, staged, .. } = m; + if let Some((file, said)) = staged { + let path = file.destination().display().to_string(); + file.commit().map_err(|e| if said.is_empty() { format!("{path}: {e}") } else { format!("{path}: {e} ({})", said.join("; ")) })?; + } rustgis_data::provenance::record(inputs); let mut v = super::raster::add_raster(s, &name, layer)?; if let (Some(Value::Object(more)), Some(o)) = (extra, v.as_object_mut()) { @@ -237,6 +253,7 @@ pub(crate) const IN_BACKGROUND: &[(&str, &str, Start)] = &[ ("stac.addBands", "Add STAC Bands", super::stac_bands::bands_work), ("stac.addIndex", "Add STAC Index", super::stac_bands::index_work), ("raster.process", "Process", super::imagery::process_work), + ("raster.rasterize", "Polygons to Raster", super::imagery::rasterize_work), ("imagery.mosaic", "Build Mosaic", super::imagery::mosaic_work), ("dl.classify", "Deep Learning", super::deeplearning::classify_work), ("embeddings.similarity", "Satellite Embedding Similarity", super::embeddings::similarity_work), diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 79cb03ee8c..49fa863648 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -28768,6 +28768,45 @@ fn raster_export_paths_report_band_class_and_credit_changes() { std::fs::remove_dir_all(dir).unwrap(); } +/// Given both an extent and a cellSize, Project Raster takes the grid as given: a source whose +/// footprint can't be placed whole in the output's system (the whole world in the south polar +/// stereographic one, which can't hold the North Pole) is projected onto it, where without them it +/// is refused for want of a footprint. +#[test] +fn raster_project_takes_a_given_grid_without_the_sources_footprint() { + use rustgis_data::raster::{ColorHint, Crs, GeoTransform, Raster}; + use rustgis_data::{Coord, Dataset, Geometry, GeometryType}; + let mut s = Session::new(Project::default()); + let gt = GeoTransform { origin_x: -180.0, origin_y: 90.0, pixel_width: 10.0, pixel_height: -10.0 }; + let r = Raster::new("World", 36, 18, vec![vec![1.0; 36 * 18]], gt, Crs::LonLat, None, ColorHint::Gray, "Float32").unwrap(); + let bytes = rustgis_data::raster::geotiff::write(&r, 0).unwrap(); + crate::cmd::raster::add_raster(&mut s, "World", rustgis_map::RasterLayer::from_bytes(r, "World.tif".to_string(), bytes)).unwrap(); + let e = s.run("raster.project", &json!({"layer": "World", "crs": 3031})).unwrap_err(); + assert!(e.contains("can't be placed in"), "{e}"); + let v = s.run("raster.project", &json!({"layer": "World", "crs": 3031, "extent": [-180, -90, 180, -60], "cellSize": 500_000})).unwrap(); + assert!(v["width"].as_u64().is_some_and(|w| w > 0), "{v}"); + // An extent layer read in place (only the part in view) is refused, as for Polygons to Raster. + let mut part = Dataset::new("part", GeometryType::Polygon, vec![]); + part.push( + Some(Geometry::Polygon(vec![vec![vec![ + Coord::new(0.0, -80.0), + Coord::new(10.0, -80.0), + Coord::new(10.0, -70.0), + Coord::new(0.0, -80.0), + ]]])), + vec![], + ); + part.windowed = true; + crate::cmd::layer::add_dataset(&mut s, part); + let e = s.run("raster.project", &json!({"layer": "World", "crs": 3031, "extent": "part", "cellSize": 500_000})).unwrap_err(); + assert!(e.contains("part: load all its features first"), "{e}"); + // The whole world reaches every cell of the grid, as projected: each takes its value. + let id = v["layer"].as_u64().unwrap() as u32; + let out = s.map().layer(id).and_then(|l| l.raster.as_ref()).and_then(|r| r.data.clone()).unwrap(); + assert_eq!(out.crs, rustgis_data::raster::Crs::from_epsg(3031).unwrap()); + assert!(out.bands[0].data.iter().all(|c| *c == 1.0), "{:?}", &out.bands[0].data[..8]); +} + /// Class labels describe source values; interpolating or averaging those values drops the labels /// with a notice, while nearest, mode and palette-safe sampling retain them. #[test] @@ -51068,6 +51107,32 @@ fn polygons_burned_onto_a_chosen_grid() { assert!(e.contains("cellSize is required"), "{e}"); let e = s.run("raster.rasterize", &json!({"layer": "soils", "nodata": 1, "cellSize": 1})).unwrap_err(); assert!(e.contains("no-data value"), "{e}"); + // An extent layer read in place holds only the part in view: refused before the run. + let mut part = Dataset::new("part", GeometryType::Polygon, vec![Field::new("unit", FieldType::Text)]); + part.push(Some(Geometry::Polygon(vec![vec![ring(0.0, 0.0, 1.0, 1.0)]])), vec![V::Text("x".into())]); + part.windowed = true; + crate::cmd::layer::add_dataset(&mut s, part); + let e = s.run("raster.rasterize", &json!({"layer": "soils", "field": "unit", "cellSize": 1, "extent": "part"})).unwrap_err(); + assert!(e.contains("part: load all its features first"), "{e}"); + let layers = layers + 1; + // An extent layer with no features: refused (as the run sizes its grid), nothing added. + crate::cmd::layer::add_dataset(&mut s, Dataset::new("nothing", GeometryType::Polygon, vec![Field::new("unit", FieldType::Text)])); + let e = s.run("raster.rasterize", &json!({"layer": "soils", "field": "unit", "cellSize": 1, "extent": "nothing"})).unwrap_err(); + assert!(e.contains("nothing has no features to take an extent from"), "{e}"); + let layers = layers + 1; + assert_eq!((s.map().layers.len(), s.project.tables.len()), (layers, tables), "nothing added by a refused run"); + // A GeoTIFF that can't be put in its place (a folder holds its name): refused, with what the + // run had to say, and nothing added. + let dir = std::env::temp_dir().join(format!("rustgis-rasterize-commit-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let taken = dir.join("soils.tif"); + std::fs::create_dir_all(taken.join("inside")).unwrap(); + let e = + s.run("raster.rasterize", &json!({"layer": "soils", "field": "unit", "cellSize": 1, "path": taken.to_string_lossy()})).unwrap_err(); + assert!(e.contains("soils.tif") && e.contains("features skipped: 1 with no value"), "{e}"); + assert_eq!((s.map().layers.len(), s.project.tables.len()), (layers, tables), "nothing added by a refused run"); + assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 1, "the staged file is removed"); + std::fs::remove_dir_all(dir).unwrap(); } /// A whole number past what a pixel holds is refused with advice that applies: a numeric field can @@ -51239,6 +51304,8 @@ fn raster_tools_run_on_another_thread() { ("raster.process", json!({"layer": dem, "operation": "clip", "extent": [10.005, 45.005, 10.02, 45.02]})), ("raster.process", json!({"layer": dem, "operation": "resample", "factor": 4})), ("imagery.mosaic", json!({"name": "Valley"})), + ("raster.rasterize", json!({"layer": "Training", "value": 3, "cellSize": 0.0005})), + ("raster.rasterize", json!({"layer": "Training", "field": "name", "cellSize": 0.0005})), ] { assert!(runs_in_background(command).is_some(), "{command}"); let here = s.run(command, &p).unwrap(); @@ -51250,10 +51317,30 @@ fn raster_tools_run_on_another_thread() { with["ran"] = json!(id); let there = s.run(command, &with).unwrap(); assert_eq!(pixels(&s, &here), pixels(&s, &there), "{command} {p}"); + // The layer, and the names that follow its own (the first run's layer holds the one asked + // for): a class table named after it is there. + let named = ["layer", "name", "classTable"]; let besides = |v: &Value| { - v.as_object().map(|o| o.iter().filter(|(k, _)| *k != "layer").map(|(k, v)| (k.clone(), v.clone())).collect::>()) + v.as_object() + .map(|o| o.iter().filter(|(k, _)| !named.contains(&k.as_str())).map(|(k, v)| (k.clone(), v.clone())).collect::>()) }; assert_eq!(besides(&here), besides(&there), "{command} {p}"); + // Each run gives the layer's id, and says the names as text, or neither: only their + // values differ. + assert!(here["layer"].is_u64() && there["layer"].is_u64(), "{command}: {here} {there}"); + for key in ["name", "classTable"] { + let said = |v: &Value| v.get(key).map(|n| n.as_str().map(|_| ()).ok_or(())); + assert_eq!(said(&here), said(&there), "{command} {key}: {here} {there}"); + assert_ne!(said(&here), Some(Err(())), "{command} {key} is not text: {here}"); + } + // A name said is the one the layer got. + if let Some(name) = there["name"].as_str() { + let id = there["layer"].as_u64().unwrap() as u32; + assert_eq!(Some(name), s.map().layer(id).map(|l| l.name.as_str()), "{command}: {there}"); + } + if let Some(table) = there["classTable"].as_str() { + assert!(s.project.tables.iter().any(|t| t.name == table), "{command}: {table}"); + } // The answer is the added layer's, whatever else the command says. assert!(there["width"].is_u64() && there["bands"].is_u64(), "{command}: {there}"); let run = raster_start(&mut s, command, &p).unwrap(); diff --git a/crates/engine/src/tests/cancellation.rs b/crates/engine/src/tests/cancellation.rs index cb485791e5..6f73c42e6e 100644 --- a/crates/engine/src/tests/cancellation.rs +++ b/crates/engine/src/tests/cancellation.rs @@ -86,6 +86,7 @@ pub(super) fn long_commands(boundaries: bool) { ("raster.index", json!({"layer": dem, "index": "ndvi", "nir": 1, "red": 1})), ("raster.process", json!({"layer": dem, "operation": "resample", "factor": 4})), ("imagery.mosaic", json!({"name": "Valley"})), + ("raster.rasterize", json!({"layer": "Squares", "field": "name", "cellSize": 0.0005, "path": out("burned.tif")})), ( "dl.classify", json!({"layer": "scene", "training": "training", "classField": "class", "bands": [1, 2], "epochs": if boundaries { 2 } else { 30 }, "model": "landcover"}), diff --git a/crates/engine/src/tests/held_layers.rs b/crates/engine/src/tests/held_layers.rs index ebc32a91ac..f555191b69 100644 --- a/crates/engine/src/tests/held_layers.rs +++ b/crates/engine/src/tests/held_layers.rs @@ -2435,6 +2435,75 @@ fn rasterize_sizes_its_grid_by_the_operation_that_burns() { assert!((16..=36).contains(&a["cells"].as_u64().unwrap()), "{a}"); } +/// Rasterize's default grid is the system a layer holds its coordinates in only when that is a +/// projected one: a layer held in ETRS89 degrees (EPSG:4258), read from a file in UTM 32N, is +/// burned onto a grid in UTM 32N. +#[test] +fn a_layer_held_in_degrees_is_burned_in_the_system_it_was_read_in() { + let geographic = Crs::Epsg(4258); + let ring: Vec = + [(11.0, 48.0), (11.01, 48.0), (11.01, 48.01), (11.0, 48.01), (11.0, 48.0)].iter().map(|(x, y)| Coord::new(*x, *y)).collect(); + let mut s = Session::new(Project::default()); + add_in(&mut s, "Plot", GeometryType::Polygon, vec![Geometry::Polygon(vec![vec![ring.clone()]])], geographic); + let id = s.map().layer_by_name("Plot").unwrap().id; + s.map_mut().layer_mut(id).unwrap().dataset.crs = Some(UTM); + let v = s.run("raster.rasterize", &json!({"layer": "Plot", "cellSize": 10, "name": "Burned"})).unwrap(); + let r = grid_of(&s, "Burned"); + assert_eq!(r.crs, UTM); + // The grid holds the corners as converted into UTM, within a cell of them. + let to = geographic.to(UTM).unwrap(); + let corners: Vec = ring.iter().map(|c| to.point(*c).unwrap()).collect(); + let mut b = rustgis_geom::Extent::EMPTY; + corners.iter().for_each(|c| b.expand(*c)); + let t = r.transform; + let e = rustgis_geom::Extent { + min_x: t.origin_x, + max_y: t.origin_y, + max_x: t.origin_x + t.pixel_width * f64::from(r.width), + min_y: t.origin_y + t.pixel_height * f64::from(r.height), + }; + assert!(e.min_x <= b.min_x && e.min_y <= b.min_y && e.max_x >= b.max_x && e.max_y >= b.max_y, "{e:?} {b:?}"); + assert!(b.min_x - e.min_x < 10.0 && b.min_y - e.min_y < 10.0 && e.max_x - b.max_x < 10.0 && e.max_y - b.max_y < 10.0, "{e:?} {b:?}"); + // And it burns about the polygon's area in UTM (some 830,000 m²) in 10 m cells. + let area = corners.windows(2).map(|w| w[0].x * w[1].y - w[1].x * w[0].y).sum::().abs() / 2.0; + let cells = v["cells"].as_f64().unwrap(); + assert!((cells * 100.0 / area - 1.0).abs() < 0.03, "{cells} cells for {area} m²"); +} + +/// An extent layer with a vertex that can't be placed in longitude/latitude sizes the grid +/// without it, and says so; clean input says nothing. +#[test] +fn an_extent_layers_unplaced_vertices_are_said() { + let (x0, y0) = (784_000.0, 5_401_300.0); + let square: Vec = + [(0.0, 0.0), (1000.0, 0.0), (1000.0, 1000.0), (0.0, 1000.0), (0.0, 0.0)].iter().map(|(x, y)| Coord::new(x0 + x, y0 + y)).collect(); + let far = vec![Coord::new(x0, y0), Coord::new(1e12, 1e12), Coord::new(x0, y0 + 500.0), Coord::new(x0, y0)]; + let mut s = Session::new(Project::default()); + add_in(&mut s, "Plot", GeometryType::Polygon, vec![Geometry::Polygon(vec![vec![square.clone()]])], UTM); + add_in(&mut s, "Clean", GeometryType::Polygon, vec![Geometry::Polygon(vec![vec![square]])], UTM); + add_in(&mut s, "Odd", GeometryType::Polygon, vec![Geometry::Polygon(vec![vec![far]])], UTM); + let said = |s: &Session, mark| s.notices_since(mark).iter().map(|n| n.text.clone()).collect::>(); + let mark = s.notice_mark(); + s.run("raster.rasterize", &json!({"layer": "Plot", "cellSize": 0.001, "crs": "EPSG:4326", "extent": "Clean", "name": "A"})).unwrap(); + assert!(said(&s, mark).iter().all(|n| !n.contains("left out of the grid's extent")), "{:?}", said(&s, mark)); + let mark = s.notice_mark(); + s.run("raster.rasterize", &json!({"layer": "Plot", "cellSize": 0.001, "crs": "EPSG:4326", "extent": "Odd", "name": "B"})).unwrap(); + assert!( + said(&s, mark) + .iter() + .any(|n| n.starts_with("Odd: 1 vertex that can't be placed in longitude/latitude was left out of the grid's extent")), + "{:?}", + said(&s, mark) + ); + // Only vertices that can't be placed: refused, saying so, not that it has no features. + let nowhere = vec![Coord::new(1e12, 1e12), Coord::new(2e12, 1e12), Coord::new(2e12, 2e12), Coord::new(1e12, 1e12)]; + add_in(&mut s, "Nowhere", GeometryType::Polygon, vec![Geometry::Polygon(vec![vec![nowhere]])], UTM); + let e = s + .run("raster.rasterize", &json!({"layer": "Plot", "cellSize": 0.001, "crs": "EPSG:4326", "extent": "Nowhere", "name": "C"})) + .unwrap_err(); + assert!(e.contains("Nowhere has no vertex that can be placed in longitude/latitude"), "{e}"); +} + /// Rasterize sizes its default grid in another system by the polygons' box in longitude/latitude, /// and says how many vertices it couldn't place there, left out of that box: a polygon held in UTM /// with a vertex far beyond any place UTM holds, burned onto a grid in degrees. With an extent diff --git a/crates/ui-egui/src/analysispane.rs b/crates/ui-egui/src/analysispane.rs index 6d5de24b21..21dbef2895 100644 --- a/crates/ui-egui/src/analysispane.rs +++ b/crates/ui-egui/src/analysispane.rs @@ -380,6 +380,27 @@ fn background(id: &str) -> Option<(&'static str, &'static str)> { } } +/// Starts a command that makes a raster (`workflows::runs_in_background`) asked for outside the +/// pane through the app's dispatch (Command Search): on a thread of its own, the Workflows pane +/// opened to show its progress and Cancel, as from a section; its layer is added when it lands, a +/// failure then said in the status bar. The answer says it started; one that can't start (another +/// is under way) is an error. +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn start_from_dispatch(app: &mut RustGisApp, command: &'static str, name: &'static str, p: Value) -> Result { + // Its result is shown in the section the pane shows as it starts (the first, when it never + // opened), as a run from that section's would be. + settle_section(app); + start(app, command, name, p); + match &app.workflow.job { + Some(job) if job.name == name && app.workflow.error.is_none() => { + // Opened, not toggled: a pane already open stays so; one that didn't start doesn't open it. + app.ui.open_right(crate::RightPane::Workflows); + Ok(json!({"started": name})) + } + _ => Err(app.workflow.error.clone().unwrap_or_else(|| crate::i18n::fmt("{tool} didn't start", &[("tool", tl_raw!(name))]))), + } +} + /// Starts `command` on a thread of its own; [`land_job`] applies what it made. One at a time: a /// second waits for the first to finish or be cancelled. #[cfg(not(target_arch = "wasm32"))] @@ -467,7 +488,20 @@ pub fn land_job(app: &mut RustGisApp) -> bool { return true; } let Some(job) = app.workflow.job.take() else { return false }; + // Cancelled once its work was done, before it landed (in the frame between): dropped, so + // nothing is added, and a file it wrote beside its destination is removed. + let cancelled = || Err(crate::i18n::fmt("{tool} was cancelled", &[("tool", tl_raw!(job.name))])); match job.kind { + JobKind::Tool { id, slot } if job.control.is_cancelled() => { + drop(take(&slot)); + gp::tool_abandon(&mut app.session, id); + show_job(app, job.section, cancelled()); + } + JobKind::Raster { id, slot, .. } if job.control.is_cancelled() => { + drop(take(&slot)); + workflows::raster_abandon(&mut app.session, id); + show_job(app, job.section, cancelled()); + } JobKind::Tool { id, slot } => { let Some(done) = take(&slot) else { return false }; let r = gp::tool_complete(&mut app.session, id, done).and_then(|_| app.finish_gp(id)); @@ -631,10 +665,9 @@ fn picked(app: &mut RustGisApp, purpose: &str) -> Option