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
42 changes: 40 additions & 2 deletions crates/analysis/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -173,8 +173,9 @@ pub struct ToolResult {

/// Access to the map's layers by name.
pub trait Inputs {
/// A vector layer or table by name, in longitude/latitude: the space every tool reads its
/// inputs in and writes its outputs in.
/// A vector layer or table by name, in the system the tool works in: longitude/latitude, or
/// for a tool that works in its first input's own system ([`ToolSpec::works_in_own_system`]),
/// that system when it is a projected one. Its outputs are made in the same system.
fn dataset(&self, layer: &str) -> Option<&Dataset>;
/// A standalone table by its id: an input given as a number, which no name is taken for.
fn table(&self, _id: u32) -> Option<&Dataset> {
Expand Down Expand Up @@ -229,6 +230,43 @@ pub struct ToolSpec {
pub run: fn(&dyn Inputs, &Value) -> Result<ToolResult, String>,
}

/// The built-in tools that work in their first input's own coordinate system when it is a
/// projected one, rather than in longitude/latitude ([`ToolSpec::works_in_own_system`]): those
/// whose results don't depend on the system's units or shape beyond what the input's own
/// coordinates give (attributes, vertices, envelopes, validity).
const OWN_SYSTEM_TOOLS: &[&str] = &[
"summaryStatistics",
"pivotTable",
"joinField",
"selectByAttributes",
"exportFeatures",
"polygonToLine",
"splitLineAtVertices",
"featureEnvelopeToPolygon",
"unsplitLine",
"featureVerticesToPoints",
"merge",
"checkGeometry",
"repairGeometry",
];

impl ToolSpec {
/// Whether the tool works in its first input's own coordinate system when that is a projected
/// one: its inputs are given to it in that system ([`Inputs::dataset`]), the others converted
/// into it, and its outputs are held there. Every other tool, and every external one, works in
/// longitude/latitude.
pub fn works_in_own_system(&self) -> bool {
OWN_SYSTEM_TOOLS.contains(&self.id) && TOOLS.iter().any(|t| std::ptr::eq(t, self))
}

/// Whether the tool reads the geometry of the layer its parameter `param` names, rather than
/// only its attributes (Join Field's join table): one whose geometry it doesn't read needn't
/// be converted into the system it works in.
pub fn reads_geometry_of(&self, param: &str) -> 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.

Quality, low: reads_geometry_of hard-codes the tool id and parameter name ("joinField" / "joinTable") inside a generic ToolSpec method. Behaviour is correct today, but the next tool with an attribute-only input would need another special case here and in engine/src/cmd/gp.rs. A per-parameter flag on the parameter spec would keep that knowledge in the tool table.

Confidence: high that it works; this is a maintainability point only.

!(self.id == "joinField" && param == "joinTable")
}
}

/// Runs an external tool (the spec says which).
pub type ExternalRunner = fn(&ToolSpec, &dyn Inputs, &Value) -> Result<ToolResult, String>;

Expand Down
4 changes: 2 additions & 2 deletions crates/analysis/src/repair.rs
Original file line number Diff line number Diff line change
Expand Up @@ -107,8 +107,8 @@ pub(crate) struct Repaired {
/// direction, where they would have no area ([`narrower_than`]); written as `no_area` after
/// the codes.
pub narrow: usize,
/// When the overlay rebuilt it, how far its coordinates may have moved, in their units (degrees,
/// as coordinates are stored).
/// When the overlay rebuilt it, how far its coordinates may have moved, in their units (degrees
/// for a layer in longitude/latitude, a projected system's own units for one held in it).
pub moved: Option<f64>,
/// Under [`Rule::EvenOdd`], rings dropped as duplicates before the rings were combined, since a
/// pair would cancel out: a hole repeated in its part, and every ring of a part repeated whole
Expand Down
8 changes: 6 additions & 2 deletions crates/analysis/src/tools.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ pub static TOOLS: &[ToolSpec] = &[
id: "featureEnvelopeToPolygon",
name: "Feature Envelope To Polygon",
toolbox: "Data Management › Features",
summary: "Writes one axis-aligned bounding rectangle per feature in stored longitude/latitude coordinates. Zero-area envelopes are skipped.",
summary: "Writes one axis-aligned bounding rectangle per feature in the layer's own coordinates when it is held in a projected system other than Web Mercator, else in longitude/latitude. Zero-area envelopes are skipped.",
params: &[
P { name: "input", label: "Input Features", kind: K::Layer, required: true, default: "", help: "" },
P { name: "output", label: "Output Name", kind: K::Text, required: false, default: "", help: "" },
Expand Down Expand Up @@ -6715,6 +6715,9 @@ fn export_features(inp: &dyn Inputs, p: &Json) -> Result<ToolResult, String> {
rs.retain(|r| rustgis_data::query::eval(&e, ds, *r));
}
let mut out = copy_schema(ds, out_name(p, format!("{}_Export", ds.name)), ds.geometry_type);
// Its features as they are: in the input's system, which exports use by default, with what it

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.

Comment is slightly inaccurate: the output's features are held in the system the run worked in (held_in, set by hold_results), which may differ from the input's crs (the export default). Suggest: "Its features as they are, held in the system the run worked in, with the input's crs (the system exports use by default) and what it lost on reading."

Confidence: high; wording only.

// lost on reading.
(out.crs, out.crs_incomplete, out.zm_dropped) = (ds.crs, ds.crs_incomplete, ds.zm_dropped);
for r in rs {
if let Some(f) = ds.features.get(r) {
out.push(f.geometry.clone(), f.attrs.clone());
Expand Down Expand Up @@ -8165,7 +8168,8 @@ fn split_line_at_vertices(inp: &dyn Inputs, p: &Json) -> Result<ToolResult, Stri
geometry::split(inp, p)
}

/// Encloses each feature independently in longitude/latitude axes.
/// Encloses each feature independently in its layer's own axes (longitude/latitude for a layer
/// not in a projected system).
fn feature_envelope_to_polygon(inp: &dyn Inputs, p: &Json) -> Result<ToolResult, String> {
geometry::convert(inp, p, geometry::Conversion::FeatureEnvelopeToPolygon)
}
Expand Down
21 changes: 15 additions & 6 deletions crates/analysis/src/tools/repair_geometry.rs
Original file line number Diff line number Diff line change
Expand Up @@ -232,7 +232,10 @@ fn run_with_room(
}
out.features = list.into();

let mut messages = notices(&tally, &field, rule);
// The units its coordinates are in, which the overlay's rounding moves them by.
let crs = ds.coord_crs();
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 {
Expand All @@ -251,7 +254,7 @@ fn run_with_room(
/// and per kind of change beyond the codes: pieces dropped (with too few points or no area, or
/// narrower than a step of the overlay's grid in any direction), holes taken out, parts merged or
/// split, coordinates moved. `field` is the output's repairs field.
fn notices(t: &Tally, field: &str, rule: Rule) -> Vec<String> {
fn notices(t: &Tally, field: &str, rule: Rule, units: &str) -> Vec<String> {
let mut messages = vec![summary(t)];
let is = |n: usize| if n == 1 { "is" } else { "are" };
let was = |n: usize| if n == 1 { "was" } else { "were" };
Expand Down Expand Up @@ -343,7 +346,7 @@ fn notices(t: &Tally, field: &str, rule: Rule) -> Vec<String> {
}
if t.overlaid > 0 {
messages.push(format!(
"{TOOL}: {} {} rebuilt by geo's boolean overlay, which rounds coordinates to a fine grid: they may have moved by up to {} degrees of longitude or latitude, and vertices in the middle of straight edges were left out",
"{TOOL}: {} {} rebuilt by geo's boolean overlay, which rounds coordinates to a fine grid: they may have moved by up to {} {units}, and vertices in the middle of straight edges were left out",
features(t.overlaid),
was(t.overlaid),
rounded_up(t.moved)
Expand Down Expand Up @@ -399,6 +402,8 @@ fn summary(t: &Tally) -> String {
#[cfg(test)]
mod tests {
use super::*;
/// The units a layer in longitude/latitude has its coordinates in.
const DEGREES: &str = "degrees of longitude or latitude";

/// The inputs: one layer, with nothing selected.
struct One(Dataset);
Expand Down Expand Up @@ -456,22 +461,26 @@ mod tests {
fn features_left_as_they_were_are_counted_by_reason() {
let t = Tally { processed: 9, failed: 1, ..Tally::default() };
assert_eq!(
notices(&t, "repairs", Rule::default()),
notices(&t, "repairs", Rule::default(), DEGREES),
[
"Repair Geometry: repaired 0 of 9 features",
"Repair Geometry: 1 feature couldn't be repaired, because geo's geometry operations failed on it, and is written unchanged, with repair_failed in repairs",
]
);
let t = Tally { processed: 9, work: 2, memory: 3, failed: 2, ..Tally::default() };
assert_eq!(
notices(&t, "repairs_2", Rule::default())[1..],
notices(&t, "repairs_2", Rule::default(), DEGREES)[1..],
[
"Repair Geometry: 2 features were too complex to repair within the work limit and are written unchanged, with too_complex in repairs_2",
"Repair Geometry: 3 features couldn't be repaired, because there wasn't enough memory to repair them, and are written unchanged, with too_complex in repairs_2",
"Repair Geometry: 2 features couldn't be repaired, because geo's geometry operations failed on them, and are written unchanged, with repair_failed in repairs_2",
]
);
assert_eq!(notices(&Tally::default(), "repairs", Rule::default()), ["Repair Geometry: no features to repair"]);
assert_eq!(notices(&Tally::default(), "repairs", Rule::default(), DEGREES), ["Repair Geometry: no features to repair"]);
// A layer held in a projected system is told its bound in that system's units.
let rebuilt = Tally { overlaid: 1, moved: 0.01, ..Tally::default() };
let said = notices(&rebuilt, "repairs", Rule::default(), "units of EPSG:32632").join("\n");
assert!(said.contains("may have moved by up to 1.0e-2 units of EPSG:32632, and vertices"), "{said}");
}

/// A cancel stops the repairs at the next feature, and the copies at the next row.
Expand Down
22 changes: 21 additions & 1 deletion crates/data/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1075,7 +1075,7 @@ impl Dataset {
}
}

/// The dataset in longitude/latitude, the space analysis tools work in: borrowed while its
/// The dataset in longitude/latitude, the space most analysis tools work in: borrowed while its
/// coordinates are longitude/latitude ([`Dataset::coord_crs`]); otherwise a copy with every
/// geometry converted, missing coordinates kept. Refused, naming the first feature that can't
/// be, when one of its places can't be converted. The copy is held in longitude/latitude
Expand Down Expand Up @@ -1104,6 +1104,26 @@ impl Dataset {
Ok(Cow::Owned(out))
}

/// The dataset in `crs`, the system a tool works in when it works in its first input's own
/// ([`Dataset::in_lonlat`] for longitude/latitude): borrowed while its coordinates are already
/// there; otherwise a copy held there ([`Dataset::hold_in`]), missing coordinates kept.
/// Refused as [`Dataset::hold_in`] refuses, naming the first feature with a place `crs` can't
/// hold.
pub fn in_crs(&self, crs: raster::Crs) -> std::result::Result<Cow<'_, Dataset>, String> {
if crs == raster::Crs::LonLat {
return self.in_lonlat();
}
if self.coord_crs().to(crs)?.is_identity() {
return Ok(Cow::Borrowed(self));
}
let mut out = self.clone();
// A copy for one run, not the layer: a window's rows are converted as they are.
let windowed = std::mem::take(&mut out.windowed);
out.hold_in(crs)?;
out.windowed = windowed;
Ok(Cow::Owned(out))
}

/// A longitude/latitude box in its own coordinates ([`Dataset::coord_crs`]), as
/// [`raster::Reprojection::extent`] converts it: for asking which features a box reaches, once
/// for the box rather than once a feature. The box itself while they are
Expand Down
13 changes: 12 additions & 1 deletion crates/data/src/raster/crs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -330,7 +330,9 @@ impl TryFrom<SavedCrs> for Crs {
Ok(match s {
SavedCrs::LonLat => Crs::LonLat,
SavedCrs::WebMercator => Crs::WebMercator,
SavedCrs::Epsg(e) => Crs::Epsg(e),
// A code another variant stands for (4326, 3857 and its aliases), as a file written
// by hand or by another program may give it, is that variant, as `from_epsg` gives it.
SavedCrs::Epsg(e) => Crs::from_epsg(u32::from(e)).unwrap_or(Crs::Epsg(e)),

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.

AGENTS.md: this changes how a project is read, but no fixture was added.

SavedCrs::Epsg now reads 4326 as LonLat and 3857/3785 as WebMercator, so a saved project's {"Epsg": …} reads differently from before. AGENTS.md (docs/maintaining.md, "saved files and settings") says a pull request that changes how a project is read adds or updates a fixture project in schema/fixtures/, which must open and validate against the schema. The new unit test in this file covers the mapping, but it doesn't cover the file-reading rule.

Suggested fix: add a small fixture under schema/fixtures/ whose layers use {"Epsg": 3857} and {"Epsg": 4326}, and check that it opens and validates. Alternatively, say in the PR why no fixture is needed.

Confidence: medium. I did not check whether the schema fixture tests exercise every Crs read path.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in 6e7414b. New fixture schema/fixtures/held_epsg_variants.rgis has one layer held in {"Epsg": 3857} (with crs {"Epsg": 4326}) and one held in {"Epsg": 4326} (with crs {"Epsg": 3857}). It validates against the schema (the schema check), and the_epsg_variants_fixture_opens_as_rustgis_own_systems opens it: Web Mercator and lon/lat as RustGIS's own variants, with the point checked against PROJ 9.9.0 (1280174.144123 6224110.131660).

SavedCrs::Proj { proj4, label, wkt } => Crs::custom(CustomCrs { proj4, label, wkt, ..CustomCrs::default() })?,
})
}
Expand Down Expand Up @@ -2462,6 +2464,15 @@ impl Transformer {
mod tests {
use super::*;

/// A saved code another variant stands for reads as that variant, so Web Mercator saved as
/// `{"Epsg": 3857}` isn't taken for a projected system of its own.
#[test]
fn a_saved_code_another_variant_stands_for_reads_as_it() {
for (code, crs) in [(3857, Crs::WebMercator), (3785, Crs::WebMercator), (4326, Crs::LonLat), (32632, Crs::Epsg(32632))] {
assert_eq!(Crs::try_from(SavedCrs::Epsg(code)), Ok(crs), "EPSG:{code}");
}
}

/// An ESRI code reads as the system the picker offers for it (`ESRI:102033`, as a `.prj` and
/// the coordinate system boxes name it); one the catalog lacks is refused with its name.
#[test]
Expand Down
Loading
Loading