From 6d65c920686bdd68499c5155dbb4d13d18299f83 Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Mon, 19 Oct 2026 10:11:00 -0300 Subject: [PATCH 1/8] Zarr: a variable that follows the time slider (#554) layer.addZarr takes "time": true. The variable's time axis is read from its CF coordinate (model calendars included) and the layer shows the last of its steps in the slider's window, or nothing when none falls in it; the slider turns on over the axis when it is off, and "start"/"end" take a period of a longer axis. Moving, playing or exporting the slider reads that step's slice, only its chunks, keeping the last eight; a web store's next two steps are read ahead in the background. The stretch is fixed at the first slice's range, so a colour means one value at every step. The project keeps the layer by its store and selection (ZarrTime) and reads the slider's step again when it opens. The Zarr dialog has a Follow the time slider box (desktop). Co-Authored-By: Claude Opus 5.5 --- crates/data/src/raster/zarr.rs | 75 +++++++++ crates/engine/src/cmd/project.rs | 2 + crates/engine/src/cmd/time.rs | 7 + crates/engine/src/cmd/zarr.rs | 255 ++++++++++++++++++++++++++++++- crates/engine/src/project.rs | 3 + crates/engine/src/tests.rs | 105 +++++++++++++ crates/map/src/raster.rs | 77 +++++++++- crates/ui-egui/src/zarrui.rs | 26 ++++ docs/user-guide/data.md | 14 ++ docs/user-guide/workspace.md | 2 + 10 files changed, 563 insertions(+), 3 deletions(-) diff --git a/crates/data/src/raster/zarr.rs b/crates/data/src/raster/zarr.rs index 1243a599af..09ac1c7adf 100644 --- a/crates/data/src/raster/zarr.rs +++ b/crates/data/src/raster/zarr.rs @@ -1256,6 +1256,81 @@ pub fn info_keys(store: &Store) -> Vec { keys } +/// The chunk keys of the coordinates of `variable`'s dimensions other than the map's (as +/// [`info_keys`] lists them for every variable). +pub fn coordinate_keys(store: &Store, variable: &str) -> Vec { + let Some(v) = store.array(variable) else { return Vec::new() }; + let (y, x) = map_dims(v); + let mut keys = Vec::new(); + for (d, name) in v.dim_names().iter().enumerate() { + if d == y || d == x { + continue; + } + if let Some(c) = + store.coordinate(v, name).filter(|c| c.shape.first().is_some_and(|n| *n <= MAX_COORDS) && c.unsupported().is_none()) + { + keys.extend(all_keys(c).into_iter().filter(|k| !keys.contains(k)).collect::>()); + } + } + keys +} + +/// `variable`'s time dimension: the first of its dimensions other than the map's whose +/// coordinate has CF time units (`days since 2001-01-01`), with its steps as milliseconds since +/// 1970 (UTC). A model calendar's dates are taken by their day, one past its month's end (360_day's +/// 30 February) on the month's last. `None` when no dimension has such a coordinate, or one of +/// its steps isn't a date. +pub fn time_axis(store: &Store, variable: &str, chunks: &HashMap>) -> Option<(String, Vec)> { + let v = store.array(variable)?; + let (y, x) = map_dims(v); + for (d, name) in v.dim_names().iter().enumerate() { + if d == y || d == x { + continue; + } + let Some(c) = store.coordinate(v, name) else { continue }; + if !attr_str(c, "units").is_some_and(|u| u.contains(" since ")) { + continue; + } + let Ok(vals) = values_1d(c, chunks) else { continue }; + let ms: Option> = vals.iter().map(|t| time_ms(c, *t)).collect(); + if let Some(ms) = ms.filter(|m| !m.is_empty()) { + return Some((name.clone(), ms)); + } + } + None +} + +/// A CF time coordinate's value as milliseconds since 1970 (see [`time_axis`]). +fn time_ms(c: &Array, v: f64) -> Option { + let units = attr_str(c, "units")?; + let calendar = attr_str(c, "calendar").unwrap_or("standard").to_ascii_lowercase(); + let (unit, since) = units.split_once(" since ")?; + let secs = match unit.trim().to_ascii_lowercase().as_str() { + "seconds" | "second" | "s" => 1.0, + "minutes" | "minute" | "min" => 60.0, + "hours" | "hour" | "h" => 3600.0, + "days" | "day" | "d" => 86_400.0, + _ => return None, + }; + if !(v.is_finite() && v.abs() < 1e13) { + return None; + } + let since = since.trim(); + let t = match calendar.as_str() { + "standard" | "gregorian" | "proleptic_gregorian" => epoch_seconds(since)? + v * secs, + "noleap" | "365_day" | "all_leap" | "366_day" | "360_day" => { + let day = fixed_calendar(&calendar, since, v * secs)?; + let mut p = day.splitn(3, '-').map(|x| x.parse::().ok()); + let (y, m, d) = (p.next()??, p.next()??, p.next()??); + let last = days_from_civil(if m == 12 { y + 1 } else { y }, if m == 12 { 1 } else { m + 1 }, 1) - days_from_civil(y, m, 1); + days_from_civil(y, m, d.min(last)) as f64 * 86_400.0 + (v * secs).rem_euclid(86_400.0) + } + _ => return None, + }; + let ms = t * 1000.0; + ms.is_finite().then_some(ms) +} + /// A coordinate value as a label: a CF time (`days since 1850-01-01`) as a date, else the /// number and units. fn label(c: &Array, v: f64) -> String { diff --git a/crates/engine/src/cmd/project.rs b/crates/engine/src/cmd/project.rs index 782de94fc5..55a6bcc309 100644 --- a/crates/engine/src/cmd/project.rs +++ b/crates/engine/src/cmd/project.rs @@ -51,6 +51,8 @@ fn reset(s: &mut Session, p: Project) { s.tool = Tool::Explore; s.clear_history(); s.history_from_file = s.project.gp_history.len(); + // Zarr layers that follow the time slider read the step it is at. + super::zarr::follow_time(s); } fn new(s: &mut Session, p: &Value) -> CmdResult { diff --git a/crates/engine/src/cmd/time.rs b/crates/engine/src/cmd/time.rs index 8758c1301f..3e050cc3aa 100644 --- a/crates/engine/src/cmd/time.rs +++ b/crates/engine/src/cmd/time.rs @@ -32,6 +32,7 @@ pub fn commands() -> Vec { let id = s.layer_id(p)?; let l = s.map_mut().layer_mut(id).ok_or("no such layer")?; let was = l.time.take().map(|t| t.field); + super::zarr::follow_time(s); Ok(json!({"unbound": was})) }) .when(need_feature_layer) @@ -61,6 +62,7 @@ pub fn commands() -> Vec { }; sl.go_to(t); m.apply_time(); + super::zarr::follow_time(s); Ok(info(s)) }) .view() @@ -72,6 +74,7 @@ pub fn commands() -> Vec { let m = s.map_mut(); m.time.as_mut().ok_or("the time slider is off")?.step(by, wrap); m.apply_time(); + super::zarr::follow_time(s); Ok(info(s)) }) .view() @@ -167,6 +170,7 @@ pub(crate) fn set(s: &mut Session, p: &Value) -> CmdResult { if b(p, "off") == Some(true) { s.map_mut().time = None; s.map_mut().apply_time(); + super::zarr::follow_time(s); return Ok(info(s)); } let (start, end, at) = (date(p, "start")?, date(p, "end")?, date(p, "date")?); @@ -245,6 +249,7 @@ pub(crate) fn set(s: &mut Session, p: &Value) -> CmdResult { t.normalize(); t.go_to(target); m.apply_time(); + super::zarr::follow_time(s); Ok(info(s)) } @@ -310,6 +315,8 @@ fn frames(s: &mut Session, steps: &[f64], w: f64, h: f64, gif: Option) -> R sl.current = *t; } s.map_mut().apply_time(); + // Zarr layers that follow the slider read this step's slice. + super::zarr::follow_time(s); // Dated tile layers have this step's address now: natively, map_png (through // rustgis_render::render_complete) fetches the tiles it lacks and waits for them // before it draws, so each frame shows its own date's imagery. diff --git a/crates/engine/src/cmd/zarr.rs b/crates/engine/src/cmd/zarr.rs index 1720c60656..8d9a2e3dad 100644 --- a/crates/engine/src/cmd/zarr.rs +++ b/crates/engine/src/cmd/zarr.rs @@ -9,9 +9,11 @@ use std::path::Path; use rustgis_data::raster::{self, Crs, zarr}; use rustgis_map::raster::RasterLayer; +#[cfg(not(target_arch = "wasm32"))] +use rustgis_map::raster::ZarrTime; use serde_json::Value; -use super::ps; +use super::{b, ps}; use crate::{CmdResult, CommandSpec as C, Session}; pub fn commands() -> Vec { @@ -20,7 +22,7 @@ pub fn commands() -> Vec { .view() .params(r#"{"path": "a Zarr store's folder" | "url": "https://… a store with consolidated metadata"}"#), C::new("layer.addZarr", "Add Zarr Variable", "Home › Add › Add Data", add).params( - r#"{"path": folder | "url": "https://…", "variable"?: "its path in the store (default: the first)", "index"?: {"time": 3, "level": 0} (other dimensions' steps, default 0), "crs"?: "EPSG:… for a store that doesn't say", "name"?: text, "ran"?: (internal: a slice the app has read)}"#, + r#"{"path": folder | "url": "https://…", "variable"?: "its path in the store (default: the first)", "index"?: {"time": 3, "level": 0} (other dimensions' steps, default 0), "crs"?: "EPSG:… for a store that doesn't say", "name"?: text, "time"?: bool (follow the time slider: the layer shows the step the slider is at, and turns the slider on over the variable's dates when it is off; desktop), "start"?, "end"?: dates (with time: the period to take, for an axis longer than the slider's 20,000 steps), "ran"?: (internal: a slice the app has read)}"#, ), ] } @@ -182,6 +184,9 @@ pub fn pick_variable(store: &zarr::Store, sel: &mut zarr::Selection) -> Result<( } pub(crate) fn add(s: &mut Session, p: &Value) -> CmdResult { + if b(p, "time") == Some(true) { + return add_following(s, p); + } let src = source(p)?; #[cfg_attr(target_arch = "wasm32", allow(unused_mut))] let mut sel = selection(p); @@ -236,3 +241,249 @@ pub(crate) fn add(s: &mut Session, p: &Value) -> CmdResult { } } } + +// --- Following the time slider (opengeos/RustGIS#554) -------------------------------------------- + +/// Slices kept for layers that follow the time slider, by store and selection: the last few, so +/// stepping back and forth or looping doesn't read them again. +#[cfg(not(target_arch = "wasm32"))] +const SLICES_KEPT: usize = 8; + +/// The slices kept (see [`SLICES_KEPT`]), newest last. +#[cfg(not(target_arch = "wasm32"))] +fn slices() -> &'static std::sync::Mutex)>> { + static S: std::sync::OnceLock)>>> = std::sync::OnceLock::new(); + S.get_or_init(Default::default) +} + +/// Web stores' metadata, read once per run (the last few stores). +#[cfg(not(target_arch = "wasm32"))] +fn stores() -> &'static std::sync::Mutex)>> { + static S: std::sync::OnceLock)>>> = std::sync::OnceLock::new(); + S.get_or_init(Default::default) +} + +#[cfg(not(target_arch = "wasm32"))] +fn is_web(store: &str) -> bool { + let lower = store.to_ascii_lowercase(); + lower.starts_with("http://") || lower.starts_with("https://") +} + +/// A web store's metadata, from the run's cache when it was read before. +#[cfg(not(target_arch = "wasm32"))] +fn cached_store(url: &str) -> Result, String> { + if let Some((_, st)) = stores().lock().ok().and_then(|c| c.iter().find(|(u, _)| u == url).cloned()) { + return Ok(st); + } + let st = std::sync::Arc::new(store_at(url)?); + if let Ok(mut c) = stores().lock() { + c.push((url.to_string(), st.clone())); + let excess = c.len().saturating_sub(4); + c.drain(..excess); + } + Ok(st) +} + +/// Step `i` of a following layer's variable, from the kept slices or read now. +#[cfg(not(target_arch = "wasm32"))] +fn read_step(zt: &ZarrTime, i: usize) -> Result, String> { + let sel = zt.selection(i); + let key = format!("{}\u{0}{sel}\u{0}{}", zt.store, zt.crs.as_deref().unwrap_or("")); + if let Some((_, r)) = slices().lock().ok().and_then(|c| c.iter().find(|(k, _)| *k == key).cloned()) { + return Ok(r); + } + let crs = zt.crs.as_deref().map(str::trim).filter(|c| !c.is_empty()); + let r = if is_web(&zt.store) { + let st = cached_store(&zt.store)?; + let plan = zarr::plan(&st, &zarr::Selection::parse(&sel)).map_err(|e| e.to_string())?; + let (chunks, _) = fetch(&zt.store, &plan.keys)?; + let crs = crs.map(Crs::parse).transpose()?; + zarr::assemble(&st, &plan, &chunks, &sel, crs).map_err(|e| e.to_string())? + } else { + zarr::read_dir(Path::new(&zt.store), &sel, crs).map_err(|e| e.to_string())? + }; + let r = std::sync::Arc::new(r); + if let Ok(mut c) = slices().lock() { + c.retain(|(k, _)| *k != key); + c.push((key, r.clone())); + let excess = c.len().saturating_sub(SLICES_KEPT); + c.drain(..excess); + } + Ok(r) +} + +/// Layers that follow the time slider read the step it shows, in every map: the last of their +/// steps in the slider's window, or none (the layer draws nothing) when no step falls in it. A +/// web store's next steps are then read ahead in the background, so playing doesn't wait for +/// each. A slice that can't be read leaves its layer empty, and says why. +pub(crate) fn follow_time(s: &mut Session) { + #[cfg(not(target_arch = "wasm32"))] + { + let mut errors = Vec::new(); + let mut ahead: Vec<(ZarrTime, usize)> = Vec::new(); + for m in &mut s.project.maps { + let window = m.time.as_ref().map(rustgis_map::time::TimeSlider::window); + for l in &mut m.layers { + let name = l.name.clone(); + let Some(rl) = l.raster.as_mut() else { continue }; + let Some(zt) = rl.time_zarr.as_mut() else { continue }; + let want = zt.step_for(window); + if want == zt.shown && (want.is_none() || rl.data.is_some()) { + continue; + } + match want { + None => { + rl.data = None; + zt.shown = None; + } + Some(i) => match read_step(zt, i) { + Ok(r) => { + rl.data = Some(r); + zt.shown = Some(i); + if is_web(&zt.store) { + ahead.push((zt.clone(), i)); + } + } + Err(e) => { + rl.data = None; + zt.shown = None; + errors.push(format!("{name}: {e}")); + } + }, + } + } + } + for e in errors { + s.notify(e, true); + } + for (zt, i) in ahead { + std::thread::spawn(move || { + for j in (i + 1..zt.dates.len()).take(2) { + if read_step(&zt, j).is_err() { + break; + } + } + }); + } + } + #[cfg(target_arch = "wasm32")] + let _ = s; +} + +/// `layer.addZarr` with `"time": true`: the variable's time axis read from its coordinate, a layer +/// that shows the step the slider is at, and the slider turned on over the axis when it is off. +/// The stretch is fixed at the first slice's, so a colour means one value at every step. +fn add_following(s: &mut Session, p: &Value) -> CmdResult { + #[cfg(target_arch = "wasm32")] + { + let _ = (s, p); + Err("in the web app, a Zarr variable can't follow the time slider yet".into()) + } + #[cfg(not(target_arch = "wasm32"))] + { + if p.get("ran").is_some_and(|r| !r.is_null()) { + return Err("time and ran don't go together".into()); + } + let src = source(p)?; + let mut sel = selection(p); + let crs = ps(p, "crs").map(str::trim).filter(|c| !c.is_empty()).map(str::to_string); + if let Some(c) = &crs { + Crs::parse(c)?; + } + let (root, store, chunks) = match src { + Source::Dir(d) => { + let store = zarr::read_metadata(Path::new(&d)).map_err(|e| format!("{d}: {e}"))?; + let mut chunks = HashMap::new(); + let mut total = 0u64; + for k in zarr::coordinate_keys(&store, &sel.variable) { + let path = Path::new(&d).join(&k); + let Ok(meta) = std::fs::metadata(&path) else { continue }; + if !meta.is_file() || meta.len() > zarr::MAX_CHUNK_FILE { + continue; + } + total = total.saturating_add(meta.len()); + if total > zarr::MAX_READ { + return Err(format!("{d}: the coordinates are too large to read")); + } + if let Ok(b) = std::fs::read(&path) { + chunks.insert(k, b); + } + } + let full = std::path::absolute(&d).map(|p| p.display().to_string()).unwrap_or(d); + (full, std::sync::Arc::new(store), chunks) + } + Source::Url(u) => { + let store = cached_store(&u)?; + (u, store, HashMap::new()) + } + }; + pick_variable(&store, &mut sel)?; + let chunks = + if chunks.is_empty() && is_web(&root) { fetch(&root, &zarr::coordinate_keys(&store, &sel.variable))?.0 } else { chunks }; + let (dim, dates) = zarr::time_axis(&store, &sel.variable, &chunks).ok_or_else(|| { + format!("{} has no time dimension (a coordinate with CF units, such as \"days since 2001-01-01\")", sel.variable) + })?; + // The period asked for, else the whole axis. + let date = |k: &str| -> Result, String> { + match p.get(k).filter(|v| !v.is_null()) { + None => Ok(None), + Some(v) => rustgis_data::time::parse_input(v) + .map(Some) + .ok_or_else(|| format!("{k} is a date (2015-06-01, a year, or milliseconds since 1970)")), + } + }; + let (start, end) = (date("start")?, date("end")?); + let inside = |d: &f64| start.is_none_or(|a| *d >= a) && end.is_none_or(|z| *d <= z); + let first = dates.iter().position(inside).ok_or("no step of the variable falls between start and end")?; + let picked: Vec = dates[first..].iter().copied().take_while(inside).collect(); + if picked.len() > rustgis_map::raster::MAX_ZARR_STEPS { + return Err(format!( + "{} has {} steps there; the time slider takes {} at most: give start and end", + sel.variable, + picked.len(), + rustgis_map::raster::MAX_ZARR_STEPS + )); + } + let mut zt = ZarrTime { + store: root.clone(), + variable: sel.variable.clone(), + index: sel.index.iter().filter(|(d, _)| *d != dim).cloned().collect(), + dim, + offset: first as u64, + dates: picked, + crs, + shown: None, + }; + zt.repair(); + // The slider, on over the variable's dates when it is off. + if s.map().time.is_none() { + let dates: Vec = zt.dates.iter().map(|d| serde_json::json!(d)).collect(); + super::time::set(s, &serde_json::json!({"dates": dates}))?; + } + let window = s.map().time.as_ref().map(rustgis_map::time::TimeSlider::window); + let want = zt.step_for(window); + // The first slice the layer shows sets its style; with no step in the window, the first step's. + let r = read_step(&zt, want.unwrap_or(0)).map_err(|e| format!("{root}: {e}"))?; + let mut layer = RasterLayer::from_path((*r).clone(), root.clone()); + if is_web(&root) { + layer.path = None; + } + layer.data = want.map(|_| r.clone()); + // One stretch for every step: the first slice's range, fixed. + let band = layer.style.renderer.bands().first().copied().unwrap_or(0); + if !matches!(layer.style.stretch, rustgis_map::raster::Stretch::Custom { .. }) + && let Some(stats) = r.bands.get(band).map(|b| &b.stats) + { + let n = rustgis_map::raster::Normalizer::new(layer.style.stretch, stats, &r.data_type); + if n.lo.is_finite() && n.hi.is_finite() && n.lo < n.hi { + layer.style.stretch = rustgis_map::raster::Stretch::Custom { min: n.lo, max: n.hi }; + } + } + zt.shown = want; + let name = ps(p, "name") + .map(str::to_string) + .unwrap_or_else(|| layer_name(&root, &zarr::Selection { variable: zt.variable.clone(), index: zt.index.clone() }, &[])); + layer.time_zarr = Some(zt); + super::raster::add_raster(s, &name, layer) + } +} diff --git a/crates/engine/src/project.rs b/crates/engine/src/project.rs index 057ae4b044..b2d14dacf6 100644 --- a/crates/engine/src/project.rs +++ b/crates/engine/src/project.rs @@ -504,6 +504,9 @@ impl Project { m.tiles.retain_mut(|t| t.repair().map_err(|e| log::warn!("{}: {e}", m.name)).is_ok()); m.tiles.truncate(rustgis_map::tiles::MAX_TILE_LAYERS); for l in &mut m.layers { + if let Some(z) = l.raster.as_mut().and_then(|r| r.time_zarr.as_mut()) { + z.repair(); + } if let Some(rl) = &mut l.raster && rl.data.is_none() && let Err(e) = rl.reload() diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index ed4bd73d3b..38afb832b6 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -6278,6 +6278,111 @@ fn lidar_point_clouds() { /// and by Add Data, saved by folder and selection and read again when the project opens; a slice /// the app read itself handed over by id. #[cfg(not(target_arch = "wasm32"))] +/// A Zarr store in a temporary folder: `t` over three monthly steps (days since 2001-01-01: 0, +/// 31, 59) on a 3 × 4 grid, step `k`'s values `100·k + i`. +fn zarr_store_over_time(tag: &str) -> (std::path::PathBuf, String) { + let dir = std::env::temp_dir().join(format!("rustgis-zarr-{tag}-{}", std::process::id())); + let store = dir.join("air.zarr"); + let _ = std::fs::remove_dir_all(&dir); + for d in ["t", "lat", "lon", "time"] { + std::fs::create_dir_all(store.join(d)).unwrap(); + } + let arr = |shape: &str, chunks: &str, dtype: &str| { + serde_json::from_str::(&format!( + r#"{{"shape":{shape},"chunks":{chunks},"dtype":"{dtype}","compressor":null,"fill_value":null,"filters":null,"order":"C","zarr_format":2}}"# + )) + .unwrap() + }; + let meta = json!({"metadata": { + ".zgroup": {"zarr_format": 2}, + "t/.zarray": arr("[3,3,4]", "[1,3,4]", ">(); + std::fs::write(store.join("lat/0"), f32s(&[10.0, 20.0, 30.0])).unwrap(); + std::fs::write(store.join("lon/0"), f32s(&[1.0, 2.0, 3.0, 4.0])).unwrap(); + std::fs::write(store.join("time/0"), [0i32, 31, 59].iter().flat_map(|x| x.to_le_bytes()).collect::>()).unwrap(); + for t in 0..3 { + let v: Vec = (0..12).map(|i| (t * 100 + i) as f32).collect(); + std::fs::write(store.join(format!("t/{t}.0.0")), f32s(&v)).unwrap(); + } + let path = store.display().to_string(); + (dir, path) +} + +/// A Zarr variable follows the time slider (#554): the slice drawn is the step the slider is at, +/// the stretch is the same at every step, and the project keeps the layer by its store. +#[test] +fn a_zarr_variable_follows_the_time_slider() { + let (dir, path) = zarr_store_over_time("follow"); + let mut s = Session::new(Project::default()); + let id = s.run("layer.addZarr", &json!({"path": path, "variable": "t", "time": true})).unwrap()["layer"].as_u64().unwrap() as u32; + // The slider is on over the variable's three dates, at the first. + let info = s.run("time.info", &Value::Null).unwrap(); + assert_eq!(info["steps"], 3, "{info}"); + let first = |s: &Session| s.map().layer(id).and_then(|l| l.raster.as_ref()).and_then(|r| r.data.as_ref()).map(|d| d.bands[0].data[0]); + // North up: the last latitude row first; step k's values are 100·k + i. + assert_eq!(first(&s), Some(8.0)); + let rl = s.map().layer(id).unwrap().raster.clone().unwrap(); + assert!(matches!(rl.style.stretch, rustgis_map::raster::Stretch::Custom { .. }), "{:?}", rl.style.stretch); + assert!(s.map().layer(id).unwrap().name.ends_with(" t"), "{}", s.map().layer(id).unwrap().name); + let stretch = rl.style.stretch; + // Moving the slider moves the slice; the stretch stays. + s.run("time.goTo", &json!({"step": 2})).unwrap(); + assert_eq!(first(&s), Some(208.0)); + s.run("time.step", &json!({"by": -1})).unwrap(); + assert_eq!(first(&s), Some(108.0)); + assert_eq!(s.map().layer(id).unwrap().raster.as_ref().unwrap().style.stretch, stretch); + // Saved and opened again: the store and the step, read again. + let text = serde_json::to_string(&s.project).unwrap(); + assert!(text.contains("\"time_zarr\"") && !text.contains("\"embedded\""), "kept by its store, not as a slice"); + let mut t = Session::new(Project::default()); + t.run("project.openText", &json!({"text": text})).unwrap(); + let again = t + .map() + .layers + .iter() + .find(|l| l.is_raster()) + .and_then(|l| l.raster.as_ref()) + .and_then(|r| r.data.as_ref()) + .map(|d| d.bands[0].data[0]); + assert_eq!(again, Some(108.0)); + // A window with no step of the variable: nothing drawn. + s.run("time.set", &json!({"dates": ["2000-06-01", "2001-01-01", "2001-02-01", "2001-03-01"], "date": "2000-06-01"})).unwrap(); + assert_eq!(first(&s), None); + s.run("time.goTo", &json!({"step": 3})).unwrap(); + assert_eq!(first(&s), Some(208.0)); + // The animation reads each step's slice. + let zip = std::env::temp_dir().join(format!("rustgis-zarr-frames-{}.zip", std::process::id())); + let r = s.run("time.export", &json!({"path": zip.display().to_string(), "width": 64, "height": 48})).unwrap(); + assert_eq!(r["frames"], 4, "{r}"); + let _ = std::fs::remove_file(zip); + // A period: the steps from February on, the layer's first step the second of the axis. + let id2 = s.run("layer.addZarr", &json!({"path": path, "variable": "t", "time": true, "start": "2001-01-20", "name": "late"})).unwrap() + ["layer"] + .as_u64() + .unwrap() as u32; + let zt = s.map().layer(id2).unwrap().raster.as_ref().unwrap().time_zarr.clone().unwrap(); + assert_eq!((zt.offset, zt.dates.len(), zt.dim.as_str()), (1, 2, "time")); + for bad in [ + json!({"path": path, "variable": "t", "time": true, "start": "2002-01-01"}), + json!({"path": path, "variable": "t", "time": true, "start": "June"}), + json!({"path": path, "variable": "t", "time": true, "ran": 1}), + json!({"path": path, "variable": "lat", "time": true}), + ] { + assert!(s.run("layer.addZarr", &bad).is_err(), "{bad}"); + } + let _ = std::fs::remove_dir_all(dir); +} + #[test] fn zarr_stores_in_folders_and_handed_over() { let dir = std::env::temp_dir().join(format!("rustgis-zarr-{}", std::process::id())); diff --git a/crates/map/src/raster.rs b/crates/map/src/raster.rs index 9ef5a36151..da523d8155 100644 --- a/crates/map/src/raster.rs +++ b/crates/map/src/raster.rs @@ -32,6 +32,10 @@ pub struct RasterLayer { /// For a raster GDAL reads: the coordinate system given for a file that doesn't say. #[serde(default, skip_serializing_if = "Option::is_none")] pub crs: Option, + /// A Zarr variable that follows the time slider: its slice is the step the slider shows, + /// read by the engine as the slider moves (opengeos/RustGIS#554). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub time_zarr: Option, pub style: RasterStyle, /// The pixels; `None` when the source couldn't be read. #[serde(skip)] @@ -66,6 +70,7 @@ impl RasterLayer { embedded: None, subdataset: None, crs: None, + time_zarr: None, style, data: Some(Arc::new(raster)), masked: MaskedStats::default(), @@ -81,14 +86,19 @@ impl RasterLayer { embedded: Some(Arc::new(bytes)), subdataset: None, crs: None, + time_zarr: None, style, data: Some(Arc::new(raster)), masked: MaskedStats::default(), } } - /// Reads the pixels again from the path or the embedded file (after a project opens). + /// Reads the pixels again from the path or the embedded file (after a project opens). A + /// layer that follows the time slider is left to the engine, which reads the step shown. pub fn reload(&mut self) -> Result<(), String> { + if self.time_zarr.is_some() { + return Ok(()); + } let r = if let Some(bytes) = &self.embedded { rustgis_data::raster::read_bytes(self.file_name.as_deref().unwrap_or("raster.tif"), bytes) } else if let Some(p) = &self.path { @@ -135,6 +145,71 @@ impl RasterLayer { } } +/// The most steps a Zarr layer following the time slider lists (as the slider itself does). +pub const MAX_ZARR_STEPS: usize = crate::time::MAX_STEPS; + +/// A Zarr variable that follows the time slider: the store (a folder or a web address), the +/// variable, the other dimensions' fixed steps, and its time dimension's steps as dates. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct ZarrTime { + /// The store's folder or web address. + pub store: String, + pub variable: String, + /// The other dimensions' steps (a pressure level), as `layer.addZarr`'s `index`. + #[serde(skip_serializing_if = "Vec::is_empty")] + pub index: Vec<(String, u64)>, + /// The time dimension's name. + pub dim: String, + /// The step of `dim` the first of `dates` is (a period chosen from a longer axis). + #[serde(skip_serializing_if = "is_zero")] + pub offset: u64, + /// The steps' dates, milliseconds since 1970 (UTC), in order. + pub dates: Vec, + /// The coordinate system given for a store that doesn't say. + #[serde(skip_serializing_if = "Option::is_none")] + pub crs: Option, + /// The step whose slice the layer holds (an index into `dates`); `None` when none is. + #[serde(skip)] + pub shown: Option, +} + +fn is_zero(v: &u64) -> bool { + *v == 0 +} + +impl ZarrTime { + /// The step to show for the slider's window `[from, to)`: the last one in it, `None` when + /// none falls in it. With the slider off, the first step. + pub fn step_for(&self, window: Option<(f64, f64)>) -> Option { + match window { + None => (!self.dates.is_empty()).then_some(0), + Some((from, to)) => self.dates.iter().rposition(|d| *d >= from && *d < to), + } + } + + /// The selection of step `i` as `zarr::Selection::parse` reads it: `t2m[time=12,level=3]`. + pub fn selection(&self, i: usize) -> String { + let mut parts = vec![format!("{}={}", self.dim, self.offset.saturating_add(i as u64))]; + parts.extend(self.index.iter().filter(|(d, _)| *d != self.dim).map(|(d, v)| format!("{d}={v}"))); + format!("{}[{}]", self.variable, parts.join(",")) + } + + /// Keeps a loaded layer within bounds: dates finite, in order, at most [`MAX_ZARR_STEPS`]; + /// names of sane length. + pub fn repair(&mut self) { + self.dates.retain(|d| d.is_finite()); + self.dates.truncate(MAX_ZARR_STEPS); + self.dates.sort_by(f64::total_cmp); + self.dates.dedup(); + self.index.truncate(32); + for t in [&mut self.store, &mut self.variable, &mut self.dim] { + *t = t.chars().take(4096).collect(); + } + self.shown = None; + } +} + pub(crate) mod b64 { use std::sync::Arc; diff --git a/crates/ui-egui/src/zarrui.rs b/crates/ui-egui/src/zarrui.rs index 8e5bb4f135..f10a0704c5 100644 --- a/crates/ui-egui/src/zarrui.rs +++ b/crates/ui-egui/src/zarrui.rs @@ -55,6 +55,8 @@ pub struct State { /// without metadata. forbidden: usize, pub error: Option, + /// Add the variable as a layer that follows the time slider (opengeos/RustGIS#554). + pub follow: bool, } impl State { @@ -339,6 +341,13 @@ pub fn picker(app: &mut RustGisApp, ui: &mut egui::Ui) { d["labels"].get(step as usize).and_then(Value::as_str).map(str::to_string) }) .collect(); + // A variable with a dimension besides the map's can follow the time slider (desktop). + let timed = vars[st.variable]["dims"].as_array().into_iter().flatten().any(|d| d["map"] != json!(true)); + if cfg!(not(target_arch = "wasm32")) && timed { + ui.checkbox(&mut st.follow, crate::tl!("Follow the time slider")).on_hover_text(crate::tl!( + "The layer shows the step the time slider is at, and turns the slider on over the variable's dates." + )); + } ui.add_space(4.0); ui.horizontal(|ui| { if ui.add_enabled(!busy, egui::Button::new(crate::tl!("Add to Map"))).clicked() { @@ -355,6 +364,23 @@ fn add(app: &mut RustGisApp, sel: zarr::Selection, labels: &[String]) { Some(t) => format!("{t} {}", rustgis_engine::cmd::zarr::layer_name("", &sel, labels)), None => rustgis_engine::cmd::zarr::layer_name(&st.root, &sel, labels), }; + // Following the time slider: the engine reads each step itself, a folder's or a web store's. + if st.follow && cfg!(not(target_arch = "wasm32")) { + let index: serde_json::Map = sel.index.iter().map(|(d, i)| (d.clone(), json!(i))).collect(); + let key = if st.web { "url" } else { "path" }; + let mut p = json!({key: st.root, "variable": sel.variable, "index": index, "time": true}); + if let Some(t) = &st.title { + p["name"] = json!(format!("{t} {}", sel.variable)); + } + if !st.crs.trim().is_empty() { + p["crs"] = json!(st.crs.trim()); + } + match app.run("layer.addZarr", p) { + Ok(_) => app.map.invalidate(), + Err(e) => app.ui.zarr.error = Some(e), + } + return; + } if !st.web { let index: serde_json::Map = sel.index.iter().map(|(d, i)| (d.clone(), json!(i))).collect(); let mut p = json!({"path": st.root, "variable": sel.variable, "index": index, "name": name}); diff --git a/docs/user-guide/data.md b/docs/user-guide/data.md index 5f47c4d263..5dc01fb707 100644 --- a/docs/user-guide/data.md +++ b/docs/user-guide/data.md @@ -424,6 +424,20 @@ Google Cloud's CMIP6 bucket does, ARCO-ERA5's doesn't (the desktop reads both). rustgis-cli run --cmd 'layer.addZarr={"url":"https://storage.googleapis.com/gcp-public-data-arco-era5/ar/1959-2022-full_37-1h-0p25deg-chunk-1.zarr-v2","variable":"2m_temperature","index":{"time":539100}}' ``` +**Follow the time slider** (desktop; `layer.addZarr` with `"time": true`) adds the variable as one +layer whose step is the time slider's. The slider turns on over the variable's dates when it is +off, and the layer shows the last of its steps in the slider's window, or nothing when none falls +in it. Moving or playing the slider reads that step's slice (only its chunks), keeping the last +eight read. A web store's next two steps are read ahead in the background. The stretch is fixed at +the first slice's range, so a colour means the same value at every step, and **Export** writes an +animation of it. An axis longer than the slider's 20,000 steps (hourly ERA5) needs `"start"` and +`"end"` to take a period. The project keeps such a layer by its store and selection, not as a slice, +and reads the slider's step again when it opens. + +```sh +rustgis-cli run --cmd 'layer.addZarr={"path":"air.zarr","variable":"t","time":true}' --cmd 'time.export={"path":"t.gif"}' +``` + A store in a folder is saved in the project by its folder and slice (`2m_temperature[time=539100]`) and read again when the project opens, as Add Data on the folder does (its first variable); a store by web address is kept in the project as the slice read. `?zarr=
` in a web app link diff --git a/docs/user-guide/workspace.md b/docs/user-guide/workspace.md index debcdcc384..214bc6279d 100644 --- a/docs/user-guide/workspace.md +++ b/docs/user-guide/workspace.md @@ -64,6 +64,8 @@ Tools for working across maps and views, and for setting up the app the way you cloud-optimised GeoTIFF a file per date with `layer.addUrl`, giving its `start` and `end`. For example NASA GIBS daily MODIS imagery: `https://gibs.earthdata.nasa.gov/wmts/epsg3857/best/MODIS_Terra_CorrectedReflectance_TrueColor/default/{date:YYYY-MM-DD}/GoogleMapsCompatible_Level9/{z}/{y}/{x}.jpg`. + - A Zarr variable added with **Follow the time slider** (Add Data › Zarr…) shows the step the + slider is at; see [Zarr stores](data.md#zarr-stores). - From scripts: `time.bind` (`"layer"`, `"field"`, `"start"`, `"end"`, `"unit"`, `"interval"`, `"show"`), `time.set` (the window: `"start"`, `"end"`, `"unit"`, `"interval"`, `"show"`, `"speed"`, `"loop"`, `"format"`…), `time.goTo` (`"date"`, or `"step"` from 0), `time.step` (`"by"`, negative goes From dda9ba511d033e0d8f8925a5c35b32206136b5ba Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Mon, 19 Oct 2026 23:44:04 -0300 Subject: [PATCH 2/8] Zarr: dates stay one per step; read-ahead fetches each slice once, on two threads at most (#601 review) - An axis out of order or with a date twice is refused by layer.addZarr's time, and repair clears dates it can't match to steps instead of sorting them onto the wrong ones. - Read-ahead skips slices kept or already being read, runs on at most two threads, and the step shown waits for a read ahead of it rather than fetching it again. - Tests: the Zarr store helper sits above the doc comment it had taken from zarr_stores_in_folders_and_handed_over, which gets its doc and cfg back; the new test is desktop-only like its helper. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/zarr.rs | 97 +++++++++++++++++++++++++++++++---- crates/engine/src/tests.rs | 17 ++++-- crates/map/src/raster.rs | 33 ++++++++++-- 3 files changed, 131 insertions(+), 16 deletions(-) diff --git a/crates/engine/src/cmd/zarr.rs b/crates/engine/src/cmd/zarr.rs index 8d9a2e3dad..2e274b53fb 100644 --- a/crates/engine/src/cmd/zarr.rs +++ b/crates/engine/src/cmd/zarr.rs @@ -284,11 +284,91 @@ fn cached_store(url: &str) -> Result, String> { Ok(st) } +/// The key a slice is kept by: its store, selection and coordinate system. +#[cfg(not(target_arch = "wasm32"))] +fn slice_key(zt: &ZarrTime, i: usize) -> String { + format!("{}\u{0}{}\u{0}{}", zt.store, zt.selection(i), zt.crs.as_deref().unwrap_or("")) +} + +#[cfg(not(target_arch = "wasm32"))] +fn is_kept(key: &str) -> bool { + slices().lock().is_ok_and(|c| c.iter().any(|(k, _)| k == key)) +} + +/// Slices being read ahead in the background, by key: each is read once, however often the +/// slider moves meanwhile. +#[cfg(not(target_arch = "wasm32"))] +fn reading_ahead() -> &'static std::sync::Mutex> { + static R: std::sync::OnceLock>> = std::sync::OnceLock::new(); + R.get_or_init(Default::default) +} + +/// The most threads reading ahead at once. +#[cfg(not(target_arch = "wasm32"))] +const MAX_READ_AHEAD: usize = 2; + +#[cfg(not(target_arch = "wasm32"))] +static READ_AHEAD_THREADS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + +/// Reads the two steps after `i` in the background, those neither kept nor already being read, +/// on at most [`MAX_READ_AHEAD`] threads: a thread more is skipped (the next step starts one). +#[cfg(not(target_arch = "wasm32"))] +fn read_ahead(zt: ZarrTime, i: usize) { + use std::sync::atomic::Ordering; + let keys: Vec<(usize, String)> = (i + 1..zt.dates.len()) + .take(2) + .map(|j| (j, slice_key(&zt, j))) + .filter(|(_, k)| !is_kept(k) && reading_ahead().lock().is_ok_and(|mut r| r.insert(k.clone()))) + .collect(); + if keys.is_empty() { + return; + } + let release = |keys: &[(usize, String)]| { + if let Ok(mut r) = reading_ahead().lock() { + for (_, k) in keys { + r.remove(k); + } + } + }; + if READ_AHEAD_THREADS.fetch_add(1, Ordering::SeqCst) >= MAX_READ_AHEAD { + READ_AHEAD_THREADS.fetch_sub(1, Ordering::SeqCst); + release(&keys); + return; + } + std::thread::spawn(move || { + for (n, (j, _)) in keys.iter().enumerate() { + let ok = read_step(&zt, *j).is_ok(); + release(&keys[n..=n]); + if !ok { + release(&keys[n + 1..]); + break; + } + } + READ_AHEAD_THREADS.fetch_sub(1, Ordering::SeqCst); + }); +} + +/// Waits (up to a minute) for a step being read ahead, so it isn't fetched twice. +#[cfg(not(target_arch = "wasm32"))] +fn wait_for_read_ahead(key: &str) { + let start = std::time::Instant::now(); + while start.elapsed() < std::time::Duration::from_secs(60) && reading_ahead().lock().is_ok_and(|r| r.contains(key)) { + std::thread::sleep(std::time::Duration::from_millis(20)); + } +} + +/// Step `i`, once a read ahead of it has finished, so it isn't fetched twice. +#[cfg(not(target_arch = "wasm32"))] +fn read_waiting(zt: &ZarrTime, i: usize) -> Result, String> { + wait_for_read_ahead(&slice_key(zt, i)); + read_step(zt, i) +} + /// Step `i` of a following layer's variable, from the kept slices or read now. #[cfg(not(target_arch = "wasm32"))] fn read_step(zt: &ZarrTime, i: usize) -> Result, String> { let sel = zt.selection(i); - let key = format!("{}\u{0}{sel}\u{0}{}", zt.store, zt.crs.as_deref().unwrap_or("")); + let key = slice_key(zt, i); if let Some((_, r)) = slices().lock().ok().and_then(|c| c.iter().find(|(k, _)| *k == key).cloned()) { return Ok(r); } @@ -336,7 +416,7 @@ pub(crate) fn follow_time(s: &mut Session) { rl.data = None; zt.shown = None; } - Some(i) => match read_step(zt, i) { + Some(i) => match read_waiting(zt, i) { Ok(r) => { rl.data = Some(r); zt.shown = Some(i); @@ -357,13 +437,7 @@ pub(crate) fn follow_time(s: &mut Session) { s.notify(e, true); } for (zt, i) in ahead { - std::thread::spawn(move || { - for j in (i + 1..zt.dates.len()).take(2) { - if read_step(&zt, j).is_err() { - break; - } - } - }); + read_ahead(zt, i); } } #[cfg(target_arch = "wasm32")] @@ -423,6 +497,11 @@ fn add_following(s: &mut Session, p: &Value) -> CmdResult { let (dim, dates) = zarr::time_axis(&store, &sel.variable, &chunks).ok_or_else(|| { format!("{} has no time dimension (a coordinate with CF units, such as \"days since 2001-01-01\")", sel.variable) })?; + // Each date is a step: an axis out of order or with a date twice (stores joined end to end) + // can't be followed step by step. + if !dates.iter().all(|d| d.is_finite()) || !dates.windows(2).all(|w| w[0] < w[1]) { + return Err(format!("{}'s time axis isn't in increasing order without repeats, so it can't follow the slider", sel.variable)); + } // The period asked for, else the whole axis. let date = |k: &str| -> Result, String> { match p.get(k).filter(|v| !v.is_null()) { diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 38afb832b6..7a54f15f74 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -6274,12 +6274,9 @@ fn lidar_point_clouds() { let _ = std::fs::remove_dir_all(dir); } -/// A Zarr store in a folder: its variables listed (with time labels), a slice added by command -/// and by Add Data, saved by folder and selection and read again when the project opens; a slice -/// the app read itself handed over by id. -#[cfg(not(target_arch = "wasm32"))] /// A Zarr store in a temporary folder: `t` over three monthly steps (days since 2001-01-01: 0, /// 31, 59) on a 3 × 4 grid, step `k`'s values `100·k + i`. +#[cfg(not(target_arch = "wasm32"))] fn zarr_store_over_time(tag: &str) -> (std::path::PathBuf, String) { let dir = std::env::temp_dir().join(format!("rustgis-zarr-{tag}-{}", std::process::id())); let store = dir.join("air.zarr"); @@ -6320,6 +6317,7 @@ fn zarr_store_over_time(tag: &str) -> (std::path::PathBuf, String) { /// A Zarr variable follows the time slider (#554): the slice drawn is the step the slider is at, /// the stretch is the same at every step, and the project keeps the layer by its store. +#[cfg(not(target_arch = "wasm32"))] #[test] fn a_zarr_variable_follows_the_time_slider() { let (dir, path) = zarr_store_over_time("follow"); @@ -6380,9 +6378,20 @@ fn a_zarr_variable_follows_the_time_slider() { ] { assert!(s.run("layer.addZarr", &bad).is_err(), "{bad}"); } + // An axis with a date twice, or going back: each date is a step, so it can't be followed. + let (dir2, twice) = zarr_store_over_time("twice"); + std::fs::write(std::path::Path::new(&twice).join("time/0"), [0i32, 31, 31].iter().flat_map(|x| x.to_le_bytes()).collect::>()) + .unwrap(); + let e = s.run("layer.addZarr", &json!({"path": twice, "variable": "t", "time": true})).unwrap_err(); + assert!(e.contains("increasing order"), "{e}"); + let _ = std::fs::remove_dir_all(dir2); let _ = std::fs::remove_dir_all(dir); } +/// A Zarr store in a folder: its variables listed (with time labels), a slice added by command +/// and by Add Data, saved by folder and selection and read again when the project opens; a slice +/// the app read itself handed over by id. +#[cfg(not(target_arch = "wasm32"))] #[test] fn zarr_stores_in_folders_and_handed_over() { let dir = std::env::temp_dir().join(format!("rustgis-zarr-{}", std::process::id())); diff --git a/crates/map/src/raster.rs b/crates/map/src/raster.rs index da523d8155..ff0c6cadd5 100644 --- a/crates/map/src/raster.rs +++ b/crates/map/src/raster.rs @@ -198,10 +198,12 @@ impl ZarrTime { /// Keeps a loaded layer within bounds: dates finite, in order, at most [`MAX_ZARR_STEPS`]; /// names of sane length. pub fn repair(&mut self) { - self.dates.retain(|d| d.is_finite()); self.dates.truncate(MAX_ZARR_STEPS); - self.dates.sort_by(f64::total_cmp); - self.dates.dedup(); + // Date `i` is step `offset + i`: dates out of order, repeated or not finite (a project + // edited by hand) can't be matched to steps, so none is followed rather than the wrong one. + if !self.dates.iter().all(|d| d.is_finite()) || !self.dates.windows(2).all(|w| w[0] < w[1]) { + self.dates.clear(); + } self.index.truncate(32); for t in [&mut self.store, &mut self.variable, &mut self.dim] { *t = t.chars().take(4096).collect(); @@ -937,6 +939,31 @@ mod tests { use super::*; + /// A following layer's dates are its steps from `offset` on, one each: repair keeps them as + /// they are when they are in order, and follows none rather than the wrong step otherwise. + #[test] + fn zarr_dates_keep_their_steps() { + let zt = |dates: Vec| { + let mut z = ZarrTime { + store: "s".into(), + variable: "t".into(), + index: Vec::new(), + dim: "time".into(), + offset: 3, + dates, + crs: None, + shown: Some(1), + }; + z.repair(); + z + }; + let ok = zt(vec![1.0, 2.0, 5.0]); + assert_eq!((ok.dates, ok.shown), (vec![1.0, 2.0, 5.0], None)); + for bad in [vec![2.0, 1.0], vec![1.0, 1.0, 2.0], vec![1.0, f64::NAN]] { + assert!(zt(bad.clone()).dates.is_empty(), "{bad:?}"); + } + } + fn dem() -> Raster { let gt = GeoTransform { origin_x: 0.0, origin_y: 4.0, pixel_width: 1.0, pixel_height: -1.0 }; let data: Vec = (0..16).map(|i| (i % 4 + i / 4) as f32).collect(); From 72a74ff70c9abddaa33303ed88159056cf363d43 Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Tue, 20 Oct 2026 00:04:53 -0300 Subject: [PATCH 3/8] Zarr: read-ahead gives its keys back even on a panic; dates before 1 CE read (#601 review) - A read-ahead thread releases its keys and its place among the threads in a drop guard, so a panic on a hostile store can't stall later steps or stop read-ahead; a step waits for one being read ahead 15 s at most, then reads it itself. - A CF date's leading minus is the year's sign, not a separator (date_parts), in model calendars. Co-Authored-By: Claude Opus 5.5 --- crates/data/src/raster/zarr.rs | 29 ++++++++++++++++++++++++----- crates/engine/src/cmd/zarr.rs | 21 +++++++++++++++++---- 2 files changed, 41 insertions(+), 9 deletions(-) diff --git a/crates/data/src/raster/zarr.rs b/crates/data/src/raster/zarr.rs index 09ac1c7adf..0c05e78adf 100644 --- a/crates/data/src/raster/zarr.rs +++ b/crates/data/src/raster/zarr.rs @@ -1320,8 +1320,7 @@ fn time_ms(c: &Array, v: f64) -> Option { "standard" | "gregorian" | "proleptic_gregorian" => epoch_seconds(since)? + v * secs, "noleap" | "365_day" | "all_leap" | "366_day" | "360_day" => { let day = fixed_calendar(&calendar, since, v * secs)?; - let mut p = day.splitn(3, '-').map(|x| x.parse::().ok()); - let (y, m, d) = (p.next()??, p.next()??, p.next()??); + let (Some(y), Some(m), Some(d)) = date_parts(&day) else { return None }; let last = days_from_civil(if m == 12 { y + 1 } else { y }, if m == 12 { 1 } else { m + 1 }, 1) - days_from_civil(y, m, 1); days_from_civil(y, m, d.min(last)) as f64 * 86_400.0 + (v * secs).rem_euclid(86_400.0) } @@ -1367,12 +1366,22 @@ fn label(c: &Array, v: f64) -> String { if units.is_empty() { n } else { format!("{n} {units}") } } +/// A date's year, month and day as its text has them: `2001-03-05`, or `-0001-01-01` for a year +/// before 1 CE (the sign is the year's, not a separator). +fn date_parts(s: &str) -> (Option, Option, Option) { + let (sign, rest) = match s.trim().strip_prefix('-') { + Some(r) => (-1, r), + None => (1, s.trim()), + }; + let mut p = rest.splitn(3, '-').map(|x| x.trim().parse::().ok()); + (p.next().flatten().map(|y| sign * y), p.next().flatten(), p.next().flatten()) +} + /// A date in a model calendar of fixed-length years (365, 366 or 360 days): `secs` after `since`. fn fixed_calendar(calendar: &str, since: &str, secs: f64) -> Option { - let mut d = since.split([' ', 'T']).next()?.splitn(3, '-').map(|p| p.trim().parse::().ok()); + let (y, m, d) = date_parts(since.split([' ', 'T']).next()?); // The parts of a hostile `units` string are kept to sane ranges, so nothing below overflows. - let (y0, m0, d0) = - (d.next()??.clamp(-MAX_YEAR, MAX_YEAR), d.next().flatten().unwrap_or(1).clamp(1, 12), d.next().flatten().unwrap_or(1).clamp(1, 31)); + let (y0, m0, d0) = (y?.clamp(-MAX_YEAR, MAX_YEAR), m.unwrap_or(1).clamp(1, 12), d.unwrap_or(1).clamp(1, 31)); let months: [i64; 12] = match calendar { "360_day" => [30; 12], "all_leap" | "366_day" => [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31], @@ -1579,6 +1588,16 @@ pub fn read_dir(dir: &std::path::Path, selection: &str, crs: Option<&str>) -> Re mod tests { use super::*; + /// A CF date's parts, a year before 1 CE included (its sign isn't a separator). + #[test] + fn dates_before_1_ce() { + assert_eq!(date_parts("2001-03-05"), (Some(2001), Some(3), Some(5))); + assert_eq!(date_parts("-0001-01-01"), (Some(-1), Some(1), Some(1))); + assert_eq!(date_parts("1850"), (Some(1850), None, None)); + assert_eq!(date_parts("x-1-1"), (None, Some(1), Some(1))); + assert!(fixed_calendar("noleap", "-0001-01-01", 0.0).is_some()); + } + fn lz4_block(raw: &[u8]) -> Vec { lz4_flex::block::compress(raw) } diff --git a/crates/engine/src/cmd/zarr.rs b/crates/engine/src/cmd/zarr.rs index 2e274b53fb..7ede2457d1 100644 --- a/crates/engine/src/cmd/zarr.rs +++ b/crates/engine/src/cmd/zarr.rs @@ -335,24 +335,37 @@ fn read_ahead(zt: ZarrTime, i: usize) { release(&keys); return; } + // Whatever ends the thread, a panic on a hostile store included, its keys and its place + // among the threads are given back. + struct Done(Vec); + impl Drop for Done { + fn drop(&mut self) { + if let Ok(mut r) = reading_ahead().lock() { + for k in &self.0 { + r.remove(k); + } + } + READ_AHEAD_THREADS.fetch_sub(1, Ordering::SeqCst); + } + } std::thread::spawn(move || { + let _done = Done(keys.iter().map(|(_, k)| k.clone()).collect()); for (n, (j, _)) in keys.iter().enumerate() { let ok = read_step(&zt, *j).is_ok(); release(&keys[n..=n]); if !ok { - release(&keys[n + 1..]); break; } } - READ_AHEAD_THREADS.fetch_sub(1, Ordering::SeqCst); }); } -/// Waits (up to a minute) for a step being read ahead, so it isn't fetched twice. +/// Waits (up to 15 s) for a step being read ahead, so it isn't fetched twice; after that it is +/// read here. #[cfg(not(target_arch = "wasm32"))] fn wait_for_read_ahead(key: &str) { let start = std::time::Instant::now(); - while start.elapsed() < std::time::Duration::from_secs(60) && reading_ahead().lock().is_ok_and(|r| r.contains(key)) { + while start.elapsed() < std::time::Duration::from_secs(15) && reading_ahead().lock().is_ok_and(|r| r.contains(key)) { std::thread::sleep(std::time::Duration::from_millis(20)); } } From 3c93ba69a5e68e34ecfc390cbe2168af54834424 Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Tue, 20 Oct 2026 01:02:35 -0300 Subject: [PATCH 4/8] Zarr: the layer shows the slider's step after an export and undo; the slider waits for a first read; model calendars keep their dates apart (#602 review) - time.export, and undo or redo, bring following Zarr layers back to the slider's step, not the last frame's. - layer.addZarr's time reads the first step before turning the slider on, so a store that can't be read leaves the map as it was. - A step that couldn't be read isn't read again on every call; it's tried again once the slider moves to it anew. - In model calendars the time of day in `since` counts, and a 360- or 366-day year is laid over its real year in proportion, so daily dates (30 February, 1 March) stay distinct and in order instead of being clamped onto one. Co-Authored-By: Claude Opus 5.5 --- crates/data/src/raster/zarr.rs | 75 +++++++++++++++++++++++++++++----- crates/engine/src/cmd/time.rs | 1 + crates/engine/src/cmd/zarr.rs | 13 ++++-- crates/engine/src/lib.rs | 2 + crates/engine/src/tests.rs | 10 +++++ 5 files changed, 87 insertions(+), 14 deletions(-) diff --git a/crates/data/src/raster/zarr.rs b/crates/data/src/raster/zarr.rs index 0c05e78adf..fe74f069f6 100644 --- a/crates/data/src/raster/zarr.rs +++ b/crates/data/src/raster/zarr.rs @@ -1277,9 +1277,9 @@ pub fn coordinate_keys(store: &Store, variable: &str) -> Vec { /// `variable`'s time dimension: the first of its dimensions other than the map's whose /// coordinate has CF time units (`days since 2001-01-01`), with its steps as milliseconds since -/// 1970 (UTC). A model calendar's dates are taken by their day, one past its month's end (360_day's -/// 30 February) on the month's last. `None` when no dimension has such a coordinate, or one of -/// its steps isn't a date. +/// 1970 (UTC). A `noleap` date is the same real date; a 360- or 366-day year is laid over its real +/// year in proportion (360_day's 30 February falls about 1 March), so its dates stay distinct and +/// in order. `None` when no dimension has such a coordinate, or one of its steps isn't a date. pub fn time_axis(store: &Store, variable: &str, chunks: &HashMap>) -> Option<(String, Vec)> { let v = store.array(variable)?; let (y, x) = map_dims(v); @@ -1319,10 +1319,32 @@ fn time_ms(c: &Array, v: f64) -> Option { let t = match calendar.as_str() { "standard" | "gregorian" | "proleptic_gregorian" => epoch_seconds(since)? + v * secs, "noleap" | "365_day" | "all_leap" | "366_day" | "360_day" => { - let day = fixed_calendar(&calendar, since, v * secs)?; + // The time of day `since` gives counts too (`days since 2000-01-01 12:00`). + let offset = v * secs + since.split_once([' ', 'T']).map_or(0.0, |(_, clock)| clock_seconds(clock)); + let day = fixed_calendar(&calendar, since, offset)?; let (Some(y), Some(m), Some(d)) = date_parts(&day) else { return None }; - let last = days_from_civil(if m == 12 { y + 1 } else { y }, if m == 12 { 1 } else { m + 1 }, 1) - days_from_civil(y, m, 1); - days_from_civil(y, m, d.min(last)) as f64 * 86_400.0 + (v * secs).rem_euclid(86_400.0) + let into_day = offset.rem_euclid(86_400.0); + match calendar.as_str() { + // Every day of a 365-day year is a real date. + "noleap" | "365_day" => days_from_civil(y, m, d) as f64 * 86_400.0 + into_day, + // 360 or 366 days: placed in the real year in proportion. + _ => { + let (model, before): (f64, i64) = if calendar == "360_day" { + (360.0, (m - 1) * 30) + } else { + ( + 366.0, + [0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335] + .get((m - 1).clamp(0, 11) as usize) + .copied() + .unwrap_or(0), + ) + }; + let start = days_from_civil(y, 1, 1); + let real = (days_from_civil(y + 1, 1, 1) - start) as f64; + (start as f64 + ((before + d - 1) as f64 + into_day / 86_400.0) / model * real) * 86_400.0 + } + } } _ => return None, }; @@ -1403,12 +1425,17 @@ fn fixed_calendar(calendar: &str, since: &str, secs: f64) -> Option { /// Seconds since 1970 of `YYYY-MM-DD[ T]HH:MM:SS`. fn epoch_seconds(s: &str) -> Option { let (date, time) = s.split_once([' ', 'T']).unwrap_or((s, "0:0:0")); - let mut d = date.splitn(3, '-').map(|p| p.trim().parse::().ok()); - let (y, m, day) = - (d.next()??.clamp(-MAX_YEAR, MAX_YEAR), d.next().flatten().unwrap_or(1).clamp(1, 12), d.next().flatten().unwrap_or(1).clamp(1, 31)); - let mut t = time.trim().trim_end_matches('Z').split(':').map(|p| p.trim().parse::().ok()); + let (y, m, day) = date_parts(date); + let (y, m, day) = (y?.clamp(-MAX_YEAR, MAX_YEAR), m.unwrap_or(1).clamp(1, 12), day.unwrap_or(1).clamp(1, 31)); + Some(days_from_civil(y, m, day) as f64 * 86_400.0 + clock_seconds(time)) +} + +/// Seconds into the day of `HH:MM:SS` (parts missing are 0; a trailing `Z` is dropped), kept +/// within a few days so a hostile string can't push a date far off. +fn clock_seconds(time: &str) -> f64 { + let mut t = time.trim().trim_end_matches('Z').split(':').map(|p| p.trim().parse::().ok().filter(|v| v.is_finite())); let (hh, mm, ss) = (t.next().flatten().unwrap_or(0.0), t.next().flatten().unwrap_or(0.0), t.next().flatten().unwrap_or(0.0)); - Some(days_from_civil(y, m, day) as f64 * 86_400.0 + hh * 3600.0 + mm * 60.0 + ss) + (hh * 3600.0 + mm * 60.0 + ss).clamp(-7.0 * 86_400.0, 7.0 * 86_400.0) } /// The years a `since` date may name: far past any data, small enough that day counts can't @@ -1598,6 +1625,32 @@ mod tests { assert!(fixed_calendar("noleap", "-0001-01-01", 0.0).is_some()); } + /// Model calendars: the time of day in `since` counts, and daily 360- and 366-day dates stay + /// distinct and in order (30 February and 1 March are two days). + #[test] + fn model_calendar_dates_stay_apart() { + let arr = serde_json::json!({"shape": [2], "chunks": [2], "dtype": " = (0..800).map(|d| at(cal, "days since 2001-01-01", f64::from(d))).collect(); + assert!(days.windows(2).all(|w| w[0] < w[1]), "{cal}: not in order"); + // A year's first day is the real year's. + assert_eq!(days[0], 978_307_200_000.0, "{cal}"); + } + } + fn lz4_block(raw: &[u8]) -> Vec { lz4_flex::block::compress(raw) } diff --git a/crates/engine/src/cmd/time.rs b/crates/engine/src/cmd/time.rs index 3e050cc3aa..9912e7e072 100644 --- a/crates/engine/src/cmd/time.rs +++ b/crates/engine/src/cmd/time.rs @@ -282,6 +282,7 @@ fn export(s: &mut Session, p: &Value) -> CmdResult { let made = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| frames(s, &steps, w, h, gif.then_some(speed)))); s.map_mut().time = Some(saved); s.map_mut().apply_time(); + super::zarr::follow_time(s); let bytes = made.map_err(|_| "exporting the time steps failed unexpectedly".to_string())??; rustgis_data::io::write_atomic(std::path::Path::new(&path), &bytes).map_err(|e| format!("{path}: {e}"))?; Ok(json!({"path": path, "frames": steps.len(), "bytes": bytes.len()})) diff --git a/crates/engine/src/cmd/zarr.rs b/crates/engine/src/cmd/zarr.rs index 7ede2457d1..8d98376f30 100644 --- a/crates/engine/src/cmd/zarr.rs +++ b/crates/engine/src/cmd/zarr.rs @@ -421,7 +421,8 @@ pub(crate) fn follow_time(s: &mut Session) { let Some(rl) = l.raster.as_mut() else { continue }; let Some(zt) = rl.time_zarr.as_mut() else { continue }; let want = zt.step_for(window); - if want == zt.shown && (want.is_none() || rl.data.is_some()) { + // The step shown, or one that couldn't be read (tried again once the slider moves). + if want == zt.shown { continue; } match want { @@ -439,7 +440,7 @@ pub(crate) fn follow_time(s: &mut Session) { } Err(e) => { rl.data = None; - zt.shown = None; + zt.shown = Some(i); errors.push(format!("{name}: {e}")); } }, @@ -547,6 +548,9 @@ fn add_following(s: &mut Session, p: &Value) -> CmdResult { shown: None, }; zt.repair(); + // The first step read before the slider is touched, so a store that can't be read leaves + // the map as it was. + let first = read_step(&zt, 0).map_err(|e| format!("{root}: {e}"))?; // The slider, on over the variable's dates when it is off. if s.map().time.is_none() { let dates: Vec = zt.dates.iter().map(|d| serde_json::json!(d)).collect(); @@ -555,7 +559,10 @@ fn add_following(s: &mut Session, p: &Value) -> CmdResult { let window = s.map().time.as_ref().map(rustgis_map::time::TimeSlider::window); let want = zt.step_for(window); // The first slice the layer shows sets its style; with no step in the window, the first step's. - let r = read_step(&zt, want.unwrap_or(0)).map_err(|e| format!("{root}: {e}"))?; + let r = match want { + Some(i) if i != 0 => read_step(&zt, i).map_err(|e| format!("{root}: {e}"))?, + _ => first, + }; let mut layer = RasterLayer::from_path((*r).clone(), root.clone()); if is_web(&root) { layer.path = None; diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 1ab03149e5..449340e0fb 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -1039,6 +1039,8 @@ impl Session { m.apply_time(); } } + // Zarr layers that follow the slider read the step it is back at. + cmd::zarr::follow_time(self); } fn open_layout_name(&self) -> Option { diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 7a54f15f74..b5b10b43a2 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -6362,6 +6362,8 @@ fn a_zarr_variable_follows_the_time_slider() { let zip = std::env::temp_dir().join(format!("rustgis-zarr-frames-{}.zip", std::process::id())); let r = s.run("time.export", &json!({"path": zip.display().to_string(), "width": 64, "height": 48})).unwrap(); assert_eq!(r["frames"], 4, "{r}"); + // After the export the slider is back at its step, and the layer shows it. + assert_eq!(first(&s), Some(208.0), "the layer shows the step the slider is back at"); let _ = std::fs::remove_file(zip); // A period: the steps from February on, the layer's first step the second of the axis. let id2 = s.run("layer.addZarr", &json!({"path": path, "variable": "t", "time": true, "start": "2001-01-20", "name": "late"})).unwrap() @@ -6384,6 +6386,14 @@ fn a_zarr_variable_follows_the_time_slider() { .unwrap(); let e = s.run("layer.addZarr", &json!({"path": twice, "variable": "t", "time": true})).unwrap_err(); assert!(e.contains("increasing order"), "{e}"); + // A store whose first slice can't be read leaves the slider as it was. + let (dir3, broken) = zarr_store_over_time("broken"); + std::fs::remove_file(std::path::Path::new(&broken).join("t/0.0.0")).unwrap(); + std::fs::write(std::path::Path::new(&broken).join("t/0.0.0"), b"short").unwrap(); + let mut fresh = Session::new(Project::default()); + assert!(fresh.run("layer.addZarr", &json!({"path": broken, "variable": "t", "time": true})).is_err()); + assert!(fresh.map().time.is_none(), "a store that can't be read leaves the slider as it was"); + let _ = std::fs::remove_dir_all(dir3); let _ = std::fs::remove_dir_all(dir2); let _ = std::fs::remove_dir_all(dir); } From b603d101a97bdcd93d38506de62bc3495f8069fe Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Tue, 20 Oct 2026 01:43:45 -0300 Subject: [PATCH 5/8] Zarr: a folder with no variable named follows the slider with its first one; read-ahead never panics for want of a thread (#601 review) - add_following picks the variable before reading a folder's coordinates, so leaving `variable` out (its default, the store's first) no longer fails with "no time dimension". Tested. - Read-ahead starts its thread with thread::Builder, and gives back its keys and place when no thread can be had. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/zarr.rs | 12 ++++++++++-- crates/engine/src/tests.rs | 4 ++++ 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/zarr.rs b/crates/engine/src/cmd/zarr.rs index 8d98376f30..a0d9614f79 100644 --- a/crates/engine/src/cmd/zarr.rs +++ b/crates/engine/src/cmd/zarr.rs @@ -348,7 +348,8 @@ fn read_ahead(zt: ZarrTime, i: usize) { READ_AHEAD_THREADS.fetch_sub(1, Ordering::SeqCst); } } - std::thread::spawn(move || { + let ids: Vec = keys.iter().map(|(_, k)| k.clone()).collect(); + let spawned = std::thread::Builder::new().name("zarr-read-ahead".into()).spawn(move || { let _done = Done(keys.iter().map(|(_, k)| k.clone()).collect()); for (n, (j, _)) in keys.iter().enumerate() { let ok = read_step(&zt, *j).is_ok(); @@ -358,6 +359,10 @@ fn read_ahead(zt: ZarrTime, i: usize) { } } }); + // No thread to be had: nothing is read ahead, and its keys and place are given back. + if spawned.is_err() { + drop(Done(ids)); + } } /// Waits (up to 15 s) for a step being read ahead, so it isn't fetched twice; after that it is @@ -421,7 +426,8 @@ pub(crate) fn follow_time(s: &mut Session) { let Some(rl) = l.raster.as_mut() else { continue }; let Some(zt) = rl.time_zarr.as_mut() else { continue }; let want = zt.step_for(window); - // The step shown, or one that couldn't be read (tried again once the slider moves). + // The step shown, or one that couldn't be read: that one isn't read again (nor its + // error said again) until the slider has moved to another step and back. if want == zt.shown { continue; } @@ -481,6 +487,8 @@ fn add_following(s: &mut Session, p: &Value) -> CmdResult { let (root, store, chunks) = match src { Source::Dir(d) => { let store = zarr::read_metadata(Path::new(&d)).map_err(|e| format!("{d}: {e}"))?; + // The variable first (the store's first when none is given), so its coordinates are read. + pick_variable(&store, &mut sel)?; let mut chunks = HashMap::new(); let mut total = 0u64; for k in zarr::coordinate_keys(&store, &sel.variable) { diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index b5b10b43a2..6dce5d84cd 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -6386,6 +6386,10 @@ fn a_zarr_variable_follows_the_time_slider() { .unwrap(); let e = s.run("layer.addZarr", &json!({"path": twice, "variable": "t", "time": true})).unwrap_err(); assert!(e.contains("increasing order"), "{e}"); + // With no variable named, a folder's first one follows the slider. + let mut plain = Session::new(Project::default()); + let r = plain.run("layer.addZarr", &json!({"path": path, "time": true})).unwrap(); + assert!(plain.map().layer(r["layer"].as_u64().unwrap() as u32).unwrap().raster.as_ref().unwrap().time_zarr.is_some()); // A store whose first slice can't be read leaves the slider as it was. let (dir3, broken) = zarr_store_over_time("broken"); std::fs::remove_file(std::path::Path::new(&broken).join("t/0.0.0")).unwrap(); From f58e5b667c318c5837aa80f6e715de96c0679528 Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Tue, 20 Oct 2026 01:53:15 -0300 Subject: [PATCH 6/8] Zarr: a folder store rewritten on disk is read again, not served from the slice cache (#603 review) Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/zarr.rs | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/zarr.rs b/crates/engine/src/cmd/zarr.rs index a0d9614f79..03ff2db406 100644 --- a/crates/engine/src/cmd/zarr.rs +++ b/crates/engine/src/cmd/zarr.rs @@ -287,7 +287,18 @@ fn cached_store(url: &str) -> Result, String> { /// The key a slice is kept by: its store, selection and coordinate system. #[cfg(not(target_arch = "wasm32"))] fn slice_key(zt: &ZarrTime, i: usize) -> String { - format!("{}\u{0}{}\u{0}{}", zt.store, zt.selection(i), zt.crs.as_deref().unwrap_or("")) + // A folder store rewritten on disk (a model run adding steps) is read again: its metadata's + // time of change is part of the key. + let changed = if is_web(&zt.store) { + String::new() + } else { + [".zmetadata", "zarr.json", ".zgroup"] + .iter() + .find_map(|f| std::fs::metadata(Path::new(&zt.store).join(f)).and_then(|m| m.modified()).ok()) + .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok()) + .map_or_else(String::new, |d| d.as_millis().to_string()) + }; + format!("{}\u{0}{}\u{0}{}\u{0}{changed}", zt.store, zt.selection(i), zt.crs.as_deref().unwrap_or("")) } #[cfg(not(target_arch = "wasm32"))] From 457735ebe2f419de8e17998d4dc2760367e16a70 Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Tue, 20 Oct 2026 12:52:59 -0300 Subject: [PATCH 7/8] Zarr: one slice key per read; a time coordinate of the dimension's length; follow off for a variable without time Co-Authored-By: Claude Opus 5.5 --- crates/data/src/raster/zarr.rs | 4 +++- crates/engine/src/cmd/zarr.rs | 20 +++++++++++--------- crates/ui-egui/src/zarrui.rs | 4 ++++ 3 files changed, 18 insertions(+), 10 deletions(-) diff --git a/crates/data/src/raster/zarr.rs b/crates/data/src/raster/zarr.rs index fe74f069f6..803ea638cd 100644 --- a/crates/data/src/raster/zarr.rs +++ b/crates/data/src/raster/zarr.rs @@ -1287,7 +1287,9 @@ pub fn time_axis(store: &Store, variable: &str, chunks: &HashMap if d == y || d == x { continue; } - let Some(c) = store.coordinate(v, name) else { continue }; + // A coordinate of the dimension's own length (one found at the root, of another group, + // may not be), so date `i` is step `i`. + let Some(c) = store.coordinate(v, name).filter(|c| c.shape.first() == v.shape.get(d)) else { continue }; if !attr_str(c, "units").is_some_and(|u| u.contains(" since ")) { continue; } diff --git a/crates/engine/src/cmd/zarr.rs b/crates/engine/src/cmd/zarr.rs index 03ff2db406..1ab9d04ff0 100644 --- a/crates/engine/src/cmd/zarr.rs +++ b/crates/engine/src/cmd/zarr.rs @@ -362,8 +362,8 @@ fn read_ahead(zt: ZarrTime, i: usize) { let ids: Vec = keys.iter().map(|(_, k)| k.clone()).collect(); let spawned = std::thread::Builder::new().name("zarr-read-ahead".into()).spawn(move || { let _done = Done(keys.iter().map(|(_, k)| k.clone()).collect()); - for (n, (j, _)) in keys.iter().enumerate() { - let ok = read_step(&zt, *j).is_ok(); + for (n, (j, k)) in keys.iter().enumerate() { + let ok = read_step(&zt, *j, k.clone()).is_ok(); release(&keys[n..=n]); if !ok { break; @@ -389,15 +389,17 @@ fn wait_for_read_ahead(key: &str) { /// Step `i`, once a read ahead of it has finished, so it isn't fetched twice. #[cfg(not(target_arch = "wasm32"))] fn read_waiting(zt: &ZarrTime, i: usize) -> Result, String> { - wait_for_read_ahead(&slice_key(zt, i)); - read_step(zt, i) + // One key for the wait and the read: a store rewritten between them is read once. + let key = slice_key(zt, i); + wait_for_read_ahead(&key); + read_step(zt, i, key) } -/// Step `i` of a following layer's variable, from the kept slices or read now. +/// Step `i` of a following layer's variable, kept as `key` (its [`slice_key`]), from the kept +/// slices or read now. #[cfg(not(target_arch = "wasm32"))] -fn read_step(zt: &ZarrTime, i: usize) -> Result, String> { +fn read_step(zt: &ZarrTime, i: usize, key: String) -> Result, String> { let sel = zt.selection(i); - let key = slice_key(zt, i); if let Some((_, r)) = slices().lock().ok().and_then(|c| c.iter().find(|(k, _)| *k == key).cloned()) { return Ok(r); } @@ -569,7 +571,7 @@ fn add_following(s: &mut Session, p: &Value) -> CmdResult { zt.repair(); // The first step read before the slider is touched, so a store that can't be read leaves // the map as it was. - let first = read_step(&zt, 0).map_err(|e| format!("{root}: {e}"))?; + let first = read_step(&zt, 0, slice_key(&zt, 0)).map_err(|e| format!("{root}: {e}"))?; // The slider, on over the variable's dates when it is off. if s.map().time.is_none() { let dates: Vec = zt.dates.iter().map(|d| serde_json::json!(d)).collect(); @@ -579,7 +581,7 @@ fn add_following(s: &mut Session, p: &Value) -> CmdResult { let want = zt.step_for(window); // The first slice the layer shows sets its style; with no step in the window, the first step's. let r = match want { - Some(i) if i != 0 => read_step(&zt, i).map_err(|e| format!("{root}: {e}"))?, + Some(i) if i != 0 => read_step(&zt, i, slice_key(&zt, i)).map_err(|e| format!("{root}: {e}"))?, _ => first, }; let mut layer = RasterLayer::from_path((*r).clone(), root.clone()); diff --git a/crates/ui-egui/src/zarrui.rs b/crates/ui-egui/src/zarrui.rs index f10a0704c5..d3121fd4ce 100644 --- a/crates/ui-egui/src/zarrui.rs +++ b/crates/ui-egui/src/zarrui.rs @@ -343,6 +343,10 @@ pub fn picker(app: &mut RustGisApp, ui: &mut egui::Ui) { .collect(); // A variable with a dimension besides the map's can follow the time slider (desktop). let timed = vars[st.variable]["dims"].as_array().into_iter().flatten().any(|d| d["map"] != json!(true)); + // A variable with only the map's dimensions can't follow: the box is gone, so is its choice. + if !timed { + st.follow = false; + } if cfg!(not(target_arch = "wasm32")) && timed { ui.checkbox(&mut st.follow, crate::tl!("Follow the time slider")).on_hover_text(crate::tl!( "The layer shows the step the time slider is at, and turns the slider on over the variable's dates." From 54d5e66ff346b7ab9a978d7b714844a8a7a7aafd Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Tue, 20 Oct 2026 13:38:38 -0300 Subject: [PATCH 8/8] Docs: a following Zarr layer is kept by reference for a folder or a web store; the slice rule is for a single step Co-Authored-By: Claude Opus 5.5 --- docs/user-guide/data.md | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/docs/user-guide/data.md b/docs/user-guide/data.md index 97ddc7ed02..58844fa92d 100644 --- a/docs/user-guide/data.md +++ b/docs/user-guide/data.md @@ -481,16 +481,17 @@ in it. Moving or playing the slider reads that step's slice (only its chunks), k eight read. A web store's next two steps are read ahead in the background. The stretch is fixed at the first slice's range, so a colour means the same value at every step, and **Export** writes an animation of it. An axis longer than the slider's 20,000 steps (hourly ERA5) needs `"start"` and -`"end"` to take a period. The project keeps such a layer by its store and selection, not as a slice, -and reads the slider's step again when it opens. +`"end"` to take a period. The project keeps such a layer by its store (a folder or a web address) +and selection, not as a slice, and reads the slider's step again when it opens. ```sh rustgis-cli run --cmd 'layer.addZarr={"path":"air.zarr","variable":"t","time":true}' --cmd 'time.export={"path":"t.gif"}' ``` -A store in a folder is saved in the project by its folder and slice (`2m_temperature[time=539100]`) -and read again when the project opens, as Add Data on the folder does (its first variable); a -store by web address is kept in the project as the slice read. `?zarr=
` in a web app link +A single step (a layer that doesn't follow the slider) from a store in a folder is saved in the +project by its folder and slice (`2m_temperature[time=539100]`) and read again when the project +opens, as Add Data on the folder does (its first variable); a single step from a store by web +address is kept in the project as the slice read. `?zarr=
` in a web app link opens the dialog on a store. ## Project items