diff --git a/crates/data/src/source/mod.rs b/crates/data/src/source/mod.rs index 64c90af0da..b514c6543d 100644 --- a/crates/data/src/source/mod.rs +++ b/crates/data/src/source/mod.rs @@ -485,6 +485,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 + } /// Whether the source's notes ([`SourceInfo::notes`]) already count the features it keeps /// with a place that can't be given in longitude/latitude, so a whole read doesn't count them /// again. @@ -754,6 +760,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 says_unplaced_at_open(&self) -> bool { self.0.says_unplaced_at_open() } diff --git a/crates/data/src/source/parquet.rs b/crates/data/src/source/parquet.rs index da9165cf6d..254c7daa86 100644 --- a/crates/data/src/source/parquet.rs +++ b/crates/data/src/source/parquet.rs @@ -489,6 +489,42 @@ 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 a statistics object, or whose statistics give no + /// 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)?; + 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)) => { + 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, + } + })?; + (lo.is_finite() && hi.is_finite() && lo <= hi).then_some((lo, hi)) + } + fn reads_own_box(&self) -> bool { true } @@ -1071,6 +1107,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 b0a70934b9..5eeed7bb43 100644 --- a/crates/data/src/source/tests.rs +++ b/crates/data/src/source/tests.rs @@ -5103,6 +5103,127 @@ fn write_projected_parquet_fixture(ds: &Dataset, path: &Path, rows: usize, dicti 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))); +} + +/// 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}"); +} + +/// 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)); +} + /// The spatial index, loaded after the rows in Hilbert order, holds one entry with the box of /// each feature that has a place (none for one without), and the same layer gives the same index /// nodes each time. diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index f8e1f2a996..41b265a254 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -148,7 +148,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 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; @@ -7712,35 +7712,49 @@ 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; + // 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" => 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. + // 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 { 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); @@ -7754,11 +7768,17 @@ 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) => { + 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)?, // 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") @@ -7766,27 +7786,40 @@ 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}'")), }; // 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. @@ -7803,6 +7836,9 @@ fn symbology(s: &mut Session, p: &Value) -> CmdResult { _ => String::new(), }; let order = if rest.by_number { "by number" } else { "in text order" }; + // 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; @@ -7819,6 +7855,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 d1ffa103c7..e574cb658e 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -48345,6 +48345,182 @@ 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"] = 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::>() + }; + // 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}"); + // 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"})); + 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); +} + +/// 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::>() + }; + // 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]})); + 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), 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), 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); + 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), 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)); + 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 89b3dc02b1..1626beab33 100644 --- a/crates/map/src/source.rs +++ b/crates/map/src/source.rs @@ -1216,6 +1216,18 @@ 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` 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) + } + + /// 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 ef6e600c61..fe006a50f5 100644 --- a/crates/map/src/symbology.rs +++ b/crates/map/src/symbology.rs @@ -1343,6 +1343,33 @@ 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`; 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, + 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))? + }; + 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 /// 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. @@ -1361,6 +1388,27 @@ 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 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; + }; + 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( @@ -4696,6 +4744,32 @@ 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]); + // 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()); + } + #[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 f269dc6a84..842c100cc3 100644 --- a/docs/user-guide/cartography.md +++ b/docs/user-guide/cartography.md @@ -48,9 +48,13 @@ 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 (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 + 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