Skip to content
Merged
123 changes: 114 additions & 9 deletions crates/analysis/src/tools.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2838,7 +2838,8 @@ fn symmetrical_difference(inp: &dyn Inputs, p: &Json) -> Result<ToolResult, Stri
/// typing it into the field would, so text that isn't a number becomes empty in a numeric field.
/// A number becomes text at full precision, and a fractional one an integer by truncation; one
/// beyond an integer field's range, or not finite, becomes empty. Text becomes a Boolean as typing
/// it would: true for true, yes, 1 or y, else false.
/// it would ([`Value::yes_no`]): text that isn't one of its words is empty (so is the text `2`),
/// and a number, not text, that is whole is yes when it isn't 0.
fn converted(v: &Value, ty: FieldType) -> Value {
match (v, ty) {
(Value::Int(_), FieldType::Integer)
Expand All @@ -2859,6 +2860,11 @@ fn converted(v: &Value, ty: FieldType) -> Value {
(Value::Float(_), FieldType::Integer) => Value::Null,
(Value::Float(f), FieldType::Text) => Value::Text(f.to_string()),
(Value::Bool(b), FieldType::Integer) => Value::Int(i64::from(*b)),
// A whole number is yes when it isn't 0, as a shapefile writes it.
(Value::Int(i), FieldType::Boolean) => Value::Bool(*i != 0),
Comment thread
Mavrick-F marked this conversation as resolved.
Resolved
(Value::Float(f), FieldType::Boolean) if f.fract() == 0.0 => Value::Bool(*f != 0.0),
// A fraction is no yes/no value: null, not the text it's shown as (`0.0000001` shows `0`).
(Value::Float(_), FieldType::Boolean) => Value::Null,
(Value::Bool(b), FieldType::Double) => Value::Float(if *b { 1.0 } else { 0.0 }),
// Text that reads as an integer is one; text that reads as another number goes as that
// float would, so one out of range (or not a number) is empty, not clamped.
Expand Down Expand Up @@ -2922,9 +2928,9 @@ fn update_on(inp: &dyn Inputs, p: &Json, threads: Option<usize>) -> Result<ToolR
}
}
let kept = out.features.len();
// For each input field, how many update values its type couldn't hold, written as null, and
// how many date-times a date field kept only the day of.
let mut unfit = vec![(0usize, 0usize); ds.fields.len()];
// For each input field, how many update values its type couldn't hold, written as null, how
// many date-times a date field kept only the day of, and how many numbers it cut or rounded.
let mut unfit = vec![Unfit::default(); ds.fields.len()];
crate::control::begin(zones.len());
for (done, z) in zones.iter().enumerate() {
crate::control::check()?;
Expand All @@ -2935,12 +2941,10 @@ fn update_on(inp: &dyn Inputs, p: &Json, threads: Option<usize>) -> Result<ToolR
.iter()
.zip(&from)
.zip(&mut unfit)
.map(|((f, i), (n, days))| {
.map(|((f, i), unfit)| {
let Some(v) = i.and_then(|i| u.attrs.get(i)) else { return Value::Null };
let c = converted(v, f.ty);
// Empty or `<null>` text asks for null: no loss.
*n += usize::from(c.is_null() && !v.asks_null());
*days += usize::from(matches!(v, Value::DateTime(t) if f.ty == FieldType::Date && !t.is_date()));
unfit.add(v, &c, f.ty);
c
})
.collect();
Expand All @@ -2951,7 +2955,9 @@ fn update_on(inp: &dyn Inputs, p: &Json, threads: Option<usize>) -> Result<ToolR
let mut losses: Vec<rustgis_data::loss::LossMessage> = Vec::new();
messages.extend(left_out.notes("Update", &up.name));
let features = |n: usize| if n == 1 { "1 update feature".to_string() } else { format!("{n} update features") };
for (f, (n, days)) in ds.fields.iter().zip(unfit) {
// The cuts and roundings are said one notice per kind, naming their fields.
let (mut cut, mut round): (Vec<(&str, usize)>, Vec<(&str, usize)>) = (Vec::new(), Vec::new());
for (f, Unfit { nulls: n, days, fractions, rounded }) in ds.fields.iter().zip(unfit) {
if n > 0 {
losses.push(rustgis_data::loss::LossMessage {
code: rustgis_data::loss::LossCode::DroppedValue,
Expand All @@ -2965,10 +2971,68 @@ fn update_on(inp: &dyn Inputs, p: &Json, threads: Option<usize>) -> Result<ToolR
text: format!("Update: '{}' holds dates, so {} kept only {their} day", f.name, features(days)),
});
}
if fractions > 0 {
Comment thread
Mavrick-F marked this conversation as resolved.
Resolved
cut.push((&f.name, fractions));
}
if rounded > 0 {
round.push((&f.name, rounded));
}
}
let named = |fields: &[(&str, usize)]| {
let total: usize = fields.iter().map(|(_, n)| n).sum();
let values = if total == 1 { "1 update value".to_string() } else { format!("{total} update values") };
let (its, was) = if total == 1 { ("its", "was") } else { ("their", "were") };
(values, its, was, fields.iter().map(|(f, _)| format!("'{f}'")).collect::<Vec<_>>().join(", "))
};
if !cut.is_empty() {
let (values, its, _, fields) = named(&cut);
losses.push(rustgis_data::loss::LossMessage {
code: rustgis_data::loss::LossCode::ChangedTruncated,
text: format!("Update: {values} lost {its} fraction in fields that hold whole numbers: {fields}"),
});
}
if !round.is_empty() {
let (values, _, was, fields) = named(&round);
losses.push(rustgis_data::loss::LossMessage {
code: rustgis_data::loss::LossCode::ChangedRounded,
text: format!("Update: {values} {was} rounded to the digits a decimal holds, in {fields}"),
});
}
Ok(ToolResult { losses, output: Output::Layer(out), messages })
}

/// What [`converted`] lost of one input field's update values, counted for one notice per kind.
#[derive(Clone, Copy, Debug, Default)]
struct Unfit {
/// Values its type couldn't hold, written as null.
nulls: usize,
/// Date-times a date field kept only the day of.
days: usize,
/// Numbers with a fraction a whole-number field cut.
fractions: usize,
/// Numbers a decimal field rounded: whole numbers past 2^53, and text with more digits than it holds.
rounded: usize,
}

impl Unfit {
/// Counts what converting `v` to `c` in a `ty` field lost.
fn add(&mut self, v: &Value, c: &Value, ty: FieldType) {
// Empty or `<null>` text asks for null: no loss.
self.nulls += usize::from(c.is_null() && !v.asks_null());
self.days += usize::from(matches!(v, Value::DateTime(t) if ty == FieldType::Date && !t.is_date()));
// Text is read from its digits, which a decimal can round away: `2.0000000000000001` has a
// fraction, `2.000` hasn't.
let fraction = matches!(c, Value::Int(_))
&& match v {
Value::Float(f) => f.fract() != 0.0,
Value::Text(t) => Value::text_has_fraction(t),
_ => false,
};
self.fractions += usize::from(fraction);
self.rounded += usize::from(ty == FieldType::Double && matches!(c, Value::Float(_)) && v.rounds_as_double());
}
}

/// The most split areas (split polygons, or values of the split field) Split takes: more is an
/// error before anything is clipped, not thousands of layers. Areas that come out empty count too.
const MAX_SPLIT_AREAS: usize = 1000;
Expand Down Expand Up @@ -14543,6 +14607,41 @@ mod tests {
);
}

#[test]
fn update_says_the_fractions_it_cuts_the_numbers_it_rounds_and_the_words_that_arent_yes_or_no() {
let fields = vec![Field::new("n", FieldType::Integer), Field::new("x", FieldType::Double), Field::new("b", FieldType::Boolean)];
let mut parcels = Dataset::new("parcels", GeometryType::Polygon, fields);
parcels.push(Some(sq(0.0, 0.0, 1.0)), vec![Value::Null, Value::Null, Value::Null]);
let fields = vec![Field::new("n", FieldType::Double), Field::new("x", FieldType::Integer), Field::new("b", FieldType::Text)];
let mut zones = Dataset::new("zones", GeometryType::Polygon, fields);
let m = |zones: &Dataset| Map(HashMap::from([("parcels".to_string(), parcels.clone()), ("zones".to_string(), zones.clone())]));
let run = |zones: &Dataset| crate::run("update", &m(zones), &serde_json::json!({"input": "parcels", "update": "zones"})).unwrap();
// Whole numbers, numbers a decimal holds, and yes/no words lose nothing.
zones.push(Some(sq(5.0, 0.0, 1.0)), vec![Value::Float(2.0), Value::Int(1 << 53), Value::Text(" No ".into())]);
assert_eq!(said(&run(&zones))[1..], [] as [&str; 0]);
zones.push(Some(sq(7.0, 0.0, 1.0)), vec![Value::Float(-2.7), Value::Int((1 << 53) + 1), Value::Text("maybe".into())]);
let lossy = [
"DroppedValue: Update: 'b' is null in 1 update feature, whose value isn't a Boolean value",
"ChangedTruncated: Update: 1 update value lost its fraction in fields that hold whole numbers: 'n'",
"ChangedRounded: Update: 1 update value was rounded to the digits a decimal holds, in 'x'",
];
let res = run(&zones);
assert_eq!(said(&res)[1..], lossy);
let out = layer(res);
let last = out.features.last().unwrap();
assert_eq!(last.attrs, [Value::Int(-2), Value::Float(9_007_199_254_740_992.0), Value::Null]);
// Written as text, the same.
let fields = vec![Field::new("n", FieldType::Text), Field::new("x", FieldType::Text), Field::new("b", FieldType::Text)];
let mut zones = Dataset::new("zones", GeometryType::Polygon, fields);
zones.push(Some(sq(5.0, 0.0, 1.0)), vec![Value::Text("2.000".into()), Value::Text("1e3".into()), Value::Text("yes".into())]);
assert_eq!(said(&run(&zones))[1..], [] as [&str; 0]);
zones.push(
Some(sq(7.0, 0.0, 1.0)),
vec![Value::Text("2.0000000000000000001e0".into()), Value::Text("9007199254740993.0".into()), Value::Text("maybe".into())],
);
assert_eq!(said(&run(&zones))[1..], lossy);
}

#[test]
fn converted_keeps_fitting_values_and_converts_the_rest() {
let third = 1.0 / 3.0;
Expand Down Expand Up @@ -14570,6 +14669,12 @@ mod tests {
}
assert_eq!(converted(&Value::Bool(true), FieldType::Double), Value::Float(1.0));
assert_eq!(converted(&Value::Int(5), FieldType::Text), Value::Text("5".into()));
// A whole number is yes when it isn't 0; a fraction or a word that isn't yes or no is neither.
assert_eq!(converted(&Value::Int(2), FieldType::Boolean), Value::Bool(true));
assert_eq!(converted(&Value::Float(0.0), FieldType::Boolean), Value::Bool(false));
assert_eq!(converted(&Value::Float(0.5), FieldType::Boolean), Value::Null);
assert_eq!(converted(&Value::Float(1e-7), FieldType::Boolean), Value::Null, "not the 0 it shows as");
assert_eq!(converted(&Value::Text("maybe".into()), FieldType::Boolean), Value::Null);
assert_eq!(converted(&Value::Text("x".into()), FieldType::Double), Value::Null);
assert_eq!(converted(&Value::Null, FieldType::Text), Value::Null);
// A date-time into a date field is its day; a date into a date-time field, its midnight.
Expand Down
29 changes: 28 additions & 1 deletion crates/data/src/io.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3391,7 +3391,7 @@ impl TextColumn {
/// `0.10000000000000001` (0.1 to 17 digits) and `0.00000000023283064365386962890625` (2^-32
/// exactly) are; `12345678901234567891` and `0.12345678901234567891` aren't. No Double's exact
/// value has more than 767 significant digits, so longer text isn't one, and isn't formatted.
fn double_holds(v: &str) -> bool {
pub fn double_holds(v: &str) -> bool {
/// The digits of a number's mantissa without leading or trailing zeros.
fn digits(s: &str) -> String {
let mantissa = s.split(['e', 'E']).next().unwrap_or_default();
Expand Down Expand Up @@ -4911,6 +4911,33 @@ pub fn text_in_dates<'a>(features: impl IntoIterator<Item = &'a crate::Feature>,
counts
}

/// For each field, how many values a GeoPackage export writes empty in a yes/no field, as they
/// aren't yes or no ([`Value::as_yes_no`]): `0.5`, `maybe`, a date. Null and empty text aren't counted.
pub fn unheld_yes_no(ds: &Dataset) -> Vec<usize> {
let mut counts = vec![0usize; ds.fields.len()];
for f in &ds.features {
for ((n, field), v) in counts.iter_mut().zip(&ds.fields).zip(&f.attrs) {
*n += usize::from(field.ty == FieldType::Boolean && !v.asks_null() && v.as_yes_no().is_none());
}
}
counts
}

/// What a GeoPackage export to `target` says of the values it wrote empty in yes/no fields
/// ([`unheld_yes_no`]). `None` when there was none.
pub fn unheld_yes_no_note(fields: &[Field], counts: &[usize], target: &str) -> Option<crate::loss::Note> {
let total: usize = counts.iter().sum();
if total == 0 {
return None;
}
let target: String = target.chars().map(dbf_notice_char).collect();
let what = if total == 1 { "1 value isn't yes or no and was".to_string() } else { format!("{total} values aren't yes or no and were") };
Some(crate::loss::Note::loss(
crate::loss::LossCode::DroppedValue,
format!("{target}: {what} written empty, in {}", named_fields(fields, counts)),
))
}

/// What a GeoPackage export to `target` says of the text it wrote in date fields
/// ([`text_in_dates`]). `None` when there was none.
pub fn text_in_dates_note(fields: &[Field], counts: &[usize], target: &str) -> Option<crate::loss::Note> {
Expand Down
4 changes: 4 additions & 0 deletions crates/data/src/source/gpkg.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1429,6 +1429,9 @@ fn sql_value(v: &Value, ty: FieldType) -> rusqlite::types::Value {
use rusqlite::types::Value as Sql;
match (v, ty) {
(Value::Null, _) => Sql::Null,
// A yes/no field holds a yes/no value, read as a yes/no field reads one; other values are
// null, as `io::unheld_yes_no` counts them.
(v, FieldType::Boolean) => v.as_yes_no().map_or(Sql::Null, |b| Sql::Integer(i64::from(b))),
(Value::Int(x), _) => Sql::Integer(*x),
(Value::Float(x), _) if x.is_finite() => Sql::Real(*x),
(Value::Float(_), _) => Sql::Null,
Expand Down Expand Up @@ -1509,6 +1512,7 @@ fn value(v: ValueRef<'_>, ty: FieldType, unread: &mut Vec<usize>, rounded: Optio
(ValueRef::Real(f), FieldType::Integer) if f.fract() == 0.0 && f.abs() < 9e15 => Value::Int(f as i64),
(ValueRef::Real(f), _) => Value::Float(f),
(ValueRef::Text(t), FieldType::Text) => Value::Text(String::from_utf8_lossy(t).into_owned()),
(ValueRef::Text(t), FieldType::Boolean) => super::yes_no_text(&String::from_utf8_lossy(t), unread, k),
Comment thread
Mavrick-F marked this conversation as resolved.
Resolved
(ValueRef::Text(t), ty) => Value::parse_source(&String::from_utf8_lossy(t), ty),
(ValueRef::Blob(_), _) => Value::Null,
}
Expand Down
1 change: 1 addition & 0 deletions crates/data/src/source/gpkg_mem.rs
Original file line number Diff line number Diff line change
Expand Up @@ -326,6 +326,7 @@ fn value(v: &Val, ty: FieldType, unread: &mut Vec<usize>, rounded: &mut Vec<usiz
(Val::Real(f), FieldType::Integer) if f.fract() == 0.0 && f.abs() < 9e15 => Value::Int(*f as i64),
(Val::Real(f), _) => Value::Float(*f),
(Val::Text(t), FieldType::Text) => Value::Text(t.clone()),
(Val::Text(t), FieldType::Boolean) => super::yes_no_text(t, unread, k),
(Val::Text(t), ty) => Value::parse_source(t, ty),
}
}
Expand Down
26 changes: 23 additions & 3 deletions crates/data/src/source/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -257,8 +257,9 @@ pub struct Batch {
pub complete: bool,
/// Rows that couldn't be read.
pub skipped: usize,
/// Values in date fields that weren't dates and are read as null, counted for each field by
/// its position; empty when there were none. Said by [`unread_dates_note`].
/// Values in date fields that weren't dates, and text in yes/no fields that was neither yes nor
/// no ([`yes_no_text`]), read as null, counted for each field by its position; empty when there
/// were none. Said by [`unread_dates_note`].
pub unread_dates: Vec<usize>,
/// Date-times of date fields that had digits past the microsecond, rounded to it, counted for
/// each field by its position. Said by [`rounded_dates_note`].
Expand All @@ -281,6 +282,17 @@ pub(crate) fn unread_date(counts: &mut Vec<usize>, k: usize) {
unread_dates_by(counts, k, 1);
}

/// The value of the yes/no field at `k` from a file's text ([`crate::Value::yes_no`]): text that
/// is neither yes nor no is null, counted in `counts` ([`Batch::unread_dates`]), which says it as a
/// value that isn't yes or no ([`unread_dates_note`]). Empty text and `<Null>` are null, uncounted.
pub(crate) fn yes_no_text(text: &str, counts: &mut Vec<usize>, k: usize) -> crate::Value {
let v = crate::Value::parse(text, crate::FieldType::Boolean);
if v.is_null() && !text.trim().is_empty() && !crate::Value::is_null_marker(text) {
unread_date(counts, k);
}
v
}

/// Counts one more text value `<Null>` read as null in the field at `k` ([`Batch::null_text`]).
pub(crate) fn null_text_at(counts: &mut Vec<usize>, k: usize) {
unread_dates_by(counts, k, 1);
Expand Down Expand Up @@ -332,7 +344,15 @@ pub fn unread_dates_note(fields: &[crate::Field], counts: &[usize]) -> Option<cr
if total == 0 {
return None;
}
let what = if total == 1 { "1 value isn't a date and was".to_string() } else { format!("{total} values aren't dates and were") };
// Yes/no fields count text that isn't yes or no here too ([`yes_no_text`]).
let counted = |boolean: bool| fields.iter().zip(counts).any(|(f, n)| *n > 0 && (f.ty == crate::FieldType::Boolean) == boolean);
let what = match (counted(false), counted(true), total == 1) {
(false, true, true) => "1 value isn't yes or no and was".to_string(),
(false, true, false) => format!("{total} values aren't yes or no and were"),
(true, true, _) => format!("{total} values aren't dates or yes/no values and were"),
(_, _, true) => "1 value isn't a date and was".to_string(),
_ => format!("{total} values aren't dates and were"),
};
let text = format!("{what} read as empty, in {}", crate::io::named_fields(fields, counts));
Some(crate::loss::Note::loss(crate::loss::LossCode::DroppedValue, text))
}
Expand Down
Loading
Loading