Skip to content
Merged
88 changes: 9 additions & 79 deletions crates/analysis/src/stats.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ use std::cell::OnceCell;
use std::cmp::Ordering;
use std::collections::HashMap;

pub(crate) use rustgis_data::value::cmp_number;
use rustgis_data::value::cmp_values;
use rustgis_data::{Dataset, FieldType, Value};
use serde_json::Value as Json;

Expand Down Expand Up @@ -253,85 +255,13 @@ pub fn group_rows(ds: &Dataset, rows: &[usize], keys: &[usize]) -> Vec<Group> {
groups
}

/// Orders group keys value by value: nulls, then numbers (true and false as 1 and 0) by value,
/// Orders group keys value by value ([`cmp_values`]): nulls, then numbers (true and false as 1 and 0) by value,
/// then dates and date-times by instant (and then by their text), then text by its lower case and
/// then by character code. Numbers equal in value are ordered by
/// kind (1 before 1.0). This is a total order, whatever mix of kinds a field holds (text that reads
/// as a number is still text), so the order never depends on the records'.
fn cmp_keys(a: &[Value], b: &[Value]) -> Ordering {
a.iter().zip(b).map(|(x, y)| cmp_key(x, y)).find(|o| o.is_ne()).unwrap_or(Ordering::Equal)
}

/// Orders two group key values (see [`cmp_keys`]).
fn cmp_key(x: &Value, y: &Value) -> Ordering {
/// A number's kind, the tie-break between equal values: true/false, then whole, then decimal.
fn kind(v: &Value) -> u8 {
match v {
Value::Bool(_) => 0,
Value::Int(_) => 1,
_ => 2,
}
}
let rank = |v: &Value| match v {
Value::Null => 0,
Value::Date(_) | Value::DateTime(_) => 2,
Value::Text(_) => 3,
_ => 1,
};
rank(x).cmp(&rank(y)).then_with(|| match (x, y) {
(Value::Date(_) | Value::DateTime(_), _) => x.temporal_key().cmp(&y.temporal_key()).then_with(|| x.to_string().cmp(&y.to_string())),
(Value::Text(a), Value::Text(b)) => {
a.chars().flat_map(char::to_lowercase).cmp(b.chars().flat_map(char::to_lowercase)).then_with(|| a.cmp(b))
}
(Value::Null, Value::Null) => Ordering::Equal,
_ => cmp_number(x, y).then_with(|| kind(x).cmp(&kind(y))),
})
}

/// Orders two numbers (true and false as 1 and 0) by value, exactly: a whole number against a
/// decimal without rounding it to f64. Every NaN is one value, above all others; −0 is 0.
pub(crate) fn cmp_number(x: &Value, y: &Value) -> Ordering {
/// A number as a whole number or a decimal.
enum N {
I(i64),
F(f64),
}
let n = |v: &Value| match v {
Value::Bool(b) => N::I(i64::from(*b)),
Value::Int(i) => N::I(*i),
Value::Float(f) if f.is_nan() => N::F(f64::NAN),
Value::Float(f) => N::F(f + 0.0),
Value::Null | Value::Text(_) | Value::Date(_) | Value::DateTime(_) => N::F(f64::NAN),
};
match (n(x), n(y)) {
(N::I(a), N::I(b)) => a.cmp(&b),
(N::F(a), N::F(b)) => a.total_cmp(&b),
(N::I(a), N::F(b)) => cmp_int_float(a, b),
(N::F(a), N::I(b)) => cmp_int_float(b, a).reverse(),
}
}

/// Orders a whole number against a decimal exactly; NaN is above every number.
fn cmp_int_float(i: i64, f: f64) -> Ordering {
// 2^63: no i64 reaches it, every i64 is at least its negative.
const TWO_63: f64 = 9_223_372_036_854_775_808.0;
if f.is_nan() || f >= TWO_63 {
return Ordering::Less;
}
if f < -TWO_63 {
return Ordering::Greater;
}
let t = f.trunc();
// In range, so the truncated decimal is a whole number an i64 holds exactly.
i.cmp(&(t as i64)).then_with(|| {
if f > t {
Ordering::Less
} else if f < t {
Ordering::Greater
} else {
Ordering::Equal
}
})
a.iter().zip(b).map(|(x, y)| cmp_values(x, y)).find(|o| o.is_ne()).unwrap_or(Ordering::Equal)
}

/// One field's values within a group, without its nulls, in record order.
Expand Down Expand Up @@ -1258,14 +1188,14 @@ mod tests {
// Whole numbers and decimals compare exactly past 2^53, and NaNs of either sign are one
// group, after the numbers.
let big = (1i64 << 53) + 1;
assert_eq!(cmp_key(&Value::Int(big), &Value::Float(9_007_199_254_740_992.0)), Ordering::Greater);
assert_eq!(cmp_values(&Value::Int(big), &Value::Float(9_007_199_254_740_992.0)), Ordering::Greater);
let mixed_big = table(&[(Value::Int(big), ""), (Value::Float(9_007_199_254_740_992.0), "")]);
let order: Vec<Vec<Value>> = group_rows(&mixed_big, &[0, 1], &[0]).into_iter().map(|g| g.key).collect();
assert_eq!(order, vec![vec![Value::Float(9_007_199_254_740_992.0)], vec![Value::Int(big)]]);
assert_eq!(cmp_key(&Value::Int(i64::MAX), &Value::Float(9.3e18)), Ordering::Less);
assert_eq!(cmp_key(&Value::Int(i64::MIN), &Value::Float(f64::NEG_INFINITY)), Ordering::Greater);
assert_eq!(cmp_key(&Value::Int(3), &Value::Float(3.5)), Ordering::Less);
assert_eq!(cmp_key(&Value::Int(-3), &Value::Float(-3.5)), Ordering::Greater);
assert_eq!(cmp_values(&Value::Int(i64::MAX), &Value::Float(9.3e18)), Ordering::Less);
assert_eq!(cmp_values(&Value::Int(i64::MIN), &Value::Float(f64::NEG_INFINITY)), Ordering::Greater);
assert_eq!(cmp_values(&Value::Int(3), &Value::Float(3.5)), Ordering::Less);
assert_eq!(cmp_values(&Value::Int(-3), &Value::Float(-3.5)), Ordering::Greater);
let nans = table(&[(Value::Float(-f64::NAN), ""), (Value::Float(f64::INFINITY), ""), (Value::Float(f64::NAN), "")]);
let keys: Vec<Vec<Value>> = group_rows(&nans, &[0, 1, 2], &[0]).into_iter().map(|g| g.key).collect();
assert_eq!(keys.len(), 2);
Expand Down
79 changes: 79 additions & 0 deletions crates/data/src/value.rs
Original file line number Diff line number Diff line change
Expand Up @@ -407,6 +407,85 @@ impl PartialOrd for Value {
}
}

/// Orders any two values: nulls, then numbers (true and false as 1 and 0) by value, then dates and
/// date-times by instant (and then by their text), then text by its lower case and then by
/// character code. Numbers equal in value are ordered by kind (1 before 1.0). This is a total
/// order, whatever mix of kinds a field holds (text that reads as a number is still text), so an
/// order made with it never depends on how the values came. [`PartialOrd`] isn't one: it reads
/// text as a number beside a number, and compares a number that isn't finite as its text.
pub fn cmp_values(x: &Value, y: &Value) -> std::cmp::Ordering {
use std::cmp::Ordering;
/// A number's kind, the tie-break between equal values: true/false, then whole, then decimal.
fn kind(v: &Value) -> u8 {
match v {
Value::Bool(_) => 0,
Value::Int(_) => 1,
_ => 2,
}
}
let rank = |v: &Value| match v {
Value::Null => 0,
Value::Date(_) | Value::DateTime(_) => 2,
Value::Text(_) => 3,
_ => 1,
};
rank(x).cmp(&rank(y)).then_with(|| match (x, y) {
(Value::Date(_) | Value::DateTime(_), _) => x.temporal_key().cmp(&y.temporal_key()).then_with(|| x.to_string().cmp(&y.to_string())),
(Value::Text(a), Value::Text(b)) => {
a.chars().flat_map(char::to_lowercase).cmp(b.chars().flat_map(char::to_lowercase)).then_with(|| a.cmp(b))
}
(Value::Null, Value::Null) => Ordering::Equal,
_ => cmp_number(x, y).then_with(|| kind(x).cmp(&kind(y))),
})
}

/// Orders two numbers (true and false as 1 and 0) by value, exactly: a whole number against a
/// decimal without rounding it to f64. Every NaN is one value, above all others; −0 is 0.
pub fn cmp_number(x: &Value, y: &Value) -> std::cmp::Ordering {
/// A number as a whole number or a decimal.
enum N {
I(i64),
F(f64),
}
let n = |v: &Value| match v {
Value::Bool(b) => N::I(i64::from(*b)),
Value::Int(i) => N::I(*i),
Value::Float(f) if f.is_nan() => N::F(f64::NAN),
Value::Float(f) => N::F(f + 0.0),
Value::Null | Value::Text(_) | Value::Date(_) | Value::DateTime(_) => N::F(f64::NAN),
};
match (n(x), n(y)) {
(N::I(a), N::I(b)) => a.cmp(&b),
(N::F(a), N::F(b)) => a.total_cmp(&b),
(N::I(a), N::F(b)) => cmp_int_float(a, b),
(N::F(a), N::I(b)) => cmp_int_float(b, a).reverse(),
}
}

/// Orders a whole number against a decimal exactly; NaN is above every number.
fn cmp_int_float(i: i64, f: f64) -> std::cmp::Ordering {
use std::cmp::Ordering;
// 2^63: no i64 reaches it, every i64 is at least its negative.
const TWO_63: f64 = 9_223_372_036_854_775_808.0;
if f.is_nan() || f >= TWO_63 {
return Ordering::Less;
}
if f < -TWO_63 {
return Ordering::Greater;
}
let t = f.trunc();
// In range, so the truncated decimal is a whole number an i64 holds exactly.
i.cmp(&(t as i64)).then_with(|| {
if f > t {
Ordering::Less
} else if f < t {
Ordering::Greater
} else {
Ordering::Equal
}
})
}

/// `i` against `f` exactly, without rounding `i` to the nearest f64: unknown for NaN.
fn int_cmp_f64(i: i64, f: f64) -> Option<std::cmp::Ordering> {
use std::cmp::Ordering;
Expand Down
4 changes: 2 additions & 2 deletions crates/engine/command-surface.txt
Original file line number Diff line number Diff line change
Expand Up @@ -284,7 +284,7 @@ layer.transparency layer? value
layer.visibility layer? visible?
layer.zoomTo layer?
layout.activate name layout
layout.addElement layout? kind frame? of? text? size? color? bold? italic? align? letterSpacing? rotation? wrap? valign? lineSpacing? case? font? fallback? title? subtitle? allClasses? hideOther? showNoData? exclude? layerOrder? columnBreaks? columns? textSize? classLabels? sizes? showCounts? showLayerNames? orientation? ticks? tickSide? reverse? fill? width? radius? dash? dir? head? angle? length? image? path? layer? field? label? group? statistic? order? bars? other? stack? values? decimals? barColor? classes? labelAlign? mirror? max? hideLabels? barOutline? rows? fields? header? step? type? crs? short? mgrs? labels? style? tickLength? format? hemisphere? edges? labelOrientation? labelSize? off? name? direction? at? section? band? side? gap? thickness? unit? lineColor? lineWidth? min? guides? outline? units? divisions? subdivisions? divisionsBeforeZero? labelPosition? unitLabel? unitLabelPosition? fit? x? y? w? h? background?
layout.addElement layout? kind frame? of? text? size? color? bold? italic? align? letterSpacing? rotation? wrap? valign? lineSpacing? case? font? fallback? title? subtitle? allClasses? hideOther? showNoData? exclude? layerOrder? columnBreaks? columns? textSize? classLabels? sizes? showCounts? showLayerNames? orientation? ticks? tickSide? reverse? fill? width? radius? dash? dir? head? angle? length? image? path? layer? field? label? group? statistic? order? bars? other? stack? values? decimals? barColor? classes? labelAlign? mirror? max? hideLabels? barOutline? rows? fields? header? sort? descending? selectedOnly? step? type? crs? short? mgrs? labels? style? tickLength? format? hemisphere? edges? labelOrientation? labelSize? off? name? direction? at? section? band? side? gap? thickness? unit? lineColor? lineWidth? min? guides? outline? units? divisions? subdivisions? divisionsBeforeZero? labelPosition? unitLabel? unitLabelPosition? fit? x? y? w? h? background?
layout.addFrame layout? shape? points? map? x? y? w? h?
layout.arrange layout? element to
layout.arrangement favourite? save? arrangement? remove?
Expand All @@ -306,7 +306,7 @@ layout.save layout? path
layout.series layout? layer nameField? frame? margin? off?
layout.seriesPage layout? page
layout.seriesRefresh layout?
layout.update layout? element x? y? w? h? name? visible? locked? text? size? color? bold? italic? align? letterSpacing? rotation? wrap? valign? lineSpacing? case? font? fallback? title? subtitle? allClasses? hideOther? showNoData? exclude? layerOrder? columnBreaks? labels? classLabels? columns? textSize? showLayerNames? sizes? showCounts? orientation? ticks? tickSide? reverse? style? fill? outline? radius? width? dash? dir? head? angle? length? units? divisions? subdivisions? divisionsBeforeZero? labelPosition? unitLabel? unitLabelPosition? fit? map? scale? center? bearing? pitch? grid? extentIndicator? extentNumbers? border? section? layer? field? label? group? statistic? order? bars? other? stack? values? decimals? barColor? classes? labelAlign? mirror? max? band? side? gap? thickness? unit? lineColor? lineWidth? min? guides? barOutline? hideLabels? rows? fields? header? image? path? background?
layout.update layout? element x? y? w? h? name? visible? locked? text? size? color? bold? italic? align? letterSpacing? rotation? wrap? valign? lineSpacing? case? font? fallback? title? subtitle? allClasses? hideOther? showNoData? exclude? layerOrder? columnBreaks? labels? classLabels? columns? textSize? showLayerNames? sizes? showCounts? orientation? ticks? tickSide? reverse? style? fill? outline? radius? width? dash? dir? head? angle? length? units? divisions? subdivisions? divisionsBeforeZero? labelPosition? unitLabel? unitLabelPosition? fit? map? scale? center? bearing? pitch? grid? extentIndicator? extentNumbers? border? section? layer? field? label? group? statistic? order? bars? other? stack? values? decimals? barColor? classes? labelAlign? mirror? max? band? side? gap? thickness? unit? lineColor? lineWidth? min? guides? barOutline? hideLabels? rows? fields? header? sort? descending? selectedOnly? image? path? background?
locator.find locator? text limit? zoom?
map.activate name
map.addTiles url kind? name? bounds? attribution? minZoom? maxZoom? tileSize? singleImage? tms? subdomains? layers? styleLayers? opacity? blend? resampling? overlay? top? replace? id? view? start? end? unit? interval? dates? legend? connection? anonymous?
Expand Down
5 changes: 5 additions & 0 deletions crates/engine/src/cmd/layout.rs
Original file line number Diff line number Diff line change
Expand Up @@ -261,6 +261,9 @@ pub fn commands() -> Vec<C> {
r##""rows"?, "##,
r##""fields"?: [field names] (table: its columns, in this order; default [], every field in the layer's order), "##,
r##""header"?: bool (table: the row of field names; default true), "##,
r##""sort"?: field (table: its rows ordered by this field, empty values first, numbers by value, dates by instant, text ignoring case; default none, the layer's order), "##,
r##""descending"?: bool (table: the largest value of "sort" first; default false), "##,
r##""selectedOnly"?: bool (table: only the layer's selected features, none selected leaving it without rows; default false), "##,
r##""step"?: degrees, or a measured grid's units (metres) (0 picks one), "##,
r##""type"?: "graticule" (latitudes and longitudes, default) | "measured" (eastings and northings in a projected system), "##,
r##""crs"?: a measured grid's coordinate system: EPSG:25832, WKT or a PROJ string ("" or none: the map's when projected, else the UTM zone at the frame's centre), "##,
Expand Down Expand Up @@ -406,6 +409,8 @@ pub fn commands() -> Vec<C> {
r##""rows"?, "##,
r##""fields"?: [field names] (table, as in layout.addElement, of the layer it will show, plus any the table already shows of that layer and it has lost, spelled the same; [] returns to every field, null leaves them; another "layer" without them drops them), "##,
r##""header"?: bool (table, as in layout.addElement; null leaves it as it is), "##,
r##""sort"?: field|null (table, as in layout.addElement, of the layer it will show; null returns to the layer's order; another "layer" without it drops it), "##,
r##""descending"?: bool, "selectedOnly"?: bool (table, as in layout.addElement; null leaves each as it is), "##,
r##""image"?: base64 (picture: its new image, its file no longer remembered, which is said when it had one), "##,
r##""path"?: a PNG or JPEG file (picture: read again, its image replacing the one it has, and remembered as its file; a file missing, over 16 MB, not a PNG or JPEG, or one that can't be drawn is refused and the picture left as it was; image and path together are refused; refused in the browser, which has no file paths: give its image; null leaves each as it is; refused for other elements), "##,
r##""background"?: {"fill"?, "outline"?, "width"?, "radius"?, "padding"?, as in layout.addElement, the keys not given keeping theirs} | null (removes it); a map frame takes none}"##,
Expand Down
Loading
Loading