Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions crates/analysis/src/rasterops.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1631,6 +1631,12 @@ pub fn transform_polygon_to_lonlat(rings: &[Vec<Coord>], tr: Option<&Transformer
Ok(out_rings)
}

/// Whether a (multi-)polygon has a part whose exterior ring has three points or more: one without
/// has no area, so nothing is lost when it can't be read.
pub fn has_a_ring(polys: &[Vec<Vec<Coord>>]) -> bool {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: the name has_a_ring says less than the check does. It returns true only when some part's exterior ring has at least three points, which is the test for "this polygon can have area". The name reads as "has any ring", and callers in Zonal Statistics and Tabulate Area depend on the narrower meaning. Something like has_an_exterior_of_three_points or can_have_area would say what it checks.

Category: quality

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Left for the release quality pass: a naming and tidying point, with no change in behaviour.

polys.iter().any(|part| part.first().is_some_and(|ring| ring.len() >= 3))
}

/// The polygon parts of a (multi-)polygon feature, checked and taken apart into rings, in the
/// system they are in: [`transform_feature_polygons_to_lonlat`] with no transformer. It doesn't
/// look at Cancel: a caller looping over features does, between them.
Expand Down
259 changes: 189 additions & 70 deletions crates/analysis/src/tools.rs

Large diffs are not rendered by default.

44 changes: 26 additions & 18 deletions crates/analysis/src/tools/check_geometry.rs
Original file line number Diff line number Diff line change
Expand Up @@ -154,9 +154,9 @@ fn run_with_room(
}
out.features = list.into();

let mut messages = notices(&tally, &problem_field);
let (mut messages, losses) = notices(&tally, &problem_field);
messages.extend(notes);
Ok(ToolResult { losses: Vec::new(), output: Output::Layer(out), messages })
Ok(ToolResult { losses, output: Output::Layer(out), messages })
}

/// The memory an output row copying `attrs` (`width` of them, of `out_width` values in the
Expand All @@ -183,17 +183,22 @@ pub(super) fn row_bytes(attrs: &[Value], width: usize, out_width: usize, texts:
}

/// The run's notices: the result in one line, then one notice per kind of feature not checked
/// fully or not copied whole. `problem` is the output's problem field.
fn notices(t: &Tally, problem: &str) -> Vec<String> {
/// fully or not copied whole, and the losses among them. `problem` is the output's problem field.
fn notices(t: &Tally, problem: &str) -> (Vec<String>, Vec<rustgis_data::loss::LossMessage>) {
use rustgis_data::loss::{LossCode, LossMessage};
let mut messages = vec![summary(t.found, t.checked, &t.counts)];
let mut losses = Vec::new();
let they = |n: usize| if n == 1 { "it is" } else { "they are" };
let non_finite = Code::ALL.iter().position(|c| *c == Code::NonFiniteCoordinate).and_then(|k| t.counts.get(k)).copied().unwrap_or(0);
if non_finite > 0 {
messages.push(format!(
"{TOOL}: {} with non-finite coordinates {} written without geometry",
features(non_finite),
if non_finite == 1 { "is" } else { "are" }
));
losses.push(LossMessage {
code: LossCode::DroppedGeometry,
text: format!(
"{TOOL}: {} with non-finite coordinates {} written without geometry",
features(non_finite),
if non_finite == 1 { "is" } else { "are" }
),
});
}
if t.work_limit > 0 {
messages.push(format!(
Expand Down Expand Up @@ -224,12 +229,15 @@ fn notices(t: &Tally, problem: &str) -> Vec<String> {
));
}
if t.extra > 0 {
messages.push(format!(
"{TOOL}: {} had more attribute values than the layer has fields; the extra values aren't in the output",
features(t.extra)
));
losses.push(LossMessage {
code: LossCode::DroppedExtraAttributes,
text: format!(
"{TOOL}: {} had more attribute values than the layer has fields; the extra values aren't in the output",
features(t.extra)
),
});
}
messages
(messages, losses)
}

/// "1 feature", "2 features".
Expand Down Expand Up @@ -308,14 +316,14 @@ mod tests {
#[test]
fn features_not_checked_fully_are_counted_by_reason() {
assert_eq!(
notices(&too_complex(0, 1, 0), "problem"),
notices(&too_complex(0, 1, 0), "problem").0,
[
"Check Geometry: 1 of 9 features has problems (too_complex: 1)",
"Check Geometry: some rings or parts of 1 feature could not be checked against each other, because geo's relate operation failed on them; it is in the output as too_complex",
]
);
assert_eq!(
notices(&too_complex(2, 3, 1), "problem"),
notices(&too_complex(2, 3, 1), "problem").0,
[
"Check Geometry: 4 of 9 features have problems (too_complex: 4)",
"Check Geometry: 2 features could not be checked fully (too complex for the work limit); they are in the output as too_complex",
Expand All @@ -326,7 +334,7 @@ mod tests {
for n in [1, 2] {
memory.memory = n;
assert_eq!(
notices(&memory, "problem").get(1).map(String::as_str),
notices(&memory, "problem").0.get(1).map(String::as_str),
Some(if n == 1 {
"Check Geometry: 1 feature could not be checked fully, because there wasn't enough memory to check it; it is in the output as too_complex"
} else {
Expand All @@ -336,7 +344,7 @@ mod tests {
}
let t = Tally { checked: 2, found: 2, unrelated: 2, ..Tally::default() };
assert_eq!(
notices(&t, "problem_2").last().map(String::as_str),
notices(&t, "problem_2").0.last().map(String::as_str),
Some(
"Check Geometry: the rings or parts of 2 features weren't all checked against each other, because some of their rings or parts already have problems of their own (see problem_2)"
)
Expand Down
54 changes: 36 additions & 18 deletions crates/analysis/src/tools/repair_geometry.rs
Original file line number Diff line number Diff line change
Expand Up @@ -237,17 +237,44 @@ fn run_with_room(
let units = if crs.is_geographic() { "degrees of longitude or latitude".to_string() } else { format!("units of {}", crs.label()) };
let mut messages = notices(&tally, &field, rule, &units);
messages.extend(notes);
let losses = (tally.extra > 0)
.then(|| rustgis_data::loss::LossMessage {
code: rustgis_data::loss::LossCode::DroppedExtraAttributes,
let losses = losses(&tally);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: let losses = losses(&tally); works because the call runs before the binding, but it reads as a self-reference. Renaming the helper (for example loss_messages) would make the call site clear.

Category: quality

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Left for the release quality pass: a naming and tidying point, with no change in behaviour.

Ok(ToolResult { output: Output::Layer(out), messages, losses })
}

/// The notice for features that couldn't be repaired and are written without geometry, of the
/// kinds `lost` picks, with the count of each: `None` when there are none.
fn without_geometry(t: &Tally, lost: bool) -> Option<String> {
let kinds = Gone::ALL.iter().zip(t.gone).filter(|(g, n)| *n > 0 && (**g != Gone::Null) == lost);
let gone: usize = kinds.clone().map(|(_, n)| n).sum();
let by: Vec<String> = kinds.map(|(g, n)| format!("{}: {n}", g.as_str())).collect();
(gone > 0).then(|| {
format!(
"{TOOL}: {} couldn't be repaired and {} written without geometry ({})",
features(gone),
if gone == 1 { "is" } else { "are" },
by.join(", ")
)
})
}

/// The run's losses: features whose geometry is left out, and attribute values past the layer's
/// fields. A feature without geometry to begin with loses none.
fn losses(t: &Tally) -> Vec<rustgis_data::loss::LossMessage> {
use rustgis_data::loss::{LossCode, LossMessage};
let mut losses = Vec::new();
if let Some(text) = without_geometry(t, true) {
losses.push(LossMessage { code: LossCode::DroppedGeometry, text });
}
if t.extra > 0 {
losses.push(LossMessage {
code: LossCode::DroppedExtraAttributes,
text: format!(
"{TOOL}: {} had more attribute values than the layer has fields; the extra values aren't in the output",
features(tally.extra)
features(t.extra)
),
})
.into_iter()
.collect();
Ok(ToolResult { output: Output::Layer(out), messages, losses })
});
}
losses
}

/// The run's notices: the result in one line, then one notice per kind of feature not repaired,
Expand All @@ -256,18 +283,9 @@ fn run_with_room(
/// split, coordinates moved. `field` is the output's repairs field.
fn notices(t: &Tally, field: &str, rule: Rule, units: &str) -> Vec<String> {
let mut messages = vec![summary(t)];
messages.extend(without_geometry(t, false));
let is = |n: usize| if n == 1 { "is" } else { "are" };
let was = |n: usize| if n == 1 { "was" } else { "were" };
let gone: usize = t.gone.iter().sum();
if gone > 0 {
let by: Vec<String> = Gone::ALL.iter().zip(t.gone).filter(|(_, n)| *n > 0).map(|(g, n)| format!("{}: {n}", g.as_str())).collect();
messages.push(format!(
"{TOOL}: {} couldn't be repaired and {} written without geometry ({})",
features(gone),
is(gone),
by.join(", ")
));
}
if t.work > 0 {
messages.push(format!(
"{TOOL}: {} {} too complex to repair within the work limit and {} written unchanged, with too_complex in {field}",
Expand Down
33 changes: 25 additions & 8 deletions crates/analysis/src/tools/tabulate_area.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
//! Class-by-zone tables on the same cell-centre masks as Zonal Statistics.
use super::*;
use rustgis_data::loss::{LossCode, LossMessage};
use rustgis_data::{Measure, raster::Raster};

/// Counts or measures every class in each zone. One zone's mask is built as one step without
Expand Down Expand Up @@ -88,11 +89,12 @@ pub(super) fn run_on(inp: &dyn Inputs, p: &Json, threads: Option<usize>) -> Resu
let name = unique_field(&out, &format!("class_{class}"));
out.fields.push(Field::new(name, if count { FieldType::Integer } else { FieldType::Double }));
}
let (mut nodata, mut invalid, mut parts, mut empty) = (0u64, 0usize, 0usize, 0usize);
let (mut nodata, mut invalid, mut unreadable, mut parts, mut empty) = (0u64, 0usize, 0usize, 0usize, 0usize);
for (group, total) in groups.into_iter().zip(totals) {
crate::control::check()?;
nodata += total.nodata;
invalid += total.invalid;
unreadable += total.unreadable;
parts += total.parts;
empty += usize::from(total.values.iter().all(|v| *v == 0.0));
let mut attrs = group.key;
Expand All @@ -111,15 +113,25 @@ pub(super) fn run_on(inp: &dyn Inputs, p: &Json, threads: Option<usize>) -> Resu
messages.push(format!("{nodata} NoData or non-finite cell(s) inside zones were excluded (counted once per zone)"));
}
if invalid > 0 {
messages.push(format!("{invalid} zone feature(s) had missing or invalid polygon geometry and were excluded"));
messages.push(format!("{invalid} zone feature(s) had no polygon with an area and were excluded"));
}
let mut losses = Vec::new();
if unreadable > 0 {
losses.push(LossMessage {
code: LossCode::DroppedGeometry,
text: format!("{unreadable} zone feature(s) had invalid polygon geometry and were excluded"),
});
}
if parts > 0 {
messages.push(format!("{parts} polygon part(s) could not be projected onto the raster grid; valid parts were retained"));
losses.push(LossMessage {
code: LossCode::DroppedGeometry,
text: format!("{parts} polygon part(s) could not be projected onto the raster grid; valid parts were retained"),
});
}
if empty > 0 {
messages.push(format!("{empty} zone(s) contained no valid raster cell centres; their class values are zero"));
}
Ok(ToolResult { losses: Vec::new(), output: Output::Table(out), messages })
Ok(ToolResult { losses, output: Output::Table(out), messages })
}

/// All finite valid band values, sorted numerically. The wide table has Pivot Table's column
Expand Down Expand Up @@ -158,6 +170,8 @@ struct Totals {
values: Vec<f64>,
nodata: u64,
invalid: usize,
/// Zone features whose polygon couldn't be read.
unreadable: usize,
parts: usize,
}

Expand All @@ -172,7 +186,7 @@ fn summarize(
classes: &HashMap<u32, usize>,
areas: &CellAreas<'_>,
) -> Result<Totals, String> {
let mut total = Totals { values: vec![0.0; classes.len()], nodata: 0, invalid: 0, parts: 0 };
let mut total = Totals { values: vec![0.0; classes.len()], nodata: 0, invalid: 0, unreadable: 0, parts: 0 };
let mut polygons = Vec::new();
for &row in rows {
crate::control::check()?;
Expand All @@ -181,9 +195,12 @@ fn summarize(
Some(Geometry::Polygon(p)) => crate::rasterops::validated_polygon_parts(p).ok(),
_ => None,
};
match valid {
Some(p) => polygons.extend(p),
None => total.invalid += 1,
// A polygon that can't be read is lost to its zone; a feature with no polygon, or none
// with an area, has no area to lose.
match (valid, shape) {
(Some(p), _) => polygons.extend(p),
(None, Some(Geometry::Polygon(p))) if crate::rasterops::has_a_ring(p) => total.unreadable += 1,
(None, _) => total.invalid += 1,
}
}
let mut failures = Vec::new();
Expand Down
17 changes: 11 additions & 6 deletions crates/analysis/tests/integration/check_geometry.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,11 @@ impl Inputs for Layer {

type Ring<'a> = &'a [(f64, f64)];

/// What a run says: its messages, then its losses, each after its code.
fn said(r: &ToolResult) -> Vec<String> {
r.messages.iter().cloned().chain(r.losses.iter().map(|l| format!("{:?}: {}", l.code, l.text))).collect()
}

fn layer(ty: GeometryType) -> Layer {
Layer { ds: Dataset::new("input", ty, vec![Field::new("name", FieldType::Text)]), selected: vec![] }
}
Expand Down Expand Up @@ -323,10 +328,10 @@ fn non_finite_coordinates_are_written_without_geometry() {
assert!(ds.extent().is_empty(), "nothing to spoil the extent");
assert_eq!(text(ds, 0, "detail"), "2 non-finite coordinates, the first in exterior ring of part 1; written without geometry");
assert_eq!(
r.messages,
said(&r),
[
"Check Geometry: 1 of 1 feature has problems (non_finite_coordinate: 1)",
"Check Geometry: 1 feature with non-finite coordinates is written without geometry",
"DroppedGeometry: Check Geometry: 1 feature with non-finite coordinates is written without geometry",
]
);
// Several: plural. A bowtie in another part is still found; the parts aren't related, which
Expand All @@ -338,11 +343,11 @@ fn non_finite_coordinates_are_written_without_geometry() {
assert!(ds.features.iter().all(|f| f.geometry.is_none()));
assert_eq!(text(ds, 2, "problem"), "non_finite_coordinate, self_intersection");
assert_eq!(
r.messages,
said(&r),
[
"Check Geometry: 3 of 3 features have problems (non_finite_coordinate: 3, self_intersection: 1)",
"Check Geometry: 3 features with non-finite coordinates are written without geometry",
"Check Geometry: the rings or parts of 1 feature weren't all checked against each other, because some of their rings or parts already have problems of their own (see problem)",
"DroppedGeometry: Check Geometry: 3 features with non-finite coordinates are written without geometry",
]
);
}
Expand Down Expand Up @@ -494,8 +499,8 @@ fn extra_attribute_values_are_reported() {
let ds = dataset(&r);
assert_eq!(ds.features[0].attrs.len(), 3);
assert_eq!(
r.messages[1],
"Check Geometry: 1 feature had more attribute values than the layer has fields; the extra values aren't in the output"
said(&r)[1],
"DroppedExtraAttributes: Check Geometry: 1 feature had more attribute values than the layer has fields; the extra values aren't in the output"
);
}

Expand Down
11 changes: 9 additions & 2 deletions crates/analysis/tests/integration/repair_geometry.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,11 @@ impl Inputs for Layer {

type Ring<'a> = &'a [(f64, f64)];

/// What a run says: its messages, then its losses, each after its code.
fn said(r: &ToolResult) -> Vec<String> {
r.messages.iter().cloned().chain(r.losses.iter().map(|l| format!("{:?}: {}", l.code, l.text))).collect()
}

fn layer(ty: GeometryType) -> Layer {
Layer { ds: Dataset::new("input", ty, vec![Field::new("name", FieldType::Text)]), selected: vec![] }
}
Expand Down Expand Up @@ -446,16 +451,18 @@ fn a_mixed_layer_says_what_was_done_with_counts() {
let without: Vec<bool> = ds.features.iter().map(|f| f.geometry.is_none()).collect();
assert_eq!(without, [false, false, false, true, false, false, false, false, true, true]);
assert_eq!(
r.messages,
said(&r),
[
"Repair Geometry: repaired 6 of 10 features (too_few_points: 1, ring_not_closed: 1, self_intersection: 1, hole_outside_shell: 1, disconnected_interior: 1, parts_overlap: 1)",
"Repair Geometry: 3 features couldn't be repaired and are written without geometry (null_geometry: 1, non_finite_coordinate: 1, no_area: 1)",
// A feature without geometry to begin with loses none.
"Repair Geometry: 1 feature couldn't be repaired and is written without geometry (null_geometry: 1)",
"Repair Geometry: 1 ring or part with too few distinct points or no area was dropped from 1 feature",
"Repair Geometry: holes not inside their exterior ring were taken out of 1 feature; what of a hole is inside its exterior ring stays a hole",
"Repair Geometry: the parts that overlapped or touched along a line were merged in 1 feature",
"Repair Geometry: 1 feature whose interior was cut into pieces by rings touching at points is written with each piece as a part of its own",
// The hole outside makes the largest extent, 21 across: a grid step of 2^-26, five of them.
"Repair Geometry: 4 features were rebuilt by geo's boolean overlay, which rounds coordinates to a fine grid: they may have moved by up to 7.5e-8 degrees of longitude or latitude, and vertices in the middle of straight edges were left out",
"DroppedGeometry: Repair Geometry: 2 features couldn't be repaired and are written without geometry (non_finite_coordinate: 1, no_area: 1)",
]
);
}
Expand Down
Loading
Loading