From 021fc41da3c657c1e58a97f18c19daf890ff4905 Mon Sep 17 00:00:00 2001 From: PawelKra <15887575+PawelKra@users.noreply.github.com> Date: Tue, 3 Nov 2026 11:13:17 +0100 Subject: [PATCH 1/4] fix(style): Unique Values on numbers in numeric order, and say what is past the first 64 (#1340) Unique Values on a numeric field listed its classes and legend as text: 10153 before 1741, 9627 last. Dataset::unique_values sorted the values' text, and Renderer::class_order sorted the legend by label. Classes are now ordered by number when every value reads as one (a numeric field, or a text field of codes), with empty and values after them; otherwise by text, as before. Whole numbers past 2^53 are compared exactly. The legend follows the same order, and a class renamed by hand keeps its value's place. The order is read from the class values, so projects saved with classes in text order list them by number too, with no change to the renderer or the project format. Unique Values keeps at most 64 classes. The list was cut after the text sort, so a numeric field with more values kept a text-ordered subset (10, 100, 1000 before 2), and Unique Values by a field gave no notice of the features drawn as . It now keeps the first 64 in the order above, and layer.symbology reports how many features are past them, by a field as it already did by an expression. Unique Values by an expression keeps the first values by number too: it tracks the first by text and by number together, and uses the second when no value read as text. --- crates/data/src/lib.rs | 57 +++++++- crates/data/src/value.rs | 170 ++++++++++++++++++++++ crates/engine/src/cmd/layer.rs | 20 ++- crates/engine/src/tests.rs | 118 ++++++++++++++- crates/map/src/symbology.rs | 253 ++++++++++++++++++++++++++++----- docs/user-guide/cartography.md | 6 +- 6 files changed, 576 insertions(+), 48 deletions(-) diff --git a/crates/data/src/lib.rs b/crates/data/src/lib.rs index 0abaa2ee05..97f12615e4 100644 --- a/crates/data/src/lib.rs +++ b/crates/data/src/lib.rs @@ -499,13 +499,26 @@ impl Dataset { r } - /// Distinct display values of a field over the features `rows` keeps, sorted, capped at `limit`. + /// Distinct display values of a field over the features `rows` keeps, the first `limit` in + /// Unique Values' order ([`value::sort_class_values`]: by number when they read as numbers). pub fn unique_values(&self, field: usize, rows: &[bool], limit: usize) -> Vec { - let mut v: Vec = self.kept_features(rows).map(|f| f.attrs.get(field).map(|x| x.to_string()).unwrap_or_default()).collect(); - v.sort(); - v.dedup(); + self.unique_values_counted(field, rows, limit).0 + } + + /// [`Dataset::unique_values`], and what is past them: how many of the kept features with a + /// geometry have a value past the first `limit`, and whether those were taken by number. + pub fn unique_values_counted(&self, field: usize, rows: &[bool], limit: usize) -> (Vec, value::PastClasses) { + let mut drawn: std::collections::HashMap = std::collections::HashMap::new(); + for f in self.kept_features(rows) { + let text = f.attrs.get(field).map(|x| x.to_string()).unwrap_or_default(); + *drawn.entry(text).or_insert(0) += usize::from(f.geometry.is_some()); + } + let mut v: Vec = drawn.keys().cloned().collect(); + let by_number = value::numeric_classes(v.iter().map(String::as_str)); + value::sort_class_values(&mut v); + let features = v.get(limit..).unwrap_or_default().iter().filter_map(|k| drawn.get(k)).sum(); v.truncate(limit); - v + (v, value::PastClasses { features, by_number }) } } @@ -561,6 +574,40 @@ mod tests { assert_eq!(d.value(99, 99), &Value::Null); } + /// #1340: a numeric field's distinct values are in numeric order, and the first `limit` kept + /// are the smallest; a text field's keep text order. + #[test] + fn unique_values_of_a_numeric_field_are_in_numeric_order() { + let point = || Some(Geometry::Point(Coord::new(0.0, 0.0))); + let fields = vec![Field::new("i", FieldType::Integer), Field::new("r", FieldType::Double), Field::new("t", FieldType::Text)]; + let mut d = Dataset::new("t", GeometryType::Point, fields); + for (i, r, t) in [(100, 10.0, "b"), (9, 2.5, "A"), (10, -1.0, "10"), (9, 10.0, "9")] { + d.push(point(), vec![Value::Int(i), Value::Float(r), Value::Text(t.into())]); + } + d.push(point(), vec![Value::Null, Value::Null, Value::Null]); + assert_eq!(d.unique_values(0, &[], 10), ["9", "10", "100", ""]); + assert_eq!(d.unique_values(1, &[], 10), ["-1", "2.5", "10", ""]); + assert_eq!(d.unique_values(2, &[], 10), ["10", "9", "", "A", "b"], "text keeps its order"); + // The first two are the two smallest, and the features past them are counted. + let (first, past) = d.unique_values_counted(0, &[], 2); + assert_eq!(first, ["9", "10"]); + assert_eq!(past, value::PastClasses { features: 2, by_number: true }); + assert_eq!(d.unique_values_counted(0, &[], 10).1.features, 0); + assert_eq!(d.unique_values_counted(2, &[], 10).1, value::PastClasses { features: 0, by_number: false }); + // Only kept features count, and only those with a geometry (one without draws nothing). + d.push(None, vec![Value::Int(500)]); + assert_eq!(d.unique_values_counted(0, &[], 2).1.features, 2); + assert_eq!(d.unique_values_counted(0, &[true, true, true, true, false], 2).1.features, 1); + // (A row past the end of `rows` is kept.) + assert_eq!(d.unique_values(0, &[false, false, true, false, false, false], 10), ["10"]); + // A text value in a numeric field (a hostile file) orders the field as text, and says so + // though the values kept are numbers. + d.push(point(), vec![Value::Text("x".into())]); + let (first, past) = d.unique_values_counted(0, &[], 3); + assert_eq!(first, ["10", "100", "500"]); + assert_eq!(past, value::PastClasses { features: 4, by_number: false }); + } + #[test] fn push_keeps_the_largest_id_instead_of_searching_for_it() { let mut d = Dataset::new("t", GeometryType::Point, vec![]); diff --git a/crates/data/src/value.rs b/crates/data/src/value.rs index 48489d214b..6efb274994 100644 --- a/crates/data/src/value.rs +++ b/crates/data/src/value.rs @@ -136,3 +136,173 @@ impl PartialOrd for Value { } } } + +/// A Unique Values class's value, given as its text, read as a number: a whole number exactly +/// (past 2^53 too), any other as a decimal. +#[derive(Clone, Copy)] +enum ClassNumber { + Whole(i128), + Decimal(f64), +} + +fn class_number(text: &str) -> Option { + match text.parse::() { + Ok(i) => Some(ClassNumber::Whole(i)), + Err(_) => text.parse::().ok().map(ClassNumber::Decimal), + } +} + +/// Orders two class numbers by value, exactly: NaN after every other number. +fn cmp_class_numbers(a: ClassNumber, b: ClassNumber) -> std::cmp::Ordering { + use std::cmp::Ordering; + // A whole number against a decimal: as decimals, and where they're equal (as a whole number + // past 2^53 can be to the decimal it rounds to), exactly. A decimal equal to a whole + // number's is itself whole and within i128, so the cast is exact. + let whole_to_decimal = |i: i128, f: f64| match (i as f64).partial_cmp(&f) { + Some(Ordering::Equal) => i.cmp(&(f as i128)), + Some(o) => o, + None => Ordering::Less, + }; + match (a, b) { + (ClassNumber::Whole(x), ClassNumber::Whole(y)) => x.cmp(&y), + (ClassNumber::Whole(x), ClassNumber::Decimal(y)) => whole_to_decimal(x, y), + (ClassNumber::Decimal(x), ClassNumber::Whole(y)) => whole_to_decimal(y, x).reverse(), + (ClassNumber::Decimal(x), ClassNumber::Decimal(y)) => match (x.is_nan(), y.is_nan()) { + (false, false) => x.partial_cmp(&y).unwrap_or(Ordering::Equal), + (nan_x, nan_y) => nan_x.cmp(&nan_y), + }, + } +} + +/// Whether a class value's text keeps Unique Values classes from being ordered by number: text +/// that reads as no number, other than the empty text and `` (a missing value's). +pub fn orders_as_text(text: &str) -> bool { + !text.is_empty() && text != "" && class_number(text).is_none() +} + +/// Whether Unique Values classes with these values, given as their text, are ordered by number: +/// when one reads as a number and every other does too, or is the empty text or ``. A +/// numeric field's values always are; a text field's when it holds only numbers, such as codes. +pub fn numeric_classes<'a>(values: impl IntoIterator) -> bool { + let mut number = false; + for v in values { + if orders_as_text(v) { + return false; + } + number |= !v.is_empty() && v != ""; + } + number +} + +/// Orders two Unique Values classes' values, given as their text, when [`numeric_classes`]: by +/// number (9 before 10), then the rest (the empty text, ``) after them by text. Values equal +/// in number are ordered by text (1 before 1.0), so this is a total order on texts. +pub fn cmp_numeric_classes(a: &str, b: &str) -> std::cmp::Ordering { + use std::cmp::Ordering; + match (class_number(a), class_number(b)) { + (Some(x), Some(y)) => cmp_class_numbers(x, y).then_with(|| a.cmp(b)), + (Some(_), None) => Ordering::Less, + (None, Some(_)) => Ordering::Greater, + (None, None) => a.cmp(b), + } +} + +/// What Unique Values leaves out of its classes: how many kept features with a geometry have a +/// value past the first it keeps (drawn as ``), and whether those first were +/// taken by number ([`numeric_classes`] over every value) or by text. The classes kept can all be +/// numbers though they were taken by text, past a text value that sorts after them. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct PastClasses { + pub features: usize, + pub by_number: bool, +} + +/// Sorts Unique Values classes' values, given as their text: by number when +/// [`numeric_classes`], else by text. +pub fn sort_class_values(values: &mut [String]) { + if numeric_classes(values.iter().map(String::as_str)) { + values.sort_by(|a, b| cmp_numeric_classes(a, b)); + } else { + values.sort(); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn sorted(values: &[&str]) -> Vec { + let mut v: Vec = values.iter().map(|s| s.to_string()).collect(); + sort_class_values(&mut v); + v + } + + #[test] + fn classes_are_ordered_by_number_when_every_value_reads_as_one() { + assert_eq!(sorted(&["100", "9", "10"]), ["9", "10", "100"]); + assert_eq!(sorted(&["10", "2.5", "-1"]), ["-1", "2.5", "10"]); + // As a field's display text writes them: a large decimal without an exponent. + assert_eq!(sorted(&["100000000000000000000", "3e2", "250"]), ["250", "3e2", "100000000000000000000"]); + assert_eq!(sorted(&[&i64::MAX.to_string(), &i64::MIN.to_string(), "0"]), [i64::MIN.to_string(), "0".into(), i64::MAX.to_string()]); + } + + #[test] + fn a_text_among_the_values_keeps_text_order() { + assert_eq!(sorted(&["b", "A", "10", "9"]), ["10", "9", "A", "b"]); + assert_eq!(sorted(&["10", "9", "1 0"]), ["1 0", "10", "9"], "a number with a space is text"); + assert!(!numeric_classes(["9", "x"])); + } + + #[test] + fn missing_values_go_after_the_numbers() { + assert_eq!(sorted(&["", "10", "", "9"]), ["9", "10", "", ""]); + assert!(numeric_classes(["", "5"])); + // With no number, nothing to order by number. + assert!(!numeric_classes(["", ""])); + assert!(!numeric_classes([])); + } + + #[test] + fn whole_numbers_past_2_53_are_ordered_exactly() { + // 2^53 + 1 and 2^53 are one decimal; as whole numbers they differ. + assert_eq!(sorted(&["9007199254740993", "9007199254740992"]), ["9007199254740992", "9007199254740993"]); + assert_eq!(sorted(&["-9007199254740992", "-9007199254740993"]), ["-9007199254740993", "-9007199254740992"]); + // A decimal that reads as 2^53 is between them. + assert_eq!( + sorted(&["9007199254740993", "9007199254740992.5", "9007199254740991"]), + ["9007199254740991", "9007199254740992.5", "9007199254740993"] + ); + // Below zero, where their texts order the other way. + assert_eq!(sorted(&["-9007199254740992.5", "-9007199254740993"]), ["-9007199254740993", "-9007199254740992.5"]); + assert_eq!(cmp_numeric_classes("9007199254740992.5", "9007199254740993"), std::cmp::Ordering::Less); + assert_eq!(cmp_numeric_classes("9007199254740993", "9007199254740992.5"), std::cmp::Ordering::Greater); + } + + #[test] + fn numbers_equal_in_value_and_not_a_number_have_a_place() { + // Equal in number: by text, so the order is total and repeatable. + assert_eq!(sorted(&["1.0", "1"]), ["1", "1.0"]); + assert_eq!(sorted(&["0", "-0"]), ["-0", "0"]); + // Infinities in their place, NaN after every number and before missing values. + assert_eq!(sorted(&["NaN", "inf", "", "0", "-inf"]), ["-inf", "0", "inf", "NaN", ""]); + } + + #[test] + fn the_numeric_order_is_total() { + let values = ["NaN", "-inf", "inf", "1", "1.0", "-0", "0", "9007199254740993", "9007199254740992.5", "2.5", "", ""]; + for a in values { + assert_eq!(cmp_numeric_classes(a, a), std::cmp::Ordering::Equal, "{a}"); + for b in values { + assert_eq!(cmp_numeric_classes(a, b), cmp_numeric_classes(b, a).reverse(), "{a} {b}"); + if a != b { + assert_ne!(cmp_numeric_classes(a, b), std::cmp::Ordering::Equal, "{a} {b}"); + } + for c in values { + if cmp_numeric_classes(a, b).is_lt() && cmp_numeric_classes(b, c).is_lt() { + assert!(cmp_numeric_classes(a, c).is_lt(), "{a} < {b} < {c}"); + } + } + } + } + } +} diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 2075e6a975..88a1ca68d4 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -3933,7 +3933,7 @@ fn symbology(s: &mut Session, p: &Value) -> CmdResult { _ => expression, }; // Features past the first values an expression's classes keep. - let mut rest = 0; + let mut rest = rustgis_data::value::PastClasses::default(); let mut r = match kind.as_str() { "single" | "singlesymbol" => Renderer::Single(base), "unique" | "uniquevalues" => match &expression { @@ -3946,7 +3946,11 @@ fn symbology(s: &mut Session, p: &Value) -> CmdResult { } r } - None => Renderer::unique(&l.dataset, &rows()?, &field(false)?, ramp.unwrap_or(Ramp::Harbour), base)?, + 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)); @@ -3979,14 +3983,22 @@ fn symbology(s: &mut Session, p: &Value) -> CmdResult { let name = l.name.clone(); // Classes are the values given with no map scale: one given only at some scales never is. let by_scale = r.expression().is_some_and(rustgis_map::qgis::reads_scale); + // Where the values past the classes come from, and in which order the first are kept. + let values = match &r { + Renderer::Unique { expression: Some(_), .. } => "the expression gives".to_string(), + Renderer::Unique { field, .. } => format!("of {field}"), + _ => String::new(), + }; + let order = if rest.by_number { "by number" } else { "in text order" }; let out = with(s, p, |l| { l.renderer = r; take_no_fill(l); })?; - if rest > 0 { + if rest.features > 0 { + let rest = rest.features; s.notify( format!( - "{name}: {rest} features whose value is past the first {keep} values the expression gives (in text order) are drawn as " + "{name}: {rest} features whose value is past the first {keep} values {values} ({order}) are drawn as " ), false, ); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index f03725d582..24f93332df 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -871,6 +871,116 @@ fn unique_values_by_expression_keep_their_classes_and_say_scales() { assert_eq!(kept.iter().map(|c| c.0.as_str()).collect::>(), ["overview"]); } +/// A layer of points read from GeoJSON, one for each value given, in that order: the integer +/// field `n` holds it, the text field `code` its digits, the text field `name` "h" and them. +fn numbered_points(values: &[i64]) -> Session { + let feats: Vec = values + .iter() + .enumerate() + .map(|(i, n)| { + json!({"type": "Feature", "geometry": {"type": "Point", "coordinates": [i as f64 * 0.1, 0.0]}, + "properties": {"n": n, "code": n.to_string(), "name": format!("h{n}")}}) + }) + .collect(); + let text = json!({"type": "FeatureCollection", "features": feats}).to_string(); + let (ds, _) = rustgis_data::io::read_geojson(&text, "Herds").unwrap(); + let ty = |f: &str| ds.fields[ds.field_index(f).unwrap()].ty; + assert_eq!( + (ty("n"), ty("code"), ty("name")), + (rustgis_data::FieldType::Integer, rustgis_data::FieldType::Text, rustgis_data::FieldType::Text) + ); + let mut s = Session::new(Project::default()); + let id = s.map_mut().add_dataset(ds); + s.active_layer = Some(id); + s +} + +fn herd_legend(s: &Session) -> Vec { + s.map().layer_by_name("Herds").unwrap().renderer.legend().into_iter().map(|e| e.label).collect() +} + +fn herd_classes(s: &Session) -> Vec { + match &s.map().layer_by_name("Herds").unwrap().renderer { + rustgis_map::Renderer::Unique { classes, .. } => classes.iter().map(|c| c.0.clone()).collect(), + r => panic!("{r:?}"), + } +} + +/// #1340: Unique Values on an integer field lists its classes and legend by number, as on a text +/// field holding only numbers; a text field of other text keeps text order. +#[test] +fn unique_values_on_a_number_field_are_in_numeric_order() { + let herds = [10153, 12490, 14443, 1741, 1910, 19947, 2723, 3076, 3672, 4060, 5985, 7636, 9081, 9627]; + let mut s = numbered_points(&herds); + let mut sorted = herds.to_vec(); + sorted.sort_unstable(); + let numbers: Vec = sorted.iter().map(i64::to_string).collect(); + let mut legend = numbers.clone(); + legend.push("".into()); + for field in ["n", "code"] { + let mark = s.notice_mark(); + s.run("layer.symbology", &json!({"layer": "Herds", "type": "unique", "field": field})).unwrap(); + assert_eq!(herd_classes(&s), numbers, "{field}"); + assert_eq!(herd_legend(&s), legend, "{field}"); + // Every value has a class: nothing to say. + assert!(!s.notices_since(mark).iter().any(|n| n.text.contains("past the first")), "{:?}", s.notices_since(mark)); + } + // A renamed class keeps its value's row. + s.run("layer.symbology", &json!({"layer": "Herds", "type": "unique", "field": "n"})).unwrap(); + s.run("layer.classStyle", &json!({"layer": "Herds", "value": "9627", "label": "Most"})).unwrap(); + let mut renamed = legend.clone(); + renamed[sorted.iter().position(|v| *v == 9627).unwrap()] = "Most".into(); + assert_eq!(herd_legend(&s), renamed); + // Text: text order. + s.run("layer.symbology", &json!({"layer": "Herds", "type": "unique", "field": "name"})).unwrap(); + let mut names: Vec = herds.iter().map(|n| format!("h{n}")).collect(); + names.sort(); + assert_eq!(herd_classes(&s), names); + names.push("".into()); + assert_eq!(herd_legend(&s), names); +} + +/// More values than Unique Values keeps: the first by number (or by text, for text) are classes, +/// and the features past them are said, with how many, whether classed by a field or an +/// expression. +#[test] +fn unique_values_on_a_field_say_what_is_past_their_classes() { + let max = rustgis_map::symbology::MAX_UNIQUE; + // 100 values, each on two features, in no order. + let values: Vec = (0..100).rev().chain(0..100).map(|i| i * 7).collect(); + let mut s = numbered_points(&values); + let past = 2 * (100 - max); + let first: Vec = (0..max as i64).map(|i| (i * 7).to_string()).collect(); + for field in ["n", "code"] { + let mark = s.notice_mark(); + s.run("layer.symbology", &json!({"layer": "Herds", "type": "unique", "field": field})).unwrap(); + assert_eq!(herd_classes(&s), first, "{field}"); + let said = format!( + "Herds: {past} features whose value is past the first {max} values of {field} (by number) are drawn as " + ); + assert!(s.notices_since(mark).iter().any(|n| n.text == said), "{said}\n{:?}", s.notices_since(mark)); + } + let mark = s.notice_mark(); + s.run("layer.symbology", &json!({"layer": "Herds", "type": "unique", "expression": "n"})).unwrap(); + assert_eq!(herd_classes(&s), first); + let said = format!("Herds: {past} features whose value is past the first {max} values the expression gives (by number)"); + assert!(s.notices_since(mark).iter().any(|n| n.text.starts_with(&said)), "{:?}", s.notices_since(mark)); + // Text: the first in text order. + let mark = s.notice_mark(); + s.run("layer.symbology", &json!({"layer": "Herds", "type": "unique", "field": "name"})).unwrap(); + let mut names: Vec = (0..100).map(|i| format!("h{}", i * 7)).collect(); + names.sort(); + assert_eq!(herd_classes(&s), names[..max]); + let said = format!("Herds: {past} features whose value is past the first {max} values of name (in text order)"); + assert!(s.notices_since(mark).iter().any(|n| n.text.starts_with(&said)), "{:?}", s.notices_since(mark)); + // A selection of fewer values says nothing. + let mark = s.notice_mark(); + s.run("layer.definitionQuery", &json!({"layer": "Herds", "where": "n < 300"})).unwrap(); + s.run("layer.symbology", &json!({"layer": "Herds", "type": "unique", "field": "n"})).unwrap(); + assert_eq!(herd_classes(&s).len(), 43); + assert!(!s.notices_since(mark).iter().any(|n| n.text.contains("past the first")), "{:?}", s.notices_since(mark)); +} + #[test] fn unique_values_class_by_an_expression() { let mut s = world(); @@ -926,7 +1036,8 @@ fn unique_values_class_by_an_expression() { let l = s.map().layer_by_name("Cities").unwrap(); let (_, rest) = rustgis_map::Renderer::unique_by_counted(&l.dataset, &[], "name", rustgis_map::Ramp::Harbour, l.renderer.base_symbol()).unwrap(); - assert!(rest > 0); + assert!(rest.features > 0 && !rest.by_number); + let rest = rest.features; let said = format!("Cities: {rest} features whose value is past the first {} values the expression gives", rustgis_map::symbology::MAX_UNIQUE); assert!(s.notices.iter().any(|n| n.text.starts_with(&said)), "{:?}", s.notices.last()); @@ -4450,7 +4561,10 @@ fn layer_class_style_edits_one_class() { } // A numeric value names its class as the data prints it, whether sent as an integer or not. s.run("layer.symbology", &json!({"layer": "Countries", "type": "unique", "field": "pop_est"})).unwrap(); - for v in [json!(211049527), json!(211049527.0)] { + // A whole value among the first classes (the smallest, as they're in numeric order). + let rustgis_map::Renderer::Unique { classes, .. } = renderer(&s) else { panic!("unique renderer expected") }; + let whole = classes.iter().find_map(|(k, _)| k.parse::().ok().filter(|n| *n > 1000)).unwrap(); + for v in [json!(whole), json!(whole as f64)] { let r = s.run("layer.classStyle", &json!({"layer": "Countries", "value": v, "label": "Brazil"})).unwrap(); assert_eq!(r["label"], "Brazil", "{v}"); } diff --git a/crates/map/src/symbology.rs b/crates/map/src/symbology.rs index d12b471c14..4d789167c9 100644 --- a/crates/map/src/symbology.rs +++ b/crates/map/src/symbology.rs @@ -3,6 +3,7 @@ use std::collections::BTreeMap; +use rustgis_data::value::PastClasses; use rustgis_data::{Dataset, FieldType, GeometryType}; use serde::{Deserialize, Serialize}; @@ -886,12 +887,19 @@ impl Renderer { /// Builds a unique-values renderer on `field`, from the rows `rows` keeps (a row past its end /// counts, so `&[]` keeps them all). pub fn unique(ds: &Dataset, rows: &[bool], field: &str, ramp: Ramp, base: Symbol) -> Result { + Self::unique_counted(ds, rows, field, ramp, base).map(|(r, _)| r) + } + + /// [`Renderer::unique`], and how many kept features with a geometry have a value past the + /// first [`MAX_UNIQUE`] (by number when every value reads as one, else by text), drawn as + /// ``. + pub fn unique_counted(ds: &Dataset, rows: &[bool], field: &str, ramp: Ramp, base: Symbol) -> Result<(Renderer, PastClasses), String> { let fi = ds.field_index(field).ok_or_else(|| format!("no field named '{field}'"))?; - let vals = ds.unique_values(fi, rows, MAX_UNIQUE); + let (vals, rest) = ds.unique_values_counted(fi, rows, MAX_UNIQUE); let n = vals.len(); let classes = vals.into_iter().enumerate().map(|(k, v)| (v, base.with_ramp_fill(ramp.pick(k, n), ds.geometry_type))).collect(); let other = base.with_ramp_fill(OTHER_FILL, ds.geometry_type); - Ok(Renderer::Unique { + let renderer = Renderer::Unique { field: ds.fields.get(fi).map(|f| f.name.clone()).unwrap_or_default(), classes, other, @@ -903,7 +911,8 @@ impl Renderer { class_fills: Default::default(), other_fills: Vec::new(), expression: None, - }) + }; + Ok((renderer, rest)) } /// Builds a Unique Values renderer classing by an expression's values over the rows `rows` @@ -916,8 +925,15 @@ impl Renderer { } /// [`Renderer::unique_by`], and how many kept features with a geometry have a value past the - /// first [`MAX_UNIQUE`] (in text order), drawn as ``. - pub fn unique_by_counted(ds: &Dataset, rows: &[bool], expression: &str, ramp: Ramp, base: Symbol) -> Result<(Renderer, usize), String> { + /// first [`MAX_UNIQUE`] (by number when every value reads as one, else by text), drawn as + /// ``. + pub fn unique_by_counted( + ds: &Dataset, + rows: &[bool], + expression: &str, + ramp: Ramp, + base: Symbol, + ) -> Result<(Renderer, PastClasses), String> { Self::unique_by_up_to(ds, rows, expression, ramp, base, MAX_UNIQUE) } @@ -930,7 +946,7 @@ impl Renderer { ramp: Ramp, base: Symbol, max: usize, - ) -> Result<(Renderer, usize), String> { + ) -> Result<(Renderer, PastClasses), String> { let max = max.clamp(1, MAX_EXPRESSION_CLASSES); let text = expression.trim(); if text.chars().count() > rustgis_data::query::MAX_LEN { @@ -938,11 +954,11 @@ impl Renderer { } let e = rustgis_data::query::parse(text, ds)?; let env = rustgis_data::query::Env::default(); - // The first values in order, never more than `max` kept, each with its features: one - // put out of the first can't come back (any later one is past the last kept), so its - // features and every later one past the last kept are counted as the rest. - let mut kept: BTreeMap = BTreeMap::new(); - let mut rest = 0usize; + // The first values by text, and while every value reads as a number, by number too: the + // order is known only once every feature is classed (`rustgis_data::value::numeric_classes`). + let mut by_text: FirstValues = FirstValues::new(max); + let mut by_number: FirstValues = FirstValues::new(max); + let mut text_seen = false; for r in (0..ds.features.len()).filter(|r| rows.get(*r).copied().unwrap_or(true)) { let v = match rustgis_data::query::value(&e, ds, r, &env) { rustgis_data::Value::Null => continue, @@ -951,16 +967,20 @@ impl Renderer { }; // (A feature without a geometry draws nothing, so it isn't counted.) let drawn = usize::from(ds.features.get(r).is_some_and(|f| f.geometry.is_some())); - if kept.len() >= max && kept.last_key_value().is_some_and(|(last, _)| v > *last) { - rest += drawn; - continue; - } - *kept.entry(v).or_insert(0) += drawn; - if kept.len() > max { - rest += kept.pop_last().map_or(0, |(_, n)| n); + text_seen = text_seen || rustgis_data::value::orders_as_text(&v); + if !text_seen { + by_number.add(NumericClass(v.clone()), drawn); } - } - let vals: Vec = kept.into_keys().collect(); + by_text.add(v, drawn); + } + // (Numbers come before the empty text and ``, so with any number, one is kept.) + let numeric = !text_seen && rustgis_data::value::numeric_classes(by_number.kept.keys().map(|k| k.0.as_str())); + let (vals, features): (Vec, usize) = if numeric { + (by_number.kept.into_keys().map(|k| k.0).collect(), by_number.rest) + } else { + (by_text.kept.into_keys().collect(), by_text.rest) + }; + let rest = PastClasses { features, by_number: numeric }; let n = vals.len(); let classes = vals.into_iter().enumerate().map(|(k, v)| (v, base.with_ramp_fill(ramp.pick(k, n), ds.geometry_type))).collect(); Ok(( @@ -1442,29 +1462,44 @@ impl Renderer { } } } - let mut v: Vec = classes - .iter() - .zip(&used) - .filter(|(_, u)| **u) - .map(|((k, s), _)| LegendEntry { label: unique_label(class_labels, k), symbol: *s, fallback: false }) + let mut v: Vec = self + .class_order() + .into_iter() + .filter(|i| used.get(*i).copied().unwrap_or(false)) + .filter_map(|i| classes.get(i)) + .map(|(k, s)| LegendEntry { label: unique_label(class_labels, k), symbol: *s, fallback: false }) .collect(); - v.sort_by_cached_key(|e| e.label.to_lowercase()); if other_used && visible { v.push(LegendEntry { label: other_label.clone().unwrap_or_else(|| OTHER_VALUES.into()), symbol: *other, fallback: true }); } v } - /// The order `legend()` lists the Unique Values classes in: their indices in `classes`, - /// sorted by label without regard to case (a stable sort, so a repeated value keeps its first - /// class first). Empty for the other renderers, whose legend follows their classes. + /// The order `legend()` lists the Unique Values classes in: their indices in `classes`, by + /// value when [`Renderer::classes_by_number`] (9 before 10, a class renamed by hand in its + /// value's place), else by label without regard to case. The sort is stable, so a repeated + /// value keeps its first class first. Empty for the other renderers, whose legend follows + /// their classes. pub fn class_order(&self) -> Vec { let Renderer::Unique { classes, class_labels, .. } = self else { return Vec::new() }; let mut order: Vec = (0..classes.len()).collect(); - order.sort_by_cached_key(|i| classes.get(*i).map(|(k, _)| unique_label(class_labels, k).to_lowercase())); + if self.classes_by_number() { + let value = |i: &usize| classes.get(*i).map_or("", |(k, _)| k.as_str()); + order.sort_by(|a, b| rustgis_data::value::cmp_numeric_classes(value(a), value(b))); + } else { + order.sort_by_cached_key(|i| classes.get(*i).map(|(k, _)| unique_label(class_labels, k).to_lowercase())); + } order } + /// Whether Unique Values' classes are ordered by number: when their values read as numbers + /// ([`rustgis_data::value::numeric_classes`]), as a numeric field's do. False for the other + /// renderers. + pub fn classes_by_number(&self) -> bool { + let Renderer::Unique { classes, .. } = self else { return false }; + rustgis_data::value::numeric_classes(classes.iter().map(|(k, _)| k.as_str())) + } + pub fn legend(&self) -> Vec { match self { Renderer::Single(_) => Vec::new(), @@ -1757,6 +1792,49 @@ pub fn normalize_label(t: &str) -> String { t.trim().chars().take(MAX_LABEL).collect::().trim_end().to_string() } +/// The first values in a map's order, never more than `max` kept, each with how many features +/// with a geometry have it, and how many have a value past them. A value put out of the first +/// can't come back (any later one is past the last kept), so its features and every later one +/// past the last kept are counted as the rest. +struct FirstValues { + kept: BTreeMap, + rest: usize, + max: usize, +} + +impl FirstValues { + fn new(max: usize) -> Self { + FirstValues { kept: BTreeMap::new(), rest: 0, max } + } + + fn add(&mut self, v: K, drawn: usize) { + if self.kept.len() >= self.max && self.kept.last_key_value().is_some_and(|(last, _)| v > *last) { + self.rest += drawn; + return; + } + *self.kept.entry(v).or_insert(0) += drawn; + if self.kept.len() > self.max { + self.rest += self.kept.pop_last().map_or(0, |(_, n)| n); + } + } +} + +/// A class value's text ordered as [`rustgis_data::value::cmp_numeric_classes`] has it. +#[derive(PartialEq, Eq)] +struct NumericClass(String); + +impl Ord for NumericClass { + fn cmp(&self, other: &Self) -> std::cmp::Ordering { + rustgis_data::value::cmp_numeric_classes(&self.0, &other.0) + } +} + +impl PartialOrd for NumericClass { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } +} + /// A Unique Values class's legend label: the one set by hand, or its value. fn unique_label(class_labels: &BTreeMap, value: &str) -> String { class_labels.get(value).cloned().unwrap_or_else(|| value.to_string()) @@ -3418,22 +3496,125 @@ mod tests { fn unique_values_by_an_expression_count_what_is_past_their_classes() { let base = Symbol::default_for(GeometryType::Point, 0); let mut d = Dataset::new("p", GeometryType::Point, vec![rustgis_data::Field::new("n", rustgis_data::FieldType::Integer)]); - // 100 values, each on two features, in no order: the first 64 (as text) are kept. + // 100 values, each on two features, in no order: the first 64 (by number) are kept. for i in (0..100i64).rev().chain(0..100) { d.push(Some(rustgis_data::Geometry::Point(rustgis_geom::Coord::new(0.0, 0.0))), vec![rustgis_data::Value::Int(i)]); } let (r, rest) = Renderer::unique_by_counted(&d, &[], "n", Ramp::Harbour, base).unwrap(); let Renderer::Unique { classes, .. } = &r else { panic!() }; - let mut all: Vec = (0..100).map(|i: i64| i.to_string()).collect(); + let all: Vec = (0..100).map(|i: i64| i.to_string()).collect(); + assert_eq!(classes.iter().map(|c| c.0.clone()).collect::>(), all[..MAX_UNIQUE]); + assert_eq!(rest, PastClasses { features: 2 * (100 - MAX_UNIQUE), by_number: true }); + // Text the expression makes of them is kept in text order. + let (r, rest) = Renderer::unique_by_counted(&d, &[], "'k' || n", Ramp::Harbour, base).unwrap(); + let Renderer::Unique { classes, .. } = &r else { panic!() }; + let mut all: Vec = (0..100).map(|i: i64| format!("k{i}")).collect(); all.sort(); assert_eq!(classes.iter().map(|c| c.0.clone()).collect::>(), all[..MAX_UNIQUE]); - assert_eq!(rest, 2 * (100 - MAX_UNIQUE)); + assert_eq!(rest, PastClasses { features: 2 * (100 - MAX_UNIQUE), by_number: false }); + // One text among the numbers, given last: the first are taken in text order, though every + // value before it read as a number, and though those kept are all numbers. + let (r, rest) = Renderer::unique_by_counted(&d, &[], "CASE WHEN n = 99 THEN 'x' ELSE n END", Ramp::Harbour, base).unwrap(); + let Renderer::Unique { classes, .. } = &r else { panic!() }; + let mut all: Vec = (0..99).map(|i: i64| i.to_string()).chain(["x".to_string()]).collect(); + all.sort(); + assert_eq!(classes.iter().map(|c| c.0.clone()).collect::>(), all[..MAX_UNIQUE]); + assert_eq!(rest, PastClasses { features: 2 * (100 - MAX_UNIQUE), by_number: false }); let (_, rest) = Renderer::unique_by_counted(&d, &[], "n % 10", Ramp::Harbour, base).unwrap(); - assert_eq!(rest, 0); + assert_eq!(rest, PastClasses { features: 0, by_number: true }); // A feature without a geometry draws nothing, so it isn't counted. d.push(None, vec![rustgis_data::Value::Int(99)]); let (_, rest) = Renderer::unique_by_counted(&d, &[], "n", Ramp::Harbour, base).unwrap(); - assert_eq!(rest, 2 * (100 - MAX_UNIQUE)); + assert_eq!(rest.features, 2 * (100 - MAX_UNIQUE)); + } + + /// #1340: Unique Values on a numeric field, by the field or by an expression, class and list + /// their values in numeric order; on a text field, in text order and by label, as before. + #[test] + fn unique_values_of_numbers_are_in_numeric_order() { + let point = || Some(rustgis_data::Geometry::Point(rustgis_geom::Coord::new(0.0, 0.0))); + let base = Symbol::default_for(GeometryType::Point, 0); + let fields = vec![Field::new("i", FieldType::Integer), Field::new("r", FieldType::Double), Field::new("t", FieldType::Text)]; + let mut d = Dataset::new("t", GeometryType::Point, fields); + for (i, r, t) in [(10153, 10.0, "b"), (1741, 2.5, "A"), (9627, -1.0, "10"), (9, 10.0, "9")] { + d.push(point(), vec![Value::Int(i), Value::Float(r), Value::Text(t.into())]); + } + let values = |r: &Renderer| match r { + Renderer::Unique { classes, .. } => classes.iter().map(|c| c.0.clone()).collect::>(), + _ => panic!("{r:?}"), + }; + let labels = |l: Vec| l.into_iter().map(|e| e.label).collect::>(); + for (by, expected) in [("i", ["9", "1741", "9627", "10153"]), ("r", ["-1", "2.5", "10", ""])] { + let expected: Vec<&str> = expected.into_iter().filter(|v| !v.is_empty()).collect(); + let by_field = Renderer::unique(&d, &[], by, Ramp::Harbour, base).unwrap(); + let by_expression = Renderer::unique_by(&d, &[], by, Ramp::Harbour, base).unwrap(); + for r in [&by_field, &by_expression] { + assert_eq!(values(r), expected, "{by}"); + assert!(r.classes_by_number()); + let mut legend = expected.clone(); + legend.push(OTHER_VALUES); + assert_eq!(labels(r.legend()), legend, "{by}"); + assert_eq!(labels(r.legend_for(&d, &[])), expected, "{by}: what is drawn"); + } + } + // A text field: text order, and the legend by label without regard to case. + let r = Renderer::unique(&d, &[], "t", Ramp::Harbour, base).unwrap(); + assert_eq!(values(&r), ["10", "9", "A", "b"]); + assert!(!r.classes_by_number()); + assert_eq!(labels(r.legend_for(&d, &[])), ["10", "9", "A", "b"]); + // Nulls are a class after the numbers. + d.push(point(), vec![Value::Null]); + let r = Renderer::unique(&d, &[], "i", Ramp::Harbour, base).unwrap(); + assert_eq!(values(&r), ["9", "1741", "9627", "10153", ""]); + assert_eq!(labels(r.legend_for(&d, &[])), ["9", "1741", "9627", "10153", ""]); + } + + /// A class of numbers renamed by hand keeps its value's place in the legend; classes saved in + /// text order (a project from before) are listed in numeric order too. + #[test] + fn a_renamed_number_class_keeps_its_place() { + let s = |c| Symbol::default_for(GeometryType::Polygon, c); + let mut r = unique(&[("10", s(0)), ("100", s(1)), ("9", s(2))], s(3), Ramp::Ember); + assert_eq!(r.class_order(), [2, 0, 1]); + let labels = |r: &Renderer| r.legend().into_iter().map(|e| e.label).collect::>(); + assert_eq!(labels(&r), ["9", "10", "100", OTHER_VALUES]); + let style = ClassStyle { label: Some("Arable".into()), ..Default::default() }; + r.set_class_style(&ClassRef::Value("100".into()), &style, GeometryType::Polygon).unwrap(); + assert_eq!(labels(&r), ["9", "10", "Arable", OTHER_VALUES]); + // Each row keeps its class's own symbol. + let fills: Vec = r.legend().iter().map(|e| e.symbol.fill).collect(); + assert_eq!(fills, [s(2).fill, s(0).fill, s(1).fill, s(3).fill]); + // A repeated value keeps its first class first. + let r = unique(&[("10", s(0)), ("9", s(1)), ("10", s(2))], s(3), Ramp::Ember); + assert_eq!(r.class_order(), [1, 0, 2]); + // With text among them, by label as before. + let r = unique(&[("10", s(0)), ("b", s(1)), ("9", s(2)), ("A", s(4))], s(3), Ramp::Ember); + assert_eq!(labels(&r), ["10", "9", "A", "b", OTHER_VALUES]); + } + + /// Past [`MAX_UNIQUE`] values, the classes are the smallest numbers and the features past + /// them are counted; with fewer, none are. + #[test] + fn unique_values_of_a_field_count_what_is_past_their_classes() { + let base = Symbol::default_for(GeometryType::Point, 0); + let mut d = Dataset::new("p", GeometryType::Point, vec![Field::new("n", FieldType::Integer)]); + for i in (0..100i64).rev().chain(0..100) { + d.push(Some(rustgis_data::Geometry::Point(rustgis_geom::Coord::new(0.0, 0.0))), vec![Value::Int(i)]); + } + let (r, rest) = Renderer::unique_counted(&d, &[], "n", Ramp::Harbour, base).unwrap(); + let Renderer::Unique { classes, .. } = &r else { panic!() }; + let first: Vec = (0..MAX_UNIQUE).map(|i| i.to_string()).collect(); + assert_eq!(classes.iter().map(|c| c.0.clone()).collect::>(), first); + assert_eq!(rest, PastClasses { features: 2 * (100 - MAX_UNIQUE), by_number: true }); + // The same as by the expression of the field. + assert_eq!(Renderer::unique_by_counted(&d, &[], "n", Ramp::Harbour, base).unwrap().1, rest); + // A feature without a geometry draws nothing, so it isn't counted. + d.push(None, vec![Value::Int(99)]); + assert_eq!(Renderer::unique_counted(&d, &[], "n", Ramp::Harbour, base).unwrap().1, rest); + let rows: Vec = (0..d.features.len()).map(|r| r < 100).collect(); + assert_eq!(Renderer::unique_counted(&d, &rows, "n", Ramp::Harbour, base).unwrap().1.features, 100 - MAX_UNIQUE); + let few: Vec = (0..d.features.len()).map(|r| r < MAX_UNIQUE).collect(); + assert_eq!(Renderer::unique_counted(&d, &few, "n", Ramp::Harbour, base).unwrap().1.features, 0); } /// The rest is in the legend when its stacked fills or strokes draw, though its own symbol @@ -3584,7 +3765,7 @@ mod tests { panic!("unique renderer expected") }; let keys: Vec<&str> = classes.iter().map(|(k, _)| k.as_str()).collect(); - assert_eq!(keys, vec!["1000", "2"]); + assert_eq!(keys, vec!["2", "1000"]); } fn unique(classes: &[(&str, Symbol)], other: Symbol, ramp: Ramp) -> Renderer { diff --git a/docs/user-guide/cartography.md b/docs/user-guide/cartography.md index 87de0d3d1b..6a60755001 100644 --- a/docs/user-guide/cartography.md +++ b/docs/user-guide/cartography.md @@ -12,7 +12,11 @@ Select a layer in Layers and open **Style › Symbology** (or the Symbology pane - **Single Symbol**: one fill, outline and marker for every feature. - **Unique Values**: one colour per distinct value of a field. If no field is chosen, the current renderer's field is kept when available; otherwise the first available field is used, including - text fields. The Layers pane and layout legends list only the + text fields. The classes and the legend are in numeric order when every value is a number + (9, 10, 100, as on a numeric field or a text field of codes), otherwise in text order; a class + renamed by hand keeps its value's place among numbers. There are up to 64 classes, the first in + that order; features with a value past them draw as ``, and a notice says how + many. The Layers pane and layout legends list only the classes that drawn features use (after the definition query and display filters); `` appears only when a drawn feature falls outside the classes and its symbol is not fully transparent. A layout legend can leave it out with **Hide other values** (see From 7770cc01c26e8da5d7a5391e84688ed5ad5d44fd Mon Sep 17 00:00:00 2001 From: PawelKra <15887575+PawelKra@users.noreply.github.com> Date: Tue, 3 Nov 2026 12:04:45 +0100 Subject: [PATCH 2/4] fix(style): compare whole class values by their digits, and sort only the first 64 Whole numbers went through i128, so values past its range fell back to f64 and tied, and i128::MAX tied with 2^127 through a saturating cast. A text of a sign and digits is now compared by its digits at any length. Against a decimal, the two are compared as f64 first; where those are equal, the decimal is written out in full and the digits compared. Each value is now read as a number once (value::ClassText) instead of on every comparison, and Dataset::unique_values_counted sets the first `limit` values apart with select_nth_unstable_by before sorting them. On 1,000,000 distinct integers this takes 304 ms, against 652 ms before and 158 ms for the old text sort. The user guide now describes the two orders separately. Classes are taken in numeric or in text order (by character) over every value. The legend lists the classes it has by number when they are all numbers, otherwise by label without regard to case. Two code comments that still said the legend is sorted by label now say what it does. --- crates/data/src/lib.rs | 18 ++- crates/data/src/value.rs | 267 +++++++++++++++++++++++++++------ crates/map/src/symbology.rs | 36 ++--- crates/ui-egui/src/panes.rs | 2 +- docs/user-guide/cartography.md | 13 +- 5 files changed, 256 insertions(+), 80 deletions(-) diff --git a/crates/data/src/lib.rs b/crates/data/src/lib.rs index 97f12615e4..c710c84df3 100644 --- a/crates/data/src/lib.rs +++ b/crates/data/src/lib.rs @@ -513,12 +513,20 @@ impl Dataset { let text = f.attrs.get(field).map(|x| x.to_string()).unwrap_or_default(); *drawn.entry(text).or_insert(0) += usize::from(f.geometry.is_some()); } - let mut v: Vec = drawn.keys().cloned().collect(); - let by_number = value::numeric_classes(v.iter().map(String::as_str)); - value::sort_class_values(&mut v); - let features = v.get(limit..).unwrap_or_default().iter().filter_map(|k| drawn.get(k)).sum(); + // Each value read as a number once, not on every comparison. + let mut v: Vec<(value::ClassText, usize)> = drawn.into_iter().map(|(t, n)| (value::ClassText::new(t), n)).collect(); + let by_number = value::ClassText::numeric(v.iter().map(|(t, _)| t)); + let order = |a: &(value::ClassText, usize), b: &(value::ClassText, usize)| { + if by_number { a.0.cmp(&b.0) } else { a.0.text().cmp(b.0.text()) } + }; + // Only the first `limit` need sorting: the rest are set apart in linear time. + if limit < v.len() { + v.select_nth_unstable_by(limit, order); + } + let features = v.get(limit..).unwrap_or_default().iter().map(|(_, n)| n).sum(); v.truncate(limit); - (v, value::PastClasses { features, by_number }) + v.sort_by(order); + (v.into_iter().map(|(t, _)| t.into_text()).collect(), value::PastClasses { features, by_number }) } } diff --git a/crates/data/src/value.rs b/crates/data/src/value.rs index 6efb274994..216d840968 100644 --- a/crates/data/src/value.rs +++ b/crates/data/src/value.rs @@ -137,73 +137,196 @@ impl PartialOrd for Value { } } -/// A Unique Values class's value, given as its text, read as a number: a whole number exactly -/// (past 2^53 too), any other as a decimal. -#[derive(Clone, Copy)] +/// A Unique Values class's value, given as its text, read as a number: a whole number (a sign, +/// then digits, of any length) by its digits, so exactly; any other as a decimal. +#[derive(Clone, Copy, Debug)] enum ClassNumber { - Whole(i128), + /// Below zero or not, and where its digits start in the text, past the sign and any leading + /// zeros (none left for 0). + Whole { + negative: bool, + start: usize, + }, Decimal(f64), } fn class_number(text: &str) -> Option { - match text.parse::() { - Ok(i) => Some(ClassNumber::Whole(i)), - Err(_) => text.parse::().ok().map(ClassNumber::Decimal), + let (negative, unsigned) = match text.strip_prefix('-') { + Some(rest) => (true, rest), + None => (false, text.strip_prefix('+').unwrap_or(text)), + }; + if !unsigned.is_empty() && unsigned.bytes().all(|b| b.is_ascii_digit()) { + let digits = unsigned.trim_start_matches('0'); + return Some(ClassNumber::Whole { negative: negative && !digits.is_empty(), start: text.len() - digits.len() }); } + text.parse::().ok().map(ClassNumber::Decimal) +} + +/// A whole number's sign and digits (past leading zeros) in `text`. +fn whole_digits(text: &str, negative: bool, start: usize) -> (bool, &str) { + (negative, text.get(start..).unwrap_or_default()) } -/// Orders two class numbers by value, exactly: NaN after every other number. -fn cmp_class_numbers(a: ClassNumber, b: ClassNumber) -> std::cmp::Ordering { +/// Orders two whole numbers given by their sign and digits (without leading zeros). +fn cmp_wholes((negative_a, a): (bool, &str), (negative_b, b): (bool, &str)) -> std::cmp::Ordering { use std::cmp::Ordering; - // A whole number against a decimal: as decimals, and where they're equal (as a whole number - // past 2^53 can be to the decimal it rounds to), exactly. A decimal equal to a whole - // number's is itself whole and within i128, so the cast is exact. - let whole_to_decimal = |i: i128, f: f64| match (i as f64).partial_cmp(&f) { - Some(Ordering::Equal) => i.cmp(&(f as i128)), - Some(o) => o, - None => Ordering::Less, - }; - match (a, b) { - (ClassNumber::Whole(x), ClassNumber::Whole(y)) => x.cmp(&y), - (ClassNumber::Whole(x), ClassNumber::Decimal(y)) => whole_to_decimal(x, y), - (ClassNumber::Decimal(x), ClassNumber::Whole(y)) => whole_to_decimal(y, x).reverse(), - (ClassNumber::Decimal(x), ClassNumber::Decimal(y)) => match (x.is_nan(), y.is_nan()) { - (false, false) => x.partial_cmp(&y).unwrap_or(Ordering::Equal), - (nan_x, nan_y) => nan_x.cmp(&nan_y), + let size = a.len().cmp(&b.len()).then_with(|| a.cmp(b)); + match (negative_a, negative_b) { + (false, false) => size, + (true, true) => size.reverse(), + (false, true) => Ordering::Greater, + (true, false) => Ordering::Less, + } +} + +/// Orders the whole number written `text` (its sign and digits `whole`) against the decimal `f`, +/// exactly: NaN after it. +fn cmp_whole_decimal(text: &str, whole: (bool, &str), f: f64) -> std::cmp::Ordering { + use std::cmp::Ordering; + if f.is_nan() { + return Ordering::Less; + } + if f.is_infinite() { + return if f > 0.0 { Ordering::Less } else { Ordering::Greater }; + } + // As decimals first: rounding keeps order, so where the whole number's decimal is above or + // below `f`, the whole number is too. + match text.parse::().ok().and_then(|w| w.partial_cmp(&f)) { + Some(Ordering::Equal) | None => {} + Some(o) => return o, + } + // Equal as decimals, `f` is a whole number (one a whole number rounds to): written out in + // full, its digits are compared exactly (2^53 + 1 against 2^53, i128::MAX against 2^127). + let full = format!("{f:.0}"); + match class_number(&full) { + Some(ClassNumber::Whole { negative, start }) => cmp_wholes(whole, whole_digits(&full, negative, start)), + _ => Ordering::Equal, + } +} + +/// Orders two class numbers, read from the texts `a` and `b`, by value: whole numbers exactly, +/// decimals as `f64`, NaN after every other number. Two decimals' texts that round to the same +/// `f64` compare equal here (and then by text in [`cmp_numeric_classes`]); a numeric field's never +/// do, as its display text reads back as the same `f64`, so only a text field of decimals past +/// 15 or so digits can be ordered by text. +fn cmp_class_numbers(a: &str, x: ClassNumber, b: &str, y: ClassNumber) -> std::cmp::Ordering { + use std::cmp::Ordering; + match (x, y) { + (ClassNumber::Whole { negative: na, start: sa }, ClassNumber::Whole { negative: nb, start: sb }) => { + cmp_wholes(whole_digits(a, na, sa), whole_digits(b, nb, sb)) + } + (ClassNumber::Whole { negative, start }, ClassNumber::Decimal(f)) => cmp_whole_decimal(a, whole_digits(a, negative, start), f), + (ClassNumber::Decimal(f), ClassNumber::Whole { negative, start }) => { + cmp_whole_decimal(b, whole_digits(b, negative, start), f).reverse() + } + (ClassNumber::Decimal(f), ClassNumber::Decimal(g)) => match (f.is_nan(), g.is_nan()) { + (false, false) => f.partial_cmp(&g).unwrap_or(Ordering::Equal), + (nan_f, nan_g) => nan_f.cmp(&nan_g), }, } } +/// Orders two class values, each a text and the number it reads as, as [`cmp_numeric_classes`]. +fn cmp_read_classes(a: &str, x: Option, b: &str, y: Option) -> std::cmp::Ordering { + use std::cmp::Ordering; + match (x, y) { + (Some(x), Some(y)) => cmp_class_numbers(a, x, b, y).then_with(|| a.cmp(b)), + (Some(_), None) => Ordering::Less, + (None, Some(_)) => Ordering::Greater, + (None, None) => a.cmp(b), + } +} + +/// Whether a value's text is a missing value's: the empty text or ``. +fn missing(text: &str) -> bool { + text.is_empty() || text == "" +} + /// Whether a class value's text keeps Unique Values classes from being ordered by number: text /// that reads as no number, other than the empty text and `` (a missing value's). pub fn orders_as_text(text: &str) -> bool { - !text.is_empty() && text != "" && class_number(text).is_none() + !missing(text) && class_number(text).is_none() } -/// Whether Unique Values classes with these values, given as their text, are ordered by number: -/// when one reads as a number and every other does too, or is the empty text or ``. A -/// numeric field's values always are; a text field's when it holds only numbers, such as codes. -pub fn numeric_classes<'a>(values: impl IntoIterator) -> bool { +/// [`numeric_classes`] over texts already read as numbers. +fn numeric_read<'a>(values: impl IntoIterator)>) -> bool { let mut number = false; - for v in values { - if orders_as_text(v) { + for (text, n) in values { + if missing(text) { + continue; + } + if n.is_none() { return false; } - number |= !v.is_empty() && v != ""; + number = true; } number } +/// Whether Unique Values classes with these values, given as their text, are ordered by number: +/// when one reads as a number and every other does too, or is the empty text or ``. A +/// numeric field's values always are; a text field's when it holds only numbers, such as codes. +pub fn numeric_classes<'a>(values: impl IntoIterator) -> bool { + numeric_read(values.into_iter().map(|v| (v, class_number(v)))) +} + /// Orders two Unique Values classes' values, given as their text, when [`numeric_classes`]: by /// number (9 before 10), then the rest (the empty text, ``) after them by text. Values equal /// in number are ordered by text (1 before 1.0), so this is a total order on texts. pub fn cmp_numeric_classes(a: &str, b: &str) -> std::cmp::Ordering { - use std::cmp::Ordering; - match (class_number(a), class_number(b)) { - (Some(x), Some(y)) => cmp_class_numbers(x, y).then_with(|| a.cmp(b)), - (Some(_), None) => Ordering::Less, - (None, Some(_)) => Ordering::Greater, - (None, None) => a.cmp(b), + cmp_read_classes(a, class_number(a), b, class_number(b)) +} + +/// A class value's text, read as a number once: ordered as [`cmp_numeric_classes`] orders texts, +/// without reading them again on every comparison. +#[derive(Clone, Debug)] +pub struct ClassText { + text: String, + number: Option, +} + +impl ClassText { + pub fn new(text: String) -> Self { + let number = class_number(&text); + ClassText { text, number } + } + + pub fn text(&self) -> &str { + &self.text + } + + pub fn into_text(self) -> String { + self.text + } + + /// [`orders_as_text`] for this value. + pub fn orders_as_text(&self) -> bool { + !missing(&self.text) && self.number.is_none() + } + + /// [`numeric_classes`] over these values. + pub fn numeric<'a>(values: impl IntoIterator) -> bool { + numeric_read(values.into_iter().map(|c| (c.text.as_str(), c.number))) + } +} + +impl PartialEq for ClassText { + fn eq(&self, other: &Self) -> bool { + self.text == other.text + } +} + +impl Eq for ClassText {} + +impl Ord for ClassText { + fn cmp(&self, other: &Self) -> std::cmp::Ordering { + cmp_read_classes(&self.text, self.number, &other.text, other.number) + } +} + +impl PartialOrd for ClassText { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) } } @@ -219,12 +342,14 @@ pub struct PastClasses { /// Sorts Unique Values classes' values, given as their text: by number when /// [`numeric_classes`], else by text. -pub fn sort_class_values(values: &mut [String]) { - if numeric_classes(values.iter().map(String::as_str)) { - values.sort_by(|a, b| cmp_numeric_classes(a, b)); +pub fn sort_class_values(values: &mut Vec) { + let mut read: Vec = std::mem::take(values).into_iter().map(ClassText::new).collect(); + if ClassText::numeric(&read) { + read.sort(); } else { - values.sort(); + read.sort_by(|a, b| a.text.cmp(&b.text)); } + values.extend(read.into_iter().map(ClassText::into_text)); } #[cfg(test)] @@ -278,6 +403,41 @@ mod tests { assert_eq!(cmp_numeric_classes("9007199254740993", "9007199254740992.5"), std::cmp::Ordering::Greater); } + /// Whole numbers of any length are ordered by their digits: past i128 too, and against a + /// decimal at i128's limit. + #[test] + fn whole_numbers_past_i128_are_ordered_exactly() { + let below_min = "-170141183460469231731687303715884105729"; + let further_below = "-170141183460469231731687303715884105730"; + assert_eq!(sorted(&[below_min, further_below]), [further_below, below_min]); + let past_max = "170141183460469231731687303715884105729"; + let further_past = "170141183460469231731687303715884105730"; + assert_eq!(sorted(&[further_past, past_max]), [past_max, further_past]); + // i128::MAX is below 2^127, which reads as one decimal with it. + let max = i128::MAX.to_string(); + assert_eq!(sorted(&["1.7014118346046923e38", &max]), [max.as_str(), "1.7014118346046923e38"]); + assert_eq!( + sorted(&["170141183460469231731687303715884105728.0", past_max]), + ["170141183460469231731687303715884105728.0", past_max] + ); + // Hundreds of digits: above every decimal but infinity. + let huge = format!("1{}", "0".repeat(400)); + let below_huge = format!("-{huge}"); + assert_eq!( + sorted(&["inf", &huge, "1e308", &below_huge, "-inf", "-1e308"]), + ["-inf", below_huge.as_str(), "-1e308", "1e308", huge.as_str(), "inf"] + ); + // A large float's display text is a whole number in full (its shortest digits, then + // zeros): neighbouring floats' texts are in the floats' order. + for v in [1e300, -1e300, 1.2345678901234568e20, 9.007199254740994e15] { + let (a, b) = (Value::Float(v).to_string(), Value::Float(v.next_up()).to_string()); + assert!(matches!(class_number(&a), Some(ClassNumber::Whole { .. })), "{a}"); + assert_eq!(cmp_numeric_classes(&a, &b), std::cmp::Ordering::Less, "{a} {b}"); + } + // Signs and leading zeros: one number, ordered by text. + assert_eq!(sorted(&["7", "007", "+7", "-0", "0", "-00", "+0"]), ["+0", "-0", "-00", "0", "+7", "007", "7"]); + } + #[test] fn numbers_equal_in_value_and_not_a_number_have_a_place() { // Equal in number: by text, so the order is total and repeatable. @@ -289,7 +449,28 @@ mod tests { #[test] fn the_numeric_order_is_total() { - let values = ["NaN", "-inf", "inf", "1", "1.0", "-0", "0", "9007199254740993", "9007199254740992.5", "2.5", "", ""]; + let values = [ + "NaN", + "-inf", + "inf", + "1", + "1.0", + "+1", + "01", + "-0", + "0", + "9007199254740993", + "9007199254740992.5", + "-9007199254740993", + "-9007199254740992.5", + "170141183460469231731687303715884105727", + "1.7014118346046923e38", + "170141183460469231731687303715884105729", + "-170141183460469231731687303715884105730", + "2.5", + "", + "", + ]; for a in values { assert_eq!(cmp_numeric_classes(a, a), std::cmp::Ordering::Equal, "{a}"); for b in values { diff --git a/crates/map/src/symbology.rs b/crates/map/src/symbology.rs index 4d789167c9..b095079c56 100644 --- a/crates/map/src/symbology.rs +++ b/crates/map/src/symbology.rs @@ -957,7 +957,7 @@ impl Renderer { // The first values by text, and while every value reads as a number, by number too: the // order is known only once every feature is classed (`rustgis_data::value::numeric_classes`). let mut by_text: FirstValues = FirstValues::new(max); - let mut by_number: FirstValues = FirstValues::new(max); + let mut by_number: FirstValues = FirstValues::new(max); let mut text_seen = false; for r in (0..ds.features.len()).filter(|r| rows.get(*r).copied().unwrap_or(true)) { let v = match rustgis_data::query::value(&e, ds, r, &env) { @@ -967,16 +967,18 @@ impl Renderer { }; // (A feature without a geometry draws nothing, so it isn't counted.) let drawn = usize::from(ds.features.get(r).is_some_and(|f| f.geometry.is_some())); - text_seen = text_seen || rustgis_data::value::orders_as_text(&v); + // Read as a number once. + let read = rustgis_data::value::ClassText::new(v); + text_seen = text_seen || read.orders_as_text(); if !text_seen { - by_number.add(NumericClass(v.clone()), drawn); + by_number.add(read.clone(), drawn); } - by_text.add(v, drawn); + by_text.add(read.into_text(), drawn); } // (Numbers come before the empty text and ``, so with any number, one is kept.) - let numeric = !text_seen && rustgis_data::value::numeric_classes(by_number.kept.keys().map(|k| k.0.as_str())); + let numeric = !text_seen && rustgis_data::value::ClassText::numeric(by_number.kept.keys()); let (vals, features): (Vec, usize) = if numeric { - (by_number.kept.into_keys().map(|k| k.0).collect(), by_number.rest) + (by_number.kept.into_keys().map(rustgis_data::value::ClassText::into_text).collect(), by_number.rest) } else { (by_text.kept.into_keys().collect(), by_text.rest) }; @@ -1484,8 +1486,8 @@ impl Renderer { let Renderer::Unique { classes, class_labels, .. } = self else { return Vec::new() }; let mut order: Vec = (0..classes.len()).collect(); if self.classes_by_number() { - let value = |i: &usize| classes.get(*i).map_or("", |(k, _)| k.as_str()); - order.sort_by(|a, b| rustgis_data::value::cmp_numeric_classes(value(a), value(b))); + // (Each value read as a number once; the sort is stable.) + order.sort_by_cached_key(|i| rustgis_data::value::ClassText::new(classes.get(*i).map(|(k, _)| k.clone()).unwrap_or_default())); } else { order.sort_by_cached_key(|i| classes.get(*i).map(|(k, _)| unique_label(class_labels, k).to_lowercase())); } @@ -1504,7 +1506,7 @@ impl Renderer { match self { Renderer::Single(_) => Vec::new(), Renderer::Unique { classes, other, class_labels, other_label, .. } => { - // Keep symbols attached to their sorted labels and the fallback at the end. + // Keep symbols attached to their classes in `class_order` and the fallback at the end. let mut v: Vec = self .class_order() .into_iter() @@ -1819,22 +1821,6 @@ impl FirstValues { } } -/// A class value's text ordered as [`rustgis_data::value::cmp_numeric_classes`] has it. -#[derive(PartialEq, Eq)] -struct NumericClass(String); - -impl Ord for NumericClass { - fn cmp(&self, other: &Self) -> std::cmp::Ordering { - rustgis_data::value::cmp_numeric_classes(&self.0, &other.0) - } -} - -impl PartialOrd for NumericClass { - fn partial_cmp(&self, other: &Self) -> Option { - Some(self.cmp(other)) - } -} - /// A Unique Values class's legend label: the one set by hand, or its value. fn unique_label(class_labels: &BTreeMap, value: &str) -> String { class_labels.get(value).cloned().unwrap_or_else(|| value.to_string()) diff --git a/crates/ui-egui/src/panes.rs b/crates/ui-egui/src/panes.rs index c03209f01d..e33b08c35c 100644 --- a/crates/ui-egui/src/panes.rs +++ b/crates/ui-egui/src/panes.rs @@ -4547,7 +4547,7 @@ fn legend_list(app: &mut RustGisApp, ui: &mut Ui, l: &Layer, t: &Tokens) { |ui| { ui.set_width(ui.available_width()); let legend = l.renderer.legend(); - // Unique Values legends sort their classes by label: row i shows class `order[i]`, + // Unique Values legends sort their classes (by value or by label): row i shows class `order[i]`, // and the rows past them (``) keep their place. let order = l.renderer.class_order(); // At most MAX_UNIQUE classes (a style import can bring more), then Unique Values' diff --git a/docs/user-guide/cartography.md b/docs/user-guide/cartography.md index 6a60755001..900211869e 100644 --- a/docs/user-guide/cartography.md +++ b/docs/user-guide/cartography.md @@ -12,12 +12,13 @@ Select a layer in Layers and open **Style › Symbology** (or the Symbology pane - **Single Symbol**: one fill, outline and marker for every feature. - **Unique Values**: one colour per distinct value of a field. If no field is chosen, the current renderer's field is kept when available; otherwise the first available field is used, including - text fields. The classes and the legend are in numeric order when every value is a number - (9, 10, 100, as on a numeric field or a text field of codes), otherwise in text order; a class - renamed by hand keeps its value's place among numbers. There are up to 64 classes, the first in - that order; features with a value past them draw as ``, and a notice says how - many. The Layers pane and layout legends list only the - classes that drawn features use (after the definition query and display filters); + text fields. There are up to 64 classes: the first values in numeric order when every value is + a number (9, 10, 100, as on a numeric field or a text field of codes), otherwise in text order + (by character, so `B` before `a`). Features with a value past them draw as + ``, and a notice says how many and in which order the classes were taken. The + legend lists the classes by number when every class is a number, a class renamed by hand in its + value's place, and otherwise by label without regard to case. The Layers pane and layout + legends list only the classes that drawn features use (after the definition query and display filters); `` appears only when a drawn feature falls outside the classes and its symbol is not fully transparent. A layout legend can leave it out with **Hide other values** (see [Layouts](layouts.md)). Instead of a field, Unique Values can class by an From 77ce93cce5a7d9a859b56c17d9fadc393b8a23cc Mon Sep 17 00:00:00 2001 From: PawelKra <15887575+PawelKra@users.noreply.github.com> Date: Tue, 3 Nov 2026 12:27:23 +0100 Subject: [PATCH 3/4] fix(style): compare class values exactly as written, and say what Subtypes cut A whole number against a decimal that reads as the same f64 fell to the text tiebreak, so -9007199254740991.9 sorted before -9007199254740992, and two decimals that read as one f64 did the same. Class values no longer go through f64 to be compared. Each text Rust reads as a decimal is kept as its significant digits and the place of its point, and two numbers compare by sign, point and digits: whole numbers, decimals and exponents alike, at any length. f64 still decides what is a number, and reads the words inf and NaN. data.subtypes draws the layer by Unique Values of the subtype field and cut it at 64 values without a word. It now gives the same notice as layer.symbology, with the number of features drawn as . --- crates/data/src/value.rs | 194 ++++++++++++++++++++------------ crates/engine/src/cmd/design.rs | 18 ++- crates/engine/src/tests.rs | 32 ++++++ 3 files changed, 173 insertions(+), 71 deletions(-) diff --git a/crates/data/src/value.rs b/crates/data/src/value.rs index 216d840968..a0fbe609d9 100644 --- a/crates/data/src/value.rs +++ b/crates/data/src/value.rs @@ -137,92 +137,117 @@ impl PartialOrd for Value { } } -/// A Unique Values class's value, given as its text, read as a number: a whole number (a sign, -/// then digits, of any length) by its digits, so exactly; any other as a decimal. +/// A Unique Values class's value, given as its text, read as a number exactly as written: any +/// text Rust reads as a decimal (`9`, `-2.5`, `1e300`, `.5`, past 2^53 or i128), kept as its +/// significant digits and the place of its point rather than rounded to an `f64`; or one of the +/// words a decimal can be (infinity, NaN). #[derive(Clone, Copy, Debug)] enum ClassNumber { - /// Below zero or not, and where its digits start in the text, past the sign and any leading - /// zeros (none left for 0). - Whole { + /// `0.d…d × 10^point`: below zero or not, where its significant digits start and end in the + /// text (a point between them is skipped when they're read; none for zero), and `point`. + Finite { negative: bool, start: usize, + end: usize, + point: i64, }, - Decimal(f64), + Infinite { + negative: bool, + }, + NaN, } +/// The largest exponent kept, so sums with it can't overflow: an exponent past it (past 2^61, as +/// no value's display text has, only a text typed so) is taken as it, and numbers with two such +/// exponents of one sign are ordered by their digits. +const MAX_EXPONENT: i64 = i64::MAX / 4; + fn class_number(text: &str) -> Option { - let (negative, unsigned) = match text.strip_prefix('-') { + // Only what Rust reads as a decimal is a number. + let f = text.parse::().ok()?; + let (negative, body) = match text.strip_prefix('-') { Some(rest) => (true, rest), None => (false, text.strip_prefix('+').unwrap_or(text)), }; - if !unsigned.is_empty() && unsigned.bytes().all(|b| b.is_ascii_digit()) { - let digits = unsigned.trim_start_matches('0'); - return Some(ClassNumber::Whole { negative: negative && !digits.is_empty(), start: text.len() - digits.len() }); - } - text.parse::().ok().map(ClassNumber::Decimal) -} - -/// A whole number's sign and digits (past leading zeros) in `text`. -fn whole_digits(text: &str, negative: bool, start: usize) -> (bool, &str) { - (negative, text.get(start..).unwrap_or_default()) -} - -/// Orders two whole numbers given by their sign and digits (without leading zeros). -fn cmp_wholes((negative_a, a): (bool, &str), (negative_b, b): (bool, &str)) -> std::cmp::Ordering { - use std::cmp::Ordering; - let size = a.len().cmp(&b.len()).then_with(|| a.cmp(b)); - match (negative_a, negative_b) { - (false, false) => size, - (true, true) => size.reverse(), - (false, true) => Ordering::Greater, - (true, false) => Ordering::Less, - } + let offset = text.len() - body.len(); + let (mantissa, exponent) = match body.find(['e', 'E']) { + Some(i) => (body.get(..i).unwrap_or_default(), body.get(i + 1..).unwrap_or_default()), + None => (body, ""), + }; + if !mantissa.bytes().all(|b| b.is_ascii_digit() || b == b'.') { + // A word: inf, infinity or NaN. + return Some(if f.is_nan() { ClassNumber::NaN } else { ClassNumber::Infinite { negative: f < 0.0 } }); + } + // (Rust read the text, so an exponent given has digits: one that doesn't parse is too large.) + let size = |digits: &str| digits.parse::().unwrap_or(MAX_EXPONENT).min(MAX_EXPONENT); + let exponent = match exponent.strip_prefix('-') { + _ if exponent.is_empty() => 0, + Some(digits) => -size(digits), + None => size(exponent.strip_prefix('+').unwrap_or(exponent)), + }; + let dot = mantissa.find('.').unwrap_or(mantissa.len()); + let significant = |b: &u8| b.is_ascii_digit() && *b != b'0'; + let (Some(first), Some(last)) = (mantissa.bytes().position(|b| significant(&b)), mantissa.bytes().rposition(|b| significant(&b))) + else { + return Some(ClassNumber::Finite { negative: false, start: offset, end: offset, point: 0 }); + }; + // Digits from the first significant one to the point, or minus the zeros between them. + let point = if first < dot { (dot - first) as i64 } else { -((first - dot - 1) as i64) }; + Some(ClassNumber::Finite { negative, start: offset + first, end: offset + last + 1, point: point.saturating_add(exponent) }) } -/// Orders the whole number written `text` (its sign and digits `whole`) against the decimal `f`, -/// exactly: NaN after it. -fn cmp_whole_decimal(text: &str, whole: (bool, &str), f: f64) -> std::cmp::Ordering { - use std::cmp::Ordering; - if f.is_nan() { - return Ordering::Less; - } - if f.is_infinite() { - return if f > 0.0 { Ordering::Less } else { Ordering::Greater }; - } - // As decimals first: rounding keeps order, so where the whole number's decimal is above or - // below `f`, the whole number is too. - match text.parse::().ok().and_then(|w| w.partial_cmp(&f)) { - Some(Ordering::Equal) | None => {} - Some(o) => return o, - } - // Equal as decimals, `f` is a whole number (one a whole number rounds to): written out in - // full, its digits are compared exactly (2^53 + 1 against 2^53, i128::MAX against 2^127). - let full = format!("{f:.0}"); - match class_number(&full) { - Some(ClassNumber::Whole { negative, start }) => cmp_wholes(whole, whole_digits(&full, negative, start)), - _ => Ordering::Equal, - } +/// The significant digits of a number between `start` and `end` in `text`, past any point. +fn significant_digits(text: &str, start: usize, end: usize) -> impl Iterator + '_ { + text.get(start..end).unwrap_or_default().bytes().filter(|b| *b != b'.') } -/// Orders two class numbers, read from the texts `a` and `b`, by value: whole numbers exactly, -/// decimals as `f64`, NaN after every other number. Two decimals' texts that round to the same -/// `f64` compare equal here (and then by text in [`cmp_numeric_classes`]); a numeric field's never -/// do, as its display text reads back as the same `f64`, so only a text field of decimals past -/// 15 or so digits can be ordered by text. +/// Orders two class numbers, read from the texts `a` and `b`, exactly by value: NaN after every +/// other number. Numbers equal in value (`1`, `1.0`, `1e0`) compare equal here, and then by text +/// in [`cmp_numeric_classes`]. fn cmp_class_numbers(a: &str, x: ClassNumber, b: &str, y: ClassNumber) -> std::cmp::Ordering { use std::cmp::Ordering; + // -1, 0 or 1, and for a finite number other than 0, its size against another of its sign. + let sign = |n: ClassNumber| match n { + ClassNumber::Finite { start, end, .. } if start == end => 0, + ClassNumber::Finite { negative, .. } | ClassNumber::Infinite { negative } => { + if negative { + -1 + } else { + 1 + } + } + ClassNumber::NaN => 2, + }; match (x, y) { - (ClassNumber::Whole { negative: na, start: sa }, ClassNumber::Whole { negative: nb, start: sb }) => { - cmp_wholes(whole_digits(a, na, sa), whole_digits(b, nb, sb)) + (ClassNumber::NaN, ClassNumber::NaN) => Ordering::Equal, + (ClassNumber::NaN, _) => Ordering::Greater, + (_, ClassNumber::NaN) => Ordering::Less, + (ClassNumber::Infinite { negative: n }, ClassNumber::Infinite { negative: m }) => m.cmp(&n), + (ClassNumber::Infinite { negative }, _) => { + if negative { + Ordering::Less + } else { + Ordering::Greater + } + } + (_, ClassNumber::Infinite { negative }) => { + if negative { + Ordering::Greater + } else { + Ordering::Less + } } - (ClassNumber::Whole { negative, start }, ClassNumber::Decimal(f)) => cmp_whole_decimal(a, whole_digits(a, negative, start), f), - (ClassNumber::Decimal(f), ClassNumber::Whole { negative, start }) => { - cmp_whole_decimal(b, whole_digits(b, negative, start), f).reverse() + (ClassNumber::Finite { negative, start: sa, end: ea, point: pa }, ClassNumber::Finite { start: sb, end: eb, point: pb, .. }) => { + sign(x).cmp(&sign(y)).then_with(|| { + if sign(x) == 0 { + return Ordering::Equal; + } + // The same sign: the larger size has its point further on, or the same and larger + // digits (shorter ones as if ended with zeros). + let size = pa.cmp(&pb).then_with(|| significant_digits(a, sa, ea).cmp(significant_digits(b, sb, eb))); + if negative { size.reverse() } else { size } + }) } - (ClassNumber::Decimal(f), ClassNumber::Decimal(g)) => match (f.is_nan(), g.is_nan()) { - (false, false) => f.partial_cmp(&g).unwrap_or(Ordering::Equal), - (nan_f, nan_g) => nan_f.cmp(&nan_g), - }, } } @@ -413,9 +438,13 @@ mod tests { let past_max = "170141183460469231731687303715884105729"; let further_past = "170141183460469231731687303715884105730"; assert_eq!(sorted(&[further_past, past_max]), [past_max, further_past]); - // i128::MAX is below 2^127, which reads as one decimal with it. + // i128::MAX against decimals that read as one f64 with it (2^127): by what is written. let max = i128::MAX.to_string(); - assert_eq!(sorted(&["1.7014118346046923e38", &max]), [max.as_str(), "1.7014118346046923e38"]); + assert_eq!(sorted(&["1.7014118346046923e38", &max]), ["1.7014118346046923e38", max.as_str()]); + assert_eq!( + sorted(&["170141183460469231731687303715884105728.0", &max]), + [max.as_str(), "170141183460469231731687303715884105728.0"] + ); assert_eq!( sorted(&["170141183460469231731687303715884105728.0", past_max]), ["170141183460469231731687303715884105728.0", past_max] @@ -431,13 +460,33 @@ mod tests { // zeros): neighbouring floats' texts are in the floats' order. for v in [1e300, -1e300, 1.2345678901234568e20, 9.007199254740994e15] { let (a, b) = (Value::Float(v).to_string(), Value::Float(v.next_up()).to_string()); - assert!(matches!(class_number(&a), Some(ClassNumber::Whole { .. })), "{a}"); + assert!(!a.contains(['.', 'e']), "{a}"); assert_eq!(cmp_numeric_classes(&a, &b), std::cmp::Ordering::Less, "{a} {b}"); } // Signs and leading zeros: one number, ordered by text. assert_eq!(sorted(&["7", "007", "+7", "-0", "0", "-00", "+0"]), ["+0", "-0", "-00", "0", "+7", "007", "7"]); } + /// Decimals are ordered by what is written, not by the f64 they read as: two that read as + /// one f64, a decimal against a whole number it rounds to, and exponents. + #[test] + fn decimals_are_ordered_exactly_as_written() { + assert_eq!(sorted(&["10000000000000000.5", "9999999999999999.9"]), ["9999999999999999.9", "10000000000000000.5"]); + assert_eq!(cmp_numeric_classes("-9007199254740992", "-9007199254740991.9"), std::cmp::Ordering::Less); + assert_eq!(cmp_numeric_classes("9007199254740992", "9007199254740992.1"), std::cmp::Ordering::Less); + assert_eq!(sorted(&["0.30000000000000001", "0.3", "0.29999999999999999"]), ["0.29999999999999999", "0.3", "0.30000000000000001"]); + // One value written five ways: equal, then by text. + assert_eq!(sorted(&["1e2", "100", "100.0", "0.1e3", "+1E+2"]), ["+1E+2", "0.1e3", "100", "100.0", "1e2"]); + // Small and large exponents, and ones past what an i64 holds. + let tiny = format!("1e-{}", "9".repeat(30)); + let huge = format!("1e{}", "9".repeat(30)); + assert_eq!( + sorted(&[&huge, "1e400", "0", &tiny, "1e-400", "-1e-400", ".5", "5."]), + ["-1e-400", "0", tiny.as_str(), "1e-400", ".5", "5.", "1e400", huge.as_str()] + ); + assert_eq!(sorted(&["-0.0", "0e5", "-0", "0.000"]), ["-0", "-0.0", "0.000", "0e5"], "zeros are one value"); + } + #[test] fn numbers_equal_in_value_and_not_a_number_have_a_place() { // Equal in number: by text, so the order is total and repeatable. @@ -467,6 +516,13 @@ mod tests { "1.7014118346046923e38", "170141183460469231731687303715884105729", "-170141183460469231731687303715884105730", + "10000000000000000.5", + "9999999999999999.9", + "-9007199254740991.9", + "1e2", + "0.1e3", + "1e-400", + "-1e-400", "2.5", "", "", diff --git a/crates/engine/src/cmd/design.rs b/crates/engine/src/cmd/design.rs index a4a5f16342..9dde438715 100644 --- a/crates/engine/src/cmd/design.rs +++ b/crates/engine/src/cmd/design.rs @@ -818,12 +818,26 @@ fn subtypes(s: &mut Session, p: &Json) -> CmdResult { let symbolize = b(p, "symbolize").unwrap_or(true); let l = s.map_mut().layer_mut(id).ok_or("no such layer")?; // Unique values by subtype code. + let mut past = rustgis_data::value::PastClasses::default(); if symbolize { let base = l.renderer.base_symbol(); - l.renderer = rustgis_map::Renderer::unique(&l.dataset, &[], &fname, rustgis_map::Ramp::default(), base)?; + let (r, rest) = rustgis_map::Renderer::unique_counted(&l.dataset, &[], &fname, rustgis_map::Ramp::default(), base)?; + l.renderer = r; + past = rest; } let n = subs.len(); - l.design.subtypes = Some(Subtypes { field: fname, subtypes: subs }); + let name = l.name.clone(); + l.design.subtypes = Some(Subtypes { field: fname.clone(), subtypes: subs }); + if past.features > 0 { + let (max, order) = (rustgis_map::symbology::MAX_UNIQUE, if past.by_number { "by number" } else { "in text order" }); + s.notify( + format!( + "{name}: {} features whose value is past the first {max} values of {fname} ({order}) are drawn as ", + past.features + ), + false, + ); + } Ok(json!({"subtypes": n})) } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 24f93332df..6a32252b79 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -981,6 +981,38 @@ fn unique_values_on_a_field_say_what_is_past_their_classes() { assert!(!s.notices_since(mark).iter().any(|n| n.text.contains("past the first")), "{:?}", s.notices_since(mark)); } +/// Subtypes draw the layer by Unique Values of the subtype field: past 64 values, the features +/// drawn as are said too. +#[test] +fn subtypes_say_what_is_past_their_classes() { + let max = rustgis_map::symbology::MAX_UNIQUE; + let subtypes = json!([{"code": 0, "name": "None"}, {"code": 7, "name": "Seven"}]); + let past = |s: &Session, mark| { + s.notices_since(mark).iter().filter(|n| n.text.contains("past the first")).map(|n| n.text.clone()).collect::>() + }; + // 100 values, each on two features. + let values: Vec = (0..100).rev().chain(0..100).map(|i| i * 7).collect(); + let mut s = numbered_points(&values); + let mark = s.notice_mark(); + s.run("data.subtypes", &json!({"layer": "Herds", "field": "n", "subtypes": subtypes})).unwrap(); + let first: Vec = (0..max as i64).map(|i| (i * 7).to_string()).collect(); + assert_eq!(herd_classes(&s), first); + let said = format!( + "Herds: {} features whose value is past the first {max} values of n (by number) are drawn as ", + 2 * (100 - max) + ); + assert_eq!(past(&s, mark), [said]); + // Not drawn by them, or with fewer values: nothing to say. + let mark = s.notice_mark(); + s.run("data.subtypes", &json!({"layer": "Herds", "field": "n", "subtypes": subtypes, "symbolize": false})).unwrap(); + assert!(past(&s, mark).is_empty()); + let mut s = numbered_points(&[0, 7, 14, 7]); + let mark = s.notice_mark(); + s.run("data.subtypes", &json!({"layer": "Herds", "field": "n", "subtypes": subtypes})).unwrap(); + assert_eq!(herd_classes(&s), ["0", "7", "14"]); + assert!(past(&s, mark).is_empty()); +} + #[test] fn unique_values_class_by_an_expression() { let mut s = world(); From fc4b6d2796a27388c08c4d4810975284e5263d61 Mon Sep 17 00:00:00 2001 From: PawelKra <15887575+PawelKra@users.noreply.github.com> Date: Tue, 3 Nov 2026 13:05:02 +0100 Subject: [PATCH 4/4] fix(style): read only a float's words as numbers, and count Subtypes' cut among drawn features Rust's float parser accepts inf, infinity and nan in any case, so a text value such as Nan (a name) or Infinity read as a number and could put a text field in numeric order. Only the words a float's display text writes (NaN, inf, -inf) are numbers now; the others stay text. data.subtypes counted every feature past the first 64 values, including those a definition query hides, which aren't drawn. The classes still come from every feature, so the query drops none, but the notice now counts only the drawn features with a value that is none of them. --- crates/data/src/value.rs | 27 +++++++++++++++++++++++++-- crates/engine/src/cmd/design.rs | 22 ++++++++++++++++++++-- crates/engine/src/tests.rs | 16 ++++++++++++++++ 3 files changed, 61 insertions(+), 4 deletions(-) diff --git a/crates/data/src/value.rs b/crates/data/src/value.rs index a0fbe609d9..9d062d3fa8 100644 --- a/crates/data/src/value.rs +++ b/crates/data/src/value.rs @@ -175,8 +175,13 @@ fn class_number(text: &str) -> Option { None => (body, ""), }; if !mantissa.bytes().all(|b| b.is_ascii_digit() || b == b'.') { - // A word: inf, infinity or NaN. - return Some(if f.is_nan() { ClassNumber::NaN } else { ClassNumber::Infinite { negative: f < 0.0 } }); + // A word: a number only as a float's display text writes it (`inf`, `-inf`, `NaN`), so a + // text value such as `Nan` (a name) or `Infinity` stays text. + return match text { + "NaN" => Some(ClassNumber::NaN), + "inf" | "-inf" => Some(ClassNumber::Infinite { negative: f < 0.0 }), + _ => None, + }; } // (Rust read the text, so an exponent given has digits: one that doesn't parse is too large.) let size = |digits: &str| digits.parse::().unwrap_or(MAX_EXPONENT).min(MAX_EXPONENT); @@ -487,6 +492,24 @@ mod tests { assert_eq!(sorted(&["-0.0", "0e5", "-0", "0.000"]), ["-0", "-0.0", "0.000", "0e5"], "zeros are one value"); } + /// Words are numbers only as a float's display text writes them: `Nan` (a name) and + /// `Infinity` are text, and keep text order. + #[test] + fn only_a_floats_words_are_numbers() { + for word in ["Nan", "nan", "NAN", "Inf", "INF", "infinity", "Infinity", "+inf", "-Infinity"] { + assert!(orders_as_text(word), "{word}"); + let mut text_order = vec![word, "10", "9"]; + text_order.sort(); + assert_eq!(sorted(&[word, "10", "9"]), text_order, "{word}"); + } + for word in ["NaN", "inf", "-inf"] { + assert!(!orders_as_text(word), "{word}"); + } + assert_eq!(sorted(&["NaN", "10", "-inf", "9", "inf"]), ["-inf", "9", "10", "inf", "NaN"]); + let shown: Vec = [f64::NAN, f64::INFINITY, f64::NEG_INFINITY].iter().map(|f| Value::Float(*f).to_string()).collect(); + assert_eq!(shown, ["NaN", "inf", "-inf"], "as a float field's values are written"); + } + #[test] fn numbers_equal_in_value_and_not_a_number_have_a_place() { // Equal in number: by text, so the order is total and repeatable. diff --git a/crates/engine/src/cmd/design.rs b/crates/engine/src/cmd/design.rs index 9dde438715..a6dea36096 100644 --- a/crates/engine/src/cmd/design.rs +++ b/crates/engine/src/cmd/design.rs @@ -2,6 +2,7 @@ //! Relationships, and Edit › Manage Edits, Snapping, Features (modify tools), Elevation and //! Corrections. Every feature edit goes through [`apply`], which enforces the layer's design. +use rustgis_data::value::PastClasses; use rustgis_data::{Feature, FieldType, Geometry, GeometryType, Value}; use rustgis_geom::{Coord, lonlat_to_merc, merc_to_lonlat}; use rustgis_map::design::{ @@ -818,12 +819,15 @@ fn subtypes(s: &mut Session, p: &Json) -> CmdResult { let symbolize = b(p, "symbolize").unwrap_or(true); let l = s.map_mut().layer_mut(id).ok_or("no such layer")?; // Unique values by subtype code. - let mut past = rustgis_data::value::PastClasses::default(); + let mut past = PastClasses::default(); if symbolize { let base = l.renderer.base_symbol(); + // The classes come from every feature, so a definition query doesn't drop any; the + // features past them are counted among those it lets through, which are drawn. let (r, rest) = rustgis_map::Renderer::unique_counted(&l.dataset, &[], &fname, rustgis_map::Ramp::default(), base)?; + let rows = l.visible_rows(); + past = PastClasses { features: drawn_past(&l.dataset, &r, &fname, &rows), ..rest }; l.renderer = r; - past = rest; } let n = subs.len(); let name = l.name.clone(); @@ -841,6 +845,20 @@ fn subtypes(s: &mut Session, p: &Json) -> CmdResult { Ok(json!({"subtypes": n})) } +/// How many features `rows` keeps, with a geometry, have a value of `field` that is none of the +/// Unique Values `renderer`'s classes: those drawn as ``. +fn drawn_past(ds: &rustgis_data::Dataset, renderer: &rustgis_map::Renderer, field: &str, rows: &[bool]) -> usize { + let (rustgis_map::Renderer::Unique { classes, .. }, Some(fi)) = (renderer, ds.field_index(field)) else { return 0 }; + let classes: std::collections::HashSet<&str> = classes.iter().map(|(k, _)| k.as_str()).collect(); + ds.features + .iter() + .enumerate() + .filter(|(r, f)| rows.get(*r).copied().unwrap_or(true) && f.geometry.is_some()) + // (Each value's text as `Dataset::unique_values` writes it, a missing one empty.) + .filter(|(_, f)| !classes.contains(f.attrs.get(fi).map(|v| v.to_string()).unwrap_or_default().as_str())) + .count() +} + fn attribute_rule(s: &mut Session, p: &Json) -> CmdResult { let id = s.layer_id(p)?; let name = ps(p, "name").map(str::trim).filter(|n| !n.is_empty()).ok_or("name is required")?.to_string(); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 6a32252b79..74d369793c 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -1002,6 +1002,22 @@ fn subtypes_say_what_is_past_their_classes() { 2 * (100 - max) ); assert_eq!(past(&s, mark), [said]); + // Only the features a definition query lets through are drawn, so only they are counted; + // the classes still come from every feature. + s.run("layer.definitionQuery", &json!({"layer": "Herds", "where": "n >= 600"})).unwrap(); + let mark = s.notice_mark(); + s.run("data.subtypes", &json!({"layer": "Herds", "field": "n", "subtypes": subtypes})).unwrap(); + assert_eq!(herd_classes(&s), first, "classes from every feature"); + let said = format!( + "Herds: {} features whose value is past the first {max} values of n (by number) are drawn as ", + 2 * (100 - 600 / 7 - 1) + ); + assert_eq!(past(&s, mark), [said]); + s.run("layer.definitionQuery", &json!({"layer": "Herds", "where": "n < 300"})).unwrap(); + let mark = s.notice_mark(); + s.run("data.subtypes", &json!({"layer": "Herds", "field": "n", "subtypes": subtypes})).unwrap(); + assert!(past(&s, mark).is_empty(), "every drawn feature has a class"); + s.run("layer.definitionQuery", &json!({"layer": "Herds", "where": ""})).unwrap(); // Not drawn by them, or with fewer values: nothing to say. let mark = s.notice_mark(); s.run("data.subtypes", &json!({"layer": "Herds", "field": "n", "subtypes": subtypes, "symbolize": false})).unwrap();