Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion crates/engine/command-surface.txt
Original file line number Diff line number Diff line change
Expand Up @@ -477,7 +477,7 @@ raster.info layer?
raster.mask layer? values? min? max? inside? clear?
raster.measure layer? kind points base?
raster.measurements clear?
raster.mosaic inputs name? path?
raster.mosaic inputs name? path? ran?
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? ran?
Expand Down
348 changes: 218 additions & 130 deletions crates/engine/src/cmd/imagery.rs

Large diffs are not rendered by default.

57 changes: 46 additions & 11 deletions crates/engine/src/cmd/raster.rs
Original file line number Diff line number Diff line change
Expand Up @@ -489,14 +489,22 @@ pub(crate) fn as_scan(p: &Value) -> Result<bool, String> {
}
}

/// Says what reading several rasters left out, each `(raster, line)`: one notice a kind (the same
/// line), naming the rasters that share it (three, then a count), as AGENTS.md's Never silent asks.
/// Says what reading several rasters left out ([`loss_lines`]), a notice a line.
pub(crate) fn say_losses(s: &mut Session, losses: Vec<(String, String)>) {
for line in loss_lines(losses) {
s.notify(line, false);
}
}

/// What reading several rasters left out, each `(raster, line)`, as it is said: one line a kind (the
/// same line), naming the rasters that share it (three, then a count), as AGENTS.md's Never silent
/// asks.
///
/// Lines that differ only in their numbers ("1 scale…", "2 scale…") are one kind. When the
/// numbers are the same for every raster the kind is said once; when they differ, each raster's
/// own line is said (three rasters or fewer), or the range they give, for each of them ("4
/// rasters (a, b, c, …), each: 1–2 scale…"): never summed, since a size limit isn't a count.
pub(crate) fn say_losses(s: &mut Session, losses: Vec<(String, String)>) {
pub(crate) fn loss_lines(losses: Vec<(String, String)>) -> Vec<String> {
// A line's kind: its text with each number taken out, and those numbers. A number is a run of
// digits standing as a word of its own: one inside a name (`scene2024.tif`) stays text.
fn kind_of(line: &str) -> (Vec<&str>, Vec<u64>) {
Expand Down Expand Up @@ -547,13 +555,12 @@ pub(crate) fn say_losses(s: &mut Session, losses: Vec<(String, String)>) {
None => kinds.push((parts_owned, numbers.iter().map(|n| (*n, *n)).collect(), vec![(name, line)])),
}
}
let mut lines = Vec::new();
for (parts, ranges, named) in kinds {
let differ = ranges.iter().any(|(lo, hi)| lo != hi);
// A few rasters whose numbers differ: each its own, so none is lost in a range.
if differ && named.len() <= 3 {
for (name, line) in named {
s.notify(format!("{name}: {line}"), false);
}
lines.extend(named.into_iter().map(|(name, line)| format!("{name}: {line}")));
continue;
}
let names: Vec<String> = named.into_iter().map(|(name, _)| name).collect();
Expand All @@ -572,8 +579,9 @@ pub(crate) fn say_losses(s: &mut Session, losses: Vec<(String, String)>) {
}
};
let each = if differ { ", each" } else { "" };
s.notify(format!("{who}{each}: {line}"), false);
lines.push(format!("{who}{each}: {line}"));
}
lines
}

/// Opens a raster file by path; `ignored` is said with what reading it lost (options given that
Expand Down Expand Up @@ -1305,6 +1313,9 @@ pub(super) fn write_geotiff_with_guidance(
wrote_geotiff(r, bi, path, cog, band_hint)
}

/// The band instruction of a file a tool writes of its result ([`write_geotiff_with_guidance`]).
pub(super) const RESULT_BAND: &str = "export the resulting layer with share.exportRaster and give \"band\" for another";

/// [`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(
Expand All @@ -1317,6 +1328,30 @@ pub(super) fn write_cog_staged(
Ok((wrote_geotiff(r, bi, path, Some(cog), band_hint)?, staged))
}

/// [`write_geotiff_with_guidance`]'s plain GeoTIFF, written beside `path` and put in its place when
/// the returned file is committed, as [`write_cog_staged`]'s is. It is encoded in memory first, as
/// `share.exportRaster`'s plain one is; Cancel is looked at as it is encoded and every megabyte
/// written.
pub(super) fn write_plain_staged(
r: &Raster,
bi: usize,
path: &str,
band_hint: &str,
) -> Result<(super::exports::Wrote, rustgis_data::io::StagedWrite), String> {
use std::io::Write;
let bytes = raster::geotiff::write(r, bi).map_err(|e| e.to_string())?;
let look = || rustgis_data::progress::check().map_err(std::io::Error::other);
let (staged, ()) = rustgis_data::io::stage_streamed(Path::new(path), |w| {
for piece in bytes.chunks(1 << 20) {
look()?;
w.write_all(piece)?;
}
look()
})
.map_err(|e: std::io::Error| format!("{path}: {e}"))?;
Ok((wrote_geotiff(r, bi, path, None, band_hint)?, staged))
}

/// What writing `r`'s band `bi` to `path` says.
fn wrote_geotiff(
r: &Raster,
Expand Down Expand Up @@ -1347,10 +1382,10 @@ fn wrote_geotiff(
})
}

/// Writes a tool's raster file and reports the same export notes as `share.exportRaster`.
pub(super) fn write_and_report(s: &mut Session, r: &Raster, bi: usize, cog: bool, path: &str) -> Result<Value, String> {
let wrote =
write_geotiff_with_guidance(r, bi, cog, path, "export the resulting layer with share.exportRaster and give \"band\" for another")?;
/// Writes a tool's raster file, a Cloud Optimized GeoTIFF, and reports the same export notes as
/// `share.exportRaster`.
pub(super) fn write_and_report(s: &mut Session, r: &Raster, bi: usize, path: &str) -> Result<Value, String> {
let wrote = write_geotiff_with_guidance(r, bi, true, path, RESULT_BAND)?;
for note in wrote.notes {
s.say_written(note);
}
Expand Down
1 change: 1 addition & 0 deletions crates/engine/src/cmd/workflows.rs
Original file line number Diff line number Diff line change
Expand Up @@ -505,6 +505,7 @@ pub(crate) const IN_BACKGROUND: &[(&str, &str, Start)] = &[
("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),
("raster.mosaic", "Mosaic Rasters", super::imagery::mosaic_rasters_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),
Expand Down
145 changes: 139 additions & 6 deletions crates/engine/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20841,6 +20841,8 @@ fn plugin_mosaics_of_project_layers_need_no_files() {
json!({"inputs": ["west", "east.tif"]}),
json!({"inputs": ["west", "../east.tif"]}),
json!({"inputs": ["west", "east"], "name": "../elevation"}),
// A run to hand over is no way round it: what is named is asked about all the same.
json!({"inputs": ["west", "east.tif"], "ran": 1}),
] {
let e = forward(&mut s, "eng-mosaic", "raster.mosaic", params.clone()).unwrap_err();
assert!(e.contains("'files' permission"), "{params}: {e}");
Expand All @@ -20852,6 +20854,7 @@ fn plugin_mosaics_of_project_layers_need_no_files() {
(json!({"inputs": ["west", "Countries"]}), "no raster layer 'Countries'"),
(json!({"inputs": ["west", 3]}), "each input is a raster layer's name or a file path"),
(json!({"inputs": vec!["west"; 10_001]}), "at most 10000 inputs"),
(json!({"inputs": ["west", "east"], "ran": 1}), "no longer kept"),
] {
let e = forward(&mut s, "eng-mosaic", "raster.mosaic", params.clone()).unwrap_err();
assert!(e.contains(why) && !e.contains("permission"), "{params}: {e}");
Expand Down Expand Up @@ -20914,16 +20917,11 @@ fn clip_resample_and_mosaic_run_with_imagery_off() {
forward(&mut s, "eng-imagery-off", id, p).unwrap();
}
check(&s, "plugin");
// As the desktop app runs clip and resample: worked out on a thread, landed, then added by the
// command. A mosaic has no such run.
// As the desktop app runs them: worked out on a thread, landed, then added by the command.
#[cfg(not(target_arch = "wasm32"))]
{
use crate::cmd::workflows::{raster_land, raster_start};
for (id, p) in commands("app") {
if id == "raster.mosaic" {
s.run(id, &p).unwrap();
continue;
}
let run = raster_start(&mut s, id, &p).unwrap();
let ran = run.id;
let made = std::thread::spawn(move || run.run(&rustgis_analysis::control::Control::new())).join().unwrap().unwrap();
Expand Down Expand Up @@ -53727,6 +53725,141 @@ fn raster_tools_run_on_another_thread() {
assert!(runs_in_background("raster.editPixels").is_none());
}

/// Mosaic Rasters made on another thread, as the app makes it (#2907): the cells, the answer, the
/// file and what it says are those of one made here, nothing is said and no file is put in place
/// before it lands, and it is refused with the same words, whether its start or its run refuses it.
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn a_mosaic_made_on_another_thread_is_the_one_made_here() {
use crate::cmd::workflows::{raster_land, raster_start};
use rustgis_analysis::control::Control;
use rustgis_data::raster::{ColorHint, Crs, GeoTransform, Raster, geotiff};
let dir = std::env::temp_dir().join(format!("rustgis-mosaic-thread-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let at = |file: &str| dir.join(file).display().to_string();
// Two bands of 10 × 10 cells, `base` and up, with a hole at the top left.
let tile = |name: &str, x0: f64, base: f32| {
let band = |b: f32| (0..100).map(|i| if i == 0 { -9999.0 } else { base + b + i as f32 }).collect::<Vec<f32>>();
let gt = GeoTransform { origin_x: x0, origin_y: 1.0, pixel_width: 0.1, pixel_height: -0.1 };
Raster::new(name, 10, 10, vec![band(0.0), band(0.5)], gt, Crs::LonLat, Some(-9999.0), ColorHint::Gray, "Float32").unwrap()
};
let mut s = Session::new(Project::default());
let mut over = tile("over", 0.5, 900.0);
over.bands[0].name = "Altitude".into();
over.copyright = Some("Someone".into());
for r in [tile("west", 0.0, 100.0), over, tile("off", 0.55, 0.0)] {
let (name, bytes) = (r.name.clone(), geotiff::write_all(&r).unwrap());
crate::cmd::raster::add_raster(&mut s, &name, rustgis_map::RasterLayer::from_bytes(r, format!("{name}.tif"), bytes)).unwrap();
}
// A file that says what its reading left out, one that lies off the grid, and one that isn't a raster.
for (file, r) in [("east.tif", tile("east", 1.0, 200.0)), ("astray.tif", tile("astray", 2.03, 0.0))] {
std::fs::write(at(file), geotiff::write_all(&r).unwrap()).unwrap();
}
let sidecar = r#"<PAMDataset><PAMRasterBand band="1"><Offset>5</Offset></PAMRasterBand></PAMDataset>"#;
std::fs::write(at("east.tif.aux.xml"), sidecar).unwrap();
std::fs::write(at("broken.tif"), b"not a raster").unwrap();
let cells = |s: &Session, v: &Value| {
let l = s.map().layer(v["layer"].as_u64().unwrap() as u32).unwrap();
let r = l.raster.as_ref().unwrap().data.clone().unwrap();
let bits: Vec<u32> = r.bands.iter().flat_map(|b| b.data.iter().map(|x| x.to_bits())).collect();
let names: Vec<String> = r.bands.iter().map(|b| b.name.clone()).collect();
(r.width, r.height, r.transform, r.nodata, names, bits)
};
let said = |s: &Session, mark: u64, path: &str| -> Vec<String> {
s.notices_since(mark).iter().map(|n| n.text.replace(path, "PATH")).collect()
};
for (inputs, file, notices) in [
// Where they overlap, the first wins.
(json!(["west", "over"]), None, 2),
(json!(["over", "west"]), None, 1),
(json!(["west", at("east.tif"), "over"]), None, 3),
(json!([at("east.tif"), "over", "west"]), Some("mosaic.tif"), 4),
] {
let with = |name: &str| {
let path = file.map(|f| at(&format!("{name}_{f}")));
(json!({"inputs": inputs, "name": name, "path": path}), path.unwrap_or("(no file)".into()))
};
let (p, path_here) = with("here");
let mark = s.notice_mark();
let here = s.run("raster.mosaic", &p).unwrap();
let said_here = said(&s, mark, &path_here);
// What the file lost, the credits left out, the band names not kept, then the file written.
assert_eq!(said_here.len(), notices, "{inputs}: {said_here:?}");
let (p, path_there) = with("there");
if file.is_some() {
std::fs::write(&path_there, b"before").unwrap();
}
// Let go of once made, before it lands (a late Cancel, another project opened): the file
// there stays, and no other is left.
let files = || std::fs::read_dir(&dir).unwrap().count();
let before = files();
let run = raster_start(&mut s, "raster.mosaic", &p).unwrap();
let mark = s.notice_mark();
let made = std::thread::spawn(move || run.run(&Control::new())).join().unwrap().unwrap();
drop(made);
assert!(file.is_none() || std::fs::read(&path_there).unwrap() == b"before", "{inputs}");
assert_eq!(files(), before, "{inputs}: a staged file was left");
let run = raster_start(&mut s, "raster.mosaic", &p).unwrap();
let id = run.id;
let made = std::thread::spawn(move || run.run(&Control::new())).join().unwrap().unwrap();
assert!(s.notices_since(mark).is_empty(), "nothing is said before it lands: {:?}", s.notices_since(mark));
assert!(file.is_none() || std::fs::read(&path_there).unwrap() == b"before", "{inputs}: in place before it lands");
assert_eq!(raster_land(&mut s, id, made), Ok(true));
let there = s.finish_raster("raster.mosaic", id, &p).unwrap();
assert_eq!(said(&s, mark, &path_there), said_here, "{inputs}");
assert_eq!(cells(&s, &there), cells(&s, &here), "{inputs}");
assert!((here.get("path").is_some(), there.get("path").is_some()) == (file.is_some(), file.is_some()), "{here} {there}");

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: this assert! compares a tuple built from here/there against a tuple that repeats file.is_some(), so a failure message doesn't say which side differs. An assert_eq! with each side's own value reads more clearly and points at the case that broke:

Suggested change
assert!((here.get("path").is_some(), there.get("path").is_some()) == (file.is_some(), file.is_some()), "{here} {there}");
assert_eq!((here.get("path").is_some(), there.get("path").is_some()), (file.is_some(), file.is_some()), "{here} {there}");

Category: quality

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed, assert_eq! would name the side that differs; the assertion itself is right, so I'm leaving it, and the rows that shadows the total in Tiles::join (imagery.rs:2164, 2168), for a push needed for another reason, or the release quality pass.

On the review's other two points, the description is updated:

  • Command Search doesn't reach it. search_disabled (chrome.rs:1275) greys a command that has a required parameter and no entry in search_action, and the palette runs only the rows it doesn't grey (chrome.rs:1468). inputs is required and raster.mosaic has no entry, so nothing reaches lib.rs:3399 with it yet. The intro now says so, and Reaches says it the same way.
  • Memory now gives the multiples. They are from the code: cargo xtask memory has table scenarios only (xtask/src/memory.rs, scenarios).

for key in ["width", "height", "bands"] {
assert_eq!(there[key], here[key], "{inputs}: {key}");
}
if file.is_some() {
assert_eq!(std::fs::read(&path_there).unwrap(), std::fs::read(&path_here).unwrap(), "{inputs}");
}
}
// Where it is refused first, whichever input: an error of an earlier input comes before a later
// one's, and a file that can't be written says what the inputs had to say too.
let nowhere = dir.join("no").join("such.tif").display().to_string();
for (p, why, starts) in [
(json!({"inputs": ["west"]}), "two or more", false),
(json!({"inputs": ["west", "nowhere"]}), "no raster layer 'nowhere'", false),
(json!({"inputs": ["west", "off", "nowhere"]}), "don't line up", false),
(json!({"inputs": ["west", "over"], "name": "n".repeat(201)}), "name", false),
(json!({"inputs": [at("gone.tif"), "nowhere"]}), "gone.tif", true),
(json!({"inputs": [at("broken.tif"), "west"]}), "broken.tif", true),
(json!({"inputs": ["west", at("east.tif"), "nowhere"]}), "no raster layer 'nowhere'", true),
(json!({"inputs": ["west", at("astray.tif"), at("gone.tif")]}), "don't line up", true),
(json!({"inputs": ["west", at("east.tif"), 3]}), "each input is a raster layer's name or a file path", true),
(json!({"inputs": ["west", at("east.tif")], "path": nowhere}), "not applied", true),
] {
let layers = s.map().layers.len();
let here = s.run("raster.mosaic", &p).unwrap_err();
assert!(here.contains(why), "{p}: {here}");
let there = match raster_start(&mut s, "raster.mosaic", &p) {
Err(e) => (e, false),
Ok(run) => (std::thread::spawn(move || run.run(&Control::new())).join().unwrap().err().unwrap(), true),
};
assert_eq!(there, (here, starts), "{p}");
assert_eq!(s.map().layers.len(), layers, "{p}");
}
// A file that can't be put in place (a folder is there) is refused as the raster is added, with
// what the inputs had to say and not that it was exported.
std::fs::create_dir(at("folder.tif")).unwrap();
let p = json!({"inputs": ["west", at("east.tif")], "path": at("folder.tif")});
let (layers, files) = (s.map().layers.len(), std::fs::read_dir(&dir).unwrap().count());
let mark = s.notice_mark();
let here = s.run("raster.mosaic", &p).unwrap_err();
assert!(here.starts_with(&at("folder.tif")) && here.contains("not applied") && !here.contains("Exported"), "{here}");
let run = raster_start(&mut s, "raster.mosaic", &p).unwrap();
let id = run.id;
let made = run.run(&Control::new()).unwrap();
assert_eq!(raster_land(&mut s, id, made), Ok(true));
assert_eq!(s.finish_raster("raster.mosaic", id, &p).unwrap_err(), here);
assert!(s.notices_since(mark).iter().all(|n| !n.text.contains("Exported")), "{:?}", s.notices_since(mark));
assert_eq!((s.map().layers.len(), std::fs::read_dir(&dir).unwrap().count()), (layers, files));
let _ = std::fs::remove_dir_all(&dir);
}

/// Export Features and Export Raster written on another thread, as the app writes them (#1291
/// step 3): the file, the answer and what the export says are those of one written here, nothing
/// is said until it lands, and one cancelled before it starts writes nothing (a cancel in the
Expand Down
10 changes: 9 additions & 1 deletion crates/engine/src/tests/cancellation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,8 @@ pub(super) fn long_commands(boundaries: bool) {
layer.touch_geometry();
}
}
s.run("layer.addDataBytes", &json!({"fileName": "dem.tif", "data": if boundaries { tiny_raster(false) } else { dem_b64() }})).unwrap();
let data = if boundaries { tiny_raster(false) } else { dem_b64() };
s.run("layer.addDataBytes", &json!({"fileName": "dem.tif", "data": data})).unwrap();
let dem = s.map().layers.iter().find(|l| l.is_raster()).unwrap().name.clone();
// What some of them read: a later DEM, a slope, training squares, an imagery workspace, a
// two-class scene with its training polygons, and a layout.
Expand Down Expand Up @@ -87,6 +88,7 @@ pub(super) fn long_commands(boundaries: bool) {
("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")})),
("raster.mosaic", json!({"inputs": ["dem_later", out("tile.tif"), dem], "path": out("mosaic.tif")})),
(
"dl.classify",
json!({"layer": "scene", "training": "training", "classField": "class", "bands": [1, 2], "epochs": if boundaries { 2 } else { 30 }, "model": "landcover"}),
Expand Down Expand Up @@ -114,6 +116,12 @@ pub(super) fn long_commands(boundaries: bool) {
"index": "ndvi", "bbox": [10.0, 45.0, 10.02, 45.02]}),
),
];
// A mosaic's input read from a file, and a file where it writes its own: Cancel keeps both.
{
use base64::Engine;
std::fs::write(out("tile.tif"), base64::engine::general_purpose::STANDARD.decode(&data).unwrap()).unwrap();
std::fs::write(out("mosaic.tif"), b"before").unwrap();
}
// Every command that runs in the background is here, and only those.
/// Keeps the shared fixture list in step with the production registry.
fn listed<'a>(l: &[(&'a str, Value)]) -> std::collections::BTreeSet<&'a str> {
Expand Down
Loading