From 74e447260a8103bd6803ed4addeecc4d49070a48 Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Sun, 22 Nov 2026 15:03:14 -0300 Subject: [PATCH 1/4] feat(symbology): say classes come from the view; close manual classes at GeoParquet statistics (#2497) On a layer read in place, layer.symbology now gives one notice when Unique Values, a Graduated method or Proportional Symbols are worked out from the features of the view read so far. Manual classes on a GeoParquet read in place close at the field's range from the column statistics (FeatureSource::field_range), else stay open as in #2506. Co-Authored-By: Claude Opus 5.5 --- crates/data/src/source/mod.rs | 10 ++++ crates/data/src/source/parquet.rs | 47 +++++++++++++++++++ crates/data/src/source/tests.rs | 26 +++++++++++ crates/engine/src/cmd/layer.rs | 77 ++++++++++++++++++++++--------- crates/engine/src/tests.rs | 60 ++++++++++++++++++++++++ crates/map/src/source.rs | 6 +++ crates/map/src/symbology.rs | 47 +++++++++++++++++++ docs/user-guide/cartography.md | 9 ++-- 8 files changed, 258 insertions(+), 24 deletions(-) diff --git a/crates/data/src/source/mod.rs b/crates/data/src/source/mod.rs index 3a4bc5026e..eaaa3f54dc 100644 --- a/crates/data/src/source/mod.rs +++ b/crates/data/src/source/mod.rs @@ -425,6 +425,12 @@ pub trait FeatureSource: Send + Sync { fn skipped_at_open(&self) -> usize { 0 } + /// The smallest and largest value of a numeric field across the whole source, when the source + /// states them without being read (GeoParquet column statistics); `None` when any part of it + /// doesn't, or the field has no value. + fn field_range(&self, _field: &str) -> Option<(f64, f64)> { + None + } /// Reads the features a request asks for. A source read by its web address fails with /// [`remote::NEED`] until the bytes the read needs are fetched: run it with /// [`remote::drive`] (see [`FeatureSource::remote`]). @@ -684,6 +690,10 @@ impl FeatureSource for Fetching { self.0.skipped_at_open() } + fn field_range(&self, field: &str) -> Option<(f64, f64)> { + self.0.field_range(field) + } + fn read(&self, req: &Request) -> Result { read_blocking(&self.0, req) } diff --git a/crates/data/src/source/parquet.rs b/crates/data/src/source/parquet.rs index 0f23118234..2cac2f6db6 100644 --- a/crates/data/src/source/parquet.rs +++ b/crates/data/src/source/parquet.rs @@ -486,6 +486,36 @@ impl FeatureSource for ParquetSource { &self.info } + /// From every row group's statistics of the field's column, which the footer holds: no byte of + /// the data is read. A row group without them (and not all nulls) leaves the range unknown. + fn field_range(&self, field: &str) -> Option<(f64, f64)> { + let i = self.info.fields.iter().position(|f| f.name == field && f.ty.is_numeric())?; + let col = *self.field_cols.get(i)?; + let md = self.reader.metadata(); + let desc = md.file_metadata().schema_descr().column(col); + // Unsigned integers are ordered as unsigned in the statistics, not as the values are read. + if matches!(desc.logical_type_ref(), Some(LogicalType::Integer(t)) if !t.is_signed) + || matches!( + desc.converted_type(), + ConvertedType::UINT_8 | ConvertedType::UINT_16 | ConvertedType::UINT_32 | ConvertedType::UINT_64 + ) + { + return None; + } + let scale = decimal_scale(&desc).map_or(1.0, |s| 10f64.powi(-s)); + let (lo, hi) = (0..md.num_row_groups()).try_fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), g| { + let rg = md.row_group(g); + let s = rg.columns().get(col)?.statistics()?; + match (number_stat(s, false), number_stat(s, true)) { + (Some(a), Some(b)) => Some((lo.min(a * scale), hi.max(b * scale))), + // A row group of nulls only has no bounds. + _ if s.null_count_opt() == Some(u64::try_from(rg.num_rows()).ok()?) => Some((lo, hi)), + _ => None, + } + })?; + (lo.is_finite() && hi.is_finite() && lo <= hi).then_some((lo, hi)) + } + /// Its own system, in which it gives its features as the file holds them. fn coord_crs(&self) -> crate::raster::Crs { self.reproject.crs() @@ -1064,6 +1094,23 @@ fn stat(s: Option<&Statistics>, max: bool) -> Option { } } +/// A numeric column's smallest or largest value in a row group's statistics. +fn number_stat(s: &Statistics, max: bool) -> Option { + match s { + Statistics::Int32(v) => (if max { v.max_opt() } else { v.min_opt() }).map(|x| f64::from(*x)), + // Past 2^53, the next double out, so the bound still holds every value. + Statistics::Int64(v) => (if max { v.max_opt() } else { v.min_opt() }).map(|&x| { + let y = x as f64; + match (y as i128).cmp(&i128::from(x)) { + std::cmp::Ordering::Less if max => y.next_up(), + std::cmp::Ordering::Greater if !max => y.next_down(), + _ => y, + } + }), + _ => stat(Some(s), max), + } +} + /// A row group's bounding box from its covering statistics. fn group_extent(md: &ParquetMetaData, g: usize, c: [usize; 4]) -> Option { let rg = md.row_groups().get(g)?; diff --git a/crates/data/src/source/tests.rs b/crates/data/src/source/tests.rs index 1f7baf1ee1..f6ba368605 100644 --- a/crates/data/src/source/tests.rs +++ b/crates/data/src/source/tests.rs @@ -4881,3 +4881,29 @@ fn write_projected_parquet_fixture(ds: &Dataset, path: &Path, rows: usize, dicti writer.write(&batch).unwrap(); writer.close().unwrap(); } + +/// A GeoParquet field's range comes from its column statistics; text, missing and all-null +/// fields have none (#2497). +#[test] +fn geoparquet_field_range_comes_from_column_statistics() { + let fields = vec![ + Field::new("height", FieldType::Double), + Field::new("floors", FieldType::Integer), + Field::new("name", FieldType::Text), + Field::new("empty", FieldType::Double), + ]; + let mut ds = Dataset::new("b", crate::GeometryType::Point, fields); + for (i, h) in [3.5, -2.0, 41.25].into_iter().enumerate() { + let floors = if i == 1 { Value::Null } else { Value::Int(i as i64 * 7 - 3) }; + ds.push(Some(Geometry::Point(Coord::new(i as f64, 0.0))), vec![Value::Float(h), floors, Value::Text("x".into()), Value::Null]); + } + let source = parquet::ParquetSource::open_bytes(parquet::write(&ds).unwrap(), "b").unwrap(); + assert_eq!(source.field_range("height"), Some((-2.0, 41.25))); + assert_eq!(source.field_range("floors"), Some((-3.0, 11.0))); + for none in ["name", "empty", "nope"] { + assert_eq!(source.field_range(none), None, "{none}"); + } + // A wrapper says the same. + #[cfg(not(target_arch = "wasm32"))] + assert_eq!(Fetching(Arc::new(source)).field_range("height"), Some((-2.0, 41.25))); +} diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 4b3c453743..f03ed1d634 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -150,7 +150,7 @@ pub fn commands() -> Vec { .when(need_layer), C::new("layer.symbology", "Symbology", "Style › Drawing", symbology).roles(&[]).effects(crate::policy::Effects::NONE) .when(need_feature_layer) - .params(r#"{"layer"?, "type": "single"|"unique"|"graduated"|"proportional", "field"?, "expression"?: expression|null (unique: class by this expression's values instead of a field; blank or null: by a field; with neither key, Unique Values keep the layer's expression), "classes"?: 1..12, "method"?: "naturalBreaks"|"equalInterval"|"quantile"|"geometricInterval"|"standardDeviation"|"arithmeticProgression"|"headTailBreaks"|"manual", "breaks"?: [numbers] (manual: the classes' upper bounds, closed by the field's largest value; on a layer read in place, the first class takes every value up to its bound and one more class every value past the last), "ramp"?: string}"#), + .params(r#"{"layer"?, "type": "single"|"unique"|"graduated"|"proportional", "field"?, "expression"?: expression|null (unique: class by this expression's values instead of a field; blank or null: by a field; with neither key, Unique Values keep the layer's expression), "classes"?: 1..12, "method"?: "naturalBreaks"|"equalInterval"|"quantile"|"geometricInterval"|"standardDeviation"|"arithmeticProgression"|"headTailBreaks"|"manual", "breaks"?: [numbers] (manual: the classes' upper bounds, closed by the field's largest value; on a layer read in place, closed by the file's smallest and largest values when it states them (GeoParquet column statistics), else the first class takes every value up to its bound and one more class every value past the last; other methods and unique values on a layer read in place class the features of the view read so far, and say so), "ramp"?: string}"#), C::new("layer.ramp", "Color Scheme", "Style › Drawing", |s, p| { let r = s.ramp(s_req(p, "ramp")?)?; let mut dropped = None; @@ -7499,35 +7499,45 @@ fn symbology(s: &mut Session, p: &Value) -> CmdResult { }; // Features past the first values an expression's classes keep. let mut rest = rustgis_data::value::PastClasses::default(); + // On a layer read in place, classes worked out from the features of the view read so far + // (#2497), and what becomes of the values elsewhere in the layer. + let mut from_view: Option<&str> = None; let mut r = match kind.as_str() { "single" | "singlesymbol" => Renderer::Single(base), - "unique" | "uniquevalues" => match &expression { - Some(e) => { - let (mut r, n) = Renderer::unique_by_up_to(&l.dataset, &rows()?, e, ramp.unwrap_or(Ramp::Harbour), base, keep)?; - rest = n; - // (Clearing the expression goes back to the field it had.) - if let (Renderer::Unique { field, .. }, Some(last)) = (&mut r, last_field) { - *field = last.to_string(); + "unique" | "uniquevalues" => { + from_view = Some("values not among them are drawn as "); + match &expression { + Some(e) => { + let (mut r, n) = Renderer::unique_by_up_to(&l.dataset, &rows()?, e, ramp.unwrap_or(Ramp::Harbour), base, keep)?; + rest = n; + // (Clearing the expression goes back to the field it had.) + if let (Renderer::Unique { field, .. }, Some(last)) = (&mut r, last_field) { + *field = last.to_string(); + } + r + } + None => { + let (r, n) = Renderer::unique_counted(&l.dataset, &rows()?, &field(false)?, ramp.unwrap_or(Ramp::Harbour), base)?; + rest = n; + r } - r - } - None => { - let (r, n) = Renderer::unique_counted(&l.dataset, &rows()?, &field(false)?, ramp.unwrap_or(Ramp::Harbour), base)?; - rest = n; - r } - }, + } "graduated" | "graduatedcolors" => { let (field, ramp) = (field(true)?, ramp.unwrap_or(Ramp::Ember)); + // The field's range across the whole layer, when its file states it (GeoParquet + // column statistics): it closes manual classes on a layer read in place. + let range = l.source.as_ref().and_then(|src| src.field_range(&field)); // Manual with no bounds keeps the layer's current ones on the same field, so switching // to it changes nothing. let kept = match &l.renderer { Renderer::Graduated { field: f, breaks, .. } if *f == field => { let mut b = breaks.clone(); // On a layer read in place, the last bound closed the classes at the largest - // value read: the open class takes its place, so the classes keep their number. + // value read, or at the file's: the open class takes its place, so the classes + // keep their number. A bound past the file's largest value is one of its own. let open = rustgis_map::symbology::OPEN_ABOVE; - if l.is_streamed() && b.last().is_some_and(|v| *v < open) { + if l.is_streamed() && b.last().is_some_and(|v| *v < open && range.is_none_or(|(_, hi)| *v <= hi)) { b.pop(); if b.is_empty() { b.push(open); @@ -7541,11 +7551,14 @@ fn symbology(s: &mut Session, p: &Value) -> CmdResult { // A layer read in place holds only the features of the last view read, so its // range is unknown: the classes take every value up to the first bound and past // the last. - (ClassMethod::Manual, Some(b)) if l.is_streamed() => Renderer::graduated_manual_open(&l.dataset, &field, &b, ramp, base)?, + (ClassMethod::Manual, Some(b)) if l.is_streamed() => match range { + Some(range) => Renderer::graduated_manual_within(&l.dataset, &field, &b, range, ramp, base)?, + None => Renderer::graduated_manual_open(&l.dataset, &field, &b, ramp, base)?, + }, (ClassMethod::Manual, Some(b)) => Renderer::graduated_manual(&l.dataset, &rows()?, &field, &b, ramp, base)?, // Manual with nothing to keep starts from the view's classes, open at both ends. (ClassMethod::Manual, None) if l.is_streamed() => { - let r = Renderer::graduated(&l.dataset, &rows()?, &field, classes, method, ramp, base).map_err(|e| { + let r = Renderer::graduated(&l.dataset, &rows()?, &field, classes, method, ramp.clone(), base).map_err(|e| { // The file has values; the view read so far holds none. if e == format!("'{field}' has no numeric values") { format!("'{field}' has no values in the view read so far: give manual breaks, or read a view where it has some") @@ -7553,15 +7566,27 @@ fn symbology(s: &mut Session, p: &Value) -> CmdResult { e } })?; - r.opened().unwrap_or(r) + from_view = Some("the first and last classes take every value below and above them"); + let r = r.opened().unwrap_or(r); + match (&r, range) { + (Renderer::Graduated { breaks, .. }, Some(range)) => { + from_view = Some("the file's smallest and largest values close the first and last classes"); + Renderer::graduated_manual_within(&l.dataset, &field, breaks, range, ramp, base)? + } + _ => r, + } + } + _ => { + from_view = Some("values below or above them are drawn in the first or last class"); + Renderer::graduated(&l.dataset, &rows()?, &field, classes, method, ramp, base)? } - _ => Renderer::graduated(&l.dataset, &rows()?, &field, classes, method, ramp, base)?, } } "proportional" | "proportionalsymbols" => { if g != GeometryType::Point { return Err("Proportional Symbols needs a point layer".into()); } + from_view = Some("the symbol sizes are scaled to their values"); Renderer::proportional(&l.dataset, &rows()?, &field(true)?, base)? } other => return Err(format!("unknown symbology '{other}'")), @@ -7590,6 +7615,7 @@ fn symbology(s: &mut Session, p: &Value) -> CmdResult { _ => String::new(), }; let order = if rest.by_number { "by number" } else { "in text order" }; + let from_view = from_view.filter(|_| l.is_streamed()).map(|then| (l.dataset.kept_features(&l.visible_rows()).count(), then)); let mut dropped = None; let out = with(s, p, |l| { l.renderer = r; @@ -7606,6 +7632,15 @@ fn symbology(s: &mut Session, p: &Value) -> CmdResult { false, ); } + if let Some((n, then)) = from_view { + s.notify( + format!( + "{name}: its symbology is worked out from the {n} feature{} of the view read so far, not the whole layer read in place; {then}", + if n == 1 { "" } else { "s" } + ), + false, + ); + } if by_scale { s.notify( format!( diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index abfdd7b115..339cac0860 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -46177,6 +46177,66 @@ fn manual_breaks_on_a_layer_read_in_place_are_open_at_both_ends() { assert_eq!(opened.renderer, saved); } +/// On a GeoParquet read in place, manual classes close at the field's range from the column +/// statistics, and classes worked out from the view say so (#2497). +#[test] +fn classes_on_a_geoparquet_read_in_place_close_at_its_statistics_and_say_what_comes_from_the_view() { + use rustgis_data::{Coord, Dataset, Field, FieldType, Geometry, GeometryType, Value as V}; + use rustgis_map::Renderer; + let mut ds = Dataset::new("buildings", GeometryType::Point, vec![Field::new("height", FieldType::Double)]); + for h in 1..=40 { + ds.push(Some(Geometry::Point(Coord::new(f64::from(h), 0.0))), vec![V::Float(f64::from(h))]); + } + let dir = std::env::temp_dir().join(format!("rustgis-classes-in-view-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("buildings.parquet"); + rustgis_data::io::write_path(&ds, &path).unwrap(); + let mut s = Session::new(Project::default()); + let id = + s.run("layer.addData", &json!({"path": path.display().to_string(), "stream": true})).unwrap()["layer"].as_u64().unwrap() as u32; + assert!(s.map().layer(id).unwrap().is_streamed()); + let classes = |s: &Session| match &s.map().layer(id).unwrap().renderer { + Renderer::Graduated { breaks, min, .. } => (breaks.clone(), *min), + r => panic!("{r:?}"), + }; + // What a run said about the view. + let run = |s: &mut Session, mut p: Value| { + (p["layer"], p["field"]) = (json!(id), json!("height")); + let mark = s.notice_mark(); + s.run("layer.symbology", &p).unwrap(); + s.notices_since(mark).iter().filter(|n| n.text.contains("of the view read so far")).map(|n| n.text.clone()).collect::>() + }; + // Manual breaks close at the file's smallest and largest values, before any view is read. + assert!(run(&mut s, json!({"type": "graduated", "breaks": [4, 7, 10, 15, 25]})).is_empty()); + assert_eq!(classes(&s), (vec![4.0, 7.0, 10.0, 15.0, 25.0, 40.0], 1.0)); + // Kept, they stay as they are; a bound past the largest value is one of its own. + run(&mut s, json!({"type": "graduated", "method": "manual"})); + assert_eq!(classes(&s).0, [4.0, 7.0, 10.0, 15.0, 25.0, 40.0]); + run(&mut s, json!({"type": "graduated", "breaks": [5, 50]})); + run(&mut s, json!({"type": "graduated", "method": "manual"})); + assert_eq!(classes(&s).0, [5.0, 50.0]); + // A view of low heights is read: quantiles and unique values come from it, and say so. + let v = view_of(&mut s, rustgis_geom::Extent::new(0.5, -1.0, 3.5, 1.0)); + crate::render::render_png(s.map_mut(), &v).unwrap(); + let n = s.map().layer(id).unwrap().dataset.features.len(); + assert!(n > 0 && n < 40, "{n}"); + let said = run(&mut s, json!({"type": "graduated", "method": "quantile", "classes": 2})); + assert_eq!( + said, + [format!( + "buildings: its symbology is worked out from the {n} features of the view read so far, not the whole layer read in place; values below or above them are drawn in the first or last class" + )] + ); + assert!(run(&mut s, json!({"type": "unique"}))[0].ends_with("values not among them are drawn as ")); + // Manual from the view's classes: its inner bounds come from the view, its ends from the file. + run(&mut s, json!({"type": "single"})); + let said = run(&mut s, json!({"type": "graduated", "method": "manual", "classes": 2})); + assert!(said[0].ends_with("the file's smallest and largest values close the first and last classes"), "{said:?}"); + let (breaks, min) = classes(&s); + assert_eq!((breaks.len(), breaks.last(), min), (2, Some(&40.0), 1.0)); + let _ = std::fs::remove_dir_all(dir); +} + /// Raster-side projection failures retain good multipart coverage and reach both command results. #[test] fn raster_projection_failures_are_reported_for_zonal_statistics_and_clipping() { diff --git a/crates/map/src/source.rs b/crates/map/src/source.rs index bd7051d48c..97b552e2e0 100644 --- a/crates/map/src/source.rs +++ b/crates/map/src/source.rs @@ -1167,6 +1167,12 @@ impl SourceLayer { self.handle.as_ref().map_or(rustgis_data::raster::Crs::LonLat, |h| h.coord_crs()) } + /// A numeric field's range across the whole source, when it states one ([`FeatureSource::field_range`]); + /// `None` until it is open. + pub fn field_range(&self, field: &str) -> Option<(f64, f64)> { + self.handle.as_ref()?.field_range(field) + } + /// A source that can be read whole a chunk at a time, for an export. pub fn visit_source(&self) -> Option> { self.handle.as_ref().filter(|h| h.visits_chunks()).cloned() diff --git a/crates/map/src/symbology.rs b/crates/map/src/symbology.rs index 77a13ef592..f4810dff64 100644 --- a/crates/map/src/symbology.rs +++ b/crates/map/src/symbology.rs @@ -1343,6 +1343,31 @@ impl Renderer { Ok(Self::graduated_on(ds, fi, ClassMethod::Manual, ramp, base, breaks, OPEN_BELOW)) } + /// [`Renderer::graduated_manual_open`] for a layer whose field's range `(lo, hi)` the file + /// states (GeoParquet column statistics): the classes close at it, as with the values at hand + /// ([`Renderer::graduated_manual`]). An open last bound among `breaks` (the layer's current + /// classes) gives way to `hi`. + pub fn graduated_manual_within( + ds: &Dataset, + field: &str, + breaks: &[f64], + (lo, hi): (f64, f64), + ramp: Ramp, + base: Symbol, + ) -> Result { + let fi = numeric_field(ds, field)?; + if breaks.contains(&OPEN_BELOW) { + return Err(format!("manual breaks must be above {OPEN_BELOW:e}")); + } + // The open class alone is one class of every value. + let breaks = if !breaks.is_empty() && breaks.iter().all(|v| *v >= OPEN_ABOVE) { + vec![hi] + } else { + manual_bounds(breaks, |v| v.is_finite() && v < OPEN_ABOVE, Some(hi))? + }; + Ok(Self::graduated_on(ds, fi, ClassMethod::Manual, ramp, base, breaks, lo)) + } + /// Closed Graduated Colors classes made open, as [`Renderer::graduated_manual_open`] makes /// them: the open class takes the place of the bound that closed them, so every feature keeps /// its class. `None` for other renderers and for classes already open. @@ -4584,6 +4609,28 @@ mod tests { assert_eq!(manual(&heights(&[]), &[4.0]).unwrap_err(), "'height' has no numeric values"); } + #[test] + fn manual_classes_within_the_file_range_close_at_it() { + let base = Symbol::default_for(GeometryType::Polygon, 0); + // No value at hand: the file's range closes the classes, the view's values set nothing. + let d = heights(&[Some(100.0)]); + let within = |b: &[f64]| Renderer::graduated_manual_within(&d, "height", b, (0.5, 60.0), Ramp::Ember, base); + let ends = |r: Renderer| match r { + Renderer::Graduated { breaks, min, .. } => (breaks, min), + r => panic!("{r:?}"), + }; + assert_eq!(ends(within(&[25.0, 4.0, 7.0, 10.0, 15.0]).unwrap()), (vec![4.0, 7.0, 10.0, 15.0, 25.0, 60.0], 0.5)); + let r = within(&[4.0, 25.0]).unwrap(); + assert_eq!(labels_of(&r), ["0.50 – 4", "4 – 25", "25 – 60"]); + // A bound past the largest closes the classes itself; the open class gives way to it. + assert_eq!(ends(within(&[4.0, 80.0]).unwrap()).0, [4.0, 80.0]); + assert_eq!(ends(within(&[4.0, OPEN_ABOVE]).unwrap()).0, [4.0, 60.0]); + assert_eq!(ends(within(&[OPEN_ABOVE]).unwrap()).0, [60.0]); + // Hostile bounds are refused as with no range. + assert!(within(&[]).is_err() && within(&[f64::NAN]).is_err() && within(&[OPEN_BELOW, 4.0]).is_err()); + assert!(Renderer::graduated_manual_within(&d, "name", &[1.0], (0.0, 1.0), Ramp::Ember, base).is_err()); + } + #[test] fn classes_open_at_one_end_are_opened_at_both() { let base = Symbol::default_for(GeometryType::Polygon, 0); diff --git a/docs/user-guide/cartography.md b/docs/user-guide/cartography.md index c84a9c5e02..4745afb9fe 100644 --- a/docs/user-guide/cartography.md +++ b/docs/user-guide/cartography.md @@ -48,9 +48,12 @@ Select a layer in Layers and open **Style › Symbology** (or the Symbology pane many small ones (city sizes, incomes). It sets its own number of classes, at most the number asked. Manual keeps the bounds you type: each class's upper bound is a number to edit or take out, **Split the widest class** adds one, and the field's largest value closes the last class. On a layer read in - place, whose values aren't all at hand, the field's range is unknown: the first class takes - every value up to its bound, and one more class takes every value past the last bound, shown - as "up to 4" and "more than 25" in the legend. If no field is + place, whose values aren't all at hand, a GeoParquet file's column statistics give the field's + smallest and largest values, which close the classes; without them the range is unknown: the + first class takes every value up to its bound, and one more class takes every value past the + last bound, shown as "up to 4" and "more than 25" in the legend. The other methods and Unique + Values on a layer read in place class the features of the view read so far, and the status bar + says so. If no field is chosen, the current renderer's field is kept when it is numeric; otherwise the first numeric field is used. If the layer has no numeric field, or the switch fails for another reason, the pane shows why and keeps the current renderer. When numeric From a454b987f00afd4954ce96397b115e7d20395389 Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Sun, 22 Nov 2026 17:16:12 -0300 Subject: [PATCH 2/4] fix(symbology): review round for #2715 - The file's range is looked up by the field as the layer spells it, so a name in another case finds it (CodeRabbit). - A first manual bound below the file's smallest value keeps the first class open instead of reading backwards (CodeRabbit). - Docs and params say the range is the whole file's, whatever the definition query keeps; field_range's doc says what a row group without statistics does. - Tests: unsigned, no statistics, decimal and Int64 past 2^53 columns; notice checks by their parts. Co-Authored-By: Claude Opus 5.5 --- crates/data/src/source/parquet.rs | 4 ++- crates/data/src/source/tests.rs | 45 +++++++++++++++++++++++++++++++ crates/engine/src/cmd/layer.rs | 6 +++-- crates/engine/src/tests.rs | 28 +++++++++++-------- crates/map/src/source.rs | 2 +- crates/map/src/symbology.rs | 10 +++++-- docs/user-guide/cartography.md | 3 ++- 7 files changed, 80 insertions(+), 18 deletions(-) diff --git a/crates/data/src/source/parquet.rs b/crates/data/src/source/parquet.rs index 2cac2f6db6..15475550fe 100644 --- a/crates/data/src/source/parquet.rs +++ b/crates/data/src/source/parquet.rs @@ -487,7 +487,9 @@ impl FeatureSource for ParquetSource { } /// From every row group's statistics of the field's column, which the footer holds: no byte of - /// the data is read. A row group without them (and not all nulls) leaves the range unknown. + /// the data is read. A row group without a statistics object, or whose statistics give no + /// bounds while it has values, leaves the range unknown (`None`); one whose statistics count + /// only nulls adds nothing. The field is named exactly as the source lists it. fn field_range(&self, field: &str) -> Option<(f64, f64)> { let i = self.info.fields.iter().position(|f| f.name == field && f.ty.is_numeric())?; let col = *self.field_cols.get(i)?; diff --git a/crates/data/src/source/tests.rs b/crates/data/src/source/tests.rs index f6ba368605..d9aeeb10f7 100644 --- a/crates/data/src/source/tests.rs +++ b/crates/data/src/source/tests.rs @@ -4907,3 +4907,48 @@ fn geoparquet_field_range_comes_from_column_statistics() { #[cfg(not(target_arch = "wasm32"))] assert_eq!(Fetching(Arc::new(source)).field_range("height"), Some((-2.0, 41.25))); } + +/// The column statistics that can't give a field's range, and the ones scaled or rounded to +/// hold every value: unsigned integers, a column without statistics, decimals, and Int64 past +/// 2^53 (#2497). +#[test] +fn geoparquet_field_range_refuses_unsigned_and_missing_statistics() { + use ::parquet::data_type::{ByteArray, ByteArrayType, DoubleType, Int32Type, Int64Type}; + use ::parquet::file::properties::{EnabledStatistics, WriterProperties}; + use ::parquet::file::writer::SerializedFileWriter; + use ::parquet::schema::types::ColumnPath; + let schema = ::parquet::schema::parser::parse_message_type( + "message m { REQUIRED BINARY geometry; OPTIONAL INT32 count (UINT_32); OPTIONAL INT64 price (DECIMAL(10,2)); OPTIONAL INT64 big; OPTIONAL DOUBLE bare; }", + ) + .unwrap(); + let props = WriterProperties::builder().set_column_statistics_enabled(ColumnPath::from("bare"), EnabledStatistics::None).build(); + let mut bytes = Vec::new(); + let mut w = SerializedFileWriter::new(&mut bytes, Arc::new(schema), Arc::new(props)).unwrap(); + let mut rg = w.next_row_group().unwrap(); + let geom = ByteArray::from(wkb::encode(&Geometry::Point(Coord::new(0.0, 0.0)))); + let mut col = rg.next_column().unwrap().unwrap(); + col.typed::().write_batch(&[geom.clone(), geom], None, None).unwrap(); + col.close().unwrap(); + let mut col = rg.next_column().unwrap().unwrap(); + col.typed::().write_batch(&[1, -1], Some(&[1, 1]), None).unwrap(); + col.close().unwrap(); + let big = (1i64 << 53) + 1; + for values in [[12_345, -50], [-big, big]] { + let mut col = rg.next_column().unwrap().unwrap(); + col.typed::().write_batch(&values, Some(&[1, 1]), None).unwrap(); + col.close().unwrap(); + } + let mut col = rg.next_column().unwrap().unwrap(); + col.typed::().write_batch(&[1.0, 2.0], Some(&[1, 1]), None).unwrap(); + col.close().unwrap(); + rg.close().unwrap(); + w.close().unwrap(); + let source = parquet::ParquetSource::open_bytes(bytes, "m").unwrap(); + let kinds: Vec<_> = source.info().fields.iter().map(|f| (f.name.as_str(), f.ty)).collect(); + assert!(kinds.contains(&("count", FieldType::Integer)) && kinds.contains(&("bare", FieldType::Double)), "{kinds:?}"); + assert_eq!(source.field_range("count"), None); + assert_eq!(source.field_range("bare"), None); + assert_eq!(source.field_range("price"), Some((-50.0 * 10f64.powi(-2), 12_345.0 * 10f64.powi(-2)))); + let (lo, hi) = source.field_range("big").unwrap(); + assert!(i128::from(big) <= hi as i128 && lo as i128 <= -i128::from(big), "{lo} {hi}"); +} diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index f03ed1d634..cb19651656 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -150,7 +150,7 @@ pub fn commands() -> Vec { .when(need_layer), C::new("layer.symbology", "Symbology", "Style › Drawing", symbology).roles(&[]).effects(crate::policy::Effects::NONE) .when(need_feature_layer) - .params(r#"{"layer"?, "type": "single"|"unique"|"graduated"|"proportional", "field"?, "expression"?: expression|null (unique: class by this expression's values instead of a field; blank or null: by a field; with neither key, Unique Values keep the layer's expression), "classes"?: 1..12, "method"?: "naturalBreaks"|"equalInterval"|"quantile"|"geometricInterval"|"standardDeviation"|"arithmeticProgression"|"headTailBreaks"|"manual", "breaks"?: [numbers] (manual: the classes' upper bounds, closed by the field's largest value; on a layer read in place, closed by the file's smallest and largest values when it states them (GeoParquet column statistics), else the first class takes every value up to its bound and one more class every value past the last; other methods and unique values on a layer read in place class the features of the view read so far, and say so), "ramp"?: string}"#), + .params(r#"{"layer"?, "type": "single"|"unique"|"graduated"|"proportional", "field"?, "expression"?: expression|null (unique: class by this expression's values instead of a field; blank or null: by a field; with neither key, Unique Values keep the layer's expression), "classes"?: 1..12, "method"?: "naturalBreaks"|"equalInterval"|"quantile"|"geometricInterval"|"standardDeviation"|"arithmeticProgression"|"headTailBreaks"|"manual", "breaks"?: [numbers] (manual: the classes' upper bounds, closed by the field's largest value; on a layer read in place, closed by the whole file's smallest and largest values when it states them (GeoParquet column statistics; a definition query doesn't narrow them), else the first class takes every value up to its bound and one more class every value past the last; other methods and unique values on a layer read in place class the features of the view read so far, and say so), "ramp"?: string}"#), C::new("layer.ramp", "Color Scheme", "Style › Drawing", |s, p| { let r = s.ramp(s_req(p, "ramp")?)?; let mut dropped = None; @@ -7527,7 +7527,9 @@ fn symbology(s: &mut Session, p: &Value) -> CmdResult { let (field, ramp) = (field(true)?, ramp.unwrap_or(Ramp::Ember)); // The field's range across the whole layer, when its file states it (GeoParquet // column statistics): it closes manual classes on a layer read in place. - let range = l.source.as_ref().and_then(|src| src.field_range(&field)); + // The field as the layer spells it, which a name in another case finds. + let range = + l.dataset.field_index(&field).and_then(|i| l.dataset.fields.get(i)).and_then(|f| l.source.as_ref()?.field_range(&f.name)); // Manual with no bounds keeps the layer's current ones on the same field, so switching // to it changes nothing. let kept = match &l.renderer { diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 339cac0860..b067e23707 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -46201,7 +46201,10 @@ fn classes_on_a_geoparquet_read_in_place_close_at_its_statistics_and_say_what_co }; // What a run said about the view. let run = |s: &mut Session, mut p: Value| { - (p["layer"], p["field"]) = (json!(id), json!("height")); + p["layer"] = json!(id); + if p.get("field").is_none() { + p["field"] = json!("height"); + } let mark = s.notice_mark(); s.run("layer.symbology", &p).unwrap(); s.notices_since(mark).iter().filter(|n| n.text.contains("of the view read so far")).map(|n| n.text.clone()).collect::>() @@ -46220,20 +46223,23 @@ fn classes_on_a_geoparquet_read_in_place_close_at_its_statistics_and_say_what_co crate::render::render_png(s.map_mut(), &v).unwrap(); let n = s.map().layer(id).unwrap().dataset.features.len(); assert!(n > 0 && n < 40, "{n}"); - let said = run(&mut s, json!({"type": "graduated", "method": "quantile", "classes": 2})); - assert_eq!( - said, - [format!( - "buildings: its symbology is worked out from the {n} features of the view read so far, not the whole layer read in place; values below or above them are drawn in the first or last class" - )] - ); - assert!(run(&mut s, json!({"type": "unique"}))[0].ends_with("values not among them are drawn as ")); + // One notice: the layer, the count of features read, and where values elsewhere go. + let says = |said: &[String], then: &str| { + let [one] = said else { panic!("{said:?}") }; + assert!(one.starts_with("buildings: ") && one.contains(&format!(" {n} features of the view read so far")), "{one}"); + assert!(one.contains(then), "{one}"); + }; + says(&run(&mut s, json!({"type": "graduated", "method": "quantile", "classes": 2})), "first or last class"); + says(&run(&mut s, json!({"type": "unique"})), ""); // Manual from the view's classes: its inner bounds come from the view, its ends from the file. run(&mut s, json!({"type": "single"})); - let said = run(&mut s, json!({"type": "graduated", "method": "manual", "classes": 2})); - assert!(said[0].ends_with("the file's smallest and largest values close the first and last classes"), "{said:?}"); + says(&run(&mut s, json!({"type": "graduated", "method": "manual", "classes": 2})), "file's smallest and largest values"); let (breaks, min) = classes(&s); assert_eq!((breaks.len(), breaks.last(), min), (2, Some(&40.0), 1.0)); + // The field named in another case finds the file's range too; a bound below it keeps the + // first class open. + run(&mut s, json!({"type": "graduated", "field": "HEIGHT", "breaks": [0.5, 4]})); + assert_eq!(classes(&s), (vec![0.5, 4.0, 40.0], rustgis_map::symbology::OPEN_BELOW)); let _ = std::fs::remove_dir_all(dir); } diff --git a/crates/map/src/source.rs b/crates/map/src/source.rs index 97b552e2e0..4dd27da1a9 100644 --- a/crates/map/src/source.rs +++ b/crates/map/src/source.rs @@ -1168,7 +1168,7 @@ impl SourceLayer { } /// A numeric field's range across the whole source, when it states one ([`FeatureSource::field_range`]); - /// `None` until it is open. + /// `None` while the source isn't open (before a project's reopen finishes, say). pub fn field_range(&self, field: &str) -> Option<(f64, f64)> { self.handle.as_ref()?.field_range(field) } diff --git a/crates/map/src/symbology.rs b/crates/map/src/symbology.rs index f4810dff64..f80dee135b 100644 --- a/crates/map/src/symbology.rs +++ b/crates/map/src/symbology.rs @@ -1346,7 +1346,8 @@ impl Renderer { /// [`Renderer::graduated_manual_open`] for a layer whose field's range `(lo, hi)` the file /// states (GeoParquet column statistics): the classes close at it, as with the values at hand /// ([`Renderer::graduated_manual`]). An open last bound among `breaks` (the layer's current - /// classes) gives way to `hi`. + /// classes) gives way to `hi`; a first bound below `lo` keeps the first class open ("up to"), + /// so its range never reads backwards. pub fn graduated_manual_within( ds: &Dataset, field: &str, @@ -1365,7 +1366,8 @@ impl Renderer { } else { manual_bounds(breaks, |v| v.is_finite() && v < OPEN_ABOVE, Some(hi))? }; - Ok(Self::graduated_on(ds, fi, ClassMethod::Manual, ramp, base, breaks, lo)) + let min = if breaks.first().is_some_and(|b| *b < lo) { OPEN_BELOW } else { lo }; + Ok(Self::graduated_on(ds, fi, ClassMethod::Manual, ramp, base, breaks, min)) } /// Closed Graduated Colors classes made open, as [`Renderer::graduated_manual_open`] makes @@ -4626,6 +4628,10 @@ mod tests { assert_eq!(ends(within(&[4.0, 80.0]).unwrap()).0, [4.0, 80.0]); assert_eq!(ends(within(&[4.0, OPEN_ABOVE]).unwrap()).0, [4.0, 60.0]); assert_eq!(ends(within(&[OPEN_ABOVE]).unwrap()).0, [60.0]); + // A first bound below the file's smallest value: the first class stays open. + let low = within(&[0.25, 4.0]).unwrap(); + assert_eq!(ends(low.clone()), (vec![0.25, 4.0, 60.0], OPEN_BELOW)); + assert_eq!(labels_of(&low), ["up to 0.25", "0.25 – 4", "4 – 60"]); // Hostile bounds are refused as with no range. assert!(within(&[]).is_err() && within(&[f64::NAN]).is_err() && within(&[OPEN_BELOW, 4.0]).is_err()); assert!(Renderer::graduated_manual_within(&d, "name", &[1.0], (0.0, 1.0), Ramp::Ember, base).is_err()); diff --git a/docs/user-guide/cartography.md b/docs/user-guide/cartography.md index 4745afb9fe..0a0d5c967e 100644 --- a/docs/user-guide/cartography.md +++ b/docs/user-guide/cartography.md @@ -49,7 +49,8 @@ Select a layer in Layers and open **Style › Symbology** (or the Symbology pane asked. Manual keeps the bounds you type: each class's upper bound is a number to edit or take out, **Split the widest class** adds one, and the field's largest value closes the last class. On a layer read in place, whose values aren't all at hand, a GeoParquet file's column statistics give the field's - smallest and largest values, which close the classes; without them the range is unknown: the + smallest and largest values, which close the classes (the whole file's, even when a definition + query keeps fewer rows); without them the range is unknown: the first class takes every value up to its bound, and one more class takes every value past the last bound, shown as "up to 4" and "more than 25" in the legend. The other methods and Unique Values on a layer read in place class the features of the view read so far, and the status bar From 27ff81ae8a2e4a6316367da17714c5ee27658098 Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Mon, 23 Nov 2026 17:16:58 -0300 Subject: [PATCH 3/4] fix: keep hand edits on classes closed at the file's range On a GeoParquet read in place, Manual closes the classes at the file's range, so classes closed at the view's range or left open (#2506) lost the labels and colours set by hand although the bounds between classes were the same. They now carry over when every feature keeps its class. The notice no longer says "not the whole layer" when the view holds the whole source and its count is exact. Row group bounds that are not finite or not in order leave the range unknown. Co-Authored-By: Claude Opus 5.5 --- crates/data/src/source/parquet.rs | 10 ++- crates/data/src/source/tests.rs | 50 ++++++++++++++ crates/engine/src/cmd/layer.rs | 16 +++-- crates/engine/src/tests.rs | 108 ++++++++++++++++++++++++++++++ crates/map/src/source.rs | 6 ++ crates/map/src/symbology.rs | 20 ++++++ 6 files changed, 203 insertions(+), 7 deletions(-) diff --git a/crates/data/src/source/parquet.rs b/crates/data/src/source/parquet.rs index 54c9f58d44..3eb7fb3b1f 100644 --- a/crates/data/src/source/parquet.rs +++ b/crates/data/src/source/parquet.rs @@ -488,8 +488,9 @@ impl FeatureSource for ParquetSource { /// From every row group's statistics of the field's column, which the footer holds: no byte of /// the data is read. A row group without a statistics object, or whose statistics give no - /// bounds while it has values, leaves the range unknown (`None`); one whose statistics count - /// only nulls adds nothing. The field is named exactly as the source lists it. + /// bounds while it has values, or bounds that aren't finite and in order, leaves the range + /// unknown (`None`); one whose statistics count only nulls adds nothing. The field is named exactly + /// as the source lists it. fn field_range(&self, field: &str) -> Option<(f64, f64)> { let i = self.info.fields.iter().position(|f| f.name == field && f.ty.is_numeric())?; let col = *self.field_cols.get(i)?; @@ -509,7 +510,10 @@ impl FeatureSource for ParquetSource { let rg = md.row_group(g); let s = rg.columns().get(col)?.statistics()?; match (number_stat(s, false), number_stat(s, true)) { - (Some(a), Some(b)) => Some((lo.min(a * scale), hi.max(b * scale))), + (Some(a), Some(b)) => { + let (a, b) = (a * scale, b * scale); + (a.is_finite() && b.is_finite() && a <= b).then(|| (lo.min(a), hi.max(b))) + } // A row group of nulls only has no bounds. _ if s.null_count_opt() == Some(u64::try_from(rg.num_rows()).ok()?) => Some((lo, hi)), _ => None, diff --git a/crates/data/src/source/tests.rs b/crates/data/src/source/tests.rs index cb8b38a9b4..fd8494b21f 100644 --- a/crates/data/src/source/tests.rs +++ b/crates/data/src/source/tests.rs @@ -4972,3 +4972,53 @@ fn geoparquet_field_range_refuses_unsigned_and_missing_statistics() { let (lo, hi) = source.field_range("big").unwrap(); assert!(i128::from(big) <= hi as i128 && lo as i128 <= -i128::from(big), "{lo} {hi}"); } + +/// Row groups whose statistics hold their smallest and largest value in order are joined; one that +/// gives them reversed leaves the range unknown, whatever the others give. +#[test] +fn geoparquet_field_range_checks_each_row_group() { + use ::parquet::data_type::{ByteArray, ByteArrayType, DoubleType, Int64Type}; + use ::parquet::file::statistics::Statistics; + use ::parquet::file::writer::SerializedFileWriter; + let schema = ::parquet::schema::parser::parse_message_type( + "message m { REQUIRED BINARY geometry; REQUIRED INT64 whole; REQUIRED DOUBLE real; }", + ) + .unwrap(); + let mut bytes = Vec::new(); + let mut w = SerializedFileWriter::new(&mut bytes, Arc::new(schema), Arc::default()).unwrap(); + let geom = ByteArray::from(wkb::encode(&Geometry::Point(Coord::new(0.0, 0.0)))); + for (lo, hi) in [(10, 20), (40, 50)] { + let mut rg = w.next_row_group().unwrap(); + let mut col = rg.next_column().unwrap().unwrap(); + col.typed::().write_batch(&[geom.clone(), geom.clone()], None, None).unwrap(); + col.close().unwrap(); + let mut col = rg.next_column().unwrap().unwrap(); + col.typed::().write_batch(&[lo, hi], None, None).unwrap(); + col.close().unwrap(); + let mut col = rg.next_column().unwrap().unwrap(); + col.typed::().write_batch(&[lo as f64, hi as f64], None, None).unwrap(); + col.close().unwrap(); + rg.close().unwrap(); + } + w.close().unwrap(); + let open = |bytes| parquet::ParquetSource::open_bytes(bytes, "m").unwrap(); + let source = open(bytes.clone()); + assert_eq!((source.field_range("whole"), source.field_range("real")), (Some((10.0, 50.0)), Some((10.0, 50.0)))); + // The second group's bounds, swapped where the footer holds them. + let len = u32::from_le_bytes(bytes[bytes.len() - 8..bytes.len() - 4].try_into().unwrap()) as usize; + let footer = bytes.len() - 8 - len; + for (a, b) in [(40i64.to_le_bytes(), 50i64.to_le_bytes()), (40f64.to_le_bytes(), 50f64.to_le_bytes())] { + for at in footer..bytes.len() - 8 { + if bytes[at..at + 8] == a { + bytes[at..at + 8].copy_from_slice(&b); + } else if bytes[at..at + 8] == b { + bytes[at..at + 8].copy_from_slice(&a); + } + } + } + let md = ::parquet::file::metadata::ParquetMetaDataReader::new().parse_and_finish(&bytes::Bytes::from(bytes.clone())).unwrap(); + let Some(Statistics::Int64(st)) = md.row_group(1).column(1).statistics() else { panic!() }; + assert_eq!((st.min_opt(), st.max_opt()), (Some(&50), Some(&40))); + let source = open(bytes); + assert_eq!((source.field_range("whole"), source.field_range("real")), (None, None)); +} diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index d7e4b90a9a..f849f9cf8a 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -7585,6 +7585,8 @@ fn symbology(s: &mut Session, p: &Value) -> CmdResult { // On a layer read in place, classes worked out from the features of the view read so far // (#2497), and what becomes of the values elsewhere in the layer. let mut from_view: Option<&str> = None; + // The file's largest value, when it closes Manual classes. + let mut closed_at = None; let mut r = match kind.as_str() { "single" | "singlesymbol" => Renderer::Single(base), "unique" | "uniquevalues" => { @@ -7637,7 +7639,10 @@ fn symbology(s: &mut Session, p: &Value) -> CmdResult { // range is unknown: the classes take every value up to the first bound and past // the last. (ClassMethod::Manual, Some(b)) if l.is_streamed() => match range { - Some(range) => Renderer::graduated_manual_within(&l.dataset, &field, &b, range, ramp, base)?, + Some(range) => { + closed_at = Some(range.1); + Renderer::graduated_manual_within(&l.dataset, &field, &b, range, ramp, base)? + } None => Renderer::graduated_manual_open(&l.dataset, &field, &b, ramp, base)?, }, (ClassMethod::Manual, Some(b)) => Renderer::graduated_manual(&l.dataset, &rows()?, &field, &b, ramp, base)?, @@ -7678,12 +7683,13 @@ fn symbology(s: &mut Session, p: &Value) -> CmdResult { }; // Applied again on the same field, the classes keep the labels set by hand, and the colours // and outlines set by hand too while the colour scheme stays (#314). Closed classes made open - // on a layer read in place class every feature as before, so their edits carry over too. + // on a layer read in place class every feature as before, so their edits carry over too; so do + // those of the view's classes closed at the file's range. let opened = match &r { Renderer::Graduated { breaks, .. } if l.is_streamed() && breaks.last() == Some(&rustgis_map::symbology::OPEN_ABOVE) => { l.renderer.opened() } - _ => None, + _ => closed_at.and_then(|hi| l.renderer.with_ends_of(&r, hi)), }; r.carry_edits_from(opened.as_ref().unwrap_or(&l.renderer), g); // The same field and scheme again carry the classes' alpha, which No Fill made 0. @@ -7700,7 +7706,9 @@ fn symbology(s: &mut Session, p: &Value) -> CmdResult { _ => String::new(), }; let order = if rest.by_number { "by number" } else { "in text order" }; - let from_view = from_view.filter(|_| l.is_streamed()).map(|then| (l.dataset.kept_features(&l.visible_rows()).count(), then)); + // A view that holds the whole source says nothing. + let part = l.source.as_ref().is_some_and(|src| src.exact_count() != Some(l.dataset.features.len() as u64)); + let from_view = from_view.filter(|_| part).map(|then| (l.dataset.kept_features(&l.visible_rows()).count(), then)); let mut dropped = None; let out = with(s, p, |l| { l.renderer = r; diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index c759d15849..af53cfe134 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -46858,6 +46858,114 @@ fn classes_on_a_geoparquet_read_in_place_close_at_its_statistics_and_say_what_co let _ = std::fs::remove_dir_all(dir); } +/// On a GeoParquet read in place, with a view of part of the file, a label and colour set by hand +/// on the view's classes stay when Manual closes them at the file's range, and only while the +/// inner bounds stay; the notice of the view is for a view that isn't the whole source (#2497). +#[test] +fn hand_edits_and_the_notice_on_a_geoparquet_read_in_place_follow_the_view() { + use rustgis_data::source::{Batch, FeatureSource, Request, SourceInfo}; + use rustgis_data::{Coord, Dataset, Field, FieldType, Geometry, GeometryType, Value as V}; + use rustgis_map::source::{PostgisOrigin, SourceLayer}; + // A source that counts its features as told. + struct Says(SourceInfo); + impl FeatureSource for Says { + fn info(&self) -> &SourceInfo { + &self.0 + } + fn read(&self, _: &Request) -> rustgis_data::Result { + Ok(Batch::default()) + } + } + let mut ds = Dataset::new("buildings", GeometryType::Point, vec![Field::new("height", FieldType::Double)]); + for h in 1..=40 { + ds.push(Some(Geometry::Point(Coord::new(f64::from(h), 0.0))), vec![V::Float(f64::from(h))]); + } + let dir = std::env::temp_dir().join(format!("rustgis-hand-edits-in-view-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("buildings.parquet"); + rustgis_data::io::write_path(&ds, &path).unwrap(); + let mut s = Session::new(Project::default()); + let id = + s.run("layer.addData", &json!({"path": path.display().to_string(), "stream": true})).unwrap()["layer"].as_u64().unwrap() as u32; + let run = |s: &mut Session, mut p: Value| { + p["layer"] = json!(id); + p["type"] = json!("graduated"); + p["field"] = json!("height"); + let mark = s.notice_mark(); + s.run("layer.symbology", &p).unwrap(); + s.notices_since(mark).iter().filter(|n| n.text.contains("of the view read so far")).count() + }; + let red = rustgis_map::Rgba::rgb(255, 0, 0); + let legend = |s: &Session| s.map().layer(id).unwrap().renderer.legend(); + let kept = |s: &Session| { + legend(s).iter().enumerate().filter(|(_, c)| c.label == "Tall" || c.symbol.fill == red).map(|(i, _)| i).collect::>() + }; + // Part of the file: three classes of the view's, the middle one edited by hand. + let edited = |s: &mut Session| { + run(s, json!({"type": "graduated", "breaks": [99]})); + assert_eq!(run(s, json!({"method": "equalInterval", "classes": 3})), 1); + s.run("layer.classStyle", &json!({"layer": id, "index": 1, "label": "Tall", "color": "#ff0000"})).unwrap(); + assert_eq!(kept(s), [1]); + match &s.map().layer(id).unwrap().renderer { + rustgis_map::Renderer::Graduated { breaks, .. } => breaks.clone(), + r => panic!("{r:?}"), + } + }; + let v = view_of(&mut s, rustgis_geom::Extent::new(0.5, -1.0, 3.5, 1.0)); + crate::render::render_png(s.map_mut(), &v).unwrap(); + assert!(s.map().layer(id).unwrap().dataset.features.len() < 40); + let b = edited(&mut s); + run(&mut s, json!({"method": "manual"})); + assert_eq!((kept(&s), legend(&s)[2].label.ends_with("40")), (vec![1], true)); + // The same inner bounds, typed. + edited(&mut s); + run(&mut s, json!({"breaks": [b[0], b[1]]})); + assert_eq!(kept(&s), [1]); + // Other inner bounds, one fewer, one more, or a closing bound of one's own: none is kept. + for other in [vec![b[0], b[1] + 1.0], vec![b[0]], vec![b[0], b[1], b[2]], vec![b[0], b[1], 50.0]] { + edited(&mut s); + run(&mut s, json!({"breaks": other})); + assert!(kept(&s).is_empty(), "{other:?}: {:?}", kept(&s)); + } + // Nor those of a class past the file's largest value, once its bound is taken out. + run(&mut s, json!({"breaks": [5, 50]})); + s.run("layer.classStyle", &json!({"layer": id, "index": 1, "label": "Tall", "color": "#ff0000"})).unwrap(); + run(&mut s, json!({"breaks": [5]})); + assert!(kept(&s).is_empty()); + // Open classes a project saved before they closed at the file's range keep theirs too. + edited(&mut s); + let l = s.map_mut().layer_mut(id).unwrap(); + l.renderer = l.renderer.opened().unwrap(); + run(&mut s, json!({"method": "manual"})); + assert_eq!((kept(&s), legend(&s)[2].label.ends_with("40")), (vec![1], true)); + // Nor when the classes are worked out again from another view. + edited(&mut s); + let v = view_of(&mut s, rustgis_geom::Extent::new(-5.0, -5.0, 45.0, 5.0)); + crate::render::render_png(s.map_mut(), &v).unwrap(); + let l = s.map().layer(id).unwrap(); + assert_eq!((l.dataset.features.len(), l.feature_count()), (40, Some(40))); + // The view now holds the whole source: nothing to say. + let classes = json!({"method": "equalInterval", "classes": 3}); + assert_eq!(run(&mut s, classes.clone()), 0); + assert!(kept(&s).is_empty()); + // The same 40 features of a source that doesn't count them, counts more, or whose count can + // be an estimate (a database's): the notice stays. + let source = s.map().layer(id).unwrap().source.as_ref().unwrap(); + let info = source.info().unwrap().clone(); + let says = |count| Box::new(Says(SourceInfo { count, ..info.clone() })); + let origin = PostgisOrigin { database: "postgres:host=h".into(), table: "t".into(), family: None, crs: None }; + for (source, said) in [ + (SourceLayer::from_path("b.parquet", None, says(None)), 1), + (SourceLayer::from_path("b.parquet", None, says(Some(41))), 1), + (SourceLayer::from_postgis(origin, says(Some(40))), 1), + (SourceLayer::from_path("b.parquet", None, says(Some(40))), 0), + ] { + s.map_mut().layer_mut(id).unwrap().source = Some(source); + assert_eq!(run(&mut s, classes.clone()), said); + } + let _ = std::fs::remove_dir_all(dir); +} + /// Raster-side projection failures retain good multipart coverage and reach both command results. #[test] fn raster_projection_failures_are_reported_for_zonal_statistics_and_clipping() { diff --git a/crates/map/src/source.rs b/crates/map/src/source.rs index b85296e529..2be08b2467 100644 --- a/crates/map/src/source.rs +++ b/crates/map/src/source.rs @@ -1214,6 +1214,12 @@ impl SourceLayer { self.handle.as_ref()?.field_range(field) } + /// Its source's number of features, when known exactly: a database's can be an estimate. + pub fn exact_count(&self) -> Option { + let database = self.postgis.is_some() || self.mysql.is_some() || self.sqlserver.is_some(); + self.info().filter(|_| !database)?.count + } + /// Whether its source tests its features against a box in its own system /// ([`FeatureSource::reads_own_box`]); no until it is open. pub fn reads_own_box(&self) -> bool { diff --git a/crates/map/src/symbology.rs b/crates/map/src/symbology.rs index 1607b019b2..f66c1b3c19 100644 --- a/crates/map/src/symbology.rs +++ b/crates/map/src/symbology.rs @@ -1388,6 +1388,26 @@ impl Renderer { Some(open) } + /// These Graduated Colors classes with the ends of `other`'s, whose last bound closes them at + /// the field's largest value `hi` ([`Renderer::graduated_manual_within`]), when the bounds + /// between classes are the same: every feature keeps its class. `None` for other renderers, + /// for other inner bounds, and when either last bound is past `hi` (one of its own). + pub fn with_ends_of(&self, other: &Renderer, hi: f64) -> Option { + let (Renderer::Graduated { breaks: ours, .. }, Renderer::Graduated { breaks: theirs, min: start, .. }) = (self, other) else { + return None; + }; + let ((our_last, our_inner), (their_last, their_inner)) = (ours.split_last()?, theirs.split_last()?); + if our_inner != their_inner || *their_last != hi || (*our_last > hi && *our_last < OPEN_ABOVE) { + return None; + } + let mut same = self.clone(); + if let Renderer::Graduated { breaks, min, .. } = &mut same { + breaks.clone_from(theirs); + *min = *start; + } + Some(same) + } + /// A graduated renderer on `field`, with the bounds `breaks` works out from the field's sorted /// values. fn graduated_by( From e8000f3a1a70997040bd1196f03372e4c4cf7279 Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Tue, 24 Nov 2026 15:20:37 -0300 Subject: [PATCH 4/4] test: hand edits on view classes keep both the label and the colour Also say in the doc of with_ends_of that an open last bound is taken as closed at the file's largest value. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/tests.rs | 8 +++++--- crates/map/src/symbology.rs | 3 ++- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index ee9311c23c..069032ee6f 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -47918,6 +47918,8 @@ fn hand_edits_and_the_notice_on_a_geoparquet_read_in_place_follow_the_view() { let kept = |s: &Session| { legend(s).iter().enumerate().filter(|(_, c)| c.label == "Tall" || c.symbol.fill == red).map(|(i, _)| i).collect::>() }; + // Both edits, on the class they were made on. + let both = |s: &Session| legend(s)[1].label == "Tall" && legend(s)[1].symbol.fill == red; // Part of the file: three classes of the view's, the middle one edited by hand. let edited = |s: &mut Session| { run(s, json!({"type": "graduated", "breaks": [99]})); @@ -47934,11 +47936,11 @@ fn hand_edits_and_the_notice_on_a_geoparquet_read_in_place_follow_the_view() { assert!(s.map().layer(id).unwrap().dataset.features.len() < 40); let b = edited(&mut s); run(&mut s, json!({"method": "manual"})); - assert_eq!((kept(&s), legend(&s)[2].label.ends_with("40")), (vec![1], true)); + assert_eq!((kept(&s), both(&s), legend(&s)[2].label.ends_with("40")), (vec![1], true, true)); // The same inner bounds, typed. edited(&mut s); run(&mut s, json!({"breaks": [b[0], b[1]]})); - assert_eq!(kept(&s), [1]); + assert_eq!((kept(&s), both(&s)), (vec![1], true)); // Other inner bounds, one fewer, one more, or a closing bound of one's own: none is kept. for other in [vec![b[0], b[1] + 1.0], vec![b[0]], vec![b[0], b[1], b[2]], vec![b[0], b[1], 50.0]] { edited(&mut s); @@ -47955,7 +47957,7 @@ fn hand_edits_and_the_notice_on_a_geoparquet_read_in_place_follow_the_view() { let l = s.map_mut().layer_mut(id).unwrap(); l.renderer = l.renderer.opened().unwrap(); run(&mut s, json!({"method": "manual"})); - assert_eq!((kept(&s), legend(&s)[2].label.ends_with("40")), (vec![1], true)); + assert_eq!((kept(&s), both(&s), legend(&s)[2].label.ends_with("40")), (vec![1], true, true)); // Nor when the classes are worked out again from another view. edited(&mut s); let v = view_of(&mut s, rustgis_geom::Extent::new(-5.0, -5.0, 45.0, 5.0)); diff --git a/crates/map/src/symbology.rs b/crates/map/src/symbology.rs index 291b894629..86fe5533e6 100644 --- a/crates/map/src/symbology.rs +++ b/crates/map/src/symbology.rs @@ -1391,7 +1391,8 @@ impl Renderer { /// These Graduated Colors classes with the ends of `other`'s, whose last bound closes them at /// the field's largest value `hi` ([`Renderer::graduated_manual_within`]), when the bounds /// between classes are the same: every feature keeps its class. `None` for other renderers, - /// for other inner bounds, and when either last bound is past `hi` (one of its own). + /// for other inner bounds, and when either last bound is a typed one past `hi`; an open last + /// bound of these classes ([`OPEN_ABOVE`]) is taken as closed at `hi`. pub fn with_ends_of(&self, other: &Renderer, hi: f64) -> Option { let (Renderer::Graduated { breaks: ours, .. }, Renderer::Graduated { breaks: theirs, min: start, .. }) = (self, other) else { return None;