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
65 changes: 44 additions & 21 deletions crates/engine/src/cmd/embeddings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@

use std::collections::BTreeMap;

#[cfg(not(target_arch = "wasm32"))]
use rustgis_data::loss::{LossCode, Note};
use rustgis_data::{Geometry, GeometryType, raster};
use rustgis_map::raster::RasterLayer;
use serde_json::{Value, json};
Expand Down Expand Up @@ -823,14 +825,15 @@ pub(crate) fn similarity_work(s: &Session, p: &Value) -> Result<super::workflows
rustgis_data::progress::check().map_err(|e| e.to_string())?;
// Before anything is asked of the network: a layer that can't be the reference is refused.
let (points, from, taken) = points()?;
let (files, place, mut notes) = tile_files(area, &[year])?;
let (files, place, searched) = tile_files(area, &[year])?;
let mut notes: Vec<Note> = searched.into_iter().map(Note::plain).collect();

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.

searched is the search's own notes (series_notes, about line 424). Tiles past the search's list, and index rows that can't be read, are features left out of the read, and this maps them to Note::plain, so a strict run doesn't see them. The reference-layer counts a few lines up (about line 804, "features without geometry / that aren't points / can't be given in longitude/latitude, left out of the reference") are plain too, while the reference points left out just below are coded dropped.feature. The PR body lists only the reference-layer counts as kept plain on purpose, and not these. Either code the dropped rows and tiles and the reference left-outs dropped.feature (the same kind of loss as missed_points), or add them to "Kept plain on purpose" with the reason.

I haven't checked whether the search's notes ever report a loss that isn't a dropped feature. The inline comment covers only the notes that are clearly dropped rows or tiles.

Category: quality

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Kept plain in this PR: the search's notes mix tiles past the list with notes that only inform. Splitting them by code is left for the release quality pass.

let file = files.first().ok_or("AlphaEarth has no file there")?;
let w = read_window(file, area, cell)?;
notes.extend(w.notes());
let r = &w.raster;
// A reference with no embedding fails with what its layer said.
let (reference, missed) = reference(r, &points).map_err(|e| with_notes(e, &taken))?;
notes.extend(taken);
notes.extend(taken.into_iter().map(Note::plain));
notes.extend(missed_points(missed, points.len()));
let band = similarity_band(r, &reference)?;
let name = name.unwrap_or_else(|| format!("AlphaEarth {year} similarity"));
Expand Down Expand Up @@ -860,7 +863,8 @@ pub(crate) fn change_work(s: &Session, p: &Value) -> Result<super::workflows::Wo
#[cfg(not(target_arch = "wasm32"))]
Ok(Box::new(move || {
rustgis_data::progress::check().map_err(|e| e.to_string())?;
let (files, place, mut notes) = tile_files(area, &[from, to])?;
let (files, place, searched) = tile_files(area, &[from, to])?;
let mut notes: Vec<Note> = searched.into_iter().map(Note::plain).collect();
let (Some(a), Some(b)) = (files.first(), files.get(1)) else { return Err("AlphaEarth has no files there".into()) };
let a = read_window(a, area, cell)?;
let b = read_window(b, area, cell)?;
Expand All @@ -879,7 +883,7 @@ const IN_THE_BROWSER: &str = "AlphaEarth's similarity and change are worked out
/// The made raster, kept as a GeoTIFF, with what to say of it once it is added (by its name on
/// the map) and what the command answers besides.
#[cfg(not(target_arch = "wasm32"))]
fn made_saying(r: rustgis_data::raster::Raster, notes: Vec<String>, extra: Value) -> Result<super::workflows::Made, String> {
fn made_saying(r: rustgis_data::raster::Raster, notes: Vec<Note>, extra: Value) -> Result<super::workflows::Made, String> {
let bytes = raster::geotiff::write_all(&r).map_err(|e| e.to_string())?;
let name = r.name.clone();
let layer = RasterLayer::from_written(r, format!("{name}.tif"), bytes);
Expand All @@ -888,7 +892,7 @@ fn made_saying(r: rustgis_data::raster::Raster, notes: Vec<String>, extra: Value
let id = v.get("layer").and_then(Value::as_u64).and_then(|i| u32::try_from(i).ok());
let added = id.and_then(|id| s.map().layer(id)).map_or(said, |l| l.name.clone());
for note in notes {
s.notify(format!("{added}: {note}"), false);
s.say(note.prefixed(&added));
}
});
Ok(super::workflows::made_layer(name, layer, Some(extra), Some(then)))
Expand Down Expand Up @@ -956,26 +960,36 @@ fn pick_tile(found: &emb::SeriesFound, years: &[i32]) -> Result<(Vec<String>, St
/// are on one grid, so the second's says the same; anything it adds is said too, by its year),
/// and what each file's header left out, by year: once, for both, when both left it out.
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn two_years_notes(a: &super::layer::WindowRaster, b: &super::layer::WindowRaster, (from, to): (i32, i32)) -> Vec<String> {
let mut notes = a.read_notes();
pub(crate) fn two_years_notes(a: &super::layer::WindowRaster, b: &super::layer::WindowRaster, (from, to): (i32, i32)) -> Vec<Note> {
let mut notes: Vec<Note> = a.read_notes().into_iter().map(Note::plain).collect();
for n in b.read_notes() {
if !notes.contains(&n) {
notes.push(format!("the {to} file: {n}"));
if !notes.iter().any(|known| known.text == n) {
notes.push(Note::plain(format!("the {to} file: {n}")));
}
}
for l in a.raster.lost.texts() {
let both = b.raster.lost.says(l);
notes.push(if both { format!("the {from} and {to} files: {l}") } else { format!("the {from} file: {l}") });
for l in a.raster.lost.iter() {
let both = b.raster.lost.says(&l.text);
notes.push(if both {
l.clone().prefixed(&format!("the {from} and {to} files"))
} else {
l.clone().prefixed(&format!("the {from} file"))
});
}
notes.extend(b.raster.lost.texts().filter(|l| !a.raster.lost.says(l)).map(|l| format!("the {to} file: {l}")));
notes.extend(b.raster.lost.iter().filter(|l| !a.raster.lost.says(&l.text)).map(|l| l.clone().prefixed(&format!("the {to} file"))));
notes
}

/// What a similarity says of its reference points that have no embedding in the area read.
/// What a similarity says of its reference points that have no embedding in the area read: left
/// out of the reference, so a loss.
#[cfg(not(target_arch = "wasm32"))]
fn missed_points(missed: usize, of: usize) -> Option<String> {
fn missed_points(missed: usize, of: usize) -> Option<Note> {
(missed > 0).then(|| {
format!("{missed} of the {of} reference points have no embedding in the area read (outside it, or no data there) and were left out")
Note::loss(
LossCode::DroppedFeature,
format!(
"{missed} of the {of} reference points have no embedding in the area read (outside it, or no data there) and were left out"
),
)
})
}

Expand Down Expand Up @@ -1519,22 +1533,31 @@ mod tests {
// Reference points with no embedding: said with a count, nothing when all have one.
assert_eq!(missed_points(0, 3), None);
assert_eq!(
missed_points(1, 3).as_deref(),
Some("1 of the 3 reference points have no embedding in the area read (outside it, or no data there) and were left out")
missed_points(1, 3),
Some(Note::loss(
LossCode::DroppedFeature,
"1 of the 3 reference points have no embedding in the area read (outside it, or no data there) and were left out"
))
);
// What the work says is said once its raster is added, under the layer's name; a raster
// with nothing to say adds none.
let mut s = Session::new(Project::default());
let r = quantised([[1.0; 3]; 4]);
let made = |name: &str, notes: Vec<String>| {
let made = |name: &str, notes: Vec<Note>| {
let raster = rustgis_analysis::rasterops::derive(&r, name, vec![vec![0.5; 4]]).unwrap();
made_saying(raster, notes, json!({"year": 2024})).unwrap()
};
let mark = s.notice_mark();
let v = super::super::workflows::add_made(&mut s, made("Sim", notes.clone())).unwrap();
let mut with_loss: Vec<Note> = notes.iter().map(Note::from).collect();
with_loss.extend(missed_points(2, 5));
let v = super::super::workflows::add_made(&mut s, made("Sim", with_loss)).unwrap();
assert_eq!(v["year"], 2024);
let said: Vec<String> = s.notices_since(mark).iter().map(|n| n.text.clone()).collect();
assert_eq!(said.iter().filter(|n| n.starts_with("Sim: ")).count(), 5, "{said:?}");
assert_eq!(said.iter().filter(|n| n.starts_with("Sim: ")).count(), 6, "{said:?}");
// The loss keeps its code under the layer's name; the others are ordinary notices.
let coded: Vec<_> = s.notices_since(mark).iter().filter_map(|n| n.loss().map(|c| (c, n.text.clone()))).collect();
assert_eq!(coded.len(), 1, "{coded:?}");
assert!(coded[0].0 == LossCode::DroppedFeature && coded[0].1.starts_with("Sim: 2 of the 5 reference points"), "{coded:?}");
let mark = s.notice_mark();
super::super::workflows::add_made(&mut s, made("Clean", Vec::new())).unwrap();
assert!(!s.notices_since(mark).iter().any(|n| n.text.starts_with("Clean: ")));
Expand Down
44 changes: 41 additions & 3 deletions crates/engine/src/cmd/gp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -395,7 +395,15 @@ pub fn external_start(s: &mut Session, tool: &str, params: &Value) -> Result<Ext
return Err(format!("no GeoLibre tool '{tool}'"));
}
let params = params.clone();
let job = preparing(&continuation, || pin.prepare_suite(&map_inputs(s, Some(spec), &params, Tiled::ByPath)?, &params))?;
let (job, said, lost) = preparing(&continuation, || {
let inputs = map_inputs(s, Some(spec), &params, Tiled::ByPath)?;
Ok((pin.prepare_suite(&inputs, &params)?, inputs.messages.clone(), inputs.losses.clone()))
})?;
// What reading its inputs approximated or lost, said now, as a plugin tool's are.
if !said.is_empty() {
s.notify(format!("{}: {}", spec.name, said.join("; ")), false);
}
say_input_losses(s, spec.name, lost);
s.next_pending = s.next_pending.wrapping_add(1);
let id = s.next_pending;
let run = ExternalRun {
Expand Down Expand Up @@ -534,19 +542,21 @@ pub fn plugin_start(s: &mut Session, tool: &str, params: &Value) -> Result<Plugi
let spec = pin.spec();
let plugin = pin.plugin().ok_or_else(|| format!("no plugin tool '{tool}'"))?;
let (_, tid) = rustgis_plugins::split_id(spec.id).ok_or("invalid plugin tool id")?;
let (job, full_ids, said) = preparing(&continuation, || {
let (job, full_ids, said, lost) = preparing(&continuation, || {
let inputs = map_inputs(s, Some(spec), resolved, Tiled::Overview)?;
let job = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
rustgis_plugins::tools::prepare_pinned(plugin.plugin(), tid, &inputs, resolved)
}))
.unwrap_or_else(|_| Err(format!("{} failed unexpectedly", spec.name)))?;
Ok((job, full_ids(&inputs.loaded), inputs.messages.clone()))
Ok((job, full_ids(&inputs.loaded), inputs.messages.clone(), inputs.losses.clone()))
})?;
// What reading its inputs approximated (a raster's overview read for a file read in place),
// said now: the run's result is the plugin's own.
if !said.is_empty() {
s.notify(format!("{}: {}", spec.name, said.join("; ")), false);
}
// What reading its inputs lost (a layer's rows or geometry left out), as a loss with its code.
say_input_losses(s, spec.name, lost);
Comment thread
Mavrick-F marked this conversation as resolved.
Resolved
let read = read_layers(s, spec, resolved);
s.next_pending = s.next_pending.wrapping_add(1);
let id = s.next_pending;
Expand Down Expand Up @@ -4170,6 +4180,13 @@ fn apply_with(
Ok((out, messages))
}

/// Says what reading a plugin tool's inputs lost, each as a loss with its code, under the tool's name.
fn say_input_losses(s: &mut Session, tool: &str, lost: Vec<LossMessage>) {
for loss in lost {
publish_tool_loss(s, loss.code, &format!("{tool}: {}", loss.text), false);
}
}

/// Publishes a typed loss, retaining it through rollback when a file has already been delivered.
fn publish_tool_loss(s: &mut Session, code: LossCode, text: &str, written: bool) {
let mark = s.notice_mark();
Expand All @@ -4183,6 +4200,27 @@ fn publish_tool_loss(s: &mut Session, code: LossCode, text: &str, written: bool)
mod file_tests {
use super::*;

#[test]
fn a_plugin_tools_input_losses_are_said_with_their_codes() {
let mut s = Session::new(crate::Project::default());
let mark = s.notice_mark();
say_input_losses(&mut s, "Make Points", Vec::new());
assert!(s.notices_since(mark).is_empty(), "a clean read says nothing");
let lost = vec![
LossMessage { code: LossCode::DroppedFeature, text: "Sites: 2 rows couldn't be read and were left out".into() },
LossMessage { code: LossCode::DroppedValue, text: "Sites: 1 value isn't a date and was read as empty, in 'day'".into() },
];
say_input_losses(&mut s, "Make Points", lost);
let said: Vec<_> = s.notices_since(mark).iter().map(|n| (n.loss(), n.text.clone())).collect();
assert_eq!(
said,
[
(Some(LossCode::DroppedFeature), "Make Points: Sites: 2 rows couldn't be read and were left out".to_string()),
(Some(LossCode::DroppedValue), "Make Points: Sites: 1 value isn't a date and was read as empty, in 'day'".to_string()),
]
);
}

#[test]
fn raster_to_pmtiles_queues_the_archive_without_changing_the_map() {
use rustgis_data::raster::{ColorHint, Crs, GeoTransform, Raster};
Expand Down
31 changes: 25 additions & 6 deletions crates/engine/src/cmd/imagery.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1777,17 +1777,34 @@ pub(crate) fn process_work(s: &Session, p: &Value) -> Result<super::workflows::W
format!("no cell of {} falls inside {pl} ({} polygon part(s) failed raster projection)", r.name, failed_parts.len())
})?;
let clipped = clip_window(&r, cols, rows, Some(&mask), None, out)?;
let mut messages = Vec::new();
// Each a loss with its code: said as a notice once the clip is added, and kept in the
// answer's `messages` for a script.
let mut notes = Vec::new();
if skipped > 0 {
messages.push(format!("{pl}: skipped {skipped} feature(s) with invalid polygon geometry"));
notes.push(rustgis_data::loss::Note::loss(
rustgis_data::loss::LossCode::DroppedFeature,
format!("{pl}: skipped {skipped} feature(s) with invalid polygon geometry"),
));
Comment on lines +1784 to +1787

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.

Features with an invalid polygon are left out of the clip, so dropped.feature fits here. The same loss is coded dropped.geometry in its twins: zonal statistics (crates/analysis/src/tools.rs, "feature(s) had invalid geometry, so their statistics are empty", about line 8753) and Tabulate Area (crates/analysis/src/tools/tabulate_area.rs, "zone feature(s) had invalid polygon geometry and were excluded", about line 121). The loss.rs comment says producers must use the same code for the same loss, so a strict run with --allow dropped.feature clears the clip but not the zonal statistics, and the reverse. Pick one code for excluded polygon features and use it in all three. dropped.feature matches the code's own description. The analysis twins are outside this diff, so either fix them in this PR or in a follow-up.

Category: quality

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Here a whole feature is left out of the clip, so dropped.feature. Whether its twins should code the same loss alike is left for the release quality pass.

}
if !failed_parts.is_empty() {
messages.push(format!(
"{pl}: skipped {} polygon part(s) that could not be projected onto the raster grid; valid parts were retained",
failed_parts.len()
notes.push(rustgis_data::loss::Note::loss(
rustgis_data::loss::LossCode::DroppedGeometry,
format!(
"{pl}: skipped {} polygon part(s) that could not be projected onto the raster grid; valid parts were retained",
failed_parts.len()
),
));
}
super::workflows::made(clipped, (!messages.is_empty()).then(|| json!({"messages": messages})))
let messages: Vec<&str> = notes.iter().map(|n| n.text.as_str()).collect();
let extra = (!messages.is_empty()).then(|| json!({"messages": messages}));
let then: Option<super::workflows::Then> = (!notes.is_empty()).then(|| {
Box::new(move |s: &mut Session, _: &mut Value| {
for note in notes {
s.say(note);
}
}) as super::workflows::Then
});
super::workflows::made_then(clipped, extra, then)
}))
}
"clip" => {
Expand Down Expand Up @@ -2701,6 +2718,8 @@ fn clip_window(
}
// Some of the values rounded when the file was read may be in the window: how many isn't known.
out.keep_rounded_mark(r);
// What reading the input left out was said, with its code, when the input was read: a clip,
// like a resample or a pixel edit, doesn't say it again.
Ok(out)
}

Expand Down
7 changes: 4 additions & 3 deletions crates/engine/src/cmd/layer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6742,9 +6742,10 @@ pub(crate) struct WindowRaster {
impl WindowRaster {
/// What to say of the read, in order, and what its raster left out (`lost`: what the header
/// holds but isn't read, values past `f32`'s range), for a caller that makes another raster
/// from it and so doesn't add this one (whose `lost` the layer would say).
pub(crate) fn notes(&self) -> Vec<String> {
self.read_notes().into_iter().chain(self.raster.lost.texts().map(String::from)).collect()
/// from it and so doesn't add this one (whose `lost` the layer would say). The read's own notes
/// are plain (the box's edges are empty ground, not data left out); `lost` keeps its codes.
pub(crate) fn notes(&self) -> Vec<rustgis_data::loss::Note> {
self.read_notes().into_iter().map(rustgis_data::loss::Note::plain).chain(self.raster.lost.iter().cloned()).collect()
}

/// What to say of the read alone (its size and level, a cell size finer than the file's, the
Expand Down
Loading
Loading