diff --git a/crates/engine/src/cmd/deeplearning.rs b/crates/engine/src/cmd/deeplearning.rs index 6e368969cd..c73c7e4740 100644 --- a/crates/engine/src/cmd/deeplearning.rs +++ b/crates/engine/src/cmd/deeplearning.rs @@ -183,7 +183,9 @@ fn train(s: &Session, p: &Value) -> Result<(DlModel, super::whole::Unread), Stri /// training layer is read whole and the pixels under its polygons sampled there, as the network /// learns). struct Training { - raster: std::sync::Arc, + /// Read as the model is fitted: from its file, for a layer read in place from one, in a + /// classification's run. + raster: super::workflows::Input, bands: Vec, /// The training layer's rows, read whole in [`Training::fit`]. rows: super::whole::Whole, @@ -204,6 +206,7 @@ impl Training { fn fit(self) -> Result<(DlModel, super::whole::Unread), String> { let Training { raster, bands, rows, field, hidden, epochs, name, .. } = self; let (ds, unread) = rows.read()?; + let raster = raster.read()?; let model = Self::learn(&ds, field, &raster, &bands, &hidden, epochs, name).map_err(|e| unread.explain(e))?; Ok((model, unread)) } @@ -269,9 +272,9 @@ fn training_polygons(ds: &rustgis_data::Dataset, fi: usize) -> Result<(Vec Result { - let r = raster(s, p)?; - r.require_coordinates()?; - let bands = bands_param(p, &r)?; + let r = super::imagery::input(s, p)?; + r.held().require_coordinates()?; + let bands = bands_param(p, r.held())?; let tl = super::imagery::training_name(p)?; let l = s .map() @@ -299,7 +302,7 @@ fn training(s: &Session, p: &Value) -> Result { let (name, auto) = match ps(p, "model").map(str::trim).filter(|m| !m.is_empty()) { Some(m) => (super::within("model", "a model's name", m, 200)?, None), None => { - let base = format!("{}_model", r.name); + let base = format!("{}_model", r.held().name); (free_name(s, &base), Some(base)) } }; @@ -332,16 +335,17 @@ enum Model { /// trains one), and the work that trains the model if need be and classifies the pixels. A model /// trained is kept in the project once the classes are added. pub(crate) fn classify_work(s: &Session, p: &Value) -> Result { - let r = raster(s, p)?; - r.require_coordinates()?; + let r = super::imagery::input(s, p)?; + r.held().require_coordinates()?; let model = if p.get("training").is_some() { Model::Train(training(s, p)?) } else { let i = model_index(s, p)?; Model::Saved(s.project.dl_models.get(i).cloned().ok_or("no model")?) }; - let out = name(p, format!("{}_dl", r.name))?; + let out = name(p, format!("{}_dl", r.held().name))?; Ok(Box::new(move || { + let r = r.read()?; let (m, trained) = match model { Model::Saved(m) => (m, None), Model::Train(t) => { diff --git a/crates/engine/src/cmd/gp.rs b/crates/engine/src/cmd/gp.rs index ab4184b26c..18451b5b71 100644 --- a/crates/engine/src/cmd/gp.rs +++ b/crates/engine/src/cmd/gp.rs @@ -1562,7 +1562,7 @@ pub(crate) fn tiled_inputs( // reads no pixels through the run's inputs. let Some(spec) = spec.filter(|t| t.id != "rasterToPmtiles") else { return Ok(read) }; let mut seen = std::collections::HashSet::new(); - let (mut overviews, mut held_overviews, mut rounded) = (Vec::new(), Vec::new(), Vec::new()); + let (mut said, mut held_overviews) = (Vec::new(), Vec::new()); for parameter in spec.params { let value = params.get(parameter.name).unwrap_or(&Value::Null); let names: Vec<&str> = match parameter.kind { @@ -1613,47 +1613,9 @@ pub(crate) fn tiled_inputs( } continue; } - // A batch's read is used again only while the file is the revision it was read at. - let revision = file_revisions(std::path::Path::new(path)); - let kept = BATCH_READS.with(|b| b.borrow().as_ref().and_then(|reads| reads.get(path).cloned())); - let (r, count) = match kept.filter(|(.., at)| revision.is_some() && *at == revision) { - Some((r, count, _)) => (r, count), - None => { - #[cfg(test)] - TILED_READS.with(|n| n.set(n.get() + 1)); - // The last file a batch read alone: let go before another is read, so a batch - // over several files holds one, and doesn't hold it uncounted while the next - // is planned. - BATCH_READS.with(|b| { - if let Some(reads) = b.borrow_mut().as_mut() { - reads.clear(); - } - }); - let _turn = tiled_turn().map_err(|e| format!("{}: {e}", l.name))?; - let r = std::sync::Arc::new( - rustgis_data::raster::read_path_with(std::path::Path::new(path), None, None) - .map_err(|e| format!("{}: {e}", l.name))?, - ); - // Counted as held from before the next run's turn, for as long as anything - // (this run, the batch) holds it. - let bytes: usize = r.bands.iter().map(|b| b.data.len().saturating_mul(4)).sum(); - let count = std::sync::Arc::new(rustgis_data::memory::Holding::of(bytes as u64)); - BATCH_READS.with(|b| { - if let Some(reads) = b.borrow_mut().as_mut() { - reads.insert(path.to_string(), (r.clone(), count.clone(), revision.clone())); - } - }); - (r, count) - } - }; + let (r, count) = read_tiled(&l.name, path)?; held.push(count); - let n: u64 = r.rounded.iter().sum(); - if n > 0 { - rounded.push(format!("{} {n}", l.name)); - } - if let Some((fw, fh)) = r.overview { - overviews.push(format!("{} at its {} × {} overview of the {fw} × {fh} raster", l.name, r.width, r.height)); - } + said.push((l.name.clone(), r.clone())); read.insert(key, r); } } @@ -1664,16 +1626,80 @@ pub(crate) fn tiled_inputs( held_overviews.join("; ") )); } + messages.extend(tiled_read_notes(&said, "the tool's")); + Ok(read) +} + +/// What a run says of the raster files read in place it read again from their file +/// ([`read_tiled`]), each with its layer's name: one notice of each kind, naming each raster. +/// `whose` says whose results are built on values rounded as they were read. +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn tiled_read_notes(read: &[(String, std::sync::Arc)], whose: &str) -> Vec { + let (mut rounded, mut overviews) = (Vec::new(), Vec::new()); + for (name, r) in read { + let n: u64 = r.rounded.iter().sum(); + if n > 0 { + rounded.push(format!("{name} {n}")); + } + if let Some((fw, fh)) = r.overview { + overviews.push(format!("{name} at its {} × {} overview of the {fw} × {fh} raster", r.width, r.height)); + } + } + let mut notes = Vec::new(); if !rounded.is_empty() { - messages.push(format!( - "values rounded to 32-bit floats as the file was read for the run, the tool's results built on them: {}", + notes.push(format!( + "values rounded to 32-bit floats as the file was read for the run, {whose} results built on them: {}", rounded.join("; ") )); } if !overviews.is_empty() { - messages.push(format!("read at the finest level each can hold: {}", overviews.join("; "))); + notes.push(format!("read at the finest level each can hold: {}", overviews.join("; "))); } - Ok(read) + notes +} + +/// The raster file read in place at `path` (layer `name`'s), read again from the file at the +/// finest level the run can hold, with its count in [`rustgis_data::memory::held`]: a batch's +/// read of it while the file is unchanged ([`BATCH_READS`]), else read now, in its turn +/// ([`tiled_turn`]). The GeoTIFF reader looks at Cancel between its chunks through the progress +/// probe the run installed. +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn read_tiled( + name: &str, + path: &str, +) -> Result<(std::sync::Arc, std::sync::Arc), String> { + // A batch's read is used again only while the file is the revision it was read at. + let revision = file_revisions(std::path::Path::new(path)); + let kept = BATCH_READS.with(|b| b.borrow().as_ref().and_then(|reads| reads.get(path).cloned())); + let (r, count) = match kept.filter(|(.., at)| revision.is_some() && *at == revision) { + Some((r, count, _)) => (r, count), + None => { + #[cfg(test)] + TILED_READS.with(|n| n.set(n.get() + 1)); + // The last file a batch read alone: let go before another is read, so a batch over + // several files holds one, and doesn't hold it uncounted while the next is planned. + BATCH_READS.with(|b| { + if let Some(reads) = b.borrow_mut().as_mut() { + reads.clear(); + } + }); + let _turn = tiled_turn().map_err(|e| format!("{name}: {e}"))?; + let r = std::sync::Arc::new( + rustgis_data::raster::read_path_with(std::path::Path::new(path), None, None).map_err(|e| format!("{name}: {e}"))?, + ); + // Counted as held from before the next run's turn, for as long as anything (this + // run, the batch) holds it. + let bytes: usize = r.bands.iter().map(|b| b.data.len().saturating_mul(4)).sum(); + let count = std::sync::Arc::new(rustgis_data::memory::Holding::of(bytes as u64)); + BATCH_READS.with(|b| { + if let Some(reads) = b.borrow_mut().as_mut() { + reads.insert(path.to_string(), (r.clone(), count.clone(), revision.clone())); + } + }); + (r, count) + } + }; + Ok((r, count)) } /// A raster file read in place for a run, its count in [`rustgis_data::memory::held`], which lasts diff --git a/crates/engine/src/cmd/imagery.rs b/crates/engine/src/cmd/imagery.rs index 27ce619cfd..07b00c94fb 100644 --- a/crates/engine/src/cmd/imagery.rs +++ b/crates/engine/src/cmd/imagery.rs @@ -136,6 +136,12 @@ pub(crate) fn raster(s: &Session, p: &Value) -> Result, String> { raster_named(s, raster_name(p)?) } +/// The raster layer `p` names, for a command that makes its raster in the background: a layer +/// read in place from a file is read from it as the work runs ([`super::workflows::Input`]). +pub(crate) fn input(s: &Session, p: &Value) -> Result { + super::workflows::Input::of(s, raster_name(p)?) +} + /// The output's name the parameters give, else `d`; one over 200 characters is refused (#1888). pub(crate) fn name(p: &Value, d: String) -> Result { match ps(p, "name").map(str::trim).filter(|n| !n.is_empty()) { @@ -186,8 +192,8 @@ pub(crate) fn class_layer(r: Raster) -> Result /// What the Classification Wizard (k-means) reads of the session, and the work that makes its /// classes. pub(crate) fn classify_work(s: &Session, p: &Value) -> Result { - let r = raster(s, p)?; - let bands = bands_param(p, &r)?; + let r = input(s, p)?; + let bands = bands_param(p, r.held())?; if bands.is_empty() { return Err("give at least one band".into()); } @@ -195,8 +201,9 @@ pub(crate) fn classify_work(s: &Session, p: &Value) -> Result 5, Some(_) => uint(p, "classes").filter(|k| (2..=50).contains(k)).ok_or("classes is 2 to 50")? as usize, }; - let out = name(p, format!("{}_classes", r.name))?; + let out = name(p, format!("{}_classes", r.held().name))?; Ok(Box::new(move || { + let r = r.read()?; let classes = rasterops::kmeans(&r, &bands, k, 20)?; let layer = class_layer(rasterops::derive(&r, &out, vec![classes])?)?; Ok(super::workflows::made_layer(out, layer, None, None)) @@ -1300,18 +1307,19 @@ fn change(s: &mut Session, p: &Value) -> CmdResult { /// What a change detection reads of the session, and the work that compares the rasters. pub(crate) fn change_work(s: &Session, p: &Value) -> Result { let [before, after] = change_names(p)?; - let a = raster_named(s, before)?; - let bfr = raster_named(s, after)?; + let a = super::workflows::Input::of(s, before)?; + let bfr = super::workflows::Input::of(s, after)?; // The method is checked before any pixels are resampled. let method = ps(p, "method").unwrap_or("difference").to_string(); if !matches!(method.as_str(), "difference" | "ratio" | "percent") { return Err(format!("unknown method '{method}'")); } let band = uint(p, "band").unwrap_or(1).saturating_sub(1) as usize; - a.bands.get(band).ok_or("no such band")?; - bfr.bands.get(band).ok_or_else(|| format!("{} has no band {}", bfr.name, band + 1))?; - let out_name = name(p, format!("{}_change", a.name))?; + a.held().bands.get(band).ok_or("no such band")?; + bfr.held().bands.get(band).ok_or_else(|| format!("{} has no band {}", bfr.held().name, band + 1))?; + let out_name = name(p, format!("{}_change", a.held().name))?; Ok(Box::new(move || { + let (a, bfr) = (a.read()?, bfr.read()?); let av = &a.bands.get(band).ok_or("no such band")?.data; let bv = rasterops::resample_to(&bfr, band, &a)?; // A cell either raster draws see-through has no colour to compare (#1810): the first's by @@ -1532,10 +1540,10 @@ fn supervised(s: &mut Session, p: &Value) -> CmdResult { /// What a classification from training polygons reads of the session (the raster, and each /// polygon with its class), and the work that classifies it. pub(crate) fn supervised_work(s: &Session, p: &Value) -> Result { - let r = raster(s, p)?; + let r = input(s, p)?; // Training polygons on the map mean nothing on a scan laid there to look at. - r.require_coordinates()?; - let bands = bands_param(p, &r)?; + r.held().require_coordinates()?; + let bands = bands_param(p, r.held())?; // With none, every pixel would be equally near every class. if bands.is_empty() { return Err("give at least one band".into()); @@ -1549,8 +1557,9 @@ pub(crate) fn supervised_work(s: &Session, p: &Value) -> Result Result { - let r = raster(s, p)?; + let r = input(s, p)?; let bn = |k: &str, d: u64| uint(p, k).unwrap_or(d); let (blue, green, red, nir, swir) = (bn("blue", 1), bn("green", 2), bn("red", 3), bn("nir", 4), bn("swir", 5)); let idx = ps(p, "index").ok_or("index is required")?; let expr = index_expression(idx, blue, green, red, nir, swir)?; - let out = name(p, format!("{}_{idx}", r.name))?; - Ok(Box::new(move || super::workflows::made(rasterops::derive(&r, &out, vec![rasterops::band_math(&r, &expr)?])?, None))) + let out = name(p, format!("{}_{idx}", r.held().name))?; + Ok(Box::new(move || { + let r = r.read()?; + super::workflows::made(rasterops::derive(&r, &out, vec![rasterops::band_math(&r, &expr)?])?, None) + })) } /// Processes a raster via clipping or resampling. @@ -1633,13 +1645,13 @@ fn process(s: &mut Session, p: &Value) -> CmdResult { /// What a clip or resample reads of the session (the raster, and the polygons or extent it is /// clipped to), and the work that makes it. pub(crate) fn process_work(s: &Session, p: &Value) -> Result { - let r = raster(s, p)?; + let r = input(s, p)?; match ps(p, "operation").ok_or("operation is required")? { "clip" if p.get("polygon").is_some_and(|v| !v.is_null()) => { // Before the mask, which places the polygons on the raster's coordinates. - r.require_coordinates()?; + r.held().require_coordinates()?; // A name over the limit is refused before any feature is transformed. - let out = name(p, format!("{}_clip", r.name))?; + let out = name(p, format!("{}_clip", r.held().name))?; let pl = clip_polygon(p).ok_or("polygon is a polygon layer's name")?; let l = s .map() @@ -1698,6 +1710,7 @@ pub(crate) fn process_work(s: &Session, p: &Value) -> Result Result { // Before the extent is placed on the raster's coordinates. - r.require_coordinates()?; + r.held().require_coordinates()?; let e = match p.get("extent").and_then(Value::as_array) { Some(a) => { let n: Vec = a.iter().filter_map(Value::as_f64).collect(); @@ -1740,26 +1753,25 @@ pub(crate) fn process_work(s: &Session, p: &Value) -> Result { // Never coarser than the raster itself; trailing columns and rows short of a full // block are left out. - r.require_coordinates()?; - let k = (uint(p, "factor").unwrap_or(2).clamp(2, 64) as u32).min(r.width.min(r.height)).max(1); - let (w, h) = ((r.width / k).max(1), (r.height / k).max(1)); - let out = name(p, format!("{}_resampled", r.name))?; + r.held().require_coordinates()?; + let factor = uint(p, "factor").unwrap_or(2).clamp(2, 64) as u32; + let out = name(p, format!("{}_resampled", r.held().name))?; Ok(Box::new(move || { + let r = r.read()?; + let k = factor.min(r.width.min(r.height)).max(1); + let (w, h) = ((r.width / k).max(1), (r.height / k).max(1)); // Each output pixel is the mean of the valid pixels it covers. let bands = r .bands @@ -1814,6 +1826,20 @@ pub(crate) fn process_work(s: &Session, p: &Value) -> Result Result<(std::ops::Range, std::ops::Range), String> { + let px = edge_pixels(r, e).ok_or("the extent can't be placed on the raster")?; + let c0 = px.iter().map(|p| p.0).fold(f64::INFINITY, f64::min).floor().max(0.0) as u32; + let c1 = px.iter().map(|p| p.0).fold(f64::NEG_INFINITY, f64::max).ceil().min(r.width as f64) as u32; + let r0 = px.iter().map(|p| p.1).fold(f64::INFINITY, f64::min).floor().max(0.0) as u32; + let r1 = px.iter().map(|p| p.1).fold(f64::NEG_INFINITY, f64::max).ceil().min(r.height as f64) as u32; + if c1 <= c0 || r1 <= r0 { + return Err("the extent doesn't overlap the raster".into()); + } + Ok((c0..c1, r0..r1)) +} + /// Most inputs a mosaic takes. const MAX_MOSAIC_INPUTS: usize = 10_000; diff --git a/crates/engine/src/cmd/workflows.rs b/crates/engine/src/cmd/workflows.rs index 8064246d61..b4f07fc9d9 100644 --- a/crates/engine/src/cmd/workflows.rs +++ b/crates/engine/src/cmd/workflows.rs @@ -112,12 +112,161 @@ fn feature_ds<'a>(s: &'a Session, p: &Value) -> Result<&'a Dataset, String> { Ok(&l.dataset) } -fn raster_of(s: &Session, name: &str) -> Result, String> { - s.map() - .layer_by_name(name) - .and_then(|l| l.raster.as_ref()) - .and_then(|r| r.data.clone()) - .ok_or_else(|| format!("no raster layer '{name}'")) +/// The raster layer named `name`, as a command that makes a raster reads it ([`Input`]). +fn raster_of(s: &Session, name: &str) -> Result { + Input::of(s, name) +} + +/// A raster layer a command that makes a raster reads ([`IN_BACKGROUND`]): the raster the layer +/// holds, which the command's start checks its parameters against, and for a layer read in place +/// from a file on this computer ([`rustgis_map::raster::RasterLayer::tiled`]), that file, read +/// again as the work runs ([`Input::read`]). Such a layer holds only the small overview the map +/// draws from zoomed out; the file has the same bands, extent and coordinate system, but more +/// pixels (#2761). +#[derive(Clone)] +pub(crate) struct Input { + held: std::sync::Arc, + /// The layer's name and its file, for one read in place from a file on this computer. + file: Option<(String, String)>, +} + +impl Input { + /// The raster layer named `name`. + pub(crate) fn of(input: &impl super::InputSource, name: &str) -> Result { + let context = input.input_context(); + let rl = context.map().layer_by_name(name).and_then(|l| Some((l, l.raster.as_ref()?))); + let (l, rl) = rl.ok_or_else(|| format!("no raster layer '{name}'"))?; + let held = rl.data.clone().ok_or_else(|| format!("no raster layer '{name}'"))?; + let file = rl.path.clone().filter(|_| rl.tiled).map(|path| (l.name.clone(), path)); + Ok(Input { held, file }) + } + + /// The raster the layer holds: for one read in place from a file, its overview, with the + /// file's bands, extent and system but not its size. Checked as the command starts. + pub(crate) fn held(&self) -> &Raster { + &self.held + } + + /// The raster the work reads: within a run ([`reading_files`]), a layer read in place from a + /// file on this computer is read again from it, at the finest level the run can hold (the + /// full image when it fits), once for the run however many inputs name it; otherwise, and for + /// any other layer, the raster the layer holds. + pub(crate) fn read(&self) -> Result { + #[cfg(not(target_arch = "wasm32"))] + if let Some((name, path)) = &self.file + && RUN_READS.with(|r| r.borrow().is_some()) + { + let kept = RUN_READS.with(|r| r.borrow().as_ref().and_then(|read| read.iter().find(|k| k.0 == *path).cloned())); + let (_, _, raster, count) = match kept { + Some(k) => k, + None => { + let (raster, count) = super::gp::read_tiled(name, path)?; + let k = (path.clone(), name.clone(), raster, count); + RUN_READS.with(|r| { + if let Some(read) = r.borrow_mut().as_mut() { + read.push(k.clone()); + } + }); + k + } + }; + return Ok(Read { raster, _count: Some(count) }); + } + // The browser has no files to read by path: none is read in place from one there. + #[cfg(target_arch = "wasm32")] + let _ = &self.file; + Ok(Read { raster: self.held.clone(), _count: None }) + } +} + +/// A raster a command's work reads ([`Input::read`]), counted in +/// [`rustgis_data::memory::held`] while it is held when it was read from its file. +pub(crate) struct Read { + raster: std::sync::Arc, + _count: Option>, +} + +impl std::ops::Deref for Read { + type Target = Raster; + fn deref(&self) -> &Raster { + &self.raster + } +} + +/// A raster file read in place that a run read ([`RUN_READS`]): its path, its layer's name, the +/// raster read and its count in [`rustgis_data::memory::held`]. +#[cfg(not(target_arch = "wasm32"))] +type RunRead = (String, String, std::sync::Arc, std::sync::Arc); + +#[cfg(not(target_arch = "wasm32"))] +thread_local! { + /// The raster files read in place that a run's work read on this thread ([`Input::read`]), + /// each by its path with its layer's name and its count, kept while the run reads + /// ([`reading_files`]); `None` otherwise. + static RUN_READS: std::cell::RefCell>> = const { std::cell::RefCell::new(None) }; +} + +/// [`RUN_READS`] for one run while it lives: put back as it was before when the run ends +/// ([`RunReads::end`]), or as it unwinds from a panic, so nothing a run read is kept, or read +/// from its file, past it. +#[cfg(not(target_arch = "wasm32"))] +struct RunReads(Option>>); + +#[cfg(not(target_arch = "wasm32"))] +impl RunReads { + fn start() -> RunReads { + RunReads(Some(RUN_READS.with(|r| r.borrow_mut().replace(Vec::new())))) + } + + /// What the run read, [`RUN_READS`] put back as it was. + fn end(&mut self) -> Vec { + let outer = self.0.take().flatten(); + RUN_READS.with(|r| std::mem::replace(&mut *r.borrow_mut(), outer)).unwrap_or_default() + } +} + +#[cfg(not(target_arch = "wasm32"))] +impl Drop for RunReads { + fn drop(&mut self) { + if self.0.is_some() { + self.end(); + } + } +} + +/// Runs `work` (command `name`'s) so the raster layers read in place it reads are read from their +/// file ([`Input::read`]), each file read once for the run, and adds to what is said once its +/// raster is added each that was read from an overview, or with values rounded. +pub(crate) fn reading_files(name: &str, work: impl FnOnce() -> Result) -> Result { + #[cfg(target_arch = "wasm32")] + { + let _ = name; + work() + } + #[cfg(not(target_arch = "wasm32"))] + { + let mut run = RunReads::start(); + let made = work(); + let read = run.end(); + let made = made?; + let read: Vec<(String, std::sync::Arc)> = read.into_iter().map(|(_, name, r, _)| (name, r)).collect(); + let notes: Vec = super::gp::tiled_read_notes(&read, "its").into_iter().map(|n| format!("{name}: {n}")).collect(); + if notes.is_empty() { + return Ok(made); + } + let then = made.then; + Ok(Made { + then: Some(Box::new(move |s: &mut Session, v: &mut Value| { + for note in notes { + s.notify(note, false); + } + if let Some(then) = then { + then(s, v); + } + })), + ..made + }) + } } fn band_of(p: &Value, r: &Raster) -> Result { @@ -286,7 +435,7 @@ pub(crate) fn made_or_ran(s: &mut Session, p: &Value, command: &str) -> CmdResul let made = work(s, p)?; // Where a person at a terminal can stop it with Ctrl-C: no work cap, as on the app's thread. let control = if s.stoppable { rustgis_analysis::control::Control::stoppable() } else { rustgis_analysis::control::Control::new() }; - let made = rustgis_analysis::run_under(name, &control, made)?; + let made = rustgis_analysis::run_under(name, &control, || reading_files(name, made))?; s.check_continuation(&owner)?; add_made(s, made) } @@ -319,7 +468,9 @@ impl RasterRun { let still = std::sync::Arc::new(move || current.check().is_ok()) as crate::render::rustgis_tiles::cache::Still; // A bug in the work, as one in a tool, must not take the app down. std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { - crate::render::rustgis_tiles::cache::with_still(still, || rustgis_analysis::run_under(name, control, work)) + crate::render::rustgis_tiles::cache::with_still(still, || { + rustgis_analysis::run_under(name, control, || reading_files(name, work)) + }) })) .unwrap_or_else(|_| Err(format!("{name} failed unexpectedly"))) .map(|m| Made { @@ -1380,12 +1531,19 @@ fn apply_function(r: &Raster, p: &Value, target: Option<&Raster>, remaps: &mut R } } -/// The raster a resample step (`p`) takes the grid of: none for another function. -fn resample_target(s: &Session, p: &Value) -> Result>, String> { +/// The raster a resample step (`p`) takes the grid of: none for another function. Its size is +/// checked as it is read ([`read_target`]). +fn resample_target(s: &Session, p: &Value) -> Result, String> { if ps(p, "function") != Some("resample") { return Ok(None); } - let t = raster_of(s, resample_target_name(p)?.ok_or("target (a raster to match) is required")?)?; + Ok(Some(raster_of(s, resample_target_name(p)?.ok_or("target (a raster to match) is required")?)?)) +} + +/// A resample's target ([`resample_target`]) read for the work, refused past this computer's cells. +fn read_target(t: Option<&Input>) -> Result, String> { + let Some(t) = t else { return Ok(None) }; + let t = t.read()?; if t.width as usize * t.height as usize > rasterops::max_pixels() { return Err(format!("the target grid is larger than this computer's {} cells", rasterops::max_pixels())); } @@ -1400,7 +1558,7 @@ fn raster_function(s: &mut Session, p: &Value) -> CmdResult { fn function_work(s: &Session, p: &Value) -> Result { let src = raster_of(s, ps(p, "layer").ok_or("layer is required")?)?; let target = resample_target(s, p)?; - let name = out_name(p, format!("{}_{}", src.name, ps(p, "function").unwrap_or("")))?; + let name = out_name(p, format!("{}_{}", src.held().name, ps(p, "function").unwrap_or("")))?; let defaults = s.raster_defaults.clone(); let mut p = p.clone(); // Read here, on the command's thread, where an unreadable value is said (#1600); only a remap @@ -1409,6 +1567,8 @@ fn function_work(s: &Session, p: &Value) -> Result { super::settle_bool(&mut p, "keep"); } Ok(Box::new(move || { + let src = src.read()?; + let target = read_target(target.as_ref())?; let mut remaps = Remaps::default(); let pixels = apply_function(&src, &p, target.as_deref(), &mut remaps)?; // Only a resample takes another raster's grid. @@ -1476,16 +1636,23 @@ fn function_chain_work(s: &Session, p: &Value) -> Result { let named = Some(out_name(p, String::new())?).filter(|n| !n.is_empty()); let defaults = s.raster_defaults.clone(); Ok(Box::new(move || { - let mut cur: Raster = (*src).clone(); + let src = src.read()?; + // Each step's output, the next step's input; the first step reads the raster itself, not + // a copy of it. + let mut cur: Option = None; let mut names = Vec::new(); let mut remaps = Remaps::default(); for (i, (st, target)) in steps.iter().zip(&targets).enumerate() { let f = func(st); - let pixels = apply_function(&cur, st, target.as_deref(), &mut remaps).map_err(|e| format!("step {} ({f}): {e}", i + 1))?; + let target = read_target(target.as_ref()).map_err(|e| format!("step {} ({f}): {e}", i + 1))?; + let input = cur.as_ref().unwrap_or(&src); + let pixels = apply_function(input, st, target.as_deref(), &mut remaps).map_err(|e| format!("step {} ({f}): {e}", i + 1))?; // Only a resample takes another raster's grid; otherwise the grid is the current one. - cur = derive_function(target.as_deref().unwrap_or(&cur), &cur.name, st, pixels)?; + let next = derive_function(target.as_deref().unwrap_or(input), &input.name, st, pixels)?; + cur = Some(next); names.push(f); } + let mut cur = cur.ok_or("the chain made no raster")?; cur.name = named.unwrap_or_else(|| format!("{}_{}", cur.name, names.join("_"))); // A chain that ends in a hillshade is drawn as one. let mut m = match steps.last() { @@ -1512,7 +1679,7 @@ fn suitability_work(s: &Session, p: &Value) -> Result { let mut criteria = Vec::new(); for c in crit { let r = raster_of(s, criterion_layer(c)?)?; - let band = band_of(c, &r)?; + let band = band_of(c, r.held())?; let ranges: Vec<(f64, f64, f64)> = c .get("ranges") .and_then(Value::as_array) @@ -1530,10 +1697,12 @@ fn suitability_work(s: &Session, p: &Value) -> Result { } let name = out_name(p, "Suitability".into())?; Ok(Box::new(move || { + let first = first.read()?; let mut scored = Vec::new(); let mut empty = Vec::new(); for (r, band, ranges, weight) in &criteria { - let on_grid = rasterops::resample_to(r, *band, &first)?; + let r = r.read()?; + let on_grid = rasterops::resample_to(&r, *band, &first)?; let remap = rasterops::remap(&rasterops::derive(&first, &r.name, vec![on_grid])?, 0, ranges, false)?; empty.extend(remap.empty.into_iter().map(|(lo, hi)| (r.name.clone(), lo, hi))); scored.push((remap.cells, *weight)); @@ -1557,46 +1726,11 @@ fn viewshed(s: &mut Session, p: &Value) -> CmdResult { fn viewshed_work(s: &Session, p: &Value) -> Result { let dem = raster_of(s, ps(p, "layer").ok_or("layer is required")?)?; let at = Coord::new(f(p, "lon").ok_or("lon is required")?, f(p, "lat").ok_or("lat is required")?); - let band = band_of(p, &dem)?; - let (cx, cy) = dem.cell_size_m(); - // The whole raster by default, however large: its diagonal reaches every cell from any - // observer, and only the raster's cells are worked out. A radius given past the diagonal - // covers the same cells, so it is taken as the diagonal: nothing is left out. - let diagonal = (cx * dem.width as f64).hypot(cy * dem.height as f64).max(1.0); - let radius = match p.get("radius") { - None | Some(Value::Null) => diagonal, - Some(v) => { - f(p, "radius").filter(|r| *r > 0.0).ok_or_else(|| format!("radius must be a number of metres above 0, not {v}"))?.min(diagonal) - } - }; - // A raster around the whole Earth (in longitude/latitude) has its east and west edges side - // by side, but rays don't cross from one to the other: said when the radius reaches an edge. - // (Within half a cell of 360°: a cell size stored rounded falls a little short.) - let pw = dem.transform.pixel_width.abs(); - let round_the_earth = dem.crs.is_geographic() && pw * f64::from(dem.width) >= 360.0 - pw / 2.0; - let (oc, or) = dem.pixel_at(at).unwrap_or((0, 0)); - let (w, h) = (i64::from(dem.width), i64::from(dem.height)); - let (near, far) = (oc.min(w - 1 - oc), oc.max(w - 1 - oc)); - // Only when the way across the edge is shorter than the way through the raster: the cell - // just across the near edge is `near + 1` cells away across it and `far` through the raster, - // and with no shorter way (the observer within a cell of the middle column) every cell is - // worked out as near as it is. - let seam = round_the_earth && near + 1 < far && (near as f64 + 1.0) * cx <= radius; - // The ground just across the edge is the far edge's column, reached only through the raster: - // worked out the long way round in the rows where the radius reaches it (cell centres, as the - // viewshed measures them). The rows with ground across the edge within the radius are those - // where it reaches a cell one past the near edge. All of them are worked out when the radius - // reaches the far column in the farthest of those rows, none when it doesn't reach the far - // column even on the observer's row. - let reaches = |dc: i64, dr: i64| (dc as f64 * cx).hypot(dr as f64 * cy) <= radius; - // The rows are walked only on a raster round the Earth, at most its height. - let last_row = if seam { (0..=or.max(h - 1 - or)).take_while(|dr| reaches(near + 1, *dr)).last().unwrap_or(0) } else { 0 }; - let across = if !reaches(far, 0) { - "left out of the viewshed" - } else if reaches(far, last_row) { - "worked out the long way round" - } else { - "worked out the long way round near the observer's row and left out farther from it" + let band = band_of(p, dem.held())?; + // A radius given is checked here; the raster's own reach is taken as the work reads it. + let given = match p.get("radius") { + None | Some(Value::Null) => None, + Some(v) => Some(f(p, "radius").filter(|r| *r > 0.0).ok_or_else(|| format!("radius must be a number of metres above 0, not {v}"))?), }; // Refused, naming it, when it isn't a height a viewshed takes: never another one used. let height = match p.get("height") { @@ -1613,9 +1747,45 @@ fn viewshed_work(s: &Session, p: &Value) -> Result { } Some(other) => return Err(format!("heights must be \"nearest\" or \"bilinear\", not {other}")), }; - let name = out_name(p, format!("{}_viewshed", dem.name))?; - let dem_name = dem.name.clone(); + let name = out_name(p, format!("{}_viewshed", dem.held().name))?; + let dem_name = dem.held().name.clone(); Ok(Box::new(move || { + let dem = dem.read()?; + let (cx, cy) = dem.cell_size_m(); + // The whole raster by default, however large: its diagonal reaches every cell from any + // observer, and only the raster's cells are worked out. A radius given past the diagonal + // covers the same cells, so it is taken as the diagonal: nothing is left out. + let diagonal = (cx * dem.width as f64).hypot(cy * dem.height as f64).max(1.0); + let radius = given.map_or(diagonal, |r| r.min(diagonal)); + // A raster around the whole Earth (in longitude/latitude) has its east and west edges side + // by side, but rays don't cross from one to the other: said when the radius reaches an edge. + // (Within half a cell of 360°: a cell size stored rounded falls a little short.) + let pw = dem.transform.pixel_width.abs(); + let round_the_earth = dem.crs.is_geographic() && pw * f64::from(dem.width) >= 360.0 - pw / 2.0; + let (oc, or) = dem.pixel_at(at).unwrap_or((0, 0)); + let (w, h) = (i64::from(dem.width), i64::from(dem.height)); + let (near, far) = (oc.min(w - 1 - oc), oc.max(w - 1 - oc)); + // Only when the way across the edge is shorter than the way through the raster: the cell + // just across the near edge is `near + 1` cells away across it and `far` through the raster, + // and with no shorter way (the observer within a cell of the middle column) every cell is + // worked out as near as it is. + let seam = round_the_earth && near + 1 < far && (near as f64 + 1.0) * cx <= radius; + // The ground just across the edge is the far edge's column, reached only through the raster: + // worked out the long way round in the rows where the radius reaches it (cell centres, as the + // viewshed measures them). The rows with ground across the edge within the radius are those + // where it reaches a cell one past the near edge. All of them are worked out when the radius + // reaches the far column in the farthest of those rows, none when it doesn't reach the far + // column even on the observer's row. + let reaches = |dc: i64, dr: i64| (dc as f64 * cx).hypot(dr as f64 * cy) <= radius; + // The rows are walked only on a raster round the Earth, at most its height. + let last_row = if seam { (0..=or.max(h - 1 - or)).take_while(|dr| reaches(near + 1, *dr)).last().unwrap_or(0) } else { 0 }; + let across = if !reaches(far, 0) { + "left out of the viewshed" + } else if reaches(far, last_row) { + "worked out the long way round" + } else { + "worked out the long way round near the observer's row and left out farther from it" + }; let vs = rasterops::viewshed(&dem, band, at, height, radius, heights)?; let seen = vs.cells.iter().filter(|v| **v == 1.0).count(); let (through_gaps, read_nearest) = (vs.through_gaps, vs.read_nearest); @@ -1655,8 +1825,11 @@ fn viewshed_work(s: &Session, p: &Value) -> Result { })) } +/// `analysis.lineOfSight`: the line from `from` to `to` over the elevation raster's held pixels, +/// split where it turns visible or hidden, with its profile. On the app's thread, so a layer read +/// in place from a file is read from the overview it holds. fn line_of_sight(s: &mut Session, p: &Value) -> CmdResult { - let dem = raster_of(s, ps(p, "layer").ok_or("layer is required")?)?; + let dem = raster_of(s, ps(p, "layer").ok_or("layer is required")?)?.held; let name = out_name(p, "Line of Sight".into())?; let (a, b2) = (point(p, "from")?, point(p, "to")?); let band = band_of(p, &dem)?; diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 8b7c62eaea..6f08860e1f 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -422,13 +422,14 @@ fn names_said(names: &[String]) -> String { /// What a raster layer read in place holds for its statistics and tools, when it holds an /// overview of the image the map draws. A file on this computer (`tools_read_file`) is read again -/// by each geoprocessing tool, at the finest level it can hold ([`crate::cmd::gp`]). +/// by each geoprocessing tool and each command that makes a raster in the background, at the +/// finest level it can hold ([`crate::cmd::gp`], [`crate::cmd::workflows::Input`]). pub(crate) fn in_place_overview(d: &rustgis_data::raster::Raster, tools_read_file: bool) -> Option { let (fw, fh) = d.overview?; let (w, h) = (d.width, d.height); Some(if tools_read_file { format!( - "read in place: the map draws its {fw} × {fh} pixels as it needs them, and geoprocessing tools read the file (built-in ones at the finest level they can hold, GeoLibre ones whole), while statistics, histograms, plugin tools and other raster commands read a {w} × {h} overview" + "read in place: the map draws its {fw} × {fh} pixels as it needs them, and geoprocessing tools and the commands that make a raster read the file (at the finest level they can hold, GeoLibre tools whole), while statistics, histograms, plugin tools, Build Mosaic, Train Deep Learning Model and other raster commands read a {w} × {h} overview" ) } else { format!( diff --git a/crates/engine/src/tests/tiled_files.rs b/crates/engine/src/tests/tiled_files.rs index f800a5e19c..4d917198d7 100644 --- a/crates/engine/src/tests/tiled_files.rs +++ b/crates/engine/src/tests/tiled_files.rs @@ -113,7 +113,7 @@ fn a_large_local_tiled_geotiff_draws_its_full_image_zoomed_in() { let notes = said(&s, mark); assert!( notes.iter().any(|n| n.starts_with("checks: read in place: the map draws its 1024 × 1024 pixels") - && n.contains("geoprocessing tools read the file") + && n.contains("geoprocessing tools and the commands that make a raster read the file") && n.contains("read a 512 × 512 overview")), "{notes:?}" ); @@ -297,3 +297,64 @@ fn an_original_image_grid_reads_a_tiled_files_grid() { let e = crate::image_grid::read(raster(&s, "checks")).err().unwrap_or_default(); assert!(e.contains("changed since its pixels were loaded"), "{e}"); } + +/// A command that makes a raster reads the file, not the overview the layer holds, as it runs +/// where the caller waits and as the app runs it on another thread: an index over the file has +/// its 1024 × 1024 pixels, and a resample by 2 of it 512 × 512. Two criteria of a suitability on +/// the same layer read its file once. The full image fits, so nothing is said of an overview. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_command_that_makes_a_raster_reads_a_tiled_file_at_its_full_size() { + use crate::cmd::workflows::{raster_land, raster_start}; + let d = dir("made"); + let path = checkerboard(&d); + let _held = HeldWhole::at(1_000_000); + let mut s = Session::new(Project::default()); + s.run("layer.addData", &json!({"path": path})).unwrap(); + assert!(raster(&s, "checks").tiled); + let size = |s: &Session, name: &str| raster(s, name).data.as_ref().map(|r| (r.width, r.height, r.overview)); + let mark = s.notice_mark(); + s.run("raster.index", &json!({"layer": "checks", "index": "ndvi", "red": 1, "nir": 2, "name": "index"})).unwrap(); + assert_eq!(size(&s, "index"), Some((1024, 1024, None)), "where the caller waits"); + // As the app runs it: started here, made by the run (on its own thread in the app; on this + // one here), added when run again. + let p = json!({"layer": "checks", "operation": "resample", "factor": 2, "name": "halved"}); + let run = raster_start(&mut s, "raster.process", &p).unwrap(); + let id = run.id; + let made = run.run(&rustgis_analysis::control::Control::new()).unwrap(); + assert!(raster_land(&mut s, id, made).unwrap()); + s.run("raster.process", &json!({"ran": id})).unwrap(); + assert_eq!(size(&s, "halved"), Some((512, 512, None)), "made by the run"); + let reads = || crate::cmd::gp::TILED_READS.with(std::cell::Cell::get); + let before = reads(); + let criterion = json!({"layer": "checks", "ranges": [[0, 255, 1]]}); + s.run("analysis.suitability", &json!({"criteria": [criterion, criterion], "name": "suits"})).unwrap(); + assert_eq!(reads() - before, 1, "the file read once for the run"); + assert_eq!(size(&s, "suits"), Some((1024, 1024, None))); + let notes = said(&s, mark); + assert!(!notes.iter().any(|n| n.contains("finest level") || n.contains("rounded")), "{notes:?}"); +} + +/// A run whose work panics leaves nothing of its reads behind: on the same thread afterwards, a +/// command's input outside a run is the overview the layer holds, not its file. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_run_that_panics_reads_no_file_after_it() { + use crate::cmd::workflows::{Input, reading_files}; + let d = dir("panic"); + let path = checkerboard(&d); + let _held = HeldWhole::at(1_000_000); + let mut s = Session::new(Project::default()); + s.run("layer.addData", &json!({"path": path})).unwrap(); + let input = Input::of(&s, "checks").unwrap(); + let mut within = 0; + let ran = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + reading_files("Indices", || { + within = input.read().unwrap().width; + panic!("the work failed"); + }) + })); + assert!(ran.is_err()); + assert_eq!(within, 1024, "the file, within the run"); + assert_eq!(input.read().unwrap().width, 512, "the overview the layer holds, after the run"); +}