diff --git a/crates/engine/command-surface.txt b/crates/engine/command-surface.txt index 2f99f709a9..a033aafd91 100644 --- a/crates/engine/command-surface.txt +++ b/crates/engine/command-surface.txt @@ -125,7 +125,7 @@ edit.updateBox layer? row featureId? box edit.updateCircle layer? row featureId? circle edit.vertex layer? row action part? ring? index lon? lat? embeddings.add dataset url? year? bands? stretch? dimension? bbox? name? ran? -embeddings.addCube dataset bbox? start? end? bands? stretch? name? found? complete? +embeddings.addCube dataset bbox? start? end? bands? stretch? name? found? complete? unusable? embeddings.change dataset from? to? bbox? cellSize? name? ran? embeddings.datasets embeddings.search dataset year? bbox? footprints? diff --git a/crates/engine/src/cmd/embeddings.rs b/crates/engine/src/cmd/embeddings.rs index a4575436d0..050b51614e 100644 --- a/crates/engine/src/cmd/embeddings.rs +++ b/crates/engine/src/cmd/embeddings.rs @@ -32,7 +32,7 @@ pub fn commands() -> Vec { r#"{"dataset": "alphaearth" | "earth-index" | "tessera" | "olmoearth", "url"?: "AlphaEarth's tile or Earth Index's file, as embeddings.search lists it (Earth Index: default the MGRS tile at the view's centre)", "year"?: number (Tessera and OlmoEarth, default 2024), "bands"?: [red, green, blue] (bands from 1; AlphaEarth default [2, 17, 10], Tessera and OlmoEarth [1, 2, 3]), "stretch"?: number (AlphaEarth: dequantised values shown over ±stretch, default 0.3), "dimension"?: number (Earth Index: a vector value kept as each point's `value`, from 1), "bbox"?: [west, south, east, north] | "view" (Earth Index, Tessera and OlmoEarth: the area read, default the map's extent), "name"?: text, "ran"?: (internal: what the app read)}"#, ), C::new("embeddings.addCube", "Add Satellite Embeddings over Time", "Home › Add › Web Data", add_cube).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Network)).params( - r#"{"dataset": "alphaearth", "bbox"?: [west, south, east, north] | "view" (the area searched, default the map's extent), "start"?: year (default 2017), "end"?: year (default 2025), "bands"?: [red, green, blue] (bands from 1, default [2, 17, 10]), "stretch"?: number (dequantised values shown over ±stretch, default 0.3), "name"?: text, "found"?: (internal: the tiles the app found, each {years: {year: address}}), "complete"?: (internal: false when the app's search read only part of the index)} → a tile layer per AlphaEarth tile, a file per year, following the time slider (turned on over the years when it is off)"#, + r#"{"dataset": "alphaearth", "bbox"?: [west, south, east, north] | "view" (the area searched, default the map's extent), "start"?: year (default 2017), "end"?: year (default 2025), "bands"?: [red, green, blue] (bands from 1, default [2, 17, 10]), "stretch"?: number (dequantised values shown over ±stretch, default 0.3), "name"?: text, "found"?: (internal: the tiles the app found, each {years: {year: address}}), "complete"?: (internal: false when the app's search read only part of the index), "unusable"?: (internal: the rows of the index the app's search left out, as they can't be read)} → a tile layer per AlphaEarth tile, a file per year, following the time slider (turned on over the years when it is off)"#, ), // Each makes a raster; on another thread from the app (workflows::IN_BACKGROUND). C::new("embeddings.similarity", "Satellite Embedding Similarity", "Home › Add › Web Data", similarity).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Network)).params( @@ -118,16 +118,15 @@ fn search(s: &mut Session, p: &Value) -> CmdResult { } #[cfg(not(target_arch = "wasm32"))] { - let (tiles, complete) = match d.id { + let found = match d.id { "alphaearth" => emb::search_aef_blocking(area, year)?, "earth-index" => emb::search_earth_index_blocking(area)?, - _ => tessera::tiles(tessera::store(d.id).ok_or_else(|| format!("{} can't be searched", d.name))?, area, year), + _ => tessera::tiles(tessera::store(d.id).ok_or_else(|| format!("{} can't be searched", d.name))?, area, year).into(), }; + search_notices(s, d, &found); + let emb::Found { tiles, complete, .. } = found; let mut r = json!({"dataset": d.id, "year": year, "count": tiles.len(), "complete": complete, "tiles": tiles.iter().map(emb::Tile::to_json).collect::>()}); - if !complete { - s.notify(format!("{}: the area holds more tiles than one search reads; zoom in to list them all", d.name), false); - } if super::b(p, "footprints") != Some(false) && !tiles.is_empty() && tessera::store(d.id).is_none() { let name = format!("{} tiles {year}", d.name.split(" (").next().unwrap_or(d.name)); if let Some(id) = super::stac::add_collection(s, &emb::footprints_geojson(&tiles), &name)? { @@ -138,6 +137,17 @@ fn search(s: &mut Session, p: &Value) -> CmdResult { } } +/// Says what a search left out: rows past one read, and rows that can't be read. +#[cfg(not(target_arch = "wasm32"))] +fn search_notices(s: &mut Session, d: &emb::EmbeddingDataset, found: &emb::Found) { + if !found.complete { + s.notify(format!("{}: the area holds more tiles than one search reads; zoom in to list them all", d.name), false); + } + if let Some(note) = emb::unusable_note(found.unusable, found.complete) { + s.notify(format!("{}: {note}", d.name), false); + } +} + fn add(s: &mut Session, p: &Value) -> CmdResult { let d = dataset(p)?; let name = ps(p, "name").map(str::trim).filter(|n| !n.is_empty()).map(str::to_string); @@ -220,24 +230,28 @@ fn add_cube(s: &mut Session, p: &Value) -> CmdResult { let given = p.get("found").filter(|v| !v.is_null()); // Whether the index was read whole: a tile-year with no file is then the index's gap, not // the read's. The files handed over outside the years asked for, left out. And what the - // search left out, said once the cube is added (a refused one adds nothing to speak of). - let (series, complete, outside, notes) = match given { + // search left out, said once the cube is added (a refused one adds nothing to speak of), or + // with the error when there is no tile; the rows that can't be read, of which one may be a file. + let (series, complete, outside, unusable, notes) = match given { Some(v) => { let (series, outside) = found(v, start, end)?; let complete = super::b(p, "complete") != Some(false); // A part read: said even when every year of the tiles handed over is there. - let notes = if complete { Vec::new() } else { vec![PART_READ.to_string()] }; - (series, complete, outside, notes) + let unusable = p.get("unusable").and_then(Value::as_u64).and_then(|n| usize::try_from(n).ok()).unwrap_or(0); + let left = emb::SeriesFound { complete, unusable, ..Default::default() }; + (series, complete, outside, unusable, series_notes(&left)) } None => { - let (series, complete, notes) = search_series(s, p, (start, end))?; - (series, complete, 0, notes) + let f = search_series(s, p, (start, end))?; + let notes = series_notes(&f); + (f.series.into_iter().map(|x| x.years).collect(), f.complete, 0, f.unusable, notes) } }; let listed = series.len(); let series: Vec> = series.into_iter().filter(|y| !y.is_empty()).collect(); if series.is_empty() { - return Err(format!("AlphaEarth has no tiles there for {start}–{end}")); + let left = if notes.is_empty() { String::new() } else { format!(" ({})", notes.join("; ")) }; + return Err(format!("AlphaEarth has no tiles there for {start}–{end}{left}")); } let room = rustgis_map::tiles::MAX_TILE_LAYERS.saturating_sub(s.map().tiles.len()); if series.len() > room { @@ -325,19 +339,22 @@ fn add_cube(s: &mut Session, p: &Value) -> CmdResult { false, ); } + let read = if unusable > 0 { ", among the rows that can be read" } else { "" }; if listed > series.len() { - s.notify(format!("{base}: {} of the {listed} tiles have no file in {start}–{end} and were left out", listed - series.len()), false); + let n = listed - series.len(); + s.notify(format!("{base}: {n} of the {listed} tiles have no file in {start}–{end}{read} and were left out"), false); } if missing > 0 { let total = series.len() * span; + let (index, zoom) = if complete { + ("AlphaEarth's index", "") + } else { + ("the part of AlphaEarth's index that was read", " (zoom in to read it whole)") + }; s.notify( - if complete { - format!("{base}: {missing} of the {total} tile-years have no file in AlphaEarth's index; in those years the tile shows nothing") - } else { - format!( - "{base}: {missing} of the {total} tile-years have no file in the part of AlphaEarth's index that was read (zoom in to read it whole); in those years the tile shows nothing" - ) - }, + format!( + "{base}: {missing} of the {total} tile-years have no file in {index}{read}{zoom}; in those years the tile shows nothing" + ), false, ); } @@ -377,9 +394,8 @@ fn found(v: &Value, start: i32, end: i32) -> Result<(Vec>, } /// AlphaEarth's tiles over the years where the command says, from one read of the index, waiting -/// for it (the command line); whether it read the index whole for the area; and what the read -/// left out, to be said. -fn search_series(s: &mut Session, p: &Value, years: (i32, i32)) -> Result<(Vec>, bool, Vec), String> { +/// for it (the command line), with what the read left out. +fn search_series(s: &mut Session, p: &Value, years: (i32, i32)) -> Result { let area = bbox(s, p)?; #[cfg(target_arch = "wasm32")] { @@ -394,18 +410,15 @@ fn search_series(s: &mut Session, p: &Value, years: (i32, i32)) -> Result<(Vec Vec { let mut notes = Vec::new(); if !f.complete { @@ -417,6 +430,7 @@ fn series_notes(f: &emb::SeriesFound) -> Vec { if f.duplicates > 0 { notes.push(format!("AlphaEarth: {} tile-years had a second file in the index; the first was taken", f.duplicates)); } + notes.extend(emb::unusable_note(f.unusable, f.complete).map(|n| format!("AlphaEarth: {n}"))); notes } @@ -744,7 +758,10 @@ fn pick_tile(found: &emb::SeriesFound, years: &[i32]) -> Result<(Vec, St ), }; // A part of the index read: the tile may be in the rest of it. - if found.complete { none } else { format!("{none}, in the part of the index that was read: take a smaller box to read it whole") } + let none = + if found.complete { none } else { format!("{none}, in the part of the index that was read: take a smaller box to read it whole") }; + // Or in a row left out. + emb::unusable_note(found.unusable, found.complete).map_or_else(|| none.clone(), |n| format!("{none} ({n})")) })?; let files: Vec = years.iter().filter_map(|y| tile.years.get(y).cloned()).collect(); let place = files.first().and_then(|u| emb::aef_place(u)).unwrap_or_else(|| tile.tile.title.clone()); @@ -764,6 +781,7 @@ fn pick_tile(found: &emb::SeriesFound, years: &[i32]) -> Result<(Vec, St if found.duplicates > 0 { notes.push(format!("{} tile-years had a second file in AlphaEarth's index; the first was taken", found.duplicates)); } + notes.extend(emb::unusable_note(found.unusable, found.complete)); if kept + dropped > 1 { notes.push(format!( "the area meets {} AlphaEarth tiles: one is read ({place}), the nearest its centre with files for {listed}; a box within one tile is read whole", @@ -1042,6 +1060,46 @@ mod tests { let whole = json!([{"years": {"2024": file(2024, "7-8"), "2025": file(2025, "7-8")}}]); v.run("embeddings.addCube", &json!({"dataset": "alphaearth", "start": 2024, "found": whole, "complete": false})).unwrap(); assert!(v.notices.iter().any(|n| n.text.contains("more tiles than one search reads")), "a part read is said"); + // Rows the search left out, as they can't be read, one of which may be the file: said, with a + // missing year's notice that doesn't call it the index's gap, and in the error of no tiles. + let mut x = Session::new(Project::default()); + let some = json!([{"years": {"2025": file(2025, "9-1")}}]); + let gap = |end: &str| format!("1 of the 2 tile-years have no file in {end}; in those years the tile shows nothing"); + let dated = ", among the rows that can be read"; + for (complete, end) in [ + (true, format!("AlphaEarth's index{dated}")), + (false, format!("the part of AlphaEarth's index that was read{dated} (zoom in to read it whole)")), + ] { + let p = json!({"dataset": "alphaearth", "start": 2024, "found": some, "complete": complete, "unusable": 4}); + x.run("embeddings.addCube", &p).unwrap(); + let said: Vec<&str> = x.notices.iter().map(|n| n.text.as_str()).collect(); + let note = if complete { "read: 4" } else { "read: 4 of those read" }; + assert!( + said.iter().any(|n| n.ends_with(&format!("left out, as their date, address or footprint can't be {note}"))), + "{said:?}" + ); + assert!(said.iter().any(|n| n.ends_with(&gap(&end))), "{said:?}"); + x.notices.clear(); + } + let out = json!([{"years": {"2025": file(2025, "9-2")}}, {"years": {"2016": file(2016, "9-3")}}]); + x.run("embeddings.addCube", &json!({"dataset": "alphaearth", "start": 2024, "found": out, "unusable": 4})).unwrap(); + let out = format!("1 of the 2 tiles have no file in 2024–2025{dated} and were left out"); + assert!(x.notices.iter().any(|n| n.text.ends_with(&out)), "{out}"); + let none = json!([{"years": {"2016": file(2016, "9-1")}}]); + let empty = |x: &mut Session, unusable: u64| { + let p = json!({"dataset": "alphaearth", "start": 2024, "found": none, "unusable": unusable}); + x.run("embeddings.addCube", &p).unwrap_err() + }; + let e = empty(&mut x, 4); + assert!( + e.ends_with("(AlphaEarth: rows of AlphaEarth's index left out, as their date, address or footprint can't be read: 4)"), + "{e}" + ); + assert_eq!(empty(&mut x, 0), "AlphaEarth has no tiles there for 2024–2025"); + // So is a part of the index read. + let part = json!({"dataset": "alphaearth", "start": 2024, "found": none, "complete": false, "unusable": 4}); + let e = x.run("embeddings.addCube", &part).unwrap_err(); + assert!(e.contains(PART_READ) && e.ends_with("can't be read: 4 of those read)"), "{e}"); // An hourly slider widened over the years would be more steps than it lists: refused, // the slider and the map as they were. let mut h = Session::new(Project::default()); @@ -1082,12 +1140,30 @@ mod tests { fn series_notes_say_what_a_search_left_out() { let whole = emb::SeriesFound { complete: true, ..Default::default() }; assert!(series_notes(&whole).is_empty(), "a whole search says nothing"); - let gaps = emb::SeriesFound { complete: false, dropped: 61, duplicates: 2, ..Default::default() }; + let gaps = emb::SeriesFound { complete: false, dropped: 61, duplicates: 2, unusable: 4, ..Default::default() }; let notes = series_notes(&gaps); - assert_eq!(notes.len(), 3, "{notes:?}"); + assert_eq!(notes.len(), 4, "{notes:?}"); + assert_eq!( + notes[3], + "AlphaEarth: rows of AlphaEarth's index left out, as their date, address or footprint can't be read: 4 of those read" + ); assert!(notes.iter().any(|n| n == PART_READ), "{notes:?}"); assert!(notes.iter().any(|n| n.contains("61 tiles past the 60 a search lists were left out")), "{notes:?}"); assert!(notes.iter().any(|n| n.contains("2 tile-years had a second file in the index")), "{notes:?}"); + // A search of one year says the rows left out too, and nothing when there were none. + let mut s = Session::new(Project::default()); + let d = emb::dataset("alphaearth").unwrap(); + search_notices(&mut s, d, &emb::Found { complete: true, ..Default::default() }); + assert!(s.notices.is_empty()); + search_notices(&mut s, d, &emb::Found { complete: true, unusable: 4, ..Default::default() }); + assert!( + s.notices.len() == 1 && s.notices[0].text.ends_with("left out, as their date, address or footprint can't be read: 4"), + "{:?}", + s.notices[0].text + ); + // So does the tile a similarity or a change picks, or fails to. + let e = pick_tile(&emb::SeriesFound { complete: true, unusable: 4, ..Default::default() }, &[2024]).unwrap_err(); + assert!(e.starts_with("AlphaEarth has no tiles there (rows of AlphaEarth's index left out"), "{e}"); } /// A plugin's command in the app (`leave_downloads`) doesn't read an AlphaEarth tile's header @@ -1240,32 +1316,38 @@ mod tests { years: years.iter().map(|y| (*y, format!("https://x.org/{y}/23S/h{y}-{place}.tiff"))).collect(), }; // One tile, the index read whole: nothing to say. - let one = emb::SeriesFound { series: vec![tile("0-0", &[2017, 2025])], dropped: 0, duplicates: 0, complete: true }; + let one = emb::SeriesFound { series: vec![tile("0-0", &[2017, 2025])], dropped: 0, duplicates: 0, complete: true, unusable: 0 }; let (files, place, notes) = pick_tile(&one, &[2017, 2025]).unwrap(); assert_eq!(files, ["https://x.org/2017/23S/h2017-0-0.tiff", "https://x.org/2025/23S/h2025-0-0.tiff"]); assert_eq!((place.as_str(), notes.len()), ("23S 0-0", 0)); // The nearest tile without 2017: the next one is read. Part of the index read, and three // tiles past a search's list: each said, the tiles counted with them. - let many = - emb::SeriesFound { series: vec![tile("0-0", &[2025]), tile("0-1", &[2017, 2025])], dropped: 3, duplicates: 2, complete: false }; + let many = emb::SeriesFound { + series: vec![tile("0-0", &[2025]), tile("0-1", &[2017, 2025])], + dropped: 3, + duplicates: 2, + complete: false, + unusable: 4, + }; let (files, place, notes) = pick_tile(&many, &[2017, 2025]).unwrap(); assert_eq!((files.len(), place.as_str()), (2, "23S 0-1")); - assert_eq!(notes.len(), 4, "{notes:?}"); + assert_eq!(notes.len(), 5, "{notes:?}"); assert!(notes[0].contains("a tile nearer its centre may have been missed"), "{notes:?}"); assert_eq!(notes[1], "3 AlphaEarth tiles past the 60 nearest the area's centre were left out, not looked at: take a smaller box"); assert_eq!(notes[2], "2 tile-years had a second file in AlphaEarth's index; the first was taken"); - assert!(notes[3].starts_with("the area meets 5 AlphaEarth tiles: one is read (23S 0-1)"), "{notes:?}"); + assert_eq!(notes[3], "rows of AlphaEarth's index left out, as their date, address or footprint can't be read: 4 of those read"); + assert!(notes[4].starts_with("the area meets 5 AlphaEarth tiles: one is read (23S 0-1)"), "{notes:?}"); // No tile with the years: tiles left out are said, not taken for none there, and so is a // part of the index read. let e = pick_tile(&many, &[2018]).unwrap_err(); assert!(e.contains("none of the 2 AlphaEarth tiles nearest the area's centre has files for 2018, and 3 more"), "{e}"); assert!( e.ends_with( - "and 3 more were left out: take a smaller box, in the part of the index that was read: take a smaller box to read it whole" + "and 3 more were left out: take a smaller box, in the part of the index that was read: take a smaller box to read it whole (rows of AlphaEarth's index left out, as their date, address or footprint can't be read: 4 of those read)" ), "{e}" ); - let kept = emb::SeriesFound { dropped: 0, duplicates: 0, complete: true, ..many.clone() }; + let kept = emb::SeriesFound { dropped: 0, duplicates: 0, complete: true, unusable: 0, ..many.clone() }; assert_eq!(pick_tile(&kept, &[2018]).unwrap_err(), "AlphaEarth has no tile there with files for 2018"); assert_eq!( pick_tile(&emb::SeriesFound { complete: true, ..emb::SeriesFound::default() }, &[2018]).unwrap_err(), @@ -1289,7 +1371,7 @@ mod tests { let v = super::super::workflows::add_made(&mut s, made("Sim", notes.clone())).unwrap(); assert_eq!(v["year"], 2024); let said: Vec = s.notices_since(mark).iter().map(|n| n.text.clone()).collect(); - assert_eq!(said.iter().filter(|n| n.starts_with("Sim: ")).count(), 4, "{said:?}"); + assert_eq!(said.iter().filter(|n| n.starts_with("Sim: ")).count(), 5, "{said:?}"); 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: "))); diff --git a/crates/tiles/src/embeddings.rs b/crates/tiles/src/embeddings.rs index 8b519ba1a7..b4de4ebd66 100644 --- a/crates/tiles/src/embeddings.rs +++ b/crates/tiles/src/embeddings.rs @@ -282,6 +282,51 @@ fn year_of(t: i64) -> i32 { i32::try_from(y).unwrap_or(0) } +/// The year of an index row, from its `datetime`: a timestamp column, read as date-times since +/// native dates (#1894), and before them as a number since 1970 or as text. +fn aef_year(v: &Value) -> Option { + match v { + Value::DateTime(t) => i32::try_from(t.date().ymd().0).ok(), + Value::Date(d) => i32::try_from(d.ymd().0).ok(), + Value::Int(t) => Some(year_of(*t)), + Value::Text(t) => t.get(..4).and_then(|y| y.parse().ok()), + _ => None, + } +} + +/// What a search takes of a row of the index (its `datetime` in column `date`, its address in +/// `href`): its year, its file's web address and its footprint. `None` when one can't be read. +fn row_parts(f: &Feature, date: Option, href: Option) -> Option<(i32, String, &Geometry)> { + let at = |c: Option| f.attrs.get(c?); + let url = https(&at(href)?.to_string()); + Some((aef_year(at(date)?)?, url.starts_with("https://").then_some(url)?, f.geometry.as_ref()?)) +} + +/// How many rows of what the index read a search can't use ([`row_parts`], and those whose footprint +/// the reader couldn't decode) and leaves out; an error when it can use none of an index read whole, +/// as the search would answer that there are no tiles (a read in part didn't see the others, and is +/// said as one). A row without a footprint is in no box, so a search reads none. +fn unusable(fields: &[Field], batch: &Batch) -> Result { + let col = |n: &str| fields.iter().position(|f| f.name == n); + let (date, href) = (col("datetime"), col(AEF_HREF)); + let usable = batch.features.iter().filter(|f| row_parts(f, date, href).is_some()).count(); + let n = (batch.features.len() - usable).saturating_add(batch.skipped); + if n > 0 && usable == 0 && batch.complete { + return Err(format!( + "AlphaEarth's index has {n} rows there, none whose date, address and footprint can be read, so its tiles can't be listed" + )); + } + Ok(n) +} + +/// What to say of the `n` rows of AlphaEarth's index a search left out, as it can't use them +/// ([`Found::unusable`], [`SeriesFound::unusable`]), of those it read when it read the index in part +/// (not `complete`): nothing when there were none. +pub fn unusable_note(n: usize, complete: bool) -> Option { + let read = if complete { "" } else { " of those read" }; + (n > 0).then(|| format!("rows of AlphaEarth's index left out, as their date, address or footprint can't be read: {n}{read}")) +} + /// The tiles of a year in what the index read, nearest the box's centre first (at most /// [`MAX_TILES`]). pub fn aef_tiles(fields: &[Field], batch: &Batch, year: i32, bbox: [f64; 4]) -> Vec { @@ -301,19 +346,7 @@ fn aef_rows(fields: &[Field], batch: &Batch, bbox: [f64; 4], keep: impl Fn(i32) .features .iter() .filter_map(|f| { - let year = date.and_then(|c| f.attrs.get(c)).and_then(|v| match v { - Value::Int(t) => Some(year_of(*t)), - Value::Text(t) => t.get(..4).and_then(|y| y.parse().ok()), - _ => None, - })?; - if !keep(year) { - return None; - } - let url = https(&text(f, href)); - if !url.starts_with("https://") { - return None; - } - let g = f.geometry.as_ref()?; + let (year, url, g) = row_parts(f, date, href).filter(|(year, ..)| keep(*year))?; let e = g.extent(); let footprint = match g { Geometry::Polygon(p) => { @@ -373,6 +406,8 @@ pub struct SeriesFound { pub duplicates: usize, /// Whether the index was read whole for the box. pub complete: bool, + /// Rows left out because their date, address or footprint can't be read. + pub unusable: usize, } /// How far apart (degrees, about 10 m) two years' footprint corners may be and still be one @@ -449,9 +484,34 @@ pub fn aef_place(url: &str) -> Option { Some(format!("{zone} {place}")) } -/// What a search found: the tiles, and whether the index was read whole for the box (a box -/// holding more rows than one search reads is read in part, and the map should be zoomed in). -pub type Found = (Vec, bool); +/// What a search found. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Found { + pub tiles: Vec, + /// Whether the index was read whole for the box (a box holding more rows than one search reads + /// is read in part, and the map should be zoomed in). + pub complete: bool, + /// Rows of the index left out because their date, address or footprint can't be read (AlphaEarth). + pub unusable: usize, +} + +impl From<(Vec, bool)> for Found { + fn from((tiles, complete): (Vec, bool)) -> Self { + Found { tiles, complete, unusable: 0 } + } +} + +/// [`Found`], from what the index read. +fn found(fields: &[Field], batch: &Batch, year: i32, bbox: [f64; 4]) -> Result { + let unusable = unusable(fields, batch)?; + Ok(Found { tiles: aef_tiles(fields, batch, year, bbox), complete: batch.complete, unusable }) +} + +/// [`SeriesFound`], from what the index read. +fn series_found(fields: &[Field], batch: &Batch, years: (i32, i32), bbox: [f64; 4]) -> Result { + let unusable = unusable(fields, batch)?; + Ok(SeriesFound { unusable, ..aef_series(fields, batch, years, bbox) }) +} fn aef_request(bbox: [f64; 4]) -> Request { Request { extent: Some(Extent::new(bbox[0], bbox[1], bbox[2], bbox[3])), limit: MAX_INDEX_ROWS, own: None } @@ -467,9 +527,7 @@ pub fn search_aef(bbox: [f64; 4], year: i32, done: Box Result { let bbox = check_bbox(bbox)?; let (fields, batch) = rustgis_data::source::query_url_blocking(AEF_INDEX, vec![AEF_HREF.into()], aef_request(bbox)).map_err(|e| e.to_string())?; - Ok((aef_tiles(&fields, &batch, year, bbox), batch.complete)) + found(&fields, &batch, year, bbox) } /// Finds AlphaEarth's tiles in a box over the years `first` to `last`, each with its file a year: @@ -493,7 +551,7 @@ pub fn search_aef_series(bbox: [f64; 4], years: (i32, i32), done: Box Result Err(e), - _ => Ok((found, all)), + _ => Ok((found, all).into()), }); } }), @@ -1015,6 +1073,89 @@ mod tests { assert_eq!(aef_series(&[], &batch, (2017, 2025), [0.0, 0.0, 1.0, 1.0]).series, Vec::new()); } + /// The index as its reader gives it: a Parquet timestamp column, read as date-times. + #[test] + fn index_rows_read_from_parquet_have_their_years() { + use rustgis_data::DateTime; + use rustgis_data::source::{FeatureSource, parquet}; + let file = |date: &dyn Fn(i32) -> Value| { + let fields = vec![ + Field::new("id", FieldType::Text), + Field::new("datetime", FieldType::DateTime), + Field::new(AEF_HREF, FieldType::Text), + Field::new("proj:epsg", FieldType::Text), + ]; + let mut ds = Dataset::new("index", GeometryType::Polygon, fields); + for year in [2017, 2024, 2025] { + let ring = [(-43.4, -21.0), (-42.6, -21.0), (-42.6, -20.7), (-43.4, -20.7), (-43.4, -21.0)]; + let ring = ring.iter().map(|(x, y)| Coord::new(*x, *y)).collect(); + let href = format!("s3://us-west-2.opendata.source.coop/a/{year}/23S/x{year}-0-0.tiff"); + let attrs = vec![Value::Text("1".into()), date(year), Value::Text(href), Value::Text("EPSG:32723".into())]; + ds.push(Some(Geometry::Polygon(vec![vec![ring]])), attrs); + } + let src = parquet::ParquetSource::open_bytes(parquet::write(&ds).unwrap(), "index").unwrap().exact(); + (src.info().fields.clone(), src.read(&Request::all()).unwrap()) + }; + let bbox = [-42.89, -20.76, -42.87, -20.74]; + // 1 January in UTC, as the index has it, and without a zone. + let micros = |year: i32| year_start_ms(year) as i64 * 1000; + for utc in [true, false] { + let at = |y: i32| if utc { DateTime::with_offset(micros(y), 0) } else { DateTime::local(micros(y)) }; + let (fields, batch) = file(&|y| Value::DateTime(at(y).unwrap())); + assert!(matches!(batch.features.first().and_then(|f| f.attrs.get(1)), Some(Value::DateTime(_)))); + let one = found(&fields, &batch, 2024, bbox).unwrap(); + assert_eq!((one.tiles.len(), one.complete, one.unusable), (1, true, 0)); + assert_eq!(one.tiles[0].url, "https://data.source.coop/a/2024/23S/x2024-0-0.tiff"); + let f = series_found(&fields, &batch, (2017, 2025), bbox).unwrap(); + let years: Vec> = f.series.iter().map(|s| s.years.keys().copied().collect()).collect(); + assert_eq!((years, f.unusable), (vec![vec![2017, 2024, 2025]], 0)); + // A year with no file is no tiles, while the dates are read. + assert_eq!(found(&fields, &batch, 2020, bbox), Ok((Vec::new(), true).into())); + } + // A row without a date among others is left out, counted whatever the year asked for. + let (fields, batch) = file(&|y| if y == 2025 { Value::Null } else { Value::DateTime(DateTime::local(micros(y)).unwrap()) }); + let left = found(&fields, &batch, 2024, bbox).unwrap(); + assert_eq!((left.tiles.len(), left.unusable), (1, 1)); + let left = series_found(&fields, &batch, (2017, 2025), bbox).unwrap(); + assert_eq!((left.series[0].years.len(), left.unusable), (2, 1)); + // So are rows without a web address, or without a footprint. + let (fields, whole) = file(&|y| Value::DateTime(DateTime::local(micros(y)).unwrap())); + let spoil: [fn(&mut Feature); 2] = [|f| f.attrs[2] = Value::Text("ftp://nowhere".into()), |f| f.geometry = None]; + for spoil in spoil { + let mut batch = whole.clone(); + spoil(&mut batch.features[0]); + assert_eq!(found(&fields, &batch, 2024, bbox).unwrap().unusable, 1); + assert_eq!(series_found(&fields, &batch, (2017, 2025), bbox).unwrap().unusable, 1); + } + // And those in the box whose footprint the reader couldn't decode, which it counts itself. + let mut batch = Batch { skipped: 2, ..whole.clone() }; + assert_eq!(found(&fields, &batch, 2024, bbox).unwrap().unusable, 2); + assert_eq!(series_found(&fields, &batch, (2017, 2025), bbox).unwrap().unusable, 2); + batch.features.clear(); + assert!(found(&fields, &batch, 2024, bbox).unwrap_err().contains("has 2 rows there")); + assert_eq!( + unusable_note(1, true).as_deref(), + Some("rows of AlphaEarth's index left out, as their date, address or footprint can't be read: 1") + ); + assert!(unusable_note(1, false).unwrap().ends_with("can't be read: 1 of those read")); + assert_eq!((unusable_note(0, true), unusable_note(0, false)), (None, None)); + // Rows whose dates can't be read are said, not taken for no tiles; no rows are no tiles. + let (fields, mut batch) = file(&|_| Value::Null); + let e = found(&fields, &batch, 2024, bbox).unwrap_err(); + assert!(e.contains("has 3 rows there, none whose date, address and footprint can be read"), "{e}"); + assert_eq!(series_found(&fields, &batch, (2017, 2025), bbox).unwrap_err(), e); + // A read in part didn't see the others, which may be good: no error, the part read being said. + batch.complete = false; + let part = found(&fields, &batch, 2024, bbox).unwrap(); + assert_eq!((part.tiles.len(), part.complete, part.unusable), (0, false, 3)); + assert_eq!(series_found(&fields, &batch, (2017, 2025), bbox).unwrap().unusable, 3); + batch.complete = true; + batch.features.clear(); + assert_eq!(found(&fields, &batch, 2024, bbox), Ok((Vec::new(), true).into())); + assert_eq!(aef_year(&Value::Date(rustgis_data::Date::from_ymd(2024, 1, 1).unwrap())), Some(2024)); + assert_eq!(aef_year(&Value::Text("2024-01-01T00:00:00Z".into())), Some(2024)); + } + #[test] fn principal_component_colours() { // Two clusters along one direction: their first component tells them apart. diff --git a/crates/ui-egui/src/embeddingsui.rs b/crates/ui-egui/src/embeddingsui.rs index 9eb8d2d0a3..3227b32346 100644 --- a/crates/ui-egui/src/embeddingsui.rs +++ b/crates/ui-egui/src/embeddingsui.rs @@ -58,6 +58,8 @@ pub struct State { pub found: Vec, /// Each tile found's file a year, by `found`'s order, when the search was over the years. years: Vec>, + /// The rows that search left out, as they can't be read (handed over as `unusable`). + years_unusable: usize, /// Whether the search over the years read the index whole (handed over as `complete`). years_whole: bool, /// The footprints layer of the last search, and its project (`Session::opened`): layer ids @@ -81,6 +83,7 @@ impl Default for State { searched: None, found: Vec::new(), years: Vec::new(), + years_unusable: 0, years_whole: true, footprints: None, error: None, @@ -135,12 +138,13 @@ struct Listed { years: Vec>, dropped: usize, duplicates: usize, + unusable: usize, } impl Listed { fn of_series(f: SeriesFound) -> Listed { let (tiles, years) = f.series.into_iter().map(|s| (s.tile, s.years)).unzip(); - Listed { tiles, complete: f.complete, years, dropped: f.dropped, duplicates: f.duplicates } + Listed { tiles, complete: f.complete, years, dropped: f.dropped, duplicates: f.duplicates, unusable: f.unusable } } } @@ -152,7 +156,7 @@ pub fn poll(app: &mut RustGisApp, ctx: &egui::Context) { .lock() .unwrap_or_else(|e| e.into_inner()) .take() - .map(|r| Ok(r.map(|(tiles, complete)| Listed { tiles, complete, ..Default::default() }))), + .map(|r| Ok(r.map(|f| Listed { tiles: f.tiles, complete: f.complete, unusable: f.unusable, ..Default::default() }))), Some(Read::Series(slot)) => slot.lock().unwrap_or_else(|e| e.into_inner()).take().map(|r| Ok(r.map(Listed::of_series))), Some(Read::Data(slot, _)) => slot.lock().unwrap_or_else(|e| e.into_inner()).take().map(Err), }; @@ -163,7 +167,7 @@ pub fn poll(app: &mut RustGisApp, ctx: &egui::Context) { let read = app.ui.embeddings.reading.take(); match landed { Ok(found) => match found { - Ok(Listed { tiles, complete, years, dropped, duplicates }) => { + Ok(Listed { tiles, complete, years, dropped, duplicates, unusable }) => { let st = &mut app.ui.embeddings; // A search for a dataset no longer picked: its tiles aren't this one's. // Or for a project since closed. @@ -171,7 +175,8 @@ pub fn poll(app: &mut RustGisApp, ctx: &egui::Context) { if st.searched.is_some_and(|(_, d, o)| d != st.dataset || o != opened) { return; } - let mut info = if tiles.is_empty() { + // Nothing found in a part of the index read is said as one. + let mut info = if tiles.is_empty() && complete { tl!("Nothing found where the map is").to_string() } else if complete { crate::i18n::fmt("{n} found where the map is", &[("n", &tiles.len().to_string())]) @@ -190,10 +195,25 @@ pub fn poll(app: &mut RustGisApp, ctx: &egui::Context) { &[("n", &duplicates.to_string())], )); } + if unusable > 0 { + let n = unusable.to_string(); + info.push_str(&if complete { + crate::i18n::fmt( + " · rows of the index left out, as their date, address or footprint can't be read: {n}", + &[("n", &n)], + ) + } else { + crate::i18n::fmt( + " · rows of the index left out, as their date, address or footprint can't be read: {n} of those read", + &[("n", &n)], + ) + }); + } st.info = Some(info); st.found = tiles; st.years = years; st.years_whole = complete; + st.years_unusable = unusable; show_footprints(app); } Err(e) => app.ui.embeddings.error = Some(e), @@ -294,7 +314,7 @@ fn search(app: &mut RustGisApp) { match st.dataset { "alphaearth" => emb::search_aef(bbox, st.year, done), "earth-index" => emb::search_earth_index(bbox, done), - id => done(Ok(tessera::tiles(tessera::store(id).unwrap_or(&tessera::TESSERA), bbox, st.year))), + id => done(Ok(tessera::tiles(tessera::store(id).unwrap_or(&tessera::TESSERA), bbox, st.year).into())), } st.reading = Some(Read::Search(slot)); } @@ -317,7 +337,7 @@ fn add(app: &mut RustGisApp, i: usize) { ( "embeddings.addCube", json!({ - "dataset": "alphaearth", "found": found, "complete": st.years_whole, + "dataset": "alphaearth", "found": found, "complete": st.years_whole, "unusable": st.years_unusable, "start": first, "end": last, "bands": bands, "stretch": stretch, }), ) @@ -692,3 +712,38 @@ fn card(ui: &mut egui::Ui, t: &crate::theme::Tokens, tile: &Tile, i: usize, busy ui.add_space(2.0); act } + +#[cfg(test)] +mod tests { + use super::*; + + /// A search says the index's rows it left out, of one year and over the years, and nothing + /// when there were none. + #[test] + fn a_search_says_the_rows_it_left_out() { + let mut app = RustGisApp::with_sample(); + let ctx = egui::Context::default(); + let mut said = |read: Read| { + app.ui.embeddings.reading = Some(read); + poll(&mut app, &ctx); + let st = &mut app.ui.embeddings; + (st.info.take().unwrap(), st.years_unusable) + }; + for (unusable, left) in [(0, false), (4, true)] { + let one = Found { complete: true, unusable, ..Default::default() }; + let years = SeriesFound { complete: true, unusable, ..Default::default() }; + for (info, handed) in [ + said(Read::Search(std::sync::Arc::new(std::sync::Mutex::new(Some(Ok(one)))))), + said(Read::Series(std::sync::Arc::new(std::sync::Mutex::new(Some(Ok(years)))))), + ] { + assert_eq!(info.ends_with("left out, as their date, address or footprint can't be read: 4"), left, "{info}"); + // What embeddings.addCube is handed with a tile found. + assert_eq!(handed, unusable); + } + } + // Of a part of the index read: said as one, though nothing is found in it. + let part = Found { unusable: 4, ..Default::default() }; + let (info, _) = said(Read::Search(std::sync::Arc::new(std::sync::Mutex::new(Some(Ok(part)))))); + assert!(info.contains("more than one search reads") && info.ends_with("can't be read: 4 of those read"), "{info}"); + } +}